-
Notifications
You must be signed in to change notification settings - Fork 179
/
state.go
1015 lines (903 loc) · 34.2 KB
/
state.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 badger
import (
"errors"
"fmt"
"sync/atomic"
"github.com/dgraph-io/badger/v2"
"github.com/onflow/flow-go/consensus/hotstuff"
"github.com/onflow/flow-go/model/flow"
"github.com/onflow/flow-go/module"
statepkg "github.com/onflow/flow-go/state"
"github.com/onflow/flow-go/state/protocol"
"github.com/onflow/flow-go/state/protocol/invalid"
"github.com/onflow/flow-go/state/protocol/protocol_state"
"github.com/onflow/flow-go/storage"
"github.com/onflow/flow-go/storage/badger/operation"
"github.com/onflow/flow-go/storage/badger/transaction"
)
// cachedHeader caches a block header and its ID.
type cachedHeader struct {
id flow.Identifier
header *flow.Header
}
type State struct {
metrics module.ComplianceMetrics
db *badger.DB
headers storage.Headers
blocks storage.Blocks
qcs storage.QuorumCertificates
results storage.ExecutionResults
seals storage.Seals
epoch struct {
setups storage.EpochSetups
commits storage.EpochCommits
}
params protocol.Params
protocolStateSnapshotsDB storage.ProtocolState
protocolState protocol.MutableProtocolState
versionBeacons storage.VersionBeacons
// finalizedRootHeight marks the cutoff of the history this node knows about. We cache it in the state
// because it cannot change over the lifecycle of a protocol state instance. It is frequently
// larger than the height of the root block of the spork, (also cached below as
// `sporkRootBlockHeight`), for instance, if the node joined in an epoch after the last spork.
finalizedRootHeight uint64
// sealedRootHeight returns the root block that is sealed.
sealedRootHeight uint64
// sporkRootBlockHeight is the height of the root block in the current spork. We cache it in
// the state, because it cannot change over the lifecycle of a protocol state instance.
// Caution: A node that joined in a later epoch past the spork, the node will likely _not_
// know the spork's root block in full (though it will always know the height).
sporkRootBlockHeight uint64
// cache the latest finalized and sealed block headers as these are common queries.
// It can be cached because the protocol state is solely responsible for updating these values.
cachedFinal *atomic.Pointer[cachedHeader]
cachedSealed *atomic.Pointer[cachedHeader]
}
var _ protocol.State = (*State)(nil)
type BootstrapConfig struct {
// SkipNetworkAddressValidation flags allows skipping all the network address related
// validations not needed for an unstaked node
SkipNetworkAddressValidation bool
}
func defaultBootstrapConfig() *BootstrapConfig {
return &BootstrapConfig{
SkipNetworkAddressValidation: false,
}
}
type BootstrapConfigOptions func(conf *BootstrapConfig)
func SkipNetworkAddressValidation(conf *BootstrapConfig) {
conf.SkipNetworkAddressValidation = true
}
func Bootstrap(
metrics module.ComplianceMetrics,
db *badger.DB,
headers storage.Headers,
seals storage.Seals,
results storage.ExecutionResults,
blocks storage.Blocks,
qcs storage.QuorumCertificates,
setups storage.EpochSetups,
commits storage.EpochCommits,
protocolStateSnapshotsDB storage.ProtocolState,
versionBeacons storage.VersionBeacons,
root protocol.Snapshot,
options ...BootstrapConfigOptions,
) (*State, error) {
config := defaultBootstrapConfig()
for _, opt := range options {
opt(config)
}
isBootstrapped, err := IsBootstrapped(db)
if err != nil {
return nil, fmt.Errorf("failed to determine whether database contains bootstrapped state: %w", err)
}
if isBootstrapped {
return nil, fmt.Errorf("expected empty database")
}
if err := IsValidRootSnapshot(root, !config.SkipNetworkAddressValidation); err != nil {
return nil, fmt.Errorf("cannot bootstrap invalid root snapshot: %w", err)
}
segment, err := root.SealingSegment()
if err != nil {
return nil, fmt.Errorf("could not get sealing segment: %w", err)
}
_, rootSeal, err := root.SealedResult()
if err != nil {
return nil, fmt.Errorf("could not get sealed result for sealing segment: %w", err)
}
err = operation.RetryOnConflictTx(db, transaction.Update, func(tx *transaction.Tx) error {
// sealing segment is in ascending height order, so the tail is the
// oldest ancestor and head is the newest child in the segment
// TAIL <- ... <- HEAD
lastFinalized := segment.Finalized() // the highest block in sealing segment is the last finalized block
lastSealed := segment.Sealed() // the lowest block in sealing segment is the last sealed block
// 1) bootstrap the sealing segment
// creating sealed root block with the rootResult
// creating finalized root block with lastFinalized
err = bootstrapSealingSegment(blocks, qcs, segment, lastFinalized, rootSeal)(tx)
if err != nil {
return fmt.Errorf("could not bootstrap sealing chain segment blocks: %w", err)
}
// 2) insert the root quorum certificate into the database
qc, err := root.QuorumCertificate()
if err != nil {
return fmt.Errorf("could not get root qc: %w", err)
}
err = qcs.StoreTx(qc)(tx)
if err != nil {
return fmt.Errorf("could not insert root qc: %w", err)
}
// 3) initialize the current protocol state height/view pointers
err = transaction.WithTx(bootstrapStatePointers(root))(tx)
if err != nil {
return fmt.Errorf("could not bootstrap height/view pointers: %w", err)
}
// 4) initialize values related to the epoch logic
err = bootstrapEpoch(setups, commits, root.Epochs(), !config.SkipNetworkAddressValidation)(tx)
if err != nil {
return fmt.Errorf("could not bootstrap epoch values: %w", err)
}
// 5) initialize spork params
err = transaction.WithTx(bootstrapSporkInfo(root))(tx)
if err != nil {
return fmt.Errorf("could not bootstrap spork info: %w", err)
}
// 6) set metric values, we pass `false` here since this node has empty storage and doesn't know anything about EFM.
err = updateEpochMetrics(metrics, root, false)
if err != nil {
return fmt.Errorf("could not update epoch metrics: %w", err)
}
metrics.BlockSealed(lastSealed)
metrics.SealedHeight(lastSealed.Header.Height)
metrics.FinalizedHeight(lastFinalized.Header.Height)
for _, block := range segment.Blocks {
metrics.BlockFinalized(block)
}
// 7) bootstrap dynamic protocol state
err = bootstrapProtocolState(segment, root, protocolStateSnapshotsDB)(tx)
if err != nil {
return fmt.Errorf("could not bootstrap protocol state: %w", err)
}
// 8) initialize version beacon
err = transaction.WithTx(boostrapVersionBeacon(root))(tx)
if err != nil {
return fmt.Errorf("could not bootstrap version beacon: %w", err)
}
return nil
})
if err != nil {
return nil, fmt.Errorf("bootstrapping failed: %w", err)
}
instanceParams, err := ReadInstanceParams(db, headers, seals)
if err != nil {
return nil, fmt.Errorf("could not read instance params: %w", err)
}
params := &Params{
GlobalParams: root.Params(),
InstanceParams: instanceParams,
}
return newState(
metrics,
db,
headers,
seals,
results,
blocks,
qcs,
setups,
commits,
protocolStateSnapshotsDB,
versionBeacons,
params,
)
}
// bootstrapProtocolState bootstraps data structures needed for Dynamic Protocol State.
// It inserts the root protocol state and indexes all blocks in the sealing segment assuming that
// dynamic protocol state didn't change in the sealing segment.
// The root snapshot's sealing segment must not straddle any epoch transitions
// or epoch phase transitions.
func bootstrapProtocolState(segment *flow.SealingSegment, root protocol.Snapshot, protocolState storage.ProtocolState) func(tx *transaction.Tx) error {
return func(tx *transaction.Tx) error {
rootProtocolState, err := root.ProtocolState()
if err != nil {
return fmt.Errorf("could not get root protocol state: %w", err)
}
rootProtocolStateEntry := rootProtocolState.Entry().ProtocolStateEntry
protocolStateID := rootProtocolStateEntry.ID()
err = protocolState.StoreTx(protocolStateID, rootProtocolStateEntry)(tx)
if err != nil {
return fmt.Errorf("could not insert root protocol state: %w", err)
}
// NOTE: as specified in the godoc, this code assumes that each block
// in the sealing segment in within the same phase within the same epoch.
// the sealing segment.
for _, block := range segment.AllBlocks() {
err = protocolState.Index(block.ID(), protocolStateID)(tx)
if err != nil {
return fmt.Errorf("could not index root protocol state: %w", err)
}
}
return nil
}
}
// bootstrapSealingSegment inserts all blocks and associated metadata for the
// protocol state root snapshot to disk.
func bootstrapSealingSegment(
blocks storage.Blocks,
qcs storage.QuorumCertificates,
segment *flow.SealingSegment,
head *flow.Block,
rootSeal *flow.Seal,
) func(tx *transaction.Tx) error {
return func(tx *transaction.Tx) error {
for _, result := range segment.ExecutionResults {
err := transaction.WithTx(operation.SkipDuplicates(operation.InsertExecutionResult(result)))(tx)
if err != nil {
return fmt.Errorf("could not insert execution result: %w", err)
}
err = transaction.WithTx(operation.IndexExecutionResult(result.BlockID, result.ID()))(tx)
if err != nil {
return fmt.Errorf("could not index execution result: %w", err)
}
}
// insert the first seal (in case the segment's first block contains no seal)
if segment.FirstSeal != nil {
err := transaction.WithTx(operation.InsertSeal(segment.FirstSeal.ID(), segment.FirstSeal))(tx)
if err != nil {
return fmt.Errorf("could not insert first seal: %w", err)
}
}
// root seal contains the result ID for the sealed root block. If the sealed root block is
// different from the finalized root block, then it means the node dynamically bootstrapped.
// In that case, we should index the result of the sealed root block so that the EN is able
// to execute the next block.
err := transaction.WithTx(operation.SkipDuplicates(operation.IndexExecutionResult(rootSeal.BlockID, rootSeal.ResultID)))(tx)
if err != nil {
return fmt.Errorf("could not index root result: %w", err)
}
for _, block := range segment.ExtraBlocks {
blockID := block.ID()
height := block.Header.Height
err := blocks.StoreTx(block)(tx)
if err != nil {
return fmt.Errorf("could not insert SealingSegment extra block: %w", err)
}
err = transaction.WithTx(operation.IndexBlockHeight(height, blockID))(tx)
if err != nil {
return fmt.Errorf("could not index SealingSegment extra block (id=%x): %w", blockID, err)
}
err = qcs.StoreTx(block.Header.QuorumCertificate())(tx)
if err != nil {
return fmt.Errorf("could not store qc for SealingSegment extra block (id=%x): %w", blockID, err)
}
}
for i, block := range segment.Blocks {
blockID := block.ID()
height := block.Header.Height
err := blocks.StoreTx(block)(tx)
if err != nil {
return fmt.Errorf("could not insert SealingSegment block: %w", err)
}
err = transaction.WithTx(operation.IndexBlockHeight(height, blockID))(tx)
if err != nil {
return fmt.Errorf("could not index SealingSegment block (id=%x): %w", blockID, err)
}
err = qcs.StoreTx(block.Header.QuorumCertificate())(tx)
if err != nil {
return fmt.Errorf("could not store qc for SealingSegment block (id=%x): %w", blockID, err)
}
// index the latest seal as of this block
latestSealID, ok := segment.LatestSeals[blockID]
if !ok {
return fmt.Errorf("missing latest seal for sealing segment block (id=%s)", blockID)
}
// sanity check: make sure the seal exists
var latestSeal flow.Seal
err = transaction.WithTx(operation.RetrieveSeal(latestSealID, &latestSeal))(tx)
if err != nil {
return fmt.Errorf("could not verify latest seal for block (id=%x) exists: %w", blockID, err)
}
err = transaction.WithTx(operation.IndexLatestSealAtBlock(blockID, latestSealID))(tx)
if err != nil {
return fmt.Errorf("could not index block seal: %w", err)
}
// for all but the first block in the segment, index the parent->child relationship
if i > 0 {
err = transaction.WithTx(operation.InsertBlockChildren(block.Header.ParentID, []flow.Identifier{blockID}))(tx)
if err != nil {
return fmt.Errorf("could not insert child index for block (id=%x): %w", blockID, err)
}
}
}
// insert an empty child index for the final block in the segment
err = transaction.WithTx(operation.InsertBlockChildren(head.ID(), nil))(tx)
if err != nil {
return fmt.Errorf("could not insert child index for head block (id=%x): %w", head.ID(), err)
}
return nil
}
}
// bootstrapStatePointers instantiates special pointers used to by the protocol
// state to keep track of special block heights and views.
func bootstrapStatePointers(root protocol.Snapshot) func(*badger.Txn) error {
return func(tx *badger.Txn) error {
segment, err := root.SealingSegment()
if err != nil {
return fmt.Errorf("could not get sealing segment: %w", err)
}
highest := segment.Finalized()
lowest := segment.Sealed()
// find the finalized seal that seals the lowest block, meaning seal.BlockID == lowest.ID()
seal, err := segment.FinalizedSeal()
if err != nil {
return fmt.Errorf("could not get finalized seal from sealing segment: %w", err)
}
safetyData := &hotstuff.SafetyData{
LockedOneChainView: highest.Header.View,
HighestAcknowledgedView: highest.Header.View,
}
// Per convention, all blocks in the sealing segment must be finalized. Therefore, a QC must
// exist for the `highest` block in the sealing segment. The QC for `highest` should be
// contained in the `root` Snapshot and returned by `root.QuorumCertificate()`. Otherwise,
// the Snapshot is incomplete, because consensus nodes require this QC. To reduce the chance of
// accidental misconfiguration undermining consensus liveness, we do the following sanity checks:
// * `rootQC` should not be nil
// * `rootQC` should be for `highest` block, i.e. its view and blockID should match
rootQC, err := root.QuorumCertificate()
if err != nil {
return fmt.Errorf("could not get root QC: %w", err)
}
if rootQC == nil {
return fmt.Errorf("QC for highest (finalized) block in sealing segment cannot be nil")
}
if rootQC.View != highest.Header.View {
return fmt.Errorf("root QC's view %d does not match the highest block in sealing segment (view %d)", rootQC.View, highest.Header.View)
}
if rootQC.BlockID != highest.Header.ID() {
return fmt.Errorf("root QC is for block %v, which does not match the highest block %v in sealing segment", rootQC.BlockID, highest.Header.ID())
}
livenessData := &hotstuff.LivenessData{
CurrentView: highest.Header.View + 1,
NewestQC: rootQC,
}
// insert initial views for HotStuff
err = operation.InsertSafetyData(highest.Header.ChainID, safetyData)(tx)
if err != nil {
return fmt.Errorf("could not insert safety data: %w", err)
}
err = operation.InsertLivenessData(highest.Header.ChainID, livenessData)(tx)
if err != nil {
return fmt.Errorf("could not insert liveness data: %w", err)
}
// insert height pointers
err = operation.InsertRootHeight(highest.Header.Height)(tx)
if err != nil {
return fmt.Errorf("could not insert finalized root height: %w", err)
}
// the sealed root height is the lowest block in sealing segment
err = operation.InsertSealedRootHeight(lowest.Header.Height)(tx)
if err != nil {
return fmt.Errorf("could not insert sealed root height: %w", err)
}
err = operation.InsertFinalizedHeight(highest.Header.Height)(tx)
if err != nil {
return fmt.Errorf("could not insert finalized height: %w", err)
}
err = operation.InsertSealedHeight(lowest.Header.Height)(tx)
if err != nil {
return fmt.Errorf("could not insert sealed height: %w", err)
}
err = operation.IndexFinalizedSealByBlockID(seal.BlockID, seal.ID())(tx)
if err != nil {
return fmt.Errorf("could not index sealed block: %w", err)
}
return nil
}
}
// bootstrapEpoch bootstraps the protocol state database with information about
// the previous, current, and next epochs as of the root snapshot.
// This has to be bootstrapped before dynamic protocol state.
// TODO(yuraolex): This information can be bootstrapped from dynamic protocol state.
func bootstrapEpoch(
epochSetups storage.EpochSetups,
epochCommits storage.EpochCommits,
epochs protocol.EpochQuery,
verifyNetworkAddress bool,
) func(*transaction.Tx) error {
return func(tx *transaction.Tx) error {
previous := epochs.Previous()
current := epochs.Current()
next := epochs.Next()
// build the status as we go
status := new(flow.EpochStatus)
var setups []*flow.EpochSetup
var commits []*flow.EpochCommit
// insert previous epoch if it exists
_, err := previous.Counter()
if err == nil {
// if there is a previous epoch, both setup and commit events must exist
setup, err := protocol.ToEpochSetup(previous)
if err != nil {
return fmt.Errorf("could not get previous epoch setup event: %w", err)
}
commit, err := protocol.ToEpochCommit(previous)
if err != nil {
return fmt.Errorf("could not get previous epoch commit event: %w", err)
}
if err := protocol.IsValidEpochSetup(setup, verifyNetworkAddress); err != nil {
return fmt.Errorf("invalid setup: %w", err)
}
if err := protocol.IsValidEpochCommit(commit, setup); err != nil {
return fmt.Errorf("invalid commit: %w", err)
}
err = indexFirstHeight(previous)(tx.DBTxn)
if err != nil {
return fmt.Errorf("could not index epoch first height: %w", err)
}
setups = append(setups, setup)
commits = append(commits, commit)
status.PreviousEpoch.SetupID = setup.ID()
status.PreviousEpoch.CommitID = commit.ID()
} else if !errors.Is(err, protocol.ErrNoPreviousEpoch) {
return fmt.Errorf("could not retrieve previous epoch: %w", err)
}
// insert current epoch - both setup and commit events must exist
setup, err := protocol.ToEpochSetup(current)
if err != nil {
return fmt.Errorf("could not get current epoch setup event: %w", err)
}
commit, err := protocol.ToEpochCommit(current)
if err != nil {
return fmt.Errorf("could not get current epoch commit event: %w", err)
}
if err := protocol.IsValidEpochSetup(setup, verifyNetworkAddress); err != nil {
return fmt.Errorf("invalid setup: %w", err)
}
if err := protocol.IsValidEpochCommit(commit, setup); err != nil {
return fmt.Errorf("invalid commit: %w", err)
}
err = indexFirstHeight(current)(tx.DBTxn)
if err != nil {
return fmt.Errorf("could not index epoch first height: %w", err)
}
setups = append(setups, setup)
commits = append(commits, commit)
status.CurrentEpoch.SetupID = setup.ID()
status.CurrentEpoch.CommitID = commit.ID()
// insert next epoch, if it exists
_, err = next.Counter()
if err == nil {
// either only the setup event, or both the setup and commit events must exist
setup, err := protocol.ToEpochSetup(next)
if err != nil {
return fmt.Errorf("could not get next epoch setup event: %w", err)
}
if err := protocol.IsValidEpochSetup(setup, verifyNetworkAddress); err != nil {
return fmt.Errorf("invalid setup: %w", err)
}
setups = append(setups, setup)
status.NextEpoch.SetupID = setup.ID()
commit, err := protocol.ToEpochCommit(next)
if err != nil && !errors.Is(err, protocol.ErrNextEpochNotCommitted) {
return fmt.Errorf("could not get next epoch commit event: %w", err)
}
if err == nil {
if err := protocol.IsValidEpochCommit(commit, setup); err != nil {
return fmt.Errorf("invalid commit")
}
commits = append(commits, commit)
status.NextEpoch.CommitID = commit.ID()
}
} else if !errors.Is(err, protocol.ErrNextEpochNotSetup) {
return fmt.Errorf("could not get next epoch: %w", err)
}
// sanity check: ensure epoch status is valid
err = status.Check()
if err != nil {
return fmt.Errorf("bootstrapping resulting in invalid epoch status: %w", err)
}
// insert all epoch setup/commit service events
// dynamic protocol state relies on these events being stored
for _, setup := range setups {
err = epochSetups.StoreTx(setup)(tx)
if err != nil {
return fmt.Errorf("could not store epoch setup event: %w", err)
}
}
for _, commit := range commits {
err = epochCommits.StoreTx(commit)(tx)
if err != nil {
return fmt.Errorf("could not store epoch commit event: %w", err)
}
}
return nil
}
}
// bootstrapSporkInfo bootstraps the protocol state with information about the
// spork which is used to disambiguate Flow networks.
func bootstrapSporkInfo(root protocol.Snapshot) func(*badger.Txn) error {
return func(tx *badger.Txn) error {
params := root.Params()
sporkID := params.SporkID()
err := operation.InsertSporkID(sporkID)(tx)
if err != nil {
return fmt.Errorf("could not insert spork ID: %w", err)
}
sporkRootBlockHeight := params.SporkRootBlockHeight()
err = operation.InsertSporkRootBlockHeight(sporkRootBlockHeight)(tx)
if err != nil {
return fmt.Errorf("could not insert spork root block height: %w", err)
}
version := params.ProtocolVersion()
err = operation.InsertProtocolVersion(version)(tx)
if err != nil {
return fmt.Errorf("could not insert protocol version: %w", err)
}
threshold := params.EpochCommitSafetyThreshold()
err = operation.InsertEpochCommitSafetyThreshold(threshold)(tx)
if err != nil {
return fmt.Errorf("could not insert epoch commit safety threshold: %w", err)
}
return nil
}
}
// indexFirstHeight indexes the first height for the epoch, as part of bootstrapping.
// The input epoch must have been started (the first block of the epoch has been finalized).
// No errors are expected during normal operation.
func indexFirstHeight(epoch protocol.Epoch) func(*badger.Txn) error {
return func(tx *badger.Txn) error {
counter, err := epoch.Counter()
if err != nil {
return fmt.Errorf("could not get epoch counter: %w", err)
}
firstHeight, err := epoch.FirstHeight()
if err != nil {
return fmt.Errorf("could not get epoch first height: %w", err)
}
err = operation.InsertEpochFirstHeight(counter, firstHeight)(tx)
if err != nil {
return fmt.Errorf("could not index first height %d for epoch %d: %w", firstHeight, counter, err)
}
return nil
}
}
func OpenState(
metrics module.ComplianceMetrics,
db *badger.DB,
headers storage.Headers,
seals storage.Seals,
results storage.ExecutionResults,
blocks storage.Blocks,
qcs storage.QuorumCertificates,
setups storage.EpochSetups,
commits storage.EpochCommits,
protocolState storage.ProtocolState,
versionBeacons storage.VersionBeacons,
) (*State, error) {
isBootstrapped, err := IsBootstrapped(db)
if err != nil {
return nil, fmt.Errorf("failed to determine whether database contains bootstrapped state: %w", err)
}
if !isBootstrapped {
return nil, fmt.Errorf("expected database to contain bootstrapped state")
}
globalParams, err := ReadGlobalParams(db)
if err != nil {
return nil, fmt.Errorf("could not read global params: %w", err)
}
instanceParams, err := ReadInstanceParams(db, headers, seals)
if err != nil {
return nil, fmt.Errorf("could not read instance params: %w", err)
}
params := &Params{
GlobalParams: globalParams,
InstanceParams: instanceParams,
}
state, err := newState(
metrics,
db,
headers,
seals,
results,
blocks,
qcs,
setups,
commits,
protocolState,
versionBeacons,
params,
)
if err != nil {
return nil, fmt.Errorf("could not create state: %w", err)
}
// report last finalized and sealed block height
finalSnapshot := state.Final()
head, err := finalSnapshot.Head()
if err != nil {
return nil, fmt.Errorf("unexpected error to get finalized block: %w", err)
}
metrics.FinalizedHeight(head.Height)
sealed, err := state.Sealed().Head()
if err != nil {
return nil, fmt.Errorf("could not get latest sealed block: %w", err)
}
metrics.SealedHeight(sealed.Height)
epochFallbackTriggered, err := state.isEpochEmergencyFallbackTriggered()
if err != nil {
return nil, fmt.Errorf("could not check epoch emergency fallback flag: %w", err)
}
// update all epoch related metrics
err = updateEpochMetrics(metrics, finalSnapshot, epochFallbackTriggered)
if err != nil {
return nil, fmt.Errorf("failed to update epoch metrics: %w", err)
}
return state, nil
}
func (state *State) Params() protocol.Params {
return state.params
}
// Sealed returns a snapshot for the latest sealed block. A latest sealed block
// must always exist, so this function always returns a valid snapshot.
func (state *State) Sealed() protocol.Snapshot {
cached := state.cachedSealed.Load()
if cached == nil {
return invalid.NewSnapshotf("internal inconsistency: no cached sealed header")
}
return NewFinalizedSnapshot(state, cached.id, cached.header)
}
// Final returns a snapshot for the latest finalized block. A latest finalized
// block must always exist, so this function always returns a valid snapshot.
func (state *State) Final() protocol.Snapshot {
cached := state.cachedFinal.Load()
if cached == nil {
return invalid.NewSnapshotf("internal inconsistency: no cached final header")
}
return NewFinalizedSnapshot(state, cached.id, cached.header)
}
// AtHeight returns a snapshot for the finalized block at the given height.
// This function may return an invalid.Snapshot with:
// - state.ErrUnknownSnapshotReference:
// -> if no block with the given height has been finalized, even if it is incorporated
// -> if the given height is below the root height
// - exception for critical unexpected storage errors
func (state *State) AtHeight(height uint64) protocol.Snapshot {
// retrieve the block ID for the finalized height
var blockID flow.Identifier
err := state.db.View(operation.LookupBlockHeight(height, &blockID))
if err != nil {
if errors.Is(err, storage.ErrNotFound) {
return invalid.NewSnapshotf("unknown finalized height %d: %w", height, statepkg.ErrUnknownSnapshotReference)
}
// critical storage error
return invalid.NewSnapshotf("could not look up block by height: %w", err)
}
return newSnapshotWithIncorporatedReferenceBlock(state, blockID)
}
// AtBlockID returns a snapshot for the block with the given ID. The block may be
// finalized or un-finalized.
// This function may return an invalid.Snapshot with:
// - state.ErrUnknownSnapshotReference:
// -> if no block with the given ID exists in the state
// - exception for critical unexpected storage errors
func (state *State) AtBlockID(blockID flow.Identifier) protocol.Snapshot {
exists, err := state.headers.Exists(blockID)
if err != nil {
return invalid.NewSnapshotf("could not check existence of reference block: %w", err)
}
if !exists {
return invalid.NewSnapshotf("unknown block %x: %w", blockID, statepkg.ErrUnknownSnapshotReference)
}
return newSnapshotWithIncorporatedReferenceBlock(state, blockID)
}
// newState initializes a new state backed by the provided a badger database,
// mempools and service components.
// The parameter `expectedBootstrappedState` indicates whether the database
// is expected to contain an already bootstrapped state or not
func newState(
metrics module.ComplianceMetrics,
db *badger.DB,
headers storage.Headers,
seals storage.Seals,
results storage.ExecutionResults,
blocks storage.Blocks,
qcs storage.QuorumCertificates,
setups storage.EpochSetups,
commits storage.EpochCommits,
protocolStateSnapshots storage.ProtocolState,
versionBeacons storage.VersionBeacons,
params protocol.Params,
) (*State, error) {
state := &State{
metrics: metrics,
db: db,
headers: headers,
results: results,
seals: seals,
blocks: blocks,
qcs: qcs,
epoch: struct {
setups storage.EpochSetups
commits storage.EpochCommits
}{
setups: setups,
commits: commits,
},
params: params,
protocolStateSnapshotsDB: protocolStateSnapshots,
protocolState: protocol_state.NewMutableProtocolState(
protocolStateSnapshots,
params,
headers,
results,
setups,
commits,
),
versionBeacons: versionBeacons,
cachedFinal: new(atomic.Pointer[cachedHeader]),
cachedSealed: new(atomic.Pointer[cachedHeader]),
}
// populate the protocol state cache
err := state.populateCache()
if err != nil {
return nil, fmt.Errorf("failed to populate cache: %w", err)
}
return state, nil
}
// IsBootstrapped returns whether the database contains a bootstrapped state
func IsBootstrapped(db *badger.DB) (bool, error) {
var finalized uint64
err := db.View(operation.RetrieveFinalizedHeight(&finalized))
if errors.Is(err, storage.ErrNotFound) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("retrieving finalized height failed: %w", err)
}
return true, nil
}
// updateEpochMetrics update the `consensus_compliance_current_epoch_counter` and the
// `consensus_compliance_current_epoch_phase` metric
func updateEpochMetrics(metrics module.ComplianceMetrics, snap protocol.Snapshot, epochFallbackTriggered bool) error {
// update epoch counter
counter, err := snap.Epochs().Current().Counter()
if err != nil {
return fmt.Errorf("could not get current epoch counter: %w", err)
}
metrics.CurrentEpochCounter(counter)
// update epoch phase
phase, err := snap.Phase()
if err != nil {
return fmt.Errorf("could not get current epoch counter: %w", err)
}
metrics.CurrentEpochPhase(phase)
// update committed epoch final view
err = updateCommittedEpochFinalView(metrics, snap)
if err != nil {
return fmt.Errorf("could not update committed epoch final view")
}
currentEpochFinalView, err := snap.Epochs().Current().FinalView()
if err != nil {
return fmt.Errorf("could not update current epoch final view: %w", err)
}
metrics.CurrentEpochFinalView(currentEpochFinalView)
dkgPhase1FinalView, dkgPhase2FinalView, dkgPhase3FinalView, err := protocol.DKGPhaseViews(snap.Epochs().Current())
if err != nil {
return fmt.Errorf("could not get dkg phase final view: %w", err)
}
metrics.CurrentDKGPhase1FinalView(dkgPhase1FinalView)
metrics.CurrentDKGPhase2FinalView(dkgPhase2FinalView)
metrics.CurrentDKGPhase3FinalView(dkgPhase3FinalView)
// EECC - check whether the epoch emergency fallback flag has been set
// in the database. If so, skip updating any epoch-related metrics.
if epochFallbackTriggered {
metrics.EpochEmergencyFallbackTriggered()
}
return nil
}
// boostrapVersionBeacon bootstraps version beacon, by adding the latest beacon
// to an index, if present.
func boostrapVersionBeacon(
snapshot protocol.Snapshot,
) func(*badger.Txn) error {
return func(txn *badger.Txn) error {
versionBeacon, err := snapshot.VersionBeacon()
if err != nil {
return err
}
if versionBeacon == nil {
return nil
}
return operation.IndexVersionBeaconByHeight(versionBeacon)(txn)
}
}
// populateCache is used after opening or bootstrapping the state to populate the cache.
// The cache must be populated before the State receives any queries.
// No errors expected during normal operations.
func (state *State) populateCache() error {
// cache the initial value for finalized block
err := state.db.View(func(tx *badger.Txn) error {
// finalized header
var finalizedHeight uint64
err := operation.RetrieveFinalizedHeight(&finalizedHeight)(tx)
if err != nil {
return fmt.Errorf("could not lookup finalized height: %w", err)
}
var cachedFinalHeader cachedHeader
err = operation.LookupBlockHeight(finalizedHeight, &cachedFinalHeader.id)(tx)
if err != nil {
return fmt.Errorf("could not lookup finalized id (height=%d): %w", finalizedHeight, err)
}
cachedFinalHeader.header, err = state.headers.ByBlockID(cachedFinalHeader.id)
if err != nil {
return fmt.Errorf("could not get finalized block (id=%x): %w", cachedFinalHeader.id, err)
}
state.cachedFinal.Store(&cachedFinalHeader)
// sealed header
var sealedHeight uint64
err = operation.RetrieveSealedHeight(&sealedHeight)(tx)
if err != nil {
return fmt.Errorf("could not lookup sealed height: %w", err)
}
var cachedSealedHeader cachedHeader
err = operation.LookupBlockHeight(sealedHeight, &cachedSealedHeader.id)(tx)
if err != nil {
return fmt.Errorf("could not lookup sealed id (height=%d): %w", sealedHeight, err)
}
cachedSealedHeader.header, err = state.headers.ByBlockID(cachedSealedHeader.id)
if err != nil {
return fmt.Errorf("could not get sealed block (id=%x): %w", cachedSealedHeader.id, err)
}
state.cachedSealed.Store(&cachedSealedHeader)
return nil
})
if err != nil {
return fmt.Errorf("could not cache finalized header: %w", err)
}
state.finalizedRootHeight = state.Params().FinalizedRoot().Height
state.sealedRootHeight = state.Params().SealedRoot().Height
state.sporkRootBlockHeight = state.Params().SporkRootBlockHeight()
return nil
}
// updateCommittedEpochFinalView updates the `committed_epoch_final_view` metric
// based on the current epoch phase of the input snapshot. It should be called
// at startup and during transitions between EpochSetup and EpochCommitted phases.
//
// For example, suppose we have epochs N and N+1.
// If we are in epoch N's Staking or Setup Phase, then epoch N's final view should be the value of the metric.
// If we are in epoch N's Committed Phase, then epoch N+1's final view should be the value of the metric.
func updateCommittedEpochFinalView(metrics module.ComplianceMetrics, snap protocol.Snapshot) error {
phase, err := snap.Phase()
if err != nil {
return fmt.Errorf("could not get epoch phase: %w", err)
}
// update metric based of epoch phase
switch phase {
case flow.EpochPhaseStaking, flow.EpochPhaseSetup:
// if we are in Staking or Setup phase, then set the metric value to the current epoch's final view
finalView, err := snap.Epochs().Current().FinalView()
if err != nil {
return fmt.Errorf("could not get current epoch final view from snapshot: %w", err)
}
metrics.CommittedEpochFinalView(finalView)
case flow.EpochPhaseCommitted:
// if we are in Committed phase, then set the metric value to the next epoch's final view
finalView, err := snap.Epochs().Next().FinalView()
if err != nil {
return fmt.Errorf("could not get next epoch final view from snapshot: %w", err)
}
metrics.CommittedEpochFinalView(finalView)
default:
return fmt.Errorf("invalid phase: %s", phase)