state_test_util.go 7.07 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 20
package tests

import (
	"bytes"
21
	"encoding/hex"
22
	"fmt"
Taylor Gerring's avatar
Taylor Gerring committed
23
	"io"
24 25
	"math/big"
	"strconv"
26
	"testing"
27 28 29 30 31 32 33

	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/core"
	"github.com/ethereum/go-ethereum/core/state"
	"github.com/ethereum/go-ethereum/core/vm"
	"github.com/ethereum/go-ethereum/crypto"
	"github.com/ethereum/go-ethereum/ethdb"
Taylor Gerring's avatar
Taylor Gerring committed
34
	"github.com/ethereum/go-ethereum/logger/glog"
35 36
)

37
func RunStateTestWithReader(ruleSet RuleSet, r io.Reader, skipTests []string) error {
Taylor Gerring's avatar
Taylor Gerring committed
38 39 40
	tests := make(map[string]VmTest)
	if err := readJson(r, &tests); err != nil {
		return err
41
	}
42

43
	if err := runStateTests(ruleSet, tests, skipTests); err != nil {
Taylor Gerring's avatar
Taylor Gerring committed
44 45 46 47 48 49
		return err
	}

	return nil
}

50
func RunStateTest(ruleSet RuleSet, p string, skipTests []string) error {
51
	tests := make(map[string]VmTest)
Taylor Gerring's avatar
Taylor Gerring committed
52 53 54 55
	if err := readJsonFile(p, &tests); err != nil {
		return err
	}

56
	if err := runStateTests(ruleSet, tests, skipTests); err != nil {
Taylor Gerring's avatar
Taylor Gerring committed
57 58 59 60 61 62 63
		return err
	}

	return nil

}

64
func BenchStateTest(ruleSet RuleSet, p string, conf bconf, b *testing.B) error {
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
	tests := make(map[string]VmTest)
	if err := readJsonFile(p, &tests); err != nil {
		return err
	}
	test, ok := tests[conf.name]
	if !ok {
		return fmt.Errorf("test not found: %s", conf.name)
	}

	// XXX Yeah, yeah...
	env := make(map[string]string)
	env["currentCoinbase"] = test.Env.CurrentCoinbase
	env["currentDifficulty"] = test.Env.CurrentDifficulty
	env["currentGasLimit"] = test.Env.CurrentGasLimit
	env["currentNumber"] = test.Env.CurrentNumber
	env["previousHash"] = test.Env.PreviousHash
	if n, ok := test.Env.CurrentTimestamp.(float64); ok {
		env["currentTimestamp"] = strconv.Itoa(int(n))
	} else {
		env["currentTimestamp"] = test.Env.CurrentTimestamp.(string)
	}

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
89
		benchStateTest(ruleSet, test, env, b)
90 91 92 93 94
	}

	return nil
}

95
func benchStateTest(ruleSet RuleSet, test VmTest, env map[string]string, b *testing.B) {
96 97
	b.StopTimer()
	db, _ := ethdb.NewMemDatabase()
98
	statedb, _ := state.New(common.Hash{}, db)
99
	for addr, account := range test.Pre {
100
		obj := StateObjectFromAccount(db, addr, account, statedb.MarkStateObjectDirty)
101 102 103 104 105 106 107
		statedb.SetStateObject(obj)
		for a, v := range account.Storage {
			obj.SetState(common.HexToHash(a), common.HexToHash(v))
		}
	}
	b.StartTimer()

108
	RunState(ruleSet, statedb, env, test.Exec)
109 110
}

111
func runStateTests(ruleSet RuleSet, tests map[string]VmTest, skipTests []string) error {
112 113
	skipTest := make(map[string]bool, len(skipTests))
	for _, name := range skipTests {
Taylor Gerring's avatar
Taylor Gerring committed
114 115
		skipTest[name] = true
	}
116 117

	for name, test := range tests {
118
		if skipTest[name] /*|| name != "callcodecallcode_11" */ {
Taylor Gerring's avatar
Taylor Gerring committed
119
			glog.Infoln("Skipping state test", name)
120
			continue
121
		}
122

123
		//fmt.Println("StateTest:", name)
124
		if err := runStateTest(ruleSet, test); err != nil {
Taylor Gerring's avatar
Taylor Gerring committed
125
			return fmt.Errorf("%s: %s\n", name, err.Error())
126 127
		}

128
		//glog.Infoln("State test passed: ", name)
Taylor Gerring's avatar
Taylor Gerring committed
129 130 131
		//fmt.Println(string(statedb.Dump()))
	}
	return nil
132

Taylor Gerring's avatar
Taylor Gerring committed
133
}
134

