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