github.com/theQRL/go-zond@v0.2.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 "errors" 23 "fmt" 24 "math/big" 25 "strconv" 26 "strings" 27 28 "github.com/theQRL/go-qrllib/dilithium" 29 "github.com/theQRL/go-zond/common" 30 "github.com/theQRL/go-zond/common/hexutil" 31 "github.com/theQRL/go-zond/common/math" 32 "github.com/theQRL/go-zond/core" 33 "github.com/theQRL/go-zond/core/rawdb" 34 "github.com/theQRL/go-zond/core/state" 35 "github.com/theQRL/go-zond/core/state/snapshot" 36 "github.com/theQRL/go-zond/core/types" 37 "github.com/theQRL/go-zond/core/vm" 38 "github.com/theQRL/go-zond/crypto" 39 "github.com/theQRL/go-zond/params" 40 "github.com/theQRL/go-zond/rlp" 41 "github.com/theQRL/go-zond/trie" 42 "github.com/theQRL/go-zond/trie/triedb/hashdb" 43 "github.com/theQRL/go-zond/trie/triedb/pathdb" 44 "github.com/theQRL/go-zond/zonddb" 45 "golang.org/x/crypto/sha3" 46 ) 47 48 // StateTest checks transaction processing without block context. 49 // See https://github.com/ethereum/EIPs/issues/176 for the test format specification. 50 type StateTest struct { 51 json stJSON 52 } 53 54 // StateSubtest selects a specific configuration of a General State Test. 55 type StateSubtest struct { 56 Fork string 57 Index int 58 } 59 60 func (t *StateTest) UnmarshalJSON(in []byte) error { 61 return json.Unmarshal(in, &t.json) 62 } 63 64 type stJSON struct { 65 Env stEnv `json:"env"` 66 Pre core.GenesisAlloc `json:"pre"` 67 Tx stTransaction `json:"transaction"` 68 Out hexutil.Bytes `json:"out"` 69 Post map[string][]stPostState `json:"post"` 70 } 71 72 type stPostState struct { 73 Root common.UnprefixedHash `json:"hash"` 74 Logs common.UnprefixedHash `json:"logs"` 75 TxBytes hexutil.Bytes `json:"txbytes"` 76 ExpectException string `json:"expectException"` 77 Indexes struct { 78 Data int `json:"data"` 79 Gas int `json:"gas"` 80 Value int `json:"value"` 81 } 82 } 83 84 //go:generate go run github.com/fjl/gencodec -type stEnv -field-override stEnvMarshaling -out gen_stenv.go 85 86 type stEnv struct { 87 Coinbase common.Address `json:"currentCoinbase" gencodec:"required"` 88 Random *big.Int `json:"currentRandom" gencodec:"optional"` 89 GasLimit uint64 `json:"currentGasLimit" gencodec:"required"` 90 Number uint64 `json:"currentNumber" gencodec:"required"` 91 Timestamp uint64 `json:"currentTimestamp" gencodec:"required"` 92 BaseFee *big.Int `json:"currentBaseFee" gencodec:"optional"` 93 } 94 95 type stEnvMarshaling struct { 96 Coinbase common.Address 97 Random *math.HexOrDecimal256 98 GasLimit math.HexOrDecimal64 99 Number math.HexOrDecimal64 100 Timestamp math.HexOrDecimal64 101 BaseFee *math.HexOrDecimal256 102 } 103 104 //go:generate go run github.com/fjl/gencodec -type stTransaction -field-override stTransactionMarshaling -out gen_sttransaction.go 105 106 type stTransaction struct { 107 GasPrice *big.Int `json:"gasPrice"` 108 MaxFeePerGas *big.Int `json:"maxFeePerGas"` 109 MaxPriorityFeePerGas *big.Int `json:"maxPriorityFeePerGas"` 110 Nonce uint64 `json:"nonce"` 111 To string `json:"to"` 112 Data []string `json:"data"` 113 AccessLists []*types.AccessList `json:"accessLists,omitempty"` 114 GasLimit []uint64 `json:"gasLimit"` 115 Value []string `json:"value"` 116 Seed string `json:"seed"` 117 Sender *common.Address `json:"sender"` 118 } 119 120 type stTransactionMarshaling struct { 121 GasPrice *math.HexOrDecimal256 122 MaxFeePerGas *math.HexOrDecimal256 123 MaxPriorityFeePerGas *math.HexOrDecimal256 124 Nonce math.HexOrDecimal64 125 GasLimit []math.HexOrDecimal64 126 Seed hexutil.Bytes 127 } 128 129 // GetChainConfig takes a fork definition and returns a chain config. 130 // The fork definition can be 131 // - a plain forkname, e.g. `Byzantium`, 132 // - a fork basename, and a list of EIPs to enable; e.g. `Byzantium+1884+1283`. 133 func GetChainConfig(forkString string) (baseConfig *params.ChainConfig, eips []int, err error) { 134 var ( 135 splitForks = strings.Split(forkString, "+") 136 ok bool 137 baseName, eipsStrings = splitForks[0], splitForks[1:] 138 ) 139 if baseConfig, ok = Forks[baseName]; !ok { 140 return nil, nil, UnsupportedForkError{baseName} 141 } 142 for _, eip := range eipsStrings { 143 if eipNum, err := strconv.Atoi(eip); err != nil { 144 return nil, nil, fmt.Errorf("syntax error, invalid eip number %v", eipNum) 145 } else { 146 if !vm.ValidEip(eipNum) { 147 return nil, nil, fmt.Errorf("syntax error, invalid eip number %v", eipNum) 148 } 149 eips = append(eips, eipNum) 150 } 151 } 152 return baseConfig, eips, nil 153 } 154 155 // Subtests returns all valid subtests of the test. 156 func (t *StateTest) Subtests() []StateSubtest { 157 var sub []StateSubtest 158 for fork, pss := range t.json.Post { 159 for i := range pss { 160 sub = append(sub, StateSubtest{fork, i}) 161 } 162 } 163 return sub 164 } 165 166 // checkError checks if the error returned by the state transition matches any expected error. 167 // A failing expectation returns a wrapped version of the original error, if any, 168 // or a new error detailing the failing expectation. 169 // This function does not return or modify the original error, it only evaluates and returns expectations for the error. 170 func (t *StateTest) checkError(subtest StateSubtest, err error) error { 171 expectedError := t.json.Post[subtest.Fork][subtest.Index].ExpectException 172 if err == nil && expectedError == "" { 173 return nil 174 } 175 if err == nil && expectedError != "" { 176 return fmt.Errorf("expected error %q, got no error", expectedError) 177 } 178 if err != nil && expectedError == "" { 179 return fmt.Errorf("unexpected error: %w", err) 180 } 181 if err != nil && expectedError != "" { 182 // Ignore expected errors (TODO MariusVanDerWijden check error string) 183 return nil 184 } 185 return nil 186 } 187 188 // Run executes a specific subtest and verifies the post-state and logs 189 func (t *StateTest) Run(subtest StateSubtest, vmconfig vm.Config, snapshotter bool, scheme string, postCheck func(err error, snaps *snapshot.Tree, state *state.StateDB)) (result error) { 190 triedb, snaps, statedb, root, err := t.RunNoVerify(subtest, vmconfig, snapshotter, scheme) 191 192 // Invoke the callback at the end of function for further analysis. 193 defer func() { 194 postCheck(result, snaps, statedb) 195 196 if triedb != nil { 197 triedb.Close() 198 } 199 }() 200 checkedErr := t.checkError(subtest, err) 201 if checkedErr != nil { 202 return checkedErr 203 } 204 // The error has been checked; if it was unexpected, it's already returned. 205 if err != nil { 206 // Here, an error exists but it was expected. 207 // We do not check the post state or logs. 208 return nil 209 } 210 post := t.json.Post[subtest.Fork][subtest.Index] 211 // N.B: We need to do this in a two-step process, because the first Commit takes care 212 // of self-destructs, and we need to touch the coinbase _after_ it has potentially self-destructed. 213 if root != common.Hash(post.Root) { 214 return fmt.Errorf("post state root mismatch: got %x, want %x", root, post.Root) 215 } 216 if logs := rlpHash(statedb.Logs()); logs != common.Hash(post.Logs) { 217 return fmt.Errorf("post state logs hash mismatch: got %x, want %x", logs, post.Logs) 218 } 219 statedb, _ = state.New(root, statedb.Database(), snaps) 220 return nil 221 } 222 223 // RunNoVerify runs a specific subtest and returns the statedb and post-state root 224 func (t *StateTest) RunNoVerify(subtest StateSubtest, vmconfig vm.Config, snapshotter bool, scheme string) (*trie.Database, *snapshot.Tree, *state.StateDB, common.Hash, error) { 225 config, eips, err := GetChainConfig(subtest.Fork) 226 if err != nil { 227 return nil, nil, nil, common.Hash{}, UnsupportedForkError{subtest.Fork} 228 } 229 vmconfig.ExtraEips = eips 230 231 block := t.genesis(config).ToBlock() 232 triedb, snaps, statedb := MakePreState(rawdb.NewMemoryDatabase(), t.json.Pre, snapshotter, scheme) 233 234 var baseFee *big.Int 235 baseFee = t.json.Env.BaseFee 236 if baseFee == nil { 237 // Retesteth uses `0x10` for genesis baseFee. Therefore, it defaults to 238 // parent - 2 : 0xa as the basefee for 'this' context. 239 baseFee = big.NewInt(0x0a) 240 } 241 242 post := t.json.Post[subtest.Fork][subtest.Index] 243 msg, err := t.json.Tx.toMessage(post, baseFee) 244 if err != nil { 245 triedb.Close() 246 return nil, nil, nil, common.Hash{}, err 247 } 248 249 // Try to recover tx with current signer 250 if len(post.TxBytes) != 0 { 251 var ttx types.Transaction 252 err := ttx.UnmarshalBinary(post.TxBytes) 253 if err != nil { 254 triedb.Close() 255 return nil, nil, nil, common.Hash{}, err 256 } 257 258 if _, err := types.Sender(types.LatestSigner(config), &ttx); err != nil { 259 triedb.Close() 260 return nil, nil, nil, common.Hash{}, err 261 } 262 } 263 264 // Prepare the ZVM. 265 txContext := core.NewZVMTxContext(msg) 266 context := core.NewZVMBlockContext(block.Header(), nil, &t.json.Env.Coinbase) 267 context.GetHash = vmTestBlockHash 268 context.BaseFee = baseFee 269 context.Random = nil 270 if t.json.Env.Random != nil { 271 rnd := common.BigToHash(t.json.Env.Random) 272 context.Random = &rnd 273 } 274 zvm := vm.NewZVM(context, txContext, statedb, config, vmconfig) 275 276 // Execute the message. 277 snapshot := statedb.Snapshot() 278 gaspool := new(core.GasPool) 279 gaspool.AddGas(block.GasLimit()) 280 _, err = core.ApplyMessage(zvm, msg, gaspool) 281 if err != nil { 282 statedb.RevertToSnapshot(snapshot) 283 } 284 // Add 0-value mining reward. This only makes a difference in the cases 285 // where 286 // - the coinbase self-destructed, or 287 // - there are only 'bad' transactions, which aren't executed. In those cases, 288 // the coinbase gets no txfee, so isn't created, and thus needs to be touched 289 statedb.AddBalance(block.Coinbase(), new(big.Int)) 290 291 // Commit state mutations into database. 292 root, _ := statedb.Commit(block.NumberU64(), true) 293 return triedb, snaps, statedb, root, err 294 } 295 296 func (t *StateTest) gasLimit(subtest StateSubtest) uint64 { 297 return t.json.Tx.GasLimit[t.json.Post[subtest.Fork][subtest.Index].Indexes.Gas] 298 } 299 300 func MakePreState(db zonddb.Database, accounts core.GenesisAlloc, snapshotter bool, scheme string) (*trie.Database, *snapshot.Tree, *state.StateDB) { 301 tconf := &trie.Config{Preimages: true} 302 if scheme == rawdb.HashScheme { 303 tconf.HashDB = hashdb.Defaults 304 } else { 305 tconf.PathDB = pathdb.Defaults 306 } 307 triedb := trie.NewDatabase(db, tconf) 308 sdb := state.NewDatabaseWithNodeDB(db, triedb) 309 statedb, _ := state.New(types.EmptyRootHash, sdb, nil) 310 for addr, a := range accounts { 311 statedb.SetCode(addr, a.Code) 312 statedb.SetNonce(addr, a.Nonce) 313 statedb.SetBalance(addr, a.Balance) 314 for k, v := range a.Storage { 315 statedb.SetState(addr, k, v) 316 } 317 } 318 // Commit and re-open to start with a clean state. 319 root, _ := statedb.Commit(0, false) 320 321 var snaps *snapshot.Tree 322 if snapshotter { 323 snapconfig := snapshot.Config{ 324 CacheSize: 1, 325 Recovery: false, 326 NoBuild: false, 327 AsyncBuild: false, 328 } 329 snaps, _ = snapshot.New(snapconfig, db, triedb, root) 330 } 331 statedb, _ = state.New(root, sdb, snaps) 332 return triedb, snaps, statedb 333 } 334 335 func (t *StateTest) genesis(config *params.ChainConfig) *core.Genesis { 336 genesis := &core.Genesis{ 337 Config: config, 338 Coinbase: t.json.Env.Coinbase, 339 GasLimit: t.json.Env.GasLimit, 340 Number: t.json.Env.Number, 341 Timestamp: t.json.Env.Timestamp, 342 Alloc: t.json.Pre, 343 } 344 if t.json.Env.Random != nil { 345 // Post-Merge 346 genesis.Mixhash = common.BigToHash(t.json.Env.Random) 347 } 348 return genesis 349 } 350 351 func (tx *stTransaction) toMessage(ps stPostState, baseFee *big.Int) (*core.Message, error) { 352 var from common.Address 353 // If 'sender' field is present, use that 354 if tx.Sender != nil { 355 from = *tx.Sender 356 } else if len(tx.Seed) > 0 { 357 // Derive sender from key if needed. 358 key, err := dilithium.NewDilithiumFromHexSeed(tx.Seed) 359 if err != nil { 360 return nil, fmt.Errorf("invalid seed: %v", err) 361 } 362 from = common.Address(key.GetAddress()) 363 } 364 // Parse recipient if present. 365 var to *common.Address 366 if tx.To != "" { 367 to = new(common.Address) 368 if err := to.UnmarshalText([]byte(tx.To)); err != nil { 369 return nil, fmt.Errorf("invalid to address: %v", err) 370 } 371 } 372 373 // Get values specific to this post state. 374 if ps.Indexes.Data > len(tx.Data) { 375 return nil, fmt.Errorf("tx data index %d out of bounds", ps.Indexes.Data) 376 } 377 if ps.Indexes.Value > len(tx.Value) { 378 return nil, fmt.Errorf("tx value index %d out of bounds", ps.Indexes.Value) 379 } 380 if ps.Indexes.Gas > len(tx.GasLimit) { 381 return nil, fmt.Errorf("tx gas limit index %d out of bounds", ps.Indexes.Gas) 382 } 383 dataHex := tx.Data[ps.Indexes.Data] 384 valueHex := tx.Value[ps.Indexes.Value] 385 gasLimit := tx.GasLimit[ps.Indexes.Gas] 386 // Value, Data hex encoding is messy: https://github.com/ethereum/tests/issues/203 387 value := new(big.Int) 388 if valueHex != "0x" { 389 v, ok := math.ParseBig256(valueHex) 390 if !ok { 391 return nil, fmt.Errorf("invalid tx value %q", valueHex) 392 } 393 value = v 394 } 395 data, err := hex.DecodeString(strings.TrimPrefix(dataHex, "0x")) 396 if err != nil { 397 return nil, fmt.Errorf("invalid tx data %q", dataHex) 398 } 399 var accessList types.AccessList 400 if tx.AccessLists != nil && tx.AccessLists[ps.Indexes.Data] != nil { 401 accessList = *tx.AccessLists[ps.Indexes.Data] 402 } 403 // If baseFee provided, set gasPrice to effectiveGasPrice. 404 gasPrice := tx.GasPrice 405 if baseFee != nil { 406 if tx.MaxFeePerGas == nil { 407 tx.MaxFeePerGas = gasPrice 408 } 409 if tx.MaxFeePerGas == nil { 410 tx.MaxFeePerGas = new(big.Int) 411 } 412 if tx.MaxPriorityFeePerGas == nil { 413 tx.MaxPriorityFeePerGas = tx.MaxFeePerGas 414 } 415 gasPrice = math.BigMin(new(big.Int).Add(tx.MaxPriorityFeePerGas, baseFee), 416 tx.MaxFeePerGas) 417 } 418 if gasPrice == nil { 419 return nil, errors.New("no gas price provided") 420 } 421 422 msg := &core.Message{ 423 From: from, 424 To: to, 425 Nonce: tx.Nonce, 426 Value: value, 427 GasLimit: gasLimit, 428 GasPrice: gasPrice, 429 GasFeeCap: tx.MaxFeePerGas, 430 GasTipCap: tx.MaxPriorityFeePerGas, 431 Data: data, 432 AccessList: accessList, 433 } 434 return msg, nil 435 } 436 437 func rlpHash(x interface{}) (h common.Hash) { 438 hw := sha3.NewLegacyKeccak256() 439 rlp.Encode(hw, x) 440 hw.Sum(h[:0]) 441 return h 442 } 443 444 func vmTestBlockHash(n uint64) common.Hash { 445 return common.BytesToHash(crypto.Keccak256([]byte(big.NewInt(int64(n)).String()))) 446 }