diff --git a/README.md b/README.md index 0a2a5ea..a5c472f 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ A client-only BRC-100 wallet application at [mountaintops.net](https://mountaint ## Receiving, expiration and recovery -The original address keeps the exact `[1, 'mountaintops']`, decimal key ID `1`, counterparty `anyone`, `forSelf: true` derivation. Browser workers search canonical decimal key IDs from `1` upward, returning the first match for a fixed BRC-234 target. The suggested target uses a measured 30-second, 95th-percentile work estimate; each work slice is bounded to 30 seconds. A match is saved before display and requires an explicit **Use this address** selection. Pausing saves verified search progress through the wallet. Restarting without a checkpoint simply repeats deterministic work. +The original address keeps the exact `[1, 'mountaintops']`, decimal key ID `1`, counterparty `anyone`, `forSelf: true` derivation. Browser workers search canonical decimal key IDs from `1` upward, returning the first match for a fixed BRC-234 target. The suggested target uses a measured 30-second, 95th-percentile work estimate; each work slice is bounded to 30 seconds. Search is free. A match requires explicit **Save address to wallet · fees apply** before the address can be displayed/shared, then **Use this address** to switch receiving. Pausing is free; saving resumable progress to the wallet is an explicit fee-bearing step. Unsaved work can always be repeated deterministically from ID 1; no published address depends on that session's memory. Address publications, primary selections, search progress, permanent receiving retirements, chain checkpoints, bounded-history completion are immutable encrypted on-chain PushDrop records using SDK `LocalKVStore` in wallet basket `mntops v1`. Each metadata record uses a 1-satoshi output plus network fees and the wallet's permission flow. There are no certificate APIs or certificate storage. Independent random record keys allow concurrent-device records to merge without overwriting another device's address history. A published address is never acknowledged until the wallet can read its record back. @@ -24,6 +24,8 @@ Address, TXID and script-hash predicates are independent. The app displays fundi 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. +The **Transactions this session** list is ephemeral React state and clears on reload. Mountaintops does not create extra history tokens or load past completed payments into that list. The wallet retains its own mandatory transaction records and coin proofs; native unfinished-action checks remain for duplicate-payment protection. For existing desktop wallets, the client prefers their standard JSON bridge over SDK 4's changed binary output format, only after verifying the same identity and network. CWI/mobile transports are unchanged. + ## Development and validation Use Node 24: diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 8406fd4..5cf444a 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -6,6 +6,7 @@ import { applyExpirations, bookFromRecords, primaryFromRecords } from './address import { readCoverage, type Coverage } from './coverageClient.ts' import { refreshCoins, type Coin } from './coins.ts' import { importCoins, sendCoins, unfinishedWalletActions } from './actions.ts' +import { preferCompatibleTransport } from './walletClient.ts' import './style.css' const client = new WalletClient('auto') @@ -26,6 +27,8 @@ export default function Mountaintops() { const [balances, setBalances] = useState>({}) const [target, setTarget] = useState('auto') const [found, setFound] = useState(null) + const [candidate, setCandidate] = useState<{ stage: number; keyID: string; address: string } | null>(null) + const [pausedSearch, setPausedSearch] = useState<{ stage: number; next: string } | null>(null) const [recipient, setRecipient] = useState('') const [amount, setAmount] = useState('') const [txid, setTxid] = useState('') @@ -41,16 +44,17 @@ export default function Mountaintops() { const run = async (task: () => Promise, quiet = false) => { if (operation.current) return operation.current = true; setBusy(true) - if (!quiet) { setError(''); setMessage('') } + if (!quiet) { setError(''); setMessage('Working… Check your wallet for any permission request.') } try { await task() } catch (e) { setError(e instanceof Error ? e.message : 'Operation unavailable. Check your wallet before retrying a payment.') } finally { operation.current = false; setBusy(false) } } const reload = async (previous: Session | null = current.current): Promise => { + await preferCompatibleTransport(client) const { network } = await client.getNetwork({}) const { publicKey: identity } = await client.getPublicKey({ identityKey: true }) if (previous && (previous.identity !== identity || previous.network !== network)) { - setSession(null); setBalances({}); setFound(null) + setSession(null); setBalances({}); setFound(null); setCandidate(null); setPausedSearch(null); setHistory([]); setTxid('') throw new Error('Wallet account or network changed. Connect again to load its own records.') } const store = previous?.store ?? new WalletRecords(client, identity, network) @@ -90,51 +94,50 @@ export default function Mountaintops() { const expected = await client.getPublicKey({ protocolID: [1, 'mountaintops'], keyID: result.keyID, counterparty: 'anyone', forSelf: true }) if (PublicKey.fromString(expected.publicKey).toAddress(fresh.network) !== result.address) throw new Error('Mined public key does not match the wallet') if (!existing) await fresh.store.append('address', { keyID: result.keyID, address: result.address, targetStage: result.stage }) - await reload(fresh); setFound(result.keyID) + await reload(fresh); setFound(result.keyID); setCandidate(null) setMessage('Address saved as an encrypted PushDrop record in your wallet. Review it, then select “Use this address”.') }) } - const mine = async () => { + const mine = async (resumeStage?: number) => { await run(async () => { const fresh = await reload() if (fresh.receivingBlocked) throw new Error(fresh.receivingBlocked) if (fresh.network !== 'mainnet') throw new Error('BRC-234 mining targets mainnet; testnet has no sunset schedule.') const minimum = Math.min(27, Math.max(1, fresh.coverage.stage, fresh.coverage.state?.pending?.target ?? 0, ...fresh.book.map(x => lastCoveredStage(x.address) + 1))) - const chosen = target === 'auto' ? undefined : Number(target) + const chosen = resumeStage ?? (target === 'auto' ? undefined : Number(target)) if (chosen !== undefined && chosen < minimum) throw new Error(`Choose stage ${minimum} or later to improve the saved addresses.`) const saved = fresh.records.filter(x => x.kind === 'search' && x.data.stage === chosen).at(-1) + const resume = pausedSearch && pausedSearch.stage === chosen ? pausedSearch.next : saved?.data.next const nextWorker = new Worker(new URL('./miner.worker.ts', import.meta.url), { type: 'module' }) - worker.current = nextWorker; searchProgress.current = null; setSearching(true); setFound(null) + worker.current = nextWorker; searchProgress.current = null; setSearching(true); setFound(null); setCandidate(null); setPausedSearch(null) nextWorker.onmessage = ({ data }) => { if (worker.current !== nextWorker) return if (data.kind === 'started') setMessage(`Searching stage ${data.stage}. Suggested work budget: 30 seconds; completion time is uncertain.`) if (data.kind === 'progress') { searchProgress.current = { stage: data.stage, next: data.next } - setMessage(`Searching stage ${data.stage}: ${BigInt(data.next).toLocaleString()} key IDs checked · ${Math.floor(data.elapsed / 1000)} seconds.`) + setMessage(`Searching stage ${data.stage}: ${(BigInt(data.next) - 1n).toLocaleString()} key IDs checked · ${Math.floor(data.elapsed / 1000)} seconds.`) } if (['found', 'paused', 'error'].includes(data.kind)) { nextWorker.terminate(); worker.current = null; setSearching(false) - if (data.kind === 'found') void publishFound(data) - if (data.kind === 'paused') void run(async () => { - const now = await reload(); await now.store.append('search', { stage: data.stage, next: data.next }); await reload(now) - setTarget(String(data.stage)); setMessage('No match yet. Progress saved in your wallet. Continue this target or choose an easier one.') - }) + if (data.kind === 'found') { setCandidate(data); setMessage('Match found. Save it to your wallet before using or sharing it. Saving incurs a 1-satoshi record plus network fees.') } + if (data.kind === 'paused') { + setPausedSearch({ stage: data.stage, next: data.next }); setTarget(String(data.stage)) + setMessage('No match in this 30-second slice. Continue here for free, or save progress in your wallet to resume on another device.') + } if (data.kind === 'error') setError(String(data.message)) } } nextWorker.onerror = () => { nextWorker.terminate(); worker.current = null; setSearching(false); setError('Address worker failed. Published addresses remain in your wallet.') } - nextWorker.postMessage({ identityKey: fresh.identity, network: fresh.network, minimumStage: minimum, targetStage: chosen, start: saved?.data.next ?? '1' }) + nextWorker.postMessage({ identityKey: fresh.identity, network: fresh.network, minimumStage: minimum, targetStage: chosen, start: resume ?? '1' }) }) } const cancelMine = () => { worker.current?.terminate(); worker.current = null; setSearching(false) - void run(async () => { - const progress = searchProgress.current - if (progress && current.current) { await current.current.store.append('search', progress); await reload() } - setMessage('Search paused. Published addresses remain available from your wallet on another device.') - }) + const progress = searchProgress.current + if (progress) { setPausedSearch(progress); setTarget(String(progress.stage)) } + setMessage('Search paused. Continue here for free, or save progress in your wallet to resume on another device. Saved addresses are already recoverable.') } const choose = (keyID: string) => void run(async () => { const fresh = await reload(); const entry = fresh.book.find(x => x.keyID === keyID) @@ -154,7 +157,8 @@ export default function Mountaintops() { if (unresolvedActions(fresh.records).length) throw new Error('Review the unfinished wallet action before another payment.') const entry = fresh.book.find(x => x.keyID === keyID)! const coins = await refreshCoins(client, fresh.store, entry, fresh.coverage, setMessage) - setTxid(await importCoins(client, fresh.store, entry, coins, fresh.coverage, setMessage)); setBalances(x => ({ ...x, [keyID]: undefined })) + const submitted = await importCoins(client, fresh.store, entry, coins, fresh.coverage, setMessage) + setTxid(submitted); setHistory(x => [{ txid: submitted, description: 'Import to wallet', status: 'Submitted' }, ...x]); setBalances(x => ({ ...x, [keyID]: undefined })) await reload(fresh); setMessage('Import submitted. Check wallet status; confirmations and wallet credit may follow later.') }) const send = () => void run(async () => { @@ -163,25 +167,18 @@ export default function Mountaintops() { if (fresh.receivingBlocked) throw new Error(fresh.receivingBlocked) const own = fresh.book.find(x => x.address === recipient) if (own) assertReceivable(own, fresh.coverage.stage) - setTxid(await sendCoins(client, fresh.store, recipient, amount, fresh.coverage, setMessage)) + const submitted = await sendCoins(client, fresh.store, recipient, amount, fresh.coverage, setMessage) + setTxid(submitted); setHistory(x => [{ txid: submitted, description: `Send ${amount} BSV`, status: 'Submitted' }, ...x]) setRecipient(''); setAmount(''); await reload(fresh) setMessage('Payment submitted. Exchange credit and confirmation are separate; check wallet history before retrying.') }) - const loadHistory = () => void run(async () => { - await reload(); const actions = [] - for (let offset = 0; ; offset += 100) { - const page = await client.listActions({ labels: ['mountaintops actions v1'], limit: 100, offset }) - actions.push(...page.actions.map(x => ({ txid: x.txid, description: x.description, status: x.status }))) - if (page.actions.length < 100) break - if (offset >= 10_000) throw new Error('Open your wallet for complete transaction history.') - } - setHistory(actions) - }) const disabled = busy || searching const primary = session?.book.find(x => x.keyID === session.primary) const foundEntry = session?.book.find(x => x.keyID === found) const pendingActions = session ? unresolvedActions(session.records) : [] + const savedSearches = session ? [...new Map(session.records.filter(x => x.kind === 'search').map(x => [Number(x.data.stage), x.data])).values()] + .filter(x => Number(x.stage) > Math.max(...session.book.map(entry => lastCoveredStage(entry.address)))) : [] const card = (entry: AddressRecord, selected = false) => { const coins = balances[entry.keyID] const pending = session!.coverage.state?.pending @@ -199,22 +196,30 @@ export default function Mountaintops() { + {!entry.retiredAt && !selected &&

Selecting this address saves your preference in the wallet: a 1-satoshi record plus network fees.

}

