github.com/MaynardMiner/ethereumprogpow@v1.8.23/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/ethereumprogpow/ethereumprogpow/common" 27 "github.com/ethereumprogpow/ethereumprogpow/common/hexutil" 28 "github.com/ethereumprogpow/ethereumprogpow/common/math" 29 "github.com/ethereumprogpow/ethereumprogpow/core" 30 "github.com/ethereumprogpow/ethereumprogpow/core/state" 31 "github.com/ethereumprogpow/ethereumprogpow/core/types" 32 "github.com/ethereumprogpow/ethereumprogpow/core/vm" 33 "github.com/ethereumprogpow/ethereumprogpow/crypto" 34 "github.com/ethereumprogpow/ethereumprogpow/ethdb" 35 "github.com/ethereumprogpow/ethereumprogpow/params" 36 "github.com/ethereumprogpow/ethereumprogpow/rlp" 37 "golang.org/x/crypto/sha3" 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 // Commit block 147 statedb.Commit(config.IsEIP158(block.Number())) 148 // Add 0-value mining reward. This only makes a difference in the cases 149 // where 150 // - the coinbase suicided, or 151 // - there are only 'bad' transactions, which aren't executed. In those cases, 152 // the coinbase gets no txfee, so isn't created, and thus needs to be touched 153 statedb.AddBalance(block.Coinbase(), new(big.Int)) 154 // And _now_ get the state root 155 root := statedb.IntermediateRoot(config.IsEIP158(block.Number())) 156 // N.B: We need to do this in a two-step process, because the first Commit takes care 157 // of suicides, and we need to touch the coinbase _after_ it has potentially suicided. 158 if root != common.Hash(post.Root) { 159 return statedb, fmt.Errorf("post state root mismatch: got %x, want %x", root, post.Root) 160 } 161 if logs := rlpHash(statedb.Logs()); logs != common.Hash(post.Logs) { 162 return statedb, fmt.Errorf("post state logs hash mismatch: got %x, want %x", logs, post.Logs) 163 } 164 return statedb, nil 165 } 166 167 func (t *StateTest) gasLimit(subtest StateSubtest) uint64 { 168 return t.json.Tx.GasLimit[t.json.Post[subtest.Fork][subtest.Index].Indexes.Gas] 169 } 170 171 func MakePreState(db ethdb.Database, accounts core.GenesisAlloc) *state.StateDB { 172 sdb := state.NewDatabase(db) 173 statedb, _ := state.New(common.Hash{}, sdb) 174 for addr, a := range accounts { 175 statedb.SetCode(addr, a.Code) 176 statedb.SetNonce(addr, a.Nonce) 177 statedb.SetBalance(addr, a.Balance) 178 for k, v := range a.Storage { 179 statedb.SetState(addr, k, v) 180 } 181 } 182 // Commit and re-open to start with a clean state. 183 root, _ := statedb.Commit(false) 184 statedb, _ = state.New(root, sdb) 185 return statedb 186 } 187 188 func (t *StateTest) genesis(config *params.ChainConfig) *core.Genesis { 189 return &core.Genesis{ 190 Config: config, 191 Coinbase: t.json.Env.Coinbase, 192 Difficulty: t.json.Env.Difficulty, 193 GasLimit: t.json.Env.GasLimit, 194 Number: t.json.Env.Number, 195 Timestamp: t.json.Env.Timestamp, 196 Alloc: t.json.Pre, 197 } 198 } 199 200 func (tx *stTransaction) toMessage(ps stPostState) (core.Message, error) { 201 // Derive sender from private key if present. 202 var from common.Address 203 if len(tx.PrivateKey) > 0 { 204 key, err := crypto.ToECDSA(tx.PrivateKey) 205 if err != nil { 206 return nil, fmt.Errorf("invalid private key: %v", err) 207 } 208 from = crypto.PubkeyToAddress(key.PublicKey) 209 } 210 // Parse recipient if present. 211 var to *common.Address 212 if tx.To != "" { 213 to = new(common.Address) 214 if err := to.UnmarshalText([]byte(tx.To)); err != nil { 215 return nil, fmt.Errorf("invalid to address: %v", err) 216 } 217 } 218 219 // Get values specific to this post state. 220 if ps.Indexes.Data > len(tx.Data) { 221 return nil, fmt.Errorf("tx data index %d out of bounds", ps.Indexes.Data) 222 } 223 if ps.Indexes.Value > len(tx.Value) { 224 return nil, fmt.Errorf("tx value index %d out of bounds", ps.Indexes.Value) 225 } 226 if ps.Indexes.Gas > len(tx.GasLimit) { 227 return nil, fmt.Errorf("tx gas limit index %d out of bounds", ps.Indexes.Gas) 228 } 229 dataHex := tx.Data[ps.Indexes.Data] 230 valueHex := tx.Value[ps.Indexes.Value] 231 gasLimit := tx.GasLimit[ps.Indexes.Gas] 232 // Value, Data hex encoding is messy: https://github.com/ethereum/tests/issues/203 233 value := new(big.Int) 234 if valueHex != "0x" { 235 v, ok := math.ParseBig256(valueHex) 236 if !ok { 237 return nil, fmt.Errorf("invalid tx value %q", valueHex) 238 } 239 value = v 240 } 241 data, err := hex.DecodeString(strings.TrimPrefix(dataHex, "0x")) 242 if err != nil { 243 return nil, fmt.Errorf("invalid tx data %q", dataHex) 244 } 245 246 msg := types.NewMessage(from, to, tx.Nonce, value, gasLimit, tx.GasPrice, data, true) 247 return msg, nil 248 } 249 250 func rlpHash(x interface{}) (h common.Hash) { 251 hw := sha3.NewLegacyKeccak256() 252 rlp.Encode(hw, x) 253 hw.Sum(h[:0]) 254 return h 255 }