donationbee-verify 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,67 @@
1
+ Metadata-Version: 2.5
2
+ Name: donationbee-verify
3
+ Version: 0.1.0
4
+ Summary: Independent verifier for DonationBee payment ledgers: checks every hash, signature, witness and anchor itself
5
+ Project-URL: Homepage, https://bee.theorycorner.com
6
+ Project-URL: Source, https://github.com/HallowDance/donationbee
7
+ Project-URL: Specification, https://github.com/HallowDance/donationbee/blob/master/docs/LEDGER_SPEC.md
8
+ Author: Ivo Iliev
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: c2sp,donations,merkle-tree,transparency-log,verification
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Environment :: Console
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Security :: Cryptography
17
+ Requires-Python: >=3.12
18
+ Requires-Dist: cryptography>=43
19
+ Requires-Dist: httpx>=0.27
20
+ Requires-Dist: pynacl>=1.5
21
+ Requires-Dist: rfc8785>=0.1.4
22
+ Description-Content-Type: text/markdown
23
+
24
+ # donationbee-verify
25
+
26
+ An independent checker for [DonationBee](https://bee.theorycorner.com) payment ledgers. It doesn't
27
+ take the server's word for anything: it downloads the public entries and redoes every check
28
+ itself.
29
+
30
+ ```sh
31
+ pip install donationbee-verify
32
+ vpp-verify --url https://bee.theorycorner.com
33
+ ```
34
+
35
+ ## What it checks
36
+
37
+ - **The chain.** Every entry's hash, its link to the previous entry, and its signature by the key
38
+ that was in charge at that point. Key changes count only when enough offline root keys signed
39
+ them.
40
+ - **The Merkle tree.** It recomputes the tree and checks that the log's signed checkpoints match
41
+ it.
42
+ - **Recipient confirmations.** Every passkey (WebAuthn) signature a recipient made to confirm a
43
+ payment.
44
+ - **Witnesses** (`--witness <vkey> --min-witnesses k`). Independent witnesses must have cosigned
45
+ the checkpoint you see, so you know you're seeing the same history as everyone else.
46
+ - **Anchors** (`--anchors-repo <git url> --check-ots`). Checkpoints published in a git repo the
47
+ operator doesn't control, and their Bitcoin timestamps.
48
+ - **Domains** (`--check-domains`). Each recipient's website still lists the passkey they confirm
49
+ with.
50
+ - **Receipts** (`--receipt receipt.json`). Your payment is still in the ledger, unchanged. If it
51
+ isn't, the verifier writes out an evidence file you can show to others.
52
+
53
+ Pin the ledger you expect with `--pin-genesis <hash>`, so nobody can swap in a different one.
54
+
55
+ ## Why it's separate
56
+
57
+ This package shares no code with the DonationBee server. It's written from the format
58
+ specification ([LEDGER_SPEC.md](https://github.com/HallowDance/donationbee/blob/master/docs/LEDGER_SPEC.md))
59
+ and tested against shared test vectors. That way a bug or a lie in the server can't hide inside the
60
+ tool meant to catch it.
61
+
62
+ Its dependencies are small: `pynacl` (Ed25519), `cryptography` (passkey signatures), `rfc8785`
63
+ (canonical JSON) and `httpx`.
64
+
65
+ ## License
66
+
67
+ Apache-2.0.
@@ -0,0 +1,11 @@
1
+ vpp_verify/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ vpp_verify/cli.py,sha256=kgwqq6q0mjnevm7fqhxqdfg0-pr7lKEI7_tRHM3SLHI,12034
3
+ vpp_verify/core.py,sha256=9RPzlmr96HrNQZSHHMe3_vKjiT50cW2ApvCLF_nCqs0,11987
4
+ vpp_verify/merkle.py,sha256=wLQ9PtM44KUenkC8WfXkty5cn79X4FAn7ORpJhNQU-w,2724
5
+ vpp_verify/note.py,sha256=syYV70GchaH4c9xwri8QGGb_NEzoRIJSr60UVBPaI8s,6854
6
+ vpp_verify/webauthn.py,sha256=AmlkD8grh0-Iw233mOyyIKlXdZAN_9QmrdwZJ_7vpoo,2885
7
+ donationbee_verify-0.1.0.dist-info/METADATA,sha256=0VYmnoFMLOk2nRX0czyTT8yML0-7z3j9elufv2yBJ8w,2898
8
+ donationbee_verify-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
+ donationbee_verify-0.1.0.dist-info/entry_points.txt,sha256=XkJlqkZu49yvX-6osnlxQ16iuFgMeimkFsHN1dro3fU,51
10
+ donationbee_verify-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
11
+ donationbee_verify-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ vpp-verify = vpp_verify.cli:main
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
vpp_verify/__init__.py ADDED
File without changes
vpp_verify/cli.py ADDED
@@ -0,0 +1,306 @@
1
+ """vpp-verify: check a VPP ledger without trusting the server that serves it.
2
+
3
+ Trust comes from: a pinned genesis hash, witness cosignatures (--witness), an independently
4
+ hosted anchors repo (--anchors-repo) and Bitcoin (--check-ots), and recipients' own domains
5
+ (--check-domains). The server only supplies data; every claim is recomputed here.
6
+ """
7
+
8
+ import argparse
9
+ import base64
10
+ import json
11
+ import shutil
12
+ import subprocess
13
+ import sys
14
+ import tempfile
15
+ from pathlib import Path
16
+
17
+ import httpx
18
+
19
+ from . import merkle
20
+ from .core import ChainState, VerificationError, checkpoint_key, verify_entry
21
+ from .note import Checkpoint, Note, NoteError, Verifier, verify_cosignature, verify_note_signature
22
+
23
+
24
+ class Failure(Exception):
25
+ pass
26
+
27
+
28
+ # --- data sources ---
29
+
30
+
31
+ def _fetch_entries(client: httpx.Client, base: str, up_to: int | None = None):
32
+ after = 0
33
+ while up_to is None or after < up_to:
34
+ page = client.get(f"{base}/api/v1/entries", params={"after": after, "limit": 500}).json()
35
+ yield from page["entries"]
36
+ if not page.get("next_after"):
37
+ return
38
+ after = page["next_after"]
39
+
40
+
41
+ def _fetch_checkpoint(client: httpx.Client, base: str) -> Note:
42
+ r = client.get(f"{base}/api/v1/checkpoint")
43
+ r.raise_for_status()
44
+ return Note.parse(r.text)
45
+
46
+
47
+ # --- checks ---
48
+
49
+
50
+ def check_log_signature(state: ChainState, note: Note) -> Checkpoint:
51
+ cp = Checkpoint.parse(note.text)
52
+ if cp.origin != state.origin:
53
+ raise Failure(f"checkpoint origin {cp.origin!r} is not this ledger ({state.origin!r})")
54
+ if cp.size > state.seq:
55
+ raise Failure(f"checkpoint size {cp.size} is beyond the {state.seq} verified entries")
56
+ if cp.size == 0:
57
+ raise Failure("empty checkpoint")
58
+ v = Verifier(state.origin, 0x01, checkpoint_key(state, cp.size))
59
+ try:
60
+ if not verify_note_signature(note, v):
61
+ raise Failure(f"checkpoint {cp.size} is not signed by the ledger key for that size")
62
+ except NoteError as e:
63
+ raise Failure(str(e)) from None
64
+ if cp.root != state.root_at(cp.size):
65
+ raise Failure(f"checkpoint {cp.size} root differs from the tree of the served entries")
66
+ return cp
67
+
68
+
69
+ def count_witnesses(note: Note, witnesses: list[Verifier]) -> list[str]:
70
+ ok = []
71
+ for w in witnesses:
72
+ try:
73
+ if verify_cosignature(note, w) is not None:
74
+ ok.append(w.name)
75
+ except NoteError as e:
76
+ raise Failure(f"witness {w.name}: {e}") from None
77
+ return ok
78
+
79
+
80
+ def _anchors_dir(repo: str, workdir: Path) -> Path:
81
+ p = Path(repo)
82
+ if p.is_dir():
83
+ return p
84
+ dest = workdir / "anchors"
85
+ subprocess.run(["git", "clone", "-q", "--depth", "1", repo, str(dest)], check=True)
86
+ return dest
87
+
88
+
89
+ def check_anchors(state: ChainState, repo: Path, check_ots: bool) -> list[str]:
90
+ lines = []
91
+ files = sorted(repo.glob("anchors/**/*.checkpoint"), key=lambda f: int(f.stem))
92
+ if not files:
93
+ raise Failure(f"no anchors found in {repo}")
94
+ for f in files:
95
+ note = Note.parse(f.read_text())
96
+ cp = check_log_signature(state, note)
97
+ status = "matches chain"
98
+ ots_file = f.with_name(f.name + ".ots")
99
+ if check_ots:
100
+ status += ", ots " + _ots_verify(f, ots_file)
101
+ lines.append(f"anchor size {cp.size}: {status}")
102
+ return lines
103
+
104
+
105
+ def _ots_verify(target: Path, proof: Path) -> str:
106
+ if not proof.exists():
107
+ return "missing"
108
+ if not shutil.which("ots"):
109
+ return "skipped (ots not installed)"
110
+ r = subprocess.run(
111
+ ["ots", "verify", "-f", str(target), str(proof)], capture_output=True, text=True
112
+ )
113
+ out = (r.stderr or r.stdout).strip()
114
+ if r.returncode == 0:
115
+ return "ok (in Bitcoin)"
116
+ if "Pending confirmation" in out:
117
+ return "pending (not yet in a Bitcoin block)"
118
+ # `ots verify` checks complete proofs against a local Bitcoin node.
119
+ raise Failure(f"OpenTimestamps verification failed for {target.name}: {out[:200]}")
120
+
121
+
122
+ def check_domains(state: ChainState, client: httpx.Client) -> list[str]:
123
+ lines = []
124
+ for rcpt, keys in state.recipient_keys.items():
125
+ for body in keys.values():
126
+ url = f"https://{body['domain']}/.well-known/vpp.json"
127
+ try:
128
+ doc = client.get(url, follow_redirects=False, timeout=10).json()
129
+ except (httpx.HTTPError, ValueError) as e:
130
+ lines.append(f"{rcpt} @ {body['domain']}: UNREACHABLE ({e.__class__.__name__})")
131
+ continue
132
+ listed = (
133
+ doc.get("log") == state.origin
134
+ and doc.get("profile") == rcpt
135
+ and body["fingerprint"] in doc.get("keys", [])
136
+ )
137
+ lines.append(
138
+ f"{rcpt} @ {body['domain']}: {'key listed' if listed else 'KEY NOT LISTED'}"
139
+ )
140
+ return lines
141
+
142
+
143
+ # --- receipts ---
144
+
145
+
146
+ def verify_receipt(
147
+ receipt: dict,
148
+ state: ChainState | None,
149
+ witnesses: list[Verifier],
150
+ min_witnesses: int,
151
+ client: httpx.Client | None,
152
+ base: str | None,
153
+ ) -> list[str]:
154
+ import hashlib
155
+
156
+ wire = receipt["entry"]
157
+ envelope = base64.urlsafe_b64decode(wire["envelope"] + "=" * (-len(wire["envelope"]) % 4))
158
+ h = hashlib.sha256(b"vpp:entry:v1\x00" + bytes.fromhex(wire["prev_hash"]) + envelope).digest()
159
+ if h.hex() != wire["hash"]:
160
+ raise Failure("receipt entry hash does not match its envelope")
161
+ note = Note.parse(receipt["checkpoint"])
162
+ cp = Checkpoint.parse(note.text)
163
+ proof = [base64.b64decode(p) for p in receipt["inclusion_proof"]]
164
+ if not merkle.verify_inclusion(merkle.leaf_hash(h), wire["seq"] - 1, cp.size, proof, cp.root):
165
+ raise Failure("receipt inclusion proof is invalid")
166
+ lines = [f"receipt: entry {wire['seq']} is included in checkpoint size {cp.size}"]
167
+ names = count_witnesses(note, witnesses)
168
+ if len(names) < min_witnesses:
169
+ raise Failure(
170
+ f"receipt checkpoint has {len(names)} witness cosignatures, need {min_witnesses}"
171
+ )
172
+ if names:
173
+ lines.append(f"receipt: cosigned by {', '.join(names)}")
174
+
175
+ if state is None:
176
+ return lines
177
+ # Online: the ledger served now must still contain the entry, and agree with the receipt.
178
+ try:
179
+ check_log_signature(state, note)
180
+ if state.hashes.get(wire["seq"]) != h:
181
+ raise Failure(f"entry {wire['seq']} served now differs from the receipt")
182
+ except Failure as e:
183
+ lines.append(misbehaviour(note, client, base, str(e)))
184
+ raise Failure("\n".join(lines)) from None
185
+ lines.append("receipt: entry still present and consistent with the current ledger")
186
+ return lines
187
+
188
+
189
+ def misbehaviour(signed: Note, client, base, reason: str) -> str:
190
+ """A transferable bundle: a checkpoint the ledger signed, and what it serves now."""
191
+ bundle = {"reason": reason, "signed_checkpoint": str(signed)}
192
+ if client is not None:
193
+ try:
194
+ bundle["current_checkpoint"] = str(_fetch_checkpoint(client, base))
195
+ except (httpx.HTTPError, NoteError):
196
+ pass
197
+ path = Path(tempfile.gettempdir()) / "vpp-misbehaviour.json"
198
+ path.write_text(json.dumps(bundle, indent=2))
199
+ return f"MISBEHAVIOUR: {reason}. Evidence bundle written to {path}"
200
+
201
+
202
+ # --- main ---
203
+
204
+
205
+ def main(argv: list[str] | None = None, client: httpx.Client | None = None) -> int:
206
+ """`client` is injectable for tests; normally one is created for --url."""
207
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter)
208
+ src = p.add_mutually_exclusive_group(required=True)
209
+ src.add_argument("--url", help="ledger base URL, e.g. https://proofs.example")
210
+ src.add_argument("--file", type=Path, help="JSON file with 'entries' (and 'checkpoints')")
211
+ p.add_argument("--pin-genesis", help="expected genesis entry hash (hex); strongly recommended")
212
+ p.add_argument("--witness", action="append", default=[], help="witness vkey (repeatable)")
213
+ p.add_argument("--min-witnesses", type=int, default=0, help="cosignatures required")
214
+ p.add_argument("--anchors-repo", help="path or git URL of the public anchors repo")
215
+ p.add_argument("--check-ots", action="store_true", help="verify anchors' Bitcoin timestamps")
216
+ p.add_argument("--check-domains", action="store_true", help="re-check recipients' domains")
217
+ p.add_argument("--receipt", type=Path, help="also verify a payer receipt.json")
218
+ args = p.parse_args(argv)
219
+
220
+ owns_client = client is None and args.url is not None
221
+ if owns_client:
222
+ client = httpx.Client(timeout=30, follow_redirects=True)
223
+ base = args.url.rstrip("/") if args.url else None
224
+ pinned = bytes.fromhex(args.pin_genesis) if args.pin_genesis else None
225
+ out: list[str] = []
226
+ try:
227
+ witnesses = [Verifier.parse(w) for w in args.witness]
228
+ state = ChainState()
229
+ latest: Note | None = None
230
+ file_checkpoints: list[str] = []
231
+ if args.file:
232
+ data = json.loads(args.file.read_text())
233
+ entries = data["entries"]
234
+ file_checkpoints = [c["note"] for c in data.get("checkpoints", [])]
235
+ else:
236
+ latest = _fetch_checkpoint(client, base) # first, so entries cover it
237
+ entries = _fetch_entries(client, base)
238
+ for wire in entries:
239
+ verify_entry(state, wire)
240
+ if state.seq == 1 and pinned is not None and state.head != pinned:
241
+ raise VerificationError(1, "genesis hash does not match the pinned value")
242
+ if state.seq == 0:
243
+ raise Failure("ledger is empty")
244
+ out.append(f"chain: {state.seq} entries verified, root {state.root.hex()[:16]}…")
245
+ out.append(
246
+ f"payments confirmed by recipients: {len(state.confirmed)}/{len(state.payments)}"
247
+ )
248
+
249
+ for raw in file_checkpoints:
250
+ cp = check_log_signature(state, Note.parse(raw))
251
+ out.append(f"checkpoint size {cp.size}: signed and matches chain")
252
+ if latest is not None:
253
+ cp = check_log_signature(state, latest)
254
+ names = count_witnesses(latest, witnesses)
255
+ out.append(
256
+ f"latest checkpoint size {cp.size}: cosigned by {len(names)} of "
257
+ f"{len(witnesses)} given witnesses {names}"
258
+ )
259
+ if len(witnesses) and latest is None:
260
+ raise Failure("witness checks need --url")
261
+ if args.min_witnesses:
262
+ if latest is None or len(count_witnesses(latest, witnesses)) < args.min_witnesses:
263
+ raise Failure(
264
+ f"fewer than {args.min_witnesses} witnesses cosigned the checkpoint;"
265
+ " the server may be showing you a private fork"
266
+ )
267
+
268
+ if args.anchors_repo:
269
+ with tempfile.TemporaryDirectory() as tmp:
270
+ out += check_anchors(
271
+ state, _anchors_dir(args.anchors_repo, Path(tmp)), args.check_ots
272
+ )
273
+ if args.check_domains:
274
+ out += check_domains(state, client or httpx.Client(timeout=10))
275
+ if args.receipt:
276
+ out += verify_receipt(
277
+ json.loads(args.receipt.read_text()),
278
+ state,
279
+ witnesses,
280
+ args.min_witnesses,
281
+ client,
282
+ base,
283
+ )
284
+ except VerificationError as e:
285
+ print("\n".join(out), file=sys.stderr)
286
+ print(f"FAIL {e}", file=sys.stderr)
287
+ return 1
288
+ except (Failure, NoteError, httpx.HTTPError) as e:
289
+ print("\n".join(out), file=sys.stderr)
290
+ print(f"FAIL {e}", file=sys.stderr)
291
+ return 1
292
+ finally:
293
+ if owns_client:
294
+ client.close()
295
+
296
+ print("\n".join(out))
297
+ print("OK")
298
+ if pinned is None:
299
+ print("note: genesis not pinned; pass --pin-genesis to detect a substituted ledger")
300
+ if not args.min_witnesses and args.url:
301
+ print("note: no --min-witnesses; a server could show you a fork no one else sees")
302
+ return 0
303
+
304
+
305
+ if __name__ == "__main__":
306
+ sys.exit(main())
vpp_verify/core.py ADDED
@@ -0,0 +1,289 @@
1
+ """Chain verification, implemented from docs/LEDGER_SPEC.md only. Must not import `vpp`."""
2
+
3
+ import base64
4
+ import hashlib
5
+ import json
6
+ from dataclasses import dataclass, field
7
+
8
+ import rfc8785
9
+ from nacl.exceptions import BadSignatureError
10
+ from nacl.signing import VerifyKey
11
+
12
+ from . import merkle
13
+ from .webauthn import WebAuthnError, b64url_decode, fingerprint, load_key, verify_assertion
14
+
15
+ DOMAIN = b"vpp:entry:v1\x00"
16
+ ZERO = bytes(32)
17
+ MAX_SAFE_INT = 2**53 - 1
18
+
19
+
20
+ class VerificationError(Exception):
21
+ def __init__(self, seq: int, message: str):
22
+ super().__init__(f"seq {seq}: {message}")
23
+ self.seq = seq
24
+ self.message = message
25
+
26
+
27
+ @dataclass
28
+ class ChainState:
29
+ """Everything a verifier needs to resume from a trusted point."""
30
+
31
+ seq: int = 0
32
+ head: bytes = ZERO
33
+ origin: str | None = None
34
+ online_key: bytes | None = None
35
+ root_keys: list[str] = field(default_factory=list)
36
+ root_threshold: int = 0
37
+ used_online_keys: set[bytes] = field(default_factory=set)
38
+ used_root_sets: set[tuple] = field(default_factory=set)
39
+ # seq -> online key that signed it; checkpoints of size n are signed by keys[n].
40
+ signer_at: dict[int, bytes] = field(default_factory=dict)
41
+ hashes: dict[int, bytes] = field(default_factory=dict)
42
+ leaves: list[bytes] = field(default_factory=list) # RFC 6962 leaf hashes
43
+ payments: dict[int, dict] = field(default_factory=dict)
44
+ recipient_keys: dict[str, dict[str, dict]] = field(default_factory=dict) # rcpt -> cred -> body
45
+ confirmed: dict[int, list[int]] = field(
46
+ default_factory=dict
47
+ ) # payment seq -> confirmation seqs
48
+
49
+ @property
50
+ def root(self) -> bytes:
51
+ return merkle.root_from_leaves(self.leaves)
52
+
53
+ def root_at(self, size: int) -> bytes:
54
+ return merkle.root_from_leaves(self.leaves[:size])
55
+
56
+
57
+ def _b64url_decode(s: str) -> bytes:
58
+ return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
59
+
60
+
61
+ def _key_id(public_key: bytes) -> str:
62
+ return hashlib.sha256(public_key).digest()[:8].hex()
63
+
64
+
65
+ def _origin_hash(origin: str) -> bytes:
66
+ return hashlib.sha256(origin.encode()).digest()
67
+
68
+
69
+ def _ed25519_ok(pub: bytes, msg: bytes, sig: bytes) -> bool:
70
+ try:
71
+ VerifyKey(pub).verify(msg, sig)
72
+ return True
73
+ except (BadSignatureError, ValueError):
74
+ return False
75
+
76
+
77
+ def _root_sig_count(stmt: bytes, root_sigs: list[dict], allowed: list[str]) -> int:
78
+ ok = set()
79
+ for rs in root_sigs:
80
+ k = rs["key"]
81
+ if (
82
+ k in allowed
83
+ and k not in ok
84
+ and _ed25519_ok(bytes.fromhex(k), stmt, bytes.fromhex(rs["sig"]))
85
+ ):
86
+ ok.add(k)
87
+ return len(ok)
88
+
89
+
90
+ def confirmation_challenge(origin: str, entry_hashes: list[bytes]) -> bytes:
91
+ return hashlib.sha256(
92
+ b"vpp:confirm:v1\x00" + _origin_hash(origin) + b"".join(entry_hashes)
93
+ ).digest()
94
+
95
+
96
+ def _no_floats(value, seq: int) -> None:
97
+ if isinstance(value, float):
98
+ raise VerificationError(seq, "envelope contains a float")
99
+ if isinstance(value, int) and not isinstance(value, bool) and abs(value) > MAX_SAFE_INT:
100
+ raise VerificationError(seq, "envelope integer exceeds 2^53-1")
101
+ if isinstance(value, dict):
102
+ for v in value.values():
103
+ _no_floats(v, seq)
104
+ elif isinstance(value, list):
105
+ for v in value:
106
+ _no_floats(v, seq)
107
+
108
+
109
+ def verify_entry(state: ChainState, wire: dict) -> None:
110
+ """Check one wire entry against the state and advance it. Raises VerificationError."""
111
+ seq = wire.get("seq")
112
+ expected_seq = state.seq + 1
113
+ if seq != expected_seq:
114
+ raise VerificationError(seq if isinstance(seq, int) else -1, f"expected seq {expected_seq}")
115
+
116
+ prev_hash = bytes.fromhex(wire["prev_hash"])
117
+ if prev_hash != state.head:
118
+ raise VerificationError(seq, "prev_hash does not match previous entry's hash")
119
+
120
+ envelope = _b64url_decode(wire["envelope"])
121
+ try:
122
+ env = json.loads(envelope)
123
+ except ValueError as e:
124
+ raise VerificationError(seq, f"envelope is not JSON: {e}") from None
125
+ _no_floats(env, seq)
126
+ if rfc8785.dumps(env) != envelope:
127
+ raise VerificationError(seq, "envelope is not RFC 8785 canonical")
128
+ if env.get("v") != 1:
129
+ raise VerificationError(seq, f"unsupported version {env.get('v')!r}")
130
+ if env.get("seq") != seq:
131
+ raise VerificationError(seq, "envelope seq does not match position")
132
+
133
+ computed = hashlib.sha256(DOMAIN + prev_hash + envelope).digest()
134
+ if computed.hex() != wire["hash"]:
135
+ raise VerificationError(seq, "hash mismatch")
136
+
137
+ entry_type = env.get("type")
138
+ body = env.get("body", {})
139
+ try:
140
+ signer = _authority(state, seq, entry_type, body)
141
+ if env.get("key_id") != _key_id(signer):
142
+ raise VerificationError(seq, "key_id is not the authorized key")
143
+ if not _ed25519_ok(signer, computed, bytes.fromhex(wire["sig"])):
144
+ raise VerificationError(seq, "bad signature")
145
+ _check_semantics(state, seq, entry_type, body)
146
+ except (KeyError, TypeError, ValueError) as e:
147
+ raise VerificationError(seq, f"malformed {entry_type} body: {e!r}") from None
148
+
149
+ state.seq = seq
150
+ state.head = computed
151
+ state.hashes[seq] = computed
152
+ state.leaves.append(merkle.leaf_hash(computed))
153
+ state.signer_at[seq] = signer
154
+ state.used_online_keys.add(signer)
155
+
156
+
157
+ def _authority(state: ChainState, seq: int, entry_type: str, body: dict) -> bytes:
158
+ """Return the key that must have signed this entry, applying key changes (LEDGER_SPEC §5)."""
159
+ if seq == 1:
160
+ if entry_type != "genesis":
161
+ raise VerificationError(seq, "first entry must be genesis")
162
+ keys, thr = body["root_keys"], body["root_threshold"]
163
+ if len(set(keys)) != len(keys) or not 1 <= thr <= len(keys):
164
+ raise VerificationError(seq, "invalid root key set")
165
+ online = bytes.fromhex(body["online_key"])
166
+ stmt = b"vpp:genesis:v1\x00" + _origin_hash(body["origin"]) + online
167
+ if _root_sig_count(stmt, body["root_sigs"], keys) < thr:
168
+ raise VerificationError(seq, "genesis lacks root-key threshold")
169
+ state.origin, state.online_key = body["origin"], online
170
+ state.root_keys, state.root_threshold = keys, thr
171
+ state.used_root_sets.add((tuple(sorted(keys)), thr))
172
+ return online
173
+ if entry_type == "genesis":
174
+ raise VerificationError(seq, "genesis after seq 1")
175
+
176
+ if entry_type == "key_rotation":
177
+ new = bytes.fromhex(body["new_online_key"])
178
+ if bytes.fromhex(body["from_online_key"]) != state.online_key:
179
+ raise VerificationError(seq, "rotation does not replace the active key")
180
+ if new in state.used_online_keys:
181
+ raise VerificationError(seq, "online key reused")
182
+ stmt = b"vpp:rotate:v1\x00" + _origin_hash(state.origin) + state.online_key + new
183
+ if _root_sig_count(stmt, body["root_sigs"], state.root_keys) < state.root_threshold:
184
+ raise VerificationError(seq, "rotation lacks root-key threshold")
185
+ state.online_key = new
186
+ return new # signed by the new key
187
+
188
+ if entry_type == "root_rotation":
189
+ keys, thr = body["new_root_keys"], body["new_root_threshold"]
190
+ if len(set(keys)) != len(keys) or not 1 <= thr <= len(keys):
191
+ raise VerificationError(seq, "invalid new root key set")
192
+ if (tuple(sorted(keys)), thr) in state.used_root_sets:
193
+ raise VerificationError(seq, "root key set reused")
194
+ sets = {
195
+ "from": {"keys": sorted(state.root_keys), "threshold": state.root_threshold},
196
+ "to": {"keys": sorted(keys), "threshold": thr},
197
+ }
198
+ stmt = b"vpp:root-rotate:v1\x00" + _origin_hash(state.origin) + rfc8785.dumps(sets)
199
+ if _root_sig_count(stmt, body["root_sigs"], state.root_keys) < state.root_threshold:
200
+ raise VerificationError(seq, "root rotation lacks old root threshold")
201
+ state.root_keys, state.root_threshold = keys, thr
202
+ state.used_root_sets.add((tuple(sorted(keys)), thr))
203
+ return state.online_key
204
+
205
+
206
+ def _check_semantics(state: ChainState, seq: int, entry_type: str, body: dict) -> None:
207
+ if entry_type == "payment":
208
+ amt = body["amount"]
209
+ state.payments[seq] = {
210
+ "currency": amt["currency"],
211
+ "value": amt["value"],
212
+ "reversed": 0,
213
+ "recipient": body["recipient"],
214
+ }
215
+ elif entry_type == "reversal":
216
+ ref = state.payments.get(body["ref_seq"])
217
+ if ref is None:
218
+ raise VerificationError(seq, "reversal does not reference an earlier payment")
219
+ if body["amount"]["currency"] != ref["currency"]:
220
+ raise VerificationError(seq, "reversal currency differs from payment")
221
+ ref["reversed"] += body["amount"]["value"]
222
+ if ref["reversed"] > ref["value"]:
223
+ raise VerificationError(seq, "reversals exceed payment amount")
224
+ elif entry_type == "correction":
225
+ if not 1 <= body["ref_seq"] < seq:
226
+ raise VerificationError(seq, "correction must reference an earlier entry")
227
+ elif entry_type == "recipient_key":
228
+ spki = b64url_decode(body["public_key_spki"])
229
+ try:
230
+ load_key(spki, body["alg"])
231
+ except (WebAuthnError, ValueError) as e:
232
+ raise VerificationError(seq, f"recipient key unusable: {e}") from None
233
+ if body["fingerprint"] != fingerprint(spki):
234
+ raise VerificationError(seq, "recipient key fingerprint mismatch")
235
+ state.recipient_keys.setdefault(body["recipient"], {})[body["credential_id"]] = body
236
+ elif entry_type == "confirmation":
237
+ _check_confirmation(state, seq, body)
238
+ elif entry_type not in ("genesis", "key_rotation", "root_rotation"):
239
+ raise VerificationError(seq, f"unknown entry type {entry_type!r}")
240
+
241
+
242
+ def _check_confirmation(state: ChainState, seq: int, body: dict) -> None:
243
+ rcpt = body["recipient"]
244
+ key = state.recipient_keys.get(rcpt, {}).get(body["credential_id"])
245
+ if key is None:
246
+ raise VerificationError(seq, "confirmation by an unregistered recipient key")
247
+ refs = body["ref_seqs"]
248
+ if not refs or len(set(refs)) != len(refs):
249
+ raise VerificationError(seq, "confirmation needs distinct ref_seqs")
250
+ for r in refs:
251
+ p = state.payments.get(r)
252
+ if p is None or p["recipient"] != rcpt:
253
+ raise VerificationError(seq, f"seq {r} is not a payment to {rcpt}")
254
+ challenge = confirmation_challenge(state.origin, [state.hashes[r] for r in refs])
255
+ try:
256
+ verify_assertion(
257
+ spki_der=b64url_decode(key["public_key_spki"]),
258
+ alg=key["alg"],
259
+ rp_id=key["rp_id"],
260
+ origin=key["origin"],
261
+ challenge=challenge,
262
+ authenticator_data=b64url_decode(body["authenticator_data"]),
263
+ client_data_json=b64url_decode(body["client_data_json"]),
264
+ signature=b64url_decode(body["signature"]),
265
+ )
266
+ except WebAuthnError as e:
267
+ raise VerificationError(seq, f"confirmation assertion invalid: {e}") from None
268
+ for r in refs:
269
+ state.confirmed.setdefault(r, []).append(seq)
270
+
271
+
272
+ def verify_chain(entries: list[dict], *, pinned_genesis: bytes | None = None) -> ChainState:
273
+ state = ChainState()
274
+ for wire in entries:
275
+ verify_entry(state, wire)
276
+ if state.seq == 1 and pinned_genesis is not None and state.head != pinned_genesis:
277
+ raise VerificationError(1, "genesis hash does not match the pinned value")
278
+ return state
279
+
280
+
281
+ def checkpoint_key(state: ChainState, size: int) -> bytes:
282
+ """The online key that signed the checkpoint for `size` (the signer of entry `size`)."""
283
+ if size not in state.signer_at:
284
+ raise VerificationError(size, "checkpoint beyond verified entries")
285
+ return state.signer_at[size]
286
+
287
+
288
+ def verify_commitment(commitment: str, value: str, salt: bytes) -> bool:
289
+ return commitment == "c1:" + hashlib.sha256(salt + value.encode()).hexdigest()
vpp_verify/merkle.py ADDED
@@ -0,0 +1,91 @@
1
+ """RFC 6962 / RFC 9162 Merkle tree verification. Written from the RFCs, not from `vpp`."""
2
+
3
+ import hashlib
4
+
5
+ EMPTY_ROOT = hashlib.sha256(b"").digest()
6
+
7
+
8
+ def leaf_hash(data: bytes) -> bytes:
9
+ return hashlib.sha256(b"\x00" + data).digest()
10
+
11
+
12
+ def node_hash(left: bytes, right: bytes) -> bytes:
13
+ return hashlib.sha256(b"\x01" + left + right).digest()
14
+
15
+
16
+ def root_from_leaves(leaves: list[bytes]) -> bytes:
17
+ """MTH over leaf *hashes* (already 0x00-prefixed and hashed). O(n), for verifiers that hold
18
+ every entry anyway."""
19
+ if not leaves:
20
+ return EMPTY_ROOT
21
+ # Stack of (height, hash) for perfect subtrees, merged right to left at the end.
22
+ stack: list[tuple[int, bytes]] = []
23
+ for h in leaves:
24
+ height, cur = 0, h
25
+ while stack and stack[-1][0] == height:
26
+ _, left = stack.pop()
27
+ cur = node_hash(left, cur)
28
+ height += 1
29
+ stack.append((height, cur))
30
+ _, acc = stack.pop()
31
+ while stack:
32
+ _, left = stack.pop()
33
+ acc = node_hash(left, acc)
34
+ return acc
35
+
36
+
37
+ def verify_inclusion(leaf: bytes, index: int, size: int, proof: list[bytes], root: bytes) -> bool:
38
+ """RFC 9162 §2.1.3.2. `leaf` is the leaf hash."""
39
+ if index >= size or index < 0:
40
+ return False
41
+ fn, sn, r = index, size - 1, leaf
42
+ for p in proof:
43
+ if sn == 0:
44
+ return False
45
+ if fn & 1 or fn == sn:
46
+ r = node_hash(p, r)
47
+ if not fn & 1:
48
+ while not fn & 1 and fn != 0:
49
+ fn >>= 1
50
+ sn >>= 1
51
+ else:
52
+ r = node_hash(r, p)
53
+ fn >>= 1
54
+ sn >>= 1
55
+ return sn == 0 and r == root
56
+
57
+
58
+ def verify_consistency(
59
+ size1: int, size2: int, root1: bytes, root2: bytes, proof: list[bytes]
60
+ ) -> bool:
61
+ """RFC 9162 §2.1.4.2, plus the trivial cases tlog-witness spells out."""
62
+ if size1 < 0 or size1 > size2:
63
+ return False
64
+ if size1 == size2:
65
+ return not proof and root1 == root2
66
+ if size1 == 0:
67
+ return not proof
68
+ if not proof:
69
+ return False
70
+ if size1 & (size1 - 1) == 0: # exact power of two: old root is the first node
71
+ proof = [root1, *proof]
72
+ fn, sn = size1 - 1, size2 - 1
73
+ while fn & 1:
74
+ fn >>= 1
75
+ sn >>= 1
76
+ fr = sr = proof[0]
77
+ for c in proof[1:]:
78
+ if sn == 0:
79
+ return False
80
+ if fn & 1 or fn == sn:
81
+ fr = node_hash(c, fr)
82
+ sr = node_hash(c, sr)
83
+ if not fn & 1:
84
+ while not fn & 1 and fn != 0:
85
+ fn >>= 1
86
+ sn >>= 1
87
+ else:
88
+ sr = node_hash(sr, c)
89
+ fn >>= 1
90
+ sn >>= 1
91
+ return fr == root1 and sr == root2 and sn == 0
vpp_verify/note.py ADDED
@@ -0,0 +1,206 @@
1
+ """C2SP signed-note, tlog-checkpoint and tlog-cosignature (Ed25519) verification.
2
+
3
+ Specs: https://c2sp.org/signed-note, /tlog-checkpoint, /tlog-cosignature. Written from them,
4
+ not from `vpp`.
5
+ """
6
+
7
+ import base64
8
+ import binascii
9
+ import hashlib
10
+ import struct
11
+ from dataclasses import dataclass
12
+
13
+ from nacl.exceptions import BadSignatureError
14
+ from nacl.signing import VerifyKey
15
+
16
+ EM_DASH = "—"
17
+ SIG_ED25519 = 0x01
18
+ SIG_COSIGNATURE_ED25519 = 0x04
19
+
20
+
21
+ class NoteError(ValueError):
22
+ pass
23
+
24
+
25
+ def b64decode_canonical(s: str) -> bytes:
26
+ try:
27
+ raw = base64.b64decode(s, validate=True)
28
+ except (binascii.Error, ValueError):
29
+ raise NoteError(f"invalid base64: {s[:20]}") from None
30
+ if base64.b64encode(raw).decode() != s:
31
+ raise NoteError("non-canonical base64")
32
+ return raw
33
+
34
+
35
+ def key_id(name: str, sig_type: int, public_key: bytes) -> bytes:
36
+ return hashlib.sha256(name.encode() + b"\n" + bytes([sig_type]) + public_key).digest()[:4]
37
+
38
+
39
+ def check_name(name: str) -> None:
40
+ if not name or len(name.encode()) > 255 or "+" in name:
41
+ raise NoteError(f"invalid key name {name!r}")
42
+ if any(c.isspace() or ord(c) < 0x20 for c in name):
43
+ raise NoteError(f"invalid key name {name!r}")
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class Verifier:
48
+ """A verifier key: `<name>+<hex key id>+<base64(type || pubkey)>`."""
49
+
50
+ name: str
51
+ sig_type: int
52
+ public_key: bytes
53
+
54
+ @property
55
+ def key_id(self) -> bytes:
56
+ return key_id(self.name, self.sig_type, self.public_key)
57
+
58
+ @classmethod
59
+ def parse(cls, vkey: str) -> "Verifier":
60
+ try:
61
+ # Names can't contain '+', but base64 can: only the first two '+' are separators.
62
+ name, hex_id, b64 = vkey.split("+", 2)
63
+ except ValueError:
64
+ raise NoteError("vkey must be name+id+key") from None
65
+ check_name(name)
66
+ raw = b64decode_canonical(b64)
67
+ if len(raw) != 33 or raw[0] not in (SIG_ED25519, SIG_COSIGNATURE_ED25519):
68
+ raise NoteError("only Ed25519 (0x01) and Ed25519 cosignature (0x04) keys supported")
69
+ v = cls(name, raw[0], raw[1:])
70
+ if v.key_id.hex() != hex_id:
71
+ raise NoteError("vkey id does not match key")
72
+ return v
73
+
74
+ def __str__(self) -> str:
75
+ b64 = base64.b64encode(bytes([self.sig_type]) + self.public_key).decode()
76
+ return f"{self.name}+{self.key_id.hex()}+{b64}"
77
+
78
+
79
+ @dataclass(frozen=True)
80
+ class Signature:
81
+ name: str
82
+ key_id: bytes
83
+ sig: bytes # everything after the 4-byte key id
84
+
85
+ @property
86
+ def line(self) -> str:
87
+ return f"{EM_DASH} {self.name} {base64.b64encode(self.key_id + self.sig).decode()}\n"
88
+
89
+
90
+ @dataclass(frozen=True)
91
+ class Note:
92
+ text: str # includes its final newline
93
+ signatures: tuple[Signature, ...]
94
+
95
+ @classmethod
96
+ def parse(cls, raw: str) -> "Note":
97
+ if len(raw) > 1_000_000:
98
+ raise NoteError("note too large")
99
+ if any(ord(c) < 0x20 and c != "\n" for c in raw):
100
+ raise NoteError("control character in note")
101
+ idx = raw.rfind("\n\n")
102
+ if idx < 0:
103
+ raise NoteError("missing signature separator")
104
+ text, sig_block = raw[: idx + 1], raw[idx + 2 :]
105
+ if not sig_block.endswith("\n"):
106
+ raise NoteError("signature block must end with newline")
107
+ sigs = []
108
+ for line in sig_block[:-1].split("\n"):
109
+ if not line.startswith(EM_DASH + " "):
110
+ raise NoteError(f"bad signature line {line[:40]!r}")
111
+ try:
112
+ name, b64 = line[2:].split(" ")
113
+ except ValueError:
114
+ raise NoteError("bad signature line") from None
115
+ check_name(name)
116
+ blob = b64decode_canonical(b64)
117
+ if len(blob) < 5:
118
+ raise NoteError("signature too short")
119
+ sigs.append(Signature(name, blob[:4], blob[4:]))
120
+ if not sigs:
121
+ raise NoteError("note has no signatures")
122
+ if len(sigs) > 64:
123
+ raise NoteError("too many signatures")
124
+ return cls(text, tuple(sigs))
125
+
126
+ def __str__(self) -> str:
127
+ return self.text + "\n" + "".join(s.line for s in self.signatures)
128
+
129
+ def find(self, v: Verifier) -> Signature | None:
130
+ for s in self.signatures:
131
+ if s.name == v.name and s.key_id == v.key_id:
132
+ return s
133
+ return None
134
+
135
+
136
+ def _ed25519_ok(public_key: bytes, msg: bytes, sig: bytes) -> bool:
137
+ try:
138
+ VerifyKey(public_key).verify(msg, sig)
139
+ return True
140
+ except (BadSignatureError, ValueError):
141
+ return False
142
+
143
+
144
+ def verify_note_signature(note: Note, v: Verifier) -> bool:
145
+ """True if `v` signed the note (type 0x01). A matching but invalid signature raises."""
146
+ if v.sig_type != SIG_ED25519:
147
+ raise NoteError("not a note-signing key")
148
+ s = note.find(v)
149
+ if s is None:
150
+ return False
151
+ if len(s.sig) != 64 or not _ed25519_ok(v.public_key, note.text.encode(), s.sig):
152
+ raise NoteError(f"invalid signature from {v.name}")
153
+ return True
154
+
155
+
156
+ @dataclass(frozen=True)
157
+ class Checkpoint:
158
+ origin: str
159
+ size: int
160
+ root: bytes
161
+ extensions: tuple[str, ...] = ()
162
+
163
+ @classmethod
164
+ def parse(cls, text: str) -> "Checkpoint":
165
+ if not text.endswith("\n"):
166
+ raise NoteError("checkpoint must end with newline")
167
+ lines = text[:-1].split("\n")
168
+ if len(lines) < 3 or any(not ln for ln in lines):
169
+ raise NoteError("checkpoint needs origin, size, root")
170
+ origin, size_s, root_b64, *ext = lines
171
+ check_name(origin)
172
+ if not size_s.isdigit() or (size_s != "0" and size_s.startswith("0")):
173
+ raise NoteError("bad tree size")
174
+ root = b64decode_canonical(root_b64)
175
+ if len(root) != 32:
176
+ raise NoteError("root must be 32 bytes")
177
+ return cls(origin, int(size_s), root, tuple(ext))
178
+
179
+ @property
180
+ def text(self) -> str:
181
+ lines = [
182
+ self.origin,
183
+ str(self.size),
184
+ base64.b64encode(self.root).decode(),
185
+ *self.extensions,
186
+ ]
187
+ return "\n".join(lines) + "\n"
188
+
189
+
190
+ def cosignature_message(checkpoint_text: str, timestamp: int) -> bytes:
191
+ return f"cosignature/v1\ntime {timestamp}\n".encode() + checkpoint_text.encode()
192
+
193
+
194
+ def verify_cosignature(note: Note, v: Verifier) -> int | None:
195
+ """Returns the cosignature timestamp if `v` cosigned this checkpoint (type 0x04)."""
196
+ if v.sig_type != SIG_COSIGNATURE_ED25519:
197
+ raise NoteError("not a cosigner key")
198
+ s = note.find(v)
199
+ if s is None:
200
+ return None
201
+ if len(s.sig) != 8 + 64:
202
+ raise NoteError(f"bad cosignature length from {v.name}")
203
+ (ts,) = struct.unpack(">Q", s.sig[:8])
204
+ if not _ed25519_ok(v.public_key, cosignature_message(note.text, ts), s.sig[8:]):
205
+ raise NoteError(f"invalid cosignature from {v.name}")
206
+ return ts
vpp_verify/webauthn.py ADDED
@@ -0,0 +1,85 @@
1
+ """WebAuthn assertion verification (W3C WebAuthn L2 §7.2, steps relevant to a third party)."""
2
+
3
+ import base64
4
+ import hashlib
5
+ import json
6
+
7
+ from cryptography.exceptions import InvalidSignature
8
+ from cryptography.hazmat.primitives import hashes
9
+ from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa
10
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
11
+ from cryptography.hazmat.primitives.serialization import load_der_public_key
12
+
13
+ FLAG_UP = 0x01 # user present
14
+ FLAG_UV = 0x04 # user verified
15
+
16
+
17
+ class WebAuthnError(ValueError):
18
+ pass
19
+
20
+
21
+ def b64url(data: bytes) -> str:
22
+ return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
23
+
24
+
25
+ def b64url_decode(s: str) -> bytes:
26
+ return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
27
+
28
+
29
+ def fingerprint(spki_der: bytes) -> str:
30
+ return "k1:" + hashlib.sha256(spki_der).hexdigest()
31
+
32
+
33
+ def load_key(spki_der: bytes, alg: int):
34
+ key = load_der_public_key(spki_der)
35
+ expected = {-7: ec.EllipticCurvePublicKey, -8: Ed25519PublicKey, -257: rsa.RSAPublicKey}
36
+ if alg not in expected or not isinstance(key, expected[alg]):
37
+ raise WebAuthnError(f"key type does not match alg {alg}")
38
+ if alg == -7 and not isinstance(key.curve, ec.SECP256R1):
39
+ raise WebAuthnError("ES256 requires P-256")
40
+ return key
41
+
42
+
43
+ def verify_assertion(
44
+ *,
45
+ spki_der: bytes,
46
+ alg: int,
47
+ rp_id: str,
48
+ origin: str,
49
+ challenge: bytes,
50
+ authenticator_data: bytes,
51
+ client_data_json: bytes,
52
+ signature: bytes,
53
+ ) -> None:
54
+ try:
55
+ cd = json.loads(client_data_json)
56
+ except ValueError:
57
+ raise WebAuthnError("clientDataJSON is not JSON") from None
58
+ if cd.get("type") != "webauthn.get":
59
+ raise WebAuthnError("not an assertion")
60
+ if cd.get("challenge") != b64url(challenge):
61
+ raise WebAuthnError("challenge mismatch")
62
+ if cd.get("origin") != origin:
63
+ raise WebAuthnError(f"origin mismatch: {cd.get('origin')!r}")
64
+ if cd.get("crossOrigin") is True:
65
+ raise WebAuthnError("cross-origin assertion")
66
+
67
+ if len(authenticator_data) < 37:
68
+ raise WebAuthnError("authenticatorData too short")
69
+ if authenticator_data[:32] != hashlib.sha256(rp_id.encode()).digest():
70
+ raise WebAuthnError("rpIdHash mismatch")
71
+ flags = authenticator_data[32]
72
+ if not flags & FLAG_UP or not flags & FLAG_UV:
73
+ raise WebAuthnError("user presence and verification are required")
74
+
75
+ msg = authenticator_data + hashlib.sha256(client_data_json).digest()
76
+ key = load_key(spki_der, alg)
77
+ try:
78
+ if alg == -7:
79
+ key.verify(signature, msg, ec.ECDSA(hashes.SHA256()))
80
+ elif alg == -8:
81
+ key.verify(signature, msg)
82
+ else:
83
+ key.verify(signature, msg, padding.PKCS1v15(), hashes.SHA256())
84
+ except InvalidSignature:
85
+ raise WebAuthnError("bad assertion signature") from None