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