aboutsummaryrefslogtreecommitdiffstats
path: root/cmd/ethtest/main.go
blob: 952ba1bd626fcfceab9e83e1214296eb14d572aa (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
/*
    This file is part of go-ethereum

    go-ethereum is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    go-ethereum is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with go-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @authors:
 *  Jeffrey Wilcke <i@jev.io>
 */

package main

import (
    "bytes"
    "encoding/json"
    "io"
    "io/ioutil"
    "log"
    "math/big"
    "os"
    "strconv"
    "strings"

    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/core/state"
    "github.com/ethereum/go-ethereum/core/types"
    "github.com/ethereum/go-ethereum/core/vm"
    "github.com/ethereum/go-ethereum/ethdb"
    "github.com/ethereum/go-ethereum/logger"
    "github.com/ethereum/go-ethereum/tests/helper"
)

type Log struct {
    AddressF string   `json:"address"`
    DataF    string   `json:"data"`
    TopicsF  []string `json:"topics"`
    BloomF   string   `json:"bloom"`
}

func (self Log) Address() []byte      { return common.Hex2Bytes(self.AddressF) }
func (self Log) Data() []byte         { return common.Hex2Bytes(self.DataF) }
func (self Log) RlpData() interface{} { return nil }
func (self Log) Topics() [][]byte {
    t := make([][]byte, len(self.TopicsF))
    for i, topic := range self.TopicsF {
        t[i] = common.Hex2Bytes(topic)
    }
    return t
}

type Account struct {
    Balance string
    Code    string
    Nonce   string
    Storage map[string]string
}

func StateObjectFromAccount(db common.Database, addr string, account Account) *state.StateObject {
    obj := state.NewStateObject(common.HexToAddress(addr), db)
    obj.SetBalance(common.Big(account.Balance))

    if common.IsHex(account.Code) {
        account.Code = account.Code[2:]
    }
    obj.SetCode(common.Hex2Bytes(account.Code))
    obj.SetNonce(common.Big(account.Nonce).Uint64())

    return obj
}

type VmTest struct {
    Callcreates   interface{}
    Env           Env
    Exec          map[string]string
    Transaction   map[string]string
    Logs          []Log
    Gas           string
    Out           string
    Post          map[string]Account
    Pre           map[string]Account
    PostStateRoot string
}

type Env struct {
    CurrentCoinbase   string
    CurrentDifficulty string
    CurrentGasLimit   string
    CurrentNumber     string
    CurrentTimestamp  interface{}
    PreviousHash      string
}

func RunVmTest(r io.Reader) (failed int) {
    tests := make(map[string]VmTest)

    data, _ := ioutil.ReadAll(r)
    err := json.Unmarshal(data, &tests)
    if err != nil {
        log.Fatalln(err)
    }

    for name, test := range tests {
        db, _ := ethdb.NewMemDatabase()
        statedb := state.New(common.Hash{}, db)
        for addr, account := range test.Pre {
            obj := StateObjectFromAccount(db, addr, account)
            statedb.SetStateObject(obj)
        }

        env := make(map[string]string)
        env["currentCoinbase"] = test.Env.CurrentCoinbase
        env["currentDifficulty"] = test.Env.CurrentDifficulty
        env["currentGasLimit"] = test.Env.CurrentGasLimit
        env["currentNumber"] = test.Env.CurrentNumber
        env["previousHash"] = test.Env.PreviousHash
        if n, ok := test.Env.CurrentTimestamp.(float64); ok {
            env["currentTimestamp"] = strconv.Itoa(int(n))
        } else {
            env["currentTimestamp"] = test.Env.CurrentTimestamp.(string)
        }

        ret, logs, _, _ := helper.RunState(statedb, env, test.Transaction)
        statedb.Sync()

        rexp := helper.FromHex(test.Out)
        if bytes.Compare(rexp, ret) != 0 {
            helper.Log.Infof("%s's return failed. Expected %x, got %x\n", name, rexp, ret)
            failed = 1
        }

        for addr, account := range test.Post {
            obj := statedb.GetStateObject(common.HexToAddress(addr))
            if obj == nil {
                continue
            }

            if len(test.Exec) == 0 {
                if obj.Balance().Cmp(common.Big(account.Balance)) != 0 {
                    helper.Log.Infof("%s's : (%x) balance failed. Expected %v, got %v => %v\n", name, obj.Address().Bytes()[:4], account.Balance, obj.Balance(), new(big.Int).Sub(common.Big(account.Balance), obj.Balance()))
                    failed = 1
                }
            }

            for addr, value := range account.Storage {
                v := obj.GetState(common.HexToHash(addr)).Bytes()
                vexp := helper.FromHex(value)

                if bytes.Compare(v, vexp) != 0 {
                    helper.Log.Infof("%s's : (%x: %s) storage failed. Expected %x, got %x (%v %v)\n", name, obj.Address().Bytes()[0:4], addr, vexp, v, common.BigD(vexp), common.BigD(v))
                    failed = 1
                }
            }
        }

        statedb.Sync()
        //if !bytes.Equal(common.Hex2Bytes(test.PostStateRoot), statedb.Root()) {
        if common.HexToHash(test.PostStateRoot) != statedb.Root() {
            helper.Log.Infof("%s's : Post state root failed. Expected %s, got %x", name, test.PostStateRoot, statedb.Root())
            failed = 1
        }

        if len(test.Logs) > 0 {
            if len(test.Logs) != len(logs) {
                helper.Log.Infof("log length failed. Expected %d, got %d", len(test.Logs), len(logs))
                failed = 1
            } else {
                for i, log := range test.Logs {
                    if common.HexToAddress(log.AddressF) != logs[i].Address() {
                        helper.Log.Infof("'%s' log address failed. Expected %v got %x", name, log.AddressF, logs[i].Address())
                        failed = 1
                    }

                    if !bytes.Equal(logs[i].Data(), helper.FromHex(log.DataF)) {
                        helper.Log.Infof("'%s' log data failed. Expected %v got %x", name, log.DataF, logs[i].Data())
                        failed = 1
                    }

                    if len(log.TopicsF) != len(logs[i].Topics()) {
                        helper.Log.Infof("'%s' log topics length failed. Expected %d got %d", name, len(log.TopicsF), logs[i].Topics())
                        failed = 1
                    } else {
                        for j, topic := range log.TopicsF {
                            if common.HexToHash(topic) != logs[i].Topics()[j] {
                                helper.Log.Infof("'%s' log topic[%d] failed. Expected %v got %x", name, j, topic, logs[i].Topics()[j])
                                failed = 1
                            }
                        }
                    }
                    genBloom := common.LeftPadBytes(types.LogsBloom(state.Logs{logs[i]}).Bytes(), 256)

                    if !bytes.Equal(genBloom, common.Hex2Bytes(log.BloomF)) {
                        helper.Log.Infof("'%s' bloom failed.", name)
                        failed = 1
                    }
                }
            }
        }

        if failed == 1 {
            helper.Log.Infoln(string(statedb.Dump()))
        }

        logger.Flush()
    }

    return
}

func main() {
    helper.Logger.SetLogLevel(5)
    vm.Debug = true

    if len(os.Args) > 1 {
        os.Exit(RunVmTest(strings.NewReader(os.Args[1])))
    } else {
        os.Exit(RunVmTest(os.Stdin))
    }
}