-
Notifications
You must be signed in to change notification settings - Fork 0
/
peer.go
329 lines (287 loc) · 8.79 KB
/
peer.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
package peer
import (
"context"
"encoding/hex"
"errors"
"fmt"
"net"
"sync"
"time"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
"github.com/dnerochain/dnero/common"
cmn "github.com/dnerochain/dnero/common"
"github.com/dnerochain/dnero/crypto"
cn "github.com/dnerochain/dnero/p2p/connection"
nu "github.com/dnerochain/dnero/p2p/netutil"
p2ptypes "github.com/dnerochain/dnero/p2p/types"
"github.com/dnerochain/dnero/rlp"
)
var logger *log.Entry = log.WithFields(log.Fields{"prefix": "p2p"})
const maxExtraHandshakeInfo = 4096
//
// Peer models a peer node in a network
//
type Peer struct {
connection *cn.Connection
isPersistent bool
isOutbound bool
isSeed bool
netAddress *nu.NetAddress
nodeInfo p2ptypes.NodeInfo // information of the blockchain node of the peer
config PeerConfig
// Life cycle
wg *sync.WaitGroup
quit chan struct{}
ctx context.Context
cancel context.CancelFunc
stopped bool
}
//
// PeerConfig specifies the configuration of a peer
//
type PeerConfig struct {
HandshakeTimeout time.Duration
DialTimeout time.Duration
}
// CreateOutboundPeer creates an instance of an outbound peer
func CreateOutboundPeer(peerAddr *nu.NetAddress, peerConfig PeerConfig, connConfig cn.ConnectionConfig) (*Peer, error) {
netconn, err := dial(peerAddr, peerConfig)
if err != nil {
logger.Debugf("Error dialing the peer: %v", peerAddr)
return nil, err
}
peer := createPeer(netconn, true, peerConfig, connConfig)
if peer == nil {
return nil, errors.New("Failed to create outbound peer")
}
return peer, nil
}
// CreateInboundPeer creates an instance of an inbound peer
func CreateInboundPeer(netconn net.Conn, peerConfig PeerConfig, connConfig cn.ConnectionConfig) (*Peer, error) {
peer := createPeer(netconn, false, peerConfig, connConfig)
if peer == nil {
return nil, errors.New("Failed to create inbound peer")
}
return peer, nil
}
// GetDefaultPeerConfig creates the default PeerConfig
func GetDefaultPeerConfig() PeerConfig {
return PeerConfig{
HandshakeTimeout: 10 * time.Second,
DialTimeout: 10 * time.Second,
}
}
// Start is called when the peer starts
// NOTE: need to call peer.Handshake() before peer.Start()
func (peer *Peer) Start(ctx context.Context) bool {
c, cancel := context.WithCancel(ctx)
peer.ctx = c
peer.cancel = cancel
success := peer.connection.Start(c)
return success
}
// Wait suspends the caller goroutine
func (peer *Peer) Wait() {
peer.wg.Wait()
}
// CancelConnection for testing purpose only
func (peer *Peer) CancelConnection() {
peer.connection.CancelConnection()
}
// Stop is called when the peer stops
func (peer *Peer) Stop() {
peer.connection.Stop()
}
// Handshake handles the initial signaling between two peers
// NOTE: need to call peer.Handshake() before peer.Start()
func (peer *Peer) Handshake(sourceNodeInfo *p2ptypes.NodeInfo) error {
remoteAddr := peer.connection.GetNetconn().RemoteAddr()
logger.Infof("Handshaking with %v...", remoteAddr)
timeout := peer.config.HandshakeTimeout
peer.connection.GetNetconn().SetDeadline(time.Now().Add(timeout))
var s *rlp.Stream
var sendError error
var recvError error
targetPeerNodeInfo := p2ptypes.NodeInfo{}
cmn.Parallel(
func() {
sendError = rlp.Encode(peer.connection.GetBufNetconn(), sourceNodeInfo)
},
func() {
s = rlp.NewStream(peer.connection.GetBufReader(), 1024)
recvError = s.Decode(&targetPeerNodeInfo)
},
)
if sendError != nil {
logger.Errorf("Error during handshake/send: %v", sendError)
return sendError
}
if recvError != nil {
logger.Errorf("Error during handshake/recv: %v", recvError)
return recvError
}
netconn := peer.connection.GetNetconn()
targetNodePubKey, err := crypto.PublicKeyFromBytes(targetPeerNodeInfo.PubKeyBytes)
if err != nil {
logger.Errorf("Error during handshake/recv: %v", err)
return err
}
targetPeerNodeInfo.PubKey = targetNodePubKey
peer.nodeInfo = targetPeerNodeInfo
// Forward compatibility.
localChainID := viper.GetString(common.CfgGenesisChainID)
cmn.Parallel(
func() {
sendError = rlp.Encode(peer.connection.GetBufNetconn(), localChainID)
if sendError != nil {
return
}
sendError = rlp.Encode(peer.connection.GetBufNetconn(), "EOH")
},
func() {
var msg string
recvError = s.Decode(&msg)
if recvError != nil {
return
}
if msg == "EOH" {
return
}
if msg != localChainID {
recvError = fmt.Errorf("ChainID mismatch: peer chainID: %v, local ChainID: %v", msg, localChainID)
return
}
logger.Infof("Peer ChainID: %v", msg)
for {
recvError = s.Decode(&msg)
if recvError != nil {
return
}
if msg == "EOH" {
return
}
}
},
)
if sendError != nil {
logger.Errorf("Error during handshake/send extra info: %v", sendError)
return sendError
}
if recvError != nil {
logger.Errorf("Error during handshake/recv extra info: %v", recvError)
return recvError
}
remotePub, err := peer.connection.DoEncHandshake(
crypto.PrivKeyToECDSA(sourceNodeInfo.PrivKey), crypto.PubKeyToECDSA(targetNodePubKey))
if err != nil {
logger.Errorf("Error during handshake/key exchange: %v", err)
return err
} else {
if remotePub.Address() != targetNodePubKey.Address() {
err = fmt.Errorf("expected remote address: %v, actual address: %v", targetNodePubKey.Address(), remotePub.Address())
logger.Errorf("Error during handshake/key exchange: %v", err)
return err
}
}
logger.Infof("Using encrypted transport for peer: %v", targetNodePubKey.Address())
if !peer.isOutbound {
peer.SetNetAddress(nu.NewNetAddressWithEnforcedPort(netconn.RemoteAddr(), int(peer.nodeInfo.Port)))
}
netconn.SetDeadline(time.Time{})
logger.Infof("Handshake completed, target address: %v, target public key: %v, address: %v",
remoteAddr, hex.EncodeToString(targetNodePubKey.ToBytes()), targetNodePubKey.Address())
return nil
}
// Send sends the given message through the specified channel to the target peer
func (peer *Peer) Send(channelID cmn.ChannelIDEnum, message interface{}) bool {
success := peer.connection.EnqueueMessage(channelID, message)
return success
}
// AttemptToSend attempts to send the given message through the specified channel to the target peer (non-blocking)
func (peer *Peer) AttemptToSend(channelID cmn.ChannelIDEnum, message interface{}) bool {
success := peer.connection.AttemptToEnqueueMessage(channelID, message)
return success
}
// CanSend indicates whether more messages can be sent through the specified channel
func (peer *Peer) CanSend(channelID cmn.ChannelIDEnum) bool {
canSend := peer.connection.CanEnqueueMessage(channelID)
return canSend
}
// GetConnection returns the connection object attached to the peer
func (peer *Peer) GetConnection() *cn.Connection {
return peer.connection
}
// GetRemoteAddress returns the remote address of the peer
func (peer *Peer) GetRemoteAddress() net.Addr {
return peer.connection.GetNetconn().RemoteAddr()
}
// SetPersistency sets the persistency for the given peer
func (peer *Peer) SetPersistency(persistent bool) {
peer.isPersistent = persistent
}
// IsPersistent returns whether the peer is persistent
func (peer *Peer) IsPersistent() bool {
return peer.isPersistent
}
// IsOutbound returns whether the peer is an outbound peer
func (peer *Peer) IsOutbound() bool {
return peer.isOutbound
}
// SetSeed sets the isSeed for the given peer
func (peer *Peer) SetSeed(isSeed bool) {
peer.isSeed = isSeed
}
// IsSeed returns whether the peer is a seed peer
func (peer *Peer) IsSeed() bool {
return peer.isSeed
}
// SetNetAddress sets the network address of the peer
func (peer *Peer) SetNetAddress(netAddr *nu.NetAddress) {
peer.netAddress = netAddr
}
// NetAddress returns the network address of the peer
func (peer *Peer) NetAddress() *nu.NetAddress {
return peer.netAddress
}
// SetPort sets the network port of the peer
func (peer *Peer) SetPort(port uint16) {
peer.netAddress.Port = port
peer.nodeInfo.Port = port
}
// ID returns the unique idenitifier of the peer in the P2P network
func (peer *Peer) ID() string {
peerID := peer.nodeInfo.PubKey.Address() // use the blockchain address as the peer ID
id := peerID.Hex()
return id
}
func dial(addr *nu.NetAddress, config PeerConfig) (net.Conn, error) {
netconn, err := addr.DialTimeout(config.DialTimeout)
if err != nil {
return nil, err
}
return netconn, nil
}
func createPeer(netconn net.Conn, isOutbound bool,
peerConfig PeerConfig, connConfig cn.ConnectionConfig) *Peer {
connection := cn.CreateConnection(netconn, connConfig)
if connection == nil {
logger.Errorf("Failed to create connection")
if netconn != nil {
netconn.Close()
}
return nil
}
var netAddress *nu.NetAddress
if isOutbound {
netAddress = nu.NewNetAddress(netconn.RemoteAddr())
}
peer := &Peer{
connection: connection,
isOutbound: isOutbound,
netAddress: netAddress,
config: peerConfig,
wg: &sync.WaitGroup{},
}
return peer
}