-
Notifications
You must be signed in to change notification settings - Fork 142
/
sync.go
598 lines (479 loc) · 15.7 KB
/
sync.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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
package sync
import (
"context"
"fmt"
"time"
"github.com/pactus-project/pactus/consensus"
"github.com/pactus-project/pactus/crypto/bls"
"github.com/pactus-project/pactus/genesis"
"github.com/pactus-project/pactus/network"
"github.com/pactus-project/pactus/state"
"github.com/pactus-project/pactus/sync/bundle"
"github.com/pactus-project/pactus/sync/bundle/message"
"github.com/pactus-project/pactus/sync/cache"
"github.com/pactus-project/pactus/sync/firewall"
"github.com/pactus-project/pactus/sync/peerset"
"github.com/pactus-project/pactus/sync/peerset/peer"
"github.com/pactus-project/pactus/sync/peerset/peer/service"
"github.com/pactus-project/pactus/sync/peerset/peer/status"
"github.com/pactus-project/pactus/sync/peerset/session"
"github.com/pactus-project/pactus/util"
"github.com/pactus-project/pactus/util/logger"
"github.com/pactus-project/pactus/util/ntp"
)
// IMPORTANT NOTES:
//
// 1. The Sync module is based on pulling instead of pushing. This means that the network
// does not update a node (push); instead, a node should update itself (pull).
//
// 2. The Synchronizer should not have any locks to prevent deadlocks. All submodules,
// such as state or consensus, should be thread-safe.
type synchronizer struct {
ctx context.Context
cancel context.CancelFunc
config *Config
valKeys []*bls.ValidatorKey
state state.Facade
consMgr consensus.Manager
peerSet *peerset.PeerSet
firewall *firewall.Firewall
cache *cache.Cache
handlers map[message.Type]messageHandler
broadcastCh <-chan message.Message
networkCh <-chan network.Event
network network.Network
logger *logger.SubLogger
ntp *ntp.Checker
}
func NewSynchronizer(
conf *Config,
valKeys []*bls.ValidatorKey,
state state.Facade,
consMgr consensus.Manager,
network network.Network,
broadcastCh <-chan message.Message,
) (Synchronizer, error) {
ctx, cancel := context.WithCancel(context.Background())
sync := &synchronizer{
ctx: ctx,
cancel: cancel,
config: conf,
valKeys: valKeys,
state: state,
consMgr: consMgr,
network: network,
broadcastCh: broadcastCh,
networkCh: network.EventChannel(),
ntp: ntp.NewNtpChecker(),
}
sync.peerSet = peerset.NewPeerSet(conf.SessionTimeout())
sync.logger = logger.NewSubLogger("_sync", sync)
fw, err := firewall.NewFirewall(conf.Firewall, network, sync.peerSet, state)
if err != nil {
return nil, err
}
sync.firewall = fw
cacheSize := conf.CacheSize()
ca, err := cache.NewCache(conf.CacheSize())
if err != nil {
return nil, err
}
sync.cache = ca
sync.logger.Info("cache setup", "size", cacheSize)
handlers := make(map[message.Type]messageHandler)
handlers[message.TypeHello] = newHelloHandler(sync)
handlers[message.TypeHelloAck] = newHelloAckHandler(sync)
handlers[message.TypeTransaction] = newTransactionsHandler(sync)
handlers[message.TypeQueryProposal] = newQueryProposalHandler(sync)
handlers[message.TypeProposal] = newProposalHandler(sync)
handlers[message.TypeQueryVote] = newQueryVoteHandler(sync)
handlers[message.TypeVote] = newVoteHandler(sync)
handlers[message.TypeBlockAnnounce] = newBlockAnnounceHandler(sync)
handlers[message.TypeBlocksRequest] = newBlocksRequestHandler(sync)
handlers[message.TypeBlocksResponse] = newBlocksResponseHandler(sync)
sync.handlers = handlers
return sync, nil
}
func (sync *synchronizer) Start() error {
if err := sync.network.JoinTopic(network.TopicIDBlock, sync.shouldPropagateBlockMessage); err != nil {
return err
}
if err := sync.network.JoinTopic(network.TopicIDTransaction, sync.shouldPropagateTransactionMessage); err != nil {
return err
}
// TODO: Not joining consensus topic when we are syncing
if err := sync.network.JoinTopic(network.TopicIDConsensus, sync.shouldPropagateConsensusMessage); err != nil {
return err
}
go sync.ntp.Start()
go sync.receiveLoop()
go sync.broadcastLoop()
return nil
}
func (sync *synchronizer) Stop() {
sync.cancel()
sync.ntp.Stop()
sync.logger.Debug("context closed", "reason", sync.ctx.Err())
}
func (sync *synchronizer) ClockOffset() (time.Duration, error) {
return sync.ntp.ClockOffset()
}
func (sync *synchronizer) IsClockOutOfSync() bool {
return sync.ntp.IsOutOfSync()
}
func (sync *synchronizer) stateHeight() uint32 {
stateHeight := sync.state.LastBlockHeight()
return stateHeight
}
func (sync *synchronizer) moveConsensusToNewHeight() {
stateHeight := sync.stateHeight()
consHeight, _ := sync.consMgr.HeightRound()
if stateHeight >= consHeight {
sync.consMgr.MoveToNewHeight()
}
}
func (sync *synchronizer) prepareBundle(msg message.Message) *bundle.Bundle {
h := sync.handlers[msg.Type()]
bdl := h.PrepareBundle(msg)
// Bundles will be carried through LibP2P.
// In future we might support other libraries.
bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagCarrierLibP2P)
switch sync.state.Genesis().ChainType() {
case genesis.Mainnet:
bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkMainnet)
case genesis.Testnet:
bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagNetworkTestnet)
case genesis.Localnet:
// It's localnet and for testing purpose only
}
bdl.SetSequenceNo(sync.peerSet.TotalSentBundles())
return bdl
}
func (sync *synchronizer) sendTo(msg message.Message, pid peer.ID) {
bdl := sync.prepareBundle(msg)
data, _ := bdl.Encode()
sync.network.SendTo(data, pid)
sync.peerSet.UpdateLastSent(pid)
sync.peerSet.UpdateSentMetric(&pid, msg.Type(), int64(len(data)))
sync.logger.Debug("bundle sent", "bundle", bdl, "pid", pid)
}
func (sync *synchronizer) broadcast(msg message.Message) {
if msg.Type() == message.TypeBlockAnnounce {
m := msg.(*message.BlockAnnounceMessage)
if sync.cache.HasBlockInCache(m.Height()) {
// We have received the block announcement from other peers before,
// so we can simply ignore broadcasting it again.
// This helps to reduce the network bandwidth.
return
}
}
bdl := sync.prepareBundle(msg)
bdl.Flags = util.SetFlag(bdl.Flags, bundle.BundleFlagBroadcasted)
data, _ := bdl.Encode()
sync.network.Broadcast(data, msg.TopicID())
sync.peerSet.UpdateSentMetric(nil, msg.Type(), int64(len(data)))
sync.logger.Debug("bundle broadcasted", "bundle", bdl)
}
func (sync *synchronizer) SelfID() peer.ID {
return sync.network.SelfID()
}
func (sync *synchronizer) Moniker() string {
return sync.config.Moniker
}
func (sync *synchronizer) PeerSet() *peerset.PeerSet {
return sync.peerSet
}
func (sync *synchronizer) Services() service.Services {
return sync.config.Services
}
func (sync *synchronizer) sayHello(pid peer.ID) {
s := sync.peerSet.GetPeerStatus(pid)
if s.IsKnown() {
return
}
msg := message.NewHelloMessage(
sync.SelfID(),
sync.config.Moniker,
sync.config.Services,
sync.stateHeight(),
sync.state.LastBlockHash(),
sync.state.Genesis().Hash(),
)
msg.Sign(sync.valKeys)
sync.logger.Info("sending Hello message", "to", pid)
sync.sendTo(msg, pid)
}
func (sync *synchronizer) broadcastLoop() {
for {
select {
case <-sync.ctx.Done():
return
case msg := <-sync.broadcastCh:
sync.broadcast(msg)
}
}
}
func (sync *synchronizer) receiveLoop() {
for {
select {
case <-sync.ctx.Done():
return
case evt := <-sync.networkCh:
switch evt.Type() {
case network.EventTypeGossip:
ge := evt.(*network.GossipMessage)
sync.processGossipMessage(ge)
case network.EventTypeStream:
se := evt.(*network.StreamMessage)
sync.processStreamMessage(se)
case network.EventTypeConnect:
ce := evt.(*network.ConnectEvent)
sync.processConnectEvent(ce)
case network.EventTypeDisconnect:
de := evt.(*network.DisconnectEvent)
sync.processDisconnectEvent(de)
case network.EventTypeProtocols:
pe := evt.(*network.ProtocolsEvents)
sync.processProtocolsEvent(pe)
}
}
}
}
func (sync *synchronizer) processGossipMessage(msg *network.GossipMessage) {
sync.logger.Debug("processing gossip message", "pid", msg.From)
bdl, err := sync.firewall.OpenGossipBundle(msg.Data, msg.From)
if err != nil {
sync.logger.Debug("error on parsing a Gossip bundle",
"from", msg.From, "bundle", bdl, "error", err)
return
}
sync.processIncomingBundle(bdl, msg.From)
}
func (sync *synchronizer) processStreamMessage(msg *network.StreamMessage) {
sync.logger.Debug("processing stream message", "pid", msg.From)
defer func() {
_ = msg.Reader.Close()
}()
bdl, err := sync.firewall.OpenStreamBundle(msg.Reader, msg.From)
if err != nil {
sync.logger.Debug("error on parsing a Stream bundle",
"from", msg.From, "bundle", bdl, "error", err)
return
}
sync.processIncomingBundle(bdl, msg.From)
}
func (sync *synchronizer) processConnectEvent(ce *network.ConnectEvent) {
sync.logger.Debug("processing connect event", "pid", ce.PeerID)
sync.peerSet.UpdateAddress(ce.PeerID, ce.RemoteAddress, ce.Direction)
sync.peerSet.UpdateStatus(ce.PeerID, status.StatusConnected)
}
func (sync *synchronizer) processProtocolsEvent(pe *network.ProtocolsEvents) {
sync.logger.Debug("processing protocols event", "pid", pe.PeerID, "protocols", pe.Protocols)
sync.peerSet.UpdateProtocols(pe.PeerID, pe.Protocols)
sync.sayHello(pe.PeerID)
}
func (sync *synchronizer) processDisconnectEvent(de *network.DisconnectEvent) {
sync.logger.Debug("processing disconnect event", "pid", de.PeerID)
sync.peerSet.UpdateStatus(de.PeerID, status.StatusDisconnected)
}
func (sync *synchronizer) processIncomingBundle(bdl *bundle.Bundle, from peer.ID) {
sync.logger.Debug("received a bundle", "from", from, "bundle", bdl)
handler := sync.handlers[bdl.Message.Type()]
if handler == nil {
sync.logger.Error("invalid message type", "type", bdl.Message.Type())
return
}
handler.ParseMessage(bdl.Message, from)
}
func (sync *synchronizer) String() string {
return fmt.Sprintf("{☍ %d ⛃ %d}",
sync.peerSet.Len(),
sync.cache.Len())
}
// updateBlockchain checks whether the node's height is shorter than the network's height or not.
// If the node's height is shorter than the network's height by more than two hours (720 blocks),
// it should start downloading blocks from the network's nodes.
// Otherwise, the node can request the latest blocks from any nodes.
func (sync *synchronizer) updateBlockchain() {
// Maybe we have some blocks inside the cache?
sync.tryCommitBlocks()
// Check if we have any expired sessions
sync.peerSet.SetExpiredSessionsAsUncompleted()
// Try to re-download the blocks for uncompleted sessions
sessions := sync.peerSet.Sessions()
for _, ssn := range sessions {
if ssn.Status == session.Uncompleted {
sync.logger.Info("uncompleted block request, re-download",
"sid", ssn.SessionID, "pid", ssn.PeerID,
"stats", sync.peerSet.SessionStats())
sent := sync.sendBlockRequestToRandomPeer(ssn.From, ssn.Count, false)
if !sent {
break
}
}
}
// Check if there are any open sessions.
// If open sessions exist, we should wait for them to close.
// Otherwise, we might request to download the same blocks from different peers.
// TODO: write test for me
if sync.peerSet.HasAnyOpenSession() {
sync.logger.Debug("we have open session",
"stats", sync.peerSet.SessionStats())
return
}
sync.peerSet.RemoveAllSessions()
blockInterval := sync.state.Params().BlockInterval()
curTime := util.RoundNow(int(blockInterval.Seconds()))
lastBlockTime := sync.state.LastBlockTime()
diff := curTime.Sub(lastBlockTime)
numOfBlocks := uint32(diff.Seconds() / blockInterval.Seconds())
if numOfBlocks <= 1 {
// We are sync
return
}
downloadHeight := sync.state.LastBlockHeight()
downloadHeight++
if sync.cache.HasBlockInCache(downloadHeight) {
// The last block exists inside the cache, without the certificate.
// Ignore downloading this block again.
downloadHeight++
}
sync.logger.Info("start syncing with the network",
"numOfBlocks", numOfBlocks, "height", downloadHeight)
if numOfBlocks > sync.config.PruneWindow {
// Don't have blocks for mre than 10 days
sync.downloadBlocks(downloadHeight, true)
} else {
sync.downloadBlocks(downloadHeight, false)
}
}
// downloadBlocks starts downloading blocks from the network.
func (sync *synchronizer) downloadBlocks(from uint32, onlyFullNodes bool) {
sync.logger.Debug("downloading blocks", "from", from)
for i := sync.peerSet.NumberOfSessions(); i < sync.config.MaxSessions; i++ {
count := sync.config.BlockPerSession
sent := sync.sendBlockRequestToRandomPeer(from, count, onlyFullNodes)
if !sent {
return
}
from += count
}
}
func (sync *synchronizer) sendBlockRequestToRandomPeer(from, count uint32, onlyFullNodes bool) bool {
// Prevent downloading blocks that might be cached before
for sync.cache.HasBlockInCache(from) {
from++
count--
if count == 0 {
// we have blocks inside the cache
sync.logger.Debug("sending download request ignored", "from", from+1)
return true
}
}
for i := sync.peerSet.NumberOfSessions(); i < sync.config.MaxSessions; i++ {
peer := sync.peerSet.GetRandomPeer()
if peer == nil {
break
}
// Don't open a new session if we already have an open session with the same peer.
// This helps us to get blocks from different peers.
if sync.peerSet.HasOpenSession(peer.PeerID) {
continue
}
// We haven't completed the handshake with this peer.
if !peer.Status.IsKnown() {
if onlyFullNodes {
sync.network.CloseConnection(peer.PeerID)
}
continue
}
if onlyFullNodes && !peer.IsFullNode() {
if onlyFullNodes {
sync.network.CloseConnection(peer.PeerID)
}
continue
}
sid := sync.peerSet.OpenSession(peer.PeerID, from, count)
msg := message.NewBlocksRequestMessage(sid, from, count)
sync.sendTo(msg, peer.PeerID)
sync.logger.Info("blocks request sent",
"from", from+1, "count", count, "pid", peer.PeerID, "sid", sid)
return true
}
sync.logger.Warn("unable to open a new session",
"stats", sync.peerSet.SessionStats())
return false
}
func (sync *synchronizer) tryCommitBlocks() {
onError := func(height uint32, err error) {
sync.logger.Warn("committing block failed, removing block from the cache",
"height", height, "error", err)
sync.cache.RemoveBlock(height)
}
height := sync.stateHeight() + 1
for {
blk := sync.cache.GetBlock(height)
if blk == nil {
break
}
cert := sync.cache.GetCertificate(height)
if cert == nil {
break
}
trxs := blk.Transactions()
for i := 0; i < trxs.Len(); i++ {
trx := trxs[i]
if trx.IsPublicKeyStriped() {
pub, err := sync.state.PublicKey(trx.Payload().Signer())
if err != nil {
onError(height, err)
return
}
trx.SetPublicKey(pub)
}
}
if err := blk.BasicCheck(); err != nil {
onError(height, err)
return
}
if err := cert.BasicCheck(); err != nil {
onError(height, err)
return
}
sync.logger.Trace("committing block", "height", height, "block", blk)
if err := sync.state.CommitBlock(blk, cert); err != nil {
onError(height, err)
return
}
height++
}
}
func (sync *synchronizer) prepareBlocks(from, count uint32) [][]byte {
ourHeight := sync.stateHeight()
if from > ourHeight {
sync.logger.Debug("we don't have block at this height", "height", from)
return nil
}
if from+count > ourHeight {
count = ourHeight - from + 1
}
blocks := make([][]byte, 0, count)
for height := from; height < from+count; height++ {
cBlk := sync.state.CommittedBlock(height)
if cBlk == nil {
sync.logger.Warn("unable to find a block", "height", height)
return nil
}
blocks = append(blocks, cBlk.Data)
}
return blocks
}
func (sync *synchronizer) shouldPropagateBlockMessage(_ *network.GossipMessage) bool {
return sync.firewall.AllowBlockRequest()
}
func (sync *synchronizer) shouldPropagateTransactionMessage(_ *network.GossipMessage) bool {
return sync.firewall.AllowTransactionRequest()
}
func (sync *synchronizer) shouldPropagateConsensusMessage(_ *network.GossipMessage) bool {
return sync.firewall.AllowConsensusRequest()
}