touchstone-verify 0.3.2__tar.gz

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,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.
@@ -0,0 +1,81 @@
1
+ Metadata-Version: 2.4
2
+ Name: touchstone-verify
3
+ Version: 0.3.2
4
+ Summary: Independently verify a Touchstone disclosure — zero dependencies, pure Python.
5
+ Author: Touchstone
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://touchstone.cv
8
+ Project-URL: Source, https://github.com/Touchstone-CV/touchstone-verify
9
+ Keywords: touchstone,audit-log,verifier,ed25519,tamper-evident,provenance
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Security :: Cryptography
13
+ Requires-Python: >=3.8
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Dynamic: license-file
17
+
18
+ # touchstone-verify
19
+
20
+ Independently verify a **[Touchstone](https://touchstone.cv)** disclosure — in pure Python,
21
+ with **zero dependencies**. Read it before you trust it: it's a small, self-contained file.
22
+
23
+ A disclosure is a tamper-evident slice of an agent's action log. This package re-derives,
24
+ with no trust in Touchstone, that the slice is **intact** (entry hashes recompute), **attributed**
25
+ (the subject's Ed25519 signature holds, epoch-aware across key rotation), and **ordered**
26
+ (hash-chained, with checkpoints that are append-only, server-signed, and witness-co-signed). It
27
+ also checks **selective-disclosure** field proofs and reports the external anchors. It proves
28
+ tampering by anyone who is not Touchstone — it does **not** prove completeness, and says so.
29
+
30
+ It agrees byte-for-byte with the other two Touchstone verifiers (`verify.php`, `verifier.js`):
31
+ all three are tested against the same conformance corpus.
32
+
33
+ ## Install
34
+
35
+ ```bash
36
+ pip install touchstone-verify
37
+ ```
38
+
39
+ ## Use
40
+
41
+ Command line — pass a file, a URL, or a disclosure token:
42
+
43
+ ```bash
44
+ touchstone-verify https://touchstone.cv/d/833cd4ca23fbb940dd71843ca47a807e
45
+ touchstone-verify ./bundle.json
46
+ touchstone-verify 833cd4ca23fbb940dd71843ca47a807e # fetches from touchstone.cv
47
+ ```
48
+
49
+ Exit code `0` = verified, `1` = a load-bearing check failed, `2` = couldn't load.
50
+
51
+ Library:
52
+
53
+ ```python
54
+ from touchstone_verify import verify_disclosure
55
+ import json, urllib.request
56
+
57
+ bundle = json.load(urllib.request.urlopen("https://touchstone.cv/d/<token>"))
58
+ result = verify_disclosure(bundle)
59
+ print(result["ok"]) # True / False
60
+ for e in result["entries"]:
61
+ for c in e["checks"]:
62
+ print(c["ok"], c["msg"])
63
+ ```
64
+
65
+ ## What it checks
66
+
67
+ - **Integrity** — every `entry_hash` recomputes from its fields.
68
+ - **Attribution** — the subject signature verifies over the canonical signed content; genesis
69
+ proof-of-possession; `key_rotation` new-key PoP; counterparty co-signatures.
70
+ - **Ordering** — `prev_hash` chain linkage; Merkle inclusion in the cited checkpoint.
71
+ - **Checkpoints** — server signature over each Merkle root; append-only linkage between
72
+ consecutive checkpoints; independent witness co-signatures.
73
+ - **Selective disclosure** — each revealed field proves Merkle inclusion in `payload_hash`;
74
+ withheld fields never appear in the bundle.
75
+
76
+ For split-view / Bitcoin-anchor cross-checking across independent relays, see the companion
77
+ `gossip_check.py` at <https://touchstone.cv/gossip_check.py>.
78
+
79
+ ## License
80
+
81
+ [Apache-2.0](./LICENSE).
@@ -0,0 +1,64 @@
1
+ # touchstone-verify
2
+
3
+ Independently verify a **[Touchstone](https://touchstone.cv)** disclosure — in pure Python,
4
+ with **zero dependencies**. Read it before you trust it: it's a small, self-contained file.
5
+
6
+ A disclosure is a tamper-evident slice of an agent's action log. This package re-derives,
7
+ with no trust in Touchstone, that the slice is **intact** (entry hashes recompute), **attributed**
8
+ (the subject's Ed25519 signature holds, epoch-aware across key rotation), and **ordered**
9
+ (hash-chained, with checkpoints that are append-only, server-signed, and witness-co-signed). It
10
+ also checks **selective-disclosure** field proofs and reports the external anchors. It proves
11
+ tampering by anyone who is not Touchstone — it does **not** prove completeness, and says so.
12
+
13
+ It agrees byte-for-byte with the other two Touchstone verifiers (`verify.php`, `verifier.js`):
14
+ all three are tested against the same conformance corpus.
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ pip install touchstone-verify
20
+ ```
21
+
22
+ ## Use
23
+
24
+ Command line — pass a file, a URL, or a disclosure token:
25
+
26
+ ```bash
27
+ touchstone-verify https://touchstone.cv/d/833cd4ca23fbb940dd71843ca47a807e
28
+ touchstone-verify ./bundle.json
29
+ touchstone-verify 833cd4ca23fbb940dd71843ca47a807e # fetches from touchstone.cv
30
+ ```
31
+
32
+ Exit code `0` = verified, `1` = a load-bearing check failed, `2` = couldn't load.
33
+
34
+ Library:
35
+
36
+ ```python
37
+ from touchstone_verify import verify_disclosure
38
+ import json, urllib.request
39
+
40
+ bundle = json.load(urllib.request.urlopen("https://touchstone.cv/d/<token>"))
41
+ result = verify_disclosure(bundle)
42
+ print(result["ok"]) # True / False
43
+ for e in result["entries"]:
44
+ for c in e["checks"]:
45
+ print(c["ok"], c["msg"])
46
+ ```
47
+
48
+ ## What it checks
49
+
50
+ - **Integrity** — every `entry_hash` recomputes from its fields.
51
+ - **Attribution** — the subject signature verifies over the canonical signed content; genesis
52
+ proof-of-possession; `key_rotation` new-key PoP; counterparty co-signatures.
53
+ - **Ordering** — `prev_hash` chain linkage; Merkle inclusion in the cited checkpoint.
54
+ - **Checkpoints** — server signature over each Merkle root; append-only linkage between
55
+ consecutive checkpoints; independent witness co-signatures.
56
+ - **Selective disclosure** — each revealed field proves Merkle inclusion in `payload_hash`;
57
+ withheld fields never appear in the bundle.
58
+
59
+ For split-view / Bitcoin-anchor cross-checking across independent relays, see the companion
60
+ `gossip_check.py` at <https://touchstone.cv/gossip_check.py>.
61
+
62
+ ## License
63
+
64
+ [Apache-2.0](./LICENSE).
@@ -0,0 +1,28 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "touchstone-verify"
7
+ version = "0.3.2"
8
+ description = "Independently verify a Touchstone disclosure — zero dependencies, pure Python."
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = { text = "Apache-2.0" }
12
+ authors = [{ name = "Touchstone" }]
13
+ keywords = ["touchstone", "audit-log", "verifier", "ed25519", "tamper-evident", "provenance"]
14
+ classifiers = [
15
+ "License :: OSI Approved :: Apache Software License",
16
+ "Programming Language :: Python :: 3",
17
+ "Topic :: Security :: Cryptography",
18
+ ]
19
+
20
+ [project.urls]
21
+ Homepage = "https://touchstone.cv"
22
+ Source = "https://github.com/Touchstone-CV/touchstone-verify"
23
+
24
+ [project.scripts]
25
+ touchstone-verify = "touchstone_verify.__main__:main"
26
+
27
+ [tool.setuptools.packages.find]
28
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,9 @@
1
+ """touchstone-verify — independently verify a Touchstone disclosure, zero dependencies.
2
+
3
+ from touchstone_verify import verify_disclosure
4
+ result = verify_disclosure(bundle_dict) # {"ok": True/False, "entries": [...], ...}
5
+ """
6
+ from .verify import jcs, verify_disclosure
7
+
8
+ __all__ = ["verify_disclosure", "jcs"]
9
+ __version__ = "0.3.2"
@@ -0,0 +1,74 @@
1
+ """CLI: python -m touchstone_verify <disclosure.json | /d/<token> | <token> | URL>
2
+
3
+ Reads a bundle from a file, a https URL, or a Touchstone disclosure token (fetched
4
+ from --base, default https://touchstone.cv), verifies it, and prints PASS/FAIL.
5
+ Exit 0 = verified, 1 = failed, 2 = could not load.
6
+ """
7
+ import json
8
+ import re
9
+ import sys
10
+ import urllib.request
11
+
12
+ from .verify import verify_disclosure
13
+
14
+ GREEN, RED, DIM, RST = "\033[32m", "\033[31m", "\033[2m", "\033[0m"
15
+
16
+
17
+ def _load(arg: str, base: str) -> dict:
18
+ if arg.startswith("http://") or arg.startswith("https://"):
19
+ with urllib.request.urlopen(arg, timeout=15) as r:
20
+ return json.load(r)
21
+ try:
22
+ with open(arg, encoding="utf-8") as fh:
23
+ return json.load(fh)
24
+ except (FileNotFoundError, OSError):
25
+ token = arg.rsplit("/", 1)[-1]
26
+ if not re.match(r"^[0-9a-f]{8,64}$", token):
27
+ raise SystemExit(f"not a file, URL, or disclosure token: {arg}")
28
+ with urllib.request.urlopen(f"{base}/d/{token}", timeout=15) as r:
29
+ return json.load(r)
30
+
31
+
32
+ def main(argv=None) -> int:
33
+ argv = list(sys.argv[1:] if argv is None else argv)
34
+ base = "https://touchstone.cv"
35
+ if "--base" in argv:
36
+ i = argv.index("--base")
37
+ base = argv[i + 1].rstrip("/")
38
+ del argv[i:i + 2]
39
+ if not argv:
40
+ print("usage: python -m touchstone_verify <file|url|token> [--base URL]", file=sys.stderr)
41
+ return 2
42
+
43
+ try:
44
+ bundle = _load(argv[0], base)
45
+ except Exception as e: # noqa: BLE001
46
+ print(f"could not load: {e}", file=sys.stderr)
47
+ return 2
48
+
49
+ res = verify_disclosure(bundle)
50
+ if not res.get("format_ok"):
51
+ print(f"{RED}NOT A DISCLOSURE{RST}: {res.get('error')}")
52
+ return 2
53
+
54
+ print(f"recorder {res['recorder']} subject {res.get('subject')} tier {res.get('tier')}\n")
55
+ for c in res.get("checkpoints", []):
56
+ mark = GREEN + "✓" + RST if c["ok"] else (RED + "✗" + RST)
57
+ print(f" [{mark}] {c['msg']}")
58
+ for e in res["entries"]:
59
+ print(f" seq {e['seq']} ({e['type']}){' [redacted]' if e['redacted'] else ''}:")
60
+ for c in e["checks"]:
61
+ mark = GREEN + "✓" + RST if c["ok"] else (RED + "✗" + RST)
62
+ tail = "" if c["fatal"] else f" {DIM}(info){RST}"
63
+ print(f" [{mark}] {c['msg']}{tail}")
64
+
65
+ print("")
66
+ if res["ok"]:
67
+ print(f"{GREEN}PASS{RST} — integrity, attribution and ordering hold (not completeness).")
68
+ return 0
69
+ print(f"{RED}FAIL{RST} — a load-bearing check did not hold.")
70
+ return 1
71
+
72
+
73
+ if __name__ == "__main__":
74
+ raise SystemExit(main())
@@ -0,0 +1,102 @@
1
+ """Pure-Python Ed25519 signature verification (RFC 8032 reference).
2
+
3
+ Vendored so the verifier has zero dependencies — an auditor reads this file rather
4
+ than trusting a compiled crypto library. Verify-only; no signing, no secret handling.
5
+ """
6
+ import hashlib
7
+
8
+ _p = 2**255 - 19
9
+ _L = 2**252 + 27742317777372353535851937790883648493
10
+ _d = (-121665 * pow(121666, _p - 2, _p)) % _p
11
+ _I = pow(2, (_p - 1) // 4, _p)
12
+
13
+
14
+ def _sha512(b: bytes) -> bytes:
15
+ return hashlib.sha512(b).digest()
16
+
17
+
18
+ def _inv(x: int) -> int:
19
+ return pow(x, _p - 2, _p)
20
+
21
+
22
+ def _x_recover(y: int) -> int:
23
+ xx = (y * y - 1) * _inv(_d * y * y + 1)
24
+ x = pow(xx, (_p + 3) // 8, _p)
25
+ if (x * x - xx) % _p != 0:
26
+ x = (x * _I) % _p
27
+ if x % 2 != 0:
28
+ x = _p - x
29
+ return x
30
+
31
+
32
+ _By = (4 * _inv(5)) % _p
33
+ _Bx = _x_recover(_By)
34
+ _B = (_Bx % _p, _By % _p, 1, (_Bx * _By) % _p) # extended coords (X, Y, Z, T)
35
+
36
+
37
+ def _edwards_add(P, Q):
38
+ x1, y1, z1, t1 = P
39
+ x2, y2, z2, t2 = Q
40
+ a = ((y1 - x1) * (y2 - x2)) % _p
41
+ b = ((y1 + x1) * (y2 + x2)) % _p
42
+ c = (t1 * 2 * _d * t2) % _p
43
+ dd = (z1 * 2 * z2) % _p
44
+ e, f, g, h = b - a, dd - c, dd + c, b + a
45
+ return ((e * f) % _p, (g * h) % _p, (f * g) % _p, (e * h) % _p)
46
+
47
+
48
+ def _scalarmult(P, e: int):
49
+ if e == 0:
50
+ return (0, 1, 1, 0)
51
+ Q = _scalarmult(P, e // 2)
52
+ Q = _edwards_add(Q, Q)
53
+ if e & 1:
54
+ Q = _edwards_add(Q, P)
55
+ return Q
56
+
57
+
58
+ def _encode_point(P) -> bytes:
59
+ x, y, z, _ = P
60
+ zi = _inv(z)
61
+ x = (x * zi) % _p
62
+ y = (y * zi) % _p
63
+ val = y | ((x & 1) << 255)
64
+ return val.to_bytes(32, "little")
65
+
66
+
67
+ def _decode_point(s: bytes):
68
+ y = int.from_bytes(s, "little") & ((1 << 255) - 1)
69
+ x = _x_recover(y)
70
+ if x & 1 != (int.from_bytes(s, "little") >> 255) & 1:
71
+ x = _p - x
72
+ P = (x % _p, y % _p, 1, (x * y) % _p)
73
+ if not _on_curve(P):
74
+ raise ValueError("point not on curve")
75
+ return P
76
+
77
+
78
+ def _on_curve(P) -> bool:
79
+ x, y, z, t = P
80
+ zi = _inv(z)
81
+ x = (x * zi) % _p
82
+ y = (y * zi) % _p
83
+ return (-x * x + y * y - 1 - _d * x * x * y * y) % _p == 0
84
+
85
+
86
+ def verify(public_key: bytes, message: bytes, signature: bytes) -> bool:
87
+ """True iff `signature` (64 bytes) is a valid Ed25519 signature of `message`
88
+ under `public_key` (32 bytes)."""
89
+ if len(public_key) != 32 or len(signature) != 64:
90
+ return False
91
+ try:
92
+ A = _decode_point(public_key)
93
+ R = signature[:32]
94
+ s = int.from_bytes(signature[32:], "little")
95
+ if s >= _L:
96
+ return False
97
+ h = int.from_bytes(_sha512(R + public_key + message), "little") % _L
98
+ left = _scalarmult(_B, s)
99
+ right = _edwards_add(_decode_point(R), _scalarmult(A, h))
100
+ return _encode_point(left) == _encode_point(right)
101
+ except Exception:
102
+ return False
@@ -0,0 +1,318 @@
1
+ """Verify a Touchstone disclosure bundle — independently, with zero dependencies.
2
+
3
+ A faithful port of verifier/verify.php and public/verifier.js: same JCS, entry_hash,
4
+ signed_content, Merkle, selective-disclosure and anchor rules, so all three agree on
5
+ the same bytes (checked against the shared conformance corpus). Checks integrity,
6
+ attribution (subject signature, epoch-aware for key rotation), ordering, checkpoint
7
+ append-only + server signatures + witnesses, selective-disclosure field proofs, and
8
+ reports the external anchors. Proves tampering by anyone who is not Touchstone; it
9
+ does not prove completeness, and says so.
10
+ """
11
+ import hashlib
12
+ import json
13
+
14
+ from ._ed25519 import verify as _ed_verify
15
+
16
+
17
+ def jcs(v) -> str:
18
+ """RFC 8785-ish canonical JSON, matching Canonicalizer.php + verifier.js (no
19
+ non-ASCII escaping, compact separators, recursive key sort)."""
20
+ if isinstance(v, list):
21
+ return "[" + ",".join(jcs(x) for x in v) + "]"
22
+ if isinstance(v, dict):
23
+ return "{" + ",".join(json.dumps(k, ensure_ascii=False) + ":" + jcs(v[k]) for k in sorted(v)) + "}"
24
+ return json.dumps(v, ensure_ascii=False, separators=(",", ":"))
25
+
26
+
27
+ def _sha256_hex(b: bytes) -> str:
28
+ return hashlib.sha256(b).hexdigest()
29
+
30
+
31
+ def _ed(pub_b64: str, msg: str, sig_b64: str) -> bool:
32
+ try:
33
+ pub = _b64(pub_b64)
34
+ sig = _b64(sig_b64)
35
+ except Exception:
36
+ return False
37
+ return _ed_verify(pub, msg.encode("utf-8"), sig)
38
+
39
+
40
+ def _b64(s: str) -> bytes:
41
+ import base64
42
+ return base64.b64decode(s.replace("-", "+").replace("_", "/") + "===")
43
+
44
+
45
+ def _mleaf(hex_h: str) -> str:
46
+ return _sha256_hex(b"\x00" + bytes.fromhex(hex_h))
47
+
48
+
49
+ def _mnode(l: str, r: str) -> str:
50
+ return _sha256_hex(b"\x01" + bytes.fromhex(l) + bytes.fromhex(r))
51
+
52
+
53
+ def _merkle_from_proof(leaf_hex: str, proof):
54
+ # fail-closed: malformed hash/proof (bad hex, non-list) → None, which equals no root.
55
+ try:
56
+ cur = _mleaf(leaf_hex)
57
+ for step in proof:
58
+ cur = _mnode(cur, step["hash"]) if step.get("side") == "right" else _mnode(step["hash"], cur)
59
+ return cur
60
+ except Exception:
61
+ return None
62
+
63
+
64
+ def _entry_hash(e) -> str:
65
+ s = "\n".join([
66
+ str(e["seq"]), e["prev_hash"], e["server_ts"], e["payload_hash"],
67
+ e["actor_sub"], e.get("counterparty_sub") or "", e["actor_sig"],
68
+ ])
69
+ return _sha256_hex(s.encode("utf-8"))
70
+
71
+
72
+ def _signed_content(recorder_id: str, e) -> str:
73
+ return jcs({
74
+ "v": 1, "recorder_id": recorder_id, "event_type": e["event_type"],
75
+ "actor_sub": e["actor_sub"], "counterparty_sub": e.get("counterparty_sub"),
76
+ "payload_hash": e["payload_hash"], "client_ts": e.get("client_ts"),
77
+ })
78
+
79
+
80
+ def verify_disclosure(b: dict) -> dict:
81
+ """Verify a decoded touchstone-disclosure/1 bundle. Returns
82
+ {ok, format_ok, recorder, subject, tier, entries:[{seq,type,checks:[{ok,fatal,msg}]}],
83
+ checkpoints:[{ok,fatal,msg}]}. `ok` is the AND of all fatal checks."""
84
+ if not isinstance(b, dict) or b.get("format") != "touchstone-disclosure/1":
85
+ return {"ok": False, "format_ok": False, "error": "not a touchstone-disclosure/1 bundle"}
86
+
87
+ # structural guard: a malformed top-level shape rejects gracefully (never crashes).
88
+ rec = b.get("recorder")
89
+ entries = b.get("entries")
90
+ _cps = b.get("checkpoints") # optional; a non-list (null, {}, …) means "none" (matches verify.php/js)
91
+ checkpoints = _cps if isinstance(_cps, list) else []
92
+ # a disclosure must carry a recorder object and a non-empty entries list (genesis at least).
93
+ if not isinstance(rec, dict) or not isinstance(entries, list) or not entries \
94
+ or not all(isinstance(e, dict) for e in entries) or not all(isinstance(c, dict) for c in checkpoints):
95
+ return {"ok": False, "format_ok": False, "error": "malformed bundle structure"}
96
+ _pid = rec.get("public_id")
97
+ recorder_id = _pid if isinstance(_pid, str) else ""
98
+ _pk = rec.get("signing_pubkey")
99
+ pubkey = _pk if isinstance(_pk, str) else ""
100
+ # only well-formed epochs participate; a malformed one is dropped (its rotated key is then
101
+ # untrusted → fail-closed), matching verify.php / verifier.js.
102
+ sk = rec.get("signing_keys")
103
+ epochs = [k for k in sk if isinstance(k, dict) and isinstance(k.get("from_seq"), int)
104
+ and not isinstance(k.get("from_seq"), bool) and isinstance(k.get("pubkey"), str)] if isinstance(sk, list) else []
105
+ epochs = sorted(epochs, key=lambda x: x["from_seq"])
106
+
107
+ def key_for_seq(seq: int) -> str:
108
+ k = pubkey
109
+ for ep in epochs:
110
+ if int(ep["from_seq"]) <= seq:
111
+ k = ep["pubkey"]
112
+ else:
113
+ break
114
+ return k
115
+
116
+ server_pub = b.get("server_pubkey")
117
+ server_pub = server_pub if isinstance(server_pub, str) and server_pub else None
118
+ cp_by_id = {cp.get("id"): cp for cp in checkpoints}
119
+ by_seq = {e.get("seq"): e for e in entries}
120
+ state = {"ok": True}
121
+ cp_checks = []
122
+
123
+ def cp_add(ok: bool, msg: str, fatal: bool):
124
+ cp_checks.append({"ok": ok, "fatal": fatal, "msg": msg})
125
+ if fatal and not ok:
126
+ state["ok"] = False
127
+
128
+ # Key epochs must be introduced by their key_rotation entry when it's in the bundle,
129
+ # else an attacker injects a forged epoch (see verify.php). Genesis is bound by the PoP.
130
+ for ep in epochs:
131
+ try:
132
+ if int(ep["from_seq"]) == 0:
133
+ continue
134
+ rot = by_seq.get(int(ep["from_seq"]) - 1)
135
+ if rot is None:
136
+ cp_add(True, f"key epoch from seq {ep['from_seq']} relies on a key_rotation entry not in this disclosure — verify the full chain", False)
137
+ continue
138
+ rb = {}
139
+ if rot.get("body_enc"):
140
+ try:
141
+ rb = json.loads(rot["body_enc"])
142
+ except Exception:
143
+ rb = {}
144
+ cp_add(rot.get("event_type") == "key_rotation" and rb.get("new_signing_pubkey") == ep["pubkey"],
145
+ f"key epoch from seq {ep['from_seq']} introduced by its key_rotation entry", True)
146
+ except Exception:
147
+ cp_add(False, "malformed key epoch — rejected", True)
148
+ cp_add(True, f'attribution binds to the genesis key, which self-claims subject "{rec.get("subject_sub")}"; '
149
+ f'confirm that key at /.well-known/touchstone/pubkeys/{rec.get("subject_sub")} — this bundle alone '
150
+ "does not prove the subject→key binding", False)
151
+
152
+ prev_cp = None
153
+
154
+ def _is_int(x):
155
+ return isinstance(x, int) and not isinstance(x, bool)
156
+
157
+ for cp in sorted(cp_by_id.values(), key=lambda c: c.get("seq_start", 0) if _is_int(c.get("seq_start")) else 0):
158
+ try:
159
+ # strict checkpoint field types — reject type-confused checkpoints uniformly
160
+ # (matches verify.php / verifier.js).
161
+ if not (_is_int(cp.get("id")) and _is_int(cp.get("seq_start")) and _is_int(cp.get("seq_end"))
162
+ and isinstance(cp.get("merkle_root"), str) and isinstance(cp.get("head_hash"), str)):
163
+ cp_add(False, "malformed checkpoint field types — rejected", True)
164
+ prev_cp = cp
165
+ continue
166
+ if server_pub:
167
+ cp_add(_ed(server_pub, cp["merkle_root"], cp.get("recorder_sig", "")),
168
+ f"checkpoint #{cp['id']} root signed by Touchstone server", True)
169
+ else:
170
+ cp_add(True, f"checkpoint #{cp['id']} server signature unverifiable (no server_pubkey)", False)
171
+ if prev_cp is not None:
172
+ if int(cp["seq_start"]) > int(prev_cp["seq_end"]) + 1:
173
+ cp_add(True, f"checkpoint #{cp['id']} follows #{prev_cp['id']} (intermediate checkpoints not in this disclosure)", False)
174
+ else:
175
+ contig = int(cp["seq_start"]) == int(prev_cp["seq_end"]) + 1
176
+ linked = cp.get("prev_checkpoint_hash") and cp["prev_checkpoint_hash"] == prev_cp["head_hash"]
177
+ cp_add(bool(contig and linked), f"checkpoint #{cp['id']} extends #{prev_cp['id']} append-only", True)
178
+ for w in (cp["witnesses"] if isinstance(cp.get("witnesses"), list) else []):
179
+ msg = f"touchstone-cp-witness:v1:{recorder_id}:{cp['id']}:{cp['merkle_root']}:{cp['head_hash']}"
180
+ cp_add(_ed(w["witness_pubkey"], msg, w["witness_sig"]),
181
+ f"checkpoint #{cp['id']} witnessed by {w['witness_sub']} ({w['grade']})", True)
182
+ except Exception:
183
+ cp_add(False, "malformed checkpoint — rejected", True)
184
+ prev_cp = cp
185
+
186
+ entries_out = []
187
+ for e in entries:
188
+ checks = []
189
+
190
+ def add(ok: bool, msg: str, fatal: bool):
191
+ checks.append({"ok": ok, "fatal": fatal, "msg": msg})
192
+ if fatal and not ok:
193
+ state["ok"] = False
194
+
195
+ # strict field types: reject type-confused entries uniformly instead of coercing.
196
+ types_ok = isinstance(e.get("seq"), int) and not isinstance(e.get("seq"), bool) \
197
+ and all(isinstance(e.get(f), str) for f in ("prev_hash", "entry_hash", "payload_hash", "actor_sub", "actor_sig"))
198
+ if "counterparty_sub" in e and e["counterparty_sub"] is not None and not isinstance(e["counterparty_sub"], str):
199
+ types_ok = False
200
+ if not types_ok:
201
+ add(False, "malformed entry field types — rejected", True)
202
+ entries_out.append({"seq": e["seq"] if isinstance(e.get("seq"), int) else -1,
203
+ "type": str(e.get("event_type", "")), "redacted": False, "checks": checks})
204
+ continue
205
+
206
+ try: # fail-closed: any malformed entry (missing field, bad type) → rejected
207
+ add(_entry_hash(e) == e["entry_hash"], "entry_hash integrity", True)
208
+
209
+ seq_key = key_for_seq(int(e["seq"]))
210
+ if int(e["seq"]) == 0:
211
+ challenge = "touchstone-pop:v1:" + rec["subject_sub"] + ":" + seq_key
212
+ add(_ed(seq_key, challenge, e["actor_sig"]), "genesis proof-of-possession", True)
213
+ else:
214
+ add(_ed(seq_key, _signed_content(recorder_id, e), e["actor_sig"]), "actor signature (subject key)", True)
215
+
216
+ if e.get("event_type") == "key_rotation" and e.get("body_enc"):
217
+ try:
218
+ rb = json.loads(e["body_enc"])
219
+ except Exception:
220
+ rb = {}
221
+ np = rb.get("new_signing_pubkey", "")
222
+ add(_ed(np, f"touchstone-rotate:v1:{recorder_id}:{np}", rb.get("new_key_pop", "")),
223
+ "key rotation → new key proof-of-possession", True)
224
+
225
+ if e.get("counterparty_sig") and e.get("counterparty_pubkey"):
226
+ add(_ed(e["counterparty_pubkey"], _signed_content(recorder_id, e), e["counterparty_sig"]),
227
+ f"counterparty co-signature ({e.get('counterparty_sub')}, {e.get('counterparty_grade', 'claimed')})", True)
228
+ elif e.get("counterparty_sub"):
229
+ add(True, f"names counterparty {e['counterparty_sub']} (awaiting co-signature)", False)
230
+
231
+ if by_seq.get(e["seq"] - 1):
232
+ add(e["prev_hash"] == by_seq[e["seq"] - 1]["entry_hash"], f"chain linkage to seq {e['seq'] - 1}", True)
233
+
234
+ # merkle_proof is a list (possibly empty: a single-entry checkpoint's proof IS
235
+ # empty, root == leaf) — run whenever present, matching verify.php/verifier.js. An
236
+ # empty object {} is treated as an empty list (PHP can't tell {} from [] under
237
+ # assoc decode, so all three normalize it the same way).
238
+ mp = e.get("merkle_proof")
239
+ if isinstance(mp, dict) and not mp:
240
+ mp = []
241
+ _cid = e.get("checkpoint_id")
242
+ if isinstance(mp, list) and isinstance(_cid, int) and not isinstance(_cid, bool) and cp_by_id.get(_cid):
243
+ cp = cp_by_id[e["checkpoint_id"]]
244
+ add(_merkle_from_proof(e["entry_hash"], mp) == cp["merkle_root"],
245
+ f"merkle inclusion in checkpoint #{cp['id']}", True)
246
+ any_confirmed = False
247
+ for a in (cp.get("anchors") or []):
248
+ if not isinstance(a, dict):
249
+ continue
250
+ try:
251
+ blob = json.loads(a.get("token_blob") or "{}")
252
+ except Exception:
253
+ blob = {}
254
+ if a.get("method") == "self" and a.get("status") == "confirmed":
255
+ # verify the server signed the head — don't trust the status label
256
+ self_ok = _ed(server_pub, cp["head_hash"], a.get("token_blob", "")) if server_pub else None
257
+ if self_ok is False:
258
+ add(False, f"self anchor signature INVALID (checkpoint #{cp['id']})", True)
259
+ else:
260
+ add(True, f"anchored (self, {a.get('external_ts')})" + (" — server signature verified" if self_ok else ""), False)
261
+ any_confirmed = True
262
+ elif a.get("method") == "ots" and a.get("status") == "confirmed" and blob.get("bitcoin_height"):
263
+ # The height is the SERVER'S claim; this offline check does not confirm the
264
+ # proof commits to that block. (Self anchors above are signature-verified;
265
+ # OTS needs Bitcoin, which is out of scope for an offline tool.) Say so, and
266
+ # point at how to confirm it — don't present a claim as a verified fact.
267
+ add(True, f"OTS → Bitcoin block {blob['bitcoin_height']} CLAIMED ({a.get('external_ts')}) "
268
+ f"— not confirmed against mainnet here; verify the downloadable .ots with "
269
+ f"`ots verify`, which recomputes the committed root against the real block", False)
270
+ any_confirmed = True
271
+ elif a.get("method") == "ots":
272
+ add(True, "OTS submitted, Bitcoin-pending (re-check with ots upgrade/verify)", False)
273
+ elif a.get("method") == "tsa" and a.get("status") == "confirmed":
274
+ add(True, f"RFC 3161 timestamp ({a.get('external_ts')}); cryptographic check: openssl ts -verify", False)
275
+ any_confirmed = True
276
+ if not any_confirmed:
277
+ add(False, "no confirmed external anchor yet", False)
278
+ else:
279
+ add(False, "not yet checkpointed/anchored (integrity+signature only)", False)
280
+
281
+ if e.get("sd"):
282
+ _rev = e.get("sd_revealed")
283
+ revealed = _rev if isinstance(_rev, list) else [] # non-list → nothing revealed (matches verify.php/js)
284
+ committed = None
285
+ ks = e.get("sd_keyset")
286
+ if isinstance(ks, dict) and ks: # empty {} → treat as no key-set commitment (matches verify.php)
287
+ keys = sorted(ks["keys"] if isinstance(ks.get("keys"), list) else [])
288
+ ks_leaf = _sha256_hex(("tsd:keyset:v1\n" + jcs(keys)).encode("utf-8"))
289
+ add(_merkle_from_proof(ks_leaf, ks.get("proof", [])) == e["payload_hash"],
290
+ f"selective-disclosure key-set committed ({len(keys)} fields)", True)
291
+ committed = keys
292
+ for f in revealed:
293
+ leaf = _sha256_hex(("tsd:field:v1\n" + jcs([f["k"], f["v"], f["s"]])).encode("utf-8"))
294
+ add(_merkle_from_proof(leaf, f.get("proof", [])) == e["payload_hash"],
295
+ f'selective field "{f["k"]}" proven in payload_hash', True)
296
+ if committed is not None:
297
+ add(f["k"] in committed, f'revealed field "{f["k"]}" in committed key-set', True)
298
+ shown = len(revealed)
299
+ if committed is not None:
300
+ revealed_keys = [f["k"] for f in revealed]
301
+ withheld = [k for k in committed if k not in revealed_keys]
302
+ add(True, f"selective disclosure: {shown} of {len(committed)} committed field(s) revealed; "
303
+ f"withheld (provably sealed): {', '.join(withheld) or 'none'}", False)
304
+ else:
305
+ count = e.get("sd_field_count", 0)
306
+ add(True, f"selective disclosure: {shown} of {count} field(s) revealed (key-set not committed)", False)
307
+ except Exception:
308
+ add(False, "malformed entry — rejected", True)
309
+
310
+ _seq = e.get("seq")
311
+ entries_out.append({"seq": _seq if isinstance(_seq, int) else -1, "type": e.get("event_type", ""),
312
+ "redacted": bool(e.get("redacted")), "checks": checks})
313
+
314
+ return {
315
+ "ok": state["ok"], "format_ok": True, "recorder": recorder_id,
316
+ "subject": rec.get("subject_sub"), "tier": rec.get("trust_tier"),
317
+ "entries": entries_out, "checkpoints": cp_checks,
318
+ }
@@ -0,0 +1,81 @@
1
+ Metadata-Version: 2.4
2
+ Name: touchstone-verify
3
+ Version: 0.3.2
4
+ Summary: Independently verify a Touchstone disclosure — zero dependencies, pure Python.
5
+ Author: Touchstone
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://touchstone.cv
8
+ Project-URL: Source, https://github.com/Touchstone-CV/touchstone-verify
9
+ Keywords: touchstone,audit-log,verifier,ed25519,tamper-evident,provenance
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Security :: Cryptography
13
+ Requires-Python: >=3.8
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Dynamic: license-file
17
+
18
+ # touchstone-verify
19
+
20
+ Independently verify a **[Touchstone](https://touchstone.cv)** disclosure — in pure Python,
21
+ with **zero dependencies**. Read it before you trust it: it's a small, self-contained file.
22
+
23
+ A disclosure is a tamper-evident slice of an agent's action log. This package re-derives,
24
+ with no trust in Touchstone, that the slice is **intact** (entry hashes recompute), **attributed**
25
+ (the subject's Ed25519 signature holds, epoch-aware across key rotation), and **ordered**
26
+ (hash-chained, with checkpoints that are append-only, server-signed, and witness-co-signed). It
27
+ also checks **selective-disclosure** field proofs and reports the external anchors. It proves
28
+ tampering by anyone who is not Touchstone — it does **not** prove completeness, and says so.
29
+
30
+ It agrees byte-for-byte with the other two Touchstone verifiers (`verify.php`, `verifier.js`):
31
+ all three are tested against the same conformance corpus.
32
+
33
+ ## Install
34
+
35
+ ```bash
36
+ pip install touchstone-verify
37
+ ```
38
+
39
+ ## Use
40
+
41
+ Command line — pass a file, a URL, or a disclosure token:
42
+
43
+ ```bash
44
+ touchstone-verify https://touchstone.cv/d/833cd4ca23fbb940dd71843ca47a807e
45
+ touchstone-verify ./bundle.json
46
+ touchstone-verify 833cd4ca23fbb940dd71843ca47a807e # fetches from touchstone.cv
47
+ ```
48
+
49
+ Exit code `0` = verified, `1` = a load-bearing check failed, `2` = couldn't load.
50
+
51
+ Library:
52
+
53
+ ```python
54
+ from touchstone_verify import verify_disclosure
55
+ import json, urllib.request
56
+
57
+ bundle = json.load(urllib.request.urlopen("https://touchstone.cv/d/<token>"))
58
+ result = verify_disclosure(bundle)
59
+ print(result["ok"]) # True / False
60
+ for e in result["entries"]:
61
+ for c in e["checks"]:
62
+ print(c["ok"], c["msg"])
63
+ ```
64
+
65
+ ## What it checks
66
+
67
+ - **Integrity** — every `entry_hash` recomputes from its fields.
68
+ - **Attribution** — the subject signature verifies over the canonical signed content; genesis
69
+ proof-of-possession; `key_rotation` new-key PoP; counterparty co-signatures.
70
+ - **Ordering** — `prev_hash` chain linkage; Merkle inclusion in the cited checkpoint.
71
+ - **Checkpoints** — server signature over each Merkle root; append-only linkage between
72
+ consecutive checkpoints; independent witness co-signatures.
73
+ - **Selective disclosure** — each revealed field proves Merkle inclusion in `payload_hash`;
74
+ withheld fields never appear in the bundle.
75
+
76
+ For split-view / Bitcoin-anchor cross-checking across independent relays, see the companion
77
+ `gossip_check.py` at <https://touchstone.cv/gossip_check.py>.
78
+
79
+ ## License
80
+
81
+ [Apache-2.0](./LICENSE).
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/touchstone_verify/__init__.py
5
+ src/touchstone_verify/__main__.py
6
+ src/touchstone_verify/_ed25519.py
7
+ src/touchstone_verify/verify.py
8
+ src/touchstone_verify.egg-info/PKG-INFO
9
+ src/touchstone_verify.egg-info/SOURCES.txt
10
+ src/touchstone_verify.egg-info/dependency_links.txt
11
+ src/touchstone_verify.egg-info/entry_points.txt
12
+ src/touchstone_verify.egg-info/top_level.txt
13
+ tests/test_conformance.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ touchstone-verify = touchstone_verify.__main__:main
@@ -0,0 +1 @@
1
+ touchstone_verify
@@ -0,0 +1,60 @@
1
+ """Conformance: this verifier against the shared Touchstone corpus (same fixtures
2
+ verify.php and verifier.js check). Valid bundles pass; every documented tamper fails.
3
+ Runnable with pytest or as a plain script: python tests/test_conformance.py
4
+ """
5
+ import base64
6
+ import copy
7
+ import json
8
+ import os
9
+ import sys
10
+
11
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
12
+ from touchstone_verify import verify_disclosure # noqa: E402
13
+
14
+ DIR = os.path.join(os.path.dirname(__file__), "fixtures")
15
+
16
+
17
+ def _load(name):
18
+ with open(os.path.join(DIR, name), encoding="utf-8") as fh:
19
+ return json.load(fh)
20
+
21
+
22
+ def _first_non_genesis(b):
23
+ return next((e for e in b["entries"] if e["seq"] != 0), b["entries"][0])
24
+
25
+
26
+ TAMPERS = {
27
+ "entry_hash": lambda b: _first_non_genesis(b).__setitem__("entry_hash", "f" * 64),
28
+ "actor_sig": lambda b: _first_non_genesis(b).__setitem__("actor_sig", base64.b64encode(bytes([1] * 64)).decode()),
29
+ "checkpoint_root": lambda b: b.get("checkpoints") and b["checkpoints"][0].__setitem__("merkle_root", "a" * 64),
30
+ "sd_revealed_value": lambda b: next(
31
+ (f.__setitem__("v", "__TAMPERED__") for e in b["entries"] if e.get("sd") for f in e.get("sd_revealed", [])[:1]),
32
+ None,
33
+ ),
34
+ "sd_keyset_drop": lambda b: next(
35
+ (e["sd_keyset"]["keys"].pop() for e in b["entries"] if e.get("sd_keyset", {}).get("keys")),
36
+ None,
37
+ ),
38
+ "inject_epoch": lambda b: b["recorder"].setdefault("signing_keys", []).append({"from_seq": 1, "pubkey": "A" * 43 + "="}),
39
+ }
40
+
41
+
42
+ def test_corpus():
43
+ manifest = _load("manifest.json")
44
+ for case in manifest["cases"]:
45
+ bundle = _load(case["file"])
46
+ res = verify_disclosure(bundle)
47
+ assert res["ok"] == case["expect_ok"], f"{case['file']} expected ok={case['expect_ok']}"
48
+ if case.get("withheld_absent"):
49
+ assert case["withheld_absent"] not in json.dumps(bundle), f"{case['file']} leaked withheld content"
50
+ for name in manifest["tampers"]:
51
+ t = copy.deepcopy(bundle)
52
+ TAMPERS[name](t)
53
+ if json.dumps(t) == json.dumps(bundle):
54
+ continue
55
+ assert verify_disclosure(t)["ok"] is False, f"{case['file']} tamper '{name}' must be rejected"
56
+
57
+
58
+ if __name__ == "__main__":
59
+ test_corpus()
60
+ print("conformance OK — touchstone-verify matches the corpus on valid + tampered bundles.")