-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathblock_view_validator.go
More file actions
2636 lines (2308 loc) · 101 KB
/
block_view_validator.go
File metadata and controls
2636 lines (2308 loc) · 101 KB
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 lib
import (
"bytes"
"crypto/sha256"
"fmt"
"github.com/google/uuid"
"io"
"math"
"net"
"sort"
"strconv"
"github.com/deso-protocol/core/consensus"
"github.com/deso-protocol/core/bls"
"github.com/deso-protocol/uint256"
"github.com/dgraph-io/badger/v3"
"github.com/golang/glog"
"github.com/pkg/errors"
)
// RegisterAsValidator: Registers a new validator. This transaction can be called multiple times
// if a validator needs to update any of their registration info such as their domains. Once
// a validator is registered, stake can be assigned to that validator, the validator is eligible
// to participate in consensus by voting, and may be selected as leader to propose new blocks.
//
// UnregisterAsValidator: Unregisters an existing validator. This unstakes all stake assigned to this
// validator and removes this validator from the set of eligible validators. A user would have to
// re-register by submitting a subsequent RegisterAsValidator transaction to be re-included.
//
// UnjailValidator: Unjails a jailed validator if sufficient time (epochs) have elapsed since the
// validator was first jailed. A validator is jailed if they fail to participate in consensus by
// either voting or proposing blocks for too long. A jailed validator is ineligible to receive
// any block rewards and ineligible to elected leader.
//
// TYPES: ValidatorEntry
//
const MaxDelegatedStakeCommissionBasisPoints = uint64(10000) // 100% commission
type ValidatorEntry struct {
// The ValidatorPKID is the primary key for a ValidatorEntry. It is the PKID
// for the transactor who registered the validator. A user's PKID can only
// be associated with one validator.
ValidatorPKID *PKID
// Domains is a slice of web domains where the validator can be reached.
// Note: if someone is updating their ValidatorEntry, they need to include
// all domains. The Domains field is not appended to. It is overwritten.
Domains [][]byte
// DisableDelegatedStake is a boolean that indicates whether the validator
// disallows delegated / 3rd party stake being assigned to themselves. If
// a validator sets DisableDelegatedStake to true, then they can still
// stake with themselves, but all other users will receive an error if they
// try to stake with this validator.
DisableDelegatedStake bool
// DelegatedStakeCommissionBasisPoints determines the percentage of
// staking rewards that the validator takes as commission from its stake delegators'
// rewards. For example, if a stake delegator has 5 DESO in staking rewards and the
// validator's commission rate is 10%, then the validator receives 0.5 DESO and the
// stake delegator receives 4.5 DESO.
DelegatedStakeCommissionBasisPoints uint64
// The VotingPublicKey is a BLS PublicKey that is used in consensus messages.
// A validator signs consensus messages with their VotingPrivateKey and then
// other validators can reliably prove the message came from this validator
// by verifying against their VotingPublicKey.
VotingPublicKey *bls.PublicKey
// The VotingAuthorization is the BLS signature of the SHA256(TransactorPublicKey)
// by the VotingPrivateKey. This proves that this validator is indeed the proper
// owner of the corresponding VotingPrivateKey. See comment on
// CreateValidatorVotingAuthorizationPayload for more details.
VotingAuthorization *bls.Signature
// TotalStakeAmountNanos is a cached value of this validator's total stake, calculated
// by summing all the corresponding StakeEntries assigned to this validator. We cache
// the value here to avoid the O(N) operation of recomputing when determining a
// validator's total stake. This way it is an O(1) operation instead.
TotalStakeAmountNanos *uint256.Int
// LastActiveAtEpochNumber is the last epoch in which this validator either 1) participated in
// consensus by voting or proposing blocks, or 2) unjailed themselves. If a validator is
// inactive for too long, then they are jailed.
LastActiveAtEpochNumber uint64
// JailedAtEpochNumber tracks when a validator was first jailed. This helps to verify
// that enough time (epochs) have passed before the validator is able to unjail themselves.
JailedAtEpochNumber uint64
ExtraData map[string][]byte
isDeleted bool
}
func (validatorEntry *ValidatorEntry) Status() ValidatorStatus {
// ValidatorEntry.Status() is a virtual/derived field that is not stored in
// the database, but instead constructed from other ValidatorEntry fields.
// No sense in storing duplicative data twice. This saves memory and ensures
// that e.g. the ValidatorEntry.JailedAtEpochNumber field and the
// ValidatorEntry.Status() return value will never get out of sync.
//
// Make sure that any fields referenced here are included in the ValidatorMapKey
// since the ValidatorEntry.Status() value is used as a field in a Badger index.
if validatorEntry.JailedAtEpochNumber > uint64(0) {
return ValidatorStatusJailed
}
return ValidatorStatusActive
}
func toConsensusValidators(validatorEntries []*ValidatorEntry) []consensus.Validator {
var consensusValidators []consensus.Validator
for _, validatorEntry := range validatorEntries {
consensusValidators = append(consensusValidators, validatorEntry)
}
return consensusValidators
}
type ValidatorStatus uint8
const (
ValidatorStatusInvalid ValidatorStatus = 0
ValidatorStatusActive ValidatorStatus = 1
ValidatorStatusJailed ValidatorStatus = 2
)
func (validatorStatus ValidatorStatus) ToString() string {
switch validatorStatus {
case ValidatorStatusActive:
return "Active"
case ValidatorStatusJailed:
return "Jailed"
default:
return "Unknown"
}
}
func (validatorEntry *ValidatorEntry) Copy() *ValidatorEntry {
// Copy domains.
var domainsCopy [][]byte
for _, domain := range validatorEntry.Domains {
domainsCopy = append(domainsCopy, append([]byte{}, domain...)) // Makes a copy.
}
// Return new ValidatorEntry.
return &ValidatorEntry{
ValidatorPKID: validatorEntry.ValidatorPKID.NewPKID(),
Domains: domainsCopy,
DisableDelegatedStake: validatorEntry.DisableDelegatedStake,
DelegatedStakeCommissionBasisPoints: validatorEntry.DelegatedStakeCommissionBasisPoints,
VotingPublicKey: validatorEntry.VotingPublicKey.Copy(),
VotingAuthorization: validatorEntry.VotingAuthorization.Copy(),
TotalStakeAmountNanos: validatorEntry.TotalStakeAmountNanos.Clone(),
LastActiveAtEpochNumber: validatorEntry.LastActiveAtEpochNumber,
JailedAtEpochNumber: validatorEntry.JailedAtEpochNumber,
ExtraData: copyExtraData(validatorEntry.ExtraData),
isDeleted: validatorEntry.isDeleted,
}
}
func (validatorEntry *ValidatorEntry) RawEncodeWithoutMetadata(blockHeight uint64, skipMetadata ...bool) []byte {
var data []byte
data = append(data, EncodeToBytes(blockHeight, validatorEntry.ValidatorPKID, skipMetadata...)...)
// Domains
data = append(data, UintToBuf(uint64(len(validatorEntry.Domains)))...)
for _, domain := range validatorEntry.Domains {
data = append(data, EncodeByteArray(domain)...)
}
data = append(data, BoolToByte(validatorEntry.DisableDelegatedStake))
data = append(data, UintToBuf(validatorEntry.DelegatedStakeCommissionBasisPoints)...)
data = append(data, EncodeBLSPublicKey(validatorEntry.VotingPublicKey)...)
data = append(data, EncodeBLSSignature(validatorEntry.VotingAuthorization)...)
data = append(data, VariableEncodeUint256(validatorEntry.TotalStakeAmountNanos)...)
data = append(data, UintToBuf(validatorEntry.LastActiveAtEpochNumber)...)
data = append(data, UintToBuf(validatorEntry.JailedAtEpochNumber)...)
data = append(data, EncodeExtraData(validatorEntry.ExtraData)...)
return data
}
func (validatorEntry *ValidatorEntry) RawDecodeWithoutMetadata(blockHeight uint64, rr *bytes.Reader) error {
var err error
// ValidatorPKID
validatorEntry.ValidatorPKID, err = DecodeDeSoEncoder(&PKID{}, rr)
if err != nil {
return errors.Wrapf(err, "ValidatorEntry.Decode: Problem reading ValidatorPKID: ")
}
// Domains
numDomains, err := ReadUvarint(rr)
if err != nil {
return errors.Wrapf(err, "ValidatorEntry.Decode: Problem reading Domains: ")
}
for ii := 0; ii < int(numDomains); ii++ {
domain, err := DecodeByteArray(rr)
if err != nil {
return errors.Wrapf(err, "ValidatorEntry.Decode: Problem reading Domains: ")
}
validatorEntry.Domains = append(validatorEntry.Domains, domain)
}
// DisableDelegatedStake
validatorEntry.DisableDelegatedStake, err = ReadBoolByte(rr)
if err != nil {
return errors.Wrapf(err, "ValidatorEntry.Decode: Problem reading DisableDelegatedStake: ")
}
// DelegatedStakeCommissionBasisPoints
validatorEntry.DelegatedStakeCommissionBasisPoints, err = ReadUvarint(rr)
if err != nil {
return errors.Wrapf(err, "ValidatorEntry.Decode: Problem reading DelegatedStakeCommissionBasisPoints: ")
}
// VotingPublicKey
validatorEntry.VotingPublicKey, err = DecodeBLSPublicKey(rr)
if err != nil {
return errors.Wrapf(err, "ValidatorEntry.Decode: Problem reading VotingPublicKey: ")
}
// VotingAuthorization
validatorEntry.VotingAuthorization, err = DecodeBLSSignature(rr)
if err != nil {
return errors.Wrapf(err, "ValidatorEntry.Decode: Problem reading VotingAuthorization: ")
}
// TotalStakeAmountNanos
validatorEntry.TotalStakeAmountNanos, err = VariableDecodeUint256(rr)
if err != nil {
return errors.Wrapf(err, "ValidatorEntry.Decode: Problem reading TotalStakeAmountNanos: ")
}
// LastActiveAtEpochNumber
validatorEntry.LastActiveAtEpochNumber, err = ReadUvarint(rr)
if err != nil {
return errors.Wrapf(err, "ValidatorEntry.Decode: Problem reading LastActiveAtEpochNumber: ")
}
// JailedAtEpochNumber
validatorEntry.JailedAtEpochNumber, err = ReadUvarint(rr)
if err != nil {
return errors.Wrapf(err, "ValidatorEntry.Decode: Problem reading JailedAtEpochNumber: ")
}
// ExtraData
validatorEntry.ExtraData, err = DecodeExtraData(rr)
if err != nil {
return errors.Wrapf(err, "ValidatorEntry.Decode: Problem reading ExtraData: ")
}
return nil
}
func (validatorEntry *ValidatorEntry) GetVersionByte(blockHeight uint64) byte {
return 0
}
func (validatorEntry *ValidatorEntry) GetEncoderType() EncoderType {
return EncoderTypeValidatorEntry
}
func (validatorEntry *ValidatorEntry) ToBLSPublicKeyPKIDPairEntry() *BLSPublicKeyPKIDPairEntry {
return &BLSPublicKeyPKIDPairEntry{
BLSPublicKey: validatorEntry.VotingPublicKey.Copy(),
PKID: validatorEntry.ValidatorPKID.NewPKID(),
isDeleted: validatorEntry.isDeleted,
}
}
func (validatorEntry *ValidatorEntry) IsDeleted() bool {
return validatorEntry.isDeleted
}
//
// TYPES: BLSPublicKeyPKIDPairEntry
//
type BLSPublicKeyPKIDPairEntry struct {
BLSPublicKey *bls.PublicKey
PKID *PKID
isDeleted bool
}
func (blsPublicKeyPKIDPairEntry *BLSPublicKeyPKIDPairEntry) Copy() *BLSPublicKeyPKIDPairEntry {
return &BLSPublicKeyPKIDPairEntry{
BLSPublicKey: blsPublicKeyPKIDPairEntry.BLSPublicKey.Copy(),
PKID: blsPublicKeyPKIDPairEntry.PKID.NewPKID(),
isDeleted: blsPublicKeyPKIDPairEntry.isDeleted,
}
}
func (blsPublicKeyPKIDPairEntry *BLSPublicKeyPKIDPairEntry) ToMapKey() bls.SerializedPublicKey {
return blsPublicKeyPKIDPairEntry.BLSPublicKey.Serialize()
}
func (blsPublicKeyPKIDPairEntry *BLSPublicKeyPKIDPairEntry) ToSnapshotMapKey(snapshotAtEpoch uint64) SnapshotValidatorBLSPublicKeyMapKey {
return SnapshotValidatorBLSPublicKeyMapKey{
SnapshotAtEpochNumber: snapshotAtEpoch,
ValidatorBLSPublicKey: blsPublicKeyPKIDPairEntry.BLSPublicKey.Serialize(),
}
}
func (blsPublicKeyPKIDPairEntry *BLSPublicKeyPKIDPairEntry) RawEncodeWithoutMetadata(blockHeight uint64, skipMetadata ...bool) []byte {
var data []byte
data = append(data, EncodeBLSPublicKey(blsPublicKeyPKIDPairEntry.BLSPublicKey)...)
data = append(data, EncodeToBytes(blockHeight, blsPublicKeyPKIDPairEntry.PKID, skipMetadata...)...)
return data
}
func (blsPublicKeyPKIDPairEntry *BLSPublicKeyPKIDPairEntry) RawDecodeWithoutMetadata(blockHeight uint64, rr *bytes.Reader) error {
var err error
blsPublicKeyPKIDPairEntry.BLSPublicKey, err = DecodeBLSPublicKey(rr)
if err != nil {
return errors.Wrapf(err, "BLSPublicKeyPKIDPairEntry.Decode: Problem reading BLSPublicKey: ")
}
blsPublicKeyPKIDPairEntry.PKID, err = DecodeDeSoEncoder(&PKID{}, rr)
if err != nil {
return errors.Wrapf(err, "BLSPublicKeyPKIDPairEntry.Decode: Problem reading PKID: ")
}
return nil
}
func (blsPublicKeyPKIDPairEntry *BLSPublicKeyPKIDPairEntry) GetVersionByte(blockHeight uint64) byte {
return 0
}
func (blsPublicKeyPKIDPairEntry *BLSPublicKeyPKIDPairEntry) GetEncoderType() EncoderType {
return EncoderTypeBLSPublicKeyPKIDPairEntry
}
//
// TYPES: RegisterAsValidatorMetadata
//
type RegisterAsValidatorMetadata struct {
Domains [][]byte
DisableDelegatedStake bool
DelegatedStakeCommissionBasisPoints uint64
VotingPublicKey *bls.PublicKey
VotingAuthorization *bls.Signature
}
func (txnData *RegisterAsValidatorMetadata) GetTxnType() TxnType {
return TxnTypeRegisterAsValidator
}
func (txnData *RegisterAsValidatorMetadata) ToBytes(preSignature bool) ([]byte, error) {
var data []byte
// Domains
data = append(data, UintToBuf(uint64(len(txnData.Domains)))...)
for _, domain := range txnData.Domains {
data = append(data, EncodeByteArray(domain)...)
}
data = append(data, BoolToByte(txnData.DisableDelegatedStake))
data = append(data, UintToBuf(txnData.DelegatedStakeCommissionBasisPoints)...)
data = append(data, EncodeBLSPublicKey(txnData.VotingPublicKey)...)
data = append(data, EncodeBLSSignature(txnData.VotingAuthorization)...)
return data, nil
}
func (txnData *RegisterAsValidatorMetadata) FromBytes(data []byte) error {
rr := bytes.NewReader(data)
// Domains
numDomains, err := ReadUvarint(rr)
if err != nil {
return errors.Wrapf(err, "RegisterAsValidatorMetadata.FromBytes: Problem reading Domains: ")
}
for ii := 0; ii < int(numDomains); ii++ {
domain, err := DecodeByteArray(rr)
if err != nil {
return errors.Wrapf(err, "RegisterAsValidatorMetadata.FromBytes: Problem reading Domains: ")
}
txnData.Domains = append(txnData.Domains, domain)
}
// DisableDelegatedStake
txnData.DisableDelegatedStake, err = ReadBoolByte(rr)
if err != nil {
return errors.Wrapf(err, "RegisterAsValidatorMetadata.FromBytes: Problem reading DisableDelegatedStake: ")
}
// DelegatedStakeCommissionBasisPoints
txnData.DelegatedStakeCommissionBasisPoints, err = ReadUvarint(rr)
if err != nil {
return errors.Wrapf(err, "RegisterAsValidatorMetadata.FromBytes: Problem reading DelegatedStakeCommissionBasisPoints: ")
}
// VotingPublicKey
txnData.VotingPublicKey, err = DecodeBLSPublicKey(rr)
if err != nil {
return errors.Wrapf(err, "RegisterAsValidatorMetadata.FromBytes: Problem reading VotingPublicKey: ")
}
// VotingAuthorization
txnData.VotingAuthorization, err = DecodeBLSSignature(rr)
if err != nil {
return errors.Wrapf(err, "RegisterAsValidatorMetadata.FromBytes: Problem reading VotingAuthorization: ")
}
return nil
}
func (txnData *RegisterAsValidatorMetadata) New() DeSoTxnMetadata {
return &RegisterAsValidatorMetadata{}
}
//
// TYPES: UnregisterAsValidatorMetadata
//
type UnregisterAsValidatorMetadata struct{}
func (txnData *UnregisterAsValidatorMetadata) GetTxnType() TxnType {
return TxnTypeUnregisterAsValidator
}
func (txnData *UnregisterAsValidatorMetadata) ToBytes(preSignature bool) ([]byte, error) {
return []byte{}, nil
}
func (txnData *UnregisterAsValidatorMetadata) FromBytes(data []byte) error {
return nil
}
func (txnData *UnregisterAsValidatorMetadata) New() DeSoTxnMetadata {
return &UnregisterAsValidatorMetadata{}
}
//
// TYPES: UnjailValidatorMetadata
//
type UnjailValidatorMetadata struct{}
func (txnData *UnjailValidatorMetadata) GetTxnType() TxnType {
return TxnTypeUnjailValidator
}
func (txnData *UnjailValidatorMetadata) ToBytes(preSignature bool) ([]byte, error) {
return []byte{}, nil
}
func (txnData *UnjailValidatorMetadata) FromBytes(data []byte) error {
return nil
}
func (txnData *UnjailValidatorMetadata) New() DeSoTxnMetadata {
return &UnjailValidatorMetadata{}
}
//
// TYPES: RegisterAsValidatorTxindexMetadata
//
type RegisterAsValidatorTxindexMetadata struct {
ValidatorPublicKeyBase58Check string
Domains []string
DisableDelegatedStake bool
DelegatedStakeCommissionBasisPoints uint64
VotingPublicKey string
VotingAuthorization string
}
func (txindexMetadata *RegisterAsValidatorTxindexMetadata) RawEncodeWithoutMetadata(blockHeight uint64, skipMetadata ...bool) []byte {
var data []byte
data = append(data, EncodeByteArray([]byte(txindexMetadata.ValidatorPublicKeyBase58Check))...)
// Domains
data = append(data, UintToBuf(uint64(len(txindexMetadata.Domains)))...)
for _, domain := range txindexMetadata.Domains {
data = append(data, EncodeByteArray([]byte(domain))...)
}
data = append(data, BoolToByte(txindexMetadata.DisableDelegatedStake))
data = append(data, UintToBuf(txindexMetadata.DelegatedStakeCommissionBasisPoints)...)
data = append(data, EncodeByteArray([]byte(txindexMetadata.VotingPublicKey))...)
data = append(data, EncodeByteArray([]byte(txindexMetadata.VotingAuthorization))...)
return data
}
func (txindexMetadata *RegisterAsValidatorTxindexMetadata) RawDecodeWithoutMetadata(blockHeight uint64, rr *bytes.Reader) error {
var err error
// ValidatorPublicKeyBase58Check
validatorPublicKeyBase58CheckBytes, err := DecodeByteArray(rr)
if err != nil {
return errors.Wrapf(err, "RegisterAsValidatorTxindexMetadata.Decode: Problem reading ValidatorPublicKeyBase58Check: ")
}
txindexMetadata.ValidatorPublicKeyBase58Check = string(validatorPublicKeyBase58CheckBytes)
// Domains
numDomains, err := ReadUvarint(rr)
if err != nil {
return errors.Wrapf(err, "RegisterAsValidatorTxindexMetadata.Decode: Problem reading Domains: ")
}
for ii := 0; ii < int(numDomains); ii++ {
domain, err := DecodeByteArray(rr)
if err != nil {
return errors.Wrapf(err, "RegisterAsValidatorTxindexMetadata.Decode: Problem reading Domains: ")
}
txindexMetadata.Domains = append(txindexMetadata.Domains, string(domain))
}
// DisableDelegatedStake
txindexMetadata.DisableDelegatedStake, err = ReadBoolByte(rr)
if err != nil {
return errors.Wrapf(err, "RegisterAsValidatorTxindexMetadata.Decode: Problem reading DisableDelegatedStake: ")
}
// DelegatedStakeCommissionBasisPoints
txindexMetadata.DelegatedStakeCommissionBasisPoints, err = ReadUvarint(rr)
if err != nil {
return errors.Wrapf(err, "RegisterAsValidatorTxindexMetadata.Decode: Problem reading DelegatedStakeCommissionBasisPoints: ")
}
// VotingPublicKey
votingPublicKeyBytes, err := DecodeByteArray(rr)
if err != nil {
return errors.Wrapf(err, "RegisterAsValidatorTxindexMetadata.Decode: Problem reading VotingPublicKey: ")
}
txindexMetadata.VotingPublicKey = string(votingPublicKeyBytes)
// VotingAuthorization
votingAuthorizationBytes, err := DecodeByteArray(rr)
if err != nil {
return errors.Wrapf(err, "RegisterAsValidatorTxindexMetadata.Decode: Problem reading VotingAuthorization: ")
}
txindexMetadata.VotingAuthorization = string(votingAuthorizationBytes)
return nil
}
func (txindexMetadata *RegisterAsValidatorTxindexMetadata) GetVersionByte(blockHeight uint64) byte {
return 0
}
func (txindexMetadata *RegisterAsValidatorTxindexMetadata) GetEncoderType() EncoderType {
return EncoderTypeRegisterAsValidatorTxindexMetadata
}
//
// TYPES: UnstakedStakerTxindexMetadata
//
type UnstakedStakerTxindexMetadata struct {
StakerPublicKeyBase58Check string
UnstakeAmountNanos *uint256.Int
}
func (txindexMetadata *UnstakedStakerTxindexMetadata) RawEncodeWithoutMetadata(blockHeight uint64, skipMetadata ...bool) []byte {
var data []byte
data = append(data, EncodeByteArray([]byte(txindexMetadata.StakerPublicKeyBase58Check))...)
data = append(data, VariableEncodeUint256(txindexMetadata.UnstakeAmountNanos)...)
return data
}
func (txindexMetadata *UnstakedStakerTxindexMetadata) RawDecodeWithoutMetadata(blockHeight uint64, rr *bytes.Reader) error {
var err error
// StakerPublicKeyBase58Check
stakerPublicKeyBase58CheckBytes, err := DecodeByteArray(rr)
if err != nil {
return errors.Wrapf(err, "UnstakedStakerTxindexMetadata.Decode: Problem reading StakerPublicKeyBase58Check: ")
}
txindexMetadata.StakerPublicKeyBase58Check = string(stakerPublicKeyBase58CheckBytes)
// UnstakeAmountNanos
txindexMetadata.UnstakeAmountNanos, err = VariableDecodeUint256(rr)
if err != nil {
return errors.Wrapf(err, "UnstakedStakerTxindexMetadata.Decode: Problem reading UnstakeAmountNanos: ")
}
return nil
}
//
// TYPES: UnregisterAsValidatorTxindexMetadata
//
type UnregisterAsValidatorTxindexMetadata struct {
ValidatorPublicKeyBase58Check string
UnstakedStakers []*UnstakedStakerTxindexMetadata
}
func (txindexMetadata *UnregisterAsValidatorTxindexMetadata) RawEncodeWithoutMetadata(blockHeight uint64, skipMetadata ...bool) []byte {
var data []byte
data = append(data, EncodeByteArray([]byte(txindexMetadata.ValidatorPublicKeyBase58Check))...)
// UnstakedStakers
data = append(data, UintToBuf(uint64(len(txindexMetadata.UnstakedStakers)))...)
for _, unstakedStaker := range txindexMetadata.UnstakedStakers {
data = append(data, unstakedStaker.RawEncodeWithoutMetadata(blockHeight, skipMetadata...)...)
}
return data
}
func (txindexMetadata *UnregisterAsValidatorTxindexMetadata) RawDecodeWithoutMetadata(blockHeight uint64, rr *bytes.Reader) error {
var err error
// ValidatorPublicKeyBase58Check
validatorPublicKeyBase58CheckBytes, err := DecodeByteArray(rr)
if err != nil {
return errors.Wrapf(err, "UnregisterAsValidatorTxindexMetadata.Decode: Problem reading ValidatorPublicKeyBase58Check: ")
}
txindexMetadata.ValidatorPublicKeyBase58Check = string(validatorPublicKeyBase58CheckBytes)
// UnstakedStakers
numUnstakedStakers, err := ReadUvarint(rr)
if err != nil {
return errors.Wrapf(err, "UnregisterAsValidatorTxindexMetadata.Decode: Problem reading UnstakedStakers: ")
}
for ii := 0; ii < int(numUnstakedStakers); ii++ {
unstakedStaker := &UnstakedStakerTxindexMetadata{}
err = unstakedStaker.RawDecodeWithoutMetadata(blockHeight, rr)
if err != nil {
return errors.Wrapf(err, "UnregisterAsValidatorTxindexMetadata.Decode: Problem reading UnstakedStakers: ")
}
txindexMetadata.UnstakedStakers = append(txindexMetadata.UnstakedStakers, unstakedStaker)
}
return nil
}
func (txindexMetadata *UnregisterAsValidatorTxindexMetadata) GetVersionByte(blockHeight uint64) byte {
return 0
}
func (txindexMetadata *UnregisterAsValidatorTxindexMetadata) GetEncoderType() EncoderType {
return EncoderTypeUnregisterAsValidatorTxindexMetadata
}
//
// TYPES: UnjailValidatorTxindexMetadata
//
type UnjailValidatorTxindexMetadata struct {
}
func (txindexMetadata *UnjailValidatorTxindexMetadata) RawEncodeWithoutMetadata(blockHeight uint64, skipMetadata ...bool) []byte {
return []byte{}
}
func (txindexMetadata *UnjailValidatorTxindexMetadata) RawDecodeWithoutMetadata(blockHeight uint64, rr *bytes.Reader) error {
return nil
}
func (txindexMetadata *UnjailValidatorTxindexMetadata) GetVersionByte(blockHeight uint64) byte {
return 0
}
func (txindexMetadata *UnjailValidatorTxindexMetadata) GetEncoderType() EncoderType {
return EncoderTypeUnjailValidatorTxindexMetadata
}
//
// DB UTILS
//
//
// ValidatorEntry DB UTILS
//
func DBKeyForValidatorByPKID(validatorEntry *ValidatorEntry) []byte {
key := append([]byte{}, Prefixes.PrefixValidatorByPKID...)
key = append(key, validatorEntry.ValidatorPKID.ToBytes()...)
return key
}
func DBKeyForValidatorByStatusAndStakeAmount(validatorEntry *ValidatorEntry) []byte {
key := append([]byte{}, Prefixes.PrefixValidatorByStatusAndStakeAmount...)
key = append(key, EncodeUint8(uint8(validatorEntry.Status()))...)
key = append(key, FixedWidthEncodeUint256(validatorEntry.TotalStakeAmountNanos)...)
key = append(key, validatorEntry.ValidatorPKID.ToBytes()...)
return key
}
func GetValidatorPKIDFromDBKeyForValidatorByStatusAndStakeAmount(key []byte) (*PKID, error) {
validatorPKIDBytes := key[len(key)-PublicKeyLenCompressed:]
if len(validatorPKIDBytes) != PublicKeyLenCompressed {
return nil, fmt.Errorf(
"GetValidatorPKIDFromDBKeyForValidatorByStatusAndStakeAmount: Problem reading ValidatorPKID: "+
"Length of ValidatorPKIDBytes is %d but expected %d",
len(validatorPKIDBytes), PublicKeyLenCompressed,
)
}
return NewPKID(validatorPKIDBytes), nil
}
func DBGetValidatorByPKID(handle *badger.DB, snap *Snapshot, pkid *PKID) (*ValidatorEntry, error) {
var ret *ValidatorEntry
err := handle.View(func(txn *badger.Txn) error {
var innerErr error
ret, innerErr = DBGetValidatorByPKIDWithTxn(txn, snap, pkid)
return innerErr
})
return ret, err
}
func DBGetValidatorByPKIDWithTxn(txn *badger.Txn, snap *Snapshot, pkid *PKID) (*ValidatorEntry, error) {
// Retrieve ValidatorEntry from db.
key := DBKeyForValidatorByPKID(&ValidatorEntry{ValidatorPKID: pkid})
validatorBytes, err := DBGetWithTxn(txn, snap, key)
if err != nil {
// We don't want to error if the key isn't found. Instead, return nil.
if err == badger.ErrKeyNotFound {
return nil, nil
}
return nil, errors.Wrapf(err, "DBGetValidatorByPKID: problem retrieving ValidatorEntry")
}
// Decode ValidatorEntry from bytes.
validatorEntry := &ValidatorEntry{}
rr := bytes.NewReader(validatorBytes)
if exist, err := DecodeFromBytes(validatorEntry, rr); !exist || err != nil {
return nil, errors.Wrapf(err, "DBGetValidatorByPKID: problem decoding ValidatorEntry")
}
return validatorEntry, nil
}
func DBGetTopActiveValidatorsByStakeAmount(
handle *badger.DB,
snap *Snapshot,
limit uint64,
validatorEntriesToSkip []*ValidatorEntry,
) ([]*ValidatorEntry, error) {
var validatorEntries []*ValidatorEntry
// Convert validatorEntriesToSkip to the ValidatorPKIDs we need to skip.
validatorPKIDsToSkip := NewSet([]PKID{})
for _, validatorEntryToSkip := range validatorEntriesToSkip {
validatorPKIDsToSkip.Add(*validatorEntryToSkip.ValidatorPKID)
}
// Define a function to filter out validators PKIDs we want to skip while seeking through the DB.
// We can't simply pass in the exact keys from the UtxoView that we need to skip through because
// it's possible that the validator entries (and their total stake amounts) have changed in the
// UtxoView, and no longer match the stake amounts in the DB used to index them.
canSkipValidatorInBadgerSeek := func(badgerKey []byte) bool {
validatorPKID, err := GetValidatorPKIDFromDBKeyForValidatorByStatusAndStakeAmount(badgerKey)
if err != nil {
// We return false here to be safe. Once the seek has completed, we attempt to parse the
// keys a second time below. Any failures there will result in an error that we can propagate
// to the caller.
return false
}
return validatorPKIDsToSkip.Includes(*validatorPKID)
}
// Retrieve top N active ValidatorEntry keys by stake.
key := append([]byte{}, Prefixes.PrefixValidatorByStatusAndStakeAmount...)
key = append(key, EncodeUint8(uint8(ValidatorStatusActive))...)
keysFound, err := EnumerateKeysOnlyForPrefixWithLimitOffsetOrderAndSkipFunc(
handle, key, int(limit), nil, true, canSkipValidatorInBadgerSeek,
)
if err != nil {
return nil, errors.Wrapf(err, "DBGetTopActiveValidatorsByStakeAmount: problem retrieving top validators: ")
}
// For each key found, parse the ValidatorPKID from the key,
// then retrieve the ValidatorEntry by the ValidatorPKID.
for _, keyFound := range keysFound {
validatorPKID, err := GetValidatorPKIDFromDBKeyForValidatorByStatusAndStakeAmount(keyFound)
if err != nil {
return nil, errors.Wrapf(err, "DBGetTopActiveValidatorsByStakeAmount: problem reading ValidatorPKID: ")
}
// Retrieve ValidatorEntry by PKID.
validatorEntry, err := DBGetValidatorByPKID(handle, snap, validatorPKID)
if err != nil {
return nil, errors.Wrapf(err, "DBGetTopActiveValidatorsByStakeAmount: problem retrieving validator by PKID: ")
}
validatorEntries = append(validatorEntries, validatorEntry)
}
return validatorEntries, nil
}
// In order to optimize the flush, we want to only write entries to the db that have changed.
// On top of that, we add a further optimization to only update the
// PrefixValidatorByStatusAndStakeAmount index if the stake amount or status has changed in the
// validator. Not doing this results in a lot of writes to badger
// every epoch that eventually slow block processing to a crawl. This is essentially a bug in
// badger when you repeatedly write to the same key, and we're papering over it here in response
// to encountering the issue. In an ideal world, badger would work as intended and this extra
// optimization wouldn't be necessary.
func DBUpdateValidatorWithTxn(
txn *badger.Txn,
snap *Snapshot,
validatorEntry *ValidatorEntry,
blockHeight uint64,
eventManager *EventManager,
) error {
if validatorEntry == nil {
// This should never happen but is a sanity check.
glog.Errorf("DBPutValidatorWithTxn: called with nil ValidatorEntry")
return nil
}
// Look up the existing ValidatorEntry from the db
dbEntry, err := DBGetValidatorByPKIDWithTxn(txn, snap, validatorEntry.ValidatorPKID)
if err != nil {
return errors.Wrapf(err, "DBUpdateValidatorWithTxn: ")
}
dbEntryBytes := EncodeToBytes(blockHeight, dbEntry)
entryToWriteBytes := EncodeToBytes(blockHeight, validatorEntry)
// If the entry we're about to write is the exact same as what's already in the db then
// don't write it.
//
// In 99%+ of cases, the entries will be identical so we save a lot from
// this optimization, and it significantly speeds up block processing ot have it. When they
// differ, typically it's only because of LastActiveAtEpochNumber. For this reason, we have
// a secondary optimization to only update the PrefixValidatorByStatusAndStakeAmount index
// when absolutely necessary.
if bytes.Equal(dbEntryBytes, entryToWriteBytes) {
// We explicitly emit an upsert operation here for state syncer
// for the case where the entry is the same.
if eventManager != nil {
eventManager.stateSyncerOperation(&StateSyncerOperationEvent{
StateChangeEntry: &StateChangeEntry{
OperationType: DbOperationTypeUpsert,
KeyBytes: DBKeyForValidatorByPKID(validatorEntry),
EncoderBytes: entryToWriteBytes,
AncestralRecordBytes: dbEntryBytes,
IsReverted: false,
},
FlushId: uuid.Nil,
IsMempoolTxn: eventManager.isMempoolManager,
})
}
return nil
}
// Set ValidatorEntry in PrefixValidatorByPKID. This should gracefully overwrite an existing entry
// if one exists.
key := DBKeyForValidatorByPKID(validatorEntry)
if err := DBSetWithTxn(txn, snap, key, EncodeToBytes(blockHeight, validatorEntry), eventManager); err != nil {
return errors.Wrapf(
err, "DBPutValidatorWithTxn: problem storing ValidatorEntry in index PrefixValidatorByPKID",
)
}
// If the entry we're about to write has the exact same stake amount and the exact same status,
// then there is no need to update PrefixValidatorByStatusAndStakeAmount. This saves us a lot in terms
// of block processing time due to the aforementioned badger bug.
if dbEntry == nil || validatorEntry.TotalStakeAmountNanos.Cmp(dbEntry.TotalStakeAmountNanos) != 0 ||
validatorEntry.Status() != dbEntry.Status() {
// Here we need to delete the existing value in the index first
if dbEntry != nil {
key = DBKeyForValidatorByStatusAndStakeAmount(dbEntry)
// Note we set isDeleted=false as a hint to the state syncer that we're about to
// update this value immediately after.
if err := DBDeleteWithTxn(txn, snap, key, eventManager, false); err != nil {
return errors.Wrapf(
err, "DBUpdateValidatorWithTxn: problem deleting ValidatorEntry from index "+
"PrefixValidatorByStatusAndStakeAmount",
)
}
}
// Set ValidatorEntry key in PrefixValidatorByStatusAndStakeAmount. The value should be nil.
// We parse the ValidatorPKID from the key for this index.
key = DBKeyForValidatorByStatusAndStakeAmount(validatorEntry)
if err := DBSetWithTxn(txn, snap, key, nil, eventManager); err != nil {
return errors.Wrapf(
err, "DBUpdateValidatorWithTxn: problem storing ValidatorEntry in index PrefixValidatorByStatusAndStakeAmount",
)
}
}
return nil
}
func DBDeleteValidatorWithTxn(txn *badger.Txn, snap *Snapshot, validatorPKID *PKID, eventManager *EventManager, entryIsDeleted bool) error {
if validatorPKID == nil {
// This should never happen but is a sanity check.
glog.Errorf("DBDeleteValidatorWithTxn: called with nil ValidatorPKID")
return nil
}
// Look up the existing ValidatorEntry in the db using the PKID. We need to use this
// validator's values to delete the corresponding indexes.
validatorEntry, err := DBGetValidatorByPKIDWithTxn(txn, snap, validatorPKID)
if err != nil {
return errors.Wrapf(err, "DBDeleteValidatorWithTxn: problem retrieving "+
"ValidatorEntry for PKID %v: ", validatorPKID)
}
// If there is no ValidatorEntry in the DB for this PKID, then there is nothing to
// delete.
if validatorEntry == nil {
return nil
}
// Delete ValidatorEntry from PrefixValidatorByPKID.
key := DBKeyForValidatorByPKID(validatorEntry)
if err := DBDeleteWithTxn(txn, snap, key, eventManager, entryIsDeleted); err != nil {
return errors.Wrapf(
err, "DBDeleteValidatorWithTxn: problem deleting ValidatorEntry from index PrefixValidatorByPKID",
)
}
// Delete ValidatorEntry.PKID from PrefixValidatorByStatusAndStakeAmount.
key = DBKeyForValidatorByStatusAndStakeAmount(validatorEntry)
if err := DBDeleteWithTxn(txn, snap, key, eventManager, entryIsDeleted); err != nil {
return errors.Wrapf(
err, "DBDeleteValidatorWithTxn: problem deleting ValidatorEntry from index PrefixValidatorByStatusAndStakeAmount",
)
}
return nil
}
//
// BLSPublicKeyPKIDPairEntry DB Utils
//
func DBKeyForValidatorBLSPublicKeyToPKIDPairEntry(blsPublicKey *bls.PublicKey) []byte {
key := append([]byte{}, Prefixes.PrefixValidatorBLSPublicKeyPKIDPairEntry...)
key = append(key, blsPublicKey.ToBytes()...)
return key
}
func DBPutValidatorBLSPublicKeyPKIDPairEntryWithTxn(
txn *badger.Txn,
snap *Snapshot,
validatorBLSPublicKeyPKIDPairEntry *BLSPublicKeyPKIDPairEntry,
blockHeight uint64,
eventManager *EventManager,
) error {
if validatorBLSPublicKeyPKIDPairEntry == nil {
// This should never happen but is a sanity check.
glog.Errorf("DBPutValidatorBLSPublicKeyPKIDPairEntryWithTxn: called with nil BLSPublicKeyPKIDPairEntry")
return nil
}
key := DBKeyForValidatorBLSPublicKeyToPKIDPairEntry(validatorBLSPublicKeyPKIDPairEntry.BLSPublicKey)
if err := DBSetWithTxn(txn, snap, key, EncodeToBytes(blockHeight, validatorBLSPublicKeyPKIDPairEntry), eventManager); err != nil {
return errors.Wrapf(
err, "DBPutValidatorBLSPublicKeyPKIDPairEntryWithTxn: problem storing BLSPublicKeyPKIDPairEntry in index PrefixValidatorBLSPublicKeyPKIDPairEntry",
)
}
return nil
}
func DBDeleteBLSPublicKeyPKIDPairEntryWithTxn(txn *badger.Txn, snap *Snapshot, blsPublicKey *bls.PublicKey, eventManager *EventManager, entryIsDeleted bool) error {
if blsPublicKey == nil {
// This should never happen but is a sanity check.
glog.Errorf("DBDeleteBLSPublicKeyPKIDPairEntryWithTxn: called with nil blsPublicKey")
return nil
}
key := DBKeyForValidatorBLSPublicKeyToPKIDPairEntry(blsPublicKey)
if err := DBDeleteWithTxn(txn, snap, key, eventManager, entryIsDeleted); err != nil {
return errors.Wrapf(
err, "DBDeleteBLSPublicKeyPKIDPairEntryWithTxn: problem deleting BLSPublicKeyPKIDPairEntry from index PrefixValidatorBLSPublicKeyPKIDPairEntry",
)
}
return nil
}
func DBGetValidatorBLSPublicKeyPKIDPairEntry(handle *badger.DB, snap *Snapshot, blsPublicKey *bls.PublicKey) (*BLSPublicKeyPKIDPairEntry, error) {
var ret *BLSPublicKeyPKIDPairEntry
err := handle.View(func(txn *badger.Txn) error {
var innerErr error
ret, innerErr = DBGetValidatorBLSPublicKeyPKIDPairEntryWithTxn(txn, snap, blsPublicKey)
return innerErr
})
return ret, err
}
func DBGetValidatorBLSPublicKeyPKIDPairEntryWithTxn(txn *badger.Txn, snap *Snapshot, blsPublicKey *bls.PublicKey) (*BLSPublicKeyPKIDPairEntry, error) {
// Retrieve ValidatorEntry from db.
key := DBKeyForValidatorBLSPublicKeyToPKIDPairEntry(blsPublicKey)
validatorBytes, err := DBGetWithTxn(txn, snap, key)
if err != nil {
// We don't want to error if the key isn't found. Instead, return nil.
if errors.Is(err, badger.ErrKeyNotFound) {
return nil, nil
}
return nil, errors.Wrapf(err, "DBGetValidatorBLSPublicKeyPKIDPairEntryWithTxn: problem retrieving BLSPublicKeyPKIDPairEntry")
}
// Decode ValidatorEntry from bytes.
blsPublicKeyPKIDPairEntry := &BLSPublicKeyPKIDPairEntry{}
rr := bytes.NewReader(validatorBytes)
if exist, err := DecodeFromBytes(blsPublicKeyPKIDPairEntry, rr); !exist || err != nil {
return nil, errors.Wrapf(err, "DBGetValidatorBLSPublicKeyPKIDPairEntryWithTxn: problem decoding BLSPublicKeyPKIDPairEntry")
}
return blsPublicKeyPKIDPairEntry, nil
}
//
// BLOCKCHAIN UTILS
//
func (bc *Blockchain) CreateRegisterAsValidatorTxn(
transactorPublicKey []byte,