@agoric/cosmos 0.34.1 → 0.34.2-calypso-dev-84eb287.0

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.
Files changed (193) hide show
  1. package/MAINTAINERS.md +3 -0
  2. package/Makefile +67 -41
  3. package/agoric/config.go +35 -0
  4. package/ante/ante.go +65 -0
  5. package/ante/expected_keepers.go +26 -0
  6. package/ante/inbound.go +137 -0
  7. package/ante/inbound_test.go +228 -0
  8. package/ante/vm_admission.go +65 -0
  9. package/app/app.go +396 -211
  10. package/app/export.go +13 -9
  11. package/app/sim_test.go +4 -4
  12. package/app/upgrade.go +215 -0
  13. package/binding.gyp.in +29 -4
  14. package/buf.work.yaml +4 -0
  15. package/cmd/agd/agvm.go +42 -0
  16. package/cmd/agd/find_binary.go +22 -7
  17. package/cmd/agd/main.go +133 -10
  18. package/cmd/libdaemon/main.go +67 -53
  19. package/cmd/libdaemon/main_test.go +37 -0
  20. package/daemon/cmd/genaccounts.go +22 -18
  21. package/daemon/cmd/root.go +253 -52
  22. package/daemon/cmd/root_test.go +190 -2
  23. package/daemon/cmd/testnet.go +17 -6
  24. package/daemon/main.go +6 -3
  25. package/e2e_test/Makefile +29 -0
  26. package/e2e_test/README.md +100 -0
  27. package/e2e_test/go.mod +217 -0
  28. package/e2e_test/go.sum +1323 -0
  29. package/e2e_test/ibc_conformance_test.go +56 -0
  30. package/e2e_test/pfm_test.go +613 -0
  31. package/e2e_test/util.go +271 -0
  32. package/git-revision.txt +1 -0
  33. package/go.mod +207 -0
  34. package/go.sum +1877 -0
  35. package/package.json +13 -21
  36. package/proto/agoric/swingset/genesis.proto +14 -0
  37. package/proto/agoric/swingset/swingset.proto +6 -3
  38. package/proto/agoric/vlocalchain/.clang-format +7 -0
  39. package/proto/agoric/vlocalchain/vlocalchain.proto +31 -0
  40. package/proto/agoric/vstorage/query.proto +53 -1
  41. package/proto/agoric/vtransfer/genesis.proto +18 -0
  42. package/scripts/protocgen.sh +16 -6
  43. package/third_party/proto/buf.yaml +1 -0
  44. package/third_party/proto/cosmos/base/query/v1beta1/pagination.proto +4 -1
  45. package/third_party/proto/cosmos/base/v1beta1/coin.proto +7 -4
  46. package/third_party/proto/cosmos/upgrade/v1beta1/upgrade.proto +16 -6
  47. package/third_party/proto/cosmos_proto/cosmos.proto +97 -0
  48. package/third_party/proto/google/api/annotations.proto +1 -1
  49. package/third_party/proto/google/api/http.proto +181 -120
  50. package/third_party/proto/google/api/httpbody.proto +9 -6
  51. package/third_party/proto/google/protobuf/any.proto +1 -7
  52. package/third_party/proto/ibc/core/channel/v1/channel.proto +15 -1
  53. package/third_party/proto/ibc/core/client/v1/client.proto +9 -6
  54. package/tools/tools.go +11 -0
  55. package/types/events.go +41 -0
  56. package/types/kv_entry.go +114 -0
  57. package/types/kv_entry_helpers.go +276 -0
  58. package/types/kv_entry_helpers_test.go +237 -0
  59. package/types/kv_entry_test.go +143 -0
  60. package/upgradegaia.sh +75 -0
  61. package/vm/action.go +134 -0
  62. package/vm/action_test.go +149 -0
  63. package/vm/client.go +113 -0
  64. package/vm/client_test.go +182 -0
  65. package/vm/controller.go +49 -0
  66. package/vm/core_proposals.go +51 -0
  67. package/vm/jsonrpcconn/jsonrpcconn.go +160 -0
  68. package/vm/jsonrpcconn/jsonrpcconn_test.go +126 -0
  69. package/vm/proto_json.go +38 -0
  70. package/vm/proto_json_test.go +103 -0
  71. package/vm/server.go +124 -0
  72. package/x/swingset/abci.go +26 -37
  73. package/x/swingset/alias.go +9 -6
  74. package/x/swingset/client/cli/query.go +2 -2
  75. package/x/swingset/client/cli/tx.go +52 -33
  76. package/x/swingset/client/proposal_handler.go +2 -17
  77. package/x/swingset/genesis.go +163 -37
  78. package/x/swingset/handler.go +2 -1
  79. package/x/swingset/keeper/extension_snapshotter.go +309 -0
  80. package/x/swingset/keeper/extension_snapshotter_test.go +104 -0
  81. package/x/swingset/keeper/keeper.go +95 -48
  82. package/x/swingset/keeper/keeper_test.go +77 -0
  83. package/x/swingset/keeper/migrations.go +7 -2
  84. package/x/swingset/keeper/msg_server.go +71 -56
  85. package/x/swingset/keeper/proposal.go +15 -9
  86. package/x/swingset/keeper/querier.go +24 -15
  87. package/x/swingset/keeper/swing_store_exports_handler.go +872 -0
  88. package/x/swingset/keeper/swing_store_exports_handler_test.go +247 -0
  89. package/x/swingset/keeper/test_utils.go +16 -0
  90. package/x/swingset/module.go +33 -11
  91. package/x/swingset/proposal_handler.go +5 -4
  92. package/x/swingset/swingset.go +73 -0
  93. package/x/swingset/testing/queue.go +17 -0
  94. package/x/swingset/types/codec.go +2 -2
  95. package/x/swingset/types/default-params.go +23 -17
  96. package/x/swingset/types/expected_keepers.go +14 -2
  97. package/x/swingset/types/genesis.pb.go +361 -18
  98. package/x/swingset/types/msgs.go +87 -26
  99. package/x/swingset/types/msgs.pb.go +16 -16
  100. package/x/swingset/types/params.go +76 -1
  101. package/x/swingset/types/params_test.go +116 -0
  102. package/x/swingset/types/proposal.go +10 -9
  103. package/x/swingset/types/swingset.pb.go +83 -81
  104. package/x/swingset/types/types.go +30 -28
  105. package/x/vbank/genesis.go +0 -2
  106. package/x/vbank/handler.go +2 -1
  107. package/x/vbank/keeper/keeper.go +3 -2
  108. package/x/vbank/keeper/querier.go +9 -4
  109. package/x/vbank/keeper/rewards.go +1 -1
  110. package/x/vbank/module.go +0 -5
  111. package/x/vbank/types/msgs.go +0 -12
  112. package/x/vbank/vbank.go +34 -32
  113. package/x/vbank/vbank_test.go +20 -20
  114. package/x/vibc/alias.go +3 -0
  115. package/x/vibc/handler.go +17 -15
  116. package/x/vibc/keeper/keeper.go +113 -89
  117. package/x/vibc/keeper/triggers.go +101 -0
  118. package/x/vibc/module.go +5 -8
  119. package/x/vibc/types/expected_keepers.go +28 -6
  120. package/x/vibc/types/ibc_module.go +336 -0
  121. package/x/vibc/types/msgs.go +1 -1
  122. package/x/vibc/types/msgs.pb.go +1 -1
  123. package/x/vibc/types/receiver.go +170 -0
  124. package/x/vlocalchain/alias.go +19 -0
  125. package/x/vlocalchain/handler.go +21 -0
  126. package/x/vlocalchain/keeper/keeper.go +279 -0
  127. package/x/vlocalchain/keeper/keeper_test.go +97 -0
  128. package/x/vlocalchain/types/codec.go +34 -0
  129. package/x/vlocalchain/types/key.go +27 -0
  130. package/x/vlocalchain/types/msgs.go +16 -0
  131. package/x/vlocalchain/types/vlocalchain.pb.go +1072 -0
  132. package/x/vlocalchain/vlocalchain.go +114 -0
  133. package/x/vlocalchain/vlocalchain_test.go +434 -0
  134. package/x/vstorage/README.md +138 -0
  135. package/x/vstorage/capdata/capdata.go +298 -0
  136. package/x/vstorage/capdata/capdata_test.go +352 -0
  137. package/x/vstorage/client/cli/query.go +51 -4
  138. package/x/vstorage/genesis.go +0 -3
  139. package/x/vstorage/handler.go +2 -1
  140. package/x/vstorage/keeper/grpc_query.go +220 -0
  141. package/x/vstorage/keeper/keeper.go +75 -57
  142. package/x/vstorage/keeper/keeper_grpc_test.go +300 -0
  143. package/x/vstorage/keeper/keeper_test.go +40 -62
  144. package/x/vstorage/keeper/querier.go +39 -14
  145. package/x/vstorage/keeper/querier_test.go +113 -0
  146. package/x/vstorage/module.go +0 -5
  147. package/x/vstorage/testing/queue.go +27 -0
  148. package/x/vstorage/types/path_keys.go +22 -10
  149. package/x/vstorage/types/path_keys_test.go +84 -18
  150. package/x/vstorage/types/query.pb.go +646 -36
  151. package/x/vstorage/types/query.pb.gw.go +119 -0
  152. package/x/vstorage/types/types.go +0 -66
  153. package/x/vstorage/vstorage.go +33 -35
  154. package/x/vstorage/vstorage_test.go +19 -19
  155. package/x/vtransfer/alias.go +13 -0
  156. package/x/vtransfer/genesis.go +39 -0
  157. package/x/vtransfer/genesis_test.go +12 -0
  158. package/x/vtransfer/handler.go +20 -0
  159. package/x/vtransfer/ibc_middleware.go +186 -0
  160. package/x/vtransfer/ibc_middleware_test.go +448 -0
  161. package/x/vtransfer/keeper/keeper.go +281 -0
  162. package/x/vtransfer/module.go +124 -0
  163. package/x/vtransfer/types/expected_keepers.go +38 -0
  164. package/x/vtransfer/types/genesis.pb.go +327 -0
  165. package/x/vtransfer/types/key.go +9 -0
  166. package/x/vtransfer/types/msgs.go +9 -0
  167. package/app/const.go +0 -6
  168. package/cmd/helper/main.go +0 -21
  169. package/proto/agoric/lien/genesis.proto +0 -25
  170. package/proto/agoric/lien/lien.proto +0 -25
  171. package/x/lien/alias.go +0 -17
  172. package/x/lien/genesis.go +0 -58
  173. package/x/lien/genesis_test.go +0 -101
  174. package/x/lien/keeper/account.go +0 -285
  175. package/x/lien/keeper/keeper.go +0 -254
  176. package/x/lien/keeper/keeper_test.go +0 -623
  177. package/x/lien/lien.go +0 -203
  178. package/x/lien/lien_test.go +0 -529
  179. package/x/lien/module.go +0 -115
  180. package/x/lien/spec/01_concepts.md +0 -146
  181. package/x/lien/spec/02_messages.md +0 -96
  182. package/x/lien/types/accountkeeper.go +0 -81
  183. package/x/lien/types/accountstate.go +0 -27
  184. package/x/lien/types/expected_keepers.go +0 -18
  185. package/x/lien/types/genesis.pb.go +0 -567
  186. package/x/lien/types/key.go +0 -25
  187. package/x/lien/types/lien.pb.go +0 -403
  188. package/x/swingset/keeper/snapshotter.go +0 -491
  189. package/x/swingset/keeper/snapshotter_test.go +0 -185
  190. package/x/swingset/legacy/v32/params.go +0 -37
  191. package/x/swingset/legacy/v32/params_test.go +0 -133
  192. package/x/vibc/ibc.go +0 -442
  193. /package/{src/index.cjs → index.cjs} +0 -0
