bitswap.go 4.84 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, p *peer.Peer, s bsnet.NetMessageService, directory bsnet.Routing, d ds.Datastore) 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 69
	const maxProviders = 20
	peersToQuery := bs.routing.FindProvidersAsync(ctx, k, maxProviders)
70

71
	go func() {
72 73
		message := bsmsg.New()
		message.AppendWanted(k)
74
		for iiiii := range peersToQuery {
75
			// u.DOut("bitswap got peersToQuery: %s\n", iiiii)
76
			go func(p *peer.Peer) {
77
				response, err := bs.sender.SendRequest(ctx, p, message)
78 79 80
				if err != nil {
					return
				}
81 82 83 84 85
				// 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)

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

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

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

111
// TODO(brian): handle errors
112
func (bs *bitswap) ReceiveMessage(ctx context.Context, p *peer.Peer, incoming bsmsg.BitSwapMessage) (
113
	*peer.Peer, bsmsg.BitSwapMessage, error) {
114

115 116 117 118 119 120
	if p == nil {
		return nil, nil, errors.New("Received nil Peer")
	}
	if incoming == nil {
		return nil, nil, errors.New("Received nil Message")
	}
121

122
	bs.strategy.MessageReceived(p, incoming) // FIRST
123

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

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

150 151 152
// 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
153
	bs.sender.SendMessage(ctx, p, m)
154
	go bs.strategy.MessageSent(p, m)
155 156
}

157 158 159 160 161 162
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)
163
				go bs.send(ctx, p, message)
164 165 166 167
			}
		}
	}
}