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

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

6
	key "github.com/ipfs/go-ipfs/blocks/key"
7 8
	bsmsg "github.com/ipfs/go-ipfs/exchange/bitswap/message"
	routing "github.com/ipfs/go-ipfs/routing"
Jeromy's avatar
Jeromy committed
9 10

	peer "gx/ipfs/QmQGwpJy9P4yXZySmqkZEXCmbBpJUb8xntCv8Ca4taZwDC/go-libp2p-peer"
Jeromy's avatar
Jeromy committed
11 12
	host "gx/ipfs/QmXJBB9U6e6ennAJPzk8E2rSaVGuHVR2jCxE9H9gPDtRrq/go-libp2p/p2p/host"
	inet "gx/ipfs/QmXJBB9U6e6ennAJPzk8E2rSaVGuHVR2jCxE9H9gPDtRrq/go-libp2p/p2p/net"
Jakub Sztandera's avatar
Jakub Sztandera committed
13
	logging "gx/ipfs/QmYtB7Qge8cJpXc4irsEp8zRqfnZMBeB7aTrMEkPk67DRv/go-log"
14
	ma "gx/ipfs/QmYzDkkgAEmrcNzFCiYo6L1dTX4EAG1gZkbtdbd9trL4vd/go-multiaddr"
Jeromy's avatar
Jeromy committed
15
	ggio "gx/ipfs/QmZ4Qi3GaRbjcx28Sme5eMH7RQjGkt8wHxt2a65oLaeFEV/gogo-protobuf/io"
Jeromy's avatar
Jeromy committed
16
	pstore "gx/ipfs/QmZ62t46e9p7vMYqCmptwQC1RhRv5cpQ5cwoqYspedaXyq/go-libp2p-peerstore"
Jeromy's avatar
Jeromy committed
17
	context "gx/ipfs/QmZy2y8t9zQH2a1b8q2ZSLKp17ATuJoCNxxyMFG5qFExpt/go-net/context"
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 23
// NewFromIpfsHost returns a BitSwapNetwork supported by underlying IPFS host
func NewFromIpfsHost(host host.Host, r routing.IpfsRouting) 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 30 31
	host.Network().Notify((*netNotifiee)(&bitswapNetwork))
	// TODO: StopNotify.

32
	return &bitswapNetwork
33 34
}

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

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

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

47 48
	// first, make sure we're connected.
	// if this fails, we cannot connect to given peer.
49
	//TODO(jbenet) move this into host.NewStream?
Jeromy's avatar
Jeromy committed
50
	if err := bsnet.host.Connect(ctx, pstore.PeerInfo{ID: p}); err != nil {
51
		return nil, err
52 53
	}

54
	return bsnet.host.NewStream(ctx, ProtocolBitswap, p)
55 56 57 58 59 60 61 62
}

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

	s, err := bsnet.newStreamToPeer(ctx, p)
63 64 65
	if err != nil {
		return err
	}
66 67
	defer s.Close()

68
	if err := outgoing.ToNet(s); err != nil {
69
		log.Debugf("error: %s", err)
70 71 72 73
		return err
	}

	return err
74 75
}

76
func (bsnet *impl) SendRequest(
77
	ctx context.Context,
78
	p peer.ID,
79 80
	outgoing bsmsg.BitSwapMessage) (bsmsg.BitSwapMessage, error) {

81
	s, err := bsnet.newStreamToPeer(ctx, p)
82 83 84
	if err != nil {
		return nil, err
	}
85 86 87
	defer s.Close()

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

92 93
	incoming, err := bsmsg.FromNet(s)
	if err != nil {
94
		log.Debugf("error: %s", err)
95 96 97 98
		return incoming, err
	}

	return incoming, nil
99 100
}

101 102
func (bsnet *impl) SetDelegate(r Receiver) {
	bsnet.receiver = r
103
}
104

105
func (bsnet *impl) ConnectTo(ctx context.Context, p peer.ID) error {
Jeromy's avatar
Jeromy committed
106
	return bsnet.host.Connect(ctx, pstore.PeerInfo{ID: p})
107 108
}

109
// FindProvidersAsync returns a channel of providers for the given key
110
func (bsnet *impl) FindProvidersAsync(ctx context.Context, k key.Key, max int) <-chan peer.ID {
111 112 113 114 115 116 117 118 119

	// 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
120
	for _, id := range connectedPeers {
121 122 123
		if id == bsnet.host.ID() {
			continue // ignore self as provider
		}
124 125 126
		out <- id
	}

127 128 129 130
	go func() {
		defer close(out)
		providers := bsnet.routing.FindProvidersAsync(ctx, k, max)
		for info := range providers {
131 132
			if info.ID == bsnet.host.ID() {
				continue // ignore self as provider
133
			}
Jeromy's avatar
Jeromy committed
134
			bsnet.host.Peerstore().AddAddrs(info.ID, info.Addrs, pstore.TempAddrTTL)
135 136
			select {
			case <-ctx.Done():
137
				return
138 139 140 141 142
			case out <- info.ID:
			}
		}
	}()
	return out
143 144 145
}

// Provide provides the key to the network
146
func (bsnet *impl) Provide(ctx context.Context, k key.Key) error {
147 148 149
	return bsnet.routing.Provide(ctx, k)
}

150 151
// handleNewStream receives a new stream from the network.
func (bsnet *impl) handleNewStream(s inet.Stream) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
152
	defer s.Close()
153 154 155 156 157

	if bsnet.receiver == nil {
		return
	}

Jeromy's avatar
Jeromy committed
158
	reader := ggio.NewDelimitedReader(s, inet.MessageSizeMax)
159
	for {
Jeromy's avatar
Jeromy committed
160
		received, err := bsmsg.FromPBReader(reader)
161
		if err != nil {
Jeromy's avatar
Jeromy committed
162 163 164 165
			if err != io.EOF {
				go bsnet.receiver.ReceiveError(err)
				log.Debugf("bitswap net handleNewStream from %s error: %s", s.Conn().RemotePeer(), err)
			}
166 167
			return
		}
168

169 170 171 172 173
		p := s.Conn().RemotePeer()
		ctx := context.Background()
		log.Debugf("bitswap net handleNewStream from %s", s.Conn().RemotePeer())
		bsnet.receiver.ReceiveMessage(ctx, p, received)
	}
174
}
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191

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