bitswap_test.go 16.3 KB
Newer Older
1
package bitswap
Brian Tiger Chow's avatar
Brian Tiger Chow committed
2 3

import (
4
	"bytes"
5
	"context"
Jeromy's avatar
Jeromy committed
6
	"fmt"
7
	"sync"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
8 9 10
	"testing"
	"time"

jbenet's avatar
jbenet committed
11
	blockstore "github.com/ipfs/go-ipfs/blocks/blockstore"
12
	blocksutil "github.com/ipfs/go-ipfs/blocks/blocksutil"
13
	decision "github.com/ipfs/go-ipfs/exchange/bitswap/decision"
14 15 16
	tn "github.com/ipfs/go-ipfs/exchange/bitswap/testnet"
	mockrouting "github.com/ipfs/go-ipfs/routing/mock"
	delay "github.com/ipfs/go-ipfs/thirdparty/delay"
17 18

	detectrace "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-detect-race"
19

Steven Allen's avatar
Steven Allen committed
20 21 22 23 24
	blocks "gx/ipfs/QmYsEQydGrsxNZfAiskvQ76N2xE9hDQtSAkRSynwMiUK3c/go-block-format"
	p2ptestutil "gx/ipfs/QmZTcPxK6VqrwY94JpKZPvEqAZ6tEr1rLrpcqJbbRZbg2V/go-libp2p-netutil"
	tu "gx/ipfs/QmeDA8gNhvRTsbrjEieay5wezupJDiky8xvCzDABbsGzmp/go-testutil"
	travis "gx/ipfs/QmeDA8gNhvRTsbrjEieay5wezupJDiky8xvCzDABbsGzmp/go-testutil/ci/travis"
	cid "gx/ipfs/QmeSrf6pzut73u6zLQkRFQ3ygt3k6XFT2kjdYP8Tnkwwyg/go-cid"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
25 26
)

Brian Tiger Chow's avatar
Brian Tiger Chow committed
27 28
// FIXME the tests are really sensitive to the network delay. fix them to work
// well under varying conditions
29 30
const kNetworkDelay = 0 * time.Millisecond

31 32 33 34
func getVirtualNetwork() tn.Network {
	return tn.VirtualNetwork(mockrouting.NewServer(), delay.Fixed(kNetworkDelay))
}

35
func TestClose(t *testing.T) {
36
	vnet := getVirtualNetwork()
37
	sesgen := NewTestSessionGenerator(vnet)
Jeromy's avatar
Jeromy committed
38
	defer sesgen.Close()
39
	bgen := blocksutil.NewBlockGenerator()
40 41 42 43

	block := bgen.Next()
	bitswap := sesgen.Next()

44
	bitswap.Exchange.Close()
45
	bitswap.Exchange.GetBlock(context.Background(), block.Cid())
46 47
}

