github.com/theQRL/go-zond@v0.2.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/eip1559"
    26  	"github.com/theQRL/go-zond/core/rawdb"
    27  	"github.com/theQRL/go-zond/core/state"
    28  	"github.com/theQRL/go-zond/core/types"
    29  	"github.com/theQRL/go-zond/core/vm"
    30  	"github.com/theQRL/go-zond/params"
    31  	"github.com/theQRL/go-zond/trie"
    32  	"github.com/theQRL/go-zond/zonddb"
    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  	withdrawals []*types.Withdrawal
    48  
    49  	config *params.ChainConfig
    50  	engine consensus.Engine
    51  }
    52  
    53  // SetCoinbase sets the coinbase of the generated block.
    54  // It can be called at most once.
    55  func (b *BlockGen) SetCoinbase(addr common.Address) {
    56  	if b.gasPool != nil {
    57  		if len(b.txs) > 0 {
    58  			panic("coinbase must be set before adding transactions")
    59  		}
    60  		panic("coinbase can only be set once")
    61  	}
    62  	b.header.Coinbase = addr
    63  	b.gasPool = new(GasPool).AddGas(b.header.GasLimit)
    64  }
    65  
    66  // SetExtra sets the extra data field of the generated block.
    67  func (b *BlockGen) SetExtra(data []byte) {
    68  	b.header.Extra = data
    69  }
    70  
    71  // addTx adds a transaction to the generated block. If no coinbase has
    72  // been set, the block's coinbase is set to the zero address.
    73  //
    74  // There are a few options can be passed as well in order to run some
    75  // customized rules.
    76  // - bc:       enables the ability to query historical block hashes for BLOCKHASH
    77  // - vmConfig: extends the flexibility for customizing zvm rules, e.g. enable extra EIPs
    78  func (b *BlockGen) addTx(bc *BlockChain, vmConfig vm.Config, tx *types.Transaction) {
    79  	if b.gasPool == nil {
    80  		b.SetCoinbase(common.Address{})
    81  	}
    82  	b.statedb.SetTxContext(tx.Hash(), len(b.txs))
    83  	receipt, err := ApplyTransaction(b.config, bc, &b.header.Coinbase, b.gasPool, b.statedb, b.header, tx, &b.header.GasUsed, vmConfig)
    84  	if err != nil {
    85  		panic(err)
    86  	}
    87  	b.txs = append(b.txs, tx)
    88  	b.receipts = append(b.receipts, receipt)
    89  }
    90  
    91  // AddTx adds a transaction to the generated block. If no coinbase has
    92  // been set, the block's coinbase is set to the zero address.
    93  //
    94  // AddTx panics if the transaction cannot be executed. In addition to
    95  // the protocol-imposed limitations (gas limit, etc.), there are some
    96  // further limitations on the content of transactions that can be
    97  // added. Notably, contract code relying on the BLOCKHASH instruction
    98  // will panic during execution.
    99  func (b *BlockGen) AddTx(tx *types.Transaction) {
   100  	b.addTx(nil, vm.Config{}, tx)
   101  }
   102  
   103  // AddTxWithChain adds a transaction to the generated block. If no coinbase has
   104  // been set, the block's coinbase is set to the zero address.
   105  //
   106  // AddTxWithChain panics if the transaction cannot be executed. In addition to
   107  // the protocol-imposed limitations (gas limit, etc.), there are some
   108  // further limitations on the content of transactions that can be
   109  // added. If contract code relies on the BLOCKHASH instruction,
   110  // the block in chain will be returned.
   111  func (b *BlockGen) AddTxWithChain(bc *BlockChain, tx *types.Transaction) {
   112  	b.addTx(bc, vm.Config{}, tx)
   113  }
   114  
   115  // AddTxWithVMConfig adds a transaction to the generated block. If no coinbase has
   116  // been set, the block's coinbase is set to the zero address.
   117  // The zvm interpreter can be customized with the provided vm config.
   118  func (b *BlockGen) AddTxWithVMConfig(tx *types.Transaction, config vm.Config) {
   119  	b.addTx(nil, config, tx)
   120  }
   121  
   122  // GetBalance returns the balance of the given address at the generated block.
   123  func (b *BlockGen) GetBalance(addr common.Address) *big.Int {
   124  	return b.statedb.GetBalance(addr)
   125  }
   126  
   127  // AddUncheckedTx forcefully adds a transaction to the block without any
   128  // validation.
   129  //
   130  // AddUncheckedTx will cause consensus failures when used during real
   131  // chain processing. This is best used in conjunction with raw block insertion.
   132  func (b *BlockGen) AddUncheckedTx(tx *types.Transaction) {
   133  	b.txs = append(b.txs, tx)
   134  }
   135  
   136  // Number returns the block number of the block being generated.
   137  func (b *BlockGen) Number() *big.Int {
   138  	return new(big.Int).Set(b.header.Number)
   139  }
   140  
   141  // Timestamp returns the timestamp of the block being generated.
   142  func (b *BlockGen) Timestamp() uint64 {
   143  	return b.header.Time
   144  }
   145  
   146  // BaseFee returns the EIP-1559 base fee of the block being generated.
   147  func (b *BlockGen) BaseFee() *big.Int {
   148  	return new(big.Int).Set(b.header.BaseFee)
   149  }
   150  
   151  // AddUncheckedReceipt forcefully adds a receipts to the block without a
   152  // backing transaction.
   153  //
   154  // AddUncheckedReceipt will cause consensus failures when used during real
   155  // chain processing. This is best used in conjunction with raw block insertion.
   156  func (b *BlockGen) AddUncheckedReceipt(receipt *types.Receipt) {
   157  	b.receipts = append(b.receipts, receipt)
   158  }
   159  
   160  // TxNonce returns the next valid transaction nonce for the
   161  // account at addr. It panics if the account does not exist.
   162  func (b *BlockGen) TxNonce(addr common.Address) uint64 {
   163  	if !b.statedb.Exist(addr) {
   164  		panic("account does not exist")
   165  	}
   166  	return b.statedb.GetNonce(addr)
   167  }
   168  
   169  // AddWithdrawal adds a withdrawal to the generated block.
   170  // It returns the withdrawal index.
   171  func (b *BlockGen) AddWithdrawal(w *types.Withdrawal) uint64 {
   172  	cpy := *w
   173  	cpy.Index = b.nextWithdrawalIndex()
   174  	b.withdrawals = append(b.withdrawals, &cpy)
   175  	return cpy.Index
   176  }
   177  
   178  // nextWithdrawalIndex computes the index of the next withdrawal.
   179  func (b *BlockGen) nextWithdrawalIndex() uint64 {
   180  	if len(b.withdrawals) != 0 {
   181  		return b.withdrawals[len(b.withdrawals)-1].Index + 1
   182  	}
   183  	for i := b.i - 1; i >= 0; i-- {
   184  		if wd := b.chain[i].Withdrawals(); len(wd) != 0 {
   185  			return wd[len(wd)-1].Index + 1
   186  		}
   187  		if i == 0 {
   188  			// Correctly set the index if no parent had withdrawals.
   189  			if wd := b.parent.Withdrawals(); len(wd) != 0 {
   190  				return wd[len(wd)-1].Index + 1
   191  			}
   192  		}
   193  	}
   194  	return 0
   195  }
   196  
   197  // PrevBlock returns a previously generated block by number. It panics if
   198  // num is greater or equal to the number of the block being generated.
   199  // For index -1, PrevBlock returns the parent block given to GenerateChain.
   200  func (b *BlockGen) PrevBlock(index int) *types.Block {
   201  	if index >= b.i {
   202  		panic(fmt.Errorf("block index %d out of range (%d,%d)", index, -1, b.i))
   203  	}
   204  	if index == -1 {
   205  		return b.parent
   206  	}
   207  	return b.chain[index]
   208  }
   209  
   210  // OffsetTime modifies the time instance of a block, implicitly changing its
   211  // associated difficulty. It's useful to test scenarios where forking is not
   212  // tied to chain length directly.
   213  func (b *BlockGen) OffsetTime(seconds int64) {
   214  	b.header.Time += uint64(seconds)
   215  	if b.header.Time <= b.parent.Header().Time {
   216  		panic("block time out of range")
   217  	}
   218  }
   219  
   220  // GenerateChain creates a chain of n blocks. The first block's
   221  // parent will be the provided parent. db is used to store
   222  // intermediate states and should contain the parent's state trie.
   223  //
   224  // The generator function is called with a new block generator for
   225  // every block. Any transactions added to the generator
   226  // become part of the block. If gen is nil, the blocks will be empty
   227  // and their coinbase will be the zero address.
   228  func GenerateChain(config *params.ChainConfig, parent *types.Block, engine consensus.Engine, db zonddb.Database, n int, gen func(int, *BlockGen)) ([]*types.Block, []types.Receipts) {
   229  	if config == nil {
   230  		config = params.TestChainConfig
   231  	}
   232  	blocks, receipts := make(types.Blocks, n), make([]types.Receipts, n)
   233  	chainreader := &fakeChainReader{config: config}
   234  	genblock := func(i int, parent *types.Block, triedb *trie.Database, statedb *state.StateDB) (*types.Block, types.Receipts) {
   235  		b := &BlockGen{i: i, chain: blocks, parent: parent, statedb: statedb, config: config, engine: engine}
   236  		b.header = makeHeader(chainreader, parent, statedb)
   237  
   238  		// Execute any user modifications to the block
   239  		if gen != nil {
   240  			gen(i, b)
   241  		}
   242  		if b.engine != nil {
   243  			body := types.Body{Transactions: b.txs, Withdrawals: b.withdrawals}
   244  			block, err := b.engine.FinalizeAndAssemble(chainreader, b.header, statedb, &body, b.receipts)
   245  			if err != nil {
   246  				panic(err)
   247  			}
   248  
   249  			// Write state changes to db
   250  			root, err := statedb.Commit(b.header.Number.Uint64(), true)
   251  			if err != nil {
   252  				panic(fmt.Sprintf("state write error: %v", err))
   253  			}
   254  			if err = triedb.Commit(root, false); err != nil {
   255  				panic(fmt.Sprintf("trie write error: %v", err))
   256  			}
   257  			return block, b.receipts
   258  		}
   259  		return nil, nil
   260  	}
   261  	// Forcibly use hash-based state scheme for retaining all nodes in disk.
   262  	triedb := trie.NewDatabase(db, trie.HashDefaults)
   263  	defer triedb.Close()
   264  
   265  	for i := 0; i < n; i++ {
   266  		statedb, err := state.New(parent.Root(), state.NewDatabaseWithNodeDB(db, triedb), nil)
   267  		if err != nil {
   268  			panic(err)
   269  		}
   270  		block, receipt := genblock(i, parent, triedb, statedb)
   271  		blocks[i] = block
   272  		receipts[i] = receipt
   273  		parent = block
   274  	}
   275  	return blocks, receipts
   276  }
   277  
   278  // GenerateChainWithGenesis is a wrapper of GenerateChain which will initialize
   279  // genesis block to database first according to the provided genesis specification
   280  // then generate chain on top.
   281  func GenerateChainWithGenesis(genesis *Genesis, engine consensus.Engine, n int, gen func(int, *BlockGen)) (zonddb.Database, []*types.Block, []types.Receipts) {
   282  	db := rawdb.NewMemoryDatabase()
   283  	triedb := trie.NewDatabase(db, trie.HashDefaults)
   284  	defer triedb.Close()
   285  	_, err := genesis.Commit(db, triedb)
   286  	if err != nil {
   287  		panic(err)
   288  	}
   289  	blocks, receipts := GenerateChain(genesis.Config, genesis.ToBlock(), engine, db, n, gen)
   290  	return db, blocks, receipts
   291  }
   292  
   293  func makeHeader(chain consensus.ChainReader, parent *types.Block, state *state.StateDB) *types.Header {
   294  	var time uint64
   295  	if parent.Time() == 0 {
   296  		time = 10
   297  	} else {
   298  		time = parent.Time() + 10 // block time is fixed at 10 seconds
   299  	}
   300  	header := &types.Header{
   301  		Root:       state.IntermediateRoot(true),
   302  		ParentHash: parent.Hash(),
   303  		Coinbase:   parent.Coinbase(),
   304  		GasLimit:   parent.GasLimit(),
   305  		Number:     new(big.Int).Add(parent.Number(), common.Big1),
   306  		Time:       time,
   307  		BaseFee:    eip1559.CalcBaseFee(chain.Config(), parent.Header()),
   308  	}
   309  
   310  	return header
   311  }
   312  
   313  // makeHeaderChain creates a deterministic chain of headers rooted at parent.
   314  func makeHeaderChain(chainConfig *params.ChainConfig, parent *types.Header, n int, engine consensus.Engine, db zonddb.Database, seed int) []*types.Header {
   315  	blocks := makeBlockChain(chainConfig, types.NewBlockWithHeader(parent), n, engine, db, seed)
   316  	headers := make([]*types.Header, len(blocks))
   317  	for i, block := range blocks {
   318  		headers[i] = block.Header()
   319  	}
   320  	return headers
   321  }
   322  
   323  // makeHeaderChainWithGenesis creates a deterministic chain of headers from genesis.
   324  func makeHeaderChainWithGenesis(genesis *Genesis, n int, engine consensus.Engine, seed int) (zonddb.Database, []*types.Header) {
   325  	db, blocks := makeBlockChainWithGenesis(genesis, n, engine, seed)
   326  	headers := make([]*types.Header, len(blocks))
   327  	for i, block := range blocks {
   328  		headers[i] = block.Header()
   329  	}
   330  	return db, headers
   331  }
   332  
   333  // makeBlockChain creates a deterministic chain of blocks rooted at parent.
   334  func makeBlockChain(chainConfig *params.ChainConfig, parent *types.Block, n int, engine consensus.Engine, db zonddb.Database, seed int) []*types.Block {
   335  	blocks, _ := GenerateChain(chainConfig, parent, engine, db, n, func(i int, b *BlockGen) {
   336  		b.SetCoinbase(common.Address{0: byte(seed), 19: byte(i)})
   337  	})
   338  	return blocks
   339  }
   340  
   341  // makeBlockChain creates a deterministic chain of blocks from genesis
   342  func makeBlockChainWithGenesis(genesis *Genesis, n int, engine consensus.Engine, seed int) (zonddb.Database, []*types.Block) {
   343  	db, blocks, _ := GenerateChainWithGenesis(genesis, engine, n, func(i int, b *BlockGen) {
   344  		b.SetCoinbase(common.Address{0: byte(seed), 19: byte(i)})
   345  	})
   346  	return db, blocks
   347  }
   348  
   349  type fakeChainReader struct {
   350  	config *params.ChainConfig
   351  }
   352  
   353  // Config returns the chain configuration.
   354  func (cr *fakeChainReader) Config() *params.ChainConfig {
   355  	return cr.config
   356  }
   357  
   358  func (cr *fakeChainReader) CurrentHeader() *types.Header                            { return nil }
   359  func (cr *fakeChainReader) GetHeaderByNumber(number uint64) *types.Header           { return nil }
   360  func (cr *fakeChainReader) GetHeaderByHash(hash common.Hash) *types.Header          { return nil }
   361  func (cr *fakeChainReader) GetHeader(hash common.Hash, number uint64) *types.Header { return nil }
   362  func (cr *fakeChainReader) GetBlock(hash common.Hash, number uint64) *types.Block   { return nil }