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