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