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