github.com/tacshi/go-ethereum@v0.0.0-20230616113857-84a434e20921/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/tacshi/go-ethereum/common"
    24  	"github.com/tacshi/go-ethereum/consensus"
    25  	"github.com/tacshi/go-ethereum/consensus/misc"
    26  	"github.com/tacshi/go-ethereum/core/rawdb"
    27  	"github.com/tacshi/go-ethereum/core/state"
    28  	"github.com/tacshi/go-ethereum/core/types"
    29  	"github.com/tacshi/go-ethereum/core/vm"
    30  	"github.com/tacshi/go-ethereum/ethdb"
    31  	"github.com/tacshi/go-ethereum/params"
    32  	"github.com/tacshi/go-ethereum/trie"
    33  )
    34  
    35  // BlockGen creates blocks for testing.
    36  // See GenerateChain for a detailed explanation.
    37  type BlockGen struct {
    38  	i       int
    39  	parent  *types.Block
    40  	chain   []*types.Block
    41  	header  *types.Header
    42  	statedb *state.StateDB
    43  
    44  	gasPool     *GasPool
    45  	txs         []*types.Transaction
    46  	receipts    []*types.Receipt
    47  	uncles      []*types.Header
    48  	withdrawals []*types.Withdrawal
    49  
    50  	config *params.ChainConfig
    51  	engine consensus.Engine
    52  }
    53  
    54  // SetCoinbase sets the coinbase of the generated block.
    55  // It can be called at most once.
    56  func (b *BlockGen) SetCoinbase(addr common.Address) {
    57  	if b.gasPool != nil {
    58  		if len(b.txs) > 0 {
    59  			panic("coinbase must be set before adding transactions")
    60  		}
    61  		panic("coinbase can only be set once")
    62  	}
    63  	b.header.Coinbase = addr
    64  	b.gasPool = new(GasPool).AddGas(b.header.GasLimit)
    65  }
    66  
    67  // SetExtra sets the extra data field of the generated block.
    68  func (b *BlockGen) SetExtra(data []byte) {
    69  	b.header.Extra = data
    70  }
    71  
    72  // SetNonce sets the nonce field of the generated block.
    73  func (b *BlockGen) SetNonce(nonce types.BlockNonce) {
    74  	b.header.Nonce = nonce
    75  }
    76  
    77  // SetDifficulty sets the difficulty field of the generated block. This method is
    78  // useful for Clique tests where the difficulty does not depend on time. For the
    79  // ethash tests, please use OffsetTime, which implicitly recalculates the diff.
    80  func (b *BlockGen) SetDifficulty(diff *big.Int) {
    81  	b.header.Difficulty = diff
    82  }
    83  
    84  // SetPos makes the header a PoS-header (0 difficulty)
    85  func (b *BlockGen) SetPoS() {
    86  	b.header.Difficulty = new(big.Int)
    87  }
    88  
    89  // addTx adds a transaction to the generated block. If no coinbase has
    90  // been set, the block's coinbase is set to the zero address.
    91  //
    92  // There are a few options can be passed as well in order to run some
    93  // customized rules.
    94  // - bc:       enables the ability to query historical block hashes for BLOCKHASH
    95  // - vmConfig: extends the flexibility for customizing evm rules, e.g. enable extra EIPs
    96  func (b *BlockGen) addTx(bc *BlockChain, vmConfig vm.Config, tx *types.Transaction) {
    97  	if b.gasPool == nil {
    98  		b.SetCoinbase(common.Address{})
    99  	}
   100  	b.statedb.SetTxContext(tx.Hash(), len(b.txs))
   101  	receipt, _, err := ApplyTransaction(b.config, bc, &b.header.Coinbase, b.gasPool, b.statedb, b.header, tx, &b.header.GasUsed, vmConfig)
   102  	if err != nil {
   103  		panic(err)
   104  	}
   105  	b.txs = append(b.txs, tx)
   106  	b.receipts = append(b.receipts, receipt)
   107  }
   108  
   109  // AddTx adds a transaction to the generated block. If no coinbase has
   110  // been set, the block's coinbase is set to the zero address.
   111  //
   112  // AddTx panics if the transaction cannot be executed. In addition to
   113  // the protocol-imposed limitations (gas limit, etc.), there are some
   114  // further limitations on the content of transactions that can be
   115  // added. Notably, contract code relying on the BLOCKHASH instruction
   116  // will panic during execution.
   117  func (b *BlockGen) AddTx(tx *types.Transaction) {
   118  	b.addTx(nil, vm.Config{}, tx)
   119  }
   120  
   121  // AddTxWithChain adds a transaction to the generated block. If no coinbase has
   122  // been set, the block's coinbase is set to the zero address.
   123  //
   124  // AddTxWithChain panics if the transaction cannot be executed. In addition to
   125  // the protocol-imposed limitations (gas limit, etc.), there are some
   126  // further limitations on the content of transactions that can be
   127  // added. If contract code relies on the BLOCKHASH instruction,
   128  // the block in chain will be returned.
   129  func (b *BlockGen) AddTxWithChain(bc *BlockChain, tx *types.Transaction) {
   130  	b.addTx(bc, vm.Config{}, tx)
   131  }
   132  
   133  // AddTxWithVMConfig adds a transaction to the generated block. If no coinbase has
   134  // been set, the block's coinbase is set to the zero address.
   135  // The evm interpreter can be customized with the provided vm config.
   136  func (b *BlockGen) AddTxWithVMConfig(tx *types.Transaction, config vm.Config) {
   137  	b.addTx(nil, config, tx)
   138  }
   139  
   140  // GetBalance returns the balance of the given address at the generated block.
   141  func (b *BlockGen) GetBalance(addr common.Address) *big.Int {
   142  	return b.statedb.GetBalance(addr)
   143  }
   144  
   145  // AddUncheckedTx forcefully adds a transaction to the block without any
   146  // validation.
   147  //
   148  // AddUncheckedTx will cause consensus failures when used during real
   149  // chain processing. This is best used in conjunction with raw block insertion.
   150  func (b *BlockGen) AddUncheckedTx(tx *types.Transaction) {
   151  	b.txs = append(b.txs, tx)
   152  }
   153  
   154  // Number returns the block number of the block being generated.
   155  func (b *BlockGen) Number() *big.Int {
   156  	return new(big.Int).Set(b.header.Number)
   157  }
   158  
   159  // Timestamp returns the timestamp of the block being generated.
   160  func (b *BlockGen) Timestamp() uint64 {
   161  	return b.header.Time
   162  }
   163  
   164  // BaseFee returns the EIP-1559 base fee of the block being generated.
   165  func (b *BlockGen) BaseFee() *big.Int {
   166  	return new(big.Int).Set(b.header.BaseFee)
   167  }
   168  
   169  // AddUncheckedReceipt forcefully adds a receipts to the block without a
   170  // backing transaction.
   171  //
   172  // AddUncheckedReceipt will cause consensus failures when used during real
   173  // chain processing. This is best used in conjunction with raw block insertion.
   174  func (b *BlockGen) AddUncheckedReceipt(receipt *types.Receipt) {
   175  	b.receipts = append(b.receipts, receipt)
   176  }
   177  
   178  // TxNonce returns the next valid transaction nonce for the
   179  // account at addr. It panics if the account does not exist.
   180  func (b *BlockGen) TxNonce(addr common.Address) uint64 {
   181  	if !b.statedb.Exist(addr) {
   182  		panic("account does not exist")
   183  	}
   184  	return b.statedb.GetNonce(addr)
   185  }
   186  
   187  // AddUncle adds an uncle header to the generated block.
   188  func (b *BlockGen) AddUncle(h *types.Header) {
   189  	// The uncle will have the same timestamp and auto-generated difficulty
   190  	h.Time = b.header.Time
   191  
   192  	var parent *types.Header
   193  	for i := b.i - 1; i >= 0; i-- {
   194  		if b.chain[i].Hash() == h.ParentHash {
   195  			parent = b.chain[i].Header()
   196  			break
   197  		}
   198  	}
   199  	chainreader := &fakeChainReader{config: b.config}
   200  	h.Difficulty = b.engine.CalcDifficulty(chainreader, b.header.Time, parent)
   201  
   202  	// The gas limit and price should be derived from the parent
   203  	h.GasLimit = parent.GasLimit
   204  	if b.config.IsLondon(h.Number) {
   205  		h.BaseFee = misc.CalcBaseFee(b.config, parent)
   206  		if !b.config.IsLondon(parent.Number) {
   207  			parentGasLimit := parent.GasLimit * b.config.ElasticityMultiplier()
   208  			h.GasLimit = CalcGasLimit(parentGasLimit, parentGasLimit)
   209  		}
   210  	}
   211  	b.uncles = append(b.uncles, h)
   212  }
   213  
   214  // AddWithdrawal adds a withdrawal to the generated block.
   215  // It returns the withdrawal index.
   216  func (b *BlockGen) AddWithdrawal(w *types.Withdrawal) uint64 {
   217  	cpy := *w
   218  	cpy.Index = b.nextWithdrawalIndex()
   219  	b.withdrawals = append(b.withdrawals, &cpy)
   220  	return cpy.Index
   221  }
   222  
   223  // nextWithdrawalIndex computes the index of the next withdrawal.
   224  func (b *BlockGen) nextWithdrawalIndex() uint64 {
   225  	if len(b.withdrawals) != 0 {
   226  		return b.withdrawals[len(b.withdrawals)-1].Index + 1
   227  	}
   228  	for i := b.i - 1; i >= 0; i-- {
   229  		if wd := b.chain[i].Withdrawals(); len(wd) != 0 {
   230  			return wd[len(wd)-1].Index + 1
   231  		}
   232  		if i == 0 {
   233  			// Correctly set the index if no parent had withdrawals.
   234  			if wd := b.parent.Withdrawals(); len(wd) != 0 {
   235  				return wd[len(wd)-1].Index + 1
   236  			}
   237  		}
   238  	}
   239  	return 0
   240  }
   241  
   242  // PrevBlock returns a previously generated block by number. It panics if
   243  // num is greater or equal to the number of the block being generated.
   244  // For index -1, PrevBlock returns the parent block given to GenerateChain.
   245  func (b *BlockGen) PrevBlock(index int) *types.Block {
   246  	if index >= b.i {
   247  		panic(fmt.Errorf("block index %d out of range (%d,%d)", index, -1, b.i))
   248  	}
   249  	if index == -1 {
   250  		return b.parent
   251  	}
   252  	return b.chain[index]
   253  }
   254  
   255  // OffsetTime modifies the time instance of a block, implicitly changing its
   256  // associated difficulty. It's useful to test scenarios where forking is not
   257  // tied to chain length directly.
   258  func (b *BlockGen) OffsetTime(seconds int64) {
   259  	b.header.Time += uint64(seconds)
   260  	if b.header.Time <= b.parent.Header().Time {
   261  		panic("block time out of range")
   262  	}
   263  	chainreader := &fakeChainReader{config: b.config}
   264  	b.header.Difficulty = b.engine.CalcDifficulty(chainreader, b.header.Time, b.parent.Header())
   265  }
   266  
   267  // GenerateChain creates a chain of n blocks. The first block's
   268  // parent will be the provided parent. db is used to store
   269  // intermediate states and should contain the parent's state trie.
   270  //
   271  // The generator function is called with a new block generator for
   272  // every block. Any transactions and uncles added to the generator
   273  // become part of the block. If gen is nil, the blocks will be empty
   274  // and their coinbase will be the zero address.
   275  //
   276  // Blocks created by GenerateChain do not contain valid proof of work
   277  // values. Inserting them into BlockChain requires use of FakePow or
   278  // a similar non-validating proof of work implementation.
   279  func GenerateChain(config *params.ChainConfig, parent *types.Block, engine consensus.Engine, db ethdb.Database, n int, gen func(int, *BlockGen)) ([]*types.Block, []types.Receipts) {
   280  	if config == nil {
   281  		config = params.TestChainConfig
   282  	}
   283  	blocks, receipts := make(types.Blocks, n), make([]types.Receipts, n)
   284  	chainreader := &fakeChainReader{config: config}
   285  	genblock := func(i int, parent *types.Block, statedb *state.StateDB) (*types.Block, types.Receipts) {
   286  		b := &BlockGen{i: i, chain: blocks, parent: parent, statedb: statedb, config: config, engine: engine}
   287  		b.header = makeHeader(chainreader, parent, statedb, b.engine)
   288  
   289  		// Set the difficulty for clique block. The chain maker doesn't have access
   290  		// to a chain, so the difficulty will be left unset (nil). Set it here to the
   291  		// correct value.
   292  		if b.header.Difficulty == nil {
   293  			if config.TerminalTotalDifficulty == nil {
   294  				// Clique chain
   295  				b.header.Difficulty = big.NewInt(2)
   296  			} else {
   297  				// Post-merge chain
   298  				b.header.Difficulty = big.NewInt(0)
   299  			}
   300  		}
   301  		// Mutate the state and block according to any hard-fork specs
   302  		if daoBlock := config.DAOForkBlock; daoBlock != nil {
   303  			limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange)
   304  			if b.header.Number.Cmp(daoBlock) >= 0 && b.header.Number.Cmp(limit) < 0 {
   305  				if config.DAOForkSupport {
   306  					b.header.Extra = common.CopyBytes(params.DAOForkBlockExtra)
   307  				}
   308  			}
   309  		}
   310  		if config.DAOForkSupport && config.DAOForkBlock != nil && config.DAOForkBlock.Cmp(b.header.Number) == 0 {
   311  			misc.ApplyDAOHardFork(statedb)
   312  		}
   313  		// Execute any user modifications to the block
   314  		if gen != nil {
   315  			gen(i, b)
   316  		}
   317  		if b.engine != nil {
   318  			block, err := b.engine.FinalizeAndAssemble(chainreader, b.header, statedb, b.txs, b.uncles, b.receipts, b.withdrawals)
   319  			if err != nil {
   320  				panic(err)
   321  			}
   322  
   323  			// Write state changes to db
   324  			root, err := statedb.Commit(config.IsEIP158(b.header.Number))
   325  			if err != nil {
   326  				panic(fmt.Sprintf("state write error: %v", err))
   327  			}
   328  			if err := statedb.Database().TrieDB().Commit(root, false); err != nil {
   329  				panic(fmt.Sprintf("trie write error: %v", err))
   330  			}
   331  			return block, b.receipts
   332  		}
   333  		return nil, nil
   334  	}
   335  	for i := 0; i < n; i++ {
   336  		statedb, err := state.New(parent.Root(), state.NewDatabase(db), nil)
   337  		if err != nil {
   338  			panic(err)
   339  		}
   340  		block, receipt := genblock(i, parent, statedb)
   341  		blocks[i] = block
   342  		receipts[i] = receipt
   343  		parent = block
   344  	}
   345  	return blocks, receipts
   346  }
   347  
   348  // GenerateChainWithGenesis is a wrapper of GenerateChain which will initialize
   349  // genesis block to database first according to the provided genesis specification
   350  // then generate chain on top.
   351  func GenerateChainWithGenesis(genesis *Genesis, engine consensus.Engine, n int, gen func(int, *BlockGen)) (ethdb.Database, []*types.Block, []types.Receipts) {
   352  	db := rawdb.NewMemoryDatabase()
   353  	_, err := genesis.Commit(db, trie.NewDatabase(db))
   354  	if err != nil {
   355  		panic(err)
   356  	}
   357  	blocks, receipts := GenerateChain(genesis.Config, genesis.ToBlock(), engine, db, n, gen)
   358  	return db, blocks, receipts
   359  }
   360  
   361  func makeHeader(chain consensus.ChainReader, parent *types.Block, state *state.StateDB, engine consensus.Engine) *types.Header {
   362  	var time uint64
   363  	if parent.Time() == 0 {
   364  		time = 10
   365  	} else {
   366  		time = parent.Time() + 10 // block time is fixed at 10 seconds
   367  	}
   368  	header := &types.Header{
   369  		Root:       state.IntermediateRoot(chain.Config().IsEIP158(parent.Number())),
   370  		ParentHash: parent.Hash(),
   371  		Coinbase:   parent.Coinbase(),
   372  		Difficulty: engine.CalcDifficulty(chain, time, &types.Header{
   373  			Number:     parent.Number(),
   374  			Time:       time - 10,
   375  			Difficulty: parent.Difficulty(),
   376  			UncleHash:  parent.UncleHash(),
   377  		}),
   378  		GasLimit: parent.GasLimit(),
   379  		Number:   new(big.Int).Add(parent.Number(), common.Big1),
   380  		Time:     time,
   381  	}
   382  	if chain.Config().IsLondon(header.Number) {
   383  		header.BaseFee = misc.CalcBaseFee(chain.Config(), parent.Header())
   384  		if !chain.Config().IsLondon(parent.Number()) {
   385  			parentGasLimit := parent.GasLimit() * chain.Config().ElasticityMultiplier()
   386  			header.GasLimit = CalcGasLimit(parentGasLimit, parentGasLimit)
   387  		}
   388  	}
   389  	return header
   390  }
   391  
   392  // makeHeaderChain creates a deterministic chain of headers rooted at parent.
   393  func makeHeaderChain(chainConfig *params.ChainConfig, parent *types.Header, n int, engine consensus.Engine, db ethdb.Database, seed int) []*types.Header {
   394  	blocks := makeBlockChain(chainConfig, types.NewBlockWithHeader(parent), n, engine, db, seed)
   395  	headers := make([]*types.Header, len(blocks))
   396  	for i, block := range blocks {
   397  		headers[i] = block.Header()
   398  	}
   399  	return headers
   400  }
   401  
   402  // makeHeaderChainWithGenesis creates a deterministic chain of headers from genesis.
   403  func makeHeaderChainWithGenesis(genesis *Genesis, n int, engine consensus.Engine, seed int) (ethdb.Database, []*types.Header) {
   404  	db, blocks := makeBlockChainWithGenesis(genesis, n, engine, seed)
   405  	headers := make([]*types.Header, len(blocks))
   406  	for i, block := range blocks {
   407  		headers[i] = block.Header()
   408  	}
   409  	return db, headers
   410  }
   411  
   412  // makeBlockChain creates a deterministic chain of blocks rooted at parent.
   413  func makeBlockChain(chainConfig *params.ChainConfig, parent *types.Block, n int, engine consensus.Engine, db ethdb.Database, seed int) []*types.Block {
   414  	blocks, _ := GenerateChain(chainConfig, parent, engine, db, n, func(i int, b *BlockGen) {
   415  		b.SetCoinbase(common.Address{0: byte(seed), 19: byte(i)})
   416  	})
   417  	return blocks
   418  }
   419  
   420  // makeBlockChain creates a deterministic chain of blocks from genesis
   421  func makeBlockChainWithGenesis(genesis *Genesis, n int, engine consensus.Engine, seed int) (ethdb.Database, []*types.Block) {
   422  	db, blocks, _ := GenerateChainWithGenesis(genesis, engine, n, func(i int, b *BlockGen) {
   423  		b.SetCoinbase(common.Address{0: byte(seed), 19: byte(i)})
   424  	})
   425  	return db, blocks
   426  }
   427  
   428  type fakeChainReader struct {
   429  	config *params.ChainConfig
   430  }
   431  
   432  // Config returns the chain configuration.
   433  func (cr *fakeChainReader) Config() *params.ChainConfig {
   434  	return cr.config
   435  }
   436  
   437  func (cr *fakeChainReader) CurrentHeader() *types.Header                            { return nil }
   438  func (cr *fakeChainReader) GetHeaderByNumber(number uint64) *types.Header           { return nil }
   439  func (cr *fakeChainReader) GetHeaderByHash(hash common.Hash) *types.Header          { return nil }
   440  func (cr *fakeChainReader) GetHeader(hash common.Hash, number uint64) *types.Header { return nil }
   441  func (cr *fakeChainReader) GetBlock(hash common.Hash, number uint64) *types.Block   { return nil }
   442  func (cr *fakeChainReader) GetTd(hash common.Hash, number uint64) *big.Int          { return nil }