-
Notifications
You must be signed in to change notification settings - Fork 178
/
service_event.go
1281 lines (1123 loc) · 33 KB
/
service_event.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 convert
import (
"encoding/hex"
"fmt"
"github.com/coreos/go-semver/semver"
"github.com/onflow/cadence"
"github.com/onflow/cadence/encoding/ccf"
"github.com/onflow/crypto"
"github.com/onflow/flow-go/fvm/systemcontracts"
"github.com/onflow/flow-go/model/flow"
)
// ServiceEvent converts a service event encoded as the generic flow.Event
// type to a flow.ServiceEvent type for use within protocol software and protocol
// state. This acts as the conversion from the Cadence type to the flow-go type.
func ServiceEvent(chainID flow.ChainID, event flow.Event) (*flow.ServiceEvent, error) {
events := systemcontracts.ServiceEventsForChain(chainID)
// depending on type of service event construct Go type
switch event.Type {
case events.EpochSetup.EventType():
return convertServiceEventEpochSetup(event)
case events.EpochCommit.EventType():
return convertServiceEventEpochCommit(event)
case events.VersionBeacon.EventType():
return convertServiceEventVersionBeacon(event)
default:
return nil, fmt.Errorf("invalid event type: %s", event.Type)
}
}
// convertServiceEventEpochSetup converts a service event encoded as the generic
// flow.Event type to a ServiceEvent type for an EpochSetup event
// CONVENTION: in the returned `EpochSetup` event,
// - Node identities listed in `EpochSetup.Participants` are in CANONICAL ORDER
// - for each cluster assignment (i.e. element in `EpochSetup.Assignments`), the nodeIDs are listed in CANONICAL ORDER
func convertServiceEventEpochSetup(event flow.Event) (*flow.ServiceEvent, error) {
// decode bytes using ccf
payload, err := ccf.Decode(nil, event.Payload)
if err != nil {
return nil, fmt.Errorf("could not unmarshal event payload: %w", err)
}
// NOTE: variable names prefixed with cdc represent cadence types
cdcEvent, ok := payload.(cadence.Event)
if !ok {
return nil, invalidCadenceTypeError("payload", payload, cadence.Event{})
}
const expectedFieldCount = 11
if len(cdcEvent.Fields) < expectedFieldCount {
return nil, fmt.Errorf(
"insufficient fields in EpochSetup event (%d < %d)",
len(cdcEvent.Fields),
expectedFieldCount,
)
}
if cdcEvent.Type() == nil {
return nil, fmt.Errorf("EpochSetup event doesn't have type")
}
// parse EpochSetup event
var counter cadence.UInt64
var firstView cadence.UInt64
var finalView cadence.UInt64
var randomSrcHex cadence.String
var dkgPhase1FinalView cadence.UInt64
var dkgPhase2FinalView cadence.UInt64
var dkgPhase3FinalView cadence.UInt64
var cdcClusters cadence.Array
var cdcParticipants cadence.Array
var targetDuration cadence.UInt64 // Epoch duration [seconds]
var targetEndTimeUnix cadence.UInt64 // Unix time [seconds]
var foundFieldCount int
evt := cdcEvent.Type().(*cadence.EventType)
for i, f := range evt.Fields {
switch f.Identifier {
case "counter":
foundFieldCount++
counter, ok = cdcEvent.Fields[i].(cadence.UInt64)
if !ok {
return nil, invalidCadenceTypeError(
"counter",
cdcEvent.Fields[i],
cadence.UInt64(0),
)
}
case "nodeInfo":
foundFieldCount++
cdcParticipants, ok = cdcEvent.Fields[i].(cadence.Array)
if !ok {
return nil, invalidCadenceTypeError(
"participants",
cdcEvent.Fields[i],
cadence.Array{},
)
}
case "firstView":
foundFieldCount++
firstView, ok = cdcEvent.Fields[i].(cadence.UInt64)
if !ok {
return nil, invalidCadenceTypeError(
"firstView",
cdcEvent.Fields[i],
cadence.UInt64(0),
)
}
case "finalView":
foundFieldCount++
finalView, ok = cdcEvent.Fields[i].(cadence.UInt64)
if !ok {
return nil, invalidCadenceTypeError(
"finalView",
cdcEvent.Fields[i],
cadence.UInt64(0),
)
}
case "collectorClusters":
foundFieldCount++
cdcClusters, ok = cdcEvent.Fields[i].(cadence.Array)
if !ok {
return nil, invalidCadenceTypeError(
"clusters",
cdcEvent.Fields[i],
cadence.Array{},
)
}
case "randomSource":
foundFieldCount++
randomSrcHex, ok = cdcEvent.Fields[i].(cadence.String)
if !ok {
return nil, invalidCadenceTypeError(
"randomSource",
cdcEvent.Fields[i],
cadence.String(""),
)
}
case "targetDuration":
foundFieldCount++
targetDuration, ok = cdcEvent.Fields[i].(cadence.UInt64)
if !ok {
return nil, invalidCadenceTypeError(
"targetDuration",
cdcEvent.Fields[i],
cadence.UInt64(0),
)
}
case "targetEndTime":
foundFieldCount++
targetEndTimeUnix, ok = cdcEvent.Fields[i].(cadence.UInt64)
if !ok {
return nil, invalidCadenceTypeError(
"targetEndTime",
cdcEvent.Fields[i],
cadence.UInt64(0),
)
}
case "DKGPhase1FinalView":
foundFieldCount++
dkgPhase1FinalView, ok = cdcEvent.Fields[i].(cadence.UInt64)
if !ok {
return nil, invalidCadenceTypeError(
"dkgPhase1FinalView",
cdcEvent.Fields[i],
cadence.UInt64(0),
)
}
case "DKGPhase2FinalView":
foundFieldCount++
dkgPhase2FinalView, ok = cdcEvent.Fields[i].(cadence.UInt64)
if !ok {
return nil, invalidCadenceTypeError(
"dkgPhase2FinalView",
cdcEvent.Fields[i],
cadence.UInt64(0),
)
}
case "DKGPhase3FinalView":
foundFieldCount++
dkgPhase3FinalView, ok = cdcEvent.Fields[i].(cadence.UInt64)
if !ok {
return nil, invalidCadenceTypeError(
"dkgPhase3FinalView",
cdcEvent.Fields[i],
cadence.UInt64(0),
)
}
}
}
if foundFieldCount != expectedFieldCount {
return nil, fmt.Errorf(
"EpochSetup event required fields not found (%d != %d)",
foundFieldCount,
expectedFieldCount,
)
}
setup := &flow.EpochSetup{
Counter: uint64(counter),
FirstView: uint64(firstView),
FinalView: uint64(finalView),
DKGPhase1FinalView: uint64(dkgPhase1FinalView),
DKGPhase2FinalView: uint64(dkgPhase2FinalView),
DKGPhase3FinalView: uint64(dkgPhase3FinalView),
TargetDuration: uint64(targetDuration),
TargetEndTime: uint64(targetEndTimeUnix),
}
// random source from the event must be a hex string
// containing exactly 128 bits (equivalent to 16 bytes or 32 hex characters)
setup.RandomSource, err = hex.DecodeString(string(randomSrcHex))
if err != nil {
return nil, fmt.Errorf(
"could not decode random source hex (%v): %w",
randomSrcHex,
err,
)
}
if len(setup.RandomSource) != flow.EpochSetupRandomSourceLength {
return nil, fmt.Errorf(
"random source in epoch setup event must be of (%d) bytes, got (%d)",
flow.EpochSetupRandomSourceLength,
len(setup.RandomSource),
)
}
// parse cluster assignments; returned assignments are in canonical order
setup.Assignments, err = convertClusterAssignments(cdcClusters.Values)
if err != nil {
return nil, fmt.Errorf("could not convert cluster assignments: %w", err)
}
// parse epoch participants; returned node identities are in canonical order
setup.Participants, err = convertParticipants(cdcParticipants.Values)
if err != nil {
return nil, fmt.Errorf("could not convert participants: %w", err)
}
// construct the service event
serviceEvent := &flow.ServiceEvent{
Type: flow.ServiceEventSetup,
Event: setup,
}
return serviceEvent, nil
}
// convertServiceEventEpochCommit converts a service event encoded as the generic
// flow.Event type to a ServiceEvent type for an EpochCommit event
func convertServiceEventEpochCommit(event flow.Event) (*flow.ServiceEvent, error) {
// decode bytes using ccf
payload, err := ccf.Decode(nil, event.Payload)
if err != nil {
return nil, fmt.Errorf("could not unmarshal event payload: %w", err)
}
cdcEvent, ok := payload.(cadence.Event)
if !ok {
return nil, invalidCadenceTypeError("payload", payload, cadence.Event{})
}
const expectedFieldCount = 3
if len(cdcEvent.Fields) < expectedFieldCount {
return nil, fmt.Errorf(
"insufficient fields in EpochCommit event (%d < %d)",
len(cdcEvent.Fields),
expectedFieldCount,
)
}
if cdcEvent.Type() == nil {
return nil, fmt.Errorf("EpochCommit event doesn't have type")
}
// Extract EpochCommit event fields
var counter cadence.UInt64
var cdcClusterQCVotes cadence.Array
var cdcDKGKeys cadence.Array
var foundFieldCount int
evt := cdcEvent.Type().(*cadence.EventType)
for i, f := range evt.Fields {
switch f.Identifier {
case "counter":
foundFieldCount++
counter, ok = cdcEvent.Fields[i].(cadence.UInt64)
if !ok {
return nil, invalidCadenceTypeError(
"counter",
cdcEvent.Fields[i],
cadence.UInt64(0),
)
}
case "clusterQCs":
foundFieldCount++
cdcClusterQCVotes, ok = cdcEvent.Fields[i].(cadence.Array)
if !ok {
return nil, invalidCadenceTypeError(
"clusterQCs",
cdcEvent.Fields[i],
cadence.Array{},
)
}
case "dkgPubKeys":
foundFieldCount++
cdcDKGKeys, ok = cdcEvent.Fields[i].(cadence.Array)
if !ok {
return nil, invalidCadenceTypeError(
"dkgPubKeys",
cdcEvent.Fields[i],
cadence.Array{},
)
}
}
}
if foundFieldCount != expectedFieldCount {
return nil, fmt.Errorf(
"EpochCommit event required fields not found (%d != %d)",
foundFieldCount,
expectedFieldCount,
)
}
commit := &flow.EpochCommit{
Counter: uint64(counter),
}
// parse cluster qc votes
commit.ClusterQCs, err = convertClusterQCVotes(cdcClusterQCVotes.Values)
if err != nil {
return nil, fmt.Errorf("could not convert cluster qc votes: %w", err)
}
// parse DKG group key and participants
// Note: this is read in the same order as `DKGClient.SubmitResult` ie. with the group public key first followed by individual keys
// https://github.com/onflow/flow-go/blob/feature/dkg/module/dkg/client.go#L182-L183
dkgGroupKey, dkgParticipantKeys, err := convertDKGKeys(cdcDKGKeys.Values)
if err != nil {
return nil, fmt.Errorf("could not convert DKG keys: %w", err)
}
commit.DKGGroupKey = dkgGroupKey
commit.DKGParticipantKeys = dkgParticipantKeys
// create the service event
serviceEvent := &flow.ServiceEvent{
Type: flow.ServiceEventCommit,
Event: commit,
}
return serviceEvent, nil
}
// convertClusterAssignments converts the Cadence representation of cluster
// assignments included in the EpochSetup into the protocol AssignmentList
// representation.
// CONVENTION: for each cluster assignment (i.e. element in `AssignmentList`), the nodeIDs are listed in CANONICAL ORDER
func convertClusterAssignments(cdcClusters []cadence.Value) (flow.AssignmentList, error) {
// ensure we don't have duplicate cluster indices
indices := make(map[uint]struct{})
// parse cluster assignments to Go types
clusterAssignments := make([]flow.IdentifierList, len(cdcClusters))
for _, value := range cdcClusters {
cdcCluster, ok := value.(cadence.Struct)
if !ok {
return nil, invalidCadenceTypeError("cluster", cdcCluster, cadence.Struct{})
}
const expectedFieldCount = 2
if len(cdcCluster.Fields) < expectedFieldCount {
return nil, fmt.Errorf(
"insufficient fields (%d < %d)",
len(cdcCluster.Fields),
expectedFieldCount,
)
}
if cdcCluster.Type() == nil {
return nil, fmt.Errorf("cluster struct doesn't have type")
}
// Extract cluster fields
var clusterIndex cadence.UInt16
var weightsByNodeID cadence.Dictionary
var foundFieldCount int
cdcClusterType := cdcCluster.Type().(*cadence.StructType)
for i, f := range cdcClusterType.Fields {
switch f.Identifier {
case "index":
foundFieldCount++
clusterIndex, ok = cdcCluster.Fields[i].(cadence.UInt16)
if !ok {
return nil, invalidCadenceTypeError(
"index",
cdcCluster.Fields[i],
cadence.UInt16(0),
)
}
case "nodeWeights":
foundFieldCount++
weightsByNodeID, ok = cdcCluster.Fields[i].(cadence.Dictionary)
if !ok {
return nil, invalidCadenceTypeError(
"nodeWeights",
cdcCluster.Fields[i],
cadence.Dictionary{},
)
}
}
}
if foundFieldCount != expectedFieldCount {
return nil, fmt.Errorf(
"cluster struct required fields not found (%d != %d)",
foundFieldCount,
expectedFieldCount,
)
}
// ensure cluster index is valid
if int(clusterIndex) >= len(cdcClusters) {
return nil, fmt.Errorf(
"invalid cdcCluster index (%d) outside range [0,%d]",
clusterIndex,
len(cdcClusters)-1,
)
}
_, dup := indices[uint(clusterIndex)]
if dup {
return nil, fmt.Errorf("duplicate cdcCluster index (%d)", clusterIndex)
}
// read weights to retrieve node IDs of cdcCluster members
clusterMembers := make(flow.IdentifierList, 0, len(weightsByNodeID.Pairs))
for _, pair := range weightsByNodeID.Pairs {
nodeIDString, ok := pair.Key.(cadence.String)
if !ok {
return nil, invalidCadenceTypeError(
"clusterWeights.nodeID",
pair.Key,
cadence.String(""),
)
}
nodeID, err := flow.HexStringToIdentifier(string(nodeIDString))
if err != nil {
return nil, fmt.Errorf(
"could not convert hex string to identifer: %w",
err,
)
}
clusterMembers = append(clusterMembers, nodeID)
}
// IMPORTANT: for each cluster, node IDs must be in *canonical order*
clusterAssignments[clusterIndex] = clusterMembers.Sort(flow.IdentifierCanonical)
}
return clusterAssignments, nil
}
// convertParticipants converts the network participants specified in the
// EpochSetup event into an IdentityList.
// CONVENTION: returned IdentityList is in CANONICAL ORDER
func convertParticipants(cdcParticipants []cadence.Value) (flow.IdentitySkeletonList, error) {
participants := make(flow.IdentitySkeletonList, 0, len(cdcParticipants))
var err error
for _, value := range cdcParticipants {
// checking compliance with expected format
cdcNodeInfoStruct, ok := value.(cadence.Struct)
if !ok {
return nil, invalidCadenceTypeError(
"cdcNodeInfoFields",
value,
cadence.Struct{},
)
}
const expectedFieldCount = 14
if len(cdcNodeInfoStruct.Fields) < expectedFieldCount {
return nil, fmt.Errorf(
"insufficient fields (%d < %d)",
len(cdcNodeInfoStruct.Fields),
expectedFieldCount,
)
}
if cdcNodeInfoStruct.Type() == nil {
return nil, fmt.Errorf("nodeInfo struct doesn't have type")
}
cdcNodeInfoStructType := cdcNodeInfoStruct.Type().(*cadence.StructType)
const requiredFieldCount = 6
var foundFieldCount int
var nodeIDHex cadence.String
var role cadence.UInt8
var address cadence.String
var networkKeyHex cadence.String
var stakingKeyHex cadence.String
var initialWeight cadence.UInt64
for i, f := range cdcNodeInfoStructType.Fields {
switch f.Identifier {
case "id":
foundFieldCount++
nodeIDHex, ok = cdcNodeInfoStruct.Fields[i].(cadence.String)
if !ok {
return nil, invalidCadenceTypeError(
"nodeInfo.id",
cdcNodeInfoStruct.Fields[i],
cadence.String(""),
)
}
case "role":
foundFieldCount++
role, ok = cdcNodeInfoStruct.Fields[i].(cadence.UInt8)
if !ok {
return nil, invalidCadenceTypeError(
"nodeInfo.role",
cdcNodeInfoStruct.Fields[i],
cadence.UInt8(0),
)
}
case "networkingAddress":
foundFieldCount++
address, ok = cdcNodeInfoStruct.Fields[i].(cadence.String)
if !ok {
return nil, invalidCadenceTypeError(
"nodeInfo.networkingAddress",
cdcNodeInfoStruct.Fields[i],
cadence.String(""),
)
}
case "networkingKey":
foundFieldCount++
networkKeyHex, ok = cdcNodeInfoStruct.Fields[i].(cadence.String)
if !ok {
return nil, invalidCadenceTypeError(
"nodeInfo.networkingKey",
cdcNodeInfoStruct.Fields[i],
cadence.String(""),
)
}
case "stakingKey":
foundFieldCount++
stakingKeyHex, ok = cdcNodeInfoStruct.Fields[i].(cadence.String)
if !ok {
return nil, invalidCadenceTypeError(
"nodeInfo.stakingKey",
cdcNodeInfoStruct.Fields[i],
cadence.String(""),
)
}
case "initialWeight":
foundFieldCount++
initialWeight, ok = cdcNodeInfoStruct.Fields[i].(cadence.UInt64)
if !ok {
return nil, invalidCadenceTypeError(
"nodeInfo.initialWeight",
cdcNodeInfoStruct.Fields[i],
cadence.UInt64(0),
)
}
}
}
if foundFieldCount != requiredFieldCount {
return nil, fmt.Errorf(
"NodeInfo struct required fields not found (%d != %d)",
foundFieldCount,
requiredFieldCount,
)
}
if !flow.Role(role).Valid() {
return nil, fmt.Errorf("invalid role %d", role)
}
identity := &flow.IdentitySkeleton{
InitialWeight: uint64(initialWeight),
Address: string(address),
Role: flow.Role(role),
}
// convert nodeID string into identifier
identity.NodeID, err = flow.HexStringToIdentifier(string(nodeIDHex))
if err != nil {
return nil, fmt.Errorf("could not convert hex string to identifer: %w", err)
}
// parse to PublicKey the networking key hex string
networkKeyBytes, err := hex.DecodeString(string(networkKeyHex))
if err != nil {
return nil, fmt.Errorf(
"could not decode network public key into bytes: %w",
err,
)
}
identity.NetworkPubKey, err = crypto.DecodePublicKey(
crypto.ECDSAP256,
networkKeyBytes,
)
if err != nil {
return nil, fmt.Errorf("could not decode network public key: %w", err)
}
// parse to PublicKey the staking key hex string
stakingKeyBytes, err := hex.DecodeString(string(stakingKeyHex))
if err != nil {
return nil, fmt.Errorf(
"could not decode staking public key into bytes: %w",
err,
)
}
identity.StakingPubKey, err = crypto.DecodePublicKey(
crypto.BLSBLS12381,
stakingKeyBytes,
)
if err != nil {
return nil, fmt.Errorf("could not decode staking public key: %w", err)
}
participants = append(participants, identity)
}
// IMPORTANT: returned identities must be in *canonical order*
participants = participants.Sort(flow.Canonical[flow.IdentitySkeleton])
return participants, nil
}
// convertClusterQCVotes converts raw cluster QC votes from the EpochCommit event
// to a representation suitable for inclusion in the protocol state. Votes are
// aggregated as part of this conversion.
func convertClusterQCVotes(cdcClusterQCs []cadence.Value) (
[]flow.ClusterQCVoteData,
error,
) {
// avoid duplicate indices
indices := make(map[uint]struct{})
qcVoteDatas := make([]flow.ClusterQCVoteData, len(cdcClusterQCs))
// CAUTION: Votes are not validated prior to aggregation. This means a single
// invalid vote submission will result in a fully invalid QC for that cluster.
// Votes must be validated by the ClusterQC smart contract.
for _, cdcClusterQC := range cdcClusterQCs {
cdcClusterQCStruct, ok := cdcClusterQC.(cadence.Struct)
if !ok {
return nil, invalidCadenceTypeError(
"clusterQC",
cdcClusterQC,
cadence.Struct{},
)
}
const expectedFieldCount = 4
if len(cdcClusterQCStruct.Fields) < expectedFieldCount {
return nil, fmt.Errorf(
"insufficient fields (%d < %d)",
len(cdcClusterQCStruct.Fields),
expectedFieldCount,
)
}
if cdcClusterQCStruct.Type() == nil {
return nil, fmt.Errorf("clusterQC struct doesn't have type")
}
cdcClusterQCStructType := cdcClusterQCStruct.Type().(*cadence.StructType)
const requiredFieldCount = 3
var foundFieldCount int
var index cadence.UInt16
var cdcVoterIDs cadence.Array
var cdcRawVotes cadence.Array
for i, f := range cdcClusterQCStructType.Fields {
switch f.Identifier {
case "index":
foundFieldCount++
index, ok = cdcClusterQCStruct.Fields[i].(cadence.UInt16)
if !ok {
return nil, invalidCadenceTypeError(
"ClusterQC.index",
cdcClusterQCStruct.Fields[i],
cadence.UInt16(0),
)
}
case "voteSignatures":
foundFieldCount++
cdcRawVotes, ok = cdcClusterQCStruct.Fields[i].(cadence.Array)
if !ok {
return nil, invalidCadenceTypeError(
"clusterQC.voteSignatures",
cdcClusterQCStruct.Fields[i],
cadence.Array{},
)
}
case "voterIDs":
foundFieldCount++
cdcVoterIDs, ok = cdcClusterQCStruct.Fields[i].(cadence.Array)
if !ok {
return nil, invalidCadenceTypeError(
"clusterQC.voterIDs",
cdcClusterQCStruct.Fields[i],
cadence.Array{},
)
}
}
}
if foundFieldCount != requiredFieldCount {
return nil, fmt.Errorf(
"clusterQC struct required fields not found (%d != %d)",
foundFieldCount,
requiredFieldCount,
)
}
if int(index) >= len(cdcClusterQCs) {
return nil, fmt.Errorf(
"invalid index (%d) not in range [0,%d]",
index,
len(cdcClusterQCs),
)
}
_, dup := indices[uint(index)]
if dup {
return nil, fmt.Errorf("duplicate cluster QC index (%d)", index)
}
voterIDs := make([]flow.Identifier, 0, len(cdcVoterIDs.Values))
for _, cdcVoterID := range cdcVoterIDs.Values {
voterIDHex, ok := cdcVoterID.(cadence.String)
if !ok {
return nil, invalidCadenceTypeError(
"clusterQC[i].voterID",
cdcVoterID,
cadence.String(""),
)
}
voterID, err := flow.HexStringToIdentifier(string(voterIDHex))
if err != nil {
return nil, fmt.Errorf("could not convert voter ID from hex: %w", err)
}
voterIDs = append(voterIDs, voterID)
}
// gather all the vote signatures
signatures := make([]crypto.Signature, 0, len(cdcRawVotes.Values))
for _, cdcRawVote := range cdcRawVotes.Values {
rawVoteHex, ok := cdcRawVote.(cadence.String)
if !ok {
return nil, invalidCadenceTypeError(
"clusterQC[i].vote",
cdcRawVote,
cadence.String(""),
)
}
rawVoteBytes, err := hex.DecodeString(string(rawVoteHex))
if err != nil {
return nil, fmt.Errorf("could not convert raw vote from hex: %w", err)
}
signatures = append(signatures, rawVoteBytes)
}
// Aggregate BLS signatures
aggregatedSignature, err := crypto.AggregateBLSSignatures(signatures)
if err != nil {
// expected errors of the function are:
// - empty list of signatures
// - an input signature does not deserialize to a valid point
// Both are not expected at this stage because list is guaranteed not to be
// empty and individual signatures have been validated.
return nil, fmt.Errorf("cluster qc vote aggregation failed: %w", err)
}
// check that aggregated signature is not identity, because an identity signature
// is invalid if verified under an identity public key. This can happen in two cases:
// - If the quorum has at least one honest signer, and given all staking key proofs of possession
// are valid, it's extremely unlikely for the aggregated public key (and the corresponding
// aggregated signature) to be identity.
// - If all quorum is malicious and intentionally forge an identity aggregate. As of the previous point,
// this is only possible if there is no honest collector involved in constructing the cluster QC.
// Hence, the cluster would need to contain a supermajority of malicious collectors.
// As we are assuming that the fraction of malicious collectors overall does not exceed 1/3 (measured
// by stake), the probability for randomly assigning 2/3 or more byzantine collectors to a single cluster
// vanishes (provided a sufficiently high collector count in total).
//
// Note that at this level, all individual signatures are guaranteed to be valid
// w.r.t their corresponding staking public key. It is therefore enough to check
// the aggregated signature to conclude whether the aggregated public key is identity.
// This check is therefore a sanity check to catch a potential issue early.
if crypto.IsBLSSignatureIdentity(aggregatedSignature) {
return nil, fmt.Errorf("cluster qc vote aggregation failed because resulting BLS signature is identity")
}
// set the fields on the QC vote data object
qcVoteDatas[int(index)] = flow.ClusterQCVoteData{
SigData: aggregatedSignature,
VoterIDs: voterIDs,
}
}
return qcVoteDatas, nil
}
// convertDKGKeys converts hex-encoded DKG public keys as received by the DKG
// smart contract into crypto.PublicKey representations suitable for inclusion
// in the protocol state.
func convertDKGKeys(cdcDKGKeys []cadence.Value) (
groupKey crypto.PublicKey,
participantKeys []crypto.PublicKey,
err error,
) {
hexDKGKeys := make([]string, 0, len(cdcDKGKeys))
for _, value := range cdcDKGKeys {
keyHex, ok := value.(cadence.String)
if !ok {
return nil, nil, invalidCadenceTypeError("dkgKey", value, cadence.String(""))
}
hexDKGKeys = append(hexDKGKeys, string(keyHex))
}
// pop first element - group public key hex string
groupPubKeyHex := hexDKGKeys[0]
hexDKGKeys = hexDKGKeys[1:]
// decode group public key
groupKeyBytes, err := hex.DecodeString(groupPubKeyHex)
if err != nil {
return nil, nil, fmt.Errorf(
"could not decode group public key into bytes: %w",
err,
)
}
groupKey, err = crypto.DecodePublicKey(crypto.BLSBLS12381, groupKeyBytes)
if err != nil {
return nil, nil, fmt.Errorf("could not decode group public key: %w", err)
}
// decode individual public keys
dkgParticipantKeys := make([]crypto.PublicKey, 0, len(hexDKGKeys))
for _, pubKeyString := range hexDKGKeys {
pubKeyBytes, err := hex.DecodeString(pubKeyString)
if err != nil {
return nil, nil, fmt.Errorf(
"could not decode individual public key into bytes: %w",
err,
)
}
pubKey, err := crypto.DecodePublicKey(crypto.BLSBLS12381, pubKeyBytes)
if err != nil {
return nil, nil, fmt.Errorf("could not decode dkg public key: %w", err)
}
dkgParticipantKeys = append(dkgParticipantKeys, pubKey)
}
return groupKey, dkgParticipantKeys, nil
}
func invalidCadenceTypeError(
fieldName string,
actualType, expectedType cadence.Value,
) error {
return fmt.Errorf(
"invalid Cadence type for field %s (got=%s, expected=%s)",
fieldName,
actualType.Type().ID(),
expectedType.Type().ID(),
)
}
func convertServiceEventVersionBeacon(event flow.Event) (*flow.ServiceEvent, error) {
payload, err := ccf.Decode(nil, event.Payload)
if err != nil {
return nil, fmt.Errorf("could not unmarshal event payload: %w", err)
}
versionBeacon, err := DecodeCadenceValue(
"VersionBeacon payload", payload, func(cdcEvent cadence.Event) (
flow.VersionBeacon,
error,
) {
const expectedFieldCount = 2
if len(cdcEvent.Fields) != expectedFieldCount {
return flow.VersionBeacon{}, fmt.Errorf(
"unexpected number of fields in VersionBeacon event (%d != %d)",
len(cdcEvent.Fields),
expectedFieldCount,
)
}
if cdcEvent.Type() == nil {
return flow.VersionBeacon{}, fmt.Errorf("VersionBeacon event doesn't have type")
}
var versionBoundariesValue, sequenceValue cadence.Value
var foundFieldCount int
evt := cdcEvent.Type().(*cadence.EventType)
for i, f := range evt.Fields {
switch f.Identifier {
case "versionBoundaries":
foundFieldCount++
versionBoundariesValue = cdcEvent.Fields[i]
case "sequence":
foundFieldCount++
sequenceValue = cdcEvent.Fields[i]
}
}
if foundFieldCount != expectedFieldCount {
return flow.VersionBeacon{}, fmt.Errorf(
"VersionBeacon event required fields not found (%d != %d)",
foundFieldCount,
expectedFieldCount,
)
}
versionBoundaries, err := DecodeCadenceValue(
".versionBoundaries", versionBoundariesValue, convertVersionBoundaries,
)
if err != nil {
return flow.VersionBeacon{}, err
}
sequence, err := DecodeCadenceValue(
".sequence", sequenceValue, func(cadenceVal cadence.UInt64) (
uint64,
error,
) {
return uint64(cadenceVal), nil
},
)
if err != nil {
return flow.VersionBeacon{}, err
}
return flow.VersionBeacon{
VersionBoundaries: versionBoundaries,
Sequence: sequence,
}, err
},
)
if err != nil {
return nil, err
}
// a converted version beacon event should also be valid
if err := versionBeacon.Validate(); err != nil {
return nil, fmt.Errorf("invalid VersionBeacon event: %w", err)
}
// create the service event
serviceEvent := &flow.ServiceEvent{
Type: flow.ServiceEventVersionBeacon,
Event: &versionBeacon,
}