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