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