test_how_bitcoin_works_lesson.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. # SPDX-License-Identifier: Apache-2.0
  2. """The how-Bitcoin-works lesson: registered, honest about what was run, diagrams intact, and safe to read.
  3. docs/wiki/How-Bitcoin-Works-Keys-UTXOs-Mining-and-Why-It-Is-Pseudonymous-and-Traceable.md is page 2 of the five-page
  4. cryptocurrency set (issue 397). A banner that claims more than was run, a dead link, a missing registration, a diagram with
  5. no picture or alt text, a wallet address or a stray long hex value, a snapshot whose hash no longer matches its own header
  6. fields, a worked answer that the heuristic does not give, price talk, advice for evading tracing, or a register row with no
  7. URL and no date would each teach or reveal the wrong thing.
  8. """
  9. import datetime
  10. import hashlib
  11. import json
  12. import re
  13. import struct
  14. from decimal import Decimal
  15. from pathlib import Path
  16. ROOT = Path(__file__).resolve().parent.parent
  17. WIKI = ROOT / "docs" / "wiki"
  18. NAME = "How-Bitcoin-Works-Keys-UTXOs-Mining-and-Why-It-Is-Pseudonymous-and-Traceable"
  19. PAGE = WIKI / f"{NAME}.md"
  20. PAGE_ONE = "Blockchain-Fundamentals-Hashes-Blocks-Nodes-Consensus-and-Forks"
  21. HANDS_ON = "Hands-On-Whonix-and-Qubes-OS-Gateway-Split-Compartments-Disposables-and-Policy-Prompts"
  22. LINK =re.compile(r"\]\(([A-Za-z0-9_-]+)\.md(?:#([^)]*))?\)")
  23. # A wallet address in any of the common shapes: legacy Bitcoin, Bech32 Bitcoin, Ethereum and Monero.
  24. ADDRESS = re.compile(
  25. r"\b[13][a-km-zA-HJ-NP-Z1-9]{25,34}\b"
  26. r"|\bbc1[ac-hj-np-z02-9]{11,71}\b"
  27. r"|\b0x[0-9a-fA-F]{40}\b"
  28. r"|\b4[0-9AB][1-9A-HJ-NP-Za-km-z]{93}\b"
  29. )
  30. HEX64 = re.compile(r"\b[0-9a-f]{64}\b")
  31. # A dotted quad is an address unless it follows the word "release" (a four-part version).
  32. IPV4 = re.compile(r"(?<!release )\b(?:\d{1,3}\.){3}\d{1,3}\b")
  33. WRAPPED = re.compile(
  34. 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>",
  35. re.DOTALL,
  36. )
  37. STATUS_WORDS = ("Read", "Run on", "General knowledge", "**est.**", "Constructed")
  38. URL = re.compile(r"\]\(https?://[^)\s]+\)")
  39. DATE = "2026-11-01"
  40. TIP = "974138"
  41. # The only 64-digit hex values the page may carry: public block, Merkle and transaction identifiers read from a public
  42. # explorer and named in the snapshot. Anything else is a stray value.
  43. PUBLIC_HEX = {
  44. "00000000152340ca42227603908689183edc47355204e7aca59383b0aaac1fd8", # block 57043 hash
  45. "0000000013e7e85518dac94d012d73253d3fdac5c30c4143b177f3086f129580", # block 57042 hash (its previous block)
  46. "5c1d2211f598cd6498f42b269fe3ce4a6fdb40eaa638f86a0579c4e63a721b5a", # block 57043 Merkle root
  47. "bd9075d78e65a98fb054cb33cf0ecf14e3e7f8b3150231df8680919a79ac8fe5", # block 57043 reward transaction
  48. "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d", # the famous transaction
  49. }
  50. SNAP = "## A real snapshot: one famous public transaction"
  51. EXERCISE = "## Free exercise: cluster a synthetic graph"
  52. def text() -> str:
  53. return PAGE.read_text(encoding="utf-8")
  54. def slug(heading: str) -> str:
  55. return re.sub(r"[^a-z0-9-]", "", re.sub(r"[^a-z0-9 -]", "", heading.lower()).strip().replace(" ", "-"))
  56. def headings(body: str) -> set[str]:
  57. return {slug(h) for h in re.findall(r"^#+ (.+)$", body, re.MULTILINE)}
  58. def section(body: str, heading: str) -> str:
  59. return body.split(heading)[1].split("\n## ")[0]
  60. def register_rows(body: str) -> list[list[str]]:
  61. reg = body.split("## Claims register")[1]
  62. rows = [line for line in reg.splitlines() if line.startswith("|") and not line.startswith("|---")]
  63. return [[c.strip() for c in r.strip("|").split("|")] for r in rows[1:]]
  64. def rows_missing_status(body: str) -> list[str]:
  65. return [r[0] for r in register_rows(body) if not any(w in r[-1] for w in STATUS_WORDS)]
  66. def sourced_rows_without_url_and_date(body: str) -> list[str]:
  67. """Rows that cite a page must carry a URL and the read date; process and framing rows are exempt by name."""
  68. exempt = ("The maintainer's framing", "The author's own", "General knowledge", "Constructed by the author")
  69. bad = []
  70. for row in register_rows(body):
  71. if row[1].startswith(exempt):
  72. continue
  73. if not URL.search(row[1]) or DATE not in row[2]:
  74. bad.append(row[0])
  75. return bad
  76. def snapshot(body: str) -> dict[str, str]:
  77. """The snapshot table as {row label: value}, with backticks removed."""
  78. out = {}
  79. for line in section(body, SNAP).splitlines():
  80. if line.startswith("|") and not line.startswith("|---"):
  81. cells = [c.strip().strip("`") for c in line.strip("|").split("|")]
  82. out[cells[0]] = cells[1]
  83. return out
  84. def number(cell: str) -> int:
  85. return int(re.match(r"[\d,]+", cell).group(0).replace(",", ""))
  86. def dsha(raw: bytes) -> bytes:
  87. return hashlib.sha256(hashlib.sha256(raw).digest()).digest()
  88. def header_hash(version: int, prev: str, merkle: str, when: int, bits: int, nonce: int) -> str:
  89. """Double SHA-256 of the 80-byte header, shown the way explorers show it (byte order reversed)."""
  90. raw = (
  91. struct.pack("<I", version)
  92. + bytes.fromhex(prev)[::-1]
  93. + bytes.fromhex(merkle)[::-1]
  94. + struct.pack("<III", when, bits, nonce)
  95. )
  96. assert len(raw) == 80
  97. return dsha(raw)[::-1].hex()
  98. def merkle_of_two(a: str, b: str) -> str:
  99. return dsha(bytes.fromhex(a)[::-1] + bytes.fromhex(b)[::-1])[::-1].hex()
  100. # ---- the synthetic graph in the exercise -------------------------------------------------------------------------
  101. def exercise_rows(body: str) -> list[tuple[str, list[tuple[str, Decimal]], list[tuple[str, Decimal]], Decimal]]:
  102. rows = []
  103. for line in section(body, EXERCISE).splitlines():
  104. m = re.match(r"\| (T\d) \| ([^|]+) \| ([^|]+) \| ([\d.]+) \|", line)
  105. if m:
  106. pair = re.compile(r"([A-Z]\d) ([\d.]+)")
  107. ins = [(a, Decimal(v)) for a, v in pair.findall(m[2])]
  108. outs = [(a, Decimal(v)) for a, v in pair.findall(m[3])]
  109. rows.append((m[1], ins, outs, Decimal(m[4])))
  110. return rows
  111. def seen_before(body: str) -> set[str]:
  112. m = re.search(r"\*\*Seen before T1:\*\* ([A-Z0-9, ]+)\.", section(body, EXERCISE))
  113. return {a.strip() for a in m[1].split(",")}
  114. def common_input_clusters(rows) -> set[frozenset[str]]:
  115. """Union-find over the inputs of each transaction: addresses spent together are one cluster."""
  116. parent: dict[str, str] = {}
  117. def find(x: str) -> str:
  118. parent.setdefault(x, x)
  119. while parent[x] != x:
  120. parent[x] = parent[parent[x]]
  121. x = parent[x]
  122. return x
  123. for _tx, ins, _outs, _fee in rows:
  124. first = find(ins[0][0])
  125. for addr, _v in ins[1:]:
  126. parent[find(addr)] = first
  127. groups: dict[str, set[str]] = {}
  128. for a in list(parent):
  129. groups.setdefault(find(a), set()).add(a)
  130. return {frozenset(g) for g in groups.values()}
  131. def change_labels(rows, seen: set[str]) -> dict[str, str]:
  132. """One-time change rule in the shape the research paper describes: exactly one output is new, none repeats an input."""
  133. seen = set(seen)
  134. out = {}
  135. for tx, ins, outs, _fee in rows:
  136. in_addrs = {a for a, _ in ins}
  137. seen |= in_addrs
  138. new = [a for a, _ in outs if a not in seen]
  139. if len(new) == 1 and not (in_addrs & {a for a, _ in outs}):
  140. out[tx] = new[0]
  141. seen |= {a for a, _ in outs}
  142. return out
  143. def merged(clusters: set[frozenset[str]], change: dict[str, str], rows) -> set[frozenset[str]]:
  144. """Add each labeled change address to the cluster of its transaction's inputs."""
  145. result = [set(c) for c in clusters]
  146. for tx, ins, _outs, _fee in rows:
  147. if tx in change:
  148. for c in result:
  149. if ins[0][0] in c:
  150. c.add(change[tx])
  151. return {frozenset(c) for c in result}
  152. def answer_sets(body: str, label: str) -> set[frozenset[str]]:
  153. line = next(r for r in section(body, EXERCISE).splitlines() if r.startswith(f"| {label} |"))
  154. return {frozenset(s.strip() for s in grp.split(",")) for grp in re.findall(r"\{([^}]*)\}", line)}
  155. # ---- the page ----------------------------------------------------------------------------------------------------
  156. def test_the_banner_says_it_was_written_from_reading_and_names_what_was_run():
  157. body = text()
  158. assert body.startswith("# How Bitcoin works")
  159. assert "Status: unverified draft, written from reading" in body
  160. assert "Nothing on this page was run on a blockchain network or a node" in body
  161. assert "**Not run:**" in body and DATE in body
  162. assert "## Not verified, plainly" in body
  163. assert "defensive and educational" in body.lower()
  164. def test_every_linked_wiki_page_exists_and_every_anchor_is_a_real_heading():
  165. found = LINK.findall(text())
  166. assert len({t for t, _ in found}) >= 6, "the guard collected too few links"
  167. missing = sorted({t for t, _ in found if not (WIKI / f"{t}.md").exists()})
  168. assert not missing, missing
  169. bad = []
  170. for target, anchor in found:
  171. if anchor and anchor not in headings((WIKI / f"{target}.md").read_text(encoding="utf-8")):
  172. bad.append(f"{target}#{anchor}")
  173. assert not bad, bad
  174. def test_the_page_links_the_existing_lessons_and_names_the_siblings_correctly():
  175. body = text()
  176. links = {t for t, _ in LINK.findall(body)}
  177. for needed in (
  178. "Cryptography-Fundamentals-Symmetric-Asymmetric-Hashing-Certificates-and-Keys",
  179. "Hashing-Encryption-and-Keys",
  180. "Privacy-vs-Security-Blinds-and-Locks-Physical-Security-and-Monero",
  181. "Tor-I2P-and-the-Darknet-Without-the-Myths",
  182. "The-Darknet-Landscape-Markets-OPSEC-Clearnet-and-Layering-Tor-I2P-and-VPN",
  183. ):
  184. assert needed in links, needed
  185. assert "#digital-signatures" in body
  186. assert "#what-pinodexmr-documents" in body, "the PiNodeXMR example on the overview page is linked"
  187. # Page one is linked once it is in the wiki, and named in plain text until then.
  188. if (WIKI / f"{PAGE_ONE}.md").exists():
  189. assert PAGE_ONE in links, "page one exists, so it must be linked"
  190. else:
  191. assert PAGE_ONE not in body, "page one is not in the wiki yet; name it in plain text"
  192. assert "Blockchain fundamentals" in body and "issue 396" in body
  193. for issue in ("396", "398", "399", "400", "372"):
  194. assert issue in body, f"issue {issue} is named"
  195. assert HANDS_ON in links, "the hands-on Whonix and Qubes exercises (issue 372) exist and must be linked"
  196. assert "which are not written yet and are named in plain text, not linked" not in body
  197. # Pages three, four and five are in the wiki, so they are linked, and the stale statement is gone.
  198. for prefix in ("How-Monero-Works-", "Wallets-and-Key-Custody-", "Running-Monero-Properly-"):
  199. found = {t for t in links if t.startswith(prefix)}
  200. assert found, f"the page {prefix} exists and must be linked"
  201. assert all((WIKI / f"{t}.md").is_file() for t in found), found
  202. assert "Pages not in the wiki yet" not in body
  203. def test_the_lesson_is_registered_in_contents_reading_order_and_nav():
  204. nav = (WIKI / "_nav.yaml").read_text(encoding="utf-8")
  205. assert f"page: {NAME}," in nav
  206. for special in ("Contents.md", "Reading-Order.md", "Home.md", "_Sidebar.md"):
  207. assert f"{NAME}.md" in (WIKI / special).read_text(encoding="utf-8"), special
  208. line = next(row for row in nav.splitlines() if f"page: {NAME}," in row)
  209. assert 'status: "draft"' in line, "the banner says unverified draft"
  210. def test_glossary_rows_point_at_real_headings():
  211. heads = headings(text())
  212. anchors = set()
  213. rows = 0
  214. for line in (WIKI / "Glossary.md").read_text(encoding="utf-8").splitlines():
  215. if f"{NAME}.md" in line:
  216. rows += 1
  217. anchors.update(re.findall(rf"{NAME}\.md#([a-z0-9-]+)", line))
  218. assert rows >= 12, "expected glossary rows for the new terms"
  219. assert anchors and anchors <= heads, sorted(anchors - heads)
  220. def test_no_addresses_stray_hex_ip_addresses_em_dashes_or_money_amounts():
  221. body = text()
  222. assert not ADDRESS.findall(body), ADDRESS.findall(body)
  223. assert not IPV4.findall(body), IPV4.findall(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. found = set(HEX64.findall(body))
  227. assert found, "the guard collected no hash at all"
  228. assert found <= PUBLIC_HEX, sorted(found - PUBLIC_HEX)
  229. assert "bitcoin" in body.lower(), "the guard collected nothing"
  230. def test_the_address_and_hex_guards_bite():
  231. assert ADDRESS.search("send to 1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa today")
  232. assert ADDRESS.search("send to bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq today")
  233. assert ADDRESS.search("send to 0x" + "ab" * 20 + " today")
  234. assert ADDRESS.search("send to 4" + "A" + "b" * 93 + " today")
  235. assert not ADDRESS.search("the placeholder addresses A1, A2 and C1 are labels, not addresses")
  236. assert HEX64.search("key " + "ab" * 32) and "ab" * 32 not in PUBLIC_HEX
  237. assert IPV4.search("host 192.0.2.7") and not IPV4.search("as of release 0.9.7.1")
  238. def test_the_snapshot_records_the_date_the_height_and_the_tip_and_prints_no_address():
  239. part = section(text(), SNAP)
  240. assert DATE in part and TIP in part and "57043" in part
  241. assert "blockstream.info" in part, "the explorer is named"
  242. assert "I print no address" in part
  243. def test_the_snapshot_hash_merkle_root_and_reward_match_their_own_fields():
  244. rows = snapshot(text())
  245. want = rows["Block hash"]
  246. got = header_hash(
  247. int(rows["Version"]),
  248. rows["Previous block hash"],
  249. rows["Merkle root"],
  250. int(rows["Time (Unix seconds)"]),
  251. int(rows["Difficulty bits (hex)"], 16),
  252. int(rows["Nonce"]),
  253. )
  254. assert got == want, (got, want)
  255. assert rows["Transactions in block"] == "2"
  256. assert merkle_of_two(rows["Reward transaction id"], rows["Transaction id"]) == rows["Merkle root"]
  257. when = int(rows["Time (Unix seconds)"])
  258. utc = datetime.datetime.fromtimestamp(when, datetime.UTC).strftime("%Y-%m-%d %H:%M:%S")
  259. assert rows["Time (UTC)"].startswith(utc), (rows["Time (UTC)"], utc)
  260. subsidy, fee = number(rows["Block subsidy at that height (satoshis)"]), number(rows["Fee (satoshis)"])
  261. assert subsidy == 5_000_000_000 == 50 * 100_000_000
  262. assert number(rows["Reward transaction output (satoshis)"]) == subsidy + fee, "reward = subsidy + the one fee"
  263. assert number(rows["Input value, all inputs (satoshis)"]) == number(rows["Output value (satoshis)"]) + fee
  264. assert number(rows["Inputs"]) == 131 and rows["Outputs"].startswith("1")
  265. assert rows["Distinct addresses among the inputs"].startswith("1"), "all inputs were paid to one address"
  266. height = number(rows["Block height"])
  267. assert number(rows["Confirmations when read"]) == int(TIP) - height + 1
  268. def test_the_snapshot_guard_bites():
  269. good = (
  270. "00000000152340ca42227603908689183edc47355204e7aca59383b0aaac1fd8",
  271. "0000000013e7e85518dac94d012d73253d3fdac5c30c4143b177f3086f129580",
  272. "5c1d2211f598cd6498f42b269fe3ce4a6fdb40eaa638f86a0579c4e63a721b5a",
  273. )
  274. assert header_hash(1, good[1], good[2], 1274552191, 0x1C159C24, 188133155) == good[0]
  275. assert header_hash(1, good[1], good[2], 1274552191, 0x1C159C24, 188133156) != good[0], "one nonce digit changes it"
  276. assert merkle_of_two(
  277. "bd9075d78e65a98fb054cb33cf0ecf14e3e7f8b3150231df8680919a79ac8fe5",
  278. "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
  279. ) == good[2]
  280. assert merkle_of_two(
  281. "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
  282. "bd9075d78e65a98fb054cb33cf0ecf14e3e7f8b3150231df8680919a79ac8fe5",
  283. ) != good[2], "order matters"
  284. def test_the_halving_and_difficulty_arithmetic_on_the_page_is_right():
  285. body = text()
  286. assert "210,000" in body and "2,016" in body
  287. tip = int(TIP)
  288. halvings = tip // 210_000
  289. assert halvings == 4
  290. assert Decimal(50) / (2**halvings) == Decimal("3.125")
  291. assert "3.125" in body, "the subsidy at the recorded tip, from the rule, is stated"
  292. assert 2016 * 600 == 1_209_600
  293. def test_the_synthetic_exercise_has_the_shape_the_answer_key_depends_on():
  294. body = text()
  295. rows = exercise_rows(body)
  296. assert len(rows) == 4, "the guard collected too few transactions"
  297. for tx, ins, outs, fee in rows:
  298. assert sum(v for _, v in ins) == sum(v for _, v in outs) + fee, f"{tx} does not balance"
  299. names = {a for _, ins, outs, _ in rows for a, _ in ins + outs}
  300. assert all(re.fullmatch(r"[A-Z]\d", n) for n in names), "placeholder labels only"
  301. assert not ADDRESS.findall(section(body, EXERCISE))
  302. assert "synthetic" in section(body, EXERCISE).lower() and "no chain data" in section(body, EXERCISE).lower()
  303. def test_the_answer_key_is_what_the_two_rules_actually_give():
  304. body = text()
  305. rows = exercise_rows(body)
  306. seen = seen_before(body)
  307. clusters = common_input_clusters(rows)
  308. multi = {c for c in clusters if len(c) > 1}
  309. assert answer_sets(body, "Common-input rule") == multi
  310. change = change_labels(rows, seen)
  311. assert change == {"T1": "C1", "T2": "C2"}, change
  312. assert answer_sets(body, "After the change rule") == {c for c in merged(clusters, change, rows) if len(c) > 1}
  313. section_text = section(body, EXERCISE)
  314. for must in ("not proved", "equal", "tag", "ambiguous"):
  315. assert must in section_text.lower(), must
  316. def test_the_exercise_guard_bites():
  317. rows = [
  318. ("T1", [("A1", Decimal(1)), ("A2", Decimal(1))], [("B1", Decimal(2))], Decimal(0)),
  319. ("T2", [("C1", Decimal(1))], [("D1", Decimal(1))], Decimal(0)),
  320. ]
  321. assert common_input_clusters(rows) == {frozenset({"A1", "A2"}), frozenset({"C1"})}, "unrelated inputs stay apart"
  322. chained = rows + [("T3", [("A2", Decimal(1)), ("E1", Decimal(1))], [("F1", Decimal(2))], Decimal(0))]
  323. assert frozenset({"A1", "A2", "E1"}) in common_input_clusters(chained), "the effect is transitive"
  324. wrong = {frozenset({"A1", "A2"})}
  325. assert wrong != {c for c in common_input_clusters(chained) if len(c) > 1}, "a wrong key would be caught"
  326. two_new = [("T1", [("A1", Decimal(1))], [("B1", Decimal("0.5")), ("B2", Decimal("0.5"))], Decimal(0))]
  327. assert change_labels(two_new, set()) == {}, "two new outputs: ambiguous, so nothing is labeled"
  328. self_change = [("T1", [("A1", Decimal(1))], [("A1", Decimal("0.5")), ("B2", Decimal("0.5"))], Decimal(0))]
  329. assert change_labels(self_change, set()) == {}, "an output that repeats an input is skipped"
  330. def test_every_diagram_has_alt_text_a_source_and_a_picture_that_exists():
  331. body = text()
  332. found = list(WRAPPED.finditer(body))
  333. assert len(found) == 5, "expected five diagrams"
  334. assert len(re.findall(r"```mermaid", body)) == len(found), "a Mermaid block has no picture above it"
  335. manifest = json.loads((ROOT / "docs" / "diagrams.json").read_text())
  336. for m in found:
  337. alt = m["alt"].strip()
  338. assert 20 <= len(alt) <= 150, alt
  339. assert alt.lower() not in {"diagram", "image", "picture"}, alt
  340. png = (PAGE.parent / m["path"]).resolve()
  341. assert png.is_file(), m["path"]
  342. assert png.relative_to(ROOT).as_posix() in manifest, m["path"]
  343. assert m["src"].lstrip().startswith(("flowchart", "sequenceDiagram")), m["path"]
  344. def test_the_diagram_guard_bites():
  345. bare = "![alt text here](images/x.png)\n\nno details block, so no source\n"
  346. assert not WRAPPED.search(bare)
  347. 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>"
  348. assert WRAPPED.search(good)
  349. assert not WRAPPED.search(good.replace("<details>\n", ""))
  350. def test_the_diagrams_cover_the_topics_the_issue_asks_for():
  351. alts = " ".join(m["alt"].lower() for m in WRAPPED.finditer(text()))
  352. for topic in ("utxo", "keys", "cluster", "traced", "peeling"):
  353. assert topic in alts, topic
  354. def test_every_claims_register_row_has_a_status():
  355. rows = register_rows(text())
  356. assert len(rows) >= 20, "the guard collected too few rows"
  357. assert not rows_missing_status(text())
  358. def test_every_sourced_row_has_a_url_and_the_read_date():
  359. assert not sourced_rows_without_url_and_date(text())
  360. reg = text().split("## Claims register")[1]
  361. for host in (
  362. "bitcoin.org/bitcoin.pdf",
  363. "developer.bitcoin.org/devguide/transactions.html",
  364. "developer.bitcoin.org/devguide/block_chain.html",
  365. "developer.bitcoin.org/devguide/mining.html",
  366. "developer.bitcoin.org/devguide/p2p_network.html",
  367. "developer.bitcoin.org/devguide/wallets.html",
  368. "en.bitcoin.it/wiki/Controlled_supply",
  369. "chainparams.cpp",
  370. "imc13.pdf",
  371. "arxiv.org/abs/1107.4524",
  372. "arxiv.org/abs/1804.04080",
  373. "justice.gov/opa/pr/department-justice-seizes-23-million",
  374. "bitcointalk.org/index.php?topic=137.0",
  375. "blockstream.info/api",
  376. ):
  377. assert host in reg, host
  378. assert reg.count(DATE) >= 15
  379. def test_the_register_guards_bite():
  380. bad = "## Claims register\n\n| Claim | Source | Status |\n|---|---|---|\n| X | y | maybe |\n"
  381. assert rows_missing_status(bad) == ["X"]
  382. undated = "## Claims register\n\n| Claim | Source | Status |\n|---|---|---|\n| X | [p](https://example.com/p) | Read 2026-10-31 |\n"
  383. assert sourced_rows_without_url_and_date(undated) == ["X"]
  384. nourl = "## Claims register\n\n| Claim | Source | Status |\n|---|---|---|\n| X | a page | Read 2026-11-01 |\n"
  385. assert sourced_rows_without_url_and_date(nourl) == ["X"]
  386. def test_every_documented_case_has_a_date_a_source_and_the_limit_it_shows():
  387. part = section(text(), "## Documented cases: what tracing showed")
  388. rows = [
  389. [c.strip() for c in line.strip("|").split("|")]
  390. for line in part.splitlines()
  391. if line.startswith("|") and not line.startswith("|---")
  392. ][1:]
  393. assert len(rows) >= 4, "the guard collected too few cases"
  394. for row in rows:
  395. assert re.search(r"20\d\d", row[1]), f"no date: {row[0]}"
  396. assert URL.search(row[2]) or "register" in row[2].lower(), f"no source: {row[0]}"
  397. assert len(row[3]) > 40, f"no statement of what it shows: {row[0]}"
  398. for needed in ("2021-06-07", "April 11 2012", "March 15 2013", "number 21-528"):
  399. assert needed in part or needed.replace(" ", " ") in text(), needed
  400. def test_the_traced_cases_use_no_personal_addresses_and_say_what_was_not_read():
  401. body = text()
  402. not_verified = section(body, "## Not verified, plainly")
  403. for unread in ("affidavit", "Nick", "tracking ransomware end-to-end"):
  404. assert unread.lower() in not_verified.lower(), unread
  405. assert "63.7" in body and "approximately 75" in body, "the case figures are in bitcoin, as the release gives them"
  406. def test_the_page_does_not_repeat_the_stance_and_has_no_price_talk_shilling_or_evasion_content():
  407. body = text().lower()
  408. for banned in (
  409. "to the moon", "shitcoin", "memecoin", "hodl", "lambo", "buy the dip", "bullish", "bearish",
  410. "market cap", "all-time high", "pump", "airdrop", "evade detection", "avoid law enforcement",
  411. "launder money", "hide your funds", "bypass kyc", "how to avoid being traced", "untraceable",
  412. "cryptobro", "mcafee", "to avoid tracing", "stay anonymous", "cover your tracks",
  413. ):
  414. assert banned not in body, banned
  415. assert body.count("price") <= 1 and body.count("trading") <= 1, "named once as out of scope, nothing more"
  416. assert "no how-to for anything illegal" in body
  417. assert "no advice for avoiding tracing" in body or "no advice for evading tracing" in body
  418. def test_the_page_says_what_an_analyst_cannot_conclude():
  419. body = text()
  420. part = section(body, "## What an analyst can and cannot conclude")
  421. for needed in ("can say", "cannot say"):
  422. assert needed in part.lower(), needed
  423. assert "## Pseudonymous is not anonymous" in body
  424. assert "## What a ransom payment leaves behind" in body
  425. exercise = section(body, EXERCISE)
  426. assert "Not run" in exercise
  427. def test_old_pages_are_dated_where_they_are_used():
  428. body = text()
  429. assert "2009-2020" in body, "the developer guide's own copyright range is stated"
  430. assert "2008" in body, "the whitepaper's year is stated"
  431. assert "last edited on 15 April 2026" in body, "the wiki page's own edit date is stated"
  432. assert "Wayback" in body or "web.archive.org" in body, "the way the press release was read is stated"