/
hashgraph.go
1689 lines (1420 loc) · 42.4 KB
/
hashgraph.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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package hashgraph
import (
"fmt"
"math"
"reflect"
"sort"
"strconv"
"github.com/mosaicnetworks/babble/src/common"
"github.com/mosaicnetworks/babble/src/peers"
"github.com/sirupsen/logrus"
)
const (
// ROOT_DEPTH determines how many FrameEvents are included in the Root. It
// is preferable not to make ROOT_DEPTH configurable because if peers use
// diffent values, they will produce different Roots, different Frames, and
// different Blocks. Perhaps this parameter should be tied to the number of
// Peers rather than hard-coded.
ROOT_DEPTH = 10
// COIN_ROUND_FREQ defines the frequency of coin rounds
COIN_ROUND_FREQ = float64(4)
)
// Hashgraph is a DAG of Events. It also contains methods to extract a consensus
// order of Events and map them onto a blockchain.
type Hashgraph struct {
Store Store // store of Events, Rounds, and Blocks
UndeterminedEvents []string // [index] => hash . FIFO queue of Events whose consensus order is not yet determined
PendingRounds *PendingRoundsCache // FIFO queue of Rounds which have not attained consensus yet
PendingSignatures *SigPool // Pool of Block signatures that need to be processed (matched with Blocks)
LastConsensusRound *int // index of last consensus round
FirstConsensusRound *int // index of first consensus round (only used in tests)
AnchorBlock *int // index of last block with enough signatures
roundLowerBound *int // rounds and events below this lower bound have a special treatement (cf fastsync)
LastCommitedRoundEvents int // number of events in round before LastConsensusRound
ConsensusTransactions int // number of consensus transactions
PendingLoadedEvents int // number of loaded events that are not yet committed
commitCallback InternalCommitCallback // commit block callback
topologicalIndex int // counter used to order events in topological order (only local)
ancestorCache *common.LRU
selfAncestorCache *common.LRU
stronglySeeCache *common.LRU
roundCache *common.LRU
timestampCache *common.LRU
witnessCache *common.LRU
logger *logrus.Entry
}
// NewHashgraph instantiates a Hashgraph with an underlying data store and a
// commit callback
func NewHashgraph(store Store, commitCallback InternalCommitCallback, logger *logrus.Entry) *Hashgraph {
if logger == nil {
log := logrus.New()
log.Level = logrus.DebugLevel
logger = logrus.NewEntry(log)
}
cacheSize := store.CacheSize()
hashgraph := Hashgraph{
Store: store,
PendingRounds: NewPendingRoundsCache(),
PendingSignatures: NewSigPool(),
commitCallback: commitCallback,
ancestorCache: common.NewLRU(cacheSize, nil),
selfAncestorCache: common.NewLRU(cacheSize, nil),
stronglySeeCache: common.NewLRU(cacheSize, nil),
roundCache: common.NewLRU(cacheSize, nil),
timestampCache: common.NewLRU(cacheSize, nil),
witnessCache: common.NewLRU(cacheSize, nil),
logger: logger,
}
return &hashgraph
}
// Init sets the initial PeerSet, which also creates the corresponding Roots and
// updates the Repertoire.
func (h *Hashgraph) Init(peerSet *peers.PeerSet) error {
if err := h.Store.SetPeerSet(0, peerSet); err != nil {
return fmt.Errorf("Error setting PeerSet: %v", err)
}
return nil
}
/*******************************************************************************
Private Methods
*******************************************************************************/
//true if y is an ancestor of x
func (h *Hashgraph) ancestor(x, y string) (bool, error) {
if c, ok := h.ancestorCache.Get(key{x, y}); ok {
return c.(bool), nil
}
a, err := h._ancestor(x, y)
if err != nil {
return false, err
}
h.ancestorCache.Add(key{x, y}, a)
return a, nil
}
func (h *Hashgraph) _ancestor(x, y string) (bool, error) {
if x == y {
return true, nil
}
ex, err := h.Store.GetEvent(x)
if err != nil {
return false, err
}
ey, err := h.Store.GetEvent(y)
if err != nil {
return false, err
}
entry, ok := ex.lastAncestors[ey.Creator()]
res := ok && entry.Index >= ey.Index()
return res, nil
}
//true if y is a self-ancestor of x
func (h *Hashgraph) selfAncestor(x, y string) (bool, error) {
if c, ok := h.selfAncestorCache.Get(key{x, y}); ok {
return c.(bool), nil
}
a, err := h._selfAncestor(x, y)
if err != nil {
return false, err
}
h.selfAncestorCache.Add(key{x, y}, a)
return a, nil
}
func (h *Hashgraph) _selfAncestor(x, y string) (bool, error) {
if x == y {
return true, nil
}
ex, err := h.Store.GetEvent(x)
if err != nil {
return false, err
}
ey, err := h.Store.GetEvent(y)
if err != nil {
return false, err
}
return ex.Creator() == ey.Creator() && ex.Index() >= ey.Index(), nil
}
/*
True if x sees y
It is not necessary to detect forks because we assume that the InsertEvent
function makes it impossible to insert two Events at the same height for
the same participant.
*/
func (h *Hashgraph) see(x, y string) (bool, error) {
return h.ancestor(x, y)
}
//true if x strongly sees y based on peers set
func (h *Hashgraph) stronglySee(x, y string, peers *peers.PeerSet) (bool, error) {
if c, ok := h.stronglySeeCache.Get(treKey{x, y, peers.Hex()}); ok {
return c.(bool), nil
}
ss, err := h._stronglySee(x, y, peers)
if err != nil {
return false, err
}
h.stronglySeeCache.Add(treKey{x, y, peers.Hex()}, ss)
return ss, nil
}
func (h *Hashgraph) _stronglySee(x, y string, peers *peers.PeerSet) (bool, error) {
ex, err := h.Store.GetEvent(x)
if err != nil {
return false, err
}
ey, err := h.Store.GetEvent(y)
if err != nil {
return false, err
}
c := 0
for p := range peers.ByPubKey {
xla, xlaok := ex.lastAncestors[p]
yfd, yfdok := ey.firstDescendants[p]
if xlaok && yfdok && xla.Index >= yfd.Index {
c++
}
}
return c >= peers.SuperMajority(), nil
}
func (h *Hashgraph) round(x string) (int, error) {
if c, ok := h.roundCache.Get(x); ok {
return c.(int), nil
}
r, err := h._round(x)
if err != nil {
return -1, err
}
h.roundCache.Add(x, r)
return r, nil
}
func (h *Hashgraph) _round(x string) (int, error) {
ex, err := h.Store.GetEvent(x)
if err != nil {
return math.MinInt32, err
}
parentRound := -1
if ex.SelfParent() != "" {
parentRound, err = h.round(ex.SelfParent())
if err != nil {
return math.MinInt32, err
}
}
if ex.OtherParent() != "" {
opRound, err := h.round(ex.OtherParent())
if err != nil {
return math.MinInt32, err
}
if opRound > parentRound {
parentRound = opRound
}
}
if parentRound == -1 {
return 0, nil
}
round := parentRound
// Retrieve the ParentRound's PeerSet and count strongly-seen witnesses
// based on that PeerSet.
parentRoundObj, err := h.Store.GetRound(parentRound)
if err != nil {
return math.MinInt32, err
}
parentRoundPeerSet, err := h.Store.GetPeerSet(parentRound)
if err != nil {
return math.MinInt32, err
}
c := 0
for _, w := range parentRoundObj.Witnesses() {
ss, err := h.stronglySee(x, w, parentRoundPeerSet)
if err != nil {
return math.MinInt32, err
}
if ss {
c++
}
}
// If there is a super-majority of strongly-seen witnesses, increment the
// round
if c >= parentRoundPeerSet.SuperMajority() {
round++
}
return round, nil
}
func (h *Hashgraph) witness(x string) (bool, error) {
if c, ok := h.witnessCache.Get(x); ok {
return c.(bool), nil
}
r, err := h._witness(x)
if err != nil {
return false, err
}
h.witnessCache.Add(x, r)
return r, nil
}
//true if x is a witness (first event of a round for the owner)
func (h *Hashgraph) _witness(x string) (bool, error) {
ex, err := h.Store.GetEvent(x)
if err != nil {
return false, err
}
xRound, err := h.round(x)
if err != nil {
return false, err
}
//does the creator belong to the PeerSet?
peerSet, err := h.Store.GetPeerSet(xRound)
if err != nil {
return false, err
}
if _, ok := peerSet.ByPubKey[ex.Creator()]; !ok {
return false, nil
}
spRound := -1
if ex.SelfParent() != "" {
spRound, err = h.round(ex.SelfParent())
if err != nil {
return false, err
}
}
return xRound > spRound, nil
}
func (h *Hashgraph) roundReceived(x string) (int, error) {
ex, err := h.Store.GetEvent(x)
if err != nil {
return -1, err
}
res := -1
if ex.roundReceived != nil {
res = *ex.roundReceived
}
return res, nil
}
func (h *Hashgraph) lamportTimestamp(x string) (int, error) {
if c, ok := h.timestampCache.Get(x); ok {
return c.(int), nil
}
r, err := h._lamportTimestamp(x)
if err != nil {
return -1, err
}
h.timestampCache.Add(x, r)
return r, nil
}
func (h *Hashgraph) _lamportTimestamp(x string) (int, error) {
plt := -1
ex, err := h.Store.GetEvent(x)
if err != nil {
return math.MinInt32, err
}
if ex.SelfParent() != "" {
plt, err = h.lamportTimestamp(ex.SelfParent())
if err != nil {
return math.MinInt32, err
}
}
if ex.OtherParent() != "" {
opLT := math.MinInt32
if _, err := h.Store.GetEvent(ex.OtherParent()); err == nil {
//if we know the other-parent, fetch its Round directly
t, err := h.lamportTimestamp(ex.OtherParent())
if err != nil {
return math.MinInt32, err
}
opLT = t
}
if opLT > plt {
plt = opLT
}
}
return plt + 1, nil
}
//round(x) - round(y)
func (h *Hashgraph) roundDiff(x, y string) (int, error) {
xRound, err := h.round(x)
if err != nil {
return math.MinInt32, fmt.Errorf("event %s has negative round", x)
}
yRound, err := h.round(y)
if err != nil {
return math.MinInt32, fmt.Errorf("event %s has negative round", y)
}
return xRound - yRound, nil
}
// Check the SelfParent is the Creator's last known Event
func (h *Hashgraph) checkSelfParent(event *Event) error {
selfParent := event.SelfParent()
creator := event.Creator()
creatorLastKnown, err := h.Store.LastEventFrom(creator)
if err != nil {
// First Event
if common.IsStore(err, common.Empty) && selfParent == "" {
return nil
}
// This is not a normal error
return NewSelfParentError(err.Error(), false)
}
selfParentLegit := selfParent == creatorLastKnown
// This error is to be expected in normal operation and may not be a cause
// of concern. It can arrise when the hashgraph is being accessed
// concurrently by multiple go-routines.
if !selfParentLegit {
return NewSelfParentError("Self-parent not last known event by creator", true)
}
return nil
}
//Check if we know the OtherParent
func (h *Hashgraph) checkOtherParent(event *Event) error {
otherParent := event.OtherParent()
if otherParent != "" {
//Check if we have it
_, err := h.Store.GetEvent(otherParent)
if err != nil {
return fmt.Errorf("Other-parent not known")
}
}
return nil
}
//initialize arrays of last ancestors and first descendants
func (h *Hashgraph) initEventCoordinates(event *Event) error {
event.lastAncestors = NewCoordinatesMap()
event.firstDescendants = NewCoordinatesMap()
selfParent, selfParentError := h.Store.GetEvent(event.SelfParent())
otherParent, otherParentError := h.Store.GetEvent(event.OtherParent())
if selfParentError != nil && otherParentError == nil {
event.lastAncestors = otherParent.lastAncestors.Copy()
} else if otherParentError != nil && selfParentError == nil {
event.lastAncestors = selfParent.lastAncestors.Copy()
} else if otherParentError == nil && selfParentError == nil {
selfParentLastAncestors := selfParent.lastAncestors
otherParentLastAncestors := otherParent.lastAncestors
event.lastAncestors = selfParentLastAncestors.Copy()
for p, ola := range otherParentLastAncestors {
sla, ok := event.lastAncestors[p]
if !ok || sla.Index < ola.Index {
event.lastAncestors[p] = EventCoordinates{
Index: ola.Index,
Hash: ola.Hash,
}
}
}
}
event.firstDescendants[event.Creator()] = EventCoordinates{
Index: event.Index(),
Hash: event.Hex(),
}
event.lastAncestors[event.Creator()] = EventCoordinates{
Index: event.Index(),
Hash: event.Hex(),
}
return nil
}
// update first descendant of each ancestor to point to event
func (h *Hashgraph) updateAncestorFirstDescendant(event *Event) error {
for _, c := range event.lastAncestors {
ah := c.Hash
for {
a, err := h.Store.GetEvent(ah)
if err != nil {
break
}
_, ok := a.firstDescendants[event.Creator()]
if !ok {
a.firstDescendants[event.Creator()] = EventCoordinates{
Index: event.Index(),
Hash: event.Hex(),
}
if err := h.Store.SetEvent(a); err != nil {
return err
}
// Stopping condition. We don't want to go all the way down to
// the bottom of the hashgraph (which could happen if the event
// is from a new participant). So we stop at the ancestors that
// are witnesses.
if w, err := h.witness(ah); err == nil && w {
break
}
ah = a.SelfParent()
} else {
break
}
}
}
return nil
}
func (h *Hashgraph) createFrameEvent(x string) (*FrameEvent, error) {
ev, err := h.Store.GetEvent(x)
if err != nil {
return nil, fmt.Errorf("FrameEvent %s not found", x)
}
round, err := h.round(x)
if err != nil {
return nil, err
}
roundInfo, err := h.Store.GetRound(round)
if err != nil {
return nil, err
}
te, ok := roundInfo.CreatedEvents[x]
if !ok {
return nil, fmt.Errorf("round %d CreatedEvents[%s] not found", round, x)
}
witness := te.Witness
lt, err := h.lamportTimestamp(x)
if err != nil {
return nil, err
}
frameEvent := &FrameEvent{
Core: ev,
Round: round,
LamportTimestamp: lt,
Witness: witness,
}
return frameEvent, nil
}
func (h *Hashgraph) createRoot(participant string, head string) (*Root, error) {
root := NewRoot()
if head != "" {
headEvent, err := h.createFrameEvent(head)
if err != nil {
return nil, err
}
reverseRootEvents := []*FrameEvent{headEvent}
index := headEvent.Core.Index()
for i := 0; i < ROOT_DEPTH; i++ {
index = index - 1
if index >= 0 {
peh, err := h.Store.ParticipantEvent(participant, index)
if err != nil {
break
}
rev, err := h.createFrameEvent(peh)
if err != nil {
return nil, err
}
reverseRootEvents = append(reverseRootEvents, rev)
} else {
break
}
}
for i := len(reverseRootEvents) - 1; i >= 0; i-- {
root.Insert(reverseRootEvents[i])
}
}
return root, nil
}
func (h *Hashgraph) SetWireInfo(event *Event) error {
selfParentIndex := -1
otherParentCreatorID := uint32(0)
otherParentIndex := -1
creator, ok := h.Store.RepertoireByPubKey()[event.Creator()]
if !ok {
return fmt.Errorf("Creator %s not found", event.Creator())
}
if event.SelfParent() != "" {
selfParent, err := h.Store.GetEvent(event.SelfParent())
if err != nil {
return err
}
selfParentIndex = selfParent.Index()
}
if event.OtherParent() != "" {
otherParent, err := h.Store.GetEvent(event.OtherParent())
if err != nil {
return err
}
otherParentCreator, ok := h.Store.RepertoireByPubKey()[otherParent.Creator()]
if !ok {
return fmt.Errorf("Creator %s not found", otherParent.Creator())
}
otherParentCreatorID = otherParentCreator.ID()
otherParentIndex = otherParent.Index()
}
event.SetWireInfo(selfParentIndex,
otherParentCreatorID,
otherParentIndex,
creator.ID())
return nil
}
//Remove processed Signatures from SigPool
func (h *Hashgraph) removeProcessedSignatures(processedSignatures map[string]bool) {
for k := range processedSignatures {
h.PendingSignatures.Remove(k)
}
}
//InsertEventAndRunConsensus inserts an Event in the Hashgraph and call the
//consensus methods.
func (h *Hashgraph) InsertEventAndRunConsensus(event *Event, setWireInfo bool) error {
if err := h.InsertEvent(event, setWireInfo); err != nil {
if !IsNormalSelfParentError(err) {
h.logger.WithError(err).Errorf("InsertEvent")
}
return err
}
if err := h.DivideRounds(); err != nil {
h.logger.WithError(err).Errorf("DivideRounds")
return err
}
if err := h.DecideFame(); err != nil {
h.logger.WithError(err).Errorf("DecideFame")
return err
}
if err := h.DecideRoundReceived(); err != nil {
h.logger.WithError(err).Errorf("DecideRoundReceived")
return err
}
if err := h.ProcessDecidedRounds(); err != nil {
h.logger.WithError(err).Errorf("ProcessDecidedRounds")
return err
}
return nil
}
//InsertEvent attempts to insert an Event in the DAG. It verifies the signature,
//checks the ancestors are known, and prevents the introduction of forks.
func (h *Hashgraph) InsertEvent(event *Event, setWireInfo bool) error {
//verify signature
if ok, err := event.Verify(); !ok {
if err != nil {
return err
}
fields := logrus.Fields{
"event": event.Hex(),
"creator": event.Creator(),
"self_parent": event.SelfParent(),
}
h.logger.WithFields(fields).Errorf("Invalid Event signature")
return fmt.Errorf("Invalid Event signature %s", event.Hex())
}
// checkSelfParent can return normal errors (expected when the hasghraph is
// accessed by multiple concurrent go-routines). Normal errors are only
// logged at the Trace level, which helps to keep logs clean in normal
// operations.
err := h.checkSelfParent(event)
if err != nil {
fields := logrus.Fields{
"event": event.Hex(),
"creator": event.Creator(),
"self_parent": event.SelfParent(),
}
if !IsNormalSelfParentError(err) {
h.logger.WithFields(fields).WithError(err).Errorf("CheckSelfParent")
} else {
h.logger.WithFields(fields).WithError(err).Tracef("CheckSelfParent")
}
return err
}
if err := h.checkOtherParent(event); err != nil {
h.logger.WithFields(logrus.Fields{
"event": event.Hex(),
"creator": event.Creator(),
"other_parent": event.OtherParent(),
}).WithError(err).Errorf("CheckOtherParent")
return err
}
event.topologicalIndex = h.topologicalIndex
h.topologicalIndex++
if setWireInfo {
if err := h.SetWireInfo(event); err != nil {
return fmt.Errorf("SetWireInfo: %s", err)
}
}
if err := h.initEventCoordinates(event); err != nil {
return fmt.Errorf("InitEventCoordinates: %s", err)
}
if err := h.Store.SetEvent(event); err != nil {
return fmt.Errorf("SetEvent: %s", err)
}
if err := h.updateAncestorFirstDescendant(event); err != nil {
return fmt.Errorf("UpdateAncestorFirstDescendant: %s", err)
}
h.UndeterminedEvents = append(h.UndeterminedEvents, event.Hex())
if event.IsLoaded() {
h.PendingLoadedEvents++
}
for _, bs := range event.BlockSignatures() {
h.logger.Debugf("Inserting pending signature %v", bs.Key())
h.PendingSignatures.Add(bs)
}
return nil
}
// InsertFrameEvent inserts the FrameEvent's core Event, without checking its
// parents or signature. It doesnt add the Event to UndeterminedEvents either.
func (h *Hashgraph) InsertFrameEvent(frameEvent *FrameEvent) error {
event := frameEvent.Core
// Set caches so round, witness, and timestamp won't be recalculated
h.roundCache.Add(event.Hex(), frameEvent.Round)
h.witnessCache.Add(event.Hex(), frameEvent.Witness)
h.timestampCache.Add(event.Hex(), frameEvent.LamportTimestamp)
// Set the event's private fields for later use
event.SetRound(frameEvent.Round)
event.SetLamportTimestamp(frameEvent.LamportTimestamp)
//Create/update RoundInfo object in store
roundInfo, err := h.Store.GetRound(frameEvent.Round)
if err != nil {
if !common.IsStore(err, common.KeyNotFound) {
return err
}
roundInfo = NewRoundInfo()
}
roundInfo.AddCreatedEvent(event.Hex(), frameEvent.Witness)
err = h.Store.SetRound(frameEvent.Round, roundInfo)
if err != nil {
return err
}
// Init EventCoordinates.
if err := h.initEventCoordinates(event); err != nil {
return fmt.Errorf("InitEventCoordinates: %s", err)
}
if err := h.Store.SetEvent(event); err != nil {
return fmt.Errorf("SetEvent: %s", err)
}
if err := h.updateAncestorFirstDescendant(event); err != nil {
return fmt.Errorf("UpdateAncestorFirstDescendant: %s", err)
}
// All FrameEvents are consensus events, ie. they have a round-received and
// were committed. We need to record FrameEvents as consensus events because
// it comes into play in GetFrame/CreateRoot
if err := h.Store.AddConsensusEvent(event); err != nil {
return fmt.Errorf("AddConsensusEvent: %v", event)
}
return nil
}
// DivideRounds assigns a Round and LamportTimestamp to Events, and flags them
// as witnesses if necessary. Pushes Rounds in the PendingRounds queue if
// necessary.
func (h *Hashgraph) DivideRounds() error {
for _, hash := range h.UndeterminedEvents {
ev, err := h.Store.GetEvent(hash)
if err != nil {
return err
}
updateEvent := false
// Compute Event's round, update the corresponding Round object, and add
// it to the PendingRounds queue if necessary.
if ev.round == nil {
roundNumber, err := h.round(hash)
if err != nil {
return err
}
ev.SetRound(roundNumber)
updateEvent = true
roundInfo, err := h.Store.GetRound(roundNumber)
if err != nil {
if !common.IsStore(err, common.KeyNotFound) {
return err
}
roundInfo = NewRoundInfo()
}
if !h.PendingRounds.Queued(roundNumber) &&
!roundInfo.decided &&
(h.roundLowerBound == nil || roundNumber > *h.roundLowerBound) {
h.PendingRounds.Set(&PendingRound{roundNumber, false})
}
witness, err := h.witness(hash)
if err != nil {
return err
}
roundInfo.AddCreatedEvent(hash, witness)
err = h.Store.SetRound(roundNumber, roundInfo)
if err != nil {
return err
}
}
// Compute the Event's LamportTimestamp
if ev.lamportTimestamp == nil {
lamportTimestamp, err := h.lamportTimestamp(hash)
if err != nil {
return err
}
ev.SetLamportTimestamp(lamportTimestamp)
updateEvent = true
}
if updateEvent {
h.Store.SetEvent(ev)
}
}
return nil
}
// DecideFame decides if witnesses are famous
func (h *Hashgraph) DecideFame() error {
// Initialize the vote map
votes := make(map[string](map[string]bool)) //[x][y]=>vote(x,y)
setVote := func(votes map[string]map[string]bool, x, y string, vote bool) {
if votes[x] == nil {
votes[x] = make(map[string]bool)
}
votes[x][y] = vote
}
decidedRounds := []int{}
for _, r := range h.PendingRounds.GetOrderedPendingRounds() {
roundIndex := r.Index
rRoundInfo, err := h.Store.GetRound(roundIndex)
if err != nil {
return err
}
rPeerSet, err := h.Store.GetPeerSet(roundIndex)
if err != nil {
return err
}
for _, x := range rRoundInfo.Witnesses() {
if rRoundInfo.IsDecided(x) {
continue
}
VOTE_LOOP:
for j := roundIndex + 1; j <= h.Store.LastRound(); j++ {
jRoundInfo, err := h.Store.GetRound(j)
if err != nil {
return err
}
jPeerSet, err := h.Store.GetPeerSet(j)
if err != nil {
return err
}
for _, y := range jRoundInfo.Witnesses() {
diff := j - roundIndex
if diff == 1 {
ycx, err := h.see(y, x)
if err != nil {
return err
}
setVote(votes, y, x, ycx)
} else {
jPrevRoundInfo, err := h.Store.GetRound(j - 1)
if err != nil {
return err
}
jPrevPeerSet, err := h.Store.GetPeerSet(j - 1)
if err != nil {
return err
}
// collection of witnesses from round j-1 that are
// strongly seen by y, based on round j-1 PeerSet.
ssWitnesses := []string{}
for _, w := range jPrevRoundInfo.Witnesses() {
ss, err := h.stronglySee(y, w, jPrevPeerSet)
if err != nil {
return err
}
if ss {
ssWitnesses = append(ssWitnesses, w)
}
}
// Collect votes from these witnesses.
yays := 0
nays := 0
for _, w := range ssWitnesses {
if votes[w][x] {
yays++
} else {
nays++
}
}
v := false
t := nays
if yays >= nays {
v = true
t = yays
}
// normal round
if math.Mod(float64(diff), COIN_ROUND_FREQ) > 0 {
if t >= jPeerSet.SuperMajority() {
rRoundInfo.SetFame(x, v)
setVote(votes, y, x, v)
break VOTE_LOOP // break out of j loop
} else {
setVote(votes, y, x, v)
}
} else { // coin round
if t >= jPeerSet.SuperMajority() {
setVote(votes, y, x, v)
} else {
setVote(votes, y, x, middleBit(y)) // middle bit of y's hash
}
}
}
}
}
}
if rRoundInfo.WitnessesDecided(rPeerSet) {
decidedRounds = append(decidedRounds, roundIndex)
}
err = h.Store.SetRound(roundIndex, rRoundInfo)
if err != nil {
return err
}
}
h.PendingRounds.Update(decidedRounds)
return nil
}
// DecideRoundReceived assigns a RoundReceived to undetermined events when they