{coins === undefined ? 'Funds not checked in this session.' : `${entry.retiredAt ? 'Verified retained funds' : 'Verified unspent funds'}: ${money(coins.reduce((sum, coin) => sum + coin.satoshis, 0))}`}

Address details

Key ID {entry.keyID}. Address filter satisfied through stage {lastCoveredStage(entry.address)}. Transaction eligibility also affects receiving.

{coins &&

Funding transactions: {coins.filter(x => x.fundingCoverage === 'covered').length} covered at confirmation, {coins.filter(x => x.fundingCoverage === 'outside coverage').length} outside the coverage rules, {coins.filter(x => x.fundingCoverage === 'unconfirmed').length} unconfirmed. These labels do not change ownership or actual unspent funds.

}
} - return
+ return

Mountaintops

Shout your BSV transactions from the mountaintops.
Absolutely no privacy!

Your receiving addresses

Coverage deadlines apply to receiving and free lookups. Your coins remain yours after an address expires.

- {!session ? <>

Connect your BRC-100 wallet. Recovery records use encrypted on-chain PushDrop tokens in your wallet’s basket. Saving records uses a 1-satoshi token plus network fees; your wallet controls approval. Mountaintops has no application server.

: <> + {!session ? <>

Connect your BRC-100 wallet. Recovery records use encrypted on-chain PushDrop tokens in your wallet’s basket. Saving records uses a 1-satoshi token plus network fees; your wallet controls approval. Mountaintops has no application server.

: <>

{session.network} · coverage through block {session.coverage.height.toLocaleString()}{session.network === 'mainnet' && ` · stage ${session.coverage.stage}`}

{session.receivingBlocked &&

{session.receivingBlocked}

} {session.coverage.persistenceWarning &&

{session.coverage.persistenceWarning}

} {primary ? card(primary, true) :

No eligible receiving address selected. Find or select one below. Historical coins remain accessible.

} -

Find longer coverage

Suggested work budget: 30 seconds. Longer coverage can take more time. Publishing an address or saving progress creates an encrypted wallet record and incurs network fees.

- - {searching ? : } +

Find longer coverage

Search in your browser for free, in 30-second work slices. A match may arrive sooner. Save a result to your wallet before using it, then select it as your receiving address.

+ + {searching ? : } + {searching &&

{message}

} + {pausedSearch && } + {!searching && savedSearches.map(search =>

Recovered from your wallet; next key ID {String(search.next)}.

)} + {candidate &&

Match found · not saved yet

Passes the address filter through stage {lastCoveredStage(candidate.address)}. Your receiving address has not changed.

Creates an encrypted 1-satoshi PushDrop record plus network fees. Only saved addresses can be selected or shared.

} {foundEntry &&

Found and saved. Review before switching:

{card(foundEntry)}
}

Previous and saved addresses

Previous addresses can receive until their own expiration. Expired addresses are kept for historical access.

{session.book.filter(x => x.keyID !== primary?.keyID && x.keyID !== foundEntry?.keyID).map(x => card(x))} @@ -235,7 +240,7 @@ export default function Mountaintops() { await reload(fresh); setMessage('Wallet action state checked.') })}>{action.state === 'prepared' ? 'Cancel unsubmitted preparation' : 'Check wallet outcome'}
)}
}

