From 7aaa28a31e63c608bfdc6af7c259a06eeae0d7ac Mon Sep 17 00:00:00 2001 From: Dave Collins Date: Wed, 13 Mar 2019 01:12:28 -0500 Subject: [PATCH] txscript: Optimize ExtractPkScriptAddrs pubkeyhash. This continues the process of converting the ExtractPkScriptAddrs function to use the optimized extraction functions recently introduced as part of the typeOfScript conversion. In particular, this converts the detection for pay-to-pubkey-hash scripts. --- txscript/standard.go | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/txscript/standard.go b/txscript/standard.go index 8b5b098556..7d3833c6c1 100644 --- a/txscript/standard.go +++ b/txscript/standard.go @@ -805,6 +805,19 @@ func PushedData(script []byte) ([][]byte, error) { return data, nil } +// pubKeyHashToAddrs is a convenience function to attempt to convert the +// passed hash to a pay-to-pubkey-hash address housed within an address +// slice. It is used to consolidate common code. +func pubKeyHashToAddrs(hash []byte, params *chaincfg.Params) []btcutil.Address { + // Skip the pubkey hash if it's invalid for some reason. + var addrs []btcutil.Address + addr, err := btcutil.NewAddressPubKeyHash(hash, params) + if err == nil { + addrs = append(addrs, addr) + } + return addrs +} + // scriptHashToAddrs is a convenience function to attempt to convert the passed // hash to a pay-to-script-hash address housed within an address slice. It is // used to consolidate common code. @@ -827,6 +840,11 @@ func ExtractPkScriptAddrs(pkScript []byte, chainParams *chaincfg.Params) (Script // Avoid parsing the script for the cases that already have the able to // work with raw scripts. + // Check for pay-to-pubkey-hash script. + if hash := extractPubKeyHash(pkScript); hash != nil { + return PubKeyHashTy, pubKeyHashToAddrs(hash, chainParams), 1, nil + } + // Check for pay-to-script-hash. if hash := extractScriptHash(pkScript); hash != nil { return ScriptHashTy, scriptHashToAddrs(hash, chainParams), 1, nil @@ -849,18 +867,6 @@ func ExtractPkScriptAddrs(pkScript []byte, chainParams *chaincfg.Params) (Script scriptClass := typeOfScript(scriptVersion, pkScript) switch scriptClass { - case PubKeyHashTy: - // A pay-to-pubkey-hash script is of the form: - // OP_DUP OP_HASH160 OP_EQUALVERIFY OP_CHECKSIG - // Therefore the pubkey hash is the 3rd item on the stack. - // Skip the pubkey hash if it's invalid for some reason. - requiredSigs = 1 - addr, err := btcutil.NewAddressPubKeyHash(pops[2].data, - chainParams) - if err == nil { - addrs = append(addrs, addr) - } - case WitnessV0PubKeyHashTy: // A pay-to-witness-pubkey-hash script is of thw form: // OP_0 <20-byte hash>