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