-
Notifications
You must be signed in to change notification settings - Fork 139
/
Copy pathdistribution.go
1160 lines (1004 loc) · 45.7 KB
/
distribution.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package integration
import (
"strings"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"cosmossdk.io/math"
distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
transfertypes "github.com/cosmos/ibc-go/v8/modules/apps/transfer/types"
clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types"
channeltypes "github.com/cosmos/ibc-go/v8/modules/core/04-channel/types"
sdk "github.com/cosmos/cosmos-sdk/types"
icstestingutils "github.com/cosmos/interchain-security/v5/testutil/integration"
consumerkeeper "github.com/cosmos/interchain-security/v5/x/ccv/consumer/keeper"
consumertypes "github.com/cosmos/interchain-security/v5/x/ccv/consumer/types"
providerkeeper "github.com/cosmos/interchain-security/v5/x/ccv/provider/keeper"
providertypes "github.com/cosmos/interchain-security/v5/x/ccv/provider/types"
ccv "github.com/cosmos/interchain-security/v5/x/ccv/types"
)
// This test is valid for minimal viable consumer chain
func (s *CCVTestSuite) TestRewardsDistribution() {
// set up channel and delegate some tokens in order for validator set update to be sent to the consumer chain
s.SetupCCVChannel(s.path)
s.SetupTransferChannel()
bondAmt := math.NewInt(10000000)
delAddr := s.providerChain.SenderAccount.GetAddress()
delegate(s, delAddr, bondAmt)
s.nextEpoch()
// register a consumer reward denom
params := s.consumerApp.GetConsumerKeeper().GetConsumerParams(s.consumerCtx())
params.RewardDenoms = []string{sdk.DefaultBondDenom}
s.consumerApp.GetConsumerKeeper().SetParams(s.consumerCtx(), params)
// relay VSC packets from provider to consumer
relayAllCommittedPackets(s, s.providerChain, s.path, ccv.ProviderPortID, s.path.EndpointB.ChannelID, 1)
// reward for the provider chain will be sent after each 2 blocks
s.consumerApp.GetConsumerKeeper().SetBlocksPerDistributionTransmission(s.consumerCtx(), 2)
s.consumerChain.NextBlock()
consumerAccountKeeper := s.consumerApp.GetTestAccountKeeper()
providerAccountKeeper := s.providerApp.GetTestAccountKeeper()
consumerBankKeeper := s.consumerApp.GetTestBankKeeper()
providerBankKeeper := s.providerApp.GetTestBankKeeper()
providerKeeper := s.providerApp.GetProviderKeeper()
providerDistributionKeeper := s.providerApp.GetTestDistributionKeeper()
// send coins to the fee pool which is used for reward distribution
consumerFeePoolAddr := consumerAccountKeeper.GetModuleAccount(s.consumerCtx(), authtypes.FeeCollectorName).GetAddress()
feePoolTokensOld := consumerBankKeeper.GetAllBalances(s.consumerCtx(), consumerFeePoolAddr)
fees := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(100)))
err := consumerBankKeeper.SendCoinsFromAccountToModule(s.consumerCtx(), s.consumerChain.SenderAccount.GetAddress(), authtypes.FeeCollectorName, fees)
s.Require().NoError(err)
feePoolTokens := consumerBankKeeper.GetAllBalances(s.consumerCtx(), consumerFeePoolAddr)
s.Require().Equal(math.NewInt(100).Add(feePoolTokensOld.AmountOf(sdk.DefaultBondDenom)), feePoolTokens.AmountOf(sdk.DefaultBondDenom))
// calculate the reward for consumer and provider chain. Consumer will receive ConsumerRedistributeFrac, the rest is going to provider
frac, err := math.LegacyNewDecFromStr(s.consumerApp.GetConsumerKeeper().GetConsumerRedistributionFrac(s.consumerCtx()))
s.Require().NoError(err)
consumerExpectedRewards, _ := sdk.NewDecCoinsFromCoins(feePoolTokens...).MulDec(frac).TruncateDecimal()
providerExpectedRewards := feePoolTokens.Sub(consumerExpectedRewards...)
s.consumerChain.NextBlock()
// amount from the fee pool is divided between consumer redistribute address and address reserved for provider chain
feePoolTokens = consumerBankKeeper.GetAllBalances(s.consumerCtx(), consumerFeePoolAddr)
s.Require().Equal(0, len(feePoolTokens))
consumerRedistributeAddr := consumerAccountKeeper.GetModuleAccount(s.consumerCtx(), consumertypes.ConsumerRedistributeName).GetAddress()
consumerTokens := consumerBankKeeper.GetAllBalances(s.consumerCtx(), consumerRedistributeAddr)
s.Require().Equal(consumerExpectedRewards.AmountOf(sdk.DefaultBondDenom), consumerTokens.AmountOf(sdk.DefaultBondDenom))
providerRedistributeAddr := consumerAccountKeeper.GetModuleAccount(s.consumerCtx(), consumertypes.ConsumerToSendToProviderName).GetAddress()
providerTokens := consumerBankKeeper.GetAllBalances(s.consumerCtx(), providerRedistributeAddr)
s.Require().Equal(providerExpectedRewards.AmountOf(sdk.DefaultBondDenom), providerTokens.AmountOf(sdk.DefaultBondDenom))
// send the reward to provider chain after 2 blocks
s.consumerChain.NextBlock()
providerTokens = consumerBankKeeper.GetAllBalances(s.consumerCtx(), providerRedistributeAddr)
s.Require().Equal(0, len(providerTokens))
relayAllCommittedPackets(s, s.consumerChain, s.transferPath, transfertypes.PortID, s.transferPath.EndpointA.ChannelID, 1)
s.providerChain.NextBlock()
// Since consumer reward denom is not yet registered, the coins never get into the fee pool, staying in the ConsumerRewardsPool
rewardPool := providerAccountKeeper.GetModuleAccount(s.providerCtx(), providertypes.ConsumerRewardsPool).GetAddress()
rewardCoins := providerBankKeeper.GetAllBalances(s.providerCtx(), rewardPool)
// Check that the reward pool contains a coin with an IBC denom
rewardsIBCdenom := ""
for _, coin := range rewardCoins {
if strings.HasPrefix(coin.Denom, "ibc") {
rewardsIBCdenom = coin.Denom
}
}
s.Require().NotZero(rewardsIBCdenom)
// Check that the coins got into the ConsumerRewardsPool
providerExpRewardsAmount := providerExpectedRewards.AmountOf(sdk.DefaultBondDenom)
s.Require().Equal(rewardCoins.AmountOf(rewardsIBCdenom), providerExpRewardsAmount)
// Advance a block and check that the coins are still in the ConsumerRewardsPool
s.providerChain.NextBlock()
rewardCoins = providerBankKeeper.GetAllBalances(s.providerCtx(), rewardPool)
s.Require().Equal(rewardCoins.AmountOf(rewardsIBCdenom), providerExpRewardsAmount)
// Set the consumer reward denom. This would be done by a governance proposal in prod.
providerKeeper.SetConsumerRewardDenom(s.providerCtx(), rewardsIBCdenom)
// Refill the consumer fee pool
err = consumerBankKeeper.SendCoinsFromAccountToModule(
s.consumerCtx(),
s.consumerChain.SenderAccount.GetAddress(),
authtypes.FeeCollectorName,
fees,
)
s.Require().NoError(err)
// Pass two blocks
s.consumerChain.NextBlock()
s.consumerChain.NextBlock()
// Save the consumer validators total outstanding rewards on the provider
consumerValsOutstandingRewardsFunc := func(ctx sdk.Context) sdk.DecCoins {
totalRewards := sdk.DecCoins{}
for _, v := range providerKeeper.GetConsumerValSet(ctx, s.consumerChain.ChainID) {
val, err := s.providerApp.GetTestStakingKeeper().GetValidatorByConsAddr(ctx, sdk.ConsAddress(v.ProviderConsAddr))
s.Require().NoError(err)
valAddr, err := sdk.ValAddressFromBech32(val.GetOperator())
s.Require().NoError(err)
valReward, _ := providerDistributionKeeper.GetValidatorOutstandingRewards(ctx, valAddr)
totalRewards = totalRewards.Add(valReward.Rewards...)
}
return totalRewards
}
consuValsRewards := consumerValsOutstandingRewardsFunc(s.providerCtx())
// increase the block height so validators are eligible for consumer rewards (see `IsEligibleForConsumerRewards`)
numberOfBlocksToStartReceivingRewards :=
providerKeeper.GetNumberOfEpochsToStartReceivingRewards(s.providerCtx()) * providerKeeper.GetBlocksPerEpoch(s.providerCtx())
for s.providerCtx().BlockHeight() <= numberOfBlocksToStartReceivingRewards {
s.providerChain.NextBlock()
}
// Transfer rewards from consumer to provider and distribute rewards to
// validators and community pool by calling BeginBlockRD
relayAllCommittedPackets(
s,
s.consumerChain,
s.transferPath,
transfertypes.PortID,
s.transferPath.EndpointA.ChannelID,
1,
)
// Consumer allocations are distributed between the validators and the community pool.
// The decimals resulting from the distribution are expected to remain in the consumer allocations.
rewardsAlloc := providerKeeper.GetConsumerRewardsAllocation(s.providerCtx(), s.consumerChain.ChainID)
remainingAlloc := rewardsAlloc.Rewards.AmountOf(rewardsIBCdenom)
s.Require().True(remainingAlloc.LTE(math.LegacyOneDec()))
// Check that the reward pool still holds the coins from the first transfer
// which were never allocated since they were not whitelisted
// plus the remaining decimals from the second transfer.
rewardCoins = providerBankKeeper.GetAllBalances(s.providerCtx(), rewardPool)
s.Require().Equal(
math.LegacyNewDecFromInt(rewardCoins.AmountOf(rewardsIBCdenom)),
math.LegacyNewDecFromInt(providerExpRewardsAmount).Add(remainingAlloc),
)
// Check that the distribution module account balance is equal to the consumer rewards
consuValsRewardsReceived := consumerValsOutstandingRewardsFunc(s.providerCtx()).Sub(consuValsRewards)
distrAcct := providerDistributionKeeper.GetDistributionAccount(s.providerCtx())
distrAcctBalance := providerBankKeeper.GetAllBalances(s.providerCtx(), distrAcct.GetAddress())
s.Require().Equal(
// ceil the total consumer rewards since the validators allocation use some rounding
consuValsRewardsReceived.AmountOf(rewardsIBCdenom).Ceil(),
math.LegacyNewDecFromInt(distrAcctBalance.AmountOf(rewardsIBCdenom)),
)
}
// TestSendRewardsRetries tests that failed reward transmissions are retried every BlocksPerDistributionTransmission blocks
func (s *CCVTestSuite) TestSendRewardsRetries() {
// TODO: this setup can be consolidated with other tests in the file
// ccv and transmission channels setup
s.SetupCCVChannel(s.path)
s.SetupTransferChannel()
bondAmt := math.NewInt(10000000)
delAddr := s.providerChain.SenderAccount.GetAddress()
delegate(s, delAddr, bondAmt)
s.nextEpoch()
// Register denom on consumer chain
params := s.consumerApp.GetConsumerKeeper().GetConsumerParams(s.consumerCtx())
params.RewardDenoms = []string{sdk.DefaultBondDenom}
s.consumerApp.GetConsumerKeeper().SetParams(s.consumerCtx(), params)
// relay VSC packets from provider to consumer
relayAllCommittedPackets(s, s.providerChain, s.path, ccv.ProviderPortID, s.path.EndpointB.ChannelID, 1)
consumerBankKeeper := s.consumerApp.GetTestBankKeeper()
consumerKeeper := s.consumerApp.GetConsumerKeeper()
// reward for the provider chain will be sent after each 1000 blocks
s.consumerApp.GetConsumerKeeper().SetBlocksPerDistributionTransmission(s.consumerCtx(), 1000)
// fill fee pool
fees := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(100)))
err := consumerBankKeeper.SendCoinsFromAccountToModule(s.consumerCtx(),
s.consumerChain.SenderAccount.GetAddress(), authtypes.FeeCollectorName, fees)
s.Require().NoError(err)
// Corrupt transmission channel, confirm escrow balance is not updated
// when reward dist is attempted, but LTBH is updated
oldEscBalance := s.getEscrowBalance()
oldLbth := consumerKeeper.GetLastTransmissionBlockHeight(s.consumerCtx())
s.corruptTransChannel()
s.prepareRewardDist()
s.consumerChain.NextBlock()
newEscBalance := s.getEscrowBalance()
s.Require().Equal(oldEscBalance, newEscBalance,
"expected escrow balance to NOT BE updated - OLD: %s, NEW: %s", oldEscBalance, newEscBalance)
newLbth := consumerKeeper.GetLastTransmissionBlockHeight(s.consumerCtx())
s.Require().Equal(oldLbth.Height+consumerKeeper.GetBlocksPerDistributionTransmission(s.consumerCtx()), newLbth.Height,
"expected new LTBH to be previous value + blocks per dist transmission")
// Prepare reward distribution again, confirm escrow balance is still not updated, but LTBH is updated
oldEscBalance = s.getEscrowBalance()
oldLbth = consumerKeeper.GetLastTransmissionBlockHeight(s.consumerCtx())
s.prepareRewardDist()
s.consumerChain.NextBlock()
newEscBalance = s.getEscrowBalance()
s.Require().Equal(oldEscBalance, newEscBalance,
"expected escrow balance to NOT BE updated - OLD: %s, NEW: %s", oldEscBalance, newEscBalance)
newLbth = consumerKeeper.GetLastTransmissionBlockHeight(s.consumerCtx())
s.Require().Equal(oldLbth.Height+consumerKeeper.GetBlocksPerDistributionTransmission(s.consumerCtx()), newLbth.Height,
"expected new LTBH to be previous value + blocks per dist transmission")
// Now fix transmission channel, confirm escrow balance is updated upon reward distribution
transChanID := s.consumerApp.GetConsumerKeeper().GetDistributionTransmissionChannel(s.consumerCtx())
tChan, _ := s.consumerApp.GetIBCKeeper().ChannelKeeper.GetChannel(s.consumerCtx(), transfertypes.PortID, transChanID)
tChan.Counterparty.PortId = transfertypes.PortID
s.consumerApp.GetIBCKeeper().ChannelKeeper.SetChannel(s.consumerCtx(), transfertypes.PortID, transChanID, tChan)
oldEscBalance = s.getEscrowBalance()
s.prepareRewardDist()
s.consumerChain.NextBlock()
newEscBalance = s.getEscrowBalance()
s.Require().NotEqual(oldEscBalance, newEscBalance,
"expected escrow balance to BE updated - OLD: %s, NEW: %s", oldEscBalance, newEscBalance)
}
// TestEndBlockRD tests that the last transmission block height (LTBH) is correctly updated after the expected
// number of block have passed. It also checks that the IBC transfer transfer states are discarded if
// the reward distribution to the provider has failed.
//
// Note: this method is effectively a unit test for EndBLockRD(), but is written as an integration test to avoid excessive mocking.
func (s *CCVTestSuite) TestEndBlockRD() {
testCases := []struct {
name string
prepareRewardDist bool
corruptTransChannel bool
expLBThUpdated bool
expEscrowBalanceChanged bool
denomRegistered bool
}{
{
name: "should not update LBTH before blocks per dist trans block are passed",
prepareRewardDist: false,
corruptTransChannel: false,
expLBThUpdated: false,
denomRegistered: true,
expEscrowBalanceChanged: false,
},
{
name: "should update LBTH when blocks per dist trans or more block are passed",
prepareRewardDist: true,
corruptTransChannel: false,
expLBThUpdated: true,
denomRegistered: true,
expEscrowBalanceChanged: true,
},
{
name: "should update LBTH and discard the IBC transfer states when sending rewards to provider fails",
prepareRewardDist: true,
corruptTransChannel: true,
expLBThUpdated: true,
denomRegistered: true,
expEscrowBalanceChanged: false,
},
{
name: "should not change escrow balance when denom is not registered",
prepareRewardDist: true,
corruptTransChannel: false,
expLBThUpdated: true,
denomRegistered: false,
expEscrowBalanceChanged: false,
},
{
name: "should change escrow balance when denom is registered",
prepareRewardDist: true,
corruptTransChannel: false,
expLBThUpdated: true,
denomRegistered: true,
expEscrowBalanceChanged: true,
},
}
for _, tc := range testCases {
s.SetupTest()
// ccv and transmission channels setup
s.SetupCCVChannel(s.path)
s.SetupTransferChannel()
bondAmt := math.NewInt(10000000)
delAddr := s.providerChain.SenderAccount.GetAddress()
delegate(s, delAddr, bondAmt)
s.nextEpoch()
if tc.denomRegistered {
params := s.consumerApp.GetConsumerKeeper().GetConsumerParams(s.consumerCtx())
params.RewardDenoms = []string{sdk.DefaultBondDenom}
s.consumerApp.GetConsumerKeeper().SetParams(s.consumerCtx(), params)
}
// relay VSC packets from provider to consumer
relayAllCommittedPackets(s, s.providerChain, s.path, ccv.ProviderPortID, s.path.EndpointB.ChannelID, 1)
consumerKeeper := s.consumerApp.GetConsumerKeeper()
consumerBankKeeper := s.consumerApp.GetTestBankKeeper()
// reward for the provider chain will be sent after each 1000 blocks
s.consumerApp.GetConsumerKeeper().SetBlocksPerDistributionTransmission(s.consumerCtx(), 1000)
// fill fee pool
fees := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(100)))
err := consumerBankKeeper.SendCoinsFromAccountToModule(s.consumerCtx(),
s.consumerChain.SenderAccount.GetAddress(), authtypes.FeeCollectorName, fees)
s.Require().NoError(err)
oldLbth := consumerKeeper.GetLastTransmissionBlockHeight(s.consumerCtx())
oldEscBalance := s.getEscrowBalance()
if tc.prepareRewardDist {
s.prepareRewardDist()
}
if tc.corruptTransChannel {
s.corruptTransChannel()
}
s.consumerChain.NextBlock()
if tc.expLBThUpdated {
lbth := consumerKeeper.GetLastTransmissionBlockHeight(s.consumerCtx())
// checks that the current LBTH is greater than the old one
s.Require().True(oldLbth.Height < lbth.Height)
// confirm the LBTH was updated during the most recently executed block
s.Require().Equal(s.consumerCtx().BlockHeight()-1, lbth.Height)
}
currentEscrowBalance := s.getEscrowBalance()
if tc.expEscrowBalanceChanged {
// check that the coins present on the escrow account balance are updated
s.Require().NotEqual(currentEscrowBalance, oldEscBalance,
"expected escrow balance to BE updated - OLD: %s, NEW: %s", oldEscBalance, currentEscrowBalance)
} else {
// check that the coins present on the escrow account balance aren't updated
s.Require().Equal(currentEscrowBalance, oldEscBalance,
"expected escrow balance to NOT BE updated - OLD: %s, NEW: %s", oldEscBalance, currentEscrowBalance)
}
}
}
// TestSendRewardsToProvider is effectively a unit test for SendRewardsToProvider(),
// but is written as an integration test to avoid excessive mocking.
func (s *CCVTestSuite) TestSendRewardsToProvider() {
testCases := []struct {
name string
setup func(sdk.Context, *consumerkeeper.Keeper, icstestingutils.TestBankKeeper)
expError bool
tokenTransfers int
}{
{
name: "successful token transfer",
setup: func(ctx sdk.Context, keeper *consumerkeeper.Keeper, bankKeeper icstestingutils.TestBankKeeper) {
s.SetupTransferChannel()
// register a consumer reward denom
params := keeper.GetConsumerParams(ctx)
params.RewardDenoms = []string{sdk.DefaultBondDenom}
keeper.SetParams(ctx, params)
// send coins to the pool which is used for collect reward distributions to be sent to the provider
err := bankKeeper.SendCoinsFromAccountToModule(
ctx,
s.consumerChain.SenderAccount.GetAddress(),
consumertypes.ConsumerToSendToProviderName,
sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(100))),
)
s.Require().NoError(err)
},
expError: false,
tokenTransfers: 1,
},
{
name: "no transfer channel",
setup: func(ctx sdk.Context, keeper *consumerkeeper.Keeper, bankKeeper icstestingutils.TestBankKeeper) {
},
expError: false,
tokenTransfers: 0,
},
{
name: "no reward denom",
setup: func(ctx sdk.Context, keeper *consumerkeeper.Keeper, bankKeeper icstestingutils.TestBankKeeper) {
s.SetupTransferChannel()
},
expError: false,
tokenTransfers: 0,
},
{
name: "reward balance is zero",
setup: func(ctx sdk.Context, keeper *consumerkeeper.Keeper, bankKeeper icstestingutils.TestBankKeeper) {
s.SetupTransferChannel()
// register a consumer reward denom
params := keeper.GetConsumerParams(ctx)
params.RewardDenoms = []string{"uatom"}
keeper.SetParams(ctx, params)
denoms := keeper.AllowedRewardDenoms(ctx)
s.Require().Len(denoms, 1)
},
expError: false,
tokenTransfers: 0,
},
{
name: "no distribution transmission channel",
setup: func(ctx sdk.Context, keeper *consumerkeeper.Keeper, bankKeeper icstestingutils.TestBankKeeper) {
s.SetupTransferChannel()
// register a consumer reward denom
params := keeper.GetConsumerParams(ctx)
params.RewardDenoms = []string{sdk.DefaultBondDenom}
params.DistributionTransmissionChannel = ""
keeper.SetParams(ctx, params)
// send coins to the pool which is used for collect reward distributions to be sent to the provider
err := bankKeeper.SendCoinsFromAccountToModule(
ctx,
s.consumerChain.SenderAccount.GetAddress(),
consumertypes.ConsumerToSendToProviderName,
sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(100))),
)
s.Require().NoError(err)
},
expError: false,
tokenTransfers: 0,
},
{
name: "no recipient address",
setup: func(ctx sdk.Context, keeper *consumerkeeper.Keeper, bankKeeper icstestingutils.TestBankKeeper) {
s.SetupTransferChannel()
// register a consumer reward denom
params := keeper.GetConsumerParams(ctx)
params.RewardDenoms = []string{sdk.DefaultBondDenom}
params.ProviderFeePoolAddrStr = ""
keeper.SetParams(ctx, params)
// send coins to the pool which is used for collect reward distributions to be sent to the provider
err := bankKeeper.SendCoinsFromAccountToModule(
ctx,
s.consumerChain.SenderAccount.GetAddress(),
consumertypes.ConsumerToSendToProviderName,
sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(100))),
)
s.Require().NoError(err)
},
expError: true,
tokenTransfers: 0,
},
}
for _, tc := range testCases {
s.SetupTest()
// ccv channels setup
s.SetupCCVChannel(s.path)
bondAmt := math.NewInt(10000000)
delAddr := s.providerChain.SenderAccount.GetAddress()
delegate(s, delAddr, bondAmt)
s.providerChain.NextBlock()
// customized setup
consumerCtx := s.consumerCtx()
consumerKeeper := s.consumerApp.GetConsumerKeeper()
tc.setup(consumerCtx, &consumerKeeper, s.consumerApp.GetTestBankKeeper())
// call SendRewardsToProvider
err := s.consumerApp.GetConsumerKeeper().SendRewardsToProvider(consumerCtx)
if tc.expError {
s.Require().Error(err)
} else {
s.Require().NoError(err)
}
// check whether the amount of token transfers is as expected
commitments := s.consumerApp.GetIBCKeeper().ChannelKeeper.GetAllPacketCommitmentsAtChannel(
consumerCtx,
transfertypes.PortID,
s.consumerApp.GetConsumerKeeper().GetDistributionTransmissionChannel(consumerCtx),
)
s.Require().Len(commitments, tc.tokenTransfers, "unexpected amount of token transfers; test: %s", tc.name)
}
}
// TestIBCTransferMiddleware tests the logic of the IBC transfer OnRecvPacket callback
func (s *CCVTestSuite) TestIBCTransferMiddleware() {
var (
data transfertypes.FungibleTokenPacketData
packet channeltypes.Packet
getIBCDenom func(string, string) string
)
// set up an arbitrary address that is not the consumer rewards pool address
notConsumerRewardsPoolAddr := s.providerChain.SenderAccount.GetAddress().String()
testCases := []struct {
name string
setup func(sdk.Context, *providerkeeper.Keeper, icstestingutils.TestBankKeeper)
rewardsAllocated bool
expErr bool
}{
{
"invalid IBC packet",
func(sdk.Context, *providerkeeper.Keeper, icstestingutils.TestBankKeeper) {
packet = channeltypes.Packet{}
},
false,
true,
},
{
"IBC packet sender isn't a consumer chain",
func(ctx sdk.Context, keeper *providerkeeper.Keeper, bankKeeper icstestingutils.TestBankKeeper) {
// make the sender consumer chain impossible to identify
packet.DestinationChannel = "CorruptedChannelId"
},
false,
false,
},
{
"IBC Transfer recipient is not the consumer rewards pool address",
func(ctx sdk.Context, keeper *providerkeeper.Keeper, bankKeeper icstestingutils.TestBankKeeper) {
data.Receiver = notConsumerRewardsPoolAddr
packet.Data = data.GetBytes()
},
false,
false,
},
{
"IBC Transfer coin denom isn't registered",
func(ctx sdk.Context, keeper *providerkeeper.Keeper, bankKeeper icstestingutils.TestBankKeeper) {},
false,
false,
},
{
"successful token transfer to empty pool",
func(ctx sdk.Context, keeper *providerkeeper.Keeper, bankKeeper icstestingutils.TestBankKeeper) {
keeper.SetConsumerRewardDenom(
s.providerCtx(),
getIBCDenom(packet.DestinationPort, packet.DestinationChannel),
)
},
true,
false,
},
{
"successful token transfer to filled pool",
func(ctx sdk.Context, keeper *providerkeeper.Keeper, bankKeeper icstestingutils.TestBankKeeper) {
keeper.SetConsumerRewardDenom(
ctx,
getIBCDenom(packet.DestinationPort, packet.DestinationChannel),
)
// fill consumer reward pool
bankKeeper.SendCoinsFromAccountToModule(
ctx,
s.providerChain.SenderAccount.GetAddress(),
providertypes.ConsumerRewardsPool,
sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(100_000))),
)
// update consumer allocation
keeper.SetConsumerRewardsAllocation(
ctx,
s.consumerChain.ChainID,
providertypes.ConsumerRewardsAllocation{
Rewards: sdk.NewDecCoins(sdk.NewDecCoin(sdk.DefaultBondDenom, math.NewInt(100_000))),
},
)
},
true,
false,
},
}
for _, tc := range testCases {
s.Run(tc.name, func() {
s.SetupTest()
s.SetupCCVChannel(s.path)
s.SetupTransferChannel()
providerKeeper := s.providerApp.GetProviderKeeper()
bankKeeper := s.providerApp.GetTestBankKeeper()
amount := math.NewInt(100)
data = transfertypes.NewFungibleTokenPacketData( // can be explicitly changed in setup
sdk.DefaultBondDenom,
amount.String(),
authtypes.NewModuleAddress(consumertypes.ConsumerToSendToProviderName).String(),
providerKeeper.GetConsumerRewardsPoolAddressStr(s.providerCtx()),
"",
)
packet = channeltypes.NewPacket( // can be explicitly changed in setup
data.GetBytes(),
uint64(1),
s.transferPath.EndpointA.ChannelConfig.PortID,
s.transferPath.EndpointA.ChannelID,
s.transferPath.EndpointB.ChannelConfig.PortID,
s.transferPath.EndpointB.ChannelID,
clienttypes.NewHeight(1, 100),
0,
)
providerKeeper.SetConsumerRewardDenom(s.providerCtx(),
transfertypes.GetPrefixedDenom(
packet.DestinationPort,
packet.DestinationChannel,
sdk.DefaultBondDenom,
),
)
getIBCDenom = func(dstPort, dstChannel string) string {
return transfertypes.ParseDenomTrace(
transfertypes.GetPrefixedDenom(
packet.DestinationPort,
packet.DestinationChannel,
sdk.DefaultBondDenom,
),
).IBCDenom()
}
tc.setup(s.providerCtx(), &providerKeeper, bankKeeper)
cbs, ok := s.providerChain.App.GetIBCKeeper().Router.GetRoute(transfertypes.ModuleName)
s.Require().True(ok)
// save the IBC transfer rewards transferred
rewardsPoolBalance := bankKeeper.GetAllBalances(s.providerCtx(), sdk.MustAccAddressFromBech32(data.Receiver))
// save the consumer's rewards allocated
consumerRewardsAllocations := providerKeeper.GetConsumerRewardsAllocation(s.providerCtx(), s.consumerChain.ChainID)
// execute middleware OnRecvPacket logic
ack := cbs.OnRecvPacket(s.providerCtx(), packet, sdk.AccAddress{})
// compute expected rewards with provider denom
expRewards := sdk.Coin{
Amount: amount,
Denom: getIBCDenom(packet.DestinationPort, packet.DestinationChannel),
}
// compute the balance and allocation difference
rewardsTransferred := bankKeeper.GetAllBalances(s.providerCtx(), sdk.MustAccAddressFromBech32(data.Receiver)).
Sub(rewardsPoolBalance...)
rewardsAllocated := providerKeeper.GetConsumerRewardsAllocation(s.providerCtx(), s.consumerChain.ChainID).
Rewards.Sub(consumerRewardsAllocations.Rewards)
if !tc.expErr {
s.Require().True(ack.Success())
// verify that the consumer rewards pool received the IBC coins
s.Require().Equal(rewardsTransferred, sdk.Coins{expRewards})
if tc.rewardsAllocated {
// check the data receiver address is set to the consumer rewards pool address
s.Require().Equal(data.GetReceiver(), providerKeeper.GetConsumerRewardsPoolAddressStr(s.providerCtx()))
// verify that consumer rewards allocation is updated
s.Require().Equal(rewardsAllocated, sdk.NewDecCoinsFromCoins(expRewards))
} else {
// verify that consumer rewards aren't allocated
s.Require().Empty(rewardsAllocated)
}
} else {
s.Require().False(ack.Success())
}
})
}
}
// TestAllocateTokens is a happy-path test of the consumer rewards pool allocation
// to opted-in validators and the community pool
func (s *CCVTestSuite) TestAllocateTokens() {
// set up channel and delegate some tokens in order for validator set update to be sent to the consumer chain
s.SetupAllCCVChannels()
providerKeeper := s.providerApp.GetProviderKeeper()
bankKeeper := s.providerApp.GetTestBankKeeper()
distributionKeeper := s.providerApp.GetTestDistributionKeeper()
accountKeeper := s.providerApp.GetTestAccountKeeper()
getDistrAcctBalFn := func(ctx sdk.Context) sdk.DecCoins {
bal := bankKeeper.GetAllBalances(ctx, accountKeeper.GetModuleAccount(ctx, distrtypes.ModuleName).GetAddress())
return sdk.NewDecCoinsFromCoins(bal...)
}
totalRewards := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(100))}
// increase the block height so validators are eligible for consumer rewards (see `IsEligibleForConsumerRewards`)
numberOfBlocksToStartReceivingRewards := providerKeeper.GetNumberOfEpochsToStartReceivingRewards(
s.providerCtx()) * providerKeeper.GetBlocksPerEpoch(s.providerCtx())
providerCtx := s.providerCtx().WithBlockHeight(numberOfBlocksToStartReceivingRewards + s.providerCtx().BlockHeight())
// fund consumer rewards pool
bankKeeper.SendCoinsFromAccountToModule(
providerCtx,
s.providerChain.SenderAccount.GetAddress(),
providertypes.ConsumerRewardsPool,
totalRewards,
)
// Allocate rewards evenly between consumers
rewardsPerChain := totalRewards.QuoInt(math.NewInt(int64(len(s.consumerBundles))))
for chainID := range s.consumerBundles {
// update consumer allocation
providerKeeper.SetConsumerRewardsAllocation(
providerCtx,
chainID,
providertypes.ConsumerRewardsAllocation{
Rewards: sdk.NewDecCoinsFromCoins(rewardsPerChain...),
},
)
}
// iterate over the validators and verify that no validator has outstanding rewards
totalValsRewards := sdk.DecCoins{}
for _, val := range s.providerChain.Vals.Validators {
valRewards, err := distributionKeeper.GetValidatorOutstandingRewards(providerCtx, sdk.ValAddress(val.Address))
s.Require().NoError(err)
totalValsRewards = totalValsRewards.Add(valRewards.Rewards...)
}
s.Require().True(totalValsRewards.IsZero())
// At this point the distribution module account
// only holds the community pool's tokens
// since there are no validators with outstanding rewards
lastCommPool := getDistrAcctBalFn(providerCtx)
// execute BeginBlock to trigger the token allocation
providerKeeper.BeginBlockRD(providerCtx)
valNum := len(s.providerChain.Vals.Validators)
consNum := len(s.consumerBundles)
// compute the expected validators token allocation by subtracting the community tax
rewardsPerChainDec := sdk.NewDecCoinsFromCoins(rewardsPerChain...)
communityTax, err := distributionKeeper.GetCommunityTax(providerCtx)
s.Require().NoError(err)
rewardsPerChainTrunc, _ := rewardsPerChainDec.
MulDecTruncate(math.LegacyOneDec().Sub(communityTax)).TruncateDecimal()
validatorsExpRewardsPerChain := sdk.NewDecCoinsFromCoins(rewardsPerChainTrunc...).QuoDec(math.LegacyNewDec(int64(valNum)))
// multiply by the number of consumers
validatorsExpRewards := validatorsExpRewardsPerChain.MulDec(math.LegacyNewDec(int64(consNum)))
// verify the validator tokens allocation
// note that the validators have the same voting power to keep things simple
for _, val := range s.providerChain.Vals.Validators {
valRewards, err := distributionKeeper.GetValidatorOutstandingRewards(providerCtx, sdk.ValAddress(val.Address))
s.Require().NoError(err)
s.Require().Equal(
valRewards.Rewards,
validatorsExpRewards,
)
}
// check that the total expected rewards are transferred to the distribution module account
// store the decimal remainders in the consumer reward allocations
allocRemainderPerChain := providerKeeper.GetConsumerRewardsAllocation(providerCtx, s.consumerChain.ChainID).Rewards
// compute the total rewards distributed to the distribution module balance (validator outstanding rewards + community pool tax),
totalRewardsDistributed := sdk.NewDecCoinsFromCoins(totalRewards...).Sub(allocRemainderPerChain.MulDec(math.LegacyNewDec(int64(consNum))))
// compare the expected total rewards against the distribution module balance
s.Require().Equal(lastCommPool.Add(totalRewardsDistributed...), getDistrAcctBalFn(providerCtx))
}
// getEscrowBalance gets the current balances in the escrow account holding the transferred tokens to the provider
func (s *CCVTestSuite) getEscrowBalance() sdk.Coins {
consumerBankKeeper := s.consumerApp.GetTestBankKeeper()
transChanID := s.consumerApp.GetConsumerKeeper().GetDistributionTransmissionChannel(s.consumerCtx())
escAddr := transfertypes.GetEscrowAddress(transfertypes.PortID, transChanID)
return consumerBankKeeper.GetAllBalances(s.consumerCtx(), escAddr)
}
// corruptTransChannel intentionally causes the reward distribution to fail by corrupting the transmission,
// causing the SendPacket function to return an error.
// Note that the Transferkeeper sends the outgoing fees to an escrow address BEFORE the reward distribution
// is aborted within the SendPacket function.
func (s *CCVTestSuite) corruptTransChannel() {
transChanID := s.consumerApp.GetConsumerKeeper().GetDistributionTransmissionChannel(s.consumerCtx())
tChan, _ := s.consumerApp.GetIBCKeeper().ChannelKeeper.GetChannel(
s.consumerCtx(), transfertypes.PortID, transChanID)
tChan.Counterparty.PortId = "invalid/PortID"
s.consumerApp.GetIBCKeeper().ChannelKeeper.SetChannel(
s.consumerCtx(), transfertypes.PortID, transChanID, tChan)
}
// prepareRewardDist passes enough blocks so that a reward distribution is triggered in the next consumer EndBlock
func (s *CCVTestSuite) prepareRewardDist() {
consumerKeeper := s.consumerApp.GetConsumerKeeper()
bpdt := consumerKeeper.GetBlocksPerDistributionTransmission(s.consumerCtx())
currentHeight := s.consumerCtx().BlockHeight()
lastTransHeight := consumerKeeper.GetLastTransmissionBlockHeight(s.consumerCtx())
blocksSinceLastTrans := currentHeight - lastTransHeight.Height
blocksToGo := bpdt - blocksSinceLastTrans
s.coordinator.CommitNBlocks(s.consumerChain, uint64(blocksToGo))
}
func (s *CCVTestSuite) TestAllocateTokensToConsumerValidators() {
providerKeeper := s.providerApp.GetProviderKeeper()
distributionKeeper := s.providerApp.GetTestDistributionKeeper()
bankKeeper := s.providerApp.GetTestBankKeeper()
chainID := s.consumerChain.ChainID
testCases := []struct {
name string
consuValLen int
tokens sdk.DecCoins
rate math.LegacyDec
expAllocated sdk.DecCoins
}{
{
name: "tokens are empty",
tokens: sdk.DecCoins{},
rate: math.LegacyZeroDec(),
expAllocated: nil,
},
{
name: "consumer valset is empty - total voting power is zero",
tokens: sdk.DecCoins{sdk.NewDecCoin(sdk.DefaultBondDenom, math.NewInt(100_000))},
rate: math.LegacyZeroDec(),
expAllocated: nil,
},
{
name: "expect all tokens to be allocated to a single validator",
consuValLen: 1,
tokens: sdk.DecCoins{sdk.NewDecCoin(sdk.DefaultBondDenom, math.NewInt(999))},
rate: math.LegacyNewDecWithPrec(5, 1),
expAllocated: sdk.DecCoins{sdk.NewDecCoin(sdk.DefaultBondDenom, math.NewInt(999))},
},
{
name: "expect tokens to be allocated evenly between validators",
consuValLen: 2,
tokens: sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, math.LegacyNewDecFromIntWithPrec(math.NewInt(999), 2))},
rate: math.LegacyOneDec(),
expAllocated: sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, math.LegacyNewDecFromIntWithPrec(math.NewInt(999), 2))},
},
}
for _, tc := range testCases {
s.Run(tc.name, func() {
ctx, _ := s.providerCtx().CacheContext()
// increase the block height so validators are eligible for consumer rewards (see `IsEligibleForConsumerRewards`)
ctx = ctx.WithBlockHeight(providerKeeper.GetNumberOfEpochsToStartReceivingRewards(ctx)*providerKeeper.GetBlocksPerEpoch(ctx) +
ctx.BlockHeight())
// change the consumer valset
consuVals := providerKeeper.GetConsumerValSet(ctx, chainID)
providerKeeper.DeleteConsumerValSet(ctx, chainID)
providerKeeper.SetConsumerValSet(ctx, chainID, consuVals[0:tc.consuValLen])
consuVals = providerKeeper.GetConsumerValSet(ctx, chainID)
// set the same consumer commission rate for all consumer validators
for _, v := range consuVals {
provAddr := providertypes.NewProviderConsAddress(sdk.ConsAddress(v.ProviderConsAddr))
err := providerKeeper.SetConsumerCommissionRate(
ctx,
chainID,
provAddr,
tc.rate,
)
s.Require().NoError(err)
}
// allocate tokens
res := providerKeeper.AllocateTokensToConsumerValidators(
ctx,
chainID,
tc.tokens,
)
// check that the expected result is returned
s.Require().Equal(tc.expAllocated, res)
if !tc.expAllocated.Empty() {
// rewards are expected to be allocated evenly between validators
rewardsPerVal := tc.expAllocated.QuoDec(math.LegacyNewDec(int64(len(consuVals))))
// check that the rewards are allocated to validators
for _, v := range consuVals {
valAddr := sdk.ValAddress(v.ProviderConsAddr)
rewards, err := s.providerApp.GetTestDistributionKeeper().GetValidatorOutstandingRewards(
ctx,
valAddr,
)
s.Require().NoError(err)
s.Require().Equal(rewardsPerVal, rewards.Rewards)
// send rewards to the distribution module
valRewardsTrunc, _ := rewards.Rewards.TruncateDecimal()
err = bankKeeper.SendCoinsFromAccountToModule(
ctx,
s.providerChain.SenderAccount.GetAddress(),
distrtypes.ModuleName,
valRewardsTrunc)
s.Require().NoError(err)
// check that validators can withdraw their rewards
withdrawnCoins, err := distributionKeeper.WithdrawValidatorCommission(
ctx,
valAddr,
)
s.Require().NoError(err)
// check that the withdrawn coins is equal to the entire reward amount
// times the set consumer commission rate
commission := rewards.Rewards.MulDec(tc.rate)
c, _ := commission.TruncateDecimal()
s.Require().Equal(withdrawnCoins, c)
// check that validators get rewards in their balance
s.Require().Equal(withdrawnCoins, bankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddr)))
}
} else {
for _, v := range consuVals {
valAddr := sdk.ValAddress(v.ProviderConsAddr)
rewards, err := s.providerApp.GetTestDistributionKeeper().GetValidatorOutstandingRewards(
ctx,
valAddr,
)
s.Require().NoError(err)
s.Require().Zero(rewards.Rewards)
}
}
})
}
}
// TestAllocateTokensToConsumerValidatorsWithDifferentValidatorHeights tests `AllocateTokensToConsumerValidators` with
// consumer validators that have different heights. Specifically, test that validators that have been consumer validators
// for some time receive rewards, while validators that recently became consumer validators do not receive rewards.
func (s *CCVTestSuite) TestAllocateTokensToConsumerValidatorsWithDifferentValidatorHeights() {
// Note this test is an adaptation of a `TestAllocateTokensToConsumerValidators` testcase.
providerKeeper := s.providerApp.GetProviderKeeper()
distributionKeeper := s.providerApp.GetTestDistributionKeeper()
bankKeeper := s.providerApp.GetTestBankKeeper()
chainID := s.consumerChain.ChainID
tokens := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, math.LegacyNewDecFromIntWithPrec(math.NewInt(999), 2))}
rate := math.LegacyOneDec()
expAllocated := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, math.LegacyNewDecFromIntWithPrec(math.NewInt(999), 2))}
ctx, _ := s.providerCtx().CacheContext()
// If the provider chain has not yet reached `GetNumberOfEpochsToStartReceivingRewards * GetBlocksPerEpoch` block height,
// then all validators receive rewards (see `IsEligibleForConsumerRewards`). In this test, we want to check whether
// validators receive rewards or not based on how long they have been consumer validators. Because of this, we increase the block height.
ctx = ctx.WithBlockHeight(providerKeeper.GetNumberOfEpochsToStartReceivingRewards(ctx)*providerKeeper.GetBlocksPerEpoch(ctx) + 1)
// update the consumer validators
consuVals := providerKeeper.GetConsumerValSet(ctx, chainID)
// first 2 validators were consumer validators since block height 1 and hence get rewards
consuVals[0].JoinHeight = 1
consuVals[1].JoinHeight = 1
// last 2 validators were consumer validators since block height 2 and hence do not get rewards because they
// have not been consumer validators for `GetNumberOfEpochsToStartReceivingRewards * GetBlocksPerEpoch` blocks
consuVals[2].JoinHeight = 2
consuVals[3].JoinHeight = 2