// Bitcoin vault tests: derive 2-of-3 vaults of every script type from real // BIP32 keys, build a PSBT, have two cosigners sign separate copies (as two // hardware wallets would), merge them, and finalise a network transaction. import test from 'node:test'; import assert from 'node:assert/strict'; import { HDKey } from '@scure/bip32'; import { hex } from '@scure/base'; import * as btc from '@scure/btc-signer'; import * as core from '../lib/btc/core.ts'; import * as P from '../lib/btc/psbt.ts'; const seeds = ['000102030405060708090a0b0c0d0e0f', 'fffcf9f6f3f0edeae7e4e1dedbd8d5d2', '4b381541583be4423346c643850da4b3']; const masters = seeds.map((s) => HDKey.fromMasterSeed(hex.decode(s.padEnd(32, '0')))); const fpHex = (m) => m.fingerprint.toString(16).padStart(8, '0'); function makeVault(scriptType, network = 'testnet') { const path = core.defaultPath(scriptType, network); const cosigners = masters.map((m, i) => ({ name: `Key ${i + 1}`, fingerprint: fpHex(m), path, xpub: core.normalizeXpub(m.derive(path).publicExtendedKey.replace(/^xpub/, 'xpub'), 'mainnet' === network ? 'mainnet' : 'mainnet') && null, })); // derive account xpubs with the right version bytes for the network const v = core.versions(network); cosigners.forEach((c, i) => { const node = HDKey.fromMasterSeed(hex.decode(seeds[i].padEnd(32, '0')), v).derive(path); c.xpub = core.normalizeXpub(node.publicExtendedKey, network); }); return { kind: 'btc', id: 't', name: 'Test', network, scriptType, m: 2, cosigners, createdAt: 0 }; } test('BIP380 descriptor checksum vector', () => { assert.equal(core.descriptorChecksum('raw(deadbeef)'), '89f8spxm'); assert.equal( core.descriptorChecksum("sh(multi(2,[00000000/111'/222]xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc,xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L/0))"), 'ggrsrxfy'); }); test('xpub normalisation: zpub → xpub, rejects xprv and wrong network', () => { const node = HDKey.fromMasterSeed(hex.decode(seeds[0].padEnd(32, '0'))).derive("m/48'/0'/0'/2'"); const x = node.publicExtendedKey; // re-encode as Zpub const { base58check } = awaitImportBase(); const raw = base58check.decode(x); const z = raw.slice(); new DataView(z.buffer).setUint32(0, 0x02aa7ed3); assert.equal(core.normalizeXpub(base58check.encode(z), 'mainnet'), x); assert.throws(() => core.normalizeXpub(node.privateExtendedKey, 'mainnet'), /PRIVATE/); assert.throws(() => core.normalizeXpub(x, 'testnet'), /mainnet/); }); import { base58check as b58c } from '@scure/base'; import { sha256 } from '@noble/hashes/sha2.js'; function awaitImportBase() { return { base58check: b58c(sha256) }; } test('addresses have the right format per script type', () => { const exp = { p2tr: /^tb1p/, p2wsh: /^tb1q/, 'p2sh-p2wsh': /^2/, p2sh: /^2/ }; for (const t of Object.keys(exp)) { const v = makeVault(t); const a = core.deriveAddress(v, 0, 0); assert.match(a.address, exp[t], t); assert.notEqual(a.address, core.deriveAddress(v, 0, 1).address); assert.notEqual(a.address, core.deriveAddress(v, 1, 0).address); } const main = makeVault('p2wsh', 'mainnet'); assert.match(core.deriveAddress(main, 0, 0).address, /^bc1q[a-z0-9]{58}$/); assert.match(core.deriveAddress(makeVault('p2tr', 'mainnet'), 0, 0).address, /^bc1p[a-z0-9]{58}$/); }); test('cosigner order does not change addresses (sorted multisig)', () => { for (const t of ['p2tr', 'p2wsh', 'p2sh-p2wsh', 'p2sh']) { const v = makeVault(t); const r = { ...v, cosigners: [...v.cosigners].reverse() }; assert.equal(core.deriveAddress(v, 0, 5).address, core.deriveAddress(r, 0, 5).address, t); } }); test('descriptor shape', () => { const v = makeVault('p2tr'); const d = core.descriptor(v); assert.match(d, new RegExp(`^tr\\(${core.NUMS_H},sortedmulti_a\\(2,\\[${v.cosigners[0].fingerprint}/48h/1h/0h/3h\\]tpub`)); assert.match(d, /#[a-z0-9]{8}$/); assert.match(core.descriptor(makeVault('p2sh-p2wsh')), /^sh\(wsh\(sortedmulti\(2,/); assert.equal(core.walletPolicy(v), null); assert.equal(core.walletPolicy(makeVault('p2wsh')).template, 'wsh(sortedmulti(2,@0/**,@1/**,@2/**))'); }); // Builds a fake funding tx paying `value` to the vault address. function fund(addr, value) { const prev = new btc.Transaction({ allowUnknownOutputs: true }); prev.addOutput({ script: addr.script, amount: value }); prev.addInput({ txid: new Uint8Array(32).fill(7), index: 0, finalScriptSig: new Uint8Array([0x51]) }); const raw = prev.toBytes(true, false); return { txid: prev.id, vout: 0, value, confirmed: true, addr, prevTxHex: hex.encode(raw) }; } for (const t of ['p2tr', 'p2wsh', 'p2sh-p2wsh', 'p2sh']) { test(`${t}: 2-of-3 PSBT round trip (build → 2 separate signers → combine → finalize)`, () => { const v = makeVault(t); const a0 = core.deriveAddress(v, 0, 0), a1 = core.deriveAddress(v, 0, 1); const utxos = [fund(a0, 60_000n), fund(a1, 50_000n)]; const dest = core.deriveAddress(makeVault('p2wsh'), 0, 99).address; // any valid tb1 address const res = P.buildPsbt(v, { recipients: [{ address: dest, amount: 70_000n }], feeRate: 2, utxos, change: core.deriveAddress(v, 1, 0) }); assert.equal(res.inputs.length, 2); const sum = P.summarize(v, res.psbt); assert.equal(sum.outputs.filter((o) => o.isChange).length, 1); assert.equal(sum.fee, res.fee); const signWith = (i) => { const tx = P.parsePsbt(res.psbt); const priv = HDKey.fromMasterSeed(hex.decode(seeds[i].padEnd(32, '0')), core.versions('testnet')).derive(v.cosigners[i].path); for (let k = 0; k < tx.inputsLength; k++) { const ch = res.inputs[k].addr; tx.signIdx(priv.deriveChild(ch.change).deriveChild(ch.index).privateKey, k); } return tx; }; const s0 = signWith(0), s2 = signWith(2); const one = P.combine(res.psbt, [s0]); let st = P.signatureStatus(v, one); assert.deepEqual(st.signed, [v.cosigners[0].fingerprint]); assert.equal(st.complete, false); assert.throws(() => P.finalize(one)); const both = P.combine(one, [s2]); st = P.signatureStatus(v, both); assert.equal(st.complete, true); assert.deepEqual(st.signed.sort(), [v.cosigners[0].fingerprint, v.cosigners[2].fingerprint].sort()); const fin = P.finalize(both); const parsed = btc.Transaction.fromRaw(hex.decode(fin.hex), { allowUnknownOutputs: true }); assert.equal(parsed.id, fin.txid); // native segwit/taproot txids are fixed before signing; P2SH ones include the scriptSig if (t === 'p2tr' || t === 'p2wsh') assert.equal(fin.txid, sum.txid); assert.equal(parsed.inputsLength, 2); // actual vsize should be within a few vbytes of the estimate used for fees // fee estimate must never undershoot (stuck tx) and only slightly overshoot assert.ok(res.vsize >= parsed.vsize - 2 && res.vsize <= parsed.vsize * 1.03, `vsize ${parsed.vsize} vs estimate ${res.vsize}`); }); } test('coordinator file for non-taproot vaults', () => { const f = core.multisigConfigFile(makeVault('p2wsh')); assert.match(f, /Policy: 2 of 3/); assert.match(f, /Format: P2WSH/); assert.equal(core.multisigConfigFile(makeVault('p2tr')), null); }); import * as I from '../lib/btc/import.ts'; test('import: descriptor and config file round-trip to the same addresses', () => { for (const t of ['p2tr', 'p2wsh', 'p2sh-p2wsh', 'p2sh']) { const v = makeVault(t); const fromDesc = I.parseVaultConfig(core.descriptor(v)); assert.equal(fromDesc.scriptType, t); assert.equal(fromDesc.m, 2); const rebuilt = { ...v, cosigners: fromDesc.cosigners.map((c, i) => ({ ...c, name: 'k' + i })) }; assert.equal(core.deriveAddress(rebuilt, 0, 3).address, core.deriveAddress(v, 0, 3).address, t); const file = core.multisigConfigFile(v); if (file) { const fromFile = I.parseVaultConfig(file); assert.equal(fromFile.scriptType, t); const r2 = { ...v, cosigners: fromFile.cosigners.map((c, i) => ({ ...c, name: 'k' + i })) }; assert.equal(core.deriveAddress(r2, 1, 2).address, core.deriveAddress(v, 1, 2).address, t + ' file'); } } }); test('import: single cosigner from key-origin string and Coldcard JSON', () => { const v = makeVault('p2wsh'); const c = v.cosigners[1]; const s = `[${c.fingerprint}/48h/1h/0h/2h]${c.xpub}`; assert.deepEqual(I.parseCosigner(s, 'p2wsh', 'testnet'), { fingerprint: c.fingerprint, path: c.path, xpub: c.xpub, source: 'file' }); const cc = JSON.stringify({ xfp: c.fingerprint.toUpperCase(), p2wsh: c.xpub, p2wsh_deriv: "m/48'/1'/0'/2'" }); assert.equal(I.parseCosigner(cc, 'p2wsh', 'testnet').xpub, c.xpub); });