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:
@@ -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's own RPC port will not work.
|
||||
</p>
|
||||
</section>
|
||||
);
|
||||
};
|
||||
@@ -1,5 +1,5 @@
|
||||
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 { formatTimestamp, truncateMiddle } from './format';
|
||||
import { INVOICE_TONES } from './format';
|
||||
@@ -7,7 +7,7 @@ import { Amount } from './Amount';
|
||||
import { CopyField } from './CopyField';
|
||||
import { EmptyWallet, UnsupportedSection } from './EmptyWallet';
|
||||
import { useSelectedWallet } from './useSelectedWallet';
|
||||
import { useCapabilities, useInvoices, useReceiveAddress } from './useWalletData';
|
||||
import { errorMessage, useCapabilities, useInvoices, useReceiveAddress } from './useWalletData';
|
||||
import { CreateInvoiceDialog } from './dialogs/CreateInvoiceDialog';
|
||||
|
||||
// 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 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 [invoiceOpen, setInvoiceOpen] = useState(false);
|
||||
|
||||
@@ -39,10 +45,11 @@ export const ReceiveView = () => {
|
||||
</h3>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => refetch()}
|
||||
className="flex items-center gap-1 text-[11px] text-primary hover:underline"
|
||||
onClick={() => next.mutate()}
|
||||
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
|
||||
</button>
|
||||
</div>
|
||||
@@ -60,6 +67,20 @@ export const ReceiveView = () => {
|
||||
payer.
|
||||
</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>
|
||||
)}
|
||||
|
||||
@@ -5,7 +5,7 @@ import { Check, Eye, KeyRound, Pencil, Star, Trash2, X } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { KIND_LABELS, walletSectionPath } from './shared';
|
||||
import { truncateMiddle } from './format';
|
||||
import { ChainSourceCard } from './ChainSourceCard';
|
||||
import { CopyField } from './CopyField';
|
||||
import { EmptyWallet } from './EmptyWallet';
|
||||
import { LockBadge } from './LockBadge';
|
||||
@@ -130,14 +130,13 @@ export const WalletSettingsView = () => {
|
||||
</section>
|
||||
)}
|
||||
|
||||
<ChainSourceCard />
|
||||
|
||||
{config && (
|
||||
<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>
|
||||
<dl className="space-y-1.5 text-xs">
|
||||
<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="Store key">
|
||||
{config.storeKeyConfigured ? 'configured' : <span className="text-destructive">missing</span>}
|
||||
|
||||
@@ -82,7 +82,6 @@ export type WalletSummary = {
|
||||
|
||||
export type WalletConfig = {
|
||||
network: BitcoinNetwork;
|
||||
esploraUrl: string;
|
||||
unlockTtlSec: number;
|
||||
/** Wallet creation is refused without it, so the UI blocks the form rather than failing on submit. */
|
||||
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 —
|
||||
* 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) {
|
||||
const { get } = useClient();
|
||||
const qc = useQueryClient();
|
||||
const key = [...ROOT_KEY, 'address', walletId] as const;
|
||||
|
||||
const query = useQuery({
|
||||
queryKey: [...ROOT_KEY, 'address', walletId] as const,
|
||||
queryFn: () => get<{ address: string; type: string }>(`${base(walletId!)}/address?peek=true`),
|
||||
queryKey: key,
|
||||
queryFn: () => get<AddressResponse>(`${base(walletId!)}/address?peek=true`),
|
||||
enabled: walletId != null && enabled,
|
||||
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 {
|
||||
address: query.data?.address ?? null,
|
||||
addressType: query.data?.type ?? null,
|
||||
isLoading: query.isLoading,
|
||||
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 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();
|
||||
return useQuery({
|
||||
queryKey: configKey(service),
|
||||
queryFn: () => get<ServiceConnectionState>(`/${service}/_config`),
|
||||
queryFn: () => get<TState>(`/${service}/_config`),
|
||||
staleTime: 60_000,
|
||||
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
|
||||
* 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 qc = useQueryClient();
|
||||
|
||||
const invalidate = () => qc.invalidateQueries({ queryKey: [service] });
|
||||
|
||||
const save = useMutation({
|
||||
mutationFn: (input: TInput) => put<{ connection: ServiceConnection }>(`/${service}/_config`, input),
|
||||
mutationFn: (input: TInput) => put<TSaved>(`/${service}/_config`, input),
|
||||
onSuccess: invalidate,
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user