ipfs_impl.go 5.93 KB
Newer Older
1 2 3
package network

import (
Jeromy's avatar
Jeromy committed
4 5
	"io"

6 7
	bsmsg "github.com/ipfs/go-ipfs/exchange/bitswap/message"
	routing "github.com/ipfs/go-ipfs/routing"
George Antoniadis's avatar
George Antoniadis committed
8
	key "gx/ipfs/Qmce4Y4zg3sYr7xKM5UueS67vhNni6EeWgCRnb7MbLJMew/go-key"
Jeromy's avatar
Jeromy committed
9

Jeromy's avatar
Jeromy committed
10 11 12
	pstore "gx/ipfs/QmSZi9ygLohBUGyHMqE5N6eToPwqcg7bZQTULeVLFu7Q6d/go-libp2p-peerstore"
	logging "gx/ipfs/QmSpJByNKFX1sCsHBEp3R73FL4NF6FnQTEGyNAXHm2GS52/go-log"
	peer "gx/ipfs/QmWtbQU15LaB5B1JC2F7TV9P4K88vD3PpA4AJrwfCjhML8/go-libp2p-peer"
13
	ma "gx/ipfs/QmYzDkkgAEmrcNzFCiYo6L1dTX4EAG1gZkbtdbd9trL4vd/go-multiaddr"
Jeromy's avatar
Jeromy committed
14
	ggio "gx/ipfs/QmZ4Qi3GaRbjcx28Sme5eMH7RQjGkt8wHxt2a65oLaeFEV/gogo-protobuf/io"
Jeromy's avatar
Jeromy committed
15
	context "gx/ipfs/QmZy2y8t9zQH2a1b8q2ZSLKp17ATuJoCNxxyMFG5qFExpt/go-net/context"
Jeromy's avatar
Jeromy committed
16 17
	host "gx/ipfs/Qmf4ETeAWXuThBfWwonVyFqGFSgTWepUDEr1txcctvpTXS/go-libp2p/p2p/host"
	inet "gx/ipfs/Qmf4ETeAWXuThBfWwonVyFqGFSgTWepUDEr1txcctvpTXS/go-libp2p/p2p/net"
18 19
)

