github.com/Elemental-core/elementalcore@v0.0.0-20191206075037-63891242267a/core/chain_makers.go (about)

     1  // Copyright 2015 The elementalcore Authors
     2  // This file is part of the elementalcore library.
     3  //
     4  // The elementalcore 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 elementalcore 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 elementalcore 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/Elemental-core/elementalcore/common"
    24  	"github.com/Elemental-core/elementalcore/consensus/dpos"
    25  	"github.com/Elemental-core/elementalcore/consensus/ethash"
    26  	"github.com/Elemental-core/elementalcore/consensus/misc"
    27  	"github.com/Elemental-core/elementalcore/core/state"
    28  	"github.com/Elemental-core/elementalcore/core/types"
    29  	"github.com/Elemental-core/elementalcore/core/vm"
    30  	"github.com/Elemental-core/elementalcore/ethdb"
    31  	"github.com/Elemental-core/elementalcore/params"
    32  )
    33  
    34  // So we can deterministically seed different blockchains
    35  var (
    36  	canonicalSeed = 1
    37  	forkSeed      = 2
    38  )
    39  
    40  // BlockGen creates blocks for testing.
    41  // See GenerateChain for a detailed explanation.
    42  type BlockGen struct {
    43  	i       int
    44  	parent  *types.Block
    45  	chain   []*types.Block
    46  	header  *types.Header
    47  	statedb *state.StateDB
    48  
    49  	gasPool  *GasPool
    50  	txs      []*types.Transaction
    51  	receipts []*types.Receipt
    52  	uncles   []*types.Header
    53  
    54  	config *params.ChainConfig
    55  }
    56  
    57  // SetCoinbase sets the coinbase of the generated block.
    58  // It can be called at most once.
    59  func (b *BlockGen) SetCoinbase(addr common.Address) {
    60  	if b.gasPool != nil {
    61  		if len(b.txs) > 0 {
    62  			panic("coinbase must be set before adding transactions")
    63  		}
    64  		panic("coinbase can only be set once")
    65  	}
    66  	b.header.Coinbase = addr
    67  	b.gasPool = new(GasPool).AddGas(b.header.GasLimit)
    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, 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 = ethash.CalcDifficulty(b.config, b.header.Time.Uint64(), b.parent.Header())
   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, db ethdb.Database, n int, gen func(int, *BlockGen)) ([]*types.Block, []types.Receipts) {
   161  	if config == nil {
   162  		config = params.DposChainConfig
   163  	}
   164  	blocks, receipts := make(types.Blocks, n), make([]types.Receipts, n)
   165  	genblock := func(i int, h *types.Header, statedb *state.StateDB) (*types.Block, types.Receipts) {
   166  		b := &BlockGen{parent: parent, i: i, chain: blocks, header: h, statedb: statedb, config: config}
   167  		// Mutate the state and block according to any hard-fork specs
   168  		if daoBlock := config.DAOForkBlock; daoBlock != nil {
   169  			limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange)
   170  			if h.Number.Cmp(daoBlock) >= 0 && h.Number.Cmp(limit) < 0 {
   171  				if config.DAOForkSupport {
   172  					h.Extra = common.CopyBytes(params.DAOForkBlockExtra)
   173  				}
   174  			}
   175  		}
   176  		if config.DAOForkSupport && config.DAOForkBlock != nil && config.DAOForkBlock.Cmp(h.Number) == 0 {
   177  			misc.ApplyDAOHardFork(statedb)
   178  		}
   179  		// Execute any user modifications to the block and finalize it
   180  		if gen != nil {
   181  			gen(i, b)
   182  		}
   183  		dpos.AccumulateRewards(config, statedb, h, b.uncles)
   184  		root, err := statedb.CommitTo(db, config.IsEIP158(h.Number))
   185  		if err != nil {
   186  			panic(fmt.Sprintf("state write error: %v", err))
   187  		}
   188  		h.Root = root
   189  		h.DposContext = parent.Header().DposContext
   190  		return types.NewBlock(h, b.txs, b.uncles, b.receipts), b.receipts
   191  	}
   192  	for i := 0; i < n; i++ {
   193  		statedb, err := state.New(parent.Root(), state.NewDatabase(db))
   194  		if err != nil {
   195  			panic(err)
   196  		}
   197  		header := makeHeader(config, parent, statedb)
   198  		block, receipt := genblock(i, header, statedb)
   199  		blocks[i] = block
   200  		receipts[i] = receipt
   201  		parent = block
   202  	}
   203  	return blocks, receipts
   204  }
   205  
   206  func makeHeader(config *params.ChainConfig, parent *types.Block, state *state.StateDB) *types.Header {
   207  	var time *big.Int
   208  	if parent.Time() == nil {
   209  		time = big.NewInt(10)
   210  	} else {
   211  		time = new(big.Int).Add(parent.Time(), big.NewInt(10)) // block time is fixed at 10 seconds
   212  	}
   213  
   214  	return &types.Header{
   215  		Root:        state.IntermediateRoot(config.IsEIP158(parent.Number())),
   216  		ParentHash:  parent.Hash(),
   217  		Coinbase:    parent.Coinbase(),
   218  		Difficulty:  parent.Difficulty(),
   219  		DposContext: &types.DposContextProto{},
   220  		GasLimit:    CalcGasLimit(parent),
   221  		GasUsed:     new(big.Int),
   222  		Number:      new(big.Int).Add(parent.Number(), common.Big1),
   223  		Time:        time,
   224  	}
   225  }
   226  
   227  // newCanonical creates a chain database, and injects a deterministic canonical
   228  // chain. Depending on the full flag, if creates either a full block chain or a
   229  // header only chain.
   230  func newCanonical(n int, full bool) (ethdb.Database, *BlockChain, error) {
   231  	// Initialize a fresh chain with only a genesis block
   232  	gspec := new(Genesis)
   233  	db, _ := ethdb.NewMemDatabase()
   234  	genesis := gspec.MustCommit(db)
   235  
   236  	blockchain, _ := NewBlockChain(db, params.AllEthashProtocolChanges, ethash.NewFaker(), vm.Config{})
   237  	// Create and inject the requested chain
   238  	if n == 0 {
   239  		return db, blockchain, nil
   240  	}
   241  	if full {
   242  		// Full block-chain requested
   243  		blocks := makeBlockChain(genesis, n, db, canonicalSeed)
   244  		_, err := blockchain.InsertChain(blocks)
   245  		return db, blockchain, err
   246  	}
   247  	// Header-only chain requested
   248  	headers := makeHeaderChain(genesis.Header(), n, db, canonicalSeed)
   249  	_, err := blockchain.InsertHeaderChain(headers, 1)
   250  	return db, blockchain, err
   251  }
   252  
   253  // makeHeaderChain creates a deterministic chain of headers rooted at parent.
   254  func makeHeaderChain(parent *types.Header, n int, db ethdb.Database, seed int) []*types.Header {
   255  	blocks := makeBlockChain(types.NewBlockWithHeader(parent), n, db, seed)
   256  	headers := make([]*types.Header, len(blocks))
   257  	for i, block := range blocks {
   258  		headers[i] = block.Header()
   259  	}
   260  	return headers
   261  }
   262  
   263  // makeBlockChain creates a deterministic chain of blocks rooted at parent.
   264  func makeBlockChain(parent *types.Block, n int, db ethdb.Database, seed int) []*types.Block {
   265  	blocks, _ := GenerateChain(params.DposChainConfig, parent, db, n, func(i int, b *BlockGen) {
   266  		b.SetCoinbase(common.Address{0: byte(seed), 19: byte(i)})
   267  	})
   268  	return blocks
   269  }