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