@shelby-protocol/sdk 0.3.0 → 0.4.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 (126) hide show
  1. package/dist/browser/index.d.ts +19 -10
  2. package/dist/browser/index.mjs +4200 -146
  3. package/dist/core/aptos-explorer.mjs +46 -5
  4. package/dist/core/blobs.mjs +12 -4
  5. package/dist/core/chunk.mjs +58 -9
  6. package/dist/core/clients/ShelbyBlobClient.d.ts +155 -83
  7. package/dist/core/clients/ShelbyBlobClient.mjs +1286 -17
  8. package/dist/core/clients/ShelbyClient.d.ts +39 -6
  9. package/dist/core/clients/ShelbyClient.mjs +3233 -23
  10. package/dist/core/clients/ShelbyClientConfig.d.ts +9 -1
  11. package/dist/core/clients/ShelbyClientConfig.mjs +0 -1
  12. package/dist/core/clients/ShelbyMetadataClient.d.ts +20 -6
  13. package/dist/core/clients/ShelbyMetadataClient.mjs +388 -6
  14. package/dist/core/clients/ShelbyMicropaymentChannelClient.d.ts +7 -7
  15. package/dist/core/clients/ShelbyMicropaymentChannelClient.mjs +894 -13
  16. package/dist/core/clients/ShelbyPlacementGroupClient.mjs +310 -8
  17. package/dist/core/clients/ShelbyRPCClient.d.ts +117 -25
  18. package/dist/core/clients/ShelbyRPCClient.mjs +1245 -12
  19. package/dist/core/clients/index.d.ts +4 -2
  20. package/dist/core/clients/index.mjs +3802 -39
  21. package/dist/core/clients/utils.mjs +65 -6
  22. package/dist/core/commitments.d.ts +12 -1
  23. package/dist/core/commitments.mjs +277 -11
  24. package/dist/core/constants.d.ts +3 -3
  25. package/dist/core/constants.mjs +39 -16
  26. package/dist/core/erasure/clay-codes.mjs +129 -4
  27. package/dist/core/erasure/constants.d.ts +16 -1
  28. package/dist/core/erasure/constants.mjs +48 -11
  29. package/dist/core/erasure/default.mjs +191 -9
  30. package/dist/core/erasure/index.d.ts +1 -1
  31. package/dist/core/erasure/index.mjs +281 -24
  32. package/dist/core/erasure/reed-solomon.mjs +68 -4
  33. package/dist/core/erasure/utils.mjs +0 -2
  34. package/dist/core/errors.d.ts +20 -1
  35. package/dist/core/errors.mjs +58 -8
  36. package/dist/core/index.d.ts +9 -9
  37. package/dist/core/index.mjs +4194 -146
  38. package/dist/core/layout.mjs +37 -5
  39. package/dist/core/networks.mjs +10 -5
  40. package/dist/core/operations/generated/sdk.d.ts +807 -42
  41. package/dist/core/operations/generated/sdk.mjs +267 -18
  42. package/dist/core/operations/index.d.ts +1 -1
  43. package/dist/core/operations/index.mjs +368 -24
  44. package/dist/core/promises.mjs +4 -4
  45. package/dist/core/rpc-responses.d.ts +1 -57
  46. package/dist/core/rpc-responses.mjs +14 -15
  47. package/dist/core/shelby-explorer.mjs +31 -6
  48. package/dist/core/sp/chunk_proof.d.ts +23 -0
  49. package/dist/core/sp/chunk_proof.mjs +113 -0
  50. package/dist/core/sp/index.d.ts +3 -0
  51. package/dist/core/sp/index.mjs +402 -0
  52. package/dist/core/sp/sp_write_client.d.ts +53 -0
  53. package/dist/core/sp/sp_write_client.mjs +302 -0
  54. package/dist/core/strings.mjs +0 -2
  55. package/dist/core/types/blobs.d.ts +24 -5
  56. package/dist/core/types/blobs.mjs +24 -1
  57. package/dist/core/types/index.d.ts +2 -2
  58. package/dist/core/types/index.mjs +275 -10
  59. package/dist/core/types/payments.d.ts +6 -6
  60. package/dist/core/types/payments.mjs +230 -5
  61. package/dist/core/types/placement_groups.mjs +0 -1
  62. package/dist/core/types/storage_providers.d.ts +32 -6
  63. package/dist/core/types/storage_providers.mjs +22 -1
  64. package/dist/core/utils.mjs +94 -8
  65. package/dist/gen/rpc_server_pb.d.ts +295 -0
  66. package/dist/gen/rpc_server_pb.mjs +28 -0
  67. package/dist/node/clients/ShelbyNodeClient.d.ts +2 -0
  68. package/dist/node/clients/ShelbyNodeClient.mjs +3237 -24
  69. package/dist/node/clients/index.d.ts +2 -0
  70. package/dist/node/clients/index.mjs +3236 -26
  71. package/dist/node/index.d.ts +9 -9
  72. package/dist/node/index.mjs +4217 -153
  73. package/dist/node/parallel/commitment_worker.d.ts +9 -0
  74. package/dist/node/parallel/commitment_worker.mjs +85 -0
  75. package/dist/node/parallel/commitment_worker_pool.d.ts +35 -0
  76. package/dist/node/parallel/commitment_worker_pool.mjs +339 -0
  77. package/dist/node/parallel/coverage_flush.d.ts +16 -0
  78. package/dist/node/parallel/coverage_flush.mjs +43 -0
  79. package/dist/node/parallel/default_commitment_worker_pool.d.ts +24 -0
  80. package/dist/node/parallel/default_commitment_worker_pool.mjs +355 -0
  81. package/dist/node/parallel/index.d.ts +12 -0
  82. package/dist/node/parallel/index.mjs +631 -0
  83. package/dist/node/parallel/parallel_commitments.d.ts +32 -0
  84. package/dist/node/parallel/parallel_commitments.mjs +614 -0
  85. package/dist/node/parallel/worker_pool.d.ts +74 -0
  86. package/dist/node/parallel/worker_pool.mjs +301 -0
  87. package/dist/node/testUtil.mjs +8 -4
  88. package/package.json +16 -5
  89. package/dist/chunk-3NRBHSMQ.mjs +0 -12
  90. package/dist/chunk-5BVSWXQJ.mjs +0 -801
  91. package/dist/chunk-6FJNAUU5.mjs +0 -278
  92. package/dist/chunk-6XSZRDLJ.mjs +0 -375
  93. package/dist/chunk-7P6ASYW6.mjs +0 -9
  94. package/dist/chunk-A4IG6GSE.mjs +0 -21
  95. package/dist/chunk-AD2G3QYD.mjs +0 -0
  96. package/dist/chunk-AUQDI5BS.mjs +0 -43
  97. package/dist/chunk-AY3HBWXA.mjs +0 -51
  98. package/dist/chunk-BDSW5PHM.mjs +0 -37
  99. package/dist/chunk-C6RQ3AEU.mjs +0 -51
  100. package/dist/chunk-CQ6QPIZK.mjs +0 -37
  101. package/dist/chunk-D6GQHO6G.mjs +0 -15
  102. package/dist/chunk-EM67QTMR.mjs +0 -0
  103. package/dist/chunk-I6NG5GNL.mjs +0 -8
  104. package/dist/chunk-JTXYKO3U.mjs +0 -38
  105. package/dist/chunk-KG2TMLEV.mjs +0 -207
  106. package/dist/chunk-M3CP5TFP.mjs +0 -39
  107. package/dist/chunk-M7W43K2Q.mjs +0 -505
  108. package/dist/chunk-MB7C7VQF.mjs +0 -0
  109. package/dist/chunk-MNCQBEMS.mjs +0 -55
  110. package/dist/chunk-MQUVYMNQ.mjs +0 -0
  111. package/dist/chunk-NEO7Z3ZQ.mjs +0 -49
  112. package/dist/chunk-NHWWORCH.mjs +0 -72
  113. package/dist/chunk-OEK24ON7.mjs +0 -135
  114. package/dist/chunk-QQ57OGQ2.mjs +0 -0
  115. package/dist/chunk-RNNJXTX2.mjs +0 -154
  116. package/dist/chunk-S6Q4OG7H.mjs +0 -83
  117. package/dist/chunk-TET3DJEO.mjs +0 -199
  118. package/dist/chunk-UEZNZBJO.mjs +0 -104
  119. package/dist/chunk-V46D5NBW.mjs +0 -11
  120. package/dist/chunk-V4B3GAMQ.mjs +0 -42
  121. package/dist/chunk-WFWRBNTW.mjs +0 -412
  122. package/dist/chunk-WTICJPDB.mjs +0 -0
  123. package/dist/chunk-XNEIWM4O.mjs +0 -0
  124. package/dist/chunk-Z4FZ7W6L.mjs +0 -39
  125. package/dist/chunk-Z7RFCADT.mjs +0 -0
  126. package/dist/chunk-ZHXCVRZX.mjs +0 -0
