github.com/baptiste-b-pegasys/quorum/v22@v22.4.2/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/ethereum/go-ethereum/common"
    24  	"github.com/ethereum/go-ethereum/consensus"
    25  	"github.com/ethereum/go-ethereum/consensus/misc"
    26  	"github.com/ethereum/go-ethereum/core/state"
    27  	"github.com/ethereum/go-ethereum/core/types"
    28  	"github.com/ethereum/go-ethereum/core/vm"
    29  	"github.com/ethereum/go-ethereum/ethdb"
    30  	"github.com/ethereum/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  	privateStatedb *state.StateDB // Quorum
    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  // SetNonce sets the nonce field of the generated block.
    72  func (b *BlockGen) SetNonce(nonce types.BlockNonce) {
    73  	b.header.Nonce = nonce
    74  }
    75  
    76  // SetDifficulty sets the difficulty field of the generated block. This method is
    77  // useful for Clique tests where the difficulty does not depend on time. For the
    78  // ethash tests, please use OffsetTime, which implicitly recalculates the diff.
    79  func (b *BlockGen) SetDifficulty(diff *big.Int) {
    80  	b.header.Difficulty = diff
    81  }
    82  
    83  // AddTx adds a transaction to the generated block. If no coinbase has
    84  // been set, the block's coinbase is set to the zero address.
    85  //
    86  // AddTx panics if the transaction cannot be executed. In addition to
    87  // the protocol-imposed limitations (gas limit, etc.), there are some
    88  // further limitations on the content of transactions that can be
    89  // added. Notably, contract code relying on the BLOCKHASH instruction
    90  // will panic during execution.
    91  func (b *BlockGen) AddTx(tx *types.Transaction) {
    92  	b.AddTxWithChain(&BlockChain{quorumConfig: &QuorumChainConfig{}}, tx)
    93  }
    94  
    95  // AddTxWithChain adds a transaction to the generated block. If no coinbase has
    96  // been set, the block's coinbase is set to the zero address.
    97  //
    98  // AddTxWithChain panics if the transaction cannot be executed. In addition to
    99  // the protocol-imposed limitations (gas limit, etc.), there are some
   100  // further limitations on the content of transactions that can be
   101  // added. If contract code relies on the BLOCKHASH instruction,
   102  // the block in chain will be returned.
   103  func (b *BlockGen) AddTxWithChain(bc *BlockChain, tx *types.Transaction) {
   104  	if b.gasPool == nil {
   105  		b.SetCoinbase(common.Address{})
   106  	}
   107  	b.statedb.Prepare(tx.Hash(), common.Hash{}, len(b.txs))
   108  	// Quorum
   109  	privateDb := b.privateStatedb
   110  	if privateDb == nil {
   111  		privateDb = b.statedb
   112  	}
   113  	// End Quorum
   114  
   115  	receipt, _, err := ApplyTransaction(b.config, bc, &b.header.Coinbase, b.gasPool, b.statedb, privateDb, b.header, tx, &b.header.GasUsed, vm.Config{}, false, nil)
   116  	if err != nil {
   117  		panic(err)
   118  	}
   119  	b.txs = append(b.txs, tx)
   120  	b.receipts = append(b.receipts, receipt)
   121  }
   122  
   123  // AddUncheckedTx forcefully adds a transaction to the block without any
   124  // validation.
   125  //
   126  // AddUncheckedTx will cause consensus failures when used during real
   127  // chain processing. This is best used in conjunction with raw block insertion.
   128  func (b *BlockGen) AddUncheckedTx(tx *types.Transaction) {
   129  	b.txs = append(b.txs, tx)
   130  }
   131  
   132  // Number returns the block number of the block being generated.
   133  func (b *BlockGen) Number() *big.Int {
   134  	return new(big.Int).Set(b.header.Number)
   135  }
   136  
   137  // AddUncheckedReceipt forcefully adds a receipts to the block without a
   138  // backing transaction.
   139  //
   140  // AddUncheckedReceipt will cause consensus failures when used during real
   141  // chain processing. This is best used in conjunction with raw block insertion.
   142  func (b *BlockGen) AddUncheckedReceipt(receipt *types.Receipt) {
   143  	b.receipts = append(b.receipts, receipt)
   144  }
   145  
   146  // TxNonce returns the next valid transaction nonce for the
   147  // account at addr. It panics if the account does not exist.
   148  func (b *BlockGen) TxNonce(addr common.Address) uint64 {
   149  	if !b.statedb.Exist(addr) {
   150  		panic("account does not exist")
   151  	}
   152  	return b.statedb.GetNonce(addr)
   153  }
   154  
   155  // AddUncle adds an uncle header to the generated block.
   156  func (b *BlockGen) AddUncle(h *types.Header) {
   157  	b.uncles = append(b.uncles, h)
   158  }
   159  
   160  // PrevBlock returns a previously generated block by number. It panics if
   161  // num is greater or equal to the number of the block being generated.
   162  // For index -1, PrevBlock returns the parent block given to GenerateChain.
   163  func (b *BlockGen) PrevBlock(index int) *types.Block {
   164  	if index >= b.i {
   165  		panic(fmt.Errorf("block index %d out of range (%d,%d)", index, -1, b.i))
   166  	}
   167  	if index == -1 {
   168  		return b.parent
   169  	}
   170  	return b.chain[index]
   171  }
   172  
   173  // OffsetTime modifies the time instance of a block, implicitly changing its
   174  // associated difficulty. It's useful to test scenarios where forking is not
   175  // tied to chain length directly.
   176  func (b *BlockGen) OffsetTime(seconds int64) {
   177  	b.header.Time += uint64(seconds)
   178  	if b.header.Time <= b.parent.Header().Time {
   179  		panic("block time out of range")
   180  	}
   181  	chainreader := &fakeChainReader{config: b.config}
   182  	b.header.Difficulty = b.engine.CalcDifficulty(chainreader, b.header.Time, b.parent.Header())
   183  }
   184  
   185  // GenerateChain creates a chain of n blocks. The first block's
   186  // parent will be the provided parent. db is used to store
   187  // intermediate states and should contain the parent's state trie.
   188  //
   189  // The generator function is called with a new block generator for
   190  // every block. Any transactions and uncles added to the generator
   191  // become part of the block. If gen is nil, the blocks will be empty
   192  // and their coinbase will be the zero address.
   193  //
   194  // Blocks created by GenerateChain do not contain valid proof of work
   195  // values. Inserting them into BlockChain requires use of FakePow or
   196  // a similar non-validating proof of work implementation.
   197  func GenerateChain(config *params.ChainConfig, parent *types.Block, engine consensus.Engine, db ethdb.Database, n int, gen func(int, *BlockGen)) ([]*types.Block, []types.Receipts) {
   198  	if config == nil {
   199  		config = params.TestChainConfig
   200  	}
   201  	blocks, receipts := make(types.Blocks, n), make([]types.Receipts, n)
   202  	chainreader := &fakeChainReader{config: config}
   203  	// Quorum: add `privateStatedb` argument
   204  	genblock := func(i int, parent *types.Block, statedb *state.StateDB, privateStatedb *state.StateDB) (*types.Block, types.Receipts) {
   205  		b := &BlockGen{i: i, chain: blocks, parent: parent, statedb: statedb, privateStatedb: privateStatedb, config: config, engine: engine}
   206  		b.header = makeHeader(chainreader, parent, statedb, b.engine)
   207  
   208  		// Mutate the state and block according to any hard-fork specs
   209  		if daoBlock := config.DAOForkBlock; daoBlock != nil {
   210  			limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange)
   211  			if b.header.Number.Cmp(daoBlock) >= 0 && b.header.Number.Cmp(limit) < 0 {
   212  				if config.DAOForkSupport {
   213  					b.header.Extra = common.CopyBytes(params.DAOForkBlockExtra)
   214  				}
   215  			}
   216  		}
   217  		if config.DAOForkSupport && config.DAOForkBlock != nil && config.DAOForkBlock.Cmp(b.header.Number) == 0 {
   218  			misc.ApplyDAOHardFork(statedb)
   219  		}
   220  		// Execute any user modifications to the block
   221  		if gen != nil {
   222  			gen(i, b)
   223  		}
   224  		if b.engine != nil {
   225  			// Finalize and seal the block
   226  			block, _ := b.engine.FinalizeAndAssemble(chainreader, b.header, statedb, b.txs, b.uncles, b.receipts)
   227  
   228  			// Write state changes to db
   229  			root, err := statedb.Commit(config.IsEIP158(b.header.Number))
   230  			if err != nil {
   231  				panic(fmt.Sprintf("state write error: %v", err))
   232  			}
   233  			if err := statedb.Database().TrieDB().Commit(root, false, nil); err != nil {
   234  				panic(fmt.Sprintf("trie write error: %v", err))
   235  			}
   236  			return block, b.receipts
   237  		}
   238  		return nil, nil
   239  	}
   240  	for i := 0; i < n; i++ {
   241  		statedb, err := state.New(parent.Root(), state.NewDatabase(db), nil)
   242  		if err != nil {
   243  			panic(err)
   244  		}
   245  		privateStatedb, err := state.New(parent.Root(), state.NewDatabase(db), nil) // Quorum
   246  		if err != nil {
   247  			panic(err)
   248  		}
   249  		// Quorum: add `privateStatedb` argument
   250  		block, receipt := genblock(i, parent, statedb, privateStatedb)
   251  		blocks[i] = block
   252  		receipts[i] = receipt
   253  		parent = block
   254  	}
   255  	return blocks, receipts
   256  }
   257  
   258  func makeHeader(chain consensus.ChainReader, parent *types.Block, state *state.StateDB, engine consensus.Engine) *types.Header {
   259  	var time uint64
   260  	if parent.Time() == 0 {
   261  		time = 10
   262  	} else {
   263  		time = parent.Time() + 10 // block time is fixed at 10 seconds
   264  	}
   265  
   266  	return &types.Header{
   267  		Root:       state.IntermediateRoot(chain.Config().IsEIP158(parent.Number())),
   268  		ParentHash: parent.Hash(),
   269  		Coinbase:   parent.Coinbase(),
   270  		Difficulty: engine.CalcDifficulty(chain, time, &types.Header{
   271  			Number:     parent.Number(),
   272  			Time:       time - 10,
   273  			Difficulty: parent.Difficulty(),
   274  			UncleHash:  parent.UncleHash(),
   275  		}),
   276  		GasLimit: CalcGasLimit(parent, parent.GasLimit(), parent.GasLimit()),
   277  		Number:   new(big.Int).Add(parent.Number(), common.Big1),
   278  		Time:     time,
   279  	}
   280  }
   281  
   282  // makeHeaderChain creates a deterministic chain of headers rooted at parent.
   283  func makeHeaderChain(parent *types.Header, n int, engine consensus.Engine, db ethdb.Database, seed int) []*types.Header {
   284  	blocks := makeBlockChain(types.NewBlockWithHeader(parent), n, engine, db, seed)
   285  	headers := make([]*types.Header, len(blocks))
   286  	for i, block := range blocks {
   287  		headers[i] = block.Header()
   288  	}
   289  	return headers
   290  }
   291  
   292  // makeBlockChain creates a deterministic chain of blocks rooted at parent.
   293  func makeBlockChain(parent *types.Block, n int, engine consensus.Engine, db ethdb.Database, seed int) []*types.Block {
   294  	blocks, _ := GenerateChain(params.TestChainConfig, parent, engine, db, n, func(i int, b *BlockGen) {
   295  		b.SetCoinbase(common.Address{0: byte(seed), 19: byte(i)})
   296  	})
   297  	return blocks
   298  }
   299  
   300  type fakeChainReader struct {
   301  	config *params.ChainConfig
   302  }
   303  
   304  // Config returns the chain configuration.
   305  func (cr *fakeChainReader) Config() *params.ChainConfig {
   306  	return cr.config
   307  }
   308  
   309  func (cr *fakeChainReader) CurrentHeader() *types.Header                            { return nil }
   310  func (cr *fakeChainReader) GetHeaderByNumber(number uint64) *types.Header           { return nil }
   311  func (cr *fakeChainReader) GetHeaderByHash(hash common.Hash) *types.Header          { return nil }
   312  func (cr *fakeChainReader) GetHeader(hash common.Hash, number uint64) *types.Header { return nil }
   313  func (cr *fakeChainReader) GetBlock(hash common.Hash, number uint64) *types.Block   { return nil }