From 0cec774a75abe6721803e6f8d3f6c5935efc3cd0 Mon Sep 17 00:00:00 2001 From: Wilmer Paulino Date: Tue, 4 Dec 2018 10:19:58 -0800 Subject: [PATCH 1/3] txscript: add support to re-derive output's PkScript from input In this commit, we extend the txscript package to support re-deriving the PkScript of an output by looking at the input's signature script/witness attempting to spend it. As of this commit, the only supported types are P2SH, v0 P2WSH, and v0 P2WPKH. This will serve useful to detect when a particular script has been spent on-chain. A set of test vectors has also been added for the supported script types to ensure its correctness. --- txscript/pkscript.go | 260 ++++++++++++++++++++++ txscript/pkscript_test.go | 440 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 700 insertions(+) create mode 100644 txscript/pkscript.go create mode 100644 txscript/pkscript_test.go diff --git a/txscript/pkscript.go b/txscript/pkscript.go new file mode 100644 index 00000000..e2823a8b --- /dev/null +++ b/txscript/pkscript.go @@ -0,0 +1,260 @@ +package txscript + +import ( + "crypto/sha256" + "errors" + "fmt" + + "github.com/btcsuite/btcd/btcec" + "github.com/btcsuite/btcd/chaincfg" + "github.com/btcsuite/btcd/wire" + "github.com/btcsuite/btcutil" + "golang.org/x/crypto/ripemd160" +) + +const ( + // pubKeyHashSigScriptLen is the length of a signature script attempting + // to spend a P2PKH script. The only other possible length value is 107 + // bytes, due to the signature within it. This length is determined by + // the following: + // 0x47 or 0x48 (71 or 72 byte data push) | <71 or 72 byte sig> | + // 0x21 (33 byte data push) | <33 byte compressed pubkey> + pubKeyHashSigScriptLen = 106 + + // compressedPubKeyLen is the length in bytes of a compressed public + // key. + compressedPubKeyLen = 33 + + // pubKeyHashLen is the length of a P2PKH script. + pubKeyHashLen = 25 + + // witnessV0PubKeyHashLen is the length of a P2WPKH script. + witnessV0PubKeyHashLen = 22 + + // scriptHashLen is the length of a P2SH script. + scriptHashLen = 23 + + // witnessV0ScriptHashLen is the length of a P2WSH script. + witnessV0ScriptHashLen = 34 + + // maxLen is the maximum script length supported by ParsePkScript. + maxLen = witnessV0ScriptHashLen +) + +var ( + // ErrUnsupportedScriptType is an error returned when we attempt to + // parse/re-compute an output script into a PkScript struct. + ErrUnsupportedScriptType = errors.New("unsupported script type") +) + +// PkScript is a wrapper struct around a byte array, allowing it to be used +// as a map index. +type PkScript struct { + // class is the type of the script encoded within the byte array. This + // is used to determine the correct length of the script within the byte + // array. + class ScriptClass + + // script is the script contained within a byte array. If the script is + // smaller than the length of the byte array, it will be padded with 0s + // at the end. + script [maxLen]byte +} + +// ParsePkScript parses an output script into the PkScript struct. +// ErrUnsupportedScriptType is returned when attempting to parse an unsupported +// script type. +func ParsePkScript(pkScript []byte) (PkScript, error) { + var outputScript PkScript + scriptClass, _, _, err := ExtractPkScriptAddrs( + pkScript, &chaincfg.MainNetParams, + ) + if err != nil { + return outputScript, fmt.Errorf("unable to parse script type: "+ + "%v", err) + } + + if !isSupportedScriptType(scriptClass) { + return outputScript, ErrUnsupportedScriptType + } + + outputScript.class = scriptClass + copy(outputScript.script[:], pkScript) + + return outputScript, nil +} + +// isSupportedScriptType determines whether the script type is supported by the +// PkScript struct. +func isSupportedScriptType(class ScriptClass) bool { + switch class { + case PubKeyHashTy, WitnessV0PubKeyHashTy, ScriptHashTy, + WitnessV0ScriptHashTy: + return true + default: + return false + } +} + +// Class returns the script type. +func (s PkScript) Class() ScriptClass { + return s.class +} + +// Script returns the script as a byte slice without any padding. +func (s PkScript) Script() []byte { + var script []byte + + switch s.class { + case PubKeyHashTy: + script = make([]byte, pubKeyHashLen) + copy(script, s.script[:pubKeyHashLen]) + + case WitnessV0PubKeyHashTy: + script = make([]byte, witnessV0PubKeyHashLen) + copy(script, s.script[:witnessV0PubKeyHashLen]) + + case ScriptHashTy: + script = make([]byte, scriptHashLen) + copy(script, s.script[:scriptHashLen]) + + case WitnessV0ScriptHashTy: + script = make([]byte, witnessV0ScriptHashLen) + copy(script, s.script[:witnessV0ScriptHashLen]) + + default: + // Unsupported script type. + return nil + } + + return script +} + +// Address encodes the script into an address for the given chain. +func (s PkScript) Address(chainParams *chaincfg.Params) (btcutil.Address, error) { + _, addrs, _, err := ExtractPkScriptAddrs(s.Script(), chainParams) + if err != nil { + return nil, fmt.Errorf("unable to parse address: %v", err) + } + + return addrs[0], nil +} + +// String returns a hex-encoded string representation of the script. +func (s PkScript) String() string { + str, _ := DisasmString(s.Script()) + return str +} + +// ComputePkScript computes the pkScript of an transaction output by looking at +// the transaction input's signature script or witness. +// +// NOTE: Only P2PKH, P2SH, P2WSH, and P2WPKH redeem scripts are supported. +func ComputePkScript(sigScript []byte, witness wire.TxWitness) (PkScript, error) { + var pkScript PkScript + + // Ensure that either an input's signature script or a witness was + // provided. + if len(sigScript) == 0 && len(witness) == 0 { + return pkScript, ErrUnsupportedScriptType + } + + // We'll start by checking the input's signature script, if provided. + switch { + // If a signature script is provided with a length long enough to + // represent a P2PKH script, then we'll attempt to parse the compressed + // public key from it. + case len(sigScript) == pubKeyHashSigScriptLen || + len(sigScript) == pubKeyHashSigScriptLen+1: + + // The public key should be found as the last part of the + // signature script. We'll attempt to parse it to ensure this is + // a P2PKH redeem script. + pubKey := sigScript[len(sigScript)-compressedPubKeyLen:] + if btcec.IsCompressedPubKey(pubKey) { + pubKeyHash := hash160(pubKey) + script, err := payToPubKeyHashScript(pubKeyHash) + if err != nil { + return pkScript, err + } + + pkScript.class = PubKeyHashTy + copy(pkScript.script[:], script) + return pkScript, nil + } + + // If it isn't, we'll assume it is a P2SH signature script. + fallthrough + + // If we failed to parse a compressed public key from the script in the + // case above, or if the script length is not that of a P2PKH one, and + // our redeem script is only composed of data pushed, we can assume it's + // a P2SH signature script. + case len(sigScript) > 0 && IsPushOnlyScript(sigScript): + // The redeem script will always be the last data push of the + // signature script, so we'll parse the script into opcodes to + // obtain it. + parsedOpcodes, err := parseScript(sigScript) + if err != nil { + return pkScript, err + } + redeemScript := parsedOpcodes[len(parsedOpcodes)-1].data + + scriptHash := hash160(redeemScript) + script, err := payToScriptHashScript(scriptHash) + if err != nil { + return pkScript, err + } + + pkScript.class = ScriptHashTy + copy(pkScript.script[:], script) + return pkScript, nil + + case len(sigScript) > 0: + return pkScript, ErrUnsupportedScriptType + } + + // If a witness was provided instead, we'll use the last item of the + // witness stack to determine the proper witness type. + lastWitnessItem := witness[len(witness)-1] + + switch { + // If the witness stack has a size of 2 and its last item is a + // compressed public key, then this is a P2WPKH witness. + case len(witness) == 2 && len(lastWitnessItem) == compressedPubKeyLen: + pubKeyHash := hash160(lastWitnessItem) + script, err := payToWitnessPubKeyHashScript(pubKeyHash) + if err != nil { + return pkScript, err + } + + pkScript.class = WitnessV0PubKeyHashTy + copy(pkScript.script[:], script) + return pkScript, nil + + // For any other witnesses, we'll assume it's a P2WSH witness. + default: + scriptHash := sha256.Sum256(lastWitnessItem) + script, err := payToWitnessScriptHashScript(scriptHash[:]) + if err != nil { + return pkScript, err + } + + pkScript.class = WitnessV0ScriptHashTy + copy(pkScript.script[:], script) + return pkScript, nil + } +} + +// hash160 returns the RIPEMD160 hash of the SHA-256 HASH of the given data. +func hash160(data []byte) []byte { + h := sha256.Sum256(data) + return ripemd160h(h[:]) +} + +// ripemd160h returns the RIPEMD160 hash of the given data. +func ripemd160h(data []byte) []byte { + h := ripemd160.New() + h.Write(data) + return h.Sum(nil) +} diff --git a/txscript/pkscript_test.go b/txscript/pkscript_test.go new file mode 100644 index 00000000..dd892827 --- /dev/null +++ b/txscript/pkscript_test.go @@ -0,0 +1,440 @@ +package txscript + +import ( + "bytes" + "testing" + + "github.com/btcsuite/btcd/wire" +) + +// TestParsePkScript ensures that the supported script types can be parsed +// correctly and re-derived into its raw byte representation. +func TestParsePkScript(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + pkScript []byte + valid bool + }{ + { + name: "empty output script", + pkScript: []byte{}, + valid: false, + }, + { + name: "valid P2PKH", + pkScript: []byte{ + // OP_DUP + 0x76, + // OP_HASH160 + 0xa9, + // OP_DATA_20 + 0x14, + // <20-byte pubkey hash> + 0xf0, 0x7a, 0xb8, 0xce, 0x72, 0xda, 0x4e, 0x76, + 0x0b, 0x74, 0x7d, 0x48, 0xd6, 0x65, 0xec, 0x96, + 0xad, 0xf0, 0x24, 0xf5, + // OP_EQUALVERIFY + 0x88, + // OP_CHECKSIG + 0xac, + }, + valid: true, + }, + // Invalid P2PKH - same as above but replaced OP_CHECKSIG with + // OP_CHECKSIGVERIFY. + { + name: "invalid P2PKH", + pkScript: []byte{ + // OP_DUP + 0x76, + // OP_HASH160 + 0xa9, + // OP_DATA_20 + 0x14, + // <20-byte pubkey hash> + 0xf0, 0x7a, 0xb8, 0xce, 0x72, 0xda, 0x4e, 0x76, + 0x0b, 0x74, 0x7d, 0x48, 0xd6, 0x65, 0xec, 0x96, + 0xad, 0xf0, 0x24, 0xf5, + // OP_EQUALVERIFY + 0x88, + // OP_CHECKSIGVERIFY + 0xad, + }, + valid: false, + }, + { + name: "valid P2SH", + pkScript: []byte{ + // OP_HASH160 + 0xA9, + // OP_DATA_20 + 0x14, + // <20-byte script hash> + 0xec, 0x6f, 0x7a, 0x5a, 0xa8, 0xf2, 0xb1, 0x0c, + 0xa5, 0x15, 0x04, 0x52, 0x3a, 0x60, 0xd4, 0x03, + 0x06, 0xf6, 0x96, 0xcd, + // OP_EQUAL + 0x87, + }, + valid: true, + }, + // Invalid P2SH - same as above but replaced OP_EQUAL with + // OP_EQUALVERIFY. + { + name: "invalid P2SH", + pkScript: []byte{ + // OP_HASH160 + 0xA9, + // OP_DATA_20 + 0x14, + // <20-byte script hash> + 0xec, 0x6f, 0x7a, 0x5a, 0xa8, 0xf2, 0xb1, 0x0c, + 0xa5, 0x15, 0x04, 0x52, 0x3a, 0x60, 0xd4, 0x03, + 0x06, 0xf6, 0x96, 0xcd, + // OP_EQUALVERIFY + 0x88, + }, + valid: false, + }, + { + name: "valid v0 P2WSH", + pkScript: []byte{ + // OP_0 + 0x00, + // OP_DATA_32 + 0x20, + // <32-byte script hash> + 0xec, 0x6f, 0x7a, 0x5a, 0xa8, 0xf2, 0xb1, 0x0c, + 0xa5, 0x15, 0x04, 0x52, 0x3a, 0x60, 0xd4, 0x03, + 0x06, 0xf6, 0x96, 0xcd, 0x06, 0xf6, 0x96, 0xcd, + 0x06, 0xf6, 0x96, 0xcd, 0x06, 0xf6, 0x96, 0xcd, + }, + valid: true, + }, + // Invalid v0 P2WSH - same as above but missing one byte. + { + name: "invalid v0 P2WSH", + pkScript: []byte{ + // OP_0 + 0x00, + // OP_DATA_32 + 0x20, + // <32-byte script hash> + 0xec, 0x6f, 0x7a, 0x5a, 0xa8, 0xf2, 0xb1, 0x0c, + 0xa5, 0x15, 0x04, 0x52, 0x3a, 0x60, 0xd4, 0x03, + 0x06, 0xf6, 0x96, 0xcd, 0x06, 0xf6, 0x96, 0xcd, + 0x06, 0xf6, 0x96, 0xcd, 0x06, 0xf6, 0x96, + }, + valid: false, + }, + { + name: "valid v0 P2WPKH", + pkScript: []byte{ + // OP_0 + 0x00, + // OP_DATA_20 + 0x14, + // <20-byte pubkey hash> + 0xec, 0x6f, 0x7a, 0x5a, 0xa8, 0xf2, 0xb1, 0x0c, + 0xa5, 0x15, 0x04, 0x52, 0x3a, 0x60, 0xd4, 0x03, + 0x06, 0xf6, 0x96, 0xcd, + }, + valid: true, + }, + // Invalid v0 P2WPKH - same as above but missing one byte. + { + name: "invalid v0 P2WPKH", + pkScript: []byte{ + // OP_0 + 0x00, + // OP_DATA_20 + 0x14, + // <20-byte pubkey hash> + 0xec, 0x6f, 0x7a, 0x5a, 0xa8, 0xf2, 0xb1, 0x0c, + 0xa5, 0x15, 0x04, 0x52, 0x3a, 0x60, 0xd4, 0x03, + 0x06, 0xf6, 0x96, + }, + valid: false, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + pkScript, err := ParsePkScript(test.pkScript) + switch { + case err != nil && test.valid: + t.Fatalf("unable to parse valid pkScript=%x: %v", + test.pkScript, err) + case err == nil && !test.valid: + t.Fatalf("successfully parsed invalid pkScript=%x", + test.pkScript) + } + + if !test.valid { + return + } + + if !bytes.Equal(pkScript.Script(), test.pkScript) { + t.Fatalf("expected to re-derive pkScript=%x, "+ + "got pkScript=%x", test.pkScript, + pkScript.Script()) + } + }) + } +} + +// TestComputePkScript ensures that we can correctly re-derive an output's +// pkScript by looking at the input's signature script/witness attempting to +// spend it. +func TestComputePkScript(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + sigScript []byte + witness wire.TxWitness + class ScriptClass + pkScript []byte + }{ + { + name: "empty sigScript and witness", + sigScript: nil, + witness: nil, + class: NonStandardTy, + pkScript: nil, + }, + { + name: "P2PKH sigScript", + sigScript: []byte{ + // OP_DATA_71, + 0x47, + // <71-byte sig> + 0x30, 0x44, 0x02, 0x20, 0x65, 0x92, 0xd8, 0x8e, + 0x1d, 0x0a, 0x4a, 0x3c, 0xc5, 0x9f, 0x92, 0xae, + 0xfe, 0x62, 0x54, 0x74, 0xa9, 0x4d, 0x13, 0xa5, + 0x9f, 0x84, 0x97, 0x78, 0xfc, 0xe7, 0xdf, 0x4b, + 0xe0, 0xc2, 0x28, 0xd8, 0x02, 0x20, 0x2d, 0xea, + 0x36, 0x96, 0x19, 0x1f, 0xb7, 0x00, 0xc5, 0xa7, + 0x7e, 0x22, 0xd9, 0xfb, 0x6b, 0x42, 0x67, 0x42, + 0xa4, 0x2c, 0xac, 0xdb, 0x74, 0xa2, 0x7c, 0x43, + 0xcd, 0x89, 0xa0, 0xf9, 0x44, 0x54, 0x01, + // OP_DATA_33 + 0x21, + // <33-byte compressed pubkey> + 0x02, 0x7d, 0x56, 0x12, 0x09, 0x75, 0x31, 0xc2, + 0x17, 0xfd, 0xd4, 0xd2, 0xe1, 0x7a, 0x35, 0x4b, + 0x17, 0xf2, 0x7a, 0xef, 0x30, 0x9f, 0xb2, 0x7f, + 0x1f, 0x1f, 0x7b, 0x73, 0x7d, 0x9a, 0x24, 0x49, + 0x90, + }, + witness: nil, + class: PubKeyHashTy, + pkScript: []byte{ + // OP_DUP + 0x76, + // OP_HASH160 + 0xa9, + // OP_DATA_20 + 0x14, + // <20-byte pubkey hash> + 0xf0, 0x7a, 0xb8, 0xce, 0x72, 0xda, 0x4e, 0x76, + 0x0b, 0x74, 0x7d, 0x48, 0xd6, 0x65, 0xec, 0x96, + 0xad, 0xf0, 0x24, 0xf5, + // OP_EQUALVERIFY + 0x88, + // OP_CHECKSIG + 0xac, + }, + }, + { + name: "NP2WPKH sigScript", + // Since this is a NP2PKH output, the sigScript is a + // data push of a serialized v0 P2WPKH script. + sigScript: []byte{ + // OP_DATA_16 + 0x16, + // <22-byte redeem script> + 0x00, 0x14, 0x1d, 0x7c, 0xd6, 0xc7, 0x5c, 0x2e, + 0x86, 0xf4, 0xcb, 0xf9, 0x8e, 0xae, 0xd2, 0x21, + 0xb3, 0x0b, 0xd9, 0xa0, 0xb9, 0x28, + }, + // NP2PKH outputs include a witness, but it is not + // needed to reconstruct the pkScript. + witness: nil, + class: ScriptHashTy, + pkScript: []byte{ + // OP_HASH160 + 0xa9, + // OP_DATA_20 + 0x14, + // <20-byte script hash> + 0x90, 0x1c, 0x86, 0x94, 0xc0, 0x3f, 0xaf, 0xd5, + 0x52, 0x28, 0x10, 0xe0, 0x33, 0x0f, 0x26, 0xe6, + 0x7a, 0x85, 0x33, 0xcd, + // OP_EQUAL + 0x87, + }, + }, + { + name: "P2SH sigScript", + sigScript: []byte{ + 0x00, 0x49, 0x30, 0x46, 0x02, 0x21, 0x00, 0xda, + 0xe6, 0xb6, 0x14, 0x1b, 0xa7, 0x24, 0x4f, 0x54, + 0x62, 0xb6, 0x2a, 0x3b, 0x27, 0x59, 0xde, 0xe4, + 0x46, 0x76, 0x19, 0x4e, 0x6c, 0x56, 0x8d, 0x5b, + 0x1c, 0xda, 0x96, 0x2d, 0x4f, 0x6d, 0x79, 0x02, + 0x21, 0x00, 0xa6, 0x6f, 0x60, 0x34, 0x46, 0x09, + 0x0a, 0x22, 0x3c, 0xec, 0x30, 0x33, 0xd9, 0x86, + 0x24, 0xd2, 0x73, 0xa8, 0x91, 0x55, 0xa5, 0xe6, + 0x96, 0x66, 0x0b, 0x6a, 0x50, 0xa3, 0x46, 0x45, + 0xbb, 0x67, 0x01, 0x48, 0x30, 0x45, 0x02, 0x21, + 0x00, 0xe2, 0x73, 0x49, 0xdb, 0x93, 0x82, 0xe1, + 0xf8, 0x8d, 0xae, 0x97, 0x5c, 0x71, 0x19, 0xb7, + 0x79, 0xb6, 0xda, 0x43, 0xa8, 0x4f, 0x16, 0x05, + 0x87, 0x11, 0x9f, 0xe8, 0x12, 0x1d, 0x85, 0xae, + 0xee, 0x02, 0x20, 0x6f, 0x23, 0x2d, 0x0a, 0x7b, + 0x4b, 0xfa, 0xcd, 0x56, 0xa0, 0x72, 0xcc, 0x2a, + 0x44, 0x81, 0x31, 0xd1, 0x0d, 0x73, 0x35, 0xf9, + 0xa7, 0x54, 0x8b, 0xee, 0x1f, 0x70, 0xc5, 0x71, + 0x0b, 0x37, 0x9e, 0x01, 0x47, 0x52, 0x21, 0x03, + 0xab, 0x11, 0x5d, 0xa6, 0xdf, 0x4f, 0x54, 0x0b, + 0xd6, 0xc9, 0xc4, 0xbe, 0x5f, 0xdd, 0xcc, 0x24, + 0x58, 0x8e, 0x7c, 0x2c, 0xaf, 0x13, 0x82, 0x28, + 0xdd, 0x0f, 0xce, 0x29, 0xfd, 0x65, 0xb8, 0x7c, + 0x21, 0x02, 0x15, 0xe8, 0xb7, 0xbf, 0xfe, 0x8d, + 0x9b, 0xbd, 0x45, 0x81, 0xf9, 0xc3, 0xb6, 0xf1, + 0x6d, 0x67, 0x08, 0x36, 0xc3, 0x0b, 0xb2, 0xe0, + 0x3e, 0xfd, 0x9d, 0x41, 0x03, 0xb5, 0x59, 0xeb, + 0x67, 0xcd, 0x52, 0xae, + }, + witness: nil, + class: ScriptHashTy, + pkScript: []byte{ + // OP_HASH160 + 0xA9, + // OP_DATA_20 + 0x14, + // <20-byte script hash> + 0x12, 0xd6, 0x9c, 0xd3, 0x38, 0xa3, 0x8d, 0x0d, + 0x77, 0x83, 0xcf, 0x22, 0x64, 0x97, 0x63, 0x3d, + 0x3c, 0x20, 0x79, 0xea, + // OP_EQUAL + 0x87, + }, + }, + // Invalid P2SH (non push-data only script). + { + name: "invalid P2SH sigScript", + sigScript: []byte{0x6b, 0x65, 0x6b}, // kek + witness: nil, + class: NonStandardTy, + pkScript: nil, + }, + { + name: "P2WSH witness", + sigScript: nil, + witness: [][]byte{ + []byte{}, + // Witness script. + []byte{ + 0x21, 0x03, 0x82, 0x62, 0xa6, 0xc6, + 0xce, 0xc9, 0x3c, 0x2d, 0x3e, 0xcd, + 0x6c, 0x60, 0x72, 0xef, 0xea, 0x86, + 0xd0, 0x2f, 0xf8, 0xe3, 0x32, 0x8b, + 0xbd, 0x02, 0x42, 0xb2, 0x0a, 0xf3, + 0x42, 0x59, 0x90, 0xac, 0xac, + }, + }, + class: WitnessV0ScriptHashTy, + pkScript: []byte{ + // OP_0 + 0x00, + // OP_DATA_32 + 0x20, + // <32-byte script hash> + 0x01, 0xd5, 0xd9, 0x2e, 0xff, 0xa6, 0xff, 0xba, + 0x3e, 0xfa, 0x37, 0x9f, 0x98, 0x30, 0xd0, 0xf7, + 0x56, 0x18, 0xb1, 0x33, 0x93, 0x82, 0x71, 0x52, + 0xd2, 0x6e, 0x43, 0x09, 0x00, 0x0e, 0x88, 0xb1, + }, + }, + { + name: "P2WPKH witness", + sigScript: nil, + witness: [][]byte{ + // Signature is not needed to re-derive the + // pkScript. + []byte{}, + // Compressed pubkey. + []byte{ + 0x03, 0x82, 0x62, 0xa6, 0xc6, 0xce, + 0xc9, 0x3c, 0x2d, 0x3e, 0xcd, 0x6c, + 0x60, 0x72, 0xef, 0xea, 0x86, 0xd0, + 0x2f, 0xf8, 0xe3, 0x32, 0x8b, 0xbd, + 0x02, 0x42, 0xb2, 0x0a, 0xf3, 0x42, + 0x59, 0x90, 0xac, + }, + }, + class: WitnessV0PubKeyHashTy, + pkScript: []byte{ + // OP_0 + 0x00, + // OP_DATA_20 + 0x14, + // <20-byte pubkey hash> + 0x1d, 0x7c, 0xd6, 0xc7, 0x5c, 0x2e, 0x86, 0xf4, + 0xcb, 0xf9, 0x8e, 0xae, 0xd2, 0x21, 0xb3, 0x0b, + 0xd9, 0xa0, 0xb9, 0x28, + }, + }, + // Invalid v0 P2WPKH - same as above but missing a byte on the + // public key. + { + name: "invalid P2WPKH witness", + sigScript: nil, + witness: [][]byte{ + // Signature is not needed to re-derive the + // pkScript. + []byte{}, + // Malformed compressed pubkey. + []byte{ + 0x03, 0x82, 0x62, 0xa6, 0xc6, 0xce, + 0xc9, 0x3c, 0x2d, 0x3e, 0xcd, 0x6c, + 0x60, 0x72, 0xef, 0xea, 0x86, 0xd0, + 0x2f, 0xf8, 0xe3, 0x32, 0x8b, 0xbd, + 0x02, 0x42, 0xb2, 0x0a, 0xf3, 0x42, + 0x59, 0x90, + }, + }, + class: WitnessV0PubKeyHashTy, + pkScript: nil, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + valid := test.pkScript != nil + pkScript, err := ComputePkScript( + test.sigScript, test.witness, + ) + if err != nil && valid { + t.Fatalf("unable to compute pkScript: %v", err) + } + + if !valid { + return + } + + if pkScript.Class() != test.class { + t.Fatalf("expected pkScript of type %v, got %v", + test.class, pkScript.Class()) + } + if !bytes.Equal(pkScript.Script(), test.pkScript) { + t.Fatalf("expected pkScript=%x, got pkScript=%x", + test.pkScript, pkScript.Script()) + } + }) + } +} From be2b6dc98ad36055fc8d0aadc5c09d628a5d285f Mon Sep 17 00:00:00 2001 From: Wilmer Paulino Date: Tue, 4 Dec 2018 10:21:56 -0800 Subject: [PATCH 2/3] rpcwebsocket: modify rescanKeys to take addresses as strings In this commit, we modify the rescanKeys struct, which contains the relevant keys that should be matched when rescanning the chain, to take addresses in their string representation. This ends up simplifying a lot of the logic as we no longer have to special-case specific script types. --- rpcwebsocket.go | 117 ++++-------------------------------------------- 1 file changed, 8 insertions(+), 109 deletions(-) diff --git a/rpcwebsocket.go b/rpcwebsocket.go index 8b9d06b4..1a758ffb 100644 --- a/rpcwebsocket.go +++ b/rpcwebsocket.go @@ -20,8 +20,6 @@ import ( "sync" "time" - "golang.org/x/crypto/ripemd160" - "github.com/btcsuite/btcd/blockchain" "github.com/btcsuite/btcd/btcjson" "github.com/btcsuite/btcd/chaincfg" @@ -31,6 +29,7 @@ import ( "github.com/btcsuite/btcd/wire" "github.com/btcsuite/btcutil" "github.com/btcsuite/websocket" + "golang.org/x/crypto/ripemd160" ) const ( @@ -1978,12 +1977,8 @@ func deserializeOutpoints(serializedOuts []btcjson.OutPoint) ([]*wire.OutPoint, } type rescanKeys struct { - fallbacks map[string]struct{} - pubKeyHashes map[[ripemd160.Size]byte]struct{} - scriptHashes map[[ripemd160.Size]byte]struct{} - compressedPubKeys map[[33]byte]struct{} - uncompressedPubKeys map[[65]byte]struct{} - unspent map[wire.OutPoint]struct{} + addrs map[string]struct{} + unspent map[wire.OutPoint]struct{} } // unspentSlice returns a slice of currently-unspent outpoints for the rescan @@ -2052,57 +2047,8 @@ func rescanBlock(wsc *wsClient, lookups *rescanKeys, blk *btcutil.Block) { txout.PkScript, wsc.server.cfg.ChainParams) for _, addr := range addrs { - switch a := addr.(type) { - case *btcutil.AddressPubKeyHash: - if _, ok := lookups.pubKeyHashes[*a.Hash160()]; !ok { - continue - } - - case *btcutil.AddressScriptHash: - if _, ok := lookups.scriptHashes[*a.Hash160()]; !ok { - continue - } - - case *btcutil.AddressPubKey: - found := false - switch sa := a.ScriptAddress(); len(sa) { - case 33: // Compressed - var key [33]byte - copy(key[:], sa) - if _, ok := lookups.compressedPubKeys[key]; ok { - found = true - } - - case 65: // Uncompressed - var key [65]byte - copy(key[:], sa) - if _, ok := lookups.uncompressedPubKeys[key]; ok { - found = true - } - - default: - rpcsLog.Warnf("Skipping rescanned pubkey of unknown "+ - "serialized length %d", len(sa)) - continue - } - - // If the transaction output pays to the pubkey of - // a rescanned P2PKH address, include it as well. - if !found { - pkh := a.AddressPubKeyHash() - if _, ok := lookups.pubKeyHashes[*pkh.Hash160()]; !ok { - continue - } - } - - default: - // A new address type must have been added. Encode as a - // payment address string and check the fallback map. - addrStr := addr.EncodeAddress() - _, ok := lookups.fallbacks[addrStr] - if !ok { - continue - } + if _, ok := lookups.addrs[addr.String()]; !ok { + continue } outpoint := wire.OutPoint{ @@ -2353,58 +2299,11 @@ func handleRescan(wsc *wsClient, icmd interface{}) (interface{}, error) { // Build lookup maps. lookups := rescanKeys{ - fallbacks: map[string]struct{}{}, - pubKeyHashes: map[[ripemd160.Size]byte]struct{}{}, - scriptHashes: map[[ripemd160.Size]byte]struct{}{}, - compressedPubKeys: map[[33]byte]struct{}{}, - uncompressedPubKeys: map[[65]byte]struct{}{}, - unspent: map[wire.OutPoint]struct{}{}, + addrs: map[string]struct{}{}, + unspent: map[wire.OutPoint]struct{}{}, } - var compressedPubkey [33]byte - var uncompressedPubkey [65]byte - params := wsc.server.cfg.ChainParams for _, addrStr := range cmd.Addresses { - addr, err := btcutil.DecodeAddress(addrStr, params) - if err != nil { - jsonErr := btcjson.RPCError{ - Code: btcjson.ErrRPCInvalidAddressOrKey, - Message: "Rescan address " + addrStr + ": " + - err.Error(), - } - return nil, &jsonErr - } - switch a := addr.(type) { - case *btcutil.AddressPubKeyHash: - lookups.pubKeyHashes[*a.Hash160()] = struct{}{} - - case *btcutil.AddressScriptHash: - lookups.scriptHashes[*a.Hash160()] = struct{}{} - - case *btcutil.AddressPubKey: - pubkeyBytes := a.ScriptAddress() - switch len(pubkeyBytes) { - case 33: // Compressed - copy(compressedPubkey[:], pubkeyBytes) - lookups.compressedPubKeys[compressedPubkey] = struct{}{} - - case 65: // Uncompressed - copy(uncompressedPubkey[:], pubkeyBytes) - lookups.uncompressedPubKeys[uncompressedPubkey] = struct{}{} - - default: - jsonErr := btcjson.RPCError{ - Code: btcjson.ErrRPCInvalidAddressOrKey, - Message: "Pubkey " + addrStr + " is of unknown length", - } - return nil, &jsonErr - } - - default: - // A new address type must have been added. Use encoded - // payment address string as a fallback until a fast path - // is added. - lookups.fallbacks[addrStr] = struct{}{} - } + lookups.addrs[addrStr] = struct{}{} } for _, outpoint := range outpoints { lookups.unspent[*outpoint] = struct{}{} From f6eae62a77102a618a731e04e0f219b1feccfbdb Mon Sep 17 00:00:00 2001 From: Wilmer Paulino Date: Tue, 4 Dec 2018 10:23:33 -0800 Subject: [PATCH 3/3] rpcwebsocket: detect and notify spend of script In this commit, we modify the rescanBlock method to also determine whether a script (encoded as an address in its rescanKeys) has been spent. Upon detecting a spend, a btcjson.RedeemingTxNtfn is sent to the client who requested it. --- rpcwebsocket.go | 76 +++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 67 insertions(+), 9 deletions(-) diff --git a/rpcwebsocket.go b/rpcwebsocket.go index 1a758ffb..eddac5ab 100644 --- a/rpcwebsocket.go +++ b/rpcwebsocket.go @@ -2015,7 +2015,28 @@ func rescanBlock(wsc *wsClient, lookups *rescanKeys, blk *btcutil.Block) { spentNotified := false recvNotified := false + // notifySpend is a closure we'll use when we first detect that + // a transactions spends an outpoint/script in our filter list. + notifySpend := func() error { + if txHex == "" { + txHex = txHexString(tx.MsgTx()) + } + marshalledJSON, err := newRedeemingTxNotification( + txHex, tx.Index(), blk, + ) + if err != nil { + return fmt.Errorf("unable to marshal "+ + "btcjson.RedeeminTxNtfn: %v", err) + } + + return wsc.QueueNotification(marshalledJSON) + } + + // We'll start by iterating over the transaction's inputs to + // determine if it spends an outpoint/script in our filter list. for _, txin := range tx.MsgTx().TxIn { + // If it spends an outpoint, we'll dispatch a spend + // notification for the transaction. if _, ok := lookups.unspent[txin.PreviousOutPoint]; ok { delete(lookups.unspent, txin.PreviousOutPoint) @@ -2023,21 +2044,58 @@ func rescanBlock(wsc *wsClient, lookups *rescanKeys, blk *btcutil.Block) { continue } - if txHex == "" { - txHex = txHexString(tx.MsgTx()) - } - marshalledJSON, err := newRedeemingTxNotification(txHex, tx.Index(), blk) - if err != nil { - rpcsLog.Errorf("Failed to marshal redeemingtx notification: %v", err) - continue - } + err := notifySpend() - err = wsc.QueueNotification(marshalledJSON) // Stop the rescan early if the websocket client // disconnected. if err == ErrClientQuit { return } + if err != nil { + rpcsLog.Errorf("Unable to notify "+ + "redeeming transaction %v: %v", + tx.Hash(), err) + continue + } + + spentNotified = true + } + + // We'll also recompute the pkScript the input is + // attempting to spend to determine whether it is + // relevant to us. + pkScript, err := txscript.ComputePkScript( + txin.SignatureScript, txin.Witness, + ) + if err != nil { + continue + } + addr, err := pkScript.Address(wsc.server.cfg.ChainParams) + if err != nil { + continue + } + + // If it is, we'll also dispatch a spend notification + // for this transaction if we haven't already. + if _, ok := lookups.addrs[addr.String()]; ok { + if spentNotified { + continue + } + + err := notifySpend() + + // Stop the rescan early if the websocket client + // disconnected. + if err == ErrClientQuit { + return + } + if err != nil { + rpcsLog.Errorf("Unable to notify "+ + "redeeming transaction %v: %v", + tx.Hash(), err) + continue + } + spentNotified = true } }