state_test_util.go 12.2 KB
Newer Older
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 6 7 8
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
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 13 14
// GNU Lesser General Public License for more details.
//
// 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 18 19
package tests

import (
20 21
	"encoding/hex"
	"encoding/json"
22
	"fmt"
23
	"math/big"
24
	"strconv"
25
	"strings"
26 27

	"github.com/ethereum/go-ethereum/common"
28
	"github.com/ethereum/go-ethereum/common/hexutil"
29
	"github.com/ethereum/go-ethereum/common/math"
30
	"github.com/ethereum/go-ethereum/core"
31
	"github.com/ethereum/go-ethereum/core/rawdb"
32
	"github.com/ethereum/go-ethereum/core/state"
33
	"github.com/ethereum/go-ethereum/core/state/snapshot"
34
	"github.com/ethereum/go-ethereum/core/types"
35 36
	"github.com/ethereum/go-ethereum/core/vm"
	"github.com/ethereum/go-ethereum/crypto"
37
	"github.com/ethereum/go-ethereum/ethdb"
38
	"github.com/ethereum/go-ethereum/params"
39
	"github.com/ethereum/go-ethereum/rlp"
40
	"golang.org/x/crypto/sha3"
41 42
)

43 44 45 46 47
// StateTest checks transaction processing without block context.
// See https://github.com/ethereum/EIPs/issues/176 for the test format specification.
type StateTest struct {
	json stJSON
}
Taylor Gerring's avatar
Taylor Gerring committed
48

49 50 51 52
// StateSubtest selects a specific configuration of a General State Test.
type StateSubtest struct {
	Fork  string
	Index int
Taylor Gerring's avatar
Taylor Gerring committed
53 54
}

55 56 57
func (t *StateTest) UnmarshalJSON(in []byte) error {
	return json.Unmarshal(in, &t.json)
}
Taylor Gerring's avatar
Taylor Gerring committed
58

59 60 61 62 63 64 65 66 67
type stJSON struct {
	Env  stEnv                    `json:"env"`
	Pre  core.GenesisAlloc        `json:"pre"`
	Tx   stTransaction            `json:"transaction"`
	Out  hexutil.Bytes            `json:"out"`
	Post map[string][]stPostState `json:"post"`
}

type stPostState struct {
68 69 70 71 72
	Root            common.UnprefixedHash `json:"hash"`
	Logs            common.UnprefixedHash `json:"logs"`
	TxBytes         hexutil.Bytes         `json:"txbytes"`
	ExpectException string                `json:"expectException"`
	Indexes         struct {
73 74 75
		Data  int `json:"data"`
		Gas   int `json:"gas"`
		Value int `json:"value"`
Taylor Gerring's avatar
Taylor Gerring committed
76
	}
77
}
Taylor Gerring's avatar
Taylor Gerring committed
78

79
//go:generate gencodec -type stEnv -field-override stEnvMarshaling -out gen_stenv.go
Taylor Gerring's avatar
Taylor Gerring committed
80

81 82 83
type stEnv struct {
	Coinbase   common.Address `json:"currentCoinbase"   gencodec:"required"`
	Difficulty *big.Int       `json:"currentDifficulty" gencodec:"required"`
84
	GasLimit   uint64         `json:"currentGasLimit"   gencodec:"required"`
85 86
	Number     uint64         `json:"currentNumber"     gencodec:"required"`
	Timestamp  uint64         `json:"currentTimestamp"  gencodec:"required"`
87
	BaseFee    *big.Int       `json:"currentBaseFee"  gencodec:"optional"`
Taylor Gerring's avatar
Taylor Gerring committed
88 89
}

90 91 92
type stEnvMarshaling struct {
	Coinbase   common.UnprefixedAddress
	Difficulty *math.HexOrDecimal256
93
	GasLimit   math.HexOrDecimal64
94 95
	Number     math.HexOrDecimal64
	Timestamp  math.HexOrDecimal64
96
	BaseFee    *math.HexOrDecimal256
97 98 99 100 101
}

//go:generate gencodec -type stTransaction -field-override stTransactionMarshaling -out gen_sttransaction.go