@@ -0,0 +1,631 @@
1
+ // src/node/parallel/worker_pool.ts
2
+ import fs from "fs";
3
+ import path from "path";
4
+ import { fileURLToPath } from "url";
5
+ import { Worker } from "worker_threads";
6
+
7
+ // src/node/parallel/coverage_flush.ts
8
+ import { takeCoverage } from "v8";
9
+ var FLUSH_REQUEST = "__shelby_cov_flush_request__";
10
+ var FLUSH_ACK = "__shelby_cov_flush_ack__";
11
+ var coverageEnabled = () => Boolean(process.env.NODE_V8_COVERAGE);
12
+ var isType = (msg, type) => typeof msg === "object" && msg !== null && msg.type === type;
13
+ function isCoverageFlushMessage(msg) {
14
+ return isType(msg, FLUSH_REQUEST) || isType(msg, FLUSH_ACK);
15
+ }
16
+ function registerWorkerCoverageFlush(port) {
17
+ if (!coverageEnabled() || !port) return;
18
+ port.on("message", (msg) => {
19
+ if (isType(msg, FLUSH_REQUEST)) {
20
+ takeCoverage();
21
+ port.postMessage({ type: FLUSH_ACK });
22
+ }
23
+ });
24
+ }
25
+ function flushWorkerCoverage(worker, timeoutMs = 2e3) {
26
+ if (!coverageEnabled()) return Promise.resolve();
27
+ return new Promise((resolve) => {
28
+ const onMessage = (msg) => {
29
+ if (isType(msg, FLUSH_ACK)) finish();
30
+ };
31
+ const finish = () => {
32
+ clearTimeout(timer);
33
+ worker.off("message", onMessage);
34
+ resolve();
35
+ };
36
+ const timer = setTimeout(finish, timeoutMs);
37
+ worker.on("message", onMessage);
38
+ try {
39
+ worker.postMessage({ type: FLUSH_REQUEST });
40
+ } catch {
41
+ finish();
42
+ }
43
+ });
44
+ }
45
+
46
+ // src/node/parallel/worker_pool.ts
47
+ var WorkerPool = class {
48
+ workers = [];
49
+ queue = [];
50
+ maxWorkers;
51
+ workerPath;
52
+ isTerminating = false;
53
+ activeTasks = /* @__PURE__ */ new Set();
54
+ inFlightCount = 0;
55
+ slotWaiters = [];
56
+ constructor(maxWorkers, workerPath) {
57
+ if (!Number.isSafeInteger(maxWorkers) || maxWorkers < 1) {
58
+ throw new Error(
59
+ `maxWorkers must be a positive safe integer, got ${maxWorkers}`
60
+ );
61
+ }
62
+ this.maxWorkers = maxWorkers;
63
+ this.workerPath = workerPath;
64
+ }
65
+ /**
66
+ * Resolve the path to a worker script relative to the calling module.
67
+ *
68
+ * Pass `import.meta.url` from the subclass file along with the script name
69
+ * (without extension). The extension is inferred from the calling module's
70
+ * own extension so that both the TypeScript source (.ts) and the compiled
71
+ * output (.mjs / .js) are handled correctly.
72
+ *
73
+ * @example
74
+ * constructor(maxWorkers: number) {
75
+ * super(maxWorkers, WorkerPool.resolveWorkerPath(import.meta.url, "my_worker"));
76
+ * }
77
+ */
78
+ static resolveWorkerPath(importMetaUrl, scriptName) {
79
+ const currentPath = fileURLToPath(importMetaUrl);
80
+ const dir = path.dirname(currentPath);
81
+ const ext = path.extname(currentPath);
82
+ const workerExt = ext === ".mjs" ? ".mjs" : ext === ".js" ? ".js" : ".ts";
83
+ if (workerExt === ".ts") {
84
+ const srcSegment = `${path.sep}src${path.sep}`;
85
+ const srcIdx = currentPath.indexOf(srcSegment);
86
+ if (srcIdx !== -1) {
87
+ const packageRoot = currentPath.slice(0, srcIdx);
88
+ const relFromSrc = path.relative(path.join(packageRoot, "src"), dir);
89
+ return path.join(
90
+ packageRoot,
91
+ "dist",
92
+ "workers",
93
+ relFromSrc,
94
+ `${scriptName}.js`
95
+ );
96
+ }
97
+ }
98
+ let workerPath = path.join(dir, `${scriptName}${workerExt}`);
99
+ if (fs.existsSync(workerPath)) {
100
+ return workerPath;
101
+ }
102
+ workerPath = path.join(dir, "workers", `${scriptName}${workerExt}`);
103
+ if (fs.existsSync(workerPath)) {
104
+ return workerPath;
105
+ }
106
+ return path.join(dir, `${scriptName}${workerExt}`);
107
+ }
108
+ initialize() {
109
+ this.isTerminating = false;
110
+ if (!fs.existsSync(this.workerPath)) {
111
+ throw new Error(
112
+ `Could not find worker script at ${this.workerPath}. Running as ${path.extname(this.workerPath)}, expected worker at same extension.`
113
+ );
114
+ }
115
+ for (let i = 0; i < this.maxWorkers; i++) {
116
+ this.workers.push({ worker: new Worker(this.workerPath), busy: false });
117
+ }
118
+ }
119
+ isInitialized() {
120
+ return this.workers.length > 0;
121
+ }
122
+ /**
123
+ * Acquire a back-pressure slot before submitting work to the pool.
124
+ * Resolves immediately if fewer than `maxWorkers` chunksets are in flight;
125
+ * otherwise waits until a slot is released. Callers must call `releaseSlot()`
126
+ * when the submitted task settles (resolve or reject).
127
+ *
128
+ * Moving back-pressure into the pool ensures a single global bound on
129
+ * buffered memory regardless of how many concurrent callers share the pool.
130
+ */
131
+ acquireSlot() {
132
+ if (this.inFlightCount < this.maxWorkers) {
133
+ this.inFlightCount++;
134
+ return Promise.resolve();
135
+ }
136
+ return new Promise((resolve, reject) => {
137
+ this.slotWaiters.push({
138
+ resolve: () => {
139
+ this.inFlightCount++;
140
+ resolve();
141
+ },
142
+ reject
143
+ });
144
+ });
145
+ }
146
+ releaseSlot() {
147
+ this.inFlightCount--;
148
+ const next = this.slotWaiters.shift();
149
+ if (next) {
150
+ next.resolve();
151
+ }
152
+ }
153
+ enqueueTask(task) {
154
+ this.activeTasks.add(task);
155
+ if (this.isTerminating) {
156
+ this.activeTasks.delete(task);
157
+ task.reject(
158
+ new Error("Worker pool is being terminated - cannot process new tasks")
159
+ );
160
+ return;
161
+ }
162
+ const availableWorker = this.workers.find((w) => !w.busy);
163
+ if (availableWorker) {
164
+ this.executeTask(availableWorker, task);
165
+ } else {
166
+ this.queue.push(task);
167
+ }
168
+ }
169
+ processNextQueuedTask(preferredWorker) {
170
+ const nextTask = this.queue.shift();
171
+ if (!nextTask) return;
172
+ if (preferredWorker && !preferredWorker.busy && preferredWorker.worker) {
173
+ this.executeTask(preferredWorker, nextTask);
174
+ return;
175
+ }
176
+ const availableWorker = this.workers.find((w) => !w.busy && w.worker);
177
+ if (availableWorker) {
178
+ this.executeTask(availableWorker, nextTask);
179
+ } else {
180
+ this.queue.unshift(nextTask);
181
+ }
182
+ }
183
+ rejectAllQueuedTasks(error) {
184
+ const tasks = this.queue.splice(0);
185
+ for (const task of tasks) {
186
+ this.activeTasks.delete(task);
187
+ task.reject(error);
188
+ }
189
+ }
190
+ rejectAllActiveTasks(error) {
191
+ const tasks = Array.from(this.activeTasks);
192
+ this.activeTasks.clear();
193
+ for (const task of tasks) {
194
+ task.reject(error);
195
+ }
196
+ }
197
+ executeTask(workerWrapper, task) {
198
+ workerWrapper.busy = true;
199
+ const cleanup = () => {
200
+ workerWrapper.worker.off("message", messageHandler);
201
+ workerWrapper.worker.off("error", errorHandler);
202
+ workerWrapper.worker.off("exit", exitHandler);
203
+ workerWrapper.busy = false;
204
+ };
205
+ const messageHandler = (message) => {
206
+ cleanup();
207
+ this.activeTasks.delete(task);
208
+ if (message.success && message.result !== void 0) {
209
+ task.resolve(message.result);
210
+ } else {
211
+ task.reject(new Error(message.error ?? "Worker processing failed"));
212
+ }
213
+ this.processNextQueuedTask(workerWrapper);
214
+ };
215
+ const errorHandler = (error) => {
216
+ workerWrapper.worker.off("message", messageHandler);
217
+ workerWrapper.worker.off("error", errorHandler);
218
+ workerWrapper.busy = false;
219
+ this.activeTasks.delete(task);
220
+ task.reject(error);
221
+ };
222
+ const exitHandler = (exitCode) => {
223
+ workerWrapper.worker.off("message", messageHandler);
224
+ workerWrapper.worker.off("error", errorHandler);
225
+ workerWrapper.worker.off("exit", exitHandler);
226
+ workerWrapper.busy = false;
227
+ this.activeTasks.delete(task);
228
+ task.reject(
229
+ new Error(`Worker terminated unexpectedly with exit code ${exitCode}`)
230
+ );
231
+ if (this.isTerminating) return;
232
+ try {
233
+ const newWorker = new Worker(this.workerPath);
234
+ if (this.isTerminating) {
235
+ newWorker.terminate().catch(() => {
236
+ });
237
+ return;
238
+ }
239
+ workerWrapper.worker = newWorker;
240
+ this.processNextQueuedTask(workerWrapper);
241
+ } catch (_error) {
242
+ const index = this.workers.indexOf(workerWrapper);
243
+ if (index > -1) this.workers.splice(index, 1);
244
+ if (this.workers.length === 0) {
245
+ this.rejectAllQueuedTasks(
246
+ new Error(
247
+ "All workers have died and could not be replaced - worker pool is non-functional"
248
+ )
249
+ );
250
+ return;
251
+ }
252
+ this.processNextQueuedTask();
253
+ }
254
+ };
255
+ workerWrapper.worker.on("message", messageHandler);
256
+ workerWrapper.worker.on("error", errorHandler);
257
+ workerWrapper.worker.on("exit", exitHandler);
258
+ this.postTaskMessage(workerWrapper.worker, task);
259
+ }
260
+ /**
261
+ * Terminate all workers and reject all pending tasks.
262
+ *
263
+ * This pool is NOT designed to be reused after termination.
264
+ * Create a new instance if a fresh pool is needed.
265
+ */
266
+ async terminate() {
267
+ this.isTerminating = true;
268
+ const terminationError = new Error(
269
+ "Worker pool is being terminated - task cancelled"
270
+ );
271
+ this.rejectAllQueuedTasks(terminationError);
272
+ this.rejectAllActiveTasks(terminationError);
273
+ const waiters = this.slotWaiters.splice(0);
274
+ for (const waiter of waiters) {
275
+ waiter.reject(terminationError);
276
+ }
277
+ const terminatePromises = this.workers.map(async (workerWrapper) => {
278
+ const worker = workerWrapper.worker;
279
+ await flushWorkerCoverage(worker);
280
+ await new Promise((resolve) => {
281
+ let resolved = false;
282
+ const doResolve = () => {
283
+ if (!resolved) {
284
+ resolved = true;
285
+ resolve();
286
+ }
287
+ };
288
+ let timeoutId;
289
+ const exitHandler = () => {
290
+ if (timeoutId) clearTimeout(timeoutId);
291
+ doResolve();
292
+ };
293
+ worker.removeAllListeners("message");
294
+ worker.removeAllListeners("error");
295
+ worker.once("exit", exitHandler);
296
+ timeoutId = setTimeout(() => {
297
+ worker.removeListener("exit", exitHandler);
298
+ doResolve();
299
+ }, 2e3);
300
+ worker.terminate().catch(() => {
301
+ });
302
+ });
303
+ });
304
+ await Promise.all(terminatePromises);
305
+ this.workers = [];
306
+ this.queue = [];
307
+ this.inFlightCount = 0;
308
+ this.isTerminating = false;
309
+ }
310
+ };
311
+
312
+ // src/node/parallel/commitment_worker_pool.ts
313
+ var CommitmentWorkerPool = class extends WorkerPool {
314
+ constructor(maxWorkers) {
315
+ super(
316
+ maxWorkers,
317
+ WorkerPool.resolveWorkerPath(import.meta.url, "commitment_worker")
318
+ );
319
+ }
320
+ postTaskMessage(worker, task) {
321
+ worker.postMessage(
322
+ {
323
+ chunksetData: task.chunksetData,
324
+ encoding: task.encoding
325
+ },
326
+ [task.chunksetData.buffer]
327
+ );
328
+ }
329
+ /**
330
+ * Dispatch a chunkset to a worker for encoding. Returns a promise that
331
+ * resolves to the chunkset's commitment once the worker finishes.
332
+ *
333
+ * The caller must ensure `chunksetData` is not used after this call
334
+ * (its underlying buffer is transferred to the worker thread).
335
+ */
336
+ encodeChunkset(chunksetIdx, chunksetData, encoding) {
337
+ return new Promise((resolve, reject) => {
338
+ const task = {
339
+ chunksetIdx,
340
+ chunksetData,
341
+ encoding,
342
+ resolve,
343
+ reject
344
+ };
345
+ this.enqueueTask(task);
346
+ });
347
+ }
348
+ };
349
+
350
+ // src/node/parallel/default_commitment_worker_pool.ts
351
+ import { availableParallelism } from "os";
352
+ function defaultCommitmentWorkerCount() {
353
+ return Math.max(1, availableParallelism() - 1);
354
+ }
355
+ function createDefaultCommitmentWorkerPool(options = {}) {
356
+ const pool = new CommitmentWorkerPool(
357
+ options.workers ?? defaultCommitmentWorkerCount()
358
+ );
359
+ pool.initialize();
360
+ return pool;
361
+ }
362
+
363
+ // src/node/parallel/parallel_commitments.ts
364
+ import { Hex as Hex3 } from "@aptos-labs/ts-sdk";
365
+
366
+ // src/core/commitments.ts
367
+ import { Hex as Hex2 } from "@aptos-labs/ts-sdk";
368
+ import { z } from "zod";
369
+
370
+ // src/core/erasure/constants.ts
371
+ var ERASURE_CODE_PARAMS = {
372
+ ["ClayCode_16Total_10Data_13Helper" /* ClayCode_16Total_10Data_13Helper */]: {
373
+ // total chunks (data + parity)
374
+ erasure_n: 16,
375
+ // data chunks
376
+ erasure_k: 10,
377
+ // helper nodes
378
+ erasure_d: 13,
379
+ // enum index
380
+ enumIndex: 0
381
+ },
382
+ ["ClayCode_4Total_2Data_3Helper" /* ClayCode_4Total_2Data_3Helper */]: {
383
+ // total chunks (data + parity)
384
+ erasure_n: 4,
385
+ // data chunks
386
+ erasure_k: 2,
387
+ // helper nodes
388
+ erasure_d: 3,
389
+ // enum index
390
+ enumIndex: 1
391
+ }
392
+ };
393
+ var DEFAULT_ERASURE_N = ERASURE_CODE_PARAMS["ClayCode_16Total_10Data_13Helper" /* ClayCode_16Total_10Data_13Helper */].erasure_n;
394
+ var DEFAULT_ERASURE_K = ERASURE_CODE_PARAMS["ClayCode_16Total_10Data_13Helper" /* ClayCode_16Total_10Data_13Helper */].erasure_k;
395
+ var DEFAULT_ERASURE_D = ERASURE_CODE_PARAMS["ClayCode_16Total_10Data_13Helper" /* ClayCode_16Total_10Data_13Helper */].erasure_d;
396
+ var DEFAULT_ERASURE_M = DEFAULT_ERASURE_N - DEFAULT_ERASURE_K;
397
+
398
+ // src/core/chunk.ts
399
+ var CHUNK_SIZE_PARAMS = {
400
+ ["ChunkSet10MiB_Chunk1MiB" /* ChunkSet10MiB_Chunk1MiB */]: {
401
+ // 1MiB
402
+ chunkSizeBytes: 1 * 1024 * 1024,
403
+ // 10MiB
404
+ chunksetSizeBytes: 10 * 1024 * 1024
405
+ },
406
+ ["ChunkSet2MiB_Chunk1MiB" /* ChunkSet2MiB_Chunk1MiB */]: {
407
+ // 1MiB
408
+ chunkSizeBytes: 1 * 1024 * 1024,
409
+ // 2MiB
410
+ chunksetSizeBytes: 2 * 1024 * 1024
411
+ }
412
+ };
413
+ var DEFAULT_CHUNK_SIZE_BYTES = CHUNK_SIZE_PARAMS["ChunkSet10MiB_Chunk1MiB" /* ChunkSet10MiB_Chunk1MiB */].chunkSizeBytes;
414
+ var DEFAULT_CHUNKSET_SIZE_BYTES = CHUNK_SIZE_PARAMS["ChunkSet10MiB_Chunk1MiB" /* ChunkSet10MiB_Chunk1MiB */].chunksetSizeBytes;
415
+ var ERASURE_CODE_AND_CHUNK_MAPPING = {
416
+ ["ClayCode_16Total_10Data_13Helper" /* ClayCode_16Total_10Data_13Helper */]: {
417
+ ...CHUNK_SIZE_PARAMS.ChunkSet10MiB_Chunk1MiB
418
+ },
419
+ ["ClayCode_4Total_2Data_3Helper" /* ClayCode_4Total_2Data_3Helper */]: {
420
+ ...CHUNK_SIZE_PARAMS.ChunkSet2MiB_Chunk1MiB
421
+ }
422
+ };
423
+
424
+ // src/core/utils.ts
425
+ import {
426
+ AccountAddress,
427
+ Hex
428
+ } from "@aptos-labs/ts-sdk";
429
+ async function* readInChunks(input, chunkSize) {
430
+ let idx = 0;
431
+ if (isReadableStream(input)) {
432
+ const reader = input.getReader();
433
+ let buffer = new Uint8Array(chunkSize);
434
+ let bufferWriteOffset = 0;
435
+ try {
436
+ while (true) {
437
+ const { value, done } = await reader.read();
438
+ if (done) break;
439
+ if (value === void 0) continue;
440
+ let srcOffset = 0;
441
+ while (srcOffset < value.length) {
442
+ const remainingCapacity = chunkSize - bufferWriteOffset;
443
+ const bytesToCopy = Math.min(
444
+ remainingCapacity,
445
+ value.length - srcOffset
446
+ );
447
+ buffer.set(
448
+ value.subarray(srcOffset, srcOffset + bytesToCopy),
449
+ bufferWriteOffset
450
+ );
451
+ bufferWriteOffset += bytesToCopy;
452
+ srcOffset += bytesToCopy;
453
+ if (bufferWriteOffset >= chunkSize) {
454
+ yield [idx++, buffer];
455
+ buffer = new Uint8Array(chunkSize);
456
+ bufferWriteOffset = 0;
457
+ }
458
+ }
459
+ }
460
+ } finally {
461
+ reader.releaseLock();
462
+ }
463
+ if (bufferWriteOffset > 0) {
464
+ yield [idx++, buffer.subarray(0, bufferWriteOffset)];
465
+ }
466
+ return;
467
+ }
468
+ const view = toUint8Array(input);
469
+ for (let offset = 0; offset < view.byteLength; offset += chunkSize) {
470
+ yield [
471
+ idx++,
472
+ view.subarray(offset, Math.min(offset + chunkSize, view.byteLength))
473
+ ];
474
+ }
475
+ }
476
+ async function concatHashes(parts) {
477
+ const chunks = parts.map((part) => Hex.fromHexInput(part).toUint8Array());
478
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);
479
+ const combined = new Uint8Array(totalLength);
480
+ let offset = 0;
481
+ for (const chunk of chunks) {
482
+ combined.set(chunk, offset);
483
+ offset += chunk.byteLength;
484
+ }
485
+ return Hex.fromHexInput(
486
+ new Uint8Array(await crypto.subtle.digest("SHA-256", combined))
487
+ );
488
+ }
489
+ function isReadableStream(value) {
490
+ return typeof value === "object" && value !== null && "getReader" in value && typeof value.getReader === "function";
491
+ }
492
+ function toUint8Array(view) {
493
+ return view instanceof Uint8Array ? view : new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
494
+ }
495
+
496
+ // src/core/commitments.ts
497
+ var COMMITMENT_SCHEMA_VERSION = "1.3";
498
+ var ChunksetCommitmentSchema = z.object({
499
+ // Chunkset root (vector commitment of child chunks)
500
+ chunkset_root: z.string(),
501
+ // the size is known statically from the current configuration
502
+ chunk_commitments: z.array(z.string())
503
+ }).refine(
504
+ (data) => {
505
+ return data.chunk_commitments.length === DEFAULT_ERASURE_K + DEFAULT_ERASURE_M;
506
+ },
507
+ {
508
+ message: `Chunkset must have exactly ${DEFAULT_ERASURE_K + DEFAULT_ERASURE_M} chunks (ERASURE_K + ERASURE_M = ${DEFAULT_ERASURE_K} + ${DEFAULT_ERASURE_M})`,
509
+ path: ["chunk_commitments"]
510
+ }
511
+ );
512
+ function expectedTotalChunksets(rawSize, chunksetSize = DEFAULT_CHUNKSET_SIZE_BYTES) {
513
+ if (chunksetSize <= 0) {
514
+ throw new Error("chunksetSize must be positive");
515
+ }
516
+ if (rawSize === 0) return 1;
517
+ return Math.ceil(rawSize / chunksetSize);
518
+ }
519
+ var BlobCommitmentsSchema = z.object({
520
+ schema_version: z.string(),
521
+ raw_data_size: z.number(),
522
+ // FIXME I am not sure about this being here, or if it should be somewhere else
523
+ blob_merkle_root: z.string(),
524
+ chunkset_commitments: z.array(ChunksetCommitmentSchema)
525
+ }).refine(
526
+ (data) => {
527
+ return expectedTotalChunksets(data.raw_data_size) === data.chunkset_commitments.length;
528
+ },
529
+ {
530
+ message: "Total chunkset count mismatches with raw data size",
531
+ // FIXME put more details in here
532
+ path: ["chunkset_commitments"]
533
+ }
534
+ );
535
+ async function generateMerkleRoot(leafHashes) {
536
+ if (!leafHashes.length) {
537
+ throw new Error(
538
+ "An empty array cannot be used to construct a Merkle tree."
539
+ );
540
+ }
541
+ const zeroArray = new Uint8Array(leafHashes[0].toUint8Array().length);
542
+ const zeroBytes = Hex2.fromHexInput(zeroArray);
543
+ let currentLeaves = leafHashes;
544
+ while (currentLeaves.length > 1) {
545
+ if (currentLeaves.length % 2 !== 0) {
546
+ currentLeaves.push(zeroBytes);
547
+ }
548
+ const nextLeaves = [];
549
+ for (let i = 0; i < currentLeaves.length; i += 2) {
550
+ nextLeaves.push(
551
+ await concatHashes([
552
+ currentLeaves[i].toUint8Array(),
553
+ currentLeaves[i + 1].toUint8Array()
554
+ ])
555
+ );
556
+ }
557
+ currentLeaves = nextLeaves;
558
+ }
559
+ return currentLeaves[0];
560
+ }
561
+
562
+ // src/node/parallel/parallel_commitments.ts
563
+ function toCommitmentEncoding(provider) {
564
+ const cfg = provider.config;
565
+ if (typeof cfg.erasure_d !== "number" || typeof cfg.enumIndex !== "number") {
566
+ throw new Error(
567
+ "generateCommitmentsParallel requires a Clay erasure coding provider (erasure_d and enumIndex must be set on provider.config)"
568
+ );
569
+ }
570
+ return {
571
+ erasure_n: cfg.erasure_n,
572
+ erasure_k: cfg.erasure_k,
573
+ erasure_d: cfg.erasure_d,
574
+ chunkSizeBytes: cfg.chunkSizeBytes,
575
+ enumIndex: cfg.enumIndex
576
+ };
577
+ }
578
+ async function generateCommitmentsParallel(provider, data, options) {
579
+ const encoding = toCommitmentEncoding(provider);
580
+ const chunksetSize = encoding.erasure_k * encoding.chunkSizeBytes;
581
+ const ownPool = options?.pool === void 0;
582
+ const pool = options?.pool ?? createDefaultCommitmentWorkerPool({ workers: options?.concurrency });
583
+ if (!pool.isInitialized()) {
584
+ throw new Error(
585
+ "The provided CommitmentWorkerPool has not been initialized. Call pool.initialize() before passing it to generateCommitmentsParallel."
586
+ );
587
+ }
588
+ try {
589
+ const pending = [];
590
+ let rawDataSize = 0;
591
+ for await (const [idx, chunkData] of readInChunks(data, chunksetSize)) {
592
+ rawDataSize += chunkData.length;
593
+ await pool.acquireSlot();
594
+ const copy = new Uint8Array(chunkData);
595
+ const p = pool.encodeChunkset(idx, copy, encoding);
596
+ pending[idx] = p;
597
+ p.then(pool.releaseSlot.bind(pool), pool.releaseSlot.bind(pool));
598
+ }
599
+ if (rawDataSize === 0) {
600
+ pending[0] = pool.encodeChunkset(
601
+ 0,
602
+ new Uint8Array(chunksetSize),
603
+ encoding
604
+ );
605
+ }
606
+ const chunksetCommitments = await Promise.all(pending);
607
+ const chunksetHashes = chunksetCommitments.map(
608
+ (c) => Hex3.fromHexInput(c.chunkset_root)
609
+ );
610
+ return {
611
+ schema_version: COMMITMENT_SCHEMA_VERSION,
612
+ raw_data_size: rawDataSize,
613
+ blob_merkle_root: (await generateMerkleRoot(chunksetHashes)).toString(),
614
+ chunkset_commitments: chunksetCommitments
615
+ };
616
+ } finally {
617
+ if (ownPool) {
618
+ await pool.terminate();
619
+ }
620
+ }
621
+ }
622
+ export {
623
+ CommitmentWorkerPool,
624
+ WorkerPool,
625
+ createDefaultCommitmentWorkerPool,
626
+ defaultCommitmentWorkerCount,
627
+ flushWorkerCoverage,
628
+ generateCommitmentsParallel,
629
+ isCoverageFlushMessage,
630
+ registerWorkerCoverageFlush
631
+ };
@@ -0,0 +1,32 @@
1
+ import { BlobCommitments } from '../../core/commitments.js';
2
+ import { a as ErasureCodingProvider } from '../../clay-codes-DdXABBDx.js';
3
+ import { CommitmentWorkerPool } from './commitment_worker_pool.js';
4
+ import '@aptos-labs/ts-sdk';
5
+ import 'zod';
6
+ import '@shelby-protocol/clay-codes';
7
+ import 'node:worker_threads';
8
+ import './commitment_worker.js';
9
+ import './worker_pool.js';
10
+
11
+ /**
12
+ * Parallel drop-in replacement for `generateCommitments`.
13
+ *
14
+ * Chunksets are dispatched to worker threads as they are read from the stream,
15
+ * so encoding of chunkset N overlaps with reading of chunkset N+1. The final
16
+ * `BlobCommitments` is identical to what `generateCommitments` would produce.
17
+ *
18
+ * @param provider - Erasure coding provider (must be a Clay provider).
19
+ * @param data - Input data as a stream or buffer.
20
+ * @param options.concurrency - Number of worker threads. Defaults to
21
+ * `availableParallelism() - 1` (minimum 1).
22
+ * @param options.pool - A caller-managed `CommitmentWorkerPool`. When provided,
23
+ * the pool is used as-is and is NOT terminated when the function returns —
24
+ * the caller is responsible for calling `pool.terminate()`. When omitted, an
25
+ * internal pool is created and terminated automatically.
26
+ */
27
+ declare function generateCommitmentsParallel(provider: ErasureCodingProvider, data: ReadableStream<Uint8Array> | Uint8Array, options?: {
28
+ concurrency?: number;
29
+ pool?: CommitmentWorkerPool;
30
+ }): Promise<BlobCommitments>;
31
+
32
+ export { generateCommitmentsParallel };