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