github.com/kisexp/xdchain@v0.0.0-20211206025815-490d6b732aa7/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/kisexp/xdchain/core/state/snapshot" 28 29 "github.com/kisexp/xdchain/common" 30 "github.com/kisexp/xdchain/common/hexutil" 31 "github.com/kisexp/xdchain/common/math" 32 "github.com/kisexp/xdchain/core" 33 "github.com/kisexp/xdchain/core/rawdb" 34 "github.com/kisexp/xdchain/core/state" 35 "github.com/kisexp/xdchain/core/types" 36 "github.com/kisexp/xdchain/core/vm" 37 "github.com/kisexp/xdchain/crypto" 38 "github.com/kisexp/xdchain/ethdb" 39 "github.com/kisexp/xdchain/params" 40 "github.com/kisexp/xdchain/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 txContext := core.NewEVMTxContext(msg) 186 context := core.NewEVMBlockContext(block.Header(), nil, &t.json.Env.Coinbase) 187 context.GetHash = vmTestBlockHash 188 evm := vm.NewEVM(context, txContext, statedb, statedb, config, vmconfig) 189 190 if config.IsYoloV2(context.BlockNumber) { 191 statedb.AddAddressToAccessList(msg.From()) 192 if dst := msg.To(); dst != nil { 193 statedb.AddAddressToAccessList(*dst) 194 // If it's a create-tx, the destination will be added inside evm.create 195 } 196 for _, addr := range evm.ActivePrecompiles() { 197 statedb.AddAddressToAccessList(addr) 198 } 199 } 200 gaspool := new(core.GasPool) 201 gaspool.AddGas(block.GasLimit()) 202 snapshot := statedb.Snapshot() 203 if _, err := core.ApplyMessage(evm, msg, gaspool); err != nil { 204 statedb.RevertToSnapshot(snapshot) 205 } 206 // Commit block 207 statedb.Commit(config.IsEIP158(block.Number())) 208 // Add 0-value mining reward. This only makes a difference in the cases 209 // where 210 // - the coinbase suicided, or 211 // - there are only 'bad' transactions, which aren't executed. In those cases, 212 // the coinbase gets no txfee, so isn't created, and thus needs to be touched 213 statedb.AddBalance(block.Coinbase(), new(big.Int)) 214 // And _now_ get the state root 215 root := statedb.IntermediateRoot(config.IsEIP158(block.Number())) 216 return snaps, statedb, root, nil 217 } 218 219 func (t *StateTest) gasLimit(subtest StateSubtest) uint64 { 220 return t.json.Tx.GasLimit[t.json.Post[subtest.Fork][subtest.Index].Indexes.Gas] 221 } 222 223 func MakePreState(db ethdb.Database, accounts core.GenesisAlloc, snapshotter bool) (*snapshot.Tree, *state.StateDB) { 224 sdb := state.NewDatabase(db) 225 statedb, _ := state.New(common.Hash{}, sdb, nil) 226 for addr, a := range accounts { 227 statedb.SetCode(addr, a.Code) 228 statedb.SetNonce(addr, a.Nonce) 229 statedb.SetBalance(addr, a.Balance) 230 for k, v := range a.Storage { 231 statedb.SetState(addr, k, v) 232 } 233 } 234 // Commit and re-open to start with a clean state. 235 root, _ := statedb.Commit(false) 236 237 var snaps *snapshot.Tree 238 if snapshotter { 239 snaps = snapshot.New(db, sdb.TrieDB(), 1, root, false, false) 240 } 241 statedb, _ = state.New(root, sdb, snaps) 242 return snaps, statedb 243 } 244 245 func (t *StateTest) genesis(config *params.ChainConfig) *core.Genesis { 246 return &core.Genesis{ 247 Config: config, 248 Coinbase: t.json.Env.Coinbase, 249 Difficulty: t.json.Env.Difficulty, 250 GasLimit: t.json.Env.GasLimit, 251 Number: t.json.Env.Number, 252 Timestamp: t.json.Env.Timestamp, 253 Alloc: t.json.Pre, 254 } 255 } 256 257 func (tx *stTransaction) toMessage(ps stPostState) (core.Message, error) { 258 // Derive sender from private key if present. 259 var from common.Address 260 if len(tx.PrivateKey) > 0 { 261 key, err := crypto.ToECDSA(tx.PrivateKey) 262 if err != nil { 263 return nil, fmt.Errorf("invalid private key: %v", err) 264 } 265 from = crypto.PubkeyToAddress(key.PublicKey) 266 } 267 // Parse recipient if present. 268 var to *common.Address 269 if tx.To != "" { 270 to = new(common.Address) 271 if err := to.UnmarshalText([]byte(tx.To)); err != nil { 272 return nil, fmt.Errorf("invalid to address: %v", err) 273 } 274 } 275 276 // Get values specific to this post state. 277 if ps.Indexes.Data > len(tx.Data) { 278 return nil, fmt.Errorf("tx data index %d out of bounds", ps.Indexes.Data) 279 } 280 if ps.Indexes.Value > len(tx.Value) { 281 return nil, fmt.Errorf("tx value index %d out of bounds", ps.Indexes.Value) 282 } 283 if ps.Indexes.Gas > len(tx.GasLimit) { 284 return nil, fmt.Errorf("tx gas limit index %d out of bounds", ps.Indexes.Gas) 285 } 286 dataHex := tx.Data[ps.Indexes.Data] 287 valueHex := tx.Value[ps.Indexes.Value] 288 gasLimit := tx.GasLimit[ps.Indexes.Gas] 289 // Value, Data hex encoding is messy: https://github.com/ethereum/tests/issues/203 290 value := new(big.Int) 291 if valueHex != "0x" { 292 v, ok := math.ParseBig256(valueHex) 293 if !ok { 294 return nil, fmt.Errorf("invalid tx value %q", valueHex) 295 } 296 value = v 297 } 298 data, err := hex.DecodeString(strings.TrimPrefix(dataHex, "0x")) 299 if err != nil { 300 return nil, fmt.Errorf("invalid tx data %q", dataHex) 301 } 302 303 msg := types.NewMessage(from, to, tx.Nonce, value, gasLimit, tx.GasPrice, data, true) 304 return msg, nil 305 } 306 307 func rlpHash(x interface{}) (h common.Hash) { 308 hw := sha3.NewLegacyKeccak256() 309 rlp.Encode(hw, x) 310 hw.Sum(h[:0]) 311 return h 312 }