135
func runStateTest(ruleSet RuleSet, test VmTest) error {
Taylor Gerring's avatar
Taylor Gerring committed
136
	db, _ := ethdb.NewMemDatabase()
137
	statedb, _ := state.New(common.Hash{}, db)
Taylor Gerring's avatar
Taylor Gerring committed
138
	for addr, account := range test.Pre {
139
		obj := StateObjectFromAccount(db, addr, account, statedb.MarkStateObjectDirty)
Taylor Gerring's avatar
Taylor Gerring committed
140 141 142
		statedb.SetStateObject(obj)
		for a, v := range account.Storage {
			obj.SetState(common.HexToHash(a), common.HexToHash(v))
143
		}
Taylor Gerring's avatar
Taylor Gerring committed
144
	}
145

Taylor Gerring's avatar
Taylor Gerring committed
146 147 148 149 150 151 152 153 154 155 156 157
	// XXX Yeah, yeah...
	env := make(map[string]string)
	env["currentCoinbase"] = test.Env.CurrentCoinbase
	env["currentDifficulty"] = test.Env.CurrentDifficulty
	env["currentGasLimit"] = test.Env.CurrentGasLimit
	env["currentNumber"] = test.Env.CurrentNumber
	env["previousHash"] = test.Env.PreviousHash
	if n, ok := test.Env.CurrentTimestamp.(float64); ok {
		env["currentTimestamp"] = strconv.Itoa(int(n))
	} else {
		env["currentTimestamp"] = test.Env.CurrentTimestamp.(string)
	}
158

Taylor Gerring's avatar
Taylor Gerring committed
159 160 161 162
	var (
		ret []byte
		// gas  *big.Int
		// err  error
163
		logs vm.Logs
Taylor Gerring's avatar
Taylor Gerring committed
164 165
	)

166
	ret, logs, _, _ = RunState(ruleSet, statedb, env, test.Transaction)
Taylor Gerring's avatar
Taylor Gerring committed
167

168
	// Compare expected and actual return
Taylor Gerring's avatar
Taylor Gerring committed
169 170 171 172
	rexp := common.FromHex(test.Out)
	if bytes.Compare(rexp, ret) != 0 {
		return fmt.Errorf("return failed. Expected %x, got %x\n", rexp, ret)
	}
173

Taylor Gerring's avatar
Taylor Gerring committed
174 175 176
	// check post state
	for addr, account := range test.Post {
		obj := statedb.GetStateObject(common.HexToAddress(addr))
177 178 179
		if obj == nil {
			return fmt.Errorf("did not find expected post-state account: %s", addr)
		}
180

Taylor Gerring's avatar
Taylor Gerring committed
181
		if obj.Balance().Cmp(common.Big(account.Balance)) != 0 {
182
			return fmt.Errorf("(%x) balance failed. Expected: %v have: %v\n", obj.Address().Bytes()[:4], common.String2Big(account.Balance), obj.Balance())
183 184
		}

Taylor Gerring's avatar
Taylor Gerring committed
185
		if obj.Nonce() != common.String2Big(account.Nonce).Uint64() {
186
			return fmt.Errorf("(%x) nonce failed. Expected: %v have: %v\n", obj.Address().Bytes()[:4], account.Nonce, obj.Nonce())
187 188
		}

Taylor Gerring's avatar
Taylor Gerring committed
189
		for addr, value := range account.Storage {
190
			v := statedb.GetState(obj.Address(), common.HexToHash(addr))
Taylor Gerring's avatar
Taylor Gerring committed
191
			vexp := common.HexToHash(value)
Taylor Gerring's avatar
Taylor Gerring committed
192

Taylor Gerring's avatar
Taylor Gerring committed
193
			if v != vexp {
194
				return fmt.Errorf("storage failed:\n%x: %s:\nexpected: %x\nhave:     %x\n(%v %v)\n", obj.Address().Bytes(), addr, vexp, v, vexp.Big(), v.Big())
Taylor Gerring's avatar
Taylor Gerring committed
195 196
			}
		}
Taylor Gerring's avatar
Taylor Gerring committed
197
	}
198

199 200
	root, _ := statedb.Commit()
	if common.HexToHash(test.PostStateRoot) != root {
201
		return fmt.Errorf("Post state root error. Expected: %s have: %x", test.PostStateRoot, root)
Taylor Gerring's avatar
Taylor Gerring committed
202
	}
Taylor Gerring's avatar
Taylor Gerring committed
203 204 205 206 207 208 209 210

	// check logs
	if len(test.Logs) > 0 {
		if err := checkLogs(test.Logs, logs); err != nil {
			return err
		}
	}

Taylor Gerring's avatar
Taylor Gerring committed
211
	return nil
212 213
}

214
func RunState(ruleSet RuleSet, statedb *state.StateDB, env, tx map[string]string) ([]byte, vm.Logs, *big.Int, error) {
215
	var (
216 217 218 219 220
		data  = common.FromHex(tx["data"])
		gas   = common.Big(tx["gasLimit"])
		price = common.Big(tx["gasPrice"])
		value = common.Big(tx["value"])
		nonce = common.Big(tx["nonce"]).Uint64()
221 222 223 224 225 226 227 228 229 230
	)

	var to *common.Address
	if len(tx["to"]) > 2 {
		t := common.HexToAddress(tx["to"])
		to = &t
	}
	// Set pre compiled contracts
	vm.Precompiled = vm.PrecompiledContracts()
	snapshot := statedb.Copy()
231
	gaspool := new(core.GasPool).AddGas(common.Big(env["currentGasLimit"]))
232

233 234 235
	key, _ := hex.DecodeString(tx["secretKey"])
	addr := crypto.PubkeyToAddress(crypto.ToECDSA(key).PublicKey)
	message := NewMessage(addr, to, data, value, gas, price, nonce)
236
	vmenv := NewEnvFromMap(ruleSet, statedb, env, tx)
237
	vmenv.origin = addr
238 239
	ret, _, err := core.ApplyMessage(vmenv, message, gaspool)
	if core.IsNonceErr(err) || core.IsInvalidTxErr(err) || core.IsGasLimitErr(err) {
240 241
		statedb.Set(snapshot)
	}
242
	statedb.Commit()
243 244 245

	return ret, vmenv.state.Logs(), vmenv.Gas, err
}