github.com/lbryio/lbcd@v0.22.119/txscript/standard.go (about)

     1  // Copyright (c) 2013-2020 The btcsuite developers
     2  // Use of this source code is governed by an ISC
     3  // license that can be found in the LICENSE file.
     4  
     5  package txscript
     6  
     7  import (
     8  	"fmt"
     9  
    10  	"github.com/lbryio/lbcd/chaincfg"
    11  	"github.com/lbryio/lbcd/wire"
    12  	btcutil "github.com/lbryio/lbcutil"
    13  )
    14  
    15  const (
    16  	// MaxDataCarrierSize is the maximum number of bytes allowed in pushed
    17  	// data to be considered a nulldata transaction
    18  	MaxDataCarrierSize = 80
    19  
    20  	// StandardVerifyFlags are the script flags which are used when
    21  	// executing transaction scripts to enforce additional checks which
    22  	// are required for the script to be considered standard.  These checks
    23  	// help reduce issues related to transaction malleability as well as
    24  	// allow pay-to-script hash transactions.  Note these flags are
    25  	// different than what is required for the consensus rules in that they
    26  	// are more strict.
    27  	//
    28  	// TODO: This definition does not belong here.  It belongs in a policy
    29  	// package.
    30  	StandardVerifyFlags = ScriptBip16 |
    31  		ScriptVerifyDERSignatures |
    32  		ScriptVerifyStrictEncoding |
    33  		ScriptVerifyMinimalData |
    34  		ScriptStrictMultiSig |
    35  		ScriptDiscourageUpgradableNops |
    36  		ScriptVerifyCleanStack |
    37  		ScriptVerifyNullFail |
    38  		ScriptVerifyCheckLockTimeVerify |
    39  		ScriptVerifyCheckSequenceVerify |
    40  		ScriptVerifyLowS |
    41  		ScriptStrictMultiSig |
    42  		ScriptVerifyWitness |
    43  		ScriptVerifyDiscourageUpgradeableWitnessProgram |
    44  		ScriptVerifyMinimalIf |
    45  		ScriptVerifyWitnessPubKeyType
    46  )
    47  
    48  // ScriptClass is an enumeration for the list of standard types of script.
    49  type ScriptClass byte
    50  
    51  // Classes of script payment known about in the blockchain.
    52  const (
    53  	NonStandardTy         ScriptClass = iota // None of the recognized forms.
    54  	PubKeyTy                                 // Pay pubkey.
    55  	PubKeyHashTy                             // Pay pubkey hash.
    56  	WitnessV0PubKeyHashTy                    // Pay witness pubkey hash.
    57  	ScriptHashTy                             // Pay to script hash.
    58  	WitnessV0ScriptHashTy                    // Pay to witness script hash.
    59  	MultiSigTy                               // Multi signature.
    60  	NullDataTy                               // Empty data-only (provably prunable).
    61  	WitnessUnknownTy                         // Witness unknown
    62  )
    63  
    64  // scriptClassToName houses the human-readable strings which describe each
    65  // script class.
    66  var scriptClassToName = []string{
    67  	NonStandardTy:         "nonstandard",
    68  	PubKeyTy:              "pubkey",
    69  	PubKeyHashTy:          "pubkeyhash",
    70  	WitnessV0PubKeyHashTy: "witness_v0_keyhash",
    71  	ScriptHashTy:          "scripthash",
    72  	WitnessV0ScriptHashTy: "witness_v0_scripthash",
    73  	MultiSigTy:            "multisig",
    74  	NullDataTy:            "nulldata",
    75  	WitnessUnknownTy:      "witness_unknown",
    76  }
    77  
    78  // String implements the Stringer interface by returning the name of
    79  // the enum script class. If the enum is invalid then "Invalid" will be
    80  // returned.
    81  func (t ScriptClass) String() string {
    82  	if int(t) > len(scriptClassToName) || int(t) < 0 {
    83  		return "Invalid"
    84  	}
    85  	return scriptClassToName[t]
    86  }
    87  
    88  // extractCompressedPubKey extracts a compressed public key from the passed
    89  // script if it is a standard pay-to-compressed-secp256k1-pubkey script.  It
    90  // will return nil otherwise.
    91  func extractCompressedPubKey(script []byte) []byte {
    92  	// A pay-to-compressed-pubkey script is of the form:
    93  	//  OP_DATA_33 <33-byte compressed pubkey> OP_CHECKSIG
    94  
    95  	// All compressed secp256k1 public keys must start with 0x02 or 0x03.
    96  	if len(script) == 35 &&
    97  		script[34] == OP_CHECKSIG &&
    98  		script[0] == OP_DATA_33 &&
    99  		(script[1] == 0x02 || script[1] == 0x03) {
   100  
   101  		return script[1:34]
   102  	}
   103  
   104  	return nil
   105  }
   106  
   107  // extractUncompressedPubKey extracts an uncompressed public key from the
   108  // passed script if it is a standard pay-to-uncompressed-secp256k1-pubkey
   109  // script.  It will return nil otherwise.
   110  func extractUncompressedPubKey(script []byte) []byte {
   111  	// A pay-to-uncompressed-pubkey script is of the form:
   112  	//   OP_DATA_65 <65-byte uncompressed pubkey> OP_CHECKSIG
   113  	//
   114  	// All non-hybrid uncompressed secp256k1 public keys must start with 0x04.
   115  	// Hybrid uncompressed secp256k1 public keys start with 0x06 or 0x07:
   116  	//   - 0x06 => hybrid format for even Y coords
   117  	//   - 0x07 => hybrid format for odd Y coords
   118  	if len(script) == 67 &&
   119  		script[66] == OP_CHECKSIG &&
   120  		script[0] == OP_DATA_65 &&
   121  		(script[1] == 0x04 || script[1] == 0x06 || script[1] == 0x07) {
   122  
   123  		return script[1:66]
   124  	}
   125  	return nil
   126  }
   127  
   128  // extractPubKey extracts either compressed or uncompressed public key from the
   129  // passed script if it is a either a standard pay-to-compressed-secp256k1-pubkey
   130  // or pay-to-uncompressed-secp256k1-pubkey script, respectively.  It will return
   131  // nil otherwise.
   132  func extractPubKey(script []byte) []byte {
   133  	if pubKey := extractCompressedPubKey(script); pubKey != nil {
   134  		return pubKey
   135  	}
   136  	return extractUncompressedPubKey(script)
   137  }
   138  
   139  // isPubKeyScript returns whether or not the passed script is either a standard
   140  // pay-to-compressed-secp256k1-pubkey or pay-to-uncompressed-secp256k1-pubkey
   141  // script.
   142  func isPubKeyScript(script []byte) bool {
   143  	return extractPubKey(script) != nil
   144  }
   145  
   146  // extractPubKeyHash extracts the public key hash from the passed script if it
   147  // is a standard pay-to-pubkey-hash script.  It will return nil otherwise.
   148  func extractPubKeyHash(script []byte) []byte {
   149  	// A pay-to-pubkey-hash script is of the form:
   150  	//  OP_DUP OP_HASH160 <20-byte hash> OP_EQUALVERIFY OP_CHECKSIG
   151  	if len(script) == 25 &&
   152  		script[0] == OP_DUP &&
   153  		script[1] == OP_HASH160 &&
   154  		script[2] == OP_DATA_20 &&
   155  		script[23] == OP_EQUALVERIFY &&
   156  		script[24] == OP_CHECKSIG {
   157  
   158  		return script[3:23]
   159  	}
   160  
   161  	return nil
   162  }
   163  
   164  // isPubKeyHashScript returns whether or not the passed script is a standard
   165  // pay-to-pubkey-hash script.
   166  func isPubKeyHashScript(script []byte) bool {
   167  	return extractPubKeyHash(script) != nil
   168  }
   169  
   170  // extractScriptHash extracts the script hash from the passed script if it is a
   171  // standard pay-to-script-hash script.  It will return nil otherwise.
   172  //
   173  // NOTE: This function is only valid for version 0 opcodes.  Since the function
   174  // does not accept a script version, the results are undefined for other script
   175  // versions.
   176  func extractScriptHash(script []byte) []byte {
   177  	// A pay-to-script-hash script is of the form:
   178  	//  OP_HASH160 <20-byte scripthash> OP_EQUAL
   179  	if len(script) == 23 &&
   180  		script[0] == OP_HASH160 &&
   181  		script[1] == OP_DATA_20 &&
   182  		script[22] == OP_EQUAL {
   183  
   184  		return script[2:22]
   185  	}
   186  
   187  	return nil
   188  }
   189  
   190  // isScriptHashScript returns whether or not the passed script is a standard
   191  // pay-to-script-hash script.
   192  func isScriptHashScript(script []byte) bool {
   193  	return extractScriptHash(script) != nil
   194  }
   195  
   196  // multiSigDetails houses details extracted from a standard multisig script.
   197  type multiSigDetails struct {
   198  	requiredSigs int
   199  	numPubKeys   int
   200  	pubKeys      [][]byte
   201  	valid        bool
   202  }
   203  
   204  // extractMultisigScriptDetails attempts to extract details from the passed
   205  // script if it is a standard multisig script.  The returned details struct will
   206  // have the valid flag set to false otherwise.
   207  //
   208  // The extract pubkeys flag indicates whether or not the pubkeys themselves
   209  // should also be extracted and is provided because extracting them results in
   210  // an allocation that the caller might wish to avoid.  The pubKeys member of
   211  // the returned details struct will be nil when the flag is false.
   212  //
   213  // NOTE: This function is only valid for version 0 scripts.  The returned
   214  // details struct will always be empty and have the valid flag set to false for
   215  // other script versions.
   216  func extractMultisigScriptDetails(scriptVersion uint16, script []byte, extractPubKeys bool) multiSigDetails {
   217  	// The only currently supported script version is 0.
   218  	if scriptVersion != 0 {
   219  		return multiSigDetails{}
   220  	}
   221  
   222  	// A multi-signature script is of the form:
   223  	//  NUM_SIGS PUBKEY PUBKEY PUBKEY ... NUM_PUBKEYS OP_CHECKMULTISIG
   224  
   225  	// The script can't possibly be a multisig script if it doesn't end with
   226  	// OP_CHECKMULTISIG or have at least two small integer pushes preceding it.
   227  	// Fail fast to avoid more work below.
   228  	if len(script) < 3 || script[len(script)-1] != OP_CHECKMULTISIG {
   229  		return multiSigDetails{}
   230  	}
   231  
   232  	// The first opcode must be a small integer specifying the number of
   233  	// signatures required.
   234  	tokenizer := MakeScriptTokenizer(scriptVersion, script)
   235  	if !tokenizer.Next() || !isSmallInt(tokenizer.Opcode()) {
   236  		return multiSigDetails{}
   237  	}
   238  	requiredSigs := asSmallInt(tokenizer.Opcode())
   239  
   240  	// The next series of opcodes must either push public keys or be a small
   241  	// integer specifying the number of public keys.
   242  	var numPubKeys int
   243  	var pubKeys [][]byte
   244  	if extractPubKeys {
   245  		pubKeys = make([][]byte, 0, MaxPubKeysPerMultiSig)
   246  	}
   247  	for tokenizer.Next() {
   248  		if isSmallInt(tokenizer.Opcode()) {
   249  			break
   250  		}
   251  
   252  		data := tokenizer.Data()
   253  		numPubKeys++
   254  		if !isStrictPubKeyEncoding(data) {
   255  			continue
   256  		}
   257  		if extractPubKeys {
   258  			pubKeys = append(pubKeys, data)
   259  		}
   260  	}
   261  	if tokenizer.Done() {
   262  		return multiSigDetails{}
   263  	}
   264  
   265  	// The next opcode must be a small integer specifying the number of public
   266  	// keys required.
   267  	op := tokenizer.Opcode()
   268  	if !isSmallInt(op) || asSmallInt(op) != numPubKeys {
   269  		return multiSigDetails{}
   270  	}
   271  
   272  	// There must only be a single opcode left unparsed which will be
   273  	// OP_CHECKMULTISIG per the check above.
   274  	if int32(len(tokenizer.Script()))-tokenizer.ByteIndex() != 1 {
   275  		return multiSigDetails{}
   276  	}
   277  
   278  	return multiSigDetails{
   279  		requiredSigs: requiredSigs,
   280  		numPubKeys:   numPubKeys,
   281  		pubKeys:      pubKeys,
   282  		valid:        true,
   283  	}
   284  }
   285  
   286  // isMultisigScript returns whether or not the passed script is a standard
   287  // multisig script.
   288  //
   289  // NOTE: This function is only valid for version 0 scripts.  It will always
   290  // return false for other script versions.
   291  func isMultisigScript(scriptVersion uint16, script []byte) bool {
   292  	// Since this is only checking the form of the script, don't extract the
   293  	// public keys to avoid the allocation.
   294  	details := extractMultisigScriptDetails(scriptVersion, script, false)
   295  	return details.valid
   296  }
   297  
   298  // IsMultisigScript returns whether or not the passed script is a standard
   299  // multisignature script.
   300  //
   301  // NOTE: This function is only valid for version 0 scripts.  Since the function
   302  // does not accept a script version, the results are undefined for other script
   303  // versions.
   304  //
   305  // The error is DEPRECATED and will be removed in the major version bump.
   306  func IsMultisigScript(script []byte) (bool, error) {
   307  	const scriptVersion = 0
   308  	return isMultisigScript(scriptVersion, script), nil
   309  }
   310  
   311  // IsMultisigSigScript returns whether or not the passed script appears to be a
   312  // signature script which consists of a pay-to-script-hash multi-signature
   313  // redeem script.  Determining if a signature script is actually a redemption of
   314  // pay-to-script-hash requires the associated public key script which is often
   315  // expensive to obtain.  Therefore, this makes a fast best effort guess that has
   316  // a high probability of being correct by checking if the signature script ends
   317  // with a data push and treating that data push as if it were a p2sh redeem
   318  // script
   319  //
   320  // NOTE: This function is only valid for version 0 scripts.  Since the function
   321  // does not accept a script version, the results are undefined for other script
   322  // versions.
   323  func IsMultisigSigScript(script []byte) bool {
   324  	const scriptVersion = 0
   325  
   326  	// The script can't possibly be a multisig signature script if it doesn't
   327  	// end with OP_CHECKMULTISIG in the redeem script or have at least two small
   328  	// integers preceding it, and the redeem script itself must be preceded by
   329  	// at least a data push opcode.  Fail fast to avoid more work below.
   330  	if len(script) < 4 || script[len(script)-1] != OP_CHECKMULTISIG {
   331  		return false
   332  	}
   333  
   334  	// Parse through the script to find the last opcode and any data it might
   335  	// push and treat it as a p2sh redeem script even though it might not
   336  	// actually be one.
   337  	possibleRedeemScript := finalOpcodeData(scriptVersion, script)
   338  	if possibleRedeemScript == nil {
   339  		return false
   340  	}
   341  
   342  	// Finally, return if that possible redeem script is a multisig script.
   343  	return isMultisigScript(scriptVersion, possibleRedeemScript)
   344  }
   345  
   346  // extractWitnessPubKeyHash extracts the witness public key hash from the passed
   347  // script if it is a standard pay-to-witness-pubkey-hash script. It will return
   348  // nil otherwise.
   349  func extractWitnessPubKeyHash(script []byte) []byte {
   350  	// A pay-to-witness-pubkey-hash script is of the form:
   351  	//   OP_0 OP_DATA_20 <20-byte-hash>
   352  	if len(script) == 22 &&
   353  		script[0] == OP_0 &&
   354  		script[1] == OP_DATA_20 {
   355  
   356  		return script[2:22]
   357  	}
   358  
   359  	return nil
   360  }
   361  
   362  // isWitnessPubKeyHashScript returns whether or not the passed script is a
   363  // standard pay-to-witness-pubkey-hash script.
   364  func isWitnessPubKeyHashScript(script []byte) bool {
   365  	return extractWitnessPubKeyHash(script) != nil
   366  }
   367  
   368  // extractWitnessScriptHash extracts the witness script hash from the passed
   369  // script if it is standard pay-to-witness-script-hash script. It will return
   370  // nil otherwise.
   371  func extractWitnessScriptHash(script []byte) []byte {
   372  	// A pay-to-witness-script-hash script is of the form:
   373  	//   OP_0 OP_DATA_32 <32-byte-hash>
   374  	if len(script) == 34 &&
   375  		script[0] == OP_0 &&
   376  		script[1] == OP_DATA_32 {
   377  
   378  		return script[2:34]
   379  	}
   380  
   381  	return nil
   382  }
   383  
   384  // isWitnessScriptHashScript returns whether or not the passed script is a
   385  // standard pay-to-witness-script-hash script.
   386  func isWitnessScriptHashScript(script []byte) bool {
   387  	return extractWitnessScriptHash(script) != nil
   388  }
   389  
   390  // extractWitnessProgramInfo returns the version and program if the passed
   391  // script constitutes a valid witness program. The last return value indicates
   392  // whether or not the script is a valid witness program.
   393  func extractWitnessProgramInfo(script []byte) (int, []byte, bool) {
   394  	// Skip parsing if we know the program is invalid based on size.
   395  	if len(script) < 4 || len(script) > 42 {
   396  		return 0, nil, false
   397  	}
   398  
   399  	const scriptVersion = 0
   400  	tokenizer := MakeScriptTokenizer(scriptVersion, script)
   401  
   402  	// The first opcode must be a small int.
   403  	if !tokenizer.Next() ||
   404  		!isSmallInt(tokenizer.Opcode()) {
   405  
   406  		return 0, nil, false
   407  	}
   408  	version := asSmallInt(tokenizer.Opcode())
   409  
   410  	// The second opcode must be a canonical data push, the length of the
   411  	// data push is bounded to 40 by the initial check on overall script
   412  	// length.
   413  	if !tokenizer.Next() ||
   414  		!isCanonicalPush(tokenizer.Opcode(), tokenizer.Data()) {
   415  
   416  		return 0, nil, false
   417  	}
   418  	program := tokenizer.Data()
   419  
   420  	// The witness program is valid if there are no more opcodes, and we
   421  	// terminated without a parsing error.
   422  	valid := tokenizer.Done() && tokenizer.Err() == nil
   423  
   424  	return version, program, valid
   425  }
   426  
   427  // isWitnessProgramScript returns true if the passed script is a witness
   428  // program, and false otherwise. A witness program MUST adhere to the following
   429  // constraints: there must be exactly two pops (program version and the program
   430  // itself), the first opcode MUST be a small integer (0-16), the push data MUST
   431  // be canonical, and finally the size of the push data must be between 2 and 40
   432  // bytes.
   433  //
   434  // The length of the script must be between 4 and 42 bytes. The
   435  // smallest program is the witness version, followed by a data push of
   436  // 2 bytes.  The largest allowed witness program has a data push of
   437  // 40-bytes.
   438  //
   439  // NOTE: This function is only valid for version 0 scripts.  Since the function
   440  // does not accept a script version, the results are undefined for other script
   441  // versions.
   442  func isWitnessProgramScript(script []byte) bool {
   443  	_, _, valid := extractWitnessProgramInfo(script)
   444  	return valid
   445  }
   446  
   447  // isNullDataScript returns whether or not the passed script is a standard
   448  // null data script.
   449  //
   450  // NOTE: This function is only valid for version 0 scripts.  It will always
   451  // return false for other script versions.
   452  func isNullDataScript(scriptVersion uint16, script []byte) bool {
   453  	// The only currently supported script version is 0.
   454  	if scriptVersion != 0 {
   455  		return false
   456  	}
   457  
   458  	// A null script is of the form:
   459  	//  OP_RETURN <optional data>
   460  	//
   461  	// Thus, it can either be a single OP_RETURN or an OP_RETURN followed by a
   462  	// data push up to MaxDataCarrierSize bytes.
   463  
   464  	// The script can't possibly be a a null data script if it doesn't start
   465  	// with OP_RETURN.  Fail fast to avoid more work below.
   466  	if len(script) < 1 || script[0] != OP_RETURN {
   467  		return false
   468  	}
   469  
   470  	// Single OP_RETURN.
   471  	if len(script) == 1 {
   472  		return true
   473  	}
   474  
   475  	// OP_RETURN followed by data push up to MaxDataCarrierSize bytes.
   476  	tokenizer := MakeScriptTokenizer(scriptVersion, script[1:])
   477  	return tokenizer.Next() && tokenizer.Done() &&
   478  		(isSmallInt(tokenizer.Opcode()) || tokenizer.Opcode() <= OP_PUSHDATA4) &&
   479  		len(tokenizer.Data()) <= MaxDataCarrierSize
   480  }
   481  
   482  // scriptType returns the type of the script being inspected from the known
   483  // standard types.
   484  //
   485  // NOTE:  All scripts that are not version 0 are currently considered non
   486  // standard.
   487  func typeOfScript(scriptVersion uint16, script []byte) ScriptClass {
   488  	if scriptVersion != 0 {
   489  		return NonStandardTy
   490  	}
   491  
   492  	switch {
   493  	case isPubKeyScript(script):
   494  		return PubKeyTy
   495  	case isPubKeyHashScript(script):
   496  		return PubKeyHashTy
   497  	case isScriptHashScript(script):
   498  		return ScriptHashTy
   499  	case isWitnessPubKeyHashScript(script):
   500  		return WitnessV0PubKeyHashTy
   501  	case isWitnessScriptHashScript(script):
   502  		return WitnessV0ScriptHashTy
   503  	case isMultisigScript(scriptVersion, script):
   504  		return MultiSigTy
   505  	case isNullDataScript(scriptVersion, script):
   506  		return NullDataTy
   507  	default:
   508  		return NonStandardTy
   509  	}
   510  }
   511  
   512  // GetScriptClass returns the class of the script passed.
   513  //
   514  // NonStandardTy will be returned when the script does not parse.
   515  func GetScriptClass(script []byte) ScriptClass {
   516  	const scriptVersion = 0
   517  	return typeOfScript(scriptVersion, script)
   518  }
   519  
   520  // NewScriptClass returns the ScriptClass corresponding to the string name
   521  // provided as argument. ErrUnsupportedScriptType error is returned if the
   522  // name doesn't correspond to any known ScriptClass.
   523  //
   524  // Not to be confused with GetScriptClass.
   525  func NewScriptClass(name string) (*ScriptClass, error) {
   526  	for i, n := range scriptClassToName {
   527  		if n == name {
   528  			value := ScriptClass(i)
   529  			return &value, nil
   530  		}
   531  	}
   532  
   533  	return nil, fmt.Errorf("%w: %s", ErrUnsupportedScriptType, name)
   534  }
   535  
   536  // expectedInputs returns the number of arguments required by a script.
   537  // If the script is of unknown type such that the number can not be determined
   538  // then -1 is returned. We are an internal function and thus assume that class
   539  // is the real class of pops (and we can thus assume things that were determined
   540  // while finding out the type).
   541  //
   542  // NOTE: This function is only valid for version 0 scripts.  Since the function
   543  // does not accept a script version, the results are undefined for other script
   544  // versions.
   545  func expectedInputs(script []byte, class ScriptClass) int {
   546  	switch class {
   547  	case PubKeyTy:
   548  		return 1
   549  
   550  	case PubKeyHashTy:
   551  		return 2
   552  
   553  	case WitnessV0PubKeyHashTy:
   554  		return 2
   555  
   556  	case ScriptHashTy:
   557  		// Not including script.  That is handled by the caller.
   558  		return 1
   559  
   560  	case WitnessV0ScriptHashTy:
   561  		// Not including script.  That is handled by the caller.
   562  		return 1
   563  
   564  	case MultiSigTy:
   565  		// Standard multisig has a push a small number for the number
   566  		// of sigs and number of keys.  Check the first push instruction
   567  		// to see how many arguments are expected. typeOfScript already
   568  		// checked this so we know it'll be a small int.  Also, due to
   569  		// the original bitcoind bug where OP_CHECKMULTISIG pops an
   570  		// additional item from the stack, add an extra expected input
   571  		// for the extra push that is required to compensate.
   572  		return asSmallInt(script[0]) + 1
   573  
   574  	case NullDataTy:
   575  		fallthrough
   576  	default:
   577  		return -1
   578  	}
   579  }
   580  
   581  // ScriptInfo houses information about a script pair that is determined by
   582  // CalcScriptInfo.
   583  type ScriptInfo struct {
   584  	// PkScriptClass is the class of the public key script and is equivalent
   585  	// to calling GetScriptClass on it.
   586  	PkScriptClass ScriptClass
   587  
   588  	// NumInputs is the number of inputs provided by the public key script.
   589  	NumInputs int
   590  
   591  	// ExpectedInputs is the number of outputs required by the signature
   592  	// script and any pay-to-script-hash scripts. The number will be -1 if
   593  	// unknown.
   594  	ExpectedInputs int
   595  
   596  	// SigOps is the number of signature operations in the script pair.
   597  	SigOps int
   598  }
   599  
   600  // CalcScriptInfo returns a structure providing data about the provided script
   601  // pair.  It will error if the pair is in someway invalid such that they can not
   602  // be analysed, i.e. if they do not parse or the pkScript is not a push-only
   603  // script
   604  //
   605  // NOTE: This function is only valid for version 0 scripts.  Since the function
   606  // does not accept a script version, the results are undefined for other script
   607  // versions.
   608  //
   609  // DEPRECATED.  This will be removed in the next major version bump.
   610  func CalcScriptInfo(sigScript, pkScript []byte, witness wire.TxWitness,
   611  	bip16, segwit bool) (*ScriptInfo, error) {
   612  
   613  	// Count the number of opcodes in the signature script while also ensuring
   614  	// that successfully parses.  Since there is a check below to ensure the
   615  	// script is push only, this equates to the number of inputs to the public
   616  	// key script.
   617  	const scriptVersion = 0
   618  	var numInputs int
   619  	tokenizer := MakeScriptTokenizer(scriptVersion, sigScript)
   620  	for tokenizer.Next() {
   621  		numInputs++
   622  	}
   623  	if err := tokenizer.Err(); err != nil {
   624  		return nil, err
   625  	}
   626  
   627  	if err := checkScriptParses(scriptVersion, pkScript); err != nil {
   628  		return nil, err
   629  	}
   630  
   631  	// Can't have a signature script that doesn't just push data.
   632  	if !IsPushOnlyScript(sigScript) {
   633  		return nil, scriptError(ErrNotPushOnly,
   634  			"signature script is not push only")
   635  	}
   636  
   637  	si := new(ScriptInfo)
   638  	si.PkScriptClass = typeOfScript(scriptVersion, pkScript)
   639  
   640  	si.ExpectedInputs = expectedInputs(pkScript, si.PkScriptClass)
   641  
   642  	switch {
   643  	// Count sigops taking into account pay-to-script-hash.
   644  	case si.PkScriptClass == ScriptHashTy && bip16 && !segwit:
   645  		// The redeem script is the final data push of the signature script.
   646  		redeemScript := finalOpcodeData(scriptVersion, sigScript)
   647  		reedeemClass := typeOfScript(scriptVersion, redeemScript)
   648  		rsInputs := expectedInputs(redeemScript, reedeemClass)
   649  		if rsInputs == -1 {
   650  			si.ExpectedInputs = -1
   651  		} else {
   652  			si.ExpectedInputs += rsInputs
   653  		}
   654  		si.SigOps = countSigOpsV0(redeemScript, true)
   655  
   656  		// All entries pushed to stack (or are OP_RESERVED and exec
   657  		// will fail).
   658  		si.NumInputs = numInputs
   659  
   660  	// If segwit is active, and this is a regular p2wkh output, then we'll
   661  	// treat the script as a p2pkh output in essence.
   662  	case si.PkScriptClass == WitnessV0PubKeyHashTy && segwit:
   663  
   664  		si.SigOps = GetWitnessSigOpCount(sigScript, pkScript, witness)
   665  		si.NumInputs = len(witness)
   666  
   667  	// We'll attempt to detect the nested p2sh case so we can accurately
   668  	// count the signature operations involved.
   669  	case si.PkScriptClass == ScriptHashTy &&
   670  		IsWitnessProgram(sigScript[1:]) && bip16 && segwit:
   671  
   672  		// Extract the pushed witness program from the sigScript so we
   673  		// can determine the number of expected inputs.
   674  		redeemClass := typeOfScript(scriptVersion, sigScript[1:])
   675  		shInputs := expectedInputs(sigScript[1:], redeemClass)
   676  		if shInputs == -1 {
   677  			si.ExpectedInputs = -1
   678  		} else {
   679  			si.ExpectedInputs += shInputs
   680  		}
   681  
   682  		si.SigOps = GetWitnessSigOpCount(sigScript, pkScript, witness)
   683  
   684  		si.NumInputs = len(witness)
   685  		si.NumInputs += numInputs
   686  
   687  	// If segwit is active, and this is a p2wsh output, then we'll need to
   688  	// examine the witness script to generate accurate script info.
   689  	case si.PkScriptClass == WitnessV0ScriptHashTy && segwit:
   690  		witnessScript := witness[len(witness)-1]
   691  		redeemClass := typeOfScript(scriptVersion, witnessScript)
   692  		shInputs := expectedInputs(witnessScript, redeemClass)
   693  		if shInputs == -1 {
   694  			si.ExpectedInputs = -1
   695  		} else {
   696  			si.ExpectedInputs += shInputs
   697  		}
   698  
   699  		si.SigOps = GetWitnessSigOpCount(sigScript, pkScript, witness)
   700  		si.NumInputs = len(witness)
   701  
   702  	default:
   703  		si.SigOps = countSigOpsV0(pkScript, true)
   704  
   705  		// All entries pushed to stack (or are OP_RESERVED and exec
   706  		// will fail).
   707  		si.NumInputs = numInputs
   708  	}
   709  
   710  	return si, nil
   711  }
   712  
   713  // CalcMultiSigStats returns the number of public keys and signatures from
   714  // a multi-signature transaction script.  The passed script MUST already be
   715  // known to be a multi-signature script.
   716  //
   717  // NOTE: This function is only valid for version 0 scripts.  Since the function
   718  // does not accept a script version, the results are undefined for other script
   719  // versions.
   720  func CalcMultiSigStats(script []byte) (int, int, error) {
   721  	// The public keys are not needed here, so pass false to avoid the extra
   722  	// allocation.
   723  	const scriptVersion = 0
   724  	details := extractMultisigScriptDetails(scriptVersion, script, false)
   725  	if !details.valid {
   726  		str := fmt.Sprintf("script %x is not a multisig script", script)
   727  		return 0, 0, scriptError(ErrNotMultisigScript, str)
   728  	}
   729  
   730  	return details.numPubKeys, details.requiredSigs, nil
   731  }
   732  
   733  // payToPubKeyHashScript creates a new script to pay a transaction
   734  // output to a 20-byte pubkey hash. It is expected that the input is a valid
   735  // hash.
   736  func payToPubKeyHashScript(pubKeyHash []byte) ([]byte, error) {
   737  	return NewScriptBuilder().AddOp(OP_DUP).AddOp(OP_HASH160).
   738  		AddData(pubKeyHash).AddOp(OP_EQUALVERIFY).AddOp(OP_CHECKSIG).
   739  		Script()
   740  }
   741  
   742  // payToWitnessPubKeyHashScript creates a new script to pay to a version 0
   743  // pubkey hash witness program. The passed hash is expected to be valid.
   744  func payToWitnessPubKeyHashScript(pubKeyHash []byte) ([]byte, error) {
   745  	return NewScriptBuilder().AddOp(OP_0).AddData(pubKeyHash).Script()
   746  }
   747  
   748  // payToScriptHashScript creates a new script to pay a transaction output to a
   749  // script hash. It is expected that the input is a valid hash.
   750  func payToScriptHashScript(scriptHash []byte) ([]byte, error) {
   751  	return NewScriptBuilder().AddOp(OP_HASH160).AddData(scriptHash).
   752  		AddOp(OP_EQUAL).Script()
   753  }
   754  
   755  // payToWitnessPubKeyHashScript creates a new script to pay to a version 0
   756  // script hash witness program. The passed hash is expected to be valid.
   757  func payToWitnessScriptHashScript(scriptHash []byte) ([]byte, error) {
   758  	return NewScriptBuilder().AddOp(OP_0).AddData(scriptHash).Script()
   759  }
   760  
   761  // payToPubkeyScript creates a new script to pay a transaction output to a
   762  // public key. It is expected that the input is a valid pubkey.
   763  func payToPubKeyScript(serializedPubKey []byte) ([]byte, error) {
   764  	return NewScriptBuilder().AddData(serializedPubKey).
   765  		AddOp(OP_CHECKSIG).Script()
   766  }
   767  
   768  // PayToAddrScript creates a new script to pay a transaction output to a the
   769  // specified address.
   770  func PayToAddrScript(addr btcutil.Address) ([]byte, error) {
   771  	const nilAddrErrStr = "unable to generate payment script for nil address"
   772  
   773  	switch addr := addr.(type) {
   774  	case *btcutil.AddressPubKeyHash:
   775  		if addr == nil {
   776  			return nil, scriptError(ErrUnsupportedAddress,
   777  				nilAddrErrStr)
   778  		}
   779  		return payToPubKeyHashScript(addr.ScriptAddress())
   780  
   781  	case *btcutil.AddressScriptHash:
   782  		if addr == nil {
   783  			return nil, scriptError(ErrUnsupportedAddress,
   784  				nilAddrErrStr)
   785  		}
   786  		return payToScriptHashScript(addr.ScriptAddress())
   787  
   788  	case *btcutil.AddressPubKey:
   789  		if addr == nil {
   790  			return nil, scriptError(ErrUnsupportedAddress,
   791  				nilAddrErrStr)
   792  		}
   793  		return payToPubKeyScript(addr.ScriptAddress())
   794  
   795  	case *btcutil.AddressWitnessPubKeyHash:
   796  		if addr == nil {
   797  			return nil, scriptError(ErrUnsupportedAddress,
   798  				nilAddrErrStr)
   799  		}
   800  		return payToWitnessPubKeyHashScript(addr.ScriptAddress())
   801  	case *btcutil.AddressWitnessScriptHash:
   802  		if addr == nil {
   803  			return nil, scriptError(ErrUnsupportedAddress,
   804  				nilAddrErrStr)
   805  		}
   806  		return payToWitnessScriptHashScript(addr.ScriptAddress())
   807  	}
   808  
   809  	str := fmt.Sprintf("unable to generate payment script for unsupported "+
   810  		"address type %T", addr)
   811  	return nil, scriptError(ErrUnsupportedAddress, str)
   812  }
   813  
   814  // NullDataScript creates a provably-prunable script containing OP_RETURN
   815  // followed by the passed data.  An Error with the error code ErrTooMuchNullData
   816  // will be returned if the length of the passed data exceeds MaxDataCarrierSize.
   817  func NullDataScript(data []byte) ([]byte, error) {
   818  	if len(data) > MaxDataCarrierSize {
   819  		str := fmt.Sprintf("data size %d is larger than max "+
   820  			"allowed size %d", len(data), MaxDataCarrierSize)
   821  		return nil, scriptError(ErrTooMuchNullData, str)
   822  	}
   823  
   824  	return NewScriptBuilder().AddOp(OP_RETURN).AddData(data).Script()
   825  }
   826  
   827  // MultiSigScript returns a valid script for a multisignature redemption where
   828  // nrequired of the keys in pubkeys are required to have signed the transaction
   829  // for success.  An Error with the error code ErrTooManyRequiredSigs will be
   830  // returned if nrequired is larger than the number of keys provided.
   831  func MultiSigScript(pubkeys []*btcutil.AddressPubKey, nrequired int) ([]byte, error) {
   832  	if len(pubkeys) < nrequired {
   833  		str := fmt.Sprintf("unable to generate multisig script with "+
   834  			"%d required signatures when there are only %d public "+
   835  			"keys available", nrequired, len(pubkeys))
   836  		return nil, scriptError(ErrTooManyRequiredSigs, str)
   837  	}
   838  
   839  	builder := NewScriptBuilder().AddInt64(int64(nrequired))
   840  	for _, key := range pubkeys {
   841  		builder.AddData(key.ScriptAddress())
   842  	}
   843  	builder.AddInt64(int64(len(pubkeys)))
   844  	builder.AddOp(OP_CHECKMULTISIG)
   845  
   846  	return builder.Script()
   847  }
   848  
   849  // PushedData returns an array of byte slices containing any pushed data found
   850  // in the passed script.  This includes OP_0, but not OP_1 - OP_16.
   851  //
   852  // NOTE: This function is only valid for version 0 scripts.  Since the function
   853  // does not accept a script version, the results are undefined for other script
   854  // versions.
   855  func PushedData(script []byte) ([][]byte, error) {
   856  	const scriptVersion = 0
   857  
   858  	var data [][]byte
   859  	tokenizer := MakeScriptTokenizer(scriptVersion, script)
   860  	for tokenizer.Next() {
   861  		if tokenizer.Data() != nil {
   862  			data = append(data, tokenizer.Data())
   863  		} else if tokenizer.Opcode() == OP_0 {
   864  			data = append(data, nil)
   865  		}
   866  	}
   867  	if err := tokenizer.Err(); err != nil {
   868  		return nil, err
   869  	}
   870  	return data, nil
   871  }
   872  
   873  // pubKeyHashToAddrs is a convenience function to attempt to convert the
   874  // passed hash to a pay-to-pubkey-hash address housed within an address
   875  // slice.  It is used to consolidate common code.
   876  func pubKeyHashToAddrs(hash []byte, params *chaincfg.Params) []btcutil.Address {
   877  	// Skip the pubkey hash if it's invalid for some reason.
   878  	var addrs []btcutil.Address
   879  	addr, err := btcutil.NewAddressPubKeyHash(hash, params)
   880  	if err == nil {
   881  		addrs = append(addrs, addr)
   882  	}
   883  	return addrs
   884  }
   885  
   886  // scriptHashToAddrs is a convenience function to attempt to convert the passed
   887  // hash to a pay-to-script-hash address housed within an address slice.  It is
   888  // used to consolidate common code.
   889  func scriptHashToAddrs(hash []byte, params *chaincfg.Params) []btcutil.Address {
   890  	// Skip the hash if it's invalid for some reason.
   891  	var addrs []btcutil.Address
   892  	addr, err := btcutil.NewAddressScriptHashFromHash(hash, params)
   893  	if err == nil {
   894  		addrs = append(addrs, addr)
   895  	}
   896  	return addrs
   897  }
   898  
   899  // ExtractPkScriptAddrs returns the type of script, addresses and required
   900  // signatures associated with the passed PkScript.  Note that it only works for
   901  // 'standard' transaction script types.  Any data such as public keys which are
   902  // invalid are omitted from the results.
   903  //
   904  // NOTE: This function only attempts to identify version 0 scripts.  The return
   905  // value will indicate a nonstandard script type for other script versions along
   906  // with an invalid script version error.
   907  func ExtractPkScriptAddrs(pkScript []byte, chainParams *chaincfg.Params) (ScriptClass, []btcutil.Address, int, error) {
   908  
   909  	pkScript = StripClaimScriptPrefix(pkScript)
   910  
   911  	// Check for pay-to-pubkey-hash script.
   912  	if hash := extractPubKeyHash(pkScript); hash != nil {
   913  		return PubKeyHashTy, pubKeyHashToAddrs(hash, chainParams), 1, nil
   914  	}
   915  
   916  	// Check for pay-to-script-hash.
   917  	if hash := extractScriptHash(pkScript); hash != nil {
   918  		return ScriptHashTy, scriptHashToAddrs(hash, chainParams), 1, nil
   919  	}
   920  
   921  	// Check for pay-to-pubkey script.
   922  	if data := extractPubKey(pkScript); data != nil {
   923  		var addrs []btcutil.Address
   924  		addr, err := btcutil.NewAddressPubKey(data, chainParams)
   925  		if err == nil {
   926  			addrs = append(addrs, addr)
   927  		}
   928  		return PubKeyTy, addrs, 1, nil
   929  	}
   930  
   931  	// Check for multi-signature script.
   932  	const scriptVersion = 0
   933  	details := extractMultisigScriptDetails(scriptVersion, pkScript, true)
   934  	if details.valid {
   935  		// Convert the public keys while skipping any that are invalid.
   936  		addrs := make([]btcutil.Address, 0, len(details.pubKeys))
   937  		for _, pubkey := range details.pubKeys {
   938  			addr, err := btcutil.NewAddressPubKey(pubkey, chainParams)
   939  			if err == nil {
   940  				addrs = append(addrs, addr)
   941  			}
   942  		}
   943  		return MultiSigTy, addrs, details.requiredSigs, nil
   944  	}
   945  
   946  	// Check for null data script.
   947  	if isNullDataScript(scriptVersion, pkScript) {
   948  		// Null data transactions have no addresses or required signatures.
   949  		return NullDataTy, nil, 0, nil
   950  	}
   951  
   952  	if hash := extractWitnessPubKeyHash(pkScript); hash != nil {
   953  		var addrs []btcutil.Address
   954  		addr, err := btcutil.NewAddressWitnessPubKeyHash(hash, chainParams)
   955  		if err == nil {
   956  			addrs = append(addrs, addr)
   957  		}
   958  		return WitnessV0PubKeyHashTy, addrs, 1, nil
   959  	}
   960  
   961  	if hash := extractWitnessScriptHash(pkScript); hash != nil {
   962  		var addrs []btcutil.Address
   963  		addr, err := btcutil.NewAddressWitnessScriptHash(hash, chainParams)
   964  		if err == nil {
   965  			addrs = append(addrs, addr)
   966  		}
   967  		return WitnessV0ScriptHashTy, addrs, 1, nil
   968  	}
   969  
   970  	// If none of the above passed, then the address must be non-standard.
   971  	return NonStandardTy, nil, 0, nil
   972  }
   973  
   974  // AtomicSwapDataPushes houses the data pushes found in atomic swap contracts.
   975  type AtomicSwapDataPushes struct {
   976  	RecipientHash160 [20]byte
   977  	RefundHash160    [20]byte
   978  	SecretHash       [32]byte
   979  	SecretSize       int64
   980  	LockTime         int64
   981  }
   982  
   983  // ExtractAtomicSwapDataPushes returns the data pushes from an atomic swap
   984  // contract.  If the script is not an atomic swap contract,
   985  // ExtractAtomicSwapDataPushes returns (nil, nil).  Non-nil errors are returned
   986  // for unparsable scripts.
   987  //
   988  // NOTE: Atomic swaps are not considered standard script types by the dcrd
   989  // mempool policy and should be used with P2SH.  The atomic swap format is also
   990  // expected to change to use a more secure hash function in the future.
   991  //
   992  // This function is only defined in the txscript package due to API limitations
   993  // which prevent callers using txscript to parse nonstandard scripts.
   994  //
   995  // DEPRECATED.  This will be removed in the next major version bump.  The error
   996  // should also likely be removed if the code is reimplemented by any callers
   997  // since any errors result in a nil result anyway.
   998  func ExtractAtomicSwapDataPushes(version uint16, pkScript []byte) (*AtomicSwapDataPushes, error) {
   999  	// An atomic swap is of the form:
  1000  	//  IF
  1001  	//   SIZE <secret size> EQUALVERIFY SHA256 <32-byte secret> EQUALVERIFY DUP
  1002  	//   HASH160 <20-byte recipient hash>
  1003  	//  ELSE
  1004  	//   <locktime> CHECKLOCKTIMEVERIFY DROP DUP HASH160 <20-byte refund hash>
  1005  	//  ENDIF
  1006  	//  EQUALVERIFY CHECKSIG
  1007  	type templateMatch struct {
  1008  		expectCanonicalInt bool
  1009  		maxIntBytes        int
  1010  		opcode             byte
  1011  		extractedInt       int64
  1012  		extractedData      []byte
  1013  	}
  1014  	var template = [20]templateMatch{
  1015  		{opcode: OP_IF},
  1016  		{opcode: OP_SIZE},
  1017  		{expectCanonicalInt: true, maxIntBytes: maxScriptNumLen},
  1018  		{opcode: OP_EQUALVERIFY},
  1019  		{opcode: OP_SHA256},
  1020  		{opcode: OP_DATA_32},
  1021  		{opcode: OP_EQUALVERIFY},
  1022  		{opcode: OP_DUP},
  1023  		{opcode: OP_HASH160},
  1024  		{opcode: OP_DATA_20},
  1025  		{opcode: OP_ELSE},
  1026  		{expectCanonicalInt: true, maxIntBytes: cltvMaxScriptNumLen},
  1027  		{opcode: OP_CHECKLOCKTIMEVERIFY},
  1028  		{opcode: OP_DROP},
  1029  		{opcode: OP_DUP},
  1030  		{opcode: OP_HASH160},
  1031  		{opcode: OP_DATA_20},
  1032  		{opcode: OP_ENDIF},
  1033  		{opcode: OP_EQUALVERIFY},
  1034  		{opcode: OP_CHECKSIG},
  1035  	}
  1036  
  1037  	var templateOffset int
  1038  	tokenizer := MakeScriptTokenizer(version, pkScript)
  1039  	for tokenizer.Next() {
  1040  		// Not an atomic swap script if it has more opcodes than expected in the
  1041  		// template.
  1042  		if templateOffset >= len(template) {
  1043  			return nil, nil
  1044  		}
  1045  
  1046  		op := tokenizer.Opcode()
  1047  		data := tokenizer.Data()
  1048  		tplEntry := &template[templateOffset]
  1049  		if tplEntry.expectCanonicalInt {
  1050  			switch {
  1051  			case data != nil:
  1052  				val, err := makeScriptNum(data, true, tplEntry.maxIntBytes)
  1053  				if err != nil {
  1054  					return nil, err
  1055  				}
  1056  				tplEntry.extractedInt = int64(val)
  1057  
  1058  			case isSmallInt(op):
  1059  				tplEntry.extractedInt = int64(asSmallInt(op))
  1060  
  1061  			// Not an atomic swap script if the opcode does not push an int.
  1062  			default:
  1063  				return nil, nil
  1064  			}
  1065  		} else {
  1066  			if op != tplEntry.opcode {
  1067  				return nil, nil
  1068  			}
  1069  
  1070  			tplEntry.extractedData = data
  1071  		}
  1072  
  1073  		templateOffset++
  1074  	}
  1075  	if err := tokenizer.Err(); err != nil {
  1076  		return nil, err
  1077  	}
  1078  	if !tokenizer.Done() || templateOffset != len(template) {
  1079  		return nil, nil
  1080  	}
  1081  
  1082  	// At this point, the script appears to be an atomic swap, so populate and
  1083  	// return the extacted data.
  1084  	pushes := AtomicSwapDataPushes{
  1085  		SecretSize: template[2].extractedInt,
  1086  		LockTime:   template[11].extractedInt,
  1087  	}
  1088  	copy(pushes.SecretHash[:], template[5].extractedData)
  1089  	copy(pushes.RecipientHash160[:], template[9].extractedData)
  1090  	copy(pushes.RefundHash160[:], template[16].extractedData)
  1091  	return &pushes, nil
  1092  }