github.com/alanchchen/go-ethereum@v1.6.6-0.20170601190819-6171d01b1195/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/ethereum/go-ethereum/common" 24 "github.com/ethereum/go-ethereum/consensus/ethash" 25 "github.com/ethereum/go-ethereum/consensus/misc" 26 "github.com/ethereum/go-ethereum/core/state" 27 "github.com/ethereum/go-ethereum/core/types" 28 "github.com/ethereum/go-ethereum/core/vm" 29 "github.com/ethereum/go-ethereum/ethdb" 30 "github.com/ethereum/go-ethereum/event" 31 "github.com/ethereum/go-ethereum/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, &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.TestChainConfig 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 ethash.AccumulateRewards(statedb, h, b.uncles) 184 root, err := statedb.Commit(config.IsEIP158(h.Number)) 185 if err != nil { 186 panic(fmt.Sprintf("state write error: %v", err)) 187 } 188 h.Root = root 189 return types.NewBlock(h, b.txs, b.uncles, b.receipts), b.receipts 190 } 191 for i := 0; i < n; i++ { 192 statedb, err := state.New(parent.Root(), db) 193 if err != nil { 194 panic(err) 195 } 196 header := makeHeader(config, parent, statedb) 197 block, receipt := genblock(i, header, statedb) 198 blocks[i] = block 199 receipts[i] = receipt 200 parent = block 201 } 202 return blocks, receipts 203 } 204 205 func makeHeader(config *params.ChainConfig, parent *types.Block, state *state.StateDB) *types.Header { 206 var time *big.Int 207 if parent.Time() == nil { 208 time = big.NewInt(10) 209 } else { 210 time = new(big.Int).Add(parent.Time(), big.NewInt(10)) // block time is fixed at 10 seconds 211 } 212 213 return &types.Header{ 214 Root: state.IntermediateRoot(config.IsEIP158(parent.Number())), 215 ParentHash: parent.Hash(), 216 Coinbase: parent.Coinbase(), 217 Difficulty: ethash.CalcDifficulty(config, time.Uint64(), &types.Header{ 218 Number: parent.Number(), 219 Time: new(big.Int).Sub(time, big.NewInt(10)), 220 Difficulty: parent.Difficulty(), 221 }), 222 GasLimit: CalcGasLimit(parent), 223 GasUsed: new(big.Int), 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(n int, full bool) (ethdb.Database, *BlockChain, error) { 233 // Initialize a fresh chain with only a genesis block 234 gspec := new(Genesis) 235 db, _ := ethdb.NewMemDatabase() 236 genesis := gspec.MustCommit(db) 237 238 blockchain, _ := NewBlockChain(db, params.AllProtocolChanges, ethash.NewFaker(), new(event.TypeMux), vm.Config{}) 239 // Create and inject the requested chain 240 if n == 0 { 241 return db, blockchain, nil 242 } 243 if full { 244 // Full block-chain requested 245 blocks := makeBlockChain(genesis, n, db, canonicalSeed) 246 _, err := blockchain.InsertChain(blocks) 247 return db, blockchain, err 248 } 249 // Header-only chain requested 250 headers := makeHeaderChain(genesis.Header(), n, db, canonicalSeed) 251 _, err := blockchain.InsertHeaderChain(headers, 1) 252 return db, blockchain, err 253 } 254 255 // makeHeaderChain creates a deterministic chain of headers rooted at parent. 256 func makeHeaderChain(parent *types.Header, n int, db ethdb.Database, seed int) []*types.Header { 257 blocks := makeBlockChain(types.NewBlockWithHeader(parent), n, db, seed) 258 headers := make([]*types.Header, len(blocks)) 259 for i, block := range blocks { 260 headers[i] = block.Header() 261 } 262 return headers 263 } 264 265 // makeBlockChain creates a deterministic chain of blocks rooted at parent. 266 func makeBlockChain(parent *types.Block, n int, db ethdb.Database, seed int) []*types.Block { 267 blocks, _ := GenerateChain(params.TestChainConfig, parent, db, n, func(i int, b *BlockGen) { 268 b.SetCoinbase(common.Address{0: byte(seed), 19: byte(i)}) 269 }) 270 return blocks 271 }