-
Notifications
You must be signed in to change notification settings - Fork 0
/
staking.go
656 lines (579 loc) · 20.8 KB
/
staking.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
package fch
import (
"context"
"fmt"
"math/big"
"sync"
"github.com/ethereum/go-ethereum/common"
"github.com/Timestopeofficial/feechain/block"
"github.com/Timestopeofficial/feechain/consensus/quorum"
"github.com/Timestopeofficial/feechain/core/rawdb"
"github.com/Timestopeofficial/feechain/core/types"
"github.com/Timestopeofficial/feechain/eth/rpc"
"github.com/Timestopeofficial/feechain/internal/chain"
internalCommon "github.com/Timestopeofficial/feechain/internal/common"
"github.com/Timestopeofficial/feechain/numeric"
commonRPC "github.com/Timestopeofficial/feechain/rpc/common"
"github.com/Timestopeofficial/feechain/shard"
"github.com/Timestopeofficial/feechain/shard/committee"
"github.com/Timestopeofficial/feechain/staking/availability"
"github.com/Timestopeofficial/feechain/staking/effective"
staking "github.com/Timestopeofficial/feechain/staking/types"
"github.com/pkg/errors"
)
var (
zero = numeric.ZeroDec()
bigZero = big.NewInt(0)
)
func (fch *Feechain) readAndUpdateRawStakes(
epoch *big.Int,
decider quorum.Decider,
comm shard.Committee,
rawStakes []effective.SlotPurchase,
validatorSpreads map[common.Address]numeric.Dec,
) []effective.SlotPurchase {
for i := range comm.Slots {
slot := comm.Slots[i]
slotAddr := slot.EcdsaAddress
slotKey := slot.BLSPublicKey
spread, ok := validatorSpreads[slotAddr]
if !ok {
snapshot, err := fch.BlockChain.ReadValidatorSnapshotAtEpoch(epoch, slotAddr)
if err != nil {
continue
}
wrapper := snapshot.Validator
spread = numeric.NewDecFromBigInt(wrapper.TotalDelegation()).
QuoInt64(int64(len(wrapper.SlotPubKeys)))
validatorSpreads[slotAddr] = spread
}
commonRPC.SetRawStake(decider, slotKey, spread)
// add entry to array for median calculation
rawStakes = append(rawStakes, effective.SlotPurchase{
Addr: slotAddr,
Key: slotKey,
RawStake: spread,
EPoSStake: spread,
})
}
return rawStakes
}
func (fch *Feechain) getSuperCommittees() (*quorum.Transition, error) {
nowE := fch.BlockChain.CurrentHeader().Epoch()
if fch.BlockChain.CurrentHeader().IsLastBlockInEpoch() {
// current epoch is current header epoch + 1 if the header was last block of prev epoch
nowE = new(big.Int).Add(nowE, common.Big1)
}
thenE := new(big.Int).Sub(nowE, common.Big1)
var (
nowCommittee, prevCommittee *shard.State
err error
)
nowCommittee, err = fch.BlockChain.ReadShardState(nowE)
if err != nil {
return nil, err
}
prevCommittee, err = fch.BlockChain.ReadShardState(thenE)
if err != nil {
return nil, err
}
stakedSlotsNow, stakedSlotsThen :=
shard.ExternalSlotsAvailableForEpoch(nowE),
shard.ExternalSlotsAvailableForEpoch(thenE)
then, now :=
quorum.NewRegistry(stakedSlotsThen, int(thenE.Int64())),
quorum.NewRegistry(stakedSlotsNow, int(nowE.Int64()))
rawStakes := []effective.SlotPurchase{}
validatorSpreads := map[common.Address]numeric.Dec{}
for _, comm := range prevCommittee.Shards {
decider := quorum.NewDecider(quorum.SuperMajorityStake, comm.ShardID)
// before staking skip computing
if fch.BlockChain.Config().IsStaking(prevCommittee.Epoch) {
if _, err := decider.SetVoters(&comm, prevCommittee.Epoch); err != nil {
return nil, err
}
}
rawStakes = fch.readAndUpdateRawStakes(thenE, decider, comm, rawStakes, validatorSpreads)
then.Deciders[fmt.Sprintf("shard-%d", comm.ShardID)] = decider
}
then.MedianStake = effective.Median(rawStakes)
rawStakes = []effective.SlotPurchase{}
validatorSpreads = map[common.Address]numeric.Dec{}
for _, comm := range nowCommittee.Shards {
decider := quorum.NewDecider(quorum.SuperMajorityStake, comm.ShardID)
if _, err := decider.SetVoters(&comm, nowCommittee.Epoch); err != nil {
return nil, errors.Wrapf(
err,
"committee is only available from staking epoch: %v, current epoch: %v",
fch.BlockChain.Config().StakingEpoch,
fch.BlockChain.CurrentHeader().Epoch(),
)
}
rawStakes = fch.readAndUpdateRawStakes(nowE, decider, comm, rawStakes, validatorSpreads)
now.Deciders[fmt.Sprintf("shard-%d", comm.ShardID)] = decider
}
now.MedianStake = effective.Median(rawStakes)
return &quorum.Transition{Previous: then, Current: now}, nil
}
// IsStakingEpoch ...
func (fch *Feechain) IsStakingEpoch(epoch *big.Int) bool {
return fch.BlockChain.Config().IsStaking(epoch)
}
// IsPreStakingEpoch ...
// func (fch *Feechain) IsPreStakingEpoch(epoch *big.Int) bool {
// return fch.BlockChain.Config().IsPreStaking(epoch)
// }
// IsNoEarlyUnlockEpoch ...
// func (fch *Feechain) IsNoEarlyUnlockEpoch(epoch *big.Int) bool {
// return fch.BlockChain.Config().IsNoEarlyUnlock(epoch)
// }
// IsCommitteeSelectionBlock checks if the given block is the committee selection block
func (fch *Feechain) IsCommitteeSelectionBlock(header *block.Header) bool {
return chain.IsCommitteeSelectionBlock(fch.BlockChain, header)
}
// GetDelegationLockingPeriodInEpoch ...
func (fch *Feechain) GetDelegationLockingPeriodInEpoch(epoch *big.Int) int {
return chain.GetLockPeriodInEpoch(fch.BlockChain, epoch)
}
// SendStakingTx adds a staking transaction
func (fch *Feechain) SendStakingTx(ctx context.Context, signedStakingTx *staking.StakingTransaction) error {
stx, _, _, _ := rawdb.ReadStakingTransaction(fch.chainDb, signedStakingTx.Hash())
if stx == nil {
return fch.NodeAPI.AddPendingStakingTransaction(signedStakingTx)
}
return ErrFinalizedTransaction
}
// GetStakingTransactionsHistory returns list of staking transactions hashes of address.
func (fch *Feechain) GetStakingTransactionsHistory(address, txType, order string) ([]common.Hash, error) {
return fch.NodeAPI.GetStakingTransactionsHistory(address, txType, order)
}
// GetStakingTransactionsCount returns the number of staking transactions of address.
func (fch *Feechain) GetStakingTransactionsCount(address, txType string) (uint64, error) {
return fch.NodeAPI.GetStakingTransactionsCount(address, txType)
}
// GetSuperCommittees ..
func (fch *Feechain) GetSuperCommittees() (*quorum.Transition, error) {
nowE := fch.BlockChain.CurrentHeader().Epoch()
key := fmt.Sprintf("sc-%s", nowE.String())
res, err := fch.SingleFlightRequest(
key, func() (interface{}, error) {
thenE := new(big.Int).Sub(nowE, common.Big1)
thenKey := fmt.Sprintf("sc-%s", thenE.String())
fch.group.Forget(thenKey)
return fch.getSuperCommittees()
})
if err != nil {
return nil, err
}
return res.(*quorum.Transition), err
}
// GetValidators returns validators for a particular epoch.
func (fch *Feechain) GetValidators(epoch *big.Int) (*shard.Committee, error) {
state, err := fch.BlockChain.ReadShardState(epoch)
if err != nil {
return nil, err
}
for _, cmt := range state.Shards {
if cmt.ShardID == fch.ShardID {
return &cmt, nil
}
}
return nil, nil
}
// GetValidatorSelfDelegation returns the amount of staking after applying all delegated stakes
func (fch *Feechain) GetValidatorSelfDelegation(addr common.Address) *big.Int {
wrapper, err := fch.BlockChain.ReadValidatorInformation(addr)
if err != nil || wrapper == nil {
return nil
}
if len(wrapper.Delegations) == 0 {
return nil
}
return wrapper.Delegations[0].Amount
}
// GetElectedValidatorAddresses returns the address of elected validators for current epoch
func (fch *Feechain) GetElectedValidatorAddresses() []common.Address {
list, _ := fch.BlockChain.ReadShardState(fch.BlockChain.CurrentBlock().Epoch())
return list.StakedValidators().Addrs
}
// GetAllValidatorAddresses returns the up to date validator candidates for next epoch
func (fch *Feechain) GetAllValidatorAddresses() []common.Address {
return fch.BlockChain.ValidatorCandidates()
}
var (
epochBlocksMap = map[common.Address]map[uint64]staking.EpochSigningEntry{}
mapLock = sync.Mutex{}
)
func (fch *Feechain) getEpochSigning(epoch *big.Int, addr common.Address) (staking.EpochSigningEntry, error) {
entry := staking.EpochSigningEntry{}
mapLock.Lock()
defer mapLock.Unlock()
if validatorMap, ok := epochBlocksMap[addr]; ok {
if val, ok := validatorMap[epoch.Uint64()]; ok {
return val, nil
}
}
snapshot, err := fch.BlockChain.ReadValidatorSnapshotAtEpoch(epoch, addr)
if err != nil {
return entry, err
}
// the signing information is for the previous epoch
prevEpoch := big.NewInt(0).Sub(epoch, common.Big1)
entry.Epoch = prevEpoch
entry.Blocks = snapshot.Validator.Counters
// subtract previous epoch counters if exists
prevEpochSnap, err := fch.BlockChain.ReadValidatorSnapshotAtEpoch(prevEpoch, addr)
if err == nil {
entry.Blocks.NumBlocksSigned.Sub(
entry.Blocks.NumBlocksSigned,
prevEpochSnap.Validator.Counters.NumBlocksSigned,
)
entry.Blocks.NumBlocksToSign.Sub(
entry.Blocks.NumBlocksToSign,
prevEpochSnap.Validator.Counters.NumBlocksToSign,
)
}
// update map when adding new entry, also remove an entry beyond last 30
if _, ok := epochBlocksMap[addr]; !ok {
epochBlocksMap[addr] = map[uint64]staking.EpochSigningEntry{}
}
epochBlocksMap[addr][epoch.Uint64()] = entry
epochMinus30 := big.NewInt(0).Sub(epoch, big.NewInt(staking.SigningHistoryLength))
delete(epochBlocksMap[addr], epochMinus30.Uint64())
return entry, nil
}
// GetValidatorInformation returns the information of validator
func (fch *Feechain) GetValidatorInformation(
addr common.Address, block *types.Block,
) (*staking.ValidatorRPCEnhanced, error) {
bc := fch.BlockChain
wrapper, err := bc.ReadValidatorInformationAtRoot(addr, block.Root())
if err != nil {
s, _ := internalCommon.AddressToBech32(addr)
return nil, errors.Wrapf(err, "not found address in current state %s", s)
}
now := block.Epoch()
// At the last block of epoch, block epoch is e while val.LastEpochInCommittee
// is already updated to e+1. So need the >= check rather than ==
inCommittee := wrapper.LastEpochInCommittee.Cmp(now) >= 0
defaultReply := &staking.ValidatorRPCEnhanced{
CurrentlyInCommittee: inCommittee,
Wrapper: *wrapper,
Performance: nil,
ComputedMetrics: nil,
TotalDelegated: wrapper.TotalDelegation(),
EPoSStatus: effective.ValidatorStatus(
inCommittee, wrapper.Status,
).String(),
EPoSWinningStake: nil,
BootedStatus: nil,
ActiveStatus: wrapper.Validator.Status.String(),
Lifetime: &staking.AccumulatedOverLifetime{
BlockReward: wrapper.BlockReward,
Signing: wrapper.Counters,
APR: zero,
},
}
snapshot, err := bc.ReadValidatorSnapshotAtEpoch(
now, addr,
)
if err != nil {
return defaultReply, nil
}
computed := availability.ComputeCurrentSigning(
snapshot.Validator, wrapper,
)
lastBlockOfEpoch := shard.Schedule.EpochLastBlock(fch.BeaconChain.CurrentBlock().Header().Epoch().Uint64())
computed.BlocksLeftInEpoch = lastBlockOfEpoch - fch.BeaconChain.CurrentBlock().Header().Number().Uint64()
if defaultReply.CurrentlyInCommittee {
defaultReply.Performance = &staking.CurrentEpochPerformance{
CurrentSigningPercentage: *computed,
}
}
stats, err := bc.ReadValidatorStats(addr)
if err != nil {
// when validator has no stats, default boot-status to not booted
notBooted := effective.NotBooted.String()
defaultReply.BootedStatus = ¬Booted
return defaultReply, nil
}
latestAPR := numeric.ZeroDec()
l := len(stats.APRs)
if l > 0 {
latestAPR = stats.APRs[l-1].Value
}
defaultReply.Lifetime.APR = latestAPR
defaultReply.Lifetime.EpochAPRs = stats.APRs
// average apr cache keys
// key := fmt.Sprintf("apr-%s-%d", addr.Hex(), now.Uint64())
// prevKey := fmt.Sprintf("apr-%s-%d", addr.Hex(), now.Uint64()-1)
// delete entry for previous epoch
// b.apiCache.Forget(prevKey)
// calculate last APRHistoryLength epochs for averaging APR
// epochFrom := bc.GasPriceConfig().StakingEpoch
// nowMinus := big.NewInt(0).Sub(now, big.NewInt(staking.APRHistoryLength))
// if nowMinus.Cmp(epochFrom) > 0 {
// epochFrom = nowMinus
// }
// if len(stats.APRs) > 0 && stats.APRs[0].Epoch.Cmp(epochFrom) > 0 {
// epochFrom = stats.APRs[0].Epoch
// }
// epochToAPRs := map[int64]numeric.Dec{}
// for i := 0; i < len(stats.APRs); i++ {
// entry := stats.APRs[i]
// epochToAPRs[entry.Epoch.Int64()] = entry.Value
// }
// at this point, validator is active and has apr's for the recent 100 epochs
// compute average apr over history
// if avgAPR, err := b.SingleFlightRequest(
// key, func() (interface{}, error) {
// total := numeric.ZeroDec()
// count := 0
// for i := epochFrom.Int64(); i < now.Int64(); i++ {
// if apr, ok := epochToAPRs[i]; ok {
// total = total.Add(apr)
// }
// count++
// }
// if count == 0 {
// return nil, errors.New("no apr snapshots available")
// }
// return total.QuoInt64(int64(count)), nil
// },
// ); err != nil {
// // could not compute average apr from snapshot
// // assign the latest apr available from stats
// defaultReply.Lifetime.APR = numeric.ZeroDec()
// } else {
// defaultReply.Lifetime.APR = avgAPR.(numeric.Dec)
// }
epochBlocks := []staking.EpochSigningEntry{}
epochFrom := bc.Config().StakingEpoch
nowMinus := big.NewInt(0).Sub(now, big.NewInt(staking.SigningHistoryLength))
if nowMinus.Cmp(epochFrom) > 0 {
epochFrom = nowMinus
}
for i := now.Int64(); i > epochFrom.Int64(); i-- {
epoch := big.NewInt(i)
entry, err := fch.getEpochSigning(epoch, addr)
if err != nil {
break
}
epochBlocks = append(epochBlocks, entry)
}
defaultReply.Lifetime.EpochBlocks = epochBlocks
if defaultReply.CurrentlyInCommittee {
defaultReply.ComputedMetrics = stats
defaultReply.EPoSWinningStake = &stats.TotalEffectiveStake
}
if !defaultReply.CurrentlyInCommittee {
reason := stats.BootedStatus.String()
defaultReply.BootedStatus = &reason
}
return defaultReply, nil
}
// GetMedianRawStakeSnapshot ..
func (fch *Feechain) GetMedianRawStakeSnapshot() (
*committee.CompletedEPoSRound, error,
) {
blockNum := fch.CurrentBlock().NumberU64()
key := fmt.Sprintf("median-%d", blockNum)
// delete cache for previous block
prevKey := fmt.Sprintf("median-%d", blockNum-1)
fch.group.Forget(prevKey)
res, err := fch.SingleFlightRequest(
key,
func() (interface{}, error) {
// Compute for next epoch
epoch := big.NewInt(0).Add(fch.CurrentBlock().Epoch(), big.NewInt(1))
return committee.NewEPoSRound(epoch, fch.BlockChain, true)
// return committee.NewEPoSRound(epoch, fch.BlockChain, fch.BlockChain.Config().IsEPoSBound35(epoch))
},
)
if err != nil {
return nil, err
}
return res.(*committee.CompletedEPoSRound), nil
}
// GetDelegationsByValidator returns all delegation information of a validator
func (fch *Feechain) GetDelegationsByValidator(validator common.Address) []*staking.Delegation {
wrapper, err := fch.BlockChain.ReadValidatorInformation(validator)
if err != nil || wrapper == nil {
return nil
}
delegations := []*staking.Delegation{}
for i := range wrapper.Delegations {
delegations = append(delegations, &wrapper.Delegations[i])
}
return delegations
}
// GetDelegationsByValidatorAtBlock returns all delegation information of a validator at the given block
func (fch *Feechain) GetDelegationsByValidatorAtBlock(
validator common.Address, block *types.Block,
) []*staking.Delegation {
wrapper, err := fch.BlockChain.ReadValidatorInformationAtRoot(validator, block.Root())
if err != nil || wrapper == nil {
return nil
}
delegations := []*staking.Delegation{}
for i := range wrapper.Delegations {
delegations = append(delegations, &wrapper.Delegations[i])
}
return delegations
}
// GetDelegationsByDelegator returns all delegation information of a delegator
func (fch *Feechain) GetDelegationsByDelegator(
delegator common.Address,
) ([]common.Address, []*staking.Delegation) {
block := fch.BlockChain.CurrentBlock()
return fch.GetDelegationsByDelegatorByBlock(delegator, block)
}
// GetDelegationsByDelegatorByBlock returns all delegation information of a delegator
func (fch *Feechain) GetDelegationsByDelegatorByBlock(
delegator common.Address, block *types.Block,
) ([]common.Address, []*staking.Delegation) {
addresses := []common.Address{}
delegations := []*staking.Delegation{}
delegationIndexes, err := fch.BlockChain.
ReadDelegationsByDelegatorAt(delegator, block.Number())
if err != nil {
return nil, nil
}
for i := range delegationIndexes {
wrapper, err := fch.BlockChain.ReadValidatorInformationAtRoot(
delegationIndexes[i].ValidatorAddress, block.Root(),
)
if err != nil || wrapper == nil {
return nil, nil
}
if uint64(len(wrapper.Delegations)) > delegationIndexes[i].Index {
delegations = append(delegations, &wrapper.Delegations[delegationIndexes[i].Index])
} else {
delegations = append(delegations, nil)
}
addresses = append(addresses, delegationIndexes[i].ValidatorAddress)
}
return addresses, delegations
}
// UndelegationPayouts ..
type UndelegationPayouts struct {
Data map[common.Address]map[common.Address]*big.Int
}
func NewUndelegationPayouts() *UndelegationPayouts {
return &UndelegationPayouts{
Data: make(map[common.Address]map[common.Address]*big.Int),
}
}
func (u *UndelegationPayouts) SetPayoutByDelegatorAddrAndValidatorAddr(
delegator, validator common.Address, amount *big.Int,
) {
if u.Data[delegator] == nil {
u.Data[delegator] = make(map[common.Address]*big.Int)
}
if totalPayout, ok := u.Data[delegator][validator]; ok {
u.Data[delegator][validator] = new(big.Int).Add(totalPayout, amount)
} else {
u.Data[delegator][validator] = amount
}
}
// GetUndelegationPayouts returns the undelegation payouts for each delegator
//
// Due to in-memory caching, it is possible to get undelegation payouts for a state / epoch
// that has been pruned but have it be lost (and unable to recompute) after the node restarts.
// This not a problem if a full (archival) DB is used.
func (fch *Feechain) GetUndelegationPayouts(
ctx context.Context, epoch *big.Int,
) (*UndelegationPayouts, error) {
// if !fch.IsPreStakingEpoch(epoch) {
// return nil, fmt.Errorf("not pre-staking epoch or later")
// }
payouts, ok := fch.undelegationPayoutsCache.Get(epoch.Uint64())
if ok {
return payouts.(*UndelegationPayouts), nil
}
undelegationPayouts := NewUndelegationPayouts()
// require second to last block as saved undelegations are AFTER undelegations are payed out
blockNumber := shard.Schedule.EpochLastBlock(epoch.Uint64()) - 1
undelegationPayoutBlock, err := fch.BlockByNumber(ctx, rpc.BlockNumber(blockNumber))
if err != nil || undelegationPayoutBlock == nil {
// Block not found, so no undelegationPayouts (not an error)
return undelegationPayouts, nil
}
lockingPeriod := fch.GetDelegationLockingPeriodInEpoch(undelegationPayoutBlock.Epoch())
for _, validator := range fch.GetAllValidatorAddresses() {
wrapper, err := fch.BlockChain.ReadValidatorInformationAtRoot(validator, undelegationPayoutBlock.Root())
if err != nil || wrapper == nil {
continue // Not a validator at this epoch or unable to fetch validator info because of pruned state.
}
// noEarlyUnlock := fch.IsNoEarlyUnlockEpoch(epoch)
for _, delegation := range wrapper.Delegations {
// withdraw := delegation.RemoveUnlockedUndelegations(epoch, wrapper.LastEpochInCommittee, lockingPeriod, noEarlyUnlock)
withdraw := delegation.RemoveUnlockedUndelegations(epoch, lockingPeriod)
if withdraw.Cmp(bigZero) == 1 {
undelegationPayouts.SetPayoutByDelegatorAddrAndValidatorAddr(validator, delegation.DelegatorAddress, withdraw)
}
}
}
fch.undelegationPayoutsCache.Add(epoch.Uint64(), undelegationPayouts)
return undelegationPayouts, nil
}
// GetTotalStakingSnapshot ..
func (fch *Feechain) GetTotalStakingSnapshot() *big.Int {
if stake := fch.totalStakeCache.pop(fch.CurrentBlock().NumberU64()); stake != nil {
return stake
}
currHeight := fch.CurrentBlock().NumberU64()
candidates := fch.BlockChain.ValidatorCandidates()
if len(candidates) == 0 {
stake := big.NewInt(0)
fch.totalStakeCache.push(currHeight, stake)
return stake
}
stakes := big.NewInt(0)
for i := range candidates {
snapshot, _ := fch.BlockChain.ReadValidatorSnapshot(candidates[i])
validator, _ := fch.BlockChain.ReadValidatorInformation(candidates[i])
if !committee.IsEligibleForEPoSAuction(
snapshot, validator,
) {
continue
}
for i := range validator.Delegations {
stakes.Add(stakes, validator.Delegations[i].Amount)
}
}
fch.totalStakeCache.push(currHeight, stakes)
return stakes
}
// GetCurrentStakingErrorSink ..
func (fch *Feechain) GetCurrentStakingErrorSink() types.TransactionErrorReports {
return fch.NodeAPI.ReportStakingErrorSink()
}
// totalStakeCache ..
type totalStakeCache struct {
sync.Mutex
cachedBlockHeight uint64
stake *big.Int
// duration is in blocks
duration uint64
}
// newTotalStakeCache ..
func newTotalStakeCache(duration uint64) *totalStakeCache {
return &totalStakeCache{
cachedBlockHeight: 0,
stake: nil,
duration: duration,
}
}
func (c *totalStakeCache) push(currBlockHeight uint64, stake *big.Int) {
c.Lock()
defer c.Unlock()
c.cachedBlockHeight = currBlockHeight
c.stake = stake
}
func (c *totalStakeCache) pop(currBlockHeight uint64) *big.Int {
if currBlockHeight > c.cachedBlockHeight+c.duration {
return nil
}
return c.stake
}