-
Notifications
You must be signed in to change notification settings - Fork 321
/
rolldposctx.go
647 lines (593 loc) · 18 KB
/
rolldposctx.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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
// Copyright (c) 2019 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 rolldpos
import (
"sync"
"time"
"github.com/facebookgo/clock"
"github.com/iotexproject/go-fsm"
"github.com/iotexproject/go-pkgs/crypto"
"github.com/iotexproject/iotex-address/address"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"go.uber.org/zap"
"github.com/iotexproject/iotex-core/action/protocol/rolldpos"
"github.com/iotexproject/iotex-core/actpool"
"github.com/iotexproject/iotex-core/blockchain"
"github.com/iotexproject/iotex-core/config"
"github.com/iotexproject/iotex-core/consensus/consensusfsm"
"github.com/iotexproject/iotex-core/consensus/scheme"
"github.com/iotexproject/iotex-core/endorsement"
"github.com/iotexproject/iotex-core/pkg/log"
"github.com/iotexproject/iotex-core/state"
)
var (
timeSlotMtc = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "iotex_consensus_round",
Help: "Consensus round",
},
[]string{},
)
blockIntervalMtc = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "iotex_consensus_block_interval",
Help: "Consensus block interval",
},
[]string{},
)
consensusDurationMtc = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "iotex_consensus_elapse_time",
Help: "Consensus elapse time.",
},
[]string{},
)
)
func init() {
prometheus.MustRegister(timeSlotMtc)
prometheus.MustRegister(blockIntervalMtc)
prometheus.MustRegister(consensusDurationMtc)
}
// CandidatesByHeightFunc defines a function to overwrite candidates
type CandidatesByHeightFunc func(uint64) ([]*state.Candidate, error)
type rollDPoSCtx struct {
cfg config.RollDPoS
// TODO: explorer dependency deleted at #1085, need to add api params here
chain blockchain.Blockchain
actPool actpool.ActPool
broadcastHandler scheme.Broadcast
roundCalc *roundCalculator
encodedAddr string
priKey crypto.PrivateKey
round *roundCtx
clock clock.Clock
active bool
mutex sync.RWMutex
}
func newRollDPoSCtx(
cfg config.RollDPoS,
active bool,
blockInterval time.Duration,
toleratedOvertime time.Duration,
timeBasedRotation bool,
chain blockchain.Blockchain,
actPool actpool.ActPool,
rp *rolldpos.Protocol,
broadcastHandler scheme.Broadcast,
candidatesByHeightFunc CandidatesByHeightFunc,
encodedAddr string,
priKey crypto.PrivateKey,
clock clock.Clock,
) *rollDPoSCtx {
if candidatesByHeightFunc == nil {
candidatesByHeightFunc = chain.CandidatesByHeight
}
roundCalc := &roundCalculator{
blockInterval: blockInterval,
candidatesByHeightFunc: candidatesByHeightFunc,
chain: chain,
rp: rp,
timeBasedRotation: timeBasedRotation,
toleratedOvertime: toleratedOvertime,
}
round, err := roundCalc.NewRoundWithToleration(0, clock.Now())
if err != nil {
log.Logger("consensus").Panic("failed to generate round context", zap.Error(err))
}
if cfg.FSM.AcceptBlockTTL+cfg.FSM.AcceptProposalEndorsementTTL+cfg.FSM.AcceptLockEndorsementTTL+cfg.FSM.CommitTTL > blockInterval {
log.Logger("consensus").Panic(
"invalid ttl config, the sum of ttls should be equal to block interval",
zap.Duration("acceptBlockTTL", cfg.FSM.AcceptBlockTTL),
zap.Duration("acceptProposalEndorsementTTL", cfg.FSM.AcceptProposalEndorsementTTL),
zap.Duration("acceptLockEndorsementTTL", cfg.FSM.AcceptLockEndorsementTTL),
zap.Duration("commitTTL", cfg.FSM.CommitTTL),
zap.Duration("blockInterval", blockInterval),
)
}
return &rollDPoSCtx{
cfg: cfg,
active: active,
encodedAddr: encodedAddr,
priKey: priKey,
chain: chain,
actPool: actPool,
broadcastHandler: broadcastHandler,
clock: clock,
roundCalc: roundCalc,
round: round,
}
}
func (ctx *rollDPoSCtx) CheckVoteEndorser(
height uint64,
vote *ConsensusVote,
en *endorsement.Endorsement,
) error {
endorserAddr, err := address.FromBytes(en.Endorser().Hash())
if err != nil {
return err
}
if !ctx.roundCalc.IsDelegate(endorserAddr.String(), height) {
return errors.Errorf("%s is not delegate of the corresponding round", endorserAddr)
}
return nil
}
func (ctx *rollDPoSCtx) CheckBlockProposer(
height uint64,
proposal *blockProposal,
en *endorsement.Endorsement,
) error {
if height != proposal.block.Height() {
return errors.Errorf(
"block height %d different from expected %d",
proposal.block.Height(),
height,
)
}
endorserAddr, err := address.FromBytes(en.Endorser().Hash())
if err != nil {
return err
}
if ctx.roundCalc.Proposer(height, en.Timestamp()) != endorserAddr.String() {
return errors.Errorf(
"%s is not proposer of the corresponding round, %s expected",
endorserAddr.String(),
ctx.roundCalc.Proposer(height, en.Timestamp()),
)
}
proposerAddr := proposal.ProposerAddress()
if ctx.roundCalc.Proposer(height, proposal.block.Timestamp()) != proposerAddr {
return errors.Errorf("%s is not proposer of the correpsonding round", proposerAddr)
}
if !proposal.block.VerifySignature() {
return errors.Errorf("invalid block signature")
}
if proposerAddr != endorserAddr.String() {
round, err := ctx.roundCalc.NewRound(height, en.Timestamp())
if err != nil {
return err
}
if err := round.AddBlock(proposal.block); err != nil {
return err
}
blkHash := proposal.block.HashBlock()
for _, e := range proposal.proofOfLock {
if err := round.AddVoteEndorsement(
NewConsensusVote(blkHash[:], PROPOSAL),
e,
); err == nil {
continue
}
if err := round.AddVoteEndorsement(
NewConsensusVote(blkHash[:], COMMIT),
e,
); err != nil {
return err
}
}
if !round.EndorsedByMajority(blkHash[:], []ConsensusVoteTopic{PROPOSAL, COMMIT}) {
return errors.Wrap(ErrInsufficientEndorsements, "failed to verify proof of lock")
}
}
return nil
}
func (ctx *rollDPoSCtx) RoundCalc() *roundCalculator {
return ctx.roundCalc
}
/////////////////////////////////////
// ConsensusFSM interfaces
/////////////////////////////////////
func (ctx *rollDPoSCtx) NewConsensusEvent(
eventType fsm.EventType,
data interface{},
) *consensusfsm.ConsensusEvent {
ctx.mutex.RLock()
defer ctx.mutex.RUnlock()
return ctx.newConsensusEvent(eventType, data)
}
func (ctx *rollDPoSCtx) NewBackdoorEvt(
dst fsm.State,
) *consensusfsm.ConsensusEvent {
ctx.mutex.RLock()
defer ctx.mutex.RUnlock()
return ctx.newConsensusEvent(consensusfsm.BackdoorEvent, dst)
}
func (ctx *rollDPoSCtx) Logger() *zap.Logger {
ctx.mutex.RLock()
defer ctx.mutex.RUnlock()
return ctx.logger()
}
func (ctx *rollDPoSCtx) Prepare() (
isDelegate bool,
proposal interface{},
isProposer bool,
locked bool,
precommitEndorsement interface{},
delay time.Duration,
err error,
) {
ctx.mutex.Lock()
defer ctx.mutex.Unlock()
height := ctx.chain.TipHeight() + 1
newRound, err := ctx.roundCalc.UpdateRound(ctx.round, height, ctx.clock.Now())
if err != nil {
return
}
ctx.logger().Debug(
"new round",
zap.Uint64("height", newRound.height),
zap.String("ts", ctx.clock.Now().String()),
zap.Uint64("epoch", newRound.epochNum),
zap.Uint64("epochStartHeight", newRound.epochStartHeight),
zap.Uint32("round", newRound.roundNum),
zap.String("roundStartTime", newRound.roundStartTime.String()),
)
ctx.round = newRound
if active := ctx.active; !active {
ctx.logger().Info("current node is in standby mode")
delay = ctx.round.NextRoundStartTime().Sub(ctx.clock.Now())
isDelegate = false
return
}
if isDelegate = ctx.round.IsDelegate(ctx.encodedAddr); !isDelegate {
ctx.logger().Info("current node is not an active consensus delegate")
delay = ctx.round.NextRoundStartTime().Sub(ctx.clock.Now())
return
}
if locked = ctx.round.IsLocked(); locked {
if proposal, err = ctx.endorseBlockProposal(newBlockProposal(
ctx.round.Block(ctx.round.HashOfBlockInLock()),
ctx.round.ProofOfLock(),
)); err != nil {
return
}
precommitEndorsement = ctx.round.ReadyToCommit(ctx.encodedAddr)
}
if isProposer = ctx.round.Proposer() == ctx.encodedAddr; isProposer {
ctx.logger().Info("current node is a proposer")
if proposal == nil {
if proposal, err = ctx.mintNewBlock(); err != nil {
return
}
}
} else {
ctx.logger().Info("current node is an active consensus delegate")
}
delay = ctx.round.StartTime().Sub(ctx.clock.Now())
timeSlotMtc.WithLabelValues().Set(float64(ctx.round.roundNum))
return
}
func (ctx *rollDPoSCtx) NewProposalEndorsement(msg interface{}) (interface{}, error) {
ctx.mutex.RLock()
defer ctx.mutex.RUnlock()
var blockHash []byte
if msg != nil {
ecm, ok := msg.(*EndorsedConsensusMessage)
if !ok {
return nil, errors.New("invalid endorsed block")
}
proposal, ok := ecm.Document().(*blockProposal)
if !ok {
return nil, errors.New("invalid endorsed block")
}
blkHash := proposal.block.HashBlock()
blockHash = blkHash[:]
if proposal.block.WorkingSet == nil {
if err := ctx.chain.ValidateBlock(proposal.block); err != nil {
return nil, errors.Wrapf(err, "error when validating the proposed block")
}
}
if err := ctx.round.AddBlock(proposal.block); err != nil {
return nil, err
}
ctx.loggerWithStats().Debug("accept block proposal", log.Hex("block", blockHash))
} else if ctx.round.IsLocked() {
blockHash = ctx.round.HashOfBlockInLock()
}
return ctx.newEndorsement(
blockHash,
PROPOSAL,
ctx.round.StartTime().Add(ctx.cfg.FSM.AcceptBlockTTL),
)
}
func (ctx *rollDPoSCtx) NewLockEndorsement(
msg interface{},
) (interface{}, error) {
ctx.mutex.RLock()
defer ctx.mutex.RUnlock()
blkHash, err := ctx.verifyVote(
msg,
[]ConsensusVoteTopic{PROPOSAL, COMMIT}, // commit is counted as one proposal
)
switch errors.Cause(err) {
case ErrInsufficientEndorsements:
return nil, nil
case nil:
if len(blkHash) != 0 {
ctx.loggerWithStats().Debug("Locked", log.Hex("block", blkHash))
return ctx.newEndorsement(
blkHash,
LOCK,
ctx.round.StartTime().Add(
ctx.cfg.FSM.AcceptBlockTTL+ctx.cfg.FSM.AcceptProposalEndorsementTTL,
),
)
}
ctx.loggerWithStats().Debug("Unlocked")
}
return nil, err
}
func (ctx *rollDPoSCtx) NewPreCommitEndorsement(
msg interface{},
) (interface{}, error) {
ctx.mutex.RLock()
defer ctx.mutex.RUnlock()
blkHash, err := ctx.verifyVote(
msg,
[]ConsensusVoteTopic{LOCK, COMMIT}, // commit endorse is counted as one lock endorse
)
switch errors.Cause(err) {
case ErrInsufficientEndorsements:
return nil, nil
case nil:
ctx.loggerWithStats().Debug("Ready to pre-commit")
return ctx.newEndorsement(
blkHash,
COMMIT,
ctx.round.StartTime().Add(
ctx.cfg.FSM.AcceptBlockTTL+ctx.cfg.FSM.AcceptProposalEndorsementTTL+ctx.cfg.FSM.AcceptLockEndorsementTTL,
),
)
default:
return nil, err
}
}
func (ctx *rollDPoSCtx) Commit(msg interface{}) (bool, error) {
ctx.mutex.Lock()
defer ctx.mutex.Unlock()
blkHash, err := ctx.verifyVote(msg, []ConsensusVoteTopic{COMMIT})
switch errors.Cause(err) {
case ErrInsufficientEndorsements:
return false, nil
case nil:
ctx.loggerWithStats().Debug("Ready to commit")
default:
return false, err
}
// this is redudant check for now, as we only accept endorsements of the received blocks
pendingBlock := ctx.round.Block(blkHash)
if pendingBlock == nil {
return false, nil
}
ctx.logger().Info("consensus reached", zap.Uint64("blockHeight", ctx.round.Height()))
if err := pendingBlock.Finalize(
ctx.round.Endorsements(blkHash, []ConsensusVoteTopic{COMMIT}),
ctx.round.StartTime().Add(
ctx.cfg.FSM.AcceptBlockTTL+ctx.cfg.FSM.AcceptProposalEndorsementTTL+ctx.cfg.FSM.AcceptLockEndorsementTTL,
),
); err != nil {
return false, errors.Wrap(err, "failed to add endorsements to block")
}
// Commit and broadcast the pending block
switch err := ctx.chain.CommitBlock(pendingBlock); errors.Cause(err) {
case blockchain.ErrInvalidTipHeight:
return true, nil
case nil:
break
default:
return false, errors.Wrap(err, "error when committing a block")
}
// Remove transfers in this block from ActPool and reset ActPool state
ctx.actPool.Reset()
// Broadcast the committed block to the network
if blkProto := pendingBlock.ConvertToBlockPb(); blkProto != nil {
if err := ctx.broadcastHandler(blkProto); err != nil {
ctx.logger().Error(
"error when broadcasting blkProto",
zap.Error(err),
zap.Uint64("block", pendingBlock.Height()),
)
}
// putblock to parent chain if the current node is proposer and current chain is a sub chain
if ctx.round.Proposer() == ctx.encodedAddr && ctx.chain.ChainAddress() != "" {
// TODO: explorer dependency deleted at #1085, need to call putblock related method
}
} else {
ctx.logger().Panic(
"error when converting a block into a proto msg",
zap.Uint64("block", pendingBlock.Height()),
)
}
consensusDurationMtc.WithLabelValues().Set(float64(time.Since(ctx.round.roundStartTime)))
if pendingBlock.Height() > 1 {
prevBlkHeader, err := ctx.chain.BlockHeaderByHeight(pendingBlock.Height() - 1)
if err != nil {
log.L().Error("Error when getting the previous block header.",
zap.Error(err),
zap.Uint64("height", pendingBlock.Height()-1),
)
}
blockIntervalMtc.WithLabelValues().Set(float64(pendingBlock.Timestamp().Sub(prevBlkHeader.Timestamp())))
}
return true, nil
}
func (ctx *rollDPoSCtx) Broadcast(endorsedMsg interface{}) {
ctx.mutex.RLock()
defer ctx.mutex.RUnlock()
ecm, ok := endorsedMsg.(*EndorsedConsensusMessage)
if !ok {
ctx.loggerWithStats().Error("invalid message type", zap.Any("message", ecm))
return
}
msg, err := ecm.Proto()
if err != nil {
ctx.loggerWithStats().Error("failed to generate protobuf message", zap.Error(err))
return
}
if err := ctx.broadcastHandler(msg); err != nil {
ctx.loggerWithStats().Error("fail to broadcast", zap.Error(err))
}
}
func (ctx *rollDPoSCtx) IsStaleEvent(evt *consensusfsm.ConsensusEvent) bool {
ctx.mutex.RLock()
defer ctx.mutex.RUnlock()
return ctx.round.IsStale(evt.Height(), evt.Round(), evt.Data())
}
func (ctx *rollDPoSCtx) IsFutureEvent(evt *consensusfsm.ConsensusEvent) bool {
ctx.mutex.RLock()
defer ctx.mutex.RUnlock()
return ctx.round.IsFuture(evt.Height(), evt.Round())
}
func (ctx *rollDPoSCtx) IsStaleUnmatchedEvent(evt *consensusfsm.ConsensusEvent) bool {
ctx.mutex.RLock()
defer ctx.mutex.RUnlock()
return ctx.clock.Now().Sub(evt.Timestamp()) > ctx.cfg.FSM.UnmatchedEventTTL
}
func (ctx *rollDPoSCtx) Height() uint64 {
ctx.mutex.RLock()
defer ctx.mutex.RUnlock()
return ctx.round.Height()
}
func (ctx *rollDPoSCtx) Activate(active bool) {
ctx.mutex.Lock()
defer ctx.mutex.Unlock()
ctx.active = active
}
func (ctx *rollDPoSCtx) Active() bool {
ctx.mutex.RLock()
defer ctx.mutex.RUnlock()
return ctx.active
}
///////////////////////////////////////////
// private functions
///////////////////////////////////////////
func (ctx *rollDPoSCtx) mintNewBlock() (*EndorsedConsensusMessage, error) {
actionMap := ctx.actPool.PendingActionMap()
ctx.logger().Debug("Pick actions from the action pool.", zap.Int("action", len(actionMap)))
blk, err := ctx.chain.MintNewBlock(
actionMap,
ctx.round.StartTime(),
)
if err != nil {
return nil, err
}
var proofOfUnlock []*endorsement.Endorsement
if ctx.round.IsUnlocked() {
proofOfUnlock = ctx.round.ProofOfLock()
}
return ctx.endorseBlockProposal(newBlockProposal(blk, proofOfUnlock))
}
func (ctx *rollDPoSCtx) endorseBlockProposal(proposal *blockProposal) (*EndorsedConsensusMessage, error) {
en, err := endorsement.Endorse(ctx.priKey, proposal, ctx.round.StartTime())
if err != nil {
return nil, err
}
return NewEndorsedConsensusMessage(proposal.block.Height(), proposal, en), nil
}
func (ctx *rollDPoSCtx) logger() *zap.Logger {
return ctx.round.Log(log.Logger("consensus"))
}
func (ctx *rollDPoSCtx) newConsensusEvent(
eventType fsm.EventType,
data interface{},
) *consensusfsm.ConsensusEvent {
switch ed := data.(type) {
case *EndorsedConsensusMessage:
roundNum, _, err := ctx.roundCalc.RoundInfo(ed.Height(), ed.Endorsement().Timestamp())
if err != nil {
ctx.logger().Error(
"failed to calcualte round for generating consensus event",
zap.String("eventType", string(eventType)),
zap.Uint64("height", ed.Height()),
zap.String("timestamp", ed.Endorsement().Timestamp().String()),
zap.Any("data", data),
zap.Error(err),
)
return nil
}
return consensusfsm.NewConsensusEvent(
eventType,
data,
ed.Height(),
roundNum,
ctx.clock.Now(),
)
default:
return consensusfsm.NewConsensusEvent(
eventType,
data,
ctx.round.Height(),
ctx.round.Number(),
ctx.clock.Now(),
)
}
}
func (ctx *rollDPoSCtx) loggerWithStats() *zap.Logger {
return ctx.round.LogWithStats(log.Logger("consensus"))
}
func (ctx *rollDPoSCtx) verifyVote(
msg interface{},
topics []ConsensusVoteTopic,
) ([]byte, error) {
consensusMsg, ok := msg.(*EndorsedConsensusMessage)
if !ok {
return nil, errors.New("invalid msg")
}
vote, ok := consensusMsg.Document().(*ConsensusVote)
if !ok {
return nil, errors.New("invalid msg")
}
blkHash := vote.BlockHash()
endorsement := consensusMsg.Endorsement()
if err := ctx.round.AddVoteEndorsement(vote, endorsement); err != nil {
return blkHash, err
}
ctx.loggerWithStats().Debug(
"verified consensus vote",
log.Hex("block", blkHash),
zap.Uint8("topic", uint8(vote.Topic())),
zap.String("endorser", endorsement.Endorser().HexString()),
)
if !ctx.round.EndorsedByMajority(blkHash, topics) {
return blkHash, ErrInsufficientEndorsements
}
return blkHash, nil
}
func (ctx *rollDPoSCtx) newEndorsement(
blkHash []byte,
topic ConsensusVoteTopic,
timestamp time.Time,
) (*EndorsedConsensusMessage, error) {
vote := NewConsensusVote(
blkHash,
topic,
)
en, err := endorsement.Endorse(ctx.priKey, vote, timestamp)
if err != nil {
return nil, err
}
return NewEndorsedConsensusMessage(ctx.round.Height(), vote, en), nil
}