@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.
- package/dist/Streamable.d.ts +268 -0
- package/dist/Streamable.js +416 -0
- package/dist/adapters/index.d.ts +190 -0
- package/dist/adapters/index.js +107 -0
- package/dist/adapters/types.d.ts +149 -0
- package/dist/adapters/types.js +67 -0
- package/dist/binio.d.ts +9 -0
- package/dist/binio.js +30 -0
- package/dist/bip39.d.ts +91 -0
- package/dist/bip39.js +417 -0
- package/dist/derive.d.ts +2 -0
- package/dist/derive.js +9 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.js +53 -0
- package/dist/javaStreamables.d.ts +233 -0
- package/dist/javaStreamables.js +332 -0
- package/dist/lease/LeaseMonitor.d.ts +44 -0
- package/dist/lease/LeaseMonitor.js +107 -0
- package/dist/lease/LeaseStore.d.ts +57 -0
- package/dist/lease/LeaseStore.js +144 -0
- package/dist/lease/WatermarkStore.d.ts +61 -0
- package/dist/lease/WatermarkStore.js +202 -0
- package/dist/lease/index.d.ts +14 -0
- package/dist/lease/index.js +13 -0
- package/dist/lease-client.d.ts +31 -0
- package/dist/lease-client.js +39 -0
- package/dist/minima32.d.ts +18 -0
- package/dist/minima32.js +112 -0
- package/dist/minimaWireSerializer.d.ts +60 -0
- package/dist/minimaWireSerializer.js +71 -0
- package/dist/mmr.d.ts +156 -0
- package/dist/mmr.js +342 -0
- package/dist/mx.d.ts +1 -0
- package/dist/mx.js +1 -0
- package/dist/params.d.ts +29 -0
- package/dist/params.js +16 -0
- package/dist/script.d.ts +7 -0
- package/dist/script.js +22 -0
- package/dist/scripts/contract-helpers.d.ts +252 -0
- package/dist/scripts/contract-helpers.js +394 -0
- package/dist/scripts/dapp-types.d.ts +119 -0
- package/dist/scripts/dapp-types.js +72 -0
- package/dist/scripts/index.d.ts +4 -0
- package/dist/scripts/index.js +4 -0
- package/dist/scripts/types.d.ts +81 -0
- package/dist/scripts/types.js +145 -0
- package/dist/scripts/witness-serializer.d.ts +29 -0
- package/dist/scripts/witness-serializer.js +288 -0
- package/dist/transaction.d.ts +106 -0
- package/dist/transaction.js +284 -0
- package/dist/treekey.d.ts +383 -0
- package/dist/treekey.js +762 -0
- package/dist/tx/TransactionLifecycle.d.ts +55 -0
- package/dist/tx/TransactionLifecycle.js +189 -0
- package/dist/tx/TransactionReceiptStore.d.ts +36 -0
- package/dist/tx/TransactionReceiptStore.js +85 -0
- package/dist/tx/TransactionService.d.ts +50 -0
- package/dist/tx/TransactionService.js +178 -0
- package/dist/tx/index.d.ts +13 -0
- package/dist/tx/index.js +12 -0
- package/dist/tx/types.d.ts +114 -0
- package/dist/tx/types.js +5 -0
- package/dist/util.d.ts +1 -0
- package/dist/util.js +1 -0
- package/dist/utils.d.ts +8 -0
- package/dist/utils.js +35 -0
- package/dist/verify.d.ts +18 -0
- package/dist/verify.js +162 -0
- package/dist/version.d.ts +12 -0
- package/dist/version.js +12 -0
- package/dist/wots.d.ts +232 -0
- package/dist/wots.js +538 -0
- package/package.json +65 -0
- package/src/Streamable.d.ts +265 -0
- package/src/Streamable.js +431 -0
- package/src/Streamable.ts +567 -0
- package/src/__tests__/Streamable.parity.test.ts +422 -0
- package/src/__tests__/perAddressDerivation.parity.test.ts +152 -0
- package/src/__tests__/wots-parity.test.ts +289 -0
- package/src/adapters/index.d.ts +190 -0
- package/src/adapters/index.js +117 -0
- package/src/adapters/index.ts +301 -0
- package/src/adapters/types.ts +235 -0
- package/src/addr.oracle.test.ts +25 -0
- package/src/address.test.ts +55 -0
- package/src/binio.ts +21 -0
- package/src/bip39.d.ts +91 -0
- package/src/bip39.js +427 -0
- package/src/bip39.ts +432 -0
- package/src/derive.d.ts +2 -0
- package/src/derive.js +13 -0
- package/src/derive.ts +11 -0
- package/src/index.d.ts +26 -0
- package/src/index.js +128 -0
- package/src/index.test.ts +5 -0
- package/src/index.ts +206 -0
- package/src/javaStreamables.d.ts +233 -0
- package/src/javaStreamables.js +328 -0
- package/src/javaStreamables.ts +403 -0
- package/src/lease/LeaseMonitor.d.ts +44 -0
- package/src/lease/LeaseMonitor.js +111 -0
- package/src/lease/LeaseMonitor.ts +157 -0
- package/src/lease/LeaseStore.d.ts +57 -0
- package/src/lease/LeaseStore.js +148 -0
- package/src/lease/LeaseStore.ts +203 -0
- package/src/lease/WatermarkStore.d.ts +61 -0
- package/src/lease/WatermarkStore.js +206 -0
- package/src/lease/WatermarkStore.ts +270 -0
- package/src/lease/index.d.ts +14 -0
- package/src/lease/index.js +22 -0
- package/src/lease/index.ts +41 -0
- package/src/lease-client.d.ts +31 -0
- package/src/lease-client.js +44 -0
- package/src/lease-client.ts +69 -0
- package/src/minima32.d.ts +10 -0
- package/src/minima32.js +113 -0
- package/src/minima32.test.ts +11 -0
- package/src/minima32.ts +127 -0
- package/src/minimaWireSerializer.d.ts +189 -0
- package/src/minimaWireSerializer.js +311 -0
- package/src/minimaWireSerializer.test.ts +466 -0
- package/src/minimaWireSerializer.ts +117 -0
- package/src/mmr.d.ts +153 -0
- package/src/mmr.js +351 -0
- package/src/mmr.oracle.test.ts +28 -0
- package/src/mmr.ts +429 -0
- package/src/mx.test.ts +25 -0
- package/src/mx.ts +1 -0
- package/src/params.d.ts +29 -0
- package/src/params.d.ts.map +1 -0
- package/src/params.js +20 -0
- package/src/params.js.map +1 -0
- package/src/params.ts +44 -0
- package/src/script.d.ts +7 -0
- package/src/script.js +27 -0
- package/src/script.ts +24 -0
- package/src/scripts/contract-helpers.ts +609 -0
- package/src/scripts/dapp-types.ts +240 -0
- package/src/scripts/index.ts +22 -0
- package/src/scripts/types.ts +247 -0
- package/src/scripts/witness-serializer.ts +384 -0
- package/src/transaction.ts +430 -0
- package/src/treekey.d.ts +383 -0
- package/src/treekey.js +778 -0
- package/src/treekey.parity.test.ts +459 -0
- package/src/treekey.ts +979 -0
- package/src/tx/TransactionLifecycle.d.ts +55 -0
- package/src/tx/TransactionLifecycle.js +188 -0
- package/src/tx/TransactionLifecycle.ts +280 -0
- package/src/tx/TransactionReceiptStore.d.ts +36 -0
- package/src/tx/TransactionReceiptStore.js +89 -0
- package/src/tx/TransactionReceiptStore.ts +112 -0
- package/src/tx/TransactionService.d.ts +31 -0
- package/src/tx/TransactionService.js +140 -0
- package/src/tx/TransactionService.ts +250 -0
- package/src/tx/index.d.ts +13 -0
- package/src/tx/index.js +20 -0
- package/src/tx/index.ts +44 -0
- package/src/tx/types.d.ts +80 -0
- package/src/tx/types.js +6 -0
- package/src/tx/types.ts +127 -0
- package/src/util.d.ts +1 -0
- package/src/util.js +5 -0
- package/src/util.ts +1 -0
- package/src/utils.d.ts +8 -0
- package/src/utils.js +42 -0
- package/src/utils.ts +38 -0
- package/src/verify.ts +209 -0
- package/src/version.ts +13 -0
- package/src/wots.d.ts +224 -0
- package/src/wots.d.ts.map +1 -0
- package/src/wots.js +559 -0
- package/src/wots.js.map +1 -0
- package/src/wots.ts +636 -0
- package/test-vectors.json +45 -0
package/src/treekey.js
ADDED
|
@@ -0,0 +1,778 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* TreeKey/TreeKeyNode Implementation matching Minima's TreeKey.java and TreeKeyNode.java
|
|
4
|
+
*
|
|
5
|
+
* This implements the hierarchical key tree structure where:
|
|
6
|
+
* - Each TreeKeyNode contains 64 Winternitz keys
|
|
7
|
+
* - The node's PUBLIC KEY = MMR root of all 64 Winternitz public keys
|
|
8
|
+
* - Signatures include the Winternitz leaf pubkey + signature + MMR proof
|
|
9
|
+
*
|
|
10
|
+
* Default structure: 3 levels x 64 keys = 64^3 = 262,144 one-time signatures
|
|
11
|
+
*/
|
|
12
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
13
|
+
exports.TreeKey = exports.TreeKeyNode = exports.DEFAULT_LEVELS = exports.DEFAULT_KEYS_PER_LEVEL = void 0;
|
|
14
|
+
exports.setTreeKeyLogger = setTreeKeyLogger;
|
|
15
|
+
exports.disableTreeKeyLogger = disableTreeKeyLogger;
|
|
16
|
+
exports.isTreeKeyDebugEnabled = isTreeKeyDebugEnabled;
|
|
17
|
+
exports.getRootPublicKey = getRootPublicKey;
|
|
18
|
+
exports.verifyTreeSignature = verifyTreeSignature;
|
|
19
|
+
exports.serializeTreeSignature = serializeTreeSignature;
|
|
20
|
+
exports.deserializeTreeSignature = deserializeTreeSignature;
|
|
21
|
+
exports.createPerAddressTreeKey = createPerAddressTreeKey;
|
|
22
|
+
exports.createPerAddressTreeKeyAsync = createPerAddressTreeKeyAsync;
|
|
23
|
+
exports.deriveAddressPublicKey = deriveAddressPublicKey;
|
|
24
|
+
exports.getPerAddressPublicKey = getPerAddressPublicKey;
|
|
25
|
+
const javaStreamables_1 = require("./javaStreamables");
|
|
26
|
+
const wots_1 = require("./wots");
|
|
27
|
+
const params_1 = require("./params");
|
|
28
|
+
const mmr_1 = require("./mmr");
|
|
29
|
+
const Streamable_1 = require("./Streamable");
|
|
30
|
+
const adapters_1 = require("./adapters");
|
|
31
|
+
// Module-level debug logger - can be set externally for parity testing
|
|
32
|
+
let treeKeyLogger = new adapters_1.NoopLogger();
|
|
33
|
+
let treeKeyDebugEnabled = false;
|
|
34
|
+
/**
|
|
35
|
+
* Enable TreeKey debug logging with a custom logger
|
|
36
|
+
* Use this for parity testing to capture wallet init intermediate values
|
|
37
|
+
*
|
|
38
|
+
* WARNING: Debug logging outputs sensitive cryptographic material including
|
|
39
|
+
* seeds and private key derivation. NEVER enable in production builds.
|
|
40
|
+
* This is intended for development/testing parity verification only.
|
|
41
|
+
*/
|
|
42
|
+
function setTreeKeyLogger(logger) {
|
|
43
|
+
treeKeyLogger = logger;
|
|
44
|
+
treeKeyDebugEnabled = true;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Disable TreeKey debug logging
|
|
48
|
+
*/
|
|
49
|
+
function disableTreeKeyLogger() {
|
|
50
|
+
treeKeyLogger = new adapters_1.NoopLogger();
|
|
51
|
+
treeKeyDebugEnabled = false;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Check if TreeKey debug logging is enabled
|
|
55
|
+
*/
|
|
56
|
+
function isTreeKeyDebugEnabled() {
|
|
57
|
+
return treeKeyDebugEnabled;
|
|
58
|
+
}
|
|
59
|
+
exports.DEFAULT_KEYS_PER_LEVEL = 64;
|
|
60
|
+
exports.DEFAULT_LEVELS = 3;
|
|
61
|
+
/**
|
|
62
|
+
* Compute root public key from a Winternitz signature proof
|
|
63
|
+
* Matches SignatureProof.getRootPublicKey() in Java
|
|
64
|
+
*/
|
|
65
|
+
function getRootPublicKey(proof) {
|
|
66
|
+
const leafData = (0, mmr_1.createMMRDataLeafNode)(proof.leafPubkey, 0n);
|
|
67
|
+
return (0, mmr_1.calculateProofRoot)(leafData, proof.mmrProof);
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* TreeKeyNode - One node in the key tree containing 64 Winternitz keys
|
|
71
|
+
*
|
|
72
|
+
* Matches TreeKeyNode.java (see attached_assets/TreeKeyNode_1767574401422.java):
|
|
73
|
+
*
|
|
74
|
+
* Key generation (lines 44-62):
|
|
75
|
+
* - Creates 64 Winternitz keys from a deterministic seed
|
|
76
|
+
* - For each key: MiniData pubkey = wots.getPublicKey() returns 32-byte DIGEST
|
|
77
|
+
* - Adds to MMR: MMRData.CreateMMRDataLeafNode(pubkey, MiniNumber.ZERO)
|
|
78
|
+
* - Public key = MMR root (mPublicKey = mTree.getRoot().getData())
|
|
79
|
+
*
|
|
80
|
+
* MMR leaf construction (see MMRData.java lines 30-36):
|
|
81
|
+
* MMRData.CreateMMRDataLeafNode(pubkeyDigest, MiniNumber.ZERO)
|
|
82
|
+
* → hash = Crypto.hashAllObjects(MiniNumber.ZERO, zData, zSumValue)
|
|
83
|
+
* → Serialization: [0x00,0x01,0x00] + [4-byte-len + pubkey] + [0x00,0x01,0x00]
|
|
84
|
+
*
|
|
85
|
+
* MMR parent construction (see MMRData.java lines 38-50):
|
|
86
|
+
* MMRData.CreateMMRDataParentNode(left, right)
|
|
87
|
+
* → hash = Crypto.hashAllObjects(MiniNumber.ONE, left.data, right.data, sumValue)
|
|
88
|
+
*
|
|
89
|
+
* IMPORTANT: Minima NEVER stores the 1088-byte full WOTS public key.
|
|
90
|
+
* Only the 32-byte digest is stored and used for MMR construction.
|
|
91
|
+
*/
|
|
92
|
+
class TreeKeyNode {
|
|
93
|
+
constructor(privateSeed, keysPerLevel = exports.DEFAULT_KEYS_PER_LEVEL) {
|
|
94
|
+
this.childCache = new Map();
|
|
95
|
+
if (privateSeed.length !== 32) {
|
|
96
|
+
throw new Error('Private seed must be 32 bytes');
|
|
97
|
+
}
|
|
98
|
+
if (treeKeyDebugEnabled) {
|
|
99
|
+
treeKeyLogger.debug(`[TreeKeyNode] ========== INIT START ==========`);
|
|
100
|
+
treeKeyLogger.debug(`[TreeKeyNode] Private seed: ${(0, wots_1.hex)(privateSeed)}`);
|
|
101
|
+
treeKeyLogger.debug(`[TreeKeyNode] Keys per level: ${keysPerLevel}`);
|
|
102
|
+
}
|
|
103
|
+
this.seed = privateSeed;
|
|
104
|
+
this.keysPerLevel = keysPerLevel;
|
|
105
|
+
// Hash the seed to create child seed (for deriving child nodes)
|
|
106
|
+
// From TreeKeyNode.java: mChildSeed = Crypto.getInstance().hashObject(zPrivateSeed);
|
|
107
|
+
// hashObject serializes as MiniData (length-prefixed) then hashes
|
|
108
|
+
this.childSeed = (0, javaStreamables_1.hashObject)(privateSeed);
|
|
109
|
+
if (treeKeyDebugEnabled) {
|
|
110
|
+
treeKeyLogger.debug(`[TreeKeyNode] Child seed (hashObject): ${(0, wots_1.hex)(this.childSeed)}`);
|
|
111
|
+
}
|
|
112
|
+
// Generate all Winternitz public key DIGESTS (32 bytes each)
|
|
113
|
+
// Java's Winternitz.getPublicKey() returns SHA3-256(full_key) = 32 bytes
|
|
114
|
+
// See WinternitzOTSignature.getPublicKey() lines 103-121: hashes full 1088B key, returns 32B digest
|
|
115
|
+
// TreeKeyNode.java line 53: MiniData pubkey = wots.getPublicKey() - stores the 32B digest
|
|
116
|
+
// MMRData.CreateMMRDataLeafNode(pubkey, MiniNumber.ZERO) - builds leaves from digests
|
|
117
|
+
this.publicKeyDigests = [];
|
|
118
|
+
for (let i = 0; i < keysPerLevel; i++) {
|
|
119
|
+
// Digest (32 bytes) - used for MMR tree, SignatureProof.leafPubkey, and address derivation
|
|
120
|
+
const pkDigest = (0, wots_1.derivePKdigest)(privateSeed, i, (0, params_1.getParamSet)());
|
|
121
|
+
this.publicKeyDigests.push(pkDigest);
|
|
122
|
+
// Log first few keys for debugging
|
|
123
|
+
if (treeKeyDebugEnabled && i < 3) {
|
|
124
|
+
treeKeyLogger.debug(`[TreeKeyNode] WOTS key[${i}] digest (32B): ${(0, wots_1.hex)(pkDigest)}`);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
if (treeKeyDebugEnabled) {
|
|
128
|
+
treeKeyLogger.debug(`[TreeKeyNode] Generated ${this.publicKeyDigests.length} WOTS key digests`);
|
|
129
|
+
const lastIdx = this.publicKeyDigests.length - 1;
|
|
130
|
+
treeKeyLogger.debug(`[TreeKeyNode] WOTS key[${lastIdx}] digest: ${(0, wots_1.hex)(this.publicKeyDigests[lastIdx])}`);
|
|
131
|
+
}
|
|
132
|
+
// Build MMR tree from 32-byte PUBLIC KEY DIGESTS (Java-compatible)
|
|
133
|
+
// Java's TreeKeyNode: MMRData.CreateMMRDataLeafNode(wots.getPublicKey(), ZERO)
|
|
134
|
+
// where getPublicKey() returns SHA3-256(full_key) = 32-byte DIGEST
|
|
135
|
+
this.mmrTree = mmr_1.MMRTree.fromPublicKeys(this.publicKeyDigests);
|
|
136
|
+
// Root public key = MMR root
|
|
137
|
+
const root = this.mmrTree.getRoot();
|
|
138
|
+
if (!root) {
|
|
139
|
+
throw new Error('Failed to compute MMR root');
|
|
140
|
+
}
|
|
141
|
+
this.rootPubkey = root.data;
|
|
142
|
+
if (treeKeyDebugEnabled) {
|
|
143
|
+
treeKeyLogger.debug(`[TreeKeyNode] MMR root (node public key): ${(0, wots_1.hex)(this.rootPubkey)}`);
|
|
144
|
+
treeKeyLogger.debug(`[TreeKeyNode] ========== INIT END ==========`);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Async factory method for TreeKeyNode with progress reporting
|
|
149
|
+
* Yields to event loop every few keys to keep UI responsive
|
|
150
|
+
*/
|
|
151
|
+
static async createWithProgress(privateSeed, keysPerLevel = exports.DEFAULT_KEYS_PER_LEVEL, onProgress) {
|
|
152
|
+
if (privateSeed.length !== 32) {
|
|
153
|
+
throw new Error('Private seed must be 32 bytes');
|
|
154
|
+
}
|
|
155
|
+
const node = Object.create(TreeKeyNode.prototype);
|
|
156
|
+
node.seed = privateSeed;
|
|
157
|
+
node.keysPerLevel = keysPerLevel;
|
|
158
|
+
node.childSeed = (0, javaStreamables_1.hashObject)(privateSeed);
|
|
159
|
+
node.publicKeyDigests = [];
|
|
160
|
+
node.childCache = new Map();
|
|
161
|
+
// Generate Winternitz public key DIGESTS with progress (32 bytes each)
|
|
162
|
+
// Java's Winternitz.getPublicKey() returns SHA3-256(full_key) = 32 bytes
|
|
163
|
+
// See WinternitzOTSignature.getPublicKey() lines 103-121: hashes full 1088B key, returns 32B digest
|
|
164
|
+
for (let i = 0; i < keysPerLevel; i++) {
|
|
165
|
+
// Digest (32 bytes) - used for MMR tree, SignatureProof.leafPubkey, and address derivation
|
|
166
|
+
const pkDigest = (0, wots_1.derivePKdigest)(privateSeed, i, (0, params_1.getParamSet)());
|
|
167
|
+
node.publicKeyDigests.push(pkDigest);
|
|
168
|
+
// Report progress every 4 keys and yield to event loop
|
|
169
|
+
if (onProgress && (i + 1) % 4 === 0) {
|
|
170
|
+
onProgress({
|
|
171
|
+
phase: 'wots_keys',
|
|
172
|
+
current: i + 1,
|
|
173
|
+
total: keysPerLevel,
|
|
174
|
+
message: `Generating signing key ${i + 1}/${keysPerLevel}`
|
|
175
|
+
});
|
|
176
|
+
// Yield to event loop to keep UI responsive
|
|
177
|
+
await new Promise(resolve => setTimeout(resolve, 0));
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
// Report MMR build phase
|
|
181
|
+
if (onProgress) {
|
|
182
|
+
onProgress({
|
|
183
|
+
phase: 'mmr_build',
|
|
184
|
+
current: 0,
|
|
185
|
+
total: 1,
|
|
186
|
+
message: 'Building secure Merkle tree...'
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
// Build MMR tree from 32-byte PUBLIC KEY DIGESTS (Java-compatible)
|
|
190
|
+
// Java's TreeKeyNode: MMRData.CreateMMRDataLeafNode(wots.getPublicKey(), ZERO)
|
|
191
|
+
// where getPublicKey() returns SHA3-256(full_key) = 32-byte DIGEST
|
|
192
|
+
node.mmrTree = mmr_1.MMRTree.fromPublicKeys(node.publicKeyDigests);
|
|
193
|
+
const root = node.mmrTree.getRoot();
|
|
194
|
+
if (!root) {
|
|
195
|
+
throw new Error('Failed to compute MMR root');
|
|
196
|
+
}
|
|
197
|
+
node.rootPubkey = root.data;
|
|
198
|
+
if (onProgress) {
|
|
199
|
+
onProgress({
|
|
200
|
+
phase: 'mmr_build',
|
|
201
|
+
current: 1,
|
|
202
|
+
total: 1,
|
|
203
|
+
message: 'Merkle tree complete'
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
return node;
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Get the public key for this tree node (MMR root of all 64 Winternitz keys)
|
|
210
|
+
*/
|
|
211
|
+
getPublicKey() {
|
|
212
|
+
return this.rootPubkey;
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Get the full Winternitz public key at a specific index (0-63)
|
|
216
|
+
* Returns the full L×32 byte public key (1088 bytes), derived on-demand
|
|
217
|
+
*
|
|
218
|
+
* NOTE: This is only used for local signature verification in tests.
|
|
219
|
+
* Java's Winternitz.getPublicKey() returns a 32-byte digest, not this.
|
|
220
|
+
* For production code, use getWOTSPublicKeyDigest() instead.
|
|
221
|
+
*
|
|
222
|
+
* @deprecated Use getWOTSPublicKeyDigest() for Minima compatibility
|
|
223
|
+
*/
|
|
224
|
+
getWOTSPublicKey(index) {
|
|
225
|
+
if (index < 0 || index >= this.keysPerLevel) {
|
|
226
|
+
throw new Error(`Key index ${index} out of range [0, ${this.keysPerLevel})`);
|
|
227
|
+
}
|
|
228
|
+
// Derive on-demand - expensive but only used for tests
|
|
229
|
+
return (0, wots_1.deriveFullPublicKey)(this.seed, index, (0, params_1.getParamSet)());
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Get the Winternitz public key digest at a specific index (0-63)
|
|
233
|
+
* Returns the 32-byte SHA3 hash of the full public key
|
|
234
|
+
*/
|
|
235
|
+
getWOTSPublicKeyDigest(index) {
|
|
236
|
+
if (index < 0 || index >= this.keysPerLevel) {
|
|
237
|
+
throw new Error(`Key index ${index} out of range [0, ${this.keysPerLevel})`);
|
|
238
|
+
}
|
|
239
|
+
return this.publicKeyDigests[index];
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Get the MMR proof for a specific key index
|
|
243
|
+
*/
|
|
244
|
+
getProof(keyIndex) {
|
|
245
|
+
return this.mmrTree.getProof(keyIndex);
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Sign data with a specific key from this node
|
|
249
|
+
* Returns a SignatureProof containing the 32-byte leaf pubkey DIGEST, signature, and MMR proof
|
|
250
|
+
*
|
|
251
|
+
* CRITICAL: Java's WinternitzOTSignature.getSignature() ALWAYS hashes the message first,
|
|
252
|
+
* regardless of input length. From BouncyCastle WinternitzOTSignature.java lines 137-138:
|
|
253
|
+
* messDigestOTS.update(message, 0, message.length);
|
|
254
|
+
* messDigestOTS.doFinal(hash, 0);
|
|
255
|
+
*
|
|
256
|
+
* We MUST always hash to match Java verification, which also always hashes.
|
|
257
|
+
*
|
|
258
|
+
* CRITICAL FIX (January 2026): leafPubkey is the 32-byte WOTS public key DIGEST.
|
|
259
|
+
* Java's Winternitz.getPublicKey() returns SHA3-256(full_key) = 32 bytes!
|
|
260
|
+
* Previous bug: We stored 1088-byte full keys, Java expected 32-byte digests → verification failed.
|
|
261
|
+
*/
|
|
262
|
+
sign(keyIndex, data) {
|
|
263
|
+
if (keyIndex < 0 || keyIndex >= this.keysPerLevel) {
|
|
264
|
+
throw new Error(`Key index ${keyIndex} out of range [0, ${this.keysPerLevel})`);
|
|
265
|
+
}
|
|
266
|
+
if (treeKeyDebugEnabled) {
|
|
267
|
+
treeKeyLogger.debug(`[TreeKeyNode.sign] ========== SIGN START ==========`);
|
|
268
|
+
treeKeyLogger.debug(`[TreeKeyNode.sign] keyIndex: ${keyIndex}`);
|
|
269
|
+
treeKeyLogger.debug(`[TreeKeyNode.sign] input data (${data.length}B): ${(0, wots_1.hex)(data).substring(0, 64)}${data.length > 32 ? '...' : ''}`);
|
|
270
|
+
}
|
|
271
|
+
// Get the 32-byte Winternitz public key DIGEST for SignatureProof
|
|
272
|
+
// CRITICAL FIX: Java's Winternitz.getPublicKey() returns SHA3-256(full_key) = 32 bytes!
|
|
273
|
+
// NOT the 1088-byte full key! This was the bug causing "allsignaturesvalid":false errors.
|
|
274
|
+
const leafPubkey = this.publicKeyDigests[keyIndex];
|
|
275
|
+
if (treeKeyDebugEnabled) {
|
|
276
|
+
treeKeyLogger.debug(`[TreeKeyNode.sign] leafPubkey (${leafPubkey.length}B DIGEST): ${(0, wots_1.hex)(leafPubkey)}`);
|
|
277
|
+
}
|
|
278
|
+
// CRITICAL: Do NOT pre-hash here! wotsSign() now handles internal hashing (matching Java/BouncyCastle).
|
|
279
|
+
// Java's WinternitzOTSignature.getSignature() hashes internally, so wotsSign() does too.
|
|
280
|
+
// Call sites pass the same 32-byte values Java passes:
|
|
281
|
+
// - For TX signing: the 32-byte transaction digest
|
|
282
|
+
// - For parent→child: the 32-byte childRoot (MMR root of child proof)
|
|
283
|
+
// WOTS hashes once internally - this is by design for Minima compatibility.
|
|
284
|
+
if (treeKeyDebugEnabled) {
|
|
285
|
+
treeKeyLogger.debug(`[TreeKeyNode.sign] dataToSign (raw input, WOTS hashes internally): ${(0, wots_1.hex)(data)}`);
|
|
286
|
+
}
|
|
287
|
+
// Sign data directly - wotsSign() handles internal hashing
|
|
288
|
+
const signature = (0, wots_1.wotsSign)(this.seed, keyIndex, data, (0, params_1.getParamSet)());
|
|
289
|
+
if (treeKeyDebugEnabled) {
|
|
290
|
+
treeKeyLogger.debug(`[TreeKeyNode.sign] signature (${signature.length}B): ${(0, wots_1.hex)(signature).substring(0, 64)}...${(0, wots_1.hex)(signature).substring((0, wots_1.hex)(signature).length - 32)}`);
|
|
291
|
+
}
|
|
292
|
+
// Get the MMR proof for this key
|
|
293
|
+
const mmrProof = this.getProof(keyIndex);
|
|
294
|
+
if (treeKeyDebugEnabled) {
|
|
295
|
+
treeKeyLogger.debug(`[TreeKeyNode.sign] MMR proof chunks: ${mmrProof.chunks.length}`);
|
|
296
|
+
treeKeyLogger.debug(`[TreeKeyNode.sign] ========== SIGN END ==========`);
|
|
297
|
+
}
|
|
298
|
+
return { leafPubkey, signature, mmrProof };
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Create a child TreeKeyNode at the specified index
|
|
302
|
+
* Matches TreeKeyNode.java getChild()
|
|
303
|
+
*
|
|
304
|
+
* PERFORMANCE FIX: Child nodes are now cached to avoid regenerating
|
|
305
|
+
* 64 WOTS keys on every getChild() call. This is critical for address
|
|
306
|
+
* derivation performance where getChild() is called 64 times.
|
|
307
|
+
*/
|
|
308
|
+
getChild(childIndex) {
|
|
309
|
+
if (childIndex < 0 || childIndex >= this.keysPerLevel) {
|
|
310
|
+
throw new Error(`Child index ${childIndex} out of range [0, ${this.keysPerLevel})`);
|
|
311
|
+
}
|
|
312
|
+
// Check cache first
|
|
313
|
+
const cached = this.childCache.get(childIndex);
|
|
314
|
+
if (cached) {
|
|
315
|
+
if (treeKeyDebugEnabled) {
|
|
316
|
+
treeKeyLogger.debug(`[TreeKeyNode.getChild] Using cached child at index ${childIndex}`);
|
|
317
|
+
}
|
|
318
|
+
return cached;
|
|
319
|
+
}
|
|
320
|
+
if (treeKeyDebugEnabled) {
|
|
321
|
+
treeKeyLogger.debug(`[TreeKeyNode.getChild] Creating child at index ${childIndex}`);
|
|
322
|
+
treeKeyLogger.debug(`[TreeKeyNode.getChild] Parent childSeed: ${(0, wots_1.hex)(this.childSeed)}`);
|
|
323
|
+
}
|
|
324
|
+
// From TreeKeyNode.java:
|
|
325
|
+
// MiniData seed = Crypto.getInstance().hashAllObjects(new MiniNumber(zChild), mChildSeed);
|
|
326
|
+
const childSeed = (0, javaStreamables_1.deriveChainSeedJava)(this.childSeed, childIndex);
|
|
327
|
+
if (treeKeyDebugEnabled) {
|
|
328
|
+
treeKeyLogger.debug(`[TreeKeyNode.getChild] Derived childSeed: ${(0, wots_1.hex)(childSeed)}`);
|
|
329
|
+
}
|
|
330
|
+
const child = new TreeKeyNode(childSeed, this.keysPerLevel);
|
|
331
|
+
if (treeKeyDebugEnabled) {
|
|
332
|
+
treeKeyLogger.debug(`[TreeKeyNode.getChild] Child public key: ${(0, wots_1.hex)(child.getPublicKey())}`);
|
|
333
|
+
}
|
|
334
|
+
// Cache for future use
|
|
335
|
+
this.childCache.set(childIndex, child);
|
|
336
|
+
return child;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
exports.TreeKeyNode = TreeKeyNode;
|
|
340
|
+
/**
|
|
341
|
+
* TreeKey - Full hierarchical key tree with multiple levels
|
|
342
|
+
*
|
|
343
|
+
* Matches TreeKey.java:
|
|
344
|
+
* - Default: 3 levels x 64 keys = 262,144 one-time signatures
|
|
345
|
+
* - Tracks usage count to determine which key to use
|
|
346
|
+
* - Produces multi-level signatures
|
|
347
|
+
*/
|
|
348
|
+
class TreeKey {
|
|
349
|
+
constructor(privateSeed, keysPerLevel = exports.DEFAULT_KEYS_PER_LEVEL, levels = exports.DEFAULT_LEVELS) {
|
|
350
|
+
this.uses = 0;
|
|
351
|
+
/**
|
|
352
|
+
* Parent-child signature cache for efficiency
|
|
353
|
+
* Key format: "l1" for root->level1, "l1,l2" for level1->level2
|
|
354
|
+
* Value: SignatureProof for parent signing child's pubkey
|
|
355
|
+
*/
|
|
356
|
+
this.parentChildSigCache = new Map();
|
|
357
|
+
if (privateSeed.length !== 32) {
|
|
358
|
+
throw new Error('Private seed must be 32 bytes');
|
|
359
|
+
}
|
|
360
|
+
if (treeKeyDebugEnabled) {
|
|
361
|
+
treeKeyLogger.debug(`[TreeKey] ========== WALLET INIT START ==========`);
|
|
362
|
+
treeKeyLogger.debug(`[TreeKey] Private seed: ${(0, wots_1.hex)(privateSeed)}`);
|
|
363
|
+
treeKeyLogger.debug(`[TreeKey] Levels: ${levels}, Keys per level: ${keysPerLevel}`);
|
|
364
|
+
treeKeyLogger.debug(`[TreeKey] Total capacity: ${Math.pow(keysPerLevel, levels)} signatures`);
|
|
365
|
+
}
|
|
366
|
+
this.privateSeed = privateSeed;
|
|
367
|
+
this.levels = levels;
|
|
368
|
+
this.keysPerLevel = keysPerLevel;
|
|
369
|
+
// Initialize root node
|
|
370
|
+
this.root = new TreeKeyNode(privateSeed, keysPerLevel);
|
|
371
|
+
this.publicKey = this.root.getPublicKey();
|
|
372
|
+
if (treeKeyDebugEnabled) {
|
|
373
|
+
treeKeyLogger.debug(`[TreeKey] Root public key: ${(0, wots_1.hex)(this.publicKey)}`);
|
|
374
|
+
treeKeyLogger.debug(`[TreeKey] ========== WALLET INIT END ==========`);
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Async factory method for TreeKey with progress reporting
|
|
379
|
+
* Reports progress as the root TreeKeyNode generates its 64 signing keys
|
|
380
|
+
*/
|
|
381
|
+
static async createWithProgress(privateSeed, keysPerLevel = exports.DEFAULT_KEYS_PER_LEVEL, levels = exports.DEFAULT_LEVELS, onProgress) {
|
|
382
|
+
if (privateSeed.length !== 32) {
|
|
383
|
+
throw new Error('Private seed must be 32 bytes');
|
|
384
|
+
}
|
|
385
|
+
const treeKey = Object.create(TreeKey.prototype);
|
|
386
|
+
treeKey.privateSeed = privateSeed;
|
|
387
|
+
treeKey.levels = levels;
|
|
388
|
+
treeKey.keysPerLevel = keysPerLevel;
|
|
389
|
+
treeKey.uses = 0;
|
|
390
|
+
treeKey.parentChildSigCache = new Map();
|
|
391
|
+
// Create root node with progress reporting
|
|
392
|
+
treeKey.root = await TreeKeyNode.createWithProgress(privateSeed, keysPerLevel, onProgress);
|
|
393
|
+
treeKey.publicKey = treeKey.root.getPublicKey();
|
|
394
|
+
if (onProgress) {
|
|
395
|
+
onProgress({
|
|
396
|
+
phase: 'complete',
|
|
397
|
+
current: keysPerLevel,
|
|
398
|
+
total: keysPerLevel,
|
|
399
|
+
message: 'Key tree ready'
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
return treeKey;
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* Get the root TreeKeyNode (for internal use)
|
|
406
|
+
*/
|
|
407
|
+
getRootNode() {
|
|
408
|
+
return this.root;
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* Get the root public key (for watermark tracking)
|
|
412
|
+
*/
|
|
413
|
+
getRootPublicKey() {
|
|
414
|
+
return this.publicKey;
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* Get the wallet's public key (root of the key tree)
|
|
418
|
+
*/
|
|
419
|
+
getPublicKey() {
|
|
420
|
+
return this.publicKey;
|
|
421
|
+
}
|
|
422
|
+
/**
|
|
423
|
+
* Get the maximum number of signatures this tree can produce
|
|
424
|
+
*/
|
|
425
|
+
getMaxUses() {
|
|
426
|
+
return Math.pow(this.keysPerLevel, this.levels);
|
|
427
|
+
}
|
|
428
|
+
/**
|
|
429
|
+
* Get current usage count
|
|
430
|
+
*/
|
|
431
|
+
getUses() {
|
|
432
|
+
return this.uses;
|
|
433
|
+
}
|
|
434
|
+
/**
|
|
435
|
+
* Set the usage counter (for resuming from a known state)
|
|
436
|
+
*/
|
|
437
|
+
setUses(uses) {
|
|
438
|
+
this.uses = uses;
|
|
439
|
+
}
|
|
440
|
+
/**
|
|
441
|
+
* Generate cache key for parent-child signature
|
|
442
|
+
* @param path - Array of indices leading to the child (e.g., [l1] or [l1, l2])
|
|
443
|
+
*/
|
|
444
|
+
getCacheKey(path) {
|
|
445
|
+
return path.join(',');
|
|
446
|
+
}
|
|
447
|
+
/**
|
|
448
|
+
* Check if a parent-child signature is cached
|
|
449
|
+
* @param path - Array of indices (e.g., [l1] for root->level1)
|
|
450
|
+
*/
|
|
451
|
+
hasParentChildSig(path) {
|
|
452
|
+
return this.parentChildSigCache.has(this.getCacheKey(path));
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* Get a cached parent-child signature
|
|
456
|
+
* @param path - Array of indices (e.g., [l1] for root->level1)
|
|
457
|
+
*/
|
|
458
|
+
getParentChildSig(path) {
|
|
459
|
+
return this.parentChildSigCache.get(this.getCacheKey(path));
|
|
460
|
+
}
|
|
461
|
+
/**
|
|
462
|
+
* Cache a parent-child signature for reuse
|
|
463
|
+
* This allows the same signature to be reused across multiple signing operations
|
|
464
|
+
*
|
|
465
|
+
* @param path - Array of indices leading to the child (e.g., [l1] or [l1, l2])
|
|
466
|
+
* @param sig - SignatureProof from parent signing child's public key
|
|
467
|
+
*/
|
|
468
|
+
setParentChildSig(path, sig) {
|
|
469
|
+
this.parentChildSigCache.set(this.getCacheKey(path), sig);
|
|
470
|
+
}
|
|
471
|
+
/**
|
|
472
|
+
* Get all cached parent-child signatures (for serialization/persistence)
|
|
473
|
+
*/
|
|
474
|
+
getCachedSignatures() {
|
|
475
|
+
return new Map(this.parentChildSigCache);
|
|
476
|
+
}
|
|
477
|
+
/**
|
|
478
|
+
* Restore cached signatures (for hydrating from persistence)
|
|
479
|
+
*/
|
|
480
|
+
restoreCachedSignatures(cache) {
|
|
481
|
+
this.parentChildSigCache = new Map(cache);
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* Convert a usage number to the path through the tree
|
|
485
|
+
* Matches TreeKey.java baseConversion()
|
|
486
|
+
*
|
|
487
|
+
* For uses=0: [0,0,0]
|
|
488
|
+
* For uses=1: [0,0,1]
|
|
489
|
+
* For uses=64: [0,1,0]
|
|
490
|
+
* etc.
|
|
491
|
+
*/
|
|
492
|
+
baseConversion(num) {
|
|
493
|
+
const result = [];
|
|
494
|
+
let counter = num;
|
|
495
|
+
while (counter !== 0) {
|
|
496
|
+
const div = Math.floor(counter / this.keysPerLevel);
|
|
497
|
+
const remain = counter - (div * this.keysPerLevel);
|
|
498
|
+
result.push(remain);
|
|
499
|
+
counter = div;
|
|
500
|
+
}
|
|
501
|
+
// Pad to required levels
|
|
502
|
+
while (result.length < this.levels) {
|
|
503
|
+
result.push(0);
|
|
504
|
+
}
|
|
505
|
+
// Reverse to get [addressIndex, l1, l2] order
|
|
506
|
+
result.reverse();
|
|
507
|
+
return result;
|
|
508
|
+
}
|
|
509
|
+
/**
|
|
510
|
+
* Sign data with the current key and increment usage
|
|
511
|
+
*
|
|
512
|
+
* Matches TreeKey.java sign():
|
|
513
|
+
* - Determines path through tree based on usage count
|
|
514
|
+
* - Each level's key signs the next level's root public key
|
|
515
|
+
* - Final level signs the actual data
|
|
516
|
+
*
|
|
517
|
+
* CRITICAL FIX (January 2026): Build proofs bottom-up to sign child's getRootPublicKey()
|
|
518
|
+
*
|
|
519
|
+
* Java's TreeKey.verify() verifies non-leaf signatures against childsig.getRootPublicKey(),
|
|
520
|
+
* which is the 32-byte MMR root computed from the NEXT proof's leafPubkey + MMRproof.
|
|
521
|
+
*
|
|
522
|
+
* Uses parent-child signature caching for efficiency:
|
|
523
|
+
* - Parent-child signatures are cached and reused
|
|
524
|
+
* - Only the final data signature is computed fresh each time
|
|
525
|
+
*/
|
|
526
|
+
sign(data) {
|
|
527
|
+
if (this.uses >= this.getMaxUses()) {
|
|
528
|
+
throw new Error('No more keys available (tree exhausted)');
|
|
529
|
+
}
|
|
530
|
+
// Get the path through the tree
|
|
531
|
+
const path = this.baseConversion(this.uses);
|
|
532
|
+
// Navigate to all nodes first
|
|
533
|
+
const nodes = [this.root];
|
|
534
|
+
let currentNode = this.root;
|
|
535
|
+
for (let i = 0; i < this.levels - 1; i++) {
|
|
536
|
+
currentNode = currentNode.getChild(path[i]);
|
|
537
|
+
nodes.push(currentNode);
|
|
538
|
+
}
|
|
539
|
+
// nodes = [root, L1, L2] for a 3-level tree
|
|
540
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
541
|
+
// BUILD PROOFS BOTTOM-UP: Start from leaf, work up to root
|
|
542
|
+
// This ensures we sign exactly what Java's verification will compute.
|
|
543
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
544
|
+
const proofs = new Array(this.levels);
|
|
545
|
+
// STEP 1: Create leaf proof FIRST (signs actual data)
|
|
546
|
+
const leafDepth = this.levels - 1;
|
|
547
|
+
const leafNode = nodes[leafDepth];
|
|
548
|
+
const leafKeyIndex = path[leafDepth];
|
|
549
|
+
const leafProof = leafNode.sign(leafKeyIndex, data);
|
|
550
|
+
proofs[leafDepth] = leafProof;
|
|
551
|
+
// STEP 2: Work backwards, each parent signs childProof.getRootPublicKey()
|
|
552
|
+
for (let depth = this.levels - 2; depth >= 0; depth--) {
|
|
553
|
+
const parentNode = nodes[depth];
|
|
554
|
+
const keyIndex = path[depth];
|
|
555
|
+
const childProof = proofs[depth + 1];
|
|
556
|
+
const childRoot = getRootPublicKey(childProof);
|
|
557
|
+
// Cache key includes full path to ensure uniqueness
|
|
558
|
+
const cachePath = path.slice(0, depth + 2);
|
|
559
|
+
let sigProof = this.getParentChildSig(cachePath);
|
|
560
|
+
if (!sigProof) {
|
|
561
|
+
// Not cached: compute and cache
|
|
562
|
+
sigProof = parentNode.sign(keyIndex, childRoot); // Sign the 32-byte MMR root!
|
|
563
|
+
this.setParentChildSig(cachePath, sigProof);
|
|
564
|
+
}
|
|
565
|
+
proofs[depth] = sigProof;
|
|
566
|
+
}
|
|
567
|
+
// Increment usage counter
|
|
568
|
+
this.uses++;
|
|
569
|
+
return { proofs };
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* Get the public key for a level-1 address (single index)
|
|
573
|
+
* This is the MMR root of the level-1 TreeKeyNode's 64 Winternitz keys.
|
|
574
|
+
*
|
|
575
|
+
* Use this for wallet addresses where each address = one level-1 node.
|
|
576
|
+
*
|
|
577
|
+
* @param l1 - Level 1 index (0-63, corresponds to wallet address index)
|
|
578
|
+
* @returns 32-byte MMR root public key for SIGNEDBY scripts
|
|
579
|
+
*/
|
|
580
|
+
getAddressPublicKey(l1) {
|
|
581
|
+
// Get level-1 child node's public key (MMR root of its 64 WOTS keys)
|
|
582
|
+
const level1Node = this.root.getChild(l1);
|
|
583
|
+
return level1Node.getPublicKey();
|
|
584
|
+
}
|
|
585
|
+
/**
|
|
586
|
+
* Get the public key for a specific signing key at tree index (l1, l2)
|
|
587
|
+
* This navigates to the level-2 node for signing operations.
|
|
588
|
+
*
|
|
589
|
+
* @param l1 - Level 1 index (address)
|
|
590
|
+
* @param l2 - Level 2 index (signing key within address)
|
|
591
|
+
* @returns 32-byte MMR root public key of level-2 node
|
|
592
|
+
*/
|
|
593
|
+
getSigningNodePublicKey(l1, l2) {
|
|
594
|
+
// Navigate to level 2 node
|
|
595
|
+
const level1Node = this.root.getChild(l1);
|
|
596
|
+
const level2Node = level1Node.getChild(l2);
|
|
597
|
+
return level2Node.getPublicKey();
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
exports.TreeKey = TreeKey;
|
|
601
|
+
/**
|
|
602
|
+
* Verify a tree signature against expected public key and data
|
|
603
|
+
*
|
|
604
|
+
* Matches TreeKey.java verify():
|
|
605
|
+
* - First proof's computed root must match expected public key
|
|
606
|
+
* - Each intermediate proof must sign the next level's root
|
|
607
|
+
* - Final proof must verify against the actual data
|
|
608
|
+
*/
|
|
609
|
+
function verifyTreeSignature(expectedPubkey, data, signature) {
|
|
610
|
+
const { proofs } = signature;
|
|
611
|
+
if (proofs.length === 0) {
|
|
612
|
+
return false;
|
|
613
|
+
}
|
|
614
|
+
// Import wotsVerify for verification
|
|
615
|
+
const { wotsVerify } = require('./wots');
|
|
616
|
+
const paramSet = (0, params_1.getParamSet)();
|
|
617
|
+
for (let depth = 0; depth < proofs.length; depth++) {
|
|
618
|
+
const proof = proofs[depth];
|
|
619
|
+
// Compute the root public key from this proof
|
|
620
|
+
const rootPubkey = getRootPublicKey(proof);
|
|
621
|
+
// First level: must match expected public key
|
|
622
|
+
if (depth === 0) {
|
|
623
|
+
for (let i = 0; i < expectedPubkey.length; i++) {
|
|
624
|
+
if (rootPubkey[i] !== expectedPubkey[i]) {
|
|
625
|
+
return false;
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
// Determine what was signed
|
|
630
|
+
let signedData;
|
|
631
|
+
if (depth === proofs.length - 1) {
|
|
632
|
+
// Final level: signed the actual data
|
|
633
|
+
signedData = data;
|
|
634
|
+
}
|
|
635
|
+
else {
|
|
636
|
+
// Intermediate level: signed the next level's root public key
|
|
637
|
+
signedData = getRootPublicKey(proofs[depth + 1]);
|
|
638
|
+
}
|
|
639
|
+
// Verify the Winternitz signature
|
|
640
|
+
// Use wotsVerifyDigest since leafPubkey is now a 32-byte digest (not 1088-byte full key)
|
|
641
|
+
if (!(0, wots_1.wotsVerifyDigest)(proof.signature, signedData, proof.leafPubkey, paramSet)) {
|
|
642
|
+
return false;
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
return true;
|
|
646
|
+
}
|
|
647
|
+
/**
|
|
648
|
+
* Serialize a TreeSignature to bytes
|
|
649
|
+
*
|
|
650
|
+
* Uses Streamable.writeSignature() for byte-exact compatibility
|
|
651
|
+
* with Java's Signature.writeDataStream().
|
|
652
|
+
*/
|
|
653
|
+
function serializeTreeSignature(sig) {
|
|
654
|
+
// Convert to Streamable format (adds blockTime to MMRProof)
|
|
655
|
+
const streamableSig = {
|
|
656
|
+
proofs: sig.proofs.map(proof => ({
|
|
657
|
+
leafPubkey: proof.leafPubkey,
|
|
658
|
+
signature: proof.signature,
|
|
659
|
+
mmrProof: {
|
|
660
|
+
blockTime: 0n, // Default for compatibility
|
|
661
|
+
chunks: proof.mmrProof.chunks
|
|
662
|
+
}
|
|
663
|
+
}))
|
|
664
|
+
};
|
|
665
|
+
// Use canonical serializer for byte-exact Java compatibility
|
|
666
|
+
return (0, Streamable_1.writeSignature)(streamableSig);
|
|
667
|
+
}
|
|
668
|
+
/**
|
|
669
|
+
* Deserialize a TreeSignature from bytes
|
|
670
|
+
*
|
|
671
|
+
* Matches Java's Signature.readDataStream():
|
|
672
|
+
* - Number of proofs: MiniNumber format
|
|
673
|
+
* - Each SignatureProof: MiniData(pubkey) + MiniData(signature) + MMRProof
|
|
674
|
+
*/
|
|
675
|
+
function deserializeTreeSignature(data) {
|
|
676
|
+
let offset = 0;
|
|
677
|
+
// Read MiniNumber for proof count
|
|
678
|
+
// Format: [scale: 1 byte] [length: 1 byte] [data: N bytes]
|
|
679
|
+
const scale = data[offset];
|
|
680
|
+
const numBytesLen = data[offset + 1];
|
|
681
|
+
offset += 2;
|
|
682
|
+
// Read the number bytes (big-endian)
|
|
683
|
+
let numProofs = 0;
|
|
684
|
+
for (let i = 0; i < numBytesLen; i++) {
|
|
685
|
+
numProofs = (numProofs << 8) | data[offset + i];
|
|
686
|
+
}
|
|
687
|
+
offset += numBytesLen;
|
|
688
|
+
const proofs = [];
|
|
689
|
+
for (let i = 0; i < numProofs; i++) {
|
|
690
|
+
// Leaf pubkey - MiniData format (4-byte length prefix + data)
|
|
691
|
+
const pubkeyLen = (data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3];
|
|
692
|
+
offset += 4;
|
|
693
|
+
const leafPubkey = data.slice(offset, offset + pubkeyLen);
|
|
694
|
+
offset += pubkeyLen;
|
|
695
|
+
// Signature - MiniData format (4-byte length prefix + data)
|
|
696
|
+
const sigLen = (data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3];
|
|
697
|
+
offset += 4;
|
|
698
|
+
const signature = data.slice(offset, offset + sigLen);
|
|
699
|
+
offset += sigLen;
|
|
700
|
+
// MMR proof - new format returns { proof, blockTime }
|
|
701
|
+
const { proof: mmrProof } = (0, mmr_1.deserializeMMRProof)(data.slice(offset));
|
|
702
|
+
// Calculate how many bytes the MMR proof consumed
|
|
703
|
+
// Format: blockTime (MiniNumber: 3 bytes for 0) + length (MiniNumber: 3 bytes for count)
|
|
704
|
+
// + each chunk (1 byte isLeft + 32 bytes hash + 3 bytes value MiniNumber)
|
|
705
|
+
const mmrProofLen = 3 + 3 + (mmrProof.chunks.length * (1 + 32 + 3));
|
|
706
|
+
offset += mmrProofLen;
|
|
707
|
+
proofs.push({ leafPubkey, signature, mmrProof });
|
|
708
|
+
}
|
|
709
|
+
return { proofs };
|
|
710
|
+
}
|
|
711
|
+
/**
|
|
712
|
+
* ============================================================================
|
|
713
|
+
* PER-ADDRESS TREEKEY FACTORY
|
|
714
|
+
* ============================================================================
|
|
715
|
+
*
|
|
716
|
+
* Minima Wallet.createNewKey() creates independent TreeKeys per address:
|
|
717
|
+
* MiniData modifier = new MiniData(new BigInteger(Integer.toString(numkeys)));
|
|
718
|
+
* MiniData privseed = Crypto.getInstance().hashObjects(baseSeed, modifier);
|
|
719
|
+
* TreeKey treekey = TreeKey.createDefault(privseed);
|
|
720
|
+
*
|
|
721
|
+
* Each address gets its own TreeKey with:
|
|
722
|
+
* - Unique seed derived from baseSeed + addressIndex
|
|
723
|
+
* - Size=64, depth=3 (matching TreeKey.createDefault)
|
|
724
|
+
* - 4096 one-time signatures per address (64×64)
|
|
725
|
+
*
|
|
726
|
+
* Total wallet capacity: 64 addresses × 4096 signatures = 262,144 signatures
|
|
727
|
+
* ============================================================================
|
|
728
|
+
*/
|
|
729
|
+
/**
|
|
730
|
+
* Create a per-address TreeKey matching Minima Wallet.createNewKey()
|
|
731
|
+
*
|
|
732
|
+
* @param baseSeed - 32-byte wallet base seed (from mnemonic)
|
|
733
|
+
* @param addressIndex - Address index (0-63)
|
|
734
|
+
* @returns TreeKey for this address with size=64, depth=3
|
|
735
|
+
*/
|
|
736
|
+
function createPerAddressTreeKey(baseSeed, addressIndex) {
|
|
737
|
+
const addressSeed = (0, javaStreamables_1.derivePerAddressSeed)(baseSeed, addressIndex);
|
|
738
|
+
return new TreeKey(addressSeed, 64, 3);
|
|
739
|
+
}
|
|
740
|
+
/**
|
|
741
|
+
* Async version with progress reporting for UI
|
|
742
|
+
*
|
|
743
|
+
* @param baseSeed - 32-byte wallet base seed
|
|
744
|
+
* @param addressIndex - Address index (0-63)
|
|
745
|
+
* @param onProgress - Optional progress callback
|
|
746
|
+
* @returns Promise resolving to TreeKey for this address
|
|
747
|
+
*/
|
|
748
|
+
async function createPerAddressTreeKeyAsync(baseSeed, addressIndex, onProgress) {
|
|
749
|
+
const addressSeed = (0, javaStreamables_1.derivePerAddressSeed)(baseSeed, addressIndex);
|
|
750
|
+
return TreeKey.createWithProgress(addressSeed, 64, 3, onProgress);
|
|
751
|
+
}
|
|
752
|
+
/**
|
|
753
|
+
* Derive address public key from base seed and address index
|
|
754
|
+
*
|
|
755
|
+
* This is the fast path for getting an address public key without
|
|
756
|
+
* needing to construct the full TreeKey. Useful for address derivation
|
|
757
|
+
* during wallet initialization.
|
|
758
|
+
*
|
|
759
|
+
* @param baseSeed - 32-byte wallet base seed
|
|
760
|
+
* @param addressIndex - Address index (0-63)
|
|
761
|
+
* @returns 32-byte address public key (MMR root of per-address TreeKey)
|
|
762
|
+
*/
|
|
763
|
+
function deriveAddressPublicKey(baseSeed, addressIndex) {
|
|
764
|
+
const treeKey = createPerAddressTreeKey(baseSeed, addressIndex);
|
|
765
|
+
return treeKey.getPublicKey();
|
|
766
|
+
}
|
|
767
|
+
/**
|
|
768
|
+
* Get the address public key from a per-address TreeKey
|
|
769
|
+
*
|
|
770
|
+
* In the per-address architecture, each address has its own TreeKey,
|
|
771
|
+
* and the address public key is simply the TreeKey's root public key.
|
|
772
|
+
*
|
|
773
|
+
* @param treeKey - Per-address TreeKey
|
|
774
|
+
* @returns 32-byte address public key (TreeKey root)
|
|
775
|
+
*/
|
|
776
|
+
function getPerAddressPublicKey(treeKey) {
|
|
777
|
+
return treeKey.getPublicKey();
|
|
778
|
+
}
|