aboutsummaryrefslogtreecommitdiffstats
path: root/tests/blocktest.go
blob: 34bd69ac85f0082bec3d07ffb5f3be06df1b974d (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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package tests

import (
    "bytes"
    "encoding/hex"
    "encoding/json"
    "errors"
    "fmt"
    "io/ioutil"
    "math/big"
    "runtime"
    "strconv"
    "strings"

    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/core/types"
    "github.com/ethereum/go-ethereum/rlp"
    "github.com/ethereum/go-ethereum/core/state"
)

// Block Test JSON Format
type btJSON struct {
    Blocks             []btBlock
    GenesisBlockHeader btHeader
    Pre                map[string]btAccount
    PostState          map[string]btAccount
}

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

type btHeader struct {
    Bloom            string
    Coinbase         string
    MixHash          string
    Nonce            string
    Number           string
    ParentHash       string
    ReceiptTrie      string
    SeedHash         string
    StateRoot        string
    TransactionsTrie string
    UncleHash        string

    ExtraData  string
    Difficulty string
    GasLimit   string
    GasUsed    string
    Timestamp  string
}

type btTransaction struct {
    Data     string
    GasLimit string
    GasPrice string
    Nonce    string
    R        string
    S        string
    To       string
    V        string
    Value    string
}

type btBlock struct {
    BlockHeader  *btHeader
    Rlp          string
    Transactions []btTransaction
    UncleHeaders []string
}

type BlockTest struct {
    Genesis *types.Block
    Blocks  []*types.Block

    preAccounts map[string]btAccount
}

// LoadBlockTests loads a block test JSON file.
func LoadBlockTests(file string) (map[string]*BlockTest, error) {
    bt := make(map[string]*btJSON)
    if err := loadJSON(file, &bt); err != nil {
        return nil, err
    }
    out := make(map[string]*BlockTest)
    for name, in := range bt {
        var err error
        if out[name], err = convertTest(in); err != nil {
            return nil, fmt.Errorf("bad test %q: %v", err)
        }
    }
    return out, nil
}

// InsertPreState populates the given database with the genesis
// accounts defined by the test.
func (t *BlockTest) InsertPreState(db common.Database) (*state.StateDB, error) {
    statedb := state.New(common.Hash{}, db)
    for addrString, acct := range t.preAccounts {
        // XXX: is is worth it checking for errors here?
        //addr, _ := hex.DecodeString(addrString)
        code, _ := hex.DecodeString(strings.TrimPrefix(acct.Code, "0x"))
        balance, _ := new(big.Int).SetString(acct.Balance, 0)
        nonce, _ := strconv.ParseUint(acct.Nonce, 16, 64)

        obj := statedb.NewStateObject(common.HexToAddress(addrString))
        obj.SetCode(code)
        obj.SetBalance(balance)
        obj.SetNonce(nonce)
        // for k, v := range acct.Storage {
        //  obj.SetState(k, v)
        // }
    }
    // sync objects to trie
    statedb.Update(nil)
    // sync trie to disk
    statedb.Sync()

    if !bytes.Equal(t.Genesis.Root().Bytes(), statedb.Root().Bytes()) {
        return nil, errors.New("computed state root does not match genesis block")
    }
    return statedb, nil
}

func (t *BlockTest) ValidatePostState(statedb *state.StateDB) error {
    for addrString, acct := range t.preAccounts {
        // XXX: is is worth it checking for errors here?
        addr, _ := hex.DecodeString(addrString)
        code, _ := hex.DecodeString(strings.TrimPrefix(acct.Code, "0x"))
        balance, _ := new(big.Int).SetString(acct.Balance, 0)
        nonce, _ := strconv.ParseUint(acct.Nonce, 16, 64)

        // address is indirectly verified by the other fields, as it's the db key
        code2 := statedb.GetCode(common.BytesToAddress(addr))
        balance2 := statedb.GetBalance(common.BytesToAddress(addr))
        nonce2 := statedb.GetNonce(common.BytesToAddress(addr))
        if !bytes.Equal(code2, code) {
            return fmt.Errorf("account code mismatch, addr, found, expected: ", addrString, hex.EncodeToString(code2), hex.EncodeToString(code))
        }
        if balance2.Cmp(balance) != 0 {
            return fmt.Errorf("account balance mismatch, addr, found, expected: ", addrString, balance2, balance)
        }
        if nonce2 != nonce {
            return fmt.Errorf("account nonce mismatch, addr, found, expected: ", addrString, nonce2, nonce)
        }
    }
    return nil
}

func convertTest(in *btJSON) (out *BlockTest, err error) {
    // the conversion handles errors by catching panics.
    // you might consider this ugly, but the alternative (passing errors)
    // would be much harder to read.
    defer func() {
        if recovered := recover(); recovered != nil {
            buf := make([]byte, 64<<10)
            buf = buf[:runtime.Stack(buf, false)]
            err = fmt.Errorf("%v\n%s", recovered, buf)
        }
    }()
    out = &BlockTest{preAccounts: in.Pre}
    out.Genesis = mustConvertGenesis(in.GenesisBlockHeader)
    out.Blocks = mustConvertBlocks(in.Blocks)
    return out, err
}

func mustConvertGenesis(testGenesis btHeader) *types.Block {
    hdr := mustConvertHeader(testGenesis)
    hdr.Number = big.NewInt(0)
    b := types.NewBlockWithHeader(hdr)
    b.Td = new(big.Int)
    b.Reward = new(big.Int)
    return b
}

func mustConvertHeader(in btHeader) *types.Header {
    // hex decode these fields
    header := &types.Header{
        //SeedHash:    mustConvertBytes(in.SeedHash),
        MixDigest:   mustConvertHash(in.MixHash),
        Bloom:       mustConvertBloom(in.Bloom),
        ReceiptHash: mustConvertHash(in.ReceiptTrie),
        TxHash:      mustConvertHash(in.TransactionsTrie),
        Root:        mustConvertHash(in.StateRoot),
        Coinbase:    mustConvertAddress(in.Coinbase),
        UncleHash:   mustConvertHash(in.UncleHash),
        ParentHash:  mustConvertHash(in.ParentHash),
        Extra:       string(mustConvertBytes(in.ExtraData)),
        GasUsed:     mustConvertBigInt10(in.GasUsed),
        GasLimit:    mustConvertBigInt10(in.GasLimit),
        Difficulty:  mustConvertBigInt10(in.Difficulty),
        Time:        mustConvertUint(in.Timestamp),
    }
    // XXX cheats? :-)
    header.SetNonce(common.BytesToHash(mustConvertBytes(in.Nonce)).Big().Uint64())
    return header
}

func mustConvertBlocks(testBlocks []btBlock) []*types.Block {
    var out []*types.Block
    for i, inb := range testBlocks {
        var b types.Block
        r := bytes.NewReader(mustConvertBytes(inb.Rlp))
        if err := rlp.Decode(r, &b); err != nil {
            panic(fmt.Errorf("invalid block %d: %q", i, inb.Rlp))
        }
        out = append(out, &b)
    }
    return out
}

func mustConvertBytes(in string) []byte {
    out, err := hex.DecodeString(strings.TrimPrefix(in, "0x"))
    if err != nil {
        panic(fmt.Errorf("invalid hex: %q", in))
    }
    return out
}

func mustConvertHash(in string) common.Hash {
    out, err := hex.DecodeString(strings.TrimPrefix(in, "0x"))
    if err != nil {
        panic(fmt.Errorf("invalid hex: %q", in))
    }
    return common.BytesToHash(out)
}

func mustConvertAddress(in string) common.Address {
    out, err := hex.DecodeString(strings.TrimPrefix(in, "0x"))
    if err != nil {
        panic(fmt.Errorf("invalid hex: %q", in))
    }
    return common.BytesToAddress(out)
}

func mustConvertBloom(in string) types.Bloom {
    out, err := hex.DecodeString(strings.TrimPrefix(in, "0x"))
    if err != nil {
        panic(fmt.Errorf("invalid hex: %q", in))
    }
    return types.BytesToBloom(out)
}

func mustConvertBigInt10(in string) *big.Int {
    out, ok := new(big.Int).SetString(in, 10)
    if !ok {
        panic(fmt.Errorf("invalid integer: %q", in))
    }
    return out
}

func mustConvertUint(in string) uint64 {
    out, err := strconv.ParseUint(in, 0, 64)
    if err != nil {
        panic(fmt.Errorf("invalid integer: %q", in))
    }
    return out
}

// loadJSON reads the given file and unmarshals its content.
func loadJSON(file string, val interface{}) error {
    content, err := ioutil.ReadFile(file)
    if err != nil {
        return err
    }
    if err := json.Unmarshal(content, val); err != nil {
        if syntaxerr, ok := err.(*json.SyntaxError); ok {
            line := findLine(content, syntaxerr.Offset)
            return fmt.Errorf("JSON syntax error at %v:%v: %v", file, line, err)
        }
        return fmt.Errorf("JSON unmarshal error in %v: %v", file, err)
    }
    return nil
}

// findLine returns the line number for the given offset into data.
func findLine(data []byte, offset int64) (line int) {
    line = 1
    for i, r := range string(data) {
        if int64(i) >= offset {
            return
        }
        if r == '\n' {
            line++
        }
    }
    return
}