bitswap.go 4.76 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
	ctx, cancelFunc := context.WithCancel(parent)
65
	// TODO add to wantlist
66
	promise := bs.notifications.Subscribe(ctx, k)
67

68
	go func() {
69 70 71 72
		const maxProviders = 20
		peersToQuery := bs.routing.FindProvidersAsync(ctx, k, maxProviders)
		message := bsmsg.New()
		message.AppendWanted(k)
73 74
		for iiiii := range peersToQuery {
			go func(p *peer.Peer) {
75
				response, err := bs.sender.SendRequest(ctx, p, message)
76 77 78
				if err != nil {
					return
				}
79 80 81 82 83
				// 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)

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

	select {
93 94
	case block := <-promise:
		cancelFunc()
95
		// TODO remove from wantlist
96
		return &block, nil
97 98
	case <-parent.Done():
		return nil, parent.Err()
99 100 101
	}
}

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

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

120
	bs.strategy.MessageReceived(p, incoming) // FIRST
121

122
	for _, block := range incoming.Blocks() {
123 124 125
		// TODO verify blocks?
		if err := bs.blockstore.Put(block); err != nil {
			continue // FIXME(brian): err ignored
126
		}
127 128 129 130
		go bs.notifications.Publish(block)
		go func() {
			_ = bs.HasBlock(ctx, block) // FIXME err ignored
		}()
131 132
	}

133 134 135 136 137
	for _, key := range incoming.Wantlist() {
		if bs.strategy.ShouldSendBlockToPeer(key, p) {
			block, errBlockNotFound := bs.blockstore.Get(key)
			if errBlockNotFound != nil {
				return nil, nil, errBlockNotFound
138
			}
139 140 141 142
			message := bsmsg.New()
			message.AppendBlock(*block)
			defer bs.strategy.MessageSent(p, message)
			return p, message, nil
143 144
		}
	}
145
	return nil, nil, nil
146
}
147

148 149 150
// 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
151
	bs.sender.SendMessage(ctx, p, m)
152
	go bs.strategy.MessageSent(p, m)
153 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
				go bs.send(ctx, p, message)
162 163 164 165
			}
		}
	}
}