github.com/codingfuture/orig-energi3@v0.8.4/core/chain_makers.go (about)

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