2015-01-30 07:03:01 +01:00
|
|
|
// Copyright (c) 2013-2015 Conformal Systems LLC.
|
2013-06-12 23:35:27 +02:00
|
|
|
// Use of this source code is governed by an ISC
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
2015-01-30 07:03:01 +01:00
|
|
|
package txscript
|
2013-06-12 23:35:27 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/binary"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
2014-07-03 02:37:49 +02:00
|
|
|
"time"
|
|
|
|
|
2015-02-06 17:38:24 +01:00
|
|
|
"github.com/btcsuite/btcd/btcec"
|
2015-02-06 06:18:27 +01:00
|
|
|
"github.com/btcsuite/btcd/chaincfg"
|
2015-02-05 22:16:39 +01:00
|
|
|
"github.com/btcsuite/btcd/wire"
|
2015-01-15 17:42:26 +01:00
|
|
|
"github.com/btcsuite/btcutil"
|
2013-06-12 23:35:27 +02:00
|
|
|
)
|
|
|
|
|
2014-01-04 16:56:02 +01:00
|
|
|
var (
|
2014-10-12 23:40:09 +02:00
|
|
|
// ErrStackShortScript is returned if the script has an opcode that is
|
2014-01-04 16:56:02 +01:00
|
|
|
// too long for the length of the script.
|
2014-10-12 23:40:09 +02:00
|
|
|
ErrStackShortScript = errors.New("execute past end of script")
|
2014-01-04 16:56:02 +01:00
|
|
|
|
2014-10-12 23:40:09 +02:00
|
|
|
// ErrStackLongScript is returned if the script has an opcode that is
|
2014-03-14 19:40:35 +01:00
|
|
|
// too long for the length of the script.
|
2014-10-12 23:40:09 +02:00
|
|
|
ErrStackLongScript = errors.New("script is longer than maximum allowed")
|
2014-03-14 19:40:35 +01:00
|
|
|
|
2014-10-12 23:40:09 +02:00
|
|
|
// ErrStackUnderflow is returned if an opcode requires more items on the
|
|
|
|
// stack than is present.f
|
|
|
|
ErrStackUnderflow = errors.New("stack underflow")
|
2014-01-04 16:56:02 +01:00
|
|
|
|
2014-10-12 23:40:09 +02:00
|
|
|
// ErrStackInvalidArgs is returned if the argument for an opcode is out
|
2014-01-04 16:56:02 +01:00
|
|
|
// of acceptable range.
|
2014-10-12 23:40:09 +02:00
|
|
|
ErrStackInvalidArgs = errors.New("invalid argument")
|
2014-01-04 16:56:02 +01:00
|
|
|
|
2014-10-12 23:40:09 +02:00
|
|
|
// ErrStackOpDisabled is returned when a disabled opcode is encountered
|
2014-01-04 16:56:02 +01:00
|
|
|
// in the script.
|
2014-10-12 23:40:09 +02:00
|
|
|
ErrStackOpDisabled = errors.New("Disabled Opcode")
|
2014-01-04 16:56:02 +01:00
|
|
|
|
2014-10-12 23:40:09 +02:00
|
|
|
// ErrStackVerifyFailed is returned when one of the OP_VERIFY or
|
2014-01-04 16:56:02 +01:00
|
|
|
// OP_*VERIFY instructions is executed and the conditions fails.
|
2014-10-12 23:40:09 +02:00
|
|
|
ErrStackVerifyFailed = errors.New("Verify failed")
|
2014-01-04 16:56:02 +01:00
|
|
|
|
2014-10-12 23:40:09 +02:00
|
|
|
// ErrStackNumberTooBig is returned when the argument for an opcode that
|
2014-01-04 16:56:02 +01:00
|
|
|
// should be an offset is obviously far too large.
|
2014-10-12 23:40:09 +02:00
|
|
|
ErrStackNumberTooBig = errors.New("number too big")
|
2014-01-04 16:56:02 +01:00
|
|
|
|
2014-10-12 23:40:09 +02:00
|
|
|
// ErrStackInvalidOpcode is returned when an opcode marked as invalid or
|
2014-01-04 16:56:02 +01:00
|
|
|
// a completely undefined opcode is encountered.
|
2014-10-12 23:40:09 +02:00
|
|
|
ErrStackInvalidOpcode = errors.New("Invalid Opcode")
|
2014-01-04 16:56:02 +01:00
|
|
|
|
2014-10-12 23:40:09 +02:00
|
|
|
// ErrStackReservedOpcode is returned when an opcode marked as reserved
|
2014-01-04 16:56:02 +01:00
|
|
|
// is encountered.
|
2014-10-12 23:40:09 +02:00
|
|
|
ErrStackReservedOpcode = errors.New("Reserved Opcode")
|
2014-01-04 16:56:02 +01:00
|
|
|
|
2014-10-12 23:40:09 +02:00
|
|
|
// ErrStackEarlyReturn is returned when OP_RETURN is executed in the
|
2014-01-04 16:56:02 +01:00
|
|
|
// script.
|
2014-10-12 23:40:09 +02:00
|
|
|
ErrStackEarlyReturn = errors.New("Script returned early")
|
2014-01-04 16:56:02 +01:00
|
|
|
|
2014-10-12 23:40:09 +02:00
|
|
|
// ErrStackNoIf is returned if an OP_ELSE or OP_ENDIF is encountered
|
2014-01-04 16:56:02 +01:00
|
|
|
// without first having an OP_IF or OP_NOTIF in the script.
|
2014-10-12 23:40:09 +02:00
|
|
|
ErrStackNoIf = errors.New("OP_ELSE or OP_ENDIF with no matching OP_IF")
|
2014-01-04 16:56:02 +01:00
|
|
|
|
2014-10-12 23:40:09 +02:00
|
|
|
// ErrStackMissingEndif is returned if the end of a script is reached
|
2014-01-04 16:56:02 +01:00
|
|
|
// without and OP_ENDIF to correspond to a conditional expression.
|
2014-10-12 23:40:09 +02:00
|
|
|
ErrStackMissingEndif = fmt.Errorf("execute fail, in conditional execution")
|
2014-01-04 16:56:02 +01:00
|
|
|
|
2014-10-12 23:40:09 +02:00
|
|
|
// ErrStackTooManyPubkeys is returned if an OP_CHECKMULTISIG is
|
2014-01-04 16:56:02 +01:00
|
|
|
// encountered with more than MaxPubKeysPerMultiSig pubkeys present.
|
2014-10-12 23:40:09 +02:00
|
|
|
ErrStackTooManyPubkeys = errors.New("Invalid pubkey count in OP_CHECKMULTISIG")
|
2014-01-04 16:56:02 +01:00
|
|
|
|
2014-10-12 23:40:09 +02:00
|
|
|
// ErrStackTooManyOperations is returned if a script has more than
|
2014-01-04 16:56:02 +01:00
|
|
|
// MaxOpsPerScript opcodes that do not push data.
|
2014-10-12 23:40:09 +02:00
|
|
|
ErrStackTooManyOperations = errors.New("Too many operations in script")
|
2014-01-04 16:56:02 +01:00
|
|
|
|
2014-10-12 23:40:09 +02:00
|
|
|
// ErrStackElementTooBig is returned if the size of an element to be
|
2014-01-04 16:56:02 +01:00
|
|
|
// pushed to the stack is over MaxScriptElementSize.
|
2014-10-12 23:40:09 +02:00
|
|
|
ErrStackElementTooBig = errors.New("Element in script too large")
|
2014-01-04 16:56:02 +01:00
|
|
|
|
2014-10-12 23:40:09 +02:00
|
|
|
// ErrStackUnknownAddress is returned when ScriptToAddrHash does not
|
2014-01-04 16:56:02 +01:00
|
|
|
// recognise the pattern of the script and thus can not find the address
|
|
|
|
// for payment.
|
2014-10-12 23:40:09 +02:00
|
|
|
ErrStackUnknownAddress = errors.New("non-recognised address")
|
2014-01-04 16:56:02 +01:00
|
|
|
|
2014-10-12 23:40:09 +02:00
|
|
|
// ErrStackScriptFailed is returned when at the end of a script the
|
2014-01-04 16:56:02 +01:00
|
|
|
// boolean on top of the stack is false signifying that the script has
|
|
|
|
// failed.
|
2014-10-12 23:40:09 +02:00
|
|
|
ErrStackScriptFailed = errors.New("execute fail, fail on stack")
|
2014-01-04 16:56:02 +01:00
|
|
|
|
2014-10-12 23:40:09 +02:00
|
|
|
// ErrStackScriptUnfinished is returned when CheckErrorCondition is
|
2014-01-04 16:56:02 +01:00
|
|
|
// called on a script that has not finished executing.
|
2014-10-12 23:40:09 +02:00
|
|
|
ErrStackScriptUnfinished = errors.New("Error check when script unfinished")
|
2014-01-04 16:56:02 +01:00
|
|
|
|
2014-10-12 23:40:09 +02:00
|
|
|
// ErrStackEmptyStack is returned when the stack is empty at the end of
|
2014-01-04 16:56:02 +01:00
|
|
|
// execution. Normal operation requires that a boolean is on top of the
|
|
|
|
// stack when the scripts have finished executing.
|
2014-10-12 23:40:09 +02:00
|
|
|
ErrStackEmptyStack = errors.New("Stack empty at end of execution")
|
2014-01-04 16:56:02 +01:00
|
|
|
|
2014-10-12 23:40:09 +02:00
|
|
|
// ErrStackP2SHNonPushOnly is returned when a Pay-to-Script-Hash
|
2014-01-04 16:56:02 +01:00
|
|
|
// transaction is encountered and the ScriptSig does operations other
|
|
|
|
// than push data (in violation of bip16).
|
2014-10-12 23:40:09 +02:00
|
|
|
ErrStackP2SHNonPushOnly = errors.New("pay to script hash with non " +
|
2014-01-04 16:56:02 +01:00
|
|
|
"pushonly input")
|
|
|
|
|
2014-10-12 23:40:09 +02:00
|
|
|
// ErrStackInvalidParseType is an internal error returned from
|
2014-01-04 16:56:02 +01:00
|
|
|
// ScriptToAddrHash ony if the internal data tables are wrong.
|
2014-10-12 23:40:09 +02:00
|
|
|
ErrStackInvalidParseType = errors.New("internal error: invalid parsetype found")
|
2014-01-04 16:56:02 +01:00
|
|
|
|
2014-10-12 23:40:09 +02:00
|
|
|
// ErrStackInvalidAddrOffset is an internal error returned from
|
2014-01-04 16:56:02 +01:00
|
|
|
// ScriptToAddrHash ony if the internal data tables are wrong.
|
2014-10-12 23:40:09 +02:00
|
|
|
ErrStackInvalidAddrOffset = errors.New("internal error: invalid offset found")
|
2014-01-04 16:56:02 +01:00
|
|
|
|
2014-10-12 23:40:09 +02:00
|
|
|
// ErrStackInvalidIndex is returned when an out-of-bounds index was
|
2014-01-04 16:56:02 +01:00
|
|
|
// passed to a function.
|
2014-10-12 23:40:09 +02:00
|
|
|
ErrStackInvalidIndex = errors.New("Invalid script index")
|
2014-01-04 16:56:02 +01:00
|
|
|
|
2014-10-12 23:40:09 +02:00
|
|
|
// ErrStackNonPushOnly is returned when ScriptInfo is called with a
|
2014-01-04 16:56:02 +01:00
|
|
|
// pkScript that peforms operations other that pushing data to the stack.
|
2014-10-12 23:40:09 +02:00
|
|
|
ErrStackNonPushOnly = errors.New("SigScript is non pushonly")
|
2014-03-14 19:35:36 +01:00
|
|
|
|
2014-10-12 23:40:09 +02:00
|
|
|
// ErrStackOverflow is returned when stack and altstack combined depth
|
2014-03-14 19:35:36 +01:00
|
|
|
// is over the limit.
|
2014-10-12 23:40:09 +02:00
|
|
|
ErrStackOverflow = errors.New("Stacks overflowed")
|
2014-01-04 16:56:02 +01:00
|
|
|
)
|
2013-10-09 01:13:52 +02:00
|
|
|
|
2014-03-14 19:40:35 +01:00
|
|
|
const (
|
|
|
|
// maxStackSize is the maximum combined height of stack and alt stack
|
|
|
|
// during execution.
|
|
|
|
maxStackSize = 1000
|
|
|
|
|
|
|
|
// maxScriptSize is the maximum allowed length of a raw script.
|
|
|
|
maxScriptSize = 10000
|
|
|
|
)
|
2014-03-14 19:35:36 +01:00
|
|
|
|
2014-01-03 20:35:31 +01:00
|
|
|
// ErrUnsupportedAddress is returned when a concrete type that implements
|
|
|
|
// a btcutil.Address is not a supported type.
|
|
|
|
var ErrUnsupportedAddress = errors.New("unsupported address type")
|
|
|
|
|
2013-06-12 23:35:27 +02:00
|
|
|
// Bip16Activation is the timestamp where BIP0016 is valid to use in the
|
|
|
|
// blockchain. To be used to determine if BIP0016 should be called for or not.
|
|
|
|
// This timestamp corresponds to Sun Apr 1 00:00:00 UTC 2012.
|
|
|
|
var Bip16Activation = time.Unix(1333238400, 0)
|
|
|
|
|
2014-10-11 21:55:28 +02:00
|
|
|
// SigHashType represents hash type bits at the end of a signature.
|
|
|
|
type SigHashType byte
|
|
|
|
|
2013-06-12 23:35:27 +02:00
|
|
|
// Hash type bits from the end of a signature.
|
|
|
|
const (
|
2014-10-11 21:55:28 +02:00
|
|
|
SigHashOld SigHashType = 0x0
|
|
|
|
SigHashAll SigHashType = 0x1
|
|
|
|
SigHashNone SigHashType = 0x2
|
|
|
|
SigHashSingle SigHashType = 0x3
|
|
|
|
SigHashAnyOneCanPay SigHashType = 0x80
|
2013-06-12 23:35:27 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
// These are the constants specified for maximums in individual scripts.
|
|
|
|
const (
|
|
|
|
MaxOpsPerScript = 201 // Max number of non-push operations.
|
|
|
|
MaxPubKeysPerMultiSig = 20 // Multisig can't have more sigs than this.
|
|
|
|
MaxScriptElementSize = 520 // Max bytes pushable to the stack.
|
|
|
|
)
|
|
|
|
|
2013-07-05 01:54:55 +02:00
|
|
|
// ScriptClass is an enumeration for the list of standard types of script.
|
|
|
|
type ScriptClass byte
|
2013-06-12 23:35:27 +02:00
|
|
|
|
2013-07-05 01:54:55 +02:00
|
|
|
// Classes of script payment known about in the blockchain.
|
2013-06-12 23:35:27 +02:00
|
|
|
const (
|
2013-11-14 22:05:20 +01:00
|
|
|
NonStandardTy ScriptClass = iota // None of the recognized forms.
|
|
|
|
PubKeyTy // Pay pubkey.
|
2013-07-31 02:31:27 +02:00
|
|
|
PubKeyHashTy // Pay pubkey hash.
|
|
|
|
ScriptHashTy // Pay to script hash.
|
|
|
|
MultiSigTy // Multi signature.
|
2013-11-14 22:05:20 +01:00
|
|
|
NullDataTy // Empty data-only (provably prunable).
|
2013-06-12 23:35:27 +02:00
|
|
|
)
|
|
|
|
|
2013-11-06 01:10:16 +01:00
|
|
|
var scriptClassToName = []string{
|
2013-11-14 22:05:20 +01:00
|
|
|
NonStandardTy: "nonstandard",
|
2013-11-14 18:13:58 +01:00
|
|
|
PubKeyTy: "pubkey",
|
|
|
|
PubKeyHashTy: "pubkeyhash",
|
|
|
|
ScriptHashTy: "scripthash",
|
|
|
|
MultiSigTy: "multisig",
|
2013-11-14 22:05:20 +01:00
|
|
|
NullDataTy: "nulldata",
|
2013-11-06 01:10:16 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// String implements the Stringer interface by returning the name of
|
|
|
|
// the enum script class. If the enum is invalid then "Invalid" will be
|
|
|
|
// returned.
|
|
|
|
func (t ScriptClass) String() string {
|
|
|
|
if int(t) > len(scriptClassToName) || int(t) < 0 {
|
|
|
|
return "Invalid"
|
|
|
|
}
|
|
|
|
return scriptClassToName[t]
|
|
|
|
}
|
|
|
|
|
2015-01-30 07:03:01 +01:00
|
|
|
// Script is the virtual machine that executes scripts.
|
2013-06-12 23:35:27 +02:00
|
|
|
type Script struct {
|
2014-12-23 18:15:41 +01:00
|
|
|
scripts [][]parsedOpcode
|
|
|
|
scriptidx int
|
|
|
|
scriptoff int
|
|
|
|
lastcodesep int
|
|
|
|
dstack Stack // data stack
|
|
|
|
astack Stack // alt stack
|
2015-02-05 22:16:39 +01:00
|
|
|
tx wire.MsgTx
|
2014-12-23 18:15:41 +01:00
|
|
|
txidx int
|
|
|
|
condStack []int
|
|
|
|
numOps int
|
|
|
|
bip16 bool // treat execution as pay-to-script-hash
|
|
|
|
der bool // enforce DER encoding
|
|
|
|
strictMultiSig bool // verify multisig stack item is zero length
|
|
|
|
discourageUpgradableNops bool // NOP1 to NOP10 are reserved for future soft-fork upgrades
|
|
|
|
savedFirstStack [][]byte // stack from first script for bip16 scripts
|
2013-06-12 23:35:27 +02:00
|
|
|
}
|
|
|
|
|
2014-02-19 23:17:02 +01:00
|
|
|
// isSmallInt returns whether or not the opcode is considered a small integer,
|
|
|
|
// which is an OP_0, or OP_1 through OP_16.
|
|
|
|
func isSmallInt(op *opcode) bool {
|
|
|
|
if op.value == OP_0 || (op.value >= OP_1 && op.value <= OP_16) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2013-06-12 23:35:27 +02:00
|
|
|
// isPubkey returns true if the script passed is a pubkey transaction, false
|
|
|
|
// otherwise.
|
|
|
|
func isPubkey(pops []parsedOpcode) bool {
|
2014-02-21 09:11:11 +01:00
|
|
|
// valid pubkeys are either 33 or 65 bytes
|
2013-06-12 23:35:27 +02:00
|
|
|
return len(pops) == 2 &&
|
2014-02-21 09:11:11 +01:00
|
|
|
(len(pops[0].data) == 33 || len(pops[0].data) == 65) &&
|
2013-06-12 23:35:27 +02:00
|
|
|
pops[1].opcode.value == OP_CHECKSIG
|
|
|
|
}
|
|
|
|
|
|
|
|
// isPubkeyHash returns true if the script passed is a pubkey hash transaction,
|
|
|
|
// false otherwise.
|
|
|
|
func isPubkeyHash(pops []parsedOpcode) bool {
|
|
|
|
return len(pops) == 5 &&
|
|
|
|
pops[0].opcode.value == OP_DUP &&
|
|
|
|
pops[1].opcode.value == OP_HASH160 &&
|
|
|
|
pops[2].opcode.value == OP_DATA_20 &&
|
|
|
|
pops[3].opcode.value == OP_EQUALVERIFY &&
|
|
|
|
pops[4].opcode.value == OP_CHECKSIG
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
// isScriptHash returns true if the script passed is a pay-to-script-hash (P2SH)
|
|
|
|
// transction, false otherwise.
|
|
|
|
func isScriptHash(pops []parsedOpcode) bool {
|
|
|
|
return len(pops) == 3 &&
|
|
|
|
pops[0].opcode.value == OP_HASH160 &&
|
|
|
|
pops[1].opcode.value == OP_DATA_20 &&
|
|
|
|
pops[2].opcode.value == OP_EQUAL
|
|
|
|
}
|
|
|
|
|
2013-06-27 01:32:11 +02:00
|
|
|
// IsPayToScriptHash returns true if the script is in the standard
|
|
|
|
// Pay-To-Script-Hash format, false otherwise.
|
|
|
|
func IsPayToScriptHash(script []byte) bool {
|
|
|
|
pops, err := parseScript(script)
|
|
|
|
if err != nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return isScriptHash(pops)
|
|
|
|
}
|
|
|
|
|
2013-06-12 23:35:27 +02:00
|
|
|
// isMultiSig returns true if the passed script is a multisig transaction, false
|
|
|
|
// otherwise.
|
|
|
|
func isMultiSig(pops []parsedOpcode) bool {
|
|
|
|
l := len(pops)
|
|
|
|
// absolute minimum is 1 pubkey so
|
2014-02-19 23:17:02 +01:00
|
|
|
// OP_0/OP_1-16, pubkey, OP_1, OP_CHECKMULTISIG
|
2013-06-12 23:35:27 +02:00
|
|
|
if l < 4 {
|
|
|
|
return false
|
|
|
|
}
|
2014-02-19 23:17:02 +01:00
|
|
|
if !isSmallInt(pops[0].opcode) {
|
2013-06-12 23:35:27 +02:00
|
|
|
return false
|
|
|
|
}
|
2014-02-19 23:17:02 +01:00
|
|
|
if !isSmallInt(pops[l-2].opcode) {
|
2013-06-12 23:35:27 +02:00
|
|
|
return false
|
|
|
|
}
|
2014-01-04 22:13:29 +01:00
|
|
|
if pops[l-1].opcode.value != OP_CHECKMULTISIG {
|
2013-06-12 23:35:27 +02:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
for _, pop := range pops[1 : l-2] {
|
|
|
|
// valid pubkeys are either 65 or 33 bytes
|
|
|
|
if len(pop.data) != 33 &&
|
|
|
|
len(pop.data) != 65 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2013-11-14 22:05:20 +01:00
|
|
|
// isNullData returns true if the passed script is a null data transaction,
|
|
|
|
// false otherwise.
|
|
|
|
func isNullData(pops []parsedOpcode) bool {
|
|
|
|
// A nulldata transaction is either a single OP_RETURN or an
|
2014-05-01 15:41:29 +02:00
|
|
|
// OP_RETURN SMALLDATA (where SMALLDATA is a push data up to 40 bytes).
|
2013-11-14 22:05:20 +01:00
|
|
|
l := len(pops)
|
|
|
|
if l == 1 && pops[0].opcode.value == OP_RETURN {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
return l == 2 &&
|
|
|
|
pops[0].opcode.value == OP_RETURN &&
|
|
|
|
pops[1].opcode.value <= OP_PUSHDATA4 &&
|
2014-05-01 15:41:29 +02:00
|
|
|
len(pops[1].data) <= 40
|
2013-11-14 22:05:20 +01:00
|
|
|
}
|
|
|
|
|
2013-06-12 23:35:27 +02:00
|
|
|
// isPushOnly returns true if the script only pushes data, false otherwise.
|
|
|
|
func isPushOnly(pops []parsedOpcode) bool {
|
|
|
|
// technically we cheat here, we don't look at opcodes
|
|
|
|
for _, pop := range pops {
|
|
|
|
// all opcodes up to OP_16 are data instructions.
|
|
|
|
if pop.opcode.value < OP_FALSE ||
|
|
|
|
pop.opcode.value > OP_16 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2013-09-27 03:34:25 +02:00
|
|
|
// IsPushOnlyScript returns whether or not the passed script only pushes data.
|
|
|
|
// If the script does not parse false will be returned.
|
|
|
|
func IsPushOnlyScript(script []byte) bool {
|
|
|
|
pops, err := parseScript(script)
|
|
|
|
if err != nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return isPushOnly(pops)
|
|
|
|
}
|
|
|
|
|
2014-03-18 18:54:29 +01:00
|
|
|
// canonicalPush returns true if the object is either not a push instruction
|
|
|
|
// or the push instruction contained wherein is matches the canonical form
|
|
|
|
// or using the smallest instruction to do the job. False otherwise.
|
|
|
|
func canonicalPush(pop parsedOpcode) bool {
|
|
|
|
opcode := pop.opcode.value
|
|
|
|
data := pop.data
|
|
|
|
dataLen := len(pop.data)
|
|
|
|
if opcode > OP_16 {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
if opcode < OP_PUSHDATA1 && opcode > OP_0 && (dataLen == 1 && data[0] <= 16) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if opcode == OP_PUSHDATA1 && dataLen < OP_PUSHDATA1 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if opcode == OP_PUSHDATA2 && dataLen <= 0xff {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if opcode == OP_PUSHDATA4 && dataLen <= 0xffff {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2014-02-20 06:05:35 +01:00
|
|
|
// HasCanonicalPushes returns whether or not the passed script only contains
|
|
|
|
// canonical data pushes. A canonical data push one where the fewest number of
|
|
|
|
// bytes possible to encode the size of the data being pushed is used. This
|
|
|
|
// includes using the small integer opcodes for single byte data that can be
|
|
|
|
// represented directly.
|
|
|
|
func HasCanonicalPushes(script []byte) bool {
|
|
|
|
pops, err := parseScript(script)
|
|
|
|
if err != nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, pop := range pops {
|
2014-03-18 18:54:29 +01:00
|
|
|
if !canonicalPush(pop) {
|
2014-02-20 06:05:35 +01:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2013-07-05 01:54:55 +02:00
|
|
|
// GetScriptClass returns the class of the script passed. If the script does not
|
|
|
|
// parse then NonStandardTy will be returned.
|
|
|
|
func GetScriptClass(script []byte) ScriptClass {
|
|
|
|
pops, err := parseScript(script)
|
|
|
|
if err != nil {
|
|
|
|
return NonStandardTy
|
|
|
|
}
|
|
|
|
return typeOfScript(pops)
|
|
|
|
}
|
|
|
|
|
2013-06-12 23:35:27 +02:00
|
|
|
// scriptType returns the type of the script being inspected from the known
|
|
|
|
// standard types.
|
2013-07-05 01:54:55 +02:00
|
|
|
func typeOfScript(pops []parsedOpcode) ScriptClass {
|
2013-06-12 23:35:27 +02:00
|
|
|
// XXX dubious optimisation: order these in order of popularity in the
|
|
|
|
// blockchain
|
|
|
|
if isPubkey(pops) {
|
2013-07-05 01:54:55 +02:00
|
|
|
return PubKeyTy
|
2013-06-12 23:35:27 +02:00
|
|
|
} else if isPubkeyHash(pops) {
|
2013-07-05 01:54:55 +02:00
|
|
|
return PubKeyHashTy
|
2013-06-12 23:35:27 +02:00
|
|
|
} else if isScriptHash(pops) {
|
2013-07-05 01:54:55 +02:00
|
|
|
return ScriptHashTy
|
2013-06-12 23:35:27 +02:00
|
|
|
} else if isMultiSig(pops) {
|
2013-07-05 01:54:55 +02:00
|
|
|
return MultiSigTy
|
2013-11-14 22:05:20 +01:00
|
|
|
} else if isNullData(pops) {
|
|
|
|
return NullDataTy
|
2013-06-12 23:35:27 +02:00
|
|
|
}
|
2013-07-05 01:54:55 +02:00
|
|
|
return NonStandardTy
|
2013-06-12 23:35:27 +02:00
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
// parseScript preparses the script in bytes into a list of parsedOpcodes while
|
|
|
|
// applying a number of sanity checks.
|
|
|
|
func parseScript(script []byte) ([]parsedOpcode, error) {
|
2013-06-28 01:46:34 +02:00
|
|
|
return parseScriptTemplate(script, opcodemap)
|
|
|
|
}
|
|
|
|
|
|
|
|
// parseScriptTemplate is the same as parseScript but allows the passing of the
|
2013-07-25 16:40:11 +02:00
|
|
|
// template list for testing purposes. On error we return the list of parsed
|
|
|
|
// opcodes so far.
|
2013-06-28 01:46:34 +02:00
|
|
|
func parseScriptTemplate(script []byte, opcodemap map[byte]*opcode) ([]parsedOpcode, error) {
|
2013-09-25 18:38:20 +02:00
|
|
|
retScript := make([]parsedOpcode, 0, len(script))
|
2013-06-12 23:35:27 +02:00
|
|
|
for i := 0; i < len(script); {
|
|
|
|
instr := script[i]
|
|
|
|
op, ok := opcodemap[instr]
|
|
|
|
if !ok {
|
2014-10-12 23:40:09 +02:00
|
|
|
return retScript, ErrStackInvalidOpcode
|
2013-06-12 23:35:27 +02:00
|
|
|
}
|
|
|
|
pop := parsedOpcode{opcode: op}
|
|
|
|
// parse data out of instruction.
|
|
|
|
switch {
|
|
|
|
case op.length == 1:
|
|
|
|
// no data, done here
|
|
|
|
i++
|
|
|
|
case op.length > 1:
|
|
|
|
if len(script[i:]) < op.length {
|
2014-10-12 23:40:09 +02:00
|
|
|
return retScript, ErrStackShortScript
|
2013-06-12 23:35:27 +02:00
|
|
|
}
|
|
|
|
// slice out the data.
|
|
|
|
pop.data = script[i+1 : i+op.length]
|
|
|
|
i += op.length
|
|
|
|
case op.length < 0:
|
|
|
|
var l uint
|
|
|
|
off := i + 1
|
2014-03-14 21:59:43 +01:00
|
|
|
|
|
|
|
if len(script[off:]) < -op.length {
|
2014-10-12 23:40:09 +02:00
|
|
|
return retScript, ErrStackShortScript
|
2014-03-14 21:59:43 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Next -length bytes are little endian length of data.
|
2013-06-12 23:35:27 +02:00
|
|
|
switch op.length {
|
|
|
|
case -1:
|
2014-03-14 21:59:43 +01:00
|
|
|
l = uint(script[off])
|
2013-06-12 23:35:27 +02:00
|
|
|
case -2:
|
2014-03-14 21:59:43 +01:00
|
|
|
l = ((uint(script[off+1]) << 8) |
|
|
|
|
uint(script[off]))
|
2013-06-12 23:35:27 +02:00
|
|
|
case -4:
|
2014-03-14 21:59:43 +01:00
|
|
|
l = ((uint(script[off+3]) << 24) |
|
|
|
|
(uint(script[off+2]) << 16) |
|
|
|
|
(uint(script[off+1]) << 8) |
|
|
|
|
uint(script[off]))
|
2013-06-12 23:35:27 +02:00
|
|
|
default:
|
2013-07-25 16:40:11 +02:00
|
|
|
return retScript,
|
|
|
|
fmt.Errorf("invalid opcode length %d",
|
2013-07-31 02:31:27 +02:00
|
|
|
op.length)
|
2013-06-12 23:35:27 +02:00
|
|
|
}
|
|
|
|
|
2014-03-14 21:59:43 +01:00
|
|
|
off += -op.length // beginning of data
|
2013-10-09 00:21:40 +02:00
|
|
|
// Disallow entries that do not fit script or were
|
|
|
|
// sign extended.
|
2013-10-09 02:27:19 +02:00
|
|
|
if int(l) > len(script[off:]) || int(l) < 0 {
|
2014-10-12 23:40:09 +02:00
|
|
|
return retScript, ErrStackShortScript
|
2013-06-12 23:35:27 +02:00
|
|
|
}
|
|
|
|
pop.data = script[off : off+int(l)]
|
|
|
|
i += 1 - op.length + int(l)
|
|
|
|
}
|
|
|
|
retScript = append(retScript, pop)
|
|
|
|
}
|
|
|
|
return retScript, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// unparseScript reversed the action of parseScript and returns the
|
|
|
|
// parsedOpcodes as a list of bytes
|
2013-09-10 17:39:29 +02:00
|
|
|
func unparseScript(pops []parsedOpcode) ([]byte, error) {
|
2013-09-25 18:38:20 +02:00
|
|
|
script := make([]byte, 0, len(pops))
|
2013-06-12 23:35:27 +02:00
|
|
|
for _, pop := range pops {
|
2013-09-10 17:39:29 +02:00
|
|
|
b, err := pop.bytes()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
script = append(script, b...)
|
2013-06-12 23:35:27 +02:00
|
|
|
}
|
2013-09-10 17:39:29 +02:00
|
|
|
return script, nil
|
2013-06-12 23:35:27 +02:00
|
|
|
}
|
|
|
|
|
2013-10-24 16:13:58 +02:00
|
|
|
// ScriptFlags is a bitmask defining additional operations or
|
|
|
|
// tests that will be done when executing a Script.
|
|
|
|
type ScriptFlags uint32
|
|
|
|
|
|
|
|
const (
|
|
|
|
// ScriptBip16 defines whether the bip16 threshhold has passed and thus
|
|
|
|
// pay-to-script hash transactions will be fully validated.
|
|
|
|
ScriptBip16 ScriptFlags = 1 << iota
|
|
|
|
|
|
|
|
// ScriptCanonicalSignatures defines whether additional canonical
|
|
|
|
// signature checks are performed when parsing a signature.
|
|
|
|
//
|
|
|
|
// Canonical (DER) signatures are not required in the tx rules for
|
|
|
|
// block acceptance, but are checked in recent versions of bitcoind
|
|
|
|
// when accepting transactions to the mempool. Non-canonical (valid
|
|
|
|
// BER but not valid DER) transactions can potentially be changed
|
|
|
|
// before mined into a block, either by adding extra padding or
|
|
|
|
// flipping the sign of the R or S value in the signature, creating a
|
|
|
|
// transaction that still validates and spends the inputs, but is not
|
|
|
|
// recognized by creator of the transaction. Performing a canonical
|
|
|
|
// check enforces script signatures use a unique DER format.
|
|
|
|
ScriptCanonicalSignatures
|
2014-05-27 19:59:24 +02:00
|
|
|
|
|
|
|
// ScriptStrictMultiSig defines whether to verify the stack item
|
|
|
|
// used by CHECKMULTISIG is zero length.
|
|
|
|
ScriptStrictMultiSig
|
2014-12-23 18:15:41 +01:00
|
|
|
|
|
|
|
// ScriptDiscourageUpgradableNops defines whether to verify that
|
|
|
|
// NOP1 through NOP10 are reserved for future soft-fork upgrades. This
|
|
|
|
// flag must not be used for consensus critical code nor applied to
|
|
|
|
// blocks as this flag is only for stricter standard transaction
|
|
|
|
// checks. This flag is only applied when the above opcodes are
|
|
|
|
// executed.
|
|
|
|
ScriptDiscourageUpgradableNops
|
2015-01-29 21:30:21 +01:00
|
|
|
|
|
|
|
// ScriptVerifySigPushOnly defines that signature scripts must contain
|
|
|
|
// only pushed data. This is rule 2 of BIP0062.
|
|
|
|
ScriptVerifySigPushOnly
|
2013-10-24 16:13:58 +02:00
|
|
|
)
|
|
|
|
|
2013-06-12 23:35:27 +02:00
|
|
|
// NewScript returns a new script engine for the provided tx and input idx with
|
|
|
|
// a signature script scriptSig and a pubkeyscript scriptPubKey. If bip16 is
|
|
|
|
// true then it will be treated as if the bip16 threshhold has passed and thus
|
|
|
|
// pay-to-script hash transactions will be fully validated.
|
2015-02-05 22:16:39 +01:00
|
|
|
func NewScript(scriptSig []byte, scriptPubKey []byte, txidx int, tx *wire.MsgTx, flags ScriptFlags) (*Script, error) {
|
2013-06-12 23:35:27 +02:00
|
|
|
var m Script
|
2015-01-29 21:30:21 +01:00
|
|
|
if flags&ScriptVerifySigPushOnly == ScriptVerifySigPushOnly && !IsPushOnlyScript(scriptSig) {
|
|
|
|
return nil, ErrStackNonPushOnly
|
|
|
|
}
|
|
|
|
|
2013-06-12 23:35:27 +02:00
|
|
|
scripts := [][]byte{scriptSig, scriptPubKey}
|
|
|
|
m.scripts = make([][]parsedOpcode, len(scripts))
|
|
|
|
for i, scr := range scripts {
|
2014-03-14 19:40:35 +01:00
|
|
|
if len(scr) > maxScriptSize {
|
2014-10-12 23:40:09 +02:00
|
|
|
return nil, ErrStackLongScript
|
2014-03-14 19:40:35 +01:00
|
|
|
}
|
2013-06-12 23:35:27 +02:00
|
|
|
var err error
|
|
|
|
m.scripts[i], err = parseScript(scr)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2013-06-26 15:16:00 +02:00
|
|
|
// If the first scripts(s) are empty, must start on later ones.
|
|
|
|
if i == 0 && len(scr) == 0 {
|
|
|
|
// This could end up seeing an invalid initial pc if
|
|
|
|
// all scripts were empty. However, that is an invalid
|
|
|
|
// case and should fail.
|
2013-06-12 23:35:27 +02:00
|
|
|
m.scriptidx = i + 1
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-10-24 16:13:58 +02:00
|
|
|
// Parse flags.
|
|
|
|
bip16 := flags&ScriptBip16 == ScriptBip16
|
2013-06-12 23:35:27 +02:00
|
|
|
if bip16 && isScriptHash(m.scripts[1]) {
|
|
|
|
// if we are pay to scripthash then we only accept input
|
|
|
|
// scripts that push data
|
|
|
|
if !isPushOnly(m.scripts[0]) {
|
2014-10-12 23:40:09 +02:00
|
|
|
return nil, ErrStackP2SHNonPushOnly
|
2013-06-12 23:35:27 +02:00
|
|
|
}
|
|
|
|
m.bip16 = true
|
|
|
|
}
|
2013-10-24 16:13:58 +02:00
|
|
|
if flags&ScriptCanonicalSignatures == ScriptCanonicalSignatures {
|
|
|
|
m.der = true
|
|
|
|
}
|
2014-05-27 19:59:24 +02:00
|
|
|
if flags&ScriptStrictMultiSig == ScriptStrictMultiSig {
|
|
|
|
m.strictMultiSig = true
|
|
|
|
}
|
2014-12-23 18:15:41 +01:00
|
|
|
if flags&ScriptDiscourageUpgradableNops == ScriptDiscourageUpgradableNops {
|
|
|
|
m.discourageUpgradableNops = true
|
|
|
|
}
|
2013-06-12 23:35:27 +02:00
|
|
|
|
|
|
|
m.tx = *tx
|
|
|
|
m.txidx = txidx
|
|
|
|
m.condStack = []int{OpCondTrue}
|
|
|
|
|
|
|
|
return &m, nil
|
|
|
|
}
|
|
|
|
|
2013-07-06 18:58:28 +02:00
|
|
|
// Execute will execute all script in the script engine and return either nil
|
2013-06-12 23:35:27 +02:00
|
|
|
// for successful validation or an error if one occurred.
|
|
|
|
func (s *Script) Execute() (err error) {
|
|
|
|
done := false
|
|
|
|
for done != true {
|
|
|
|
log.Tracef("%v", newLogClosure(func() string {
|
|
|
|
dis, err := s.DisasmPC()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Sprintf("stepping (%v)", err)
|
|
|
|
}
|
|
|
|
return fmt.Sprintf("stepping %v", dis)
|
|
|
|
}))
|
|
|
|
|
|
|
|
done, err = s.Step()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
log.Tracef("%v", newLogClosure(func() string {
|
|
|
|
var dstr, astr string
|
|
|
|
|
|
|
|
// if we're tracing, dump the stacks.
|
|
|
|
if s.dstack.Depth() != 0 {
|
2014-08-29 15:27:46 +02:00
|
|
|
dstr = "Stack:\n" + s.dstack.String()
|
2013-06-12 23:35:27 +02:00
|
|
|
}
|
|
|
|
if s.astack.Depth() != 0 {
|
2014-08-29 15:27:46 +02:00
|
|
|
astr = "AltStack:\n" + s.astack.String()
|
2013-06-12 23:35:27 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return dstr + astr
|
|
|
|
}))
|
|
|
|
}
|
2013-06-18 18:39:00 +02:00
|
|
|
|
|
|
|
return s.CheckErrorCondition()
|
|
|
|
}
|
|
|
|
|
|
|
|
// CheckErrorCondition returns nil if the running script has ended and was
|
|
|
|
// successful, leaving a a true boolean on the stack. An error otherwise,
|
|
|
|
// including if the script has not finished.
|
|
|
|
func (s *Script) CheckErrorCondition() (err error) {
|
|
|
|
// Check we are actually done. if pc is past the end of script array
|
|
|
|
// then we have run out of scripts to run.
|
|
|
|
if s.scriptidx < len(s.scripts) {
|
2014-10-12 23:40:09 +02:00
|
|
|
return ErrStackScriptUnfinished
|
2013-06-18 18:39:00 +02:00
|
|
|
}
|
2013-06-12 23:35:27 +02:00
|
|
|
if s.dstack.Depth() < 1 {
|
2014-10-12 23:40:09 +02:00
|
|
|
return ErrStackEmptyStack
|
2013-06-12 23:35:27 +02:00
|
|
|
}
|
|
|
|
v, err := s.dstack.PopBool()
|
|
|
|
if err == nil && v == false {
|
|
|
|
// log interesting data.
|
2014-02-19 20:22:33 +01:00
|
|
|
log.Tracef("%v", newLogClosure(func() string {
|
2013-06-12 23:35:27 +02:00
|
|
|
dis0, _ := s.DisasmScript(0)
|
|
|
|
dis1, _ := s.DisasmScript(1)
|
2013-06-18 18:39:00 +02:00
|
|
|
return fmt.Sprintf("scripts failed: script0: %s\n"+
|
|
|
|
"script1: %s", dis0, dis1)
|
2014-02-19 20:22:33 +01:00
|
|
|
}))
|
2014-10-12 23:40:09 +02:00
|
|
|
err = ErrStackScriptFailed
|
2013-06-12 23:35:27 +02:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Step will execute the next instruction and move the program counter to the
|
|
|
|
// next opcode in the script, or the next script if the curent has ended. Step
|
|
|
|
// will return true in the case that the last opcode was successfully executed.
|
|
|
|
// if an error is returned then the result of calling Step or any other method
|
|
|
|
// is undefined.
|
2014-10-13 02:39:01 +02:00
|
|
|
func (s *Script) Step() (done bool, err error) {
|
2013-06-12 23:35:27 +02:00
|
|
|
// verify that it is pointing to a valid script address
|
2014-10-13 02:39:01 +02:00
|
|
|
err = s.validPC()
|
2013-06-12 23:35:27 +02:00
|
|
|
if err != nil {
|
2014-03-14 19:27:01 +01:00
|
|
|
return true, err
|
2013-06-12 23:35:27 +02:00
|
|
|
}
|
2014-10-13 02:39:01 +02:00
|
|
|
opcode := s.scripts[s.scriptidx][s.scriptoff]
|
2013-06-12 23:35:27 +02:00
|
|
|
|
2014-10-13 02:39:01 +02:00
|
|
|
err = opcode.exec(s)
|
2014-03-14 19:27:01 +01:00
|
|
|
if err != nil {
|
|
|
|
return true, err
|
2013-06-12 23:35:27 +02:00
|
|
|
}
|
|
|
|
|
2014-10-13 02:39:01 +02:00
|
|
|
if s.dstack.Depth()+s.astack.Depth() > maxStackSize {
|
2014-10-12 23:40:09 +02:00
|
|
|
return false, ErrStackOverflow
|
2014-03-14 19:35:36 +01:00
|
|
|
}
|
|
|
|
|
2013-06-12 23:35:27 +02:00
|
|
|
// prepare for next instruction
|
2014-10-13 02:39:01 +02:00
|
|
|
s.scriptoff++
|
|
|
|
if s.scriptoff >= len(s.scripts[s.scriptidx]) {
|
2014-03-14 15:52:22 +01:00
|
|
|
// Illegal to have an `if' that straddles two scripts.
|
2014-10-13 02:39:01 +02:00
|
|
|
if err == nil && len(s.condStack) != 1 {
|
2014-10-12 23:40:09 +02:00
|
|
|
return false, ErrStackMissingEndif
|
2014-03-14 15:52:22 +01:00
|
|
|
}
|
|
|
|
|
2014-03-14 18:22:57 +01:00
|
|
|
// alt stack doesn't persist.
|
2014-10-13 02:39:01 +02:00
|
|
|
_ = s.astack.DropN(s.astack.Depth())
|
|
|
|
|
|
|
|
s.numOps = 0 // number of ops is per script.
|
|
|
|
s.scriptoff = 0
|
|
|
|
if s.scriptidx == 0 && s.bip16 {
|
|
|
|
s.scriptidx++
|
|
|
|
s.savedFirstStack = s.GetStack()
|
|
|
|
} else if s.scriptidx == 1 && s.bip16 {
|
2013-06-18 18:39:00 +02:00
|
|
|
// Put us past the end for CheckErrorCondition()
|
2014-10-13 02:39:01 +02:00
|
|
|
s.scriptidx++
|
2013-06-18 18:39:00 +02:00
|
|
|
// We check script ran ok, if so then we pull
|
|
|
|
// the script out of the first stack and executre that.
|
2014-10-13 02:39:01 +02:00
|
|
|
err := s.CheckErrorCondition()
|
2013-06-12 23:35:27 +02:00
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
2013-06-18 18:39:00 +02:00
|
|
|
|
2014-10-13 02:39:01 +02:00
|
|
|
script := s.savedFirstStack[len(s.savedFirstStack)-1]
|
2013-06-12 23:35:27 +02:00
|
|
|
pops, err := parseScript(script)
|
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
2014-10-13 02:39:01 +02:00
|
|
|
s.scripts = append(s.scripts, pops)
|
2013-06-12 23:35:27 +02:00
|
|
|
// Set stack to be the stack from first script
|
|
|
|
// minus the script itself
|
2014-10-13 02:39:01 +02:00
|
|
|
s.SetStack(s.savedFirstStack[:len(s.savedFirstStack)-1])
|
2013-06-18 18:39:00 +02:00
|
|
|
} else {
|
2014-10-13 02:39:01 +02:00
|
|
|
s.scriptidx++
|
2013-06-12 23:35:27 +02:00
|
|
|
}
|
|
|
|
// there are zero length scripts in the wild
|
2014-10-13 02:39:01 +02:00
|
|
|
if s.scriptidx < len(s.scripts) && s.scriptoff >= len(s.scripts[s.scriptidx]) {
|
|
|
|
s.scriptidx++
|
2013-06-12 23:35:27 +02:00
|
|
|
}
|
2014-10-13 02:39:01 +02:00
|
|
|
s.lastcodesep = 0
|
|
|
|
if s.scriptidx >= len(s.scripts) {
|
2014-03-14 19:27:01 +01:00
|
|
|
return true, nil
|
2013-06-12 23:35:27 +02:00
|
|
|
}
|
|
|
|
}
|
2014-03-14 19:27:01 +01:00
|
|
|
return false, nil
|
2013-06-12 23:35:27 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// curPC returns either the current script and offset, or an error if the
|
|
|
|
// position isn't valid.
|
2014-10-13 02:39:01 +02:00
|
|
|
func (s *Script) curPC() (script int, off int, err error) {
|
|
|
|
err = s.validPC()
|
2013-06-12 23:35:27 +02:00
|
|
|
if err != nil {
|
|
|
|
return 0, 0, err
|
|
|
|
}
|
2014-10-13 02:39:01 +02:00
|
|
|
return s.scriptidx, s.scriptoff, nil
|
2013-06-12 23:35:27 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// validPC returns an error if the current script position is valid for
|
|
|
|
// execution, nil otherwise.
|
2014-10-13 02:39:01 +02:00
|
|
|
func (s *Script) validPC() error {
|
|
|
|
if s.scriptidx >= len(s.scripts) {
|
|
|
|
return fmt.Errorf("Past input scripts %v:%v %v:xxxx", s.scriptidx, s.scriptoff, len(s.scripts))
|
2013-06-12 23:35:27 +02:00
|
|
|
}
|
2014-10-13 02:39:01 +02:00
|
|
|
if s.scriptoff >= len(s.scripts[s.scriptidx]) {
|
|
|
|
return fmt.Errorf("Past input scripts %v:%v %v:%04d", s.scriptidx, s.scriptoff, s.scriptidx, len(s.scripts[s.scriptidx]))
|
2013-06-12 23:35:27 +02:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// DisasmScript returns the disassembly string for the script at offset
|
|
|
|
// ``idx''. Where 0 is the scriptSig and 1 is the scriptPubKey.
|
2014-10-13 02:39:01 +02:00
|
|
|
func (s *Script) DisasmScript(idx int) (disstr string, err error) {
|
|
|
|
if idx >= len(s.scripts) {
|
2014-10-12 23:40:09 +02:00
|
|
|
return "", ErrStackInvalidIndex
|
2013-06-12 23:35:27 +02:00
|
|
|
}
|
2014-10-13 02:39:01 +02:00
|
|
|
for i := range s.scripts[idx] {
|
|
|
|
disstr = disstr + s.disasm(idx, i) + "\n"
|
2013-06-12 23:35:27 +02:00
|
|
|
}
|
|
|
|
return disstr, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// DisasmPC returns the string for the disassembly of the opcode that will be
|
|
|
|
// next to execute when Step() is called.
|
2014-10-13 02:39:01 +02:00
|
|
|
func (s *Script) DisasmPC() (disstr string, err error) {
|
|
|
|
scriptidx, scriptoff, err := s.curPC()
|
2013-06-12 23:35:27 +02:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2014-10-13 02:39:01 +02:00
|
|
|
return s.disasm(scriptidx, scriptoff), nil
|
2013-06-12 23:35:27 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// disasm is a helper member to produce the output for DisasmPC and
|
|
|
|
// DisasmScript. It produces the opcode prefixed by the program counter at the
|
|
|
|
// provided position in the script. it does no error checking and leaves that
|
|
|
|
// to the caller to provide a valid offse.
|
2014-10-13 02:39:01 +02:00
|
|
|
func (s *Script) disasm(scriptidx int, scriptoff int) string {
|
2013-06-12 23:35:27 +02:00
|
|
|
return fmt.Sprintf("%02x:%04x: %s", scriptidx, scriptoff,
|
2014-10-13 02:39:01 +02:00
|
|
|
s.scripts[scriptidx][scriptoff].print(false))
|
2013-06-12 23:35:27 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// subScript will return the script since the last OP_CODESEPARATOR
|
|
|
|
func (s *Script) subScript() []parsedOpcode {
|
|
|
|
return s.scripts[s.scriptidx][s.lastcodesep:]
|
|
|
|
}
|
|
|
|
|
|
|
|
// removeOpcode will remove any opcode matching ``opcode'' from the opcode
|
|
|
|
// stream in pkscript
|
|
|
|
func removeOpcode(pkscript []parsedOpcode, opcode byte) []parsedOpcode {
|
2013-09-25 18:38:20 +02:00
|
|
|
retScript := make([]parsedOpcode, 0, len(pkscript))
|
2013-06-12 23:35:27 +02:00
|
|
|
for _, pop := range pkscript {
|
|
|
|
if pop.opcode.value != opcode {
|
|
|
|
retScript = append(retScript, pop)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return retScript
|
|
|
|
}
|
|
|
|
|
|
|
|
// removeOpcodeByData will return the pkscript minus any opcodes that would
|
|
|
|
// push the data in ``data'' to the stack.
|
|
|
|
func removeOpcodeByData(pkscript []parsedOpcode, data []byte) []parsedOpcode {
|
2013-09-25 18:38:20 +02:00
|
|
|
retScript := make([]parsedOpcode, 0, len(pkscript))
|
2013-06-12 23:35:27 +02:00
|
|
|
for _, pop := range pkscript {
|
2014-03-18 18:54:29 +01:00
|
|
|
if !canonicalPush(pop) || !bytes.Contains(pop.data, data) {
|
2013-06-12 23:35:27 +02:00
|
|
|
retScript = append(retScript, pop)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return retScript
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2014-01-04 01:47:00 +01:00
|
|
|
// DisasmString formats a disassembled script for one line printing. When the
|
|
|
|
// script fails to parse, the returned string will contain the disassembled
|
|
|
|
// script up to the point the failure occurred along with the string '[error]'
|
|
|
|
// appended. In addition, the reason the script failed to parse is returned
|
|
|
|
// if the caller wants more information about the failure.
|
2013-06-12 23:35:27 +02:00
|
|
|
func DisasmString(buf []byte) (string, error) {
|
|
|
|
disbuf := ""
|
|
|
|
opcodes, err := parseScript(buf)
|
|
|
|
for _, pop := range opcodes {
|
|
|
|
disbuf += pop.print(true) + " "
|
|
|
|
}
|
|
|
|
if disbuf != "" {
|
|
|
|
disbuf = disbuf[:len(disbuf)-1]
|
|
|
|
}
|
2014-01-04 01:47:00 +01:00
|
|
|
if err != nil {
|
|
|
|
disbuf += "[error]"
|
|
|
|
}
|
|
|
|
return disbuf, err
|
2013-06-12 23:35:27 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// calcScriptHash will, given the a script and hashtype for the current
|
|
|
|
// scriptmachine, calculate the doubleSha256 hash of the transaction and
|
|
|
|
// script to be used for signature signing and verification.
|
2015-02-05 22:16:39 +01:00
|
|
|
func calcScriptHash(script []parsedOpcode, hashType SigHashType, tx *wire.MsgTx, idx int) []byte {
|
2013-06-12 23:35:27 +02:00
|
|
|
|
|
|
|
// remove all instances of OP_CODESEPARATOR still left in the script
|
|
|
|
script = removeOpcode(script, OP_CODESEPARATOR)
|
|
|
|
|
|
|
|
// Make a deep copy of the transaction, zeroing out the script
|
|
|
|
// for all inputs that are not currently being processed.
|
2013-09-10 17:39:29 +02:00
|
|
|
txCopy := tx.Copy()
|
2013-06-12 23:35:27 +02:00
|
|
|
for i := range txCopy.TxIn {
|
2015-02-05 22:16:39 +01:00
|
|
|
var txIn wire.TxIn
|
2013-06-12 23:35:27 +02:00
|
|
|
txIn = *txCopy.TxIn[i]
|
|
|
|
txCopy.TxIn[i] = &txIn
|
2013-09-10 17:39:29 +02:00
|
|
|
if i == idx {
|
|
|
|
// unparseScript cannot fail here, because removeOpcode
|
|
|
|
// above only returns a valid script.
|
|
|
|
sigscript, _ := unparseScript(script)
|
|
|
|
txCopy.TxIn[idx].SignatureScript = sigscript
|
2013-06-12 23:35:27 +02:00
|
|
|
} else {
|
|
|
|
txCopy.TxIn[i].SignatureScript = []byte{}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// Default behaviour has all outputs set up.
|
|
|
|
for i := range txCopy.TxOut {
|
2015-02-05 22:16:39 +01:00
|
|
|
var txOut wire.TxOut
|
2013-06-12 23:35:27 +02:00
|
|
|
txOut = *txCopy.TxOut[i]
|
|
|
|
txCopy.TxOut[i] = &txOut
|
|
|
|
}
|
|
|
|
|
|
|
|
switch hashType & 31 {
|
|
|
|
case SigHashNone:
|
|
|
|
txCopy.TxOut = txCopy.TxOut[0:0] // empty slice
|
|
|
|
for i := range txCopy.TxIn {
|
2013-09-10 17:39:29 +02:00
|
|
|
if i != idx {
|
2013-06-12 23:35:27 +02:00
|
|
|
txCopy.TxIn[i].Sequence = 0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
case SigHashSingle:
|
2013-09-10 17:39:29 +02:00
|
|
|
if idx >= len(txCopy.TxOut) {
|
2013-07-30 23:45:26 +02:00
|
|
|
// This was created by a buggy implementation.
|
|
|
|
// In this case we do the same as bitcoind and bitcoinj
|
|
|
|
// and return 1 (as a uint256 little endian) as an
|
|
|
|
// error. Unfortunately this was not checked anywhere
|
|
|
|
// and thus is treated as the actual
|
|
|
|
// hash.
|
|
|
|
hash := make([]byte, 32)
|
|
|
|
hash[0] = 0x01
|
|
|
|
return hash
|
|
|
|
}
|
|
|
|
// Resize output array to up to and including requested index.
|
2013-09-10 17:39:29 +02:00
|
|
|
txCopy.TxOut = txCopy.TxOut[:idx+1]
|
2013-06-12 23:35:27 +02:00
|
|
|
// all but current output get zeroed out
|
2013-09-10 17:39:29 +02:00
|
|
|
for i := 0; i < idx; i++ {
|
2013-06-12 23:35:27 +02:00
|
|
|
txCopy.TxOut[i].Value = -1
|
|
|
|
txCopy.TxOut[i].PkScript = []byte{}
|
|
|
|
}
|
|
|
|
// Sequence on all other inputs is 0, too.
|
|
|
|
for i := range txCopy.TxIn {
|
2013-09-10 17:39:29 +02:00
|
|
|
if i != idx {
|
2013-06-12 23:35:27 +02:00
|
|
|
txCopy.TxIn[i].Sequence = 0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
default:
|
|
|
|
// XXX bitcoind treats undefined hashtypes like normal
|
|
|
|
// SigHashAll for purposes of hash generation.
|
|
|
|
fallthrough
|
|
|
|
case SigHashOld:
|
|
|
|
fallthrough
|
|
|
|
case SigHashAll:
|
|
|
|
// nothing special here
|
|
|
|
}
|
|
|
|
if hashType&SigHashAnyOneCanPay != 0 {
|
2013-09-10 17:39:29 +02:00
|
|
|
txCopy.TxIn = txCopy.TxIn[idx : idx+1]
|
|
|
|
idx = 0
|
2013-06-12 23:35:27 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
var wbuf bytes.Buffer
|
2013-08-05 22:08:28 +02:00
|
|
|
txCopy.Serialize(&wbuf)
|
2013-06-12 23:35:27 +02:00
|
|
|
// Append LE 4 bytes hash type
|
|
|
|
binary.Write(&wbuf, binary.LittleEndian, uint32(hashType))
|
|
|
|
|
2015-02-05 22:16:39 +01:00
|
|
|
return wire.DoubleSha256(wbuf.Bytes())
|
2013-06-12 23:35:27 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// getStack returns the contents of stack as a byte array bottom up
|
|
|
|
func getStack(stack *Stack) [][]byte {
|
|
|
|
array := make([][]byte, stack.Depth())
|
|
|
|
for i := range array {
|
|
|
|
// PeekByteArry can't fail due to overflow, already checked
|
|
|
|
array[len(array)-i-1], _ =
|
|
|
|
stack.PeekByteArray(i)
|
|
|
|
}
|
|
|
|
return array
|
|
|
|
}
|
|
|
|
|
|
|
|
// setStack sets the stack to the contents of the array where the last item in
|
|
|
|
// the array is the top item in the stack.
|
|
|
|
func setStack(stack *Stack, data [][]byte) {
|
|
|
|
// This can not error. Only errors are for invalid arguments.
|
|
|
|
_ = stack.DropN(stack.Depth())
|
|
|
|
|
|
|
|
for i := range data {
|
|
|
|
stack.PushByteArray(data[i])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetStack returns the contents of the primary stack as an array. where the
|
|
|
|
// last item in the array is the top of the stack.
|
|
|
|
func (s *Script) GetStack() [][]byte {
|
|
|
|
return getStack(&s.dstack)
|
|
|
|
}
|
|
|
|
|
|
|
|
// SetStack sets the contents of the primary stack to the contents of the
|
|
|
|
// provided array where the last item in the array will be the top of the stack.
|
|
|
|
func (s *Script) SetStack(data [][]byte) {
|
|
|
|
setStack(&s.dstack, data)
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetAltStack returns the contents of the primary stack as an array. where the
|
|
|
|
// last item in the array is the top of the stack.
|
|
|
|
func (s *Script) GetAltStack() [][]byte {
|
|
|
|
return getStack(&s.astack)
|
|
|
|
}
|
|
|
|
|
|
|
|
// SetAltStack sets the contents of the primary stack to the contents of the
|
|
|
|
// provided array where the last item in the array will be the top of the stack.
|
|
|
|
func (s *Script) SetAltStack(data [][]byte) {
|
|
|
|
setStack(&s.astack, data)
|
|
|
|
}
|
2013-06-20 19:07:44 +02:00
|
|
|
|
|
|
|
// GetSigOpCount provides a quick count of the number of signature operations
|
|
|
|
// in a script. a CHECKSIG operations counts for 1, and a CHECK_MULTISIG for 20.
|
2013-07-25 16:40:11 +02:00
|
|
|
// If the script fails to parse, then the count up to the point of failure is
|
|
|
|
// returned.
|
2013-07-25 15:27:58 +02:00
|
|
|
func GetSigOpCount(script []byte) int {
|
2013-07-25 16:40:11 +02:00
|
|
|
// We don't check error since parseScript returns the parsed-up-to-error
|
|
|
|
// list of pops.
|
|
|
|
pops, _ := parseScript(script)
|
2013-06-20 19:07:44 +02:00
|
|
|
|
2013-07-25 15:27:58 +02:00
|
|
|
return getSigOpCount(pops, false)
|
2013-06-20 19:07:44 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// GetPreciseSigOpCount returns the number of signature operations in
|
|
|
|
// scriptPubKey. If bip16 is true then scriptSig may be searched for the
|
|
|
|
// Pay-To-Script-Hash script in order to find the precise number of signature
|
2013-07-31 02:31:27 +02:00
|
|
|
// operations in the transaction. If the script fails to parse, then the
|
2013-07-25 16:40:11 +02:00
|
|
|
// count up to the point of failure is returned.
|
2013-07-25 15:27:58 +02:00
|
|
|
func GetPreciseSigOpCount(scriptSig, scriptPubKey []byte, bip16 bool) int {
|
2013-07-25 16:40:11 +02:00
|
|
|
// We don't check error since parseScript returns the parsed-up-to-error
|
|
|
|
// list of pops.
|
|
|
|
pops, _ := parseScript(scriptPubKey)
|
2013-06-20 19:07:44 +02:00
|
|
|
// non P2SH transactions just treated as normal.
|
|
|
|
if !(bip16 && isScriptHash(pops)) {
|
2013-07-25 15:27:58 +02:00
|
|
|
return getSigOpCount(pops, true)
|
2013-06-20 19:07:44 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Ok so this is P2SH, get the contained script and count it..
|
|
|
|
|
|
|
|
sigPops, err := parseScript(scriptSig)
|
|
|
|
if err != nil {
|
2013-07-25 15:27:58 +02:00
|
|
|
return 0
|
2013-06-20 19:07:44 +02:00
|
|
|
}
|
|
|
|
if !isPushOnly(sigPops) || len(sigPops) == 0 {
|
2013-07-25 15:27:58 +02:00
|
|
|
return 0
|
2013-06-20 19:07:44 +02:00
|
|
|
}
|
|
|
|
|
2013-06-21 02:33:56 +02:00
|
|
|
shScript := sigPops[len(sigPops)-1].data
|
2013-06-20 19:07:44 +02:00
|
|
|
// Means that sigPops is jus OP_1 - OP_16, no sigops there.
|
|
|
|
if shScript == nil {
|
2013-07-25 15:27:58 +02:00
|
|
|
return 0
|
2013-06-20 19:07:44 +02:00
|
|
|
}
|
|
|
|
|
2013-07-25 16:40:11 +02:00
|
|
|
shPops, _ := parseScript(shScript)
|
2013-06-20 19:07:44 +02:00
|
|
|
|
2013-07-25 15:27:58 +02:00
|
|
|
return getSigOpCount(shPops, true)
|
2013-06-20 19:07:44 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// getSigOpCount is the implementation function for counting the number of
|
|
|
|
// signature operations in the script provided by pops. If precise mode is
|
|
|
|
// requested then we attempt to count the number of operations for a multisig
|
|
|
|
// op. Otherwise we use the maximum.
|
|
|
|
func getSigOpCount(pops []parsedOpcode, precise bool) int {
|
|
|
|
nSigs := 0
|
|
|
|
for i, pop := range pops {
|
|
|
|
switch pop.opcode.value {
|
|
|
|
case OP_CHECKSIG:
|
2013-06-21 02:33:56 +02:00
|
|
|
fallthrough
|
2013-06-20 19:07:44 +02:00
|
|
|
case OP_CHECKSIGVERIFY:
|
|
|
|
nSigs++
|
2014-01-04 22:13:29 +01:00
|
|
|
case OP_CHECKMULTISIG:
|
2013-06-21 02:33:56 +02:00
|
|
|
fallthrough
|
2013-06-20 19:07:44 +02:00
|
|
|
case OP_CHECKMULTISIGVERIFY:
|
|
|
|
// If we are being precise then look for familiar
|
|
|
|
// patterns for multisig, for now all we recognise is
|
2013-06-21 02:33:56 +02:00
|
|
|
// OP_1 - OP_16 to signify the number of pubkeys.
|
2013-06-20 19:07:44 +02:00
|
|
|
// Otherwise, we use the max of 20.
|
|
|
|
if precise && i > 0 &&
|
2013-06-21 02:33:56 +02:00
|
|
|
pops[i-1].opcode.value >= OP_1 &&
|
|
|
|
pops[i-1].opcode.value <= OP_16 {
|
|
|
|
nSigs += int(pops[i-1].opcode.value -
|
2013-06-20 19:07:44 +02:00
|
|
|
(OP_1 - 1))
|
|
|
|
} else {
|
|
|
|
nSigs += MaxPubKeysPerMultiSig
|
|
|
|
}
|
|
|
|
default:
|
|
|
|
// not a sigop.
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nSigs
|
|
|
|
}
|
2013-09-10 17:39:29 +02:00
|
|
|
|
2014-02-20 18:39:03 +01:00
|
|
|
// payToPubKeyHashScript creates a new script to pay a transaction
|
|
|
|
// output to a 20-byte pubkey hash. It is expected that the input is a valid
|
|
|
|
// hash.
|
2014-12-20 08:34:39 +01:00
|
|
|
func payToPubKeyHashScript(pubKeyHash []byte) ([]byte, error) {
|
2014-02-20 18:42:06 +01:00
|
|
|
return NewScriptBuilder().AddOp(OP_DUP).AddOp(OP_HASH160).
|
|
|
|
AddData(pubKeyHash).AddOp(OP_EQUALVERIFY).AddOp(OP_CHECKSIG).
|
2014-02-20 18:39:03 +01:00
|
|
|
Script()
|
2013-09-10 17:39:29 +02:00
|
|
|
}
|
|
|
|
|
2014-02-20 18:39:03 +01:00
|
|
|
// payToScriptHashScript creates a new script to pay a transaction output to a
|
|
|
|
// script hash. It is expected that the input is a valid hash.
|
2014-12-20 08:34:39 +01:00
|
|
|
func payToScriptHashScript(scriptHash []byte) ([]byte, error) {
|
2014-02-20 18:42:06 +01:00
|
|
|
return NewScriptBuilder().AddOp(OP_HASH160).AddData(scriptHash).
|
2014-02-21 09:09:55 +01:00
|
|
|
AddOp(OP_EQUAL).Script()
|
2014-01-03 20:35:31 +01:00
|
|
|
}
|
|
|
|
|
2014-02-20 19:37:42 +01:00
|
|
|
// payToPubkeyScript creates a new script to pay a transaction output to a
|
|
|
|
// public key. It is expected that the input is a valid pubkey.
|
2014-12-20 08:34:39 +01:00
|
|
|
func payToPubKeyScript(serializedPubKey []byte) ([]byte, error) {
|
2014-02-20 19:37:42 +01:00
|
|
|
return NewScriptBuilder().AddData(serializedPubKey).
|
2014-02-21 09:09:55 +01:00
|
|
|
AddOp(OP_CHECKSIG).Script()
|
2014-02-20 19:37:42 +01:00
|
|
|
}
|
|
|
|
|
2014-01-03 20:35:31 +01:00
|
|
|
// PayToAddrScript creates a new script to pay a transaction output to a the
|
2014-02-20 19:37:42 +01:00
|
|
|
// specified address.
|
2014-01-03 20:35:31 +01:00
|
|
|
func PayToAddrScript(addr btcutil.Address) ([]byte, error) {
|
|
|
|
switch addr := addr.(type) {
|
|
|
|
case *btcutil.AddressPubKeyHash:
|
|
|
|
if addr == nil {
|
|
|
|
return nil, ErrUnsupportedAddress
|
|
|
|
}
|
2014-12-20 08:34:39 +01:00
|
|
|
return payToPubKeyHashScript(addr.ScriptAddress())
|
2014-01-03 20:35:31 +01:00
|
|
|
|
|
|
|
case *btcutil.AddressScriptHash:
|
|
|
|
if addr == nil {
|
|
|
|
return nil, ErrUnsupportedAddress
|
|
|
|
}
|
2014-12-20 08:34:39 +01:00
|
|
|
return payToScriptHashScript(addr.ScriptAddress())
|
2014-02-20 19:37:42 +01:00
|
|
|
|
|
|
|
case *btcutil.AddressPubKey:
|
|
|
|
if addr == nil {
|
|
|
|
return nil, ErrUnsupportedAddress
|
|
|
|
}
|
2014-12-20 08:34:39 +01:00
|
|
|
return payToPubKeyScript(addr.ScriptAddress())
|
2014-01-03 20:35:31 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil, ErrUnsupportedAddress
|
|
|
|
}
|
|
|
|
|
2014-02-21 01:20:24 +01:00
|
|
|
// ErrBadNumRequired is returned from MultiSigScript when nrequired is larger
|
|
|
|
// than the number of provided public keys.
|
2014-02-21 09:09:55 +01:00
|
|
|
var ErrBadNumRequired = errors.New("more signatures required than keys present")
|
2014-02-21 01:20:24 +01:00
|
|
|
|
|
|
|
// MultiSigScript returns a valid script for a multisignature redemption where
|
|
|
|
// nrequired of the keys in pubkeys are required to have signed the transaction
|
|
|
|
// for success. An ErrBadNumRequired will be returned if nrequired is larger than
|
|
|
|
// the number of keys provided.
|
|
|
|
func MultiSigScript(pubkeys []*btcutil.AddressPubKey, nrequired int) ([]byte, error) {
|
|
|
|
if len(pubkeys) < nrequired {
|
|
|
|
return nil, ErrBadNumRequired
|
|
|
|
}
|
|
|
|
|
|
|
|
builder := NewScriptBuilder().AddInt64(int64(nrequired))
|
2014-02-21 09:09:55 +01:00
|
|
|
for _, key := range pubkeys {
|
2014-02-21 01:20:24 +01:00
|
|
|
builder.AddData(key.ScriptAddress())
|
|
|
|
}
|
|
|
|
builder.AddInt64(int64(len(pubkeys)))
|
|
|
|
builder.AddOp(OP_CHECKMULTISIG)
|
|
|
|
|
2014-12-20 08:34:39 +01:00
|
|
|
return builder.Script()
|
2014-02-21 01:20:24 +01:00
|
|
|
}
|
|
|
|
|
2013-09-10 17:39:29 +02:00
|
|
|
// SignatureScript creates an input signature script for tx to spend
|
2014-08-25 22:09:23 +02:00
|
|
|
// BTC sent from a previous output to the owner of privKey. tx must
|
2013-09-10 17:39:29 +02:00
|
|
|
// include all transaction inputs and outputs, however txin scripts are
|
|
|
|
// allowed to be filled or empty. The returned script is calculated to
|
|
|
|
// be used as the idx'th txin sigscript for tx. subscript is the PkScript
|
2014-08-25 22:09:23 +02:00
|
|
|
// of the previous output being used as the idx'th input. privKey is
|
2013-09-10 17:39:29 +02:00
|
|
|
// serialized in either a compressed or uncompressed format based on
|
2014-08-25 22:09:23 +02:00
|
|
|
// compress. This format must match the same format used to generate
|
2013-09-10 17:39:29 +02:00
|
|
|
// the payment address, or the script validation will fail.
|
2015-02-05 22:16:39 +01:00
|
|
|
func SignatureScript(tx *wire.MsgTx, idx int, subscript []byte, hashType SigHashType, privKey *btcec.PrivateKey, compress bool) ([]byte, error) {
|
2014-10-31 13:14:41 +01:00
|
|
|
sig, err := RawTxInSignature(tx, idx, subscript, hashType, privKey)
|
2014-04-18 00:15:30 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2014-08-25 22:09:23 +02:00
|
|
|
pk := (*btcec.PublicKey)(&privKey.PublicKey)
|
2014-04-18 00:15:30 +02:00
|
|
|
var pkData []byte
|
|
|
|
if compress {
|
|
|
|
pkData = pk.SerializeCompressed()
|
|
|
|
} else {
|
|
|
|
pkData = pk.SerializeUncompressed()
|
|
|
|
}
|
|
|
|
|
2014-12-20 08:34:39 +01:00
|
|
|
return NewScriptBuilder().AddData(sig).AddData(pkData).Script()
|
2013-09-10 17:39:29 +02:00
|
|
|
}
|
|
|
|
|
2014-10-31 13:14:41 +01:00
|
|
|
// RawTxInSignature returns the serialized ECDSA signature for the input
|
|
|
|
// idx of the given transaction, with hashType appended to it.
|
2015-02-05 22:16:39 +01:00
|
|
|
func RawTxInSignature(tx *wire.MsgTx, idx int, subScript []byte,
|
2014-10-13 14:47:44 +02:00
|
|
|
hashType SigHashType, key *btcec.PrivateKey) ([]byte, error) {
|
2014-04-18 00:15:30 +02:00
|
|
|
parsedScript, err := parseScript(subScript)
|
2013-09-10 17:39:29 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("cannot parse output script: %v", err)
|
|
|
|
}
|
|
|
|
hash := calcScriptHash(parsedScript, hashType, tx, idx)
|
2014-09-29 23:31:26 +02:00
|
|
|
signature, err := key.Sign(hash)
|
2013-09-10 17:39:29 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("cannot sign tx input: %s", err)
|
|
|
|
}
|
|
|
|
|
2014-09-29 23:31:26 +02:00
|
|
|
return append(signature.Serialize(), byte(hashType)), nil
|
2014-04-18 00:15:30 +02:00
|
|
|
}
|
|
|
|
|
2015-02-05 22:16:39 +01:00
|
|
|
func p2pkSignatureScript(tx *wire.MsgTx, idx int, subScript []byte, hashType SigHashType, privKey *btcec.PrivateKey) ([]byte, error) {
|
2014-10-31 13:14:41 +01:00
|
|
|
sig, err := RawTxInSignature(tx, idx, subScript, hashType, privKey)
|
2014-04-18 00:15:30 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2013-09-10 17:39:29 +02:00
|
|
|
}
|
2014-02-20 18:39:03 +01:00
|
|
|
|
2014-12-20 08:34:39 +01:00
|
|
|
return NewScriptBuilder().AddData(sig).Script()
|
2014-04-18 00:15:30 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// signMultiSig signs as many of the outputs in the provided multisig script as
|
|
|
|
// possible. It returns the generated script and a boolean if the script fulfils
|
|
|
|
// the contract (i.e. nrequired signatures are provided). Since it is arguably
|
|
|
|
// legal to not be able to sign any of the outputs, no error is returned.
|
2015-02-05 22:16:39 +01:00
|
|
|
func signMultiSig(tx *wire.MsgTx, idx int, subScript []byte, hashType SigHashType,
|
2014-04-18 00:15:30 +02:00
|
|
|
addresses []btcutil.Address, nRequired int, kdb KeyDB) ([]byte, bool) {
|
|
|
|
// We start with a single OP_FALSE to work around the (now standard)
|
|
|
|
// but in the reference implementation that causes a spurious pop at
|
|
|
|
// the end of OP_CHECKMULTISIG.
|
|
|
|
builder := NewScriptBuilder().AddOp(OP_FALSE)
|
|
|
|
signed := 0
|
|
|
|
for _, addr := range addresses {
|
|
|
|
key, _, err := kdb.GetKey(addr)
|
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
2014-10-31 13:14:41 +01:00
|
|
|
sig, err := RawTxInSignature(tx, idx, subScript, hashType, key)
|
2014-04-18 00:15:30 +02:00
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
builder.AddData(sig)
|
|
|
|
signed++
|
|
|
|
if signed == nRequired {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2014-12-20 08:34:39 +01:00
|
|
|
script, _ := builder.Script()
|
|
|
|
return script, signed == nRequired
|
2014-04-18 00:15:30 +02:00
|
|
|
}
|
|
|
|
|
2015-02-06 06:18:27 +01:00
|
|
|
func sign(chainParams *chaincfg.Params, tx *wire.MsgTx, idx int,
|
|
|
|
subScript []byte, hashType SigHashType, kdb KeyDB, sdb ScriptDB) ([]byte,
|
|
|
|
ScriptClass, []btcutil.Address, int, error) {
|
2014-04-18 00:15:30 +02:00
|
|
|
|
2015-02-06 06:18:27 +01:00
|
|
|
class, addresses, nrequired, err := ExtractPkScriptAddrs(subScript,
|
|
|
|
chainParams)
|
2014-04-18 00:15:30 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, NonStandardTy, nil, 0, err
|
|
|
|
}
|
|
|
|
|
|
|
|
switch class {
|
|
|
|
case PubKeyTy:
|
|
|
|
// look up key for address
|
|
|
|
key, _, err := kdb.GetKey(addresses[0])
|
|
|
|
if err != nil {
|
|
|
|
return nil, class, nil, 0, err
|
|
|
|
}
|
|
|
|
|
|
|
|
script, err := p2pkSignatureScript(tx, idx, subScript, hashType,
|
|
|
|
key)
|
|
|
|
if err != nil {
|
|
|
|
return nil, class, nil, 0, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return script, class, addresses, nrequired, nil
|
|
|
|
case PubKeyHashTy:
|
|
|
|
// look up key for address
|
|
|
|
key, compressed, err := kdb.GetKey(addresses[0])
|
|
|
|
if err != nil {
|
|
|
|
return nil, class, nil, 0, err
|
|
|
|
}
|
|
|
|
|
|
|
|
script, err := SignatureScript(tx, idx, subScript, hashType,
|
|
|
|
key, compressed)
|
|
|
|
if err != nil {
|
|
|
|
return nil, class, nil, 0, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return script, class, addresses, nrequired, nil
|
|
|
|
case ScriptHashTy:
|
|
|
|
script, err := sdb.GetScript(addresses[0])
|
|
|
|
if err != nil {
|
|
|
|
return nil, class, nil, 0, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return script, class, addresses, nrequired, nil
|
|
|
|
case MultiSigTy:
|
|
|
|
script, _ := signMultiSig(tx, idx, subScript, hashType,
|
|
|
|
addresses, nrequired, kdb)
|
|
|
|
return script, class, addresses, nrequired, nil
|
|
|
|
case NullDataTy:
|
|
|
|
return nil, class, nil, 0,
|
|
|
|
errors.New("can't sign NULLDATA transactions")
|
|
|
|
default:
|
|
|
|
return nil, class, nil, 0,
|
|
|
|
errors.New("can't sign unknown transactions")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// mergeScripts merges sigScript and prevScript assuming they are both
|
|
|
|
// partial solutions for pkScript spending output idx of tx. class, addresses
|
|
|
|
// and nrequired are the result of extracting the addresses from pkscript.
|
|
|
|
// The return value is the best effort merging of the two scripts. Calling this
|
|
|
|
// function with addresses, class and nrequired that do not match pkScript is
|
|
|
|
// an error and results in undefined behaviour.
|
2015-02-06 06:18:27 +01:00
|
|
|
func mergeScripts(chainParams *chaincfg.Params, tx *wire.MsgTx, idx int,
|
2014-04-18 00:15:30 +02:00
|
|
|
pkScript []byte, class ScriptClass, addresses []btcutil.Address,
|
|
|
|
nRequired int, sigScript, prevScript []byte) []byte {
|
|
|
|
|
|
|
|
// TODO(oga) the scripthash and multisig paths here are overly
|
|
|
|
// inefficient in that they will recompute already known data.
|
|
|
|
// some internal refactoring could probably make this avoid needless
|
|
|
|
// extra calculations.
|
|
|
|
switch class {
|
|
|
|
case ScriptHashTy:
|
|
|
|
// Remove the last push in the script and then recurse.
|
|
|
|
// this could be a lot less inefficient.
|
|
|
|
sigPops, err := parseScript(sigScript)
|
|
|
|
if err != nil || len(sigPops) == 0 {
|
|
|
|
return prevScript
|
|
|
|
}
|
|
|
|
prevPops, err := parseScript(prevScript)
|
|
|
|
if err != nil || len(prevPops) == 0 {
|
|
|
|
return sigScript
|
|
|
|
}
|
|
|
|
|
|
|
|
// assume that script in sigPops is the correct one, we just
|
|
|
|
// made it.
|
|
|
|
script := sigPops[len(sigPops)-1].data
|
|
|
|
|
|
|
|
// We already know this information somewhere up the stack.
|
|
|
|
class, addresses, nrequired, err :=
|
2015-02-06 06:18:27 +01:00
|
|
|
ExtractPkScriptAddrs(script, chainParams)
|
2014-04-18 00:15:30 +02:00
|
|
|
|
|
|
|
// regenerate scripts.
|
|
|
|
sigScript, _ := unparseScript(sigPops)
|
|
|
|
prevScript, _ := unparseScript(prevPops)
|
|
|
|
|
|
|
|
// Merge
|
2015-02-06 06:18:27 +01:00
|
|
|
mergedScript := mergeScripts(chainParams, tx, idx, script,
|
|
|
|
class, addresses, nrequired, sigScript, prevScript)
|
2014-04-18 00:15:30 +02:00
|
|
|
|
|
|
|
// Reappend the script and return the result.
|
|
|
|
builder := NewScriptBuilder()
|
|
|
|
builder.script = mergedScript
|
|
|
|
builder.AddData(script)
|
2014-12-20 08:34:39 +01:00
|
|
|
finalScript, _ := builder.Script()
|
|
|
|
return finalScript
|
2014-04-18 00:15:30 +02:00
|
|
|
case MultiSigTy:
|
|
|
|
return mergeMultiSig(tx, idx, addresses, nRequired, pkScript,
|
|
|
|
sigScript, prevScript)
|
|
|
|
|
|
|
|
// It doesn't actualy make sense to merge anything other than multiig
|
|
|
|
// and scripthash (because it could contain multisig). Everything else
|
|
|
|
// has either zero signature, can't be spent, or has a single signature
|
|
|
|
// which is either present or not. The other two cases are handled
|
|
|
|
// above. In the conflict case here we just assume the longest is
|
|
|
|
// correct (this matches behaviour of the reference implementation).
|
|
|
|
default:
|
|
|
|
if len(sigScript) > len(prevScript) {
|
|
|
|
return sigScript
|
|
|
|
}
|
|
|
|
return prevScript
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// mergeMultiSig combines the two signature scripts sigScript and prevScript
|
|
|
|
// that both provide signatures for pkScript in output idx of tx. addresses
|
|
|
|
// and nRequired should be the results from extracting the addresses from
|
|
|
|
// pkScript. Since this function is internal only we assume that the arguments
|
|
|
|
// have come from other functions internally and thus are all consistent with
|
|
|
|
// each other, behaviour is undefined if this contract is broken.
|
2015-02-05 22:16:39 +01:00
|
|
|
func mergeMultiSig(tx *wire.MsgTx, idx int, addresses []btcutil.Address,
|
2014-04-18 00:15:30 +02:00
|
|
|
nRequired int, pkScript, sigScript, prevScript []byte) []byte {
|
|
|
|
|
|
|
|
// This is an internal only function and we already parsed this script
|
|
|
|
// as ok for multisig (this is how we got here), so if this fails then
|
|
|
|
// all assumptions are broken and who knows which way is up?
|
|
|
|
pkPops, _ := parseScript(pkScript)
|
|
|
|
|
|
|
|
sigPops, err := parseScript(sigScript)
|
|
|
|
if err != nil || len(sigPops) == 0 {
|
|
|
|
return prevScript
|
|
|
|
}
|
|
|
|
|
|
|
|
prevPops, err := parseScript(prevScript)
|
|
|
|
if err != nil || len(prevPops) == 0 {
|
|
|
|
return sigScript
|
|
|
|
}
|
|
|
|
|
|
|
|
// Convenience function to avoid duplication.
|
|
|
|
extractSigs := func(pops []parsedOpcode, sigs [][]byte) [][]byte {
|
|
|
|
for _, pop := range pops {
|
|
|
|
if len(pop.data) != 0 {
|
|
|
|
sigs = append(sigs, pop.data)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return sigs
|
|
|
|
}
|
|
|
|
|
|
|
|
possibleSigs := make([][]byte, 0, len(sigPops)+len(prevPops))
|
|
|
|
possibleSigs = extractSigs(sigPops, possibleSigs)
|
|
|
|
possibleSigs = extractSigs(prevPops, possibleSigs)
|
|
|
|
|
|
|
|
// Now we need to match the signatures to pubkeys, the only real way to
|
|
|
|
// do that is to try to verify them all and match it to the pubkey
|
|
|
|
// that verifies it. we then can go through the addresses in order
|
|
|
|
// to build our script. Anything that doesn't parse or doesn't verify we
|
|
|
|
// throw away.
|
|
|
|
addrToSig := make(map[string][]byte)
|
|
|
|
sigLoop:
|
|
|
|
for _, sig := range possibleSigs {
|
|
|
|
|
|
|
|
// can't have a valid signature that doesn't at least have a
|
|
|
|
// hashtype, in practise it is even longer than this. but
|
|
|
|
// that'll be checked next.
|
|
|
|
if len(sig) < 1 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
tSig := sig[:len(sig)-1]
|
2014-10-11 21:55:28 +02:00
|
|
|
hashType := SigHashType(sig[len(sig)-1])
|
2014-04-18 00:15:30 +02:00
|
|
|
|
|
|
|
pSig, err := btcec.ParseDERSignature(tSig, btcec.S256())
|
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// We have to do this each round since hash types may vary
|
|
|
|
// between signatures and so the hash will vary. We can,
|
|
|
|
// however, assume no sigs etc are in the script since that
|
|
|
|
// would make the transaction nonstandard and thus not
|
|
|
|
// MultiSigTy, so we just need to hash the full thing.
|
|
|
|
hash := calcScriptHash(pkPops, hashType, tx, idx)
|
|
|
|
|
|
|
|
for _, addr := range addresses {
|
|
|
|
// All multisig addresses should be pubkey addreses
|
|
|
|
// it is an error to call this internal function with
|
|
|
|
// bad input.
|
|
|
|
pkaddr := addr.(*btcutil.AddressPubKey)
|
|
|
|
|
|
|
|
pubKey := pkaddr.PubKey()
|
|
|
|
|
|
|
|
// If it matches we put it in the map. We only
|
|
|
|
// can take one signature per public key so if we
|
|
|
|
// already have one, we can throw this away.
|
2014-09-29 23:31:26 +02:00
|
|
|
if pSig.Verify(hash, pubKey) {
|
2014-04-18 00:15:30 +02:00
|
|
|
aStr := addr.EncodeAddress()
|
|
|
|
if _, ok := addrToSig[aStr]; !ok {
|
|
|
|
addrToSig[aStr] = sig
|
|
|
|
}
|
|
|
|
continue sigLoop
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Extra opcode to handle the extra arg consumed (due to previous bugs
|
|
|
|
// in the reference implementation).
|
|
|
|
builder := NewScriptBuilder().AddOp(OP_FALSE)
|
|
|
|
doneSigs := 0
|
|
|
|
// This assumes that addresses are in the same order as in the script.
|
|
|
|
for _, addr := range addresses {
|
|
|
|
sig, ok := addrToSig[addr.EncodeAddress()]
|
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
builder.AddData(sig)
|
|
|
|
doneSigs++
|
|
|
|
if doneSigs == nRequired {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// padding for missing ones.
|
|
|
|
for i := doneSigs; i < nRequired; i++ {
|
|
|
|
builder.AddOp(OP_0)
|
|
|
|
}
|
|
|
|
|
2014-12-20 08:34:39 +01:00
|
|
|
script, _ := builder.Script()
|
|
|
|
return script
|
2014-04-18 00:15:30 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// KeyDB is an interface type provided to SignTxOutput, it encapsulates
|
|
|
|
// any user state required to get the private keys for an address.
|
|
|
|
type KeyDB interface {
|
2014-09-29 23:31:26 +02:00
|
|
|
GetKey(btcutil.Address) (*btcec.PrivateKey, bool, error)
|
2014-04-18 00:15:30 +02:00
|
|
|
}
|
|
|
|
|
2014-09-29 23:31:26 +02:00
|
|
|
// KeyClosure implements ScriptDB with a closure
|
|
|
|
type KeyClosure func(btcutil.Address) (*btcec.PrivateKey, bool, error)
|
2014-04-18 00:15:30 +02:00
|
|
|
|
|
|
|
// GetKey implements KeyDB by returning the result of calling the closure
|
2014-09-29 23:31:26 +02:00
|
|
|
func (kc KeyClosure) GetKey(address btcutil.Address) (*btcec.PrivateKey,
|
2014-04-18 00:15:30 +02:00
|
|
|
bool, error) {
|
|
|
|
return kc(address)
|
|
|
|
}
|
|
|
|
|
|
|
|
// ScriptDB is an interface type provided to SignTxOutput, it encapsulates
|
|
|
|
// any user state required to get the scripts for an pay-to-script-hash address.
|
|
|
|
type ScriptDB interface {
|
|
|
|
GetScript(btcutil.Address) ([]byte, error)
|
|
|
|
}
|
|
|
|
|
|
|
|
// ScriptClosure implements ScriptDB with a closure
|
|
|
|
type ScriptClosure func(btcutil.Address) ([]byte, error)
|
|
|
|
|
|
|
|
// GetScript implements ScriptDB by returning the result of calling the closure
|
|
|
|
func (sc ScriptClosure) GetScript(address btcutil.Address) ([]byte, error) {
|
|
|
|
return sc(address)
|
|
|
|
}
|
|
|
|
|
|
|
|
// SignTxOutput signs output idx of the given tx to resolve the script given in
|
|
|
|
// pkScript with a signature type of hashType. Any keys required will be
|
|
|
|
// looked up by calling getKey() with the string of the given address.
|
2014-10-10 12:43:32 +02:00
|
|
|
// Any pay-to-script-hash signatures will be similarly looked up by calling
|
2014-04-18 00:15:30 +02:00
|
|
|
// getScript. If previousScript is provided then the results in previousScript
|
|
|
|
// will be merged in a type-dependant manner with the newly generated.
|
|
|
|
// signature script.
|
2015-02-06 06:18:27 +01:00
|
|
|
func SignTxOutput(chainParams *chaincfg.Params, tx *wire.MsgTx, idx int,
|
2014-10-11 21:55:28 +02:00
|
|
|
pkScript []byte, hashType SigHashType, kdb KeyDB, sdb ScriptDB,
|
2014-04-18 00:15:30 +02:00
|
|
|
previousScript []byte) ([]byte, error) {
|
|
|
|
|
2015-02-06 06:18:27 +01:00
|
|
|
sigScript, class, addresses, nrequired, err := sign(chainParams, tx,
|
|
|
|
idx, pkScript, hashType, kdb, sdb)
|
2014-04-18 00:15:30 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if class == ScriptHashTy {
|
|
|
|
// TODO keep the sub addressed and pass down to merge.
|
2015-02-06 06:18:27 +01:00
|
|
|
realSigScript, _, _, _, err := sign(chainParams, tx, idx,
|
|
|
|
sigScript, hashType, kdb, sdb)
|
2014-04-18 00:15:30 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// This is a bad thing. Append the p2sh script as the last
|
|
|
|
// push in the script.
|
|
|
|
builder := NewScriptBuilder()
|
|
|
|
builder.script = realSigScript
|
|
|
|
builder.AddData(sigScript)
|
|
|
|
|
2014-12-20 08:34:39 +01:00
|
|
|
sigScript, _ = builder.Script()
|
2014-04-18 00:15:30 +02:00
|
|
|
// TODO keep a copy of the script for merging.
|
|
|
|
}
|
|
|
|
|
|
|
|
// Merge scripts. with any previous data, if any.
|
2015-02-06 06:18:27 +01:00
|
|
|
mergedScript := mergeScripts(chainParams, tx, idx, pkScript, class,
|
|
|
|
addresses, nrequired, sigScript, previousScript)
|
2014-04-18 00:15:30 +02:00
|
|
|
return mergedScript, nil
|
2013-09-10 17:39:29 +02:00
|
|
|
}
|
|
|
|
|
2013-10-09 01:13:52 +02:00
|
|
|
// expectedInputs returns the number of arguments required by a script.
|
|
|
|
// If the script is of unnown type such that the number can not be determined
|
2014-02-20 18:19:48 +01:00
|
|
|
// then -1 is returned. We are an internal function and thus assume that class
|
2013-10-09 01:13:52 +02:00
|
|
|
// is the real class of pops (and we can thus assume things that were
|
|
|
|
// determined while finding out the type).
|
|
|
|
func expectedInputs(pops []parsedOpcode, class ScriptClass) int {
|
|
|
|
// count needed inputs.
|
|
|
|
switch class {
|
|
|
|
case PubKeyTy:
|
|
|
|
return 1
|
|
|
|
case PubKeyHashTy:
|
|
|
|
return 2
|
|
|
|
case ScriptHashTy:
|
|
|
|
// Not including script, handled below.
|
|
|
|
return 1
|
|
|
|
case MultiSigTy:
|
|
|
|
// Standard multisig has a push a small number for the number
|
2014-03-17 05:07:20 +01:00
|
|
|
// of sigs and number of keys. Check the first push instruction
|
|
|
|
// to see how many arguments are expected. typeOfScript already
|
|
|
|
// checked this so we know it'll be a small int. Also, due to
|
|
|
|
// the original bitcoind bug where OP_CHECKMULTISIG pops an
|
|
|
|
// additional item from the stack, add an extra expected input
|
|
|
|
// for the extra push that is required to compensate.
|
|
|
|
return asSmallInt(pops[0].opcode) + 1
|
2013-11-14 22:05:20 +01:00
|
|
|
case NullDataTy:
|
|
|
|
fallthrough
|
2013-10-09 01:13:52 +02:00
|
|
|
default:
|
|
|
|
return -1
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-10-13 02:39:01 +02:00
|
|
|
// ScriptInfo houses information about a script pair that is determined by
|
|
|
|
// CalcScriptInfo.
|
2013-10-09 01:13:52 +02:00
|
|
|
type ScriptInfo struct {
|
|
|
|
// The class of the sigscript, equivalent to calling GetScriptClass
|
|
|
|
// on the sigScript.
|
|
|
|
PkScriptClass ScriptClass
|
2014-10-13 02:39:01 +02:00
|
|
|
|
|
|
|
// NumInputs is the number of inputs provided by the pkScript.
|
2013-10-09 01:13:52 +02:00
|
|
|
NumInputs int
|
2014-10-13 02:39:01 +02:00
|
|
|
|
|
|
|
// ExpectedInputs is the number of outputs required by sigScript and any
|
2013-10-09 01:13:52 +02:00
|
|
|
// pay-to-script-hash scripts. The number will be -1 if unknown.
|
|
|
|
ExpectedInputs int
|
2014-10-13 02:39:01 +02:00
|
|
|
|
|
|
|
// SigOps is the nubmer of signature operations in the script pair.
|
2013-10-09 01:13:52 +02:00
|
|
|
SigOps int
|
|
|
|
}
|
|
|
|
|
|
|
|
// CalcScriptInfo returns a structure providing data about the scriptpair that
|
|
|
|
// are provided as arguments. It will error if the pair is in someway invalid
|
2014-01-06 19:14:43 +01:00
|
|
|
// such that they can not be analysed, i.e. if they do not parse or the
|
2013-10-09 01:13:52 +02:00
|
|
|
// pkScript is not a push-only script
|
|
|
|
func CalcScriptInfo(sigscript, pkscript []byte, bip16 bool) (*ScriptInfo, error) {
|
|
|
|
si := new(ScriptInfo)
|
|
|
|
// parse both scripts.
|
|
|
|
sigPops, err := parseScript(sigscript)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
pkPops, err := parseScript(pkscript)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// push only sigScript makes little sense.
|
|
|
|
si.PkScriptClass = typeOfScript(pkPops)
|
|
|
|
|
|
|
|
// Can't have a pkScript that doesn't just push data.
|
|
|
|
if !isPushOnly(sigPops) {
|
2014-10-12 23:40:09 +02:00
|
|
|
return nil, ErrStackNonPushOnly
|
2013-10-09 01:13:52 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
si.ExpectedInputs = expectedInputs(pkPops, si.PkScriptClass)
|
|
|
|
// all entries push to stack (or are OP_RESERVED and exec will fail).
|
|
|
|
si.NumInputs = len(sigPops)
|
|
|
|
|
|
|
|
if si.PkScriptClass == ScriptHashTy && bip16 {
|
|
|
|
// grab the last push instruction in the script and pull out the
|
|
|
|
// data.
|
|
|
|
script := sigPops[len(sigPops)-1].data
|
|
|
|
// check for existance and error else.
|
|
|
|
shPops, err := parseScript(script)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
shClass := typeOfScript(shPops)
|
|
|
|
|
|
|
|
shInputs := expectedInputs(shPops, shClass)
|
|
|
|
if shInputs == -1 {
|
|
|
|
// We have no fucking clue, then.
|
|
|
|
si.ExpectedInputs = -1
|
|
|
|
} else {
|
|
|
|
si.ExpectedInputs += shInputs
|
|
|
|
}
|
|
|
|
si.SigOps = getSigOpCount(shPops, true)
|
|
|
|
} else {
|
|
|
|
si.SigOps = getSigOpCount(pkPops, true)
|
|
|
|
}
|
|
|
|
|
|
|
|
return si, nil
|
|
|
|
}
|
2013-11-14 18:14:25 +01:00
|
|
|
|
2014-02-19 23:17:02 +01:00
|
|
|
// asSmallInt returns the passed opcode, which must be true according to
|
|
|
|
// isSmallInt(), as an integer.
|
|
|
|
func asSmallInt(op *opcode) int {
|
|
|
|
if op.value == OP_0 {
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
|
|
|
|
return int(op.value - (OP_1 - 1))
|
|
|
|
}
|
|
|
|
|
2013-11-14 18:14:25 +01:00
|
|
|
// CalcMultiSigStats returns the number of public keys and signatures from
|
|
|
|
// a multi-signature transaction script. The passed script MUST already be
|
|
|
|
// known to be a multi-signature script.
|
|
|
|
func CalcMultiSigStats(script []byte) (int, int, error) {
|
|
|
|
pops, err := parseScript(script)
|
|
|
|
if err != nil {
|
|
|
|
return 0, 0, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// A multi-signature script is of the pattern:
|
|
|
|
// NUM_SIGS PUBKEY PUBKEY PUBKEY... NUM_PUBKEYS OP_CHECKMULTISIG
|
|
|
|
// Therefore the number of signatures is the oldest item on the stack
|
|
|
|
// and the number of pubkeys is the 2nd to last. Also, the absolute
|
|
|
|
// minimum for a multi-signature script is 1 pubkey, so at least 4
|
|
|
|
// items must be on the stack per:
|
|
|
|
// OP_1 PUBKEY OP_1 OP_CHECKMULTISIG
|
|
|
|
if len(pops) < 4 {
|
2014-10-12 23:40:09 +02:00
|
|
|
return 0, 0, ErrStackUnderflow
|
2013-11-14 18:14:25 +01:00
|
|
|
}
|
|
|
|
|
2014-02-19 23:17:02 +01:00
|
|
|
numSigs := asSmallInt(pops[0].opcode)
|
|
|
|
numPubKeys := asSmallInt(pops[len(pops)-2].opcode)
|
2013-11-14 18:14:25 +01:00
|
|
|
return numPubKeys, numSigs, nil
|
|
|
|
}
|
2014-05-08 19:14:01 +02:00
|
|
|
|
|
|
|
// PushedData returns an array of byte slices containing any pushed data found
|
|
|
|
// in the passed script. This includes OP_0, but not OP_1 - OP_16.
|
|
|
|
func PushedData(script []byte) ([][]byte, error) {
|
|
|
|
pops, err := parseScript(script)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
var data [][]byte
|
|
|
|
for _, pop := range pops {
|
|
|
|
if pop.data != nil {
|
|
|
|
data = append(data, pop.data)
|
|
|
|
} else if pop.opcode.value == OP_0 {
|
|
|
|
data = append(data, []byte{})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return data, nil
|
|
|
|
}
|