yuntian-deng commited on
Commit
8ae72a1
·
verified ·
1 Parent(s): e8912b0

snapshot 2026-04-21T16:53:01Z

Browse files
Files changed (2) hide show
  1. README.md +1 -1
  2. verify.py +131 -33
README.md CHANGED
@@ -50,4 +50,4 @@ print(len(entries), "entries")
50
 
51
  Run by [@da03](https://github.com/da03).
52
 
53
- Last auto-generated: 2026-04-21T16:42:57Z
 
50
 
51
  Run by [@da03](https://github.com/da03).
52
 
53
+ Last auto-generated: 2026-04-21T16:53:00Z
verify.py CHANGED
@@ -1,38 +1,48 @@
1
  #!/usr/bin/env python3
2
  """
3
- verify.py - standalone chain verifier for append.page
4
 
5
- Usage:
6
- python verify.py path/to/page.jsonl
7
- curl -sS https://append.page/p/<slug>/raw | python verify.py /dev/stdin
8
- python verify.py path/to/page.jsonl --with-bodies path/to/bodies.json
 
 
 
 
 
9
 
10
  Exit codes:
11
- 0 chain is intact
12
- 1 chain is broken (failure details on stderr)
13
- 2 usage error
14
 
15
  What it checks:
16
  1. Each entry's `hash` matches SHA-256(JCS-canonical(entry_minus_hash)).
17
  2. Each entry's `prev_hash` matches the previous entry's `hash`.
18
- 3. The first entry's `prev_hash` matches SHA-256("genesis|<slug>|<page_created_at>").
19
- (The genesis seed only depends on the slug + page creation timestamp; we
20
- derive `page_created_at` from a "?genesis_at=<ISO8601>" hint on the URL
21
- or from the first entry's metadata if available; otherwise the genesis
22
- check is skipped with a note.)
23
- 4. With --with-bodies: each revealed (body, salt) pair hashes to the on-chain
24
- body_commitment for its entry.
25
-
26
- Dependencies: stdlib only (json, hashlib, sys, argparse) + the `jcs` PyPI
27
- package for RFC 8785 canonicalization. Install with: pip install jcs
28
- (falls back to a sort_keys + compact-separators approach if jcs is missing,
29
- which is byte-equivalent for our entry shape since we use only string/integer
30
- values, no floats and no special escaping).
 
 
 
31
  """
32
  import argparse
33
  import hashlib
34
  import json
35
  import sys
 
 
36
  from typing import Optional
37
 
38
  try:
@@ -132,29 +142,109 @@ def verify_chain(
132
  return True, f"verified {len(entries)} entries, chain intact, head: {expected_prev_hash}"
133
 
134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  def main() -> int:
136
- ap = argparse.ArgumentParser(description="Verify an append.page chain (JSONL).")
137
- ap.add_argument("jsonl", help="path to a .jsonl file (or /dev/stdin)")
 
 
 
 
 
 
 
 
 
138
  ap.add_argument(
139
  "--with-bodies",
140
  metavar="PATH",
141
- help="JSON file mapping entry_id -> {body, salt} (salt as hex)",
 
 
 
 
142
  )
143
  ap.add_argument(
144
  "--genesis-at",
145
  metavar="ISO8601",
146
- help="page creation timestamp; if supplied, also verifies entry[0].prev_hash "
147
- "== SHA-256(\"genesis|<slug>|<ts>\")",
 
 
148
  )
149
  args = ap.parse_args()
150
 
151
- with open(args.jsonl, "r", encoding="utf-8") as f:
152
- entries = [json.loads(line) for line in f if line.strip()]
 
153
 
154
- bodies_by_id = None
155
- if args.with_bodies:
156
- with open(args.with_bodies, "r", encoding="utf-8") as f:
157
- bodies_by_id = json.load(f)
 
 
 
 
 
 
 
 
 
158
 
159
  ok, msg = verify_chain(entries, bodies_by_id)
160
  if not ok:
@@ -172,7 +262,15 @@ def main() -> int:
172
  )
173
  return 1
174
 
175
- print(f"OK: {msg}")
 
 
 
 
 
 
 
 
176
  return 0
177
 
178
 
 
1
  #!/usr/bin/env python3
2
  """
3
+ verify.py - standalone chain + body verifier for append.page
4
 
5
+ Common usage (one URL, full check):
6
+ python verify.py https://append.page/p/<slug>
7
+
8
+ Other modes:
9
+ python verify.py path/to/page.jsonl # chain only, offline
10
+ curl -sS https://append.page/p/<slug>/raw | \\
11
+ python verify.py /dev/stdin # chain only, offline
12
+ python verify.py path/to/page.jsonl \\
13
+ --with-bodies path/to/bodies.json # chain + bodies, offline
14
 
15
  Exit codes:
16
+ 0 chain (and optionally bodies) intact
17
+ 1 verification failed (details on stderr)
18
+ 2 usage error / network failure
19
 
20
  What it checks:
21
  1. Each entry's `hash` matches SHA-256(JCS-canonical(entry_minus_hash)).
22
  2. Each entry's `prev_hash` matches the previous entry's `hash`.
23
+ 3. seq increments by 1 from 0; page slug is constant across the chain.
24
+ 4. The first entry's `prev_hash` matches the genesis seed
25
+ SHA-256("genesis|<slug>|<page_created_at>"). Pass --genesis-at <ISO>
26
+ to enforce this; without it the genesis check is skipped with a note.
27
+ 5. URL mode + bodies mode: each non-erased entry's body+salt satisfies
28
+ SHA-256(salt || body) == entry.body_commitment. Erased entries skip
29
+ this check (the body is gone). The API still returns salt for
30
+ erased entries, so anyone who archived a body privately before
31
+ erasure can re-verify it offline by passing --with-bodies on a
32
+ JSON file they assemble themselves.
33
+
34
+ Dependencies: stdlib only (json, hashlib, sys, argparse, urllib) + the
35
+ `jcs` PyPI package for RFC 8785 canonicalization. Install with:
36
+ pip install jcs
37
+ (falls back to sort_keys + compact-separators, which is byte-equivalent
38
+ for our entry shape since we use only string and integer values).
39
  """
40
  import argparse
41
  import hashlib
42
  import json
43
  import sys
44
+ import urllib.error
45
+ import urllib.request
46
  from typing import Optional
47
 
48
  try:
 
142
  return True, f"verified {len(entries)} entries, chain intact, head: {expected_prev_hash}"
143
 
144
 
145
+ def _http_get_jsonl(url: str) -> list[dict]:
146
+ """Download a JSONL endpoint and parse one object per non-empty line."""
147
+ with urllib.request.urlopen(url, timeout=30) as resp:
148
+ text = resp.read().decode("utf-8")
149
+ return [json.loads(line) for line in text.splitlines() if line.strip()]
150
+
151
+
152
+ def _http_post_json(url: str, payload: dict) -> dict:
153
+ req = urllib.request.Request(
154
+ url,
155
+ data=json.dumps(payload).encode("utf-8"),
156
+ headers={"content-type": "application/json"},
157
+ method="POST",
158
+ )
159
+ with urllib.request.urlopen(req, timeout=30) as resp:
160
+ return json.loads(resp.read().decode("utf-8"))
161
+
162
+
163
+ def fetch_url(base_url: str) -> tuple[list[dict], dict[str, dict]]:
164
+ """
165
+ Fetch the chain (one HTTP call) plus all bodies+salts (one bulk POST per
166
+ 200-id batch). Returns (entries, bodies_by_id) where bodies_by_id maps
167
+ entry id -> {body, salt}. Erased entries are omitted from bodies_by_id
168
+ (no body to verify against); the chain check still applies to them.
169
+ The API does still return salt for erased entries — useful if you
170
+ have a private archive of the body and want to recheck offline.
171
+ """
172
+ base_url = base_url.rstrip("/")
173
+ raw_url = base_url + "/raw"
174
+ bodies_url = base_url + "/bodies"
175
+
176
+ entries = _http_get_jsonl(raw_url)
177
+ if not entries:
178
+ return entries, {}
179
+
180
+ ids = [e["id"] for e in entries]
181
+ bodies_by_id: dict[str, dict] = {}
182
+ for batch_start in range(0, len(ids), 200):
183
+ batch = ids[batch_start : batch_start + 200]
184
+ resp = _http_post_json(bodies_url, {"ids": batch})
185
+ for item in resp.get("entries", []):
186
+ entry = item.get("entry", {})
187
+ entry_id = entry.get("id")
188
+ if not entry_id:
189
+ continue
190
+ if item.get("erased"):
191
+ continue
192
+ body = item.get("body")
193
+ salt = item.get("salt")
194
+ if body is None or salt is None:
195
+ continue
196
+ bodies_by_id[entry_id] = {"body": body, "salt": salt}
197
+ return entries, bodies_by_id
198
+
199
+
200
  def main() -> int:
201
+ ap = argparse.ArgumentParser(
202
+ description="Verify an append.page chain (and optionally bodies)."
203
+ )
204
+ ap.add_argument(
205
+ "source",
206
+ help=(
207
+ "either an append.page URL like https://append.page/p/<slug> "
208
+ "(fetches chain + bodies + salts and verifies everything), or a "
209
+ "path to a .jsonl file (chain-only unless --with-bodies given)"
210
+ ),
211
+ )
212
  ap.add_argument(
213
  "--with-bodies",
214
  metavar="PATH",
215
+ help=(
216
+ "JSON file mapping entry_id -> {body, salt} (salt as hex). "
217
+ "Ignored when SOURCE is a URL — bodies are fetched live in "
218
+ "that case."
219
+ ),
220
  )
221
  ap.add_argument(
222
  "--genesis-at",
223
  metavar="ISO8601",
224
+ help=(
225
+ "page creation timestamp; if supplied, also verifies "
226
+ 'entry[0].prev_hash == SHA-256("genesis|<slug>|<ts>")'
227
+ ),
228
  )
229
  args = ap.parse_args()
230
 
231
+ is_url = args.source.startswith("http://") or args.source.startswith(
232
+ "https://"
233
+ )
234
 
235
+ bodies_by_id: Optional[dict[str, dict]] = None
236
+ if is_url:
237
+ try:
238
+ entries, bodies_by_id = fetch_url(args.source)
239
+ except urllib.error.URLError as e:
240
+ print(f"FAIL: could not fetch {args.source}: {e}", file=sys.stderr)
241
+ return 2
242
+ else:
243
+ with open(args.source, "r", encoding="utf-8") as f:
244
+ entries = [json.loads(line) for line in f if line.strip()]
245
+ if args.with_bodies:
246
+ with open(args.with_bodies, "r", encoding="utf-8") as f:
247
+ bodies_by_id = json.load(f)
248
 
249
  ok, msg = verify_chain(entries, bodies_by_id)
250
  if not ok:
 
262
  )
263
  return 1
264
 
265
+ body_note = ""
266
+ if bodies_by_id is not None:
267
+ verified = sum(1 for _ in bodies_by_id)
268
+ skipped = len(entries) - verified
269
+ body_note = (
270
+ f"; verified {verified} bodies (commitment matches),"
271
+ f" skipped {skipped} (erased or no body)"
272
+ )
273
+ print(f"OK: {msg}{body_note}")
274
  return 0
275
 
276