-
Notifications
You must be signed in to change notification settings - Fork 107
/
node.go
1318 lines (1147 loc) · 38.8 KB
/
node.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 committee
import (
"container/heap"
"context"
"errors"
"fmt"
"math"
"sync"
"time"
"github.com/eapache/channels"
"github.com/oasisprotocol/oasis-core/go/common/logging"
"github.com/oasisprotocol/oasis-core/go/common/node"
"github.com/oasisprotocol/oasis-core/go/common/pubsub"
"github.com/oasisprotocol/oasis-core/go/common/workerpool"
consensus "github.com/oasisprotocol/oasis-core/go/consensus/api"
commonFlags "github.com/oasisprotocol/oasis-core/go/oasis-node/cmd/common/flags"
registryApi "github.com/oasisprotocol/oasis-core/go/registry/api"
roothashApi "github.com/oasisprotocol/oasis-core/go/roothash/api"
"github.com/oasisprotocol/oasis-core/go/roothash/api/block"
"github.com/oasisprotocol/oasis-core/go/runtime/host"
storageApi "github.com/oasisprotocol/oasis-core/go/storage/api"
"github.com/oasisprotocol/oasis-core/go/storage/mkvs/checkpoint"
mkvsDB "github.com/oasisprotocol/oasis-core/go/storage/mkvs/db/api"
workerCommon "github.com/oasisprotocol/oasis-core/go/worker/common"
"github.com/oasisprotocol/oasis-core/go/worker/common/committee"
"github.com/oasisprotocol/oasis-core/go/worker/common/p2p/rpc"
"github.com/oasisprotocol/oasis-core/go/worker/registration"
"github.com/oasisprotocol/oasis-core/go/worker/storage/api"
storagePub "github.com/oasisprotocol/oasis-core/go/worker/storage/p2p/pub"
storageSync "github.com/oasisprotocol/oasis-core/go/worker/storage/p2p/sync"
)
var (
_ committee.NodeHooks = (*Node)(nil)
// ErrNonLocalBackend is the error returned when the storage backend doesn't implement the LocalBackend interface.
ErrNonLocalBackend = errors.New("storage: storage backend doesn't support local storage")
)
const (
// RoundLatest is a magic value for the latest round.
RoundLatest = math.MaxUint64
defaultUndefinedRound = ^uint64(0)
checkpointSyncRetryDelay = 10 * time.Second
// The maximum number of rounds the worker can be behind the chain before it's sensible for
// it to register as available.
maximumRoundDelayForAvailability = uint64(10)
// The minimum number of rounds the worker can be behind the chain before it's sensible for
// it to stop advertising availability.
minimumRoundDelayForUnavailability = uint64(15)
// The number of rounds ahead of consensus that the worker will allow round waiters to wait.
// Trying to wait for rounds further in the future will return an error immediately.
roundWaitConsensusOffset = uint64(1)
// maxInFlightRounds is the maximum number of rounds that should be fetched before waiting
// for them to be applied.
maxInFlightRounds = 100
)
type roundItem interface {
GetRound() uint64
}
// outOfOrderRoundQueue is a Round()-based min priority queue.
type outOfOrderRoundQueue []roundItem
// Sorting interface.
func (q outOfOrderRoundQueue) Len() int { return len(q) }
func (q outOfOrderRoundQueue) Less(i, j int) bool { return q[i].GetRound() < q[j].GetRound() }
func (q outOfOrderRoundQueue) Swap(i, j int) { q[i], q[j] = q[j], q[i] }
// Push appends x as the last element in the heap's array.
func (q *outOfOrderRoundQueue) Push(x interface{}) {
*q = append(*q, x.(roundItem))
}
// Pop removes and returns the last element in the heap's array.
func (q *outOfOrderRoundQueue) Pop() interface{} {
old := *q
n := len(old)
x := old[n-1]
*q = old[0 : n-1]
return x
}
// fetchedDiff has all the context needed for a single GetDiff operation.
type fetchedDiff struct {
fetched bool
pf rpc.PeerFeedback
err error
round uint64
prevRoot storageApi.Root
thisRoot storageApi.Root
writeLog storageApi.WriteLog
}
func (d *fetchedDiff) GetRound() uint64 {
return d.round
}
type finalizeResult struct {
summary *blockSummary
err error
}
type roundWaiter struct {
round uint64
ch chan uint64
}
// Node watches blocks for storage changes.
type Node struct { // nolint: maligned
commonNode *committee.Node
roleProvider registration.RoleProvider
rpcRoleProvider registration.RoleProvider
roleAvailable bool
logger *logging.Logger
localStorage storageApi.LocalBackend
storageSync storageSync.Client
undefinedRound uint64
fetchPool *workerpool.Pool
workerCommonCfg workerCommon.Config
checkpointer checkpoint.Checkpointer
checkpointSyncCfg *CheckpointSyncConfig
checkpointSyncForced bool
syncedLock sync.RWMutex
syncedState blockSummary
roundWaiters []roundWaiter
blockCh *channels.InfiniteChannel
diffCh chan *fetchedDiff
finalizeCh chan finalizeResult
ctx context.Context
ctxCancel context.CancelFunc
quitCh chan struct{}
workerQuitCh chan struct{}
initCh chan struct{}
}
func NewNode(
commonNode *committee.Node,
fetchPool *workerpool.Pool,
roleProvider registration.RoleProvider,
rpcRoleProvider registration.RoleProvider,
workerCommonCfg workerCommon.Config,
localStorage storageApi.LocalBackend,
checkpointerCfg *checkpoint.CheckpointerConfig,
checkpointSyncCfg *CheckpointSyncConfig,
) (*Node, error) {
initMetrics()
n := &Node{
commonNode: commonNode,
roleProvider: roleProvider,
rpcRoleProvider: rpcRoleProvider,
logger: logging.GetLogger("worker/storage/committee").With("runtime_id", commonNode.Runtime.ID()),
workerCommonCfg: workerCommonCfg,
localStorage: localStorage,
fetchPool: fetchPool,
checkpointSyncCfg: checkpointSyncCfg,
blockCh: channels.NewInfiniteChannel(),
diffCh: make(chan *fetchedDiff),
finalizeCh: make(chan finalizeResult),
quitCh: make(chan struct{}),
workerQuitCh: make(chan struct{}),
initCh: make(chan struct{}),
}
// Validate checkpoint sync configuration.
if err := checkpointSyncCfg.Validate(); err != nil {
return nil, fmt.Errorf("bad checkpoint sync configuration: %w", err)
}
// Initialize sync state.
n.syncedState.Round = defaultUndefinedRound
n.ctx, n.ctxCancel = context.WithCancel(context.Background())
// Create a new checkpointer if enabled.
if checkpointerCfg != nil {
checkpointerCfg = &checkpoint.CheckpointerConfig{
Name: "runtime",
Namespace: commonNode.Runtime.ID(),
CheckInterval: checkpointerCfg.CheckInterval,
RootsPerVersion: 2, // State root and I/O root.
GetParameters: func(ctx context.Context) (*checkpoint.CreationParameters, error) {
rt, rerr := commonNode.Runtime.ActiveDescriptor(ctx)
if rerr != nil {
return nil, fmt.Errorf("failed to retrieve runtime descriptor: %w", rerr)
}
blk, rerr := commonNode.Consensus.RootHash().GetGenesisBlock(ctx, &roothashApi.RuntimeRequest{
RuntimeID: rt.ID,
Height: consensus.HeightLatest,
})
if rerr != nil {
return nil, fmt.Errorf("failed to retrieve genesis block: %w", rerr)
}
return &checkpoint.CreationParameters{
Interval: rt.Storage.CheckpointInterval,
NumKept: rt.Storage.CheckpointNumKept,
ChunkSize: rt.Storage.CheckpointChunkSize,
InitialVersion: blk.Header.Round,
}, nil
},
GetRoots: func(ctx context.Context, version uint64) ([]storageApi.Root, error) {
blk, berr := commonNode.Runtime.History().GetBlock(ctx, version)
if berr != nil {
return nil, berr
}
return blk.Header.StorageRoots(), nil
},
}
var err error
n.checkpointer, err = checkpoint.NewCheckpointer(
n.ctx,
localStorage.NodeDB(),
localStorage.Checkpointer(),
*checkpointerCfg,
)
if err != nil {
return nil, fmt.Errorf("failed to create checkpointer: %w", err)
}
}
// Register prune handler.
commonNode.Runtime.History().Pruner().RegisterHandler(&pruneHandler{
logger: n.logger,
node: n,
})
// Register storage sync service.
commonNode.P2P.RegisterProtocolServer(storageSync.NewServer(commonNode.Runtime.ID(), localStorage))
n.storageSync = storageSync.NewClient(commonNode.P2P, commonNode.Runtime.ID())
// Register storage pub service if configured.
if rpcRoleProvider != nil {
commonNode.P2P.RegisterProtocolServer(storagePub.NewServer(commonNode.Runtime.ID(), localStorage))
}
return n, nil
}
// Service interface.
// Name returns the service name.
func (n *Node) Name() string {
return "committee node"
}
// Start causes the worker to start responding to tendermint new block events.
func (n *Node) Start() error {
go n.watchQuit()
go n.worker()
if n.checkpointer != nil {
go n.consensusCheckpointSyncer()
}
return nil
}
// Stop causes the worker to stop watching and shut down.
func (n *Node) Stop() {
n.ctxCancel()
}
// Quit returns a channel that will be closed when the worker stops.
func (n *Node) Quit() <-chan struct{} {
return n.quitCh
}
// Cleanup cleans up any leftover state after the worker is stopped.
func (n *Node) Cleanup() {
// Nothing to do here?
}
// Initialized returns a channel that will be closed once the worker finished starting up.
func (n *Node) Initialized() <-chan struct{} {
return n.initCh
}
// GetStatus returns the storage committee node status.
func (n *Node) GetStatus(ctx context.Context) (*api.Status, error) {
n.syncedLock.RLock()
defer n.syncedLock.RUnlock()
return &api.Status{
LastFinalizedRound: n.syncedState.Round,
}, nil
}
func (n *Node) WaitForRound(round uint64, root *storageApi.Root) (<-chan uint64, error) {
retCh := make(chan uint64, 1)
if root != nil {
round = root.Version
}
consensusRound := roothashApi.RoundInvalid
n.commonNode.CrossNode.Lock()
if blk := n.commonNode.CurrentBlock; blk != nil {
consensusRound = blk.Header.Round
}
n.commonNode.CrossNode.Unlock()
if round > consensusRound+roundWaitConsensusOffset && !commonFlags.DebugDontBlameOasis() {
close(retCh)
return nil, storageApi.ErrVersionNotFound
}
n.syncedLock.Lock()
defer n.syncedLock.Unlock()
if round <= n.syncedState.Round || (root != nil && n.localStorage.NodeDB().HasRoot(*root)) {
retCh <- n.syncedState.Round
close(retCh)
return retCh, nil
}
n.roundWaiters = append(n.roundWaiters, roundWaiter{
round: round,
ch: retCh,
})
return retCh, nil
}
func (n *Node) PauseCheckpointer(pause bool) error {
if !commonFlags.DebugDontBlameOasis() {
return api.ErrCantPauseCheckpointer
}
n.checkpointer.Pause(pause)
return nil
}
// GetLocalStorage returns the local storage backend used by this storage node.
func (n *Node) GetLocalStorage() storageApi.LocalBackend {
return n.localStorage
}
// NodeHooks implementation.
func (n *Node) HandlePeerTx(ctx context.Context, tx []byte) error {
// Nothing to do here.
return nil
}
// Guarded by CrossNode.
func (n *Node) HandleEpochTransitionLocked(snapshot *committee.EpochSnapshot) {
// Nothing to do here.
}
// Guarded by CrossNode.
func (n *Node) HandleNewBlockEarlyLocked(*block.Block) {
// Nothing to do here.
}
// Guarded by CrossNode.
func (n *Node) HandleNewBlockLocked(blk *block.Block) {
// Notify the state syncer that there is a new block.
n.blockCh.In() <- blk
}
// Guarded by CrossNode.
func (n *Node) HandleNewEventLocked(*roothashApi.Event) {
// Nothing to do here.
}
func (n *Node) HandleRuntimeHostEvent(ev *host.Event) {
// Nothing to do here.
}
// Watcher implementation.
// GetLastSynced returns the height, IORoot hash and StateRoot hash of the last block that was fully synced to.
func (n *Node) GetLastSynced() (uint64, storageApi.Root, storageApi.Root) {
n.syncedLock.RLock()
defer n.syncedLock.RUnlock()
var io, state storageApi.Root
for _, root := range n.syncedState.Roots {
switch root.Type {
case storageApi.RootTypeIO:
io = root
case storageApi.RootTypeState:
state = root
}
}
return n.syncedState.Round, io, state
}
func (n *Node) fetchDiff(round uint64, prevRoot, thisRoot storageApi.Root) {
result := &fetchedDiff{
fetched: false,
pf: rpc.NewNopPeerFeedback(),
round: round,
prevRoot: prevRoot,
thisRoot: thisRoot,
}
defer func() {
n.diffCh <- result
}()
// Check if the new root doesn't already exist.
if !n.localStorage.NodeDB().HasRoot(thisRoot) {
result.fetched = true
if thisRoot.Hash.Equal(&prevRoot.Hash) {
// Even if HasRoot returns false the root can still exist if it is equal
// to the previous root and the root was emitted by the consensus committee
// directly (e.g., during an epoch transition). In this case we need to
// still apply the (empty) write log.
result.writeLog = storageApi.WriteLog{}
} else {
// New root does not yet exist in storage and we need to fetch it from a
// remote node.
n.logger.Debug("calling GetDiff",
"old_root", prevRoot,
"new_root", thisRoot,
)
ctx, cancel := context.WithCancel(n.ctx)
defer cancel()
rsp, pf, err := n.storageSync.GetDiff(ctx, &storageSync.GetDiffRequest{StartRoot: prevRoot, EndRoot: thisRoot})
if err != nil {
result.err = err
return
}
result.pf = pf
result.writeLog = rsp.WriteLog
}
}
}
func (n *Node) finalize(summary *blockSummary) {
err := n.localStorage.NodeDB().Finalize(n.ctx, summary.Roots)
switch err {
case nil:
n.logger.Debug("storage round finalized",
"round", summary.Round,
)
case storageApi.ErrAlreadyFinalized:
// This can happen if we are restoring after a roothash migration or if
// we crashed before updating the sync state.
n.logger.Warn("storage round already finalized",
"round", summary.Round,
)
err = nil
default:
n.logger.Error("failed to finalize storage round",
"err", err,
"round", summary.Round,
)
}
n.finalizeCh <- finalizeResult{
summary: summary,
err: err,
}
}
func (n *Node) initGenesis(rt *registryApi.Runtime, genesisBlock *block.Block) error {
n.logger.Info("initializing storage at genesis")
// Check what the latest finalized version in the database is as we may be using a database
// from a previous version or network.
latestVersion, _ := n.localStorage.NodeDB().GetLatestVersion()
stateRoot := storageApi.Root{
Namespace: rt.ID,
Version: genesisBlock.Header.Round,
Type: storageApi.RootTypeState,
Hash: genesisBlock.Header.StateRoot,
}
var compatible bool
switch {
case latestVersion < stateRoot.Version:
// Latest version is earlier than the genesis state root. In case it has the same hash
// we can fill in all the missing versions.
maybeRoot := stateRoot
maybeRoot.Version = latestVersion
if n.localStorage.NodeDB().HasRoot(maybeRoot) {
n.logger.Debug("latest version earlier than genesis state root, filling in versions",
"genesis_state_root", genesisBlock.Header.StateRoot,
"genesis_round", genesisBlock.Header.Round,
"latest_version", latestVersion,
)
for v := latestVersion; v < stateRoot.Version; v++ {
err := n.localStorage.Apply(n.ctx, &storageApi.ApplyRequest{
Namespace: rt.ID,
RootType: storageApi.RootTypeState,
SrcRound: v,
SrcRoot: stateRoot.Hash,
DstRound: v + 1,
DstRoot: stateRoot.Hash,
WriteLog: nil, // No changes.
})
if err != nil {
return fmt.Errorf("failed to fill in version %d: %w", v, err)
}
err = n.localStorage.NodeDB().Finalize(n.ctx, []storageApi.Root{{
Namespace: rt.ID,
Version: v + 1,
Type: storageApi.RootTypeState,
Hash: stateRoot.Hash,
// We can ignore I/O roots.
}})
if err != nil {
return fmt.Errorf("failed to finalize version %d: %w", v, err)
}
}
compatible = true
}
default:
// Latest finalized version is the same or ahead, root must exist.
compatible = n.localStorage.NodeDB().HasRoot(stateRoot)
}
// If we are incompatible and the local version is greater or the same as the genesis version,
// we cannot do anything. If the local version is lower we assume the node will sync from a
// different node.
if !compatible && latestVersion >= stateRoot.Version {
n.logger.Error("existing state is incompatible with runtime genesis state",
"genesis_state_root", genesisBlock.Header.StateRoot,
"genesis_round", genesisBlock.Header.Round,
"latest_version", latestVersion,
)
return fmt.Errorf("existing state is incompatible with runtime genesis state")
}
if !compatible {
// Database is empty, so assume the state will be replicated from another node.
n.logger.Warn("non-empty state root but no state available, assuming replication",
"state_root", genesisBlock.Header.StateRoot,
)
n.checkpointSyncForced = true
}
return nil
}
func (n *Node) flushSyncedState(summary *blockSummary) uint64 {
n.syncedLock.Lock()
defer n.syncedLock.Unlock()
n.syncedState = *summary
// Wake up any round waiters.
filtered := make([]roundWaiter, 0, len(n.roundWaiters))
for _, w := range n.roundWaiters {
if w.round <= n.syncedState.Round {
w.ch <- n.syncedState.Round
close(w.ch)
} else {
filtered = append(filtered, w)
}
}
n.roundWaiters = filtered
return n.syncedState.Round
}
func (n *Node) watchQuit() {
// Close quit channel on any worker quitting.
<-n.workerQuitCh
close(n.quitCh)
}
func (n *Node) consensusCheckpointSyncer() {
// Make sure we always create a checkpoint when the consensus layer creates a checkpoint. The
// reason why we do this is to make it faster for storage nodes that use consensus state sync
// to catch up as exactly the right checkpoint will be available.
consensusCp := n.commonNode.Consensus.Checkpointer()
if consensusCp == nil {
return
}
// Wait for the common node to be initialized.
select {
case <-n.commonNode.Initialized():
case <-n.ctx.Done():
return
}
// Determine the maximum number of consensus checkpoints to keep.
consensusParams, err := n.commonNode.Consensus.GetParameters(n.ctx, consensus.HeightLatest)
if err != nil {
n.logger.Error("failed to fetch consensus parameters",
"err", err,
)
return
}
ch, sub, err := consensusCp.WatchCheckpoints()
if err != nil {
n.logger.Error("failed to watch checkpoints",
"err", err,
)
return
}
defer sub.Close()
var (
versions []uint64
blkCh <-chan *consensus.Block
blkSub pubsub.ClosableSubscription
)
defer func() {
if blkCh != nil {
blkSub.Close()
blkSub = nil
blkCh = nil
}
}()
for {
select {
case <-n.quitCh:
return
case <-n.ctx.Done():
return
case version := <-ch:
// We need to wait for the next version as that is what will be in the consensus
// checkpoint.
versions = append(versions, version+1)
// Make sure that we limit the size of the checkpoint queue.
if uint64(len(versions)) > consensusParams.Parameters.StateCheckpointNumKept {
versions = versions[1:]
}
n.logger.Debug("consensus checkpoint detected, queuing runtime checkpoint",
"version", version+1,
"num_versions", len(versions),
)
if blkCh == nil {
blkCh, blkSub, err = n.commonNode.Consensus.WatchBlocks(n.ctx)
if err != nil {
n.logger.Error("failed to watch blocks",
"err", err,
)
continue
}
}
case blk := <-blkCh:
// If there's nothing remaining, unsubscribe.
if len(versions) == 0 {
n.logger.Debug("no more queued consensus checkpoint versions")
blkSub.Close()
blkSub = nil
blkCh = nil
continue
}
var newVersions []uint64
for idx, version := range versions {
if version > uint64(blk.Height) {
// We need to wait for further versions.
newVersions = versions[idx:]
break
}
// Lookup what runtime round corresponds to the given consensus layer version and make
// sure we checkpoint it.
blk, err := n.commonNode.Consensus.RootHash().GetLatestBlock(n.ctx, &roothashApi.RuntimeRequest{
RuntimeID: n.commonNode.Runtime.ID(),
Height: int64(version),
})
if err != nil {
n.logger.Error("failed to get runtime block corresponding to consensus checkpoint",
"err", err,
"height", version,
)
continue
}
// We may have not yet synced the corresponding runtime round locally. In this case
// we need to wait until this is the case.
n.syncedLock.RLock()
lastSyncedRound := n.syncedState.Round
n.syncedLock.RUnlock()
if blk.Header.Round > lastSyncedRound {
n.logger.Debug("runtime round not available yet for checkpoint, waiting",
"height", version,
"round", blk.Header.Round,
"last_synced_round", lastSyncedRound,
)
newVersions = versions[idx:]
break
}
// Force runtime storage checkpointer to create a checkpoint at this round.
n.logger.Info("consensus checkpoint, force runtime checkpoint",
"height", version,
"round", blk.Header.Round,
)
n.checkpointer.ForceCheckpoint(blk.Header.Round)
}
versions = newVersions
}
}
}
// This is only called from the main worker goroutine, so no locking should be necessary.
func (n *Node) nudgeAvailability(lastSynced, latest uint64) {
if lastSynced == n.undefinedRound || latest == n.undefinedRound {
return
}
if latest-lastSynced < maximumRoundDelayForAvailability && !n.roleAvailable {
n.roleProvider.SetAvailable(func(nd *node.Node) error {
return nil
})
if n.rpcRoleProvider != nil {
n.rpcRoleProvider.SetAvailable(func(nd *node.Node) error {
return nil
})
}
n.roleAvailable = true
}
if latest-lastSynced > minimumRoundDelayForUnavailability && n.roleAvailable {
n.roleProvider.SetUnavailable()
if n.rpcRoleProvider != nil {
n.rpcRoleProvider.SetUnavailable()
}
n.roleAvailable = false
}
}
func (n *Node) worker() { // nolint: gocyclo
defer close(n.workerQuitCh)
defer close(n.diffCh)
// Wait for the common node to be initialized.
select {
case <-n.commonNode.Initialized():
case <-n.ctx.Done():
close(n.initCh)
return
}
n.logger.Info("starting committee node")
// Determine genesis block.
genesisBlock, err := n.commonNode.Consensus.RootHash().GetGenesisBlock(n.ctx, &roothashApi.RuntimeRequest{
RuntimeID: n.commonNode.Runtime.ID(),
Height: consensus.HeightLatest,
})
if err != nil {
n.logger.Error("can't retrieve genesis block", "err", err)
return
}
n.undefinedRound = genesisBlock.Header.Round - 1
// Determine last finalized storage version.
if version, dbNonEmpty := n.localStorage.NodeDB().GetLatestVersion(); dbNonEmpty {
var blk *block.Block
blk, err = n.commonNode.Runtime.History().GetBlock(n.ctx, version)
switch err {
case nil:
// Set last synced version to last finalized storage version.
n.flushSyncedState(summaryFromBlock(blk))
default:
// Failed to fetch historic block. This is fine when the network just went through a
// dump/restore upgrade and we don't have any information before genesis. We treat the
// database as unsynced and will proceed to either use checkpoints or sync iteratively.
n.logger.Warn("failed to fetch historic block",
"err", err,
"round", version,
)
}
}
var fetcherGroup sync.WaitGroup
n.syncedLock.RLock()
cachedLastRound := n.syncedState.Round
n.syncedLock.RUnlock()
if cachedLastRound == defaultUndefinedRound || cachedLastRound < genesisBlock.Header.Round {
cachedLastRound = n.undefinedRound
}
// Initialize genesis from the runtime descriptor.
isInitialStartup := (cachedLastRound == n.undefinedRound)
if isInitialStartup {
var rt *registryApi.Runtime
rt, err = n.commonNode.Runtime.ActiveDescriptor(n.ctx)
if err != nil {
n.logger.Error("failed to retrieve runtime registry descriptor",
"err", err,
)
return
}
if err = n.initGenesis(rt, genesisBlock); err != nil {
n.logger.Error("failed to initialize storage at genesis",
"err", err,
)
return
}
}
// Notify the checkpointer of the genesis round so it can be checkpointed.
if n.checkpointer != nil {
n.checkpointer.ForceCheckpoint(genesisBlock.Header.Round)
n.checkpointer.Flush()
}
// Check if we are able to fetch the first block that we would be syncing if we used iterative
// syncing. In case we cannot (likely because we synced the consensus layer via state sync), we
// must wait for a later checkpoint to become available.
if !n.checkpointSyncForced {
// Determine what is the first round that we would need to sync.
iterativeSyncStart := cachedLastRound
if iterativeSyncStart == n.undefinedRound {
iterativeSyncStart++
}
// Check if we actually have information about that round. This assumes that any reindexing
// was already performed (the common node would not indicate being initialized otherwise).
_, err = n.commonNode.Runtime.History().GetBlock(n.ctx, iterativeSyncStart)
SyncStartCheck:
switch {
case err == nil:
case errors.Is(err, roothashApi.ErrNotFound):
// No information is available about the initial round. Query the earliest historic
// block and check if that block has the genesis state root and empty I/O root.
var earlyBlk *block.Block
earlyBlk, err = n.commonNode.Runtime.History().GetEarliestBlock(n.ctx)
switch err {
case nil:
// Make sure the state root is still the same as at genesis time.
if !earlyBlk.Header.StateRoot.Equal(&genesisBlock.Header.StateRoot) {
break
}
// Make sure the I/O root is empty.
if !earlyBlk.Header.IORoot.IsEmpty() {
break
}
// If this is the case, we can start syncing from this round instead. Fill in the
// remaining versions to make sure they actually exist in the database.
n.logger.Debug("filling in versions to genesis",
"genesis_round", genesisBlock.Header.Round,
"earliest_round", earlyBlk.Header.Round,
)
for v := genesisBlock.Header.Round; v < earlyBlk.Header.Round; v++ {
err = n.localStorage.Apply(n.ctx, &storageApi.ApplyRequest{
Namespace: n.commonNode.Runtime.ID(),
RootType: storageApi.RootTypeState,
SrcRound: v,
SrcRoot: genesisBlock.Header.StateRoot,
DstRound: v + 1,
DstRoot: genesisBlock.Header.StateRoot,
WriteLog: nil, // No changes.
})
switch err {
case nil:
case storageApi.ErrAlreadyFinalized:
// Ignore already finalized versions.
continue
default:
n.logger.Error("failed to fill in version",
"version", v,
"err", err,
)
return
}
err = n.localStorage.NodeDB().Finalize(n.ctx, []storageApi.Root{{
Namespace: n.commonNode.Runtime.ID(),
Version: v + 1,
Type: storageApi.RootTypeState,
Hash: genesisBlock.Header.StateRoot,
// We can ignore I/O roots.
}})
if err != nil {
n.logger.Error("failed to finalize filled in version",
"version", v,
"err", err,
)
return
}
}
cachedLastRound = n.flushSyncedState(summaryFromBlock(earlyBlk))
// No need to force a checkpoint sync.
break SyncStartCheck
default:
// This should never happen as the block should exist.
n.logger.Warn("failed to query earliest block in local history",
"err", err,
)
}
// No information is available about this round, force checkpoint sync.
n.logger.Warn("forcing checkpoint sync as we don't have authoritative block info",
"round", iterativeSyncStart,
)
n.checkpointSyncForced = true
default:
// Unknown error while fetching block information, abort.
n.logger.Error("failed to query block",
"err", err,
)
return
}
}
n.logger.Info("worker initialized",
"genesis_round", genesisBlock.Header.Round,
"last_synced", cachedLastRound,
)
outOfOrderDoneDiffs := &outOfOrderRoundQueue{}
outOfOrderFinalizable := &outOfOrderRoundQueue{}
syncingRounds := make(map[uint64]*inFlight)
hashCache := make(map[uint64]*blockSummary)
lastFullyAppliedRound := cachedLastRound
heap.Init(outOfOrderDoneDiffs)
// Try to perform initial sync from state and io checkpoints if either:
//
// - Checkpoint sync has been forced because there is insufficient information available to use
// incremental sync.
//
// - We haven't synced anything yet and checkpoint sync is not disabled.
//
if (isInitialStartup && !n.checkpointSyncCfg.Disabled) || n.checkpointSyncForced {
var (
summary *blockSummary
attempt int
)
CheckpointSyncRetry:
for {
summary, err = n.syncCheckpoints(genesisBlock.Header.Round)
if err == nil {
break
}
attempt++
switch n.checkpointSyncForced {
case true:
// We have no other options but to perform a checkpoint sync as we are missing
// either state or authoritative blocks.
n.logger.Info("checkpoint sync required, retrying",
"err", err,
"attempt", attempt,
)
case false:
if attempt > 1 {
break CheckpointSyncRetry
}
// Try syncing again. The main reason for this is the sync failing due to a
// checkpoint pruning race condition (where nodes list a checkpoint which is
// then deleted just before we request its chunks). One retry is enough.
n.logger.Info("first checkpoint sync failed, trying once more", "err", err)
}
// Delay before retrying.
select {
case <-time.After(checkpointSyncRetryDelay):
case <-n.ctx.Done():
return
}
}
if err != nil {
n.logger.Info("checkpoint sync failed", "err", err)
} else {
cachedLastRound = n.flushSyncedState(summary)
lastFullyAppliedRound = cachedLastRound