@totemsdk/core 1.0.0

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