Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/wasm-miniscript/js/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ declare module "./wasm/wasm_miniscript" {

interface WrapPsbt {
signWithXprv(this: WrapPsbt, xprv: string): SignPsbtResult;
signWithPrv(this: WrapPsbt, prv: Buffer): SignPsbtResult;
}
}

Expand Down
25 changes: 25 additions & 0 deletions packages/wasm-miniscript/src/psbt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ use crate::WrapDescriptor;
use miniscript::bitcoin::secp256k1::Secp256k1;
use miniscript::bitcoin::Psbt;
use miniscript::psbt::PsbtExt;
use miniscript::ToPublicKey;
use std::collections::HashMap;
use std::str::FromStr;
use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::{JsError, JsValue};
Expand Down Expand Up @@ -75,6 +77,29 @@ impl WrapPsbt {
.and_then(|r| r.try_to_js_value())
}

#[wasm_bindgen(js_name = signWithPrv)]
pub fn sign_with_prv(&mut self, prv: Vec<u8>) -> Result<JsValue, JsError> {
let privkey = miniscript::bitcoin::PrivateKey::from_slice(
&prv,
miniscript::bitcoin::network::Network::Bitcoin,
)
.map_err(|_| JsError::new("Invalid private key"))?;
let mut map: HashMap<miniscript::bitcoin::PublicKey, miniscript::bitcoin::PrivateKey> =
std::collections::HashMap::new();
map.insert(privkey.public_key(&Secp256k1::new()), privkey);
map.insert(
privkey
.public_key(&Secp256k1::new())
.to_x_only_pubkey()
.to_public_key(),
privkey,
);
self.0
.sign(&map, &Secp256k1::new())
.map_err(|(_, errors)| JsError::new(&format!("{} errors: {:?}", errors.len(), errors)))
.and_then(|r| r.try_to_js_value())
}

#[wasm_bindgen(js_name = finalize)]
pub fn finalize_mut(&mut self) -> Result<(), JsError> {
self.0
Expand Down
31 changes: 15 additions & 16 deletions packages/wasm-miniscript/test/descriptorUtil.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import * as assert from "node:assert";
import * as fs from "fs/promises";
import * as utxolib from "@bitgo/utxo-lib";
import { Descriptor } from "../js";
import * as assert from "node:assert";
import { DescriptorNode, MiniscriptNode } from "../js/ast";
import { DescriptorNode, MiniscriptNode, formatNode } from "../js/ast";

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

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

/**
Expand All @@ -55,13 +51,16 @@ export function getDescriptorForScriptType(
scope === "external"
? utxolib.bitgo.getExternalChainCode(scriptType)
: utxolib.bitgo.getInternalChainCode(scriptType);
const multi: MiniscriptNode = {
multi: [2, ...rootWalletKeys.triple.map((_, i) => expand(rootWalletKeys, i, chain))],
};
switch (scriptType) {
case "p2sh":
return expand("sh(multi(2,$0,$1,$2))", rootWalletKeys, chain);
return formatNode({ sh: multi });
case "p2shP2wsh":
return expand("sh(wsh(multi(2,$0,$1,$2)))", rootWalletKeys, chain);
return formatNode({ sh: { wsh: multi } });
case "p2wsh":
return expand("wsh(multi(2,$0,$1,$2))", rootWalletKeys, chain);
return formatNode({ wsh: multi });
default:
throw new Error(`Unsupported script type ${scriptType}`);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as utxolib from "@bitgo/utxo-lib";
import * as assert from "node:assert";
import { getPsbtFixtures, PsbtStage } from "./psbtFixtures";
import { getPsbtFixtures, PsbtStage } from "./psbtFixedScriptCompatFixtures";
import { Descriptor, Psbt } from "../js";

import { getDescriptorForScriptType } from "./descriptorUtil";
Expand Down
113 changes: 113 additions & 0 deletions packages/wasm-miniscript/test/psbtFromDescriptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import assert from "node:assert";
import { BIP32Interface } from "@bitgo/utxo-lib";
import { getKey } from "@bitgo/utxo-lib/dist/src/testutil";

import { DescriptorNode, formatNode } from "../js/ast";
import { mockPsbtDefault } from "./psbtFromDescriptor.util";
import { Descriptor } from "../js";
import { toWrappedPsbt } from "./psbt.util";

function toKeyWithPath(k: BIP32Interface, path = "*"): string {
return k.toBase58() + "/" + path;
}

function toKeyPlain(k: Buffer): string {
return k.toString("hex");
}

const external = getKey("external");
const a = getKey("a");
const b = getKey("b");
const c = getKey("c");
const keys = { external, a, b, c };
function getKeyName(bipKey: BIP32Interface) {
return Object.keys(keys).find(
(k) => keys[k as keyof typeof keys] === bipKey,
) as keyof typeof keys;
}

function describeSignDescriptor(
name: string,
descriptor: DescriptorNode,
signSeqs: BIP32Interface[][],
) {
describe(`psbt with descriptor ${name}`, function () {
const isTaproot = Object.keys(descriptor)[0] === "tr";
const psbt = mockPsbtDefault({
descriptorSelf: Descriptor.fromString(formatNode(descriptor), "derivable"),
descriptorOther: Descriptor.fromString(
formatNode({ wpkh: toKeyWithPath(external) }),
"derivable",
),
});

function getSigResult(keys: BIP32Interface[]) {
return {
[isTaproot ? "Schnorr" : "Ecdsa"]: keys.map((key) =>
key.publicKey.subarray(isTaproot ? 1 : 0).toString("hex"),
),
};
}

signSeqs.forEach((signSeq, i) => {
it(`should sign ${signSeq.map((k) => getKeyName(k))} xprv`, function () {
const wrappedPsbt = toWrappedPsbt(psbt);
signSeq.forEach((key) => {
assert.deepStrictEqual(wrappedPsbt.signWithXprv(key.toBase58()), {
0: getSigResult([key.derive(0)]),
1: getSigResult([key.derive(1)]),
});
});
wrappedPsbt.finalize();
});

it(`should sign ${signSeq.map((k) => getKeyName(k))} prv buffer`, function () {
if (isTaproot) {
// signing with non-bip32 taproot keys is not supported apparently
this.skip();
}
const wrappedPsbt = toWrappedPsbt(psbt);
signSeq.forEach((key) => {
assert.deepStrictEqual(wrappedPsbt.signWithPrv(key.derive(0).privateKey), {
0: getSigResult([key.derive(0)]),
1: getSigResult([]),
});
});
});
});
});
}

describeSignDescriptor(
"Wsh2Of3",
{
wsh: { multi: [2, toKeyWithPath(a), toKeyWithPath(b), toKeyWithPath(c)] },
},
[
[a, b],
[b, a],
],
);

describeSignDescriptor(
"Tr1Of3",
{
tr: [toKeyWithPath(a), [{ pk: toKeyWithPath(b) }, { pk: toKeyWithPath(c) }]],
},
[[a], [b], [c]],
);

// while we cannot sign with a derived plain xonly key, we can sign with an xprv
describeSignDescriptor(
"TrWithExternalPlain",
{
tr: [
toKeyPlain(external.publicKey),
[
{ pk: toKeyPlain(external.publicKey) },
{ or_b: [{ pk: toKeyPlain(external.publicKey) }, { "s:pk": toKeyWithPath(a) }] },
],
],
},
[[a]],
);
Loading