github.com/digdeepmining/go-atheios@v1.5.13-0.20180902133602-d5687a2e6f43/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 "errors" 21 "fmt" 22 "math/big" 23 "sync" 24 25 "github.com/atheioschain/go-atheios" 26 "github.com/atheioschain/go-atheios/accounts/abi/bind" 27 "github.com/atheioschain/go-atheios/common" 28 "github.com/atheioschain/go-atheios/core" 29 "github.com/atheioschain/go-atheios/core/state" 30 "github.com/atheioschain/go-atheios/core/types" 31 "github.com/atheioschain/go-atheios/core/vm" 32 "github.com/atheioschain/go-atheios/ethdb" 33 "github.com/atheioschain/go-atheios/event" 34 "github.com/atheioschain/go-atheios/params" 35 "golang.org/x/net/context" 36 ) 37 38 // Default chain configuration which sets homestead phase at block 0 (i.e. no frontier) 39 var chainConfig = ¶ms.ChainConfig{HomesteadBlock: big.NewInt(0), EIP150Block: new(big.Int), EIP158Block: new(big.Int)} 40 41 // This nil assignment ensures compile time that SimulatedBackend implements bind.ContractBackend. 42 var _ bind.ContractBackend = (*SimulatedBackend)(nil) 43 44 var errBlockNumberUnsupported = errors.New("SimulatedBackend cannot access blocks other than the latest block") 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(accounts ...core.GenesisAccount) *SimulatedBackend { 62 database, _ := ethdb.NewMemDatabase() 63 core.WriteGenesisBlockForTesting(database, accounts...) 64 blockchain, _ := core.NewBlockChain(database, chainConfig, new(core.FakePow), new(event.TypeMux), vm.Config{}) 65 backend := &SimulatedBackend{database: database, blockchain: blockchain} 66 backend.rollback() 67 return backend 68 } 69 70 // Commit imports all the pending transactions as a single block and starts a 71 // fresh new state. 72 func (b *SimulatedBackend) Commit() { 73 b.mu.Lock() 74 defer b.mu.Unlock() 75 76 if _, err := b.blockchain.InsertChain([]*types.Block{b.pendingBlock}); err != nil { 77 panic(err) // This cannot happen unless the simulator is wrong, fail in that case 78 } 79 b.rollback() 80 } 81 82 // Rollback aborts all pending transactions, reverting to the last committed state. 83 func (b *SimulatedBackend) Rollback() { 84 b.mu.Lock() 85 defer b.mu.Unlock() 86 87 b.rollback() 88 } 89 90 func (b *SimulatedBackend) rollback() { 91 blocks, _ := core.GenerateChain(chainConfig, b.blockchain.CurrentBlock(), b.database, 1, func(int, *core.BlockGen) {}) 92 b.pendingBlock = blocks[0] 93 b.pendingState, _ = state.New(b.pendingBlock.Root(), b.database) 94 } 95 96 // CodeAt returns the code associated with a certain account in the blockchain. 97 func (b *SimulatedBackend) CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error) { 98 b.mu.Lock() 99 defer b.mu.Unlock() 100 101 if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 { 102 return nil, errBlockNumberUnsupported 103 } 104 statedb, _ := b.blockchain.State() 105 return statedb.GetCode(contract), nil 106 } 107 108 // BalanceAt returns the wei balance of a certain account in the blockchain. 109 func (b *SimulatedBackend) BalanceAt(ctx context.Context, contract common.Address, blockNumber *big.Int) (*big.Int, error) { 110 b.mu.Lock() 111 defer b.mu.Unlock() 112 113 if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 { 114 return nil, errBlockNumberUnsupported 115 } 116 statedb, _ := b.blockchain.State() 117 return statedb.GetBalance(contract), nil 118 } 119 120 // NonceAt returns the nonce of a certain account in the blockchain. 121 func (b *SimulatedBackend) NonceAt(ctx context.Context, contract common.Address, blockNumber *big.Int) (uint64, error) { 122 b.mu.Lock() 123 defer b.mu.Unlock() 124 125 if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 { 126 return 0, errBlockNumberUnsupported 127 } 128 statedb, _ := b.blockchain.State() 129 return statedb.GetNonce(contract), nil 130 } 131 132 // StorageAt returns the value of key in the storage of an account in the blockchain. 133 func (b *SimulatedBackend) StorageAt(ctx context.Context, contract common.Address, key common.Hash, blockNumber *big.Int) ([]byte, error) { 134 b.mu.Lock() 135 defer b.mu.Unlock() 136 137 if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 { 138 return nil, errBlockNumberUnsupported 139 } 140 statedb, _ := b.blockchain.State() 141 val := statedb.GetState(contract, key) 142 return val[:], nil 143 } 144 145 // TransactionReceipt returns the receipt of a transaction. 146 func (b *SimulatedBackend) TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) { 147 return core.GetReceipt(b.database, txHash), 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 ethereum.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 ethereum.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 ethereum.CallMsg) (*big.Int, error) { 202 b.mu.Lock() 203 defer b.mu.Unlock() 204 205 // Binary search the gas requirement, as it may be higher than the amount used 206 var lo, hi uint64 207 if call.Gas != nil { 208 hi = call.Gas.Uint64() 209 } else { 210 hi = b.pendingBlock.GasLimit().Uint64() 211 } 212 for lo+1 < hi { 213 // Take a guess at the gas, and check transaction validity 214 mid := (hi + lo) / 2 215 call.Gas = new(big.Int).SetUint64(mid) 216 217 snapshot := b.pendingState.Snapshot() 218 _, gas, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState) 219 b.pendingState.RevertToSnapshot(snapshot) 220 221 // If the transaction became invalid or used all the gas (failed), raise the gas limit 222 if err != nil || gas.Cmp(call.Gas) == 0 { 223 lo = mid 224 continue 225 } 226 // Otherwise assume the transaction succeeded, lower the gas limit 227 hi = mid 228 } 229 return new(big.Int).SetUint64(hi), nil 230 } 231 232 // callContract implemens common code between normal and pending contract calls. 233 // state is modified during execution, make sure to copy it if necessary. 234 func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallMsg, block *types.Block, statedb *state.StateDB) ([]byte, *big.Int, error) { 235 // Ensure message is initialized properly. 236 if call.GasPrice == nil { 237 call.GasPrice = big.NewInt(1) 238 } 239 if call.Gas == nil || call.Gas.BitLen() == 0 { 240 call.Gas = big.NewInt(50000000) 241 } 242 if call.Value == nil { 243 call.Value = new(big.Int) 244 } 245 // Set infinite balance to the fake caller account. 246 from := statedb.GetOrNewStateObject(call.From) 247 from.SetBalance(common.MaxBig) 248 // Execute the call. 249 msg := callmsg{call} 250 251 evmContext := core.NewEVMContext(msg, block.Header(), b.blockchain) 252 // Create a new environment which holds all relevant information 253 // about the transaction and calling mechanisms. 254 vmenv := vm.NewEVM(evmContext, statedb, chainConfig, vm.Config{}) 255 gaspool := new(core.GasPool).AddGas(common.MaxBig) 256 ret, gasUsed, _, err := core.NewStateTransition(vmenv, msg, gaspool).TransitionDb() 257 return ret, gasUsed, err 258 } 259 260 // SendTransaction updates the pending block to include the given transaction. 261 // It panics if the transaction is invalid. 262 func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transaction) error { 263 b.mu.Lock() 264 defer b.mu.Unlock() 265 266 sender, err := types.Sender(types.HomesteadSigner{}, tx) 267 if err != nil { 268 panic(fmt.Errorf("invalid transaction: %v", err)) 269 } 270 nonce := b.pendingState.GetNonce(sender) 271 if tx.Nonce() != nonce { 272 panic(fmt.Errorf("invalid transaction nonce: got %d, want %d", tx.Nonce(), nonce)) 273 } 274 275 blocks, _ := core.GenerateChain(chainConfig, b.blockchain.CurrentBlock(), b.database, 1, func(number int, block *core.BlockGen) { 276 for _, tx := range b.pendingBlock.Transactions() { 277 block.AddTx(tx) 278 } 279 block.AddTx(tx) 280 }) 281 b.pendingBlock = blocks[0] 282 b.pendingState, _ = state.New(b.pendingBlock.Root(), b.database) 283 return nil 284 } 285 286 // callmsg implements core.Message to allow passing it as a transaction simulator. 287 type callmsg struct { 288 ethereum.CallMsg 289 } 290 291 func (m callmsg) From() common.Address { return m.CallMsg.From } 292 func (m callmsg) Nonce() uint64 { return 0 } 293 func (m callmsg) CheckNonce() bool { return false } 294 func (m callmsg) To() *common.Address { return m.CallMsg.To } 295 func (m callmsg) GasPrice() *big.Int { return m.CallMsg.GasPrice } 296 func (m callmsg) Gas() *big.Int { return m.CallMsg.Gas } 297 func (m callmsg) Value() *big.Int { return m.CallMsg.Value } 298 func (m callmsg) Data() []byte { return m.CallMsg.Data }