github.com/n1ghtfa1l/go-vnt@v0.6.4-alpha.6/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/vntchain/go-vnt/common"
    24  	"github.com/vntchain/go-vnt/consensus"
    25  	"github.com/vntchain/go-vnt/core/state"
    26  	"github.com/vntchain/go-vnt/core/types"
    27  	"github.com/vntchain/go-vnt/core/vm"
    28  	"github.com/vntchain/go-vnt/params"
    29  	"github.com/vntchain/go-vnt/vntdb"
    30  )
    31  
    32  // So we can deterministically seed different blockchains
    33  var (
    34  	canonicalSeed = 1
    35  	forkSeed      = 2
    36  )
    37  
    38  // BlockGen creates blocks for testing.
    39  // See GenerateChain for a detailed explanation.
    40  type BlockGen struct {
    41  	i           int
    42  	parent      *types.Block
    43  	chain       []*types.Block
    44  	chainReader consensus.ChainReader
    45  	header      *types.Header
    46  	statedb     *state.StateDB
    47  
    48  	gasPool  *GasPool
    49  	txs      []*types.Transaction
    50  	receipts []*types.Receipt
    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  // AddTx adds a transaction to the generated block. If no coinbase has
    75  // been set, the block's coinbase is set to the zero address.
    76  //
    77  // AddTx panics if the transaction cannot be executed. In addition to
    78  // the protocol-imposed limitations (gas limit, etc.), there are some
    79  // further limitations on the content of transactions that can be
    80  // added. Notably, contract code relying on the BLOCKHASH instruction
    81  // will panic during execution.
    82  func (b *BlockGen) AddTx(tx *types.Transaction) {
    83  	b.AddTxWithChain(nil, tx)
    84  }
    85  
    86  // AddTxWithChain adds a transaction to the generated block. If no coinbase has
    87  // been set, the block's coinbase is set to the zero address.
    88  //
    89  // AddTxWithChain panics if the transaction cannot be executed. In addition to
    90  // the protocol-imposed limitations (gas limit, etc.), there are some
    91  // further limitations on the content of transactions that can be
    92  // added. If contract code relies on the BLOCKHASH instruction,
    93  // the block in chain will be returned.
    94  func (b *BlockGen) AddTxWithChain(bc *BlockChain, tx *types.Transaction) {
    95  	if b.gasPool == nil {
    96  		b.SetCoinbase(common.Address{})
    97  	}
    98  	b.statedb.Prepare(tx.Hash(), common.Hash{}, len(b.txs))
    99  	receipt, _, err := ApplyTransaction(b.config, bc, &b.header.Coinbase, b.gasPool, b.statedb, b.header, tx, &b.header.GasUsed, vm.Config{})
   100  	if err != nil {
   101  		panic(err)
   102  	}
   103  	b.txs = append(b.txs, tx)
   104  	b.receipts = append(b.receipts, receipt)
   105  }
   106  
   107  // Number returns the block number of the block being generated.
   108  func (b *BlockGen) Number() *big.Int {
   109  	return new(big.Int).Set(b.header.Number)
   110  }
   111  
   112  // AddUncheckedReceipt forcefully adds a receipts to the block without a
   113  // backing transaction.
   114  //
   115  // AddUncheckedReceipt will cause consensus failures when used during real
   116  // chain processing. This is best used in conjunction with raw block insertion.
   117  func (b *BlockGen) AddUncheckedReceipt(receipt *types.Receipt) {
   118  	b.receipts = append(b.receipts, receipt)
   119  }
   120  
   121  // TxNonce returns the next valid transaction nonce for the
   122  // account at addr. It panics if the account does not exist.
   123  func (b *BlockGen) TxNonce(addr common.Address) uint64 {
   124  	if !b.statedb.Exist(addr) {
   125  		panic("account does not exist")
   126  	}
   127  	return b.statedb.GetNonce(addr)
   128  }
   129  
   130  // PrevBlock returns a previously generated block by number. It panics if
   131  // num is greater or equal to the number of the block being generated.
   132  // For index -1, PrevBlock returns the parent block given to GenerateChain.
   133  func (b *BlockGen) PrevBlock(index int) *types.Block {
   134  	if index >= b.i {
   135  		panic("block index out of range")
   136  	}
   137  	if index == -1 {
   138  		return b.parent
   139  	}
   140  	return b.chain[index]
   141  }
   142  
   143  // OffsetTime modifies the time instance of a block, implicitly changing its
   144  // associated difficulty. It's useful to test scenarios where forking is not
   145  // tied to chain length directly.
   146  func (b *BlockGen) OffsetTime(seconds int64) {
   147  	b.header.Time.Add(b.header.Time, new(big.Int).SetInt64(seconds))
   148  	if b.header.Time.Cmp(b.parent.Header().Time) <= 0 {
   149  		panic("block time out of range")
   150  	}
   151  	b.header.Difficulty = b.engine.CalcDifficulty(b.chainReader, b.header.Time.Uint64(), b.parent.Header())
   152  }
   153  
   154  // GenerateChain creates a chain of n blocks. The first block's
   155  // parent will be the provided parent. db is used to store
   156  // intermediate states and should contain the parent's state trie.
   157  //
   158  // The generator function is called with a new block generator for
   159  // every block. Any transactions added to the generator
   160  // become part of the block. If gen is nil, the blocks will be empty
   161  // and their coinbase will be the zero address.
   162  //
   163  // Blocks created by GenerateChain do not contain valid proof of work
   164  // values.
   165  func GenerateChain(config *params.ChainConfig, parent *types.Block, engine consensus.Engine, db vntdb.Database, n int, gen func(int, *BlockGen)) ([]*types.Block, []types.Receipts) {
   166  	if config == nil {
   167  		config = params.TestChainConfig
   168  	}
   169  	blocks, receipts := make(types.Blocks, n), make([]types.Receipts, n)
   170  	genblock := func(i int, parent *types.Block, statedb *state.StateDB) (*types.Block, types.Receipts) {
   171  		// It's nonetheless ugly to spin up a blockchain here. Get rid of this somehow.
   172  		blockchain, _ := NewBlockChain(db, nil, config, engine, vm.Config{})
   173  		defer blockchain.Stop()
   174  
   175  		b := &BlockGen{i: i, parent: parent, chain: blocks, chainReader: blockchain, statedb: statedb, config: config, engine: engine}
   176  		b.header = makeHeader(b.chainReader, parent, statedb, b.engine)
   177  
   178  		// Execute any user modifications to the block and finalize it
   179  		if gen != nil {
   180  			gen(i, b)
   181  		}
   182  
   183  		if b.engine != nil {
   184  			block, _ := b.engine.Finalize(b.chainReader, b.header, statedb, b.txs, b.receipts)
   185  			// Write state changes to db
   186  			root, err := statedb.Commit(true)
   187  			if err != nil {
   188  				panic(fmt.Sprintf("state write error: %v", err))
   189  			}
   190  			if err := statedb.Database().TrieDB().Commit(root, false); err != nil {
   191  				panic(fmt.Sprintf("trie write error: %v", err))
   192  			}
   193  			return block, b.receipts
   194  		}
   195  		return nil, nil
   196  	}
   197  	for i := 0; i < n; i++ {
   198  		statedb, err := state.New(parent.Root(), state.NewDatabase(db))
   199  		if err != nil {
   200  			panic(err)
   201  		}
   202  		block, receipt := genblock(i, parent, statedb)
   203  		blocks[i] = block
   204  		receipts[i] = receipt
   205  		parent = block
   206  	}
   207  	return blocks, receipts
   208  }
   209  
   210  func makeHeader(chain consensus.ChainReader, parent *types.Block, state *state.StateDB, engine consensus.Engine) *types.Header {
   211  	var time *big.Int
   212  	if parent.Time() == nil {
   213  		time = big.NewInt(10)
   214  	} else {
   215  		time = new(big.Int).Add(parent.Time(), big.NewInt(2)) // block's time interval always be 2 seconds
   216  	}
   217  
   218  	return &types.Header{
   219  		Root:       state.IntermediateRoot(true),
   220  		ParentHash: parent.Hash(),
   221  		Coinbase:   parent.Coinbase(),
   222  		Difficulty: engine.CalcDifficulty(chain, time.Uint64(), &types.Header{}),
   223  		GasLimit:   CalcGasLimit(parent),
   224  		Number:     new(big.Int).Add(parent.Number(), common.Big1),
   225  		Time:       time,
   226  	}
   227  }
   228  
   229  // newCanonical creates a chain database, and injects a deterministic canonical
   230  // chain. Depending on the full flag, if creates either a full block chain or a
   231  // header only chain.
   232  func newCanonical(engine consensus.Engine, n int, full bool) (vntdb.Database, *BlockChain, error) {
   233  	db := vntdb.NewMemDatabase()
   234  	// New genesis and write to db
   235  	g := Genesis{
   236  		Config:     params.TestChainConfig,
   237  		Timestamp:  0,
   238  		Difficulty: big.NewInt(1),
   239  		Number:     0,
   240  	}
   241  
   242  	genesis := g.MustCommit(db)
   243  
   244  	// Initialize a fresh chain with only a genesis block
   245  	blockchain, _ := NewBlockChain(db, nil, params.TestChainConfig, engine, vm.Config{})
   246  	// Create and inject the requested chain
   247  	if n == 0 {
   248  		return db, blockchain, nil
   249  	}
   250  	if full {
   251  		// Full block-chain requested
   252  		blocks := makeBlockChain(genesis, n, engine, db, canonicalSeed)
   253  		_, err := blockchain.InsertChain(blocks)
   254  		return db, blockchain, err
   255  	}
   256  	// Header-only chain requested
   257  	headers := makeHeaderChain(genesis.Header(), n, engine, db, canonicalSeed)
   258  	_, err := blockchain.InsertHeaderChain(headers, 1)
   259  	return db, blockchain, err
   260  }
   261  
   262  // makeHeaderChain creates a deterministic chain of headers rooted at parent.
   263  func makeHeaderChain(parent *types.Header, n int, engine consensus.Engine, db vntdb.Database, seed int) []*types.Header {
   264  	blocks := makeBlockChain(types.NewBlockWithHeader(parent), n, engine, db, seed)
   265  	headers := make([]*types.Header, len(blocks))
   266  	for i, block := range blocks {
   267  		headers[i] = block.Header()
   268  	}
   269  	return headers
   270  }
   271  
   272  // makeBlockChain creates a deterministic chain of blocks rooted at parent.
   273  func makeBlockChain(parent *types.Block, n int, engine consensus.Engine, db vntdb.Database, seed int) []*types.Block {
   274  	blocks, _ := GenerateChain(params.TestChainConfig, parent, engine, db, n, func(i int, b *BlockGen) {
   275  		b.SetCoinbase(common.Address{0: byte(seed), 19: byte(i)})
   276  	})
   277  	return blocks
   278  }