github.com/palcoin-project/palcd@v1.0.0/txscript/script.go (about)

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