Merge pull request #4 from daglabs/remove-segwit

Remove segwit
This commit is contained in:
stasatdaglabs 2018-06-17 17:56:29 +03:00 committed by GitHub
commit 9581a31d5a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
120 changed files with 1051 additions and 5647 deletions

5
.gitignore vendored
View File

@ -34,4 +34,7 @@ _testmain.go
*.exe
# IDE
.idea
.idea
.vscode
debug
debug.test

View File

@ -1073,7 +1073,7 @@ func (a *AddrManager) GetBestLocalAddress(remoteAddr *wire.NetAddress) *wire.Net
} else {
ip = net.IPv4zero
}
services := wire.SFNodeNetwork | wire.SFNodeWitness | wire.SFNodeBloom
services := wire.SFNodeNetwork | wire.SFNodeBloom
bestAddress = wire.NewNetAddressIPPort(ip, 0, services)
}

View File

@ -58,29 +58,27 @@ type orphanBlock struct {
// However, the returned snapshot must be treated as immutable since it is
// shared by all callers.
type BestState struct {
Hash chainhash.Hash // The hash of the block.
Height int32 // The height of the block.
Bits uint32 // The difficulty bits of the block.
BlockSize uint64 // The size of the block.
BlockWeight uint64 // The weight of the block.
NumTxns uint64 // The number of txns in the block.
TotalTxns uint64 // The total number of txns in the chain.
MedianTime time.Time // Median time as per CalcPastMedianTime.
Hash chainhash.Hash // The hash of the block.
Height int32 // The height of the block.
Bits uint32 // The difficulty bits of the block.
BlockSize uint64 // The size of the block.
NumTxns uint64 // The number of txns in the block.
TotalTxns uint64 // The total number of txns in the chain.
MedianTime time.Time // Median time as per CalcPastMedianTime.
}
// newBestState returns a new best stats instance for the given parameters.
func newBestState(node *blockNode, blockSize, blockWeight, numTxns,
func newBestState(node *blockNode, blockSize, numTxns,
totalTxns uint64, medianTime time.Time) *BestState {
return &BestState{
Hash: node.hash,
Height: node.height,
Bits: node.bits,
BlockSize: blockSize,
BlockWeight: blockWeight,
NumTxns: numTxns,
TotalTxns: totalTxns,
MedianTime: medianTime,
Hash: node.hash,
Height: node.height,
Bits: node.bits,
BlockSize: blockSize,
NumTxns: numTxns,
TotalTxns: totalTxns,
MedianTime: medianTime,
}
}
@ -99,7 +97,6 @@ type BlockChain struct {
timeSource MedianTimeSource
sigCache *txscript.SigCache
indexManager IndexManager
hashCache *txscript.HashCache
// The following fields are calculated based upon the provided chain
// parameters. They are also set when the instance is created and
@ -600,8 +597,7 @@ func (b *BlockChain) connectBlock(node *blockNode, block *btcutil.Block, view *U
b.stateLock.RUnlock()
numTxns := uint64(len(block.MsgBlock().Transactions))
blockSize := uint64(block.MsgBlock().SerializeSize())
blockWeight := uint64(GetBlockWeight(block))
state := newBestState(node, blockSize, blockWeight, numTxns,
state := newBestState(node, blockSize, numTxns,
curTotalTxns+numTxns, node.CalcPastMedianTime())
// Atomically insert info into the database.
@ -712,9 +708,8 @@ func (b *BlockChain) disconnectBlock(node *blockNode, block *btcutil.Block, view
b.stateLock.RUnlock()
numTxns := uint64(len(prevBlock.MsgBlock().Transactions))
blockSize := uint64(prevBlock.MsgBlock().SerializeSize())
blockWeight := uint64(GetBlockWeight(prevBlock))
newTotalTxns := curTotalTxns - uint64(len(block.MsgBlock().Transactions))
state := newBestState(prevNode, blockSize, blockWeight, numTxns,
state := newBestState(prevNode, blockSize, numTxns,
newTotalTxns, prevNode.CalcPastMedianTime())
err = b.db.Update(func(dbTx database.Tx) error {
@ -1629,16 +1624,6 @@ type Config struct {
// This field can be nil if the caller does not wish to make use of an
// index manager.
IndexManager IndexManager
// HashCache defines a transaction hash mid-state cache to use when
// validating transactions. This cache has the potential to greatly
// speed up transaction validation as re-using the pre-calculated
// mid-state eliminates the O(N^2) validation complexity due to the
// SigHashAll flag.
//
// This field can be nil if the caller is not interested in using a
// signature cache.
HashCache *txscript.HashCache
}
// New returns a BlockChain instance using the provided configuration details.
@ -1688,7 +1673,6 @@ func New(config *Config) (*BlockChain, error) {
maxRetargetTimespan: targetTimespan * adjustmentFactor,
blocksPerRetarget: int32(targetTimespan / targetTimePerBlock),
index: newBlockIndex(config.DB, params),
hashCache: config.HashCache,
bestChain: newChainView(nil),
orphans: make(map[chainhash.Hash]*orphanBlock),
prevOrphans: make(map[chainhash.Hash][]*orphanBlock),

View File

@ -987,8 +987,7 @@ func (b *BlockChain) createChainState() error {
// genesis block, use its timestamp for the median time.
numTxns := uint64(len(genesisBlock.MsgBlock().Transactions))
blockSize := uint64(genesisBlock.MsgBlock().SerializeSize())
blockWeight := uint64(GetBlockWeight(genesisBlock))
b.stateSnapshot = newBestState(node, blockSize, blockWeight, numTxns,
b.stateSnapshot = newBestState(node, blockSize, numTxns,
numTxns, time.Unix(node.timestamp, 0))
// Create the initial the database chain state including creating the
@ -1192,10 +1191,8 @@ func (b *BlockChain) initChainState() error {
// Initialize the state related to the best block.
blockSize := uint64(len(blockBytes))
blockWeight := uint64(GetBlockWeight(btcutil.NewBlock(&block)))
numTxns := uint64(len(block.Transactions))
b.stateSnapshot = newBestState(tip, blockSize, blockWeight,
numTxns, state.totalTxns, tip.CalcPastMedianTime())
b.stateSnapshot = newBestState(tip, blockSize, numTxns, state.totalTxns, tip.CalcPastMedianTime())
return nil
})

View File

@ -41,10 +41,6 @@ const (
// maximum allowed size.
ErrBlockTooBig
// ErrBlockWeightTooHigh indicates that the block's computed weight
// metric exceeds the maximum allowed value.
ErrBlockWeightTooHigh
// ErrBlockVersionTooOld indicates the block version is too old and is
// no longer accepted since the majority of the network has upgraded
// to a newer version.
@ -195,20 +191,6 @@ const (
// the stack.
ErrScriptValidation
// ErrUnexpectedWitness indicates that a block includes transactions
// with witness data, but doesn't also have a witness commitment within
// the coinbase transaction.
ErrUnexpectedWitness
// ErrInvalidWitnessCommitment indicates that a block's witness
// commitment is not well formed.
ErrInvalidWitnessCommitment
// ErrWitnessCommitmentMismatch indicates that the witness commitment
// included in the block's coinbase transaction doesn't match the
// manually computed witness commitment.
ErrWitnessCommitmentMismatch
// ErrPreviousBlockUnknown indicates that the previous block is not known.
ErrPreviousBlockUnknown
@ -224,49 +206,45 @@ const (
// Map of ErrorCode values back to their constant names for pretty printing.
var errorCodeStrings = map[ErrorCode]string{
ErrDuplicateBlock: "ErrDuplicateBlock",
ErrBlockTooBig: "ErrBlockTooBig",
ErrBlockVersionTooOld: "ErrBlockVersionTooOld",
ErrBlockWeightTooHigh: "ErrBlockWeightTooHigh",
ErrInvalidTime: "ErrInvalidTime",
ErrTimeTooOld: "ErrTimeTooOld",
ErrTimeTooNew: "ErrTimeTooNew",
ErrDifficultyTooLow: "ErrDifficultyTooLow",
ErrUnexpectedDifficulty: "ErrUnexpectedDifficulty",
ErrHighHash: "ErrHighHash",
ErrBadMerkleRoot: "ErrBadMerkleRoot",
ErrBadCheckpoint: "ErrBadCheckpoint",
ErrForkTooOld: "ErrForkTooOld",
ErrCheckpointTimeTooOld: "ErrCheckpointTimeTooOld",
ErrNoTransactions: "ErrNoTransactions",
ErrNoTxInputs: "ErrNoTxInputs",
ErrNoTxOutputs: "ErrNoTxOutputs",
ErrTxTooBig: "ErrTxTooBig",
ErrBadTxOutValue: "ErrBadTxOutValue",
ErrDuplicateTxInputs: "ErrDuplicateTxInputs",
ErrBadTxInput: "ErrBadTxInput",
ErrMissingTxOut: "ErrMissingTxOut",
ErrUnfinalizedTx: "ErrUnfinalizedTx",
ErrDuplicateTx: "ErrDuplicateTx",
ErrOverwriteTx: "ErrOverwriteTx",
ErrImmatureSpend: "ErrImmatureSpend",
ErrSpendTooHigh: "ErrSpendTooHigh",
ErrBadFees: "ErrBadFees",
ErrTooManySigOps: "ErrTooManySigOps",
ErrFirstTxNotCoinbase: "ErrFirstTxNotCoinbase",
ErrMultipleCoinbases: "ErrMultipleCoinbases",
ErrBadCoinbaseScriptLen: "ErrBadCoinbaseScriptLen",
ErrBadCoinbaseValue: "ErrBadCoinbaseValue",
ErrMissingCoinbaseHeight: "ErrMissingCoinbaseHeight",
ErrBadCoinbaseHeight: "ErrBadCoinbaseHeight",
ErrScriptMalformed: "ErrScriptMalformed",
ErrScriptValidation: "ErrScriptValidation",
ErrUnexpectedWitness: "ErrUnexpectedWitness",
ErrInvalidWitnessCommitment: "ErrInvalidWitnessCommitment",
ErrWitnessCommitmentMismatch: "ErrWitnessCommitmentMismatch",
ErrPreviousBlockUnknown: "ErrPreviousBlockUnknown",
ErrInvalidAncestorBlock: "ErrInvalidAncestorBlock",
ErrPrevBlockNotBest: "ErrPrevBlockNotBest",
ErrDuplicateBlock: "ErrDuplicateBlock",
ErrBlockTooBig: "ErrBlockTooBig",
ErrBlockVersionTooOld: "ErrBlockVersionTooOld",
ErrInvalidTime: "ErrInvalidTime",
ErrTimeTooOld: "ErrTimeTooOld",
ErrTimeTooNew: "ErrTimeTooNew",
ErrDifficultyTooLow: "ErrDifficultyTooLow",
ErrUnexpectedDifficulty: "ErrUnexpectedDifficulty",
ErrHighHash: "ErrHighHash",
ErrBadMerkleRoot: "ErrBadMerkleRoot",
ErrBadCheckpoint: "ErrBadCheckpoint",
ErrForkTooOld: "ErrForkTooOld",
ErrCheckpointTimeTooOld: "ErrCheckpointTimeTooOld",
ErrNoTransactions: "ErrNoTransactions",
ErrNoTxInputs: "ErrNoTxInputs",
ErrNoTxOutputs: "ErrNoTxOutputs",
ErrTxTooBig: "ErrTxTooBig",
ErrBadTxOutValue: "ErrBadTxOutValue",
ErrDuplicateTxInputs: "ErrDuplicateTxInputs",
ErrBadTxInput: "ErrBadTxInput",
ErrMissingTxOut: "ErrMissingTxOut",
ErrUnfinalizedTx: "ErrUnfinalizedTx",
ErrDuplicateTx: "ErrDuplicateTx",
ErrOverwriteTx: "ErrOverwriteTx",
ErrImmatureSpend: "ErrImmatureSpend",
ErrSpendTooHigh: "ErrSpendTooHigh",
ErrBadFees: "ErrBadFees",
ErrTooManySigOps: "ErrTooManySigOps",
ErrFirstTxNotCoinbase: "ErrFirstTxNotCoinbase",
ErrMultipleCoinbases: "ErrMultipleCoinbases",
ErrBadCoinbaseScriptLen: "ErrBadCoinbaseScriptLen",
ErrBadCoinbaseValue: "ErrBadCoinbaseValue",
ErrMissingCoinbaseHeight: "ErrMissingCoinbaseHeight",
ErrBadCoinbaseHeight: "ErrBadCoinbaseHeight",
ErrScriptMalformed: "ErrScriptMalformed",
ErrScriptValidation: "ErrScriptValidation",
ErrPreviousBlockUnknown: "ErrPreviousBlockUnknown",
ErrInvalidAncestorBlock: "ErrInvalidAncestorBlock",
ErrPrevBlockNotBest: "ErrPrevBlockNotBest",
}
// String returns the ErrorCode as a human-readable name.

View File

@ -16,7 +16,6 @@ func TestErrorCodeStringer(t *testing.T) {
}{
{ErrDuplicateBlock, "ErrDuplicateBlock"},
{ErrBlockTooBig, "ErrBlockTooBig"},
{ErrBlockWeightTooHigh, "ErrBlockWeightTooHigh"},
{ErrBlockVersionTooOld, "ErrBlockVersionTooOld"},
{ErrInvalidTime, "ErrInvalidTime"},
{ErrTimeTooOld, "ErrTimeTooOld"},
@ -52,9 +51,6 @@ func TestErrorCodeStringer(t *testing.T) {
{ErrBadCoinbaseHeight, "ErrBadCoinbaseHeight"},
{ErrScriptMalformed, "ErrScriptMalformed"},
{ErrScriptValidation, "ErrScriptValidation"},
{ErrUnexpectedWitness, "ErrUnexpectedWitness"},
{ErrInvalidWitnessCommitment, "ErrInvalidWitnessCommitment"},
{ErrWitnessCommitmentMismatch, "ErrWitnessCommitmentMismatch"},
{ErrPreviousBlockUnknown, "ErrPreviousBlockUnknown"},
{ErrInvalidAncestorBlock, "ErrInvalidAncestorBlock"},
{ErrPrevBlockNotBest, "ErrPrevBlockNotBest"},

View File

@ -229,7 +229,7 @@ func TestFullBlocks(t *testing.T) {
// Ensure there is an error due to deserializing the block.
var msgBlock wire.MsgBlock
err := msgBlock.BtcDecode(bytes.NewReader(item.RawBlock), 0, wire.BaseEncoding)
err := msgBlock.BtcDecode(bytes.NewReader(item.RawBlock), 0)
if _, ok := err.(*wire.MessageError); !ok {
t.Fatalf("block %q (hash %s, height %d) should have "+
"failed to decode", item.Name, blockHash,

View File

@ -309,7 +309,7 @@ func calcMerkleRoot(txns []*wire.MsgTx) chainhash.Hash {
for _, tx := range txns {
utilTxns = append(utilTxns, btcutil.NewTx(tx))
}
merkles := blockchain.BuildMerkleTreeStore(utilTxns, false)
merkles := blockchain.BuildMerkleTreeStore(utilTxns)
return *merkles[len(merkles)-1]
}
@ -635,10 +635,10 @@ func nonCanonicalVarInt(val uint32) []byte {
// encoding.
func encodeNonCanonicalBlock(b *wire.MsgBlock) []byte {
var buf bytes.Buffer
b.Header.BtcEncode(&buf, 0, wire.BaseEncoding)
b.Header.BtcEncode(&buf, 0)
buf.Write(nonCanonicalVarInt(uint32(len(b.Transactions))))
for _, tx := range b.Transactions {
tx.BtcEncode(&buf, 0, wire.BaseEncoding)
tx.BtcEncode(&buf, 0)
}
return buf.Bytes()
}

View File

@ -51,18 +51,6 @@ const (
// hash.
addrKeyTypeScriptHash = 1
// addrKeyTypePubKeyHash is the address type in an address key which
// represents a pay-to-witness-pubkey-hash address. This is required
// as the 20-byte data push of a p2wkh witness program may be the same
// data push used a p2pkh address.
addrKeyTypeWitnessPubKeyHash = 2
// addrKeyTypeScriptHash is the address type in an address key which
// represents a pay-to-witness-script-hash address. This is required,
// as p2wsh are distinct from p2sh addresses since they use a new
// script template, as well as a 32-byte data push.
addrKeyTypeWitnessScriptHash = 3
// Size of a transaction entry. It consists of 4 bytes block id + 4
// bytes offset + 4 bytes length.
txEntrySize = 4 + 4 + 4
@ -546,24 +534,6 @@ func addrToKey(addr btcutil.Address) ([addrKeySize]byte, error) {
result[0] = addrKeyTypePubKeyHash
copy(result[1:], addr.AddressPubKeyHash().Hash160()[:])
return result, nil
case *btcutil.AddressWitnessScriptHash:
var result [addrKeySize]byte
result[0] = addrKeyTypeWitnessScriptHash
// P2WSH outputs utilize a 32-byte data push created by hashing
// the script with sha256 instead of hash160. In order to keep
// all address entries within the database uniform and compact,
// we use a hash160 here to reduce the size of the salient data
// push to 20-bytes.
copy(result[1:], btcutil.Hash160(addr.ScriptAddress()))
return result, nil
case *btcutil.AddressWitnessPubKeyHash:
var result [addrKeySize]byte
result[0] = addrKeyTypeWitnessPubKeyHash
copy(result[1:], addr.Hash160()[:])
return result, nil
}
return [addrKeySize]byte{}, errUnsupportedAddressType

View File

@ -5,42 +5,12 @@
package blockchain
import (
"bytes"
"fmt"
"math"
"github.com/daglabs/btcd/chaincfg/chainhash"
"github.com/daglabs/btcd/txscript"
"github.com/daglabs/btcutil"
)
const (
// CoinbaseWitnessDataLen is the required length of the only element within
// the coinbase's witness data if the coinbase transaction contains a
// witness commitment.
CoinbaseWitnessDataLen = 32
// CoinbaseWitnessPkScriptLength is the length of the public key script
// containing an OP_RETURN, the WitnessMagicBytes, and the witness
// commitment itself. In order to be a valid candidate for the output
// containing the witness commitment
CoinbaseWitnessPkScriptLength = 38
)
var (
// WitnessMagicBytes is the prefix marker within the public key script
// of a coinbase output to indicate that this output holds the witness
// commitment for a block.
WitnessMagicBytes = []byte{
txscript.OP_RETURN,
txscript.OP_DATA_36,
0xaa,
0x21,
0xa9,
0xed,
}
)
// nextPowerOfTwo returns the next highest power of two from a given number if
// it is not already a power of two. This is a helper function used during the
// calculation of a merkle tree.
@ -96,12 +66,7 @@ func HashMerkleBranches(left *chainhash.Hash, right *chainhash.Hash) *chainhash.
// are calculated by concatenating the left node with itself before hashing.
// Since this function uses nodes that are pointers to the hashes, empty nodes
// will be nil.
//
// The additional bool parameter indicates if we are generating the merkle tree
// using witness transaction id's rather than regular transaction id's. This
// also presents an additional case wherein the wtxid of the coinbase transaction
// is the zeroHash.
func BuildMerkleTreeStore(transactions []*btcutil.Tx, witness bool) []*chainhash.Hash {
func BuildMerkleTreeStore(transactions []*btcutil.Tx) []*chainhash.Hash {
// Calculate how many entries are required to hold the binary merkle
// tree as a linear array and create an array of that size.
nextPoT := nextPowerOfTwo(len(transactions))
@ -110,21 +75,7 @@ func BuildMerkleTreeStore(transactions []*btcutil.Tx, witness bool) []*chainhash
// Create the base transaction hashes and populate the array with them.
for i, tx := range transactions {
// If we're computing a witness merkle root, instead of the
// regular txid, we use the modified wtxid which includes a
// transaction's witness data within the digest. Additionally,
// the coinbase's wtxid is all zeroes.
switch {
case witness && i == 0:
var zeroHash chainhash.Hash
merkles[i] = &zeroHash
case witness:
wSha := tx.MsgTx().WitnessHash()
merkles[i] = &wSha
default:
merkles[i] = tx.Hash()
}
merkles[i] = tx.Hash()
}
// Start the array offset after the last transaction and adjusted to the
@ -153,113 +104,3 @@ func BuildMerkleTreeStore(transactions []*btcutil.Tx, witness bool) []*chainhash
return merkles
}
// ExtractWitnessCommitment attempts to locate, and return the witness
// commitment for a block. The witness commitment is of the form:
// SHA256(witness root || witness nonce). The function additionally returns a
// boolean indicating if the witness root was located within any of the txOut's
// in the passed transaction. The witness commitment is stored as the data push
// for an OP_RETURN with special magic bytes to aide in location.
func ExtractWitnessCommitment(tx *btcutil.Tx) ([]byte, bool) {
// The witness commitment *must* be located within one of the coinbase
// transaction's outputs.
if !IsCoinBase(tx) {
return nil, false
}
msgTx := tx.MsgTx()
for i := len(msgTx.TxOut) - 1; i >= 0; i-- {
// The public key script that contains the witness commitment
// must shared a prefix with the WitnessMagicBytes, and be at
// least 38 bytes.
pkScript := msgTx.TxOut[i].PkScript
if len(pkScript) >= CoinbaseWitnessPkScriptLength &&
bytes.HasPrefix(pkScript, WitnessMagicBytes) {
// The witness commitment itself is a 32-byte hash
// directly after the WitnessMagicBytes. The remaining
// bytes beyond the 38th byte currently have no consensus
// meaning.
start := len(WitnessMagicBytes)
end := CoinbaseWitnessPkScriptLength
return msgTx.TxOut[i].PkScript[start:end], true
}
}
return nil, false
}
// ValidateWitnessCommitment validates the witness commitment (if any) found
// within the coinbase transaction of the passed block.
func ValidateWitnessCommitment(blk *btcutil.Block) error {
// If the block doesn't have any transactions at all, then we won't be
// able to extract a commitment from the non-existent coinbase
// transaction. So we exit early here.
if len(blk.Transactions()) == 0 {
str := "cannot validate witness commitment of block without " +
"transactions"
return ruleError(ErrNoTransactions, str)
}
coinbaseTx := blk.Transactions()[0]
if len(coinbaseTx.MsgTx().TxIn) == 0 {
return ruleError(ErrNoTxInputs, "transaction has no inputs")
}
witnessCommitment, witnessFound := ExtractWitnessCommitment(coinbaseTx)
// If we can't find a witness commitment in any of the coinbase's
// outputs, then the block MUST NOT contain any transactions with
// witness data.
if !witnessFound {
for _, tx := range blk.Transactions() {
msgTx := tx.MsgTx()
if msgTx.HasWitness() {
str := fmt.Sprintf("block contains transaction with witness" +
" data, yet no witness commitment present")
return ruleError(ErrUnexpectedWitness, str)
}
}
return nil
}
// At this point the block contains a witness commitment, so the
// coinbase transaction MUST have exactly one witness element within
// its witness data and that element must be exactly
// CoinbaseWitnessDataLen bytes.
coinbaseWitness := coinbaseTx.MsgTx().TxIn[0].Witness
if len(coinbaseWitness) != 1 {
str := fmt.Sprintf("the coinbase transaction has %d items in "+
"its witness stack when only one is allowed",
len(coinbaseWitness))
return ruleError(ErrInvalidWitnessCommitment, str)
}
witnessNonce := coinbaseWitness[0]
if len(witnessNonce) != CoinbaseWitnessDataLen {
str := fmt.Sprintf("the coinbase transaction witness nonce "+
"has %d bytes when it must be %d bytes",
len(witnessNonce), CoinbaseWitnessDataLen)
return ruleError(ErrInvalidWitnessCommitment, str)
}
// Finally, with the preliminary checks out of the way, we can check if
// the extracted witnessCommitment is equal to:
// SHA256(witnessMerkleRoot || witnessNonce). Where witnessNonce is the
// coinbase transaction's only witness item.
witnessMerkleTree := BuildMerkleTreeStore(blk.Transactions(), true)
witnessMerkleRoot := witnessMerkleTree[len(witnessMerkleTree)-1]
var witnessPreimage [chainhash.HashSize * 2]byte
copy(witnessPreimage[:], witnessMerkleRoot[:])
copy(witnessPreimage[chainhash.HashSize:], witnessNonce)
computedCommitment := chainhash.DoubleHashB(witnessPreimage[:])
if !bytes.Equal(computedCommitment, witnessCommitment) {
str := fmt.Sprintf("witness commitment does not match: "+
"computed %v, coinbase includes %v", computedCommitment,
witnessCommitment)
return ruleError(ErrWitnessCommitmentMismatch, str)
}
return nil
}

View File

@ -13,7 +13,7 @@ import (
// TestMerkle tests the BuildMerkleTreeStore API.
func TestMerkle(t *testing.T) {
block := btcutil.NewBlock(&Block100000)
merkles := BuildMerkleTreeStore(block.Transactions(), false)
merkles := BuildMerkleTreeStore(block.Transactions())
calculatedMerkleRoot := merkles[len(merkles)-1]
wantMerkle := &Block100000.Header.MerkleRoot
if !wantMerkle.IsEqual(calculatedMerkleRoot) {

View File

@ -20,7 +20,6 @@ type txValidateItem struct {
txInIndex int
txIn *wire.TxIn
tx *btcutil.Tx
sigHashes *txscript.TxSigHashes
}
// txValidator provides a type which asynchronously validates transaction
@ -33,7 +32,6 @@ type txValidator struct {
utxoView *UtxoViewpoint
flags txscript.ScriptFlags
sigCache *txscript.SigCache
hashCache *txscript.HashCache
}
// sendResult sends the result of a script pair validation on the internal
@ -71,20 +69,16 @@ out:
// Create a new script engine for the script pair.
sigScript := txIn.SignatureScript
witness := txIn.Witness
pkScript := utxo.PkScript()
inputAmount := utxo.Amount()
vm, err := txscript.NewEngine(pkScript, txVI.tx.MsgTx(),
txVI.txInIndex, v.flags, v.sigCache, txVI.sigHashes,
inputAmount)
txVI.txInIndex, v.flags, v.sigCache)
if err != nil {
str := fmt.Sprintf("failed to parse input "+
"%s:%d which references output %v - "+
"%v (input witness %x, input script "+
"bytes %x, prev output script bytes %x)",
"%v (input script bytes %x, prev "+
"output script bytes %x)",
txVI.tx.Hash(), txVI.txInIndex,
txIn.PreviousOutPoint, err, witness,
sigScript, pkScript)
txIn.PreviousOutPoint, err, sigScript, pkScript)
err := ruleError(ErrScriptMalformed, str)
v.sendResult(err)
break out
@ -94,11 +88,10 @@ out:
if err := vm.Execute(); err != nil {
str := fmt.Sprintf("failed to validate input "+
"%s:%d which references output %v - "+
"%v (input witness %x, input script "+
"bytes %x, prev output script bytes %x)",
"%v (input script bytes %x, prev output "+
"script bytes %x)",
txVI.tx.Hash(), txVI.txInIndex,
txIn.PreviousOutPoint, err, witness,
sigScript, pkScript)
txIn.PreviousOutPoint, err, sigScript, pkScript)
err := ruleError(ErrScriptValidation, str)
v.sendResult(err)
break out
@ -173,47 +166,20 @@ func (v *txValidator) Validate(items []*txValidateItem) error {
// newTxValidator returns a new instance of txValidator to be used for
// validating transaction scripts asynchronously.
func newTxValidator(utxoView *UtxoViewpoint, flags txscript.ScriptFlags,
sigCache *txscript.SigCache, hashCache *txscript.HashCache) *txValidator {
func newTxValidator(utxoView *UtxoViewpoint, flags txscript.ScriptFlags, sigCache *txscript.SigCache) *txValidator {
return &txValidator{
validateChan: make(chan *txValidateItem),
quitChan: make(chan struct{}),
resultChan: make(chan error),
utxoView: utxoView,
sigCache: sigCache,
hashCache: hashCache,
flags: flags,
}
}
// ValidateTransactionScripts validates the scripts for the passed transaction
// using multiple goroutines.
func ValidateTransactionScripts(tx *btcutil.Tx, utxoView *UtxoViewpoint,
flags txscript.ScriptFlags, sigCache *txscript.SigCache,
hashCache *txscript.HashCache) error {
// First determine if segwit is active according to the scriptFlags. If
// it isn't then we don't need to interact with the HashCache.
segwitActive := flags&txscript.ScriptVerifyWitness == txscript.ScriptVerifyWitness
// If the hashcache doesn't yet has the sighash midstate for this
// transaction, then we'll compute them now so we can re-use them
// amongst all worker validation goroutines.
if segwitActive && tx.MsgTx().HasWitness() &&
!hashCache.ContainsHashes(tx.Hash()) {
hashCache.AddSigHashes(tx.MsgTx())
}
var cachedHashes *txscript.TxSigHashes
if segwitActive && tx.MsgTx().HasWitness() {
// The same pointer to the transaction's sighash midstate will
// be re-used amongst all validation goroutines. By
// pre-computing the sighash here instead of during validation,
// we ensure the sighashes
// are only computed once.
cachedHashes, _ = hashCache.GetSigHashes(tx.Hash())
}
func ValidateTransactionScripts(tx *btcutil.Tx, utxoView *UtxoViewpoint, flags txscript.ScriptFlags, sigCache *txscript.SigCache) error {
// Collect all of the transaction inputs and required information for
// validation.
txIns := tx.MsgTx().TxIn
@ -228,26 +194,18 @@ func ValidateTransactionScripts(tx *btcutil.Tx, utxoView *UtxoViewpoint,
txInIndex: txInIdx,
txIn: txIn,
tx: tx,
sigHashes: cachedHashes,
}
txValItems = append(txValItems, txVI)
}
// Validate all of the inputs.
validator := newTxValidator(utxoView, flags, sigCache, hashCache)
validator := newTxValidator(utxoView, flags, sigCache)
return validator.Validate(txValItems)
}
// checkBlockScripts executes and validates the scripts for all transactions in
// the passed block using multiple goroutines.
func checkBlockScripts(block *btcutil.Block, utxoView *UtxoViewpoint,
scriptFlags txscript.ScriptFlags, sigCache *txscript.SigCache,
hashCache *txscript.HashCache) error {
// First determine if segwit is active according to the scriptFlags. If
// it isn't then we don't need to interact with the HashCache.
segwitActive := scriptFlags&txscript.ScriptVerifyWitness == txscript.ScriptVerifyWitness
func checkBlockScripts(block *btcutil.Block, utxoView *UtxoViewpoint, scriptFlags txscript.ScriptFlags, sigCache *txscript.SigCache) error {
// Collect all of the transaction inputs and required information for
// validation for all transactions in the block into a single slice.
numInputs := 0
@ -256,28 +214,6 @@ func checkBlockScripts(block *btcutil.Block, utxoView *UtxoViewpoint,
}
txValItems := make([]*txValidateItem, 0, numInputs)
for _, tx := range block.Transactions() {
hash := tx.Hash()
// If the HashCache is present, and it doesn't yet contain the
// partial sighashes for this transaction, then we add the
// sighashes for the transaction. This allows us to take
// advantage of the potential speed savings due to the new
// digest algorithm (BIP0143).
if segwitActive && tx.HasWitness() && hashCache != nil &&
!hashCache.ContainsHashes(hash) {
hashCache.AddSigHashes(tx.MsgTx())
}
var cachedHashes *txscript.TxSigHashes
if segwitActive && tx.HasWitness() {
if hashCache != nil {
cachedHashes, _ = hashCache.GetSigHashes(hash)
} else {
cachedHashes = txscript.NewTxSigHashes(tx.MsgTx())
}
}
for txInIdx, txIn := range tx.MsgTx().TxIn {
// Skip coinbases.
if txIn.PreviousOutPoint.Index == math.MaxUint32 {
@ -288,14 +224,13 @@ func checkBlockScripts(block *btcutil.Block, utxoView *UtxoViewpoint,
txInIndex: txInIdx,
txIn: txIn,
tx: tx,
sigHashes: cachedHashes,
}
txValItems = append(txValItems, txVI)
}
}
// Validate all of the inputs.
validator := newTxValidator(utxoView, scriptFlags, sigCache, hashCache)
validator := newTxValidator(utxoView, scriptFlags, sigCache)
start := time.Now()
if err := validator.Validate(txValItems); err != nil {
return err
@ -304,16 +239,5 @@ func checkBlockScripts(block *btcutil.Block, utxoView *UtxoViewpoint,
log.Tracef("block %v took %v to verify", block.Hash(), elapsed)
// If the HashCache is present, once we have validated the block, we no
// longer need the cached hashes for these transactions, so we purge
// them from the cache.
if segwitActive && hashCache != nil {
for _, tx := range block.Transactions() {
if tx.MsgTx().HasWitness() {
hashCache.PurgeSigHashes(tx.Hash())
}
}
}
return nil
}

View File

@ -41,7 +41,7 @@ func TestCheckBlockScripts(t *testing.T) {
}
scriptFlags := txscript.ScriptBip16
err = checkBlockScripts(blocks[0], view, scriptFlags, nil, nil)
err = checkBlockScripts(blocks[0], view, scriptFlags, nil)
if err != nil {
t.Errorf("Transaction script validation failed: %v\n", err)
return

View File

@ -19,6 +19,10 @@ import (
)
const (
// MaxSigOpsPerBlock is the maximum number of signature operations
// allowed for a block. It is a fraction of the max block payload size.
MaxSigOpsPerBlock = wire.MaxBlockPayload / 50
// MaxTimeOffsetSeconds is the maximum number of seconds a block time
// is allowed to be ahead of the current time. This is currently 2
// hours.
@ -41,6 +45,10 @@ const (
// baseSubsidy is the starting subsidy amount for mined blocks. This
// value is halved every SubsidyHalvingInterval blocks.
baseSubsidy = 50 * btcutil.SatoshiPerBitcoin
// MaxOutputsPerBlock is the maximum number of transaction outputs there
// can be in a block of max size.
MaxOutputsPerBlock = wire.MaxBlockPayload / wire.MinTxOutPayload
)
var (
@ -216,10 +224,10 @@ func CheckTransactionSanity(tx *btcutil.Tx) error {
// A transaction must not exceed the maximum allowed block payload when
// serialized.
serializedTxSize := tx.MsgTx().SerializeSizeStripped()
if serializedTxSize > MaxBlockBaseSize {
serializedTxSize := tx.MsgTx().SerializeSize()
if serializedTxSize > wire.MaxBlockPayload {
str := fmt.Sprintf("serialized transaction is too big - got "+
"%d, max %d", serializedTxSize, MaxBlockBaseSize)
"%d, max %d", serializedTxSize, wire.MaxBlockPayload)
return ruleError(ErrTxTooBig, str)
}
@ -480,19 +488,19 @@ func checkBlockSanity(block *btcutil.Block, powLimit *big.Int, timeSource Median
}
// A block must not have more transactions than the max block payload or
// else it is certainly over the weight limit.
if numTx > MaxBlockBaseSize {
// else it is certainly over the block size limit.
if numTx > wire.MaxBlockPayload {
str := fmt.Sprintf("block contains too many transactions - "+
"got %d, max %d", numTx, MaxBlockBaseSize)
"got %d, max %d", numTx, wire.MaxBlockPayload)
return ruleError(ErrBlockTooBig, str)
}
// A block must not exceed the maximum allowed block payload when
// serialized.
serializedSize := msgBlock.SerializeSizeStripped()
if serializedSize > MaxBlockBaseSize {
serializedSize := msgBlock.SerializeSize()
if serializedSize > wire.MaxBlockPayload {
str := fmt.Sprintf("serialized block is too big - got %d, "+
"max %d", serializedSize, MaxBlockBaseSize)
"max %d", serializedSize, wire.MaxBlockPayload)
return ruleError(ErrBlockTooBig, str)
}
@ -527,7 +535,7 @@ func checkBlockSanity(block *btcutil.Block, powLimit *big.Int, timeSource Median
// checks. Bitcoind builds the tree here and checks the merkle root
// after the following checks, but there is no reason not to check the
// merkle root matches here.
merkles := BuildMerkleTreeStore(block.Transactions(), false)
merkles := BuildMerkleTreeStore(block.Transactions())
calculatedMerkleRoot := merkles[len(merkles)-1]
if !header.MerkleRoot.IsEqual(calculatedMerkleRoot) {
str := fmt.Sprintf("block merkle root is invalid - block "+
@ -557,11 +565,11 @@ func checkBlockSanity(block *btcutil.Block, powLimit *big.Int, timeSource Median
// We could potentially overflow the accumulator so check for
// overflow.
lastSigOps := totalSigOps
totalSigOps += (CountSigOps(tx) * WitnessScaleFactor)
if totalSigOps < lastSigOps || totalSigOps > MaxBlockSigOpsCost {
totalSigOps += CountSigOps(tx)
if totalSigOps < lastSigOps || totalSigOps > MaxSigOpsPerBlock {
str := fmt.Sprintf("block contains too many signature "+
"operations - got %v, max %v", totalSigOps,
MaxBlockSigOpsCost)
MaxSigOpsPerBlock)
return ruleError(ErrTooManySigOps, str)
}
}
@ -777,42 +785,6 @@ func (b *BlockChain) checkBlockContext(block *btcutil.Block, prevNode *blockNode
return err
}
}
// Query for the Version Bits state for the segwit soft-fork
// deployment. If segwit is active, we'll switch over to
// enforcing all the new rules.
segwitState, err := b.deploymentState(prevNode,
chaincfg.DeploymentSegwit)
if err != nil {
return err
}
// If segwit is active, then we'll need to fully validate the
// new witness commitment for adherence to the rules.
if segwitState == ThresholdActive {
// Validate the witness commitment (if any) within the
// block. This involves asserting that if the coinbase
// contains the special commitment output, then this
// merkle root matches a computed merkle root of all
// the wtxid's of the transactions within the block. In
// addition, various other checks against the
// coinbase's witness stack.
if err := ValidateWitnessCommitment(block); err != nil {
return err
}
// Once the witness commitment, witness nonce, and sig
// op cost have been validated, we can finally assert
// that the block's weight doesn't exceed the current
// consensus parameter.
blockWeight := GetBlockWeight(block)
if blockWeight > MaxBlockWeight {
str := fmt.Sprintf("block's weight metric is "+
"too high - got %v, max %v",
blockWeight, MaxBlockWeight)
return ruleError(ErrBlockWeightTooHigh, str)
}
}
}
return nil
@ -1047,15 +1019,6 @@ func (b *BlockChain) checkConnectBlock(node *blockNode, block *btcutil.Block, vi
// https://en.bitcoin.it/wiki/BIP_0016 for more details.
enforceBIP0016 := node.timestamp >= txscript.Bip16Activation.Unix()
// Query for the Version Bits state for the segwit soft-fork
// deployment. If segwit is active, we'll switch over to enforcing all
// the new rules.
segwitState, err := b.deploymentState(node.parent, chaincfg.DeploymentSegwit)
if err != nil {
return err
}
enforceSegWit := segwitState == ThresholdActive
// The number of signature operations must be less than the maximum
// allowed per block. Note that the preliminary sanity checks on a
// block also include a check similar to this one, but this check
@ -1063,28 +1026,31 @@ func (b *BlockChain) checkConnectBlock(node *blockNode, block *btcutil.Block, vi
// signature operations in each of the input transaction public key
// scripts.
transactions := block.Transactions()
totalSigOpCost := 0
totalSigOps := 0
for i, tx := range transactions {
// Since the first (and only the first) transaction has
// already been verified to be a coinbase transaction,
// use i == 0 as an optimization for the flag to
// countP2SHSigOps for whether or not the transaction is
// a coinbase transaction rather than having to do a
// full coinbase check again.
sigOpCost, err := GetSigOpCost(tx, i == 0, view, enforceBIP0016,
enforceSegWit)
if err != nil {
return err
numsigOps := CountSigOps(tx)
if enforceBIP0016 {
// Since the first (and only the first) transaction has
// already been verified to be a coinbase transaction,
// use i == 0 as an optimization for the flag to
// countP2SHSigOps for whether or not the transaction is
// a coinbase transaction rather than having to do a
// full coinbase check again.
numP2SHSigOps, err := CountP2SHSigOps(tx, i == 0, view)
if err != nil {
return err
}
numsigOps += numP2SHSigOps
}
// Check for overflow or going over the limits. We have to do
// this on every loop iteration to avoid overflow.
lastSigOpCost := totalSigOpCost
totalSigOpCost += sigOpCost
if totalSigOpCost < lastSigOpCost || totalSigOpCost > MaxBlockSigOpsCost {
lastSigops := totalSigOps
totalSigOps += numsigOps
if totalSigOps < lastSigops || totalSigOps > MaxSigOpsPerBlock {
str := fmt.Sprintf("block contains too many "+
"signature operations - got %v, max %v",
totalSigOpCost, MaxBlockSigOpsCost)
totalSigOps, MaxSigOpsPerBlock)
return ruleError(ErrTooManySigOps, str)
}
}
@ -1212,20 +1178,12 @@ func (b *BlockChain) checkConnectBlock(node *blockNode, block *btcutil.Block, vi
}
}
// Enforce the segwit soft-fork package once the soft-fork has shifted
// into the "active" version bits state.
if enforceSegWit {
scriptFlags |= txscript.ScriptVerifyWitness
scriptFlags |= txscript.ScriptStrictMultiSig
}
// Now that the inexpensive checks are done and have passed, verify the
// transactions are actually allowed to spend the coins by running the
// expensive ECDSA signature check scripts. Doing this last helps
// prevent CPU exhaustion attacks.
if runScripts {
err := checkBlockScripts(block, view, scriptFlags, b.sigCache,
b.hashCache)
err := checkBlockScripts(block, view, scriptFlags, b.sigCache)
if err != nil {
return err
}

View File

@ -176,7 +176,7 @@ func TestCheckSerializedHeight(t *testing.T) {
// Create an empty coinbase template to be used in the tests below.
coinbaseOutpoint := wire.NewOutPoint(&chainhash.Hash{}, math.MaxUint32)
coinbaseTx := wire.NewMsgTx(1)
coinbaseTx.AddTxIn(wire.NewTxIn(coinbaseOutpoint, nil, nil))
coinbaseTx.AddTxIn(wire.NewTxIn(coinbaseOutpoint, nil))
// Expected rule errors.
missingHeightError := RuleError{

View File

@ -1,117 +0,0 @@
// Copyright (c) 2013-2017 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package blockchain
import (
"fmt"
"github.com/daglabs/btcd/txscript"
"github.com/daglabs/btcd/wire"
"github.com/daglabs/btcutil"
)
const (
// MaxBlockWeight defines the maximum block weight, where "block
// weight" is interpreted as defined in BIP0141. A block's weight is
// calculated as the sum of the of bytes in the existing transactions
// and header, plus the weight of each byte within a transaction. The
// weight of a "base" byte is 4, while the weight of a witness byte is
// 1. As a result, for a block to be valid, the BlockWeight MUST be
// less than, or equal to MaxBlockWeight.
MaxBlockWeight = 4000000
// MaxBlockBaseSize is the maximum number of bytes within a block
// which can be allocated to non-witness data.
MaxBlockBaseSize = 1000000
// MaxBlockSigOpsCost is the maximum number of signature operations
// allowed for a block. It is calculated via a weighted algorithm which
// weights segregated witness sig ops lower than regular sig ops.
MaxBlockSigOpsCost = 80000
// WitnessScaleFactor determines the level of "discount" witness data
// receives compared to "base" data. A scale factor of 4, denotes that
// witness data is 1/4 as cheap as regular non-witness data.
WitnessScaleFactor = 4
// MinTxOutputWeight is the minimum possible weight for a transaction
// output.
MinTxOutputWeight = WitnessScaleFactor * wire.MinTxOutPayload
// MaxOutputsPerBlock is the maximum number of transaction outputs there
// can be in a block of max weight size.
MaxOutputsPerBlock = MaxBlockWeight / MinTxOutputWeight
)
// GetBlockWeight computes the value of the weight metric for a given block.
// Currently the weight metric is simply the sum of the block's serialized size
// without any witness data scaled proportionally by the WitnessScaleFactor,
// and the block's serialized size including any witness data.
func GetBlockWeight(blk *btcutil.Block) int64 {
msgBlock := blk.MsgBlock()
baseSize := msgBlock.SerializeSizeStripped()
totalSize := msgBlock.SerializeSize()
// (baseSize * 3) + totalSize
return int64((baseSize * (WitnessScaleFactor - 1)) + totalSize)
}
// GetTransactionWeight computes the value of the weight metric for a given
// transaction. Currently the weight metric is simply the sum of the
// transactions's serialized size without any witness data scaled
// proportionally by the WitnessScaleFactor, and the transaction's serialized
// size including any witness data.
func GetTransactionWeight(tx *btcutil.Tx) int64 {
msgTx := tx.MsgTx()
baseSize := msgTx.SerializeSizeStripped()
totalSize := msgTx.SerializeSize()
// (baseSize * 3) + totalSize
return int64((baseSize * (WitnessScaleFactor - 1)) + totalSize)
}
// GetSigOpCost returns the unified sig op cost for the passed transaction
// respecting current active soft-forks which modified sig op cost counting.
// The unified sig op cost for a transaction is computed as the sum of: the
// legacy sig op count scaled according to the WitnessScaleFactor, the sig op
// count for all p2sh inputs scaled by the WitnessScaleFactor, and finally the
// unscaled sig op count for any inputs spending witness programs.
func GetSigOpCost(tx *btcutil.Tx, isCoinBaseTx bool, utxoView *UtxoViewpoint, bip16, segWit bool) (int, error) {
numSigOps := CountSigOps(tx) * WitnessScaleFactor
if bip16 {
numP2SHSigOps, err := CountP2SHSigOps(tx, isCoinBaseTx, utxoView)
if err != nil {
return 0, nil
}
numSigOps += (numP2SHSigOps * WitnessScaleFactor)
}
if segWit && !isCoinBaseTx {
msgTx := tx.MsgTx()
for txInIndex, txIn := range msgTx.TxIn {
// Ensure the referenced output is available and hasn't
// already been spent.
utxo := utxoView.LookupEntry(txIn.PreviousOutPoint)
if utxo == nil || utxo.IsSpent() {
str := fmt.Sprintf("output %v referenced from "+
"transaction %s:%d either does not "+
"exist or has already been spent",
txIn.PreviousOutPoint, tx.Hash(),
txInIndex)
return 0, ruleError(ErrMissingTxOut, str)
}
witness := txIn.Witness
sigScript := txIn.SignatureScript
pkScript := utxo.PkScript()
numSigOps += txscript.GetWitnessSigOpCount(sigScript, pkScript, witness)
}
}
return numSigOps, nil
}

View File

@ -30,9 +30,7 @@ type GetBlockHeaderVerboseResult struct {
type GetBlockVerboseResult struct {
Hash string `json:"hash"`
Confirmations uint64 `json:"confirmations"`
StrippedSize int32 `json:"strippedsize"`
Size int32 `json:"size"`
Weight int32 `json:"weight"`
Height int64 `json:"height"`
Version int32 `json:"version"`
VersionHex string `json:"versionHex"`
@ -122,7 +120,6 @@ type GetBlockTemplateResultTx struct {
Depends []int64 `json:"depends"`
Fee int64 `json:"fee"`
SigOps int64 `json:"sigops"`
Weight int64 `json:"weight"`
}
// GetBlockTemplateResultAux models the coinbaseaux field of the
@ -142,7 +139,6 @@ type GetBlockTemplateResult struct {
PreviousHash string `json:"previousblockhash"`
SigOpLimit int64 `json:"sigoplimit,omitempty"`
SizeLimit int64 `json:"sizelimit,omitempty"`
WeightLimit int64 `json:"weightlimit,omitempty"`
Transactions []GetBlockTemplateResultTx `json:"transactions"`
Version int32 `json:"version"`
CoinbaseAux *GetBlockTemplateResultAux `json:"coinbaseaux,omitempty"`
@ -150,9 +146,6 @@ type GetBlockTemplateResult struct {
CoinbaseValue *int64 `json:"coinbasevalue,omitempty"`
WorkID string `json:"workid,omitempty"`
// Witness commitment defined in BIP 0141.
DefaultWitnessCommitment string `json:"default_witness_commitment,omitempty"`
// Optional long polling from BIP 0022.
LongPollID string `json:"longpollid,omitempty"`
LongPollURI string `json:"longpolluri,omitempty"`
@ -264,7 +257,6 @@ type GetPeerInfoResult struct {
// getrawmempool returns an array of transaction hashes.
type GetRawMempoolVerboseResult struct {
Size int32 `json:"size"`
Vsize int32 `json:"vsize"`
Fee float64 `json:"fee"`
Time int64 `json:"time"`
Height int64 `json:"height"`
@ -316,7 +308,6 @@ type Vin struct {
Vout uint32 `json:"vout"`
ScriptSig *ScriptSig `json:"scriptSig"`
Sequence uint32 `json:"sequence"`
Witness []string `json:"txinwitness"`
}
// IsCoinBase returns a bool to show if a Vin is a Coinbase one or not.
@ -324,44 +315,19 @@ func (v *Vin) IsCoinBase() bool {
return len(v.Coinbase) > 0
}
// HasWitness returns a bool to show if a Vin has any witness data associated
// with it or not.
func (v *Vin) HasWitness() bool {
return len(v.Witness) > 0
}
// MarshalJSON provides a custom Marshal method for Vin.
func (v *Vin) MarshalJSON() ([]byte, error) {
if v.IsCoinBase() {
coinbaseStruct := struct {
Coinbase string `json:"coinbase"`
Sequence uint32 `json:"sequence"`
Witness []string `json:"witness,omitempty"`
Coinbase string `json:"coinbase"`
Sequence uint32 `json:"sequence"`
}{
Coinbase: v.Coinbase,
Sequence: v.Sequence,
Witness: v.Witness,
}
return json.Marshal(coinbaseStruct)
}
if v.HasWitness() {
txStruct := struct {
Txid string `json:"txid"`
Vout uint32 `json:"vout"`
ScriptSig *ScriptSig `json:"scriptSig"`
Witness []string `json:"txinwitness"`
Sequence uint32 `json:"sequence"`
}{
Txid: v.Txid,
Vout: v.Vout,
ScriptSig: v.ScriptSig,
Witness: v.Witness,
Sequence: v.Sequence,
}
return json.Marshal(txStruct)
}
txStruct := struct {
Txid string `json:"txid"`
Vout uint32 `json:"vout"`
@ -388,7 +354,6 @@ type VinPrevOut struct {
Txid string `json:"txid"`
Vout uint32 `json:"vout"`
ScriptSig *ScriptSig `json:"scriptSig"`
Witness []string `json:"txinwitness"`
PrevOut *PrevOut `json:"prevOut"`
Sequence uint32 `json:"sequence"`
}
@ -398,12 +363,6 @@ func (v *VinPrevOut) IsCoinBase() bool {
return len(v.Coinbase) > 0
}
// HasWitness returns a bool to show if a Vin has any witness data associated
// with it or not.
func (v *VinPrevOut) HasWitness() bool {
return len(v.Witness) > 0
}
// MarshalJSON provides a custom Marshal method for VinPrevOut.
func (v *VinPrevOut) MarshalJSON() ([]byte, error) {
if v.IsCoinBase() {
@ -417,25 +376,6 @@ func (v *VinPrevOut) MarshalJSON() ([]byte, error) {
return json.Marshal(coinbaseStruct)
}
if v.HasWitness() {
txStruct := struct {
Txid string `json:"txid"`
Vout uint32 `json:"vout"`
ScriptSig *ScriptSig `json:"scriptSig"`
Witness []string `json:"txinwitness"`
PrevOut *PrevOut `json:"prevOut,omitempty"`
Sequence uint32 `json:"sequence"`
}{
Txid: v.Txid,
Vout: v.Vout,
ScriptSig: v.ScriptSig,
Witness: v.Witness,
PrevOut: v.PrevOut,
Sequence: v.Sequence,
}
return json.Marshal(txStruct)
}
txStruct := struct {
Txid string `json:"txid"`
Vout uint32 `json:"vout"`
@ -462,18 +402,17 @@ type Vout struct {
// GetMiningInfoResult models the data from the getmininginfo command.
type GetMiningInfoResult struct {
Blocks int64 `json:"blocks"`
CurrentBlockSize uint64 `json:"currentblocksize"`
CurrentBlockWeight uint64 `json:"currentblockweight"`
CurrentBlockTx uint64 `json:"currentblocktx"`
Difficulty float64 `json:"difficulty"`
Errors string `json:"errors"`
Generate bool `json:"generate"`
GenProcLimit int32 `json:"genproclimit"`
HashesPerSec int64 `json:"hashespersec"`
NetworkHashPS int64 `json:"networkhashps"`
PooledTx uint64 `json:"pooledtx"`
TestNet bool `json:"testnet"`
Blocks int64 `json:"blocks"`
CurrentBlockSize uint64 `json:"currentblocksize"`
CurrentBlockTx uint64 `json:"currentblocktx"`
Difficulty float64 `json:"difficulty"`
Errors string `json:"errors"`
Generate bool `json:"generate"`
GenProcLimit int32 `json:"genproclimit"`
HashesPerSec int64 `json:"hashespersec"`
NetworkHashPS int64 `json:"networkhashps"`
PooledTx uint64 `json:"pooledtx"`
TestNet bool `json:"testnet"`
}
// GetWorkResult models the data from the getwork command.
@ -504,7 +443,6 @@ type TxRawResult struct {
Txid string `json:"txid"`
Hash string `json:"hash,omitempty"`
Size int32 `json:"size,omitempty"`
Vsize int32 `json:"vsize,omitempty"`
Version int32 `json:"version"`
LockTime uint32 `json:"locktime"`
Vin []Vin `json:"vin"`
@ -522,7 +460,6 @@ type SearchRawTransactionsResult struct {
Txid string `json:"txid"`
Hash string `json:"hash"`
Size string `json:"size"`
Vsize string `json:"vsize"`
Version int32 `json:"version"`
LockTime uint32 `json:"locktime"`
Vin []VinPrevOut `json:"vin"`

View File

@ -27,19 +27,6 @@ func NewAddMultisigAddressCmd(nRequired int, keys []string, account *string) *Ad
}
}
// AddWitnessAddressCmd defines the addwitnessaddress JSON-RPC command.
type AddWitnessAddressCmd struct {
Address string
}
// NewAddWitnessAddressCmd returns a new instance which can be used to issue a
// addwitnessaddress JSON-RPC command.
func NewAddWitnessAddressCmd(address string) *AddWitnessAddressCmd {
return &AddWitnessAddressCmd{
Address: address,
}
}
// CreateMultisigCmd defines the createmultisig JSON-RPC command.
type CreateMultisigCmd struct {
NRequired int
@ -658,7 +645,6 @@ func init() {
flags := UFWalletOnly
MustRegisterCmd("addmultisigaddress", (*AddMultisigAddressCmd)(nil), flags)
MustRegisterCmd("addwitnessaddress", (*AddWitnessAddressCmd)(nil), flags)
MustRegisterCmd("createmultisig", (*CreateMultisigCmd)(nil), flags)
MustRegisterCmd("dumpprivkey", (*DumpPrivKeyCmd)(nil), flags)
MustRegisterCmd("encryptwallet", (*EncryptWalletCmd)(nil), flags)

View File

@ -61,19 +61,6 @@ func TestWalletSvrCmds(t *testing.T) {
Account: btcjson.String("test"),
},
},
{
name: "addwitnessaddress",
newCmd: func() (interface{}, error) {
return btcjson.NewCmd("addwitnessaddress", "1address")
},
staticCmd: func() interface{} {
return btcjson.NewAddWitnessAddressCmd("1address")
},
marshalled: `{"jsonrpc":"1.0","method":"addwitnessaddress","params":["1address"],"id":1}`,
unmarshalled: &btcjson.AddWitnessAddressCmd{
Address: "1address",
},
},
{
name: "createmultisig",
newCmd: func() (interface{}, error) {

View File

@ -8,12 +8,12 @@ import (
"errors"
"math"
"math/big"
"strings"
"time"
"fmt"
"github.com/daglabs/btcd/chaincfg/chainhash"
"github.com/daglabs/btcd/wire"
"fmt"
)
// These variables are the chain proof-of-work limit parameters for each default
@ -92,11 +92,6 @@ const (
// 68, 112, and 113.
DeploymentCSV
// DeploymentSegwit defines the rule change deployment ID for the
// Segregated Witness (segwit) soft-fork package. The segwit package
// includes the deployment of BIPS 141, 142, 144, 145, 147 and 173.
DeploymentSegwit
// NOTE: DefinedDeployments must always come last since it is used to
// determine how many defined deployments there currently are.
@ -256,14 +251,8 @@ type Params struct {
// Human-readable prefix for Bech32 encoded addresses
Prefix Bech32Prefix
// Human-readable part for Bech32 encoded segwit addresses, as defined
// in BIP 173.
Bech32HRPSegwit string
// Address encoding magics
PrivateKeyID byte // First byte of a WIF private key
WitnessPubKeyHashAddrID byte // First byte of a P2WPKH address
WitnessScriptHashAddrID byte // First byte of a P2WSH address
PrivateKeyID byte // First byte of a WIF private key
// BIP32 hierarchical deterministic extended key magics
HDPrivateKeyID [4]byte
@ -344,11 +333,6 @@ var MainNetParams = Params{
StartTime: 1462060800, // May 1st, 2016
ExpireTime: 1493596800, // May 1st, 2017
},
DeploymentSegwit: {
BitNumber: 1,
StartTime: 1479168000, // November 15, 2016 UTC
ExpireTime: 1510704000, // November 15, 2017 UTC.
},
},
// Mempool parameters
@ -357,14 +341,8 @@ var MainNetParams = Params{
// Human-readable part for Bech32 encoded addresses
Prefix: DagCoin,
// Human-readable part for Bech32 encoded segwit addresses, as defined in
// BIP 173.
Bech32HRPSegwit: "bc", // always bc for main net
// Address encoding magics
PrivateKeyID: 0x80, // starts with 5 (uncompressed) or K (compressed)
WitnessPubKeyHashAddrID: 0x06, // starts with p2
WitnessScriptHashAddrID: 0x0A, // starts with 7Xh
PrivateKeyID: 0x80, // starts with 5 (uncompressed) or K (compressed)
// BIP32 hierarchical deterministic extended key magics
HDPrivateKeyID: [4]byte{0x04, 0x88, 0xad, 0xe4}, // starts with xprv
@ -421,11 +399,6 @@ var RegressionNetParams = Params{
StartTime: 0, // Always available for vote
ExpireTime: math.MaxInt64, // Never expires
},
DeploymentSegwit: {
BitNumber: 1,
StartTime: 0, // Always available for vote
ExpireTime: math.MaxInt64, // Never expires.
},
},
// Mempool parameters
@ -434,10 +407,6 @@ var RegressionNetParams = Params{
// Human-readable part for Bech32 encoded addresses
Prefix: DagReg,
// Human-readable part for Bech32 encoded segwit addresses, as defined in
// BIP 173.
Bech32HRPSegwit: "bcrt", // always bcrt for reg test net
// Address encoding magics
PrivateKeyID: 0xef, // starts with 9 (uncompressed) or c (compressed)
@ -513,11 +482,6 @@ var TestNet3Params = Params{
StartTime: 1456790400, // March 1st, 2016
ExpireTime: 1493596800, // May 1st, 2017
},
DeploymentSegwit: {
BitNumber: 1,
StartTime: 1462060800, // May 1, 2016 UTC
ExpireTime: 1493596800, // May 1, 2017 UTC.
},
},
// Mempool parameters
@ -526,14 +490,8 @@ var TestNet3Params = Params{
// Human-readable part for Bech32 encoded addresses
Prefix: DagTest,
// Human-readable part for Bech32 encoded segwit addresses, as defined in
// BIP 173.
Bech32HRPSegwit: "tb", // always tb for test net
// Address encoding magics
WitnessPubKeyHashAddrID: 0x03, // starts with QW
WitnessScriptHashAddrID: 0x28, // starts with T7n
PrivateKeyID: 0xef, // starts with 9 (uncompressed) or c (compressed)
PrivateKeyID: 0xef, // starts with 9 (uncompressed) or c (compressed)
// BIP32 hierarchical deterministic extended key magics
HDPrivateKeyID: [4]byte{0x04, 0x35, 0x83, 0x94}, // starts with tprv
@ -594,28 +552,15 @@ var SimNetParams = Params{
StartTime: 0, // Always available for vote
ExpireTime: math.MaxInt64, // Never expires
},
DeploymentSegwit: {
BitNumber: 1,
StartTime: 0, // Always available for vote
ExpireTime: math.MaxInt64, // Never expires.
},
},
// Mempool parameters
RelayNonStdTxs: true,
PrivateKeyID: 0x64, // starts with 4 (uncompressed) or F (compressed)
// Human-readable part for Bech32 encoded addresses
Prefix: DagSim,
// Human-readable part for Bech32 encoded segwit addresses, as defined in
// BIP 173.
Bech32HRPSegwit: "sb", // always sb for sim net
// Address encoding magics
PrivateKeyID: 0x64, // starts with 4 (uncompressed) or F (compressed)
WitnessPubKeyHashAddrID: 0x19, // starts with Gg
WitnessScriptHashAddrID: 0x28, // starts with ?
// BIP32 hierarchical deterministic extended key magics
HDPrivateKeyID: [4]byte{0x04, 0x20, 0xb9, 0x00}, // starts with sprv
HDPublicKeyID: [4]byte{0x04, 0x20, 0xbd, 0x3a}, // starts with spub
@ -638,9 +583,8 @@ var (
)
var (
registeredNets = make(map[wire.BitcoinNet]struct{})
bech32SegwitPrefixes = make(map[string]struct{})
hdPrivToPubKeyIDs = make(map[[4]byte][]byte)
registeredNets = make(map[wire.BitcoinNet]struct{})
hdPrivToPubKeyIDs = make(map[[4]byte][]byte)
)
// String returns the hostname of the DNS seed in human-readable form.
@ -664,9 +608,6 @@ func Register(params *Params) error {
registeredNets[params.Net] = struct{}{}
hdPrivToPubKeyIDs[params.HDPrivateKeyID] = params.HDPublicKeyID[:]
// A valid Bech32 encoded segwit address always has as prefix the
// human-readable part for the given net followed by '1'.
bech32SegwitPrefixes[params.Bech32HRPSegwit+"1"] = struct{}{}
return nil
}
@ -678,15 +619,6 @@ func mustRegister(params *Params) {
}
}
// IsBech32SegwitPrefix returns whether the prefix is a known prefix for segwit
// addresses on any default or registered network. This is used when decoding
// an address string into a specific address type.
func IsBech32SegwitPrefix(prefix string) bool {
prefix = strings.ToLower(prefix)
_, ok := bech32SegwitPrefixes[prefix]
return ok
}
// HDPrivateKeyToPublicKeyID accepts a private hierarchical deterministic
// extended key id and returns the associated public key id. When the provided
// id is not registered, the ErrUnknownHDKeyID error will be returned.

View File

@ -3,7 +3,6 @@ package chaincfg_test
import (
"bytes"
"reflect"
"strings"
"testing"
. "github.com/daglabs/btcd/chaincfg"
@ -13,11 +12,10 @@ import (
// network. This is necessary to test the registration of and
// lookup of encoding magics from the network.
var mockNetParams = Params{
Name: "mocknet",
Net: 1<<32 - 1,
Bech32HRPSegwit: "tc",
HDPrivateKeyID: [4]byte{0x01, 0x02, 0x03, 0x04},
HDPublicKeyID: [4]byte{0x05, 0x06, 0x07, 0x08},
Name: "mocknet",
Net: 1<<32 - 1,
HDPrivateKeyID: [4]byte{0x01, 0x02, 0x03, 0x04},
HDPublicKeyID: [4]byte{0x05, 0x06, 0x07, 0x08},
}
func TestRegister(t *testing.T) {
@ -37,10 +35,9 @@ func TestRegister(t *testing.T) {
}
tests := []struct {
name string
register []registerTest
segwitPrefixes []prefixTest
hdMagics []hdTest
name string
register []registerTest
hdMagics []hdTest
}{
{
name: "default networks",
@ -66,44 +63,6 @@ func TestRegister(t *testing.T) {
err: ErrDuplicateNet,
},
},
segwitPrefixes: []prefixTest{
{
prefix: MainNetParams.Bech32HRPSegwit + "1",
valid: true,
},
{
prefix: TestNet3Params.Bech32HRPSegwit + "1",
valid: true,
},
{
prefix: RegressionNetParams.Bech32HRPSegwit + "1",
valid: true,
},
{
prefix: SimNetParams.Bech32HRPSegwit + "1",
valid: true,
},
{
prefix: strings.ToUpper(MainNetParams.Bech32HRPSegwit + "1"),
valid: true,
},
{
prefix: mockNetParams.Bech32HRPSegwit + "1",
valid: false,
},
{
prefix: "abc1",
valid: false,
},
{
prefix: "1",
valid: false,
},
{
prefix: MainNetParams.Bech32HRPSegwit,
valid: false,
},
},
hdMagics: []hdTest{
{
priv: MainNetParams.HDPrivateKeyID[:],
@ -148,44 +107,6 @@ func TestRegister(t *testing.T) {
err: nil,
},
},
segwitPrefixes: []prefixTest{
{
prefix: MainNetParams.Bech32HRPSegwit + "1",
valid: true,
},
{
prefix: TestNet3Params.Bech32HRPSegwit + "1",
valid: true,
},
{
prefix: RegressionNetParams.Bech32HRPSegwit + "1",
valid: true,
},
{
prefix: SimNetParams.Bech32HRPSegwit + "1",
valid: true,
},
{
prefix: strings.ToUpper(MainNetParams.Bech32HRPSegwit + "1"),
valid: true,
},
{
prefix: mockNetParams.Bech32HRPSegwit + "1",
valid: true,
},
{
prefix: "abc1",
valid: false,
},
{
prefix: "1",
valid: false,
},
{
prefix: MainNetParams.Bech32HRPSegwit,
valid: false,
},
},
hdMagics: []hdTest{
{
priv: mockNetParams.HDPrivateKeyID[:],
@ -223,44 +144,6 @@ func TestRegister(t *testing.T) {
err: ErrDuplicateNet,
},
},
segwitPrefixes: []prefixTest{
{
prefix: MainNetParams.Bech32HRPSegwit + "1",
valid: true,
},
{
prefix: TestNet3Params.Bech32HRPSegwit + "1",
valid: true,
},
{
prefix: RegressionNetParams.Bech32HRPSegwit + "1",
valid: true,
},
{
prefix: SimNetParams.Bech32HRPSegwit + "1",
valid: true,
},
{
prefix: strings.ToUpper(MainNetParams.Bech32HRPSegwit + "1"),
valid: true,
},
{
prefix: mockNetParams.Bech32HRPSegwit + "1",
valid: true,
},
{
prefix: "abc1",
valid: false,
},
{
prefix: "1",
valid: false,
},
{
prefix: MainNetParams.Bech32HRPSegwit,
valid: false,
},
},
hdMagics: []hdTest{
{
priv: MainNetParams.HDPrivateKeyID[:],
@ -307,13 +190,6 @@ func TestRegister(t *testing.T) {
test.name, regTest.name, err, regTest.err)
}
}
for i, prxTest := range test.segwitPrefixes {
valid := IsBech32SegwitPrefix(prxTest.prefix)
if valid != prxTest.valid {
t.Errorf("%s: segwit prefix %s (%d) valid mismatch: got %v expected %v",
test.name, prxTest.prefix, i, valid, prxTest.valid)
}
}
for i, magTest := range test.hdMagics {
pubKey, err := HDPrivateKeyToPublicKeyID(magTest.priv[:])
if !reflect.DeepEqual(err, magTest.err) {

View File

@ -20,15 +20,15 @@ import (
"strings"
"time"
"github.com/daglabs/btcd/blockchain"
"github.com/btcsuite/go-socks/socks"
"github.com/daglabs/btcd/chaincfg"
"github.com/daglabs/btcd/chaincfg/chainhash"
"github.com/daglabs/btcd/connmgr"
"github.com/daglabs/btcd/database"
_ "github.com/daglabs/btcd/database/ffldb"
"github.com/daglabs/btcd/mempool"
"github.com/daglabs/btcd/wire"
"github.com/daglabs/btcutil"
"github.com/btcsuite/go-socks/socks"
flags "github.com/jessevdk/go-flags"
)
@ -49,12 +49,8 @@ const (
defaultFreeTxRelayLimit = 15.0
defaultBlockMinSize = 0
defaultBlockMaxSize = 750000
defaultBlockMinWeight = 0
defaultBlockMaxWeight = 3000000
blockMaxSizeMin = 1000
blockMaxSizeMax = blockchain.MaxBlockBaseSize - 1000
blockMaxWeightMin = 4000
blockMaxWeightMax = blockchain.MaxBlockWeight - 4000
blockMaxSizeMax = wire.MaxBlockPayload - 1000
defaultGenerate = false
defaultMaxOrphanTransactions = 100
defaultMaxOrphanTxSize = 100000
@ -145,8 +141,6 @@ type config struct {
MiningAddrs []string `long:"miningaddr" description:"Add the specified payment address to the list of addresses to use for generated blocks -- At least one address is required if the generate option is set"`
BlockMinSize uint32 `long:"blockminsize" description:"Mininum block size in bytes to be used when creating a block"`
BlockMaxSize uint32 `long:"blockmaxsize" description:"Maximum block size in bytes to be used when creating a block"`
BlockMinWeight uint32 `long:"blockminweight" description:"Mininum block weight to be used when creating a block"`
BlockMaxWeight uint32 `long:"blockmaxweight" description:"Maximum block weight to be used when creating a block"`
BlockPrioritySize uint32 `long:"blockprioritysize" description:"Size in bytes for high-priority/low-fee transactions when creating a block"`
UserAgentComments []string `long:"uacomment" description:"Comment to add to the user agent -- See BIP 14 for more information."`
NoPeerBloomFilters bool `long:"nopeerbloomfilters" description:"Disable bloom filtering support"`
@ -417,8 +411,6 @@ func loadConfig() (*config, []string, error) {
FreeTxRelayLimit: defaultFreeTxRelayLimit,
BlockMinSize: defaultBlockMinSize,
BlockMaxSize: defaultBlockMaxSize,
BlockMinWeight: defaultBlockMinWeight,
BlockMaxWeight: defaultBlockMaxWeight,
BlockPrioritySize: mempool.DefaultBlockPrioritySize,
MaxOrphanTxs: defaultMaxOrphanTransactions,
SigCacheMaxSize: defaultSigCacheMaxSize,
@ -771,19 +763,6 @@ func loadConfig() (*config, []string, error) {
return nil, nil, err
}
// Limit the max block weight to a sane value.
if cfg.BlockMaxWeight < blockMaxWeightMin ||
cfg.BlockMaxWeight > blockMaxWeightMax {
str := "%s: The blockmaxweight option must be in between %d " +
"and %d -- parsed [%d]"
err := fmt.Errorf(str, funcName, blockMaxWeightMin,
blockMaxWeightMax, cfg.BlockMaxWeight)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
// Limit the max orphan count to a sane vlue.
if cfg.MaxOrphanTxs < 0 {
str := "%s: The maxorphantx option may not be less than 0 " +
@ -797,24 +776,6 @@ func loadConfig() (*config, []string, error) {
// Limit the block priority and minimum block sizes to max block size.
cfg.BlockPrioritySize = minUint32(cfg.BlockPrioritySize, cfg.BlockMaxSize)
cfg.BlockMinSize = minUint32(cfg.BlockMinSize, cfg.BlockMaxSize)
cfg.BlockMinWeight = minUint32(cfg.BlockMinWeight, cfg.BlockMaxWeight)
switch {
// If the max block size isn't set, but the max weight is, then we'll
// set the limit for the max block size to a safe limit so weight takes
// precedence.
case cfg.BlockMaxSize == defaultBlockMaxSize &&
cfg.BlockMaxWeight != defaultBlockMaxWeight:
cfg.BlockMaxSize = blockchain.MaxBlockBaseSize - 1000
// If the max block weight isn't set, but the block size is, then we'll
// scale the set weight accordingly based on the max block size value.
case cfg.BlockMaxSize != defaultBlockMaxSize &&
cfg.BlockMaxWeight == defaultBlockMaxWeight:
cfg.BlockMaxWeight = cfg.BlockMaxSize * blockchain.WitnessScaleFactor
}
// Look for illegal characters in the user agent comments.
for _, uaComment := range cfg.UserAgentComments {

View File

@ -274,8 +274,8 @@ the method name for further details such as parameter and return information.
|Parameters|1. block hash (string, required) - the hash of the block<br />2. verbose (boolean, optional, default=true) - specifies the block is returned as a JSON object instead of hex-encoded string<br />3. verbosetx (boolean, optional, default=false) - specifies that each transaction is returned as a JSON object and only applies if the `verbose` flag is true.<font color="orange">**This parameter is a btcd extension**</font>|
|Description|Returns information about a block given its hash.|
|Returns (verbose=false)|`"data" (string) hex-encoded bytes of the serialized block`|
|Returns (verbose=true, verbosetx=false)|`{ (json object)`<br />&nbsp;&nbsp;`"hash": "blockhash", (string) the hash of the block (same as provided)`<br />&nbsp;&nbsp;`"confirmations": n, (numeric) the number of confirmations`<br />&nbsp;&nbsp;`"strippedsize", n (numeric) the size of the block without witness data`<br />&nbsp;&nbsp;`"size": n, (numeric) the size of the block`<br />&nbsp;&nbsp;`"weight": n, (numeric) value of the weight metric`<br />&nbsp;&nbsp;`"height": n, (numeric) the height of the block in the block chain`<br />&nbsp;&nbsp;`"version": n, (numeric) the block version`<br />&nbsp;&nbsp;`"merkleroot": "hash", (string) root hash of the merkle tree`<br />&nbsp;&nbsp;`"tx": [ (json array of string) the transaction hashes`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"transactionhash", (string) hash of the parent transaction`<br />&nbsp;&nbsp;&nbsp;&nbsp;`...`<br />&nbsp;&nbsp;`]`<br />&nbsp;&nbsp;`"time": n, (numeric) the block time in seconds since 1 Jan 1970 GMT`<br />&nbsp;&nbsp;`"nonce": n, (numeric) the block nonce`<br />&nbsp;&nbsp;`"bits", n, (numeric) the bits which represent the block difficulty`<br />&nbsp;&nbsp;`difficulty: n.nn, (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty`<br />&nbsp;&nbsp;`"previousblockhash": "hash", (string) the hash of the previous block`<br />&nbsp;&nbsp;`"nextblockhash": "hash", (string) the hash of the next block (only if there is one)`<br />`}`|
|Returns (verbose=true, verbosetx=true)|`{ (json object)`<br />&nbsp;&nbsp;`"hash": "blockhash", (string) the hash of the block (same as provided)`<br />&nbsp;&nbsp;`"confirmations": n, (numeric) the number of confirmations`<br />&nbsp;&nbsp;`"strippedsize", n (numeric) the size of the block without witness data`<br />&nbsp;&nbsp;`"size": n, (numeric) the size of the block`<br />&nbsp;&nbsp;`"weight": n, (numeric) value of the weight metric`<br />&nbsp;&nbsp;`"height": n, (numeric) the height of the block in the block chain`<br />&nbsp;&nbsp;`"version": n, (numeric) the block version`<br />&nbsp;&nbsp;`"merkleroot": "hash", (string) root hash of the merkle tree`<br />&nbsp;&nbsp;`"rawtx": [ (array of json objects) the transactions as json objects`<br />&nbsp;&nbsp;&nbsp;&nbsp;`(see getrawtransaction json object details)`<br />&nbsp;&nbsp;`]`<br />&nbsp;&nbsp;`"time": n, (numeric) the block time in seconds since 1 Jan 1970 GMT`<br />&nbsp;&nbsp;`"nonce": n, (numeric) the block nonce`<br />&nbsp;&nbsp;`"bits", n, (numeric) the bits which represent the block difficulty`<br />&nbsp;&nbsp;`difficulty: n.nn, (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty`<br />&nbsp;&nbsp;`"previousblockhash": "hash", (string) the hash of the previous block`<br />&nbsp;&nbsp;`"nextblockhash": "hash", (string) the hash of the next block`<br />`}`|
|Returns (verbose=true, verbosetx=false)|`{ (json object)`<br />&nbsp;&nbsp;`"hash": "blockhash", (string) the hash of the block (same as provided)`<br />&nbsp;&nbsp;`"confirmations": n, (numeric) the number of confirmations`<br />&nbsp;&nbsp;`"size", n (numeric) the size of the block`<br />&nbsp;&nbsp;`"size": n, (numeric) the size of the block`<br />&nbsp;&nbsp;`"height": n, (numeric) the height of the block in the block chain`<br />&nbsp;&nbsp;`"version": n, (numeric) the block version`<br />&nbsp;&nbsp;`"merkleroot": "hash", (string) root hash of the merkle tree`<br />&nbsp;&nbsp;`"tx": [ (json array of string) the transaction hashes`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"transactionhash", (string) hash of the parent transaction`<br />&nbsp;&nbsp;&nbsp;&nbsp;`...`<br />&nbsp;&nbsp;`]`<br />&nbsp;&nbsp;`"time": n, (numeric) the block time in seconds since 1 Jan 1970 GMT`<br />&nbsp;&nbsp;`"nonce": n, (numeric) the block nonce`<br />&nbsp;&nbsp;`"bits", n, (numeric) the bits which represent the block difficulty`<br />&nbsp;&nbsp;`difficulty: n.nn, (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty`<br />&nbsp;&nbsp;`"previousblockhash": "hash", (string) the hash of the previous block`<br />&nbsp;&nbsp;`"nextblockhash": "hash", (string) the hash of the next block (only if there is one)`<br />`}`|
|Returns (verbose=true, verbosetx=true)|`{ (json object)`<br />&nbsp;&nbsp;`"hash": "blockhash", (string) the hash of the block (same as provided)`<br />&nbsp;&nbsp;`"confirmations": n, (numeric) the number of confirmations`<br />&nbsp;&nbsp;`"size", n (numeric) the size of the block`<br />&nbsp;&nbsp;`"size": n, (numeric) the size of the block`<br />&nbsp;&nbsp;`"height": n, (numeric) the height of the block in the block chain`<br />&nbsp;&nbsp;`"version": n, (numeric) the block version`<br />&nbsp;&nbsp;`"merkleroot": "hash", (string) root hash of the merkle tree`<br />&nbsp;&nbsp;`"rawtx": [ (array of json objects) the transactions as json objects`<br />&nbsp;&nbsp;&nbsp;&nbsp;`(see getrawtransaction json object details)`<br />&nbsp;&nbsp;`]`<br />&nbsp;&nbsp;`"time": n, (numeric) the block time in seconds since 1 Jan 1970 GMT`<br />&nbsp;&nbsp;`"nonce": n, (numeric) the block nonce`<br />&nbsp;&nbsp;`"bits", n, (numeric) the bits which represent the block difficulty`<br />&nbsp;&nbsp;`difficulty: n.nn, (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty`<br />&nbsp;&nbsp;`"previousblockhash": "hash", (string) the hash of the previous block`<br />&nbsp;&nbsp;`"nextblockhash": "hash", (string) the hash of the next block`<br />`}`|
|Example Return (verbose=false)|`"010000000000000000000000000000000000000000000000000000000000000000000000`<br />`3ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a29ab5f49`<br />`ffff001d1dac2b7c01010000000100000000000000000000000000000000000000000000`<br />`00000000000000000000ffffffff4d04ffff001d0104455468652054696d65732030332f`<br />`4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f`<br />`6e64206261696c6f757420666f722062616e6b73ffffffff0100f2052a01000000434104`<br />`678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f`<br />`4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000"`<br /><font color="orange">**Newlines added for display purposes. The actual return does not contain newlines.**</font>|
|Example Return (verbose=true, verbosetx=false)|`{`<br />&nbsp;&nbsp;`"hash": "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f",`<br />&nbsp;&nbsp;`"confirmations": 277113,`<br />&nbsp;&nbsp;`"size": 285,`<br />&nbsp;&nbsp;`"height": 0,`<br />&nbsp;&nbsp;`"version": 1,`<br />&nbsp;&nbsp;`"merkleroot": "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b",`<br />&nbsp;&nbsp;`"tx": [`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"`<br />&nbsp;&nbsp;`],`<br />&nbsp;&nbsp;`"time": 1231006505,`<br />&nbsp;&nbsp;`"nonce": 2083236893,`<br />&nbsp;&nbsp;`"bits": "1d00ffff",`<br />&nbsp;&nbsp;`"difficulty": 1,`<br />&nbsp;&nbsp;`"previousblockhash": "0000000000000000000000000000000000000000000000000000000000000000",`<br />&nbsp;&nbsp;`"nextblockhash": "00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048"`<br />`}`|
[Return to Overview](#MethodOverview)<br />
@ -397,8 +397,8 @@ Example Return|`{`<br />&nbsp;&nbsp;`"bytes": 310768,`<br />&nbsp;&nbsp;`"size":
|Method|getmininginfo|
|Parameters|None|
|Description|Returns a JSON object containing mining-related information.|
|Returns|`{ (json object)`<br />&nbsp;&nbsp;`"blocks": n, (numeric) latest best block`<br />&nbsp;&nbsp;`"currentblocksize": n, (numeric) size of the latest best block`<br />&nbsp;&nbsp;`"currentblockweight": n, (numeric) weight of the latest best block`<br />&nbsp;&nbsp;`"currentblocktx": n, (numeric) number of transactions in the latest best block`<br />&nbsp;&nbsp;`"difficulty": n.nn, (numeric) current target difficulty`<br />&nbsp;&nbsp;`"errors": "errors", (string) any current errors`<br />&nbsp;&nbsp;`"generate": true or false, (boolean) whether or not server is set to generate coins`<br />&nbsp;&nbsp;`"genproclimit": n, (numeric) number of processors to use for coin generation (-1 when disabled)`<br />&nbsp;&nbsp;`"hashespersec": n, (numeric) recent hashes per second performance measurement while generating coins`<br />&nbsp;&nbsp;`"networkhashps": n, (numeric) estimated network hashes per second for the most recent blocks`<br />&nbsp;&nbsp;`"pooledtx": n, (numeric) number of transactions in the memory pool`<br />&nbsp;&nbsp;`"testnet": true or false, (boolean) whether or not server is using testnet`<br />`}`|
|Example Return|`{`<br />&nbsp;&nbsp;`"blocks": 236526,`<br />&nbsp;&nbsp;`"currentblocksize": 185,`<br />&nbsp;&nbsp;`"currentblockweight": 740,`<br />&nbsp;&nbsp;`"currentblocktx": 1,`<br />&nbsp;&nbsp;`"difficulty": 256,`<br />&nbsp;&nbsp;`"errors": "",`<br />&nbsp;&nbsp;`"generate": false,`<br />&nbsp;&nbsp;`"genproclimit": -1,`<br />&nbsp;&nbsp;`"hashespersec": 0,`<br />&nbsp;&nbsp;`"networkhashps": 33081554756,`<br />&nbsp;&nbsp;`"pooledtx": 8,`<br />&nbsp;&nbsp;`"testnet": true,`<br />`}`|
|Returns|`{ (json object)`<br />&nbsp;&nbsp;`"blocks": n, (numeric) latest best block`<br />&nbsp;&nbsp;`"currentblocksize": n, (numeric) size of the latest best block`<br />&nbsp;&nbsp;`"currentblocktx": n, (numeric) number of transactions in the latest best block`<br />&nbsp;&nbsp;`"difficulty": n.nn, (numeric) current target difficulty`<br />&nbsp;&nbsp;`"errors": "errors", (string) any current errors`<br />&nbsp;&nbsp;`"generate": true or false, (boolean) whether or not server is set to generate coins`<br />&nbsp;&nbsp;`"genproclimit": n, (numeric) number of processors to use for coin generation (-1 when disabled)`<br />&nbsp;&nbsp;`"hashespersec": n, (numeric) recent hashes per second performance measurement while generating coins`<br />&nbsp;&nbsp;`"networkhashps": n, (numeric) estimated network hashes per second for the most recent blocks`<br />&nbsp;&nbsp;`"pooledtx": n, (numeric) number of transactions in the memory pool`<br />&nbsp;&nbsp;`"testnet": true or false, (boolean) whether or not server is using testnet`<br />`}`|
|Example Return|`{`<br />&nbsp;&nbsp;`"blocks": 236526,`<br />&nbsp;&nbsp;`"currentblocksize": 185,`<br />&nbsp;&nbsp;`"currentblocktx": 1,`<br />&nbsp;&nbsp;`"difficulty": 256,`<br />&nbsp;&nbsp;`"errors": "",`<br />&nbsp;&nbsp;`"generate": false,`<br />&nbsp;&nbsp;`"genproclimit": -1,`<br />&nbsp;&nbsp;`"hashespersec": 0,`<br />&nbsp;&nbsp;`"networkhashps": 33081554756,`<br />&nbsp;&nbsp;`"pooledtx": 8,`<br />&nbsp;&nbsp;`"testnet": true,`<br />`}`|
[Return to Overview](#MethodOverview)<br />
***
@ -446,7 +446,7 @@ Example Return|`{`<br />&nbsp;&nbsp;`"bytes": 310768,`<br />&nbsp;&nbsp;`"size":
|Parameters|1. transaction hash (string, required) - the hash of the transaction<br />2. verbose (int, optional, default=0) - specifies the transaction is returned as a JSON object instead of hex-encoded string|
|Description|Returns information about a transaction given its hash.|
|Returns (verbose=0)|`"data" (string) hex-encoded bytes of the serialized transaction`|
|Returns (verbose=1)|`{ (json object)`<br />&nbsp;&nbsp;`"hex": "data", (string) hex-encoded transaction`<br />&nbsp;&nbsp;`"txid": "hash", (string) the hash of the transaction`<br />&nbsp;&nbsp;`"version": n, (numeric) the transaction version`<br />&nbsp;&nbsp;`"locktime": n, (numeric) the transaction lock time`<br />&nbsp;&nbsp;`"vin": [ (array of json objects) the transaction inputs as json objects`<br />&nbsp;&nbsp;<font color="orange">For coinbase transactions:</font><br />&nbsp;&nbsp;&nbsp;&nbsp;`{ (json object)`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"coinbase": "data", (string) the hex-encoded bytes of the signature script`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"sequence": n, (numeric) the script sequence number`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"txinwitness": “data", (string) the witness stack for the input`<br />&nbsp;&nbsp;&nbsp;&nbsp;`}`<br />&nbsp;&nbsp;<font color="orange">For non-coinbase transactions:</font><br />&nbsp;&nbsp;&nbsp;&nbsp;`{ (json object)`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"txid": "hash", (string) the hash of the origin transaction`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"vout": n, (numeric) the index of the output being redeemed from the origin transaction`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"scriptSig": { (json object) the signature script used to redeem the origin transaction`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"asm": "asm", (string) disassembly of the script`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"hex": "data", (string) hex-encoded bytes of the script`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`}`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"sequence": n, (numeric) the script sequence number`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"txinwitness": “data", (string) the witness stack for the input`<br />&nbsp;&nbsp;&nbsp;&nbsp;`}, ...`<br />&nbsp;&nbsp;`]`<br />&nbsp;&nbsp;`"vout": [ (array of json objects) the transaction outputs as json objects`<br />&nbsp;&nbsp;&nbsp;&nbsp;`{ (json object)`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"value": n, (numeric) the value in BTC`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"n": n, (numeric) the index of this transaction output`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"scriptPubKey": { (json object) the public key script used to pay coins`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"asm": "asm", (string) disassembly of the script`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"hex": "data", (string) hex-encoded bytes of the script`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"reqSigs": n, (numeric) the number of required signatures`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"type": "scripttype" (string) the type of the script (e.g. 'pubkeyhash')`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"addresses": [ (json array of string) the bitcoin addresses associated with this output`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"bitcoinaddress", (string) the bitcoin address`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`...`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`]`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`}`<br />&nbsp;&nbsp;&nbsp;&nbsp;`}, ...`<br />&nbsp;&nbsp;`]`<br />`}`|
|Returns (verbose=1)|`{ (json object)`<br />&nbsp;&nbsp;`"hex": "data", (string) hex-encoded transaction`<br />&nbsp;&nbsp;`"txid": "hash", (string) the hash of the transaction`<br />&nbsp;&nbsp;`"version": n, (numeric) the transaction version`<br />&nbsp;&nbsp;`"locktime": n, (numeric) the transaction lock time`<br />&nbsp;&nbsp;`"vin": [ (array of json objects) the transaction inputs as json objects`<br />&nbsp;&nbsp;<font color="orange">For coinbase transactions:</font><br />&nbsp;&nbsp;&nbsp;&nbsp;`{ (json object)`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"coinbase": "data", (string) the hex-encoded bytes of the signature script`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"sequence": n, (numeric) the script sequence number`<br />&nbsp;&nbsp;&nbsp;&nbsp;`}`<br />&nbsp;&nbsp;<font color="orange">For non-coinbase transactions:</font><br />&nbsp;&nbsp;&nbsp;&nbsp;`{ (json object)`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"txid": "hash", (string) the hash of the origin transaction`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"vout": n, (numeric) the index of the output being redeemed from the origin transaction`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"scriptSig": { (json object) the signature script used to redeem the origin transaction`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"asm": "asm", (string) disassembly of the script`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"hex": "data", (string) hex-encoded bytes of the script`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`}`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"sequence": n, (numeric) the script sequence number`<br />&nbsp;&nbsp;&nbsp;&nbsp;`}, ...`<br />&nbsp;&nbsp;`]`<br />&nbsp;&nbsp;`"vout": [ (array of json objects) the transaction outputs as json objects`<br />&nbsp;&nbsp;&nbsp;&nbsp;`{ (json object)`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"value": n, (numeric) the value in BTC`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"n": n, (numeric) the index of this transaction output`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"scriptPubKey": { (json object) the public key script used to pay coins`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"asm": "asm", (string) disassembly of the script`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"hex": "data", (string) hex-encoded bytes of the script`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"reqSigs": n, (numeric) the number of required signatures`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"type": "scripttype" (string) the type of the script (e.g. 'pubkeyhash')`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"addresses": [ (json array of string) the bitcoin addresses associated with this output`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"bitcoinaddress", (string) the bitcoin address`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`...`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`]`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`}`<br />&nbsp;&nbsp;&nbsp;&nbsp;`}, ...`<br />&nbsp;&nbsp;`]`<br />`}`|
|Example Return (verbose=0)|`"010000000104be666c7053ef26c6110597dad1c1e81b5e6be53d17a8b9d0b34772054bac60000000`<br />`008c493046022100cb42f8df44eca83dd0a727988dcde9384953e830b1f8004d57485e2ede1b9c8f`<br />`022100fbce8d84fcf2839127605818ac6c3e7a1531ebc69277c504599289fb1e9058df0141045a33`<br />`76eeb85e494330b03c1791619d53327441002832f4bd618fd9efa9e644d242d5e1145cb9c2f71965`<br />`656e276633d4ff1a6db5e7153a0a9042745178ebe0f5ffffffff0280841e00000000001976a91406`<br />`f1b6703d3f56427bfcfd372f952d50d04b64bd88ac4dd52700000000001976a9146b63f291c295ee`<br />`abd9aee6be193ab2d019e7ea7088ac00000000`<br /><font color="orange">**Newlines added for display purposes. The actual return does not contain newlines.**</font>|
|Example Return (verbose=1)|`{`<br />&nbsp;&nbsp;`"hex": "01000000010000000000000000000000000000000000000000000000000000000000000000f...",`<br />&nbsp;&nbsp;`"txid": "90743aad855880e517270550d2a881627d84db5265142fd1e7fb7add38b08be9",`<br />&nbsp;&nbsp;`"version": 1,`<br />&nbsp;&nbsp;`"locktime": 0,`<br />&nbsp;&nbsp;`"vin": [`<br />&nbsp;&nbsp;<font color="orange">For coinbase transactions:</font><br />&nbsp;&nbsp;&nbsp;&nbsp;`{ (json object)`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"coinbase": "03708203062f503253482f04066d605108f800080100000ea2122f6f7a636f696e4065757374726174756d2f",`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"sequence": 0,`<br />&nbsp;&nbsp;&nbsp;&nbsp;`}`<br />&nbsp;&nbsp;<font color="orange">For non-coinbase transactions:</font><br />&nbsp;&nbsp;&nbsp;&nbsp;`{`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"txid": "60ac4b057247b3d0b9a8173de56b5e1be8c1d1da970511c626ef53706c66be04",`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"vout": 0,`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"scriptSig": {`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"asm": "3046022100cb42f8df44eca83dd0a727988dcde9384953e830b1f8004d57485e2ede1b9c8f0...",`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"hex": "493046022100cb42f8df44eca83dd0a727988dcde9384953e830b1f8004d57485e2ede1b9c8...",`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`}`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"sequence": 4294967295,`<br />&nbsp;&nbsp;&nbsp;&nbsp;`}`<br />&nbsp;&nbsp;`]`<br />&nbsp;&nbsp;`"vout": [`<br />&nbsp;&nbsp;&nbsp;&nbsp;`{`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"value": 25.1394,`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"n": 0,`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"scriptPubKey": {`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"asm": "OP_DUP OP_HASH160 ea132286328cfc819457b9dec386c4b5c84faa5c OP_EQUALVERIFY OP_CHECKSIG",`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"hex": "76a914ea132286328cfc819457b9dec386c4b5c84faa5c88ac",`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"reqSigs": 1,`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"type": "pubkeyhash"`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"addresses": [`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"1NLg3QJMsMQGM5KEUaEu5ADDmKQSLHwmyh",`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`]`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`}`<br />&nbsp;&nbsp;&nbsp;&nbsp;`}`<br />&nbsp;&nbsp;`]`<br />`}`|
[Return to Overview](#MethodOverview)<br />
@ -484,7 +484,7 @@ Example Return|`{`<br />&nbsp;&nbsp;`"bytes": 310768,`<br />&nbsp;&nbsp;`"size":
|Description|Returns an array of hashes for all of the transactions currently in the memory pool.<br />The `verbose` flag specifies that each transaction is returned as a JSON object.|
|Notes|<font color="orange">Since btcd does not perform any mining, the priority related fields `startingpriority` and `currentpriority` that are available when the `verbose` flag is set are always 0.</font>|
|Returns (verbose=false)|`[ (json array of string)`<br />&nbsp;&nbsp;`"transactionhash", (string) hash of the transaction`<br />&nbsp;&nbsp;`...`<br />`]`|
|Returns (verbose=true)|`{ (json object)`<br />&nbsp;&nbsp;`"transactionhash": { (json object)`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"size": n, (numeric) transaction size in bytes`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"vsize": n, (numeric) transaction virtual size`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"fee" : n, (numeric) transaction fee in bitcoins`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"time": n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"height": n, (numeric) block height when transaction entered the pool`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"startingpriority": n, (numeric) priority when transaction entered the pool`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"currentpriority": n, (numeric) current priority`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"depends": [ (json array) unconfirmed transactions used as inputs for this transaction`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"transactionhash", (string) hash of the parent transaction`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`...`<br />&nbsp;&nbsp;&nbsp;&nbsp;`]`<br />&nbsp;&nbsp;`}, ...`<br />`}`|
|Returns (verbose=true)|`{ (json object)`<br />&nbsp;&nbsp;`"transactionhash": { (json object)`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"size": n, (numeric) transaction size in bytes`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"size": n, (numeric) transaction virtual size`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"fee" : n, (numeric) transaction fee in bitcoins`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"time": n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"height": n, (numeric) block height when transaction entered the pool`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"startingpriority": n, (numeric) priority when transaction entered the pool`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"currentpriority": n, (numeric) current priority`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"depends": [ (json array) unconfirmed transactions used as inputs for this transaction`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"transactionhash", (string) hash of the parent transaction`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`...`<br />&nbsp;&nbsp;&nbsp;&nbsp;`]`<br />&nbsp;&nbsp;`}, ...`<br />`}`|
|Example Return (verbose=false)|`[`<br />&nbsp;&nbsp;`"3480058a397b6ffcc60f7e3345a61370fded1ca6bef4b58156ed17987f20d4e7",`<br />&nbsp;&nbsp;`"cbfe7c056a358c3a1dbced5a22b06d74b8650055d5195c1c2469e6b63a41514a"`<br />`]`|
|Example Return (verbose=true)|`{`<br />&nbsp;&nbsp;`"1697a19cede08694278f19584e8dcc87945f40c6b59a942dd8906f133ad3f9cc": {`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"size": 226,`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"fee" : 0.0001,`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"time": 1387992789,`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"height": 276836,`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"startingpriority": 0,`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"currentpriority": 0,`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"depends": [`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"aa96f672fcc5a1ec6a08a94aa46d6b789799c87bd6542967da25a96b2dee0afb",`<br />&nbsp;&nbsp;&nbsp;&nbsp;`]`<br />`}`|
[Return to Overview](#MethodOverview)<br />
@ -634,7 +634,7 @@ The following is an overview of the RPC methods which are implemented by btcd, b
|Parameters|1. address (string, required) - bitcoin address <br /> 2. verbose (int, optional, default=true) - specifies the transaction is returned as a JSON object instead of hex-encoded string <br />3. skip (int, optional, default=0) - the number of leading transactions to leave out of the final response <br /> 4. count (int, optional, default=100) - the maximum number of transactions to return <br /> 5. vinextra (int, optional, default=0) - Specify that extra data from previous output will be returned in vin <br /> 6. reverse (boolean, optional, default=false) - Specifies that the transactions should be returned in reverse chronological order|
|Description|Returns raw data for transactions involving the passed address. Returned transactions are pulled from both the database, and transactions currently in the mempool. Transactions pulled from the mempool will have the `"confirmations"` field set to 0. Usage of this RPC requires the optional `--addrindex` flag to be activated, otherwise all responses will simply return with an error stating the address index has not yet been built up. Similarly, until the address index has caught up with the current best height, all requests will return an error response in order to avoid serving stale data.|
|Returns (verbose=0)|`[ (json array of strings)` <br/>&nbsp;&nbsp; `"serializedtx", ... hex-encoded bytes of the serialized transaction` <br/>`]` |
|Returns (verbose=1)|`[ (array of json objects)` <br/> &nbsp;&nbsp; `{ (json object)`<br />&nbsp;&nbsp;`"hex": "data", (string) hex-encoded transaction`<br />&nbsp;&nbsp;`"txid": "hash", (string) the hash of the transaction`<br />&nbsp;&nbsp;`"version": n, (numeric) the transaction version`<br />&nbsp;&nbsp;`"locktime": n, (numeric) the transaction lock time`<br />&nbsp;&nbsp;`"vin": [ (array of json objects) the transaction inputs as json objects`<br />&nbsp;&nbsp;<font color="orange">For coinbase transactions:</font><br />&nbsp;&nbsp;&nbsp;&nbsp;`{ (json object)`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"coinbase": "data", (string) the hex-encoded bytes of the signature script`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"txinwitness": “data", (string) the witness stack for the input`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"sequence": n, (numeric) the script sequence number`<br />&nbsp;&nbsp;&nbsp;&nbsp;`}`<br />&nbsp;&nbsp;<font color="orange">For non-coinbase transactions:</font><br />&nbsp;&nbsp;&nbsp;&nbsp;`{ (json object)`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"txid": "hash", (string) the hash of the origin transaction`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"vout": n, (numeric) the index of the output being redeemed from the origin transaction`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"scriptSig": { (json object) the signature script used to redeem the origin transaction`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"asm": "asm", (string) disassembly of the script`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"hex": "data", (string) hex-encoded bytes of the script`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`}`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"prevOut": { (json object) Data from the origin transaction output with index vout.`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"addresses": ["value",...], (array of string) previous output addresses`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"value": n.nnn, (numeric) previous output value`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`}`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"txinwitness": “data", (string) the witness stack for the input`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"sequence": n, (numeric) the script sequence number`<br />&nbsp;&nbsp;&nbsp;&nbsp;`}, ...`<br />&nbsp;&nbsp;`]`<br />&nbsp;&nbsp;`"vout": [ (array of json objects) the transaction outputs as json objects`<br />&nbsp;&nbsp;&nbsp;&nbsp;`{ (json object)`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"value": n, (numeric) the value in BTC`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"n": n, (numeric) the index of this transaction output`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"scriptPubKey": { (json object) the public key script used to pay coins`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"asm": "asm", (string) disassembly of the script`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"hex": "data", (string) hex-encoded bytes of the script`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"reqSigs": n, (numeric) the number of required signatures`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"type": "scripttype" (string) the type of the script (e.g. 'pubkeyhash')`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"addresses": [ (json array of string) the bitcoin addresses associated with this output`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"address", (string) the bitcoin address`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`...`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`]`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`}`<br />&nbsp;&nbsp;&nbsp;&nbsp;`}, ...`<br /> &nbsp;&nbsp;&nbsp;`]`<br />&nbsp;&nbsp; `"blockhash":"hash" Hash of the block the transaction is part of.` <br /> &nbsp;&nbsp; `"confirmations":n, Number of numeric confirmations of block.` <br /> &nbsp;&nbsp;&nbsp;`"time":t, Transaction time in seconds since the epoch.` <br /> &nbsp;&nbsp;&nbsp;`"blocktime":t, Block time in seconds since the epoch.`<br />`},...`<br/> `]`|
|Returns (verbose=1)|`[ (array of json objects)` <br/> &nbsp;&nbsp; `{ (json object)`<br />&nbsp;&nbsp;`"hex": "data", (string) hex-encoded transaction`<br />&nbsp;&nbsp;`"txid": "hash", (string) the hash of the transaction`<br />&nbsp;&nbsp;`"version": n, (numeric) the transaction version`<br />&nbsp;&nbsp;`"locktime": n, (numeric) the transaction lock time`<br />&nbsp;&nbsp;`"vin": [ (array of json objects) the transaction inputs as json objects`<br />&nbsp;&nbsp;<font color="orange">For coinbase transactions:</font><br />&nbsp;&nbsp;&nbsp;&nbsp;`{ (json object)`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"coinbase": "data", (string) the hex-encoded bytes of the signature script`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"sequence": n, (numeric) the script sequence number`<br />&nbsp;&nbsp;&nbsp;&nbsp;`}`<br />&nbsp;&nbsp;<font color="orange">For non-coinbase transactions:</font><br />&nbsp;&nbsp;&nbsp;&nbsp;`{ (json object)`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"txid": "hash", (string) the hash of the origin transaction`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"vout": n, (numeric) the index of the output being redeemed from the origin transaction`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"scriptSig": { (json object) the signature script used to redeem the origin transaction`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"asm": "asm", (string) disassembly of the script`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"hex": "data", (string) hex-encoded bytes of the script`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`}`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"prevOut": { (json object) Data from the origin transaction output with index vout.`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"addresses": ["value",...], (array of string) previous output addresses`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"value": n.nnn, (numeric) previous output value`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`}`<br />&nbsp;&nbsp;&nbsp;&nbsp;`"sequence": n, (numeric) the script sequence number`<br />&nbsp;&nbsp;&nbsp;&nbsp;`}, ...`<br />&nbsp;&nbsp;`]`<br />&nbsp;&nbsp;`"vout": [ (array of json objects) the transaction outputs as json objects`<br />&nbsp;&nbsp;&nbsp;&nbsp;`{ (json object)`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"value": n, (numeric) the value in BTC`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"n": n, (numeric) the index of this transaction output`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"scriptPubKey": { (json object) the public key script used to pay coins`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"asm": "asm", (string) disassembly of the script`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"hex": "data", (string) hex-encoded bytes of the script`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"reqSigs": n, (numeric) the number of required signatures`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"type": "scripttype" (string) the type of the script (e.g. 'pubkeyhash')`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"addresses": [ (json array of string) the bitcoin addresses associated with this output`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`"address", (string) the bitcoin address`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`...`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`]`<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`}`<br />&nbsp;&nbsp;&nbsp;&nbsp;`}, ...`<br /> &nbsp;&nbsp;&nbsp;`]`<br />&nbsp;&nbsp; `"blockhash":"hash" Hash of the block the transaction is part of.` <br /> &nbsp;&nbsp; `"confirmations":n, Number of numeric confirmations of block.` <br /> &nbsp;&nbsp;&nbsp;`"time":t, Transaction time in seconds since the epoch.` <br /> &nbsp;&nbsp;&nbsp;`"blocktime":t, Block time in seconds since the epoch.`<br />`},...`<br/> `]`|
[Return to Overview](#ExtMethodOverview)<br />
***

View File

@ -299,7 +299,6 @@ func TestBIP0009(t *testing.T) {
t.Parallel()
testBIP0009(t, "dummy", chaincfg.DeploymentTestDummy)
testBIP0009(t, "segwit", chaincfg.DeploymentSegwit)
}
// TestBIP0009Mining ensures blocks built via btcd's CPU miner follow the rules

View File

@ -181,7 +181,7 @@ func CreateBlock(prevBlock *btcutil.Block, inclusionTxs []*btcutil.Tx,
if inclusionTxs != nil {
blockTxns = append(blockTxns, inclusionTxs...)
}
merkles := blockchain.BuildMerkleTreeStore(blockTxns, false)
merkles := blockchain.BuildMerkleTreeStore(blockTxns)
var block wire.MsgBlock
block.Header = wire.BlockHeader{
Version: blockVersion,

View File

@ -403,7 +403,7 @@ func (m *memWallet) fundTx(tx *wire.MsgTx, amt btcutil.Amount, feeRate btcutil.A
// Add the selected output to the transaction, updating the
// current tx size while accounting for the size of the future
// sigScript.
tx.AddTxIn(wire.NewTxIn(&outPoint, nil, nil))
tx.AddTxIn(wire.NewTxIn(&outPoint, nil))
txSize = tx.SerializeSize() + spendSize*len(tx.TxIn)
// Calculate the fee required for the txn at this point

View File

@ -208,7 +208,7 @@ func (ef *FeeEstimator) ObserveTransaction(t *TxDesc) {
hash := *t.Tx.Hash()
if _, ok := ef.observed[hash]; !ok {
size := uint32(GetTxVirtualSize(t.Tx))
size := uint32(t.Tx.MsgTx().SerializeSize())
ef.observed[hash] = &observedTransaction{
hash: hash,

View File

@ -82,9 +82,6 @@ type Config struct {
// SigCache defines a signature cache to use.
SigCache *txscript.SigCache
// HashCache defines the transaction hash mid-state cache to use.
HashCache *txscript.HashCache
// AddrIndex defines the optional address index instance to use for
// indexing the unconfirmed transactions in the memory pool.
// This can be nil if the address index is not enabled.
@ -125,10 +122,10 @@ type Policy struct {
// of big orphans.
MaxOrphanTxSize int
// MaxSigOpCostPerTx is the cumulative maximum cost of all the signature
// operations in a single transaction we will relay or mine. It is a
// fraction of the max signature operations for a block.
MaxSigOpCostPerTx int
// MaxSigOpsPerTx is the maximum number of signature operations
// in a single transaction we will relay or mine. It is a fraction
// of the max signature operations for a block.
MaxSigOpsPerTx int
// MinRelayTxFee defines the minimum transaction fee in BTC/kB to be
// considered a non-zero fee.
@ -527,7 +524,7 @@ func (mp *TxPool) addTransaction(utxoView *blockchain.UtxoViewpoint, tx *btcutil
Added: time.Now(),
Height: height,
Fee: fee,
FeePerKB: fee * 1000 / GetTxVirtualSize(tx),
FeePerKB: fee * 1000 / int64(tx.MsgTx().SerializeSize()),
},
StartingPriority: mining.CalcPriority(tx.MsgTx(), utxoView, height),
}
@ -639,22 +636,6 @@ func (mp *TxPool) FetchTransaction(txHash *chainhash.Hash) (*btcutil.Tx, error)
func (mp *TxPool) maybeAcceptTransaction(tx *btcutil.Tx, isNew, rateLimit, rejectDupOrphans bool) ([]*chainhash.Hash, *TxDesc, error) {
txHash := tx.Hash()
// If a transaction has iwtness data, and segwit isn't active yet, If
// segwit isn't active yet, then we won't accept it into the mempool as
// it can't be mined yet.
if tx.MsgTx().HasWitness() {
segwitActive, err := mp.cfg.IsDeploymentActive(chaincfg.DeploymentSegwit)
if err != nil {
return nil, nil, err
}
if !segwitActive {
str := fmt.Sprintf("transaction %v has witness data, "+
"but segwit isn't active yet", txHash)
return nil, nil, txRuleError(wire.RejectNonstandard, str)
}
}
// Don't accept the transaction if it already exists in the pool. This
// applies to orphan transactions as well when the reject duplicate
// orphans flag is set. This check is intended to be a quick check to
@ -825,17 +806,16 @@ func (mp *TxPool) maybeAcceptTransaction(tx *btcutil.Tx, isNew, rateLimit, rejec
// the coinbase address itself can contain signature operations, the
// maximum allowed signature operations per transaction is less than
// the maximum allowed signature operations per block.
// TODO(roasbeef): last bool should be conditional on segwit activation
sigOpCost, err := blockchain.GetSigOpCost(tx, false, utxoView, true, true)
sigOpCount, err := blockchain.CountP2SHSigOps(tx, false, utxoView)
if err != nil {
if cerr, ok := err.(blockchain.RuleError); ok {
return nil, nil, chainRuleError(cerr)
}
return nil, nil, err
}
if sigOpCost > mp.cfg.Policy.MaxSigOpCostPerTx {
str := fmt.Sprintf("transaction %v sigop cost is too high: %d > %d",
txHash, sigOpCost, mp.cfg.Policy.MaxSigOpCostPerTx)
if sigOpCount > mp.cfg.Policy.MaxSigOpsPerTx {
str := fmt.Sprintf("transaction %v sigop count is too high: %d > %d",
txHash, sigOpCount, mp.cfg.Policy.MaxSigOpsPerTx)
return nil, nil, txRuleError(wire.RejectNonstandard, str)
}
@ -850,7 +830,7 @@ func (mp *TxPool) maybeAcceptTransaction(tx *btcutil.Tx, isNew, rateLimit, rejec
// which is more desirable. Therefore, as long as the size of the
// transaction does not exceeed 1000 less than the reserved space for
// high-priority transactions, don't require a fee for it.
serializedSize := GetTxVirtualSize(tx)
serializedSize := int64(tx.MsgTx().SerializeSize())
minFee := calcMinRequiredTxRelayFee(serializedSize,
mp.cfg.Policy.MinRelayTxFee)
if serializedSize >= (DefaultBlockPrioritySize-1000) && txFee < minFee {
@ -902,8 +882,7 @@ func (mp *TxPool) maybeAcceptTransaction(tx *btcutil.Tx, isNew, rateLimit, rejec
// Verify crypto signatures for each input and reject the transaction if
// any don't verify.
err = blockchain.ValidateTransactionScripts(tx, utxoView,
txscript.StandardVerifyFlags, mp.cfg.SigCache,
mp.cfg.HashCache)
txscript.StandardVerifyFlags, mp.cfg.SigCache)
if err != nil {
if cerr, ok := err.(blockchain.RuleError); ok {
return nil, nil, chainRuleError(cerr)
@ -1196,7 +1175,6 @@ func (mp *TxPool) RawMempoolVerbose() map[string]*btcjson.GetRawMempoolVerboseRe
mpd := &btcjson.GetRawMempoolVerboseResult{
Size: int32(tx.MsgTx().SerializeSize()),
Vsize: int32(GetTxVirtualSize(tx)),
Fee: btcutil.Amount(desc.Fee).ToBTC(),
Time: desc.Added.Unix(),
Height: int64(desc.Height),

View File

@ -313,7 +313,7 @@ func newPoolHarness(chainParams *chaincfg.Params) (*poolHarness, []spendableOutp
FreeTxRelayLimit: 15.0,
MaxOrphanTxs: 5,
MaxOrphanTxSize: 1000,
MaxSigOpCostPerTx: blockchain.MaxBlockSigOpsCost / 4,
MaxSigOpsPerTx: blockchain.MaxSigOpsPerBlock / 5,
MinRelayTxFee: 1000, // 1 Satoshi per byte
MaxTxVersion: 1,
},

View File

@ -19,10 +19,6 @@ const (
// that are considered standard in a pay-to-script-hash script.
maxStandardP2SHSigOps = 15
// maxStandardTxCost is the max weight permitted by any transaction
// according to the current default policy.
maxStandardTxWeight = 400000
// maxStandardSigScriptSize is the maximum size allowed for a
// transaction input signature script to be considered standard. This
// value allows for a 15-of-15 CHECKMULTISIG pay-to-script-hash with
@ -42,6 +38,11 @@ const (
// (1 + 15*74 + 3) + (15*34 + 3) + 23 = 1650
maxStandardSigScriptSize = 1650
// MaxStandardTxSize is the maximum size allowed for transactions that
// are considered standard and will therefore be relayed and considered
// for mining.
MaxStandardTxSize = 100000
// DefaultMinRelayTxFee is the minimum fee in satoshi that is required
// for a transaction to be treated as free for relay and mining
// purposes. It is also used to help determine if a transaction is
@ -215,18 +216,6 @@ func isDust(txOut *wire.TxOut, minRelayTxFee btcutil.Amount) bool {
// 36 prev outpoint, 1 script len, 73 script [1 OP_DATA_72,
// 72 sig], 4 sequence
//
// Pay-to-witness-pubkey-hash bytes breakdown:
//
// Output to witness key hash (31 bytes);
// 8 value, 1 script len, 22 script [1 OP_0, 1 OP_DATA_20,
// 20 bytes hash160]
//
// Input (67 bytes as the 107 witness stack is discounted):
// 36 prev outpoint, 1 script len, 0 script (not sigScript), 107
// witness stack bytes [1 element length, 33 compressed pubkey,
// element length 72 sig], 4 sequence
//
//
// Theoretically this could examine the script type of the output script
// and use a different size for the typical input script size for
// pay-to-pubkey vs pay-to-pubkey-hash inputs per the above breakdowns,
@ -236,22 +225,8 @@ func isDust(txOut *wire.TxOut, minRelayTxFee btcutil.Amount) bool {
//
// The most common scripts are pay-to-pubkey-hash, and as per the above
// breakdown, the minimum size of a p2pkh input script is 148 bytes. So
// that figure is used. If the output being spent is a witness program,
// then we apply the witness discount to the size of the signature.
//
// The segwit analogue to p2pkh is a p2wkh output. This is the smallest
// output possible using the new segwit features. The 107 bytes of
// witness data is discounted by a factor of 4, leading to a computed
// value of 67 bytes of witness data.
//
// Both cases share a 41 byte preamble required to reference the input
// being spent and the sequence number of the input.
totalSize := txOut.SerializeSize() + 41
if txscript.IsWitnessProgram(txOut.PkScript) {
totalSize += (107 / blockchain.WitnessScaleFactor)
} else {
totalSize += 107
}
// that figure is used.
totalSize := txOut.SerializeSize() + 148
// The output is considered dust if the cost to the network to spend the
// coins is more than 1/3 of the minimum free transaction relay fee.
@ -299,10 +274,10 @@ func checkTransactionStandard(tx *btcutil.Tx, height int32,
// almost as much to process as the sender fees, limit the maximum
// size of a transaction. This also helps mitigate CPU exhaustion
// attacks.
txWeight := blockchain.GetTransactionWeight(tx)
if txWeight > maxStandardTxWeight {
str := fmt.Sprintf("weight of transaction %v is larger than max "+
"allowed weight of %v", txWeight, maxStandardTxWeight)
serializedLen := msgTx.SerializeSize()
if serializedLen > MaxStandardTxSize {
str := fmt.Sprintf("transaction size of %v is larger than max "+
"allowed size of %v", serializedLen, MaxStandardTxSize)
return txRuleError(wire.RejectNonstandard, str)
}
@ -367,16 +342,3 @@ func checkTransactionStandard(tx *btcutil.Tx, height int32,
return nil
}
// GetTxVirtualSize computes the virtual size of a given transaction. A
// transaction's virtual size is based off its weight, creating a discount for
// any witness data it contains, proportional to the current
// blockchain.WitnessScaleFactor value.
func GetTxVirtualSize(tx *btcutil.Tx) int64 {
// vSize := (weight(tx) + 3) / 4
// := (((baseSize * 3) + totalSize) + 3) / 4
// We add 3 here as a way to compute the ceiling of the prior arithmetic
// to 4. The division by 4 creates a discount for wit witness data.
return (blockchain.GetTransactionWeight(tx) + (blockchain.WitnessScaleFactor - 1)) /
blockchain.WitnessScaleFactor
}

View File

@ -41,13 +41,13 @@ func TestCalcMinRequiredTxRelayFee(t *testing.T) {
},
{
"max standard tx size with default minimum relay fee",
maxStandardTxWeight / 4,
MaxStandardTxSize,
DefaultMinRelayTxFee,
100000,
},
{
"max standard tx size with max satoshi relay fee",
maxStandardTxWeight / 4,
MaxStandardTxSize,
btcutil.MaxSatoshi,
btcutil.MaxSatoshi,
},
@ -360,7 +360,7 @@ func TestCheckTransactionStandard(t *testing.T) {
TxOut: []*wire.TxOut{{
Value: 0,
PkScript: bytes.Repeat([]byte{0x00},
(maxStandardTxWeight/4)+1),
MaxStandardTxSize+1),
}},
LockTime: 0,
},

View File

@ -5,7 +5,6 @@
package mining
import (
"bytes"
"container/heap"
"fmt"
"time"
@ -198,9 +197,9 @@ type BlockTemplate struct {
// sum of the fees of all other transactions.
Fees []int64
// SigOpCosts contains the number of signature operations each
// SigOpCounts contains the number of signature operations each
// transaction in the generated template performs.
SigOpCosts []int64
SigOpCounts []int64
// Height is the height at which the block template connects to the main
// chain.
@ -211,12 +210,6 @@ type BlockTemplate struct {
// NewBlockTemplate for details on which this can be useful to generate
// templates without a coinbase payment address.
ValidPayAddress bool
// WitnessCommitment is a commitment to the witness data (if any)
// within the block. This field will only be populted once segregated
// witness has been activated, and the block contains a transaction
// which has witness data.
WitnessCommitment []byte
}
// mergeUtxoView adds all of the entries in viewB to viewA. The result is that
@ -352,7 +345,6 @@ type BlkTmplGenerator struct {
chain *blockchain.BlockChain
timeSource blockchain.MedianTimeSource
sigCache *txscript.SigCache
hashCache *txscript.HashCache
}
// NewBlkTmplGenerator returns a new block template generator for the given
@ -364,8 +356,7 @@ type BlkTmplGenerator struct {
func NewBlkTmplGenerator(policy *Policy, params *chaincfg.Params,
txSource TxSource, chain *blockchain.BlockChain,
timeSource blockchain.MedianTimeSource,
sigCache *txscript.SigCache,
hashCache *txscript.HashCache) *BlkTmplGenerator {
sigCache *txscript.SigCache) *BlkTmplGenerator {
return &BlkTmplGenerator{
policy: policy,
@ -374,7 +365,6 @@ func NewBlkTmplGenerator(policy *Policy, params *chaincfg.Params,
chain: chain,
timeSource: timeSource,
sigCache: sigCache,
hashCache: hashCache,
}
}
@ -463,7 +453,7 @@ func (g *BlkTmplGenerator) NewBlockTemplate(payToAddress btcutil.Address) (*Bloc
if err != nil {
return nil, err
}
coinbaseSigOpCost := int64(blockchain.CountSigOps(coinbaseTx)) * blockchain.WitnessScaleFactor
numCoinbaseSigOps := int64(blockchain.CountSigOps(coinbaseTx))
// Get the current source transactions and create a priority queue to
// hold the transactions which are ready for inclusion into a block
@ -497,9 +487,9 @@ func (g *BlkTmplGenerator) NewBlockTemplate(payToAddress btcutil.Address) (*Bloc
// However, since the total fees aren't known yet, use a dummy value for
// the coinbase fee which will be updated later.
txFees := make([]int64, 0, len(sourceTxns))
txSigOpCosts := make([]int64, 0, len(sourceTxns))
txSigOpCounts := make([]int64, 0, len(sourceTxns))
txFees = append(txFees, -1) // Updated once known
txSigOpCosts = append(txSigOpCosts, coinbaseSigOpCost)
txSigOpCounts = append(txSigOpCounts, numCoinbaseSigOps)
log.Debugf("Considering %d transactions for inclusion to new block",
len(sourceTxns))
@ -597,23 +587,10 @@ mempoolLoop:
// The starting block size is the size of the block header plus the max
// possible transaction count size, plus the size of the coinbase
// transaction.
blockWeight := uint32((blockHeaderOverhead * blockchain.WitnessScaleFactor) +
blockchain.GetTransactionWeight(coinbaseTx))
blockSigOpCost := coinbaseSigOpCost
blockSize := blockHeaderOverhead + uint32(coinbaseTx.MsgTx().SerializeSize())
blockSigOps := numCoinbaseSigOps
totalFees := int64(0)
// Query the version bits state to see if segwit has been activated, if
// so then this means that we'll include any transactions with witness
// data in the mempool, and also add the witness commitment as an
// OP_RETURN output in the coinbase transaction.
segwitState, err := g.chain.ThresholdState(chaincfg.DeploymentSegwit)
if err != nil {
return nil, err
}
segwitActive := segwitState == blockchain.ThresholdActive
witnessIncluded := false
// Choose which transactions make it into the block.
for priorityQueue.Len() > 0 {
// Grab the highest priority (or highest fee per kilobyte
@ -621,72 +598,42 @@ mempoolLoop:
prioItem := heap.Pop(priorityQueue).(*txPrioItem)
tx := prioItem.tx
switch {
// If segregated witness has not been activated yet, then we
// shouldn't include any witness transactions in the block.
case !segwitActive && tx.HasWitness():
continue
// Otherwise, Keep track of if we've included a transaction
// with witness data or not. If so, then we'll need to include
// the witness commitment as the last output in the coinbase
// transaction.
case segwitActive && !witnessIncluded && tx.HasWitness():
// If we're about to include a transaction bearing
// witness data, then we'll also need to include a
// witness commitment in the coinbase transaction.
// Therefore, we account for the additional weight
// within the block with a model coinbase tx with a
// witness commitment.
coinbaseCopy := btcutil.NewTx(coinbaseTx.MsgTx().Copy())
coinbaseCopy.MsgTx().TxIn[0].Witness = [][]byte{
bytes.Repeat([]byte("a"),
blockchain.CoinbaseWitnessDataLen),
}
coinbaseCopy.MsgTx().AddTxOut(&wire.TxOut{
PkScript: bytes.Repeat([]byte("a"),
blockchain.CoinbaseWitnessPkScriptLength),
})
// In order to accurately account for the weight
// addition due to this coinbase transaction, we'll add
// the difference of the transaction before and after
// the addition of the commitment to the block weight.
weightDiff := blockchain.GetTransactionWeight(coinbaseCopy) -
blockchain.GetTransactionWeight(coinbaseTx)
blockWeight += uint32(weightDiff)
witnessIncluded = true
}
// Grab any transactions which depend on this one.
deps := dependers[*tx.Hash()]
// Enforce maximum block size. Also check for overflow.
txWeight := uint32(blockchain.GetTransactionWeight(tx))
blockPlusTxWeight := blockWeight + txWeight
if blockPlusTxWeight < blockWeight ||
blockPlusTxWeight >= g.policy.BlockMaxWeight {
txSize := uint32(tx.MsgTx().SerializeSize())
blockPlusTxSize := blockSize + txSize
if blockPlusTxSize < blockSize ||
blockPlusTxSize >= g.policy.BlockMaxSize {
log.Tracef("Skipping tx %s because it would exceed "+
"the max block weight", tx.Hash())
"the max block size", tx.Hash())
logSkippedDeps(tx, deps)
continue
}
// Enforce maximum signature operation cost per block. Also
// check for overflow.
sigOpCost, err := blockchain.GetSigOpCost(tx, false,
blockUtxos, true, segwitActive)
// Enforce maximum signature operations per block. Also check
// for overflow.
numSigOps := int64(blockchain.CountSigOps(tx))
if blockSigOps+numSigOps < blockSigOps ||
blockSigOps+numSigOps > blockchain.MaxSigOpsPerBlock {
log.Tracef("Skipping tx %s because it would exceed "+
"the maximum sigops per block", tx.Hash())
logSkippedDeps(tx, deps)
continue
}
numP2SHSigOps, err := blockchain.CountP2SHSigOps(tx, false,
blockUtxos)
if err != nil {
log.Tracef("Skipping tx %s due to error in "+
"GetSigOpCost: %v", tx.Hash(), err)
logSkippedDeps(tx, deps)
continue
}
if blockSigOpCost+int64(sigOpCost) < blockSigOpCost ||
blockSigOpCost+int64(sigOpCost) > blockchain.MaxBlockSigOpsCost {
numSigOps += int64(numP2SHSigOps)
if blockSigOps+numSigOps < blockSigOps ||
blockSigOps+numSigOps > blockchain.MaxSigOpsPerBlock {
log.Tracef("Skipping tx %s because it would "+
"exceed the maximum sigops per block", tx.Hash())
logSkippedDeps(tx, deps)
@ -697,13 +644,13 @@ mempoolLoop:
// minimum block size.
if sortedByFee &&
prioItem.feePerKB < int64(g.policy.TxMinFreeFee) &&
blockPlusTxWeight >= g.policy.BlockMinWeight {
blockPlusTxSize >= g.policy.BlockMinSize {
log.Tracef("Skipping tx %s with feePerKB %d "+
"< TxMinFreeFee %d and block weight %d >= "+
"minBlockWeight %d", tx.Hash(), prioItem.feePerKB,
g.policy.TxMinFreeFee, blockPlusTxWeight,
g.policy.BlockMinWeight)
log.Tracef("Skipping tx %s with feePerKB %.2f "+
"< TxMinFreeFee %d and block size %d >= "+
"minBlockSize %d", tx.Hash(), prioItem.feePerKB,
g.policy.TxMinFreeFee, blockPlusTxSize,
g.policy.BlockMinSize)
logSkippedDeps(tx, deps)
continue
}
@ -711,13 +658,13 @@ mempoolLoop:
// Prioritize by fee per kilobyte once the block is larger than
// the priority size or there are no more high-priority
// transactions.
if !sortedByFee && (blockPlusTxWeight >= g.policy.BlockPrioritySize ||
if !sortedByFee && (blockPlusTxSize >= g.policy.BlockPrioritySize ||
prioItem.priority <= MinHighPriority) {
log.Tracef("Switching to sort by fees per "+
"kilobyte blockSize %d >= BlockPrioritySize "+
"%d || priority %.2f <= minHighPriority %.2f",
blockPlusTxWeight, g.policy.BlockPrioritySize,
log.Tracef("Switching to sort by fees per kilobyte "+
"blockSize %d >= BlockPrioritySize %d || "+
"priority %.2f <= minHighPriority %.2f",
blockPlusTxSize, g.policy.BlockPrioritySize,
prioItem.priority, MinHighPriority)
sortedByFee = true
@ -729,7 +676,7 @@ mempoolLoop:
// is too low. Otherwise this transaction will be the
// final one in the high-priority section, so just fall
// though to the code below so it is added now.
if blockPlusTxWeight > g.policy.BlockPrioritySize ||
if blockPlusTxSize > g.policy.BlockPrioritySize ||
prioItem.priority < MinHighPriority {
heap.Push(priorityQueue, prioItem)
@ -748,8 +695,7 @@ mempoolLoop:
continue
}
err = blockchain.ValidateTransactionScripts(tx, blockUtxos,
txscript.StandardVerifyFlags, g.sigCache,
g.hashCache)
txscript.StandardVerifyFlags, g.sigCache)
if err != nil {
log.Tracef("Skipping tx %s due to error in "+
"ValidateTransactionScripts: %v", tx.Hash(), err)
@ -767,11 +713,11 @@ mempoolLoop:
// save the fees and signature operation counts to the block
// template.
blockTxns = append(blockTxns, tx)
blockWeight += txWeight
blockSigOpCost += int64(sigOpCost)
blockSize += txSize
blockSigOps += int64(numSigOps)
totalFees += prioItem.fee
txFees = append(txFees, prioItem.fee)
txSigOpCosts = append(txSigOpCosts, int64(sigOpCost))
txSigOpCounts = append(txSigOpCounts, numSigOps)
log.Tracef("Adding tx %s (priority %.2f, feePerKB %.2f)",
prioItem.tx.Hash(), prioItem.priority, prioItem.feePerKB)
@ -790,55 +736,13 @@ mempoolLoop:
}
// Now that the actual transactions have been selected, update the
// block weight for the real transaction count and coinbase value with
// block size for the real transaction count and coinbase value with
// the total fees accordingly.
blockWeight -= wire.MaxVarIntPayload -
(uint32(wire.VarIntSerializeSize(uint64(len(blockTxns)))) *
blockchain.WitnessScaleFactor)
blockSize -= wire.MaxVarIntPayload -
uint32(wire.VarIntSerializeSize(uint64(len(blockTxns))))
coinbaseTx.MsgTx().TxOut[0].Value += totalFees
txFees[0] = -totalFees
// If segwit is active and we included transactions with witness data,
// then we'll need to include a commitment to the witness data in an
// OP_RETURN output within the coinbase transaction.
var witnessCommitment []byte
if witnessIncluded {
// The witness of the coinbase transaction MUST be exactly 32-bytes
// of all zeroes.
var witnessNonce [blockchain.CoinbaseWitnessDataLen]byte
coinbaseTx.MsgTx().TxIn[0].Witness = wire.TxWitness{witnessNonce[:]}
// Next, obtain the merkle root of a tree which consists of the
// wtxid of all transactions in the block. The coinbase
// transaction will have a special wtxid of all zeroes.
witnessMerkleTree := blockchain.BuildMerkleTreeStore(blockTxns,
true)
witnessMerkleRoot := witnessMerkleTree[len(witnessMerkleTree)-1]
// The preimage to the witness commitment is:
// witnessRoot || coinbaseWitness
var witnessPreimage [64]byte
copy(witnessPreimage[:32], witnessMerkleRoot[:])
copy(witnessPreimage[32:], witnessNonce[:])
// The witness commitment itself is the double-sha256 of the
// witness preimage generated above. With the commitment
// generated, the witness script for the output is: OP_RETURN
// OP_DATA_36 {0xaa21a9ed || witnessCommitment}. The leading
// prefix is referred to as the "witness magic bytes".
witnessCommitment = chainhash.DoubleHashB(witnessPreimage[:])
witnessScript := append(blockchain.WitnessMagicBytes, witnessCommitment...)
// Finally, create the OP_RETURN carrying witness commitment
// output as an additional output within the coinbase.
commitmentOutput := &wire.TxOut{
Value: 0,
PkScript: witnessScript,
}
coinbaseTx.MsgTx().TxOut = append(coinbaseTx.MsgTx().TxOut,
commitmentOutput)
}
// Calculate the required difficulty for the block. The timestamp
// is potentially adjusted to ensure it comes after the median time of
// the last several blocks per the chain consensus rules.
@ -856,7 +760,7 @@ mempoolLoop:
}
// Create a new block ready to be solved.
merkles := blockchain.BuildMerkleTreeStore(blockTxns, false)
merkles := blockchain.BuildMerkleTreeStore(blockTxns)
var msgBlock wire.MsgBlock
msgBlock.Header = wire.BlockHeader{
Version: nextBlockVersion,
@ -880,18 +784,17 @@ mempoolLoop:
return nil, err
}
log.Debugf("Created new block template (%d transactions, %d in "+
"fees, %d signature operations cost, %d weight, target difficulty "+
"%064x)", len(msgBlock.Transactions), totalFees, blockSigOpCost,
blockWeight, blockchain.CompactToBig(msgBlock.Header.Bits))
log.Debugf("Created new block template (%d transactions, %d in fees, "+
"%d signature operations, %d bytes, target difficulty %064x)",
len(msgBlock.Transactions), totalFees, blockSigOps, blockSize,
blockchain.CompactToBig(msgBlock.Header.Bits))
return &BlockTemplate{
Block: &msgBlock,
Fees: txFees,
SigOpCosts: txSigOpCosts,
Height: nextBlockHeight,
ValidPayAddress: payToAddress != nil,
WitnessCommitment: witnessCommitment,
Block: &msgBlock,
Fees: txFees,
SigOpCounts: txSigOpCounts,
Height: nextBlockHeight,
ValidPayAddress: payToAddress != nil,
}, nil
}
@ -943,7 +846,7 @@ func (g *BlkTmplGenerator) UpdateExtraNonce(msgBlock *wire.MsgBlock, blockHeight
// Recalculate the merkle root with the updated extra nonce.
block := btcutil.NewBlock(msgBlock)
merkles := blockchain.BuildMerkleTreeStore(block.Transactions(), false)
merkles := blockchain.BuildMerkleTreeStore(block.Transactions())
msgBlock.Header.MerkleRoot = *merkles[len(merkles)-1]
return nil
}

View File

@ -21,15 +21,7 @@ const (
// the generation of block templates. See the documentation for
// NewBlockTemplate for more details on each of these parameters are used.
type Policy struct {
// BlockMinWeight is the minimum block weight to be used when
// generating a block template.
BlockMinWeight uint32
// BlockMaxWeight is the maximum block weight to be used when
// generating a block template.
BlockMaxWeight uint32
// BlockMinWeight is the minimum block size to be used when generating
// BlockMinSize is the minimum block size to be used when generating
// a block template.
BlockMinSize uint32

View File

@ -226,15 +226,6 @@ func (sm *SyncManager) startSync() {
return
}
// Once the segwit soft-fork package has activated, we only
// want to sync from peers which are witness enabled to ensure
// that we fully validate all blockchain data.
segwitActive, err := sm.chain.IsDeploymentActive(chaincfg.DeploymentSegwit)
if err != nil {
log.Errorf("Unable to query for segwit soft-fork state: %v", err)
return
}
best := sm.chain.BestSnapshot()
var bestPeer *peerpkg.Peer
for peer, state := range sm.peerStates {
@ -242,11 +233,6 @@ func (sm *SyncManager) startSync() {
continue
}
if segwitActive && !peer.IsWitnessEnabled() {
log.Debugf("peer %v not witness enabled, skipping", peer)
continue
}
// Remove sync candidate peers that are no longer candidates due
// to passing their latest known block. NOTE: The < is
// intentional as opposed to <=. While technically the peer
@ -334,16 +320,9 @@ func (sm *SyncManager) isSyncCandidate(peer *peerpkg.Peer) bool {
}
} else {
// The peer is not a candidate for sync if it's not a full
// node. Additionally, if the segwit soft-fork package has
// activated, then the peer must also be upgraded.
segwitActive, err := sm.chain.IsDeploymentActive(chaincfg.DeploymentSegwit)
if err != nil {
log.Errorf("Unable to query for segwit "+
"soft-fork state: %v", err)
}
// node.
nodeServices := peer.Services()
if nodeServices&wire.SFNodeNetwork != wire.SFNodeNetwork ||
(segwitActive && !peer.IsWitnessEnabled()) {
if nodeServices&wire.SFNodeNetwork != wire.SFNodeNetwork {
return false
}
}
@ -746,13 +725,6 @@ func (sm *SyncManager) fetchHeaderBlocks() {
sm.requestedBlocks[*node.hash] = struct{}{}
syncPeerState.requestedBlocks[*node.hash] = struct{}{}
// If we're fetching from a witness enabled peer
// post-fork, then ensure that we receive all the
// witness data in the blocks.
if sm.syncPeer.IsWitnessEnabled() {
iv.Type = wire.InvTypeWitnessBlock
}
gdmsg.AddInvVect(iv)
numRequested++
}
@ -881,15 +853,11 @@ func (sm *SyncManager) handleHeadersMsg(hmsg *headersMsg) {
// are in the memory pool (either the main pool or orphan pool).
func (sm *SyncManager) haveInventory(invVect *wire.InvVect) (bool, error) {
switch invVect.Type {
case wire.InvTypeWitnessBlock:
fallthrough
case wire.InvTypeBlock:
// Ask chain if the block is known to it in any form (main
// chain, side chain, or orphan).
return sm.chain.HaveBlock(&invVect.Hash)
case wire.InvTypeWitnessTx:
fallthrough
case wire.InvTypeTx:
// Ask the transaction memory pool if the transaction is known
// to it in any form (main pool or orphan).
@ -979,8 +947,6 @@ func (sm *SyncManager) handleInvMsg(imsg *invMsg) {
switch iv.Type {
case wire.InvTypeBlock:
case wire.InvTypeTx:
case wire.InvTypeWitnessBlock:
case wire.InvTypeWitnessTx:
default:
continue
}
@ -1011,14 +977,6 @@ func (sm *SyncManager) handleInvMsg(imsg *invMsg) {
}
}
// Ignore invs block invs from non-witness enabled
// peers, as after segwit activation we only want to
// download from peers that can provide us full witness
// data for blocks.
if !peer.IsWitnessEnabled() && iv.Type == wire.InvTypeBlock {
continue
}
// Add it to the request queue.
state.requestQueue = append(state.requestQueue, iv)
continue
@ -1076,8 +1034,6 @@ func (sm *SyncManager) handleInvMsg(imsg *invMsg) {
requestQueue = requestQueue[1:]
switch iv.Type {
case wire.InvTypeWitnessBlock:
fallthrough
case wire.InvTypeBlock:
// Request the block if there is not already a pending
// request.
@ -1086,16 +1042,10 @@ func (sm *SyncManager) handleInvMsg(imsg *invMsg) {
sm.limitMap(sm.requestedBlocks, maxRequestedBlocks)
state.requestedBlocks[iv.Hash] = struct{}{}
if peer.IsWitnessEnabled() {
iv.Type = wire.InvTypeWitnessBlock
}
gdmsg.AddInvVect(iv)
numRequested++
}
case wire.InvTypeWitnessTx:
fallthrough
case wire.InvTypeTx:
// Request the transaction if there is not already a
// pending request.
@ -1104,12 +1054,6 @@ func (sm *SyncManager) handleInvMsg(imsg *invMsg) {
sm.limitMap(sm.requestedTxns, maxRequestedTxns)
state.requestedTxns[iv.Hash] = struct{}{}
// If the peer is capable, request the txn
// including all witness data.
if peer.IsWitnessEnabled() {
iv.Type = wire.InvTypeWitnessTx
}
gdmsg.AddInvVect(iv)
numRequested++
}

View File

@ -9,10 +9,10 @@ import (
"strings"
"time"
"github.com/btcsuite/btclog"
"github.com/daglabs/btcd/chaincfg/chainhash"
"github.com/daglabs/btcd/txscript"
"github.com/daglabs/btcd/wire"
"github.com/btcsuite/btclog"
)
const (
@ -91,12 +91,8 @@ func invSummary(invList []*wire.InvVect) string {
switch iv.Type {
case wire.InvTypeError:
return fmt.Sprintf("error %s", iv.Hash)
case wire.InvTypeWitnessBlock:
return fmt.Sprintf("witness block %s", iv.Hash)
case wire.InvTypeBlock:
return fmt.Sprintf("block %s", iv.Hash)
case wire.InvTypeWitnessTx:
return fmt.Sprintf("witness tx %s", iv.Hash)
case wire.InvTypeTx:
return fmt.Sprintf("tx %s", iv.Hash)
}

View File

@ -17,11 +17,11 @@ import (
"sync/atomic"
"time"
"github.com/btcsuite/go-socks/socks"
"github.com/daglabs/btcd/blockchain"
"github.com/daglabs/btcd/chaincfg"
"github.com/daglabs/btcd/chaincfg/chainhash"
"github.com/daglabs/btcd/wire"
"github.com/btcsuite/go-socks/socks"
"github.com/davecgh/go-spew/spew"
)
@ -324,7 +324,6 @@ func newNetAddress(addr net.Addr, services wire.ServiceFlag) (*wire.NetAddress,
type outMsg struct {
msg wire.Message
doneChan chan<- struct{}
encoding wire.MessageEncoding
}
// stallControlCmd represents the command of a stall control message.
@ -439,9 +438,6 @@ type Peer struct {
protocolVersion uint32 // negotiated protocol version
sendHeadersPreferred bool // peer sent a sendheaders message
verAckReceived bool
witnessEnabled bool
wireEncoding wire.MessageEncoding
knownInventory *mruInventoryMap
prevGetBlocksMtx sync.Mutex
@ -789,18 +785,6 @@ func (p *Peer) WantsHeaders() bool {
return sendHeadersPreferred
}
// IsWitnessEnabled returns true if the peer has signalled that it supports
// segregated witness.
//
// This function is safe for concurrent access.
func (p *Peer) IsWitnessEnabled() bool {
p.flagsMtx.Lock()
witnessEnabled := p.witnessEnabled
p.flagsMtx.Unlock()
return witnessEnabled
}
// localVersionMsg creates a version message that can be used to send to the
// remote peer.
func (p *Peer) localVersionMsg() (*wire.MsgVersion, error) {
@ -1088,22 +1072,8 @@ func (p *Peer) handleRemoteVersionMsg(msg *wire.MsgVersion) error {
// Set the remote peer's user agent.
p.userAgent = msg.UserAgent
// Determine if the peer would like to receive witness data with
// transactions, or not.
if p.services&wire.SFNodeWitness == wire.SFNodeWitness {
p.witnessEnabled = true
}
p.flagsMtx.Unlock()
// Once the version message has been exchanged, we're able to determine
// if this peer knows how to encode witness data over the wire
// protocol. If so, then we'll switch to a decoding mode which is
// prepared for the new transaction format introduced as part of
// BIP0144.
if p.services&wire.SFNodeWitness == wire.SFNodeWitness {
p.wireEncoding = wire.WitnessEncoding
}
return nil
}
@ -1143,9 +1113,9 @@ func (p *Peer) handlePongMsg(msg *wire.MsgPong) {
}
// readMessage reads the next bitcoin message from the peer with logging.
func (p *Peer) readMessage(encoding wire.MessageEncoding) (wire.Message, []byte, error) {
n, msg, buf, err := wire.ReadMessageWithEncodingN(p.conn,
p.ProtocolVersion(), p.cfg.ChainParams.Net, encoding)
func (p *Peer) readMessage() (wire.Message, []byte, error) {
n, msg, buf, err := wire.ReadMessageN(p.conn,
p.ProtocolVersion(), p.cfg.ChainParams.Net)
atomic.AddUint64(&p.bytesReceived, uint64(n))
if p.cfg.Listeners.OnRead != nil {
p.cfg.Listeners.OnRead(p, n, msg, err)
@ -1176,7 +1146,7 @@ func (p *Peer) readMessage(encoding wire.MessageEncoding) (wire.Message, []byte,
}
// writeMessage sends a bitcoin message to the peer with logging.
func (p *Peer) writeMessage(msg wire.Message, enc wire.MessageEncoding) error {
func (p *Peer) writeMessage(msg wire.Message) error {
// Don't do anything if we're disconnecting.
if atomic.LoadInt32(&p.disconnect) != 0 {
return nil
@ -1198,8 +1168,8 @@ func (p *Peer) writeMessage(msg wire.Message, enc wire.MessageEncoding) error {
}))
log.Tracef("%v", newLogClosure(func() string {
var buf bytes.Buffer
_, err := wire.WriteMessageWithEncodingN(&buf, msg, p.ProtocolVersion(),
p.cfg.ChainParams.Net, enc)
_, err := wire.WriteMessageN(&buf, msg, p.ProtocolVersion(),
p.cfg.ChainParams.Net)
if err != nil {
return err.Error()
}
@ -1207,8 +1177,8 @@ func (p *Peer) writeMessage(msg wire.Message, enc wire.MessageEncoding) error {
}))
// Write the message to the peer.
n, err := wire.WriteMessageWithEncodingN(p.conn, msg,
p.ProtocolVersion(), p.cfg.ChainParams.Net, enc)
n, err := wire.WriteMessageN(p.conn, msg,
p.ProtocolVersion(), p.cfg.ChainParams.Net)
atomic.AddUint64(&p.bytesSent, uint64(n))
if p.cfg.Listeners.OnWrite != nil {
p.cfg.Listeners.OnWrite(p, n, msg, err)
@ -1469,7 +1439,7 @@ out:
// Read a message and stop the idle timer as soon as the read
// is done. The timer is reset below for the next iteration if
// needed.
rmsg, buf, err := p.readMessage(p.wireEncoding)
rmsg, buf, err := p.readMessage()
idleTimer.Stop()
if err != nil {
// In order to allow regression tests with malformed messages, don't
@ -1743,9 +1713,7 @@ out:
// If this is a new block, then we'll blast it
// out immediately, sipping the inv trickle
// queue.
if iv.Type == wire.InvTypeBlock ||
iv.Type == wire.InvTypeWitnessBlock {
if iv.Type == wire.InvTypeBlock {
invMsg := wire.NewMsgInvSizeHint(1)
invMsg.AddInvVect(iv)
waiting = queuePacket(outMsg{msg: invMsg},
@ -1867,7 +1835,7 @@ out:
p.stallControl <- stallControlMsg{sccSendMessage, msg.msg}
err := p.writeMessage(msg.msg, msg.encoding)
err := p.writeMessage(msg.msg)
if err != nil {
p.Disconnect()
if p.shouldLogWriteError(err) {
@ -1944,18 +1912,6 @@ out:
//
// This function is safe for concurrent access.
func (p *Peer) QueueMessage(msg wire.Message, doneChan chan<- struct{}) {
p.QueueMessageWithEncoding(msg, doneChan, wire.BaseEncoding)
}
// QueueMessageWithEncoding adds the passed bitcoin message to the peer send
// queue. This function is identical to QueueMessage, however it allows the
// caller to specify the wire encoding type that should be used when
// encoding/decoding blocks and transactions.
//
// This function is safe for concurrent access.
func (p *Peer) QueueMessageWithEncoding(msg wire.Message, doneChan chan<- struct{},
encoding wire.MessageEncoding) {
// Avoid risk of deadlock if goroutine already exited. The goroutine
// we will be sending to hangs around until it knows for a fact that
// it is marked as disconnected and *then* it drains the channels.
@ -1967,7 +1923,7 @@ func (p *Peer) QueueMessageWithEncoding(msg wire.Message, doneChan chan<- struct
}
return
}
p.outputQueue <- outMsg{msg: msg, encoding: encoding, doneChan: doneChan}
p.outputQueue <- outMsg{msg: msg, doneChan: doneChan}
}
// QueueInventory adds the passed inventory to the inventory send queue which
@ -2099,7 +2055,7 @@ func (p *Peer) WaitForDisconnect() {
// acceptable then return an error.
func (p *Peer) readRemoteVersionMsg() error {
// Read their version message.
msg, _, err := p.readMessage(wire.LatestEncoding)
msg, _, err := p.readMessage()
if err != nil {
return err
}
@ -2111,7 +2067,7 @@ func (p *Peer) readRemoteVersionMsg() error {
rejectMsg := wire.NewMsgReject(msg.Command(), wire.RejectMalformed,
errStr)
return p.writeMessage(rejectMsg, wire.LatestEncoding)
return p.writeMessage(rejectMsg)
}
if err := p.handleRemoteVersionMsg(remoteVerMsg); err != nil {
@ -2131,7 +2087,7 @@ func (p *Peer) writeLocalVersionMsg() error {
return err
}
return p.writeMessage(localVerMsg, wire.LatestEncoding)
return p.writeMessage(localVerMsg)
}
// negotiateInboundProtocol waits to receive a version message from the peer
@ -2174,7 +2130,6 @@ func newPeerBase(origCfg *Config, inbound bool) *Peer {
p := Peer{
inbound: inbound,
wireEncoding: wire.BaseEncoding,
knownInventory: newMruInventoryMap(maxKnownInventory),
stallControl: make(chan stallControlMsg, 1), // nonblocking sync
outputQueue: make(chan outMsg, outputBufferSize),

View File

@ -12,11 +12,11 @@ import (
"testing"
"time"
"github.com/btcsuite/go-socks/socks"
"github.com/daglabs/btcd/chaincfg"
"github.com/daglabs/btcd/chaincfg/chainhash"
"github.com/daglabs/btcd/peer"
"github.com/daglabs/btcd/wire"
"github.com/btcsuite/go-socks/socks"
)
// conn mocks a network connection by implementing the net.Conn interface. It
@ -108,7 +108,6 @@ type peerStats struct {
wantTimeOffset int64
wantBytesSent uint64
wantBytesReceived uint64
wantWitnessEnabled bool
}
// testPeer tests the given peer's flags and stats
@ -186,12 +185,6 @@ func testPeer(t *testing.T, p *peer.Peer, s peerStats) {
return
}
if p.IsWitnessEnabled() != s.wantWitnessEnabled {
t.Errorf("testPeer: wrong WitnessEnabled - got %v, want %v",
p.IsWitnessEnabled(), s.wantWitnessEnabled)
return
}
stats := p.StatsSnapshot()
if p.ID() != stats.ID {
@ -243,7 +236,7 @@ func TestPeerConnection(t *testing.T) {
UserAgentVersion: "1.0",
UserAgentComments: []string{"comment"},
ChainParams: &chaincfg.MainNetParams,
Services: wire.SFNodeNetwork | wire.SFNodeWitness,
Services: wire.SFNodeNetwork,
}
wantStats1 := peerStats{
@ -259,11 +252,10 @@ func TestPeerConnection(t *testing.T) {
wantTimeOffset: int64(0),
wantBytesSent: 167, // 143 version + 24 verack
wantBytesReceived: 167,
wantWitnessEnabled: false,
}
wantStats2 := peerStats{
wantUserAgent: wire.DefaultUserAgent + "peer:1.0(comment)/",
wantServices: wire.SFNodeNetwork | wire.SFNodeWitness,
wantServices: wire.SFNodeNetwork,
wantProtocolVersion: wire.RejectVersion,
wantConnected: true,
wantVersionKnown: true,
@ -274,7 +266,6 @@ func TestPeerConnection(t *testing.T) {
wantTimeOffset: int64(0),
wantBytesSent: 167, // 143 version + 24 verack
wantBytesReceived: 167,
wantWitnessEnabled: true,
}
tests := []struct {

View File

@ -943,44 +943,6 @@ func (c *Client) GetRawChangeAddress(account string) (btcutil.Address, error) {
return c.GetRawChangeAddressAsync(account).Receive()
}
// FutureAddWitnessAddressResult is a future promise to deliver the result of
// a AddWitnessAddressAsync RPC invocation (or an applicable error).
type FutureAddWitnessAddressResult chan *response
// Receive waits for the response promised by the future and returns the new
// address.
func (r FutureAddWitnessAddressResult) Receive() (btcutil.Address, error) {
res, err := receiveFuture(r)
if err != nil {
return nil, err
}
// Unmarshal result as a string.
var addr string
err = json.Unmarshal(res, &addr)
if err != nil {
return nil, err
}
return btcutil.DecodeAddress(addr, &chaincfg.MainNetParams)
}
// AddWitnessAddressAsync returns an instance of a type that can be used to get
// the result of the RPC at some future time by invoking the Receive function on
// the returned instance.
//
// See AddWitnessAddress for the blocking version and more details.
func (c *Client) AddWitnessAddressAsync(address string) FutureAddWitnessAddressResult {
cmd := btcjson.NewAddWitnessAddressCmd(address)
return c.sendCmd(cmd)
}
// AddWitnessAddress adds a witness address for a script and returns the new
// address (P2SH of the witness script).
func (c *Client) AddWitnessAddress(address string) (btcutil.Address, error) {
return c.AddWitnessAddressAsync(address).Receive()
}
// FutureGetAccountAddressResult is a future promise to deliver the result of a
// GetAccountAddressAsync RPC invocation (or an applicable error).
type FutureGetAccountAddressResult chan *response

View File

@ -27,6 +27,7 @@ import (
"sync/atomic"
"time"
"github.com/btcsuite/websocket"
"github.com/daglabs/btcd/blockchain"
"github.com/daglabs/btcd/blockchain/indexers"
"github.com/daglabs/btcd/btcec"
@ -41,7 +42,6 @@ import (
"github.com/daglabs/btcd/txscript"
"github.com/daglabs/btcd/wire"
"github.com/daglabs/btcutil"
"github.com/btcsuite/websocket"
)
// API version constants
@ -500,7 +500,7 @@ func peerExists(connMgr rpcserverConnManager, addr string, nodeID int32) bool {
// latest protocol version and returns a hex-encoded string of the result.
func messageToHex(msg wire.Message) (string, error) {
var buf bytes.Buffer
if err := msg.BtcEncode(&buf, maxProtocolVersion, wire.WitnessEncoding); err != nil {
if err := msg.BtcEncode(&buf, maxProtocolVersion); err != nil {
context := fmt.Sprintf("Failed to encode msg of type %T", msg)
return "", internalRPCError(err.Error(), context)
}
@ -531,7 +531,7 @@ func handleCreateRawTransaction(s *rpcServer, cmd interface{}, closeChan <-chan
}
prevOut := wire.NewOutPoint(txHash, input.Vout)
txIn := wire.NewTxIn(prevOut, []byte{}, nil)
txIn := wire.NewTxIn(prevOut, []byte{})
if c.LockTime != nil && *c.LockTime != 0 {
txIn.Sequence = wire.MaxTxInSequenceNum - 1
}
@ -634,23 +634,6 @@ func handleDebugLevel(s *rpcServer, cmd interface{}, closeChan <-chan struct{})
return "Done.", nil
}
// witnessToHex formats the passed witness stack as a slice of hex-encoded
// strings to be used in a JSON response.
func witnessToHex(witness wire.TxWitness) []string {
// Ensure nil is returned when there are no entries versus an empty
// slice so it can properly be omitted as necessary.
if len(witness) == 0 {
return nil
}
result := make([]string, 0, len(witness))
for _, wit := range witness {
result = append(result, hex.EncodeToString(wit))
}
return result
}
// createVinList returns a slice of JSON objects for the inputs of the passed
// transaction.
func createVinList(mtx *wire.MsgTx) []btcjson.Vin {
@ -660,7 +643,6 @@ func createVinList(mtx *wire.MsgTx) []btcjson.Vin {
txIn := mtx.TxIn[0]
vinList[0].Coinbase = hex.EncodeToString(txIn.SignatureScript)
vinList[0].Sequence = txIn.Sequence
vinList[0].Witness = witnessToHex(txIn.Witness)
return vinList
}
@ -678,10 +660,6 @@ func createVinList(mtx *wire.MsgTx) []btcjson.Vin {
Asm: disbuf,
Hex: hex.EncodeToString(txIn.SignatureScript),
}
if mtx.HasWitness() {
vinEntry.Witness = witnessToHex(txIn.Witness)
}
}
return vinList
@ -753,9 +731,8 @@ func createTxRawResult(chainParams *chaincfg.Params, mtx *wire.MsgTx,
txReply := &btcjson.TxRawResult{
Hex: mtxHex,
Txid: txHash,
Hash: mtx.WitnessHash().String(),
Hash: mtx.TxHash().String(),
Size: int32(mtx.SerializeSize()),
Vsize: int32(mempool.GetTxVirtualSize(btcutil.NewTx(mtx))),
Vin: createVinList(mtx),
Vout: createVoutList(mtx, chainParams, nil),
Version: mtx.Version,
@ -1129,8 +1106,6 @@ func handleGetBlock(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (i
Confirmations: uint64(1 + best.Height - blockHeight),
Height: int64(blockHeight),
Size: int32(len(blkBytes)),
StrippedSize: int32(blk.MsgBlock().SerializeSizeStripped()),
Weight: int32(blockchain.GetBlockWeight(blk)),
Bits: strconv.FormatInt(int64(blockHeader.Bits), 16),
Difficulty: getDifficultyRatio(blockHeader.Bits, params),
NextHash: nextHashString,
@ -1247,9 +1222,6 @@ func handleGetBlockChainInfo(s *rpcServer, cmd interface{}, closeChan <-chan str
case chaincfg.DeploymentCSV:
forkName = "csv"
case chaincfg.DeploymentSegwit:
forkName = "segwit"
default:
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInternal.Code,
@ -1631,7 +1603,7 @@ func (state *gbtWorkState) updateBlockTemplate(s *rpcServer, useCoinbaseValue bo
// Update the merkle root.
block := btcutil.NewBlock(template.Block)
merkles := blockchain.BuildMerkleTreeStore(block.Transactions(), false)
merkles := blockchain.BuildMerkleTreeStore(block.Transactions())
template.Block.Header.MerkleRoot = *merkles[len(merkles)-1]
}
@ -1718,14 +1690,12 @@ func (state *gbtWorkState) blockTemplateResult(useCoinbaseValue bool, submitOld
return nil, internalRPCError(err.Error(), context)
}
bTx := btcutil.NewTx(tx)
resultTx := btcjson.GetBlockTemplateResultTx{
Data: hex.EncodeToString(txBuf.Bytes()),
Hash: txHash.String(),
Depends: depends,
Fee: template.Fees[i],
SigOps: template.SigOpCosts[i],
Weight: blockchain.GetTransactionWeight(bTx),
SigOps: template.SigOpCounts[i],
}
transactions = append(transactions, resultTx)
}
@ -1741,8 +1711,7 @@ func (state *gbtWorkState) blockTemplateResult(useCoinbaseValue bool, submitOld
CurTime: header.Timestamp.Unix(),
Height: int64(template.Height),
PreviousHash: header.PrevBlock.String(),
WeightLimit: blockchain.MaxBlockWeight,
SigOpLimit: blockchain.MaxBlockSigOpsCost,
SigOpLimit: blockchain.MaxSigOpsPerBlock,
SizeLimit: wire.MaxBlockPayload,
Transactions: transactions,
Version: header.Version,
@ -1755,11 +1724,6 @@ func (state *gbtWorkState) blockTemplateResult(useCoinbaseValue bool, submitOld
NonceRange: gbtNonceRange,
Capabilities: gbtCapabilities,
}
// If the generated block template includes transactions with witness
// data, then include the witness commitment in the GBT result.
if template.WitnessCommitment != nil {
reply.DefaultWitnessCommitment = hex.EncodeToString(template.WitnessCommitment)
}
if useCoinbaseValue {
reply.CoinbaseAux = gbtCoinbaseAux
@ -1790,7 +1754,7 @@ func (state *gbtWorkState) blockTemplateResult(useCoinbaseValue bool, submitOld
Hash: tx.TxHash().String(),
Depends: []int64{},
Fee: template.Fees[0],
SigOps: template.SigOpCosts[0],
SigOps: template.SigOpCounts[0],
}
reply.CoinbaseTxn = &resultTx
@ -1997,8 +1961,6 @@ func chainErrToGBTErrString(err error) string {
return "duplicate"
case blockchain.ErrBlockTooBig:
return "bad-blk-length"
case blockchain.ErrBlockWeightTooHigh:
return "bad-blk-weight"
case blockchain.ErrBlockVersionTooOld:
return "bad-version"
case blockchain.ErrInvalidTime:
@ -2067,12 +2029,6 @@ func chainErrToGBTErrString(err error) string {
return "bad-script-malformed"
case blockchain.ErrScriptValidation:
return "bad-script-validate"
case blockchain.ErrUnexpectedWitness:
return "unexpected-witness"
case blockchain.ErrInvalidWitnessCommitment:
return "bad-witness-nonce-size"
case blockchain.ErrWitnessCommitmentMismatch:
return "bad-witness-merkle-match"
case blockchain.ErrPreviousBlockUnknown:
return "prev-blk-not-found"
case blockchain.ErrInvalidAncestorBlock:
@ -2355,17 +2311,16 @@ func handleGetMiningInfo(s *rpcServer, cmd interface{}, closeChan <-chan struct{
best := s.cfg.Chain.BestSnapshot()
result := btcjson.GetMiningInfoResult{
Blocks: int64(best.Height),
CurrentBlockSize: best.BlockSize,
CurrentBlockWeight: best.BlockWeight,
CurrentBlockTx: best.NumTxns,
Difficulty: getDifficultyRatio(best.Bits, s.cfg.ChainParams),
Generate: s.cfg.CPUMiner.IsMining(),
GenProcLimit: s.cfg.CPUMiner.NumWorkers(),
HashesPerSec: int64(s.cfg.CPUMiner.HashesPerSecond()),
NetworkHashPS: networkHashesPerSec,
PooledTx: uint64(s.cfg.TxMemPool.Count()),
TestNet: cfg.TestNet3,
Blocks: int64(best.Height),
CurrentBlockSize: best.BlockSize,
CurrentBlockTx: best.NumTxns,
Difficulty: getDifficultyRatio(best.Bits, s.cfg.ChainParams),
Generate: s.cfg.CPUMiner.IsMining(),
GenProcLimit: s.cfg.CPUMiner.NumWorkers(),
HashesPerSec: int64(s.cfg.CPUMiner.HashesPerSecond()),
NetworkHashPS: networkHashesPerSec,
PooledTx: uint64(s.cfg.TxMemPool.Count()),
TestNet: cfg.TestNet3,
}
return &result, nil
}
@ -2943,10 +2898,6 @@ func createVinListPrevOut(s *rpcServer, mtx *wire.MsgTx, chainParams *chaincfg.P
},
}
if len(txIn.Witness) != 0 {
vinEntry.Witness = witnessToHex(txIn.Witness)
}
// Add the entry to the list now if it already passed the filter
// since the previous output might not be available.
passesFilter := len(filterAddrMap) == 0

View File

@ -65,21 +65,19 @@ var helpDescsEnUS = map[string]string{
"prevout-value": "previous output value",
// VinPrevOut help.
"vinprevout-coinbase": "The hex-encoded bytes of the signature script (coinbase txns only)",
"vinprevout-txid": "The hash of the origin transaction (non-coinbase txns only)",
"vinprevout-vout": "The index of the output being redeemed from the origin transaction (non-coinbase txns only)",
"vinprevout-scriptSig": "The signature script used to redeem the origin transaction as a JSON object (non-coinbase txns only)",
"vinprevout-txinwitness": "The witness stack of the passed input, encoded as a JSON string array",
"vinprevout-prevOut": "Data from the origin transaction output with index vout.",
"vinprevout-sequence": "The script sequence number",
"vinprevout-coinbase": "The hex-encoded bytes of the signature script (coinbase txns only)",
"vinprevout-txid": "The hash of the origin transaction (non-coinbase txns only)",
"vinprevout-vout": "The index of the output being redeemed from the origin transaction (non-coinbase txns only)",
"vinprevout-scriptSig": "The signature script used to redeem the origin transaction as a JSON object (non-coinbase txns only)",
"vinprevout-prevOut": "Data from the origin transaction output with index vout.",
"vinprevout-sequence": "The script sequence number",
// Vin help.
"vin-coinbase": "The hex-encoded bytes of the signature script (coinbase txns only)",
"vin-txid": "The hash of the origin transaction (non-coinbase txns only)",
"vin-vout": "The index of the output being redeemed from the origin transaction (non-coinbase txns only)",
"vin-scriptSig": "The signature script used to redeem the origin transaction as a JSON object (non-coinbase txns only)",
"vin-txinwitness": "The witness used to redeem the input encoded as a string array of its items",
"vin-sequence": "The script sequence number",
"vin-coinbase": "The hex-encoded bytes of the signature script (coinbase txns only)",
"vin-txid": "The hash of the origin transaction (non-coinbase txns only)",
"vin-vout": "The index of the output being redeemed from the origin transaction (non-coinbase txns only)",
"vin-scriptSig": "The signature script used to redeem the origin transaction as a JSON object (non-coinbase txns only)",
"vin-sequence": "The script sequence number",
// ScriptPubKeyResult help.
"scriptpubkeyresult-asm": "Disassembly of the script",
@ -206,7 +204,6 @@ var helpDescsEnUS = map[string]string{
"txrawresult-time": "Transaction time in seconds since 1 Jan 1970 GMT",
"txrawresult-blocktime": "Block time in seconds since the 1 Jan 1970 GMT",
"txrawresult-size": "The size of the transaction in bytes",
"txrawresult-vsize": "The virtual size of the transaction in bytes",
"txrawresult-hash": "The wtxid of the transaction",
// SearchRawTransactionsResult help.
@ -222,7 +219,6 @@ var helpDescsEnUS = map[string]string{
"searchrawtransactionsresult-time": "Transaction time in seconds since 1 Jan 1970 GMT",
"searchrawtransactionsresult-blocktime": "Block time in seconds since the 1 Jan 1970 GMT",
"searchrawtransactionsresult-size": "The size of the transaction in bytes",
"searchrawtransactionsresult-vsize": "The virtual size of the transaction in bytes",
// GetBlockVerboseResult help.
"getblockverboseresult-hash": "The hash of the block (same as provided)",
@ -240,8 +236,6 @@ var helpDescsEnUS = map[string]string{
"getblockverboseresult-difficulty": "The proof-of-work difficulty as a multiple of the minimum difficulty",
"getblockverboseresult-previousblockhash": "The hash of the previous block",
"getblockverboseresult-nextblockhash": "The hash of the next block (only if there is one)",
"getblockverboseresult-strippedsize": "The size of the block without witness data",
"getblockverboseresult-weight": "The weight of the block",
// GetBlockCountCmd help.
"getblockcount--synopsis": "Returns the number of blocks in the longest block chain.",
@ -291,37 +285,34 @@ var helpDescsEnUS = map[string]string{
"getblocktemplateresulttx-depends": "Other transactions before this one (by 1-based index in the 'transactions' list) that must be present in the final block if this one is",
"getblocktemplateresulttx-fee": "Difference in value between transaction inputs and outputs (in Satoshi)",
"getblocktemplateresulttx-sigops": "Total number of signature operations as counted for purposes of block limits",
"getblocktemplateresulttx-weight": "The weight of the transaction",
// GetBlockTemplateResultAux help.
"getblocktemplateresultaux-flags": "Hex-encoded byte-for-byte data to include in the coinbase signature script",
// GetBlockTemplateResult help.
"getblocktemplateresult-bits": "Hex-encoded compressed difficulty",
"getblocktemplateresult-curtime": "Current time as seen by the server (recommended for block time); must fall within mintime/maxtime rules",
"getblocktemplateresult-height": "Height of the block to be solved",
"getblocktemplateresult-previousblockhash": "Hex-encoded big-endian hash of the previous block",
"getblocktemplateresult-sigoplimit": "Number of sigops allowed in blocks ",
"getblocktemplateresult-sizelimit": "Number of bytes allowed in blocks",
"getblocktemplateresult-transactions": "Array of transactions as JSON objects",
"getblocktemplateresult-version": "The block version",
"getblocktemplateresult-coinbaseaux": "Data that should be included in the coinbase signature script",
"getblocktemplateresult-coinbasetxn": "Information about the coinbase transaction",
"getblocktemplateresult-coinbasevalue": "Total amount available for the coinbase in Satoshi",
"getblocktemplateresult-workid": "This value must be returned with result if provided (not provided)",
"getblocktemplateresult-longpollid": "Identifier for long poll request which allows monitoring for expiration",
"getblocktemplateresult-longpolluri": "An alternate URI to use for long poll requests if provided (not provided)",
"getblocktemplateresult-submitold": "Not applicable",
"getblocktemplateresult-target": "Hex-encoded big-endian number which valid results must be less than",
"getblocktemplateresult-expires": "Maximum number of seconds (starting from when the server sent the response) this work is valid for",
"getblocktemplateresult-maxtime": "Maximum allowed time",
"getblocktemplateresult-mintime": "Minimum allowed time",
"getblocktemplateresult-mutable": "List of mutations the server explicitly allows",
"getblocktemplateresult-noncerange": "Two concatenated hex-encoded big-endian 32-bit integers which represent the valid ranges of nonces the miner may scan",
"getblocktemplateresult-capabilities": "List of server capabilities including 'proposal' to indicate support for block proposals",
"getblocktemplateresult-reject-reason": "Reason the proposal was invalid as-is (only applies to proposal responses)",
"getblocktemplateresult-default_witness_commitment": "The witness commitment itself. Will be populated if the block has witness data",
"getblocktemplateresult-weightlimit": "The current limit on the max allowed weight of a block",
"getblocktemplateresult-bits": "Hex-encoded compressed difficulty",
"getblocktemplateresult-curtime": "Current time as seen by the server (recommended for block time); must fall within mintime/maxtime rules",
"getblocktemplateresult-height": "Height of the block to be solved",
"getblocktemplateresult-previousblockhash": "Hex-encoded big-endian hash of the previous block",
"getblocktemplateresult-sigoplimit": "Number of sigops allowed in blocks ",
"getblocktemplateresult-sizelimit": "Number of bytes allowed in blocks",
"getblocktemplateresult-transactions": "Array of transactions as JSON objects",
"getblocktemplateresult-version": "The block version",
"getblocktemplateresult-coinbaseaux": "Data that should be included in the coinbase signature script",
"getblocktemplateresult-coinbasetxn": "Information about the coinbase transaction",
"getblocktemplateresult-coinbasevalue": "Total amount available for the coinbase in Satoshi",
"getblocktemplateresult-workid": "This value must be returned with result if provided (not provided)",
"getblocktemplateresult-longpollid": "Identifier for long poll request which allows monitoring for expiration",
"getblocktemplateresult-longpolluri": "An alternate URI to use for long poll requests if provided (not provided)",
"getblocktemplateresult-submitold": "Not applicable",
"getblocktemplateresult-target": "Hex-encoded big-endian number which valid results must be less than",
"getblocktemplateresult-expires": "Maximum number of seconds (starting from when the server sent the response) this work is valid for",
"getblocktemplateresult-maxtime": "Maximum allowed time",
"getblocktemplateresult-mintime": "Minimum allowed time",
"getblocktemplateresult-mutable": "List of mutations the server explicitly allows",
"getblocktemplateresult-noncerange": "Two concatenated hex-encoded big-endian 32-bit integers which represent the valid ranges of nonces the miner may scan",
"getblocktemplateresult-capabilities": "List of server capabilities including 'proposal' to indicate support for block proposals",
"getblocktemplateresult-reject-reason": "Reason the proposal was invalid as-is (only applies to proposal responses)",
// GetBlockTemplateCmd help.
"getblocktemplate--synopsis": "Returns a JSON object with information necessary to construct a block to mine or accepts a proposal to validate.\n" +
@ -411,18 +402,17 @@ var helpDescsEnUS = map[string]string{
"getmempoolinforesult-size": "Number of transactions in the mempool",
// GetMiningInfoResult help.
"getmininginforesult-blocks": "Height of the latest best block",
"getmininginforesult-currentblocksize": "Size of the latest best block",
"getmininginforesult-currentblockweight": "Weight of the latest best block",
"getmininginforesult-currentblocktx": "Number of transactions in the latest best block",
"getmininginforesult-difficulty": "Current target difficulty",
"getmininginforesult-errors": "Any current errors",
"getmininginforesult-generate": "Whether or not server is set to generate coins",
"getmininginforesult-genproclimit": "Number of processors to use for coin generation (-1 when disabled)",
"getmininginforesult-hashespersec": "Recent hashes per second performance measurement while generating coins",
"getmininginforesult-networkhashps": "Estimated network hashes per second for the most recent blocks",
"getmininginforesult-pooledtx": "Number of transactions in the memory pool",
"getmininginforesult-testnet": "Whether or not server is using testnet",
"getmininginforesult-blocks": "Height of the latest best block",
"getmininginforesult-currentblocksize": "Size of the latest best block",
"getmininginforesult-currentblocktx": "Number of transactions in the latest best block",
"getmininginforesult-difficulty": "Current target difficulty",
"getmininginforesult-errors": "Any current errors",
"getmininginforesult-generate": "Whether or not server is set to generate coins",
"getmininginforesult-genproclimit": "Number of processors to use for coin generation (-1 when disabled)",
"getmininginforesult-hashespersec": "Recent hashes per second performance measurement while generating coins",
"getmininginforesult-networkhashps": "Estimated network hashes per second for the most recent blocks",
"getmininginforesult-pooledtx": "Number of transactions in the memory pool",
"getmininginforesult-testnet": "Whether or not server is using testnet",
// GetMiningInfoCmd help.
"getmininginfo--synopsis": "Returns a JSON object containing mining-related information.",
@ -475,7 +465,6 @@ var helpDescsEnUS = map[string]string{
"getrawmempoolverboseresult-startingpriority": "Priority when transaction entered the pool",
"getrawmempoolverboseresult-currentpriority": "Current priority",
"getrawmempoolverboseresult-depends": "Unconfirmed transactions used as inputs for this transaction",
"getrawmempoolverboseresult-vsize": "The virtual size of a transaction",
// GetRawMempoolCmd help.
"getrawmempool--synopsis": "Returns information about all of the transactions currently in the memory pool.",

View File

@ -4,7 +4,9 @@
package main
import "testing"
import (
"testing"
)
// TestHelp ensures the help is reasonably accurate by checking that every
// command specified also has result types defined and the one-line usage and

View File

@ -43,8 +43,7 @@ import (
const (
// defaultServices describes the default services that are supported by
// the server.
defaultServices = wire.SFNodeNetwork | wire.SFNodeBloom |
wire.SFNodeWitness | wire.SFNodeCF
defaultServices = wire.SFNodeNetwork | wire.SFNodeBloom | wire.SFNodeCF
// defaultRequiredServices describes the default services that are
// required to be supported by outbound peers.
@ -209,7 +208,6 @@ type server struct {
addrManager *addrmgr.AddrManager
connManager *connmgr.ConnManager
sigCache *txscript.SigCache
hashCache *txscript.HashCache
rpcServer *rpcServer
syncManager *netsync.SyncManager
chain *blockchain.BlockChain
@ -410,25 +408,6 @@ func (sp *serverPeer) OnVersion(_ *peer.Peer, msg *wire.MsgVersion) {
// Outbound connections.
if !sp.Inbound() {
// After soft-fork activation, only make outbound
// connection to peers if they flag that they're segwit
// enabled.
chain := sp.server.chain
segwitActive, err := chain.IsDeploymentActive(chaincfg.DeploymentSegwit)
if err != nil {
peerLog.Errorf("Unable to query for segwit "+
"soft-fork state: %v", err)
return
}
if segwitActive && !sp.IsWitnessEnabled() {
peerLog.Infof("Disconnecting non-segwit "+
"peer %v, isn't segwit enabled and "+
"we need more segwit enabled peers", sp)
sp.Disconnect()
return
}
// TODO(davec): Only do this if not doing the initial block
// download and the local address is routable.
if !cfg.DisableListen /* && isCurrent? */ {
@ -637,18 +616,12 @@ func (sp *serverPeer) OnGetData(_ *peer.Peer, msg *wire.MsgGetData) {
}
var err error
switch iv.Type {
case wire.InvTypeWitnessTx:
err = sp.server.pushTxMsg(sp, &iv.Hash, c, waitChan, wire.WitnessEncoding)
case wire.InvTypeTx:
err = sp.server.pushTxMsg(sp, &iv.Hash, c, waitChan, wire.BaseEncoding)
case wire.InvTypeWitnessBlock:
err = sp.server.pushBlockMsg(sp, &iv.Hash, c, waitChan, wire.WitnessEncoding)
err = sp.server.pushTxMsg(sp, &iv.Hash, c, waitChan)
case wire.InvTypeBlock:
err = sp.server.pushBlockMsg(sp, &iv.Hash, c, waitChan, wire.BaseEncoding)
case wire.InvTypeFilteredWitnessBlock:
err = sp.server.pushMerkleBlockMsg(sp, &iv.Hash, c, waitChan, wire.WitnessEncoding)
err = sp.server.pushBlockMsg(sp, &iv.Hash, c, waitChan)
case wire.InvTypeFilteredBlock:
err = sp.server.pushMerkleBlockMsg(sp, &iv.Hash, c, waitChan, wire.BaseEncoding)
err = sp.server.pushMerkleBlockMsg(sp, &iv.Hash, c, waitChan)
default:
peerLog.Warnf("Unknown type in inventory request %d",
iv.Type)
@ -1282,7 +1255,7 @@ func (s *server) TransactionConfirmed(tx *btcutil.Tx) {
// pushTxMsg sends a tx message for the provided transaction hash to the
// connected peer. An error is returned if the transaction hash is not known.
func (s *server) pushTxMsg(sp *serverPeer, hash *chainhash.Hash, doneChan chan<- struct{},
waitChan <-chan struct{}, encoding wire.MessageEncoding) error {
waitChan <-chan struct{}) error {
// Attempt to fetch the requested transaction from the pool. A
// call could be made to check for existence first, but simply trying
@ -1303,7 +1276,7 @@ func (s *server) pushTxMsg(sp *serverPeer, hash *chainhash.Hash, doneChan chan<-
<-waitChan
}
sp.QueueMessageWithEncoding(tx.MsgTx(), doneChan, encoding)
sp.QueueMessage(tx.MsgTx(), doneChan)
return nil
}
@ -1311,7 +1284,7 @@ func (s *server) pushTxMsg(sp *serverPeer, hash *chainhash.Hash, doneChan chan<-
// pushBlockMsg sends a block message for the provided block hash to the
// connected peer. An error is returned if the block hash is not known.
func (s *server) pushBlockMsg(sp *serverPeer, hash *chainhash.Hash, doneChan chan<- struct{},
waitChan <-chan struct{}, encoding wire.MessageEncoding) error {
waitChan <-chan struct{}) error {
// Fetch the raw block bytes from the database.
var blockBytes []byte
@ -1356,7 +1329,7 @@ func (s *server) pushBlockMsg(sp *serverPeer, hash *chainhash.Hash, doneChan cha
if !sendInv {
dc = doneChan
}
sp.QueueMessageWithEncoding(&msgBlock, dc, encoding)
sp.QueueMessage(&msgBlock, dc)
// When the peer requests the final block that was advertised in
// response to a getblocks message which requested more blocks than
@ -1379,7 +1352,7 @@ func (s *server) pushBlockMsg(sp *serverPeer, hash *chainhash.Hash, doneChan cha
// loaded, this call will simply be ignored if there is no filter loaded. An
// error is returned if the block hash is not known.
func (s *server) pushMerkleBlockMsg(sp *serverPeer, hash *chainhash.Hash,
doneChan chan<- struct{}, waitChan <-chan struct{}, encoding wire.MessageEncoding) error {
doneChan chan<- struct{}, waitChan <-chan struct{}) error {
// Do not send a response if the peer doesn't have a filter loaded.
if !sp.filter.IsLoaded() {
@ -1427,8 +1400,7 @@ func (s *server) pushMerkleBlockMsg(sp *serverPeer, hash *chainhash.Hash,
dc = doneChan
}
if txIndex < uint32(len(blkTransactions)) {
sp.QueueMessageWithEncoding(blkTransactions[txIndex], dc,
encoding)
sp.QueueMessage(blkTransactions[txIndex], dc)
}
}
@ -2462,7 +2434,6 @@ func newServer(listenAddrs []string, db database.DB, chainParams *chaincfg.Param
timeSource: blockchain.NewMedianTime(),
services: services,
sigCache: txscript.NewSigCache(cfg.SigCacheMaxSize),
hashCache: txscript.NewHashCache(cfg.SigCacheMaxSize),
cfCheckptCaches: make(map[wire.FilterType][]cfHeaderKV),
}
@ -2520,7 +2491,6 @@ func newServer(listenAddrs []string, db database.DB, chainParams *chaincfg.Param
TimeSource: s.timeSource,
SigCache: s.sigCache,
IndexManager: indexManager,
HashCache: s.hashCache,
})
if err != nil {
return nil, err
@ -2563,7 +2533,7 @@ func newServer(listenAddrs []string, db database.DB, chainParams *chaincfg.Param
FreeTxRelayLimit: cfg.FreeTxRelayLimit,
MaxOrphanTxs: cfg.MaxOrphanTxs,
MaxOrphanTxSize: defaultMaxOrphanTxSize,
MaxSigOpCostPerTx: blockchain.MaxBlockSigOpsCost / 4,
MaxSigOpsPerTx: blockchain.MaxSigOpsPerBlock / 5,
MinRelayTxFee: cfg.minRelayTxFee,
MaxTxVersion: 2,
},
@ -2576,7 +2546,6 @@ func newServer(listenAddrs []string, db database.DB, chainParams *chaincfg.Param
},
IsDeploymentActive: s.chain.IsDeploymentActive,
SigCache: s.sigCache,
HashCache: s.hashCache,
AddrIndex: s.addrIndex,
FeeEstimator: s.feeEstimator,
}
@ -2601,16 +2570,13 @@ func newServer(listenAddrs []string, db database.DB, chainParams *chaincfg.Param
// NOTE: The CPU miner relies on the mempool, so the mempool has to be
// created before calling the function to create the CPU miner.
policy := mining.Policy{
BlockMinWeight: cfg.BlockMinWeight,
BlockMaxWeight: cfg.BlockMaxWeight,
BlockMinSize: cfg.BlockMinSize,
BlockMaxSize: cfg.BlockMaxSize,
BlockPrioritySize: cfg.BlockPrioritySize,
TxMinFreeFee: cfg.minRelayTxFee,
}
blockTemplateGenerator := mining.NewBlkTmplGenerator(&policy,
s.chainParams, s.txMemPool, s.chain, s.timeSource,
s.sigCache, s.hashCache)
s.chainParams, s.txMemPool, s.chain, s.timeSource, s.sigCache)
s.cpuMiner = cpuminer.New(&cpuminer.Config{
ChainParams: chainParams,
BlockTemplateGenerator: blockTemplateGenerator,

View File

@ -1253,12 +1253,6 @@
["0x17 0x3014021077777777777777777777777777777777020001", "0 CHECKSIG NOT", "DERSIG", "SIG_DER", "Zero-length S is incorrectly encoded for DERSIG"],
["0x27 0x302402107777777777777777777777777777777702108777777777777777777777777777777701", "0 CHECKSIG NOT", "DERSIG", "SIG_DER", "Negative S is incorrectly encoded for DERSIG"],
["Some basic segwit checks"],
[["00", 0.00000000 ], "", "0 0x206e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d", "P2SH,WITNESS", "EVAL_FALSE", "Invalid witness script"],
[["51", 0.00000000 ], "", "0 0x206e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d", "P2SH,WITNESS", "WITNESS_PROGRAM_MISMATCH", "Witness script hash mismatch"],
[["00", 0.00000000 ], "", "0 0x206e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d", "", "OK", "Invalid witness script without WITNESS"],
[["51", 0.00000000 ], "", "0 0x206e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d", "", "OK", "Witness script hash mismatch without WITNESS"],
["Automatically generated test cases"],
[
"0x47 0x304402200a5c6163f07b8d3b013c4d1d6dba25e780b39658d79ba37af7057a3b7f15ffa102201fd9b4eaa9943f734928b99a83592c2e7bf342ea2680f6a2bb705167966b742001",
@ -1856,655 +1850,6 @@
"P2SH with CLEANSTACK"
],
["Testing with uncompressed keys in witness v0 without WITNESS_PUBKEYTYPE"],
[
[
"304402200d461c140cfdfcf36b94961db57ae8c18d1cb80e9d95a9e47ac22470c1bf125502201c8dc1cbfef6a3ef90acbbb992ca22fe9466ee6f9d4898eda277a7ac3ab4b25101",
"410479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8ac",
0.00000001
],
"",
"0 0x20 0xb95237b48faaa69eb078e1170be3b5cbb3fddf16d0a991e14ad274f7b33a4f64",
"P2SH,WITNESS",
"OK",
"Basic P2WSH"
],
[
[
"304402201e7216e5ccb3b61d46946ec6cc7e8c4e0117d13ac2fd4b152197e4805191c74202203e9903e33e84d9ee1dd13fb057afb7ccfb47006c23f6a067185efbc9dd780fc501",
"0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",
0.00000001
],
"",
"0 0x14 0x91b24bf9f5288532960ac687abb035127b1d28a5",
"P2SH,WITNESS",
"OK",
"Basic P2WPKH"
],
[
[
"3044022066e02c19a513049d49349cf5311a1b012b7c4fae023795a18ab1d91c23496c22022025e216342c8e07ce8ef51e8daee88f84306a9de66236cab230bb63067ded1ad301",
"410479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8ac",
0.00000001
],
"0x22 0x0020b95237b48faaa69eb078e1170be3b5cbb3fddf16d0a991e14ad274f7b33a4f64",
"HASH160 0x14 0xf386c2ba255cc56d20cfa6ea8b062f8b59945518 EQUAL",
"P2SH,WITNESS",
"OK",
"Basic P2SH(P2WSH)"
],
[
[
"304402200929d11561cd958460371200f82e9cae64c727a495715a31828e27a7ad57b36d0220361732ced04a6f97351ecca21a56d0b8cd4932c1da1f8f569a2b68e5e48aed7801",
"0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",
0.00000001
],
"0x16 0x001491b24bf9f5288532960ac687abb035127b1d28a5",
"HASH160 0x14 0x17743beb429c55c942d2ec703b98c4d57c2df5c6 EQUAL",
"P2SH,WITNESS",
"OK",
"Basic P2SH(P2WPKH)"
],
[
[
"304402202589f0512cb2408fb08ed9bd24f85eb3059744d9e4f2262d0b7f1338cff6e8b902206c0978f449693e0578c71bc543b11079fd0baae700ee5e9a6bee94db490af9fc01",
"41048282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f5150811f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26cafac",
0.00000000
],
"",
"0 0x20 0xac8ebd9e52c17619a381fa4f71aebb696087c6ef17c960fd0587addad99c0610",
"P2SH,WITNESS",
"EVAL_FALSE",
"Basic P2WSH with the wrong key"
],
[
[
"304402206ef7fdb2986325d37c6eb1a8bb24aeb46dede112ed8fc76c7d7500b9b83c0d3d02201edc2322c794fe2d6b0bd73ed319e714aa9b86d8891961530d5c9b7156b60d4e01",
"048282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f5150811f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf",
0.00000000
],
"",
"0 0x14 0x7cf9c846cd4882efec4bf07e44ebdad495c94f4b",
"P2SH,WITNESS",
"EVAL_FALSE",
"Basic P2WPKH with the wrong key"
],
[
[
"30440220069ea3581afaf8187f63feee1fd2bd1f9c0dc71ea7d6e8a8b07ee2ebcf824bf402201a4fdef4c532eae59223be1eda6a397fc835142d4ddc6c74f4aa85b766a5c16f01",
"41048282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f5150811f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26cafac",
0.00000000
],
"0x22 0x0020ac8ebd9e52c17619a381fa4f71aebb696087c6ef17c960fd0587addad99c0610",
"HASH160 0x14 0x61039a003883787c0d6ebc66d97fdabe8e31449d EQUAL",
"P2SH,WITNESS",
"EVAL_FALSE",
"Basic P2SH(P2WSH) with the wrong key"
],
[
[
"304402204209e49457c2358f80d0256bc24535b8754c14d08840fc4be762d6f5a0aed80b02202eaf7d8fc8d62f60c67adcd99295528d0e491ae93c195cec5a67e7a09532a88001",
"048282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f5150811f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf",
0.00000000
],
"0x16 0x00147cf9c846cd4882efec4bf07e44ebdad495c94f4b",
"HASH160 0x14 0x4e0c2aed91315303fc6a1dc4c7bc21c88f75402e EQUAL",
"P2SH,WITNESS",
"EVAL_FALSE",
"Basic P2SH(P2WPKH) with the wrong key"
],
[
[
"304402202589f0512cb2408fb08ed9bd24f85eb3059744d9e4f2262d0b7f1338cff6e8b902206c0978f449693e0578c71bc543b11079fd0baae700ee5e9a6bee94db490af9fc01",
"41048282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f5150811f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26cafac",
0.00000000
],
"",
"0 0x20 0xac8ebd9e52c17619a381fa4f71aebb696087c6ef17c960fd0587addad99c0610",
"P2SH",
"OK",
"Basic P2WSH with the wrong key but no WITNESS"
],
[
[
"304402206ef7fdb2986325d37c6eb1a8bb24aeb46dede112ed8fc76c7d7500b9b83c0d3d02201edc2322c794fe2d6b0bd73ed319e714aa9b86d8891961530d5c9b7156b60d4e01",
"048282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f5150811f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf",
0.00000000
],
"",
"0 0x14 0x7cf9c846cd4882efec4bf07e44ebdad495c94f4b",
"P2SH",
"OK",
"Basic P2WPKH with the wrong key but no WITNESS"
],
[
[
"30440220069ea3581afaf8187f63feee1fd2bd1f9c0dc71ea7d6e8a8b07ee2ebcf824bf402201a4fdef4c532eae59223be1eda6a397fc835142d4ddc6c74f4aa85b766a5c16f01",
"41048282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f5150811f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26cafac",
0.00000000
],
"0x22 0x0020ac8ebd9e52c17619a381fa4f71aebb696087c6ef17c960fd0587addad99c0610",
"HASH160 0x14 0x61039a003883787c0d6ebc66d97fdabe8e31449d EQUAL",
"P2SH",
"OK",
"Basic P2SH(P2WSH) with the wrong key but no WITNESS"
],
[
[
"304402204209e49457c2358f80d0256bc24535b8754c14d08840fc4be762d6f5a0aed80b02202eaf7d8fc8d62f60c67adcd99295528d0e491ae93c195cec5a67e7a09532a88001",
"048282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f5150811f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf",
0.00000000
],
"0x16 0x00147cf9c846cd4882efec4bf07e44ebdad495c94f4b",
"HASH160 0x14 0x4e0c2aed91315303fc6a1dc4c7bc21c88f75402e EQUAL",
"P2SH",
"OK",
"Basic P2SH(P2WPKH) with the wrong key but no WITNESS"
],
[
[
"3044022066faa86e74e8b30e82691b985b373de4f9e26dc144ec399c4f066aa59308e7c202204712b86f28c32503faa051dbeabff2c238ece861abc36c5e0b40b1139ca222f001",
"410479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8ac",
0.00000000
],
"",
"0 0x20 0xb95237b48faaa69eb078e1170be3b5cbb3fddf16d0a991e14ad274f7b33a4f64",
"P2SH,WITNESS",
"EVAL_FALSE",
"Basic P2WSH with wrong value"
],
[
[
"304402203b3389b87448d7dfdb5e82fb854fcf92d7925f9938ea5444e36abef02c3d6a9602202410bc3265049abb07fd2e252c65ab7034d95c9d5acccabe9fadbdc63a52712601",
"0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",
0.00000000
],
"",
"0 0x14 0x91b24bf9f5288532960ac687abb035127b1d28a5",
"P2SH,WITNESS",
"EVAL_FALSE",
"Basic P2WPKH with wrong value"
],
[
[
"3044022000a30c4cfc10e4387be528613575434826ad3c15587475e0df8ce3b1746aa210022008149265e4f8e9dafe1f3ea50d90cb425e9e40ea7ebdd383069a7cfa2b77004701",
"410479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8ac",
0.00000000
],
"0x22 0x0020b95237b48faaa69eb078e1170be3b5cbb3fddf16d0a991e14ad274f7b33a4f64",
"HASH160 0x14 0xf386c2ba255cc56d20cfa6ea8b062f8b59945518 EQUAL",
"P2SH,WITNESS",
"EVAL_FALSE",
"Basic P2SH(P2WSH) with wrong value"
],
[
[
"304402204fc3a2cd61a47913f2a5f9107d0ad4a504c7b31ee2d6b3b2f38c2b10ee031e940220055d58b7c3c281aaa381d8f486ac0f3e361939acfd568046cb6a311cdfa974cf01",
"0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",
0.00000000
],
"0x16 0x001491b24bf9f5288532960ac687abb035127b1d28a5",
"HASH160 0x14 0x17743beb429c55c942d2ec703b98c4d57c2df5c6 EQUAL",
"P2SH,WITNESS",
"EVAL_FALSE",
"Basic P2SH(P2WPKH) with wrong value"
],
[
[
"304402205ae57ae0534c05ca9981c8a6cdf353b505eaacb7375f96681a2d1a4ba6f02f84022056248e68643b7d8ce7c7d128c9f1f348bcab8be15d094ad5cadd24251a28df8001",
"0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",
0.00000000
],
"",
"1 0x14 0x91b24bf9f5288532960ac687abb035127b1d28a5",
"DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM,P2SH,WITNESS",
"DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM",
"P2WPKH with future witness version"
],
[
[
"3044022064100ca0e2a33332136775a86cd83d0230e58b9aebb889c5ac952abff79a46ef02205f1bf900e022039ad3091bdaf27ac2aef3eae9ed9f190d821d3e508405b9513101",
"0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",
0.00000000
],
"",
"0 0x1f 0xb34b78da162751647974d5cb7410aa428ad339dbf7d1e16e833f68a0cbf1c3",
"P2SH,WITNESS",
"WITNESS_PROGRAM_WRONG_LENGTH",
"P2WPKH with wrong witness program length"
],
[
"",
"0 0x20 0xb95237b48faaa69eb078e1170be3b5cbb3fddf16d0a991e14ad274f7b33a4f64",
"P2SH,WITNESS",
"WITNESS_PROGRAM_WITNESS_EMPTY",
"P2WSH with empty witness"
],
[
[
"3044022039105b995a5f448639a997a5c90fda06f50b49df30c3bdb6663217bf79323db002206fecd54269dec569fcc517178880eb58bb40f381a282bb75766ff3637d5f4b4301",
"400479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8ac",
0.00000000
],
"",
"0 0x20 0xb95237b48faaa69eb078e1170be3b5cbb3fddf16d0a991e14ad274f7b33a4f64",
"P2SH,WITNESS",
"WITNESS_PROGRAM_MISMATCH",
"P2WSH with witness program mismatch"
],
[
[
"304402201a96950593cb0af32d080b0f193517f4559241a8ebd1e95e414533ad64a3f423022047f4f6d3095c23235bdff3aeff480d0529c027a3f093cb265b7cbf148553b85101",
"0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",
"",
0.00000000
],
"",
"0 0x14 0x91b24bf9f5288532960ac687abb035127b1d28a5",
"P2SH,WITNESS",
"WITNESS_PROGRAM_MISMATCH",
"P2WPKH with witness program mismatch"
],
[
[
"304402201a96950593cb0af32d080b0f193517f4559241a8ebd1e95e414533ad64a3f423022047f4f6d3095c23235bdff3aeff480d0529c027a3f093cb265b7cbf148553b85101",
"0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",
0.00000000
],
"11",
"0 0x14 0x91b24bf9f5288532960ac687abb035127b1d28a5",
"P2SH,WITNESS",
"WITNESS_MALLEATED",
"P2WPKH with non-empty scriptSig"
],
[
[
"304402204209e49457c2358f80d0256bc24535b8754c14d08840fc4be762d6f5a0aed80b02202eaf7d8fc8d62f60c67adcd99295528d0e491ae93c195cec5a67e7a09532a88001",
"048282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f5150811f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf",
0.00000000
],
"11 0x16 0x00147cf9c846cd4882efec4bf07e44ebdad495c94f4b",
"HASH160 0x14 0x4e0c2aed91315303fc6a1dc4c7bc21c88f75402e EQUAL",
"P2SH,WITNESS",
"WITNESS_MALLEATED_P2SH",
"P2SH(P2WPKH) with superfluous push in scriptSig"
],
[
[
"",
0.00000000
],
"0x47 0x304402200a5c6163f07b8d3b013c4d1d6dba25e780b39658d79ba37af7057a3b7f15ffa102201fd9b4eaa9943f734928b99a83592c2e7bf342ea2680f6a2bb705167966b742001",
"0x41 0x0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8 CHECKSIG",
"P2SH,WITNESS",
"WITNESS_UNEXPECTED",
"P2PK with witness"
],
["Testing with compressed keys in witness v0 with WITNESS_PUBKEYTYPE"],
[
[
"304402204256146fcf8e73b0fd817ffa2a4e408ff0418ff987dd08a4f485b62546f6c43c02203f3c8c3e2febc051e1222867f5f9d0eaf039d6792911c10940aa3cc74123378e01",
"210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798ac",
0.00000001
],
"",
"0 0x20 0x1863143c14c5166804bd19203356da136c985678cd4d27a1b8c6329604903262",
"P2SH,WITNESS,WITNESS_PUBKEYTYPE",
"OK",
"Basic P2WSH with compressed key"
],
[
[
"304402204edf27486f11432466b744df533e1acac727e0c83e5f912eb289a3df5bf8035f022075809fdd876ede40ad21667eba8b7e96394938f9c9c50f11b6a1280cce2cea8601",
"0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
0.00000001
],
"",
"0 0x14 0x751e76e8199196d454941c45d1b3a323f1433bd6",
"P2SH,WITNESS,WITNESS_PUBKEYTYPE",
"OK",
"Basic P2WPKH with compressed key"
],
[
[
"304402203a549090cc46bce1e5e95c4922ea2c12747988e0207b04c42f81cdbe87bb1539022050f57a245b875fd5119c419aaf050bcdf41384f0765f04b809e5bced1fe7093d01",
"210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798ac",
0.00000001
],
"0x22 0x00201863143c14c5166804bd19203356da136c985678cd4d27a1b8c6329604903262",
"HASH160 0x14 0xe4300531190587e3880d4c3004f5355d88ff928d EQUAL",
"P2SH,WITNESS,WITNESS_PUBKEYTYPE",
"OK",
"Basic P2SH(P2WSH) with compressed key"
],
[
[
"304402201bc0d53046827f4a35a3166e33e3b3366c4085540dc383b95d21ed2ab11e368a0220333e78c6231214f5f8e59621e15d7eeab0d4e4d0796437e00bfbd2680c5f9c1701",
"0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
0.00000001
],
"0x16 0x0014751e76e8199196d454941c45d1b3a323f1433bd6",
"HASH160 0x14 0xbcfeb728b584253d5f3f70bcb780e9ef218a68f4 EQUAL",
"P2SH,WITNESS,WITNESS_PUBKEYTYPE",
"OK",
"Basic P2SH(P2WPKH) with compressed key"
],
["Testing with uncompressed keys in witness v0 with WITNESS_PUBKEYTYPE"],
[
[
"304402200d461c140cfdfcf36b94961db57ae8c18d1cb80e9d95a9e47ac22470c1bf125502201c8dc1cbfef6a3ef90acbbb992ca22fe9466ee6f9d4898eda277a7ac3ab4b25101",
"410479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8ac",
0.00000001
],
"",
"0 0x20 0xb95237b48faaa69eb078e1170be3b5cbb3fddf16d0a991e14ad274f7b33a4f64",
"P2SH,WITNESS,WITNESS_PUBKEYTYPE",
"WITNESS_PUBKEYTYPE",
"Basic P2WSH"
],
[
[
"304402201e7216e5ccb3b61d46946ec6cc7e8c4e0117d13ac2fd4b152197e4805191c74202203e9903e33e84d9ee1dd13fb057afb7ccfb47006c23f6a067185efbc9dd780fc501",
"0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",
0.00000001
],
"",
"0 0x14 0x91b24bf9f5288532960ac687abb035127b1d28a5",
"P2SH,WITNESS,WITNESS_PUBKEYTYPE",
"WITNESS_PUBKEYTYPE",
"Basic P2WPKH"
],
[
[
"3044022066e02c19a513049d49349cf5311a1b012b7c4fae023795a18ab1d91c23496c22022025e216342c8e07ce8ef51e8daee88f84306a9de66236cab230bb63067ded1ad301",
"410479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8ac",
0.00000001
],
"0x22 0x0020b95237b48faaa69eb078e1170be3b5cbb3fddf16d0a991e14ad274f7b33a4f64",
"HASH160 0x14 0xf386c2ba255cc56d20cfa6ea8b062f8b59945518 EQUAL",
"P2SH,WITNESS,WITNESS_PUBKEYTYPE",
"WITNESS_PUBKEYTYPE",
"Basic P2SH(P2WSH)"
],
[
[
"304402200929d11561cd958460371200f82e9cae64c727a495715a31828e27a7ad57b36d0220361732ced04a6f97351ecca21a56d0b8cd4932c1da1f8f569a2b68e5e48aed7801",
"0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",
0.00000001
],
"0x16 0x001491b24bf9f5288532960ac687abb035127b1d28a5",
"HASH160 0x14 0x17743beb429c55c942d2ec703b98c4d57c2df5c6 EQUAL",
"P2SH,WITNESS,WITNESS_PUBKEYTYPE",
"WITNESS_PUBKEYTYPE",
"Basic P2SH(P2WPKH)"
],
["Testing P2WSH multisig with compressed keys"],
[
[
"",
"304402207eb8a59b5c65fc3f6aeef77066556ed5c541948a53a3ba7f7c375b8eed76ee7502201e036a7a9a98ff919ff94dc905d67a1ec006f79ef7cff0708485c8bb79dce38e01",
"5121038282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f8179852ae",
0.00000001
],
"",
"0 0x20 0x06c24420938f0fa3c1cb2707d867154220dca365cdbfa0dd2a83854730221460",
"P2SH,WITNESS,WITNESS_PUBKEYTYPE",
"OK",
"P2WSH CHECKMULTISIG with compressed keys"
],
[
[
"",
"3044022033706aed33b8155d5486df3b9bca8cdd3bd4bdb5436dce46d72cdaba51d22b4002203626e94fe53a178af46624f17315c6931f20a30b103f5e044e1eda0c3fe185c601",
"5121038282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f8179852ae",
0.00000001
],
"0x22 0x002006c24420938f0fa3c1cb2707d867154220dca365cdbfa0dd2a83854730221460",
"HASH160 0x14 0x26282aad7c29369d15fed062a778b6100d31a340 EQUAL",
"P2SH,WITNESS,WITNESS_PUBKEYTYPE",
"OK",
"P2SH(P2WSH) CHECKMULTISIG with compressed keys"
],
[
[
"",
"304402204048b7371ab1c544362efb89af0c80154747d665aa4fcfb2edfd2d161e57b42e02207e043748e96637080ffc3acbd4dcc6fee1e58d30f6d1269535f32188e5ddae7301",
"5121038282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f8179852ae",
0.00000001
],
"",
"0 0x20 0x06c24420938f0fa3c1cb2707d867154220dca365cdbfa0dd2a83854730221460",
"P2SH,WITNESS,WITNESS_PUBKEYTYPE",
"OK",
"P2WSH CHECKMULTISIG with compressed keys"
],
[
[
"",
"3044022073902ef0b8a554c36c44cc03c1b64df96ce2914ebcf946f5bb36078fd5245cdf02205b148f1ba127065fb8c83a5a9576f2dcd111739788ed4bb3ee08b2bd3860c91c01",
"5121038282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f8179852ae",
0.00000001
],
"0x22 0x002006c24420938f0fa3c1cb2707d867154220dca365cdbfa0dd2a83854730221460",
"HASH160 0x14 0x26282aad7c29369d15fed062a778b6100d31a340 EQUAL",
"P2SH,WITNESS,WITNESS_PUBKEYTYPE",
"OK",
"P2SH(P2WSH) CHECKMULTISIG with compressed keys"
],
["Testing P2WSH multisig with compressed and uncompressed keys (first key being the key closer to the top of stack)"],
[
[
"",
"304402202d092ededd1f060609dbf8cb76950634ff42b3e62cf4adb69ab92397b07d742302204ff886f8d0817491a96d1daccdcc820f6feb122ee6230143303100db37dfa79f01",
"5121038282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508410479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b852ae",
0.00000001
],
"",
"0 0x20 0x08a6665ebfd43b02323423e764e185d98d1587f903b81507dbb69bfc41005efa",
"P2SH,WITNESS",
"OK",
"P2WSH CHECKMULTISIG with first key uncompressed and signing with the first key"
],
[
[
"",
"304402202dd7e91243f2235481ffb626c3b7baf2c859ae3a5a77fb750ef97b99a8125dc002204960de3d3c3ab9496e218ec57e5240e0e10a6f9546316fe240c216d45116d29301",
"5121038282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508410479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b852ae",
0.00000001
],
"0x22 0x002008a6665ebfd43b02323423e764e185d98d1587f903b81507dbb69bfc41005efa",
"HASH160 0x14 0x6f5ecd4b83b77f3c438f5214eff96454934fc5d1 EQUAL",
"P2SH,WITNESS",
"OK",
"P2SH(P2WSH) CHECKMULTISIG first key uncompressed and signing with the first key"
],
[
[
"",
"304402202d092ededd1f060609dbf8cb76950634ff42b3e62cf4adb69ab92397b07d742302204ff886f8d0817491a96d1daccdcc820f6feb122ee6230143303100db37dfa79f01",
"5121038282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508410479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b852ae",
0.00000001
],
"",
"0 0x20 0x08a6665ebfd43b02323423e764e185d98d1587f903b81507dbb69bfc41005efa",
"P2SH,WITNESS,WITNESS_PUBKEYTYPE",
"WITNESS_PUBKEYTYPE",
"P2WSH CHECKMULTISIG with first key uncompressed and signing with the first key"
],
[
[
"",
"304402202dd7e91243f2235481ffb626c3b7baf2c859ae3a5a77fb750ef97b99a8125dc002204960de3d3c3ab9496e218ec57e5240e0e10a6f9546316fe240c216d45116d29301",
"5121038282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508410479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b852ae",
0.00000001
],
"0x22 0x002008a6665ebfd43b02323423e764e185d98d1587f903b81507dbb69bfc41005efa",
"HASH160 0x14 0x6f5ecd4b83b77f3c438f5214eff96454934fc5d1 EQUAL",
"P2SH,WITNESS,WITNESS_PUBKEYTYPE",
"WITNESS_PUBKEYTYPE",
"P2SH(P2WSH) CHECKMULTISIG with first key uncompressed and signing with the first key"
],
[
[
"",
"304402201e9e6f7deef5b2f21d8223c5189b7d5e82d237c10e97165dd08f547c4e5ce6ed02206796372eb1cc6acb52e13ee2d7f45807780bf96b132cb6697f69434be74b1af901",
"5121038282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508410479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b852ae",
0.00000001
],
"",
"0 0x20 0x08a6665ebfd43b02323423e764e185d98d1587f903b81507dbb69bfc41005efa",
"P2SH,WITNESS",
"OK",
"P2WSH CHECKMULTISIG with first key uncompressed and signing with the second key"
],
[
[
"",
"3044022045e667f3f0f3147b95597a24babe9afecea1f649fd23637dfa7ed7e9f3ac18440220295748e81005231135289fe3a88338dabba55afa1bdb4478691337009d82b68d01",
"5121038282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508410479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b852ae",
0.00000001
],
"0x22 0x002008a6665ebfd43b02323423e764e185d98d1587f903b81507dbb69bfc41005efa",
"HASH160 0x14 0x6f5ecd4b83b77f3c438f5214eff96454934fc5d1 EQUAL",
"P2SH,WITNESS",
"OK",
"P2SH(P2WSH) CHECKMULTISIG with first key uncompressed and signing with the second key"
],
[
[
"",
"304402201e9e6f7deef5b2f21d8223c5189b7d5e82d237c10e97165dd08f547c4e5ce6ed02206796372eb1cc6acb52e13ee2d7f45807780bf96b132cb6697f69434be74b1af901",
"5121038282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508410479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b852ae",
0.00000001
],
"",
"0 0x20 0x08a6665ebfd43b02323423e764e185d98d1587f903b81507dbb69bfc41005efa",
"P2SH,WITNESS,WITNESS_PUBKEYTYPE",
"WITNESS_PUBKEYTYPE",
"P2WSH CHECKMULTISIG with first key uncompressed and signing with the second key"
],
[
[
"",
"3044022045e667f3f0f3147b95597a24babe9afecea1f649fd23637dfa7ed7e9f3ac18440220295748e81005231135289fe3a88338dabba55afa1bdb4478691337009d82b68d01",
"5121038282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508410479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b852ae",
0.00000001
],
"0x22 0x002008a6665ebfd43b02323423e764e185d98d1587f903b81507dbb69bfc41005efa",
"HASH160 0x14 0x6f5ecd4b83b77f3c438f5214eff96454934fc5d1 EQUAL",
"P2SH,WITNESS,WITNESS_PUBKEYTYPE",
"WITNESS_PUBKEYTYPE",
"P2SH(P2WSH) CHECKMULTISIG with first key uncompressed and signing with the second key"
],
[
[
"",
"3044022046f5367a261fd8f8d7de6eb390491344f8ec2501638fb9a1095a0599a21d3f4c02205c1b3b51d20091c5f1020841bbca87b44ebe25405c64e4acf758f2eae8665f8401",
"5141048282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f5150811f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f8179852ae",
0.00000001
],
"",
"0 0x20 0x230828ed48871f0f362ce9432aa52f620f442cc8d9ce7a8b5e798365595a38bb",
"P2SH,WITNESS",
"OK",
"P2WSH CHECKMULTISIG with second key uncompressed and signing with the first key"
],
[
[
"",
"3044022053e210e4fb1881e6092fd75c3efc5163105599e246ded661c0ee2b5682cc2d6c02203a26b7ada8682a095b84c6d1b881637000b47d761fc837c4cee33555296d63f101",
"5141048282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f5150811f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f8179852ae",
0.00000001
],
"0x22 0x0020230828ed48871f0f362ce9432aa52f620f442cc8d9ce7a8b5e798365595a38bb",
"HASH160 0x14 0x3478e7019ce61a68148f87549579b704cbe4c393 EQUAL",
"P2SH,WITNESS",
"OK",
"P2SH(P2WSH) CHECKMULTISIG second key uncompressed and signing with the first key"
],
[
[
"",
"3044022046f5367a261fd8f8d7de6eb390491344f8ec2501638fb9a1095a0599a21d3f4c02205c1b3b51d20091c5f1020841bbca87b44ebe25405c64e4acf758f2eae8665f8401",
"5141048282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f5150811f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f8179852ae",
0.00000001
],
"",
"0 0x20 0x230828ed48871f0f362ce9432aa52f620f442cc8d9ce7a8b5e798365595a38bb",
"P2SH,WITNESS,WITNESS_PUBKEYTYPE",
"OK",
"P2WSH CHECKMULTISIG with second key uncompressed and signing with the first key should pass as the uncompressed key is not used"
],
[
[
"",
"3044022053e210e4fb1881e6092fd75c3efc5163105599e246ded661c0ee2b5682cc2d6c02203a26b7ada8682a095b84c6d1b881637000b47d761fc837c4cee33555296d63f101",
"5141048282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f5150811f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f8179852ae",
0.00000001
],
"0x22 0x0020230828ed48871f0f362ce9432aa52f620f442cc8d9ce7a8b5e798365595a38bb",
"HASH160 0x14 0x3478e7019ce61a68148f87549579b704cbe4c393 EQUAL",
"P2SH,WITNESS,WITNESS_PUBKEYTYPE",
"OK",
"P2SH(P2WSH) CHECKMULTISIG with second key uncompressed and signing with the first key should pass as the uncompressed key is not used"
],
[
[
"",
"304402206c6d9f5daf85b54af2a93ec38b15ab27f205dbf5c735365ff12451e43613d1f40220736a44be63423ed5ebf53491618b7cc3d8a5093861908da853739c73717938b701",
"5141048282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f5150811f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f8179852ae",
0.00000001
],
"",
"0 0x20 0x230828ed48871f0f362ce9432aa52f620f442cc8d9ce7a8b5e798365595a38bb",
"P2SH,WITNESS",
"OK",
"P2WSH CHECKMULTISIG with second key uncompressed and signing with the second key"
],
[
[
"",
"30440220687871bc6144012d75baf585bb26ce13997f7d8c626f4d8825b069c3b2d064470220108936fe1c57327764782253e99090b09c203ec400ed35ce9e026ce2ecf842a001",
"5141048282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f5150811f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f8179852ae",
0.00000001
],
"0x22 0x0020230828ed48871f0f362ce9432aa52f620f442cc8d9ce7a8b5e798365595a38bb",
"HASH160 0x14 0x3478e7019ce61a68148f87549579b704cbe4c393 EQUAL",
"P2SH,WITNESS",
"OK",
"P2SH(P2WSH) CHECKMULTISIG with second key uncompressed and signing with the second key"
],
[
[
"",
"304402206c6d9f5daf85b54af2a93ec38b15ab27f205dbf5c735365ff12451e43613d1f40220736a44be63423ed5ebf53491618b7cc3d8a5093861908da853739c73717938b701",
"5141048282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f5150811f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f8179852ae",
0.00000001
],
"",
"0 0x20 0x230828ed48871f0f362ce9432aa52f620f442cc8d9ce7a8b5e798365595a38bb",
"P2SH,WITNESS,WITNESS_PUBKEYTYPE",
"WITNESS_PUBKEYTYPE",
"P2WSH CHECKMULTISIG with second key uncompressed and signing with the second key"
],
[
[
"",
"30440220687871bc6144012d75baf585bb26ce13997f7d8c626f4d8825b069c3b2d064470220108936fe1c57327764782253e99090b09c203ec400ed35ce9e026ce2ecf842a001",
"5141048282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f5150811f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f8179852ae",
0.00000001
],
"0x22 0x0020230828ed48871f0f362ce9432aa52f620f442cc8d9ce7a8b5e798365595a38bb",
"HASH160 0x14 0x3478e7019ce61a68148f87549579b704cbe4c393 EQUAL",
"P2SH,WITNESS,WITNESS_PUBKEYTYPE",
"WITNESS_PUBKEYTYPE",
"P2SH(P2WSH) CHECKMULTISIG with second key uncompressed and signing with the second key"
],
["CHECKSEQUENCEVERIFY tests"],
["", "CHECKSEQUENCEVERIFY", "CHECKSEQUENCEVERIFY", "INVALID_STACK_OPERATION", "CSV automatically fails on a empty stack"],
["-1", "CHECKSEQUENCEVERIFY", "CHECKSEQUENCEVERIFY", "NEGATIVE_LOCKTIME", "CSV automatically fails if stack top is negative"],
@ -2513,88 +1858,6 @@
["4294967296", "CHECKSEQUENCEVERIFY", "CHECKSEQUENCEVERIFY", "UNSATISFIED_LOCKTIME",
"CSV fails if stack top bit 1 << 31 is not set, and tx version < 2"],
["MINIMALIF tests"],
["MINIMALIF is not applied to non-segwit scripts"],
["1", "IF 1 ENDIF", "P2SH,WITNESS,MINIMALIF", "OK"],
["2", "IF 1 ENDIF", "P2SH,WITNESS,MINIMALIF", "OK"],
["0x02 0x0100", "IF 1 ENDIF", "P2SH,WITNESS,MINIMALIF", "OK"],
["0", "IF 1 ENDIF", "P2SH,WITNESS,MINIMALIF", "EVAL_FALSE"],
["0x01 0x00", "IF 1 ENDIF", "P2SH,WITNESS,MINIMALIF", "EVAL_FALSE"],
["1", "NOTIF 1 ENDIF", "P2SH,WITNESS,MINIMALIF", "EVAL_FALSE"],
["2", "NOTIF 1 ENDIF", "P2SH,WITNESS,MINIMALIF", "EVAL_FALSE"],
["0x02 0x0100", "NOTIF 1 ENDIF", "P2SH,WITNESS,MINIMALIF", "EVAL_FALSE"],
["0", "NOTIF 1 ENDIF", "P2SH,WITNESS,MINIMALIF", "OK"],
["0x01 0x00", "NOTIF 1 ENDIF", "P2SH,WITNESS,MINIMALIF", "OK"],
["Normal P2SH IF 1 ENDIF"],
["1 0x03 0x635168", "HASH160 0x14 0xe7309652a8e3f600f06f5d8d52d6df03d2176cc3 EQUAL", "P2SH,WITNESS,MINIMALIF", "OK"],
["2 0x03 0x635168", "HASH160 0x14 0xe7309652a8e3f600f06f5d8d52d6df03d2176cc3 EQUAL", "P2SH,WITNESS,MINIMALIF", "OK"],
["0x02 0x0100 0x03 0x635168", "HASH160 0x14 0xe7309652a8e3f600f06f5d8d52d6df03d2176cc3 EQUAL", "P2SH,WITNESS,MINIMALIF", "OK"],
["0 0x03 0x635168", "HASH160 0x14 0xe7309652a8e3f600f06f5d8d52d6df03d2176cc3 EQUAL", "P2SH,WITNESS,MINIMALIF", "EVAL_FALSE"],
["0x01 0x00 0x03 0x635168", "HASH160 0x14 0xe7309652a8e3f600f06f5d8d52d6df03d2176cc3 EQUAL", "P2SH,WITNESS,MINIMALIF", "EVAL_FALSE"],
["0x03 0x635168", "HASH160 0x14 0xe7309652a8e3f600f06f5d8d52d6df03d2176cc3 EQUAL", "P2SH,WITNESS,MINIMALIF", "UNBALANCED_CONDITIONAL"],
["Normal P2SH NOTIF 1 ENDIF"],
["1 0x03 0x645168", "HASH160 0x14 0x0c3f8fe3d6ca266e76311ecda544c67d15fdd5b0 EQUAL", "P2SH,WITNESS,MINIMALIF", "EVAL_FALSE"],
["2 0x03 0x645168", "HASH160 0x14 0x0c3f8fe3d6ca266e76311ecda544c67d15fdd5b0 EQUAL", "P2SH,WITNESS,MINIMALIF", "EVAL_FALSE"],
["0x02 0x0100 0x03 0x645168", "HASH160 0x14 0x0c3f8fe3d6ca266e76311ecda544c67d15fdd5b0 EQUAL", "P2SH,WITNESS,MINIMALIF", "EVAL_FALSE"],
["0 0x03 0x645168", "HASH160 0x14 0x0c3f8fe3d6ca266e76311ecda544c67d15fdd5b0 EQUAL", "P2SH,WITNESS,MINIMALIF", "OK"],
["0x01 0x00 0x03 0x645168", "HASH160 0x14 0x0c3f8fe3d6ca266e76311ecda544c67d15fdd5b0 EQUAL", "P2SH,WITNESS,MINIMALIF", "OK"],
["0x03 0x645168", "HASH160 0x14 0x0c3f8fe3d6ca266e76311ecda544c67d15fdd5b0 EQUAL", "P2SH,WITNESS,MINIMALIF", "UNBALANCED_CONDITIONAL"],
["P2WSH IF 1 ENDIF"],
[["01", "635168", 0.00000001], "", "0 0x20 0xc7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "P2SH,WITNESS", "OK"],
[["02", "635168", 0.00000001], "", "0 0x20 0xc7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "P2SH,WITNESS", "OK"],
[["0100", "635168", 0.00000001], "", "0 0x20 0xc7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "P2SH,WITNESS", "OK"],
[["", "635168", 0.00000001], "", "0 0x20 0xc7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "P2SH,WITNESS", "EVAL_FALSE"],
[["00", "635168", 0.00000001], "", "0 0x20 0xc7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "P2SH,WITNESS", "EVAL_FALSE"],
[["01", "635168", 0.00000001], "", "0 0x20 0xc7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "P2SH,WITNESS,MINIMALIF", "OK"],
[["02", "635168", 0.00000001], "", "0 0x20 0xc7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "P2SH,WITNESS,MINIMALIF", "MINIMALIF"],
[["0100", "635168", 0.00000001], "", "0 0x20 0xc7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "P2SH,WITNESS,MINIMALIF", "MINIMALIF"],
[["", "635168", 0.00000001], "", "0 0x20 0xc7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "P2SH,WITNESS,MINIMALIF", "EVAL_FALSE"],
[["00", "635168", 0.00000001], "", "0 0x20 0xc7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "P2SH,WITNESS,MINIMALIF", "MINIMALIF"],
[["635168", 0.00000001], "", "0 0x20 0xc7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "P2SH,WITNESS", "UNBALANCED_CONDITIONAL"],
[["635168", 0.00000001], "", "0 0x20 0xc7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "P2SH,WITNESS,MINIMALIF", "UNBALANCED_CONDITIONAL"],
["P2WSH NOTIF 1 ENDIF"],
[["01", "645168", 0.00000001], "", "0 0x20 0xf913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "P2SH,WITNESS", "EVAL_FALSE"],
[["02", "645168", 0.00000001], "", "0 0x20 0xf913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "P2SH,WITNESS", "EVAL_FALSE"],
[["0100", "645168", 0.00000001], "", "0 0x20 0xf913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "P2SH,WITNESS", "EVAL_FALSE"],
[["", "645168", 0.00000001], "", "0 0x20 0xf913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "P2SH,WITNESS", "OK"],
[["00", "645168", 0.00000001], "", "0 0x20 0xf913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "P2SH,WITNESS", "OK"],
[["01", "645168", 0.00000001], "", "0 0x20 0xf913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "P2SH,WITNESS,MINIMALIF", "EVAL_FALSE"],
[["02", "645168", 0.00000001], "", "0 0x20 0xf913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "P2SH,WITNESS,MINIMALIF", "MINIMALIF"],
[["0100", "645168", 0.00000001], "", "0 0x20 0xf913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "P2SH,WITNESS,MINIMALIF", "MINIMALIF"],
[["", "645168", 0.00000001], "", "0 0x20 0xf913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "P2SH,WITNESS,MINIMALIF", "OK"],
[["00", "645168", 0.00000001], "", "0 0x20 0xf913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "P2SH,WITNESS,MINIMALIF", "MINIMALIF"],
[["645168", 0.00000001], "", "0 0x20 0xf913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "P2SH,WITNESS", "UNBALANCED_CONDITIONAL"],
[["645168", 0.00000001], "", "0 0x20 0xf913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "P2SH,WITNESS,MINIMALIF", "UNBALANCED_CONDITIONAL"],
["P2SH-P2WSH IF 1 ENDIF"],
[["01", "635168", 0.00000001], "0x22 0x0020c7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "HASH160 0x14 0x9b27ee6d9010c21bf837b334d043be5d150e7ba7 EQUAL", "P2SH,WITNESS", "OK"],
[["02", "635168", 0.00000001], "0x22 0x0020c7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "HASH160 0x14 0x9b27ee6d9010c21bf837b334d043be5d150e7ba7 EQUAL", "P2SH,WITNESS", "OK"],
[["0100", "635168", 0.00000001], "0x22 0x0020c7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "HASH160 0x14 0x9b27ee6d9010c21bf837b334d043be5d150e7ba7 EQUAL", "P2SH,WITNESS", "OK"],
[["", "635168", 0.00000001], "0x22 0x0020c7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "HASH160 0x14 0x9b27ee6d9010c21bf837b334d043be5d150e7ba7 EQUAL", "P2SH,WITNESS", "EVAL_FALSE"],
[["00", "635168", 0.00000001], "0x22 0x0020c7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "HASH160 0x14 0x9b27ee6d9010c21bf837b334d043be5d150e7ba7 EQUAL", "P2SH,WITNESS", "EVAL_FALSE"],
[["01", "635168", 0.00000001], "0x22 0x0020c7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "HASH160 0x14 0x9b27ee6d9010c21bf837b334d043be5d150e7ba7 EQUAL", "P2SH,WITNESS,MINIMALIF", "OK"],
[["02", "635168", 0.00000001], "0x22 0x0020c7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "HASH160 0x14 0x9b27ee6d9010c21bf837b334d043be5d150e7ba7 EQUAL", "P2SH,WITNESS,MINIMALIF", "MINIMALIF"],
[["0100", "635168", 0.00000001], "0x22 0x0020c7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "HASH160 0x14 0x9b27ee6d9010c21bf837b334d043be5d150e7ba7 EQUAL", "P2SH,WITNESS,MINIMALIF", "MINIMALIF"],
[["", "635168", 0.00000001], "0x22 0x0020c7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "HASH160 0x14 0x9b27ee6d9010c21bf837b334d043be5d150e7ba7 EQUAL", "P2SH,WITNESS,MINIMALIF", "EVAL_FALSE"],
[["00", "635168", 0.00000001], "0x22 0x0020c7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "HASH160 0x14 0x9b27ee6d9010c21bf837b334d043be5d150e7ba7 EQUAL", "P2SH,WITNESS,MINIMALIF", "MINIMALIF"],
[["635168", 0.00000001], "0x22 0x0020c7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "HASH160 0x14 0x9b27ee6d9010c21bf837b334d043be5d150e7ba7 EQUAL", "P2SH,WITNESS", "UNBALANCED_CONDITIONAL"],
[["635168", 0.00000001], "0x22 0x0020c7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "HASH160 0x14 0x9b27ee6d9010c21bf837b334d043be5d150e7ba7 EQUAL", "P2SH,WITNESS,MINIMALIF", "UNBALANCED_CONDITIONAL"],
["P2SH-P2WSH NOTIF 1 ENDIF"],
[["01", "645168", 0.00000001], "0x22 0x0020f913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "HASH160 0x14 0xdbb7d1c0a56b7a9c423300c8cca6e6e065baf1dc EQUAL", "P2SH,WITNESS", "EVAL_FALSE"],
[["02", "645168", 0.00000001], "0x22 0x0020f913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "HASH160 0x14 0xdbb7d1c0a56b7a9c423300c8cca6e6e065baf1dc EQUAL", "P2SH,WITNESS", "EVAL_FALSE"],
[["0100", "645168", 0.00000001], "0x22 0x0020f913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "HASH160 0x14 0xdbb7d1c0a56b7a9c423300c8cca6e6e065baf1dc EQUAL", "P2SH,WITNESS", "EVAL_FALSE"],
[["", "645168", 0.00000001], "0x22 0x0020f913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "HASH160 0x14 0xdbb7d1c0a56b7a9c423300c8cca6e6e065baf1dc EQUAL", "P2SH,WITNESS", "OK"],
[["00", "645168", 0.00000001], "0x22 0x0020f913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "HASH160 0x14 0xdbb7d1c0a56b7a9c423300c8cca6e6e065baf1dc EQUAL", "P2SH,WITNESS", "OK"],
[["01", "645168", 0.00000001], "0x22 0x0020f913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "HASH160 0x14 0xdbb7d1c0a56b7a9c423300c8cca6e6e065baf1dc EQUAL", "P2SH,WITNESS,MINIMALIF", "EVAL_FALSE"],
[["02", "645168", 0.00000001], "0x22 0x0020f913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "HASH160 0x14 0xdbb7d1c0a56b7a9c423300c8cca6e6e065baf1dc EQUAL", "P2SH,WITNESS,MINIMALIF", "MINIMALIF"],
[["0100", "645168", 0.00000001], "0x22 0x0020f913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "HASH160 0x14 0xdbb7d1c0a56b7a9c423300c8cca6e6e065baf1dc EQUAL", "P2SH,WITNESS,MINIMALIF", "MINIMALIF"],
[["", "645168", 0.00000001], "0x22 0x0020f913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "HASH160 0x14 0xdbb7d1c0a56b7a9c423300c8cca6e6e065baf1dc EQUAL", "P2SH,WITNESS,MINIMALIF", "OK"],
[["00", "645168", 0.00000001], "0x22 0x0020f913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "HASH160 0x14 0xdbb7d1c0a56b7a9c423300c8cca6e6e065baf1dc EQUAL", "P2SH,WITNESS,MINIMALIF", "MINIMALIF"],
[["645168", 0.00000001], "0x22 0x0020f913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "HASH160 0x14 0xdbb7d1c0a56b7a9c423300c8cca6e6e065baf1dc EQUAL", "P2SH,WITNESS", "UNBALANCED_CONDITIONAL"],
[["645168", 0.00000001], "0x22 0x0020f913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "HASH160 0x14 0xdbb7d1c0a56b7a9c423300c8cca6e6e065baf1dc EQUAL", "P2SH,WITNESS,MINIMALIF", "UNBALANCED_CONDITIONAL"],
["NULLFAIL should cover all signatures and signatures only"],
["0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0", "0x01 0x14 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0x01 0x14 CHECKMULTISIG NOT", "DERSIG", "OK", "BIP66 and NULLFAIL-compliant"],
["0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0", "0x01 0x14 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0x01 0x14 CHECKMULTISIG NOT", "DERSIG,NULLFAIL", "OK", "BIP66 and NULLFAIL-compliant"],

View File

@ -245,94 +245,5 @@
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "4194304 CHECKSEQUENCEVERIFY 1"]],
"010000000100010000000000000000000000000000000000000000000000000000000000000000000000000040000100000000000000000000000000", "P2SH,CHECKSEQUENCEVERIFY"],
["Unknown witness program version (with DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM)"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x51", 1000],
["0000000000000000000000000000000000000000000000000000000000000100", 1, "0x60 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f", 2000],
["0000000000000000000000000000000000000000000000000000000000000100", 2, "0x51", 3000]],
"0100000000010300010000000000000000000000000000000000000000000000000000000000000000000000ffffffff00010000000000000000000000000000000000000000000000000000000000000100000000ffffffff00010000000000000000000000000000000000000000000000000000000000000200000000ffffffff03e8030000000000000151d0070000000000000151b80b00000000000001510002483045022100a3cec69b52cba2d2de623ffffffffff1606184ea55476c0f8189fda231bc9cbb022003181ad597f7c380a7d1c740286b1d022b8b04ded028b833282e055e03b8efef812103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc710000000000", "P2SH,WITNESS,DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM"],
["Unknown length for witness program v0"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x51", 1000],
["0000000000000000000000000000000000000000000000000000000000000100", 1, "0x00 0x15 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3fff", 2000],
["0000000000000000000000000000000000000000000000000000000000000100", 2, "0x51", 3000]],
"0100000000010300010000000000000000000000000000000000000000000000000000000000000000000000ffffffff00010000000000000000000000000000000000000000000000000000000000000100000000ffffffff00010000000000000000000000000000000000000000000000000000000000000200000000ffffffff04b60300000000000001519e070000000000000151860b0000000000000100960000000000000001510002473044022022fceb54f62f8feea77faac7083c3b56c4676a78f93745adc8a35800bc36adfa022026927df9abcf0a8777829bcfcce3ff0a385fa54c3f9df577405e3ef24ee56479022103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc710000000000", "P2SH,WITNESS"],
["Witness with SigHash Single|AnyoneCanPay (same index output value changed)"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x51", 1000],
["0000000000000000000000000000000000000000000000000000000000000100", 1, "0x00 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f", 2000],
["0000000000000000000000000000000000000000000000000000000000000100", 2, "0x51", 3000]],
"0100000000010300010000000000000000000000000000000000000000000000000000000000000000000000ffffffff00010000000000000000000000000000000000000000000000000000000000000100000000ffffffff00010000000000000000000000000000000000000000000000000000000000000200000000ffffffff03e80300000000000001516c070000000000000151b80b0000000000000151000248304502210092f4777a0f17bf5aeb8ae768dec5f2c14feabf9d1fe2c89c78dfed0f13fdb86902206da90a86042e252bcd1e80a168c719e4a1ddcc3cebea24b9812c5453c79107e9832103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc710000000000", "P2SH,WITNESS"],
["Witness with SigHash None|AnyoneCanPay (input sequence changed)"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x51", 1000],
["0000000000000000000000000000000000000000000000000000000000000100", 1, "0x00 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f", 2000],
["0000000000000000000000000000000000000000000000000000000000000100", 2, "0x51", 3000]],
"0100000000010300010000000000000000000000000000000000000000000000000000000000000000000000ffffffff000100000000000000000000000000000000000000000000000000000000000001000000000100000000010000000000000000000000000000000000000000000000000000000000000200000000ffffffff00000248304502210091b32274295c2a3fa02f5bce92fb2789e3fc6ea947fbe1a76e52ea3f4ef2381a022079ad72aefa3837a2e0c033a8652a59731da05fa4a813f4fc48e87c075037256b822103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc710000000000", "P2SH,WITNESS"],
["Witness with SigHash All|AnyoneCanPay (third output value changed)"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x51", 1000],
["0000000000000000000000000000000000000000000000000000000000000100", 1, "0x00 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f", 2000],
["0000000000000000000000000000000000000000000000000000000000000100", 2, "0x51", 3000]],
"0100000000010300010000000000000000000000000000000000000000000000000000000000000000000000ffffffff00010000000000000000000000000000000000000000000000000000000000000100000000ffffffff00010000000000000000000000000000000000000000000000000000000000000200000000ffffffff03e8030000000000000151d0070000000000000151540b00000000000001510002483045022100a3cec69b52cba2d2de623eeef89e0ba1606184ea55476c0f8189fda231bc9cbb022003181ad597f7c380a7d1c740286b1d022b8b04ded028b833282e055e03b8efef812103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc710000000000", "P2SH,WITNESS"],
["Witness with a push of 521 bytes"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x00 0x20 0x33198a9bfef674ebddb9ffaa52928017b8472791e54c609cb95f278ac6b1e349", 1000]],
"0100000000010100010000000000000000000000000000000000000000000000000000000000000000000000ffffffff010000000000000000015102fd0902000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002755100000000", "P2SH,WITNESS"],
["Witness with unknown version which push false on the stack should be invalid (even without DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM)"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x60 0x02 0x0000", 2000]],
"0100000000010100010000000000000000000000000000000000000000000000000000000000000000000000ffffffff010000000000000000015101010100000000", "P2SH,WITNESS"],
["Witness program should leave clean stack"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x00 0x20 0x2f04a3aa051f1f60d695f6c44c0c3d383973dfd446ace8962664a76bb10e31a8", 2000]],
"0100000000010100010000000000000000000000000000000000000000000000000000000000000000000000ffffffff01000000000000000001510102515100000000", "P2SH,WITNESS"],
["Witness v0 with a push of 2 bytes"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x00 0x02 0x0001", 2000]],
"0100000000010100010000000000000000000000000000000000000000000000000000000000000000000000ffffffff010000000000000000015101040002000100000000", "P2SH,WITNESS"],
["Unknown witness version with non empty scriptSig"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x60 0x02 0x0001", 2000]],
"01000000010001000000000000000000000000000000000000000000000000000000000000000000000151ffffffff010000000000000000015100000000", "P2SH,WITNESS"],
["Non witness Single|AnyoneCanPay hash input's position (permutation)"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x21 0x03596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc71 CHECKSIG", 1000],
["0000000000000000000000000000000000000000000000000000000000000100", 1, "0x21 0x03596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc71 CHECKSIG", 1001]],
"010000000200010000000000000000000000000000000000000000000000000000000000000100000049483045022100acb96cfdbda6dc94b489fd06f2d720983b5f350e31ba906cdbd800773e80b21c02200d74ea5bdf114212b4bbe9ed82c36d2e369e302dff57cb60d01c428f0bd3daab83ffffffff0001000000000000000000000000000000000000000000000000000000000000000000004847304402202a0b4b1294d70540235ae033d78e64b4897ec859c7b6f1b2b1d8a02e1d46006702201445e756d2254b0f1dfda9ab8e1e1bc26df9668077403204f32d16a49a36eb6983ffffffff02e9030000000000000151e803000000000000015100000000", "P2SH,WITNESS"],
["P2WSH with a redeem representing a witness scriptPubKey should fail"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x00 0x20 0x34b6c399093e06cf9f0f7f660a1abcfe78fcf7b576f43993208edd9518a0ae9b", 1000]],
"0100000000010100010000000000000000000000000000000000000000000000000000000000000000000000ffffffff0001045102010100000000", "P2SH,WITNESS"],
["33 bytes push should be considered a witness scriptPubKey"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x60 0x21 0xff25429251b5a84f452230a3c75fd886b7fc5a7865ce4a7bb7a9d7c5be6da3dbff", 1000]],
"010000000100010000000000000000000000000000000000000000000000000000000000000000000000ffffffff01e803000000000000015100000000", "P2SH,WITNESS,DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM"],
["FindAndDelete tests"],
["This is a test of FindAndDelete. The first tx is a spend of normal scriptPubKey and the second tx is a spend of bare P2WSH."],
["The redeemScript/witnessScript is CHECKSIGVERIFY <0x30450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e01>."],
["The signature is <0x30450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e01> <pubkey>,"],
["where the pubkey is obtained through key recovery with sig and the wrong sighash."],
["This is to show that FindAndDelete is applied only to non-segwit scripts"],
["To show that the tests are 'correctly wrong', they should pass by modifying OP_CHECKSIG under interpreter.cpp"],
["by replacing (sigversion == SIGVERSION_BASE) with (sigversion != SIGVERSION_BASE)"],
["Non-segwit: wrong sighash (without FindAndDelete) = 1ba1fe3bc90c5d1265460e684ce6774e324f0fabdf67619eda729e64e8b6bc08"],
[[["f18783ace138abac5d3a7a5cf08e88fe6912f267ef936452e0c27d090621c169", 7000, "HASH160 0x14 0x0c746489e2d83cdbb5b90b432773342ba809c134 EQUAL", 200000]],
"010000000169c12106097dc2e0526493ef67f21269fe888ef05c7a3a5dacab38e1ac8387f1581b0000b64830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e012103b12a1ec8428fc74166926318c15e17408fea82dbb157575e16a8c365f546248f4aad4830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e01ffffffff0101000000000000000000000000", "P2SH,WITNESS"],
["BIP143: wrong sighash (with FindAndDelete) = 71c9cd9b2869b9c70b01b1f0360c148f42dee72297db312638df136f43311f23"],
[[["f18783ace138abac5d3a7a5cf08e88fe6912f267ef936452e0c27d090621c169", 7500, "0x00 0x20 0x9e1be07558ea5cc8e02ed1d80c0911048afad949affa36d5c3951e3159dbea19", 200000]],
"0100000000010169c12106097dc2e0526493ef67f21269fe888ef05c7a3a5dacab38e1ac8387f14c1d000000ffffffff01010000000000000000034830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e012102a9d7ed6e161f0e255c10bbfcca0128a9e2035c2c8da58899c54d22d3a31afdef4aad4830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e0100000000", "P2SH,WITNESS"],
["This is multisig version of the FindAndDelete tests"],
["Script is 2 CHECKMULTISIGVERIFY <sig1> <sig2> DROP"],
["52af4830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e0148304502205286f726690b2e9b0207f0345711e63fa7012045b9eb0f19c2458ce1db90cf43022100e89f17f86abc5b149eba4115d4f128bcf45d77fb3ecdd34f594091340c0395960175"],
["Signature is 0 <sig1> <sig2> 2 <key1> <key2>"],
["Should pass by replacing (sigversion == SIGVERSION_BASE) with (sigversion != SIGVERSION_BASE) under OP_CHECKMULTISIG"],
["Non-segwit: wrong sighash (without FindAndDelete) = 4bc6a53e8e16ef508c19e38bba08831daba85228b0211f323d4cb0999cf2a5e8"],
[[["9628667ad48219a169b41b020800162287d2c0f713c04157e95c484a8dcb7592", 7000, "HASH160 0x14 0x5748407f5ca5cdca53ba30b79040260770c9ee1b EQUAL", 200000]],
"01000000019275cb8d4a485ce95741c013f7c0d28722160008021bb469a11982d47a662896581b0000fd6f01004830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e0148304502205286f726690b2e9b0207f0345711e63fa7012045b9eb0f19c2458ce1db90cf43022100e89f17f86abc5b149eba4115d4f128bcf45d77fb3ecdd34f594091340c039596015221023fd5dd42b44769c5653cbc5947ff30ab8871f240ad0c0e7432aefe84b5b4ff3421039d52178dbde360b83f19cf348deb04fa8360e1bf5634577be8e50fafc2b0e4ef4c9552af4830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e0148304502205286f726690b2e9b0207f0345711e63fa7012045b9eb0f19c2458ce1db90cf43022100e89f17f86abc5b149eba4115d4f128bcf45d77fb3ecdd34f594091340c0395960175ffffffff0101000000000000000000000000", "P2SH,WITNESS"],
["BIP143: wrong sighash (with FindAndDelete) = 17c50ec2181ecdfdc85ca081174b248199ba81fff730794d4f69b8ec031f2dce"],
[[["9628667ad48219a169b41b020800162287d2c0f713c04157e95c484a8dcb7592", 7500, "0x00 0x20 0x9b66c15b4e0b4eb49fa877982cafded24859fe5b0e2dbfbe4f0df1de7743fd52", 200000]],
"010000000001019275cb8d4a485ce95741c013f7c0d28722160008021bb469a11982d47a6628964c1d000000ffffffff0101000000000000000007004830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e0148304502205286f726690b2e9b0207f0345711e63fa7012045b9eb0f19c2458ce1db90cf43022100e89f17f86abc5b149eba4115d4f128bcf45d77fb3ecdd34f594091340c03959601010221023cb6055f4b57a1580c5a753e19610cafaedf7e0ff377731c77837fd666eae1712102c1b1db303ac232ffa8e5e7cc2cf5f96c6e40d3e6914061204c0541cb2043a0969552af4830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e0148304502205286f726690b2e9b0207f0345711e63fa7012045b9eb0f19c2458ce1db90cf43022100e89f17f86abc5b149eba4115d4f128bcf45d77fb3ecdd34f594091340c039596017500000000", "P2SH,WITNESS"],
["Make diffs cleaner by leaving a comment here without comma at the end"]
]

View File

@ -317,198 +317,5 @@
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "HASH160 0x14 0x7c17aff532f22beb54069942f9bf567a66133eaf EQUAL"]],
"0200000001000100000000000000000000000000000000000000000000000000000000000000000000030251b2010000000100000000000000000000000000", "P2SH,CHECKSEQUENCEVERIFY"],
["Valid P2WPKH (Private key of segwit tests is L5AQtV2HDm4xGsseLokK2VAT2EtYKcTm3c7HwqnJBFt9LdaQULsM)"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x00 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f", 1000]],
"0100000000010100010000000000000000000000000000000000000000000000000000000000000000000000ffffffff01e8030000000000001976a9144c9c3dfac4207d5d8cb89df5722cb3d712385e3f88ac02483045022100cfb07164b36ba64c1b1e8c7720a56ad64d96f6ef332d3d37f9cb3c96477dc44502200a464cd7a9cf94cd70f66ce4f4f0625ef650052c7afcfe29d7d7e01830ff91ed012103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc7100000000", "P2SH,WITNESS"],
["Valid P2WSH"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x00 0x20 0xff25429251b5a84f452230a3c75fd886b7fc5a7865ce4a7bb7a9d7c5be6da3db", 1000]],
"0100000000010100010000000000000000000000000000000000000000000000000000000000000000000000ffffffff01e8030000000000001976a9144c9c3dfac4207d5d8cb89df5722cb3d712385e3f88ac02483045022100aa5d8aa40a90f23ce2c3d11bc845ca4a12acd99cbea37de6b9f6d86edebba8cb022022dedc2aa0a255f74d04c0b76ece2d7c691f9dd11a64a8ac49f62a99c3a05f9d01232103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc71ac00000000", "P2SH,WITNESS"],
["Valid P2SH(P2WPKH)"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "HASH160 0x14 0xfe9c7dacc9fcfbf7e3b7d5ad06aa2b28c5a7b7e3 EQUAL", 1000]],
"01000000000101000100000000000000000000000000000000000000000000000000000000000000000000171600144c9c3dfac4207d5d8cb89df5722cb3d712385e3fffffffff01e8030000000000001976a9144c9c3dfac4207d5d8cb89df5722cb3d712385e3f88ac02483045022100cfb07164b36ba64c1b1e8c7720a56ad64d96f6ef332d3d37f9cb3c96477dc44502200a464cd7a9cf94cd70f66ce4f4f0625ef650052c7afcfe29d7d7e01830ff91ed012103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc7100000000", "P2SH,WITNESS"],
["Valid P2SH(P2WSH)"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "HASH160 0x14 0x2135ab4f0981830311e35600eebc7376dce3a914 EQUAL", 1000]],
"0100000000010100010000000000000000000000000000000000000000000000000000000000000000000023220020ff25429251b5a84f452230a3c75fd886b7fc5a7865ce4a7bb7a9d7c5be6da3dbffffffff01e8030000000000001976a9144c9c3dfac4207d5d8cb89df5722cb3d712385e3f88ac02483045022100aa5d8aa40a90f23ce2c3d11bc845ca4a12acd99cbea37de6b9f6d86edebba8cb022022dedc2aa0a255f74d04c0b76ece2d7c691f9dd11a64a8ac49f62a99c3a05f9d01232103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc71ac00000000", "P2SH,WITNESS"],
["Witness with SigHash Single|AnyoneCanPay"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 2, "0x51", 3100],
["0000000000000000000000000000000000000000000000000000000000000100", 1, "0x00 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f", 2000],
["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x51", 1100],
["0000000000000000000000000000000000000000000000000000000000000100", 3, "0x51", 4100]],
"0100000000010400010000000000000000000000000000000000000000000000000000000000000200000000ffffffff00010000000000000000000000000000000000000000000000000000000000000100000000ffffffff00010000000000000000000000000000000000000000000000000000000000000000000000ffffffff00010000000000000000000000000000000000000000000000000000000000000300000000ffffffff05540b0000000000000151d0070000000000000151840300000000000001513c0f00000000000001512c010000000000000151000248304502210092f4777a0f17bf5aeb8ae768dec5f2c14feabf9d1fe2c89c78dfed0f13fdb86902206da90a86042e252bcd1e80a168c719e4a1ddcc3cebea24b9812c5453c79107e9832103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc71000000000000", "P2SH,WITNESS"],
["Witness with SigHash Single|AnyoneCanPay (same signature as previous)"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x51", 1000],
["0000000000000000000000000000000000000000000000000000000000000100", 1, "0x00 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f", 2000],
["0000000000000000000000000000000000000000000000000000000000000100", 2, "0x51", 3000]],
"0100000000010300010000000000000000000000000000000000000000000000000000000000000000000000ffffffff00010000000000000000000000000000000000000000000000000000000000000100000000ffffffff00010000000000000000000000000000000000000000000000000000000000000200000000ffffffff03e8030000000000000151d0070000000000000151b80b0000000000000151000248304502210092f4777a0f17bf5aeb8ae768dec5f2c14feabf9d1fe2c89c78dfed0f13fdb86902206da90a86042e252bcd1e80a168c719e4a1ddcc3cebea24b9812c5453c79107e9832103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc710000000000", "P2SH,WITNESS"],
["Witness with SigHash Single"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x51", 1000],
["0000000000000000000000000000000000000000000000000000000000000100", 1, "0x00 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f", 2000],
["0000000000000000000000000000000000000000000000000000000000000100", 2, "0x51", 3000]],
"0100000000010300010000000000000000000000000000000000000000000000000000000000000000000000ffffffff00010000000000000000000000000000000000000000000000000000000000000100000000ffffffff00010000000000000000000000000000000000000000000000000000000000000200000000ffffffff0484030000000000000151d0070000000000000151540b0000000000000151c800000000000000015100024730440220699e6b0cfe015b64ca3283e6551440a34f901ba62dd4c72fe1cb815afb2e6761022021cc5e84db498b1479de14efda49093219441adc6c543e5534979605e273d80b032103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc710000000000", "P2SH,WITNESS"],
["Witness with SigHash Single (same signature as previous)"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x51", 1000],
["0000000000000000000000000000000000000000000000000000000000000100", 1, "0x00 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f", 2000],
["0000000000000000000000000000000000000000000000000000000000000100", 2, "0x51", 3000]],
"0100000000010300010000000000000000000000000000000000000000000000000000000000000000000000ffffffff00010000000000000000000000000000000000000000000000000000000000000100000000ffffffff00010000000000000000000000000000000000000000000000000000000000000200000000ffffffff03e8030000000000000151d0070000000000000151b80b000000000000015100024730440220699e6b0cfe015b64ca3283e6551440a34f901ba62dd4c72fe1cb815afb2e6761022021cc5e84db498b1479de14efda49093219441adc6c543e5534979605e273d80b032103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc710000000000", "P2SH,WITNESS"],
["Witness with SigHash None|AnyoneCanPay"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 2, "0x51", 3100],
["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x51", 1100],
["0000000000000000000000000000000000000000000000000000000000000100", 1, "0x00 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f", 2000],
["0000000000000000000000000000000000000000000000000000000000000100", 3, "0x51", 4100]],
"0100000000010400010000000000000000000000000000000000000000000000000000000000000200000000ffffffff00010000000000000000000000000000000000000000000000000000000000000000000000ffffffff00010000000000000000000000000000000000000000000000000000000000000100000000ffffffff00010000000000000000000000000000000000000000000000000000000000000300000000ffffffff04b60300000000000001519e070000000000000151860b00000000000001009600000000000000015100000248304502210091b32274295c2a3fa02f5bce92fb2789e3fc6ea947fbe1a76e52ea3f4ef2381a022079ad72aefa3837a2e0c033a8652a59731da05fa4a813f4fc48e87c075037256b822103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc710000000000", "P2SH,WITNESS"],
["Witness with SigHash None|AnyoneCanPay (same signature as previous)"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x51", 1000],
["0000000000000000000000000000000000000000000000000000000000000100", 1, "0x00 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f", 2000],
["0000000000000000000000000000000000000000000000000000000000000100", 2, "0x51", 3000]],
"0100000000010300010000000000000000000000000000000000000000000000000000000000000000000000ffffffff00010000000000000000000000000000000000000000000000000000000000000100000000ffffffff00010000000000000000000000000000000000000000000000000000000000000200000000ffffffff03e8030000000000000151d0070000000000000151b80b0000000000000151000248304502210091b32274295c2a3fa02f5bce92fb2789e3fc6ea947fbe1a76e52ea3f4ef2381a022079ad72aefa3837a2e0c033a8652a59731da05fa4a813f4fc48e87c075037256b822103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc710000000000", "P2SH,WITNESS"],
["Witness with SigHash None"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x51", 1000],
["0000000000000000000000000000000000000000000000000000000000000100", 1, "0x00 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f", 2000],
["0000000000000000000000000000000000000000000000000000000000000100", 2, "0x51", 3000]],
"0100000000010300010000000000000000000000000000000000000000000000000000000000000000000000ffffffff00010000000000000000000000000000000000000000000000000000000000000100000000ffffffff00010000000000000000000000000000000000000000000000000000000000000200000000ffffffff04b60300000000000001519e070000000000000151860b0000000000000100960000000000000001510002473044022022fceb54f62f8feea77faac7083c3b56c4676a78f93745adc8a35800bc36adfa022026927df9abcf0a8777829bcfcce3ff0a385fa54c3f9df577405e3ef24ee56479022103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc710000000000", "P2SH,WITNESS"],
["Witness with SigHash None (same signature as previous)"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x51", 1000],
["0000000000000000000000000000000000000000000000000000000000000100", 1, "0x00 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f", 2000],
["0000000000000000000000000000000000000000000000000000000000000100", 2, "0x51", 3000]],
"0100000000010300010000000000000000000000000000000000000000000000000000000000000000000000ffffffff00010000000000000000000000000000000000000000000000000000000000000100000000ffffffff00010000000000000000000000000000000000000000000000000000000000000200000000ffffffff03e8030000000000000151d0070000000000000151b80b00000000000001510002473044022022fceb54f62f8feea77faac7083c3b56c4676a78f93745adc8a35800bc36adfa022026927df9abcf0a8777829bcfcce3ff0a385fa54c3f9df577405e3ef24ee56479022103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc710000000000", "P2SH,WITNESS"],
["Witness with SigHash None (same signature, only sequences changed)"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x51", 1000],
["0000000000000000000000000000000000000000000000000000000000000100", 1, "0x00 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f", 2000],
["0000000000000000000000000000000000000000000000000000000000000100", 2, "0x51", 3000]],
"01000000000103000100000000000000000000000000000000000000000000000000000000000000000000000200000000010000000000000000000000000000000000000000000000000000000000000100000000ffffffff000100000000000000000000000000000000000000000000000000000000000002000000000200000003e8030000000000000151d0070000000000000151b80b00000000000001510002473044022022fceb54f62f8feea77faac7083c3b56c4676a78f93745adc8a35800bc36adfa022026927df9abcf0a8777829bcfcce3ff0a385fa54c3f9df577405e3ef24ee56479022103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc710000000000", "P2SH,WITNESS"],
["Witness with SigHash All|AnyoneCanPay"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 2, "0x51", 3100],
["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x51", 1100],
["0000000000000000000000000000000000000000000000000000000000000100", 1, "0x00 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f", 2000],
["0000000000000000000000000000000000000000000000000000000000000100", 3, "0x51", 4100]],
"0100000000010400010000000000000000000000000000000000000000000000000000000000000200000000ffffffff00010000000000000000000000000000000000000000000000000000000000000000000000ffffffff00010000000000000000000000000000000000000000000000000000000000000100000000ffffffff00010000000000000000000000000000000000000000000000000000000000000300000000ffffffff03e8030000000000000151d0070000000000000151b80b0000000000000151000002483045022100a3cec69b52cba2d2de623eeef89e0ba1606184ea55476c0f8189fda231bc9cbb022003181ad597f7c380a7d1c740286b1d022b8b04ded028b833282e055e03b8efef812103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc710000000000", "P2SH,WITNESS"],
["Witness with SigHash All|AnyoneCanPay (same signature as previous)"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x51", 1000],
["0000000000000000000000000000000000000000000000000000000000000100", 1, "0x00 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f", 2000],
["0000000000000000000000000000000000000000000000000000000000000100", 2, "0x51", 3000]],
"0100000000010300010000000000000000000000000000000000000000000000000000000000000000000000ffffffff00010000000000000000000000000000000000000000000000000000000000000100000000ffffffff00010000000000000000000000000000000000000000000000000000000000000200000000ffffffff03e8030000000000000151d0070000000000000151b80b00000000000001510002483045022100a3cec69b52cba2d2de623eeef89e0ba1606184ea55476c0f8189fda231bc9cbb022003181ad597f7c380a7d1c740286b1d022b8b04ded028b833282e055e03b8efef812103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc710000000000", "P2SH,WITNESS"],
["Unknown witness program version (without DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM)"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x51", 1000],
["0000000000000000000000000000000000000000000000000000000000000100", 1, "0x60 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f", 2000],
["0000000000000000000000000000000000000000000000000000000000000100", 2, "0x51", 3000]],
"0100000000010300010000000000000000000000000000000000000000000000000000000000000000000000ffffffff00010000000000000000000000000000000000000000000000000000000000000100000000ffffffff00010000000000000000000000000000000000000000000000000000000000000200000000ffffffff03e8030000000000000151d0070000000000000151b80b00000000000001510002483045022100a3cec69b52cba2d2de623ffffffffff1606184ea55476c0f8189fda231bc9cbb022003181ad597f7c380a7d1c740286b1d022b8b04ded028b833282e055e03b8efef812103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc710000000000", "P2SH,WITNESS"],
["Witness with a push of 520 bytes"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x00 0x20 0x33198a9bfef674ebddb9ffaa52928017b8472791e54c609cb95f278ac6b1e349", 1000]],
"0100000000010100010000000000000000000000000000000000000000000000000000000000000000000000ffffffff010000000000000000015102fd08020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002755100000000", "P2SH,WITNESS"],
["Transaction mixing all SigHash, segwit and normal inputs"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x00 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f", 1000],
["0000000000000000000000000000000000000000000000000000000000000100", 1, "0x00 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f", 1001],
["0000000000000000000000000000000000000000000000000000000000000100", 2, "DUP HASH160 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f EQUALVERIFY CHECKSIG", 1002],
["0000000000000000000000000000000000000000000000000000000000000100", 3, "DUP HASH160 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f EQUALVERIFY CHECKSIG", 1003],
["0000000000000000000000000000000000000000000000000000000000000100", 4, "DUP HASH160 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f EQUALVERIFY CHECKSIG", 1004],
["0000000000000000000000000000000000000000000000000000000000000100", 5, "DUP HASH160 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f EQUALVERIFY CHECKSIG", 1005],
["0000000000000000000000000000000000000000000000000000000000000100", 6, "DUP HASH160 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f EQUALVERIFY CHECKSIG", 1006],
["0000000000000000000000000000000000000000000000000000000000000100", 7, "0x00 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f", 1007],
["0000000000000000000000000000000000000000000000000000000000000100", 8, "0x00 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f", 1008],
["0000000000000000000000000000000000000000000000000000000000000100", 9, "0x00 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f", 1009],
["0000000000000000000000000000000000000000000000000000000000000100", 10, "0x00 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f", 1010],
["0000000000000000000000000000000000000000000000000000000000000100", 11, "DUP HASH160 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f EQUALVERIFY CHECKSIG", 1011]],
"0100000000010c00010000000000000000000000000000000000000000000000000000000000000000000000ffffffff00010000000000000000000000000000000000000000000000000000000000000100000000ffffffff0001000000000000000000000000000000000000000000000000000000000000020000006a473044022026c2e65b33fcd03b2a3b0f25030f0244bd23cc45ae4dec0f48ae62255b1998a00220463aa3982b718d593a6b9e0044513fd67a5009c2fdccc59992cffc2b167889f4012103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc71ffffffff0001000000000000000000000000000000000000000000000000000000000000030000006a4730440220008bd8382911218dcb4c9f2e75bf5c5c3635f2f2df49b36994fde85b0be21a1a02205a539ef10fb4c778b522c1be852352ea06c67ab74200977c722b0bc68972575a012103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc71ffffffff0001000000000000000000000000000000000000000000000000000000000000040000006b483045022100d9436c32ff065127d71e1a20e319e4fe0a103ba0272743dbd8580be4659ab5d302203fd62571ee1fe790b182d078ecfd092a509eac112bea558d122974ef9cc012c7012103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc71ffffffff0001000000000000000000000000000000000000000000000000000000000000050000006a47304402200e2c149b114ec546015c13b2b464bbcb0cdc5872e6775787527af6cbc4830b6c02207e9396c6979fb15a9a2b96ca08a633866eaf20dc0ff3c03e512c1d5a1654f148012103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc71ffffffff0001000000000000000000000000000000000000000000000000000000000000060000006b483045022100b20e70d897dc15420bccb5e0d3e208d27bdd676af109abbd3f88dbdb7721e6d6022005836e663173fbdfe069f54cde3c2decd3d0ea84378092a5d9d85ec8642e8a41012103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc71ffffffff00010000000000000000000000000000000000000000000000000000000000000700000000ffffffff00010000000000000000000000000000000000000000000000000000000000000800000000ffffffff00010000000000000000000000000000000000000000000000000000000000000900000000ffffffff00010000000000000000000000000000000000000000000000000000000000000a00000000ffffffff00010000000000000000000000000000000000000000000000000000000000000b0000006a47304402206639c6e05e3b9d2675a7f3876286bdf7584fe2bbd15e0ce52dd4e02c0092cdc60220757d60b0a61fc95ada79d23746744c72bac1545a75ff6c2c7cdb6ae04e7e9592012103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc71ffffffff0ce8030000000000000151e9030000000000000151ea030000000000000151eb030000000000000151ec030000000000000151ed030000000000000151ee030000000000000151ef030000000000000151f0030000000000000151f1030000000000000151f2030000000000000151f30300000000000001510248304502210082219a54f61bf126bfc3fa068c6e33831222d1d7138c6faa9d33ca87fd4202d6022063f9902519624254d7c2c8ea7ba2d66ae975e4e229ae38043973ec707d5d4a83012103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc7102473044022017fb58502475848c1b09f162cb1688d0920ff7f142bed0ef904da2ccc88b168f02201798afa61850c65e77889cbcd648a5703b487895517c88f85cdd18b021ee246a012103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc7100000000000247304402202830b7926e488da75782c81a54cd281720890d1af064629ebf2e31bf9f5435f30220089afaa8b455bbeb7d9b9c3fe1ed37d07685ade8455c76472cda424d93e4074a012103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc7102473044022026326fcdae9207b596c2b05921dbac11d81040c4d40378513670f19d9f4af893022034ecd7a282c0163b89aaa62c22ec202cef4736c58cd251649bad0d8139bcbf55012103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc71024730440220214978daeb2f38cd426ee6e2f44131a33d6b191af1c216247f1dd7d74c16d84a02205fdc05529b0bc0c430b4d5987264d9d075351c4f4484c16e91662e90a72aab24012103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc710247304402204a6e9f199dc9672cf2ff8094aaa784363be1eb62b679f7ff2df361124f1dca3302205eeb11f70fab5355c9c8ad1a0700ea355d315e334822fa182227e9815308ee8f012103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc710000000000", "P2SH,WITNESS"],
["Unknown version witness program with empty witness"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x60 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f", 1000]],
"010000000100010000000000000000000000000000000000000000000000000000000000000000000000ffffffff01e803000000000000015100000000", "P2SH,WITNESS"],
["Witness SIGHASH_SINGLE with output out of bound"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x51", 1000],
["0000000000000000000000000000000000000000000000000000000000000100", 1, "0x00 0x20 0x4d6c2a32c87821d68fc016fca70797abdb80df6cd84651d40a9300c6bad79e62", 1000]],
"0100000000010200010000000000000000000000000000000000000000000000000000000000000000000000ffffffff00010000000000000000000000000000000000000000000000000000000000000100000000ffffffff01d00700000000000001510003483045022100e078de4e96a0e05dcdc0a414124dd8475782b5f3f0ed3f607919e9a5eeeb22bf02201de309b3a3109adb3de8074b3610d4cf454c49b61247a2779a0bcbf31c889333032103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc711976a9144c9c3dfac4207d5d8cb89df5722cb3d712385e3f88ac00000000", "P2SH,WITNESS"],
["1 byte push should not be considered a witness scriptPubKey"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x60 0x01 0x01", 1000]],
"010000000100010000000000000000000000000000000000000000000000000000000000000000000000ffffffff01e803000000000000015100000000", "P2SH,WITNESS,DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM"],
["41 bytes push should not be considered a witness scriptPubKey"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x60 0x29 0xff25429251b5a84f452230a3c75fd886b7fc5a7865ce4a7bb7a9d7c5be6da3dbff0000000000000000", 1000]],
"010000000100010000000000000000000000000000000000000000000000000000000000000000000000ffffffff01e803000000000000015100000000", "P2SH,WITNESS,DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM"],
["The witness version must use OP_1 to OP_16 only"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x01 0x10 0x02 0x0001", 1000]],
"010000000100010000000000000000000000000000000000000000000000000000000000000000000000ffffffff01e803000000000000015100000000", "P2SH,WITNESS,DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM"],
["The witness program push must be canonical"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x60 0x4c02 0x0001", 1000]],
"010000000100010000000000000000000000000000000000000000000000000000000000000000000000ffffffff01e803000000000000015100000000", "P2SH,WITNESS,DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM"],
["Witness Single|AnyoneCanPay does not hash input's position"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x00 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f", 1000],
["0000000000000000000000000000000000000000000000000000000000000100", 1, "0x00 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f", 1001]],
"0100000000010200010000000000000000000000000000000000000000000000000000000000000000000000ffffffff00010000000000000000000000000000000000000000000000000000000000000100000000ffffffff02e8030000000000000151e90300000000000001510247304402206d59682663faab5e4cb733c562e22cdae59294895929ec38d7c016621ff90da0022063ef0af5f970afe8a45ea836e3509b8847ed39463253106ac17d19c437d3d56b832103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc710248304502210085001a820bfcbc9f9de0298af714493f8a37b3b354bfd21a7097c3e009f2018c022050a8b4dbc8155d4d04da2f5cdd575dcf8dd0108de8bec759bd897ea01ecb3af7832103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc7100000000", "P2SH,WITNESS"],
["Witness Single|AnyoneCanPay does not hash input's position (permutation)"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 1, "0x00 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f", 1001],
["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x00 0x14 0x4c9c3dfac4207d5d8cb89df5722cb3d712385e3f", 1000]],
"0100000000010200010000000000000000000000000000000000000000000000000000000000000100000000ffffffff00010000000000000000000000000000000000000000000000000000000000000000000000ffffffff02e9030000000000000151e80300000000000001510248304502210085001a820bfcbc9f9de0298af714493f8a37b3b354bfd21a7097c3e009f2018c022050a8b4dbc8155d4d04da2f5cdd575dcf8dd0108de8bec759bd897ea01ecb3af7832103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc710247304402206d59682663faab5e4cb733c562e22cdae59294895929ec38d7c016621ff90da0022063ef0af5f970afe8a45ea836e3509b8847ed39463253106ac17d19c437d3d56b832103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc7100000000", "P2SH,WITNESS"],
["Non witness Single|AnyoneCanPay hash input's position"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "0x21 0x03596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc71 CHECKSIG", 1000],
["0000000000000000000000000000000000000000000000000000000000000100", 1, "0x21 0x03596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc71 CHECKSIG", 1001]],
"01000000020001000000000000000000000000000000000000000000000000000000000000000000004847304402202a0b4b1294d70540235ae033d78e64b4897ec859c7b6f1b2b1d8a02e1d46006702201445e756d2254b0f1dfda9ab8e1e1bc26df9668077403204f32d16a49a36eb6983ffffffff00010000000000000000000000000000000000000000000000000000000000000100000049483045022100acb96cfdbda6dc94b489fd06f2d720983b5f350e31ba906cdbd800773e80b21c02200d74ea5bdf114212b4bbe9ed82c36d2e369e302dff57cb60d01c428f0bd3daab83ffffffff02e8030000000000000151e903000000000000015100000000", "P2SH,WITNESS"],
["BIP143 examples: details and private keys are available in BIP143"],
["BIP143 example: P2WSH with OP_CODESEPARATOR and out-of-range SIGHASH_SINGLE."],
[[["6eb316926b1c5d567cd6f5e6a84fec606fc53d7b474526d1fff3948020c93dfe", 0, "0x21 0x036d5c20fa14fb2f635474c1dc4ef5909d4568e5569b79fc94d3448486e14685f8 CHECKSIG", 156250000],
["f825690aee1b3dc247da796cacb12687a5e802429fd291cfd63e010f02cf1508", 0, "0x00 0x20 0x5d1b56b63d714eebe542309525f484b7e9d6f686b3781b6f61ef925d66d6f6a0", 4900000000]],
"01000000000102fe3dc9208094f3ffd12645477b3dc56f60ec4fa8e6f5d67c565d1c6b9216b36e000000004847304402200af4e47c9b9629dbecc21f73af989bdaa911f7e6f6c2e9394588a3aa68f81e9902204f3fcf6ade7e5abb1295b6774c8e0abd94ae62217367096bc02ee5e435b67da201ffffffff0815cf020f013ed6cf91d29f4202e8a58726b1ac6c79da47c23d1bee0a6925f80000000000ffffffff0100f2052a010000001976a914a30741f8145e5acadf23f751864167f32e0963f788ac000347304402200de66acf4527789bfda55fc5459e214fa6083f936b430a762c629656216805ac0220396f550692cd347171cbc1ef1f51e15282e837bb2b30860dc77c8f78bc8501e503473044022027dc95ad6b740fe5129e7e62a75dd00f291a2aeb1200b84b09d9e3789406b6c002201a9ecd315dd6a0e632ab20bbb98948bc0c6fb204f2c286963bb48517a7058e27034721026dccc749adc2a9d0d89497ac511f760f45c47dc5ed9cf352a58ac706453880aeadab210255a9626aebf5e29c0e6538428ba0d1dcf6ca98ffdf086aa8ced5e0d0215ea465ac00000000", "P2SH,WITNESS"],
["BIP143 example: P2WSH with unexecuted OP_CODESEPARATOR and SINGLE|ANYONECANPAY"],
[[["01c0cf7fba650638e55eb91261b183251fbb466f90dff17f10086817c542b5e9", 0, "0x00 0x20 0xba468eea561b26301e4cf69fa34bde4ad60c81e70f059f045ca9a79931004a4d", 16777215],
["1b2a9a426ba603ba357ce7773cb5805cb9c7c2b386d100d1fc9263513188e680", 0, "0x00 0x20 0xd9bbfbe56af7c4b7f960a70d7ea107156913d9e5a26b0a71429df5e097ca6537", 16777215]],
"01000000000102e9b542c5176808107ff1df906f46bb1f2583b16112b95ee5380665ba7fcfc0010000000000ffffffff80e68831516392fcd100d186b3c2c7b95c80b53c77e77c35ba03a66b429a2a1b0000000000ffffffff0280969800000000001976a914de4b231626ef508c9a74a8517e6783c0546d6b2888ac80969800000000001976a9146648a8cd4531e1ec47f35916de8e259237294d1e88ac02483045022100f6a10b8604e6dc910194b79ccfc93e1bc0ec7c03453caaa8987f7d6c3413566002206216229ede9b4d6ec2d325be245c5b508ff0339bf1794078e20bfe0babc7ffe683270063ab68210392972e2eb617b2388771abe27235fd5ac44af8e61693261550447a4c3e39da98ac024730440220032521802a76ad7bf74d0e2c218b72cf0cbc867066e2e53db905ba37f130397e02207709e2188ed7f08f4c952d9d13986da504502b8c3be59617e043552f506c46ff83275163ab68210392972e2eb617b2388771abe27235fd5ac44af8e61693261550447a4c3e39da98ac00000000", "P2SH,WITNESS"],
["BIP143 example: Same as the previous example with input-output pairs swapped"],
[[["1b2a9a426ba603ba357ce7773cb5805cb9c7c2b386d100d1fc9263513188e680", 0, "0x00 0x20 0xd9bbfbe56af7c4b7f960a70d7ea107156913d9e5a26b0a71429df5e097ca6537", 16777215],
["01c0cf7fba650638e55eb91261b183251fbb466f90dff17f10086817c542b5e9", 0, "0x00 0x20 0xba468eea561b26301e4cf69fa34bde4ad60c81e70f059f045ca9a79931004a4d", 16777215]],
"0100000000010280e68831516392fcd100d186b3c2c7b95c80b53c77e77c35ba03a66b429a2a1b0000000000ffffffffe9b542c5176808107ff1df906f46bb1f2583b16112b95ee5380665ba7fcfc0010000000000ffffffff0280969800000000001976a9146648a8cd4531e1ec47f35916de8e259237294d1e88ac80969800000000001976a914de4b231626ef508c9a74a8517e6783c0546d6b2888ac024730440220032521802a76ad7bf74d0e2c218b72cf0cbc867066e2e53db905ba37f130397e02207709e2188ed7f08f4c952d9d13986da504502b8c3be59617e043552f506c46ff83275163ab68210392972e2eb617b2388771abe27235fd5ac44af8e61693261550447a4c3e39da98ac02483045022100f6a10b8604e6dc910194b79ccfc93e1bc0ec7c03453caaa8987f7d6c3413566002206216229ede9b4d6ec2d325be245c5b508ff0339bf1794078e20bfe0babc7ffe683270063ab68210392972e2eb617b2388771abe27235fd5ac44af8e61693261550447a4c3e39da98ac00000000", "P2SH,WITNESS"],
["BIP143 example: P2SH-P2WSH 6-of-6 multisig signed with 6 different SIGHASH types"],
[[["6eb98797a21c6c10aa74edf29d618be109f48a8e94c694f3701e08ca69186436", 1, "HASH160 0x14 0x9993a429037b5d912407a71c252019287b8d27a5 EQUAL", 987654321]],
"0100000000010136641869ca081e70f394c6948e8af409e18b619df2ed74aa106c1ca29787b96e0100000023220020a16b5755f7f6f96dbd65f5f0d6ab9418b89af4b1f14a1bb8a09062c35f0dcb54ffffffff0200e9a435000000001976a914389ffce9cd9ae88dcc0631e88a821ffdbe9bfe2688acc0832f05000000001976a9147480a33f950689af511e6e84c138dbbd3c3ee41588ac080047304402206ac44d672dac41f9b00e28f4df20c52eeb087207e8d758d76d92c6fab3b73e2b0220367750dbbe19290069cba53d096f44530e4f98acaa594810388cf7409a1870ce01473044022068c7946a43232757cbdf9176f009a928e1cd9a1a8c212f15c1e11ac9f2925d9002205b75f937ff2f9f3c1246e547e54f62e027f64eefa2695578cc6432cdabce271502473044022059ebf56d98010a932cf8ecfec54c48e6139ed6adb0728c09cbe1e4fa0915302e022007cd986c8fa870ff5d2b3a89139c9fe7e499259875357e20fcbb15571c76795403483045022100fbefd94bd0a488d50b79102b5dad4ab6ced30c4069f1eaa69a4b5a763414067e02203156c6a5c9cf88f91265f5a942e96213afae16d83321c8b31bb342142a14d16381483045022100a5263ea0553ba89221984bd7f0b13613db16e7a70c549a86de0cc0444141a407022005c360ef0ae5a5d4f9f2f87a56c1546cc8268cab08c73501d6b3be2e1e1a8a08824730440220525406a1482936d5a21888260dc165497a90a15669636d8edca6b9fe490d309c022032af0c646a34a44d1f4576bf6a4a74b67940f8faa84c7df9abe12a01a11e2b4783cf56210307b8ae49ac90a048e9b53357a2354b3334e9c8bee813ecb98e99a7e07e8c3ba32103b28f0c28bfab54554ae8c658ac5c3e0ce6e79ad336331f78c428dd43eea8449b21034b8113d703413d57761b8b9781957b8c0ac1dfe69f492580ca4195f50376ba4a21033400f6afecb833092a9a21cfdf1ed1376e58c5d1f47de74683123987e967a8f42103a6d48b1131e94ba04d9737d61acdaa1322008af9602b3b14862c07a1789aac162102d8b661b0b3302ee2f162b09e07a55ad5dfbe673a9f01d9f0c19617681024306b56ae00000000", "P2SH,WITNESS"],
["FindAndDelete tests"],
["This is a test of FindAndDelete. The first tx is a spend of normal P2SH and the second tx is a spend of bare P2WSH."],
["The redeemScript/witnessScript is CHECKSIGVERIFY <0x30450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e01>."],
["The signature is <0x30450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e01> <pubkey>,"],
["where the pubkey is obtained through key recovery with sig and correct sighash."],
["This is to show that FindAndDelete is applied only to non-segwit scripts"],
["Non-segwit: correct sighash (with FindAndDelete) = 1ba1fe3bc90c5d1265460e684ce6774e324f0fabdf67619eda729e64e8b6bc08"],
[[["f18783ace138abac5d3a7a5cf08e88fe6912f267ef936452e0c27d090621c169", 7000, "HASH160 0x14 0x0c746489e2d83cdbb5b90b432773342ba809c134 EQUAL", 200000]],
"010000000169c12106097dc2e0526493ef67f21269fe888ef05c7a3a5dacab38e1ac8387f1581b0000b64830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e0121037a3fb04bcdb09eba90f69961ba1692a3528e45e67c85b200df820212d7594d334aad4830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e01ffffffff0101000000000000000000000000", "P2SH,WITNESS"],
["BIP143: correct sighash (without FindAndDelete) = 71c9cd9b2869b9c70b01b1f0360c148f42dee72297db312638df136f43311f23"],
[[["f18783ace138abac5d3a7a5cf08e88fe6912f267ef936452e0c27d090621c169", 7500, "0x00 0x20 0x9e1be07558ea5cc8e02ed1d80c0911048afad949affa36d5c3951e3159dbea19", 200000]],
"0100000000010169c12106097dc2e0526493ef67f21269fe888ef05c7a3a5dacab38e1ac8387f14c1d000000ffffffff01010000000000000000034830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e012102a9781d66b61fb5a7ef00ac5ad5bc6ffc78be7b44a566e3c87870e1079368df4c4aad4830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e0100000000", "P2SH,WITNESS"],
["This is multisig version of the FindAndDelete tests"],
["Script is 2 CHECKMULTISIGVERIFY <sig1> <sig2> DROP"],
["52af4830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e0148304502205286f726690b2e9b0207f0345711e63fa7012045b9eb0f19c2458ce1db90cf43022100e89f17f86abc5b149eba4115d4f128bcf45d77fb3ecdd34f594091340c0395960175"],
["Signature is 0 <sig1> <sig2> 2 <key1> <key2>"],
["Non-segwit: correct sighash (with FindAndDelete) = 1d50f00ba4db2917b903b0ec5002e017343bb38876398c9510570f5dce099295"],
[[["9628667ad48219a169b41b020800162287d2c0f713c04157e95c484a8dcb7592", 7000, "HASH160 0x14 0x5748407f5ca5cdca53ba30b79040260770c9ee1b EQUAL", 200000]],
"01000000019275cb8d4a485ce95741c013f7c0d28722160008021bb469a11982d47a662896581b0000fd6f01004830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e0148304502205286f726690b2e9b0207f0345711e63fa7012045b9eb0f19c2458ce1db90cf43022100e89f17f86abc5b149eba4115d4f128bcf45d77fb3ecdd34f594091340c03959601522102cd74a2809ffeeed0092bc124fd79836706e41f048db3f6ae9df8708cefb83a1c2102e615999372426e46fd107b76eaf007156a507584aa2cc21de9eee3bdbd26d36c4c9552af4830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e0148304502205286f726690b2e9b0207f0345711e63fa7012045b9eb0f19c2458ce1db90cf43022100e89f17f86abc5b149eba4115d4f128bcf45d77fb3ecdd34f594091340c0395960175ffffffff0101000000000000000000000000", "P2SH,WITNESS"],
["BIP143: correct sighash (without FindAndDelete) = c1628a1e7c67f14ca0c27c06e4fdeec2e6d1a73c7a91d7c046ff83e835aebb72"],
[[["9628667ad48219a169b41b020800162287d2c0f713c04157e95c484a8dcb7592", 7500, "0x00 0x20 0x9b66c15b4e0b4eb49fa877982cafded24859fe5b0e2dbfbe4f0df1de7743fd52", 200000]],
"010000000001019275cb8d4a485ce95741c013f7c0d28722160008021bb469a11982d47a6628964c1d000000ffffffff0101000000000000000007004830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e0148304502205286f726690b2e9b0207f0345711e63fa7012045b9eb0f19c2458ce1db90cf43022100e89f17f86abc5b149eba4115d4f128bcf45d77fb3ecdd34f594091340c0395960101022102966f109c54e85d3aee8321301136cedeb9fc710fdef58a9de8a73942f8e567c021034ffc99dd9a79dd3cb31e2ab3e0b09e0e67db41ac068c625cd1f491576016c84e9552af4830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e0148304502205286f726690b2e9b0207f0345711e63fa7012045b9eb0f19c2458ce1db90cf43022100e89f17f86abc5b149eba4115d4f128bcf45d77fb3ecdd34f594091340c039596017500000000", "P2SH,WITNESS"],
["Make diffs cleaner by leaving a comment here without comma at the end"]
]

View File

@ -5,8 +5,6 @@
package txscript
import (
"bytes"
"crypto/sha256"
"fmt"
"math/big"
@ -48,8 +46,7 @@ const (
// ScriptVerifyCleanStack defines that the stack must contain only
// one stack element after evaluation and that the element must be
// true if interpreted as a boolean. This is rule 6 of BIP0062.
// This flag should never be used without the ScriptBip16 flag nor the
// ScriptVerifyWitness flag.
// This flag should never be used without the ScriptBip16 flag.
ScriptVerifyCleanStack
// ScriptVerifyDERSignatures defines that signatures are required
@ -76,23 +73,6 @@ const (
// ScriptVerifyStrictEncoding defines that signature scripts and
// public keys must follow the strict encoding requirements.
ScriptVerifyStrictEncoding
// ScriptVerifyWitness defines whether or not to verify a transaction
// output using a witness program template.
ScriptVerifyWitness
// ScriptVerifyDiscourageUpgradeableWitnessProgram makes witness
// program with versions 2-16 non-standard.
ScriptVerifyDiscourageUpgradeableWitnessProgram
// ScriptVerifyMinimalIf makes a script with an OP_IF/OP_NOTIF whose
// operand is anything other than empty vector or [0x01] non-standard.
ScriptVerifyMinimalIf
// ScriptVerifyWitnessPubKeyType makes a script within a check-sig
// operation whose public key isn't serialized in a compressed format
// non-standard.
ScriptVerifyWitnessPubKeyType
)
const (
@ -102,14 +82,6 @@ const (
// MaxScriptSize is the maximum allowed length of a raw script.
MaxScriptSize = 10000
// payToWitnessPubKeyHashDataSize is the size of the witness program's
// data push for a pay-to-witness-pub-key-hash output.
payToWitnessPubKeyHashDataSize = 20
// payToWitnessScriptHashDataSize is the size of the witness program's
// data push for a pay-to-witness-script-hash output.
payToWitnessScriptHashDataSize = 32
)
// halforder is used to tame ECDSA malleability (see BIP0062).
@ -129,12 +101,8 @@ type Engine struct {
numOps int
flags ScriptFlags
sigCache *SigCache
hashCache *TxSigHashes
bip16 bool // treat execution as pay-to-script-hash
savedFirstStack [][]byte // stack from first script for bip16 scripts
witnessVersion int
witnessProgram []byte
inputAmount int64
}
// hasFlag returns whether the script engine instance has the passed flag set.
@ -241,122 +209,6 @@ func (vm *Engine) curPC() (script int, off int, err error) {
return vm.scriptIdx, vm.scriptOff, nil
}
// isWitnessVersionActive returns true if a witness program was extracted
// during the initialization of the Engine, and the program's version matches
// the specified version.
func (vm *Engine) isWitnessVersionActive(version uint) bool {
return vm.witnessProgram != nil && uint(vm.witnessVersion) == version
}
// verifyWitnessProgram validates the stored witness program using the passed
// witness as input.
func (vm *Engine) verifyWitnessProgram(witness [][]byte) error {
if vm.isWitnessVersionActive(0) {
switch len(vm.witnessProgram) {
case payToWitnessPubKeyHashDataSize: // P2WKH
// The witness stack should consist of exactly two
// items: the signature, and the pubkey.
if len(witness) != 2 {
err := fmt.Sprintf("should have exactly two "+
"items in witness, instead have %v", len(witness))
return scriptError(ErrWitnessProgramMismatch, err)
}
// Now we'll resume execution as if it were a regular
// p2pkh transaction.
pkScript, err := payToPubKeyHashScript(vm.witnessProgram)
if err != nil {
return err
}
pops, err := parseScript(pkScript)
if err != nil {
return err
}
// Set the stack to the provided witness stack, then
// append the pkScript generated above as the next
// script to execute.
vm.scripts = append(vm.scripts, pops)
vm.SetStack(witness)
case payToWitnessScriptHashDataSize: // P2WSH
// Additionally, The witness stack MUST NOT be empty at
// this point.
if len(witness) == 0 {
return scriptError(ErrWitnessProgramEmpty, "witness "+
"program empty passed empty witness")
}
// Obtain the witness script which should be the last
// element in the passed stack. The size of the script
// MUST NOT exceed the max script size.
witnessScript := witness[len(witness)-1]
if len(witnessScript) > MaxScriptSize {
str := fmt.Sprintf("witnessScript size %d "+
"is larger than max allowed size %d",
len(witnessScript), MaxScriptSize)
return scriptError(ErrScriptTooBig, str)
}
// Ensure that the serialized pkScript at the end of
// the witness stack matches the witness program.
witnessHash := sha256.Sum256(witnessScript)
if !bytes.Equal(witnessHash[:], vm.witnessProgram) {
return scriptError(ErrWitnessProgramMismatch,
"witness program hash mismatch")
}
// With all the validity checks passed, parse the
// script into individual op-codes so w can execute it
// as the next script.
pops, err := parseScript(witnessScript)
if err != nil {
return err
}
// The hash matched successfully, so use the witness as
// the stack, and set the witnessScript to be the next
// script executed.
vm.scripts = append(vm.scripts, pops)
vm.SetStack(witness[:len(witness)-1])
default:
errStr := fmt.Sprintf("length of witness program "+
"must either be %v or %v bytes, instead is %v bytes",
payToWitnessPubKeyHashDataSize,
payToWitnessScriptHashDataSize,
len(vm.witnessProgram))
return scriptError(ErrWitnessProgramWrongLength, errStr)
}
} else if vm.hasFlag(ScriptVerifyDiscourageUpgradeableWitnessProgram) {
errStr := fmt.Sprintf("new witness program versions "+
"invalid: %v", vm.witnessProgram)
return scriptError(ErrDiscourageUpgradableWitnessProgram, errStr)
} else {
// If we encounter an unknown witness program version and we
// aren't discouraging future unknown witness based soft-forks,
// then we de-activate the segwit behavior within the VM for
// the remainder of execution.
vm.witnessProgram = nil
}
if vm.isWitnessVersionActive(0) {
// All elements within the witness stack must not be greater
// than the maximum bytes which are allowed to be pushed onto
// the stack.
for _, witElement := range vm.GetStack() {
if len(witElement) > MaxScriptElementSize {
str := fmt.Sprintf("element size %d exceeds "+
"max allowed size %d", len(witElement),
MaxScriptElementSize)
return scriptError(ErrElementTooBig, str)
}
}
}
return nil
}
// DisasmPC returns the string for the disassembly of the opcode that will be
// next to execute when Step() is called.
func (vm *Engine) DisasmPC() (string, error) {
@ -395,14 +247,6 @@ func (vm *Engine) CheckErrorCondition(finalScript bool) error {
"error check when script unfinished")
}
// If we're in version zero witness execution mode, and this was the
// final script, then the stack MUST be clean in order to maintain
// compatibility with BIP16.
if finalScript && vm.isWitnessVersionActive(0) && vm.dstack.Depth() != 1 {
return scriptError(ErrEvalFalse, "witness program must "+
"have clean stack")
}
if finalScript && vm.hasFlag(ScriptVerifyCleanStack) &&
vm.dstack.Depth() != 1 {
@ -500,15 +344,6 @@ func (vm *Engine) Step() (done bool, err error) {
// Set stack to be the stack from first script minus the
// script itself
vm.SetStack(vm.savedFirstStack[:len(vm.savedFirstStack)-1])
} else if (vm.scriptIdx == 1 && vm.witnessProgram != nil) ||
(vm.scriptIdx == 2 && vm.witnessProgram != nil && vm.bip16) { // Nested P2SH.
vm.scriptIdx++
witness := vm.tx.TxIn[vm.txIdx].Witness
if err := vm.verifyWitnessProgram(witness); err != nil {
return false, err
}
} else {
vm.scriptIdx++
}
@ -582,13 +417,6 @@ func (vm *Engine) checkHashTypeEncoding(hashType SigHashType) error {
// checkPubKeyEncoding returns whether or not the passed public key adheres to
// the strict encoding requirements if enabled.
func (vm *Engine) checkPubKeyEncoding(pubKey []byte) error {
if vm.hasFlag(ScriptVerifyWitnessPubKeyType) &&
vm.isWitnessVersionActive(0) && !btcec.IsCompressedPubKey(pubKey) {
str := "only uncompressed keys are accepted post-segwit"
return scriptError(ErrWitnessPubKeyType, str)
}
if !vm.hasFlag(ScriptVerifyStrictEncoding) {
return nil
}
@ -801,7 +629,7 @@ func (vm *Engine) SetAltStack(data [][]byte) {
// transaction, and input index. The flags modify the behavior of the script
// engine according to the description provided by each flag.
func NewEngine(scriptPubKey []byte, tx *wire.MsgTx, txIdx int, flags ScriptFlags,
sigCache *SigCache, hashCache *TxSigHashes, inputAmount int64) (*Engine, error) {
sigCache *SigCache) (*Engine, error) {
// The provided transaction input index must refer to a valid input.
if txIdx < 0 || txIdx >= len(tx.TxIn) {
@ -821,19 +649,15 @@ func NewEngine(scriptPubKey []byte, tx *wire.MsgTx, txIdx int, flags ScriptFlags
}
// The clean stack flag (ScriptVerifyCleanStack) is not allowed without
// either the pay-to-script-hash (P2SH) evaluation (ScriptBip16)
// flag or the Segregated Witness (ScriptVerifyWitness) flag.
// the pay-to-script-hash (P2SH) evaluation (ScriptBip16) flag.
//
// Recall that evaluating a P2SH script without the flag set results in
// non-P2SH evaluation which leaves the P2SH inputs on the stack.
// Thus, allowing the clean stack flag without the P2SH flag would make
// it possible to have a situation where P2SH would not be a soft fork
// when it should be. The same goes for segwit which will pull in
// additional scripts for execution from the witness stack.
vm := Engine{flags: flags, sigCache: sigCache, hashCache: hashCache,
inputAmount: inputAmount}
if vm.hasFlag(ScriptVerifyCleanStack) && (!vm.hasFlag(ScriptBip16) &&
!vm.hasFlag(ScriptVerifyWitness)) {
// non-P2SH evaluation which leaves the P2SH inputs on the stack. Thus,
// allowing the clean stack flag without the P2SH flag would make it
// possible to have a situation where P2SH would not be a soft fork when
// it should be.
vm := Engine{flags: flags, sigCache: sigCache}
if vm.hasFlag(ScriptVerifyCleanStack) && !vm.hasFlag(ScriptBip16) {
return nil, scriptError(ErrInvalidFlags,
"invalid flags combination")
}
@ -884,67 +708,6 @@ func NewEngine(scriptPubKey []byte, tx *wire.MsgTx, txIdx int, flags ScriptFlags
vm.astack.verifyMinimalData = true
}
// Check to see if we should execute in witness verification mode
// according to the set flags. We check both the pkScript, and sigScript
// here since in the case of nested p2sh, the scriptSig will be a valid
// witness program. For nested p2sh, all the bytes after the first data
// push should *exactly* match the witness program template.
if vm.hasFlag(ScriptVerifyWitness) {
// If witness evaluation is enabled, then P2SH MUST also be
// active.
if !vm.hasFlag(ScriptBip16) {
errStr := "P2SH must be enabled to do witness verification"
return nil, scriptError(ErrInvalidFlags, errStr)
}
var witProgram []byte
switch {
case isWitnessProgram(vm.scripts[1]):
// The scriptSig must be *empty* for all native witness
// programs, otherwise we introduce malleability.
if len(scriptSig) != 0 {
errStr := "native witness program cannot " +
"also have a signature script"
return nil, scriptError(ErrWitnessMalleated, errStr)
}
witProgram = scriptPubKey
case len(tx.TxIn[txIdx].Witness) != 0 && vm.bip16:
// The sigScript MUST be *exactly* a single canonical
// data push of the witness program, otherwise we
// reintroduce malleability.
sigPops := vm.scripts[0]
if len(sigPops) == 1 && canonicalPush(sigPops[0]) &&
IsWitnessProgram(sigPops[0].data) {
witProgram = sigPops[0].data
} else {
errStr := "signature script for witness " +
"nested p2sh is not canonical"
return nil, scriptError(ErrWitnessMalleatedP2SH, errStr)
}
}
if witProgram != nil {
var err error
vm.witnessVersion, vm.witnessProgram, err = ExtractWitnessProgramInfo(witProgram)
if err != nil {
return nil, err
}
} else {
// If we didn't find a witness program in either the
// pkScript or as a datapush within the sigScript, then
// there MUST NOT be any witness data associated with
// the input being validated.
if vm.witnessProgram == nil && len(tx.TxIn[txIdx].Witness) != 0 {
errStr := "non-witness inputs cannot have a witness"
return nil, scriptError(ErrWitnessUnexpected, errStr)
}
}
}
vm.tx = *tx
vm.txIdx = txIdx

View File

@ -54,7 +54,7 @@ func TestBadPC(t *testing.T) {
pkScript := mustParseShortForm("NOP")
for _, test := range tests {
vm, err := NewEngine(pkScript, tx, 0, 0, nil, nil, -1)
vm, err := NewEngine(pkScript, tx, 0, 0, nil)
if err != nil {
t.Errorf("Failed to create script: %v", err)
}
@ -111,7 +111,7 @@ func TestCheckErrorCondition(t *testing.T) {
pkScript := mustParseShortForm("NOP NOP NOP NOP NOP NOP NOP NOP NOP" +
" NOP TRUE")
vm, err := NewEngine(pkScript, tx, 0, 0, nil, nil, 0)
vm, err := NewEngine(pkScript, tx, 0, 0, nil)
if err != nil {
t.Errorf("failed to create script: %v", err)
}
@ -187,7 +187,7 @@ func TestInvalidFlagCombinations(t *testing.T) {
pkScript := []byte{OP_NOP}
for i, test := range tests {
_, err := NewEngine(pkScript, tx, 0, test, nil, nil, -1)
_, err := NewEngine(pkScript, tx, 0, test, nil)
if !IsErrorCode(err, ErrInvalidFlags) {
t.Fatalf("TestInvalidFlagCombinations #%d unexpected "+
"error: %v", i, err)

View File

@ -209,15 +209,6 @@ const (
// operations.
ErrNullFail
// ErrWitnessMalleated is returned if ScriptVerifyWitness is set and a
// native p2wsh program is encountered which has a non-empty sigScript.
ErrWitnessMalleated
// ErrWitnessMalleatedP2SH is returned if ScriptVerifyWitness if set
// and the validation logic for nested p2sh encounters a sigScript
// which isn't *exactyl* a datapush of the witness program.
ErrWitnessMalleatedP2SH
// -------------------------------
// Failures related to soft forks.
// -------------------------------
@ -236,46 +227,6 @@ const (
// reached.
ErrUnsatisfiedLockTime
// ErrMinimalIf is returned if ScriptVerifyWitness is set and the
// operand of an OP_IF/OP_NOF_IF are not either an empty vector or
// [0x01].
ErrMinimalIf
// ErrDiscourageUpgradableWitnessProgram is returned if
// ScriptVerifyWitness is set and the versino of an executing witness
// program is outside the set of currently defined witness program
// vesions.
ErrDiscourageUpgradableWitnessProgram
// ----------------------------------------
// Failures related to segregated witness.
// ----------------------------------------
// ErrWitnessProgramEmpty is returned if ScriptVerifyWitness is set and
// the witness stack itself is empty.
ErrWitnessProgramEmpty
// ErrWitnessProgramMismatch is returned if ScriptVerifyWitness is set
// and the witness itself for a p2wkh witness program isn't *exactly* 2
// items or if the witness for a p2wsh isn't the sha255 of the witness
// script.
ErrWitnessProgramMismatch
// ErrWitnessProgramWrongLength is returned if ScriptVerifyWitness is
// set and the length of the witness program violates the length as
// dictated by the current witness version.
ErrWitnessProgramWrongLength
// ErrWitnessUnexpected is returned if ScriptVerifyWitness is set and a
// transaction includes witness data but doesn't spend an which is a
// witness program (nested or native).
ErrWitnessUnexpected
// ErrWitnessPubKeyType is returned if ScriptVerifyWitness is set and
// the public key used in either a check-sig or check-multi-sig isn't
// serialized in a compressed format.
ErrWitnessPubKeyType
// numErrorCodes is the maximum error code number used in tests. This
// entry MUST be the last entry in the enum.
numErrorCodes
@ -283,56 +234,47 @@ const (
// Map of ErrorCode values back to their constant names for pretty printing.
var errorCodeStrings = map[ErrorCode]string{
ErrInternal: "ErrInternal",
ErrInvalidFlags: "ErrInvalidFlags",
ErrInvalidIndex: "ErrInvalidIndex",
ErrUnsupportedAddress: "ErrUnsupportedAddress",
ErrNotMultisigScript: "ErrNotMultisigScript",
ErrTooManyRequiredSigs: "ErrTooManyRequiredSigs",
ErrTooMuchNullData: "ErrTooMuchNullData",
ErrEarlyReturn: "ErrEarlyReturn",
ErrEmptyStack: "ErrEmptyStack",
ErrEvalFalse: "ErrEvalFalse",
ErrScriptUnfinished: "ErrScriptUnfinished",
ErrInvalidProgramCounter: "ErrInvalidProgramCounter",
ErrScriptTooBig: "ErrScriptTooBig",
ErrElementTooBig: "ErrElementTooBig",
ErrTooManyOperations: "ErrTooManyOperations",
ErrStackOverflow: "ErrStackOverflow",
ErrInvalidPubKeyCount: "ErrInvalidPubKeyCount",
ErrInvalidSignatureCount: "ErrInvalidSignatureCount",
ErrNumberTooBig: "ErrNumberTooBig",
ErrVerify: "ErrVerify",
ErrEqualVerify: "ErrEqualVerify",
ErrNumEqualVerify: "ErrNumEqualVerify",
ErrCheckSigVerify: "ErrCheckSigVerify",
ErrCheckMultiSigVerify: "ErrCheckMultiSigVerify",
ErrDisabledOpcode: "ErrDisabledOpcode",
ErrReservedOpcode: "ErrReservedOpcode",
ErrMalformedPush: "ErrMalformedPush",
ErrInvalidStackOperation: "ErrInvalidStackOperation",
ErrUnbalancedConditional: "ErrUnbalancedConditional",
ErrMinimalData: "ErrMinimalData",
ErrInvalidSigHashType: "ErrInvalidSigHashType",
ErrSigDER: "ErrSigDER",
ErrSigHighS: "ErrSigHighS",
ErrNotPushOnly: "ErrNotPushOnly",
ErrSigNullDummy: "ErrSigNullDummy",
ErrPubKeyType: "ErrPubKeyType",
ErrCleanStack: "ErrCleanStack",
ErrNullFail: "ErrNullFail",
ErrDiscourageUpgradableNOPs: "ErrDiscourageUpgradableNOPs",
ErrNegativeLockTime: "ErrNegativeLockTime",
ErrUnsatisfiedLockTime: "ErrUnsatisfiedLockTime",
ErrWitnessProgramEmpty: "ErrWitnessProgramEmpty",
ErrWitnessProgramMismatch: "ErrWitnessProgramMismatch",
ErrWitnessProgramWrongLength: "ErrWitnessProgramWrongLength",
ErrWitnessMalleated: "ErrWitnessMalleated",
ErrWitnessMalleatedP2SH: "ErrWitnessMalleatedP2SH",
ErrWitnessUnexpected: "ErrWitnessUnexpected",
ErrMinimalIf: "ErrMinimalIf",
ErrWitnessPubKeyType: "ErrWitnessPubKeyType",
ErrDiscourageUpgradableWitnessProgram: "ErrDiscourageUpgradableWitnessProgram",
ErrInternal: "ErrInternal",
ErrInvalidFlags: "ErrInvalidFlags",
ErrInvalidIndex: "ErrInvalidIndex",
ErrUnsupportedAddress: "ErrUnsupportedAddress",
ErrNotMultisigScript: "ErrNotMultisigScript",
ErrTooManyRequiredSigs: "ErrTooManyRequiredSigs",
ErrTooMuchNullData: "ErrTooMuchNullData",
ErrEarlyReturn: "ErrEarlyReturn",
ErrEmptyStack: "ErrEmptyStack",
ErrEvalFalse: "ErrEvalFalse",
ErrScriptUnfinished: "ErrScriptUnfinished",
ErrInvalidProgramCounter: "ErrInvalidProgramCounter",
ErrScriptTooBig: "ErrScriptTooBig",
ErrElementTooBig: "ErrElementTooBig",
ErrTooManyOperations: "ErrTooManyOperations",
ErrStackOverflow: "ErrStackOverflow",
ErrInvalidPubKeyCount: "ErrInvalidPubKeyCount",
ErrInvalidSignatureCount: "ErrInvalidSignatureCount",
ErrNumberTooBig: "ErrNumberTooBig",
ErrVerify: "ErrVerify",
ErrEqualVerify: "ErrEqualVerify",
ErrNumEqualVerify: "ErrNumEqualVerify",
ErrCheckSigVerify: "ErrCheckSigVerify",
ErrCheckMultiSigVerify: "ErrCheckMultiSigVerify",
ErrDisabledOpcode: "ErrDisabledOpcode",
ErrReservedOpcode: "ErrReservedOpcode",
ErrMalformedPush: "ErrMalformedPush",
ErrInvalidStackOperation: "ErrInvalidStackOperation",
ErrUnbalancedConditional: "ErrUnbalancedConditional",
ErrMinimalData: "ErrMinimalData",
ErrInvalidSigHashType: "ErrInvalidSigHashType",
ErrSigDER: "ErrSigDER",
ErrSigHighS: "ErrSigHighS",
ErrNotPushOnly: "ErrNotPushOnly",
ErrSigNullDummy: "ErrSigNullDummy",
ErrPubKeyType: "ErrPubKeyType",
ErrCleanStack: "ErrCleanStack",
ErrNullFail: "ErrNullFail",
ErrDiscourageUpgradableNOPs: "ErrDiscourageUpgradableNOPs",
ErrNegativeLockTime: "ErrNegativeLockTime",
ErrUnsatisfiedLockTime: "ErrUnsatisfiedLockTime",
}
// String returns the ErrorCode as a human-readable name.

View File

@ -57,15 +57,6 @@ func TestErrorCodeStringer(t *testing.T) {
{ErrDiscourageUpgradableNOPs, "ErrDiscourageUpgradableNOPs"},
{ErrNegativeLockTime, "ErrNegativeLockTime"},
{ErrUnsatisfiedLockTime, "ErrUnsatisfiedLockTime"},
{ErrWitnessProgramEmpty, "ErrWitnessProgramEmpty"},
{ErrWitnessProgramMismatch, "ErrWitnessProgramMismatch"},
{ErrWitnessProgramWrongLength, "ErrWitnessProgramWrongLength"},
{ErrWitnessMalleated, "ErrWitnessMalleated"},
{ErrWitnessMalleatedP2SH, "ErrWitnessMalleatedP2SH"},
{ErrWitnessUnexpected, "ErrWitnessUnexpected"},
{ErrMinimalIf, "ErrMinimalIf"},
{ErrWitnessPubKeyType, "ErrWitnessPubKeyType"},
{ErrDiscourageUpgradableWitnessProgram, "ErrDiscourageUpgradableWitnessProgram"},
{0xffff, "Unknown ErrorCode (65535)"},
}

View File

@ -103,7 +103,7 @@ func ExampleSignTxOutput() {
// contains a single output that pays to address in the amount of 1 BTC.
originTx := wire.NewMsgTx(wire.TxVersion)
prevOut := wire.NewOutPoint(&chainhash.Hash{}, ^uint32(0))
txIn := wire.NewTxIn(prevOut, []byte{txscript.OP_0, txscript.OP_0}, nil)
txIn := wire.NewTxIn(prevOut, []byte{txscript.OP_0, txscript.OP_0})
originTx.AddTxIn(txIn)
pkScript, err := txscript.PayToAddrScript(addr)
if err != nil {
@ -121,7 +121,7 @@ func ExampleSignTxOutput() {
// signature script at this point since it hasn't been created or signed
// yet, hence nil is provided for it.
prevOut = wire.NewOutPoint(&originTxHash, 0)
txIn = wire.NewTxIn(prevOut, nil, nil)
txIn = wire.NewTxIn(prevOut, nil)
redeemTx.AddTxIn(txIn)
// Ordinarily this would contain that actual destination of the funds,
@ -165,8 +165,7 @@ func ExampleSignTxOutput() {
flags := txscript.ScriptBip16 | txscript.ScriptVerifyDERSignatures |
txscript.ScriptStrictMultiSig |
txscript.ScriptDiscourageUpgradableNops
vm, err := txscript.NewEngine(originTx.TxOut[0].PkScript, redeemTx, 0,
flags, nil, nil, -1)
vm, err := txscript.NewEngine(originTx.TxOut[0].PkScript, redeemTx, 0, flags, nil)
if err != nil {
fmt.Println(err)
return

View File

@ -1,89 +0,0 @@
// Copyright (c) 2016 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package txscript
import (
"sync"
"github.com/daglabs/btcd/chaincfg/chainhash"
"github.com/daglabs/btcd/wire"
)
// TxSigHashes houses the partial set of sighashes introduced within BIP0143.
// This partial set of sighashes may be re-used within each input across a
// transaction when validating all inputs. As a result, validation complexity
// for SigHashAll can be reduced by a polynomial factor.
type TxSigHashes struct {
HashPrevOuts chainhash.Hash
HashSequence chainhash.Hash
HashOutputs chainhash.Hash
}
// NewTxSigHashes computes, and returns the cached sighashes of the given
// transaction.
func NewTxSigHashes(tx *wire.MsgTx) *TxSigHashes {
return &TxSigHashes{
HashPrevOuts: calcHashPrevOuts(tx),
HashSequence: calcHashSequence(tx),
HashOutputs: calcHashOutputs(tx),
}
}
// HashCache houses a set of partial sighashes keyed by txid. The set of partial
// sighashes are those introduced within BIP0143 by the new more efficient
// sighash digest calculation algorithm. Using this threadsafe shared cache,
// multiple goroutines can safely re-use the pre-computed partial sighashes
// speeding up validation time amongst all inputs found within a block.
type HashCache struct {
sigHashes map[chainhash.Hash]*TxSigHashes
sync.RWMutex
}
// NewHashCache returns a new instance of the HashCache given a maximum number
// of entries which may exist within it at anytime.
func NewHashCache(maxSize uint) *HashCache {
return &HashCache{
sigHashes: make(map[chainhash.Hash]*TxSigHashes, maxSize),
}
}
// AddSigHashes computes, then adds the partial sighashes for the passed
// transaction.
func (h *HashCache) AddSigHashes(tx *wire.MsgTx) {
h.Lock()
h.sigHashes[tx.TxHash()] = NewTxSigHashes(tx)
h.Unlock()
}
// ContainsHashes returns true if the partial sighashes for the passed
// transaction currently exist within the HashCache, and false otherwise.
func (h *HashCache) ContainsHashes(txid *chainhash.Hash) bool {
h.RLock()
_, found := h.sigHashes[*txid]
h.RUnlock()
return found
}
// GetSigHashes possibly returns the previously cached partial sighashes for
// the passed transaction. This function also returns an additional boolean
// value indicating if the sighashes for the passed transaction were found to
// be present within the HashCache.
func (h *HashCache) GetSigHashes(txid *chainhash.Hash) (*TxSigHashes, bool) {
h.RLock()
item, found := h.sigHashes[*txid]
h.RUnlock()
return item, found
}
// PurgeSigHashes removes all partial sighashes from the HashCache belonging to
// the passed transaction.
func (h *HashCache) PurgeSigHashes(txid *chainhash.Hash) {
h.Lock()
delete(h.sigHashes, *txid)
h.Unlock()
}

View File

@ -1,182 +0,0 @@
// Copyright (c) 2017 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package txscript
import (
"math/rand"
"testing"
"time"
"github.com/daglabs/btcd/wire"
"github.com/davecgh/go-spew/spew"
)
// genTestTx creates a random transaction for uses within test cases.
func genTestTx() (*wire.MsgTx, error) {
tx := wire.NewMsgTx(2)
tx.Version = rand.Int31()
numTxins := rand.Intn(11)
for i := 0; i < numTxins; i++ {
randTxIn := wire.TxIn{
PreviousOutPoint: wire.OutPoint{
Index: uint32(rand.Int31()),
},
Sequence: uint32(rand.Int31()),
}
_, err := rand.Read(randTxIn.PreviousOutPoint.Hash[:])
if err != nil {
return nil, err
}
tx.TxIn = append(tx.TxIn, &randTxIn)
}
numTxouts := rand.Intn(11)
for i := 0; i < numTxouts; i++ {
randTxOut := wire.TxOut{
Value: rand.Int63(),
PkScript: make([]byte, rand.Intn(30)),
}
if _, err := rand.Read(randTxOut.PkScript); err != nil {
return nil, err
}
tx.TxOut = append(tx.TxOut, &randTxOut)
}
return tx, nil
}
// TestHashCacheAddContainsHashes tests that after items have been added to the
// hash cache, the ContainsHashes method returns true for all the items
// inserted. Conversely, ContainsHashes should return false for any items
// _not_ in the hash cache.
func TestHashCacheAddContainsHashes(t *testing.T) {
t.Parallel()
rand.Seed(time.Now().Unix())
cache := NewHashCache(10)
var err error
// First, we'll generate 10 random transactions for use within our
// tests.
const numTxns = 10
txns := make([]*wire.MsgTx, numTxns)
for i := 0; i < numTxns; i++ {
txns[i], err = genTestTx()
if err != nil {
t.Fatalf("unable to generate test tx: %v", err)
}
}
// With the transactions generated, we'll add each of them to the hash
// cache.
for _, tx := range txns {
cache.AddSigHashes(tx)
}
// Next, we'll ensure that each of the transactions inserted into the
// cache are properly located by the ContainsHashes method.
for _, tx := range txns {
txid := tx.TxHash()
if ok := cache.ContainsHashes(&txid); !ok {
t.Fatalf("txid %v not found in cache but should be: ",
txid)
}
}
randTx, err := genTestTx()
if err != nil {
t.Fatalf("unable to generate tx: %v", err)
}
// Finally, we'll assert that a transaction that wasn't added to the
// cache won't be reported as being present by the ContainsHashes
// method.
randTxid := randTx.TxHash()
if ok := cache.ContainsHashes(&randTxid); ok {
t.Fatalf("txid %v wasn't inserted into cache but was found",
randTxid)
}
}
// TestHashCacheAddGet tests that the sighashes for a particular transaction
// are properly retrieved by the GetSigHashes function.
func TestHashCacheAddGet(t *testing.T) {
t.Parallel()
rand.Seed(time.Now().Unix())
cache := NewHashCache(10)
// To start, we'll generate a random transaction and compute the set of
// sighashes for the transaction.
randTx, err := genTestTx()
if err != nil {
t.Fatalf("unable to generate tx: %v", err)
}
sigHashes := NewTxSigHashes(randTx)
// Next, add the transaction to the hash cache.
cache.AddSigHashes(randTx)
// The transaction inserted into the cache above should be found.
txid := randTx.TxHash()
cacheHashes, ok := cache.GetSigHashes(&txid)
if !ok {
t.Fatalf("tx %v wasn't found in cache", txid)
}
// Finally, the sighashes retrieved should exactly match the sighash
// originally inserted into the cache.
if *sigHashes != *cacheHashes {
t.Fatalf("sighashes don't match: expected %v, got %v",
spew.Sdump(sigHashes), spew.Sdump(cacheHashes))
}
}
// TestHashCachePurge tests that items are able to be properly removed from the
// hash cache.
func TestHashCachePurge(t *testing.T) {
t.Parallel()
rand.Seed(time.Now().Unix())
cache := NewHashCache(10)
var err error
// First we'll start by inserting numTxns transactions into the hash cache.
const numTxns = 10
txns := make([]*wire.MsgTx, numTxns)
for i := 0; i < numTxns; i++ {
txns[i], err = genTestTx()
if err != nil {
t.Fatalf("unable to generate test tx: %v", err)
}
}
for _, tx := range txns {
cache.AddSigHashes(tx)
}
// Once all the transactions have been inserted, we'll purge them from
// the hash cache.
for _, tx := range txns {
txid := tx.TxHash()
cache.PurgeSigHashes(&txid)
}
// At this point, none of the transactions inserted into the hash cache
// should be found within the cache.
for _, tx := range txns {
txid := tx.TxHash()
if ok := cache.ContainsHashes(&txid); ok {
t.Fatalf("tx %v found in cache but should have "+
"been purged: ", txid)
}
}
}

View File

@ -918,47 +918,6 @@ func opcodeNop(op *parsedOpcode, vm *Engine) error {
return nil
}
// popIfBool enforces the "minimal if" policy during script execution if the
// particular flag is set. If so, in order to eliminate an additional source
// of nuisance malleability, post-segwit for version 0 witness programs, we now
// require the following: for OP_IF and OP_NOT_IF, the top stack item MUST
// either be an empty byte slice, or [0x01]. Otherwise, the item at the top of
// the stack will be popped and interpreted as a boolean.
func popIfBool(vm *Engine) (bool, error) {
// When not in witness execution mode, not executing a v0 witness
// program, or the minimal if flag isn't set pop the top stack item as
// a normal bool.
if !vm.isWitnessVersionActive(0) || !vm.hasFlag(ScriptVerifyMinimalIf) {
return vm.dstack.PopBool()
}
// At this point, a v0 witness program is being executed and the minimal
// if flag is set, so enforce additional constraints on the top stack
// item.
so, err := vm.dstack.PopByteArray()
if err != nil {
return false, err
}
// The top element MUST have a length of at least one.
if len(so) > 1 {
str := fmt.Sprintf("minimal if is active, top element MUST "+
"have a length of at least, instead length is %v",
len(so))
return false, scriptError(ErrMinimalIf, str)
}
// Additionally, if the length is one, then the value MUST be 0x01.
if len(so) == 1 && so[0] != 0x01 {
str := fmt.Sprintf("minimal if is active, top stack item MUST "+
"be an empty byte array or 0x01, is instead: %v",
so[0])
return false, scriptError(ErrMinimalIf, str)
}
return asBool(so), nil
}
// opcodeIf treats the top item on the data stack as a boolean and removes it.
//
// An appropriate entry is added to the conditional stack depending on whether
@ -977,7 +936,8 @@ func popIfBool(vm *Engine) (bool, error) {
func opcodeIf(op *parsedOpcode, vm *Engine) error {
condVal := OpCondFalse
if vm.isBranchExecuting() {
ok, err := popIfBool(vm)
ok, err := vm.dstack.PopBool()
if err != nil {
return err
}
@ -1011,7 +971,7 @@ func opcodeIf(op *parsedOpcode, vm *Engine) error {
func opcodeNotIf(op *parsedOpcode, vm *Engine) error {
condVal := OpCondFalse
if vm.isBranchExecuting() {
ok, err := popIfBool(vm)
ok, err := vm.dstack.PopBool()
if err != nil {
return err
}
@ -2088,28 +2048,12 @@ func opcodeCheckSig(op *parsedOpcode, vm *Engine) error {
// Get script starting from the most recent OP_CODESEPARATOR.
subScript := vm.subScript()
// Remove the signature since there is no way for a signature
// to sign itself.
subScript = removeOpcodeByData(subScript, fullSigBytes)
// Generate the signature hash based on the signature hash type.
var hash []byte
if vm.isWitnessVersionActive(0) {
var sigHashes *TxSigHashes
if vm.hashCache != nil {
sigHashes = vm.hashCache
} else {
sigHashes = NewTxSigHashes(&vm.tx)
}
hash, err = calcWitnessSignatureHash(subScript, sigHashes, hashType,
&vm.tx, vm.txIdx, vm.inputAmount)
if err != nil {
return err
}
} else {
// Remove the signature since there is no way for a signature
// to sign itself.
subScript = removeOpcodeByData(subScript, fullSigBytes)
hash = calcSignatureHash(subScript, hashType, &vm.tx, vm.txIdx)
}
hash := calcSignatureHash(subScript, hashType, &vm.tx, vm.txIdx)
pubKey, err := btcec.ParsePubKey(pkBytes, btcec.S256())
if err != nil {
@ -2275,12 +2219,9 @@ func opcodeCheckMultiSig(op *parsedOpcode, vm *Engine) error {
// Get script starting from the most recent OP_CODESEPARATOR.
script := vm.subScript()
// Remove the signature in pre version 0 segwit scripts since there is
// no way for a signature to sign itself.
if !vm.isWitnessVersionActive(0) {
for _, sigInfo := range signatures {
script = removeOpcodeByData(script, sigInfo.signature)
}
// Remove the signatures in scripts since there is no way for a signature to sign itself.
for _, sigInfo := range signatures {
script = removeOpcodeByData(script, sigInfo.signature)
}
success := true
@ -2362,23 +2303,7 @@ func opcodeCheckMultiSig(op *parsedOpcode, vm *Engine) error {
}
// Generate the signature hash based on the signature hash type.
var hash []byte
if vm.isWitnessVersionActive(0) {
var sigHashes *TxSigHashes
if vm.hashCache != nil {
sigHashes = vm.hashCache
} else {
sigHashes = NewTxSigHashes(&vm.tx)
}
hash, err = calcWitnessSignatureHash(script, sigHashes, hashType,
&vm.tx, vm.txIdx, vm.inputAmount)
if err != nil {
return err
}
} else {
hash = calcSignatureHash(script, hashType, &vm.tx, vm.txIdx)
}
hash := calcSignatureHash(script, hashType, &vm.tx, vm.txIdx)
var valid bool
if vm.sigCache != nil {

View File

@ -23,16 +23,9 @@ import (
// scriptTestName returns a descriptive test name for the given reference script
// test data.
func scriptTestName(test []interface{}) (string, error) {
// Account for any optional leading witness data.
var witnessOffset int
if _, ok := test[0].([]interface{}); ok {
witnessOffset++
}
// In addition to the optional leading witness data, the test must
// consist of at least a signature script, public key script, flags,
// The test must consist of a signature script, public key script, flags,
// and expected error. Finally, it may optionally contain a comment.
if len(test) < witnessOffset+4 || len(test) > witnessOffset+5 {
if len(test) < 4 || len(test) > 5 {
return "", fmt.Errorf("invalid test length %d", len(test))
}
@ -40,11 +33,11 @@ func scriptTestName(test []interface{}) (string, error) {
// construct the name based on the signature script, public key script,
// and flags.
var name string
if len(test) == witnessOffset+5 {
name = fmt.Sprintf("test (%s)", test[witnessOffset+4])
if len(test) == 5 {
name = fmt.Sprintf("test (%s)", test[4])
} else {
name = fmt.Sprintf("test ([%s, %s, %s])", test[witnessOffset],
test[witnessOffset+1], test[witnessOffset+2])
name = fmt.Sprintf("test ([%s, %s, %s])", test[0],
test[1], test[2])
}
return name, nil
}
@ -57,22 +50,6 @@ func parseHex(tok string) ([]byte, error) {
return hex.DecodeString(tok[2:])
}
// parseWitnessStack parses a json array of witness items encoded as hex into a
// slice of witness elements.
func parseWitnessStack(elements []interface{}) ([][]byte, error) {
witness := make([][]byte, len(elements))
for i, e := range elements {
witElement, err := hex.DecodeString(e.(string))
if err != nil {
return nil, err
}
witness[i] = witElement
}
return witness, nil
}
// shortFormOps holds a map of opcode names to values for use in short form
// parsing. It is declared here so it only needs to be created once.
var shortFormOps map[string]byte
@ -184,14 +161,6 @@ func parseScriptFlags(flagStr string) (ScriptFlags, error) {
flags |= ScriptVerifySigPushOnly
case "STRICTENC":
flags |= ScriptVerifyStrictEncoding
case "WITNESS":
flags |= ScriptVerifyWitness
case "DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM":
flags |= ScriptVerifyDiscourageUpgradeableWitnessProgram
case "MINIMALIF":
flags |= ScriptVerifyMinimalIf
case "WITNESS_PUBKEYTYPE":
flags |= ScriptVerifyWitnessPubKeyType
default:
return flags, fmt.Errorf("invalid flag: %s", flag)
}
@ -261,24 +230,6 @@ func parseExpectedResult(expected string) ([]ErrorCode, error) {
return []ErrorCode{ErrNegativeLockTime}, nil
case "UNSATISFIED_LOCKTIME":
return []ErrorCode{ErrUnsatisfiedLockTime}, nil
case "MINIMALIF":
return []ErrorCode{ErrMinimalIf}, nil
case "DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM":
return []ErrorCode{ErrDiscourageUpgradableWitnessProgram}, nil
case "WITNESS_PROGRAM_WRONG_LENGTH":
return []ErrorCode{ErrWitnessProgramWrongLength}, nil
case "WITNESS_PROGRAM_WITNESS_EMPTY":
return []ErrorCode{ErrWitnessProgramEmpty}, nil
case "WITNESS_PROGRAM_MISMATCH":
return []ErrorCode{ErrWitnessProgramMismatch}, nil
case "WITNESS_MALLEATED":
return []ErrorCode{ErrWitnessMalleated}, nil
case "WITNESS_MALLEATED_P2SH":
return []ErrorCode{ErrWitnessMalleatedP2SH}, nil
case "WITNESS_UNEXPECTED":
return []ErrorCode{ErrWitnessUnexpected}, nil
case "WITNESS_PUBKEYTYPE":
return []ErrorCode{ErrWitnessPubKeyType}, nil
}
return nil, fmt.Errorf("unrecognized expected result in test data: %v",
@ -286,23 +237,21 @@ func parseExpectedResult(expected string) ([]ErrorCode, error) {
}
// createSpendTx generates a basic spending transaction given the passed
// signature, witness and public key scripts.
func createSpendingTx(witness [][]byte, sigScript, pkScript []byte,
outputValue int64) *wire.MsgTx {
// signature and public key scripts.
func createSpendingTx(sigScript, pkScript []byte) *wire.MsgTx {
coinbaseTx := wire.NewMsgTx(wire.TxVersion)
outPoint := wire.NewOutPoint(&chainhash.Hash{}, ^uint32(0))
txIn := wire.NewTxIn(outPoint, []byte{OP_0, OP_0}, nil)
txOut := wire.NewTxOut(outputValue, pkScript)
txIn := wire.NewTxIn(outPoint, []byte{OP_0, OP_0})
txOut := wire.NewTxOut(0, pkScript)
coinbaseTx.AddTxIn(txIn)
coinbaseTx.AddTxOut(txOut)
spendingTx := wire.NewMsgTx(wire.TxVersion)
coinbaseTxSha := coinbaseTx.TxHash()
outPoint = wire.NewOutPoint(&coinbaseTxSha, 0)
txIn = wire.NewTxIn(outPoint, sigScript, witness)
txOut = wire.NewTxOut(outputValue, nil)
coinbaseTxHash := coinbaseTx.TxHash()
outPoint = wire.NewOutPoint(&coinbaseTxHash, 0)
txIn = wire.NewTxIn(outPoint, sigScript)
txOut = wire.NewTxOut(0, nil)
spendingTx.AddTxIn(txIn)
spendingTx.AddTxOut(txOut)
@ -310,14 +259,6 @@ func createSpendingTx(witness [][]byte, sigScript, pkScript []byte,
return spendingTx
}
// scriptWithInputVal wraps a target pkScript with the value of the output in
// which it is contained. The inputVal is necessary in order to properly
// validate inputs which spend nested, or native witness programs.
type scriptWithInputVal struct {
inputVal int64
pkScript []byte
}
// testScripts ensures all of the passed script tests execute with the expected
// results with or without using a signature cache, as specified by the
// parameter.
@ -345,39 +286,8 @@ func testScripts(t *testing.T, tests [][]interface{}, useSigCache bool) {
continue
}
var (
witness wire.TxWitness
inputAmt btcutil.Amount
)
// When the first field of the test data is a slice it contains
// witness data and everything else is offset by 1 as a result.
witnessOffset := 0
if witnessData, ok := test[0].([]interface{}); ok {
witnessOffset++
// If this is a witness test, then the final element
// within the slice is the input amount, so we ignore
// all but the last element in order to parse the
// witness stack.
strWitnesses := witnessData[:len(witnessData)-1]
witness, err = parseWitnessStack(strWitnesses)
if err != nil {
t.Errorf("%s: can't parse witness; %v", name, err)
continue
}
inputAmt, err = btcutil.NewAmount(witnessData[len(witnessData)-1].(float64))
if err != nil {
t.Errorf("%s: can't parse input amt: %v",
name, err)
continue
}
}
// Extract and parse the signature script from the test fields.
scriptSigStr, ok := test[witnessOffset].(string)
scriptSigStr, ok := test[0].(string)
if !ok {
t.Errorf("%s: signature script is not a string", name)
continue
@ -390,7 +300,7 @@ func testScripts(t *testing.T, tests [][]interface{}, useSigCache bool) {
}
// Extract and parse the public key script from the test fields.
scriptPubKeyStr, ok := test[witnessOffset+1].(string)
scriptPubKeyStr, ok := test[1].(string)
if !ok {
t.Errorf("%s: public key script is not a string", name)
continue
@ -403,7 +313,7 @@ func testScripts(t *testing.T, tests [][]interface{}, useSigCache bool) {
}
// Extract and parse the script flags from the test fields.
flagsStr, ok := test[witnessOffset+2].(string)
flagsStr, ok := test[2].(string)
if !ok {
t.Errorf("%s: flags field is not a string", name)
continue
@ -421,7 +331,7 @@ func testScripts(t *testing.T, tests [][]interface{}, useSigCache bool) {
// fine grained with its errors than the reference test data, so
// some of the reference test data errors map to more than one
// possibility.
resultStr, ok := test[witnessOffset+3].(string)
resultStr, ok := test[3].(string)
if !ok {
t.Errorf("%s: result field is not a string", name)
continue
@ -435,10 +345,8 @@ func testScripts(t *testing.T, tests [][]interface{}, useSigCache bool) {
// Generate a transaction pair such that one spends from the
// other and the provided signature and public key scripts are
// used, then create a new engine to execute the scripts.
tx := createSpendingTx(witness, scriptSig, scriptPubKey,
int64(inputAmt))
vm, err := NewEngine(scriptPubKey, tx, 0, flags, sigCache, nil,
int64(inputAmt))
tx := createSpendingTx(scriptSig, scriptPubKey)
vm, err := NewEngine(scriptPubKey, tx, 0, flags, sigCache)
if err == nil {
err = vm.Execute()
}
@ -566,7 +474,7 @@ testloop:
continue
}
prevOuts := make(map[wire.OutPoint]scriptWithInputVal)
prevOuts := make(map[wire.OutPoint][]byte)
for j, iinput := range inputs {
input, ok := iinput.([]interface{})
if !ok {
@ -575,7 +483,7 @@ testloop:
continue testloop
}
if len(input) < 3 || len(input) > 4 {
if len(input) != 3 {
t.Errorf("bad test (%dth input wrong length)"+
"%d: %v", j, i, test)
continue testloop
@ -617,25 +525,11 @@ testloop:
continue testloop
}
var inputValue float64
if len(input) == 4 {
inputValue, ok = input[3].(float64)
if !ok {
t.Errorf("bad test (%dth input value not int) "+
"%d: %v", j, i, test)
continue
}
}
v := scriptWithInputVal{
inputVal: int64(inputValue),
pkScript: script,
}
prevOuts[*wire.NewOutPoint(prevhash, idx)] = v
prevOuts[*wire.NewOutPoint(prevhash, idx)] = script
}
for k, txin := range tx.MsgTx().TxIn {
prevOut, ok := prevOuts[txin.PreviousOutPoint]
pkScript, ok := prevOuts[txin.PreviousOutPoint]
if !ok {
t.Errorf("bad test (missing %dth input) %d:%v",
k, i, test)
@ -644,8 +538,7 @@ testloop:
// These are meant to fail, so as soon as the first
// input fails the transaction has failed. (some of the
// test txns have good inputs, too..
vm, err := NewEngine(prevOut.pkScript, tx.MsgTx(), k,
flags, nil, nil, prevOut.inputVal)
vm, err := NewEngine(pkScript, tx.MsgTx(), k, flags, nil)
if err != nil {
continue testloop
}
@ -677,7 +570,7 @@ func TestTxValidTests(t *testing.T) {
// form is either:
// ["this is a comment "]
// or:
// [[[previous hash, previous index, previous scriptPubKey, input value]...,]
// [[[previous hash, previous index, previous scriptPubKey]...,]
// serializedTransaction, verifyFlags]
testloop:
for i, test := range tests {
@ -721,7 +614,7 @@ testloop:
continue
}
prevOuts := make(map[wire.OutPoint]scriptWithInputVal)
prevOuts := make(map[wire.OutPoint][]byte)
for j, iinput := range inputs {
input, ok := iinput.([]interface{})
if !ok {
@ -730,7 +623,7 @@ testloop:
continue
}
if len(input) < 3 || len(input) > 4 {
if len(input) != 3 {
t.Errorf("bad test (%dth input wrong length)"+
"%d: %v", j, i, test)
continue
@ -772,32 +665,21 @@ testloop:
continue
}
var inputValue float64
if len(input) == 4 {
inputValue, ok = input[3].(float64)
if !ok {
t.Errorf("bad test (%dth input value not int) "+
"%d: %v", j, i, test)
continue
}
}
v := scriptWithInputVal{
inputVal: int64(inputValue),
pkScript: script,
}
prevOuts[*wire.NewOutPoint(prevhash, idx)] = v
prevOuts[*wire.NewOutPoint(prevhash, idx)] = script
}
for k, txin := range tx.MsgTx().TxIn {
prevOut, ok := prevOuts[txin.PreviousOutPoint]
pkScript, ok := prevOuts[txin.PreviousOutPoint]
if !ok {
t.Errorf("bad test (missing %dth input) %d:%v",
k, i, test)
continue testloop
}
vm, err := NewEngine(prevOut.pkScript, tx.MsgTx(), k,
flags, nil, nil, prevOut.inputVal)
if i == 93 {
fmt.Printf("lalala")
}
vm, err := NewEngine(pkScript, tx.MsgTx(), k, flags, nil)
if err != nil {
t.Errorf("test (%d:%v:%d) failed to create "+
"script: %v", i, test, k, err)

View File

@ -70,98 +70,6 @@ func IsPayToScriptHash(script []byte) bool {
return isScriptHash(pops)
}
// isWitnessScriptHash returns true if the passed script is a
// pay-to-witness-script-hash transaction, false otherwise.
func isWitnessScriptHash(pops []parsedOpcode) bool {
return len(pops) == 2 &&
pops[0].opcode.value == OP_0 &&
pops[1].opcode.value == OP_DATA_32
}
// IsPayToWitnessScriptHash returns true if the is in the standard
// pay-to-witness-script-hash (P2WSH) format, false otherwise.
func IsPayToWitnessScriptHash(script []byte) bool {
pops, err := parseScript(script)
if err != nil {
return false
}
return isWitnessScriptHash(pops)
}
// IsPayToWitnessPubKeyHash returns true if the is in the standard
// pay-to-witness-pubkey-hash (P2WKH) format, false otherwise.
func IsPayToWitnessPubKeyHash(script []byte) bool {
pops, err := parseScript(script)
if err != nil {
return false
}
return isWitnessPubKeyHash(pops)
}
// isWitnessPubKeyHash returns true if the passed script is a
// pay-to-witness-pubkey-hash, and false otherwise.
func isWitnessPubKeyHash(pops []parsedOpcode) bool {
return len(pops) == 2 &&
pops[0].opcode.value == OP_0 &&
pops[1].opcode.value == OP_DATA_20
}
// IsWitnessProgram returns true if the passed script is a valid witness
// program which is encoded according to the passed witness program version. A
// witness program must be a small integer (from 0-16), followed by 2-40 bytes
// of pushed data.
func IsWitnessProgram(script []byte) bool {
// The length of the script must be between 4 and 42 bytes. The
// smallest program is the witness version, followed by a data push of
// 2 bytes. The largest allowed witness program has a data push of
// 40-bytes.
if len(script) < 4 || len(script) > 42 {
return false
}
pops, err := parseScript(script)
if err != nil {
return false
}
return isWitnessProgram(pops)
}
// isWitnessProgram returns true if the passed script is a witness program, and
// false otherwise. A witness program MUST adhere to the following constraints:
// there must be exactly two pops (program version and the program itself), the
// first opcode MUST be a small integer (0-16), the push data MUST be
// canonical, and finally the size of the push data must be between 2 and 40
// bytes.
func isWitnessProgram(pops []parsedOpcode) bool {
return len(pops) == 2 &&
isSmallInt(pops[0].opcode) &&
canonicalPush(pops[1]) &&
(len(pops[1].data) >= 2 && len(pops[1].data) <= 40)
}
// ExtractWitnessProgramInfo attempts to extract the witness program version,
// as well as the witness program itself from the passed script.
func ExtractWitnessProgramInfo(script []byte) (int, []byte, error) {
pops, err := parseScript(script)
if err != nil {
return 0, nil, err
}
// If at this point, the scripts doesn't resemble a witness program,
// then we'll exit early as there isn't a valid version or program to
// extract.
if !isWitnessProgram(pops) {
return 0, nil, fmt.Errorf("script is not a witness program, " +
"unable to extract version or witness program")
}
witnessVersion := asSmallInt(pops[0].opcode)
witnessProgram := pops[1].data
return witnessVersion, witnessProgram, nil
}
// isPushOnly returns true if the script only pushes data, false otherwise.
func isPushOnly(pops []parsedOpcode) bool {
// NOTE: This function does NOT verify opcodes directly since it is
@ -370,190 +278,6 @@ func removeOpcodeByData(pkscript []parsedOpcode, data []byte) []parsedOpcode {
}
// calcHashPrevOuts calculates a single hash of all the previous outputs
// (txid:index) referenced within the passed transaction. This calculated hash
// can be re-used when validating all inputs spending segwit outputs, with a
// signature hash type of SigHashAll. This allows validation to re-use previous
// hashing computation, reducing the complexity of validating SigHashAll inputs
// from O(N^2) to O(N).
func calcHashPrevOuts(tx *wire.MsgTx) chainhash.Hash {
var b bytes.Buffer
for _, in := range tx.TxIn {
// First write out the 32-byte transaction ID one of whose
// outputs are being referenced by this input.
b.Write(in.PreviousOutPoint.Hash[:])
// Next, we'll encode the index of the referenced output as a
// little endian integer.
var buf [4]byte
binary.LittleEndian.PutUint32(buf[:], in.PreviousOutPoint.Index)
b.Write(buf[:])
}
return chainhash.DoubleHashH(b.Bytes())
}
// calcHashSequence computes an aggregated hash of each of the sequence numbers
// within the inputs of the passed transaction. This single hash can be re-used
// when validating all inputs spending segwit outputs, which include signatures
// using the SigHashAll sighash type. This allows validation to re-use previous
// hashing computation, reducing the complexity of validating SigHashAll inputs
// from O(N^2) to O(N).
func calcHashSequence(tx *wire.MsgTx) chainhash.Hash {
var b bytes.Buffer
for _, in := range tx.TxIn {
var buf [4]byte
binary.LittleEndian.PutUint32(buf[:], in.Sequence)
b.Write(buf[:])
}
return chainhash.DoubleHashH(b.Bytes())
}
// calcHashOutputs computes a hash digest of all outputs created by the
// transaction encoded using the wire format. This single hash can be re-used
// when validating all inputs spending witness programs, which include
// signatures using the SigHashAll sighash type. This allows computation to be
// cached, reducing the total hashing complexity from O(N^2) to O(N).
func calcHashOutputs(tx *wire.MsgTx) chainhash.Hash {
var b bytes.Buffer
for _, out := range tx.TxOut {
wire.WriteTxOut(&b, 0, 0, out)
}
return chainhash.DoubleHashH(b.Bytes())
}
// calcWitnessSignatureHash computes the sighash digest of a transaction's
// segwit input using the new, optimized digest calculation algorithm defined
// in BIP0143: https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki.
// This function makes use of pre-calculated sighash fragments stored within
// the passed HashCache to eliminate duplicate hashing computations when
// calculating the final digest, reducing the complexity from O(N^2) to O(N).
// Additionally, signatures now cover the input value of the referenced unspent
// output. This allows offline, or hardware wallets to compute the exact amount
// being spent, in addition to the final transaction fee. In the case the
// wallet if fed an invalid input amount, the real sighash will differ causing
// the produced signature to be invalid.
func calcWitnessSignatureHash(subScript []parsedOpcode, sigHashes *TxSigHashes,
hashType SigHashType, tx *wire.MsgTx, idx int, amt int64) ([]byte, error) {
// As a sanity check, ensure the passed input index for the transaction
// is valid.
if idx > len(tx.TxIn)-1 {
return nil, fmt.Errorf("idx %d but %d txins", idx, len(tx.TxIn))
}
// We'll utilize this buffer throughout to incrementally calculate
// the signature hash for this transaction.
var sigHash bytes.Buffer
// First write out, then encode the transaction's version number.
var bVersion [4]byte
binary.LittleEndian.PutUint32(bVersion[:], uint32(tx.Version))
sigHash.Write(bVersion[:])
// Next write out the possibly pre-calculated hashes for the sequence
// numbers of all inputs, and the hashes of the previous outs for all
// outputs.
var zeroHash chainhash.Hash
// If anyone can pay isn't active, then we can use the cached
// hashPrevOuts, otherwise we just write zeroes for the prev outs.
if hashType&SigHashAnyOneCanPay == 0 {
sigHash.Write(sigHashes.HashPrevOuts[:])
} else {
sigHash.Write(zeroHash[:])
}
// If the sighash isn't anyone can pay, single, or none, the use the
// cached hash sequences, otherwise write all zeroes for the
// hashSequence.
if hashType&SigHashAnyOneCanPay == 0 &&
hashType&sigHashMask != SigHashSingle &&
hashType&sigHashMask != SigHashNone {
sigHash.Write(sigHashes.HashSequence[:])
} else {
sigHash.Write(zeroHash[:])
}
txIn := tx.TxIn[idx]
// Next, write the outpoint being spent.
sigHash.Write(txIn.PreviousOutPoint.Hash[:])
var bIndex [4]byte
binary.LittleEndian.PutUint32(bIndex[:], txIn.PreviousOutPoint.Index)
sigHash.Write(bIndex[:])
if isWitnessPubKeyHash(subScript) {
// The script code for a p2wkh is a length prefix varint for
// the next 25 bytes, followed by a re-creation of the original
// p2pkh pk script.
sigHash.Write([]byte{0x19})
sigHash.Write([]byte{OP_DUP})
sigHash.Write([]byte{OP_HASH160})
sigHash.Write([]byte{OP_DATA_20})
sigHash.Write(subScript[1].data)
sigHash.Write([]byte{OP_EQUALVERIFY})
sigHash.Write([]byte{OP_CHECKSIG})
} else {
// For p2wsh outputs, and future outputs, the script code is
// the original script, with all code separators removed,
// serialized with a var int length prefix.
rawScript, _ := unparseScript(subScript)
wire.WriteVarBytes(&sigHash, 0, rawScript)
}
// Next, add the input amount, and sequence number of the input being
// signed.
var bAmount [8]byte
binary.LittleEndian.PutUint64(bAmount[:], uint64(amt))
sigHash.Write(bAmount[:])
var bSequence [4]byte
binary.LittleEndian.PutUint32(bSequence[:], txIn.Sequence)
sigHash.Write(bSequence[:])
// If the current signature mode isn't single, or none, then we can
// re-use the pre-generated hashoutputs sighash fragment. Otherwise,
// we'll serialize and add only the target output index to the signature
// pre-image.
if hashType&SigHashSingle != SigHashSingle &&
hashType&SigHashNone != SigHashNone {
sigHash.Write(sigHashes.HashOutputs[:])
} else if hashType&sigHashMask == SigHashSingle && idx < len(tx.TxOut) {
var b bytes.Buffer
wire.WriteTxOut(&b, 0, 0, tx.TxOut[idx])
sigHash.Write(chainhash.DoubleHashB(b.Bytes()))
} else {
sigHash.Write(zeroHash[:])
}
// Finally, write out the transaction's locktime, and the sig hash
// type.
var bLockTime [4]byte
binary.LittleEndian.PutUint32(bLockTime[:], tx.LockTime)
sigHash.Write(bLockTime[:])
var bHashType [4]byte
binary.LittleEndian.PutUint32(bHashType[:], uint32(hashType))
sigHash.Write(bHashType[:])
return chainhash.DoubleHashB(sigHash.Bytes()), nil
}
// CalcWitnessSigHash computes the sighash digest for the specified input of
// the target transaction observing the desired sig hash type.
func CalcWitnessSigHash(script []byte, sigHashes *TxSigHashes, hType SigHashType,
tx *wire.MsgTx, idx int, amt int64) ([]byte, error) {
parsedScript, err := parseScript(script)
if err != nil {
return nil, fmt.Errorf("cannot parse output script: %v", err)
}
return calcWitnessSignatureHash(parsedScript, sigHashes, hType, tx, idx,
amt)
}
// shallowCopyTx creates a shallow copy of the transaction for use when
// calculating the signature hash. It is used over the Copy method on the
// transaction itself since that is a deep copy and therefore does more work and
@ -682,8 +406,8 @@ func calcSignatureHash(script []parsedOpcode, hashType SigHashType, tx *wire.Msg
// The final hash is the double sha256 of both the serialized modified
// transaction and the hash type (encoded as a 4-byte little-endian
// value) appended.
wbuf := bytes.NewBuffer(make([]byte, 0, txCopy.SerializeSizeStripped()+4))
txCopy.SerializeNoWitness(wbuf)
wbuf := bytes.NewBuffer(make([]byte, 0, txCopy.SerializeSize()+4))
txCopy.Serialize(wbuf)
binary.Write(wbuf, binary.LittleEndian, hashType)
return chainhash.DoubleHashB(wbuf.Bytes())
}
@ -788,65 +512,6 @@ func GetPreciseSigOpCount(scriptSig, scriptPubKey []byte, bip16 bool) int {
return getSigOpCount(shPops, true)
}
// GetWitnessSigOpCount returns the number of signature operations generated by
// spending the passed pkScript with the specified witness, or sigScript.
// Unlike GetPreciseSigOpCount, this function is able to accurately count the
// number of signature operations generated by spending witness programs, and
// nested p2sh witness programs. If the script fails to parse, then the count
// up to the point of failure is returned.
func GetWitnessSigOpCount(sigScript, pkScript []byte, witness wire.TxWitness) int {
// If this is a regular witness program, then we can proceed directly
// to counting its signature operations without any further processing.
if IsWitnessProgram(pkScript) {
return getWitnessSigOps(pkScript, witness)
}
// Next, we'll check the sigScript to see if this is a nested p2sh
// witness program. This is a case wherein the sigScript is actually a
// datapush of a p2wsh witness program.
sigPops, err := parseScript(sigScript)
if err != nil {
return 0
}
if IsPayToScriptHash(pkScript) && isPushOnly(sigPops) &&
IsWitnessProgram(sigScript[1:]) {
return getWitnessSigOps(sigScript[1:], witness)
}
return 0
}
// getWitnessSigOps returns the number of signature operations generated by
// spending the passed witness program wit the passed witness. The exact
// signature counting heuristic is modified by the version of the passed
// witness program. If the version of the witness program is unable to be
// extracted, then 0 is returned for the sig op count.
func getWitnessSigOps(pkScript []byte, witness wire.TxWitness) int {
// Attempt to extract the witness program version.
witnessVersion, witnessProgram, err := ExtractWitnessProgramInfo(
pkScript,
)
if err != nil {
return 0
}
switch witnessVersion {
case 0:
switch {
case len(witnessProgram) == payToWitnessPubKeyHashDataSize:
return 1
case len(witnessProgram) == payToWitnessScriptHashDataSize &&
len(witness) > 0:
witnessScript := witness[len(witness)-1]
pops, _ := parseScript(witnessScript)
return getSigOpCount(pops, true)
}
}
return 0
}
// IsUnspendable returns whether the passed public key script is unspendable, or
// guaranteed to fail at execution. This allows inputs to be pruned instantly
// when entering the UTXO set.

View File

@ -8,8 +8,6 @@ import (
"bytes"
"reflect"
"testing"
"github.com/daglabs/btcd/wire"
)
// TestParseOpcode tests for opcode parsing with bad data templates.
@ -3846,94 +3844,6 @@ func TestGetPreciseSigOps(t *testing.T) {
}
}
// TestGetWitnessSigOpCount tests that the sig op counting for p2wkh, p2wsh,
// nested p2sh, and invalid variants are counted properly.
func TestGetWitnessSigOpCount(t *testing.T) {
t.Parallel()
tests := []struct {
name string
sigScript []byte
pkScript []byte
witness wire.TxWitness
numSigOps int
}{
// A regualr p2wkh witness program. The output being spent
// should only have a single sig-op counted.
{
name: "p2wkh",
pkScript: mustParseShortForm("OP_0 DATA_20 " +
"0x365ab47888e150ff46f8d51bce36dcd680f1283f"),
witness: wire.TxWitness{
hexToBytes("3045022100ee9fe8f9487afa977" +
"6647ebcf0883ce0cd37454d7ce19889d34ba2c9" +
"9ce5a9f402200341cb469d0efd3955acb9e46" +
"f568d7e2cc10f9084aaff94ced6dc50a59134ad01"),
hexToBytes("03f0000d0639a22bfaf217e4c9428" +
"9c2b0cc7fa1036f7fd5d9f61a9d6ec153100e"),
},
numSigOps: 1,
},
// A p2wkh witness program nested within a p2sh output script.
// The pattern should be recognized properly and attribute only
// a single sig op.
{
name: "nested p2sh",
sigScript: hexToBytes("160014ad0ffa2e387f07" +
"e7ead14dc56d5a97dbd6ff5a23"),
pkScript: mustParseShortForm("HASH160 DATA_20 " +
"0xb3a84b564602a9d68b4c9f19c2ea61458ff7826c EQUAL"),
witness: wire.TxWitness{
hexToBytes("3045022100cb1c2ac1ff1d57d" +
"db98f7bdead905f8bf5bcc8641b029ce8eef25" +
"c75a9e22a4702203be621b5c86b771288706be5" +
"a7eee1db4fceabf9afb7583c1cc6ee3f8297b21201"),
hexToBytes("03f0000d0639a22bfaf217e4c9" +
"4289c2b0cc7fa1036f7fd5d9f61a9d6ec153100e"),
},
numSigOps: 1,
},
// A p2sh script that spends a 2-of-2 multi-sig output.
{
name: "p2wsh multi-sig spend",
numSigOps: 2,
pkScript: hexToBytes("0020e112b88a0cd87ba387f" +
"449d443ee2596eb353beb1f0351ab2cba8909d875db23"),
witness: wire.TxWitness{
hexToBytes("522103b05faca7ceda92b493" +
"3f7acdf874a93de0dc7edc461832031cd69cbb1d1e" +
"6fae2102e39092e031c1621c902e3704424e8d8" +
"3ca481d4d4eeae1b7970f51c78231207e52ae"),
},
},
// A p2wsh witness program. However, the witness script fails
// to parse after the valid portion of the script. As a result,
// the valid portion of the script should still be counted.
{
name: "witness script doesn't parse",
numSigOps: 1,
pkScript: hexToBytes("0020e112b88a0cd87ba387f44" +
"9d443ee2596eb353beb1f0351ab2cba8909d875db23"),
witness: wire.TxWitness{
mustParseShortForm("DUP HASH160 " +
"'17VZNX1SN5NtKa8UQFxwQbFeFc3iqRYhem'" +
" EQUALVERIFY CHECKSIG DATA_20 0x91"),
},
},
}
for _, test := range tests {
count := GetWitnessSigOpCount(test.sigScript, test.pkScript,
test.witness)
if count != test.numSigOps {
t.Errorf("%s: expected count of %d, got %d", test.name,
test.numSigOps, count)
}
}
}
// TestRemoveOpcodes ensures that removing opcodes from scripts behaves as
// expected.
func TestRemoveOpcodes(t *testing.T) {
@ -4181,38 +4091,6 @@ func TestIsPayToScriptHash(t *testing.T) {
}
}
// TestIsPayToWitnessScriptHash ensures the IsPayToWitnessScriptHash function
// returns the expected results for all the scripts in scriptClassTests.
func TestIsPayToWitnessScriptHash(t *testing.T) {
t.Parallel()
for _, test := range scriptClassTests {
script := mustParseShortForm(test.script)
shouldBe := (test.class == WitnessV0ScriptHashTy)
p2wsh := IsPayToWitnessScriptHash(script)
if p2wsh != shouldBe {
t.Errorf("%s: expected p2wsh %v, got %v", test.name,
shouldBe, p2wsh)
}
}
}
// TestIsPayToWitnessPubKeyHash ensures the IsPayToWitnessPubKeyHash function
// returns the expected results for all the scripts in scriptClassTests.
func TestIsPayToWitnessPubKeyHash(t *testing.T) {
t.Parallel()
for _, test := range scriptClassTests {
script := mustParseShortForm(test.script)
shouldBe := (test.class == WitnessV0PubKeyHashTy)
p2wkh := IsPayToWitnessPubKeyHash(script)
if p2wkh != shouldBe {
t.Errorf("%s: expected p2wkh %v, got %v", test.name,
shouldBe, p2wkh)
}
}
}
// TestHasCanonicalPushes ensures the canonicalPush function properly determines
// what is considered a canonical push for the purposes of removeOpcodeByData.
func TestHasCanonicalPushes(t *testing.T) {

View File

@ -14,61 +14,6 @@ import (
"github.com/daglabs/btcutil"
)
// RawTxInWitnessSignature returns the serialized ECDA signature for the input
// idx of the given transaction, with the hashType appended to it. This
// function is identical to RawTxInSignature, however the signature generated
// signs a new sighash digest defined in BIP0143.
func RawTxInWitnessSignature(tx *wire.MsgTx, sigHashes *TxSigHashes, idx int,
amt int64, subScript []byte, hashType SigHashType,
key *btcec.PrivateKey) ([]byte, error) {
parsedScript, err := parseScript(subScript)
if err != nil {
return nil, fmt.Errorf("cannot parse output script: %v", err)
}
hash, err := calcWitnessSignatureHash(parsedScript, sigHashes, hashType, tx,
idx, amt)
if err != nil {
return nil, err
}
signature, err := key.Sign(hash)
if err != nil {
return nil, fmt.Errorf("cannot sign tx input: %s", err)
}
return append(signature.Serialize(), byte(hashType)), nil
}
// WitnessSignature creates an input witness stack for tx to spend BTC sent
// from a previous output to the owner of privKey using the p2wkh script
// template. The passed transaction must contain all the inputs and outputs as
// dictated by the passed hashType. The signature generated observes the new
// transaction digest algorithm defined within BIP0143.
func WitnessSignature(tx *wire.MsgTx, sigHashes *TxSigHashes, idx int, amt int64,
subscript []byte, hashType SigHashType, privKey *btcec.PrivateKey,
compress bool) (wire.TxWitness, error) {
sig, err := RawTxInWitnessSignature(tx, sigHashes, idx, amt, subscript,
hashType, privKey)
if err != nil {
return nil, err
}
pk := (*btcec.PublicKey)(&privKey.PublicKey)
var pkData []byte
if compress {
pkData = pk.SerializeCompressed()
} else {
pkData = pk.SerializeUncompressed()
}
// A witness script is actually a stack, so we return an array of byte
// slices here, rather than a single byte slice.
return wire.TxWitness{sig, pkData}, nil
}
// RawTxInSignature returns the serialized ECDSA signature for the input idx of
// the given transaction, with hashType appended to it.
func RawTxInSignature(tx *wire.MsgTx, idx int, subScript []byte,

View File

@ -53,10 +53,10 @@ func mkGetScript(scripts map[string][]byte) ScriptDB {
})
}
func checkScripts(msg string, tx *wire.MsgTx, idx int, inputAmt int64, sigScript, pkScript []byte) error {
func checkScripts(msg string, tx *wire.MsgTx, idx int, sigScript, pkScript []byte) error {
tx.TxIn[idx].SignatureScript = sigScript
vm, err := NewEngine(pkScript, tx, idx,
ScriptBip16|ScriptVerifyDERSignatures, nil, nil, inputAmt)
ScriptBip16|ScriptVerifyDERSignatures, nil)
if err != nil {
return fmt.Errorf("failed to make script engine for %s: %v",
msg, err)
@ -71,7 +71,7 @@ func checkScripts(msg string, tx *wire.MsgTx, idx int, inputAmt int64, sigScript
return nil
}
func signAndCheck(msg string, tx *wire.MsgTx, idx int, inputAmt int64, pkScript []byte,
func signAndCheck(msg string, tx *wire.MsgTx, idx int, pkScript []byte,
hashType SigHashType, kdb KeyDB, sdb ScriptDB,
previousScript []byte) error {
@ -81,7 +81,7 @@ func signAndCheck(msg string, tx *wire.MsgTx, idx int, inputAmt int64, pkScript
return fmt.Errorf("failed to sign output %s: %v", msg, err)
}
return checkScripts(msg, tx, idx, inputAmt, sigScript, pkScript)
return checkScripts(msg, tx, idx, sigScript, pkScript)
}
func TestSignTxOutput(t *testing.T) {
@ -99,7 +99,6 @@ func TestSignTxOutput(t *testing.T) {
SigHashNone | SigHashAnyOneCanPay,
SigHashSingle | SigHashAnyOneCanPay,
}
inputAmounts := []int64{5, 10, 15}
tx := &wire.MsgTx{
Version: 1,
TxIn: []*wire.TxIn{
@ -166,7 +165,7 @@ func TestSignTxOutput(t *testing.T) {
"for %s: %v", msg, err)
}
if err := signAndCheck(msg, tx, i, inputAmounts[i], pkScript, hashType,
if err := signAndCheck(msg, tx, i, pkScript, hashType,
mkGetKey(map[string]addressToKey{
address.EncodeAddress(): {key, false},
}), mkGetScript(nil), nil); err != nil {
@ -227,7 +226,7 @@ func TestSignTxOutput(t *testing.T) {
break
}
err = checkScripts(msg, tx, i, inputAmounts[i], sigScript, pkScript)
err = checkScripts(msg, tx, i, sigScript, pkScript)
if err != nil {
t.Errorf("twice signed script invalid for "+
"%s: %v", msg, err)
@ -264,8 +263,7 @@ func TestSignTxOutput(t *testing.T) {
"for %s: %v", msg, err)
}
if err := signAndCheck(msg, tx, i, inputAmounts[i],
pkScript, hashType,
if err := signAndCheck(msg, tx, i, pkScript, hashType,
mkGetKey(map[string]addressToKey{
address.EncodeAddress(): {key, true},
}), mkGetScript(nil), nil); err != nil {
@ -327,8 +325,7 @@ func TestSignTxOutput(t *testing.T) {
break
}
err = checkScripts(msg, tx, i, inputAmounts[i],
sigScript, pkScript)
err = checkScripts(msg, tx, i, sigScript, pkScript)
if err != nil {
t.Errorf("twice signed script invalid for "+
"%s: %v", msg, err)
@ -364,8 +361,7 @@ func TestSignTxOutput(t *testing.T) {
"for %s: %v", msg, err)
}
if err := signAndCheck(msg, tx, i, inputAmounts[i],
pkScript, hashType,
if err := signAndCheck(msg, tx, i, pkScript, hashType,
mkGetKey(map[string]addressToKey{
address.EncodeAddress(): {key, false},
}), mkGetScript(nil), nil); err != nil {
@ -426,7 +422,7 @@ func TestSignTxOutput(t *testing.T) {
break
}
err = checkScripts(msg, tx, i, inputAmounts[i], sigScript, pkScript)
err = checkScripts(msg, tx, i, sigScript, pkScript)
if err != nil {
t.Errorf("twice signed script invalid for "+
"%s: %v", msg, err)
@ -462,8 +458,7 @@ func TestSignTxOutput(t *testing.T) {
"for %s: %v", msg, err)
}
if err := signAndCheck(msg, tx, i, inputAmounts[i],
pkScript, hashType,
if err := signAndCheck(msg, tx, i, pkScript, hashType,
mkGetKey(map[string]addressToKey{
address.EncodeAddress(): {key, true},
}), mkGetScript(nil), nil); err != nil {
@ -524,8 +519,7 @@ func TestSignTxOutput(t *testing.T) {
break
}
err = checkScripts(msg, tx, i, inputAmounts[i],
sigScript, pkScript)
err = checkScripts(msg, tx, i, sigScript, pkScript)
if err != nil {
t.Errorf("twice signed script invalid for "+
"%s: %v", msg, err)
@ -579,8 +573,7 @@ func TestSignTxOutput(t *testing.T) {
break
}
if err := signAndCheck(msg, tx, i, inputAmounts[i],
scriptPkScript, hashType,
if err := signAndCheck(msg, tx, i, scriptPkScript, hashType,
mkGetKey(map[string]addressToKey{
address.EncodeAddress(): {key, false},
}), mkGetScript(map[string][]byte{
@ -664,8 +657,7 @@ func TestSignTxOutput(t *testing.T) {
break
}
err = checkScripts(msg, tx, i, inputAmounts[i],
sigScript, scriptPkScript)
err = checkScripts(msg, tx, i, sigScript, scriptPkScript)
if err != nil {
t.Errorf("twice signed script invalid for "+
"%s: %v", msg, err)
@ -718,8 +710,7 @@ func TestSignTxOutput(t *testing.T) {
break
}
if err := signAndCheck(msg, tx, i, inputAmounts[i],
scriptPkScript, hashType,
if err := signAndCheck(msg, tx, i, scriptPkScript, hashType,
mkGetKey(map[string]addressToKey{
address.EncodeAddress(): {key, true},
}), mkGetScript(map[string][]byte{
@ -803,8 +794,7 @@ func TestSignTxOutput(t *testing.T) {
break
}
err = checkScripts(msg, tx, i, inputAmounts[i],
sigScript, scriptPkScript)
err = checkScripts(msg, tx, i, sigScript, scriptPkScript)
if err != nil {
t.Errorf("twice signed script invalid for "+
"%s: %v", msg, err)
@ -856,8 +846,7 @@ func TestSignTxOutput(t *testing.T) {
break
}
if err := signAndCheck(msg, tx, i, inputAmounts[i],
scriptPkScript, hashType,
if err := signAndCheck(msg, tx, i, scriptPkScript, hashType,
mkGetKey(map[string]addressToKey{
address.EncodeAddress(): {key, false},
}), mkGetScript(map[string][]byte{
@ -939,8 +928,7 @@ func TestSignTxOutput(t *testing.T) {
break
}
err = checkScripts(msg, tx, i, inputAmounts[i],
sigScript, scriptPkScript)
err = checkScripts(msg, tx, i, sigScript, scriptPkScript)
if err != nil {
t.Errorf("twice signed script invalid for "+
"%s: %v", msg, err)
@ -991,8 +979,7 @@ func TestSignTxOutput(t *testing.T) {
break
}
if err := signAndCheck(msg, tx, i, inputAmounts[i],
scriptPkScript, hashType,
if err := signAndCheck(msg, tx, i, scriptPkScript, hashType,
mkGetKey(map[string]addressToKey{
address.EncodeAddress(): {key, true},
}), mkGetScript(map[string][]byte{
@ -1074,8 +1061,7 @@ func TestSignTxOutput(t *testing.T) {
break
}
err = checkScripts(msg, tx, i, inputAmounts[i],
sigScript, scriptPkScript)
err = checkScripts(msg, tx, i, sigScript, scriptPkScript)
if err != nil {
t.Errorf("twice signed script invalid for "+
"%s: %v", msg, err)
@ -1144,8 +1130,7 @@ func TestSignTxOutput(t *testing.T) {
break
}
if err := signAndCheck(msg, tx, i, inputAmounts[i],
scriptPkScript, hashType,
if err := signAndCheck(msg, tx, i, scriptPkScript, hashType,
mkGetKey(map[string]addressToKey{
address1.EncodeAddress(): {key1, true},
address2.EncodeAddress(): {key2, true},
@ -1232,8 +1217,7 @@ func TestSignTxOutput(t *testing.T) {
}
// Only 1 out of 2 signed, this *should* fail.
if checkScripts(msg, tx, i, inputAmounts[i], sigScript,
scriptPkScript) == nil {
if checkScripts(msg, tx, i, sigScript, scriptPkScript) == nil {
t.Errorf("part signed script valid for %s", msg)
break
}
@ -1251,8 +1235,7 @@ func TestSignTxOutput(t *testing.T) {
break
}
err = checkScripts(msg, tx, i, inputAmounts[i], sigScript,
scriptPkScript)
err = checkScripts(msg, tx, i, sigScript, scriptPkScript)
if err != nil {
t.Errorf("fully signed script invalid for "+
"%s: %v", msg, err)
@ -1336,8 +1319,7 @@ func TestSignTxOutput(t *testing.T) {
}
// Only 1 out of 2 signed, this *should* fail.
if checkScripts(msg, tx, i, inputAmounts[i], sigScript,
scriptPkScript) == nil {
if checkScripts(msg, tx, i, sigScript, scriptPkScript) == nil {
t.Errorf("part signed script valid for %s", msg)
break
}
@ -1357,8 +1339,7 @@ func TestSignTxOutput(t *testing.T) {
}
// Now we should pass.
err = checkScripts(msg, tx, i, inputAmounts[i],
sigScript, scriptPkScript)
err = checkScripts(msg, tx, i, sigScript, scriptPkScript)
if err != nil {
t.Errorf("fully signed script invalid for "+
"%s: %v", msg, err)
@ -1631,7 +1612,7 @@ nexttest:
tx.AddTxOut(output)
for range sigScriptTests[i].inputs {
txin := wire.NewTxIn(coinbaseOutPoint, nil, nil)
txin := wire.NewTxIn(coinbaseOutPoint, nil)
tx.AddTxIn(txin)
}
@ -1680,7 +1661,7 @@ nexttest:
scriptFlags := ScriptBip16 | ScriptVerifyDERSignatures
for j := range tx.TxIn {
vm, err := NewEngine(sigScriptTests[i].
inputs[j].txout.PkScript, tx, j, scriptFlags, nil, nil, 0)
inputs[j].txout.PkScript, tx, j, scriptFlags, nil)
if err != nil {
t.Errorf("cannot create script vm for test %v: %v",
sigScriptTests[i].name, err)

View File

@ -8,7 +8,6 @@ import (
"fmt"
"github.com/daglabs/btcd/chaincfg"
"github.com/daglabs/btcd/wire"
"github.com/daglabs/btcutil"
)
@ -38,11 +37,7 @@ const (
ScriptVerifyCheckLockTimeVerify |
ScriptVerifyCheckSequenceVerify |
ScriptVerifyLowS |
ScriptStrictMultiSig |
ScriptVerifyWitness |
ScriptVerifyDiscourageUpgradeableWitnessProgram |
ScriptVerifyMinimalIf |
ScriptVerifyWitnessPubKeyType
ScriptStrictMultiSig
)
// ScriptClass is an enumeration for the list of standard types of script.
@ -50,27 +45,23 @@ type ScriptClass byte
// Classes of script payment known about in the blockchain.
const (
NonStandardTy ScriptClass = iota // None of the recognized forms.
PubKeyTy // Pay pubkey.
PubKeyHashTy // Pay pubkey hash.
WitnessV0PubKeyHashTy // Pay witness pubkey hash.
ScriptHashTy // Pay to script hash.
WitnessV0ScriptHashTy // Pay to witness script hash.
MultiSigTy // Multi signature.
NullDataTy // Empty data-only (provably prunable).
NonStandardTy ScriptClass = iota // None of the recognized forms.
PubKeyTy // Pay pubkey.
PubKeyHashTy // Pay pubkey hash.
ScriptHashTy // Pay to script hash.
MultiSigTy // Multi signature.
NullDataTy // Empty data-only (provably prunable).
)
// scriptClassToName houses the human-readable strings which describe each
// script class.
var scriptClassToName = []string{
NonStandardTy: "nonstandard",
PubKeyTy: "pubkey",
PubKeyHashTy: "pubkeyhash",
WitnessV0PubKeyHashTy: "witness_v0_keyhash",
ScriptHashTy: "scripthash",
WitnessV0ScriptHashTy: "witness_v0_scripthash",
MultiSigTy: "multisig",
NullDataTy: "nulldata",
NonStandardTy: "nonstandard",
PubKeyTy: "pubkey",
PubKeyHashTy: "pubkeyhash",
ScriptHashTy: "scripthash",
MultiSigTy: "multisig",
NullDataTy: "nulldata",
}
// String implements the Stringer interface by returning the name of
@ -163,12 +154,8 @@ func typeOfScript(pops []parsedOpcode) ScriptClass {
return PubKeyTy
} else if isPubkeyHash(pops) {
return PubKeyHashTy
} else if isWitnessPubKeyHash(pops) {
return WitnessV0PubKeyHashTy
} else if isScriptHash(pops) {
return ScriptHashTy
} else if isWitnessScriptHash(pops) {
return WitnessV0ScriptHashTy
} else if isMultiSig(pops) {
return MultiSigTy
} else if isNullData(pops) {
@ -201,17 +188,10 @@ func expectedInputs(pops []parsedOpcode, class ScriptClass) int {
case PubKeyHashTy:
return 2
case WitnessV0PubKeyHashTy:
return 2
case ScriptHashTy:
// Not including script. That is handled by the caller.
return 1
case WitnessV0ScriptHashTy:
// Not including script. That is handled by the caller.
return 1
case MultiSigTy:
// Standard multisig has a push a small number for the number
// of sigs and number of keys. Check the first push instruction
@ -252,9 +232,7 @@ type ScriptInfo struct {
// pair. It will error if the pair is in someway invalid such that they can not
// be analysed, i.e. if they do not parse or the pkScript is not a push-only
// script
func CalcScriptInfo(sigScript, pkScript []byte, witness wire.TxWitness,
bip16, segwit bool) (*ScriptInfo, error) {
func CalcScriptInfo(sigScript, pkScript []byte, bip16 bool) (*ScriptInfo, error) {
sigPops, err := parseScript(sigScript)
if err != nil {
return nil, err
@ -277,9 +255,10 @@ func CalcScriptInfo(sigScript, pkScript []byte, witness wire.TxWitness,
si.ExpectedInputs = expectedInputs(pkPops, si.PkScriptClass)
switch {
// Count sigops taking into account pay-to-script-hash.
case si.PkScriptClass == ScriptHashTy && bip16 && !segwit:
// All entries pushed to stack (or are OP_RESERVED and exec will fail).
si.NumInputs = len(sigPops)
if si.PkScriptClass == ScriptHashTy && bip16 {
// The pay-to-hash-script is the final data push of the
// signature script.
script := sigPops[len(sigPops)-1].data
@ -295,62 +274,8 @@ func CalcScriptInfo(sigScript, pkScript []byte, witness wire.TxWitness,
si.ExpectedInputs += shInputs
}
si.SigOps = getSigOpCount(shPops, true)
// All entries pushed to stack (or are OP_RESERVED and exec
// will fail).
si.NumInputs = len(sigPops)
// If segwit is active, and this is a regular p2wkh output, then we'll
// treat the script as a p2pkh output in essence.
case si.PkScriptClass == WitnessV0PubKeyHashTy && segwit:
si.SigOps = GetWitnessSigOpCount(sigScript, pkScript, witness)
si.NumInputs = len(witness)
// We'll attempt to detect the nested p2sh case so we can accurately
// count the signature operations involved.
case si.PkScriptClass == ScriptHashTy &&
IsWitnessProgram(sigScript[1:]) && bip16 && segwit:
// Extract the pushed witness program from the sigScript so we
// can determine the number of expected inputs.
pkPops, _ := parseScript(sigScript[1:])
shInputs := expectedInputs(pkPops, typeOfScript(pkPops))
if shInputs == -1 {
si.ExpectedInputs = -1
} else {
si.ExpectedInputs += shInputs
}
si.SigOps = GetWitnessSigOpCount(sigScript, pkScript, witness)
si.NumInputs = len(witness)
si.NumInputs += len(sigPops)
// If segwit is active, and this is a p2wsh output, then we'll need to
// examine the witness script to generate accurate script info.
case si.PkScriptClass == WitnessV0ScriptHashTy && segwit:
// The witness script is the final element of the witness
// stack.
witnessScript := witness[len(witness)-1]
pops, _ := parseScript(witnessScript)
shInputs := expectedInputs(pops, typeOfScript(pops))
if shInputs == -1 {
si.ExpectedInputs = -1
} else {
si.ExpectedInputs += shInputs
}
si.SigOps = GetWitnessSigOpCount(sigScript, pkScript, witness)
si.NumInputs = len(witness)
default:
} else {
si.SigOps = getSigOpCount(pkPops, true)
// All entries pushed to stack (or are OP_RESERVED and exec
// will fail).
si.NumInputs = len(sigPops)
}
return si, nil
@ -391,12 +316,6 @@ func payToPubKeyHashScript(pubKeyHash []byte) ([]byte, error) {
Script()
}
// payToWitnessPubKeyHashScript creates a new script to pay to a version 0
// pubkey hash witness program. The passed hash is expected to be valid.
func payToWitnessPubKeyHashScript(pubKeyHash []byte) ([]byte, error) {
return NewScriptBuilder().AddOp(OP_0).AddData(pubKeyHash).Script()
}
// payToScriptHashScript creates a new script to pay a transaction output to a
// script hash. It is expected that the input is a valid hash.
func payToScriptHashScript(scriptHash []byte) ([]byte, error) {
@ -404,12 +323,6 @@ func payToScriptHashScript(scriptHash []byte) ([]byte, error) {
AddOp(OP_EQUAL).Script()
}
// payToWitnessPubKeyHashScript creates a new script to pay to a version 0
// script hash witness program. The passed hash is expected to be valid.
func payToWitnessScriptHashScript(scriptHash []byte) ([]byte, error) {
return NewScriptBuilder().AddOp(OP_0).AddData(scriptHash).Script()
}
// payToPubkeyScript creates a new script to pay a transaction output to a
// public key. It is expected that the input is a valid pubkey.
func payToPubKeyScript(serializedPubKey []byte) ([]byte, error) {
@ -443,19 +356,6 @@ func PayToAddrScript(addr btcutil.Address) ([]byte, error) {
nilAddrErrStr)
}
return payToPubKeyScript(addr.ScriptAddress())
case *btcutil.AddressWitnessPubKeyHash:
if addr == nil {
return nil, scriptError(ErrUnsupportedAddress,
nilAddrErrStr)
}
return payToWitnessPubKeyHashScript(addr.ScriptAddress())
case *btcutil.AddressWitnessScriptHash:
if addr == nil {
return nil, scriptError(ErrUnsupportedAddress,
nilAddrErrStr)
}
return payToWitnessScriptHashScript(addr.ScriptAddress())
}
str := fmt.Sprintf("unable to generate payment script for unsupported "+
@ -546,18 +446,6 @@ func ExtractPkScriptAddrs(pkScript []byte, chainParams *chaincfg.Params) (Script
addrs = append(addrs, addr)
}
case WitnessV0PubKeyHashTy:
// A pay-to-witness-pubkey-hash script is of thw form:
// OP_0 <20-byte hash>
// Therefore, the pubkey hash is the second item on the stack.
// Skip the pubkey hash if it's invalid for some reason.
requiredSigs = 1
addr, err := btcutil.NewAddressWitnessPubKeyHash(pops[1].data,
chainParams)
if err == nil {
addrs = append(addrs, addr)
}
case PubKeyTy:
// A pay-to-pubkey script is of the form:
// <pubkey> OP_CHECKSIG
@ -581,18 +469,6 @@ func ExtractPkScriptAddrs(pkScript []byte, chainParams *chaincfg.Params) (Script
addrs = append(addrs, addr)
}
case WitnessV0ScriptHashTy:
// A pay-to-witness-script-hash script is of the form:
// OP_0 <32-byte hash>
// Therefore, the script hash is the second item on the stack.
// Skip the script hash if it's invalid for some reason.
requiredSigs = 1
addr, err := btcutil.NewAddressWitnessScriptHash(pops[1].data,
chainParams)
if err == nil {
addrs = append(addrs, addr)
}
case MultiSigTy:
// A multi-signature script is of the form:
// <numsigs> <pubkey> <pubkey> <pubkey>... <numpubkeys> OP_CHECKMULTISIG

View File

@ -6,12 +6,10 @@ package txscript
import (
"bytes"
"encoding/hex"
"reflect"
"testing"
"github.com/daglabs/btcd/chaincfg"
"github.com/daglabs/btcd/wire"
"github.com/daglabs/btcutil"
)
@ -380,10 +378,8 @@ func TestCalcScriptInfo(t *testing.T) {
name string
sigScript string
pkScript string
witness []string
bip16 bool
segwit bool
bip16 bool
scriptInfo ScriptInfo
scriptInfoErr error
@ -461,91 +457,13 @@ func TestCalcScriptInfo(t *testing.T) {
SigOps: 3,
},
},
{
// A v0 p2wkh spend.
name: "p2wkh script",
pkScript: "OP_0 DATA_20 0x365ab47888e150ff46f8d51bce36dcd680f1283f",
witness: []string{
"3045022100ee9fe8f9487afa977" +
"6647ebcf0883ce0cd37454d7ce19889d34ba2c9" +
"9ce5a9f402200341cb469d0efd3955acb9e46" +
"f568d7e2cc10f9084aaff94ced6dc50a59134ad01",
"03f0000d0639a22bfaf217e4c9428" +
"9c2b0cc7fa1036f7fd5d9f61a9d6ec153100e",
},
segwit: true,
scriptInfo: ScriptInfo{
PkScriptClass: WitnessV0PubKeyHashTy,
NumInputs: 2,
ExpectedInputs: 2,
SigOps: 1,
},
},
{
// Nested p2sh v0
name: "p2wkh nested inside p2sh",
pkScript: "HASH160 DATA_20 " +
"0xb3a84b564602a9d68b4c9f19c2ea61458ff7826c EQUAL",
sigScript: "DATA_22 0x0014ad0ffa2e387f07e7ead14dc56d5a97dbd6ff5a23",
witness: []string{
"3045022100cb1c2ac1ff1d57d" +
"db98f7bdead905f8bf5bcc8641b029ce8eef25" +
"c75a9e22a4702203be621b5c86b771288706be5" +
"a7eee1db4fceabf9afb7583c1cc6ee3f8297b21201",
"03f0000d0639a22bfaf217e4c9" +
"4289c2b0cc7fa1036f7fd5d9f61a9d6ec153100e",
},
segwit: true,
bip16: true,
scriptInfo: ScriptInfo{
PkScriptClass: ScriptHashTy,
NumInputs: 3,
ExpectedInputs: 3,
SigOps: 1,
},
},
{
// A v0 p2wsh spend.
name: "p2wsh spend of a p2wkh witness script",
pkScript: "0 DATA_32 0xe112b88a0cd87ba387f44" +
"9d443ee2596eb353beb1f0351ab2cba8909d875db23",
witness: []string{
"3045022100cb1c2ac1ff1d57d" +
"db98f7bdead905f8bf5bcc8641b029ce8eef25" +
"c75a9e22a4702203be621b5c86b771288706be5" +
"a7eee1db4fceabf9afb7583c1cc6ee3f8297b21201",
"03f0000d0639a22bfaf217e4c9" +
"4289c2b0cc7fa1036f7fd5d9f61a9d6ec153100e",
"76a914064977cb7b4a2e0c9680df0ef696e9e0e296b39988ac",
},
segwit: true,
scriptInfo: ScriptInfo{
PkScriptClass: WitnessV0ScriptHashTy,
NumInputs: 3,
ExpectedInputs: 3,
SigOps: 1,
},
},
}
for _, test := range tests {
sigScript := mustParseShortForm(test.sigScript)
pkScript := mustParseShortForm(test.pkScript)
var witness wire.TxWitness
for _, witElement := range test.witness {
wit, err := hex.DecodeString(witElement)
if err != nil {
t.Fatalf("unable to decode witness "+
"element: %v", err)
}
witness = append(witness, wit)
}
si, err := CalcScriptInfo(sigScript, pkScript, witness,
test.bip16, test.segwit)
si, err := CalcScriptInfo(sigScript, pkScript, test.bip16)
if e := tstCheckScriptError(err, test.scriptInfoErr); e != nil {
t.Errorf("scriptinfo test %q: %v", test.name, e)
continue
@ -1025,20 +943,6 @@ var scriptClassTests = []struct {
"3 CHECKMULTISIG",
class: NonStandardTy,
},
// New standard segwit script templates.
{
// A pay to witness pub key hash pk script.
name: "Pay To Witness PubkeyHash",
script: "0 DATA_20 0x1d0f172a0ecb48aee1be1f2687d2963ae33f71a1",
class: WitnessV0PubKeyHashTy,
},
{
// A pay to witness scripthash pk script.
name: "Pay To Witness Scripthash",
script: "0 DATA_32 0x9f96ade4b41d5433f4eda31e1738ec2b36f6e7d1420d94a6af99801a88f7f7ff",
class: WitnessV0ScriptHashTy,
},
}
// TestScriptClass ensures all the scripts in scriptClassTests have the expected
@ -1082,21 +986,11 @@ func TestStringifyClass(t *testing.T) {
class: PubKeyHashTy,
stringed: "pubkeyhash",
},
{
name: "witnesspubkeyhash",
class: WitnessV0PubKeyHashTy,
stringed: "witness_v0_keyhash",
},
{
name: "scripthash",
class: ScriptHashTy,
stringed: "scripthash",
},
{
name: "witnessscripthash",
class: WitnessV0ScriptHashTy,
stringed: "witness_v0_scripthash",
},
{
name: "multisigty",
class: MultiSigTy,

View File

@ -394,7 +394,7 @@ func BenchmarkDecodeGetHeaders(b *testing.B) {
// Serialize it so the bytes are available to test the decode below.
var bb bytes.Buffer
if err := m.BtcEncode(&bb, pver, LatestEncoding); err != nil {
if err := m.BtcEncode(&bb, pver); err != nil {
b.Fatalf("MsgGetHeaders.BtcEncode: unexpected error: %v", err)
}
buf := bb.Bytes()
@ -404,7 +404,7 @@ func BenchmarkDecodeGetHeaders(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
r.Seek(0, 0)
msg.BtcDecode(r, pver, LatestEncoding)
msg.BtcDecode(r, pver)
}
}
@ -424,7 +424,7 @@ func BenchmarkDecodeHeaders(b *testing.B) {
// Serialize it so the bytes are available to test the decode below.
var bb bytes.Buffer
if err := m.BtcEncode(&bb, pver, LatestEncoding); err != nil {
if err := m.BtcEncode(&bb, pver); err != nil {
b.Fatalf("MsgHeaders.BtcEncode: unexpected error: %v", err)
}
buf := bb.Bytes()
@ -434,7 +434,7 @@ func BenchmarkDecodeHeaders(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
r.Seek(0, 0)
msg.BtcDecode(r, pver, LatestEncoding)
msg.BtcDecode(r, pver)
}
}
@ -454,7 +454,7 @@ func BenchmarkDecodeGetBlocks(b *testing.B) {
// Serialize it so the bytes are available to test the decode below.
var bb bytes.Buffer
if err := m.BtcEncode(&bb, pver, LatestEncoding); err != nil {
if err := m.BtcEncode(&bb, pver); err != nil {
b.Fatalf("MsgGetBlocks.BtcEncode: unexpected error: %v", err)
}
buf := bb.Bytes()
@ -464,7 +464,7 @@ func BenchmarkDecodeGetBlocks(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
r.Seek(0, 0)
msg.BtcDecode(r, pver, LatestEncoding)
msg.BtcDecode(r, pver)
}
}
@ -481,7 +481,7 @@ func BenchmarkDecodeAddr(b *testing.B) {
// Serialize it so the bytes are available to test the decode below.
var bb bytes.Buffer
if err := ma.BtcEncode(&bb, pver, LatestEncoding); err != nil {
if err := ma.BtcEncode(&bb, pver); err != nil {
b.Fatalf("MsgAddr.BtcEncode: unexpected error: %v", err)
}
buf := bb.Bytes()
@ -491,7 +491,7 @@ func BenchmarkDecodeAddr(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
r.Seek(0, 0)
msg.BtcDecode(r, pver, LatestEncoding)
msg.BtcDecode(r, pver)
}
}
@ -511,7 +511,7 @@ func BenchmarkDecodeInv(b *testing.B) {
// Serialize it so the bytes are available to test the decode below.
var bb bytes.Buffer
if err := m.BtcEncode(&bb, pver, LatestEncoding); err != nil {
if err := m.BtcEncode(&bb, pver); err != nil {
b.Fatalf("MsgInv.BtcEncode: unexpected error: %v", err)
}
buf := bb.Bytes()
@ -521,7 +521,7 @@ func BenchmarkDecodeInv(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
r.Seek(0, 0)
msg.BtcDecode(r, pver, LatestEncoding)
msg.BtcDecode(r, pver)
}
}
@ -541,7 +541,7 @@ func BenchmarkDecodeNotFound(b *testing.B) {
// Serialize it so the bytes are available to test the decode below.
var bb bytes.Buffer
if err := m.BtcEncode(&bb, pver, LatestEncoding); err != nil {
if err := m.BtcEncode(&bb, pver); err != nil {
b.Fatalf("MsgNotFound.BtcEncode: unexpected error: %v", err)
}
buf := bb.Bytes()
@ -551,7 +551,7 @@ func BenchmarkDecodeNotFound(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
r.Seek(0, 0)
msg.BtcDecode(r, pver, LatestEncoding)
msg.BtcDecode(r, pver)
}
}
@ -579,7 +579,7 @@ func BenchmarkDecodeMerkleBlock(b *testing.B) {
// Serialize it so the bytes are available to test the decode below.
var bb bytes.Buffer
if err := m.BtcEncode(&bb, pver, LatestEncoding); err != nil {
if err := m.BtcEncode(&bb, pver); err != nil {
b.Fatalf("MsgMerkleBlock.BtcEncode: unexpected error: %v", err)
}
buf := bb.Bytes()
@ -589,7 +589,7 @@ func BenchmarkDecodeMerkleBlock(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
r.Seek(0, 0)
msg.BtcDecode(r, pver, LatestEncoding)
msg.BtcDecode(r, pver)
}
}

View File

@ -60,7 +60,7 @@ func (h *BlockHeader) BlockHash() chainhash.Hash {
// This is part of the Message interface implementation.
// See Deserialize for decoding block headers stored to disk, such as in a
// database, as opposed to decoding block headers from the wire.
func (h *BlockHeader) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error {
func (h *BlockHeader) BtcDecode(r io.Reader, pver uint32) error {
return readBlockHeader(r, pver, h)
}
@ -68,7 +68,7 @@ func (h *BlockHeader) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) e
// This is part of the Message interface implementation.
// See Serialize for encoding block headers to be stored to disk, such as in a
// database, as opposed to encoding block headers for the wire.
func (h *BlockHeader) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {
func (h *BlockHeader) BtcEncode(w io.Writer, pver uint32) error {
return writeBlockHeader(w, pver, h)
}

View File

@ -79,11 +79,10 @@ func TestBlockHeaderWire(t *testing.T) {
}
tests := []struct {
in *BlockHeader // Data to encode
out *BlockHeader // Expected decoded data
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
enc MessageEncoding // Message encoding variant to use
in *BlockHeader // Data to encode
out *BlockHeader // Expected decoded data
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
}{
// Latest protocol version.
{
@ -91,7 +90,6 @@ func TestBlockHeaderWire(t *testing.T) {
baseBlockHdr,
baseBlockHdrEncoded,
ProtocolVersion,
BaseEncoding,
},
// Protocol version BIP0035Version.
@ -100,7 +98,6 @@ func TestBlockHeaderWire(t *testing.T) {
baseBlockHdr,
baseBlockHdrEncoded,
BIP0035Version,
BaseEncoding,
},
// Protocol version BIP0031Version.
@ -109,7 +106,6 @@ func TestBlockHeaderWire(t *testing.T) {
baseBlockHdr,
baseBlockHdrEncoded,
BIP0031Version,
BaseEncoding,
},
// Protocol version NetAddressTimeVersion.
@ -118,7 +114,6 @@ func TestBlockHeaderWire(t *testing.T) {
baseBlockHdr,
baseBlockHdrEncoded,
NetAddressTimeVersion,
BaseEncoding,
},
// Protocol version MultipleAddressVersion.
@ -127,7 +122,6 @@ func TestBlockHeaderWire(t *testing.T) {
baseBlockHdr,
baseBlockHdrEncoded,
MultipleAddressVersion,
BaseEncoding,
},
}
@ -147,7 +141,7 @@ func TestBlockHeaderWire(t *testing.T) {
}
buf.Reset()
err = test.in.BtcEncode(&buf, pver, 0)
err = test.in.BtcEncode(&buf, pver)
if err != nil {
t.Errorf("BtcEncode #%d error %v", i, err)
continue
@ -173,7 +167,7 @@ func TestBlockHeaderWire(t *testing.T) {
}
rbuf = bytes.NewReader(test.buf)
err = bh.BtcDecode(rbuf, pver, test.enc)
err = bh.BtcDecode(rbuf, pver)
if err != nil {
t.Errorf("BtcDecode #%d error %v", i, err)
continue

View File

@ -17,14 +17,14 @@ type fakeMessage struct {
// BtcDecode doesn't do anything. It just satisfies the wire.Message
// interface.
func (msg *fakeMessage) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error {
func (msg *fakeMessage) BtcDecode(r io.Reader, pver uint32) error {
return nil
}
// BtcEncode writes the payload field of the fake message or forces an error
// if the forceEncodeErr flag of the fake message is set. It also satisfies the
// wire.Message interface.
func (msg *fakeMessage) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {
func (msg *fakeMessage) BtcEncode(w io.Writer, pver uint32) error {
if msg.forceEncodeErr {
err := &MessageError{
Func: "fakeMessage.BtcEncode",

View File

@ -18,10 +18,6 @@ const (
// Maximum payload size for an inventory vector.
maxInvVectPayload = 4 + chainhash.HashSize
// InvWitnessFlag denotes that the inventory vector type is requesting,
// or sending a version which includes witness data.
InvWitnessFlag = 1 << 30
)
// InvType represents the allowed types of inventory vectors. See InvVect.
@ -29,24 +25,18 @@ type InvType uint32
// These constants define the various supported inventory vector types.
const (
InvTypeError InvType = 0
InvTypeTx InvType = 1
InvTypeBlock InvType = 2
InvTypeFilteredBlock InvType = 3
InvTypeWitnessBlock InvType = InvTypeBlock | InvWitnessFlag
InvTypeWitnessTx InvType = InvTypeTx | InvWitnessFlag
InvTypeFilteredWitnessBlock InvType = InvTypeFilteredBlock | InvWitnessFlag
InvTypeError InvType = 0
InvTypeTx InvType = 1
InvTypeBlock InvType = 2
InvTypeFilteredBlock InvType = 3
)
// Map of service flags back to their constant names for pretty printing.
var ivStrings = map[InvType]string{
InvTypeError: "ERROR",
InvTypeTx: "MSG_TX",
InvTypeBlock: "MSG_BLOCK",
InvTypeFilteredBlock: "MSG_FILTERED_BLOCK",
InvTypeWitnessBlock: "MSG_WITNESS_BLOCK",
InvTypeWitnessTx: "MSG_WITNESS_TX",
InvTypeFilteredWitnessBlock: "MSG_FILTERED_WITNESS_BLOCK",
InvTypeError: "ERROR",
InvTypeTx: "MSG_TX",
InvTypeBlock: "MSG_BLOCK",
InvTypeFilteredBlock: "MSG_FILTERED_BLOCK",
}
// String returns the InvType in human-readable form.

View File

@ -59,31 +59,13 @@ const (
CmdCFCheckpt = "cfcheckpt"
)
// MessageEncoding represents the wire message encoding format to be used.
type MessageEncoding uint32
const (
// BaseEncoding encodes all messages in the default format specified
// for the Bitcoin wire protocol.
BaseEncoding MessageEncoding = 1 << iota
// WitnessEncoding encodes all messages other than transaction messages
// using the default Bitcoin wire protocol specification. For transaction
// messages, the new encoding format detailed in BIP0144 will be used.
WitnessEncoding
)
// LatestEncoding is the most recently specified encoding for the Bitcoin wire
// protocol.
var LatestEncoding = WitnessEncoding
// Message is an interface that describes a bitcoin message. A type that
// implements Message has complete control over the representation of its data
// and may therefore contain additional or fewer fields than those which
// are used directly in the protocol encoded message.
type Message interface {
BtcDecode(io.Reader, uint32, MessageEncoding) error
BtcEncode(io.Writer, uint32, MessageEncoding) error
BtcDecode(io.Reader, uint32) error
BtcEncode(io.Writer, uint32) error
Command() string
MaxPayloadLength(uint32) uint32
}
@ -242,27 +224,6 @@ func discardInput(r io.Reader, n uint32) {
// information and returns the number of bytes written. This function is the
// same as WriteMessage except it also returns the number of bytes written.
func WriteMessageN(w io.Writer, msg Message, pver uint32, btcnet BitcoinNet) (int, error) {
return WriteMessageWithEncodingN(w, msg, pver, btcnet, BaseEncoding)
}
// WriteMessage writes a bitcoin Message to w including the necessary header
// information. This function is the same as WriteMessageN except it doesn't
// doesn't return the number of bytes written. This function is mainly provided
// for backwards compatibility with the original API, but it's also useful for
// callers that don't care about byte counts.
func WriteMessage(w io.Writer, msg Message, pver uint32, btcnet BitcoinNet) error {
_, err := WriteMessageN(w, msg, pver, btcnet)
return err
}
// WriteMessageWithEncodingN writes a bitcoin Message to w including the
// necessary header information and returns the number of bytes written.
// This function is the same as WriteMessageN except it also allows the caller
// to specify the message encoding format to be used when serializing wire
// messages.
func WriteMessageWithEncodingN(w io.Writer, msg Message, pver uint32,
btcnet BitcoinNet, encoding MessageEncoding) (int, error) {
totalBytes := 0
// Enforce max command size.
@ -277,7 +238,7 @@ func WriteMessageWithEncodingN(w io.Writer, msg Message, pver uint32,
// Encode the message payload.
var bw bytes.Buffer
err := msg.BtcEncode(&bw, pver, encoding)
err := msg.BtcEncode(&bw, pver)
if err != nil {
return totalBytes, err
}
@ -327,15 +288,22 @@ func WriteMessageWithEncodingN(w io.Writer, msg Message, pver uint32,
return totalBytes, err
}
// ReadMessageWithEncodingN reads, validates, and parses the next bitcoin Message
// from r for the provided protocol version and bitcoin network. It returns the
// number of bytes read in addition to the parsed Message and raw bytes which
// comprise the message. This function is the same as ReadMessageN except it
// allows the caller to specify which message encoding is to to consult when
// decoding wire messages.
func ReadMessageWithEncodingN(r io.Reader, pver uint32, btcnet BitcoinNet,
enc MessageEncoding) (int, Message, []byte, error) {
// WriteMessage writes a bitcoin Message to w including the necessary header
// information. This function is the same as WriteMessageN except it doesn't
// doesn't return the number of bytes written. This function is mainly provided
// for backwards compatibility with the original API, but it's also useful for
// callers that don't care about byte counts.
func WriteMessage(w io.Writer, msg Message, pver uint32, btcnet BitcoinNet) error {
_, err := WriteMessageN(w, msg, pver, btcnet)
return err
}
// ReadMessageN reads, validates, and parses the next bitcoin Message from r for
// the provided protocol version and bitcoin network. It returns the number of
// bytes read in addition to the parsed Message and raw bytes which comprise the
// message. This function is the same as ReadMessage except it also returns the
// number of bytes read.
func ReadMessageN(r io.Reader, pver uint32, btcnet BitcoinNet) (int, Message, []byte, error) {
totalBytes := 0
n, hdr, err := readMessageHeader(r)
totalBytes += n
@ -407,7 +375,7 @@ func ReadMessageWithEncodingN(r io.Reader, pver uint32, btcnet BitcoinNet,
// Unmarshal message. NOTE: This must be a *bytes.Buffer since the
// MsgVersion BtcDecode function requires it.
pr := bytes.NewBuffer(payload)
err = msg.BtcDecode(pr, pver, enc)
err = msg.BtcDecode(pr, pver)
if err != nil {
return totalBytes, nil, nil, err
}
@ -415,15 +383,6 @@ func ReadMessageWithEncodingN(r io.Reader, pver uint32, btcnet BitcoinNet,
return totalBytes, msg, payload, nil
}
// ReadMessageN reads, validates, and parses the next bitcoin Message from r for
// the provided protocol version and bitcoin network. It returns the number of
// bytes read in addition to the parsed Message and raw bytes which comprise the
// message. This function is the same as ReadMessage except it also returns the
// number of bytes read.
func ReadMessageN(r io.Reader, pver uint32, btcnet BitcoinNet) (int, Message, []byte, error) {
return ReadMessageWithEncodingN(r, pver, btcnet, BaseEncoding)
}
// ReadMessage reads, validates, and parses the next bitcoin Message from r for
// the provided protocol version and bitcoin network. It returns the parsed
// Message and raw bytes which comprise the message. This function only differs

View File

@ -57,7 +57,7 @@ func (msg *MsgAddr) ClearAddresses() {
// BtcDecode decodes r using the bitcoin protocol encoding into the receiver.
// This is part of the Message interface implementation.
func (msg *MsgAddr) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error {
func (msg *MsgAddr) BtcDecode(r io.Reader, pver uint32) error {
count, err := ReadVarInt(r, pver)
if err != nil {
return err
@ -85,7 +85,7 @@ func (msg *MsgAddr) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) err
// BtcEncode encodes the receiver to w using the bitcoin protocol encoding.
// This is part of the Message interface implementation.
func (msg *MsgAddr) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {
func (msg *MsgAddr) BtcEncode(w io.Writer, pver uint32) error {
// Protocol versions before MultipleAddressVersion only allowed 1 address
// per message.
count := len(msg.AddrList)

View File

@ -139,11 +139,10 @@ func TestAddrWire(t *testing.T) {
}
tests := []struct {
in *MsgAddr // Message to encode
out *MsgAddr // Expected decoded message
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
enc MessageEncoding // Message encoding format
in *MsgAddr // Message to encode
out *MsgAddr // Expected decoded message
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
}{
// Latest protocol version with no addresses.
{
@ -151,7 +150,6 @@ func TestAddrWire(t *testing.T) {
noAddr,
noAddrEncoded,
ProtocolVersion,
BaseEncoding,
},
// Latest protocol version with multiple addresses.
@ -160,7 +158,6 @@ func TestAddrWire(t *testing.T) {
multiAddr,
multiAddrEncoded,
ProtocolVersion,
BaseEncoding,
},
// Protocol version MultipleAddressVersion-1 with no addresses.
@ -169,7 +166,6 @@ func TestAddrWire(t *testing.T) {
noAddr,
noAddrEncoded,
MultipleAddressVersion - 1,
BaseEncoding,
},
}
@ -177,7 +173,7 @@ func TestAddrWire(t *testing.T) {
for i, test := range tests {
// Encode the message to wire format.
var buf bytes.Buffer
err := test.in.BtcEncode(&buf, test.pver, test.enc)
err := test.in.BtcEncode(&buf, test.pver)
if err != nil {
t.Errorf("BtcEncode #%d error %v", i, err)
continue
@ -191,7 +187,7 @@ func TestAddrWire(t *testing.T) {
// Decode the message from wire format.
var msg MsgAddr
rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver, test.enc)
err = msg.BtcDecode(rbuf, test.pver)
if err != nil {
t.Errorf("BtcDecode #%d error %v", i, err)
continue
@ -255,31 +251,30 @@ func TestAddrWireErrors(t *testing.T) {
}
tests := []struct {
in *MsgAddr // Value to encode
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
enc MessageEncoding // Message encoding format
max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error
readErr error // Expected read error
in *MsgAddr // Value to encode
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error
readErr error // Expected read error
}{
// Latest protocol version with intentional read/write errors.
// Force error in addresses count
{baseAddr, baseAddrEncoded, pver, BaseEncoding, 0, io.ErrShortWrite, io.EOF},
{baseAddr, baseAddrEncoded, pver, 0, io.ErrShortWrite, io.EOF},
// Force error in address list.
{baseAddr, baseAddrEncoded, pver, BaseEncoding, 1, io.ErrShortWrite, io.EOF},
{baseAddr, baseAddrEncoded, pver, 1, io.ErrShortWrite, io.EOF},
// Force error with greater than max inventory vectors.
{maxAddr, maxAddrEncoded, pver, BaseEncoding, 3, wireErr, wireErr},
{maxAddr, maxAddrEncoded, pver, 3, wireErr, wireErr},
// Force error with greater than max inventory vectors for
// protocol versions before multiple addresses were allowed.
{maxAddr, maxAddrEncoded, pverMA - 1, BaseEncoding, 3, wireErr, wireErr},
{maxAddr, maxAddrEncoded, pverMA - 1, 3, wireErr, wireErr},
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
// Encode to wire format.
w := newFixedWriter(test.max)
err := test.in.BtcEncode(w, test.pver, test.enc)
err := test.in.BtcEncode(w, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.writeErr) {
t.Errorf("BtcEncode #%d wrong error got: %v, want: %v",
i, err, test.writeErr)
@ -299,7 +294,7 @@ func TestAddrWireErrors(t *testing.T) {
// Decode from wire format.
var msg MsgAddr
r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver, test.enc)
err = msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) {
t.Errorf("BtcDecode #%d wrong error got: %v, want: %v",
i, err, test.readErr)

View File

@ -333,7 +333,7 @@ type MsgAlert struct {
// BtcDecode decodes r using the bitcoin protocol encoding into the receiver.
// This is part of the Message interface implementation.
func (msg *MsgAlert) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error {
func (msg *MsgAlert) BtcDecode(r io.Reader, pver uint32) error {
var err error
msg.SerializedPayload, err = ReadVarBytes(r, pver, MaxMessagePayload,
@ -354,7 +354,7 @@ func (msg *MsgAlert) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) er
// BtcEncode encodes the receiver to w using the bitcoin protocol encoding.
// This is part of the Message interface implementation.
func (msg *MsgAlert) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {
func (msg *MsgAlert) BtcEncode(w io.Writer, pver uint32) error {
var err error
var serializedpayload []byte
if msg.Payload != nil {

View File

@ -16,7 +16,6 @@ import (
// TestMsgAlert tests the MsgAlert API.
func TestMsgAlert(t *testing.T) {
pver := ProtocolVersion
encoding := BaseEncoding
serializedpayload := []byte("some message")
signature := []byte("some sig")
@ -49,7 +48,7 @@ func TestMsgAlert(t *testing.T) {
// Test BtcEncode with Payload == nil
var buf bytes.Buffer
err := msg.BtcEncode(&buf, pver, encoding)
err := msg.BtcEncode(&buf, pver)
if err != nil {
t.Error(err.Error())
}
@ -66,7 +65,7 @@ func TestMsgAlert(t *testing.T) {
// note: Payload is an empty Alert but not nil
msg.Payload = new(Alert)
buf = *new(bytes.Buffer)
err = msg.BtcEncode(&buf, pver, encoding)
err = msg.BtcEncode(&buf, pver)
if err != nil {
t.Error(err.Error())
}
@ -95,11 +94,10 @@ func TestMsgAlertWire(t *testing.T) {
}
tests := []struct {
in *MsgAlert // Message to encode
out *MsgAlert // Expected decoded message
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
enc MessageEncoding // Message encoding format
in *MsgAlert // Message to encode
out *MsgAlert // Expected decoded message
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
}{
// Latest protocol version.
{
@ -107,7 +105,6 @@ func TestMsgAlertWire(t *testing.T) {
baseMsgAlert,
baseMsgAlertEncoded,
ProtocolVersion,
BaseEncoding,
},
// Protocol version BIP0035Version.
@ -116,7 +113,6 @@ func TestMsgAlertWire(t *testing.T) {
baseMsgAlert,
baseMsgAlertEncoded,
BIP0035Version,
BaseEncoding,
},
// Protocol version BIP0031Version.
@ -125,7 +121,6 @@ func TestMsgAlertWire(t *testing.T) {
baseMsgAlert,
baseMsgAlertEncoded,
BIP0031Version,
BaseEncoding,
},
// Protocol version NetAddressTimeVersion.
@ -134,7 +129,6 @@ func TestMsgAlertWire(t *testing.T) {
baseMsgAlert,
baseMsgAlertEncoded,
NetAddressTimeVersion,
BaseEncoding,
},
// Protocol version MultipleAddressVersion.
@ -143,7 +137,6 @@ func TestMsgAlertWire(t *testing.T) {
baseMsgAlert,
baseMsgAlertEncoded,
MultipleAddressVersion,
BaseEncoding,
},
}
@ -151,7 +144,7 @@ func TestMsgAlertWire(t *testing.T) {
for i, test := range tests {
// Encode the message to wire format.
var buf bytes.Buffer
err := test.in.BtcEncode(&buf, test.pver, test.enc)
err := test.in.BtcEncode(&buf, test.pver)
if err != nil {
t.Errorf("BtcEncode #%d error %v", i, err)
continue
@ -165,7 +158,7 @@ func TestMsgAlertWire(t *testing.T) {
// Decode the message from wire format.
var msg MsgAlert
rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver, test.enc)
err = msg.BtcDecode(rbuf, test.pver)
if err != nil {
t.Errorf("BtcDecode #%d error %v", i, err)
continue
@ -182,7 +175,6 @@ func TestMsgAlertWire(t *testing.T) {
// of MsgAlert to confirm error paths work correctly.
func TestMsgAlertWireErrors(t *testing.T) {
pver := ProtocolVersion
encoding := BaseEncoding
baseMsgAlert := NewMsgAlert([]byte("some payload"), []byte("somesig"))
baseMsgAlertEncoded := []byte{
@ -194,29 +186,28 @@ func TestMsgAlertWireErrors(t *testing.T) {
}
tests := []struct {
in *MsgAlert // Value to encode
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
enc MessageEncoding // Message encoding format
max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error
readErr error // Expected read error
in *MsgAlert // Value to encode
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error
readErr error // Expected read error
}{
// Force error in payload length.
{baseMsgAlert, baseMsgAlertEncoded, pver, BaseEncoding, 0, io.ErrShortWrite, io.EOF},
{baseMsgAlert, baseMsgAlertEncoded, pver, 0, io.ErrShortWrite, io.EOF},
// Force error in payload.
{baseMsgAlert, baseMsgAlertEncoded, pver, BaseEncoding, 1, io.ErrShortWrite, io.EOF},
{baseMsgAlert, baseMsgAlertEncoded, pver, 1, io.ErrShortWrite, io.EOF},
// Force error in signature length.
{baseMsgAlert, baseMsgAlertEncoded, pver, BaseEncoding, 13, io.ErrShortWrite, io.EOF},
{baseMsgAlert, baseMsgAlertEncoded, pver, 13, io.ErrShortWrite, io.EOF},
// Force error in signature.
{baseMsgAlert, baseMsgAlertEncoded, pver, BaseEncoding, 14, io.ErrShortWrite, io.EOF},
{baseMsgAlert, baseMsgAlertEncoded, pver, 14, io.ErrShortWrite, io.EOF},
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
// Encode to wire format.
w := newFixedWriter(test.max)
err := test.in.BtcEncode(w, test.pver, test.enc)
err := test.in.BtcEncode(w, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.writeErr) {
t.Errorf("BtcEncode #%d wrong error got: %v, want: %v",
i, err, test.writeErr)
@ -236,7 +227,7 @@ func TestMsgAlertWireErrors(t *testing.T) {
// Decode from wire format.
var msg MsgAlert
r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver, test.enc)
err = msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) {
t.Errorf("BtcDecode #%d wrong error got: %v, want: %v",
i, err, test.readErr)
@ -257,7 +248,7 @@ func TestMsgAlertWireErrors(t *testing.T) {
// Test Error on empty Payload
baseMsgAlert.SerializedPayload = []byte{}
w := new(bytes.Buffer)
err := baseMsgAlert.BtcEncode(w, pver, encoding)
err := baseMsgAlert.BtcEncode(w, pver)
if _, ok := err.(*MessageError); !ok {
t.Errorf("MsgAlert.BtcEncode wrong error got: %T, want: %T",
err, MessageError{})
@ -268,7 +259,7 @@ func TestMsgAlertWireErrors(t *testing.T) {
baseMsgAlert.Payload = new(Alert)
baseMsgAlert.Payload.SetCancel = make([]int32, maxCountSetCancel+1)
buf := *new(bytes.Buffer)
err = baseMsgAlert.BtcEncode(&buf, pver, encoding)
err = baseMsgAlert.BtcEncode(&buf, pver)
if _, ok := err.(*MessageError); !ok {
t.Errorf("MsgAlert.BtcEncode wrong error got: %T, want: %T",
err, MessageError{})
@ -278,7 +269,7 @@ func TestMsgAlertWireErrors(t *testing.T) {
baseMsgAlert.Payload = new(Alert)
baseMsgAlert.Payload.SetSubVer = make([]string, maxCountSetSubVer+1)
buf = *new(bytes.Buffer)
err = baseMsgAlert.BtcEncode(&buf, pver, encoding)
err = baseMsgAlert.BtcEncode(&buf, pver)
if _, ok := err.(*MessageError); !ok {
t.Errorf("MsgAlert.BtcEncode wrong error got: %T, want: %T",
err, MessageError{})

View File

@ -23,8 +23,7 @@ const defaultTransactionAlloc = 2048
const MaxBlocksPerMsg = 500
// MaxBlockPayload is the maximum bytes a block message can be in bytes.
// After Segregated Witness, the max block payload has been raised to 4MB.
const MaxBlockPayload = 4000000
const MaxBlockPayload = 1000000
// maxTxPerBlock is the maximum number of transactions that could
// possibly fit into a block.
@ -61,7 +60,7 @@ func (msg *MsgBlock) ClearTransactions() {
// This is part of the Message interface implementation.
// See Deserialize for decoding blocks stored to disk, such as in a database, as
// opposed to decoding blocks from the wire.
func (msg *MsgBlock) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error {
func (msg *MsgBlock) BtcDecode(r io.Reader, pver uint32) error {
err := readBlockHeader(r, pver, &msg.Header)
if err != nil {
return err
@ -84,7 +83,7 @@ func (msg *MsgBlock) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) er
msg.Transactions = make([]*MsgTx, 0, txCount)
for i := uint64(0); i < txCount; i++ {
tx := MsgTx{}
err := tx.BtcDecode(r, pver, enc)
err := tx.BtcDecode(r, pver)
if err != nil {
return err
}
@ -107,19 +106,7 @@ func (msg *MsgBlock) Deserialize(r io.Reader) error {
// At the current time, there is no difference between the wire encoding
// at protocol version 0 and the stable long-term storage format. As
// a result, make use of BtcDecode.
//
// Passing an encoding type of WitnessEncoding to BtcEncode for the
// MessageEncoding parameter indicates that the transactions within the
// block are expected to be serialized according to the new
// serialization structure defined in BIP0141.
return msg.BtcDecode(r, 0, WitnessEncoding)
}
// DeserializeNoWitness decodes a block from r into the receiver similar to
// Deserialize, however DeserializeWitness strips all (if any) witness data
// from the transactions within the block before encoding them.
func (msg *MsgBlock) DeserializeNoWitness(r io.Reader) error {
return msg.BtcDecode(r, 0, BaseEncoding)
return msg.BtcDecode(r, 0)
}
// DeserializeTxLoc decodes r in the same manner Deserialize does, but it takes
@ -173,7 +160,7 @@ func (msg *MsgBlock) DeserializeTxLoc(r *bytes.Buffer) ([]TxLoc, error) {
// This is part of the Message interface implementation.
// See Serialize for encoding blocks to be stored to disk, such as in a
// database, as opposed to encoding blocks for the wire.
func (msg *MsgBlock) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {
func (msg *MsgBlock) BtcEncode(w io.Writer, pver uint32) error {
err := writeBlockHeader(w, pver, &msg.Header)
if err != nil {
return err
@ -185,7 +172,7 @@ func (msg *MsgBlock) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) er
}
for _, tx := range msg.Transactions {
err = tx.BtcEncode(w, pver, enc)
err = tx.BtcEncode(w, pver)
if err != nil {
return err
}
@ -207,24 +194,11 @@ func (msg *MsgBlock) Serialize(w io.Writer) error {
// At the current time, there is no difference between the wire encoding
// at protocol version 0 and the stable long-term storage format. As
// a result, make use of BtcEncode.
//
// Passing WitnessEncoding as the encoding type here indicates that
// each of the transactions should be serialized using the witness
// serialization structure defined in BIP0141.
return msg.BtcEncode(w, 0, WitnessEncoding)
}
// SerializeNoWitness encodes a block to w using an identical format to
// Serialize, with all (if any) witness data stripped from all transactions.
// This method is provided in additon to the regular Serialize, in order to
// allow one to selectively encode transaction witness data to non-upgraded
// peers which are unaware of the new encoding.
func (msg *MsgBlock) SerializeNoWitness(w io.Writer) error {
return msg.BtcEncode(w, 0, BaseEncoding)
return msg.BtcEncode(w, 0)
}
// SerializeSize returns the number of bytes it would take to serialize the
// block, factoring in any witness data within transaction.
// block.
func (msg *MsgBlock) SerializeSize() int {
// Block header bytes + Serialized varint size for the number of
// transactions.
@ -237,20 +211,6 @@ func (msg *MsgBlock) SerializeSize() int {
return n
}
// SerializeSizeStripped returns the number of bytes it would take to serialize
// the block, excluding any witness data (if any).
func (msg *MsgBlock) SerializeSizeStripped() int {
// Block header bytes + Serialized varint size for the number of
// transactions.
n := blockHeaderLen + VarIntSerializeSize(uint64(len(msg.Transactions)))
for _, tx := range msg.Transactions {
n += tx.SerializeSizeStripped()
}
return n
}
// Command returns the protocol command string for the message. This is part
// of the Message interface implementation.
func (msg *MsgBlock) Command() string {

View File

@ -36,7 +36,7 @@ func TestBlock(t *testing.T) {
// Ensure max payload is expected value for latest protocol version.
// Num addresses (varInt) + max allowed addresses.
wantPayload := uint32(4000000)
wantPayload := uint32(1000000)
maxPayload := msg.MaxPayloadLength(pver)
if maxPayload != wantPayload {
t.Errorf("MaxPayloadLength: wrong max payload length for "+
@ -110,12 +110,11 @@ func TestBlockHash(t *testing.T) {
// of transaction inputs and outputs and protocol versions.
func TestBlockWire(t *testing.T) {
tests := []struct {
in *MsgBlock // Message to encode
out *MsgBlock // Expected decoded message
buf []byte // Wire encoding
txLocs []TxLoc // Expected transaction locations
pver uint32 // Protocol version for wire encoding
enc MessageEncoding // Message encoding format
in *MsgBlock // Message to encode
out *MsgBlock // Expected decoded message
buf []byte // Wire encoding
txLocs []TxLoc // Expected transaction locations
pver uint32 // Protocol version for wire encoding
}{
// Latest protocol version.
{
@ -124,7 +123,6 @@ func TestBlockWire(t *testing.T) {
blockOneBytes,
blockOneTxLocs,
ProtocolVersion,
BaseEncoding,
},
// Protocol version BIP0035Version.
@ -134,7 +132,6 @@ func TestBlockWire(t *testing.T) {
blockOneBytes,
blockOneTxLocs,
BIP0035Version,
BaseEncoding,
},
// Protocol version BIP0031Version.
@ -144,7 +141,6 @@ func TestBlockWire(t *testing.T) {
blockOneBytes,
blockOneTxLocs,
BIP0031Version,
BaseEncoding,
},
// Protocol version NetAddressTimeVersion.
@ -154,7 +150,6 @@ func TestBlockWire(t *testing.T) {
blockOneBytes,
blockOneTxLocs,
NetAddressTimeVersion,
BaseEncoding,
},
// Protocol version MultipleAddressVersion.
@ -164,16 +159,14 @@ func TestBlockWire(t *testing.T) {
blockOneBytes,
blockOneTxLocs,
MultipleAddressVersion,
BaseEncoding,
},
// TODO(roasbeef): add case for witnessy block
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
// Encode the message to wire format.
var buf bytes.Buffer
err := test.in.BtcEncode(&buf, test.pver, test.enc)
err := test.in.BtcEncode(&buf, test.pver)
if err != nil {
t.Errorf("BtcEncode #%d error %v", i, err)
continue
@ -187,7 +180,7 @@ func TestBlockWire(t *testing.T) {
// Decode the message from wire format.
var msg MsgBlock
rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver, test.enc)
err = msg.BtcDecode(rbuf, test.pver)
if err != nil {
t.Errorf("BtcDecode #%d error %v", i, err)
continue
@ -209,37 +202,36 @@ func TestBlockWireErrors(t *testing.T) {
pver := uint32(60002)
tests := []struct {
in *MsgBlock // Value to encode
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
enc MessageEncoding // Message encoding format
max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error
readErr error // Expected read error
in *MsgBlock // Value to encode
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error
readErr error // Expected read error
}{
// Force error in version.
{&blockOne, blockOneBytes, pver, BaseEncoding, 0, io.ErrShortWrite, io.EOF},
{&blockOne, blockOneBytes, pver, 0, io.ErrShortWrite, io.EOF},
// Force error in prev block hash.
{&blockOne, blockOneBytes, pver, BaseEncoding, 4, io.ErrShortWrite, io.EOF},
{&blockOne, blockOneBytes, pver, 4, io.ErrShortWrite, io.EOF},
// Force error in merkle root.
{&blockOne, blockOneBytes, pver, BaseEncoding, 36, io.ErrShortWrite, io.EOF},
{&blockOne, blockOneBytes, pver, 36, io.ErrShortWrite, io.EOF},
// Force error in timestamp.
{&blockOne, blockOneBytes, pver, BaseEncoding, 68, io.ErrShortWrite, io.EOF},
{&blockOne, blockOneBytes, pver, 68, io.ErrShortWrite, io.EOF},
// Force error in difficulty bits.
{&blockOne, blockOneBytes, pver, BaseEncoding, 72, io.ErrShortWrite, io.EOF},
{&blockOne, blockOneBytes, pver, 72, io.ErrShortWrite, io.EOF},
// Force error in header nonce.
{&blockOne, blockOneBytes, pver, BaseEncoding, 76, io.ErrShortWrite, io.EOF},
{&blockOne, blockOneBytes, pver, 76, io.ErrShortWrite, io.EOF},
// Force error in transaction count.
{&blockOne, blockOneBytes, pver, BaseEncoding, 80, io.ErrShortWrite, io.EOF},
{&blockOne, blockOneBytes, pver, 80, io.ErrShortWrite, io.EOF},
// Force error in transactions.
{&blockOne, blockOneBytes, pver, BaseEncoding, 81, io.ErrShortWrite, io.EOF},
{&blockOne, blockOneBytes, pver, 81, io.ErrShortWrite, io.EOF},
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
// Encode to wire format.
w := newFixedWriter(test.max)
err := test.in.BtcEncode(w, test.pver, test.enc)
err := test.in.BtcEncode(w, test.pver)
if err != test.writeErr {
t.Errorf("BtcEncode #%d wrong error got: %v, want: %v",
i, err, test.writeErr)
@ -249,7 +241,7 @@ func TestBlockWireErrors(t *testing.T) {
// Decode from wire format.
var msg MsgBlock
r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver, test.enc)
err = msg.BtcDecode(r, test.pver)
if err != test.readErr {
t.Errorf("BtcDecode #%d wrong error got: %v, want: %v",
i, err, test.readErr)
@ -396,10 +388,9 @@ func TestBlockOverflowErrors(t *testing.T) {
pver := uint32(70001)
tests := []struct {
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
enc MessageEncoding // Message encoding format
err error // Expected error
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
err error // Expected error
}{
// Block that claims to have ~uint64(0) transactions.
{
@ -418,7 +409,7 @@ func TestBlockOverflowErrors(t *testing.T) {
0x01, 0xe3, 0x62, 0x99, // Nonce
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, // TxnCount
}, pver, BaseEncoding, &MessageError{},
}, pver, &MessageError{},
},
}
@ -427,7 +418,7 @@ func TestBlockOverflowErrors(t *testing.T) {
// Decode from wire format.
var msg MsgBlock
r := bytes.NewReader(test.buf)
err := msg.BtcDecode(r, test.pver, test.enc)
err := msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.err) {
t.Errorf("BtcDecode #%d wrong error got: %v, want: %v",
i, err, reflect.TypeOf(test.err))

View File

@ -41,7 +41,7 @@ func (msg *MsgCFCheckpt) AddCFHeader(header *chainhash.Hash) error {
// BtcDecode decodes r using the bitcoin protocol encoding into the receiver.
// This is part of the Message interface implementation.
func (msg *MsgCFCheckpt) BtcDecode(r io.Reader, pver uint32, _ MessageEncoding) error {
func (msg *MsgCFCheckpt) BtcDecode(r io.Reader, pver uint32) error {
// Read filter type
err := readElement(r, &msg.FilterType)
if err != nil {
@ -77,7 +77,7 @@ func (msg *MsgCFCheckpt) BtcDecode(r io.Reader, pver uint32, _ MessageEncoding)
// BtcEncode encodes the receiver to w using the bitcoin protocol encoding.
// This is part of the Message interface implementation.
func (msg *MsgCFCheckpt) BtcEncode(w io.Writer, pver uint32, _ MessageEncoding) error {
func (msg *MsgCFCheckpt) BtcEncode(w io.Writer, pver uint32) error {
// Write filter type
err := writeElement(w, msg.FilterType)
if err != nil {
@ -120,7 +120,7 @@ func (msg *MsgCFCheckpt) Deserialize(r io.Reader) error {
// At the current time, there is no difference between the wire encoding
// and the stable long-term storage format. As a result, make use of
// BtcDecode.
return msg.BtcDecode(r, 0, BaseEncoding)
return msg.BtcDecode(r, 0)
}
// Command returns the protocol command string for the message. This is part

View File

@ -47,7 +47,7 @@ func (msg *MsgCFHeaders) AddCFHash(hash *chainhash.Hash) error {
// BtcDecode decodes r using the bitcoin protocol encoding into the receiver.
// This is part of the Message interface implementation.
func (msg *MsgCFHeaders) BtcDecode(r io.Reader, pver uint32, _ MessageEncoding) error {
func (msg *MsgCFHeaders) BtcDecode(r io.Reader, pver uint32) error {
// Read filter type
err := readElement(r, &msg.FilterType)
if err != nil {
@ -97,7 +97,7 @@ func (msg *MsgCFHeaders) BtcDecode(r io.Reader, pver uint32, _ MessageEncoding)
// BtcEncode encodes the receiver to w using the bitcoin protocol encoding.
// This is part of the Message interface implementation.
func (msg *MsgCFHeaders) BtcEncode(w io.Writer, pver uint32, _ MessageEncoding) error {
func (msg *MsgCFHeaders) BtcEncode(w io.Writer, pver uint32) error {
// Write filter type
err := writeElement(w, msg.FilterType)
if err != nil {
@ -153,7 +153,7 @@ func (msg *MsgCFHeaders) Deserialize(r io.Reader) error {
// At the current time, there is no difference between the wire encoding
// and the stable long-term storage format. As a result, make use of
// BtcDecode.
return msg.BtcDecode(r, 0, BaseEncoding)
return msg.BtcDecode(r, 0)
}
// Command returns the protocol command string for the message. This is part

View File

@ -39,7 +39,7 @@ type MsgCFilter struct {
// BtcDecode decodes r using the bitcoin protocol encoding into the receiver.
// This is part of the Message interface implementation.
func (msg *MsgCFilter) BtcDecode(r io.Reader, pver uint32, _ MessageEncoding) error {
func (msg *MsgCFilter) BtcDecode(r io.Reader, pver uint32) error {
// Read filter type
err := readElement(r, &msg.FilterType)
if err != nil {
@ -60,7 +60,7 @@ func (msg *MsgCFilter) BtcDecode(r io.Reader, pver uint32, _ MessageEncoding) er
// BtcEncode encodes the receiver to w using the bitcoin protocol encoding.
// This is part of the Message interface implementation.
func (msg *MsgCFilter) BtcEncode(w io.Writer, pver uint32, _ MessageEncoding) error {
func (msg *MsgCFilter) BtcEncode(w io.Writer, pver uint32) error {
size := len(msg.Data)
if size > MaxCFilterDataSize {
str := fmt.Sprintf("cfilter size too large for message "+
@ -94,7 +94,7 @@ func (msg *MsgCFilter) Deserialize(r io.Reader) error {
// At the current time, there is no difference between the wire encoding
// and the stable long-term storage format. As a result, make use of
// BtcDecode.
return msg.BtcDecode(r, 0, BaseEncoding)
return msg.BtcDecode(r, 0)
}
// Command returns the protocol command string for the message. This is part

View File

@ -21,7 +21,7 @@ type MsgFeeFilter struct {
// BtcDecode decodes r using the bitcoin protocol encoding into the receiver.
// This is part of the Message interface implementation.
func (msg *MsgFeeFilter) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error {
func (msg *MsgFeeFilter) BtcDecode(r io.Reader, pver uint32) error {
if pver < FeeFilterVersion {
str := fmt.Sprintf("feefilter message invalid for protocol "+
"version %d", pver)
@ -33,7 +33,7 @@ func (msg *MsgFeeFilter) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding
// BtcEncode encodes the receiver to w using the bitcoin protocol encoding.
// This is part of the Message interface implementation.
func (msg *MsgFeeFilter) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {
func (msg *MsgFeeFilter) BtcEncode(w io.Writer, pver uint32) error {
if pver < FeeFilterVersion {
str := fmt.Sprintf("feefilter message invalid for protocol "+
"version %d", pver)

View File

@ -43,14 +43,14 @@ func TestFeeFilterLatest(t *testing.T) {
// Test encode with latest protocol version.
var buf bytes.Buffer
err := msg.BtcEncode(&buf, pver, BaseEncoding)
err := msg.BtcEncode(&buf, pver)
if err != nil {
t.Errorf("encode of MsgFeeFilter failed %v err <%v>", msg, err)
}
// Test decode with latest protocol version.
readmsg := NewMsgFeeFilter(0)
err = readmsg.BtcDecode(&buf, pver, BaseEncoding)
err = readmsg.BtcDecode(&buf, pver)
if err != nil {
t.Errorf("decode of MsgFeeFilter failed [%v] err <%v>", buf, err)
}
@ -91,7 +91,7 @@ func TestFeeFilterWire(t *testing.T) {
for i, test := range tests {
// Encode the message to wire format.
var buf bytes.Buffer
err := test.in.BtcEncode(&buf, test.pver, BaseEncoding)
err := test.in.BtcEncode(&buf, test.pver)
if err != nil {
t.Errorf("BtcEncode #%d error %v", i, err)
continue
@ -105,7 +105,7 @@ func TestFeeFilterWire(t *testing.T) {
// Decode the message from wire format.
var msg MsgFeeFilter
rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver, BaseEncoding)
err = msg.BtcDecode(rbuf, test.pver)
if err != nil {
t.Errorf("BtcDecode #%d error %v", i, err)
continue
@ -149,7 +149,7 @@ func TestFeeFilterWireErrors(t *testing.T) {
for i, test := range tests {
// Encode to wire format.
w := newFixedWriter(test.max)
err := test.in.BtcEncode(w, test.pver, BaseEncoding)
err := test.in.BtcEncode(w, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.writeErr) {
t.Errorf("BtcEncode #%d wrong error got: %v, want: %v",
i, err, test.writeErr)
@ -169,7 +169,7 @@ func TestFeeFilterWireErrors(t *testing.T) {
// Decode from wire format.
var msg MsgFeeFilter
r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver, BaseEncoding)
err = msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) {
t.Errorf("BtcDecode #%d wrong error got: %v, want: %v",
i, err, test.readErr)

View File

@ -27,7 +27,7 @@ type MsgFilterAdd struct {
// BtcDecode decodes r using the bitcoin protocol encoding into the receiver.
// This is part of the Message interface implementation.
func (msg *MsgFilterAdd) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error {
func (msg *MsgFilterAdd) BtcDecode(r io.Reader, pver uint32) error {
if pver < BIP0037Version {
str := fmt.Sprintf("filteradd message invalid for protocol "+
"version %d", pver)
@ -42,7 +42,7 @@ func (msg *MsgFilterAdd) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding
// BtcEncode encodes the receiver to w using the bitcoin protocol encoding.
// This is part of the Message interface implementation.
func (msg *MsgFilterAdd) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {
func (msg *MsgFilterAdd) BtcEncode(w io.Writer, pver uint32) error {
if pver < BIP0037Version {
str := fmt.Sprintf("filteradd message invalid for protocol "+
"version %d", pver)

View File

@ -14,7 +14,6 @@ import (
// TestFilterAddLatest tests the MsgFilterAdd API against the latest protocol
// version.
func TestFilterAddLatest(t *testing.T) {
enc := BaseEncoding
pver := ProtocolVersion
data := []byte{0x01, 0x02}
@ -38,14 +37,14 @@ func TestFilterAddLatest(t *testing.T) {
// Test encode with latest protocol version.
var buf bytes.Buffer
err := msg.BtcEncode(&buf, pver, enc)
err := msg.BtcEncode(&buf, pver)
if err != nil {
t.Errorf("encode of MsgFilterAdd failed %v err <%v>", msg, err)
}
// Test decode with latest protocol version.
var readmsg MsgFilterAdd
err = readmsg.BtcDecode(&buf, pver, enc)
err = readmsg.BtcDecode(&buf, pver)
if err != nil {
t.Errorf("decode of MsgFilterAdd failed [%v] err <%v>", buf, err)
}
@ -62,14 +61,14 @@ func TestFilterAddCrossProtocol(t *testing.T) {
// Encode with latest protocol version.
var buf bytes.Buffer
err := msg.BtcEncode(&buf, ProtocolVersion, LatestEncoding)
err := msg.BtcEncode(&buf, ProtocolVersion)
if err != nil {
t.Errorf("encode of MsgFilterAdd failed %v err <%v>", msg, err)
}
// Decode with old protocol version.
var readmsg MsgFilterAdd
err = readmsg.BtcDecode(&buf, BIP0031Version, LatestEncoding)
err = readmsg.BtcDecode(&buf, BIP0031Version)
if err == nil {
t.Errorf("decode of MsgFilterAdd succeeded when it shouldn't "+
"have %v", msg)
@ -90,7 +89,7 @@ func TestFilterAddMaxDataSize(t *testing.T) {
// Encode with latest protocol version.
var buf bytes.Buffer
err := msg.BtcEncode(&buf, ProtocolVersion, LatestEncoding)
err := msg.BtcEncode(&buf, ProtocolVersion)
if err == nil {
t.Errorf("encode of MsgFilterAdd succeeded when it shouldn't "+
"have %v", msg)
@ -98,7 +97,7 @@ func TestFilterAddMaxDataSize(t *testing.T) {
// Decode with latest protocol version.
readbuf := bytes.NewReader(data)
err = msg.BtcDecode(readbuf, ProtocolVersion, LatestEncoding)
err = msg.BtcDecode(readbuf, ProtocolVersion)
if err == nil {
t.Errorf("decode of MsgFilterAdd succeeded when it shouldn't "+
"have %v", msg)
@ -117,37 +116,27 @@ func TestFilterAddWireErrors(t *testing.T) {
baseFilterAddEncoded := append([]byte{0x04}, baseData...)
tests := []struct {
in *MsgFilterAdd // Value to encode
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
enc MessageEncoding // Message encoding format
max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error
readErr error // Expected read error
in *MsgFilterAdd // Value to encode
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error
readErr error // Expected read error
}{
// Latest protocol version with intentional read/write errors.
// Force error in data size.
{
baseFilterAdd, baseFilterAddEncoded, pver, BaseEncoding, 0,
io.ErrShortWrite, io.EOF,
},
{baseFilterAdd, baseFilterAddEncoded, pver, 0, io.ErrShortWrite, io.EOF},
// Force error in data.
{
baseFilterAdd, baseFilterAddEncoded, pver, BaseEncoding, 1,
io.ErrShortWrite, io.EOF,
},
{baseFilterAdd, baseFilterAddEncoded, pver, 1, io.ErrShortWrite, io.EOF},
// Force error due to unsupported protocol version.
{
baseFilterAdd, baseFilterAddEncoded, pverNoFilterAdd, BaseEncoding, 5,
wireErr, wireErr,
},
{baseFilterAdd, baseFilterAddEncoded, pverNoFilterAdd, 5, wireErr, wireErr},
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
// Encode to wire format.
w := newFixedWriter(test.max)
err := test.in.BtcEncode(w, test.pver, test.enc)
err := test.in.BtcEncode(w, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.writeErr) {
t.Errorf("BtcEncode #%d wrong error got: %v, want: %v",
i, err, test.writeErr)
@ -167,7 +156,7 @@ func TestFilterAddWireErrors(t *testing.T) {
// Decode from wire format.
var msg MsgFilterAdd
r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver, test.enc)
err = msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) {
t.Errorf("BtcDecode #%d wrong error got: %v, want: %v",
i, err, test.readErr)

View File

@ -18,7 +18,7 @@ type MsgFilterClear struct{}
// BtcDecode decodes r using the bitcoin protocol encoding into the receiver.
// This is part of the Message interface implementation.
func (msg *MsgFilterClear) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error {
func (msg *MsgFilterClear) BtcDecode(r io.Reader, pver uint32) error {
if pver < BIP0037Version {
str := fmt.Sprintf("filterclear message invalid for protocol "+
"version %d", pver)
@ -30,7 +30,7 @@ func (msg *MsgFilterClear) BtcDecode(r io.Reader, pver uint32, enc MessageEncodi
// BtcEncode encodes the receiver to w using the bitcoin protocol encoding.
// This is part of the Message interface implementation.
func (msg *MsgFilterClear) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {
func (msg *MsgFilterClear) BtcEncode(w io.Writer, pver uint32) error {
if pver < BIP0037Version {
str := fmt.Sprintf("filterclear message invalid for protocol "+
"version %d", pver)

View File

@ -43,14 +43,14 @@ func TestFilterClearCrossProtocol(t *testing.T) {
// Encode with latest protocol version.
var buf bytes.Buffer
err := msg.BtcEncode(&buf, ProtocolVersion, LatestEncoding)
err := msg.BtcEncode(&buf, ProtocolVersion)
if err != nil {
t.Errorf("encode of MsgFilterClear failed %v err <%v>", msg, err)
}
// Decode with old protocol version.
var readmsg MsgFilterClear
err = readmsg.BtcDecode(&buf, BIP0031Version, LatestEncoding)
err = readmsg.BtcDecode(&buf, BIP0031Version)
if err == nil {
t.Errorf("decode of MsgFilterClear succeeded when it "+
"shouldn't have %v", msg)
@ -68,7 +68,6 @@ func TestFilterClearWire(t *testing.T) {
out *MsgFilterClear // Expected decoded message
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
enc MessageEncoding // Message encoding format
}{
// Latest protocol version.
{
@ -76,7 +75,6 @@ func TestFilterClearWire(t *testing.T) {
msgFilterClear,
msgFilterClearEncoded,
ProtocolVersion,
BaseEncoding,
},
// Protocol version BIP0037Version + 1.
@ -85,7 +83,6 @@ func TestFilterClearWire(t *testing.T) {
msgFilterClear,
msgFilterClearEncoded,
BIP0037Version + 1,
BaseEncoding,
},
// Protocol version BIP0037Version.
@ -94,7 +91,6 @@ func TestFilterClearWire(t *testing.T) {
msgFilterClear,
msgFilterClearEncoded,
BIP0037Version,
BaseEncoding,
},
}
@ -102,7 +98,7 @@ func TestFilterClearWire(t *testing.T) {
for i, test := range tests {
// Encode the message to wire format.
var buf bytes.Buffer
err := test.in.BtcEncode(&buf, test.pver, test.enc)
err := test.in.BtcEncode(&buf, test.pver)
if err != nil {
t.Errorf("BtcEncode #%d error %v", i, err)
continue
@ -116,7 +112,7 @@ func TestFilterClearWire(t *testing.T) {
// Decode the message from wire format.
var msg MsgFilterClear
rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver, test.enc)
err = msg.BtcDecode(rbuf, test.pver)
if err != nil {
t.Errorf("BtcDecode #%d error %v", i, err)
continue
@ -142,15 +138,13 @@ func TestFilterClearWireErrors(t *testing.T) {
in *MsgFilterClear // Value to encode
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
enc MessageEncoding // Message encoding format
max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error
readErr error // Expected read error
}{
// Force error due to unsupported protocol version.
{
baseFilterClear, baseFilterClearEncoded,
pverNoFilterClear, BaseEncoding, 4, wireErr, wireErr,
baseFilterClear, baseFilterClearEncoded, pverNoFilterClear, 4, wireErr, wireErr,
},
}
@ -158,7 +152,7 @@ func TestFilterClearWireErrors(t *testing.T) {
for i, test := range tests {
// Encode to wire format.
w := newFixedWriter(test.max)
err := test.in.BtcEncode(w, test.pver, test.enc)
err := test.in.BtcEncode(w, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.writeErr) {
t.Errorf("BtcEncode #%d wrong error got: %v, want: %v",
i, err, test.writeErr)
@ -178,7 +172,7 @@ func TestFilterClearWireErrors(t *testing.T) {
// Decode from wire format.
var msg MsgFilterClear
r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver, test.enc)
err = msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) {
t.Errorf("BtcDecode #%d wrong error got: %v, want: %v",
i, err, test.readErr)

View File

@ -51,7 +51,7 @@ type MsgFilterLoad struct {
// BtcDecode decodes r using the bitcoin protocol encoding into the receiver.
// This is part of the Message interface implementation.
func (msg *MsgFilterLoad) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error {
func (msg *MsgFilterLoad) BtcDecode(r io.Reader, pver uint32) error {
if pver < BIP0037Version {
str := fmt.Sprintf("filterload message invalid for protocol "+
"version %d", pver)
@ -81,7 +81,7 @@ func (msg *MsgFilterLoad) BtcDecode(r io.Reader, pver uint32, enc MessageEncodin
// BtcEncode encodes the receiver to w using the bitcoin protocol encoding.
// This is part of the Message interface implementation.
func (msg *MsgFilterLoad) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {
func (msg *MsgFilterLoad) BtcEncode(w io.Writer, pver uint32) error {
if pver < BIP0037Version {
str := fmt.Sprintf("filterload message invalid for protocol "+
"version %d", pver)

View File

@ -15,7 +15,6 @@ import (
// version.
func TestFilterLoadLatest(t *testing.T) {
pver := ProtocolVersion
enc := BaseEncoding
data := []byte{0x01, 0x02}
msg := NewMsgFilterLoad(data, 10, 0, 0)
@ -38,14 +37,14 @@ func TestFilterLoadLatest(t *testing.T) {
// Test encode with latest protocol version.
var buf bytes.Buffer
err := msg.BtcEncode(&buf, pver, enc)
err := msg.BtcEncode(&buf, pver)
if err != nil {
t.Errorf("encode of MsgFilterLoad failed %v err <%v>", msg, err)
}
// Test decode with latest protocol version.
readmsg := MsgFilterLoad{}
err = readmsg.BtcDecode(&buf, pver, enc)
err = readmsg.BtcDecode(&buf, pver)
if err != nil {
t.Errorf("decode of MsgFilterLoad failed [%v] err <%v>", buf, err)
}
@ -59,7 +58,7 @@ func TestFilterLoadCrossProtocol(t *testing.T) {
// Encode with latest protocol version.
var buf bytes.Buffer
err := msg.BtcEncode(&buf, ProtocolVersion, BaseEncoding)
err := msg.BtcEncode(&buf, ProtocolVersion)
if err != nil {
t.Errorf("encode of NewMsgFilterLoad failed %v err <%v>", msg,
err)
@ -67,7 +66,7 @@ func TestFilterLoadCrossProtocol(t *testing.T) {
// Decode with old protocol version.
var readmsg MsgFilterLoad
err = readmsg.BtcDecode(&buf, BIP0031Version, BaseEncoding)
err = readmsg.BtcDecode(&buf, BIP0031Version)
if err == nil {
t.Errorf("decode of MsgFilterLoad succeeded when it shouldn't have %v",
msg)
@ -81,7 +80,7 @@ func TestFilterLoadMaxFilterSize(t *testing.T) {
// Encode with latest protocol version.
var buf bytes.Buffer
err := msg.BtcEncode(&buf, ProtocolVersion, BaseEncoding)
err := msg.BtcEncode(&buf, ProtocolVersion)
if err == nil {
t.Errorf("encode of MsgFilterLoad succeeded when it shouldn't "+
"have %v", msg)
@ -89,7 +88,7 @@ func TestFilterLoadMaxFilterSize(t *testing.T) {
// Decode with latest protocol version.
readbuf := bytes.NewReader(data)
err = msg.BtcDecode(readbuf, ProtocolVersion, BaseEncoding)
err = msg.BtcDecode(readbuf, ProtocolVersion)
if err == nil {
t.Errorf("decode of MsgFilterLoad succeeded when it shouldn't "+
"have %v", msg)
@ -103,7 +102,7 @@ func TestFilterLoadMaxHashFuncsSize(t *testing.T) {
// Encode with latest protocol version.
var buf bytes.Buffer
err := msg.BtcEncode(&buf, ProtocolVersion, BaseEncoding)
err := msg.BtcEncode(&buf, ProtocolVersion)
if err == nil {
t.Errorf("encode of MsgFilterLoad succeeded when it shouldn't have %v",
msg)
@ -118,7 +117,7 @@ func TestFilterLoadMaxHashFuncsSize(t *testing.T) {
}
// Decode with latest protocol version.
readbuf := bytes.NewReader(newBuf)
err = msg.BtcDecode(readbuf, ProtocolVersion, BaseEncoding)
err = msg.BtcDecode(readbuf, ProtocolVersion)
if err == nil {
t.Errorf("decode of MsgFilterLoad succeeded when it shouldn't have %v",
msg)
@ -141,44 +140,37 @@ func TestFilterLoadWireErrors(t *testing.T) {
0x00) // Flags
tests := []struct {
in *MsgFilterLoad // Value to encode
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
enc MessageEncoding // Message encoding format
max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error
readErr error // Expected read error
in *MsgFilterLoad // Value to encode
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error
readErr error // Expected read error
}{
// Latest protocol version with intentional read/write errors.
// Force error in filter size.
{
baseFilterLoad, baseFilterLoadEncoded, pver, BaseEncoding, 0,
io.ErrShortWrite, io.EOF,
baseFilterLoad, baseFilterLoadEncoded, pver, 0, io.ErrShortWrite, io.EOF,
},
// Force error in filter.
{
baseFilterLoad, baseFilterLoadEncoded, pver, BaseEncoding, 1,
io.ErrShortWrite, io.EOF,
baseFilterLoad, baseFilterLoadEncoded, pver, 1, io.ErrShortWrite, io.EOF,
},
// Force error in hash funcs.
{
baseFilterLoad, baseFilterLoadEncoded, pver, BaseEncoding, 5,
io.ErrShortWrite, io.EOF,
baseFilterLoad, baseFilterLoadEncoded, pver, 5, io.ErrShortWrite, io.EOF,
},
// Force error in tweak.
{
baseFilterLoad, baseFilterLoadEncoded, pver, BaseEncoding, 9,
io.ErrShortWrite, io.EOF,
baseFilterLoad, baseFilterLoadEncoded, pver, 9, io.ErrShortWrite, io.EOF,
},
// Force error in flags.
{
baseFilterLoad, baseFilterLoadEncoded, pver, BaseEncoding, 13,
io.ErrShortWrite, io.EOF,
baseFilterLoad, baseFilterLoadEncoded, pver, 13, io.ErrShortWrite, io.EOF,
},
// Force error due to unsupported protocol version.
{
baseFilterLoad, baseFilterLoadEncoded, pverNoFilterLoad, BaseEncoding,
10, wireErr, wireErr,
baseFilterLoad, baseFilterLoadEncoded, pverNoFilterLoad, 10, wireErr, wireErr,
},
}
@ -186,7 +178,7 @@ func TestFilterLoadWireErrors(t *testing.T) {
for i, test := range tests {
// Encode to wire format.
w := newFixedWriter(test.max)
err := test.in.BtcEncode(w, test.pver, test.enc)
err := test.in.BtcEncode(w, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.writeErr) {
t.Errorf("BtcEncode #%d wrong error got: %v, want: %v",
i, err, test.writeErr)
@ -206,7 +198,7 @@ func TestFilterLoadWireErrors(t *testing.T) {
// Decode from wire format.
var msg MsgFilterLoad
r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver, test.enc)
err = msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) {
t.Errorf("BtcDecode #%d wrong error got: %v, want: %v",
i, err, test.readErr)

View File

@ -18,13 +18,13 @@ type MsgGetAddr struct{}
// BtcDecode decodes r using the bitcoin protocol encoding into the receiver.
// This is part of the Message interface implementation.
func (msg *MsgGetAddr) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error {
func (msg *MsgGetAddr) BtcDecode(r io.Reader, pver uint32) error {
return nil
}
// BtcEncode encodes the receiver to w using the bitcoin protocol encoding.
// This is part of the Message interface implementation.
func (msg *MsgGetAddr) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {
func (msg *MsgGetAddr) BtcEncode(w io.Writer, pver uint32) error {
return nil
}

View File

@ -42,11 +42,10 @@ func TestGetAddrWire(t *testing.T) {
msgGetAddrEncoded := []byte{}
tests := []struct {
in *MsgGetAddr // Message to encode
out *MsgGetAddr // Expected decoded message
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
enc MessageEncoding // Message encoding variant.
in *MsgGetAddr // Message to encode
out *MsgGetAddr // Expected decoded message
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
}{
// Latest protocol version.
{
@ -54,7 +53,6 @@ func TestGetAddrWire(t *testing.T) {
msgGetAddr,
msgGetAddrEncoded,
ProtocolVersion,
BaseEncoding,
},
// Protocol version BIP0035Version.
@ -63,7 +61,6 @@ func TestGetAddrWire(t *testing.T) {
msgGetAddr,
msgGetAddrEncoded,
BIP0035Version,
BaseEncoding,
},
// Protocol version BIP0031Version.
@ -72,7 +69,6 @@ func TestGetAddrWire(t *testing.T) {
msgGetAddr,
msgGetAddrEncoded,
BIP0031Version,
BaseEncoding,
},
// Protocol version NetAddressTimeVersion.
@ -81,7 +77,6 @@ func TestGetAddrWire(t *testing.T) {
msgGetAddr,
msgGetAddrEncoded,
NetAddressTimeVersion,
BaseEncoding,
},
// Protocol version MultipleAddressVersion.
@ -90,7 +85,6 @@ func TestGetAddrWire(t *testing.T) {
msgGetAddr,
msgGetAddrEncoded,
MultipleAddressVersion,
BaseEncoding,
},
}
@ -98,7 +92,7 @@ func TestGetAddrWire(t *testing.T) {
for i, test := range tests {
// Encode the message to wire format.
var buf bytes.Buffer
err := test.in.BtcEncode(&buf, test.pver, test.enc)
err := test.in.BtcEncode(&buf, test.pver)
if err != nil {
t.Errorf("BtcEncode #%d error %v", i, err)
continue
@ -112,7 +106,7 @@ func TestGetAddrWire(t *testing.T) {
// Decode the message from wire format.
var msg MsgGetAddr
rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver, test.enc)
err = msg.BtcDecode(rbuf, test.pver)
if err != nil {
t.Errorf("BtcDecode #%d error %v", i, err)
continue

View File

@ -50,7 +50,7 @@ func (msg *MsgGetBlocks) AddBlockLocatorHash(hash *chainhash.Hash) error {
// BtcDecode decodes r using the bitcoin protocol encoding into the receiver.
// This is part of the Message interface implementation.
func (msg *MsgGetBlocks) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error {
func (msg *MsgGetBlocks) BtcDecode(r io.Reader, pver uint32) error {
err := readElement(r, &msg.ProtocolVersion)
if err != nil {
return err
@ -85,7 +85,7 @@ func (msg *MsgGetBlocks) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding
// BtcEncode encodes the receiver to w using the bitcoin protocol encoding.
// This is part of the Message interface implementation.
func (msg *MsgGetBlocks) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {
func (msg *MsgGetBlocks) BtcEncode(w io.Writer, pver uint32) error {
count := len(msg.BlockLocatorHashes)
if count > MaxBlockLocatorsPerMsg {
str := fmt.Sprintf("too many block locator hashes for message "+

View File

@ -142,11 +142,10 @@ func TestGetBlocksWire(t *testing.T) {
}
tests := []struct {
in *MsgGetBlocks // Message to encode
out *MsgGetBlocks // Expected decoded message
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
enc MessageEncoding // Message encoding format
in *MsgGetBlocks // Message to encode
out *MsgGetBlocks // Expected decoded message
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
}{
// Latest protocol version with no block locators.
{
@ -154,7 +153,6 @@ func TestGetBlocksWire(t *testing.T) {
noLocators,
noLocatorsEncoded,
ProtocolVersion,
BaseEncoding,
},
// Latest protocol version with multiple block locators.
@ -163,7 +161,6 @@ func TestGetBlocksWire(t *testing.T) {
multiLocators,
multiLocatorsEncoded,
ProtocolVersion,
BaseEncoding,
},
// Protocol version BIP0035Version with no block locators.
@ -172,7 +169,6 @@ func TestGetBlocksWire(t *testing.T) {
noLocators,
noLocatorsEncoded,
BIP0035Version,
BaseEncoding,
},
// Protocol version BIP0035Version with multiple block locators.
@ -181,7 +177,6 @@ func TestGetBlocksWire(t *testing.T) {
multiLocators,
multiLocatorsEncoded,
BIP0035Version,
BaseEncoding,
},
// Protocol version BIP0031Version with no block locators.
@ -190,7 +185,6 @@ func TestGetBlocksWire(t *testing.T) {
noLocators,
noLocatorsEncoded,
BIP0031Version,
BaseEncoding,
},
// Protocol version BIP0031Versionwith multiple block locators.
@ -199,7 +193,6 @@ func TestGetBlocksWire(t *testing.T) {
multiLocators,
multiLocatorsEncoded,
BIP0031Version,
BaseEncoding,
},
// Protocol version NetAddressTimeVersion with no block locators.
@ -208,7 +201,6 @@ func TestGetBlocksWire(t *testing.T) {
noLocators,
noLocatorsEncoded,
NetAddressTimeVersion,
BaseEncoding,
},
// Protocol version NetAddressTimeVersion multiple block locators.
@ -217,7 +209,6 @@ func TestGetBlocksWire(t *testing.T) {
multiLocators,
multiLocatorsEncoded,
NetAddressTimeVersion,
BaseEncoding,
},
// Protocol version MultipleAddressVersion with no block locators.
@ -226,7 +217,6 @@ func TestGetBlocksWire(t *testing.T) {
noLocators,
noLocatorsEncoded,
MultipleAddressVersion,
BaseEncoding,
},
// Protocol version MultipleAddressVersion multiple block locators.
@ -235,7 +225,6 @@ func TestGetBlocksWire(t *testing.T) {
multiLocators,
multiLocatorsEncoded,
MultipleAddressVersion,
BaseEncoding,
},
}
@ -243,7 +232,7 @@ func TestGetBlocksWire(t *testing.T) {
for i, test := range tests {
// Encode the message to wire format.
var buf bytes.Buffer
err := test.in.BtcEncode(&buf, test.pver, test.enc)
err := test.in.BtcEncode(&buf, test.pver)
if err != nil {
t.Errorf("BtcEncode #%d error %v", i, err)
continue
@ -257,7 +246,7 @@ func TestGetBlocksWire(t *testing.T) {
// Decode the message from wire format.
var msg MsgGetBlocks
rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver, test.enc)
err = msg.BtcDecode(rbuf, test.pver)
if err != nil {
t.Errorf("BtcDecode #%d error %v", i, err)
continue
@ -336,31 +325,30 @@ func TestGetBlocksWireErrors(t *testing.T) {
}
tests := []struct {
in *MsgGetBlocks // Value to encode
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
enc MessageEncoding // Message encoding format
max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error
readErr error // Expected read error
in *MsgGetBlocks // Value to encode
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error
readErr error // Expected read error
}{
// Force error in protocol version.
{baseGetBlocks, baseGetBlocksEncoded, pver, BaseEncoding, 0, io.ErrShortWrite, io.EOF},
{baseGetBlocks, baseGetBlocksEncoded, pver, 0, io.ErrShortWrite, io.EOF},
// Force error in block locator hash count.
{baseGetBlocks, baseGetBlocksEncoded, pver, BaseEncoding, 4, io.ErrShortWrite, io.EOF},
{baseGetBlocks, baseGetBlocksEncoded, pver, 4, io.ErrShortWrite, io.EOF},
// Force error in block locator hashes.
{baseGetBlocks, baseGetBlocksEncoded, pver, BaseEncoding, 5, io.ErrShortWrite, io.EOF},
{baseGetBlocks, baseGetBlocksEncoded, pver, 5, io.ErrShortWrite, io.EOF},
// Force error in stop hash.
{baseGetBlocks, baseGetBlocksEncoded, pver, BaseEncoding, 69, io.ErrShortWrite, io.EOF},
{baseGetBlocks, baseGetBlocksEncoded, pver, 69, io.ErrShortWrite, io.EOF},
// Force error with greater than max block locator hashes.
{maxGetBlocks, maxGetBlocksEncoded, pver, BaseEncoding, 7, wireErr, wireErr},
{maxGetBlocks, maxGetBlocksEncoded, pver, 7, wireErr, wireErr},
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
// Encode to wire format.
w := newFixedWriter(test.max)
err := test.in.BtcEncode(w, test.pver, test.enc)
err := test.in.BtcEncode(w, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.writeErr) {
t.Errorf("BtcEncode #%d wrong error got: %v, want: %v",
i, err, test.writeErr)
@ -380,7 +368,7 @@ func TestGetBlocksWireErrors(t *testing.T) {
// Decode from wire format.
var msg MsgGetBlocks
r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver, test.enc)
err = msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) {
t.Errorf("BtcDecode #%d wrong error got: %v, want: %v",
i, err, test.readErr)

View File

@ -20,7 +20,7 @@ type MsgGetCFCheckpt struct {
// BtcDecode decodes r using the bitcoin protocol encoding into the receiver.
// This is part of the Message interface implementation.
func (msg *MsgGetCFCheckpt) BtcDecode(r io.Reader, pver uint32, _ MessageEncoding) error {
func (msg *MsgGetCFCheckpt) BtcDecode(r io.Reader, pver uint32) error {
err := readElement(r, &msg.FilterType)
if err != nil {
return err
@ -31,7 +31,7 @@ func (msg *MsgGetCFCheckpt) BtcDecode(r io.Reader, pver uint32, _ MessageEncodin
// BtcEncode encodes the receiver to w using the bitcoin protocol encoding.
// This is part of the Message interface implementation.
func (msg *MsgGetCFCheckpt) BtcEncode(w io.Writer, pver uint32, _ MessageEncoding) error {
func (msg *MsgGetCFCheckpt) BtcEncode(w io.Writer, pver uint32) error {
err := writeElement(w, msg.FilterType)
if err != nil {
return err

View File

@ -21,7 +21,7 @@ type MsgGetCFHeaders struct {
// BtcDecode decodes r using the bitcoin protocol encoding into the receiver.
// This is part of the Message interface implementation.
func (msg *MsgGetCFHeaders) BtcDecode(r io.Reader, pver uint32, _ MessageEncoding) error {
func (msg *MsgGetCFHeaders) BtcDecode(r io.Reader, pver uint32) error {
err := readElement(r, &msg.FilterType)
if err != nil {
return err
@ -37,7 +37,7 @@ func (msg *MsgGetCFHeaders) BtcDecode(r io.Reader, pver uint32, _ MessageEncodin
// BtcEncode encodes the receiver to w using the bitcoin protocol encoding.
// This is part of the Message interface implementation.
func (msg *MsgGetCFHeaders) BtcEncode(w io.Writer, pver uint32, _ MessageEncoding) error {
func (msg *MsgGetCFHeaders) BtcEncode(w io.Writer, pver uint32) error {
err := writeElement(w, msg.FilterType)
if err != nil {
return err

View File

@ -25,7 +25,7 @@ type MsgGetCFilters struct {
// BtcDecode decodes r using the bitcoin protocol encoding into the receiver.
// This is part of the Message interface implementation.
func (msg *MsgGetCFilters) BtcDecode(r io.Reader, pver uint32, _ MessageEncoding) error {
func (msg *MsgGetCFilters) BtcDecode(r io.Reader, pver uint32) error {
err := readElement(r, &msg.FilterType)
if err != nil {
return err
@ -41,7 +41,7 @@ func (msg *MsgGetCFilters) BtcDecode(r io.Reader, pver uint32, _ MessageEncoding
// BtcEncode encodes the receiver to w using the bitcoin protocol encoding.
// This is part of the Message interface implementation.
func (msg *MsgGetCFilters) BtcEncode(w io.Writer, pver uint32, _ MessageEncoding) error {
func (msg *MsgGetCFilters) BtcEncode(w io.Writer, pver uint32) error {
err := writeElement(w, msg.FilterType)
if err != nil {
return err

View File

@ -37,7 +37,7 @@ func (msg *MsgGetData) AddInvVect(iv *InvVect) error {
// BtcDecode decodes r using the bitcoin protocol encoding into the receiver.
// This is part of the Message interface implementation.
func (msg *MsgGetData) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error {
func (msg *MsgGetData) BtcDecode(r io.Reader, pver uint32) error {
count, err := ReadVarInt(r, pver)
if err != nil {
return err
@ -67,7 +67,7 @@ func (msg *MsgGetData) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding)
// BtcEncode encodes the receiver to w using the bitcoin protocol encoding.
// This is part of the Message interface implementation.
func (msg *MsgGetData) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {
func (msg *MsgGetData) BtcEncode(w io.Writer, pver uint32) error {
// Limit to max inventory vectors per message.
count := len(msg.InvList)
if count > MaxInvPerMsg {

View File

@ -113,11 +113,10 @@ func TestGetDataWire(t *testing.T) {
}
tests := []struct {
in *MsgGetData // Message to encode
out *MsgGetData // Expected decoded message
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
enc MessageEncoding // Message encoding format
in *MsgGetData // Message to encode
out *MsgGetData // Expected decoded message
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
}{
// Latest protocol version with no inv vectors.
{
@ -125,7 +124,6 @@ func TestGetDataWire(t *testing.T) {
NoInv,
NoInvEncoded,
ProtocolVersion,
BaseEncoding,
},
// Latest protocol version with multiple inv vectors.
@ -134,7 +132,6 @@ func TestGetDataWire(t *testing.T) {
MultiInv,
MultiInvEncoded,
ProtocolVersion,
BaseEncoding,
},
// Protocol version BIP0035Version no inv vectors.
@ -143,7 +140,6 @@ func TestGetDataWire(t *testing.T) {
NoInv,
NoInvEncoded,
BIP0035Version,
BaseEncoding,
},
// Protocol version BIP0035Version with multiple inv vectors.
@ -152,7 +148,6 @@ func TestGetDataWire(t *testing.T) {
MultiInv,
MultiInvEncoded,
BIP0035Version,
BaseEncoding,
},
// Protocol version BIP0031Version no inv vectors.
@ -161,7 +156,6 @@ func TestGetDataWire(t *testing.T) {
NoInv,
NoInvEncoded,
BIP0031Version,
BaseEncoding,
},
// Protocol version BIP0031Version with multiple inv vectors.
@ -170,7 +164,6 @@ func TestGetDataWire(t *testing.T) {
MultiInv,
MultiInvEncoded,
BIP0031Version,
BaseEncoding,
},
// Protocol version NetAddressTimeVersion no inv vectors.
@ -179,7 +172,6 @@ func TestGetDataWire(t *testing.T) {
NoInv,
NoInvEncoded,
NetAddressTimeVersion,
BaseEncoding,
},
// Protocol version NetAddressTimeVersion with multiple inv vectors.
@ -188,7 +180,6 @@ func TestGetDataWire(t *testing.T) {
MultiInv,
MultiInvEncoded,
NetAddressTimeVersion,
BaseEncoding,
},
// Protocol version MultipleAddressVersion no inv vectors.
@ -197,7 +188,6 @@ func TestGetDataWire(t *testing.T) {
NoInv,
NoInvEncoded,
MultipleAddressVersion,
BaseEncoding,
},
// Protocol version MultipleAddressVersion with multiple inv vectors.
@ -206,7 +196,6 @@ func TestGetDataWire(t *testing.T) {
MultiInv,
MultiInvEncoded,
MultipleAddressVersion,
BaseEncoding,
},
}
@ -214,7 +203,7 @@ func TestGetDataWire(t *testing.T) {
for i, test := range tests {
// Encode the message to wire format.
var buf bytes.Buffer
err := test.in.BtcEncode(&buf, test.pver, test.enc)
err := test.in.BtcEncode(&buf, test.pver)
if err != nil {
t.Errorf("BtcEncode #%d error %v", i, err)
continue
@ -228,7 +217,7 @@ func TestGetDataWire(t *testing.T) {
// Decode the message from wire format.
var msg MsgGetData
rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver, test.enc)
err = msg.BtcDecode(rbuf, test.pver)
if err != nil {
t.Errorf("BtcDecode #%d error %v", i, err)
continue
@ -280,28 +269,27 @@ func TestGetDataWireErrors(t *testing.T) {
}
tests := []struct {
in *MsgGetData // Value to encode
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
enc MessageEncoding // Message encoding format
max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error
readErr error // Expected read error
in *MsgGetData // Value to encode
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error
readErr error // Expected read error
}{
// Latest protocol version with intentional read/write errors.
// Force error in inventory vector count
{baseGetData, baseGetDataEncoded, pver, BaseEncoding, 0, io.ErrShortWrite, io.EOF},
{baseGetData, baseGetDataEncoded, pver, 0, io.ErrShortWrite, io.EOF},
// Force error in inventory list.
{baseGetData, baseGetDataEncoded, pver, BaseEncoding, 1, io.ErrShortWrite, io.EOF},
{baseGetData, baseGetDataEncoded, pver, 1, io.ErrShortWrite, io.EOF},
// Force error with greater than max inventory vectors.
{maxGetData, maxGetDataEncoded, pver, BaseEncoding, 3, wireErr, wireErr},
{maxGetData, maxGetDataEncoded, pver, 3, wireErr, wireErr},
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
// Encode to wire format.
w := newFixedWriter(test.max)
err := test.in.BtcEncode(w, test.pver, test.enc)
err := test.in.BtcEncode(w, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.writeErr) {
t.Errorf("BtcEncode #%d wrong error got: %v, want: %v",
i, err, test.writeErr)
@ -321,7 +309,7 @@ func TestGetDataWireErrors(t *testing.T) {
// Decode from wire format.
var msg MsgGetData
r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver, test.enc)
err = msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) {
t.Errorf("BtcDecode #%d wrong error got: %v, want: %v",
i, err, test.readErr)

View File

@ -47,7 +47,7 @@ func (msg *MsgGetHeaders) AddBlockLocatorHash(hash *chainhash.Hash) error {
// BtcDecode decodes r using the bitcoin protocol encoding into the receiver.
// This is part of the Message interface implementation.
func (msg *MsgGetHeaders) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error {
func (msg *MsgGetHeaders) BtcDecode(r io.Reader, pver uint32) error {
err := readElement(r, &msg.ProtocolVersion)
if err != nil {
return err
@ -82,7 +82,7 @@ func (msg *MsgGetHeaders) BtcDecode(r io.Reader, pver uint32, enc MessageEncodin
// BtcEncode encodes the receiver to w using the bitcoin protocol encoding.
// This is part of the Message interface implementation.
func (msg *MsgGetHeaders) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {
func (msg *MsgGetHeaders) BtcEncode(w io.Writer, pver uint32) error {
// Limit to max block locator hashes per message.
count := len(msg.BlockLocatorHashes)
if count > MaxBlockLocatorsPerMsg {

View File

@ -132,11 +132,10 @@ func TestGetHeadersWire(t *testing.T) {
}
tests := []struct {
in *MsgGetHeaders // Message to encode
out *MsgGetHeaders // Expected decoded message
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
enc MessageEncoding // Message encoding format
in *MsgGetHeaders // Message to encode
out *MsgGetHeaders // Expected decoded message
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
}{
// Latest protocol version with no block locators.
{
@ -144,7 +143,6 @@ func TestGetHeadersWire(t *testing.T) {
noLocators,
noLocatorsEncoded,
ProtocolVersion,
BaseEncoding,
},
// Latest protocol version with multiple block locators.
@ -153,7 +151,6 @@ func TestGetHeadersWire(t *testing.T) {
multiLocators,
multiLocatorsEncoded,
ProtocolVersion,
BaseEncoding,
},
// Protocol version BIP0035Version with no block locators.
@ -162,7 +159,6 @@ func TestGetHeadersWire(t *testing.T) {
noLocators,
noLocatorsEncoded,
BIP0035Version,
BaseEncoding,
},
// Protocol version BIP0035Version with multiple block locators.
@ -171,7 +167,6 @@ func TestGetHeadersWire(t *testing.T) {
multiLocators,
multiLocatorsEncoded,
BIP0035Version,
BaseEncoding,
},
// Protocol version BIP0031Version with no block locators.
@ -180,7 +175,6 @@ func TestGetHeadersWire(t *testing.T) {
noLocators,
noLocatorsEncoded,
BIP0031Version,
BaseEncoding,
},
// Protocol version BIP0031Versionwith multiple block locators.
@ -189,7 +183,6 @@ func TestGetHeadersWire(t *testing.T) {
multiLocators,
multiLocatorsEncoded,
BIP0031Version,
BaseEncoding,
},
// Protocol version NetAddressTimeVersion with no block locators.
@ -198,7 +191,6 @@ func TestGetHeadersWire(t *testing.T) {
noLocators,
noLocatorsEncoded,
NetAddressTimeVersion,
BaseEncoding,
},
// Protocol version NetAddressTimeVersion multiple block locators.
@ -207,7 +199,6 @@ func TestGetHeadersWire(t *testing.T) {
multiLocators,
multiLocatorsEncoded,
NetAddressTimeVersion,
BaseEncoding,
},
// Protocol version MultipleAddressVersion with no block locators.
@ -216,7 +207,6 @@ func TestGetHeadersWire(t *testing.T) {
noLocators,
noLocatorsEncoded,
MultipleAddressVersion,
BaseEncoding,
},
// Protocol version MultipleAddressVersion multiple block locators.
@ -225,7 +215,6 @@ func TestGetHeadersWire(t *testing.T) {
multiLocators,
multiLocatorsEncoded,
MultipleAddressVersion,
BaseEncoding,
},
}
@ -233,7 +222,7 @@ func TestGetHeadersWire(t *testing.T) {
for i, test := range tests {
// Encode the message to wire format.
var buf bytes.Buffer
err := test.in.BtcEncode(&buf, test.pver, test.enc)
err := test.in.BtcEncode(&buf, test.pver)
if err != nil {
t.Errorf("BtcEncode #%d error %v", i, err)
continue
@ -247,7 +236,7 @@ func TestGetHeadersWire(t *testing.T) {
// Decode the message from wire format.
var msg MsgGetHeaders
rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver, test.enc)
err = msg.BtcDecode(rbuf, test.pver)
if err != nil {
t.Errorf("BtcDecode #%d error %v", i, err)
continue
@ -327,31 +316,30 @@ func TestGetHeadersWireErrors(t *testing.T) {
}
tests := []struct {
in *MsgGetHeaders // Value to encode
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
enc MessageEncoding // Message encoding format
max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error
readErr error // Expected read error
in *MsgGetHeaders // Value to encode
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error
readErr error // Expected read error
}{
// Force error in protocol version.
{baseGetHeaders, baseGetHeadersEncoded, pver, BaseEncoding, 0, io.ErrShortWrite, io.EOF},
{baseGetHeaders, baseGetHeadersEncoded, pver, 0, io.ErrShortWrite, io.EOF},
// Force error in block locator hash count.
{baseGetHeaders, baseGetHeadersEncoded, pver, BaseEncoding, 4, io.ErrShortWrite, io.EOF},
{baseGetHeaders, baseGetHeadersEncoded, pver, 4, io.ErrShortWrite, io.EOF},
// Force error in block locator hashes.
{baseGetHeaders, baseGetHeadersEncoded, pver, BaseEncoding, 5, io.ErrShortWrite, io.EOF},
{baseGetHeaders, baseGetHeadersEncoded, pver, 5, io.ErrShortWrite, io.EOF},
// Force error in stop hash.
{baseGetHeaders, baseGetHeadersEncoded, pver, BaseEncoding, 69, io.ErrShortWrite, io.EOF},
{baseGetHeaders, baseGetHeadersEncoded, pver, 69, io.ErrShortWrite, io.EOF},
// Force error with greater than max block locator hashes.
{maxGetHeaders, maxGetHeadersEncoded, pver, BaseEncoding, 7, wireErr, wireErr},
{maxGetHeaders, maxGetHeadersEncoded, pver, 7, wireErr, wireErr},
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
// Encode to wire format.
w := newFixedWriter(test.max)
err := test.in.BtcEncode(w, test.pver, test.enc)
err := test.in.BtcEncode(w, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.writeErr) {
t.Errorf("BtcEncode #%d wrong error got: %v, want: %v",
i, err, test.writeErr)
@ -371,7 +359,7 @@ func TestGetHeadersWireErrors(t *testing.T) {
// Decode from wire format.
var msg MsgGetHeaders
r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver, test.enc)
err = msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) {
t.Errorf("BtcDecode #%d wrong error got: %v, want: %v",
i, err, test.readErr)

View File

@ -36,7 +36,7 @@ func (msg *MsgHeaders) AddBlockHeader(bh *BlockHeader) error {
// BtcDecode decodes r using the bitcoin protocol encoding into the receiver.
// This is part of the Message interface implementation.
func (msg *MsgHeaders) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error {
func (msg *MsgHeaders) BtcDecode(r io.Reader, pver uint32) error {
count, err := ReadVarInt(r, pver)
if err != nil {
return err
@ -79,7 +79,7 @@ func (msg *MsgHeaders) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding)
// BtcEncode encodes the receiver to w using the bitcoin protocol encoding.
// This is part of the Message interface implementation.
func (msg *MsgHeaders) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {
func (msg *MsgHeaders) BtcEncode(w io.Writer, pver uint32) error {
// Limit to max block headers per message.
count := len(msg.Headers)
if count > MaxBlockHeadersPerMsg {

View File

@ -95,11 +95,10 @@ func TestHeadersWire(t *testing.T) {
}
tests := []struct {
in *MsgHeaders // Message to encode
out *MsgHeaders // Expected decoded message
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
enc MessageEncoding // Message encoding format
in *MsgHeaders // Message to encode
out *MsgHeaders // Expected decoded message
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
}{
// Latest protocol version with no headers.
{
@ -107,7 +106,6 @@ func TestHeadersWire(t *testing.T) {
noHeaders,
noHeadersEncoded,
ProtocolVersion,
BaseEncoding,
},
// Latest protocol version with one header.
@ -116,7 +114,6 @@ func TestHeadersWire(t *testing.T) {
oneHeader,
oneHeaderEncoded,
ProtocolVersion,
BaseEncoding,
},
// Protocol version BIP0035Version with no headers.
@ -125,7 +122,6 @@ func TestHeadersWire(t *testing.T) {
noHeaders,
noHeadersEncoded,
BIP0035Version,
BaseEncoding,
},
// Protocol version BIP0035Version with one header.
@ -134,7 +130,6 @@ func TestHeadersWire(t *testing.T) {
oneHeader,
oneHeaderEncoded,
BIP0035Version,
BaseEncoding,
},
// Protocol version BIP0031Version with no headers.
@ -143,7 +138,6 @@ func TestHeadersWire(t *testing.T) {
noHeaders,
noHeadersEncoded,
BIP0031Version,
BaseEncoding,
},
// Protocol version BIP0031Version with one header.
@ -152,7 +146,6 @@ func TestHeadersWire(t *testing.T) {
oneHeader,
oneHeaderEncoded,
BIP0031Version,
BaseEncoding,
},
// Protocol version NetAddressTimeVersion with no headers.
{
@ -160,7 +153,6 @@ func TestHeadersWire(t *testing.T) {
noHeaders,
noHeadersEncoded,
NetAddressTimeVersion,
BaseEncoding,
},
// Protocol version NetAddressTimeVersion with one header.
@ -169,7 +161,6 @@ func TestHeadersWire(t *testing.T) {
oneHeader,
oneHeaderEncoded,
NetAddressTimeVersion,
BaseEncoding,
},
// Protocol version MultipleAddressVersion with no headers.
@ -178,7 +169,6 @@ func TestHeadersWire(t *testing.T) {
noHeaders,
noHeadersEncoded,
MultipleAddressVersion,
BaseEncoding,
},
// Protocol version MultipleAddressVersion with one header.
@ -187,7 +177,6 @@ func TestHeadersWire(t *testing.T) {
oneHeader,
oneHeaderEncoded,
MultipleAddressVersion,
BaseEncoding,
},
}
@ -195,7 +184,7 @@ func TestHeadersWire(t *testing.T) {
for i, test := range tests {
// Encode the message to wire format.
var buf bytes.Buffer
err := test.in.BtcEncode(&buf, test.pver, test.enc)
err := test.in.BtcEncode(&buf, test.pver)
if err != nil {
t.Errorf("BtcEncode #%d error %v", i, err)
continue
@ -209,7 +198,7 @@ func TestHeadersWire(t *testing.T) {
// Decode the message from wire format.
var msg MsgHeaders
rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver, test.enc)
err = msg.BtcDecode(rbuf, test.pver)
if err != nil {
t.Errorf("BtcDecode #%d error %v", i, err)
continue
@ -293,32 +282,31 @@ func TestHeadersWireErrors(t *testing.T) {
}
tests := []struct {
in *MsgHeaders // Value to encode
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
enc MessageEncoding // Message encoding format
max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error
readErr error // Expected read error
in *MsgHeaders // Value to encode
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error
readErr error // Expected read error
}{
// Latest protocol version with intentional read/write errors.
// Force error in header count.
{oneHeader, oneHeaderEncoded, pver, BaseEncoding, 0, io.ErrShortWrite, io.EOF},
{oneHeader, oneHeaderEncoded, pver, 0, io.ErrShortWrite, io.EOF},
// Force error in block header.
{oneHeader, oneHeaderEncoded, pver, BaseEncoding, 5, io.ErrShortWrite, io.EOF},
{oneHeader, oneHeaderEncoded, pver, 5, io.ErrShortWrite, io.EOF},
// Force error with greater than max headers.
{maxHeaders, maxHeadersEncoded, pver, BaseEncoding, 3, wireErr, wireErr},
{maxHeaders, maxHeadersEncoded, pver, 3, wireErr, wireErr},
// Force error with number of transactions.
{transHeader, transHeaderEncoded, pver, BaseEncoding, 81, io.ErrShortWrite, io.EOF},
{transHeader, transHeaderEncoded, pver, 81, io.ErrShortWrite, io.EOF},
// Force error with included transactions.
{transHeader, transHeaderEncoded, pver, BaseEncoding, len(transHeaderEncoded), nil, wireErr},
{transHeader, transHeaderEncoded, pver, len(transHeaderEncoded), nil, wireErr},
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
// Encode to wire format.
w := newFixedWriter(test.max)
err := test.in.BtcEncode(w, test.pver, test.enc)
err := test.in.BtcEncode(w, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.writeErr) {
t.Errorf("BtcEncode #%d wrong error got: %v, want: %v",
i, err, test.writeErr)
@ -338,7 +326,7 @@ func TestHeadersWireErrors(t *testing.T) {
// Decode from wire format.
var msg MsgHeaders
r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver, test.enc)
err = msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) {
t.Errorf("BtcDecode #%d wrong error got: %v, want: %v",
i, err, test.readErr)

View File

@ -45,7 +45,7 @@ func (msg *MsgInv) AddInvVect(iv *InvVect) error {
// BtcDecode decodes r using the bitcoin protocol encoding into the receiver.
// This is part of the Message interface implementation.
func (msg *MsgInv) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error {
func (msg *MsgInv) BtcDecode(r io.Reader, pver uint32) error {
count, err := ReadVarInt(r, pver)
if err != nil {
return err
@ -75,7 +75,7 @@ func (msg *MsgInv) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) erro
// BtcEncode encodes the receiver to w using the bitcoin protocol encoding.
// This is part of the Message interface implementation.
func (msg *MsgInv) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {
func (msg *MsgInv) BtcEncode(w io.Writer, pver uint32) error {
// Limit to max inventory vectors per message.
count := len(msg.InvList)
if count > MaxInvPerMsg {

View File

@ -113,11 +113,10 @@ func TestInvWire(t *testing.T) {
}
tests := []struct {
in *MsgInv // Message to encode
out *MsgInv // Expected decoded message
buf []byte // Wire encoding pver uint32
pver uint32 // Protocol version for wire encoding
enc MessageEncoding // Message encodinf format
in *MsgInv // Message to encode
out *MsgInv // Expected decoded message
buf []byte // Wire encoding pver uint32
pver uint32 // Protocol version for wire encoding
}{
// Latest protocol version with no inv vectors.
{
@ -125,7 +124,6 @@ func TestInvWire(t *testing.T) {
NoInv,
NoInvEncoded,
ProtocolVersion,
BaseEncoding,
},
// Latest protocol version with multiple inv vectors.
@ -134,7 +132,6 @@ func TestInvWire(t *testing.T) {
MultiInv,
MultiInvEncoded,
ProtocolVersion,
BaseEncoding,
},
// Protocol version BIP0035Version no inv vectors.
@ -143,7 +140,6 @@ func TestInvWire(t *testing.T) {
NoInv,
NoInvEncoded,
BIP0035Version,
BaseEncoding,
},
// Protocol version BIP0035Version with multiple inv vectors.
@ -152,7 +148,6 @@ func TestInvWire(t *testing.T) {
MultiInv,
MultiInvEncoded,
BIP0035Version,
BaseEncoding,
},
// Protocol version BIP0031Version no inv vectors.
@ -161,7 +156,6 @@ func TestInvWire(t *testing.T) {
NoInv,
NoInvEncoded,
BIP0031Version,
BaseEncoding,
},
// Protocol version BIP0031Version with multiple inv vectors.
@ -170,7 +164,6 @@ func TestInvWire(t *testing.T) {
MultiInv,
MultiInvEncoded,
BIP0031Version,
BaseEncoding,
},
// Protocol version NetAddressTimeVersion no inv vectors.
@ -179,7 +172,6 @@ func TestInvWire(t *testing.T) {
NoInv,
NoInvEncoded,
NetAddressTimeVersion,
BaseEncoding,
},
// Protocol version NetAddressTimeVersion with multiple inv vectors.
@ -188,7 +180,6 @@ func TestInvWire(t *testing.T) {
MultiInv,
MultiInvEncoded,
NetAddressTimeVersion,
BaseEncoding,
},
// Protocol version MultipleAddressVersion no inv vectors.
@ -197,7 +188,6 @@ func TestInvWire(t *testing.T) {
NoInv,
NoInvEncoded,
MultipleAddressVersion,
BaseEncoding,
},
// Protocol version MultipleAddressVersion with multiple inv vectors.
@ -206,7 +196,6 @@ func TestInvWire(t *testing.T) {
MultiInv,
MultiInvEncoded,
MultipleAddressVersion,
BaseEncoding,
},
}
@ -214,7 +203,7 @@ func TestInvWire(t *testing.T) {
for i, test := range tests {
// Encode the message to wire format.
var buf bytes.Buffer
err := test.in.BtcEncode(&buf, test.pver, test.enc)
err := test.in.BtcEncode(&buf, test.pver)
if err != nil {
t.Errorf("BtcEncode #%d error %v", i, err)
continue
@ -228,7 +217,7 @@ func TestInvWire(t *testing.T) {
// Decode the message from wire format.
var msg MsgInv
rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver, test.enc)
err = msg.BtcDecode(rbuf, test.pver)
if err != nil {
t.Errorf("BtcDecode #%d error %v", i, err)
continue
@ -280,28 +269,27 @@ func TestInvWireErrors(t *testing.T) {
}
tests := []struct {
in *MsgInv // Value to encode
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
enc MessageEncoding // Message encoding format
max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error
readErr error // Expected read error
in *MsgInv // Value to encode
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error
readErr error // Expected read error
}{
// Latest protocol version with intentional read/write errors.
// Force error in inventory vector count
{baseInv, baseInvEncoded, pver, BaseEncoding, 0, io.ErrShortWrite, io.EOF},
{baseInv, baseInvEncoded, pver, 0, io.ErrShortWrite, io.EOF},
// Force error in inventory list.
{baseInv, baseInvEncoded, pver, BaseEncoding, 1, io.ErrShortWrite, io.EOF},
{baseInv, baseInvEncoded, pver, 1, io.ErrShortWrite, io.EOF},
// Force error with greater than max inventory vectors.
{maxInv, maxInvEncoded, pver, BaseEncoding, 3, wireErr, wireErr},
{maxInv, maxInvEncoded, pver, 3, wireErr, wireErr},
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
// Encode to wire format.
w := newFixedWriter(test.max)
err := test.in.BtcEncode(w, test.pver, test.enc)
err := test.in.BtcEncode(w, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.writeErr) {
t.Errorf("BtcEncode #%d wrong error got: %v, want: %v",
i, err, test.writeErr)
@ -321,7 +309,7 @@ func TestInvWireErrors(t *testing.T) {
// Decode from wire format.
var msg MsgInv
r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver, test.enc)
err = msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) {
t.Errorf("BtcDecode #%d wrong error got: %v, want: %v",
i, err, test.readErr)

View File

@ -19,7 +19,7 @@ type MsgMemPool struct{}
// BtcDecode decodes r using the bitcoin protocol encoding into the receiver.
// This is part of the Message interface implementation.
func (msg *MsgMemPool) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error {
func (msg *MsgMemPool) BtcDecode(r io.Reader, pver uint32) error {
if pver < BIP0035Version {
str := fmt.Sprintf("mempool message invalid for protocol "+
"version %d", pver)
@ -31,7 +31,7 @@ func (msg *MsgMemPool) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding)
// BtcEncode encodes the receiver to w using the bitcoin protocol encoding.
// This is part of the Message interface implementation.
func (msg *MsgMemPool) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {
func (msg *MsgMemPool) BtcEncode(w io.Writer, pver uint32) error {
if pver < BIP0035Version {
str := fmt.Sprintf("mempool message invalid for protocol "+
"version %d", pver)

View File

@ -11,7 +11,6 @@ import (
func TestMemPool(t *testing.T) {
pver := ProtocolVersion
enc := BaseEncoding
// Ensure the command is expected value.
wantCmd := "mempool"
@ -32,7 +31,7 @@ func TestMemPool(t *testing.T) {
// Test encode with latest protocol version.
var buf bytes.Buffer
err := msg.BtcEncode(&buf, pver, enc)
err := msg.BtcEncode(&buf, pver)
if err != nil {
t.Errorf("encode of MsgMemPool failed %v err <%v>", msg, err)
}
@ -40,7 +39,7 @@ func TestMemPool(t *testing.T) {
// Older protocol versions should fail encode since message didn't
// exist yet.
oldPver := BIP0035Version - 1
err = msg.BtcEncode(&buf, oldPver, enc)
err = msg.BtcEncode(&buf, oldPver)
if err == nil {
s := "encode of MsgMemPool passed for old protocol version %v err <%v>"
t.Errorf(s, msg, err)
@ -48,14 +47,14 @@ func TestMemPool(t *testing.T) {
// Test decode with latest protocol version.
readmsg := NewMsgMemPool()
err = readmsg.BtcDecode(&buf, pver, enc)
err = readmsg.BtcDecode(&buf, pver)
if err != nil {
t.Errorf("decode of MsgMemPool failed [%v] err <%v>", buf, err)
}
// Older protocol versions should fail decode since message didn't
// exist yet.
err = readmsg.BtcDecode(&buf, oldPver, enc)
err = readmsg.BtcDecode(&buf, oldPver)
if err == nil {
s := "decode of MsgMemPool passed for old protocol version %v err <%v>"
t.Errorf(s, msg, err)

Some files were not shown because too many files have changed in this diff Show More