aboutsummaryrefslogtreecommitdiffstats
path: root/swarm/network/stream/intervals_test.go
blob: c72311a5927d17f466014d56a7c1a56aeb644590 (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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
// Copyright 2018 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 stream

import (
    "context"
    "encoding/binary"
    "errors"
    "fmt"
    "sync"
    "testing"
    "time"

    "github.com/dexon-foundation/dexon/log"
    "github.com/dexon-foundation/dexon/node"
    "github.com/dexon-foundation/dexon/p2p/enode"
    "github.com/dexon-foundation/dexon/p2p/simulations/adapters"
    "github.com/dexon-foundation/dexon/swarm/network/simulation"
    "github.com/dexon-foundation/dexon/swarm/state"
    "github.com/dexon-foundation/dexon/swarm/storage"
    "github.com/dexon-foundation/dexon/swarm/testutil"
)

func TestIntervalsLive(t *testing.T) {
    testIntervals(t, true, nil, false)
    testIntervals(t, true, nil, true)
}

func TestIntervalsHistory(t *testing.T) {
    testIntervals(t, false, NewRange(9, 26), false)
    testIntervals(t, false, NewRange(9, 26), true)
}

func TestIntervalsLiveAndHistory(t *testing.T) {
    testIntervals(t, true, NewRange(9, 26), false)
    testIntervals(t, true, NewRange(9, 26), true)
}

func testIntervals(t *testing.T, live bool, history *Range, skipCheck bool) {

    nodes := 2
    chunkCount := dataChunkCount
    externalStreamName := "externalStream"
    externalStreamSessionAt := uint64(50)
    externalStreamMaxKeys := uint64(100)

    sim := simulation.New(map[string]simulation.ServiceFunc{
        "intervalsStreamer": func(ctx *adapters.ServiceContext, bucket *sync.Map) (node.Service, func(), error) {
            addr, netStore, delivery, clean, err := newNetStoreAndDelivery(ctx, bucket)
            if err != nil {
                return nil, nil, err
            }

            r := NewRegistry(addr.ID(), delivery, netStore, state.NewInmemoryStore(), &RegistryOptions{
                Retrieval: RetrievalDisabled,
                Syncing:   SyncingRegisterOnly,
                SkipCheck: skipCheck,
            }, nil)
            bucket.Store(bucketKeyRegistry, r)

            r.RegisterClientFunc(externalStreamName, func(p *Peer, t string, live bool) (Client, error) {
                return newTestExternalClient(netStore), nil
            })
            r.RegisterServerFunc(externalStreamName, func(p *Peer, t string, live bool) (Server, error) {
                return newTestExternalServer(t, externalStreamSessionAt, externalStreamMaxKeys, nil), nil
            })

            cleanup := func() {
                r.Close()
                clean()
            }

            return r, cleanup, nil
        },
    })
    defer sim.Close()

    log.Info("Adding nodes to simulation")
    _, err := sim.AddNodesAndConnectChain(nodes)
    if err != nil {
        t.Fatal(err)
    }

    ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
    defer cancel()

    if _, err := sim.WaitTillHealthy(ctx); err != nil {
        t.Fatal(err)
    }

    result := sim.Run(ctx, func(ctx context.Context, sim *simulation.Simulation) (err error) {
        nodeIDs := sim.UpNodeIDs()
        storer := nodeIDs[0]
        checker := nodeIDs[1]

        item, ok := sim.NodeItem(storer, bucketKeyFileStore)
        if !ok {
            return fmt.Errorf("No filestore")
        }
        fileStore := item.(*storage.FileStore)

        size := chunkCount * chunkSize

        _, wait, err := fileStore.Store(ctx, testutil.RandomReader(1, size), int64(size), false)
        if err != nil {
            return fmt.Errorf("store: %v", err)
        }
        err = wait(ctx)
        if err != nil {
            return fmt.Errorf("wait store: %v", err)
        }

        item, ok = sim.NodeItem(checker, bucketKeyRegistry)
        if !ok {
            return fmt.Errorf("No registry")
        }
        registry := item.(*Registry)

        liveErrC := make(chan error)
        historyErrC := make(chan error)

        err = registry.Subscribe(storer, NewStream(externalStreamName, "", live), history, Top)
        if err != nil {
            return err
        }

        disconnected := watchDisconnections(ctx, sim)
        defer func() {
            if err != nil && disconnected.bool() {
                err = errors.New("disconnect events received")
            }
        }()

        go func() {
            if !live {
                close(liveErrC)
                return
            }

            var err error
            defer func() {
                liveErrC <- err
            }()

            // live stream
            var liveHashesChan chan []byte
            liveHashesChan, err = getHashes(ctx, registry, storer, NewStream(externalStreamName, "", true))
            if err != nil {
                log.Error("get hashes", "err", err)
                return
            }
            i := externalStreamSessionAt

            // we have subscribed, enable notifications
            err = enableNotifications(registry, storer, NewStream(externalStreamName, "", true))
            if err != nil {
                return
            }

            for {
                select {
                case hash := <-liveHashesChan:
                    h := binary.BigEndian.Uint64(hash)
                    if h != i {
                        err = fmt.Errorf("expected live hash %d, got %d", i, h)
                        return
                    }
                    i++
                    if i > externalStreamMaxKeys {
                        return
                    }
                case <-ctx.Done():
                    return
                }
            }
        }()

        go func() {
            if live && history == nil {
                close(historyErrC)
                return
            }

            var err error
            defer func() {
                historyErrC <- err
            }()

            // history stream
            var historyHashesChan chan []byte
            historyHashesChan, err = getHashes(ctx, registry, storer, NewStream(externalStreamName, "", false))
            if err != nil {
                log.Error("get hashes", "err", err)
                return
            }

            var i uint64
            historyTo := externalStreamMaxKeys
            if history != nil {
                i = history.From
                if history.To != 0 {
                    historyTo = history.To
                }
            }

            // we have subscribed, enable notifications
            err = enableNotifications(registry, storer, NewStream(externalStreamName, "", false))
            if err != nil {
                return
            }

            for {
                select {
                case hash := <-historyHashesChan:
                    h := binary.BigEndian.Uint64(hash)
                    if h != i {
                        err = fmt.Errorf("expected history hash %d, got %d", i, h)
                        return
                    }
                    i++
                    if i > historyTo {
                        return
                    }
                case <-ctx.Done():
                    return
                }
            }
        }()

        if err := <-liveErrC; err != nil {
            return err
        }
        if err := <-historyErrC; err != nil {
            return err
        }

        return nil
    })

    if result.Error != nil {
        t.Fatal(result.Error)
    }
}

func getHashes(ctx context.Context, r *Registry, peerID enode.ID, s Stream) (chan []byte, error) {
    peer := r.getPeer(peerID)

    client, err := peer.getClient(ctx, s)
    if err != nil {
        return nil, err
    }

    c := client.Client.(*testExternalClient)

    return c.hashes, nil
}

func enableNotifications(r *Registry, peerID enode.ID, s Stream) error {
    peer := r.getPeer(peerID)

    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()

    client, err := peer.getClient(ctx, s)
    if err != nil {
        return err
    }

    close(client.Client.(*testExternalClient).enableNotificationsC)

    return nil
}

type testExternalClient struct {
    hashes               chan []byte
    store                storage.SyncChunkStore
    enableNotificationsC chan struct{}
}

func newTestExternalClient(store storage.SyncChunkStore) *testExternalClient {
    return &testExternalClient{
        hashes:               make(chan []byte),
        store:                store,
        enableNotificationsC: make(chan struct{}),
    }
}

func (c *testExternalClient) NeedData(ctx context.Context, hash []byte) func(context.Context) error {
    wait := c.store.FetchFunc(ctx, storage.Address(hash))
    if wait == nil {
        return nil
    }
    select {
    case c.hashes <- hash:
    case <-ctx.Done():
        log.Warn("testExternalClient NeedData context", "err", ctx.Err())
        return func(_ context.Context) error {
            return ctx.Err()
        }
    }
    return wait
}

func (c *testExternalClient) BatchDone(Stream, uint64, []byte, []byte) func() (*TakeoverProof, error) {
    return nil
}

func (c *testExternalClient) Close() {}

type testExternalServer struct {
    t         string
    keyFunc   func(key []byte, index uint64)
    sessionAt uint64
    maxKeys   uint64
}

func newTestExternalServer(t string, sessionAt, maxKeys uint64, keyFunc func(key []byte, index uint64)) *testExternalServer {
    if keyFunc == nil {
        keyFunc = binary.BigEndian.PutUint64
    }
    return &testExternalServer{
        t:         t,
        keyFunc:   keyFunc,
        sessionAt: sessionAt,
        maxKeys:   maxKeys,
    }
}

func (s *testExternalServer) SessionIndex() (uint64, error) {
    return s.sessionAt, nil
}

func (s *testExternalServer) SetNextBatch(from uint64, to uint64) ([]byte, uint64, uint64, *HandoverProof, error) {
    if to > s.maxKeys {
        to = s.maxKeys
    }
    b := make([]byte, HashSize*(to-from+1))
    for i := from; i <= to; i++ {
        s.keyFunc(b[(i-from)*HashSize:(i-from+1)*HashSize], i)
    }
    return b, from, to, nil, nil
}

func (s *testExternalServer) GetData(context.Context, []byte) ([]byte, error) {
    return make([]byte, 4096), nil
}

func (s *testExternalServer) Close() {}