@totemsdk/core 1.2.6 → 1.2.8

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 (96) hide show
  1. package/dist/MiniNumber.js +9 -1
  2. package/dist/canonical.d.ts +3 -0
  3. package/dist/canonical.js +22 -0
  4. package/dist/cjs/MiniNumber.d.ts +47 -0
  5. package/dist/cjs/MiniNumber.js +310 -0
  6. package/dist/cjs/Streamable.d.ts +268 -0
  7. package/dist/cjs/Streamable.js +439 -0
  8. package/dist/cjs/adapters/index.d.ts +190 -0
  9. package/dist/cjs/adapters/index.js +118 -0
  10. package/dist/cjs/adapters/types.d.ts +150 -0
  11. package/dist/cjs/adapters/types.js +81 -0
  12. package/dist/cjs/binio.d.ts +9 -0
  13. package/dist/cjs/binio.js +25 -0
  14. package/dist/cjs/bip39.d.ts +91 -0
  15. package/dist/cjs/bip39.js +434 -0
  16. package/dist/cjs/canonical.d.ts +3 -0
  17. package/dist/cjs/canonical.js +27 -0
  18. package/dist/cjs/derive.d.ts +2 -0
  19. package/dist/cjs/derive.js +13 -0
  20. package/dist/cjs/index.d.ts +49 -0
  21. package/dist/cjs/index.js +231 -0
  22. package/dist/cjs/javaStreamables.d.ts +254 -0
  23. package/dist/cjs/javaStreamables.js +391 -0
  24. package/dist/cjs/lease/LeaseMonitor.d.ts +44 -0
  25. package/dist/cjs/lease/LeaseMonitor.js +115 -0
  26. package/dist/cjs/lease/LeaseStore.d.ts +58 -0
  27. package/dist/cjs/lease/LeaseStore.js +151 -0
  28. package/dist/cjs/lease/WatermarkStore.d.ts +61 -0
  29. package/dist/cjs/lease/WatermarkStore.js +209 -0
  30. package/dist/cjs/lease/index.d.ts +14 -0
  31. package/dist/cjs/lease/index.js +22 -0
  32. package/dist/cjs/lease-client.d.ts +31 -0
  33. package/dist/cjs/lease-client.js +44 -0
  34. package/dist/cjs/legacy.d.ts +23 -0
  35. package/dist/cjs/legacy.js +163 -0
  36. package/dist/cjs/minima32.d.ts +18 -0
  37. package/dist/cjs/minima32.js +121 -0
  38. package/dist/cjs/minimaWireSerializer.d.ts +60 -0
  39. package/dist/cjs/minimaWireSerializer.js +77 -0
  40. package/dist/cjs/mmr.d.ts +157 -0
  41. package/dist/cjs/mmr.js +352 -0
  42. package/dist/cjs/mx.d.ts +1 -0
  43. package/dist/cjs/mx.js +10 -0
  44. package/dist/cjs/package.json +1 -0
  45. package/dist/cjs/params.d.ts +29 -0
  46. package/dist/cjs/params.js +20 -0
  47. package/dist/cjs/script.d.ts +7 -0
  48. package/dist/cjs/script.js +27 -0
  49. package/dist/cjs/scripts/contract-helpers.d.ts +252 -0
  50. package/dist/cjs/scripts/contract-helpers.js +407 -0
  51. package/dist/cjs/scripts/dapp-types.d.ts +119 -0
  52. package/dist/cjs/scripts/dapp-types.js +77 -0
  53. package/dist/cjs/scripts/index.d.ts +4 -0
  54. package/dist/cjs/scripts/index.js +38 -0
  55. package/dist/cjs/scripts/types.d.ts +81 -0
  56. package/dist/cjs/scripts/types.js +159 -0
  57. package/dist/cjs/scripts/witness-serializer.d.ts +29 -0
  58. package/dist/cjs/scripts/witness-serializer.js +306 -0
  59. package/dist/cjs/transaction.d.ts +106 -0
  60. package/dist/cjs/transaction.js +293 -0
  61. package/dist/cjs/treekey.d.ts +399 -0
  62. package/dist/cjs/treekey.js +827 -0
  63. package/dist/cjs/tx/TransactionLifecycle.d.ts +55 -0
  64. package/dist/cjs/tx/TransactionLifecycle.js +205 -0
  65. package/dist/cjs/tx/TransactionReceiptStore.d.ts +36 -0
  66. package/dist/cjs/tx/TransactionReceiptStore.js +93 -0
  67. package/dist/cjs/tx/TransactionService.d.ts +50 -0
  68. package/dist/cjs/tx/TransactionService.js +186 -0
  69. package/dist/cjs/tx/index.d.ts +13 -0
  70. package/dist/cjs/tx/index.js +20 -0
  71. package/dist/cjs/tx/types.d.ts +115 -0
  72. package/dist/cjs/tx/types.js +6 -0
  73. package/dist/cjs/util.d.ts +1 -0
  74. package/dist/cjs/util.js +5 -0
  75. package/dist/cjs/utils.d.ts +8 -0
  76. package/dist/cjs/utils.js +42 -0
  77. package/dist/cjs/verify.d.ts +18 -0
  78. package/dist/cjs/verify.js +174 -0
  79. package/dist/cjs/version.d.ts +12 -0
  80. package/dist/cjs/version.js +15 -0
  81. package/dist/cjs/wasm-sync.d.ts +71 -0
  82. package/dist/cjs/wasm-sync.js +97 -0
  83. package/dist/cjs/wots.d.ts +232 -0
  84. package/dist/cjs/wots.js +589 -0
  85. package/dist/index.d.ts +9 -3
  86. package/dist/index.js +25 -2
  87. package/dist/minimaWireSerializer.js +2 -2
  88. package/dist/mmr.js +1 -1
  89. package/dist/transaction.js +10 -10
  90. package/dist/treekey.js +14 -0
  91. package/dist/wasm-sync.d.ts +2 -2
  92. package/dist/wasm-sync.js +3 -1
  93. package/dist/wots.d.ts +1 -1
  94. package/package.json +84 -45
  95. package/dist/wasm-bridge.d.ts +0 -54
  96. package/dist/wasm-bridge.js +0 -303
