github.com/luckypickle/go-ethereum-vet@v1.14.2/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/luckypickle/go-ethereum-vet/common" 27 "github.com/luckypickle/go-ethereum-vet/common/hexutil" 28 "github.com/luckypickle/go-ethereum-vet/common/math" 29 "github.com/luckypickle/go-ethereum-vet/core" 30 "github.com/luckypickle/go-ethereum-vet/core/state" 31 "github.com/luckypickle/go-ethereum-vet/core/types" 32 "github.com/luckypickle/go-ethereum-vet/core/vm" 33 "github.com/luckypickle/go-ethereum-vet/crypto" 34 "github.com/luckypickle/go-ethereum-vet/crypto/sha3" 35 "github.com/luckypickle/go-ethereum-vet/ethdb" 36 "github.com/luckypickle/go-ethereum-vet/params" 37 "github.com/luckypickle/go-ethereum-vet/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 statedb := MakePreState(ethdb.NewMemDatabase(), t.json.Pre) 130 131 post := t.json.Post[subtest.Fork][subtest.Index] 132 msg, err := t.json.Tx.toMessage(post) 133 if err != nil { 134 return nil, err 135 } 136 context := core.NewEVMContext(msg, block.Header(), nil, &t.json.Env.Coinbase) 137 context.GetHash = vmTestBlockHash 138 evm := vm.NewEVM(context, statedb, config, vmconfig) 139 140 gaspool := new(core.GasPool) 141 gaspool.AddGas(block.GasLimit()) 142 snapshot := statedb.Snapshot() 143 if _, _, _, err := core.ApplyMessage(evm, msg, gaspool); err != nil { 144 statedb.RevertToSnapshot(snapshot) 145 } 146 if logs := rlpHash(statedb.Logs()); logs != common.Hash(post.Logs) { 147 return statedb, fmt.Errorf("post state logs hash mismatch: got %x, want %x", logs, post.Logs) 148 } 149 root, _ := statedb.Commit(config.IsEIP158(block.Number())) 150 if root != common.Hash(post.Root) { 151 return statedb, fmt.Errorf("post state root mismatch: got %x, want %x", root, post.Root) 152 } 153 return statedb, nil 154 } 155 156 func (t *StateTest) gasLimit(subtest StateSubtest) uint64 { 157 return t.json.Tx.GasLimit[t.json.Post[subtest.Fork][subtest.Index].Indexes.Gas] 158 } 159 160 func MakePreState(db ethdb.Database, accounts core.GenesisAlloc) *state.StateDB { 161 sdb := state.NewDatabase(db) 162 statedb, _ := state.New(common.Hash{}, sdb) 163 for addr, a := range accounts { 164 statedb.SetCode(addr, a.Code) 165 statedb.SetNonce(addr, a.Nonce) 166 statedb.SetBalance(addr, a.Balance) 167 for k, v := range a.Storage { 168 statedb.SetState(addr, k, v) 169 } 170 } 171 // Commit and re-open to start with a clean state. 172 root, _ := statedb.Commit(false) 173 statedb, _ = state.New(root, sdb) 174 return statedb 175 } 176 177 func (t *StateTest) genesis(config *params.ChainConfig) *core.Genesis { 178 return &core.Genesis{ 179 Config: config, 180 Coinbase: t.json.Env.Coinbase, 181 Difficulty: t.json.Env.Difficulty, 182 GasLimit: t.json.Env.GasLimit, 183 Number: t.json.Env.Number, 184 Timestamp: t.json.Env.Timestamp, 185 Alloc: t.json.Pre, 186 } 187 } 188 189 func (tx *stTransaction) toMessage(ps stPostState) (core.Message, error) { 190 // Derive sender from private key if present. 191 var from common.Address 192 if len(tx.PrivateKey) > 0 { 193 key, err := crypto.ToECDSA(tx.PrivateKey) 194 if err != nil { 195 return nil, fmt.Errorf("invalid private key: %v", err) 196 } 197 from = crypto.PubkeyToAddress(key.PublicKey) 198 } 199 // Parse recipient if present. 200 var to *common.Address 201 if tx.To != "" { 202 to = new(common.Address) 203 if err := to.UnmarshalText([]byte(tx.To)); err != nil { 204 return nil, fmt.Errorf("invalid to address: %v", err) 205 } 206 } 207 208 // Get values specific to this post state. 209 if ps.Indexes.Data > len(tx.Data) { 210 return nil, fmt.Errorf("tx data index %d out of bounds", ps.Indexes.Data) 211 } 212 if ps.Indexes.Value > len(tx.Value) { 213 return nil, fmt.Errorf("tx value index %d out of bounds", ps.Indexes.Value) 214 } 215 if ps.Indexes.Gas > len(tx.GasLimit) { 216 return nil, fmt.Errorf("tx gas limit index %d out of bounds", ps.Indexes.Gas) 217 } 218 dataHex := tx.Data[ps.Indexes.Data] 219 valueHex := tx.Value[ps.Indexes.Value] 220 gasLimit := tx.GasLimit[ps.Indexes.Gas] 221 // Value, Data hex encoding is messy: https://github.com/ethereum/tests/issues/203 222 value := new(big.Int) 223 if valueHex != "0x" { 224 v, ok := math.ParseBig256(valueHex) 225 if !ok { 226 return nil, fmt.Errorf("invalid tx value %q", valueHex) 227 } 228 value = v 229 } 230 data, err := hex.DecodeString(strings.TrimPrefix(dataHex, "0x")) 231 if err != nil { 232 return nil, fmt.Errorf("invalid tx data %q", dataHex) 233 } 234 235 msg := types.NewMessage(from, to, tx.Nonce, value, gasLimit, tx.GasPrice, data, true) 236 return msg, nil 237 } 238 239 func rlpHash(x interface{}) (h common.Hash) { 240 hw := sha3.NewKeccak256() 241 rlp.Encode(hw, x) 242 hw.Sum(h[:0]) 243 return h 244 }