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

import (
4
	"context"
5
	"fmt"
Jeromy's avatar
Jeromy committed
6
	"io"
7
	"time"
Jeromy's avatar
Jeromy committed
8

9
	bsmsg "github.com/ipfs/go-ipfs/exchange/bitswap/message"
Jeromy's avatar
Jeromy committed
10

11 12
	pstore "gx/ipfs/QmPgDWmTmuzvP7QE5zwo1TmjbJme9pmZHNujB2453jkCTr/go-libp2p-peerstore"
	routing "gx/ipfs/QmPjTrrSfE6TzLv6ya6VWhGcCgPrUAdcgrDcQyRDX2VyW1/go-libp2p-routing"
Jeromy's avatar
Jeromy committed
13
	logging "gx/ipfs/QmSpJByNKFX1sCsHBEp3R73FL4NF6FnQTEGyNAXHm2GS52/go-log"
14 15 16
	cid "gx/ipfs/QmTprEaAA2A9bst5XH7exuyi5KzNMK3SEDNN8rBDnKWcUS/go-cid"
	ma "gx/ipfs/QmXY77cVe7rVRQXZZQRioukUM7aRW3BTcAgJe12MCtb3Ji/go-multiaddr"
	peer "gx/ipfs/QmXYjuNuxVzXKJCfWasQk1RqkhVLDM9jtUKhqc2WPQmFSB/go-libp2p-peer"
Jeromy's avatar
Jeromy committed
17
	ggio "gx/ipfs/QmZ4Qi3GaRbjcx28Sme5eMH7RQjGkt8wHxt2a65oLaeFEV/gogo-protobuf/io"
18 19
	host "gx/ipfs/QmZy7c24mmkEHpNJndwgsEE3wcVxHd8yB969yTnAJFVw7f/go-libp2p-host"
	inet "gx/ipfs/QmahYsGWry85Y7WUe2SX5G4JkH2zifEQAUtJVLZ24aC9DF/go-libp2p-net"
20 21
)

Jeromy's avatar
Jeromy committed
22
var log = logging.Logger("bitswap_network")
Jeromy's avatar
Jeromy committed
23

24 25
var sendMessageTimeout = time.Minute * 10

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

38
	return &bitswapNetwork
39 40
}

41 42
// impl transforms the ipfs network interface, which sends and receives
// NetMessage objects, into the bitswap network interface.
43
type impl struct {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
44
	host    host.Host
45
	routing routing.ContentRouting
46 47 48

	// inbound messages from the network are forwarded to the receiver
	receiver Receiver
49 50
}

Jeromy's avatar
Jeromy committed
51 52 53 54 55 56 57 58
type streamMessageSender struct {
	s inet.Stream
}

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

59 60
func (s *streamMessageSender) SendMsg(ctx context.Context, msg bsmsg.BitSwapMessage) error {
	return msgToStream(ctx, s.s, msg)
61 62
}

63 64 65 66 67 68 69 70 71 72
func msgToStream(ctx context.Context, s inet.Stream, msg bsmsg.BitSwapMessage) error {
	deadline := time.Now().Add(sendMessageTimeout)
	if dl, ok := ctx.Deadline(); ok {
		deadline = dl
	}

	if err := s.SetWriteDeadline(deadline); err != nil {
		log.Warningf("error setting deadline: %s", err)
	}

73 74 75 76 77 78 79 80 81 82 83 84 85 86
	switch s.Protocol() {
	case ProtocolBitswap:
		if err := msg.ToNetV1(s); err != nil {
			log.Debugf("error: %s", err)
			return err
		}
	case ProtocolBitswapOne, ProtocolBitswapNoVers:
		if err := msg.ToNetV0(s); err != nil {
			log.Debugf("error: %s", err)
			return err
		}
	default:
		return fmt.Errorf("unrecognized protocol on remote: %s", s.Protocol())
	}
87 88 89 90

	if err := s.SetWriteDeadline(time.Time{}); err != nil {
		log.Warningf("error resetting deadline: %s", err)
	}
91
	return nil
Jeromy's avatar
Jeromy committed
92 93 94 95 96 97 98 99 100 101 102
}

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
}

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

105 106
	// first, make sure we're connected.
	// if this fails, we cannot connect to given peer.
107
	//TODO(jbenet) move this into host.NewStream?
Jeromy's avatar
Jeromy committed
108
	if err := bsnet.host.Connect(ctx, pstore.PeerInfo{ID: p}); err != nil {
109
		return nil, err
110 111
	}

112
	return bsnet.host.NewStream(ctx, p, ProtocolBitswap, ProtocolBitswapOne, ProtocolBitswapNoVers)
113 114 115 116 117 118 119 120
}

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

	s, err := bsnet.newStreamToPeer(ctx, p)
121 122 123
	if err != nil {
		return err
	}
124 125
	defer s.Close()

126
	return msgToStream(ctx, s, outgoing)
127 128
}

129 130
func (bsnet *impl) SetDelegate(r Receiver) {
	bsnet.receiver = r
131
}
132

133
func (bsnet *impl) ConnectTo(ctx context.Context, p peer.ID) error {
Jeromy's avatar
Jeromy committed
134
	return bsnet.host.Connect(ctx, pstore.PeerInfo{ID: p})
135 136
}

137
// FindProvidersAsync returns a channel of providers for the given key
138
func (bsnet *impl) FindProvidersAsync(ctx context.Context, k *cid.Cid, max int) <-chan peer.ID {
139 140 141 142 143 144 145 146 147

	// 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
148
	for _, id := range connectedPeers {
149 150 151
		if id == bsnet.host.ID() {
			continue // ignore self as provider
		}
152 153 154
		out <- id
	}

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

// Provide provides the key to the network
174
func (bsnet *impl) Provide(ctx context.Context, k *cid.Cid) error {
175
	return bsnet.routing.Provide(ctx, k, true)
176 177
}

178 179
// handleNewStream receives a new stream from the network.
func (bsnet *impl) handleNewStream(s inet.Stream) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
180
	defer s.Close()
181 182 183 184 185

	if bsnet.receiver == nil {
		return
	}

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

197 198 199 200 201
		p := s.Conn().RemotePeer()
		ctx := context.Background()
		log.Debugf("bitswap net handleNewStream from %s", s.Conn().RemotePeer())
		bsnet.receiver.ReceiveMessage(ctx, p, received)
	}
202
}
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219

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
220 221
func (nn *netNotifiee) Listen(n inet.Network, a ma.Multiaddr)      {}
func (nn *netNotifiee) ListenClose(n inet.Network, a ma.Multiaddr) {}