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