-
Notifications
You must be signed in to change notification settings - Fork 750
Expand file tree
/
Copy pathgrandpa_test.go
More file actions
763 lines (601 loc) · 29.9 KB
/
grandpa_test.go
File metadata and controls
763 lines (601 loc) · 29.9 KB
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
//go:build !test_e2e
package wasm
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"os"
"testing"
"time"
"github.com/strangelove-ventures/interchaintest/v8"
"github.com/strangelove-ventures/interchaintest/v8/chain/cosmos"
"github.com/strangelove-ventures/interchaintest/v8/chain/polkadot"
"github.com/strangelove-ventures/interchaintest/v8/ibc"
"github.com/strangelove-ventures/interchaintest/v8/testutil"
testifysuite "github.com/stretchr/testify/suite"
sdkmath "cosmossdk.io/math"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
govtypes "github.com/cosmos/cosmos-sdk/x/gov/types"
"github.com/cosmos/ibc-go/e2e/testsuite"
"github.com/cosmos/ibc-go/e2e/testsuite/query"
"github.com/cosmos/ibc-go/e2e/testvalues"
wasmtypes "github.com/cosmos/ibc-go/modules/light-clients/08-wasm/types"
transfertypes "github.com/cosmos/ibc-go/v8/modules/apps/transfer/types"
clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types"
ibcexported "github.com/cosmos/ibc-go/v8/modules/core/exported"
ibctesting "github.com/cosmos/ibc-go/v8/testing"
)
const (
composable = "composable"
simd = "simd"
wasmSimdImage = "ghcr.io/cosmos/ibc-go-wasm-simd"
defaultWasmClientID = "08-wasm-0"
)
func TestGrandpaTestSuite(t *testing.T) {
// this test suite only works with the hyperspace relayer, for now hard code this here.
// this will enforce that the hyperspace relayer is used in CI.
t.Setenv(testsuite.RelayerIDEnv, "hyperspace")
// TODO: this value should be passed in via the config file / CI, not hard coded in the test.
// This configuration can be handled in https://github.com/cosmos/ibc-go/issues/4697
if testsuite.IsCI() && !testsuite.IsFork() {
t.Setenv(testsuite.ChainImageEnv, wasmSimdImage)
}
// wasm tests require a longer voting period to account for the time it takes to upload a contract.
testvalues.VotingPeriod = time.Minute * 5
validateTestConfig()
testifysuite.Run(t, new(GrandpaTestSuite))
}
type GrandpaTestSuite struct {
testsuite.E2ETestSuite
}
// TestMsgTransfer_Succeeds_GrandpaContract features
// * sets up a Polkadot parachain
// * sets up a Cosmos chain
// * sets up the Hyperspace relayer
// * Funds a user wallet on both chains
// * Pushes a wasm client contract to the Cosmos chain
// * create client, connection, and channel in relayer
// * start relayer
// * send transfer over ibc
func (s *GrandpaTestSuite) TestMsgTransfer_Succeeds_GrandpaContract() {
ctx := context.Background()
t := s.T()
chainA, chainB := s.GetGrandpaTestChains()
polkadotChain, ok := chainA.(*polkadot.PolkadotChain)
s.Require().True(ok)
cosmosChain, ok := chainB.(*cosmos.CosmosChain)
s.Require().True(ok)
// we explicitly skip path creation as the contract needs to be uploaded before we can create clients.
r := s.ConfigureRelayer(ctx, polkadotChain, cosmosChain, nil, func(options *interchaintest.InterchainBuildOptions) {
options.SkipPathCreation = true
})
cosmosWallet := s.CreateUserOnChainB(ctx, testvalues.StartingTokenAmount)
file, err := os.Open("contracts/ics10_grandpa_cw.wasm.gz")
s.Require().NoError(err)
checksum := s.PushNewWasmClientProposal(ctx, cosmosChain, cosmosWallet, file)
s.Require().NotEmpty(checksum, "checksum was empty but should not have been")
eRep := s.GetRelayerExecReporter()
// Set client contract hash in cosmos chain config
err = r.SetClientContractHash(ctx, eRep, cosmosChain.Config(), checksum)
s.Require().NoError(err)
// Ensure parachain has started (starts 1 session/epoch after relay chain)
err = testutil.WaitForBlocks(ctx, 1, polkadotChain)
s.Require().NoError(err, "polkadot chain failed to make blocks")
// Fund users on both cosmos and parachain, mints Asset 1 for Alice
fundAmount := int64(12_333_000_000_000)
polkadotUser, cosmosUser := s.fundUsers(ctx, fundAmount, polkadotChain, cosmosChain)
// TODO: this can be refactored to broadcast a MsgTransfer instead of CLI.
// https://github.com/cosmos/ibc-go/issues/4963
amountToSend := int64(1_770_000)
transfer := ibc.WalletAmount{
Address: polkadotUser.FormattedAddress(),
Denom: cosmosChain.Config().Denom,
Amount: sdkmath.NewInt(amountToSend),
}
pathName := s.GetPathName(0)
err = r.GeneratePath(ctx, eRep, cosmosChain.Config().ChainID, polkadotChain.Config().ChainID, pathName)
s.Require().NoError(err)
// Create new clients
err = r.CreateClients(ctx, eRep, pathName, ibc.DefaultClientOpts())
s.Require().NoError(err)
err = testutil.WaitForBlocks(ctx, 1, cosmosChain, polkadotChain) // these 1 block waits seem to be needed to reduce flakiness
s.Require().NoError(err)
// Create a new connection
err = r.CreateConnections(ctx, eRep, pathName)
s.Require().NoError(err)
err = testutil.WaitForBlocks(ctx, 1, cosmosChain, polkadotChain)
s.Require().NoError(err)
// Create a new channel & get channels from each chain
err = r.CreateChannel(ctx, eRep, pathName, ibc.DefaultChannelOpts())
s.Require().NoError(err)
err = testutil.WaitForBlocks(ctx, 1, cosmosChain, polkadotChain)
s.Require().NoError(err)
// Start relayer
s.Require().NoError(r.StartRelayer(ctx, eRep, pathName))
t.Run("send successful IBC transfer from Cosmos to Polkadot parachain", func(t *testing.T) {
// Send 1.77 stake from cosmosUser to parachainUser
tx, err := cosmosChain.SendIBCTransfer(ctx, "channel-0", cosmosUser.KeyName(), transfer, ibc.TransferOptions{})
s.Require().NoError(tx.Validate(), "source ibc transfer tx is invalid")
s.Require().NoError(err)
// verify token balance for cosmos user has decreased
balance, err := cosmosChain.GetBalance(ctx, cosmosUser.FormattedAddress(), cosmosChain.Config().Denom)
s.Require().NoError(err)
s.Require().Equal(balance, sdkmath.NewInt(fundAmount-amountToSend), "unexpected cosmos user balance after first tx")
err = testutil.WaitForBlocks(ctx, 15, cosmosChain, polkadotChain)
s.Require().NoError(err)
// Verify tokens arrived on parachain user
parachainUserStake, err := polkadotChain.GetIbcBalance(ctx, string(polkadotUser.Address()), 2)
s.Require().NoError(err)
s.Require().Equal(amountToSend, parachainUserStake.Amount.Int64(), "unexpected parachain user balance after first tx")
})
t.Run("send two successful IBC transfers from Polkadot parachain to Cosmos, first with ibc denom, second with parachain denom", func(t *testing.T) {
// Send 1.16 stake from parachainUser to cosmosUser
amountToReflect := int64(1_160_000)
reflectTransfer := ibc.WalletAmount{
Address: cosmosUser.FormattedAddress(),
Denom: "2", // stake
Amount: sdkmath.NewInt(amountToReflect),
}
_, err := polkadotChain.SendIBCTransfer(ctx, "channel-0", polkadotUser.KeyName(), reflectTransfer, ibc.TransferOptions{})
s.Require().NoError(err)
// Send 1.88 "UNIT" from Alice to cosmosUser
amountUnits := sdkmath.NewInt(1_880_000_000_000)
unitTransfer := ibc.WalletAmount{
Address: cosmosUser.FormattedAddress(),
Denom: "1", // UNIT
Amount: amountUnits,
}
_, err = polkadotChain.SendIBCTransfer(ctx, "channel-0", "alice", unitTransfer, ibc.TransferOptions{})
s.Require().NoError(err)
// Wait for MsgRecvPacket on cosmos chain
finalStakeBal := sdkmath.NewInt(fundAmount - amountToSend + amountToReflect)
err = cosmos.PollForBalance(ctx, cosmosChain, 20, ibc.WalletAmount{
Address: cosmosUser.FormattedAddress(),
Denom: cosmosChain.Config().Denom,
Amount: finalStakeBal,
})
s.Require().NoError(err)
// Wait for a new update state
err = testutil.WaitForBlocks(ctx, 5, cosmosChain, polkadotChain)
s.Require().NoError(err)
// Verify cosmos user's final "stake" balance
cosmosUserStakeBal, err := cosmosChain.GetBalance(ctx, cosmosUser.FormattedAddress(), cosmosChain.Config().Denom)
s.Require().NoError(err)
s.Require().True(cosmosUserStakeBal.Equal(finalStakeBal))
// Verify cosmos user's final "unit" balance
denom := transfertypes.NewDenom("UNIT", transfertypes.NewTrace("transfer", "channel-0"))
cosmosUserUnitBal, err := cosmosChain.GetBalance(ctx, cosmosUser.FormattedAddress(), denom.IBCDenom())
s.Require().NoError(err)
s.Require().True(cosmosUserUnitBal.Equal(amountUnits))
// Verify parachain user's final "unit" balance (will be less than expected due gas costs for stake tx)
parachainUserUnits, err := polkadotChain.GetIbcBalance(ctx, string(polkadotUser.Address()), 1)
s.Require().NoError(err)
s.Require().True(parachainUserUnits.Amount.LTE(sdkmath.NewInt(fundAmount)), "parachain user's final unit amount not expected")
// Verify parachain user's final "stake" balance
parachainUserStake, err := polkadotChain.GetIbcBalance(ctx, string(polkadotUser.Address()), 2)
s.Require().NoError(err)
s.Require().True(parachainUserStake.Amount.Equal(sdkmath.NewInt(amountToSend-amountToReflect)), "parachain user's final stake amount not expected")
})
}
// TestMsgTransfer_TimesOut_GrandpaContract
// sets up cosmos and polkadot chains, hyperspace relayer, and funds users on both chains
// * sends transfer over ibc channel, this transfer should timeout
func (s *GrandpaTestSuite) TestMsgTransfer_TimesOut_GrandpaContract() {
ctx := context.Background()
t := s.T()
chainA, chainB := s.GetGrandpaTestChains()
polkadotChain, ok := chainA.(*polkadot.PolkadotChain)
s.Require().True(ok)
cosmosChain, ok := chainB.(*cosmos.CosmosChain)
s.Require().True(ok)
// we explicitly skip path creation as the contract needs to be uploaded before we can create clients.
r := s.ConfigureRelayer(ctx, polkadotChain, cosmosChain, nil, func(options *interchaintest.InterchainBuildOptions) {
options.SkipPathCreation = true
})
cosmosWallet := s.CreateUserOnChainB(ctx, testvalues.StartingTokenAmount)
file, err := os.Open("contracts/ics10_grandpa_cw.wasm.gz")
s.Require().NoError(err)
checksum := s.PushNewWasmClientProposal(ctx, cosmosChain, cosmosWallet, file)
s.Require().NotEmpty(checksum, "checksum was empty but should not have been")
eRep := s.GetRelayerExecReporter()
// Set client contract hash in cosmos chain config
err = r.SetClientContractHash(ctx, eRep, cosmosChain.Config(), checksum)
s.Require().NoError(err)
// Ensure parachain has started (starts 1 session/epoch after relay chain)
err = testutil.WaitForBlocks(ctx, 1, polkadotChain)
s.Require().NoError(err, "polkadot chain failed to make blocks")
// Fund users on both cosmos and parachain, mints Asset 1 for Alice
fundAmount := int64(12_333_000_000_000)
polkadotUser, cosmosUser := s.fundUsers(ctx, fundAmount, polkadotChain, cosmosChain)
// TODO: this can be refactored to broadcast a MsgTransfer instead of CLI.
// https://github.com/cosmos/ibc-go/issues/4963
amountToSend := int64(1_770_000)
transfer := ibc.WalletAmount{
Address: polkadotUser.FormattedAddress(),
Denom: cosmosChain.Config().Denom,
Amount: sdkmath.NewInt(amountToSend),
}
pathName := s.GetPathName(0)
err = r.GeneratePath(ctx, eRep, cosmosChain.Config().ChainID, polkadotChain.Config().ChainID, pathName)
s.Require().NoError(err)
// Create new clients
err = r.CreateClients(ctx, eRep, pathName, ibc.DefaultClientOpts())
s.Require().NoError(err)
err = testutil.WaitForBlocks(ctx, 1, cosmosChain, polkadotChain) // these 1 block waits seem to be needed to reduce flakiness
s.Require().NoError(err)
// Create a new connection
err = r.CreateConnections(ctx, eRep, pathName)
s.Require().NoError(err)
err = testutil.WaitForBlocks(ctx, 1, cosmosChain, polkadotChain)
s.Require().NoError(err)
// Create a new channel & get channels from each chain
err = r.CreateChannel(ctx, eRep, pathName, ibc.DefaultChannelOpts())
s.Require().NoError(err)
err = testutil.WaitForBlocks(ctx, 1, cosmosChain, polkadotChain)
s.Require().NoError(err)
// Start relayer
s.Require().NoError(r.StartRelayer(ctx, eRep, pathName))
t.Run("IBC transfer from Cosmos chain to Polkadot parachain times out", func(t *testing.T) {
// Stop relayer
s.Require().NoError(r.StopRelayer(ctx, s.GetRelayerExecReporter()))
tx, err := cosmosChain.SendIBCTransfer(ctx, "channel-0", cosmosUser.KeyName(), transfer, ibc.TransferOptions{Timeout: testvalues.ImmediatelyTimeout()})
s.Require().NoError(err)
s.Require().NoError(tx.Validate(), "source ibc transfer tx is invalid")
time.Sleep(time.Nanosecond * 1) // want it to timeout immediately
// check that tokens are escrowed
actualBalance, err := cosmosChain.GetBalance(ctx, cosmosUser.FormattedAddress(), cosmosChain.Config().Denom)
s.Require().NoError(err)
expected := fundAmount - amountToSend
s.Require().Equal(expected, actualBalance.Int64())
// start relayer
s.Require().NoError(r.StartRelayer(ctx, s.GetRelayerExecReporter(), s.GetPathName(0)))
err = testutil.WaitForBlocks(ctx, 15, polkadotChain, cosmosChain)
s.Require().NoError(err)
// ensure that receiver on parachain did not receive any tokens
receiverBalance, err := polkadotChain.GetIbcBalance(ctx, polkadotUser.FormattedAddress(), 2)
s.Require().NoError(err)
s.Require().Equal(int64(0), receiverBalance.Amount.Int64())
// check that tokens have been refunded to sender address
senderBalance, err := cosmosChain.GetBalance(ctx, cosmosUser.FormattedAddress(), cosmosChain.Config().Denom)
s.Require().NoError(err)
s.Require().Equal(fundAmount, senderBalance.Int64())
})
}
// TestMsgMigrateContract_Success_GrandpaContract features
// * sets up a Polkadot parachain
// * sets up a Cosmos chain
// * sets up the Hyperspace relayer
// * Funds a user wallet on both chains
// * Pushes a wasm client contract to the Cosmos chain
// * create client in relayer
// * Pushes a new wasm client contract to the Cosmos chain
// * Migrates the wasm client contract
func (s *GrandpaTestSuite) TestMsgMigrateContract_Success_GrandpaContract() {
ctx := context.Background()
chainA, chainB := s.GetGrandpaTestChains()
polkadotChain, ok := chainA.(*polkadot.PolkadotChain)
s.Require().True(ok)
cosmosChain, ok := chainB.(*cosmos.CosmosChain)
s.Require().True(ok)
// we explicitly skip path creation as the contract needs to be uploaded before we can create clients.
r := s.ConfigureRelayer(ctx, polkadotChain, cosmosChain, nil, func(options *interchaintest.InterchainBuildOptions) {
options.SkipPathCreation = true
})
cosmosWallet := s.CreateUserOnChainB(ctx, testvalues.StartingTokenAmount)
file, err := os.Open("contracts/ics10_grandpa_cw.wasm.gz")
s.Require().NoError(err)
checksum := s.PushNewWasmClientProposal(ctx, cosmosChain, cosmosWallet, file)
s.Require().NotEmpty(checksum, "checksum was empty but should not have been")
eRep := s.GetRelayerExecReporter()
// Set client contract hash in cosmos chain config
err = r.SetClientContractHash(ctx, eRep, cosmosChain.Config(), checksum)
s.Require().NoError(err)
// Ensure parachain has started (starts 1 session/epoch after relay chain)
err = testutil.WaitForBlocks(ctx, 1, polkadotChain)
s.Require().NoError(err, "polkadot chain failed to make blocks")
pathName := s.GetPathName(0)
err = r.GeneratePath(ctx, eRep, cosmosChain.Config().ChainID, polkadotChain.Config().ChainID, pathName)
s.Require().NoError(err)
// Create new clients
err = r.CreateClients(ctx, eRep, pathName, ibc.DefaultClientOpts())
s.Require().NoError(err)
err = testutil.WaitForBlocks(ctx, 1, cosmosChain, polkadotChain) // these 1 block waits seem to be needed to reduce flakiness
s.Require().NoError(err)
// Do not start relayer
// This contract is a dummy contract that will always succeed migration.
// Other entry points are unimplemented.
migrateFile, err := os.Open("contracts/migrate_success.wasm.gz")
s.Require().NoError(err)
// First Store the code
newChecksum := s.PushNewWasmClientProposal(ctx, cosmosChain, cosmosWallet, migrateFile)
s.Require().NotEmpty(newChecksum, "checksum was empty but should not have been")
newChecksumBz, err := hex.DecodeString(newChecksum)
s.Require().NoError(err)
// Attempt to migrate the contract
message := wasmtypes.NewMsgMigrateContract(
authtypes.NewModuleAddress(govtypes.ModuleName).String(),
defaultWasmClientID,
newChecksumBz,
[]byte("{}"),
)
s.ExecuteAndPassGovV1Proposal(ctx, message, cosmosChain, cosmosWallet)
clientState, err := query.ClientState(ctx, cosmosChain, defaultWasmClientID)
s.Require().NoError(err)
wasmClientState, ok := clientState.(*wasmtypes.ClientState)
s.Require().True(ok)
s.Require().Equal(newChecksumBz, wasmClientState.Checksum)
}
// TestMsgMigrateContract_ContractError_GrandpaContract features
// * sets up a Polkadot parachain
// * sets up a Cosmos chain
// * sets up the Hyperspace relayer
// * Funds a user wallet on both chains
// * Pushes a wasm client contract to the Cosmos chain
// * create client in relayer
// * Pushes a new wasm client contract to the Cosmos chain
// * Migrates the wasm client contract with a contract that will always fail migration
func (s *GrandpaTestSuite) TestMsgMigrateContract_ContractError_GrandpaContract() {
ctx := context.Background()
chainA, chainB := s.GetGrandpaTestChains()
polkadotChain, ok := chainA.(*polkadot.PolkadotChain)
s.Require().True(ok)
cosmosChain, ok := chainB.(*cosmos.CosmosChain)
s.Require().True(ok)
// we explicitly skip path creation as the contract needs to be uploaded before we can create clients.
r := s.ConfigureRelayer(ctx, polkadotChain, cosmosChain, nil, func(options *interchaintest.InterchainBuildOptions) {
options.SkipPathCreation = true
})
cosmosWallet := s.CreateUserOnChainB(ctx, testvalues.StartingTokenAmount)
file, err := os.Open("contracts/ics10_grandpa_cw.wasm.gz")
s.Require().NoError(err)
checksum := s.PushNewWasmClientProposal(ctx, cosmosChain, cosmosWallet, file)
s.Require().NotEmpty(checksum, "checksum was empty but should not have been")
eRep := s.GetRelayerExecReporter()
// Set client contract hash in cosmos chain config
err = r.SetClientContractHash(ctx, eRep, cosmosChain.Config(), checksum)
s.Require().NoError(err)
// Ensure parachain has started (starts 1 session/epoch after relay chain)
err = testutil.WaitForBlocks(ctx, 1, polkadotChain)
s.Require().NoError(err, "polkadot chain failed to make blocks")
pathName := s.GetPathName(0)
err = r.GeneratePath(ctx, eRep, cosmosChain.Config().ChainID, polkadotChain.Config().ChainID, pathName)
s.Require().NoError(err)
// Create new clients
err = r.CreateClients(ctx, eRep, pathName, ibc.DefaultClientOpts())
s.Require().NoError(err)
err = testutil.WaitForBlocks(ctx, 1, cosmosChain, polkadotChain) // these 1 block waits seem to be needed to reduce flakiness
s.Require().NoError(err)
// Do not start the relayer
// This contract is a dummy contract that will always fail migration.
// Other entry points are unimplemented.
migrateFile, err := os.Open("contracts/migrate_error.wasm.gz")
s.Require().NoError(err)
// First Store the code
newChecksum := s.PushNewWasmClientProposal(ctx, cosmosChain, cosmosWallet, migrateFile)
s.Require().NotEmpty(newChecksum, "checksum was empty but should not have been")
newChecksumBz, err := hex.DecodeString(newChecksum)
s.Require().NoError(err)
// Attempt to migrate the contract
message := wasmtypes.NewMsgMigrateContract(
authtypes.NewModuleAddress(govtypes.ModuleName).String(),
defaultWasmClientID,
newChecksumBz,
[]byte("{}"),
)
err = s.ExecuteGovV1Proposal(ctx, message, cosmosChain, cosmosWallet)
s.Require().Error(err)
version := cosmosChain.Nodes()[0].Image.Version
if govV1FailedReasonFeatureReleases.IsSupported(version) {
// This is the error string that is returned from the contract
s.Require().ErrorContains(err, "migration not supported")
}
}
// TestRecoverClient_Succeeds_GrandpaContract features:
// * setup cosmos and polkadot substrates nodes
// * funds test user wallets on both chains
// * stores a wasm client contract on the cosmos chain
// * creates a subject client using the hyperspace relayer
// * waits the expiry period and asserts the subject client status has expired
// * creates a substitute client using the hyperspace relayer
// * executes a gov proposal to recover the expired client
// * asserts the status of the subject client has been restored to active
// NOTE: The testcase features a modified grandpa client contract compiled as:
// - ics10_grandpa_cw_expiry.wasm.gz
// This contract modifies the unbonding period to 1600s with the trusting period being calculated as (unbonding period / 3).
func (s *GrandpaTestSuite) TestRecoverClient_Succeeds_GrandpaContract() {
ctx := context.Background()
// set the trusting period to a value which will still be valid upon client creation, but invalid before the first update
// the contract uses 1600s as the unbonding period with the trusting period evaluating to (unbonding period / 3)
modifiedTrustingPeriod := (1600 * time.Second) / 3
chainA, chainB := s.GetGrandpaTestChains()
polkadotChain, ok := chainA.(*polkadot.PolkadotChain)
s.Require().True(ok)
cosmosChain, ok := chainB.(*cosmos.CosmosChain)
s.Require().True(ok)
// we explicitly skip path creation as the contract needs to be uploaded before we can create clients.
r := s.ConfigureRelayer(ctx, polkadotChain, cosmosChain, nil, func(options *interchaintest.InterchainBuildOptions) {
options.SkipPathCreation = true
})
cosmosWallet := s.CreateUserOnChainB(ctx, testvalues.StartingTokenAmount)
file, err := os.Open("contracts/ics10_grandpa_cw_expiry.wasm.gz")
s.Require().NoError(err)
codeHash := s.PushNewWasmClientProposal(ctx, cosmosChain, cosmosWallet, file)
s.Require().NotEmpty(codeHash, "codehash was empty but should not have been")
eRep := s.GetRelayerExecReporter()
// Set client contract hash in cosmos chain config
err = r.SetClientContractHash(ctx, eRep, cosmosChain.Config(), codeHash)
s.Require().NoError(err)
// Ensure parachain has started (starts 1 session/epoch after relay chain)
err = testutil.WaitForBlocks(ctx, 1, polkadotChain)
s.Require().NoError(err, "polkadot chain failed to make blocks")
// Fund users on both cosmos and parachain, mints Asset 1 for Alice
fundAmount := int64(12_333_000_000_000)
_, cosmosUser := s.fundUsers(ctx, fundAmount, polkadotChain, cosmosChain)
pathName := s.GetPathName(0)
err = r.GeneratePath(ctx, eRep, cosmosChain.Config().ChainID, polkadotChain.Config().ChainID, pathName)
s.Require().NoError(err)
// create client pair with subject (bad trusting period)
subjectClientID := clienttypes.FormatClientIdentifier(wasmtypes.Wasm, 0)
// TODO: The hyperspace relayer makes no use of create client opts
// https://github.com/strangelove-ventures/interchaintest/blob/main/relayer/hyperspace/hyperspace_commander.go#L83
s.SetupClients(ctx, r, ibc.CreateClientOptions{
TrustingPeriod: modifiedTrustingPeriod.String(), // NOTE: this is hardcoded within the cw contract: ics10_grapnda_cw_expiry.wasm
})
// wait for block
err = testutil.WaitForBlocks(ctx, 1, cosmosChain, polkadotChain)
s.Require().NoError(err)
// wait the bad trusting period
time.Sleep(modifiedTrustingPeriod)
// create client pair with substitute
substituteClientID := clienttypes.FormatClientIdentifier(wasmtypes.Wasm, 1)
s.SetupClients(ctx, r, ibc.DefaultClientOpts())
// wait for block
err = testutil.WaitForBlocks(ctx, 1, cosmosChain, polkadotChain)
s.Require().NoError(err)
// ensure subject client is expired
status, err := query.ClientStatus(ctx, cosmosChain, subjectClientID)
s.Require().NoError(err)
s.Require().Equal(ibcexported.Expired.String(), status, "unexpected subject client status")
// ensure substitute client is active
status, err = query.ClientStatus(ctx, cosmosChain, substituteClientID)
s.Require().NoError(err)
s.Require().Equal(ibcexported.Active.String(), status, "unexpected substitute client status")
version := cosmosChain.Nodes()[0].Image.Version
if govV1FeatureReleases.IsSupported(version) {
// create and execute a client recovery proposal
authority, err := query.ModuleAccountAddress(ctx, govtypes.ModuleName, cosmosChain)
s.Require().NoError(err)
msgRecoverClient := clienttypes.NewMsgRecoverClient(authority.String(), subjectClientID, substituteClientID)
s.Require().NotNil(msgRecoverClient)
s.ExecuteAndPassGovV1Proposal(ctx, msgRecoverClient, cosmosChain, cosmosUser)
} else {
proposal := clienttypes.NewClientUpdateProposal(ibctesting.Title, ibctesting.Description, subjectClientID, substituteClientID)
s.ExecuteAndPassGovV1Beta1Proposal(ctx, cosmosChain, cosmosWallet, proposal)
}
// ensure subject client is active
status, err = query.ClientStatus(ctx, cosmosChain, subjectClientID)
s.Require().NoError(err)
s.Require().Equal(ibcexported.Active.String(), status)
// ensure substitute client is active
status, err = query.ClientStatus(ctx, cosmosChain, substituteClientID)
s.Require().NoError(err)
s.Require().Equal(ibcexported.Active.String(), status)
}
// extractChecksumFromGzippedContent takes a gzipped wasm contract and returns the checksum.
func (s *GrandpaTestSuite) extractChecksumFromGzippedContent(zippedContent []byte) string {
content, err := wasmtypes.Uncompress(zippedContent, wasmtypes.MaxWasmSize)
s.Require().NoError(err)
checksum32 := sha256.Sum256(content)
return hex.EncodeToString(checksum32[:])
}
// PushNewWasmClientProposal submits a new wasm client governance proposal to the chain.
func (s *GrandpaTestSuite) PushNewWasmClientProposal(ctx context.Context, chain *cosmos.CosmosChain, wallet ibc.Wallet, proposalContentReader io.Reader) string {
zippedContent, err := io.ReadAll(proposalContentReader)
s.Require().NoError(err)
computedChecksum := s.extractChecksumFromGzippedContent(zippedContent)
s.Require().NoError(err)
message := wasmtypes.MsgStoreCode{
Signer: authtypes.NewModuleAddress(govtypes.ModuleName).String(),
WasmByteCode: zippedContent,
}
s.ExecuteAndPassGovV1Proposal(ctx, &message, chain, wallet)
codeResp, err := query.GRPCQuery[wasmtypes.QueryCodeResponse](ctx, chain, &wasmtypes.QueryCodeRequest{Checksum: computedChecksum})
s.Require().NoError(err)
checksumBz := codeResp.Data
checksum32 := sha256.Sum256(checksumBz)
actualChecksum := hex.EncodeToString(checksum32[:])
s.Require().Equal(computedChecksum, actualChecksum, "checksum returned from query did not match the computed checksum")
return actualChecksum
}
func (s *GrandpaTestSuite) fundUsers(ctx context.Context, fundAmount int64, polkadotChain ibc.Chain, cosmosChain ibc.Chain) (ibc.Wallet, ibc.Wallet) {
users := interchaintest.GetAndFundTestUsers(s.T(), ctx, "user", sdkmath.NewInt(fundAmount), polkadotChain, cosmosChain)
polkadotUser, cosmosUser := users[0], users[1]
err := testutil.WaitForBlocks(ctx, 2, polkadotChain, cosmosChain) // Only waiting 1 block is flaky for parachain
s.Require().NoError(err, "cosmos or polkadot chain failed to make blocks")
// Check balances are correct
amount := sdkmath.NewInt(fundAmount)
polkadotUserAmount, err := polkadotChain.GetBalance(ctx, polkadotUser.FormattedAddress(), polkadotChain.Config().Denom)
s.Require().NoError(err)
s.Require().True(polkadotUserAmount.Equal(amount), "Initial polkadot user amount not expected")
parachainUserAmount, err := polkadotChain.GetBalance(ctx, polkadotUser.FormattedAddress(), "")
s.Require().NoError(err)
s.Require().True(parachainUserAmount.Equal(amount), "Initial parachain user amount not expected")
cosmosUserAmount, err := cosmosChain.GetBalance(ctx, cosmosUser.FormattedAddress(), cosmosChain.Config().Denom)
s.Require().NoError(err)
s.Require().True(cosmosUserAmount.Equal(amount), "Initial cosmos user amount not expected")
return polkadotUser, cosmosUser
}
// validateTestConfig ensures that the given test config is valid for this test suite.
func validateTestConfig() {
tc := testsuite.LoadConfig()
if tc.ActiveRelayer != "hyperspace" {
panic(fmt.Errorf("hyperspace relayer must be specified"))
}
}
// getConfigOverrides returns configuration overrides that will be applied to the simapp.
func getConfigOverrides() map[string]any {
consensusOverrides := make(testutil.Toml)
blockTime := 5
blockT := (time.Duration(blockTime) * time.Second).String()
consensusOverrides["timeout_commit"] = blockT
consensusOverrides["timeout_propose"] = blockT
configTomlOverrides := make(testutil.Toml)
configTomlOverrides["consensus"] = consensusOverrides
configTomlOverrides["log_level"] = "info"
configFileOverrides := make(map[string]any)
configFileOverrides["config/config.toml"] = configTomlOverrides
return configFileOverrides
}
// GetGrandpaTestChains returns the configured chains for the grandpa test suite.
func (s *GrandpaTestSuite) GetGrandpaTestChains() (ibc.Chain, ibc.Chain) {
return s.GetChains(func(options *testsuite.ChainOptions) {
// configure chain A (polkadot)
options.ChainASpec.ChainName = composable
options.ChainASpec.Type = "polkadot"
options.ChainASpec.ChainID = "rococo-local"
options.ChainASpec.Name = "composable"
options.ChainASpec.Images = []ibc.DockerImage{
// TODO: https://github.com/cosmos/ibc-go/issues/4965
{
Repository: "ghcr.io/misko9/polkadot-node",
Version: "v39",
UidGid: "1000:1000",
},
{
Repository: "ghcr.io/misko9/parachain-node",
Version: "20231122v39",
UidGid: "1000:1000",
},
}
options.ChainASpec.Bin = "polkadot"
options.ChainASpec.Bech32Prefix = composable
options.ChainASpec.Denom = "uDOT"
options.ChainASpec.GasPrices = ""
options.ChainASpec.GasAdjustment = 0
options.ChainASpec.TrustingPeriod = ""
options.ChainASpec.CoinType = "354"
// these values are set by default for our cosmos chains, we need to explicitly remove them here.
options.ChainASpec.ModifyGenesis = nil
options.ChainASpec.ConfigFileOverrides = nil
options.ChainASpec.EncodingConfig = nil
// configure chain B (cosmos)
options.ChainBSpec.ChainName = simd // Set chain name so that a suffix with a "dash" is not appended (required for hyperspace)
options.ChainBSpec.Type = "cosmos"
options.ChainBSpec.Name = "simd"
options.ChainBSpec.ChainID = simd
options.ChainBSpec.Bin = simd
options.ChainBSpec.Bech32Prefix = "cosmos"
// TODO: hyperspace relayer assumes a denom of "stake", hard code this here right now.
// https://github.com/cosmos/ibc-go/issues/4964
options.ChainBSpec.Denom = "stake"
options.ChainBSpec.GasPrices = "0.00stake"
options.ChainBSpec.GasAdjustment = 1
options.ChainBSpec.TrustingPeriod = "504h"
options.ChainBSpec.CoinType = "118"
options.ChainBSpec.ChainConfig.NoHostMount = false
options.ChainBSpec.ConfigFileOverrides = getConfigOverrides()
options.ChainBSpec.EncodingConfig = testsuite.SDKEncodingConfig()
})
}