move the wallet's chain source out of env and into the ui

WALLET_ESPLORA_URL was the one wallet setting an owner actually has to change — off a
public explorer that rate-limits and sees every address, onto their own indexer — and it
was the one they could only change with a shell and a restart. It now lives in
service_connections under 'esplora' and is edited at Wallet -> Settings -> Chain source,
probed against /blocks/tip/height before it is stored.

The URL joins the backend fingerprint, so re-pointing rebuilds every on-chain backend and
drops the gap-limit scan taken through the old endpoint. /_health probes what the wallets
actually use rather than the built-in default, and /_officer/config no longer reports a URL
it cannot know.

Also two receive-screen defects the Blockstream 429 exposed: a query error rendered as
"No address available", and the "new address" button called refetch() on the ?peek=true
query, so it re-fetched the same address instead of advancing the index.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-03 22:59:00 +00:00
co-authored by Claude Opus 5
parent f45bc9292b
commit ff73e86983
13 changed files with 396 additions and 41 deletions
+3 -3
View File
@@ -53,9 +53,9 @@ VAULT_STORE_KEY="<generate with: openssl rand -base64 32>"
# HEADSCALE_USER=officer # HEADSCALE_USER=officer
# ── Bitcoin wallet (officer-wallet) ───────────────────────────────────────────────────────────── # ── Bitcoin wallet (officer-wallet) ─────────────────────────────────────────────────────────────
# Chain data source for the self-custodial on-chain wallet. Any Esplora-compatible API works — # The chain data source is NOT here — it is configured from the app, at Wallet → Settings → Chain
# mempool.space by default, or point it at your own node's esplora/electrs when you run one. # source, and stored per owner. Any Esplora-compatible API works (electrs, esplora, mempool.space);
# WALLET_ESPLORA_URL=https://mempool.space/api # it defaults to the public mempool.space until you set one.
# WALLET_NETWORK=bitcoin # bitcoin | testnet | signet | regtest # WALLET_NETWORK=bitcoin # bitcoin | testnet | signet | regtest
# #
# How long an unlocked wallet stays unlocked, in seconds. Default 900 (15 min). The root key is held # How long an unlocked wallet stays unlocked, in seconds. Default 900 (15 min). The root key is held
@@ -13,7 +13,7 @@ import { encryptSecret, decryptSecret } from '../crypto';
// moment someone forgot to strip it. // moment someone forgot to strip it.
/** The services that keep a connection here. Extending it is a one-line change, not a migration. */ /** The services that keep a connection here. Extending it is a one-line change, not a migration. */
export type ServiceName = 'transmission' | 'slskd'; export type ServiceName = 'transmission' | 'slskd' | 'esplora';
export type ServiceConnection = { export type ServiceConnection = {
id: number; id: number;
+107
View File
@@ -0,0 +1,107 @@
import { deleteServiceConnection, getServiceConnection, saveServiceConnection } from 'officerdb';
import { invalidateAll } from './resolve';
import { getChainSource, getConfig, invalidateChainSource, normalizeEsploraUrl } from './upstream';
// `/_config` — which Esplora endpoint this owner's on-chain wallets read the chain from.
//
// This is the one wallet setting that is NOT per-wallet and NOT key material: an endpoint serves every
// on-chain wallet the owner has, and it holds no secret, because Esplora is an unauthenticated read API.
// It went from an env var to a row for one reason — it is the setting most likely to need changing, and
// the reason to change it (a public explorer rate-limiting you, or seeing every address you own) shows
// up long after the deployment that set it.
//
// PRIVACY, NOT CUSTODY. An Esplora endpoint learns which addresses you ask about, so pointing this at
// your own indexer is a real privacy upgrade. It is never a custody risk: the endpoint sees no key, and
// a hostile one can lie about balances but cannot move a coin.
export type ChainProbe = { ok: boolean; blockHeight?: number | null; error?: string; ms?: number };
/**
* Is there an Esplora API at this URL, and does it know the tip?
*
* `/blocks/tip/height` is the cheapest endpoint Esplora has and the one every implementation has — a
* bare number in the body. Anything else answering (a bitcoind RPC port, a mempool.space *web* root, an
* nginx default page) fails here rather than at the first address scan, which is the whole point: the
* owner finds out while looking at the form.
*/
export async function probe(baseUrl: string): Promise<ChainProbe> {
const started = Date.now();
try {
const res = await fetch(`${baseUrl}/blocks/tip/height`, {
headers: { Accept: 'text/plain' },
signal: AbortSignal.timeout(8_000),
redirect: 'manual',
});
const body = (await res.text()).trim();
if (!res.ok) {
return { ok: false, error: `endpoint returned ${res.status}: ${body.slice(0, 200)}`, ms: Date.now() - started };
}
const height = Number(body);
if (!Number.isFinite(height) || height <= 0) {
return {
ok: false,
error: `that URL answered, but not like an Esplora API (expected a block height, got "${body.slice(0, 60)}")`,
ms: Date.now() - started,
};
}
return { ok: true, blockHeight: height, ms: Date.now() - started };
} catch (err) {
return { ok: false, error: `could not reach the endpoint (${String(err)})`, ms: Date.now() - started };
}
}
const bad = (error: string, status = 400) => Response.json({ error }, { status });
const isHttpUrl = (url: string): boolean => /^https?:\/\//i.test(url);
/** The URL in use plus whether it is the owner's or the built-in default. No secrets exist here at all. */
async function state(userId: number): Promise<Response> {
const connection = await getServiceConnection(userId, 'esplora');
const source = await getChainSource(userId);
return Response.json({
configured: !!connection,
connection,
esploraUrl: source.baseUrl,
custom: source.custom,
defaultUrl: getConfig().esploraUrl,
network: getConfig().network,
});
}
type ConfigBody = { url?: unknown };
async function save(req: Request, userId: number): Promise<Response> {
const body = ((await req.json().catch(() => null)) as ConfigBody | null) ?? {};
const url = typeof body.url === 'string' ? normalizeEsploraUrl(body.url) : '';
if (!url) return bad('url is required');
if (!isHttpUrl(url)) return bad('url must start with http:// or https://');
const result = await probe(url);
if (!result.ok) return bad(result.error ?? 'that endpoint did not answer');
await saveServiceConnection({ userId, service: 'esplora', url });
invalidateChainSource(userId);
// Every on-chain backend holds an EsploraChain built from the old URL, and a cached gap-limit scan
// taken through it. Both are now wrong, so drop the instances rather than trying to patch them.
invalidateAll();
return Response.json({ ...(await state(userId).then((r) => r.json())), probe: result });
}
/** `/_config` — GET what is in use, PUT to change it, DELETE to fall back to the built-in default. */
export async function handleConfigRoute(req: Request, userId: number, subpath: string): Promise<Response> {
if (subpath && subpath !== '/') return bad('not found', 404);
if (req.method === 'GET') return state(userId);
if (req.method === 'POST' || req.method === 'PUT') return save(req, userId);
if (req.method === 'DELETE') {
await deleteServiceConnection(userId, 'esplora');
invalidateChainSource(userId);
invalidateAll();
return state(userId);
}
return bad('method not allowed', 405);
}
+36 -7
View File
@@ -1,7 +1,8 @@
import type { SidecarCommand, SidecarEvent } from '../protocol'; import type { SidecarCommand, SidecarEvent } from '../protocol';
import { createSidecarConnector } from '../connect'; import { createSidecarConnector } from '../connect';
import { handleConfigRoute } from './config';
import { handleOfficerRoute } from './routes'; import { handleOfficerRoute } from './routes';
import { getConfig, hasStoreKey } from './upstream'; import { getChainSource, getConfig, hasStoreKey } from './upstream';
import { lockAll } from './keys'; import { lockAll } from './keys';
import { invalidateAll } from './resolve'; import { invalidateAll } from './resolve';
@@ -30,7 +31,10 @@ import { invalidateAll } from './resolve';
// HTTP CONTRACT — the platform strips its /api/wallet mount prefix before forwarding. // HTTP CONTRACT — the platform strips its /api/wallet mount prefix before forwarding.
// //
// GET /_health ours. Reports network, chain reachability, store key. // GET /_health ours. Reports network, chain reachability, store key.
// GET /_officer/config network + esplora + unlock TTL + storeKeyConfigured // GET /_config the owner's Esplora endpoint (or the built-in default)
// PUT /_config {url} — probed before it is stored
// DELETE /_config fall back to the built-in default
// GET /_officer/config network + unlock TTL + storeKeyConfigured
// //
// GET /_officer/wallets list. Never includes secrets. // GET /_officer/wallets list. Never includes secrets.
// POST /_officer/wallets create. Seeded wallets return the mnemonic ONCE, // POST /_officer/wallets create. Seeded wallets return the mnemonic ONCE,
@@ -103,18 +107,42 @@ const server = Bun.serve({
async fetch(req) { async fetch(req) {
const url = new URL(req.url); const url = new URL(req.url);
// `/_config` is the chain endpoint, which is per-owner — so unlike /_health it needs the header.
if (url.pathname === '/_config' || url.pathname.startsWith('/_config/')) {
const officerUser = req.headers.get('X-Officer-User');
const userId = Number(officerUser);
if (!officerUser || !Number.isInteger(userId) || userId <= 0) {
return Response.json({ error: 'missing or invalid X-Officer-User' }, { status: 401 });
}
try {
return await handleConfigRoute(req, userId, url.pathname.slice('/_config'.length));
} catch (err) {
console.error(`[wallet] ${req.method} ${url.pathname} failed`, err instanceof Error ? err.message : err);
return Response.json({ error: 'internal error' }, { status: 500 });
}
}
if (url.pathname === '/_health') { if (url.pathname === '/_health') {
const cfg = getConfig(); const cfg = getConfig();
// Health has to probe the endpoint the wallets ACTUALLY use, not the built-in default — reporting
// the default green while the owner's own indexer is down would be worse than no health at all.
// The header is optional here (health predates it), so fall back rather than 401.
const healthUser = Number(req.headers.get('X-Officer-User'));
const chain =
Number.isInteger(healthUser) && healthUser > 0
? await getChainSource(healthUser)
: { baseUrl: cfg.esploraUrl, custom: false };
const started = Date.now(); const started = Date.now();
try { try {
const res = await fetch(`${cfg.esploraUrl}/blocks/tip/height`, { const res = await fetch(`${chain.baseUrl}/blocks/tip/height`, {
signal: AbortSignal.timeout(5_000), signal: AbortSignal.timeout(5_000),
}); });
const height = res.ok ? Number(await res.text()) : null; const height = res.ok ? Number(await res.text()) : null;
return Response.json({ return Response.json({
ok: res.ok, ok: res.ok,
network: cfg.network, network: cfg.network,
esplora: cfg.esploraUrl, esplora: chain.baseUrl,
custom: chain.custom,
blockHeight: Number.isFinite(height) ? height : null, blockHeight: Number.isFinite(height) ? height : null,
// Surfaced because wallet creation is refused without it, and that failure would otherwise // Surfaced because wallet creation is refused without it, and that failure would otherwise
// look like a bug rather than a missing config line. // look like a bug rather than a missing config line.
@@ -126,7 +154,8 @@ const server = Bun.serve({
{ {
ok: false, ok: false,
network: cfg.network, network: cfg.network,
esplora: cfg.esploraUrl, esplora: chain.baseUrl,
custom: chain.custom,
error: String(err), error: String(err),
storeKeyConfigured: hasStoreKey(), storeKeyConfigured: hasStoreKey(),
ms: Date.now() - started, ms: Date.now() - started,
@@ -152,8 +181,8 @@ const server = Bun.serve({
}, },
}); });
const cfg = getConfig(); // No esplora URL in the banner: it is per-owner state read from the database now, not a boot constant.
console.log(`[wallet] listening on 127.0.0.1:${port} — network=${cfg.network} esplora=${cfg.esploraUrl}`); console.log(`[wallet] listening on 127.0.0.1:${port} — network=${getConfig().network}`);
if (!hasStoreKey()) { if (!hasStoreKey()) {
console.warn('[wallet] VAULT_STORE_KEY is unset — wallet creation will be refused until it is configured'); console.warn('[wallet] VAULT_STORE_KEY is unset — wallet creation will be refused until it is configured');
} }
+9 -7
View File
@@ -14,7 +14,7 @@ import { LndHubBackend } from './backends/lndhub';
import { NwcBackend } from './backends/nwc'; import { NwcBackend } from './backends/nwc';
import { OnchainBackend } from './backends/onchain'; import { OnchainBackend } from './backends/onchain';
import { sessionFor } from './keys'; import { sessionFor } from './keys';
import { getConfig } from './upstream'; import { getChainSource } from './upstream';
import { BackendError, BIP_ADDRESS_TYPE, type AddressType, type BitcoinNetwork, type WalletBackend } from './types'; import { BackendError, BIP_ADDRESS_TYPE, type AddressType, type BitcoinNetwork, type WalletBackend } from './types';
// Turns a stored wallet row into a live backend instance. This is the one place that knows the mapping // Turns a stored wallet row into a live backend instance. This is the one place that knows the mapping
@@ -38,8 +38,8 @@ export function invalidateAll(): void {
} }
/** A stable fingerprint of the inputs a backend was built from, so a stale instance is detected. */ /** A stable fingerprint of the inputs a backend was built from, so a stale instance is detected. */
function versionOf(wallet: WalletSummary, config: Record<string, unknown> | null): string { function versionOf(wallet: WalletSummary, config: Record<string, unknown> | null, esploraUrl: string): string {
return JSON.stringify([wallet.kind, wallet.network, wallet.defaultBip, wallet.xpubs, config]); return JSON.stringify([wallet.kind, wallet.network, wallet.defaultBip, wallet.xpubs, config, esploraUrl]);
} }
export type Resolved = { wallet: WalletSummary; backend: WalletBackend }; export type Resolved = { wallet: WalletSummary; backend: WalletBackend };
@@ -50,12 +50,15 @@ export async function resolveBackend(userId: number, walletId: number): Promise<
const secrets = await getWalletSecrets(userId, walletId); const secrets = await getWalletSecrets(userId, walletId);
const config = secrets?.config ?? null; const config = secrets?.config ?? null;
const version = versionOf(wallet, config); // Read per resolve rather than per build: the URL is in the fingerprint, so pointing the owner at a
// different indexer rebuilds every backend and drops the scan taken through the old one.
const { baseUrl: esploraUrl } = await getChainSource(userId);
const version = versionOf(wallet, config, esploraUrl);
const hit = cache.get(walletId); const hit = cache.get(walletId);
if (hit && hit.configVersion === version) return { wallet, backend: hit.backend }; if (hit && hit.configVersion === version) return { wallet, backend: hit.backend };
const backend = build(wallet, config); const backend = build(wallet, config, esploraUrl);
cache.set(walletId, { backend, configVersion: version }); cache.set(walletId, { backend, configVersion: version });
return { wallet, backend }; return { wallet, backend };
} }
@@ -81,7 +84,7 @@ function required(config: Record<string, unknown> | null, key: string, kind: str
return v; return v;
} }
function build(wallet: WalletSummary, config: Record<string, unknown> | null): WalletBackend { function build(wallet: WalletSummary, config: Record<string, unknown> | null, esploraUrl: string): WalletBackend {
const network = wallet.network as BitcoinNetwork; const network = wallet.network as BitcoinNetwork;
switch (wallet.kind) { switch (wallet.kind) {
@@ -123,7 +126,6 @@ function build(wallet: WalletSummary, config: Record<string, unknown> | null): W
if (Object.keys(accountXpub).length === 0) { if (Object.keys(accountXpub).length === 0) {
throw new BackendError('wallet has no account xpubs', 500, 'BAD_CONFIG'); throw new BackendError('wallet has no account xpubs', 500, 'BAD_CONFIG');
} }
const { esploraUrl } = getConfig();
return new OnchainBackend({ return new OnchainBackend({
chain: new EsploraChain({ baseUrl: esploraUrl, network }), chain: new EsploraChain({ baseUrl: esploraUrl, network }),
network, network,
+7 -2
View File
@@ -116,12 +116,17 @@ export async function handleOfficerRoute(req: Request, url: URL): Promise<Respon
} }
} }
/** Non-secret deployment facts the UI needs before any wallet exists. */ /**
* Non-secret deployment facts the UI needs before any wallet exists.
*
* No esplora URL: that is per-owner now and lives at `/_config`, which is also the only place that can
* say whether it is the owner's endpoint or the fallback. Reporting the default here would have shown
* the wrong URL to anyone who had set their own.
*/
function handleConfig(): Response { function handleConfig(): Response {
const cfg = getConfig(); const cfg = getConfig();
return json({ return json({
network: cfg.network, network: cfg.network,
esploraUrl: cfg.esploraUrl,
unlockTtlSec: cfg.unlockTtlSec, unlockTtlSec: cfg.unlockTtlSec,
// The UI blocks wallet creation on this rather than letting the first write fail on a crypto error. // The UI blocks wallet creation on this rather than letting the first write fail on a crypto error.
storeKeyConfigured: hasStoreKey(), storeKeyConfigured: hasStoreKey(),
+46 -3
View File
@@ -1,9 +1,15 @@
import type { BitcoinNetwork } from './types'; import type { BitcoinNetwork } from './types';
import { getServiceCredentials } from 'officerdb';
// The ONLY reader of WALLET_* env in the tree. Everything else — node URLs, macaroons, runes, LNDHub // The ONLY reader of WALLET_* env in the tree. Everything else — node URLs, macaroons, runes, LNDHub
// credentials, NWC URIs — is per-wallet configuration the owner enters at runtime and lives encrypted in // credentials, NWC URIs — is per-wallet configuration the owner enters at runtime and lives encrypted in
// Postgres (databases/officer_db/src/schema/wallet.ts), not here. Env holds only what is genuinely // Postgres (databases/officer_db/src/schema/wallet.ts), not here. Env holds only what is genuinely
// deployment-wide: which chain we're on and where to get chain data. // deployment-wide: which chain we're on.
//
// WHERE CHAIN DATA COMES FROM IS NOT ENV. It used to be WALLET_ESPLORA_URL, which meant the one setting
// an owner actually has to change — off the public explorer, onto their own indexer — was the one
// setting they could only change with a shell and a restart. It now lives in `service_connections`
// under 'esplora' and is edited from Wallet → Settings; see getChainSource below.
const NETWORKS: readonly BitcoinNetwork[] = ['bitcoin', 'testnet', 'signet', 'regtest']; const NETWORKS: readonly BitcoinNetwork[] = ['bitcoin', 'testnet', 'signet', 'regtest'];
@@ -33,17 +39,54 @@ export function getConfig(): WalletConfig {
warned = true; warned = true;
} }
const esploraUrl = process.env.WALLET_ESPLORA_URL?.trim().replace(/\/+$/, '') || DEFAULT_ESPLORA[network];
const ttl = Number(process.env.WALLET_UNLOCK_TTL_SEC ?? 900); const ttl = Number(process.env.WALLET_UNLOCK_TTL_SEC ?? 900);
return { return {
network, network,
esploraUrl, /** The built-in default, used until the owner stores one. `getChainSource` is the real answer. */
esploraUrl: DEFAULT_ESPLORA[network],
// Clamp: a zero TTL makes the wallet unusable, and an unbounded one defeats auto-lock entirely. // Clamp: a zero TTL makes the wallet unusable, and an unbounded one defeats auto-lock entirely.
unlockTtlSec: Number.isFinite(ttl) ? Math.min(Math.max(ttl, 30), 86_400) : 900, unlockTtlSec: Number.isFinite(ttl) ? Math.min(Math.max(ttl, 30), 86_400) : 900,
}; };
} }
export type ChainSource = {
/** Esplora API root, no trailing slash. */
baseUrl: string;
/** True when this is the owner's stored endpoint rather than the built-in public default. */
custom: boolean;
};
/** Short TTL: a save invalidates explicitly, so this only bounds how stale a *concurrent* reader can be. */
const CHAIN_TTL_MS = 60_000;
const chainCache = new Map<number, { source: ChainSource; at: number }>();
export const normalizeEsploraUrl = (url: string): string => url.trim().replace(/\/+$/, '');
/**
* Where to read the chain, for this owner.
*
* Falls back to the public default rather than failing: a wallet with no stored endpoint is still a
* working watch-only wallet, just one pointed at an explorer that rate-limits and can see every address
* it asks about. The default is a starting point, not a destination.
*/
export async function getChainSource(userId: number): Promise<ChainSource> {
const hit = chainCache.get(userId);
if (hit && Date.now() - hit.at < CHAIN_TTL_MS) return hit.source;
const creds = await getServiceCredentials(userId, 'esplora');
const source: ChainSource = creds?.url
? { baseUrl: normalizeEsploraUrl(creds.url), custom: true }
: { baseUrl: getConfig().esploraUrl, custom: false };
chainCache.set(userId, { source, at: Date.now() });
return source;
}
export function invalidateChainSource(userId: number): void {
chainCache.delete(userId);
}
/** /**
* Whether VAULT_STORE_KEY is present. The sidecar can serve a locked, watch-only view without it, but * Whether VAULT_STORE_KEY is present. The sidecar can serve a locked, watch-only view without it, but
* every write path that touches an encrypted column will throw, so /_health reports it explicitly rather * every write path that touches an encrypted column will throw, so /_health reports it explicitly rather
@@ -0,0 +1,129 @@
import type { ServiceConnectionState } from '../../hooks/useServiceConnection';
import { useEffect, useState } from 'react';
import { CheckCircle2, Loader2, RotateCcw, TriangleAlert } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
serviceErrorMessage,
useServiceConnection,
useServiceConnectionActions,
} from '../../hooks/useServiceConnection';
// Where on-chain wallets read the chain from. One endpoint serves every on-chain wallet the owner has,
// which is why it sits here and not on a wallet.
//
// PRIVACY, NOT CUSTODY. An Esplora endpoint learns every address you ask it about, so pointing this at
// your own indexer is a real upgrade — but it never sees a key and cannot move a coin. That framing is
// on the card deliberately: the risk of getting it wrong is being watched, not being robbed.
//
// It must speak the Esplora REST API. bitcoind's own RPC is NOT that — running your own node means
// running electrs, esplora or mempool.space alongside it and pointing this at that.
type ChainState = ServiceConnectionState & {
esploraUrl: string;
custom: boolean;
defaultUrl: string;
network: string;
};
type SaveResult = ChainState & { probe?: { blockHeight?: number | null; ms?: number } };
export const ChainSourceCard = () => {
const { data, isLoading } = useServiceConnection<ChainState>('wallet');
const { save, forget } = useServiceConnectionActions<{ url: string }, SaveResult>('wallet');
const [url, setUrl] = useState('');
const [error, setError] = useState<string | null>(null);
const [height, setHeight] = useState<number | null>(null);
// Seeded from whatever is in use, so the field starts as the answer to "what is this pointed at" and the
// owner edits it rather than retyping it. Keyed on the URL: a save or reset should re-seed.
useEffect(() => {
if (data) setUrl(data.esploraUrl);
}, [data?.esploraUrl]);
const trimmed = url.trim();
const dirty = !!data && trimmed !== data.esploraUrl;
const busy = save.isPending || forget.isPending;
const submit = async () => {
setError(null);
setHeight(null);
try {
const result = await save.mutateAsync({ url: trimmed });
setHeight(result.probe?.blockHeight ?? null);
} catch (err) {
setError(serviceErrorMessage(err));
}
};
const reset = async () => {
setError(null);
setHeight(null);
try {
await forget.mutateAsync();
} catch (err) {
setError(serviceErrorMessage(err));
}
};
return (
<section className="max-w-2xl rounded-xl border border-border p-4">
<h3 className="mb-2 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">Chain source</h3>
<p className="mb-3 text-xs text-muted-foreground">
The Esplora API on-chain wallets read balances and history from. It sees every address this wallet asks about,
so your own indexer is a privacy upgrade it never sees a key and cannot spend.
</p>
<div className="flex flex-col gap-2 sm:flex-row">
<Input
value={url}
onChange={(ev) => setUrl(ev.target.value)}
onKeyDown={(ev) => {
if (ev.key === 'Enter' && trimmed && dirty && !busy) void submit();
}}
placeholder={data?.defaultUrl ?? 'https://mempool.space/api'}
disabled={isLoading || busy}
className="h-8 font-mono text-xs"
aria-label="Esplora API URL"
autoComplete="off"
spellCheck={false}
/>
<div className="flex shrink-0 gap-2">
<Button size="sm" onClick={submit} disabled={!trimmed || !dirty || busy}>
{save.isPending ? <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" /> : null}
{save.isPending ? 'Connecting…' : 'Save & connect'}
</Button>
{data?.custom && (
<Button size="sm" variant="outline" onClick={reset} disabled={busy} title="Back to the public default">
<RotateCcw className="mr-1.5 h-3.5 w-3.5" />
Reset
</Button>
)}
</div>
</div>
{error && (
<p className="mt-2 flex items-start gap-1.5 text-xs text-destructive">
<TriangleAlert className="mt-0.5 h-3.5 w-3.5 shrink-0" />
<span>{error}</span>
</p>
)}
{height != null && !error && (
<p className="mt-2 flex items-center gap-1.5 text-xs text-emerald-500">
<CheckCircle2 className="h-3.5 w-3.5 shrink-0" />
Connected block {height.toLocaleString()}
</p>
)}
<p className="mt-2 text-[11px] text-muted-foreground">
{data?.custom
? 'Using your endpoint.'
: `Using the built-in default (${data?.defaultUrl ?? '—'}), which rate-limits and can see every address you look up.`}{' '}
This must be an <span className="font-mono">Esplora</span> REST API electrs, esplora or a mempool.space
instance. bitcoin-core&apos;s own RPC port will not work.
</p>
</section>
);
};
@@ -1,5 +1,5 @@
import { useState } from 'react'; import { useState } from 'react';
import { Loader2, Plus, RefreshCw, Zap } from 'lucide-react'; import { Loader2, Plus, RefreshCw, TriangleAlert, Zap } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { formatTimestamp, truncateMiddle } from './format'; import { formatTimestamp, truncateMiddle } from './format';
import { INVOICE_TONES } from './format'; import { INVOICE_TONES } from './format';
@@ -7,7 +7,7 @@ import { Amount } from './Amount';
import { CopyField } from './CopyField'; import { CopyField } from './CopyField';
import { EmptyWallet, UnsupportedSection } from './EmptyWallet'; import { EmptyWallet, UnsupportedSection } from './EmptyWallet';
import { useSelectedWallet } from './useSelectedWallet'; import { useSelectedWallet } from './useSelectedWallet';
import { useCapabilities, useInvoices, useReceiveAddress } from './useWalletData'; import { errorMessage, useCapabilities, useInvoices, useReceiveAddress } from './useWalletData';
import { CreateInvoiceDialog } from './dialogs/CreateInvoiceDialog'; import { CreateInvoiceDialog } from './dialogs/CreateInvoiceDialog';
// Receiving. Works while locked — deriving an address needs the account xpub, not the seed, which is why // Receiving. Works while locked — deriving an address needs the account xpub, not the seed, which is why
@@ -22,7 +22,13 @@ export const ReceiveView = () => {
const canOnchain = capabilities.includes('onchainReceive'); const canOnchain = capabilities.includes('onchainReceive');
const canLightning = capabilities.includes('lightningReceive'); const canLightning = capabilities.includes('lightningReceive');
const { address, addressType, isLoading: addressLoading, refetch } = useReceiveAddress(walletId, canOnchain); const {
address,
addressType,
isLoading: addressLoading,
error: addressError,
next,
} = useReceiveAddress(walletId, canOnchain);
const { invoices } = useInvoices(walletId, canLightning, 10); const { invoices } = useInvoices(walletId, canLightning, 10);
const [invoiceOpen, setInvoiceOpen] = useState(false); const [invoiceOpen, setInvoiceOpen] = useState(false);
@@ -39,10 +45,11 @@ export const ReceiveView = () => {
</h3> </h3>
<button <button
type="button" type="button"
onClick={() => refetch()} onClick={() => next.mutate()}
className="flex items-center gap-1 text-[11px] text-primary hover:underline" disabled={next.isPending}
className="flex items-center gap-1 text-[11px] text-primary hover:underline disabled:opacity-50"
> >
<RefreshCw className="h-3 w-3" /> <RefreshCw className={`h-3 w-3 ${next.isPending ? 'animate-spin' : ''}`} />
new address new address
</button> </button>
</div> </div>
@@ -60,6 +67,20 @@ export const ReceiveView = () => {
payer. payer.
</p> </p>
</> </>
) : addressError ? (
// Deriving an address needs the chain source, so this fails whenever the Esplora endpoint is
// down or rate-limiting. Showing "no address available" for that sent the last debugging
// session looking at derivation code when the answer was a 429 in the response body.
<div className="flex items-start gap-2 text-xs text-destructive">
<TriangleAlert className="mt-0.5 h-3.5 w-3.5 shrink-0" />
<div className="min-w-0">
<p className="break-words">{errorMessage(addressError, 'Could not derive an address')}</p>
<p className="mt-1 text-muted-foreground">
Addresses are derived locally, but the wallet checks the chain to find an unused one. Check{' '}
<span className="font-medium">Settings Chain source</span>.
</p>
</div>
</div>
) : ( ) : (
<p className="text-xs text-muted-foreground">No address available.</p> <p className="text-xs text-muted-foreground">No address available.</p>
)} )}
@@ -5,7 +5,7 @@ import { Check, Eye, KeyRound, Pencil, Star, Trash2, X } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { KIND_LABELS, walletSectionPath } from './shared'; import { KIND_LABELS, walletSectionPath } from './shared';
import { truncateMiddle } from './format'; import { ChainSourceCard } from './ChainSourceCard';
import { CopyField } from './CopyField'; import { CopyField } from './CopyField';
import { EmptyWallet } from './EmptyWallet'; import { EmptyWallet } from './EmptyWallet';
import { LockBadge } from './LockBadge'; import { LockBadge } from './LockBadge';
@@ -130,14 +130,13 @@ export const WalletSettingsView = () => {
</section> </section>
)} )}
<ChainSourceCard />
{config && ( {config && (
<section className="max-w-2xl rounded-xl border border-border p-4"> <section className="max-w-2xl rounded-xl border border-border p-4">
<h3 className="mb-2 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">Deployment</h3> <h3 className="mb-2 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">Deployment</h3>
<dl className="space-y-1.5 text-xs"> <dl className="space-y-1.5 text-xs">
<Row label="Network">{config.network}</Row> <Row label="Network">{config.network}</Row>
<Row label="Esplora">
<span className="font-mono text-[11px]">{truncateMiddle(config.esploraUrl, 28, 12)}</span>
</Row>
<Row label="Max unlock window">{formatMinutes(config.unlockTtlSec)}</Row> <Row label="Max unlock window">{formatMinutes(config.unlockTtlSec)}</Row>
<Row label="Store key"> <Row label="Store key">
{config.storeKeyConfigured ? 'configured' : <span className="text-destructive">missing</span>} {config.storeKeyConfigured ? 'configured' : <span className="text-destructive">missing</span>}
@@ -82,7 +82,6 @@ export type WalletSummary = {
export type WalletConfig = { export type WalletConfig = {
network: BitcoinNetwork; network: BitcoinNetwork;
esploraUrl: string;
unlockTtlSec: number; unlockTtlSec: number;
/** Wallet creation is refused without it, so the UI blocks the form rather than failing on submit. */ /** Wallet creation is refused without it, so the UI blocks the form rather than failing on submit. */
storeKeyConfigured: boolean; storeKeyConfigured: boolean;
@@ -220,22 +220,35 @@ export function useFees(walletId: number | null, enabled = true) {
* A receive address. `peek` returns the current unused address without advancing the derivation index — * A receive address. `peek` returns the current unused address without advancing the derivation index —
* which is what a screen that merely *displays* an address must do, or every render burns an address. * which is what a screen that merely *displays* an address must do, or every render burns an address.
*/ */
type AddressResponse = { address: string; type: string };
export function useReceiveAddress(walletId: number | null, enabled = true) { export function useReceiveAddress(walletId: number | null, enabled = true) {
const { get } = useClient(); const { get } = useClient();
const qc = useQueryClient();
const key = [...ROOT_KEY, 'address', walletId] as const;
const query = useQuery({ const query = useQuery({
queryKey: [...ROOT_KEY, 'address', walletId] as const, queryKey: key,
queryFn: () => get<{ address: string; type: string }>(`${base(walletId!)}/address?peek=true`), queryFn: () => get<AddressResponse>(`${base(walletId!)}/address?peek=true`),
enabled: walletId != null && enabled, enabled: walletId != null && enabled,
staleTime: 60_000, staleTime: 60_000,
}); });
// `peek=false` CONSUMES: the sidecar advances its issued mark so this address is never handed out
// again. Refetching the peeked query returns the same address forever, which is why this is a separate
// call and not `refetch()` — that was the bug behind a "new address" button that changed nothing.
const next = useMutation({
mutationFn: () => get<AddressResponse>(`${base(walletId!)}/address?peek=false`),
onSuccess: (data) => qc.setQueryData(key, data),
onError: (err) => toast.error(errorMessage(err, 'Could not derive a new address')),
});
return { return {
address: query.data?.address ?? null, address: query.data?.address ?? null,
addressType: query.data?.type ?? null, addressType: query.data?.type ?? null,
isLoading: query.isLoading, isLoading: query.isLoading,
error: query.error, error: query.error,
refetch: query.refetch, next,
}; };
} }
@@ -46,11 +46,16 @@ export function serviceErrorMessage(err: unknown): string {
const configKey = (service: string) => [service, 'connection'] as const; const configKey = (service: string) => [service, 'connection'] as const;
const healthKey = (service: string) => [service, 'health'] as const; const healthKey = (service: string) => [service, 'health'] as const;
export function useServiceConnection(service: string) { /**
* `TState` widens the GET body for services that answer with more than the two common fields — the wallet
* adds the URL actually in use and whether it is the owner's or a fallback. The base shape is required, so
* `configured`/`connection` are always there to branch on.
*/
export function useServiceConnection<TState extends ServiceConnectionState = ServiceConnectionState>(service: string) {
const { get } = useClient(); const { get } = useClient();
return useQuery({ return useQuery({
queryKey: configKey(service), queryKey: configKey(service),
queryFn: () => get<ServiceConnectionState>(`/${service}/_config`), queryFn: () => get<TState>(`/${service}/_config`),
staleTime: 60_000, staleTime: 60_000,
retry: false, retry: false,
}); });
@@ -94,14 +99,17 @@ export function useServiceHealth(service: string) {
* Save and forget. Both invalidate the WHOLE service prefix, not just the connection: re-pointing at a * Save and forget. Both invalidate the WHOLE service prefix, not just the connection: re-pointing at a
* different daemon invalidates every list, stat and setting already in the cache. * different daemon invalidates every list, stat and setting already in the cache.
*/ */
export function useServiceConnectionActions<TInput extends Record<string, unknown>>(service: string) { export function useServiceConnectionActions<
TInput extends Record<string, unknown>,
TSaved = { connection: ServiceConnection },
>(service: string) {
const { put, delete: del } = useClient(); const { put, delete: del } = useClient();
const qc = useQueryClient(); const qc = useQueryClient();
const invalidate = () => qc.invalidateQueries({ queryKey: [service] }); const invalidate = () => qc.invalidateQueries({ queryKey: [service] });
const save = useMutation({ const save = useMutation({
mutationFn: (input: TInput) => put<{ connection: ServiceConnection }>(`/${service}/_config`, input), mutationFn: (input: TInput) => put<TSaved>(`/${service}/_config`, input),
onSuccess: invalidate, onSuccess: invalidate,
}); });