index.html raw

   1  <!doctype html>
   2  <html lang="en">
   3  <head>
   4  <meta charset="utf-8">
   5  <title>tinywallet — two chains, one seed</title>
   6  <link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 16 16%22><rect width=%2216%22 height=%2216%22 fill=%22%230f1115%22/></svg>">
   7  <style>
   8    body { font: 14px/1.5 system-ui, sans-serif; margin: 0; padding: 24px; background: #14161a; color: #e6e6e6; }
   9    h1 { font-size: 18px; margin: 0 0 4px; }
  10    p.note { color: #9aa0a6; margin: 0 0 20px; }
  11    .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(360px, 1fr)); gap: 16px; }
  12    .card { border: 1px solid #2b2f36; border-radius: 10px; padding: 16px; background: #1a1d22; }
  13    .card h2 { font-size: 15px; margin: 0 0 8px; display: flex; justify-content: space-between; }
  14    .status { color: #9aa0a6; font-size: 12px; white-space: pre-wrap; margin: 8px 0; }
  15    label { display: block; margin: 8px 0 2px; color: #9aa0a6; font-size: 12px; }
  16    input, select, textarea { width: 100%; box-sizing: border-box; background: #0f1115; color: #e6e6e6;
  17      border: 1px solid #2b2f36; border-radius: 6px; padding: 6px; font: inherit; }
  18    textarea { height: 64px; resize: vertical; }
  19    button { margin: 8px 6px 0 0; background: #2f6feb; border: 0; color: #fff; border-radius: 6px; padding: 6px 10px; font: inherit; cursor: pointer; }
  20    button.secondary { background: #303540; }
  21    button:disabled { opacity: .45; cursor: default; }
  22    .words { font-family: ui-monospace, monospace; background: #0f1115; border: 1px solid #6b4; border-radius: 6px;
  23      padding: 10px; margin-top: 8px; word-spacing: 8px; line-height: 2; }
  24    .address { font-family: ui-monospace, monospace; color: #8fd18f; word-break: break-all; }
  25    .error { color: #ff8a80; }
  26    .ready { color: #8fd18f; font-weight: 600; }
  27    .card.folded > :not(h2):not(.foldrow):not(.status) { display: none; }
  28    .foldrow { display: flex; gap: 8px; align-items: center; margin-bottom: 8px; }
  29    .foldrow button { padding: 2px 10px; font-size: 12px; }
  30    #swap pre { background: #0f1115; border: 1px solid #333; border-radius: 6px; padding: 10px;
  31      max-height: 260px; overflow: auto; white-space: pre-wrap; }
  32    #swap label { display: block; margin: 6px 0; }
  33  </style>
  34  </head>
  35  <body>
  36  <h1>tinywallet</h1>
  37  <p class="note">Two chains, one seed. The keys never leave this page; the chains are read by
  38  nostrino over the relay, and the wallet talks to it in frames.</p>
  39  
  40  <p><button id="connect">Connect</button> <span id="connect-status" class="status"></span></p>
  41  
  42  <p>
  43    <button id="save-backup" class="secondary">Save a backup of the chain data</button>
  44    <button id="pick-restore" class="secondary">Restore from a backup</button>
  45    <input id="restore-files" type="file" multiple hidden>
  46    <span id="backup-status" class="status"></span>
  47  </p>
  48  
  49  <div class="grid" id="cards"></div>
  50  
  51  <section id="verify" hidden>
  52    <h2>Verify a swap</h2>
  53    <p class="status">Paste the dossier: signed terms, the counterparty's transactions, and the facts
  54      your indexers returned. The wallet decides; nothing here asks the venue.</p>
  55    <div id="indexers"></div>
  56    <textarea id="dossier" rows="10" placeholder='{"terms":{...},"legs":[...],"need":2,"sources":[...]}'></textarea>
  57    <button id="verify-run">Verify</button>
  58    <button id="verify-fetch" class="secondary">Fetch facts from the selected sources</button>
  59    <div id="verify-report"></div>
  60  </section>
  61  
  62  <section id="swap">
  63    <h2>Swap</h2>
  64    <p class="status" id="swap-status">starting the swap worker…</p>
  65    <div id="swap-vault">
  66      <label>swap vault passphrase <input id="swap-passphrase" type="password" size="24" placeholder="seals the swap engine's own state"></label>
  67      <button id="swap-unlock">Unlock vault</button>
  68      <button id="swap-create-vault" class="secondary">Create vault</button>
  69      <button id="swap-lock" class="secondary">Lock</button>
  70    </div>
  71    <div id="swap-form">
  72      <label>BLAKE amount <input id="swap-blake" placeholder="1000" size="12"></label>
  73      <label>BTC sats <input id="swap-sats" placeholder="10000" size="12"></label>
  74      <label>direction
  75        <select id="swap-direction">
  76          <option value="sell-blake">I give BLAKE</option>
  77          <option value="buy-blake">I give BTC</option>
  78        </select>
  79      </label>
  80      <label>minutes <input id="swap-minutes" placeholder="60" size="6"></label>
  81      <button id="swap-create">Create swap</button>
  82      <button id="swap-coins" class="secondary">Wallet coins</button>
  83      <button id="swap-refresh" class="secondary">Refresh state</button>
  84    </div>
  85    <div id="swap-htlc">
  86      <p class="status">The HTLC is the wallet's, not the engine's: it derives the script from the
  87        terms and signs with its own keys. Fill the terms to see what it derives.</p>
  88      <label>chain
  89        <select id="swap-chain">
  90          <option value="btc">btc</option>
  91          <option value="blake">blake</option>
  92        </select>
  93      </label>
  94      <label>claimer x-only pubkey <input id="swap-claimer" size="66" placeholder="64 hex"></label>
  95      <label>refunder x-only pubkey <input id="swap-refunder" size="66" placeholder="64 hex"></label>
  96      <label>secret hash <input id="swap-secret-hash" size="66" placeholder="32 bytes, 64 hex"></label>
  97      <label>locktime <input id="swap-locktime" size="10" placeholder="block height"></label>
  98      <button id="swap-derive">Derive HTLC</button>
  99    </div>
 100    <pre id="swap-view">no state yet</pre>
 101  </section>
 102  
 103  <script type="module">
 104  import { Wallet, Writer, Reader, METHOD } from './wallet.js';
 105  
 106  // The local rig is the default: two regtest chains on one page. The `chains` and `network`
 107  // query parameters point the same page at a live deployment: `?chains=btc&network=btc` is a
 108  // mainnet Bitcoin wallet, and the blake leg follows once its chain profile carries the fork
 109  // checkpoint (the profile JSON is per card, so the two legs can name different files).
 110  const QUERY = new URLSearchParams(location.search);
 111  const WANTED = (QUERY.get('chains') || 'btc,blake').split(',').map((s) => s.trim()).filter(Boolean);
 112  // An explicit chain list means a live deployment; the local rig is what you get with no query at
 113  // all. Guessing regtest for `?chains=btc` is how a mainnet sync gets labelled regtest.
 114  // Mainnet is the product; the rig is what you get by asking for it.
 115  const NETWORK = QUERY.get('network') || 'btc';
 116  
 117  // The network profile is per chain, not one for both: the fork's rules live in the xbt profile
 118  // (its header format, its target shift, its checkpoint), while its transport parameters are
 119  // Bitcoin's. Calling the fork "btc" here is how it synced from genesis instead of its checkpoint.
 120  const profileFor = (name) => (NETWORK === 'regtest' ? 'regtest' : name === 'blake' ? 'xbt' : 'btc');
 121  
 122  const CHAINS = WANTED.filter((name) => name === 'btc' || name === 'blake').map((name) => ({
 123    name,
 124    network: profileFor(name),
 125    label: (name === 'btc' ? 'bitcoin (BTC)' : 'blakecoin (XBT)') + (NETWORK === 'regtest' ? ' · regtest' : ' · mainnet'),
 126  }));
 127  
 128  // Caller wraps a worker whose Go module parks in select{}. Every call is one request.
 129  class Caller {
 130    constructor(worker) {
 131      this.worker = worker;
 132      this.seq = 1;
 133      this.pending = new Map();
 134      this.ready = new Promise((resolve, reject) => (this.settle = { resolve, reject }));
 135      worker.onmessage = (event) => this.receive(event.data);
 136    }
 137  
 138    receive(message) {
 139      if (message.kind === 'ready') return this.settle.resolve();
 140      if (message.kind === 'failed') return this.settle.reject(new Error(message.error));
 141      if (message.kind === 'log') {
 142        // A worker's console is not the page's; the loader forwards it so a failed connection
 143        // says why instead of leaving the page on "opening the workers…".
 144        (window.__workerLogs = window.__workerLogs || []).push(message.level + ': ' + message.text);
 145        console.warn('[worker ' + message.level + '] ' + message.text);
 146        return;
 147      }
 148      if (message.kind !== 'call') return;
 149      const waiter = this.pending.get(message.id);
 150      if (!waiter) return;
 151      this.pending.delete(message.id);
 152      if (message.error) waiter.reject(new Error(message.error));
 153      else waiter.resolve(message.result);
 154    }
 155  
 156    async call(fn, ...args) {
 157      await this.ready;
 158      const id = this.seq++;
 159      // A MessagePort can only cross into a worker if it is transferred, and postMessage
 160      // without a transfer list refuses it outright ("a MessagePort could not be cloned
 161      // because it was not transferred"). The wallet is handed its chain channels inside an
 162      // array of descriptors, so the search for ports is recursive rather than one level deep.
 163      const transfer = [];
 164      const collect = (value) => {
 165        if (value instanceof MessagePort) transfer.push(value);
 166        else if (Array.isArray(value)) value.forEach(collect);
 167        else if (value && typeof value === 'object') Object.values(value).forEach(collect);
 168      };
 169      args.forEach(collect);
 170      return new Promise((resolve, reject) => {
 171        this.pending.set(id, { resolve, reject });
 172        this.worker.postMessage({ kind: 'call', id, fn, args }, transfer);
 173      });
 174    }
 175  }
 176  
 177  let wallet = null;
 178  
 179  function spawn(wasm, global) {
 180    const worker = new Worker('worker.js?wasm=' + encodeURIComponent(wasm) + '&global=' + global);
 181    return new Caller(worker);
 182  }
 183  
 184  function el(tag, attrs = {}, children = []) {
 185    const node = document.createElement(tag);
 186    for (const [key, value] of Object.entries(attrs)) node.setAttribute(key, value);
 187    for (const child of children) node.append(child);
 188    return node;
 189  }
 190  
 191  const cards = new Map();
 192  const refreshers = new Map();
 193  
 194  for (const chain of CHAINS) {
 195    const card = el('div', { class: 'card' });
 196    const title = el('h2', {}, [chain.label]);
 197    const status = el('div', { class: 'status' }, ['not connected']);
 198    const uri = el('input', { placeholder: 'nostr+chaindata://<gateway>?relay=wss://…' });
 199    uri.value = localStorage.getItem('uri:' + chain.name) || '';
 200    const profile = el('input', { placeholder: 'profile JSON (only for a chain with no built-in profile)' });
 201    profile.value = localStorage.getItem('profile:' + chain.name) || '';
 202    const words = el('select');
 203    for (const count of [12, 24]) words.append(el('option', { value: String(count) }, [count + ' words']));
 204    const passphrase = el('input', { type: 'password', placeholder: 'passphrase that seals the seed' });
 205    const phrase = el('textarea', { placeholder: 'the words, to restore' });
 206    let scanBack;
 207    const output = el('div', { class: 'status' });
 208    const actions = el('div');
 209  
 210    const create = el('button', {}, ['Create']);
 211    const restore = el('button', { class: 'secondary' }, ['Restore']);
 212    const unlock = el('button', { class: 'secondary' }, ['Unlock']);
 213    const next = el('button', { class: 'secondary' }, ['Next receive address']);
 214    const sync = el('button', { class: 'secondary' }, ['Sync']);
 215    const scanBackButton = el('button', { class: 'secondary' }, ['Scan back']);
 216    const fullRescanButton = el('button', { class: 'secondary' }, ['Full rescan']);
 217    const pause = el('button', { class: 'secondary' }, ['Pause']);
 218    const coins = el('button', { class: 'secondary' }, ['Coins']);
 219    const lock = el('button', { class: 'secondary' }, ['Lock']);
 220    pause.disabled = true;
 221    actions.append(create, restore, unlock, next, sync, scanBackButton, fullRescanButton, pause, coins, lock);
 222  
 223    const show = (text, className) => {
 224      output.className = 'status' + (className ? ' ' + className : '');
 225      output.textContent = text;
 226    };
 227  
 228    const refresh = async () => {
 229      if (!wallet) return;
 230      try {
 231        const state = await wallet.status(chain.name);
 232        status.textContent =
 233          'profile ' + state.profile + ' · account ' + state.account + ' · ' + state.hrp + '\n' +
 234          (state.hasWallet ? (state.unlocked ? 'unlocked' : 'locked') : 'no wallet yet') +
 235          ' · tip ' + state.tip + ' · filters ' + state.filters +
 236          ' · matches ' + state.matches +
 237          '\naddresses: ' + state.receive + ' receive, ' + state.change + ' change';
 238      } catch (error) {
 239        status.textContent = 'error: ' + error.message;
 240      }
 241    };
 242  
 243    const need = () => {
 244      if (!wallet) throw new Error('connect first');
 245      return wallet;
 246    };
 247  
 248    create.onclick = async () => {
 249      try {
 250        const result = await need().create(chain.name, Number(words.value), passphrase.value);
 251        passphrase.value = '';
 252        show('write these words down. they are the wallet, and they are shown once.', 'error');
 253  
 254        const shown = el('div', { class: 'words' }, [result.mnemonic]);
 255        const confirm = el('textarea', { placeholder: 'type the words back to confirm you have them' });
 256        const check = el('button', {}, ['Confirm']);
 257        const panel = el('div', {}, [shown, el('label', {}, ['confirm']), confirm, check]);
 258        output.after(panel);
 259  
 260        check.onclick = () => {
 261          if (confirm.value.trim().split(/\s+/).join(' ') !== result.mnemonic) {
 262            show('that is not what was shown. the words are still above; copy them exactly.', 'error');
 263            return;
 264          }
 265          panel.remove();
 266          show('confirmed. first receive address (m/84\'/' + (chain.name === 'btc' ? 0 : 1) + '/0\'/0/0):');
 267          output.append(el('div', { class: 'address' }, [result.address]));
 268          refresh();
 269        };
 270      } catch (error) {
 271        show(error.message, 'error');
 272      }
 273    };
 274  
 275    restore.onclick = async () => {
 276      try {
 277        const result = await need().restore(chain.name, phrase.value, passphrase.value);
 278        passphrase.value = '';
 279        phrase.value = '';
 280        show('restored. first receive address:');
 281        output.append(el('div', { class: 'address' }, [result.address]));
 282        refresh();
 283      } catch (error) {
 284        show(error.message, 'error');
 285      }
 286    };
 287  
 288    unlock.onclick = async () => {
 289      try {
 290        await need().unlock(chain.name, passphrase.value);
 291        passphrase.value = '';
 292        show('unlocked');
 293        refresh();
 294      } catch (error) {
 295        show(error.message, 'error');
 296      }
 297    };
 298  
 299    lock.onclick = async () => {
 300      try {
 301        await need().lock(chain.name);
 302        show('locked');
 303        refresh();
 304      } catch (error) {
 305        show(error.message, 'error');
 306      }
 307    };
 308  
 309    next.onclick = async () => {
 310      try {
 311        const state = await need().status(chain.name);
 312        const derived = await need().addresses(chain.name, false, state.receive, 1);
 313        show('receive address ' + derived.indexes[0] + ':');
 314        output.append(el('div', { class: 'address' }, [derived.addresses[0]]));
 315        refresh();
 316      } catch (error) {
 317        show(error.message, 'error');
 318      }
 319    };
 320  
 321    // The walk the wallet wants once it has keys: filters from the tip downwards, stopping after a
 322    // gap. Headers and filter headers were already verified by prepare on connect.
 323    scanBackButton.onclick = async () => {
 324      scanBackButton.disabled = true;
 325      show('scanning back from the tip…');
 326      try {
 327        const result = await need().scanBack(chain.name, 500, 20000);
 328        show('scanned back to ' + result.from + ' (tip ' + result.tip + ', filters ' + result.filters + ')\n' +
 329          result.matched.length + ' match(es)' +
 330          (result.matched.length ? ': ' + result.matched.slice(0, 10).join(', ') : ' — stopped at the gap'));
 331        refresh();
 332      } catch (error) {
 333        show(error.message, 'error');
 334      } finally {
 335        scanBackButton.disabled = false;
 336      }
 337    };
 338  
 339    // Sync is the backwards walk: newest first, stopping once the wallet's activity has clearly
 340    // been passed. That is what a user restoring a wallet is actually looking for.
 341    sync.onclick = async () => {
 342      sync.disabled = true;
 343      pause.disabled = false;
 344      setReadiness(chain.name, 'syncing');
 345      show('syncing backwards from the tip…');
 346      try {
 347        const result = await need().scanBack(chain.name, 500, 20000);
 348        show('scanned back to ' + result.from + ' (tip ' + result.tip + ', filters ' + result.filters + ')\n' +
 349          result.matched.length + ' match(es)' +
 350          (result.matched.length ? ': ' + result.matched.slice(0, 10).join(', ') : ' — stopped at the gap'));
 351        refresh();
 352        askForBackup('sync');
 353      } catch (error) {
 354        show(error.message, 'error');
 355      } finally {
 356        sync.disabled = false;
 357        pause.disabled = true;
 358        setReadiness(chain.name, 'current');
 359      }
 360    };
 361  
 362    // Full rescan is the deliberate version: no gap stop, from genesis, for a wallet with old coins.
 363    fullRescanButton.onclick = async () => {
 364      fullRescanButton.disabled = true;
 365      setReadiness(chain.name, 'syncing');
 366      show('full rescan from genesis, no gap stop…');
 367      try {
 368        await need().setFilterStart(chain.name, 0);
 369        const result = await need().scanBack(chain.name, 500, 0);
 370        show('full rescan reached ' + result.from + ' (tip ' + result.tip + ')\n' +
 371          result.matched.length + ' match(es)');
 372        refresh();
 373      } catch (error) {
 374        show(error.message, 'error');
 375      } finally {
 376        fullRescanButton.disabled = false;
 377        setReadiness(chain.name, 'current');
 378      }
 379    };
 380  
 381    pause.onclick = () => {
 382      if (!need().pause()) {
 383        show('no sync is running');
 384        return;
 385      }
 386      pause.disabled = true;
 387      show('pausing: everything already verified stays in the store');
 388    };
 389  
 390    coins.onclick = async () => {
 391      try {
 392        const held = await need().unspent();
 393        show(held.length ? held.length + ' coin(s)' : 'no coins yet: a match only becomes a coin when a block is fetched and verified');
 394        for (const coin of held) {
 395          output.append(el('div', { class: 'address' }, [coin.value + ' sat · ' + coin.txid + ':' + coin.vout + ' · height ' + coin.height]));
 396        }
 397      } catch (error) {
 398        show(error.message, 'error');
 399      }
 400    };
 401  
 402    const progress = el('div', { class: 'status' }, ['']);
 403    // A folded card keeps the title and the fold row, so a wallet that is not the one being used
 404    // takes a line instead of a screen.
 405    const fold = document.createElement('button');
 406    fold.className = 'secondary';
 407    fold.textContent = 'fold';
 408  
 409    const foldNote = document.createElement('span');
 410    foldNote.className = 'status';
 411  
 412    const foldRow = document.createElement('div');
 413    foldRow.className = 'foldrow';
 414    foldRow.append(fold, foldNote);
 415  
 416    fold.onclick = () => {
 417      const folded = card.classList.toggle('folded');
 418      fold.textContent = folded ? 'unfold' : 'fold';
 419      foldNote.textContent = folded ? 'folded: tip, filters and state stay live' : '';
 420    };
 421    card.append(title, foldRow, progress, status, el('label', {}, ['gateway uri']), uri,
 422      el('label', {}, ['chain name in the URI']), profile,
 423      el('label', {}, ['network profile']), el('div', { class: 'status' }, [chain.network]),
 424      el('label', {}, ['seed']), words, el('label', {}, ['passphrase']), passphrase,
 425      el('label', {}, ['words to restore']), phrase, actions, output);
 426    cards.set(chain.name, card);
 427    refreshers.set(chain.name, refresh);
 428    document.getElementById('cards').append(card);
 429  }
 430  
 431  function presetId(name) {
 432    return 'idx-' + name.replace(/[^a-z0-9]/gi, '-');
 433  }
 434  
 435  async function loadIndexers() {
 436    const box = document.getElementById('indexers');
 437    box.textContent = '';
 438  
 439    if (!wallet) return;
 440  
 441    const presets = await wallet.indexers();
 442  
 443    for (const preset of presets) {
 444      const input = Object.assign(document.createElement('input'), {
 445        type: 'checkbox', id: presetId(preset.name),
 446      });
 447      // Every preset starts selected: a verdict needs a quorum, and leaving the user with one box
 448      // ticked would quietly make the quorum unreachable.
 449      input.checked = true;
 450  
 451      const line = el('label', { class: 'status' }, [
 452        input, ' ' + preset.name + ' · ' + preset.chain + ' · ' + preset.shape +
 453        (preset.note ? ' — ' + preset.note : ''),
 454      ]);
 455      box.append(el('div', {}, [line]));
 456    }
 457  }
 458  
 459  function selectedPresets(presets) {
 460    return presets.filter((preset) => {
 461      const input = document.getElementById(presetId(preset.name));
 462      return input && input.checked;
 463    });
 464  }
 465  
 466  async function fetchEsploraFact(base, txid) {
 467    const root = base.replace(/\/+$/, '');
 468    const response = await fetch(root + '/tx/' + txid);
 469  
 470    // A 404 is the chain saying it has never seen this transaction: that is an answer, and the
 471    // verifier must be able to report it as absence rather than as a source that stayed silent.
 472    if (response.status === 404) return { found: false };
 473    if (!response.ok) throw new Error('HTTP ' + response.status);
 474  
 475    const status = await response.json();
 476    if (!status || !status.status || !status.status.confirmed) return { found: false };
 477    const hex = (await (await fetch(root + '/tx/' + txid + '/hex')).text()).trim();
 478    return { found: true, hex, height: status.status.block_height || 0 };
 479  }
 480  
 481  async function fetchRabidFact(base, txid) {
 482    const root = base.replace(/\/+$/, '');
 483    const response = await fetch(root + '/tx/' + txid);
 484    const body = await response.json();
 485    if (!response.ok || body.error) {
 486      const detail = typeof body.error === 'string' ? body.error : JSON.stringify(body.error || {});
 487      throw new Error('the explorer did not answer for this transaction (pruned: ' + detail + ')');
 488    }
 489    const hex = body.hex || body.raw;
 490    if (!hex) throw new Error('the source returned no transaction bytes');
 491    return { found: true, hex, height: body.block_height || 0 };
 492  }
 493  
 494  // fetchFacts asks the selected sources about every transaction the dossier names, using the
 495  // wallet's own txid computation, and writes the answers back into the dossier. The sources are
 496  // asked for all the transactions at once per source, which is the batching the verifier wants.
 497  async function fetchFacts(dossier) {
 498    const presets = selectedPresets(await wallet.indexers());
 499  
 500    if (!presets.length) throw new Error('select at least two sources for a quorum');
 501  
 502    const hexes = [];
 503    const chainOf = [];
 504  
 505    for (const leg of dossier.legs || []) {
 506      for (const key of ['funding', 'refund', 'claim']) {
 507        if (leg[key]) { hexes.push(leg[key]); chainOf.push(leg.chain); }
 508      }
 509    }
 510  
 511    const ids = await wallet.txids(hexes);
 512    const collected = new Map();
 513  
 514    for (const preset of presets) {
 515      for (let i = 0; i < ids.length; i += 1) {
 516        if (chainOf[i] !== preset.chain) continue;
 517        try {
 518          const fact = preset.shape === 'rabid'
 519            ? await fetchRabidFact(preset.base_url, ids[i])
 520            : await fetchEsploraFact(preset.base_url, ids[i]);
 521          const facts = collected.get(preset.name) || {};
 522          facts[ids[i]] = fact;
 523          collected.set(preset.name, facts);
 524        } catch (error) {
 525          // A source that could not answer is simply absent from the dossier: the verifier
 526          // reports the shortfall rather than silently counting it.
 527          console.warn(preset.name + ': ' + error.message);
 528        }
 529      }
 530    }
 531  
 532    dossier.need = dossier.need || 2;
 533    dossier.sources = [...collected.entries()].map(([name, facts]) => ({ name, facts }));
 534  
 535    return dossier;
 536  }
 537  
 538  document.getElementById('verify-fetch').onclick = async () => {
 539    const out = document.getElementById('verify-report');
 540    out.textContent = '';
 541  
 542    if (!wallet) {
 543      out.className = 'status error';
 544      out.textContent = 'connect first: the fetch needs the wallet to compute txids';
 545      return;
 546    }
 547  
 548    try {
 549      const dossier = JSON.parse(document.getElementById('dossier').value);
 550      const filled = await fetchFacts(dossier);
 551      document.getElementById('dossier').value = JSON.stringify(filled, null, 1);
 552      out.className = 'status';
 553      out.textContent = 'fetched from: ' + filled.sources.map((s) => s.name).join(', ') +
 554        ' — now press Verify';
 555    } catch (error) {
 556      out.className = 'status error';
 557      out.textContent = error.message;
 558    }
 559  };
 560  
 561  document.getElementById('verify-run').onclick = async () => {
 562    const out = document.getElementById('verify-report');
 563    out.textContent = '';
 564  
 565    if (!wallet) {
 566      out.className = 'status error';
 567      out.textContent = 'connect first: the verification runs in the same worker as the wallet';
 568      return;
 569    }
 570  
 571    try {
 572      const report = await wallet.verify(document.getElementById('dossier').value);
 573      const head = el('div', { class: 'status' }, [report.verdict.toUpperCase()]);
 574      head.className = 'status ' + (report.verdict === 'pass' ? '' : 'error');
 575      out.append(head);
 576  
 577      const found = report.checks.filter((check) => check.status === 'pass' || check.status === 'warn');
 578      out.append(el('div', { class: 'status' }, [
 579        'verified by ' + report.agreement + ' of ' + report.quorum + ' independent sources',
 580      ]));
 581  
 582      if (report.independence && report.independence.warnings && report.independence.warnings.length) {
 583        for (const warning of report.independence.warnings) {
 584          out.append(el('div', { class: 'status' }, [warning]));
 585        }
 586      }
 587  
 588      // Unverifiable and failed are different things and are never merged into one list.
 589      const groups = [
 590        ['failed', report.checks.filter((check) => check.status === 'fail')],
 591        ['unverifiable', report.checks.filter((check) => check.status === 'unverifiable')],
 592        ['passed', found],
 593      ];
 594  
 595      for (const [label, checks] of groups) {
 596        if (!checks.length) continue;
 597        out.append(el('h3', {}, [label + ' (' + checks.length + ')']));
 598        for (const check of checks) {
 599          out.append(el('div', { class: 'address' }, [
 600            '[' + check.tier + '] ' + check.name + ' — ' + check.detail +
 601            (check.sources && check.sources.length ? ' · sources: ' + check.sources.join(', ') : ''),
 602          ]));
 603        }
 604      }
 605    } catch (error) {
 606      out.className = 'status error';
 607      out.textContent = error.message;
 608    }
 609  };
 610  
 611  window.connect = async () => {
 612    const chains = [];
 613  
 614    for (const chain of CHAINS) {
 615      const card = cards.get(chain.name);
 616      const uri = card.querySelector('input').value.trim();
 617      const profile = card.querySelectorAll('input')[1].value.trim();
 618      if (!uri) throw new Error(chain.label + ': a gateway URI is needed');
 619  
 620      localStorage.setItem('uri:' + chain.name, uri);
 621      localStorage.setItem('profile:' + chain.name, profile);
 622  
 623      const channel = new MessageChannel();
 624  
 625      // A second channel from the channel worker itself: the sync loop pushes its height on it as
 626      // it climbs, so the card shows progress instead of waiting for the whole request to finish.
 627      const syncChannel = new MessageChannel();
 628      syncChannel.port1.onmessage = (event) => {
 629        let line;
 630        try {
 631          line = JSON.parse(new TextDecoder().decode(new Uint8Array(event.data)));
 632        } catch (error) {
 633          return;
 634        }
 635  
 636        const target = cards.get(chain.name);
 637        if (!target) return;
 638  
 639        const out = target.querySelectorAll('.status')[0];
 640        if (out) out.textContent = line.phase + ' ' + Number(line.tip) + ' · filters ' + Number(line.filters);
 641  
 642        // The channel only sends progress while it is working, so a message is proof the tunnel is
 643        // up. Writing the state line from it removes the stale 'not connected', which was only ever
 644        // the placeholder that refresh() had not overwritten yet.
 645        const state = target.querySelectorAll('.status')[1];
 646        if (state) state.textContent = 'connected · ' + line.phase + ' ' + Number(line.tip);
 647      };
 648  
 649      const caller = spawn('nostrino-channel.wasm', 'nostrinoChannel');
 650      const problem = await caller.call('open', channel.port2, uri, chain.name, profile, syncChannel.port2, chain.network);
 651  
 652      if (problem) throw new Error(chain.label + ': ' + problem);
 653  
 654      // The chain profile's checkpoint is the fork boundary: the light client starts there
 655      // instead of downloading Bitcoin's history again, and the wallet uses the same height to
 656      // decide which coins are this chain's own money.
 657      let forkHeight = 0;
 658      try {
 659        const parsed = JSON.parse(profile);
 660        if (parsed && parsed.checkpoint && parsed.checkpoint.height) forkHeight = parsed.checkpoint.height;
 661      } catch (error) {
 662        // The channel has already refused an unparseable profile; this is only the fork height.
 663      }
 664  
 665      chains.push({ name: chain.name, network: chain.network, forkHeight, port: channel.port1 });
 666    }
 667  
 668    const channel = new MessageChannel();
 669  
 670    wallet = new Wallet(channel.port1);
 671    window.wallet = wallet;
 672  
 673    const caller = spawn('tinywallet.wasm', 'tinywallet');
 674    const problem = await caller.call('open', channel.port2, chains);
 675  
 676    if (problem) throw new Error('wallet: ' + problem);
 677  };
 678  
 679  const connectButton = document.getElementById('connect');
 680  const connectStatus = document.getElementById('connect-status');
 681  connectStatus.textContent = 'not connected: paste a gateway URI in a card and press Connect';
 682  
 683  // readiness is what the top line and the swap tools read: a chain is either still syncing or it
 684  // has been verified to its tip. The swap section is hidden and the top line says "syncing" until
 685  // every chain is current, because a swap priced against a chain that is half verified is a swap
 686  // against a chain nobody can see.
 687  const readiness = new Map();
 688  
 689  function setReadiness(name, state) {
 690    readiness.set(name, state);
 691    updateTopStatus();
 692  }
 693  
 694  function updateTopStatus() {
 695    if (!CHAINS.length) return;
 696  
 697    const syncing = CHAINS.map((c) => c.name).filter((n) => readiness.get(n) !== 'current');
 698    const section = document.getElementById('verify');
 699    const failed = CHAINS.map((c) => c.name).filter((n) => readiness.get(n) === 'failed');
 700  
 701    if (failed.length) {
 702      connectStatus.className = 'status error';
 703      connectStatus.textContent = 'could not verify ' + failed.join(' and ') + ' — press Sync to retry';
 704      if (section) section.hidden = true;
 705  
 706      return;
 707    }
 708  
 709    if (syncing.length) {
 710      connectStatus.className = 'status';
 711      connectStatus.textContent = 'syncing ' + syncing.join(' and ') + '…';
 712      if (section) section.hidden = true;
 713  
 714      return;
 715    }
 716  
 717    connectStatus.className = 'status ready';
 718    connectStatus.textContent = 'up to date: both chains verified to their tips';
 719  
 720    if (section) {
 721      section.hidden = false;
 722  
 723      // The swap tools are the point of the page once the chains are current, so they move above
 724      // the connect row instead of staying under the cards.
 725      if (section.dataset.placed !== '1') {
 726        document.getElementById('connect').parentElement.before(section);
 727        section.dataset.placed = '1';
 728      }
 729    }
 730  }
 731  
 732  connectButton.onclick = async () => {
 733    connectButton.disabled = true;
 734    connectStatus.className = 'status';
 735    connectStatus.textContent = 'opening the workers…';
 736    readiness.clear();
 737    try {
 738      await window.connect();
 739  
 740      for (const chain of CHAINS) readiness.set(chain.name, 'syncing');
 741  
 742      updateTopStatus();
 743    loadIndexers();
 744  
 745    // Verify the chain in the background straight away: headers and filter headers are the cheap
 746    // half and need no seed, so the tip is real before anyone enters words.
 747    // Verifying headers is the first thing that happens and it takes a while, so it says so on the
 748    // page rather than only in the console: a page that looks idle is a page the user thinks is
 749    // broken.
 750    const prepared = [];
 751  
 752    for (const name of cards.keys()) refreshers.get(name)?.();
 753  
 754    updateTopStatus();
 755  
 756    for (const chain of CHAINS) {
 757      const stateLine = cards.get(chain.name).querySelectorAll('.status')[1];
 758      if (stateLine) stateLine.textContent = 'connected · verifying headers and filter headers…';
 759  
 760      // A header sync is a ten-minute conversation over a relay, and a browser tab is allowed to
 761      // stall in the middle of it. One retry costs a few seconds; not retrying costs the whole
 762      // sync, so the page keeps asking until the chain is verified or it has tried enough times to
 763      // conclude the gateway is not coming back.
 764      (async () => {
 765        const tries = 6;
 766  
 767        for (let attempt = 1; attempt <= tries; attempt++) {
 768          try {
 769            const position = await wallet.prepare(chain.name);
 770            console.log('prepared ' + chain.name + ': ' + position);
 771  
 772            prepared.push(chain.name);
 773            refreshers.get(chain.name)?.();
 774            setReadiness(chain.name, 'current');
 775  
 776            return;
 777          } catch (error) {
 778            console.warn('prepare ' + chain.name + ' attempt ' + attempt + ': ' + error.message);
 779  
 780            if (attempt === tries) {
 781              if (stateLine) stateLine.textContent = 'headers failed: ' + error.message;
 782  
 783              setReadiness(chain.name, 'failed');
 784  
 785              return;
 786            }
 787  
 788            if (stateLine) {
 789              stateLine.textContent = 'connected · headers attempt ' + attempt + ' failed, retrying in ' + (2 * attempt) + 's';
 790            }
 791  
 792            await new Promise((resolve) => setTimeout(resolve, 2000 * attempt));
 793          }
 794        }
 795      })();
 796    }
 797    } catch (error) {
 798      connectStatus.textContent = 'error: ' + error.message;
 799      connectButton.disabled = false;
 800    }
 801  };
 802  
 803  // ---------------------------------------------------------------- swap ---
 804  //
 805  // The swap engine runs in its own worker, in the background: it owns that state machine and its
 806  // vault, and it projects what it knows into this card. The page never reaches into it; it sends a
 807  // command envelope and renders the result, which is the same vocabulary the CLI speaks.
 808  const swap = (() => {
 809    const statusEl = document.getElementById('swap-status');
 810    const viewEl = document.getElementById('swap-view');
 811    let worker = null;
 812    let ready = false;
 813    let seq = 0;
 814  
 815    const show = (text, className) => {
 816      statusEl.className = 'status' + (className ? ' ' + className : '');
 817      statusEl.textContent = text;
 818    };
 819  
 820    const send = (envelope) => {
 821      if (!worker) return;
 822      seq += 1;
 823      worker.postMessage(JSON.stringify({ seq, at_ms: Date.now(), ...envelope }));
 824    };
 825  
 826    const command = (name, args) => {
 827      send({ kind: 'command', body: JSON.stringify({ command: name, args: args || {} }) });
 828    };
 829  
 830    const render = (envelope) => {
 831      if (envelope.kind === 'worker-ready') {
 832        ready = true;
 833        show('swap engine ready');
 834        command('engine.dashboard');
 835  
 836        return;
 837      }
 838  
 839      if (envelope.kind === 'hello-ack') {
 840        ready = true;
 841  
 842        return;
 843      }
 844  
 845      if (envelope.kind !== 'command-result') return;
 846  
 847      let result;
 848  
 849      try {
 850        result = JSON.parse(envelope.body || '{}');
 851      } catch (error) {
 852        show('the swap engine sent a result that is not JSON', 'error');
 853  
 854        return;
 855      }
 856  
 857      if (result.ok) {
 858        show(result.command + ' ok', 'ready');
 859      } else {
 860        let problem = result.command + ': ' + (result.error || 'failed');
 861  
 862        // The two failures a new page meets first both have an obvious next action; saying it here
 863        // is the difference between a wall and a step.
 864        if ((result.error || '').includes('no vault')) {
 865          problem += ' — press Create vault, with a passphrase, to make one';
 866        }
 867  
 868        show(problem, 'error');
 869      }
 870  
 871      let text = result.text || '';
 872  
 873      if (result.data) text += (text ? '\n\n' : '') + JSON.stringify(result.data, null, 2);
 874  
 875      viewEl.textContent = text || '(no output)';
 876    };
 877  
 878    try {
 879      worker = new Worker('swap-worker.js');
 880    } catch (error) {
 881      show('the browser refused the swap worker: ' + error, 'error');
 882    }
 883  
 884    if (worker) {
 885      worker.onmessage = (event) => {
 886        if (typeof event.data !== 'string' || !event.data.startsWith('{')) return;
 887  
 888        let envelope;
 889  
 890        try {
 891          envelope = JSON.parse(event.data);
 892        } catch (error) {
 893          return;
 894        }
 895  
 896        render(envelope);
 897      };
 898  
 899      worker.onerror = (event) => {
 900        show('swap worker failed: ' + (event.message || 'unknown'), 'error');
 901      };
 902  
 903      // A worker whose domain is slower than the page still answers: if the ready announcement has
 904      // not arrived, ask.
 905      setTimeout(() => {
 906        if (!ready) send({ kind: 'hello' });
 907      }, 2000);
 908    }
 909  
 910    return { command };
 911  })();
 912  
 913  document.getElementById('swap-refresh').onclick = () => swap.command('engine.dashboard');
 914  
 915  // The swap engine's inputs come from the wallet, not from a second copy of the chain state: this
 916  // is the wallet's own coin list, the same one `unspent` hands to any caller. It is shown here so
 917  // the seam is visible before the engine is wired to it.
 918  document.getElementById('swap-coins').onclick = async () => {
 919    const view = document.getElementById('swap-view');
 920  
 921    if (!wallet) {
 922      document.getElementById('swap-status').className = 'status error';
 923      document.getElementById('swap-status').textContent = 'connect first: the coins come from the wallet';
 924  
 925      return;
 926    }
 927  
 928    try {
 929      const coins = await wallet.unspent();
 930      const lines = coins.map((coin) => coin.value + ' sat · ' + coin.txid + ':' + coin.vout + ' · height ' + coin.height);
 931  
 932      view.textContent = coins.length ? lines.join('\n') : 'no coins: the wallet has no verified matches yet';
 933      document.getElementById('swap-status').className = 'status';
 934      document.getElementById('swap-status').textContent = coins.length + ' coin(s) the swap engine can spend';
 935    } catch (error) {
 936      document.getElementById('swap-status').className = 'status error';
 937      document.getElementById('swap-status').textContent = 'wallet: ' + error.message;
 938    }
 939  };
 940  
 941  // derive and sign are the two calls a swap actually needs from the wallet. They are wired to the
 942  // same buttons as the engine's own state for now, so the contract can be exercised before the
 943  // engine asks for it.
 944  document.getElementById('swap-derive').onclick = async () => {
 945    const view = document.getElementById('swap-view');
 946    const status = document.getElementById('swap-status');
 947  
 948    if (!wallet) {
 949      status.className = 'status error';
 950      status.textContent = 'connect first: the script is derived from the wallet\'s keys';
 951  
 952      return;
 953    }
 954  
 955    try {
 956      const chain = document.getElementById('swap-chain').value;
 957      const claimer = hexBytes(document.getElementById('swap-claimer').value.trim());
 958      const refunder = hexBytes(document.getElementById('swap-refunder').value.trim());
 959      const secretHash = hexBytes(document.getElementById('swap-secret-hash').value.trim());
 960      const locktime = Number(document.getElementById('swap-locktime').value || 0);
 961  
 962      const derived = await wallet.derive(chain, claimer, refunder, secretHash, locktime);
 963  
 964      view.textContent = 'address ' + derived.address + '\nscript ' + bytesHex(derived.script) + '\nprogram ' + bytesHex(derived.program);
 965      status.className = 'status ready';
 966      status.textContent = 'derived the HTLC for ' + chain;
 967    } catch (error) {
 968      status.className = 'status error';
 969      status.textContent = 'derive: ' + error.message;
 970    }
 971  };
 972  
 973  function hexBytes(text) {
 974    if (!/^([0-9a-fA-F]{2})*$/.test(text)) throw new Error('not hex: ' + text);
 975  
 976    const out = new Uint8Array(text.length / 2);
 977  
 978    for (let i = 0; i < out.length; i++) out[i] = parseInt(text.slice(2 * i, 2 * i + 2), 16);
 979  
 980    return out;
 981  }
 982  
 983  function bytesHex(bytes) {
 984    return Array.from(bytes || []).map((b) => b.toString(16).padStart(2, '0')).join('');
 985  }
 986  
 987  // The swap engine keeps its own vault today, so the page has to open it before any engine command
 988  // answers. That is the seam the wallet's own key will replace: once the engine asks the wallet to
 989  // sign, this passphrase box goes away and there is one seed on the page instead of two.
 990  const swapPassphrase = () => document.getElementById('swap-passphrase').value;
 991  
 992  document.getElementById('swap-unlock').onclick = () => {
 993    const passphrase = swapPassphrase();
 994  
 995    if (!passphrase) {
 996      document.getElementById('swap-status').className = 'status error';
 997      document.getElementById('swap-status').textContent = 'the vault needs its passphrase';
 998  
 999      return;
1000    }
1001  
1002    swap.command('vault.unlock', { passphrase });
1003  };
1004  
1005  document.getElementById('swap-create-vault').onclick = () => {
1006    const passphrase = swapPassphrase();
1007  
1008    if (!passphrase) {
1009      document.getElementById('swap-status').className = 'status error';
1010      document.getElementById('swap-status').textContent = 'a new vault needs a passphrase';
1011  
1012      return;
1013    }
1014  
1015    swap.command('vault.create', { passphrase });
1016  };
1017  
1018  document.getElementById('swap-lock').onclick = () => swap.command('vault.lock');
1019  
1020  document.getElementById('swap-create').onclick = () => {
1021    const blake = document.getElementById('swap-blake').value.trim();
1022    const sats = document.getElementById('swap-sats').value.trim();
1023  
1024    if (!blake || !sats) {
1025      document.getElementById('swap-status').className = 'status error';
1026      document.getElementById('swap-status').textContent = 'a swap needs a BLAKE amount and a BTC amount';
1027  
1028      return;
1029    }
1030  
1031    swap.command('engine.new', { blake, sats });
1032  };
1033  
1034  // A backup is the chain data this page paid to download: the headers, filter headers and
1035  // filters the light clients verified. It is written as bounded chunk files and a manifest that
1036  // names each one with its SHA-256, so a copy that lost a file cannot silently restore less.
1037  const KINDS = [
1038    { kind: 1, name: 'headers' },
1039    { kind: 2, name: 'filter_headers' },
1040    { kind: 3, name: 'filters' },
1041  ];
1042  const CHUNK_BYTES = 256 * 1024;
1043  
1044  const backupStatus = document.getElementById('backup-status');
1045  const saveBackup = document.getElementById('save-backup');
1046  const pickRestore = document.getElementById('pick-restore');
1047  const restoreFiles = document.getElementById('restore-files');
1048  
1049  const sayBackup = (text, failed) => {
1050    backupStatus.textContent = text;
1051    backupStatus.className = 'status' + (failed ? ' error' : '');
1052  };
1053  
1054  // chunkName is the file a chunk is written to, matching pkg/backup's naming.
1055  const chunkName = (kindName, from) => kindName + '-' + String(from).padStart(8, '0') + '.nsbk';
1056  
1057  // fileSink writes one file: a chosen directory when the browser has the File System Access
1058  // API, otherwise one download per chunk. Both are a person's file, which is the point.
1059  async function fileSink() {
1060    // __downloadOnlyBackups is the seam a driver uses (and a browser without the File System
1061    // Access API falls back to anyway): one download per file instead of a native picker.
1062    if (window.showDirectoryPicker && !window.__downloadOnlyBackups) {
1063      const directory = await window.showDirectoryPicker({ mode: 'readwrite' });
1064      return async (name, bytes) => {
1065        const handle = await directory.getFileHandle(name, { create: true });
1066        const stream = await handle.createWritable();
1067        await stream.write(bytes);
1068        await stream.close();
1069      };
1070    }
1071    return async (name, bytes) => {
1072      const link = document.createElement('a');
1073      link.href = URL.createObjectURL(new Blob([bytes], { type: 'application/octet-stream' }));
1074      link.download = name;
1075      document.body.append(link);
1076      link.click();
1077      link.remove();
1078      URL.revokeObjectURL(link.href);
1079    };
1080  }
1081  
1082  const hexOf = async (bytes) => Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)))
1083    .map((b) => b.toString(16).padStart(2, '0')).join('');
1084  
1085  // chainAnchor reads the deployment profile's checkpoint: the block both chains share, which the
1086  // light client starts at and the wallet treats as the fork boundary.
1087  function chainAnchor(profileText) {
1088    let profile = {};
1089    try { profile = JSON.parse(profileText); } catch (error) { /* the channel reports it */ }
1090    const checkpoint = profile.checkpoint;
1091    if (checkpoint && checkpoint.height) {
1092      return {
1093        anchor: { height: checkpoint.height, block_hash: checkpoint.block_hash, filter_header: checkpoint.filter_header },
1094        headerFrom: checkpoint.height + 1,
1095        filterFrom: checkpoint.height + 1,
1096      };
1097    }
1098    return {
1099      anchor: { height: 0, block_hash: profile.genesis_hash || '', filter_header: '' },
1100      headerFrom: 1,
1101      filterFrom: 0,
1102    };
1103  }
1104  
1105  async function saveChain(write, chain) {
1106    const profileText = localStorage.getItem('profile:' + chain.name) || '';
1107    const { anchor, headerFrom, filterFrom } = chainAnchor(profileText);
1108    if (!anchor.filter_header) {
1109      throw new Error(chain.label + ': a backup needs the chain profile\'s checkpoint, so the anchor and its filter header are stated');
1110    }
1111    const state = await wallet.status(chain.name);
1112    if (!state.tip) throw new Error(chain.label + ': nothing verified yet');
1113  
1114    const chunks = [];
1115    let filterBytes = 0;
1116    let headers = 0;
1117    let filterHeaders = 0;
1118    let filters = 0;
1119  
1120    for (const { kind, name } of KINDS) {
1121      let from = kind === 1 ? headerFrom : filterFrom;
1122      let added = 0;
1123      for (;;) {
1124        let chunk;
1125        try {
1126          chunk = await wallet.backup(chain.name, kind, from, CHUNK_BYTES);
1127        } catch (error) {
1128          // A wallet that scans recent history has no filters below its birth height; a kind
1129          // that produced nothing is absent, and any failure after a chunk is real.
1130          if (added === 0) break;
1131          throw error;
1132        }
1133        added++;
1134        const file = chunkName(name, chunk.from);
1135        await write(file, chunk.raw);
1136        chunks.push({ file, kind, from: chunk.from, count: chunk.count, bytes: chunk.raw.length, sha256: await hexOf(chunk.raw) });
1137        if (kind === 1) headers += chunk.count;
1138        if (kind === 2) filterHeaders += chunk.count;
1139        if (kind === 3) { filters += chunk.count; filterBytes += chunk.raw.length; }
1140        from = chunk.from + chunk.count;
1141        if (from > state.tip) break;
1142      }
1143    }
1144  
1145    return {
1146      name: chain.name, network: chain.network, anchor,
1147      header_from: headerFrom, filter_from: filterFrom, tip: state.tip,
1148      headers, filter_headers: filterHeaders, filters, filter_bytes: filterBytes, chunks,
1149    };
1150  }
1151  
1152  saveBackup.onclick = async () => {
1153    if (!wallet) { sayBackup('connect first', true); return; }
1154    saveBackup.disabled = true;
1155    try {
1156      sayBackup('choose where to save the backup…');
1157      const write = await fileSink();
1158      const manifest = { version: 1, created: new Date().toISOString(), chains: [] };
1159      for (const chain of CHAINS) {
1160        sayBackup('backing up ' + chain.label + '…');
1161        manifest.chains.push(await saveChain(write, chain));
1162      }
1163      await write('manifest.json', new TextEncoder().encode(JSON.stringify(manifest, null, 2) + '\n'));
1164      sessionStorage.setItem('backup-saved', '1');
1165      const total = manifest.chains.reduce((sum, c) => sum + c.filter_bytes, 0);
1166      sayBackup('saved ' + manifest.chains.length + ' chains, ' + manifest.chains.reduce((n, c) => n + c.chunks.length, 0) +
1167        ' chunk(s), ' + (total / 1048576).toFixed(1) + ' MiB of filters');
1168    } catch (error) {
1169      sayBackup(error.message, true);
1170    } finally {
1171      saveBackup.disabled = false;
1172    }
1173  };
1174  
1175  pickRestore.onclick = () => restoreFiles.click();
1176  
1177  restoreFiles.onchange = async () => {
1178    if (!wallet) { sayBackup('connect first', true); return; }
1179    try {
1180      const files = new Map(Array.from(restoreFiles.files).map((file) => [file.name, file]));
1181      const manifestFile = files.get('manifest.json');
1182      if (!manifestFile) throw new Error('the selection has no manifest.json');
1183      const manifest = JSON.parse(await manifestFile.text());
1184      if (manifest.version !== 1 || !Array.isArray(manifest.chains)) throw new Error('not a version 1 backup');
1185  
1186      for (const chain of manifest.chains) {
1187        const profileText = localStorage.getItem('profile:' + chain.name) || '';
1188        const { anchor } = chainAnchor(profileText);
1189        if (anchor.height !== chain.anchor.height || anchor.block_hash !== chain.anchor.block_hash) {
1190          throw new Error(chain.name + ': the backup is anchored at ' + chain.anchor.height + ', this profile at ' + anchor.height);
1191        }
1192  
1193        sayBackup('restoring ' + chain.name + '…');
1194        for (const kind of [1, 2, 3]) {
1195          for (const info of chain.chunks.filter((chunk) => chunk.kind === kind)) {
1196            const file = files.get(info.file);
1197            if (!file) throw new Error(info.file + ' is missing');
1198            const bytes = new Uint8Array(await file.arrayBuffer());
1199            if (bytes.length !== info.bytes) throw new Error(info.file + ' is ' + bytes.length + ' bytes, the manifest says ' + info.bytes);
1200            if ((await hexOf(bytes)) !== info.sha256) throw new Error(info.file + ' does not match its SHA-256');
1201            await wallet.restoreChunk(chain.name, bytes);
1202          }
1203        }
1204      }
1205      sayBackup('restored ' + manifest.chains.length + ' chain(s); sync to continue from the tip');
1206    } catch (error) {
1207      sayBackup(error.message, true);
1208    }
1209  };
1210  
1211  // askForBackup is the automatic prompt: a sync costs hours of bandwidth, and a person who has
1212  // just paid it should be offered the copy before they close the tab.
1213  function askForBackup(why) {
1214    if (sessionStorage.getItem('backup-saved') || !wallet) return;
1215    if (sessionStorage.getItem('backup-asked') === why) return;
1216    sessionStorage.setItem('backup-asked', why);
1217    if (confirm('Save a backup of the chain data now? It is the expensive part of setting up another instance.')) {
1218      saveBackup.onclick();
1219    }
1220  }
1221  
1222  window.addEventListener('error', (event) => console.error('page:', event.message));
1223  </script>
1224  </body>
1225  </html>
1226