@agoric/cosmos 0.34.2-dev-a29afed.0.a29afed → 0.34.2-dev-cb1866d.0.cb1866d

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,23 @@
1
1
  package keeper_test
2
2
 
3
3
  import (
4
+ "bytes"
5
+ "compress/gzip"
6
+ "crypto/sha512"
7
+ "strings"
8
+ "testing"
9
+
10
+ "github.com/stretchr/testify/require"
4
11
  "github.com/stretchr/testify/suite"
5
12
  "go.uber.org/mock/gomock"
6
13
 
14
+ "cosmossdk.io/log"
15
+ "cosmossdk.io/store"
16
+ storemetrics "cosmossdk.io/store/metrics"
7
17
  storetypes "cosmossdk.io/store/types"
8
18
  cmtproto "github.com/cometbft/cometbft/proto/tendermint/types"
9
19
  cmttime "github.com/cometbft/cometbft/types/time"
20
+ dbm "github.com/cosmos/cosmos-db"
10
21
  "github.com/cosmos/cosmos-sdk/codec"
11
22
  paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper"
12
23
 
@@ -21,6 +32,10 @@ import (
21
32
  vbanktypes "github.com/Agoric/agoric-sdk/golang/cosmos/x/vbank/types"
22
33
  )
23
34
 
35
+ var (
36
+ submitAddr = sdk.AccAddress([]byte("submitter"))
37
+ )
38
+
24
39
  type KeeperTestSuite struct {
25
40
  suite.Suite
26
41
 
@@ -84,7 +99,8 @@ func (suite *KeeperTestSuite) TearDownTest() {
84
99
  // 2. Actions are pushed to the high priority queue with correct
85
100
  // 3. Eval contains the expected JS code and permits
86
101
  // 4. Proper metadata
87
- func (suite *KeeperTestSuite) TestCoreEval() {
102
+ // TODO: Fix this test https://github.com/Agoric/agoric-sdk/issues/12243
103
+ func (suite *KeeperTestSuite) SkipFailingTestCoreEval() {
88
104
  suite.SetupTest()
89
105
  // Create a mock vstorage keeper that expects a queue push with the correct action
90
106
  mockVstorageKeeper := swingtestutil.NewMockVstorageKeeper(suite.ctrl)
@@ -119,3 +135,283 @@ func (suite *KeeperTestSuite) TestCoreEval() {
119
135
  suite.NotNil(resp)
120
136
  suite.Empty(resp.Result)
121
137
  }
138
+
139
+ func TestMsgServer(t *testing.T) {
140
+ suite.Run(t, new(KeeperTestSuite))
141
+ }
142
+
143
+ // testMsgServerEnv holds the test environment for message server tests
144
+ type testMsgServerEnv struct {
145
+ ctx sdk.Context
146
+ msgServer types.MsgServer
147
+ ctrl *gomock.Controller
148
+ }
149
+
150
+ // setupMsgServerTest creates a test environment with a configured keeper and message server.
151
+ // If expectPushQueueItem is true, the mock vstorage keeper will expect a PushQueueItem call.
152
+ func setupMsgServerTest(t *testing.T, expectPushQueueItem bool) *testMsgServerEnv {
153
+ t.Helper()
154
+
155
+ // Create mock controller
156
+ ctrl := gomock.NewController(t)
157
+
158
+ // Create mock keepers
159
+ mockAccountKeeper := swingtestutil.NewMockAccountKeeper(ctrl)
160
+ mockBankKeeper := swingtestutil.NewMockBankKeeper(ctrl)
161
+ mockVstorageKeeper := swingtestutil.NewMockVstorageKeeper(ctrl)
162
+
163
+ // Set up expectations if needed
164
+ if expectPushQueueItem {
165
+ mockVstorageKeeper.EXPECT().
166
+ PushQueueItem(gomock.Any(), gomock.Eq("actionQueue"), gomock.Any()).
167
+ Return(nil).
168
+ Times(1)
169
+ }
170
+
171
+ // Create keeper with stores
172
+ encCfg := moduletestutil.MakeTestEncodingConfig()
173
+ key := storetypes.NewKVStoreKey(types.StoreKey)
174
+ paramsKey := storetypes.NewKVStoreKey("params")
175
+ paramsTKey := storetypes.NewTransientStoreKey("transient_params")
176
+
177
+ db := dbm.NewMemDB()
178
+ logger := log.NewNopLogger()
179
+ ms := store.NewCommitMultiStore(db, logger, storemetrics.NewNoOpMetrics())
180
+ ms.MountStoreWithDB(key, storetypes.StoreTypeIAVL, db)
181
+ ms.MountStoreWithDB(paramsKey, storetypes.StoreTypeIAVL, db)
182
+ ms.MountStoreWithDB(paramsTKey, storetypes.StoreTypeTransient, db)
183
+ err := ms.LoadLatestVersion()
184
+ if err != nil {
185
+ t.Fatalf("Failed to load multi-store: %v", err)
186
+ }
187
+
188
+ ctx := sdk.NewContext(ms, cmtproto.Header{Time: cmttime.Now()}, false, logger)
189
+
190
+ callToController := func(ctx sdk.Context, jsonRequest string) (jsonReply string, err error) {
191
+ return "", nil
192
+ }
193
+
194
+ paramsKeeper := paramskeeper.NewKeeper(encCfg.Codec, codec.NewLegacyAmino(), paramsKey, paramsTKey)
195
+ paramsKeeper.Subspace(types.ModuleName)
196
+ paramsSubspace, _ := paramsKeeper.GetSubspace(types.ModuleName)
197
+
198
+ testKeeper := keeper.NewKeeper(
199
+ encCfg.Codec,
200
+ runtime.NewKVStoreService(key),
201
+ paramsSubspace,
202
+ mockAccountKeeper,
203
+ mockBankKeeper,
204
+ mockVstorageKeeper,
205
+ vbanktypes.ReservePoolName,
206
+ authority,
207
+ callToController,
208
+ )
209
+ testKeeper.SetParams(ctx, types.DefaultParams())
210
+
211
+ return &testMsgServerEnv{
212
+ ctx: ctx,
213
+ msgServer: keeper.NewMsgServerImpl(testKeeper),
214
+ ctrl: ctrl,
215
+ }
216
+ }
217
+
218
+ func TestInstallBundle(t *testing.T) {
219
+ env := setupMsgServerTest(t, true)
220
+ defer env.ctrl.Finish()
221
+
222
+ // Create a valid gzip-compressed bundle
223
+ bundleData := `{"moduleFormat":"endoZipBase64","endoZipBase64":"test"}`
224
+ var buf bytes.Buffer
225
+ gzipWriter := gzip.NewWriter(&buf)
226
+ _, err := gzipWriter.Write([]byte(bundleData))
227
+ if err != nil {
228
+ t.Fatalf("Failed to write gzip data: %v", err)
229
+ }
230
+ err = gzipWriter.Close()
231
+ if err != nil {
232
+ t.Fatalf("Failed to close gzip writer: %v", err)
233
+ }
234
+
235
+ // Test with bundle size matching actual data
236
+ msg := &types.MsgInstallBundle{
237
+ Submitter: submitAddr,
238
+ CompressedBundle: buf.Bytes(),
239
+ UncompressedSize: int64(len(bundleData)),
240
+ }
241
+ resp, err := env.msgServer.InstallBundle(env.ctx, msg)
242
+ if err != nil {
243
+ t.Fatalf("InstallBundle failed: %v", err)
244
+ }
245
+ if resp == nil {
246
+ t.Fatal("Expected non-nil response")
247
+ }
248
+ }
249
+
250
+ func TestInstallBundleJustUnderSizeLimit(t *testing.T) {
251
+ env := setupMsgServerTest(t, false)
252
+ defer env.ctrl.Finish()
253
+
254
+ // Create minimal gzip data
255
+ var buf bytes.Buffer
256
+ gzipWriter := gzip.NewWriter(&buf)
257
+ if err := gzipWriter.Close(); err != nil {
258
+ t.Fatalf("Failed to close gzip writer: %v", err)
259
+ }
260
+
261
+ msg := &types.MsgInstallBundle{
262
+ Submitter: submitAddr,
263
+ UncompressedSize: int64(types.DefaultBundleUncompressedSizeLimitBytes) - 1,
264
+ CompressedBundle: buf.Bytes(),
265
+ }
266
+
267
+ // Bundle just under the limit should pass size validation (but fail on decompression)
268
+ _, err := env.msgServer.InstallBundle(env.ctx, msg)
269
+ if err == nil {
270
+ t.Fatal("Expected error for mismatched uncompressed size")
271
+ }
272
+ if strings.Contains(err.Error(), "Uncompressed size out of range") {
273
+ t.Errorf("Should not fail on size validation just under the limit, got: %v", err)
274
+ }
275
+ }
276
+
277
+ func TestInstallBundleAtSizeLimit(t *testing.T) {
278
+ env := setupMsgServerTest(t, false)
279
+ defer env.ctrl.Finish()
280
+
281
+ // Create minimal gzip data
282
+ var buf bytes.Buffer
283
+ gzipWriter := gzip.NewWriter(&buf)
284
+ if err := gzipWriter.Close(); err != nil {
285
+ t.Fatalf("Failed to close gzip writer: %v", err)
286
+ }
287
+
288
+ msg := &types.MsgInstallBundle{
289
+ Submitter: submitAddr,
290
+ UncompressedSize: int64(types.DefaultBundleUncompressedSizeLimitBytes),
291
+ CompressedBundle: buf.Bytes(),
292
+ }
293
+
294
+ // With exclusive limit, a bundle at exactly the limit should be rejected
295
+ _, err := env.msgServer.InstallBundle(env.ctx, msg)
296
+ if err == nil {
297
+ t.Fatal("Bundle at the limit should fail validation (exclusive limit)")
298
+ }
299
+ if !strings.Contains(err.Error(), "Uncompressed size out of range") {
300
+ t.Errorf("Expected 'Uncompressed size out of range' error, got: %v", err)
301
+ }
302
+ }
303
+
304
+ func TestInstallBundleChunkCountAtLimit(t *testing.T) {
305
+ env := setupMsgServerTest(t, false)
306
+ defer env.ctrl.Finish()
307
+
308
+ params := types.DefaultParams()
309
+ chunkIndexLimit := types.MaxArtifactChunksCount(
310
+ params.BundleUncompressedSizeLimitBytes,
311
+ params.ChunkSizeLimitBytes,
312
+ )
313
+ chunkedArtifact := makeChunkedArtifact(t, chunkIndexLimit)
314
+
315
+ msg := &types.MsgInstallBundle{
316
+ Submitter: submitAddr,
317
+ ChunkedArtifact: chunkedArtifact,
318
+ }
319
+
320
+ _, err := env.msgServer.InstallBundle(env.ctx, msg)
321
+ if err != nil {
322
+ t.Fatalf("bundle with max chunk count should be accepted, got %v", err)
323
+ }
324
+ }
325
+
326
+ func TestInstallBundleChunkCountOverLimit(t *testing.T) {
327
+ env := setupMsgServerTest(t, false)
328
+ defer env.ctrl.Finish()
329
+
330
+ params := types.DefaultParams()
331
+ chunkIndexLimit := types.MaxArtifactChunksCount(
332
+ params.BundleUncompressedSizeLimitBytes,
333
+ params.ChunkSizeLimitBytes,
334
+ )
335
+ chunkedArtifact := makeChunkedArtifact(t, chunkIndexLimit+1)
336
+
337
+ msg := &types.MsgInstallBundle{
338
+ Submitter: submitAddr,
339
+ ChunkedArtifact: chunkedArtifact,
340
+ }
341
+
342
+ _, err := env.msgServer.InstallBundle(env.ctx, msg)
343
+ if err == nil {
344
+ t.Fatal("expected error for bundle with too many chunks")
345
+ }
346
+ if !strings.Contains(err.Error(), "Number of bundle chunks must be less than") {
347
+ t.Fatalf("unexpected error for chunk count over limit: %v", err)
348
+ }
349
+ }
350
+
351
+ func TestSendChunkUsesWrappedContext(t *testing.T) {
352
+ env := setupMsgServerTest(t, false)
353
+ defer env.ctrl.Finish()
354
+
355
+ chunkData := make([]byte, int(types.DefaultChunkSizeLimitBytes)+1)
356
+ msg := &types.MsgSendChunk{
357
+ ChunkedArtifactId: 1,
358
+ Submitter: submitAddr,
359
+ ChunkIndex: 0,
360
+ ChunkData: chunkData,
361
+ }
362
+
363
+ require.NotPanics(t, func() {
364
+ _, err := env.msgServer.SendChunk(env.ctx, msg)
365
+ require.Error(t, err)
366
+ require.Contains(t, err.Error(), "Chunk size must be at most")
367
+ })
368
+ }
369
+
370
+ func TestInstallBundleOverSizeLimit(t *testing.T) {
371
+ env := setupMsgServerTest(t, false)
372
+ defer env.ctrl.Finish()
373
+
374
+ // Create minimal gzip data
375
+ var buf bytes.Buffer
376
+ gzipWriter := gzip.NewWriter(&buf)
377
+ if err := gzipWriter.Close(); err != nil {
378
+ t.Fatalf("Failed to close gzip writer: %v", err)
379
+ }
380
+
381
+ msg := &types.MsgInstallBundle{
382
+ Submitter: submitAddr,
383
+ UncompressedSize: int64(types.DefaultBundleUncompressedSizeLimitBytes) + 1,
384
+ CompressedBundle: buf.Bytes(),
385
+ }
386
+
387
+ // This should fail during size validation
388
+ _, err := env.msgServer.InstallBundle(env.ctx, msg)
389
+ if err == nil {
390
+ t.Fatal("Bundle over the limit should fail validation")
391
+ }
392
+ if !strings.Contains(err.Error(), "Uncompressed size out of range") {
393
+ t.Errorf("Expected 'Uncompressed size out of range' error, got: %v", err)
394
+ }
395
+ }
396
+
397
+ func makeChunkedArtifact(t *testing.T, chunkCount int64) *types.ChunkedArtifact {
398
+ t.Helper()
399
+ if chunkCount <= 0 {
400
+ t.Fatalf("chunkCount must be positive, got %d", chunkCount)
401
+ }
402
+
403
+ hash := strings.Repeat("0", sha512.Size*2)
404
+ chunks := make([]*types.ChunkInfo, int(chunkCount))
405
+ for i := range chunks {
406
+ chunks[i] = &types.ChunkInfo{
407
+ SizeBytes: 1,
408
+ Sha512: hash,
409
+ }
410
+ }
411
+
412
+ return &types.ChunkedArtifact{
413
+ Sha512: hash,
414
+ SizeBytes: uint64(chunkCount),
415
+ Chunks: chunks,
416
+ }
417
+ }
@@ -75,6 +75,9 @@ var (
75
75
 
76
76
  DefaultBootstrapVatConfig = "@agoric/vm-config/decentral-core-config.json"
77
77
 
78
+ DefaultInstallationDeadlineBlocks int64 = -1 // unlimited
79
+ DefaultInstallationDeadlineSeconds int64 = 24 * 60 * 60 // 24 hours
80
+
78
81
  DefaultPowerFlagFees = []PowerFlagFee{
79
82
  NewPowerFlagFee(PowerFlagSmartWallet, sdk.NewCoins(sdk.NewInt64Coin("ubld", 10_000_000))),
80
83
  }
@@ -100,6 +103,12 @@ var (
100
103
  // UintMapEntry{VatCleanupSnapshots, DefaultVatCleanupSnapshots},
101
104
  // UintMapEntry{VatCleanupTranscripts, DefaultVatCleanupTranscripts},
102
105
  }
106
+
107
+ // DefaultBundleUncompressedSizeLimitBytes is the (exclusive) limit on uncompressed bundle size.
108
+ // We must ensure there is an exclusive int64 limit in order to detect an underflow.
109
+ // Bundles must be strictly less than this size.
110
+ DefaultBundleUncompressedSizeLimitBytes int64 = 10_000_000
111
+ DefaultChunkSizeLimitBytes int64 = 490_000
103
112
  )
104
113
 
105
114
  // move DefaultBeansPerUnit to a function to allow for boot overriding of the Default params
@@ -0,0 +1,103 @@
1
+ package types
2
+
3
+ import (
4
+ "fmt"
5
+
6
+ storetypes "cosmossdk.io/store"
7
+ "github.com/cosmos/cosmos-sdk/codec"
8
+ sdk "github.com/cosmos/cosmos-sdk/types"
9
+ )
10
+
11
+ type ListTools struct {
12
+ cdc codec.Codec
13
+ nodeStore storetypes.KVStore
14
+ }
15
+
16
+ type ListKey struct {
17
+ keyBytes []byte
18
+ }
19
+
20
+ func (ListTools) Key(id uint64) ListKey {
21
+ keyBytes := sdk.Uint64ToBigEndian(id)
22
+ return ListKey{keyBytes: keyBytes}
23
+ }
24
+
25
+ func (lt ListTools) Fetch(key ListKey) *ChunkedArtifactNode {
26
+ var node ChunkedArtifactNode
27
+ if !lt.nodeStore.Has(key.keyBytes) {
28
+ return nil
29
+ }
30
+ bz := lt.nodeStore.Get(key.keyBytes)
31
+ lt.cdc.MustUnmarshal(bz, &node)
32
+ return &node
33
+ }
34
+
35
+ func (lt ListTools) Store(key ListKey, node *ChunkedArtifactNode) {
36
+ bz := lt.cdc.MustMarshal(node)
37
+ lt.nodeStore.Set(key.keyBytes, bz)
38
+ }
39
+
40
+ func (lt ListTools) Delete(key ListKey) {
41
+ lt.nodeStore.Delete(key.keyBytes)
42
+ }
43
+
44
+ // Unlink removes a node from a non-circular list where PrevId == 0 indicates
45
+ // the head and NextId == 0 indicates the tail.
46
+ func (lt ListTools) Unlink(victim *ChunkedArtifactNode, updateEnds func(first, last *uint64)) error {
47
+ if victim == nil {
48
+ return fmt.Errorf("missing chunked artifact node during unlink")
49
+ }
50
+
51
+ if updateEnds != nil && (victim.PrevId == 0 || victim.NextId == 0) {
52
+ var firstp, lastp *uint64
53
+ if victim.PrevId == 0 {
54
+ // This is the first node in the list.
55
+ first := victim.NextId
56
+ firstp = &first
57
+ }
58
+ if victim.NextId == 0 {
59
+ // This is the last node in the list.
60
+ last := victim.PrevId
61
+ lastp = &last
62
+ }
63
+ updateEnds(firstp, lastp)
64
+ }
65
+
66
+ updateNode := func(id uint64, op string, mutate func(*ChunkedArtifactNode)) error {
67
+ key := lt.Key(id)
68
+ node := lt.Fetch(key)
69
+ if node == nil {
70
+ return fmt.Errorf("missing chunked artifact node id=%d during %s", id, op)
71
+ }
72
+ mutate(node)
73
+ lt.Store(key, node)
74
+ return nil
75
+ }
76
+
77
+ if victim.PrevId != 0 {
78
+ // Look up the previous node, set its next to the victim node's next.
79
+ if err := updateNode(victim.PrevId, "unlink prev", func(prevNode *ChunkedArtifactNode) {
80
+ prevNode.NextId = victim.NextId
81
+ }); err != nil {
82
+ return err
83
+ }
84
+ }
85
+
86
+ if victim.NextId != 0 {
87
+ // Look up the next node, set its previous to the victim node's previous.
88
+ if err := updateNode(victim.NextId, "unlink next", func(nextNode *ChunkedArtifactNode) {
89
+ nextNode.PrevId = victim.PrevId
90
+ }); err != nil {
91
+ return err
92
+ }
93
+ }
94
+
95
+ return nil
96
+ }
97
+
98
+ func NewListTools(ctx sdk.Context, nodeStore storetypes.KVStore, cdc codec.Codec) *ListTools {
99
+ return &ListTools{
100
+ cdc: cdc,
101
+ nodeStore: nodeStore,
102
+ }
103
+ }
@@ -3,8 +3,11 @@ package types
3
3
  import (
4
4
  "bytes"
5
5
  "compress/gzip"
6
+ "crypto/sha512"
6
7
  "encoding/json"
7
8
  "io"
9
+ "math"
10
+ "regexp"
8
11
  "strings"
9
12
 
10
13
  sdkioerrors "cosmossdk.io/errors"
@@ -27,12 +30,14 @@ var (
27
30
  _ sdk.Msg = &MsgDeliverInbound{}
28
31
  _ sdk.Msg = &MsgProvision{}
29
32
  _ sdk.Msg = &MsgInstallBundle{}
33
+ _ sdk.Msg = &MsgSendChunk{}
30
34
  _ sdk.Msg = &MsgWalletAction{}
31
35
  _ sdk.Msg = &MsgWalletSpendAction{}
32
36
  _ sdk.Msg = &MsgCoreEval{}
33
37
 
34
38
  _ vm.ControllerAdmissionMsg = &MsgDeliverInbound{}
35
39
  _ vm.ControllerAdmissionMsg = &MsgInstallBundle{}
40
+ _ vm.ControllerAdmissionMsg = &MsgSendChunk{}
36
41
  _ vm.ControllerAdmissionMsg = &MsgProvision{}
37
42
  _ vm.ControllerAdmissionMsg = &MsgWalletAction{}
38
43
  _ vm.ControllerAdmissionMsg = &MsgWalletSpendAction{}
@@ -64,6 +69,10 @@ func DefineCustomGetSigners(options *signing.Options) {
64
69
  proto.MessageName(protoadapt.MessageV2Of(&MsgInstallBundle{})),
65
70
  createSignerFieldFunc("submitter"),
66
71
  )
72
+ options.DefineCustomGetSigners(
73
+ proto.MessageName(protoadapt.MessageV2Of(&MsgSendChunk{})),
74
+ createSignerFieldFunc("submitter"),
75
+ )
67
76
  options.DefineCustomGetSigners(
68
77
  proto.MessageName(protoadapt.MessageV2Of(&MsgWalletAction{})),
69
78
  createSignerFieldFunc("owner"),
@@ -74,6 +83,10 @@ func DefineCustomGetSigners(options *signing.Options) {
74
83
  )
75
84
  }
76
85
 
86
+ // IsHexBytes defines a regular expression to check if the string represents
87
+ // only hexadecimal bytes.
88
+ var IsHexBytes = regexp.MustCompile(`^([0-9a-fA-F]{2})+$`).MatchString
89
+
77
90
  // Contextual information about the message source of an action on an inbound queue.
78
91
  // This context should be unique per inboundQueueRecord.
79
92
  type ActionContext struct {
@@ -94,11 +107,13 @@ type InboundQueueRecord struct {
94
107
  Context ActionContext `json:"context"`
95
108
  }
96
109
 
97
- const (
98
- // bundleUncompressedSizeLimit is the (exclusive) limit on uncompressed bundle size.
99
- // We must ensure there is an exclusive int64 limit in order to detect an underflow.
100
- bundleUncompressedSizeLimit int64 = 10 * 1024 * 1024 // 10MB
101
- )
110
+ // MaxArtifactChunkCount derives the maximum number of entries in an artifact manifest
111
+ func MaxArtifactChunksCount(bundleUncompressedSizeLimitBytes int64, chunkSizeLimitBytes int64) int64 {
112
+ if chunkSizeLimitBytes <= 0 {
113
+ return 0
114
+ }
115
+ return (bundleUncompressedSizeLimitBytes + chunkSizeLimitBytes - 1) / chunkSizeLimitBytes
116
+ }
102
117
 
103
118
  // Charge an account address for the beans associated with given messages and storage.
104
119
  // See list of bean charges in default-params.go
@@ -434,24 +449,26 @@ func (msg MsgInstallBundle) ValidateBasic() error {
434
449
  if msg.Submitter.Empty() {
435
450
  return sdkioerrors.Wrap(sdkerrors.ErrInvalidAddress, "Submitter address cannot be empty")
436
451
  }
437
- if len(msg.Bundle) == 0 && len(msg.CompressedBundle) == 0 {
452
+ hasBundle, hasCompressed, hasChunks := len(msg.Bundle) > 0, len(msg.CompressedBundle) > 0, msg.ChunkedArtifact != nil
453
+ switch {
454
+ case hasBundle && hasCompressed, hasBundle && hasChunks, hasCompressed && hasChunks:
455
+ return sdkioerrors.Wrap(sdkerrors.ErrUnknownRequest, "Cannot submit more than one of bundle, compressed bundle, or chunks")
456
+ case !hasBundle && !hasCompressed && !hasChunks:
438
457
  return sdkioerrors.Wrap(sdkerrors.ErrUnknownRequest, "Bundle cannot be empty")
458
+ case msg.UncompressedSize < 0:
459
+ return sdkioerrors.Wrap(sdkerrors.ErrUnknownRequest, "Uncompressed size cannot be negative")
460
+ case msg.UncompressedSize == 0 && hasCompressed:
461
+ return sdkioerrors.Wrap(sdkerrors.ErrUnknownRequest, "Uncompressed size must be set with a compressed bundle")
462
+ case msg.UncompressedSize != 0 && hasBundle:
463
+ return sdkioerrors.Wrap(sdkerrors.ErrUnknownRequest, "Uncompressed size cannot be set with a legacy bundle")
464
+ }
465
+ if !hasChunks {
466
+ // We don't check the accuracy of the uncompressed size here, since it could comsume significant CPU.
467
+ return nil
439
468
  }
440
- if len(msg.Bundle) != 0 && len(msg.CompressedBundle) != 0 {
441
- return sdkioerrors.Wrap(sdkerrors.ErrUnknownRequest, "Cannot submit both a compressed and an uncompressed bundle at the same time")
442
- }
443
- if len(msg.Bundle) > 0 && msg.UncompressedSize != 0 {
444
- return sdkioerrors.Wrap(sdkerrors.ErrUnknownRequest, "Uncompressed size cannot be set without a compressed bundle")
445
- }
446
- if len(msg.CompressedBundle) > 0 && !(msg.UncompressedSize > 0) {
447
- return sdkioerrors.Wrap(sdkerrors.ErrUnknownRequest, "Uncompressed size must be positive")
448
- }
449
- if msg.UncompressedSize >= bundleUncompressedSizeLimit {
450
- // must enforce a limit to avoid overflow when computing its successor in Uncompress()
451
- return sdkioerrors.Wrap(sdkerrors.ErrUnknownRequest, "Uncompressed size out of range")
452
- }
453
- // We don't check the accuracy of the uncompressed size here, since it could comsume significant CPU.
454
- return nil
469
+
470
+ // Check that the chunks are valid.
471
+ return msg.ChunkedArtifact.ValidateBasic()
455
472
  }
456
473
 
457
474
  // GetSigners defines whose signature is required
@@ -518,3 +535,96 @@ func (msg *MsgInstallBundle) Uncompress() error {
518
535
  msg.UncompressedSize = 0
519
536
  return nil
520
537
  }
538
+
539
+ func (bc ChunkedArtifact) ValidateBasic() error {
540
+ if len(bc.Chunks) == 0 {
541
+ return sdkioerrors.Wrap(sdkerrors.ErrUnknownRequest, "Bundle chunks cannot be empty")
542
+ }
543
+ if len(bc.Sha512) != sha512.Size*2 {
544
+ return sdkioerrors.Wrapf(sdkerrors.ErrUnknownRequest, "Bundle hash must be %d characters", sha512.Size*2)
545
+ }
546
+ if !IsHexBytes(bc.Sha512) {
547
+ return sdkioerrors.Wrap(sdkerrors.ErrUnknownRequest, "Bundle hash must be a hex byte string")
548
+ }
549
+ var totalSize uint64
550
+ for i, chunk := range bc.Chunks {
551
+ if totalSize > math.MaxUint64-chunk.SizeBytes {
552
+ return sdkioerrors.Wrapf(sdkerrors.ErrUnknownRequest, "bundle size overflows uint64 at chunk %d", i)
553
+ }
554
+ totalSize += chunk.SizeBytes
555
+ if len(chunk.Sha512) != sha512.Size*2 {
556
+ return sdkioerrors.Wrapf(sdkerrors.ErrUnknownRequest, "Chunk %d hash must be %d characters", i, sha512.Size*2)
557
+ }
558
+ if !IsHexBytes(chunk.Sha512) {
559
+ return sdkioerrors.Wrapf(sdkerrors.ErrUnknownRequest, "Chunk %d hash must be a hex byte string", i)
560
+ }
561
+ switch chunk.State {
562
+ case ChunkState_CHUNK_STATE_UNSPECIFIED,
563
+ ChunkState_CHUNK_STATE_IN_FLIGHT,
564
+ ChunkState_CHUNK_STATE_RECEIVED,
565
+ ChunkState_CHUNK_STATE_PROCESSED:
566
+ // valid states
567
+ default:
568
+ return sdkioerrors.Wrapf(sdkerrors.ErrUnknownRequest, "Chunk %d state %s is unrecognized", i, chunk.State.String())
569
+ }
570
+ }
571
+
572
+ if bc.SizeBytes != totalSize {
573
+ return sdkioerrors.Wrapf(sdkerrors.ErrUnknownRequest, "bundle size %d does not match total chunk sizes %d", bc.SizeBytes, totalSize)
574
+ }
575
+ return nil
576
+ }
577
+
578
+ func NewMsgSendChunk(chunkedArtifactId uint64, submitter sdk.AccAddress, chunkIndex uint64, chunkData []byte) *MsgSendChunk {
579
+ return &MsgSendChunk{
580
+ ChunkedArtifactId: chunkedArtifactId,
581
+ Submitter: submitter,
582
+ ChunkIndex: chunkIndex,
583
+ ChunkData: chunkData,
584
+ }
585
+ }
586
+
587
+ // CheckAdmissibility implements the vm.ControllerAdmissionMsg interface.
588
+ func (msg MsgSendChunk) CheckAdmissibility(ctx sdk.Context, data interface{}) error {
589
+ keeper, ok := data.(SwingSetKeeper)
590
+ if !ok {
591
+ return sdkioerrors.Wrapf(sdkerrors.ErrInvalidRequest, "data must be a SwingSetKeeper, not a %T", data)
592
+ }
593
+ beansPerUnit := keeper.GetBeansPerUnit(ctx)
594
+ return chargeAdmission(ctx, keeper, beansPerUnit, msg.Submitter, []string{string(msg.ChunkData)}, uint64(len(msg.ChunkData)))
595
+ }
596
+
597
+ // GetInboundMsgCount implements InboundMsgCarrier.
598
+ func (msg MsgSendChunk) GetInboundMsgCount() int32 {
599
+ return 1
600
+ }
601
+
602
+ // IsHighPriority implements the vm.ControllerAdmissionMsg interface.
603
+ func (msg MsgSendChunk) IsHighPriority(ctx sdk.Context, data interface{}) (bool, error) {
604
+ return false, nil
605
+ }
606
+
607
+ // Route should return the name of the module
608
+ func (msg MsgSendChunk) Route() string { return RouterKey }
609
+
610
+ // Type should return the action
611
+ func (msg MsgSendChunk) Type() string { return "SendChunk" }
612
+
613
+ // ValidateBasic runs stateless checks on the message
614
+ func (msg MsgSendChunk) ValidateBasic() error {
615
+ if msg.ChunkedArtifactId == 0 {
616
+ return sdkioerrors.Wrap(sdkerrors.ErrUnknownRequest, "Chunked artifact id must be positive")
617
+ }
618
+ if msg.Submitter.Empty() {
619
+ return sdkioerrors.Wrap(sdkerrors.ErrInvalidAddress, "Submitter address cannot be empty")
620
+ }
621
+ if len(msg.ChunkData) == 0 {
622
+ return sdkioerrors.Wrap(sdkerrors.ErrUnknownRequest, "Chunk data cannot be empty")
623
+ }
624
+ return nil
625
+ }
626
+
627
+ // GetSigners defines whose signature is required
628
+ func (msg MsgSendChunk) GetSigners() []sdk.AccAddress {
629
+ return []sdk.AccAddress{msg.Submitter}
630
+ }