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