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