github.com/bcskill/bcschain/v3@v3.4.9-beta2/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  	"golang.org/x/crypto/sha3"
    27  
    28  	"github.com/bcskill/bcschain/v3/common"
    29  	"github.com/bcskill/bcschain/v3/common/hexutil"
    30  	"github.com/bcskill/bcschain/v3/common/math"
    31  	"github.com/bcskill/bcschain/v3/core"
    32  	"github.com/bcskill/bcschain/v3/core/state"
    33  	"github.com/bcskill/bcschain/v3/core/types"
    34  	"github.com/bcskill/bcschain/v3/core/vm"
    35  	"github.com/bcskill/bcschain/v3/crypto"
    36  	"github.com/bcskill/bcschain/v3/ethdb"
    37  	"github.com/bcskill/bcschain/v3/params"
    38  	"github.com/bcskill/bcschain/v3/rlp"
    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  	db := ethdb.NewMemDatabase()
   131  	statedb := MakePreState(db, t.json.Pre)
   132  
   133  	post := t.json.Post[subtest.Fork][subtest.Index]
   134  	msg, err := t.json.Tx.toMessage(post)
   135  	if err != nil {
   136  		return nil, err
   137  	}
   138  	context := core.NewEVMContext(msg, block.Header(), nil, &t.json.Env.Coinbase)
   139  	context.GetHash = vmTestBlockHash
   140  	evm := vm.NewEVM(context, statedb, config, vmconfig)
   141  
   142  	gaspool := new(core.GasPool)
   143  	gaspool.AddGas(block.GasLimit())
   144  	snapshot := statedb.Snapshot()
   145  	if _, _, _, err := core.ApplyMessage(evm, msg, gaspool); err != nil {
   146  		statedb.RevertToSnapshot(snapshot)
   147  	}
   148  	root, _ := statedb.Commit(config.IsEIP158(block.Number()))
   149  	if root != common.Hash(post.Root) {
   150  		return statedb, fmt.Errorf("post state root mismatch: got %x, want %x", root, post.Root)
   151  	}
   152  	if logs := rlpHash(statedb.Logs()); logs != common.Hash(post.Logs) {
   153  		return statedb, fmt.Errorf("post state logs hash mismatch: got %x, want %x", logs, post.Logs)
   154  	}
   155  	return statedb, nil
   156  }
   157  
   158  func (t *StateTest) gasLimit(subtest StateSubtest) uint64 {
   159  	return t.json.Tx.GasLimit[t.json.Post[subtest.Fork][subtest.Index].Indexes.Gas]
   160  }
   161  
   162  func MakePreState(db common.Database, accounts core.GenesisAlloc) *state.StateDB {
   163  	sdb := state.NewDatabase(db)
   164  	statedb, _ := state.New(common.Hash{}, sdb)
   165  	for addr, a := range accounts {
   166  		statedb.SetCode(addr, a.Code)
   167  		statedb.SetNonce(addr, a.Nonce)
   168  		statedb.SetBalance(addr, a.Balance)
   169  		for k, v := range a.Storage {
   170  			statedb.SetState(addr, k, v)
   171  		}
   172  	}
   173  	// Commit and re-open to start with a clean state.
   174  	root, _ := statedb.Commit(false)
   175  	statedb, _ = state.New(root, sdb)
   176  	return statedb
   177  }
   178  
   179  func (t *StateTest) genesis(config *params.ChainConfig) *core.Genesis {
   180  	return &core.Genesis{
   181  		Config:     config,
   182  		Coinbase:   t.json.Env.Coinbase,
   183  		Difficulty: t.json.Env.Difficulty,
   184  		GasLimit:   t.json.Env.GasLimit,
   185  		Number:     t.json.Env.Number,
   186  		Timestamp:  t.json.Env.Timestamp,
   187  		Alloc:      t.json.Pre,
   188  	}
   189  }
   190  
   191  func (tx *stTransaction) toMessage(ps stPostState) (core.Message, error) {
   192  	// Derive sender from private key if present.
   193  	var from common.Address
   194  	if len(tx.PrivateKey) > 0 {
   195  		key, err := crypto.ToECDSA(tx.PrivateKey)
   196  		if err != nil {
   197  			return nil, fmt.Errorf("invalid private key: %v", err)
   198  		}
   199  		from = crypto.PubkeyToAddress(key.PublicKey)
   200  	}
   201  	// Parse recipient if present.
   202  	var to *common.Address
   203  	if tx.To != "" {
   204  		to = new(common.Address)
   205  		if err := to.UnmarshalText([]byte(tx.To)); err != nil {
   206  			return nil, fmt.Errorf("invalid to address: %v", err)
   207  		}
   208  	}
   209  
   210  	// Get values specific to this post state.
   211  	if ps.Indexes.Data > len(tx.Data) {
   212  		return nil, fmt.Errorf("tx data index %d out of bounds", ps.Indexes.Data)
   213  	}
   214  	if ps.Indexes.Value > len(tx.Value) {
   215  		return nil, fmt.Errorf("tx value index %d out of bounds", ps.Indexes.Value)
   216  	}
   217  	if ps.Indexes.Gas > len(tx.GasLimit) {
   218  		return nil, fmt.Errorf("tx gas limit index %d out of bounds", ps.Indexes.Gas)
   219  	}
   220  	dataHex := tx.Data[ps.Indexes.Data]
   221  	valueHex := tx.Value[ps.Indexes.Value]
   222  	gasLimit := tx.GasLimit[ps.Indexes.Gas]
   223  	// Value, Data hex encoding is messy: https://github.com/ethereum/tests/issues/203
   224  	value := new(big.Int)
   225  	if valueHex != "0x" {
   226  		v, ok := math.ParseBig256(valueHex)
   227  		if !ok {
   228  			return nil, fmt.Errorf("invalid tx value %q", valueHex)
   229  		}
   230  		value = v
   231  	}
   232  	data, err := hex.DecodeString(strings.TrimPrefix(dataHex, "0x"))
   233  	if err != nil {
   234  		return nil, fmt.Errorf("invalid tx data %q", dataHex)
   235  	}
   236  
   237  	msg := types.NewMessage(from, to, tx.Nonce, value, gasLimit, tx.GasPrice, data, true)
   238  	return msg, nil
   239  }
   240  
   241  func rlpHash(x interface{}) (h common.Hash) {
   242  	hw := sha3.NewLegacyKeccak256()
   243  	rlp.Encode(hw, x)
   244  	hw.Sum(h[:0])
   245  	return h
   246  }