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