1 // Copyright (c) 2016 The btcsuite developers
2 // Use of this source code is governed by an ISC
3 // license that can be found in the LICENSE file.
5 // The vast majority of the rules tested in this package were ported from the
6 // the original Java-based 'official' block acceptance tests at
7 // https://github.com/TheBlueMatt/test-scripts as well as some additional tests
8 // available in the Core python port of the same.
10 package fullblocktests
21 "github.com/btcsuite/btcd/blockchain"
22 "github.com/btcsuite/btcd/btcec"
23 "github.com/btcsuite/btcd/chaincfg"
24 "github.com/btcsuite/btcd/chaincfg/chainhash"
25 "github.com/btcsuite/btcd/txscript"
26 "github.com/btcsuite/btcd/wire"
27 "github.com/btcsuite/btcutil"
31 // Intentionally defined here rather than using constants from codebase
32 // to ensure consensus changes are detected.
33 maxBlockSigOps = 20000
34 maxBlockSize = 1000000
35 minCoinbaseScriptLen = 2
36 maxCoinbaseScriptLen = 100
38 maxScriptElementSize = 520
40 // numLargeReorgBlocks is the number of blocks to use in the large block
41 // reorg test (when enabled). This is the equivalent of 1 week's worth
43 numLargeReorgBlocks = 1088
47 // opTrueScript is simply a public key script that contains the OP_TRUE
48 // opcode. It is defined here to reduce garbage creation.
49 opTrueScript = []byte{txscript.OP_TRUE}
51 // lowFee is a single satoshi and exists to make the test code more
53 lowFee = btcutil.Amount(1)
56 // TestInstance is an interface that describes a specific test instance returned
57 // by the tests generated in this package. It should be type asserted to one
58 // of the concrete test instance types in order to test accordingly.
59 type TestInstance interface {
60 FullBlockTestInstance()
63 // AcceptedBlock defines a test instance that expects a block to be accepted to
64 // the blockchain either by extending the main chain, on a side chain, or as an
66 type AcceptedBlock struct {
74 // Ensure AcceptedBlock implements the TestInstance interface.
75 var _ TestInstance = AcceptedBlock{}
77 // FullBlockTestInstance only exists to allow AcceptedBlock to be treated as a
80 // This implements the TestInstance interface.
81 func (b AcceptedBlock) FullBlockTestInstance() {}
83 // RejectedBlock defines a test instance that expects a block to be rejected by
84 // the blockchain consensus rules.
85 type RejectedBlock struct {
89 RejectCode blockchain.ErrorCode
92 // Ensure RejectedBlock implements the TestInstance interface.
93 var _ TestInstance = RejectedBlock{}
95 // FullBlockTestInstance only exists to allow RejectedBlock to be treated as a
98 // This implements the TestInstance interface.
99 func (b RejectedBlock) FullBlockTestInstance() {}
101 // OrphanOrRejectedBlock defines a test instance that expects a block to either
102 // be accepted as an orphan or rejected. This is useful since some
103 // implementations might optimize the immediate rejection of orphan blocks when
104 // their parent was previously rejected, while others might accept it as an
105 // orphan that eventually gets flushed (since the parent can never be accepted
106 // to ultimately link it).
107 type OrphanOrRejectedBlock struct {
113 // Ensure ExpectedTip implements the TestInstance interface.
114 var _ TestInstance = OrphanOrRejectedBlock{}
116 // FullBlockTestInstance only exists to allow OrphanOrRejectedBlock to be
117 // treated as a TestInstance.
119 // This implements the TestInstance interface.
120 func (b OrphanOrRejectedBlock) FullBlockTestInstance() {}
122 // ExpectedTip defines a test instance that expects a block to be the current
123 // tip of the main chain.
124 type ExpectedTip struct {
130 // Ensure ExpectedTip implements the TestInstance interface.
131 var _ TestInstance = ExpectedTip{}
133 // FullBlockTestInstance only exists to allow ExpectedTip to be treated as a
136 // This implements the TestInstance interface.
137 func (b ExpectedTip) FullBlockTestInstance() {}
139 // RejectedNonCanonicalBlock defines a test instance that expects a serialized
140 // block that is not canonical and therefore should be rejected.
141 type RejectedNonCanonicalBlock struct {
147 // FullBlockTestInstance only exists to allow RejectedNonCanonicalBlock to be treated as
150 // This implements the TestInstance interface.
151 func (b RejectedNonCanonicalBlock) FullBlockTestInstance() {}
153 // spendableOut represents a transaction output that is spendable along with
154 // additional metadata such as the block its in and how much it pays.
155 type spendableOut struct {
156 prevOut wire.OutPoint
157 amount btcutil.Amount
160 // makeSpendableOutForTx returns a spendable output for the given transaction
161 // and transaction output index within the transaction.
162 func makeSpendableOutForTx(tx *wire.MsgTx, txOutIndex uint32) spendableOut {
164 prevOut: wire.OutPoint{
168 amount: btcutil.Amount(tx.TxOut[txOutIndex].Value),
172 // makeSpendableOut returns a spendable output for the given block, transaction
173 // index within the block, and transaction output index within the transaction.
174 func makeSpendableOut(block *wire.MsgBlock, txIndex, txOutIndex uint32) spendableOut {
175 return makeSpendableOutForTx(block.Transactions[txIndex], txOutIndex)
178 // testGenerator houses state used to easy the process of generating test blocks
179 // that build from one another along with housing other useful things such as
180 // available spendable outputs used throughout the tests.
181 type testGenerator struct {
182 params *chaincfg.Params
186 blocks map[chainhash.Hash]*wire.MsgBlock
187 blocksByName map[string]*wire.MsgBlock
188 blockHeights map[string]int32
190 // Used for tracking spendable coinbase outputs.
191 spendableOuts []spendableOut
192 prevCollectedHash chainhash.Hash
194 // Common key for any tests which require signed transactions.
195 privKey *btcec.PrivateKey
198 // makeTestGenerator returns a test generator instance initialized with the
199 // genesis block as the tip.
200 func makeTestGenerator(params *chaincfg.Params) (testGenerator, error) {
201 privKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), []byte{0x01})
202 genesis := params.GenesisBlock
203 genesisHash := genesis.BlockHash()
204 return testGenerator{
206 blocks: map[chainhash.Hash]*wire.MsgBlock{genesisHash: genesis},
207 blocksByName: map[string]*wire.MsgBlock{"genesis": genesis},
208 blockHeights: map[string]int32{"genesis": 0},
216 // payToScriptHashScript returns a standard pay-to-script-hash for the provided
218 func payToScriptHashScript(redeemScript []byte) []byte {
219 redeemScriptHash := btcutil.Hash160(redeemScript)
220 script, err := txscript.NewScriptBuilder().
221 AddOp(txscript.OP_HASH160).AddData(redeemScriptHash).
222 AddOp(txscript.OP_EQUAL).Script()
229 // pushDataScript returns a script with the provided items individually pushed
231 func pushDataScript(items ...[]byte) []byte {
232 builder := txscript.NewScriptBuilder()
233 for _, item := range items {
234 builder.AddData(item)
236 script, err := builder.Script()
243 // standardCoinbaseScript returns a standard script suitable for use as the
244 // signature script of the coinbase transaction of a new block. In particular,
245 // it starts with the block height that is required by version 2 blocks.
246 func standardCoinbaseScript(blockHeight int32, extraNonce uint64) ([]byte, error) {
247 return txscript.NewScriptBuilder().AddInt64(int64(blockHeight)).
248 AddInt64(int64(extraNonce)).Script()
251 // opReturnScript returns a provably-pruneable OP_RETURN script with the
253 func opReturnScript(data []byte) []byte {
254 builder := txscript.NewScriptBuilder()
255 script, err := builder.AddOp(txscript.OP_RETURN).AddData(data).Script()
262 // uniqueOpReturnScript returns a standard provably-pruneable OP_RETURN script
263 // with a random uint64 encoded as the data.
264 func uniqueOpReturnScript() []byte {
265 rand, err := wire.RandomUint64()
270 data := make([]byte, 8)
271 binary.LittleEndian.PutUint64(data[0:8], rand)
272 return opReturnScript(data)
275 // createCoinbaseTx returns a coinbase transaction paying an appropriate
276 // subsidy based on the passed block height. The coinbase signature script
277 // conforms to the requirements of version 2 blocks.
278 func (g *testGenerator) createCoinbaseTx(blockHeight int32) *wire.MsgTx {
279 extraNonce := uint64(0)
280 coinbaseScript, err := standardCoinbaseScript(blockHeight, extraNonce)
285 tx := wire.NewMsgTx(1)
286 tx.AddTxIn(&wire.TxIn{
287 // Coinbase transactions have no inputs, so previous outpoint is
288 // zero hash and max index.
289 PreviousOutPoint: *wire.NewOutPoint(&chainhash.Hash{},
290 wire.MaxPrevOutIndex),
291 Sequence: wire.MaxTxInSequenceNum,
292 SignatureScript: coinbaseScript,
294 tx.AddTxOut(&wire.TxOut{
295 Value: blockchain.CalcBlockSubsidy(blockHeight, g.params),
296 PkScript: opTrueScript,
301 // calcMerkleRoot creates a merkle tree from the slice of transactions and
302 // returns the root of the tree.
303 func calcMerkleRoot(txns []*wire.MsgTx) chainhash.Hash {
305 return chainhash.Hash{}
308 utilTxns := make([]*btcutil.Tx, 0, len(txns))
309 for _, tx := range txns {
310 utilTxns = append(utilTxns, btcutil.NewTx(tx))
312 merkles := blockchain.BuildMerkleTreeStore(utilTxns, false)
313 return *merkles[len(merkles)-1]
316 // solveBlock attempts to find a nonce which makes the passed block header hash
317 // to a value less than the target difficulty. When a successful solution is
318 // found true is returned and the nonce field of the passed header is updated
319 // with the solution. False is returned if no solution exists.
321 // NOTE: This function will never solve blocks with a nonce of 0. This is done
322 // so the 'nextBlock' function can properly detect when a nonce was modified by
324 func solveBlock(header *wire.BlockHeader) bool {
325 // sbResult is used by the solver goroutines to send results.
326 type sbResult struct {
331 // solver accepts a block header and a nonce range to test. It is
332 // intended to be run as a goroutine.
333 targetDifficulty := blockchain.CompactToBig(header.Bits)
334 quit := make(chan bool)
335 results := make(chan sbResult)
336 solver := func(hdr wire.BlockHeader, startNonce, stopNonce uint32) {
337 // We need to modify the nonce field of the header, so make sure
338 // we work with a copy of the original header.
339 for i := startNonce; i >= startNonce && i <= stopNonce; i++ {
345 hash := hdr.BlockHash()
346 if blockchain.HashToBig(&hash).Cmp(
347 targetDifficulty) <= 0 {
349 results <- sbResult{true, i}
354 results <- sbResult{false, 0}
357 startNonce := uint32(1)
358 stopNonce := uint32(math.MaxUint32)
359 numCores := uint32(runtime.NumCPU())
360 noncesPerCore := (stopNonce - startNonce) / numCores
361 for i := uint32(0); i < numCores; i++ {
362 rangeStart := startNonce + (noncesPerCore * i)
363 rangeStop := startNonce + (noncesPerCore * (i + 1)) - 1
365 rangeStop = stopNonce
367 go solver(*header, rangeStart, rangeStop)
369 for i := uint32(0); i < numCores; i++ {
373 header.Nonce = result.nonce
381 // additionalCoinbase returns a function that itself takes a block and
382 // modifies it by adding the provided amount to coinbase subsidy.
383 func additionalCoinbase(amount btcutil.Amount) func(*wire.MsgBlock) {
384 return func(b *wire.MsgBlock) {
385 // Increase the first proof-of-work coinbase subsidy by the
387 b.Transactions[0].TxOut[0].Value += int64(amount)
391 // additionalSpendFee returns a function that itself takes a block and modifies
392 // it by adding the provided fee to the spending transaction.
394 // NOTE: The coinbase value is NOT updated to reflect the additional fee. Use
395 // 'additionalCoinbase' for that purpose.
396 func additionalSpendFee(fee btcutil.Amount) func(*wire.MsgBlock) {
397 return func(b *wire.MsgBlock) {
398 // Increase the fee of the spending transaction by reducing the
400 if int64(fee) > b.Transactions[1].TxOut[0].Value {
401 panic(fmt.Sprintf("additionalSpendFee: fee of %d "+
402 "exceeds available spend transaction value",
405 b.Transactions[1].TxOut[0].Value -= int64(fee)
409 // replaceSpendScript returns a function that itself takes a block and modifies
410 // it by replacing the public key script of the spending transaction.
411 func replaceSpendScript(pkScript []byte) func(*wire.MsgBlock) {
412 return func(b *wire.MsgBlock) {
413 b.Transactions[1].TxOut[0].PkScript = pkScript
417 // replaceCoinbaseSigScript returns a function that itself takes a block and
418 // modifies it by replacing the signature key script of the coinbase.
419 func replaceCoinbaseSigScript(script []byte) func(*wire.MsgBlock) {
420 return func(b *wire.MsgBlock) {
421 b.Transactions[0].TxIn[0].SignatureScript = script
425 // additionalTx returns a function that itself takes a block and modifies it by
426 // adding the the provided transaction.
427 func additionalTx(tx *wire.MsgTx) func(*wire.MsgBlock) {
428 return func(b *wire.MsgBlock) {
433 // createSpendTx creates a transaction that spends from the provided spendable
434 // output and includes an additional unique OP_RETURN output to ensure the
435 // transaction ends up with a unique hash. The script is a simple OP_TRUE
436 // script which avoids the need to track addresses and signature scripts in the
438 func createSpendTx(spend *spendableOut, fee btcutil.Amount) *wire.MsgTx {
439 spendTx := wire.NewMsgTx(1)
440 spendTx.AddTxIn(&wire.TxIn{
441 PreviousOutPoint: spend.prevOut,
442 Sequence: wire.MaxTxInSequenceNum,
443 SignatureScript: nil,
445 spendTx.AddTxOut(wire.NewTxOut(int64(spend.amount-fee),
447 spendTx.AddTxOut(wire.NewTxOut(0, uniqueOpReturnScript()))
452 // createSpendTxForTx creates a transaction that spends from the first output of
453 // the provided transaction and includes an additional unique OP_RETURN output
454 // to ensure the transaction ends up with a unique hash. The public key script
455 // is a simple OP_TRUE script which avoids the need to track addresses and
456 // signature scripts in the tests. The signature script is nil.
457 func createSpendTxForTx(tx *wire.MsgTx, fee btcutil.Amount) *wire.MsgTx {
458 spend := makeSpendableOutForTx(tx, 0)
459 return createSpendTx(&spend, fee)
462 // nextBlock builds a new block that extends the current tip associated with the
463 // generator and updates the generator's tip to the newly generated block.
465 // The block will include the following:
466 // - A coinbase that pays the required subsidy to an OP_TRUE script
467 // - When a spendable output is provided:
468 // - A transaction that spends from the provided output the following outputs:
469 // - One that pays the inputs amount minus 1 atom to an OP_TRUE script
470 // - One that contains an OP_RETURN output with a random uint64 in order to
471 // ensure the transaction has a unique hash
473 // Additionally, if one or more munge functions are specified, they will be
474 // invoked with the block prior to solving it. This provides callers with the
475 // opportunity to modify the block which is especially useful for testing.
477 // In order to simply the logic in the munge functions, the following rules are
478 // applied after all munge functions have been invoked:
479 // - The merkle root will be recalculated unless it was manually changed
480 // - The block will be solved unless the nonce was changed
481 func (g *testGenerator) nextBlock(blockName string, spend *spendableOut, mungers ...func(*wire.MsgBlock)) *wire.MsgBlock {
482 // Create coinbase transaction for the block using any additional
483 // subsidy if specified.
484 nextHeight := g.tipHeight + 1
485 coinbaseTx := g.createCoinbaseTx(nextHeight)
486 txns := []*wire.MsgTx{coinbaseTx}
488 // Create the transaction with a fee of 1 atom for the
489 // miner and increase the coinbase subsidy accordingly.
490 fee := btcutil.Amount(1)
491 coinbaseTx.TxOut[0].Value += int64(fee)
493 // Create a transaction that spends from the provided spendable
494 // output and includes an additional unique OP_RETURN output to
495 // ensure the transaction ends up with a unique hash, then add
496 // add it to the list of transactions to include in the block.
497 // The script is a simple OP_TRUE script in order to avoid the
498 // need to track addresses and signature scripts in the tests.
499 txns = append(txns, createSpendTx(spend, fee))
502 // Use a timestamp that is one second after the previous block unless
503 // this is the first block in which case the current time is used.
506 ts = time.Unix(time.Now().Unix(), 0)
508 ts = g.tip.Header.Timestamp.Add(time.Second)
511 block := wire.MsgBlock{
512 Header: wire.BlockHeader{
514 PrevBlock: g.tip.BlockHash(),
515 MerkleRoot: calcMerkleRoot(txns),
516 Bits: g.params.PowLimitBits,
518 Nonce: 0, // To be solved.
523 // Perform any block munging just before solving. Only recalculate the
524 // merkle root if it wasn't manually changed by a munge function.
525 curMerkleRoot := block.Header.MerkleRoot
526 curNonce := block.Header.Nonce
527 for _, f := range mungers {
530 if block.Header.MerkleRoot == curMerkleRoot {
531 block.Header.MerkleRoot = calcMerkleRoot(block.Transactions)
534 // Only solve the block if the nonce wasn't manually changed by a munge
536 if block.Header.Nonce == curNonce && !solveBlock(&block.Header) {
537 panic(fmt.Sprintf("Unable to solve block at height %d",
541 // Update generator state and return the block.
542 blockHash := block.BlockHash()
543 g.blocks[blockHash] = &block
544 g.blocksByName[blockName] = &block
545 g.blockHeights[blockName] = nextHeight
547 g.tipName = blockName
548 g.tipHeight = nextHeight
552 // updateBlockState manually updates the generator state to remove all internal
553 // map references to a block via its old hash and insert new ones for the new
554 // block hash. This is useful if the test code has to manually change a block
555 // after 'nextBlock' has returned.
556 func (g *testGenerator) updateBlockState(oldBlockName string, oldBlockHash chainhash.Hash, newBlockName string, newBlock *wire.MsgBlock) {
557 // Look up the height from the existing entries.
558 blockHeight := g.blockHeights[oldBlockName]
560 // Remove existing entries.
561 delete(g.blocks, oldBlockHash)
562 delete(g.blocksByName, oldBlockName)
563 delete(g.blockHeights, oldBlockName)
566 newBlockHash := newBlock.BlockHash()
567 g.blocks[newBlockHash] = newBlock
568 g.blocksByName[newBlockName] = newBlock
569 g.blockHeights[newBlockName] = blockHeight
572 // setTip changes the tip of the instance to the block with the provided name.
573 // This is useful since the tip is used for things such as generating subsequent
575 func (g *testGenerator) setTip(blockName string) {
576 g.tip = g.blocksByName[blockName]
577 g.tipName = blockName
578 g.tipHeight = g.blockHeights[blockName]
581 // oldestCoinbaseOuts removes the oldest coinbase output that was previously
582 // saved to the generator and returns the set as a slice.
583 func (g *testGenerator) oldestCoinbaseOut() spendableOut {
584 op := g.spendableOuts[0]
585 g.spendableOuts = g.spendableOuts[1:]
589 // saveTipCoinbaseOut adds the coinbase tx output in the current tip block to
590 // the list of spendable outputs.
591 func (g *testGenerator) saveTipCoinbaseOut() {
592 g.spendableOuts = append(g.spendableOuts, makeSpendableOut(g.tip, 0, 0))
593 g.prevCollectedHash = g.tip.BlockHash()
596 // saveSpendableCoinbaseOuts adds all coinbase outputs from the last block that
597 // had its coinbase tx output colleted to the current tip. This is useful to
598 // batch the collection of coinbase outputs once the tests reach a stable point
599 // so they don't have to manually add them for the right tests which will
600 // ultimately end up being the best chain.
601 func (g *testGenerator) saveSpendableCoinbaseOuts() {
602 // Ensure tip is reset to the current one when done.
603 curTipName := g.tipName
604 defer g.setTip(curTipName)
606 // Loop through the ancestors of the current tip until the
607 // reaching the block that has already had the coinbase outputs
609 var collectBlocks []*wire.MsgBlock
610 for b := g.tip; b != nil; b = g.blocks[b.Header.PrevBlock] {
611 if b.BlockHash() == g.prevCollectedHash {
614 collectBlocks = append(collectBlocks, b)
616 for i := range collectBlocks {
617 g.tip = collectBlocks[len(collectBlocks)-1-i]
618 g.saveTipCoinbaseOut()
622 // nonCanonicalVarInt return a variable-length encoded integer that is encoded
623 // with 9 bytes even though it could be encoded with a minimal canonical
625 func nonCanonicalVarInt(val uint32) []byte {
628 binary.LittleEndian.PutUint64(rv[1:], uint64(val))
632 // encodeNonCanonicalBlock serializes the block in a non-canonical way by
633 // encoding the number of transactions using a variable-length encoded integer
634 // with 9 bytes even though it should be encoded with a minimal canonical
636 func encodeNonCanonicalBlock(b *wire.MsgBlock) []byte {
638 b.Header.BtcEncode(&buf, 0, wire.BaseEncoding)
639 buf.Write(nonCanonicalVarInt(uint32(len(b.Transactions))))
640 for _, tx := range b.Transactions {
641 tx.BtcEncode(&buf, 0, wire.BaseEncoding)
646 // cloneBlock returns a deep copy of the provided block.
647 func cloneBlock(b *wire.MsgBlock) wire.MsgBlock {
648 var blockCopy wire.MsgBlock
649 blockCopy.Header = b.Header
650 for _, tx := range b.Transactions {
651 blockCopy.AddTransaction(tx.Copy())
656 // repeatOpcode returns a byte slice with the provided opcode repeated the
657 // specified number of times.
658 func repeatOpcode(opcode uint8, numRepeats int) []byte {
659 return bytes.Repeat([]byte{opcode}, numRepeats)
662 // assertScriptSigOpsCount panics if the provided script does not have the
663 // specified number of signature operations.
664 func assertScriptSigOpsCount(script []byte, expected int) {
665 numSigOps := txscript.GetSigOpCount(script)
666 if numSigOps != expected {
667 _, file, line, _ := runtime.Caller(1)
668 panic(fmt.Sprintf("assertion failed at %s:%d: generated number "+
669 "of sigops for script is %d instead of expected %d",
670 file, line, numSigOps, expected))
674 // countBlockSigOps returns the number of legacy signature operations in the
675 // scripts in the passed block.
676 func countBlockSigOps(block *wire.MsgBlock) int {
678 for _, tx := range block.Transactions {
679 for _, txIn := range tx.TxIn {
680 numSigOps := txscript.GetSigOpCount(txIn.SignatureScript)
681 totalSigOps += numSigOps
683 for _, txOut := range tx.TxOut {
684 numSigOps := txscript.GetSigOpCount(txOut.PkScript)
685 totalSigOps += numSigOps
692 // assertTipBlockSigOpsCount panics if the current tip block associated with the
693 // generator does not have the specified number of signature operations.
694 func (g *testGenerator) assertTipBlockSigOpsCount(expected int) {
695 numSigOps := countBlockSigOps(g.tip)
696 if numSigOps != expected {
697 panic(fmt.Sprintf("generated number of sigops for block %q "+
698 "(height %d) is %d instead of expected %d", g.tipName,
699 g.tipHeight, numSigOps, expected))
703 // assertTipBlockSize panics if the if the current tip block associated with the
704 // generator does not have the specified size when serialized.
705 func (g *testGenerator) assertTipBlockSize(expected int) {
706 serializeSize := g.tip.SerializeSize()
707 if serializeSize != expected {
708 panic(fmt.Sprintf("block size of block %q (height %d) is %d "+
709 "instead of expected %d", g.tipName, g.tipHeight,
710 serializeSize, expected))
714 // assertTipNonCanonicalBlockSize panics if the if the current tip block
715 // associated with the generator does not have the specified non-canonical size
717 func (g *testGenerator) assertTipNonCanonicalBlockSize(expected int) {
718 serializeSize := len(encodeNonCanonicalBlock(g.tip))
719 if serializeSize != expected {
720 panic(fmt.Sprintf("block size of block %q (height %d) is %d "+
721 "instead of expected %d", g.tipName, g.tipHeight,
722 serializeSize, expected))
726 // assertTipBlockNumTxns panics if the number of transactions in the current tip
727 // block associated with the generator does not match the specified value.
728 func (g *testGenerator) assertTipBlockNumTxns(expected int) {
729 numTxns := len(g.tip.Transactions)
730 if numTxns != expected {
731 panic(fmt.Sprintf("number of txns in block %q (height %d) is "+
732 "%d instead of expected %d", g.tipName, g.tipHeight,
737 // assertTipBlockHash panics if the current tip block associated with the
738 // generator does not match the specified hash.
739 func (g *testGenerator) assertTipBlockHash(expected chainhash.Hash) {
740 hash := g.tip.BlockHash()
741 if hash != expected {
742 panic(fmt.Sprintf("block hash of block %q (height %d) is %v "+
743 "instead of expected %v", g.tipName, g.tipHeight, hash,
748 // assertTipBlockMerkleRoot panics if the merkle root in header of the current
749 // tip block associated with the generator does not match the specified hash.
750 func (g *testGenerator) assertTipBlockMerkleRoot(expected chainhash.Hash) {
751 hash := g.tip.Header.MerkleRoot
752 if hash != expected {
753 panic(fmt.Sprintf("merkle root of block %q (height %d) is %v "+
754 "instead of expected %v", g.tipName, g.tipHeight, hash,
759 // assertTipBlockTxOutOpReturn panics if the current tip block associated with
760 // the generator does not have an OP_RETURN script for the transaction output at
761 // the provided tx index and output index.
762 func (g *testGenerator) assertTipBlockTxOutOpReturn(txIndex, txOutIndex uint32) {
763 if txIndex >= uint32(len(g.tip.Transactions)) {
764 panic(fmt.Sprintf("Transaction index %d in block %q "+
765 "(height %d) does not exist", txIndex, g.tipName,
769 tx := g.tip.Transactions[txIndex]
770 if txOutIndex >= uint32(len(tx.TxOut)) {
771 panic(fmt.Sprintf("transaction index %d output %d in block %q "+
772 "(height %d) does not exist", txIndex, txOutIndex,
773 g.tipName, g.tipHeight))
776 txOut := tx.TxOut[txOutIndex]
777 if txOut.PkScript[0] != txscript.OP_RETURN {
778 panic(fmt.Sprintf("transaction index %d output %d in block %q "+
779 "(height %d) is not an OP_RETURN", txIndex, txOutIndex,
780 g.tipName, g.tipHeight))
784 // Generate returns a slice of tests that can be used to exercise the consensus
785 // validation rules. The tests are intended to be flexible enough to allow both
786 // unit-style tests directly against the blockchain code as well as integration
787 // style tests over the peer-to-peer network. To achieve that goal, each test
788 // contains additional information about the expected result, however that
789 // information can be ignored when doing comparison tests between two
790 // independent versions over the peer-to-peer network.
791 func Generate(includeLargeReorg bool) (tests [][]TestInstance, err error) {
792 // In order to simplify the generation code which really should never
793 // fail unless the test code itself is broken, panics are used
794 // internally. This deferred func ensures any panics don't escape the
795 // generator by replacing the named error return with the underlying
798 if r := recover(); r != nil {
801 switch rt := r.(type) {
807 err = errors.New("Unknown panic")
812 // Create a test generator instance initialized with the genesis block
814 g, err := makeTestGenerator(regressionNetParams)
819 // Define some convenience helper functions to return an individual test
820 // instance that has the described characteristics.
822 // acceptBlock creates a test instance that expects the provided block
823 // to be accepted by the consensus rules.
825 // rejectBlock creates a test instance that expects the provided block
826 // to be rejected by the consensus rules.
828 // rejectNonCanonicalBlock creates a test instance that encodes the
829 // provided block using a non-canonical encoded as described by the
830 // encodeNonCanonicalBlock function and expected it to be rejected.
832 // orphanOrRejectBlock creates a test instance that expected the
833 // provided block to either by accepted as an orphan or rejected by the
836 // expectTipBlock creates a test instance that expects the provided
837 // block to be the current tip of the block chain.
838 acceptBlock := func(blockName string, block *wire.MsgBlock, isMainChain, isOrphan bool) TestInstance {
839 blockHeight := g.blockHeights[blockName]
840 return AcceptedBlock{blockName, block, blockHeight, isMainChain,
843 rejectBlock := func(blockName string, block *wire.MsgBlock, code blockchain.ErrorCode) TestInstance {
844 blockHeight := g.blockHeights[blockName]
845 return RejectedBlock{blockName, block, blockHeight, code}
847 rejectNonCanonicalBlock := func(blockName string, block *wire.MsgBlock) TestInstance {
848 blockHeight := g.blockHeights[blockName]
849 encoded := encodeNonCanonicalBlock(block)
850 return RejectedNonCanonicalBlock{blockName, encoded, blockHeight}
852 orphanOrRejectBlock := func(blockName string, block *wire.MsgBlock) TestInstance {
853 blockHeight := g.blockHeights[blockName]
854 return OrphanOrRejectedBlock{blockName, block, blockHeight}
856 expectTipBlock := func(blockName string, block *wire.MsgBlock) TestInstance {
857 blockHeight := g.blockHeights[blockName]
858 return ExpectedTip{blockName, block, blockHeight}
861 // Define some convenience helper functions to populate the tests slice
862 // with test instances that have the described characteristics.
864 // accepted creates and appends a single acceptBlock test instance for
865 // the current tip which expects the block to be accepted to the main
868 // acceptedToSideChainWithExpectedTip creates an appends a two-instance
869 // test. The first instance is an acceptBlock test instance for the
870 // current tip which expects the block to be accepted to a side chain.
871 // The second instance is an expectBlockTip test instance for provided
874 // rejected creates and appends a single rejectBlock test instance for
877 // rejectedNonCanonical creates and appends a single
878 // rejectNonCanonicalBlock test instance for the current tip.
880 // orphanedOrRejected creates and appends a single orphanOrRejectBlock
881 // test instance for the current tip.
883 tests = append(tests, []TestInstance{
884 acceptBlock(g.tipName, g.tip, true, false),
887 acceptedToSideChainWithExpectedTip := func(tipName string) {
888 tests = append(tests, []TestInstance{
889 acceptBlock(g.tipName, g.tip, false, false),
890 expectTipBlock(tipName, g.blocksByName[tipName]),
893 rejected := func(code blockchain.ErrorCode) {
894 tests = append(tests, []TestInstance{
895 rejectBlock(g.tipName, g.tip, code),
898 rejectedNonCanonical := func() {
899 tests = append(tests, []TestInstance{
900 rejectNonCanonicalBlock(g.tipName, g.tip),
903 orphanedOrRejected := func() {
904 tests = append(tests, []TestInstance{
905 orphanOrRejectBlock(g.tipName, g.tip),
909 // ---------------------------------------------------------------------
910 // Generate enough blocks to have mature coinbase outputs to work with.
912 // genesis -> bm0 -> bm1 -> ... -> bm99
913 // ---------------------------------------------------------------------
915 coinbaseMaturity := g.params.CoinbaseMaturity
916 var testInstances []TestInstance
917 for i := uint16(0); i < coinbaseMaturity; i++ {
918 blockName := fmt.Sprintf("bm%d", i)
919 g.nextBlock(blockName, nil)
920 g.saveTipCoinbaseOut()
921 testInstances = append(testInstances, acceptBlock(g.tipName,
924 tests = append(tests, testInstances)
926 // Collect spendable outputs. This simplifies the code below.
927 var outs []*spendableOut
928 for i := uint16(0); i < coinbaseMaturity; i++ {
929 op := g.oldestCoinbaseOut()
930 outs = append(outs, &op)
933 // ---------------------------------------------------------------------
934 // Basic forking and reorg tests.
935 // ---------------------------------------------------------------------
937 // ---------------------------------------------------------------------
938 // The comments below identify the structure of the chain being built.
940 // The values in parenthesis repesent which outputs are being spent.
942 // For example, b1(0) indicates the first collected spendable output
943 // which, due to the code above to create the correct number of blocks,
944 // is the first output that can be spent at the current block height due
945 // to the coinbase maturity requirement.
946 // ---------------------------------------------------------------------
948 // Start by building a couple of blocks at current tip (value in parens
949 // is which output is spent):
951 // ... -> b1(0) -> b2(1)
952 g.nextBlock("b1", outs[0])
955 g.nextBlock("b2", outs[1])
958 // Create a fork from b1. There should not be a reorg since b2 was seen
961 // ... -> b1(0) -> b2(1)
964 g.nextBlock("b3", outs[1])
965 b3Tx1Out := makeSpendableOut(g.tip, 1, 0)
966 acceptedToSideChainWithExpectedTip("b2")
968 // Extend b3 fork to make the alternative chain longer and force reorg.
970 // ... -> b1(0) -> b2(1)
971 // \-> b3(1) -> b4(2)
972 g.nextBlock("b4", outs[2])
975 // Extend b2 fork twice to make first chain longer and force reorg.
977 // ... -> b1(0) -> b2(1) -> b5(2) -> b6(3)
978 // \-> b3(1) -> b4(2)
980 g.nextBlock("b5", outs[2])
981 acceptedToSideChainWithExpectedTip("b4")
983 g.nextBlock("b6", outs[3])
986 // ---------------------------------------------------------------------
987 // Double spend tests.
988 // ---------------------------------------------------------------------
990 // Create a fork that double spends.
992 // ... -> b1(0) -> b2(1) -> b5(2) -> b6(3)
993 // \-> b7(2) -> b8(4)
994 // \-> b3(1) -> b4(2)
996 g.nextBlock("b7", outs[2])
997 acceptedToSideChainWithExpectedTip("b6")
999 g.nextBlock("b8", outs[4])
1000 rejected(blockchain.ErrMissingTxOut)
1002 // ---------------------------------------------------------------------
1003 // Too much proof-of-work coinbase tests.
1004 // ---------------------------------------------------------------------
1006 // Create a block that generates too coinbase.
1008 // ... -> b1(0) -> b2(1) -> b5(2) -> b6(3)
1010 // \-> b3(1) -> b4(2)
1012 g.nextBlock("b9", outs[4], additionalCoinbase(1))
1013 rejected(blockchain.ErrBadCoinbaseValue)
1015 // Create a fork that ends with block that generates too much coinbase.
1017 // ... -> b1(0) -> b2(1) -> b5(2) -> b6(3)
1018 // \-> b10(3) -> b11(4)
1019 // \-> b3(1) -> b4(2)
1021 g.nextBlock("b10", outs[3])
1022 acceptedToSideChainWithExpectedTip("b6")
1024 g.nextBlock("b11", outs[4], additionalCoinbase(1))
1025 rejected(blockchain.ErrBadCoinbaseValue)
1027 // Create a fork that ends with block that generates too much coinbase
1028 // as before, but with a valid fork first.
1030 // ... -> b1(0) -> b2(1) -> b5(2) -> b6(3)
1031 // | \-> b12(3) -> b13(4) -> b14(5)
1032 // | (b12 added last)
1033 // \-> b3(1) -> b4(2)
1035 b12 := g.nextBlock("b12", outs[3])
1036 b13 := g.nextBlock("b13", outs[4])
1037 b14 := g.nextBlock("b14", outs[5], additionalCoinbase(1))
1038 tests = append(tests, []TestInstance{
1039 acceptBlock("b13", b13, false, true),
1040 acceptBlock("b14", b14, false, true),
1041 rejectBlock("b12", b12, blockchain.ErrBadCoinbaseValue),
1042 expectTipBlock("b13", b13),
1045 // ---------------------------------------------------------------------
1046 // Checksig signature operation count tests.
1047 // ---------------------------------------------------------------------
1049 // Add a block with max allowed signature operations using OP_CHECKSIG.
1051 // ... -> b5(2) -> b12(3) -> b13(4) -> b15(5)
1052 // \-> b3(1) -> b4(2)
1054 manySigOps := repeatOpcode(txscript.OP_CHECKSIG, maxBlockSigOps)
1055 g.nextBlock("b15", outs[5], replaceSpendScript(manySigOps))
1056 g.assertTipBlockSigOpsCount(maxBlockSigOps)
1059 // Attempt to add block with more than max allowed signature operations
1060 // using OP_CHECKSIG.
1062 // ... -> b5(2) -> b12(3) -> b13(4) -> b15(5)
1064 // \-> b3(1) -> b4(2)
1065 tooManySigOps := repeatOpcode(txscript.OP_CHECKSIG, maxBlockSigOps+1)
1066 g.nextBlock("b16", outs[6], replaceSpendScript(tooManySigOps))
1067 g.assertTipBlockSigOpsCount(maxBlockSigOps + 1)
1068 rejected(blockchain.ErrTooManySigOps)
1070 // ---------------------------------------------------------------------
1071 // Cross-fork spend tests.
1072 // ---------------------------------------------------------------------
1074 // Create block that spends a tx created on a different fork.
1076 // ... -> b5(2) -> b12(3) -> b13(4) -> b15(5)
1077 // \ \-> b17(b3.tx[1])
1078 // \-> b3(1) -> b4(2)
1080 g.nextBlock("b17", &b3Tx1Out)
1081 rejected(blockchain.ErrMissingTxOut)
1083 // Create block that forks and spends a tx created on a third fork.
1085 // ... -> b5(2) -> b12(3) -> b13(4) -> b15(5)
1086 // | \-> b18(b3.tx[1]) -> b19(6)
1087 // \-> b3(1) -> b4(2)
1089 g.nextBlock("b18", &b3Tx1Out)
1090 acceptedToSideChainWithExpectedTip("b15")
1092 g.nextBlock("b19", outs[6])
1093 rejected(blockchain.ErrMissingTxOut)
1095 // ---------------------------------------------------------------------
1096 // Immature coinbase tests.
1097 // ---------------------------------------------------------------------
1099 // Create block that spends immature coinbase.
1101 // ... -> b13(4) -> b15(5)
1104 g.nextBlock("b20", outs[7])
1105 rejected(blockchain.ErrImmatureSpend)
1107 // Create block that spends immature coinbase on a fork.
1109 // ... -> b13(4) -> b15(5)
1110 // \-> b21(5) -> b22(7)
1112 g.nextBlock("b21", outs[5])
1113 acceptedToSideChainWithExpectedTip("b15")
1115 g.nextBlock("b22", outs[7])
1116 rejected(blockchain.ErrImmatureSpend)
1118 // ---------------------------------------------------------------------
1119 // Max block size tests.
1120 // ---------------------------------------------------------------------
1122 // Create block that is the max allowed size.
1124 // ... -> b15(5) -> b23(6)
1126 g.nextBlock("b23", outs[6], func(b *wire.MsgBlock) {
1127 bytesToMaxSize := maxBlockSize - b.SerializeSize() - 3
1128 sizePadScript := repeatOpcode(0x00, bytesToMaxSize)
1129 replaceSpendScript(sizePadScript)(b)
1131 g.assertTipBlockSize(maxBlockSize)
1134 // Create block that is the one byte larger than max allowed size. This
1135 // is done on a fork and should be rejected regardless.
1137 // ... -> b15(5) -> b23(6)
1138 // \-> b24(6) -> b25(7)
1140 g.nextBlock("b24", outs[6], func(b *wire.MsgBlock) {
1141 bytesToMaxSize := maxBlockSize - b.SerializeSize() - 3
1142 sizePadScript := repeatOpcode(0x00, bytesToMaxSize+1)
1143 replaceSpendScript(sizePadScript)(b)
1145 g.assertTipBlockSize(maxBlockSize + 1)
1146 rejected(blockchain.ErrBlockTooBig)
1148 // Parent was rejected, so this block must either be an orphan or
1149 // outright rejected due to an invalid parent.
1150 g.nextBlock("b25", outs[7])
1151 orphanedOrRejected()
1153 // ---------------------------------------------------------------------
1154 // Coinbase script length limits tests.
1155 // ---------------------------------------------------------------------
1157 // Create block that has a coinbase script that is smaller than the
1158 // required length. This is done on a fork and should be rejected
1159 // regardless. Also, create a block that builds on the rejected block.
1161 // ... -> b15(5) -> b23(6)
1162 // \-> b26(6) -> b27(7)
1164 tooSmallCbScript := repeatOpcode(0x00, minCoinbaseScriptLen-1)
1165 g.nextBlock("b26", outs[6], replaceCoinbaseSigScript(tooSmallCbScript))
1166 rejected(blockchain.ErrBadCoinbaseScriptLen)
1168 // Parent was rejected, so this block must either be an orphan or
1169 // outright rejected due to an invalid parent.
1170 g.nextBlock("b27", outs[7])
1171 orphanedOrRejected()
1173 // Create block that has a coinbase script that is larger than the
1174 // allowed length. This is done on a fork and should be rejected
1175 // regardless. Also, create a block that builds on the rejected block.
1177 // ... -> b15(5) -> b23(6)
1178 // \-> b28(6) -> b29(7)
1180 tooLargeCbScript := repeatOpcode(0x00, maxCoinbaseScriptLen+1)
1181 g.nextBlock("b28", outs[6], replaceCoinbaseSigScript(tooLargeCbScript))
1182 rejected(blockchain.ErrBadCoinbaseScriptLen)
1184 // Parent was rejected, so this block must either be an orphan or
1185 // outright rejected due to an invalid parent.
1186 g.nextBlock("b29", outs[7])
1187 orphanedOrRejected()
1189 // Create block that has a max length coinbase script.
1191 // ... -> b23(6) -> b30(7)
1193 maxSizeCbScript := repeatOpcode(0x00, maxCoinbaseScriptLen)
1194 g.nextBlock("b30", outs[7], replaceCoinbaseSigScript(maxSizeCbScript))
1197 // ---------------------------------------------------------------------
1198 // Multisig[Verify]/ChecksigVerifiy signature operation count tests.
1199 // ---------------------------------------------------------------------
1201 // Create block with max signature operations as OP_CHECKMULTISIG.
1203 // ... -> b30(7) -> b31(8)
1205 // OP_CHECKMULTISIG counts for 20 sigops.
1206 manySigOps = repeatOpcode(txscript.OP_CHECKMULTISIG, maxBlockSigOps/20)
1207 g.nextBlock("b31", outs[8], replaceSpendScript(manySigOps))
1208 g.assertTipBlockSigOpsCount(maxBlockSigOps)
1211 // Create block with more than max allowed signature operations using
1212 // OP_CHECKMULTISIG.
1217 // OP_CHECKMULTISIG counts for 20 sigops.
1218 tooManySigOps = repeatOpcode(txscript.OP_CHECKMULTISIG, maxBlockSigOps/20)
1219 tooManySigOps = append(manySigOps, txscript.OP_CHECKSIG)
1220 g.nextBlock("b32", outs[9], replaceSpendScript(tooManySigOps))
1221 g.assertTipBlockSigOpsCount(maxBlockSigOps + 1)
1222 rejected(blockchain.ErrTooManySigOps)
1224 // Create block with max signature operations as OP_CHECKMULTISIGVERIFY.
1226 // ... -> b31(8) -> b33(9)
1228 manySigOps = repeatOpcode(txscript.OP_CHECKMULTISIGVERIFY, maxBlockSigOps/20)
1229 g.nextBlock("b33", outs[9], replaceSpendScript(manySigOps))
1230 g.assertTipBlockSigOpsCount(maxBlockSigOps)
1233 // Create block with more than max allowed signature operations using
1234 // OP_CHECKMULTISIGVERIFY.
1239 tooManySigOps = repeatOpcode(txscript.OP_CHECKMULTISIGVERIFY, maxBlockSigOps/20)
1240 tooManySigOps = append(manySigOps, txscript.OP_CHECKSIG)
1241 g.nextBlock("b34", outs[10], replaceSpendScript(tooManySigOps))
1242 g.assertTipBlockSigOpsCount(maxBlockSigOps + 1)
1243 rejected(blockchain.ErrTooManySigOps)
1245 // Create block with max signature operations as OP_CHECKSIGVERIFY.
1247 // ... -> b33(9) -> b35(10)
1250 manySigOps = repeatOpcode(txscript.OP_CHECKSIGVERIFY, maxBlockSigOps)
1251 g.nextBlock("b35", outs[10], replaceSpendScript(manySigOps))
1252 g.assertTipBlockSigOpsCount(maxBlockSigOps)
1255 // Create block with more than max allowed signature operations using
1256 // OP_CHECKSIGVERIFY.
1261 tooManySigOps = repeatOpcode(txscript.OP_CHECKSIGVERIFY, maxBlockSigOps+1)
1262 g.nextBlock("b36", outs[11], replaceSpendScript(tooManySigOps))
1263 g.assertTipBlockSigOpsCount(maxBlockSigOps + 1)
1264 rejected(blockchain.ErrTooManySigOps)
1266 // ---------------------------------------------------------------------
1267 // Spending of tx outputs in block that failed to connect tests.
1268 // ---------------------------------------------------------------------
1270 // Create block that spends a transaction from a block that failed to
1271 // connect (due to containing a double spend).
1275 // \-> b38(b37.tx[1])
1278 doubleSpendTx := createSpendTx(outs[11], lowFee)
1279 g.nextBlock("b37", outs[11], additionalTx(doubleSpendTx))
1280 b37Tx1Out := makeSpendableOut(g.tip, 1, 0)
1281 rejected(blockchain.ErrMissingTxOut)
1284 g.nextBlock("b38", &b37Tx1Out)
1285 rejected(blockchain.ErrMissingTxOut)
1287 // ---------------------------------------------------------------------
1288 // Pay-to-script-hash signature operation count tests.
1289 // ---------------------------------------------------------------------
1291 // Create a pay-to-script-hash redeem script that consists of 9
1292 // signature operations to be used in the next three blocks.
1293 const redeemScriptSigOps = 9
1294 redeemScript := pushDataScript(g.privKey.PubKey().SerializeCompressed())
1295 redeemScript = append(redeemScript, bytes.Repeat([]byte{txscript.OP_2DUP,
1296 txscript.OP_CHECKSIGVERIFY}, redeemScriptSigOps-1)...)
1297 redeemScript = append(redeemScript, txscript.OP_CHECKSIG)
1298 assertScriptSigOpsCount(redeemScript, redeemScriptSigOps)
1300 // Create a block that has enough pay-to-script-hash outputs such that
1301 // another block can be created that consumes them all and exceeds the
1302 // max allowed signature operations per block.
1304 // ... -> b35(10) -> b39(11)
1306 b39 := g.nextBlock("b39", outs[11], func(b *wire.MsgBlock) {
1307 // Create a chain of transactions each spending from the
1308 // previous one such that each contains an output that pays to
1309 // the redeem script and the total number of signature
1310 // operations in those redeem scripts will be more than the
1311 // max allowed per block.
1312 p2shScript := payToScriptHashScript(redeemScript)
1313 txnsNeeded := (maxBlockSigOps / redeemScriptSigOps) + 1
1314 prevTx := b.Transactions[1]
1315 for i := 0; i < txnsNeeded; i++ {
1316 prevTx = createSpendTxForTx(prevTx, lowFee)
1317 prevTx.TxOut[0].Value -= 2
1318 prevTx.AddTxOut(wire.NewTxOut(2, p2shScript))
1319 b.AddTransaction(prevTx)
1322 g.assertTipBlockNumTxns((maxBlockSigOps / redeemScriptSigOps) + 3)
1325 // Create a block with more than max allowed signature operations where
1326 // the majority of them are in pay-to-script-hash scripts.
1328 // ... -> b35(10) -> b39(11)
1331 g.nextBlock("b40", outs[12], func(b *wire.MsgBlock) {
1332 txnsNeeded := (maxBlockSigOps / redeemScriptSigOps)
1333 for i := 0; i < txnsNeeded; i++ {
1334 // Create a signed transaction that spends from the
1335 // associated p2sh output in b39.
1336 spend := makeSpendableOutForTx(b39.Transactions[i+2], 2)
1337 tx := createSpendTx(&spend, lowFee)
1338 sig, err := txscript.RawTxInSignature(tx, 0,
1339 redeemScript, txscript.SigHashAll, g.privKey)
1343 tx.TxIn[0].SignatureScript = pushDataScript(sig,
1345 b.AddTransaction(tx)
1348 // Create a final tx that includes a non-pay-to-script-hash
1349 // output with the number of signature operations needed to push
1350 // the block one over the max allowed.
1351 fill := maxBlockSigOps - (txnsNeeded * redeemScriptSigOps) + 1
1352 finalTx := b.Transactions[len(b.Transactions)-1]
1353 tx := createSpendTxForTx(finalTx, lowFee)
1354 tx.TxOut[0].PkScript = repeatOpcode(txscript.OP_CHECKSIG, fill)
1355 b.AddTransaction(tx)
1357 rejected(blockchain.ErrTooManySigOps)
1359 // Create a block with the max allowed signature operations where the
1360 // majority of them are in pay-to-script-hash scripts.
1362 // ... -> b35(10) -> b39(11) -> b41(12)
1364 g.nextBlock("b41", outs[12], func(b *wire.MsgBlock) {
1365 txnsNeeded := (maxBlockSigOps / redeemScriptSigOps)
1366 for i := 0; i < txnsNeeded; i++ {
1367 spend := makeSpendableOutForTx(b39.Transactions[i+2], 2)
1368 tx := createSpendTx(&spend, lowFee)
1369 sig, err := txscript.RawTxInSignature(tx, 0,
1370 redeemScript, txscript.SigHashAll, g.privKey)
1374 tx.TxIn[0].SignatureScript = pushDataScript(sig,
1376 b.AddTransaction(tx)
1379 // Create a final tx that includes a non-pay-to-script-hash
1380 // output with the number of signature operations needed to push
1381 // the block to exactly the max allowed.
1382 fill := maxBlockSigOps - (txnsNeeded * redeemScriptSigOps)
1386 finalTx := b.Transactions[len(b.Transactions)-1]
1387 tx := createSpendTxForTx(finalTx, lowFee)
1388 tx.TxOut[0].PkScript = repeatOpcode(txscript.OP_CHECKSIG, fill)
1389 b.AddTransaction(tx)
1393 // ---------------------------------------------------------------------
1394 // Reset the chain to a stable base.
1396 // ... -> b35(10) -> b39(11) -> b42(12) -> b43(13)
1398 // ---------------------------------------------------------------------
1401 g.nextBlock("b42", outs[12])
1402 acceptedToSideChainWithExpectedTip("b41")
1404 g.nextBlock("b43", outs[13])
1407 // ---------------------------------------------------------------------
1408 // Various malformed block tests.
1409 // ---------------------------------------------------------------------
1411 // Create block with an otherwise valid transaction in place of where
1412 // the coinbase must be.
1416 g.nextBlock("b44", nil, func(b *wire.MsgBlock) {
1417 nonCoinbaseTx := createSpendTx(outs[14], lowFee)
1418 b.Transactions[0] = nonCoinbaseTx
1420 rejected(blockchain.ErrFirstTxNotCoinbase)
1422 // Create block with no transactions.
1427 g.nextBlock("b45", nil, func(b *wire.MsgBlock) {
1428 b.Transactions = nil
1430 rejected(blockchain.ErrNoTransactions)
1432 // Create block with invalid proof of work.
1437 b46 := g.nextBlock("b46", outs[14])
1438 // This can't be done inside a munge function passed to nextBlock
1439 // because the block is solved after the function returns and this test
1440 // requires an unsolved block.
1442 origHash := b46.BlockHash()
1444 // Keep incrementing the nonce until the hash treated as
1445 // a uint256 is higher than the limit.
1447 blockHash := b46.BlockHash()
1448 hashNum := blockchain.HashToBig(&blockHash)
1449 if hashNum.Cmp(g.params.PowLimit) >= 0 {
1453 g.updateBlockState("b46", origHash, "b46", b46)
1455 rejected(blockchain.ErrHighHash)
1457 // Create block with a timestamp too far in the future.
1462 g.nextBlock("b47", outs[14], func(b *wire.MsgBlock) {
1463 // 3 hours in the future clamped to 1 second precision.
1464 nowPlus3Hours := time.Now().Add(time.Hour * 3)
1465 b.Header.Timestamp = time.Unix(nowPlus3Hours.Unix(), 0)
1467 rejected(blockchain.ErrTimeTooNew)
1469 // Create block with an invalid merkle root.
1474 g.nextBlock("b48", outs[14], func(b *wire.MsgBlock) {
1475 b.Header.MerkleRoot = chainhash.Hash{}
1477 rejected(blockchain.ErrBadMerkleRoot)
1479 // Create block with an invalid proof-of-work limit.
1484 g.nextBlock("b49", outs[14], func(b *wire.MsgBlock) {
1487 rejected(blockchain.ErrUnexpectedDifficulty)
1489 // Create block with an invalid negative proof-of-work limit.
1494 b49a := g.nextBlock("b49a", outs[14])
1495 // This can't be done inside a munge function passed to nextBlock
1496 // because the block is solved after the function returns and this test
1497 // involves an unsolvable block.
1499 origHash := b49a.BlockHash()
1500 b49a.Header.Bits = 0x01810000 // -1 in compact form.
1501 g.updateBlockState("b49a", origHash, "b49a", b49a)
1503 rejected(blockchain.ErrUnexpectedDifficulty)
1505 // Create block with two coinbase transactions.
1510 coinbaseTx := g.createCoinbaseTx(g.tipHeight + 1)
1511 g.nextBlock("b50", outs[14], additionalTx(coinbaseTx))
1512 rejected(blockchain.ErrMultipleCoinbases)
1514 // Create block with duplicate transactions.
1516 // This test relies on the shape of the shape of the merkle tree to test
1517 // the intended condition and thus is asserted below.
1522 g.nextBlock("b51", outs[14], func(b *wire.MsgBlock) {
1523 b.AddTransaction(b.Transactions[1])
1525 g.assertTipBlockNumTxns(3)
1526 rejected(blockchain.ErrDuplicateTx)
1528 // Create a block that spends a transaction that does not exist.
1533 g.nextBlock("b52", outs[14], func(b *wire.MsgBlock) {
1534 hash := newHashFromStr("00000000000000000000000000000000" +
1535 "00000000000000000123456789abcdef")
1536 b.Transactions[1].TxIn[0].PreviousOutPoint.Hash = *hash
1537 b.Transactions[1].TxIn[0].PreviousOutPoint.Index = 0
1539 rejected(blockchain.ErrMissingTxOut)
1541 // ---------------------------------------------------------------------
1542 // Block header median time tests.
1543 // ---------------------------------------------------------------------
1545 // Reset the chain to a stable base.
1547 // ... -> b33(9) -> b35(10) -> b39(11) -> b42(12) -> b43(13) -> b53(14)
1549 g.nextBlock("b53", outs[14])
1552 // Create a block with a timestamp that is exactly the median time. The
1553 // block must be rejected.
1555 // ... -> b33(9) -> b35(10) -> b39(11) -> b42(12) -> b43(13) -> b53(14)
1557 g.nextBlock("b54", outs[15], func(b *wire.MsgBlock) {
1558 medianBlock := g.blocks[b.Header.PrevBlock]
1559 for i := 0; i < medianTimeBlocks/2; i++ {
1560 medianBlock = g.blocks[medianBlock.Header.PrevBlock]
1562 b.Header.Timestamp = medianBlock.Header.Timestamp
1564 rejected(blockchain.ErrTimeTooOld)
1566 // Create a block with a timestamp that is one second after the median
1567 // time. The block must be accepted.
1569 // ... -> b33(9) -> b35(10) -> b39(11) -> b42(12) -> b43(13) -> b53(14) -> b55(15)
1571 g.nextBlock("b55", outs[15], func(b *wire.MsgBlock) {
1572 medianBlock := g.blocks[b.Header.PrevBlock]
1573 for i := 0; i < medianTimeBlocks/2; i++ {
1574 medianBlock = g.blocks[medianBlock.Header.PrevBlock]
1576 medianBlockTime := medianBlock.Header.Timestamp
1577 b.Header.Timestamp = medianBlockTime.Add(time.Second)
1581 // ---------------------------------------------------------------------
1582 // CVE-2012-2459 (block hash collision due to merkle tree algo) tests.
1583 // ---------------------------------------------------------------------
1585 // Create two blocks that have the same hash via merkle tree tricks to
1586 // ensure that the valid block is accepted even though it has the same
1587 // hash as the invalid block that was rejected first.
1589 // This is accomplished by building the blocks as follows:
1591 // b57 (valid block):
1593 // root = h1234 = h(h12 || h34)
1595 // h12 = h(h(cb) || h(tx2)) h34 = h(h(tx3) || h(tx3))
1597 // coinbase tx2 tx3 nil
1599 // transactions: coinbase, tx2, tx3
1600 // merkle tree level 1: h12 = h(h(cb) || h(tx2))
1601 // h34 = h(h(tx3) || h(tx3)) // Algo reuses tx3
1602 // merkle tree root: h(h12 || h34)
1604 // b56 (invalid block with the same hash):
1606 // root = h1234 = h(h12 || h34)
1608 // h12 = h(h(cb) || h(tx2)) h34 = h(h(tx3) || h(tx3))
1610 // coinbase tx2 tx3 tx3
1612 // transactions: coinbase, tx2, tx3, tx3
1613 // merkle tree level 1: h12 = h(h(cb) || h(tx2))
1614 // h34 = h(h(tx3) || h(tx3)) // real tx3 dup
1615 // merkle tree root: h(h12 || h34)
1617 // ... -> b55(15) -> b57(16)
1620 b57 := g.nextBlock("b57", outs[16], func(b *wire.MsgBlock) {
1621 tx2 := b.Transactions[1]
1622 tx3 := createSpendTxForTx(tx2, lowFee)
1623 b.AddTransaction(tx3)
1625 g.assertTipBlockNumTxns(3)
1628 b56 := g.nextBlock("b56", nil, func(b *wire.MsgBlock) {
1629 *b = cloneBlock(b57)
1630 b.AddTransaction(b.Transactions[2])
1632 g.assertTipBlockNumTxns(4)
1633 g.assertTipBlockHash(b57.BlockHash())
1634 g.assertTipBlockMerkleRoot(b57.Header.MerkleRoot)
1635 rejected(blockchain.ErrDuplicateTx)
1637 // Since the two blocks have the same hash and the generator state now
1638 // has b56 associated with the hash, manually remove b56, replace it
1639 // with b57, and then reset the tip to it.
1640 g.updateBlockState("b56", b56.BlockHash(), "b57", b57)
1644 // Create a block that contains two duplicate txns that are not in a
1645 // consecutive position within the merkle tree.
1647 // This is accomplished by building the block as follows:
1649 // transactions: coinbase, tx2, tx3, tx4, tx5, tx6, tx3, tx4
1650 // merkle tree level 2: h12 = h(h(cb) || h(tx2))
1651 // h34 = h(h(tx3) || h(tx4))
1652 // h56 = h(h(tx5) || h(tx6))
1653 // h78 = h(h(tx3) || h(tx4)) // Same as h34
1654 // merkle tree level 1: h1234 = h(h12 || h34)
1655 // h5678 = h(h56 || h78)
1656 // merkle tree root: h(h1234 || h5678)
1659 // ... -> b55(15) -> b57(16)
1662 g.nextBlock("b56p2", outs[16], func(b *wire.MsgBlock) {
1663 // Create 4 transactions that each spend from the previous tx
1665 spendTx := b.Transactions[1]
1666 for i := 0; i < 4; i++ {
1667 spendTx = createSpendTxForTx(spendTx, lowFee)
1668 b.AddTransaction(spendTx)
1671 // Add the duplicate transactions (3rd and 4th).
1672 b.AddTransaction(b.Transactions[2])
1673 b.AddTransaction(b.Transactions[3])
1675 g.assertTipBlockNumTxns(8)
1676 rejected(blockchain.ErrDuplicateTx)
1678 // ---------------------------------------------------------------------
1679 // Invalid transaction type tests.
1680 // ---------------------------------------------------------------------
1682 // Create block with a transaction that tries to spend from an index
1683 // that is out of range from an otherwise valid and existing tx.
1688 g.nextBlock("b58", outs[17], func(b *wire.MsgBlock) {
1689 b.Transactions[1].TxIn[0].PreviousOutPoint.Index = 42
1691 rejected(blockchain.ErrMissingTxOut)
1693 // Create block with transaction that pays more than its inputs.
1698 g.nextBlock("b59", outs[17], func(b *wire.MsgBlock) {
1699 b.Transactions[1].TxOut[0].Value = int64(outs[17].amount) + 1
1701 rejected(blockchain.ErrSpendTooHigh)
1703 // ---------------------------------------------------------------------
1705 // ---------------------------------------------------------------------
1707 // Create a good block to reset the chain to a stable base.
1709 // ... -> b57(16) -> b60(17)
1711 g.nextBlock("b60", outs[17])
1714 // Create block that has a tx with the same hash as an existing tx that
1715 // has not been fully spent.
1719 g.nextBlock("b61", outs[18], func(b *wire.MsgBlock) {
1720 // Duplicate the coinbase of the parent block to force the
1722 parent := g.blocks[b.Header.PrevBlock]
1723 b.Transactions[0] = parent.Transactions[0]
1725 rejected(blockchain.ErrOverwriteTx)
1727 // ---------------------------------------------------------------------
1728 // Blocks with non-final transaction tests.
1729 // ---------------------------------------------------------------------
1731 // Create block that contains a non-final non-coinbase transaction.
1736 g.nextBlock("b62", outs[18], func(b *wire.MsgBlock) {
1737 // A non-final transaction must have at least one input with a
1738 // non-final sequence number in addition to a non-final lock
1740 b.Transactions[1].LockTime = 0xffffffff
1741 b.Transactions[1].TxIn[0].Sequence = 0
1743 rejected(blockchain.ErrUnfinalizedTx)
1745 // Create block that contains a non-final coinbase transaction.
1750 g.nextBlock("b63", outs[18], func(b *wire.MsgBlock) {
1751 // A non-final transaction must have at least one input with a
1752 // non-final sequence number in addition to a non-final lock
1754 b.Transactions[0].LockTime = 0xffffffff
1755 b.Transactions[0].TxIn[0].Sequence = 0
1757 rejected(blockchain.ErrUnfinalizedTx)
1759 // ---------------------------------------------------------------------
1760 // Non-canonical variable-length integer tests.
1761 // ---------------------------------------------------------------------
1763 // Create a max size block with the variable-length integer for the
1764 // number of transactions replaced with a larger non-canonical version
1765 // that causes the block size to exceed the max allowed size. Then,
1766 // create another block that is identical except with the canonical
1767 // encoding and ensure it is accepted. The intent is to verify the
1768 // implementation does not reject the second block, which will have the
1769 // same hash, due to the first one already being rejected.
1771 // ... -> b60(17) -> b64(18)
1774 b64a := g.nextBlock("b64a", outs[18], func(b *wire.MsgBlock) {
1775 bytesToMaxSize := maxBlockSize - b.SerializeSize() - 3
1776 sizePadScript := repeatOpcode(0x00, bytesToMaxSize)
1777 replaceSpendScript(sizePadScript)(b)
1779 g.assertTipNonCanonicalBlockSize(maxBlockSize + 8)
1780 rejectedNonCanonical()
1783 b64 := g.nextBlock("b64", outs[18], func(b *wire.MsgBlock) {
1784 *b = cloneBlock(b64a)
1786 // Since the two blocks have the same hash and the generator state now
1787 // has b64a associated with the hash, manually remove b64a, replace it
1788 // with b64, and then reset the tip to it.
1789 g.updateBlockState("b64a", b64a.BlockHash(), "b64", b64)
1791 g.assertTipBlockHash(b64a.BlockHash())
1792 g.assertTipBlockSize(maxBlockSize)
1795 // ---------------------------------------------------------------------
1796 // Same block transaction spend tests.
1797 // ---------------------------------------------------------------------
1799 // Create block that spends an output created earlier in the same block.
1801 // ... b64(18) -> b65(19)
1803 g.nextBlock("b65", outs[19], func(b *wire.MsgBlock) {
1804 tx3 := createSpendTxForTx(b.Transactions[1], lowFee)
1805 b.AddTransaction(tx3)
1809 // Create block that spends an output created later in the same block.
1813 g.nextBlock("b66", nil, func(b *wire.MsgBlock) {
1814 tx2 := createSpendTx(outs[20], lowFee)
1815 tx3 := createSpendTxForTx(tx2, lowFee)
1816 b.AddTransaction(tx3)
1817 b.AddTransaction(tx2)
1819 rejected(blockchain.ErrMissingTxOut)
1821 // Create block that double spends a transaction created in the same
1827 g.nextBlock("b67", outs[20], func(b *wire.MsgBlock) {
1828 tx2 := b.Transactions[1]
1829 tx3 := createSpendTxForTx(tx2, lowFee)
1830 tx4 := createSpendTxForTx(tx2, lowFee)
1831 b.AddTransaction(tx3)
1832 b.AddTransaction(tx4)
1834 rejected(blockchain.ErrMissingTxOut)
1836 // ---------------------------------------------------------------------
1837 // Extra subsidy tests.
1838 // ---------------------------------------------------------------------
1840 // Create block that pays 10 extra to the coinbase and a tx that only
1846 g.nextBlock("b68", outs[20], additionalCoinbase(10), additionalSpendFee(9))
1847 rejected(blockchain.ErrBadCoinbaseValue)
1849 // Create block that pays 10 extra to the coinbase and a tx that pays
1850 // the extra 10 fee.
1852 // ... -> b65(19) -> b69(20)
1854 g.nextBlock("b69", outs[20], additionalCoinbase(10), additionalSpendFee(10))
1857 // ---------------------------------------------------------------------
1858 // More signature operations counting tests.
1860 // The next several tests ensure signature operations are counted before
1861 // script elements that cause parse failure while those after are
1862 // ignored and that signature operations after script elements that
1863 // successfully parse even if that element will fail at run-time are
1865 // ---------------------------------------------------------------------
1867 // Create block with more than max allowed signature operations such
1868 // that the signature operation that pushes it over the limit is after
1869 // a push data with a script element size that is larger than the max
1870 // allowed size when executed. The block must be rejected because the
1871 // signature operation after the script element must be counted since
1872 // the script parses validly.
1874 // The script generated consists of the following form:
1876 // Comment assumptions:
1877 // maxBlockSigOps = 20000
1878 // maxScriptElementSize = 520
1880 // [0-19999] : OP_CHECKSIG
1881 // [20000] : OP_PUSHDATA4
1882 // [20001-20004]: 521 (little-endian encoded maxScriptElementSize+1)
1883 // [20005-20525]: too large script element
1884 // [20526] : OP_CHECKSIG (goes over the limit)
1888 scriptSize := maxBlockSigOps + 5 + (maxScriptElementSize + 1) + 1
1889 tooManySigOps = repeatOpcode(txscript.OP_CHECKSIG, scriptSize)
1890 tooManySigOps[maxBlockSigOps] = txscript.OP_PUSHDATA4
1891 binary.LittleEndian.PutUint32(tooManySigOps[maxBlockSigOps+1:],
1892 maxScriptElementSize+1)
1893 g.nextBlock("b70", outs[21], replaceSpendScript(tooManySigOps))
1894 g.assertTipBlockSigOpsCount(maxBlockSigOps + 1)
1895 rejected(blockchain.ErrTooManySigOps)
1897 // Create block with more than max allowed signature operations such
1898 // that the signature operation that pushes it over the limit is before
1899 // an invalid push data that claims a large amount of data even though
1900 // that much data is not provided.
1905 scriptSize = maxBlockSigOps + 5 + maxScriptElementSize + 1
1906 tooManySigOps = repeatOpcode(txscript.OP_CHECKSIG, scriptSize)
1907 tooManySigOps[maxBlockSigOps+1] = txscript.OP_PUSHDATA4
1908 binary.LittleEndian.PutUint32(tooManySigOps[maxBlockSigOps+2:], 0xffffffff)
1909 g.nextBlock("b71", outs[21], replaceSpendScript(tooManySigOps))
1910 g.assertTipBlockSigOpsCount(maxBlockSigOps + 1)
1911 rejected(blockchain.ErrTooManySigOps)
1913 // Create block with the max allowed signature operations such that all
1914 // counted signature operations are before an invalid push data that
1915 // claims a large amount of data even though that much data is not
1916 // provided. The pushed data itself consists of OP_CHECKSIG so the
1917 // block would be rejected if any of them were counted.
1919 // ... -> b69(20) -> b72(21)
1921 scriptSize = maxBlockSigOps + 5 + maxScriptElementSize
1922 manySigOps = repeatOpcode(txscript.OP_CHECKSIG, scriptSize)
1923 manySigOps[maxBlockSigOps] = txscript.OP_PUSHDATA4
1924 binary.LittleEndian.PutUint32(manySigOps[maxBlockSigOps+1:], 0xffffffff)
1925 g.nextBlock("b72", outs[21], replaceSpendScript(manySigOps))
1926 g.assertTipBlockSigOpsCount(maxBlockSigOps)
1929 // Create block with the max allowed signature operations such that all
1930 // counted signature operations are before an invalid push data that
1931 // contains OP_CHECKSIG in the number of bytes to push. The block would
1932 // be rejected if any of them were counted.
1934 // ... -> b72(21) -> b73(22)
1935 scriptSize = maxBlockSigOps + 5 + (maxScriptElementSize + 1)
1936 manySigOps = repeatOpcode(txscript.OP_CHECKSIG, scriptSize)
1937 manySigOps[maxBlockSigOps] = txscript.OP_PUSHDATA4
1938 g.nextBlock("b73", outs[22], replaceSpendScript(manySigOps))
1939 g.assertTipBlockSigOpsCount(maxBlockSigOps)
1942 // ---------------------------------------------------------------------
1943 // Dead execution path tests.
1944 // ---------------------------------------------------------------------
1946 // Create block with an invalid opcode in a dead execution path.
1948 // ... -> b73(22) -> b74(23)
1949 script := []byte{txscript.OP_IF, txscript.OP_INVALIDOPCODE,
1950 txscript.OP_ELSE, txscript.OP_TRUE, txscript.OP_ENDIF}
1951 g.nextBlock("b74", outs[23], replaceSpendScript(script), func(b *wire.MsgBlock) {
1952 tx2 := b.Transactions[1]
1953 tx3 := createSpendTxForTx(tx2, lowFee)
1954 tx3.TxIn[0].SignatureScript = []byte{txscript.OP_FALSE}
1955 b.AddTransaction(tx3)
1959 // ---------------------------------------------------------------------
1960 // Various OP_RETURN tests.
1961 // ---------------------------------------------------------------------
1963 // Create a block that has multiple transactions each with a single
1964 // OP_RETURN output.
1966 // ... -> b74(23) -> b75(24)
1967 g.nextBlock("b75", outs[24], func(b *wire.MsgBlock) {
1968 // Add 4 outputs to the spending transaction that are spent
1970 const numAdditionalOutputs = 4
1971 const zeroCoin = int64(0)
1972 spendTx := b.Transactions[1]
1973 for i := 0; i < numAdditionalOutputs; i++ {
1974 spendTx.AddTxOut(wire.NewTxOut(zeroCoin, opTrueScript))
1977 // Add transactions spending from the outputs added above that
1978 // each contain an OP_RETURN output.
1980 // NOTE: The createSpendTx func adds the OP_RETURN output.
1981 zeroFee := btcutil.Amount(0)
1982 for i := uint32(0); i < numAdditionalOutputs; i++ {
1983 spend := makeSpendableOut(b, 1, i+2)
1984 tx := createSpendTx(&spend, zeroFee)
1985 b.AddTransaction(tx)
1988 g.assertTipBlockNumTxns(6)
1989 g.assertTipBlockTxOutOpReturn(5, 1)
1990 b75OpReturnOut := makeSpendableOut(g.tip, 5, 1)
1993 // Reorg to a side chain that does not contain the OP_RETURNs.
1995 // ... -> b74(23) -> b75(24)
1996 // \-> b76(24) -> b77(25)
1998 g.nextBlock("b76", outs[24])
1999 acceptedToSideChainWithExpectedTip("b75")
2001 g.nextBlock("b77", outs[25])
2004 // Reorg back to the original chain that contains the OP_RETURNs.
2006 // ... -> b74(23) -> b75(24) -> b78(25) -> b79(26)
2007 // \-> b76(24) -> b77(25)
2009 g.nextBlock("b78", outs[25])
2010 acceptedToSideChainWithExpectedTip("b77")
2012 g.nextBlock("b79", outs[26])
2015 // Create a block that spends an OP_RETURN.
2017 // ... -> b74(23) -> b75(24) -> b78(25) -> b79(26)
2018 // \-> b76(24) -> b77(25) \-> b80(b75.tx[5].out[1])
2020 // An OP_RETURN output doesn't have any value and the default behavior
2021 // of nextBlock is to assign a fee of one, so increment the amount here
2022 // to effective negate that behavior.
2023 b75OpReturnOut.amount++
2024 g.nextBlock("b80", &b75OpReturnOut)
2025 rejected(blockchain.ErrMissingTxOut)
2027 // Create a block that has a transaction with multiple OP_RETURNs. Even
2028 // though it's not considered a standard transaction, it is still valid
2029 // by the consensus rules.
2031 // ... -> b79(26) -> b81(27)
2034 g.nextBlock("b81", outs[27], func(b *wire.MsgBlock) {
2035 const numAdditionalOutputs = 4
2036 const zeroCoin = int64(0)
2037 spendTx := b.Transactions[1]
2038 for i := 0; i < numAdditionalOutputs; i++ {
2039 opRetScript := uniqueOpReturnScript()
2040 spendTx.AddTxOut(wire.NewTxOut(zeroCoin, opRetScript))
2043 for i := uint32(2); i < 6; i++ {
2044 g.assertTipBlockTxOutOpReturn(1, i)
2048 // ---------------------------------------------------------------------
2049 // Large block re-org test.
2050 // ---------------------------------------------------------------------
2052 if !includeLargeReorg {
2056 // Ensure the tip the re-org test builds on is the best chain tip.
2058 // ... -> b81(27) -> ...
2061 // Collect all of the spendable coinbase outputs from the previous
2062 // collection point up to the current tip.
2063 g.saveSpendableCoinbaseOuts()
2064 spendableOutOffset := g.tipHeight - int32(coinbaseMaturity)
2066 // Extend the main chain by a large number of max size blocks.
2068 // ... -> br0 -> br1 -> ... -> br#
2070 reorgSpend := *outs[spendableOutOffset]
2071 reorgStartBlockName := g.tipName
2072 chain1TipName := g.tipName
2073 for i := int32(0); i < numLargeReorgBlocks; i++ {
2074 chain1TipName = fmt.Sprintf("br%d", i)
2075 g.nextBlock(chain1TipName, &reorgSpend, func(b *wire.MsgBlock) {
2076 bytesToMaxSize := maxBlockSize - b.SerializeSize() - 3
2077 sizePadScript := repeatOpcode(0x00, bytesToMaxSize)
2078 replaceSpendScript(sizePadScript)(b)
2080 g.assertTipBlockSize(maxBlockSize)
2081 g.saveTipCoinbaseOut()
2082 testInstances = append(testInstances, acceptBlock(g.tipName,
2083 g.tip, true, false))
2085 // Use the next available spendable output. First use up any
2086 // remaining spendable outputs that were already popped into the
2087 // outs slice, then just pop them from the stack.
2088 if spendableOutOffset+1+i < int32(len(outs)) {
2089 reorgSpend = *outs[spendableOutOffset+1+i]
2091 reorgSpend = g.oldestCoinbaseOut()
2094 tests = append(tests, testInstances)
2096 // Create a side chain that has the same length.
2098 // ... -> br0 -> ... -> br#
2099 // \-> bralt0 -> ... -> bralt#
2100 g.setTip(reorgStartBlockName)
2102 chain2TipName := g.tipName
2103 for i := uint16(0); i < numLargeReorgBlocks; i++ {
2104 chain2TipName = fmt.Sprintf("bralt%d", i)
2105 g.nextBlock(chain2TipName, nil)
2106 testInstances = append(testInstances, acceptBlock(g.tipName,
2107 g.tip, false, false))
2109 testInstances = append(testInstances, expectTipBlock(chain1TipName,
2110 g.blocksByName[chain1TipName]))
2111 tests = append(tests, testInstances)
2113 // Extend the side chain by one to force the large reorg.
2115 // ... -> bralt0 -> ... -> bralt# -> bralt#+1
2116 // \-> br0 -> ... -> br#
2117 g.nextBlock(fmt.Sprintf("bralt%d", g.tipHeight+1), nil)
2118 chain2TipName = g.tipName
2121 // Extend the first chain by two to force a large reorg back to it.
2123 // ... -> br0 -> ... -> br# -> br#+1 -> br#+2
2124 // \-> bralt0 -> ... -> bralt# -> bralt#+1
2125 g.setTip(chain1TipName)
2126 g.nextBlock(fmt.Sprintf("br%d", g.tipHeight+1), nil)
2127 chain1TipName = g.tipName
2128 acceptedToSideChainWithExpectedTip(chain2TipName)
2130 g.nextBlock(fmt.Sprintf("br%d", g.tipHeight+2), nil)
2131 chain1TipName = g.tipName