Jeromy's avatar
Jeromy committed
48 49 50 51 52 53 54 55 56
func TestProviderForKeyButNetworkCannotFind(t *testing.T) { // TODO revisit this

	rs := mockrouting.NewServer()
	net := tn.VirtualNetwork(rs, delay.Fixed(kNetworkDelay))
	g := NewTestSessionGenerator(net)
	defer g.Close()

	block := blocks.NewBlock([]byte("block"))
	pinfo := p2ptestutil.RandTestBogusIdentityOrFatal(t)
57
	rs.Client(pinfo).Provide(context.Background(), block.Cid(), true) // but not on network
Jeromy's avatar
Jeromy committed
58 59 60 61

	solo := g.Next()
	defer solo.Exchange.Close()

rht's avatar
rht committed
62 63
	ctx, cancel := context.WithTimeout(context.Background(), time.Nanosecond)
	defer cancel()
64
	_, err := solo.Exchange.GetBlock(ctx, block.Cid())
Jeromy's avatar
Jeromy committed
65 66 67 68 69 70

	if err != context.DeadlineExceeded {
		t.Fatal("Expected DeadlineExceeded error")
	}
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
71 72
func TestGetBlockFromPeerAfterPeerAnnounces(t *testing.T) {

73
	net := tn.VirtualNetwork(mockrouting.NewServer(), delay.Fixed(kNetworkDelay))
74
	block := blocks.NewBlock([]byte("block"))
75
	g := NewTestSessionGenerator(net)
Jeromy's avatar
Jeromy committed
76
	defer g.Close()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
77

78 79
	peers := g.Instances(2)
	hasBlock := peers[0]
Jeromy's avatar
Jeromy committed
80
	defer hasBlock.Exchange.Close()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
81

82
	if err := hasBlock.Exchange.HasBlock(block); err != nil {
83 84
		t.Fatal(err)
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
85

86
	wantsBlock := peers[1]
Jeromy's avatar
Jeromy committed
87
	defer wantsBlock.Exchange.Close()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
88

rht's avatar
rht committed
89 90
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
91
	received, err := wantsBlock.Exchange.GetBlock(ctx, block.Cid())
Brian Tiger Chow's avatar
Brian Tiger Chow committed
92 93 94 95
	if err != nil {
		t.Log(err)
		t.Fatal("Expected to succeed")
	}
96

Jeromy's avatar
Jeromy committed
97
	if !bytes.Equal(block.RawData(), received.RawData()) {
98 99
		t.Fatal("Data doesn't match")
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
100 101
}

102
func TestLargeSwarm(t *testing.T) {
103 104 105
	if testing.Short() {
		t.SkipNow()
	}
106
	numInstances := 100
107
	numBlocks := 2
108 109 110 111
	if detectrace.WithRace() {
		// when running with the race detector, 500 instances launches
		// well over 8k goroutines. This hits a race detector limit.
		numInstances = 100
112 113
	} else if travis.IsRunning() {
		numInstances = 200
114 115 116
	} else {
		t.Parallel()
	}
117 118
	PerformDistributionTest(t, numInstances, numBlocks)
}
119

120 121 122
func TestLargeFile(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
123
	}
124 125 126 127 128

	if !travis.IsRunning() {
		t.Parallel()
	}

129 130 131
	numInstances := 10
	numBlocks := 100
	PerformDistributionTest(t, numInstances, numBlocks)
132 133
}

134 135 136 137 138 139 140 141 142 143 144 145
func TestLargeFileNoRebroadcast(t *testing.T) {
	rbd := rebroadcastDelay.Get()
	rebroadcastDelay.Set(time.Hour * 24 * 365 * 10) // ten years should be long enough
	if testing.Short() {
		t.SkipNow()
	}
	numInstances := 10
	numBlocks := 100
	PerformDistributionTest(t, numInstances, numBlocks)
	rebroadcastDelay.Set(rbd)
}

146 147 148 149 150 151 152 153 154
func TestLargeFileTwoPeers(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}
	numInstances := 2
	numBlocks := 100
	PerformDistributionTest(t, numInstances, numBlocks)
}

155
func PerformDistributionTest(t *testing.T, numInstances, numBlocks int) {
156
	ctx := context.Background()
157 158 159
	if testing.Short() {
		t.SkipNow()
	}
160
	net := tn.VirtualNetwork(mockrouting.NewServer(), delay.Fixed(kNetworkDelay))
161
	sg := NewTestSessionGenerator(net)
Jeromy's avatar
Jeromy committed
162
	defer sg.Close()
163
	bg := blocksutil.NewBlockGenerator()
164 165 166 167 168 169

	instances := sg.Instances(numInstances)
	blocks := bg.Blocks(numBlocks)

	t.Log("Give the blocks to the first instance")

170 171 172 173 174 175 176 177 178 179 180 181 182
	nump := len(instances) - 1
	// assert we're properly connected
	for _, inst := range instances {
		peers := inst.Exchange.wm.ConnectedPeers()
		for i := 0; i < 10 && len(peers) != nump; i++ {
			time.Sleep(time.Millisecond * 50)
			peers = inst.Exchange.wm.ConnectedPeers()
		}
		if len(peers) != nump {
			t.Fatal("not enough peers connected to instance")
		}
	}

183
	var blkeys []*cid.Cid
184 185
	first := instances[0]
	for _, b := range blocks {
186
		blkeys = append(blkeys, b.Cid())
187
		first.Exchange.HasBlock(b)
188 189 190 191
	}

	t.Log("Distribute!")

Jeromy's avatar
Jeromy committed
192
	wg := sync.WaitGroup{}
193 194
	errs := make(chan error)

195
	for _, inst := range instances[1:] {
Jeromy's avatar
Jeromy committed
196 197 198
		wg.Add(1)
		go func(inst Instance) {
			defer wg.Done()
199
			outch, err := inst.Exchange.GetBlocks(ctx, blkeys)
Jeromy's avatar
Jeromy committed
200
			if err != nil {
201
				errs <- err
Jeromy's avatar
Jeromy committed
202
			}
203
			for range outch {
Jeromy's avatar
Jeromy committed
204 205
			}
		}(inst)
206
	}
207 208 209 210 211 212 213 214 215 216 217

	go func() {
		wg.Wait()
		close(errs)
	}()

	for err := range errs {
		if err != nil {
			t.Fatal(err)
		}
	}
218 219 220 221 222

	t.Log("Verify!")

	for _, inst := range instances {
		for _, b := range blocks {
223
			if _, err := inst.Blockstore().Get(b.Cid()); err != nil {
224 225 226 227 228 229
				t.Fatal(err)
			}
		}
	}
}

230
// TODO simplify this test. get to the _essence_!
231
func TestSendToWantingPeer(t *testing.T) {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
232 233 234 235
	if testing.Short() {
		t.SkipNow()
	}

236
	net := tn.VirtualNetwork(mockrouting.NewServer(), delay.Fixed(kNetworkDelay))
237
	sg := NewTestSessionGenerator(net)
Jeromy's avatar
Jeromy committed
238
	defer sg.Close()
239
	bg := blocksutil.NewBlockGenerator()
240

Brian Tiger Chow's avatar
Brian Tiger Chow committed
241 242
	prev := rebroadcastDelay.Set(time.Second / 2)
	defer func() { rebroadcastDelay.Set(prev) }()
243

244 245 246
	peers := sg.Instances(2)
	peerA := peers[0]
	peerB := peers[1]
247

248 249
	t.Logf("Session %v\n", peerA.Peer)
	t.Logf("Session %v\n", peerB.Peer)
250

251
	waitTime := time.Second * 5
252

253 254
	alpha := bg.Next()
	// peerA requests and waits for block alpha
255
	ctx, cancel := context.WithTimeout(context.Background(), waitTime)
rht's avatar
rht committed
256
	defer cancel()
257
	alphaPromise, err := peerA.Exchange.GetBlocks(ctx, []*cid.Cid{alpha.Cid()})
258
	if err != nil {
259 260
		t.Fatal(err)
	}
261

262
	// peerB announces to the network that he has block alpha
263
	err = peerB.Exchange.HasBlock(alpha)
264
	if err != nil {
265 266
		t.Fatal(err)
	}
267

268 269 270 271
	// At some point, peerA should get alpha (or timeout)
	blkrecvd, ok := <-alphaPromise
	if !ok {
		t.Fatal("context timed out and broke promise channel!")
272
	}
273

274
	if !blkrecvd.Cid().Equals(alpha.Cid()) {
275
		t.Fatal("Wrong block!")
276
	}
277

278
}
Jeromy's avatar
Jeromy committed
279

jbenet's avatar
jbenet committed
280 281 282 283 284 285
func TestEmptyKey(t *testing.T) {
	net := tn.VirtualNetwork(mockrouting.NewServer(), delay.Fixed(kNetworkDelay))
	sg := NewTestSessionGenerator(net)
	defer sg.Close()
	bs := sg.Instances(1)[0].Exchange

Jeromy's avatar
Jeromy committed
286 287 288
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
	defer cancel()

289
	_, err := bs.GetBlock(ctx, nil)
jbenet's avatar
jbenet committed
290 291 292 293 294
	if err != blockstore.ErrNotFound {
		t.Error("empty str key should return ErrNotFound")
	}
}

Steven Allen's avatar
Steven Allen committed
295
func assertStat(t *testing.T, st *Stat, sblks, rblks, sdata, rdata uint64) {
Jeromy's avatar
Jeromy committed
296
	if sblks != st.BlocksSent {
Steven Allen's avatar
Steven Allen committed
297
		t.Errorf("mismatch in blocks sent: %d vs %d", sblks, st.BlocksSent)
Jeromy's avatar
Jeromy committed
298 299 300
	}

	if rblks != st.BlocksReceived {
Steven Allen's avatar
Steven Allen committed
301
		t.Errorf("mismatch in blocks recvd: %d vs %d", rblks, st.BlocksReceived)
Jeromy's avatar
Jeromy committed
302 303 304
	}

	if sdata != st.DataSent {
Steven Allen's avatar
Steven Allen committed
305
		t.Errorf("mismatch in data sent: %d vs %d", sdata, st.DataSent)
Jeromy's avatar
Jeromy committed
306 307 308
	}

	if rdata != st.DataReceived {
Steven Allen's avatar
Steven Allen committed
309
		t.Errorf("mismatch in data recvd: %d vs %d", rdata, st.DataReceived)
Jeromy's avatar
Jeromy committed
310 311 312
	}
}

Jeromy's avatar
Jeromy committed
313
func TestBasicBitswap(t *testing.T) {
314
	net := tn.VirtualNetwork(mockrouting.NewServer(), delay.Fixed(kNetworkDelay))
315
	sg := NewTestSessionGenerator(net)
316
	defer sg.Close()
Jeromy's avatar
Jeromy committed
317 318
	bg := blocksutil.NewBlockGenerator()

319
	t.Log("Test a one node trying to get one block from another")
Jeromy's avatar
Jeromy committed
320

321
	instances := sg.Instances(3)
Jeromy's avatar
Jeromy committed
322
	blocks := bg.Blocks(1)
323
	err := instances[0].Exchange.HasBlock(blocks[0])
Jeromy's avatar
Jeromy committed
324 325 326 327
	if err != nil {
		t.Fatal(err)
	}

328
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
rht's avatar
rht committed
329
	defer cancel()
330
	blk, err := instances[1].Exchange.GetBlock(ctx, blocks[0].Cid())
Jeromy's avatar
Jeromy committed
331 332 333 334
	if err != nil {
		t.Fatal(err)
	}

335 336 337 338 339 340 341 342 343 344
	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)
Jeromy's avatar
Jeromy committed
345 346
	}

