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