github.com/cryptotooltop/go-ethereum@v0.0.0-20231103184714-151d1922f3e5/accounts/abi/bind/backends/simulated.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 backends 18 19 import ( 20 "context" 21 "errors" 22 "fmt" 23 "math/big" 24 "sync" 25 "time" 26 27 "github.com/scroll-tech/go-ethereum" 28 "github.com/scroll-tech/go-ethereum/accounts/abi" 29 "github.com/scroll-tech/go-ethereum/accounts/abi/bind" 30 "github.com/scroll-tech/go-ethereum/common" 31 "github.com/scroll-tech/go-ethereum/common/hexutil" 32 "github.com/scroll-tech/go-ethereum/common/math" 33 "github.com/scroll-tech/go-ethereum/consensus/ethash" 34 "github.com/scroll-tech/go-ethereum/core" 35 "github.com/scroll-tech/go-ethereum/core/bloombits" 36 "github.com/scroll-tech/go-ethereum/core/rawdb" 37 "github.com/scroll-tech/go-ethereum/core/state" 38 "github.com/scroll-tech/go-ethereum/core/types" 39 "github.com/scroll-tech/go-ethereum/core/vm" 40 "github.com/scroll-tech/go-ethereum/eth/filters" 41 "github.com/scroll-tech/go-ethereum/ethdb" 42 "github.com/scroll-tech/go-ethereum/event" 43 "github.com/scroll-tech/go-ethereum/log" 44 "github.com/scroll-tech/go-ethereum/params" 45 "github.com/scroll-tech/go-ethereum/rollup/fees" 46 "github.com/scroll-tech/go-ethereum/rpc" 47 ) 48 49 // This nil assignment ensures at compile time that SimulatedBackend implements bind.ContractBackend. 50 var _ bind.ContractBackend = (*SimulatedBackend)(nil) 51 52 var ( 53 errBlockNumberUnsupported = errors.New("simulatedBackend cannot access blocks other than the latest block") 54 errBlockDoesNotExist = errors.New("block does not exist in blockchain") 55 errTransactionDoesNotExist = errors.New("transaction does not exist") 56 ) 57 58 // SimulatedBackend implements bind.ContractBackend, simulating a blockchain in 59 // the background. Its main purpose is to allow for easy testing of contract bindings. 60 // Simulated backend implements the following interfaces: 61 // ChainReader, ChainStateReader, ContractBackend, ContractCaller, ContractFilterer, ContractTransactor, 62 // DeployBackend, GasEstimator, GasPricer, LogFilterer, PendingContractCaller, TransactionReader, and TransactionSender 63 type SimulatedBackend struct { 64 database ethdb.Database // In memory database to store our testing data 65 blockchain *core.BlockChain // Ethereum blockchain to handle the consensus 66 67 mu sync.Mutex 68 pendingBlock *types.Block // Currently pending block that will be imported on request 69 pendingState *state.StateDB // Currently pending state that will be the active on request 70 71 events *filters.EventSystem // Event system for filtering log events live 72 73 config *params.ChainConfig 74 } 75 76 // NewSimulatedBackendWithDatabase creates a new binding backend based on the given database 77 // and uses a simulated blockchain for testing purposes. 78 // A simulated backend always uses chainID 1337. 79 func NewSimulatedBackendWithDatabase(database ethdb.Database, alloc core.GenesisAlloc, gasLimit uint64) *SimulatedBackend { 80 genesis := core.Genesis{Config: params.AllEthashProtocolChanges, GasLimit: gasLimit, Alloc: alloc} 81 genesis.MustCommit(database) 82 blockchain, _ := core.NewBlockChain(database, nil, genesis.Config, ethash.NewFaker(), vm.Config{}, nil, nil, false) 83 84 backend := &SimulatedBackend{ 85 database: database, 86 blockchain: blockchain, 87 config: genesis.Config, 88 events: filters.NewEventSystem(&filterBackend{database, blockchain}, false), 89 } 90 backend.rollback(blockchain.CurrentBlock()) 91 return backend 92 } 93 94 // NewSimulatedBackend creates a new binding backend using a simulated blockchain 95 // for testing purposes. 96 // A simulated backend always uses chainID 1337. 97 func NewSimulatedBackend(alloc core.GenesisAlloc, gasLimit uint64) *SimulatedBackend { 98 return NewSimulatedBackendWithDatabase(rawdb.NewMemoryDatabase(), alloc, gasLimit) 99 } 100 101 // Close terminates the underlying blockchain's update loop. 102 func (b *SimulatedBackend) Close() error { 103 b.blockchain.Stop() 104 return nil 105 } 106 107 // Commit imports all the pending transactions as a single block and starts a 108 // fresh new state. 109 func (b *SimulatedBackend) Commit() { 110 b.mu.Lock() 111 defer b.mu.Unlock() 112 113 if _, err := b.blockchain.InsertChain([]*types.Block{b.pendingBlock}); err != nil { 114 panic(err) // This cannot happen unless the simulator is wrong, fail in that case 115 } 116 // Using the last inserted block here makes it possible to build on a side 117 // chain after a fork. 118 b.rollback(b.pendingBlock) 119 } 120 121 // Rollback aborts all pending transactions, reverting to the last committed state. 122 func (b *SimulatedBackend) Rollback() { 123 b.mu.Lock() 124 defer b.mu.Unlock() 125 126 b.rollback(b.blockchain.CurrentBlock()) 127 } 128 129 func (b *SimulatedBackend) rollback(parent *types.Block) { 130 blocks, _ := core.GenerateChain(b.config, parent, ethash.NewFaker(), b.database, 1, func(int, *core.BlockGen) {}) 131 132 b.pendingBlock = blocks[0] 133 b.pendingState, _ = state.New(b.pendingBlock.Root(), b.blockchain.StateCache(), nil) 134 } 135 136 // Fork creates a side-chain that can be used to simulate reorgs. 137 // 138 // This function should be called with the ancestor block where the new side 139 // chain should be started. Transactions (old and new) can then be applied on 140 // top and Commit-ed. 141 // 142 // Note, the side-chain will only become canonical (and trigger the events) when 143 // it becomes longer. Until then CallContract will still operate on the current 144 // canonical chain. 145 // 146 // There is a % chance that the side chain becomes canonical at the same length 147 // to simulate live network behavior. 148 func (b *SimulatedBackend) Fork(ctx context.Context, parent common.Hash) error { 149 b.mu.Lock() 150 defer b.mu.Unlock() 151 152 if len(b.pendingBlock.Transactions()) != 0 { 153 return errors.New("pending block dirty") 154 } 155 block, err := b.blockByHash(ctx, parent) 156 if err != nil { 157 return err 158 } 159 b.rollback(block) 160 return nil 161 } 162 163 // stateByBlockNumber retrieves a state by a given blocknumber. 164 func (b *SimulatedBackend) stateByBlockNumber(ctx context.Context, blockNumber *big.Int) (*state.StateDB, error) { 165 if blockNumber == nil || blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) == 0 { 166 return b.blockchain.State() 167 } 168 block, err := b.blockByNumber(ctx, blockNumber) 169 if err != nil { 170 return nil, err 171 } 172 return b.blockchain.StateAt(block.Root()) 173 } 174 175 // CodeAt returns the code associated with a certain account in the blockchain. 176 func (b *SimulatedBackend) CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error) { 177 b.mu.Lock() 178 defer b.mu.Unlock() 179 180 stateDB, err := b.stateByBlockNumber(ctx, blockNumber) 181 if err != nil { 182 return nil, err 183 } 184 185 return stateDB.GetCode(contract), nil 186 } 187 188 // BalanceAt returns the wei balance of a certain account in the blockchain. 189 func (b *SimulatedBackend) BalanceAt(ctx context.Context, contract common.Address, blockNumber *big.Int) (*big.Int, error) { 190 b.mu.Lock() 191 defer b.mu.Unlock() 192 193 stateDB, err := b.stateByBlockNumber(ctx, blockNumber) 194 if err != nil { 195 return nil, err 196 } 197 198 return stateDB.GetBalance(contract), nil 199 } 200 201 // NonceAt returns the nonce of a certain account in the blockchain. 202 func (b *SimulatedBackend) NonceAt(ctx context.Context, contract common.Address, blockNumber *big.Int) (uint64, error) { 203 b.mu.Lock() 204 defer b.mu.Unlock() 205 206 stateDB, err := b.stateByBlockNumber(ctx, blockNumber) 207 if err != nil { 208 return 0, err 209 } 210 211 return stateDB.GetNonce(contract), nil 212 } 213 214 // StorageAt returns the value of key in the storage of an account in the blockchain. 215 func (b *SimulatedBackend) StorageAt(ctx context.Context, contract common.Address, key common.Hash, blockNumber *big.Int) ([]byte, error) { 216 b.mu.Lock() 217 defer b.mu.Unlock() 218 219 stateDB, err := b.stateByBlockNumber(ctx, blockNumber) 220 if err != nil { 221 return nil, err 222 } 223 224 val := stateDB.GetState(contract, key) 225 return val[:], nil 226 } 227 228 // TransactionReceipt returns the receipt of a transaction. 229 func (b *SimulatedBackend) TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) { 230 b.mu.Lock() 231 defer b.mu.Unlock() 232 233 receipt, _, _, _ := rawdb.ReadReceipt(b.database, txHash, b.config) 234 return receipt, nil 235 } 236 237 // TransactionByHash checks the pool of pending transactions in addition to the 238 // blockchain. The isPending return value indicates whether the transaction has been 239 // mined yet. Note that the transaction may not be part of the canonical chain even if 240 // it's not pending. 241 func (b *SimulatedBackend) TransactionByHash(ctx context.Context, txHash common.Hash) (*types.Transaction, bool, error) { 242 b.mu.Lock() 243 defer b.mu.Unlock() 244 245 tx := b.pendingBlock.Transaction(txHash) 246 if tx != nil { 247 return tx, true, nil 248 } 249 tx, _, _, _ = rawdb.ReadTransaction(b.database, txHash) 250 if tx != nil { 251 return tx, false, nil 252 } 253 return nil, false, ethereum.NotFound 254 } 255 256 // BlockByHash retrieves a block based on the block hash. 257 func (b *SimulatedBackend) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) { 258 b.mu.Lock() 259 defer b.mu.Unlock() 260 261 return b.blockByHash(ctx, hash) 262 } 263 264 // blockByHash retrieves a block based on the block hash without Locking. 265 func (b *SimulatedBackend) blockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) { 266 if hash == b.pendingBlock.Hash() { 267 return b.pendingBlock, nil 268 } 269 270 block := b.blockchain.GetBlockByHash(hash) 271 if block != nil { 272 return block, nil 273 } 274 275 return nil, errBlockDoesNotExist 276 } 277 278 // BlockByNumber retrieves a block from the database by number, caching it 279 // (associated with its hash) if found. 280 func (b *SimulatedBackend) BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error) { 281 b.mu.Lock() 282 defer b.mu.Unlock() 283 284 return b.blockByNumber(ctx, number) 285 } 286 287 // blockByNumber retrieves a block from the database by number, caching it 288 // (associated with its hash) if found without Lock. 289 func (b *SimulatedBackend) blockByNumber(ctx context.Context, number *big.Int) (*types.Block, error) { 290 if number == nil || number.Cmp(b.pendingBlock.Number()) == 0 { 291 return b.blockchain.CurrentBlock(), nil 292 } 293 294 block := b.blockchain.GetBlockByNumber(uint64(number.Int64())) 295 if block == nil { 296 return nil, errBlockDoesNotExist 297 } 298 299 return block, nil 300 } 301 302 // HeaderByHash returns a block header from the current canonical chain. 303 func (b *SimulatedBackend) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) { 304 b.mu.Lock() 305 defer b.mu.Unlock() 306 307 if hash == b.pendingBlock.Hash() { 308 return b.pendingBlock.Header(), nil 309 } 310 311 header := b.blockchain.GetHeaderByHash(hash) 312 if header == nil { 313 return nil, errBlockDoesNotExist 314 } 315 316 return header, nil 317 } 318 319 // HeaderByNumber returns a block header from the current canonical chain. If number is 320 // nil, the latest known header is returned. 321 func (b *SimulatedBackend) HeaderByNumber(ctx context.Context, block *big.Int) (*types.Header, error) { 322 b.mu.Lock() 323 defer b.mu.Unlock() 324 325 if block == nil || block.Cmp(b.pendingBlock.Number()) == 0 { 326 return b.blockchain.CurrentHeader(), nil 327 } 328 329 return b.blockchain.GetHeaderByNumber(uint64(block.Int64())), nil 330 } 331 332 // TransactionCount returns the number of transactions in a given block. 333 func (b *SimulatedBackend) TransactionCount(ctx context.Context, blockHash common.Hash) (uint, error) { 334 b.mu.Lock() 335 defer b.mu.Unlock() 336 337 if blockHash == b.pendingBlock.Hash() { 338 return uint(b.pendingBlock.Transactions().Len()), nil 339 } 340 341 block := b.blockchain.GetBlockByHash(blockHash) 342 if block == nil { 343 return uint(0), errBlockDoesNotExist 344 } 345 346 return uint(block.Transactions().Len()), nil 347 } 348 349 // TransactionInBlock returns the transaction for a specific block at a specific index. 350 func (b *SimulatedBackend) TransactionInBlock(ctx context.Context, blockHash common.Hash, index uint) (*types.Transaction, error) { 351 b.mu.Lock() 352 defer b.mu.Unlock() 353 354 if blockHash == b.pendingBlock.Hash() { 355 transactions := b.pendingBlock.Transactions() 356 if uint(len(transactions)) < index+1 { 357 return nil, errTransactionDoesNotExist 358 } 359 360 return transactions[index], nil 361 } 362 363 block := b.blockchain.GetBlockByHash(blockHash) 364 if block == nil { 365 return nil, errBlockDoesNotExist 366 } 367 368 transactions := block.Transactions() 369 if uint(len(transactions)) < index+1 { 370 return nil, errTransactionDoesNotExist 371 } 372 373 return transactions[index], nil 374 } 375 376 // PendingCodeAt returns the code associated with an account in the pending state. 377 func (b *SimulatedBackend) PendingCodeAt(ctx context.Context, contract common.Address) ([]byte, error) { 378 b.mu.Lock() 379 defer b.mu.Unlock() 380 381 return b.pendingState.GetCode(contract), nil 382 } 383 384 func newRevertError(result *core.ExecutionResult) *revertError { 385 reason, errUnpack := abi.UnpackRevert(result.Revert()) 386 err := errors.New("execution reverted") 387 if errUnpack == nil { 388 err = fmt.Errorf("execution reverted: %v", reason) 389 } 390 return &revertError{ 391 error: err, 392 reason: hexutil.Encode(result.Revert()), 393 } 394 } 395 396 // revertError is an API error that encompasses an EVM revert with JSON error 397 // code and a binary data blob. 398 type revertError struct { 399 error 400 reason string // revert reason hex encoded 401 } 402 403 // ErrorCode returns the JSON error code for a revert. 404 // See: https://github.com/ethereum/wiki/wiki/JSON-RPC-Error-Codes-Improvement-Proposal 405 func (e *revertError) ErrorCode() int { 406 return 3 407 } 408 409 // ErrorData returns the hex encoded revert reason. 410 func (e *revertError) ErrorData() interface{} { 411 return e.reason 412 } 413 414 // CallContract executes a contract call. 415 func (b *SimulatedBackend) CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) { 416 b.mu.Lock() 417 defer b.mu.Unlock() 418 419 if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 { 420 return nil, errBlockNumberUnsupported 421 } 422 stateDB, err := b.blockchain.State() 423 if err != nil { 424 return nil, err 425 } 426 res, err := b.callContract(ctx, call, b.blockchain.CurrentBlock(), stateDB) 427 if err != nil { 428 return nil, err 429 } 430 // If the result contains a revert reason, try to unpack and return it. 431 if len(res.Revert()) > 0 { 432 return nil, newRevertError(res) 433 } 434 return res.Return(), res.Err 435 } 436 437 // PendingCallContract executes a contract call on the pending state. 438 func (b *SimulatedBackend) PendingCallContract(ctx context.Context, call ethereum.CallMsg) ([]byte, error) { 439 b.mu.Lock() 440 defer b.mu.Unlock() 441 defer b.pendingState.RevertToSnapshot(b.pendingState.Snapshot()) 442 443 res, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState) 444 if err != nil { 445 return nil, err 446 } 447 // If the result contains a revert reason, try to unpack and return it. 448 if len(res.Revert()) > 0 { 449 return nil, newRevertError(res) 450 } 451 return res.Return(), res.Err 452 } 453 454 // PendingNonceAt implements PendingStateReader.PendingNonceAt, retrieving 455 // the nonce currently pending for the account. 456 func (b *SimulatedBackend) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) { 457 b.mu.Lock() 458 defer b.mu.Unlock() 459 460 return b.pendingState.GetOrNewStateObject(account).Nonce(), nil 461 } 462 463 // SuggestGasPrice implements ContractTransactor.SuggestGasPrice. Since the simulated 464 // chain doesn't have miners, we just return a gas price of 1 for any call. 465 func (b *SimulatedBackend) SuggestGasPrice(ctx context.Context) (*big.Int, error) { 466 b.mu.Lock() 467 defer b.mu.Unlock() 468 469 if b.pendingBlock.Header().BaseFee != nil { 470 return b.pendingBlock.Header().BaseFee, nil 471 } 472 return big.NewInt(1), nil 473 } 474 475 // SuggestGasTipCap implements ContractTransactor.SuggestGasTipCap. Since the simulated 476 // chain doesn't have miners, we just return a gas tip of 1 for any call. 477 func (b *SimulatedBackend) SuggestGasTipCap(ctx context.Context) (*big.Int, error) { 478 return big.NewInt(1), nil 479 } 480 481 // EstimateGas executes the requested code against the currently pending block/state and 482 // returns the used amount of gas. 483 func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMsg) (uint64, error) { 484 b.mu.Lock() 485 defer b.mu.Unlock() 486 487 // Determine the lowest and highest possible gas limits to binary search in between 488 var ( 489 lo uint64 = params.TxGas - 1 490 hi uint64 491 cap uint64 492 ) 493 if call.Gas >= params.TxGas { 494 hi = call.Gas 495 } else { 496 hi = b.pendingBlock.GasLimit() 497 } 498 // Normalize the max fee per gas the call is willing to spend. 499 var feeCap *big.Int 500 if call.GasPrice != nil && (call.GasFeeCap != nil || call.GasTipCap != nil) { 501 return 0, errors.New("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified") 502 } else if call.GasPrice != nil { 503 feeCap = call.GasPrice 504 } else if call.GasFeeCap != nil { 505 feeCap = call.GasFeeCap 506 } else { 507 feeCap = common.Big0 508 } 509 // Recap the highest gas allowance with account's balance. 510 if feeCap.BitLen() != 0 { 511 balance := b.pendingState.GetBalance(call.From) // from can't be nil 512 available := new(big.Int).Set(balance) 513 if call.Value != nil { 514 if call.Value.Cmp(available) >= 0 { 515 return 0, errors.New("insufficient funds for transfer") 516 } 517 available.Sub(available, call.Value) 518 } 519 allowance := new(big.Int).Div(available, feeCap) 520 if allowance.IsUint64() && hi > allowance.Uint64() { 521 transfer := call.Value 522 if transfer == nil { 523 transfer = new(big.Int) 524 } 525 log.Warn("Gas estimation capped by limited funds", "original", hi, "balance", balance, 526 "sent", transfer, "feecap", feeCap, "fundable", allowance) 527 hi = allowance.Uint64() 528 } 529 } 530 cap = hi 531 532 // Create a helper to check if a gas allowance results in an executable transaction 533 executable := func(gas uint64) (bool, *core.ExecutionResult, error) { 534 call.Gas = gas 535 536 snapshot := b.pendingState.Snapshot() 537 res, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState) 538 b.pendingState.RevertToSnapshot(snapshot) 539 540 if err != nil { 541 if errors.Is(err, core.ErrIntrinsicGas) { 542 return true, nil, nil // Special case, raise gas limit 543 } 544 return true, nil, err // Bail out 545 } 546 return res.Failed(), res, nil 547 } 548 // Execute the binary search and hone in on an executable gas limit 549 for lo+1 < hi { 550 mid := (hi + lo) / 2 551 failed, _, err := executable(mid) 552 553 // If the error is not nil(consensus error), it means the provided message 554 // call or transaction will never be accepted no matter how much gas it is 555 // assigned. Return the error directly, don't struggle any more 556 if err != nil { 557 return 0, err 558 } 559 if failed { 560 lo = mid 561 } else { 562 hi = mid 563 } 564 } 565 // Reject the transaction as invalid if it still fails at the highest allowance 566 if hi == cap { 567 failed, result, err := executable(hi) 568 if err != nil { 569 return 0, err 570 } 571 if failed { 572 if result != nil && result.Err != vm.ErrOutOfGas { 573 if len(result.Revert()) > 0 { 574 return 0, newRevertError(result) 575 } 576 return 0, result.Err 577 } 578 // Otherwise, the specified gas cap is too low 579 return 0, fmt.Errorf("gas required exceeds allowance (%d)", cap) 580 } 581 } 582 return hi, nil 583 } 584 585 // callContract implements common code between normal and pending contract calls. 586 // state is modified during execution, make sure to copy it if necessary. 587 func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallMsg, block *types.Block, stateDB *state.StateDB) (*core.ExecutionResult, error) { 588 // Gas prices post 1559 need to be initialized 589 if call.GasPrice != nil && (call.GasFeeCap != nil || call.GasTipCap != nil) { 590 return nil, errors.New("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified") 591 } 592 head := b.blockchain.CurrentHeader() 593 if !b.blockchain.Config().IsLondon(head.Number) { 594 // If there's no basefee, then it must be a non-1559 execution 595 if call.GasPrice == nil { 596 call.GasPrice = new(big.Int) 597 } 598 call.GasFeeCap, call.GasTipCap = call.GasPrice, call.GasPrice 599 } else { 600 // A basefee is provided, necessitating 1559-type execution 601 if call.GasPrice != nil { 602 // User specified the legacy gas field, convert to 1559 gas typing 603 call.GasFeeCap, call.GasTipCap = call.GasPrice, call.GasPrice 604 } else { 605 // User specified 1559 gas feilds (or none), use those 606 if call.GasFeeCap == nil { 607 call.GasFeeCap = new(big.Int) 608 } 609 if call.GasTipCap == nil { 610 call.GasTipCap = new(big.Int) 611 } 612 // Backfill the legacy gasPrice for EVM execution, unless we're all zeroes 613 call.GasPrice = new(big.Int) 614 if call.GasFeeCap.BitLen() > 0 || call.GasTipCap.BitLen() > 0 { 615 if head.BaseFee != nil { 616 call.GasPrice = math.BigMin(new(big.Int).Add(call.GasTipCap, head.BaseFee), call.GasFeeCap) 617 } else { 618 call.GasPrice = math.BigMin(call.GasTipCap, call.GasFeeCap) 619 } 620 } 621 } 622 } 623 // Ensure message is initialized properly. 624 if call.Gas == 0 { 625 call.Gas = 50000000 626 } 627 if call.Value == nil { 628 call.Value = new(big.Int) 629 } 630 // Set infinite balance to the fake caller account. 631 from := stateDB.GetOrNewStateObject(call.From) 632 from.SetBalance(math.MaxBig256) 633 // Execute the call. 634 msg := callMsg{call} 635 636 txContext := core.NewEVMTxContext(msg) 637 evmContext := core.NewEVMBlockContext(block.Header(), b.blockchain, b.config, nil) 638 // Create a new environment which holds all relevant information 639 // about the transaction and calling mechanisms. 640 vmEnv := vm.NewEVM(evmContext, txContext, stateDB, b.config, vm.Config{NoBaseFee: true}) 641 gasPool := new(core.GasPool).AddGas(math.MaxUint64) 642 signer := types.MakeSigner(b.blockchain.Config(), head.Number) 643 l1DataFee, err := fees.EstimateL1DataFeeForMessage(msg, head.BaseFee, b.blockchain.Config().ChainID, signer, stateDB) 644 if err != nil { 645 return nil, err 646 } 647 648 return core.NewStateTransition(vmEnv, msg, gasPool, l1DataFee).TransitionDb() 649 } 650 651 // SendTransaction updates the pending block to include the given transaction. 652 // It panics if the transaction is invalid. 653 func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transaction) error { 654 b.mu.Lock() 655 defer b.mu.Unlock() 656 657 // Get the last block 658 block, err := b.blockByHash(ctx, b.pendingBlock.ParentHash()) 659 if err != nil { 660 panic("could not fetch parent") 661 } 662 // Check transaction validity 663 signer := types.MakeSigner(b.blockchain.Config(), block.Number()) 664 sender, err := types.Sender(signer, tx) 665 if err != nil { 666 panic(fmt.Errorf("invalid transaction: %v", err)) 667 } 668 nonce := b.pendingState.GetNonce(sender) 669 if tx.Nonce() != nonce { 670 panic(fmt.Errorf("invalid transaction nonce: got %d, want %d", tx.Nonce(), nonce)) 671 } 672 // Include tx in chain 673 blocks, _ := core.GenerateChain(b.config, block, ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) { 674 for _, tx := range b.pendingBlock.Transactions() { 675 block.AddTxWithChain(b.blockchain, tx) 676 } 677 block.AddTxWithChain(b.blockchain, tx) 678 }) 679 stateDB, _ := b.blockchain.State() 680 681 b.pendingBlock = blocks[0] 682 b.pendingState, _ = state.New(b.pendingBlock.Root(), stateDB.Database(), nil) 683 return nil 684 } 685 686 // FilterLogs executes a log filter operation, blocking during execution and 687 // returning all the results in one batch. 688 // 689 // TODO(karalabe): Deprecate when the subscription one can return past data too. 690 func (b *SimulatedBackend) FilterLogs(ctx context.Context, query ethereum.FilterQuery) ([]types.Log, error) { 691 var filter *filters.Filter 692 if query.BlockHash != nil { 693 // Block filter requested, construct a single-shot filter 694 filter = filters.NewBlockFilter(&filterBackend{b.database, b.blockchain}, *query.BlockHash, query.Addresses, query.Topics) 695 } else { 696 // Initialize unset filter boundaries to run from genesis to chain head 697 from := int64(0) 698 if query.FromBlock != nil { 699 from = query.FromBlock.Int64() 700 } 701 to := int64(-1) 702 if query.ToBlock != nil { 703 to = query.ToBlock.Int64() 704 } 705 // Construct the range filter 706 filter = filters.NewRangeFilter(&filterBackend{b.database, b.blockchain}, from, to, query.Addresses, query.Topics) 707 } 708 // Run the filter and return all the logs 709 logs, err := filter.Logs(ctx) 710 if err != nil { 711 return nil, err 712 } 713 res := make([]types.Log, len(logs)) 714 for i, nLog := range logs { 715 res[i] = *nLog 716 } 717 return res, nil 718 } 719 720 // SubscribeFilterLogs creates a background log filtering operation, returning a 721 // subscription immediately, which can be used to stream the found events. 722 func (b *SimulatedBackend) SubscribeFilterLogs(ctx context.Context, query ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) { 723 // Subscribe to contract events 724 sink := make(chan []*types.Log) 725 726 sub, err := b.events.SubscribeLogs(query, sink) 727 if err != nil { 728 return nil, err 729 } 730 // Since we're getting logs in batches, we need to flatten them into a plain stream 731 return event.NewSubscription(func(quit <-chan struct{}) error { 732 defer sub.Unsubscribe() 733 for { 734 select { 735 case logs := <-sink: 736 for _, nlog := range logs { 737 select { 738 case ch <- *nlog: 739 case err := <-sub.Err(): 740 return err 741 case <-quit: 742 return nil 743 } 744 } 745 case err := <-sub.Err(): 746 return err 747 case <-quit: 748 return nil 749 } 750 } 751 }), nil 752 } 753 754 // SubscribeNewHead returns an event subscription for a new header. 755 func (b *SimulatedBackend) SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (ethereum.Subscription, error) { 756 // subscribe to a new head 757 sink := make(chan *types.Header) 758 sub := b.events.SubscribeNewHeads(sink) 759 760 return event.NewSubscription(func(quit <-chan struct{}) error { 761 defer sub.Unsubscribe() 762 for { 763 select { 764 case head := <-sink: 765 select { 766 case ch <- head: 767 case err := <-sub.Err(): 768 return err 769 case <-quit: 770 return nil 771 } 772 case err := <-sub.Err(): 773 return err 774 case <-quit: 775 return nil 776 } 777 } 778 }), nil 779 } 780 781 // AdjustTime adds a time shift to the simulated clock. 782 // It can only be called on empty blocks. 783 func (b *SimulatedBackend) AdjustTime(adjustment time.Duration) error { 784 b.mu.Lock() 785 defer b.mu.Unlock() 786 787 if len(b.pendingBlock.Transactions()) != 0 { 788 return errors.New("Could not adjust time on non-empty block") 789 } 790 791 blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) { 792 block.OffsetTime(int64(adjustment.Seconds())) 793 }) 794 stateDB, _ := b.blockchain.State() 795 796 b.pendingBlock = blocks[0] 797 b.pendingState, _ = state.New(b.pendingBlock.Root(), stateDB.Database(), nil) 798 799 return nil 800 } 801 802 // Blockchain returns the underlying blockchain. 803 func (b *SimulatedBackend) Blockchain() *core.BlockChain { 804 return b.blockchain 805 } 806 807 // callMsg implements core.Message to allow passing it as a transaction simulator. 808 type callMsg struct { 809 ethereum.CallMsg 810 } 811 812 func (m callMsg) From() common.Address { return m.CallMsg.From } 813 func (m callMsg) Nonce() uint64 { return 0 } 814 func (m callMsg) IsFake() bool { return true } 815 func (m callMsg) To() *common.Address { return m.CallMsg.To } 816 func (m callMsg) GasPrice() *big.Int { return m.CallMsg.GasPrice } 817 func (m callMsg) GasFeeCap() *big.Int { return m.CallMsg.GasFeeCap } 818 func (m callMsg) GasTipCap() *big.Int { return m.CallMsg.GasTipCap } 819 func (m callMsg) Gas() uint64 { return m.CallMsg.Gas } 820 func (m callMsg) Value() *big.Int { return m.CallMsg.Value } 821 func (m callMsg) Data() []byte { return m.CallMsg.Data } 822 func (m callMsg) AccessList() types.AccessList { return m.CallMsg.AccessList } 823 func (m callMsg) IsL1MessageTx() bool { return false } 824 825 // filterBackend implements filters.Backend to support filtering for logs without 826 // taking bloom-bits acceleration structures into account. 827 type filterBackend struct { 828 db ethdb.Database 829 bc *core.BlockChain 830 } 831 832 func (fb *filterBackend) ChainDb() ethdb.Database { return fb.db } 833 func (fb *filterBackend) EventMux() *event.TypeMux { panic("not supported") } 834 835 func (fb *filterBackend) HeaderByNumber(ctx context.Context, block rpc.BlockNumber) (*types.Header, error) { 836 if block == rpc.LatestBlockNumber { 837 return fb.bc.CurrentHeader(), nil 838 } 839 return fb.bc.GetHeaderByNumber(uint64(block.Int64())), nil 840 } 841 842 func (fb *filterBackend) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) { 843 return fb.bc.GetHeaderByHash(hash), nil 844 } 845 846 func (fb *filterBackend) GetReceipts(ctx context.Context, hash common.Hash) (types.Receipts, error) { 847 number := rawdb.ReadHeaderNumber(fb.db, hash) 848 if number == nil { 849 return nil, nil 850 } 851 return rawdb.ReadReceipts(fb.db, hash, *number, fb.bc.Config()), nil 852 } 853 854 func (fb *filterBackend) GetLogs(ctx context.Context, hash common.Hash) ([][]*types.Log, error) { 855 number := rawdb.ReadHeaderNumber(fb.db, hash) 856 if number == nil { 857 return nil, nil 858 } 859 receipts := rawdb.ReadReceipts(fb.db, hash, *number, fb.bc.Config()) 860 if receipts == nil { 861 return nil, nil 862 } 863 logs := make([][]*types.Log, len(receipts)) 864 for i, receipt := range receipts { 865 logs[i] = receipt.Logs 866 } 867 return logs, nil 868 } 869 870 func (fb *filterBackend) SubscribeNewTxsEvent(ch chan<- core.NewTxsEvent) event.Subscription { 871 return nullSubscription() 872 } 873 874 func (fb *filterBackend) SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription { 875 return fb.bc.SubscribeChainEvent(ch) 876 } 877 878 func (fb *filterBackend) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription { 879 return fb.bc.SubscribeRemovedLogsEvent(ch) 880 } 881 882 func (fb *filterBackend) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription { 883 return fb.bc.SubscribeLogsEvent(ch) 884 } 885 886 func (fb *filterBackend) SubscribePendingLogsEvent(ch chan<- []*types.Log) event.Subscription { 887 return nullSubscription() 888 } 889 890 func (fb *filterBackend) BloomStatus() (uint64, uint64) { return 4096, 0 } 891 892 func (fb *filterBackend) ServiceFilter(ctx context.Context, ms *bloombits.MatcherSession) { 893 panic("not supported") 894 } 895 896 func nullSubscription() event.Subscription { 897 return event.NewSubscription(func(quit <-chan struct{}) error { 898 <-quit 899 return nil 900 }) 901 }