Skip to content

Commit cef432f

Browse files
feat(descriptor): convert descriptor templates to AST format
Rewrite descriptor template strings as AST nodes for better reliability. Replace string templates with explicit AST node construction. Issue: BTC-1845
1 parent ae600dd commit cef432f

File tree

1 file changed

+15
-16
lines changed

1 file changed

+15
-16
lines changed

packages/wasm-miniscript/test/descriptorUtil.ts

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
1+
import * as assert from "node:assert";
12
import * as fs from "fs/promises";
23
import * as utxolib from "@bitgo/utxo-lib";
3-
import { Descriptor } from "../js";
4-
import * as assert from "node:assert";
5-
import { DescriptorNode, MiniscriptNode } from "../js/ast";
4+
import { DescriptorNode, MiniscriptNode, formatNode } from "../js/ast";
65

76
async function assertEqualJSON(path: string, value: unknown): Promise<void> {
87
try {
@@ -29,16 +28,13 @@ export async function assertEqualFixture(
2928
}
3029

3130
/** Expand a template with the given root wallet keys and chain code */
32-
function expand(template: string, rootWalletKeys: utxolib.bitgo.RootWalletKeys, chainCode: number) {
33-
return template.replace(/\$([0-9])/g, (_, i) => {
34-
const keyIndex = parseInt(i, 10);
35-
if (keyIndex !== 0 && keyIndex !== 1 && keyIndex !== 2) {
36-
throw new Error("Invalid key index");
37-
}
38-
const xpub = rootWalletKeys.triple[keyIndex].neutered().toBase58();
39-
const prefix = rootWalletKeys.derivationPrefixes[keyIndex];
40-
return xpub + "/" + prefix + "/" + chainCode + "/*";
41-
});
31+
function expand(rootWalletKeys: utxolib.bitgo.RootWalletKeys, keyIndex: number, chainCode: number) {
32+
if (keyIndex !== 0 && keyIndex !== 1 && keyIndex !== 2) {
33+
throw new Error("Invalid key index");
34+
}
35+
const xpub = rootWalletKeys.triple[keyIndex].neutered().toBase58();
36+
const prefix = rootWalletKeys.derivationPrefixes[keyIndex];
37+
return xpub + "/" + prefix + "/" + chainCode + "/*";
4238
}
4339

4440
/**
@@ -55,13 +51,16 @@ export function getDescriptorForScriptType(
5551
scope === "external"
5652
? utxolib.bitgo.getExternalChainCode(scriptType)
5753
: utxolib.bitgo.getInternalChainCode(scriptType);
54+
const multi: MiniscriptNode = {
55+
multi: [2, ...rootWalletKeys.triple.map((_, i) => expand(rootWalletKeys, i, chain))],
56+
};
5857
switch (scriptType) {
5958
case "p2sh":
60-
return expand("sh(multi(2,$0,$1,$2))", rootWalletKeys, chain);
59+
return formatNode({ sh: multi });
6160
case "p2shP2wsh":
62-
return expand("sh(wsh(multi(2,$0,$1,$2)))", rootWalletKeys, chain);
61+
return formatNode({ sh: { wsh: multi } });
6362
case "p2wsh":
64-
return expand("wsh(multi(2,$0,$1,$2))", rootWalletKeys, chain);
63+
return formatNode({ wsh: multi });
6564
default:
6665
throw new Error(`Unsupported script type ${scriptType}`);
6766
}

0 commit comments

Comments
 (0)