github.com/devfans/go-ethereum@v1.5.10-0.20170326212234-7419d0c38291/core/chain_makers.go (about)

     1  // Copyright 2015 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package core
    18  
    19  import (
    20  	"fmt"
    21  	"math/big"
    22  
    23  	"github.com/ethereum/go-ethereum/common"
    24  	"github.com/ethereum/go-ethereum/core/state"
    25  	"github.com/ethereum/go-ethereum/core/types"
    26  	"github.com/ethereum/go-ethereum/core/vm"
    27  	"github.com/ethereum/go-ethereum/ethdb"
    28  	"github.com/ethereum/go-ethereum/event"
    29  	"github.com/ethereum/go-ethereum/params"
    30  	"github.com/ethereum/go-ethereum/pow"
    31  )
    32  
    33  // So we can deterministically seed different blockchains
    34  var (
    35  	canonicalSeed = 1
    36  	forkSeed      = 2
    37  )
    38  
    39  // BlockGen creates blocks for testing.
    40  // See GenerateChain for a detailed explanation.
    41  type BlockGen struct {
    42  	i       int
    43  	parent  *types.Block
    44  	chain   []*types.Block
    45  	header  *types.Header
    46  	statedb *state.StateDB
    47  
    48  	gasPool  *GasPool
    49  	txs      []*types.Transaction
    50  	receipts []*types.Receipt
    51  	uncles   []*types.Header
    52  
    53  	config *params.ChainConfig
    54  }
    55  
    56  // SetCoinbase sets the coinbase of the generated block.
    57  // It can be called at most once.
    58  func (b *BlockGen) SetCoinbase(addr common.Address) {
    59  	if b.gasPool != nil {
    60  		if len(b.txs) > 0 {
    61  			panic("coinbase must be set before adding transactions")
    62  		}
    63  		panic("coinbase can only be set once")
    64  	}
    65  	b.header.Coinbase = addr
    66  	b.gasPool = new(GasPool).AddGas(b.header.GasLimit)
    67  }
    68  
    69  // SetExtra sets the extra data field of the generated block.
    70  func (b *BlockGen) SetExtra(data []byte) {
    71  	b.header.Extra = data
    72  }
    73  
    74  // AddTx adds a transaction to the generated block. If no coinbase has
    75  // been set, the block's coinbase is set to the zero address.
    76  //
    77  // AddTx panics if the transaction cannot be executed. In addition to
    78  // the protocol-imposed limitations (gas limit, etc.), there are some
    79  // further limitations on the content of transactions that can be
    80  // added. Notably, contract code relying on the BLOCKHASH instruction
    81  // will panic during execution.
    82  func (b *BlockGen) AddTx(tx *types.Transaction) {
    83  	if b.gasPool == nil {
    84  		b.SetCoinbase(common.Address{})
    85  	}
    86  	b.statedb.StartRecord(tx.Hash(), common.Hash{}, len(b.txs))
    87  	receipt, _, err := ApplyTransaction(b.config, nil, b.gasPool, b.statedb, b.header, tx, b.header.GasUsed, vm.Config{})
    88  	if err != nil {
    89  		panic(err)
    90  	}
    91  	b.txs = append(b.txs, tx)
    92  	b.receipts = append(b.receipts, receipt)
    93  }
    94  
    95  // Number returns the block number of the block being generated.
    96  func (b *BlockGen) Number() *big.Int {
    97  	return new(big.Int).Set(b.header.Number)
    98  }
    99  
   100  // AddUncheckedReceipts forcefully adds a receipts to the block without a
   101  // backing transaction.
   102  //
   103  // AddUncheckedReceipts will cause consensus failures when used during real
   104  // chain processing. This is best used in conjunction with raw block insertion.
   105  func (b *BlockGen) AddUncheckedReceipt(receipt *types.Receipt) {
   106  	b.receipts = append(b.receipts, receipt)
   107  }
   108  
   109  // TxNonce returns the next valid transaction nonce for the
   110  // account at addr. It panics if the account does not exist.
   111  func (b *BlockGen) TxNonce(addr common.Address) uint64 {
   112  	if !b.statedb.Exist(addr) {
   113  		panic("account does not exist")
   114  	}
   115  	return b.statedb.GetNonce(addr)
   116  }
   117  
   118  // AddUncle adds an uncle header to the generated block.
   119  func (b *BlockGen) AddUncle(h *types.Header) {
   120  	b.uncles = append(b.uncles, h)
   121  }
   122  
   123  // PrevBlock returns a previously generated block by number. It panics if
   124  // num is greater or equal to the number of the block being generated.
   125  // For index -1, PrevBlock returns the parent block given to GenerateChain.
   126  func (b *BlockGen) PrevBlock(index int) *types.Block {
   127  	if index >= b.i {
   128  		panic("block index out of range")
   129  	}
   130  	if index == -1 {
   131  		return b.parent
   132  	}
   133  	return b.chain[index]
   134  }
   135  
   136  // OffsetTime modifies the time instance of a block, implicitly changing its
   137  // associated difficulty. It's useful to test scenarios where forking is not
   138  // tied to chain length directly.
   139  func (b *BlockGen) OffsetTime(seconds int64) {
   140  	b.header.Time.Add(b.header.Time, new(big.Int).SetInt64(seconds))
   141  	if b.header.Time.Cmp(b.parent.Header().Time) <= 0 {
   142  		panic("block time out of range")
   143  	}
   144  	b.header.Difficulty = CalcDifficulty(b.config, b.header.Time.Uint64(), b.parent.Time().Uint64(), b.parent.Number(), b.parent.Difficulty())
   145  }
   146  
   147  // GenerateChain creates a chain of n blocks. The first block's
   148  // parent will be the provided parent. db is used to store
   149  // intermediate states and should contain the parent's state trie.
   150  //
   151  // The generator function is called with a new block generator for
   152  // every block. Any transactions and uncles added to the generator
   153  // become part of the block. If gen is nil, the blocks will be empty
   154  // and their coinbase will be the zero address.
   155  //
   156  // Blocks created by GenerateChain do not contain valid proof of work
   157  // values. Inserting them into BlockChain requires use of FakePow or
   158  // a similar non-validating proof of work implementation.
   159  func GenerateChain(config *params.ChainConfig, parent *types.Block, db ethdb.Database, n int, gen func(int, *BlockGen)) ([]*types.Block, []types.Receipts) {
   160  	if config == nil {
   161  		config = params.TestChainConfig
   162  	}
   163  	blocks, receipts := make(types.Blocks, n), make([]types.Receipts, n)
   164  	genblock := func(i int, h *types.Header, statedb *state.StateDB) (*types.Block, types.Receipts) {
   165  		b := &BlockGen{parent: parent, i: i, chain: blocks, header: h, statedb: statedb, config: config}
   166  		// Mutate the state and block according to any hard-fork specs
   167  		if daoBlock := config.DAOForkBlock; daoBlock != nil {
   168  			limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange)
   169  			if h.Number.Cmp(daoBlock) >= 0 && h.Number.Cmp(limit) < 0 {
   170  				if config.DAOForkSupport {
   171  					h.Extra = common.CopyBytes(params.DAOForkBlockExtra)
   172  				}
   173  			}
   174  		}
   175  		if config.DAOForkSupport && config.DAOForkBlock != nil && config.DAOForkBlock.Cmp(h.Number) == 0 {
   176  			ApplyDAOHardFork(statedb)
   177  		}
   178  		// Execute any user modifications to the block and finalize it
   179  		if gen != nil {
   180  			gen(i, b)
   181  		}
   182  		AccumulateRewards(statedb, h, b.uncles)
   183  		root, err := statedb.Commit(config.IsEIP158(h.Number))
   184  		if err != nil {
   185  			panic(fmt.Sprintf("state write error: %v", err))
   186  		}
   187  		h.Root = root
   188  		return types.NewBlock(h, b.txs, b.uncles, b.receipts), b.receipts
   189  	}
   190  	for i := 0; i < n; i++ {
   191  		statedb, err := state.New(parent.Root(), db)
   192  		if err != nil {
   193  			panic(err)
   194  		}
   195  		header := makeHeader(config, parent, statedb)
   196  		block, receipt := genblock(i, header, statedb)
   197  		blocks[i] = block
   198  		receipts[i] = receipt
   199  		parent = block
   200  	}
   201  	return blocks, receipts
   202  }
   203  
   204  func makeHeader(config *params.ChainConfig, parent *types.Block, state *state.StateDB) *types.Header {
   205  	var time *big.Int
   206  	if parent.Time() == nil {
   207  		time = big.NewInt(10)
   208  	} else {
   209  		time = new(big.Int).Add(parent.Time(), big.NewInt(10)) // block time is fixed at 10 seconds
   210  	}
   211  	return &types.Header{
   212  		Root:       state.IntermediateRoot(config.IsEIP158(parent.Number())),
   213  		ParentHash: parent.Hash(),
   214  		Coinbase:   parent.Coinbase(),
   215  		Difficulty: CalcDifficulty(config, time.Uint64(), new(big.Int).Sub(time, big.NewInt(10)).Uint64(), parent.Number(), parent.Difficulty()),
   216  		GasLimit:   CalcGasLimit(parent),
   217  		GasUsed:    new(big.Int),
   218  		Number:     new(big.Int).Add(parent.Number(), common.Big1),
   219  		Time:       time,
   220  	}
   221  }
   222  
   223  // newCanonical creates a chain database, and injects a deterministic canonical
   224  // chain. Depending on the full flag, if creates either a full block chain or a
   225  // header only chain.
   226  func newCanonical(n int, full bool) (ethdb.Database, *BlockChain, error) {
   227  	// Initialize a fresh chain with only a genesis block
   228  	gspec := new(Genesis)
   229  	db, _ := ethdb.NewMemDatabase()
   230  	genesis := gspec.MustCommit(db)
   231  
   232  	blockchain, _ := NewBlockChain(db, params.AllProtocolChanges, pow.FakePow{}, new(event.TypeMux), vm.Config{})
   233  	// Create and inject the requested chain
   234  	if n == 0 {
   235  		return db, blockchain, nil
   236  	}
   237  	if full {
   238  		// Full block-chain requested
   239  		blocks := makeBlockChain(genesis, n, db, canonicalSeed)
   240  		_, err := blockchain.InsertChain(blocks)
   241  		return db, blockchain, err
   242  	}
   243  	// Header-only chain requested
   244  	headers := makeHeaderChain(genesis.Header(), n, db, canonicalSeed)
   245  	_, err := blockchain.InsertHeaderChain(headers, 1)
   246  	return db, blockchain, err
   247  }
   248  
   249  // makeHeaderChain creates a deterministic chain of headers rooted at parent.
   250  func makeHeaderChain(parent *types.Header, n int, db ethdb.Database, seed int) []*types.Header {
   251  	blocks := makeBlockChain(types.NewBlockWithHeader(parent), n, db, seed)
   252  	headers := make([]*types.Header, len(blocks))
   253  	for i, block := range blocks {
   254  		headers[i] = block.Header()
   255  	}
   256  	return headers
   257  }
   258  
   259  // makeBlockChain creates a deterministic chain of blocks rooted at parent.
   260  func makeBlockChain(parent *types.Block, n int, db ethdb.Database, seed int) []*types.Block {
   261  	blocks, _ := GenerateChain(params.TestChainConfig, parent, db, n, func(i int, b *BlockGen) {
   262  		b.SetCoinbase(common.Address{0: byte(seed), 19: byte(i)})
   263  	})
   264  	return blocks
   265  }