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
|
// Copyright 2019 The dexon-consensus Authors
// This file is part of the dexon-consensus library.
//
// The dexon-consensus library is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// The dexon-consensus library is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
// General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the dexon-consensus library. If not, see
// <http://www.gnu.org/licenses/>.
package core
import (
"errors"
"fmt"
"sort"
"sync"
"time"
"github.com/dexon-foundation/dexon-consensus/common"
"github.com/dexon-foundation/dexon-consensus/core/crypto"
"github.com/dexon-foundation/dexon-consensus/core/types"
"github.com/dexon-foundation/dexon-consensus/core/utils"
)
// Errors for sanity check error.
var (
ErrBlockFromOlderPosition = errors.New("block from older position")
ErrNotGenesisBlock = errors.New("not a genesis block")
ErrIsGenesisBlock = errors.New("is a genesis block")
ErrIncorrectParentHash = errors.New("incorrect parent hash")
ErrInvalidBlockHeight = errors.New("invalid block height")
ErrInvalidRoundID = errors.New("invalid round id")
ErrNotFollowTipPosition = errors.New("not follow tip position")
ErrDuplicatedPendingBlock = errors.New("duplicated pending block")
ErrRetrySanityCheckLater = errors.New("retry sanity check later")
ErrRoundNotIncreasing = errors.New("round not increasing")
ErrRoundNotSwitch = errors.New("round not switch")
ErrIncorrectBlockRandomnessResult = errors.New(
"incorrect block randomness result")
)
type pendingBlockRecord struct {
position types.Position
block *types.Block
}
type pendingBlockRecords []pendingBlockRecord
func (pb *pendingBlockRecords) insert(p pendingBlockRecord) error {
idx := sort.Search(len(*pb), func(i int) bool {
return !(*pb)[i].position.Older(p.position)
})
switch idx {
case len(*pb):
*pb = append(*pb, p)
default:
if (*pb)[idx].position.Equal(p.position) {
// Allow to overwrite pending block record for empty blocks, we may
// need to pull that block from others when its parent is not found
// locally.
if (*pb)[idx].block == nil && p.block != nil {
(*pb)[idx].block = p.block
return nil
}
return ErrDuplicatedPendingBlock
}
// Insert the value to that index.
*pb = append((*pb), pendingBlockRecord{})
copy((*pb)[idx+1:], (*pb)[idx:])
(*pb)[idx] = p
}
return nil
}
func (pb pendingBlockRecords) searchByHeight(h uint64) (
pendingBlockRecord, bool) {
idx := sort.Search(len(pb), func(i int) bool {
return pb[i].position.Height >= h
})
if idx == len(pb) || pb[idx].position.Height != h {
return pendingBlockRecord{}, false
}
return pb[idx], true
}
func (pb pendingBlockRecords) searchByPosition(p types.Position) (
pendingBlockRecord, bool) {
idx := sort.Search(len(pb), func(i int) bool {
return !pb[i].block.Position.Older(p)
})
if idx == len(pb) || !pb[idx].position.Equal(p) {
return pendingBlockRecord{}, false
}
return pb[idx], true
}
type blockChainConfig struct {
roundBasedConfig
minBlockInterval time.Duration
}
func (c *blockChainConfig) fromConfig(round uint64, config *types.Config) {
c.minBlockInterval = config.MinBlockInterval
c.setupRoundBasedFields(round, config)
}
func newBlockChainConfig(prev blockChainConfig, config *types.Config) (
c blockChainConfig) {
c = blockChainConfig{}
c.fromConfig(prev.roundID+1, config)
c.setRoundBeginHeight(prev.roundEndHeight)
return
}
type tsigVerifierGetter interface {
UpdateAndGet(uint64) (TSigVerifier, bool, error)
}
type blockChain struct {
lock sync.RWMutex
ID types.NodeID
lastConfirmed *types.Block
lastDelivered *types.Block
signer *utils.Signer
vGetter tsigVerifierGetter
app Application
logger common.Logger
pendingRandomnesses map[types.Position]*types.BlockRandomnessResult
configs []blockChainConfig
pendingBlocks pendingBlockRecords
confirmedBlocks types.BlocksByPosition
dMoment time.Time
}
func newBlockChain(nID types.NodeID, dMoment time.Time, initBlock *types.Block,
initConfig blockChainConfig, app Application, vGetter tsigVerifierGetter,
signer *utils.Signer, logger common.Logger) *blockChain {
if initBlock != nil {
if initConfig.roundID != initBlock.Position.Round {
panic(fmt.Errorf("incompatible config/block %s %d",
initBlock, initConfig.roundID))
}
} else {
if initConfig.roundID != 0 {
panic(fmt.Errorf("genesis config should from round 0 %d",
initConfig.roundID))
}
}
return &blockChain{
ID: nID,
lastConfirmed: initBlock,
lastDelivered: initBlock,
signer: signer,
vGetter: vGetter,
app: app,
logger: logger,
configs: []blockChainConfig{initConfig},
dMoment: dMoment,
pendingRandomnesses: make(
map[types.Position]*types.BlockRandomnessResult),
}
}
func (bc *blockChain) appendConfig(round uint64, config *types.Config) error {
expectedRound := uint64(len(bc.configs))
if bc.lastConfirmed != nil {
expectedRound += bc.lastConfirmed.Position.Round
}
if round != expectedRound {
return ErrRoundNotIncreasing
}
bc.configs = append(bc.configs, newBlockChainConfig(
bc.configs[len(bc.configs)-1], config))
return nil
}
func (bc *blockChain) proposeBlock(position types.Position,
proposeTime time.Time) (b *types.Block, err error) {
bc.lock.RLock()
defer bc.lock.RUnlock()
return bc.prepareBlock(position, proposeTime, false)
}
func (bc *blockChain) extractBlocks() (ret []*types.Block) {
bc.lock.Lock()
defer bc.lock.Unlock()
for len(bc.confirmedBlocks) > 0 {
c := bc.confirmedBlocks[0]
if c.Position.Round >= DKGDelayRound && len(c.Finalization.Randomness) == 0 {
break
}
c, bc.confirmedBlocks = bc.confirmedBlocks[0], bc.confirmedBlocks[1:]
// TODO(mission): remove these duplicated field if we fully converted
// to single chain.
c.Finalization.ParentHash = c.ParentHash
c.Finalization.Timestamp = c.Timestamp
// It's a workaround, the height for application is one-based.
c.Finalization.Height = c.Position.Height + 1
ret = append(ret, c)
bc.lastDelivered = c
}
return
}
func (bc *blockChain) sanityCheck(b *types.Block) error {
if b.IsEmpty() {
panic(fmt.Errorf("pass empty block to sanity check: %s", b))
}
bc.lock.RLock()
defer bc.lock.RUnlock()
if bc.lastConfirmed == nil {
// It should be a genesis block.
if !b.IsGenesis() {
return ErrNotGenesisBlock
}
// TODO(mission): Do we have to check timestamp of genesis block?
return nil
}
if b.IsGenesis() {
return ErrIsGenesisBlock
}
if b.Position.Height != bc.lastConfirmed.Position.Height+1 {
if b.Position.Height > bc.lastConfirmed.Position.Height {
return ErrRetrySanityCheckLater
}
return ErrInvalidBlockHeight
}
tipConfig := bc.tipConfig()
if tipConfig.isLastBlock(bc.lastConfirmed) {
if b.Position.Round != bc.lastConfirmed.Position.Round+1 {
return ErrRoundNotSwitch
}
} else {
if b.Position.Round != bc.lastConfirmed.Position.Round {
return ErrInvalidRoundID
}
}
if !b.ParentHash.Equal(bc.lastConfirmed.Hash) {
return ErrIncorrectParentHash
}
if err := utils.VerifyBlockSignature(b); err != nil {
return err
}
return nil
}
// addEmptyBlock is called when an empty block is confirmed by BA.
func (bc *blockChain) addEmptyBlock(position types.Position) (
*types.Block, error) {
bc.lock.Lock()
defer bc.lock.Unlock()
add := func() *types.Block {
emptyB, err := bc.prepareBlock(position, time.Time{}, true)
if err != nil || emptyB == nil {
// This helper is expected to be called when an empty block is ready
// to be confirmed.
panic(err)
}
bc.confirmBlock(emptyB)
bc.checkIfBlocksConfirmed()
return emptyB
}
if bc.lastConfirmed != nil {
if !position.Newer(bc.lastConfirmed.Position) {
bc.logger.Warn("Dropping empty block: older than tip",
"position", &position,
"last-confirmed", bc.lastConfirmed)
return nil, ErrBlockFromOlderPosition
}
if bc.lastConfirmed.Position.Height+1 == position.Height {
return add(), nil
}
} else if position.Height == 0 && position.Round == 0 {
return add(), nil
}
return nil, bc.addPendingBlockRecord(pendingBlockRecord{position, nil})
}
// addBlock should be called when the block is confirmed by BA, we won't perform
// sanity check against this block, it's ok to add block with skipping height.
func (bc *blockChain) addBlock(b *types.Block) error {
bc.lock.Lock()
defer bc.lock.Unlock()
confirmed := false
if bc.lastConfirmed != nil {
if !b.Position.Newer(bc.lastConfirmed.Position) {
bc.logger.Warn("Dropping block: older than tip",
"block", b, "last-confirmed", bc.lastConfirmed)
return nil
}
if bc.lastConfirmed.Position.Height+1 == b.Position.Height {
confirmed = true
}
} else if b.IsGenesis() {
confirmed = true
}
if !confirmed {
return bc.addPendingBlockRecord(pendingBlockRecord{b.Position, b})
}
bc.confirmBlock(b)
bc.checkIfBlocksConfirmed()
return nil
}
func (bc *blockChain) shouldAddRandomness(r *types.BlockRandomnessResult) bool {
bc.lock.RLock()
defer bc.lock.RUnlock()
if bc.lastDelivered != nil &&
bc.lastDelivered.Position.Newer(r.Position) {
return false
}
_, exists := bc.pendingRandomnesses[r.Position]
if exists {
return false
}
b := bc.findPendingBlock(r.Position)
return b == nil || len(b.Finalization.Randomness) == 0
}
func (bc *blockChain) addRandomness(r *types.BlockRandomnessResult) error {
if !bc.shouldAddRandomness(r) {
return nil
}
ok, err := bc.verifyRandomness(r.BlockHash, r.Position.Round, r.Randomness)
if err != nil {
return err
}
if !ok {
return ErrIncorrectBlockRandomnessResult
}
bc.lock.Lock()
defer bc.lock.Unlock()
if b := bc.findPendingBlock(r.Position); b != nil {
if !r.BlockHash.Equal(b.Hash) {
panic(fmt.Errorf("mismathed randomness: %s %s", b, r))
}
b.Finalization.Randomness = r.Randomness
} else {
bc.pendingRandomnesses[r.Position] = r
}
return nil
}
// TODO(mission): remove this method after removing the strong binding between
// BA and blockchain.
func (bc *blockChain) tipRound() uint64 {
bc.lock.RLock()
defer bc.lock.RUnlock()
if bc.lastConfirmed == nil {
return 0
}
offset, tipConfig := uint64(0), bc.tipConfig()
if tipConfig.isLastBlock(bc.lastConfirmed) {
offset++
}
return bc.lastConfirmed.Position.Round + offset
}
// TODO(mission): the pulling should be done inside of blockchain, then we don't
// have to expose this method.
func (bc *blockChain) confirmed(h uint64) bool {
bc.lock.RLock()
defer bc.lock.RUnlock()
if bc.lastConfirmed != nil && bc.lastConfirmed.Position.Height >= h {
return true
}
r, found := bc.pendingBlocks.searchByHeight(h)
if !found {
return false
}
return r.block != nil
}
// TODO(mission): this method can be removed after refining the relation between
// BA and block storage.
func (bc *blockChain) nextBlock() (uint64, time.Time) {
bc.lock.RLock()
defer bc.lock.RUnlock()
// It's ok to access tip config directly without checking the existence of
// lastConfirmed block in the scenario of "nextBlock" method.
tip, config := bc.lastConfirmed, bc.configs[0]
if tip == nil {
return 0, bc.dMoment
}
return tip.Position.Height + 1, tip.Timestamp.Add(config.minBlockInterval)
}
func (bc *blockChain) pendingBlocksWithoutRandomness() (hashes common.Hashes) {
bc.lock.RLock()
defer bc.lock.RUnlock()
for _, b := range bc.confirmedBlocks {
if b.Position.Round == 0 || len(b.Finalization.Randomness) > 0 {
continue
}
hashes = append(hashes, b.Hash)
}
for _, r := range bc.pendingBlocks {
if r.position.Round == 0 {
continue
}
if r.block != nil && len(r.block.Finalization.Randomness) == 0 {
hashes = append(hashes, r.block.Hash)
}
}
return
}
func (bc *blockChain) lastDeliveredBlock() *types.Block {
bc.lock.RLock()
defer bc.lock.RUnlock()
return bc.lastDelivered
}
func (bc *blockChain) lastPendingBlock() *types.Block {
bc.lock.RLock()
defer bc.lock.RUnlock()
if len(bc.confirmedBlocks) == 0 {
return nil
}
return bc.confirmedBlocks[0]
}
func (bc *blockChain) processFinalizedBlock(b *types.Block) error {
return bc.addRandomness(&types.BlockRandomnessResult{
BlockHash: b.Hash,
Position: b.Position,
Randomness: b.Finalization.Randomness,
})
}
/////////////////////////////////////////////
//
// internal helpers
//
/////////////////////////////////////////////
// findPendingBlock is a helper to find a block in either pending or confirmed
// state by position.
func (bc *blockChain) findPendingBlock(p types.Position) *types.Block {
if idx := sort.Search(len(bc.confirmedBlocks), func(i int) bool {
return !bc.confirmedBlocks[i].Position.Older(p)
}); idx != len(bc.confirmedBlocks) &&
bc.confirmedBlocks[idx].Position.Equal(p) {
return bc.confirmedBlocks[idx]
}
pendingRec, _ := bc.pendingBlocks.searchByPosition(p)
return pendingRec.block
}
func (bc *blockChain) addPendingBlockRecord(p pendingBlockRecord) error {
if err := bc.pendingBlocks.insert(p); err != nil {
if err == ErrDuplicatedPendingBlock {
// TODO(mission): stop ignoreing this error once our BA can confirm
// blocks uniquely and sequentially.
err = nil
}
return err
}
if p.block != nil {
bc.setRandomnessFromPending(p.block)
}
return nil
}
func (bc *blockChain) checkIfBlocksConfirmed() {
var err error
for len(bc.pendingBlocks) > 0 {
if bc.pendingBlocks[0].position.Height <
bc.lastConfirmed.Position.Height+1 {
panic(fmt.Errorf("unexpected case %s %s", bc.lastConfirmed,
bc.pendingBlocks[0].position))
}
if bc.pendingBlocks[0].position.Height >
bc.lastConfirmed.Position.Height+1 {
break
}
var pending pendingBlockRecord
pending, bc.pendingBlocks = bc.pendingBlocks[0], bc.pendingBlocks[1:]
nextTip := pending.block
if nextTip == nil {
if nextTip, err = bc.prepareBlock(
pending.position, time.Time{}, true); err != nil {
// It should not be error when prepare empty block for correct
// position.
panic(err)
}
}
bc.confirmBlock(nextTip)
}
}
func (bc *blockChain) purgeConfig() {
for bc.configs[0].roundID < bc.lastConfirmed.Position.Round {
bc.configs = bc.configs[1:]
}
if bc.configs[0].roundID != bc.lastConfirmed.Position.Round {
panic(fmt.Errorf("mismatched tip config: %d %d",
bc.configs[0].roundID, bc.lastConfirmed.Position.Round))
}
}
func (bc *blockChain) verifyRandomness(
blockHash common.Hash, round uint64, randomness []byte) (bool, error) {
if round < DKGDelayRound {
return len(randomness) == 0, nil
}
v, ok, err := bc.vGetter.UpdateAndGet(round)
if err != nil {
return false, err
}
if !ok {
return false, ErrTSigNotReady
}
return v.VerifySignature(blockHash, crypto.Signature{
Type: "bls",
Signature: randomness}), nil
}
func (bc *blockChain) prepareBlock(position types.Position,
proposeTime time.Time, empty bool) (b *types.Block, err error) {
// TODO(mission): refine timestamp.
b = &types.Block{Position: position, Timestamp: proposeTime}
tip := bc.lastConfirmed
// Make sure we can propose a block at expected position for callers.
if tip == nil {
// The case for genesis block.
if !position.Equal(types.Position{}) {
b, err = nil, ErrNotGenesisBlock
return
} else if empty {
b.Timestamp = bc.dMoment
} else {
bc.logger.Debug("Calling genesis Application.PreparePayload")
if b.Payload, err = bc.app.PreparePayload(b.Position); err != nil {
b = nil
return
}
bc.logger.Debug("Calling genesis Application.PrepareWitness")
if b.Witness, err = bc.app.PrepareWitness(0); err != nil {
b = nil
return
}
}
} else {
tipConfig := bc.tipConfig()
if tip.Position.Height+1 != position.Height {
b, err = nil, ErrNotFollowTipPosition
return
}
if tipConfig.isLastBlock(tip) {
if tip.Position.Round+1 != position.Round {
b, err = nil, ErrRoundNotSwitch
return
}
} else {
if tip.Position.Round != position.Round {
b, err = nil, ErrInvalidRoundID
return
}
}
b.ParentHash = tip.Hash
if !empty {
bc.logger.Debug("Calling Application.PreparePayload",
"position", b.Position)
if b.Payload, err = bc.app.PreparePayload(b.Position); err != nil {
b = nil
return
}
bc.logger.Debug("Calling Application.PrepareWitness",
"height", tip.Witness.Height)
if b.Witness, err = bc.app.PrepareWitness(
tip.Witness.Height); err != nil {
b = nil
return
}
if !b.Timestamp.After(tip.Timestamp) {
b.Timestamp = tip.Timestamp.Add(tipConfig.minBlockInterval)
}
} else {
b.Witness.Height = tip.Witness.Height
b.Witness.Data = make([]byte, len(tip.Witness.Data))
copy(b.Witness.Data, tip.Witness.Data)
b.Timestamp = tip.Timestamp.Add(tipConfig.minBlockInterval)
}
}
if empty {
if b.Hash, err = utils.HashBlock(b); err != nil {
b = nil
return
}
} else {
if err = bc.signer.SignBlock(b); err != nil {
b = nil
return
}
}
return
}
func (bc *blockChain) tipConfig() blockChainConfig {
if bc.lastConfirmed == nil {
panic(fmt.Errorf("attempting to access config without tip"))
}
if bc.lastConfirmed.Position.Round != bc.configs[0].roundID {
panic(fmt.Errorf("inconsist config and tip: %d %d",
bc.lastConfirmed.Position.Round, bc.configs[0].roundID))
}
return bc.configs[0]
}
func (bc *blockChain) confirmBlock(b *types.Block) {
if bc.lastConfirmed != nil &&
bc.lastConfirmed.Position.Height+1 != b.Position.Height {
panic(fmt.Errorf("confirmed blocks not continuous in height: %s %s",
bc.lastConfirmed, b))
}
bc.logger.Debug("Calling Application.BlockConfirmed", "block", b)
bc.app.BlockConfirmed(*b)
bc.lastConfirmed = b
bc.setRandomnessFromPending(b)
bc.confirmedBlocks = append(bc.confirmedBlocks, b)
bc.purgeConfig()
}
func (bc *blockChain) setRandomnessFromPending(b *types.Block) {
if r, exist := bc.pendingRandomnesses[b.Position]; exist {
if !r.BlockHash.Equal(b.Hash) {
panic(fmt.Errorf("mismathed randomness: %s %s", b, r))
}
b.Finalization.Randomness = r.Randomness
delete(bc.pendingRandomnesses, b.Position)
}
}
|