github.com/lbryio/lbcd@v0.22.119/blockchain/fullblocktests/generate.go (about)

     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.
     4  
     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.
     9  
    10  package fullblocktests
    11  
    12  import (
    13  	"bytes"
    14  	"encoding/binary"
    15  	"errors"
    16  	"fmt"
    17  	"math"
    18  	"runtime"
    19  	"time"
    20  
    21  	"github.com/lbryio/lbcd/blockchain"
    22  	"github.com/lbryio/lbcd/btcec"
    23  	"github.com/lbryio/lbcd/chaincfg"
    24  	"github.com/lbryio/lbcd/chaincfg/chainhash"
    25  	"github.com/lbryio/lbcd/txscript"
    26  	"github.com/lbryio/lbcd/wire"
    27  	btcutil "github.com/lbryio/lbcutil"
    28  )
    29  
    30  const (
    31  	// Intentionally defined here rather than using constants from codebase
    32  	// to ensure consensus changes are detected.
    33  	maxBlockSigOps       = 20000
    34  	maxBlockSize         = 8000000
    35  	minCoinbaseScriptLen = 2
    36  	maxCoinbaseScriptLen = 100
    37  	medianTimeBlocks     = 11
    38  	maxScriptElementSize = 20000
    39  
    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
    42  	// of blocks.
    43  	numLargeReorgBlocks = 1088
    44  )
    45  
    46  var (
    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}
    50  
    51  	// lowFee is a single satoshi and exists to make the test code more
    52  	// readable.
    53  	lowFee = btcutil.Amount(1)
    54  )
    55  
    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()
    61  }
    62  
    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
    65  // orphan.
    66  type AcceptedBlock struct {
    67  	Name        string
    68  	Block       *wire.MsgBlock
    69  	Height      int32
    70  	IsMainChain bool
    71  	IsOrphan    bool
    72  }
    73  
    74  // Ensure AcceptedBlock implements the TestInstance interface.
    75  var _ TestInstance = AcceptedBlock{}
    76  
    77  // FullBlockTestInstance only exists to allow AcceptedBlock to be treated as a
    78  // TestInstance.
    79  //
    80  // This implements the TestInstance interface.
    81  func (b AcceptedBlock) FullBlockTestInstance() {}
    82  
    83  // RejectedBlock defines a test instance that expects a block to be rejected by
    84  // the blockchain consensus rules.
    85  type RejectedBlock struct {
    86  	Name       string
    87  	Block      *wire.MsgBlock
    88  	Height     int32
    89  	RejectCode blockchain.ErrorCode
    90  }
    91  
    92  // Ensure RejectedBlock implements the TestInstance interface.
    93  var _ TestInstance = RejectedBlock{}
    94  
    95  // FullBlockTestInstance only exists to allow RejectedBlock to be treated as a
    96  // TestInstance.
    97  //
    98  // This implements the TestInstance interface.
    99  func (b RejectedBlock) FullBlockTestInstance() {}
   100  
   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 {
   108  	Name   string
   109  	Block  *wire.MsgBlock
   110  	Height int32
   111  }
   112  
   113  // Ensure ExpectedTip implements the TestInstance interface.
   114  var _ TestInstance = OrphanOrRejectedBlock{}
   115  
   116  // FullBlockTestInstance only exists to allow OrphanOrRejectedBlock to be
   117  // treated as a TestInstance.
   118  //
   119  // This implements the TestInstance interface.
   120  func (b OrphanOrRejectedBlock) FullBlockTestInstance() {}
   121  
   122  // ExpectedTip defines a test instance that expects a block to be the current
   123  // tip of the main chain.
   124  type ExpectedTip struct {
   125  	Name   string
   126  	Block  *wire.MsgBlock
   127  	Height int32
   128  }
   129  
   130  // Ensure ExpectedTip implements the TestInstance interface.
   131  var _ TestInstance = ExpectedTip{}
   132  
   133  // FullBlockTestInstance only exists to allow ExpectedTip to be treated as a
   134  // TestInstance.
   135  //
   136  // This implements the TestInstance interface.
   137  func (b ExpectedTip) FullBlockTestInstance() {}
   138  
   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 {
   142  	Name     string
   143  	RawBlock []byte
   144  	Height   int32
   145  }
   146  
   147  // FullBlockTestInstance only exists to allow RejectedNonCanonicalBlock to be treated as
   148  // a TestInstance.
   149  //
   150  // This implements the TestInstance interface.
   151  func (b RejectedNonCanonicalBlock) FullBlockTestInstance() {}
   152  
   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
   158  }
   159  
   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 {
   163  	return spendableOut{
   164  		prevOut: wire.OutPoint{
   165  			Hash:  tx.TxHash(),
   166  			Index: txOutIndex,
   167  		},
   168  		amount: btcutil.Amount(tx.TxOut[txOutIndex].Value),
   169  	}
   170  }
   171  
   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)
   176  }
   177  
   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
   183  	tip          *wire.MsgBlock
   184  	tipName      string
   185  	tipHeight    int32
   186  	blocks       map[chainhash.Hash]*wire.MsgBlock
   187  	blocksByName map[string]*wire.MsgBlock
   188  	blockHeights map[string]int32
   189  
   190  	// Used for tracking spendable coinbase outputs.
   191  	spendableOuts     []spendableOut
   192  	prevCollectedHash chainhash.Hash
   193  
   194  	// Common key for any tests which require signed transactions.
   195  	privKey *btcec.PrivateKey
   196  }
   197  
   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{
   205  		params:       params,
   206  		blocks:       map[chainhash.Hash]*wire.MsgBlock{genesisHash: genesis},
   207  		blocksByName: map[string]*wire.MsgBlock{"genesis": genesis},
   208  		blockHeights: map[string]int32{"genesis": 0},
   209  		tip:          genesis,
   210  		tipName:      "genesis",
   211  		tipHeight:    0,
   212  		privKey:      privKey,
   213  	}, nil
   214  }
   215  
   216  // payToScriptHashScript returns a standard pay-to-script-hash for the provided
   217  // redeem script.
   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()
   223  	if err != nil {
   224  		panic(err)
   225  	}
   226  	return script
   227  }
   228  
   229  // pushDataScript returns a script with the provided items individually pushed
   230  // to the stack.
   231  func pushDataScript(items ...[]byte) []byte {
   232  	builder := txscript.NewScriptBuilder()
   233  	for _, item := range items {
   234  		builder.AddData(item)
   235  	}
   236  	script, err := builder.Script()
   237  	if err != nil {
   238  		panic(err)
   239  	}
   240  	return script
   241  }
   242  
   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()
   249  }
   250  
   251  // opReturnScript returns a provably-pruneable OP_RETURN script with the
   252  // provided data.
   253  func opReturnScript(data []byte) []byte {
   254  	builder := txscript.NewScriptBuilder()
   255  	script, err := builder.AddOp(txscript.OP_RETURN).AddData(data).Script()
   256  	if err != nil {
   257  		panic(err)
   258  	}
   259  	return script
   260  }
   261  
   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()
   266  	if err != nil {
   267  		panic(err)
   268  	}
   269  
   270  	data := make([]byte, 8)
   271  	binary.LittleEndian.PutUint64(data[0:8], rand)
   272  	return opReturnScript(data)
   273  }
   274  
   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)
   281  	if err != nil {
   282  		panic(err)
   283  	}
   284  
   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,
   293  	})
   294  	tx.AddTxOut(&wire.TxOut{
   295  		Value:    blockchain.CalcBlockSubsidy(blockHeight, g.params),
   296  		PkScript: opTrueScript,
   297  	})
   298  	return tx
   299  }
   300  
   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 {
   304  	if len(txns) == 0 {
   305  		return chainhash.Hash{}
   306  	}
   307  
   308  	utilTxns := make([]*btcutil.Tx, 0, len(txns))
   309  	for _, tx := range txns {
   310  		utilTxns = append(utilTxns, btcutil.NewTx(tx))
   311  	}
   312  	merkles := blockchain.BuildMerkleTreeStore(utilTxns, false)
   313  	return *merkles[len(merkles)-1]
   314  }
   315  
   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.
   320  //
   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
   323  // a munge function.
   324  func solveBlock(header *wire.BlockHeader) bool {
   325  	// sbResult is used by the solver goroutines to send results.
   326  	type sbResult struct {
   327  		found bool
   328  		nonce uint32
   329  	}
   330  
   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++ {
   340  			select {
   341  			case <-quit:
   342  				return
   343  			default:
   344  				hdr.Nonce = i
   345  				hash := hdr.BlockPoWHash()
   346  				if blockchain.HashToBig(&hash).Cmp(targetDifficulty) <= 0 {
   347  					results <- sbResult{true, i}
   348  					return
   349  				}
   350  			}
   351  		}
   352  		results <- sbResult{false, 0}
   353  	}
   354  
   355  	startNonce := uint32(1)
   356  	stopNonce := uint32(math.MaxUint32)
   357  	numCores := uint32(runtime.NumCPU())
   358  	noncesPerCore := (stopNonce - startNonce) / numCores
   359  	for i := uint32(0); i < numCores; i++ {
   360  		rangeStart := startNonce + (noncesPerCore * i)
   361  		rangeStop := startNonce + (noncesPerCore * (i + 1)) - 1
   362  		if i == numCores-1 {
   363  			rangeStop = stopNonce
   364  		}
   365  		go solver(*header, rangeStart, rangeStop)
   366  	}
   367  	for i := uint32(0); i < numCores; i++ {
   368  		result := <-results
   369  		if result.found {
   370  			close(quit)
   371  			header.Nonce = result.nonce
   372  			return true
   373  		}
   374  	}
   375  
   376  	return false
   377  }
   378  
   379  // additionalCoinbase returns a function that itself takes a block and
   380  // modifies it by adding the provided amount to coinbase subsidy.
   381  func additionalCoinbase(amount btcutil.Amount) func(*wire.MsgBlock) {
   382  	return func(b *wire.MsgBlock) {
   383  		// Increase the first proof-of-work coinbase subsidy by the
   384  		// provided amount.
   385  		b.Transactions[0].TxOut[0].Value += int64(amount)
   386  	}
   387  }
   388  
   389  // additionalSpendFee returns a function that itself takes a block and modifies
   390  // it by adding the provided fee to the spending transaction.
   391  //
   392  // NOTE: The coinbase value is NOT updated to reflect the additional fee.  Use
   393  // 'additionalCoinbase' for that purpose.
   394  func additionalSpendFee(fee btcutil.Amount) func(*wire.MsgBlock) {
   395  	return func(b *wire.MsgBlock) {
   396  		// Increase the fee of the spending transaction by reducing the
   397  		// amount paid.
   398  		if int64(fee) > b.Transactions[1].TxOut[0].Value {
   399  			panic(fmt.Sprintf("additionalSpendFee: fee of %d "+
   400  				"exceeds available spend transaction value",
   401  				fee))
   402  		}
   403  		b.Transactions[1].TxOut[0].Value -= int64(fee)
   404  	}
   405  }
   406  
   407  // replaceSpendScript returns a function that itself takes a block and modifies
   408  // it by replacing the public key script of the spending transaction.
   409  func replaceSpendScript(pkScript []byte) func(*wire.MsgBlock) {
   410  	return func(b *wire.MsgBlock) {
   411  		b.Transactions[1].TxOut[0].PkScript = pkScript
   412  	}
   413  }
   414  
   415  // replaceCoinbaseSigScript returns a function that itself takes a block and
   416  // modifies it by replacing the signature key script of the coinbase.
   417  func replaceCoinbaseSigScript(script []byte) func(*wire.MsgBlock) {
   418  	return func(b *wire.MsgBlock) {
   419  		b.Transactions[0].TxIn[0].SignatureScript = script
   420  	}
   421  }
   422  
   423  // additionalTx returns a function that itself takes a block and modifies it by
   424  // adding the the provided transaction.
   425  func additionalTx(tx *wire.MsgTx) func(*wire.MsgBlock) {
   426  	return func(b *wire.MsgBlock) {
   427  		b.AddTransaction(tx)
   428  	}
   429  }
   430  
   431  // createSpendTx creates a transaction that spends from the provided spendable
   432  // output and includes an additional unique OP_RETURN output to ensure the
   433  // transaction ends up with a unique hash.  The script is a simple OP_TRUE
   434  // script which avoids the need to track addresses and signature scripts in the
   435  // tests.
   436  func createSpendTx(spend *spendableOut, fee btcutil.Amount) *wire.MsgTx {
   437  	spendTx := wire.NewMsgTx(1)
   438  	spendTx.AddTxIn(&wire.TxIn{
   439  		PreviousOutPoint: spend.prevOut,
   440  		Sequence:         wire.MaxTxInSequenceNum,
   441  		SignatureScript:  nil,
   442  	})
   443  	spendTx.AddTxOut(wire.NewTxOut(int64(spend.amount-fee),
   444  		opTrueScript))
   445  	spendTx.AddTxOut(wire.NewTxOut(0, uniqueOpReturnScript()))
   446  
   447  	return spendTx
   448  }
   449  
   450  // createSpendTxForTx creates a transaction that spends from the first output of
   451  // the provided transaction and includes an additional unique OP_RETURN output
   452  // to ensure the transaction ends up with a unique hash.  The public key script
   453  // is a simple OP_TRUE script which avoids the need to track addresses and
   454  // signature scripts in the tests.  The signature script is nil.
   455  func createSpendTxForTx(tx *wire.MsgTx, fee btcutil.Amount) *wire.MsgTx {
   456  	spend := makeSpendableOutForTx(tx, 0)
   457  	return createSpendTx(&spend, fee)
   458  }
   459  
   460  // nextBlock builds a new block that extends the current tip associated with the
   461  // generator and updates the generator's tip to the newly generated block.
   462  //
   463  // The block will include the following:
   464  // - A coinbase that pays the required subsidy to an OP_TRUE script
   465  // - When a spendable output is provided:
   466  //   - A transaction that spends from the provided output the following outputs:
   467  //   - One that pays the inputs amount minus 1 atom to an OP_TRUE script
   468  //   - One that contains an OP_RETURN output with a random uint64 in order to
   469  //     ensure the transaction has a unique hash
   470  //
   471  // Additionally, if one or more munge functions are specified, they will be
   472  // invoked with the block prior to solving it.  This provides callers with the
   473  // opportunity to modify the block which is especially useful for testing.
   474  //
   475  // In order to simply the logic in the munge functions, the following rules are
   476  // applied after all munge functions have been invoked:
   477  // - The merkle root will be recalculated unless it was manually changed
   478  // - The block will be solved unless the nonce was changed
   479  func (g *testGenerator) nextBlock(blockName string, spend *spendableOut, mungers ...func(*wire.MsgBlock)) *wire.MsgBlock {
   480  	// Create coinbase transaction for the block using any additional
   481  	// subsidy if specified.
   482  	nextHeight := g.tipHeight + 1
   483  	coinbaseTx := g.createCoinbaseTx(nextHeight)
   484  	txns := []*wire.MsgTx{coinbaseTx}
   485  	if spend != nil {
   486  		// Create the transaction with a fee of 1 atom for the
   487  		// miner and increase the coinbase subsidy accordingly.
   488  		fee := btcutil.Amount(1)
   489  		coinbaseTx.TxOut[0].Value += int64(fee)
   490  
   491  		// Create a transaction that spends from the provided spendable
   492  		// output and includes an additional unique OP_RETURN output to
   493  		// ensure the transaction ends up with a unique hash, then add
   494  		// add it to the list of transactions to include in the block.
   495  		// The script is a simple OP_TRUE script in order to avoid the
   496  		// need to track addresses and signature scripts in the tests.
   497  		txns = append(txns, createSpendTx(spend, fee))
   498  	}
   499  
   500  	// Use a timestamp that is one second after the previous block unless
   501  	// this is the first block in which case the current time is used.
   502  	var ts time.Time
   503  	if nextHeight == 1 {
   504  		ts = time.Unix(time.Now().Unix(), 0)
   505  	} else {
   506  		ts = g.tip.Header.Timestamp.Add(time.Second)
   507  	}
   508  
   509  	block := wire.MsgBlock{
   510  		Header: wire.BlockHeader{
   511  			Version:    1,
   512  			PrevBlock:  g.tip.BlockHash(),
   513  			MerkleRoot: calcMerkleRoot(txns),
   514  			Bits:       g.params.PowLimitBits,
   515  			Timestamp:  ts,
   516  			Nonce:      0, // To be solved.
   517  		},
   518  		Transactions: txns,
   519  	}
   520  
   521  	// Perform any block munging just before solving.  Only recalculate the
   522  	// merkle root if it wasn't manually changed by a munge function.
   523  	curMerkleRoot := block.Header.MerkleRoot
   524  	curNonce := block.Header.Nonce
   525  	for _, f := range mungers {
   526  		f(&block)
   527  	}
   528  	if block.Header.MerkleRoot == curMerkleRoot {
   529  		block.Header.MerkleRoot = calcMerkleRoot(block.Transactions)
   530  	}
   531  
   532  	// Only solve the block if the nonce wasn't manually changed by a munge
   533  	// function.
   534  	if block.Header.Nonce == curNonce && !solveBlock(&block.Header) {
   535  		panic(fmt.Sprintf("Unable to solve block at height %d",
   536  			nextHeight))
   537  	}
   538  
   539  	// Update generator state and return the block.
   540  	blockHash := block.BlockHash()
   541  	g.blocks[blockHash] = &block
   542  	g.blocksByName[blockName] = &block
   543  	g.blockHeights[blockName] = nextHeight
   544  	g.tip = &block
   545  	g.tipName = blockName
   546  	g.tipHeight = nextHeight
   547  	return &block
   548  }
   549  
   550  // updateBlockState manually updates the generator state to remove all internal
   551  // map references to a block via its old hash and insert new ones for the new
   552  // block hash.  This is useful if the test code has to manually change a block
   553  // after 'nextBlock' has returned.
   554  func (g *testGenerator) updateBlockState(oldBlockName string, oldBlockHash chainhash.Hash, newBlockName string, newBlock *wire.MsgBlock) {
   555  	// Look up the height from the existing entries.
   556  	blockHeight := g.blockHeights[oldBlockName]
   557  
   558  	// Remove existing entries.
   559  	delete(g.blocks, oldBlockHash)
   560  	delete(g.blocksByName, oldBlockName)
   561  	delete(g.blockHeights, oldBlockName)
   562  
   563  	// Add new entries.
   564  	newBlockHash := newBlock.BlockHash()
   565  	g.blocks[newBlockHash] = newBlock
   566  	g.blocksByName[newBlockName] = newBlock
   567  	g.blockHeights[newBlockName] = blockHeight
   568  }
   569  
   570  // setTip changes the tip of the instance to the block with the provided name.
   571  // This is useful since the tip is used for things such as generating subsequent
   572  // blocks.
   573  func (g *testGenerator) setTip(blockName string) {
   574  	g.tip = g.blocksByName[blockName]
   575  	g.tipName = blockName
   576  	g.tipHeight = g.blockHeights[blockName]
   577  }
   578  
   579  // oldestCoinbaseOuts removes the oldest coinbase output that was previously
   580  // saved to the generator and returns the set as a slice.
   581  func (g *testGenerator) oldestCoinbaseOut() spendableOut {
   582  	op := g.spendableOuts[0]
   583  	g.spendableOuts = g.spendableOuts[1:]
   584  	return op
   585  }
   586  
   587  // saveTipCoinbaseOut adds the coinbase tx output in the current tip block to
   588  // the list of spendable outputs.
   589  func (g *testGenerator) saveTipCoinbaseOut() {
   590  	g.spendableOuts = append(g.spendableOuts, makeSpendableOut(g.tip, 0, 0))
   591  	g.prevCollectedHash = g.tip.BlockHash()
   592  }
   593  
   594  // saveSpendableCoinbaseOuts adds all coinbase outputs from the last block that
   595  // had its coinbase tx output colleted to the current tip.  This is useful to
   596  // batch the collection of coinbase outputs once the tests reach a stable point
   597  // so they don't have to manually add them for the right tests which will
   598  // ultimately end up being the best chain.
   599  func (g *testGenerator) saveSpendableCoinbaseOuts() {
   600  	// Ensure tip is reset to the current one when done.
   601  	curTipName := g.tipName
   602  	defer g.setTip(curTipName)
   603  
   604  	// Loop through the ancestors of the current tip until the
   605  	// reaching the block that has already had the coinbase outputs
   606  	// collected.
   607  	var collectBlocks []*wire.MsgBlock
   608  	for b := g.tip; b != nil; b = g.blocks[b.Header.PrevBlock] {
   609  		if b.BlockHash() == g.prevCollectedHash {
   610  			break
   611  		}
   612  		collectBlocks = append(collectBlocks, b)
   613  	}
   614  	for i := range collectBlocks {
   615  		g.tip = collectBlocks[len(collectBlocks)-1-i]
   616  		g.saveTipCoinbaseOut()
   617  	}
   618  }
   619  
   620  // nonCanonicalVarInt return a variable-length encoded integer that is encoded
   621  // with 9 bytes even though it could be encoded with a minimal canonical
   622  // encoding.
   623  func nonCanonicalVarInt(val uint32) []byte {
   624  	var rv [9]byte
   625  	rv[0] = 0xff
   626  	binary.LittleEndian.PutUint64(rv[1:], uint64(val))
   627  	return rv[:]
   628  }
   629  
   630  // encodeNonCanonicalBlock serializes the block in a non-canonical way by
   631  // encoding the number of transactions using a variable-length encoded integer
   632  // with 9 bytes even though it should be encoded with a minimal canonical
   633  // encoding.
   634  func encodeNonCanonicalBlock(b *wire.MsgBlock) []byte {
   635  	var buf bytes.Buffer
   636  	b.Header.BtcEncode(&buf, 0, wire.BaseEncoding)
   637  	buf.Write(nonCanonicalVarInt(uint32(len(b.Transactions))))
   638  	for _, tx := range b.Transactions {
   639  		tx.BtcEncode(&buf, 0, wire.BaseEncoding)
   640  	}
   641  	return buf.Bytes()
   642  }
   643  
   644  // cloneBlock returns a deep copy of the provided block.
   645  func cloneBlock(b *wire.MsgBlock) wire.MsgBlock {
   646  	var blockCopy wire.MsgBlock
   647  	blockCopy.Header = b.Header
   648  	for _, tx := range b.Transactions {
   649  		blockCopy.AddTransaction(tx.Copy())
   650  	}
   651  	return blockCopy
   652  }
   653  
   654  // repeatOpcode returns a byte slice with the provided opcode repeated the
   655  // specified number of times.
   656  func repeatOpcode(opcode uint8, numRepeats int) []byte {
   657  	return bytes.Repeat([]byte{opcode}, numRepeats)
   658  }
   659  
   660  // assertScriptSigOpsCount panics if the provided script does not have the
   661  // specified number of signature operations.
   662  func assertScriptSigOpsCount(script []byte, expected int) {
   663  	numSigOps := txscript.GetSigOpCount(script)
   664  	if numSigOps != expected {
   665  		_, file, line, _ := runtime.Caller(1)
   666  		panic(fmt.Sprintf("assertion failed at %s:%d: generated number "+
   667  			"of sigops for script is %d instead of expected %d",
   668  			file, line, numSigOps, expected))
   669  	}
   670  }
   671  
   672  // countBlockSigOps returns the number of legacy signature operations in the
   673  // scripts in the passed block.
   674  func countBlockSigOps(block *wire.MsgBlock) int {
   675  	totalSigOps := 0
   676  	for _, tx := range block.Transactions {
   677  		for _, txIn := range tx.TxIn {
   678  			numSigOps := txscript.GetSigOpCount(txIn.SignatureScript)
   679  			totalSigOps += numSigOps
   680  		}
   681  		for _, txOut := range tx.TxOut {
   682  			numSigOps := txscript.GetSigOpCount(txOut.PkScript)
   683  			totalSigOps += numSigOps
   684  		}
   685  	}
   686  
   687  	return totalSigOps
   688  }
   689  
   690  // assertTipBlockSigOpsCount panics if the current tip block associated with the
   691  // generator does not have the specified number of signature operations.
   692  func (g *testGenerator) assertTipBlockSigOpsCount(expected int) {
   693  	numSigOps := countBlockSigOps(g.tip)
   694  	if numSigOps != expected {
   695  		panic(fmt.Sprintf("generated number of sigops for block %q "+
   696  			"(height %d) is %d instead of expected %d", g.tipName,
   697  			g.tipHeight, numSigOps, expected))
   698  	}
   699  }
   700  
   701  // assertTipBlockSize panics if the if the current tip block associated with the
   702  // generator does not have the specified size when serialized.
   703  func (g *testGenerator) assertTipBlockSize(expected int) {
   704  	serializeSize := g.tip.SerializeSize()
   705  	if serializeSize != expected {
   706  		panic(fmt.Sprintf("block size of block %q (height %d) is %d "+
   707  			"instead of expected %d", g.tipName, g.tipHeight,
   708  			serializeSize, expected))
   709  	}
   710  }
   711  
   712  // assertTipNonCanonicalBlockSize panics if the if the current tip block
   713  // associated with the generator does not have the specified non-canonical size
   714  // when serialized.
   715  func (g *testGenerator) assertTipNonCanonicalBlockSize(expected int) {
   716  	serializeSize := len(encodeNonCanonicalBlock(g.tip))
   717  	if serializeSize != expected {
   718  		panic(fmt.Sprintf("block size of block %q (height %d) is %d "+
   719  			"instead of expected %d", g.tipName, g.tipHeight,
   720  			serializeSize, expected))
   721  	}
   722  }
   723  
   724  // assertTipBlockNumTxns panics if the number of transactions in the current tip
   725  // block associated with the generator does not match the specified value.
   726  func (g *testGenerator) assertTipBlockNumTxns(expected int) {
   727  	numTxns := len(g.tip.Transactions)
   728  	if numTxns != expected {
   729  		panic(fmt.Sprintf("number of txns in block %q (height %d) is "+
   730  			"%d instead of expected %d", g.tipName, g.tipHeight,
   731  			numTxns, expected))
   732  	}
   733  }
   734  
   735  // assertTipBlockHash panics if the current tip block associated with the
   736  // generator does not match the specified hash.
   737  func (g *testGenerator) assertTipBlockHash(expected chainhash.Hash) {
   738  	hash := g.tip.BlockHash()
   739  	if hash != expected {
   740  		panic(fmt.Sprintf("block hash of block %q (height %d) is %v "+
   741  			"instead of expected %v", g.tipName, g.tipHeight, hash,
   742  			expected))
   743  	}
   744  }
   745  
   746  // assertTipBlockMerkleRoot panics if the merkle root in header of the current
   747  // tip block associated with the generator does not match the specified hash.
   748  func (g *testGenerator) assertTipBlockMerkleRoot(expected chainhash.Hash) {
   749  	hash := g.tip.Header.MerkleRoot
   750  	if hash != expected {
   751  		panic(fmt.Sprintf("merkle root of block %q (height %d) is %v "+
   752  			"instead of expected %v", g.tipName, g.tipHeight, hash,
   753  			expected))
   754  	}
   755  }
   756  
   757  // assertTipBlockTxOutOpReturn panics if the current tip block associated with
   758  // the generator does not have an OP_RETURN script for the transaction output at
   759  // the provided tx index and output index.
   760  func (g *testGenerator) assertTipBlockTxOutOpReturn(txIndex, txOutIndex uint32) {
   761  	if txIndex >= uint32(len(g.tip.Transactions)) {
   762  		panic(fmt.Sprintf("Transaction index %d in block %q "+
   763  			"(height %d) does not exist", txIndex, g.tipName,
   764  			g.tipHeight))
   765  	}
   766  
   767  	tx := g.tip.Transactions[txIndex]
   768  	if txOutIndex >= uint32(len(tx.TxOut)) {
   769  		panic(fmt.Sprintf("transaction index %d output %d in block %q "+
   770  			"(height %d) does not exist", txIndex, txOutIndex,
   771  			g.tipName, g.tipHeight))
   772  	}
   773  
   774  	txOut := tx.TxOut[txOutIndex]
   775  	if txOut.PkScript[0] != txscript.OP_RETURN {
   776  		panic(fmt.Sprintf("transaction index %d output %d in block %q "+
   777  			"(height %d) is not an OP_RETURN", txIndex, txOutIndex,
   778  			g.tipName, g.tipHeight))
   779  	}
   780  }
   781  
   782  // Generate returns a slice of tests that can be used to exercise the consensus
   783  // validation rules.  The tests are intended to be flexible enough to allow both
   784  // unit-style tests directly against the blockchain code as well as integration
   785  // style tests over the peer-to-peer network.  To achieve that goal, each test
   786  // contains additional information about the expected result, however that
   787  // information can be ignored when doing comparison tests between two
   788  // independent versions over the peer-to-peer network.
   789  func Generate(includeLargeReorg bool) (tests [][]TestInstance, err error) {
   790  	// In order to simplify the generation code which really should never
   791  	// fail unless the test code itself is broken, panics are used
   792  	// internally.  This deferred func ensures any panics don't escape the
   793  	// generator by replacing the named error return with the underlying
   794  	// panic error.
   795  	defer func() {
   796  		if r := recover(); r != nil {
   797  			tests = nil
   798  
   799  			switch rt := r.(type) {
   800  			case string:
   801  				err = errors.New(rt)
   802  			case error:
   803  				err = rt
   804  			default:
   805  				err = errors.New("Unknown panic")
   806  			}
   807  		}
   808  	}()
   809  
   810  	// Create a test generator instance initialized with the genesis block
   811  	// as the tip.
   812  	g, err := makeTestGenerator(FbRegressionNetParams)
   813  	if err != nil {
   814  		return nil, err
   815  	}
   816  
   817  	// Define some convenience helper functions to return an individual test
   818  	// instance that has the described characteristics.
   819  	//
   820  	// acceptBlock creates a test instance that expects the provided block
   821  	// to be accepted by the consensus rules.
   822  	//
   823  	// rejectBlock creates a test instance that expects the provided block
   824  	// to be rejected by the consensus rules.
   825  	//
   826  	// rejectNonCanonicalBlock creates a test instance that encodes the
   827  	// provided block using a non-canonical encoded as described by the
   828  	// encodeNonCanonicalBlock function and expected it to be rejected.
   829  	//
   830  	// orphanOrRejectBlock creates a test instance that expected the
   831  	// provided block to either by accepted as an orphan or rejected by the
   832  	// consensus rules.
   833  	//
   834  	// expectTipBlock creates a test instance that expects the provided
   835  	// block to be the current tip of the block chain.
   836  	acceptBlock := func(blockName string, block *wire.MsgBlock, isMainChain, isOrphan bool) TestInstance {
   837  		blockHeight := g.blockHeights[blockName]
   838  		return AcceptedBlock{blockName, block, blockHeight, isMainChain,
   839  			isOrphan}
   840  	}
   841  	rejectBlock := func(blockName string, block *wire.MsgBlock, code blockchain.ErrorCode) TestInstance {
   842  		blockHeight := g.blockHeights[blockName]
   843  		return RejectedBlock{blockName, block, blockHeight, code}
   844  	}
   845  	rejectNonCanonicalBlock := func(blockName string, block *wire.MsgBlock) TestInstance {
   846  		blockHeight := g.blockHeights[blockName]
   847  		encoded := encodeNonCanonicalBlock(block)
   848  		return RejectedNonCanonicalBlock{blockName, encoded, blockHeight}
   849  	}
   850  	orphanOrRejectBlock := func(blockName string, block *wire.MsgBlock) TestInstance {
   851  		blockHeight := g.blockHeights[blockName]
   852  		return OrphanOrRejectedBlock{blockName, block, blockHeight}
   853  	}
   854  	expectTipBlock := func(blockName string, block *wire.MsgBlock) TestInstance {
   855  		blockHeight := g.blockHeights[blockName]
   856  		return ExpectedTip{blockName, block, blockHeight}
   857  	}
   858  
   859  	// Define some convenience helper functions to populate the tests slice
   860  	// with test instances that have the described characteristics.
   861  	//
   862  	// accepted creates and appends a single acceptBlock test instance for
   863  	// the current tip which expects the block to be accepted to the main
   864  	// chain.
   865  	//
   866  	// acceptedToSideChainWithExpectedTip creates an appends a two-instance
   867  	// test.  The first instance is an acceptBlock test instance for the
   868  	// current tip which expects the block to be accepted to a side chain.
   869  	// The second instance is an expectBlockTip test instance for provided
   870  	// values.
   871  	//
   872  	// rejected creates and appends a single rejectBlock test instance for
   873  	// the current tip.
   874  	//
   875  	// rejectedNonCanonical creates and appends a single
   876  	// rejectNonCanonicalBlock test instance for the current tip.
   877  	//
   878  	// orphanedOrRejected creates and appends a single orphanOrRejectBlock
   879  	// test instance for the current tip.
   880  	accepted := func() {
   881  		tests = append(tests, []TestInstance{
   882  			acceptBlock(g.tipName, g.tip, true, false),
   883  		})
   884  	}
   885  	acceptedToSideChainWithExpectedTip := func(tipName string) {
   886  		tests = append(tests, []TestInstance{
   887  			acceptBlock(g.tipName, g.tip, false, false),
   888  			expectTipBlock(tipName, g.blocksByName[tipName]),
   889  		})
   890  	}
   891  	rejected := func(code blockchain.ErrorCode) {
   892  		tests = append(tests, []TestInstance{
   893  			rejectBlock(g.tipName, g.tip, code),
   894  		})
   895  	}
   896  	rejectedNonCanonical := func() {
   897  		tests = append(tests, []TestInstance{
   898  			rejectNonCanonicalBlock(g.tipName, g.tip),
   899  		})
   900  	}
   901  	orphanedOrRejected := func() {
   902  		tests = append(tests, []TestInstance{
   903  			orphanOrRejectBlock(g.tipName, g.tip),
   904  		})
   905  	}
   906  
   907  	// ---------------------------------------------------------------------
   908  	// Generate enough blocks to have mature coinbase outputs to work with.
   909  	//
   910  	//   genesis -> bm0 -> bm1 -> ... -> bm99
   911  	// ---------------------------------------------------------------------
   912  
   913  	coinbaseMaturity := g.params.CoinbaseMaturity
   914  	var testInstances []TestInstance
   915  	for i := uint16(0); i < coinbaseMaturity; i++ {
   916  		blockName := fmt.Sprintf("bm%d", i)
   917  		g.nextBlock(blockName, nil)
   918  		g.saveTipCoinbaseOut()
   919  		testInstances = append(testInstances, acceptBlock(g.tipName,
   920  			g.tip, true, false))
   921  	}
   922  	tests = append(tests, testInstances)
   923  
   924  	// Collect spendable outputs.  This simplifies the code below.
   925  	var outs []*spendableOut
   926  	for i := uint16(0); i < coinbaseMaturity; i++ {
   927  		op := g.oldestCoinbaseOut()
   928  		outs = append(outs, &op)
   929  	}
   930  
   931  	// ---------------------------------------------------------------------
   932  	// Basic forking and reorg tests.
   933  	// ---------------------------------------------------------------------
   934  
   935  	// ---------------------------------------------------------------------
   936  	// The comments below identify the structure of the chain being built.
   937  	//
   938  	// The values in parenthesis repesent which outputs are being spent.
   939  	//
   940  	// For example, b1(0) indicates the first collected spendable output
   941  	// which, due to the code above to create the correct number of blocks,
   942  	// is the first output that can be spent at the current block height due
   943  	// to the coinbase maturity requirement.
   944  	// ---------------------------------------------------------------------
   945  
   946  	// Start by building a couple of blocks at current tip (value in parens
   947  	// is which output is spent):
   948  	//
   949  	//   ... -> b1(0) -> b2(1)
   950  	g.nextBlock("b1", outs[0])
   951  	accepted()
   952  
   953  	g.nextBlock("b2", outs[1])
   954  	accepted()
   955  
   956  	// Create a fork from b1.  There should not be a reorg since b2 was seen
   957  	// first.
   958  	//
   959  	//   ... -> b1(0) -> b2(1)
   960  	//               \-> b3(1)
   961  	g.setTip("b1")
   962  	g.nextBlock("b3", outs[1])
   963  	b3Tx1Out := makeSpendableOut(g.tip, 1, 0)
   964  	acceptedToSideChainWithExpectedTip("b2")
   965  
   966  	// Extend b3 fork to make the alternative chain longer and force reorg.
   967  	//
   968  	//   ... -> b1(0) -> b2(1)
   969  	//               \-> b3(1) -> b4(2)
   970  	g.nextBlock("b4", outs[2])
   971  	accepted()
   972  
   973  	// Extend b2 fork twice to make first chain longer and force reorg.
   974  	//
   975  	//   ... -> b1(0) -> b2(1) -> b5(2) -> b6(3)
   976  	//               \-> b3(1) -> b4(2)
   977  	g.setTip("b2")
   978  	g.nextBlock("b5", outs[2])
   979  	acceptedToSideChainWithExpectedTip("b4")
   980  
   981  	g.nextBlock("b6", outs[3])
   982  	accepted()
   983  
   984  	// ---------------------------------------------------------------------
   985  	// Double spend tests.
   986  	// ---------------------------------------------------------------------
   987  
   988  	// Create a fork that double spends.
   989  	//
   990  	//   ... -> b1(0) -> b2(1) -> b5(2) -> b6(3)
   991  	//                                 \-> b7(2) -> b8(4)
   992  	//               \-> b3(1) -> b4(2)
   993  	g.setTip("b5")
   994  	g.nextBlock("b7", outs[2])
   995  	acceptedToSideChainWithExpectedTip("b6")
   996  
   997  	g.nextBlock("b8", outs[4])
   998  	rejected(blockchain.ErrMissingTxOut)
   999  
  1000  	// ---------------------------------------------------------------------
  1001  	// Too much proof-of-work coinbase tests.
  1002  	// ---------------------------------------------------------------------
  1003  
  1004  	// Create a block that generates too coinbase.
  1005  	//
  1006  	//   ... -> b1(0) -> b2(1) -> b5(2) -> b6(3)
  1007  	//                                         \-> b9(4)
  1008  	//               \-> b3(1) -> b4(2)
  1009  	g.setTip("b6")
  1010  	g.nextBlock("b9", outs[4], additionalCoinbase(1))
  1011  	rejected(blockchain.ErrBadCoinbaseValue)
  1012  
  1013  	// Create a fork that ends with block that generates too much coinbase.
  1014  	//
  1015  	//   ... -> b1(0) -> b2(1) -> b5(2) -> b6(3)
  1016  	//                                 \-> b10(3) -> b11(4)
  1017  	//               \-> b3(1) -> b4(2)
  1018  	g.setTip("b5")
  1019  	g.nextBlock("b10", outs[3])
  1020  	acceptedToSideChainWithExpectedTip("b6")
  1021  
  1022  	g.nextBlock("b11", outs[4], additionalCoinbase(1))
  1023  	rejected(blockchain.ErrBadCoinbaseValue)
  1024  
  1025  	// Create a fork that ends with block that generates too much coinbase
  1026  	// as before, but with a valid fork first.
  1027  	//
  1028  	//   ... -> b1(0) -> b2(1) -> b5(2) -> b6(3)
  1029  	//              |                  \-> b12(3) -> b13(4) -> b14(5)
  1030  	//              |                      (b12 added last)
  1031  	//               \-> b3(1) -> b4(2)
  1032  	g.setTip("b5")
  1033  	b12 := g.nextBlock("b12", outs[3])
  1034  	b13 := g.nextBlock("b13", outs[4])
  1035  	b14 := g.nextBlock("b14", outs[5], additionalCoinbase(1))
  1036  	tests = append(tests, []TestInstance{
  1037  		acceptBlock("b13", b13, false, true),
  1038  		acceptBlock("b14", b14, false, true),
  1039  		rejectBlock("b12", b12, blockchain.ErrBadCoinbaseValue),
  1040  		expectTipBlock("b13", b13),
  1041  	})
  1042  
  1043  	// ---------------------------------------------------------------------
  1044  	// Checksig signature operation count tests.
  1045  	// ---------------------------------------------------------------------
  1046  
  1047  	// Add a block with max allowed signature operations using OP_CHECKSIG.
  1048  	//
  1049  	//   ... -> b5(2) -> b12(3) -> b13(4) -> b15(5)
  1050  	//   \-> b3(1) -> b4(2)
  1051  	g.setTip("b13")
  1052  	manySigOps := repeatOpcode(txscript.OP_CHECKSIG, maxBlockSigOps)
  1053  	g.nextBlock("b15", outs[5], replaceSpendScript(manySigOps))
  1054  	g.assertTipBlockSigOpsCount(maxBlockSigOps)
  1055  	accepted()
  1056  
  1057  	// Attempt to add block with more than max allowed signature operations
  1058  	// using OP_CHECKSIG.
  1059  	//
  1060  	//   ... -> b5(2) -> b12(3) -> b13(4) -> b15(5)
  1061  	//   \                                         \-> b16(7)
  1062  	//    \-> b3(1) -> b4(2)
  1063  	tooManySigOps := repeatOpcode(txscript.OP_CHECKSIG, maxBlockSigOps+1)
  1064  	g.nextBlock("b16", outs[6], replaceSpendScript(tooManySigOps))
  1065  	g.assertTipBlockSigOpsCount(maxBlockSigOps + 1)
  1066  	rejected(blockchain.ErrTooManySigOps)
  1067  
  1068  	// ---------------------------------------------------------------------
  1069  	// Cross-fork spend tests.
  1070  	// ---------------------------------------------------------------------
  1071  
  1072  	// Create block that spends a tx created on a different fork.
  1073  	//
  1074  	//   ... -> b5(2) -> b12(3) -> b13(4) -> b15(5)
  1075  	//   \                                         \-> b17(b3.tx[1])
  1076  	//    \-> b3(1) -> b4(2)
  1077  	g.setTip("b15")
  1078  	g.nextBlock("b17", &b3Tx1Out)
  1079  	rejected(blockchain.ErrMissingTxOut)
  1080  
  1081  	// Create block that forks and spends a tx created on a third fork.
  1082  	//
  1083  	//   ... -> b5(2) -> b12(3) -> b13(4) -> b15(5)
  1084  	//   |                               \-> b18(b3.tx[1]) -> b19(6)
  1085  	//    \-> b3(1) -> b4(2)
  1086  	g.setTip("b13")
  1087  	g.nextBlock("b18", &b3Tx1Out)
  1088  	acceptedToSideChainWithExpectedTip("b15")
  1089  
  1090  	g.nextBlock("b19", outs[6])
  1091  	rejected(blockchain.ErrMissingTxOut)
  1092  
  1093  	// ---------------------------------------------------------------------
  1094  	// Immature coinbase tests.
  1095  	// ---------------------------------------------------------------------
  1096  
  1097  	// Create block that spends immature coinbase.
  1098  	//
  1099  	//   ... -> b13(4) -> b15(5)
  1100  	//                          \-> b20(7)
  1101  	g.setTip("b15")
  1102  	g.nextBlock("b20", outs[7])
  1103  	rejected(blockchain.ErrImmatureSpend)
  1104  
  1105  	// Create block that spends immature coinbase on a fork.
  1106  	//
  1107  	//   ... -> b13(4) -> b15(5)
  1108  	//                \-> b21(5) -> b22(7)
  1109  	g.setTip("b13")
  1110  	g.nextBlock("b21", outs[5])
  1111  	acceptedToSideChainWithExpectedTip("b15")
  1112  
  1113  	g.nextBlock("b22", outs[7])
  1114  	rejected(blockchain.ErrImmatureSpend)
  1115  
  1116  	// ---------------------------------------------------------------------
  1117  	// Max block size tests.
  1118  	// ---------------------------------------------------------------------
  1119  
  1120  	// Create block that is the max allowed size.
  1121  	//
  1122  	//   ... -> b15(5) -> b23(6)
  1123  	g.setTip("b15")
  1124  	g.nextBlock("b23", outs[6], func(b *wire.MsgBlock) {
  1125  		bytesToMaxSize := maxBlockSize - b.SerializeSize() - 3
  1126  		sizePadScript := repeatOpcode(0x00, bytesToMaxSize)
  1127  		replaceSpendScript(sizePadScript)(b)
  1128  	})
  1129  	g.assertTipBlockSize(maxBlockSize)
  1130  	accepted()
  1131  
  1132  	// Create block that is the one byte larger than max allowed size.  This
  1133  	// is done on a fork and should be rejected regardless.
  1134  	//
  1135  	//   ... -> b15(5) -> b23(6)
  1136  	//                \-> b24(6) -> b25(7)
  1137  	g.setTip("b15")
  1138  	g.nextBlock("b24", outs[6], func(b *wire.MsgBlock) {
  1139  		bytesToMaxSize := maxBlockSize - b.SerializeSize() - 3
  1140  		sizePadScript := repeatOpcode(0x00, bytesToMaxSize+1)
  1141  		replaceSpendScript(sizePadScript)(b)
  1142  	})
  1143  	g.assertTipBlockSize(maxBlockSize + 1)
  1144  	rejected(blockchain.ErrBlockTooBig)
  1145  
  1146  	// Parent was rejected, so this block must either be an orphan or
  1147  	// outright rejected due to an invalid parent.
  1148  	g.nextBlock("b25", outs[7])
  1149  	orphanedOrRejected()
  1150  
  1151  	// ---------------------------------------------------------------------
  1152  	// Coinbase script length limits tests.
  1153  	// ---------------------------------------------------------------------
  1154  
  1155  	// Create block that has a coinbase script that is smaller than the
  1156  	// required length.  This is done on a fork and should be rejected
  1157  	// regardless.  Also, create a block that builds on the rejected block.
  1158  	//
  1159  	//   ... -> b15(5) -> b23(6)
  1160  	//                \-> b26(6) -> b27(7)
  1161  	g.setTip("b15")
  1162  	tooSmallCbScript := repeatOpcode(0x00, minCoinbaseScriptLen-1)
  1163  	g.nextBlock("b26", outs[6], replaceCoinbaseSigScript(tooSmallCbScript))
  1164  	rejected(blockchain.ErrBadCoinbaseScriptLen)
  1165  
  1166  	// Parent was rejected, so this block must either be an orphan or
  1167  	// outright rejected due to an invalid parent.
  1168  	g.nextBlock("b27", outs[7])
  1169  	orphanedOrRejected()
  1170  
  1171  	// Create block that has a coinbase script that is larger than the
  1172  	// allowed length.  This is done on a fork and should be rejected
  1173  	// regardless.  Also, create a block that builds on the rejected block.
  1174  	//
  1175  	//   ... -> b15(5) -> b23(6)
  1176  	//                \-> b28(6) -> b29(7)
  1177  	g.setTip("b15")
  1178  	tooLargeCbScript := repeatOpcode(0x00, maxCoinbaseScriptLen+1)
  1179  	g.nextBlock("b28", outs[6], replaceCoinbaseSigScript(tooLargeCbScript))
  1180  	rejected(blockchain.ErrBadCoinbaseScriptLen)
  1181  
  1182  	// Parent was rejected, so this block must either be an orphan or
  1183  	// outright rejected due to an invalid parent.
  1184  	g.nextBlock("b29", outs[7])
  1185  	orphanedOrRejected()
  1186  
  1187  	// Create block that has a max length coinbase script.
  1188  	//
  1189  	//   ... -> b23(6) -> b30(7)
  1190  	g.setTip("b23")
  1191  	maxSizeCbScript := repeatOpcode(0x00, maxCoinbaseScriptLen)
  1192  	g.nextBlock("b30", outs[7], replaceCoinbaseSigScript(maxSizeCbScript))
  1193  	accepted()
  1194  
  1195  	// ---------------------------------------------------------------------
  1196  	// Multisig[Verify]/ChecksigVerifiy signature operation count tests.
  1197  	// ---------------------------------------------------------------------
  1198  
  1199  	// Create block with max signature operations as OP_CHECKMULTISIG.
  1200  	//
  1201  	//   ... -> b30(7) -> b31(8)
  1202  	//
  1203  	// OP_CHECKMULTISIG counts for 20 sigops.
  1204  	manySigOps = repeatOpcode(txscript.OP_CHECKMULTISIG, maxBlockSigOps/20)
  1205  	g.nextBlock("b31", outs[8], replaceSpendScript(manySigOps))
  1206  	g.assertTipBlockSigOpsCount(maxBlockSigOps)
  1207  	accepted()
  1208  
  1209  	// Create block with more than max allowed signature operations using
  1210  	// OP_CHECKMULTISIG.
  1211  	//
  1212  	//   ... -> b31(8)
  1213  	//                \-> b32(9)
  1214  	//
  1215  	// OP_CHECKMULTISIG counts for 20 sigops.
  1216  	tooManySigOps = repeatOpcode(txscript.OP_CHECKMULTISIG, maxBlockSigOps/20)
  1217  	tooManySigOps = append(manySigOps, txscript.OP_CHECKSIG)
  1218  	g.nextBlock("b32", outs[9], replaceSpendScript(tooManySigOps))
  1219  	g.assertTipBlockSigOpsCount(maxBlockSigOps + 1)
  1220  	rejected(blockchain.ErrTooManySigOps)
  1221  
  1222  	// Create block with max signature operations as OP_CHECKMULTISIGVERIFY.
  1223  	//
  1224  	//   ... -> b31(8) -> b33(9)
  1225  	g.setTip("b31")
  1226  	manySigOps = repeatOpcode(txscript.OP_CHECKMULTISIGVERIFY, maxBlockSigOps/20)
  1227  	g.nextBlock("b33", outs[9], replaceSpendScript(manySigOps))
  1228  	g.assertTipBlockSigOpsCount(maxBlockSigOps)
  1229  	accepted()
  1230  
  1231  	// Create block with more than max allowed signature operations using
  1232  	// OP_CHECKMULTISIGVERIFY.
  1233  	//
  1234  	//   ... -> b33(9)
  1235  	//                \-> b34(10)
  1236  	//
  1237  	tooManySigOps = repeatOpcode(txscript.OP_CHECKMULTISIGVERIFY, maxBlockSigOps/20)
  1238  	tooManySigOps = append(manySigOps, txscript.OP_CHECKSIG)
  1239  	g.nextBlock("b34", outs[10], replaceSpendScript(tooManySigOps))
  1240  	g.assertTipBlockSigOpsCount(maxBlockSigOps + 1)
  1241  	rejected(blockchain.ErrTooManySigOps)
  1242  
  1243  	// Create block with max signature operations as OP_CHECKSIGVERIFY.
  1244  	//
  1245  	//   ... -> b33(9) -> b35(10)
  1246  	//
  1247  	g.setTip("b33")
  1248  	manySigOps = repeatOpcode(txscript.OP_CHECKSIGVERIFY, maxBlockSigOps)
  1249  	g.nextBlock("b35", outs[10], replaceSpendScript(manySigOps))
  1250  	g.assertTipBlockSigOpsCount(maxBlockSigOps)
  1251  	accepted()
  1252  
  1253  	// Create block with more than max allowed signature operations using
  1254  	// OP_CHECKSIGVERIFY.
  1255  	//
  1256  	//   ... -> b35(10)
  1257  	//                 \-> b36(11)
  1258  	//
  1259  	tooManySigOps = repeatOpcode(txscript.OP_CHECKSIGVERIFY, maxBlockSigOps+1)
  1260  	g.nextBlock("b36", outs[11], replaceSpendScript(tooManySigOps))
  1261  	g.assertTipBlockSigOpsCount(maxBlockSigOps + 1)
  1262  	rejected(blockchain.ErrTooManySigOps)
  1263  
  1264  	// ---------------------------------------------------------------------
  1265  	// Spending of tx outputs in block that failed to connect tests.
  1266  	// ---------------------------------------------------------------------
  1267  
  1268  	// Create block that spends a transaction from a block that failed to
  1269  	// connect (due to containing a double spend).
  1270  	//
  1271  	//   ... -> b35(10)
  1272  	//                 \-> b37(11)
  1273  	//                 \-> b38(b37.tx[1])
  1274  	//
  1275  	g.setTip("b35")
  1276  	doubleSpendTx := createSpendTx(outs[11], lowFee)
  1277  	g.nextBlock("b37", outs[11], additionalTx(doubleSpendTx))
  1278  	b37Tx1Out := makeSpendableOut(g.tip, 1, 0)
  1279  	rejected(blockchain.ErrMissingTxOut)
  1280  
  1281  	g.setTip("b35")
  1282  	g.nextBlock("b38", &b37Tx1Out)
  1283  	rejected(blockchain.ErrMissingTxOut)
  1284  
  1285  	// ---------------------------------------------------------------------
  1286  	// Pay-to-script-hash signature operation count tests.
  1287  	// ---------------------------------------------------------------------
  1288  
  1289  	// Create a pay-to-script-hash redeem script that consists of 9
  1290  	// signature operations to be used in the next three blocks.
  1291  	const redeemScriptSigOps = 9
  1292  	redeemScript := pushDataScript(g.privKey.PubKey().SerializeCompressed())
  1293  	redeemScript = append(redeemScript, bytes.Repeat([]byte{txscript.OP_2DUP,
  1294  		txscript.OP_CHECKSIGVERIFY}, redeemScriptSigOps-1)...)
  1295  	redeemScript = append(redeemScript, txscript.OP_CHECKSIG)
  1296  	assertScriptSigOpsCount(redeemScript, redeemScriptSigOps)
  1297  
  1298  	// Create a block that has enough pay-to-script-hash outputs such that
  1299  	// another block can be created that consumes them all and exceeds the
  1300  	// max allowed signature operations per block.
  1301  	//
  1302  	//   ... -> b35(10) -> b39(11)
  1303  	g.setTip("b35")
  1304  	b39 := g.nextBlock("b39", outs[11], func(b *wire.MsgBlock) {
  1305  		// Create a chain of transactions each spending from the
  1306  		// previous one such that each contains an output that pays to
  1307  		// the redeem script and the total number of signature
  1308  		// operations in those redeem scripts will be more than the
  1309  		// max allowed per block.
  1310  		p2shScript := payToScriptHashScript(redeemScript)
  1311  		txnsNeeded := (maxBlockSigOps / redeemScriptSigOps) + 1
  1312  		prevTx := b.Transactions[1]
  1313  		for i := 0; i < txnsNeeded; i++ {
  1314  			prevTx = createSpendTxForTx(prevTx, lowFee)
  1315  			prevTx.TxOut[0].Value -= 2
  1316  			prevTx.AddTxOut(wire.NewTxOut(2, p2shScript))
  1317  			b.AddTransaction(prevTx)
  1318  		}
  1319  	})
  1320  	g.assertTipBlockNumTxns((maxBlockSigOps / redeemScriptSigOps) + 3)
  1321  	accepted()
  1322  
  1323  	// Create a block with more than max allowed signature operations where
  1324  	// the majority of them are in pay-to-script-hash scripts.
  1325  	//
  1326  	//   ... -> b35(10) -> b39(11)
  1327  	//                            \-> b40(12)
  1328  	g.setTip("b39")
  1329  	g.nextBlock("b40", outs[12], func(b *wire.MsgBlock) {
  1330  		txnsNeeded := (maxBlockSigOps / redeemScriptSigOps)
  1331  		for i := 0; i < txnsNeeded; i++ {
  1332  			// Create a signed transaction that spends from the
  1333  			// associated p2sh output in b39.
  1334  			spend := makeSpendableOutForTx(b39.Transactions[i+2], 2)
  1335  			tx := createSpendTx(&spend, lowFee)
  1336  			sig, err := txscript.RawTxInSignature(tx, 0,
  1337  				redeemScript, txscript.SigHashAll, g.privKey)
  1338  			if err != nil {
  1339  				panic(err)
  1340  			}
  1341  			tx.TxIn[0].SignatureScript = pushDataScript(sig,
  1342  				redeemScript)
  1343  			b.AddTransaction(tx)
  1344  		}
  1345  
  1346  		// Create a final tx that includes a non-pay-to-script-hash
  1347  		// output with the number of signature operations needed to push
  1348  		// the block one over the max allowed.
  1349  		fill := maxBlockSigOps - (txnsNeeded * redeemScriptSigOps) + 1
  1350  		finalTx := b.Transactions[len(b.Transactions)-1]
  1351  		tx := createSpendTxForTx(finalTx, lowFee)
  1352  		tx.TxOut[0].PkScript = repeatOpcode(txscript.OP_CHECKSIG, fill)
  1353  		b.AddTransaction(tx)
  1354  	})
  1355  	rejected(blockchain.ErrTooManySigOps)
  1356  
  1357  	// Create a block with the max allowed signature operations where the
  1358  	// majority of them are in pay-to-script-hash scripts.
  1359  	//
  1360  	//   ... -> b35(10) -> b39(11) -> b41(12)
  1361  	g.setTip("b39")
  1362  	g.nextBlock("b41", outs[12], func(b *wire.MsgBlock) {
  1363  		txnsNeeded := (maxBlockSigOps / redeemScriptSigOps)
  1364  		for i := 0; i < txnsNeeded; i++ {
  1365  			spend := makeSpendableOutForTx(b39.Transactions[i+2], 2)
  1366  			tx := createSpendTx(&spend, lowFee)
  1367  			sig, err := txscript.RawTxInSignature(tx, 0,
  1368  				redeemScript, txscript.SigHashAll, g.privKey)
  1369  			if err != nil {
  1370  				panic(err)
  1371  			}
  1372  			tx.TxIn[0].SignatureScript = pushDataScript(sig,
  1373  				redeemScript)
  1374  			b.AddTransaction(tx)
  1375  		}
  1376  
  1377  		// Create a final tx that includes a non-pay-to-script-hash
  1378  		// output with the number of signature operations needed to push
  1379  		// the block to exactly the max allowed.
  1380  		fill := maxBlockSigOps - (txnsNeeded * redeemScriptSigOps)
  1381  		if fill == 0 {
  1382  			return
  1383  		}
  1384  		finalTx := b.Transactions[len(b.Transactions)-1]
  1385  		tx := createSpendTxForTx(finalTx, lowFee)
  1386  		tx.TxOut[0].PkScript = repeatOpcode(txscript.OP_CHECKSIG, fill)
  1387  		b.AddTransaction(tx)
  1388  	})
  1389  	accepted()
  1390  
  1391  	// ---------------------------------------------------------------------
  1392  	// Reset the chain to a stable base.
  1393  	//
  1394  	//   ... -> b35(10) -> b39(11) -> b42(12) -> b43(13)
  1395  	//                            \-> b41(12)
  1396  	// ---------------------------------------------------------------------
  1397  
  1398  	g.setTip("b39")
  1399  	g.nextBlock("b42", outs[12])
  1400  	acceptedToSideChainWithExpectedTip("b41")
  1401  
  1402  	g.nextBlock("b43", outs[13])
  1403  	accepted()
  1404  
  1405  	// ---------------------------------------------------------------------
  1406  	// Various malformed block tests.
  1407  	// ---------------------------------------------------------------------
  1408  
  1409  	// Create block with an otherwise valid transaction in place of where
  1410  	// the coinbase must be.
  1411  	//
  1412  	//   ... -> b43(13)
  1413  	//                 \-> b44(14)
  1414  	g.nextBlock("b44", nil, func(b *wire.MsgBlock) {
  1415  		nonCoinbaseTx := createSpendTx(outs[14], lowFee)
  1416  		b.Transactions[0] = nonCoinbaseTx
  1417  	})
  1418  	rejected(blockchain.ErrFirstTxNotCoinbase)
  1419  
  1420  	// Create block with no transactions.
  1421  	//
  1422  	//   ... -> b43(13)
  1423  	//                 \-> b45(_)
  1424  	g.setTip("b43")
  1425  	g.nextBlock("b45", nil, func(b *wire.MsgBlock) {
  1426  		b.Transactions = nil
  1427  	})
  1428  	rejected(blockchain.ErrNoTransactions)
  1429  
  1430  	// Create block with invalid proof of work.
  1431  	//
  1432  	//   ... -> b43(13)
  1433  	//                 \-> b46(14)
  1434  	g.setTip("b43")
  1435  	b46 := g.nextBlock("b46", outs[14])
  1436  	// This can't be done inside a munge function passed to nextBlock
  1437  	// because the block is solved after the function returns and this test
  1438  	// requires an unsolved block.
  1439  	{
  1440  		origHash := b46.BlockHash()
  1441  		for {
  1442  			// Keep incrementing the nonce until the hash treated as
  1443  			// a uint256 is higher than the limit.
  1444  			b46.Header.Nonce++
  1445  			blockHash := b46.Header.BlockPoWHash()
  1446  			hashNum := blockchain.HashToBig(&blockHash)
  1447  			if hashNum.Cmp(g.params.PowLimit) >= 0 {
  1448  				break
  1449  			}
  1450  		}
  1451  		g.updateBlockState("b46", origHash, "b46", b46)
  1452  	}
  1453  	rejected(blockchain.ErrHighHash)
  1454  
  1455  	// Create block with a timestamp too far in the future.
  1456  	//
  1457  	//   ... -> b43(13)
  1458  	//                 \-> b47(14)
  1459  	g.setTip("b43")
  1460  	g.nextBlock("b47", outs[14], func(b *wire.MsgBlock) {
  1461  		// 3 hours in the future clamped to 1 second precision.
  1462  		nowPlus3Hours := time.Now().Add(time.Hour * 3)
  1463  		b.Header.Timestamp = time.Unix(nowPlus3Hours.Unix(), 0)
  1464  	})
  1465  	rejected(blockchain.ErrTimeTooNew)
  1466  
  1467  	// Create block with an invalid merkle root.
  1468  	//
  1469  	//   ... -> b43(13)
  1470  	//                 \-> b48(14)
  1471  	g.setTip("b43")
  1472  	g.nextBlock("b48", outs[14], func(b *wire.MsgBlock) {
  1473  		b.Header.MerkleRoot = chainhash.Hash{}
  1474  	})
  1475  	rejected(blockchain.ErrBadMerkleRoot)
  1476  
  1477  	// Create block with an invalid proof-of-work limit.
  1478  	//
  1479  	//   ... -> b43(13)
  1480  	//                 \-> b49(14)
  1481  	g.setTip("b43")
  1482  	g.nextBlock("b49", outs[14], func(b *wire.MsgBlock) {
  1483  		b.Header.Bits--
  1484  	})
  1485  	rejected(blockchain.ErrUnexpectedDifficulty)
  1486  
  1487  	// Create block with an invalid negative proof-of-work limit.
  1488  	//
  1489  	//   ... -> b43(13)
  1490  	//                 \-> b49a(14)
  1491  	g.setTip("b43")
  1492  	b49a := g.nextBlock("b49a", outs[14])
  1493  	// This can't be done inside a munge function passed to nextBlock
  1494  	// because the block is solved after the function returns and this test
  1495  	// involves an unsolvable block.
  1496  	{
  1497  		origHash := b49a.BlockHash()
  1498  		b49a.Header.Bits = 0x01810000 // -1 in compact form.
  1499  		g.updateBlockState("b49a", origHash, "b49a", b49a)
  1500  	}
  1501  	rejected(blockchain.ErrUnexpectedDifficulty)
  1502  
  1503  	// Create block with two coinbase transactions.
  1504  	//
  1505  	//   ... -> b43(13)
  1506  	//                 \-> b50(14)
  1507  	g.setTip("b43")
  1508  	coinbaseTx := g.createCoinbaseTx(g.tipHeight + 1)
  1509  	g.nextBlock("b50", outs[14], additionalTx(coinbaseTx))
  1510  	rejected(blockchain.ErrMultipleCoinbases)
  1511  
  1512  	// Create block with duplicate transactions.
  1513  	//
  1514  	// This test relies on the shape of the shape of the merkle tree to test
  1515  	// the intended condition and thus is asserted below.
  1516  	//
  1517  	//   ... -> b43(13)
  1518  	//                 \-> b51(14)
  1519  	g.setTip("b43")
  1520  	g.nextBlock("b51", outs[14], func(b *wire.MsgBlock) {
  1521  		b.AddTransaction(b.Transactions[1])
  1522  	})
  1523  	g.assertTipBlockNumTxns(3)
  1524  	rejected(blockchain.ErrDuplicateTx)
  1525  
  1526  	// Create a block that spends a transaction that does not exist.
  1527  	//
  1528  	//   ... -> b43(13)
  1529  	//                 \-> b52(14)
  1530  	g.setTip("b43")
  1531  	g.nextBlock("b52", outs[14], func(b *wire.MsgBlock) {
  1532  		hash := newHashFromStr("00000000000000000000000000000000" +
  1533  			"00000000000000000123456789abcdef")
  1534  		b.Transactions[1].TxIn[0].PreviousOutPoint.Hash = *hash
  1535  		b.Transactions[1].TxIn[0].PreviousOutPoint.Index = 0
  1536  	})
  1537  	rejected(blockchain.ErrMissingTxOut)
  1538  
  1539  	// ---------------------------------------------------------------------
  1540  	// Block header median time tests.
  1541  	// ---------------------------------------------------------------------
  1542  
  1543  	// Reset the chain to a stable base.
  1544  	//
  1545  	//   ... -> b33(9) -> b35(10) -> b39(11) -> b42(12) -> b43(13) -> b53(14)
  1546  	g.setTip("b43")
  1547  	g.nextBlock("b53", outs[14])
  1548  	accepted()
  1549  
  1550  	// Create a block with a timestamp that is exactly the median time.  The
  1551  	// block must be rejected.
  1552  	//
  1553  	//   ... -> b33(9) -> b35(10) -> b39(11) -> b42(12) -> b43(13) -> b53(14)
  1554  	//                                                                       \-> b54(15)
  1555  	g.nextBlock("b54", outs[15], func(b *wire.MsgBlock) {
  1556  		medianBlock := g.blocks[b.Header.PrevBlock]
  1557  		for i := 0; i < medianTimeBlocks/2; i++ {
  1558  			medianBlock = g.blocks[medianBlock.Header.PrevBlock]
  1559  		}
  1560  		b.Header.Timestamp = medianBlock.Header.Timestamp
  1561  	})
  1562  	rejected(blockchain.ErrTimeTooOld)
  1563  
  1564  	// Create a block with a timestamp that is one second after the median
  1565  	// time.  The block must be accepted.
  1566  	//
  1567  	//   ... -> b33(9) -> b35(10) -> b39(11) -> b42(12) -> b43(13) -> b53(14) -> b55(15)
  1568  	g.setTip("b53")
  1569  	g.nextBlock("b55", outs[15], func(b *wire.MsgBlock) {
  1570  		medianBlock := g.blocks[b.Header.PrevBlock]
  1571  		for i := 0; i < medianTimeBlocks/2; i++ {
  1572  			medianBlock = g.blocks[medianBlock.Header.PrevBlock]
  1573  		}
  1574  		medianBlockTime := medianBlock.Header.Timestamp
  1575  		b.Header.Timestamp = medianBlockTime.Add(time.Second)
  1576  	})
  1577  	accepted()
  1578  
  1579  	// ---------------------------------------------------------------------
  1580  	// CVE-2012-2459 (block hash collision due to merkle tree algo) tests.
  1581  	// ---------------------------------------------------------------------
  1582  
  1583  	// Create two blocks that have the same hash via merkle tree tricks to
  1584  	// ensure that the valid block is accepted even though it has the same
  1585  	// hash as the invalid block that was rejected first.
  1586  	//
  1587  	// This is accomplished by building the blocks as follows:
  1588  	//
  1589  	// b57 (valid block):
  1590  	//
  1591  	//                root = h1234 = h(h12 || h34)
  1592  	//	        //                           \\
  1593  	//	  h12 = h(h(cb) || h(tx2))  h34 = h(h(tx3) || h(tx3))
  1594  	//	   //                  \\             //           \\
  1595  	//	 coinbase              tx2           tx3           nil
  1596  	//
  1597  	//   transactions: coinbase, tx2, tx3
  1598  	//   merkle tree level 1: h12 = h(h(cb) || h(tx2))
  1599  	//                        h34 = h(h(tx3) || h(tx3)) // Algo reuses tx3
  1600  	//   merkle tree root: h(h12 || h34)
  1601  	//
  1602  	// b56 (invalid block with the same hash):
  1603  	//
  1604  	//                root = h1234 = h(h12 || h34)
  1605  	//	        //                          \\
  1606  	//	  h12 = h(h(cb) || h(tx2))  h34 = h(h(tx3) || h(tx3))
  1607  	//	   //                  \\             //           \\
  1608  	//	 coinbase              tx2           tx3           tx3
  1609  	//
  1610  	//   transactions: coinbase, tx2, tx3, tx3
  1611  	//   merkle tree level 1: h12 = h(h(cb) || h(tx2))
  1612  	//                        h34 = h(h(tx3) || h(tx3)) // real tx3 dup
  1613  	//   merkle tree root: h(h12 || h34)
  1614  	//
  1615  	//   ... -> b55(15) -> b57(16)
  1616  	//                 \-> b56(16)
  1617  	g.setTip("b55")
  1618  	b57 := g.nextBlock("b57", outs[16], func(b *wire.MsgBlock) {
  1619  		tx2 := b.Transactions[1]
  1620  		tx3 := createSpendTxForTx(tx2, lowFee)
  1621  		b.AddTransaction(tx3)
  1622  	})
  1623  	g.assertTipBlockNumTxns(3)
  1624  
  1625  	g.setTip("b55")
  1626  	b56 := g.nextBlock("b56", nil, func(b *wire.MsgBlock) {
  1627  		*b = cloneBlock(b57)
  1628  		b.AddTransaction(b.Transactions[2])
  1629  	})
  1630  	g.assertTipBlockNumTxns(4)
  1631  	g.assertTipBlockHash(b57.BlockHash())
  1632  	g.assertTipBlockMerkleRoot(b57.Header.MerkleRoot)
  1633  	rejected(blockchain.ErrDuplicateTx)
  1634  
  1635  	// Since the two blocks have the same hash and the generator state now
  1636  	// has b56 associated with the hash, manually remove b56, replace it
  1637  	// with b57, and then reset the tip to it.
  1638  	g.updateBlockState("b56", b56.BlockHash(), "b57", b57)
  1639  	g.setTip("b57")
  1640  	accepted()
  1641  
  1642  	// Create a block that contains two duplicate txns that are not in a
  1643  	// consecutive position within the merkle tree.
  1644  	//
  1645  	// This is accomplished by building the block as follows:
  1646  	//
  1647  	//   transactions: coinbase, tx2, tx3, tx4, tx5, tx6, tx3, tx4
  1648  	//   merkle tree level 2: h12 = h(h(cb) || h(tx2))
  1649  	//                        h34 = h(h(tx3) || h(tx4))
  1650  	//                        h56 = h(h(tx5) || h(tx6))
  1651  	//                        h78 = h(h(tx3) || h(tx4)) // Same as h34
  1652  	//   merkle tree level 1: h1234 = h(h12 || h34)
  1653  	//                        h5678 = h(h56 || h78)
  1654  	//   merkle tree root: h(h1234 || h5678)
  1655  	//
  1656  	//
  1657  	//   ... -> b55(15) -> b57(16)
  1658  	//                 \-> b56p2(16)
  1659  	g.setTip("b55")
  1660  	g.nextBlock("b56p2", outs[16], func(b *wire.MsgBlock) {
  1661  		// Create 4 transactions that each spend from the previous tx
  1662  		// in the block.
  1663  		spendTx := b.Transactions[1]
  1664  		for i := 0; i < 4; i++ {
  1665  			spendTx = createSpendTxForTx(spendTx, lowFee)
  1666  			b.AddTransaction(spendTx)
  1667  		}
  1668  
  1669  		// Add the duplicate transactions (3rd and 4th).
  1670  		b.AddTransaction(b.Transactions[2])
  1671  		b.AddTransaction(b.Transactions[3])
  1672  	})
  1673  	g.assertTipBlockNumTxns(8)
  1674  	rejected(blockchain.ErrDuplicateTx)
  1675  
  1676  	// ---------------------------------------------------------------------
  1677  	// Invalid transaction type tests.
  1678  	// ---------------------------------------------------------------------
  1679  
  1680  	// Create block with a transaction that tries to spend from an index
  1681  	// that is out of range from an otherwise valid and existing tx.
  1682  	//
  1683  	//   ... -> b57(16)
  1684  	//                 \-> b58(17)
  1685  	g.setTip("b57")
  1686  	g.nextBlock("b58", outs[17], func(b *wire.MsgBlock) {
  1687  		b.Transactions[1].TxIn[0].PreviousOutPoint.Index = 42
  1688  	})
  1689  	rejected(blockchain.ErrMissingTxOut)
  1690  
  1691  	// Create block with transaction that pays more than its inputs.
  1692  	//
  1693  	//   ... -> b57(16)
  1694  	//                 \-> b59(17)
  1695  	g.setTip("b57")
  1696  	g.nextBlock("b59", outs[17], func(b *wire.MsgBlock) {
  1697  		b.Transactions[1].TxOut[0].Value = int64(outs[17].amount) + 1
  1698  	})
  1699  	rejected(blockchain.ErrSpendTooHigh)
  1700  
  1701  	// ---------------------------------------------------------------------
  1702  	// BIP0030 tests.
  1703  	// ---------------------------------------------------------------------
  1704  
  1705  	// Create a good block to reset the chain to a stable base.
  1706  	//
  1707  	//   ... -> b57(16) -> b60(17)
  1708  	g.setTip("b57")
  1709  	g.nextBlock("b60", outs[17])
  1710  	accepted()
  1711  
  1712  	// Create block that has a tx with the same hash as an existing tx that
  1713  	// has not been fully spent.
  1714  	//
  1715  	//   ... -> b60(17)
  1716  	//                 \-> b61(18)
  1717  	g.nextBlock("b61", outs[18], func(b *wire.MsgBlock) {
  1718  		// Duplicate the coinbase of the parent block to force the
  1719  		// condition.
  1720  		parent := g.blocks[b.Header.PrevBlock]
  1721  		b.Transactions[0] = parent.Transactions[0]
  1722  	})
  1723  	rejected(blockchain.ErrOverwriteTx)
  1724  
  1725  	// ---------------------------------------------------------------------
  1726  	// Blocks with non-final transaction tests.
  1727  	// ---------------------------------------------------------------------
  1728  
  1729  	// Create block that contains a non-final non-coinbase transaction.
  1730  	//
  1731  	//   ... -> b60(17)
  1732  	//                 \-> b62(18)
  1733  	g.setTip("b60")
  1734  	g.nextBlock("b62", outs[18], func(b *wire.MsgBlock) {
  1735  		// A non-final transaction must have at least one input with a
  1736  		// non-final sequence number in addition to a non-final lock
  1737  		// time.
  1738  		b.Transactions[1].LockTime = 0xffffffff
  1739  		b.Transactions[1].TxIn[0].Sequence = 0
  1740  	})
  1741  	rejected(blockchain.ErrUnfinalizedTx)
  1742  
  1743  	// Create block that contains a non-final coinbase transaction.
  1744  	//
  1745  	//   ... -> b60(17)
  1746  	//                 \-> b63(18)
  1747  	g.setTip("b60")
  1748  	g.nextBlock("b63", outs[18], func(b *wire.MsgBlock) {
  1749  		// A non-final transaction must have at least one input with a
  1750  		// non-final sequence number in addition to a non-final lock
  1751  		// time.
  1752  		b.Transactions[0].LockTime = 0xffffffff
  1753  		b.Transactions[0].TxIn[0].Sequence = 0
  1754  	})
  1755  	rejected(blockchain.ErrUnfinalizedTx)
  1756  
  1757  	// ---------------------------------------------------------------------
  1758  	// Non-canonical variable-length integer tests.
  1759  	// ---------------------------------------------------------------------
  1760  
  1761  	// Create a max size block with the variable-length integer for the
  1762  	// number of transactions replaced with a larger non-canonical version
  1763  	// that causes the block size to exceed the max allowed size.  Then,
  1764  	// create another block that is identical except with the canonical
  1765  	// encoding and ensure it is accepted.  The intent is to verify the
  1766  	// implementation does not reject the second block, which will have the
  1767  	// same hash, due to the first one already being rejected.
  1768  	//
  1769  	//   ... -> b60(17) -> b64(18)
  1770  	//                 \-> b64a(18)
  1771  	g.setTip("b60")
  1772  	b64a := g.nextBlock("b64a", outs[18], func(b *wire.MsgBlock) {
  1773  		bytesToMaxSize := maxBlockSize - b.SerializeSize() - 3
  1774  		sizePadScript := repeatOpcode(0x00, bytesToMaxSize)
  1775  		replaceSpendScript(sizePadScript)(b)
  1776  	})
  1777  	g.assertTipNonCanonicalBlockSize(maxBlockSize + 8)
  1778  	rejectedNonCanonical()
  1779  
  1780  	g.setTip("b60")
  1781  	b64 := g.nextBlock("b64", outs[18], func(b *wire.MsgBlock) {
  1782  		*b = cloneBlock(b64a)
  1783  	})
  1784  	// Since the two blocks have the same hash and the generator state now
  1785  	// has b64a associated with the hash, manually remove b64a, replace it
  1786  	// with b64, and then reset the tip to it.
  1787  	g.updateBlockState("b64a", b64a.BlockHash(), "b64", b64)
  1788  	g.setTip("b64")
  1789  	g.assertTipBlockHash(b64a.BlockHash())
  1790  	g.assertTipBlockSize(maxBlockSize)
  1791  	accepted()
  1792  
  1793  	// ---------------------------------------------------------------------
  1794  	// Same block transaction spend tests.
  1795  	// ---------------------------------------------------------------------
  1796  
  1797  	// Create block that spends an output created earlier in the same block.
  1798  	//
  1799  	//   ... b64(18) -> b65(19)
  1800  	g.setTip("b64")
  1801  	g.nextBlock("b65", outs[19], func(b *wire.MsgBlock) {
  1802  		tx3 := createSpendTxForTx(b.Transactions[1], lowFee)
  1803  		b.AddTransaction(tx3)
  1804  	})
  1805  	accepted()
  1806  
  1807  	// Create block that spends an output created later in the same block.
  1808  	//
  1809  	//   ... -> b65(19)
  1810  	//                 \-> b66(20)
  1811  	g.nextBlock("b66", nil, func(b *wire.MsgBlock) {
  1812  		tx2 := createSpendTx(outs[20], lowFee)
  1813  		tx3 := createSpendTxForTx(tx2, lowFee)
  1814  		b.AddTransaction(tx3)
  1815  		b.AddTransaction(tx2)
  1816  	})
  1817  	rejected(blockchain.ErrMissingTxOut)
  1818  
  1819  	// Create block that double spends a transaction created in the same
  1820  	// block.
  1821  	//
  1822  	//   ... -> b65(19)
  1823  	//                 \-> b67(20)
  1824  	g.setTip("b65")
  1825  	g.nextBlock("b67", outs[20], func(b *wire.MsgBlock) {
  1826  		tx2 := b.Transactions[1]
  1827  		tx3 := createSpendTxForTx(tx2, lowFee)
  1828  		tx4 := createSpendTxForTx(tx2, lowFee)
  1829  		b.AddTransaction(tx3)
  1830  		b.AddTransaction(tx4)
  1831  	})
  1832  	rejected(blockchain.ErrMissingTxOut)
  1833  
  1834  	// ---------------------------------------------------------------------
  1835  	// Extra subsidy tests.
  1836  	// ---------------------------------------------------------------------
  1837  
  1838  	// Create block that pays 10 extra to the coinbase and a tx that only
  1839  	// pays 9 fee.
  1840  	//
  1841  	//   ... -> b65(19)
  1842  	//                 \-> b68(20)
  1843  	g.setTip("b65")
  1844  	g.nextBlock("b68", outs[20], additionalCoinbase(10), additionalSpendFee(9))
  1845  	rejected(blockchain.ErrBadCoinbaseValue)
  1846  
  1847  	// Create block that pays 10 extra to the coinbase and a tx that pays
  1848  	// the extra 10 fee.
  1849  	//
  1850  	//   ... -> b65(19) -> b69(20)
  1851  	g.setTip("b65")
  1852  	g.nextBlock("b69", outs[20], additionalCoinbase(10), additionalSpendFee(10))
  1853  	accepted()
  1854  
  1855  	// ---------------------------------------------------------------------
  1856  	// More signature operations counting tests.
  1857  	//
  1858  	// The next several tests ensure signature operations are counted before
  1859  	// script elements that cause parse failure while those after are
  1860  	// ignored and that signature operations after script elements that
  1861  	// successfully parse even if that element will fail at run-time are
  1862  	// counted.
  1863  	// ---------------------------------------------------------------------
  1864  
  1865  	// Create block with more than max allowed signature operations such
  1866  	// that the signature operation that pushes it over the limit is after
  1867  	// a push data with a script element size that is larger than the max
  1868  	// allowed size when executed.  The block must be rejected because the
  1869  	// signature operation after the script element must be counted since
  1870  	// the script parses validly.
  1871  	//
  1872  	// The script generated consists of the following form:
  1873  	//
  1874  	//  Comment assumptions:
  1875  	//    maxBlockSigOps = 20000
  1876  	//    maxScriptElementSize = 20000
  1877  	//
  1878  	//  [0-19999]    : OP_CHECKSIG
  1879  	//  [20000]      : OP_PUSHDATA4
  1880  	//  [20001-20004]: 521 (little-endian encoded maxScriptElementSize+1)
  1881  	//  [20005-20525]: too large script element
  1882  	//  [20526]      : OP_CHECKSIG (goes over the limit)
  1883  	//
  1884  	//   ... -> b69(20)
  1885  	//                 \-> b70(21)
  1886  	scriptSize := maxBlockSigOps + 5 + (maxScriptElementSize + 1) + 1
  1887  	tooManySigOps = repeatOpcode(txscript.OP_CHECKSIG, scriptSize)
  1888  	tooManySigOps[maxBlockSigOps] = txscript.OP_PUSHDATA4
  1889  	binary.LittleEndian.PutUint32(tooManySigOps[maxBlockSigOps+1:],
  1890  		maxScriptElementSize+1)
  1891  	g.nextBlock("b70", outs[21], replaceSpendScript(tooManySigOps))
  1892  	g.assertTipBlockSigOpsCount(maxBlockSigOps + 1)
  1893  	rejected(blockchain.ErrTooManySigOps)
  1894  
  1895  	// Create block with more than max allowed signature operations such
  1896  	// that the signature operation that pushes it over the limit is before
  1897  	// an invalid push data that claims a large amount of data even though
  1898  	// that much data is not provided.
  1899  	//
  1900  	//   ... -> b69(20)
  1901  	//                 \-> b71(21)
  1902  	g.setTip("b69")
  1903  	scriptSize = maxBlockSigOps + 5 + maxScriptElementSize + 1
  1904  	tooManySigOps = repeatOpcode(txscript.OP_CHECKSIG, scriptSize)
  1905  	tooManySigOps[maxBlockSigOps+1] = txscript.OP_PUSHDATA4
  1906  	binary.LittleEndian.PutUint32(tooManySigOps[maxBlockSigOps+2:], 0xffffffff)
  1907  	g.nextBlock("b71", outs[21], replaceSpendScript(tooManySigOps))
  1908  	g.assertTipBlockSigOpsCount(maxBlockSigOps + 1)
  1909  	rejected(blockchain.ErrTooManySigOps)
  1910  
  1911  	// Create block with the max allowed signature operations such that all
  1912  	// counted signature operations are before an invalid push data that
  1913  	// claims a large amount of data even though that much data is not
  1914  	// provided.  The pushed data itself consists of OP_CHECKSIG so the
  1915  	// block would be rejected if any of them were counted.
  1916  	//
  1917  	//   ... -> b69(20) -> b72(21)
  1918  	g.setTip("b69")
  1919  	scriptSize = maxBlockSigOps + 5 + maxScriptElementSize
  1920  	manySigOps = repeatOpcode(txscript.OP_CHECKSIG, scriptSize)
  1921  	manySigOps[maxBlockSigOps] = txscript.OP_PUSHDATA4
  1922  	binary.LittleEndian.PutUint32(manySigOps[maxBlockSigOps+1:], 0xffffffff)
  1923  	g.nextBlock("b72", outs[21], replaceSpendScript(manySigOps))
  1924  	g.assertTipBlockSigOpsCount(maxBlockSigOps)
  1925  	accepted()
  1926  
  1927  	// Create block with the max allowed signature operations such that all
  1928  	// counted signature operations are before an invalid push data that
  1929  	// contains OP_CHECKSIG in the number of bytes to push.  The block would
  1930  	// be rejected if any of them were counted.
  1931  	//
  1932  	//   ... -> b72(21) -> b73(22)
  1933  	scriptSize = maxBlockSigOps + 5 + (maxScriptElementSize + 1)
  1934  	manySigOps = repeatOpcode(txscript.OP_CHECKSIG, scriptSize)
  1935  	manySigOps[maxBlockSigOps] = txscript.OP_PUSHDATA4
  1936  	g.nextBlock("b73", outs[22], replaceSpendScript(manySigOps))
  1937  	g.assertTipBlockSigOpsCount(maxBlockSigOps)
  1938  	accepted()
  1939  
  1940  	// ---------------------------------------------------------------------
  1941  	// Dead execution path tests.
  1942  	// ---------------------------------------------------------------------
  1943  
  1944  	// Create block with an invalid opcode in a dead execution path.
  1945  	//
  1946  	//   ... -> b73(22) -> b74(23)
  1947  	script := []byte{txscript.OP_IF, txscript.OP_INVALIDOPCODE,
  1948  		txscript.OP_ELSE, txscript.OP_TRUE, txscript.OP_ENDIF}
  1949  	g.nextBlock("b74", outs[23], replaceSpendScript(script), func(b *wire.MsgBlock) {
  1950  		tx2 := b.Transactions[1]
  1951  		tx3 := createSpendTxForTx(tx2, lowFee)
  1952  		tx3.TxIn[0].SignatureScript = []byte{txscript.OP_FALSE}
  1953  		b.AddTransaction(tx3)
  1954  	})
  1955  	accepted()
  1956  
  1957  	// ---------------------------------------------------------------------
  1958  	// Various OP_RETURN tests.
  1959  	// ---------------------------------------------------------------------
  1960  
  1961  	// Create a block that has multiple transactions each with a single
  1962  	// OP_RETURN output.
  1963  	//
  1964  	//   ... -> b74(23) -> b75(24)
  1965  	g.nextBlock("b75", outs[24], func(b *wire.MsgBlock) {
  1966  		// Add 4 outputs to the spending transaction that are spent
  1967  		// below.
  1968  		const numAdditionalOutputs = 4
  1969  		const zeroCoin = int64(0)
  1970  		spendTx := b.Transactions[1]
  1971  		for i := 0; i < numAdditionalOutputs; i++ {
  1972  			spendTx.AddTxOut(wire.NewTxOut(zeroCoin, opTrueScript))
  1973  		}
  1974  
  1975  		// Add transactions spending from the outputs added above that
  1976  		// each contain an OP_RETURN output.
  1977  		//
  1978  		// NOTE: The createSpendTx func adds the OP_RETURN output.
  1979  		zeroFee := btcutil.Amount(0)
  1980  		for i := uint32(0); i < numAdditionalOutputs; i++ {
  1981  			spend := makeSpendableOut(b, 1, i+2)
  1982  			tx := createSpendTx(&spend, zeroFee)
  1983  			b.AddTransaction(tx)
  1984  		}
  1985  	})
  1986  	g.assertTipBlockNumTxns(6)
  1987  	g.assertTipBlockTxOutOpReturn(5, 1)
  1988  	b75OpReturnOut := makeSpendableOut(g.tip, 5, 1)
  1989  	accepted()
  1990  
  1991  	// Reorg to a side chain that does not contain the OP_RETURNs.
  1992  	//
  1993  	//   ... -> b74(23) -> b75(24)
  1994  	//                 \-> b76(24) -> b77(25)
  1995  	g.setTip("b74")
  1996  	g.nextBlock("b76", outs[24])
  1997  	acceptedToSideChainWithExpectedTip("b75")
  1998  
  1999  	g.nextBlock("b77", outs[25])
  2000  	accepted()
  2001  
  2002  	// Reorg back to the original chain that contains the OP_RETURNs.
  2003  	//
  2004  	//   ... -> b74(23) -> b75(24) -> b78(25) -> b79(26)
  2005  	//                 \-> b76(24) -> b77(25)
  2006  	g.setTip("b75")
  2007  	g.nextBlock("b78", outs[25])
  2008  	acceptedToSideChainWithExpectedTip("b77")
  2009  
  2010  	g.nextBlock("b79", outs[26])
  2011  	accepted()
  2012  
  2013  	// Create a block that spends an OP_RETURN.
  2014  	//
  2015  	//   ... -> b74(23) -> b75(24) -> b78(25) -> b79(26)
  2016  	//                 \-> b76(24) -> b77(25)           \-> b80(b75.tx[5].out[1])
  2017  	//
  2018  	// An OP_RETURN output doesn't have any value and the default behavior
  2019  	// of nextBlock is to assign a fee of one, so increment the amount here
  2020  	// to effective negate that behavior.
  2021  	b75OpReturnOut.amount++
  2022  	g.nextBlock("b80", &b75OpReturnOut)
  2023  	rejected(blockchain.ErrMissingTxOut)
  2024  
  2025  	// Create a block that has a transaction with multiple OP_RETURNs.  Even
  2026  	// though it's not considered a standard transaction, it is still valid
  2027  	// by the consensus rules.
  2028  	//
  2029  	//   ... -> b79(26) -> b81(27)
  2030  	//
  2031  	g.setTip("b79")
  2032  	g.nextBlock("b81", outs[27], func(b *wire.MsgBlock) {
  2033  		const numAdditionalOutputs = 4
  2034  		const zeroCoin = int64(0)
  2035  		spendTx := b.Transactions[1]
  2036  		for i := 0; i < numAdditionalOutputs; i++ {
  2037  			opRetScript := uniqueOpReturnScript()
  2038  			spendTx.AddTxOut(wire.NewTxOut(zeroCoin, opRetScript))
  2039  		}
  2040  	})
  2041  	for i := uint32(2); i < 6; i++ {
  2042  		g.assertTipBlockTxOutOpReturn(1, i)
  2043  	}
  2044  	accepted()
  2045  
  2046  	// ---------------------------------------------------------------------
  2047  	// Large block re-org test.
  2048  	// ---------------------------------------------------------------------
  2049  
  2050  	if !includeLargeReorg {
  2051  		return tests, nil
  2052  	}
  2053  
  2054  	// Ensure the tip the re-org test builds on is the best chain tip.
  2055  	//
  2056  	//   ... -> b81(27) -> ...
  2057  	g.setTip("b81")
  2058  
  2059  	// Collect all of the spendable coinbase outputs from the previous
  2060  	// collection point up to the current tip.
  2061  	g.saveSpendableCoinbaseOuts()
  2062  	spendableOutOffset := g.tipHeight - int32(coinbaseMaturity)
  2063  
  2064  	// Extend the main chain by a large number of max size blocks.
  2065  	//
  2066  	//   ... -> br0 -> br1 -> ... -> br#
  2067  	testInstances = nil
  2068  	reorgSpend := *outs[spendableOutOffset]
  2069  	reorgStartBlockName := g.tipName
  2070  	chain1TipName := g.tipName
  2071  	for i := int32(0); i < numLargeReorgBlocks; i++ {
  2072  		chain1TipName = fmt.Sprintf("br%d", i)
  2073  		g.nextBlock(chain1TipName, &reorgSpend, func(b *wire.MsgBlock) {
  2074  			bytesToMaxSize := maxBlockSize - b.SerializeSize() - 3
  2075  			sizePadScript := repeatOpcode(0x00, bytesToMaxSize)
  2076  			replaceSpendScript(sizePadScript)(b)
  2077  		})
  2078  		g.assertTipBlockSize(maxBlockSize)
  2079  		g.saveTipCoinbaseOut()
  2080  		testInstances = append(testInstances, acceptBlock(g.tipName,
  2081  			g.tip, true, false))
  2082  
  2083  		// Use the next available spendable output.  First use up any
  2084  		// remaining spendable outputs that were already popped into the
  2085  		// outs slice, then just pop them from the stack.
  2086  		if spendableOutOffset+1+i < int32(len(outs)) {
  2087  			reorgSpend = *outs[spendableOutOffset+1+i]
  2088  		} else {
  2089  			reorgSpend = g.oldestCoinbaseOut()
  2090  		}
  2091  	}
  2092  	tests = append(tests, testInstances)
  2093  
  2094  	// Create a side chain that has the same length.
  2095  	//
  2096  	//   ... -> br0    -> ... -> br#
  2097  	//      \-> bralt0 -> ... -> bralt#
  2098  	g.setTip(reorgStartBlockName)
  2099  	testInstances = nil
  2100  	chain2TipName := g.tipName
  2101  	for i := uint16(0); i < numLargeReorgBlocks; i++ {
  2102  		chain2TipName = fmt.Sprintf("bralt%d", i)
  2103  		g.nextBlock(chain2TipName, nil)
  2104  		testInstances = append(testInstances, acceptBlock(g.tipName,
  2105  			g.tip, false, false))
  2106  	}
  2107  	testInstances = append(testInstances, expectTipBlock(chain1TipName,
  2108  		g.blocksByName[chain1TipName]))
  2109  	tests = append(tests, testInstances)
  2110  
  2111  	// Extend the side chain by one to force the large reorg.
  2112  	//
  2113  	//   ... -> bralt0 -> ... -> bralt# -> bralt#+1
  2114  	//      \-> br0    -> ... -> br#
  2115  	g.nextBlock(fmt.Sprintf("bralt%d", g.tipHeight+1), nil)
  2116  	chain2TipName = g.tipName
  2117  	accepted()
  2118  
  2119  	// Extend the first chain by two to force a large reorg back to it.
  2120  	//
  2121  	//   ... -> br0    -> ... -> br#    -> br#+1    -> br#+2
  2122  	//      \-> bralt0 -> ... -> bralt# -> bralt#+1
  2123  	g.setTip(chain1TipName)
  2124  	g.nextBlock(fmt.Sprintf("br%d", g.tipHeight+1), nil)
  2125  	chain1TipName = g.tipName
  2126  	acceptedToSideChainWithExpectedTip(chain2TipName)
  2127  
  2128  	g.nextBlock(fmt.Sprintf("br%d", g.tipHeight+2), nil)
  2129  	chain1TipName = g.tipName
  2130  	accepted()
  2131  
  2132  	return tests, nil
  2133  }