Jeromy's avatar
Jeromy committed
347 348 349 350 351 352 353 354 355 356
	st0, err := instances[0].Exchange.Stat()
	if err != nil {
		t.Fatal(err)
	}

	st1, err := instances[1].Exchange.Stat()
	if err != nil {
		t.Fatal(err)
	}

Steven Allen's avatar
Steven Allen committed
357 358
	st2, err := instances[2].Exchange.Stat()
	if err != nil {
Jeromy's avatar
Jeromy committed
359 360 361
		t.Fatal(err)
	}

Steven Allen's avatar
Steven Allen committed
362 363 364 365 366 367 368 369 370
	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())
Jeromy's avatar
Jeromy committed
371 372
	}

Jeromy's avatar
Jeromy committed
373 374 375 376 377 378 379 380
	t.Log(blk)
	for _, inst := range instances {
		err := inst.Exchange.Close()
		if err != nil {
			t.Fatal(err)
		}
	}
}
Jeromy's avatar
Jeromy committed
381 382 383 384 385 386 387 388 389 390 391 392

func TestDoubleGet(t *testing.T) {
	net := tn.VirtualNetwork(mockrouting.NewServer(), delay.Fixed(kNetworkDelay))
	sg := NewTestSessionGenerator(net)
	defer sg.Close()
	bg := blocksutil.NewBlockGenerator()

	t.Log("Test a one node trying to get one block from another")

	instances := sg.Instances(2)
	blocks := bg.Blocks(1)

Jeromy's avatar
Jeromy committed
393 394 395
	// 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.
Jeromy's avatar
Jeromy committed
396
	ctx1, cancel1 := context.WithCancel(context.Background())
397
	blkch1, err := instances[1].Exchange.GetBlocks(ctx1, []*cid.Cid{blocks[0].Cid()})
Jeromy's avatar
Jeromy committed
398 399 400 401 402 403 404
	if err != nil {
		t.Fatal(err)
	}

	ctx2, cancel2 := context.WithCancel(context.Background())
	defer cancel2()

405
	blkch2, err := instances[1].Exchange.GetBlocks(ctx2, []*cid.Cid{blocks[0].Cid()})
Jeromy's avatar
Jeromy committed
406 407 408 409
	if err != nil {
		t.Fatal(err)
	}

410
	// ensure both requests make it into the wantlist at the same time
Jeromy's avatar
Jeromy committed
411
	time.Sleep(time.Millisecond * 20)
Jeromy's avatar
Jeromy committed
412 413 414 415 416 417 418 419 420 421 422 423
	cancel1()

	_, ok := <-blkch1
	if ok {
		t.Fatal("expected channel to be closed")
	}

	err = instances[0].Exchange.HasBlock(blocks[0])
	if err != nil {
		t.Fatal(err)
	}

424 425 426 427 428 429 430
	select {
	case blk, ok := <-blkch2:
		if !ok {
			t.Fatal("expected to get the block here")
		}
		t.Log(blk)
	case <-time.After(time.Second * 5):
Jeromy's avatar
Jeromy committed
431 432 433 434 435 436 437 438
		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")
		}
439
		t.Fatal("timed out waiting on block")
Jeromy's avatar
Jeromy committed
440 441 442 443 444 445 446 447 448
	}

	for _, inst := range instances {
		err := inst.Exchange.Close()
		if err != nil {
			t.Fatal(err)
		}
	}
}
449 450 451 452 453 454 455 456 457 458 459

