aboutsummaryrefslogtreecommitdiffstats
path: root/les/odr_test.go
blob: cf609be882a007b4a0b0b8e5287959bce1bcbbe4 (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
// Copyright 2016 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package les

import (
    "bytes"
    "context"
    "math/big"
    "testing"
    "time"

    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/common/math"
    "github.com/ethereum/go-ethereum/core"
    "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/eth"
    "github.com/ethereum/go-ethereum/ethdb"
    "github.com/ethereum/go-ethereum/light"
    "github.com/ethereum/go-ethereum/params"
    "github.com/ethereum/go-ethereum/rlp"
)

type odrTestFn func(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte

func TestOdrGetBlockLes1(t *testing.T) { testOdr(t, 1, 1, odrGetBlock) }

func TestOdrGetBlockLes2(t *testing.T) { testOdr(t, 2, 1, odrGetBlock) }

func odrGetBlock(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
    var block *types.Block
    if bc != nil {
        block = bc.GetBlockByHash(bhash)
    } else {
        block, _ = lc.GetBlockByHash(ctx, bhash)
    }
    if block == nil {
        return nil
    }
    rlp, _ := rlp.EncodeToBytes(block)
    return rlp
}

func TestOdrGetReceiptsLes1(t *testing.T) { testOdr(t, 1, 1, odrGetReceipts) }

func TestOdrGetReceiptsLes2(t *testing.T) { testOdr(t, 2, 1, odrGetReceipts) }

func odrGetReceipts(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
    var receipts types.Receipts
    if bc != nil {
        receipts = core.GetBlockReceipts(db, bhash, core.GetBlockNumber(db, bhash))
    } else {
        receipts, _ = light.GetBlockReceipts(ctx, lc.Odr(), bhash, core.GetBlockNumber(db, bhash))
    }
    if receipts == nil {
        return nil
    }
    rlp, _ := rlp.EncodeToBytes(receipts)
    return rlp
}

func TestOdrAccountsLes1(t *testing.T) { testOdr(t, 1, 1, odrAccounts) }

func TestOdrAccountsLes2(t *testing.T) { testOdr(t, 2, 1, odrAccounts) }

func odrAccounts(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
    dummyAddr := common.HexToAddress("1234567812345678123456781234567812345678")
    acc := []common.Address{testBankAddress, acc1Addr, acc2Addr, dummyAddr}

    var (
        res []byte
        st  *state.StateDB
        err error
    )
    for _, addr := range acc {
        if bc != nil {
            header := bc.GetHeaderByHash(bhash)
            st, err = state.New(header.Root, state.NewDatabase(db))
        } else {
            header := lc.GetHeaderByHash(bhash)
            st = light.NewState(ctx, header, lc.Odr())
        }
        if err == nil {
            bal := st.GetBalance(addr)
            rlp, _ := rlp.EncodeToBytes(bal)
            res = append(res, rlp...)
        }
    }

    return res
}

func TestOdrContractCallLes1(t *testing.T) { testOdr(t, 1, 2, odrContractCall) }

func TestOdrContractCallLes2(t *testing.T) { testOdr(t, 2, 2, odrContractCall) }

type callmsg struct {
    types.Message
}

func (callmsg) CheckNonce() bool { return false }

func odrContractCall(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
    data := common.Hex2Bytes("60CD26850000000000000000000000000000000000000000000000000000000000000000")

    var res []byte
    for i := 0; i < 3; i++ {
        data[35] = byte(i)
        if bc != nil {
            header := bc.GetHeaderByHash(bhash)
            statedb, err := state.New(header.Root, state.NewDatabase(db))

            if err == nil {
                from := statedb.GetOrNewStateObject(testBankAddress)
                from.SetBalance(math.MaxBig256)

                msg := callmsg{types.NewMessage(from.Address(), &testContractAddr, 0, new(big.Int), 100000, new(big.Int), data, false)}

                context := core.NewEVMContext(msg, header, bc, nil)
                vmenv := vm.NewEVM(context, statedb, config, vm.Config{})

                //vmenv := core.NewEnv(statedb, config, bc, msg, header, vm.Config{})
                gp := new(core.GasPool).AddGas(math.MaxUint64)
                ret, _, _, _ := core.ApplyMessage(vmenv, msg, gp)
                res = append(res, ret...)
            }
        } else {
            header := lc.GetHeaderByHash(bhash)
            state := light.NewState(ctx, header, lc.Odr())
            state.SetBalance(testBankAddress, math.MaxBig256)
            msg := callmsg{types.NewMessage(testBankAddress, &testContractAddr, 0, new(big.Int), 100000, new(big.Int), data, false)}
            context := core.NewEVMContext(msg, header, lc, nil)
            vmenv := vm.NewEVM(context, state, config, vm.Config{})
            gp := new(core.GasPool).AddGas(math.MaxUint64)
            ret, _, _, _ := core.ApplyMessage(vmenv, msg, gp)
            if state.Error() == nil {
                res = append(res, ret...)
            }
        }
    }
    return res
}

func testOdr(t *testing.T, protocol int, expFail uint64, fn odrTestFn) {
    // Assemble the test environment
    peers := newPeerSet()
    dist := newRequestDistributor(peers, make(chan struct{}))
    rm := newRetrieveManager(peers, dist, nil)
    db, _ := ethdb.NewMemDatabase()
    ldb, _ := ethdb.NewMemDatabase()
    odr := NewLesOdr(ldb, light.NewChtIndexer(db, true), light.NewBloomTrieIndexer(db, true), eth.NewBloomIndexer(db, light.BloomTrieFrequency), rm)
    pm := newTestProtocolManagerMust(t, false, 4, testChainGen, nil, nil, db)
    lpm := newTestProtocolManagerMust(t, true, 0, nil, peers, odr, ldb)
    _, err1, lpeer, err2 := newTestPeerPair("peer", protocol, pm, lpm)
    select {
    case <-time.After(time.Millisecond * 100):
    case err := <-err1:
        t.Fatalf("peer 1 handshake error: %v", err)
    case err := <-err2:
        t.Fatalf("peer 1 handshake error: %v", err)
    }

    lpm.synchronise(lpeer)

    test := func(expFail uint64) {
        for i := uint64(0); i <= pm.blockchain.CurrentHeader().Number.Uint64(); i++ {
            bhash := core.GetCanonicalHash(db, i)
            b1 := fn(light.NoOdr, db, pm.chainConfig, pm.blockchain.(*core.BlockChain), nil, bhash)

            ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
            defer cancel()
            b2 := fn(ctx, ldb, lpm.chainConfig, nil, lpm.blockchain.(*light.LightChain), bhash)

            eq := bytes.Equal(b1, b2)
            exp := i < expFail
            if exp && !eq {
                t.Errorf("odr mismatch")
            }
            if !exp && eq {
                t.Errorf("unexpected odr match")
            }
        }
    }

    // temporarily remove peer to test odr fails
    // expect retrievals to fail (except genesis block) without a les peer
    peers.Unregister(lpeer.id)
    time.Sleep(time.Millisecond * 10) // ensure that all peerSetNotify callbacks are executed
    test(expFail)
    // expect all retrievals to pass
    peers.Register(lpeer)
    time.Sleep(time.Millisecond * 10) // ensure that all peerSetNotify callbacks are executed
    lpeer.lock.Lock()
    lpeer.hasBlock = func(common.Hash, uint64) bool { return true }
    lpeer.lock.Unlock()
    test(5)
    // still expect all retrievals to pass, now data should be cached locally
    peers.Unregister(lpeer.id)
    time.Sleep(time.Millisecond * 10) // ensure that all peerSetNotify callbacks are executed
    test(5)
}