forked from iotexproject/iotex-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
agent.go
405 lines (374 loc) · 11.7 KB
/
agent.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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
// Copyright (c) 2018 IoTeX
// This is an alpha (internal) release and is not suitable for production. This source code is provided 'as is' and no
// warranties are given as to title or non-infringement, merchantability or fitness for purpose and, to the extent
// permitted by law, all liability for your use of the code is disclaimed. This source code is governed by Apache
// License 2.0 that can be found in the LICENSE file.
package p2p
import (
"context"
"encoding/hex"
"fmt"
"io"
"math"
"strconv"
"strings"
"time"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes"
p2p "github.com/iotexproject/go-p2p"
peerstore "github.com/libp2p/go-libp2p-peerstore"
multiaddr "github.com/multiformats/go-multiaddr"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"go.uber.org/zap"
"github.com/iotexproject/iotex-core/config"
"github.com/iotexproject/iotex-core/pkg/log"
"github.com/iotexproject/iotex-core/protogen"
"github.com/iotexproject/iotex-core/protogen/iotexrpc"
)
const (
successStr = "success"
failureStr = "failure"
)
var (
p2pMsgCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "iotex_p2p_message_counter",
Help: "P2P message stats",
},
[]string{"protocol", "message", "direction", "peer", "status"},
)
p2pMsgLatency = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "iotex_p2p_message_latency",
Help: "message latency",
Buckets: prometheus.LinearBuckets(0, 10, 200),
},
[]string{"protocol", "message", "status"},
)
)
func init() {
prometheus.MustRegister(p2pMsgCounter)
prometheus.MustRegister(p2pMsgLatency)
}
const (
// TODO: the topic could be fine tuned
broadcastTopic = "broadcast"
unicastTopic = "unicast"
numDialRetries = 8
dialRetryInterval = 2 * time.Second
)
type (
// HandleBroadcastInbound handles broadcast message when agent listens it from the network
HandleBroadcastInbound func(context.Context, uint32, proto.Message)
// HandleUnicastInboundAsync handles unicast message when agent listens it from the network
HandleUnicastInboundAsync func(context.Context, uint32, peerstore.PeerInfo, proto.Message)
)
// Agent is the agent to help the blockchain node connect into the P2P networks and send/receive messages
type Agent struct {
cfg config.Network
topicSuffix string
broadcastInboundHandler HandleBroadcastInbound
unicastInboundAsyncHandler HandleUnicastInboundAsync
host *p2p.Host
}
// NewAgent instantiates a local P2P agent instance
func NewAgent(cfg config.Config, broadcastHandler HandleBroadcastInbound, unicastHandler HandleUnicastInboundAsync) *Agent {
gh := cfg.Genesis.Hash()
return &Agent{
cfg: cfg.Network,
// Make sure the honest node only care the messages related the chain from the same genesis
topicSuffix: hex.EncodeToString(gh[22:]), // last 10 bytes of genesis hash
broadcastInboundHandler: broadcastHandler,
unicastInboundAsyncHandler: unicastHandler,
}
}
// Start connects into P2P network
func (p *Agent) Start(ctx context.Context) error {
ready := make(chan interface{})
p2p.SetLogger(log.L())
opts := []p2p.Option{
p2p.HostName(p.cfg.Host),
p2p.Port(p.cfg.Port),
p2p.Gossip(),
p2p.SecureIO(),
p2p.MasterKey(p.cfg.MasterKey),
}
if p.cfg.EnableRateLimit {
opts = append(opts, p2p.WithRateLimit(p.cfg.RateLimit))
}
if p.cfg.ExternalHost != "" {
opts = append(opts, p2p.ExternalHostName(p.cfg.ExternalHost))
opts = append(opts, p2p.ExternalPort(p.cfg.ExternalPort))
}
if p.cfg.RelayType != "" {
opts = append(opts, p2p.WithRelay(p.cfg.RelayType))
}
host, err := p2p.NewHost(ctx, opts...)
if err != nil {
return errors.Wrap(err, "error when instantiating Agent host")
}
if err := host.AddBroadcastPubSub(broadcastTopic+p.topicSuffix, func(ctx context.Context, data []byte) (err error) {
// Blocking handling the broadcast message until the agent is started
<-ready
var (
peerID string
broadcast iotexrpc.BroadcastMsg
latency int64
)
skip := false
defer func() {
// Skip accounting if the broadcast message is not handled
if skip {
return
}
status := successStr
if err != nil {
status = failureStr
}
p2pMsgCounter.WithLabelValues("broadcast", strconv.Itoa(int(broadcast.MsgType)), "in", peerID, status).Inc()
p2pMsgLatency.WithLabelValues("broadcast", strconv.Itoa(int(broadcast.MsgType)), status).Observe(float64(latency))
}()
if err = proto.Unmarshal(data, &broadcast); err != nil {
err = errors.Wrap(err, "error when marshaling broadcast message")
return
}
// Skip the broadcast message if it's from the node itself
rawmsg, ok := p2p.GetBroadcastMsg(ctx)
if !ok {
err = errors.New("error when asserting broadcast msg context")
return
}
peerID = rawmsg.GetFrom().Pretty()
if p.host.HostIdentity() == peerID {
skip = true
return
}
t, _ := ptypes.Timestamp(broadcast.GetTimestamp())
latency = time.Since(t).Nanoseconds() / time.Millisecond.Nanoseconds()
msg, err := protogen.TypifyRPCMsg(broadcast.MsgType, broadcast.MsgBody)
if err != nil {
err = errors.Wrap(err, "error when typifying broadcast message")
return
}
p.broadcastInboundHandler(ctx, broadcast.ChainId, msg)
return
}); err != nil {
return errors.Wrap(err, "error when adding broadcast pubsub")
}
if err := host.AddUnicastPubSub(unicastTopic+p.topicSuffix, func(ctx context.Context, _ io.Writer, data []byte) (err error) {
// Blocking handling the unicast message until the agent is started
<-ready
var (
unicast iotexrpc.UnicastMsg
peerID string
latency int64
)
defer func() {
status := successStr
if err != nil {
status = failureStr
}
p2pMsgCounter.WithLabelValues("unicast", strconv.Itoa(int(unicast.MsgType)), "in", peerID, status).Inc()
p2pMsgLatency.WithLabelValues("unicast", strconv.Itoa(int(unicast.MsgType)), status).Observe(float64(latency))
}()
if err = proto.Unmarshal(data, &unicast); err != nil {
err = errors.Wrap(err, "error when marshaling unicast message")
return
}
msg, err := protogen.TypifyRPCMsg(unicast.MsgType, unicast.MsgBody)
if err != nil {
err = errors.Wrap(err, "error when typifying unicast message")
return
}
t, _ := ptypes.Timestamp(unicast.GetTimestamp())
latency = time.Since(t).Nanoseconds() / time.Millisecond.Nanoseconds()
stream, ok := p2p.GetUnicastStream(ctx)
if !ok {
err = errors.Wrap(err, "error when typifying unicast message")
return
}
peerID = stream.Conn().RemotePeer().Pretty()
peerInfo := peerstore.PeerInfo{
ID: stream.Conn().RemotePeer(),
Addrs: []multiaddr.Multiaddr{stream.Conn().RemoteMultiaddr()},
}
p.unicastInboundAsyncHandler(ctx, unicast.ChainId, peerInfo, msg)
return
}); err != nil {
return errors.Wrap(err, "error when adding unicast pubsub")
}
if len(p.cfg.BootstrapNodes) > 0 {
var tryNum, errNum, connNum, desiredConnNum int
conn := make(chan interface{}, len(p.cfg.BootstrapNodes))
connErrChan := make(chan error, len(p.cfg.BootstrapNodes))
desiredConnNum = int(math.RoundToEven(float64(len(p.cfg.BootstrapNodes)) / 2))
if float64(desiredConnNum) <= float64(len(p.cfg.BootstrapNodes))/2 {
desiredConnNum++
}
// try to connect to all bootstrap node beside itself.
for _, bootstrapNode := range p.cfg.BootstrapNodes {
bootAddr := multiaddr.StringCast(bootstrapNode)
if strings.Contains(bootAddr.String(), host.HostIdentity()) {
continue
}
tryNum++
go func() {
if err := exponentialRetry(
func() error { return host.ConnectWithMultiaddr(ctx, bootAddr) },
dialRetryInterval,
numDialRetries,
); err != nil {
err := errors.Wrap(err, fmt.Sprintf("error when connecting bootstrap node %s", bootAddr.String()))
connErrChan <- err
return
}
conn <- true
log.L().Info("Connected bootstrap node.", zap.String("address", bootAddr.String()))
}()
}
// wait on bootnodes connection
for {
select {
case err := <-connErrChan:
log.L().Info("Connection failed.", zap.Error(err))
errNum++
if errNum == tryNum {
return errors.New("failed to connect to any bootstrap node")
}
case <-conn:
connNum++
}
// can add more condition later
if connNum >= desiredConnNum {
break
}
}
}
host.JoinOverlay(ctx)
p.host = host
close(ready)
return nil
}
// Stop disconnects from P2P network
func (p *Agent) Stop(ctx context.Context) error {
if p.host == nil {
return nil
}
if err := p.host.Close(); err != nil {
return errors.Wrap(err, "error when closing Agent host")
}
return nil
}
// BroadcastOutbound sends a broadcast message to the whole network
func (p *Agent) BroadcastOutbound(ctx context.Context, msg proto.Message) (err error) {
var msgType iotexrpc.MessageType
var msgBody []byte
defer func() {
status := successStr
if err != nil {
status = failureStr
}
p2pMsgCounter.WithLabelValues(
"broadcast",
strconv.Itoa(int(msgType)),
"out",
p.host.HostIdentity(),
status,
).Inc()
}()
msgType, msgBody, err = convertAppMsg(msg)
if err != nil {
return
}
p2pCtx, ok := GetContext(ctx)
if !ok {
err = errors.New("P2P context doesn't exist")
return
}
broadcast := iotexrpc.BroadcastMsg{
ChainId: p2pCtx.ChainID,
PeerId: p.host.HostIdentity(),
MsgType: msgType,
MsgBody: msgBody,
Timestamp: ptypes.TimestampNow(),
}
data, err := proto.Marshal(&broadcast)
if err != nil {
err = errors.Wrap(err, "error when marshaling broadcast message")
return err
}
if err = p.host.Broadcast(broadcastTopic+p.topicSuffix, data); err != nil {
err = errors.Wrap(err, "error when sending broadcast message")
return err
}
return err
}
// UnicastOutbound sends a unicast message to the given address
func (p *Agent) UnicastOutbound(ctx context.Context, peer peerstore.PeerInfo, msg proto.Message) (err error) {
var msgType iotexrpc.MessageType
var msgBody []byte
defer func() {
status := successStr
if err != nil {
status = failureStr
}
p2pMsgCounter.WithLabelValues("unicast", strconv.Itoa(int(msgType)), "out", peer.ID.Pretty(), status).Inc()
}()
msgType, msgBody, err = convertAppMsg(msg)
if err != nil {
return
}
p2pCtx, ok := GetContext(ctx)
if !ok {
err = errors.New("P2P context doesn't exist")
return
}
unicast := iotexrpc.UnicastMsg{
ChainId: p2pCtx.ChainID,
PeerId: p.host.HostIdentity(),
MsgType: msgType,
MsgBody: msgBody,
Timestamp: ptypes.TimestampNow(),
}
data, err := proto.Marshal(&unicast)
if err != nil {
err = errors.Wrap(err, "error when marshaling unicast message")
return err
}
if err = p.host.Unicast(ctx, peer, unicastTopic+p.topicSuffix, data); err != nil {
err = errors.Wrap(err, "error when sending unicast message")
return err
}
return err
}
// Info returns agents' peer info.
func (p *Agent) Info() peerstore.PeerInfo { return p.host.Info() }
// Self returns the self network address
func (p *Agent) Self() []multiaddr.Multiaddr { return p.host.Addresses() }
// Neighbors returns the neighbors' peer info
func (p *Agent) Neighbors(ctx context.Context) ([]peerstore.PeerInfo, error) {
return p.host.Neighbors(ctx)
}
func convertAppMsg(msg proto.Message) (iotexrpc.MessageType, []byte, error) {
msgType, err := protogen.GetTypeFromRPCMsg(msg)
if err != nil {
return 0, nil, errors.Wrap(err, "error when converting application message to proto")
}
msgBody, err := proto.Marshal(msg)
if err != nil {
return 0, nil, errors.Wrap(err, "error when marshaling application message")
}
return msgType, msgBody, nil
}
func exponentialRetry(f func() error, retryInterval time.Duration, numRetries int) (err error) {
for i := 0; i < numRetries; i++ {
if err = f(); err == nil {
return
}
log.L().Error("Error happens, will retry.", zap.Error(err))
time.Sleep(retryInterval)
retryInterval *= 2
}
return
}