func TestWantlistCleanup(t *testing.T) {
	net := tn.VirtualNetwork(mockrouting.NewServer(), delay.Fixed(kNetworkDelay))
	sg := NewTestSessionGenerator(net)
	defer sg.Close()
	bg := blocksutil.NewBlockGenerator()

	instances := sg.Instances(1)[0]
	bswap := instances.Exchange
	blocks := bg.Blocks(20)

460
	var keys []*cid.Cid
461
	for _, b := range blocks {
462
		keys = append(keys, b.Cid())
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
	}

	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.GetWantlist()) > 0 {
		t.Fatal("should not have anyting in 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.GetWantlist()) > 0 {
		t.Fatal("should not have anyting in wantlist")
	}

	_, err = bswap.GetBlocks(context.Background(), keys[:1])
	if err != nil {
		t.Fatal(err)
	}

	ctx, cancel = context.WithCancel(context.Background())
	_, err = bswap.GetBlocks(ctx, keys[10:])
	if err != nil {
		t.Fatal(err)
	}

	time.Sleep(time.Millisecond * 50)
	if len(bswap.GetWantlist()) != 11 {
		t.Fatal("should have 11 keys in wantlist")
	}

	cancel()
	time.Sleep(time.Millisecond * 50)
	if !(len(bswap.GetWantlist()) == 1 && bswap.GetWantlist()[0] == keys[0]) {
		t.Fatal("should only have keys[0] in wantlist")
	}
}
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530

