/
communicator.go
374 lines (331 loc) · 9.94 KB
/
communicator.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
// Copyright (c) 2020 The Meter.io developers
// Distributed under the GNU Lesser General Public License v3.0 software license, see the accompanying
// file LICENSE or <https://www.gnu.org/licenses/lgpl-3.0.html>
package comm
import (
"context"
"fmt"
"math"
"sort"
"strings"
"sync"
"time"
"github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/p2p"
"github.com/inconshreveable/log15"
"github.com/meterio/meter-pov/block"
"github.com/meterio/meter-pov/chain"
"github.com/meterio/meter-pov/co"
"github.com/meterio/meter-pov/comm/proto"
"github.com/meterio/meter-pov/meter"
"github.com/meterio/meter-pov/p2psrv"
"github.com/meterio/meter-pov/powpool"
"github.com/meterio/meter-pov/tx"
"github.com/meterio/meter-pov/txpool"
"github.com/pkg/errors"
)
var (
log = log15.New("pkg", "comm")
GlobCommInst *Communicator
)
// Communicator communicates with remote p2p peers to exchange blocks and txs, etc.
type Communicator struct {
chain *chain.Chain
txPool *txpool.TxPool
ctx context.Context
cancel context.CancelFunc
peerSet *PeerSet
syncedCh chan struct{}
newBlockFeed event.Feed
announcementCh chan *announcement
feedScope event.SubscriptionScope
goes co.Goes
onceSynced sync.Once
powPool *powpool.PowPool
configTopic string
syncTrigCh chan bool
magic [4]byte
}
func SetGlobCommInst(c *Communicator) {
GlobCommInst = c
}
func GetGlobCommInst() *Communicator {
return GlobCommInst
}
// New create a new Communicator instance.
func New(chain *chain.Chain, txPool *txpool.TxPool, powPool *powpool.PowPool, configTopic string, magic [4]byte) *Communicator {
ctx, cancel := context.WithCancel(context.Background())
c := &Communicator{
chain: chain,
txPool: txPool,
powPool: powPool,
ctx: ctx,
cancel: cancel,
peerSet: newPeerSet(),
syncedCh: make(chan struct{}),
announcementCh: make(chan *announcement),
configTopic: configTopic,
syncTrigCh: make(chan bool),
magic: magic,
}
SetGlobCommInst(c)
return c
}
// Synced returns a channel indicates if synchronization process passed.
func (c *Communicator) Synced() <-chan struct{} {
return c.syncedCh
}
// trigger a manual sync
func (c *Communicator) TriggerSync() {
c.syncTrigCh <- true
}
// Sync start synchronization process.
func (c *Communicator) Sync(handler HandleBlockStream, qcHandler HandleQC) {
const initSyncInterval = 2 * time.Second
const syncInterval = 30 * time.Second
c.goes.Go(func() {
timer := time.NewTimer(0)
defer timer.Stop()
delay := initSyncInterval
syncCount := 0
shouldSynced := func() bool {
bestQCHeight := c.chain.BestQC().QCHeight
bestBlockHeight := c.chain.BestBlock().Number()
bestBlockTime := c.chain.BestBlock().Timestamp()
now := uint64(time.Now().Unix())
if bestBlockTime+meter.BlockInterval >= now && bestQCHeight == bestBlockHeight {
return true
}
if syncCount > 2 {
return true
}
return false
}
for {
timer.Stop()
timer = time.NewTimer(delay)
select {
case <-c.ctx.Done():
return
case <-c.syncTrigCh:
log.Info("Triggered synchronization start")
best := c.chain.BestBlock().Header()
// choose peer which has the head block with higher total score
peer := c.peerSet.Slice().Find(func(peer *Peer) bool {
_, totalScore := peer.Head()
return totalScore >= best.TotalScore()
})
if peer != nil {
log.Info("trigger sync with peer", "peer", peer.RemoteAddr().String())
if err := c.sync(peer, best.Number(), handler, qcHandler); err != nil {
peer.logger.Info("synchronization failed", "err", err)
}
log.Info("triggered synchronization done", "bestQC", c.chain.BestQC().QCHeight, "bestBlock", c.chain.BestBlock().Number())
}
syncCount++
case <-timer.C:
log.Debug("synchronization start")
best := c.chain.BestBlock().Header()
// choose peer which has the head block with higher total score
peer := c.peerSet.Slice().Find(func(peer *Peer) bool {
_, totalScore := peer.Head()
return totalScore >= best.TotalScore()
})
if peer == nil {
// XXX: original setting was 3, changed to 1 for cold start
if c.peerSet.Len() < 1 {
log.Debug("no suitable peer to sync")
break
}
// if more than 3 peers connected, we are assumed to be the best
log.Debug("synchronization done, best assumed")
} else {
if err := c.sync(peer, best.Number(), handler, qcHandler); err != nil {
peer.logger.Debug("synchronization failed", "err", err)
break
}
peer.logger.Debug("synchronization done")
}
syncCount++
if shouldSynced() {
delay = syncInterval
c.onceSynced.Do(func() {
close(c.syncedCh)
})
}
}
}
})
}
// Protocols returns all supported protocols.
func (c *Communicator) Protocols() []*p2psrv.Protocol {
genesisID := c.chain.GenesisBlock().ID()
return []*p2psrv.Protocol{
&p2psrv.Protocol{
Protocol: p2p.Protocol{
Name: proto.Name,
Version: proto.Version,
Length: proto.Length,
Run: c.servePeer,
},
DiscTopic: fmt.Sprintf("%v%v%v@%x", proto.Name, proto.Version, c.configTopic, genesisID[24:]),
}}
}
// Start start the communicator.
func (c *Communicator) Start() {
c.goes.Go(c.txsLoop)
c.goes.Go(c.announcementLoop)
// XXX: disable powpool gossip
//c.goes.Go(c.powsLoop)
}
// Stop stop the communicator.
func (c *Communicator) Stop() {
c.cancel()
c.feedScope.Close()
c.goes.Wait()
}
type txsToSync struct {
txs tx.Transactions
synced bool
}
func (c *Communicator) servePeer(p *p2p.Peer, rw p2p.MsgReadWriter) error {
peer, dir := newPeer(p, rw, c.magic)
curIP := peer.RemoteAddr().String()
lastIndex := strings.LastIndex(curIP, ":")
if lastIndex >= 0 {
curIP = curIP[:lastIndex]
}
for _, knownPeer := range c.peerSet.Slice() {
knownIP := knownPeer.RemoteAddr().String()
lastIndex = strings.LastIndex(knownIP, ":")
if lastIndex >= 0 {
knownIP = knownIP[:lastIndex]
}
if knownIP == curIP {
return errors.New("duplicate IP address: " + curIP)
}
}
counter := c.peerSet.DirectionCount()
if counter.Outbound*4 < counter.Inbound && dir == "inbound" {
return errors.New("too much inbound from: " + curIP)
}
c.goes.Go(func() {
c.runPeer(peer, dir)
})
var txsToSync txsToSync
return peer.Serve(func(msg *p2p.Msg, w func(interface{})) error {
return c.handleRPC(peer, msg, w, &txsToSync)
}, proto.MaxMsgSize)
}
func (c *Communicator) runPeer(peer *Peer, dir string) {
defer peer.Disconnect(p2p.DiscRequested)
// 5sec timeout for handshake
ctx, cancel := context.WithTimeout(c.ctx, time.Second*5)
defer cancel()
status, err := proto.GetStatus(ctx, peer)
if err != nil {
peer.logger.Debug("failed to get status", "err", err)
return
}
if status.GenesisBlockID != c.chain.GenesisBlock().ID() {
peer.logger.Debug("failed to handshake", "err", "genesis id mismatch")
return
}
localClock := uint64(time.Now().Unix())
remoteClock := status.SysTimestamp
diff := localClock - remoteClock
if localClock < remoteClock {
diff = remoteClock - localClock
}
if diff > meter.BlockInterval*2 {
peer.logger.Debug("failed to handshake", "err", "sys time diff too large")
return
}
peer.UpdateHead(status.BestBlockID, status.TotalScore)
c.peerSet.Add(peer, dir)
peer.logger.Debug(fmt.Sprintf("peer added (%v)", c.peerSet.Len()))
defer func() {
c.peerSet.Remove(peer.ID())
peer.logger.Debug(fmt.Sprintf("peer removed (%v)", c.peerSet.Len()))
}()
select {
case <-peer.Done():
case <-c.ctx.Done():
case <-c.syncedCh:
c.syncTxs(peer)
select {
case <-peer.Done():
case <-c.ctx.Done():
}
}
}
// SubscribeBlock subscribe the event that new block received.
func (c *Communicator) SubscribeBlock(ch chan *NewBlockEvent) event.Subscription {
return c.feedScope.Track(c.newBlockFeed.Subscribe(ch))
}
// BroadcastBlock broadcast a block to remote peers.
func (c *Communicator) BroadcastBlock(blk *block.Block) {
h := blk.Header()
bestQC := c.chain.BestQCOrCandidate()
log.Debug("Broadcast block and qc",
"height", h.Number(),
"id", h.ID(),
"lastKblock", h.LastKBlockHeight(),
"bestQC", bestQC.String())
peers := c.peerSet.Slice().Filter(func(p *Peer) bool {
return !p.IsBlockKnown(blk.ID())
})
p := int(math.Sqrt(float64(len(peers))))
toPropagate := peers[:p]
toAnnounce := peers[p:]
for _, peer := range toPropagate {
peer := peer
peer.MarkBlock(blk.ID())
c.goes.Go(func() {
log.Debug("Sent BestQC/NewBlock to peer", "peer", peer.Peer.RemoteAddr().String())
if err := proto.NotifyNewBestQC(c.ctx, peer, bestQC); err != nil {
peer.logger.Debug("failed to broadcast new bestQC", "err", err)
}
if err := proto.NotifyNewBlock(c.ctx, peer, blk); err != nil {
peer.logger.Debug("failed to broadcast new block", "err", err)
}
})
}
for _, peer := range toAnnounce {
peer := peer
peer.MarkBlock(blk.ID())
c.goes.Go(func() {
log.Debug("Broadcast BestQC to peer", "peer", peer.Peer.RemoteAddr().String())
if err := proto.NotifyNewBestQC(c.ctx, peer, bestQC); err != nil {
peer.logger.Debug("failed to broadcast new bestQC", "err", err)
}
if err := proto.NotifyNewBlockID(c.ctx, peer, blk.ID()); err != nil {
peer.logger.Debug("failed to broadcast new block id", "err", err)
}
})
}
}
// PeerCount returns count of peers.
func (c *Communicator) PeerCount() int {
return c.peerSet.Len()
}
// PeersStats returns all peers' stats
func (c *Communicator) PeersStats() []*PeerStats {
var stats []*PeerStats
for _, peer := range c.peerSet.Slice() {
bestID, totalScore := peer.Head()
stats = append(stats, &PeerStats{
Name: peer.Name(),
BestBlockID: bestID,
TotalScore: totalScore,
PeerID: peer.ID().String(),
NetAddr: peer.RemoteAddr().String(),
Inbound: peer.Inbound(),
Duration: uint64(time.Duration(peer.Duration()) / time.Second),
})
}
sort.Slice(stats, func(i, j int) bool {
return stats[i].Duration < stats[j].Duration
})
return stats
}