conn.go 2.18 KB
Newer Older
1
2
3
4
5
package libp2pquic

import (
	"net"

6
7
	ic "github.com/libp2p/go-libp2p-crypto"
	peer "github.com/libp2p/go-libp2p-peer"
8
	tpt "github.com/libp2p/go-libp2p-transport"
9
	smux "github.com/libp2p/go-stream-muxer"
10
11
12
13
14
	quic "github.com/lucas-clemente/quic-go"
	ma "github.com/multiformats/go-multiaddr"
	manet "github.com/multiformats/go-multiaddr-net"
)

15
type conn struct {
16
17
18
	sess      quic.Session
	transport tpt.Transport

19
20
21
	localPeer      peer.ID
	privKey        ic.PrivKey
	localMultiaddr ma.Multiaddr
22

23
24
25
	remotePeerID    peer.ID
	remotePubKey    ic.PubKey
	remoteMultiaddr ma.Multiaddr
26
27
}

28
var _ tpt.Conn = &conn{}
29

30
31
func (c *conn) Close() error {
	return c.sess.Close(nil)
32
33
}

34
35
36
// IsClosed returns whether a connection is fully closed.
func (c *conn) IsClosed() bool {
	return c.sess.Context().Err() != nil
37
38
}

39
40
41
42
// OpenStream creates a new stream.
func (c *conn) OpenStream() (smux.Stream, error) {
	qstr, err := c.sess.OpenStreamSync()
	return &stream{Stream: qstr}, err
43
44
}

45
46
47
48
// AcceptStream accepts a stream opened by the other side.
func (c *conn) AcceptStream() (smux.Stream, error) {
	qstr, err := c.sess.AcceptStream()
	return &stream{Stream: qstr}, err
49
50
}

51
52
53
// LocalPeer returns our peer ID
func (c *conn) LocalPeer() peer.ID {
	return c.localPeer
54
55
}

56
57
58
// LocalPrivateKey returns our private key
func (c *conn) LocalPrivateKey() ic.PrivKey {
	return c.privKey
59
60
}

61
62
63
// RemotePeer returns the peer ID of the remote peer.
func (c *conn) RemotePeer() peer.ID {
	return c.remotePeerID
64
65
}

66
67
68
// RemotePublicKey returns the public key of the remote peer.
func (c *conn) RemotePublicKey() ic.PubKey {
	return c.remotePubKey
69
70
}

71
72
73
// LocalMultiaddr returns the local Multiaddr associated
func (c *conn) LocalMultiaddr() ma.Multiaddr {
	return c.localMultiaddr
74
75
}

76
77
78
// RemoteMultiaddr returns the remote Multiaddr associated
func (c *conn) RemoteMultiaddr() ma.Multiaddr {
	return c.remoteMultiaddr
79
80
}

81
func (c *conn) Transport() tpt.Transport {
82
83
84
85
	return c.transport
}

// TODO: there must be a better way to do this
86
func quicMultiaddr(na net.Addr) (ma.Multiaddr, error) {
87
88
89
90
91
92
93
94
95
96
	udpMA, err := manet.FromNetAddr(na)
	if err != nil {
		return nil, err
	}
	quicMA, err := ma.NewMultiaddr(udpMA.String() + "/quic")
	if err != nil {
		return nil, err
	}
	return quicMA, nil
}