github.com/linapex/ethereum-dpos-chinese@v0.0.0-20190316121959-b78b3a4a1ece/tests/state_test_util.go (about)

     1  
     2  //<developer>
     3  //    <name>linapex 曹一峰</name>
     4  //    <email>linapex@163.com</email>
     5  //    <wx>superexc</wx>
     6  //    <qqgroup>128148617</qqgroup>
     7  //    <url>https://jsq.ink</url>
     8  //    <role>pku engineer</role>
     9  //    <date>2019-03-16 12:09:50</date>
    10  //</624342686203121664>
    11  
    12  //
    13  //
    14  //
    15  //
    16  //
    17  //
    18  //
    19  //
    20  //
    21  //
    22  //
    23  //
    24  //
    25  //
    26  //
    27  
    28  package tests
    29  
    30  import (
    31  	"encoding/hex"
    32  	"encoding/json"
    33  	"fmt"
    34  	"math/big"
    35  	"strings"
    36  
    37  	"github.com/ethereum/go-ethereum/common"
    38  	"github.com/ethereum/go-ethereum/common/hexutil"
    39  	"github.com/ethereum/go-ethereum/common/math"
    40  	"github.com/ethereum/go-ethereum/core"
    41  	"github.com/ethereum/go-ethereum/core/state"
    42  	"github.com/ethereum/go-ethereum/core/types"
    43  	"github.com/ethereum/go-ethereum/core/vm"
    44  	"github.com/ethereum/go-ethereum/crypto"
    45  	"github.com/ethereum/go-ethereum/crypto/sha3"
    46  	"github.com/ethereum/go-ethereum/ethdb"
    47  	"github.com/ethereum/go-ethereum/params"
    48  	"github.com/ethereum/go-ethereum/rlp"
    49  )
    50  
    51  //
    52  //
    53  type StateTest struct {
    54  	json stJSON
    55  }
    56  
    57  //
    58  type StateSubtest struct {
    59  	Fork  string
    60  	Index int
    61  }
    62  
    63  func (t *StateTest) UnmarshalJSON(in []byte) error {
    64  	return json.Unmarshal(in, &t.json)
    65  }
    66  
    67  type stJSON struct {
    68  	Env  stEnv                    `json:"env"`
    69  	Pre  core.GenesisAlloc        `json:"pre"`
    70  	Tx   stTransaction            `json:"transaction"`
    71  	Out  hexutil.Bytes            `json:"out"`
    72  	Post map[string][]stPostState `json:"post"`
    73  }
    74  
    75  type stPostState struct {
    76  	Root    common.UnprefixedHash `json:"hash"`
    77  	Logs    common.UnprefixedHash `json:"logs"`
    78  	Indexes struct {
    79  		Data  int `json:"data"`
    80  		Gas   int `json:"gas"`
    81  		Value int `json:"value"`
    82  	}
    83  }
    84  
    85  //
    86  
    87  type stEnv struct {
    88  	Coinbase   common.Address `json:"currentCoinbase"   gencodec:"required"`
    89  	Difficulty *big.Int       `json:"currentDifficulty" gencodec:"required"`
    90  	GasLimit   uint64         `json:"currentGasLimit"   gencodec:"required"`
    91  	Number     uint64         `json:"currentNumber"     gencodec:"required"`
    92  	Timestamp  uint64         `json:"currentTimestamp"  gencodec:"required"`
    93  }
    94  
    95  type stEnvMarshaling struct {
    96  	Coinbase   common.UnprefixedAddress
    97  	Difficulty *math.HexOrDecimal256
    98  	GasLimit   math.HexOrDecimal64
    99  	Number     math.HexOrDecimal64
   100  	Timestamp  math.HexOrDecimal64
   101  }
   102  
   103  //
   104  
   105  type stTransaction struct {
   106  	GasPrice   *big.Int `json:"gasPrice"`
   107  	Nonce      uint64   `json:"nonce"`
   108  	To         string   `json:"to"`
   109  	Data       []string `json:"data"`
   110  	GasLimit   []uint64 `json:"gasLimit"`
   111  	Value      []string `json:"value"`
   112  	PrivateKey []byte   `json:"secretKey"`
   113  }
   114  
   115  type stTransactionMarshaling struct {
   116  	GasPrice   *math.HexOrDecimal256
   117  	Nonce      math.HexOrDecimal64
   118  	GasLimit   []math.HexOrDecimal64
   119  	PrivateKey hexutil.Bytes
   120  }
   121  
   122  //
   123  func (t *StateTest) Subtests() []StateSubtest {
   124  	var sub []StateSubtest
   125  	for fork, pss := range t.json.Post {
   126  		for i := range pss {
   127  			sub = append(sub, StateSubtest{fork, i})
   128  		}
   129  	}
   130  	return sub
   131  }
   132  
   133  //
   134  func (t *StateTest) Run(subtest StateSubtest, vmconfig vm.Config) (*state.StateDB, error) {
   135  	config, ok := Forks[subtest.Fork]
   136  	if !ok {
   137  		return nil, UnsupportedForkError{subtest.Fork}
   138  	}
   139  	block := t.genesis(config).ToBlock(nil)
   140  	statedb := MakePreState(ethdb.NewMemDatabase(), t.json.Pre)
   141  
   142  	post := t.json.Post[subtest.Fork][subtest.Index]
   143  	msg, err := t.json.Tx.toMessage(post)
   144  	if err != nil {
   145  		return nil, err
   146  	}
   147  	context := core.NewEVMContext(msg, block.Header(), nil, &t.json.Env.Coinbase)
   148  	context.GetHash = vmTestBlockHash
   149  	evm := vm.NewEVM(context, statedb, config, vmconfig)
   150  
   151  	gaspool := new(core.GasPool)
   152  	gaspool.AddGas(block.GasLimit())
   153  	snapshot := statedb.Snapshot()
   154  	if _, _, _, err := core.ApplyMessage(evm, msg, gaspool); err != nil {
   155  		statedb.RevertToSnapshot(snapshot)
   156  	}
   157  	if logs := rlpHash(statedb.Logs()); logs != common.Hash(post.Logs) {
   158  		return statedb, fmt.Errorf("post state logs hash mismatch: got %x, want %x", logs, post.Logs)
   159  	}
   160  	root, _ := statedb.Commit(config.IsEIP158(block.Number()))
   161  	if root != common.Hash(post.Root) {
   162  		return statedb, fmt.Errorf("post state root mismatch: got %x, want %x", root, post.Root)
   163  	}
   164  	return statedb, nil
   165  }
   166  
   167  func (t *StateTest) gasLimit(subtest StateSubtest) uint64 {
   168  	return t.json.Tx.GasLimit[t.json.Post[subtest.Fork][subtest.Index].Indexes.Gas]
   169  }
   170  
   171  func MakePreState(db ethdb.Database, accounts core.GenesisAlloc) *state.StateDB {
   172  	sdb := state.NewDatabase(db)
   173  	statedb, _ := state.New(common.Hash{}, sdb)
   174  	for addr, a := range accounts {
   175  		statedb.SetCode(addr, a.Code)
   176  		statedb.SetNonce(addr, a.Nonce)
   177  		statedb.SetBalance(addr, a.Balance)
   178  		for k, v := range a.Storage {
   179  			statedb.SetState(addr, k, v)
   180  		}
   181  	}
   182  //
   183  	root, _ := statedb.Commit(false)
   184  	statedb, _ = state.New(root, sdb)
   185  	return statedb
   186  }
   187  
   188  func (t *StateTest) genesis(config *params.ChainConfig) *core.Genesis {
   189  	return &core.Genesis{
   190  		Config:     config,
   191  		Coinbase:   t.json.Env.Coinbase,
   192  		Difficulty: t.json.Env.Difficulty,
   193  		GasLimit:   t.json.Env.GasLimit,
   194  		Number:     t.json.Env.Number,
   195  		Timestamp:  t.json.Env.Timestamp,
   196  		Alloc:      t.json.Pre,
   197  	}
   198  }
   199  
   200  func (tx *stTransaction) toMessage(ps stPostState) (core.Message, error) {
   201  //
   202  	var from common.Address
   203  	if len(tx.PrivateKey) > 0 {
   204  		key, err := crypto.ToECDSA(tx.PrivateKey)
   205  		if err != nil {
   206  			return nil, fmt.Errorf("invalid private key: %v", err)
   207  		}
   208  		from = crypto.PubkeyToAddress(key.PublicKey)
   209  	}
   210  //
   211  	var to *common.Address
   212  	if tx.To != "" {
   213  		to = new(common.Address)
   214  		if err := to.UnmarshalText([]byte(tx.To)); err != nil {
   215  			return nil, fmt.Errorf("invalid to address: %v", err)
   216  		}
   217  	}
   218  
   219  //
   220  	if ps.Indexes.Data > len(tx.Data) {
   221  		return nil, fmt.Errorf("tx data index %d out of bounds", ps.Indexes.Data)
   222  	}
   223  	if ps.Indexes.Value > len(tx.Value) {
   224  		return nil, fmt.Errorf("tx value index %d out of bounds", ps.Indexes.Value)
   225  	}
   226  	if ps.Indexes.Gas > len(tx.GasLimit) {
   227  		return nil, fmt.Errorf("tx gas limit index %d out of bounds", ps.Indexes.Gas)
   228  	}
   229  	dataHex := tx.Data[ps.Indexes.Data]
   230  	valueHex := tx.Value[ps.Indexes.Value]
   231  	gasLimit := tx.GasLimit[ps.Indexes.Gas]
   232  //
   233  	value := new(big.Int)
   234  	if valueHex != "0x" {
   235  		v, ok := math.ParseBig256(valueHex)
   236  		if !ok {
   237  			return nil, fmt.Errorf("invalid tx value %q", valueHex)
   238  		}
   239  		value = v
   240  	}
   241  	data, err := hex.DecodeString(strings.TrimPrefix(dataHex, "0x"))
   242  	if err != nil {
   243  		return nil, fmt.Errorf("invalid tx data %q", dataHex)
   244  	}
   245  
   246  	msg := types.NewMessage(from, to, tx.Nonce, value, gasLimit, tx.GasPrice, data, true)
   247  	return msg, nil
   248  }
   249  
   250  func rlpHash(x interface{}) (h common.Hash) {
   251  	hw := sha3.NewKeccak256()
   252  	rlp.Encode(hw, x)
   253  	hw.Sum(h[:0])
   254  	return h
   255  }
   256