github.com/bloxroute-labs/bor@v0.1.4/tests/state_test_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  	"encoding/hex"
    21  	"encoding/json"
    22  	"fmt"
    23  	"math/big"
    24  	"strings"
    25  
    26  	"github.com/maticnetwork/bor/common"
    27  	"github.com/maticnetwork/bor/common/hexutil"
    28  	"github.com/maticnetwork/bor/common/math"
    29  	"github.com/maticnetwork/bor/core"
    30  	"github.com/maticnetwork/bor/core/rawdb"
    31  	"github.com/maticnetwork/bor/core/state"
    32  	"github.com/maticnetwork/bor/core/types"
    33  	"github.com/maticnetwork/bor/core/vm"
    34  	"github.com/maticnetwork/bor/crypto"
    35  	"github.com/maticnetwork/bor/ethdb"
    36  	"github.com/maticnetwork/bor/params"
    37  	"github.com/maticnetwork/bor/rlp"
    38  	"golang.org/x/crypto/sha3"
    39  )
    40  
    41  // StateTest checks transaction processing without block context.
    42  // See https://github.com/ethereum/EIPs/issues/176 for the test format specification.
    43  type StateTest struct {
    44  	json stJSON
    45  }
    46  
    47  // StateSubtest selects a specific configuration of a General State Test.
    48  type StateSubtest struct {
    49  	Fork  string
    50  	Index int
    51  }
    52  
    53  func (t *StateTest) UnmarshalJSON(in []byte) error {
    54  	return json.Unmarshal(in, &t.json)
    55  }
    56  
    57  type stJSON struct {
    58  	Env  stEnv                    `json:"env"`
    59  	Pre  core.GenesisAlloc        `json:"pre"`
    60  	Tx   stTransaction            `json:"transaction"`
    61  	Out  hexutil.Bytes            `json:"out"`
    62  	Post map[string][]stPostState `json:"post"`
    63  }
    64  
    65  type stPostState struct {
    66  	Root    common.UnprefixedHash `json:"hash"`
    67  	Logs    common.UnprefixedHash `json:"logs"`
    68  	Indexes struct {
    69  		Data  int `json:"data"`
    70  		Gas   int `json:"gas"`
    71  		Value int `json:"value"`
    72  	}
    73  }
    74  
    75  //go:generate gencodec -type stEnv -field-override stEnvMarshaling -out gen_stenv.go
    76  
    77  type stEnv struct {
    78  	Coinbase   common.Address `json:"currentCoinbase"   gencodec:"required"`
    79  	Difficulty *big.Int       `json:"currentDifficulty" gencodec:"required"`
    80  	GasLimit   uint64         `json:"currentGasLimit"   gencodec:"required"`
    81  	Number     uint64         `json:"currentNumber"     gencodec:"required"`
    82  	Timestamp  uint64         `json:"currentTimestamp"  gencodec:"required"`
    83  }
    84  
    85  type stEnvMarshaling struct {
    86  	Coinbase   common.UnprefixedAddress
    87  	Difficulty *math.HexOrDecimal256
    88  	GasLimit   math.HexOrDecimal64
    89  	Number     math.HexOrDecimal64
    90  	Timestamp  math.HexOrDecimal64
    91  }
    92  
    93  //go:generate gencodec -type stTransaction -field-override stTransactionMarshaling -out gen_sttransaction.go
    94  
    95  type stTransaction struct {
    96  	GasPrice   *big.Int `json:"gasPrice"`
    97  	Nonce      uint64   `json:"nonce"`
    98  	To         string   `json:"to"`
    99  	Data       []string `json:"data"`
   100  	GasLimit   []uint64 `json:"gasLimit"`
   101  	Value      []string `json:"value"`
   102  	PrivateKey []byte   `json:"secretKey"`
   103  }
   104  
   105  type stTransactionMarshaling struct {
   106  	GasPrice   *math.HexOrDecimal256
   107  	Nonce      math.HexOrDecimal64
   108  	GasLimit   []math.HexOrDecimal64
   109  	PrivateKey hexutil.Bytes
   110  }
   111  
   112  // Subtests returns all valid subtests of the test.
   113  func (t *StateTest) Subtests() []StateSubtest {
   114  	var sub []StateSubtest
   115  	for fork, pss := range t.json.Post {
   116  		for i := range pss {
   117  			sub = append(sub, StateSubtest{fork, i})
   118  		}
   119  	}
   120  	return sub
   121  }
   122  
   123  // Run executes a specific subtest.
   124  func (t *StateTest) Run(subtest StateSubtest, vmconfig vm.Config) (*state.StateDB, error) {
   125  	config, ok := Forks[subtest.Fork]
   126  	if !ok {
   127  		return nil, UnsupportedForkError{subtest.Fork}
   128  	}
   129  	block := t.genesis(config).ToBlock(nil)
   130  	statedb := MakePreState(rawdb.NewMemoryDatabase(), t.json.Pre)
   131  
   132  	post := t.json.Post[subtest.Fork][subtest.Index]
   133  	msg, err := t.json.Tx.toMessage(post)
   134  	if err != nil {
   135  		return nil, err
   136  	}
   137  	context := core.NewEVMContext(msg, block.Header(), nil, &t.json.Env.Coinbase)
   138  	context.GetHash = vmTestBlockHash
   139  	evm := vm.NewEVM(context, statedb, config, vmconfig)
   140  
   141  	gaspool := new(core.GasPool)
   142  	gaspool.AddGas(block.GasLimit())
   143  	snapshot := statedb.Snapshot()
   144  	if _, _, _, err := core.ApplyMessage(evm, msg, gaspool); err != nil {
   145  		statedb.RevertToSnapshot(snapshot)
   146  	}
   147  	// Commit block
   148  	statedb.Commit(config.IsEIP158(block.Number()))
   149  	// Add 0-value mining reward. This only makes a difference in the cases
   150  	// where
   151  	// - the coinbase suicided, or
   152  	// - there are only 'bad' transactions, which aren't executed. In those cases,
   153  	//   the coinbase gets no txfee, so isn't created, and thus needs to be touched
   154  	statedb.AddBalance(block.Coinbase(), new(big.Int))
   155  	// And _now_ get the state root
   156  	root := statedb.IntermediateRoot(config.IsEIP158(block.Number()))
   157  	// N.B: We need to do this in a two-step process, because the first Commit takes care
   158  	// of suicides, and we need to touch the coinbase _after_ it has potentially suicided.
   159  	if root != common.Hash(post.Root) {
   160  		return statedb, fmt.Errorf("post state root mismatch: got %x, want %x", root, post.Root)
   161  	}
   162  	if logs := rlpHash(statedb.Logs()); logs != common.Hash(post.Logs) {
   163  		return statedb, fmt.Errorf("post state logs hash mismatch: got %x, want %x", logs, post.Logs)
   164  	}
   165  	return statedb, nil
   166  }
   167  
   168  func (t *StateTest) gasLimit(subtest StateSubtest) uint64 {
   169  	return t.json.Tx.GasLimit[t.json.Post[subtest.Fork][subtest.Index].Indexes.Gas]
   170  }
   171  
   172  func MakePreState(db ethdb.Database, accounts core.GenesisAlloc) *state.StateDB {
   173  	sdb := state.NewDatabase(db)
   174  	statedb, _ := state.New(common.Hash{}, sdb)
   175  	for addr, a := range accounts {
   176  		statedb.SetCode(addr, a.Code)
   177  		statedb.SetNonce(addr, a.Nonce)
   178  		statedb.SetBalance(addr, a.Balance)
   179  		for k, v := range a.Storage {
   180  			statedb.SetState(addr, k, v)
   181  		}
   182  	}
   183  	// Commit and re-open to start with a clean state.
   184  	root, _ := statedb.Commit(false)
   185  	statedb, _ = state.New(root, sdb)
   186  	return statedb
   187  }
   188  
   189  func (t *StateTest) genesis(config *params.ChainConfig) *core.Genesis {
   190  	return &core.Genesis{
   191  		Config:     config,
   192  		Coinbase:   t.json.Env.Coinbase,
   193  		Difficulty: t.json.Env.Difficulty,
   194  		GasLimit:   t.json.Env.GasLimit,
   195  		Number:     t.json.Env.Number,
   196  		Timestamp:  t.json.Env.Timestamp,
   197  		Alloc:      t.json.Pre,
   198  	}
   199  }
   200  
   201  func (tx *stTransaction) toMessage(ps stPostState) (core.Message, error) {
   202  	// Derive sender from private key if present.
   203  	var from common.Address
   204  	if len(tx.PrivateKey) > 0 {
   205  		key, err := crypto.ToECDSA(tx.PrivateKey)
   206  		if err != nil {
   207  			return nil, fmt.Errorf("invalid private key: %v", err)
   208  		}
   209  		from = crypto.PubkeyToAddress(key.PublicKey)
   210  	}
   211  	// Parse recipient if present.
   212  	var to *common.Address
   213  	if tx.To != "" {
   214  		to = new(common.Address)
   215  		if err := to.UnmarshalText([]byte(tx.To)); err != nil {
   216  			return nil, fmt.Errorf("invalid to address: %v", err)
   217  		}
   218  	}
   219  
   220  	// Get values specific to this post state.
   221  	if ps.Indexes.Data > len(tx.Data) {
   222  		return nil, fmt.Errorf("tx data index %d out of bounds", ps.Indexes.Data)
   223  	}
   224  	if ps.Indexes.Value > len(tx.Value) {
   225  		return nil, fmt.Errorf("tx value index %d out of bounds", ps.Indexes.Value)
   226  	}
   227  	if ps.Indexes.Gas > len(tx.GasLimit) {
   228  		return nil, fmt.Errorf("tx gas limit index %d out of bounds", ps.Indexes.Gas)
   229  	}
   230  	dataHex := tx.Data[ps.Indexes.Data]
   231  	valueHex := tx.Value[ps.Indexes.Value]
   232  	gasLimit := tx.GasLimit[ps.Indexes.Gas]
   233  	// Value, Data hex encoding is messy: https://github.com/ethereum/tests/issues/203
   234  	value := new(big.Int)
   235  	if valueHex != "0x" {
   236  		v, ok := math.ParseBig256(valueHex)
   237  		if !ok {
   238  			return nil, fmt.Errorf("invalid tx value %q", valueHex)
   239  		}
   240  		value = v
   241  	}
   242  	data, err := hex.DecodeString(strings.TrimPrefix(dataHex, "0x"))
   243  	if err != nil {
   244  		return nil, fmt.Errorf("invalid tx data %q", dataHex)
   245  	}
   246  
   247  	msg := types.NewMessage(from, to, tx.Nonce, value, gasLimit, tx.GasPrice, data, true)
   248  	return msg, nil
   249  }
   250  
   251  func rlpHash(x interface{}) (h common.Hash) {
   252  	hw := sha3.NewLegacyKeccak256()
   253  	rlp.Encode(hw, x)
   254  	hw.Sum(h[:0])
   255  	return h
   256  }