-
Notifications
You must be signed in to change notification settings - Fork 31
/
peer_impl.go
103 lines (89 loc) · 2.42 KB
/
peer_impl.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package peer
import (
"context"
"fmt"
"net"
"net/netip"
"github.com/pkg/errors"
"github.com/wavesplatform/gowaves/pkg/p2p/conn"
"github.com/wavesplatform/gowaves/pkg/proto"
"go.uber.org/zap"
)
type peerImplID struct {
addr16 [16]byte
nonce uint64
}
func newPeerImplID(addr net.Addr, nonce uint64) (peerImplID, error) {
var (
netStr = addr.Network()
addrStr = addr.String()
)
tcpAddr, err := net.ResolveTCPAddr(netStr, addrStr)
if err != nil {
return peerImplID{}, errors.Wrapf(err, "failed to resolve '%s' addr from '%s'", netStr, addrStr)
}
var addr16 [16]byte
copy(addr16[:], tcpAddr.IP.To16())
return peerImplID{addr16: addr16, nonce: nonce}, nil
}
func (id peerImplID) String() string {
addr := netip.AddrFrom16(id.addr16).Unmap()
return fmt.Sprintf("%s-%d", addr.String(), id.nonce)
}
type PeerImpl struct {
handshake proto.Handshake
conn conn.Connection
direction Direction
remote Remote
id peerImplID
cancel context.CancelFunc
}
func NewPeerImpl(handshake proto.Handshake, conn conn.Connection, direction Direction, remote Remote, cancel context.CancelFunc) (*PeerImpl, error) {
id, err := newPeerImplID(conn.Conn().RemoteAddr(), handshake.NodeNonce)
if err != nil {
return nil, errors.Wrap(err, "failed to create new peer")
}
return &PeerImpl{
handshake: handshake,
conn: conn,
direction: direction,
remote: remote,
id: id,
cancel: cancel,
}, nil
}
func (a *PeerImpl) Direction() Direction {
return a.direction
}
func (a *PeerImpl) Close() error {
defer a.cancel()
return a.conn.Close()
}
// SendMessage marshals provided message and sends it to its internal Remote.ToCh channel.
// It sends the error to internal Remote.ErrCh if Remote.ToCh is full.
// That notifies Handle to propagate this error to FMS through Parent.InfoCh.
func (a *PeerImpl) SendMessage(m proto.Message) {
b, err := m.MarshalBinary()
if err != nil {
zap.S().Errorf("Failed to send message %T: %v", m, err)
return
}
select {
case a.remote.ToCh <- b:
default:
a.remote.ErrCh <- errors.Errorf("remote, chan is full id %s, name %s", a.ID(), a.handshake.NodeName)
}
}
func (a *PeerImpl) ID() ID {
return a.id
}
func (a *PeerImpl) Connection() conn.Connection {
return a.conn
}
func (a *PeerImpl) Handshake() proto.Handshake {
return a.handshake
}
func (a *PeerImpl) RemoteAddr() proto.TCPAddr {
addr := a.Connection().Conn().RemoteAddr().(*net.TCPAddr)
return proto.TCPAddr(*addr)
}