type stTransaction struct {
102 103 104 105 106 107 108 109 110 111
	GasPrice             *big.Int            `json:"gasPrice"`
	MaxFeePerGas         *big.Int            `json:"maxFeePerGas"`
	MaxPriorityFeePerGas *big.Int            `json:"maxPriorityFeePerGas"`
	Nonce                uint64              `json:"nonce"`
	To                   string              `json:"to"`
	Data                 []string            `json:"data"`
	AccessLists          []*types.AccessList `json:"accessLists,omitempty"`
	GasLimit             []uint64            `json:"gasLimit"`
	Value                []string            `json:"value"`
	PrivateKey           []byte              `json:"secretKey"`
112 113 114
}

type stTransactionMarshaling struct {
115 116 117 118 119 120
	GasPrice             *math.HexOrDecimal256
	MaxFeePerGas         *math.HexOrDecimal256
	MaxPriorityFeePerGas *math.HexOrDecimal256
	Nonce                math.HexOrDecimal64
	GasLimit             []math.HexOrDecimal64
	PrivateKey           hexutil.Bytes
121 122
}

123
// GetChainConfig takes a fork definition and returns a chain config.
124 125 126
// The fork definition can be
// - a plain forkname, e.g. `Byzantium`,
// - a fork basename, and a list of EIPs to enable; e.g. `Byzantium+1884+1283`.
127
func GetChainConfig(forkString string) (baseConfig *params.ChainConfig, eips []int, err error) {
128 129 130 131 132 133 134 135 136 137 138 139
	var (
		splitForks            = strings.Split(forkString, "+")
		ok                    bool
		baseName, eipsStrings = splitForks[0], splitForks[1:]
	)
	if baseConfig, ok = Forks[baseName]; !ok {
		return nil, nil, UnsupportedForkError{baseName}
	}
	for _, eip := range eipsStrings {
		if eipNum, err := strconv.Atoi(eip); err != nil {
			return nil, nil, fmt.Errorf("syntax error, invalid eip number %v", eipNum)
		} else {
140 141 142
			if !vm.ValidEip(eipNum) {
				return nil, nil, fmt.Errorf("syntax error, invalid eip number %v", eipNum)
			}
143 144 145 146 147 148
			eips = append(eips, eipNum)
		}
	}
	return baseConfig, eips, nil
}

149 150 151 152
// Subtests returns all valid subtests of the test.
func (t *StateTest) Subtests() []StateSubtest {
	var sub []StateSubtest
	for fork, pss := range t.json.Post {
153
		for i := range pss {
154 155
			sub = append(sub, StateSubtest{fork, i})
		}
156
	}
157 158 159
	return sub
}

160
// Run executes a specific subtest and verifies the post-state and logs
161 162
func (t *StateTest) Run(subtest StateSubtest, vmconfig vm.Config, snapshotter bool) (*snapshot.Tree, *state.StateDB, error) {
	snaps, statedb, root, err := t.RunNoVerify(subtest, vmconfig, snapshotter)
163
	if err != nil {
164
		return snaps, statedb, err
165 166 167 168 169
	}
	post := t.json.Post[subtest.Fork][subtest.Index]
	// N.B: We need to do this in a two-step process, because the first Commit takes care
	// of suicides, and we need to touch the coinbase _after_ it has potentially suicided.
	if root != common.Hash(post.Root) {
170
		return snaps, statedb, fmt.Errorf("post state root mismatch: got %x, want %x", root, post.Root)
171 172
	}
	if logs := rlpHash(statedb.Logs()); logs != common.Hash(post.Logs) {
173
		return snaps, statedb, fmt.Errorf("post state logs hash mismatch: got %x, want %x", logs, post.Logs)
174
	}
175
	return snaps, statedb, nil
176 177 178
}

