github.com/murrekatt/go-ethereum@v1.5.8-0.20170123175102-fc52f2c007fb/core/evm.go (about) 1 // Copyright 2014 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 core 18 19 import ( 20 "math/big" 21 22 "github.com/ethereum/go-ethereum/common" 23 "github.com/ethereum/go-ethereum/core/types" 24 "github.com/ethereum/go-ethereum/core/vm" 25 ) 26 27 // BlockFetcher retrieves headers by their hash 28 type HeaderFetcher interface { 29 // GetHeader returns the hash corresponding to their hash 30 GetHeader(common.Hash, uint64) *types.Header 31 } 32 33 // NewEVMContext creates a new context for use in the EVM. 34 func NewEVMContext(msg Message, header *types.Header, chain HeaderFetcher) vm.Context { 35 return vm.Context{ 36 CanTransfer: CanTransfer, 37 Transfer: Transfer, 38 GetHash: GetHashFn(header, chain), 39 40 Origin: msg.From(), 41 Coinbase: header.Coinbase, 42 BlockNumber: new(big.Int).Set(header.Number), 43 Time: new(big.Int).Set(header.Time), 44 Difficulty: new(big.Int).Set(header.Difficulty), 45 GasLimit: new(big.Int).Set(header.GasLimit), 46 GasPrice: new(big.Int).Set(msg.GasPrice()), 47 } 48 } 49 50 // GetHashFn returns a GetHashFunc which retrieves header hashes by number 51 func GetHashFn(ref *types.Header, chain HeaderFetcher) func(n uint64) common.Hash { 52 return func(n uint64) common.Hash { 53 for header := chain.GetHeader(ref.ParentHash, ref.Number.Uint64()-1); header != nil; header = chain.GetHeader(header.ParentHash, header.Number.Uint64()-1) { 54 if header.Number.Uint64() == n { 55 return header.Hash() 56 } 57 } 58 59 return common.Hash{} 60 } 61 } 62 63 // CanTransfer checks wether there are enough funds in the address' account to make a transfer. 64 // This does not take the necessary gas in to account to make the transfer valid. 65 func CanTransfer(db vm.StateDB, addr common.Address, amount *big.Int) bool { 66 return db.GetBalance(addr).Cmp(amount) >= 0 67 } 68 69 // Transfer subtracts amount from sender and adds amount to recipient using the given Db 70 func Transfer(db vm.StateDB, sender, recipient common.Address, amount *big.Int) { 71 db.SubBalance(sender, amount) 72 db.AddBalance(recipient, amount) 73 }