#!/usr/bin/env python3 """Checkpoint, pause, backup and restore on the page, with every step logged as it happens. usage: run5.py """ import asyncio import hashlib import json import os import shutil import sys import time from playwright.async_api import async_playwright BTC_URI, BLAKE_URI = sys.argv[1], sys.argv[2] HERE = os.path.dirname(os.path.abspath(__file__)) OUT = os.path.join(HERE, "evidence-backup") CHUNKS = os.path.join(OUT, "chunks") for directory in (OUT, CHUNKS): os.makedirs(directory, exist_ok=True) LOG_PATH = os.path.join(OUT, "run5.log") PASSPHRASE = "backup-run-passphrase" def say(line): print(line, flush=True) with open(LOG_PATH, "a") as handle: handle.write(str(line) + "\n") def card(page, index): return page.locator("#cards .card").nth(index) async def status_text(page, index): return (await card(page, index).locator(".status").last.inner_text()).strip() async def wait_status(page, index, prefixes, seconds, label): deadline = time.time() + seconds step = 0 text = "" while time.time() < deadline: text = await status_text(page, index) if any(text.startswith(prefix) for prefix in prefixes): say(f"{label}: {text}") return text if step % 5 == 0: say(f"{label}: waiting ({step * 2}s) {text[:100]!r}") step += 1 await page.wait_for_timeout(2000) say(f"{label}: timed out with {text[:200]!r}") raise RuntimeError(f"{label}: {text[:200]}") async def wallet_status(page, index): return await page.evaluate( "(i) => window.wallet.status(i === 0 ? 'btc' : 'blake')", index) async def connect(page, profiles): for i, (uri, profile) in enumerate(zip((BTC_URI, BLAKE_URI), profiles)): say(f"connect: filling card {i}") await card(page, i).locator("input").nth(0).fill(uri) await card(page, i).locator("input").nth(1).fill(profile) await page.click("#connect", timeout=15000) say("connect: clicked") await page.wait_for_function( "() => { const s = document.getElementById('connect-status').textContent || '';" " return s.startsWith('connected:') || s.startsWith('error:'); }", timeout=120000) status = await page.inner_text("#connect-status") say(f"connect: {status}") if not status.startswith("connected:"): raise RuntimeError(status) async def create_wallet(page, index, label): say(f"{label}: create") c = card(page, index) await c.locator("input[type=password]").fill(PASSPHRASE) await c.get_by_role("button", name="Create", exact=True).click(timeout=15000) await c.locator(".words").wait_for(timeout=120000) words = (await c.locator(".words").inner_text()).strip() await c.locator("textarea").last.fill(words) await c.get_by_role("button", name="Confirm", exact=True).click(timeout=15000) await page.wait_for_function( """(i) => { const card = document.querySelectorAll('#cards .card')[i]; const o = card.querySelectorAll('.status'); return (o[o.length-1].textContent || '').startsWith('confirmed.'); }""", arg=index, timeout=120000) address = (await c.locator(".address").last.inner_text()).strip() say(f"{label}: address {address}") return words async def click_sync(page, index, label): say(f"{label}: click sync") await card(page, index).get_by_role("button", name="Sync", exact=True).click(timeout=15000) await page.wait_for_timeout(500) say(f"{label}: status now {await status_text(page, index)!r}") def verify_manifest(directory): manifest = json.loads(open(os.path.join(directory, "manifest.json"), "rb").read()) if manifest.get("version") != 1: raise RuntimeError("manifest version") for chain in manifest["chains"]: for info in chain["chunks"]: path = os.path.join(directory, info["file"]) if not os.path.exists(path): raise RuntimeError(f"missing {info['file']}") data = open(path, "rb").read() if len(data) != info["bytes"]: raise RuntimeError(f"{info['file']}: {len(data)} bytes, manifest {info['bytes']}") digest = hashlib.sha256(data).hexdigest() if digest != info["sha256"]: raise RuntimeError(f"{info['file']}: sha256 {digest}, manifest {info['sha256']}") if data[:4] != b"NSBK" or data[4] != 1: raise RuntimeError(f"{info['file']}: not a chunk") kind = data[5] height = int.from_bytes(data[6:10], "little") count = int.from_bytes(data[10:14], "little") if (kind, height, count) != (info["kind"], info["from"], info["count"]): raise RuntimeError(f"{info['file']}: {kind}/{height}/{count} != manifest") say(f"manifest {chain['name']}: anchor {chain['anchor']['height']} tip {chain['tip']} " f"{chain['headers']} headers, {chain['filter_headers']} filter headers, " f"{chain['filters']} filters, {len(chain['chunks'])} chunks, {chain['filter_bytes']} filter bytes") return manifest async def main(): summary = {} profiles = [open(os.path.join(HERE, "profile-btc.json")).read().strip(), open(os.path.join(HERE, "profile-blake.json")).read().strip()] downloads, dialogs = [], [] async with async_playwright() as p: first = os.path.join(OUT, "profile-first") shutil.rmtree(first, ignore_errors=True) context = await p.chromium.launch_persistent_context( first, viewport={"width": 1280, "height": 1800}, accept_downloads=True) page = context.pages[0] if context.pages else await context.new_page() page.on("console", lambda m: say(f"console {m.type}: {m.text}")) page.on("pageerror", lambda e: say(f"pageerror: {e}")) async def save_download(download): path = os.path.join(CHUNKS, download.suggested_filename) await download.save_as(path) downloads.append(path) say(f"download: {download.suggested_filename}") page.on("download", lambda d: asyncio.ensure_future(save_download(d))) async def note(dialog): dialogs.append(dialog.message) say(f"dialog (auto-prompt): {dialog.message}") await dialog.dismiss() page.on("dialog", lambda d: asyncio.ensure_future(note(d))) say("open the page") await page.goto("http://127.0.0.1:8080/", wait_until="load", timeout=60000) await page.evaluate("window.__downloadOnlyBackups = true") await connect(page, profiles) await page.screenshot(path=os.path.join(OUT, "01-connected-checkpoints.png")) say("screenshot: 01-connected-checkpoints") await create_wallet(page, 0, "btc") await create_wallet(page, 1, "blake") await click_sync(page, 0, "btc") btc_text = await wait_status(page, 0, ("from ", "error:"), 900, "btc sync") if btc_text.startswith("error:"): raise RuntimeError(btc_text) btc_state = await wallet_status(page, 0) say(f"btc state: {btc_state}") await page.screenshot(path=os.path.join(OUT, "02-btc-synced-from-checkpoint.png")) say("screenshot: 02-btc-synced-from-checkpoint") await click_sync(page, 1, "blake") await page.wait_for_timeout(9000) say("blake: click pause") await card(page, 1).get_by_role("button", name="Pause", exact=True).click(timeout=15000) paused_text = await wait_status(page, 1, ("paused at", "from ", "error:"), 180, "blake paused") paused_state = await wallet_status(page, 1) say(f"blake paused state: {paused_state}") await page.screenshot(path=os.path.join(OUT, "03-blake-paused.png")) say("screenshot: 03-blake-paused") await click_sync(page, 1, "blake resume") resumed_text = await wait_status(page, 1, ("from ", "error:"), 900, "blake resumed") if resumed_text.startswith("error:"): raise RuntimeError(resumed_text) resumed_state = await wallet_status(page, 1) say(f"blake resumed state: {resumed_state}") await page.screenshot(path=os.path.join(OUT, "04-blake-resumed.png")) say("screenshot: 04-blake-resumed") say("backup: click save") await page.click("#save-backup", timeout=15000) await page.wait_for_function( "() => { const s = document.getElementById('backup-status').textContent || '';" " return s.startsWith('saved ') || s.startsWith('error') || s.includes('needs'); }", timeout=300000) backup_text = await page.inner_text("#backup-status") say(f"backup: {backup_text}") await page.wait_for_timeout(3000) await page.screenshot(path=os.path.join(OUT, "05-backup-saved.png")) say("screenshot: 05-backup-saved") manifest = verify_manifest(CHUNKS) summary["backup"] = {"status": backup_text, "manifest": manifest, "dialogs": dialogs, "downloads": [os.path.basename(path) for path in downloads]} await context.close() second = os.path.join(OUT, "profile-restored") shutil.rmtree(second, ignore_errors=True) context = await p.chromium.launch_persistent_context( second, viewport={"width": 1280, "height": 1800}, accept_downloads=True) page = context.pages[0] if context.pages else await context.new_page() page.on("console", lambda m: say(f"restore console {m.type}: {m.text}")) say("restore: open the page") await page.goto("http://127.0.0.1:8080/", wait_until="load", timeout=60000) await connect(page, profiles) await create_wallet(page, 0, "btc") await create_wallet(page, 1, "blake") before = [await wallet_status(page, 0), await wallet_status(page, 1)] say(f"restore: before {before}") files = [os.path.join(CHUNKS, name) for name in sorted(os.listdir(CHUNKS))] say(f"restore: {len(files)} files") await page.set_input_files("#restore-files", files, timeout=60000) await page.wait_for_function( "() => { const s = document.getElementById('backup-status').textContent || '';" " return s.startsWith('restored ') || s.startsWith('btc:') || s.startsWith('blake:')" " || s.includes('missing') || s.includes('does not match') || s.includes('anchored'); }", timeout=300000) restore_text = await page.inner_text("#backup-status") say(f"restore: {restore_text}") if not restore_text.startswith("restored "): raise RuntimeError(restore_text) after = [await wallet_status(page, 0), await wallet_status(page, 1)] say(f"restore: after {after}") await page.screenshot(path=os.path.join(OUT, "06-restored.png")) say("screenshot: 06-restored") wanted = {chain["name"]: chain["tip"] for chain in manifest["chains"]} for state in after: if state["tip"] != wanted[state["chain"]]: raise RuntimeError(f"{state['chain']}: restored tip {state['tip']}, backup {wanted[state['chain']]}") await page.reload(wait_until="load", timeout=60000) await connect(page, profiles) # A reload leaves the seed in IndexedDB and the keys out of memory, so the wallet is # locked: the restored chain is visible (the position is data) but a sync needs the keys. for i, label in ((0, "btc"), (1, "blake")): c = card(page, i) await c.locator("input[type=password]").fill(PASSPHRASE) await c.get_by_role("button", name="Unlock", exact=True).click(timeout=15000) await page.wait_for_timeout(2000) say(f"reload: {label} unlock status {(await status_text(page, i))!r}") state = await wallet_status(page, i) say(f"reload: {label} unlocked {state['unlocked']} tip {state['tip']}") reloaded = [await wallet_status(page, 0), await wallet_status(page, 1)] say(f"reload: {reloaded}") await page.screenshot(path=os.path.join(OUT, "07-reloaded-restored.png")) say("screenshot: 07-reloaded-restored") await click_sync(page, 0, "resume after restore") resume_text = await wait_status(page, 0, ("from ", "error:"), 600, "resume after restore") await page.screenshot(path=os.path.join(OUT, "08-resume-after-restore.png")) say("screenshot: 08-resume-after-restore") summary["checkpoint"] = {"btc": 23500, "blake": 42000} summary["paused"] = {"text": paused_text, "state": paused_state} summary["resumed"] = {"text": resumed_text, "state": resumed_state} summary["restore"] = {"text": restore_text, "before": before, "after": after, "reloaded": reloaded, "resume": resume_text} await context.close() with open(os.path.join(OUT, "summary.json"), "w") as handle: json.dump(summary, handle, indent=2) say("done") asyncio.run(main())