nomosprotocol 0.2.0__tar.gz → 0.3.0__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.
Files changed (24) hide show
  1. nomosprotocol-0.3.0/LICENSE +202 -0
  2. {nomosprotocol-0.2.0 → nomosprotocol-0.3.0}/PKG-INFO +8 -5
  3. {nomosprotocol-0.2.0 → nomosprotocol-0.3.0}/README.md +3 -2
  4. {nomosprotocol-0.2.0 → nomosprotocol-0.3.0}/nomosprotocol/__init__.py +8 -4
  5. nomosprotocol-0.3.0/nomosprotocol/budgets.py +633 -0
  6. {nomosprotocol-0.2.0 → nomosprotocol-0.3.0}/nomosprotocol.egg-info/PKG-INFO +8 -5
  7. {nomosprotocol-0.2.0 → nomosprotocol-0.3.0}/nomosprotocol.egg-info/SOURCES.txt +2 -0
  8. {nomosprotocol-0.2.0 → nomosprotocol-0.3.0}/pyproject.toml +3 -3
  9. {nomosprotocol-0.2.0 → nomosprotocol-0.3.0}/nomosprotocol/accept.py +0 -0
  10. {nomosprotocol-0.2.0 → nomosprotocol-0.3.0}/nomosprotocol/act.py +0 -0
  11. {nomosprotocol-0.2.0 → nomosprotocol-0.3.0}/nomosprotocol/bindings.py +0 -0
  12. {nomosprotocol-0.2.0 → nomosprotocol-0.3.0}/nomosprotocol/carrier.py +0 -0
  13. {nomosprotocol-0.2.0 → nomosprotocol-0.3.0}/nomosprotocol/chain.py +0 -0
  14. {nomosprotocol-0.2.0 → nomosprotocol-0.3.0}/nomosprotocol/issuer.py +0 -0
  15. {nomosprotocol-0.2.0 → nomosprotocol-0.3.0}/nomosprotocol/jcs.py +0 -0
  16. {nomosprotocol-0.2.0 → nomosprotocol-0.3.0}/nomosprotocol/registrar.py +0 -0
  17. {nomosprotocol-0.2.0 → nomosprotocol-0.3.0}/nomosprotocol/statements.py +0 -0
  18. {nomosprotocol-0.2.0 → nomosprotocol-0.3.0}/nomosprotocol/suites.py +0 -0
  19. {nomosprotocol-0.2.0 → nomosprotocol-0.3.0}/nomosprotocol/witness.py +0 -0
  20. {nomosprotocol-0.2.0 → nomosprotocol-0.3.0}/nomosprotocol.egg-info/dependency_links.txt +0 -0
  21. {nomosprotocol-0.2.0 → nomosprotocol-0.3.0}/nomosprotocol.egg-info/requires.txt +0 -0
  22. {nomosprotocol-0.2.0 → nomosprotocol-0.3.0}/nomosprotocol.egg-info/top_level.txt +0 -0
  23. {nomosprotocol-0.2.0 → nomosprotocol-0.3.0}/setup.cfg +0 -0
  24. {nomosprotocol-0.2.0 → nomosprotocol-0.3.0}/tests/test_sdk.py +0 -0
@@ -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.
@@ -1,22 +1,24 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: nomosprotocol
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: NOMOS for Python: the reference verifiers for NOMOS-SPEC-007 (rev. 1.11), -008 and -010, NOMOS-SPEC-014 registrar logs, and accept(), act() and witness() for NOMOS-SPEC-009. Verify an Act, commit it exactly once, carry one, or sign the facts it needs.
5
5
  Author-email: NOMOS Protocol <hello@nomosprotocol.com>
6
- License: MIT
6
+ License: Apache-2.0
7
7
  Project-URL: Homepage, https://www.computableauthority.com
8
8
  Project-URL: Specification, https://github.com/nomos-spec/spec
9
9
  Keywords: nomos,computable-authority,agents,authorization,verifier,ed25519,es256,webauthn
10
10
  Classifier: Programming Language :: Python :: 3
11
- Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
12
  Classifier: Operating System :: OS Independent
13
13
  Classifier: Topic :: Security :: Cryptography
14
14
  Requires-Python: >=3.9
15
15
  Description-Content-Type: text/markdown
16
+ License-File: LICENSE
16
17
  Requires-Dist: cryptography>=43
17
18
  Provides-Extra: postgres
18
19
  Requires-Dist: psycopg[binary]>=3.1; extra == "postgres"
19
20
  Requires-Dist: psycopg-pool>=3.2; extra == "postgres"
21
+ Dynamic: license-file
20
22
 
21
23
  # nomosprotocol
22
24
 
@@ -110,7 +112,8 @@ chain.verify_revocation_list(lst, ROOT, now) # NOMOS-SPEC-007 rev. 1.10
110
112
 
111
113
  This package is checked against:
112
114
  - every vector of NOMOS-SPEC-007 (1.7.0, rev. 1.11, rev. 1.10 revocation sources), NOMOS-SPEC-008
113
- 0.6.0 and NOMOS-SPEC-010 0.2.0;
115
+ 0.7.0 with rev. 0.8.0 (several laws) and rev. 0.9.0 (intake questions), NOMOS-SPEC-010 0.2.0 and
116
+ NOMOS-SPEC-016 0.1.0 (budgets: 200 of 200, `budget-vectors/check.py`);
114
117
  - the NOMOS-SPEC-009 selection vectors;
115
118
  - the NOMOS-SPEC-009 HTTP runner, 17 of 17, with `accept()` behind it
116
119
  (`python/tests/conformance_rp.py`).
@@ -118,4 +121,4 @@ This package is checked against:
118
121
  `act()` also interoperates with the JavaScript sandbox, escalation and approval included
119
122
  (`python/tests/interop_sandbox.py`).
120
123
 
