github.com/ebceco/ebc@v1.8.19-0.20190309150932-8cb0b9e06484/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/ebceco/ebc/common" 24 "github.com/ebceco/ebc/consensus" 25 "github.com/ebceco/ebc/consensus/misc" 26 "github.com/ebceco/ebc/core/state" 27 "github.com/ebceco/ebc/core/types" 28 "github.com/ebceco/ebc/core/vm" 29 "github.com/ebceco/ebc/ethdb" 30 "github.com/ebceco/ebc/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 header *types.Header 40 statedb *state.StateDB 41 42 gasPool *GasPool 43 txs []*types.Transaction 44 receipts []*types.Receipt 45 uncles []*types.Header 46 47 config *params.ChainConfig 48 engine consensus.Engine 49 } 50 51 // SetCoinbase sets the coinbase of the generated block. 52 // It can be called at most once. 53 func (b *BlockGen) SetCoinbase(addr common.Address) { 54 if b.gasPool != nil { 55 if len(b.txs) > 0 { 56 panic("coinbase must be set before adding transactions") 57 } 58 panic("coinbase can only be set once") 59 } 60 b.header.Coinbase = addr 61 b.gasPool = new(GasPool).AddGas(b.header.GasLimit) 62 } 63 64 // SetExtra sets the extra data field of the generated block. 65 func (b *BlockGen) SetExtra(data []byte) { 66 b.header.Extra = data 67 } 68 69 // SetNonce sets the nonce field of the generated block. 70 func (b *BlockGen) SetNonce(nonce types.BlockNonce) { 71 b.header.Nonce = nonce 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 b.AddTxWithChain(nil, tx) 84 } 85 86 // AddTxWithChain adds a transaction to the generated block. If no coinbase has 87 // been set, the block's coinbase is set to the zero address. 88 // 89 // AddTxWithChain panics if the transaction cannot be executed. In addition to 90 // the protocol-imposed limitations (gas limit, etc.), there are some 91 // further limitations on the content of transactions that can be 92 // added. If contract code relies on the BLOCKHASH instruction, 93 // the block in chain will be returned. 94 func (b *BlockGen) AddTxWithChain(bc *BlockChain, tx *types.Transaction) { 95 if b.gasPool == nil { 96 b.SetCoinbase(common.Address{}) 97 } 98 b.statedb.Prepare(tx.Hash(), common.Hash{}, len(b.txs)) 99 receipt, _, err := ApplyTransaction(b.config, bc, &b.header.Coinbase, b.gasPool, b.statedb, b.header, tx, &b.header.GasUsed, vm.Config{}) 100 if err != nil { 101 panic(err) 102 } 103 b.txs = append(b.txs, tx) 104 b.receipts = append(b.receipts, receipt) 105 } 106 107 // Number returns the block number of the block being generated. 108 func (b *BlockGen) Number() *big.Int { 109 return new(big.Int).Set(b.header.Number) 110 } 111 112 // AddUncheckedReceipt forcefully adds a receipts to the block without a 113 // backing transaction. 114 // 115 // AddUncheckedReceipt will cause consensus failures when used during real 116 // chain processing. This is best used in conjunction with raw block insertion. 117 func (b *BlockGen) AddUncheckedReceipt(receipt *types.Receipt) { 118 b.receipts = append(b.receipts, receipt) 119 } 120 121 // TxNonce returns the next valid transaction nonce for the 122 // account at addr. It panics if the account does not exist. 123 func (b *BlockGen) TxNonce(addr common.Address) uint64 { 124 if !b.statedb.Exist(addr) { 125 panic("account does not exist") 126 } 127 return b.statedb.GetNonce(addr) 128 } 129 130 // AddUncle adds an uncle header to the generated block. 131 func (b *BlockGen) AddUncle(h *types.Header) { 132 b.uncles = append(b.uncles, h) 133 } 134 135 // PrevBlock returns a previously generated block by number. It panics if 136 // num is greater or equal to the number of the block being generated. 137 // For index -1, PrevBlock returns the parent block given to GenerateChain. 138 func (b *BlockGen) PrevBlock(index int) *types.Block { 139 if index >= b.i { 140 panic(fmt.Errorf("block index %d out of range (%d,%d)", index, -1, b.i)) 141 } 142 if index == -1 { 143 return b.parent 144 } 145 return b.chain[index] 146 } 147 148 // OffsetTime modifies the time instance of a block, implicitly changing its 149 // associated difficulty. It's useful to test scenarios where forking is not 150 // tied to chain length directly. 151 func (b *BlockGen) OffsetTime(seconds int64) { 152 b.header.Time.Add(b.header.Time, new(big.Int).SetInt64(seconds)) 153 if b.header.Time.Cmp(b.parent.Header().Time) <= 0 { 154 panic("block time out of range") 155 } 156 chainreader := &fakeChainReader{config: b.config} 157 b.header.Difficulty = b.engine.CalcDifficulty(chainreader, b.header.Time.Uint64(), b.parent.Header()) 158 } 159 160 // GenerateChain creates a chain of n blocks. The first block's 161 // parent will be the provided parent. db is used to store 162 // intermediate states and should contain the parent's state trie. 163 // 164 // The generator function is called with a new block generator for 165 // every block. Any transactions and uncles added to the generator 166 // become part of the block. If gen is nil, the blocks will be empty 167 // and their coinbase will be the zero address. 168 // 169 // Blocks created by GenerateChain do not contain valid proof of work 170 // values. Inserting them into BlockChain requires use of FakePow or 171 // a similar non-validating proof of work implementation. 172 func GenerateChain(config *params.ChainConfig, parent *types.Block, engine consensus.Engine, db ethdb.Database, n int, gen func(int, *BlockGen)) ([]*types.Block, []types.Receipts) { 173 if config == nil { 174 config = params.TestChainConfig 175 } 176 blocks, receipts := make(types.Blocks, n), make([]types.Receipts, n) 177 chainreader := &fakeChainReader{config: config} 178 genblock := func(i int, parent *types.Block, statedb *state.StateDB) (*types.Block, types.Receipts) { 179 b := &BlockGen{i: i, chain: blocks, parent: parent, statedb: statedb, config: config, engine: engine} 180 b.header = makeHeader(chainreader, parent, statedb, b.engine) 181 182 // Mutate the state and block according to any hard-fork specs 183 if daoBlock := config.DAOForkBlock; daoBlock != nil { 184 limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange) 185 if b.header.Number.Cmp(daoBlock) >= 0 && b.header.Number.Cmp(limit) < 0 { 186 if config.DAOForkSupport { 187 b.header.Extra = common.CopyBytes(params.DAOForkBlockExtra) 188 } 189 } 190 } 191 if config.DAOForkSupport && config.DAOForkBlock != nil && config.DAOForkBlock.Cmp(b.header.Number) == 0 { 192 misc.ApplyDAOHardFork(statedb) 193 } 194 // Execute any user modifications to the block 195 if gen != nil { 196 gen(i, b) 197 } 198 if b.engine != nil { 199 // Finalize and seal the block 200 block, _ := b.engine.Finalize(chainreader, b.header, statedb, b.txs, b.uncles, b.receipts) 201 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 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, func(i int, b *BlockGen) { 264 b.SetCoinbase(common.Address{0: byte(seed), 19: byte(i)}) 265 }) 266 return blocks 267 } 268 269 type fakeChainReader struct { 270 config *params.ChainConfig 271 genesis *types.Block 272 } 273 274 // Config returns the chain configuration. 275 func (cr *fakeChainReader) Config() *params.ChainConfig { 276 return cr.config 277 } 278 279 func (cr *fakeChainReader) CurrentHeader() *types.Header { return nil } 280 func (cr *fakeChainReader) GetHeaderByNumber(number uint64) *types.Header { return nil } 281 func (cr *fakeChainReader) GetHeaderByHash(hash common.Hash) *types.Header { return nil } 282 func (cr *fakeChainReader) GetHeader(hash common.Hash, number uint64) *types.Header { return nil } 283 func (cr *fakeChainReader) GetBlock(hash common.Hash, number uint64) *types.Block { return nil }