From 4348ca01c2679b4dabfeb98c962d8d1b3c872e94 Mon Sep 17 00:00:00 2001 From: Ty J Everett Date: Mon, 26 Oct 2026 18:21:00 -0700 Subject: [PATCH 1/2] Reject wallet-selected spent inputs before signing and submission --- README.md | 2 +- frontend/src/actions.ts | 19 +++++++++++++++++++ frontend/src/coins.ts | 2 +- frontend/test/actions.test.mjs | 29 ++++++++++++++++++++++++++++- 4 files changed, 49 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 82095e2..340cd52 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ Coin evidence and per-input derivation metadata are retained in the `mountaintop `shared/schedule.json` pins the normative schedule at BRC document blob `85eaa6219cec77350170d52d243e65122e453d39` ([merged proposal](https://github.com/bsv-blockchain/BRCs/blob/068e4b5eac90ebbe726fb067682bf72aadafa4ff/opinions/0234.md)). Mainnet block 1,000,000 establishes the MTP anchor. Calendar gates alone are not expiration dates: all-version non-coinbase volume, frozen pending rounds, the 14-MTP-day notice and following-block activation also apply. Coverage is replayed from parent-linked WoC block evidence and wallet checkpoints; reorged checkpoints are discarded. Initial catch-up after the anchor can be lengthy. Testnet has no fabricated mainnet sunset. -Address, TXID and script-hash predicates are independent. The app displays funding coverage at confirmation without discarding coins outside those rules. Payments/imports prepare version-1 transactions with supported wallet APIs, bounded nonce variation, `noSend` signing, final-template and final-TXID inspection, fresh coverage checks, and one explicit `sendWith` submission. Candidate payment outputs are never changed to grind. Abandoned candidates are aborted. The wallet may ask for permissions; metadata records have their own fees. The payment work budget is 30 seconds; a match at broadcast remains provisional until confirmation. +Address, TXID and script-hash predicates are independent. The app displays funding coverage at confirmation without discarding coins outside those rules. Payments/imports prepare version-1 transactions with supported wallet APIs, bounded nonce variation, `noSend` signing, final-template and final-TXID inspection, fresh coverage checks, and one explicit `sendWith` submission. Every input, including wallet-added fee/change inputs, is checked against known-outpoint spend evidence before signing and again immediately before submission. A spent or unknown input stops the payment and aborts its unsubmitted preparation. A signature or wallet balance alone does not prove spendability. Candidate payment outputs are never changed to grind. Abandoned candidates are aborted. The wallet may ask for permissions; metadata records have their own fees. The payment work budget is 30 seconds; a match at broadcast remains provisional until confirmation. Native durable wallet action history and unique labels support recovery after an interrupted submission, without requiring an extra fee-paying record before the first import. An empty wallet can import its first coins. Signed noSend preparations can be canceled by TXID from a fresh device; unsigned or uncertain actions require wallet review. An uncertain outcome blocks automatic retries and requires checking wallet history. Out-of-session signable-reference recovery is not assumed. Mountaintops does not promise that a BRC-234 merge proves provider adoption, indefinite WoC availability, complete retrieval of data a provider no longer serves, or external wallet transaction-grinding support. Such failures remain explicit, with retained funds and keys intact. diff --git a/frontend/src/actions.ts b/frontend/src/actions.ts index 164795c..f6e95cf 100644 --- a/frontend/src/actions.ts +++ b/frontend/src/actions.ts @@ -26,6 +26,20 @@ export function assertSameTemplate(before: Transaction, after: Transaction): voi if (BigInt(a.satoshis ?? -1) !== BigInt(b.satoshis ?? -1) || a.lockingScript.toHex() !== b.lockingScript.toHex()) throw new Error('Wallet changed an authorized payment or change output') } } +// A wallet signature or balance does not prove its added inputs are unspent. +export async function assertInputsUnspent(tx: Transaction, network: WalletRecords['network']): Promise { + const seen = new Set() + for (const input of tx.inputs) { + const txid = input.sourceTXID ?? input.sourceTransaction?.id('hex') + const vout = input.sourceOutputIndex + if (!txid || !/^[a-f0-9]{64}$/.test(txid) || !Number.isSafeInteger(vout) || vout < 0) throw new Error('Wallet omitted input evidence. Payment stopped.') + const outpoint = `${txid}.${vout}` + if (seen.has(outpoint)) throw new Error('Wallet repeated an input. Payment stopped.') + seen.add(outpoint) + if (!(await coinIsUnspent({ network }, { txid, vout }))) throw new Error('Your wallet chose coins that have already been spent. Payment stopped. Resolve this in your wallet before trying again.') + } +} + // Native wallet action history is durable before submission and does not need // an extra fee-paying record. In particular, an empty wallet can import its first // external coins. Signed noSend actions can be aborted by TXID on a fresh device. @@ -65,6 +79,8 @@ export async function eligibleAction(wallet: WalletInterface, store: WalletRecor for (const output of args.outputs ?? []) { if (tx.outputs.filter(x => x.lockingScript.toHex() === output.lockingScript && BigInt(x.satoshis ?? -1) === BigInt(output.satoshis)).length !== 1) throw new Error('Wallet did not preserve the requested recipient and amount') } + progress('Checking the wallet’s coins before signing…') + await assertInputsUnspent(tx, store.network) const spends: SignActionArgs['spends'] = {} for (const coin of coins) { const indices = tx.inputs.flatMap((input, index) => (input.sourceTXID ?? input.sourceTransaction?.id('hex')) === coin.txid && input.sourceOutputIndex === coin.vout ? [index] : []) @@ -103,6 +119,9 @@ export async function eligibleAction(wallet: WalletInterface, store: WalletRecor if (store.network === 'mainnet' && !addressMatches(recipient, fresh.stage)) throw new Error('Expired — do not send coins to this address.') if (fresh.state?.pending && !addressMatches(recipient, fresh.state.pending.target)) throw new Error('This address expires at the pending transition. Use a longer-coverage destination.') } + // Permission dialogs and concurrent apps can change the spend state. + progress('Checking the wallet’s coins before submission…') + await assertInputsUnspent(final, store.network) submissionStarted = true const result = await wallet.createAction({ description: 'Submit eligible Mountaintops payment', options: { sendWith: [signedTxid], acceptDelayedBroadcast: false, returnTXIDOnly: false } }) const status = result.sendWithResults?.find(x => x.txid === signedTxid)?.status diff --git a/frontend/src/coins.ts b/frontend/src/coins.ts index cc0b29c..8a418af 100644 --- a/frontend/src/coins.ts +++ b/frontend/src/coins.ts @@ -143,7 +143,7 @@ export async function verifiedEvidence(wallet: WalletInterface, entry: AddressRe // This is a known-outpoint query, including after an address expires. A generic // failed lookup is never treated as spent, unspent, or zero. The 404 meaning is // specific to WoC's documented /tx/:id/:vout/spent contract for a known output. -export async function coinIsUnspent(entry: AddressRecord, coin: Coin): Promise { +export async function coinIsUnspent(entry: Pick, coin: Pick): Promise { const response = await whatsOnChainFetch(`${apiBase(entry.network)}/tx/${coin.txid}/${coin.vout}/spent`, { signal: AbortSignal.timeout(30_000) }) if (response.status === 404) return true if (!response.ok) throw new Error(`Spend status unknown (${response.status}); retry the check before importing.`) diff --git a/frontend/test/actions.test.mjs b/frontend/test/actions.test.mjs index 28106d4..5b269d8 100644 --- a/frontend/test/actions.test.mjs +++ b/frontend/test/actions.test.mjs @@ -25,7 +25,7 @@ test('signed outputs and input ordering cannot change after authorization', () = }) test('stage-zero payment uses noSend inspection then one explicit sendWith', async () => { const previous = globalThis.fetch - globalThis.fetch = async () => Response.json({ blocks: 972777, bestblockhash: 'a'.repeat(64) }) + globalThis.fetch = async url => String(url).endsWith('/spent') ? new Response('', { status: 404 }) : Response.json({ blocks: 972777, bestblockhash: 'a'.repeat(64) }) const records = [] const store = { network: 'mainnet', load: async () => records, append: async (kind, data) => { records.push({ kind, data }); return records } } const wallet = new FixtureWallet() @@ -87,3 +87,30 @@ test('fresh-device recovery blocks another payment while a submission is sending await assert.rejects(sendCoins(wallet, { network: 'mainnet' }, new PrivateKey(43).toPublicKey().toAddress(), '0.00000001', { stage: 0 }, () => {}), /unfinished wallet action/) } }) + + +for (const afterSigning of [false, true]) test(`wallet-added spent inputs stop ${afterSigning ? 'submission after a wallet wait' : 'signing'} and abort the preparation`, async () => { + const { UnlockingScript } = await import('@bsv/sdk') + const wallet = new FixtureWallet() + const [point] = [...wallet.state.outputs.keys()] + const [sourceTXID, index] = point.split('.') + const conflicting = new Transaction(1, [{ sourceTXID, sourceOutputIndex: Number(index), sequence: 0xffffffff, unlockingScript: new UnlockingScript() }], [{ satoshis: 9999990, lockingScript: new P2PKH().lock(new PrivateKey(44).toPublicKey().toAddress()) }]) + let signed = false, aborts = 0, submissions = 0 + const create = wallet.createAction.bind(wallet), sign = wallet.signAction.bind(wallet) + wallet.createAction = async args => { if (args.options?.sendWith) submissions++; return create(args) } + wallet.signAction = async args => { signed = true; return sign(args) } + wallet.abortAction = async () => { aborts++; return { aborted: true } } + const previous = globalThis.fetch + globalThis.fetch = async url => { + if (String(url).endsWith('/spent')) return !afterSigning || signed ? Response.json({ txid: conflicting.id('hex'), vin: 0, status: 'confirmed' }) : new Response('', { status: 404 }) + if (String(url).endsWith('/hex')) return new Response(conflicting.toHex()) + return Response.json({ blocks: 972777, bestblockhash: 'a'.repeat(64) }) + } + try { + const store = { network: 'mainnet', load: async () => [] } + await assert.rejects(sendCoins(wallet, store, new PrivateKey(43).toPublicKey().toAddress(), '0.00001000', { stage: 0, state: null }, () => {}), /wallet chose coins that have already been spent/) + assert.equal(signed, afterSigning) + assert.equal(aborts, 1) + assert.equal(submissions, 0) + } finally { globalThis.fetch = previous } +}) From 7b0599f22d0a5ba9f0a26d1023b86c1fef0c3c80 Mon Sep 17 00:00:00 2001 From: Ty J Everett Date: Mon, 26 Oct 2026 18:32:54 -0700 Subject: [PATCH 2/2] Check wallet inputs before publishing recovery records --- README.md | 2 +- frontend/src/actions.ts | 34 ++---------- frontend/src/inputChecks.ts | 18 +++++++ frontend/src/recordActions.ts | 79 ++++++++++++++++++++++++++++ frontend/src/walletActionState.ts | 20 +++++++ frontend/src/walletRecords.ts | 16 +++++- frontend/test/walletRecords.test.mjs | 42 ++++++++++++++- 7 files changed, 177 insertions(+), 34 deletions(-) create mode 100644 frontend/src/inputChecks.ts create mode 100644 frontend/src/recordActions.ts create mode 100644 frontend/src/walletActionState.ts diff --git a/README.md b/README.md index 340cd52..94a7f3e 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ Coin evidence and per-input derivation metadata are retained in the `mountaintop `shared/schedule.json` pins the normative schedule at BRC document blob `85eaa6219cec77350170d52d243e65122e453d39` ([merged proposal](https://github.com/bsv-blockchain/BRCs/blob/068e4b5eac90ebbe726fb067682bf72aadafa4ff/opinions/0234.md)). Mainnet block 1,000,000 establishes the MTP anchor. Calendar gates alone are not expiration dates: all-version non-coinbase volume, frozen pending rounds, the 14-MTP-day notice and following-block activation also apply. Coverage is replayed from parent-linked WoC block evidence and wallet checkpoints; reorged checkpoints are discarded. Initial catch-up after the anchor can be lengthy. Testnet has no fabricated mainnet sunset. -Address, TXID and script-hash predicates are independent. The app displays funding coverage at confirmation without discarding coins outside those rules. Payments/imports prepare version-1 transactions with supported wallet APIs, bounded nonce variation, `noSend` signing, final-template and final-TXID inspection, fresh coverage checks, and one explicit `sendWith` submission. Every input, including wallet-added fee/change inputs, is checked against known-outpoint spend evidence before signing and again immediately before submission. A spent or unknown input stops the payment and aborts its unsubmitted preparation. A signature or wallet balance alone does not prove spendability. Candidate payment outputs are never changed to grind. Abandoned candidates are aborted. The wallet may ask for permissions; metadata records have their own fees. The payment work budget is 30 seconds; a match at broadcast remains provisional until confirmation. +Address, TXID and script-hash predicates are independent. The app displays funding coverage at confirmation without discarding coins outside those rules. Payments/imports prepare version-1 transactions with supported wallet APIs, bounded nonce variation, `noSend` signing, final-template and final-TXID inspection, fresh coverage checks, and one explicit `sendWith` submission. Every input, including wallet-added fee/change inputs, is checked against known-outpoint spend evidence before signing and again immediately before submission. A spent or unknown input stops the payment and aborts its unsubmitted preparation. A signature or wallet balance alone does not prove spendability. The same checks protect encrypted record saves: LocalKVStore prepares and signs without broadcasting, its SDK validates the token/template, then the app checks all inputs again before one explicit release. Unsubmitted record actions recover through native wallet labels; ordinary acknowledged unproven records do not block payments, while unresolved preparations do. Candidate payment outputs are never changed to grind. Abandoned candidates are aborted. The wallet may ask for permissions; metadata records have their own fees. The payment work budget is 30 seconds; a match at broadcast remains provisional until confirmation. Native durable wallet action history and unique labels support recovery after an interrupted submission, without requiring an extra fee-paying record before the first import. An empty wallet can import its first coins. Signed noSend preparations can be canceled by TXID from a fresh device; unsigned or uncertain actions require wallet review. An uncertain outcome blocks automatic retries and requires checking wallet history. Out-of-session signable-reference recovery is not assumed. Mountaintops does not promise that a BRC-234 merge proves provider adoption, indefinite WoC availability, complete retrieval of data a provider no longer serves, or external wallet transaction-grinding support. Such failures remain explicit, with retained funds and keys intact. diff --git a/frontend/src/actions.ts b/frontend/src/actions.ts index f6e95cf..2aa6ff6 100644 --- a/frontend/src/actions.ts +++ b/frontend/src/actions.ts @@ -4,7 +4,10 @@ import { bookFromRecords, validateAddress } from './addressBook.ts' import { readCoverage, type Coverage } from './coverageClient.ts' import { coinIsUnspent, retainedCoins, verifiedEvidence, type Coin } from './coins.ts' import Importer from './Importer.ts' -import type { RecoveryRecord, WalletRecords } from './walletRecords.ts' +import type { WalletRecords } from './walletRecords.ts' +import { assertInputsUnspent } from './inputChecks.ts' +import { unfinishedWalletActions } from './walletActionState.ts' +export { unfinishedWalletActions } from './walletActionState.ts' export function parseSatoshis(bsv: string): number { if (!/^(0|[1-9][0-9]*)(\.[0-9]{1,8})?$/.test(bsv)) throw new Error('Enter a positive BSV amount with at most 8 decimal places.') @@ -26,38 +29,9 @@ export function assertSameTemplate(before: Transaction, after: Transaction): voi if (BigInt(a.satoshis ?? -1) !== BigInt(b.satoshis ?? -1) || a.lockingScript.toHex() !== b.lockingScript.toHex()) throw new Error('Wallet changed an authorized payment or change output') } } -// A wallet signature or balance does not prove its added inputs are unspent. -export async function assertInputsUnspent(tx: Transaction, network: WalletRecords['network']): Promise { - const seen = new Set() - for (const input of tx.inputs) { - const txid = input.sourceTXID ?? input.sourceTransaction?.id('hex') - const vout = input.sourceOutputIndex - if (!txid || !/^[a-f0-9]{64}$/.test(txid) || !Number.isSafeInteger(vout) || vout < 0) throw new Error('Wallet omitted input evidence. Payment stopped.') - const outpoint = `${txid}.${vout}` - if (seen.has(outpoint)) throw new Error('Wallet repeated an input. Payment stopped.') - seen.add(outpoint) - if (!(await coinIsUnspent({ network }, { txid, vout }))) throw new Error('Your wallet chose coins that have already been spent. Payment stopped. Resolve this in your wallet before trying again.') - } -} - // Native wallet action history is durable before submission and does not need // an extra fee-paying record. In particular, an empty wallet can import its first // external coins. Signed noSend actions can be aborted by TXID on a fresh device. -export async function unfinishedWalletActions(wallet: WalletInterface, network: WalletRecords['network']): Promise { - const pending: RecoveryRecord[] = [] - for (let offset = 0; ; offset += 100) { - const page = await wallet.listActions({ labels: ['mountaintops actions v1'], includeLabels: true, limit: 100, offset }) - for (const action of page.actions) { - if (!['unsigned', 'nosend', 'nonfinal', 'unprocessed', 'sending', 'unproven'].includes(action.status)) continue - const id = action.labels?.find(x => x.startsWith('mountaintops request '))?.slice(21) ?? action.txid - const canAbort = action.status === 'nosend' && /^[a-f0-9]{64}$/.test(action.txid) - pending.push({ v: 1, network, kind: 'action', clock: 0, data: { id, state: canAbort ? 'prepared' : 'needs wallet review', reference: canAbort ? action.txid : null, txid: action.txid } }) - } - if (offset + page.actions.length >= page.totalActions) break - if (page.actions.length !== 100 || offset >= 10000) throw new Error('Wallet action history is incomplete. Check the wallet before another payment.') - } - return pending -} export async function eligibleAction(wallet: WalletInterface, store: WalletRecords, args: CreateActionArgs, coverage: Coverage, progress: Progress, coins: Coin[] = [], recipient?: string): Promise { const id = crypto.randomUUID() diff --git a/frontend/src/inputChecks.ts b/frontend/src/inputChecks.ts new file mode 100644 index 0000000..c700531 --- /dev/null +++ b/frontend/src/inputChecks.ts @@ -0,0 +1,18 @@ +import { type Transaction } from '@bsv/sdk' +import type { Network } from '../../shared/brc234.ts' +import { coinIsUnspent } from './coins.ts' + +// A wallet signature or balance does not prove its added inputs are unspent. +export async function assertInputsUnspent(tx: Transaction, network: Network): Promise { + const seen = new Set() + for (const input of tx.inputs) { + const txid = input.sourceTXID ?? input.sourceTransaction?.id('hex') + const vout = input.sourceOutputIndex + if (!txid || !/^[a-f0-9]{64}$/.test(txid) || !Number.isSafeInteger(vout) || vout < 0) throw new Error('Wallet omitted input evidence. Payment stopped.') + const outpoint = `${txid}.${vout}` + if (seen.has(outpoint)) throw new Error('Wallet repeated an input. Payment stopped.') + seen.add(outpoint) + if (!(await coinIsUnspent({ network }, { txid, vout }))) throw new Error('Your wallet chose coins that have already been spent. Payment stopped. Resolve this in your wallet before trying again.') + } +} + diff --git a/frontend/src/recordActions.ts b/frontend/src/recordActions.ts new file mode 100644 index 0000000..5320a42 --- /dev/null +++ b/frontend/src/recordActions.ts @@ -0,0 +1,79 @@ +import { Transaction, type WalletInterface } from '@bsv/sdk' +import type { Network } from '../../shared/brc234.ts' +import { assertInputsUnspent } from './inputChecks.ts' + +type Prepared = { tx: Transaction; txid?: string; submitted: boolean } + +// LocalKVStore binds the token and final template. Keep its action noSend until +// that validation returns, then check all inputs before one explicit release. +export class RecordActions { + readonly wallet: WalletInterface + private readonly prepared = new Map() + private readonly signed = new Map() + error: string | undefined + cleanupFailed = false + private readonly original: WalletInterface + private readonly network: Network + constructor(original: WalletInterface, network: Network) { + this.original = original; this.network = network + this.wallet = new Proxy(original, { get: (target, property) => { + if (property === 'createAction') return async (...[args, originator]: Parameters) => { + if (args.options?.signAndProcess !== false || args.options?.sendWith?.length) throw new Error('Wallet record must be prepared before submission.') + const result = await original.createAction({ ...args, labels: [...(args.labels ?? []), 'mountaintops actions v1', 'mountaintops record v1', `mountaintops request ${crypto.randomUUID()}`], options: { ...args.options, noSend: true, returnTXIDOnly: false } }, originator) + if (result.signableTransaction) this.prepared.set(result.signableTransaction.reference, { tx: Transaction.fromAtomicBEEF(result.signableTransaction.tx), submitted: false }) + return result + } + if (property === 'signAction') return async (...[args, originator]: Parameters) => { + const state = this.prepared.get(args.reference) + if (!state || args.options?.sendWith?.length) throw new Error('Wallet record preparation is unavailable. Saving stopped.') + await this.check(state.tx) + const result = await original.signAction({ ...args, options: { ...args.options, noSend: true, returnTXIDOnly: false } }, originator) + if (!result.tx || !result.txid) throw new Error('Wallet omitted the signed recovery record.') + state.tx = Transaction.fromAtomicBEEF(result.tx) + if (state.tx.id('hex') !== result.txid) throw new Error('Wallet recovery record TXID mismatch.') + state.txid = result.txid; this.signed.set(result.txid, args.reference) + return result + } + if (property === 'abortAction') return async (...[args, originator]: Parameters) => { + if (this.prepared.get(args.reference)?.submitted) throw new Error('Record submission already started; review the wallet.') + try { + const result = await original.abortAction(args, originator) + if (!result.aborted) this.cleanupFailed = true + else this.forget(args.reference) + return result + } catch (error) { this.cleanupFailed = true; throw error } + } + const value = Reflect.get(target, property, target) + return typeof value === 'function' ? value.bind(target) : value + } }) + } + begin(): void { this.error = undefined; this.cleanupFailed = false } + private forget(reference: string): void { + const state = this.prepared.get(reference) + if (state?.txid) this.signed.delete(state.txid) + this.prepared.delete(reference) + } + private async check(tx: Transaction): Promise { + try { await assertInputsUnspent(tx, this.network) } + catch (error) { this.error = error instanceof Error ? error.message : 'Wallet coin check failed. Saving stopped.'; throw error } + } + async submit(outpoint: string): Promise { + const txid = outpoint.split('.')[0], reference = this.signed.get(txid) + const state = reference && this.prepared.get(reference) + if (!reference || !state || state.submitted) throw new Error('Wallet did not prepare a verifiable new recovery record.') + try { + await this.check(state.tx) + state.submitted = true + const result = await this.original.createAction({ description: 'Submit Mountaintops recovery record', options: { sendWith: [txid], acceptDelayedBroadcast: false, returnTXIDOnly: false } }) + const status = result.sendWithResults?.find(x => x.txid === txid)?.status + if (!status || status === 'failed') throw new Error('Wallet record submission needs review.') + this.forget(reference) + } catch (error) { + if (!state.submitted) { + try { const aborted = await this.original.abortAction({ reference }); if (!aborted.aborted) this.cleanupFailed = true; else this.forget(reference) } + catch { this.cleanupFailed = true } + } else this.error = 'Wallet record submission is uncertain. Check your wallet before saving again.' + throw error + } + } +} diff --git a/frontend/src/walletActionState.ts b/frontend/src/walletActionState.ts new file mode 100644 index 0000000..9811f0f --- /dev/null +++ b/frontend/src/walletActionState.ts @@ -0,0 +1,20 @@ +import type { WalletInterface } from '@bsv/sdk' +import type { RecoveryRecord, WalletRecords } from './walletRecords.ts' + +export async function unfinishedWalletActions(wallet: WalletInterface, network: WalletRecords['network']): Promise { + const pending: RecoveryRecord[] = [] + for (let offset = 0; ; offset += 100) { + const page = await wallet.listActions({ labels: ['mountaintops actions v1'], includeLabels: true, limit: 100, offset }) + for (const action of page.actions) { + if (!['unsigned', 'nosend', 'nonfinal', 'unprocessed', 'sending', 'unproven'].includes(action.status)) continue + if (action.status === 'unproven' && action.labels?.includes('mountaintops record v1')) continue + const id = action.labels?.find(x => x.startsWith('mountaintops request '))?.slice(21) ?? action.txid + const canAbort = action.status === 'nosend' && /^[a-f0-9]{64}$/.test(action.txid) + pending.push({ v: 1, network, kind: 'action', clock: 0, data: { id, state: canAbort ? 'prepared' : 'needs wallet review', reference: canAbort ? action.txid : null, txid: action.txid } }) + } + if (offset + page.actions.length >= page.totalActions) break + if (page.actions.length !== 100 || offset >= 10000) throw new Error('Wallet action history is incomplete. Check the wallet before another payment.') + } + return pending +} + diff --git a/frontend/src/walletRecords.ts b/frontend/src/walletRecords.ts index cb48965..2e251d0 100644 --- a/frontend/src/walletRecords.ts +++ b/frontend/src/walletRecords.ts @@ -1,5 +1,7 @@ import { LocalKVStore, Utils, type WalletInterface } from '@bsv/sdk' import type { Network } from '../../shared/brc234.ts' +import { RecordActions } from './recordActions.ts' +import { unfinishedWalletActions } from './walletActionState.ts' export const RECORD_BASKET = 'mntops v1' export type RecoveryRecord = { v: 1; network: Network; kind: 'address' | 'primary' | 'retirement' | 'checkpoint' | 'search' | 'history' | 'action'; clock: number; data: Record; serial?: string } @@ -9,12 +11,14 @@ export type RecoveryRecord = { v: 1; network: Network; kind: 'address' | 'primar // All discovery and decryption uses the BRC-100 wallet; no browser persistence. export class WalletRecords { private readonly kv: LocalKVStore + private readonly actions: RecordActions readonly wallet: WalletInterface readonly identityKey: string readonly network: Network constructor(wallet: WalletInterface, identityKey: string, network: Network) { this.wallet = wallet; this.identityKey = identityKey; this.network = network - this.kv = new LocalKVStore(wallet, RECORD_BASKET, true, undefined, false) + this.actions = new RecordActions(wallet, network) + this.kv = new LocalKVStore(this.actions.wallet, RECORD_BASKET, true, undefined, false) } async load(): Promise { @@ -46,12 +50,20 @@ export class WalletRecords { } async append(kind: RecoveryRecord['kind'], data: RecoveryRecord['data']): Promise { + if ((await unfinishedWalletActions(this.wallet, this.network)).length) throw new Error('Resolve the unfinished wallet action before saving more data.') const before = await this.load() const record: RecoveryRecord = { v: 1, network: this.network, kind, clock: Math.max(0, ...before.map(x => x.clock)) + 1, data } const payload = JSON.stringify(record) if (payload.length > 64_000) throw new Error('Recovery record is too large') const key = `r${Utils.toHex(Array.from(crypto.getRandomValues(new Uint8Array(12))))}` - const outpoint = await this.kv.set(key, payload) + this.actions.begin() + let outpoint: string + try { outpoint = await this.kv.set(key, payload); await this.actions.submit(outpoint) } + catch (error) { + if (this.actions.cleanupFailed) throw new Error('Wallet record cleanup needs review. Open your wallet before trying again.') + if (this.actions.error) throw new Error(this.actions.error) + throw error + } if (await this.kv.get(key) !== payload) throw new Error('Wallet did not acknowledge the encrypted recovery record. Do not publish this address.') const after = await this.load() if (!after.some(x => x.serial === outpoint)) throw new Error('Wallet recovery record could not be read back') diff --git a/frontend/test/walletRecords.test.mjs b/frontend/test/walletRecords.test.mjs index 761ea6b..3fd1dfc 100644 --- a/frontend/test/walletRecords.test.mjs +++ b/frontend/test/walletRecords.test.mjs @@ -1,9 +1,13 @@ import assert from 'node:assert/strict' -import test from 'node:test' +import test, { before, after } from 'node:test' import { PushDrop, Utils } from '@bsv/sdk' import { WalletRecords, RECORD_BASKET } from '../src/walletRecords.ts' import { FixtureWallet, walletState } from './fixtureWallet.mjs' +const originalFetch = globalThis.fetch +before(() => { globalThis.fetch = async url => { if (String(url).endsWith('/spent')) return new Response('', { status: 404 }); throw new Error('Unexpected fixture request: ' + url) } }) +after(() => { globalThis.fetch = originalFetch }) + test('encrypted PushDrop records restore on a new wallet instance with no browser data', async () => { const state = walletState() const first = new FixtureWallet(state) @@ -68,3 +72,39 @@ test('combined publication and legacy selections follow the same order and never book.find(x => x.keyID === '18').retiredAt = { height: 1000002, lastReceiveHeight: 1000001, hash: 'f'.repeat(64), mtp: 123 } assert.equal(primaryFromRecords(book, records, 0), null) }) + + +for (const afterSigning of [false, true]) test(`recovery record rejects spent wallet inputs ${afterSigning ? 'after signing' : 'before signing'} without publication`, async () => { + const { P2PKH, PrivateKey, Transaction, UnlockingScript } = await import('@bsv/sdk') + const wallet = new FixtureWallet(), identity = (await wallet.getPublicKey({ identityKey: true })).publicKey + const [point] = [...wallet.state.outputs.keys()], [sourceTXID, index] = point.split('.') + const conflict = new Transaction(1, [{ sourceTXID, sourceOutputIndex: Number(index), sequence: 0xffffffff, unlockingScript: new UnlockingScript() }], [{ satoshis: 9999990, lockingScript: new P2PKH().lock(new PrivateKey(44).toPublicKey().toAddress()) }]) + let signed = false, aborts = 0, submissions = 0 + const create = wallet.createAction.bind(wallet), sign = wallet.signAction.bind(wallet) + wallet.createAction = async args => { if (args.options?.sendWith) submissions++; else assert.equal(args.options.noSend, true); return create(args) } + wallet.signAction = async args => { signed = true; assert.equal(args.options.noSend, true); return sign(args) } + wallet.abortAction = async () => { aborts++; return { aborted: true } } + const previous = globalThis.fetch + globalThis.fetch = async url => String(url).endsWith('/spent') ? (!afterSigning || signed ? Response.json({ txid: conflict.id('hex'), vin: 0, status: 'confirmed' }) : new Response('', { status: 404 })) : new Response(conflict.toHex()) + try { + await assert.rejects(new WalletRecords(wallet, identity, 'mainnet').append('address', { keyID: '17', address: 'fixture', targetStage: 0 }), /wallet chose coins that have already been spent/) + assert.equal(signed, afterSigning); assert.equal(aborts, 1); assert.equal(submissions, 0) + } finally { globalThis.fetch = previous } +}) + +// A fresh app must see abandoned record preparations without treating an +// acknowledged broadcast as a second payment or persisting UI history. +test('native unfinished record actions survive a new app session and block another save', async () => { + const { unfinishedWalletActions } = await import('../src/walletActionState.ts') + const wallet = new FixtureWallet(), identity = (await wallet.getPublicKey({ identityKey: true })).publicKey + const labels = ['mountaintops actions v1', 'mountaintops record v1', 'mountaintops request fixture'] + let status = 'nosend', creates = 0 + wallet.listActions = async () => ({ totalActions: 1, actions: [{ txid: 'a'.repeat(64), labels, status }] }) + wallet.createAction = async () => { creates++; throw new Error('Unexpected action') } + const pending = await unfinishedWalletActions(wallet, 'mainnet') + assert.equal(pending[0].data.reference, 'a'.repeat(64)) + await assert.rejects(new WalletRecords(wallet, identity, 'mainnet').append('primary', { keyID: '17' }), /unfinished wallet action/) + assert.equal(creates, 0) + status = 'unproven' + assert.deepEqual(await unfinishedWalletActions(wallet, 'mainnet'), []) +})