func assertLedgerMatch(ra, rb *decision.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
}

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
func assertLedgerEqual(ra, rb *decision.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) *decision.Receipt {
	return &decision.Receipt{
		Peer:      "test",
		Value:     float64(sent) / (1 + float64(recv)),
		Sent:      sent,
		Recv:      recv,
		Exchanged: exchanged,
	}
}

func TestBitswapLedgerOneWay(t *testing.T) {
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
	net := tn.VirtualNetwork(mockrouting.NewServer(), delay.Fixed(kNetworkDelay))
	sg := NewTestSessionGenerator(net)
	defer sg.Close()
	bg := blocksutil.NewBlockGenerator()

	t.Log("Test ledgers match when one peer sends block to another")

	instances := sg.Instances(2)
	blocks := bg.Blocks(1)
	err := instances[0].Exchange.HasBlock(blocks[0])
	if err != nil {
		t.Fatal(err)
	}

	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)

586
	// compare peer ledger receipts
587 588 589 590 591
	err = assertLedgerMatch(ra, rb)
	if err != nil {
		t.Fatal(err)
	}

592 593 594 595 596 597 598 599 600 601 602 603
	// 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)
	}

604 605 606 607 608 609 610 611 612
	t.Log(blk)
	for _, inst := range instances {
		err := inst.Exchange.Close()
		if err != nil {
			t.Fatal(err)
		}
	}
}

613
func TestBitswapLedgerTwoWay(t *testing.T) {
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
	net := tn.VirtualNetwork(mockrouting.NewServer(), delay.Fixed(kNetworkDelay))
	sg := NewTestSessionGenerator(net)
	defer sg.Close()
	bg := blocksutil.NewBlockGenerator()

	t.Log("Test ledgers match when two peers send one block to each other")

	instances := sg.Instances(2)
	blocks := bg.Blocks(2)
	err := instances[0].Exchange.HasBlock(blocks[0])
	if err != nil {
		t.Fatal(err)
	}

	err = instances[1].Exchange.HasBlock(blocks[1])
	if err != nil {
		t.Fatal(err)
	}

	ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
	defer cancel()
635
	_, err = instances[1].Exchange.GetBlock(ctx, blocks[0].Cid())
636 637 638 639 640 641
	if err != nil {
		t.Fatal(err)
	}

	ctx, cancel = context.WithTimeout(context.Background(), time.Second*5)
	defer cancel()
642
	blk, err := instances[0].Exchange.GetBlock(ctx, blocks[1].Cid())
643 644 645 646 647 648 649
	if err != nil {
		t.Fatal(err)
	}

	ra := instances[0].Exchange.LedgerForPeer(instances[1].Peer)
	rb := instances[1].Exchange.LedgerForPeer(instances[0].Peer)

650
	// compare peer ledger receipts
651 652 653 654 655
	err = assertLedgerMatch(ra, rb)
	if err != nil {
		t.Fatal(err)
	}

656 657 658 659 660 661 662 663 664 665 666 667
	// 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)
	}

668 669 670 671 672 673 674 675
	t.Log(blk)
	for _, inst := range instances {
		err := inst.Exchange.Close()
		if err != nil {
			t.Fatal(err)
		}
	}
}