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