/
reward_plugin.go
929 lines (834 loc) · 40.5 KB
/
reward_plugin.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
package plugin
import (
"encoding/json"
"errors"
"fmt"
"math"
"math/big"
"sort"
"sync"
"github.com/PhoenixGlobal/Phoenix-Chain-SDK/pos/gov"
"github.com/PhoenixGlobal/Phoenix-Chain-SDK/libs/common/hexutil"
"github.com/PhoenixGlobal/Phoenix-Chain-SDK/libs/rlp"
"github.com/PhoenixGlobal/Phoenix-Chain-SDK/libs/crypto"
"github.com/PhoenixGlobal/Phoenix-Chain-SDK/ethereum/core/db/snapshotdb"
"github.com/PhoenixGlobal/Phoenix-Chain-SDK/ethereum/p2p/discover"
"github.com/PhoenixGlobal/Phoenix-Chain-SDK/pos/staking"
"github.com/PhoenixGlobal/Phoenix-Chain-SDK/ethereum/core/types"
"github.com/PhoenixGlobal/Phoenix-Chain-SDK/libs/common"
"github.com/PhoenixGlobal/Phoenix-Chain-SDK/libs/common/vm"
"github.com/PhoenixGlobal/Phoenix-Chain-SDK/libs/log"
"github.com/PhoenixGlobal/Phoenix-Chain-SDK/pos/reward"
"github.com/PhoenixGlobal/Phoenix-Chain-SDK/pos/xcom"
"github.com/PhoenixGlobal/Phoenix-Chain-SDK/pos/xutil"
)
type RewardMgrPlugin struct {
db snapshotdb.DB
nodeID discover.NodeID
nodeADD common.NodeAddress
stakingPlugin *StakingPlugin
}
const (
LessThanFoundationYearDeveloperRate = 100
AfterFoundationYearDeveloperRewardRate = 50
AfterFoundationYearFoundRewardRate = 50
RewardPoolIncreaseRate = 80 // 80% of fixed-issued tokens are allocated to reward pool each year
)
var (
rewardOnce sync.Once
rm *RewardMgrPlugin = nil
millisecond = 1000
minutes = 60 * millisecond
)
func RewardMgrInstance() *RewardMgrPlugin {
rewardOnce.Do(func() {
log.Info("Init Reward plugin ...")
sdb := snapshotdb.Instance()
rm = &RewardMgrPlugin{
db: sdb,
stakingPlugin: StakingInstance(),
}
})
return rm
}
// BeginBlock does something like check input params before execute transactions,
// in RewardMgrPlugin it does nothing.
func (rmp *RewardMgrPlugin) BeginBlock(blockHash common.Hash, head *types.Header, state xcom.StateDB) error {
return nil
}
// EndBlock will handle reward work, if it's time to settle, reward staking. Then reward worker
// for create new block, this is necessary. At last if current block is the last block at the end
// of year, increasing issuance.
func (rmp *RewardMgrPlugin) EndBlock(blockHash common.Hash, head *types.Header, state xcom.StateDB) error {
blockNumber := head.Number.Uint64()
packageReward := new(big.Int)
stakingReward := new(big.Int)
var err error
if head.Number.Uint64() == common.Big1.Uint64() {
packageReward, stakingReward, err = rmp.CalcEpochReward(blockHash, head, state)
if nil != err {
log.Error("Execute CalcEpochReward fail", "blockNumber", head.Number.Uint64(), "blockHash", blockHash.TerminalString(), "err", err)
return err
}
} else {
packageReward, err = LoadNewBlockReward(blockHash, rmp.db)
if nil != err {
log.Error("Load NewBlockReward fail", "blockNumber", head.Number.Uint64(), "blockHash", blockHash.TerminalString(), "err", err)
return err
}
stakingReward, err = LoadStakingReward(blockHash, rmp.db)
if nil != err {
log.Error("Load StakingReward fail", "blockNumber", head.Number.Uint64(), "blockHash", blockHash.TerminalString(), "err", err)
return err
}
}
if err := rmp.AllocatePackageBlock(blockHash, head, packageReward, state); err != nil {
return err
}
if xutil.IsEndOfEpoch(blockNumber) {
verifierList, err := rmp.AllocateStakingReward(blockNumber, blockHash, stakingReward, state)
if err != nil {
return err
}
if err := rmp.HandleDelegatePerReward(blockHash, blockNumber, verifierList, state); err != nil {
return err
}
if err := rmp.runIncreaseIssuance(blockHash, head, state); nil != err {
return err
}
if _, _, err := rmp.CalcEpochReward(blockHash, head, state); nil != err {
log.Error("Execute CalcEpochReward fail", "blockNumber", head.Number.Uint64(), "blockHash", blockHash.TerminalString(), "err", err)
return err
}
}
return nil
}
// Confirmed does nothing
func (rmp *RewardMgrPlugin) Confirmed(nodeId discover.NodeID, block *types.Block) error {
return nil
}
func (rmp *RewardMgrPlugin) SetCurrentNodeID(nodeId discover.NodeID) {
rmp.nodeID = nodeId
add, err := xutil.NodeId2Addr(rmp.nodeID)
if err != nil {
panic(err)
}
rmp.nodeADD = add
}
func (rmp *RewardMgrPlugin) isLessThanFoundationYear(thisYear uint32) bool {
if thisYear < xcom.PhoenixChainFoundationYear()-1 {
return true
}
return false
}
func (rmp *RewardMgrPlugin) addPhoenixChainFoundation(state xcom.StateDB, currIssuance *big.Int, allocateRate uint32) {
phoenixchainFoundationIncr := percentageCalculation(currIssuance, uint64(allocateRate))
state.AddBalance(xcom.PhoenixChainFundAccount(), phoenixchainFoundationIncr)
}
func (rmp *RewardMgrPlugin) addCommunityDeveloperFoundation(state xcom.StateDB, currIssuance *big.Int, allocateRate uint32) {
developerFoundationIncr := percentageCalculation(currIssuance, uint64(allocateRate))
state.AddBalance(xcom.CDFAccount(), developerFoundationIncr)
}
func (rmp *RewardMgrPlugin) addRewardPoolIncreaseIssuance(state xcom.StateDB, currIssuance *big.Int, allocateRate uint32) {
rewardpoolIncr := percentageCalculation(currIssuance, uint64(allocateRate))
state.AddBalance(vm.RewardManagerPoolAddr, rewardpoolIncr)
}
// increaseIssuance used for increase issuance at the end of each year
func (rmp *RewardMgrPlugin) increaseIssuance(thisYear, lastYear uint32, state xcom.StateDB, blockNumber uint64, blockHash common.Hash) error {
var currIssuance *big.Int
//issuance increase
{
histIssuance := GetHistoryCumulativeIssue(state, lastYear)
increaseIssuanceRatio, err := gov.GovernIncreaseIssuanceRatio(blockNumber, blockHash)
if nil != err {
log.Error("Failed to increaseIssuance, call GovernIncreaseIssuanceRatio is failed", "blockNumber", blockNumber, "blockHash", blockHash.TerminalString(),
"histIssuance", histIssuance, "err", err)
return err
}
tmp := new(big.Int).Mul(histIssuance, big.NewInt(int64(increaseIssuanceRatio)))
currIssuance = tmp.Div(tmp, big.NewInt(10000))
// Restore the cumulative issue at this year end
histIssuance.Add(histIssuance, currIssuance)
SetYearEndCumulativeIssue(state, thisYear, histIssuance)
log.Debug("Call EndBlock on reward_plugin: increase issuance", "thisYear", thisYear, "addIssuance", currIssuance, "hit", histIssuance)
}
rewardpoolIncr := percentageCalculation(currIssuance, uint64(RewardPoolIncreaseRate))
state.AddBalance(vm.RewardManagerPoolAddr, rewardpoolIncr)
lessBalance := new(big.Int).Sub(currIssuance, rewardpoolIncr)
if rmp.isLessThanFoundationYear(thisYear) {
log.Debug("Call EndBlock on reward_plugin: increase issuance to developer", "thisYear", thisYear, "developBalance", lessBalance)
rmp.addCommunityDeveloperFoundation(state, lessBalance, LessThanFoundationYearDeveloperRate)
} else {
log.Debug("Call EndBlock on reward_plugin: increase issuance to developer and phoenixchain", "thisYear", thisYear, "develop and phoenixchain Balance", lessBalance)
rmp.addCommunityDeveloperFoundation(state, lessBalance, AfterFoundationYearDeveloperRewardRate)
rmp.addPhoenixChainFoundation(state, lessBalance, AfterFoundationYearFoundRewardRate)
}
balance := state.GetBalance(vm.RewardManagerPoolAddr)
SetYearEndBalance(state, thisYear, balance)
return nil
}
// AllocateStakingReward used for reward staking at the settle block
func (rmp *RewardMgrPlugin) AllocateStakingReward(blockNumber uint64, blockHash common.Hash, sreward *big.Int, state xcom.StateDB) ([]*staking.Candidate, error) {
log.Info("Allocate staking reward start", "blockNumber", blockNumber, "hash", blockHash,
"epoch", xutil.CalculateEpoch(blockNumber), "reward", sreward)
verifierList, err := rmp.stakingPlugin.GetVerifierCandidateInfo(blockHash, blockNumber)
if err != nil {
log.Error("Failed to AllocateStakingReward: call GetVerifierList is failed", "blockNumber", blockNumber, "hash", blockHash, "err", err)
return nil, err
}
if err := rmp.rewardStakingByValidatorList(state, verifierList, sreward); err != nil {
log.Error("reward staking by validator list fail", "err", err, "bn", blockNumber, "bh", blockHash)
return nil, err
}
return verifierList, nil
}
func (rmp *RewardMgrPlugin) ReturnDelegateReward(address common.Address, amount *big.Int, state xcom.StateDB) error {
if amount.Cmp(common.Big0) > 0 {
DelegateRewardPool := state.GetBalance(vm.DelegateRewardPoolAddr)
if DelegateRewardPool.Cmp(amount) < 0 {
return fmt.Errorf("DelegateRewardPool balance is not enougth,want %v have %v", amount, DelegateRewardPool)
}
state.SubBalance(vm.DelegateRewardPoolAddr, amount)
state.AddBalance(address, amount)
}
return nil
}
func (rmp *RewardMgrPlugin) HandleDelegatePerReward(blockHash common.Hash, blockNumber uint64, list []*staking.Candidate, state xcom.StateDB) error {
currentEpoch := xutil.CalculateEpoch(blockNumber)
for _, verifier := range list {
if verifier.CurrentEpochDelegateReward.Cmp(common.Big0) == 0 {
continue
}
if verifier.DelegateTotal.Cmp(common.Big0) == 0 {
log.Debug("handleDelegatePerReward return delegateReward", "epoch", currentEpoch, "reward", verifier.CurrentEpochDelegateReward, "add", verifier.BenefitAddress)
if err := rmp.ReturnDelegateReward(verifier.BenefitAddress, verifier.CurrentEpochDelegateReward, state); err != nil {
log.Error("HandleDelegatePerReward ReturnDelegateReward fail", "err", err, "blockNumber", blockNumber)
}
} else {
per := reward.NewDelegateRewardPer(currentEpoch, verifier.CurrentEpochDelegateReward, verifier.DelegateTotal)
if err := AppendDelegateRewardPer(blockHash, verifier.NodeId, verifier.StakingBlockNum, per, rmp.db); err != nil {
log.Error("call handleDelegatePerReward fail AppendDelegateRewardPer", "blockNumber", blockNumber, "blockHash", blockHash.TerminalString(),
"nodeId", verifier.NodeId.TerminalString(), "err", err, "CurrentEpochDelegateReward", verifier.CurrentEpochDelegateReward, "delegateTotal", verifier.DelegateTotal)
return err
}
currentEpochDelegateReward := new(big.Int).Set(verifier.CurrentEpochDelegateReward)
verifier.PrepareNextEpoch()
canAddr, err := xutil.NodeId2Addr(verifier.NodeId)
if nil != err {
log.Error("Failed to handleDelegatePerReward on rewardMgrPlugin: nodeId parse addr failed",
"blockNumber", blockNumber, "blockHash", blockHash, "nodeID", verifier.NodeId.String(), "err", err)
return err
}
if err := rmp.stakingPlugin.db.SetCanMutableStore(blockHash, canAddr, verifier.CandidateMutable); err != nil {
log.Error("Failed to handleDelegatePerReward on rewardMgrPlugin: setCanMutableStore failed",
"blockNumber", blockNumber, "blockHash", blockHash, "err", err, "mutable", verifier.CandidateMutable)
return err
}
log.Debug("handleDelegatePerReward add newDelegateRewardPer", "blockNum", blockNumber, "node_id", verifier.NodeId.TerminalString(), "stakingNum", verifier.StakingBlockNum,
"cu_epoch_delegate_reward", currentEpochDelegateReward, "total_delegate_reward", verifier.DelegateRewardTotal, "total_delegate", verifier.DelegateTotal,
"epoch", currentEpoch)
}
}
return nil
}
func (rmp *RewardMgrPlugin) WithdrawDelegateReward(blockHash common.Hash, blockNum uint64, account common.Address, list []*DelegationInfoWithRewardPerList, state xcom.StateDB) ([]reward.NodeDelegateReward, error) {
log.Debug("Call withdraw delegate reward: begin", "account", account, "list", list, "blockNum", blockNum, "blockHash", blockHash, "epoch", xutil.CalculateEpoch(blockNum))
rewards := make([]reward.NodeDelegateReward, 0)
if len(list) == 0 {
return rewards, nil
}
currentEpoch := xutil.CalculateEpoch(blockNum)
receiveReward := new(big.Int)
for _, delWithPer := range list {
rewardsReceive := calcDelegateIncome(currentEpoch, delWithPer.DelegationInfo.Delegation, delWithPer.RewardPerList)
rewards = append(rewards, reward.NodeDelegateReward{
NodeID: delWithPer.DelegationInfo.NodeID,
StakingNum: delWithPer.DelegationInfo.StakeBlockNumber,
Reward: new(big.Int).Set(delWithPer.DelegationInfo.Delegation.CumulativeIncome),
})
if len(rewardsReceive) != 0 {
if err := UpdateDelegateRewardPer(blockHash, delWithPer.DelegationInfo.NodeID, delWithPer.DelegationInfo.StakeBlockNumber, rewardsReceive, rmp.db); err != nil {
log.Error("call WithdrawDelegateReward UpdateDelegateRewardPer fail", "err", err)
return nil, err
}
}
// Execute new logic after this version.
// Update the delegation information only when there is delegation income available.
if delWithPer.DelegationInfo.Delegation.CumulativeIncome.Cmp(common.Big0) > 0 {
receiveReward.Add(receiveReward, delWithPer.DelegationInfo.Delegation.CumulativeIncome)
delWithPer.DelegationInfo.Delegation.CleanCumulativeIncome(uint32(currentEpoch))
if err := rmp.stakingPlugin.db.SetDelegateStore(blockHash, account, delWithPer.DelegationInfo.NodeID, delWithPer.DelegationInfo.StakeBlockNumber, delWithPer.DelegationInfo.Delegation); err != nil {
return nil, err
}
}
log.Debug("WithdrawDelegateReward rewardsReceive", "rewardsReceive", rewardsReceive, "blockNum", blockNum)
}
if receiveReward.Cmp(common.Big0) > 0 {
if err := rmp.ReturnDelegateReward(account, receiveReward, state); err != nil {
log.Error("Call withdraw delegate reward ReturnDelegateReward fail", "err", err, "blockNum", blockNum)
return nil, common.InternalError
}
}
log.Debug("Call withdraw delegate reward: end", "account", account, "rewards", rewards, "blockNum", blockNum, "blockHash", blockHash, "receiveReward", receiveReward)
return rewards, nil
}
func (rmp *RewardMgrPlugin) GetDelegateReward(blockHash common.Hash, blockNum uint64, account common.Address, nodes []discover.NodeID, state xcom.StateDB) ([]reward.NodeDelegateRewardPresenter, error) {
log.Debug("Call RewardMgrPlugin: query delegate reward result begin", "account", account, "nodes", nodes, "num", blockNum)
dls, err := rmp.stakingPlugin.db.GetDelegatesInfo(blockHash, account)
if err != nil {
log.Error("Call GetDelegateReward GetDelegatesInfo fail", "err", err, "account", account)
return nil, err
}
if len(dls) == 0 {
return nil, reward.ErrDelegationNotFound
}
if len(nodes) > 0 {
nodeMap := make(map[discover.NodeID]struct{})
for _, node := range nodes {
nodeMap[node] = struct{}{}
}
for i := 0; i < len(dls); {
if _, ok := nodeMap[dls[i].NodeID]; !ok {
dls = append(dls[:i], dls[i+1:]...)
} else {
i++
}
}
if len(dls) == 0 {
return nil, reward.ErrDelegationNotFound
}
} else {
if len(dls) > int(xcom.TheNumberOfDelegationsReward()) {
sort.Sort(staking.DelByDelegateEpoch(dls))
}
}
currentEpoch := xutil.CalculateEpoch(blockNum)
delegationInfoWithRewardPerList := make([]*DelegationInfoWithRewardPerList, 0)
for _, stakingNode := range dls {
delegateRewardPerList, err := rmp.GetDelegateRewardPerList(blockHash, stakingNode.NodeID, stakingNode.StakeBlockNumber, uint64(stakingNode.Delegation.DelegateEpoch), currentEpoch-1)
if err != nil {
log.Error("Call GetDelegateReward GetDelegateRewardPerList fail", "err", err, "account", account)
return nil, err
}
delegationInfoWithRewardPerList = append(delegationInfoWithRewardPerList, NewDelegationInfoWithRewardPerList(stakingNode, delegateRewardPerList))
}
rewards := make([]reward.NodeDelegateRewardPresenter, 0)
for _, delWithPer := range delegationInfoWithRewardPerList {
calcDelegateIncome(currentEpoch, delWithPer.DelegationInfo.Delegation, delWithPer.RewardPerList)
rewards = append(rewards, reward.NodeDelegateRewardPresenter{
NodeID: delWithPer.DelegationInfo.NodeID,
StakingNum: delWithPer.DelegationInfo.StakeBlockNumber,
Reward: (*hexutil.Big)(new(big.Int).Set(delWithPer.DelegationInfo.Delegation.CumulativeIncome)),
})
}
log.Debug("Call RewardMgrPlugin: query delegate reward result end", "num", blockNum, "account", account, "nodes", nodes, "rewards", rewards, "perList", delegationInfoWithRewardPerList)
return rewards, nil
}
func (rmp *RewardMgrPlugin) CalDelegateRewardAndNodeReward(totalReward *big.Int, per uint16) (*big.Int, *big.Int) {
tmp := new(big.Int).Mul(totalReward, big.NewInt(int64(per)))
tmp.Div(tmp, big.NewInt(10000))
return tmp, new(big.Int).Sub(totalReward, tmp)
}
func (rmp *RewardMgrPlugin) rewardStakingByValidatorList(state xcom.StateDB, list []*staking.Candidate, reward *big.Int) error {
validatorNum := int64(len(list))
everyValidatorReward := new(big.Int).Div(reward, big.NewInt(validatorNum))
log.Debug("calculate validator staking reward", "validator length", validatorNum, "everyOneReward", everyValidatorReward)
totalValidatorReward, totalValidatorDelegateReward := new(big.Int), new(big.Int)
for _, value := range list {
delegateReward, stakingReward := new(big.Int), new(big.Int).Set(everyValidatorReward)
if value.ShouldGiveDelegateReward() {
delegateReward, stakingReward = rmp.CalDelegateRewardAndNodeReward(everyValidatorReward, value.RewardPer)
totalValidatorDelegateReward.Add(totalValidatorDelegateReward, delegateReward)
log.Debug("allocate delegate reward of staking one-by-one", "nodeId", value.NodeId.TerminalString(), "staking reward", stakingReward, "per", value.RewardPer, "delegateReward", delegateReward)
//the CurrentEpochDelegateReward will use by cal delegate reward Per
value.CurrentEpochDelegateReward.Add(value.CurrentEpochDelegateReward, delegateReward)
}
if value.BenefitAddress != vm.RewardManagerPoolAddr {
log.Debug("allocate staking reward one-by-one", "nodeId", value.NodeId.String(),
"benefitAddress", value.BenefitAddress.String(), "staking reward", stakingReward)
state.AddBalance(value.BenefitAddress, stakingReward)
totalValidatorReward.Add(totalValidatorReward, stakingReward)
}
}
state.AddBalance(vm.DelegateRewardPoolAddr, totalValidatorDelegateReward)
state.SubBalance(vm.RewardManagerPoolAddr, new(big.Int).Add(totalValidatorDelegateReward, totalValidatorReward))
return nil
}
func (rmp *RewardMgrPlugin) getBlockMinderAddress(blockHash common.Hash, head *types.Header) (discover.NodeID, common.NodeAddress, error) {
if blockHash == common.ZeroHash {
return rmp.nodeID, rmp.nodeADD, nil
}
pk := head.CachePublicKey()
if pk == nil {
return discover.ZeroNodeID, common.ZeroNodeAddr, errors.New("failed to get the public key of the block producer")
}
return discover.PubkeyID(pk), crypto.PubkeyToNodeAddress(*pk), nil
}
// AllocatePackageBlock used for reward new block. it returns coinbase and error
func (rmp *RewardMgrPlugin) AllocatePackageBlock(blockHash common.Hash, head *types.Header, reward *big.Int, state xcom.StateDB) error {
nodeID, add, err := rmp.getBlockMinderAddress(blockHash, head)
if err != nil {
log.Error("AllocatePackageBlock getBlockMinderAddress fail", "err", err, "blockNumber", head.Number, "blockHash", blockHash)
return err
}
currVerifier, err := rmp.stakingPlugin.IsCurrVerifier(blockHash, head.Number.Uint64(), nodeID, false)
if err != nil {
log.Error("AllocatePackageBlock IsCurrVerifier fail", "err", err, "blockNumber", head.Number, "blockHash", blockHash)
return err
}
if currVerifier {
cm, err := rmp.stakingPlugin.GetCanMutable(blockHash, add)
if err != nil {
log.Error("AllocatePackageBlock GetCanMutable fail", "err", err, "blockNumber", head.Number, "blockHash", blockHash, "add", add)
return err
}
if cm.ShouldGiveDelegateReward() {
delegateReward := new(big.Int).SetUint64(0)
delegateReward, reward = rmp.CalDelegateRewardAndNodeReward(reward, cm.RewardPer)
state.SubBalance(vm.RewardManagerPoolAddr, delegateReward)
state.AddBalance(vm.DelegateRewardPoolAddr, delegateReward)
cm.CurrentEpochDelegateReward.Add(cm.CurrentEpochDelegateReward, delegateReward)
log.Debug("allocate package reward, delegate reward", "blockNumber", head.Number, "blockHash", blockHash, "delegateReward", delegateReward, "epochDelegateReward", cm.CurrentEpochDelegateReward)
if err := rmp.stakingPlugin.db.SetCanMutableStore(blockHash, add, cm); err != nil {
log.Error("AllocatePackageBlock SetCanMutableStore fail", "err", err, "blockNumber", head.Number, "blockHash", blockHash)
return err
}
}
}
if head.Coinbase != vm.RewardManagerPoolAddr {
log.Debug("allocate package reward,block reward", "blockNumber", head.Number, "blockHash", blockHash,
"coinBase", head.Coinbase.String(), "reward", reward)
state.SubBalance(vm.RewardManagerPoolAddr, reward)
state.AddBalance(head.Coinbase, reward)
}
return nil
}
type DelegationInfoWithRewardPerList struct {
DelegationInfo *staking.DelegationInfo
RewardPerList []*reward.DelegateRewardPer
}
func (d *DelegationInfoWithRewardPerList) String() string {
v, err := json.Marshal(d)
if err != nil {
panic(err)
}
return string(v)
}
func NewDelegationInfoWithRewardPerList(delegationInfo *staking.DelegationInfo, rewardPerList []*reward.DelegateRewardPer) *DelegationInfoWithRewardPerList {
return &DelegationInfoWithRewardPerList{delegationInfo, rewardPerList}
}
func (rmp *RewardMgrPlugin) GetDelegateRewardPerList(blockHash common.Hash, nodeID discover.NodeID, stakingNum, fromEpoch, toEpoch uint64) ([]*reward.DelegateRewardPer, error) {
return getDelegateRewardPerList(blockHash, nodeID, stakingNum, fromEpoch, toEpoch, rmp.db)
}
func getDelegateRewardPerList(blockHash common.Hash, nodeID discover.NodeID, stakingNum, fromEpoch, toEpoch uint64, db snapshotdb.DB) ([]*reward.DelegateRewardPer, error) {
keys := reward.DelegateRewardPerKeys(nodeID, stakingNum, fromEpoch, toEpoch)
pers := make([]*reward.DelegateRewardPer, 0)
for _, key := range keys {
val, err := db.Get(blockHash, key)
if err != nil {
if err == snapshotdb.ErrNotFound {
continue
}
return nil, err
}
list := new(reward.DelegateRewardPerList)
if err := rlp.DecodeBytes(val, list); err != nil {
return nil, err
}
for _, per := range list.Pers {
if per.Epoch >= fromEpoch && per.Epoch <= toEpoch {
pers = append(pers, per)
}
}
}
return pers, nil
}
func AppendDelegateRewardPer(blockHash common.Hash, nodeID discover.NodeID, stakingNum uint64, per *reward.DelegateRewardPer, db snapshotdb.DB) error {
key := reward.DelegateRewardPerKey(nodeID, stakingNum, per.Epoch)
list := reward.NewDelegateRewardPerList()
val, err := db.Get(blockHash, key)
if err != nil {
if err != snapshotdb.ErrNotFound {
return err
}
} else {
if err := rlp.DecodeBytes(val, list); err != nil {
return err
}
}
list.AppendDelegateRewardPer(per)
v, err := rlp.EncodeToBytes(list)
if err != nil {
return err
}
if err := db.Put(blockHash, key, v); err != nil {
return err
}
log.Debug("append delegate rewardPer", "nodeID", nodeID.TerminalString(), "stkNum", stakingNum, "per", per)
return nil
}
func UpdateDelegateRewardPer(blockHash common.Hash, nodeID discover.NodeID, stakingNum uint64, receives []reward.DelegateRewardReceipt, db snapshotdb.DB) error {
if len(receives) == 0 {
return nil
}
keys := reward.DelegateRewardPerKeys(nodeID, stakingNum, receives[0].Epoch, receives[len(receives)-1].Epoch)
var reIndex int
for _, key := range keys {
val, err := db.Get(blockHash, key)
if err != nil {
if err == snapshotdb.ErrNotFound {
continue
}
return err
}
list := new(reward.DelegateRewardPerList)
if err := rlp.DecodeBytes(val, list); err != nil {
return err
}
if len(receives)-reIndex < reward.DelegateRewardPerLength {
reIndex += list.DecreaseTotalAmount(receives[reIndex:])
} else {
reIndex += list.DecreaseTotalAmount(receives[reIndex : reIndex+reward.DelegateRewardPerLength])
}
if list.IsChange() {
log.Debug("update delegate reward per list", "nodeID", nodeID.TerminalString(), "stkNum", stakingNum, "list", list)
if list.ShouldDel() {
if err := db.Del(blockHash, key); err != nil {
return err
}
} else {
v, err := rlp.EncodeToBytes(list)
if err != nil {
return err
}
if err := db.Put(blockHash, key, v); err != nil {
return err
}
}
}
}
return nil
}
// Calculation percentage , input 100,10 cal: 100*10/100 = 10
func percentageCalculation(mount *big.Int, rate uint64) *big.Int {
ratio := new(big.Int).Mul(mount, big.NewInt(int64(rate)))
return new(big.Int).Div(ratio, common.Big100)
}
// SetYearEndCumulativeIssue used for set historical cumulative increase at the end of the year
func SetYearEndCumulativeIssue(state xcom.StateDB, year uint32, total *big.Int) {
yearEndIncreaseKey := reward.GetHistoryIncreaseKey(year)
state.SetState(vm.RewardManagerPoolAddr, yearEndIncreaseKey, total.Bytes())
}
// GetHistoryCumulativeIssue used for get the cumulative issuance of a certain year in history
func GetHistoryCumulativeIssue(state xcom.StateDB, year uint32) *big.Int {
var issue = new(big.Int)
histIncreaseKey := reward.GetHistoryIncreaseKey(year)
bIssue := state.GetState(vm.RewardManagerPoolAddr, histIncreaseKey)
log.Trace("show history cumulative issue", "lastYear", year, "amount", issue.SetBytes(bIssue))
return issue.SetBytes(bIssue)
}
func SetYearEndBalance(state xcom.StateDB, year uint32, balance *big.Int) {
yearEndBalanceKey := reward.HistoryBalancePrefix(year)
state.SetState(vm.RewardManagerPoolAddr, yearEndBalanceKey, balance.Bytes())
}
func GetYearEndBalance(state xcom.StateDB, year uint32) *big.Int {
var balance = new(big.Int)
yearEndBalanceKey := reward.HistoryBalancePrefix(year)
bBalance := state.GetState(vm.RewardManagerPoolAddr, yearEndBalanceKey)
log.Trace("show balance of reward pool at last year end", "lastYear", year, "amount", balance.SetBytes(bBalance))
return balance.SetBytes(bBalance)
}
func (rmp *RewardMgrPlugin) runIncreaseIssuance(blockHash common.Hash, head *types.Header, state xcom.StateDB) error {
yes, err := xcom.IsYearEnd(blockHash, head.Number.Uint64())
if nil != err {
log.Error("Failed to execute runIncreaseIssuance function", "currentBlockNumber", head.Number, "currentBlockHash", blockHash.TerminalString(), "err", err)
return err
}
if yes {
yearNumber, err := LoadChainYearNumber(blockHash, rmp.db)
if nil != err {
return err
}
yearNumber++
if err := StorageChainYearNumber(blockHash, rmp.db, yearNumber); nil != err {
log.Error("Failed to execute runIncreaseIssuance function", "currentBlockNumber", head.Number, "currentBlockHash", blockHash.TerminalString(), "err", err)
return err
}
incIssuanceTime, err := xcom.LoadIncIssuanceTime(blockHash, rmp.db)
if nil != err {
return err
}
if err := rmp.increaseIssuance(yearNumber, yearNumber-1, state, head.Number.Uint64(), blockHash); nil != err {
return err
}
// After the increase issue is completed, update the number of rewards to be issued
if err := StorageRemainingReward(blockHash, rmp.db, GetYearEndBalance(state, yearNumber)); nil != err {
log.Error("Failed to execute runIncreaseIssuance function", "currentBlockNumber", head.Number, "currentBlockHash", blockHash.TerminalString(), "err", err)
return err
}
if err := xcom.StorageIncIssuanceTime(blockHash, rmp.db, incIssuanceTime+int64(xcom.AdditionalCycleTime()*uint64(minutes))); nil != err {
log.Error("storage incIssuanceTime fail", "currentBlockNumber", head.Number, "currentBlockHash", blockHash.TerminalString(), "err", err)
return err
}
remainReward, err := LoadRemainingReward(blockHash, rmp.db)
if nil != err {
return err
}
incIssuanceTime, err = xcom.LoadIncIssuanceTime(blockHash, rmp.db)
if nil != err {
return err
}
log.Info("Call CalcEpochReward, increaseIssuance successful", "currBlockNumber", head.Number, "currBlockHash", blockHash, "currBlockTime", head.Time,
"yearNumber", yearNumber, "incIssuanceTime", incIssuanceTime, "yearEndBalance", GetYearEndBalance(state, yearNumber), "remainingReward", remainReward)
}
return nil
}
func (rmp *RewardMgrPlugin) CalcEpochReward(blockHash common.Hash, head *types.Header, state xcom.StateDB) (*big.Int, *big.Int, error) {
remainReward, err := LoadRemainingReward(blockHash, rmp.db)
if nil != err {
log.Error("Failed to execute CalcEpochReward function", "currentBlockNumber", head.Number, "currentBlockHash", blockHash.TerminalString(), "err", err)
return nil, nil, err
}
yearStartBlockNumber, yearStartTime, err := LoadYearStartTime(blockHash, rmp.db)
if nil != err {
log.Error("Failed to execute CalcEpochReward function", "currentBlockNumber", head.Number, "currentBlockHash", blockHash.TerminalString(), "err", err)
return nil, nil, err
}
incIssuanceTime, err := xcom.LoadIncIssuanceTime(blockHash, rmp.db)
if nil != err {
log.Error("load incIssuanceTime fail", "currentBlockNumber", head.Number, "currentBlockHash", blockHash.TerminalString(), "err", err)
return nil, nil, err
}
if yearStartTime == 0 {
yearStartBlockNumber = head.Number.Uint64()
yearStartTime = int64(head.Time)
incIssuanceTime = yearStartTime + int64(xcom.FirstAdditionalCycleTime()*uint64(minutes))
if err := xcom.StorageIncIssuanceTime(blockHash, rmp.db, incIssuanceTime); nil != err {
log.Error("storage incIssuanceTime fail", "currentBlockNumber", head.Number, "currentBlockHash", blockHash.TerminalString(), "err", err)
return nil, nil, err
}
if err := StorageYearStartTime(blockHash, rmp.db, yearStartBlockNumber, yearStartTime); nil != err {
log.Error("Storage year start time and block height failed", "currentBlockNumber", head.Number, "currentBlockHash", blockHash.TerminalString(), "err", err)
return nil, nil, err
}
remainReward = GetYearEndBalance(state, 0)
log.Info("Call CalcEpochReward, First calculation", "currBlockNumber", head.Number, "currBlockHash", blockHash, "currBlockTime", head.Time,
"yearStartBlockNumber", yearStartBlockNumber, "yearStartTime", yearStartTime, "incIssuanceTime", incIssuanceTime, "remainReward", remainReward)
}
yearNumber, err := LoadChainYearNumber(blockHash, rmp.db)
if nil != err {
log.Error("Failed to execute CalcEpochReward function", "currentBlockNumber", head.Number, "currentBlockHash", blockHash.TerminalString(), "err", err)
return nil, nil, err
}
// When the first issuance is completed
// Each settlement cycle needs to update the year start time,
// which is used to calculate the average annual block production rate
epochBlocks := xutil.CalcBlocksEachEpoch()
if yearNumber > 0 {
incIssuanceNumber, err := xcom.LoadIncIssuanceNumber(blockHash, rmp.db)
if nil != err {
return nil, nil, err
}
addition := true
if yearStartBlockNumber == 1 {
if head.Number.Uint64() <= incIssuanceNumber {
addition = false
}
}
if addition {
if yearStartBlockNumber == 1 {
yearStartBlockNumber += epochBlocks - 1
} else {
yearStartBlockNumber += epochBlocks
}
yearStartTime = int64(snapshotdb.GetDBBlockChain().GetHeaderByNumber(yearStartBlockNumber).Time)
if err := StorageYearStartTime(blockHash, rmp.db, yearStartBlockNumber, yearStartTime); nil != err {
log.Error("Storage year start time and block height failed", "currentBlockNumber", head.Number, "currentBlockHash", blockHash.TerminalString(), "err", err)
return nil, nil, err
}
log.Debug("Call CalcEpochReward, Adjust the sampling range of the block time", "currBlockNumber", head.Number, "currBlockHash", blockHash, "currBlockTime", head.Time,
"epochBlocks", epochBlocks, "yearNumber", yearNumber, "yearStartBlockNumber", yearStartBlockNumber, "yearStartTime", yearStartTime)
}
}
// First calculation, calculated according to the default block interval.
// In each subsequent settlement cycle, an average block generation interval needs to be calculated.
avgPackTime := xcom.Interval() * uint64(millisecond)
if head.Number.Uint64() > yearStartBlockNumber {
diffNumber := head.Number.Uint64() - yearStartBlockNumber
diffTime := int64(head.Time) - yearStartTime
avgPackTime = uint64(diffTime) / diffNumber
log.Debug("Call CalcEpochReward, Calculate the average block production time in the previous year", "currBlockNumber", head.Number, "currBlockHash", blockHash,
"currBlockTime", head.Time, "yearStartBlockNumber", yearStartBlockNumber, "yearStartTime", yearStartTime, "diffNumber", diffNumber, "diffTime", diffTime,
"avgPackTime", avgPackTime)
}
if err := xcom.StorageAvgPackTime(blockHash, rmp.db, avgPackTime); nil != err {
log.Error("Failed to execute StorageAvgPackTime function", "currentBlockNumber", head.Number, "currentBlockHash", blockHash.TerminalString(), "avgPackTime", avgPackTime, "err", err)
return nil, nil, err
}
epochTotalReward := new(big.Int)
// If the expected increase issue time is exceeded,
// the increase issue time will be postponed for one settlement cycle,
// and the remaining rewards will all be issued in the next settlement cycle
remainEpoch := 1
if int64(head.Time) >= incIssuanceTime {
epochTotalReward.Add(epochTotalReward, remainReward)
remainReward = new(big.Int)
log.Info("Call CalcEpochReward, The current time has exceeded the expected additional issue time", "currBlockNumber", head.Number, "currBlockHash", blockHash,
"currBlockTime", head.Time, "incIssuanceTime", incIssuanceTime, "epochTotalReward", epochTotalReward)
} else {
remainTime := incIssuanceTime - int64(head.Time)
remainBlocks := math.Ceil(float64(remainTime) / float64(avgPackTime))
if remainBlocks > float64(epochBlocks) {
remainEpoch = int(math.Ceil(remainBlocks / float64(epochBlocks)))
}
epochTotalReward = new(big.Int).Div(remainReward, new(big.Int).SetInt64(int64(remainEpoch)))
// Subtract the total reward for the next cycle to calculate the remaining rewards to be issued
remainReward = remainReward.Sub(remainReward, epochTotalReward)
log.Debug("Call CalcEpochReward, Calculation of rewards for the next settlement cycle", "currBlockNumber", head.Number, "currBlockHash", blockHash,
"currBlockTime", head.Time, "incIssuanceTime", incIssuanceTime, "remainTime", remainTime, "remainBlocks", remainBlocks, "epochBlocks", epochBlocks,
"remainEpoch", remainEpoch, "remainReward", remainReward, "epochTotalReward", epochTotalReward)
}
// If the last settlement cycle is left, record the increaseIssuance block height
if remainEpoch == 1 {
incIssuanceNumber := new(big.Int).Add(head.Number, new(big.Int).SetUint64(epochBlocks)).Uint64()
if err := xcom.StorageIncIssuanceNumber(blockHash, rmp.db, incIssuanceNumber); nil != err {
return nil, nil, err
}
log.Info("Call CalcEpochReward, IncIssuanceNumber stored successfully", "currBlockNumber", head.Number, "currBlockHash", blockHash,
"epochBlocks", epochBlocks, "incIssuanceNumber", incIssuanceNumber)
}
// Get the total block reward and staking reward for each settlement cycle
epochTotalNewBlockReward := percentageCalculation(epochTotalReward, xcom.NewBlockRewardRate())
epochTotalStakingReward := new(big.Int).Sub(epochTotalReward, epochTotalNewBlockReward)
if err := StorageRemainingReward(blockHash, rmp.db, remainReward); nil != err {
log.Error("Failed to execute CalcEpochReward function", "currentBlockNumber", head.Number, "currentBlockHash", blockHash.TerminalString(), "err", err)
return nil, nil, err
}
newBlockReward := new(big.Int).Div(epochTotalNewBlockReward, new(big.Int).SetInt64(int64(epochBlocks)))
if err := StorageNewBlockReward(blockHash, rmp.db, newBlockReward); nil != err {
log.Error("Failed to execute CalcEpochReward function", "currentBlockNumber", head.Number, "currentBlockHash", blockHash.TerminalString(), "err", err)
return nil, nil, err
}
if err := StorageStakingReward(blockHash, rmp.db, epochTotalStakingReward); nil != err {
log.Error("Failed to execute CalcEpochReward function", "currentBlockNumber", head.Number, "currentBlockHash", blockHash.TerminalString(), "err", err)
return nil, nil, err
}
log.Debug("Call CalcEpochReward, Cycle reward", "currBlockNumber", head.Number, "currBlockHash", blockHash, "currBlockTime", head.Time,
"epochTotalReward", epochTotalReward, "newBlockRewardRate", xcom.NewBlockRewardRate(), "epochTotalNewBlockReward", epochTotalNewBlockReward,
"epochTotalStakingReward", epochTotalStakingReward, "epochBlocks", epochBlocks, "newBlockReward", newBlockReward)
return newBlockReward, epochTotalStakingReward, nil
}
func StorageYearStartTime(hash common.Hash, snapshotDB snapshotdb.DB, blockNumber uint64, yearStartTime int64) error {
if blockNumber > 0 {
if err := snapshotDB.Put(hash, reward.YearStartBlockNumberKey, common.Uint64ToBytes(blockNumber)); nil != err {
log.Error("Failed to execute StorageYearStartEndTime function", "hash", hash.TerminalString(), "key", string(reward.YearStartBlockNumberKey),
"value", blockNumber, "err", err)
return err
}
}
if yearStartTime > 0 {
if err := snapshotDB.Put(hash, reward.YearStartTimeKey, common.Int64ToBytes(yearStartTime)); nil != err {
log.Error("Failed to execute StorageYearStartEndTime function", "hash", hash.TerminalString(), "key", string(reward.YearStartTimeKey),
"value", yearStartTime, "err", err)
return err
}
}
return nil
}
func LoadYearStartTime(hash common.Hash, snapshotDB snapshotdb.DB) (yearStartBlockNumber uint64, yearStartTime int64, error error) {
yearStartBlockNumberByte, err := snapshotDB.Get(hash, reward.YearStartBlockNumberKey)
if nil != err {
if err != snapshotdb.ErrNotFound {
log.Error("Failed to execute LoadYearStartEndTime function", "hash", hash.TerminalString(), "key", string(reward.YearStartBlockNumberKey), "err", err)
return 0, 0, err
} else {
yearStartBlockNumber = 0
}
} else {
yearStartBlockNumber = common.BytesToUint64(yearStartBlockNumberByte)
}
yearStartTimeByte, err := snapshotDB.Get(hash, reward.YearStartTimeKey)
if nil != err {
if err != snapshotdb.ErrNotFound {
log.Error("Failed to execute LoadYearStartEndTime function", "hash", hash.TerminalString(), "key", string(reward.YearStartTimeKey), "err", err)
return 0, 0, err
} else {
yearStartTime = 0
}
} else {
yearStartTime = common.BytesToInt64(yearStartTimeByte)
}
return
}
func StorageRemainingReward(hash common.Hash, snapshotDB snapshotdb.DB, remainReward *big.Int) error {
if err := snapshotDB.Put(hash, reward.RemainingRewardKey, remainReward.Bytes()); nil != err {
log.Error("Failed to execute StorageRemainingReward function", "hash", hash.TerminalString(), "remainReward", remainReward, "err", err)
return err
}
return nil
}
func LoadRemainingReward(hash common.Hash, snapshotDB snapshotdb.DB) (*big.Int, error) {
remainRewardByte, err := snapshotDB.Get(hash, reward.RemainingRewardKey)
if nil != err {
if err != snapshotdb.ErrNotFound {
log.Error("Failed to execute LoadRemainingReward function", "hash", hash.TerminalString(), "key", string(reward.RemainingRewardKey), "err", err)
return nil, err
}
}
return new(big.Int).SetBytes(remainRewardByte), nil
}
func StorageNewBlockReward(hash common.Hash, snapshotDB snapshotdb.DB, newBlockReward *big.Int) error {
if err := snapshotDB.Put(hash, reward.NewBlockRewardKey, newBlockReward.Bytes()); nil != err {
log.Error("Failed to execute StorageNewBlockReward function", "hash", hash.TerminalString(), "newBlockReward", newBlockReward, "err", err)
return err
}
return nil
}
func LoadNewBlockReward(hash common.Hash, snapshotDB snapshotdb.DB) (*big.Int, error) {
newBlockRewardByte, err := snapshotDB.Get(hash, reward.NewBlockRewardKey)
if nil != err {
if err == snapshotdb.ErrNotFound {
return new(big.Int).SetUint64(0), nil
}
log.Error("Failed to execute LoadRemainingReward function", "hash", hash.TerminalString(), "key", string(reward.NewBlockRewardKey), "err", err)
return nil, err
}
return new(big.Int).SetBytes(newBlockRewardByte), nil
}
func StorageStakingReward(hash common.Hash, snapshotDB snapshotdb.DB, stakingReward *big.Int) error {
if err := snapshotDB.Put(hash, reward.StakingRewardKey, stakingReward.Bytes()); nil != err {
log.Error("Failed to execute StorageStakingReward function", "hash", hash.TerminalString(), "stakingReward", stakingReward, "err", err)
return err
}
return nil
}
func LoadStakingReward(hash common.Hash, snapshotDB snapshotdb.DB) (*big.Int, error) {
stakingRewardByte, err := snapshotDB.Get(hash, reward.StakingRewardKey)
if nil != err {
if err == snapshotdb.ErrNotFound {
return new(big.Int).SetUint64(0), nil
}
log.Error("Failed to execute LoadStakingReward function", "hash", hash.TerminalString(), "key", string(reward.StakingRewardKey), "err", err)
return nil, err
}
return new(big.Int).SetBytes(stakingRewardByte), nil
}
func StorageChainYearNumber(hash common.Hash, snapshotDB snapshotdb.DB, yearNumber uint32) error {
if err := snapshotDB.Put(hash, reward.ChainYearNumberKey, common.Uint32ToBytes(yearNumber)); nil != err {
log.Error("Failed to execute StorageChainYearNumber function", "hash", hash.TerminalString(), "yearNumber", yearNumber, "err", err)
return err
}
return nil
}
func LoadChainYearNumber(hash common.Hash, snapshotDB snapshotdb.DB) (uint32, error) {
chainYearNumberByte, err := snapshotDB.Get(hash, reward.ChainYearNumberKey)
if nil != err {
if err == snapshotdb.ErrNotFound {
log.Info("Data obtained for the first year", "hash", hash.TerminalString())
return 0, nil
}
log.Error("Failed to execute LoadChainYearNumber function", "hash", hash.TerminalString(), "key", string(reward.ChainYearNumberKey), "err", err)
return 0, err
}
return common.BytesToUint32(chainYearNumberByte), nil
}