github.com/devfans/go-ethereum@v1.5.10-0.20170326212234-7419d0c38291/tests/util.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 tests
    18  
    19  import (
    20  	"bytes"
    21  	"encoding/hex"
    22  	"fmt"
    23  	"math/big"
    24  	"os"
    25  
    26  	"github.com/ethereum/go-ethereum/common"
    27  	"github.com/ethereum/go-ethereum/common/math"
    28  	"github.com/ethereum/go-ethereum/core"
    29  	"github.com/ethereum/go-ethereum/core/state"
    30  	"github.com/ethereum/go-ethereum/core/types"
    31  	"github.com/ethereum/go-ethereum/core/vm"
    32  	"github.com/ethereum/go-ethereum/crypto"
    33  	"github.com/ethereum/go-ethereum/ethdb"
    34  	"github.com/ethereum/go-ethereum/log"
    35  	"github.com/ethereum/go-ethereum/params"
    36  )
    37  
    38  var (
    39  	ForceJit  bool
    40  	EnableJit bool
    41  )
    42  
    43  func init() {
    44  	log.Root().SetHandler(log.LvlFilterHandler(log.LvlCrit, log.StreamHandler(os.Stderr, log.TerminalFormat(false))))
    45  	if os.Getenv("JITVM") == "true" {
    46  		ForceJit = true
    47  		EnableJit = true
    48  	}
    49  }
    50  
    51  func checkLogs(tlog []Log, logs []*types.Log) error {
    52  
    53  	if len(tlog) != len(logs) {
    54  		return fmt.Errorf("log length mismatch. Expected %d, got %d", len(tlog), len(logs))
    55  	} else {
    56  		for i, log := range tlog {
    57  			if common.HexToAddress(log.AddressF) != logs[i].Address {
    58  				return fmt.Errorf("log address expected %v got %x", log.AddressF, logs[i].Address)
    59  			}
    60  
    61  			if !bytes.Equal(logs[i].Data, common.FromHex(log.DataF)) {
    62  				return fmt.Errorf("log data expected %v got %x", log.DataF, logs[i].Data)
    63  			}
    64  
    65  			if len(log.TopicsF) != len(logs[i].Topics) {
    66  				return fmt.Errorf("log topics length expected %d got %d", len(log.TopicsF), logs[i].Topics)
    67  			} else {
    68  				for j, topic := range log.TopicsF {
    69  					if common.HexToHash(topic) != logs[i].Topics[j] {
    70  						return fmt.Errorf("log topic[%d] expected %v got %x", j, topic, logs[i].Topics[j])
    71  					}
    72  				}
    73  			}
    74  			genBloom := math.PaddedBigBytes(types.LogsBloom([]*types.Log{logs[i]}), 256)
    75  
    76  			if !bytes.Equal(genBloom, common.Hex2Bytes(log.BloomF)) {
    77  				return fmt.Errorf("bloom mismatch")
    78  			}
    79  		}
    80  	}
    81  	return nil
    82  }
    83  
    84  type Account struct {
    85  	Balance string
    86  	Code    string
    87  	Nonce   string
    88  	Storage map[string]string
    89  }
    90  
    91  type Log struct {
    92  	AddressF string   `json:"address"`
    93  	DataF    string   `json:"data"`
    94  	TopicsF  []string `json:"topics"`
    95  	BloomF   string   `json:"bloom"`
    96  }
    97  
    98  func (self Log) Address() []byte      { return common.Hex2Bytes(self.AddressF) }
    99  func (self Log) Data() []byte         { return common.Hex2Bytes(self.DataF) }
   100  func (self Log) RlpData() interface{} { return nil }
   101  func (self Log) Topics() [][]byte {
   102  	t := make([][]byte, len(self.TopicsF))
   103  	for i, topic := range self.TopicsF {
   104  		t[i] = common.Hex2Bytes(topic)
   105  	}
   106  	return t
   107  }
   108  
   109  func makePreState(db ethdb.Database, accounts map[string]Account) *state.StateDB {
   110  	statedb, _ := state.New(common.Hash{}, db)
   111  	for addr, account := range accounts {
   112  		insertAccount(statedb, addr, account)
   113  	}
   114  	return statedb
   115  }
   116  
   117  func insertAccount(state *state.StateDB, saddr string, account Account) {
   118  	if common.IsHex(account.Code) {
   119  		account.Code = account.Code[2:]
   120  	}
   121  	addr := common.HexToAddress(saddr)
   122  	state.SetCode(addr, common.Hex2Bytes(account.Code))
   123  	state.SetNonce(addr, math.MustParseUint64(account.Nonce))
   124  	state.SetBalance(addr, math.MustParseBig256(account.Balance))
   125  	for a, v := range account.Storage {
   126  		state.SetState(addr, common.HexToHash(a), common.HexToHash(v))
   127  	}
   128  }
   129  
   130  type VmEnv struct {
   131  	CurrentCoinbase   string
   132  	CurrentDifficulty string
   133  	CurrentGasLimit   string
   134  	CurrentNumber     string
   135  	CurrentTimestamp  interface{}
   136  	PreviousHash      string
   137  }
   138  
   139  type VmTest struct {
   140  	Callcreates interface{}
   141  	//Env         map[string]string
   142  	Env           VmEnv
   143  	Exec          map[string]string
   144  	Transaction   map[string]string
   145  	Logs          []Log
   146  	Gas           string
   147  	Out           string
   148  	Post          map[string]Account
   149  	Pre           map[string]Account
   150  	PostStateRoot string
   151  }
   152  
   153  func NewEVMEnvironment(vmTest bool, chainConfig *params.ChainConfig, statedb *state.StateDB, envValues map[string]string, tx map[string]string) (*vm.EVM, core.Message) {
   154  	var (
   155  		data  = common.FromHex(tx["data"])
   156  		gas   = math.MustParseBig256(tx["gasLimit"])
   157  		price = math.MustParseBig256(tx["gasPrice"])
   158  		value = math.MustParseBig256(tx["value"])
   159  		nonce = math.MustParseUint64(tx["nonce"])
   160  	)
   161  
   162  	origin := common.HexToAddress(tx["caller"])
   163  	if len(tx["secretKey"]) > 0 {
   164  		key, _ := hex.DecodeString(tx["secretKey"])
   165  		origin = crypto.PubkeyToAddress(crypto.ToECDSA(key).PublicKey)
   166  	}
   167  
   168  	var to *common.Address
   169  	if len(tx["to"]) > 2 {
   170  		t := common.HexToAddress(tx["to"])
   171  		to = &t
   172  	}
   173  
   174  	msg := types.NewMessage(origin, to, nonce, value, gas, price, data, true)
   175  
   176  	initialCall := true
   177  	canTransfer := func(db vm.StateDB, address common.Address, amount *big.Int) bool {
   178  		if vmTest {
   179  			if initialCall {
   180  				initialCall = false
   181  				return true
   182  			}
   183  		}
   184  		return core.CanTransfer(db, address, amount)
   185  	}
   186  	transfer := func(db vm.StateDB, sender, recipient common.Address, amount *big.Int) {
   187  		if vmTest {
   188  			return
   189  		}
   190  		core.Transfer(db, sender, recipient, amount)
   191  	}
   192  
   193  	context := vm.Context{
   194  		CanTransfer: canTransfer,
   195  		Transfer:    transfer,
   196  		GetHash: func(n uint64) common.Hash {
   197  			return common.BytesToHash(crypto.Keccak256([]byte(big.NewInt(int64(n)).String())))
   198  		},
   199  
   200  		Origin:      origin,
   201  		Coinbase:    common.HexToAddress(envValues["currentCoinbase"]),
   202  		BlockNumber: math.MustParseBig256(envValues["currentNumber"]),
   203  		Time:        math.MustParseBig256(envValues["currentTimestamp"]),
   204  		GasLimit:    math.MustParseBig256(envValues["currentGasLimit"]),
   205  		Difficulty:  math.MustParseBig256(envValues["currentDifficulty"]),
   206  		GasPrice:    price,
   207  	}
   208  	if context.GasPrice == nil {
   209  		context.GasPrice = new(big.Int)
   210  	}
   211  	return vm.NewEVM(context, statedb, chainConfig, vm.Config{NoRecursion: vmTest}), msg
   212  }