test_blockchain_fundamentals_lesson.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. # SPDX-License-Identifier: Apache-2.0
  2. """The blockchain fundamentals lesson: registered, honest about what was run, diagrams intact, and safe to read.
  3. docs/wiki/Blockchain-Fundamentals-Hashes-Blocks-Nodes-Consensus-and-Forks.md is page 1 of the five-page
  4. cryptocurrency set (issue 396). 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 table whose hash no longer matches its own
  6. header fields, price talk, or a register row with no URL and no date would each teach or reveal the wrong thing.
  7. """
  8. import datetime
  9. import hashlib
  10. import json
  11. import re
  12. import struct
  13. from pathlib import Path
  14. ROOT = Path(__file__).resolve().parent.parent
  15. WIKI = ROOT / "docs" / "wiki"
  16. NAME = "Blockchain-Fundamentals-Hashes-Blocks-Nodes-Consensus-and-Forks"
  17. PAGE = WIKI / f"{NAME}.md"
  18. LINK = re.compile(r"\]\(([A-Za-z0-9_-]+)\.md(?:#([^)]*))?\)")
  19. HANDS_ON = "Hands-On-Whonix-and-Qubes-OS-Gateway-Split-Compartments-Disposables-and-Policy-Prompts"
  20. # A wallet address in any of the common shapes: legacy Bitcoin, Bech32 Bitcoin, Ethereum and Monero.
  21. ADDRESS = re.compile(
  22. r"\b[13][a-km-zA-HJ-NP-Z1-9]{25,34}\b"
  23. r"|\bbc1[ac-hj-np-z02-9]{11,71}\b"
  24. r"|\b0x[0-9a-fA-F]{40}\b"
  25. r"|\b4[0-9AB][1-9A-HJ-NP-Za-km-z]{93}\b"
  26. )
  27. HEX64 = re.compile(r"\b[0-9a-f]{64}\b")
  28. # A dotted quad is an address unless it follows the word "release" (a four-part version).
  29. IPV4 = re.compile(r"(?<!release )\b(?:\d{1,3}\.){3}\d{1,3}\b")
  30. WRAPPED = re.compile(
  31. 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>",
  32. re.DOTALL,
  33. )
  34. STATUS_WORDS = ("Read", "Run on", "General knowledge", "**est.**")
  35. URL = re.compile(r"\]\(https?://[^)\s]+\)")
  36. DATE = "2026-11-01"
  37. TIP = "974136"
  38. # The only 64-digit hex values the page may carry: public block hashes, Merkle roots and transaction ids that were read
  39. # from a public explorer and are named in the snapshot and the exercise. Anything else is a stray value.
  40. PUBLIC_HEX = {
  41. "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f", # block 0 hash
  42. "00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048", # block 1 hash
  43. "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b", # block 0 Merkle root and transaction id
  44. "0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098", # block 1 Merkle root and transaction id
  45. "00000000d1145790a8694403d4063f323d499e655c83426834d4ce2f8dd4a2ee", # block 170 hash
  46. "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16", # the block 170 transfer
  47. "0437cd7f8525ceed2324359c2d0ba26006d92d856a9c20fa0241106ee5a597c9", # the earlier output it spends
  48. }
  49. def text() -> str:
  50. return PAGE.read_text(encoding="utf-8")
  51. def slug(heading: str) -> str:
  52. return re.sub(r"[^a-z0-9-]", "", re.sub(r"[^a-z0-9 -]", "", heading.lower()).strip().replace(" ", "-"))
  53. def headings(body: str) -> set[str]:
  54. return {slug(h) for h in re.findall(r"^#+ (.+)$", body, re.MULTILINE)}
  55. def register_rows(body: str) -> list[list[str]]:
  56. reg = body.split("## Claims register")[1]
  57. rows = [line for line in reg.splitlines() if line.startswith("|") and not line.startswith("|---")]
  58. return [[c.strip() for c in r.strip("|").split("|")] for r in rows[1:]]
  59. def rows_missing_status(body: str) -> list[str]:
  60. return [r[0] for r in register_rows(body) if not any(w in r[-1] for w in STATUS_WORDS)]
  61. def sourced_rows_without_url_and_date(body: str) -> list[str]:
  62. """Rows that cite a page must carry a URL and the read date; process and framing rows are exempt by name."""
  63. exempt = ("The maintainer's framing", "The author's own check", "General knowledge")
  64. bad = []
  65. for row in register_rows(body):
  66. if row[1].startswith(exempt):
  67. continue
  68. if not URL.search(row[1]) or DATE not in row[2]:
  69. bad.append(row[0])
  70. return bad
  71. def snapshot(body: str) -> dict[str, list[str]]:
  72. """The snapshot table as {row label: [block 0 cell, block 1 cell]}, with backticks removed."""
  73. part = body.split("## A real snapshot: the first two Bitcoin blocks")[1].split("\n## ")[0]
  74. out = {}
  75. for line in part.splitlines():
  76. if line.startswith("|") and not line.startswith("|---"):
  77. cells = [c.strip().strip("`") for c in line.strip("|").split("|")]
  78. out[cells[0]] = cells[1:]
  79. return out
  80. def header_hash(version: int, prev: str, merkle: str, when: int, bits: int, nonce: int) -> str:
  81. """Double SHA-256 of the 80-byte header, shown the way explorers show it (byte order reversed)."""
  82. raw = (
  83. struct.pack("<I", version)
  84. + bytes.fromhex(prev)[::-1]
  85. + bytes.fromhex(merkle)[::-1]
  86. + struct.pack("<III", when, bits, nonce)
  87. )
  88. assert len(raw) == 80
  89. return hashlib.sha256(hashlib.sha256(raw).digest()).digest()[::-1].hex()
  90. def test_the_banner_says_it_was_written_from_reading_and_names_the_one_calculation():
  91. body = text()
  92. assert body.startswith("# Blockchain fundamentals")
  93. assert "Status: unverified draft, written from reading" in body
  94. assert "Nothing on this page was run on a blockchain network or a node" in body
  95. assert "**Not run:**" in body and DATE in body
  96. assert "## Not verified, plainly" in body
  97. assert "Defensive and educational" in body or "defensive and educational" in body
  98. def test_every_linked_wiki_page_exists_and_every_anchor_is_a_real_heading():
  99. found = LINK.findall(text())
  100. assert len({t for t, _ in found}) >= 8, "the guard collected too few links"
  101. missing = sorted({t for t, _ in found if not (WIKI / f"{t}.md").exists()})
  102. assert not missing, missing
  103. bad = []
  104. for target, anchor in found:
  105. if anchor and anchor not in headings((WIKI / f"{target}.md").read_text(encoding="utf-8")):
  106. bad.append(f"{target}#{anchor}")
  107. assert not bad, bad
  108. def test_the_page_links_the_existing_lessons_and_the_set_siblings_now_that_they_exist():
  109. body = text()
  110. links = {t for t, _ in LINK.findall(body)}
  111. for needed in (
  112. "How-Bitcoin-Works-Keys-UTXOs-Mining-and-Why-It-Is-Pseudonymous-and-Traceable",
  113. "How-Monero-Works-Compared-with-Bitcoin-and-Ethereum-DeFi-Mixers-Swaps-and-Ransomware",
  114. "Wallets-and-Key-Custody-Hot-and-Cold-Hardware-Wallets-Recovery-Shamir-and-Multisig",
  115. "Running-Monero-Properly-Hardware-Wallet-Qubes-and-Whonix-Offline-Wallet-and-PiNodeXMR",
  116. "Cryptography-Fundamentals-Symmetric-Asymmetric-Hashing-Certificates-and-Keys",
  117. "Hashing-Encryption-and-Keys",
  118. "Privacy-vs-Security-Blinds-and-Locks-Physical-Security-and-Monero",
  119. "Tor-I2P-and-the-Darknet-Without-the-Myths",
  120. "How-Tor-Works-in-Depth-Circuits-Relays-Directory-Authorities-and-Onion-Services",
  121. "How-I2P-Works-Tunnels-Garlic-Routing-and-the-Network-Database",
  122. "The-Darknet-Landscape-Markets-OPSEC-Clearnet-and-Layering-Tor-I2P-and-VPN",
  123. ):
  124. assert needed in links, needed
  125. assert "#what-pinodexmr-documents" in body, "the PiNodeXMR example on the overview page is linked"
  126. for issue in ("397", "398", "399", "400", "372"):
  127. assert issue in body, f"issue {issue} is named"
  128. assert HANDS_ON in links, "the hands-on Whonix and Qubes exercises (issue 372) exist and must be linked"
  129. assert "which are not written yet and are named in plain text, not linked" not in body
  130. assert all((WIKI / f"{t}.md").is_file() for t in links), "a linked page is missing"
  131. # The stale statement that the set pages are not written yet is gone.
  132. assert "Pages that are not written yet" not in body
  133. def test_the_lesson_is_registered_in_contents_reading_order_and_nav():
  134. nav = (WIKI / "_nav.yaml").read_text(encoding="utf-8")
  135. assert f"page: {NAME}," in nav
  136. for special in ("Contents.md", "Reading-Order.md", "Home.md", "_Sidebar.md"):
  137. assert f"{NAME}.md" in (WIKI / special).read_text(encoding="utf-8"), special
  138. line = next(row for row in nav.splitlines() if f"page: {NAME}," in row)
  139. assert 'status: "draft"' in line, "the banner says unverified draft"
  140. def test_glossary_rows_point_at_real_headings():
  141. heads = headings(text())
  142. anchors = set()
  143. rows = 0
  144. for line in (WIKI / "Glossary.md").read_text(encoding="utf-8").splitlines():
  145. if f"{NAME}.md" in line:
  146. rows += 1
  147. anchors.update(re.findall(rf"{NAME}\.md#([a-z0-9-]+)", line))
  148. assert rows >= 10, "expected glossary rows for the new terms"
  149. assert anchors and anchors <= heads, sorted(anchors - heads)
  150. def test_no_addresses_stray_hex_ip_addresses_or_em_dashes():
  151. body = text()
  152. assert not ADDRESS.findall(body), ADDRESS.findall(body)
  153. assert not IPV4.findall(body), IPV4.findall(body)
  154. assert "—" not in body
  155. found = set(HEX64.findall(body))
  156. assert found, "the guard collected no hash at all"
  157. assert found <= PUBLIC_HEX, sorted(found - PUBLIC_HEX)
  158. assert "blockchain" in body.lower(), "the guard collected nothing"
  159. def test_the_address_and_hex_guards_bite():
  160. assert ADDRESS.search("send to 1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa today")
  161. assert ADDRESS.search("send to bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq today")
  162. assert ADDRESS.search("send to 0x" + "ab" * 20 + " today")
  163. assert ADDRESS.search("send to 4" + "A" + "b" * 93 + " today")
  164. assert not ADDRESS.search("the block hash 000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f")
  165. assert HEX64.search("key " + "ab" * 32) and "ab" * 32 not in PUBLIC_HEX
  166. assert IPV4.search("host 192.0.2.7") and not IPV4.search("as of release 0.9.7.1")
  167. def test_the_snapshot_records_the_date_and_the_height_and_prints_no_address():
  168. body = text()
  169. assert TIP in body, "the chain height at the time of the read is recorded"
  170. part = body.split("## A real snapshot: the first two Bitcoin blocks")[1].split("\n## ")[0]
  171. assert DATE in part and TIP in part
  172. assert "blockstream.info" in part, "the explorer is named"
  173. assert "I print no address" in part
  174. def test_the_snapshot_hashes_match_their_own_header_fields():
  175. rows = snapshot(text())
  176. prev0 = rows["Previous block hash"][0]
  177. zero = "0" * 64 if prev0.startswith("none") else prev0
  178. for col, prev in ((0, zero), (1, rows["Previous block hash"][1])):
  179. want = rows["Block hash"][col]
  180. got = header_hash(
  181. int(rows["Version"][col]),
  182. prev,
  183. rows["Merkle root"][col],
  184. int(rows["Time (Unix seconds)"][col]),
  185. int(rows["Difficulty bits (hex)"][col], 16),
  186. int(rows["Nonce"][col]),
  187. )
  188. assert got == want, (col, got, want)
  189. assert rows["Previous block hash"][1] == rows["Block hash"][0], "block 1 must point at block 0"
  190. for col in (0, 1):
  191. assert rows["Transactions"][col] == "1"
  192. assert rows["Transaction id"][col] == rows["Merkle root"][col], "one transaction: the root is its id"
  193. when = int(rows["Time (Unix seconds)"][col])
  194. utc = datetime.datetime.fromtimestamp(when, datetime.UTC).strftime("%Y-%m-%d %H:%M:%S")
  195. assert rows["Time (UTC)"][col].startswith(utc), (rows["Time (UTC)"][col], utc)
  196. assert rows["Height"] == ["0", "1"]
  197. def test_the_snapshot_guard_bites():
  198. good = (
  199. "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f",
  200. "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b",
  201. )
  202. assert header_hash(1, "0" * 64, good[1], 1231006505, 0x1D00FFFF, 2083236893) == good[0]
  203. assert header_hash(1, "0" * 64, good[1], 1231006505, 0x1D00FFFF, 2083236894) != good[0], "one nonce digit changes it"
  204. def test_every_diagram_has_alt_text_a_source_and_a_picture_that_exists():
  205. body = text()
  206. found = list(WRAPPED.finditer(body))
  207. assert len(found) == 5, "expected five diagrams"
  208. assert len(re.findall(r"```mermaid", body)) == len(found), "a Mermaid block has no picture above it"
  209. manifest = json.loads((ROOT / "docs" / "diagrams.json").read_text())
  210. for m in found:
  211. alt = m["alt"].strip()
  212. assert 20 <= len(alt) <= 150, alt
  213. assert alt.lower() not in {"diagram", "image", "picture"}, alt
  214. png = (PAGE.parent / m["path"]).resolve()
  215. assert png.is_file(), m["path"]
  216. assert png.relative_to(ROOT).as_posix() in manifest, m["path"]
  217. assert m["src"].lstrip().startswith(("flowchart", "sequenceDiagram")), m["path"]
  218. def test_the_diagram_guard_bites():
  219. bare = "![alt text here](images/x.png)\n\nno details block, so no source\n"
  220. assert not WRAPPED.search(bare)
  221. 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>"
  222. assert WRAPPED.search(good)
  223. assert not WRAPPED.search(good.replace("<details>\n", ""))
  224. def test_the_diagrams_cover_the_four_topics_the_issue_asks_for():
  225. body = text()
  226. alts = " ".join(m["alt"].lower() for m in WRAPPED.finditer(body))
  227. for topic in ("chain of blocks", "life of a transaction", "gossip", "fork"):
  228. assert topic in alts, topic
  229. def test_every_claims_register_row_has_a_status():
  230. rows = register_rows(text())
  231. assert len(rows) >= 20, "the guard collected too few rows"
  232. assert not rows_missing_status(text())
  233. def test_every_sourced_row_has_a_url_and_the_read_date():
  234. assert not sourced_rows_without_url_and_date(text())
  235. reg = text().split("## Claims register")[1]
  236. for host in (
  237. "bitcoin.org/bitcoin.pdf",
  238. "developer.bitcoin.org/devguide/block_chain.html",
  239. "developer.bitcoin.org/devguide/p2p_network.html",
  240. "developer.bitcoin.org/devguide/mining.html",
  241. "bitcoin.org/en/full-node",
  242. "NIST.IR.8202",
  243. "bip-0050",
  244. "ethereum.org/developers/docs/consensus-mechanisms",
  245. "ethereum.org/developers/docs/nodes-and-clients",
  246. "arxiv.org/abs/1311.0243",
  247. "blockstream.info/api",
  248. ):
  249. assert host in reg, host
  250. assert reg.count(DATE) >= 15
  251. def test_the_register_guards_bite():
  252. bad = "## Claims register\n\n| Claim | Source | Status |\n|---|---|---|\n| X | y | maybe |\n"
  253. assert rows_missing_status(bad) == ["X"]
  254. undated = "## Claims register\n\n| Claim | Source | Status |\n|---|---|---|\n| X | [p](https://example.com/p) | Read 2026-10-31 |\n"
  255. assert sourced_rows_without_url_and_date(undated) == ["X"]
  256. nourl = "## Claims register\n\n| Claim | Source | Status |\n|---|---|---|\n| X | a page | Read 2026-11-01 |\n"
  257. assert sourced_rows_without_url_and_date(nourl) == ["X"]
  258. def test_the_stance_the_background_and_the_anecdote_are_stated_once_and_plainly():
  259. body = text()
  260. assert "uses and is comfortable with cryptocurrency" in body
  261. assert "not everyone is" in body
  262. stance = body.split("## The stance, the background and where these lessons come from")[1].split("\n## ")[0]
  263. assert body.count("cryptobro") == stance.count("cryptobro") == 2, "said in the stance section only, not repeated"
  264. assert "heading up security and IT for cryptocurrency companies" in body
  265. assert "around 2009 to 2010" in body
  266. assert "CES 2016" in body and "Every Key" in body
  267. assert "John McAfee" in body and "his account" in body
  268. assert body.count("McAfee") == 1, "no other claim about that person"
  269. def test_the_page_has_no_price_talk_shilling_or_evasion_content():
  270. body = text().lower()
  271. for banned in (
  272. "to the moon", "shitcoin", "memecoin", "hodl", "lambo", "buy the dip", "bullish", "bearish",
  273. "market cap", "all-time high", "pump", "airdrop", "evade detection", "avoid law enforcement",
  274. "launder money", "hide your funds", "bypass kyc",
  275. ):
  276. assert banned not in body, banned
  277. assert body.count("price") <= 1 and body.count("trading") <= 1, "named once as out of scope, nothing more"
  278. assert "no how-to for anything illegal" in body
  279. def test_the_page_says_what_a_blockchain_is_not_and_marks_the_exercise_as_not_run():
  280. body = text()
  281. assert "## What a blockchain is not" in body
  282. assert "## Free exercise: follow one famous transaction" in body
  283. for needed in ("not a database you can edit", "not automatically anonymous", "not automatically secure"):
  284. assert needed in body.lower(), needed
  285. exercise = body.split("## Free exercise: follow one famous transaction")[1].split("\n## ")[0]
  286. assert "Not run" in exercise
  287. def test_old_pages_are_dated_where_they_are_used():
  288. body = text()
  289. assert "2009-2020" in body or "2009 to 2020" in body, "the developer guide's own copyright range is stated"
  290. assert "NIST.IR.8202" in body and "October 2018" in body
  291. assert "light sync" in body.lower(), "the Ethereum page's own caveat on light sync is reported"