github.com/tuotoo/go-ethereum@v1.7.4-0.20171121184211-049797d40a24/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/state" 34 "github.com/ethereum/go-ethereum/core/types" 35 "github.com/ethereum/go-ethereum/core/vm" 36 "github.com/ethereum/go-ethereum/ethdb" 37 "github.com/ethereum/go-ethereum/params" 38 ) 39 40 // This nil assignment ensures compile time that SimulatedBackend implements bind.ContractBackend. 41 var _ bind.ContractBackend = (*SimulatedBackend)(nil) 42 43 var errBlockNumberUnsupported = errors.New("SimulatedBackend cannot access blocks other than the latest block") 44 var errGasEstimationFailed = errors.New("gas required exceeds allowance or always failing transaction") 45 46 // SimulatedBackend implements bind.ContractBackend, simulating a blockchain in 47 // the background. Its main purpose is to allow easily testing contract bindings. 48 type SimulatedBackend struct { 49 database ethdb.Database // In memory database to store our testing data 50 blockchain *core.BlockChain // Ethereum blockchain to handle the consensus 51 52 mu sync.Mutex 53 pendingBlock *types.Block // Currently pending block that will be imported on request 54 pendingState *state.StateDB // Currently pending state that will be the active on on request 55 56 config *params.ChainConfig 57 } 58 59 // NewSimulatedBackend creates a new binding backend using a simulated blockchain 60 // for testing purposes. 61 func NewSimulatedBackend(alloc core.GenesisAlloc) *SimulatedBackend { 62 database, _ := ethdb.NewMemDatabase() 63 genesis := core.Genesis{Config: params.AllEthashProtocolChanges, Alloc: alloc} 64 genesis.MustCommit(database) 65 blockchain, _ := core.NewBlockChain(database, genesis.Config, ethash.NewFaker(), vm.Config{}) 66 backend := &SimulatedBackend{database: database, blockchain: blockchain, config: genesis.Config} 67 backend.rollback() 68 return backend 69 } 70 71 // Commit imports all the pending transactions as a single block and starts a 72 // fresh new state. 73 func (b *SimulatedBackend) Commit() { 74 b.mu.Lock() 75 defer b.mu.Unlock() 76 77 if _, err := b.blockchain.InsertChain([]*types.Block{b.pendingBlock}); err != nil { 78 panic(err) // This cannot happen unless the simulator is wrong, fail in that case 79 } 80 b.rollback() 81 } 82 83 // Rollback aborts all pending transactions, reverting to the last committed state. 84 func (b *SimulatedBackend) Rollback() { 85 b.mu.Lock() 86 defer b.mu.Unlock() 87 88 b.rollback() 89 } 90 91 func (b *SimulatedBackend) rollback() { 92 blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), b.database, 1, func(int, *core.BlockGen) {}) 93 b.pendingBlock = blocks[0] 94 b.pendingState, _ = state.New(b.pendingBlock.Root(), state.NewDatabase(b.database)) 95 } 96 97 // CodeAt returns the code associated with a certain account in the blockchain. 98 func (b *SimulatedBackend) CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error) { 99 b.mu.Lock() 100 defer b.mu.Unlock() 101 102 if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 { 103 return nil, errBlockNumberUnsupported 104 } 105 statedb, _ := b.blockchain.State() 106 return statedb.GetCode(contract), nil 107 } 108 109 // BalanceAt returns the wei balance of a certain account in the blockchain. 110 func (b *SimulatedBackend) BalanceAt(ctx context.Context, contract common.Address, blockNumber *big.Int) (*big.Int, error) { 111 b.mu.Lock() 112 defer b.mu.Unlock() 113 114 if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 { 115 return nil, errBlockNumberUnsupported 116 } 117 statedb, _ := b.blockchain.State() 118 return statedb.GetBalance(contract), nil 119 } 120 121 // NonceAt returns the nonce of a certain account in the blockchain. 122 func (b *SimulatedBackend) NonceAt(ctx context.Context, contract common.Address, blockNumber *big.Int) (uint64, error) { 123 b.mu.Lock() 124 defer b.mu.Unlock() 125 126 if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 { 127 return 0, errBlockNumberUnsupported 128 } 129 statedb, _ := b.blockchain.State() 130 return statedb.GetNonce(contract), nil 131 } 132 133 // StorageAt returns the value of key in the storage of an account in the blockchain. 134 func (b *SimulatedBackend) StorageAt(ctx context.Context, contract common.Address, key common.Hash, blockNumber *big.Int) ([]byte, error) { 135 b.mu.Lock() 136 defer b.mu.Unlock() 137 138 if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 { 139 return nil, errBlockNumberUnsupported 140 } 141 statedb, _ := b.blockchain.State() 142 val := statedb.GetState(contract, key) 143 return val[:], nil 144 } 145 146 // TransactionReceipt returns the receipt of a transaction. 147 func (b *SimulatedBackend) TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) { 148 receipt, _, _, _ := core.GetReceipt(b.database, txHash) 149 return receipt, nil 150 } 151 152 // PendingCodeAt returns the code associated with an account in the pending state. 153 func (b *SimulatedBackend) PendingCodeAt(ctx context.Context, contract common.Address) ([]byte, error) { 154 b.mu.Lock() 155 defer b.mu.Unlock() 156 157 return b.pendingState.GetCode(contract), nil 158 } 159 160 // CallContract executes a contract call. 161 func (b *SimulatedBackend) CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) { 162 b.mu.Lock() 163 defer b.mu.Unlock() 164 165 if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 { 166 return nil, errBlockNumberUnsupported 167 } 168 state, err := b.blockchain.State() 169 if err != nil { 170 return nil, err 171 } 172 rval, _, _, err := b.callContract(ctx, call, b.blockchain.CurrentBlock(), state) 173 return rval, err 174 } 175 176 // PendingCallContract executes a contract call on the pending state. 177 func (b *SimulatedBackend) PendingCallContract(ctx context.Context, call ethereum.CallMsg) ([]byte, error) { 178 b.mu.Lock() 179 defer b.mu.Unlock() 180 defer b.pendingState.RevertToSnapshot(b.pendingState.Snapshot()) 181 182 rval, _, _, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState) 183 return rval, err 184 } 185 186 // PendingNonceAt implements PendingStateReader.PendingNonceAt, retrieving 187 // the nonce currently pending for the account. 188 func (b *SimulatedBackend) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) { 189 b.mu.Lock() 190 defer b.mu.Unlock() 191 192 return b.pendingState.GetOrNewStateObject(account).Nonce(), nil 193 } 194 195 // SuggestGasPrice implements ContractTransactor.SuggestGasPrice. Since the simulated 196 // chain doens't have miners, we just return a gas price of 1 for any call. 197 func (b *SimulatedBackend) SuggestGasPrice(ctx context.Context) (*big.Int, error) { 198 return big.NewInt(1), nil 199 } 200 201 // EstimateGas executes the requested code against the currently pending block/state and 202 // returns the used amount of gas. 203 func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMsg) (*big.Int, error) { 204 b.mu.Lock() 205 defer b.mu.Unlock() 206 207 // Determine the lowest and highest possible gas limits to binary search in between 208 var ( 209 lo uint64 = params.TxGas - 1 210 hi uint64 211 cap uint64 212 ) 213 if call.Gas != nil && call.Gas.Uint64() >= params.TxGas { 214 hi = call.Gas.Uint64() 215 } else { 216 hi = b.pendingBlock.GasLimit().Uint64() 217 } 218 cap = hi 219 220 // Create a helper to check if a gas allowance results in an executable transaction 221 executable := func(gas uint64) bool { 222 call.Gas = new(big.Int).SetUint64(gas) 223 224 snapshot := b.pendingState.Snapshot() 225 _, _, failed, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState) 226 b.pendingState.RevertToSnapshot(snapshot) 227 228 if err != nil || failed { 229 return false 230 } 231 return true 232 } 233 // Execute the binary search and hone in on an executable gas limit 234 for lo+1 < hi { 235 mid := (hi + lo) / 2 236 if !executable(mid) { 237 lo = mid 238 } else { 239 hi = mid 240 } 241 } 242 // Reject the transaction as invalid if it still fails at the highest allowance 243 if hi == cap { 244 if !executable(hi) { 245 return nil, errGasEstimationFailed 246 } 247 } 248 return new(big.Int).SetUint64(hi), nil 249 } 250 251 // callContract implemens common code between normal and pending contract calls. 252 // state is modified during execution, make sure to copy it if necessary. 253 func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallMsg, block *types.Block, statedb *state.StateDB) ([]byte, *big.Int, bool, error) { 254 // Ensure message is initialized properly. 255 if call.GasPrice == nil { 256 call.GasPrice = big.NewInt(1) 257 } 258 if call.Gas == nil || call.Gas.Sign() == 0 { 259 call.Gas = big.NewInt(50000000) 260 } 261 if call.Value == nil { 262 call.Value = new(big.Int) 263 } 264 // Set infinite balance to the fake caller account. 265 from := statedb.GetOrNewStateObject(call.From) 266 from.SetBalance(math.MaxBig256) 267 // Execute the call. 268 msg := callmsg{call} 269 270 evmContext := core.NewEVMContext(msg, block.Header(), b.blockchain, nil) 271 // Create a new environment which holds all relevant information 272 // about the transaction and calling mechanisms. 273 vmenv := vm.NewEVM(evmContext, statedb, b.config, vm.Config{}) 274 gaspool := new(core.GasPool).AddGas(math.MaxBig256) 275 ret, gasUsed, _, failed, err := core.NewStateTransition(vmenv, msg, gaspool).TransitionDb() 276 return ret, gasUsed, failed, err 277 } 278 279 // SendTransaction updates the pending block to include the given transaction. 280 // It panics if the transaction is invalid. 281 func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transaction) error { 282 b.mu.Lock() 283 defer b.mu.Unlock() 284 285 sender, err := types.Sender(types.HomesteadSigner{}, tx) 286 if err != nil { 287 panic(fmt.Errorf("invalid transaction: %v", err)) 288 } 289 nonce := b.pendingState.GetNonce(sender) 290 if tx.Nonce() != nonce { 291 panic(fmt.Errorf("invalid transaction nonce: got %d, want %d", tx.Nonce(), nonce)) 292 } 293 294 blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), b.database, 1, func(number int, block *core.BlockGen) { 295 for _, tx := range b.pendingBlock.Transactions() { 296 block.AddTx(tx) 297 } 298 block.AddTx(tx) 299 }) 300 b.pendingBlock = blocks[0] 301 b.pendingState, _ = state.New(b.pendingBlock.Root(), state.NewDatabase(b.database)) 302 return nil 303 } 304 305 // JumpTimeInSeconds adds skip seconds to the clock 306 func (b *SimulatedBackend) AdjustTime(adjustment time.Duration) error { 307 b.mu.Lock() 308 defer b.mu.Unlock() 309 blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), b.database, 1, func(number int, block *core.BlockGen) { 310 for _, tx := range b.pendingBlock.Transactions() { 311 block.AddTx(tx) 312 } 313 block.OffsetTime(int64(adjustment.Seconds())) 314 }) 315 b.pendingBlock = blocks[0] 316 b.pendingState, _ = state.New(b.pendingBlock.Root(), state.NewDatabase(b.database)) 317 318 return nil 319 } 320 321 // callmsg implements core.Message to allow passing it as a transaction simulator. 322 type callmsg struct { 323 ethereum.CallMsg 324 } 325 326 func (m callmsg) From() common.Address { return m.CallMsg.From } 327 func (m callmsg) Nonce() uint64 { return 0 } 328 func (m callmsg) CheckNonce() bool { return false } 329 func (m callmsg) To() *common.Address { return m.CallMsg.To } 330 func (m callmsg) GasPrice() *big.Int { return m.CallMsg.GasPrice } 331 func (m callmsg) Gas() *big.Int { return m.CallMsg.Gas } 332 func (m callmsg) Value() *big.Int { return m.CallMsg.Value } 333 func (m callmsg) Data() []byte { return m.CallMsg.Data }