gitlab.com/yannislg/go-pulse@v0.0.0-20210722055913-a3e24e95638d/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/bind" 29 "github.com/ethereum/go-ethereum/common" 30 "github.com/ethereum/go-ethereum/common/math" 31 "github.com/ethereum/go-ethereum/consensus/ethash" 32 "github.com/ethereum/go-ethereum/core" 33 "github.com/ethereum/go-ethereum/core/bloombits" 34 "github.com/ethereum/go-ethereum/core/rawdb" 35 "github.com/ethereum/go-ethereum/core/state" 36 "github.com/ethereum/go-ethereum/core/types" 37 "github.com/ethereum/go-ethereum/core/vm" 38 "github.com/ethereum/go-ethereum/eth/filters" 39 "github.com/ethereum/go-ethereum/ethdb" 40 "github.com/ethereum/go-ethereum/event" 41 "github.com/ethereum/go-ethereum/params" 42 "github.com/ethereum/go-ethereum/rpc" 43 ) 44 45 // This nil assignment ensures compile time that SimulatedBackend implements bind.ContractBackend. 46 var _ bind.ContractBackend = (*SimulatedBackend)(nil) 47 48 var ( 49 errBlockNumberUnsupported = errors.New("simulatedBackend cannot access blocks other than the latest block") 50 errBlockDoesNotExist = errors.New("block does not exist in blockchain") 51 errTransactionDoesNotExist = errors.New("transaction does not exist") 52 errGasEstimationFailed = errors.New("gas required exceeds allowance or always failing transaction") 53 ) 54 55 // SimulatedBackend implements bind.ContractBackend, simulating a blockchain in 56 // the background. Its main purpose is to allow easily testing contract bindings. 57 // Simulated backend implements the following interfaces: 58 // ChainReader, ChainStateReader, ContractBackend, ContractCaller, ContractFilterer, ContractTransactor, 59 // DeployBackend, GasEstimator, GasPricer, LogFilterer, PendingContractCaller, TransactionReader, and TransactionSender 60 type SimulatedBackend struct { 61 database ethdb.Database // In memory database to store our testing data 62 blockchain *core.BlockChain // Ethereum blockchain to handle the consensus 63 64 mu sync.Mutex 65 pendingBlock *types.Block // Currently pending block that will be imported on request 66 pendingState *state.StateDB // Currently pending state that will be the active on on request 67 68 events *filters.EventSystem // Event system for filtering log events live 69 70 config *params.ChainConfig 71 } 72 73 // NewSimulatedBackendWithDatabase creates a new binding backend based on the given database 74 // and uses a simulated blockchain for testing purposes. 75 func NewSimulatedBackendWithDatabase(database ethdb.Database, alloc core.GenesisAlloc, gasLimit uint64) *SimulatedBackend { 76 genesis := core.Genesis{Config: params.AllEthashProtocolChanges, GasLimit: gasLimit, Alloc: alloc} 77 genesis.MustCommit(database) 78 blockchain, _ := core.NewBlockChain(database, nil, genesis.Config, ethash.NewFaker(), vm.Config{}, nil) 79 80 backend := &SimulatedBackend{ 81 database: database, 82 blockchain: blockchain, 83 config: genesis.Config, 84 events: filters.NewEventSystem(&filterBackend{database, blockchain}, false), 85 } 86 backend.rollback() 87 return backend 88 } 89 90 // NewSimulatedBackend creates a new binding backend using a simulated blockchain 91 // for testing purposes. 92 func NewSimulatedBackend(alloc core.GenesisAlloc, gasLimit uint64) *SimulatedBackend { 93 return NewSimulatedBackendWithDatabase(rawdb.NewMemoryDatabase(), alloc, gasLimit) 94 } 95 96 // Close terminates the underlying blockchain's update loop. 97 func (b *SimulatedBackend) Close() error { 98 b.blockchain.Stop() 99 return nil 100 } 101 102 // Commit imports all the pending transactions as a single block and starts a 103 // fresh new state. 104 func (b *SimulatedBackend) Commit() { 105 b.mu.Lock() 106 defer b.mu.Unlock() 107 108 if _, err := b.blockchain.InsertChain([]*types.Block{b.pendingBlock}); err != nil { 109 panic(err) // This cannot happen unless the simulator is wrong, fail in that case 110 } 111 b.rollback() 112 } 113 114 // Rollback aborts all pending transactions, reverting to the last committed state. 115 func (b *SimulatedBackend) Rollback() { 116 b.mu.Lock() 117 defer b.mu.Unlock() 118 119 b.rollback() 120 } 121 122 func (b *SimulatedBackend) rollback() { 123 blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(int, *core.BlockGen) {}) 124 statedb, _ := b.blockchain.State() 125 126 b.pendingBlock = blocks[0] 127 b.pendingState, _ = state.New(b.pendingBlock.Root(), statedb.Database(), nil) 128 } 129 130 // stateByBlockNumber retrieves a state by a given blocknumber. 131 func (b *SimulatedBackend) stateByBlockNumber(ctx context.Context, blockNumber *big.Int) (*state.StateDB, error) { 132 if blockNumber == nil || blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) == 0 { 133 return b.blockchain.State() 134 } 135 block, err := b.BlockByNumber(ctx, blockNumber) 136 if err != nil { 137 return nil, err 138 } 139 return b.blockchain.StateAt(block.Hash()) 140 } 141 142 // CodeAt returns the code associated with a certain account in the blockchain. 143 func (b *SimulatedBackend) CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error) { 144 b.mu.Lock() 145 defer b.mu.Unlock() 146 147 statedb, err := b.stateByBlockNumber(ctx, blockNumber) 148 if err != nil { 149 return nil, err 150 } 151 152 return statedb.GetCode(contract), nil 153 } 154 155 // BalanceAt returns the wei balance of a certain account in the blockchain. 156 func (b *SimulatedBackend) BalanceAt(ctx context.Context, contract common.Address, blockNumber *big.Int) (*big.Int, error) { 157 b.mu.Lock() 158 defer b.mu.Unlock() 159 160 statedb, err := b.stateByBlockNumber(ctx, blockNumber) 161 if err != nil { 162 return nil, err 163 } 164 165 return statedb.GetBalance(contract), nil 166 } 167 168 // NonceAt returns the nonce of a certain account in the blockchain. 169 func (b *SimulatedBackend) NonceAt(ctx context.Context, contract common.Address, blockNumber *big.Int) (uint64, error) { 170 b.mu.Lock() 171 defer b.mu.Unlock() 172 173 statedb, err := b.stateByBlockNumber(ctx, blockNumber) 174 if err != nil { 175 return 0, err 176 } 177 178 return statedb.GetNonce(contract), nil 179 } 180 181 // StorageAt returns the value of key in the storage of an account in the blockchain. 182 func (b *SimulatedBackend) StorageAt(ctx context.Context, contract common.Address, key common.Hash, blockNumber *big.Int) ([]byte, error) { 183 b.mu.Lock() 184 defer b.mu.Unlock() 185 186 statedb, err := b.stateByBlockNumber(ctx, blockNumber) 187 if err != nil { 188 return nil, err 189 } 190 191 val := statedb.GetState(contract, key) 192 return val[:], nil 193 } 194 195 // TransactionReceipt returns the receipt of a transaction. 196 func (b *SimulatedBackend) TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) { 197 b.mu.Lock() 198 defer b.mu.Unlock() 199 200 receipt, _, _, _ := rawdb.ReadReceipt(b.database, txHash, b.config) 201 return receipt, nil 202 } 203 204 // TransactionByHash checks the pool of pending transactions in addition to the 205 // blockchain. The isPending return value indicates whether the transaction has been 206 // mined yet. Note that the transaction may not be part of the canonical chain even if 207 // it's not pending. 208 func (b *SimulatedBackend) TransactionByHash(ctx context.Context, txHash common.Hash) (*types.Transaction, bool, error) { 209 b.mu.Lock() 210 defer b.mu.Unlock() 211 212 tx := b.pendingBlock.Transaction(txHash) 213 if tx != nil { 214 return tx, true, nil 215 } 216 tx, _, _, _ = rawdb.ReadTransaction(b.database, txHash) 217 if tx != nil { 218 return tx, false, nil 219 } 220 return nil, false, ethereum.NotFound 221 } 222 223 // BlockByHash retrieves a block based on the block hash 224 func (b *SimulatedBackend) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) { 225 b.mu.Lock() 226 defer b.mu.Unlock() 227 228 if hash == b.pendingBlock.Hash() { 229 return b.pendingBlock, nil 230 } 231 232 block := b.blockchain.GetBlockByHash(hash) 233 if block != nil { 234 return block, nil 235 } 236 237 return nil, errBlockDoesNotExist 238 } 239 240 // BlockByNumber retrieves a block from the database by number, caching it 241 // (associated with its hash) if found. 242 func (b *SimulatedBackend) BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error) { 243 b.mu.Lock() 244 defer b.mu.Unlock() 245 246 if number == nil || number.Cmp(b.pendingBlock.Number()) == 0 { 247 return b.blockchain.CurrentBlock(), nil 248 } 249 250 block := b.blockchain.GetBlockByNumber(uint64(number.Int64())) 251 if block == nil { 252 return nil, errBlockDoesNotExist 253 } 254 255 return block, nil 256 } 257 258 // HeaderByHash returns a block header from the current canonical chain. 259 func (b *SimulatedBackend) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) { 260 b.mu.Lock() 261 defer b.mu.Unlock() 262 263 if hash == b.pendingBlock.Hash() { 264 return b.pendingBlock.Header(), nil 265 } 266 267 header := b.blockchain.GetHeaderByHash(hash) 268 if header == nil { 269 return nil, errBlockDoesNotExist 270 } 271 272 return header, nil 273 } 274 275 // HeaderByNumber returns a block header from the current canonical chain. If number is 276 // nil, the latest known header is returned. 277 func (b *SimulatedBackend) HeaderByNumber(ctx context.Context, block *big.Int) (*types.Header, error) { 278 b.mu.Lock() 279 defer b.mu.Unlock() 280 281 if block == nil || block.Cmp(b.pendingBlock.Number()) == 0 { 282 return b.blockchain.CurrentHeader(), nil 283 } 284 285 return b.blockchain.GetHeaderByNumber(uint64(block.Int64())), nil 286 } 287 288 // TransactionCount returns the number of transactions in a given block 289 func (b *SimulatedBackend) TransactionCount(ctx context.Context, blockHash common.Hash) (uint, error) { 290 b.mu.Lock() 291 defer b.mu.Unlock() 292 293 if blockHash == b.pendingBlock.Hash() { 294 return uint(b.pendingBlock.Transactions().Len()), nil 295 } 296 297 block := b.blockchain.GetBlockByHash(blockHash) 298 if block == nil { 299 return uint(0), errBlockDoesNotExist 300 } 301 302 return uint(block.Transactions().Len()), nil 303 } 304 305 // TransactionInBlock returns the transaction for a specific block at a specific index 306 func (b *SimulatedBackend) TransactionInBlock(ctx context.Context, blockHash common.Hash, index uint) (*types.Transaction, error) { 307 b.mu.Lock() 308 defer b.mu.Unlock() 309 310 if blockHash == b.pendingBlock.Hash() { 311 transactions := b.pendingBlock.Transactions() 312 if uint(len(transactions)) < index+1 { 313 return nil, errTransactionDoesNotExist 314 } 315 316 return transactions[index], nil 317 } 318 319 block := b.blockchain.GetBlockByHash(blockHash) 320 if block == nil { 321 return nil, errBlockDoesNotExist 322 } 323 324 transactions := block.Transactions() 325 if uint(len(transactions)) < index+1 { 326 return nil, errTransactionDoesNotExist 327 } 328 329 return transactions[index], nil 330 } 331 332 // PendingCodeAt returns the code associated with an account in the pending state. 333 func (b *SimulatedBackend) PendingCodeAt(ctx context.Context, contract common.Address) ([]byte, error) { 334 b.mu.Lock() 335 defer b.mu.Unlock() 336 337 return b.pendingState.GetCode(contract), nil 338 } 339 340 // CallContract executes a contract call. 341 func (b *SimulatedBackend) CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) { 342 b.mu.Lock() 343 defer b.mu.Unlock() 344 345 if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 { 346 return nil, errBlockNumberUnsupported 347 } 348 state, err := b.blockchain.State() 349 if err != nil { 350 return nil, err 351 } 352 rval, _, _, err := b.callContract(ctx, call, b.blockchain.CurrentBlock(), state) 353 return rval, err 354 } 355 356 // PendingCallContract executes a contract call on the pending state. 357 func (b *SimulatedBackend) PendingCallContract(ctx context.Context, call ethereum.CallMsg) ([]byte, error) { 358 b.mu.Lock() 359 defer b.mu.Unlock() 360 defer b.pendingState.RevertToSnapshot(b.pendingState.Snapshot()) 361 362 rval, _, _, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState) 363 return rval, err 364 } 365 366 // PendingNonceAt implements PendingStateReader.PendingNonceAt, retrieving 367 // the nonce currently pending for the account. 368 func (b *SimulatedBackend) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) { 369 b.mu.Lock() 370 defer b.mu.Unlock() 371 372 return b.pendingState.GetOrNewStateObject(account).Nonce(), nil 373 } 374 375 // SuggestGasPrice implements ContractTransactor.SuggestGasPrice. Since the simulated 376 // chain doesn't have miners, we just return a gas price of 1 for any call. 377 func (b *SimulatedBackend) SuggestGasPrice(ctx context.Context) (*big.Int, error) { 378 return big.NewInt(1), nil 379 } 380 381 // EstimateGas executes the requested code against the currently pending block/state and 382 // returns the used amount of gas. 383 func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMsg) (uint64, error) { 384 b.mu.Lock() 385 defer b.mu.Unlock() 386 387 // Determine the lowest and highest possible gas limits to binary search in between 388 var ( 389 lo uint64 = params.TxGas - 1 390 hi uint64 391 cap uint64 392 ) 393 if call.Gas >= params.TxGas { 394 hi = call.Gas 395 } else { 396 hi = b.pendingBlock.GasLimit() 397 } 398 cap = hi 399 400 // Create a helper to check if a gas allowance results in an executable transaction 401 executable := func(gas uint64) bool { 402 call.Gas = gas 403 404 snapshot := b.pendingState.Snapshot() 405 _, _, failed, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState) 406 b.pendingState.RevertToSnapshot(snapshot) 407 408 if err != nil || failed { 409 return false 410 } 411 return true 412 } 413 // Execute the binary search and hone in on an executable gas limit 414 for lo+1 < hi { 415 mid := (hi + lo) / 2 416 if !executable(mid) { 417 lo = mid 418 } else { 419 hi = mid 420 } 421 } 422 // Reject the transaction as invalid if it still fails at the highest allowance 423 if hi == cap { 424 if !executable(hi) { 425 return 0, errGasEstimationFailed 426 } 427 } 428 return hi, nil 429 } 430 431 // callContract implements common code between normal and pending contract calls. 432 // state is modified during execution, make sure to copy it if necessary. 433 func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallMsg, block *types.Block, statedb *state.StateDB) ([]byte, uint64, bool, error) { 434 // Ensure message is initialized properly. 435 if call.GasPrice == nil { 436 call.GasPrice = big.NewInt(1) 437 } 438 if call.Gas == 0 { 439 call.Gas = 50000000 440 } 441 if call.Value == nil { 442 call.Value = new(big.Int) 443 } 444 // Set infinite balance to the fake caller account. 445 from := statedb.GetOrNewStateObject(call.From) 446 from.SetBalance(math.MaxBig256) 447 // Execute the call. 448 msg := callmsg{call} 449 450 evmContext := core.NewEVMContext(msg, block.Header(), b.blockchain, nil) 451 // Create a new environment which holds all relevant information 452 // about the transaction and calling mechanisms. 453 vmenv := vm.NewEVM(evmContext, statedb, b.config, vm.Config{}) 454 gaspool := new(core.GasPool).AddGas(math.MaxUint64) 455 456 return core.NewStateTransition(vmenv, msg, gaspool).TransitionDb() 457 } 458 459 // SendTransaction updates the pending block to include the given transaction. 460 // It panics if the transaction is invalid. 461 func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transaction) error { 462 b.mu.Lock() 463 defer b.mu.Unlock() 464 465 sender, err := types.Sender(types.NewEIP155Signer(b.config.ChainID), tx) 466 if err != nil { 467 panic(fmt.Errorf("invalid transaction: %v", err)) 468 } 469 nonce := b.pendingState.GetNonce(sender) 470 if tx.Nonce() != nonce { 471 panic(fmt.Errorf("invalid transaction nonce: got %d, want %d", tx.Nonce(), nonce)) 472 } 473 474 blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) { 475 for _, tx := range b.pendingBlock.Transactions() { 476 block.AddTxWithChain(b.blockchain, tx) 477 } 478 block.AddTxWithChain(b.blockchain, tx) 479 }) 480 statedb, _ := b.blockchain.State() 481 482 b.pendingBlock = blocks[0] 483 b.pendingState, _ = state.New(b.pendingBlock.Root(), statedb.Database(), nil) 484 return nil 485 } 486 487 // FilterLogs executes a log filter operation, blocking during execution and 488 // returning all the results in one batch. 489 // 490 // TODO(karalabe): Deprecate when the subscription one can return past data too. 491 func (b *SimulatedBackend) FilterLogs(ctx context.Context, query ethereum.FilterQuery) ([]types.Log, error) { 492 var filter *filters.Filter 493 if query.BlockHash != nil { 494 // Block filter requested, construct a single-shot filter 495 filter = filters.NewBlockFilter(&filterBackend{b.database, b.blockchain}, *query.BlockHash, query.Addresses, query.Topics) 496 } else { 497 // Initialize unset filter boundaried to run from genesis to chain head 498 from := int64(0) 499 if query.FromBlock != nil { 500 from = query.FromBlock.Int64() 501 } 502 to := int64(-1) 503 if query.ToBlock != nil { 504 to = query.ToBlock.Int64() 505 } 506 // Construct the range filter 507 filter = filters.NewRangeFilter(&filterBackend{b.database, b.blockchain}, from, to, query.Addresses, query.Topics, false) 508 } 509 // Run the filter and return all the logs 510 logs, err := filter.Logs(ctx) 511 if err != nil { 512 return nil, err 513 } 514 res := make([]types.Log, len(logs)) 515 for i, log := range logs { 516 res[i] = *log 517 } 518 return res, nil 519 } 520 521 // SubscribeFilterLogs creates a background log filtering operation, returning a 522 // subscription immediately, which can be used to stream the found events. 523 func (b *SimulatedBackend) SubscribeFilterLogs(ctx context.Context, query ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) { 524 // Subscribe to contract events 525 sink := make(chan []*types.Log) 526 527 sub, err := b.events.SubscribeLogs(query, sink) 528 if err != nil { 529 return nil, err 530 } 531 // Since we're getting logs in batches, we need to flatten them into a plain stream 532 return event.NewSubscription(func(quit <-chan struct{}) error { 533 defer sub.Unsubscribe() 534 for { 535 select { 536 case logs := <-sink: 537 for _, log := range logs { 538 select { 539 case ch <- *log: 540 case err := <-sub.Err(): 541 return err 542 case <-quit: 543 return nil 544 } 545 } 546 case err := <-sub.Err(): 547 return err 548 case <-quit: 549 return nil 550 } 551 } 552 }), nil 553 } 554 555 // SubscribeNewHead returns an event subscription for a new header 556 func (b *SimulatedBackend) SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (ethereum.Subscription, error) { 557 // subscribe to a new head 558 sink := make(chan *types.Header) 559 sub := b.events.SubscribeNewHeads(sink) 560 561 return event.NewSubscription(func(quit <-chan struct{}) error { 562 defer sub.Unsubscribe() 563 for { 564 select { 565 case head := <-sink: 566 select { 567 case ch <- head: 568 case err := <-sub.Err(): 569 return err 570 case <-quit: 571 return nil 572 } 573 case err := <-sub.Err(): 574 return err 575 case <-quit: 576 return nil 577 } 578 } 579 }), nil 580 } 581 582 // AdjustTime adds a time shift to the simulated clock. 583 func (b *SimulatedBackend) AdjustTime(adjustment time.Duration) error { 584 b.mu.Lock() 585 defer b.mu.Unlock() 586 587 blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) { 588 for _, tx := range b.pendingBlock.Transactions() { 589 block.AddTx(tx) 590 } 591 block.OffsetTime(int64(adjustment.Seconds())) 592 }) 593 statedb, _ := b.blockchain.State() 594 595 b.pendingBlock = blocks[0] 596 b.pendingState, _ = state.New(b.pendingBlock.Root(), statedb.Database(), nil) 597 598 return nil 599 } 600 601 // Blockchain returns the underlying blockchain. 602 func (b *SimulatedBackend) Blockchain() *core.BlockChain { 603 return b.blockchain 604 } 605 606 // callmsg implements core.Message to allow passing it as a transaction simulator. 607 type callmsg struct { 608 ethereum.CallMsg 609 } 610 611 func (m callmsg) From() common.Address { return m.CallMsg.From } 612 func (m callmsg) Nonce() uint64 { return 0 } 613 func (m callmsg) CheckNonce() bool { return false } 614 func (m callmsg) To() *common.Address { return m.CallMsg.To } 615 func (m callmsg) GasPrice() *big.Int { return m.CallMsg.GasPrice } 616 func (m callmsg) Gas() uint64 { return m.CallMsg.Gas } 617 func (m callmsg) Value() *big.Int { return m.CallMsg.Value } 618 func (m callmsg) Data() []byte { return m.CallMsg.Data } 619 620 // filterBackend implements filters.Backend to support filtering for logs without 621 // taking bloom-bits acceleration structures into account. 622 type filterBackend struct { 623 db ethdb.Database 624 bc *core.BlockChain 625 } 626 627 func (fb *filterBackend) ChainDb() ethdb.Database { return fb.db } 628 func (fb *filterBackend) EventMux() *event.TypeMux { panic("not supported") } 629 630 func (fb *filterBackend) HeaderByNumber(ctx context.Context, block rpc.BlockNumber) (*types.Header, error) { 631 if block == rpc.LatestBlockNumber { 632 return fb.bc.CurrentHeader(), nil 633 } 634 return fb.bc.GetHeaderByNumber(uint64(block.Int64())), nil 635 } 636 637 func (fb *filterBackend) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) { 638 return fb.bc.GetHeaderByHash(hash), nil 639 } 640 641 func (fb *filterBackend) GetReceipts(ctx context.Context, hash common.Hash) (types.Receipts, error) { 642 number := rawdb.ReadHeaderNumber(fb.db, hash) 643 if number == nil { 644 return nil, nil 645 } 646 return rawdb.ReadReceipts(fb.db, hash, *number, fb.bc.Config()), nil 647 } 648 649 func (fb *filterBackend) GetLogs(ctx context.Context, hash common.Hash) ([][]*types.Log, error) { 650 number := rawdb.ReadHeaderNumber(fb.db, hash) 651 if number == nil { 652 return nil, nil 653 } 654 receipts := rawdb.ReadReceipts(fb.db, hash, *number, fb.bc.Config()) 655 if receipts == nil { 656 return nil, nil 657 } 658 logs := make([][]*types.Log, len(receipts)) 659 for i, receipt := range receipts { 660 logs[i] = receipt.Logs 661 } 662 return logs, nil 663 } 664 665 func (fb *filterBackend) SubscribeNewTxsEvent(ch chan<- core.NewTxsEvent) event.Subscription { 666 return nullSubscription() 667 } 668 669 func (fb *filterBackend) SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription { 670 return fb.bc.SubscribeChainEvent(ch) 671 } 672 673 func (fb *filterBackend) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription { 674 return fb.bc.SubscribeRemovedLogsEvent(ch) 675 } 676 677 func (fb *filterBackend) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription { 678 return fb.bc.SubscribeLogsEvent(ch) 679 } 680 681 func (fb *filterBackend) SubscribePendingLogsEvent(ch chan<- []*types.Log) event.Subscription { 682 return nullSubscription() 683 } 684 685 func (fb *filterBackend) BloomStatus() (uint64, uint64) { return 4096, 0 } 686 687 func (fb *filterBackend) ServiceFilter(ctx context.Context, ms *bloombits.MatcherSession) { 688 panic("not supported") 689 } 690 691 func nullSubscription() event.Subscription { 692 return event.NewSubscription(func(quit <-chan struct{}) error { 693 <-quit 694 return nil 695 }) 696 }