github.com/aquanetwork/aquachain@v1.7.8/core/chain_makers.go (about)

     1  // Copyright 2015 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  // So we can deterministically seed different blockchains
    34  var (
    35  	canonicalSeed = 1
    36  	forkSeed      = 2
    37  )
    38  
    39  // BlockGen creates blocks for testing.
    40  // See GenerateChain for a detailed explanation.
    41  type BlockGen struct {
    42  	i           int
    43  	parent      *types.Block
    44  	chain       []*types.Block
    45  	chainReader consensus.ChainReader
    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  	engine consensus.Engine
    56  }
    57  
    58  // SetCoinbase sets the coinbase of the generated block.
    59  // It can be called at most once.
    60  func (b *BlockGen) SetCoinbase(addr common.Address) {
    61  	if b.gasPool != nil {
    62  		if len(b.txs) > 0 {
    63  			panic("coinbase must be set before adding transactions")
    64  		}
    65  		panic("coinbase can only be set once")
    66  	}
    67  	b.header.Coinbase = addr
    68  	b.gasPool = new(GasPool).AddGas(b.header.GasLimit)
    69  }
    70  
    71  // Setversion sets the header version
    72  func (b *BlockGen) SetVersion(version params.HeaderVersion) {
    73  	b.header.Version = version
    74  }
    75  
    76  // SetExtra sets the extra data field of the generated block.
    77  func (b *BlockGen) SetExtra(data []byte) {
    78  	b.header.Extra = data
    79  }
    80  
    81  // AddTx adds a transaction to the generated block. If no coinbase has
    82  // been set, the block's coinbase is set to the zero address.
    83  //
    84  // AddTx panics if the transaction cannot be executed. In addition to
    85  // the protocol-imposed limitations (gas limit, etc.), there are some
    86  // further limitations on the content of transactions that can be
    87  // added. Notably, contract code relying on the BLOCKHASH instruction
    88  // will panic during execution.
    89  func (b *BlockGen) AddTx(tx *types.Transaction) {
    90  	if b.gasPool == nil {
    91  		b.SetCoinbase(common.Address{})
    92  	}
    93  	b.statedb.Prepare(tx.Hash(), common.Hash{}, len(b.txs))
    94  	receipt, _, err := ApplyTransaction(b.config, nil, &b.header.Coinbase, b.gasPool, b.statedb, b.header, tx, &b.header.GasUsed, vm.Config{})
    95  	if err != nil {
    96  		panic(err)
    97  	}
    98  	b.txs = append(b.txs, tx)
    99  	b.receipts = append(b.receipts, receipt)
   100  }
   101  
   102  // Number returns the block number of the block being generated.
   103  func (b *BlockGen) Number() *big.Int {
   104  	return new(big.Int).Set(b.header.Number)
   105  }
   106  
   107  // AddUncheckedReceipt forcefully adds a receipts to the block without a
   108  // backing transaction.
   109  //
   110  // AddUncheckedReceipt will cause consensus failures when used during real
   111  // chain processing. This is best used in conjunction with raw block insertion.
   112  func (b *BlockGen) AddUncheckedReceipt(receipt *types.Receipt) {
   113  	b.receipts = append(b.receipts, receipt)
   114  }
   115  
   116  // TxNonce returns the next valid transaction nonce for the
   117  // account at addr. It panics if the account does not exist.
   118  func (b *BlockGen) TxNonce(addr common.Address) uint64 {
   119  	if !b.statedb.Exist(addr) {
   120  		panic("account does not exist")
   121  	}
   122  	return b.statedb.GetNonce(addr)
   123  }
   124  
   125  // AddUncle adds an uncle header to the generated block.
   126  func (b *BlockGen) AddUncle(h *types.Header) {
   127  	b.uncles = append(b.uncles, h)
   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(), nil)
   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 and uncles 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. Inserting them into BlockChain requires use of FakePow or
   165  // a similar non-validating proof of work implementation.
   166  func GenerateChain(config *params.ChainConfig, parent *types.Block, engine consensus.Engine, db aquadb.Database, n int, gen func(int, *BlockGen)) ([]*types.Block, []types.Receipts) {
   167  	if config == nil {
   168  		config = params.TestChainConfig
   169  	}
   170  	blocks, receipts := make(types.Blocks, n), make([]types.Receipts, n)
   171  	genblock := func(i int, parent *types.Block, statedb *state.StateDB) (*types.Block, types.Receipts) {
   172  		// TODO(karalabe): This is needed for clique, which depends on multiple blocks.
   173  		// It's nonetheless ugly to spin up a blockchain here. Get rid of this somehow.
   174  		blockchain, _ := NewBlockChain(db, nil, config, engine, vm.Config{})
   175  		defer blockchain.Stop()
   176  
   177  		b := &BlockGen{i: i, parent: parent, chain: blocks, chainReader: blockchain, statedb: statedb, config: config, engine: engine}
   178  		b.header = makeHeader(b.chainReader, parent, statedb, b.engine)
   179  		// Mutate the the block and state according to any hard-fork specs
   180  		if hf4 := config.GetHF(4); hf4 != nil && hf4.Cmp(b.header.Number) == 0 {
   181  			misc.ApplyHardFork4(statedb)
   182  		}
   183  		if hf5 := config.GetHF(5); hf5 != nil && hf5.Cmp(b.header.Number) == 0 {
   184  			misc.ApplyHardFork5(statedb)
   185  		}
   186  		// Execute any user modifications to the block and finalize it
   187  		if gen != nil {
   188  			gen(i, b)
   189  		}
   190  
   191  		if b.engine != nil {
   192  			block, _ := b.engine.Finalize(b.chainReader, b.header, statedb, b.txs, b.uncles, b.receipts)
   193  			// Write state changes to db
   194  			root, err := statedb.Commit(config.IsEIP158(b.header.Number))
   195  			if err != nil {
   196  				panic(fmt.Sprintf("state write error: %v", err))
   197  			}
   198  			if err := statedb.Database().TrieDB().Commit(root, false); err != nil {
   199  				panic(fmt.Sprintf("trie write error: %v", err))
   200  			}
   201  			return block, b.receipts
   202  		}
   203  		return nil, nil
   204  	} // end of genblock()
   205  	for i := 0; i < n; i++ {
   206  		statedb, err := state.New(parent.Root(), state.NewDatabase(db))
   207  		if err != nil {
   208  			panic(err)
   209  		}
   210  		block, receipt := genblock(i, parent, statedb)
   211  		blocks[i] = block
   212  		receipts[i] = receipt
   213  		parent = block
   214  	}
   215  	return blocks, receipts
   216  }
   217  
   218  func makeHeader(chain consensus.ChainReader, parent *types.Block, state *state.StateDB, engine consensus.Engine) *types.Header {
   219  	if parent.Version() == 0 {
   220  		parent.SetVersion(chain.Config().GetBlockVersion(parent.Number()))
   221  	}
   222  	var time *big.Int
   223  	if parent.Time() == nil {
   224  		time = big.NewInt(240)
   225  	} else {
   226  		time = new(big.Int).Add(parent.Time(), big.NewInt(240)) // block time is fixed at 10 seconds
   227  	}
   228  	num := new(big.Int).Add(parent.Number(), common.Big1)
   229  	return &types.Header{
   230  		Root:       state.IntermediateRoot(chain.Config().IsEIP158(num)),
   231  		ParentHash: parent.Hash(),
   232  		Coinbase:   parent.Coinbase(),
   233  		Difficulty: engine.CalcDifficulty(chain, time.Uint64(), &types.Header{
   234  			Number:     parent.Number(),
   235  			Time:       new(big.Int).Sub(time, big.NewInt(240)), // parent time
   236  			Difficulty: parent.Difficulty(),
   237  			UncleHash:  parent.UncleHash(),
   238  		}, nil),
   239  		GasLimit: CalcGasLimit(parent),
   240  		Number:   num,
   241  		Time:     time,
   242  		Version:  chain.Config().GetBlockVersion(num),
   243  	}
   244  }
   245  
   246  // newCanonical creates a chain database, and injects a deterministic canonical
   247  // chain. Depending on the full flag, if creates either a full block chain or a
   248  // header only chain.
   249  func newCanonical(engine consensus.Engine, n int, full bool) (aquadb.Database, *BlockChain, error) {
   250  	// Initialize a fresh chain with only a genesis block
   251  	gspec := new(Genesis)
   252  	db := aquadb.NewMemDatabase()
   253  	genesis := gspec.MustCommit(db)
   254  
   255  	blockchain, _ := NewBlockChain(db, nil, params.AllAquahashProtocolChanges, engine, vm.Config{})
   256  	// Create and inject the requested chain
   257  	if n == 0 {
   258  		return db, blockchain, nil
   259  	}
   260  	if full {
   261  		// Full block-chain requested
   262  		blocks := makeBlockChain(genesis, n, engine, db, canonicalSeed)
   263  		_, err := blockchain.InsertChain(blocks)
   264  		return db, blockchain, err
   265  	}
   266  	// Header-only chain requested
   267  	headers := makeHeaderChain(genesis.Header(), n, engine, db, canonicalSeed)
   268  	_, err := blockchain.InsertHeaderChain(headers, 1)
   269  	return db, blockchain, err
   270  }
   271  
   272  // makeHeaderChain creates a deterministic chain of headers rooted at parent.
   273  func makeHeaderChain(parent *types.Header, n int, engine consensus.Engine, db aquadb.Database, seed int) []*types.Header {
   274  	blocks := makeBlockChain(types.NewBlockWithHeader(parent), n, engine, db, seed)
   275  	headers := make([]*types.Header, len(blocks))
   276  	for i, block := range blocks {
   277  		headers[i] = block.Header()
   278  		headers[i].Version = params.TestChainConfig.GetBlockVersion(headers[i].Number)
   279  	}
   280  	return headers
   281  }
   282  
   283  // makeBlockChain creates a deterministic chain of blocks rooted at parent.
   284  func makeBlockChain(parent *types.Block, n int, engine consensus.Engine, db aquadb.Database, seed int) []*types.Block {
   285  	blocks, _ := GenerateChain(params.TestChainConfig, parent, engine, db, n, func(i int, b *BlockGen) {
   286  		b.header.Version = b.config.GetBlockVersion(b.Number())
   287  		b.SetCoinbase(common.Address{0: byte(seed), 19: byte(i)})
   288  	})
   289  	return blocks
   290  }