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