ipfs_impl.go 2.09 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
func (bsnet *impl) DialPeer(ctx context.Context, p peer.ID) error {
	return bsnet.network.DialPeer(ctx, p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
35 36
}

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

42
	s, err := bsnet.network.NewStream(inet.ProtocolBitswap, p)
43 44 45
	if err != nil {
		return err
	}
46 47 48
	defer s.Close()

	return outgoing.ToNet(s)
49 50
}

51
func (bsnet *impl) SendRequest(
52
	ctx context.Context,
53
	p peer.ID,
54 55
	outgoing bsmsg.BitSwapMessage) (bsmsg.BitSwapMessage, error) {

56
	s, err := bsnet.network.NewStream(inet.ProtocolBitswap, p)
57 58 59
	if err != nil {
		return nil, err
	}
60 61 62
	defer s.Close()

	if err := outgoing.ToNet(s); err != nil {
63 64
		return nil, err
	}
65 66

	return bsmsg.FromNet(s)
67 68
}

69 70
func (bsnet *impl) SetDelegate(r Receiver) {
	bsnet.receiver = r
71
}
72

73 74 75 76
func (bsnet *impl) Peerstore() peer.Peerstore {
	return bsnet.Peerstore()
}

77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
// handleNewStream receives a new stream from the network.
func (bsnet *impl) handleNewStream(s inet.Stream) {

	if bsnet.receiver == nil {
		return
	}

	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)
	}()

}