@zhoujun_aptos/octopus-ts-sdk-min 0.22.4 → 0.22.6

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 (95) hide show
  1. package/dist/common/index.d.ts +966 -0
  2. package/dist/common/index.js +4491 -0
  3. package/dist/common/index.js.map +1 -0
  4. package/dist/esm/index.d.mts +966 -0
  5. package/dist/esm/index.mjs +4449 -0
  6. package/dist/esm/index.mjs.map +1 -0
  7. package/package.json +22 -8
  8. package/dist/elgamal.d.ts +0 -31
  9. package/dist/elgamal.d.ts.map +0 -1
  10. package/dist/elgamal.js +0 -96
  11. package/dist/elgamal.js.map +0 -1
  12. package/dist/enc/index.d.ts +0 -42
  13. package/dist/enc/index.d.ts.map +0 -1
  14. package/dist/enc/index.js +0 -211
  15. package/dist/enc/index.js.map +0 -1
  16. package/dist/enc/simple_elgamal_ristretto255.d.ts +0 -28
  17. package/dist/enc/simple_elgamal_ristretto255.d.ts.map +0 -1
  18. package/dist/enc/simple_elgamal_ristretto255.js +0 -173
  19. package/dist/enc/simple_elgamal_ristretto255.js.map +0 -1
  20. package/dist/group.d.ts +0 -39
  21. package/dist/group.d.ts.map +0 -1
  22. package/dist/group.js +0 -165
  23. package/dist/group.js.map +0 -1
  24. package/dist/ibe/index.d.ts +0 -54
  25. package/dist/ibe/index.d.ts.map +0 -1
  26. package/dist/ibe/index.js +0 -280
  27. package/dist/ibe/index.js.map +0 -1
  28. package/dist/ibe/otp_hmac_boneh_franklin_bls12381_short_pk.d.ts +0 -38
  29. package/dist/ibe/otp_hmac_boneh_franklin_bls12381_short_pk.d.ts.map +0 -1
  30. package/dist/ibe/otp_hmac_boneh_franklin_bls12381_short_pk.js +0 -155
  31. package/dist/ibe/otp_hmac_boneh_franklin_bls12381_short_pk.js.map +0 -1
  32. package/dist/index.d.ts +0 -13
  33. package/dist/index.d.ts.map +0 -1
  34. package/dist/index.js +0 -50
  35. package/dist/index.js.map +0 -1
  36. package/dist/shamir_gf256.d.ts +0 -61
  37. package/dist/shamir_gf256.d.ts.map +0 -1
  38. package/dist/shamir_gf256.js +0 -295
  39. package/dist/shamir_gf256.js.map +0 -1
  40. package/dist/sig/index.d.ts +0 -42
  41. package/dist/sig/index.d.ts.map +0 -1
  42. package/dist/sig/index.js +0 -212
  43. package/dist/sig/index.js.map +0 -1
  44. package/dist/sig/schnorr_ristretto255.d.ts +0 -29
  45. package/dist/sig/schnorr_ristretto255.d.ts.map +0 -1
  46. package/dist/sig/schnorr_ristretto255.js +0 -142
  47. package/dist/sig/schnorr_ristretto255.js.map +0 -1
  48. package/dist/silent_setup_encryption.d.ts +0 -93
  49. package/dist/silent_setup_encryption.d.ts.map +0 -1
  50. package/dist/silent_setup_encryption.js +0 -342
  51. package/dist/silent_setup_encryption.js.map +0 -1
  52. package/dist/silent_setup_encryption_xchain/aptos.d.ts +0 -40
  53. package/dist/silent_setup_encryption_xchain/aptos.d.ts.map +0 -1
  54. package/dist/silent_setup_encryption_xchain/aptos.js +0 -125
  55. package/dist/silent_setup_encryption_xchain/aptos.js.map +0 -1
  56. package/dist/silent_setup_encryption_xchain/index.d.ts +0 -116
  57. package/dist/silent_setup_encryption_xchain/index.d.ts.map +0 -1
  58. package/dist/silent_setup_encryption_xchain/index.js +0 -471
  59. package/dist/silent_setup_encryption_xchain/index.js.map +0 -1
  60. package/dist/silent_setup_encryption_xchain/solana.d.ts +0 -42
  61. package/dist/silent_setup_encryption_xchain/solana.d.ts.map +0 -1
  62. package/dist/silent_setup_encryption_xchain/solana.js +0 -145
  63. package/dist/silent_setup_encryption_xchain/solana.js.map +0 -1
  64. package/dist/sym/aes256gcm.d.ts +0 -27
  65. package/dist/sym/aes256gcm.d.ts.map +0 -1
  66. package/dist/sym/aes256gcm.js +0 -107
  67. package/dist/sym/aes256gcm.js.map +0 -1
  68. package/dist/sym/index.d.ts +0 -27
  69. package/dist/sym/index.d.ts.map +0 -1
  70. package/dist/sym/index.js +0 -154
  71. package/dist/sym/index.js.map +0 -1
  72. package/dist/threshold-ibe/aptos.d.ts +0 -42
  73. package/dist/threshold-ibe/aptos.d.ts.map +0 -1
  74. package/dist/threshold-ibe/aptos.js +0 -324
  75. package/dist/threshold-ibe/aptos.js.map +0 -1
  76. package/dist/threshold-ibe/index.d.ts +0 -147
  77. package/dist/threshold-ibe/index.d.ts.map +0 -1
  78. package/dist/threshold-ibe/index.js +0 -453
  79. package/dist/threshold-ibe/index.js.map +0 -1
  80. package/dist/threshold-ibe/solana.d.ts +0 -38
  81. package/dist/threshold-ibe/solana.d.ts.map +0 -1
  82. package/dist/threshold-ibe/solana.js +0 -197
  83. package/dist/threshold-ibe/solana.js.map +0 -1
  84. package/dist/utils.d.ts +0 -12
  85. package/dist/utils.d.ts.map +0 -1
  86. package/dist/utils.js +0 -130
  87. package/dist/utils.js.map +0 -1
  88. package/dist/worker_config.d.ts +0 -30
  89. package/dist/worker_config.d.ts.map +0 -1
  90. package/dist/worker_config.js +0 -142
  91. package/dist/worker_config.js.map +0 -1
  92. package/dist/worker_task.d.ts +0 -29
  93. package/dist/worker_task.d.ts.map +0 -1
  94. package/dist/worker_task.js +0 -178
  95. package/dist/worker_task.js.map +0 -1
