gitlab.com/flarenetwork/coreth@v0.1.1/core/chain_makers.go (about) 1 // (c) 2019-2020, Ava Labs, Inc. 2 // 3 // This file is a derived work, based on the go-ethereum library whose original 4 // notices appear below. 5 // 6 // It is distributed under a license compatible with the licensing terms of the 7 // original code from which it is derived. 8 // 9 // Much love to the original authors for their work. 10 // ********** 11 // Copyright 2015 The go-ethereum Authors 12 // This file is part of the go-ethereum library. 13 // 14 // The go-ethereum library is free software: you can redistribute it and/or modify 15 // it under the terms of the GNU Lesser General Public License as published by 16 // the Free Software Foundation, either version 3 of the License, or 17 // (at your option) any later version. 18 // 19 // The go-ethereum library is distributed in the hope that it will be useful, 20 // but WITHOUT ANY WARRANTY; without even the implied warranty of 21 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 22 // GNU Lesser General Public License for more details. 23 // 24 // You should have received a copy of the GNU Lesser General Public License 25 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 26 27 package core 28 29 import ( 30 "fmt" 31 "math/big" 32 33 "github.com/ethereum/go-ethereum/common" 34 "github.com/ethereum/go-ethereum/ethdb" 35 "gitlab.com/flarenetwork/coreth/consensus" 36 "gitlab.com/flarenetwork/coreth/consensus/dummy" 37 "gitlab.com/flarenetwork/coreth/consensus/misc" 38 "gitlab.com/flarenetwork/coreth/core/state" 39 "gitlab.com/flarenetwork/coreth/core/types" 40 "gitlab.com/flarenetwork/coreth/core/vm" 41 "gitlab.com/flarenetwork/coreth/params" 42 ) 43 44 // BlockGen creates blocks for testing. 45 // See GenerateChain for a detailed explanation. 46 type BlockGen struct { 47 i int 48 parent *types.Block 49 chain []*types.Block 50 header *types.Header 51 statedb *state.StateDB 52 53 gasPool *GasPool 54 txs []*types.Transaction 55 receipts []*types.Receipt 56 uncles []*types.Header 57 58 config *params.ChainConfig 59 engine consensus.Engine 60 } 61 62 // SetCoinbase sets the coinbase of the generated block. 63 // It can be called at most once. 64 func (b *BlockGen) SetCoinbase(addr common.Address) { 65 if b.gasPool != nil { 66 if len(b.txs) > 0 { 67 panic("coinbase must be set before adding transactions") 68 } 69 panic("coinbase can only be set once") 70 } 71 b.header.Coinbase = addr 72 b.gasPool = new(GasPool).AddGas(b.header.GasLimit) 73 } 74 75 // SetExtra sets the extra data field of the generated block. 76 func (b *BlockGen) SetExtra(data []byte) { 77 b.header.Extra = data 78 } 79 80 // SetNonce sets the nonce field of the generated block. 81 func (b *BlockGen) SetNonce(nonce types.BlockNonce) { 82 b.header.Nonce = nonce 83 } 84 85 // SetDifficulty sets the difficulty field of the generated block. This method is 86 // useful for Clique tests where the difficulty does not depend on time. For the 87 // ethash tests, please use OffsetTime, which implicitly recalculates the diff. 88 func (b *BlockGen) SetDifficulty(diff *big.Int) { 89 b.header.Difficulty = diff 90 } 91 92 // AddTx adds a transaction to the generated block. If no coinbase has 93 // been set, the block's coinbase is set to the zero address. 94 // 95 // AddTx panics if the transaction cannot be executed. In addition to 96 // the protocol-imposed limitations (gas limit, etc.), there are some 97 // further limitations on the content of transactions that can be 98 // added. Notably, contract code relying on the BLOCKHASH instruction 99 // will panic during execution. 100 func (b *BlockGen) AddTx(tx *types.Transaction) { 101 b.AddTxWithChain(nil, tx) 102 } 103 104 // AddTxWithChain adds a transaction to the generated block. If no coinbase has 105 // been set, the block's coinbase is set to the zero address. 106 // 107 // AddTxWithChain panics if the transaction cannot be executed. In addition to 108 // the protocol-imposed limitations (gas limit, etc.), there are some 109 // further limitations on the content of transactions that can be 110 // added. If contract code relies on the BLOCKHASH instruction, 111 // the block in chain will be returned. 112 func (b *BlockGen) AddTxWithChain(bc *BlockChain, tx *types.Transaction) { 113 if b.gasPool == nil { 114 b.SetCoinbase(common.Address{}) 115 } 116 b.statedb.Prepare(tx.Hash(), len(b.txs)) 117 receipt, err := ApplyTransaction(b.config, bc, &b.header.Coinbase, b.gasPool, b.statedb, b.header, tx, &b.header.GasUsed, vm.Config{}) 118 if err != nil { 119 panic(err) 120 } 121 b.txs = append(b.txs, tx) 122 b.receipts = append(b.receipts, receipt) 123 } 124 125 // GetBalance returns the balance of the given address at the generated block. 126 func (b *BlockGen) GetBalance(addr common.Address) *big.Int { 127 return b.statedb.GetBalance(addr) 128 } 129 130 // AddUncheckedTx forcefully adds a transaction to the block without any 131 // validation. 132 // 133 // AddUncheckedTx will cause consensus failures when used during real 134 // chain processing. This is best used in conjunction with raw block insertion. 135 func (b *BlockGen) AddUncheckedTx(tx *types.Transaction) { 136 b.txs = append(b.txs, tx) 137 } 138 139 // Number returns the block number of the block being generated. 140 func (b *BlockGen) Number() *big.Int { 141 return new(big.Int).Set(b.header.Number) 142 } 143 144 // BaseFee returns the EIP-1559 base fee of the block being generated. 145 func (b *BlockGen) BaseFee() *big.Int { 146 return new(big.Int).Set(b.header.BaseFee) 147 } 148 149 // AddUncheckedReceipt forcefully adds a receipts to the block without a 150 // backing transaction. 151 // 152 // AddUncheckedReceipt will cause consensus failures when used during real 153 // chain processing. This is best used in conjunction with raw block insertion. 154 func (b *BlockGen) AddUncheckedReceipt(receipt *types.Receipt) { 155 b.receipts = append(b.receipts, receipt) 156 } 157 158 // TxNonce returns the next valid transaction nonce for the 159 // account at addr. It panics if the account does not exist. 160 func (b *BlockGen) TxNonce(addr common.Address) uint64 { 161 if !b.statedb.Exist(addr) { 162 panic("account does not exist") 163 } 164 return b.statedb.GetNonce(addr) 165 } 166 167 // AddUncle adds an uncle header to the generated block. 168 func (b *BlockGen) AddUncle(h *types.Header) { 169 b.uncles = append(b.uncles, h) 170 } 171 172 // PrevBlock returns a previously generated block by number. It panics if 173 // num is greater or equal to the number of the block being generated. 174 // For index -1, PrevBlock returns the parent block given to GenerateChain. 175 func (b *BlockGen) PrevBlock(index int) *types.Block { 176 if index >= b.i { 177 panic(fmt.Errorf("block index %d out of range (%d,%d)", index, -1, b.i)) 178 } 179 if index == -1 { 180 return b.parent 181 } 182 return b.chain[index] 183 } 184 185 // OffsetTime modifies the time instance of a block, implicitly changing its 186 // associated difficulty. It's useful to test scenarios where forking is not 187 // tied to chain length directly. 188 func (b *BlockGen) OffsetTime(seconds int64) { 189 b.header.Time += uint64(seconds) 190 if b.header.Time <= b.parent.Header().Time { 191 panic("block time out of range") 192 } 193 chainreader := &fakeChainReader{config: b.config} 194 b.header.Difficulty = b.engine.CalcDifficulty(chainreader, b.header.Time, b.parent.Header()) 195 } 196 197 // GenerateChain creates a chain of n blocks. The first block's 198 // parent will be the provided parent. db is used to store 199 // intermediate states and should contain the parent's state trie. 200 // 201 // The generator function is called with a new block generator for 202 // every block. Any transactions and uncles added to the generator 203 // become part of the block. If gen is nil, the blocks will be empty 204 // and their coinbase will be the zero address. 205 // 206 // Blocks created by GenerateChain do not contain valid proof of work 207 // values. Inserting them into BlockChain requires use of FakePow or 208 // a similar non-validating proof of work implementation. 209 func GenerateChain(config *params.ChainConfig, parent *types.Block, engine consensus.Engine, db ethdb.Database, n int, gen func(int, *BlockGen)) ([]*types.Block, []types.Receipts) { 210 if config == nil { 211 config = params.TestChainConfig 212 } 213 blocks, receipts := make(types.Blocks, n), make([]types.Receipts, n) 214 chainreader := &fakeChainReader{config: config} 215 genblock := func(i int, parent *types.Block, statedb *state.StateDB) (*types.Block, types.Receipts) { 216 b := &BlockGen{i: i, chain: blocks, parent: parent, statedb: statedb, config: config, engine: engine} 217 b.header = makeHeader(chainreader, config, parent, statedb, b.engine) 218 219 // Mutate the state and block according to any hard-fork specs 220 if daoBlock := config.DAOForkBlock; daoBlock != nil { 221 limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange) 222 if b.header.Number.Cmp(daoBlock) >= 0 && b.header.Number.Cmp(limit) < 0 { 223 if config.DAOForkSupport { 224 b.header.Extra = common.CopyBytes(params.DAOForkBlockExtra) 225 } 226 } 227 } 228 if config.DAOForkSupport && config.DAOForkBlock != nil && config.DAOForkBlock.Cmp(b.header.Number) == 0 { 229 misc.ApplyDAOHardFork(statedb) 230 } 231 // Execute any user modifications to the block 232 if gen != nil { 233 gen(i, b) 234 } 235 if b.engine != nil { 236 // Finalize and seal the block 237 block, err := b.engine.FinalizeAndAssemble(chainreader, b.header, statedb, b.txs, b.uncles, b.receipts) 238 if err != nil { 239 panic(fmt.Sprintf("Failed to finalize and assemble block at index %d: %s", i, err)) 240 } 241 242 // Write state changes to db 243 root, err := statedb.Commit(config.IsEIP158(b.header.Number)) 244 if err != nil { 245 panic(fmt.Sprintf("state write error: %v", err)) 246 } 247 if err := statedb.Database().TrieDB().Commit(root, false, nil); err != nil { 248 panic(fmt.Sprintf("trie write error: %v", err)) 249 } 250 return block, b.receipts 251 } 252 return nil, nil 253 } 254 for i := 0; i < n; i++ { 255 statedb, err := state.New(parent.Root(), state.NewDatabase(db), nil) 256 if err != nil { 257 panic(err) 258 } 259 block, receipt := genblock(i, parent, statedb) 260 blocks[i] = block 261 receipts[i] = receipt 262 parent = block 263 } 264 return blocks, receipts 265 } 266 267 func makeHeader(chain consensus.ChainReader, config *params.ChainConfig, parent *types.Block, state *state.StateDB, engine consensus.Engine) *types.Header { 268 var time uint64 269 if parent.Time() == 0 { 270 time = 10 271 } else { 272 time = parent.Time() + 10 // block time is fixed at 10 seconds 273 } 274 275 timestamp := new(big.Int).SetUint64(time) 276 var gasLimit uint64 277 if config.IsApricotPhase1(timestamp) { 278 gasLimit = params.ApricotPhase1GasLimit 279 } else { 280 gasLimit = CalcGasLimit(parent.GasUsed(), parent.GasLimit(), parent.GasLimit(), parent.GasLimit()) 281 } 282 283 header := &types.Header{ 284 Root: state.IntermediateRoot(chain.Config().IsEIP158(parent.Number())), 285 ParentHash: parent.Hash(), 286 Coinbase: parent.Coinbase(), 287 Difficulty: engine.CalcDifficulty(chain, time, &types.Header{ 288 Number: parent.Number(), 289 Time: time - 10, 290 Difficulty: parent.Difficulty(), 291 UncleHash: parent.UncleHash(), 292 }), 293 GasLimit: gasLimit, 294 Number: new(big.Int).Add(parent.Number(), common.Big1), 295 Time: time, 296 } 297 if chain.Config().IsApricotPhase3(timestamp) { 298 var err error 299 header.Extra, header.BaseFee, err = dummy.CalcBaseFee(chain.Config(), parent.Header(), time) 300 if err != nil { 301 panic(err) 302 } 303 } 304 return header 305 } 306 307 type fakeChainReader struct { 308 config *params.ChainConfig 309 } 310 311 // Config returns the chain configuration. 312 func (cr *fakeChainReader) Config() *params.ChainConfig { 313 return cr.config 314 } 315 316 func (cr *fakeChainReader) CurrentHeader() *types.Header { return nil } 317 func (cr *fakeChainReader) GetHeaderByNumber(number uint64) *types.Header { return nil } 318 func (cr *fakeChainReader) GetHeaderByHash(hash common.Hash) *types.Header { return nil } 319 func (cr *fakeChainReader) GetHeader(hash common.Hash, number uint64) *types.Header { return nil } 320 func (cr *fakeChainReader) GetBlock(hash common.Hash, number uint64) *types.Block { return nil }