github.com/platonnetwork/platon-go@v0.7.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  	"strings"
    25  
    26  	"github.com/PlatONnetwork/PlatON-Go/core/snapshotdb"
    27  
    28  	"github.com/PlatONnetwork/PlatON-Go/common"
    29  	"github.com/PlatONnetwork/PlatON-Go/common/hexutil"
    30  	"github.com/PlatONnetwork/PlatON-Go/common/math"
    31  	"github.com/PlatONnetwork/PlatON-Go/core"
    32  	"github.com/PlatONnetwork/PlatON-Go/core/state"
    33  	"github.com/PlatONnetwork/PlatON-Go/core/types"
    34  	"github.com/PlatONnetwork/PlatON-Go/core/vm"
    35  	"github.com/PlatONnetwork/PlatON-Go/crypto"
    36  	"github.com/PlatONnetwork/PlatON-Go/crypto/sha3"
    37  	"github.com/PlatONnetwork/PlatON-Go/ethdb"
    38  	"github.com/PlatONnetwork/PlatON-Go/params"
    39  	"github.com/PlatONnetwork/PlatON-Go/rlp"
    40  )
    41  
    42  // StateTest checks transaction processing without block context.
    43  // See https://github.com/ethereum/EIPs/issues/176 for the test format specification.
    44  type StateTest struct {
    45  	json stJSON
    46  }
    47  
    48  // StateSubtest selects a specific configuration of a General State Test.
    49  type StateSubtest struct {
    50  	Fork  string
    51  	Index int
    52  }
    53  
    54  func (t *StateTest) UnmarshalJSON(in []byte) error {
    55  	return json.Unmarshal(in, &t.json)
    56  }
    57  
    58  type stJSON struct {
    59  	Env  stEnv                    `json:"env"`
    60  	Pre  core.GenesisAlloc        `json:"pre"`
    61  	Tx   stTransaction            `json:"transaction"`
    62  	Out  hexutil.Bytes            `json:"out"`
    63  	Post map[string][]stPostState `json:"post"`
    64  }
    65  
    66  type stPostState struct {
    67  	Root    common.UnprefixedHash `json:"hash"`
    68  	Logs    common.UnprefixedHash `json:"logs"`
    69  	Indexes struct {
    70  		Data  int `json:"data"`
    71  		Gas   int `json:"gas"`
    72  		Value int `json:"value"`
    73  	}
    74  }
    75  
    76  //go:generate gencodec -type stEnv -field-override stEnvMarshaling -out gen_stenv.go
    77  
    78  type stEnv struct {
    79  	Coinbase   common.Address `json:"currentCoinbase"   gencodec:"required"`
    80  	Difficulty *big.Int       `json:"currentDifficulty" gencodec:"required"`
    81  	GasLimit   uint64         `json:"currentGasLimit"   gencodec:"required"`
    82  	Number     uint64         `json:"currentNumber"     gencodec:"required"`
    83  	Timestamp  uint64         `json:"currentTimestamp"  gencodec:"required"`
    84  }
    85  
    86  type stEnvMarshaling struct {
    87  	Coinbase   common.UnprefixedAddress
    88  	Difficulty *math.HexOrDecimal256
    89  	GasLimit   math.HexOrDecimal64
    90  	Number     math.HexOrDecimal64
    91  	Timestamp  math.HexOrDecimal64
    92  }
    93  
    94  //go:generate gencodec -type stTransaction -field-override stTransactionMarshaling -out gen_sttransaction.go
    95  
    96  type stTransaction struct {
    97  	GasPrice   *big.Int `json:"gasPrice"`
    98  	Nonce      uint64   `json:"nonce"`
    99  	To         string   `json:"to"`
   100  	Data       []string `json:"data"`
   101  	GasLimit   []uint64 `json:"gasLimit"`
   102  	Value      []string `json:"value"`
   103  	PrivateKey []byte   `json:"secretKey"`
   104  }
   105  
   106  type stTransactionMarshaling struct {
   107  	GasPrice   *math.HexOrDecimal256
   108  	Nonce      math.HexOrDecimal64
   109  	GasLimit   []math.HexOrDecimal64
   110  	PrivateKey hexutil.Bytes
   111  }
   112  
   113  // Subtests returns all valid subtests of the test.
   114  func (t *StateTest) Subtests() []StateSubtest {
   115  	var sub []StateSubtest
   116  	for fork, pss := range t.json.Post {
   117  		for i := range pss {
   118  			sub = append(sub, StateSubtest{fork, i})
   119  		}
   120  	}
   121  	return sub
   122  }
   123  
   124  // Run executes a specific subtest.
   125  func (t *StateTest) Run(subtest StateSubtest, vmconfig vm.Config) (*state.StateDB, error) {
   126  	config, ok := Forks[subtest.Fork]
   127  	if !ok {
   128  		return nil, UnsupportedForkError{subtest.Fork}
   129  	}
   130  	block := t.genesis(config).ToBlock(nil, snapshotdb.Instance())
   131  	statedb := MakePreState(ethdb.NewMemDatabase(), 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)
   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  	if logs := rlpHash(statedb.Logs()); logs != common.Hash(post.Logs) {
   149  		return statedb, fmt.Errorf("post state logs hash mismatch: got %x, want %x", logs, post.Logs)
   150  	}
   151  	// Commit block
   152  	statedb.Commit(true)
   153  	// Add 0-value mining reward. This only makes a difference in the cases
   154  	// where
   155  	// - the coinbase suicided, or
   156  	// - there are only 'bad' transactions, which aren't executed. In those cases,
   157  	//   the coinbase gets no txfee, so isn't created, and thus needs to be touched
   158  	statedb.AddBalance(block.Coinbase(), new(big.Int))
   159  	// And _now_ get the state root
   160  	root := statedb.IntermediateRoot(true)
   161  	// N.B: We need to do this in a two-step process, because the first Commit takes care
   162  	// of suicides, and we need to touch the coinbase _after_ it has potentially suicided.
   163  	if root != common.Hash(post.Root) {
   164  		return statedb, fmt.Errorf("post state root mismatch: got %x, want %x", root, post.Root)
   165  	}
   166  	return statedb, nil
   167  }
   168  
   169  func (t *StateTest) gasLimit(subtest StateSubtest) uint64 {
   170  	return t.json.Tx.GasLimit[t.json.Post[subtest.Fork][subtest.Index].Indexes.Gas]
   171  }
   172  
   173  func MakePreState(db ethdb.Database, accounts core.GenesisAlloc) *state.StateDB {
   174  	sdb := state.NewDatabase(db)
   175  	statedb, _ := state.New(common.Hash{}, sdb)
   176  	for addr, a := range accounts {
   177  		statedb.SetCode(addr, a.Code)
   178  		statedb.SetNonce(addr, a.Nonce)
   179  		statedb.SetBalance(addr, a.Balance)
   180  		for k, v := range a.Storage {
   181  			statedb.SetState(addr, k.Bytes(), v.Bytes())
   182  		}
   183  	}
   184  	// Commit and re-open to start with a clean state.
   185  	root, _ := statedb.Commit(false)
   186  	statedb, _ = state.New(root, sdb)
   187  	return statedb
   188  }
   189  
   190  func (t *StateTest) genesis(config *params.ChainConfig) *core.Genesis {
   191  	return &core.Genesis{
   192  		Config:    config,
   193  		Coinbase:  t.json.Env.Coinbase,
   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.NewKeccak256()
   253  	rlp.Encode(hw, x)
   254  	hw.Sum(h[:0])
   255  	return h
   256  }