SHOUT BSV Across To Someone

Pay from your connected wallet. Expired destinations are blocked. Wallet network fees apply.

{txid &&

Submitted TXID: {txid}

}

Submission, confirmation and exchange credit are separate. Check wallet history after an uncertain outcome before another send.

-

Shouted Transactions

{history.map(x =>

{x.description} · {x.status}
{x.txid}

)}
+

Transactions this session

This list clears when you reload or leave. Your wallet keeps its own payment records; address and coin recovery do not depend on this list.

{!history.length &&

No transactions submitted in this session.

}{history.map(x =>

{x.description} · {x.status}
{x.txid}

)}
}

About expiration and recovery

What expires?

An address stops being available for receiving here when it leaves BRC-234 coverage. New-deposit lookups stop. Ownership and spending/importing existing coins remain intact. Do not send to expired addresses from any application.

Can I use a new device?

Restore the same BRC-100 wallet account and connect here. Encrypted PushDrop records in its basket recover your addresses and retirement history; the wallet retains coin evidence. No browser data or exports from the original device are needed. Keep your wallet account and its own recovery/storage service available.

Why isn’t the sunset a fixed date?

BRC-234 begins at mainnet block 1,000,000. Transitions also depend on volume and chain-time waiting periods. An eligibility gate differs from actual expiration.

