@opendatalabs/vana-sdk 0.1.0-alpha.5f8458e → 0.1.0-alpha.606fa2d

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 (50) hide show
  1. package/README.md +55 -4
  2. package/dist/{browser-cRpdLQ3-.d.ts → browser-Bb8gLWHp.d.ts} +61 -10
  3. package/dist/browser.d.ts +1 -1
  4. package/dist/browser.js +745 -113
  5. package/dist/browser.js.map +1 -1
  6. package/dist/chains.browser.cjs +2 -2
  7. package/dist/chains.browser.cjs.map +1 -1
  8. package/dist/chains.browser.js +2 -2
  9. package/dist/chains.browser.js.map +1 -1
  10. package/dist/chains.cjs +2 -2
  11. package/dist/chains.cjs.map +1 -1
  12. package/dist/chains.js +2 -2
  13. package/dist/chains.js.map +1 -1
  14. package/dist/chains.node.cjs +2 -2
  15. package/dist/chains.node.cjs.map +1 -1
  16. package/dist/chains.node.js +2 -2
  17. package/dist/chains.node.js.map +1 -1
  18. package/dist/index.browser.d.ts +1348 -243
  19. package/dist/index.browser.js +35080 -32770
  20. package/dist/index.browser.js.map +1 -1
  21. package/dist/index.node.cjs +35587 -33174
  22. package/dist/index.node.cjs.map +1 -1
  23. package/dist/index.node.d.cts +1136 -250
  24. package/dist/index.node.d.ts +1136 -250
  25. package/dist/index.node.js +35459 -33037
  26. package/dist/index.node.js.map +1 -1
  27. package/dist/{node-CkdgwBiv.d.cts → node-D9-F9uEP.d.cts} +3 -2
  28. package/dist/{node-CkdgwBiv.d.ts → node-D9-F9uEP.d.ts} +3 -2
  29. package/dist/node.cjs +704 -67
  30. package/dist/node.cjs.map +1 -1
  31. package/dist/node.d.cts +1 -1
  32. package/dist/node.d.ts +1 -1
  33. package/dist/node.js +716 -66
  34. package/dist/node.js.map +1 -1
  35. package/dist/platform.browser.d.ts +2 -2
  36. package/dist/platform.browser.js +808 -121
  37. package/dist/platform.browser.js.map +1 -1
  38. package/dist/platform.cjs +973 -186
  39. package/dist/platform.cjs.map +1 -1
  40. package/dist/platform.d.cts +1 -1
  41. package/dist/platform.d.ts +1 -1
  42. package/dist/platform.js +985 -186
  43. package/dist/platform.js.map +1 -1
  44. package/dist/platform.node.cjs +973 -186
  45. package/dist/platform.node.cjs.map +1 -1
  46. package/dist/platform.node.d.cts +63 -12
  47. package/dist/platform.node.d.ts +63 -12
  48. package/dist/platform.node.js +985 -186
  49. package/dist/platform.node.js.map +1 -1
  50. package/package.json +40 -23
package/dist/platform.cjs CHANGED
@@ -30,31 +30,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
30
30
  ));
31
31
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
32
 
33
- // src/platform/shared/crypto-utils.ts
34
- function processWalletPublicKey(publicKey) {
35
- const publicKeyHex = publicKey.startsWith("0x") ? publicKey.slice(2) : publicKey;
36
- const publicKeyBytes = Buffer.from(publicKeyHex, "hex");
37
- return publicKeyBytes.length === 64 ? Buffer.concat([Buffer.from([4]), publicKeyBytes]) : publicKeyBytes;
38
- }
39
- function processWalletPrivateKey(privateKey) {
40
- const privateKeyHex = privateKey.startsWith("0x") ? privateKey.slice(2) : privateKey;
41
- return Buffer.from(privateKeyHex, "hex");
42
- }
43
- function parseEncryptedDataBuffer(encryptedBuffer) {
44
- return {
45
- iv: encryptedBuffer.slice(0, 16),
46
- ephemPublicKey: encryptedBuffer.slice(16, 81),
47
- // 65 bytes for uncompressed public key
48
- ciphertext: encryptedBuffer.slice(81, -32),
49
- mac: encryptedBuffer.slice(-32)
50
- };
51
- }
52
- var init_crypto_utils = __esm({
53
- "src/platform/shared/crypto-utils.ts"() {
54
- "use strict";
55
- }
56
- });
57
-
58
33
  // src/platform/shared/pgp-utils.ts
