-
Notifications
You must be signed in to change notification settings - Fork 107
/
state.go
1374 lines (1198 loc) · 43.4 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 state
import (
"bytes"
"context"
"fmt"
"math"
"sort"
beacon "github.com/oasisprotocol/oasis-core/go/beacon/api"
"github.com/oasisprotocol/oasis-core/go/common/cbor"
"github.com/oasisprotocol/oasis-core/go/common/crypto/signature"
"github.com/oasisprotocol/oasis-core/go/common/errors"
"github.com/oasisprotocol/oasis-core/go/common/keyformat"
"github.com/oasisprotocol/oasis-core/go/common/logging"
"github.com/oasisprotocol/oasis-core/go/common/quantity"
abciAPI "github.com/oasisprotocol/oasis-core/go/consensus/tendermint/api"
staking "github.com/oasisprotocol/oasis-core/go/staking/api"
"github.com/oasisprotocol/oasis-core/go/storage/mkvs"
)
var (
// AppName is the ABCI application name.
AppName = "100_staking"
// accountKeyFmt is the key format used for accounts (account addresses).
//
// Value is a CBOR-serialized account address.
accountKeyFmt = keyformat.New(0x50, &staking.Address{})
// totalSupplyKeyFmt is the key format used for the total supply.
//
// Value is a CBOR-serialized quantity.
totalSupplyKeyFmt = keyformat.New(0x51)
// commonPoolKeyFmt is the key format used for the common pool balance.
//
// Value is a CBOR-serialized quantity.
commonPoolKeyFmt = keyformat.New(0x52)
// delegationKeyFmt is the key format used for delegations (escrow address,
// delegator address).
//
// Value is CBOR-serialized delegation.
delegationKeyFmt = keyformat.New(0x53, &staking.Address{}, &staking.Address{})
// debondingDelegationKeyFmt is the key format used for debonding delegations
// (delegator address, escrow address, epoch).
//
// Value is CBOR-serialized debonding delegation.
debondingDelegationKeyFmt = keyformat.New(0x54, &staking.Address{}, &staking.Address{}, uint64(0))
// debondingQueueKeyFmt is the debonding queue key format
// (epoch, delegator address, escrow address).
//
// Value is empty.
debondingQueueKeyFmt = keyformat.New(0x55, uint64(0), &staking.Address{}, &staking.Address{})
// parametersKeyFmt is the key format used for consensus parameters.
//
// Value is CBOR-serialized staking.ConsensusParameters.
parametersKeyFmt = keyformat.New(0x56)
// lastBlockFeesKeyFmt is the accumulated fee balance for the previous block.
//
// Value is CBOR-serialized quantity.
lastBlockFeesKeyFmt = keyformat.New(0x57)
// epochSigningKeyFmt is the key format for epoch signing information.
//
// Value is CBOR-serialized EpochSigning.
epochSigningKeyFmt = keyformat.New(0x58)
// governanceDepositsKeyFmt is the key format used for the governance deposits balance.
//
// Value is a CBOR-serialized quantity.
governanceDepositsKeyFmt = keyformat.New(0x59)
logger = logging.GetLogger("tendermint/staking")
)
// ImmutableState is the immutable staking state wrapper.
type ImmutableState struct {
is *abciAPI.ImmutableState
}
func (s *ImmutableState) loadStoredBalance(ctx context.Context, key *keyformat.KeyFormat) (*quantity.Quantity, error) {
value, err := s.is.Get(ctx, key.Encode())
if err != nil {
return nil, abciAPI.UnavailableStateError(err)
}
if value == nil {
return &quantity.Quantity{}, nil
}
var q quantity.Quantity
if err = cbor.Unmarshal(value, &q); err != nil {
return nil, abciAPI.UnavailableStateError(err)
}
return &q, nil
}
// TotalSupply returns the total supply balance.
func (s *ImmutableState) TotalSupply(ctx context.Context) (*quantity.Quantity, error) {
return s.loadStoredBalance(ctx, totalSupplyKeyFmt)
}
// CommonPool returns the balance of the global common pool.
func (s *ImmutableState) CommonPool(ctx context.Context) (*quantity.Quantity, error) {
return s.loadStoredBalance(ctx, commonPoolKeyFmt)
}
// ConsensusParameters returns the consensus parameters.
func (s *ImmutableState) ConsensusParameters(ctx context.Context) (*staking.ConsensusParameters, error) {
raw, err := s.is.Get(ctx, parametersKeyFmt.Encode())
if err != nil {
return nil, abciAPI.UnavailableStateError(err)
}
if raw == nil {
return nil, fmt.Errorf("tendermint/staking: expected consensus parameters to be present in app state")
}
var params staking.ConsensusParameters
if err = cbor.Unmarshal(raw, ¶ms); err != nil {
return nil, abciAPI.UnavailableStateError(err)
}
return ¶ms, nil
}
func (s *ImmutableState) DebondingInterval(ctx context.Context) (beacon.EpochTime, error) {
params, err := s.ConsensusParameters(ctx)
if err != nil {
return beacon.EpochInvalid, err
}
return params.DebondingInterval, nil
}
func (s *ImmutableState) RewardSchedule(ctx context.Context) ([]staking.RewardStep, error) {
params, err := s.ConsensusParameters(ctx)
if err != nil {
return nil, err
}
return params.RewardSchedule, nil
}
func (s *ImmutableState) CommissionScheduleRules(ctx context.Context) (*staking.CommissionScheduleRules, error) {
params, err := s.ConsensusParameters(ctx)
if err != nil {
return nil, err
}
return ¶ms.CommissionScheduleRules, nil
}
// Thresholds returns the currently configured thresholds if any.
func (s *ImmutableState) Thresholds(ctx context.Context) (map[staking.ThresholdKind]quantity.Quantity, error) {
params, err := s.ConsensusParameters(ctx)
if err != nil {
return nil, err
}
return params.Thresholds, nil
}
// Addresses returns the non-empty addresses from the staking ledger.
func (s *ImmutableState) Addresses(ctx context.Context) ([]staking.Address, error) {
it := s.is.NewIterator(ctx)
defer it.Close()
var addresses []staking.Address
for it.Seek(accountKeyFmt.Encode()); it.Valid(); it.Next() {
var addr staking.Address
if !accountKeyFmt.Decode(it.Key(), &addr) {
break
}
addresses = append(addresses, addr)
}
if it.Err() != nil {
return nil, abciAPI.UnavailableStateError(it.Err())
}
return addresses, nil
}
// Account returns the staking account for the given account address.
func (s *ImmutableState) Account(ctx context.Context, address staking.Address) (*staking.Account, error) {
if !address.IsValid() {
return nil, fmt.Errorf("tendermint/staking: invalid account address: %s", address)
}
value, err := s.is.Get(ctx, accountKeyFmt.Encode(&address))
if err != nil {
return nil, abciAPI.UnavailableStateError(err)
}
if value == nil {
return &staking.Account{}, nil
}
var ent staking.Account
if err = cbor.Unmarshal(value, &ent); err != nil {
return nil, abciAPI.UnavailableStateError(err)
}
return &ent, nil
}
// EscrowBalance returns the escrow balance for the given account address.
func (s *ImmutableState) EscrowBalance(ctx context.Context, address staking.Address) (*quantity.Quantity, error) {
account, err := s.Account(ctx, address)
if err != nil {
return nil, err
}
return &account.Escrow.Active.Balance, nil
}
// Delegations returns all active delegations.
func (s *ImmutableState) Delegations(
ctx context.Context,
) (map[staking.Address]map[staking.Address]*staking.Delegation, error) {
it := s.is.NewIterator(ctx)
defer it.Close()
delegations := make(map[staking.Address]map[staking.Address]*staking.Delegation)
for it.Seek(delegationKeyFmt.Encode()); it.Valid(); it.Next() {
var escrowAddr staking.Address
var delegatorAddr staking.Address
if !delegationKeyFmt.Decode(it.Key(), &escrowAddr, &delegatorAddr) {
break
}
var del staking.Delegation
if err := cbor.Unmarshal(it.Value(), &del); err != nil {
return nil, abciAPI.UnavailableStateError(err)
}
if delegations[escrowAddr] == nil {
delegations[escrowAddr] = make(map[staking.Address]*staking.Delegation)
}
delegations[escrowAddr][delegatorAddr] = &del
}
if it.Err() != nil {
return nil, abciAPI.UnavailableStateError(it.Err())
}
return delegations, nil
}
// Delegation returns the delegation descriptor.
func (s *ImmutableState) Delegation(
ctx context.Context,
delegatorAddr, escrowAddr staking.Address,
) (*staking.Delegation, error) {
value, err := s.is.Get(ctx, delegationKeyFmt.Encode(&escrowAddr, &delegatorAddr))
if err != nil {
return nil, abciAPI.UnavailableStateError(err)
}
if value == nil {
return &staking.Delegation{}, nil
}
var del staking.Delegation
if err = cbor.Unmarshal(value, &del); err != nil {
return nil, abciAPI.UnavailableStateError(err)
}
return &del, nil
}
func (s *ImmutableState) DelegationsFor(
ctx context.Context,
delegatorAddr staking.Address,
) (map[staking.Address]*staking.Delegation, error) {
it := s.is.NewIterator(ctx)
defer it.Close()
delegations := make(map[staking.Address]*staking.Delegation)
for it.Seek(delegationKeyFmt.Encode()); it.Valid(); it.Next() {
var escrowAddr staking.Address
var decDelegatorAddr staking.Address
if !delegationKeyFmt.Decode(it.Key(), &escrowAddr, &decDelegatorAddr) {
break
}
if !decDelegatorAddr.Equal(delegatorAddr) {
continue
}
var del staking.Delegation
if err := cbor.Unmarshal(it.Value(), &del); err != nil {
return nil, abciAPI.UnavailableStateError(err)
}
delegations[escrowAddr] = &del
}
if it.Err() != nil {
return nil, abciAPI.UnavailableStateError(it.Err())
}
return delegations, nil
}
func (s *ImmutableState) DelegationsTo(
ctx context.Context,
destAddr staking.Address,
) (map[staking.Address]*staking.Delegation, error) {
it := s.is.NewIterator(ctx)
defer it.Close()
delegations := make(map[staking.Address]*staking.Delegation)
for it.Seek(delegationKeyFmt.Encode()); it.Valid(); it.Next() {
var escrowAddr staking.Address
var delegatorAddr staking.Address
if !delegationKeyFmt.Decode(it.Key(), &escrowAddr, &delegatorAddr) {
break
}
if !escrowAddr.Equal(destAddr) {
continue
}
var del staking.Delegation
if err := cbor.Unmarshal(it.Value(), &del); err != nil {
return nil, abciAPI.UnavailableStateError(err)
}
delegations[delegatorAddr] = &del
}
if it.Err() != nil {
return nil, abciAPI.UnavailableStateError(it.Err())
}
return delegations, nil
}
func (s *ImmutableState) DebondingDelegations(
ctx context.Context,
) (map[staking.Address]map[staking.Address][]*staking.DebondingDelegation, error) {
it := s.is.NewIterator(ctx)
defer it.Close()
delegations := make(map[staking.Address]map[staking.Address][]*staking.DebondingDelegation)
for it.Seek(debondingDelegationKeyFmt.Encode()); it.Valid(); it.Next() {
var escrowAddr staking.Address
var delegatorAddr staking.Address
if !debondingDelegationKeyFmt.Decode(it.Key(), &delegatorAddr, &escrowAddr) {
break
}
var deb staking.DebondingDelegation
if err := cbor.Unmarshal(it.Value(), &deb); err != nil {
return nil, abciAPI.UnavailableStateError(err)
}
if delegations[escrowAddr] == nil {
delegations[escrowAddr] = make(map[staking.Address][]*staking.DebondingDelegation)
}
delegations[escrowAddr][delegatorAddr] = append(delegations[escrowAddr][delegatorAddr], &deb)
}
if it.Err() != nil {
return nil, abciAPI.UnavailableStateError(it.Err())
}
return delegations, nil
}
func (s *ImmutableState) DebondingDelegation(
ctx context.Context,
delegatorAddr, escrowAddr staking.Address,
epoch beacon.EpochTime,
) (*staking.DebondingDelegation, error) {
value, err := s.is.Get(ctx, debondingDelegationKeyFmt.Encode(&delegatorAddr, &escrowAddr, uint64(epoch)))
if err != nil {
return nil, abciAPI.UnavailableStateError(err)
}
if value == nil {
return &staking.DebondingDelegation{}, nil
}
var deb staking.DebondingDelegation
if err = cbor.Unmarshal(value, &deb); err != nil {
return nil, abciAPI.UnavailableStateError(err)
}
return &deb, nil
}
func (s *ImmutableState) DebondingDelegationsFor(
ctx context.Context,
delegatorAddr staking.Address,
) (map[staking.Address][]*staking.DebondingDelegation, error) {
it := s.is.NewIterator(ctx)
defer it.Close()
delegations := make(map[staking.Address][]*staking.DebondingDelegation)
for it.Seek(debondingDelegationKeyFmt.Encode(&delegatorAddr)); it.Valid(); it.Next() {
var escrowAddr staking.Address
var decDelegatorAddr staking.Address
if !debondingDelegationKeyFmt.Decode(it.Key(), &decDelegatorAddr, &escrowAddr) {
break
}
if !decDelegatorAddr.Equal(delegatorAddr) {
continue
}
var deb staking.DebondingDelegation
if err := cbor.Unmarshal(it.Value(), &deb); err != nil {
return nil, abciAPI.UnavailableStateError(err)
}
delegations[escrowAddr] = append(delegations[escrowAddr], &deb)
}
if it.Err() != nil {
return nil, abciAPI.UnavailableStateError(it.Err())
}
return delegations, nil
}
func (s *ImmutableState) DebondingDelegationsTo(
ctx context.Context,
destAddr staking.Address,
) (map[staking.Address][]*staking.DebondingDelegation, error) {
it := s.is.NewIterator(ctx)
defer it.Close()
delegations := make(map[staking.Address][]*staking.DebondingDelegation)
for it.Seek(debondingDelegationKeyFmt.Encode()); it.Valid(); it.Next() {
var escrowAddr staking.Address
var delegatorAddr staking.Address
if !debondingDelegationKeyFmt.Decode(it.Key(), &delegatorAddr, &escrowAddr) {
break
}
if !escrowAddr.Equal(destAddr) {
continue
}
var deb staking.DebondingDelegation
if err := cbor.Unmarshal(it.Value(), &deb); err != nil {
return nil, abciAPI.UnavailableStateError(err)
}
delegations[delegatorAddr] = append(delegations[delegatorAddr], &deb)
}
if it.Err() != nil {
return nil, abciAPI.UnavailableStateError(it.Err())
}
return delegations, nil
}
type DebondingQueueEntry struct {
Epoch beacon.EpochTime
DelegatorAddr staking.Address
EscrowAddr staking.Address
Delegation *staking.DebondingDelegation
}
func (s *ImmutableState) ExpiredDebondingQueue(ctx context.Context, epoch beacon.EpochTime) ([]*DebondingQueueEntry, error) {
it := s.is.NewIterator(ctx)
defer it.Close()
var entries []*DebondingQueueEntry
for it.Seek(debondingQueueKeyFmt.Encode()); it.Valid(); it.Next() {
var decEpoch uint64
var escrowAddr staking.Address
var delegatorAddr staking.Address
if !debondingQueueKeyFmt.Decode(it.Key(), &decEpoch, &delegatorAddr, &escrowAddr) || decEpoch > uint64(epoch) {
break
}
deb, err := s.DebondingDelegation(ctx, delegatorAddr, escrowAddr, beacon.EpochTime(decEpoch))
if err != nil {
return nil, err
}
entries = append(entries, &DebondingQueueEntry{
Epoch: beacon.EpochTime(decEpoch),
DelegatorAddr: delegatorAddr,
EscrowAddr: escrowAddr,
Delegation: deb,
})
}
if it.Err() != nil {
return nil, abciAPI.UnavailableStateError(it.Err())
}
return entries, nil
}
func (s *ImmutableState) Slashing(ctx context.Context) (map[staking.SlashReason]staking.Slash, error) {
params, err := s.ConsensusParameters(ctx)
if err != nil {
return nil, err
}
if params.Slashing == nil {
return make(map[staking.SlashReason]staking.Slash), nil
}
return params.Slashing, nil
}
// LastBlockFees returns the last block fees balance.
func (s *ImmutableState) LastBlockFees(ctx context.Context) (*quantity.Quantity, error) {
return s.loadStoredBalance(ctx, lastBlockFeesKeyFmt)
}
// GovernanceDeposits returns the governance deposits balance.
func (s *ImmutableState) GovernanceDeposits(ctx context.Context) (*quantity.Quantity, error) {
return s.loadStoredBalance(ctx, governanceDepositsKeyFmt)
}
type EpochSigning struct {
Total uint64
ByEntity map[signature.PublicKey]uint64
}
func (es *EpochSigning) Update(signingEntities []signature.PublicKey) error {
oldTotal := es.Total
es.Total = oldTotal + 1
if es.Total <= oldTotal {
return fmt.Errorf("incrementing total blocks count: overflow, old_total=%d", oldTotal)
}
for _, entityID := range signingEntities {
oldCount := es.ByEntity[entityID]
es.ByEntity[entityID] = oldCount + 1
if es.ByEntity[entityID] <= oldCount {
return fmt.Errorf("incrementing count for entity %s: overflow, old_count=%d", entityID, oldCount)
}
}
return nil
}
func (es *EpochSigning) EligibleEntities(thresholdNumerator, thresholdDenominator uint64) ([]signature.PublicKey, error) {
var eligibleEntities []signature.PublicKey
if es.Total > math.MaxUint64/thresholdNumerator {
return nil, fmt.Errorf("overflow in total blocks, total=%d", es.Total)
}
thresholdPremultiplied := es.Total * thresholdNumerator
for entityID, count := range es.ByEntity {
if count > math.MaxUint64/thresholdDenominator {
return nil, fmt.Errorf("entity %s: overflow in threshold comparison, count=%d", entityID, count)
}
if count*thresholdDenominator < thresholdPremultiplied {
continue
}
eligibleEntities = append(eligibleEntities, entityID)
}
sort.Slice(eligibleEntities, func(i, j int) bool {
return bytes.Compare(eligibleEntities[i][:], eligibleEntities[j][:]) < 0
})
return eligibleEntities, nil
}
func (s *ImmutableState) EpochSigning(ctx context.Context) (*EpochSigning, error) {
value, err := s.is.Get(ctx, epochSigningKeyFmt.Encode())
if err != nil {
return nil, abciAPI.UnavailableStateError(err)
}
if value == nil {
// Not present means zero everything.
return &EpochSigning{
ByEntity: make(map[signature.PublicKey]uint64),
}, nil
}
var es EpochSigning
if err = cbor.Unmarshal(value, &es); err != nil {
return nil, abciAPI.UnavailableStateError(err)
}
return &es, nil
}
func NewImmutableState(ctx context.Context, state abciAPI.ApplicationQueryState, version int64) (*ImmutableState, error) {
is, err := abciAPI.NewImmutableState(ctx, state, version)
if err != nil {
return nil, err
}
return &ImmutableState{is}, nil
}
// MutableState is a mutable staking state wrapper.
type MutableState struct {
*ImmutableState
ms mkvs.KeyValueTree
}
func (s *MutableState) SetAccount(ctx context.Context, addr staking.Address, account *staking.Account) error {
err := s.ms.Insert(ctx, accountKeyFmt.Encode(&addr), cbor.Marshal(account))
return abciAPI.UnavailableStateError(err)
}
func (s *MutableState) SetTotalSupply(ctx context.Context, q *quantity.Quantity) error {
err := s.ms.Insert(ctx, totalSupplyKeyFmt.Encode(), cbor.Marshal(q))
return abciAPI.UnavailableStateError(err)
}
func (s *MutableState) SetCommonPool(ctx context.Context, q *quantity.Quantity) error {
err := s.ms.Insert(ctx, commonPoolKeyFmt.Encode(), cbor.Marshal(q))
return abciAPI.UnavailableStateError(err)
}
// SetConsensusParameters sets staking consensus parameters.
//
// NOTE: This method must only be called from InitChain/EndBlock contexts.
func (s *MutableState) SetConsensusParameters(ctx context.Context, params *staking.ConsensusParameters) error {
if err := s.is.CheckContextMode(ctx, []abciAPI.ContextMode{abciAPI.ContextInitChain, abciAPI.ContextEndBlock}); err != nil {
return err
}
err := s.ms.Insert(ctx, parametersKeyFmt.Encode(), cbor.Marshal(params))
return abciAPI.UnavailableStateError(err)
}
func (s *MutableState) SetDelegation(
ctx context.Context,
delegatorAddr, escrowAddr staking.Address,
d *staking.Delegation,
) error {
// Remove delegation if there are no more shares in it.
if d.Shares.IsZero() {
err := s.ms.Remove(ctx, delegationKeyFmt.Encode(&escrowAddr, &delegatorAddr))
return abciAPI.UnavailableStateError(err)
}
err := s.ms.Insert(ctx, delegationKeyFmt.Encode(&escrowAddr, &delegatorAddr), cbor.Marshal(d))
return abciAPI.UnavailableStateError(err)
}
func (s *MutableState) SetDebondingDelegation(
ctx context.Context,
delegatorAddr, escrowAddr staking.Address,
epoch beacon.EpochTime,
d *staking.DebondingDelegation,
) error {
key := debondingDelegationKeyFmt.Encode(&delegatorAddr, &escrowAddr, uint64(epoch))
if d == nil {
// Remove descriptor.
err := s.ms.Remove(ctx, key)
return abciAPI.UnavailableStateError(err)
}
// Create a copy so we don't modify the passed in object in case we are merging
// it with an existing delegation.
debDel := staking.DebondingDelegation{
Shares: *d.Shares.Clone(),
DebondEndTime: d.DebondEndTime,
}
// If a debonding delegation for the account and same end epoch already exists,
// merge the debonding delegations.
value, err := s.is.Get(ctx, key)
if err != nil {
return abciAPI.UnavailableStateError(err)
}
if value != nil {
var deb staking.DebondingDelegation
if err = cbor.Unmarshal(value, &deb); err != nil {
return abciAPI.UnavailableStateError(err)
}
if err = debDel.Merge(deb); err != nil {
return fmt.Errorf("error merging debonding delegations: %w", err)
}
}
// Add to debonding queue.
if err := s.ms.Insert(
ctx,
debondingQueueKeyFmt.Encode(uint64(d.DebondEndTime),
&delegatorAddr,
&escrowAddr,
),
[]byte{},
); err != nil {
return abciAPI.UnavailableStateError(err)
}
// Add descriptor.
if err := s.ms.Insert(ctx, key, cbor.Marshal(debDel)); err != nil {
return abciAPI.UnavailableStateError(err)
}
return nil
}
func (s *MutableState) RemoveFromDebondingQueue(
ctx context.Context,
epoch beacon.EpochTime,
delegatorAddr, escrowAddr staking.Address,
) error {
err := s.ms.Remove(ctx, debondingQueueKeyFmt.Encode(uint64(epoch), &delegatorAddr, &escrowAddr))
return abciAPI.UnavailableStateError(err)
}
func (s *MutableState) SetLastBlockFees(ctx context.Context, q *quantity.Quantity) error {
err := s.ms.Insert(ctx, lastBlockFeesKeyFmt.Encode(), cbor.Marshal(q))
return abciAPI.UnavailableStateError(err)
}
func (s *MutableState) SetEpochSigning(ctx context.Context, es *EpochSigning) error {
err := s.ms.Insert(ctx, epochSigningKeyFmt.Encode(), cbor.Marshal(es))
return abciAPI.UnavailableStateError(err)
}
func (s *MutableState) ClearEpochSigning(ctx context.Context) error {
err := s.ms.Remove(ctx, epochSigningKeyFmt.Encode())
return abciAPI.UnavailableStateError(err)
}
func (s *MutableState) SetGovernanceDeposits(ctx context.Context, q *quantity.Quantity) error {
err := s.ms.Insert(ctx, governanceDepositsKeyFmt.Encode(), cbor.Marshal(q))
return abciAPI.UnavailableStateError(err)
}
func slashPool(dst *quantity.Quantity, p *staking.SharePool, amount, total *quantity.Quantity) error {
if total.IsZero() {
// Nothing to slash.
return nil
}
// slashAmount = amount * p.Balance / total
slashAmount := p.Balance.Clone()
if err := slashAmount.Mul(amount); err != nil {
return fmt.Errorf("tendermint/staking: slashAmount.Mul: %w", err)
}
if err := slashAmount.Quo(total); err != nil {
return fmt.Errorf("tendermint/staking: slashAmount.Quo: %w", err)
}
if _, err := quantity.MoveUpTo(dst, &p.Balance, slashAmount); err != nil {
return fmt.Errorf("tendermint/staking: failed moving stake: %w", err)
}
return nil
}
// SlashEscrow slashes the escrow balance and the escrow-but-undergoing-debonding
// balance of the account, transferring it to the global common pool, returning
// the amount actually slashed.
//
// WARNING: This is an internal routine to be used to implement staking policy,
// and MUST NOT be exposed outside of backend implementations.
func (s *MutableState) SlashEscrow(
ctx *abciAPI.Context,
fromAddr staking.Address,
amount *quantity.Quantity,
) (*quantity.Quantity, error) {
var slashed quantity.Quantity
commonPool, err := s.CommonPool(ctx)
if err != nil {
return nil, fmt.Errorf("tendermint/staking: failed to query common pool for slash: %w", err)
}
from, err := s.Account(ctx, fromAddr)
if err != nil {
return nil, fmt.Errorf("tendermint/staking: failed to query account %s: %w", fromAddr, err)
}
// Compute the amount we need to slash each pool. The amount is split
// between the pools based on relative total balance.
total := from.Escrow.Active.Balance.Clone()
if err = total.Add(&from.Escrow.Debonding.Balance); err != nil {
return nil, fmt.Errorf("tendermint/staking: account total balance: %w", err)
}
if err = slashPool(&slashed, &from.Escrow.Active, amount, total); err != nil {
return nil, fmt.Errorf("tendermint/staking: failed slashing active escrow: %w", err)
}
if err = slashPool(&slashed, &from.Escrow.Debonding, amount, total); err != nil {
return nil, fmt.Errorf("tendermint/staking: failed slashing debonding escrow: %w", err)
}
// Nothing was slashed.
if slashed.IsZero() {
return &slashed, nil
}
totalSlashed := slashed.Clone()
if err = quantity.Move(commonPool, &slashed, totalSlashed); err != nil {
return nil, fmt.Errorf("tendermint/staking: failed moving stake to common pool: %w", err)
}
if err = s.SetCommonPool(ctx, commonPool); err != nil {
return nil, fmt.Errorf("tendermint/staking: failed to set common pool: %w", err)
}
if err = s.SetAccount(ctx, fromAddr, from); err != nil {
return nil, fmt.Errorf("tendermint/staking: failed to set account: %w", err)
}
if !ctx.IsCheckOnly() {
ctx.EmitEvent(abciAPI.NewEventBuilder(AppName).TypedAttribute(&staking.TakeEscrowEvent{
Owner: fromAddr,
Amount: *totalSlashed,
}))
}
return totalSlashed, nil
}
// Transfer performs a transfer between two general account balances.
func (s *MutableState) Transfer(ctx *abciAPI.Context, fromAddr, toAddr staking.Address, amount *quantity.Quantity) error {
if fromAddr.Equal(toAddr) || amount.IsZero() {
return nil
}
from, err := s.Account(ctx, fromAddr)
if err != nil {
return err
}
to, err := s.Account(ctx, toAddr)
if err != nil {
return err
}
if err = quantity.Move(&to.General.Balance, &from.General.Balance, amount); err != nil {
return staking.ErrInsufficientBalance
}
// Check against minimum balance.
params, err := s.ConsensusParameters(ctx)
if err != nil {
return fmt.Errorf("failed to fetch consensus parameters: %w", err)
}
if from.General.Balance.Cmp(¶ms.MinTransactBalance) < 0 {
ctx.Logger().Error("source account balance too low",
"account_addr", fromAddr,
"account_balance", from.General.Balance,
"min_transact_balance", params.MinTransactBalance,
)
return errors.WithContext(staking.ErrBalanceTooLow, "source account")
}
if to.General.Balance.Cmp(¶ms.MinTransactBalance) < 0 {
ctx.Logger().Error("after transfer dest account balance too low",
"account_addr", toAddr,
"account_balance", to.General.Balance,
"min_transact_balance", params.MinTransactBalance,
)
return errors.WithContext(staking.ErrBalanceTooLow, "dest account")
}
if err = s.SetAccount(ctx, fromAddr, from); err != nil {
return err
}
if err = s.SetAccount(ctx, toAddr, to); err != nil {
return err
}
if !ctx.IsCheckOnly() {
ctx.EmitEvent(abciAPI.NewEventBuilder(AppName).TypedAttribute(&staking.TransferEvent{
From: fromAddr,
To: toAddr,
Amount: *amount,
}))
}
return nil
}
// TransferFromCommon transfers up to the amount from the global common pool
// to the general balance of the account, returning true iff the
// amount transferred is > 0.
//
// If the escrow flag is true then the amount is escrowed instead of being
// transferred. The escrow operation takes the entity's commission rate into
// account and the rest is distributed to all delegators equally.
//
// WARNING: This is an internal routine to be used to implement incentivization
// policy, and MUST NOT be exposed outside of backend implementations.
func (s *MutableState) TransferFromCommon(
ctx *abciAPI.Context,
toAddr staking.Address,
amount *quantity.Quantity,
escrow bool,
) (bool, error) {
commonPool, err := s.CommonPool(ctx)
if err != nil {
return false, fmt.Errorf("tendermint/staking: failed to query common pool for transfer: %w", err)
}
// Transfer up to the given amount from the common pool to the general account balance.
to, err := s.Account(ctx, toAddr)
if err != nil {
return false, fmt.Errorf("tendermint/staking: failed to query account %s: %w", toAddr, err)
}
transferred, err := quantity.MoveUpTo(&to.General.Balance, commonPool, amount)
if err != nil {
return false, fmt.Errorf("tendermint/staking: failed to transfer from common pool: %w", err)
}
if transferred.IsZero() {
// Common pool has been depleated, nothing to transfer.
return false, nil
}
switch escrow {
case true:
// If escrow is requested, escrow the transferred stake immediately.
var com *quantity.Quantity
switch to.Escrow.Active.TotalShares.IsZero() {
case false:
// Compute commission.
var epoch beacon.EpochTime
epoch, err = ctx.AppState().GetCurrentEpoch(ctx)
if err != nil {
return false, fmt.Errorf("tendermint/staking: failed to get current epoch: %w", err)
}
rate := to.Escrow.CommissionSchedule.CurrentRate(epoch)
if rate != nil {
com = transferred.Clone()
// Multiply first.
if err = com.Mul(rate); err != nil {
return false, fmt.Errorf("tendermint/staking: failed multiplying by commission rate: %w", err)
}
if err = com.Quo(staking.CommissionRateDenominator); err != nil {
return false, fmt.Errorf("tendermint/staking: failed dividing by commission rate denominator: %w", err)
}
if err = transferred.Sub(com); err != nil {
return false, fmt.Errorf("tendermint/staking: failed subtracting commission: %w", err)
}
}
// Escrow everything except the commission (increases value of all shares).
if err = quantity.Move(&to.Escrow.Active.Balance, &to.General.Balance, transferred); err != nil {
return false, fmt.Errorf("tendermint/staking: failed transferring to active escrow balance from common pool: %w", err)
}
// Emit non commissioned reward event.
if !ctx.IsCheckOnly() {
ctx.EmitEvent(abciAPI.NewEventBuilder(AppName).TypedAttribute(&staking.AddEscrowEvent{
Owner: staking.CommonPoolAddress,
Escrow: toAddr,
Amount: *transferred,
// No new shares as this is the reward. As a result existing share price increases.
NewShares: quantity.Quantity{},
}))
}
case true:
// If nothing has been escrowed before, everything counts as commission.
com = transferred.Clone()
}
// Escrow commission.
if com != nil && !com.IsZero() {
var delegation *staking.Delegation
delegation, err = s.Delegation(ctx, toAddr, toAddr)
if err != nil {
return false, fmt.Errorf("tendermint/staking: failed to query delegation: %w", err)
}
var obtainedShares *quantity.Quantity
obtainedShares, err = to.Escrow.Active.Deposit(&delegation.Shares, &to.General.Balance, com)
if err != nil {
return false, fmt.Errorf("tendermint/staking: failed to deposit to escrow: %w", err)
}
if err = s.SetDelegation(ctx, toAddr, toAddr, delegation); err != nil {
return false, fmt.Errorf("tendermint/staking: failed to set delegation: %w", err)
}
// Emit events.
// Commission was transferred to the account, and automatically escrowed.
if !ctx.IsCheckOnly() {
ctx.EmitEvent(abciAPI.NewEventBuilder(AppName).TypedAttribute(&staking.TransferEvent{
From: staking.CommonPoolAddress,
To: toAddr,
Amount: *com,
}))
ctx.EmitEvent(abciAPI.NewEventBuilder(AppName).TypedAttribute(&staking.AddEscrowEvent{
Owner: toAddr,
Escrow: toAddr,
Amount: *com,
NewShares: *obtainedShares,
}))
}
}
case false:
if !ctx.IsCheckOnly() {
ctx.EmitEvent(abciAPI.NewEventBuilder(AppName).TypedAttribute(&staking.TransferEvent{
From: staking.CommonPoolAddress,
To: toAddr,
Amount: *transferred,
}))
}
}
if err = s.SetCommonPool(ctx, commonPool); err != nil {
return false, fmt.Errorf("tendermint/staking: failed to set common pool: %w", err)
}
if err = s.SetAccount(ctx, toAddr, to); err != nil {
return false, fmt.Errorf("tendermint/staking: failed to set account %s: %w", toAddr, err)
}
return true, nil
}
// TransferToGovernanceDeposits transfers the amount from the submitter to the
// governance deposits pool.
func (s *MutableState) TransferToGovernanceDeposits(
ctx *abciAPI.Context,
fromAddr staking.Address,
amount *quantity.Quantity,
) error {
from, err := s.Account(ctx, fromAddr)
if err != nil {
return fmt.Errorf("tendermint/staking: failed to query account %s: %w", fromAddr, err)
}
deposits, err := s.GovernanceDeposits(ctx)
if err != nil {
return fmt.Errorf("tendermint/staking: failed to query governance deposit for deposit %w", err)
}
if err = quantity.Move(deposits, &from.General.Balance, amount); err != nil {
return fmt.Errorf("tendermint/staking: failed to transfer to governance deposits, from: %s: %w", fromAddr, err)
}
if err = s.SetAccount(ctx, fromAddr, from); err != nil {