github.com/etherite/go-etherite@v0.0.0-20171015192807-5f4dd87b2f6e/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/etherite/go-etherite/common" 24 "github.com/etherite/go-etherite/consensus/ethash" 25 "github.com/etherite/go-etherite/consensus/misc" 26 "github.com/etherite/go-etherite/core/state" 27 "github.com/etherite/go-etherite/core/types" 28 "github.com/etherite/go-etherite/core/vm" 29 "github.com/etherite/go-etherite/ethdb" 30 "github.com/etherite/go-etherite/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 header *types.Header 46 statedb *state.StateDB 47 48 gasPool *GasPool 49 txs []*types.Transaction 50 receipts []*types.Receipt 51 uncles []*types.Header 52 53 config *params.ChainConfig 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 if b.gasPool == nil { 84 b.SetCoinbase(common.Address{}) 85 } 86 b.statedb.Prepare(tx.Hash(), common.Hash{}, len(b.txs)) 87 receipt, _, err := ApplyTransaction(b.config, nil, &b.header.Coinbase, b.gasPool, b.statedb, b.header, tx, b.header.GasUsed, vm.Config{}) 88 if err != nil { 89 panic(err) 90 } 91 b.txs = append(b.txs, tx) 92 b.receipts = append(b.receipts, receipt) 93 } 94 95 // Number returns the block number of the block being generated. 96 func (b *BlockGen) Number() *big.Int { 97 return new(big.Int).Set(b.header.Number) 98 } 99 100 // AddUncheckedReceipt forcefully adds a receipts to the block without a 101 // backing transaction. 102 // 103 // AddUncheckedReceipt will cause consensus failures when used during real 104 // chain processing. This is best used in conjunction with raw block insertion. 105 func (b *BlockGen) AddUncheckedReceipt(receipt *types.Receipt) { 106 b.receipts = append(b.receipts, receipt) 107 } 108 109 // TxNonce returns the next valid transaction nonce for the 110 // account at addr. It panics if the account does not exist. 111 func (b *BlockGen) TxNonce(addr common.Address) uint64 { 112 if !b.statedb.Exist(addr) { 113 panic("account does not exist") 114 } 115 return b.statedb.GetNonce(addr) 116 } 117 118 // AddUncle adds an uncle header to the generated block. 119 func (b *BlockGen) AddUncle(h *types.Header) { 120 b.uncles = append(b.uncles, h) 121 } 122 123 // PrevBlock returns a previously generated block by number. It panics if 124 // num is greater or equal to the number of the block being generated. 125 // For index -1, PrevBlock returns the parent block given to GenerateChain. 126 func (b *BlockGen) PrevBlock(index int) *types.Block { 127 if index >= b.i { 128 panic("block index out of range") 129 } 130 if index == -1 { 131 return b.parent 132 } 133 return b.chain[index] 134 } 135 136 // OffsetTime modifies the time instance of a block, implicitly changing its 137 // associated difficulty. It's useful to test scenarios where forking is not 138 // tied to chain length directly. 139 func (b *BlockGen) OffsetTime(seconds int64) { 140 b.header.Time.Add(b.header.Time, new(big.Int).SetInt64(seconds)) 141 if b.header.Time.Cmp(b.parent.Header().Time) <= 0 { 142 panic("block time out of range") 143 } 144 b.header.Difficulty = ethash.CalcDifficulty(b.config, b.header.Time.Uint64(), b.parent.Header()) 145 } 146 147 // GenerateChain creates a chain of n blocks. The first block's 148 // parent will be the provided parent. db is used to store 149 // intermediate states and should contain the parent's state trie. 150 // 151 // The generator function is called with a new block generator for 152 // every block. Any transactions and uncles added to the generator 153 // become part of the block. If gen is nil, the blocks will be empty 154 // and their coinbase will be the zero address. 155 // 156 // Blocks created by GenerateChain do not contain valid proof of work 157 // values. Inserting them into BlockChain requires use of FakePow or 158 // a similar non-validating proof of work implementation. 159 func GenerateChain(config *params.ChainConfig, parent *types.Block, db ethdb.Database, n int, gen func(int, *BlockGen)) ([]*types.Block, []types.Receipts) { 160 if config == nil { 161 config = params.TestChainConfig 162 } 163 blocks, receipts := make(types.Blocks, n), make([]types.Receipts, n) 164 genblock := func(i int, h *types.Header, statedb *state.StateDB) (*types.Block, types.Receipts) { 165 b := &BlockGen{parent: parent, i: i, chain: blocks, header: h, statedb: statedb, config: config} 166 // Mutate the state and block according to any hard-fork specs 167 if daoBlock := config.DAOForkBlock; daoBlock != nil { 168 limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange) 169 if h.Number.Cmp(daoBlock) >= 0 && h.Number.Cmp(limit) < 0 { 170 if config.DAOForkSupport { 171 h.Extra = common.CopyBytes(params.DAOForkBlockExtra) 172 } 173 } 174 } 175 if config.DAOForkSupport && config.DAOForkBlock != nil && config.DAOForkBlock.Cmp(h.Number) == 0 { 176 misc.ApplyDAOHardFork(statedb) 177 } 178 // Execute any user modifications to the block and finalize it 179 if gen != nil { 180 gen(i, b) 181 } 182 ethash.AccumulateRewards(config, statedb, h, b.uncles) 183 root, err := statedb.CommitTo(db, config.IsEIP158(h.Number)) 184 if err != nil { 185 panic(fmt.Sprintf("state write error: %v", err)) 186 } 187 h.Root = root 188 return types.NewBlock(h, b.txs, b.uncles, b.receipts), b.receipts 189 } 190 for i := 0; i < n; i++ { 191 statedb, err := state.New(parent.Root(), state.NewDatabase(db)) 192 if err != nil { 193 panic(err) 194 } 195 header := makeHeader(config, parent, statedb) 196 block, receipt := genblock(i, header, statedb) 197 blocks[i] = block 198 receipts[i] = receipt 199 parent = block 200 } 201 return blocks, receipts 202 } 203 204 func makeHeader(config *params.ChainConfig, parent *types.Block, state *state.StateDB) *types.Header { 205 var time *big.Int 206 if parent.Time() == nil { 207 time = big.NewInt(10) 208 } else { 209 time = new(big.Int).Add(parent.Time(), big.NewInt(10)) // block time is fixed at 10 seconds 210 } 211 212 return &types.Header{ 213 Root: state.IntermediateRoot(config.IsEIP158(parent.Number())), 214 ParentHash: parent.Hash(), 215 Coinbase: parent.Coinbase(), 216 Difficulty: ethash.CalcDifficulty(config, time.Uint64(), &types.Header{ 217 Number: parent.Number(), 218 Time: new(big.Int).Sub(time, big.NewInt(10)), 219 Difficulty: parent.Difficulty(), 220 UncleHash: parent.UncleHash(), 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(), 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 }