github.com/bcnmy/go-ethereum@v1.10.27/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/consensus"
    25  	"github.com/ethereum/go-ethereum/consensus/misc"
    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  // 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  	// The uncle will have the same timestamp and auto-generated difficulty
   159  	h.Time = b.header.Time
   160  
   161  	var parent *types.Header
   162  	for i := b.i - 1; i >= 0; i-- {
   163  		if b.chain[i].Hash() == h.ParentHash {
   164  			parent = b.chain[i].Header()
   165  			break
   166  		}
   167  	}
   168  	chainreader := &fakeChainReader{config: b.config}
   169  	h.Difficulty = b.engine.CalcDifficulty(chainreader, b.header.Time, parent)
   170  
   171  	// The gas limit and price should be derived from the parent
   172  	h.GasLimit = parent.GasLimit
   173  	if b.config.IsLondon(h.Number) {
   174  		h.BaseFee = misc.CalcBaseFee(b.config, parent)
   175  		if !b.config.IsLondon(parent.Number) {
   176  			parentGasLimit := parent.GasLimit * params.ElasticityMultiplier
   177  			h.GasLimit = CalcGasLimit(parentGasLimit, parentGasLimit)
   178  		}
   179  	}
   180  	b.uncles = append(b.uncles, h)
   181  }
   182  
   183  // PrevBlock returns a previously generated block by number. It panics if
   184  // num is greater or equal to the number of the block being generated.
   185  // For index -1, PrevBlock returns the parent block given to GenerateChain.
   186  func (b *BlockGen) PrevBlock(index int) *types.Block {
   187  	if index >= b.i {
   188  		panic(fmt.Errorf("block index %d out of range (%d,%d)", index, -1, b.i))
   189  	}
   190  	if index == -1 {
   191  		return b.parent
   192  	}
   193  	return b.chain[index]
   194  }
   195  
   196  // OffsetTime modifies the time instance of a block, implicitly changing its
   197  // associated difficulty. It's useful to test scenarios where forking is not
   198  // tied to chain length directly.
   199  func (b *BlockGen) OffsetTime(seconds int64) {
   200  	b.header.Time += uint64(seconds)
   201  	if b.header.Time <= b.parent.Header().Time {
   202  		panic("block time out of range")
   203  	}
   204  	chainreader := &fakeChainReader{config: b.config}
   205  	b.header.Difficulty = b.engine.CalcDifficulty(chainreader, b.header.Time, b.parent.Header())
   206  }
   207  
   208  // GenerateChain creates a chain of n blocks. The first block's
   209  // parent will be the provided parent. db is used to store
   210  // intermediate states and should contain the parent's state trie.
   211  //
   212  // The generator function is called with a new block generator for
   213  // every block. Any transactions and uncles added to the generator
   214  // become part of the block. If gen is nil, the blocks will be empty
   215  // and their coinbase will be the zero address.
   216  //
   217  // Blocks created by GenerateChain do not contain valid proof of work
   218  // values. Inserting them into BlockChain requires use of FakePow or
   219  // a similar non-validating proof of work implementation.
   220  func GenerateChain(config *params.ChainConfig, parent *types.Block, engine consensus.Engine, db ethdb.Database, n int, gen func(int, *BlockGen)) ([]*types.Block, []types.Receipts) {
   221  	if config == nil {
   222  		config = params.TestChainConfig
   223  	}
   224  	blocks, receipts := make(types.Blocks, n), make([]types.Receipts, n)
   225  	chainreader := &fakeChainReader{config: config}
   226  	genblock := func(i int, parent *types.Block, statedb *state.StateDB) (*types.Block, types.Receipts) {
   227  		b := &BlockGen{i: i, chain: blocks, parent: parent, statedb: statedb, config: config, engine: engine}
   228  		b.header = makeHeader(chainreader, parent, statedb, b.engine)
   229  
   230  		// Set the difficulty for clique block. The chain maker doesn't have access
   231  		// to a chain, so the difficulty will be left unset (nil). Set it here to the
   232  		// correct value.
   233  		if b.header.Difficulty == nil {
   234  			if config.TerminalTotalDifficulty == nil {
   235  				// Clique chain
   236  				b.header.Difficulty = big.NewInt(2)
   237  			} else {
   238  				// Post-merge chain
   239  				b.header.Difficulty = big.NewInt(0)
   240  			}
   241  		}
   242  		// Mutate the state and block according to any hard-fork specs
   243  		if daoBlock := config.DAOForkBlock; daoBlock != nil {
   244  			limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange)
   245  			if b.header.Number.Cmp(daoBlock) >= 0 && b.header.Number.Cmp(limit) < 0 {
   246  				if config.DAOForkSupport {
   247  					b.header.Extra = common.CopyBytes(params.DAOForkBlockExtra)
   248  				}
   249  			}
   250  		}
   251  		if config.DAOForkSupport && config.DAOForkBlock != nil && config.DAOForkBlock.Cmp(b.header.Number) == 0 {
   252  			misc.ApplyDAOHardFork(statedb)
   253  		}
   254  		// Execute any user modifications to the block
   255  		if gen != nil {
   256  			gen(i, b)
   257  		}
   258  		if b.engine != nil {
   259  			// Finalize and seal the block
   260  			block, _ := b.engine.FinalizeAndAssemble(chainreader, b.header, statedb, b.txs, b.uncles, b.receipts)
   261  
   262  			// Write state changes to db
   263  			root, err := statedb.Commit(config.IsEIP158(b.header.Number))
   264  			if err != nil {
   265  				panic(fmt.Sprintf("state write error: %v", err))
   266  			}
   267  			if err := statedb.Database().TrieDB().Commit(root, false, nil); err != nil {
   268  				panic(fmt.Sprintf("trie write error: %v", err))
   269  			}
   270  			return block, b.receipts
   271  		}
   272  		return nil, nil
   273  	}
   274  	for i := 0; i < n; i++ {
   275  		statedb, err := state.New(parent.Root(), state.NewDatabase(db), nil)
   276  		if err != nil {
   277  			panic(err)
   278  		}
   279  		block, receipt := genblock(i, parent, statedb)
   280  		blocks[i] = block
   281  		receipts[i] = receipt
   282  		parent = block
   283  	}
   284  	return blocks, receipts
   285  }
   286  
   287  func makeHeader(chain consensus.ChainReader, parent *types.Block, state *state.StateDB, engine consensus.Engine) *types.Header {
   288  	var time uint64
   289  	if parent.Time() == 0 {
   290  		time = 10
   291  	} else {
   292  		time = parent.Time() + 10 // block time is fixed at 10 seconds
   293  	}
   294  	header := &types.Header{
   295  		Root:       state.IntermediateRoot(chain.Config().IsEIP158(parent.Number())),
   296  		ParentHash: parent.Hash(),
   297  		Coinbase:   parent.Coinbase(),
   298  		Difficulty: engine.CalcDifficulty(chain, time, &types.Header{
   299  			Number:     parent.Number(),
   300  			Time:       time - 10,
   301  			Difficulty: parent.Difficulty(),
   302  			UncleHash:  parent.UncleHash(),
   303  		}),
   304  		GasLimit: parent.GasLimit(),
   305  		Number:   new(big.Int).Add(parent.Number(), common.Big1),
   306  		Time:     time,
   307  	}
   308  	if chain.Config().IsLondon(header.Number) {
   309  		header.BaseFee = misc.CalcBaseFee(chain.Config(), parent.Header())
   310  		if !chain.Config().IsLondon(parent.Number()) {
   311  			parentGasLimit := parent.GasLimit() * params.ElasticityMultiplier
   312  			header.GasLimit = CalcGasLimit(parentGasLimit, parentGasLimit)
   313  		}
   314  	}
   315  	return header
   316  }
   317  
   318  // makeHeaderChain creates a deterministic chain of headers rooted at parent.
   319  func makeHeaderChain(parent *types.Header, n int, engine consensus.Engine, db ethdb.Database, seed int) []*types.Header {
   320  	blocks := makeBlockChain(types.NewBlockWithHeader(parent), n, engine, db, seed)
   321  	headers := make([]*types.Header, len(blocks))
   322  	for i, block := range blocks {
   323  		headers[i] = block.Header()
   324  	}
   325  	return headers
   326  }
   327  
   328  // makeBlockChain creates a deterministic chain of blocks rooted at parent.
   329  func makeBlockChain(parent *types.Block, n int, engine consensus.Engine, db ethdb.Database, seed int) []*types.Block {
   330  	blocks, _ := GenerateChain(params.TestChainConfig, parent, engine, db, n, func(i int, b *BlockGen) {
   331  		b.SetCoinbase(common.Address{0: byte(seed), 19: byte(i)})
   332  	})
   333  	return blocks
   334  }
   335  
   336  type fakeChainReader struct {
   337  	config *params.ChainConfig
   338  }
   339  
   340  // Config returns the chain configuration.
   341  func (cr *fakeChainReader) Config() *params.ChainConfig {
   342  	return cr.config
   343  }
   344  
   345  func (cr *fakeChainReader) CurrentHeader() *types.Header                            { return nil }
   346  func (cr *fakeChainReader) GetHeaderByNumber(number uint64) *types.Header           { return nil }
   347  func (cr *fakeChainReader) GetHeaderByHash(hash common.Hash) *types.Header          { return nil }
   348  func (cr *fakeChainReader) GetHeader(hash common.Hash, number uint64) *types.Header { return nil }
   349  func (cr *fakeChainReader) GetBlock(hash common.Hash, number uint64) *types.Block   { return nil }
   350  func (cr *fakeChainReader) GetTd(hash common.Hash, number uint64) *big.Int          { return nil }