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