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