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