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