121
- MIT licensed.
124
+ Licensed under the [Apache License 2.0](LICENSE). NOMOS Protocol and Computable Authority are trademarks of SafeHaven LLC ([TRADEMARKS.md](../TRADEMARKS.md)).
@@ -90,7 +90,8 @@ chain.verify_revocation_list(lst, ROOT, now) # NOMOS-SPEC-007 rev. 1.10
90
90
 
91
91
  This package is checked against:
92
92
  - every vector of NOMOS-SPEC-007 (1.7.0, rev. 1.11, rev. 1.10 revocation sources), NOMOS-SPEC-008
93
- 0.6.0 and NOMOS-SPEC-010 0.2.0;
93
+ 0.7.0 with rev. 0.8.0 (several laws) and rev. 0.9.0 (intake questions), NOMOS-SPEC-010 0.2.0 and
94
+ NOMOS-SPEC-016 0.1.0 (budgets: 200 of 200, `budget-vectors/check.py`);
94
95
  - the NOMOS-SPEC-009 selection vectors;
95
96
  - the NOMOS-SPEC-009 HTTP runner, 17 of 17, with `accept()` behind it
96
97
  (`python/tests/conformance_rp.py`).
@@ -98,4 +99,4 @@ This package is checked against:
98
99
  `act()` also interoperates with the JavaScript sandbox, escalation and approval included
99
100
  (`python/tests/interop_sandbox.py`).
100
101
 
101
- MIT licensed.
102
+ Licensed under the [Apache License 2.0](LICENSE). NOMOS Protocol and Computable Authority are trademarks of SafeHaven LLC ([TRADEMARKS.md](../TRADEMARKS.md)).
@@ -15,7 +15,8 @@ checked with, so there is no second implementation to drift from the reference.
15
15
 
16
16
  Modules: jcs (RFC 8785), suites (NOMOS-SPEC-010), chain (NOMOS-SPEC-007), act (NOMOS-SPEC-008),
17
17
  statements, accept, carrier, witness, issuer, bindings (NOMOS-SPEC-011 tool bindings: parse, apply, digest),
