// PSBT (BIP174) construction, merging and finalisation for Sanario vaults. import * as btc from '@scure/btc-signer'; import { hex, base64 } from '@scure/base'; import { sha256 } from '@noble/hashes/sha2.js'; import { type BtcVault, type DerivedAddress, deriveAddress, inputVbytes, outputVbytes, addressToScript, NETWORKS, } from './core.ts'; export interface Utxo { txid: string; vout: number; value: bigint; confirmed: boolean; /** address entry this UTXO belongs to */ addr: DerivedAddress; /** raw previous transaction hex (needed for legacy inputs and Ledger/Trezor safety checks) */ prevTxHex?: string; } export interface Recipient { address: string; amount: bigint } export interface BuildOptions { recipients: Recipient[]; feeRate: number; // sat/vB utxos: Utxo[]; change: DerivedAddress; /** spend everything to recipients[0] (its amount is ignored) */ sendMax?: boolean; } export interface BuildResult { psbt: string; // base64 PSBT v0 fee: bigint; vsize: number; inputs: Utxo[]; changeAmount: bigint; } const DUST = 546n; const RBF_SEQUENCE = 0xfffffffd; export function inputFields(vault: BtcVault, u: Utxo) { const a = u.addr; const base: any = { txid: hex.decode(u.txid), index: u.vout, sequence: RBF_SEQUENCE, witnessUtxo: { script: a.script, amount: u.value }, }; if (vault.scriptType === 'p2tr') { const leafHash = tapLeafHash(a.leafScript!); base.tapInternalKey = a.tapInternalKey; base.tapLeafScript = a.tapLeafScript; base.tapMerkleRoot = a.tapMerkleRoot; base.tapBip32Derivation = a.keys.map((k) => [k.pubkey.slice(1), { hashes: [leafHash], der: { fingerprint: k.fingerprint, path: k.path } }]); return base; } if (u.prevTxHex) base.nonWitnessUtxo = hex.decode(u.prevTxHex); if (vault.scriptType === 'p2sh') { if (!u.prevTxHex) throw new Error('Legacy P2SH inputs need the previous transaction.'); delete base.witnessUtxo; } if (a.witnessScript) base.witnessScript = a.witnessScript; if (a.redeemScript) base.redeemScript = a.redeemScript; base.bip32Derivation = a.keys.map((k) => [k.pubkey, { fingerprint: k.fingerprint, path: k.path }]); return base; } function changeFields(vault: BtcVault, a: DerivedAddress, amount: bigint) { const o: any = { script: a.script, amount }; if (vault.scriptType === 'p2tr') { o.tapInternalKey = a.tapInternalKey; o.tapTree = [{ depth: 0, version: 0xc0, script: a.leafScript }]; o.tapBip32Derivation = a.keys.map((k) => [k.pubkey.slice(1), { hashes: [tapLeafHash(a.leafScript!)], der: { fingerprint: k.fingerprint, path: k.path } }]); } else { if (a.witnessScript) o.witnessScript = a.witnessScript; if (a.redeemScript) o.redeemScript = a.redeemScript; o.bip32Derivation = a.keys.map((k) => [k.pubkey, { fingerprint: k.fingerprint, path: k.path }]); } return o; } function tapLeafHash(script: Uint8Array): Uint8Array { // tagged hash "TapLeaf"(0xc0 || compact_size(len) || script) const tag = sha256(new TextEncoder().encode('TapLeaf')); const len = script.length < 0xfd ? Uint8Array.of(script.length) : Uint8Array.of(0xfd, script.length & 0xff, script.length >> 8); const msg = new Uint8Array([...tag, ...tag, 0xc0, ...len, ...script]); return sha256(msg); } export function newTx() { return new btc.Transaction({ allowUnknownOutputs: false, disableScriptCheck: false }); } /** Largest-first coin selection, then builds an unsigned PSBT. */ export function buildPsbt(vault: BtcVault, opts: BuildOptions): BuildResult { const { recipients, feeRate, change } = opts; if (!recipients.length) throw new Error('Add a recipient.'); if (!(feeRate >= 1)) throw new Error('Fee rate must be at least 1 sat/vB.'); const network = vault.network; const outScripts = recipients.map((r) => addressToScript(r.address, network)); for (const r of recipients) if (!opts.sendMax && r.amount < DUST) throw new Error('Amount is below the dust limit (546 sats).'); const overhead = 10.5; const perIn = inputVbytes(vault); const outVb = outScripts.reduce((s, sc) => s + outputVbytes(sc), 0); const changeVb = outputVbytes(change.script); const sorted = [...opts.utxos].sort((a, b) => (b.value > a.value ? 1 : b.value < a.value ? -1 : 0)); let selected: Utxo[] = []; let fee = 0n, changeAmount = 0n; let amounts = recipients.map((r) => r.amount); if (opts.sendMax) { if (recipients.length !== 1) throw new Error('"Send max" works with a single recipient.'); selected = sorted; const total = selected.reduce((s, u) => s + u.value, 0n); fee = BigInt(Math.ceil((overhead + perIn * selected.length + outVb) * feeRate)); amounts = [total - fee]; if (amounts[0] < DUST) throw new Error('Balance is too small to cover the network fee.'); } else { const target = amounts.reduce((s, a) => s + a, 0n); let total = 0n; for (const u of sorted) { selected.push(u); total += u.value; const feeWithChange = BigInt(Math.ceil((overhead + perIn * selected.length + outVb + changeVb) * feeRate)); const feeNoChange = BigInt(Math.ceil((overhead + perIn * selected.length + outVb) * feeRate)); if (total >= target + feeWithChange + DUST) { fee = feeWithChange; changeAmount = total - target - feeWithChange; break; } if (total >= target + feeNoChange) { fee = total - target; changeAmount = 0n; break; } // remainder goes to fee } if (fee === 0n) throw new Error('Insufficient funds for this amount plus the network fee.'); } const tx = newTx(); for (const u of selected) tx.addInput(inputFields(vault, u)); outScripts.forEach((script, i) => tx.addOutput({ script, amount: amounts[i] })); if (changeAmount > 0n) tx.addOutput(changeFields(vault, change, changeAmount)); const vsize = Math.ceil(overhead + perIn * selected.length + outVb + (changeAmount > 0n ? changeVb : 0)); return { psbt: base64.encode(tx.toPSBT(0)), fee, vsize, inputs: selected, changeAmount }; } export function parsePsbt(text: string): btc.Transaction { const t = text.trim(); let bytes: Uint8Array; if (/^[0-9a-fA-F]+$/.test(t)) bytes = hex.decode(t.toLowerCase()); else bytes = base64.decode(t.replace(/\s+/g, '')); return btc.Transaction.fromPSBT(bytes, { allowUnknownOutputs: true }); } export function psbtFromBytes(bytes: Uint8Array): btc.Transaction { // a binary .psbt file starts with "psbt\xff"; otherwise treat as text if (bytes[0] === 0x70 && bytes[1] === 0x73 && bytes[2] === 0x62 && bytes[3] === 0x74 && bytes[4] === 0xff) { return btc.Transaction.fromPSBT(bytes, { allowUnknownOutputs: true }); } return parsePsbt(new TextDecoder().decode(bytes)); } export const toBase64 = (tx: btc.Transaction) => base64.encode(tx.toPSBT(0)); /** Merge signatures from several signed copies into one PSBT. */ export function combine(base: string, others: btc.Transaction[]): string { const tx = parsePsbt(base); for (const o of others) { if (o.id !== tx.id) throw new Error('This PSBT is for a different transaction.'); tx.combine(o); } return toBase64(tx); } export interface SignatureStatus { /** fingerprints (hex) of cosigners that have signed every input */ signed: string[]; perInput: number[]; complete: boolean; } export function signatureStatus(vault: BtcVault, psbtB64: string): SignatureStatus { const tx = parsePsbt(psbtB64); const perInput: number[] = []; const signedSets: Set[] = []; for (let i = 0; i < tx.inputsLength; i++) { const inp = tx.getInput(i); const set = new Set(); if (vault.scriptType === 'p2tr') { const ders = new Map((inp.tapBip32Derivation || []).map(([k, d]) => [hex.encode(k), d.der.fingerprint])); for (const [ks] of inp.tapScriptSig || []) { const fp = ders.get(hex.encode(ks.pubKey)); if (fp !== undefined) set.add(fp.toString(16).padStart(8, '0')); } } else { const ders = new Map((inp.bip32Derivation || []).map(([k, d]) => [hex.encode(k), d.fingerprint])); for (const [pk] of inp.partialSig || []) { const fp = ders.get(hex.encode(pk)); if (fp !== undefined) set.add(fp.toString(16).padStart(8, '0')); } } if (inp.finalScriptWitness || inp.finalScriptSig) perInput.push(vault.m); else perInput.push(set.size); signedSets.push(set); } const signed = vault.cosigners.map((c) => c.fingerprint).filter((fp) => signedSets.every((s) => s.has(fp))); return { signed, perInput, complete: perInput.every((n) => n >= vault.m) }; } /** Finalise and extract the network transaction hex. */ export function finalize(psbtB64: string): { hex: string; txid: string } { const tx = parsePsbt(psbtB64); tx.finalize(); return { hex: hex.encode(tx.extract()), txid: tx.id }; } export interface PsbtSummary { txid: string; fee: bigint; outputs: { address: string; amount: bigint; isChange: boolean }[]; inputTotal: bigint; } export function summarize(vault: BtcVault, psbtB64: string): PsbtSummary { const tx = parsePsbt(psbtB64); const net = NETWORKS[vault.network].params; let inputTotal = 0n; for (let i = 0; i < tx.inputsLength; i++) { const inp = tx.getInput(i); if (inp.witnessUtxo) inputTotal += inp.witnessUtxo.amount; else if (inp.nonWitnessUtxo) inputTotal += inp.nonWitnessUtxo.outputs[inp.index!].amount; } const outputs = []; for (let i = 0; i < tx.outputsLength; i++) { const o = tx.getOutput(i); let address = '(unknown script)'; try { address = btc.Address(net).encode(btc.OutScript.decode(o.script!)); } catch { /* keep */ } const isChange = isOwnChange(vault, o); outputs.push({ address, amount: o.amount!, isChange }); } const outTotal = outputs.reduce((s, o) => s + o.amount, 0n); return { txid: tx.id, fee: inputTotal - outTotal, outputs, inputTotal }; } /** An output is change only if it re-derives to this vault's own change script. */ function isOwnChange(vault: BtcVault, o: any): boolean { const ders = vault.scriptType === 'p2tr' ? (o.tapBip32Derivation || []).map(([, d]: any) => d.der) : (o.bip32Derivation || []).map(([, d]: any) => d); const mine = ders.find((d: any) => d.fingerprint === parseInt(vault.cosigners[0].fingerprint, 16)); if (!mine || mine.path.length < 2) return false; const change = mine.path[mine.path.length - 2], index = mine.path[mine.path.length - 1]; if (change !== 1 || index >= 0x80000000) return false; try { return hex.encode(deriveAddress(vault, 1, index).script) === hex.encode(o.script); } catch { return false; } }