// RunNoVerify runs a specific subtest and returns the statedb and post-state root
179
func (t *StateTest) RunNoVerify(subtest StateSubtest, vmconfig vm.Config, snapshotter bool) (*snapshot.Tree, *state.StateDB, common.Hash, error) {
180
	config, eips, err := GetChainConfig(subtest.Fork)
181
	if err != nil {
182
		return nil, nil, common.Hash{}, UnsupportedForkError{subtest.Fork}
183
	}
184
	vmconfig.ExtraEips = eips
185
	block := t.genesis(config).ToBlock(nil)
186
	snaps, statedb := MakePreState(rawdb.NewMemoryDatabase(), t.json.Pre, snapshotter)
187

188 189 190 191 192 193 194 195 196
	var baseFee *big.Int
	if config.IsLondon(new(big.Int)) {
		baseFee = t.json.Env.BaseFee
		if baseFee == nil {
			// Retesteth uses `0x10` for genesis baseFee. Therefore, it defaults to
			// parent - 2 : 0xa as the basefee for 'this' context.
			baseFee = big.NewInt(0x0a)
		}
	}
197
	post := t.json.Post[subtest.Fork][subtest.Index]
198
	msg, err := t.json.Tx.toMessage(post, baseFee)
199
	if err != nil {
200
		return nil, nil, common.Hash{}, err
201
	}
202

203 204 205 206 207 208 209 210 211 212 213 214 215
	// Try to recover tx with current signer
	if len(post.TxBytes) != 0 {
		var ttx types.Transaction
		err := ttx.UnmarshalBinary(post.TxBytes)
		if err != nil {
			return nil, nil, common.Hash{}, err
		}

		if _, err := types.Sender(types.LatestSigner(config), &ttx); err != nil {
			return nil, nil, common.Hash{}, err
		}
	}

216
	// Prepare the EVM.
217 218
	txContext := core.NewEVMTxContext(msg)
	context := core.NewEVMBlockContext(block.Header(), nil, &t.json.Env.Coinbase)
219
	context.GetHash = vmTestBlockHash
220
	context.BaseFee = baseFee
221
	evm := vm.NewEVM(context, txContext, statedb, config, vmconfig)
222

223 224
	// Execute the message.
	snapshot := statedb.Snapshot()
225 226
	gaspool := new(core.GasPool)
	gaspool.AddGas(block.GasLimit())
227
	if _, err := core.ApplyMessage(evm, msg, gaspool); err != nil {
228 229
		statedb.RevertToSnapshot(snapshot)
	}
230

231 232 233 234 235 236 237 238 239 240
	// Commit block
	statedb.Commit(config.IsEIP158(block.Number()))
	// Add 0-value mining reward. This only makes a difference in the cases
	// where
	// - the coinbase suicided, or
	// - there are only 'bad' transactions, which aren't executed. In those cases,
	//   the coinbase gets no txfee, so isn't created, and thus needs to be touched
	statedb.AddBalance(block.Coinbase(), new(big.Int))
	// And _now_ get the state root
	root := statedb.IntermediateRoot(config.IsEIP158(block.Number()))
241
	return snaps, statedb, root, nil
242 243
}

244 245 246
func (t *StateTest) gasLimit(subtest StateSubtest) uint64 {
	return t.json.Tx.GasLimit[t.json.Post[subtest.Fork][subtest.Index].Indexes.Gas]
}
247

248
func MakePreState(db ethdb.Database, accounts core.GenesisAlloc, snapshotter bool) (*snapshot.Tree, *state.StateDB) {
249
	sdb := state.NewDatabase(db)
250
	statedb, _ := state.New(common.Hash{}, sdb, nil)
251 252 253 254 255 256 257 258 259
	for addr, a := range accounts {
		statedb.SetCode(addr, a.Code)
		statedb.SetNonce(addr, a.Nonce)
		statedb.SetBalance(addr, a.Balance)
		for k, v := range a.Storage {
			statedb.SetState(addr, k, v)
		}
	}
	// Commit and re-open to start with a clean state.
260
	root, _ := statedb.Commit(false)
261 262 263

	var snaps *snapshot.Tree
	if snapshotter {
264
		snaps, _ = snapshot.New(db, sdb.TrieDB(), 1, root, false, true, false)
265 266
	}
	statedb, _ = state.New(root, sdb, snaps)
267
	return snaps, statedb
268 269
}

