github.com/DxChainNetwork/dxc@v0.8.1-0.20220824085222-1162e304b6e7/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/DxChainNetwork/dxc/common" 24 "github.com/DxChainNetwork/dxc/consensus" 25 "github.com/DxChainNetwork/dxc/consensus/misc" 26 "github.com/DxChainNetwork/dxc/core/state" 27 "github.com/DxChainNetwork/dxc/core/types" 28 "github.com/DxChainNetwork/dxc/core/vm" 29 "github.com/DxChainNetwork/dxc/ethdb" 30 "github.com/DxChainNetwork/dxc/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 // SetDifficulty sets the difficulty field of the generated block. This method is 75 // useful for Clique tests where the difficulty does not depend on time. For the 76 // ethash tests, please use OffsetTime, which implicitly recalculates the diff. 77 func (b *BlockGen) SetDifficulty(diff *big.Int) { 78 b.header.Difficulty = diff 79 } 80 81 // AddTx adds a transaction to the generated block. If no coinbase has 82 // been set, the block's coinbase is set to the zero address. 83 // 84 // AddTx panics if the transaction cannot be executed. In addition to 85 // the protocol-imposed limitations (gas limit, etc.), there are some 86 // further limitations on the content of transactions that can be 87 // added. Notably, contract code relying on the BLOCKHASH instruction 88 // will panic during execution. 89 func (b *BlockGen) AddTx(tx *types.Transaction) { 90 b.AddTxWithChain(nil, tx) 91 } 92 93 // AddTxWithChain adds a transaction to the generated block. If no coinbase has 94 // been set, the block's coinbase is set to the zero address. 95 // 96 // AddTxWithChain panics if the transaction cannot be executed. In addition to 97 // the protocol-imposed limitations (gas limit, etc.), there are some 98 // further limitations on the content of transactions that can be 99 // added. If contract code relies on the BLOCKHASH instruction, 100 // the block in chain will be returned. 101 func (b *BlockGen) AddTxWithChain(bc *BlockChain, tx *types.Transaction) { 102 if b.gasPool == nil { 103 b.SetCoinbase(common.Address{}) 104 } 105 b.statedb.Prepare(tx.Hash(), len(b.txs)) 106 receipt, err := ApplyTransaction(b.config, bc, &b.header.Coinbase, b.gasPool, b.statedb, b.header, tx, &b.header.GasUsed, vm.Config{}, nil) 107 if err != nil { 108 panic(err) 109 } 110 b.txs = append(b.txs, tx) 111 b.receipts = append(b.receipts, receipt) 112 } 113 114 // GetBalance returns the balance of the given address at the generated block. 115 func (b *BlockGen) GetBalance(addr common.Address) *big.Int { 116 return b.statedb.GetBalance(addr) 117 } 118 119 // AddUncheckedTx forcefully adds a transaction to the block without any 120 // validation. 121 // 122 // AddUncheckedTx will cause consensus failures when used during real 123 // chain processing. This is best used in conjunction with raw block insertion. 124 func (b *BlockGen) AddUncheckedTx(tx *types.Transaction) { 125 b.txs = append(b.txs, tx) 126 } 127 128 // Number returns the block number of the block being generated. 129 func (b *BlockGen) Number() *big.Int { 130 return new(big.Int).Set(b.header.Number) 131 } 132 133 // BaseFee returns the EIP-1559 base fee of the block being generated. 134 func (b *BlockGen) BaseFee() *big.Int { 135 return new(big.Int).Set(b.header.BaseFee) 136 } 137 138 // AddUncheckedReceipt forcefully adds a receipts to the block without a 139 // backing transaction. 140 // 141 // AddUncheckedReceipt will cause consensus failures when used during real 142 // chain processing. This is best used in conjunction with raw block insertion. 143 func (b *BlockGen) AddUncheckedReceipt(receipt *types.Receipt) { 144 b.receipts = append(b.receipts, receipt) 145 } 146 147 // TxNonce returns the next valid transaction nonce for the 148 // account at addr. It panics if the account does not exist. 149 func (b *BlockGen) TxNonce(addr common.Address) uint64 { 150 if !b.statedb.Exist(addr) { 151 panic("account does not exist") 152 } 153 return b.statedb.GetNonce(addr) 154 } 155 156 // AddUncle adds an uncle header to the generated block. 157 func (b *BlockGen) AddUncle(h *types.Header) { 158 b.uncles = append(b.uncles, h) 159 } 160 161 // PrevBlock returns a previously generated block by number. It panics if 162 // num is greater or equal to the number of the block being generated. 163 // For index -1, PrevBlock returns the parent block given to GenerateChain. 164 func (b *BlockGen) PrevBlock(index int) *types.Block { 165 if index >= b.i { 166 panic(fmt.Errorf("block index %d out of range (%d,%d)", index, -1, b.i)) 167 } 168 if index == -1 { 169 return b.parent 170 } 171 return b.chain[index] 172 } 173 174 // OffsetTime modifies the time instance of a block, implicitly changing its 175 // associated difficulty. It's useful to test scenarios where forking is not 176 // tied to chain length directly. 177 func (b *BlockGen) OffsetTime(seconds int64) { 178 b.header.Time += uint64(seconds) 179 if b.header.Time <= b.parent.Header().Time { 180 panic("block time out of range") 181 } 182 chainreader := &fakeChainReader{config: b.config} 183 b.header.Difficulty = b.engine.CalcDifficulty(chainreader, b.header.Time, b.parent.Header()) 184 } 185 186 // GenerateChain creates a chain of n blocks. The first block's 187 // parent will be the provided parent. db is used to store 188 // intermediate states and should contain the parent's state trie. 189 // 190 // The generator function is called with a new block generator for 191 // every block. Any transactions and uncles added to the generator 192 // become part of the block. If gen is nil, the blocks will be empty 193 // and their coinbase will be the zero address. 194 // 195 // Blocks created by GenerateChain do not contain valid proof of work 196 // values. Inserting them into BlockChain requires use of FakePow or 197 // a similar non-validating proof of work implementation. 198 func GenerateChain(config *params.ChainConfig, parent *types.Block, engine consensus.Engine, db ethdb.Database, n int, gen func(int, *BlockGen)) ([]*types.Block, []types.Receipts) { 199 if config == nil { 200 config = params.TestChainConfig 201 } 202 blocks, receipts := make(types.Blocks, n), make([]types.Receipts, n) 203 chainreader := &fakeChainReader{config: config, engine: engine} 204 genblock := func(i int, parent *types.Block, statedb *state.StateDB) (*types.Block, types.Receipts) { 205 b := &BlockGen{i: i, chain: blocks, parent: parent, statedb: statedb, config: config, engine: engine} 206 b.header = makeHeader(chainreader, parent, statedb, b.engine) 207 208 // Mutate the state and block according to any hard-fork specs 209 if daoBlock := config.DAOForkBlock; daoBlock != nil { 210 limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange) 211 if b.header.Number.Cmp(daoBlock) >= 0 && b.header.Number.Cmp(limit) < 0 { 212 if config.DAOForkSupport { 213 b.header.Extra = common.CopyBytes(params.DAOForkBlockExtra) 214 } 215 } 216 } 217 if config.DAOForkSupport && config.DAOForkBlock != nil && config.DAOForkBlock.Cmp(b.header.Number) == 0 { 218 misc.ApplyDAOHardFork(statedb) 219 } 220 posa, isPoSA := engine.(consensus.PoSA) 221 if isPoSA { 222 if err := posa.PreHandle(chainreader, b.header, statedb); err != nil { 223 return nil, nil 224 } 225 } 226 227 // Execute any user modifications to the block 228 if gen != nil { 229 gen(i, b) 230 } 231 if b.engine != nil { 232 // Finalize and seal the block 233 block, receipts, _ := b.engine.FinalizeAndAssemble(chainreader, b.header, statedb, b.txs, b.uncles, b.receipts) 234 b.receipts = receipts 235 236 // Write state changes to db 237 root, err := statedb.Commit(config.IsEIP158(b.header.Number)) 238 if err != nil { 239 panic(fmt.Sprintf("state write error: %v", err)) 240 } 241 if err := statedb.Database().TrieDB().Commit(root, false, nil); err != nil { 242 panic(fmt.Sprintf("trie write error: %v", err)) 243 } 244 return block, b.receipts 245 } 246 return nil, nil 247 } 248 for i := 0; i < n; i++ { 249 statedb, err := state.New(parent.Root(), state.NewDatabase(db), nil) 250 if err != nil { 251 panic(err) 252 } 253 block, receipt := genblock(i, parent, statedb) 254 blocks[i] = block 255 receipts[i] = receipt 256 parent = block 257 } 258 return blocks, receipts 259 } 260 261 func makeHeader(chain consensus.ChainReader, parent *types.Block, state *state.StateDB, engine consensus.Engine) *types.Header { 262 var time uint64 263 if parent.Time() == 0 { 264 time = 10 265 } else { 266 time = parent.Time() + 10 // block time is fixed at 10 seconds 267 } 268 header := &types.Header{ 269 Root: state.IntermediateRoot(chain.Config().IsEIP158(parent.Number())), 270 ParentHash: parent.Hash(), 271 Coinbase: parent.Coinbase(), 272 Difficulty: engine.CalcDifficulty(chain, time, &types.Header{ 273 Number: parent.Number(), 274 Time: time - 10, 275 Difficulty: parent.Difficulty(), 276 UncleHash: parent.UncleHash(), 277 }), 278 GasLimit: parent.GasLimit(), 279 Number: new(big.Int).Add(parent.Number(), common.Big1), 280 Time: time, 281 } 282 if chain.Config().IsLondon(header.Number) { 283 header.BaseFee = misc.CalcBaseFee(chain.Config(), parent.Header()) 284 if !chain.Config().IsLondon(parent.Number()) { 285 parentGasLimit := parent.GasLimit() * params.ElasticityMultiplier 286 header.GasLimit = CalcGasLimit(parentGasLimit, parentGasLimit) 287 } 288 } 289 return header 290 } 291 292 // makeHeaderChain creates a deterministic chain of headers rooted at parent. 293 func makeHeaderChain(parent *types.Header, n int, engine consensus.Engine, db ethdb.Database, seed int) []*types.Header { 294 blocks := makeBlockChain(types.NewBlockWithHeader(parent), n, engine, db, seed) 295 headers := make([]*types.Header, len(blocks)) 296 for i, block := range blocks { 297 headers[i] = block.Header() 298 } 299 return headers 300 } 301 302 // makeBlockChain creates a deterministic chain of blocks rooted at parent. 303 func makeBlockChain(parent *types.Block, n int, engine consensus.Engine, db ethdb.Database, seed int) []*types.Block { 304 blocks, _ := GenerateChain(params.TestChainConfig, parent, engine, db, n, func(i int, b *BlockGen) { 305 b.SetCoinbase(common.Address{0: byte(seed), 19: byte(i)}) 306 }) 307 return blocks 308 } 309 310 type fakeChainReader struct { 311 config *params.ChainConfig 312 engine consensus.Engine 313 } 314 315 // Config returns the chain configuration. 316 func (cr *fakeChainReader) Config() *params.ChainConfig { 317 return cr.config 318 } 319 320 func (cr *fakeChainReader) Engine() consensus.Engine { 321 return cr.engine 322 } 323 324 func (cr *fakeChainReader) CurrentHeader() *types.Header { return nil } 325 func (cr *fakeChainReader) GetHeaderByNumber(number uint64) *types.Header { return nil } 326 func (cr *fakeChainReader) GetHeaderByHash(hash common.Hash) *types.Header { return nil } 327 func (cr *fakeChainReader) GetHeader(hash common.Hash, number uint64) *types.Header { return nil } 328 func (cr *fakeChainReader) GetBlock(hash common.Hash, number uint64) *types.Block { return nil }