@@ -0,0 +1,589 @@
1
+ "use strict";
2
+ /**
3
+ * WOTS Implementation - BouncyCastle Compatible
4
+ *
5
+ * This implementation matches BouncyCastle's WinternitzOTSignature exactly,
6
+ * which is used by Minima's Winternitz.java class.
7
+ *
8
+ * Key differences from standard WOTS (Winternitz):
9
+ * - w=8 means 8 BITS per digit (not base-8), so each byte is one digit (0-255)
10
+ * - Stateful PRNG (GMSSRandom) for chain seed derivation, not stateless H(i||seed)
11
+ * - 34 total chains (32 message + 2 checksum), not 89
12
+ * - Each chain hashed up to 255 times (2^8 - 1)
13
+ *
14
+ * Source: org.bouncycastle.pqc.crypto.gmss.util.{WinternitzOTSignature, WinternitzOTSVerify, GMSSRandom}
15
+ */
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.GMSSRandom = exports.h = exports.u32be = exports.u16be = exports.concatBytes = exports.fromHex = exports.hex = exports.F = void 0;
18
+ exports.setWotsLogger = setWotsLogger;
19
+ exports.disableWotsLogger = disableWotsLogger;
20
+ exports.isWotsDebugEnabled = isWotsDebugEnabled;
21
+ exports.assert32 = assert32;
22
+ exports.getLog = getLog;
23
+ exports.expandPrivateKey = expandPrivateKey;
24
+ exports.toWinternitzDigits = toWinternitzDigits;
25
+ exports.baseWWithChecksum = baseWWithChecksum;
26
+ exports.hashChain = hashChain;
27
+ exports.deriveIndexedSeed = deriveIndexedSeed;
28
+ exports.derivePKdigest = derivePKdigest;
29
+ exports.deriveFullPublicKey = deriveFullPublicKey;
30
+ exports.wotsKeypairFromSeed = wotsKeypairFromSeed;
31
+ exports.wotsSign = wotsSign;
32
+ exports.wotsSignLegacy = wotsSignLegacy;
33
+ exports.wotsPkFromSig = wotsPkFromSig;
34
+ exports.wotsVerify = wotsVerify;
35
+ exports.wotsVerifyDigest = wotsVerifyDigest;
36
+ exports.wotsPublicKeyFromSeed = wotsPublicKeyFromSeed;
37
+ exports.prfChainSeed = prfChainSeed;
38
+ const wasm_sync_js_1 = require("./wasm-sync.js");
39
+ const params_js_1 = require("./params.js");
40
+ const javaStreamables_js_1 = require("./javaStreamables.js");
41
+ const index_js_1 = require("./adapters/index.js");
42
+ // Module-level debug logger - can be set externally for parity testing
43
+ let wotsLogger = new index_js_1.NoopLogger();
44
+ let wotsDebugEnabled = false;
45
+ /**
46
+ * Enable WOTS debug logging with a custom logger
47
+ * Use this for parity testing to capture all intermediate values
48
+ *
49
+ * WARNING: Debug logging outputs sensitive cryptographic material including
50
+ * private key chains and seeds. NEVER enable in production builds.
51
+ * This is intended for development/testing parity verification only.
52
+ */
53
+ function setWotsLogger(logger) {
54
+ wotsLogger = logger;
55
+ wotsDebugEnabled = true;
56
+ }
57
+ /**
58
+ * Disable WOTS debug logging
59
+ */
60
+ function disableWotsLogger() {
61
+ wotsLogger = new index_js_1.NoopLogger();
62
+ wotsDebugEnabled = false;
63
+ }
64
+ /**
65
+ * Check if WOTS debug logging is enabled
66
+ */
67
+ function isWotsDebugEnabled() {
68
+ return wotsDebugEnabled;
69
+ }
70
+ // === Canonical helpers ===
71
+ const F = (x) => (0, wasm_sync_js_1.sha3_256)(x);
72
+ exports.F = F;
73
+ const hex = (u) => {
74
+ let s = '';
75
+ for (let i = 0; i < u.length; i++)
76
+ s += u[i].toString(16).padStart(2, '0');
77
+ return s;
78
+ };
79
+ exports.hex = hex;
80
+ const fromHex = (h) => {
81
+ const s = h.replace(/^0x/, '');
82
+ const out = new Uint8Array(s.length >> 1);
83
+ for (let i = 0; i < out.length; i++)
84
+ out[i] = parseInt(s.slice(i * 2, i * 2 + 2), 16);
85
+ return out;
86
+ };
87
+ exports.fromHex = fromHex;
88
+ const concatBytes = (...arrs) => {
89
+ const len = arrs.reduce((n, a) => n + a.length, 0);
90
+ const out = new Uint8Array(len);
91
+ let o = 0;
92
+ for (const a of arrs) {
93
+ out.set(a, o);
94
+ o += a.length;
95
+ }
96
+ return out;
97
+ };
98
+ exports.concatBytes = concatBytes;
99
+ const u16be = (n) => new Uint8Array([(n >>> 8) & 0xff, n & 0xff]);
100
+ exports.u16be = u16be;
101
+ const u32be = (n) => new Uint8Array([(n >>> 24) & 255, (n >>> 16) & 255, (n >>> 8) & 255, n & 255]);
102
+ exports.u32be = u32be;
103
+ function assert32(u, label = 'value') {
104
+ if (!(u instanceof Uint8Array))
105
+ throw new Error(`${label} must be a Uint8Array`);
106
+ if (u.length !== 32)
107
+ throw new Error(`${label} must be exactly 32 bytes; got ${u.length}`);
108
+ }
109
+ // Legacy aliases
110
+ const u8 = (len) => new Uint8Array(len);
111
+ exports.h = exports.F;
112
+ const concat = exports.concatBytes;
113
+ const defaultParamSet = (0, params_js_1.getParamSet)();
114
+ /**
115
+ * GMSSRandom - BouncyCastle's stateful PRNG for WOTS chain seed derivation
116
+ *
117
+ * Algorithm from GMSSRandom.java:
118
+ * rand = H(state)
119
+ * state = state + rand + 1 (byte-wise addition with carry)
120
+ * return rand
121
+ *
122
+ * The state is MUTATED in place after each call.
123
+ */
124
+ class GMSSRandom {
125
+ /**
126
+ * Generate next random value and update state
127
+ *
128
+ * @param state - 32-byte state array (MUTATED in place)
129
+ * @returns 32-byte random value
130
+ */
131
+ static nextSeed(state) {
132
+ assert32(state, 'state');
133
+ // rand = H(state)
134
+ const rand = (0, exports.F)(state);
135
+ // state = state + rand (byte-wise addition with carry, little-endian)
136
+ GMSSRandom.addByteArrays(state, rand);
137
+ // state = state + 1
138
+ GMSSRandom.addOne(state);
139
+ return rand;
140
+ }
141
+ /**
142
+ * Add two byte arrays: a = a + b (little-endian, with carry)
143
+ * Matches GMSSRandom.addByteArrays()
144
+ */
145
+ static addByteArrays(a, b) {
146
+ let overflow = 0;
147
+ for (let i = 0; i < a.length; i++) {
148
+ const temp = (a[i] & 0xff) + (b[i] & 0xff) + overflow;
149
+ a[i] = temp & 0xff;
150
+ overflow = temp >>> 8;
151
+ }
152
+ }
153
+ /**
154
+ * Add one to byte array: a = a + 1 (little-endian, with carry)
155
+ * Matches GMSSRandom.addOne()
156
+ */
157
+ static addOne(a) {
158
+ let overflow = 1;
159
+ for (let i = 0; i < a.length; i++) {
160
+ const temp = (a[i] & 0xff) + overflow;
161
+ a[i] = temp & 0xff;
162
+ overflow = temp >>> 8;
163
+ if (overflow === 0)
164
+ break;
165
+ }
166
+ }
167
+ }
168
+ exports.GMSSRandom = GMSSRandom;
169
+ /**
170
+ * getLog - Calculate ceil(log2(x))
171
+ *
172
+ * Matches WinternitzOTSignature.getLog():
173
+ * int log = 1;
174
+ * int i = 2;
175
+ * while (i < intValue) { i <<= 1; log++; }
176
+ * return log;
177
+ */
178
+ function getLog(intValue) {
179
+ let log = 1;
180
+ let i = 2;
181
+ while (i < intValue) {
182
+ i <<= 1;
183
+ log++;
184
+ }
185
+ return log;
186
+ }
187
+ /**
188
+ * Expand master seed into L private key chains using GMSSRandom
189
+ *
190
+ * Matches WinternitzOTSignature constructor:
191
+ * byte[] dummy = new byte[mdsize];
192
+ * System.arraycopy(seed0, 0, dummy, 0, dummy.length);
193
+ * for (int i = 0; i < keysize; i++) {
194
+ * privateKeyOTS[i] = gmssRandom.nextSeed(dummy);
195
+ * }
196
+ */
197
+ function expandPrivateKey(seed, ps = (0, params_js_1.getParamSet)()) {
198
+ assert32(seed, 'seed');
199
+ // Copy seed to mutable state
200
+ const state = new Uint8Array(seed);
201
+ if (wotsDebugEnabled) {
202
+ wotsLogger.debug(`[expandPrivateKey] Input seed: ${(0, exports.hex)(seed).substring(0, 64)}...`);
203
+ wotsLogger.debug(`[expandPrivateKey] Initial state: ${(0, exports.hex)(state).substring(0, 64)}...`);
204
+ }
205
+ // Generate L chain seeds using stateful PRNG
206
+ const privateKeys = [];
207
+ for (let i = 0; i < ps.L; i++) {
208
+ const pk = GMSSRandom.nextSeed(state);
209
+ privateKeys.push(pk);
210
+ // Log first few private keys for debugging
211
+ if (wotsDebugEnabled && i < 3) {
212
+ wotsLogger.debug(`[expandPrivateKey] pk[${i}]: ${(0, exports.hex)(pk)}`);
213
+ wotsLogger.debug(`[expandPrivateKey] state after pk[${i}]: ${(0, exports.hex)(state).substring(0, 32)}...`);
214
+ }
215
+ }
216
+ if (wotsDebugEnabled) {
217
+ wotsLogger.debug(`[expandPrivateKey] Generated ${privateKeys.length} private keys`);
218
+ wotsLogger.debug(`[expandPrivateKey] pk[33] (last): ${(0, exports.hex)(privateKeys[33])}`);
219
+ }
220
+ return privateKeys;
221
+ }
222
+ /**
223
+ * Convert message hash to Winternitz digits with checksum
224
+ *
225
+ * For w=8 (8 bits per digit), since 8 % 8 == 0:
226
+ * - Each byte of the hash IS one digit (0-255)
227
+ * - messagesize = 32 digits
228
+ * - checksum = (messagesize << w) - sum = 8192 - sum
229
+ * - checksumsize = 14 bits, extracted as 2 digits
230
+ *
231
+ * Matches WinternitzOTSignature.getSignature() for w=8 case
232
+ */
233
+ function toWinternitzDigits(hash32, ps = (0, params_js_1.getParamSet)()) {
234
+ assert32(hash32, 'hash');
235
+ if (ps.w !== 8) {
236
+ throw new Error(`Only w=8 is supported. Got w=${ps.w}`);
237
+ }
238
+ // For w=8: each byte IS a digit (0-255)
239
+ // d = 8 / w = 1 digit per byte
240
+ // k = (1 << w) - 1 = 255
241
+ const digits = [];
242
+ let c = 0; // checksum accumulator
243
+ for (let i = 0; i < hash32.length; i++) {
244
+ const digit = hash32[i] & 0xff;
245
+ digits.push(digit);
246
+ c += digit;
247
+ }
248
+ const digitSum = c;
249
+ // Checksum = (messagesize << w) - c = (32 << 8) - c = 8192 - c
250
+ c = (ps.messageSize << ps.w) - c;
251
+ const checksumBeforeExtract = c;
252
+ // Extract checksum digits: 2 digits, each 0-255
253
+ // checksumsize = 14 bits, iterate by w=8 bits
254
+ const checksumDigits = [];
255
+ const k = ps.maxDigit; // 255
256
+ for (let i = 0; i < ps.checksumSize; i += ps.w) {
257
+ checksumDigits.push(c & k);
258
+ c >>>= ps.w;
259
+ }
260
+ if (wotsDebugEnabled) {
261
+ wotsLogger.debug(`[toWinternitzDigits] Input hash: ${(0, exports.hex)(hash32)}`);
262
+ wotsLogger.debug(`[toWinternitzDigits] First 5 message digits: [${digits.slice(0, 5).join(', ')}]`);
263
+ wotsLogger.debug(`[toWinternitzDigits] Last 5 message digits: [${digits.slice(-5).join(', ')}]`);
264
+ wotsLogger.debug(`[toWinternitzDigits] Digit sum: ${digitSum}`);
265
+ wotsLogger.debug(`[toWinternitzDigits] Checksum formula: (${ps.messageSize} << ${ps.w}) - ${digitSum} = ${checksumBeforeExtract}`);
266
+ wotsLogger.debug(`[toWinternitzDigits] Checksum digits: [${checksumDigits.join(', ')}]`);
267
+ wotsLogger.debug(`[toWinternitzDigits] Total digits: ${digits.length + checksumDigits.length} (expected L=${ps.L})`);
268
+ }
269
+ return {
270
+ digits,
271
+ checksumDigits,
272
+ total: digits.length + checksumDigits.length
273
+ };
274
+ }
275
+ /**
276
+ * Decompose digest into base-w digits + checksum
277
+ * Returns flat array of all L digits
278
+ */
279
+ function baseWWithChecksum(msgHash, paramSet) {
280
+ const ps = paramSet || defaultParamSet;
281
+ const { digits, checksumDigits } = toWinternitzDigits(msgHash, ps);
282
+ const result = digits.concat(checksumDigits);
283
+ if (result.length !== ps.L) {
284
+ throw new Error(`Invalid digit length: expected ${ps.L}, got ${result.length}`);
285
+ }
286
+ return result;
287
+ }
288
+ /**
289
+ * Hash a value k times
290
+ *
291
+ * Matches WinternitzOTSignature.hashPrivateKeyBlock():
292
+ * - If rounds < 1: return input unchanged
293
+ * - Otherwise: hash `rounds` times
294
+ */
295
+ function hashChain(x, rounds) {
296
+ if (rounds < 1) {
297
+ return new Uint8Array(x);
298
+ }
299
+ let result = (0, exports.F)(x);
300
+ for (let i = 1; i < rounds; i++) {
301
+ result = (0, exports.F)(result);
302
+ }
303
+ return result;
304
+ }
305
+ /**
306
+ * Derive unique seed for a specific key index
307
+ *
308
+ * DEPRECATED: Use deriveChainSeedJava for Java parity.
309
+ * This function is preserved for backward compatibility only.
310
+ *
311
+ * The correct derivation matching Minima's TreeKeyNode.java:
312
+ * MiniData seed = Crypto.getInstance().hashAllObjects(new MiniNumber(i), zPrivateSeed);
313
+ *
314
+ * This old implementation used H(seed || u32be(i)) which is NOT Java compatible.
315
+ * @deprecated Use deriveChainSeedJava from javaStreamables.ts
316
+ */
317
+ function deriveIndexedSeed(seed, keyIndex) {
318
+ assert32(seed, 'seed');
319
+ // Use Java-compatible derivation: hashAllObjects(MiniNumber(i), MiniData(seed))
320
+ const result = (0, javaStreamables_js_1.deriveChainSeedJava)(seed, keyIndex);
321
+ if (wotsDebugEnabled) {
322
+ wotsLogger.debug(`[deriveIndexedSeed] seed=${(0, exports.hex)(seed).substring(0, 32)}..., keyIndex=${keyIndex} => ${(0, exports.hex)(result)}`);
323
+ }
324
+ return result;
325
+ }
326
+ /**
327
+ * Derive WOTS public key digest from seed and key index
328
+ *
329
+ * The key index is mixed into the seed first (deriveIndexedSeed),
330
+ * then expanded using GMSSRandom to get unique chain seeds.
331
+ *
332
+ * Matches WinternitzOTSignature.getPublicKey():
333
+ * int rounds = (1 << w) - 1; // 255 for w=8
334
+ * for (int i = 0; i < keysize; i++) {
335
+ * hashPrivateKeyBlock(i, rounds, buf, pos);
336
+ * }
337
+ * return H(buf);
338
+ */
339
+ function derivePKdigest(seed, i, ps = (0, params_js_1.getParamSet)()) {
340
+ assert32(seed, 'seed');
341
+ // Derive unique seed for this key index
342
+ const indexedSeed = deriveIndexedSeed(seed, i);
343
+ // Expand indexed seed into private keys
344
+ const privateKeys = expandPrivateKey(indexedSeed, ps);
345
+ // Hash each chain 255 times to get chain tops
346
+ const rounds = ps.maxDigit; // 255
347
+ const buf = new Uint8Array(ps.L * 32);
348
+ for (let j = 0; j < ps.L; j++) {
349
+ const top = hashChain(privateKeys[j], rounds);
350
+ buf.set(top, j * 32);
351
+ }
352
+ // Return H(all chain tops)
353
+ return (0, exports.F)(buf);
354
+ }
355
+ /**
356
+ * Derive full WOTS public key (L × 32 bytes) without final hash
357
+ *
358
+ * Returns the concatenation of all chain tops BEFORE hashing.
359
+ * Required by Minima's SignatureProof which expects the full public key.
360
+ */
361
+ function deriveFullPublicKey(seed, i, ps = (0, params_js_1.getParamSet)()) {
362
+ assert32(seed, 'seed');
363
+ if (wotsDebugEnabled) {
364
+ wotsLogger.debug(`[deriveFullPublicKey] ========== PK DERIVATION START ==========`);
365
+ wotsLogger.debug(`[deriveFullPublicKey] Master seed: ${(0, exports.hex)(seed).substring(0, 32)}..., keyIndex: ${i}`);
366
+ }
367
+ // Derive unique seed for this key index
368
+ const indexedSeed = deriveIndexedSeed(seed, i);
369
+ if (wotsDebugEnabled) {
370
+ wotsLogger.debug(`[deriveFullPublicKey] Indexed seed: ${(0, exports.hex)(indexedSeed)}`);
371
+ }
372
+ const privateKeys = expandPrivateKey(indexedSeed, ps);
373
+ const rounds = ps.maxDigit; // 255
374
+ const buf = new Uint8Array(ps.L * 32);
375
+ for (let j = 0; j < ps.L; j++) {
376
+ const top = hashChain(privateKeys[j], rounds);
377
+ buf.set(top, j * 32);
378
+ // Log first few chain tops for debugging
379
+ if (wotsDebugEnabled && j < 3) {
380
+ wotsLogger.debug(`[deriveFullPublicKey] chain[${j}]: pk=${(0, exports.hex)(privateKeys[j]).substring(0, 16)}... rounds=${rounds} => top=${(0, exports.hex)(top).substring(0, 16)}...`);
381
+ }
382
+ }
383
+ if (wotsDebugEnabled) {
384
+ wotsLogger.debug(`[deriveFullPublicKey] Full public key (${buf.length}B): ${(0, exports.hex)(buf).substring(0, 64)}...${(0, exports.hex)(buf).substring((0, exports.hex)(buf).length - 32)}`);
385
+ wotsLogger.debug(`[deriveFullPublicKey] ========== PK DERIVATION END ==========`);
386
+ }
387
+ return buf; // L * 32 = 1088 bytes
388
+ }
389
+ function wotsKeypairFromSeed(seed, index, paramSet) {
390
+ assert32(seed, 'seed');
391
+ const ps = paramSet || defaultParamSet;
392
+ const pkDigest = derivePKdigest(seed, index, ps);
393
+ return { seed, index, pk: pkDigest };
394
+ }
395
+ /**
396
+ * Sign a message using WOTS
397
+ *
398
+ * Matches Java's WinternitzOTSignature.getSignature():
399
+ * 1. Hash the message internally: hashedMsg = SHA3-256(message)
400
+ * 2. For each digit d[i]: sig[i] = hash(privateKey[i], d[i] times)
401
+ *
402
+ * IMPORTANT: This function hashes the message internally to match Java/BouncyCastle.
403
+ * Callers pass RAW 32-byte data (tx digest, child root), NOT pre-hashed!
404
+ *
405
+ * @param seed - 32-byte master seed
406
+ * @param i - Key index
407
+ * @param message - Raw 32-byte message (will be hashed internally)
408
+ * @param ps - WOTS parameter set (default: minima)
409
+ * @returns Flat signature (L × 32 = 1088 bytes)
410
+ */
411
+ function wotsSign(seed, i, message, ps = (0, params_js_1.getParamSet)()) {
412
+ assert32(seed, 'seed');
413
+ assert32(message, 'message');
414
+ if (wotsDebugEnabled) {
415
+ wotsLogger.debug(`[wotsSign] ========== WOTS SIGN START ==========`);
416
+ wotsLogger.debug(`[wotsSign] Master seed: ${(0, exports.hex)(seed)}`);
417
+ wotsLogger.debug(`[wotsSign] Key index: ${i}`);
418
+ wotsLogger.debug(`[wotsSign] Message (raw): ${(0, exports.hex)(message)}`);
419
+ }
420
+ // Derive unique seed for this key index
421
+ const indexedSeed = deriveIndexedSeed(seed, i);
422
+ if (wotsDebugEnabled) {
423
+ wotsLogger.debug(`[wotsSign] Indexed seed (after deriveIndexedSeed): ${(0, exports.hex)(indexedSeed)}`);
424
+ }
425
+ const privateKeys = expandPrivateKey(indexedSeed, ps);
426
+ // CRITICAL: Hash the message internally to match Java/BouncyCastle Winternitz behavior
427
+ // Java's WinternitzOTSignature.getSignature() always hashes the message first
428
+ // Callers pass RAW 32-byte data (tx digest, child root), NOT pre-hashed!
429
+ const hashedMsg = (0, exports.F)(message);
430
+ const { digits, checksumDigits } = toWinternitzDigits(hashedMsg, ps);
431
+ const allDigits = digits.concat(checksumDigits);
432
+ if (allDigits.length !== ps.L) {
433
+ throw new Error(`Digit length mismatch: got ${allDigits.length}, want ${ps.L}`);
434
+ }
435
+ if (wotsDebugEnabled) {
436
+ wotsLogger.debug(`[wotsSign] All ${allDigits.length} digits: [${allDigits.join(', ')}]`);
437
+ }
438
+ const out = new Uint8Array(ps.L * 32);
439
+ for (let j = 0; j < ps.L; j++) {
440
+ const rounds = allDigits[j];
441
+ const sigPart = hashChain(privateKeys[j], rounds);
442
+ out.set(sigPart, j * 32);
443
+ // Log first few and last signature chains for debugging
444
+ if (wotsDebugEnabled && (j < 3 || j >= ps.L - 2)) {
445
+ wotsLogger.debug(`[wotsSign] chain[${j}]: pk=${(0, exports.hex)(privateKeys[j]).substring(0, 16)}... rounds=${rounds} => sig=${(0, exports.hex)(sigPart).substring(0, 16)}...`);
446
+ }
447
+ }
448
+ if (wotsDebugEnabled) {
449
+ wotsLogger.debug(`[wotsSign] Signature output (${out.length} bytes): ${(0, exports.hex)(out).substring(0, 64)}...${(0, exports.hex)(out).substring((0, exports.hex)(out).length - 64)}`);
450
+ wotsLogger.debug(`[wotsSign] ========== WOTS SIGN END ==========`);
451
+ }
452
+ return out;
453
+ }
454
+ /**
455
+ * Legacy wrapper returning structured signature
456
+ */
457
+ function wotsSignLegacy(msgHash, seed, index, paramSet) {
458
+ const ps = paramSet || (0, params_js_1.getParamSet)();
459
+ const sig = wotsSign(seed, index, msgHash, ps);
460
+ const chunks = [];
461
+ for (let i = 0; i < ps.L; i++) {
462
+ chunks.push(sig.subarray(i * 32, (i + 1) * 32));
463
+ }
464
+ return { index, w: ps.w, sig: chunks };
465
+ }
466
+ /**
467
+ * Recover public key from signature
468
+ *
469
+ * Matches WinternitzOTSVerify.Verify():
470
+ * 1. Hash the message: hashedMsg = SHA3-256(message)
471
+ * 2. for each digit d[i]:
472
+ * top[i] = hash(sig[i], (255 - d[i]) times)
473
+ * 3. return H(concat(tops))
474
+ *
475
+ * CRITICAL: This function hashes the message internally to match Java/BouncyCastle
476
+ * Winternitz behavior. Both wotsSign and wotsPkFromSig hash internally for parity.
477
+ */
478
+ function wotsPkFromSig(message, signature, paramSet) {
479
+ const ps = paramSet || defaultParamSet;
480
+ // CRITICAL: Hash the message internally to match Java/BouncyCastle Winternitz behavior
481
+ const hashedMsg = (0, exports.F)(message);
482
+ const allDigits = baseWWithChecksum(hashedMsg, ps);
483
+ if (signature.sig.length !== ps.L) {
484
+ throw new Error(`Wrong signature length: expected ${ps.L}, got ${signature.sig.length}`);
485
+ }
486
+ const buf = new Uint8Array(ps.L * 32);
487
+ for (let i = 0; i < ps.L; i++) {
488
+ const stepsUp = ps.maxDigit - allDigits[i]; // 255 - d[i]
489
+ const top = hashChain(signature.sig[i], stepsUp);
490
+ buf.set(top, i * 32);
491
+ }
492
+ return (0, exports.F)(buf);
493
+ }
494
+ /**
495
+ * Verify WOTS signature against a FULL 1088-byte public key
496
+ *
497
+ * Matches Java's Winternitz.verify():
498
+ * 1. Hash the message internally: hashedMsg = SHA3-256(message)
499
+ * 2. Recover FULL public key from signature using hashedMsg (1088 bytes)
500
+ * 3. Compare FULL reconstructed key to expected FULL public key
501
+ *
502
+ * CRITICAL: Java's Winternitz.verify() compares the FULL 1088-byte reconstructed
503
+ * public key against the FULL 1088-byte stored public key, NOT a 32-byte digest!
504
+ *
505
+ * IMPORTANT: This function hashes the message internally to match Java/BouncyCastle.
506
+ * Callers pass RAW 32-byte data (tx digest, child root), NOT pre-hashed!
507
+ *
508
+ * @param sig - The 1088-byte WOTS signature
509
+ * @param message - Raw 32-byte message (will be hashed internally)
510
+ * @param pkFull - The FULL 1088-byte WOTS public key (L=34 × 32 bytes)
511
+ * @param ps - WOTS parameter set (default: minima)
512
+ */
513
+ function wotsVerify(sig, message, pkFull, ps = (0, params_js_1.getParamSet)()) {
514
+ // CRITICAL: Java verifies against FULL 1088-byte public key, not 32-byte digest
515
+ const expectedLen = ps.L * 32;
516
+ if (pkFull.length !== expectedLen) {
517
+ throw new Error(`pkFull must be exactly ${expectedLen} bytes (L=${ps.L} × 32); got ${pkFull.length}`);
518
+ }
519
+ if (sig.length !== expectedLen) {
520
+ return false;
521
+ }
522
+ // CRITICAL: Hash the message internally to match Java/BouncyCastle Winternitz behavior
523
+ const hashedMsg = (0, exports.F)(message);
524
+ const allDigits = baseWWithChecksum(hashedMsg, ps);
525
+ const buf = new Uint8Array(expectedLen);
526
+ for (let j = 0; j < ps.L; j++) {
527
+ const sigPart = sig.subarray(j * 32, (j + 1) * 32);
528
+ const stepsUp = ps.maxDigit - allDigits[j];
529
+ const top = hashChain(sigPart, stepsUp);
530
+ buf.set(top, j * 32);
531
+ }
532
+ // Compare FULL 1088-byte reconstructed key to expected FULL public key
533
+ // This matches Java: resp.isEqual(zPublicKey) where both are 1088 bytes
534
+ if (buf.length !== pkFull.length)
535
+ return false;
536
+ let diff = 0;
537
+ for (let i = 0; i < buf.length; i++)
538
+ diff |= buf[i] ^ pkFull[i];
539
+ return diff === 0;
540
+ }
541
+ /**
542
+ * Legacy verify function that accepts a 32-byte digest
543
+ * @deprecated Use wotsVerify with full 1088-byte public key instead
544
+ */
545
+ function wotsVerifyDigest(sig, message, pkDigest, ps = (0, params_js_1.getParamSet)()) {
546
+ assert32(pkDigest, 'pkDigest');
547
+ const expectedLen = ps.L * 32;
548
+ if (sig.length !== expectedLen) {
549
+ return false;
550
+ }
551
+ const msgHash = (0, exports.F)(message);
552
+ const allDigits = baseWWithChecksum(msgHash, ps);
553
+ const buf = new Uint8Array(expectedLen);
554
+ for (let j = 0; j < ps.L; j++) {
555
+ const sigPart = sig.subarray(j * 32, (j + 1) * 32);
556
+ const stepsUp = ps.maxDigit - allDigits[j];
557
+ const top = hashChain(sigPart, stepsUp);
558
+ buf.set(top, j * 32);
559
+ }
560
+ const recomputed = (0, exports.F)(buf);
561
+ if (recomputed.length !== pkDigest.length)
562
+ return false;
563
+ let diff = 0;
564
+ for (let i = 0; i < recomputed.length; i++)
565
+ diff |= recomputed[i] ^ pkDigest[i];
566
+ return diff === 0;
567
+ }
568
+ /**
569
+ * Generate WOTS public key from seed (convenience wrapper)
570
+ */
571
+ function wotsPublicKeyFromSeed(seed, index = 0, paramSet) {
572
+ assert32(seed, 'seed');
573
+ const keypair = wotsKeypairFromSeed(seed, index, paramSet);
574
+ return keypair.pk;
575
+ }
576
+ // === Legacy compatibility exports ===
577
+ // These are kept for backwards compatibility but use the BC-compatible implementation
578
+ /**
579
+ * @deprecated Use expandPrivateKey instead
580
+ */
581
+ function prfChainSeed(seed, i, j, _paramSet) {
582
+ // This function no longer makes sense with stateful PRNG
583
+ // For compatibility, derive the j-th chain seed for key i
584
+ const privateKeys = expandPrivateKey(seed, _paramSet);
585
+ if (j >= privateKeys.length) {
586
+ throw new Error(`Chain index ${j} out of range (max ${privateKeys.length - 1})`);
587
+ }
588
+ return privateKeys[j];
589
+ }
package/dist/index.d.ts CHANGED
@@ -15,13 +15,16 @@ export { sha3_256 } from './wasm-sync.js';
15
15
  export { expandPrivateKey, hashChain, derivePKdigest, deriveFullPublicKey, wotsSign, wotsVerify, wotsVerifyDigest, wotsPkFromSig, wotsPublicKeyFromSeed, wotsKeypairFromSeed, } from './wasm-sync.js';