270 271 272 273 274
func (t *StateTest) genesis(config *params.ChainConfig) *core.Genesis {
	return &core.Genesis{
		Config:     config,
		Coinbase:   t.json.Env.Coinbase,
		Difficulty: t.json.Env.Difficulty,
275
		GasLimit:   t.json.Env.GasLimit,
276 277 278
		Number:     t.json.Env.Number,
		Timestamp:  t.json.Env.Timestamp,
		Alloc:      t.json.Pre,
Taylor Gerring's avatar
Taylor Gerring committed
279
	}
280
}
281

282
func (tx *stTransaction) toMessage(ps stPostState, baseFee *big.Int) (core.Message, error) {
283 284 285 286 287 288
	// Derive sender from private key if present.
	var from common.Address
	if len(tx.PrivateKey) > 0 {
		key, err := crypto.ToECDSA(tx.PrivateKey)
		if err != nil {
			return nil, fmt.Errorf("invalid private key: %v", err)
289
		}
290 291 292 293 294 295 296 297
		from = crypto.PubkeyToAddress(key.PublicKey)
	}
	// Parse recipient if present.
	var to *common.Address
	if tx.To != "" {
		to = new(common.Address)
		if err := to.UnmarshalText([]byte(tx.To)); err != nil {
			return nil, fmt.Errorf("invalid to address: %v", err)
298
		}
299
	}
300

301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
	// Get values specific to this post state.
	if ps.Indexes.Data > len(tx.Data) {
		return nil, fmt.Errorf("tx data index %d out of bounds", ps.Indexes.Data)
	}
	if ps.Indexes.Value > len(tx.Value) {
		return nil, fmt.Errorf("tx value index %d out of bounds", ps.Indexes.Value)
	}
	if ps.Indexes.Gas > len(tx.GasLimit) {
		return nil, fmt.Errorf("tx gas limit index %d out of bounds", ps.Indexes.Gas)
	}
	dataHex := tx.Data[ps.Indexes.Data]
	valueHex := tx.Value[ps.Indexes.Value]
	gasLimit := tx.GasLimit[ps.Indexes.Gas]
	// Value, Data hex encoding is messy: https://github.com/ethereum/tests/issues/203
	value := new(big.Int)
	if valueHex != "0x" {
		v, ok := math.ParseBig256(valueHex)
		if !ok {
			return nil, fmt.Errorf("invalid tx value %q", valueHex)
		}
		value = v
	}
	data, err := hex.DecodeString(strings.TrimPrefix(dataHex, "0x"))
	if err != nil {
		return nil, fmt.Errorf("invalid tx data %q", dataHex)
Taylor Gerring's avatar
Taylor Gerring committed
326
	}
327 328 329 330
	var accessList types.AccessList
	if tx.AccessLists != nil && tx.AccessLists[ps.Indexes.Data] != nil {
		accessList = *tx.AccessLists[ps.Indexes.Data]
	}
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
	// If baseFee provided, set gasPrice to effectiveGasPrice.
	gasPrice := tx.GasPrice
	if baseFee != nil {
		if tx.MaxFeePerGas == nil {
			tx.MaxFeePerGas = gasPrice
		}
		if tx.MaxFeePerGas == nil {
			tx.MaxFeePerGas = new(big.Int)
		}
		if tx.MaxPriorityFeePerGas == nil {
			tx.MaxPriorityFeePerGas = tx.MaxFeePerGas
		}
		gasPrice = math.BigMin(new(big.Int).Add(tx.MaxPriorityFeePerGas, baseFee),
			tx.MaxFeePerGas)
	}
346 347 348
	if gasPrice == nil {
		return nil, fmt.Errorf("no gas price provided")
	}
349 350

	msg := types.NewMessage(from, to, tx.Nonce, value, gasLimit, gasPrice,
351
		tx.MaxFeePerGas, tx.MaxPriorityFeePerGas, data, accessList, false)
352
	return msg, nil
Taylor Gerring's avatar
Taylor Gerring committed
353
}
354

355
func rlpHash(x interface{}) (h common.Hash) {
356
	hw := sha3.NewLegacyKeccak256()
357 358 359
	rlp.Encode(hw, x)
	hw.Sum(h[:0])
	return h
360
}
361 362 363 364

func vmTestBlockHash(n uint64) common.Hash {
	return common.BytesToHash(crypto.Keccak256([]byte(big.NewInt(int64(n)).String())))
}