ipfs_impl.go 6.55 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

Steven Allen's avatar
Steven Allen committed
11 12
	inet "gx/ipfs/QmPjvxTpVH8qJyQDnxnsxF9kv9jezKD1kozz1hs3fCGsNh/go-libp2p-net"
	ifconnmgr "gx/ipfs/QmXuucFcuvAWYAJfhHV2h4BYreHEAsLSsiquosiXeuduTN/go-libp2p-interface-connmgr"
Steven Allen's avatar
Steven Allen committed
13
	cid "gx/ipfs/QmYVNvtQkeZ6AKSwDrjQTs432QtL6umrrK41EBq3cu7iSP/go-cid"
Steven Allen's avatar
Steven Allen committed
14
	ma "gx/ipfs/QmYmsdtJ3HsodkePE3eU3TsCaP2YvPZJ4LoXnNkDE5Tpt7/go-multiaddr"
Steven Allen's avatar
Steven Allen committed
15
	routing "gx/ipfs/QmZ383TySJVeZWzGnWui6pRcKyYZk9VkKTuW7tmKRWk5au/go-libp2p-routing"
Jeromy's avatar
Jeromy committed
16
	ggio "gx/ipfs/QmZ4Qi3GaRbjcx28Sme5eMH7RQjGkt8wHxt2a65oLaeFEV/gogo-protobuf/io"
Steven Allen's avatar
Steven Allen committed
17 18 19 20
	pstore "gx/ipfs/QmZR2XWVVBCtbgBWnQhWk2xcQfaR3W8faQPriAiaaj7rsr/go-libp2p-peerstore"
	host "gx/ipfs/Qmb8T6YBBsjYsVGfrihQLfCJveczZnneSBqBKkYEBWDjge/go-libp2p-host"
	logging "gx/ipfs/QmcVVHfdyv15GVPk7NrxdWjh2hLVccXnoD8j2tyQShiXJb/go-log"
	peer "gx/ipfs/QmdVrMn1LhB4ybb8hMVaMLXnA8XRSewMnK6YqXKXoTcRvN/go-libp2p-peer"
21 22
)

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

25 26
var sendMessageTimeout = time.Minute * 10

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

39
	return &bitswapNetwork
40 41
}

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

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

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

func (s *streamMessageSender) Close() error {
Steven Allen's avatar
Steven Allen committed
57
	return inet.FullClose(s.s)
Jeromy's avatar
Jeromy committed
58 59
}

60 61 62 63
func (s *streamMessageSender) Reset() error {
	return s.s.Reset()
}

64 65
func (s *streamMessageSender) SendMsg(ctx context.Context, msg bsmsg.BitSwapMessage) error {
	return msgToStream(ctx, s.s, msg)
66 67
}

68 69 70 71 72 73 74 75 76 77
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)
	}

78 79 80 81 82 83 84 85 86 87 88 89 90 91
	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())
	}
92 93 94 95

	if err := s.SetWriteDeadline(time.Time{}); err != nil {
		log.Warningf("error resetting deadline: %s", err)
	}
96
	return nil
Jeromy's avatar
Jeromy committed
97 98 99 100 101 102 103 104 105 106 107
}

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
}

108
func (bsnet *impl) newStreamToPeer(ctx context.Context, p peer.ID) (inet.Stream, error) {
109
	return bsnet.host.NewStream(ctx, p, ProtocolBitswap, ProtocolBitswapOne, ProtocolBitswapNoVers)
110 111 112 113 114 115 116 117
}

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

	s, err := bsnet.newStreamToPeer(ctx, p)
118 119 120
	if err != nil {
		return err
	}
121

Steven Allen's avatar
Steven Allen committed
122
	if err = msgToStream(ctx, s, outgoing); err != nil {
123
		s.Reset()
Steven Allen's avatar
Steven Allen committed
124
		return err
125
	}
126 127 128 129
	// TODO(https://github.com/libp2p/go-libp2p-net/issues/28): Avoid this goroutine.
	go inet.AwaitEOF(s)
	return s.Close()

130 131
}

132 133
func (bsnet *impl) SetDelegate(r Receiver) {
	bsnet.receiver = r
134
}
135

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

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

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

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

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

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

	if bsnet.receiver == nil {
186
		s.Reset()
187 188 189
		return
	}

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

202 203 204 205 206
		p := s.Conn().RemotePeer()
		ctx := context.Background()
		log.Debugf("bitswap net handleNewStream from %s", s.Conn().RemotePeer())
		bsnet.receiver.ReceiveMessage(ctx, p, received)
	}
207
}
208

209 210 211 212
func (bsnet *impl) ConnectionManager() ifconnmgr.ConnManager {
	return bsnet.host.ConnManager()
}

213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
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
229 230
func (nn *netNotifiee) Listen(n inet.Network, a ma.Multiaddr)      {}
func (nn *netNotifiee) ListenClose(n inet.Network, a ma.Multiaddr) {}