16
16
  export * from './params.js';
17
17
  export { deriveChainSeedJava, derivePerAddressSeed, deriveRootPrivSeed, writeMiniNumber, writeMiniData, writeMiniString, precomputeTransactionCoinID, } from './wasm-sync.js';
18
- export { createUnifiedChildTreeKey, createUnifiedRootTreeKey, deriveUnifiedAddressPublicKey, verifyTreeSignature, mmrRootFromPublicKeys, verifyMMRProof, } from './wasm-sync.js';
19
- export { phraseToSeed, generateWordList, validatePhrase, cleanSeedPhrase, } from './wasm-sync.js';
18
+ export { createUnifiedChildTreeKey, createUnifiedRootTreeKey, deriveUnifiedAddressPublicKey, verifyTreeSignature, } from './treekey.js';
19
+ export { mmrRootFromPublicKeys, verifyMMRProof, } from './wasm-sync.js';
20
+ export { phraseToSeed, generateWordList, validatePhrase, cleanSeedPhrase, } from './bip39.js';
20
21
  export { makeMxAddress, parseMxAddress, wotsAddressFromKeypair, } from './wasm-sync.js';
21
22
  export { serializeTransaction, computeTransactionDigest, } from './wasm-sync.js';
22
23
  export { timingSafeEqual, createChallenge, validateChallenge, } from './wasm-sync.js';
