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