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