forked from perlin-network/wavelet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ledger.go
1507 lines (1181 loc) · 38.1 KB
/
ledger.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
// Copyright (c) 2019 Perlin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package wavelet
import (
"bytes"
"context"
"encoding/binary"
"encoding/hex"
"fmt"
"github.com/perlin-network/wavelet/lru"
"math/rand"
"strings"
"sync"
"time"
"github.com/perlin-network/noise"
"github.com/perlin-network/noise/skademlia"
"github.com/perlin-network/wavelet/avl"
"github.com/perlin-network/wavelet/log"
"github.com/perlin-network/wavelet/store"
"github.com/perlin-network/wavelet/sys"
"github.com/pkg/errors"
"golang.org/x/crypto/blake2b"
"google.golang.org/grpc"
"google.golang.org/grpc/connectivity"
"google.golang.org/grpc/peer"
)
type bitset uint8
const (
outOfSync bitset = 0
synced = 1
finalized = 2
fullySynced = 3
)
var (
ErrOutOfSync = errors.New("Node is currently ouf of sync. Please try again later.")
)
type Ledger struct {
client *skademlia.Client
metrics *Metrics
indexer *Indexer
accounts *Accounts
rounds *Rounds
graph *Graph
gossiper *Gossiper
finalizer *Snowball
syncer *Snowball
consensus sync.WaitGroup
broadcastNops bool
broadcastNopsMaxDepth uint64
broadcastNopsDelay time.Time
broadcastNopsLock sync.Mutex
sync chan struct{}
syncVotes chan vote
syncStatus bitset
syncStatusLock sync.RWMutex
cacheCollapse *lru.LRU
cacheChunks *lru.LRU
sendQuota chan struct{}
stallDetector *StallDetector
}
type config struct {
GCDisabled bool
Genesis *string
MaxMemoryMB uint64
}
type Option func(cfg *config)
// WithoutGC disables GC. Used for testing purposes.
func WithoutGC() Option {
return func(cfg *config) {
cfg.GCDisabled = true
}
}
func WithGenesis(genesis *string) Option {
return func(cfg *config) {
cfg.Genesis = genesis
}
}
func WithMaxMemoryMB(n uint64) Option {
return func(cfg *config) {
cfg.MaxMemoryMB = n
}
}
func NewLedger(kv store.KV, client *skademlia.Client, opts ...Option) *Ledger {
var cfg config
for _, opt := range opts {
opt(&cfg)
}
logger := log.Node()
metrics := NewMetrics(context.TODO())
indexer := NewIndexer()
accounts := NewAccounts(kv)
if !cfg.GCDisabled {
go accounts.GC(context.Background())
}
rounds, err := NewRounds(kv, sys.PruningLimit)
var round *Round
if rounds != nil && err != nil {
genesis := performInception(accounts.tree, cfg.Genesis)
if err := accounts.Commit(nil); err != nil {
logger.Fatal().Err(err).Msg("BUG: accounts.Commit")
}
ptr := &genesis
if _, err := rounds.Save(ptr); err != nil {
logger.Fatal().Err(err).Msg("BUG: rounds.Save")
}
round = ptr
} else if rounds != nil {
round = rounds.Latest()
}
if round == nil {
logger.Fatal().Err(err).Msg("BUG: COULD NOT FIND GENESIS, OR STORAGE IS CORRUPTED.")
}
graph := NewGraph(WithMetrics(metrics), WithIndexer(indexer), WithRoot(round.End), VerifySignatures())
gossiper := NewGossiper(context.TODO(), client, metrics)
finalizer := NewSnowball(WithName("finalizer"), WithBeta(sys.SnowballBeta))
syncer := NewSnowball(WithName("syncer"), WithBeta(sys.SnowballBeta))
ledger := &Ledger{
client: client,
metrics: metrics,
indexer: indexer,
accounts: accounts,
rounds: rounds,
graph: graph,
gossiper: gossiper,
finalizer: finalizer,
syncer: syncer,
syncStatus: finalized, // we start node as out of sync, but finalized
sync: make(chan struct{}),
syncVotes: make(chan vote, sys.SnowballK),
cacheCollapse: lru.NewLRU(16),
cacheChunks: lru.NewLRU(1024), // In total, it will take up 1024 * 4MB.
sendQuota: make(chan struct{}, 2000),
}
stop := make(chan struct{}) // TODO: Real graceful stop.
var stallDetector *StallDetector
stallDetector = NewStallDetector(stop, StallDetectorConfig{
MaxMemoryMB: cfg.MaxMemoryMB,
}, StallDetectorDelegate{
PrepareShutdown: func(err error) {
logger := log.Node()
logger.Error().Err(err).Msg("Shutting down node...")
},
})
go stallDetector.Run()
ledger.stallDetector = stallDetector
ledger.PerformConsensus()
go ledger.SyncToLatestRound()
go ledger.PushSendQuota()
return ledger
}
// AddTransaction adds a transaction to the ledger. If the transaction has
// never been added in the ledgers graph before, it is pushed to the gossip
// mechanism to then be gossiped to this nodes peers. If the transaction is
// invalid or fails any validation checks, an error is returned. No error
// is returned if the transaction has already existed int he ledgers graph
// beforehand.
func (l *Ledger) AddTransaction(tx Transaction) error {
if l.isOutOfSync() && tx.Sender == l.client.Keys().PublicKey() {
return ErrOutOfSync
}
err := l.graph.AddTransaction(tx)
if err != nil && errors.Cause(err) != ErrAlreadyExists {
return err
}
if err == nil {
l.TakeSendQuota()
l.gossiper.Push(tx)
l.broadcastNopsLock.Lock()
if tx.Tag != sys.TagNop && tx.Sender == l.client.Keys().PublicKey() {
l.broadcastNops = true
l.broadcastNopsDelay = time.Now()
if tx.Depth > l.broadcastNopsMaxDepth {
l.broadcastNopsMaxDepth = tx.Depth
}
}
l.broadcastNopsLock.Unlock()
}
return nil
}
// Find searches through complete transaction and account indices for a specified
// query string. All indices that queried are in the form of tries. It is safe
// to call this method concurrently.
func (l *Ledger) Find(query string, max int) (results []string) {
var err error
if max > 0 {
results = make([]string, 0, max)
}
prefix := []byte(query)
if len(query)%2 == 1 { // Cut off a single character.
prefix = prefix[:len(prefix)-1]
}
prefix, err = hex.DecodeString(string(prefix))
if err != nil {
return nil
}
bucketPrefix := append(keyAccounts[:], keyAccountNonce[:]...)
fullQuery := append(bucketPrefix, prefix...)
l.Snapshot().IterateFrom(fullQuery, func(key, _ []byte) bool {
if !bytes.HasPrefix(key, fullQuery) {
return false
}
if max > 0 && len(results) >= max {
return false
}
results = append(results, hex.EncodeToString(key[len(bucketPrefix):]))
return true
})
var count = -1
if max > 0 {
count = max - len(results)
}
return append(results, l.indexer.Find(query, count)...)
}
// PushSendQuota permits one token into this nodes send quota bucket every millisecond
// such that the node may add one single transaction into its graph.
func (l *Ledger) PushSendQuota() {
for range time.Tick(1 * time.Millisecond) {
select {
case l.sendQuota <- struct{}{}:
default:
}
}
}
// TakeSendQuota removes one token from this nodes send quota bucket to signal
// that the node has added one single transaction into its graph.
func (l *Ledger) TakeSendQuota() bool {
select {
case <-l.sendQuota:
return true
default:
return false
}
}
// Protocol returns an implementation of WaveletServer to handle incoming
// RPC and streams for the ledger. The protocol is agnostic to whatever
// choice of network stack is used with Wavelet, though by default it is
// intended to be used with gRPC and Noise.
func (l *Ledger) Protocol() *Protocol {
return &Protocol{ledger: l}
}
// Graph returns the directed-acyclic-graph of transactions accompanying
// the ledger.
func (l *Ledger) Graph() *Graph {
return l.graph
}
// Finalizer returns the Snowball finalizer which finalizes the contents of individual
// consensus rounds.
func (l *Ledger) Finalizer() *Snowball {
return l.finalizer
}
// Rounds returns the round manager for the ledger.
func (l *Ledger) Rounds() *Rounds {
return l.rounds
}
// PerformConsensus spawns workers related to performing consensus, such as pulling
// missing transactions and incrementally finalizing intervals of transactions in
// the ledgers graph.
func (l *Ledger) PerformConsensus() {
go l.PullMissingTransactions()
go l.SyncTransactions()
go l.FinalizeRounds()
}
func (l *Ledger) Snapshot() *avl.Tree {
return l.accounts.Snapshot()
}
// BroadcastingNop returns true if the node is
// supposed to broadcast nop transaction.
func (l *Ledger) BroadcastingNop() bool {
l.broadcastNopsLock.Lock()
broadcastNops := l.broadcastNops
l.broadcastNopsLock.Unlock()
return broadcastNops
}
// BroadcastNop has the node send a nop transaction should they have sufficient
// balance available. They are broadcasted if no other transaction that is not a nop transaction
// is not broadcasted by the node after 500 milliseconds. These conditions only apply so long as
// at least one transaction gets broadcasted by the node within the current round. Once a round
// is tentatively being finalized, a node will stop broadcasting nops.
func (l *Ledger) BroadcastNop() *Transaction {
l.broadcastNopsLock.Lock()
broadcastNops := l.broadcastNops
broadcastNopsDelay := l.broadcastNopsDelay
l.broadcastNopsLock.Unlock()
if !broadcastNops || time.Now().Sub(broadcastNopsDelay) < 100*time.Millisecond {
return nil
}
keys := l.client.Keys()
publicKey := keys.PublicKey()
balance, _ := ReadAccountBalance(l.accounts.Snapshot(), publicKey)
// FIXME(kenta): FOR TESTNET ONLY. FAUCET DOES NOT GET ANY PERLs DEDUCTED.
if balance < sys.TransactionFeeAmount && hex.EncodeToString(publicKey[:]) != sys.FaucetAddress {
return nil
}
nop := AttachSenderToTransaction(keys, NewTransaction(keys, sys.TagNop, nil), l.graph.FindEligibleParents()...)
if err := l.AddTransaction(nop); err != nil {
return nil
}
return l.graph.FindTransaction(nop.ID)
}
func (l *Ledger) SyncTransactions() {
l.consensus.Add(1)
defer l.consensus.Done()
pullingPeriod := 1 * time.Second
t := time.NewTimer(pullingPeriod)
for {
t.Reset(pullingPeriod)
select {
case <-l.sync:
return
case <-t.C:
}
l.syncStatusLock.RLock()
status := l.syncStatus
l.syncStatusLock.RUnlock()
if status != synced {
continue
}
closestPeers := l.client.ClosestPeers()
peers := make([]*grpc.ClientConn, 0, len(closestPeers))
for _, p := range closestPeers {
if p.GetState() == connectivity.Ready {
peers = append(peers, p)
}
}
if len(peers) == 0 {
select {
case <-l.sync:
return
default:
}
continue
}
rand.Shuffle(len(peers), func(i, j int) {
peers[i], peers[j] = peers[j], peers[i]
})
now := time.Now()
currentDepth := l.graph.RootDepth()
lowLimit := currentDepth - sys.MaxDepthDiff
highLimit := currentDepth + sys.MaxDownloadDepthDiff
txs := l.Graph().GetTransactionsByDepth(&lowLimit, &highLimit)
ids := make([][]byte, len(txs))
for i, tx := range txs {
ids[i] = tx.ID[:]
}
req := &DownloadTxRequest{
Depth: currentDepth,
SkipIds: ids,
}
conn := peers[0]
client := NewWaveletClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
batch, err := client.DownloadTx(ctx, req)
if err != nil {
fmt.Println("failed to download missing transactions:", err)
cancel()
continue
}
cancel()
txCount, logicalCount := 0, 0
for _, buf := range batch.Transactions {
tx, err := UnmarshalTransaction(bytes.NewReader(buf))
if err != nil {
fmt.Printf("error unmarshaling downloaded tx [%v]: %+v", err, tx)
continue
}
if err := l.AddTransaction(tx); err != nil && errors.Cause(err) != ErrMissingParents {
fmt.Printf("error adding synced tx to graph [%v]: %+v\n", err, tx)
continue
}
logicalCount += tx.LogicalUnits()
txCount++
}
if txCount > 0 {
logger := log.Consensus("transaction-sync")
logger.Debug().
Int("synced_tx", txCount).
Int("logical_tx", logicalCount).
Dur("duration", time.Now().Sub(now)).
Msg("Transaction downloaded")
}
}
}
// PullMissingTransactions is an infinite loop continually sending RPC requests
// to pull any transactions identified to be missing by the ledger. It periodically
// samples a random peer from the network, and requests the peer for the contents
// of all missing transactions by their respective IDs. When the ledger is in amidst
// synchronizing/teleporting ahead to a new round, the infinite loop will be cleaned
// up. It is intended to call PullMissingTransactions() in a new goroutine.
func (l *Ledger) PullMissingTransactions() {
l.consensus.Add(1)
defer l.consensus.Done()
for {
select {
case <-l.sync:
return
default:
}
missing := l.graph.Missing()
if len(missing) == 0 {
select {
case <-l.sync:
return
case <-time.After(100 * time.Millisecond):
}
continue
}
closestPeers := l.client.ClosestPeers()
peers := make([]*grpc.ClientConn, 0, len(closestPeers))
for _, p := range closestPeers {
if p.GetState() == connectivity.Ready {
peers = append(peers, p)
}
}
if len(peers) == 0 {
select {
case <-l.sync:
return
case <-time.After(1 * time.Second):
}
continue
}
rand.Shuffle(len(peers), func(i, j int) {
peers[i], peers[j] = peers[j], peers[i]
})
rand.Shuffle(len(missing), func(i, j int) {
missing[i], missing[j] = missing[j], missing[i]
})
if len(missing) > 256 {
missing = missing[:256]
}
req := &DownloadMissingTxRequest{Ids: make([][]byte, len(missing))}
for i, id := range missing {
req.Ids[i] = id[:]
}
conn := peers[0]
client := NewWaveletClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
batch, err := client.DownloadMissingTx(ctx, req)
if err != nil {
fmt.Println("failed to download missing transactions:", err)
cancel()
continue
}
cancel()
count := int64(0)
for _, buf := range batch.Transactions {
tx, err := UnmarshalTransaction(bytes.NewReader(buf))
if err != nil {
fmt.Printf("error unmarshaling downloaded tx [%v]: %+v\n", err, tx)
continue
}
if err := l.AddTransaction(tx); err != nil && errors.Cause(err) != ErrMissingParents {
fmt.Printf("error adding downloaded tx to graph [%v]: %+v\n", err, tx)
continue
}
count += int64(tx.LogicalUnits())
}
l.metrics.downloadedTX.Mark(count)
l.metrics.receivedTX.Mark(count)
}
}
// FinalizeRounds periodically attempts to find an eligible critical transaction suited for the
// current round. If it finds one, it will then proceed to perform snowball sampling over its
// peers to decide on a single critical transaction that serves as an ending point for the
// current consensus round. The round is finalized, transactions of the finalized round are
// applied to the current ledger state, and the graph is updated to cleanup artifacts from
// the old round.
func (l *Ledger) FinalizeRounds() {
l.consensus.Add(1)
defer l.consensus.Done()
FINALIZE_ROUNDS:
for {
select {
case <-l.sync:
return
default:
}
if len(l.client.ClosestPeers()) < sys.SnowballK {
select {
case <-l.sync:
return
case <-time.After(1 * time.Second):
}
continue FINALIZE_ROUNDS
}
current := l.rounds.Latest()
currentDifficulty := current.ExpectedDifficulty(sys.MinDifficulty, sys.DifficultyScaleFactor)
if preferred := l.finalizer.Preferred(); preferred == nil {
eligible := l.graph.FindEligibleCritical(currentDifficulty)
if eligible == nil {
nop := l.BroadcastNop()
if nop != nil {
if !nop.IsCritical(currentDifficulty) {
select {
case <-l.sync:
return
case <-time.After(500 * time.Microsecond):
}
}
continue FINALIZE_ROUNDS
}
select {
case <-l.sync:
return
case <-time.After(1 * time.Millisecond):
}
continue FINALIZE_ROUNDS
}
results, err := l.collapseTransactions(current.Index+1, current.End, *eligible, false)
if err != nil {
fmt.Println("error collapsing transactions during finalization", err)
continue
}
candidate := NewRound(current.Index+1, results.snapshot.Checksum(), uint64(results.appliedCount), current.End, *eligible)
l.finalizer.Prefer(&candidate)
continue FINALIZE_ROUNDS
}
// Only stop broadcasting nops if the most recently added transaction
// has been applied
l.broadcastNopsLock.Lock()
preferred := l.finalizer.Preferred().(*Round)
if l.broadcastNops && l.broadcastNopsMaxDepth <= preferred.End.Depth {
l.broadcastNops = false
}
l.broadcastNopsLock.Unlock()
workerChan := make(chan *grpc.ClientConn, 16)
var workerWG sync.WaitGroup
workerWG.Add(cap(workerChan))
voteChan := make(chan vote, sys.SnowballK)
go CollectVotes(l.accounts, l.finalizer, voteChan, &workerWG, sys.SnowballK)
req := &QueryRequest{RoundIndex: current.Index + 1}
for i := 0; i < cap(workerChan); i++ {
go func() {
for conn := range workerChan {
f := func() {
client := NewWaveletClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
p := &peer.Peer{}
res, err := client.Query(ctx, req, grpc.Peer(p))
if err != nil {
cancel()
fmt.Println("error while querying peer: ", err)
return
}
cancel()
l.metrics.queried.Mark(1)
info := noise.InfoFromPeer(p)
if info == nil {
return
}
voter, ok := info.Get(skademlia.KeyID).(*skademlia.ID)
if !ok {
return
}
round, err := UnmarshalRound(bytes.NewReader(res.Round))
if err != nil {
voteChan <- vote{voter: voter, value: ZeroRoundPtr}
return
}
if round.ID == ZeroRoundID || round.Start.ID == ZeroTransactionID || round.End.ID == ZeroTransactionID {
voteChan <- vote{voter: voter, value: ZeroRoundPtr}
return
}
if round.End.Depth <= round.Start.Depth {
return
}
if round.Index != current.Index+1 {
if round.Index > sys.SyncIfRoundsDifferBy+current.Index {
select {
case l.syncVotes <- vote{voter: voter, value: &round}:
default:
}
}
return
}
if round.Start.ID != current.End.ID {
return
}
if err := l.AddTransaction(round.Start); err != nil {
return
}
if err := l.AddTransaction(round.End); err != nil {
return
}
if !round.End.IsCritical(currentDifficulty) {
return
}
results, err := l.collapseTransactions(round.Index, round.Start, round.End, false)
if err != nil {
if !strings.Contains(err.Error(), "missing ancestor") {
fmt.Println("error collapsing transactions:", err)
}
return
}
if uint64(results.appliedCount) != round.Applied {
fmt.Printf("applied %d but expected %d, rejected = %d, ignored = %d\n", results.appliedCount, round.Applied, results.rejectedCount, results.ignoredCount)
return
}
if results.snapshot.Checksum() != round.Merkle {
fmt.Printf("got merkle %x but expected %x\n", results.snapshot.Checksum(), round.Merkle)
return
}
voteChan <- vote{voter: voter, value: &round}
}
l.metrics.queryLatency.Time(f)
}
workerWG.Done()
}()
}
for !l.finalizer.Decided() {
select {
case <-l.sync:
close(workerChan)
workerWG.Wait()
workerWG.Add(1)
close(voteChan)
workerWG.Wait() // Wait for vote processor worker to stop
return
default:
}
// Randomly sample a peer to query
peers, err := SelectPeers(l.client.ClosestPeers(), sys.SnowballK)
if err != nil {
close(workerChan)
workerWG.Wait()
workerWG.Add(1)
close(voteChan)
workerWG.Wait() // Wait for vote processor worker to stop
continue FINALIZE_ROUNDS
}
for _, p := range peers {
workerChan <- p
}
}
close(workerChan)
workerWG.Wait() // Wait for query workers to stop
workerWG.Add(1)
close(voteChan)
workerWG.Wait() // Wait for vote processor worker to stop
preferred = l.finalizer.Preferred().(*Round)
l.finalizer.Reset()
results, err := l.collapseTransactions(preferred.Index, preferred.Start, preferred.End, true)
if err != nil {
if !strings.Contains(err.Error(), "missing ancestor") {
fmt.Println("error collapsing transactions during finalization:", err)
}
continue
}
if uint64(results.appliedCount) != preferred.Applied {
fmt.Printf("Expected to have applied %d transactions finalizing a round, but only applied %d transactions instead.\n", preferred.Applied, results.appliedCount)
continue
}
if results.snapshot.Checksum() != preferred.Merkle {
fmt.Printf("Expected preferred round's merkle root to be %x, but got %x.\n", preferred.Merkle, results.snapshot.Checksum())
continue
}
pruned, err := l.rounds.Save(preferred)
if err != nil {
fmt.Printf("Failed to save preferred round to our database: %v\n", err)
}
if pruned != nil {
count := l.graph.PruneBelowDepth(pruned.End.Depth)
logger := log.Consensus("prune")
logger.Debug().
Int("num_tx", count).
Uint64("current_round_id", preferred.Index).
Uint64("pruned_round_id", pruned.Index).
Msg("Pruned away round and transactions.")
}
l.graph.UpdateRootDepth(preferred.End.Depth)
if err = l.accounts.Commit(results.snapshot); err != nil {
fmt.Printf("Failed to commit collaped state to our database: %v\n", err)
}
l.metrics.acceptedTX.Mark(int64(results.appliedCount))
l.LogChanges(results.snapshot, current.Index)
l.applySync(finalized)
logger := log.Consensus("round_end")
logger.Info().
Int("num_applied_tx", results.appliedCount).
Int("num_rejected_tx", results.rejectedCount).
Int("num_ignored_tx", results.ignoredCount).
Uint64("old_round", current.Index).
Uint64("new_round", preferred.Index).
Uint8("old_difficulty", current.ExpectedDifficulty(sys.MinDifficulty, sys.DifficultyScaleFactor)).
Uint8("new_difficulty", preferred.ExpectedDifficulty(sys.MinDifficulty, sys.DifficultyScaleFactor)).
Hex("new_root", preferred.End.ID[:]).
Hex("old_root", current.End.ID[:]).
Hex("new_merkle_root", preferred.Merkle[:]).
Hex("old_merkle_root", current.Merkle[:]).
Uint64("round_depth", preferred.End.Depth-preferred.Start.Depth).
Msg("Finalized consensus round, and initialized a new round.")
//go ExportGraphDOT(finalized, contractIDs.graph)
}
}
type outOfSyncVote struct {
outOfSync bool
}
func (o *outOfSyncVote) GetID() string {
return fmt.Sprintf("%v", o.outOfSync)
}
func (l *Ledger) SyncToLatestRound() {
voteWG := new(sync.WaitGroup)
go CollectVotes(l.accounts, l.syncer, l.syncVotes, voteWG, sys.SnowballK)
syncTimeoutMultiplier := 0
for {
for {
conns, err := SelectPeers(l.client.ClosestPeers(), sys.SnowballK)
if err != nil {
select {
case <-time.After(1 * time.Second):
}
continue
}
current := l.rounds.Latest()
var wg sync.WaitGroup
wg.Add(len(conns))
for _, conn := range conns {
client := NewWaveletClient(conn)
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
p := &peer.Peer{}
res, err := client.CheckOutOfSync(
ctx,
&OutOfSyncRequest{RoundIndex: current.Index},
grpc.Peer(p),
)
if err != nil {
fmt.Println("error while checking out of sync", err)
cancel()
wg.Done()
return
}
cancel()
info := noise.InfoFromPeer(p)
if info == nil {
wg.Done()
return
}
voter, ok := info.Get(skademlia.KeyID).(*skademlia.ID)
if !ok {
wg.Done()
return
}
l.syncVotes <- vote{voter: voter, value: &outOfSyncVote{outOfSync: res.OutOfSync}}
wg.Done()
}()
}
wg.Wait()
if l.syncer.Decided() {
break
}
}
// Reset syncing Snowball sampler. Check if it is a false alarm such that we don't have to sync.
current := l.rounds.Latest()
preferred := l.syncer.Preferred()
oos := preferred.(*outOfSyncVote).outOfSync
if !oos {
l.applySync(synced)
l.syncer.Reset()
if syncTimeoutMultiplier < 60 {
syncTimeoutMultiplier++
}
time.Sleep(time.Duration(syncTimeoutMultiplier) * time.Second)
continue
}
l.setSync(outOfSync)
syncTimeoutMultiplier = 0
shutdown := func() {
close(l.sync)
l.consensus.Wait() // Wait for all consensus-related workers to shutdown.
voteWG.Add(1)
close(l.syncVotes)