@@ -0,0 +1,4491 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ ElGamal: () => elgamal_exports,
34
+ Enc: () => enc_exports,
35
+ Group: () => group_exports,
36
+ IBE: () => ibe_exports,
37
+ Sig: () => sig_exports,
38
+ SilentSetupEncryption: () => silent_setup_encryption_exports,
39
+ SilentSetupEncryptionXChain: () => silent_setup_encryption_xchain_exports,
40
+ Sym: () => sym_exports,
41
+ ThresholdIbe: () => threshold_ibe_exports,
42
+ Utils: () => utils_exports,
43
+ WorkerConfig: () => worker_config_exports,
44
+ WorkerTask: () => WorkerTask
45
+ });
46
+ module.exports = __toCommonJS(index_exports);
47
+
48
+ // src/elgamal.ts
49
+ var elgamal_exports = {};
50
+ __export(elgamal_exports, {
51
+ Ciphertext: () => Ciphertext,
52
+ DecKey: () => DecKey,
53
+ EncKey: () => EncKey,
54
+ dec: () => dec,
55
+ enc: () => enc,
56
+ multiExp: () => multiExp
57
+ });
58
+ var import_ts_sdk3 = require("@aptos-labs/ts-sdk");
59
+
60
+ // src/group.ts
61
+ var group_exports = {};
62
+ __export(group_exports, {
63
+ Element: () => Element,
64
+ Scalar: () => Scalar,
65
+ msm: () => msm,
66
+ scalarFrom512BitHash: () => scalarFrom512BitHash
67
+ });
68
+ var import_ts_sdk2 = require("@aptos-labs/ts-sdk");
69
+ var import_ed25519 = require("@noble/curves/ed25519");
70
+ var import_utils = require("@noble/curves/utils");
71
+
72
+ // src/utils.ts
73
+ var utils_exports = {};
74
+ __export(utils_exports, {
75
+ CONTRACT_ADDRESS_HEX: () => CONTRACT_ADDRESS_HEX,
76
+ SHELBYNET_CONTRACT_ADDRESS_HEX: () => SHELBYNET_CONTRACT_ADDRESS_HEX,
77
+ concatBytes: () => concatBytes,
78
+ getAptosConfig: () => getAptosConfig,
79
+ hmac_sha3_256: () => hmac_sha3_256,
80
+ kdf: () => kdf,
81
+ randBytes: () => randBytes,
82
+ sha3_256: () => sha3_256,
83
+ sha3_512: () => sha3_512,
84
+ xorBytes: () => xorBytes
85
+ });
86
+ var import_gas_station_client = require("@aptos-labs/gas-station-client");
87
+ var import_ts_sdk = require("@aptos-labs/ts-sdk");
88
+ var import_sha3 = require("@noble/hashes/sha3");
89
+ var CONTRACT_ADDRESS_HEX = "0x114f3ad54703b5afb48d596103253fdfeed121e131edb83a25dfed6cb92b73ed";
90
+ var SHELBYNET_CONTRACT_ADDRESS_HEX = "0xaa5c09269872b767ebe0dad214fc02dc9f00074380d05ff78cbcf4a1c49e0e62";
91
+ function randBytes(length) {
92
+ if (typeof crypto !== "undefined" && crypto.getRandomValues) {
93
+ return crypto.getRandomValues(new Uint8Array(length));
94
+ }
95
+ const bytes = new Uint8Array(length);
96
+ for (let i = 0; i < length; i++) {
97
+ bytes[i] = Math.floor(Math.random() * 256);
98
+ }
99
+ return bytes;
100
+ }
101
+ function xorBytes(blinder, plaintext) {
102
+ if (blinder.length != plaintext.length) {
103
+ throw new Error("Blinder and plaintext must be the same length");
104
+ }
105
+ return new Uint8Array(blinder.map((byte, index) => byte ^ plaintext[index]));
106
+ }
107
+ function concatBytes(a, b) {
108
+ const result = new Uint8Array(a.length + b.length);
109
+ result.set(a, 0);
110
+ result.set(b, a.length);
111
+ return result;
112
+ }
113
+ var KeyBlockDeriveInput = class {
114
+ seed;
115
+ dst;
116
+ targetLength;
117
+ blockIndex;
118
+ constructor(seed, dst, targetLength, blockIndex) {
119
+ this.seed = seed;
120
+ this.dst = dst;
121
+ this.targetLength = targetLength;
122
+ this.blockIndex = blockIndex;
123
+ }
124
+ serialize(serializer) {
125
+ serializer.serializeBytes(this.seed);
126
+ serializer.serializeBytes(this.dst);
127
+ serializer.serializeU64(this.targetLength);
128
+ serializer.serializeU64(this.blockIndex);
129
+ }
130
+ toBytes() {
131
+ const serializer = new import_ts_sdk.Serializer();
132
+ this.serialize(serializer);
133
+ return serializer.toUint8Array();
134
+ }
135
+ };
136
+ function kdf(seed, dst, targetLength) {
137
+ if (seed.length < 32) {
138
+ throw new Error("Seed must be at least 32 bytes");
139
+ }
140
+ let blockPreImage = new KeyBlockDeriveInput(seed, dst, targetLength, 0);
141
+ let output = new Uint8Array(0);
142
+ while (targetLength > 0) {
143
+ let blockOutput = new Uint8Array(sha3_256(blockPreImage.toBytes()).slice(0, Math.min(32, targetLength)));
144
+ output = concatBytes(output, blockOutput);
145
+ targetLength -= blockOutput.length;
146
+ blockPreImage.blockIndex++;
147
+ }
148
+ return output;
149
+ }
150
+ function hmac_sha3_256(key, message) {
151
+ if (key.length !== 32) {
152
+ throw new Error("Key must be 32 bytes");
153
+ }
154
+ key = concatBytes(key, new Uint8Array(32));
155
+ let ipad = new Uint8Array(64);
156
+ let opad = new Uint8Array(64);
157
+ for (let i = 0; i < 64; i++) {
158
+ ipad[i] = 54;
159
+ opad[i] = 92;
160
+ }
161
+ const innerInput = concatBytes(xorBytes(ipad, key), message);
162
+ const outerInput = concatBytes(xorBytes(opad, key), sha3_256(innerInput));
163
+ return sha3_256(outerInput);
164
+ }
165
+ function sha3_256(message) {
166
+ return (0, import_sha3.sha3_256)(message);
167
+ }
168
+ function sha3_512(message) {
169
+ return (0, import_sha3.sha3_512)(message);
170
+ }
171
+ function getAptosConfig(networkName) {
172
+ if (networkName === "testnet") {
173
+ return new import_ts_sdk.AptosConfig({
174
+ network: import_ts_sdk.Network.TESTNET,
175
+ clientConfig: {
176
+ API_KEY: "AG-AQYQBGCUUXENJVPK8S6BQXSKXLFP7WN6U"
177
+ },
178
+ pluginSettings: { TRANSACTION_SUBMITTER: new import_gas_station_client.GasStationTransactionSubmitter({
179
+ network: import_ts_sdk.Network.TESTNET,
180
+ apiKey: "aptoslabs_UjL29oi1TsS_88HcxKLRWoDssNhLCfiasWygcioZP9MFn"
181
+ }) }
182
+ });
183
+ } else if (networkName === "shelbynet") {
184
+ return new import_ts_sdk.AptosConfig({
185
+ network: import_ts_sdk.Network.CUSTOM,
186
+ clientConfig: {
187
+ API_KEY: "AG-CTZKWQBKTBHPRZBDDTF6YWNTQ7MKSA1ZE"
188
+ },
189
+ pluginSettings: { TRANSACTION_SUBMITTER: new import_gas_station_client.GasStationTransactionSubmitter({
190
+ network: import_ts_sdk.Network.CUSTOM,
191
+ apiKey: "aptoslabs_BMhkGMQWaPj_7GLMCrSRKR34fYeESUAR82QfscPkVgtvb",
192
+ baseUrl: "https://api.shelbynet.shelby.xyz/gs/v1"
193
+ }) },
194
+ fullnode: "https://api.shelbynet.shelby.xyz/v1"
195
+ });
196
+ } else {
197
+ throw new Error(`Unsupported network name: ${networkName}`);
198
+ }
199
+ }
200
+
201
+ // src/group.ts
202
+ var Q = BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed");
203
+ var Element = class _Element {
204
+ bytes;
205
+ constructor(bytes) {
206
+ this.bytes = bytes;
207
+ }
208
+ static dummy() {
209
+ return new _Element(new Uint8Array(32));
210
+ }
211
+ static fromInner(inner) {
212
+ const compressed = true;
213
+ const bytes = inner.toRawBytes(compressed);
214
+ return new _Element(bytes);
215
+ }
216
+ static groupIdentity() {
217
+ return _Element.fromInner(import_ed25519.RistrettoPoint.ZERO);
218
+ }
219
+ static rand() {
220
+ const randomBytes2 = randBytes(64);
221
+ const point = import_ed25519.RistrettoPoint.hashToCurve(randomBytes2);
222
+ return _Element.fromInner(point);
223
+ }
224
+ static deserialize(deserializer) {
225
+ const bytes = deserializer.deserializeBytes();
226
+ return new _Element(bytes);
227
+ }
228
+ static fromBytes(bytes) {
229
+ const deserializer = new import_ts_sdk2.Deserializer(bytes);
230
+ const ret = _Element.deserialize(deserializer);
231
+ if (deserializer.remaining() !== 0) {
232
+ throw new Error("Invalid element bytes");
233
+ }
234
+ return ret;
235
+ }
236
+ serialize(serializer) {
237
+ serializer.serializeBytes(this.bytes);
238
+ }
239
+ toBytes() {
240
+ const serializer = new import_ts_sdk2.Serializer();
241
+ this.serialize(serializer);
242
+ return serializer.toUint8Array();
243
+ }
244
+ toHex() {
245
+ return (0, import_utils.bytesToHex)(this.toBytes());
246
+ }
247
+ asInner() {
248
+ return import_ed25519.RistrettoPoint.fromHex(this.bytes);
249
+ }
250
+ add(other) {
251
+ const pointA = this.asInner();
252
+ const pointB = other.asInner();
253
+ const result = pointA.add(pointB);
254
+ return _Element.fromInner(result);
255
+ }
256
+ sub(other) {
257
+ const pointA = this.asInner();
258
+ const pointB = other.asInner();
259
+ const result = pointA.subtract(pointB);
260
+ return _Element.fromInner(result);
261
+ }
262
+ scale(scalar) {
263
+ if (scalar.isZero()) {
264
+ return _Element.groupIdentity();
265
+ }
266
+ const point = this.asInner();
267
+ const s = (0, import_utils.bytesToNumberLE)(scalar.bytes);
268
+ const result = point.multiply(s);
269
+ return _Element.fromInner(result);
270
+ }
271
+ };
272
+ var Scalar = class _Scalar {
273
+ bytes;
274
+ constructor(bytes) {
275
+ this.bytes = bytes;
276
+ }
277
+ static dummy() {
278
+ return new _Scalar(new Uint8Array(32));
279
+ }
280
+ static fromU64(x) {
281
+ return new _Scalar((0, import_utils.numberToBytesLE)(x, 32));
282
+ }
283
+ static fromLittleEndianBytesModQ(bytes) {
284
+ const value = (0, import_utils.bytesToNumberLE)(bytes) % Q;
285
+ return new _Scalar((0, import_utils.numberToBytesLE)(value, 32));
286
+ }
287
+ static rand() {
288
+ const randomBytes2 = randBytes(64);
289
+ const value = (0, import_utils.bytesToNumberLE)(randomBytes2) % Q;
290
+ const scalarValue = value === 0n ? 1n : value;
291
+ return new _Scalar((0, import_utils.numberToBytesLE)(scalarValue, 32));
292
+ }
293
+ static deserialize(deserializer) {
294
+ const bytes = deserializer.deserializeBytes();
295
+ return new _Scalar(bytes);
296
+ }
297
+ static fromBytes(bytes) {
298
+ const deserializer = new import_ts_sdk2.Deserializer(bytes);
299
+ const ret = _Scalar.deserialize(deserializer);
300
+ if (deserializer.remaining() !== 0) {
301
+ throw new Error("Invalid scalar bytes");
302
+ }
303
+ return ret;
304
+ }
305
+ serialize(serializer) {
306
+ serializer.serializeBytes(this.bytes);
307
+ }
308
+ toBytes() {
309
+ const serializer = new import_ts_sdk2.Serializer();
310
+ this.serialize(serializer);
311
+ return serializer.toUint8Array();
312
+ }
313
+ toHex() {
314
+ return (0, import_utils.bytesToHex)(this.toBytes());
315
+ }
316
+ isZero() {
317
+ return this.bytes.every((b) => b === 0);
318
+ }
319
+ add(other) {
320
+ const result = ((0, import_utils.bytesToNumberLE)(this.bytes) + (0, import_utils.bytesToNumberLE)(other.bytes)) % Q;
321
+ return new _Scalar((0, import_utils.numberToBytesLE)(result, 32));
322
+ }
323
+ sub(other) {
324
+ const result = (Q - (0, import_utils.bytesToNumberLE)(other.bytes) + (0, import_utils.bytesToNumberLE)(this.bytes)) % Q;
325
+ return new _Scalar((0, import_utils.numberToBytesLE)(result, 32));
326
+ }
327
+ mul(other) {
328
+ const result = (0, import_utils.bytesToNumberLE)(this.bytes) * (0, import_utils.bytesToNumberLE)(other.bytes) % Q;
329
+ return new _Scalar((0, import_utils.numberToBytesLE)(result, 32));
330
+ }
331
+ neg() {
332
+ const result = Q - (0, import_utils.bytesToNumberLE)(this.bytes);
333
+ return new _Scalar((0, import_utils.numberToBytesLE)(result, 32));
334
+ }
335
+ };
336
+ function msm(bases, scalars) {
337
+ let acc = Element.groupIdentity();
338
+ for (let i = 0; i < bases.length; i++) {
339
+ const scaled = bases[i].scale(scalars[i]);
340
+ acc = acc.add(scaled);
341
+ }
342
+ return acc;
343
+ }
344
+ function scalarFrom512BitHash(hash) {
345
+ if (hash.length !== 64) {
346
+ throw new Error("Hash must be 512 bits (64 bytes)");
347
+ }
348
+ const value = (0, import_utils.bytesToNumberLE)(hash) % Q;
349
+ return new Scalar((0, import_utils.numberToBytesLE)(value, 32));
350
+ }
351
+
352
+ // src/elgamal.ts
353
+ var Ciphertext = class _Ciphertext {
354
+ c0;
355
+ c1;
356
+ constructor(c0, c1) {
357
+ this.c0 = c0;
358
+ this.c1 = c1;
359
+ }
360
+ static deserialize(deserializer) {
361
+ const c0 = Element.deserialize(deserializer);
362
+ const c1 = Element.deserialize(deserializer);
363
+ return new _Ciphertext(c0, c1);
364
+ }
365
+ encode(serializer) {
366
+ this.c0.serialize(serializer);
367
+ this.c1.serialize(serializer);
368
+ }
369
+ toBytes() {
370
+ const serializer = new import_ts_sdk3.Serializer();
371
+ this.encode(serializer);
372
+ return serializer.toUint8Array();
373
+ }
374
+ add(other) {
375
+ return new _Ciphertext(this.c0.add(other.c0), this.c1.add(other.c1));
376
+ }
377
+ scale(scalar) {
378
+ return new _Ciphertext(this.c0.scale(scalar), this.c1.scale(scalar));
379
+ }
380
+ };
381
+ var DecKey = class _DecKey {
382
+ encBase;
383
+ privateScalar;
384
+ constructor(encBase, privateScalar) {
385
+ this.encBase = encBase;
386
+ this.privateScalar = privateScalar;
387
+ }
388
+ static deserialize(deserializer) {
389
+ const encBase = Element.deserialize(deserializer);
390
+ const privateScalar = Scalar.deserialize(deserializer);
391
+ return new _DecKey(encBase, privateScalar);
392
+ }
393
+ encode(serializer) {
394
+ this.encBase.serialize(serializer);
395
+ this.privateScalar.serialize(serializer);
396
+ }
397
+ };
398
+ var EncKey = class _EncKey {
399
+ encBase;
400
+ publicPoint;
401
+ constructor(encBase, publicPoint) {
402
+ this.encBase = encBase;
403
+ this.publicPoint = publicPoint;
404
+ }
405
+ static decode(deserializer) {
406
+ const encBase = Element.deserialize(deserializer);
407
+ const publicPoint = Element.deserialize(deserializer);
408
+ return new _EncKey(encBase, publicPoint);
409
+ }
410
+ encode(serializer) {
411
+ this.encBase.serialize(serializer);
412
+ this.publicPoint.serialize(serializer);
413
+ }
414
+ toBytes() {
415
+ const serializer = new import_ts_sdk3.Serializer();
416
+ this.encode(serializer);
417
+ return serializer.toUint8Array();
418
+ }
419
+ };
420
+ function enc(ek, randomizer, ptxt) {
421
+ return new Ciphertext(
422
+ ek.encBase.scale(randomizer),
423
+ ptxt.add(ek.publicPoint.scale(randomizer))
424
+ );
425
+ }
426
+ function dec(dk, ciph) {
427
+ const unblinder = ciph.c0.scale(dk.privateScalar);
428
+ return ciph.c1.sub(unblinder);
429
+ }
430
+ function multiExp(ciphs, scalars) {
431
+ let acc = new Ciphertext(
432
+ Element.groupIdentity(),
433
+ Element.groupIdentity()
434
+ );
435
+ for (let i = 0; i < ciphs.length; i++) {
436
+ acc = acc.add(ciphs[i].scale(scalars[i]));
437
+ }
438
+ return acc;
439
+ }
440
+
441
+ // src/enc/index.ts
442
+ var enc_exports = {};
443
+ __export(enc_exports, {
444
+ Ciphertext: () => Ciphertext2,
445
+ DecryptionKey: () => DecryptionKey,
446
+ EncryptionKey: () => EncryptionKey,
447
+ SCHEME_SIMPLE_ELGAMAL_RISTRETTO255: () => SCHEME_SIMPLE_ELGAMAL_RISTRETTO255,
448
+ decrypt: () => decrypt2,
449
+ deriveEncryptionKey: () => deriveEncryptionKey2,
450
+ encrypt: () => encrypt2,
451
+ encryptWithRandomness: () => encryptWithRandomness2,
452
+ keygen: () => keygen2
453
+ });
454
+ var import_ts_sdk5 = require("@aptos-labs/ts-sdk");
455
+ var import_utils5 = require("@noble/hashes/utils");
456
+
457
+ // src/enc/simple_elgamal_ristretto255.ts
458
+ var import_ts_sdk4 = require("@aptos-labs/ts-sdk");
459
+ var import_utils3 = require("@noble/hashes/utils");
460
+ var SimpleElGamalRistretto255EncKey = class _SimpleElGamalRistretto255EncKey {
461
+ elgamalEk;
462
+ constructor(elgamalEk) {
463
+ this.elgamalEk = elgamalEk;
464
+ }
465
+ static deserialize(deserializer) {
466
+ const elgamalEk = EncKey.decode(deserializer);
467
+ return new _SimpleElGamalRistretto255EncKey(elgamalEk);
468
+ }
469
+ serialize(serializer) {
470
+ this.elgamalEk.encode(serializer);
471
+ }
472
+ };
473
+ var SimpleElGamalRistretto255DecKey = class _SimpleElGamalRistretto255DecKey {
474
+ elgamalDk;
475
+ constructor(elgamalDk) {
476
+ this.elgamalDk = elgamalDk;
477
+ }
478
+ static deserialize(deserializer) {
479
+ const elgamalDk = DecKey.deserialize(deserializer);
480
+ return new _SimpleElGamalRistretto255DecKey(elgamalDk);
481
+ }
482
+ serialize(serializer) {
483
+ this.elgamalDk.encode(serializer);
484
+ }
485
+ };
486
+ var SimpleElGamalRistretto255Ciphertext = class _SimpleElGamalRistretto255Ciphertext {
487
+ elgamalCiph;
488
+ symmetricCiph;
489
+ mac;
490
+ constructor(elgamalCiph, symmetricCiph, mac) {
491
+ this.elgamalCiph = elgamalCiph;
492
+ this.symmetricCiph = symmetricCiph;
493
+ this.mac = mac;
494
+ }
495
+ static deserialize(deserializer) {
496
+ const elgamalCiph = Ciphertext.deserialize(deserializer);
497
+ const symmetricCiph = deserializer.deserializeBytes();
498
+ const mac = deserializer.deserializeBytes();
499
+ return new _SimpleElGamalRistretto255Ciphertext(elgamalCiph, symmetricCiph, mac);
500
+ }
501
+ serialize(serializer) {
502
+ this.elgamalCiph.encode(serializer);
503
+ serializer.serializeBytes(this.symmetricCiph);
504
+ serializer.serializeBytes(this.mac);
505
+ }
506
+ };
507
+ function keygen() {
508
+ const encBase = Element.rand();
509
+ const privateScalar = Scalar.rand();
510
+ const elgamalDk = new DecKey(encBase, privateScalar);
511
+ return new SimpleElGamalRistretto255DecKey(elgamalDk);
512
+ }
513
+ function deriveEncryptionKey(dk) {
514
+ const { elgamalDk } = dk;
515
+ const { encBase, privateScalar } = elgamalDk;
516
+ const publicPoint = encBase.scale(privateScalar);
517
+ const elgamalEk = new EncKey(encBase, publicPoint);
518
+ return new SimpleElGamalRistretto255EncKey(elgamalEk);
519
+ }
520
+ var EncRandomizer = class _EncRandomizer {
521
+ elgamalPtxt;
522
+ elgamalRand;
523
+ constructor(elgamalPtxt, elgamalRand) {
524
+ this.elgamalPtxt = elgamalPtxt;
525
+ this.elgamalRand = elgamalRand;
526
+ }
527
+ static deserialize(deserializer) {
528
+ const elgamalPtxt = Element.deserialize(deserializer);
529
+ const elgamalRand = Scalar.deserialize(deserializer);
530
+ return new _EncRandomizer(elgamalPtxt, elgamalRand);
531
+ }
532
+ static fromBytes(bytes) {
533
+ const deserializer = new import_ts_sdk4.Deserializer(bytes);
534
+ const ret = _EncRandomizer.deserialize(deserializer);
535
+ if (deserializer.remaining() !== 0) {
536
+ throw new Error("Invalid enc randomizer bytes");
537
+ }
538
+ return ret;
539
+ }
540
+ serialize(serializer) {
541
+ this.elgamalPtxt.serialize(serializer);
542
+ this.elgamalRand.serialize(serializer);
543
+ }
544
+ toBytes() {
545
+ const serializer = new import_ts_sdk4.Serializer();
546
+ this.serialize(serializer);
547
+ return serializer.toUint8Array();
548
+ }
549
+ };
550
+ function encrypt(ek, msg) {
551
+ const elgamalPtxt = Element.rand();
552
+ const elgamalRand = Scalar.rand();
553
+ const encRandomizer = new EncRandomizer(elgamalPtxt, elgamalRand);
554
+ return encryptWithRandomness(ek, msg, encRandomizer.toBytes());
555
+ }
556
+ function encryptWithRandomness(ek, msg, randomness) {
557
+ const { elgamalEk } = ek;
558
+ const { elgamalPtxt, elgamalRand } = EncRandomizer.fromBytes(randomness);
559
+ const elgamalCiph = enc(elgamalEk, elgamalRand, elgamalPtxt);
560
+ const seed = elgamalPtxt.toBytes();
561
+ const otp = kdf(seed, new TextEncoder().encode("OTP/SIMPLE_ELGAMAL_RISTRETTO255"), msg.length);
562
+ const symmetricCiph = xorBytes(otp, msg);
563
+ const hmacKey = kdf(seed, new TextEncoder().encode("HMAC/SIMPLE_ELGAMAL_RISTRETTO255"), 32);
564
+ const mac = hmac_sha3_256(hmacKey, symmetricCiph);
565
+ return new SimpleElGamalRistretto255Ciphertext(elgamalCiph, symmetricCiph, mac);
566
+ }
567
+ function decrypt(dk, ciphertext) {
568
+ const { elgamalDk } = dk;
569
+ const { elgamalCiph, symmetricCiph, mac } = ciphertext;
570
+ const elgamalPtxt = dec(elgamalDk, elgamalCiph);
571
+ const seed = elgamalPtxt.toBytes();
572
+ const hmacKey = kdf(seed, new TextEncoder().encode("HMAC/SIMPLE_ELGAMAL_RISTRETTO255"), 32);
573
+ const macAnother = hmac_sha3_256(hmacKey, symmetricCiph);
574
+ if ((0, import_utils3.bytesToHex)(mac) !== (0, import_utils3.bytesToHex)(macAnother)) {
575
+ return void 0;
576
+ }
577
+ const otp = kdf(seed, new TextEncoder().encode("OTP/SIMPLE_ELGAMAL_RISTRETTO255"), symmetricCiph.length);
578
+ const msg = xorBytes(otp, symmetricCiph);
579
+ return msg;
580
+ }
581
+
582
+ // src/enc/index.ts
583
+ var SCHEME_SIMPLE_ELGAMAL_RISTRETTO255 = 0;
584
+ var EncryptionKey = class _EncryptionKey {
585
+ scheme;
586
+ inner;
587
+ constructor(scheme, inner) {
588
+ this.scheme = scheme;
589
+ this.inner = inner;
590
+ }
591
+ static deserialize(deserializer) {
592
+ const scheme = deserializer.deserializeU8();
593
+ if (scheme === SCHEME_SIMPLE_ELGAMAL_RISTRETTO255) {
594
+ const inner = SimpleElGamalRistretto255EncKey.deserialize(deserializer);
595
+ return new _EncryptionKey(scheme, inner);
596
+ }
597
+ throw new Error(`Unknown scheme: ${scheme}`);
598
+ }
599
+ static fromBytes(bytes) {
600
+ const deserializer = new import_ts_sdk5.Deserializer(bytes);
601
+ const result = _EncryptionKey.deserialize(deserializer);
602
+ if (deserializer.remaining() !== 0) {
603
+ throw new Error("Invalid encryption key bytes");
604
+ }
605
+ return result;
606
+ }
607
+ static fromHex(hex) {
608
+ return _EncryptionKey.fromBytes((0, import_utils5.hexToBytes)(hex));
609
+ }
610
+ serialize(serializer) {
611
+ serializer.serializeU8(this.scheme);
612
+ this.inner.serialize(serializer);
613
+ }
614
+ toBytes() {
615
+ const serializer = new import_ts_sdk5.Serializer();
616
+ this.serialize(serializer);
617
+ return serializer.toUint8Array();
618
+ }
619
+ toHex() {
620
+ return (0, import_utils5.bytesToHex)(this.toBytes());
621
+ }
622
+ };
623
+ var DecryptionKey = class _DecryptionKey {
624
+ scheme;
625
+ inner;
626
+ constructor(scheme, inner) {
627
+ this.scheme = scheme;
628
+ this.inner = inner;
629
+ }
630
+ static deserialize(deserializer) {
631
+ const scheme = deserializer.deserializeU8();
632
+ if (scheme === SCHEME_SIMPLE_ELGAMAL_RISTRETTO255) {
633
+ const inner = SimpleElGamalRistretto255DecKey.deserialize(deserializer);
634
+ return new _DecryptionKey(scheme, inner);
635
+ }
636
+ throw new Error(`Unknown scheme: ${scheme}`);
637
+ }
638
+ static fromBytes(bytes) {
639
+ const deserializer = new import_ts_sdk5.Deserializer(bytes);
640
+ const result = _DecryptionKey.deserialize(deserializer);
641
+ if (deserializer.remaining() !== 0) {
642
+ throw new Error("Invalid decryption key bytes");
643
+ }
644
+ return result;
645
+ }
646
+ static fromHex(hex) {
647
+ return _DecryptionKey.fromBytes((0, import_utils5.hexToBytes)(hex));
648
+ }
649
+ serialize(serializer) {
650
+ serializer.serializeU8(this.scheme);
651
+ this.inner.serialize(serializer);
652
+ }
653
+ toBytes() {
654
+ const serializer = new import_ts_sdk5.Serializer();
655
+ this.serialize(serializer);
656
+ return serializer.toUint8Array();
657
+ }
658
+ toHex() {
659
+ return (0, import_utils5.bytesToHex)(this.toBytes());
660
+ }
661
+ };
662
+ var Ciphertext2 = class _Ciphertext {
663
+ scheme;
664
+ inner;
665
+ constructor(scheme, inner) {
666
+ this.scheme = scheme;
667
+ this.inner = inner;
668
+ }
669
+ static deserialize(deserializer) {
670
+ const scheme = deserializer.deserializeU8();
671
+ if (scheme === SCHEME_SIMPLE_ELGAMAL_RISTRETTO255) {
672
+ const inner = SimpleElGamalRistretto255Ciphertext.deserialize(deserializer);
673
+ return new _Ciphertext(scheme, inner);
674
+ }
675
+ throw new Error(`Unknown scheme: ${scheme}`);
676
+ }
677
+ static fromBytes(bytes) {
678
+ const deserializer = new import_ts_sdk5.Deserializer(bytes);
679
+ const result = _Ciphertext.deserialize(deserializer);
680
+ if (deserializer.remaining() !== 0) {
681
+ throw new Error("Invalid ciphertext bytes");
682
+ }
683
+ return result;
684
+ }
685
+ static fromHex(hex) {
686
+ return _Ciphertext.fromBytes((0, import_utils5.hexToBytes)(hex));
687
+ }
688
+ serialize(serializer) {
689
+ serializer.serializeU8(this.scheme);
690
+ this.inner.serialize(serializer);
691
+ }
692
+ toBytes() {
693
+ const serializer = new import_ts_sdk5.Serializer();
694
+ this.serialize(serializer);
695
+ return serializer.toUint8Array();
696
+ }
697
+ toHex() {
698
+ return (0, import_utils5.bytesToHex)(this.toBytes());
699
+ }
700
+ };
701
+ function keygen2(schemeId) {
702
+ const scheme = schemeId ?? SCHEME_SIMPLE_ELGAMAL_RISTRETTO255;
703
+ if (scheme === SCHEME_SIMPLE_ELGAMAL_RISTRETTO255) {
704
+ const dk = keygen();
705
+ return new DecryptionKey(scheme, dk);
706
+ } else {
707
+ throw new Error(`Unknown scheme: ${scheme}`);
708
+ }
709
+ }
710
+ function deriveEncryptionKey2(dk) {
711
+ if (dk.scheme === SCHEME_SIMPLE_ELGAMAL_RISTRETTO255) {
712
+ const ek = deriveEncryptionKey(dk.inner);
713
+ return new EncryptionKey(dk.scheme, ek);
714
+ } else {
715
+ throw new Error(`Unknown scheme: ${dk.scheme}`);
716
+ }
717
+ }
718
+ function encrypt2(ek, msg) {
719
+ if (ek.scheme === SCHEME_SIMPLE_ELGAMAL_RISTRETTO255) {
720
+ const ciphertext = encrypt(ek.inner, msg);
721
+ return new Ciphertext2(ek.scheme, ciphertext);
722
+ } else {
723
+ throw new Error(`Unknown scheme: ${ek.scheme}`);
724
+ }
725
+ }
726
+ function encryptWithRandomness2(ek, msg, randomness) {
727
+ if (ek.scheme === SCHEME_SIMPLE_ELGAMAL_RISTRETTO255) {
728
+ const ciphertext = encryptWithRandomness(ek.inner, msg, randomness);
729
+ return new Ciphertext2(ek.scheme, ciphertext);
730
+ } else {
731
+ throw new Error(`Unknown scheme: ${ek.scheme}`);
732
+ }
733
+ }
734
+ function decrypt2(dk, ciphertext) {
735
+ if (dk.scheme === SCHEME_SIMPLE_ELGAMAL_RISTRETTO255 && ciphertext.scheme === SCHEME_SIMPLE_ELGAMAL_RISTRETTO255) {
736
+ return decrypt(dk.inner, ciphertext.inner);
737
+ } else {
738
+ throw new Error(`Unknown scheme: dk=${dk.scheme}, ciphertext=${ciphertext.scheme}`);
739
+ }
740
+ }
741
+
742
+ // src/ibe/index.ts
743
+ var ibe_exports = {};
744
+ __export(ibe_exports, {
745
+ Ciphertext: () => Ciphertext4,
746
+ IdentityPrivateKey: () => IdentityPrivateKey2,
747
+ MasterPrivateKey: () => MasterPrivateKey2,
748
+ MasterPublicKey: () => MasterPublicKey2,
749
+ SCHEME_OTP_HAMC_BONEH_FRANKLIN_BLS12381_SHORT_PK: () => SCHEME_OTP_HAMC_BONEH_FRANKLIN_BLS12381_SHORT_PK,
750
+ decrypt: () => decrypt4,
751
+ derivePublicKey: () => derivePublicKey2,
752
+ encrypt: () => encrypt4,
753
+ encryptWithRandomness: () => encryptWithRandomness4,
754
+ extract: () => extract2,
755
+ keygen: () => keygen4
756
+ });
757
+ var import_ts_sdk6 = require("@aptos-labs/ts-sdk");
758
+ var import_utils9 = require("@noble/curves/abstract/utils");
759
+
760
+ // src/ibe/otp_hmac_boneh_franklin_bls12381_short_pk.ts
761
+ var import_bls12_381 = require("@noble/curves/bls12-381");
762
+ var import_utils6 = require("@noble/curves/utils");
763
+ var import_utils7 = require("@noble/hashes/utils");
764
+ var DST_OTP = new TextEncoder().encode("BONEH_FRANKLIN_BLS12381_SHORT_PK/OTP");
765
+ var DST_ID_HASH = new TextEncoder().encode("BONEH_FRANKLIN_BLS12381_SHORT_PK/HASH_ID_TO_CURVE");
766
+ var DST_MAC = new TextEncoder().encode("BONEH_FRANKLIN_BLS12381_SHORT_PK/MAC");
767
+ var MasterPublicKey = class _MasterPublicKey {
768
+ base;
769
+ publicPointG1;
770
+ constructor(base, publicPointG1) {
771
+ this.base = base;
772
+ this.publicPointG1 = publicPointG1;
773
+ }
774
+ static deserialize(deserializer) {
775
+ const baseBytes = deserializer.deserializeBytes();
776
+ const base = import_bls12_381.bls12_381.G1.Point.fromBytes(baseBytes);
777
+ const publicPointG1Bytes = deserializer.deserializeBytes();
778
+ const publicPointG1 = import_bls12_381.bls12_381.G1.Point.fromBytes(publicPointG1Bytes);
779
+ return new _MasterPublicKey(base, publicPointG1);
780
+ }
781
+ serialize(serializer) {
782
+ serializer.serializeBytes(this.base.toBytes());
783
+ serializer.serializeBytes(this.publicPointG1.toBytes());
784
+ }
785
+ };
786
+ var MasterPrivateKey = class _MasterPrivateKey {
787
+ base;
788
+ privateScalar;
789
+ constructor(base, privateScalar) {
790
+ this.base = base;
791
+ this.privateScalar = privateScalar;
792
+ }
793
+ static deserialize(deserializer) {
794
+ const baseBytes = deserializer.deserializeBytes();
795
+ const base = import_bls12_381.bls12_381.G1.Point.fromBytes(baseBytes);
796
+ const privateScalarBytes = deserializer.deserializeBytes();
797
+ const privateScalar = BigInt("0x" + Array.from(privateScalarBytes).reverse().map((b) => b.toString(16).padStart(2, "0")).join(""));
798
+ return new _MasterPrivateKey(base, privateScalar);
799
+ }
800
+ serialize(serializer) {
801
+ serializer.serializeBytes(this.base.toBytes());
802
+ serializer.serializeBytes((0, import_utils6.numberToBytesLE)(this.privateScalar, 32));
803
+ }
804
+ };
805
+ var IdentityPrivateKey = class _IdentityPrivateKey {
806
+ privatePointG2;
807
+ constructor(privatePointG2) {
808
+ this.privatePointG2 = privatePointG2;
809
+ }
810
+ static deserialize(deserializer) {
811
+ const privatePointG2Bytes = deserializer.deserializeBytes();
812
+ const privatePointG2 = import_bls12_381.bls12_381.G2.Point.fromBytes(privatePointG2Bytes);
813
+ return new _IdentityPrivateKey(privatePointG2);
814
+ }
815
+ serialize(serializer) {
816
+ serializer.serializeBytes(this.privatePointG2.toBytes());
817
+ }
818
+ };
819
+ var Ciphertext3 = class _Ciphertext {
820
+ c0;
821
+ symmetricCiph;
822
+ mac;
823
+ constructor(c0, symmetricCiph, mac) {
824
+ this.c0 = c0;
825
+ this.symmetricCiph = symmetricCiph;
826
+ this.mac = mac;
827
+ }
828
+ static deserialize(deserializer) {
829
+ const c0Bytes = deserializer.deserializeBytes();
830
+ const c0 = import_bls12_381.bls12_381.G1.Point.fromBytes(c0Bytes);
831
+ const symmetricCiph = deserializer.deserializeBytes();
832
+ const mac = deserializer.deserializeBytes();
833
+ return new _Ciphertext(c0, symmetricCiph, mac);
834
+ }
835
+ serialize(serializer) {
836
+ serializer.serializeBytes(this.c0.toBytes());
837
+ serializer.serializeBytes(this.symmetricCiph);
838
+ serializer.serializeBytes(this.mac);
839
+ }
840
+ };
841
+ function keygen3() {
842
+ const base = import_bls12_381.bls12_381.G1.hashToCurve((0, import_utils7.randomBytes)(32));
843
+ const privateScalar = (0, import_utils6.bytesToNumberBE)(import_bls12_381.bls12_381.utils.randomSecretKey());
844
+ return new MasterPrivateKey(base, privateScalar);
845
+ }
846
+ function derivePublicKey(privateKey) {
847
+ const publicPoint = privateKey.base.multiply(privateKey.privateScalar);
848
+ return new MasterPublicKey(privateKey.base, publicPoint);
849
+ }
850
+ function encrypt3(publicKey, id, plaintext) {
851
+ const r = (0, import_utils6.bytesToNumberBE)(import_bls12_381.bls12_381.utils.randomSecretKey());
852
+ return encryptWithRandomness3(publicKey, id, plaintext, (0, import_utils6.numberToBytesLE)(r, 32));
853
+ }
854
+ function encryptWithRandomness3(publicKey, id, plaintext, randomness) {
855
+ const r = (0, import_utils6.bytesToNumberLE)(randomness);
856
+ const idPoint = import_bls12_381.bls12_381.G2.hashToCurve(id, { DST: DST_ID_HASH });
857
+ const seedElement = import_bls12_381.bls12_381.pairing(publicKey.publicPointG1.multiply(r), idPoint);
858
+ const seed = bls12381GtReprNobleToAptos(import_bls12_381.bls12_381.fields.Fp12.toBytes(seedElement));
859
+ const otp = kdf(seed, DST_OTP, plaintext.length);
860
+ const macKey = kdf(seed, DST_MAC, 32);
861
+ const symmetricCiph = xorBytes(otp, plaintext);
862
+ const mac = hmac_sha3_256(macKey, symmetricCiph);
863
+ const c0 = publicKey.base.multiply(r);
864
+ return new Ciphertext3(c0, symmetricCiph, mac);
865
+ }
866
+ function bls12381GtReprNobleToAptos(noble) {
867
+ if (noble.length !== 576) {
868
+ throw new Error("noble must be 576 bytes");
869
+ }
870
+ const chunks = [];
871
+ for (let i = 0; i < noble.length; i += 48) {
872
+ chunks.push(noble.slice(i, i + 48).reverse());
873
+ }
874
+ const result = new Uint8Array(576);
875
+ for (let i = 0; i < 12; i++) {
876
+ result.set(chunks[i], i * 48);
877
+ }
878
+ return result;
879
+ }
880
+ function extract(privateKey, id) {
881
+ const idPoint = import_bls12_381.bls12_381.G2.hashToCurve(id, { DST: DST_ID_HASH });
882
+ const privatePointG2 = idPoint.multiply(privateKey.privateScalar);
883
+ return new IdentityPrivateKey(privatePointG2);
884
+ }
885
+ function decrypt3(identityKey, ciphertext) {
886
+ const seedElementGt = import_bls12_381.bls12_381.pairing(ciphertext.c0, identityKey.privatePointG2);
887
+ const seed = bls12381GtReprNobleToAptos(import_bls12_381.bls12_381.fields.Fp12.toBytes(seedElementGt));
888
+ const macKey = kdf(seed, DST_MAC, 32);
889
+ const macAnother = hmac_sha3_256(macKey, ciphertext.symmetricCiph);
890
+ if ((0, import_utils7.bytesToHex)(ciphertext.mac) !== (0, import_utils7.bytesToHex)(macAnother)) {
891
+ return void 0;
892
+ }
893
+ const otp = kdf(seed, DST_OTP, ciphertext.symmetricCiph.length);
894
+ const plaintext = xorBytes(otp, ciphertext.symmetricCiph);
895
+ return plaintext;
896
+ }
897
+
898
+ // src/ibe/index.ts
899
+ var SCHEME_OTP_HAMC_BONEH_FRANKLIN_BLS12381_SHORT_PK = 0;
900
+ var MasterPublicKey2 = class _MasterPublicKey {
901
+ scheme;
902
+ inner;
903
+ constructor(scheme, inner) {
904
+ if (scheme !== SCHEME_OTP_HAMC_BONEH_FRANKLIN_BLS12381_SHORT_PK) {
905
+ throw new Error(`Unknown scheme: ${scheme}`);
906
+ }
907
+ this.scheme = scheme;
908
+ this.inner = inner;
909
+ }
910
+ static deserialize(deserializer) {
911
+ const scheme = deserializer.deserializeU8();
912
+ if (scheme === SCHEME_OTP_HAMC_BONEH_FRANKLIN_BLS12381_SHORT_PK) {
913
+ const inner = MasterPublicKey.deserialize(deserializer);
914
+ return new _MasterPublicKey(scheme, inner);
915
+ }
916
+ throw new Error(`Unknown scheme: ${scheme}`);
917
+ }
918
+ static fromBytes(bytes) {
919
+ const deserializer = new import_ts_sdk6.Deserializer(bytes);
920
+ const ret = _MasterPublicKey.deserialize(deserializer);
921
+ if (deserializer.remaining() !== 0) {
922
+ throw new Error("Deserialization failed");
923
+ }
924
+ return ret;
925
+ }
926
+ static fromHex(hex) {
927
+ return _MasterPublicKey.fromBytes((0, import_utils9.hexToBytes)(hex));
928
+ }
929
+ serialize(serializer) {
930
+ serializer.serializeU8(this.scheme);
931
+ if (this.scheme === SCHEME_OTP_HAMC_BONEH_FRANKLIN_BLS12381_SHORT_PK) {
932
+ this.inner.serialize(serializer);
933
+ } else {
934
+ throw new Error(`Unknown scheme: ${this.scheme}`);
935
+ }
936
+ }
937
+ toBytes() {
938
+ const serializer = new import_ts_sdk6.Serializer();
939
+ this.serialize(serializer);
940
+ return serializer.toUint8Array();
941
+ }
942
+ toHex() {
943
+ return (0, import_utils9.bytesToHex)(this.toBytes());
944
+ }
945
+ };
946
+ var MasterPrivateKey2 = class _MasterPrivateKey {
947
+ scheme;
948
+ inner;
949
+ constructor(scheme, inner) {
950
+ if (scheme !== SCHEME_OTP_HAMC_BONEH_FRANKLIN_BLS12381_SHORT_PK) {
951
+ throw new Error(`Unknown scheme: ${scheme}`);
952
+ }
953
+ this.scheme = scheme;
954
+ this.inner = inner;
955
+ }
956
+ static deserialize(deserializer) {
957
+ const scheme = deserializer.deserializeU8();
958
+ if (scheme === SCHEME_OTP_HAMC_BONEH_FRANKLIN_BLS12381_SHORT_PK) {
959
+ const inner = MasterPrivateKey.deserialize(deserializer);
960
+ return new _MasterPrivateKey(scheme, inner);
961
+ }
962
+ throw new Error(`Unknown scheme: ${scheme}`);
963
+ }
964
+ static fromBytes(bytes) {
965
+ const deserializer = new import_ts_sdk6.Deserializer(bytes);
966
+ const ret = _MasterPrivateKey.deserialize(deserializer);
967
+ if (deserializer.remaining() !== 0) {
968
+ throw new Error("Deserialization failed");
969
+ }
970
+ return ret;
971
+ }
972
+ static fromHex(hex) {
973
+ return _MasterPrivateKey.fromBytes((0, import_utils9.hexToBytes)(hex));
974
+ }
975
+ serialize(serializer) {
976
+ serializer.serializeU8(this.scheme);
977
+ if (this.scheme === SCHEME_OTP_HAMC_BONEH_FRANKLIN_BLS12381_SHORT_PK) {
978
+ this.inner.serialize(serializer);
979
+ } else {
980
+ throw new Error(`Unknown scheme: ${this.scheme}`);
981
+ }
982
+ }
983
+ toBytes() {
984
+ const serializer = new import_ts_sdk6.Serializer();
985
+ this.serialize(serializer);
986
+ return serializer.toUint8Array();
987
+ }
988
+ toHex() {
989
+ return (0, import_utils9.bytesToHex)(this.toBytes());
990
+ }
991
+ };
992
+ var IdentityPrivateKey2 = class _IdentityPrivateKey {
993
+ scheme;
994
+ inner;
995
+ constructor(scheme, inner) {
996
+ if (scheme !== SCHEME_OTP_HAMC_BONEH_FRANKLIN_BLS12381_SHORT_PK) {
997
+ throw new Error(`Unknown scheme: ${scheme}`);
998
+ }
999
+ this.scheme = scheme;
1000
+ this.inner = inner;
1001
+ }
1002
+ static deserialize(deserializer) {
1003
+ const scheme = deserializer.deserializeU8();
1004
+ if (scheme === SCHEME_OTP_HAMC_BONEH_FRANKLIN_BLS12381_SHORT_PK) {
1005
+ const inner = IdentityPrivateKey.deserialize(deserializer);
1006
+ return new _IdentityPrivateKey(scheme, inner);
1007
+ }
1008
+ throw new Error(`Unknown scheme: ${scheme}`);
1009
+ }
1010
+ static fromBytes(bytes) {
1011
+ const deserializer = new import_ts_sdk6.Deserializer(bytes);
1012
+ const ret = _IdentityPrivateKey.deserialize(deserializer);
1013
+ if (deserializer.remaining() !== 0) {
1014
+ throw new Error("Deserialization failed");
1015
+ }
1016
+ return ret;
1017
+ }
1018
+ static fromHex(hex) {
1019
+ return _IdentityPrivateKey.fromBytes((0, import_utils9.hexToBytes)(hex));
1020
+ }
1021
+ serialize(serializer) {
1022
+ serializer.serializeU8(this.scheme);
1023
+ if (this.scheme === SCHEME_OTP_HAMC_BONEH_FRANKLIN_BLS12381_SHORT_PK) {
1024
+ this.inner.serialize(serializer);
1025
+ } else {
1026
+ throw new Error(`Unknown scheme: ${this.scheme}`);
1027
+ }
1028
+ }
1029
+ toBytes() {
1030
+ const serializer = new import_ts_sdk6.Serializer();
1031
+ this.serialize(serializer);
1032
+ return serializer.toUint8Array();
1033
+ }
1034
+ toHex() {
1035
+ return (0, import_utils9.bytesToHex)(this.toBytes());
1036
+ }
1037
+ };
1038
+ var Ciphertext4 = class _Ciphertext {
1039
+ scheme;
1040
+ inner;
1041
+ constructor(scheme, inner) {
1042
+ if (scheme !== SCHEME_OTP_HAMC_BONEH_FRANKLIN_BLS12381_SHORT_PK) {
1043
+ throw new Error(`Unknown scheme: ${scheme}`);
1044
+ }
1045
+ this.scheme = scheme;
1046
+ this.inner = inner;
1047
+ }
1048
+ static deserialize(deserializer) {
1049
+ const scheme = deserializer.deserializeU8();
1050
+ if (scheme === SCHEME_OTP_HAMC_BONEH_FRANKLIN_BLS12381_SHORT_PK) {
1051
+ const inner = Ciphertext3.deserialize(deserializer);
1052
+ return new _Ciphertext(scheme, inner);
1053
+ }
1054
+ throw new Error(`Unknown scheme: ${scheme}`);
1055
+ }
1056
+ static fromBytes(bytes) {
1057
+ const deserializer = new import_ts_sdk6.Deserializer(bytes);
1058
+ const ret = _Ciphertext.deserialize(deserializer);
1059
+ if (deserializer.remaining() !== 0) {
1060
+ throw new Error("Deserialization failed");
1061
+ }
1062
+ return ret;
1063
+ }
1064
+ static fromHex(hex) {
1065
+ return _Ciphertext.fromBytes((0, import_utils9.hexToBytes)(hex));
1066
+ }
1067
+ serialize(serializer) {
1068
+ serializer.serializeU8(this.scheme);
1069
+ if (this.scheme === SCHEME_OTP_HAMC_BONEH_FRANKLIN_BLS12381_SHORT_PK) {
1070
+ this.inner.serialize(serializer);
1071
+ } else {
1072
+ throw new Error(`Unknown scheme: ${this.scheme}`);
1073
+ }
1074
+ }
1075
+ toBytes() {
1076
+ const serializer = new import_ts_sdk6.Serializer();
1077
+ this.serialize(serializer);
1078
+ return serializer.toUint8Array();
1079
+ }
1080
+ toHex() {
1081
+ return (0, import_utils9.bytesToHex)(this.toBytes());
1082
+ }
1083
+ };
1084
+ function keygen4(scheme) {
1085
+ if (scheme === void 0) {
1086
+ scheme = SCHEME_OTP_HAMC_BONEH_FRANKLIN_BLS12381_SHORT_PK;
1087
+ }
1088
+ if (scheme === SCHEME_OTP_HAMC_BONEH_FRANKLIN_BLS12381_SHORT_PK) {
1089
+ let msk = keygen3();
1090
+ return new MasterPrivateKey2(scheme, msk);
1091
+ }
1092
+ throw new Error(`Unknown scheme: ${scheme}`);
1093
+ }
1094
+ function derivePublicKey2(privateKey) {
1095
+ if (privateKey.scheme == SCHEME_OTP_HAMC_BONEH_FRANKLIN_BLS12381_SHORT_PK) {
1096
+ return new MasterPublicKey2(SCHEME_OTP_HAMC_BONEH_FRANKLIN_BLS12381_SHORT_PK, derivePublicKey(privateKey.inner));
1097
+ }
1098
+ throw new Error(`Unknown scheme: ${privateKey.scheme}`);
1099
+ }
1100
+ function encrypt4(publicKey, id, plaintext) {
1101
+ if (publicKey.scheme == SCHEME_OTP_HAMC_BONEH_FRANKLIN_BLS12381_SHORT_PK) {
1102
+ return new Ciphertext4(
1103
+ SCHEME_OTP_HAMC_BONEH_FRANKLIN_BLS12381_SHORT_PK,
1104
+ encrypt3(publicKey.inner, id, plaintext)
1105
+ );
1106
+ }
1107
+ throw new Error(`Unknown scheme: ${publicKey.scheme}`);
1108
+ }
1109
+ function encryptWithRandomness4(publicKey, id, plaintext, randomness) {
1110
+ if (publicKey.scheme == SCHEME_OTP_HAMC_BONEH_FRANKLIN_BLS12381_SHORT_PK) {
1111
+ return new Ciphertext4(
1112
+ SCHEME_OTP_HAMC_BONEH_FRANKLIN_BLS12381_SHORT_PK,
1113
+ encryptWithRandomness3(publicKey.inner, id, plaintext, randomness)
1114
+ );
1115
+ }
1116
+ throw new Error(`Unknown scheme: ${publicKey.scheme}`);
1117
+ }
1118
+ function extract2(privateKey, id) {
1119
+ if (privateKey.scheme == SCHEME_OTP_HAMC_BONEH_FRANKLIN_BLS12381_SHORT_PK) {
1120
+ return new IdentityPrivateKey2(
1121
+ SCHEME_OTP_HAMC_BONEH_FRANKLIN_BLS12381_SHORT_PK,
1122
+ extract(privateKey.inner, id)
1123
+ );
1124
+ }
1125
+ throw new Error(`Unknown scheme: ${privateKey.scheme}`);
1126
+ }
1127
+ function decrypt4(identityKey, ciphertext) {
1128
+ if (identityKey.scheme == SCHEME_OTP_HAMC_BONEH_FRANKLIN_BLS12381_SHORT_PK) {
1129
+ return decrypt3(identityKey.inner, ciphertext.inner);
1130
+ }
1131
+ throw new Error(`Unknown scheme: ${identityKey.scheme}`);
1132
+ }
1133
+
1134
+ // src/sig/index.ts
1135
+ var sig_exports = {};
1136
+ __export(sig_exports, {
1137
+ SCHEME_SCHNORR_RISTRETTO255: () => SCHEME_SCHNORR_RISTRETTO255,
1138
+ Signature: () => Signature,
1139
+ SigningKey: () => SigningKey,
1140
+ VerifyingKey: () => VerifyingKey,
1141
+ deriveVerifyingKey: () => deriveVerifyingKey2,
1142
+ keygen: () => keygen6,
1143
+ sign: () => sign2,
1144
+ signWithRandomness: () => signWithRandomness2,
1145
+ verify: () => verify2
1146
+ });
1147
+ var import_ts_sdk7 = require("@aptos-labs/ts-sdk");
1148
+ var import_utils12 = require("@noble/hashes/utils");
1149
+
1150
+ // src/sig/schnorr_ristretto255.ts
1151
+ var import_utils10 = require("@noble/hashes/utils");
1152
+ var SchnorrRistretto255SigningKey = class _SchnorrRistretto255SigningKey {
1153
+ base;
1154
+ privateScalar;
1155
+ constructor(base, privateScalar) {
1156
+ this.base = base;
1157
+ this.privateScalar = privateScalar;
1158
+ }
1159
+ static deserialize(deserializer) {
1160
+ const base = Element.deserialize(deserializer);
1161
+ const privateScalar = Scalar.deserialize(deserializer);
1162
+ return new _SchnorrRistretto255SigningKey(base, privateScalar);
1163
+ }
1164
+ serialize(serializer) {
1165
+ this.base.serialize(serializer);
1166
+ this.privateScalar.serialize(serializer);
1167
+ }
1168
+ };
1169
+ var SchnorrRistretto255VerifyingKey = class _SchnorrRistretto255VerifyingKey {
1170
+ base;
1171
+ publicPoint;
1172
+ constructor(base, publicPoint) {
1173
+ this.base = base;
1174
+ this.publicPoint = publicPoint;
1175
+ }
1176
+ static deserialize(deserializer) {
1177
+ const base = Element.deserialize(deserializer);
1178
+ const publicPoint = Element.deserialize(deserializer);
1179
+ return new _SchnorrRistretto255VerifyingKey(base, publicPoint);
1180
+ }
1181
+ serialize(serializer) {
1182
+ this.base.serialize(serializer);
1183
+ this.publicPoint.serialize(serializer);
1184
+ }
1185
+ };
1186
+ var SchnorrRistretto255Signature = class _SchnorrRistretto255Signature {
1187
+ challenge;
1188
+ z;
1189
+ constructor(challenge, z) {
1190
+ this.challenge = challenge;
1191
+ this.z = z;
1192
+ }
1193
+ static deserialize(deserializer) {
1194
+ const challenge = Scalar.deserialize(deserializer);
1195
+ const z = Scalar.deserialize(deserializer);
1196
+ return new _SchnorrRistretto255Signature(challenge, z);
1197
+ }
1198
+ serialize(serializer) {
1199
+ this.challenge.serialize(serializer);
1200
+ this.z.serialize(serializer);
1201
+ }
1202
+ };
1203
+ function keygen5() {
1204
+ const base = Element.rand();
1205
+ const privateScalar = Scalar.rand();
1206
+ return new SchnorrRistretto255SigningKey(base, privateScalar);
1207
+ }
1208
+ function deriveVerifyingKey(sk) {
1209
+ const { base, privateScalar } = sk;
1210
+ const publicPoint = base.scale(privateScalar);
1211
+ return new SchnorrRistretto255VerifyingKey(base, publicPoint);
1212
+ }
1213
+ function sign(sk, msg) {
1214
+ const randomness = Scalar.rand().toBytes();
1215
+ return signWithRandomness(sk, msg, randomness);
1216
+ }
1217
+ function signWithRandomness(sk, msg, randomness) {
1218
+ const { base, privateScalar } = sk;
1219
+ const scalarR = Scalar.fromBytes(randomness);
1220
+ const pointA = base.scale(scalarR);
1221
+ const scalarChallenge = hashTranscriptToScalar(pointA, msg);
1222
+ console.log("scalarChallenge", scalarChallenge.toHex());
1223
+ const scalarZ = scalarR.sub(privateScalar.mul(scalarChallenge));
1224
+ return new SchnorrRistretto255Signature(scalarChallenge, scalarZ);
1225
+ }
1226
+ function verify(vk, msg, sig) {
1227
+ const { base, publicPoint } = vk;
1228
+ const { challenge, z } = sig;
1229
+ const pointA = msm([base, publicPoint], [z, challenge]);
1230
+ const scalarChallengeAnother = hashTranscriptToScalar(pointA, msg);
1231
+ return (0, import_utils10.bytesToHex)(challenge.toBytes()) === (0, import_utils10.bytesToHex)(scalarChallengeAnother.toBytes());
1232
+ }
1233
+ function hashTranscriptToScalar(pointA, msg) {
1234
+ const dst = new TextEncoder().encode("DST/SCHNORR_RISTRETTO255/OCTOPUS");
1235
+ const transcript = new Uint8Array(dst.length + pointA.toBytes().length + msg.length);
1236
+ let offset = 0;
1237
+ transcript.set(dst, offset);
1238
+ offset += dst.length;
1239
+ transcript.set(pointA.toBytes(), offset);
1240
+ offset += pointA.toBytes().length;
1241
+ transcript.set(msg, offset);
1242
+ const transcriptHash = sha3_512(transcript);
1243
+ return scalarFrom512BitHash(transcriptHash);
1244
+ }
1245
+
1246
+ // src/sig/index.ts
1247
+ var SCHEME_SCHNORR_RISTRETTO255 = 0;
1248
+ var SigningKey = class _SigningKey {
1249
+ scheme;
1250
+ inner;
1251
+ constructor(scheme, inner) {
1252
+ this.scheme = scheme;
1253
+ this.inner = inner;
1254
+ }
1255
+ static deserialize(deserializer) {
1256
+ const scheme = deserializer.deserializeU8();
1257
+ if (scheme === SCHEME_SCHNORR_RISTRETTO255) {
1258
+ const inner = SchnorrRistretto255SigningKey.deserialize(deserializer);
1259
+ return new _SigningKey(scheme, inner);
1260
+ }
1261
+ throw new Error(`Unknown scheme: ${scheme}`);
1262
+ }
1263
+ static fromBytes(bytes) {
1264
+ const deserializer = new import_ts_sdk7.Deserializer(bytes);
1265
+ const result = _SigningKey.deserialize(deserializer);
1266
+ if (deserializer.remaining() !== 0) {
1267
+ throw new Error("Invalid signing key bytes");
1268
+ }
1269
+ return result;
1270
+ }
1271
+ static fromHex(hex) {
1272
+ return _SigningKey.fromBytes((0, import_utils12.hexToBytes)(hex));
1273
+ }
1274
+ serialize(serializer) {
1275
+ serializer.serializeU8(this.scheme);
1276
+ this.inner.serialize(serializer);
1277
+ }
1278
+ toBytes() {
1279
+ const serializer = new import_ts_sdk7.Serializer();
1280
+ this.serialize(serializer);
1281
+ return serializer.toUint8Array();
1282
+ }
1283
+ toHex() {
1284
+ return (0, import_utils12.bytesToHex)(this.toBytes());
1285
+ }
1286
+ };
1287
+ var VerifyingKey = class _VerifyingKey {
1288
+ scheme;
1289
+ inner;
1290
+ constructor(scheme, inner) {
1291
+ this.scheme = scheme;
1292
+ this.inner = inner;
1293
+ }
1294
+ static deserialize(deserializer) {
1295
+ const scheme = deserializer.deserializeU8();
1296
+ if (scheme === SCHEME_SCHNORR_RISTRETTO255) {
1297
+ const inner = SchnorrRistretto255VerifyingKey.deserialize(deserializer);
1298
+ return new _VerifyingKey(scheme, inner);
1299
+ }
1300
+ throw new Error(`Unknown scheme: ${scheme}`);
1301
+ }
1302
+ static fromBytes(bytes) {
1303
+ const deserializer = new import_ts_sdk7.Deserializer(bytes);
1304
+ const result = _VerifyingKey.deserialize(deserializer);
1305
+ if (deserializer.remaining() !== 0) {
1306
+ throw new Error("Invalid verifying key bytes");
1307
+ }
1308
+ return result;
1309
+ }
1310
+ static fromHex(hex) {
1311
+ return _VerifyingKey.fromBytes((0, import_utils12.hexToBytes)(hex));
1312
+ }
1313
+ serialize(serializer) {
1314
+ serializer.serializeU8(this.scheme);
1315
+ this.inner.serialize(serializer);
1316
+ }
1317
+ toBytes() {
1318
+ const serializer = new import_ts_sdk7.Serializer();
1319
+ this.serialize(serializer);
1320
+ return serializer.toUint8Array();
1321
+ }
1322
+ toHex() {
1323
+ return (0, import_utils12.bytesToHex)(this.toBytes());
1324
+ }
1325
+ };
1326
+ var Signature = class _Signature {
1327
+ scheme;
1328
+ inner;
1329
+ constructor(scheme, inner) {
1330
+ this.scheme = scheme;
1331
+ this.inner = inner;
1332
+ }
1333
+ static deserialize(deserializer) {
1334
+ const scheme = deserializer.deserializeU8();
1335
+ if (scheme === SCHEME_SCHNORR_RISTRETTO255) {
1336
+ const inner = SchnorrRistretto255Signature.deserialize(deserializer);
1337
+ return new _Signature(scheme, inner);
1338
+ }
1339
+ throw new Error(`Unknown scheme: ${scheme}`);
1340
+ }
1341
+ static fromBytes(bytes) {
1342
+ const deserializer = new import_ts_sdk7.Deserializer(bytes);
1343
+ const result = _Signature.deserialize(deserializer);
1344
+ if (deserializer.remaining() !== 0) {
1345
+ throw new Error("Invalid signature bytes");
1346
+ }
1347
+ return result;
1348
+ }
1349
+ static fromHex(hex) {
1350
+ return _Signature.fromBytes((0, import_utils12.hexToBytes)(hex));
1351
+ }
1352
+ serialize(serializer) {
1353
+ serializer.serializeU8(this.scheme);
1354
+ this.inner.serialize(serializer);
1355
+ }
1356
+ toBytes() {
1357
+ const serializer = new import_ts_sdk7.Serializer();
1358
+ this.serialize(serializer);
1359
+ return serializer.toUint8Array();
1360
+ }
1361
+ toHex() {
1362
+ return (0, import_utils12.bytesToHex)(this.toBytes());
1363
+ }
1364
+ };
1365
+ function keygen6(schemeId) {
1366
+ const scheme = schemeId ?? SCHEME_SCHNORR_RISTRETTO255;
1367
+ if (scheme === SCHEME_SCHNORR_RISTRETTO255) {
1368
+ const sk = keygen5();
1369
+ return new SigningKey(scheme, sk);
1370
+ } else {
1371
+ throw new Error(`Unknown scheme: ${scheme}`);
1372
+ }
1373
+ }
1374
+ function deriveVerifyingKey2(sk) {
1375
+ if (sk.scheme === SCHEME_SCHNORR_RISTRETTO255) {
1376
+ const vk = deriveVerifyingKey(sk.inner);
1377
+ return new VerifyingKey(sk.scheme, vk);
1378
+ } else {
1379
+ throw new Error(`Unknown scheme: ${sk.scheme}`);
1380
+ }
1381
+ }
1382
+ function sign2(sk, msg) {
1383
+ if (sk.scheme === SCHEME_SCHNORR_RISTRETTO255) {
1384
+ const signature = sign(sk.inner, msg);
1385
+ return new Signature(sk.scheme, signature);
1386
+ } else {
1387
+ throw new Error(`Unknown scheme: ${sk.scheme}`);
1388
+ }
1389
+ }
1390
+ function signWithRandomness2(sk, msg, randomness) {
1391
+ if (sk.scheme === SCHEME_SCHNORR_RISTRETTO255) {
1392
+ const signature = signWithRandomness(sk.inner, msg, randomness);
1393
+ return new Signature(sk.scheme, signature);
1394
+ } else {
1395
+ throw new Error(`Unknown scheme: ${sk.scheme}`);
1396
+ }
1397
+ }
1398
+ function verify2(vk, msg, sig) {
1399
+ if (vk.scheme === SCHEME_SCHNORR_RISTRETTO255 && sig.scheme === SCHEME_SCHNORR_RISTRETTO255) {
1400
+ return verify(vk.inner, msg, sig.inner);
1401
+ } else {
1402
+ throw new Error(`Unknown scheme: vk=${vk.scheme}, sig=${sig.scheme}`);
1403
+ }
1404
+ }
1405
+
1406
+ // src/silent_setup_encryption.ts
1407
+ var silent_setup_encryption_exports = {};
1408
+ __export(silent_setup_encryption_exports, {
1409
+ Ciphertext: () => Ciphertext8,
1410
+ DecryptionContext: () => DecryptionContext,
1411
+ Decryptor: () => Decryptor,
1412
+ EncryptionContext: () => EncryptionContext,
1413
+ Encryptor: () => Encryptor,
1414
+ RequestForDecryptionKey: () => RequestForDecryptionKey
1415
+ });
1416
+ var import_ts_sdk16 = require("@aptos-labs/ts-sdk");
1417
+ var import_utils21 = require("@noble/curves/utils");
1418
+
1419
+ // src/shamir_gf256.ts
1420
+ var import_ts_sdk8 = require("@aptos-labs/ts-sdk");
1421
+ function hasDuplicates(array) {
1422
+ return new Set(array).size !== array.length;
1423
+ }
1424
+ function allEqual(array) {
1425
+ if (array.length === 0) {
1426
+ return true;
1427
+ }
1428
+ return array.every((item) => item === array[0]);
1429
+ }
1430
+ var GF256 = class _GF256 {
1431
+ value;
1432
+ constructor(value) {
1433
+ if (value < 0 || value >= GF256_SIZE) {
1434
+ throw new Error(`Invalid value ${value} for GF256`);
1435
+ }
1436
+ this.value = value;
1437
+ }
1438
+ log() {
1439
+ if (this.value === 0) {
1440
+ throw new Error("Invalid value");
1441
+ }
1442
+ return LOG[this.value - 1];
1443
+ }
1444
+ static exp(x) {
1445
+ return new _GF256(EXP[x % (GF256_SIZE - 1)]);
1446
+ }
1447
+ add(other) {
1448
+ return new _GF256(this.value ^ other.value);
1449
+ }
1450
+ sub(other) {
1451
+ return this.add(other);
1452
+ }
1453
+ neg() {
1454
+ return this;
1455
+ }
1456
+ mul(other) {
1457
+ if (this.value === 0 || other.value === 0) {
1458
+ return new _GF256(0);
1459
+ }
1460
+ return _GF256.exp(this.log() + other.log());
1461
+ }
1462
+ div(other) {
1463
+ return this.mul(_GF256.exp(GF256_SIZE - other.log() - 1));
1464
+ }
1465
+ equals(other) {
1466
+ return this.value === other.value;
1467
+ }
1468
+ static zero() {
1469
+ return new _GF256(0);
1470
+ }
1471
+ static one() {
1472
+ return new _GF256(1);
1473
+ }
1474
+ };
1475
+ var EXP = [
1476
+ 1,
1477
+ 3,
1478
+ 5,
1479
+ 15,
1480
+ 17,
1481
+ 51,
1482
+ 85,
1483
+ 255,
1484
+ 26,
1485
+ 46,
1486
+ 114,
1487
+ 150,
1488
+ 161,
1489
+ 248,
1490
+ 19,
1491
+ 53,
1492
+ 95,
1493
+ 225,
1494
+ 56,
1495
+ 72,
1496
+ 216,
1497
+ 115,
1498
+ 149,
1499
+ 164,
1500
+ 247,
1501
+ 2,
1502
+ 6,
1503
+ 10,
1504
+ 30,
1505
+ 34,
1506
+ 102,
1507
+ 170,
1508
+ 229,
1509
+ 52,
1510
+ 92,
1511
+ 228,
1512
+ 55,
1513
+ 89,
1514
+ 235,
1515
+ 38,
1516
+ 106,
1517
+ 190,
1518
+ 217,
1519
+ 112,
1520
+ 144,
1521
+ 171,
1522
+ 230,
1523
+ 49,
1524
+ 83,
1525
+ 245,
1526
+ 4,
1527
+ 12,
1528
+ 20,
1529
+ 60,
1530
+ 68,
1531
+ 204,
1532
+ 79,
1533
+ 209,
1534
+ 104,
1535
+ 184,
1536
+ 211,
1537
+ 110,
1538
+ 178,
1539
+ 205,
1540
+ 76,
1541
+ 212,
1542
+ 103,
1543
+ 169,
1544
+ 224,
1545
+ 59,
1546
+ 77,
1547
+ 215,
1548
+ 98,
1549
+ 166,
1550
+ 241,
1551
+ 8,
1552
+ 24,
1553
+ 40,
1554
+ 120,
1555
+ 136,
1556
+ 131,
1557
+ 158,
1558
+ 185,
1559
+ 208,
1560
+ 107,
1561
+ 189,
1562
+ 220,
1563
+ 127,
1564
+ 129,
1565
+ 152,
1566
+ 179,
1567
+ 206,
1568
+ 73,
1569
+ 219,
1570
+ 118,
1571
+ 154,
1572
+ 181,
1573
+ 196,
1574
+ 87,
1575
+ 249,
1576
+ 16,
1577
+ 48,
1578
+ 80,
1579
+ 240,
1580
+ 11,
1581
+ 29,
1582
+ 39,
1583
+ 105,
1584
+ 187,
1585
+ 214,
1586
+ 97,
1587
+ 163,
1588
+ 254,
1589
+ 25,
1590
+ 43,
1591
+ 125,
1592
+ 135,
1593
+ 146,
1594
+ 173,
1595
+ 236,
1596
+ 47,
1597
+ 113,
1598
+ 147,
1599
+ 174,
1600
+ 233,
1601
+ 32,
1602
+ 96,
1603
+ 160,
1604
+ 251,
1605
+ 22,
1606
+ 58,
1607
+ 78,
1608
+ 210,
1609
+ 109,
1610
+ 183,
1611
+ 194,
1612
+ 93,
1613
+ 231,
1614
+ 50,
1615
+ 86,
1616
+ 250,
1617
+ 21,
1618
+ 63,
1619
+ 65,
1620
+ 195,
1621
+ 94,
1622
+ 226,
1623
+ 61,
1624
+ 71,
1625
+ 201,
1626
+ 64,
1627
+ 192,
1628
+ 91,
1629
+ 237,
1630
+ 44,
1631
+ 116,
1632
+ 156,
1633
+ 191,
1634
+ 218,
1635
+ 117,
1636
+ 159,
1637
+ 186,
1638
+ 213,
1639
+ 100,
1640
+ 172,
1641
+ 239,
1642
+ 42,
1643
+ 126,
1644
+ 130,
1645
+ 157,
1646
+ 188,
1647
+ 223,
1648
+ 122,
1649
+ 142,
1650
+ 137,
1651
+ 128,
1652
+ 155,
1653
+ 182,
1654
+ 193,
1655
+ 88,
1656
+ 232,
1657
+ 35,
1658
+ 101,
1659
+ 175,
1660
+ 234,
1661
+ 37,
1662
+ 111,
1663
+ 177,
1664
+ 200,
1665
+ 67,
1666
+ 197,
1667
+ 84,
1668
+ 252,
1669
+ 31,
1670
+ 33,
1671
+ 99,
1672
+ 165,
1673
+ 244,
1674
+ 7,
1675
+ 9,
1676
+ 27,
1677
+ 45,
1678
+ 119,
1679
+ 153,
1680
+ 176,
1681
+ 203,
1682
+ 70,
1683
+ 202,
1684
+ 69,
1685
+ 207,
1686
+ 74,
1687
+ 222,
1688
+ 121,
1689
+ 139,
1690
+ 134,
1691
+ 145,
1692
+ 168,
1693
+ 227,
1694
+ 62,
1695
+ 66,
1696
+ 198,
1697
+ 81,
1698
+ 243,
1699
+ 14,
1700
+ 18,
1701
+ 54,
1702
+ 90,
1703
+ 238,
1704
+ 41,
1705
+ 123,
1706
+ 141,
1707
+ 140,
1708
+ 143,
1709
+ 138,
1710
+ 133,
1711
+ 148,
1712
+ 167,
1713
+ 242,
1714
+ 13,
1715
+ 23,
1716
+ 57,
1717
+ 75,
1718
+ 221,
1719
+ 124,
1720
+ 132,
1721
+ 151,
1722
+ 162,
1723
+ 253,
1724
+ 28,
1725
+ 36,
1726
+ 108,
1727
+ 180,
1728
+ 199,
1729
+ 82,
1730
+ 246
1731
+ ];
1732
+ var LOG = [
1733
+ 0,
1734
+ 25,
1735
+ 1,
1736
+ 50,
1737
+ 2,
1738
+ 26,
1739
+ 198,
1740
+ 75,
1741
+ 199,
1742
+ 27,
1743
+ 104,
1744
+ 51,
1745
+ 238,
1746
+ 223,
1747
+ 3,
1748
+ 100,
1749
+ 4,
1750
+ 224,
1751
+ 14,
1752
+ 52,
1753
+ 141,
1754
+ 129,
1755
+ 239,
1756
+ 76,
1757
+ 113,
1758
+ 8,
1759
+ 200,
1760
+ 248,
1761
+ 105,
1762
+ 28,
1763
+ 193,
1764
+ 125,
1765
+ 194,
1766
+ 29,
1767
+ 181,
1768
+ 249,
1769
+ 185,
1770
+ 39,
1771
+ 106,
1772
+ 77,
1773
+ 228,
1774
+ 166,
1775
+ 114,
1776
+ 154,
1777
+ 201,
1778
+ 9,
1779
+ 120,
1780
+ 101,
1781
+ 47,
1782
+ 138,
1783
+ 5,
1784
+ 33,
1785
+ 15,
1786
+ 225,
1787
+ 36,
1788
+ 18,
1789
+ 240,
1790
+ 130,
1791
+ 69,
1792
+ 53,
1793
+ 147,
1794
+ 218,
1795
+ 142,
1796
+ 150,
1797
+ 143,
1798
+ 219,
1799
+ 189,
1800
+ 54,
1801
+ 208,
1802
+ 206,
1803
+ 148,
1804
+ 19,
1805
+ 92,
1806
+ 210,
1807
+ 241,
1808
+ 64,
1809
+ 70,
1810
+ 131,
1811
+ 56,
1812
+ 102,
1813
+ 221,
1814
+ 253,
1815
+ 48,
1816
+ 191,
1817
+ 6,
1818
+ 139,
1819
+ 98,
1820
+ 179,
1821
+ 37,
1822
+ 226,
1823
+ 152,
1824
+ 34,
1825
+ 136,
1826
+ 145,
1827
+ 16,
1828
+ 126,
1829
+ 110,
1830
+ 72,
1831
+ 195,
1832
+ 163,
1833
+ 182,
1834
+ 30,
1835
+ 66,
1836
+ 58,
1837
+ 107,
1838
+ 40,
1839
+ 84,
1840
+ 250,
1841
+ 133,
1842
+ 61,
1843
+ 186,
1844
+ 43,
1845
+ 121,
1846
+ 10,
1847
+ 21,
1848
+ 155,
1849
+ 159,
1850
+ 94,
1851
+ 202,
1852
+ 78,
1853
+ 212,
1854
+ 172,
1855
+ 229,
1856
+ 243,
1857
+ 115,
1858
+ 167,
1859
+ 87,
1860
+ 175,
1861
+ 88,
1862
+ 168,
1863
+ 80,
1864
+ 244,
1865
+ 234,
1866
+ 214,
1867
+ 116,
1868
+ 79,
1869
+ 174,
1870
+ 233,
1871
+ 213,
1872
+ 231,
1873
+ 230,
1874
+ 173,
1875
+ 232,
1876
+ 44,
1877
+ 215,
1878
+ 117,
1879
+ 122,
1880
+ 235,
1881
+ 22,
1882
+ 11,
1883
+ 245,
1884
+ 89,
1885
+ 203,
1886
+ 95,
1887
+ 176,
1888
+ 156,
1889
+ 169,
1890
+ 81,
1891
+ 160,
1892
+ 127,
1893
+ 12,
1894
+ 246,
1895
+ 111,
1896
+ 23,
1897
+ 196,
1898
+ 73,
1899
+ 236,
1900
+ 216,
1901
+ 67,
1902
+ 31,
1903
+ 45,
1904
+ 164,
1905
+ 118,
1906
+ 123,
1907
+ 183,
1908
+ 204,
1909
+ 187,
1910
+ 62,
1911
+ 90,
1912
+ 251,
1913
+ 96,
1914
+ 177,
1915
+ 134,
1916
+ 59,
1917
+ 82,
1918
+ 161,
1919
+ 108,
1920
+ 170,
1921
+ 85,
1922
+ 41,
1923
+ 157,
1924
+ 151,
1925
+ 178,
1926
+ 135,
1927
+ 144,
1928
+ 97,
1929
+ 190,
1930
+ 220,
1931
+ 252,
1932
+ 188,
1933
+ 149,
1934
+ 207,
1935
+ 205,
1936
+ 55,
1937
+ 63,
1938
+ 91,
1939
+ 209,
1940
+ 83,
1941
+ 57,
1942
+ 132,
1943
+ 60,
1944
+ 65,
1945
+ 162,
1946
+ 109,
1947
+ 71,
1948
+ 20,
1949
+ 42,
1950
+ 158,
1951
+ 93,
1952
+ 86,
1953
+ 242,
1954
+ 211,
1955
+ 171,
1956
+ 68,
1957
+ 17,
1958
+ 146,
1959
+ 217,
1960
+ 35,
1961
+ 32,
1962
+ 46,
1963
+ 137,
1964
+ 180,
1965
+ 124,
1966
+ 184,
1967
+ 38,
1968
+ 119,
1969
+ 153,
1970
+ 227,
1971
+ 165,
1972
+ 103,
1973
+ 74,
1974
+ 237,
1975
+ 222,
1976
+ 197,
1977
+ 49,
1978
+ 254,
1979
+ 24,
1980
+ 13,
1981
+ 99,
1982
+ 140,
1983
+ 128,
1984
+ 192,
1985
+ 247,
1986
+ 112,
1987
+ 7
1988
+ ];
1989
+ var Polynomial = class _Polynomial {
1990
+ coefficients;
1991
+ /**
1992
+ * Construct a new Polynomial over [GF256] from the given coefficients.
1993
+ * The first coefficient is the constant term.
1994
+ */
1995
+ constructor(coefficients) {
1996
+ this.coefficients = coefficients.slice();
1997
+ while (this.coefficients.length > 0 && this.coefficients[this.coefficients.length - 1].value === 0) {
1998
+ this.coefficients.pop();
1999
+ }
2000
+ }
2001
+ static fromBytes(bytes) {
2002
+ return new _Polynomial(Array.from(bytes, (b) => new GF256(b)));
2003
+ }
2004
+ degree() {
2005
+ if (this.coefficients.length === 0) {
2006
+ return 0;
2007
+ }
2008
+ return this.coefficients.length - 1;
2009
+ }
2010
+ getCoefficient(index) {
2011
+ if (index >= this.coefficients.length) {
2012
+ return GF256.zero();
2013
+ }
2014
+ return this.coefficients[index];
2015
+ }
2016
+ add(other) {
2017
+ const degree = Math.max(this.degree(), other.degree());
2018
+ return new _Polynomial(
2019
+ Array.from(
2020
+ { length: degree + 1 },
2021
+ (_, i) => this.getCoefficient(i).add(other.getCoefficient(i))
2022
+ )
2023
+ );
2024
+ }
2025
+ mul(other) {
2026
+ const degree = this.degree() + other.degree();
2027
+ return new _Polynomial(
2028
+ Array.from({ length: degree + 1 }, (_, i) => {
2029
+ let sum = GF256.zero();
2030
+ for (let j = 0; j <= i; j++) {
2031
+ if (j <= this.degree() && i - j <= other.degree()) {
2032
+ sum = sum.add(this.getCoefficient(j).mul(other.getCoefficient(i - j)));
2033
+ }
2034
+ }
2035
+ return sum;
2036
+ })
2037
+ );
2038
+ }
2039
+ /** The polynomial s * this. */
2040
+ scale(s) {
2041
+ return new _Polynomial(this.coefficients.map((c) => c.mul(s)));
2042
+ }
2043
+ div(s) {
2044
+ return this.scale(new GF256(1).div(s));
2045
+ }
2046
+ /** The polynomial x + c. */
2047
+ static monic_linear(c) {
2048
+ return new _Polynomial([c, GF256.one()]);
2049
+ }
2050
+ static zero() {
2051
+ return new _Polynomial([]);
2052
+ }
2053
+ static one() {
2054
+ return new _Polynomial([GF256.one()]);
2055
+ }
2056
+ /** Given a set of coordinates, interpolate a polynomial. */
2057
+ static interpolate(coordinates) {
2058
+ if (coordinates.length < 1) {
2059
+ throw new Error("At least one coefficient is required");
2060
+ }
2061
+ if (hasDuplicates(coordinates.map(({ x }) => x.value))) {
2062
+ throw new Error("Coefficients must have unique x values");
2063
+ }
2064
+ return coordinates.reduce(
2065
+ (sum, { x: x_j, y: y_j }, j) => sum.add(
2066
+ coordinates.filter((_, i) => i !== j).reduce(
2067
+ (product, { x: x_i }) => product.mul(_Polynomial.monic_linear(x_i.neg()).div(x_j.sub(x_i))),
2068
+ _Polynomial.one()
2069
+ ).scale(y_j)
2070
+ ),
2071
+ _Polynomial.zero()
2072
+ );
2073
+ }
2074
+ /** Given a set of coordinates, interpolate a polynomial and evaluate it at x = 0. */
2075
+ static combine(coordinates) {
2076
+ if (coordinates.length < 1) {
2077
+ throw new Error("At least one coefficient is required");
2078
+ }
2079
+ const xValues = coordinates.map(({ x }) => x.value);
2080
+ if (hasDuplicates(xValues)) {
2081
+ throw new Error(`Coefficients must have unique x values. Found duplicates: ${xValues.join(", ")}`);
2082
+ }
2083
+ const quotient = coordinates.reduce((sum, { x: x_j, y: y_j }, j) => {
2084
+ const denominator = x_j.mul(
2085
+ coordinates.filter((_, i) => i !== j).reduce((product, { x: x_i }) => {
2086
+ const diff = x_i.sub(x_j);
2087
+ if (diff.value === 0) {
2088
+ throw new Error(`Duplicate x values detected: x_i=${x_i.value}, x_j=${x_j.value}`);
2089
+ }
2090
+ return product.mul(diff);
2091
+ }, GF256.one())
2092
+ );
2093
+ return sum.add(y_j.div(denominator));
2094
+ }, GF256.zero());
2095
+ const xProduct = coordinates.reduce((product, { x }) => product.mul(x), GF256.one());
2096
+ return xProduct.mul(quotient);
2097
+ }
2098
+ /** Evaluate the polynomial at x. */
2099
+ evaluate(x) {
2100
+ return this.coefficients.slice().reverse().reduce((sum, coefficient) => sum.mul(x).add(coefficient), GF256.zero());
2101
+ }
2102
+ equals(other) {
2103
+ if (this.coefficients.length !== other.coefficients.length) {
2104
+ return false;
2105
+ }
2106
+ return this.coefficients.every((c, i) => c.equals(other.getCoefficient(i)));
2107
+ }
2108
+ };
2109
+ var GF256_SIZE = 256;
2110
+ var Share = class _Share {
2111
+ index;
2112
+ payload;
2113
+ constructor(index, payload) {
2114
+ this.index = index;
2115
+ this.payload = payload;
2116
+ }
2117
+ deserialize(deserializer) {
2118
+ this.index = deserializer.deserializeU8();
2119
+ this.payload = deserializer.deserializeBytes();
2120
+ }
2121
+ static fromBytes(bytes) {
2122
+ const deserializer = new import_ts_sdk8.Deserializer(bytes);
2123
+ const share = new _Share(0, new Uint8Array());
2124
+ share.deserialize(deserializer);
2125
+ return share;
2126
+ }
2127
+ serialize(serializer) {
2128
+ serializer.serializeU8(this.index);
2129
+ serializer.serializeBytes(this.payload);
2130
+ }
2131
+ toBytes() {
2132
+ const serializer = new import_ts_sdk8.Serializer();
2133
+ this.serialize(serializer);
2134
+ return serializer.toUint8Array();
2135
+ }
2136
+ };
2137
+ function toInternalShare(share) {
2138
+ return {
2139
+ index: new GF256(share.index),
2140
+ payload: Array.from(share.payload, (byte) => new GF256(byte))
2141
+ };
2142
+ }
2143
+ function toShare(internalShare) {
2144
+ return new Share(internalShare.index.value, new Uint8Array(internalShare.payload.map((byte) => byte.value)));
2145
+ }
2146
+ function samplePolynomial(constant, degree) {
2147
+ const randomCoefficients = new Uint8Array(degree);
2148
+ crypto.getRandomValues(randomCoefficients);
2149
+ return Polynomial.fromBytes(new Uint8Array([constant.value, ...randomCoefficients]));
2150
+ }
2151
+ function split(secret, threshold, total) {
2152
+ if (threshold > total || threshold < 1 || total > GF256_SIZE) {
2153
+ throw new Error(`Invalid threshold ${threshold} or total ${total}`);
2154
+ }
2155
+ const polynomials = Array.from(secret, (s) => samplePolynomial(new GF256(s), threshold - 1));
2156
+ return Array.from({ length: total }, (_, i) => {
2157
+ const index = new GF256(i + 1);
2158
+ const payload = polynomials.map((p) => p.evaluate(index));
2159
+ return toShare({ index, payload });
2160
+ });
2161
+ }
2162
+ function validateShares(shares) {
2163
+ if (shares.length < 1) {
2164
+ throw new Error("At least one share is required");
2165
+ }
2166
+ if (!allEqual(shares.map(({ payload }) => payload.length))) {
2167
+ throw new Error("All shares must have the same length");
2168
+ }
2169
+ if (hasDuplicates(shares.map(({ index }) => index))) {
2170
+ throw new Error("Shares must have unique indices");
2171
+ }
2172
+ const internalShares = shares.map(toInternalShare);
2173
+ const length = internalShares[0].payload.length;
2174
+ return { internalShares, length };
2175
+ }
2176
+ function combine(shares) {
2177
+ const { internalShares, length } = validateShares(shares);
2178
+ return new Uint8Array(
2179
+ Array.from(
2180
+ { length },
2181
+ (_, i) => Polynomial.combine(
2182
+ internalShares.map(({ index, payload }) => ({
2183
+ x: index,
2184
+ y: payload[i]
2185
+ }))
2186
+ ).value
2187
+ )
2188
+ );
2189
+ }
2190
+
2191
+ // src/sym/index.ts
2192
+ var sym_exports = {};
2193
+ __export(sym_exports, {
2194
+ Ciphertext: () => Ciphertext6,
2195
+ Key: () => Key2,
2196
+ decrypt: () => decrypt6,
2197
+ encrypt: () => encrypt6,
2198
+ encryptWithRandomness: () => encryptWithRandomness6,
2199
+ keygen: () => keygen8
2200
+ });
2201
+ var import_ts_sdk10 = require("@aptos-labs/ts-sdk");
2202
+ var import_utils15 = require("@noble/curves/utils");
2203
+
2204
+ // src/sym/aes256gcm.ts
2205
+ var import_ts_sdk9 = require("@aptos-labs/ts-sdk");
2206
+ var import_aes = require("@noble/ciphers/aes");
2207
+ var import_utils13 = require("@noble/curves/utils");
2208
+ var Key = class _Key {
2209
+ inner;
2210
+ constructor(inner) {
2211
+ this.inner = inner;
2212
+ }
2213
+ static deserialize(deserializer) {
2214
+ const inner = deserializer.deserializeFixedBytes(32);
2215
+ return new _Key(inner);
2216
+ }
2217
+ serialize(serializer) {
2218
+ serializer.serializeFixedBytes(this.inner);
2219
+ }
2220
+ toBytes() {
2221
+ const serializer = new import_ts_sdk9.Serializer();
2222
+ this.serialize(serializer);
2223
+ return serializer.toUint8Array();
2224
+ }
2225
+ toHex() {
2226
+ return (0, import_utils13.bytesToHex)(this.toBytes());
2227
+ }
2228
+ };
2229
+ var Ciphertext5 = class _Ciphertext {
2230
+ iv;
2231
+ ct;
2232
+ tag;
2233
+ constructor(iv, ct, tag) {
2234
+ this.iv = iv;
2235
+ this.ct = ct;
2236
+ this.tag = tag;
2237
+ }
2238
+ static dummy() {
2239
+ return new _Ciphertext(new Uint8Array(12), new Uint8Array(0), new Uint8Array(16));
2240
+ }
2241
+ static deserialize(deserializer) {
2242
+ let iv = deserializer.deserializeFixedBytes(12);
2243
+ let ct = deserializer.deserializeBytes();
2244
+ let tag = deserializer.deserializeFixedBytes(16);
2245
+ return new _Ciphertext(iv, ct, tag);
2246
+ }
2247
+ static fromBytes(bytes) {
2248
+ let deserializer = new import_ts_sdk9.Deserializer(bytes);
2249
+ const result = _Ciphertext.deserialize(deserializer);
2250
+ if (deserializer.remaining() !== 0) {
2251
+ throw new Error("Invalid ciphertext bytes");
2252
+ }
2253
+ return result;
2254
+ }
2255
+ static fromHex(hex) {
2256
+ return _Ciphertext.fromBytes((0, import_utils13.hexToBytes)(hex));
2257
+ }
2258
+ serialize(serializer) {
2259
+ serializer.serializeFixedBytes(this.iv);
2260
+ serializer.serializeBytes(this.ct);
2261
+ serializer.serializeFixedBytes(this.tag);
2262
+ }
2263
+ toBytes() {
2264
+ let serializer = new import_ts_sdk9.Serializer();
2265
+ this.serialize(serializer);
2266
+ return serializer.toUint8Array();
2267
+ }
2268
+ toHex() {
2269
+ return (0, import_utils13.bytesToHex)(this.toBytes());
2270
+ }
2271
+ };
2272
+ function keygen7() {
2273
+ return new Key(randBytes(32));
2274
+ }
2275
+ function encrypt5(key, plaintext) {
2276
+ const nonce = randBytes(12);
2277
+ return encryptWithRandomness5(key, plaintext, nonce);
2278
+ }
2279
+ function encryptWithRandomness5(key, plaintext, randomness) {
2280
+ const nonce = randomness.slice(0, 12);
2281
+ const gcmInstance = (0, import_aes.gcm)(key.inner, nonce);
2282
+ const encrypted = gcmInstance.encrypt(plaintext);
2283
+ const tagLength = 16;
2284
+ const ciphertext = encrypted.slice(0, -tagLength);
2285
+ const tag = encrypted.slice(-tagLength);
2286
+ return new Ciphertext5(nonce, ciphertext, tag);
2287
+ }
2288
+ function decrypt5(key, ciphertext) {
2289
+ const gcmInstance = (0, import_aes.gcm)(key.inner, ciphertext.iv);
2290
+ const encryptedData = new Uint8Array(ciphertext.ct.length + ciphertext.tag.length);
2291
+ encryptedData.set(ciphertext.ct, 0);
2292
+ encryptedData.set(ciphertext.tag, ciphertext.ct.length);
2293
+ try {
2294
+ return gcmInstance.decrypt(encryptedData);
2295
+ } catch (e) {
2296
+ console.log("Failed to decrypt AES-256-GCM ciphertext", e);
2297
+ return void 0;
2298
+ }
2299
+ }
2300
+
2301
+ // src/sym/index.ts
2302
+ var SCHEME_AES256GCM = 0;
2303
+ var Key2 = class _Key {
2304
+ scheme;
2305
+ inner;
2306
+ constructor(scheme, inner) {
2307
+ this.scheme = scheme;
2308
+ this.inner = inner;
2309
+ }
2310
+ static deserialize(deserializer) {
2311
+ const scheme = deserializer.deserializeU8();
2312
+ if (scheme === SCHEME_AES256GCM) {
2313
+ const inner = Key.deserialize(deserializer);
2314
+ return new _Key(scheme, inner);
2315
+ }
2316
+ throw new Error("Invalid scheme");
2317
+ }
2318
+ static fromBytes(bytes) {
2319
+ const deserializer = new import_ts_sdk10.Deserializer(bytes);
2320
+ const result = _Key.deserialize(deserializer);
2321
+ if (deserializer.remaining() !== 0) {
2322
+ throw new Error("Invalid key bytes");
2323
+ }
2324
+ return result;
2325
+ }
2326
+ serialize(serializer) {
2327
+ serializer.serializeU8(this.scheme);
2328
+ if (this.scheme === SCHEME_AES256GCM) {
2329
+ this.inner.serialize(serializer);
2330
+ } else {
2331
+ throw new Error("Invalid scheme");
2332
+ }
2333
+ }
2334
+ toBytes() {
2335
+ const serializer = new import_ts_sdk10.Serializer();
2336
+ this.serialize(serializer);
2337
+ return serializer.toUint8Array();
2338
+ }
2339
+ toHex() {
2340
+ return (0, import_utils15.bytesToHex)(this.toBytes());
2341
+ }
2342
+ };
2343
+ var Ciphertext6 = class _Ciphertext {
2344
+ scheme;
2345
+ inner;
2346
+ constructor(scheme, inner) {
2347
+ this.scheme = scheme;
2348
+ this.inner = inner;
2349
+ }
2350
+ static dummy() {
2351
+ return new _Ciphertext(SCHEME_AES256GCM, Ciphertext5.dummy());
2352
+ }
2353
+ static deserialize(deserializer) {
2354
+ const scheme = deserializer.deserializeU8();
2355
+ if (scheme === SCHEME_AES256GCM) {
2356
+ const inner = Ciphertext5.deserialize(deserializer);
2357
+ return new _Ciphertext(scheme, inner);
2358
+ }
2359
+ throw new Error("Invalid scheme");
2360
+ }
2361
+ static fromBytes(bytes) {
2362
+ const deserializer = new import_ts_sdk10.Deserializer(bytes);
2363
+ const result = _Ciphertext.deserialize(deserializer);
2364
+ if (deserializer.remaining() !== 0) {
2365
+ throw new Error("Invalid ciphertext bytes");
2366
+ }
2367
+ return result;
2368
+ }
2369
+ serialize(serializer) {
2370
+ serializer.serializeU8(this.scheme);
2371
+ this.inner.serialize(serializer);
2372
+ }
2373
+ toBytes() {
2374
+ const serializer = new import_ts_sdk10.Serializer();
2375
+ this.serialize(serializer);
2376
+ return serializer.toUint8Array();
2377
+ }
2378
+ toHex() {
2379
+ return (0, import_utils15.bytesToHex)(this.toBytes());
2380
+ }
2381
+ };
2382
+ function keygen8(scheme) {
2383
+ if (scheme === void 0) {
2384
+ scheme = SCHEME_AES256GCM;
2385
+ }
2386
+ if (scheme === SCHEME_AES256GCM) {
2387
+ return new Key2(SCHEME_AES256GCM, keygen7());
2388
+ }
2389
+ throw new Error("Invalid scheme");
2390
+ }
2391
+ function encrypt6(key, plaintext) {
2392
+ if (key.scheme === SCHEME_AES256GCM) {
2393
+ return new Ciphertext6(SCHEME_AES256GCM, encrypt5(key.inner, plaintext));
2394
+ }
2395
+ throw new Error("Invalid scheme");
2396
+ }
2397
+ function encryptWithRandomness6(key, plaintext, randomness) {
2398
+ if (key.scheme === SCHEME_AES256GCM) {
2399
+ return new Ciphertext6(SCHEME_AES256GCM, encryptWithRandomness5(key.inner, plaintext, randomness));
2400
+ }
2401
+ throw new Error("Invalid scheme");
2402
+ }
2403
+ function decrypt6(key, ciphertext) {
2404
+ if (key.scheme === SCHEME_AES256GCM) {
2405
+ return decrypt5(key.inner, ciphertext.inner);
2406
+ }
2407
+ throw new Error("Invalid scheme");
2408
+ }
2409
+
2410
+ // src/worker_config.ts
2411
+ var worker_config_exports = {};
2412
+ __export(worker_config_exports, {
2413
+ WorkerConfig: () => WorkerConfig,
2414
+ get: () => get,
2415
+ randWorker: () => randWorker,
2416
+ view: () => view
2417
+ });
2418
+ var import_ts_sdk11 = require("@aptos-labs/ts-sdk");
2419
+ var import_utils16 = require("@noble/curves/utils");
2420
+ var WorkerConfig = class _WorkerConfig {
2421
+ expiryTimeMicrosecs;
2422
+ endpoint;
2423
+ encEk;
2424
+ sigVk;
2425
+ ibeMpk;
2426
+ constructor(expiryTimeMicrosecs, endpoint, encEk, sigVk, ibeMpk) {
2427
+ this.expiryTimeMicrosecs = expiryTimeMicrosecs;
2428
+ this.endpoint = endpoint;
2429
+ this.encEk = encEk;
2430
+ this.sigVk = sigVk;
2431
+ this.ibeMpk = ibeMpk;
2432
+ }
2433
+ static dummy() {
2434
+ const encDk = keygen2();
2435
+ const encEk = deriveEncryptionKey2(encDk);
2436
+ const sigSk = keygen6();
2437
+ const sigVk = deriveVerifyingKey2(sigSk);
2438
+ const ibeMsk = keygen4();
2439
+ const ibeMpk = derivePublicKey2(ibeMsk);
2440
+ return new _WorkerConfig(1e18, "http://localhost:3000", encEk, sigVk, ibeMpk);
2441
+ }
2442
+ static deserialize(deserializer) {
2443
+ const expiryTimeMicrosecs = Number(deserializer.deserializeU64());
2444
+ const endpoint = deserializer.deserializeStr();
2445
+ const encEk = EncryptionKey.deserialize(deserializer);
2446
+ const sigVk = VerifyingKey.deserialize(deserializer);
2447
+ const ibeMpk = MasterPublicKey2.deserialize(deserializer);
2448
+ return new _WorkerConfig(expiryTimeMicrosecs, endpoint, encEk, sigVk, ibeMpk);
2449
+ }
2450
+ static fromBytes(bytes) {
2451
+ const deserializer = new import_ts_sdk11.Deserializer(bytes);
2452
+ return _WorkerConfig.deserialize(deserializer);
2453
+ }
2454
+ static fromHex(hex) {
2455
+ return _WorkerConfig.fromBytes((0, import_utils16.hexToBytes)(hex));
2456
+ }
2457
+ serialize(serializer) {
2458
+ serializer.serializeU64(BigInt(this.expiryTimeMicrosecs));
2459
+ serializer.serializeStr(this.endpoint);
2460
+ this.encEk.serialize(serializer);
2461
+ this.sigVk.serialize(serializer);
2462
+ this.ibeMpk.serialize(serializer);
2463
+ }
2464
+ toBytes() {
2465
+ const serializer = new import_ts_sdk11.Serializer();
2466
+ this.serialize(serializer);
2467
+ return serializer.toUint8Array();
2468
+ }
2469
+ toHex() {
2470
+ return (0, import_utils16.bytesToHex)(this.toBytes());
2471
+ }
2472
+ toPrettyJson() {
2473
+ return JSON.stringify({
2474
+ expiryTimeMicrosecs: this.expiryTimeMicrosecs,
2475
+ endpoint: this.endpoint,
2476
+ encEk: this.encEk.toHex(),
2477
+ sigVk: this.sigVk.toHex(),
2478
+ ibeMpk: this.ibeMpk.toHex()
2479
+ }, null, 2);
2480
+ }
2481
+ };
2482
+ async function view(aptos, worker) {
2483
+ const moduleAddrHex = aptos.config.network === import_ts_sdk11.Network.SHELBYNET ? utils_exports.SHELBYNET_CONTRACT_ADDRESS_HEX : utils_exports.CONTRACT_ADDRESS_HEX;
2484
+ const configBcsMoveVals = await aptos.view({
2485
+ payload: {
2486
+ function: `${moduleAddrHex}::worker_config::get_bcs`,
2487
+ typeArguments: [],
2488
+ functionArguments: [worker]
2489
+ }
2490
+ });
2491
+ return WorkerConfig.fromHex(configBcsMoveVals[0].toString().slice(2));
2492
+ }
2493
+ async function get(workerEndpoint) {
2494
+ const url = `${workerEndpoint}/config_bcs`;
2495
+ const response = await fetch(url, {
2496
+ method: "GET"
2497
+ });
2498
+ if (!response.ok) {
2499
+ throw new Error(`Failed to fetch worker config: ${response.status} ${response.statusText}`);
2500
+ }
2501
+ const hex = await response.text();
2502
+ return WorkerConfig.fromHex(hex);
2503
+ }
2504
+ function randWorker() {
2505
+ const addr = new import_ts_sdk11.AccountAddress(utils_exports.randBytes(32));
2506
+ const encDk = keygen2();
2507
+ const encEk = deriveEncryptionKey2(encDk);
2508
+ const sigSk = keygen6();
2509
+ const sigVk = deriveVerifyingKey2(sigSk);
2510
+ const ibeMsk = keygen4();
2511
+ const ibeMpk = derivePublicKey2(ibeMsk);
2512
+ const config = new WorkerConfig(1e6, "http://localhost:3000", encEk, sigVk, ibeMpk);
2513
+ return { addr, config, encDk, sigSk, ibeMsk };
2514
+ }
2515
+
2516
+ // src/worker_task.ts
2517
+ var import_ts_sdk15 = require("@aptos-labs/ts-sdk");
2518
+ var import_utils20 = require("@noble/hashes/utils");
2519
+
2520
+ // src/threshold-ibe/index.ts
2521
+ var threshold_ibe_exports = {};
2522
+ __export(threshold_ibe_exports, {
2523
+ Ciphertext: () => Ciphertext7,
2524
+ Committee: () => Committee,
2525
+ ContractID: () => ContractID3,
2526
+ DecryptionKey: () => DecryptionKey2,
2527
+ EncryptionKey: () => EncryptionKey2,
2528
+ FullDecryptionDomain: () => FullDecryptionDomain,
2529
+ ProofOfPermission: () => ProofOfPermission3,
2530
+ decrypt: () => decrypt7,
2531
+ encrypt: () => encrypt7,
2532
+ verifyAndExtract: () => verifyAndExtract
2533
+ });
2534
+ var import_ts_sdk14 = require("@aptos-labs/ts-sdk");
2535
+ var import_utils19 = require("@noble/hashes/utils");
2536
+ var SolanaSDK = __toESM(require("@solana/web3.js"));
2537
+
2538
+ // src/threshold-ibe/aptos.ts
2539
+ var import_ts_sdk12 = require("@aptos-labs/ts-sdk");
2540
+ var import_utils17 = require("@noble/hashes/utils");
2541
+ var ContractID = class _ContractID {
2542
+ chainId;
2543
+ moduleAddr;
2544
+ moduleName;
2545
+ functionName;
2546
+ constructor(chainId, moduleAddr, moduleName, functionName) {
2547
+ this.chainId = chainId;
2548
+ this.moduleAddr = moduleAddr;
2549
+ this.moduleName = moduleName;
2550
+ this.functionName = functionName;
2551
+ }
2552
+ static dummy() {
2553
+ return new _ContractID(0, import_ts_sdk12.AccountAddress.fromString("0x1"), "module3", "function3");
2554
+ }
2555
+ static deserialize(deserializer) {
2556
+ const chainId = deserializer.deserializeU8();
2557
+ const moduleAddr = deserializer.deserialize(import_ts_sdk12.AccountAddress);
2558
+ const moduleName = deserializer.deserializeStr();
2559
+ const functionName = deserializer.deserializeStr();
2560
+ return new _ContractID(chainId, moduleAddr, moduleName, functionName);
2561
+ }
2562
+ static fromBytes(bytes) {
2563
+ const deserializer = new import_ts_sdk12.Deserializer(bytes);
2564
+ const ret = _ContractID.deserialize(deserializer);
2565
+ if (deserializer.remaining() !== 0) {
2566
+ throw new Error("ContractID deserialization failed: extra bytes");
2567
+ }
2568
+ return ret;
2569
+ }
2570
+ static fromHex(hex) {
2571
+ return _ContractID.fromBytes((0, import_utils17.hexToBytes)(hex));
2572
+ }
2573
+ serialize(serializer) {
2574
+ serializer.serializeU8(this.chainId);
2575
+ serializer.serialize(this.moduleAddr);
2576
+ serializer.serializeStr(this.moduleName);
2577
+ serializer.serializeStr(this.functionName);
2578
+ }
2579
+ toBytes() {
2580
+ const serializer = new import_ts_sdk12.Serializer();
2581
+ this.serialize(serializer);
2582
+ return serializer.toUint8Array();
2583
+ }
2584
+ toHex() {
2585
+ return (0, import_utils17.bytesToHex)(this.toBytes());
2586
+ }
2587
+ toPrettyMessage(indent = 0) {
2588
+ const pad = " ".repeat(indent);
2589
+ return `
2590
+ ${pad}chainId: ${this.chainId}
2591
+ ${pad}moduleAddr: ${this.moduleAddr.toStringLong()}
2592
+ ${pad}moduleName: ${this.moduleName}
2593
+ ${pad}functionName: ${this.functionName}`;
2594
+ }
2595
+ };
2596
+ var PK_SCHEME_ED25519 = 0;
2597
+ var PK_SCHEME_ANY = 1;
2598
+ var PK_SCHEME_MULTI_ED25519 = 2;
2599
+ var PK_SCHEME_MULTI_KEY = 3;
2600
+ var PK_SCHEME_KEYLESS = 4;
2601
+ var PK_SCHEME_FEDERATED_KEYLESS = 5;
2602
+ function getPublicKeyScheme(publicKey) {
2603
+ if (publicKey instanceof import_ts_sdk12.Ed25519PublicKey) {
2604
+ return PK_SCHEME_ED25519;
2605
+ } else if (publicKey instanceof import_ts_sdk12.AnyPublicKey) {
2606
+ return PK_SCHEME_ANY;
2607
+ } else if (publicKey instanceof import_ts_sdk12.MultiEd25519PublicKey) {
2608
+ return PK_SCHEME_MULTI_ED25519;
2609
+ } else if (publicKey instanceof import_ts_sdk12.MultiKey) {
2610
+ return PK_SCHEME_MULTI_KEY;
2611
+ } else if (publicKey instanceof import_ts_sdk12.KeylessPublicKey) {
2612
+ return PK_SCHEME_KEYLESS;
2613
+ } else if (publicKey instanceof import_ts_sdk12.FederatedKeylessPublicKey) {
2614
+ return PK_SCHEME_FEDERATED_KEYLESS;
2615
+ } else {
2616
+ throw new Error(`Unsupported public key type: ${publicKey.constructor.name}`);
2617
+ }
2618
+ }
2619
+ function deserializePublicKey(scheme, deserializer) {
2620
+ if (scheme === PK_SCHEME_ED25519) {
2621
+ return deserializer.deserialize(import_ts_sdk12.Ed25519PublicKey);
2622
+ } else if (scheme === PK_SCHEME_ANY) {
2623
+ return deserializer.deserialize(import_ts_sdk12.AnyPublicKey);
2624
+ } else if (scheme === PK_SCHEME_MULTI_ED25519) {
2625
+ return deserializer.deserialize(import_ts_sdk12.MultiEd25519PublicKey);
2626
+ } else if (scheme === PK_SCHEME_MULTI_KEY) {
2627
+ return deserializer.deserialize(import_ts_sdk12.MultiKey);
2628
+ } else if (scheme === PK_SCHEME_KEYLESS) {
2629
+ return deserializer.deserialize(import_ts_sdk12.KeylessPublicKey);
2630
+ } else if (scheme === PK_SCHEME_FEDERATED_KEYLESS) {
2631
+ return deserializer.deserialize(import_ts_sdk12.FederatedKeylessPublicKey);
2632
+ } else {
2633
+ throw new Error(`Unsupported public key scheme: ${scheme}`);
2634
+ }
2635
+ }
2636
+ var SIG_SCHEME_ED25519 = 0;
2637
+ var SIG_SCHEME_ANY = 1;
2638
+ var SIG_SCHEME_MULTI_ED25519 = 2;
2639
+ var SIG_SCHEME_MULTI_KEY = 3;
2640
+ var SIG_SCHEME_KEYLESS = 4;
2641
+ function getSignatureScheme(signature) {
2642
+ if (signature instanceof import_ts_sdk12.Ed25519Signature) {
2643
+ return SIG_SCHEME_ED25519;
2644
+ } else if (signature instanceof import_ts_sdk12.AnySignature) {
2645
+ return SIG_SCHEME_ANY;
2646
+ } else if (signature instanceof import_ts_sdk12.MultiEd25519Signature) {
2647
+ return SIG_SCHEME_MULTI_ED25519;
2648
+ } else if (signature instanceof import_ts_sdk12.MultiKeySignature) {
2649
+ return SIG_SCHEME_MULTI_KEY;
2650
+ } else if (signature instanceof import_ts_sdk12.KeylessSignature) {
2651
+ return SIG_SCHEME_KEYLESS;
2652
+ } else {
2653
+ throw new Error(`Unsupported signature type: ${signature.constructor.name}`);
2654
+ }
2655
+ }
2656
+ function deserializeSignature(scheme, deserializer) {
2657
+ if (scheme === SIG_SCHEME_ED25519) {
2658
+ return deserializer.deserialize(import_ts_sdk12.Ed25519Signature);
2659
+ } else if (scheme === SIG_SCHEME_ANY) {
2660
+ return deserializer.deserialize(import_ts_sdk12.AnySignature);
2661
+ } else if (scheme === SIG_SCHEME_MULTI_ED25519) {
2662
+ return deserializer.deserialize(import_ts_sdk12.MultiEd25519Signature);
2663
+ } else if (scheme === SIG_SCHEME_MULTI_KEY) {
2664
+ return deserializer.deserialize(import_ts_sdk12.MultiKeySignature);
2665
+ } else if (scheme === SIG_SCHEME_KEYLESS) {
2666
+ return deserializer.deserialize(import_ts_sdk12.KeylessSignature);
2667
+ } else {
2668
+ throw new Error(`Unsupported signature scheme: ${scheme}`);
2669
+ }
2670
+ }
2671
+ var ProofOfPermission = class _ProofOfPermission {
2672
+ userAddr;
2673
+ publicKeyScheme;
2674
+ publicKey;
2675
+ signatureScheme;
2676
+ signature;
2677
+ fullMessage;
2678
+ constructor({ userAddr, publicKey, signature, fullMessage }) {
2679
+ this.userAddr = userAddr;
2680
+ this.publicKey = publicKey;
2681
+ this.signature = signature;
2682
+ this.fullMessage = fullMessage;
2683
+ this.publicKeyScheme = getPublicKeyScheme(publicKey);
2684
+ this.signatureScheme = getSignatureScheme(signature);
2685
+ }
2686
+ static deserialize(deserializer) {
2687
+ const userAddr = deserializer.deserialize(import_ts_sdk12.AccountAddress);
2688
+ const authenticationScheme = deserializer.deserializeU8();
2689
+ const publicKey = deserializePublicKey(authenticationScheme, deserializer);
2690
+ const signatureScheme = deserializer.deserializeU8();
2691
+ const signature = deserializeSignature(signatureScheme, deserializer);
2692
+ const fullMessage = deserializer.deserializeStr();
2693
+ return new _ProofOfPermission({ userAddr, publicKey, signature, fullMessage });
2694
+ }
2695
+ static fromBytes(bytes) {
2696
+ const deserializer = new import_ts_sdk12.Deserializer(bytes);
2697
+ return _ProofOfPermission.deserialize(deserializer);
2698
+ }
2699
+ static fromHex(hex) {
2700
+ return _ProofOfPermission.fromBytes((0, import_utils17.hexToBytes)(hex));
2701
+ }
2702
+ serialize(serializer) {
2703
+ serializer.serialize(this.userAddr);
2704
+ serializer.serializeU8(this.publicKeyScheme);
2705
+ serializer.serialize(this.publicKey);
2706
+ serializer.serializeU8(this.signatureScheme);
2707
+ serializer.serialize(this.signature);
2708
+ serializer.serializeStr(this.fullMessage);
2709
+ }
2710
+ toBytes() {
2711
+ const serializer = new import_ts_sdk12.Serializer();
2712
+ this.serialize(serializer);
2713
+ return serializer.toUint8Array();
2714
+ }
2715
+ toHex() {
2716
+ return (0, import_utils17.bytesToHex)(this.toBytes());
2717
+ }
2718
+ };
2719
+ async function verifyPermission({ fullDecryptionDomain, proof }) {
2720
+ const aptos = createAptos(getChainNameFromChainId(fullDecryptionDomain.getAptosContractID().chainId));
2721
+ const taskVerifySig = async () => {
2722
+ const msgToSign = fullDecryptionDomain.toPrettyMessage();
2723
+ const msgToSignHex = (0, import_utils17.bytesToHex)(new TextEncoder().encode(msgToSign));
2724
+ const fullMessageFromPetra = proof.fullMessage.includes(msgToSign);
2725
+ const fullMessageFromAptosConnect = proof.fullMessage.includes(msgToSignHex);
2726
+ if (!fullMessageFromPetra && !fullMessageFromAptosConnect) return false;
2727
+ try {
2728
+ return await proof.publicKey.verifySignatureAsync({
2729
+ aptosConfig: aptos.config,
2730
+ message: proof.fullMessage,
2731
+ signature: proof.signature
2732
+ });
2733
+ } catch (error) {
2734
+ return false;
2735
+ }
2736
+ };
2737
+ const taskCheckAuthKey = async () => {
2738
+ try {
2739
+ const onChainAuthKeyBytes = await getAccountAuthKeyBytes(aptos, proof.userAddr);
2740
+ const userAuthKeyBytes = proof.publicKey.authKey().bcsToBytes();
2741
+ const onChainHex = (0, import_utils17.bytesToHex)(onChainAuthKeyBytes);
2742
+ const userHex = (0, import_utils17.bytesToHex)(userAuthKeyBytes);
2743
+ console.log(`onChainHex: ${onChainHex}`);
2744
+ console.log(`userHex : ${userHex}`);
2745
+ return onChainHex === userHex;
2746
+ } catch (error) {
2747
+ return false;
2748
+ }
2749
+ };
2750
+ const taskCheckPermission = async () => {
2751
+ const contractId = fullDecryptionDomain.getAptosContractID();
2752
+ try {
2753
+ const userIsPermittedMoveVal = await view2(
2754
+ aptos,
2755
+ `${contractId.moduleAddr.toStringLong()}::${contractId.moduleName}::${contractId.functionName}`,
2756
+ [],
2757
+ [proof.userAddr, fullDecryptionDomain.domain]
2758
+ );
2759
+ return userIsPermittedMoveVal?.toString() === "true";
2760
+ } catch (error) {
2761
+ return false;
2762
+ }
2763
+ };
2764
+ const [sigIsValid, authKeyMatches, userIsPermitted] = await Promise.all([
2765
+ taskVerifySig(),
2766
+ taskCheckAuthKey(),
2767
+ taskCheckPermission()
2768
+ ]);
2769
+ if (!sigIsValid) {
2770
+ throw new Error("Signature invalid.");
2771
+ }
2772
+ if (!authKeyMatches) {
2773
+ throw new Error("Authentication key mismatch: on-chain key does not match provided public key.");
2774
+ }
2775
+ if (!userIsPermitted) {
2776
+ throw new Error("Permission denied.");
2777
+ }
2778
+ }
2779
+ function getChainNameFromChainId(chainId) {
2780
+ if (chainId === 1) {
2781
+ return "mainnet";
2782
+ } else if (chainId === 2) {
2783
+ return "testnet";
2784
+ } else if (chainId === 14) {
2785
+ return "devnet";
2786
+ } else if (chainId >= 104) {
2787
+ return "shelbynet";
2788
+ } else {
2789
+ throw new Error(`Unknown chain id: ${chainId}`);
2790
+ }
2791
+ }
2792
+ function createAptos(networkName) {
2793
+ let config;
2794
+ if (networkName === "mainnet") {
2795
+ config = new import_ts_sdk12.AptosConfig({ network: import_ts_sdk12.Network.MAINNET });
2796
+ } else if (networkName === "testnet") {
2797
+ config = new import_ts_sdk12.AptosConfig({ network: import_ts_sdk12.Network.TESTNET });
2798
+ } else if (networkName === "devnet") {
2799
+ config = new import_ts_sdk12.AptosConfig({ network: import_ts_sdk12.Network.DEVNET });
2800
+ } else if (networkName === "shelbynet") {
2801
+ config = new import_ts_sdk12.AptosConfig({
2802
+ network: import_ts_sdk12.Network.CUSTOM,
2803
+ fullnode: "https://api.shelbynet.shelby.xyz/v1"
2804
+ });
2805
+ } else {
2806
+ throw new Error(`Unsupported network name: ${networkName}`);
2807
+ }
2808
+ return new import_ts_sdk12.Aptos(config);
2809
+ }
2810
+ async function getAccountAuthKeyBytes(aptos, address) {
2811
+ const accountInfo = await aptos.getAccountInfo({ accountAddress: address });
2812
+ return (0, import_utils17.hexToBytes)(accountInfo.authentication_key.replace("0x", ""));
2813
+ }
2814
+ async function view2(aptos, func, typeArguments, functionArguments) {
2815
+ const result = await aptos.view({
2816
+ payload: {
2817
+ function: func,
2818
+ typeArguments,
2819
+ functionArguments
2820
+ }
2821
+ });
2822
+ if (result.length === 0) {
2823
+ throw new Error(`View function returned empty result`);
2824
+ }
2825
+ return result[0];
2826
+ }
2827
+
2828
+ // src/threshold-ibe/solana.ts
2829
+ var import_ts_sdk13 = require("@aptos-labs/ts-sdk");
2830
+ var import_utils18 = require("@noble/hashes/utils");
2831
+ var import_web3 = require("@solana/web3.js");
2832
+ var ContractID2 = class _ContractID {
2833
+ knownChainName;
2834
+ // mainnet-beta/testnet/devnet
2835
+ programId;
2836
+ constructor({ knownChainName, programId }) {
2837
+ this.knownChainName = knownChainName;
2838
+ this.programId = programId;
2839
+ }
2840
+ static deserialize(deserializer) {
2841
+ const knownChainName = deserializer.deserializeStr();
2842
+ const programId = new import_web3.PublicKey(deserializer.deserializeBytes());
2843
+ return new _ContractID({ knownChainName, programId });
2844
+ }
2845
+ static fromBytes(bytes) {
2846
+ const deserializer = new import_ts_sdk13.Deserializer(bytes);
2847
+ return _ContractID.deserialize(deserializer);
2848
+ }
2849
+ static fromHex(hex) {
2850
+ return _ContractID.fromBytes((0, import_utils18.hexToBytes)(hex));
2851
+ }
2852
+ serialize(serializer) {
2853
+ serializer.serializeStr(this.knownChainName);
2854
+ serializer.serializeBytes(this.programId.toBytes());
2855
+ }
2856
+ toBytes() {
2857
+ const serializer = new import_ts_sdk13.Serializer();
2858
+ this.serialize(serializer);
2859
+ return serializer.toUint8Array();
2860
+ }
2861
+ toHex() {
2862
+ return (0, import_utils18.bytesToHex)(this.toBytes());
2863
+ }
2864
+ toPrettyMessage(indent = 0) {
2865
+ const pad = " ".repeat(indent);
2866
+ return `
2867
+ ${pad}knownChainName: ${this.knownChainName}
2868
+ ${pad}programId: ${this.programId.toBase58()}`;
2869
+ }
2870
+ };
2871
+ var ProofOfPermission2 = class _ProofOfPermission {
2872
+ static SCHEME_UNVERSIONED = 0;
2873
+ static SCHEME_VERSIONED = 1;
2874
+ scheme;
2875
+ inner;
2876
+ constructor(scheme, inner) {
2877
+ this.scheme = scheme;
2878
+ this.inner = inner;
2879
+ }
2880
+ static newVersioned(txn) {
2881
+ return new _ProofOfPermission(_ProofOfPermission.SCHEME_VERSIONED, txn);
2882
+ }
2883
+ static newUnversioned(txn) {
2884
+ return new _ProofOfPermission(_ProofOfPermission.SCHEME_UNVERSIONED, txn);
2885
+ }
2886
+ static deserialize(deserializer) {
2887
+ const scheme = deserializer.deserializeU8();
2888
+ const bytes = deserializer.deserializeBytes();
2889
+ if (scheme == _ProofOfPermission.SCHEME_VERSIONED) {
2890
+ const inner = import_web3.VersionedTransaction.deserialize(bytes);
2891
+ return new _ProofOfPermission(_ProofOfPermission.SCHEME_VERSIONED, inner);
2892
+ } else if (scheme == _ProofOfPermission.SCHEME_UNVERSIONED) {
2893
+ const inner = import_web3.Transaction.from(Buffer.from(bytes));
2894
+ return new _ProofOfPermission(_ProofOfPermission.SCHEME_UNVERSIONED, inner);
2895
+ } else {
2896
+ throw new Error(`Unknown scheme: ${scheme}`);
2897
+ }
2898
+ }
2899
+ static fromBytes(bytes) {
2900
+ const deserializer = new import_ts_sdk13.Deserializer(bytes);
2901
+ return _ProofOfPermission.deserialize(deserializer);
2902
+ }
2903
+ static fromHex(hex) {
2904
+ return _ProofOfPermission.fromBytes((0, import_utils18.hexToBytes)(hex));
2905
+ }
2906
+ serialize(serializer) {
2907
+ serializer.serializeU8(this.scheme);
2908
+ if (this.scheme == _ProofOfPermission.SCHEME_VERSIONED) {
2909
+ serializer.serializeBytes(this.inner.serialize());
2910
+ } else if (this.scheme == _ProofOfPermission.SCHEME_UNVERSIONED) {
2911
+ serializer.serializeBytes(this.inner.serialize());
2912
+ } else {
2913
+ throw new Error(`Unknown scheme: ${this.scheme}`);
2914
+ }
2915
+ }
2916
+ toBytes() {
2917
+ const serializer = new import_ts_sdk13.Serializer();
2918
+ this.serialize(serializer);
2919
+ return serializer.toUint8Array();
2920
+ }
2921
+ toHex() {
2922
+ return (0, import_utils18.bytesToHex)(this.toBytes());
2923
+ }
2924
+ };
2925
+ async function verifyPermission2({ fullDecryptionDomain, proof }) {
2926
+ const txn = proof.inner;
2927
+ assertTransactionValid({ txn, fullDecryptionDomain });
2928
+ await assertTransactionSimulationPasses(txn, fullDecryptionDomain.getSolanaContractID().knownChainName);
2929
+ }
2930
+ function assertTransactionValid({ txn, fullDecryptionDomain }) {
2931
+ let instructions;
2932
+ if (txn instanceof import_web3.VersionedTransaction) {
2933
+ const message = txn.message;
2934
+ instructions = message.compiledInstructions.map((ix) => {
2935
+ if (ix.programIdIndex >= message.staticAccountKeys.length) {
2936
+ throw new Error(`Program ID index ${ix.programIdIndex} is out of bounds for static account keys (length: ${message.staticAccountKeys.length}). Address table lookups are not supported for validation.`);
2937
+ }
2938
+ const programId = message.staticAccountKeys[ix.programIdIndex];
2939
+ return { programId, data: Buffer.from(ix.data) };
2940
+ });
2941
+ } else {
2942
+ instructions = txn.instructions.map((ix) => ({
2943
+ programId: ix.programId,
2944
+ data: Buffer.from(ix.data)
2945
+ }));
2946
+ }
2947
+ if (instructions.length !== 1) {
2948
+ throw new Error(`transaction must contain exactly 1 instruction, found ${instructions.length}`);
2949
+ }
2950
+ const instruction = instructions[0];
2951
+ if (!instruction.programId.equals(fullDecryptionDomain.getSolanaContractID().programId)) {
2952
+ throw new Error(`transaction instruction program ID (${instruction.programId.toString()}) does not match contract program ID`);
2953
+ }
2954
+ const instructionData = instruction.data;
2955
+ if (instructionData.length < 12) {
2956
+ throw new Error("instruction data too short (must be at least 12 bytes: 8-byte discriminator + 4-byte Vec length)");
2957
+ }
2958
+ const paramData = instructionData.slice(8);
2959
+ const vecLength = paramData.readUInt32LE(0);
2960
+ if (paramData.length < 4 + vecLength) {
2961
+ throw new Error(`instruction data incomplete: expected ${4 + vecLength} bytes after discriminator, found ${paramData.length}`);
2962
+ }
2963
+ const fullBlobNameBytes = paramData.slice(4, 4 + vecLength);
2964
+ const expectedParamDataLength = 4 + vecLength;
2965
+ if (paramData.length > expectedParamDataLength) {
2966
+ throw new Error(`instruction data has extra bytes: expected exactly ${expectedParamDataLength} bytes after discriminator, found ${paramData.length}`);
2967
+ }
2968
+ if ((0, import_utils18.bytesToHex)(fullBlobNameBytes) !== fullDecryptionDomain.toHex()) {
2969
+ throw new Error(`domain mismatch: instruction parameter does not match decryptionContext.domain`);
2970
+ }
2971
+ }
2972
+ async function assertTransactionSimulationPasses(txn, chainName) {
2973
+ let rpcUrl;
2974
+ if (chainName === "localnet" || chainName === "localhost") {
2975
+ rpcUrl = "http://127.0.0.1:8899";
2976
+ } else if (chainName === "devnet") {
2977
+ rpcUrl = "https://api.devnet.solana.com";
2978
+ } else if (chainName === "testnet") {
2979
+ rpcUrl = "https://api.testnet.solana.com";
2980
+ } else if (chainName === "mainnet-beta") {
2981
+ rpcUrl = "https://api.mainnet-beta.solana.com";
2982
+ } else {
2983
+ throw new Error(`Unknown chain name: ${chainName}`);
2984
+ }
2985
+ const connection = new import_web3.Connection(rpcUrl, "confirmed");
2986
+ let simulation;
2987
+ if (txn instanceof import_web3.VersionedTransaction) {
2988
+ simulation = await connection.simulateTransaction(txn, {
2989
+ sigVerify: true
2990
+ });
2991
+ } else {
2992
+ simulation = await connection.simulateTransaction(txn);
2993
+ }
2994
+ if (simulation.value.err) {
2995
+ throw new Error(`transaction simulation failed: ${JSON.stringify(simulation.value.err)}`);
2996
+ }
2997
+ }
2998
+
2999
+ // src/threshold-ibe/index.ts
3000
+ var Committee = class _Committee {
3001
+ workerEndpoints;
3002
+ threshold;
3003
+ constructor({ workerEndpoints, threshold }) {
3004
+ if (workerEndpoints.length === 0) throw new Error("workerEndpoints must be non-empty");
3005
+ if (threshold === 0) throw new Error("threshold must be greater than 0");
3006
+ if (threshold > workerEndpoints.length) throw new Error("threshold must be less than or equal to the number of workerEndpoints");
3007
+ this.workerEndpoints = workerEndpoints;
3008
+ this.threshold = threshold;
3009
+ }
3010
+ static dummy() {
3011
+ return new _Committee({ workerEndpoints: ["http://localhost:3000"], threshold: 1 });
3012
+ }
3013
+ static deserialize(deserializer) {
3014
+ const numWorkerEndpoints = deserializer.deserializeUleb128AsU32();
3015
+ const workerEndpoints = Array.from({ length: numWorkerEndpoints }, () => deserializer.deserializeStr());
3016
+ const threshold = Number(deserializer.deserializeU64());
3017
+ return new _Committee({ workerEndpoints, threshold });
3018
+ }
3019
+ serialize(serializer) {
3020
+ serializer.serializeU32AsUleb128(this.workerEndpoints.length);
3021
+ this.workerEndpoints.forEach((workerEndpoint) => serializer.serializeStr(workerEndpoint));
3022
+ serializer.serializeU64(this.threshold);
3023
+ }
3024
+ toPrettyMessage(indent = 0) {
3025
+ const pad = " ".repeat(indent);
3026
+ const endpoints = this.workerEndpoints.map((e) => `
3027
+ ${pad} - ${e}`).join("");
3028
+ return `
3029
+ ${pad}workerEndpoints:${endpoints}
3030
+ ${pad}threshold: ${this.threshold}`;
3031
+ }
3032
+ };
3033
+ var ContractID3 = class _ContractID {
3034
+ static SCHEME_APTOS = 0;
3035
+ static SCHEME_SOLANA = 1;
3036
+ scheme;
3037
+ inner;
3038
+ constructor(scheme, inner) {
3039
+ this.scheme = scheme;
3040
+ this.inner = inner;
3041
+ }
3042
+ static newAptos({ chainId, moduleAddr, moduleName, functionName }) {
3043
+ return new _ContractID(_ContractID.SCHEME_APTOS, new ContractID(chainId, moduleAddr, moduleName, functionName));
3044
+ }
3045
+ static newSolana({ knownChainName, programId }) {
3046
+ return new _ContractID(_ContractID.SCHEME_SOLANA, new ContractID2({ knownChainName, programId }));
3047
+ }
3048
+ static dummy() {
3049
+ return new _ContractID(_ContractID.SCHEME_APTOS, ContractID.dummy());
3050
+ }
3051
+ static deserialize(deserializer) {
3052
+ const scheme = deserializer.deserializeU8();
3053
+ if (scheme == _ContractID.SCHEME_APTOS) {
3054
+ return new _ContractID(_ContractID.SCHEME_APTOS, ContractID.deserialize(deserializer));
3055
+ } else if (scheme == _ContractID.SCHEME_SOLANA) {
3056
+ return new _ContractID(_ContractID.SCHEME_SOLANA, ContractID2.deserialize(deserializer));
3057
+ } else {
3058
+ throw new Error(`Unknown scheme: ${scheme}`);
3059
+ }
3060
+ }
3061
+ static fromBytes(bytes) {
3062
+ const deserializer = new import_ts_sdk14.Deserializer(bytes);
3063
+ return _ContractID.deserialize(deserializer);
3064
+ }
3065
+ static fromHex(hex) {
3066
+ return _ContractID.fromBytes((0, import_utils19.hexToBytes)(hex));
3067
+ }
3068
+ serialize(serializer) {
3069
+ serializer.serializeU8(this.scheme);
3070
+ if (this.scheme == _ContractID.SCHEME_APTOS) {
3071
+ this.inner.serialize(serializer);
3072
+ } else if (this.scheme == _ContractID.SCHEME_SOLANA) {
3073
+ this.inner.serialize(serializer);
3074
+ } else {
3075
+ throw new Error(`Unknown scheme: ${this.scheme}`);
3076
+ }
3077
+ }
3078
+ toBytes() {
3079
+ const serializer = new import_ts_sdk14.Serializer();
3080
+ this.serialize(serializer);
3081
+ return serializer.toUint8Array();
3082
+ }
3083
+ toHex() {
3084
+ return (0, import_utils19.bytesToHex)(this.toBytes());
3085
+ }
3086
+ toPrettyMessage(indent = 0) {
3087
+ const pad = " ".repeat(indent);
3088
+ const schemeName = this.scheme === _ContractID.SCHEME_APTOS ? "aptos" : "solana";
3089
+ const innerMsg = this.inner.toPrettyMessage(indent + 2);
3090
+ return `
3091
+ ${pad}scheme: ${schemeName}
3092
+ ${pad}inner:${innerMsg}`;
3093
+ }
3094
+ };
3095
+ var EncryptionKey2 = class _EncryptionKey {
3096
+ ibeMpks;
3097
+ constructor({ ibeMpks }) {
3098
+ this.ibeMpks = ibeMpks;
3099
+ }
3100
+ static async fetch({ committee }) {
3101
+ const ibeMpks = await Promise.all(committee.workerEndpoints.map(async (endpoint) => {
3102
+ const config = await worker_config_exports.get(endpoint);
3103
+ return config.ibeMpk;
3104
+ }));
3105
+ return new _EncryptionKey({ ibeMpks });
3106
+ }
3107
+ };
3108
+ var DecryptionKey2 = class _DecryptionKey {
3109
+ ibeDecryptionKeys;
3110
+ constructor(ibeDecryptionKeys) {
3111
+ this.ibeDecryptionKeys = ibeDecryptionKeys;
3112
+ }
3113
+ static async fetch({ committee, contractId, domain, proof }) {
3114
+ const decKeyLoadResults = await Promise.all(committee.workerEndpoints.map(async (workerEndpoint) => {
3115
+ const task = WorkerTask.newThresholdIbeDecryptionKey({ committee, contractId, domain, proof });
3116
+ const controller = new AbortController();
3117
+ const timeoutId = setTimeout(() => controller.abort(), 5e3);
3118
+ var response = null;
3119
+ try {
3120
+ response = await fetch(workerEndpoint, {
3121
+ method: "POST",
3122
+ body: task.toHex(),
3123
+ signal: controller.signal
3124
+ });
3125
+ } catch (error) {
3126
+ clearTimeout(timeoutId);
3127
+ }
3128
+ if (response == null) {
3129
+ return new WorkerTimedOut();
3130
+ }
3131
+ const responseBody = await response.text();
3132
+ if (response.status !== 200) {
3133
+ return new WorkerRejected(response.status, responseBody);
3134
+ }
3135
+ try {
3136
+ return IdentityPrivateKey2.fromHex(responseBody);
3137
+ } catch (error) {
3138
+ return new CouldNotParseDecryptionKey(responseBody);
3139
+ }
3140
+ }));
3141
+ const numSharesCollected = decKeyLoadResults.filter((loadResult) => loadResult instanceof IdentityPrivateKey2).length;
3142
+ if (numSharesCollected < committee.threshold) {
3143
+ const workerResults = committee.workerEndpoints.map((workerEndpoint, i) => {
3144
+ const result = decKeyLoadResults[i];
3145
+ return `${workerEndpoint}: ${result instanceof IdentityPrivateKey2 ? "Success" : result.toDisplayString()}`;
3146
+ }).join(", ");
3147
+ throw new Error(`Failed to collect enough shares to decrypt. Collected ${numSharesCollected} shares, but needed ${committee.threshold} shares. Worker results: ${workerResults}`);
3148
+ }
3149
+ const decKeys = decKeyLoadResults.map((loadResult) => loadResult instanceof IdentityPrivateKey2 ? loadResult : null);
3150
+ return new _DecryptionKey(decKeys);
3151
+ }
3152
+ };
3153
+ var Ciphertext7 = class _Ciphertext {
3154
+ aesCiph;
3155
+ ibeCiphs;
3156
+ constructor(aesCiph, ibeCiphs) {
3157
+ this.aesCiph = aesCiph;
3158
+ this.ibeCiphs = ibeCiphs;
3159
+ }
3160
+ static dummy() {
3161
+ return new _Ciphertext(Ciphertext6.dummy(), []);
3162
+ }
3163
+ static deserialize(deserializer) {
3164
+ const aesCiph = Ciphertext6.deserialize(deserializer);
3165
+ const ibeCiphs = deserializer.deserializeVector(Ciphertext4);
3166
+ return new _Ciphertext(aesCiph, ibeCiphs);
3167
+ }
3168
+ static fromBytes(bytes) {
3169
+ const deserializer = new import_ts_sdk14.Deserializer(bytes);
3170
+ const ret = _Ciphertext.deserialize(deserializer);
3171
+ if (deserializer.remaining() !== 0) {
3172
+ throw new Error("Ciphertext deserialization failed: extra bytes");
3173
+ }
3174
+ return ret;
3175
+ }
3176
+ static fromHex(hex) {
3177
+ return _Ciphertext.fromBytes((0, import_utils19.hexToBytes)(hex));
3178
+ }
3179
+ serialize(serializer) {
3180
+ this.aesCiph.serialize(serializer);
3181
+ serializer.serializeU32AsUleb128(this.ibeCiphs.length);
3182
+ this.ibeCiphs.forEach((ibeCiph) => ibeCiph.serialize(serializer));
3183
+ }
3184
+ toBytes() {
3185
+ const serializer = new import_ts_sdk14.Serializer();
3186
+ this.serialize(serializer);
3187
+ return serializer.toUint8Array();
3188
+ }
3189
+ };
3190
+ var FullDecryptionDomain = class _FullDecryptionDomain {
3191
+ committee;
3192
+ contractId;
3193
+ domain;
3194
+ constructor({ committee, contractId, domain }) {
3195
+ this.committee = committee;
3196
+ this.contractId = contractId;
3197
+ this.domain = domain;
3198
+ }
3199
+ static dummy() {
3200
+ return new _FullDecryptionDomain({
3201
+ committee: Committee.dummy(),
3202
+ contractId: ContractID3.dummy(),
3203
+ domain: new Uint8Array(0)
3204
+ });
3205
+ }
3206
+ static deserialize(deserializer) {
3207
+ const committee = Committee.deserialize(deserializer);
3208
+ const contractId = ContractID3.deserialize(deserializer);
3209
+ const domain = deserializer.deserializeBytes();
3210
+ return new _FullDecryptionDomain({ committee, contractId, domain });
3211
+ }
3212
+ static fromBytes(bytes) {
3213
+ const deserializer = new import_ts_sdk14.Deserializer(bytes);
3214
+ const ret = _FullDecryptionDomain.deserialize(deserializer);
3215
+ if (deserializer.remaining() !== 0) {
3216
+ throw new Error("FullDecryptionDomain deserialization failed: extra bytes");
3217
+ }
3218
+ return ret;
3219
+ }
3220
+ static fromHex(hex) {
3221
+ return _FullDecryptionDomain.fromBytes((0, import_utils19.hexToBytes)(hex));
3222
+ }
3223
+ serialize(serializer) {
3224
+ this.committee.serialize(serializer);
3225
+ this.contractId.serialize(serializer);
3226
+ serializer.serializeBytes(this.domain);
3227
+ }
3228
+ toBytes() {
3229
+ const serializer = new import_ts_sdk14.Serializer();
3230
+ this.serialize(serializer);
3231
+ return serializer.toUint8Array();
3232
+ }
3233
+ toHex() {
3234
+ return (0, import_utils19.bytesToHex)(this.toBytes());
3235
+ }
3236
+ toPrettyMessage(indent = 0) {
3237
+ const pad = " ".repeat(indent);
3238
+ return `
3239
+ ${pad}committee:${this.committee.toPrettyMessage(indent + 1)}
3240
+ ${pad}contractId:${this.contractId.toPrettyMessage(indent + 1)}
3241
+ ${pad}domain: 0x${(0, import_utils19.bytesToHex)(this.domain)}`;
3242
+ }
3243
+ getSolanaContractID() {
3244
+ if (this.contractId.scheme != ContractID3.SCHEME_SOLANA) {
3245
+ throw new Error("ContractID is not a Solana contract ID");
3246
+ }
3247
+ return this.contractId.inner;
3248
+ }
3249
+ getAptosContractID() {
3250
+ if (this.contractId.scheme != ContractID3.SCHEME_APTOS) {
3251
+ throw new Error("ContractID is not a Aptos contract ID");
3252
+ }
3253
+ return this.contractId.inner;
3254
+ }
3255
+ };
3256
+ var ProofOfPermission3 = class _ProofOfPermission {
3257
+ static SCHEME_APTOS = 0;
3258
+ static SCHEME_SOLANA = 1;
3259
+ scheme;
3260
+ inner;
3261
+ constructor(scheme, inner) {
3262
+ this.scheme = scheme;
3263
+ this.inner = inner;
3264
+ }
3265
+ /** @deprecated Use `ProofOfPermission.createAptos()` instead */
3266
+ static newAptos(id) {
3267
+ return new _ProofOfPermission(_ProofOfPermission.SCHEME_APTOS, id);
3268
+ }
3269
+ /** @deprecated Use `ProofOfPermission.createSolana()` instead */
3270
+ static newSolana(id) {
3271
+ return new _ProofOfPermission(_ProofOfPermission.SCHEME_SOLANA, id);
3272
+ }
3273
+ static createAptos({ userAddr, publicKey, signature, fullMessage }) {
3274
+ return new _ProofOfPermission(_ProofOfPermission.SCHEME_APTOS, new ProofOfPermission({ userAddr, publicKey, signature, fullMessage }));
3275
+ }
3276
+ static createSolana({ txn }) {
3277
+ const solanaProof = txn instanceof SolanaSDK.VersionedTransaction ? ProofOfPermission2.newVersioned(txn) : ProofOfPermission2.newUnversioned(txn);
3278
+ return new _ProofOfPermission(_ProofOfPermission.SCHEME_SOLANA, solanaProof);
3279
+ }
3280
+ static deserialize(deserializer) {
3281
+ const scheme = deserializer.deserializeU8();
3282
+ if (scheme == _ProofOfPermission.SCHEME_APTOS) {
3283
+ return new _ProofOfPermission(_ProofOfPermission.SCHEME_APTOS, ProofOfPermission.deserialize(deserializer));
3284
+ } else if (scheme == _ProofOfPermission.SCHEME_SOLANA) {
3285
+ return new _ProofOfPermission(_ProofOfPermission.SCHEME_SOLANA, ProofOfPermission2.deserialize(deserializer));
3286
+ } else {
3287
+ throw new Error(`Unknown scheme: ${scheme}`);
3288
+ }
3289
+ }
3290
+ static fromBytes(bytes) {
3291
+ const deserializer = new import_ts_sdk14.Deserializer(bytes);
3292
+ return _ProofOfPermission.deserialize(deserializer);
3293
+ }
3294
+ static fromHex(hex) {
3295
+ return _ProofOfPermission.fromBytes((0, import_utils19.hexToBytes)(hex));
3296
+ }
3297
+ serialize(serializer) {
3298
+ serializer.serializeU8(this.scheme);
3299
+ if (this.scheme == _ProofOfPermission.SCHEME_APTOS) {
3300
+ this.inner.serialize(serializer);
3301
+ } else if (this.scheme == _ProofOfPermission.SCHEME_SOLANA) {
3302
+ this.inner.serialize(serializer);
3303
+ } else {
3304
+ throw new Error(`Unknown scheme: ${this.scheme}`);
3305
+ }
3306
+ }
3307
+ toBytes() {
3308
+ const serializer = new import_ts_sdk14.Serializer();
3309
+ this.serialize(serializer);
3310
+ return serializer.toUint8Array();
3311
+ }
3312
+ toHex() {
3313
+ return (0, import_utils19.bytesToHex)(this.toBytes());
3314
+ }
3315
+ };
3316
+ function encrypt7({ committee, encryptionKey, contractId, domain, plaintext }) {
3317
+ if (committee.workerEndpoints.length !== encryptionKey.ibeMpks.length) {
3318
+ throw new Error("committee.workerEndpoints.length !== encryptionKey.ibeMpks.length");
3319
+ }
3320
+ const fullDecryptionDomain = new FullDecryptionDomain({
3321
+ committee,
3322
+ contractId,
3323
+ domain
3324
+ });
3325
+ const symmKey = keygen8();
3326
+ const symmKeyShares = split(symmKey.toBytes(), committee.threshold, committee.workerEndpoints.length);
3327
+ const symmCiph = encrypt6(symmKey, plaintext);
3328
+ const ibeCiphs = symmKeyShares.map((share, idx) => encrypt4(encryptionKey.ibeMpks[idx], fullDecryptionDomain.toBytes(), share.payload));
3329
+ return { fullDecryptionDomain, ciphertext: new Ciphertext7(symmCiph, ibeCiphs) };
3330
+ }
3331
+ function decrypt7({ decryptionKey, ciphertext }) {
3332
+ if (decryptionKey.ibeDecryptionKeys.length !== ciphertext.ibeCiphs.length) {
3333
+ throw new Error("decryptionKey.ibeDecryptionKeys.length !== ciphertext.ibeCiphs.length");
3334
+ }
3335
+ const symmKeyShares = ciphertext.ibeCiphs.map((ibeCiph, idx) => {
3336
+ if (decryptionKey.ibeDecryptionKeys[idx] == null) return null;
3337
+ const sharePayload = decrypt4(decryptionKey.ibeDecryptionKeys[idx], ibeCiph);
3338
+ if (sharePayload == null) return null;
3339
+ return new Share(idx + 1, sharePayload);
3340
+ }).filter((share) => share != null);
3341
+ const symmKeyBytes = combine(symmKeyShares);
3342
+ const symmKey = Key2.fromBytes(symmKeyBytes);
3343
+ return decrypt6(symmKey, ciphertext.aesCiph);
3344
+ }
3345
+ async function verifyAndExtract({ ibeMsk, committee, contractId, domain, proof }) {
3346
+ const decryptionContext = new FullDecryptionDomain({ committee, contractId, domain });
3347
+ if (contractId.scheme == ContractID3.SCHEME_APTOS && proof.scheme == ProofOfPermission3.SCHEME_APTOS) {
3348
+ await verifyPermission({ fullDecryptionDomain: decryptionContext, proof: proof.inner });
3349
+ } else if (contractId.scheme == ContractID3.SCHEME_SOLANA && proof.scheme == ProofOfPermission3.SCHEME_SOLANA) {
3350
+ await verifyPermission2({ fullDecryptionDomain: decryptionContext, proof: proof.inner });
3351
+ } else {
3352
+ throw new Error(`Unknown scheme: contractId=${contractId.scheme}, proof=${proof.scheme}`);
3353
+ }
3354
+ return extract2(ibeMsk, decryptionContext.toBytes());
3355
+ }
3356
+ var WorkerTimedOut = class {
3357
+ toDisplayString() {
3358
+ return "Timed out";
3359
+ }
3360
+ };
3361
+ var WorkerRejected = class {
3362
+ statusCode;
3363
+ responseBody;
3364
+ constructor(statusCode, responseBody) {
3365
+ this.statusCode = statusCode;
3366
+ this.responseBody = responseBody;
3367
+ }
3368
+ toDisplayString() {
3369
+ return `Rejected: ${this.statusCode} ${this.responseBody}`;
3370
+ }
3371
+ };
3372
+ var CouldNotParseDecryptionKey = class {
3373
+ originalHex;
3374
+ constructor(originalHex) {
3375
+ this.originalHex = originalHex;
3376
+ }
3377
+ toDisplayString() {
3378
+ return `Could not parse decryption key: ${this.originalHex}`;
3379
+ }
3380
+ };
3381
+
3382
+ // src/worker_task.ts
3383
+ var TYPE_SILENT_SETUP_DECRYPTION_KEY = 5;
3384
+ var TYPE_XCHAIN_SILENT_SETUP_DECRYPTION_KEY = 6;
3385
+ var TYPE_THRESHOLD_IBE_DECRYPTION_KEY = 7;
3386
+ var WorkerTask = class _WorkerTask {
3387
+ taskType;
3388
+ inner;
3389
+ constructor(taskType, inner) {
3390
+ if (taskType == TYPE_SILENT_SETUP_DECRYPTION_KEY && inner instanceof silent_setup_encryption_exports.RequestForDecryptionKey) {
3391
+ this.taskType = TYPE_SILENT_SETUP_DECRYPTION_KEY;
3392
+ this.inner = inner;
3393
+ } else if (taskType == TYPE_XCHAIN_SILENT_SETUP_DECRYPTION_KEY && inner instanceof silent_setup_encryption_xchain_exports.RequestForDecryptionKey) {
3394
+ this.taskType = TYPE_XCHAIN_SILENT_SETUP_DECRYPTION_KEY;
3395
+ this.inner = inner;
3396
+ } else if (taskType == TYPE_THRESHOLD_IBE_DECRYPTION_KEY && inner instanceof RequestForThresholdIbeDecryptionKey) {
3397
+ this.taskType = TYPE_THRESHOLD_IBE_DECRYPTION_KEY;
3398
+ this.inner = inner;
3399
+ } else {
3400
+ throw new Error(`Invalid task type: ${taskType}`);
3401
+ }
3402
+ }
3403
+ static newSilentSetupDecryptionKey(decryptionContext, userAddr, publicKey, signature) {
3404
+ return new _WorkerTask(TYPE_SILENT_SETUP_DECRYPTION_KEY, new silent_setup_encryption_exports.RequestForDecryptionKey(decryptionContext, userAddr, publicKey, signature));
3405
+ }
3406
+ static newXChainSilentSetupDecryptionKey(decryptionContext, proofOfPermission) {
3407
+ return new _WorkerTask(TYPE_XCHAIN_SILENT_SETUP_DECRYPTION_KEY, new silent_setup_encryption_xchain_exports.RequestForDecryptionKey(decryptionContext, proofOfPermission));
3408
+ }
3409
+ static newThresholdIbeDecryptionKey(args) {
3410
+ return new _WorkerTask(TYPE_THRESHOLD_IBE_DECRYPTION_KEY, new RequestForThresholdIbeDecryptionKey(args));
3411
+ }
3412
+ static deserialize(deserializer) {
3413
+ const taskType = deserializer.deserializeU8();
3414
+ let inner;
3415
+ if (taskType === TYPE_SILENT_SETUP_DECRYPTION_KEY) {
3416
+ inner = silent_setup_encryption_exports.RequestForDecryptionKey.deserialize(deserializer);
3417
+ } else if (taskType === TYPE_XCHAIN_SILENT_SETUP_DECRYPTION_KEY) {
3418
+ inner = silent_setup_encryption_xchain_exports.RequestForDecryptionKey.deserialize(deserializer);
3419
+ } else if (taskType === TYPE_THRESHOLD_IBE_DECRYPTION_KEY) {
3420
+ inner = RequestForThresholdIbeDecryptionKey.deserialize(deserializer);
3421
+ } else {
3422
+ throw new Error(`Invalid task type: ${taskType}`);
3423
+ }
3424
+ return new _WorkerTask(taskType, inner);
3425
+ }
3426
+ static fromBytes(bytes) {
3427
+ const deserializer = new import_ts_sdk15.Deserializer(bytes);
3428
+ return _WorkerTask.deserialize(deserializer);
3429
+ }
3430
+ static fromHex(hex) {
3431
+ return _WorkerTask.fromBytes((0, import_utils20.hexToBytes)(hex));
3432
+ }
3433
+ serialize(serializer) {
3434
+ serializer.serializeU8(this.taskType);
3435
+ if (this.taskType === TYPE_SILENT_SETUP_DECRYPTION_KEY) {
3436
+ this.inner.serialize(serializer);
3437
+ } else if (this.taskType === TYPE_XCHAIN_SILENT_SETUP_DECRYPTION_KEY) {
3438
+ this.inner.serialize(serializer);
3439
+ } else if (this.taskType === TYPE_THRESHOLD_IBE_DECRYPTION_KEY) {
3440
+ this.inner.serialize(serializer);
3441
+ } else {
3442
+ throw new Error(`Invalid task type: ${this.taskType}`);
3443
+ }
3444
+ }
3445
+ toBytes() {
3446
+ const serializer = new import_ts_sdk15.Serializer();
3447
+ this.serialize(serializer);
3448
+ return serializer.toUint8Array();
3449
+ }
3450
+ toHex() {
3451
+ return (0, import_utils20.bytesToHex)(this.toBytes());
3452
+ }
3453
+ unpackThresholdIbeDecryptionKey() {
3454
+ if (this.taskType !== TYPE_THRESHOLD_IBE_DECRYPTION_KEY) {
3455
+ throw new Error(`Invalid task type: ${this.taskType}`);
3456
+ }
3457
+ const request = this.inner;
3458
+ return {
3459
+ committee: request.committee,
3460
+ contractId: request.contractId,
3461
+ domain: request.domain,
3462
+ proof: request.proof
3463
+ };
3464
+ }
3465
+ };
3466
+ var RequestForThresholdIbeDecryptionKey = class _RequestForThresholdIbeDecryptionKey {
3467
+ committee;
3468
+ contractId;
3469
+ domain;
3470
+ proof;
3471
+ constructor({ committee, contractId, domain, proof }) {
3472
+ this.committee = committee;
3473
+ this.contractId = contractId;
3474
+ this.domain = domain;
3475
+ this.proof = proof;
3476
+ }
3477
+ static deserialize(deserializer) {
3478
+ const committee = Committee.deserialize(deserializer);
3479
+ const contractId = ContractID3.deserialize(deserializer);
3480
+ const domain = deserializer.deserializeBytes();
3481
+ const proof = ProofOfPermission3.deserialize(deserializer);
3482
+ return new _RequestForThresholdIbeDecryptionKey({ committee, contractId, domain, proof });
3483
+ }
3484
+ static fromBytes(bytes) {
3485
+ const deserializer = new import_ts_sdk15.Deserializer(bytes);
3486
+ return _RequestForThresholdIbeDecryptionKey.deserialize(deserializer);
3487
+ }
3488
+ static fromHex(hex) {
3489
+ return _RequestForThresholdIbeDecryptionKey.fromBytes((0, import_utils20.hexToBytes)(hex));
3490
+ }
3491
+ serialize(serializer) {
3492
+ this.committee.serialize(serializer);
3493
+ this.contractId.serialize(serializer);
3494
+ serializer.serializeBytes(this.domain);
3495
+ this.proof.serialize(serializer);
3496
+ }
3497
+ toBytes() {
3498
+ const serializer = new import_ts_sdk15.Serializer();
3499
+ this.serialize(serializer);
3500
+ return serializer.toUint8Array();
3501
+ }
3502
+ toHex() {
3503
+ return (0, import_utils20.bytesToHex)(this.toBytes());
3504
+ }
3505
+ };
3506
+
3507
+ // src/silent_setup_encryption.ts
3508
+ var EncryptionContext = class {
3509
+ workers;
3510
+ threshold;
3511
+ moduleAddr;
3512
+ moduleName;
3513
+ constructor({ workers, threshold, moduleAddr, moduleName }) {
3514
+ this.workers = workers;
3515
+ this.threshold = threshold;
3516
+ this.moduleAddr = moduleAddr;
3517
+ this.moduleName = moduleName;
3518
+ }
3519
+ serialize(serializer) {
3520
+ serializer.serializeVector(this.workers);
3521
+ serializer.serializeU64(this.threshold);
3522
+ serializer.serialize(this.moduleAddr);
3523
+ serializer.serializeStr(this.moduleName);
3524
+ }
3525
+ toBytes() {
3526
+ const serializer = new import_ts_sdk16.Serializer();
3527
+ this.serialize(serializer);
3528
+ return serializer.toUint8Array();
3529
+ }
3530
+ async loadEncryptor(aptos) {
3531
+ const workerConfigs = await Promise.all(this.workers.map(async (worker) => {
3532
+ const config = await view(aptos, worker);
3533
+ return config;
3534
+ }));
3535
+ return new Encryptor(this, workerConfigs);
3536
+ }
3537
+ };
3538
+ var DecryptionContext = class _DecryptionContext {
3539
+ workers;
3540
+ threshold;
3541
+ moduleAddr;
3542
+ moduleName;
3543
+ domain;
3544
+ constructor({ workers, threshold, moduleAddr, moduleName, domain }) {
3545
+ this.workers = workers;
3546
+ this.threshold = threshold;
3547
+ this.moduleAddr = moduleAddr;
3548
+ this.moduleName = moduleName;
3549
+ this.domain = domain;
3550
+ }
3551
+ static dummy() {
3552
+ return new _DecryptionContext({
3553
+ workers: [],
3554
+ threshold: 0,
3555
+ moduleAddr: import_ts_sdk16.AccountAddress.fromString("0x0"),
3556
+ moduleName: "",
3557
+ domain: new Uint8Array(0)
3558
+ });
3559
+ }
3560
+ static deserialize(deserializer) {
3561
+ const workers = deserializer.deserializeVector(import_ts_sdk16.AccountAddress);
3562
+ const threshold = Number(deserializer.deserializeU64());
3563
+ const moduleAddr = deserializer.deserialize(import_ts_sdk16.AccountAddress);
3564
+ const moduleName = deserializer.deserializeStr();
3565
+ const domain = deserializer.deserializeBytes();
3566
+ return new _DecryptionContext({ workers, threshold, moduleAddr, moduleName, domain });
3567
+ }
3568
+ serialize(serializer) {
3569
+ serializer.serializeVector(this.workers);
3570
+ serializer.serializeU64(this.threshold);
3571
+ serializer.serialize(this.moduleAddr);
3572
+ serializer.serializeStr(this.moduleName);
3573
+ serializer.serializeBytes(this.domain);
3574
+ }
3575
+ toBytes() {
3576
+ const serializer = new import_ts_sdk16.Serializer();
3577
+ this.serialize(serializer);
3578
+ return serializer.toUint8Array();
3579
+ }
3580
+ toHex() {
3581
+ return (0, import_utils21.bytesToHex)(this.toBytes());
3582
+ }
3583
+ toWalletSignMessage() {
3584
+ return JSON.stringify({
3585
+ messageType: "ThresholdDecryptionRequestV0",
3586
+ workers: this.workers.map((w) => w.toString()),
3587
+ threshold: this.threshold,
3588
+ moduleAddr: this.moduleAddr.toString(),
3589
+ moduleName: this.moduleName,
3590
+ domain: `0x${(0, import_utils21.bytesToHex)(this.domain)}`
3591
+ });
3592
+ }
3593
+ async loadDecryptor({ aptos, userAddr, publicKey, signature }) {
3594
+ const decKeyLoadResults = await Promise.all(this.workers.map(async (worker) => {
3595
+ const config = await view(aptos, worker);
3596
+ const task = WorkerTask.newSilentSetupDecryptionKey(this, userAddr, publicKey, signature);
3597
+ const controller = new AbortController();
3598
+ const timeoutId = setTimeout(() => controller.abort(), 5e3);
3599
+ var response = null;
3600
+ try {
3601
+ response = await fetch(config.endpoint, {
3602
+ method: "POST",
3603
+ body: task.toHex(),
3604
+ signal: controller.signal
3605
+ });
3606
+ } catch (error) {
3607
+ clearTimeout(timeoutId);
3608
+ }
3609
+ if (response == null) {
3610
+ return new WorkerTimedOut2();
3611
+ }
3612
+ const responseBody = await response.text();
3613
+ if (response.status !== 200) {
3614
+ return new WorkerRejected2(response.status, responseBody);
3615
+ }
3616
+ try {
3617
+ return IdentityPrivateKey2.fromHex(responseBody);
3618
+ } catch (error) {
3619
+ return new CouldNotParseDecryptionKey2(responseBody);
3620
+ }
3621
+ }));
3622
+ const numSharesCollected = decKeyLoadResults.filter((loadResult) => loadResult instanceof IdentityPrivateKey2).length;
3623
+ if (numSharesCollected < this.threshold) {
3624
+ const workerResults = this.workers.map((worker, i) => {
3625
+ const result = decKeyLoadResults[i];
3626
+ return `${worker}: ${result instanceof IdentityPrivateKey2 ? "Success" : result.toDisplayString()}`;
3627
+ }).join(", ");
3628
+ throw new Error(`Failed to collect enough shares to decrypt. Collected ${numSharesCollected} shares, but needed ${this.threshold} shares. Worker results: ${workerResults}`);
3629
+ }
3630
+ const decKeys = decKeyLoadResults.map((loadResult) => loadResult instanceof IdentityPrivateKey2 ? loadResult : null);
3631
+ return new Decryptor(this, decKeys);
3632
+ }
3633
+ };
3634
+ var Ciphertext8 = class _Ciphertext {
3635
+ decryptionContext;
3636
+ aesCiph;
3637
+ ibeCiphs;
3638
+ constructor(decryptionContext, aesCiph, ibeCiphs) {
3639
+ this.decryptionContext = decryptionContext;
3640
+ this.aesCiph = aesCiph;
3641
+ this.ibeCiphs = ibeCiphs;
3642
+ }
3643
+ static dummy() {
3644
+ return new _Ciphertext(DecryptionContext.dummy(), Ciphertext6.dummy(), []);
3645
+ }
3646
+ static deserialize(deserializer) {
3647
+ const decryptionContext = DecryptionContext.deserialize(deserializer);
3648
+ const aesCiph = Ciphertext6.deserialize(deserializer);
3649
+ const ibeCiphs = deserializer.deserializeVector(Ciphertext4);
3650
+ return new _Ciphertext(decryptionContext, aesCiph, ibeCiphs);
3651
+ }
3652
+ static fromBytes(bytes) {
3653
+ const deserializer = new import_ts_sdk16.Deserializer(bytes);
3654
+ const ret = _Ciphertext.deserialize(deserializer);
3655
+ if (deserializer.remaining() !== 0) {
3656
+ throw new Error("Ciphertext deserialization failed: extra bytes");
3657
+ }
3658
+ return ret;
3659
+ }
3660
+ static fromHex(hex) {
3661
+ return _Ciphertext.fromBytes((0, import_utils21.hexToBytes)(hex));
3662
+ }
3663
+ serialize(serializer) {
3664
+ this.decryptionContext.serialize(serializer);
3665
+ this.aesCiph.serialize(serializer);
3666
+ serializer.serializeU32AsUleb128(this.ibeCiphs.length);
3667
+ this.ibeCiphs.forEach((ibeCiph) => ibeCiph.serialize(serializer));
3668
+ }
3669
+ toBytes() {
3670
+ const serializer = new import_ts_sdk16.Serializer();
3671
+ this.serialize(serializer);
3672
+ return serializer.toUint8Array();
3673
+ }
3674
+ };
3675
+ var Encryptor = class {
3676
+ domain;
3677
+ workerConfigs;
3678
+ constructor(domain, workerConfigs) {
3679
+ this.domain = domain;
3680
+ this.workerConfigs = workerConfigs;
3681
+ }
3682
+ encrypt({ domain, plaintext }) {
3683
+ const decCtxt = new DecryptionContext({
3684
+ workers: this.domain.workers,
3685
+ threshold: this.domain.threshold,
3686
+ moduleAddr: this.domain.moduleAddr,
3687
+ moduleName: this.domain.moduleName,
3688
+ domain
3689
+ });
3690
+ const symmKey = keygen8();
3691
+ const symmKeyShares = split(symmKey.toBytes(), this.domain.threshold, this.domain.workers.length);
3692
+ const symmCiph = encrypt6(symmKey, plaintext);
3693
+ const ibeCiphs = symmKeyShares.map((share, idx) => encrypt4(this.workerConfigs[idx].ibeMpk, decCtxt.toBytes(), share.payload));
3694
+ return new Ciphertext8(decCtxt, symmCiph, ibeCiphs);
3695
+ }
3696
+ };
3697
+ var Decryptor = class {
3698
+ ibeDecryptionKeys;
3699
+ decryptionContext;
3700
+ constructor(decryptionContext, ibeDecryptionKeys) {
3701
+ this.decryptionContext = decryptionContext;
3702
+ this.ibeDecryptionKeys = ibeDecryptionKeys;
3703
+ }
3704
+ decrypt(ciphertext) {
3705
+ if (ciphertext.decryptionContext.toHex() !== this.decryptionContext.toHex()) {
3706
+ throw new Error("Ciphertext does not match decryption domain");
3707
+ }
3708
+ const symmKeyShares = ciphertext.ibeCiphs.map((ibeCiph, idx) => {
3709
+ if (this.ibeDecryptionKeys[idx] == null) {
3710
+ console.log(`idx=${idx}, isk is null`);
3711
+ return null;
3712
+ }
3713
+ const sharePayload = decrypt4(this.ibeDecryptionKeys[idx], ibeCiph);
3714
+ if (sharePayload == null) {
3715
+ console.log(`idx=${idx}, sharePayload is null`);
3716
+ return null;
3717
+ }
3718
+ return new Share(idx + 1, sharePayload);
3719
+ }).filter((share) => share != null);
3720
+ const symmKeyBytes = combine(symmKeyShares);
3721
+ const symmKey = Key2.fromBytes(symmKeyBytes);
3722
+ return decrypt6(symmKey, ciphertext.aesCiph);
3723
+ }
3724
+ };
3725
+ var WorkerTimedOut2 = class {
3726
+ toDisplayString() {
3727
+ return "Timed out";
3728
+ }
3729
+ };
3730
+ var WorkerRejected2 = class {
3731
+ statusCode;
3732
+ responseBody;
3733
+ constructor(statusCode, responseBody) {
3734
+ this.statusCode = statusCode;
3735
+ this.responseBody = responseBody;
3736
+ }
3737
+ toDisplayString() {
3738
+ return `Rejected: ${this.statusCode} ${this.responseBody}`;
3739
+ }
3740
+ };
3741
+ var CouldNotParseDecryptionKey2 = class {
3742
+ originalHex;
3743
+ constructor(originalHex) {
3744
+ this.originalHex = originalHex;
3745
+ }
3746
+ toDisplayString() {
3747
+ return `Could not parse decryption key: ${this.originalHex}`;
3748
+ }
3749
+ };
3750
+ var RequestForDecryptionKey = class _RequestForDecryptionKey {
3751
+ decryptionContext;
3752
+ userAddr;
3753
+ publicKey;
3754
+ signature;
3755
+ constructor(decryptionContext, userAddr, publicKey, signature) {
3756
+ this.decryptionContext = decryptionContext;
3757
+ this.userAddr = userAddr;
3758
+ this.publicKey = publicKey;
3759
+ this.signature = signature;
3760
+ }
3761
+ static deserialize(deserializer) {
3762
+ const decryptionContext = DecryptionContext.deserialize(deserializer);
3763
+ const userAddr = deserializer.deserialize(import_ts_sdk16.AccountAddress);
3764
+ const publicKey = deserializer.deserialize(import_ts_sdk16.Ed25519PublicKey);
3765
+ const signature = deserializer.deserialize(import_ts_sdk16.Ed25519Signature);
3766
+ return new _RequestForDecryptionKey(decryptionContext, userAddr, publicKey, signature);
3767
+ }
3768
+ static fromBytes(bytes) {
3769
+ const deserializer = new import_ts_sdk16.Deserializer(bytes);
3770
+ const ret = _RequestForDecryptionKey.deserialize(deserializer);
3771
+ return ret;
3772
+ }
3773
+ static fromHex(hex) {
3774
+ return _RequestForDecryptionKey.fromBytes((0, import_utils21.hexToBytes)(hex));
3775
+ }
3776
+ serialize(serializer) {
3777
+ this.decryptionContext.serialize(serializer);
3778
+ serializer.serialize(this.userAddr);
3779
+ serializer.serialize(this.publicKey);
3780
+ serializer.serialize(this.signature);
3781
+ }
3782
+ toBytes() {
3783
+ const serializer = new import_ts_sdk16.Serializer();
3784
+ this.serialize(serializer);
3785
+ return serializer.toUint8Array();
3786
+ }
3787
+ toHex() {
3788
+ return (0, import_utils21.bytesToHex)(this.toBytes());
3789
+ }
3790
+ };
3791
+
3792
+ // src/silent_setup_encryption_xchain/index.ts
3793
+ var silent_setup_encryption_xchain_exports = {};
3794
+ __export(silent_setup_encryption_xchain_exports, {
3795
+ Aptos: () => aptos_exports,
3796
+ Ciphertext: () => Ciphertext9,
3797
+ ContractID: () => ContractID6,
3798
+ DecryptionContext: () => DecryptionContext2,
3799
+ Decryptor: () => Decryptor2,
3800
+ EncryptionContext: () => EncryptionContext2,
3801
+ Encryptor: () => Encryptor2,
3802
+ ProofOfPermission: () => ProofOfPermission6,
3803
+ RequestForDecryptionKey: () => RequestForDecryptionKey2,
3804
+ SCHEME_APTOS: () => SCHEME_APTOS,
3805
+ SCHEME_SOLANA: () => SCHEME_SOLANA,
3806
+ Solana: () => solana_exports
3807
+ });
3808
+ var import_ts_sdk19 = require("@aptos-labs/ts-sdk");
3809
+ var import_utils24 = require("@noble/hashes/utils");
3810
+
3811
+ // src/silent_setup_encryption_xchain/aptos.ts
3812
+ var aptos_exports = {};
3813
+ __export(aptos_exports, {
3814
+ ContractID: () => ContractID4,
3815
+ POP_SCHEME__V0: () => POP_SCHEME__V0,
3816
+ ProofOfPermission: () => ProofOfPermission4,
3817
+ ProofOfPermissionV0: () => ProofOfPermissionV0
3818
+ });
3819
+ var import_ts_sdk17 = require("@aptos-labs/ts-sdk");
3820
+ var import_utils22 = require("@noble/hashes/utils");
3821
+ var ContractID4 = class _ContractID {
3822
+ chainId;
3823
+ // u8
3824
+ moduleAddr;
3825
+ moduleName;
3826
+ constructor(chainId, moduleAddr, moduleName) {
3827
+ this.chainId = chainId;
3828
+ this.moduleAddr = moduleAddr;
3829
+ this.moduleName = moduleName;
3830
+ }
3831
+ static dummy() {
3832
+ return new _ContractID(0, import_ts_sdk17.AccountAddress.fromString("0x0"), "");
3833
+ }
3834
+ static deserialize(deserializer) {
3835
+ const chainId = deserializer.deserializeU8();
3836
+ const moduleAddr = deserializer.deserialize(import_ts_sdk17.AccountAddress);
3837
+ const moduleName = deserializer.deserializeStr();
3838
+ return new _ContractID(chainId, moduleAddr, moduleName);
3839
+ }
3840
+ static fromBytes(bytes) {
3841
+ const deserializer = new import_ts_sdk17.Deserializer(bytes);
3842
+ return _ContractID.deserialize(deserializer);
3843
+ }
3844
+ static fromHex(hex) {
3845
+ return _ContractID.fromBytes((0, import_utils22.hexToBytes)(hex));
3846
+ }
3847
+ serialize(serializer) {
3848
+ serializer.serializeU8(this.chainId);
3849
+ serializer.serialize(this.moduleAddr);
3850
+ serializer.serializeStr(this.moduleName);
3851
+ }
3852
+ toBytes() {
3853
+ const serializer = new import_ts_sdk17.Serializer();
3854
+ this.serialize(serializer);
3855
+ return serializer.toUint8Array();
3856
+ }
3857
+ toHex() {
3858
+ return (0, import_utils22.bytesToHex)(this.toBytes());
3859
+ }
3860
+ };
3861
+ var POP_SCHEME__V0 = 0;
3862
+ var ProofOfPermission4 = class _ProofOfPermission {
3863
+ scheme;
3864
+ inner;
3865
+ constructor(scheme, inner) {
3866
+ this.scheme = scheme;
3867
+ this.inner = inner;
3868
+ }
3869
+ static newV0(v0) {
3870
+ return new _ProofOfPermission(POP_SCHEME__V0, v0);
3871
+ }
3872
+ static deserialize(deserializer) {
3873
+ const scheme = deserializer.deserializeU8();
3874
+ if (scheme === POP_SCHEME__V0) {
3875
+ const inner = ProofOfPermissionV0.deserialize(deserializer);
3876
+ return new _ProofOfPermission(scheme, inner);
3877
+ } else {
3878
+ throw new Error(`Unknown scheme: ${scheme}`);
3879
+ }
3880
+ }
3881
+ static fromBytes(bytes) {
3882
+ const deserializer = new import_ts_sdk17.Deserializer(bytes);
3883
+ return _ProofOfPermission.deserialize(deserializer);
3884
+ }
3885
+ static fromHex(hex) {
3886
+ return _ProofOfPermission.fromBytes((0, import_utils22.hexToBytes)(hex));
3887
+ }
3888
+ serialize(serializer) {
3889
+ serializer.serializeU8(this.scheme);
3890
+ this.inner.serialize(serializer);
3891
+ }
3892
+ toBytes() {
3893
+ const serializer = new import_ts_sdk17.Serializer();
3894
+ this.serialize(serializer);
3895
+ return serializer.toUint8Array();
3896
+ }
3897
+ toHex() {
3898
+ return (0, import_utils22.bytesToHex)(this.toBytes());
3899
+ }
3900
+ };
3901
+ var ProofOfPermissionV0 = class _ProofOfPermissionV0 {
3902
+ userAddr;
3903
+ publicKey;
3904
+ signature;
3905
+ constructor(userAddr, publicKey, signature) {
3906
+ this.userAddr = userAddr;
3907
+ this.publicKey = publicKey;
3908
+ this.signature = signature;
3909
+ }
3910
+ static deserialize(deserializer) {
3911
+ const userAddr = deserializer.deserialize(import_ts_sdk17.AccountAddress);
3912
+ const publicKey = deserializer.deserialize(import_ts_sdk17.Ed25519PublicKey);
3913
+ const signature = deserializer.deserialize(import_ts_sdk17.Ed25519Signature);
3914
+ return new _ProofOfPermissionV0(userAddr, publicKey, signature);
3915
+ }
3916
+ static fromBytes(bytes) {
3917
+ const deserializer = new import_ts_sdk17.Deserializer(bytes);
3918
+ return _ProofOfPermissionV0.deserialize(deserializer);
3919
+ }
3920
+ static fromHex(hex) {
3921
+ return _ProofOfPermissionV0.fromBytes((0, import_utils22.hexToBytes)(hex));
3922
+ }
3923
+ serialize(serializer) {
3924
+ serializer.serialize(this.userAddr);
3925
+ serializer.serialize(this.publicKey);
3926
+ serializer.serialize(this.signature);
3927
+ }
3928
+ toBytes() {
3929
+ const serializer = new import_ts_sdk17.Serializer();
3930
+ this.serialize(serializer);
3931
+ return serializer.toUint8Array();
3932
+ }
3933
+ toHex() {
3934
+ return (0, import_utils22.bytesToHex)(this.toBytes());
3935
+ }
3936
+ };
3937
+
3938
+ // src/silent_setup_encryption_xchain/solana.ts
3939
+ var solana_exports = {};
3940
+ __export(solana_exports, {
3941
+ ContractID: () => ContractID5,
3942
+ ContractIDV0: () => ContractIDV0,
3943
+ POP_SCHEME__UNVERSIONED_TXN: () => POP_SCHEME__UNVERSIONED_TXN,
3944
+ POP_SCHEME__VERSIONED_TXN: () => POP_SCHEME__VERSIONED_TXN,
3945
+ ProofOfPermission: () => ProofOfPermission5,
3946
+ SCHEME_V0: () => SCHEME_V0
3947
+ });
3948
+ var import_ts_sdk18 = require("@aptos-labs/ts-sdk");
3949
+ var import_utils23 = require("@noble/hashes/utils");
3950
+ var import_web32 = require("@solana/web3.js");
3951
+ var SCHEME_V0 = 0;
3952
+ var ContractID5 = class _ContractID {
3953
+ scheme;
3954
+ inner;
3955
+ constructor(scheme, inner) {
3956
+ this.scheme = scheme;
3957
+ this.inner = inner;
3958
+ }
3959
+ static newV0(v0) {
3960
+ return new _ContractID(SCHEME_V0, v0);
3961
+ }
3962
+ static deserialize(deserializer) {
3963
+ const scheme = deserializer.deserializeU8();
3964
+ if (scheme == SCHEME_V0) {
3965
+ return new _ContractID(SCHEME_V0, ContractIDV0.deserialize(deserializer));
3966
+ } else {
3967
+ throw new Error(`Unknown scheme: ${scheme}`);
3968
+ }
3969
+ }
3970
+ static fromBytes(bytes) {
3971
+ const deserializer = new import_ts_sdk18.Deserializer(bytes);
3972
+ return _ContractID.deserialize(deserializer);
3973
+ }
3974
+ static fromHex(hex) {
3975
+ return _ContractID.fromBytes((0, import_utils23.hexToBytes)(hex));
3976
+ }
3977
+ serialize(serializer) {
3978
+ serializer.serializeU8(this.scheme);
3979
+ if (this.scheme == SCHEME_V0) {
3980
+ this.inner.serialize(serializer);
3981
+ } else {
3982
+ throw new Error(`Unknown scheme: ${this.scheme}`);
3983
+ }
3984
+ }
3985
+ toBytes() {
3986
+ const serializer = new import_ts_sdk18.Serializer();
3987
+ this.serialize(serializer);
3988
+ return serializer.toUint8Array();
3989
+ }
3990
+ toHex() {
3991
+ return (0, import_utils23.bytesToHex)(this.toBytes());
3992
+ }
3993
+ };
3994
+ var ContractIDV0 = class _ContractIDV0 {
3995
+ knownChainName;
3996
+ // mainnet-beta/testnet/devnet
3997
+ programId;
3998
+ constructor(knownChainName, programId) {
3999
+ this.knownChainName = knownChainName;
4000
+ this.programId = programId;
4001
+ }
4002
+ static deserialize(deserializer) {
4003
+ const knownChainName = deserializer.deserializeStr();
4004
+ const programId = new import_web32.PublicKey(deserializer.deserializeBytes());
4005
+ return new _ContractIDV0(knownChainName, programId);
4006
+ }
4007
+ static fromBytes(bytes) {
4008
+ const deserializer = new import_ts_sdk18.Deserializer(bytes);
4009
+ return _ContractIDV0.deserialize(deserializer);
4010
+ }
4011
+ static fromHex(hex) {
4012
+ return _ContractIDV0.fromBytes((0, import_utils23.hexToBytes)(hex));
4013
+ }
4014
+ serialize(serializer) {
4015
+ serializer.serializeStr(this.knownChainName);
4016
+ serializer.serializeBytes(this.programId.toBytes());
4017
+ }
4018
+ toBytes() {
4019
+ const serializer = new import_ts_sdk18.Serializer();
4020
+ this.serialize(serializer);
4021
+ return serializer.toUint8Array();
4022
+ }
4023
+ toHex() {
4024
+ return (0, import_utils23.bytesToHex)(this.toBytes());
4025
+ }
4026
+ };
4027
+ var POP_SCHEME__UNVERSIONED_TXN = 0;
4028
+ var POP_SCHEME__VERSIONED_TXN = 1;
4029
+ var ProofOfPermission5 = class _ProofOfPermission {
4030
+ scheme;
4031
+ inner;
4032
+ constructor(scheme, inner) {
4033
+ this.scheme = scheme;
4034
+ this.inner = inner;
4035
+ }
4036
+ static newVersioned(txn) {
4037
+ return new _ProofOfPermission(POP_SCHEME__VERSIONED_TXN, txn);
4038
+ }
4039
+ static newUnversioned(txn) {
4040
+ return new _ProofOfPermission(POP_SCHEME__UNVERSIONED_TXN, txn);
4041
+ }
4042
+ static deserialize(deserializer) {
4043
+ const scheme = deserializer.deserializeU8();
4044
+ const bytes = deserializer.deserializeBytes();
4045
+ if (scheme == POP_SCHEME__VERSIONED_TXN) {
4046
+ const inner = import_web32.VersionedTransaction.deserialize(bytes);
4047
+ return new _ProofOfPermission(POP_SCHEME__VERSIONED_TXN, inner);
4048
+ } else if (scheme == POP_SCHEME__UNVERSIONED_TXN) {
4049
+ const inner = import_web32.Transaction.from(Buffer.from(bytes));
4050
+ return new _ProofOfPermission(POP_SCHEME__UNVERSIONED_TXN, inner);
4051
+ } else {
4052
+ throw new Error(`Unknown scheme: ${scheme}`);
4053
+ }
4054
+ }
4055
+ static fromBytes(bytes) {
4056
+ const deserializer = new import_ts_sdk18.Deserializer(bytes);
4057
+ return _ProofOfPermission.deserialize(deserializer);
4058
+ }
4059
+ static fromHex(hex) {
4060
+ return _ProofOfPermission.fromBytes((0, import_utils23.hexToBytes)(hex));
4061
+ }
4062
+ serialize(serializer) {
4063
+ serializer.serializeU8(this.scheme);
4064
+ if (this.scheme == POP_SCHEME__VERSIONED_TXN) {
4065
+ serializer.serializeBytes(this.inner.serialize());
4066
+ } else if (this.scheme == POP_SCHEME__UNVERSIONED_TXN) {
4067
+ serializer.serializeBytes(this.inner.serialize());
4068
+ } else {
4069
+ throw new Error(`Unknown scheme: ${this.scheme}`);
4070
+ }
4071
+ }
4072
+ toBytes() {
4073
+ const serializer = new import_ts_sdk18.Serializer();
4074
+ this.serialize(serializer);
4075
+ return serializer.toUint8Array();
4076
+ }
4077
+ toHex() {
4078
+ return (0, import_utils23.bytesToHex)(this.toBytes());
4079
+ }
4080
+ };
4081
+
4082
+ // src/silent_setup_encryption_xchain/index.ts
4083
+ var SCHEME_APTOS = 0;
4084
+ var SCHEME_SOLANA = 1;
4085
+ var ContractID6 = class _ContractID {
4086
+ scheme;
4087
+ inner;
4088
+ constructor(scheme, inner) {
4089
+ this.scheme = scheme;
4090
+ this.inner = inner;
4091
+ }
4092
+ static newAptos(id) {
4093
+ return new _ContractID(SCHEME_APTOS, id);
4094
+ }
4095
+ static newSolana(id) {
4096
+ return new _ContractID(SCHEME_SOLANA, id);
4097
+ }
4098
+ static dummy() {
4099
+ return new _ContractID(SCHEME_APTOS, ContractID4.dummy());
4100
+ }
4101
+ static deserialize(deserializer) {
4102
+ const scheme = deserializer.deserializeU8();
4103
+ if (scheme == SCHEME_APTOS) {
4104
+ return new _ContractID(SCHEME_APTOS, ContractID4.deserialize(deserializer));
4105
+ } else if (scheme == SCHEME_SOLANA) {
4106
+ return new _ContractID(SCHEME_SOLANA, ContractID5.deserialize(deserializer));
4107
+ } else {
4108
+ throw new Error(`Unknown scheme: ${scheme}`);
4109
+ }
4110
+ }
4111
+ static fromBytes(bytes) {
4112
+ const deserializer = new import_ts_sdk19.Deserializer(bytes);
4113
+ return _ContractID.deserialize(deserializer);
4114
+ }
4115
+ static fromHex(hex) {
4116
+ return _ContractID.fromBytes((0, import_utils24.hexToBytes)(hex));
4117
+ }
4118
+ serialize(serializer) {
4119
+ serializer.serializeU8(this.scheme);
4120
+ if (this.scheme == SCHEME_APTOS) {
4121
+ this.inner.serialize(serializer);
4122
+ } else if (this.scheme == SCHEME_SOLANA) {
4123
+ this.inner.serialize(serializer);
4124
+ } else {
4125
+ throw new Error(`Unknown scheme: ${this.scheme}`);
4126
+ }
4127
+ }
4128
+ toBytes() {
4129
+ const serializer = new import_ts_sdk19.Serializer();
4130
+ this.serialize(serializer);
4131
+ return serializer.toUint8Array();
4132
+ }
4133
+ toHex() {
4134
+ return (0, import_utils24.bytesToHex)(this.toBytes());
4135
+ }
4136
+ };
4137
+ var ProofOfPermission6 = class _ProofOfPermission {
4138
+ scheme;
4139
+ inner;
4140
+ constructor(scheme, inner) {
4141
+ this.scheme = scheme;
4142
+ this.inner = inner;
4143
+ }
4144
+ static newAptos(id) {
4145
+ return new _ProofOfPermission(SCHEME_APTOS, id);
4146
+ }
4147
+ static newSolana(id) {
4148
+ return new _ProofOfPermission(SCHEME_SOLANA, id);
4149
+ }
4150
+ static deserialize(deserializer) {
4151
+ const scheme = deserializer.deserializeU8();
4152
+ if (scheme == SCHEME_APTOS) {
4153
+ return new _ProofOfPermission(SCHEME_APTOS, ProofOfPermission4.deserialize(deserializer));
4154
+ } else if (scheme == SCHEME_SOLANA) {
4155
+ return new _ProofOfPermission(SCHEME_SOLANA, ProofOfPermission5.deserialize(deserializer));
4156
+ } else {
4157
+ throw new Error(`Unknown scheme: ${scheme}`);
4158
+ }
4159
+ }
4160
+ static fromBytes(bytes) {
4161
+ const deserializer = new import_ts_sdk19.Deserializer(bytes);
4162
+ return _ProofOfPermission.deserialize(deserializer);
4163
+ }
4164
+ static fromHex(hex) {
4165
+ return _ProofOfPermission.fromBytes((0, import_utils24.hexToBytes)(hex));
4166
+ }
4167
+ serialize(serializer) {
4168
+ serializer.serializeU8(this.scheme);
4169
+ if (this.scheme == SCHEME_APTOS) {
4170
+ this.inner.serialize(serializer);
4171
+ } else if (this.scheme == SCHEME_SOLANA) {
4172
+ this.inner.serialize(serializer);
4173
+ } else {
4174
+ throw new Error(`Unknown scheme: ${this.scheme}`);
4175
+ }
4176
+ }
4177
+ toBytes() {
4178
+ const serializer = new import_ts_sdk19.Serializer();
4179
+ this.serialize(serializer);
4180
+ return serializer.toUint8Array();
4181
+ }
4182
+ toHex() {
4183
+ return (0, import_utils24.bytesToHex)(this.toBytes());
4184
+ }
4185
+ };
4186
+ var EncryptionContext2 = class _EncryptionContext {
4187
+ workers;
4188
+ threshold;
4189
+ contractId;
4190
+ constructor({ workers, threshold, contractId }) {
4191
+ this.workers = workers;
4192
+ this.threshold = threshold;
4193
+ this.contractId = contractId;
4194
+ }
4195
+ static deserialize(deserializer) {
4196
+ const numWorkers = deserializer.deserializeUleb128AsU32();
4197
+ if (numWorkers === 0) throw new Error("workers must be non-empty");
4198
+ const workers = Array.from({ length: numWorkers }, () => deserializer.deserializeStr());
4199
+ const threshold = Number(deserializer.deserializeU64());
4200
+ if (threshold == 0) throw new Error("threshold must be greater than 0");
4201
+ if (threshold > numWorkers) throw new Error("threshold must be less than or equal to the number of workers");
4202
+ const contractId = ContractID6.deserialize(deserializer);
4203
+ return new _EncryptionContext({ workers, threshold, contractId });
4204
+ }
4205
+ static fromBytes(bytes) {
4206
+ const deserializer = new import_ts_sdk19.Deserializer(bytes);
4207
+ return _EncryptionContext.deserialize(deserializer);
4208
+ }
4209
+ static fromHex(hex) {
4210
+ return _EncryptionContext.fromBytes((0, import_utils24.hexToBytes)(hex));
4211
+ }
4212
+ serialize(serializer) {
4213
+ serializer.serializeU32AsUleb128(this.workers.length);
4214
+ this.workers.forEach((w) => serializer.serializeStr(w));
4215
+ serializer.serializeU64(this.threshold);
4216
+ this.contractId.serialize(serializer);
4217
+ }
4218
+ toBytes() {
4219
+ const serializer = new import_ts_sdk19.Serializer();
4220
+ this.serialize(serializer);
4221
+ return serializer.toUint8Array();
4222
+ }
4223
+ toHex() {
4224
+ return (0, import_utils24.bytesToHex)(this.toBytes());
4225
+ }
4226
+ async loadEncryptor() {
4227
+ const workerConfigs = await Promise.all(this.workers.map(async (worker) => {
4228
+ const config = await worker_config_exports.get(worker);
4229
+ return config;
4230
+ }));
4231
+ return new Encryptor2(this, workerConfigs);
4232
+ }
4233
+ };
4234
+ var DecryptionContext2 = class _DecryptionContext {
4235
+ workers;
4236
+ threshold;
4237
+ contractId;
4238
+ domain;
4239
+ constructor({ workers, threshold, contractId, domain }) {
4240
+ if (workers.length === 0) throw new Error("workers must be non-empty");
4241
+ if (threshold > workers.length) throw new Error("threshold must be less than or equal to the number of workers");
4242
+ if (threshold == 0) throw new Error("threshold must be greater than 0");
4243
+ this.workers = workers;
4244
+ this.threshold = threshold;
4245
+ this.contractId = contractId;
4246
+ this.domain = domain;
4247
+ }
4248
+ static dummy() {
4249
+ return new _DecryptionContext({
4250
+ workers: [],
4251
+ threshold: 0,
4252
+ contractId: ContractID6.dummy(),
4253
+ domain: new Uint8Array(0)
4254
+ });
4255
+ }
4256
+ static deserialize(deserializer) {
4257
+ const numWorkers = deserializer.deserializeUleb128AsU32();
4258
+ if (numWorkers === 0) throw new Error("workers must be non-empty");
4259
+ const workers = Array.from({ length: numWorkers }, () => deserializer.deserializeStr());
4260
+ const threshold = Number(deserializer.deserializeU64());
4261
+ if (threshold == 0) throw new Error("threshold must be greater than 0");
4262
+ if (threshold > numWorkers) throw new Error("threshold must be less than or equal to the number of workers");
4263
+ const contractId = ContractID6.deserialize(deserializer);
4264
+ const domain = deserializer.deserializeBytes();
4265
+ return new _DecryptionContext({ workers, threshold, contractId, domain });
4266
+ }
4267
+ static fromBytes(bytes) {
4268
+ const deserializer = new import_ts_sdk19.Deserializer(bytes);
4269
+ return _DecryptionContext.deserialize(deserializer);
4270
+ }
4271
+ static fromHex(hex) {
4272
+ return _DecryptionContext.fromBytes((0, import_utils24.hexToBytes)(hex));
4273
+ }
4274
+ serialize(serializer) {
4275
+ serializer.serializeU32AsUleb128(this.workers.length);
4276
+ this.workers.forEach((w) => serializer.serializeStr(w));
4277
+ serializer.serializeU64(this.threshold);
4278
+ this.contractId.serialize(serializer);
4279
+ serializer.serializeBytes(this.domain);
4280
+ }
4281
+ toBytes() {
4282
+ const serializer = new import_ts_sdk19.Serializer();
4283
+ this.serialize(serializer);
4284
+ return serializer.toUint8Array();
4285
+ }
4286
+ toHex() {
4287
+ return (0, import_utils24.bytesToHex)(this.toBytes());
4288
+ }
4289
+ async loadDecryptor(proof) {
4290
+ const decKeyLoadResults = await Promise.all(this.workers.map(async (workerEndpoint) => {
4291
+ const task = WorkerTask.newXChainSilentSetupDecryptionKey(this, proof);
4292
+ const controller = new AbortController();
4293
+ const timeoutId = setTimeout(() => controller.abort(), 5e3);
4294
+ var response = null;
4295
+ try {
4296
+ response = await fetch(workerEndpoint, {
4297
+ method: "POST",
4298
+ body: task.toHex(),
4299
+ signal: controller.signal
4300
+ });
4301
+ } catch (error) {
4302
+ clearTimeout(timeoutId);
4303
+ }
4304
+ if (response == null) {
4305
+ return new WorkerTimedOut3();
4306
+ }
4307
+ const responseBody = await response.text();
4308
+ if (response.status !== 200) {
4309
+ return new WorkerRejected3(response.status, responseBody);
4310
+ }
4311
+ try {
4312
+ return IdentityPrivateKey2.fromHex(responseBody);
4313
+ } catch (error) {
4314
+ return new CouldNotParseDecryptionKey3(responseBody);
4315
+ }
4316
+ }));
4317
+ const numSharesCollected = decKeyLoadResults.filter((loadResult) => loadResult instanceof IdentityPrivateKey2).length;
4318
+ if (numSharesCollected < this.threshold) {
4319
+ const workerResults = this.workers.map((worker, i) => {
4320
+ const result = decKeyLoadResults[i];
4321
+ return `${worker}: ${result instanceof IdentityPrivateKey2 ? "Success" : result.toDisplayString()}`;
4322
+ }).join(", ");
4323
+ throw new Error(`Failed to collect enough shares to decrypt. Collected ${numSharesCollected} shares, but needed ${this.threshold} shares. Worker results: ${workerResults}`);
4324
+ }
4325
+ const decKeys = decKeyLoadResults.map((loadResult) => loadResult instanceof IdentityPrivateKey2 ? loadResult : null);
4326
+ return new Decryptor2(this, decKeys);
4327
+ }
4328
+ };
4329
+ var Ciphertext9 = class _Ciphertext {
4330
+ decryptionContext;
4331
+ aesCiph;
4332
+ ibeCiphs;
4333
+ constructor(decryptionContext, aesCiph, ibeCiphs) {
4334
+ this.decryptionContext = decryptionContext;
4335
+ this.aesCiph = aesCiph;
4336
+ this.ibeCiphs = ibeCiphs;
4337
+ }
4338
+ static dummy() {
4339
+ return new _Ciphertext(DecryptionContext2.dummy(), Ciphertext6.dummy(), []);
4340
+ }
4341
+ static deserialize(deserializer) {
4342
+ const decryptionContext = DecryptionContext2.deserialize(deserializer);
4343
+ const aesCiph = Ciphertext6.deserialize(deserializer);
4344
+ const ibeCiphs = deserializer.deserializeVector(Ciphertext4);
4345
+ return new _Ciphertext(decryptionContext, aesCiph, ibeCiphs);
4346
+ }
4347
+ static fromBytes(bytes) {
4348
+ const deserializer = new import_ts_sdk19.Deserializer(bytes);
4349
+ const ret = _Ciphertext.deserialize(deserializer);
4350
+ if (deserializer.remaining() !== 0) {
4351
+ throw new Error("Ciphertext deserialization failed: extra bytes");
4352
+ }
4353
+ return ret;
4354
+ }
4355
+ static fromHex(hex) {
4356
+ return _Ciphertext.fromBytes((0, import_utils24.hexToBytes)(hex));
4357
+ }
4358
+ serialize(serializer) {
4359
+ this.decryptionContext.serialize(serializer);
4360
+ this.aesCiph.serialize(serializer);
4361
+ serializer.serializeU32AsUleb128(this.ibeCiphs.length);
4362
+ this.ibeCiphs.forEach((ibeCiph) => ibeCiph.serialize(serializer));
4363
+ }
4364
+ toBytes() {
4365
+ const serializer = new import_ts_sdk19.Serializer();
4366
+ this.serialize(serializer);
4367
+ return serializer.toUint8Array();
4368
+ }
4369
+ };
4370
+ var Encryptor2 = class {
4371
+ domain;
4372
+ workerConfigs;
4373
+ constructor(domain, workerConfigs) {
4374
+ this.domain = domain;
4375
+ this.workerConfigs = workerConfigs;
4376
+ }
4377
+ encrypt({ domain, plaintext }) {
4378
+ const decCtxt = new DecryptionContext2({
4379
+ workers: this.domain.workers,
4380
+ threshold: this.domain.threshold,
4381
+ contractId: this.domain.contractId,
4382
+ domain
4383
+ });
4384
+ const symmKey = keygen8();
4385
+ const symmKeyShares = split(symmKey.toBytes(), this.domain.threshold, this.domain.workers.length);
4386
+ const symmCiph = encrypt6(symmKey, plaintext);
4387
+ const ibeCiphs = symmKeyShares.map((share, idx) => encrypt4(this.workerConfigs[idx].ibeMpk, decCtxt.toBytes(), share.payload));
4388
+ return new Ciphertext9(decCtxt, symmCiph, ibeCiphs);
4389
+ }
4390
+ };
4391
+ var Decryptor2 = class {
4392
+ ibeDecryptionKeys;
4393
+ decryptionContext;
4394
+ constructor(decryptionContext, ibeDecryptionKeys) {
4395
+ this.decryptionContext = decryptionContext;
4396
+ this.ibeDecryptionKeys = ibeDecryptionKeys;
4397
+ }
4398
+ decrypt(ciphertext) {
4399
+ if (ciphertext.decryptionContext.toHex() !== this.decryptionContext.toHex()) {
4400
+ throw new Error("Ciphertext does not match decryption domain");
4401
+ }
4402
+ const symmKeyShares = ciphertext.ibeCiphs.map((ibeCiph, idx) => {
4403
+ if (this.ibeDecryptionKeys[idx] == null) {
4404
+ console.log(`idx=${idx}, isk is null`);
4405
+ return null;
4406
+ }
4407
+ const sharePayload = decrypt4(this.ibeDecryptionKeys[idx], ibeCiph);
4408
+ if (sharePayload == null) {
4409
+ console.log(`idx=${idx}, sharePayload is null`);
4410
+ return null;
4411
+ }
4412
+ return new Share(idx + 1, sharePayload);
4413
+ }).filter((share) => share != null);
4414
+ const symmKeyBytes = combine(symmKeyShares);
4415
+ const symmKey = Key2.fromBytes(symmKeyBytes);
4416
+ return decrypt6(symmKey, ciphertext.aesCiph);
4417
+ }
4418
+ };
4419
+ var WorkerTimedOut3 = class {
4420
+ toDisplayString() {
4421
+ return "Timed out";
4422
+ }
4423
+ };
4424
+ var WorkerRejected3 = class {
4425
+ statusCode;
4426
+ responseBody;
4427
+ constructor(statusCode, responseBody) {
4428
+ this.statusCode = statusCode;
4429
+ this.responseBody = responseBody;
4430
+ }
4431
+ toDisplayString() {
4432
+ return `Rejected: ${this.statusCode} ${this.responseBody}`;
4433
+ }
4434
+ };
4435
+ var CouldNotParseDecryptionKey3 = class {
4436
+ originalHex;
4437
+ constructor(originalHex) {
4438
+ this.originalHex = originalHex;
4439
+ }
4440
+ toDisplayString() {
4441
+ return `Could not parse decryption key: ${this.originalHex}`;
4442
+ }
4443
+ };
4444
+ var RequestForDecryptionKey2 = class _RequestForDecryptionKey {
4445
+ decryptionContext;
4446
+ proofOfPermission;
4447
+ constructor(decryptionContext, proofOfPermission) {
4448
+ this.decryptionContext = decryptionContext;
4449
+ this.proofOfPermission = proofOfPermission;
4450
+ }
4451
+ static deserialize(deserializer) {
4452
+ const decryptionContext = DecryptionContext2.deserialize(deserializer);
4453
+ const proofOfPermission = ProofOfPermission6.deserialize(deserializer);
4454
+ return new _RequestForDecryptionKey(decryptionContext, proofOfPermission);
4455
+ }
4456
+ static fromBytes(bytes) {
4457
+ const deserializer = new import_ts_sdk19.Deserializer(bytes);
4458
+ return _RequestForDecryptionKey.deserialize(deserializer);
4459
+ }
4460
+ static fromHex(hex) {
4461
+ return _RequestForDecryptionKey.fromBytes((0, import_utils24.hexToBytes)(hex));
4462
+ }
4463
+ serialize(serializer) {
4464
+ this.decryptionContext.serialize(serializer);
4465
+ this.proofOfPermission.serialize(serializer);
4466
+ }
4467
+ toBytes() {
4468
+ const serializer = new import_ts_sdk19.Serializer();
4469
+ this.serialize(serializer);
4470
+ return serializer.toUint8Array();
4471
+ }
4472
+ toHex() {
4473
+ return (0, import_utils24.bytesToHex)(this.toBytes());
4474
+ }
4475
+ };
4476
+ // Annotate the CommonJS export names for ESM import in node:
4477
+ 0 && (module.exports = {
4478
+ ElGamal,
4479
+ Enc,
4480
+ Group,
4481
+ IBE,
4482
+ Sig,
4483
+ SilentSetupEncryption,
4484
+ SilentSetupEncryptionXChain,
4485
+ Sym,
4486
+ ThresholdIbe,
4487
+ Utils,
4488
+ WorkerConfig,
4489
+ WorkerTask
4490
+ });
4491
+ //# sourceMappingURL=index.js.map