18
- registrar (NOMOS-SPEC-014 0.4.0 registrar logs: verify, fold, DNS discovery, world assembly).
18
+ registrar (NOMOS-SPEC-014 0.4.0 registrar logs: verify, fold, DNS discovery, world assembly),
19
+ budgets (NOMOS-SPEC-016: declarations, periods, derivation, facts, ledgers).
19
20
  """
20
21
  from .act import verify_act, evaluate, binding_digest
21
22
  from .chain import resolve, verify_revocation_list, fingerprint
@@ -28,12 +29,15 @@ from .statements import (
28
29
  from .accept import accept, RelyingParty, MemoryStore, postgres_store, RevocationUnavailable, status_for, ACT_MEDIA_TYPE
29
30
  from .carrier import act, NomosActError, fetch_document
30
31
  from .witness import witness, Witness
32
+ from . import budgets
31
33
  from .issuer import issuer, Issuer
32
34
  from . import registrar
33
35
  from .registrar import verify_registrar_log, fold_registrar_log, load_registrar_world, discover as discover_registrar_log
34
36
 
35
- __version__ = "0.2.0"
37
+ __version__ = "0.3.0"
36
38
  SPECIFICATIONS = {
37
- "NOMOS-SPEC-001": "2.2.0 + amendment 2.3.0", "NOMOS-SPEC-007": "rev. 1.11.0", "NOMOS-SPEC-008": "0.6.0",
38
- "NOMOS-SPEC-009": "0.2.0", "NOMOS-SPEC-010": "0.2.0", "NOMOS-SPEC-014": "0.4.0 (registrar logs)",
39
+ "NOMOS-SPEC-001": "2.2.0 + amendments 2.3.0, 2.6.0 (budgets)", "NOMOS-SPEC-007": "rev. 1.11.0",
40
+ "NOMOS-SPEC-008": "0.7.0 + rev. 0.8.0 (several laws), rev. 0.9.0 (intake questions)",
41
+ "NOMOS-SPEC-009": "0.3.0", "NOMOS-SPEC-010": "0.2.0", "NOMOS-SPEC-014": "0.4.0 (registrar logs)",
42
+ "NOMOS-SPEC-016": "0.1.0",
39
43
  }
@@ -0,0 +1,633 @@
1
+ """NOMOS-SPEC-016 Budgets: the reference implementation.
2
+
3
+ Declaration validity (§3.3), budget identity (§3.4), periods (§4), what an act counts (§5), the facts
4
+ a ledger supplies (§6), state digests (§2.3), and a ledger with the operations of §7 to §9. The
5
+ vectors in budget-vectors/ are generated and checked with this module.
6
+
7
+ Instants are integers: milliseconds since 1970-01-01T00:00:00Z. `instant()` and `iso()` convert.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from datetime import date, datetime, timedelta, timezone
13
+ from typing import Any, Dict, List, Optional, Tuple
14
+ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError, available_timezones
15
+
16
+ from .jcs import jcs, sha256_hex
17
+
18
+ MAX_AMOUNT = 2 ** 53 - 1
19
+ PERIOD_KINDS = ("year", "quarter", "month", "day", "none")
20
+ FACT_KEYS = ("consumed_before", "remaining", "limit")
21
+
22
+ _ID = re.compile(r"^[a-z0-9][a-z0-9_.-]{0,63}$")
23
+ _CURRENCY = re.compile(r"^[A-Z]{3}$")
24
+ _SEGMENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
25
+ _EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
26
+ _DAY_MS = 86_400_000
27
+
28
+
29
+ # ── Instants ────────────────────────────────────────────────────────────────────────────────────
30
+ def instant(s: str) -> int:
31
+ """RFC 3339 UTC (…Z) → milliseconds."""
32
+ if not isinstance(s, str) or not s.endswith("Z"):
33
+ raise ValueError(f"not a UTC instant: {s!r}")
34
+ dt = datetime.fromisoformat(s[:-1] + "+00:00")
35
+ return (dt - _EPOCH) // timedelta(milliseconds=1)
36
+
37
+
38
+ def iso(ms: int) -> str:
39
+ dt = _EPOCH + timedelta(milliseconds=ms)
40
+ return dt.strftime("%Y-%m-%dT%H:%M:%S.") + f"{ms % 1000:03d}Z"
41
+
42
+
43
+ def is_amount(v: Any) -> bool:
44
+ return isinstance(v, int) and not isinstance(v, bool) and 0 <= v <= MAX_AMOUNT
45
+
46
+
47
+ # ── §3.3 Validity ───────────────────────────────────────────────────────────────────────────────
48
+ def _is_path(p: Any) -> bool:
49
+ if not isinstance(p, str):
50
+ return False
51
+ if p == "action.subject":
52
+ return True
53
+ if not p.startswith("action.params."):
54
+ return False
55
+ segs = p[len("action.params."):].split(".")
56
+ return len(segs) >= 1 and all(_SEGMENT.match(s) for s in segs)
57
+
58
+
59
+ _ZONES: Optional[frozenset] = None
60
+
61
+
62
+ def _known_zone(z: Any) -> bool:
63
+ """An IANA time zone name exactly as the tz database spells it (case included)."""
64
+ global _ZONES
65
+ if _ZONES is None:
66
+ _ZONES = frozenset(available_timezones())
67
+ if not isinstance(z, str) or z not in _ZONES:
68
+ return False
69
+ try:
70
+ ZoneInfo(z)
71
+ return True
72
+ except (ZoneInfoNotFoundError, ValueError):
73
+ return False
74
+
75
+
76
+ def validate_declaration(d: Any, relying_party: bool = False) -> Optional[str]:
77
+ """§3.1 and §3.3 rules 1 and 5 for one declaration. None when valid, else a reason."""
78
+ if not isinstance(d, dict):
79
+ return "not_an_object"
80
+ allowed = {"id", "applies_to", "unit", "limit", "period", "scope", "amount", "enforcement", "facts", "source"}
81
+ if relying_party:
82
+ allowed.add("authorities")
83
+ if set(d) - allowed:
84
+ return "unknown_member"
85
+ if not isinstance(d.get("id"), str) or not _ID.match(d["id"]):
86
+ return "invalid_id"
87
+ at = d.get("applies_to")
88
+ if not isinstance(at, list) or not at or not all(isinstance(x, str) and x for x in at) or len(set(at)) != len(at):
89
+ return "invalid_applies_to"
90
+ unit = d.get("unit")
91
+ if not isinstance(unit, dict):
92
+ return "invalid_unit"
93
+ if unit.get("kind") == "money":
94
+ if set(unit) != {"kind", "currency", "minor_units"}:
95
+ return "invalid_unit"
96
+ if not isinstance(unit["currency"], str) or not _CURRENCY.match(unit["currency"]):
97
+ return "invalid_unit"
98
+ mu = unit["minor_units"]
99
+ if not isinstance(mu, int) or isinstance(mu, bool) or not 0 <= mu <= 4:
100
+ return "invalid_unit"
101
+ elif unit.get("kind") == "count":
102
+ if set(unit) != {"kind"}:
103
+ return "invalid_unit"
104
+ else:
105
+ return "invalid_unit"
106
+ if not is_amount(d.get("limit")):
107
+ return "invalid_limit"
108
+ per = d.get("period")
109
+ if not isinstance(per, dict) or per.get("kind") not in PERIOD_KINDS:
110
+ return "invalid_period"
111
+ if per["kind"] == "none":
112
+ if set(per) != {"kind"}:
113
+ return "invalid_period"
114
+ else:
115
+ if set(per) != {"kind", "time_zone"}:
116
+ return "invalid_period"
117
+ if not _known_zone(per["time_zone"]):
118
+ return "invalid_time_zone"
119
+ sc = d.get("scope")
120
+ if not isinstance(sc, dict) or len(sc) != 1:
121
+ return "invalid_scope"
122
+ if "from" in sc:
123
+ if not _is_path(sc["from"]):
124
+ return "invalid_scope"
125
+ elif "fixed" in sc:
126
+ if not isinstance(sc["fixed"], str) or not sc["fixed"]:
127
+ return "invalid_scope"
128
+ else:
129
+ return "invalid_scope"
130
+ am = d.get("amount")
131
+ if unit["kind"] == "money":
132
+ if not isinstance(am, dict) or "from" not in am or set(am) - {"from", "currency_from"}:
133
+ return "invalid_amount"
134
+ if not _is_path(am["from"]) or ("currency_from" in am and not _is_path(am["currency_from"])):
135
+ return "invalid_amount"
136
+ elif am is not None:
137
+ if not isinstance(am, dict) or len(am) != 1:
138
+ return "invalid_amount"
139
+ if "from" in am:
140
+ if not _is_path(am["from"]):
141
+ return "invalid_amount"
142
+ elif "each" in am:
143
+ if not is_amount(am["each"]):
144
+ return "invalid_amount"
145
+ else:
146
+ return "invalid_amount"
147
+ if "enforcement" in d and d["enforcement"] not in ("hard", "advisory"):
148
+ return "invalid_enforcement"
149
+ if "facts" in d:
150
+ f = d["facts"]
151
+ if not isinstance(f, dict) or not f or set(f) - set(FACT_KEYS):
152
+ return "invalid_facts"
153
+ names = list(f.values())
154
+ if not all(isinstance(n, str) and n for n in names) or len(set(names)) != len(names):
155
+ return "invalid_facts"
156
+ if "source" in d:
157
+ s = d["source"]
158
+ if not isinstance(s, dict) or set(s) - {"document", "section", "text"} or not all(isinstance(v, str) for v in s.values()):
159
+ return "invalid_source"
160
+ if relying_party and "authorities" in d:
161
+ a = d["authorities"]
162
+ if not isinstance(a, list) or not a or not all(isinstance(x, str) and x for x in a) or len(set(a)) != len(a):
163
+ return "invalid_authorities"
164
+ return None
165
+
166
+
167
+ def _could_overlap(a: dict, b: dict) -> bool:
168
+ """§3.3 rule 3: can one act fall under both budgets? Same action type, and authorities that can meet."""
169
+ if not set(a["applies_to"]) & set(b["applies_to"]):
170
+ return False
171
+ aa, ba = a.get("authorities"), b.get("authorities")
172
+ return aa is None or ba is None or bool(set(aa) & set(ba))
173
+
174
+
175
+ def validate_budgets(budgets: Any, inputs: Optional[dict] = None, authority_budgets: Optional[list] = None,
176
+ relying_party: bool = False) -> Optional[str]:
177
+ """§3.3 for a declarer's whole set. `inputs` is the artifact's data_contract.inputs (authority sets);
178
+ `authority_budgets` the authority's own set, against which a relying party's set is checked."""
179
+ if not isinstance(budgets, list):
180
+ return "not_a_list"
181
+ for d in budgets:
182
+ r = validate_declaration(d, relying_party)
183
+ if r:
184
+ return r
185
+ ids = [d["id"] for d in budgets]
186
+ if len(set(ids)) != len(ids):
187
+ return "duplicate_id"
188
+ for i, a in enumerate(budgets):
189
+ for b in budgets[i + 1:]:
190
+ if _could_overlap(a, b) and set((a.get("facts") or {}).values()) & set((b.get("facts") or {}).values()):
191
+ return "fact_name_collision"
192
+ if authority_budgets:
193
+ taken = {n for ab in authority_budgets for n in (ab.get("facts") or {}).values()}
194
+ for d in budgets:
195
+ if set((d.get("facts") or {}).values()) & taken:
196
+ return "fact_name_collision"
197
+ if inputs is not None:
198
+ for d in budgets:
199
+ for name in (d.get("facts") or {}).values():
200
+ spec = inputs.get(name) if isinstance(inputs, dict) else None
201
+ if not isinstance(spec, dict) or spec.get("source") != "relying_party" or spec.get("type") != "number":
202
+ return "fact_not_declared"
203
+ return None
204
+
205
+
206
+ # ── §3.4 Keys and identity ──────────────────────────────────────────────────────────────────────
207
+ def budget_key(declaration: dict, artifact_id: Optional[str] = None) -> str:
208
+ return f"{artifact_id}#{declaration['id']}" if artifact_id is not None else f"rp:{declaration['id']}"
209
+
210
+
211
+ def amount_spec(d: dict) -> dict:
212
+ """The declaration's amount with defaults applied (§3.1)."""
213
+ am = d.get("amount")
214
+ if d["unit"]["kind"] == "money":
215
+ return {"from": am["from"], "currency_from": am.get("currency_from", "action.params.currency")}
216
+ return dict(am) if am is not None else {"each": 1}
217
+
218
+
219
+ def identity(d: dict) -> str:
220
+ return "sha256:" + sha256_hex(jcs({"unit": d["unit"], "period": d["period"], "scope": d["scope"], "amount": amount_spec(d)}))
221
+
222
+
223
+ # ── §4 Periods ──────────────────────────────────────────────────────────────────────────────────
224
+ def _offset_ms(ms: int, zone: ZoneInfo) -> int:
225
+ dt = (_EPOCH + timedelta(milliseconds=ms)).astimezone(zone)
226
+ return dt.utcoffset() // timedelta(milliseconds=1)
227
+
228
+
229
+ def _wall_ms(ms: int, zone: ZoneInfo) -> int:
230
+ """The local wall-clock time at `ms`, as milliseconds of the same reading taken as UTC."""
231
+ return ms + _offset_ms(ms, zone)
232
+
233
+
234
+ def local_date(ms: int, zone: ZoneInfo) -> date:
235
+ return (_EPOCH + timedelta(milliseconds=_wall_ms(ms, zone))).date()
236
+
237
+
238
+ def start_of_date(d: date, zone: ZoneInfo) -> int:
239
+ """§4: the instant local 00:00 of `d` occurs; the earlier if twice; the transition if never."""
240
+ w = (datetime(d.year, d.month, d.day, tzinfo=timezone.utc) - _EPOCH) // timedelta(milliseconds=1)
241
+ offsets = {_offset_ms(w + k * 3_600_000, zone) for k in range(-36, 37)}
242
+ valid = [w - o for o in offsets if _wall_ms(w - o, zone) == w]
243
+ if valid:
244
+ return min(valid)
245
+ lo, hi = w - max(offsets), w - min(offsets) # wall(lo) < w ≤ wall(hi) across one forward transition
246
+ while lo < hi:
247
+ mid = (lo + hi) // 2
248
+ if _wall_ms(mid, zone) >= w:
249
+ hi = mid
250
+ else:
251
+ lo = mid + 1
252
+ return lo
253
+
254
+
255
+ def _first_date(kind: str, d: date) -> date:
256
+ if kind == "year":
257
+ return date(d.year, 1, 1)
258
+ if kind == "quarter":
259
+ return date(d.year, 3 * ((d.month - 1) // 3) + 1, 1)
260
+ if kind == "month":
261
+ return date(d.year, d.month, 1)
262
+ return d
263
+
264
+
265
+ def _next_first(kind: str, first: date) -> date:
266
+ if kind == "year":
267
+ return date(first.year + 1, 1, 1)
268
+ if kind in ("quarter", "month"):
269
+ m = first.month + (3 if kind == "quarter" else 1)
270
+ return date(first.year + (m - 1) // 12, (m - 1) % 12 + 1, 1)
271
+ return first + timedelta(days=1)
272
+
273
+
274
+ def period_key(ms: int, period: dict) -> str:
275
+ kind = period["kind"]
276
+ if kind == "none":
277
+ return "all"
278
+ d = local_date(ms, ZoneInfo(period["time_zone"]))
279
+ if not 1900 <= d.year <= 9999:
280
+ raise ValueError("instant out of range")
281
+ if kind == "year":
282
+ return f"{d.year:04d}"
283
+ if kind == "quarter":
284
+ return f"{d.year:04d}-Q{(d.month - 1) // 3 + 1}"
285
+ if kind == "month":
286
+ return f"{d.year:04d}-{d.month:02d}"
287
+ return f"{d.year:04d}-{d.month:02d}-{d.day:02d}"
288
+
289
+
290
+ def period_of(ms: int, period: dict) -> dict:
291
+ """{key, starts_at, ends_at} for the period containing `ms` (§4)."""
292
+ key = period_key(ms, period)
293
+ if period["kind"] == "none":
294
+ return {"key": key}
295
+ zone = ZoneInfo(period["time_zone"])
296
+ first = _first_date(period["kind"], local_date(ms, zone))
297
+ return {"key": key, "starts_at": iso(start_of_date(first, zone)),
298
+ "ends_at": iso(start_of_date(_next_first(period["kind"], first), zone))}
299
+
300
+
301
+ # ── §5 What an act counts ───────────────────────────────────────────────────────────────────────
302
+ class Refusal(Exception):
303
+ def __init__(self, decision: str, reason_code: Optional[str] = None, **detail: Any):
304
+ super().__init__(reason_code or decision)
305
+ self.decision, self.reason_code, self.detail = decision, reason_code, detail
306
+
307
+ def as_dict(self) -> dict:
308
+ out = {"decision": self.decision}
309
+ if self.reason_code:
310
+ out["reason_code"] = self.reason_code
311
+ out.update(self.detail)
312
+ return out
313
+
314
+
315
+ def read_path(action: dict, path: str) -> Tuple[bool, Any]:
316
+ if path == "action.subject":
317
+ return ("subject" in action, action.get("subject"))
318
+ cur: Any = action.get("params")
319
+ for seg in path[len("action.params."):].split("."):
320
+ if not isinstance(cur, dict) or seg not in cur:
321
+ return (False, None)
322
+ cur = cur[seg]
323
+ return (True, cur)
324
+
325
+
326
+ def derive(declaration: dict, action: dict) -> Tuple[str, int]:
327
+ """(scope, amount) for an act under this budget, or Refusal (§5.1, §5.2)."""
328
+ sc = declaration["scope"]
329
+ if "fixed" in sc:
330
+ scope = sc["fixed"]
331
+ else:
332
+ present, v = read_path(action, sc["from"])
333
+ if present and isinstance(v, str) and v:
334
+ scope = v
335
+ elif present and is_amount(v):
336
+ scope = str(v)
337
+ else:
338
+ raise Refusal("NOT_ACCEPTED", "budget_scope_invalid")
339
+ am = amount_spec(declaration)
340
+ if "each" in am:
341
+ amount = am["each"]
342
+ else:
343
+ present, v = read_path(action, am["from"])
344
+ if not (present and is_amount(v)):
345
+ raise Refusal("NOT_ACCEPTED", "budget_amount_invalid")
346
+ amount = v
347
+ if declaration["unit"]["kind"] == "money":
348
+ present, cur = read_path(action, am["currency_from"])
349
+ if not present or cur != declaration["unit"]["currency"]:
350
+ raise Refusal("NOT_ACCEPTED", "budget_currency_mismatch")
351
+ return scope, amount
352
+
353
+
354
+ # ── §2 Ledger state ─────────────────────────────────────────────────────────────────────────────
355
+ def state_digest(budget: str, scope: str, period: str, limit: int, consumed: int, held: int, version: int) -> str:
356
+ return "sha256:" + sha256_hex(jcs({"budget": budget, "scope": scope, "period": period, "limit": limit,
357
+ "consumed": consumed, "held": held, "version": version}))
358
+
359
+
360
+ def available(limit: int, consumed: int, held: int) -> int:
361
+ return max(0, limit - consumed - held)
362
+
363
+
364
+ def facts_for(declaration: dict, limit: int, consumed: int, held: int, inputs: dict) -> Dict[str, int]:
365
+ """§6: the facts this ledger supplies, only under names the authority declares from relying_party."""
366
+ out: Dict[str, int] = {}
367
+ values = {"consumed_before": consumed + held, "remaining": available(limit, consumed, held), "limit": limit}
368
+ for key, name in (declaration.get("facts") or {}).items():
369
+ spec = inputs.get(name) if isinstance(inputs, dict) else None
370
+ if isinstance(spec, dict) and spec.get("source") == "relying_party":
371
+ out[name] = values[key]
372
+ return out
373
+
374
+
375
+ class Budget:
376
+ def __init__(self, key: str, declaration: dict, authority: Optional[str] = None):
377
+ self.key, self.declaration, self.authority = key, declaration, authority
378
+ self.limit = declaration["limit"]
379
+ self.hard = declaration.get("enforcement", "hard") == "hard"
380
+
381
+ def applies(self, action_type: str, authorities: List[str]) -> bool:
382
+ if action_type not in self.declaration["applies_to"]:
383
+ return False
384
+ if self.authority is not None:
385
+ return self.authority in authorities
386
+ allowed = self.declaration.get("authorities")
387
+ return allowed is None or bool(set(allowed) & set(authorities))
388
+
389
+
390
+ class Ledger:
391
+ def __init__(self, budget: str, scope: str, period: str, limit: int):
392
+ self.budget, self.scope, self.period = budget, scope, period
393
+ self.limit, self.consumed, self.held, self.version = limit, 0, 0, 0
394
+
395
+ @property
396
+ def available(self) -> int:
397
+ return available(self.limit, self.consumed, self.held)
398
+
399
+ def digest(self) -> str:
400
+ return state_digest(self.budget, self.scope, self.period, self.limit, self.consumed, self.held, self.version)
401
+
402
+ def state(self) -> dict:
403
+ return {"budget": self.budget, "scope": self.scope, "period": self.period, "limit": self.limit,
404
+ "consumed": self.consumed, "held": self.held, "version": self.version, "state_digest": self.digest()}
405
+
406
+
407
+ class Book:
408
+ """Every ledger and entry of one relying party, with §7 to §9 applied exactly. Single-threaded:
409
+ each method is one atomic operation."""
410
+
411
+ def __init__(self, budgets: List[Budget]):
412
+ self.budgets = sorted(budgets, key=lambda b: b.key.encode())
413
+ self.ledgers: Dict[Tuple[str, str, str], Ledger] = {}
414
+ self.identities: Dict[str, str] = {}
415
+ self.entries: List[dict] = []
416
+ self.nonces: set = set()
417
+
418
+ def budget(self, key: str) -> Budget:
419
+ return next(b for b in self.budgets if b.key == key)
420
+
421
+ def _entry(self, **e: Any) -> dict:
422
+ e = {"entry_id": f"e{len(self.entries) + 1}", **e}
423
+ self.entries.append(e)
424
+ return e
425
+
426
+ def _ledger(self, b: Budget, scope: str, period: str) -> Ledger:
427
+ k = (b.key, scope, period)
428
+ if k not in self.ledgers:
429
+ self.ledgers[k] = Ledger(b.key, scope, period, b.limit)
430
+ return self.ledgers[k]
431
+
432
+ def _expire(self, led: Ledger, now: int) -> None:
433
+ for e in self.entries:
434
+ if e["kind"] == "hold" and e["status"] == "held" and (e["budget"], e["scope"], e["period"]) == (led.budget, led.scope, led.period) and now >= e["expires_at"]:
435
+ e["status"] = "expired"
436
+ led.held -= e["amount"]
437
+ led.version += 1
438
+ self._entry(kind="expire", amount=e["amount"], at=now, budget=led.budget, scope=led.scope, period=led.period, resolves=e["entry_id"])
439
+
440
+ def _plan(self, act: dict, now: int) -> List[Tuple[Budget, Ledger, int]]:
441
+ """§7.1 steps 2 and 3, shared by commit and reserve. Raises Refusal."""
442
+ action, authorities = act["action"], act["authorities"]
443
+ derived: List[Tuple[Budget, str, int, str]] = []
444
+ for b in self.budgets: # ascending budget key
445
+ if not b.applies(action["type"], authorities):
446
+ continue
447
+ ident = identity(b.declaration)
448
+ if self.identities.get(b.key, ident) != ident:
449
+ raise Refusal("NOT_ACCEPTED", "budget_redeclared", budget=b.key)
450
+ try:
451
+ scope, amount = derive(b.declaration, action)
452
+ except Refusal as r:
453
+ raise Refusal(r.decision, r.reason_code, budget=b.key)
454
+ derived.append((b, scope, amount, period_key(now, b.declaration["period"])))
455
+ derived.sort(key=lambda x: (x[0].key.encode(), x[1].encode(), x[3].encode()))
456
+ plan = []
457
+ for b, scope, amount, period in derived:
458
+ self.identities.setdefault(b.key, identity(b.declaration))
459
+ led = self._ledger(b, scope, period)
460
+ self._expire(led, now)
461
+ if led.limit != b.limit: # §13: record the limit in force
462
+ led.limit = b.limit
463
+ led.version += 1
464
+ if led.consumed + led.held + amount > MAX_AMOUNT:
465
+ raise Refusal("NOT_ACCEPTED", "budget_amount_invalid", budget=b.key)
466
+ plan.append((b, led, amount))
467
+ return plan
468
+
469
+ def _check(self, act: dict, plan: List[Tuple[Budget, Ledger, int]], now: int) -> None:
470
+ for b, led, amount in plan: # §7.1 step 5
471
+ if b.hard and amount > led.available:
472
+ p = period_of(now, b.declaration["period"])
473
+ raise Refusal("BUDGET_EXHAUSTED", None, act_id=act["act_id"], act_digest=act["act_digest"], budget=b.key, scope=led.scope,
474
+ period=p, requested=amount, available=led.available)
475
+
476
+ def commit(self, act: dict, now: int) -> dict:
477
+ """§7.1. Returns {outcome: committed, budgets: [...]} or raises Refusal. Nothing changes on refusal."""
478
+ snapshot = self._snapshot()
479
+ try:
480
+ if act["nonce"] in self.nonces:
481
+ raise Refusal("REPLAYED")
482
+ plan = self._plan(act, now)
483
+ self._check(act, plan, now)
484
+ except Refusal:
485
+ self._restore(snapshot)
486
+ raise
487
+ self.nonces.add(act["nonce"])
488
+ charged = []
489
+ for b, led, amount in plan:
490
+ before, digest_before = led.consumed + led.held, led.digest()
491
+ led.consumed += amount
492
+ led.version += 1
493
+ e = self._entry(kind="consume", amount=amount, at=now, budget=b.key, scope=led.scope, period=led.period,
494
+ act_id=act["act_id"], act_digest=act["act_digest"], reversed=False)
495
+ charged.append({"budget": b.key, "scope": led.scope, "period": led.period,
496
+ "enforcement": "hard" if b.hard else "advisory", "amount": amount, "limit": led.limit,
497
+ "consumed_before": before, "state_digest_before": digest_before, "entry_id": e["entry_id"]})
498
+ return {"outcome": "committed", "budgets": charged}
499
+
500
+ def reserve(self, act: dict, now: int, ttl_ms: int, expected_state_digest: Optional[Dict[str, str]] = None) -> dict:
501
+ """§8.1: one hold per applicable ledger. `expected_state_digest` maps budget key → digest."""
502
+ snapshot = self._snapshot()
503
+ try:
504
+ if act["nonce"] in self.nonces:
505
+ raise Refusal("REPLAYED")
506
+ plan = self._plan(act, now)
507
+ for b, led, _ in plan:
508
+ want = (expected_state_digest or {}).get(b.key)
509
+ if want is not None and want != led.digest():
510
+ raise Refusal("CONFLICT", None, budget=b.key, expected_state_digest=want)
511
+ self._check(act, plan, now)
512
+ except Refusal:
513
+ self._restore(snapshot)
514
+ raise
515
+ self.nonces.add(act["nonce"])
516
+ holds = []
517
+ for b, led, amount in plan:
518
+ digest_before = led.digest()
519
+ led.held += amount
520
+ led.version += 1
521
+ e = self._entry(kind="hold", amount=amount, at=now, budget=b.key, scope=led.scope, period=led.period,
522
+ act_id=act["act_id"], act_digest=act["act_digest"], status="held", expires_at=now + ttl_ms)
523
+ holds.append({"entry_id": e["entry_id"], "budget": b.key, "scope": led.scope, "period": led.period,
524
+ "amount": amount, "expires_at": iso(now + ttl_ms), "state_digest_before": digest_before})
525
+ return {"outcome": "held", "holds": holds}
526
+
527
+ def _hold(self, entry_id: str) -> dict:
528
+ e = next((x for x in self.entries if x["entry_id"] == entry_id), None)
529
+ if not e or e["kind"] != "hold":
530
+ raise Refusal("NOT_FOUND")
531
+ return e
532
+
533
+ def settle(self, entry_id: str, now: int, reference: Optional[str] = None, revoked: bool = False) -> dict:
534
+ """§8.2: in the ledger the hold was placed in, whatever period `now` is in. A refusal changes nothing."""
535
+ snapshot = self._snapshot()
536
+ try:
537
+ return self._settle(entry_id, now, reference, revoked)
538
+ except Refusal:
539
+ self._restore(snapshot)
540
+ raise
541
+
542
+ def _settle(self, entry_id: str, now: int, reference: Optional[str], revoked: bool) -> dict:
543
+ h = self._hold(entry_id)
544
+ led = self.ledgers[(h["budget"], h["scope"], h["period"])]
545
+ self._expire(led, now)
546
+ if h["status"] == "settled":
547
+ if reference is not None and h.get("settle_reference") == reference:
548
+ return {"outcome": "settled", "entry_id": h["settled_by"], "period": h["period"], "amount": h["amount"]}
549
+ raise Refusal("ALREADY_RESOLVED", None, status="settled")
550
+ if h["status"] != "held":
551
+ raise Refusal("ALREADY_RESOLVED", None, status=h["status"])
552
+ if revoked:
553
+ raise Refusal("AUTHORITY_REVOKED")
554
+ h["status"] = "settled"
555
+ led.held -= h["amount"]
556
+ led.consumed += h["amount"]
557
+ led.version += 1
558
+ e = self._entry(kind="settle", amount=h["amount"], at=now, budget=led.budget, scope=led.scope, period=led.period,
559
+ resolves=entry_id, reversed=False)
560
+ h["settled_by"], h["settle_reference"] = e["entry_id"], reference
561
+ return {"outcome": "settled", "entry_id": e["entry_id"], "period": led.period, "amount": h["amount"]}
562
+
563
+ def release(self, entry_id: str, now: int) -> dict:
564
+ snapshot = self._snapshot()
565
+ try:
566
+ return self._release(entry_id, now)
567
+ except Refusal:
568
+ self._restore(snapshot)
569
+ raise
570
+
571
+ def _release(self, entry_id: str, now: int) -> dict:
572
+ h = self._hold(entry_id)
573
+ led = self.ledgers[(h["budget"], h["scope"], h["period"])]
574
+ self._expire(led, now)
575
+ if h["status"] != "held":
576
+ raise Refusal("ALREADY_RESOLVED", None, status=h["status"])
577
+ h["status"] = "released"
578
+ led.held -= h["amount"]
579
+ led.version += 1
580
+ e = self._entry(kind="release", amount=h["amount"], at=now, budget=led.budget, scope=led.scope, period=led.period, resolves=entry_id)
581
+ return {"outcome": "released", "entry_id": e["entry_id"], "amount": h["amount"]}
582
+
583
+ def reverse(self, entry_id: str, now: int) -> dict:
584
+ """§9: in the ledger the entry charged, at most once."""
585
+ e = next((x for x in self.entries if x["entry_id"] == entry_id), None)
586
+ if not e or e["kind"] not in ("consume", "settle"):
587
+ raise Refusal("NOT_FOUND")
588
+ if e["reversed"]:
589
+ return {"outcome": "reversed", "entry_id": e["reversed_by"], "period": e["period"], "amount": e["amount"]}
590
+ led = self.ledgers[(e["budget"], e["scope"], e["period"])]
591
+ led.consumed -= e["amount"]
592
+ led.version += 1
593
+ r = self._entry(kind="reverse", amount=e["amount"], at=now, budget=led.budget, scope=led.scope, period=led.period, resolves=entry_id)
594
+ e["reversed"], e["reversed_by"] = True, r["entry_id"]
595
+ return {"outcome": "reversed", "entry_id": r["entry_id"], "period": led.period, "amount": e["amount"]}
596
+
597
+ def set_limit(self, budget: str, limit: int, now: int) -> dict:
598
+ """§13: the limit in force changes; recorded at once on existing ledgers of the current period."""
599
+ b = self.budget(budget)
600
+ b.limit = limit
601
+ current = period_key(now, b.declaration["period"])
602
+ touched = 0
603
+ for (bk, _, period), led in sorted(self.ledgers.items(), key=lambda kv: (kv[0][0].encode(), kv[0][1].encode(), kv[0][2].encode())):
604
+ if bk == budget and period == current and led.limit != limit:
605
+ led.limit = limit
606
+ led.version += 1
607
+ touched += 1
608
+ return {"outcome": "limit_set", "ledgers": touched}
609
+
610
+ def facts(self, act: dict, now: int, inputs: dict) -> Dict[str, int]:
611
+ """§6 without taking any ledger: what a verification at `now` would be given."""
612
+ out: Dict[str, int] = {}
613
+ for b in self.budgets:
614
+ if not b.applies(act["action"]["type"], act["authorities"]):
615
+ continue
616
+ try:
617
+ scope, _ = derive(b.declaration, act["action"])
618
+ except Refusal:
619
+ continue # an act this budget cannot count is refused at commit; nothing to supply
620
+ led = self.ledgers.get((b.key, scope, period_key(now, b.declaration["period"])))
621
+ consumed, held = (led.consumed, led.held) if led else (0, 0)
622
+ if led: # holds that have expired by `now` no longer count, even before any ledger is taken
623
+ held -= sum(e["amount"] for e in self.entries if e["kind"] == "hold" and e["status"] == "held"
624
+ and (e["budget"], e["scope"], e["period"]) == (led.budget, led.scope, led.period) and now >= e["expires_at"])
625
+ out.update(facts_for(b.declaration, b.limit, consumed, held, inputs)) # §13: the limit in force
626
+ return out
627
+
628
+ def _snapshot(self):
629
+ import copy
630
+ return copy.deepcopy((self.ledgers, self.identities, self.entries, self.nonces))
631
+
632
+ def _restore(self, snap) -> None:
633
+ self.ledgers, self.identities, self.entries, self.nonces = snap
@@ -1,22 +1,24 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: nomosprotocol
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: NOMOS for Python: the reference verifiers for NOMOS-SPEC-007 (rev. 1.11), -008 and -010, NOMOS-SPEC-014 registrar logs, and accept(), act() and witness() for NOMOS-SPEC-009. Verify an Act, commit it exactly once, carry one, or sign the facts it needs.
5
5
  Author-email: NOMOS Protocol <hello@nomosprotocol.com>
6
- License: MIT
6
+ License: Apache-2.0
7
7
  Project-URL: Homepage, https://www.computableauthority.com
8
8
  Project-URL: Specification, https://github.com/nomos-spec/spec
9
9
  Keywords: nomos,computable-authority,agents,authorization,verifier,ed25519,es256,webauthn
10
10
  Classifier: Programming Language :: Python :: 3
11
- Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
12
  Classifier: Operating System :: OS Independent
13
13
  Classifier: Topic :: Security :: Cryptography
14
14
  Requires-Python: >=3.9
15
15
  Description-Content-Type: text/markdown
16
+ License-File: LICENSE
16
17
  Requires-Dist: cryptography>=43
17
18
  Provides-Extra: postgres
18
19
  Requires-Dist: psycopg[binary]>=3.1; extra == "postgres"
19
20
  Requires-Dist: psycopg-pool>=3.2; extra == "postgres"
21
+ Dynamic: license-file
20
22
 
21
23
  # nomosprotocol
22
24
 
@@ -110,7 +112,8 @@ chain.verify_revocation_list(lst, ROOT, now) # NOMOS-SPEC-007 rev. 1.10
110
112
 
111
113
  This package is checked against:
112
114
  - every vector of NOMOS-SPEC-007 (1.7.0, rev. 1.11, rev. 1.10 revocation sources), NOMOS-SPEC-008
113
- 0.6.0 and NOMOS-SPEC-010 0.2.0;
115
+ 0.7.0 with rev. 0.8.0 (several laws) and rev. 0.9.0 (intake questions), NOMOS-SPEC-010 0.2.0 and
116
+ NOMOS-SPEC-016 0.1.0 (budgets: 200 of 200, `budget-vectors/check.py`);
114
117
  - the NOMOS-SPEC-009 selection vectors;
115
118
  - the NOMOS-SPEC-009 HTTP runner, 17 of 17, with `accept()` behind it
116
119
  (`python/tests/conformance_rp.py`).
@@ -118,4 +121,4 @@ This package is checked against:
118
121
  `act()` also interoperates with the JavaScript sandbox, escalation and approval included
119
122
  (`python/tests/interop_sandbox.py`).
120
123
 
121
- MIT licensed.
124
+ Licensed under the [Apache License 2.0](LICENSE). NOMOS Protocol and Computable Authority are trademarks of SafeHaven LLC ([TRADEMARKS.md](../TRADEMARKS.md)).
@@ -1,9 +1,11 @@
1
+ LICENSE
1
2
  README.md
2
3
  pyproject.toml
3
4
  nomosprotocol/__init__.py
4
5
  nomosprotocol/accept.py
5
6
  nomosprotocol/act.py
6
7
  nomosprotocol/bindings.py
8
+ nomosprotocol/budgets.py
7
9
  nomosprotocol/carrier.py
8
10
  nomosprotocol/chain.py
9
11
  nomosprotocol/issuer.py
@@ -4,15 +4,15 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "nomosprotocol"
7
- version = "0.2.0"
7
+ version = "0.3.0"
8
8
  description = "NOMOS for Python: the reference verifiers for NOMOS-SPEC-007 (rev. 1.11), -008 and -010, NOMOS-SPEC-014 registrar logs, and accept(), act() and witness() for NOMOS-SPEC-009. Verify an Act, commit it exactly once, carry one, or sign the facts it needs."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
11
- license = { text = "MIT" }
11
+ license = { text = "Apache-2.0" }
12
12
  authors = [{ name = "NOMOS Protocol", email = "hello@nomosprotocol.com" }]
13
13
  dependencies = ["cryptography>=43"] # 43 added deterministic (RFC 6979) ECDSA, which signing relies on
14
14
  keywords = ["nomos", "computable-authority", "agents", "authorization", "verifier", "ed25519", "es256", "webauthn"]
15
- classifiers = ["Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Topic :: Security :: Cryptography"]
15
+ classifiers = ["Programming Language :: Python :: 3", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", "Topic :: Security :: Cryptography"]
16
16
 
17
17
  [project.optional-dependencies]
18
18
  postgres = ["psycopg[binary]>=3.1", "psycopg-pool>=3.2"]
File without changes