Jeromy's avatar
Jeromy committed
20
var log = logging.Logger("bitswap_network")
Jeromy's avatar
Jeromy committed
21

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
22
// NewFromIpfsHost returns a BitSwapNetwork supported by underlying IPFS host
23
func NewFromIpfsHost(host host.Host, r routing.ContentRouting) BitSwapNetwork {
24
	bitswapNetwork := impl{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
25
		host:    host,
26
		routing: r,
27
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
28
	host.SetStreamHandler(ProtocolBitswap, bitswapNetwork.handleNewStream)
29
	host.SetStreamHandler(ProtocolBitswapOld, bitswapNetwork.handleNewStream)
30 31 32
	host.Network().Notify((*netNotifiee)(&bitswapNetwork))
	// TODO: StopNotify.

33
	return &bitswapNetwork
34 35
}

36 37
// impl transforms the ipfs network interface, which sends and receives
// NetMessage objects, into the bitswap network interface.
38
type impl struct {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
39
	host    host.Host
40
	routing routing.ContentRouting
41 42 43

	// inbound messages from the network are forwarded to the receiver
	receiver Receiver
44 45
}

Jeromy's avatar
Jeromy committed
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
type streamMessageSender struct {
	s inet.Stream
}

func (s *streamMessageSender) Close() error {
	return s.s.Close()
}

func (s *streamMessageSender) SendMsg(msg bsmsg.BitSwapMessage) error {
	return msg.ToNet(s.s)
}

func (bsnet *impl) NewMessageSender(ctx context.Context, p peer.ID) (MessageSender, error) {
	s, err := bsnet.newStreamToPeer(ctx, p)
	if err != nil {
		return nil, err
	}

	return &streamMessageSender{s: s}, nil
}

67
func (bsnet *impl) newStreamToPeer(ctx context.Context, p peer.ID) (inet.Stream, error) {
68

69 70
	// first, make sure we're connected.
	// if this fails, we cannot connect to given peer.
71
	//TODO(jbenet) move this into host.NewStream?
Jeromy's avatar
Jeromy committed
72
	if err := bsnet.host.Connect(ctx, pstore.PeerInfo{ID: p}); err != nil {
73
		return nil, err
74 75
	}

76
	return bsnet.host.NewStream(ctx, p, ProtocolBitswap, ProtocolBitswapOld)
77 78 79 80 81 82 83 84
}

func (bsnet *impl) SendMessage(
	ctx context.Context,
	p peer.ID,
	outgoing bsmsg.BitSwapMessage) error {

	s, err := bsnet.newStreamToPeer(ctx, p)
85 86 87
	if err != nil {
		return err
	}
88 89
	defer s.Close()

90
	if err := outgoing.ToNet(s); err != nil {
91
		log.Debugf("error: %s", err)
92 93 94 95
		return err
	}

	return err
96 97
}

98
func (bsnet *impl) SendRequest(
99
	ctx context.Context,
100
	p peer.ID,
101 102
	outgoing bsmsg.BitSwapMessage) (bsmsg.BitSwapMessage, error) {

103
	s, err := bsnet.newStreamToPeer(ctx, p)
104 105 106
	if err != nil {
		return nil, err
	}
107 108 109
	defer s.Close()

	if err := outgoing.ToNet(s); err != nil {
110
		log.Debugf("error: %s", err)
111 112
		return nil, err
	}
113

114 115
	incoming, err := bsmsg.FromNet(s)
	if err != nil {
116
		log.Debugf("error: %s", err)
117 118 119 120
		return incoming, err
	}

	return incoming, nil
121 122
}

123 124
func (bsnet *impl) SetDelegate(r Receiver) {
	bsnet.receiver = r
125
}
126

127
func (bsnet *impl) ConnectTo(ctx context.Context, p peer.ID) error {
Jeromy's avatar
Jeromy committed
128
	return bsnet.host.Connect(ctx, pstore.PeerInfo{ID: p})
129 130
}

131
// FindProvidersAsync returns a channel of providers for the given key
132
func (bsnet *impl) FindProvidersAsync(ctx context.Context, k key.Key, max int) <-chan peer.ID {
133 134 135 136 137 138 139 140 141

	// Since routing queries are expensive, give bitswap the peers to which we
	// have open connections. Note that this may cause issues if bitswap starts
	// precisely tracking which peers provide certain keys. This optimization
	// would be misleading. In the long run, this may not be the most
	// appropriate place for this optimization, but it won't cause any harm in
	// the short term.
	connectedPeers := bsnet.host.Network().Peers()
	out := make(chan peer.ID, len(connectedPeers)) // just enough buffer for these connectedPeers
142
	for _, id := range connectedPeers {
143 144 145
		if id == bsnet.host.ID() {
			continue // ignore self as provider
		}
146 147 148
		out <- id
	}

149 150 151 152
	go func() {
		defer close(out)
		providers := bsnet.routing.FindProvidersAsync(ctx, k, max)
		for info := range providers {
153 154
			if info.ID == bsnet.host.ID() {
				continue // ignore self as provider
155
			}
Jeromy's avatar
Jeromy committed
156
			bsnet.host.Peerstore().AddAddrs(info.ID, info.Addrs, pstore.TempAddrTTL)
157 158
			select {
			case <-ctx.Done():
159
				return
160 161 162 163 164
			case out <- info.ID:
			}
		}
	}()
	return out
165 166 167
}

// Provide provides the key to the network
168
func (bsnet *impl) Provide(ctx context.Context, k key.Key) error {
169 170 171
	return bsnet.routing.Provide(ctx, k)
}

172 173
// handleNewStream receives a new stream from the network.
func (bsnet *impl) handleNewStream(s inet.Stream) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
174
	defer s.Close()
175 176 177 178 179

	if bsnet.receiver == nil {
		return
	}

Jeromy's avatar
Jeromy committed
180
	reader := ggio.NewDelimitedReader(s, inet.MessageSizeMax)
181
	for {
Jeromy's avatar
Jeromy committed
182
		received, err := bsmsg.FromPBReader(reader)
183
		if err != nil {
Jeromy's avatar
Jeromy committed
184 185 186 187
			if err != io.EOF {
				go bsnet.receiver.ReceiveError(err)
				log.Debugf("bitswap net handleNewStream from %s error: %s", s.Conn().RemotePeer(), err)
			}
188 189
			return
		}
190

191 192 193 194 195
		p := s.Conn().RemotePeer()
		ctx := context.Background()
		log.Debugf("bitswap net handleNewStream from %s", s.Conn().RemotePeer())
		bsnet.receiver.ReceiveMessage(ctx, p, received)
	}
196
}
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213

type netNotifiee impl

func (nn *netNotifiee) impl() *impl {
	return (*impl)(nn)
}

func (nn *netNotifiee) Connected(n inet.Network, v inet.Conn) {
	nn.impl().receiver.PeerConnected(v.RemotePeer())
}

func (nn *netNotifiee) Disconnected(n inet.Network, v inet.Conn) {
	nn.impl().receiver.PeerDisconnected(v.RemotePeer())
}

func (nn *netNotifiee) OpenedStream(n inet.Network, v inet.Stream) {}
func (nn *netNotifiee) ClosedStream(n inet.Network, v inet.Stream) {}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
214 215
func (nn *netNotifiee) Listen(n inet.Network, a ma.Multiaddr)      {}
func (nn *netNotifiee) ListenClose(n inet.Network, a ma.Multiaddr) {}