github.com/core-coin/go-core/v2@v2.1.9/tests/state_test_util.go (about)

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