@@ -0,0 +1,872 @@
1
+ package keeper
2
+
3
+ import (
4
+ "encoding/json"
5
+ "errors"
6
+ "fmt"
7
+ "io"
8
+ "os"
9
+ "path/filepath"
10
+ "regexp"
11
+
12
+ sdkioerrors "cosmossdk.io/errors"
13
+ agoric "github.com/Agoric/agoric-sdk/golang/cosmos/types"
14
+ "github.com/Agoric/agoric-sdk/golang/cosmos/vm"
15
+ "github.com/Agoric/agoric-sdk/golang/cosmos/x/swingset/types"
16
+ "github.com/tendermint/tendermint/libs/log"
17
+ )
18
+
19
+ // This module abstracts the generation and handling of swing-store exports,
20
+ // including the communication with the JS side to generate and restore them.
21
+ //
22
+ // Its interface derives from the following requirements:
23
+ // - Multiple golang components may perform swing-store export or import
24
+ // operations, but the JS side does not support concurrent operations as
25
+ // there are no legitimate use cases.
26
+ // - Some components cannot block the main execution while performing an export
27
+ // operation. In particular, cosmos's state-sync snapshot process cannot
28
+ // block the logic handling tendermint events.
29
+ // - The JS swing-store cannot access historical states. To generate
30
+ // deterministic exports, the export operations that cannot block must be able
31
+ // to synchronize with commit points that will change the JS swing-store.
32
+ // - The JS swing-store export logic does however support mutation of the
33
+ // JS swing-store state after an export operation has started. Such mutations
34
+ // do not affect the export that is produced, and can span multiple blocks.
35
+ // - This implies the commit synchronization is only necessary until the JS
36
+ // side of the export operation has started.
37
+ // - Some components, in particular state-sync, may need to perform other work
38
+ // alongside generating a swing-store export. This work similarly cannot block
39
+ // the main execution, but must allow for the swing-store synchronization
40
+ // that enables generating deterministic export. For state-sync, this work
41
+ // happens before the generated swing-store export can be consumed.
42
+ //
43
+ // The general approach taken is to implement a SwingStoreExportsHandler that
44
+ // implements the communication with the JS side, enforces that no concurrent
45
+ // operations take place, defers the consumption of the export to a provided
46
+ // SwingStoreExportEventHandler, and provides some synchronization methods to
47
+ // let the application enforce mutation boundaries.
48
+ //
49
+ // There should be a single SwingStoreExportsHandler instance, and all its method
50
+ // calls should be performed from the same goroutine (no mutex enforcement).
51
+ //
52
+ // The process of generating a SwingStore export proceeds as follow:
53
+ // - The component invokes swingStoreExportsHandler.InitiateExport with an
54
+ // eventHandler for the export.
55
+ // - InitiateExport verifies no other export operation is in progress and
56
+ // starts a goroutine to perform the export operation. It requests the JS
57
+ // side to start generating an export of the swing-store, and calls the
58
+ // eventHandler's OnExportStarted method with a function param allowing it to
59
+ // retrieve the export.
60
+ // - The cosmos app will call WaitUntilSwingStoreExportStarted before
61
+ // instructing the JS controller to commit its work, satisfying the
62
+ // deterministic exports requirement.
63
+ // - OnExportStarted must call the retrieve function before returning, however
64
+ // it may perform other work before. For cosmos state-sync snapshots,
65
+ // OnExportStarted will call app.Snapshot which will invoke the swingset
66
+ // module's ExtensionSnapshotter that will retrieve and process the
67
+ // swing-store export.
68
+ // - When the retrieve function is called, it blocks until the JS export is
69
+ // ready, then creates a SwingStoreExportProvider that abstract accessing
70
+ // the content of the export. The eventHandler's OnExportRetrieved is called
71
+ // with the export provider.
72
+ // - OnExportRetrieved reads the export using the provider.
73
+ //
74
+ // Restoring a swing-store export does not have similar non-blocking requirements.
75
+ // The component simply invokes swingStoreExportsHandler.RestoreExport with a
76
+ // SwingStoreExportProvider representing the swing-store export to
77
+ // be restored, and RestoreExport will consume it and block until the JS side
78
+ // has completed the restore before returning.
79
+
80
+ // exportManifest represents the content of the JS swing-store export manifest.
81
+ // The export is exchanged between Cosmos and JS using the file system, and only
82
+ // the directory containing the export is exchanged with a blockingSend. The
83
+ // manifest is a JSON file with the agreed upon file name of
84
+ // "export-manifest.json" in the export directory. It contains the file names
85
+ // for the "export data" (described in the godoc for exportDataFilename), and
86
+ // for the opaque artifacts of the export.
87
+ type exportManifest struct {
88
+ // BlockHeight is the block height of the manifest.
89
+ BlockHeight uint64 `json:"blockHeight,omitempty"`
90
+ // Data is the filename of the export data.
91
+ Data string `json:"data,omitempty"`
92
+ // Artifacts is the list of [artifact name, file name] pairs.
93
+ Artifacts [][2]string `json:"artifacts"`
94
+ }
95
+
96
+ // ExportManifestFilename is the manifest filename which must be synchronized with the JS export/import tooling
97
+ // See packages/cosmic-swingset/src/export-kernel-db.js and packages/cosmic-swingset/src/import-kernel-db.js
98
+ const ExportManifestFilename = "export-manifest.json"
99
+
100
+ // For restore operations, the swing-store "export data" is exchanged with the
101
+ // JS side as a file which encodes "export data" entries as a sequence of
102
+ // [key, value] JSON arrays each terminated by a new line.
103
+ // NB: this is not technically jsonlines since the entries are new line
104
+ // terminated instead of being new line separated, however the parsers in both
105
+ // JS and golang handle such extra whitespace.
106
+ const exportDataFilename = "export-data.jsonl"
107
+
108
+ // UntrustedExportDataArtifactName is a special artifact name that the provider
109
+ // and consumer of an export can use to indicate the presence of a synthetic
110
+ // artifact containing untrusted "export data". This artifact must not end up in
111
+ // the list of artifacts imported by the JS import tooling (which would fail).
112
+ const UntrustedExportDataArtifactName = "UNTRUSTED-EXPORT-DATA"
113
+ const untrustedExportDataFilename = "untrusted-export-data.jsonl"
114
+
115
+ const exportedFilesMode = 0644
116
+
117
+ // swingStoreExportActionType is the action type used for all swing-store
118
+ // export blockingSend, and synchronized with the JS side in
119
+ // packages/internal/src/action-types.js
120
+ const swingStoreExportActionType = "SWING_STORE_EXPORT"
121
+
122
+ // initiateRequest is the request type for initiating an export
123
+ const initiateRequest = "initiate"
124
+
125
+ type swingStoreInitiateExportAction struct {
126
+ Type string `json:"type"` // "SWING_STORE_EXPORT"
127
+ Request string `json:"request"` // "initiate"
128
+ BlockHeight uint64 `json:"blockHeight,omitempty"` // empty if no blockHeight requested (latest)
129
+ Args [1]SwingStoreExportOptions `json:"args"`
130
+ }
131
+
132
+ // retrieveRequest is the request type for retrieving an initiated export
133
+ const retrieveRequest = "retrieve"
134
+
135
+ type swingStoreRetrieveExportAction struct {
136
+ Type string `json:"type"` // "SWING_STORE_EXPORT"
137
+ Request string `json:"request"` // "retrieve"
138
+ }
139
+ type swingStoreRetrieveResult = string
140
+
141
+ // discardRequest is the request type for discarding an initiated but an export
142
+ // that was not retrieved
143
+ const discardRequest = "discard"
144
+
145
+ type swingStoreDiscardExportAction struct {
146
+ Type string `json:"type"` // "SWING_STORE_EXPORT"
147
+ Request string `json:"request"` // "discard"
148
+ }
149
+
150
+ // restoreRequest is the request type for restoring an export
151
+ const restoreRequest = "restore"
152
+
153
+ type swingStoreRestoreExportAction struct {
154
+ Type string `json:"type"` // "SWING_STORE_EXPORT"
155
+ Request string `json:"request"` // "restore"
156
+ BlockHeight uint64 `json:"blockHeight,omitempty"` // empty if deferring blockHeight to the manifest
157
+ Args [1]swingStoreImportOptions `json:"args"`
158
+ }
159
+
160
+ const (
161
+ // SwingStoreArtifactModeNone means that no artifacts are part of the
162
+ // export / import.
163
+ SwingStoreArtifactModeNone = "none"
164
+
165
+ // SwingStoreArtifactModeOperational represents the minimal set of artifacts
166
+ // needed to operate a node.
167
+ SwingStoreArtifactModeOperational = "operational"
168
+
169
+ // SwingStoreArtifactModeReplay represents the set of artifacts needed to
170
+ // replay the current incarnation of every vat.
171
+ SwingStoreArtifactModeReplay = "replay"
172
+
173
+ // SwingStoreArtifactModeArchival represents the set of all artifacts
174
+ // providing all available historical state.
175
+ SwingStoreArtifactModeArchival = "archival"
176
+
177
+ // SwingStoreArtifactModeDebug represents the maximal set of artifacts
178
+ // available in the JS swing-store, including any kept around for debugging
179
+ // purposes only (like previous XS heap snapshots)
180
+ SwingStoreArtifactModeDebug = "debug"
181
+ )
182
+
183
+ const (
184
+ // SwingStoreExportDataModeSkip indicates "export data" should be excluded from
185
+ // an export. ArtifactMode cannot be "none" in this case.
186
+ SwingStoreExportDataModeSkip = "skip"
187
+
188
+ // SwingStoreExportDataModeRepairMetadata indicates the "export data" should be
189
+ // used to repair the metadata of an existing swing-store for an import
190
+ // operation. ArtifactMode must be "none" in this case.
191
+ SwingStoreExportDataModeRepairMetadata = "repair-metadata"
192
+
193
+ // SwingStoreExportDataModeAll indicates "export data" should be part of the
194
+ // export or import. For import, ArtifactMode cannot be "none".
195
+ SwingStoreExportDataModeAll = "all"
196
+ )
197
+
198
+ // SwingStoreExportOptions are configurable options provided to the JS swing-store export
199
+ type SwingStoreExportOptions struct {
200
+ // ArtifactMode controls the set of artifacts that should be included in the
201
+ // swing-store export. Any SwingStoreArtifactMode* const value can be used
202
+ // (None, Operational, Replay, Archival, Debug).
203
+ // See packages/cosmic-swingset/src/export-kernel-db.js initiateSwingStoreExport
204
+ ArtifactMode string `json:"artifactMode,omitempty"`
205
+ // ExportDataMode selects whether to include "export data" in the swing-store
206
+ // export or not. Use the value SwingStoreExportDataModeSkip or
207
+ // SwingStoreExportDataModeAll. If "skip", the reader returned by
208
+ // SwingStoreExportProvider's GetExportDataReader will be nil.
209
+ ExportDataMode string `json:"exportDataMode,omitempty"`
210
+ }
211
+
212
+ // SwingStoreRestoreOptions are configurable options provided to the JS swing-store import
213
+ type SwingStoreRestoreOptions struct {
214
+ // ArtifactMode controls the set of artifacts that should be restored in
215
+ // swing-store. Any SwingStoreArtifactMode* const value can be used
216
+ // (None, Operational, Replay, Archival, Debug).
217
+ // See packages/cosmic-swingset/src/import-kernel-db.js performStateSyncImport
218
+ ArtifactMode string `json:"artifactMode,omitempty"`
219
+ // ExportDataMode selects the purpose of the restore, to recreate a
220
+ // swing-store (SwingStoreExportDataModeAll), or just to import missing
221
+ // metadata (SwingStoreExportDataModeRepairMetadata).
222
+ // If RepairMetadata, ArtifactMode should be SwingStoreArtifactModeNone.
223
+ // If All, ArtifactMode must be at least SwingStoreArtifactModeOperational.
224
+ ExportDataMode string `json:"exportDataMode,omitempty"`
225
+ }
226
+
227
+ type swingStoreImportOptions struct {
228
+ // ExportDir is the directory created by RestoreExport that JS swing-store
229
+ // should import from.
230
+ ExportDir string `json:"exportDir"`
231
+ // ArtifactMode is a copy of SwingStoreRestoreOptions.ArtifactMode
232
+ ArtifactMode string `json:"artifactMode,omitempty"`
233
+ // ExportDataMode is a copy of SwingStoreRestoreOptions.ExportDataMode
234
+ ExportDataMode string `json:"exportDataMode,omitempty"`
235
+ }
236
+
237
+ var disallowedArtifactNameChar = regexp.MustCompile(`[^-_.a-zA-Z0-9]`)
238
+
239
+ // sanitizeArtifactName searches a string for all characters
240
+ // other than ASCII alphanumerics, hyphens, underscores, and dots,
241
+ // and replaces each of them with a hyphen.
242
+ func sanitizeArtifactName(name string) string {
243
+ return disallowedArtifactNameChar.ReplaceAllString(name, "-")
244
+ }
245
+
246
+ type operationDetails struct {
247
+ // isRestore indicates whether the operation in progress is a restore.
248
+ // It is assigned at creation and never mutated.
249
+ isRestore bool
250
+ // blockHeight is the block height of this in-progress operation.
251
+ // It is assigned at creation and never mutated.
252
+ blockHeight uint64
253
+ // logger is the destination for this operation's log messages.
254
+ // It is assigned at creation and never mutated.
255
+ logger log.Logger
256
+ // exportStartedResult is used to synchronize the commit boundary by the
257
+ // component performing the export operation to ensure export determinism.
258
+ // unused for restore operations
259
+ // It is assigned at creation and never mutated. The started goroutine
260
+ // writes into the channel and closes it. The main goroutine reads from the
261
+ // channel.
262
+ exportStartedResult chan error
263
+ // exportRetrieved is an internal flag indicating whether the JS generated
264
+ // export was retrieved. It can be false regardless of the component's
265
+ // eventHandler reporting an error or not. It is only indicative of whether
266
+ // the component called retrieveExport, and used to control whether to send
267
+ // a discard request if the JS side stayed responsible for the generated but
268
+ // un-retrieved export.
269
+ // It is only read or written by the export operation's goroutine.
270
+ exportRetrieved bool
271
+ // exportDone is a channel that is closed when the active export operation
272
+ // is complete.
273
+ // It is assigned at creation and never mutated. The started goroutine
274
+ // writes into the channel and closes it. The main goroutine reads from the
275
+ // channel.
276
+ exportDone chan error
277
+ }
278
+
279
+ // activeOperation is a global variable reflecting a swing-store import or
280
+ // export in progress on the JS side.
281
+ // This variable is only assigned to through calls of the public methods of
282
+ // SwingStoreExportsHandler, which rely on the exportDone channel getting
283
+ // closed to nil this variable.
284
+ // Only the calls to InitiateExport and RestoreExport set this to a non-nil
285
+ // value. The goroutine in which these calls occur is referred to as the
286
+ // "main goroutine". That goroutine may be different over time, but it's the
287
+ // caller's responsibility to ensure those goroutines do not overlap calls to
288
+ // the SwingStoreExportsHandler public methods.
289
+ // See also the details of each field for the conditions under which they are
290
+ // accessed.
291
+ var activeOperation *operationDetails
292
+
293
+ // WaitUntilSwingStoreExportStarted synchronizes with an export operation in
294
+ // progress, if any.
295
+ // The JS swing-store export must have started before a new block is committed
296
+ // to ensure the content of the export is the one expected. The app must call
297
+ // this method before sending a commit action to the JS controller.
298
+ //
299
+ // Waits for a just initiated export operation to have started in its goroutine.
300
+ // If no operation is in progress (InitiateExport hasn't been called or
301
+ // already completed), or if we previously checked if the operation had started,
302
+ // returns immediately.
303
+ //
304
+ // Must be called by the main goroutine
305
+ func WaitUntilSwingStoreExportStarted() error {
306
+ operationDetails := activeOperation
307
+ if operationDetails == nil {
308
+ return nil
309
+ }
310
+ // Block until the active operation has started, saving the result.
311
+ // The operation's goroutine only produces a value in case of an error,
312
+ // and closes the channel once the export has started or failed.
313
+ // Only the first call after an export was initiated will report an error.
314
+ startErr := <-operationDetails.exportStartedResult
315
+
316
+ // Check if the active export operation is done, and if so, nil it out so
317
+ // future calls are faster.
318
+ select {
319
+ case <-operationDetails.exportDone:
320
+ // If there was a start error, the channel is already closed at this point.
321
+ activeOperation = nil
322
+ default:
323
+ // don't wait for it to finish
324
+ // If there is no start error, the operation may take an arbitrary amount
325
+ // of time to terminate, likely spanning multiple blocks. However this
326
+ // function will only ever observe the expected activeOperation since the
327
+ // internal checkNotActive() called immediately on InitiateSnapshot will
328
+ // nil-out activeOperation if a stale value was sill sitting around.
329
+ }
330
+
331
+ return startErr
332
+ }
333
+
334
+ // WaitUntilSwingStoreExportDone synchronizes with the completion of an export
335
+ // operation in progress, if any.
336
+ // Only a single swing-store operation may execute at a time. Calling
337
+ // InitiateExport or RestoreExport will fail if a swing-store operation is
338
+ // already in progress. Furthermore, a component may need to know once an
339
+ // export it initiated has completed. Once this method call returns, the
340
+ // goroutine is guaranteed to have terminated, and the SwingStoreExportEventHandler
341
+ // provided to InitiateExport to no longer be in use.
342
+ //
343
+ // Reports any error that may have occurred from InitiateExport.
344
+ // If no export operation is in progress (InitiateExport hasn't been called or
345
+ // already completed), or if we previously checked if an export had completed,
346
+ // returns immediately.
347
+ //
348
+ // Must be called by the main goroutine
349
+ func WaitUntilSwingStoreExportDone() error {
350
+ operationDetails := activeOperation
351
+ if operationDetails == nil {
352
+ return nil
353
+ }
354
+ // Block until the active export has completed.
355
+ // The export operation's goroutine only produces a value in case of an error,
356
+ // and closes the channel once the export has completed or failed.
357
+ // Only the first call after an export was initiated will report an error.
358
+ exportErr := <-operationDetails.exportDone
359
+ activeOperation = nil
360
+
361
+ return exportErr
362
+ }
363
+
364
+ // checkNotActive returns an error if there is an active operation.
365
+ //
366
+ // Always internally called by the main goroutine
367
+ func checkNotActive() error {
368
+ operationDetails := activeOperation
369
+ if operationDetails != nil {
370
+ select {
371
+ case <-operationDetails.exportDone:
372
+ // nil-out any stale operation
373
+ activeOperation = nil
374
+ default:
375
+ if operationDetails.isRestore {
376
+ return fmt.Errorf("restore operation already in progress for height %d", operationDetails.blockHeight)
377
+ } else {
378
+ return fmt.Errorf("export operation already in progress for height %d", operationDetails.blockHeight)
379
+ }
380
+ }
381
+ }
382
+ return nil
383
+ }
384
+
385
+ // SwingStoreExportProvider gives access to a SwingStore "export data" and the
386
+ // related artifacts.
387
+ // A JS swing-store export is composed of optional "export data" (a set of
388
+ // key/value pairs), and opaque artifacts (a name and data as bytes) that
389
+ // complement the "export data".
390
+ // The abstraction is similar to the JS side swing-store export abstraction,
391
+ // but without the ability to list artifacts or random access them.
392
+ //
393
+ // A swing-store export for creating a state-sync snapshot will not contain any
394
+ // "export data" since this information is reflected every block into the
395
+ // verified cosmos DB.
396
+ // On state-sync snapshot restore, the swingset ExtensionSnapshotter will
397
+ // synthesize a provider for this module with "export data" sourced from the
398
+ // restored cosmos DB, and artifacts from the extension's payloads. When
399
+ // importing, the JS swing-store will verify that the artifacts match hashes
400
+ // contained in the trusted "export data".
401
+ type SwingStoreExportProvider struct {
402
+ // BlockHeight is the block height of the SwingStore export.
403
+ BlockHeight uint64
404
+ // GetExportDataReader returns a KVEntryReader for the "export data" of the
405
+ // SwingStore export, or nil if the "export data" is not part of this export.
406
+ GetExportDataReader func() (agoric.KVEntryReader, error)
407
+ // ReadNextArtifact is a function to return the next unread artifact in the SwingStore export.
408
+ // It errors with io.EOF upon reaching the end of the list of available artifacts.
409
+ ReadNextArtifact func() (types.SwingStoreArtifact, error)
410
+ }
411
+
412
+ // SwingStoreExportEventHandler is used to handle events that occur while generating
413
+ // a swing-store export. It is provided to SwingStoreExportsHandler.InitiateExport.
414
+ type SwingStoreExportEventHandler interface {
415
+ // OnExportStarted is called by InitiateExport in a goroutine after the
416
+ // swing-store export has successfully started.
417
+ // This is where the component performing the export must initiate its own
418
+ // off main goroutine work, which results in retrieving and processing the
419
+ // swing-store export.
420
+ //
421
+ // Must call the retrieveExport function before returning, which will in turn
422
+ // synchronously invoke OnExportRetrieved once the swing-store export is ready.
423
+ OnExportStarted(blockHeight uint64, retrieveExport func() error) error
424
+ // OnExportRetrieved is called when the swing-store export has been retrieved,
425
+ // during the retrieveExport invocation.
426
+ // The provider is not a return value to retrieveExport in order to
427
+ // report errors in components that are unable to propagate errors back to the
428
+ // OnExportStarted result, like cosmos state-sync ExtensionSnapshotter.
429
+ // The implementation must synchronously consume the provider, which becomes
430
+ // invalid after the method returns.
431
+ OnExportRetrieved(provider SwingStoreExportProvider) error
432
+ }
433
+
434
+ // SwingStoreExportsHandler exclusively manages the communication with the JS side
435
+ // related to swing-store exports, ensuring insensitivity to sub-block timing,
436
+ // and enforcing concurrency requirements.
437
+ // The caller of this submodule must arrange block level commit synchronization,
438
+ // to ensure the results are deterministic.
439
+ //
440
+ // Some blockingSend calls performed by this submodule are non-deterministic.
441
+ // This submodule will send messages to JS from goroutines at unpredictable
442
+ // times, but this is safe because when handling the messages, the JS side
443
+ // does not perform operations affecting consensus and ignores state changes
444
+ // since committing the previous block.
445
+ // Some other blockingSend calls however do change the JS swing-store and
446
+ // must happen before the Swingset controller on the JS side was inited, in
447
+ // which case the mustNotBeInited parameter will be set to true.
448
+ type SwingStoreExportsHandler struct {
449
+ logger log.Logger
450
+ blockingSend func(action vm.Jsonable, mustNotBeInited bool) (string, error)
451
+ }
452
+
453
+ // NewSwingStoreExportsHandler creates a SwingStoreExportsHandler
454
+ func NewSwingStoreExportsHandler(logger log.Logger, blockingSend func(action vm.Jsonable, mustNotBeInited bool) (string, error)) *SwingStoreExportsHandler {
455
+ return &SwingStoreExportsHandler{
456
+ logger: logger.With("module", fmt.Sprintf("x/%s", types.ModuleName), "submodule", "SwingStoreExportsHandler"),
457
+ blockingSend: blockingSend,
458
+ }
459
+ }
460
+
461
+ // InitiateExport synchronously verifies that there is not already an export or
462
+ // import operation in progress and initiates a new export in a goroutine,
463
+ // via a dedicated SWING_STORE_EXPORT blockingSend action independent of other
464
+ // block related blockingSends, calling the given eventHandler when a related
465
+ // blockingSend completes. If the eventHandler doesn't retrieve the export,
466
+ // then it sends another blockingSend action to discard it.
467
+ //
468
+ // eventHandler is invoked solely from the spawned goroutine.
469
+ // The "started" and "done" events can be used for synchronization with an
470
+ // active operation taking place in the goroutine, by calling respectively the
471
+ // WaitUntilSwingStoreExportStarted and WaitUntilSwingStoreExportDone methods
472
+ // from the goroutine that initiated the export.
473
+ //
474
+ // Must be called by the main goroutine
475
+ func (exportsHandler SwingStoreExportsHandler) InitiateExport(blockHeight uint64, eventHandler SwingStoreExportEventHandler, exportOptions SwingStoreExportOptions) error {
476
+ err := checkNotActive()
477
+ if err != nil {
478
+ return err
479
+ }
480
+
481
+ var logger log.Logger
482
+ if blockHeight != 0 {
483
+ logger = exportsHandler.logger.With("height", blockHeight)
484
+ } else {
485
+ logger = exportsHandler.logger.With("height", "latest")
486
+ }
487
+
488
+ // Indicate that an export operation has been initiated by setting the global
489
+ // activeOperation var.
490
+ // This structure is used to synchronize with the goroutine spawned below.
491
+ operationDetails := &operationDetails{
492
+ blockHeight: blockHeight,
493
+ logger: logger,
494
+ exportStartedResult: make(chan error, 1),
495
+ exportRetrieved: false,
496
+ exportDone: make(chan error, 1),
497
+ }
498
+ activeOperation = operationDetails
499
+
500
+ go func() {
501
+ var err error
502
+ var startedErr error
503
+ defer func() {
504
+ if err == nil {
505
+ err = startedErr
506
+ }
507
+ if err != nil {
508
+ operationDetails.exportDone <- err
509
+ }
510
+ // First, indicate an export is no longer in progress. This ensures that
511
+ // for an operation with a start error, a call to WaitUntilSwingStoreExportStarted
512
+ // waiting on exportStartedResult will always find the operation has
513
+ // completed, and clear the active operation instead of racing if the
514
+ // channel close order was reversed.
515
+ close(operationDetails.exportDone)
516
+ // Then signal the current export operation that it failed to start,
517
+ // which will be reported to a waiting WaitUntilSwingStoreExportStarted,
518
+ // or the next call otherwise.
519
+ if startedErr != nil {
520
+ operationDetails.exportStartedResult <- startedErr
521
+ close(operationDetails.exportStartedResult)
522
+ }
523
+ }()
524
+
525
+ initiateAction := &swingStoreInitiateExportAction{
526
+ Type: swingStoreExportActionType,
527
+ BlockHeight: blockHeight,
528
+ Request: initiateRequest,
529
+ Args: [1]SwingStoreExportOptions{exportOptions},
530
+ }
531
+
532
+ // blockingSend for SWING_STORE_EXPORT action is safe to call from a goroutine
533
+ _, startedErr = exportsHandler.blockingSend(initiateAction, false)
534
+
535
+ if startedErr != nil {
536
+ logger.Error("failed to initiate swing-store export", "err", startedErr)
537
+ // The deferred function will communicate the error and close channels
538
+ // in the appropriate order.
539
+ return
540
+ }
541
+
542
+ // Signal that the export operation has started successfully in the goroutine.
543
+ // Calls to WaitUntilSwingStoreExportStarted will no longer block.
544
+ close(operationDetails.exportStartedResult)
545
+
546
+ // The user provided OnExportStarted function should call retrieveExport()
547
+ var retrieveErr error
548
+ err = eventHandler.OnExportStarted(blockHeight, func() error {
549
+ activeOperationDetails := activeOperation
550
+ if activeOperationDetails != operationDetails || operationDetails.exportRetrieved {
551
+ // shouldn't happen, but return an error if it does
552
+ return errors.New("export operation no longer active")
553
+ }
554
+
555
+ retrieveErr = exportsHandler.retrieveExport(eventHandler.OnExportRetrieved)
556
+
557
+ return retrieveErr
558
+ })
559
+
560
+ // Restore any retrieve error swallowed by OnExportStarted
561
+ if err == nil {
562
+ err = retrieveErr
563
+ }
564
+ if err != nil {
565
+ logger.Error("failed to process swing-store export", "err", err)
566
+ }
567
+
568
+ // Check whether the JS generated export was retrieved by eventHandler
569
+ if operationDetails.exportRetrieved {
570
+ return
571
+ }
572
+
573
+ // Discarding the export so invalidate retrieveExport
574
+ operationDetails.exportRetrieved = true
575
+
576
+ discardAction := &swingStoreDiscardExportAction{
577
+ Type: swingStoreExportActionType,
578
+ Request: discardRequest,
579
+ }
580
+ _, discardErr := exportsHandler.blockingSend(discardAction, false)
581
+
582
+ if discardErr != nil {
583
+ logger.Error("failed to discard swing-store export", "err", err)
584
+ }
585
+
586
+ if err == nil {
587
+ err = discardErr
588
+ } else if discardErr != nil {
589
+ // Safe to wrap error and use detailed error info since this error
590
+ // will not go back into swingset layers
591
+ err = sdkioerrors.Wrapf(err, "failed to discard swing-store export after failing to process export: %+v", discardErr)
592
+ }
593
+ }()
594
+
595
+ return nil
596
+ }
597
+
598
+ // retrieveExport retrieves an initiated export then invokes onExportRetrieved
599
+ // with the retrieved export.
600
+ //
601
+ // It performs a SWING_STORE_EXPORT blockingSend which on success returns a
602
+ // string of the directory containing the JS swing-store export. It then reads
603
+ // the export manifest generated by the JS side, and synthesizes a
604
+ // SwingStoreExportProvider for the onExportRetrieved callback to access the
605
+ // retrieved swing-store export.
606
+ // The export manifest format is described by the exportManifest struct.
607
+ //
608
+ // After calling onExportRetrieved, the export directory and its contents are
609
+ // deleted.
610
+ //
611
+ // This will block until the export is ready. Internally invoked by the
612
+ // InitiateExport logic in the export operation's goroutine.
613
+ func (exportsHandler SwingStoreExportsHandler) retrieveExport(onExportRetrieved func(provider SwingStoreExportProvider) error) (err error) {
614
+ operationDetails := activeOperation
615
+ if operationDetails == nil {
616
+ // shouldn't happen, but return an error if it does
617
+ return errors.New("no active swing-store export operation")
618
+ }
619
+
620
+ blockHeight := operationDetails.blockHeight
621
+
622
+ action := &swingStoreRetrieveExportAction{
623
+ Type: swingStoreExportActionType,
624
+ Request: retrieveRequest,
625
+ }
626
+ out, err := exportsHandler.blockingSend(action, false)
627
+
628
+ if err != nil {
629
+ return err
630
+ }
631
+ operationDetails.exportRetrieved = true
632
+
633
+ var exportDir swingStoreRetrieveResult
634
+ err = json.Unmarshal([]byte(out), &exportDir)
635
+ if err != nil {
636
+ return err
637
+ }
638
+
639
+ defer os.RemoveAll(exportDir)
640
+
641
+ provider, err := OpenSwingStoreExportDirectory(exportDir)
642
+ if err != nil {
643
+ return err
644
+ }
645
+
646
+ if blockHeight != 0 && provider.BlockHeight != blockHeight {
647
+ return fmt.Errorf("export manifest blockHeight (%d) doesn't match (%d)", provider.BlockHeight, blockHeight)
648
+ }
649
+
650
+ err = onExportRetrieved(provider)
651
+ if err != nil {
652
+ return err
653
+ }
654
+
655
+ operationDetails.logger.Info("retrieved swing-store export", "exportDir", exportDir)
656
+
657
+ return nil
658
+ }
659
+
660
+ // OpenSwingStoreExportDirectory creates an export provider from a swing-store
661
+ // export saved on disk in the provided directory. It expects the export manifest
662
+ // to be present in that directory. The provider's function will read the
663
+ // export's data and artifacts from disk on demand. Each artifact is using a
664
+ // dedicated file, and the export data is read from a jsonl-like file, if any.
665
+ // The export manifest filename and overall export format is common with the JS
666
+ // swing-store import/export logic.
667
+ func OpenSwingStoreExportDirectory(exportDir string) (SwingStoreExportProvider, error) {
668
+ rawManifest, err := os.ReadFile(filepath.Join(exportDir, ExportManifestFilename))
669
+ if err != nil {
670
+ return SwingStoreExportProvider{}, err
671
+ }
672
+
673
+ var manifest exportManifest
674
+ err = json.Unmarshal(rawManifest, &manifest)
675
+ if err != nil {
676
+ return SwingStoreExportProvider{}, err
677
+ }
678
+
679
+ getExportDataReader := func() (agoric.KVEntryReader, error) {
680
+ if manifest.Data == "" {
681
+ return nil, nil
682
+ }
683
+
684
+ dataFile, err := os.Open(filepath.Join(exportDir, manifest.Data))
685
+ if err != nil {
686
+ return nil, err
687
+ }
688
+ exportDataReader := agoric.NewJsonlKVEntryDecoderReader(dataFile)
689
+ return exportDataReader, nil
690
+ }
691
+
692
+ nextArtifact := 0
693
+
694
+ readNextArtifact := func() (artifact types.SwingStoreArtifact, err error) {
695
+ if nextArtifact == len(manifest.Artifacts) {
696
+ return artifact, io.EOF
697
+ } else if nextArtifact > len(manifest.Artifacts) {
698
+ return artifact, fmt.Errorf("exceeded expected artifact count: %d > %d", nextArtifact, len(manifest.Artifacts))
699
+ }
700
+
701
+ artifactEntry := manifest.Artifacts[nextArtifact]
702
+ nextArtifact++
703
+
704
+ artifactName := artifactEntry[0]
705
+ fileName := artifactEntry[1]
706
+ if artifactName == UntrustedExportDataArtifactName {
707
+ return artifact, fmt.Errorf("unexpected export artifact name %s", artifactName)
708
+ }
709
+ artifact.Name = artifactName
710
+ artifact.Data, err = os.ReadFile(filepath.Join(exportDir, fileName))
711
+
712
+ return artifact, err
713
+ }
714
+
715
+ return SwingStoreExportProvider{BlockHeight: manifest.BlockHeight, GetExportDataReader: getExportDataReader, ReadNextArtifact: readNextArtifact}, nil
716
+ }
717
+
718
+ // RestoreExport restores the JS swing-store using previously exported data and artifacts.
719
+ //
720
+ // Must be called by the main goroutine
721
+ func (exportsHandler SwingStoreExportsHandler) RestoreExport(provider SwingStoreExportProvider, restoreOptions SwingStoreRestoreOptions) error {
722
+ err := checkNotActive()
723
+ if err != nil {
724
+ return err
725
+ }
726
+
727
+ blockHeight := provider.BlockHeight
728
+
729
+ // We technically don't need to create an active operation here since both
730
+ // InitiateExport and RestoreExport should only be called from the main
731
+ // goroutine, but it doesn't cost much to add in case things go wrong.
732
+ operationDetails := &operationDetails{
733
+ isRestore: true,
734
+ blockHeight: blockHeight,
735
+ logger: exportsHandler.logger,
736
+ // goroutine synchronization is unnecessary since anything checking should
737
+ // be called from the same goroutine.
738
+ // Effectively WaitUntilSwingStoreExportStarted would block infinitely and
739
+ // exportsHandler.InitiateExport will error when calling checkNotActive.
740
+ exportStartedResult: nil,
741
+ exportDone: nil,
742
+ }
743
+ activeOperation = operationDetails
744
+ defer func() {
745
+ activeOperation = nil
746
+ }()
747
+
748
+ exportDir, err := os.MkdirTemp("", fmt.Sprintf("agd-swing-store-restore-%d-*", blockHeight))
749
+ if err != nil {
750
+ return err
751
+ }
752
+ defer os.RemoveAll(exportDir)
753
+
754
+ exportsHandler.logger.Info("creating swing-store restore", "exportDir", exportDir, "height", blockHeight)
755
+
756
+ err = WriteSwingStoreExportToDirectory(provider, exportDir)
757
+ if err != nil {
758
+ return err
759
+ }
760
+
761
+ exportsHandler.logger.Info("restoring swing-store", "exportDir", exportDir, "height", blockHeight)
762
+
763
+ action := &swingStoreRestoreExportAction{
764
+ Type: swingStoreExportActionType,
765
+ BlockHeight: blockHeight,
766
+ Request: restoreRequest,
767
+ Args: [1]swingStoreImportOptions{{
768
+ ExportDir: exportDir,
769
+ ArtifactMode: restoreOptions.ArtifactMode,
770
+ ExportDataMode: restoreOptions.ExportDataMode,
771
+ }},
772
+ }
773
+
774
+ _, err = exportsHandler.blockingSend(action, true)
775
+ if err != nil {
776
+ return err
777
+ }
778
+
779
+ exportsHandler.logger.Info("restored swing-store", "exportDir", exportDir, "height", blockHeight)
780
+
781
+ return nil
782
+ }
783
+
784
+ // WriteSwingStoreExportToDirectory consumes a provider and saves a swing-store
785
+ // export to disk in the provided directory. It creates files for each artifact
786
+ // deriving a filename from the artifact name, and stores any "export data" in
787
+ // a jsonl-like file, before saving the export manifest linking these together.
788
+ // The export manifest filename and overall export format is common with the JS
789
+ // swing-store import/export logic.
790
+ func WriteSwingStoreExportToDirectory(provider SwingStoreExportProvider, exportDir string) (err error) {
791
+ handleDeferError := func(fn func() error) {
792
+ deferError := fn()
793
+ if err == nil {
794
+ err = deferError
795
+ } else if deferError != nil {
796
+ // Safe to wrap error and use detailed error info since this error
797
+ // will not go back into swingset layers
798
+ err = sdkioerrors.Wrapf(err, "deferred error %+v", deferError)
799
+ }
800
+ }
801
+
802
+ manifest := exportManifest{
803
+ BlockHeight: provider.BlockHeight,
804
+ }
805
+
806
+ exportDataReader, err := provider.GetExportDataReader()
807
+ if err != nil {
808
+ return err
809
+ }
810
+
811
+ if exportDataReader != nil {
812
+ defer handleDeferError(exportDataReader.Close)
813
+
814
+ manifest.Data = exportDataFilename
815
+ exportDataFile, err := os.OpenFile(filepath.Join(exportDir, exportDataFilename), os.O_CREATE|os.O_WRONLY, exportedFilesMode)
816
+ if err != nil {
817
+ return err
818
+ }
819
+ defer handleDeferError(exportDataFile.Close)
820
+
821
+ err = agoric.EncodeKVEntryReaderToJsonl(exportDataReader, exportDataFile)
822
+ if err != nil {
823
+ return err
824
+ }
825
+
826
+ err = exportDataFile.Sync()
827
+ if err != nil {
828
+ return err
829
+ }
830
+ }
831
+
832
+ writeExportFile := func(filename string, data []byte) error {
833
+ return os.WriteFile(filepath.Join(exportDir, filename), data, exportedFilesMode)
834
+ }
835
+
836
+ for {
837
+ artifact, err := provider.ReadNextArtifact()
838
+ if err == io.EOF {
839
+ break
840
+ } else if err != nil {
841
+ return err
842
+ }
843
+
844
+ if artifact.Name != UntrustedExportDataArtifactName {
845
+ // An artifact is only verifiable by the JS swing-store import using the
846
+ // information contained in the "export data".
847
+ // Since we cannot trust the source of the artifact at this point,
848
+ // including that the artifact's name is genuine, we generate a safe and
849
+ // unique filename from the artifact's name we received, by substituting
850
+ // any non letters-digits-hyphen-underscore-dot by a hyphen, and
851
+ // prefixing with an incremented id.
852
+ // The filename is not used for any purpose in the import logic.
853
+ filename := sanitizeArtifactName(artifact.Name)
854
+ filename = fmt.Sprintf("%d-%s", len(manifest.Artifacts), filename)
855
+ manifest.Artifacts = append(manifest.Artifacts, [2]string{artifact.Name, filename})
856
+ err = writeExportFile(filename, artifact.Data)
857
+ } else {
858
+ // Pseudo artifact containing untrusted export data which may have been
859
+ // saved separately for debugging purposes (not referenced from the manifest)
860
+ err = writeExportFile(untrustedExportDataFilename, artifact.Data)
861
+ }
862
+ if err != nil {
863
+ return err
864
+ }
865
+ }
866
+
867
+ manifestBytes, err := json.MarshalIndent(manifest, "", " ")
868
+ if err != nil {
869
+ return err
870
+ }
871
+ return writeExportFile(ExportManifestFilename, manifestBytes)
872
+ }