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