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