@bitcoinerlab/descriptors 2.3.6 → 3.0.1

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.
@@ -0,0 +1,515 @@
1
+ "use strict";
2
+ // Distributed under the MIT software license
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.buildTapTreeInfo = buildTapTreeInfo;
5
+ exports.tapTreeInfoToScriptTree = tapTreeInfoToScriptTree;
6
+ exports.buildTaprootLeafPsbtMetadata = buildTaprootLeafPsbtMetadata;
7
+ exports.buildTaprootBip32Derivations = buildTaprootBip32Derivations;
8
+ exports.normalizeTaprootPubkey = normalizeTaprootPubkey;
9
+ exports.compileSortedMultiAExpandedExpression = compileSortedMultiAExpandedExpression;
10
+ exports.collectTaprootLeafSatisfactions = collectTaprootLeafSatisfactions;
11
+ exports.selectBestTaprootLeafSatisfaction = selectBestTaprootLeafSatisfaction;
12
+ exports.collectTapTreePubkeys = collectTapTreePubkeys;
13
+ exports.satisfyTapTree = satisfyTapTree;
14
+ const bitcoinjs_lib_1 = require("bitcoinjs-lib");
15
+ const bitcoinjs_lib_internals_1 = require("./bitcoinjs-lib-internals");
16
+ const varuint_bitcoin_1 = require("varuint-bitcoin");
17
+ const uint8array_tools_1 = require("uint8array-tools");
18
+ const miniscript_1 = require("./miniscript");
19
+ const tapTree_1 = require("./tapTree");
20
+ const resourceLimits_1 = require("./resourceLimits");
21
+ const TAPROOT_LEAF_VERSION_TAPSCRIPT = 0xc0;
22
+ function expandTaprootMiniscript({ miniscript, network = bitcoinjs_lib_1.networks.bitcoin, BIP32, ECPair }) {
23
+ return (0, miniscript_1.expandMiniscript)({
24
+ miniscript,
25
+ isSegwit: true,
26
+ isTaproot: true,
27
+ network,
28
+ BIP32,
29
+ ECPair
30
+ });
31
+ }
32
+ /**
33
+ * Compiles a taproot miniscript tree into per-leaf metadata.
34
+ * Each leaf contains expanded expression metadata, key expansion map,
35
+ * compiled tapscript and leaf version. This keeps the taproot script-path data
36
+ * ready for satisfactions and witness building.
37
+ *
38
+ * `leafExpansionOverride` allows descriptor-level script expressions to provide:
39
+ * - user-facing expanded expression metadata (for selector/template use), and
40
+ * - custom expansion map and tapscript bytes for compilation.
41
+ *
42
+ * Example: sortedmulti_a can expose `expandedExpression=sortedmulti_a(...)`
43
+ * while providing a tapscript already compiled.
44
+ */
45
+ function buildTapTreeInfo({ tapTree, network = bitcoinjs_lib_1.networks.bitcoin, BIP32, ECPair, leafExpansionOverride }) {
46
+ // Defensive: parseTapTreeExpression() already enforces this for descriptor
47
+ // strings, but buildTapTreeInfo is exported and can be called directly.
48
+ (0, tapTree_1.assertTapTreeDepth)(tapTree);
49
+ if ('expression' in tapTree) {
50
+ // Tap-tree leaves store generic descriptor expressions. Most leaves are
51
+ // miniscript fragments, but descriptor-level script expressions (such as
52
+ // sortedmulti_a) can also appear and be normalized through
53
+ // `leafExpansionOverride`.
54
+ const expression = tapTree.expression;
55
+ const override = leafExpansionOverride(expression);
56
+ let expandedExpression;
57
+ let expandedMiniscript;
58
+ let expansionMap;
59
+ let tapScript;
60
+ if (override) {
61
+ // Descriptor-level expression overrides (e.g. sortedmulti_a) preserve a
62
+ // user-facing expanded expression while allowing custom compilation.
63
+ expandedExpression = override.expandedExpression;
64
+ expansionMap = override.expansionMap;
65
+ tapScript = override.tapScript;
66
+ }
67
+ else {
68
+ const expanded = expandTaprootMiniscript({
69
+ miniscript: expression,
70
+ network,
71
+ BIP32,
72
+ ECPair
73
+ });
74
+ expandedExpression = expanded.expandedMiniscript;
75
+ expandedMiniscript = expanded.expandedMiniscript;
76
+ expansionMap = expanded.expansionMap;
77
+ tapScript = (0, miniscript_1.miniscript2Script)({
78
+ expandedMiniscript: expanded.expandedMiniscript,
79
+ expansionMap,
80
+ tapscript: true
81
+ });
82
+ }
83
+ return {
84
+ expression,
85
+ expandedExpression,
86
+ ...(expandedMiniscript !== undefined ? { expandedMiniscript } : {}),
87
+ expansionMap,
88
+ tapScript,
89
+ version: TAPROOT_LEAF_VERSION_TAPSCRIPT
90
+ };
91
+ }
92
+ return {
93
+ left: buildTapTreeInfo({
94
+ tapTree: tapTree.left,
95
+ network,
96
+ BIP32,
97
+ ECPair,
98
+ leafExpansionOverride
99
+ }),
100
+ right: buildTapTreeInfo({
101
+ tapTree: tapTree.right,
102
+ network,
103
+ BIP32,
104
+ ECPair,
105
+ leafExpansionOverride
106
+ })
107
+ };
108
+ }
109
+ function tapTreeInfoToScriptTree(tapTreeInfo) {
110
+ if ('expression' in tapTreeInfo) {
111
+ return {
112
+ output: tapTreeInfo.tapScript,
113
+ version: tapTreeInfo.version
114
+ };
115
+ }
116
+ return [
117
+ tapTreeInfoToScriptTree(tapTreeInfo.left),
118
+ tapTreeInfoToScriptTree(tapTreeInfo.right)
119
+ ];
120
+ }
121
+ /**
122
+ * Builds taproot PSBT leaf metadata for every leaf in a `tapTreeInfo`.
123
+ *
124
+ * For each leaf, this function computes:
125
+ * - `tapLeafHash`: BIP341 leaf hash of tapscript + leaf version
126
+ * - `depth`: leaf depth in the tree (root children have depth 1)
127
+ * - `controlBlock`: script-path proof used in PSBT `tapLeafScript`
128
+ *
129
+ * The control block layout is:
130
+ *
131
+ * ```text
132
+ * [1-byte (leafVersion | parity)] [32-byte internal key]
133
+ * [32-byte sibling hash #1] ... [32-byte sibling hash #N]
134
+ * ```
135
+ *
136
+ * where:
137
+ * - `parity` is derived from tweaking the internal key with the tree root
138
+ * - sibling hashes are the merkle path from that leaf to the root
139
+ *
140
+ * Example tree:
141
+ *
142
+ * ```text
143
+ * root
144
+ * / \
145
+ * L1 L2
146
+ * / \
147
+ * L3 L4
148
+ * ```
149
+ *
150
+ * Depths:
151
+ * - L1 depth = 1
152
+ * - L3 depth = 2
153
+ * - L4 depth = 2
154
+ *
155
+ * Conceptual output:
156
+ *
157
+ * ```text
158
+ * [
159
+ * L1 -> { depth: 1, tapLeafHash: h1, controlBlock: [v|p, ik, hash(L2)] }
160
+ * L3 -> { depth: 2, tapLeafHash: h3, controlBlock: [v|p, ik, hash(L4), hash(L1)] }
161
+ * L4 -> { depth: 2, tapLeafHash: h4, controlBlock: [v|p, ik, hash(L3), hash(L1)] }
162
+ * ]
163
+ * ```
164
+ *
165
+ * Legend:
166
+ * - `ik`: the 32-byte internal key placed in the control block.
167
+ * - `hash(X)`: the merkle sibling hash at each level when proving leaf `X`.
168
+ *
169
+ * Note: in this diagram, `L2` is a branch node (right subtree), not a leaf,
170
+ * so `hash(L2) = TapBranch(hash(L3), hash(L4))`.
171
+ *
172
+ * Notes:
173
+ * - Leaves are returned in deterministic left-first order.
174
+ * - One metadata entry is returned per leaf.
175
+ * - `controlBlock.length === 33 + 32 * depth`.
176
+ * - Throws if internal key is invalid or merkle path cannot be found.
177
+ *
178
+ * Typical usage:
179
+ * - Convert this metadata into PSBT `tapLeafScript[]` entries
180
+ * for all leaves.
181
+ */
182
+ function buildTaprootLeafPsbtMetadata({ tapTreeInfo, internalPubkey }) {
183
+ const normalizedInternalPubkey = normalizeTaprootPubkey(internalPubkey);
184
+ const scriptTree = tapTreeInfoToScriptTree(tapTreeInfo);
185
+ const hashTree = (0, bitcoinjs_lib_internals_1.toHashTree)(scriptTree);
186
+ const tweaked = (0, bitcoinjs_lib_internals_1.tweakKey)(normalizedInternalPubkey, hashTree.hash);
187
+ if (!tweaked)
188
+ throw new Error(`Error: invalid taproot internal pubkey`);
189
+ return (0, tapTree_1.collectTapTreeLeaves)(tapTreeInfo).map(({ leaf, depth }) => {
190
+ if (depth > tapTree_1.MAX_TAPTREE_DEPTH)
191
+ throw new Error(`Error: taproot tree depth is too large, ${depth} is larger than ${tapTree_1.MAX_TAPTREE_DEPTH}`);
192
+ const tapLeafHash = (0, bitcoinjs_lib_internals_1.tapleafHash)({
193
+ output: leaf.tapScript,
194
+ version: leaf.version
195
+ });
196
+ const merklePath = (0, bitcoinjs_lib_internals_1.findScriptPath)(hashTree, tapLeafHash);
197
+ if (!merklePath)
198
+ throw new Error(`Error: could not build controlBlock for taproot leaf ${leaf.expression}`);
199
+ // controlBlock[0] packs:
200
+ // - leaf version (high bits), and
201
+ // - parity of the tweaked output key Q = P + t*G (low bit).
202
+ // `normalizedInternalPubkey` is x-only P, so parity is not encoded there.
203
+ // BIP341 requires carrying Q parity in controlBlock[0].
204
+ const controlBlock = (0, uint8array_tools_1.concat)([
205
+ Uint8Array.from([leaf.version | tweaked.parity]),
206
+ normalizedInternalPubkey,
207
+ ...merklePath
208
+ ]);
209
+ return { leaf, depth, tapLeafHash, controlBlock };
210
+ });
211
+ }
212
+ /**
213
+ * Builds PSBT `tapBip32Derivation` entries for taproot script-path spends.
214
+ *
215
+ * Leaf keys include the list of tapleaf hashes where they appear.
216
+ * If `internalKeyInfo` has derivation data, it is included with empty
217
+ * `leafHashes`.
218
+ *
219
+ * Example tree:
220
+ *
221
+ * ```text
222
+ * root
223
+ * / \
224
+ * L1 L2
225
+ *
226
+ * L1 uses key A
227
+ * L2 uses key A and key B
228
+ *
229
+ * h1 = tapleafHash(L1)
230
+ * h2 = tapleafHash(L2)
231
+ * ```
232
+ *
233
+ * Then output is conceptually:
234
+ *
235
+ * ```text
236
+ * [
237
+ * key A -> leafHashes [h1, h2]
238
+ * key B -> leafHashes [h2]
239
+ * internal key -> leafHashes []
240
+ * ]
241
+ * ```
242
+ *
243
+ * Notes:
244
+ * - Keys missing `masterFingerprint` or `path` are skipped.
245
+ * - Duplicate pubkeys are merged.
246
+ * - If the same pubkey appears with conflicting derivation metadata,
247
+ * this function throws.
248
+ * - Output and `leafHashes` are sorted deterministically.
249
+ */
250
+ function buildTaprootBip32Derivations({ tapTreeInfo, internalKeyInfo }) {
251
+ const entries = new Map();
252
+ const updateAndInsert = ({ pubkey, masterFingerprint, path, leafHash }) => {
253
+ const normalizedPubkey = normalizeTaprootPubkey(pubkey);
254
+ const pubkeyHex = (0, uint8array_tools_1.toHex)(normalizedPubkey);
255
+ const current = entries.get(pubkeyHex);
256
+ if (!current) {
257
+ const next = {
258
+ masterFingerprint,
259
+ pubkey: normalizedPubkey,
260
+ path,
261
+ leafHashes: new Map()
262
+ };
263
+ if (leafHash)
264
+ next.leafHashes.set((0, uint8array_tools_1.toHex)(leafHash), leafHash);
265
+ entries.set(pubkeyHex, next);
266
+ return;
267
+ }
268
+ if ((0, uint8array_tools_1.compare)(current.masterFingerprint, masterFingerprint) !== 0 ||
269
+ current.path !== path) {
270
+ throw new Error(`Error: inconsistent taproot key derivation metadata for pubkey ${pubkeyHex}`);
271
+ }
272
+ if (leafHash)
273
+ current.leafHashes.set((0, uint8array_tools_1.toHex)(leafHash), leafHash);
274
+ };
275
+ const leaves = (0, tapTree_1.collectTapTreeLeaves)(tapTreeInfo);
276
+ for (const { leaf } of leaves) {
277
+ const leafHash = (0, bitcoinjs_lib_internals_1.tapleafHash)({
278
+ output: leaf.tapScript,
279
+ version: leaf.version
280
+ });
281
+ for (const keyInfo of Object.values(leaf.expansionMap)) {
282
+ if (!keyInfo.pubkey || !keyInfo.masterFingerprint || !keyInfo.path)
283
+ continue;
284
+ updateAndInsert({
285
+ pubkey: keyInfo.pubkey,
286
+ masterFingerprint: keyInfo.masterFingerprint,
287
+ path: keyInfo.path,
288
+ leafHash
289
+ });
290
+ }
291
+ }
292
+ if (internalKeyInfo?.pubkey &&
293
+ internalKeyInfo.masterFingerprint &&
294
+ internalKeyInfo.path) {
295
+ updateAndInsert({
296
+ pubkey: internalKeyInfo.pubkey,
297
+ masterFingerprint: internalKeyInfo.masterFingerprint,
298
+ path: internalKeyInfo.path
299
+ });
300
+ }
301
+ return [...entries.entries()]
302
+ .sort(([a], [b]) => a.localeCompare(b))
303
+ .map(([, entry]) => ({
304
+ masterFingerprint: entry.masterFingerprint,
305
+ pubkey: entry.pubkey,
306
+ path: entry.path,
307
+ leafHashes: [...entry.leafHashes.entries()]
308
+ .sort(([a], [b]) => a.localeCompare(b))
309
+ .map(([, leafHash]) => leafHash)
310
+ }));
311
+ }
312
+ function varSliceSize(someScript) {
313
+ const length = someScript.length;
314
+ return (0, varuint_bitcoin_1.encodingLength)(length) + length;
315
+ }
316
+ function vectorSize(someVector) {
317
+ const length = someVector.length;
318
+ return ((0, varuint_bitcoin_1.encodingLength)(length) +
319
+ someVector.reduce((sum, witness) => sum + varSliceSize(witness), 0));
320
+ }
321
+ function witnessStackSize(witness) {
322
+ return vectorSize(witness);
323
+ }
324
+ function estimateTaprootWitnessSize({ stackItems, tapScript, depth }) {
325
+ if (depth > tapTree_1.MAX_TAPTREE_DEPTH)
326
+ throw new Error(`Error: taproot tree depth is too large, ${depth} is larger than ${tapTree_1.MAX_TAPTREE_DEPTH}`);
327
+ const controlBlock = new Uint8Array(33 + 32 * depth);
328
+ return witnessStackSize([...stackItems, tapScript, controlBlock]);
329
+ }
330
+ function normalizeTaprootPubkey(pubkey) {
331
+ if (pubkey.length === 32)
332
+ return pubkey;
333
+ if (pubkey.length === 33)
334
+ return pubkey.slice(1, 33);
335
+ throw new Error(`Error: invalid taproot pubkey length`);
336
+ }
337
+ /**
338
+ * Compiles an expanded `sortedmulti_a(...)` leaf expression to its internal
339
+ * `multi_a(...)` form by sorting placeholders using the resolved pubkeys from
340
+ * `expansionMap`.
341
+ */
342
+ function compileSortedMultiAExpandedExpression({ expandedExpression, expansionMap }) {
343
+ const trimmed = expandedExpression.trim();
344
+ const match = trimmed.match(/^sortedmulti_a\((.*)\)$/);
345
+ if (!match)
346
+ throw new Error(`Error: invalid sortedmulti_a() expression: ${trimmed}`);
347
+ const inner = match[1];
348
+ if (!inner)
349
+ throw new Error(`Error: invalid sortedmulti_a() expression: ${trimmed}`);
350
+ const parts = inner.split(',').map(part => part.trim());
351
+ if (parts.length < 2)
352
+ throw new Error(`Error: invalid sortedmulti_a() expression: ${trimmed}`);
353
+ const threshold = parts[0];
354
+ if (!threshold)
355
+ throw new Error(`Error: invalid sortedmulti_a() threshold: ${trimmed}`);
356
+ const placeholders = parts.slice(1);
357
+ const sortedPlaceholders = placeholders
358
+ .map(placeholder => {
359
+ const keyInfo = expansionMap[placeholder];
360
+ if (!keyInfo?.pubkey)
361
+ throw new Error(`Error: sortedmulti_a() placeholder ${placeholder} not found in expansionMap`);
362
+ return { placeholder, pubkey: keyInfo.pubkey };
363
+ })
364
+ .sort((a, b) => (0, uint8array_tools_1.compare)(a.pubkey, b.pubkey))
365
+ .map(({ placeholder }) => placeholder);
366
+ return `multi_a(${[threshold, ...sortedPlaceholders].join(',')})`;
367
+ }
368
+ /**
369
+ * Computes satisfactions for taproot script-path leaves.
370
+ *
371
+ * If `tapLeaf` is undefined, all satisfiable leaves are returned. If `tapLeaf`
372
+ * is provided, only that leaf is considered.
373
+ *
374
+ * Callers are expected to pass real signatures, or fake signatures generated
375
+ * during planning. See satisfyMiniscript() for how timeConstraints keep the
376
+ * chosen leaf consistent between planning and signing.
377
+ */
378
+ function collectTaprootLeafSatisfactions({ tapTreeInfo, preimages, signatures, timeConstraints, tapLeaf }) {
379
+ const candidates = (0, tapTree_1.selectTapLeafCandidates)({
380
+ tapTreeInfo,
381
+ ...(tapLeaf !== undefined ? { tapLeaf } : {})
382
+ });
383
+ const getLeafPubkeys = (leaf) => {
384
+ return Object.values(leaf.expansionMap).map(keyInfo => {
385
+ if (!keyInfo.pubkey)
386
+ throw new Error(`Error: taproot leaf key missing pubkey`);
387
+ return normalizeTaprootPubkey(keyInfo.pubkey);
388
+ });
389
+ };
390
+ const resolveLeafSignatures = (leaf) => {
391
+ const leafPubkeys = getLeafPubkeys(leaf);
392
+ const leafPubkeySet = new Set(leafPubkeys.map(pubkey => (0, uint8array_tools_1.toHex)(pubkey)));
393
+ return signatures
394
+ .map((sig) => ({
395
+ pubkey: normalizeTaprootPubkey(sig.pubkey),
396
+ signature: sig.signature
397
+ }))
398
+ .filter((sig) => leafPubkeySet.has((0, uint8array_tools_1.toHex)(sig.pubkey)));
399
+ };
400
+ const satisfactions = [];
401
+ for (const candidate of candidates) {
402
+ const { leaf } = candidate;
403
+ const leafSignatures = resolveLeafSignatures(leaf);
404
+ try {
405
+ let satisfierMiniscript = leaf.expandedMiniscript;
406
+ // Most taproot leaves are Miniscript fragments, so `expandedMiniscript`
407
+ // is available (and currently matches `expandedExpression`).
408
+ // Descriptor-level leaf expressions (currently `sortedmulti_a`)
409
+ // expose only `expandedExpression`, so we derive an internal
410
+ // Miniscript-equivalent form here before calling `satisfyMiniscript(...)`
411
+ if (!satisfierMiniscript) {
412
+ if (!/^sortedmulti_a\(/.test(leaf.expandedExpression.trim()))
413
+ throw new Error(`Error: taproot leaf does not provide a satisfier miniscript`);
414
+ satisfierMiniscript = compileSortedMultiAExpandedExpression({
415
+ expandedExpression: leaf.expandedExpression,
416
+ expansionMap: leaf.expansionMap
417
+ });
418
+ }
419
+ const { scriptSatisfaction, nLockTime, nSequence } = (0, miniscript_1.satisfyMiniscript)({
420
+ expandedMiniscript: satisfierMiniscript,
421
+ expansionMap: leaf.expansionMap,
422
+ signatures: leafSignatures,
423
+ preimages,
424
+ ...(timeConstraints !== undefined ? { timeConstraints } : {}),
425
+ tapscript: true
426
+ });
427
+ const satisfactionStackItems = bitcoinjs_lib_1.script.toStack(scriptSatisfaction);
428
+ (0, resourceLimits_1.assertTaprootScriptPathSatisfactionResourceLimits)({
429
+ stackItems: satisfactionStackItems
430
+ });
431
+ const totalWitnessSize = estimateTaprootWitnessSize({
432
+ stackItems: satisfactionStackItems,
433
+ tapScript: leaf.tapScript,
434
+ depth: candidate.depth
435
+ });
436
+ satisfactions.push({
437
+ leaf,
438
+ depth: candidate.depth,
439
+ tapLeafHash: candidate.tapLeafHash,
440
+ scriptSatisfaction,
441
+ stackItems: satisfactionStackItems,
442
+ nLockTime,
443
+ nSequence,
444
+ totalWitnessSize
445
+ });
446
+ }
447
+ catch (error) {
448
+ if (tapLeaf !== undefined)
449
+ throw error;
450
+ }
451
+ }
452
+ if (satisfactions.length === 0)
453
+ throw new Error(`Error: no satisfiable taproot leaves found`);
454
+ return satisfactions;
455
+ }
456
+ /**
457
+ * Selects the taproot leaf satisfaction with the smallest total witness size.
458
+ * Assumes the input list is in left-first tree order for deterministic ties.
459
+ */
460
+ function selectBestTaprootLeafSatisfaction(satisfactions) {
461
+ return satisfactions.reduce((best, current) => {
462
+ if (!best)
463
+ return current;
464
+ if (current.totalWitnessSize < best.totalWitnessSize)
465
+ return current;
466
+ return best;
467
+ });
468
+ }
469
+ /**
470
+ * Collects a unique set of taproot leaf pubkeys (x-only) across the tree.
471
+ * This is useful for building fake signatures when no signer subset is given.
472
+ */
473
+ function collectTapTreePubkeys(tapTreeInfo) {
474
+ const pubkeySet = new Set();
475
+ const pubkeys = [];
476
+ const leaves = (0, tapTree_1.collectTapTreeLeaves)(tapTreeInfo);
477
+ for (const entry of leaves) {
478
+ for (const keyInfo of Object.values(entry.leaf.expansionMap)) {
479
+ if (!keyInfo.pubkey)
480
+ throw new Error(`Error: taproot leaf key missing pubkey`);
481
+ const normalized = normalizeTaprootPubkey(keyInfo.pubkey);
482
+ const hex = (0, uint8array_tools_1.toHex)(normalized);
483
+ if (pubkeySet.has(hex))
484
+ continue;
485
+ pubkeySet.add(hex);
486
+ pubkeys.push(normalized);
487
+ }
488
+ }
489
+ return pubkeys;
490
+ }
491
+ /**
492
+ * Returns the best satisfaction for a taproot tree, by witness size.
493
+ *
494
+ * If `tapLeaf` is provided, only that leaf is considered. If `tapLeaf` is a
495
+ * bytes, it is treated as a tapLeafHash and must match exactly one leaf. If
496
+ * `tapLeaf` is a string, it is treated as a raw leaf expression and must
497
+ * match exactly one leaf (whitespace-insensitive).
498
+ *
499
+ * This function is typically called twice:
500
+ * 1) Planning pass: call it with fake signatures (built by the caller) to
501
+ * choose the best leaf without requiring user signatures.
502
+ * 2) Signing pass: call it again with real signatures and the timeConstraints
503
+ * returned from the first pass (see satisfyMiniscript() for why this keeps
504
+ * the chosen leaf consistent between planning and signing).
505
+ */
506
+ function satisfyTapTree({ tapTreeInfo, signatures, preimages, tapLeaf, timeConstraints }) {
507
+ const satisfactions = collectTaprootLeafSatisfactions({
508
+ tapTreeInfo,
509
+ preimages,
510
+ signatures,
511
+ ...(tapLeaf !== undefined ? { tapLeaf } : {}),
512
+ ...(timeConstraints !== undefined ? { timeConstraints } : {})
513
+ });
514
+ return selectBestTaprootLeafSatisfaction(satisfactions);
515
+ }
@@ -0,0 +1,86 @@
1
+ import type { ExpansionMap } from './types';
2
+ export type TreeNode<TLeaf> = TLeaf | {
3
+ left: TreeNode<TLeaf>;
4
+ right: TreeNode<TLeaf>;
5
+ };
6
+ export type TapLeaf = {
7
+ /** Raw leaf expression as written in tr(KEY,TREE). */
8
+ expression: string;
9
+ };
10
+ export type TapTreeNode = TreeNode<TapLeaf>;
11
+ export type TapLeafInfo = {
12
+ /** Raw leaf expression as written in tr(KEY,TREE). */
13
+ expression: string;
14
+ /** Expanded descriptor-level expression for this leaf. */
15
+ expandedExpression: string;
16
+ /**
17
+ * Expanded miniscript form when the leaf expression is a miniscript fragment.
18
+ *
19
+ * For descriptor-level script expressions (e.g. sortedmulti_a), this can be
20
+ * undefined even though `tapScript` is available.
21
+ */
22
+ expandedMiniscript?: string;
23
+ expansionMap: ExpansionMap;
24
+ tapScript: Uint8Array;
25
+ version: number;
26
+ };
27
+ export type TapTreeInfoNode = TreeNode<TapLeafInfo>;
28
+ export type TapLeafSelection = {
29
+ leaf: TapLeafInfo;
30
+ depth: number;
31
+ tapLeafHash: Uint8Array;
32
+ };
33
+ export declare const MAX_TAPTREE_DEPTH = 128;
34
+ export declare function assertTapTreeDepth(tapTree: TapTreeNode): void;
35
+ /**
36
+ * Collects taproot leaf metadata with depth from a tree.
37
+ * Traversal is left-first, following the order of `{left,right}` in the
38
+ * expression so tie-breaks are deterministic.
39
+ *
40
+ * Example tree:
41
+ * ```
42
+ * {pk(A),{pk(B),pk(C)}}
43
+ * ```
44
+ * Visual shape:
45
+ * ```
46
+ * root
47
+ * / \
48
+ * pk(A) branch
49
+ * / \
50
+ * pk(B) pk(C)
51
+ * ```
52
+ * Collected leaves with depth:
53
+ * ```
54
+ * [
55
+ * { leaf: pk(A), depth: 1 },
56
+ * { leaf: pk(B), depth: 2 },
57
+ * { leaf: pk(C), depth: 2 }
58
+ * ]
59
+ * ```
60
+ */
61
+ export declare function collectTapTreeLeaves(tapTreeInfo: TapTreeInfoNode): Array<{
62
+ leaf: TapLeafInfo;
63
+ depth: number;
64
+ }>;
65
+ /**
66
+ * Resolves taproot leaf candidates based on an optional selector.
67
+ *
68
+ * If `tapLeaf` is undefined, all leaves are returned for auto-selection.
69
+ * If `tapLeaf` is bytes, it is treated as a tapleaf hash and must match
70
+ * exactly one leaf.
71
+ * If `tapLeaf` is a string, it is treated as a raw taproot leaf expression
72
+ * (not expanded). Matching is whitespace-insensitive. If the expression appears
73
+ * more than once, this function throws an error.
74
+ *
75
+ * Example:
76
+ * ```
77
+ * const candidates = selectTapLeafCandidates({ tapTreeInfo, tapLeaf });
78
+ * // tapLeaf can be undefined, bytes (tapleaf hash) or a leaf expression:
79
+ * // f.ex.: 'pk(03bb...)'
80
+ * ```
81
+ */
82
+ export declare function selectTapLeafCandidates({ tapTreeInfo, tapLeaf }: {
83
+ tapTreeInfo: TapTreeInfoNode;
84
+ tapLeaf?: Uint8Array | string;
85
+ }): TapLeafSelection[];
86
+ export declare function parseTapTreeExpression(expression: string): TapTreeNode;