github.com/dim4egster/coreth@v0.10.2/core/chain_makers.go (about)

     1  // (c) 2019-2020, Ava Labs, Inc.
     2  //
     3  // This file is a derived work, based on the go-ethereum library whose original
     4  // notices appear below.
     5  //
     6  // It is distributed under a license compatible with the licensing terms of the
     7  // original code from which it is derived.
     8  //
     9  // Much love to the original authors for their work.
    10  // **********
    11  // Copyright 2015 The go-ethereum Authors
    12  // This file is part of the go-ethereum library.
    13  //
    14  // The go-ethereum library is free software: you can redistribute it and/or modify
    15  // it under the terms of the GNU Lesser General Public License as published by
    16  // the Free Software Foundation, either version 3 of the License, or
    17  // (at your option) any later version.
    18  //
    19  // The go-ethereum library is distributed in the hope that it will be useful,
    20  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    21  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    22  // GNU Lesser General Public License for more details.
    23  //
    24  // You should have received a copy of the GNU Lesser General Public License
    25  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    26  
    27  package core
    28  
    29  import (
    30  	"fmt"
    31  	"math/big"
    32  
    33  	"github.com/dim4egster/coreth/consensus"
    34  	"github.com/dim4egster/coreth/consensus/dummy"
    35  	"github.com/dim4egster/coreth/consensus/misc"
    36  	"github.com/dim4egster/coreth/core/state"
    37  	"github.com/dim4egster/coreth/core/types"
    38  	"github.com/dim4egster/coreth/core/vm"
    39  	"github.com/dim4egster/coreth/ethdb"
    40  	"github.com/dim4egster/coreth/params"
    41  	"github.com/ethereum/go-ethereum/common"
    42  )
    43  
    44  // BlockGen creates blocks for testing.
    45  // See GenerateChain for a detailed explanation.
    46  type BlockGen struct {
    47  	i       int
    48  	parent  *types.Block
    49  	chain   []*types.Block
    50  	header  *types.Header
    51  	statedb *state.StateDB
    52  
    53  	gasPool  *GasPool
    54  	txs      []*types.Transaction
    55  	receipts []*types.Receipt
    56  	uncles   []*types.Header
    57  
    58  	config           *params.ChainConfig
    59  	engine           consensus.Engine
    60  	onBlockGenerated func(*types.Block)
    61  }
    62  
    63  // SetCoinbase sets the coinbase of the generated block.
    64  // It can be called at most once.
    65  func (b *BlockGen) SetCoinbase(addr common.Address) {
    66  	if b.gasPool != nil {
    67  		if len(b.txs) > 0 {
    68  			panic("coinbase must be set before adding transactions")
    69  		}
    70  		panic("coinbase can only be set once")
    71  	}
    72  	b.header.Coinbase = addr
    73  	b.gasPool = new(GasPool).AddGas(b.header.GasLimit)
    74  }
    75  
    76  // SetExtra sets the extra data field of the generated block.
    77  func (b *BlockGen) SetExtra(data []byte) {
    78  	b.header.Extra = data
    79  }
    80  
    81  // SetNonce sets the nonce field of the generated block.
    82  func (b *BlockGen) SetNonce(nonce types.BlockNonce) {
    83  	b.header.Nonce = nonce
    84  }
    85  
    86  // SetDifficulty sets the difficulty field of the generated block. This method is
    87  // useful for Clique tests where the difficulty does not depend on time. For the
    88  // ethash tests, please use OffsetTime, which implicitly recalculates the diff.
    89  func (b *BlockGen) SetDifficulty(diff *big.Int) {
    90  	b.header.Difficulty = diff
    91  }
    92  
    93  // AddTx 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  // AddTx 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. Notably, contract code relying on the BLOCKHASH instruction
   100  // will panic during execution.
   101  func (b *BlockGen) AddTx(tx *types.Transaction) {
   102  	b.AddTxWithChain(nil, tx)
   103  }
   104  
   105  // AddTxWithChain adds a transaction to the generated block. If no coinbase has
   106  // been set, the block's coinbase is set to the zero address.
   107  //
   108  // AddTxWithChain panics if the transaction cannot be executed. In addition to
   109  // the protocol-imposed limitations (gas limit, etc.), there are some
   110  // further limitations on the content of transactions that can be
   111  // added. If contract code relies on the BLOCKHASH instruction,
   112  // the block in chain will be returned.
   113  func (b *BlockGen) AddTxWithChain(bc *BlockChain, tx *types.Transaction) {
   114  	if b.gasPool == nil {
   115  		b.SetCoinbase(common.Address{})
   116  	}
   117  	b.statedb.Prepare(tx.Hash(), len(b.txs))
   118  	receipt, err := ApplyTransaction(b.config, bc, &b.header.Coinbase, b.gasPool, b.statedb, b.header, tx, &b.header.GasUsed, vm.Config{})
   119  	if err != nil {
   120  		panic(err)
   121  	}
   122  	b.txs = append(b.txs, tx)
   123  	b.receipts = append(b.receipts, receipt)
   124  }
   125  
   126  // GetBalance returns the balance of the given address at the generated block.
   127  func (b *BlockGen) GetBalance(addr common.Address) *big.Int {
   128  	return b.statedb.GetBalance(addr)
   129  }
   130  
   131  // AddUncheckedTx forcefully adds a transaction to the block without any
   132  // validation.
   133  //
   134  // AddUncheckedTx will cause consensus failures when used during real
   135  // chain processing. This is best used in conjunction with raw block insertion.
   136  func (b *BlockGen) AddUncheckedTx(tx *types.Transaction) {
   137  	b.txs = append(b.txs, tx)
   138  }
   139  
   140  // Number returns the block number of the block being generated.
   141  func (b *BlockGen) Number() *big.Int {
   142  	return new(big.Int).Set(b.header.Number)
   143  }
   144  
   145  // BaseFee returns the EIP-1559 base fee of the block being generated.
   146  func (b *BlockGen) BaseFee() *big.Int {
   147  	return new(big.Int).Set(b.header.BaseFee)
   148  }
   149  
   150  // AddUncheckedReceipt forcefully adds a receipts to the block without a
   151  // backing transaction.
   152  //
   153  // AddUncheckedReceipt will cause consensus failures when used during real
   154  // chain processing. This is best used in conjunction with raw block insertion.
   155  func (b *BlockGen) AddUncheckedReceipt(receipt *types.Receipt) {
   156  	b.receipts = append(b.receipts, receipt)
   157  }
   158  
   159  // TxNonce returns the next valid transaction nonce for the
   160  // account at addr. It panics if the account does not exist.
   161  func (b *BlockGen) TxNonce(addr common.Address) uint64 {
   162  	if !b.statedb.Exist(addr) {
   163  		panic("account does not exist")
   164  	}
   165  	return b.statedb.GetNonce(addr)
   166  }
   167  
   168  // AddUncle adds an uncle header to the generated block.
   169  func (b *BlockGen) AddUncle(h *types.Header) {
   170  	b.uncles = append(b.uncles, h)
   171  }
   172  
   173  // PrevBlock returns a previously generated block by number. It panics if
   174  // num is greater or equal to the number of the block being generated.
   175  // For index -1, PrevBlock returns the parent block given to GenerateChain.
   176  func (b *BlockGen) PrevBlock(index int) *types.Block {
   177  	if index >= b.i {
   178  		panic(fmt.Errorf("block index %d out of range (%d,%d)", index, -1, b.i))
   179  	}
   180  	if index == -1 {
   181  		return b.parent
   182  	}
   183  	return b.chain[index]
   184  }
   185  
   186  // OffsetTime modifies the time instance of a block, implicitly changing its
   187  // associated difficulty. It's useful to test scenarios where forking is not
   188  // tied to chain length directly.
   189  func (b *BlockGen) OffsetTime(seconds int64) {
   190  	b.header.Time += uint64(seconds)
   191  	if b.header.Time <= b.parent.Header().Time {
   192  		panic("block time out of range")
   193  	}
   194  	chainreader := &fakeChainReader{config: b.config}
   195  	b.header.Difficulty = b.engine.CalcDifficulty(chainreader, b.header.Time, b.parent.Header())
   196  }
   197  
   198  // SetOnBlockGenerated sets a callback function to be invoked after each block is generated
   199  func (b *BlockGen) SetOnBlockGenerated(onBlockGenerated func(*types.Block)) {
   200  	b.onBlockGenerated = onBlockGenerated
   201  }
   202  
   203  // GenerateChain creates a chain of n blocks. The first block's
   204  // parent will be the provided parent. db is used to store
   205  // intermediate states and should contain the parent's state trie.
   206  //
   207  // The generator function is called with a new block generator for
   208  // every block. Any transactions and uncles added to the generator
   209  // become part of the block. If gen is nil, the blocks will be empty
   210  // and their coinbase will be the zero address.
   211  //
   212  // Blocks created by GenerateChain do not contain valid proof of work
   213  // values. Inserting them into BlockChain requires use of FakePow or
   214  // a similar non-validating proof of work implementation.
   215  func GenerateChain(config *params.ChainConfig, parent *types.Block, engine consensus.Engine, db ethdb.Database, n int, gap uint64, gen func(int, *BlockGen)) ([]*types.Block, []types.Receipts, error) {
   216  	if config == nil {
   217  		config = params.TestChainConfig
   218  	}
   219  	blocks, receipts := make(types.Blocks, n), make([]types.Receipts, n)
   220  	chainreader := &fakeChainReader{config: config}
   221  	genblock := func(i int, parent *types.Block, statedb *state.StateDB) (*types.Block, types.Receipts, error) {
   222  		b := &BlockGen{i: i, chain: blocks, parent: parent, statedb: statedb, config: config, engine: engine}
   223  		b.header = makeHeader(chainreader, config, parent, gap, statedb, b.engine)
   224  
   225  		// Mutate the state and block according to any hard-fork specs
   226  		timestamp := new(big.Int).SetUint64(b.header.Time)
   227  		if !config.IsApricotPhase3(timestamp) {
   228  			// avoid dynamic fee extra data override
   229  			if daoBlock := config.DAOForkBlock; daoBlock != nil {
   230  				limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange)
   231  				if b.header.Number.Cmp(daoBlock) >= 0 && b.header.Number.Cmp(limit) < 0 {
   232  					if config.DAOForkSupport {
   233  						b.header.Extra = common.CopyBytes(params.DAOForkBlockExtra)
   234  					}
   235  				}
   236  			}
   237  		}
   238  		if config.DAOForkSupport && config.DAOForkBlock != nil && config.DAOForkBlock.Cmp(b.header.Number) == 0 {
   239  			misc.ApplyDAOHardFork(statedb)
   240  		}
   241  		// Execute any user modifications to the block
   242  		if gen != nil {
   243  			gen(i, b)
   244  		}
   245  		if b.engine != nil {
   246  			// Finalize and seal the block
   247  			block, err := b.engine.FinalizeAndAssemble(chainreader, b.header, parent.Header(), statedb, b.txs, b.uncles, b.receipts)
   248  			if err != nil {
   249  				return nil, nil, fmt.Errorf("Failed to finalize and assemble block at index %d: %w", i, err)
   250  			}
   251  
   252  			// Write state changes to db
   253  			root, err := statedb.Commit(config.IsEIP158(b.header.Number), false)
   254  			if err != nil {
   255  				panic(fmt.Sprintf("state write error: %v", err))
   256  			}
   257  			if err := statedb.Database().TrieDB().Commit(root, false, nil); err != nil {
   258  				panic(fmt.Sprintf("trie write error: %v", err))
   259  			}
   260  			if b.onBlockGenerated != nil {
   261  				b.onBlockGenerated(block)
   262  			}
   263  			return block, b.receipts, nil
   264  		}
   265  		return nil, nil, nil
   266  	}
   267  	for i := 0; i < n; i++ {
   268  		statedb, err := state.New(parent.Root(), state.NewDatabase(db), nil)
   269  		if err != nil {
   270  			return nil, nil, err
   271  		}
   272  		block, receipt, err := genblock(i, parent, statedb)
   273  		if err != nil {
   274  			return nil, nil, err
   275  		}
   276  		blocks[i] = block
   277  		receipts[i] = receipt
   278  		parent = block
   279  	}
   280  	return blocks, receipts, nil
   281  }
   282  
   283  func makeHeader(chain consensus.ChainReader, config *params.ChainConfig, parent *types.Block, gap uint64, state *state.StateDB, engine consensus.Engine) *types.Header {
   284  	var time uint64
   285  	if parent.Time() == 0 {
   286  		time = gap
   287  	} else {
   288  		time = parent.Time() + gap
   289  	}
   290  
   291  	timestamp := new(big.Int).SetUint64(time)
   292  	var gasLimit uint64
   293  	if config.IsApricotPhase1(timestamp) {
   294  		gasLimit = params.ApricotPhase1GasLimit
   295  	} else {
   296  		gasLimit = CalcGasLimit(parent.GasUsed(), parent.GasLimit(), parent.GasLimit(), parent.GasLimit())
   297  	}
   298  
   299  	header := &types.Header{
   300  		Root:       state.IntermediateRoot(chain.Config().IsEIP158(parent.Number())),
   301  		ParentHash: parent.Hash(),
   302  		Coinbase:   parent.Coinbase(),
   303  		Difficulty: engine.CalcDifficulty(chain, time, &types.Header{
   304  			Number:     parent.Number(),
   305  			Time:       time - gap,
   306  			Difficulty: parent.Difficulty(),
   307  			UncleHash:  parent.UncleHash(),
   308  		}),
   309  		GasLimit: gasLimit,
   310  		Number:   new(big.Int).Add(parent.Number(), common.Big1),
   311  		Time:     time,
   312  	}
   313  	if chain.Config().IsApricotPhase3(timestamp) {
   314  		var err error
   315  		header.Extra, header.BaseFee, err = dummy.CalcBaseFee(chain.Config(), parent.Header(), time)
   316  		if err != nil {
   317  			panic(err)
   318  		}
   319  	}
   320  	return header
   321  }
   322  
   323  type fakeChainReader struct {
   324  	config *params.ChainConfig
   325  }
   326  
   327  // Config returns the chain configuration.
   328  func (cr *fakeChainReader) Config() *params.ChainConfig {
   329  	return cr.config
   330  }
   331  
   332  func (cr *fakeChainReader) CurrentHeader() *types.Header                            { return nil }
   333  func (cr *fakeChainReader) GetHeaderByNumber(number uint64) *types.Header           { return nil }
   334  func (cr *fakeChainReader) GetHeaderByHash(hash common.Hash) *types.Header          { return nil }
   335  func (cr *fakeChainReader) GetHeader(hash common.Hash, number uint64) *types.Header { return nil }
   336  func (cr *fakeChainReader) GetBlock(hash common.Hash, number uint64) *types.Block   { return nil }