bitswap.go 4.69 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3
package bitswap

import (
4 5
	"errors"

6
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
7 8
	ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/datastore.go"

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
9
	blocks "github.com/jbenet/go-ipfs/blocks"
10
	blockstore "github.com/jbenet/go-ipfs/blockstore"
11 12 13 14 15
	exchange "github.com/jbenet/go-ipfs/exchange"
	bsmsg "github.com/jbenet/go-ipfs/exchange/bitswap/message"
	bsnet "github.com/jbenet/go-ipfs/exchange/bitswap/network"
	notifications "github.com/jbenet/go-ipfs/exchange/bitswap/notifications"
	strategy "github.com/jbenet/go-ipfs/exchange/bitswap/strategy"
16
	peer "github.com/jbenet/go-ipfs/peer"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
17
	u "github.com/jbenet/go-ipfs/util"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
18 19
)

20 21
// NetMessageSession initializes a BitSwap session that communicates over the
// provided NetMessage service
22
func NetMessageSession(parent context.Context, s bsnet.NetMessageService, p *peer.Peer, d ds.Datastore, directory bsnet.Routing) exchange.Interface {
23

24
	networkAdapter := bsnet.NetMessageAdapter(s, nil)
25 26 27 28 29
	bs := &bitswap{
		blockstore:    blockstore.NewBlockstore(d),
		notifications: notifications.New(),
		strategy:      strategy.New(),
		routing:       directory,
30
		sender:        networkAdapter,
31
	}
32
	networkAdapter.SetDelegate(bs)
33 34 35 36

	return bs
}

37 38
// bitswap instances implement the bitswap protocol.
type bitswap struct {
39

40
	// sender delivers messages on behalf of the session
41
	sender bsnet.Adapter
42

43
	// blockstore is the local database
44
	// NB: ensure threadsafety
45
	blockstore blockstore.Blockstore
46

47
	// routing interface for communication
48
	routing bsnet.Routing
49

50
	notifications notifications.PubSub
51

52
	// strategy listens to network traffic and makes decisions about how to
53
	// interact with partners.
54 55
	// TODO(brian): save the strategy's state to the datastore
	strategy strategy.Strategy
56 57
}

58 59
// GetBlock attempts to retrieve a particular block from peers within the
// deadline enforced by the context
60 61
//
// TODO ensure only one active request per key
62
func (bs *bitswap) Block(parent context.Context, k u.Key) (*blocks.Block, error) {
63

64 65
	ctx, cancelFunc := context.WithCancel(parent)
	promise := bs.notifications.Subscribe(ctx, k)
66

67
	go func() {
68 69 70 71 72
		const maxProviders = 20
		peersToQuery := bs.routing.FindProvidersAsync(ctx, k, maxProviders)
		message := bsmsg.New()
		message.AppendWanted(k)
		for i := range peersToQuery {
73
			func(p *peer.Peer) {
74
				response, err := bs.sender.SendRequest(ctx, p, message)
75 76 77
				if err != nil {
					return
				}
78 79 80 81 82
				// FIXME ensure accounting is handled correctly when
				// communication fails. May require slightly different API to
				// get better guarantees. May need shared sequence numbers.
				bs.strategy.MessageSent(p, message)

83 84 85
				if response == nil {
					return
				}
86 87
				bs.ReceiveMessage(ctx, p, response)
			}(i)
88 89
		}
	}()
90 91

	select {
92 93
	case block := <-promise:
		cancelFunc()
94
		return &block, nil
95 96
	case <-parent.Done():
		return nil, parent.Err()
97 98 99
	}
}

100
// HasBlock announces the existance of a block to bitswap, potentially sending
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
101
// it to peers (Partners) whose WantLists include it.
102
func (bs *bitswap) HasBlock(ctx context.Context, blk blocks.Block) error {
103
	bs.sendToPeersThatWant(ctx, blk)
104 105 106
	return bs.routing.Provide(blk.Key())
}

107
// TODO(brian): handle errors
108
func (bs *bitswap) ReceiveMessage(
109
	ctx context.Context, p *peer.Peer, incoming bsmsg.BitSwapMessage) (
110
	*peer.Peer, bsmsg.BitSwapMessage, error) {
111 112 113 114 115 116
	if p == nil {
		return nil, nil, errors.New("Received nil Peer")
	}
	if incoming == nil {
		return nil, nil, errors.New("Received nil Message")
	}
117

118
	bs.strategy.MessageReceived(p, incoming)
119

120 121
	if incoming.Blocks() != nil {
		for _, block := range incoming.Blocks() {
122 123 124
			bs.blockstore.Put(block) // FIXME(brian): err ignored
			bs.notifications.Publish(block)
			bs.HasBlock(ctx, block) // FIXME err ignored
125 126 127 128
		}
	}

	if incoming.Wantlist() != nil {
129
		for _, key := range incoming.Wantlist() {
130
			if bs.strategy.ShouldSendBlockToPeer(key, p) {
131 132
				block, errBlockNotFound := bs.blockstore.Get(key)
				if errBlockNotFound != nil {
133
					return nil, nil, errBlockNotFound
134
				}
135 136
				message := bsmsg.New()
				message.AppendBlock(*block)
137
				bs.send(ctx, p, message)
138
			}
139 140
		}
	}
141
	return nil, nil, nil
142
}
143

144 145 146
// send strives to ensure that accounting is always performed when a message is
// sent
func (bs *bitswap) send(ctx context.Context, p *peer.Peer, m bsmsg.BitSwapMessage) {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
147
	bs.sender.SendMessage(ctx, p, m)
148
	bs.strategy.MessageSent(p, m)
149 150
}

151 152 153
func numBytes(b blocks.Block) int {
	return len(b.Data)
}
154 155 156 157 158 159 160

func (bs *bitswap) sendToPeersThatWant(ctx context.Context, block blocks.Block) {
	for _, p := range bs.strategy.Peers() {
		if bs.strategy.BlockIsWantedByPeer(block.Key(), p) {
			if bs.strategy.ShouldSendBlockToPeer(block.Key(), p) {
				message := bsmsg.New()
				message.AppendBlock(block)
161
				bs.send(ctx, p, message)
162 163 164 165
			}
		}
	}
}