-
Notifications
You must be signed in to change notification settings - Fork 102
/
valStateChanges.go
719 lines (684 loc) · 27.3 KB
/
valStateChanges.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
package keeper
import (
"bytes"
"encoding/hex"
"fmt"
"time"
"github.com/pokt-network/pocket-core/codec"
"github.com/pokt-network/pocket-core/crypto"
sdk "github.com/pokt-network/pocket-core/types"
"github.com/pokt-network/pocket-core/x/nodes/types"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/libs/strings"
)
// UpdateTendermintValidators - Apply and return accumulated updates to the staked validator set
// It gets called once after genesis, another time maybe after genesis transactions,
// then once at every EndBlock.
func (k Keeper) UpdateTendermintValidators(ctx sdk.Ctx) (updates []abci.ValidatorUpdate) {
// get the world state
store := ctx.KVStore(k.storeKey)
// allow all waiting to begin unstaking to begin unstaking
if ctx.BlockHeight()%k.BlocksPerSession(ctx) == 0 { // one block before new session (mod 1 would be session block)
k.ReleaseWaitingValidators(ctx)
}
maxValidators := k.MaxValidators(ctx)
totalPower := sdk.ZeroInt()
// Retrieve the prevState validator set addresses mapped to their respective staking power
prevStatePowerMap := k.getPrevStatePowerMap(ctx)
// Iterate over staked validators, highest power to lowest.
iterator, _ := sdk.KVStoreReversePrefixIterator(store, types.StakedValidatorsKey)
defer iterator.Close()
for count := 0; iterator.Valid() && count < int(maxValidators); iterator.Next() {
// get the validator address
valAddr := sdk.Address(iterator.Value())
// return the validator from the current store
validator, found := k.GetValidator(ctx, valAddr)
if !found {
k.Logger(ctx).Error("staking validator not found in UpdateTendermintValidators: " + valAddr.String())
// Cant delete w/out validator object due to ordering
continue
}
// sanity check for no jailed validators
if validator.Jailed {
k.Logger(ctx).Error("should never retrieve a jailed validator from the staked validators:" + validator.Address.String())
continue
}
if validator.ConsensusPower() == 0 {
k.Logger(ctx).Error("should never retrieve a zero power validator from the staked validators:" + validator.Address.String())
continue
}
// fetch the old power bytes
var valAddrBytes [sdk.AddrLen]byte
copy(valAddrBytes[:], valAddr[:])
// check the previous state: if found calculate current power...
prevStatePowerBytes, found := prevStatePowerMap[valAddrBytes]
curStatePower := validator.ConsensusPower()
var curStatePowerBytes []byte
var err error
csp := sdk.Int64(curStatePower)
curStatePowerBytes, err = k.Cdc.MarshalBinaryLengthPrefixed(&csp, ctx.BlockHeight())
if err != nil {
panic(err)
}
// if not found or the power has changed -> add this validator to the updated list
if !found || !bytes.Equal(prevStatePowerBytes, curStatePowerBytes) {
ctx.Logger().Debug(fmt.Sprintf("Updating Validator-Set to Tendermint: %s power changed to %d", validator.Address, validator.ConsensusPower()))
updates = append(updates, validator.ABCIValidatorUpdate())
// update the previous state as this will soon be the previous state
k.SetPrevStateValPower(ctx, valAddr, curStatePower)
}
// remove the validator from power map, this structure is used to keep track of who is no longer staked
delete(prevStatePowerMap, valAddrBytes)
// keep count of the number of validators to ensure we don't go over the maximum number of validators
count++
// update the total power
totalPower = totalPower.Add(sdk.NewInt(curStatePower))
}
// sort the no-longer-staked validators
noLongerStaked := sortNoLongerStakedValidators(prevStatePowerMap)
// iterate through the sorted no-longer-staked validators
for _, valAddrBytes := range noLongerStaked {
validator, found := k.GetValidator(ctx, valAddrBytes)
if !found {
ctx.Logger().Error(fmt.Sprintf("unable to retrieve `nolongerstaked` validator: %s from the world state at height: %d ", hex.EncodeToString(valAddrBytes), ctx.BlockHeight()))
continue
}
// delete from the stake validator index
k.DeletePrevStateValPower(ctx, validator.GetAddress())
// add to one of the updates for tendermint
ctx.Logger().Debug(fmt.Sprintf("Updating Validator-Set to Tendermint: %s is no longer staked, at height %d", validator.Address, ctx.BlockHeight()))
if k.Cdc.IsAfterValidatorSplitUpgrade(ctx.BlockHeight()) {
updates = append(updates, validator.ABCIValidatorZeroUpdate())
} else {
updates = append(updates, validator.ABCIValidatorUpdate())
}
// if validator was force unstaked, delete the validator from the all validators store
if validator.IsUnstaked() {
k.DeleteValidator(ctx, validator.Address)
}
}
// set total power on lookup index if there are any updates
if len(updates) > 0 {
k.SetPrevStateValidatorsPower(ctx, totalPower)
}
return updates
}
// ValidateValidatorStaking - Check Validator before staking
func (k Keeper) ValidateValidatorStaking(
ctx sdk.Ctx,
validatorNew types.Validator,
amount sdk.BigInt,
signerAddress sdk.Address,
) sdk.Error {
// check to see if the public key has already been register for that validator
validatorCur, found := k.GetValidator(ctx, validatorNew.Address)
// Before the upgrade, we validate a signer against the new validator's state
// via ValidateValidatorMsgSigner. After the upgrade, however, we accept
// MsgStake signed by the current output address that doesn't appear in the
// new validator's state. So we skip ValidateValidatorMsgSigner if 1) the
// current height is after the upgrade, 2) this is an edit-stake changing the
// output address, and 3) the signer is the current output address.
skipMsgSignerValidation := found &&
k.Cdc.IsAfterNonCustodialUpgrade(ctx.BlockHeight()) &&
k.Cdc.IsAfterOutputAddressEditorUpgrade(ctx.BlockHeight()) &&
validatorNew.Address.Equals(validatorCur.Address) &&
validatorNew.OutputAddress != nil &&
!validatorCur.OutputAddress.Equals(validatorNew.OutputAddress) &&
validatorCur.OutputAddress.Equals(signerAddress)
if !skipMsgSignerValidation {
// check the "new" validator's state first
err, valid := ValidateValidatorMsgSigner(validatorNew, signerAddress, k)
if !valid {
return err
}
}
//check that we don't allow nil output if we are after noncustodial upgrade
//so we won't accept stakes/edits with nil outputAddress
if k.Cdc.IsAfterNonCustodialUpgrade(ctx.BlockHeight()) {
if validatorNew.OutputAddress == nil {
return types.ErrNilOutputAddr(k.codespace)
}
}
coin := sdk.NewCoins(sdk.NewCoin(k.StakeDenom(ctx), amount))
if int64(len(validatorNew.Chains)) > k.MaxChains(ctx) {
return types.ErrTooManyChains(types.ModuleName)
}
if found {
//check again based on the "current" validator's state
err, valid := ValidateValidatorMsgSigner(validatorCur, signerAddress, k)
if !valid {
return err
}
// edit stake in 6.X upgrade
if ctx.IsAfterUpgradeHeight() && validatorCur.IsStaked() {
return k.ValidateEditStake(ctx, validatorCur, validatorNew, amount, signerAddress)
}
if !validatorCur.IsUnstaked() { // unstaking or already staked but before the upgrade
return types.ErrValidatorStatus(k.codespace)
}
} else {
// check the consensus params
if ctx.ConsensusParams() != nil {
tmPubKey, err := crypto.CheckConsensusPubKey(validatorNew.PublicKey.PubKey())
if err != nil {
return types.ErrValidatorPubKeyTypeNotSupported(k.Codespace(),
err.Error(),
ctx.ConsensusParams().Validator.PubKeyTypes)
}
if !strings.StringInSlice(tmPubKey.Type, ctx.ConsensusParams().Validator.PubKeyTypes) {
return types.ErrValidatorPubKeyTypeNotSupported(k.Codespace(),
tmPubKey.Type,
ctx.ConsensusParams().Validator.PubKeyTypes)
}
}
}
if amount.LT(sdk.NewInt(k.MinimumStake(ctx))) {
return types.ErrMinimumStake(k.codespace)
}
if k.Cdc.IsAfterNonCustodialUpgrade(ctx.BlockHeight()) {
if !k.AccountKeeper.HasCoins(ctx, signerAddress, coin) {
return types.ErrNotEnoughCoins(k.codespace)
}
} else {
if !k.AccountKeeper.HasCoins(ctx, validatorNew.Address, coin) {
return types.ErrNotEnoughCoins(k.codespace)
}
}
return nil
}
// ValidateValidatorMsgSigner Check Validator Signature
func ValidateValidatorMsgSigner(validator types.Validator, signerAddress sdk.Address, k Keeper) (sdk.Error, bool) {
//check if outputAddress is defined, if not only the operator/node signature is valid
if validator.OutputAddress == nil {
if !signerAddress.Equals(validator.Address) {
return types.ErrUnauthorizedSigner(k.Codespace()), false
}
} else {
if !signerAddress.Equals(validator.Address) && !signerAddress.Equals(validator.OutputAddress) {
return types.ErrUnauthorizedSigner(k.Codespace()), false
}
}
return nil, true
}
// ValidateEditStake - Validate the updates to a current staked validator
func (k Keeper) ValidateEditStake(ctx sdk.Ctx, currentValidator, newValidtor types.Validator, amount sdk.BigInt, signer sdk.Address) sdk.Error {
// ensure not staking less
diff := amount.Sub(currentValidator.StakedTokens)
if diff.IsNegative() {
return types.ErrMinimumEditStake(k.codespace)
}
if k.Cdc.IsAfterNamedFeatureActivationHeight(ctx.BlockHeight(), codec.RSCALKey) && k.Cdc.IsAfterNamedFeatureActivationHeight(ctx.BlockHeight(), codec.VEDITKey) {
//check that we are bumping up into a new bin or are above the cieling, if not return an error
if amount.LT(k.ServicerStakeWeightCeiling(ctx)) {
//grab the bin and check if we are in a new bin
flooredNewStake := amount.Sub(amount.Mod(k.ServicerStakeFloorMultiplier(ctx)))
if flooredNewStake.LTE(currentValidator.StakedTokens) {
return types.ErrSameBinEditStake(k.codespace)
}
}
}
// if stake bump
if !diff.IsZero() {
// ensure account has enough coins for bump
coin := sdk.NewCoins(sdk.NewCoin(k.StakeDenom(ctx), diff))
if k.Cdc.IsAfterNonCustodialUpgrade(ctx.BlockHeight()) {
if !k.AccountKeeper.HasCoins(ctx, signer, coin) {
return types.ErrNotEnoughCoins(k.Codespace())
}
} else {
if !k.AccountKeeper.HasCoins(ctx, currentValidator.Address, coin) {
return types.ErrNotEnoughCoins(k.Codespace())
}
}
}
if k.Cdc.IsAfterNonCustodialUpgrade(ctx.BlockHeight()) {
if k.Cdc.IsAfterOutputAddressEditorUpgrade(ctx.BlockHeight()) {
// ensure only the current output address owner can change the output address
if currentValidator.OutputAddress != nil &&
!signer.Equals(currentValidator.OutputAddress) &&
!newValidtor.OutputAddress.Equals(currentValidator.OutputAddress) {
return types.ErrDisallowedOutputAddressEdit(k.Codespace())
}
} else {
// ensure output address doesn't change
if currentValidator.OutputAddress != nil &&
!newValidtor.OutputAddress.Equals(currentValidator.OutputAddress) {
return types.ErrUnequalOutputAddr(k.Codespace())
}
}
// Following PIP-32, RewardDelegators can be set/edited only if:
// 1) The feature has been activated AND
// 2) the message is signed by the operator address.
// For more details, see
// https://forum.pokt.network/t/pip32-unleashing-the-potential-of-non-custodial-node-running/4796
if k.Cdc.IsAfterRewardDelegatorUpgrade(ctx.BlockHeight()) &&
!types.CompareStringMaps(
currentValidator.RewardDelegators,
newValidtor.RewardDelegators,
) &&
!signer.Equals(currentValidator.Address) {
return types.ErrDisallowedRewardDelegatorEdit(k.Codespace())
}
// prevent waiting vals from modifying anything
if k.IsWaitingValidator(ctx, currentValidator.Address) {
return types.ErrValidatorWaitingToUnstake(types.ModuleName)
}
}
return nil
}
// StakeValidator - Store ops when a validator stakes
func (k Keeper) StakeValidator(ctx sdk.Ctx, validator types.Validator, amount sdk.BigInt, signer crypto.PublicKey) sdk.Error {
// edit stake
if ctx.IsAfterUpgradeHeight() {
// get Validator to see if edit stake
val, found := k.GetValidator(ctx, validator.Address)
if found && val.IsStaked() {
return k.EditStakeValidator(ctx, val, validator, amount, signer)
}
}
// send the coins from address to staked module account
err := k.coinsFromUnstakedToStaked(ctx, sdk.Address(signer.Address()), amount)
if err != nil {
return err
}
// add coins to the staked field
validator, er := validator.AddStakedTokens(amount)
if er != nil {
return sdk.ErrInternal(er.Error())
}
// set the status to staked
validator = validator.UpdateStatus(sdk.Staked)
// save in the validator store
k.SetValidator(ctx, validator)
k.SetStakedValidatorByChains(ctx, validator)
// ensure there's a signing info entry for the validator (used in slashing)
_, found := k.GetValidatorSigningInfo(ctx, validator.GetAddress())
if !found {
signingInfo := types.ValidatorSigningInfo{
Address: validator.GetAddress(),
StartHeight: ctx.BlockHeight(),
JailedUntil: time.Unix(0, 0),
}
k.SetValidatorSigningInfo(ctx, validator.GetAddress(), signingInfo)
}
ctx.Logger().Info("Successfully staked validator: " + validator.Address.String())
return nil
}
// EditStakeValidator - Edit an already staked validator with the staking message
func (k Keeper) EditStakeValidator(ctx sdk.Ctx, currentValidator, updatedValidator types.Validator, amount sdk.BigInt, signer crypto.PublicKey) sdk.Error {
origValForDeletion := currentValidator
// get the difference in coins
diff := amount.Sub(currentValidator.StakedTokens)
// if they bumped the stake amount
if diff.IsPositive() {
// send the coins from address to staked module account
err := k.coinsFromUnstakedToStaked(ctx, sdk.Address(signer.Address()), diff)
if err != nil {
return err
}
currentValidator.StakedTokens = currentValidator.StakedTokens.Add(diff)
}
if k.Cdc.IsAfterNonCustodialUpgrade(ctx.BlockHeight()) {
// After the upgrade, we allow output address change
if k.Cdc.IsAfterOutputAddressEditorUpgrade(ctx.BlockHeight()) ||
currentValidator.OutputAddress == nil {
currentValidator.OutputAddress = updatedValidator.OutputAddress
}
// After the upgrade, we allow delegators change
if k.Cdc.IsAfterRewardDelegatorUpgrade(ctx.BlockHeight()) {
currentValidator.RewardDelegators = updatedValidator.RewardDelegators
}
}
// update chains
currentValidator.Chains = updatedValidator.Chains
// update service url
currentValidator.ServiceURL = updatedValidator.ServiceURL
// delete the validator from the staking set
k.deleteValidatorFromStakingSet(ctx, origValForDeletion)
// delete the validator from each individual chains set
k.deleteValidatorForChains(ctx, origValForDeletion)
// delete in main store
k.DeleteValidator(ctx, origValForDeletion.Address)
// save in the validator store
k.SetValidator(ctx, currentValidator)
// save the validator by chains
k.SetStakedValidatorByChains(ctx, currentValidator)
// patch for june 30 fork
if ctx.BlockHeight() >= 30040 {
// reset signing info
k.ResetValidatorSigningInfo(ctx, currentValidator.Address)
}
// clear cache
k.PocketKeeper.ClearSessionCache()
// log success
ctx.Logger().Info("Successfully updated staked validator: " + currentValidator.Address.String())
return nil
}
// ValidateValidatorBeginUnstaking - Check for validator status
func (k Keeper) ValidateValidatorBeginUnstaking(ctx sdk.Ctx, validator types.Validator) sdk.Error {
// must be staked to begin unstaking
if !validator.IsStaked() {
return types.ErrValidatorStatus(k.codespace)
}
if k.Cdc.IsAfterNonCustodialUpgrade(ctx.BlockHeight()) { // allow jailed validators to begin unstaking
return nil
}
if validator.IsJailed() {
return types.ErrValidatorJailed(k.codespace)
}
return nil
}
// WaitToBeginUnstakingValidator - Change validator status to waiting to begin unstaking
func (k Keeper) WaitToBeginUnstakingValidator(ctx sdk.Ctx, validator types.Validator) sdk.Error {
k.SetWaitingValidator(ctx, validator)
ctx.Logger().Info("Validator " + validator.Address.String() + " is waiting to begin unstaking until session is over")
return nil
}
// ReleaseWaitingValidators - Remove UnstakingValidators from store
func (k Keeper) ReleaseWaitingValidators(ctx sdk.Ctx) {
vals := k.GetWaitingValidators(ctx)
for _, val := range vals {
if err := k.ValidateValidatorBeginUnstaking(ctx, val); err == nil {
// if able to begin unstaking
k.BeginUnstakingValidator(ctx, val)
// create the event
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypeBeginUnstake,
sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory),
sdk.NewAttribute(sdk.AttributeKeySender, val.Address.String()),
),
sdk.NewEvent(
sdk.EventTypeMessage,
sdk.NewAttribute(sdk.AttributeKeyModule, types.EventTypeBeginUnstake),
sdk.NewAttribute(sdk.AttributeKeySender, val.Address.String()),
),
})
} else {
ctx.Logger().Info("Unable to begin unstaking validator " + val.Address.String() + ": " + err.Error())
}
k.DeleteWaitingValidator(ctx, val.Address)
}
}
// BeginUnstakingValidator - Store ops when validator begins to unstake -> starts the unstaking timer
func (k Keeper) BeginUnstakingValidator(ctx sdk.Ctx, validator types.Validator) {
// get params
params := k.GetParams(ctx)
// delete the validator from the staking set, as it is technically staked but not going to participate
k.deleteValidatorFromStakingSet(ctx, validator)
// delete the validator from each individual chains set
k.deleteValidatorForChains(ctx, validator)
// set the status
validator = validator.UpdateStatus(sdk.Unstaking)
// set the unstaking completion time and completion height appropriately
if validator.UnstakingCompletionTime.IsZero() {
validator.UnstakingCompletionTime = ctx.BlockHeader().Time.Add(params.UnstakingTime)
}
// save the now unstaked validator record and power index
k.SetValidator(ctx, validator)
ctx.Logger().Info("Began unstaking validator " + validator.Address.String())
}
// ValidateValidatorFinishUnstaking - Check if validator can finish unstaking
func (k Keeper) ValidateValidatorFinishUnstaking(ctx sdk.Ctx, validator types.Validator) sdk.Error {
if !validator.IsUnstaking() {
return types.ErrValidatorStatus(k.codespace)
}
if k.Cdc.IsAfterNonCustodialUpgrade(ctx.BlockHeight()) { // allow jailed validators to finish unstaking
return nil
}
if validator.IsJailed() {
return types.ErrValidatorJailed(k.codespace)
}
return nil
}
// FinishUnstakingValidator - Store ops to unstake a validator -> called after unstaking time is up
func (k Keeper) FinishUnstakingValidator(ctx sdk.Ctx, validator types.Validator) {
// delete the validator from the unstaking queue
k.deleteUnstakingValidator(ctx, validator)
// amount unstaked = stakedTokens
amount := validator.StakedTokens
// send the tokens from staking module account to validator account
err := k.coinsFromStakedToUnstaked(ctx, validator)
if err != nil {
k.Logger(ctx).Error(err.Error())
// even if error continue with the unstake
}
// removed the staked tokens field from validator structure
validator, err = validator.RemoveStakedTokens(amount)
if err != nil {
k.Logger(ctx).Error(err.Error())
// even if error continue with the unstake
}
// update the status to unstaked
validator = validator.UpdateStatus(sdk.Unstaked)
// update the unstaking time
validator.UnstakingCompletionTime = time.Time{}
// update the validator in the main store
k.SetValidator(ctx, validator)
ctx.Logger().Info("Finished unstaking validator " + validator.Address.String())
// create the event
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypeUnstake,
sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory),
sdk.NewAttribute(sdk.AttributeKeySender, validator.Address.String()),
),
sdk.NewEvent(
sdk.EventTypeMessage,
sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory),
sdk.NewAttribute(sdk.AttributeKeySender, validator.Address.String()),
),
})
}
// LegacyForceValidatorUnstake - Coerce unstake (called when slashed below the minimum)
func (k Keeper) LegacyForceValidatorUnstake(ctx sdk.Ctx, validator types.Validator) sdk.Error {
k.ClearSessionCache()
// delete the validator from staking set as they are unstaked
switch validator.Status {
case sdk.Staked:
k.deleteValidatorFromStakingSet(ctx, validator)
k.deleteValidatorForChains(ctx, validator)
// don't delete validator to allow for previous power to be properly updated
case sdk.Unstaking:
k.deleteUnstakingValidator(ctx, validator)
k.DeleteValidator(ctx, validator.Address)
default:
k.DeleteValidator(ctx, validator.Address)
return sdk.ErrInternal("should not happen: trying to force unstake an already unstaked validator: " + validator.Address.String())
}
// amount unstaked = stakedTokens
err := k.burnStakedTokens(ctx, validator.StakedTokens)
if err != nil {
return err
}
if validator.IsStaked() {
// remove their tokens from the field
validator, er := validator.RemoveStakedTokens(validator.StakedTokens)
if er != nil {
return sdk.ErrInternal(er.Error())
}
// update their status to unstaked
validator = validator.UpdateStatus(sdk.Unstaked)
// set the validator in store
k.SetValidator(ctx, validator)
}
ctx.Logger().Info("Force Unstaked validator " + validator.Address.String())
// create the event
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypeUnstake,
sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory),
sdk.NewAttribute(sdk.AttributeKeySender, validator.Address.String()),
),
sdk.NewEvent(
sdk.EventTypeMessage,
sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory),
sdk.NewAttribute(sdk.AttributeKeySender, validator.Address.String()),
),
})
return nil
}
// ForceValidatorUnstake - Coerce unstake (called when slashed below the minimum)
func (k Keeper) ForceValidatorUnstake(ctx sdk.Ctx, validator types.Validator) sdk.Error {
k.ClearSessionCache()
// send validator to jail || if already jailed, do nothing
k.JailValidator(ctx, validator.Address)
ctx.Logger().Info("Sent Validator to Jail for falling below minimum stake" + validator.Address.String())
k.SetWaitingValidator(ctx, validator)
ctx.Logger().Info("Validator is waiting to begin unstaking" + validator.Address.String())
ctx.Logger().Info("" + validator.Address.String())
// create the event
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypeBeginUnstake,
sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory),
sdk.NewAttribute(sdk.AttributeKeySender, validator.Address.String()),
),
sdk.NewEvent(
sdk.EventTypeMessage,
sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory),
sdk.NewAttribute(sdk.AttributeKeySender, validator.Address.String()),
),
})
return nil
}
// JailValidator - Send a validator to jail
func (k Keeper) JailValidator(ctx sdk.Ctx, addr sdk.Address) {
validator, found := k.GetValidator(ctx, addr)
if !found {
ctx.Logger().Error(fmt.Errorf("cannot find jailed validator: %v at height: %d\n", addr, ctx.BlockHeight()).Error())
return
}
if validator.Jailed {
ctx.Logger().Debug(fmt.Errorf("cannot jail already jailed validator, validator: %v a height: %d\n", validator, ctx.BlockHeight()).Error())
return
}
if validator.IsUnstaked() {
ctx.Logger().Info(fmt.Errorf("cannot jail an unstaked validator, likely left in the set to update Tendermint Val Set: %v\n", validator).Error())
return
}
// clear caching for sesssions
k.ClearSessionCache()
k.deleteValidatorFromStakingSet(ctx, validator)
validator.Jailed = true
k.SetValidator(ctx, validator)
logger := k.Logger(ctx)
logger.Debug(fmt.Sprintf("validator %s jailed", addr))
ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypeJail,
sdk.NewAttribute(types.AttributeKeyAddress, addr.String()),
sdk.NewAttribute(types.AttributeKeyReason, types.AttributeValueMissingSignature),
),
)
}
func (k Keeper) IncrementJailedValidators(ctx sdk.Ctx) {
store := ctx.KVStore(k.storeKey)
iterator, _ := sdk.KVStorePrefixIterator(store, types.AllValidatorsKey)
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
val, err := k.UnmarshalValidator(ctx, iterator.Value())
if err != nil {
ctx.Logger().Error("could not unmarshal validator in IncrementJailedValidators: ", err.Error())
continue
}
if val.IsJailed() {
addr := val.Address
signInfo, found := k.GetValidatorSigningInfo(ctx, addr)
if !found {
k.Logger(ctx).Error("could not find validator signing info in increment jail validator")
signInfo = types.ValidatorSigningInfo{
Address: addr,
StartHeight: ctx.BlockHeight(),
}
}
// increase JailedBlockCounter
signInfo.JailedBlocksCounter++
// compare against MaxJailedBlocks
if signInfo.JailedBlocksCounter > k.MaxJailedBlocks(ctx) {
if k.Cdc.IsAfterNonCustodialUpgrade(ctx.BlockHeight()) {
err := k.ForceValidatorUnstake(ctx, val)
if err != nil {
k.Logger(ctx).Error("could not force unstake in simpleSlash: " + err.Error() + "\nfor validator " + addr.String())
return
}
} else {
err := k.LegacyForceValidatorUnstake(ctx, val)
if err != nil {
k.Logger(ctx).Error("could not force unstake in simpleSlash: " + err.Error() + "\nfor validator " + addr.String())
return
}
k.DeleteValidator(ctx, addr)
}
} else {
k.SetValidatorSigningInfo(ctx, addr, signInfo)
}
}
}
}
// ValidateUnjailMessage - Check unjail message
func (k Keeper) ValidateUnjailMessage(ctx sdk.Ctx, msg types.MsgUnjail) (addr sdk.Address, err sdk.Error) {
validator, found := k.GetValidator(ctx, msg.ValidatorAddr)
if !found {
return nil, types.ErrNoValidatorForAddress(k.Codespace())
}
//Check msg Signature
err, valid := ValidateValidatorMsgSigner(validator, msg.Signer, k)
if !valid {
return nil, err
}
// cannot be unjailed if no self-delegation exists
selfDel := validator.GetTokens()
if selfDel == sdk.ZeroInt() {
return nil, types.ErrMissingSelfDelegation(k.Codespace())
}
if validator.GetTokens().LT(sdk.NewInt(k.MinimumStake(ctx))) {
if k.Cdc.IsAfterNonCustodialUpgrade(ctx.BlockHeight()) {
k.SetWaitingValidator(ctx, validator) // defensive against 'stuck in jail'
}
return nil, types.ErrSelfDelegationTooLowToUnjail(k.Codespace())
}
// cannot be unjailed if not jailed
if !validator.IsJailed() {
return nil, types.ErrValidatorNotJailed(k.Codespace())
}
addr = validator.GetAddress()
info, found := k.GetValidatorSigningInfo(ctx, addr)
if !found {
return nil, types.ErrNoValidatorForAddress(k.Codespace())
}
if info.JailedUntil.After(time.Now()) {
return nil, types.ErrValidatorJailed(k.Codespace())
}
// cannot be unjailed until out of jail
if ctx.BlockHeader().Time.Before(info.JailedUntil) {
return nil, types.ErrValidatorJailed(k.Codespace())
}
return
}
// UnjailValidator - Remove a validator from jail
func (k Keeper) UnjailValidator(ctx sdk.Ctx, addr sdk.Address) {
validator, found := k.GetValidator(ctx, addr)
if !found {
ctx.Logger().Error(fmt.Errorf("cannot unjail validator, validator not found: %v at height %d\n", addr, ctx.BlockHeight()).Error())
return
}
if !validator.Jailed {
k.Logger(ctx).Error(fmt.Sprintf("cannot unjail already unjailed validator, validator: %v at height %d\n", validator, ctx.BlockHeight()))
return
}
// On and after this upgrade height, we start clearing the global session
// cache every time a node is unjailed to prevent any non-deterministic cache
// consistency issues. We have been doing the same in other events such as
// editstake, unstake, and jail. See #1529 for more details.
if k.Cdc.IsAfterNamedFeatureActivationHeight(
ctx.BlockHeight(),
codec.ClearUnjailedValSessionKey,
) {
k.PocketKeeper.ClearSessionCache()
}
validator.Jailed = false
k.SetValidator(ctx, validator)
k.ResetValidatorSigningInfo(ctx, addr)
k.Logger(ctx).Info(fmt.Sprintf("validator %s unjailed", addr))
}