github.com/cryptotooltop/go-ethereum@v0.0.0-20231103184714-151d1922f3e5/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/scroll-tech/go-ethereum/common"
    24  	"github.com/scroll-tech/go-ethereum/consensus"
    25  	"github.com/scroll-tech/go-ethereum/consensus/misc"
    26  	"github.com/scroll-tech/go-ethereum/core/state"
    27  	"github.com/scroll-tech/go-ethereum/core/types"
    28  	"github.com/scroll-tech/go-ethereum/core/vm"
    29  	"github.com/scroll-tech/go-ethereum/ethdb"
    30  	"github.com/scroll-tech/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  	if b.header.BaseFee != nil {
   136  		return new(big.Int).Set(b.header.BaseFee)
   137  	} else {
   138  		return big.NewInt(0)
   139  	}
   140  }
   141  
   142  // AddUncheckedReceipt forcefully adds a receipts to the block without a
   143  // backing transaction.
   144  //
   145  // AddUncheckedReceipt will cause consensus failures when used during real
   146  // chain processing. This is best used in conjunction with raw block insertion.
   147  func (b *BlockGen) AddUncheckedReceipt(receipt *types.Receipt) {
   148  	b.receipts = append(b.receipts, receipt)
   149  }
   150  
   151  // TxNonce returns the next valid transaction nonce for the
   152  // account at addr. It panics if the account does not exist.
   153  func (b *BlockGen) TxNonce(addr common.Address) uint64 {
   154  	if !b.statedb.Exist(addr) {
   155  		panic("account does not exist")
   156  	}
   157  	return b.statedb.GetNonce(addr)
   158  }
   159  
   160  // AddUncle adds an uncle header to the generated block.
   161  func (b *BlockGen) AddUncle(h *types.Header) {
   162  	b.uncles = append(b.uncles, h)
   163  }
   164  
   165  // PrevBlock returns a previously generated block by number. It panics if
   166  // num is greater or equal to the number of the block being generated.
   167  // For index -1, PrevBlock returns the parent block given to GenerateChain.
   168  func (b *BlockGen) PrevBlock(index int) *types.Block {
   169  	if index >= b.i {
   170  		panic(fmt.Errorf("block index %d out of range (%d,%d)", index, -1, b.i))
   171  	}
   172  	if index == -1 {
   173  		return b.parent
   174  	}
   175  	return b.chain[index]
   176  }
   177  
   178  // OffsetTime modifies the time instance of a block, implicitly changing its
   179  // associated difficulty. It's useful to test scenarios where forking is not
   180  // tied to chain length directly.
   181  func (b *BlockGen) OffsetTime(seconds int64) {
   182  	b.header.Time += uint64(seconds)
   183  	if b.header.Time <= b.parent.Header().Time {
   184  		panic("block time out of range")
   185  	}
   186  	chainreader := &fakeChainReader{config: b.config}
   187  	b.header.Difficulty = b.engine.CalcDifficulty(chainreader, b.header.Time, b.parent.Header())
   188  }
   189  
   190  // GenerateChain creates a chain of n blocks. The first block's
   191  // parent will be the provided parent. db is used to store
   192  // intermediate states and should contain the parent's state trie.
   193  //
   194  // The generator function is called with a new block generator for
   195  // every block. Any transactions and uncles added to the generator
   196  // become part of the block. If gen is nil, the blocks will be empty
   197  // and their coinbase will be the zero address.
   198  //
   199  // Blocks created by GenerateChain do not contain valid proof of work
   200  // values. Inserting them into BlockChain requires use of FakePow or
   201  // a similar non-validating proof of work implementation.
   202  func GenerateChain(config *params.ChainConfig, parent *types.Block, engine consensus.Engine, db ethdb.Database, n int, gen func(int, *BlockGen)) ([]*types.Block, []types.Receipts) {
   203  	if config == nil {
   204  		config = params.TestChainConfig
   205  	}
   206  	blocks, receipts := make(types.Blocks, n), make([]types.Receipts, n)
   207  	chainreader := &fakeChainReader{config: config}
   208  	genblock := func(i int, parent *types.Block, statedb *state.StateDB) (*types.Block, types.Receipts) {
   209  		b := &BlockGen{i: i, chain: blocks, parent: parent, statedb: statedb, config: config, engine: engine}
   210  		b.header = makeHeader(chainreader, parent, statedb, b.engine)
   211  
   212  		// Mutate the state and block according to any hard-fork specs
   213  		if daoBlock := config.DAOForkBlock; daoBlock != nil {
   214  			limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange)
   215  			if b.header.Number.Cmp(daoBlock) >= 0 && b.header.Number.Cmp(limit) < 0 {
   216  				if config.DAOForkSupport {
   217  					b.header.Extra = common.CopyBytes(params.DAOForkBlockExtra)
   218  				}
   219  			}
   220  		}
   221  		if config.DAOForkSupport && config.DAOForkBlock != nil && config.DAOForkBlock.Cmp(b.header.Number) == 0 {
   222  			misc.ApplyDAOHardFork(statedb)
   223  		}
   224  		// Execute any user modifications to the block
   225  		if gen != nil {
   226  			gen(i, b)
   227  		}
   228  		if b.engine != nil {
   229  			// Finalize and seal the block
   230  			block, _ := b.engine.FinalizeAndAssemble(chainreader, b.header, statedb, b.txs, b.uncles, b.receipts)
   231  
   232  			// Write state changes to db
   233  			root, err := statedb.Commit(config.IsEIP158(b.header.Number))
   234  			if err != nil {
   235  				panic(fmt.Sprintf("state write error: %v", err))
   236  			}
   237  			if err := statedb.Database().TrieDB().Commit(root, false, nil); err != nil {
   238  				panic(fmt.Sprintf("trie write error: %v", err))
   239  			}
   240  			return block, b.receipts
   241  		}
   242  		return nil, nil
   243  	}
   244  	for i := 0; i < n; i++ {
   245  		statedb, err := state.New(parent.Root(), state.NewDatabase(db), nil)
   246  		if err != nil {
   247  			panic(err)
   248  		}
   249  		block, receipt := genblock(i, parent, statedb)
   250  		blocks[i] = block
   251  		receipts[i] = receipt
   252  		parent = block
   253  	}
   254  	return blocks, receipts
   255  }
   256  
   257  func makeHeader(chain consensus.ChainReader, parent *types.Block, state *state.StateDB, engine consensus.Engine) *types.Header {
   258  	var time uint64
   259  	if parent.Time() == 0 {
   260  		time = 10
   261  	} else {
   262  		time = parent.Time() + 10 // block time is fixed at 10 seconds
   263  	}
   264  	header := &types.Header{
   265  		Root:       state.IntermediateRoot(chain.Config().IsEIP158(parent.Number())),
   266  		ParentHash: parent.Hash(),
   267  		Coinbase:   parent.Coinbase(),
   268  		Difficulty: engine.CalcDifficulty(chain, time, &types.Header{
   269  			Number:     parent.Number(),
   270  			Time:       time - 10,
   271  			Difficulty: parent.Difficulty(),
   272  			UncleHash:  parent.UncleHash(),
   273  		}),
   274  		GasLimit: parent.GasLimit(),
   275  		Number:   new(big.Int).Add(parent.Number(), common.Big1),
   276  		Time:     time,
   277  	}
   278  	if chain.Config().IsLondon(header.Number) {
   279  		header.BaseFee = misc.CalcBaseFee(chain.Config(), parent.Header())
   280  		if !chain.Config().IsLondon(parent.Number()) {
   281  			parentGasLimit := parent.GasLimit() * params.ElasticityMultiplier
   282  			header.GasLimit = CalcGasLimit(parentGasLimit, parentGasLimit)
   283  		}
   284  	}
   285  	return header
   286  }
   287  
   288  // makeHeaderChain creates a deterministic chain of headers rooted at parent.
   289  func makeHeaderChain(parent *types.Header, n int, engine consensus.Engine, db ethdb.Database, seed int) []*types.Header {
   290  	blocks := makeBlockChain(types.NewBlockWithHeader(parent), n, engine, db, seed)
   291  	headers := make([]*types.Header, len(blocks))
   292  	for i, block := range blocks {
   293  		headers[i] = block.Header()
   294  	}
   295  	return headers
   296  }
   297  
   298  // makeBlockChain creates a deterministic chain of blocks rooted at parent.
   299  func makeBlockChain(parent *types.Block, n int, engine consensus.Engine, db ethdb.Database, seed int) []*types.Block {
   300  	blocks, _ := GenerateChain(params.TestChainConfig, parent, engine, db, n, func(i int, b *BlockGen) {
   301  		b.SetCoinbase(common.Address{0: byte(seed), 19: byte(i)})
   302  	})
   303  	return blocks
   304  }
   305  
   306  type fakeChainReader struct {
   307  	config *params.ChainConfig
   308  }
   309  
   310  // Config returns the chain configuration.
   311  func (cr *fakeChainReader) Config() *params.ChainConfig {
   312  	return cr.config
   313  }
   314  
   315  func (cr *fakeChainReader) CurrentHeader() *types.Header                            { return nil }
   316  func (cr *fakeChainReader) GetHeaderByNumber(number uint64) *types.Header           { return nil }
   317  func (cr *fakeChainReader) GetHeaderByHash(hash common.Hash) *types.Header          { return nil }
   318  func (cr *fakeChainReader) GetHeader(hash common.Hash, number uint64) *types.Header { return nil }
   319  func (cr *fakeChainReader) GetBlock(hash common.Hash, number uint64) *types.Block   { return nil }