@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
@@ -0,0 +1,114 @@
1
+ /**
2
+ * @module Transaction Types
3
+ * Type definitions for transaction service
4
+ */
5
+ export interface WotsIndices {
6
+ addressIndex: number;
7
+ l1: number;
8
+ l2: number;
9
+ }
10
+ export interface PrepareRequest {
11
+ to: string;
12
+ amount: string;
13
+ tokenId?: string;
14
+ burn?: string;
15
+ txId?: string;
16
+ addressIndex?: number;
17
+ }
18
+ export interface PrepareResponse {
19
+ addressIndex: number;
20
+ l1: number;
21
+ l2: number;
22
+ leaseToken: string;
23
+ digestTx: string;
24
+ digestL2: string | null;
25
+ digestL3: string | null;
26
+ txId: string;
27
+ rootPublicKey: string;
28
+ paramSet: string;
29
+ leaseId: string;
30
+ leaseTTL: number;
31
+ }
32
+ export interface SignRequest {
33
+ addressIndex: number;
34
+ l1: number;
35
+ l2: number;
36
+ digestTx: string;
37
+ }
38
+ /**
39
+ * Per-proof entry in a hierarchical TreeKey signature chain.
40
+ * Each proof represents one parent→child signing step.
41
+ */
42
+ export interface SignatureProofHex {
43
+ leafPubkey: string;
44
+ signature: string;
45
+ mmrProof: string;
46
+ }
47
+ /**
48
+ * Hierarchical witness bundle produced by per-address TreeKey signing.
49
+ *
50
+ * Index mapping:
51
+ * addressIndex — which HD address (0-63)
52
+ * l1 — L1 index within per-address TreeKey (0-63)
53
+ * l2 — L2 index within per-address TreeKey (0-63)
54
+ *
55
+ * proofs contains 3 entries for depth-3 TreeKeys (Root→L1→L2→DATA),
56
+ * matching Minima's TreeKey.sign() exactly.
57
+ */
58
+ export interface HierarchicalWitnessBundle {
59
+ addressIndex: number;
60
+ l1: number;
61
+ l2: number;
62
+ rootPublicKey: string;
63
+ proofs: SignatureProofHex[];
64
+ }
65
+ /**
66
+ * @deprecated Use HierarchicalWitnessBundle. Kept for backward compatibility.
67
+ */
68
+ export interface WitnessBundle {
69
+ addressIndex: number;
70
+ l1: number;
71
+ l2: number;
72
+ signatures: {
73
+ l1Proof: string[];
74
+ l2Proof: string[];
75
+ l3Proof: string[];
76
+ };
77
+ }
78
+ export interface SignResult {
79
+ witnessBundle: HierarchicalWitnessBundle;
80
+ signedHex: string;
81
+ }
82
+ export interface FinalizeRequest {
83
+ leaseToken: string;
84
+ signedHex?: string;
85
+ signedBase64?: string;
86
+ transactionHex?: string;
87
+ importId?: string;
88
+ }
89
+ export interface FinalizeResponse {
90
+ ok: boolean;
91
+ leaseId: string;
92
+ txpowid: string;
93
+ }
94
+ export interface TransactionMetadata {
95
+ to: string;
96
+ amount: string;
97
+ tokenId: string;
98
+ }
99
+ export interface TransactionReceipt {
100
+ txpowid: string;
101
+ timestamp: number;
102
+ to: string;
103
+ amount: string;
104
+ tokenId: string;
105
+ indices: WotsIndices;
106
+ status: 'confirmed' | 'pending' | 'failed';
107
+ txId?: string;
108
+ leaseId?: string;
109
+ }
110
+ export interface TransactionError {
111
+ code: number;
112
+ message: string;
113
+ userMessage: string;
114
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * @module Transaction Types
3
+ * Type definitions for transaction service
4
+ */
5
+ export {};
package/dist/util.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare const bytesToHex: (b: Uint8Array) => string;
package/dist/util.js ADDED
@@ -0,0 +1 @@
1
+ export const bytesToHex = (b) => "0x" + [...b].map(x => x.toString(16).padStart(2, "0")).join("").toUpperCase();
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Utility functions for byte array manipulation
3
+ */
4
+ export declare function bytesToHex(bytes: Uint8Array): string;
5
+ export declare function hexToBytes(hex: string): Uint8Array;
6
+ export declare function concatBytes(...arrays: Uint8Array[]): Uint8Array;
7
+ export declare function utf8ToBytes(str: string): Uint8Array;
8
+ export declare function bytesToUtf8(bytes: Uint8Array): string;
package/dist/utils.js ADDED
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Utility functions for byte array manipulation
3
+ */
4
+ export function bytesToHex(bytes) {
5
+ return Array.from(bytes)
6
+ .map(b => b.toString(16).padStart(2, '0'))
7
+ .join('');
8
+ }
9
+ export function hexToBytes(hex) {
10
+ if (hex.startsWith('0x'))
11
+ hex = hex.slice(2);
12
+ if (hex.length % 2 !== 0)
13
+ throw new Error('Invalid hex string');
14
+ const bytes = new Uint8Array(hex.length / 2);
15
+ for (let i = 0; i < bytes.length; i++) {
16
+ bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
17
+ }
18
+ return bytes;
19
+ }
20
+ export function concatBytes(...arrays) {
21
+ const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
22
+ const result = new Uint8Array(totalLength);
23
+ let offset = 0;
24
+ for (const arr of arrays) {
25
+ result.set(arr, offset);
26
+ offset += arr.length;
27
+ }
28
+ return result;
29
+ }
30
+ export function utf8ToBytes(str) {
31
+ return new TextEncoder().encode(str);
32
+ }
33
+ export function bytesToUtf8(bytes) {
34
+ return new TextDecoder().decode(bytes);
35
+ }
@@ -0,0 +1,18 @@
1
+ import type { TreeSignature } from './treekey.js';
2
+ import type { Bytes } from './mmr.js';
3
+ export interface VerificationResult {
4
+ valid: boolean;
5
+ error?: string;
6
+ }
7
+ export declare function normalizeHex(hex: string): string;
8
+ export declare function hexToBytes(hex: string): Uint8Array;
9
+ export declare function bytesToHex(bytes: Uint8Array): string;
10
+ export declare function deriveAddressFromPublicKey(publicKeyHex: string): string;
11
+ export declare function verifyTreeSignatureDetailed(expectedPubkey: Bytes, data: Bytes, signature: TreeSignature): VerificationResult;
12
+ export declare function verifySignature(address: string, message: string, signatureHex: string, publicKeyHex: string): boolean;
13
+ export declare function verifySignatureDetailed(address: string, message: string, signatureHex: string, publicKeyHex: string): VerificationResult;
14
+ export declare function createChallenge(domain: string, nonce?: string): string;
15
+ export declare function validateChallenge(challenge: string, options?: {
16
+ maxAgeMs?: number;
17
+ expectedDomain?: string;
18
+ }): VerificationResult;
package/dist/verify.js ADDED
@@ -0,0 +1,162 @@
1
+ import { sha3_256 } from '@noble/hashes/sha3';
2
+ import { deserializeTreeSignature } from './treekey.js';
3
+ import { scriptToAddress } from './derive.js';
4
+ import { scriptFromWotsPk } from './script.js';
5
+ import { getRootPublicKey } from './treekey.js';
6
+ import { wotsVerifyDigest } from './wots.js';
7
+ import { getParamSet } from './params.js';
8
+ export function normalizeHex(hex) {
9
+ const stripped = hex.startsWith('0x') ? hex.slice(2) : hex;
10
+ return stripped.toLowerCase();
11
+ }
12
+ export function hexToBytes(hex) {
13
+ const h = normalizeHex(hex);
14
+ if (h.length % 2 !== 0)
15
+ throw new Error('Invalid hex string: odd length');
16
+ const bytes = new Uint8Array(h.length / 2);
17
+ for (let i = 0; i < bytes.length; i++) {
18
+ bytes[i] = parseInt(h.slice(i * 2, i * 2 + 2), 16);
19
+ }
20
+ return bytes;
21
+ }
22
+ export function bytesToHex(bytes) {
23
+ return Array.from(bytes)
24
+ .map(b => b.toString(16).padStart(2, '0'))
25
+ .join('');
26
+ }
27
+ export function deriveAddressFromPublicKey(publicKeyHex) {
28
+ const pkBytes = hexToBytes(publicKeyHex);
29
+ if (pkBytes.length !== 32) {
30
+ throw new Error(`Public key must be 32 bytes (64 hex chars), got ${pkBytes.length} bytes`);
31
+ }
32
+ const script = scriptFromWotsPk(pkBytes);
33
+ return scriptToAddress(script);
34
+ }
35
+ export function verifyTreeSignatureDetailed(expectedPubkey, data, signature) {
36
+ const { proofs } = signature;
37
+ if (proofs.length === 0) {
38
+ return { valid: false, error: 'Signature contains no proofs' };
39
+ }
40
+ const paramSet = getParamSet();
41
+ for (let depth = 0; depth < proofs.length; depth++) {
42
+ const proof = proofs[depth];
43
+ const rootPubkey = getRootPublicKey(proof);
44
+ if (depth === 0) {
45
+ if (!timingSafeEqual(expectedPubkey, rootPubkey)) {
46
+ return {
47
+ valid: false,
48
+ error: 'Root public key does not match expected public key (wrong key or address)',
49
+ };
50
+ }
51
+ }
52
+ let signedData;
53
+ if (depth === proofs.length - 1) {
54
+ signedData = data;
55
+ }
56
+ else {
57
+ signedData = getRootPublicKey(proofs[depth + 1]);
58
+ }
59
+ if (!wotsVerifyDigest(proof.signature, signedData, proof.leafPubkey, paramSet)) {
60
+ return {
61
+ valid: false,
62
+ error: `WOTS signature verification failed at depth ${depth} (digest mismatch or corrupted signature)`,
63
+ };
64
+ }
65
+ }
66
+ return { valid: true };
67
+ }
68
+ export function verifySignature(address, message, signatureHex, publicKeyHex) {
69
+ const result = verifySignatureDetailed(address, message, signatureHex, publicKeyHex);
70
+ return result.valid;
71
+ }
72
+ export function verifySignatureDetailed(address, message, signatureHex, publicKeyHex) {
73
+ try {
74
+ const pkBytes = hexToBytes(publicKeyHex);
75
+ if (pkBytes.length !== 32) {
76
+ return {
77
+ valid: false,
78
+ error: `Public key must be 32 bytes (64 hex chars), got ${pkBytes.length} bytes`,
79
+ };
80
+ }
81
+ const derivedAddress = deriveAddressFromPublicKey(publicKeyHex);
82
+ if (derivedAddress.toLowerCase() !== address.toLowerCase()) {
83
+ return {
84
+ valid: false,
85
+ error: `Public key does not match claimed address. Expected ${address}, derived ${derivedAddress}`,
86
+ };
87
+ }
88
+ const sigBytes = hexToBytes(signatureHex);
89
+ let treeSignature;
90
+ try {
91
+ treeSignature = deserializeTreeSignature(sigBytes);
92
+ }
93
+ catch (e) {
94
+ return {
95
+ valid: false,
96
+ error: `Malformed signature: ${e.message}`,
97
+ };
98
+ }
99
+ const digest = sha3_256(new TextEncoder().encode(message));
100
+ return verifyTreeSignatureDetailed(pkBytes, digest, treeSignature);
101
+ }
102
+ catch (e) {
103
+ return {
104
+ valid: false,
105
+ error: `Verification error: ${e.message}`,
106
+ };
107
+ }
108
+ }
109
+ function timingSafeEqual(a, b) {
110
+ if (a.length !== b.length)
111
+ return false;
112
+ let result = 0;
113
+ for (let i = 0; i < a.length; i++) {
114
+ result |= a[i] ^ b[i];
115
+ }
116
+ return result === 0;
117
+ }
118
+ function cryptoRandomBytes(length) {
119
+ const buf = new Uint8Array(length);
120
+ if (typeof globalThis.crypto !== 'undefined' && globalThis.crypto.getRandomValues) {
121
+ globalThis.crypto.getRandomValues(buf);
122
+ }
123
+ else {
124
+ try {
125
+ const { randomFillSync } = require('crypto');
126
+ randomFillSync(buf);
127
+ }
128
+ catch {
129
+ throw new Error('No cryptographically secure RNG available');
130
+ }
131
+ }
132
+ return buf;
133
+ }
134
+ export function createChallenge(domain, nonce) {
135
+ const ts = Date.now();
136
+ const n = nonce || bytesToHex(sha3_256(new Uint8Array([...new TextEncoder().encode(`${domain}:${ts}:`), ...cryptoRandomBytes(16)]))).slice(0, 16);
137
+ return JSON.stringify({ domain, nonce: n, issuedAt: ts });
138
+ }
139
+ export function validateChallenge(challenge, options) {
140
+ try {
141
+ const parsed = JSON.parse(challenge);
142
+ const { domain, nonce, issuedAt } = parsed;
143
+ if (!domain || !nonce || !issuedAt) {
144
+ return { valid: false, error: 'Challenge missing required fields (domain, nonce, issuedAt)' };
145
+ }
146
+ if (options?.expectedDomain && domain !== options.expectedDomain) {
147
+ return { valid: false, error: `Domain mismatch: expected ${options.expectedDomain}, got ${domain}` };
148
+ }
149
+ const maxAge = options?.maxAgeMs ?? 5 * 60 * 1000;
150
+ const age = Date.now() - issuedAt;
151
+ if (age > maxAge) {
152
+ return { valid: false, error: `Challenge expired: ${Math.round(age / 1000)}s old (max ${Math.round(maxAge / 1000)}s)` };
153
+ }
154
+ if (age < 0) {
155
+ return { valid: false, error: 'Challenge issued in the future' };
156
+ }
157
+ return { valid: true };
158
+ }
159
+ catch {
160
+ return { valid: false, error: 'Invalid challenge format (not valid JSON)' };
161
+ }
162
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * SDK Core Version Information
3
+ *
4
+ * CORE_BUILD_ID is used to detect bundle duplication issues where
5
+ * the extension might bundle two different copies of sdk-core,
6
+ * computing addresses with one copy and signing with another.
7
+ *
8
+ * If you see different CORE_BUILD_IDs logged from wallet creation
9
+ * vs signing modules, there's a bundling issue.
10
+ */
11
+ export declare const CORE_BUILD_ID = "2026.02.05-v1";
12
+ export declare const CORE_VERSION = "1.0.0";
@@ -0,0 +1,12 @@
1
+ /**
2
+ * SDK Core Version Information
3
+ *
4
+ * CORE_BUILD_ID is used to detect bundle duplication issues where
5
+ * the extension might bundle two different copies of sdk-core,
6
+ * computing addresses with one copy and signing with another.
7
+ *
8
+ * If you see different CORE_BUILD_IDs logged from wallet creation
9
+ * vs signing modules, there's a bundling issue.
10
+ */
11
+ export const CORE_BUILD_ID = '2026.02.05-v1';
12
+ export const CORE_VERSION = '1.0.0';
package/dist/wots.d.ts ADDED
@@ -0,0 +1,232 @@
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 { ParamSet } from "./params.js";
16
+ import type { LoggerAdapter } from "./adapters/index.js";
17
+ /**
18
+ * Enable WOTS debug logging with a custom logger
19
+ * Use this for parity testing to capture all intermediate values
20
+ *
21
+ * WARNING: Debug logging outputs sensitive cryptographic material including
22
+ * private key chains and seeds. NEVER enable in production builds.
23
+ * This is intended for development/testing parity verification only.
24
+ */
25
+ export declare function setWotsLogger(logger: LoggerAdapter): void;
26
+ /**
27
+ * Disable WOTS debug logging
28
+ */
29
+ export declare function disableWotsLogger(): void;
30
+ /**
31
+ * Check if WOTS debug logging is enabled
32
+ */
33
+ export declare function isWotsDebugEnabled(): boolean;
34
+ export declare const F: (x: Uint8Array) => Uint8Array<ArrayBufferLike>;
35
+ export declare const hex: (u: Uint8Array) => string;
36
+ export declare const fromHex: (h: string) => Uint8Array<ArrayBuffer>;
37
+ export declare const concatBytes: (...arrs: Uint8Array[]) => Uint8Array<ArrayBuffer>;
38
+ export declare const u16be: (n: number) => Uint8Array<ArrayBuffer>;
39
+ export declare const u32be: (n: number) => Uint8Array<ArrayBuffer>;
40
+ export declare function assert32(u: Uint8Array, label?: string): void;
41
+ export declare const h: (x: Uint8Array) => Uint8Array<ArrayBufferLike>;
42
+ /**
43
+ * GMSSRandom - BouncyCastle's stateful PRNG for WOTS chain seed derivation
44
+ *
45
+ * Algorithm from GMSSRandom.java:
46
+ * rand = H(state)
47
+ * state = state + rand + 1 (byte-wise addition with carry)
48
+ * return rand
49
+ *
50
+ * The state is MUTATED in place after each call.
51
+ */
52
+ export declare class GMSSRandom {
53
+ /**
54
+ * Generate next random value and update state
55
+ *
56
+ * @param state - 32-byte state array (MUTATED in place)
57
+ * @returns 32-byte random value
58
+ */
59
+ static nextSeed(state: Uint8Array): Uint8Array;
60
+ /**
61
+ * Add two byte arrays: a = a + b (little-endian, with carry)
62
+ * Matches GMSSRandom.addByteArrays()
63
+ */
64
+ private static addByteArrays;
65
+ /**
66
+ * Add one to byte array: a = a + 1 (little-endian, with carry)
67
+ * Matches GMSSRandom.addOne()
68
+ */
69
+ private static addOne;
70
+ }
71
+ /**
72
+ * getLog - Calculate ceil(log2(x))
73
+ *
74
+ * Matches WinternitzOTSignature.getLog():
75
+ * int log = 1;
76
+ * int i = 2;
77
+ * while (i < intValue) { i <<= 1; log++; }
78
+ * return log;
79
+ */
80
+ export declare function getLog(intValue: number): number;
81
+ /**
82
+ * Expand master seed into L private key chains using GMSSRandom
83
+ *
84
+ * Matches WinternitzOTSignature constructor:
85
+ * byte[] dummy = new byte[mdsize];
86
+ * System.arraycopy(seed0, 0, dummy, 0, dummy.length);
87
+ * for (int i = 0; i < keysize; i++) {
88
+ * privateKeyOTS[i] = gmssRandom.nextSeed(dummy);
89
+ * }
90
+ */
91
+ export declare function expandPrivateKey(seed: Uint8Array, ps?: ParamSet): Uint8Array[];
92
+ /**
93
+ * Convert message hash to Winternitz digits with checksum
94
+ *
95
+ * For w=8 (8 bits per digit), since 8 % 8 == 0:
96
+ * - Each byte of the hash IS one digit (0-255)
97
+ * - messagesize = 32 digits
98
+ * - checksum = (messagesize << w) - sum = 8192 - sum
99
+ * - checksumsize = 14 bits, extracted as 2 digits
100
+ *
101
+ * Matches WinternitzOTSignature.getSignature() for w=8 case
102
+ */
103
+ export declare function toWinternitzDigits(hash32: Uint8Array, ps?: ParamSet): {
104
+ digits: number[];
105
+ checksumDigits: number[];
106
+ total: number;
107
+ };
108
+ /**
109
+ * Decompose digest into base-w digits + checksum
110
+ * Returns flat array of all L digits
111
+ */
112
+ export declare function baseWWithChecksum(msgHash: Uint8Array, paramSet?: ParamSet): number[];
113
+ /**
114
+ * Hash a value k times
115
+ *
116
+ * Matches WinternitzOTSignature.hashPrivateKeyBlock():
117
+ * - If rounds < 1: return input unchanged
118
+ * - Otherwise: hash `rounds` times
119
+ */
120
+ export declare function hashChain(x: Uint8Array, rounds: number): Uint8Array;
121
+ export type WotsKeypair = {
122
+ seed: Uint8Array;
123
+ index: number;
124
+ pk: Uint8Array;
125
+ };
126
+ /**
127
+ * Derive unique seed for a specific key index
128
+ *
129
+ * DEPRECATED: Use deriveChainSeedJava for Java parity.
130
+ * This function is preserved for backward compatibility only.
131
+ *
132
+ * The correct derivation matching Minima's TreeKeyNode.java:
133
+ * MiniData seed = Crypto.getInstance().hashAllObjects(new MiniNumber(i), zPrivateSeed);
134
+ *
135
+ * This old implementation used H(seed || u32be(i)) which is NOT Java compatible.
136
+ * @deprecated Use deriveChainSeedJava from javaStreamables.ts
137
+ */
138
+ export declare function deriveIndexedSeed(seed: Uint8Array, keyIndex: number): Uint8Array;
139
+ /**
140
+ * Derive WOTS public key digest from seed and key index
141
+ *
142
+ * The key index is mixed into the seed first (deriveIndexedSeed),
143
+ * then expanded using GMSSRandom to get unique chain seeds.
144
+ *
145
+ * Matches WinternitzOTSignature.getPublicKey():
146
+ * int rounds = (1 << w) - 1; // 255 for w=8
147
+ * for (int i = 0; i < keysize; i++) {
148
+ * hashPrivateKeyBlock(i, rounds, buf, pos);
149
+ * }
150
+ * return H(buf);
151
+ */
152
+ export declare function derivePKdigest(seed: Uint8Array, i: number, ps?: ParamSet): Uint8Array;
153
+ /**
154
+ * Derive full WOTS public key (L × 32 bytes) without final hash
155
+ *
156
+ * Returns the concatenation of all chain tops BEFORE hashing.
157
+ * Required by Minima's SignatureProof which expects the full public key.
158
+ */
159
+ export declare function deriveFullPublicKey(seed: Uint8Array, i: number, ps?: ParamSet): Uint8Array;
160
+ export declare function wotsKeypairFromSeed(seed: Uint8Array, index: number, paramSet?: ParamSet): WotsKeypair;
161
+ export type WotsSignature = {
162
+ index: number;
163
+ w: number;
164
+ sig: Uint8Array[];
165
+ };
166
+ /**
167
+ * Sign a message using WOTS
168
+ *
169
+ * Matches Java's WinternitzOTSignature.getSignature():
170
+ * 1. Hash the message internally: hashedMsg = SHA3-256(message)
171
+ * 2. For each digit d[i]: sig[i] = hash(privateKey[i], d[i] times)
172
+ *
173
+ * IMPORTANT: This function hashes the message internally to match Java/BouncyCastle.
174
+ * Callers pass RAW 32-byte data (tx digest, child root), NOT pre-hashed!
175
+ *
176
+ * @param seed - 32-byte master seed
177
+ * @param i - Key index
178
+ * @param message - Raw 32-byte message (will be hashed internally)
179
+ * @param ps - WOTS parameter set (default: minima)
180
+ * @returns Flat signature (L × 32 = 1088 bytes)
181
+ */
182
+ export declare function wotsSign(seed: Uint8Array, i: number, message: Uint8Array, ps?: ParamSet): Uint8Array;
183
+ /**
184
+ * Legacy wrapper returning structured signature
185
+ */
186
+ export declare function wotsSignLegacy(msgHash: Uint8Array, seed: Uint8Array, index: number, paramSet?: ParamSet): WotsSignature;
187
+ /**
188
+ * Recover public key from signature
189
+ *
190
+ * Matches WinternitzOTSVerify.Verify():
191
+ * 1. Hash the message: hashedMsg = SHA3-256(message)
192
+ * 2. for each digit d[i]:
193
+ * top[i] = hash(sig[i], (255 - d[i]) times)
194
+ * 3. return H(concat(tops))
195
+ *
196
+ * CRITICAL: This function hashes the message internally to match Java/BouncyCastle
197
+ * Winternitz behavior. Both wotsSign and wotsPkFromSig hash internally for parity.
198
+ */
199
+ export declare function wotsPkFromSig(message: Uint8Array, signature: WotsSignature, paramSet?: ParamSet): Uint8Array;
200
+ /**
201
+ * Verify WOTS signature against a FULL 1088-byte public key
202
+ *
203
+ * Matches Java's Winternitz.verify():
204
+ * 1. Hash the message internally: hashedMsg = SHA3-256(message)
205
+ * 2. Recover FULL public key from signature using hashedMsg (1088 bytes)
206
+ * 3. Compare FULL reconstructed key to expected FULL public key
207
+ *
208
+ * CRITICAL: Java's Winternitz.verify() compares the FULL 1088-byte reconstructed
209
+ * public key against the FULL 1088-byte stored public key, NOT a 32-byte digest!
210
+ *
211
+ * IMPORTANT: This function hashes the message internally to match Java/BouncyCastle.
212
+ * Callers pass RAW 32-byte data (tx digest, child root), NOT pre-hashed!
213
+ *
214
+ * @param sig - The 1088-byte WOTS signature
215
+ * @param message - Raw 32-byte message (will be hashed internally)
216
+ * @param pkFull - The FULL 1088-byte WOTS public key (L=34 × 32 bytes)
217
+ * @param ps - WOTS parameter set (default: minima)
218
+ */
219
+ export declare function wotsVerify(sig: Uint8Array, message: Uint8Array, pkFull: Uint8Array, ps?: ParamSet): boolean;
220
+ /**
221
+ * Legacy verify function that accepts a 32-byte digest
222
+ * @deprecated Use wotsVerify with full 1088-byte public key instead
223
+ */
224
+ export declare function wotsVerifyDigest(sig: Uint8Array, message: Uint8Array, pkDigest: Uint8Array, ps?: ParamSet): boolean;
225
+ /**
226
+ * Generate WOTS public key from seed (convenience wrapper)
227
+ */
228
+ export declare function wotsPublicKeyFromSeed(seed: Uint8Array, index?: number, paramSet?: ParamSet): Uint8Array;
229
+ /**
230
+ * @deprecated Use expandPrivateKey instead
231
+ */
232
+ export declare function prfChainSeed(seed: Uint8Array, i: number, j: number, _paramSet: ParamSet): Uint8Array;