run5.py raw
1 #!/usr/bin/env python3
2 """Checkpoint, pause, backup and restore on the page, with every step logged as it happens.
3
4 usage: run5.py <btc-uri> <blake-uri>
5 """
6
7 import asyncio
8 import hashlib
9 import json
10 import os
11 import shutil
12 import sys
13 import time
14
15 from playwright.async_api import async_playwright
16
17 BTC_URI, BLAKE_URI = sys.argv[1], sys.argv[2]
18 HERE = os.path.dirname(os.path.abspath(__file__))
19 OUT = os.path.join(HERE, "evidence-backup")
20 CHUNKS = os.path.join(OUT, "chunks")
21 for directory in (OUT, CHUNKS):
22 os.makedirs(directory, exist_ok=True)
23 LOG_PATH = os.path.join(OUT, "run5.log")
24 PASSPHRASE = "backup-run-passphrase"
25
26
27 def say(line):
28 print(line, flush=True)
29 with open(LOG_PATH, "a") as handle:
30 handle.write(str(line) + "\n")
31
32
33 def card(page, index):
34 return page.locator("#cards .card").nth(index)
35
36
37 async def status_text(page, index):
38 return (await card(page, index).locator(".status").last.inner_text()).strip()
39
40
41 async def wait_status(page, index, prefixes, seconds, label):
42 deadline = time.time() + seconds
43 step = 0
44 text = ""
45 while time.time() < deadline:
46 text = await status_text(page, index)
47 if any(text.startswith(prefix) for prefix in prefixes):
48 say(f"{label}: {text}")
49 return text
50 if step % 5 == 0:
51 say(f"{label}: waiting ({step * 2}s) {text[:100]!r}")
52 step += 1
53 await page.wait_for_timeout(2000)
54 say(f"{label}: timed out with {text[:200]!r}")
55 raise RuntimeError(f"{label}: {text[:200]}")
56
57
58 async def wallet_status(page, index):
59 return await page.evaluate(
60 "(i) => window.wallet.status(i === 0 ? 'btc' : 'blake')", index)
61
62
63 async def connect(page, profiles):
64 for i, (uri, profile) in enumerate(zip((BTC_URI, BLAKE_URI), profiles)):
65 say(f"connect: filling card {i}")
66 await card(page, i).locator("input").nth(0).fill(uri)
67 await card(page, i).locator("input").nth(1).fill(profile)
68 await page.click("#connect", timeout=15000)
69 say("connect: clicked")
70 await page.wait_for_function(
71 "() => { const s = document.getElementById('connect-status').textContent || '';"
72 " return s.startsWith('connected:') || s.startsWith('error:'); }", timeout=120000)
73 status = await page.inner_text("#connect-status")
74 say(f"connect: {status}")
75 if not status.startswith("connected:"):
76 raise RuntimeError(status)
77
78
79 async def create_wallet(page, index, label):
80 say(f"{label}: create")
81 c = card(page, index)
82 await c.locator("input[type=password]").fill(PASSPHRASE)
83 await c.get_by_role("button", name="Create", exact=True).click(timeout=15000)
84 await c.locator(".words").wait_for(timeout=120000)
85 words = (await c.locator(".words").inner_text()).strip()
86 await c.locator("textarea").last.fill(words)
87 await c.get_by_role("button", name="Confirm", exact=True).click(timeout=15000)
88 await page.wait_for_function(
89 """(i) => { const card = document.querySelectorAll('#cards .card')[i];
90 const o = card.querySelectorAll('.status');
91 return (o[o.length-1].textContent || '').startsWith('confirmed.'); }""",
92 arg=index, timeout=120000)
93 address = (await c.locator(".address").last.inner_text()).strip()
94 say(f"{label}: address {address}")
95 return words
96
97
98 async def click_sync(page, index, label):
99 say(f"{label}: click sync")
100 await card(page, index).get_by_role("button", name="Sync", exact=True).click(timeout=15000)
101 await page.wait_for_timeout(500)
102 say(f"{label}: status now {await status_text(page, index)!r}")
103
104
105 def verify_manifest(directory):
106 manifest = json.loads(open(os.path.join(directory, "manifest.json"), "rb").read())
107 if manifest.get("version") != 1:
108 raise RuntimeError("manifest version")
109
110 for chain in manifest["chains"]:
111 for info in chain["chunks"]:
112 path = os.path.join(directory, info["file"])
113 if not os.path.exists(path):
114 raise RuntimeError(f"missing {info['file']}")
115 data = open(path, "rb").read()
116 if len(data) != info["bytes"]:
117 raise RuntimeError(f"{info['file']}: {len(data)} bytes, manifest {info['bytes']}")
118 digest = hashlib.sha256(data).hexdigest()
119 if digest != info["sha256"]:
120 raise RuntimeError(f"{info['file']}: sha256 {digest}, manifest {info['sha256']}")
121 if data[:4] != b"NSBK" or data[4] != 1:
122 raise RuntimeError(f"{info['file']}: not a chunk")
123 kind = data[5]
124 height = int.from_bytes(data[6:10], "little")
125 count = int.from_bytes(data[10:14], "little")
126 if (kind, height, count) != (info["kind"], info["from"], info["count"]):
127 raise RuntimeError(f"{info['file']}: {kind}/{height}/{count} != manifest")
128 say(f"manifest {chain['name']}: anchor {chain['anchor']['height']} tip {chain['tip']} "
129 f"{chain['headers']} headers, {chain['filter_headers']} filter headers, "
130 f"{chain['filters']} filters, {len(chain['chunks'])} chunks, {chain['filter_bytes']} filter bytes")
131 return manifest
132
133
134 async def main():
135 summary = {}
136 profiles = [open(os.path.join(HERE, "profile-btc.json")).read().strip(),
137 open(os.path.join(HERE, "profile-blake.json")).read().strip()]
138 downloads, dialogs = [], []
139
140 async with async_playwright() as p:
141 first = os.path.join(OUT, "profile-first")
142 shutil.rmtree(first, ignore_errors=True)
143 context = await p.chromium.launch_persistent_context(
144 first, viewport={"width": 1280, "height": 1800}, accept_downloads=True)
145 page = context.pages[0] if context.pages else await context.new_page()
146 page.on("console", lambda m: say(f"console {m.type}: {m.text}"))
147 page.on("pageerror", lambda e: say(f"pageerror: {e}"))
148
149 async def save_download(download):
150 path = os.path.join(CHUNKS, download.suggested_filename)
151 await download.save_as(path)
152 downloads.append(path)
153 say(f"download: {download.suggested_filename}")
154
155 page.on("download", lambda d: asyncio.ensure_future(save_download(d)))
156
157 async def note(dialog):
158 dialogs.append(dialog.message)
159 say(f"dialog (auto-prompt): {dialog.message}")
160 await dialog.dismiss()
161
162 page.on("dialog", lambda d: asyncio.ensure_future(note(d)))
163
164 say("open the page")
165 await page.goto("http://127.0.0.1:8080/", wait_until="load", timeout=60000)
166 await page.evaluate("window.__downloadOnlyBackups = true")
167 await connect(page, profiles)
168 await page.screenshot(path=os.path.join(OUT, "01-connected-checkpoints.png"))
169 say("screenshot: 01-connected-checkpoints")
170
171 await create_wallet(page, 0, "btc")
172 await create_wallet(page, 1, "blake")
173
174 await click_sync(page, 0, "btc")
175 btc_text = await wait_status(page, 0, ("from ", "error:"), 900, "btc sync")
176 if btc_text.startswith("error:"):
177 raise RuntimeError(btc_text)
178 btc_state = await wallet_status(page, 0)
179 say(f"btc state: {btc_state}")
180 await page.screenshot(path=os.path.join(OUT, "02-btc-synced-from-checkpoint.png"))
181 say("screenshot: 02-btc-synced-from-checkpoint")
182
183 await click_sync(page, 1, "blake")
184 await page.wait_for_timeout(9000)
185 say("blake: click pause")
186 await card(page, 1).get_by_role("button", name="Pause", exact=True).click(timeout=15000)
187 paused_text = await wait_status(page, 1, ("paused at", "from ", "error:"), 180, "blake paused")
188 paused_state = await wallet_status(page, 1)
189 say(f"blake paused state: {paused_state}")
190 await page.screenshot(path=os.path.join(OUT, "03-blake-paused.png"))
191 say("screenshot: 03-blake-paused")
192
193 await click_sync(page, 1, "blake resume")
194 resumed_text = await wait_status(page, 1, ("from ", "error:"), 900, "blake resumed")
195 if resumed_text.startswith("error:"):
196 raise RuntimeError(resumed_text)
197 resumed_state = await wallet_status(page, 1)
198 say(f"blake resumed state: {resumed_state}")
199 await page.screenshot(path=os.path.join(OUT, "04-blake-resumed.png"))
200 say("screenshot: 04-blake-resumed")
201
202 say("backup: click save")
203 await page.click("#save-backup", timeout=15000)
204 await page.wait_for_function(
205 "() => { const s = document.getElementById('backup-status').textContent || '';"
206 " return s.startsWith('saved ') || s.startsWith('error') || s.includes('needs'); }",
207 timeout=300000)
208 backup_text = await page.inner_text("#backup-status")
209 say(f"backup: {backup_text}")
210 await page.wait_for_timeout(3000)
211 await page.screenshot(path=os.path.join(OUT, "05-backup-saved.png"))
212 say("screenshot: 05-backup-saved")
213
214 manifest = verify_manifest(CHUNKS)
215 summary["backup"] = {"status": backup_text, "manifest": manifest, "dialogs": dialogs,
216 "downloads": [os.path.basename(path) for path in downloads]}
217 await context.close()
218
219 second = os.path.join(OUT, "profile-restored")
220 shutil.rmtree(second, ignore_errors=True)
221 context = await p.chromium.launch_persistent_context(
222 second, viewport={"width": 1280, "height": 1800}, accept_downloads=True)
223 page = context.pages[0] if context.pages else await context.new_page()
224 page.on("console", lambda m: say(f"restore console {m.type}: {m.text}"))
225 say("restore: open the page")
226 await page.goto("http://127.0.0.1:8080/", wait_until="load", timeout=60000)
227 await connect(page, profiles)
228 await create_wallet(page, 0, "btc")
229 await create_wallet(page, 1, "blake")
230
231 before = [await wallet_status(page, 0), await wallet_status(page, 1)]
232 say(f"restore: before {before}")
233
234 files = [os.path.join(CHUNKS, name) for name in sorted(os.listdir(CHUNKS))]
235 say(f"restore: {len(files)} files")
236 await page.set_input_files("#restore-files", files, timeout=60000)
237 await page.wait_for_function(
238 "() => { const s = document.getElementById('backup-status').textContent || '';"
239 " return s.startsWith('restored ') || s.startsWith('btc:') || s.startsWith('blake:')"
240 " || s.includes('missing') || s.includes('does not match') || s.includes('anchored'); }",
241 timeout=300000)
242 restore_text = await page.inner_text("#backup-status")
243 say(f"restore: {restore_text}")
244 if not restore_text.startswith("restored "):
245 raise RuntimeError(restore_text)
246
247 after = [await wallet_status(page, 0), await wallet_status(page, 1)]
248 say(f"restore: after {after}")
249 await page.screenshot(path=os.path.join(OUT, "06-restored.png"))
250 say("screenshot: 06-restored")
251
252 wanted = {chain["name"]: chain["tip"] for chain in manifest["chains"]}
253 for state in after:
254 if state["tip"] != wanted[state["chain"]]:
255 raise RuntimeError(f"{state['chain']}: restored tip {state['tip']}, backup {wanted[state['chain']]}")
256
257 await page.reload(wait_until="load", timeout=60000)
258 await connect(page, profiles)
259 # A reload leaves the seed in IndexedDB and the keys out of memory, so the wallet is
260 # locked: the restored chain is visible (the position is data) but a sync needs the keys.
261 for i, label in ((0, "btc"), (1, "blake")):
262 c = card(page, i)
263 await c.locator("input[type=password]").fill(PASSPHRASE)
264 await c.get_by_role("button", name="Unlock", exact=True).click(timeout=15000)
265 await page.wait_for_timeout(2000)
266 say(f"reload: {label} unlock status {(await status_text(page, i))!r}")
267 state = await wallet_status(page, i)
268 say(f"reload: {label} unlocked {state['unlocked']} tip {state['tip']}")
269 reloaded = [await wallet_status(page, 0), await wallet_status(page, 1)]
270 say(f"reload: {reloaded}")
271 await page.screenshot(path=os.path.join(OUT, "07-reloaded-restored.png"))
272 say("screenshot: 07-reloaded-restored")
273
274 await click_sync(page, 0, "resume after restore")
275 resume_text = await wait_status(page, 0, ("from ", "error:"), 600, "resume after restore")
276 await page.screenshot(path=os.path.join(OUT, "08-resume-after-restore.png"))
277 say("screenshot: 08-resume-after-restore")
278
279 summary["checkpoint"] = {"btc": 23500, "blake": 42000}
280 summary["paused"] = {"text": paused_text, "state": paused_state}
281 summary["resumed"] = {"text": resumed_text, "state": resumed_state}
282 summary["restore"] = {"text": restore_text, "before": before, "after": after,
283 "reloaded": reloaded, "resume": resume_text}
284 await context.close()
285
286 with open(os.path.join(OUT, "summary.json"), "w") as handle:
287 json.dump(summary, handle, indent=2)
288 say("done")
289
290
291 asyncio.run(main())
292