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