github.com/mit-dci/lit@v0.0.0-20221102210550-8c3d3b49f2ce/btcutil/txscript/script.go (about)

     1  // Copyright (c) 2013-2016 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  	"bytes"
     9  	"encoding/binary"
    10  	"fmt"
    11  	"time"
    12  
    13  	"github.com/mit-dci/lit/btcutil/chaincfg/chainhash"
    14  	"github.com/mit-dci/lit/logging"
    15  	"github.com/mit-dci/lit/wire"
    16  )
    17  
    18  // Bip16Activation is the timestamp where BIP0016 is valid to use in the
    19  // blockchain.  To be used to determine if BIP0016 should be called for or not.
    20  // This timestamp corresponds to Sun Apr 1 00:00:00 UTC 2012.
    21  var Bip16Activation = time.Unix(1333238400, 0)
    22  
    23  // SigHashType represents hash type bits at the end of a signature.
    24  type SigHashType uint32
    25  
    26  // Hash type bits from the end of a signature.
    27  const (
    28  	SigHashOld          SigHashType = 0x0
    29  	SigHashAll          SigHashType = 0x1
    30  	SigHashNone         SigHashType = 0x2
    31  	SigHashSingle       SigHashType = 0x3
    32  	SigHashForkID       SigHashType = 0x40
    33  	SigHashAnyOneCanPay SigHashType = 0x80
    34  
    35  	// sigHashMask defines the number of bits of the hash type which is used
    36  	// to identify which outputs are signed.
    37  	sigHashMask = 0x1f
    38  )
    39  
    40  // These are the constants specified for maximums in individual scripts.
    41  const (
    42  	MaxOpsPerScript       = 201 // Max number of non-push operations.
    43  	MaxPubKeysPerMultiSig = 20  // Multisig can't have more sigs than this.
    44  	MaxScriptElementSize  = 520 // Max bytes pushable to the stack.
    45  )
    46  
    47  // isSmallInt returns whether or not the opcode is considered a small integer,
    48  // which is an OP_0, or OP_1 through OP_16.
    49  func isSmallInt(op *opcode) bool {
    50  	if op.value == OP_0 || (op.value >= OP_1 && op.value <= OP_16) {
    51  		return true
    52  	}
    53  	return false
    54  }
    55  
    56  // isScriptHash returns true if the script passed is a pay-to-script-hash
    57  // transaction, false otherwise.
    58  func isScriptHash(pops []parsedOpcode) bool {
    59  	return len(pops) == 3 &&
    60  		pops[0].opcode.value == OP_HASH160 &&
    61  		pops[1].opcode.value == OP_DATA_20 &&
    62  		pops[2].opcode.value == OP_EQUAL
    63  }
    64  
    65  // IsPayToScriptHash returns true if the script is in the standard
    66  // pay-to-script-hash (P2SH) format, false otherwise.
    67  func IsPayToScriptHash(script []byte) bool {
    68  	pops, err := ParseScript(script)
    69  	if err != nil {
    70  		return false
    71  	}
    72  	return isScriptHash(pops)
    73  }
    74  
    75  // isWitnessScriptHash returns true if the passed script is a
    76  // pay-to-witness-script-hash transaction, false otherwise.
    77  func isWitnessScriptHash(pops []parsedOpcode) bool {
    78  	return len(pops) == 2 &&
    79  		pops[0].opcode.value == OP_0 &&
    80  		pops[1].opcode.value == OP_DATA_32
    81  }
    82  
    83  // IsPayToWitnessScriptHash returns true if the is in the standard
    84  // pay-to-witness-script-hash (P2WSH) format, false otherwise.
    85  func IsPayToWitnessScriptHash(script []byte) bool {
    86  	pops, err := ParseScript(script)
    87  	if err != nil {
    88  		return false
    89  	}
    90  	return isWitnessScriptHash(pops)
    91  }
    92  
    93  // IsPayToWitnessPubKeyHash returns true if the is in the standard
    94  // pay-to-witness-pubkey-hash (P2WKH) format, false otherwise.
    95  func IsPayToWitnessPubKeyHash(script []byte) bool {
    96  	pops, err := ParseScript(script)
    97  	if err != nil {
    98  		return false
    99  	}
   100  	return isWitnessPubKeyHash(pops)
   101  }
   102  
   103  // isWitnessPubKeyHash returns true if the passed script is a
   104  // pay-to-witness-pubkey-hash, and false otherwise.
   105  func isWitnessPubKeyHash(pops []parsedOpcode) bool {
   106  	return len(pops) == 2 &&
   107  		pops[0].opcode.value == OP_0 &&
   108  		pops[1].opcode.value == OP_DATA_20
   109  }
   110  
   111  // IsWitnessProgram returns true if the passed script is a valid witness
   112  // program. A witness program must be a small integer (from 0-16), followed by
   113  // 2-40 bytes of pushed data.
   114  func IsWitnessProgram(script []byte) bool {
   115  	// The length of the script must be between 4 and 42 byte. The smallest
   116  	// program is the witness version, followed by a data push of 2 bytes.
   117  	// The largest allowed witness program has a data push of 40-bytes.
   118  	if len(script) < 4 || len(script) > 42 {
   119  		return false
   120  	}
   121  
   122  	pops, err := ParseScript(script)
   123  	if err != nil {
   124  		return false
   125  	}
   126  
   127  	return isWitnessProgram(pops)
   128  }
   129  
   130  // isWitnessProgram returns true if the passed script is a witness program, and
   131  // false otherwise.
   132  func isWitnessProgram(pops []parsedOpcode) bool {
   133  	return len(pops) == 2 &&
   134  		isSmallInt(pops[0].opcode) &&
   135  		canonicalPush(pops[1]) &&
   136  		(len(pops[1].data) >= 2 && len(pops[1].data) <= 40)
   137  }
   138  
   139  // ExtractWitnessProgramInfo attempts to extract the witness program version,
   140  // as well as the witness program itself from the passed script.
   141  func ExtractWitnessProgramInfo(script []byte) (int, []byte, error) {
   142  	var witnessVersion int
   143  	var witnessProgram []byte
   144  
   145  	pops, err := ParseScript(script)
   146  	if err != nil {
   147  		return witnessVersion, witnessProgram, err
   148  	}
   149  
   150  	witnessVersion = asSmallInt(pops[0].opcode)
   151  	witnessProgram = pops[1].data
   152  
   153  	return witnessVersion, witnessProgram, nil
   154  }
   155  
   156  // isPushOnly returns true if the script only pushes data, false otherwise.
   157  func isPushOnly(pops []parsedOpcode) bool {
   158  	// NOTE: This function does NOT verify opcodes directly since it is
   159  	// internal and is only called with parsed opcodes for scripts that did
   160  	// not have any parse errors.  Thus, consensus is properly maintained.
   161  
   162  	for _, pop := range pops {
   163  		// All opcodes up to OP_16 are data push instructions.
   164  		// NOTE: This does consider OP_RESERVED to be a data push
   165  		// instruction, but execution of OP_RESERVED will fail anyways
   166  		// and matches the behavior required by consensus.
   167  		if pop.opcode.value > OP_16 {
   168  			return false
   169  		}
   170  	}
   171  	return true
   172  }
   173  
   174  // IsPushOnlyScript returns whether or not the passed script only pushes data.
   175  //
   176  // False will be returned when the script does not parse.
   177  func IsPushOnlyScript(script []byte) bool {
   178  	pops, err := ParseScript(script)
   179  	if err != nil {
   180  		return false
   181  	}
   182  	return isPushOnly(pops)
   183  }
   184  
   185  // parseScriptTemplate is the same as parseScript but allows the passing of the
   186  // template list for testing purposes.  When there are parse errors, it returns
   187  // the list of parsed opcodes up to the point of failure along with the error.
   188  func parseScriptTemplate(script []byte, opcodes *[256]opcode) ([]parsedOpcode, error) {
   189  	retScript := make([]parsedOpcode, 0, len(script))
   190  	for i := 0; i < len(script); {
   191  		instr := script[i]
   192  		op := &opcodes[instr]
   193  		pop := parsedOpcode{opcode: op}
   194  
   195  		// Parse data out of instruction.
   196  		switch {
   197  		// No additional data.  Note that some of the opcodes, notably
   198  		// OP_1NEGATE, OP_0, and OP_[1-16] represent the data
   199  		// themselves.
   200  		case op.length == 1:
   201  			i++
   202  
   203  		// Data pushes of specific lengths -- OP_DATA_[1-75].
   204  		case op.length > 1:
   205  			if len(script[i:]) < op.length {
   206  				return retScript, ErrStackShortScript
   207  			}
   208  
   209  			// Slice out the data.
   210  			pop.data = script[i+1 : i+op.length]
   211  			i += op.length
   212  
   213  		// Data pushes with parsed lengths -- OP_PUSHDATAP{1,2,4}.
   214  		case op.length < 0:
   215  			var l uint
   216  			off := i + 1
   217  
   218  			if len(script[off:]) < -op.length {
   219  				return retScript, ErrStackShortScript
   220  			}
   221  
   222  			// Next -length bytes are little endian length of data.
   223  			switch op.length {
   224  			case -1:
   225  				l = uint(script[off])
   226  			case -2:
   227  				l = ((uint(script[off+1]) << 8) |
   228  					uint(script[off]))
   229  			case -4:
   230  				l = ((uint(script[off+3]) << 24) |
   231  					(uint(script[off+2]) << 16) |
   232  					(uint(script[off+1]) << 8) |
   233  					uint(script[off]))
   234  			default:
   235  				return retScript,
   236  					fmt.Errorf("invalid opcode length %d",
   237  						op.length)
   238  			}
   239  
   240  			// Move offset to beginning of the data.
   241  			off += -op.length
   242  
   243  			// Disallow entries that do not fit script or were
   244  			// sign extended.
   245  			if int(l) > len(script[off:]) || int(l) < 0 {
   246  				return retScript, ErrStackShortScript
   247  			}
   248  
   249  			pop.data = script[off : off+int(l)]
   250  			i += 1 - op.length + int(l)
   251  		}
   252  
   253  		retScript = append(retScript, pop)
   254  	}
   255  
   256  	return retScript, nil
   257  }
   258  
   259  // parseScript preparses the script in bytes into a list of parsedOpcodes while
   260  // applying a number of sanity checks.
   261  func ParseScript(script []byte) ([]parsedOpcode, error) {
   262  	return parseScriptTemplate(script, &opcodeArray)
   263  }
   264  
   265  // unparseScript reversed the action of parseScript and returns the
   266  // parsedOpcodes as a list of bytes
   267  func unparseScript(pops []parsedOpcode) ([]byte, error) {
   268  	script := make([]byte, 0, len(pops))
   269  	for _, pop := range pops {
   270  		b, err := pop.bytes()
   271  		if err != nil {
   272  			return nil, err
   273  		}
   274  		script = append(script, b...)
   275  	}
   276  	return script, nil
   277  }
   278  
   279  // DisasmString formats a disassembled script for one line printing.  When the
   280  // script fails to parse, the returned string will contain the disassembled
   281  // script up to the point the failure occurred along with the string '[error]'
   282  // appended.  In addition, the reason the script failed to parse is returned
   283  // if the caller wants more information about the failure.
   284  func DisasmString(buf []byte) (string, error) {
   285  	var disbuf bytes.Buffer
   286  	opcodes, err := ParseScript(buf)
   287  	for _, pop := range opcodes {
   288  		disbuf.WriteString(pop.print(true))
   289  		disbuf.WriteByte(' ')
   290  	}
   291  	if disbuf.Len() > 0 {
   292  		disbuf.Truncate(disbuf.Len() - 1)
   293  	}
   294  	if err != nil {
   295  		disbuf.WriteString("[error]")
   296  	}
   297  	return disbuf.String(), err
   298  }
   299  
   300  // removeOpcode will remove any opcode matching ``opcode'' from the opcode
   301  // stream in pkscript
   302  func removeOpcode(pkscript []parsedOpcode, opcode byte) []parsedOpcode {
   303  	retScript := make([]parsedOpcode, 0, len(pkscript))
   304  	for _, pop := range pkscript {
   305  		if pop.opcode.value != opcode {
   306  			retScript = append(retScript, pop)
   307  		}
   308  	}
   309  	return retScript
   310  }
   311  
   312  // canonicalPush returns true if the object is either not a push instruction
   313  // or the push instruction contained wherein is matches the canonical form
   314  // or using the smallest instruction to do the job. False otherwise.
   315  func canonicalPush(pop parsedOpcode) bool {
   316  	opcode := pop.opcode.value
   317  	data := pop.data
   318  	dataLen := len(pop.data)
   319  	if opcode > OP_16 {
   320  		return true
   321  	}
   322  
   323  	if opcode < OP_PUSHDATA1 && opcode > OP_0 && (dataLen == 1 && data[0] <= 16) {
   324  		return false
   325  	}
   326  	if opcode == OP_PUSHDATA1 && dataLen < OP_PUSHDATA1 {
   327  		return false
   328  	}
   329  	if opcode == OP_PUSHDATA2 && dataLen <= 0xff {
   330  		return false
   331  	}
   332  	if opcode == OP_PUSHDATA4 && dataLen <= 0xffff {
   333  		return false
   334  	}
   335  	return true
   336  }
   337  
   338  // removeOpcodeByData will return the script minus any opcodes that would push
   339  // the passed data to the stack.
   340  func removeOpcodeByData(pkscript []parsedOpcode, data []byte) []parsedOpcode {
   341  	retScript := make([]parsedOpcode, 0, len(pkscript))
   342  	for _, pop := range pkscript {
   343  		if !canonicalPush(pop) || !bytes.Contains(pop.data, data) {
   344  			retScript = append(retScript, pop)
   345  		}
   346  	}
   347  	return retScript
   348  
   349  }
   350  
   351  // calcHashPrevOuts calculates a single hash of all the previous outputs
   352  // (txid:index) referenced within the passed transaction. This calculated hash
   353  // can be re-used when validating all inputs spending segwit outputs, with a
   354  // signature hash type of SigHashAll. This allows validation to re-use previous
   355  // hashing computation, reducing the complexity of validating SigHashAll inputs
   356  // from  O(N^2) to O(N).
   357  func calcHashPrevOuts(tx *wire.MsgTx) chainhash.Hash {
   358  	var b bytes.Buffer
   359  	for _, in := range tx.TxIn {
   360  		// First write out the 32-byte transaction ID one of whose
   361  		// outputs are being referenced by this input.
   362  		b.Write(in.PreviousOutPoint.Hash[:])
   363  
   364  		// Next, we'll encode the index of the referenced output as a
   365  		// little endian integer.
   366  		var buf [4]byte
   367  		binary.LittleEndian.PutUint32(buf[:], in.PreviousOutPoint.Index)
   368  		b.Write(buf[:])
   369  	}
   370  
   371  	return chainhash.DoubleHashH(b.Bytes())
   372  }
   373  
   374  // calcHashSequence computes an aggregated hash of each of the sequence numbers
   375  // within the inputs of the passed transaction. This single hash can be re-used
   376  // when validating all inputs spending segwit outputs, which include signatures
   377  // using the SigHashAll sighash type. This allows validation to re-use previous
   378  // hashing computation, reducing the complexity of validating SigHashAll inputs
   379  // from O(N^2) to O(N).
   380  func calcHashSequence(tx *wire.MsgTx) chainhash.Hash {
   381  	var b bytes.Buffer
   382  	for _, in := range tx.TxIn {
   383  		var buf [4]byte
   384  		binary.LittleEndian.PutUint32(buf[:], in.Sequence)
   385  		b.Write(buf[:])
   386  	}
   387  
   388  	return chainhash.DoubleHashH(b.Bytes())
   389  }
   390  
   391  // calcHashOutputs computes a hash digest of all outputs created by the
   392  // transaction encoded using the wire format. This single hash can be re-used
   393  // when validating all inputs spending witness programs, which include
   394  // signatures using the SigHashAll sighash type. This allows computation to be
   395  // cached, reducing the total hashing complexity from O(N^2) to O(N).
   396  func calcHashOutputs(tx *wire.MsgTx) chainhash.Hash {
   397  	var b bytes.Buffer
   398  	for _, out := range tx.TxOut {
   399  		wire.WriteTxOut(&b, 0, 0, out)
   400  	}
   401  
   402  	return chainhash.DoubleHashH(b.Bytes())
   403  }
   404  
   405  // calcWitnessSignatureHash computes the sighash digest of a transaction's
   406  // segwit input using the new, optimized digest calculation algorithm defined
   407  // in BIP0143: https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki.
   408  // This function makes use of pre-calculated sighash fragments stored within
   409  // the passed HashCache to eliminate duplicate hashing computations when
   410  // calculating the final digest, reducing the complexity from O(N^2) to O(N).
   411  // Additionally, signatures now cover the input value of the referenced unspent
   412  // output. This allows offline, or hardware wallets to compute the exact amount
   413  // being spent, in addition to the final transaction fee. In the case the
   414  // wallet if fed an invalid input amount, the real sighash will differ causing
   415  // the produced signature to be invalid.
   416  func CalcWitnessSignatureHash(subScript []parsedOpcode, sigHashes *TxSigHashes,
   417  	hashType SigHashType, tx *wire.MsgTx, idx int, amt int64) []byte {
   418  
   419  	// As a sanity check, ensure the passed input index for the transaction
   420  	// is valid.
   421  	if idx > len(tx.TxIn)-1 {
   422  		logging.Errorf("calcWitnessSignatureHash error: idx %d but %d txins",
   423  			idx, len(tx.TxIn))
   424  		return nil
   425  	}
   426  
   427  	// We'll utilize this buffer throughout to incrementally calculate
   428  	// the signature hash for this transaction.
   429  	var sigHash bytes.Buffer
   430  
   431  	// First write out, then encode the transaction's version number.
   432  	var bVersion [4]byte
   433  	binary.LittleEndian.PutUint32(bVersion[:], uint32(tx.Version))
   434  	sigHash.Write(bVersion[:])
   435  
   436  	// Next write out the possibly pre-calculated hashes for the sequence
   437  	// numbers of all inputs, and the hashes of the previous outs for all
   438  	// outputs.
   439  	var zeroHash chainhash.Hash
   440  
   441  	// If anyone can pay isn't active, then we can use the cached
   442  	// hashPrevOuts, otherwise we just write zeroes for the prev outs.
   443  	if hashType&SigHashAnyOneCanPay == 0 {
   444  		sigHash.Write(sigHashes.HashPrevOuts[:])
   445  	} else {
   446  		sigHash.Write(zeroHash[:])
   447  	}
   448  
   449  	// If the sighash isn't anyone can pay, single, or none, the use the
   450  	// cached hash sequences, otherwise write all zeroes for the
   451  	// hashSequence.
   452  	if hashType&SigHashAnyOneCanPay == 0 &&
   453  		hashType&sigHashMask != SigHashSingle &&
   454  		hashType&sigHashMask != SigHashNone {
   455  		sigHash.Write(sigHashes.HashSequence[:])
   456  	} else {
   457  		sigHash.Write(zeroHash[:])
   458  	}
   459  
   460  	// Next, write the outpoint being spent.
   461  	sigHash.Write(tx.TxIn[idx].PreviousOutPoint.Hash[:])
   462  	var bIndex [4]byte
   463  	binary.LittleEndian.PutUint32(bIndex[:], tx.TxIn[idx].PreviousOutPoint.Index)
   464  	sigHash.Write(bIndex[:])
   465  
   466  	rawScript, _ := unparseScript(subScript)
   467  
   468  	if isWitnessPubKeyHash(subScript) {
   469  		// The script code for a p2wkh is a length prefix varint for
   470  		// the next 25 bytes, followed by a re-creation of the original
   471  		// p2pkh pk script.
   472  		sigHash.Write([]byte{0x19})
   473  		sigHash.Write([]byte{OP_DUP})
   474  		sigHash.Write([]byte{OP_HASH160})
   475  		sigHash.Write([]byte{OP_DATA_20})
   476  		sigHash.Write(rawScript[2:22])
   477  		sigHash.Write([]byte{OP_EQUALVERIFY})
   478  		sigHash.Write([]byte{OP_CHECKSIG})
   479  	} else {
   480  		// For p2wsh outputs, and future outputs, the script code is the
   481  		// original script, with all code separators removed, serialized
   482  		// with a var int length prefix.
   483  		wire.WriteVarBytes(&sigHash, 0, rawScript)
   484  	}
   485  
   486  	// Next, add the input amount, and sequence number of the input being
   487  	// signed.
   488  	var bAmount [8]byte
   489  	binary.LittleEndian.PutUint64(bAmount[:], uint64(amt))
   490  	sigHash.Write(bAmount[:])
   491  	var bSequence [4]byte
   492  	binary.LittleEndian.PutUint32(bSequence[:], tx.TxIn[idx].Sequence)
   493  	sigHash.Write(bSequence[:])
   494  
   495  	// If the current signature mode isn't single, or none, then we can
   496  	// re-use the pre-generated hashoutputs sighash fragment. Otherwise,
   497  	// we'll serialize and add only the target output index to the signature
   498  	// pre-image.
   499  	if hashType&SigHashSingle != SigHashSingle &&
   500  		hashType&SigHashNone != SigHashNone {
   501  		sigHash.Write(sigHashes.HashOutputs[:])
   502  	} else if hashType&sigHashMask == SigHashSingle && idx < len(tx.TxOut) {
   503  		var b bytes.Buffer
   504  		wire.WriteTxOut(&b, 0, 0, tx.TxOut[idx])
   505  		sigHash.Write(chainhash.DoubleHashB(b.Bytes()))
   506  	} else {
   507  		sigHash.Write(zeroHash[:])
   508  	}
   509  
   510  	// Finally, write out the transaction's locktime, and the sig hash
   511  	// type.
   512  	var bLockTime [4]byte
   513  	binary.LittleEndian.PutUint32(bLockTime[:], tx.LockTime)
   514  	sigHash.Write(bLockTime[:])
   515  	var bHashType [4]byte
   516  	binary.LittleEndian.PutUint32(bHashType[:], uint32(hashType))
   517  	sigHash.Write(bHashType[:])
   518  
   519  	return chainhash.DoubleHashB(sigHash.Bytes())
   520  }
   521  
   522  // calcSignatureHash will, given a script and hash type for the current script
   523  // engine instance, calculate the signature hash to be used for signing and
   524  // verification.
   525  func calcSignatureHash(script []parsedOpcode, hashType SigHashType, tx *wire.MsgTx, idx int) []byte {
   526  	// The SigHashSingle signature type signs only the corresponding input
   527  	// and output (the output with the same index number as the input).
   528  	//
   529  	// Since transactions can have more inputs than outputs, this means it
   530  	// is improper to use SigHashSingle on input indices that don't have a
   531  	// corresponding output.
   532  	//
   533  	// A bug in the original Satoshi client implementation means specifying
   534  	// an index that is out of range results in a signature hash of 1 (as a
   535  	// uint256 little endian).  The original intent appeared to be to
   536  	// indicate failure, but unfortunately, it was never checked and thus is
   537  	// treated as the actual signature hash.  This buggy behavior is now
   538  	// part of the consensus and a hard fork would be required to fix it.
   539  	//
   540  	// Due to this, care must be taken by software that creates transactions
   541  	// which make use of SigHashSingle because it can lead to an extremely
   542  	// dangerous situation where the invalid inputs will end up signing a
   543  	// hash of 1.  This in turn presents an opportunity for attackers to
   544  	// cleverly construct transactions which can steal those coins provided
   545  	// they can reuse signatures.
   546  	if hashType&sigHashMask == SigHashSingle && idx >= len(tx.TxOut) {
   547  		var hash chainhash.Hash
   548  		hash[0] = 0x01
   549  		return hash[:]
   550  	}
   551  
   552  	// Remove all instances of OP_CODESEPARATOR from the script.
   553  	script = removeOpcode(script, OP_CODESEPARATOR)
   554  
   555  	// Make a deep copy of the transaction, zeroing out the script for all
   556  	// inputs that are not currently being processed.
   557  	txCopy := tx.Copy()
   558  	for i := range txCopy.TxIn {
   559  		if i == idx {
   560  			// UnparseScript cannot fail here because removeOpcode
   561  			// above only returns a valid script.
   562  			sigScript, _ := unparseScript(script)
   563  			txCopy.TxIn[idx].SignatureScript = sigScript
   564  		} else {
   565  			txCopy.TxIn[i].SignatureScript = nil
   566  		}
   567  	}
   568  
   569  	switch hashType & sigHashMask {
   570  	case SigHashNone:
   571  		txCopy.TxOut = txCopy.TxOut[0:0] // Empty slice.
   572  		for i := range txCopy.TxIn {
   573  			if i != idx {
   574  				txCopy.TxIn[i].Sequence = 0
   575  			}
   576  		}
   577  
   578  	case SigHashSingle:
   579  		// Resize output array to up to and including requested index.
   580  		txCopy.TxOut = txCopy.TxOut[:idx+1]
   581  
   582  		// All but current output get zeroed out.
   583  		for i := 0; i < idx; i++ {
   584  			txCopy.TxOut[i].Value = -1
   585  			txCopy.TxOut[i].PkScript = nil
   586  		}
   587  
   588  		// Sequence on all other inputs is 0, too.
   589  		for i := range txCopy.TxIn {
   590  			if i != idx {
   591  				txCopy.TxIn[i].Sequence = 0
   592  			}
   593  		}
   594  
   595  	default:
   596  		// Consensus treats undefined hashtypes like normal SigHashAll
   597  		// for purposes of hash generation.
   598  		fallthrough
   599  	case SigHashOld:
   600  		fallthrough
   601  	case SigHashAll:
   602  		// Nothing special here.
   603  	}
   604  	if hashType&SigHashAnyOneCanPay != 0 {
   605  		txCopy.TxIn = txCopy.TxIn[idx : idx+1]
   606  		idx = 0
   607  	}
   608  
   609  	// The final hash is the double sha256 of both the serialized modified
   610  	// transaction and the hash type (encoded as a 4-byte little-endian
   611  	// value) appended.
   612  	var wbuf bytes.Buffer
   613  	txCopy.SerializeNoWitness(&wbuf)
   614  	binary.Write(&wbuf, binary.LittleEndian, hashType)
   615  	return chainhash.DoubleHashB(wbuf.Bytes())
   616  }
   617  
   618  // asSmallInt returns the passed opcode, which must be true according to
   619  // isSmallInt(), as an integer.
   620  func asSmallInt(op *opcode) int {
   621  	if op.value == OP_0 {
   622  		return 0
   623  	}
   624  
   625  	return int(op.value - (OP_1 - 1))
   626  }
   627  
   628  // getSigOpCount is the implementation function for counting the number of
   629  // signature operations in the script provided by pops. If precise mode is
   630  // requested then we attempt to count the number of operations for a multisig
   631  // op. Otherwise we use the maximum.
   632  func getSigOpCount(pops []parsedOpcode, precise bool) int {
   633  	nSigs := 0
   634  	for i, pop := range pops {
   635  		switch pop.opcode.value {
   636  		case OP_CHECKSIG:
   637  			fallthrough
   638  		case OP_CHECKSIGVERIFY:
   639  			nSigs++
   640  		case OP_CHECKMULTISIG:
   641  			fallthrough
   642  		case OP_CHECKMULTISIGVERIFY:
   643  			// If we are being precise then look for familiar
   644  			// patterns for multisig, for now all we recognize is
   645  			// OP_1 - OP_16 to signify the number of pubkeys.
   646  			// Otherwise, we use the max of 20.
   647  			if precise && i > 0 &&
   648  				pops[i-1].opcode.value >= OP_1 &&
   649  				pops[i-1].opcode.value <= OP_16 {
   650  				nSigs += asSmallInt(pops[i-1].opcode)
   651  			} else {
   652  				nSigs += MaxPubKeysPerMultiSig
   653  			}
   654  		default:
   655  			// Not a sigop.
   656  		}
   657  	}
   658  
   659  	return nSigs
   660  }
   661  
   662  // GetSigOpCount provides a quick count of the number of signature operations
   663  // in a script. a CHECKSIG operations counts for 1, and a CHECK_MULTISIG for 20.
   664  // If the script fails to parse, then the count up to the point of failure is
   665  // returned.
   666  func GetSigOpCount(script []byte) int {
   667  	// Don't check error since parseScript returns the parsed-up-to-error
   668  	// list of pops.
   669  	pops, _ := ParseScript(script)
   670  	return getSigOpCount(pops, false)
   671  }
   672  
   673  // GetPreciseSigOpCount returns the number of signature operations in
   674  // scriptPubKey.  If bip16 is true then scriptSig may be searched for the
   675  // Pay-To-Script-Hash script in order to find the precise number of signature
   676  // operations in the transaction.  If the script fails to parse, then the count
   677  // up to the point of failure is returned.
   678  func GetPreciseSigOpCount(scriptSig, scriptPubKey []byte, bip16 bool) int {
   679  	// Don't check error since parseScript returns the parsed-up-to-error
   680  	// list of pops.
   681  	pops, _ := ParseScript(scriptPubKey)
   682  
   683  	// Treat non P2SH transactions as normal.
   684  	if !(bip16 && isScriptHash(pops)) {
   685  		return getSigOpCount(pops, true)
   686  	}
   687  
   688  	// The public key script is a pay-to-script-hash, so parse the signature
   689  	// script to get the final item.  Scripts that fail to fully parse count
   690  	// as 0 signature operations.
   691  	sigPops, err := ParseScript(scriptSig)
   692  	if err != nil {
   693  		return 0
   694  	}
   695  
   696  	// The signature script must only push data to the stack for P2SH to be
   697  	// a valid pair, so the signature operation count is 0 when that is not
   698  	// the case.
   699  	if !isPushOnly(sigPops) || len(sigPops) == 0 {
   700  		return 0
   701  	}
   702  
   703  	// The P2SH script is the last item the signature script pushes to the
   704  	// stack.  When the script is empty, there are no signature operations.
   705  	shScript := sigPops[len(sigPops)-1].data
   706  	if len(shScript) == 0 {
   707  		return 0
   708  	}
   709  
   710  	// Parse the P2SH script and don't check the error since parseScript
   711  	// returns the parsed-up-to-error list of pops and the consensus rules
   712  	// dictate signature operations are counted up to the first parse
   713  	// failure.
   714  	shPops, _ := ParseScript(shScript)
   715  	return getSigOpCount(shPops, true)
   716  }
   717  
   718  // GetWitnessSigOpCount returns the number of signature operations generated by
   719  // spending the passed pkScript with the specified witness, and or sigScript.
   720  // Unlike GetPreciseSigOpCount, this function is able to accurately count the
   721  // number of signature operations generated by spending witness programs, and
   722  // nested p2sh witness programs. If the script fails to parse, then the count
   723  // up to the point of failure is returned.
   724  func GetWitnessSigOpCount(sigScript, pkScript []byte, witness wire.TxWitness) int {
   725  	// If this is a regular witness program, then we can proceed directly
   726  	// to counting its signature operations without any further processing.
   727  	if IsWitnessProgram(pkScript) {
   728  		return getWitnessSigOps(pkScript, witness)
   729  	}
   730  
   731  	// Next, we'll check the sigScript to see if this is a nested p2sh
   732  	// witness program. This is a case wherein the sigScript is actually a
   733  	// datapush of a p2wsh witness program.
   734  	sigPops, err := ParseScript(sigScript)
   735  	if err != nil {
   736  		return 0
   737  	}
   738  	if IsPayToScriptHash(pkScript) &&
   739  		isPushOnly(sigPops) &&
   740  		IsPayToWitnessScriptHash(sigScript[1:]) {
   741  		return getWitnessSigOps(sigScript[1:], witness)
   742  	}
   743  
   744  	return 0
   745  }
   746  
   747  // getWitnessSigOps returns the number of signature operations generated by
   748  // spending the passed witness program wit the passed witness. The exact
   749  // signature counting heuristic is modified by the version of the passed
   750  // witness program. If the version of the witness program is unable to be
   751  // extracted, then 0 is returned for the sig op count.
   752  func getWitnessSigOps(witnessProgram []byte, witness [][]byte) int {
   753  	// Attempt to extract the witness program version.
   754  	witnessVersion, _, err := ExtractWitnessProgramInfo(witnessProgram)
   755  	if err != nil {
   756  		return 0
   757  	}
   758  
   759  	switch witnessVersion {
   760  	case 0:
   761  		switch {
   762  		case len(witnessProgram) == 22:
   763  			return 1
   764  		case len(witnessProgram) == 34 && len(witness) > 0:
   765  			pkScript := witness[len(witness)-1]
   766  			pops, err := ParseScript(pkScript)
   767  			if err != nil {
   768  				return 0
   769  			}
   770  
   771  			return getSigOpCount(pops, true)
   772  		}
   773  	}
   774  
   775  	return 0
   776  }
   777  
   778  // IsUnspendable returns whether the passed public key script is unspendable, or
   779  // guaranteed to fail at execution.  This allows inputs to be pruned instantly
   780  // when entering the UTXO set.
   781  func IsUnspendable(pkScript []byte) bool {
   782  	pops, err := ParseScript(pkScript)
   783  	if err != nil {
   784  		return true
   785  	}
   786  
   787  	return len(pops) > 0 && pops[0].opcode.value == OP_RETURN
   788  }