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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. 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.

Expand Down
25 changes: 9 additions & 16 deletions frontend/src/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.')
Expand All @@ -29,21 +32,6 @@ export function assertSameTemplate(before: Transaction, after: Transaction): voi
// 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<RecoveryRecord[]> {
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<string> {
const id = crypto.randomUUID()
Expand All @@ -65,6 +53,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] : [])
Expand Down Expand Up @@ -103,6 +93,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
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/coins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<boolean> {
export async function coinIsUnspent(entry: Pick<AddressRecord, 'network'>, coin: Pick<Coin, 'txid' | 'vout'>): Promise<boolean> {
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.`)
Expand Down
18 changes: 18 additions & 0 deletions frontend/src/inputChecks.ts
Original file line number Diff line number Diff line change
@@ -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<void> {
const seen = new Set<string>()
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.')
}
}

79 changes: 79 additions & 0 deletions frontend/src/recordActions.ts
Original file line number Diff line number Diff line change
@@ -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<string, Prepared>()
private readonly signed = new Map<string, string>()
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<WalletInterface['createAction']>) => {
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<WalletInterface['signAction']>) => {
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<WalletInterface['abortAction']>) => {
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<void> {
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<void> {
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
}
}
}
20 changes: 20 additions & 0 deletions frontend/src/walletActionState.ts
Original file line number Diff line number Diff line change
@@ -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<RecoveryRecord[]> {
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
}

16 changes: 14 additions & 2 deletions frontend/src/walletRecords.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>; serial?: string }
Expand All @@ -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<RecoveryRecord[]> {
Expand Down Expand Up @@ -46,12 +50,20 @@ export class WalletRecords {
}

async append(kind: RecoveryRecord['kind'], data: RecoveryRecord['data']): Promise<RecoveryRecord[]> {
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')
Expand Down
Loading
Loading