ipfs_impl.go 2.03 KB
Newer Older
1 2 3 4 5 6
package network

import (
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"

	bsmsg "github.com/jbenet/go-ipfs/exchange/bitswap/message"
7
	inet "github.com/jbenet/go-ipfs/net"
8
	peer "github.com/jbenet/go-ipfs/peer"
9
	util "github.com/jbenet/go-ipfs/util"
10 11
)

12
var log = util.Logger("bitswap_network")
Jeromy's avatar
Jeromy committed
13

14
// NewFromIpfsNetwork returns a BitSwapNetwork supported by underlying IPFS
15
// Dialer & Service
16
func NewFromIpfsNetwork(n inet.Network) BitSwapNetwork {
17
	bitswapNetwork := impl{
18
		network: n,
19
	}
20
	n.SetHandler(inet.ProtocolBitswap, bitswapNetwork.handleNewStream)
21
	return &bitswapNetwork
22 23
}

24 25
// impl transforms the ipfs network interface, which sends and receives
// NetMessage objects, into the bitswap network interface.
26
type impl struct {
27
	network inet.Network
28 29 30

	// inbound messages from the network are forwarded to the receiver
	receiver Receiver
31 32
}

33 34
// handleNewStream receives a new stream from the network.
func (bsnet *impl) handleNewStream(s inet.Stream) {
35

36
	if bsnet.receiver == nil {
37
		return
38 39
	}

40 41 42 43 44 45 46 47 48 49 50 51 52
	go func() {
		defer s.Close()

		received, err := bsmsg.FromNet(s)
		if err != nil {
			go bsnet.receiver.ReceiveError(err)
			return
		}

		p := s.Conn().RemotePeer()
		ctx := context.Background()
		bsnet.receiver.ReceiveMessage(ctx, p, received)
	}()
53 54 55

}

56
func (bsnet *impl) DialPeer(ctx context.Context, p peer.Peer) error {
57
	return bsnet.network.DialPeer(ctx, p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
58 59
}

60
func (bsnet *impl) SendMessage(
61
	ctx context.Context,
62
	p peer.Peer,
63 64
	outgoing bsmsg.BitSwapMessage) error {

65
	s, err := bsnet.network.NewStream(inet.ProtocolBitswap, p)
66 67 68
	if err != nil {
		return err
	}
69 70 71
	defer s.Close()

	return outgoing.ToNet(s)
72 73
}

74
func (bsnet *impl) SendRequest(
75
	ctx context.Context,
76
	p peer.Peer,
77 78
	outgoing bsmsg.BitSwapMessage) (bsmsg.BitSwapMessage, error) {

79
	s, err := bsnet.network.NewStream(inet.ProtocolBitswap, p)
80 81 82
	if err != nil {
		return nil, err
	}
83 84 85
	defer s.Close()

	if err := outgoing.ToNet(s); err != nil {
86 87
		return nil, err
	}
88 89

	return bsmsg.FromNet(s)
90 91
}

92 93
func (bsnet *impl) SetDelegate(r Receiver) {
	bsnet.receiver = r
94
}