Does mining guarantee every payment is covered?

Coverage also depends on the confirmed funding TXID and, from stage 13, version 1. The app prepares eligible payments within a bounded work budget. External senders may create payments outside those rules. A filtered ledger total is never treated as spendable money.

diff --git a/frontend/src/coins.ts b/frontend/src/coins.ts index aac6784..cc0b29c 100644 --- a/frontend/src/coins.ts +++ b/frontend/src/coins.ts @@ -1,7 +1,8 @@ import { Beef, FetchHttpClient, P2PKH, Transaction, WhatsOnChain, type WalletInterface } from '@bsv/sdk' import type { AddressRecord } from '../../shared/brc234.ts' import { apiBase, wocTransactionHex, type Coverage } from './coverageClient.ts' -import { addressMatches, assertReceivable, transactionMatches } from '../../shared/brc234.ts' +import { addressMatches, assertReceivable, canonicalKeyID, transactionMatches } from '../../shared/brc234.ts' +import { validateAddress } from './addressBook.ts' import { whatsOnChainFetch } from './whatsOnChainClient.ts' import getBeefForTxid from './getBeefForTxid.ts' import type { WalletRecords } from './walletRecords.ts' @@ -82,19 +83,27 @@ export async function retainedCoins(wallet: WalletInterface, entry: AddressRecor const coins: Coin[] = [] const beef = new Beef() for (let offset = 0; ; offset += 100) { - const page = await wallet.listOutputs({ basket: COIN_BASKET, tags: [`address ${entry.address}`], tagQueryMode: 'all', include: 'entire transactions', includeCustomInstructions: true, includeTags: true, limit: 100, offset }) + // Some existing wallets acknowledge basket insertion but omit output tags + // on merged transactions. Discover the entire dedicated basket and scope + // by validated per-output metadata; tags must never hide owned coins. + const page = await wallet.listOutputs({ basket: COIN_BASKET, include: 'entire transactions', includeCustomInstructions: true, limit: 100, offset }) + if (typeof page.totalOutputs !== 'number' || !Number.isSafeInteger(page.totalOutputs) || page.totalOutputs < offset + page.outputs.length) throw new Error('Wallet returned an invalid coin count') if (page.BEEF) beef.mergeBeef(page.BEEF) for (const output of page.outputs) { if (!output.customInstructions) throw new Error('Wallet omitted the derivation metadata needed for recovery') const metadata = JSON.parse(output.customInstructions) as Coin & { v: number; network: string } - if (metadata.v !== 1 || metadata.network !== entry.network) throw new Error('Wallet coin network or schema mismatch') + if (metadata.v !== 1 || !['mainnet', 'testnet'].includes(metadata.network)) throw new Error('Wallet coin network or schema mismatch') const coin = validateCoin(metadata) - if (coin.keyID !== entry.keyID || coin.address !== entry.address || output.outpoint !== `${coin.txid}.${coin.vout}` || BigInt(output.satoshis) !== BigInt(coin.satoshis)) throw new Error('Wallet coin recovery metadata mismatch') + canonicalKeyID(coin.keyID); validateAddress(coin.address, metadata.network as AddressRecord['network']) + if (output.outpoint !== `${coin.txid}.${coin.vout}` || BigInt(output.satoshis) !== BigInt(coin.satoshis)) throw new Error('Wallet coin recovery metadata mismatch') + if (metadata.network !== entry.network || coin.address !== entry.address) continue + if (coin.keyID !== entry.keyID) throw new Error('Wallet coin derivation metadata mismatch') // Every wallet-retained output was observed during receiving or admitted // by the bounded historical bootstrap. A reorg cannot erase its ownership. coins.push(coin) } - if (page.outputs.length < 100) break + if (offset + page.outputs.length >= page.totalOutputs) break + if (page.outputs.length !== 100) throw new Error('Wallet coin pagination is incomplete') if (offset >= 100_000) throw new Error('Wallet coin pagination limit reached; balance is incomplete') } return { coins, beef } @@ -188,7 +197,18 @@ export async function refreshCoins(wallet: WalletInterface, store: WalletRecords // and its transaction/ancestry are acknowledged by the BRC-100 wallet. } } - if (found.length) { progress('Saving deposit evidence in your wallet for device-independent recovery…'); await retainCoins(wallet, entry, found) } + let retained = await retainedCoins(wallet, entry) + const alreadyRetained = new Set(retained.coins.map(coin => `${coin.txid}.${coin.vout}`)) + const newCoins = found.filter(coin => !alreadyRetained.has(`${coin.txid}.${coin.vout}`)) + if (newCoins.length) { + progress('Saving new deposit evidence in your wallet for device-independent recovery…') + await retainCoins(wallet, entry, newCoins) + retained = await retainedCoins(wallet, entry) + } + const retainedPoints = new Set(retained.coins.map(coin => `${coin.txid}.${coin.vout}`)) + if (found.some(coin => !retainedPoints.has(`${coin.txid}.${coin.vout}`))) { + throw new Error('Deposits were found, but the wallet did not return their recovery records. This is an incomplete check, not a zero balance. Keep this address available and retry before importing.') + } if (entry.retiredAt) { const records = await store.load() if (!records.some(x => x.kind === 'history' && x.data.keyID === entry.keyID && x.data.cutoffHash === entry.retiredAt?.hash)) { @@ -196,7 +216,6 @@ export async function refreshCoins(wallet: WalletInterface, store: WalletRecords catch { progress('Coin evidence is retained in your wallet. Saving historical-check completion needs wallet funds; the bounded check may repeat until it is saved. Import remains available.') } } } - const retained = await retainedCoins(wallet, entry) const unique = new Map() for (const coin of retained.coins) { // Revalidate known evidence even for wallet rows omitted from current WoC diff --git a/frontend/src/walletClient.ts b/frontend/src/walletClient.ts new file mode 100644 index 0000000..c3bdd13 --- /dev/null +++ b/frontend/src/walletClient.ts @@ -0,0 +1,18 @@ +import { WalletClient, WalletWireTransceiver } from '@bsv/sdk' + +// SDK 4 changed binary listOutputs responses. Existing desktop wallets also +// expose the standard JSON interface, whose named fields avoid that mismatch. +// Keep the same WalletClient object so LocalKVStore and all callers share it. +export async function preferCompatibleTransport(client: WalletClient, json = new WalletClient('json-api')): Promise { + await client.connectToSubstrate() + if (!(client.substrate instanceof WalletWireTransceiver)) return + try { await json.getVersion({}) } catch { return } + const [originalKey, originalNetwork, jsonKey, jsonNetwork] = await Promise.all([ + client.getPublicKey({ identityKey: true }), client.getNetwork({}), + json.getPublicKey({ identityKey: true }), json.getNetwork({}) + ]) + if (originalKey.publicKey !== jsonKey.publicKey || originalNetwork.network !== jsonNetwork.network) { + throw new Error('Wallet connections refer to different accounts or networks. Select the same wallet before continuing.') + } + client.substrate = json.substrate +} diff --git a/frontend/test/coinRecords.test.mjs b/frontend/test/coinRecords.test.mjs new file mode 100644 index 0000000..5d4d02a --- /dev/null +++ b/frontend/test/coinRecords.test.mjs @@ -0,0 +1,56 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { MerklePath, P2PKH, PublicKey, Transaction } from '@bsv/sdk' +import { COIN_BASKET, refreshCoins, retainedCoins } from '../src/coins.ts' +import { FixtureWallet } from './fixtureWallet.mjs' + +test('tagless wallet receipts remain recoverable and are scoped to each address', async () => { + const wallet = new FixtureWallet() + const entries = [] + for (const keyID of ['1', '17']) { + const pub = await wallet.getPublicKey({ protocolID: [1, 'mountaintops'], keyID, counterparty: 'anyone', forSelf: true }) + const address = PublicKey.fromString(pub.publicKey).toAddress() + const tx = new Transaction(1, [], [{ satoshis: Number(keyID), lockingScript: new P2PKH().lock(address) }]) + const coin = { txid: tx.id('hex'), vout: 0, satoshis: Number(keyID), keyID, address, height: null } + wallet.state.transactions.set(coin.txid, tx) + wallet.state.outputs.set(`${coin.txid}.0`, { basket: COIN_BASKET, tags: [], satoshis: coin.satoshis, spendable: true, customInstructions: JSON.stringify({ v: 1, network: 'mainnet', ...coin }) }) + entries.push({ keyID, address, network: 'mainnet', targetStage: 0, retiredAt: null }) + } + const original = wallet.listOutputs.bind(wallet) + wallet.listOutputs = args => { assert.equal(args.tags, undefined); return original(args) } + for (const entry of entries) { + const result = await retainedCoins(wallet, entry) + assert.equal(result.coins.length, 1) + assert.equal(result.coins[0].keyID, entry.keyID) + assert.ok(result.beef.findTransactionForSigning(result.coins[0].txid)) + } + wallet.listOutputs = async args => { const page = await original(args); return { ...page, outputs: page.outputs.slice(0, 1) } } + await assert.rejects(retainedCoins(wallet, entries[0]), /pagination is incomplete/) +}) + +test('active refresh reuses acknowledged evidence and still checks actual spend status and canonical roots', async () => { + const wallet = new FixtureWallet() + const keyID = '1' + const pub = await wallet.getPublicKey({ protocolID: [1, 'mountaintops'], keyID, counterparty: 'anyone', forSelf: true }) + const address = PublicKey.fromString(pub.publicKey).toAddress() + const source = new Transaction(1, [], [{ satoshis: 10000, lockingScript: new P2PKH().lock(address) }]) + const txid = source.id('hex'), height = 972000 + source.merklePath = MerklePath.fromCoinbaseTxidAndHeight(txid, height) + wallet.state.transactions.set(txid, source) + const coin = { txid, vout: 0, satoshis: 10000, keyID, address, height } + wallet.state.outputs.set(`${txid}.0`, { basket: COIN_BASKET, tags: [], satoshis: 10000, spendable: true, customInstructions: JSON.stringify({ v: 1, network: 'mainnet', ...coin }) }) + wallet.internalizeAction = async () => { throw new Error('Must not reinsert acknowledged evidence') } + const previous = globalThis.fetch, calls = [] + globalThis.fetch = async url => { + calls.push(String(url)) + if (String(url).includes('/unspent/all')) return Response.json({ address, result: [{ tx_hash: txid, tx_pos: 0, value: 10000, height, isSpentInMempoolTx: false }] }) + if (String(url).endsWith('/spent')) return new Response('', { status: 404 }) + if (String(url).endsWith(`/block/${height}/header`)) return Response.json({ merkleroot: txid }) + throw new Error('Unexpected proof download: ' + url) + } + try { + const coins = await refreshCoins(wallet, {}, { keyID, address, network: 'mainnet', targetStage: 0, retiredAt: null }, { stage: 0, height: 972777, activations: [] }, () => {}) + assert.equal(coins.length, 1) + assert.equal(calls.length, 3) + } finally { globalThis.fetch = previous } +}) diff --git a/frontend/test/walletClient.test.mjs b/frontend/test/walletClient.test.mjs new file mode 100644 index 0000000..d463cc6 --- /dev/null +++ b/frontend/test/walletClient.test.mjs @@ -0,0 +1,52 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { PrivateKey, Utils, WalletClient, WalletWireTransceiver } from '@bsv/sdk' +import { preferCompatibleTransport } from '../src/walletClient.ts' +import { FixtureWallet } from './fixtureWallet.mjs' + +function legacyClient(wallet) { + return new WalletClient(new WalletWireTransceiver({ transmitToWallet: async frame => { + if (frame[0] === 27) return [0, 0] // mainnet + if (frame[0] === 8) return [0, ...Utils.toArray((await wallet.getPublicKey({ identityKey: true })).publicKey, 'hex')] + if (frame[0] === 6) { + const writer = new Utils.Writer() + writer.writeUInt8(0).writeVarIntNum(1).writeVarIntNum(-1) + writer.write(new Array(32).fill(1)).writeVarIntNum(0).writeVarIntNum(1) + // Pre-v4: no spendable byte between script and custom instructions. + writer.writeVarIntNum(-1).writeVarIntNum(-1).writeVarIntNum(0).writeVarIntNum(0) + return writer.toArray() + } + throw new Error(`Unexpected wire call ${frame[0]}`) + } })) +} + +test('old binary output format is replaced by validated JSON for the same wallet', async () => { + const wallet = new FixtureWallet() + const client = legacyClient(wallet) + await assert.rejects(client.listOutputs({ basket: 'mntops v1' }), /spendable flag/) + await preferCompatibleTransport(client, new WalletClient(wallet)) + assert.equal(client.substrate, wallet) + assert.equal((await client.listOutputs({ basket: 'mntops v1' })).totalOutputs, 0) +}) +test('transport change never crosses wallet account or network boundaries', async () => { + const original = new FixtureWallet() + const client = legacyClient(original) + const before = client.substrate + const other = new FixtureWallet(undefined, new PrivateKey(43)) + await assert.rejects(preferCompatibleTransport(client, new WalletClient(other)), /different accounts or networks/) + assert.equal(client.substrate, before) + original.getNetwork = async () => ({ network: 'testnet' }) + await assert.rejects(preferCompatibleTransport(client, new WalletClient(original)), /different accounts or networks/) + assert.equal(client.substrate, before) +}) +test('native CWI and unavailable JSON leave the selected transport intact', async () => { + const wallet = new FixtureWallet() + const client = new WalletClient(wallet) + const unavailable = new WalletClient({ getVersion: async () => { throw new Error('Unavailable') } }) + await preferCompatibleTransport(client, unavailable) + assert.equal(client.substrate, wallet) + const binary = legacyClient(wallet) + const before = binary.substrate + await preferCompatibleTransport(binary, unavailable) + assert.equal(binary.substrate, before) +}) diff --git a/shared/brc234.ts b/shared/brc234.ts index c411a04..096e5d1 100644 --- a/shared/brc234.ts +++ b/shared/brc234.ts @@ -131,7 +131,7 @@ export function coverageLabel(address: string, network: Network, anchorMtp: numb if (network !== 'mainnet') return 'BRC-234 specifies mainnet coverage; no testnet sunset is defined.' const last = lastCoveredStage(address) if (last === 27) return 'No later free-coverage cutoff is scheduled.' - if (anchorMtp === null) return 'Sunset date not yet determined — schedule begins at mainnet block 1,000,000.' + if (anchorMtp === null) return `Sunset date not yet determined — schedule begins at mainnet block 1,000,000. This address passes the filter through stage ${last} and expires when stage ${last + 1} activates.` const gate = new Date(eligibilityTime(anchorMtp, last + 1) * 1000).toISOString().slice(0, 10) return `Free-coverage eligibility gate: ${gate} UTC. Actual expiration also depends on volume and chain-time activation.` }