test_paper_wallets_offline_keys_lesson.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. # SPDX-License-Identifier: Apache-2.0
  2. """The paper wallets and offline key generation lesson: registered, honest about what was run, safe to read.
  3. docs/wiki/Paper-Wallets-Generators-and-Offline-Key-Generation-Tails-Electrum-and-Monero.md is an addition to the
  4. cryptocurrency set (issue 431). A banner that claims more than was run, a command that is not labeled as run or not
  5. run, a real-looking seed phrase, key, address or long hex value, a procedure that generates before the network is
  6. cut, a generator ranked or endorsed, a dated claim with no date, a diagram with no picture or alt text, a table with
  7. an unnamed first header cell, or a register row with no URL and no date would each teach or reveal the wrong thing.
  8. The page is read through tests/wikitext.py page_text(), which strips the generated blocks (the navigation blocks exist only in the published page, issue #521).
  9. """
  10. import itertools
  11. import json
  12. import re
  13. from pathlib import Path
  14. from test_wiki_page_nav import published
  15. from wikitext import glossary_text, nav_text, page_text
  16. ROOT = Path(__file__).resolve().parent.parent
  17. WIKI = ROOT / "docs" / "wiki"
  18. NAME = "Paper-Wallets-Generators-and-Offline-Key-Generation-Tails-Electrum-and-Monero"
  19. PAGE = WIKI / f"{NAME}.md"
  20. WALLETS = "Wallets-and-Key-Custody-Hot-and-Cold-Hardware-Wallets-Recovery-Shamir-and-Multisig"
  21. RUNNING = "Running-Monero-Properly-Hardware-Wallet-Qubes-and-Whonix-Offline-Wallet-and-PiNodeXMR"
  22. LINK = re.compile(r"\]\(([A-Za-z0-9_-]+)\.md(?:#([^)]*))?\)")
  23. ADDRESS = re.compile(
  24. r"\b[13][a-km-zA-HJ-NP-Z1-9]{25,34}\b"
  25. r"|\bbc1[ac-hj-np-z02-9]{11,71}\b"
  26. r"|\b0x[0-9a-fA-F]{40}\b"
  27. r"|\b4[0-9AB][1-9A-HJ-NP-Za-km-z]{93}\b"
  28. )
  29. KEYSHAPE = re.compile(
  30. r"\b[xyztu](?:prv|pub)[1-9A-HJ-NP-Za-km-z]{20,}\b"
  31. r"|\b[5KL][1-9A-HJ-NP-Za-km-z]{50,51}\b"
  32. r"|\babandon abandon\b|\bzoo zoo\b|\blegal winner thank\b|\bmilk sad wage\b"
  33. )
  34. SERVICE_NAME = re.compile(r"\b[a-z2-7]{16,56}\.(?:onion|b32\.i2p)\b")
  35. LONG_HEX = re.compile(r"\b[0-9a-fA-F]{32,}\b")
  36. LONG_BASE64 = re.compile(r"\b[A-Za-z0-9+/]{44,}={0,2}")
  37. PHRASE_LINE = re.compile(r"^(?:[a-z]{3,8} ){11,}[a-z]{3,8}$")
  38. WRAPPED = re.compile(
  39. r"!\[(?P<alt>[^\]\n]*)\]\((?P<path>[^)\n]+)\)\n\n<details>\n<summary>Diagram source \(Mermaid\)</summary>\n\n```mermaid\n(?P<src>.*?)\n```\n\n</details>",
  40. re.DOTALL,
  41. )
  42. FENCE = re.compile(r"^```(\w*)\n(.*?)^```", re.DOTALL | re.MULTILINE)
  43. STATUS_WORDS = ("Read", "Run on", "General knowledge", "**est.**", "Constructed")
  44. URL = re.compile(r"\]\(https?://[^)\s]+\)")
  45. DATE = "2026-11-01"
  46. REASONS = "### The documented reasons"
  47. DISAGREE = "## Where the sources disagree"
  48. TOOLS = "### Tools named as examples"
  49. PROCEDURE = "### The procedure"
  50. QUBES = "### How this differs from the Qubes offline-wallet design"
  51. EXERCISE = "## Free exercise: an offline-generation checklist for a stated threat model"
  52. ORDER = ("download", "verify", "transfer", "cut", "boot", "generate", "record", "derive", "wipe", "fund", "restore", "spend")
  53. MACHINES = {"connected", "media", "offline", "second"}
  54. def text() -> str:
  55. return page_text(PAGE)
  56. def slug(heading: str) -> str:
  57. return re.sub(r"[^a-z0-9-]", "", re.sub(r"[^a-z0-9 -]", "", heading.lower()).strip().replace(" ", "-"))
  58. def headings(body: str) -> set[str]:
  59. return {slug(h) for h in re.findall(r"^#+ (.+)$", body, re.MULTILINE)}
  60. def section(body: str, heading: str) -> str:
  61. level = len(heading) - len(heading.lstrip("#"))
  62. rest = body.split(heading, 1)[1]
  63. return re.split(rf"\n#{{1,{level}}} ", rest)[0]
  64. def register_rows(body: str) -> list[list[str]]:
  65. reg = body.split("## Claims register")[1]
  66. rows = [line for line in reg.splitlines() if line.startswith("|") and not line.startswith("|---")]
  67. return [[c.strip() for c in r.strip("|").split("|")] for r in rows[1:]]
  68. def rows_missing_status(body: str) -> list[str]:
  69. return [r[0] for r in register_rows(body) if not any(w in r[-1] for w in STATUS_WORDS)]
  70. def sourced_rows_without_url_and_date(body: str) -> list[str]:
  71. exempt = ("The maintainer's", "The author's own", "General knowledge", "This page's")
  72. return [
  73. row[0]
  74. for row in register_rows(body)
  75. if not row[1].startswith(exempt) and (not URL.search(row[1]) or DATE not in row[2])
  76. ]
  77. def table_headers(body: str) -> list[list[str]]:
  78. lines = body.splitlines()
  79. return [
  80. [c.strip() for c in line.strip("|").split("|")]
  81. for i, line in enumerate(lines[:-1])
  82. if line.startswith("|") and re.match(r"^\|[-| :]+\|$", lines[i + 1])
  83. ]
  84. def tables(body: str, heading: str) -> list[list[list[str]]]:
  85. """Tables in a section as lists of data rows (cells stripped)."""
  86. result, current = [], []
  87. for line in section(body, heading).splitlines() + [""]:
  88. if re.match(r"^\|[-| :]+\|$", line):
  89. continue
  90. if line.startswith("|"):
  91. current.append([c.strip() for c in line.strip("|").split("|")])
  92. elif current:
  93. result.append(current[1:])
  94. current = []
  95. return result
  96. def code_blocks(body: str) -> list[tuple[str, str, str]]:
  97. """Every fenced block that is not Mermaid: (the nearest non-empty line above it, language, content)."""
  98. out = []
  99. for m in FENCE.finditer(body):
  100. if m.group(1) == "mermaid":
  101. continue
  102. above = [ln for ln in body[: m.start()].splitlines() if ln.strip()]
  103. out.append((above[-1] if above else "", m.group(1), m.group(2)))
  104. return out
  105. def unlabeled_blocks(body: str) -> list[str]:
  106. """Blocks whose lead-in line does not say NOT RUN or RUN on the date."""
  107. return [b[2][:40] for b in code_blocks(body) if not (b[0].startswith("NOT RUN") or b[0].startswith(f"RUN on {DATE}"))]
  108. def phrase_lines(body: str) -> list[str]:
  109. return [ln for _, _, content in code_blocks(body) for ln in content.splitlines() if PHRASE_LINE.match(ln.strip())]
  110. def procedure_problems(rows: list[list[str]]) -> list[str]:
  111. """Row cells: number, kind, machine, network, what happens. The order and the network rules the page promises."""
  112. problems, seen = [], {}
  113. for row in rows:
  114. _, kind, machine, network = row[0], row[1], row[2], row[3]
  115. seen.setdefault(kind, row[0])
  116. if kind not in ORDER:
  117. problems.append(f"unknown kind {kind}")
  118. if machine not in MACHINES:
  119. problems.append(f"unknown machine {machine}")
  120. if machine in ("offline", "second") and network != "off":
  121. problems.append(f"step {row[0]}: {machine} machine with the network {network}")
  122. if machine == "media" and network != "n/a":
  123. problems.append(f"step {row[0]}: media have no network column")
  124. kinds = [r[1] for r in rows]
  125. for a, b in itertools.pairwise(ORDER):
  126. if a in kinds and b in kinds and kinds.index(a) > kinds.index(b):
  127. problems.append(f"{a} comes after {b}")
  128. for needed in ("verify", "cut", "generate", "record", "derive", "restore", "wipe"):
  129. if needed not in kinds:
  130. problems.append(f"no {needed} step")
  131. if "cut" in kinds and "generate" in kinds:
  132. cut = kinds.index("cut")
  133. for i, row in enumerate(rows):
  134. if i > cut and row[2] == "connected" and row[1] not in ("fund", "spend"):
  135. problems.append(f"step {row[0]}: a connected machine after the cut")
  136. return problems
  137. # ---- the page ---------------------------------------------------------------------------------------------------------
  138. def test_the_banner_says_it_was_written_from_documents_and_names_what_was_run_and_not_run():
  139. body = text()
  140. assert body.startswith("# Paper wallets and offline key generation")
  141. assert "Status: unverified draft, written from reading" in body
  142. assert "**Run:**" in body and "**Not run:**" in body and "**Not read:**" in body and DATE in body
  143. assert "throwaway" in body.lower()
  144. assert "## Not verified, plainly" in body
  145. assert "defensive and educational" in body.lower()
  146. assert "no real recovery phrase, key or wallet address" in body.lower()
  147. assert "no price talk, no coin shilling and no trading advice" in body.lower()
  148. def test_the_page_file_carries_no_navigation_block_and_the_published_page_does():
  149. raw = PAGE.read_text(encoding="utf-8")
  150. assert "BEGIN GENERATED PAGE NAV" not in raw # issue #521: the publish step writes them
  151. shown = published(PAGE.stem)
  152. assert shown.count("BEGIN GENERATED PAGE NAV top") == 1 and shown.count("BEGIN GENERATED PAGE NAV bottom") == 1
  153. assert "BEGIN GENERATED" not in text()
  154. def test_every_linked_wiki_page_exists_and_every_anchor_is_a_real_heading():
  155. found = LINK.findall(text())
  156. assert len({t for t, _ in found}) >= 10, "the guard collected too few links"
  157. missing = sorted({t for t, _ in found if not (WIKI / f"{t}.md").exists()})
  158. assert not missing, missing
  159. bad = [
  160. f"{target}#{anchor}"
  161. for target, anchor in found
  162. if anchor and anchor not in headings((WIKI / f"{target}.md").read_text(encoding="utf-8"))
  163. ]
  164. assert not bad, bad
  165. def test_the_page_links_the_pages_it_extends_and_the_setups_it_uses():
  166. links = {t for t, _ in LINK.findall(text())}
  167. for needed in (
  168. WALLETS,
  169. RUNNING,
  170. "How-Monero-Works-Compared-with-Bitcoin-and-Ethereum-DeFi-Mixers-Swaps-and-Ransomware",
  171. "How-Bitcoin-Works-Keys-UTXOs-Mining-and-Why-It-Is-Pseudonymous-and-Traceable",
  172. "Cryptography-Fundamentals-Symmetric-Asymmetric-Hashing-Certificates-and-Keys",
  173. "Backups-Deep-Dive-3-2-1-1-0-Immutability-and-Restore-Testing",
  174. "The-Browsing-Setups-Compared-Tor-Browser-Brave-Whonix-Tails-and-Qubes-with-Whonix",
  175. "Business-Continuity-and-Disaster-Recovery-BCP-and-DR",
  176. "Threat-Model",
  177. ):
  178. assert needed in links, needed
  179. body = text()
  180. assert f"{WALLETS}.md#shamir-secret-sharing-slip39" in body, "the Shamir section of the wallets page is linked"
  181. assert "issue 431" in body.lower()
  182. for issue in ("399", "400"):
  183. assert issue in body, f"issue {issue} is named"
  184. def test_the_lesson_is_registered_in_the_manifest_in_the_cryptocurrency_track_in_order():
  185. nav = nav_text(WIKI)
  186. lines = nav.splitlines()
  187. mine = next(i for i, row in enumerate(lines) if f"page: {NAME}," in row)
  188. wallets = next(i for i, row in enumerate(lines) if f"page: {WALLETS}," in row)
  189. running = next(i for i, row in enumerate(lines) if f"page: {RUNNING}," in row)
  190. assert wallets < mine < running, "after the wallets page and before the running-Monero page"
  191. line = lines[mine]
  192. assert 'status: "draft"' in line and 'subgroup: "Cryptocurrency"' in line and 'audience: "learner"' in line
  193. related = re.search(r"related: \[([^\]]*)\]", line)
  194. assert related, "a related list"
  195. pages = [p.strip() for p in related.group(1).split(",")]
  196. assert 3 <= len(pages) <= 6 and len(set(pages)) == len(pages), pages
  197. assert [p for p in pages if not (WIKI / f"{p}.md").exists()] == []
  198. assert WALLETS in pages and RUNNING in pages
  199. for special in ("Contents.md", "Reading-Order.md", "_Sidebar.md"):
  200. assert f"{NAME}.md" in (WIKI / special).read_text(encoding="utf-8"), special
  201. def test_glossary_rows_point_at_real_headings_and_no_term_is_defined_twice():
  202. heads = headings(text())
  203. glossary = glossary_text(WIKI).splitlines()
  204. terms = [line.split("**")[1].strip().lower() for line in glossary if line.startswith("| **")]
  205. mine = [line for line in glossary if line.startswith("| **") and f"{NAME}.md" in line]
  206. assert len(mine) >= 5, "expected glossary rows for the new terms"
  207. anchors = {a for line in mine for a in re.findall(rf"{NAME}\.md#([a-z0-9-]+)", line)}
  208. assert anchors and anchors <= heads, sorted(anchors - heads)
  209. names = [line.split("**")[1].strip().lower() for line in mine]
  210. assert not sorted({t for t in names if terms.count(t) > 1})
  211. for needed in ("paper wallet", "paper wallet generator", "entropy"):
  212. assert any(n.startswith(needed) for n in names), needed
  213. def test_every_table_has_a_named_first_header_cell_and_the_guard_bites():
  214. heads = table_headers(text())
  215. assert len(heads) >= 10, "the guard collected too few tables"
  216. assert all(h[0] for h in heads), [h for h in heads if not h[0]]
  217. assert table_headers("| | b |\n|---|---|\n| 1 | 2 |\n") == [["", "b"]]
  218. assert table_headers("| a | b |\n|---|---|\n| 1 | 2 |\n") == [["a", "b"]]
  219. def test_no_addresses_keys_phrases_hashes_onion_names_or_money():
  220. body = text()
  221. for pattern in (ADDRESS, KEYSHAPE, SERVICE_NAME, LONG_HEX, LONG_BASE64):
  222. assert not pattern.findall(body), pattern.findall(body)
  223. assert not phrase_lines(body), phrase_lines(body)
  224. assert "—" not in body
  225. assert "$" not in body and "usd" not in body.lower() and "dollar" not in body.lower(), "no money amounts at all"
  226. assert "password: " not in body.lower()
  227. assert "wallet" in body.lower(), "the guard collected nothing"
  228. def test_the_secret_guards_bite():
  229. assert ADDRESS.search("send to 1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa today")
  230. assert ADDRESS.search("send to 0x" + "ab" * 20 + " today")
  231. assert ADDRESS.search("send to 4" + "A" + "b" * 93 + " today")
  232. assert not ADDRESS.search("the placeholders are labels, not addresses")
  233. assert KEYSHAPE.search("the phrase abandon abandon abandon") and KEYSHAPE.search("milk sad wage cup")
  234. assert SERVICE_NAME.search("connect to " + "a" * 16 + ".onion now")
  235. assert LONG_HEX.search("fingerprint " + "ab" * 20) and not LONG_HEX.search("version 7.16 and CVE-2023-39910")
  236. assert LONG_BASE64.search("sig " + "A" * 50)
  237. phrase = "```text\n" + " ".join(["word"] * 12) + "\n```"
  238. assert phrase_lines(phrase) == [" ".join(["word"] * 12)]
  239. assert not phrase_lines("```text\n<word 1> <word 2> ... <word 12>\n```")
  240. # ---- every command is labeled run or not run -------------------------------------------------------------------------
  241. def test_every_command_block_says_whether_it_was_run_and_the_run_block_touched_no_network():
  242. body = text()
  243. blocks = code_blocks(body)
  244. assert len(blocks) >= 5, "the guard collected too few command blocks"
  245. assert not unlabeled_blocks(body), unlabeled_blocks(body)
  246. ran = [b for b in blocks if b[0].startswith(f"RUN on {DATE}")]
  247. assert len(ran) == 1, "one run block: the throwaway signature check"
  248. out = ran[0][2]
  249. assert "Good signature" in out and "BAD signature" in out and "example.invalid" in out
  250. assert "exit=0" in out and "exit=1" in out
  251. for forbidden in ("curl", "wget", "recv-keys", "monero-wallet-cli", "electrum", "ssh"):
  252. assert forbidden not in out.lower(), forbidden
  253. assert "gpg (GnuPG) 2.4.7" in body, "the tool version of the run"
  254. assert any(b[0].startswith("NOT RUN") for b in blocks)
  255. def test_the_label_guard_bites():
  256. good = "NOT RUN, from the docs:\n\n```text\nx\n```\n"
  257. assert not unlabeled_blocks(good)
  258. assert unlabeled_blocks("Here is a command:\n\n```text\nx\n```\n") == ["x\n"]
  259. assert not unlabeled_blocks(f"RUN on {DATE}, throwaway:\n\n```text\nx\n```\n")
  260. assert unlabeled_blocks("RUN on 2026-10-01:\n\n```text\nx\n```\n")
  261. assert not unlabeled_blocks("```mermaid\nflowchart LR\n```\n")
  262. # ---- the history, the reasons and where the sources disagree ----------------------------------------------------------
  263. def test_the_reasons_table_covers_the_documented_problems_with_a_source_each():
  264. rows = tables(text(), REASONS)[0]
  265. assert len(rows) >= 10, "the guard collected too few reasons"
  266. flat = " ".join(" ".join(r).lower() for r in rows)
  267. for needed in (
  268. "printer",
  269. "address reuse",
  270. "change",
  271. "browser",
  272. "random",
  273. "malware",
  274. "photo",
  275. "water",
  276. "single point",
  277. "format",
  278. "sweep",
  279. ):
  280. assert needed in flat, needed
  281. for row in rows:
  282. assert len(row) == 3 and all(row), row
  283. assert "Bitcoin Wiki" in row[2] or "Electrum" in row[2] or "Milk Sad" in row[2] or "bitcoin.org" in row[2] or "est." in row[2], row
  284. def test_the_page_says_where_the_sources_disagree_and_names_them():
  285. part = section(text(), DISAGREE)
  286. rows = tables(text(), DISAGREE)[0]
  287. assert len(rows) >= 4
  288. for needed in ("Bitcoin Wiki", "BIP38", "Unanimously Discourage", "Mastering Bitcoin", "Moneropedia", "Electrum", "2011", "2016"):
  289. assert needed in part, needed
  290. low = part.lower()
  291. assert "seed" in low and "single key" in low
  292. def test_the_documented_cases_are_dated_cited_and_name_no_people():
  293. body = text()
  294. assert "CVE-2023-39910" in body and "Mersenne" in body and "32 bits" in body
  295. assert "air-gapped" in body.lower()
  296. assert "2013-08-11" in body and "Android" in body
  297. assert "2023-07-12" in body
  298. assert "Randstorm" not in body or "not read" in body.lower()
  299. assert "Libbitcoin" in body and "dispute" in body.lower(), "the maintainers' disagreement is reported"
  300. # ---- the generators ---------------------------------------------------------------------------------------------------
  301. def test_the_tools_table_is_dated_names_examples_only_and_ranks_nothing():
  302. rows = tables(text(), TOOLS)[0]
  303. assert len(rows) >= 4, "the guard collected too few tools"
  304. names = " ".join(r[0].lower() for r in rows)
  305. for tool in ("bitaddress", "bip39", "electrum", "monero"):
  306. assert tool in names, tool
  307. for row in rows:
  308. assert len(row) == 4 and all(row), row
  309. assert DATE in row[2], f"maintenance is dated: {row[0]}"
  310. flat = " ".join(" ".join(r) for r in rows)
  311. assert "2016-12-24" in flat, "bitaddress.org's last release is dated"
  312. assert "0.5.6" in flat and "2023-08-01" in flat
  313. body = text().lower()
  314. for banned in ("best generator", "we recommend", "i recommend", "the safest", "top pick", "number one", "ranked first", "winner"):
  315. assert banned not in body, banned
  316. assert "no ranking" in body and "examples" in body
  317. def test_the_judging_checklist_names_the_five_checks_and_how_to_do_each():
  318. part = section(text(), "### How to judge a generator").lower()
  319. for needed in ("open source", "reproducible", "signature", "hash", "no network", "randomness"):
  320. assert needed in part, needed
  321. # ---- the procedure ----------------------------------------------------------------------------------------------------
  322. def test_the_procedure_cuts_the_network_before_it_generates_and_keeps_secrets_off_connected_machines():
  323. rows = tables(text(), PROCEDURE)[0]
  324. assert len(rows) >= 12, "the guard collected too few steps"
  325. assert not procedure_problems(rows), procedure_problems(rows)
  326. kinds = [r[1] for r in rows]
  327. assert kinds.index("verify") < kinds.index("transfer") < kinds.index("cut") < kinds.index("generate")
  328. assert kinds.index("record") < kinds.index("derive") < kinds.index("wipe") < kinds.index("fund")
  329. assert kinds.index("fund") < kinds.index("restore") <= kinds.index("spend")
  330. def test_the_procedure_guard_bites():
  331. def row(n, kind, machine, network):
  332. return [str(n), kind, machine, network, "x"]
  333. good = [
  334. row(1, "download", "connected", "on"),
  335. row(2, "verify", "connected", "on"),
  336. row(3, "transfer", "media", "n/a"),
  337. row(4, "cut", "offline", "off"),
  338. row(5, "boot", "offline", "off"),
  339. row(6, "generate", "offline", "off"),
  340. row(7, "record", "offline", "off"),
  341. row(8, "derive", "second", "off"),
  342. row(9, "wipe", "offline", "off"),
  343. row(10, "fund", "connected", "on"),
  344. row(11, "restore", "second", "off"),
  345. row(12, "spend", "connected", "on"),
  346. ]
  347. assert procedure_problems(good) == []
  348. online = [list(r) for r in good]
  349. online[5][3] = "on"
  350. assert any("offline machine with the network on" in p for p in procedure_problems(online))
  351. late = [good[0], good[1], good[2], good[5], good[3], *good[4:5], *good[6:]]
  352. assert any("comes after" in p for p in procedure_problems(late)), "a generate before the cut is caught as an order problem"
  353. unverified = [r for r in good if r[1] != "verify"]
  354. assert any("no verify step" in p for p in procedure_problems(unverified))
  355. leak = [list(r) for r in good]
  356. leak.insert(7, row(99, "record", "connected", "on"))
  357. assert any("connected machine after the cut" in p for p in procedure_problems(leak))
  358. def test_tails_facts_are_dated_and_the_stick_is_not_a_transfer_medium():
  359. body = text()
  360. assert "Tails" in body and "7.16" in body and "2026-10-29" in body
  361. assert "Offline Mode" in body
  362. assert "Do not use your Tails USB stick to transfer files" in body
  363. assert "write-once" in body.lower() or "write-protect" in body.lower()
  364. assert "most memory" in body
  365. assert "OpenPGP" in body
  366. def test_bitcoin_and_monero_paths_are_both_covered_and_the_seeds_are_told_apart():
  367. body = text()
  368. part = section(body, "### Bitcoin: Electrum")
  369. for needed in ("Electrum", "not BIP39", "master public key", "Wallet", "Information", "sweep", "watch-only"):
  370. assert needed.lower() in part.lower(), needed
  371. monero = section(body, "### Monero: monero-wallet-cli")
  372. for needed in ("--generate-new-wallet", "--stagenet", "seed", "restore height", "25", "seed offset", "hashes.txt"):
  373. assert needed.lower() in monero.lower(), needed
  374. assert "Polyseed" in body
  375. def test_printer_risks_and_the_hand_written_alternative_are_both_discussed():
  376. part = section(text(), "### Printing, or writing by hand").lower()
  377. for needed in ("hard drive", "wi-fi", "spooler", "network", "handwrit", "logged", "no storage"):
  378. assert needed in part, needed
  379. def test_the_qubes_comparison_table_names_both_designs():
  380. rows = tables(text(), QUBES)[0]
  381. assert len(rows) >= 5
  382. flat = " ".join(" ".join(r) for r in rows)
  383. for needed in ("Qubes", "Tails", "RAM", "disk", "dom0", "wallet qube"):
  384. assert needed in flat, needed
  385. assert f"{RUNNING}.md" in section(text(), QUBES)
  386. def test_protecting_the_paper_covers_photos_fire_water_shamir_and_steel():
  387. part = section(text(), "## Protecting the paper").lower()
  388. for needed in ("photo", "fire", "water", "shamir", "steel", "laminat", "split"):
  389. assert needed in part, needed
  390. assert f"{WALLETS}.md#shamir-secret-sharing-slip39" in section(text(), "## Protecting the paper")
  391. # ---- the exercise ------------------------------------------------------------------------------------------------------
  392. def test_the_exercise_has_a_stated_threat_model_and_a_step_by_step_attacker_table():
  393. part = section(text(), EXERCISE)
  394. assert "Threat model:" in part and "throwaway" in part.lower()
  395. rows = tables(text(), EXERCISE)[0]
  396. assert len(rows) >= 11, "the guard collected too few steps"
  397. for row in rows:
  398. assert len(row) == 4 and all(row), row
  399. names = " ".join(r[0].lower() for r in rows)
  400. for needed in ("download", "verify", "disconnect", "generate", "record", "store", "restore", "power off", "printer"):
  401. assert needed in names or needed in " ".join(" ".join(r).lower() for r in rows), needed
  402. assert len(tables(text(), EXERCISE)) == 2, "a worked table and an empty template"
  403. # ---- diagrams ---------------------------------------------------------------------------------------------------------
  404. def test_every_diagram_has_alt_text_a_source_and_a_picture_that_exists():
  405. body = text()
  406. found = list(WRAPPED.finditer(body))
  407. assert len(found) == 3, "expected three diagrams"
  408. assert len(re.findall(r"```mermaid", body)) == len(found), "a Mermaid block has no picture above it"
  409. manifest = json.loads((ROOT / "docs" / "diagrams.json").read_text())
  410. for m in found:
  411. alt = m["alt"].strip()
  412. assert 20 <= len(alt) <= 150, alt
  413. png = (PAGE.parent / m["path"]).resolve()
  414. assert png.is_file(), m["path"]
  415. assert png.relative_to(ROOT).as_posix() in manifest, m["path"]
  416. assert m["src"].lstrip().startswith(("flowchart", "sequenceDiagram")), m["path"]
  417. alts = " ".join(m["alt"].lower() for m in found)
  418. for topic in ("paper wallet", "offline", "attacker"):
  419. assert topic in alts, topic
  420. def test_the_diagram_guard_bites():
  421. bare = "![alt text here](images/x.png)\n\nno details block, so no source\n"
  422. assert not WRAPPED.search(bare)
  423. good = "![alt text here](images/x.png)\n\n<details>\n<summary>Diagram source (Mermaid)</summary>\n\n```mermaid\nflowchart LR\n a --> b\n```\n\n</details>"
  424. assert WRAPPED.search(good)
  425. assert not WRAPPED.search(good.replace("<details>\n", ""))
  426. # ---- the register -----------------------------------------------------------------------------------------------------
  427. def test_every_claims_register_row_has_a_status_a_url_and_the_read_date():
  428. rows = register_rows(text())
  429. assert len(rows) >= 30, "the guard collected too few rows"
  430. assert not rows_missing_status(text())
  431. assert not sourced_rows_without_url_and_date(text())
  432. reg = text().split("## Claims register")[1]
  433. for host in (
  434. "en.bitcoin.it/w/index.php?title=Paper_wallet",
  435. "bitcoin.org/en/secure-your-wallet",
  436. "bip-0038.mediawiki",
  437. "bitcoinbook/bitcoinbook",
  438. "moneropedia/paperwallet.html",
  439. "pointbiz/bitaddress.org",
  440. "iancoleman/bip39",
  441. "electrum.readthedocs.io/en/latest/coldstorage.html",
  442. "electrum.readthedocs.io/en/latest/malware.html",
  443. "electrum.readthedocs.io/en/latest/gpg-check.html",
  444. "electrum.readthedocs.io/en/latest/faq.html",
  445. "tails.net/doc/first_steps/welcome_screen",
  446. "tails.net/doc/about/features",
  447. "tails.net/doc/about/warnings",
  448. "tails.net/install/expert",
  449. "tails.net/install/v2/Tails/amd64/stable/latest.json",
  450. "tails.net/doc/sensitive_documents/printing_and_scanning",
  451. "verify-monero-binaries.md",
  452. "offline-transaction-signing.md",
  453. "monero-wallet-cli-reference.md",
  454. "milksad.info",
  455. "bitcoin.org/en/alert/2013-08-11-android",
  456. "Browser-based_wallet",
  457. "libbitcoin/libbitcoin-explorer",
  458. ):
  459. assert host in reg, host
  460. assert reg.count(DATE) >= 30
  461. def test_the_register_guards_bite():
  462. bad = "## Claims register\n\n| Claim | Source | Status |\n|---|---|---|\n| X | y | maybe |\n"
  463. assert rows_missing_status(bad) == ["X"]
  464. undated = "## Claims register\n\n| Claim | Source | Status |\n|---|---|---|\n| X | [p](https://example.com/p) | Read 2026-10-31 |\n"
  465. assert sourced_rows_without_url_and_date(undated) == ["X"]
  466. nourl = "## Claims register\n\n| Claim | Source | Status |\n|---|---|---|\n| X | a page | Read 2026-11-01 |\n"
  467. assert sourced_rows_without_url_and_date(nourl) == ["X"]
  468. def test_the_unverified_items_are_marked_in_the_register():
  469. rows = {r[0]: r for r in register_rows(text())}
  470. run = next(r for k, r in rows.items() if "throwaway" in k.lower() and "signature" in k.lower())
  471. assert "Run on" in run[2]
  472. notrun = [r for k, r in rows.items() if k.lower().startswith("the offline procedure")]
  473. assert notrun and "**est.**" in notrun[0][2], "the assembled procedure is marked as not run"
  474. # ---- scope and tone ---------------------------------------------------------------------------------------------------
  475. def test_the_page_has_no_price_talk_shilling_evasion_content_or_maintainer_contribution_claims():
  476. body = text().lower()
  477. for banned in (
  478. "to the moon", "shitcoin", "memecoin", "hodl", "lambo", "buy the dip", "bullish", "bearish",
  479. "market cap", "all-time high", "pump", "airdrop", "evade detection", "avoid law enforcement",
  480. "launder money", "hide your funds", "bypass kyc", "how to avoid being traced", "untraceable",
  481. "cryptobro", "mcafee", "to avoid tracing", "stay anonymous", "cover your tracks", "comfortable with cryptocurrency",
  482. "affiliate", "contribut", "pull request", "his fork", "helped build", "authored",
  483. ):
  484. assert banned not in body, banned
  485. assert body.count("price") <= 1 and body.count("trading") <= 1, "only the rule sentence itself uses these words"
  486. assert "no how-to for anything illegal" in body
  487. def test_the_page_never_states_a_security_posture_detail_about_this_repository():
  488. body = text().lower()
  489. for banned in ("this repository", "our firewall", "our droplet", "this project's ssh", "our spacelift", "our doppler"):
  490. assert banned not in body, banned
  491. def test_dates_are_on_the_claims_that_go_stale():
  492. body = text()
  493. for needed in ("2026-08-06", "2024-08-05", "2024-04-28", "2023-11-02", "2026-10-08", "2012-11-20", "2023-08-01"):
  494. assert needed in body, needed
  495. assert "no edit date" in body or "no date" in body