actaseal-verify 1.0.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,184 @@
1
+ Metadata-Version: 2.4
2
+ Name: actaseal-verify
3
+ Version: 1.0.0
4
+ Summary: Standalone offline verifier for ActaSeal dispute evidence packets
5
+ License: Apache-2.0
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: cryptography
10
+ Dynamic: license-file
11
+
12
+ # actaseal-verify
13
+
14
+ Verify an ActaSeal dispute evidence packet yourself, in about 60 seconds,
15
+ without installing ActaSeal, without a network call, and without trusting
16
+ us. This repo is one script (`verify.py`) plus a spec.
17
+
18
+ Who this is for: an underwriter, dispute analyst, or auditor who has been
19
+ handed a packet (a `.zip`) and wants to check, independently, that:
20
+
21
+ - the evidence chain hasn't been tampered with (every event's hash
22
+ recomputes from its own recorded content, and the chain is unbroken);
23
+ - the receipt's signature is genuinely valid over that chain;
24
+ - the chain-of-custody and acquisition documents (the FRE 901/902 basis
25
+ for admissibility) are present and internally consistent;
26
+ - if the packet claims a payment-rail settlement anchor, that anchor's
27
+ hash actually recomputes from its declared content.
28
+
29
+ ## Verify a packet in 60 seconds
30
+
31
+ ```bash
32
+ pip install cryptography # the only third-party dependency
33
+ unzip your-packet.zip -d packet
34
+ python verify.py packet
35
+ ```
36
+
37
+ (Or `pip install .` from this repo, then `python -m verify packet`.)
38
+
39
+ Exit code `0` and `VERIFIED: ...` means every check above passed. Exit
40
+ code `1` prints exactly which check failed and why -- nothing is silently
41
+ waved through. Exit code `2` means `cryptography` isn't installed (no
42
+ partial/soft-pass is possible).
43
+
44
+ Try it right now against the demo packets checked into this repo:
45
+
46
+ ```bash
47
+ python verify.py demo/demo-packet-unanchored
48
+ python verify.py demo/demo-packet-anchored # includes a rail settlement anchor
49
+ ```
50
+
51
+ Or try it entirely in your browser, no install: **[tamper_demo/](tamper_demo/index.html)**
52
+ loads a real signed packet, lets you edit any field, and re-verifies live as you type --
53
+ break the hash chain or the signature and watch it turn red immediately. Nothing is sent
54
+ anywhere; it's a JS port of the same checks (`tamper_demo/verify_min.js`), using the
55
+ browser's native WebCrypto Ed25519 support.
56
+
57
+ ## Use it in CI
58
+
59
+ `action.yml` in this repository is a reusable GitHub Action:
60
+
61
+ ```yaml
62
+ - uses: actaseal/actaseal-verify@main
63
+ with:
64
+ packet-dir: ./extracted-packet
65
+ # anchors: ./anchors.jsonl # optional
66
+ ```
67
+
68
+ Fails the step (non-zero exit) if the packet doesn't verify.
69
+
70
+ ## Use it from Node / a browser
71
+
72
+ `@actaseal/verify` (`tamper_demo/`, `npm install @actaseal/verify`) is a
73
+ minimal, zero-dependency WebCrypto port covering chain integrity and
74
+ Ed25519 receipt signatures only -- see `tamper_demo/README.npm.md` for
75
+ its exact (reduced) scope before relying on it for anything beyond a
76
+ quick client-side check. The real `verify.py` above is the canonical,
77
+ full-scope verifier.
78
+
79
+ ## Telemetry: opt-in, count-only, off by default, NOT in verify.py itself
80
+
81
+ `verify.py` makes zero network calls, period -- that's a real,
82
+ tested guarantee (`tests/test_verify_demo_packet.py::
83
+ test_verify_has_no_external_imports_beyond_cryptography`), not a
84
+ default that can be toggled. Telemetry lives entirely in a separate,
85
+ optional wrapper instead: `verify_with_telemetry.py` calls `verify.py`'s
86
+ own `main()` completely unchanged, and only after that call returns
87
+ does it (optionally) send a ping -- `verify.py` itself never imports
88
+ `urllib` or knows telemetry exists.
89
+
90
+ ```bash
91
+ python verify_with_telemetry.py --telemetry <packet_dir>
92
+ ```
93
+
94
+ Even with `--telemetry` passed, the wrapper ships with
95
+ `TELEMETRY_ENDPOINT` set to an empty string, so it's currently an inert
96
+ no-op regardless -- nothing is transmitted until a maintainer
97
+ deliberately sets a real endpoint in a future release. When/if that
98
+ happens, a ping sends exactly three fields: the wrapper's own version
99
+ string, the verification outcome (`PASS`/`FAIL`), and a failure count
100
+ (derived by counting verify.py's own printed failure lines, never by
101
+ inspecting packet content) -- never a filename, never anything about
102
+ the specific receipt or ledger being verified. Best-effort only: any
103
+ network failure is silently swallowed and never affects the exit code
104
+ or printed result, which are always exactly what plain `python verify.py`
105
+ would have produced.
106
+
107
+ ## Why "zero-import" is the whole point
108
+
109
+ `verify.py` has no dependency on ActaSeal's code, config, database, or
110
+ network access -- it is standalone by construction (see the assertion in
111
+ `tests/test_verify_demo_packet.py::test_verify_has_no_external_imports_beyond_cryptography`).
112
+ The only third-party package it needs is `cryptography`, for Ed25519/ECDSA
113
+ signature checks. That means:
114
+
115
+ - you can read the whole verifier in one sitting (~360 lines, no
116
+ framework, no magic) and know exactly what it checks;
117
+ - you never run vendor code against your own systems to check evidence
118
+ someone handed you -- it only reads files from the packet directory;
119
+ - the packet embeds its own trust root (`manifest.json`'s
120
+ `receipt_public_key_hex`) -- verification needs no external key file,
121
+ registry, or live service lookup. You separately compare that key
122
+ against the operator's published key out of band; the packet cannot
123
+ forge that comparison, only be internally consistent or not.
124
+
125
+ This is the file that ships inside every real ActaSeal dispute packet as
126
+ `verify.py` -- what you're running here is not a simplified demo version,
127
+ it's the literal artifact.
128
+
129
+ ## What "VERIFIED" actually means
130
+
131
+ Passing does not mean "ActaSeal says this is fine." It means every one of
132
+ these independently re-derives from data already inside the packet:
133
+
134
+ 1. **Ledger chain integrity** -- each event's `payload_hash`, `event_id`,
135
+ and `event_hash` recompute from that event's own fields; the slice is
136
+ an unbroken hash chain from the manifest's declared starting point.
137
+ 2. **Receipt signature** -- the receipt's Ed25519/ECDSA signature verifies
138
+ against `manifest.json`'s embedded public key, over the canonical JSON
139
+ of the receipt (minus the signature field itself).
140
+ 3. **Receipt-to-chain binding** -- the receipt's `ledger_entry_hash` names
141
+ a real event in the slice, for the same action, and that event's
142
+ recorded action hash matches the receipt's.
143
+ 4. **Chain-of-custody / acquisition basis (FRE 901(b)(9), 902(13)-(14))**
144
+ -- the acquisition report names its tool, clock source, and custodian;
145
+ custody events are time-ordered and each bound to a real ledger event
146
+ hash; the authentication statement's key id, pubkey hash, and mandate
147
+ hash match the receipt.
148
+ 5. **Scope conformance** -- if the receipt claims an in-scope or breach
149
+ verdict, that verdict traces back to a `ScopeEvaluated` ledger event
150
+ whose recorded scope/action hashes recompute correctly.
151
+ 6. **Settlement anchor** -- if the packet claims a payment-rail
152
+ settlement anchor, its `anchor_hash` recomputes from the anchor
153
+ content; an unanchored packet says so explicitly (never silent).
154
+
155
+ See [`SPEC.md`](SPEC.md) for the full packet format.
156
+
157
+ ## What this does *not* verify
158
+
159
+ - That the underlying transaction/refund/decision was *correct* -- only
160
+ that the recorded evidence is internally consistent and unaltered.
161
+ - That `receipt_public_key_hex` belongs to the operator you think it
162
+ does -- that binding is on you, out of band (e.g. compare against a
163
+ key the operator has published elsewhere).
164
+ - Anything about a deployment you haven't been handed a packet from.
165
+
166
+ ## Repo layout
167
+
168
+ ```
169
+ verify.py the verifier -- the only file that matters at verify time
170
+ generate_demo_packet.py builds the two demo packets below, from scratch, standalone
171
+ demo/demo-packet-unanchored/ a valid packet with no settlement anchor
172
+ demo/demo-packet-anchored/ a valid packet with a payment-rail settlement anchor
173
+ tamper_demo/ in-browser, editable, live-verifying demo (see above)
174
+ SPEC.md packet format reference
175
+ tests/ pytest suite: valid packets pass, tampered ones fail loudly
176
+ ```
177
+
178
+ ## License
179
+
180
+ Apache-2.0. See [LICENSE](LICENSE).
181
+
182
+ ## Security
183
+
184
+ See [SECURITY.md](SECURITY.md) for how to report a vulnerability.
@@ -0,0 +1,6 @@
1
+ verify.py,sha256=NkHPpYAMwenXXl30O4_fqE8QI3b3A--_70GXrOYWw9A,31206
2
+ actaseal_verify-1.0.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
3
+ actaseal_verify-1.0.0.dist-info/METADATA,sha256=bSqmSy8ZIWejgADVHjAR-Gi5SA6Y349GVFjfoCwS6Vs,8158
4
+ actaseal_verify-1.0.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
5
+ actaseal_verify-1.0.0.dist-info/top_level.txt,sha256=t0nRZ9jg84QWlDQwrfqJUJgmwHuOldQ_DzvqkpQ2Lr8,7
6
+ actaseal_verify-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -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 @@
1
+ verify
verify.py ADDED
@@ -0,0 +1,702 @@
1
+ #!/usr/bin/env python3
2
+ """Offline verifier for an ActaSeal dispute evidence packet.
3
+
4
+ Standalone by design: no actaseal imports, so a counterparty can re-check
5
+ the evidence without installing or trusting ActaSeal code. Requires only
6
+ the Python standard library plus the 'cryptography' package (Ed25519).
7
+
8
+ Checks, all of which must hold:
9
+ - every ledger event's payload_hash, event_id, and event_hash recompute
10
+ from its own content (sha256 over canonical JSON: sorted keys, compact
11
+ separators, no NaN);
12
+ - the slice is an unbroken hash chain (each previous_event_hash matches
13
+ the prior event) anchored to the manifest's declared chain start;
14
+ - the manifest's action_id, event_count, and chain start match the slice;
15
+ - the receipt's Ed25519 signature verifies against the manifest's public
16
+ key over the canonical JSON of the receipt minus its signature field;
17
+ - the receipt is bound into the slice: its ledger_entry_hash names an
18
+ included event of the manifest's action, and that event's recorded
19
+ action_packet_hash (when present) matches the receipt's action_hash;
20
+ - the FRE 901/902 authentication documents are present and consistent:
21
+ acquisition.json names its tool, clock source, and custodian;
22
+ custody.json's events are time-ordered and each bound to a ledger
23
+ event hash that exists in the slice; authentication.json's declared
24
+ hash algorithm, signer key_id, pubkey hash, and mandate_hash match
25
+ the receipt, and its anchor log id matches the acquisition report.
26
+ A missing or inconsistent document fails, naming that document.
27
+ - the manifest's scope_conformance_headline is present and consistent
28
+ with the receipt's scope_conformance and the ScopeEvaluated ledger
29
+ event (verdict, breach dimensions, recorded scope/action hashes);
30
+ missing or mismatched fails naming SCOPE_*.
31
+
32
+ Trust root: receipt_public_key_hex in manifest.json. Compare it out of
33
+ band against the gateway operator's published key -- a packet re-signed
34
+ end to end with a different key is internally consistent.
35
+
36
+ Usage: python verify.py [packet_dir] [--anchors PATH]
37
+ packet_dir defaults to this script's directory. --anchors is optional:
38
+ when given, also confirms this packet's ledger_root_hash was witnessed
39
+ by a successful entry in the named anchor log (a jsonl file of
40
+ transparency-anchor records, see actaseal.ledger_anchor /
41
+ scripts/publish_anchor.py in the private ActaSeal repo).
42
+ Exit codes: 0 verified, 1 verification failed or packet unreadable,
43
+ 2 unable to run (missing 'cryptography').
44
+ """
45
+ import hashlib
46
+ import json
47
+ import sys
48
+ from pathlib import Path
49
+
50
+ # Receipt signature algorithms this verifier knows how to check. Must stay
51
+ # in lock-step with actaseal.signing.ALGORITHM_*. Both branches use only
52
+ # the 'cryptography' package this script already requires (see module
53
+ # docstring) -- adding an algorithm here must never add a new dependency.
54
+ ALGORITHM_ED25519 = "ed25519"
55
+ ALGORITHM_ECDSA_P256_SHA256 = "ecdsa-p256-sha256"
56
+
57
+ # Continuity-checkpoint failure codes (T8, ONESHOT-4 batch 3). Must stay
58
+ # in lock-step with actaseal.anchoring's constants of the same names.
59
+ ANCHOR_INCLUSION_PROOF_INVALID = "ANCHOR_INCLUSION_PROOF_INVALID"
60
+ ANCHOR_CONSISTENCY_PROOF_INVALID = "ANCHOR_CONSISTENCY_PROOF_INVALID"
61
+ ANCHOR_CHECKPOINT_MISMATCH = "ANCHOR_CHECKPOINT_MISMATCH"
62
+ STH_SIGNATURE_INVALID = "STH_SIGNATURE_INVALID"
63
+
64
+ SCHEMA_VERSION = "dispute_packet.v1"
65
+ EVENT_ID_BASIS = "ledger_event_id.v1"
66
+ EVENT_MATERIAL_FIELDS = (
67
+ "event_type",
68
+ "tenant_id",
69
+ "workspace_id",
70
+ "actor_id",
71
+ "action_id",
72
+ "action_type",
73
+ "timestamp",
74
+ "schema_version",
75
+ "payload",
76
+ "payload_hash",
77
+ "previous_event_hash",
78
+ )
79
+
80
+
81
+ def canonical_dumps(value):
82
+ return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False)
83
+
84
+
85
+ def canonical_hash(value):
86
+ return hashlib.sha256(canonical_dumps(value).encode("utf-8")).hexdigest()
87
+
88
+
89
+ def load_packet(base):
90
+ manifest = json.loads((base / "manifest.json").read_text(encoding="utf-8"))
91
+ receipt = json.loads((base / "receipt.json").read_text(encoding="utf-8"))
92
+ if not isinstance(manifest, dict):
93
+ raise ValueError("manifest.json must be a JSON object, got %s" % type(manifest).__name__)
94
+ if not isinstance(receipt, dict):
95
+ raise ValueError("receipt.json must be a JSON object, got %s" % type(receipt).__name__)
96
+ events = []
97
+ for line in (base / "ledger_slice.ndjson").read_text(encoding="utf-8").splitlines():
98
+ if line.strip():
99
+ event = json.loads(line)
100
+ if not isinstance(event, dict):
101
+ raise ValueError("each ledger_slice.ndjson line must be a JSON object, got %s" % type(event).__name__)
102
+ events.append(event)
103
+ return manifest, receipt, events
104
+
105
+
106
+ def verify_events(manifest, events, failures):
107
+ if manifest.get("schema_version") != SCHEMA_VERSION:
108
+ failures.append("MANIFEST_SCHEMA_MISMATCH")
109
+ if manifest.get("event_count") != len(events):
110
+ failures.append("EVENT_COUNT_MISMATCH: manifest=%r slice=%d" % (manifest.get("event_count"), len(events)))
111
+ if not events:
112
+ failures.append("EMPTY_LEDGER_SLICE")
113
+ return
114
+ if events[0].get("previous_event_hash") != manifest.get("chain_start_previous_event_hash"):
115
+ failures.append("CHAIN_START_MISMATCH")
116
+ previous_hash = None
117
+ for index, event in enumerate(events):
118
+ try:
119
+ material = {field: event[field] for field in EVENT_MATERIAL_FIELDS}
120
+ if canonical_hash(event["payload"]) != event["payload_hash"]:
121
+ failures.append("PAYLOAD_HASH_MISMATCH: event %d" % index)
122
+ expected_id = canonical_hash(dict(material, event_id_basis=EVENT_ID_BASIS))
123
+ if expected_id != event["event_id"]:
124
+ failures.append("EVENT_ID_MISMATCH: event %d" % index)
125
+ expected_hash = canonical_hash(dict(material, event_id=event["event_id"]))
126
+ if expected_hash != event["event_hash"]:
127
+ failures.append("EVENT_HASH_MISMATCH: event %d" % index)
128
+ if index > 0 and event["previous_event_hash"] != previous_hash:
129
+ failures.append("CHAIN_BROKEN: event %d" % index)
130
+ previous_hash = event["event_hash"]
131
+ except Exception as exc:
132
+ failures.append("MALFORMED_EVENT: event %d: %s" % (index, exc))
133
+ return
134
+ action_id = manifest.get("action_id")
135
+ if not any(event.get("action_id") == action_id for event in events):
136
+ failures.append("ACTION_NOT_IN_SLICE: %r" % action_id)
137
+
138
+
139
+ def verify_receipt(manifest, receipt, events, failures, crypto):
140
+ unsigned = dict(receipt)
141
+ signature = unsigned.pop("signature", "")
142
+ # tsa_anchor is stapled onto a receipt AFTER signing -- the signature
143
+ # covers the receipt's signing bytes, which exclude it -- so it must
144
+ # be excluded here too, the same way "signature" itself is.
145
+ unsigned.pop("tsa_anchor", None)
146
+ algorithm = receipt.get("algorithm") or ALGORITHM_ED25519
147
+ try:
148
+ data = canonical_dumps(unsigned).encode("utf-8")
149
+ signature_bytes = bytes.fromhex(signature)
150
+ public_key_hex = manifest["receipt_public_key_hex"]
151
+ if algorithm == ALGORITHM_ED25519:
152
+ public_key = crypto["ed25519_public_key_cls"].from_public_bytes(bytes.fromhex(public_key_hex))
153
+ public_key.verify(signature_bytes, data)
154
+ elif algorithm == ALGORITHM_ECDSA_P256_SHA256:
155
+ ecdsa_public_key = crypto["load_der_public_key"](bytes.fromhex(public_key_hex))
156
+ ecdsa_public_key.verify(signature_bytes, data, crypto["ecdsa_sha256"])
157
+ else:
158
+ failures.append("RECEIPT_SIGNATURE_ALGORITHM_UNKNOWN: %r" % algorithm)
159
+ return
160
+ except (crypto["invalid_signature_error"], crypto["unsupported_algorithm_error"], ValueError, KeyError, TypeError):
161
+ failures.append("RECEIPT_SIGNATURE_INVALID")
162
+
163
+ bound_event = next(
164
+ (event for event in events if event.get("event_hash") == receipt.get("ledger_entry_hash")), None
165
+ )
166
+ if bound_event is None:
167
+ failures.append("RECEIPT_LEDGER_ENTRY_NOT_IN_SLICE")
168
+ return
169
+ if bound_event.get("action_id") != manifest.get("action_id"):
170
+ failures.append("RECEIPT_BOUND_TO_DIFFERENT_ACTION")
171
+ recorded_action_hash = bound_event.get("payload", {}).get("action_packet_hash")
172
+ if recorded_action_hash is not None and recorded_action_hash != receipt.get("action_hash"):
173
+ failures.append("RECEIPT_ACTION_HASH_MISMATCH")
174
+
175
+
176
+ def _load_doc(base, name, missing_code, failures):
177
+ path = base / name
178
+ if not path.exists():
179
+ failures.append(missing_code)
180
+ return None
181
+ try:
182
+ return json.loads(path.read_text(encoding="utf-8"))
183
+ except Exception as exc:
184
+ failures.append("%s: unreadable %s: %s" % (missing_code, name, exc))
185
+ return None
186
+
187
+
188
+ def _leaf_hash(data):
189
+ return hashlib.sha256(b"\x00" + data).digest()
190
+
191
+
192
+ def _node_hash(left, right):
193
+ return hashlib.sha256(b"\x01" + left + right).digest()
194
+
195
+
196
+ def _root_from_audit_path(leaf, index, tree_size, path):
197
+ """RFC 9162 section 2.1.3.2 inclusion-proof verification. Must stay
198
+ in lock-step with actaseal.anchoring._root_from_audit_path."""
199
+ if index < 0 or index >= tree_size:
200
+ raise ValueError("leaf index outside claimed tree size")
201
+ fn, sn = index, tree_size - 1
202
+ node = leaf
203
+ for sibling in path:
204
+ if sn == 0:
205
+ raise ValueError("audit path longer than the claimed tree allows")
206
+ if fn % 2 == 1 or fn == sn:
207
+ node = _node_hash(sibling, node)
208
+ if fn % 2 == 0:
209
+ while fn % 2 == 0 and fn != 0:
210
+ fn >>= 1
211
+ sn >>= 1
212
+ else:
213
+ node = _node_hash(node, sibling)
214
+ fn >>= 1
215
+ sn >>= 1
216
+ if sn != 0:
217
+ raise ValueError("audit path shorter than the claimed tree requires")
218
+ return node
219
+
220
+
221
+ def _largest_pow2_lt(n):
222
+ split = 1
223
+ while split * 2 < n:
224
+ split *= 2
225
+ return split
226
+
227
+
228
+ def _verify_consistency_nodes(m, n, proof):
229
+ """Must stay in lock-step with actaseal.anchoring._verify_consistency_nodes."""
230
+ if m == n:
231
+ h = proof[0]
232
+ return h, h
233
+ k = _largest_pow2_lt(n)
234
+ if m <= k:
235
+ old_h, new_h_left = _verify_consistency_nodes(m, k, proof[:-1])
236
+ new_h = _node_hash(new_h_left, proof[-1])
237
+ else:
238
+ old_h_right, new_h_right = _verify_consistency_nodes(m - k, n - k, proof[:-1])
239
+ old_h = _node_hash(proof[-1], old_h_right)
240
+ new_h = _node_hash(proof[-1], new_h_right)
241
+ return old_h, new_h
242
+
243
+
244
+ def _sth_signing_bytes(sth):
245
+ return canonical_dumps(
246
+ {
247
+ "log_id": sth.get("log_id"),
248
+ "tree_size": sth.get("tree_size"),
249
+ "root_hash": sth.get("root_hash"),
250
+ "timestamp": sth.get("timestamp"),
251
+ }
252
+ ).encode("utf-8")
253
+
254
+
255
+ def _verify_sth_signature(sth, public_key_hex, crypto):
256
+ """Must stay in lock-step with actaseal.anchoring.verify_tree_head /
257
+ actaseal.receipt.verify_signature_bytes's Ed25519/ECDSA branches."""
258
+ algorithm = sth.get("algorithm") or ALGORITHM_ED25519
259
+ try:
260
+ data = _sth_signing_bytes(sth)
261
+ signature_bytes = bytes.fromhex(sth.get("signature", ""))
262
+ if algorithm == ALGORITHM_ED25519:
263
+ public_key = crypto["ed25519_public_key_cls"].from_public_bytes(bytes.fromhex(public_key_hex))
264
+ public_key.verify(signature_bytes, data)
265
+ elif algorithm == ALGORITHM_ECDSA_P256_SHA256:
266
+ ecdsa_public_key = crypto["load_der_public_key"](bytes.fromhex(public_key_hex))
267
+ ecdsa_public_key.verify(signature_bytes, data, crypto["ecdsa_sha256"])
268
+ else:
269
+ return False
270
+ except (
271
+ crypto["invalid_signature_error"],
272
+ crypto["unsupported_algorithm_error"],
273
+ ValueError,
274
+ KeyError,
275
+ TypeError,
276
+ ):
277
+ return False
278
+ return True
279
+
280
+
281
+ def _compute_receipt_hash(receipt):
282
+ """Must stay in lock-step with actaseal.receipt.receipt_hash /
283
+ signing_bytes: sha256 over the canonical receipt payload minus
284
+ signature and tsa_anchor (the latter is stapled AFTER signing)."""
285
+ unsigned = dict(receipt)
286
+ unsigned.pop("signature", None)
287
+ unsigned.pop("tsa_anchor", None)
288
+ return hashlib.sha256(canonical_dumps(unsigned).encode("utf-8")).hexdigest()
289
+
290
+
291
+ def verify_continuity_checkpoint(base, receipt, failures, crypto):
292
+ """T8 (ONESHOT-4 batch 3): optional, additive check -- silent no-op
293
+ when checkpoint.json is absent, same posture as --anchors. When a
294
+ continuity-export bundle includes checkpoint.json (a signed
295
+ SignedTreeHead) and inclusion_proof.json, confirms: the checkpoint's
296
+ own signature verifies against the public key it ships alongside;
297
+ this receipt's hash is included under that checkpoint's root (RFC
298
+ 6962 audit-path math); and the inclusion proof's claimed
299
+ root/tree_size actually match the signed checkpoint, not some other
300
+ one. When consistency_proof.json is also present (bridging to an
301
+ older trusted checkpoint), its own math is checked too."""
302
+ checkpoint_path = base / "checkpoint.json"
303
+ if not checkpoint_path.exists():
304
+ return
305
+ checkpoint = _load_doc(base, "checkpoint.json", "CHECKPOINT_DOC_MISSING", failures)
306
+ if checkpoint is None:
307
+ return
308
+ sth = checkpoint.get("sth")
309
+ sth_public_key_hex = checkpoint.get("sth_public_key_hex")
310
+ if not isinstance(sth, dict) or not sth_public_key_hex:
311
+ failures.append("CHECKPOINT_DOC_MALFORMED: checkpoint.json is missing sth or sth_public_key_hex")
312
+ return
313
+ if not _verify_sth_signature(sth, sth_public_key_hex, crypto):
314
+ failures.append(
315
+ "%s:checkpoint.json's signed tree head does not verify against its own public key" % STH_SIGNATURE_INVALID
316
+ )
317
+
318
+ proof = _load_doc(base, "inclusion_proof.json", "INCLUSION_PROOF_MISSING", failures)
319
+ if proof is None:
320
+ return
321
+
322
+ receipt_hash_value = _compute_receipt_hash(receipt)
323
+ expected_leaf = _leaf_hash(receipt_hash_value.encode("utf-8")).hex()
324
+ if proof.get("leaf_hash") != expected_leaf:
325
+ failures.append(
326
+ "%s:inclusion_proof.leaf_hash does not commit to this receipt's hash" % ANCHOR_INCLUSION_PROOF_INVALID
327
+ )
328
+ else:
329
+ try:
330
+ computed = _root_from_audit_path(
331
+ bytes.fromhex(proof["leaf_hash"]),
332
+ int(proof["entry_id"]),
333
+ int(proof["sth_tree_size"]),
334
+ [bytes.fromhex(node) for node in proof["audit_path"]],
335
+ )
336
+ if computed.hex() != proof.get("sth_root"):
337
+ failures.append(
338
+ "%s:inclusion_proof audit path does not reproduce sth_root" % ANCHOR_INCLUSION_PROOF_INVALID
339
+ )
340
+ except (ValueError, TypeError, KeyError) as exc:
341
+ failures.append("%s:inclusion_proof is malformed: %s" % (ANCHOR_INCLUSION_PROOF_INVALID, exc))
342
+
343
+ if proof.get("sth_root") != sth.get("root_hash") or proof.get("sth_tree_size") != sth.get("tree_size"):
344
+ failures.append(
345
+ "%s:inclusion_proof's checkpoint (root=%r, tree_size=%r) does not match "
346
+ "checkpoint.json's signed tree head (root=%r, tree_size=%r)"
347
+ % (
348
+ ANCHOR_CHECKPOINT_MISMATCH,
349
+ proof.get("sth_root"),
350
+ proof.get("sth_tree_size"),
351
+ sth.get("root_hash"),
352
+ sth.get("tree_size"),
353
+ )
354
+ )
355
+
356
+ consistency_path = base / "consistency_proof.json"
357
+ if not consistency_path.exists():
358
+ return
359
+ cproof = _load_doc(base, "consistency_proof.json", "CONSISTENCY_PROOF_MISSING", failures)
360
+ if cproof is None:
361
+ return
362
+ m, n = cproof.get("old_tree_size"), cproof.get("new_tree_size")
363
+ try:
364
+ m, n = int(m), int(n)
365
+ except (TypeError, ValueError):
366
+ failures.append("%s:consistency_proof has non-integer tree sizes" % ANCHOR_CONSISTENCY_PROOF_INVALID)
367
+ return
368
+ if m < 0 or n < 0 or m > n:
369
+ failures.append("%s:consistency_proof has an invalid tree-size relationship" % ANCHOR_CONSISTENCY_PROOF_INVALID)
370
+ return
371
+ if m == 0:
372
+ if cproof.get("proof"):
373
+ failures.append(
374
+ "%s:consistency_proof with old_tree_size=0 must carry no proof nodes"
375
+ % ANCHOR_CONSISTENCY_PROOF_INVALID
376
+ )
377
+ return
378
+ if m == n:
379
+ if cproof.get("proof") or cproof.get("old_root") != cproof.get("new_root"):
380
+ failures.append(
381
+ "%s:consistency_proof for equal tree sizes must have no proof nodes and matching roots"
382
+ % ANCHOR_CONSISTENCY_PROOF_INVALID
383
+ )
384
+ return
385
+ if not cproof.get("proof"):
386
+ failures.append("%s:consistency_proof is missing required proof nodes" % ANCHOR_CONSISTENCY_PROOF_INVALID)
387
+ return
388
+ try:
389
+ nodes = [bytes.fromhex(node) for node in cproof["proof"]]
390
+ old_hash, new_hash = _verify_consistency_nodes(m, n, nodes)
391
+ except (ValueError, TypeError, IndexError, KeyError):
392
+ failures.append("%s:consistency_proof is malformed" % ANCHOR_CONSISTENCY_PROOF_INVALID)
393
+ return
394
+ if old_hash.hex() != cproof.get("old_root"):
395
+ failures.append("%s:consistency_proof does not reproduce old_root" % ANCHOR_CONSISTENCY_PROOF_INVALID)
396
+ if new_hash.hex() != cproof.get("new_root"):
397
+ failures.append("%s:consistency_proof does not reproduce new_root" % ANCHOR_CONSISTENCY_PROOF_INVALID)
398
+
399
+
400
+ def verify_authentication_docs(receipt, events, base, failures):
401
+ """FRE 901(b)(9) / 902(13)-(14) posture: the acquisition report,
402
+ chain-of-custody doc, and authentication statement must be present
403
+ and internally consistent with the ledger slice and receipt."""
404
+ acquisition = _load_doc(base, "acquisition.json", "ACQUISITION_REPORT_MISSING", failures)
405
+ custody = _load_doc(base, "custody.json", "CUSTODY_DOC_MISSING", failures)
406
+ authentication = _load_doc(
407
+ base, "authentication.json", "AUTHENTICATION_STATEMENT_MISSING", failures
408
+ )
409
+ slice_hashes = set(event.get("event_hash") for event in events)
410
+
411
+ if acquisition is not None:
412
+ tool = acquisition.get("tool") or {}
413
+ if not tool.get("name") or not tool.get("version"):
414
+ failures.append("ACQUISITION_TOOL_UNDECLARED: acquisition.json lacks tool name+version")
415
+ if not acquisition.get("clock_source"):
416
+ failures.append("ACQUISITION_CLOCK_SOURCE_UNDECLARED: acquisition.json")
417
+ if not acquisition.get("acquired_at"):
418
+ failures.append("ACQUISITION_TIME_UNDECLARED: acquisition.json")
419
+
420
+ if custody is not None:
421
+ custody_events = custody.get("custody_events") or []
422
+ if not custody_events:
423
+ failures.append("CUSTODY_EMPTY: custody.json records no custody events")
424
+ timestamps = [str(event.get("at") or "") for event in custody_events]
425
+ if timestamps != sorted(timestamps):
426
+ failures.append("CUSTODY_ORDER_INVALID: custody.json events are not time-ordered")
427
+ for index, event in enumerate(custody_events):
428
+ if event.get("ledger_event_hash") not in slice_hashes:
429
+ failures.append(
430
+ "CUSTODY_EVENT_UNBOUND: custody.json event %d is not bound to a "
431
+ "ledger event hash in the slice" % index
432
+ )
433
+
434
+ if authentication is not None:
435
+ if authentication.get("hash_algorithm") != "sha256":
436
+ failures.append("AUTHENTICATION_HASH_ALGO_MISMATCH: authentication.json")
437
+ for doc_field, receipt_field in (
438
+ ("signer_key_id", "key_id"),
439
+ ("signer_pubkey_hash", "signer_pubkey_hash"),
440
+ ("mandate_hash", "mandate_hash"),
441
+ ):
442
+ if authentication.get(doc_field) != receipt.get(receipt_field):
443
+ failures.append(
444
+ "AUTHENTICATION_%s_MISMATCH: authentication.json diverges from receipt"
445
+ % doc_field.upper()
446
+ )
447
+ if acquisition is not None:
448
+ anchor = acquisition.get("external_anchor") or {}
449
+ if authentication.get("external_anchor_log_id") != anchor.get("log_id"):
450
+ failures.append(
451
+ "AUTHENTICATION_ANCHOR_LOG_MISMATCH: authentication.json vs acquisition.json"
452
+ )
453
+
454
+
455
+ def _scope_headline(scope_conformance):
456
+ # must stay in lock-step with actaseal.dispute.packet.scope_headline
457
+ if scope_conformance is None:
458
+ return "not_evaluated"
459
+ if scope_conformance.get("verdict") == "IN_SCOPE":
460
+ return "in_scope"
461
+ dims = ",".join(
462
+ str(breach.get("dimension")) for breach in (scope_conformance.get("breaches") or [])
463
+ )
464
+ return "BREACH:%s" % dims
465
+
466
+
467
+ def verify_scope_conformance(manifest, receipt, events, failures):
468
+ """The headline scope verdict must be present and consistent all the
469
+ way down: manifest headline == receipt scope_conformance == the
470
+ ScopeEvaluated ledger event (verdict, breach dimensions, and the
471
+ recorded scope/action hashes recomputed from the recorded inputs)."""
472
+ if "scope_conformance_headline" not in manifest:
473
+ failures.append("SCOPE_HEADLINE_MISSING: manifest.json")
474
+ else:
475
+ expected = _scope_headline(receipt.get("scope_conformance"))
476
+ if manifest["scope_conformance_headline"] != expected:
477
+ failures.append(
478
+ "SCOPE_HEADLINE_MISMATCH: manifest.json says %r, receipt derives %r"
479
+ % (manifest["scope_conformance_headline"], expected)
480
+ )
481
+
482
+ # ledger_slice.ndjson is the CONTIGUOUS span between this action's
483
+ # first and last event (see actaseal.dispute.packet.
484
+ # extract_ledger_slice) -- by design, that span can include OTHER
485
+ # actions' events interleaved in between (e.g. a BREACH acknowledged
486
+ # after a different action scope-evaluated in between). Scoping by
487
+ # action_id here is required so a foreign ScopeEvaluated event never
488
+ # gets compared against this receipt's own scope_conformance.
489
+ action_id = manifest.get("action_id")
490
+ scope_events = [
491
+ event
492
+ for event in events
493
+ if event.get("event_type") == "ScopeEvaluated" and event.get("action_id") == action_id
494
+ ]
495
+ result = receipt.get("scope_conformance")
496
+ if result is not None and not scope_events:
497
+ failures.append(
498
+ "SCOPE_EVENT_MISSING: receipt.json claims a scope conformance the "
499
+ "ledger_slice.ndjson never witnessed (no ScopeEvaluated event)"
500
+ )
501
+ if result is None and scope_events:
502
+ failures.append(
503
+ "SCOPE_RESULT_MISSING: receipt.json carries no scope_conformance but "
504
+ "ledger_slice.ndjson records a ScopeEvaluated event"
505
+ )
506
+ if result is not None and scope_events:
507
+ payload = scope_events[-1].get("payload", {})
508
+ if payload.get("verdict") != result.get("verdict"):
509
+ failures.append("SCOPE_VERDICT_MISMATCH: receipt.json vs ledger_slice.ndjson")
510
+ event_dims = [str(dim) for dim in (payload.get("breach_dimensions") or [])]
511
+ receipt_dims = [
512
+ str(breach.get("dimension")) for breach in (result.get("breaches") or [])
513
+ ]
514
+ if event_dims != receipt_dims:
515
+ failures.append(
516
+ "SCOPE_DIMENSIONS_MISMATCH: receipt.json breaches %r vs ledger %r"
517
+ % (receipt_dims, event_dims)
518
+ )
519
+ for hash_field, source_field in (("scope_hash", "intent_scope"), ("action_hash", "executed_action")):
520
+ source = payload.get(source_field)
521
+ if source is None or payload.get(hash_field) != canonical_hash(source):
522
+ failures.append(
523
+ "SCOPE_HASH_MISMATCH: ScopeEvaluated %s does not recompute from its recorded %s"
524
+ % (hash_field, source_field)
525
+ )
526
+ elif result.get(hash_field) != payload.get(hash_field):
527
+ failures.append(
528
+ "SCOPE_HASH_MISMATCH: receipt.json %s diverges from ledger" % hash_field
529
+ )
530
+
531
+
532
+ def verify_approver_snapshot(manifest, receipt, events, failures):
533
+ """When present, the receipt's approver_snapshot_hash must recompute
534
+ from an ApproverSnapshotCaptured ledger event for this action --
535
+ additive: a receipt that predates this field (approver_snapshot_hash
536
+ is None) is not checked at all, and stays valid either way. This is
537
+ the frozen record of exactly what the human approver saw (scope-vs-
538
+ action comparison, TTL remaining, request state) at decision time."""
539
+ snapshot_hash = receipt.get("approver_snapshot_hash")
540
+ if snapshot_hash is None:
541
+ return
542
+
543
+ action_id = manifest.get("action_id")
544
+ snapshot_events = [
545
+ event
546
+ for event in events
547
+ if event.get("event_type") == "ApproverSnapshotCaptured" and event.get("action_id") == action_id
548
+ ]
549
+ if not snapshot_events:
550
+ failures.append(
551
+ "APPROVER_SNAPSHOT_EVENT_MISSING: receipt.json claims an approver_snapshot_hash "
552
+ "the ledger_slice.ndjson never witnessed (no ApproverSnapshotCaptured event)"
553
+ )
554
+ return
555
+ payload = snapshot_events[-1].get("payload", {})
556
+ if canonical_hash(payload) != snapshot_hash:
557
+ failures.append(
558
+ "APPROVER_SNAPSHOT_HASH_MISMATCH: ApproverSnapshotCaptured payload does not "
559
+ "recompute to receipt.json's approver_snapshot_hash"
560
+ )
561
+
562
+
563
+ def verify_ledger_head_anchor(base, failures, anchors_path):
564
+ """Given an external anchor log (a jsonl file of {root_hash,
565
+ anchored_at, status, ...} records -- see
566
+ actaseal.ledger_anchor.FileAnchorBackend / scripts/publish_anchor.py),
567
+ confirms this packet's ledger_root_hash (acquisition.json) was
568
+ witnessed by some successful anchor entry. Optional: only runs when
569
+ --anchors PATH is passed on the command line -- a packet does not
570
+ ship its own anchor log, since anchoring is a separate, periodic
571
+ operator workflow, not part of packet capture. Silent no-op when
572
+ --anchors is not given, same posture as every other optional check
573
+ in this verifier."""
574
+ if anchors_path is None:
575
+ return
576
+ acquisition = _load_doc(base, "acquisition.json", "ACQUISITION_REPORT_MISSING", [])
577
+ root_hash = acquisition.get("ledger_root_hash") if acquisition else None
578
+ if not root_hash:
579
+ failures.append(
580
+ "ANCHOR_CHECK_NO_LEDGER_ROOT_HASH: acquisition.json carries no ledger_root_hash to check "
581
+ "against the supplied anchor log"
582
+ )
583
+ return
584
+ try:
585
+ lines = Path(anchors_path).read_text(encoding="utf-8").splitlines()
586
+ except OSError as exc:
587
+ failures.append("ANCHOR_LOG_UNREADABLE: %s" % exc)
588
+ return
589
+ for line in lines:
590
+ line = line.strip()
591
+ if not line:
592
+ continue
593
+ try:
594
+ entry = json.loads(line)
595
+ except ValueError:
596
+ continue
597
+ if entry.get("root_hash") == root_hash and entry.get("status") == "OK":
598
+ return
599
+ failures.append(
600
+ "ANCHOR_ENTRY_NOT_FOUND: no successful anchor entry in %s witnesses this packet's "
601
+ "ledger_root_hash %r" % (anchors_path, root_hash)
602
+ )
603
+
604
+
605
+ def verify_settlement_anchor(manifest, failures):
606
+ """The settlement anchor block must be present -- absence of a
607
+ settlement is itself stated as SETTLEMENT_UNANCHORED, never silent --
608
+ and an anchored block's anchor_hash must recompute from its content."""
609
+ block = manifest.get("settlement_anchor")
610
+ if block is None:
611
+ failures.append(
612
+ "SETTLEMENT_FIELD_MISSING: manifest.json carries no settlement_anchor "
613
+ "block (even an unanchored packet must state SETTLEMENT_UNANCHORED)"
614
+ )
615
+ return
616
+ status = block.get("status")
617
+ if status == "SETTLEMENT_UNANCHORED":
618
+ if set(block) != {"status"}:
619
+ failures.append(
620
+ "SETTLEMENT_ANCHOR_INVALID: unanchored block carries extra fields %r"
621
+ % sorted(set(block) - {"status"})
622
+ )
623
+ return
624
+ if status != "anchored":
625
+ failures.append("SETTLEMENT_ANCHOR_INVALID: unknown status %r" % status)
626
+ return
627
+ anchor = block.get("anchor")
628
+ if not isinstance(anchor, dict):
629
+ failures.append("SETTLEMENT_ANCHOR_INVALID: anchored block has no anchor content")
630
+ return
631
+ if block.get("anchor_hash") != canonical_hash(anchor):
632
+ failures.append(
633
+ "SETTLEMENT_ANCHOR_HASH_MISMATCH: anchor_hash does not recompute from "
634
+ "the anchor content in manifest.json"
635
+ )
636
+
637
+
638
+ def main(argv):
639
+ try:
640
+ from cryptography.exceptions import InvalidSignature, UnsupportedAlgorithm
641
+ from cryptography.hazmat.primitives import hashes
642
+ from cryptography.hazmat.primitives.asymmetric import ec
643
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
644
+ from cryptography.hazmat.primitives.serialization import load_der_public_key
645
+ except ImportError:
646
+ print("UNABLE_TO_RUN: the 'cryptography' package is required (pip install cryptography)")
647
+ return 2
648
+ crypto = {
649
+ "ed25519_public_key_cls": Ed25519PublicKey,
650
+ "invalid_signature_error": InvalidSignature,
651
+ "unsupported_algorithm_error": UnsupportedAlgorithm,
652
+ "load_der_public_key": load_der_public_key,
653
+ "ecdsa_sha256": ec.ECDSA(hashes.SHA256()),
654
+ }
655
+
656
+ # --anchors PATH is an optional flag, stripped out before the
657
+ # positional packet_dir argument is resolved -- it can appear
658
+ # anywhere in argv (before or after packet_dir).
659
+ positional = []
660
+ anchors_path = None
661
+ args = list(argv[1:])
662
+ while args:
663
+ arg = args.pop(0)
664
+ if arg == "--anchors":
665
+ if not args:
666
+ print("UNABLE_TO_RUN: --anchors requires a path argument")
667
+ return 2
668
+ anchors_path = args.pop(0)
669
+ else:
670
+ positional.append(arg)
671
+
672
+ base = Path(positional[0]) if positional else Path(__file__).resolve().parent
673
+ failures = []
674
+ try:
675
+ manifest, receipt, events = load_packet(base)
676
+ except Exception as exc:
677
+ print("VERIFICATION FAILED")
678
+ print(" UNREADABLE_PACKET: %s" % exc)
679
+ return 1
680
+
681
+ verify_events(manifest, events, failures)
682
+ verify_receipt(manifest, receipt, events, failures, crypto)
683
+ verify_continuity_checkpoint(base, receipt, failures, crypto)
684
+ verify_authentication_docs(receipt, events, base, failures)
685
+ verify_scope_conformance(manifest, receipt, events, failures)
686
+ verify_approver_snapshot(manifest, receipt, events, failures)
687
+ verify_ledger_head_anchor(base, failures, anchors_path)
688
+ verify_settlement_anchor(manifest, failures)
689
+
690
+ if failures:
691
+ print("VERIFICATION FAILED")
692
+ for failure in failures:
693
+ print(" " + failure)
694
+ return 1
695
+ print("VERIFIED: %d ledger events, receipt signature valid, chain intact" % len(events))
696
+ print(" action_id: %s" % manifest.get("action_id"))
697
+ print(" decision: %s (%s)" % (receipt.get("decision"), receipt.get("reason_code")))
698
+ return 0
699
+
700
+
701
+ if __name__ == "__main__":
702
+ sys.exit(main(sys.argv))