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