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