test_wallets_key_custody_lesson.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. # SPDX-License-Identifier: Apache-2.0
  2. """The wallets and key custody lesson: registered, honest about what was run, diagrams intact, safe to read.
  3. docs/wiki/Wallets-and-Key-Custody-Hot-and-Cold-Hardware-Wallets-Recovery-Shamir-and-Multisig.md is page 4 of the
  4. five-page cryptocurrency set (issue 399). A banner that claims more than was run, a dead link, a missing registration, a
  5. diagram with no picture or alt text, a recovery phrase or key or address on the page, an affiliate link without its
  6. disclosure beside it, a Raspberry Pi claim stated as fact, a drill script that does not do what the page says, a worked
  7. number that the arithmetic does not give, price talk, or a register row with no URL and no date would each teach or
  8. reveal the wrong thing.
  9. """
  10. import hashlib
  11. import importlib.util
  12. import json
  13. import math
  14. import re
  15. import subprocess
  16. import sys
  17. from pathlib import Path
  18. from wikitext import glossary_text, nav_text
  19. ROOT = Path(__file__).resolve().parent.parent
  20. WIKI = ROOT / "docs" / "wiki"
  21. NAME = "Wallets-and-Key-Custody-Hot-and-Cold-Hardware-Wallets-Recovery-Shamir-and-Multisig"
  22. PAGE = WIKI / f"{NAME}.md"
  23. PAGE_ONE = "Blockchain-Fundamentals-Hashes-Blocks-Nodes-Consensus-and-Forks"
  24. PAGE_TWO = "How-Bitcoin-Works-Keys-UTXOs-Mining-and-Why-It-Is-Pseudonymous-and-Traceable"
  25. HANDS_ON = "Hands-On-Whonix-and-Qubes-OS-Gateway-Split-Compartments-Disposables-and-Policy-Prompts"
  26. LINK =re.compile(r"\]\(([A-Za-z0-9_-]+)\.md(?:#([^)]*))?\)")
  27. # A wallet address in any of the common shapes: legacy Bitcoin, Bech32 Bitcoin, Ethereum and Monero.
  28. ADDRESS = re.compile(
  29. r"\b[13][a-km-zA-HJ-NP-Z1-9]{25,34}\b"
  30. r"|\bbc1[ac-hj-np-z02-9]{11,71}\b"
  31. r"|\b0x[0-9a-fA-F]{40}\b"
  32. r"|\b4[0-9AB][1-9A-HJ-NP-Za-km-z]{93}\b"
  33. )
  34. # Extended keys and wallet-import-format keys, and the two best-known public test phrases.
  35. KEYSHAPE = re.compile(
  36. r"\b[xyztu](?:prv|pub)[1-9A-HJ-NP-Za-km-z]{20,}\b"
  37. r"|\b[5KL][1-9A-HJ-NP-Za-km-z]{50,51}\b"
  38. r"|\babandon abandon\b|\bzoo zoo\b|\blegal winner thank\b"
  39. )
  40. HEX64 = re.compile(r"\b[0-9a-f]{64}\b")
  41. IPV4 = re.compile(r"(?<!release )\b(?:\d{1,3}\.){3}\d{1,3}\b")
  42. WRAPPED = re.compile(
  43. 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>",
  44. re.DOTALL,
  45. )
  46. STATUS_WORDS = ("Read", "Run on", "General knowledge", "**est.**", "Constructed")
  47. URL = re.compile(r"\]\(https?://[^)\s]+\)")
  48. DATE = "2026-11-01"
  49. # The only 64-digit hex value the page may carry: the SHA-256 of the public BIP39 English word list.
  50. PUBLIC_HEX = {"2f5eed53a4727b4bf8880d8f3f199efc90e58503646d9ff8eff3a2ed3b24dbda"}
  51. AFFILIATE = "https://affil.trezor.io/aff_c?offer_id=133&aff_id=32739"
  52. THREATS = "## The threat model"
  53. RECOMMEND = "## The hardware wallet I recommend: Trezor"
  54. EXERCISE = "## Free exercise: create, back up, restore and verify with no funds"
  55. def text() -> str:
  56. return PAGE.read_text(encoding="utf-8")
  57. def slug(heading: str) -> str:
  58. return re.sub(r"[^a-z0-9-]", "", re.sub(r"[^a-z0-9 -]", "", heading.lower()).strip().replace(" ", "-"))
  59. def headings(body: str) -> set[str]:
  60. return {slug(h) for h in re.findall(r"^#+ (.+)$", body, re.MULTILINE)}
  61. def section(body: str, heading: str) -> str:
  62. return body.split(heading)[1].split("\n## ")[0]
  63. def register_rows(body: str) -> list[list[str]]:
  64. reg = body.split("## Claims register")[1]
  65. rows = [line for line in reg.splitlines() if line.startswith("|") and not line.startswith("|---")]
  66. return [[c.strip() for c in r.strip("|").split("|")] for r in rows[1:]]
  67. def rows_missing_status(body: str) -> list[str]:
  68. return [r[0] for r in register_rows(body) if not any(w in r[-1] for w in STATUS_WORDS)]
  69. def sourced_rows_without_url_and_date(body: str) -> list[str]:
  70. """Rows that cite a page must carry a URL and the read date; framing and general-knowledge rows are exempt by name."""
  71. exempt = (
  72. "The maintainer's framing",
  73. "The maintainer's statement",
  74. "The maintainer's position",
  75. "The author's own",
  76. "General knowledge",
  77. )
  78. bad = []
  79. for row in register_rows(body):
  80. if row[1].startswith(exempt):
  81. continue
  82. if not URL.search(row[1]) or DATE not in row[2]:
  83. bad.append(row[0])
  84. return bad
  85. def undisclosed_links(body: str, link: str = AFFILIATE) -> list[int]:
  86. """Positions of the affiliate link with no 'affiliate link' wording and commission statement just before it."""
  87. bad = []
  88. for m in re.finditer(re.escape(link), body):
  89. before = body[max(0, m.start() - 700) : m.start()].lower()
  90. if "affiliate link" not in before or "commission" not in before or "no cost to the reader" not in before:
  91. bad.append(m.start())
  92. return bad
  93. def table_headers(body: str) -> list[list[str]]:
  94. """The header row of every table: a line starting with a pipe, followed by a separator row."""
  95. lines = body.splitlines()
  96. out = []
  97. for i, line in enumerate(lines[:-1]):
  98. if line.startswith("|") and re.match(r"^\|[-| :]+\|$", lines[i + 1]):
  99. out.append([c.strip() for c in line.strip("|").split("|")])
  100. return out
  101. def tables(body: str, heading: str) -> list[list[list[str]]]:
  102. """Tables in a section as lists of data rows (cells stripped)."""
  103. result, current = [], []
  104. for line in section(body, heading).splitlines() + [""]:
  105. if re.match(r"^\|[-| :]+\|$", line):
  106. continue
  107. if line.startswith("|"):
  108. current.append([c.strip() for c in line.strip("|").split("|")])
  109. elif current:
  110. result.append(current[1:])
  111. current = []
  112. return result
  113. def drill_source(body: str) -> str:
  114. part = section(body, EXERCISE)
  115. return re.search(r"```python\n(.*?)\n```", part, re.DOTALL).group(1)
  116. def load_drill(tmp_path: Path):
  117. script = tmp_path / "wallet_drill.py"
  118. script.write_text(drill_source(text()), encoding="utf-8")
  119. spec = importlib.util.spec_from_file_location("wallet_drill", script)
  120. module = importlib.util.module_from_spec(spec)
  121. spec.loader.exec_module(module)
  122. return script, module
  123. def made_up_words(tmp_path: Path) -> tuple[Path, list[str]]:
  124. """A 2,048-word list of invented tokens: the algorithm does not depend on the real words."""
  125. words = [f"w{i:04d}" for i in range(2048)]
  126. path = tmp_path / "words.txt"
  127. path.write_text("\n".join(words) + "\n", encoding="utf-8")
  128. return path, words
  129. # ---- the page ----------------------------------------------------------------------------------------------------
  130. def test_the_banner_says_it_was_written_from_reading_and_names_what_was_run():
  131. body = text()
  132. assert body.startswith("# Wallets and key custody")
  133. assert "Status: unverified draft, written from reading" in body
  134. assert "Nothing on this page was run on a blockchain network, a node or a hardware wallet" in body
  135. assert "**Not run:**" in body and "**Not read:**" in body and DATE in body
  136. assert "## Not verified, plainly" in body
  137. assert "defensive and educational" in body.lower()
  138. assert "I did not open it" in body or "(I did not open it)" in body, "the affiliate link was not opened"
  139. def test_every_linked_wiki_page_exists_and_every_anchor_is_a_real_heading():
  140. found = LINK.findall(text())
  141. assert len({t for t, _ in found}) >= 7, "the guard collected too few links"
  142. missing = sorted({t for t, _ in found if not (WIKI / f"{t}.md").exists()})
  143. assert not missing, missing
  144. bad = []
  145. for target, anchor in found:
  146. if anchor and anchor not in headings((WIKI / f"{target}.md").read_text(encoding="utf-8")):
  147. bad.append(f"{target}#{anchor}")
  148. assert not bad, bad
  149. def test_the_page_links_the_existing_lessons_and_names_the_siblings_correctly():
  150. body = text()
  151. links = {t for t, _ in LINK.findall(body)}
  152. for needed in (
  153. PAGE_ONE,
  154. PAGE_TWO,
  155. "Cryptography-Fundamentals-Symmetric-Asymmetric-Hashing-Certificates-and-Keys",
  156. "Hashing-Encryption-and-Keys",
  157. "Business-Continuity-and-Disaster-Recovery-BCP-and-DR",
  158. "Privacy-vs-Security-Blinds-and-Locks-Physical-Security-and-Monero",
  159. "Tor-I2P-and-the-Darknet-Without-the-Myths",
  160. ):
  161. assert needed in links, needed
  162. assert "#key-management-and-custody-the-hard-part" in body
  163. assert "#what-pinodexmr-documents" in body, "the PiNodeXMR example on the overview page is linked"
  164. # Page three is named in plain text until it is in the wiki, then it must be linked.
  165. monero = sorted(p.stem for p in WIKI.glob("How-Monero*.md"))
  166. if monero:
  167. assert any(stem in links for stem in monero), "the Monero page exists, so it must be linked"
  168. else:
  169. assert "issue 398" in body and "not in the wiki yet" in body
  170. for issue in ("396", "397", "398", "399", "400", "372"):
  171. assert issue in body, f"issue {issue} is named"
  172. assert HANDS_ON in links, "the Qubes and Whonix exercises (issue 372) exist and must be linked"
  173. def test_the_lesson_is_registered_in_contents_reading_order_and_nav():
  174. nav = nav_text(WIKI)
  175. assert f"page: {NAME}," in nav
  176. for special in ("Contents.md", "Reading-Order.md", "_Sidebar.md"):
  177. assert f"{NAME}.md" in (WIKI / special).read_text(encoding="utf-8"), special
  178. line = next(row for row in nav.splitlines() if f"page: {NAME}," in row)
  179. assert 'status: "draft"' in line, "the banner says unverified draft"
  180. assert "Page 4 of 5" in line
  181. def test_glossary_rows_point_at_real_headings():
  182. heads = headings(text())
  183. anchors = set()
  184. rows = 0
  185. for line in glossary_text(WIKI).splitlines():
  186. if f"{NAME}.md" in line:
  187. rows += 1
  188. anchors.update(re.findall(rf"{NAME}\.md#([a-z0-9-]+)", line))
  189. assert rows >= 14, "expected glossary rows for the new terms"
  190. assert anchors and anchors <= heads, sorted(anchors - heads)
  191. def test_every_table_has_a_named_first_header_cell():
  192. heads = table_headers(text())
  193. assert len(heads) >= 10, "the guard collected too few tables"
  194. assert all(h[0] for h in heads), [h for h in heads if not h[0]]
  195. def test_the_table_guard_bites():
  196. assert table_headers("| | b |\n|---|---|\n| 1 | 2 |\n") == [["", "b"]]
  197. assert table_headers("| a | b |\n|---|---|\n| 1 | 2 |\n") == [["a", "b"]]
  198. assert tables("## H\n\n| a | b |\n|---|---|\n| 1 | 2 |\n| 3 | 4 |\n\ntext\n", "## H") == [[["1", "2"], ["3", "4"]]]
  199. def test_no_addresses_keys_phrases_stray_hex_ip_addresses_em_dashes_or_money_amounts():
  200. body = text()
  201. assert not ADDRESS.findall(body), ADDRESS.findall(body)
  202. assert not KEYSHAPE.findall(body), KEYSHAPE.findall(body)
  203. assert not IPV4.findall(body), IPV4.findall(body)
  204. assert "—" not in body
  205. assert "$" not in body and "usd" not in body.lower() and "dollar" not in body.lower(), "no money amounts at all"
  206. found = set(HEX64.findall(body))
  207. assert found, "the guard collected no hash at all"
  208. assert found <= PUBLIC_HEX, sorted(found - PUBLIC_HEX)
  209. assert "wallet" in body.lower(), "the guard collected nothing"
  210. def test_the_secret_guards_bite():
  211. assert ADDRESS.search("send to 1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa today")
  212. assert ADDRESS.search("send to bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq today")
  213. assert ADDRESS.search("send to 0x" + "ab" * 20 + " today")
  214. assert ADDRESS.search("send to 4" + "A" + "b" * 93 + " today")
  215. assert not ADDRESS.search("the placeholder shares A, B and C are labels, not addresses")
  216. assert KEYSHAPE.search("key xprv" + "9" * 30)
  217. assert KEYSHAPE.search("use " + "K" + "x" * 51)
  218. assert KEYSHAPE.search("the phrase abandon abandon abandon")
  219. assert not KEYSHAPE.search("the extended public key is derived from the parent")
  220. assert HEX64.search("key " + "ab" * 32) and "ab" * 32 not in PUBLIC_HEX
  221. assert IPV4.search("host 192.0.2.7") and not IPV4.search("as of release 0.9.7.1")
  222. # ---- the Trezor recommendation and the affiliate link -----------------------------------------------------------------
  223. def test_the_affiliate_link_is_exact_and_always_disclosed_just_before_it():
  224. body = text()
  225. assert body.count(AFFILIATE) >= 1, "the maintainer's link, exactly as given"
  226. assert not undisclosed_links(body), "every occurrence has the disclosure within the preceding text"
  227. top = body[:3500].lower()
  228. assert "affiliate disclosure" in top and "may receive a commission" in top and "no cost to the reader" in top, (
  229. "a prominent disclosure near the top, before any recommendation"
  230. )
  231. assert body.index("Affiliate disclosure") < body.index("## What you will be able to do")
  232. assert "the maintainer's statement" in body and "I did not compare checkout totals" in body
  233. assert "affil.trezor.io" in body, "the host is checked against the one Trezor names"
  234. def test_the_affiliate_guard_bites():
  235. good = (
  236. "> **Affiliate disclosure.** This is an affiliate link and this project may receive a commission at no cost to "
  237. "the reader. [x](" + AFFILIATE + ")"
  238. )
  239. assert undisclosed_links(good) == []
  240. assert undisclosed_links("buy here [x](" + AFFILIATE + ")") != []
  241. assert undisclosed_links("an affiliate link, with a commission. [x](" + AFFILIATE + ")") != [], "needs the cost words"
  242. far = "an affiliate link, a commission, no cost to the reader." + " filler" * 200 + " [x](" + AFFILIATE + ")"
  243. assert undisclosed_links(far) != [], "a disclosure far away does not count"
  244. def test_the_recommendation_states_what_was_and_was_not_verified_about_open_source_and_the_pi():
  245. body = text()
  246. part = section(body, RECOMMEND)
  247. assert "open source" in part.lower() and "GPLv3" in part and "LGPLv3" in part
  248. assert "reproducible-build" in part or "reproducible build" in part.lower()
  249. assert "Raspberry Pi Zero" in part
  250. assert "PiTrezor" in part and "community project" in part and "not Trezor's project" in part
  251. assert "Supported by what I read" in part and "Not supported by what I read" in part
  252. assert "anybody that has your SD card can access your seed words and private key" in part, "the author's own caveat"
  253. assert "not vetted by security professionals" in part, "the Wasabi Wallet post's caution"
  254. assert "we leave further investigation to others" in part, "WalletScrutiny's limit"
  255. assert "diy" in part.lower()
  256. assert "archive copy" in part, "the Wasabi host did not load, and the page says so"
  257. assert "The maintainer's account (not a source)" in part and "built one himself" in part
  258. assert "that it has none is my reading (est.)" in part, "the secure-element point is marked as the author's reading"
  259. assert "The advice to buy the real device stands" in part
  260. assert "development purposes only" in part, "the emulator is for development only"
  261. assert "DIY" in part, "Trezor's own wording about DIY builds is quoted"
  262. assert "buy only from the manufacturer or its authorized channels" in body.lower()
  263. for check in ("holographic seal", "blank", "firmware", "authentication check"):
  264. assert check in part.lower() + section(body, RECOMMEND).lower(), check
  265. assert "trezor.io/resellers" in body
  266. assert "I read no other vendor's documentation" in part
  267. PI_OVERCLAIMS = (
  268. "protection of the real hardware",
  269. "same protection",
  270. "as secure as",
  271. "equivalent wallet",
  272. "equals the real device",
  273. "identical to the real",
  274. "just as secure",
  275. )
  276. PI_NEGATORS = ("not supported", "do not read", "does not", "lacks", "stands", "no source")
  277. def pi_overclaims(body: str) -> list[str]:
  278. """Phrases that put the Pi build level with the real device, with no refusal in the 250 characters around them."""
  279. bad = []
  280. for phrase in PI_OVERCLAIMS:
  281. for m in re.finditer(re.escape(phrase), body, re.IGNORECASE):
  282. context = body[max(0, m.start() - 250) : m.end() + 250].lower()
  283. if not any(n in context for n in PI_NEGATORS):
  284. bad.append(phrase)
  285. return bad
  286. def test_the_page_does_not_claim_the_pi_build_equals_the_real_device():
  287. body = text()
  288. assert "protection of the real hardware" in body, "the guard collected nothing: the refusal sentence is gone"
  289. assert pi_overclaims(body) == []
  290. # The attributed claims stay attributed to a source or marked as a reading.
  291. assert body.count("PiTrezor") >= 8
  292. def test_the_pi_overclaim_guard_bites():
  293. assert pi_overclaims("A PiTrezor gives the same protection as the real device.") == ["same protection"]
  294. assert pi_overclaims("The Pi build is just as secure, and cheaper.") == ["just as secure"]
  295. assert pi_overclaims("It is an equivalent wallet, and cheaper.") == ["equivalent wallet"]
  296. assert pi_overclaims("Not supported: that it gives the protection of the real hardware.") == []
  297. far = "It is as secure as the real device." + " filler" * 200 + " not supported"
  298. assert pi_overclaims(far) == ["as secure as"], "a refusal far away does not count"
  299. def test_no_other_vendor_is_named_or_attacked_and_the_pi_is_not_stated_as_fact():
  300. body = text()
  301. for vendor in ("Coldcard", "BitBox", "KeepKey", "Keystone", "Ledger Nano", "Ledger Stax", "Ledger Flex", "SafePal"):
  302. assert vendor not in body, vendor
  303. for claim in ("any Raspberry Pi can be a Trezor", "runs on a Raspberry Pi Zero", "can run Trezor firmware"):
  304. for m in re.finditer(re.escape(claim), body):
  305. context = body[max(0, m.start() - 200) : m.end() + 200].lower()
  306. assert any(w in context for w in ("rewrite", "not supported", "unverified", "could not")), claim
  307. # ---- BIP39, SLIP39 and the toy arithmetic ------------------------------------------------------------------------------
  308. def test_the_bip39_table_is_the_arithmetic_the_standard_gives():
  309. body = text()
  310. part = body.split("| Entropy (bits) |")[1].split("\n\n")[0]
  311. rows = [[c.strip() for c in line.strip("|").split("|")] for line in part.splitlines()[2:]]
  312. assert len(rows) == 5, "the guard collected too few rows"
  313. for ent, cs, total, words in rows:
  314. ent, cs, total, words = int(ent), int(cs), int(total), int(words)
  315. assert cs == ent // 32 and ent % 32 == 0
  316. assert total == ent + cs and total % 11 == 0 and words == total // 11
  317. assert [int(r[3]) for r in rows] == [12, 15, 18, 21, 24]
  318. assert 2**11 == 2048
  319. # One random wrong word in a 12-word phrase passes the 4-bit checksum about once in sixteen.
  320. assert 2 ** (11 * 12) // 2 ** (128) == 16
  321. assert "2,048 words" in body and "2,048 rounds" in body
  322. def test_the_slip39_sizes_on_the_page_add_up():
  323. body = text()
  324. # id 15, ext 1, e 4, GI 4, Gt 4, g 4, I 4, t 4 = 40 bits of header; ps = padding plus the secret; checksum 30.
  325. header, checksum = 15 + 1 + 4 * 6, 30
  326. for secret_bits, padded, words in ((128, 130, 20), (256, 260, 33)):
  327. assert padded % 10 == 0 and padded >= secret_bits and padded - secret_bits < 10
  328. assert (header + padded + checksum) == words * 10
  329. assert "20-word" in body and "33-word" in body
  330. assert "1,024" in body and "16 groups" in body
  331. def test_the_toy_shamir_numbers_are_what_the_arithmetic_gives():
  332. body = text()
  333. rows = {r[0]: (int(r[1]), int(r[2])) for r in tables(body, "## Shamir secret sharing (SLIP39)")[0]}
  334. assert set(rows) == {"A", "B", "C"}, "the guard collected the three shares"
  335. p = 97
  336. def f(x: int) -> int:
  337. return (42 + 7 * x) % p
  338. assert {k: v[1] for k, v in rows.items()} == {"A": f(1), "B": f(2), "C": f(3)}
  339. def recover(a: tuple[int, int], b: tuple[int, int]) -> int:
  340. (x1, y1), (x2, y2) = a, b
  341. return (y1 * x2 * pow(x2 - x1, -1, p) + y2 * x1 * pow(x1 - x2, -1, p)) % p
  342. pts = list(rows.values())
  343. for i in range(3):
  344. for j in range(i + 1, 3):
  345. assert recover(pts[i], pts[j]) == 42, "any two shares give the secret"
  346. # One share is consistent with every secret: for each s there is exactly one slope a with s + 2a = 56.
  347. x, y = rows["B"]
  348. consistent = {s for s in range(p) if any((s + a * x) % p == y for a in range(p))}
  349. assert consistent == set(range(p)) and len(consistent) == 97
  350. assert "all 97 secrets" in body and "42" in body
  351. def test_the_shamir_guard_bites():
  352. p = 97
  353. pts = [(1, (42 + 7) % p), (2, (42 + 14) % p)]
  354. (x1, y1), (x2, y2) = pts
  355. assert (y1 * x2 * pow(x2 - x1, -1, p) + y2 * x1 * pow(x1 - x2, -1, p)) % p == 42
  356. wrong = [(1, 50), (2, (42 + 14) % p)]
  357. (x1, y1), (x2, y2) = wrong
  358. assert (y1 * x2 * pow(x2 - x1, -1, p) + y2 * x1 * pow(x1 - x2, -1, p)) % p != 42, "a wrong share gives a wrong secret"
  359. def test_the_multisig_counts_on_the_page_are_what_combinatorics_gives():
  360. body = text()
  361. n, m = 3, 2
  362. assert math.comb(n, m) == 3 and sum(math.comb(n, k) for k in range(m, n + 1)) == 4
  363. assert n - m == 1 and m - 1 == 1, "one key lost and one key stolen are both survivable at 2-of-3"
  364. part = section(body, "## Multisignature wallets")
  365. assert "2-of-3" in part and "any one key can be lost" in part and "any one key can be stolen" in part
  366. # ---- the drill script on the page -------------------------------------------------------------------------------------
  367. def test_the_drill_script_has_no_network_or_file_writes_and_is_the_page_text(tmp_path):
  368. source = drill_source(text())
  369. for banned in ("socket", "urllib", "requests", "http", "subprocess", "os.system", "open(path, \"w", ".write("):
  370. assert banned not in source, banned
  371. assert "open(path, encoding=" in source, "the only file access is reading the word list"
  372. assert 'if __name__ == "__main__":' in source
  373. def test_the_drill_round_trips_checks_and_matches_an_independent_computation(tmp_path):
  374. _script, drill = load_drill(tmp_path)
  375. _path, words = made_up_words(tmp_path)
  376. entropy = bytes(range(16))
  377. phrase = drill.to_phrase(entropy, words)
  378. assert len(phrase.split()) == 12 and all(w in set(words) for w in phrase.split())
  379. assert drill.from_phrase(phrase, words) == entropy
  380. # Independent computation with integers: 128 bits of entropy then the first 4 bits of SHA-256, 11 bits per word.
  381. big = int.from_bytes(entropy, "big") << 4 | (hashlib.sha256(entropy).digest()[0] >> 4)
  382. expected = [words[(big >> (11 * (11 - i))) & 0x7FF] for i in range(12)]
  383. assert phrase.split() == expected
  384. # A changed word is either refused or restores some other wallet; it can never restore the original.
  385. parts = phrase.split()
  386. parts[4] = words[(words.index(parts[4]) + 1) % 2048]
  387. assert drill.from_phrase(" ".join(parts), words) != entropy
  388. assert drill.from_phrase(phrase + " " + words[0], words) is None, "a 13-word phrase is refused"
  389. assert drill.from_phrase(" ".join(["notaword"] * 12), words) is None, "unknown words are refused"
  390. # The seed follows the standard's shape: 64 bytes, deterministic, and the passphrase changes it without an error.
  391. seed = drill.seed(phrase)
  392. assert len(seed) == 64 and seed == drill.seed(phrase)
  393. assert drill.seed(phrase, "x") != seed and drill.seed(phrase, "x") != drill.seed(phrase, "y")
  394. assert seed == hashlib.pbkdf2_hmac("sha512", phrase.encode(), b"mnemonic", 2048)
  395. assert drill.label(seed) == hashlib.sha256(seed).hexdigest()[:8]
  396. def test_the_drill_catches_about_fifteen_in_sixteen_wrong_words(tmp_path):
  397. script, _drill = load_drill(tmp_path)
  398. path, _words = made_up_words(tmp_path)
  399. out = subprocess.run(
  400. [sys.executable, "-I", str(script), str(path), "break"], capture_output=True, text=True, check=True, timeout=120
  401. ).stdout
  402. m = re.search(r"in (\d+) made-up phrases: the checksum caught (\d+), missed (\d+)", out)
  403. assert m, out
  404. trials, caught, missed = map(int, m.groups())
  405. assert trials == 300 and caught + missed == trials
  406. assert 0.90 <= caught / trials <= 0.97, "about 15/16 are caught"
  407. def test_the_drill_make_and_check_agree_through_the_command_line(tmp_path):
  408. script, _drill = load_drill(tmp_path)
  409. path, _words = made_up_words(tmp_path)
  410. run = [sys.executable, "-I", str(script), str(path)]
  411. made = subprocess.run([*run, "make"], capture_output=True, text=True, check=True, timeout=120).stdout
  412. phrase = re.search(r"throwaway phrase: (.+)", made).group(1)
  413. first = re.search(r"fingerprint, no passphrase: ([0-9a-f]{8})", made).group(1)
  414. checked = subprocess.run(
  415. [*run, "check"], input=phrase + "\nhorse\n", capture_output=True, text=True, check=True, timeout=120
  416. ).stdout
  417. assert "checksum: ok" in checked
  418. assert re.search(r"fingerprint, no passphrase: " + first, checked), "the restore matches the backup"
  419. with_pass = re.search(r"fingerprint, with passphrase: ([0-9a-f]{8})", checked).group(1)
  420. assert with_pass != first, "a passphrase gives a different wallet and no error"
  421. bad_words = phrase.split()
  422. bad_words[0] = "w9999"
  423. bad = subprocess.run(
  424. [*run, "check"], input=" ".join(bad_words) + "\n", capture_output=True, text=True, check=True, timeout=120
  425. ).stdout
  426. assert "checksum: FAILED" in bad
  427. def test_the_drill_guard_bites(tmp_path):
  428. _script, drill = load_drill(tmp_path)
  429. _path, words = made_up_words(tmp_path)
  430. phrase = drill.to_phrase(bytes(16), words)
  431. swapped = phrase.split()
  432. swapped[0] = words[1]
  433. swapped_text = " ".join(swapped)
  434. # Entropy of all zeros has a fixed checksum; changing a word's top bits must break it or change the entropy.
  435. assert drill.from_phrase(swapped_text, words) != bytes(16), "a changed word never restores the original"
  436. short = tmp_path / "short.txt"
  437. short.write_text("one two three\n", encoding="utf-8")
  438. try:
  439. drill.load(str(short))
  440. except SystemExit:
  441. pass
  442. else:
  443. raise AssertionError("a short word list must be refused")
  444. def test_the_page_names_the_word_list_hash_and_the_scratch_conformance_run():
  445. body = text()
  446. assert next(iter(PUBLIC_HEX)) in body and "bip-0039/english.txt" in body
  447. assert "all 24 English" in body and "282 of 300" in body
  448. # ---- diagrams ---------------------------------------------------------------------------------------------------------
  449. def test_every_diagram_has_alt_text_a_source_and_a_picture_that_exists():
  450. body = text()
  451. found = list(WRAPPED.finditer(body))
  452. assert len(found) == 4, "expected four diagrams"
  453. assert len(re.findall(r"```mermaid", body)) == len(found), "a Mermaid block has no picture above it"
  454. manifest = json.loads((ROOT / "docs" / "diagrams.json").read_text())
  455. for m in found:
  456. alt = m["alt"].strip()
  457. assert 20 <= len(alt) <= 150, alt
  458. assert alt.lower() not in {"diagram", "image", "picture"}, alt
  459. png = (PAGE.parent / m["path"]).resolve()
  460. assert png.is_file(), m["path"]
  461. assert png.relative_to(ROOT).as_posix() in manifest, m["path"]
  462. assert m["src"].lstrip().startswith(("flowchart", "sequenceDiagram")), m["path"]
  463. def test_the_diagram_guard_bites():
  464. bare = "![alt text here](images/x.png)\n\nno details block, so no source\n"
  465. assert not WRAPPED.search(bare)
  466. 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>"
  467. assert WRAPPED.search(good)
  468. assert not WRAPPED.search(good.replace("<details>\n", ""))
  469. def test_the_diagrams_cover_the_topics_the_issue_asks_for():
  470. alts = " ".join(m["alt"].lower() for m in WRAPPED.finditer(text()))
  471. for topic in ("ledger", "hardware wallet", "shamir", "multisig"):
  472. assert topic in alts, topic
  473. # ---- the register -----------------------------------------------------------------------------------------------------
  474. def test_every_claims_register_row_has_a_status():
  475. rows = register_rows(text())
  476. assert len(rows) >= 30, "the guard collected too few rows"
  477. assert not rows_missing_status(text())
  478. def test_every_sourced_row_has_a_url_and_the_read_date():
  479. assert not sourced_rows_without_url_and_date(text())
  480. reg = text().split("## Claims register")[1]
  481. for host in (
  482. "bip-0039.mediawiki",
  483. "bip-0032.mediawiki",
  484. "bip-0044.mediawiki",
  485. "bip-0011.mediawiki",
  486. "bip-0174.mediawiki",
  487. "slip-0039.md",
  488. "slip-0044.md",
  489. "developer.bitcoin.org/devguide/wallets.html",
  490. "developer.bitcoin.org/devguide/transactions.html",
  491. "managing-wallets.md",
  492. "ethereum.org/developers/docs/accounts",
  493. "eips.ethereum.org/EIPS/eip-20",
  494. "moneropedia/mnemonicseed.html",
  495. "moneropedia/spendkey.html",
  496. "moneropedia/viewkey.html",
  497. "csrc.nist.gov/glossary/term/split_knowledge",
  498. "csrc.nist.gov/glossary/term/separation_of_duty",
  499. "csrc.nist.gov/glossary/term/hardware_security_module_hsm",
  500. "trezor-firmware/main/LICENSE.md",
  501. "docs/common/reproducible-build.md",
  502. "docs/core/emulator/index.md",
  503. "docs/legacy/index.md",
  504. "docs/core/misc/optiga.md",
  505. "trezor.io/learn/security-privacy/how-trezor-keeps-you-safe/security-safety-in-trezor",
  506. "trezor-safe-device-authentication-check",
  507. "trezor.io/learn/a/secure-element-in-trezor-safe-3",
  508. "trezor.io/guides/trezor-devices/trezor-safe-3/authenticate-trezor-safe-3",
  509. "trezor-s-trusted-display-verify-every-address-on-your-device",
  510. "understanding-trezor-wallet-backups-12-20-or-24-words",
  511. "personal-security-standards/scams-and-phishing",
  512. "trezor.io/resellers",
  513. "trezor.io/security",
  514. "trezor.io/affiliate",
  515. "pitrezor.com/2018/02/pitrezor-homemade-trezor-bitcoin-wallet.html",
  516. "blog.wasabiwallet.io/diy-hardware-wallets-part-ii/",
  517. "old.walletscrutiny.com/hardware/pitrezor",
  518. ):
  519. assert host in reg, host
  520. assert reg.count(DATE) >= 30
  521. def test_the_register_guards_bite():
  522. bad = "## Claims register\n\n| Claim | Source | Status |\n|---|---|---|\n| X | y | maybe |\n"
  523. assert rows_missing_status(bad) == ["X"]
  524. undated = "## Claims register\n\n| Claim | Source | Status |\n|---|---|---|\n| X | [p](https://example.com/p) | Read 2026-10-31 |\n"
  525. assert sourced_rows_without_url_and_date(undated) == ["X"]
  526. nourl = "## Claims register\n\n| Claim | Source | Status |\n|---|---|---|\n| X | a page | Read 2026-11-01 |\n"
  527. assert sourced_rows_without_url_and_date(nourl) == ["X"]
  528. def test_the_unverified_items_are_marked_in_the_register():
  529. rows = {r[0]: r for r in register_rows(text())}
  530. port = next(r for k, r in rows.items() if k.startswith("A community project (PiTrezor)"))
  531. assert "pitrezor.com" in port[1] and "Read 2026-11-01" in port[2] and "the fork's code not read" in port[2]
  532. wasabi = next(r for k, r in rows.items() if k.startswith("PiTrezor is a port that is not vetted"))
  533. assert "blog.wasabiwallet.io" in wasabi[1] and "archive copy" in wasabi[2]
  534. scrutiny = next(r for k, r in rows.items() if k.startswith("PiTrezor's verdict"))
  535. assert "walletscrutiny.com/hardware/pitrezor" in scrutiny[1] and "Read 2026-11-01" in scrutiny[2]
  536. his = next(r for k, r in rows.items() if k.startswith("The maintainer built a PiTrezor"))
  537. assert "**est.**" in his[2] and "not independently checked" in his[2], "his account is marked as his"
  538. reading = next(r for k, r in rows.items() if k.startswith("A Pi Zero has no secure element"))
  539. assert "**est.**" in reading[2] and "no source I read states it" in reading[2]
  540. assert not any(k.startswith("A Raspberry Pi Zero can reproduce") for k in rows), "the old unsourced row is replaced"
  541. link = next(r for k, r in rows.items() if k.startswith('"No cost to the reader"'))
  542. assert "**est.**" in link[2]
  543. # ---- scope and tone ---------------------------------------------------------------------------------------------------
  544. def test_the_exercise_is_a_checklist_on_a_wallet_with_no_funds_and_says_what_was_not_run():
  545. part = section(text(), EXERCISE)
  546. boxes = re.findall(r"^- \[ \] ", part, re.MULTILINE)
  547. assert len(boxes) >= 10, "the guard collected too few checklist items"
  548. for needed in ("nothing", "create", "restor", "compare", "wipe", "wrong word", "wrong passphrase", "photo"):
  549. assert needed in part.lower(), needed
  550. assert "Not run" in part
  551. assert "testnet" in part.lower() or "test network" in part.lower()
  552. def test_the_history_is_the_authors_account_and_the_recommendation_is_the_maintainers():
  553. body = text()
  554. part = section(body, "## Before hardware wallets: the Core wallet on a netbook")
  555. assert "netbook" in part and "around 2016" in part and "not sourced" in part
  556. assert "Why that setup worked" in part and "Where it fell short" in part
  557. assert "encrypted at rest" in part
  558. def test_the_threat_table_has_every_threat_the_issue_names():
  559. part = section(text(), THREATS).lower()
  560. for threat in (
  561. "malware",
  562. "clipboard",
  563. "phishing",
  564. "supply chain",
  565. "theft of the device",
  566. "coercion",
  567. "loss",
  568. "bit rot",
  569. "cloud",
  570. "human leak",
  571. ):
  572. assert threat in part, threat
  573. rows = tables(text(), THREATS)[0]
  574. assert len(rows) == 11 and all(len(r) == 4 for r in rows)
  575. def test_each_coin_is_covered_and_monero_is_not_bip39():
  576. body = text()
  577. for heading in ("### Bitcoin", "### Ethereum", "### Monero"):
  578. assert heading in body, heading
  579. monero = body.split("### Monero")[1].split("\n## ")[0]
  580. assert "25 words" in monero and "not BIP39" in monero and "spend key" in monero and "view key" in monero
  581. assert "deprecated" in monero
  582. def test_the_page_does_not_repeat_the_stance_and_has_no_price_talk_shilling_or_evasion_content():
  583. body = text().lower()
  584. for banned in (
  585. "to the moon", "shitcoin", "memecoin", "hodl", "lambo", "buy the dip", "bullish", "bearish",
  586. "market cap", "all-time high", "pump", "airdrop", "evade detection", "avoid law enforcement",
  587. "launder money", "hide your funds", "bypass kyc", "how to avoid being traced", "untraceable",
  588. "cryptobro", "mcafee", "to avoid tracing", "stay anonymous", "cover your tracks", "comfortable with cryptocurrency",
  589. ):
  590. assert banned not in body, banned
  591. assert body.count("price") <= 1 and body.count("trading") <= 1
  592. assert "no price talk, no coin shilling and no trading advice" in body
  593. assert "no how-to for anything illegal" in body
  594. def test_old_pages_are_dated_where_they_are_used():
  595. body = text()
  596. assert "2009-2020" in body, "the developer guide's own copyright range is stated"
  597. assert "2013-09-10" in body and "2017-12-18" in body, "the BIP39 and SLIP39 dates are stated"
  598. assert "June 2017" in body, "the Monero view-key statement is dated by its own text"
  599. assert "deprecated" in body, "the Monero page's own deprecation notice is stated"
  600. assert "show no edit date" in body, "Trezor's pages carry no edit date and the page says so"