From 779c923a05d273d9312922962e9d9ed4c850ff09 Mon Sep 17 00:00:00 2001 From: hannahhoward Date: Tue, 13 Nov 2018 11:25:30 -0800 Subject: [PATCH] fix(Receiver): Ignore unwanted blocks If Bitswap receives a block that isn't in it's wantlist, is should ignore it fix #21 fix #22 --- bitswap.go | 6 ++++++ bitswap_test.go | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/bitswap.go b/bitswap.go index 942679d4..4b72b52d 100644 --- a/bitswap.go +++ b/bitswap.go @@ -388,6 +388,7 @@ func (bs *Bitswap) ReceiveMessage(ctx context.Context, p peer.ID, incoming bsmsg wg := sync.WaitGroup{} for _, block := range iblocks { + wg.Add(1) go func(b blocks.Block) { // TODO: this probably doesnt need to be a goroutine... defer wg.Done() @@ -396,6 +397,11 @@ func (bs *Bitswap) ReceiveMessage(ctx context.Context, p peer.ID, incoming bsmsg log.Debugf("got block %s from %s", b, p) + // skip received blocks that are not in the wantlist + if _, contains := bs.wm.wl.Contains(b.Cid()); !contains { + return + } + if err := bs.receiveBlockFrom(b, p); err != nil { log.Warningf("ReceiveMessage recvBlockFrom error: %s", err) } diff --git a/bitswap_test.go b/bitswap_test.go index 715958eb..d55fd073 100644 --- a/bitswap_test.go +++ b/bitswap_test.go @@ -9,6 +9,7 @@ import ( "time" decision "github.com/ipfs/go-bitswap/decision" + "github.com/ipfs/go-bitswap/message" tn "github.com/ipfs/go-bitswap/testnet" blocks "github.com/ipfs/go-block-format" @@ -98,6 +99,38 @@ func TestGetBlockFromPeerAfterPeerAnnounces(t *testing.T) { } } +func TestUnwantedBlockNotAdded(t *testing.T) { + + net := tn.VirtualNetwork(mockrouting.NewServer(), delay.Fixed(kNetworkDelay)) + block := blocks.NewBlock([]byte("block")) + bsMessage := message.New(true) + bsMessage.AddBlock(block) + + g := NewTestSessionGenerator(net) + defer g.Close() + + peers := g.Instances(2) + hasBlock := peers[0] + defer hasBlock.Exchange.Close() + + if err := hasBlock.Exchange.HasBlock(block); err != nil { + t.Fatal(err) + } + + 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(block.Cid()) + if err != nil || blockInStore { + t.Fatal("Unwanted block added to block store") + } +} + func TestLargeSwarm(t *testing.T) { if testing.Short() { t.SkipNow()