23
24
  export { scriptFromWotsPk } from './script.js';
24
25
  export { makeMxAddress as encodeMx, parseMxAddress as decodeMx } from './wasm-sync.js';
26
+ /** Convert an Mx (radix-32) or hex Minima address to lowercase hex. */
27
+ export declare function mxToHex(address: string): string;
25
28
  export * from './mmr.js';
26
29
  export * from './scripts/index.js';
27
30
  export { scriptToAddress, addressToRoot } from './derive.js';
@@ -33,11 +36,14 @@ export { writeMiniByte, writeMMREntryNumber, concat, bigIntToByteArray, type Byt
33
36
  export { serializeMiniNumber, serializeMiniData, hashAllObjects, deriveChildTreeSeedJava, hashObject, serializeMiniNumberZERO, serializeMiniNumberONE, writeHashToStream, javaHashAllObjects, indexToMiniDataBytes, deriveUnifiedChildSeed, createMMREntryNumber, serializeMMREntryNumber, serializeMMRData, serializeMMREntry, type MMREntryNumber as JavaMMREntryNumber, type MMRData as JavaMMRData, type MMREntry as JavaMMREntry, } from './javaStreamables.js';
34
37
  export { TreeKey, TreeKeyNode, serializeTreeSignature, deserializeTreeSignature, getRootPublicKey, DEFAULT_KEYS_PER_LEVEL, DEFAULT_LEVELS, createUnifiedChildTreeKeyAsync, createPerAddressTreeKey, createPerAddressTreeKeyAsync, type KeyGenProgress, type ProgressCallback, type SignatureProof, type TreeSignature, } from './treekey.js';
35
38
  export type { WotsKeypair, WotsSignature } from './wots.js';
39
+ export { F, hex, fromHex, u16be, u32be, assert32, h, prfChainSeed, toWinternitzDigits, baseWWithChecksum, wotsSignLegacy, } from './wots.js';
40
+ export { toHex, canonicalJson, hashCanonical } from './canonical.js';
41
+ export { utf8ToBytes, bytesToUtf8 } from './utils.js';
36
42
  export declare const MINIMA_CONSTANTS: {
37
43
  readonly WOTS_W: 8;
38
44
  readonly WOTS_N: 32;
39
45
  readonly MAX_SIGNATURES: 262144;
40
46
  readonly SIGNATURE_LEVELS: 3;
41
- readonly ADDRESS_PREFIX: 'Mx';
47
+ readonly ADDRESS_PREFIX: "Mx";
42
48
  readonly NETWORK_ID: 1;
43
49
  };
package/dist/index.js CHANGED
@@ -18,6 +18,7 @@ export { TransactionService, TransactionLifecycle, TransactionLifecycleError, Wa
18
18
  // ---------------------------------------------------------------------------
19
19
  // Utilities
20
20
  export { bytesToHex, hexToBytes, concatBytes } from './wasm-sync.js';
21
+ import { bytesToHex, parseMxAddress } from './wasm-sync.js';
21
22
  // SHA3-256
22
23
  export { sha3_256 } from './wasm-sync.js';
23
24
  // WOTS Signatures
@@ -27,9 +28,19 @@ export * from './params.js';
27
28
  // Java-Compatible Serialization
28
29
  export { deriveChainSeedJava, derivePerAddressSeed, deriveRootPrivSeed, writeMiniNumber, writeMiniData, writeMiniString, precomputeTransactionCoinID, } from './wasm-sync.js';
29
30
  // TreeKey/TreeKeyNode — WASM-backed
30
- export { createUnifiedChildTreeKey, createUnifiedRootTreeKey, deriveUnifiedAddressPublicKey, verifyTreeSignature, mmrRootFromPublicKeys, verifyMMRProof, } from './wasm-sync.js';
31
+ // createUnifiedChildTreeKey / createUnifiedRootTreeKey come from the TS
32
+ // implementation (returning a full TreeKey object with setUses/sign/getPublicKey)
33
+ // to match the object API that downstream consumers (server, root-identity)
34
+ // rely on. The WASM binding only returns the root public key bytes.
35
+ export { createUnifiedChildTreeKey, createUnifiedRootTreeKey, deriveUnifiedAddressPublicKey, verifyTreeSignature, } from './treekey.js';
36
+ export { mmrRootFromPublicKeys, verifyMMRProof, } from './wasm-sync.js';
31
37
  // BIP39 Seed Phrase Handling
32
- export { phraseToSeed, generateWordList, validatePhrase, cleanSeedPhrase, } from './wasm-sync.js';
38
+ // NOTE: the TS implementation (bip39.ts) uses the complete 2048-word BIP39
39
+ // word list and Minima-compatible uppercase canonicalization. The WASM
40
+ // binding (wasm-sync.ts) ships a corrupted/partial word list (missing
41
+ // "hungry", contains spurious words) and lowercases instead of uppercasing,
42
+ // so the public API routes through the TS implementation.
43
+ export { phraseToSeed, generateWordList, validatePhrase, cleanSeedPhrase, } from './bip39.js';
33
44
  // Address Derivation
34
45
  export { makeMxAddress, parseMxAddress, wotsAddressFromKeypair, } from './wasm-sync.js';
35
46
  // Transaction Serialization & Digest
@@ -43,6 +54,13 @@ export { timingSafeEqual, createChallenge, validateChallenge, } from './wasm-syn
43
54
  export { scriptFromWotsPk } from './script.js';
44
55
  // Base32 Encoding (Minima-compatible) — re-export from WASM
45
56
  export { makeMxAddress as encodeMx, parseMxAddress as decodeMx } from './wasm-sync.js';
57
+ /** Convert an Mx (radix-32) or hex Minima address to lowercase hex. */
58
+ export function mxToHex(address) {
59
+ const upper = address.startsWith('0x') || address.startsWith('0X') ? address.slice(2) : address;
60
+ return upper.toUpperCase().startsWith('MX')
61
+ ? bytesToHex(parseMxAddress(address))
62
+ : upper.replace(/^0x/i, '');
63
+ }
46
64
  // Merkle Mountain Range (original JS — types and helpers)
47
65
  export * from './mmr.js';
48
66
  // Script Types, Witness Serializer, Contract Helpers
@@ -63,6 +81,11 @@ export { writeMiniByte, writeMMREntryNumber, concat, bigIntToByteArray, } from '
63
81
  export { serializeMiniNumber, serializeMiniData, hashAllObjects, deriveChildTreeSeedJava, hashObject, serializeMiniNumberZERO, serializeMiniNumberONE, writeHashToStream, javaHashAllObjects, indexToMiniDataBytes, deriveUnifiedChildSeed, createMMREntryNumber, serializeMMREntryNumber, serializeMMRData, serializeMMREntry, } from './javaStreamables.js';
64
82
  // TreeKey/TreeKeyNode — JS types and helpers
65
83
  export { TreeKey, TreeKeyNode, serializeTreeSignature, deserializeTreeSignature, getRootPublicKey, DEFAULT_KEYS_PER_LEVEL, DEFAULT_LEVELS, createUnifiedChildTreeKeyAsync, createPerAddressTreeKey, createPerAddressTreeKeyAsync, } from './treekey.js';
84
+ export { F, hex, fromHex, u16be, u32be, assert32, h, prfChainSeed, toWinternitzDigits, baseWWithChecksum, wotsSignLegacy, } from './wots.js';
85
+ // Canonical helpers (deterministic JSON + hashing)
86
+ export { toHex, canonicalJson, hashCanonical } from './canonical.js';
87
+ // Byte/string utilities
88
+ export { utf8ToBytes, bytesToUtf8 } from './utils.js';
66
89
  // Constants
67
90
  export const MINIMA_CONSTANTS = {
68
91
  WOTS_W: 8,