forked from ipfs/go-bitswap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bitswap_test.go
830 lines (682 loc) · 21.7 KB
/
bitswap_test.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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
package bitswap_test
import (
"bytes"
"context"
"fmt"
"os"
"sync"
"testing"
"time"
"github.com/ipfs/go-bitswap"
bsmsg "github.com/ipfs/go-bitswap/message"
"github.com/ipfs/go-bitswap/server"
testinstance "github.com/ipfs/go-bitswap/testinstance"
tn "github.com/ipfs/go-bitswap/testnet"
blocks "github.com/ipfs/go-block-format"
cid "github.com/ipfs/go-cid"
detectrace "github.com/ipfs/go-detect-race"
blocksutil "github.com/ipfs/go-ipfs-blocksutil"
delay "github.com/ipfs/go-ipfs-delay"
mockrouting "github.com/ipfs/go-ipfs-routing/mock"
ipld "github.com/ipfs/go-ipld-format"
peer "github.com/libp2p/go-libp2p-core/peer"
p2ptestutil "github.com/libp2p/go-libp2p-netutil"
tu "github.com/libp2p/go-libp2p-testing/etc"
)
func isCI() bool {
// https://github.blog/changelog/2020-04-15-github-actions-sets-the-ci-environment-variable-to-true/
return os.Getenv("CI") != ""
}
func addBlock(t *testing.T, ctx context.Context, inst testinstance.Instance, blk blocks.Block) {
t.Helper()
err := inst.Blockstore().Put(ctx, blk)
if err != nil {
t.Fatal(err)
}
err = inst.Exchange.NotifyNewBlocks(ctx, blk)
if err != nil {
t.Fatal(err)
}
}
// FIXME the tests are really sensitive to the network delay. fix them to work
// well under varying conditions
const kNetworkDelay = 0 * time.Millisecond
func TestClose(t *testing.T) {
vnet := tn.VirtualNetwork(mockrouting.NewServer(), delay.Fixed(kNetworkDelay))
ig := testinstance.NewTestInstanceGenerator(vnet, nil, nil)
defer ig.Close()
bgen := blocksutil.NewBlockGenerator()
block := bgen.Next()
bitswap := ig.Next()
bitswap.Exchange.Close()
_, err := bitswap.Exchange.GetBlock(context.Background(), block.Cid())
if err == nil {
t.Fatal("expected GetBlock to fail")
}
}
func TestProviderForKeyButNetworkCannotFind(t *testing.T) { // TODO revisit this
rs := mockrouting.NewServer()
net := tn.VirtualNetwork(rs, delay.Fixed(kNetworkDelay))
ig := testinstance.NewTestInstanceGenerator(net, nil, nil)
defer ig.Close()
block := blocks.NewBlock([]byte("block"))
pinfo := p2ptestutil.RandTestBogusIdentityOrFatal(t)
err := rs.Client(pinfo).Provide(context.Background(), block.Cid(), true) // but not on network
if err != nil {
t.Fatal(err)
}
solo := ig.Next()
defer solo.Exchange.Close()
ctx, cancel := context.WithTimeout(context.Background(), time.Nanosecond)
defer cancel()
_, err = solo.Exchange.GetBlock(ctx, block.Cid())
if err != context.DeadlineExceeded {
t.Fatal("Expected DeadlineExceeded error")
}
}
func TestGetBlockFromPeerAfterPeerAnnounces(t *testing.T) {
net := tn.VirtualNetwork(mockrouting.NewServer(), delay.Fixed(kNetworkDelay))
block := blocks.NewBlock([]byte("block"))
ig := testinstance.NewTestInstanceGenerator(net, nil, nil)
defer ig.Close()
peers := ig.Instances(2)
hasBlock := peers[0]
defer hasBlock.Exchange.Close()
addBlock(t, context.Background(), hasBlock, block)
wantsBlock := peers[1]
defer wantsBlock.Exchange.Close()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
received, err := wantsBlock.Exchange.GetBlock(ctx, block.Cid())
if err != nil {
t.Log(err)
t.Fatal("Expected to succeed")
}
if !bytes.Equal(block.RawData(), received.RawData()) {
t.Fatal("Data doesn't match")
}
}
func TestDoesNotProvideWhenConfiguredNotTo(t *testing.T) {
net := tn.VirtualNetwork(mockrouting.NewServer(), delay.Fixed(kNetworkDelay))
block := blocks.NewBlock([]byte("block"))
bsOpts := []bitswap.Option{bitswap.ProvideEnabled(false), bitswap.ProviderSearchDelay(50 * time.Millisecond)}
ig := testinstance.NewTestInstanceGenerator(net, nil, bsOpts)
defer ig.Close()
hasBlock := ig.Next()
defer hasBlock.Exchange.Close()
wantsBlock := ig.Next()
defer wantsBlock.Exchange.Close()
addBlock(t, context.Background(), hasBlock, block)
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Millisecond)
defer cancel()
ns := wantsBlock.Exchange.NewSession(ctx)
received, err := ns.GetBlock(ctx, block.Cid())
if received != nil {
t.Fatalf("Expected to find nothing, found %s", received)
}
if err != context.DeadlineExceeded {
t.Fatal("Expected deadline exceeded")
}
}
// Tests that a received block is not stored in the blockstore if the block was
// not requested by the client
func TestUnwantedBlockNotAdded(t *testing.T) {
net := tn.VirtualNetwork(mockrouting.NewServer(), delay.Fixed(kNetworkDelay))
block := blocks.NewBlock([]byte("block"))
bsMessage := bsmsg.New(true)
bsMessage.AddBlock(block)
ig := testinstance.NewTestInstanceGenerator(net, nil, nil)
defer ig.Close()
peers := ig.Instances(2)
hasBlock := peers[0]
defer hasBlock.Exchange.Close()
addBlock(t, context.Background(), hasBlock, block)
doesNotWantBlock := peers[1]
defer doesNotWantBlock.Exchange.Close()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
doesNotWantBlock.Exchange.ReceiveMessage(ctx, hasBlock.Peer, bsMessage)
blockInStore, err := doesNotWantBlock.Blockstore().Has(ctx, block.Cid())
if err != nil || blockInStore {
t.Fatal("Unwanted block added to block store")
}
}
// Tests that a received block is returned to the client and stored in the
// blockstore in the following scenario:
// - the want for the block has been requested by the client
// - the want for the block has not yet been sent out to a peer
//
// (because the live request queue is full)
func TestPendingBlockAdded(t *testing.T) {
ctx := context.Background()
net := tn.VirtualNetwork(mockrouting.NewServer(), delay.Fixed(kNetworkDelay))
bg := blocksutil.NewBlockGenerator()
sessionBroadcastWantCapacity := 4
ig := testinstance.NewTestInstanceGenerator(net, nil, nil)
defer ig.Close()
instance := ig.Instances(1)[0]
defer instance.Exchange.Close()
oneSecCtx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
// Request enough blocks to exceed the session's broadcast want list
// capacity (by one block). The session will put the remaining block
// into the "tofetch" queue
blks := bg.Blocks(sessionBroadcastWantCapacity + 1)
ks := make([]cid.Cid, 0, len(blks))
for _, b := range blks {
ks = append(ks, b.Cid())
}
outch, err := instance.Exchange.GetBlocks(ctx, ks)
if err != nil {
t.Fatal(err)
}
// Wait a little while to make sure the session has time to process the wants
time.Sleep(time.Millisecond * 20)
// Simulate receiving a message which contains the block in the "tofetch" queue
lastBlock := blks[len(blks)-1]
bsMessage := bsmsg.New(true)
bsMessage.AddBlock(lastBlock)
unknownPeer := peer.ID("QmUHfvCQrzyR6vFXmeyCptfCWedfcmfa12V6UuziDtrw23")
instance.Exchange.ReceiveMessage(oneSecCtx, unknownPeer, bsMessage)
// Make sure Bitswap adds the block to the output channel
blkrecvd, ok := <-outch
if !ok {
t.Fatal("timed out waiting for block")
}
if !blkrecvd.Cid().Equals(lastBlock.Cid()) {
t.Fatal("received wrong block")
}
}
func TestLargeSwarm(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
numInstances := 100
numBlocks := 2
if detectrace.WithRace() {
// when running with the race detector, 500 instances launches
// well over 8k goroutines. This hits a race detector limit.
numInstances = 20
} else if isCI() {
numInstances = 200
} else {
t.Parallel()
}
PerformDistributionTest(t, numInstances, numBlocks)
}
func TestLargeFile(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
if !isCI() {
t.Parallel()
}
numInstances := 10
numBlocks := 100
PerformDistributionTest(t, numInstances, numBlocks)
}
func TestLargeFileTwoPeers(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
numInstances := 2
numBlocks := 100
PerformDistributionTest(t, numInstances, numBlocks)
}
func PerformDistributionTest(t *testing.T, numInstances, numBlocks int) {
ctx := context.Background()
if testing.Short() {
t.SkipNow()
}
net := tn.VirtualNetwork(mockrouting.NewServer(), delay.Fixed(kNetworkDelay))
ig := testinstance.NewTestInstanceGenerator(net, nil, []bitswap.Option{
bitswap.TaskWorkerCount(5),
bitswap.EngineTaskWorkerCount(5),
bitswap.MaxOutstandingBytesPerPeer(1 << 20),
})
defer ig.Close()
bg := blocksutil.NewBlockGenerator()
instances := ig.Instances(numInstances)
blocks := bg.Blocks(numBlocks)
t.Log("Give the blocks to the first instance")
var blkeys []cid.Cid
first := instances[0]
for _, b := range blocks {
blkeys = append(blkeys, b.Cid())
addBlock(t, ctx, first, b)
}
t.Log("Distribute!")
wg := sync.WaitGroup{}
errs := make(chan error)
for _, inst := range instances[1:] {
wg.Add(1)
go func(inst testinstance.Instance) {
defer wg.Done()
outch, err := inst.Exchange.GetBlocks(ctx, blkeys)
if err != nil {
errs <- err
}
for range outch {
}
}(inst)
}
go func() {
wg.Wait()
close(errs)
}()
for err := range errs {
if err != nil {
t.Fatal(err)
}
}
}
// TODO simplify this test. get to the _essence_!
func TestSendToWantingPeer(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
net := tn.VirtualNetwork(mockrouting.NewServer(), delay.Fixed(kNetworkDelay))
ig := testinstance.NewTestInstanceGenerator(net, nil, nil)
defer ig.Close()
bg := blocksutil.NewBlockGenerator()
peers := ig.Instances(2)
peerA := peers[0]
peerB := peers[1]
t.Logf("Session %v\n", peerA.Peer)
t.Logf("Session %v\n", peerB.Peer)
waitTime := time.Second * 5
alpha := bg.Next()
// peerA requests and waits for block alpha
ctx, cancel := context.WithTimeout(context.Background(), waitTime)
defer cancel()
alphaPromise, err := peerA.Exchange.GetBlocks(ctx, []cid.Cid{alpha.Cid()})
if err != nil {
t.Fatal(err)
}
// peerB announces to the network that he has block alpha
addBlock(t, ctx, peerB, alpha)
// At some point, peerA should get alpha (or timeout)
blkrecvd, ok := <-alphaPromise
if !ok {
t.Fatal("context timed out and broke promise channel!")
}
if !blkrecvd.Cid().Equals(alpha.Cid()) {
t.Fatal("Wrong block!")
}
}
func TestEmptyKey(t *testing.T) {
net := tn.VirtualNetwork(mockrouting.NewServer(), delay.Fixed(kNetworkDelay))
ig := testinstance.NewTestInstanceGenerator(net, nil, nil)
defer ig.Close()
bs := ig.Instances(1)[0].Exchange
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
_, err := bs.GetBlock(ctx, cid.Cid{})
if !ipld.IsNotFound(err) {
t.Error("empty str key should return ErrNotFound")
}
}
func assertStat(t *testing.T, st *bitswap.Stat, sblks, rblks, sdata, rdata uint64) {
if sblks != st.BlocksSent {
t.Errorf("mismatch in blocks sent: %d vs %d", sblks, st.BlocksSent)
}
if rblks != st.BlocksReceived {
t.Errorf("mismatch in blocks recvd: %d vs %d", rblks, st.BlocksReceived)
}
if sdata != st.DataSent {
t.Errorf("mismatch in data sent: %d vs %d", sdata, st.DataSent)
}
if rdata != st.DataReceived {
t.Errorf("mismatch in data recvd: %d vs %d", rdata, st.DataReceived)
}
}
func TestBasicBitswap(t *testing.T) {
net := tn.VirtualNetwork(mockrouting.NewServer(), delay.Fixed(kNetworkDelay))
ig := testinstance.NewTestInstanceGenerator(net, nil, nil)
defer ig.Close()
bg := blocksutil.NewBlockGenerator()
t.Log("Test a one node trying to get one block from another")
instances := ig.Instances(3)
blocks := bg.Blocks(1)
// First peer has block
addBlock(t, context.Background(), instances[0], blocks[0])
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
// Second peer broadcasts want for block CID
// (Received by first and third peers)
blk, err := instances[1].Exchange.GetBlock(ctx, blocks[0].Cid())
if err != nil {
t.Fatal(err)
}
// When second peer receives block, it should send out a cancel, so third
// peer should no longer keep second peer's want
if err = tu.WaitFor(ctx, func() error {
if len(instances[2].Exchange.WantlistForPeer(instances[1].Peer)) != 0 {
return fmt.Errorf("should have no items in other peers wantlist")
}
if len(instances[1].Exchange.GetWantlist()) != 0 {
return fmt.Errorf("shouldnt have anything in wantlist")
}
return nil
}); err != nil {
t.Fatal(err)
}
st0, err := instances[0].Exchange.Stat()
if err != nil {
t.Fatal(err)
}
st1, err := instances[1].Exchange.Stat()
if err != nil {
t.Fatal(err)
}
st2, err := instances[2].Exchange.Stat()
if err != nil {
t.Fatal(err)
}
t.Log("stat node 0")
assertStat(t, st0, 1, 0, uint64(len(blk.RawData())), 0)
t.Log("stat node 1")
assertStat(t, st1, 0, 1, 0, uint64(len(blk.RawData())))
t.Log("stat node 2")
assertStat(t, st2, 0, 0, 0, 0)
if !bytes.Equal(blk.RawData(), blocks[0].RawData()) {
t.Errorf("blocks aren't equal: expected %v, actual %v", blocks[0].RawData(), blk.RawData())
}
t.Log(blk)
for _, inst := range instances {
err := inst.Exchange.Close()
if err != nil {
t.Fatal(err)
}
}
}
func TestDoubleGet(t *testing.T) {
net := tn.VirtualNetwork(mockrouting.NewServer(), delay.Fixed(kNetworkDelay))
ig := testinstance.NewTestInstanceGenerator(net, nil, nil)
defer ig.Close()
bg := blocksutil.NewBlockGenerator()
t.Log("Test a one node trying to get one block from another")
instances := ig.Instances(2)
blocks := bg.Blocks(1)
// NOTE: A race condition can happen here where these GetBlocks requests go
// through before the peers even get connected. This is okay, bitswap
// *should* be able to handle this.
ctx1, cancel1 := context.WithCancel(context.Background())
blkch1, err := instances[1].Exchange.GetBlocks(ctx1, []cid.Cid{blocks[0].Cid()})
if err != nil {
t.Fatal(err)
}
ctx2, cancel2 := context.WithCancel(context.Background())
defer cancel2()
blkch2, err := instances[1].Exchange.GetBlocks(ctx2, []cid.Cid{blocks[0].Cid()})
if err != nil {
t.Fatal(err)
}
// ensure both requests make it into the wantlist at the same time
time.Sleep(time.Millisecond * 20)
cancel1()
_, ok := <-blkch1
if ok {
t.Fatal("expected channel to be closed")
}
addBlock(t, context.Background(), instances[0], blocks[0])
select {
case blk, ok := <-blkch2:
if !ok {
t.Fatal("expected to get the block here")
}
t.Log(blk)
case <-time.After(time.Second * 5):
p1wl := instances[0].Exchange.WantlistForPeer(instances[1].Peer)
if len(p1wl) != 1 {
t.Logf("wantlist view didnt have 1 item (had %d)", len(p1wl))
} else if !p1wl[0].Equals(blocks[0].Cid()) {
t.Logf("had 1 item, it was wrong: %s %s", blocks[0].Cid(), p1wl[0])
} else {
t.Log("had correct wantlist, somehow")
}
t.Fatal("timed out waiting on block")
}
for _, inst := range instances {
err := inst.Exchange.Close()
if err != nil {
t.Fatal(err)
}
}
}
func TestWantlistCleanup(t *testing.T) {
net := tn.VirtualNetwork(mockrouting.NewServer(), delay.Fixed(kNetworkDelay))
ig := testinstance.NewTestInstanceGenerator(net, nil, nil)
defer ig.Close()
bg := blocksutil.NewBlockGenerator()
instances := ig.Instances(2)
instance := instances[0]
bswap := instance.Exchange
blocks := bg.Blocks(20)
var keys []cid.Cid
for _, b := range blocks {
keys = append(keys, b.Cid())
}
// Once context times out, key should be removed from wantlist
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*50)
defer cancel()
_, err := bswap.GetBlock(ctx, keys[0])
if err != context.DeadlineExceeded {
t.Fatal("shouldnt have fetched any blocks")
}
time.Sleep(time.Millisecond * 50)
if len(bswap.GetWantHaves()) > 0 {
t.Fatal("should not have anyting in wantlist")
}
// Once context times out, keys should be removed from wantlist
ctx, cancel = context.WithTimeout(context.Background(), time.Millisecond*50)
defer cancel()
_, err = bswap.GetBlocks(ctx, keys[:10])
if err != nil {
t.Fatal(err)
}
<-ctx.Done()
time.Sleep(time.Millisecond * 50)
if len(bswap.GetWantHaves()) > 0 {
t.Fatal("should not have anyting in wantlist")
}
// Send want for single block, with no timeout
_, err = bswap.GetBlocks(context.Background(), keys[:1])
if err != nil {
t.Fatal(err)
}
// Send want for 10 blocks
ctx, cancel = context.WithCancel(context.Background())
_, err = bswap.GetBlocks(ctx, keys[10:])
if err != nil {
t.Fatal(err)
}
// Even after 50 milli-seconds we haven't explicitly cancelled anything
// and no timeouts have expired, so we should have 11 want-haves
time.Sleep(time.Millisecond * 50)
if len(bswap.GetWantHaves()) != 11 {
t.Fatal("should have 11 keys in wantlist")
}
// Cancel the timeout for the request for 10 blocks. This should remove
// the want-haves
cancel()
// Once the cancel is processed, we are left with the request for 1 block
time.Sleep(time.Millisecond * 50)
if !(len(bswap.GetWantHaves()) == 1 && bswap.GetWantHaves()[0] == keys[0]) {
t.Fatal("should only have keys[0] in wantlist")
}
}
func assertLedgerMatch(ra, rb *server.Receipt) error {
if ra.Sent != rb.Recv {
return fmt.Errorf("mismatch in ledgers (exchanged bytes): %d sent vs %d recvd", ra.Sent, rb.Recv)
}
if ra.Recv != rb.Sent {
return fmt.Errorf("mismatch in ledgers (exchanged bytes): %d recvd vs %d sent", ra.Recv, rb.Sent)
}
if ra.Exchanged != rb.Exchanged {
return fmt.Errorf("mismatch in ledgers (exchanged blocks): %d vs %d ", ra.Exchanged, rb.Exchanged)
}
return nil
}
func assertLedgerEqual(ra, rb *server.Receipt) error {
if ra.Value != rb.Value {
return fmt.Errorf("mismatch in ledgers (value/debt ratio): %f vs %f ", ra.Value, rb.Value)
}
if ra.Sent != rb.Sent {
return fmt.Errorf("mismatch in ledgers (sent bytes): %d vs %d", ra.Sent, rb.Sent)
}
if ra.Recv != rb.Recv {
return fmt.Errorf("mismatch in ledgers (recvd bytes): %d vs %d", ra.Recv, rb.Recv)
}
if ra.Exchanged != rb.Exchanged {
return fmt.Errorf("mismatch in ledgers (exchanged blocks): %d vs %d ", ra.Exchanged, rb.Exchanged)
}
return nil
}
func newReceipt(sent, recv, exchanged uint64) *server.Receipt {
return &server.Receipt{
Peer: "test",
Value: float64(sent) / (1 + float64(recv)),
Sent: sent,
Recv: recv,
Exchanged: exchanged,
}
}
func TestBitswapLedgerOneWay(t *testing.T) {
net := tn.VirtualNetwork(mockrouting.NewServer(), delay.Fixed(kNetworkDelay))
ig := testinstance.NewTestInstanceGenerator(net, nil, nil)
defer ig.Close()
bg := blocksutil.NewBlockGenerator()
t.Log("Test ledgers match when one peer sends block to another")
instances := ig.Instances(2)
blocks := bg.Blocks(1)
addBlock(t, context.Background(), instances[0], blocks[0])
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
blk, err := instances[1].Exchange.GetBlock(ctx, blocks[0].Cid())
if err != nil {
t.Fatal(err)
}
ra := instances[0].Exchange.LedgerForPeer(instances[1].Peer)
rb := instances[1].Exchange.LedgerForPeer(instances[0].Peer)
// compare peer ledger receipts
err = assertLedgerMatch(ra, rb)
if err != nil {
t.Fatal(err)
}
// check that receipts have intended values
ratest := newReceipt(1, 0, 1)
err = assertLedgerEqual(ratest, ra)
if err != nil {
t.Fatal(err)
}
rbtest := newReceipt(0, 1, 1)
err = assertLedgerEqual(rbtest, rb)
if err != nil {
t.Fatal(err)
}
t.Log(blk)
for _, inst := range instances {
err := inst.Exchange.Close()
if err != nil {
t.Fatal(err)
}
}
}
func TestBitswapLedgerTwoWay(t *testing.T) {
net := tn.VirtualNetwork(mockrouting.NewServer(), delay.Fixed(kNetworkDelay))
ig := testinstance.NewTestInstanceGenerator(net, nil, nil)
defer ig.Close()
bg := blocksutil.NewBlockGenerator()
t.Log("Test ledgers match when two peers send one block to each other")
instances := ig.Instances(2)
blocks := bg.Blocks(2)
addBlock(t, context.Background(), instances[0], blocks[0])
addBlock(t, context.Background(), instances[1], blocks[1])
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
_, err := instances[1].Exchange.GetBlock(ctx, blocks[0].Cid())
if err != nil {
t.Fatal(err)
}
ctx, cancel = context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
blk, err := instances[0].Exchange.GetBlock(ctx, blocks[1].Cid())
if err != nil {
t.Fatal(err)
}
ra := instances[0].Exchange.LedgerForPeer(instances[1].Peer)
rb := instances[1].Exchange.LedgerForPeer(instances[0].Peer)
// compare peer ledger receipts
err = assertLedgerMatch(ra, rb)
if err != nil {
t.Fatal(err)
}
// check that receipts have intended values
rtest := newReceipt(1, 1, 2)
err = assertLedgerEqual(rtest, ra)
if err != nil {
t.Fatal(err)
}
err = assertLedgerEqual(rtest, rb)
if err != nil {
t.Fatal(err)
}
t.Log(blk)
for _, inst := range instances {
err := inst.Exchange.Close()
if err != nil {
t.Fatal(err)
}
}
}
type testingScoreLedger struct {
scorePeer server.ScorePeerFunc
started chan struct{}
closed chan struct{}
}
func newTestingScoreLedger() *testingScoreLedger {
return &testingScoreLedger{
nil,
make(chan struct{}),
make(chan struct{}),
}
}
func (tsl *testingScoreLedger) GetReceipt(p peer.ID) *server.Receipt {
return nil
}
func (tsl *testingScoreLedger) AddToSentBytes(p peer.ID, n int) {}
func (tsl *testingScoreLedger) AddToReceivedBytes(p peer.ID, n int) {}
func (tsl *testingScoreLedger) PeerConnected(p peer.ID) {}
func (tsl *testingScoreLedger) PeerDisconnected(p peer.ID) {}
func (tsl *testingScoreLedger) Start(scorePeer server.ScorePeerFunc) {
tsl.scorePeer = scorePeer
close(tsl.started)
}
func (tsl *testingScoreLedger) Stop() {
close(tsl.closed)
}
// Tests start and stop of a custom decision logic
func TestWithScoreLedger(t *testing.T) {
tsl := newTestingScoreLedger()
net := tn.VirtualNetwork(mockrouting.NewServer(), delay.Fixed(kNetworkDelay))
bsOpts := []bitswap.Option{bitswap.WithScoreLedger(tsl)}
ig := testinstance.NewTestInstanceGenerator(net, nil, bsOpts)
defer ig.Close()
i := ig.Next()
defer i.Exchange.Close()
select {
case <-tsl.started:
if tsl.scorePeer == nil {
t.Fatal("Expected the score function to be initialized")
}
case <-time.After(time.Second * 5):
t.Fatal("Expected the score ledger to be started within 5s")
}
i.Exchange.Close()
select {
case <-tsl.closed:
case <-time.After(time.Second * 5):
t.Fatal("Expected the score ledger to be closed within 5s")
}
}