gitlab.com/aquachain/aquachain@v1.17.16-rc3.0.20221018032414-e3ddf1e1c055/core/chain_makers.go (about)

     1  // Copyright 2018 The aquachain Authors
     2  // This file is part of the aquachain library.
     3  //
     4  // The aquachain 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 aquachain 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 aquachain library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package core
    18  
    19  import (
    20  	"fmt"
    21  	"math/big"
    22  
    23  	"gitlab.com/aquachain/aquachain/aquadb"
    24  	"gitlab.com/aquachain/aquachain/common"
    25  	"gitlab.com/aquachain/aquachain/consensus"
    26  	"gitlab.com/aquachain/aquachain/consensus/misc"
    27  	"gitlab.com/aquachain/aquachain/core/state"
    28  	"gitlab.com/aquachain/aquachain/core/types"
    29  	"gitlab.com/aquachain/aquachain/core/vm"
    30  	"gitlab.com/aquachain/aquachain/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  	chainReader consensus.ChainReader
    40  	header      *types.Header
    41  	statedb     *state.StateDB
    42  
    43  	gasPool  *GasPool
    44  	txs      []*types.Transaction
    45  	receipts []*types.Receipt
    46  	uncles   []*types.Header
    47  
    48  	config *params.ChainConfig
    49  	engine consensus.Engine
    50  }
    51  
    52  // SetCoinbase sets the coinbase of the generated block.
    53  // It can be called at most once.
    54  func (b *BlockGen) SetCoinbase(addr common.Address) {
    55  	if b.gasPool != nil {
    56  		if len(b.txs) > 0 {
    57  			panic("coinbase must be set before adding transactions")
    58  		}
    59  		panic("coinbase can only be set once")
    60  	}
    61  	b.header.Coinbase = addr
    62  	b.gasPool = new(GasPool).AddGas(b.header.GasLimit)
    63  }
    64  
    65  // Setversion sets the header version
    66  func (b *BlockGen) SetVersion(version params.HeaderVersion) {
    67  	b.header.Version = version
    68  }
    69  
    70  // SetExtra sets the extra data field of the generated block.
    71  func (b *BlockGen) SetExtra(data []byte) {
    72  	b.header.Extra = data
    73  }
    74  
    75  // AddTx adds a transaction to the generated block. If no coinbase has
    76  // been set, the block's coinbase is set to the zero address.
    77  //
    78  // AddTx panics if the transaction cannot be executed. In addition to
    79  // the protocol-imposed limitations (gas limit, etc.), there are some
    80  // further limitations on the content of transactions that can be
    81  // added. Notably, contract code relying on the BLOCKHASH instruction
    82  // will panic during execution.
    83  func (b *BlockGen) AddTx(tx *types.Transaction) {
    84  	if b.gasPool == nil {
    85  		b.SetCoinbase(common.Address{})
    86  	}
    87  	b.statedb.Prepare(tx.Hash(), common.Hash{}, len(b.txs))
    88  	receipt, _, err := ApplyTransaction(b.config, nil, &b.header.Coinbase, b.gasPool, b.statedb, b.header, tx, &b.header.GasUsed, vm.Config{})
    89  	if err != nil {
    90  		panic(err)
    91  	}
    92  	b.txs = append(b.txs, tx)
    93  	b.receipts = append(b.receipts, receipt)
    94  }
    95  
    96  // Number returns the block number of the block being generated.
    97  func (b *BlockGen) Number() *big.Int {
    98  	return new(big.Int).Set(b.header.Number)
    99  }
   100  
   101  // AddUncheckedReceipt forcefully adds a receipts to the block without a
   102  // backing transaction.
   103  //
   104  // AddUncheckedReceipt will cause consensus failures when used during real
   105  // chain processing. This is best used in conjunction with raw block insertion.
   106  func (b *BlockGen) AddUncheckedReceipt(receipt *types.Receipt) {
   107  	b.receipts = append(b.receipts, receipt)
   108  }
   109  
   110  // TxNonce returns the next valid transaction nonce for the
   111  // account at addr. It panics if the account does not exist.
   112  func (b *BlockGen) TxNonce(addr common.Address) uint64 {
   113  	if !b.statedb.Exist(addr) {
   114  		panic("account does not exist")
   115  	}
   116  	return b.statedb.GetNonce(addr)
   117  }
   118  
   119  // AddUncle adds an uncle header to the generated block.
   120  func (b *BlockGen) AddUncle(h *types.Header) {
   121  	b.uncles = append(b.uncles, h)
   122  }
   123  
   124  // PrevBlock returns a previously generated block by number. It panics if
   125  // num is greater or equal to the number of the block being generated.
   126  // For index -1, PrevBlock returns the parent block given to GenerateChain.
   127  func (b *BlockGen) PrevBlock(index int) *types.Block {
   128  	if index >= b.i {
   129  		panic("block index out of range")
   130  	}
   131  	if index == -1 {
   132  		return b.parent
   133  	}
   134  	return b.chain[index]
   135  }
   136  
   137  // OffsetTime modifies the time instance of a block, implicitly changing its
   138  // associated difficulty. It's useful to test scenarios where forking is not
   139  // tied to chain length directly.
   140  func (b *BlockGen) OffsetTime(seconds int64) {
   141  	b.header.Time.Add(b.header.Time, new(big.Int).SetInt64(seconds))
   142  	if b.header.Time.Cmp(b.parent.Header().Time) <= 0 {
   143  		panic("block time out of range")
   144  	}
   145  	b.header.Difficulty = b.engine.CalcDifficulty(b.chainReader, b.header.Time.Uint64(), b.parent.Header(), nil)
   146  }
   147  
   148  // GenerateChain creates a chain of n blocks. The first block's
   149  // parent will be the provided parent. db is used to store
   150  // intermediate states and should contain the parent's state trie.
   151  //
   152  // The generator function is called with a new block generator for
   153  // every block. Any transactions and uncles added to the generator
   154  // become part of the block. If gen is nil, the blocks will be empty
   155  // and their coinbase will be the zero address.
   156  //
   157  // Blocks created by GenerateChain do not contain valid proof of work
   158  // values. Inserting them into BlockChain requires use of FakePow or
   159  // a similar non-validating proof of work implementation.
   160  func GenerateChain(config *params.ChainConfig, parent *types.Block, engine consensus.Engine, db aquadb.Database, n int, gen func(int, *BlockGen)) ([]*types.Block, []types.Receipts) {
   161  	if config == nil {
   162  		config = params.TestChainConfig
   163  	}
   164  	blocks, receipts := make(types.Blocks, n), make([]types.Receipts, n)
   165  	genblock := func(i int, parent *types.Block, statedb *state.StateDB) (*types.Block, types.Receipts) {
   166  		// TODO(karalabe): This is needed for clique, which depends on multiple blocks.
   167  		// It's nonetheless ugly to spin up a blockchain here. Get rid of this somehow.
   168  		blockchain, _ := NewBlockChain(db, nil, config, engine, vm.Config{})
   169  		defer blockchain.Stop()
   170  
   171  		b := &BlockGen{i: i, parent: parent, chain: blocks, chainReader: blockchain, statedb: statedb, config: config, engine: engine}
   172  		b.header = makeHeader(b.chainReader, parent, statedb, b.engine)
   173  		// Mutate the the block and state according to any hard-fork specs
   174  		if hf4 := config.GetHF(4); hf4 != nil && hf4.Cmp(b.header.Number) == 0 {
   175  			misc.ApplyHardFork4(statedb)
   176  		}
   177  		if hf5 := config.GetHF(5); hf5 != nil && hf5.Cmp(b.header.Number) == 0 {
   178  			misc.ApplyHardFork5(statedb)
   179  		}
   180  		// Execute any user modifications to the block and finalize it
   181  		if gen != nil {
   182  			gen(i, b)
   183  		}
   184  
   185  		if b.engine != nil {
   186  			block, _ := b.engine.Finalize(b.chainReader, b.header, statedb, b.txs, b.uncles, b.receipts)
   187  			// Write state changes to db
   188  			root, err := statedb.Commit(config.IsEIP158(b.header.Number))
   189  			if err != nil {
   190  				panic(fmt.Sprintf("state write error: %v", err))
   191  			}
   192  			if err := statedb.Database().TrieDB().Commit(root, false); err != nil {
   193  				panic(fmt.Sprintf("trie write error: %v", err))
   194  			}
   195  			return block, b.receipts
   196  		}
   197  		return nil, nil
   198  	} // end of genblock()
   199  	for i := 0; i < n; i++ {
   200  		statedb, err := state.New(parent.Root(), state.NewDatabase(db))
   201  		if err != nil {
   202  			panic(err)
   203  		}
   204  		block, receipt := genblock(i, parent, statedb)
   205  		blocks[i] = block
   206  		receipts[i] = receipt
   207  		parent = block
   208  	}
   209  	return blocks, receipts
   210  }
   211  
   212  func makeHeader(chain consensus.ChainReader, parent *types.Block, state *state.StateDB, engine consensus.Engine) *types.Header {
   213  	if parent.Version() == 0 {
   214  		parent.SetVersion(chain.Config().GetBlockVersion(parent.Number()))
   215  	}
   216  	var time *big.Int
   217  	if parent.Time() == nil {
   218  		time = big.NewInt(240)
   219  	} else {
   220  		time = new(big.Int).Add(parent.Time(), big.NewInt(240)) // block time is fixed at 10 seconds
   221  	}
   222  	num := new(big.Int).Add(parent.Number(), common.Big1)
   223  	return &types.Header{
   224  		Root:       state.IntermediateRoot(chain.Config().IsEIP158(num)),
   225  		ParentHash: parent.Hash(),
   226  		Coinbase:   parent.Coinbase(),
   227  		Difficulty: engine.CalcDifficulty(chain, time.Uint64(), &types.Header{
   228  			Number:     parent.Number(),
   229  			Time:       new(big.Int).Sub(time, big.NewInt(240)), // parent time
   230  			Difficulty: parent.Difficulty(),
   231  			UncleHash:  parent.UncleHash(),
   232  		}, nil),
   233  		GasLimit: CalcGasLimit(parent),
   234  		Number:   num,
   235  		Time:     time,
   236  		Version:  chain.Config().GetBlockVersion(num),
   237  	}
   238  }