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