github.com/jimmyx0x/go-ethereum@v1.10.28/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" 25 "github.com/ethereum/go-ethereum/consensus/misc" 26 "github.com/ethereum/go-ethereum/core/rawdb" 27 "github.com/ethereum/go-ethereum/core/state" 28 "github.com/ethereum/go-ethereum/core/types" 29 "github.com/ethereum/go-ethereum/core/vm" 30 "github.com/ethereum/go-ethereum/ethdb" 31 "github.com/ethereum/go-ethereum/params" 32 "github.com/ethereum/go-ethereum/trie" 33 ) 34 35 // BlockGen creates blocks for testing. 36 // See GenerateChain for a detailed explanation. 37 type BlockGen struct { 38 i int 39 parent *types.Block 40 chain []*types.Block 41 header *types.Header 42 statedb *state.StateDB 43 44 gasPool *GasPool 45 txs []*types.Transaction 46 receipts []*types.Receipt 47 uncles []*types.Header 48 49 config *params.ChainConfig 50 engine consensus.Engine 51 } 52 53 // SetCoinbase sets the coinbase of the generated block. 54 // It can be called at most once. 55 func (b *BlockGen) SetCoinbase(addr common.Address) { 56 if b.gasPool != nil { 57 if len(b.txs) > 0 { 58 panic("coinbase must be set before adding transactions") 59 } 60 panic("coinbase can only be set once") 61 } 62 b.header.Coinbase = addr 63 b.gasPool = new(GasPool).AddGas(b.header.GasLimit) 64 } 65 66 // SetExtra sets the extra data field of the generated block. 67 func (b *BlockGen) SetExtra(data []byte) { 68 b.header.Extra = data 69 } 70 71 // SetNonce sets the nonce field of the generated block. 72 func (b *BlockGen) SetNonce(nonce types.BlockNonce) { 73 b.header.Nonce = nonce 74 } 75 76 // SetDifficulty sets the difficulty field of the generated block. This method is 77 // useful for Clique tests where the difficulty does not depend on time. For the 78 // ethash tests, please use OffsetTime, which implicitly recalculates the diff. 79 func (b *BlockGen) SetDifficulty(diff *big.Int) { 80 b.header.Difficulty = diff 81 } 82 83 // SetPos makes the header a PoS-header (0 difficulty) 84 func (b *BlockGen) SetPoS() { 85 b.header.Difficulty = new(big.Int) 86 } 87 88 // addTx adds a transaction to the generated block. If no coinbase has 89 // been set, the block's coinbase is set to the zero address. 90 // 91 // There are a few options can be passed as well in order to run some 92 // customized rules. 93 // - bc: enables the ability to query historical block hashes for BLOCKHASH 94 // - vmConfig: extends the flexibility for customizing evm rules, e.g. enable extra EIPs 95 func (b *BlockGen) addTx(bc *BlockChain, vmConfig vm.Config, tx *types.Transaction) { 96 if b.gasPool == nil { 97 b.SetCoinbase(common.Address{}) 98 } 99 b.statedb.SetTxContext(tx.Hash(), len(b.txs)) 100 receipt, err := ApplyTransaction(b.config, bc, &b.header.Coinbase, b.gasPool, b.statedb, b.header, tx, &b.header.GasUsed, vmConfig) 101 if err != nil { 102 panic(err) 103 } 104 b.txs = append(b.txs, tx) 105 b.receipts = append(b.receipts, receipt) 106 } 107 108 // AddTx adds a transaction to the generated block. If no coinbase has 109 // been set, the block's coinbase is set to the zero address. 110 // 111 // AddTx panics if the transaction cannot be executed. In addition to 112 // the protocol-imposed limitations (gas limit, etc.), there are some 113 // further limitations on the content of transactions that can be 114 // added. Notably, contract code relying on the BLOCKHASH instruction 115 // will panic during execution. 116 func (b *BlockGen) AddTx(tx *types.Transaction) { 117 b.addTx(nil, vm.Config{}, tx) 118 } 119 120 // AddTxWithChain adds a transaction to the generated block. If no coinbase has 121 // been set, the block's coinbase is set to the zero address. 122 // 123 // AddTxWithChain panics if the transaction cannot be executed. In addition to 124 // the protocol-imposed limitations (gas limit, etc.), there are some 125 // further limitations on the content of transactions that can be 126 // added. If contract code relies on the BLOCKHASH instruction, 127 // the block in chain will be returned. 128 func (b *BlockGen) AddTxWithChain(bc *BlockChain, tx *types.Transaction) { 129 b.addTx(bc, vm.Config{}, tx) 130 } 131 132 // AddTxWithVMConfig adds a transaction to the generated block. If no coinbase has 133 // been set, the block's coinbase is set to the zero address. 134 // The evm interpreter can be customized with the provided vm config. 135 func (b *BlockGen) AddTxWithVMConfig(tx *types.Transaction, config vm.Config) { 136 b.addTx(nil, config, tx) 137 } 138 139 // GetBalance returns the balance of the given address at the generated block. 140 func (b *BlockGen) GetBalance(addr common.Address) *big.Int { 141 return b.statedb.GetBalance(addr) 142 } 143 144 // AddUncheckedTx forcefully adds a transaction to the block without any 145 // validation. 146 // 147 // AddUncheckedTx will cause consensus failures when used during real 148 // chain processing. This is best used in conjunction with raw block insertion. 149 func (b *BlockGen) AddUncheckedTx(tx *types.Transaction) { 150 b.txs = append(b.txs, tx) 151 } 152 153 // Number returns the block number of the block being generated. 154 func (b *BlockGen) Number() *big.Int { 155 return new(big.Int).Set(b.header.Number) 156 } 157 158 // BaseFee returns the EIP-1559 base fee of the block being generated. 159 func (b *BlockGen) BaseFee() *big.Int { 160 return new(big.Int).Set(b.header.BaseFee) 161 } 162 163 // AddUncheckedReceipt forcefully adds a receipts to the block without a 164 // backing transaction. 165 // 166 // AddUncheckedReceipt will cause consensus failures when used during real 167 // chain processing. This is best used in conjunction with raw block insertion. 168 func (b *BlockGen) AddUncheckedReceipt(receipt *types.Receipt) { 169 b.receipts = append(b.receipts, receipt) 170 } 171 172 // TxNonce returns the next valid transaction nonce for the 173 // account at addr. It panics if the account does not exist. 174 func (b *BlockGen) TxNonce(addr common.Address) uint64 { 175 if !b.statedb.Exist(addr) { 176 panic("account does not exist") 177 } 178 return b.statedb.GetNonce(addr) 179 } 180 181 // AddUncle adds an uncle header to the generated block. 182 func (b *BlockGen) AddUncle(h *types.Header) { 183 // The uncle will have the same timestamp and auto-generated difficulty 184 h.Time = b.header.Time 185 186 var parent *types.Header 187 for i := b.i - 1; i >= 0; i-- { 188 if b.chain[i].Hash() == h.ParentHash { 189 parent = b.chain[i].Header() 190 break 191 } 192 } 193 chainreader := &fakeChainReader{config: b.config} 194 h.Difficulty = b.engine.CalcDifficulty(chainreader, b.header.Time, parent) 195 196 // The gas limit and price should be derived from the parent 197 h.GasLimit = parent.GasLimit 198 if b.config.IsLondon(h.Number) { 199 h.BaseFee = misc.CalcBaseFee(b.config, parent) 200 if !b.config.IsLondon(parent.Number) { 201 parentGasLimit := parent.GasLimit * b.config.ElasticityMultiplier() 202 h.GasLimit = CalcGasLimit(parentGasLimit, parentGasLimit) 203 } 204 } 205 b.uncles = append(b.uncles, h) 206 } 207 208 // PrevBlock returns a previously generated block by number. It panics if 209 // num is greater or equal to the number of the block being generated. 210 // For index -1, PrevBlock returns the parent block given to GenerateChain. 211 func (b *BlockGen) PrevBlock(index int) *types.Block { 212 if index >= b.i { 213 panic(fmt.Errorf("block index %d out of range (%d,%d)", index, -1, b.i)) 214 } 215 if index == -1 { 216 return b.parent 217 } 218 return b.chain[index] 219 } 220 221 // OffsetTime modifies the time instance of a block, implicitly changing its 222 // associated difficulty. It's useful to test scenarios where forking is not 223 // tied to chain length directly. 224 func (b *BlockGen) OffsetTime(seconds int64) { 225 b.header.Time += uint64(seconds) 226 if b.header.Time <= b.parent.Header().Time { 227 panic("block time out of range") 228 } 229 chainreader := &fakeChainReader{config: b.config} 230 b.header.Difficulty = b.engine.CalcDifficulty(chainreader, b.header.Time, b.parent.Header()) 231 } 232 233 // GenerateChain creates a chain of n blocks. The first block's 234 // parent will be the provided parent. db is used to store 235 // intermediate states and should contain the parent's state trie. 236 // 237 // The generator function is called with a new block generator for 238 // every block. Any transactions and uncles added to the generator 239 // become part of the block. If gen is nil, the blocks will be empty 240 // and their coinbase will be the zero address. 241 // 242 // Blocks created by GenerateChain do not contain valid proof of work 243 // values. Inserting them into BlockChain requires use of FakePow or 244 // a similar non-validating proof of work implementation. 245 func GenerateChain(config *params.ChainConfig, parent *types.Block, engine consensus.Engine, db ethdb.Database, n int, gen func(int, *BlockGen)) ([]*types.Block, []types.Receipts) { 246 if config == nil { 247 config = params.TestChainConfig 248 } 249 blocks, receipts := make(types.Blocks, n), make([]types.Receipts, n) 250 chainreader := &fakeChainReader{config: config} 251 genblock := func(i int, parent *types.Block, statedb *state.StateDB) (*types.Block, types.Receipts) { 252 b := &BlockGen{i: i, chain: blocks, parent: parent, statedb: statedb, config: config, engine: engine} 253 b.header = makeHeader(chainreader, parent, statedb, b.engine) 254 255 // Set the difficulty for clique block. The chain maker doesn't have access 256 // to a chain, so the difficulty will be left unset (nil). Set it here to the 257 // correct value. 258 if b.header.Difficulty == nil { 259 if config.TerminalTotalDifficulty == nil { 260 // Clique chain 261 b.header.Difficulty = big.NewInt(2) 262 } else { 263 // Post-merge chain 264 b.header.Difficulty = big.NewInt(0) 265 } 266 } 267 // Mutate the state and block according to any hard-fork specs 268 if daoBlock := config.DAOForkBlock; daoBlock != nil { 269 limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange) 270 if b.header.Number.Cmp(daoBlock) >= 0 && b.header.Number.Cmp(limit) < 0 { 271 if config.DAOForkSupport { 272 b.header.Extra = common.CopyBytes(params.DAOForkBlockExtra) 273 } 274 } 275 } 276 if config.DAOForkSupport && config.DAOForkBlock != nil && config.DAOForkBlock.Cmp(b.header.Number) == 0 { 277 misc.ApplyDAOHardFork(statedb) 278 } 279 // Execute any user modifications to the block 280 if gen != nil { 281 gen(i, b) 282 } 283 if b.engine != nil { 284 // Finalize and seal the block 285 block, _ := b.engine.FinalizeAndAssemble(chainreader, b.header, statedb, b.txs, b.uncles, b.receipts) 286 287 // Write state changes to db 288 root, err := statedb.Commit(config.IsEIP158(b.header.Number)) 289 if err != nil { 290 panic(fmt.Sprintf("state write error: %v", err)) 291 } 292 if err := statedb.Database().TrieDB().Commit(root, false, nil); err != nil { 293 panic(fmt.Sprintf("trie write error: %v", err)) 294 } 295 return block, b.receipts 296 } 297 return nil, nil 298 } 299 for i := 0; i < n; i++ { 300 statedb, err := state.New(parent.Root(), state.NewDatabase(db), nil) 301 if err != nil { 302 panic(err) 303 } 304 block, receipt := genblock(i, parent, statedb) 305 blocks[i] = block 306 receipts[i] = receipt 307 parent = block 308 } 309 return blocks, receipts 310 } 311 312 // GenerateChainWithGenesis is a wrapper of GenerateChain which will initialize 313 // genesis block to database first according to the provided genesis specification 314 // then generate chain on top. 315 func GenerateChainWithGenesis(genesis *Genesis, engine consensus.Engine, n int, gen func(int, *BlockGen)) (ethdb.Database, []*types.Block, []types.Receipts) { 316 db := rawdb.NewMemoryDatabase() 317 _, err := genesis.Commit(db, trie.NewDatabase(db)) 318 if err != nil { 319 panic(err) 320 } 321 blocks, receipts := GenerateChain(genesis.Config, genesis.ToBlock(), engine, db, n, gen) 322 return db, blocks, receipts 323 } 324 325 func makeHeader(chain consensus.ChainReader, parent *types.Block, state *state.StateDB, engine consensus.Engine) *types.Header { 326 var time uint64 327 if parent.Time() == 0 { 328 time = 10 329 } else { 330 time = parent.Time() + 10 // block time is fixed at 10 seconds 331 } 332 header := &types.Header{ 333 Root: state.IntermediateRoot(chain.Config().IsEIP158(parent.Number())), 334 ParentHash: parent.Hash(), 335 Coinbase: parent.Coinbase(), 336 Difficulty: engine.CalcDifficulty(chain, time, &types.Header{ 337 Number: parent.Number(), 338 Time: time - 10, 339 Difficulty: parent.Difficulty(), 340 UncleHash: parent.UncleHash(), 341 }), 342 GasLimit: parent.GasLimit(), 343 Number: new(big.Int).Add(parent.Number(), common.Big1), 344 Time: time, 345 } 346 if chain.Config().IsLondon(header.Number) { 347 header.BaseFee = misc.CalcBaseFee(chain.Config(), parent.Header()) 348 if !chain.Config().IsLondon(parent.Number()) { 349 parentGasLimit := parent.GasLimit() * chain.Config().ElasticityMultiplier() 350 header.GasLimit = CalcGasLimit(parentGasLimit, parentGasLimit) 351 } 352 } 353 return header 354 } 355 356 // makeHeaderChain creates a deterministic chain of headers rooted at parent. 357 func makeHeaderChain(chainConfig *params.ChainConfig, parent *types.Header, n int, engine consensus.Engine, db ethdb.Database, seed int) []*types.Header { 358 blocks := makeBlockChain(chainConfig, types.NewBlockWithHeader(parent), n, engine, db, seed) 359 headers := make([]*types.Header, len(blocks)) 360 for i, block := range blocks { 361 headers[i] = block.Header() 362 } 363 return headers 364 } 365 366 // makeHeaderChainWithGenesis creates a deterministic chain of headers from genesis. 367 func makeHeaderChainWithGenesis(genesis *Genesis, n int, engine consensus.Engine, seed int) (ethdb.Database, []*types.Header) { 368 db, blocks := makeBlockChainWithGenesis(genesis, n, engine, seed) 369 headers := make([]*types.Header, len(blocks)) 370 for i, block := range blocks { 371 headers[i] = block.Header() 372 } 373 return db, headers 374 } 375 376 // makeBlockChain creates a deterministic chain of blocks rooted at parent. 377 func makeBlockChain(chainConfig *params.ChainConfig, parent *types.Block, n int, engine consensus.Engine, db ethdb.Database, seed int) []*types.Block { 378 blocks, _ := GenerateChain(chainConfig, parent, engine, db, n, func(i int, b *BlockGen) { 379 b.SetCoinbase(common.Address{0: byte(seed), 19: byte(i)}) 380 }) 381 return blocks 382 } 383 384 // makeBlockChain creates a deterministic chain of blocks from genesis 385 func makeBlockChainWithGenesis(genesis *Genesis, n int, engine consensus.Engine, seed int) (ethdb.Database, []*types.Block) { 386 db, blocks, _ := GenerateChainWithGenesis(genesis, engine, n, func(i int, b *BlockGen) { 387 b.SetCoinbase(common.Address{0: byte(seed), 19: byte(i)}) 388 }) 389 return db, blocks 390 } 391 392 type fakeChainReader struct { 393 config *params.ChainConfig 394 } 395 396 // Config returns the chain configuration. 397 func (cr *fakeChainReader) Config() *params.ChainConfig { 398 return cr.config 399 } 400 401 func (cr *fakeChainReader) CurrentHeader() *types.Header { return nil } 402 func (cr *fakeChainReader) GetHeaderByNumber(number uint64) *types.Header { return nil } 403 func (cr *fakeChainReader) GetHeaderByHash(hash common.Hash) *types.Header { return nil } 404 func (cr *fakeChainReader) GetHeader(hash common.Hash, number uint64) *types.Header { return nil } 405 func (cr *fakeChainReader) GetBlock(hash common.Hash, number uint64) *types.Block { return nil } 406 func (cr *fakeChainReader) GetTd(hash common.Hash, number uint64) *big.Int { return nil }