aboutsummaryrefslogtreecommitdiffstats
path: root/swarm/network/stream/peer_test.go
blob: 98c5cc010975126e9f7bb50c9b7bb6801f5c3fc7 (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
// Copyright 2019 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"
    "fmt"
    "reflect"
    "sort"
    "sync"
    "testing"
    "time"

    "github.com/ethereum/go-ethereum/node"
    "github.com/ethereum/go-ethereum/p2p/enode"
    "github.com/ethereum/go-ethereum/p2p/simulations/adapters"
    "github.com/ethereum/go-ethereum/swarm/chunk"
    "github.com/ethereum/go-ethereum/swarm/network"
    "github.com/ethereum/go-ethereum/swarm/network/simulation"
    "github.com/ethereum/go-ethereum/swarm/state"
)

// TestSyncSubscriptionsDiff validates the output of syncSubscriptionsDiff
// function for various arguments.
func TestSyncSubscriptionsDiff(t *testing.T) {
    max := network.NewKadParams().MaxProxDisplay
    for _, tc := range []struct {
        po, prevDepth, newDepth int
        subBins, quitBins       []int
    }{
        {
            po: 0, prevDepth: -1, newDepth: 0,
            subBins: []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
        },
        {
            po: 1, prevDepth: -1, newDepth: 0,
            subBins: []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
        },
        {
            po: 2, prevDepth: -1, newDepth: 0,
            subBins: []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
        },
        {
            po: 0, prevDepth: -1, newDepth: 1,
            subBins: []int{0},
        },
        {
            po: 1, prevDepth: -1, newDepth: 1,
            subBins: []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
        },
        {
            po: 2, prevDepth: -1, newDepth: 2,
            subBins: []int{2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
        },
        {
            po: 3, prevDepth: -1, newDepth: 2,
            subBins: []int{2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
        },
        {
            po: 1, prevDepth: -1, newDepth: 2,
            subBins: []int{1},
        },
        {
            po: 0, prevDepth: 0, newDepth: 0, // 0-16 -> 0-16
        },
        {
            po: 1, prevDepth: 0, newDepth: 0, // 0-16 -> 0-16
        },
        {
            po: 0, prevDepth: 0, newDepth: 1, // 0-16 -> 0
            quitBins: []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
        },
        {
            po: 0, prevDepth: 0, newDepth: 2, // 0-16 -> 0
            quitBins: []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
        },
        {
            po: 1, prevDepth: 0, newDepth: 1, // 0-16 -> 1-16
            quitBins: []int{0},
        },
        {
            po: 1, prevDepth: 1, newDepth: 0, // 1-16 -> 0-16
            subBins: []int{0},
        },
        {
            po: 4, prevDepth: 0, newDepth: 1, // 0-16 -> 1-16
            quitBins: []int{0},
        },
        {
            po: 4, prevDepth: 0, newDepth: 4, // 0-16 -> 4-16
            quitBins: []int{0, 1, 2, 3},
        },
        {
            po: 4, prevDepth: 0, newDepth: 5, // 0-16 -> 4
            quitBins: []int{0, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
        },
        {
            po: 4, prevDepth: 5, newDepth: 0, // 4 -> 0-16
            subBins: []int{0, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
        },
        {
            po: 4, prevDepth: 5, newDepth: 6, // 4 -> 4
        },
    } {
        subBins, quitBins := syncSubscriptionsDiff(tc.po, tc.prevDepth, tc.newDepth, max)
        if fmt.Sprint(subBins) != fmt.Sprint(tc.subBins) {
            t.Errorf("po: %v, prevDepth: %v, newDepth: %v: got subBins %v, want %v", tc.po, tc.prevDepth, tc.newDepth, subBins, tc.subBins)
        }
        if fmt.Sprint(quitBins) != fmt.Sprint(tc.quitBins) {
            t.Errorf("po: %v, prevDepth: %v, newDepth: %v: got quitBins %v, want %v", tc.po, tc.prevDepth, tc.newDepth, quitBins, tc.quitBins)
        }
    }
}

// TestUpdateSyncingSubscriptions validates that syncing subscriptions are correctly
// made on initial node connections and that subscriptions are correctly changed
// when kademlia neighbourhood depth is changed by connecting more nodes.
func TestUpdateSyncingSubscriptions(t *testing.T) {
    sim := simulation.New(map[string]simulation.ServiceFunc{
        "streamer": func(ctx *adapters.ServiceContext, bucket *sync.Map) (s node.Service, cleanup func(), err 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{
                SyncUpdateDelay: 100 * time.Millisecond,
                Syncing:         SyncingAutoSubscribe,
            }, nil)
            cleanup = func() {
                r.Close()
                clean()
            }
            bucket.Store("bzz-address", addr)
            return r, cleanup, nil
        },
    })
    defer sim.Close()

    ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
    defer cancel()

    result := sim.Run(ctx, func(ctx context.Context, sim *simulation.Simulation) (err error) {
        // initial nodes, first one as pivot center of the start
        ids, err := sim.AddNodesAndConnectStar(10)
        if err != nil {
            return err
        }

        // pivot values
        pivotRegistryID := ids[0]
        pivotRegistry := sim.Service("streamer", pivotRegistryID).(*Registry)
        pivotKademlia := pivotRegistry.delivery.kad
        // nodes proximities from the pivot node
        nodeProximities := make(map[string]int)
        for _, id := range ids[1:] {
            bzzAddr, ok := sim.NodeItem(id, "bzz-address")
            if !ok {
                t.Fatal("no bzz address for node")
            }
            nodeProximities[id.String()] = chunk.Proximity(pivotKademlia.BaseAddr(), bzzAddr.(*network.BzzAddr).Over())
        }
        // wait until sync subscriptions are done for all nodes
        waitForSubscriptions(t, pivotRegistry, ids[1:]...)

        // check initial sync streams
        err = checkSyncStreamsWithRetry(pivotRegistry, nodeProximities)
        if err != nil {
            return err
        }

        // add more nodes until the depth is changed
        prevDepth := pivotKademlia.NeighbourhoodDepth()
        var noDepthChangeChecked bool // true it there was a check when no depth is changed
        for {
            ids, err := sim.AddNodes(5)
            if err != nil {
                return err
            }
            // add new nodes to sync subscriptions check
            for _, id := range ids {
                bzzAddr, ok := sim.NodeItem(id, "bzz-address")
                if !ok {
                    t.Fatal("no bzz address for node")
                }
                nodeProximities[id.String()] = chunk.Proximity(pivotKademlia.BaseAddr(), bzzAddr.(*network.BzzAddr).Over())
            }
            err = sim.Net.ConnectNodesStar(ids, pivotRegistryID)
            if err != nil {
                return err
            }
            waitForSubscriptions(t, pivotRegistry, ids...)

            newDepth := pivotKademlia.NeighbourhoodDepth()
            // depth is not changed, check if streams are still correct
            if newDepth == prevDepth {
                err = checkSyncStreamsWithRetry(pivotRegistry, nodeProximities)
                if err != nil {
                    return err
                }
                noDepthChangeChecked = true
            }
            // do the final check when depth is changed and
            // there has been at least one check
            // for the case when depth is not changed
            if newDepth != prevDepth && noDepthChangeChecked {
                // check sync streams for changed depth
                return checkSyncStreamsWithRetry(pivotRegistry, nodeProximities)
            }
            prevDepth = newDepth
        }
    })
    if result.Error != nil {
        t.Fatal(result.Error)
    }
}

// waitForSubscriptions is a test helper function that blocks until
// stream server subscriptions are established on the provided registry
// to the nodes with provided IDs.
func waitForSubscriptions(t *testing.T, r *Registry, ids ...enode.ID) {
    t.Helper()

    for retries := 0; retries < 100; retries++ {
        subs := r.api.GetPeerServerSubscriptions()
        if allSubscribed(subs, ids) {
            return
        }
        time.Sleep(50 * time.Millisecond)
    }
    t.Fatalf("missing subscriptions")
}

// allSubscribed returns true if nodes with ids have subscriptions
// in provided subs map.
func allSubscribed(subs map[string][]string, ids []enode.ID) bool {
    for _, id := range ids {
        if s, ok := subs[id.String()]; !ok || len(s) == 0 {
            return false
        }
    }
    return true
}

// checkSyncStreamsWithRetry is calling checkSyncStreams with retries.
func checkSyncStreamsWithRetry(r *Registry, nodeProximities map[string]int) (err error) {
    for retries := 0; retries < 5; retries++ {
        err = checkSyncStreams(r, nodeProximities)
        if err == nil {
            return nil
        }
        time.Sleep(500 * time.Millisecond)
    }
    return err
}

// checkSyncStreams validates that registry contains expected sync
// subscriptions to nodes with proximities in a map nodeProximities.
func checkSyncStreams(r *Registry, nodeProximities map[string]int) error {
    depth := r.delivery.kad.NeighbourhoodDepth()
    maxPO := r.delivery.kad.MaxProxDisplay
    for id, po := range nodeProximities {
        wantStreams := syncStreams(po, depth, maxPO)
        gotStreams := nodeStreams(r, id)

        if r.getPeer(enode.HexID(id)) == nil {
            // ignore removed peer
            continue
        }

        if !reflect.DeepEqual(gotStreams, wantStreams) {
            return fmt.Errorf("node %s got streams %v, want %v", id, gotStreams, wantStreams)
        }
    }
    return nil
}

// syncStreams returns expected sync streams that need to be
// established between a node with kademlia neighbourhood depth
// and a node with proximity order po.
func syncStreams(po, depth, maxPO int) (streams []string) {
    start, end := syncBins(po, depth, maxPO)
    for bin := start; bin < end; bin++ {
        streams = append(streams, NewStream("SYNC", FormatSyncBinKey(uint8(bin)), false).String())
        streams = append(streams, NewStream("SYNC", FormatSyncBinKey(uint8(bin)), true).String())
    }
    return streams
}

// nodeStreams returns stream server subscriptions on a registry
// to the peer with provided id.
func nodeStreams(r *Registry, id string) []string {
    streams := r.api.GetPeerServerSubscriptions()[id]
    sort.Strings(streams)
    return streams
}