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