-
Notifications
You must be signed in to change notification settings - Fork 384
/
testing.go
533 lines (422 loc) · 13 KB
/
testing.go
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
package bertyprotocol
import (
"context"
"crypto/ed25519"
crand "crypto/rand"
"fmt"
"net"
"testing"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpc_zap "github.com/grpc-ecosystem/go-grpc-middleware/logging/zap"
grpc_ctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags"
grpcgw "github.com/grpc-ecosystem/grpc-gateway/runtime"
datastore "github.com/ipfs/go-datastore"
ds_sync "github.com/ipfs/go-datastore/sync"
keystore "github.com/ipfs/go-ipfs-keystore"
"github.com/libp2p/go-libp2p-core/crypto"
"github.com/libp2p/go-libp2p-core/peer"
libp2p_mocknet "github.com/libp2p/go-libp2p/p2p/net/mock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
"golang.org/x/crypto/nacl/box"
"google.golang.org/grpc"
"berty.tech/berty/v2/go/internal/cryptoutil"
"berty.tech/berty/v2/go/internal/datastoreutil"
"berty.tech/berty/v2/go/internal/ipfsutil"
"berty.tech/berty/v2/go/pkg/pushtypes"
orbitdb "berty.tech/go-orbit-db"
"berty.tech/go-orbit-db/pubsub/pubsubraw"
)
type mockedPeer struct {
CoreAPI ipfsutil.CoreAPIMock
DB *BertyOrbitDB
GC *GroupContext
MKS *cryptoutil.MessageKeystore
DevKS cryptoutil.DeviceKeystore
}
func (m *mockedPeer) PeerInfo() peer.AddrInfo {
return m.CoreAPI.MockNode().Peerstore.PeerInfo(m.CoreAPI.MockNode().Identity)
}
type TestingProtocol struct {
Opts *Opts
Service Service
Client Client
}
type TestingReplicationPeer struct {
Service ReplicationService
}
type TestingOpts struct {
Logger *zap.Logger
Mocknet libp2p_mocknet.Mocknet
RDVPeer peer.AddrInfo
DeviceKeystore cryptoutil.DeviceKeystore
CoreAPIMock ipfsutil.CoreAPIMock
OrbitDB *BertyOrbitDB
ConnectFunc ConnectTestingProtocolFunc
PushSK *[32]byte
}
func NewTestingProtocol(ctx context.Context, t *testing.T, opts *TestingOpts, ds datastore.Batching) (*TestingProtocol, func()) {
if opts == nil {
opts = &TestingOpts{}
}
opts.applyDefaults(ctx)
if ds == nil {
ds = ds_sync.MutexWrap(datastore.NewMapDatastore())
}
ipfsopts := &ipfsutil.TestingAPIOpts{
Logger: opts.Logger,
Mocknet: opts.Mocknet,
RDVPeer: opts.RDVPeer,
Datastore: ds,
}
node := opts.CoreAPIMock
cleanupNode := func() {}
if node == nil {
node, cleanupNode = ipfsutil.TestingCoreAPIUsingMockNet(ctx, t, ipfsopts)
}
deviceKeystore := opts.DeviceKeystore
if deviceKeystore == nil {
deviceKeystore = cryptoutil.NewDeviceKeystore(ipfsutil.NewDatastoreKeystore(datastoreutil.NewNamespacedDatastore(ds, datastore.NewKey(NamespaceDeviceKeystore))))
}
odb := opts.OrbitDB
if odb == nil {
var err error
odb, err = NewBertyOrbitDB(ctx, node.API(), &NewOrbitDBOptions{
NewOrbitDBOptions: orbitdb.NewOrbitDBOptions{
PubSub: pubsubraw.NewPubSub(node.PubSub(), node.MockNode().PeerHost.ID(), opts.Logger, nil),
Logger: opts.Logger,
},
Datastore: ds,
DeviceKeystore: deviceKeystore,
})
require.NoError(t, err)
}
serviceOpts := Opts{
Host: node.MockNode().PeerHost,
PubSub: node.PubSub(),
Logger: opts.Logger,
RootDatastore: ds,
DeviceKeystore: deviceKeystore,
IpfsCoreAPI: node.API(),
OrbitDB: odb,
TinderDriver: node.Tinder(),
PushKey: opts.PushSK,
}
service, cleanupService := TestingService(ctx, t, serviceOpts)
// setup client
grpcLogger := opts.Logger.Named("grpc")
zapOpts := []grpc_zap.Option{}
serverOpts := []grpc.ServerOption{
grpc_middleware.WithUnaryServerChain(
grpc_ctxtags.UnaryServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),
grpc_zap.UnaryServerInterceptor(grpcLogger, zapOpts...),
),
grpc_middleware.WithStreamServerChain(
grpc_ctxtags.StreamServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),
grpc_zap.StreamServerInterceptor(grpcLogger, zapOpts...),
),
}
clientOpts := []grpc.DialOption{
grpc.WithChainUnaryInterceptor(),
grpc.WithChainStreamInterceptor(),
}
server := grpc.NewServer(serverOpts...)
client, cleanupClient := TestingClientFromServer(ctx, t, server, service, clientOpts...)
tp := &TestingProtocol{
Opts: &serviceOpts,
Client: client,
Service: service,
}
cleanup := func() {
server.Stop()
cleanupClient()
cleanupService()
cleanupNode()
}
return tp, cleanup
}
func (opts *TestingOpts) applyDefaults(ctx context.Context) {
if opts.Logger == nil {
opts.Logger = zap.NewNop()
}
if opts.Mocknet == nil {
opts.Mocknet = libp2p_mocknet.New(ctx)
}
if opts.ConnectFunc == nil {
opts.ConnectFunc = ConnectAll
}
}
func testHelperNewReplicationService(ctx context.Context, t *testing.T, logger *zap.Logger, mn libp2p_mocknet.Mocknet, rdvp peer.AddrInfo, ds datastore.Batching) (*replicationService, context.CancelFunc) {
t.Helper()
if ds == nil {
ds = ds_sync.MutexWrap(datastore.NewMapDatastore())
}
api, cleanup := ipfsutil.TestingCoreAPIUsingMockNet(ctx, t, &ipfsutil.TestingAPIOpts{
Logger: logger,
Mocknet: mn,
RDVPeer: rdvp,
Datastore: ds,
})
odb, err := NewBertyOrbitDB(ctx, api.API(), &NewOrbitDBOptions{
NewOrbitDBOptions: orbitdb.NewOrbitDBOptions{
Logger: logger,
Cache: NewOrbitDatastoreCache(ds),
},
})
require.NoError(t, err)
repl, err := NewReplicationService(ctx, ds, odb, logger)
require.NoError(t, err)
require.NotNil(t, repl)
svc, ok := repl.(*replicationService)
require.True(t, ok)
return svc, cleanup
}
func NewReplicationMockedPeer(ctx context.Context, t *testing.T, secret []byte, sk ed25519.PublicKey, opts *TestingOpts) (*TestingReplicationPeer, func()) {
// TODO: handle auth
_ = secret
_ = sk
replServ, cleanupReplMan := testHelperNewReplicationService(ctx, t, nil, opts.Mocknet, opts.RDVPeer, nil)
return &TestingReplicationPeer{
Service: replServ,
}, func() {
cleanupReplMan()
}
}
func NewTestingProtocolWithMockedPeers(ctx context.Context, t *testing.T, opts *TestingOpts, ds datastore.Batching, amount int) ([]*TestingProtocol, func()) {
t.Helper()
opts.applyDefaults(ctx)
logger := opts.Logger
if ds == nil {
ds = ds_sync.MutexWrap(datastore.NewMapDatastore())
}
cleanupRDVP := func() {}
closeRDVP := func() error { return nil }
if opts.RDVPeer.ID == "" {
rdvpeer, err := opts.Mocknet.GenPeer()
require.NoError(t, err)
require.NotNil(t, rdvpeer)
_, cleanupRDVP = ipfsutil.TestingRDVP(ctx, t, rdvpeer)
closeRDVP = rdvpeer.Close
opts.RDVPeer = rdvpeer.Peerstore().PeerInfo(rdvpeer.ID())
}
rdvpnet := opts.Mocknet.Net(opts.RDVPeer.ID)
require.NotNil(t, rdvpnet)
cls := make([]func(), amount)
tps := make([]*TestingProtocol, amount)
for i := range tps {
svcName := fmt.Sprintf("mock%d", i)
opts.Logger = logger.Named(svcName)
ds := datastoreutil.NewNamespacedDatastore(ds, datastore.NewKey(fmt.Sprintf("%d", i)))
tps[i], cls[i] = NewTestingProtocol(ctx, t, opts, ds)
}
opts.ConnectFunc(t, opts.Mocknet)
for _, net := range opts.Mocknet.Nets() {
if net != rdvpnet {
_, err := opts.Mocknet.LinkNets(net, rdvpnet)
assert.NoError(t, err)
_, err = opts.Mocknet.ConnectNets(net, rdvpnet)
assert.NoError(t, err)
}
}
cleanup := func() {
for i := range cls {
cls[i]()
}
cleanupRDVP()
rdvpnet.Close()
closeRDVP()
}
return tps, cleanup
}
// TestingService returns a configured Client struct with in-memory contexts.
func TestingService(ctx context.Context, t *testing.T, opts Opts) (Service, func()) {
t.Helper()
if opts.Logger == nil {
opts.Logger = zap.NewNop()
}
cleanupNode := func() {}
if opts.IpfsCoreAPI == nil {
var mn ipfsutil.CoreAPIMock
mn, cleanupNode = ipfsutil.TestingCoreAPI(ctx, t)
opts.IpfsCoreAPI = mn.API()
}
service, err := New(ctx, opts)
if err != nil {
t.Fatalf("failed to initialize client: %v", err)
}
cleanup := func() {
service.Close()
cleanupNode()
}
return service, cleanup
}
func TestingClientFromServer(ctx context.Context, t *testing.T, s *grpc.Server, svc Service, dialOpts ...grpc.DialOption) (client Client, cleanup func()) {
t.Helper()
var err error
client, err = NewClientFromServer(ctx, s, svc, dialOpts...)
require.NoError(t, err)
cleanup = func() {
client.Close()
}
return
}
func TestingClient(ctx context.Context, t *testing.T, svc Service, clientOpts []grpc.DialOption, serverOpts []grpc.ServerOption) (client Client, cleanup func()) {
t.Helper()
var err error
client, err = NewClient(ctx, svc, clientOpts, serverOpts)
require.NoError(t, err)
cleanup = func() { client.Close() }
return
}
// Connect Peers Helper
type ConnectTestingProtocolFunc func(*testing.T, libp2p_mocknet.Mocknet)
// ConnectAll peers between themselves
func ConnectAll(t *testing.T, m libp2p_mocknet.Mocknet) {
t.Helper()
err := m.LinkAll()
require.NoError(t, err)
err = m.ConnectAllButSelf()
require.NoError(t, err)
}
// ConnectInLine, connect peers one by one in order to make a straight line:
// ┌───┐ ┌───┐ ┌───┐ ┌───┐
// │ 1 │───▶│ 2 │───▶│ 3 │─ ─ ─ ─ ▶│ x │
// └───┘ └───┘ └───┘ └───┘
func ConnectInLine(t *testing.T, m libp2p_mocknet.Mocknet) {
t.Helper()
peers := m.Peers()
for i := 0; i < len(peers)-1; i++ {
_, err := m.LinkPeers(peers[i], peers[i+1])
require.NoError(t, err)
_, err = m.ConnectPeers(peers[i], peers[i+1])
require.NoError(t, err)
}
}
func PushServerForTests(ctx context.Context, t testing.TB, dispatchers []PushDispatcher, logger *zap.Logger) (PushService, *[32]byte, string, context.CancelFunc) {
secret := make([]byte, cryptoutil.KeySize)
_, err := crand.Read(secret)
require.NoError(t, err)
pushPK, pushSK, err := box.GenerateKey(crand.Reader)
require.NoError(t, err)
pushService, err := NewPushService(pushSK, dispatchers, logger)
require.NoError(t, err)
ctx, cancel := context.WithCancel(ctx)
server := grpc.NewServer()
mux := grpcgw.NewServeMux()
pushtypes.RegisterPushServiceServer(server, pushService)
err = pushtypes.RegisterPushServiceHandlerServer(ctx, mux, pushService)
require.NoError(t, err)
l, err := net.Listen("tcp", "127.0.0.1:0")
require.NoError(t, err)
go func() {
err := server.Serve(l)
if err != nil {
cancel()
}
}()
return pushService, pushPK, l.Addr().String(), cancel
}
func CreatePeersWithGroupTest(ctx context.Context, t testing.TB, pathBase string, memberCount int, deviceCount int) ([]*mockedPeer, crypto.PrivKey, func()) {
t.Helper()
var devKS cryptoutil.DeviceKeystore
mockedPeers := make([]*mockedPeer, memberCount*deviceCount)
g, groupSK, err := NewGroupMultiMember()
if err != nil {
t.Fatal(err)
}
mn := libp2p_mocknet.New(ctx)
rdvp, err := mn.GenPeer()
require.NoError(t, err, "failed to generate mocked peer")
_, cleanuprdvp := ipfsutil.TestingRDVP(ctx, t, rdvp)
ipfsopts := ipfsutil.TestingAPIOpts{
Mocknet: mn,
RDVPeer: rdvp.Peerstore().PeerInfo(rdvp.ID()),
}
deviceIndex := 0
cls := make([]func(), memberCount)
for i := 0; i < memberCount; i++ {
for j := 0; j < deviceCount; j++ {
ca, cleanupNode := ipfsutil.TestingCoreAPIUsingMockNet(ctx, t, &ipfsopts)
if j == 0 {
devKS = cryptoutil.NewDeviceKeystore(keystore.NewMemKeystore())
} else {
accSK, err := devKS.AccountPrivKey()
require.NoError(t, err, "deviceKeystore private key")
accProofSK, err := devKS.AccountProofPrivKey()
require.NoError(t, err, "deviceKeystore private proof key")
devKS, err = cryptoutil.NewWithExistingKeys(keystore.NewMemKeystore(), accSK, accProofSK)
require.NoError(t, err, "deviceKeystore from existing keys")
}
mk, cleanupMessageKeystore := cryptoutil.NewInMemMessageKeystore()
db, err := NewBertyOrbitDB(ctx, ca.API(), &NewOrbitDBOptions{
DeviceKeystore: devKS,
MessageKeystore: mk,
})
if err != nil {
t.Fatal(err)
}
gc, err := db.openGroup(ctx, g, nil)
if err != nil {
t.Fatalf("err: creating new group context, %v", err)
}
mp := &mockedPeer{
CoreAPI: ca,
DB: db,
GC: gc,
MKS: mk,
DevKS: devKS,
}
// setup cleanup
cls[i] = func() {
if ms := mp.GC.MetadataStore(); ms != nil {
err := ms.Drop()
assert.NoError(t, err)
}
if db := mp.DB; db != nil {
err := db.Close()
assert.NoError(t, err)
}
cleanupNode()
cleanupMessageKeystore()
}
mockedPeers[deviceIndex] = mp
deviceIndex++
}
}
connectPeers(ctx, t, ipfsopts.Mocknet)
return mockedPeers, groupSK, func() {
for _, cleanup := range cls {
cleanup()
}
cleanuprdvp()
_ = rdvp.Close()
}
}
func connectPeers(ctx context.Context, t testing.TB, mn libp2p_mocknet.Mocknet) {
t.Helper()
err := mn.LinkAll()
require.NoError(t, err)
err = mn.ConnectAllButSelf()
require.NoError(t, err)
}
func dropPeers(t *testing.T, mockedPeers []*mockedPeer) {
t.Helper()
for _, m := range mockedPeers {
if ms := m.GC.MetadataStore(); ms != nil {
if err := ms.Drop(); err != nil {
t.Fatal(err)
}
}
if db := m.DB; db != nil {
if err := db.Close(); err != nil {
t.Fatal(err)
}
}
if ca := m.CoreAPI; ca != nil {
if err := ca.MockNode().Close(); err != nil {
t.Fatal(err)
}
}
}
}