59
34
  function processPGPKeyOptions(options) {
60
35
  return {
@@ -97,144 +72,854 @@ var init_error_utils = __esm({
97
72
  }
98
73
  });
99
74
 
75
+ // src/utils/lazy-import.ts
76
+ function lazyImport(importFn) {
77
+ let cached = null;
78
+ return () => {
79
+ if (!cached) {
80
+ cached = importFn().catch((err) => {
81
+ cached = null;
82
+ throw new Error("Failed to load module", { cause: err });
83
+ });
84
+ }
85
+ return cached;
86
+ };
87
+ }
88
+ var init_lazy_import = __esm({
89
+ "src/utils/lazy-import.ts"() {
90
+ "use strict";
91
+ }
92
+ });
93
+
94
+ // src/utils/encoding.ts
95
+ function toHex(data) {
96
+ if (typeof Buffer !== "undefined" && Buffer.from) {
97
+ return Buffer.from(data).toString("hex");
98
+ }
99
+ return Array.from(data, (byte) => byte.toString(16).padStart(2, "0")).join(
100
+ ""
101
+ );
102
+ }
103
+ function fromHex(hex) {
104
+ const cleanHex = hex.startsWith("0x") ? hex.slice(2) : hex;
105
+ if (cleanHex.length % 2 !== 0) {
106
+ throw new Error("Invalid hex string: odd length");
107
+ }
108
+ if (!/^[0-9a-fA-F]*$/.test(cleanHex)) {
109
+ throw new Error("Invalid hex string: contains non-hex characters");
110
+ }
111
+ if (typeof Buffer !== "undefined" && Buffer.from) {
112
+ return new Uint8Array(Buffer.from(cleanHex, "hex"));
113
+ }
114
+ const bytes = new Uint8Array(cleanHex.length / 2);
115
+ for (let i = 0; i < cleanHex.length; i += 2) {
116
+ bytes[i / 2] = parseInt(cleanHex.substr(i, 2), 16);
117
+ }
118
+ return bytes;
119
+ }
120
+ function stringToBytes(str) {
121
+ if (typeof Buffer !== "undefined" && Buffer.from) {
122
+ return new Uint8Array(Buffer.from(str, "utf8"));
123
+ }
124
+ if (typeof TextEncoder !== "undefined") {
125
+ return new TextEncoder().encode(str);
126
+ }
127
+ const bytes = [];
128
+ for (let i = 0; i < str.length; i++) {
129
+ const char = str.charCodeAt(i);
130
+ if (char < 128) {
131
+ bytes.push(char);
132
+ } else if (char < 2048) {
133
+ bytes.push(192 | char >> 6, 128 | char & 63);
134
+ } else if (char < 55296 || char >= 57344) {
135
+ bytes.push(
136
+ 224 | char >> 12,
137
+ 128 | char >> 6 & 63,
138
+ 128 | char & 63
139
+ );
140
+ } else {
141
+ i++;
142
+ const char2 = str.charCodeAt(i);
143
+ const codePoint = 65536 + ((char & 1023) << 10 | char2 & 1023);
144
+ bytes.push(
145
+ 240 | codePoint >> 18,
146
+ 128 | codePoint >> 12 & 63,
147
+ 128 | codePoint >> 6 & 63,
148
+ 128 | codePoint & 63
149
+ );
150
+ }
151
+ }
152
+ return new Uint8Array(bytes);
153
+ }
154
+ function bytesToString(bytes) {
155
+ if (typeof Buffer !== "undefined" && Buffer.from) {
156
+ return Buffer.from(bytes).toString("utf8");
157
+ }
158
+ if (typeof TextDecoder !== "undefined") {
159
+ return new TextDecoder().decode(bytes);
160
+ }
161
+ let str = "";
162
+ let i = 0;
163
+ while (i < bytes.length) {
164
+ const byte = bytes[i];
165
+ if (byte < 128) {
166
+ str += String.fromCharCode(byte);
167
+ i++;
168
+ } else if ((byte & 224) === 192) {
169
+ str += String.fromCharCode((byte & 31) << 6 | bytes[i + 1] & 63);
170
+ i += 2;
171
+ } else if ((byte & 240) === 224) {
172
+ str += String.fromCharCode(
173
+ (byte & 15) << 12 | (bytes[i + 1] & 63) << 6 | bytes[i + 2] & 63
174
+ );
175
+ i += 3;
176
+ } else {
177
+ const codePoint = ((byte & 7) << 18 | (bytes[i + 1] & 63) << 12 | (bytes[i + 2] & 63) << 6 | bytes[i + 3] & 63) - 65536;
178
+ str += String.fromCharCode(
179
+ 55296 + (codePoint >> 10),
180
+ 56320 + (codePoint & 1023)
181
+ );
182
+ i += 4;
183
+ }
184
+ }
185
+ return str;
186
+ }
187
+ var init_encoding = __esm({
188
+ "src/utils/encoding.ts"() {
189
+ "use strict";
190
+ }
191
+ });
192
+
193
+ // src/utils/crypto-utils.ts
194
+ function concatBytes(...arrays) {
195
+ const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
196
+ const result = new Uint8Array(totalLength);
197
+ let offset = 0;
198
+ for (const arr of arrays) {
199
+ result.set(arr, offset);
200
+ offset += arr.length;
201
+ }
202
+ return result;
203
+ }
204
+ function hexToBytes(hex) {
205
+ return fromHex(hex);
206
+ }
207
+ function bytesToHex(bytes) {
208
+ return toHex(bytes);
209
+ }
210
+ function processWalletPublicKey(publicKey) {
211
+ const publicKeyHex = typeof publicKey === "string" ? publicKey.startsWith("0x") ? publicKey.slice(2) : publicKey : bytesToHex(publicKey);
212
+ const publicKeyBytes = hexToBytes(publicKeyHex);
213
+ return publicKeyBytes.length === 64 ? concatBytes(new Uint8Array([4]), publicKeyBytes) : publicKeyBytes;
214
+ }
215
+ function processWalletPrivateKey(privateKey) {
216
+ const privateKeyHex = typeof privateKey === "string" ? privateKey.startsWith("0x") ? privateKey.slice(2) : privateKey : bytesToHex(privateKey);
217
+ return hexToBytes(privateKeyHex);
218
+ }
219
+ function parseEncryptedDataBuffer(encryptedBuffer) {
220
+ return {
221
+ iv: encryptedBuffer.slice(0, 16),
222
+ ephemPublicKey: encryptedBuffer.slice(16, 81),
223
+ // 65 bytes for uncompressed public key
224
+ ciphertext: encryptedBuffer.slice(81, -32),
225
+ mac: encryptedBuffer.slice(-32)
226
+ };
227
+ }
228
+ var init_crypto_utils = __esm({
229
+ "src/utils/crypto-utils.ts"() {
230
+ "use strict";
231
+ init_encoding();
232
+ }
233
+ });
234
+
235
+ // src/crypto/services/WalletKeyEncryptionService.ts
236
+ var WalletKeyEncryptionService;
237
+ var init_WalletKeyEncryptionService = __esm({
238
+ "src/crypto/services/WalletKeyEncryptionService.ts"() {
239
+ "use strict";
240
+ init_crypto_utils();
241
+ init_encoding();
242
+ WalletKeyEncryptionService = class {
243
+ eciesProvider;
244
+ constructor(config) {
245
+ this.eciesProvider = config.eciesProvider;
246
+ }
247
+ /**
248
+ * Encrypts data using a wallet's public key.
249
+ *
250
+ * @param data - The plaintext message to encrypt for the wallet owner.
251
+ * @param publicKey - The recipient wallet's public key for encryption.
252
+ * @returns A promise that resolves to the encrypted data as a hex string.
253
+ * @throws {Error} When encryption fails due to invalid key format.
254
+ *
255
+ * @example
256
+ * ```typescript
257
+ * const encrypted = await processor.encryptWithWalletPublicKey(
258
+ * "Secret message",
259
+ * "0x04..." // 65-byte uncompressed public key
260
+ * );
261
+ * console.log(`Encrypted: ${encrypted}`);
262
+ * ```
263
+ */
264
+ async encryptWithWalletPublicKey(data, publicKey) {
265
+ const publicKeyBytes = processWalletPublicKey(publicKey);
266
+ const dataBytes = stringToBytes(data);
267
+ const encrypted = await this.eciesProvider.encrypt(
268
+ publicKeyBytes,
269
+ dataBytes
270
+ );
271
+ const result = concatBytes(
272
+ encrypted.iv,
273
+ encrypted.ephemPublicKey,
274
+ encrypted.ciphertext,
275
+ encrypted.mac
276
+ );
277
+ return bytesToHex(result);
278
+ }
279
+ /**
280
+ * Decrypts data using a wallet's private key.
281
+ *
282
+ * @param encryptedData - The hex-encoded encrypted data to decrypt.
283
+ * @param privateKey - The wallet's private key for decryption.
284
+ * @returns A promise that resolves to the decrypted plaintext message.
285
+ * @throws {Error} When decryption fails due to invalid data or key format.
286
+ *
287
+ * @example
288
+ * ```typescript
289
+ * const decrypted = await processor.decryptWithWalletPrivateKey(
290
+ * encryptedHexString,
291
+ * "0x..." // 32-byte private key
292
+ * );
293
+ * console.log(`Decrypted: ${decrypted}`);
294
+ * ```
295
+ */
296
+ async decryptWithWalletPrivateKey(encryptedData, privateKey) {
297
+ const privateKeyBytes = processWalletPrivateKey(privateKey);
298
+ const encryptedBytes = hexToBytes(encryptedData);
299
+ const encrypted = parseEncryptedDataBuffer(encryptedBytes);
300
+ const decrypted = await this.eciesProvider.decrypt(
301
+ privateKeyBytes,
302
+ encrypted
303
+ );
304
+ return bytesToString(decrypted);
305
+ }
306
+ /**
307
+ * Encrypts a Uint8Array with a wallet public key
308
+ *
309
+ * @param data - Binary data to encrypt
310
+ * @param publicKey - Public key as hex string or Uint8Array
311
+ * @returns Encrypted data structure
312
+ */
313
+ async encryptBinary(data, publicKey) {
314
+ const publicKeyBytes = processWalletPublicKey(publicKey);
315
+ return this.eciesProvider.encrypt(publicKeyBytes, data);
316
+ }
317
+ /**
318
+ * Decrypts to a Uint8Array with a wallet private key
319
+ *
320
+ * @param encrypted - Encrypted data structure
321
+ * @param privateKey - Private key as hex string or Uint8Array
322
+ * @returns Decrypted binary data
323
+ */
324
+ async decryptBinary(encrypted, privateKey) {
325
+ const privateKeyBytes = processWalletPrivateKey(privateKey);
326
+ return this.eciesProvider.decrypt(privateKeyBytes, encrypted);
327
+ }
328
+ /**
329
+ * Gets the underlying ECIES provider
330
+ *
331
+ * @returns The ECIES provider instance
332
+ */
333
+ getECIESProvider() {
334
+ return this.eciesProvider;
335
+ }
336
+ };
337
+ }
338
+ });
339
+
340
+ // src/crypto/ecies/utils.ts
341
+ function hexToBytes2(hex) {
342
+ if (hex.length % 2 !== 0) {
343
+ throw new Error("Hex string must have even length");
344
+ }
345
+ const bytes = new Uint8Array(hex.length / 2);
346
+ for (let i = 0; i < hex.length; i += 2) {
347
+ bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
348
+ }
349
+ return bytes;
350
+ }
351
+ function bytesToHex2(bytes) {
352
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
353
+ }
354
+ function stringToBytes2(str) {
355
+ return new TextEncoder().encode(str);
356
+ }
357
+ function bytesToString2(bytes) {
358
+ return new TextDecoder().decode(bytes);
359
+ }
360
+ function concatBytes2(...arrays) {
361
+ const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
362
+ const result = new Uint8Array(totalLength);
363
+ let offset = 0;
364
+ for (const arr of arrays) {
365
+ result.set(arr, offset);
366
+ offset += arr.length;
367
+ }
368
+ return result;
369
+ }
370
+ function constantTimeEqual(a, b) {
371
+ if (a.length !== b.length) return false;
372
+ let result = 0;
373
+ for (let i = 0; i < a.length; i++) {
374
+ result |= a[i] ^ b[i];
375
+ }
376
+ return result === 0;
377
+ }
378
+ var init_utils = __esm({
379
+ "src/crypto/ecies/utils.ts"() {
380
+ "use strict";
381
+ }
382
+ });
383
+
384
+ // src/crypto/ecies/constants.ts
385
+ var CURVE, CIPHER, KDF, MAC, FORMAT;
386
+ var init_constants = __esm({
387
+ "src/crypto/ecies/constants.ts"() {
388
+ "use strict";
389
+ CURVE = {
390
+ /** The elliptic curve used (secp256k1 - same as Bitcoin/Ethereum) */
391
+ name: "secp256k1",
392
+ /** Private key length in bytes */
393
+ PRIVATE_KEY_LENGTH: 32,
394
+ /** Compressed public key length in bytes (0x02 or 0x03 prefix + 32 bytes) */
395
+ COMPRESSED_PUBLIC_KEY_LENGTH: 33,
396
+ /** Uncompressed public key length in bytes (0x04 prefix + 64 bytes) */
397
+ UNCOMPRESSED_PUBLIC_KEY_LENGTH: 65,
398
+ /** ECDH shared secret X coordinate length */
399
+ SHARED_SECRET_LENGTH: 32,
400
+ /** Public key prefixes */
401
+ PREFIX: {
402
+ /** Uncompressed public key prefix */
403
+ UNCOMPRESSED: 4,
404
+ /** Compressed public key prefix for even Y */
405
+ COMPRESSED_EVEN: 2,
406
+ /** Compressed public key prefix for odd Y */
407
+ COMPRESSED_ODD: 3
408
+ },
409
+ /** X coordinate starts at byte 1 (after prefix) */
410
+ X_COORDINATE_OFFSET: 1,
411
+ /** X coordinate ends at byte 33 (1 + 32) */
412
+ X_COORDINATE_END: 33
413
+ };
414
+ CIPHER = {
415
+ /** Cipher algorithm - must match eccrypto */
416
+ algorithm: "aes-256-cbc",
417
+ /** AES key length in bytes */
418
+ KEY_LENGTH: 32,
419
+ /** Initialization vector length in bytes */
420
+ IV_LENGTH: 16,
421
+ /** Block size for AES */
422
+ BLOCK_SIZE: 16
423
+ };
424
+ KDF = {
425
+ /** Hash algorithm for key derivation - must match eccrypto */
426
+ algorithm: "sha512",
427
+ /** Output length of SHA-512 in bytes */
428
+ OUTPUT_LENGTH: 64,
429
+ /** Encryption key slice (first 32 bytes of KDF output) */
430
+ ENCRYPTION_KEY_OFFSET: 0,
431
+ ENCRYPTION_KEY_LENGTH: 32,
432
+ /** MAC key slice (last 32 bytes of KDF output) */
433
+ MAC_KEY_OFFSET: 32,
434
+ MAC_KEY_LENGTH: 32
435
+ };
436
+ MAC = {
437
+ /** MAC algorithm - must match eccrypto */
438
+ algorithm: "sha256",
439
+ /** HMAC-SHA256 output length in bytes */
440
+ LENGTH: 32
441
+ };
442
+ FORMAT = {
443
+ /** Offsets for each component in serialized format */
444
+ IV_OFFSET: 0,
445
+ IV_LENGTH: CIPHER.IV_LENGTH,
446
+ /** Ephemeral public key (always uncompressed in eccrypto format) */
447
+ EPHEMERAL_KEY_OFFSET: CIPHER.IV_LENGTH,
448
+ EPHEMERAL_KEY_LENGTH: CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH,
449
+ /** Ciphertext starts after IV and ephemeral key */
450
+ CIPHERTEXT_OFFSET: CIPHER.IV_LENGTH + CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH,
451
+ /** MAC is always the last 32 bytes */
452
+ MAC_LENGTH: MAC.LENGTH,
453
+ /** Minimum size of encrypted data (IV + ephemKey + MAC, no ciphertext) */
454
+ MIN_ENCRYPTED_LENGTH: CIPHER.IV_LENGTH + CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH + MAC.LENGTH,
455
+ /**
456
+ * Helper to calculate total length of encrypted data
457
+ *
458
+ * @param ciphertextLength - Length of the ciphertext portion
459
+ * @returns Total length including all components
460
+ */
461
+ getTotalLength: (ciphertextLength) => CIPHER.IV_LENGTH + CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH + ciphertextLength + MAC.LENGTH
462
+ };
463
+ }
464
+ });
465
+
466
+ // src/crypto/ecies/interface.ts
467
+ function isECIESEncrypted(obj) {
468
+ if (!obj || typeof obj !== "object") return false;
469
+ const enc = obj;
470
+ const isUint8Array = (value) => {
471
+ return value instanceof Uint8Array || typeof Buffer !== "undefined" && Buffer.isBuffer(value);
472
+ };
473
+ return isUint8Array(enc.iv) && enc.iv.length === CIPHER.IV_LENGTH && isUint8Array(enc.ephemPublicKey) && (enc.ephemPublicKey.length === CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH || enc.ephemPublicKey.length === CURVE.COMPRESSED_PUBLIC_KEY_LENGTH) && isUint8Array(enc.ciphertext) && enc.ciphertext.length > 0 && isUint8Array(enc.mac) && enc.mac.length === MAC.LENGTH;
474
+ }
475
+ var ECIESError;
476
+ var init_interface = __esm({
477
+ "src/crypto/ecies/interface.ts"() {
478
+ "use strict";
479
+ init_constants();
480
+ ECIESError = class extends Error {
481
+ constructor(message, code, cause) {
482
+ super(message);
483
+ this.code = code;
484
+ this.cause = cause;
485
+ this.name = "ECIESError";
486
+ }
487
+ };
488
+ }
489
+ });
490
+
491
+ // src/crypto/ecies/base.ts
492
+ var BaseECIESUint8;
493
+ var init_base = __esm({
494
+ "src/crypto/ecies/base.ts"() {
495
+ "use strict";
496
+ init_interface();
497
+ init_constants();
498
+ init_utils();
499
+ BaseECIESUint8 = class _BaseECIESUint8 {
500
+ // Cache for validated public keys to avoid repeated validation
501
+ static validatedKeys = /* @__PURE__ */ new WeakMap();
502
+ /**
503
+ * Normalizes a public key to uncompressed format.
504
+ *
505
+ * @param publicKey - Public key in any format.
506
+ * @returns Uncompressed public key (65 bytes).
507
+ * @throws {ECIESError} If key format is invalid.
508
+ */
509
+ normalizePublicKey(publicKey) {
510
+ if (_BaseECIESUint8.validatedKeys.has(publicKey)) {
511
+ return publicKey;
512
+ }
513
+ if (publicKey.length === CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH) {
514
+ if (publicKey[0] !== CURVE.PREFIX.UNCOMPRESSED) {
515
+ throw new ECIESError(
516
+ "Invalid uncompressed public key prefix",
517
+ "INVALID_KEY"
518
+ );
519
+ }
520
+ if (!this.validatePublicKey(publicKey)) {
521
+ throw new ECIESError("Invalid public key", "INVALID_KEY");
522
+ }
523
+ _BaseECIESUint8.validatedKeys.set(publicKey, true);
524
+ return publicKey;
525
+ }
526
+ if (publicKey.length === CURVE.COMPRESSED_PUBLIC_KEY_LENGTH) {
527
+ const decompressed = this.decompressPublicKey(publicKey);
528
+ if (!decompressed) {
529
+ throw new ECIESError("Failed to decompress public key", "INVALID_KEY");
530
+ }
531
+ _BaseECIESUint8.validatedKeys.set(decompressed, true);
532
+ return decompressed;
533
+ }
534
+ throw new ECIESError(
535
+ `Invalid public key length: ${publicKey.length}`,
536
+ "INVALID_KEY"
537
+ );
538
+ }
539
+ /**
540
+ * Encrypts data using ECIES.
541
+ *
542
+ * @param publicKey - The recipient's public key (compressed or uncompressed)
543
+ * @param message - The data to encrypt
544
+ * @returns Promise resolving to encrypted data structure
545
+ */
546
+ async encrypt(publicKey, message) {
547
+ try {
548
+ if (!(publicKey instanceof Uint8Array)) {
549
+ throw new ECIESError("Public key must be a Uint8Array", "INVALID_KEY");
550
+ }
551
+ if (!(message instanceof Uint8Array)) {
552
+ throw new ECIESError(
553
+ "Message must be a Uint8Array",
554
+ "ENCRYPTION_FAILED"
555
+ );
556
+ }
557
+ if (publicKey.length === 0) {
558
+ throw new ECIESError("Public key cannot be empty", "INVALID_KEY");
559
+ }
560
+ const pubKey = this.normalizePublicKey(publicKey);
561
+ let ephemeralPrivateKey;
562
+ do {
563
+ ephemeralPrivateKey = this.generateRandomBytes(
564
+ CURVE.PRIVATE_KEY_LENGTH
565
+ );
566
+ } while (!this.verifyPrivateKey(ephemeralPrivateKey));
567
+ const ephemeralPublicKey = this.createPublicKey(
568
+ ephemeralPrivateKey,
569
+ false
570
+ );
571
+ if (!ephemeralPublicKey) {
572
+ throw new ECIESError(
573
+ "Failed to generate ephemeral public key",
574
+ "ENCRYPTION_FAILED"
575
+ );
576
+ }
577
+ const sharedSecret = this.performECDH(pubKey, ephemeralPrivateKey);
578
+ const kdf = this.sha512(sharedSecret);
579
+ const encryptionKey = kdf.slice(
580
+ KDF.ENCRYPTION_KEY_OFFSET,
581
+ KDF.ENCRYPTION_KEY_OFFSET + KDF.ENCRYPTION_KEY_LENGTH
582
+ );
583
+ const macKey = kdf.slice(
584
+ KDF.MAC_KEY_OFFSET,
585
+ KDF.MAC_KEY_OFFSET + KDF.MAC_KEY_LENGTH
586
+ );
587
+ const iv = this.generateRandomBytes(CIPHER.IV_LENGTH);
588
+ const ciphertext = await this.aesEncrypt(encryptionKey, iv, message);
589
+ const macData = concatBytes2(iv, ephemeralPublicKey, ciphertext);
590
+ const mac = this.hmacSha256(macKey, macData);
591
+ this.clearBuffer(ephemeralPrivateKey);
592
+ this.clearBuffer(sharedSecret);
593
+ this.clearBuffer(kdf);
594
+ return {
595
+ iv,
596
+ ephemPublicKey: ephemeralPublicKey,
597
+ ciphertext,
598
+ mac
599
+ };
600
+ } catch (error) {
601
+ if (error instanceof ECIESError) throw error;
602
+ throw new ECIESError(
603
+ `Encryption failed: ${error instanceof Error ? error.message : "Unknown error"}`,
604
+ "ENCRYPTION_FAILED",
605
+ error instanceof Error ? error : void 0
606
+ );
607
+ }
608
+ }
609
+ /**
610
+ * Decrypts ECIES encrypted data.
611
+ *
612
+ * @param privateKey - The recipient's private key (32 bytes)
613
+ * @param encrypted - The encrypted data structure from encrypt()
614
+ * @returns Promise resolving to the original plaintext
615
+ */
616
+ async decrypt(privateKey, encrypted) {
617
+ try {
618
+ if (!(privateKey instanceof Uint8Array)) {
619
+ throw new ECIESError("Private key must be a Uint8Array", "INVALID_KEY");
620
+ }
621
+ if (!isECIESEncrypted(encrypted)) {
622
+ throw new ECIESError(
623
+ "Invalid encrypted data structure",
624
+ "DECRYPTION_FAILED"
625
+ );
626
+ }
627
+ if (privateKey.length !== CURVE.PRIVATE_KEY_LENGTH) {
628
+ throw new ECIESError(
629
+ `Invalid private key length: ${privateKey.length}`,
630
+ "INVALID_KEY"
631
+ );
632
+ }
633
+ if (!this.verifyPrivateKey(privateKey)) {
634
+ throw new ECIESError("Invalid private key", "INVALID_KEY");
635
+ }
636
+ const ephemeralPublicKey = this.normalizePublicKey(
637
+ encrypted.ephemPublicKey
638
+ );
639
+ const sharedSecret = this.performECDH(ephemeralPublicKey, privateKey);
640
+ const kdf = this.sha512(sharedSecret);
641
+ const encryptionKey = kdf.slice(
642
+ KDF.ENCRYPTION_KEY_OFFSET,
643
+ KDF.ENCRYPTION_KEY_OFFSET + KDF.ENCRYPTION_KEY_LENGTH
644
+ );
645
+ const macKey = kdf.slice(
646
+ KDF.MAC_KEY_OFFSET,
647
+ KDF.MAC_KEY_OFFSET + KDF.MAC_KEY_LENGTH
648
+ );
649
+ const macData = concatBytes2(
650
+ encrypted.iv,
651
+ encrypted.ephemPublicKey,
652
+ encrypted.ciphertext
653
+ );
654
+ const expectedMac = this.hmacSha256(macKey, macData);
655
+ if (!constantTimeEqual(encrypted.mac, expectedMac)) {
656
+ throw new ECIESError("MAC verification failed", "MAC_MISMATCH");
657
+ }
658
+ const decrypted = await this.aesDecrypt(
659
+ encryptionKey,
660
+ encrypted.iv,
661
+ encrypted.ciphertext
662
+ );
663
+ this.clearBuffer(sharedSecret);
664
+ this.clearBuffer(kdf);
665
+ return decrypted;
666
+ } catch (error) {
667
+ if (error instanceof ECIESError) throw error;
668
+ throw new ECIESError(
669
+ `Decryption failed: ${error instanceof Error ? error.message : "Unknown error"}`,
670
+ "DECRYPTION_FAILED",
671
+ error instanceof Error ? error : void 0
672
+ );
673
+ }
674
+ }
675
+ /**
676
+ * Clears sensitive data from memory using multi-pass overwrite.
677
+ *
678
+ * @remarks
679
+ * Uses multiple passes with different patterns to make it harder
680
+ * for JIT compilers to optimize away the operation. While not
681
+ * guaranteed in JavaScript, this is a best-effort approach to
682
+ * clear sensitive data from memory.
683
+ *
684
+ * @param buffer - The buffer to clear
685
+ */
686
+ clearBuffer(buffer) {
687
+ if (buffer && buffer.length > 0) {
688
+ buffer.fill(0);
689
+ buffer.fill(255);
690
+ buffer.fill(170);
691
+ buffer.fill(0);
692
+ for (let i = 0; i < buffer.length; i++) {
693
+ buffer[i] = i & 255 ^ 90;
694
+ }
695
+ buffer.fill(0);
696
+ }
697
+ }
698
+ };
699
+ }
700
+ });
701
+
702
+ // src/crypto/ecies/browser.ts
703
+ var secp256k1, import_hmac, import_sha2, BrowserECIESUint8Provider;
704
+ var init_browser = __esm({
705
+ "src/crypto/ecies/browser.ts"() {
706
+ "use strict";
707
+ secp256k1 = __toESM(require("@noble/secp256k1"), 1);
708
+ init_base();
709
+ import_hmac = require("@noble/hashes/hmac");
710
+ import_sha2 = require("@noble/hashes/sha2");
711
+ BrowserECIESUint8Provider = class extends BaseECIESUint8 {
712
+ generateRandomBytes(length) {
713
+ const bytes = new Uint8Array(length);
714
+ crypto.getRandomValues(bytes);
715
+ return bytes;
716
+ }
717
+ verifyPrivateKey(privateKey) {
718
+ try {
719
+ return secp256k1.utils.isValidPrivateKey(privateKey);
720
+ } catch {
721
+ return false;
722
+ }
723
+ }
724
+ createPublicKey(privateKey, compressed) {
725
+ try {
726
+ return secp256k1.getPublicKey(privateKey, compressed);
727
+ } catch {
728
+ return null;
729
+ }
730
+ }
731
+ validatePublicKey(publicKey) {
732
+ try {
733
+ secp256k1.Point.fromHex(publicKey);
734
+ return true;
735
+ } catch {
736
+ return false;
737
+ }
738
+ }
739
+ decompressPublicKey(publicKey) {
740
+ try {
741
+ const point = secp256k1.Point.fromHex(publicKey);
742
+ return point.toRawBytes(false);
743
+ } catch {
744
+ return null;
745
+ }
746
+ }
747
+ performECDH(publicKey, privateKey) {
748
+ try {
749
+ const sharedPoint = secp256k1.getSharedSecret(
750
+ privateKey,
751
+ publicKey,
752
+ true
753
+ );
754
+ return sharedPoint.slice(1);
755
+ } catch (error) {
756
+ throw new Error(
757
+ `ECDH failed: ${error instanceof Error ? error.message : "Unknown error"}`
758
+ );
759
+ }
760
+ }
761
+ sha512(data) {
762
+ return (0, import_sha2.sha512)(data);
763
+ }
764
+ hmacSha256(key, data) {
765
+ return (0, import_hmac.hmac)(import_sha2.sha256, key, data);
766
+ }
767
+ async aesEncrypt(key, iv, plaintext) {
768
+ const cryptoKey = await crypto.subtle.importKey(
769
+ "raw",
770
+ key,
771
+ { name: "AES-CBC" },
772
+ false,
773
+ ["encrypt"]
774
+ );
775
+ const encrypted = await crypto.subtle.encrypt(
776
+ { name: "AES-CBC", iv },
777
+ cryptoKey,
778
+ plaintext
779
+ );
780
+ return new Uint8Array(encrypted);
781
+ }
782
+ async aesDecrypt(key, iv, ciphertext) {
783
+ const cryptoKey = await crypto.subtle.importKey(
784
+ "raw",
785
+ key,
786
+ { name: "AES-CBC" },
787
+ false,
788
+ ["decrypt"]
789
+ );
790
+ const decrypted = await crypto.subtle.decrypt(
791
+ { name: "AES-CBC", iv },
792
+ cryptoKey,
793
+ ciphertext
794
+ );
795
+ return new Uint8Array(decrypted);
796
+ }
797
+ };
798
+ }
799
+ });
800
+
100
801
  // src/platform/browser.ts
101
802
  var browser_exports = {};
102
803
  __export(browser_exports, {
103
- BrowserPlatformAdapter: () => BrowserPlatformAdapter,
104
- browserPlatformAdapter: () => browserPlatformAdapter
804
+ BrowserPlatformAdapter: () => BrowserPlatformAdapter
105
805
  });
106
- var openpgp, BrowserCryptoAdapter, BrowserPGPAdapter, BrowserHttpAdapter, BrowserCacheAdapter, BrowserPlatformAdapter, browserPlatformAdapter;
107
- var init_browser = __esm({
806
+ var secp256k12, getOpenPGP, BrowserCryptoAdapter, BrowserPGPAdapter, BrowserHttpAdapter, BrowserCacheAdapter, BrowserPlatformAdapter;
807
+ var init_browser2 = __esm({
108
808
  "src/platform/browser.ts"() {
109
809
  "use strict";
110
- openpgp = __toESM(require("openpgp"), 1);
111
- init_crypto_utils();
112
810
  init_pgp_utils();
113
811
  init_error_utils();
812
+ init_lazy_import();
813
+ init_WalletKeyEncryptionService();
814
+ init_crypto_utils();
815
+ init_utils();
816
+ secp256k12 = __toESM(require("@noble/secp256k1"), 1);
817
+ init_browser();
818
+ getOpenPGP = lazyImport(() => import("openpgp"));
114
819
  BrowserCryptoAdapter = class {
820
+ eciesProvider = new BrowserECIESUint8Provider();
821
+ walletKeyEncryptionService = new WalletKeyEncryptionService({
822
+ eciesProvider: this.eciesProvider
823
+ });
115
824
  async encryptWithPublicKey(data, publicKeyHex) {
116
825
  try {
117
- const eccrypto2 = await import("eccrypto-js");
118
- const publicKeyBuffer = Buffer.from(publicKeyHex, "hex");
119
- const encrypted = await eccrypto2.encrypt(
120
- publicKeyBuffer,
121
- Buffer.from(data, "utf8")
826
+ const publicKeyBytes = hexToBytes2(publicKeyHex);
827
+ const encrypted = await this.eciesProvider.encrypt(
828
+ publicKeyBytes,
829
+ stringToBytes2(data)
122
830
  );
123
- const result = Buffer.concat([
831
+ const result = concatBytes2(
124
832
  encrypted.iv,
125
833
  encrypted.ephemPublicKey,
126
834
  encrypted.ciphertext,
127
835
  encrypted.mac
128
- ]);
129
- return result.toString("hex");
836
+ );
837
+ return bytesToHex2(result);
130
838
  } catch (error) {
131
- throw new Error(`Encryption failed: ${error}`);
839
+ throw wrapCryptoError("encryptWithPublicKey", error);
132
840
  }
133
841
  }
134
842
  async decryptWithPrivateKey(encryptedData, privateKeyHex) {
135
843
  try {
136
- const eccrypto2 = await import("eccrypto-js");
137
- const privateKeyBuffer = processWalletPrivateKey(privateKeyHex);
138
- const encryptedBuffer = Buffer.from(encryptedData, "hex");
139
- const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
140
- const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
141
- const decryptedBuffer = await eccrypto2.decrypt(
142
- privateKeyBuffer,
143
- encryptedObj
844
+ const encryptedBytes = hexToBytes2(encryptedData);
845
+ const privateKeyBytes = hexToBytes2(privateKeyHex);
846
+ const encrypted = parseEncryptedDataBuffer(encryptedBytes);
847
+ const decrypted = await this.eciesProvider.decrypt(
848
+ privateKeyBytes,
849
+ encrypted
144
850
  );
145
- return decryptedBuffer.toString("utf8");
851
+ return bytesToString2(decrypted);
146
852
  } catch (error) {
147
- throw new Error(`Decryption failed: ${error}`);
853
+ throw wrapCryptoError("decryptWithPrivateKey", error);
148
854
  }
149
855
  }
150
- async generateKeyPair() {
856
+ async encryptWithWalletPublicKey(data, publicKey) {
151
857
  try {
152
- const eccrypto2 = await import("eccrypto-js");
153
- const privateKeyBytes = new Uint8Array(32);
154
- crypto.getRandomValues(privateKeyBytes);
155
- const privateKey = Buffer.from(privateKeyBytes);
156
- const publicKey = eccrypto2.getPublicCompressed(privateKey);
157
- return {
158
- privateKey: privateKey.toString("hex"),
159
- publicKey: publicKey.toString("hex")
160
- };
858
+ return await this.walletKeyEncryptionService.encryptWithWalletPublicKey(
859
+ data,
860
+ publicKey
861
+ );
161
862
  } catch (error) {
162
- throw wrapCryptoError("key generation", error);
863
+ throw wrapCryptoError("encryptWithWalletPublicKey", error);
163
864
  }
164
865
  }
165
- async encryptWithWalletPublicKey(data, publicKey) {
866
+ async decryptWithWalletPrivateKey(encryptedData, privateKey) {
166
867
  try {
167
- const eccrypto2 = await import("eccrypto-js");
168
- const uncompressedKey = processWalletPublicKey(publicKey);
169
- const encryptedBuffer = await eccrypto2.encrypt(
170
- uncompressedKey,
171
- Buffer.from(data)
868
+ return await this.walletKeyEncryptionService.decryptWithWalletPrivateKey(
869
+ encryptedData,
870
+ privateKey
172
871
  );
173
- const result = Buffer.concat([
174
- encryptedBuffer.iv,
175
- encryptedBuffer.ephemPublicKey,
176
- encryptedBuffer.ciphertext,
177
- encryptedBuffer.mac
178
- ]);
179
- return result.toString("hex");
180
872
  } catch (error) {
181
- throw wrapCryptoError("encrypt with wallet public key", error);
873
+ throw wrapCryptoError("decryptWithWalletPrivateKey", error);
182
874
  }
183
875
  }
184
- async decryptWithWalletPrivateKey(encryptedData, privateKey) {
876
+ async generateKeyPair() {
185
877
  try {
186
- const eccrypto2 = await import("eccrypto-js");
187
- const privateKeyBuffer = processWalletPrivateKey(privateKey);
188
- const encryptedBuffer = Buffer.from(encryptedData, "hex");
189
- const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
190
- const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
191
- const decryptedBuffer = await eccrypto2.decrypt(
192
- privateKeyBuffer,
193
- encryptedObj
194
- );
195
- return decryptedBuffer.toString("utf8");
878
+ const privateKeyBytes = secp256k12.utils.randomPrivateKey();
879
+ const publicKeyBytes = secp256k12.getPublicKey(privateKeyBytes, true);
880
+ return {
881
+ privateKey: bytesToHex2(privateKeyBytes),
882
+ publicKey: bytesToHex2(publicKeyBytes)
883
+ };
196
884
  } catch (error) {
197
- throw wrapCryptoError("decrypt with wallet private key", error);
885
+ throw wrapCryptoError("generateKeyPair", error);
198
886
  }
199
887
  }
200
888
  async encryptWithPassword(data, password) {
201
889
  try {
202
- const openpgp3 = await import("openpgp");
203
- const message = await openpgp3.createMessage({
204
- binary: data
205
- });
206
- const encrypted = await openpgp3.encrypt({
890
+ const openpgp = await getOpenPGP();
891
+ const message = await openpgp.createMessage({ binary: data });
892
+ const encrypted = await openpgp.encrypt({
207
893
  message,
208
894
  passwords: [password],
209
895
  format: "binary"
210
896
  });
211
- const response = new Response(encrypted);
212
- const arrayBuffer = await response.arrayBuffer();
213
- return new Uint8Array(arrayBuffer);
897
+ return new Uint8Array(encrypted);
214
898
  } catch (error) {
215
- throw new Error(`Failed to encrypt with password: ${error}`);
899
+ throw wrapCryptoError("encryptWithPassword", error);
216
900
  }
217
901
  }
218
902
  async decryptWithPassword(encryptedData, password) {
219
903
  try {
220
- const openpgp3 = await import("openpgp");
221
- const message = await openpgp3.readMessage({
904
+ const openpgp = await getOpenPGP();
905
+ const message = await openpgp.readMessage({
222
906
  binaryMessage: encryptedData
223
907
  });
224
- const { data: decrypted } = await openpgp3.decrypt({
908
+ const { data } = await openpgp.decrypt({
225
909
  message,
226
910
  passwords: [password],
227
911
  format: "binary"
228
912
  });
229
- return new Uint8Array(decrypted);
913
+ return new Uint8Array(data);
230
914
  } catch (error) {
231
- throw new Error(`Failed to decrypt with password: ${error}`);
915
+ throw wrapCryptoError("decryptWithPassword", error);
232
916
  }
233
917
  }
234
918
  };
235
919
  BrowserPGPAdapter = class {
236
920
  async encrypt(data, publicKeyArmored) {
237
921
  try {
922
+ const openpgp = await getOpenPGP();
238
923
  const publicKey = await openpgp.readKey({ armoredKey: publicKeyArmored });
239
924
  const encrypted = await openpgp.encrypt({
240
925
  message: await openpgp.createMessage({ text: data }),
@@ -250,6 +935,7 @@ var init_browser = __esm({
250
935
  }
251
936
  async decrypt(encryptedData, privateKeyArmored) {
252
937
  try {
938
+ const openpgp = await getOpenPGP();
253
939
  const privateKey = await openpgp.readPrivateKey({
254
940
  armoredKey: privateKeyArmored
255
941
  });
@@ -267,6 +953,7 @@ var init_browser = __esm({
267
953
  }
268
954
  async generateKeyPair(options) {
269
955
  try {
956
+ const openpgp = await getOpenPGP();
270
957
  const keyGenParams = getPGPKeyGenParams(options);
271
958
  const { privateKey, publicKey } = await openpgp.generateKey(keyGenParams);
272
959
  return { publicKey, privateKey };
@@ -277,9 +964,6 @@ var init_browser = __esm({
277
964
  };
278
965
  BrowserHttpAdapter = class {
279
966
  async fetch(url, options) {
280
- if (typeof fetch === "undefined") {
281
- throw new Error("Fetch API not available in this browser environment");
282
- }
283
967
  return fetch(url, options);
284
968
  }
285
969
  };
@@ -297,17 +981,19 @@ var init_browser = __esm({
297
981
  }
298
982
  set(key, value) {
299
983
  try {
300
- if (typeof sessionStorage !== "undefined") {
301
- sessionStorage.setItem(this.prefix + key, value);
984
+ if (typeof sessionStorage === "undefined") {
985
+ return;
302
986
  }
987
+ sessionStorage.setItem(this.prefix + key, value);
303
988
  } catch {
304
989
  }
305
990
  }
306
991
  delete(key) {
307
992
  try {
308
- if (typeof sessionStorage !== "undefined") {
309
- sessionStorage.removeItem(this.prefix + key);
993
+ if (typeof sessionStorage === "undefined") {
994
+ return;
310
995
  }
996
+ sessionStorage.removeItem(this.prefix + key);
311
997
  } catch {
312
998
  }
313
999
  }
@@ -316,30 +1002,25 @@ var init_browser = __esm({
316
1002
  if (typeof sessionStorage === "undefined") {
317
1003
  return;
318
1004
  }
319
- const keys = Object.keys(sessionStorage);
320
- for (const key of keys) {
321
- if (key.startsWith(this.prefix)) {
322
- sessionStorage.removeItem(key);
1005
+ const keysToRemove = [];
1006
+ for (let i = 0; i < sessionStorage.length; i++) {
1007
+ const key = sessionStorage.key(i);
1008
+ if (key?.startsWith(this.prefix)) {
1009
+ keysToRemove.push(key);
323
1010
  }
324
1011
  }
1012
+ keysToRemove.forEach((key) => sessionStorage.removeItem(key));
325
1013
  } catch {
326
1014
  }
327
1015
  }
328
1016
  };
329
1017
  BrowserPlatformAdapter = class {
330
- crypto;
331
- pgp;
332
- http;
333
- cache;
1018
+ crypto = new BrowserCryptoAdapter();
1019
+ pgp = new BrowserPGPAdapter();
1020
+ http = new BrowserHttpAdapter();
1021
+ cache = new BrowserCacheAdapter();
334
1022
  platform = "browser";
335
- constructor() {
336
- this.crypto = new BrowserCryptoAdapter();
337
- this.pgp = new BrowserPGPAdapter();
338
- this.http = new BrowserHttpAdapter();
339
- this.cache = new BrowserCacheAdapter();
340
- }
341
1023
  };
342
- browserPlatformAdapter = new BrowserPlatformAdapter();
343
1024
  }
344
1025
  });
345
1026
 
@@ -358,12 +1039,9 @@ __export(platform_exports, {
358
1039
  isPlatformSupported: () => isPlatformSupported
359
1040
  });
360
1041
  module.exports = __toCommonJS(platform_exports);
361
- init_browser();
1042
+ init_browser2();
362
1043
 
363
1044
  // src/platform/node.ts
364
- var import_crypto = require("crypto");
365
- var openpgp2 = __toESM(require("openpgp"), 1);
366
- init_crypto_utils();
367
1045
  init_pgp_utils();
368
1046
  init_error_utils();
369
1047
 
@@ -391,29 +1069,124 @@ async function streamToUint8Array(stream) {
391
1069
  }
392
1070
 
393
1071
  // src/platform/node.ts
394
- var eccrypto = null;
395
- async function getEccrypto() {
396
- if (!eccrypto) {
1072
+ init_lazy_import();
1073
+ init_WalletKeyEncryptionService();
1074
+ init_crypto_utils();
1075
+
1076
+ // src/crypto/ecies/node.ts
1077
+ var import_crypto = require("crypto");
1078
+ init_base();
1079
+ var secp256k13;
1080
+ try {
1081
+ secp256k13 = require("secp256k1");
1082
+ } catch {
1083
+ throw new Error(
1084
+ "Native secp256k1 module not found. Please install with: npm install secp256k1\nThis is required for optimal performance in Node.js environments."
1085
+ );
1086
+ }
1087
+ var NodeECIESUint8Provider = class extends BaseECIESUint8 {
1088
+ // Identity hash function for ECDH - returns raw X coordinate
1089
+ // CRITICAL: Must handle (x, y, output) signature correctly
1090
+ identityHashFn = (x, y, output) => {
1091
+ if (output && output.length >= 32) {
1092
+ output.set(x);
1093
+ return output;
1094
+ }
1095
+ return x;
1096
+ };
1097
+ generateRandomBytes(length) {
1098
+ return new Uint8Array((0, import_crypto.randomBytes)(length));
1099
+ }
1100
+ verifyPrivateKey(privateKey) {
1101
+ return secp256k13.privateKeyVerify(Buffer.from(privateKey)) === true;
1102
+ }
1103
+ createPublicKey(privateKey, compressed) {
397
1104
  try {
398
- const eccryptoLib = await import("eccrypto");
399
- eccrypto = {
400
- encrypt: eccryptoLib.encrypt,
401
- decrypt: eccryptoLib.decrypt,
402
- getPublicCompressed: eccryptoLib.getPublicCompressed
403
- };
1105
+ return new Uint8Array(
1106
+ secp256k13.publicKeyCreate(Buffer.from(privateKey), compressed)
1107
+ );
1108
+ } catch {
1109
+ return null;
1110
+ }
1111
+ }
1112
+ validatePublicKey(publicKey) {
1113
+ return secp256k13.publicKeyVerify(Buffer.from(publicKey)) === true;
1114
+ }
1115
+ decompressPublicKey(publicKey) {
1116
+ try {
1117
+ return new Uint8Array(
1118
+ secp256k13.publicKeyConvert(Buffer.from(publicKey), false)
1119
+ );
1120
+ } catch {
1121
+ return null;
1122
+ }
1123
+ }
1124
+ performECDH(publicKey, privateKey) {
1125
+ try {
1126
+ const output = Buffer.alloc(32);
1127
+ secp256k13.ecdh(
1128
+ Buffer.from(publicKey),
1129
+ Buffer.from(privateKey),
1130
+ { hashfn: this.identityHashFn },
1131
+ output
1132
+ );
1133
+ return new Uint8Array(output);
404
1134
  } catch (error) {
405
- throw new Error(`Failed to load eccrypto library: ${error}`);
1135
+ throw new Error(
1136
+ `ECDH failed: ${error instanceof Error ? error.message : "Unknown error"}`
1137
+ );
406
1138
  }
407
1139
  }
408
- return eccrypto;
409
- }
1140
+ sha512(data) {
1141
+ return new Uint8Array(
1142
+ (0, import_crypto.createHash)("sha512").update(Buffer.from(data)).digest()
1143
+ );
1144
+ }
1145
+ hmacSha256(key, data) {
1146
+ return new Uint8Array(
1147
+ (0, import_crypto.createHmac)("sha256", Buffer.from(key)).update(Buffer.from(data)).digest()
1148
+ );
1149
+ }
1150
+ async aesEncrypt(key, iv, plaintext) {
1151
+ const cipher = (0, import_crypto.createCipheriv)(
1152
+ "aes-256-cbc",
1153
+ Buffer.from(key),
1154
+ Buffer.from(iv)
1155
+ );
1156
+ const encrypted = Buffer.concat([
1157
+ cipher.update(Buffer.from(plaintext)),
1158
+ cipher.final()
1159
+ ]);
1160
+ return new Uint8Array(encrypted);
1161
+ }
1162
+ async aesDecrypt(key, iv, ciphertext) {
1163
+ const decipher = (0, import_crypto.createDecipheriv)(
1164
+ "aes-256-cbc",
1165
+ Buffer.from(key),
1166
+ Buffer.from(iv)
1167
+ );
1168
+ const decrypted = Buffer.concat([
1169
+ decipher.update(Buffer.from(ciphertext)),
1170
+ decipher.final()
1171
+ ]);
1172
+ return new Uint8Array(decrypted);
1173
+ }
1174
+ // No Buffer compatibility methods - Uint8Array only public API
1175
+ };
1176
+
1177
+ // src/platform/node.ts
1178
+ init_interface();
1179
+ var getOpenPGP2 = lazyImport(() => import("openpgp"));
410
1180
  var NodeCryptoAdapter = class {
1181
+ eciesProvider = new NodeECIESUint8Provider();
1182
+ walletKeyEncryptionService = new WalletKeyEncryptionService({
1183
+ eciesProvider: this.eciesProvider
1184
+ });
411
1185
  async encryptWithPublicKey(data, publicKeyHex) {
412
1186
  try {
413
- const eccryptoLib = await getEccrypto();
414
1187
  const publicKey = Buffer.from(publicKeyHex, "hex");
415
1188
  const message = Buffer.from(data, "utf8");
416
- const encrypted = await eccryptoLib.encrypt(publicKey, message);
1189
+ const encrypted = await this.eciesProvider.encrypt(publicKey, message);
417
1190
  const result = Buffer.concat([
418
1191
  encrypted.iv,
419
1192
  encrypted.ephemPublicKey,
@@ -422,30 +1195,54 @@ var NodeCryptoAdapter = class {
422
1195
  ]);
423
1196
  return result.toString("hex");
424
1197
  } catch (error) {
425
- throw new Error(`Encryption failed: ${error}`);
1198
+ if (error instanceof ECIESError) {
1199
+ throw error;
1200
+ }
1201
+ throw new ECIESError(
1202
+ `Encryption failed: ${error instanceof Error ? error.message : String(error)}`,
1203
+ "ENCRYPTION_FAILED",
1204
+ error instanceof Error ? error : void 0
1205
+ );
426
1206
  }
427
1207
  }
428
1208
  async decryptWithPrivateKey(encryptedData, privateKeyHex) {
429
1209
  try {
430
- const eccryptoLib = await getEccrypto();
431
1210
  const privateKeyBuffer = processWalletPrivateKey(privateKeyHex);
432
1211
  const encryptedBuffer = Buffer.from(encryptedData, "hex");
433
1212
  const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
434
- const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
435
- const decrypted = await eccryptoLib.decrypt(
1213
+ const encryptedObj = {
1214
+ iv,
1215
+ ephemPublicKey,
1216
+ ciphertext,
1217
+ mac
1218
+ };
1219
+ const decrypted = await this.eciesProvider.decrypt(
436
1220
  privateKeyBuffer,
437
1221
  encryptedObj
438
1222
  );
439
- return decrypted.toString("utf8");
1223
+ return new TextDecoder().decode(decrypted);
440
1224
  } catch (error) {
441
- throw new Error(`Decryption failed: ${error}`);
1225
+ if (error instanceof ECIESError) {
1226
+ throw error;
1227
+ }
1228
+ throw new ECIESError(
1229
+ `Decryption failed: ${error instanceof Error ? error.message : String(error)}`,
1230
+ "DECRYPTION_FAILED",
1231
+ error instanceof Error ? error : void 0
1232
+ );
442
1233
  }
443
1234
  }
444
1235
  async generateKeyPair() {
445
1236
  try {
446
- const eccryptoLib = await getEccrypto();
447
- const privateKey = (0, import_crypto.randomBytes)(32);
448
- const publicKey = eccryptoLib.getPublicCompressed(privateKey);
1237
+ const { randomBytes: randomBytes2 } = await import("crypto");
1238
+ const secp256k14 = await import("secp256k1");
1239
+ let privateKey;
1240
+ do {
1241
+ privateKey = randomBytes2(32);
1242
+ } while (!secp256k14.privateKeyVerify(privateKey));
1243
+ const publicKey = Buffer.from(
1244
+ secp256k14.publicKeyCreate(privateKey, true)
1245
+ );
449
1246
  return {
450
1247
  privateKey: privateKey.toString("hex"),
451
1248
  publicKey: publicKey.toString("hex")
@@ -456,45 +1253,31 @@ var NodeCryptoAdapter = class {
456
1253
  }
457
1254
  async encryptWithWalletPublicKey(data, publicKey) {
458
1255
  try {
459
- const eccryptoLib = await getEccrypto();
460
- const uncompressedKey = processWalletPublicKey(publicKey);
461
- const encrypted = await eccryptoLib.encrypt(
462
- uncompressedKey,
463
- Buffer.from(data)
1256
+ return await this.walletKeyEncryptionService.encryptWithWalletPublicKey(
1257
+ data,
1258
+ publicKey
464
1259
  );
465
- const result = Buffer.concat([
466
- encrypted.iv,
467
- encrypted.ephemPublicKey,
468
- encrypted.ciphertext,
469
- encrypted.mac
470
- ]);
471
- return result.toString("hex");
472
1260
  } catch (error) {
473
1261
  throw wrapCryptoError("encrypt with wallet public key", error);
474
1262
  }
475
1263
  }
476
1264
  async decryptWithWalletPrivateKey(encryptedData, privateKey) {
477
1265
  try {
478
- const eccryptoLib = await getEccrypto();
479
- const privateKeyBuffer = processWalletPrivateKey(privateKey);
480
- const encryptedBuffer = Buffer.from(encryptedData, "hex");
481
- const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
482
- const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
483
- const decryptedBuffer = await eccryptoLib.decrypt(
484
- privateKeyBuffer,
485
- encryptedObj
1266
+ return await this.walletKeyEncryptionService.decryptWithWalletPrivateKey(
1267
+ encryptedData,
1268
+ privateKey
486
1269
  );
487
- return decryptedBuffer.toString("utf8");
488
1270
  } catch (error) {
489
1271
  throw wrapCryptoError("decrypt with wallet private key", error);
490
1272
  }
491
1273
  }
492
1274
  async encryptWithPassword(data, password) {
493
1275
  try {
494
- const message = await openpgp2.createMessage({
1276
+ const openpgp = await getOpenPGP2();
1277
+ const message = await openpgp.createMessage({
495
1278
  binary: data
496
1279
  });
497
- const encrypted = await openpgp2.encrypt({
1280
+ const encrypted = await openpgp.encrypt({
498
1281
  message,
499
1282
  passwords: [password],
500
1283
  format: "binary"
@@ -514,10 +1297,11 @@ var NodeCryptoAdapter = class {
514
1297
  }
515
1298
  async decryptWithPassword(encryptedData, password) {
516
1299
  try {
517
- const message = await openpgp2.readMessage({
1300
+ const openpgp = await getOpenPGP2();
1301
+ const message = await openpgp.readMessage({
518
1302
  binaryMessage: encryptedData
519
1303
  });
520
- const { data: decrypted } = await openpgp2.decrypt({
1304
+ const { data: decrypted } = await openpgp.decrypt({
521
1305
  message,
522
1306
  passwords: [password],
523
1307
  format: "binary"
@@ -531,12 +1315,13 @@ var NodeCryptoAdapter = class {
531
1315
  var NodePGPAdapter = class {
532
1316
  async encrypt(data, publicKeyArmored) {
533
1317
  try {
534
- const publicKey = await openpgp2.readKey({ armoredKey: publicKeyArmored });
535
- const encrypted = await openpgp2.encrypt({
536
- message: await openpgp2.createMessage({ text: data }),
1318
+ const openpgp = await getOpenPGP2();
1319
+ const publicKey = await openpgp.readKey({ armoredKey: publicKeyArmored });
1320
+ const encrypted = await openpgp.encrypt({
1321
+ message: await openpgp.createMessage({ text: data }),
537
1322
  encryptionKeys: publicKey,
538
1323
  config: {
539
- preferredCompressionAlgorithm: openpgp2.enums.compression.zlib
1324
+ preferredCompressionAlgorithm: openpgp.enums.compression.zlib
540
1325
  }
541
1326
  });
542
1327
  return encrypted;
@@ -546,13 +1331,14 @@ var NodePGPAdapter = class {
546
1331
  }
547
1332
  async decrypt(encryptedData, privateKeyArmored) {
548
1333
  try {
549
- const privateKey = await openpgp2.readPrivateKey({
1334
+ const openpgp = await getOpenPGP2();
1335
+ const privateKey = await openpgp.readPrivateKey({
550
1336
  armoredKey: privateKeyArmored
551
1337
  });
552
- const message = await openpgp2.readMessage({
1338
+ const message = await openpgp.readMessage({
553
1339
  armoredMessage: encryptedData
554
1340
  });
555
- const { data: decrypted } = await openpgp2.decrypt({
1341
+ const { data: decrypted } = await openpgp.decrypt({
556
1342
  message,
557
1343
  decryptionKeys: privateKey
558
1344
  });
@@ -563,8 +1349,9 @@ var NodePGPAdapter = class {
563
1349
  }
564
1350
  async generateKeyPair(options) {
565
1351
  try {
1352
+ const openpgp = await getOpenPGP2();
566
1353
  const keyGenParams = getPGPKeyGenParams(options);
567
- const { privateKey, publicKey } = await openpgp2.generateKey(keyGenParams);
1354
+ const { privateKey, publicKey } = await openpgp.generateKey(keyGenParams);
568
1355
  return { publicKey, privateKey };
569
1356
  } catch (error) {
570
1357
  throw wrapCryptoError("PGP key generation", error);
@@ -645,7 +1432,7 @@ async function createPlatformAdapter() {
645
1432
  const { NodePlatformAdapter: NodePlatformAdapter2 } = await import(moduleName);
646
1433
  return new NodePlatformAdapter2();
647
1434
  } else {
648
- const { BrowserPlatformAdapter: BrowserPlatformAdapter2 } = await Promise.resolve().then(() => (init_browser(), browser_exports));
1435
+ const { BrowserPlatformAdapter: BrowserPlatformAdapter2 } = await Promise.resolve().then(() => (init_browser2(), browser_exports));
649
1436
  return new BrowserPlatformAdapter2();
650
1437
  }
651
1438
  } catch (error) {
@@ -666,7 +1453,7 @@ async function createPlatformAdapterFor(platformType) {
666
1453
  const { NodePlatformAdapter: NodePlatformAdapter2 } = await import(moduleName);
667
1454
  return new NodePlatformAdapter2();
668
1455
  } else {
669
- const { BrowserPlatformAdapter: BrowserPlatformAdapter2 } = await Promise.resolve().then(() => (init_browser(), browser_exports));
1456
+ const { BrowserPlatformAdapter: BrowserPlatformAdapter2 } = await Promise.resolve().then(() => (init_browser2(), browser_exports));
670
1457
  return new BrowserPlatformAdapter2();
671
1458
  }
672
1459
  } catch (error) {
@@ -693,7 +1480,7 @@ function getPlatformCapabilities() {
693
1480
  }
694
1481
 
695
1482
  // src/platform/browser-safe.ts
696
- init_browser();
1483
+ init_browser2();
697
1484
  async function createNodePlatformAdapter() {
698
1485
  if (typeof window !== "undefined") {
699
1486
  throw new Error(