github.com/aswedchain/aswed@v1.0.1/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 "strconv" 25 "strings" 26 27 "github.com/aswedchain/aswed/core/state/snapshot" 28 29 "github.com/aswedchain/aswed/common" 30 "github.com/aswedchain/aswed/common/hexutil" 31 "github.com/aswedchain/aswed/common/math" 32 "github.com/aswedchain/aswed/core" 33 "github.com/aswedchain/aswed/core/rawdb" 34 "github.com/aswedchain/aswed/core/state" 35 "github.com/aswedchain/aswed/core/types" 36 "github.com/aswedchain/aswed/core/vm" 37 "github.com/aswedchain/aswed/crypto" 38 "github.com/aswedchain/aswed/ethdb" 39 "github.com/aswedchain/aswed/params" 40 "github.com/aswedchain/aswed/rlp" 41 "golang.org/x/crypto/sha3" 42 ) 43 44 // StateTest checks transaction processing without block context. 45 // See https://github.com/ethereum/EIPs/issues/176 for the test format specification. 46 type StateTest struct { 47 json stJSON 48 } 49 50 // StateSubtest selects a specific configuration of a General State Test. 51 type StateSubtest struct { 52 Fork string 53 Index int 54 } 55 56 func (t *StateTest) UnmarshalJSON(in []byte) error { 57 return json.Unmarshal(in, &t.json) 58 } 59 60 type stJSON struct { 61 Env stEnv `json:"env"` 62 Pre core.GenesisAlloc `json:"pre"` 63 Tx stTransaction `json:"transaction"` 64 Out hexutil.Bytes `json:"out"` 65 Post map[string][]stPostState `json:"post"` 66 } 67 68 type stPostState struct { 69 Root common.UnprefixedHash `json:"hash"` 70 Logs common.UnprefixedHash `json:"logs"` 71 Indexes struct { 72 Data int `json:"data"` 73 Gas int `json:"gas"` 74 Value int `json:"value"` 75 } 76 } 77 78 //go:generate gencodec -type stEnv -field-override stEnvMarshaling -out gen_stenv.go 79 80 type stEnv struct { 81 Coinbase common.Address `json:"currentCoinbase" gencodec:"required"` 82 Difficulty *big.Int `json:"currentDifficulty" gencodec:"required"` 83 GasLimit uint64 `json:"currentGasLimit" gencodec:"required"` 84 Number uint64 `json:"currentNumber" gencodec:"required"` 85 Timestamp uint64 `json:"currentTimestamp" gencodec:"required"` 86 } 87 88 type stEnvMarshaling struct { 89 Coinbase common.UnprefixedAddress 90 Difficulty *math.HexOrDecimal256 91 GasLimit math.HexOrDecimal64 92 Number math.HexOrDecimal64 93 Timestamp math.HexOrDecimal64 94 } 95 96 //go:generate gencodec -type stTransaction -field-override stTransactionMarshaling -out gen_sttransaction.go 97 98 type stTransaction struct { 99 GasPrice *big.Int `json:"gasPrice"` 100 Nonce uint64 `json:"nonce"` 101 To string `json:"to"` 102 Data []string `json:"data"` 103 GasLimit []uint64 `json:"gasLimit"` 104 Value []string `json:"value"` 105 PrivateKey []byte `json:"secretKey"` 106 } 107 108 type stTransactionMarshaling struct { 109 GasPrice *math.HexOrDecimal256 110 Nonce math.HexOrDecimal64 111 GasLimit []math.HexOrDecimal64 112 PrivateKey hexutil.Bytes 113 } 114 115 // GetChainConfig takes a fork definition and returns a chain config. 116 // The fork definition can be 117 // - a plain forkname, e.g. `Byzantium`, 118 // - a fork basename, and a list of EIPs to enable; e.g. `Byzantium+1884+1283`. 119 func GetChainConfig(forkString string) (baseConfig *params.ChainConfig, eips []int, err error) { 120 var ( 121 splitForks = strings.Split(forkString, "+") 122 ok bool 123 baseName, eipsStrings = splitForks[0], splitForks[1:] 124 ) 125 if baseConfig, ok = Forks[baseName]; !ok { 126 return nil, nil, UnsupportedForkError{baseName} 127 } 128 for _, eip := range eipsStrings { 129 if eipNum, err := strconv.Atoi(eip); err != nil { 130 return nil, nil, fmt.Errorf("syntax error, invalid eip number %v", eipNum) 131 } else { 132 if !vm.ValidEip(eipNum) { 133 return nil, nil, fmt.Errorf("syntax error, invalid eip number %v", eipNum) 134 } 135 eips = append(eips, eipNum) 136 } 137 } 138 return baseConfig, eips, nil 139 } 140 141 // Subtests returns all valid subtests of the test. 142 func (t *StateTest) Subtests() []StateSubtest { 143 var sub []StateSubtest 144 for fork, pss := range t.json.Post { 145 for i := range pss { 146 sub = append(sub, StateSubtest{fork, i}) 147 } 148 } 149 return sub 150 } 151 152 // Run executes a specific subtest and verifies the post-state and logs 153 func (t *StateTest) Run(subtest StateSubtest, vmconfig vm.Config, snapshotter bool) (*snapshot.Tree, *state.StateDB, error) { 154 snaps, statedb, root, err := t.RunNoVerify(subtest, vmconfig, snapshotter) 155 if err != nil { 156 return snaps, statedb, err 157 } 158 post := t.json.Post[subtest.Fork][subtest.Index] 159 // N.B: We need to do this in a two-step process, because the first Commit takes care 160 // of suicides, and we need to touch the coinbase _after_ it has potentially suicided. 161 if root != common.Hash(post.Root) { 162 return snaps, statedb, fmt.Errorf("post state root mismatch: got %x, want %x", root, post.Root) 163 } 164 if logs := rlpHash(statedb.Logs()); logs != common.Hash(post.Logs) { 165 return snaps, statedb, fmt.Errorf("post state logs hash mismatch: got %x, want %x", logs, post.Logs) 166 } 167 return snaps, statedb, nil 168 } 169 170 // RunNoVerify runs a specific subtest and returns the statedb and post-state root 171 func (t *StateTest) RunNoVerify(subtest StateSubtest, vmconfig vm.Config, snapshotter bool) (*snapshot.Tree, *state.StateDB, common.Hash, error) { 172 config, eips, err := GetChainConfig(subtest.Fork) 173 if err != nil { 174 return nil, nil, common.Hash{}, UnsupportedForkError{subtest.Fork} 175 } 176 vmconfig.ExtraEips = eips 177 block := t.genesis(config).ToBlock(nil) 178 snaps, statedb := MakePreState(rawdb.NewMemoryDatabase(), t.json.Pre, snapshotter) 179 180 post := t.json.Post[subtest.Fork][subtest.Index] 181 msg, err := t.json.Tx.toMessage(post) 182 if err != nil { 183 return nil, nil, common.Hash{}, err 184 } 185 context := core.NewEVMContext(msg, block.Header(), nil, &t.json.Env.Coinbase) 186 context.GetHash = vmTestBlockHash 187 evm := vm.NewEVM(context, statedb, config, vmconfig) 188 189 gaspool := new(core.GasPool) 190 gaspool.AddGas(block.GasLimit()) 191 snapshot := statedb.Snapshot() 192 if _, err := core.ApplyMessage(evm, msg, gaspool); err != nil { 193 statedb.RevertToSnapshot(snapshot) 194 } 195 // Commit block 196 statedb.Commit(config.IsEIP158(block.Number())) 197 // Add 0-value mining reward. This only makes a difference in the cases 198 // where 199 // - the coinbase suicided, or 200 // - there are only 'bad' transactions, which aren't executed. In those cases, 201 // the coinbase gets no txfee, so isn't created, and thus needs to be touched 202 statedb.AddBalance(block.Coinbase(), new(big.Int)) 203 // And _now_ get the state root 204 root := statedb.IntermediateRoot(config.IsEIP158(block.Number())) 205 return snaps, statedb, root, nil 206 } 207 208 func (t *StateTest) gasLimit(subtest StateSubtest) uint64 { 209 return t.json.Tx.GasLimit[t.json.Post[subtest.Fork][subtest.Index].Indexes.Gas] 210 } 211 212 func MakePreState(db ethdb.Database, accounts core.GenesisAlloc, snapshotter bool) (*snapshot.Tree, *state.StateDB) { 213 sdb := state.NewDatabase(db) 214 statedb, _ := state.New(common.Hash{}, sdb, nil) 215 for addr, a := range accounts { 216 statedb.SetCode(addr, a.Code) 217 statedb.SetNonce(addr, a.Nonce) 218 statedb.SetBalance(addr, a.Balance) 219 for k, v := range a.Storage { 220 statedb.SetState(addr, k, v) 221 } 222 } 223 // Commit and re-open to start with a clean state. 224 root, _ := statedb.Commit(false) 225 226 var snaps *snapshot.Tree 227 if snapshotter { 228 snaps = snapshot.New(db, sdb.TrieDB(), 1, root, false) 229 } 230 statedb, _ = state.New(root, sdb, snaps) 231 return snaps, statedb 232 } 233 234 func (t *StateTest) genesis(config *params.ChainConfig) *core.Genesis { 235 return &core.Genesis{ 236 Config: config, 237 Coinbase: t.json.Env.Coinbase, 238 Difficulty: t.json.Env.Difficulty, 239 GasLimit: t.json.Env.GasLimit, 240 Number: t.json.Env.Number, 241 Timestamp: t.json.Env.Timestamp, 242 Alloc: t.json.Pre, 243 } 244 } 245 246 func (tx *stTransaction) toMessage(ps stPostState) (core.Message, error) { 247 // Derive sender from private key if present. 248 var from common.Address 249 if len(tx.PrivateKey) > 0 { 250 key, err := crypto.ToECDSA(tx.PrivateKey) 251 if err != nil { 252 return nil, fmt.Errorf("invalid private key: %v", err) 253 } 254 from = crypto.PubkeyToAddress(key.PublicKey) 255 } 256 // Parse recipient if present. 257 var to *common.Address 258 if tx.To != "" { 259 to = new(common.Address) 260 if err := to.UnmarshalText([]byte(tx.To)); err != nil { 261 return nil, fmt.Errorf("invalid to address: %v", err) 262 } 263 } 264 265 // Get values specific to this post state. 266 if ps.Indexes.Data > len(tx.Data) { 267 return nil, fmt.Errorf("tx data index %d out of bounds", ps.Indexes.Data) 268 } 269 if ps.Indexes.Value > len(tx.Value) { 270 return nil, fmt.Errorf("tx value index %d out of bounds", ps.Indexes.Value) 271 } 272 if ps.Indexes.Gas > len(tx.GasLimit) { 273 return nil, fmt.Errorf("tx gas limit index %d out of bounds", ps.Indexes.Gas) 274 } 275 dataHex := tx.Data[ps.Indexes.Data] 276 valueHex := tx.Value[ps.Indexes.Value] 277 gasLimit := tx.GasLimit[ps.Indexes.Gas] 278 // Value, Data hex encoding is messy: https://github.com/ethereum/tests/issues/203 279 value := new(big.Int) 280 if valueHex != "0x" { 281 v, ok := math.ParseBig256(valueHex) 282 if !ok { 283 return nil, fmt.Errorf("invalid tx value %q", valueHex) 284 } 285 value = v 286 } 287 data, err := hex.DecodeString(strings.TrimPrefix(dataHex, "0x")) 288 if err != nil { 289 return nil, fmt.Errorf("invalid tx data %q", dataHex) 290 } 291 292 msg := types.NewMessage(from, to, tx.Nonce, value, gasLimit, tx.GasPrice, data, true) 293 return msg, nil 294 } 295 296 func rlpHash(x interface{}) (h common.Hash) { 297 hw := sha3.NewLegacyKeccak256() 298 rlp.Encode(hw, x) 299 hw.Sum(h[:0]) 300 return h 301 }