github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/tests/state_test_util.go (about) 1 // Copyright 2018 The go-ethereum Authors 2 // Copyright 2019 The go-aigar Authors 3 // This file is part of the go-aigar library. 4 // 5 // The go-aigar library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The go-aigar library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the go-aigar library. If not, see <http://www.gnu.org/licenses/>. 17 18 package tests 19 20 import ( 21 "encoding/hex" 22 "encoding/json" 23 "fmt" 24 "math/big" 25 "strconv" 26 "strings" 27 28 "github.com/AigarNetwork/aigar/common" 29 "github.com/AigarNetwork/aigar/common/hexutil" 30 "github.com/AigarNetwork/aigar/common/math" 31 "github.com/AigarNetwork/aigar/core" 32 "github.com/AigarNetwork/aigar/core/rawdb" 33 "github.com/AigarNetwork/aigar/core/state" 34 "github.com/AigarNetwork/aigar/core/types" 35 "github.com/AigarNetwork/aigar/core/vm" 36 "github.com/AigarNetwork/aigar/crypto" 37 "github.com/AigarNetwork/aigar/ethdb" 38 "github.com/AigarNetwork/aigar/params" 39 "github.com/AigarNetwork/aigar/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 } 86 87 type stEnvMarshaling struct { 88 Coinbase common.UnprefixedAddress 89 Difficulty *math.HexOrDecimal256 90 GasLimit math.HexOrDecimal64 91 Number math.HexOrDecimal64 92 Timestamp math.HexOrDecimal64 93 } 94 95 //go:generate gencodec -type stTransaction -field-override stTransactionMarshaling -out gen_sttransaction.go 96 97 type stTransaction struct { 98 GasPrice *big.Int `json:"gasPrice"` 99 Nonce uint64 `json:"nonce"` 100 To string `json:"to"` 101 Data []string `json:"data"` 102 GasLimit []uint64 `json:"gasLimit"` 103 Value []string `json:"value"` 104 PrivateKey []byte `json:"secretKey"` 105 } 106 107 type stTransactionMarshaling struct { 108 GasPrice *math.HexOrDecimal256 109 Nonce math.HexOrDecimal64 110 GasLimit []math.HexOrDecimal64 111 PrivateKey hexutil.Bytes 112 } 113 114 // getVMConfig takes a fork definition and returns a chain config. 115 // The fork definition can be 116 // - a plain forkname, e.g. `Byzantium`, 117 // - a fork basename, and a list of EIPs to enable; e.g. `Byzantium+1884+1283`. 118 func getVMConfig(forkString string) (baseConfig *params.ChainConfig, eips []int, err error) { 119 var ( 120 splitForks = strings.Split(forkString, "+") 121 ok bool 122 baseName, eipsStrings = splitForks[0], splitForks[1:] 123 ) 124 if baseConfig, ok = Forks[baseName]; !ok { 125 return nil, nil, UnsupportedForkError{baseName} 126 } 127 for _, eip := range eipsStrings { 128 if eipNum, err := strconv.Atoi(eip); err != nil { 129 return nil, nil, fmt.Errorf("syntax error, invalid eip number %v", eipNum) 130 } else { 131 eips = append(eips, eipNum) 132 } 133 } 134 return baseConfig, eips, nil 135 } 136 137 // Subtests returns all valid subtests of the test. 138 func (t *StateTest) Subtests() []StateSubtest { 139 var sub []StateSubtest 140 for fork, pss := range t.json.Post { 141 for i := range pss { 142 sub = append(sub, StateSubtest{fork, i}) 143 } 144 } 145 return sub 146 } 147 148 // Run executes a specific subtest and verifies the post-state and logs 149 func (t *StateTest) Run(subtest StateSubtest, vmconfig vm.Config) (*state.StateDB, error) { 150 statedb, root, err := t.RunNoVerify(subtest, vmconfig) 151 if err != nil { 152 return statedb, err 153 } 154 post := t.json.Post[subtest.Fork][subtest.Index] 155 // N.B: We need to do this in a two-step process, because the first Commit takes care 156 // of suicides, and we need to touch the coinbase _after_ it has potentially suicided. 157 if root != common.Hash(post.Root) { 158 return statedb, fmt.Errorf("post state root mismatch: got %x, want %x", root, post.Root) 159 } 160 if logs := rlpHash(statedb.Logs()); logs != common.Hash(post.Logs) { 161 return statedb, fmt.Errorf("post state logs hash mismatch: got %x, want %x", logs, post.Logs) 162 } 163 return statedb, nil 164 } 165 166 // RunNoVerify runs a specific subtest and returns the statedb and post-state root 167 func (t *StateTest) RunNoVerify(subtest StateSubtest, vmconfig vm.Config) (*state.StateDB, common.Hash, error) { 168 config, eips, err := getVMConfig(subtest.Fork) 169 if err != nil { 170 return nil, common.Hash{}, UnsupportedForkError{subtest.Fork} 171 } 172 vmconfig.ExtraEips = eips 173 block := t.genesis(config).ToBlock(nil) 174 statedb := MakePreState(rawdb.NewMemoryDatabase(), t.json.Pre) 175 176 post := t.json.Post[subtest.Fork][subtest.Index] 177 msg, err := t.json.Tx.toMessage(post) 178 if err != nil { 179 return nil, common.Hash{}, err 180 } 181 context := core.NewEVMContext(msg, block.Header(), nil, &t.json.Env.Coinbase) 182 context.GetHash = vmTestBlockHash 183 evm := vm.NewEVM(context, statedb, config, vmconfig) 184 185 gaspool := new(core.GasPool) 186 gaspool.AddGas(block.GasLimit()) 187 snapshot := statedb.Snapshot() 188 if _, _, _, err := core.ApplyMessage(evm, msg, gaspool); err != nil { 189 statedb.RevertToSnapshot(snapshot) 190 } 191 // Commit block 192 statedb.Commit(config.IsEIP158(block.Number())) 193 // Add 0-value mining reward. This only makes a difference in the cases 194 // where 195 // - the coinbase suicided, or 196 // - there are only 'bad' transactions, which aren't executed. In those cases, 197 // the coinbase gets no txfee, so isn't created, and thus needs to be touched 198 statedb.AddBalance(block.Coinbase(), new(big.Int)) 199 // And _now_ get the state root 200 root := statedb.IntermediateRoot(config.IsEIP158(block.Number())) 201 return statedb, root, nil 202 } 203 204 func (t *StateTest) gasLimit(subtest StateSubtest) uint64 { 205 return t.json.Tx.GasLimit[t.json.Post[subtest.Fork][subtest.Index].Indexes.Gas] 206 } 207 208 func MakePreState(db ethdb.Database, accounts core.GenesisAlloc) *state.StateDB { 209 sdb := state.NewDatabase(db) 210 statedb, _ := state.New(common.Hash{}, sdb) 211 for addr, a := range accounts { 212 statedb.SetCode(addr, a.Code) 213 statedb.SetNonce(addr, a.Nonce) 214 statedb.SetBalance(addr, a.Balance) 215 for k, v := range a.Storage { 216 statedb.SetState(addr, k, v) 217 } 218 } 219 // Commit and re-open to start with a clean state. 220 root, _ := statedb.Commit(false) 221 statedb, _ = state.New(root, sdb) 222 return statedb 223 } 224 225 func (t *StateTest) genesis(config *params.ChainConfig) *core.Genesis { 226 return &core.Genesis{ 227 Config: config, 228 Coinbase: t.json.Env.Coinbase, 229 Difficulty: t.json.Env.Difficulty, 230 GasLimit: t.json.Env.GasLimit, 231 Number: t.json.Env.Number, 232 Timestamp: t.json.Env.Timestamp, 233 Alloc: t.json.Pre, 234 } 235 } 236 237 func (tx *stTransaction) toMessage(ps stPostState) (core.Message, error) { 238 // Derive sender from private key if present. 239 var from common.Address 240 if len(tx.PrivateKey) > 0 { 241 key, err := crypto.ToECDSA(tx.PrivateKey) 242 if err != nil { 243 return nil, fmt.Errorf("invalid private key: %v", err) 244 } 245 from = crypto.PubkeyToAddress(key.PublicKey) 246 } 247 // Parse recipient if present. 248 var to *common.Address 249 if tx.To != "" { 250 to = new(common.Address) 251 if err := to.UnmarshalText([]byte(tx.To)); err != nil { 252 return nil, fmt.Errorf("invalid to address: %v", err) 253 } 254 } 255 256 // Get values specific to this post state. 257 if ps.Indexes.Data > len(tx.Data) { 258 return nil, fmt.Errorf("tx data index %d out of bounds", ps.Indexes.Data) 259 } 260 if ps.Indexes.Value > len(tx.Value) { 261 return nil, fmt.Errorf("tx value index %d out of bounds", ps.Indexes.Value) 262 } 263 if ps.Indexes.Gas > len(tx.GasLimit) { 264 return nil, fmt.Errorf("tx gas limit index %d out of bounds", ps.Indexes.Gas) 265 } 266 dataHex := tx.Data[ps.Indexes.Data] 267 valueHex := tx.Value[ps.Indexes.Value] 268 gasLimit := tx.GasLimit[ps.Indexes.Gas] 269 // Value, Data hex encoding is messy: https://github.com/ethereum/tests/issues/203 270 value := new(big.Int) 271 if valueHex != "0x" { 272 v, ok := math.ParseBig256(valueHex) 273 if !ok { 274 return nil, fmt.Errorf("invalid tx value %q", valueHex) 275 } 276 value = v 277 } 278 data, err := hex.DecodeString(strings.TrimPrefix(dataHex, "0x")) 279 if err != nil { 280 return nil, fmt.Errorf("invalid tx data %q", dataHex) 281 } 282 283 msg := types.NewMessage(from, to, tx.Nonce, value, gasLimit, tx.GasPrice, data, true) 284 return msg, nil 285 } 286 287 func rlpHash(x interface{}) (h common.Hash) { 288 hw := sha3.NewLegacyKeccak256() 289 rlp.Encode(hw, x) 290 hw.Sum(h[:0]) 291 return h 292 }