universal-paper 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ """Universal Paper reference interpreter (UP/0.1-draft).
2
+
3
+ The interpreter is a convenience, not a dependency: every result it produces
4
+ can be reproduced by hand from the specification in spec/.
5
+ """
6
+ SPEC = "UP/0.1-draft"
7
+ __version__ = "0.1.0"
@@ -0,0 +1,206 @@
1
+ """Command-line interface: python -m universal_paper <command> ... (or `up <command>` once installed)."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import os
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from .canon import content_hash
11
+ from .engine import Bundle, Evaluator, agreement_issues
12
+ from .render import render_agreement
13
+ from .report import snapshot
14
+ from .simulate import simulate
15
+ from .trace import make_trace
16
+
17
+
18
+ class InputError(Exception):
19
+ pass
20
+
21
+
22
+ def _pairs(pairs: list) -> dict:
23
+ out: dict = {}
24
+ for k, v in pairs:
25
+ if k in out:
26
+ raise InputError(f"duplicate object key {k!r} (I-JSON, RFC 7493, forbids duplicates)")
27
+ out[k] = v
28
+ return out
29
+
30
+
31
+ def _constant(name: str):
32
+ raise InputError(f"{name} is not valid JSON")
33
+
34
+
35
+ def loads(text: str):
36
+ """Strict JSON: no duplicate keys and no NaN or Infinity (RFC 8785 relies on I-JSON)."""
37
+ return json.loads(text, object_pairs_hook=_pairs, parse_constant=_constant)
38
+
39
+
40
+ def _load(p: str):
41
+ try:
42
+ text = Path(p).read_text(encoding="utf-8")
43
+ except OSError as e:
44
+ raise InputError(f"cannot read {p}: {e.strerror or e}") from None
45
+ except UnicodeDecodeError:
46
+ raise InputError(f"{p} is not UTF-8 text") from None
47
+ try:
48
+ return loads(text)
49
+ except json.JSONDecodeError as e:
50
+ raise InputError(f"{p} is not valid JSON: {e}") from None
51
+
52
+
53
+ def _out(obj, path: str | None = None) -> None:
54
+ text = json.dumps(obj, indent=2, sort_keys=True, ensure_ascii=False) + "\n"
55
+ if path:
56
+ Path(path).write_text(text)
57
+ else:
58
+ sys.stdout.write(text)
59
+
60
+
61
+ def _latest(b: Bundle) -> str:
62
+ times = [E["at"] for ch in b.chain_list for E in ch if isinstance(E, dict) and isinstance(E.get("at"), str)]
63
+ if not times:
64
+ raise InputError("the bundle has no events")
65
+ return max(times)
66
+
67
+
68
+ def _pos(b: Bundle, chain: str | None) -> list[int]:
69
+ if chain is None:
70
+ return list(range(len(b.chain_list)))
71
+ if chain.isdigit() and int(chain) < len(b.chain_list):
72
+ return [int(chain)]
73
+ if chain in b.chain_pos:
74
+ return [b.chain_pos[chain]]
75
+ raise InputError(f"no chain {chain!r} in the bundle")
76
+
77
+
78
+ def cmd_validate(a) -> int:
79
+ b = Bundle(_load(a.bundle))
80
+ ev = Evaluator(b)
81
+ bad = 0
82
+ for pos, ch in enumerate(b.chain_list):
83
+ cid = content_hash(ch[0])
84
+ label = ch[0].get("body", {}).get("agreement", {}).get("label", f"chain {pos}")
85
+ print(f"chain {pos}: {label}\n id {cid}")
86
+ for st in ev.run(cid):
87
+ mark = "ok " if st.accepted else "REJECTED"
88
+ print(f" [{mark}] #{st.index} {st.event['kind']:<7} {st.event['at']} {st.reason if not st.accepted else ''}")
89
+ bad += not st.accepted
90
+ S = ev.state_at(cid)
91
+ if S:
92
+ print(f" state {content_hash(S)} status at latest event: {ev.status(cid, _latest(b))}")
93
+ for h, ag in sorted(b.agreements.items()):
94
+ for rule, why in agreement_issues(b, ag):
95
+ print(f"agreement {h}: {rule}: {why}")
96
+ for cid in sorted(set(b.forks)):
97
+ print(f"INVALID BUNDLE: chain {cid} appears more than once (two versions of one chain)")
98
+ print(f"\n{bad} event(s) rejected." if bad else "\nEvery event is valid.")
99
+ return 2 if bad or b.forks else 0
100
+
101
+
102
+ def cmd_apply(a) -> int:
103
+ data = _load(a.bundle)
104
+ E = _load(a.event)
105
+ b = Bundle(data)
106
+ if "chain" in E:
107
+ pos = b.chain_pos.get(E["chain"])
108
+ if pos is None:
109
+ print("unknown chain", file=sys.stderr)
110
+ return 1
111
+ S = Evaluator(b).state_at(E["chain"])
112
+ else:
113
+ S = None
114
+ if isinstance(E, dict) and content_hash(E) in b.chains:
115
+ print("this genesis event already starts a chain in the bundle", file=sys.stderr)
116
+ return 2
117
+ S2, checks, reason = Evaluator(b).apply(S, E)
118
+ _out({"accepted": S2 is not None, "reason": reason, "checks": [c.to_json() for c in checks],
119
+ "state": S2, "state_hash": content_hash(S2) if S2 else None})
120
+ if S2 is not None and a.write:
121
+ if S is None:
122
+ data["chains"].append([E])
123
+ else:
124
+ data["chains"][pos].append(E)
125
+ _out(data, a.bundle)
126
+ return 0 if S2 is not None else 2
127
+
128
+
129
+ def cmd_derive(a) -> int:
130
+ b = Bundle(_load(a.bundle))
131
+ _out(snapshot(Evaluator(b), a.at or _latest(b)))
132
+ return 0
133
+
134
+
135
+ def cmd_simulate(a) -> int:
136
+ _out(simulate(_load(a.bundle), _load(a.events), a.at), a.output)
137
+ return 0
138
+
139
+
140
+ def cmd_render(a) -> int:
141
+ b = Bundle(_load(a.bundle))
142
+ if a.hashes_only:
143
+ b.disclosures = {}
144
+ ev = Evaluator(b)
145
+ for pos in _pos(b, a.chain):
146
+ S = ev.state_at(content_hash(b.chain_list[pos][0]))
147
+ ag = ev.agreement(S) or b.chain_list[pos][0]["body"]["agreement"]
148
+ sys.stdout.write(render_agreement(b, ag) + "\n")
149
+ return 0
150
+
151
+
152
+ def cmd_trace(a) -> int:
153
+ data = _load(a.bundle)
154
+ if a.config:
155
+ cfg = _load(a.config)
156
+ evals = [{**e, "data": _load(e["bundle"]) if "bundle" in e else data} for e in cfg["evaluators"]]
157
+ meta = cfg.get("meta", {})
158
+ else:
159
+ evals = [{"id": f"evaluator-{i + 1}", "name": f"Evaluator {i + 1}", "data": data} for i in range(a.evaluators)]
160
+ meta = {"title": Path(a.bundle).stem}
161
+ _out(make_trace(data, evals, meta, a.at or _latest(Bundle(data))), a.output)
162
+ return 0
163
+
164
+
165
+ def cmd_hash(a) -> int:
166
+ print(content_hash(_load(a.file)))
167
+ return 0
168
+
169
+
170
+ def main(argv=None) -> int:
171
+ p = argparse.ArgumentParser(prog="up", description="Universal Paper reference interpreter (UP/0.1-draft)")
172
+ sub = p.add_subparsers(dest="cmd", required=True)
173
+ s = sub.add_parser("validate", help="check every agreement and event in a bundle against the axioms")
174
+ s.add_argument("bundle"); s.set_defaults(f=cmd_validate)
175
+ s = sub.add_parser("apply", help="apply one event to its chain's current state; reject invalid transitions")
176
+ s.add_argument("bundle"); s.add_argument("event"); s.add_argument("--write", action="store_true", help="append the event to the bundle file if valid")
177
+ s.set_defaults(f=cmd_apply)
178
+ s = sub.add_parser("derive", help="derive states, statuses, tiers, prices, and obligations at a time")
179
+ s.add_argument("bundle"); s.add_argument("--at"); s.set_defaults(f=cmd_derive)
180
+ s = sub.add_parser("simulate", help="run hypothetical events forward and report the results")
181
+ s.add_argument("bundle"); s.add_argument("events"); s.add_argument("--at"); s.add_argument("-o", "--output")
182
+ s.set_defaults(f=cmd_simulate)
183
+ s = sub.add_parser("render", help="render agreements as human-readable text")
184
+ s.add_argument("bundle"); s.add_argument("--chain"); s.add_argument("--hashes-only", action="store_true", help="ignore disclosures")
185
+ s.set_defaults(f=cmd_render)
186
+ s = sub.add_parser("trace", help="write a trace file of every event, check, and evaluator state hash")
187
+ s.add_argument("bundle"); s.add_argument("-o", "--output"); s.add_argument("--at")
188
+ s.add_argument("--evaluators", type=int, default=3); s.add_argument("--config", help="JSON file naming evaluators and their bundle copies")
189
+ s.set_defaults(f=cmd_trace)
190
+ s = sub.add_parser("hash", help="print the content hash of a JSON object"); s.add_argument("file"); s.set_defaults(f=cmd_hash)
191
+ a = p.parse_args(argv)
192
+ try:
193
+ return a.f(a)
194
+ except InputError as e:
195
+ print(f"up: error: {e}", file=sys.stderr)
196
+ return 1
197
+ except Exception as e: # malformed input must never end in a traceback
198
+ if os.environ.get("UP_DEBUG"):
199
+ raise
200
+ print(f"up: error: the input could not be processed ({type(e).__name__}: {e}). "
201
+ "Set UP_DEBUG=1 to see the traceback.", file=sys.stderr)
202
+ return 1
203
+
204
+
205
+ if __name__ == "__main__":
206
+ sys.exit(main())
@@ -0,0 +1,145 @@
1
+ """Helpers for building agreements, events, and bundles (used by examples and tests)."""
2
+ from __future__ import annotations
3
+
4
+ import copy
5
+ import hashlib
6
+ import json
7
+ from collections.abc import Sequence
8
+ from pathlib import Path
9
+
10
+ from . import SPEC
11
+ from .canon import content_hash
12
+ from .crypto import Key, attach
13
+ from .engine import Bundle, Evaluator
14
+ from .values import seal_of
15
+
16
+ TERMS_DIR = Path(__file__).resolve().parents[2] / "spec" / "06-terms"
17
+ # The Term library ships inside the package too, so an installed copy works outside the repository.
18
+ # tools/gen_terms.py writes it; tests/test_terms.py checks it equals spec/06-terms/.
19
+ PACKAGED_TERMS = Path(__file__).resolve().parent / "terms.json"
20
+
21
+
22
+ def load_terms(directory: Path | None = None) -> dict[str, dict]:
23
+ if directory is None:
24
+ terms = json.loads(PACKAGED_TERMS.read_text(encoding="utf-8"))
25
+ return {t["id"]: t for t in terms}
26
+ out = {}
27
+ for p in sorted(directory.glob("*.json")):
28
+ t = json.loads(p.read_text(encoding="utf-8"))
29
+ out[t["id"]] = t
30
+ return out
31
+
32
+
33
+ class Actor:
34
+ def __init__(self, name: str, seed: str | None = None, ids: list[dict] | None = None):
35
+ self.name = name
36
+ self.key = Key.from_seed(seed or f"universal-paper-example:{name}")
37
+ self.ids = ids or []
38
+
39
+ @property
40
+ def pub(self) -> str:
41
+ return self.key.public
42
+
43
+ def party(self) -> dict:
44
+ p: dict = {"key": self.pub, "name": self.name}
45
+ if self.ids:
46
+ p["ids"] = self.ids
47
+ return p
48
+
49
+
50
+ class World:
51
+ """A growing set of terms, mandates, chains, and disclosures."""
52
+
53
+ def __init__(self, terms: dict[str, dict] | None = None):
54
+ self.terms = terms or load_terms()
55
+ self.mandates: list[dict] = []
56
+ self.chains: list[list[dict]] = []
57
+ self.disclosures: list[dict] = []
58
+ self._salt_n = 0
59
+
60
+ # ---- content -------------------------------------------------------
61
+
62
+ def clause(self, n: str, term: str, params: dict, over: list[str] | None = None) -> dict:
63
+ c = {"n": n, "term": term, "def": content_hash(self.terms[term]), "params": params}
64
+ if over:
65
+ c["over"] = over
66
+ return c
67
+
68
+ def agreement(self, parties: list[tuple[str, Actor]], clauses: list[dict], label: str) -> dict:
69
+ ps: list[dict] = sorted(({"role": r, "party": a.party()} for r, a in parties), key=lambda p: (p["role"], p["party"]["key"]))
70
+ return {"type": "Agreement", "spec": SPEC, "parties": ps, "clauses": clauses, "label": label}
71
+
72
+ def seal(self, value, label: str) -> dict:
73
+ """Seal a value with a deterministic salt. EXAMPLES ONLY: real salts must be random."""
74
+ self._salt_n += 1
75
+ salt = hashlib.sha256(f"example-salt:{label}:{self._salt_n}".encode()).hexdigest()
76
+ s = seal_of(value, salt)
77
+ self.disclosures.append({"seal": s["seal"], "salt": salt, "value": value})
78
+ return s
79
+
80
+ def mandate(self, principal: Actor, agent: Key, not_before: str, expires: str, scope: dict) -> str:
81
+ m = {"type": "Mandate", "spec": SPEC, "principal": principal.pub, "agent": agent.public,
82
+ "not_before": not_before, "expires": expires, "scope": scope}
83
+ m = attach(m, principal.key.sign_obj(m))
84
+ self.mandates.append(m)
85
+ return content_hash(m)
86
+
87
+ # ---- bundle and events --------------------------------------------
88
+
89
+ def data(self, disclosures: bool = True, all_terms: bool = False) -> dict:
90
+ used = {c["def"] for ch in self.chains for e in ch
91
+ for c in (e.get("body", {}).get("agreement") or {}).get("clauses", [])}
92
+ d = {"type": "Bundle", "spec": SPEC,
93
+ "terms": [t for t in self.terms.values() if all_terms or content_hash(t) in used],
94
+ "mandates": list(self.mandates),
95
+ "chains": copy.deepcopy(self.chains)}
96
+ if disclosures and self.disclosures:
97
+ d["disclosures"] = list(self.disclosures)
98
+ return d
99
+
100
+ def bundle(self) -> Bundle:
101
+ return Bundle(self.data(all_terms=True))
102
+
103
+ def chain_id(self, pos: int) -> str:
104
+ return content_hash(self.chains[pos][0])
105
+
106
+ def _state(self, pos: int):
107
+ ev = Evaluator(self.bundle())
108
+ return ev.state_at(self.chain_id(pos))
109
+
110
+ def event(self, pos: int | None, kind: str, by: Actor, at: str, body: dict,
111
+ cosigners: Sequence[Actor] = (), agent: tuple[Key, str] | None = None,
112
+ expect: bool = True) -> tuple[int, str]:
113
+ """Append a signed event. pos=None starts a new chain. agent=(agent key, mandate hash) signs for `by`."""
114
+ E = {"type": "Event", "spec": SPEC, "kind": kind, "at": at, "by": by.pub, "body": body}
115
+ if pos is not None:
116
+ S = self._state(pos)
117
+ E["chain"] = self.chain_id(pos)
118
+ E["prev"] = content_hash(S)
119
+ sigs = [agent[0].sign_obj(E, agent[1]) if agent else by.key.sign_obj(E)]
120
+ sigs += [c.key.sign_obj(E) for c in cosigners]
121
+ E = attach(E, *sigs)
122
+ if pos is None:
123
+ self.chains.append([E])
124
+ pos = len(self.chains) - 1
125
+ else:
126
+ self.chains[pos].append(E)
127
+ ev = Evaluator(self.bundle())
128
+ step = ev.run(self.chain_id(pos))[-1]
129
+ if step.accepted != expect:
130
+ raise AssertionError(f"event at {at} by {by.name} expected {'accept' if expect else 'reject'}: {step.reason}")
131
+ return pos, content_hash(E)
132
+
133
+ def propose(self, by, ag, at, pos=None, **kw):
134
+ body = {"agreement": ag}
135
+ if "supersedes" in kw:
136
+ body["supersedes"] = kw.pop("supersedes")
137
+ if "expires" in kw:
138
+ body["expires"] = kw.pop("expires")
139
+ return self.event(pos, "propose", by, at, body, **kw)
140
+
141
+ def accept(self, pos, by, target, at, **kw):
142
+ return self.event(pos, "accept", by, at, {"target": target}, **kw)
143
+
144
+ def attest(self, pos, by, clause, ctype, data, at, **kw):
145
+ return self.event(pos, "attest", by, at, {"claim": {"type": ctype, "clause": clause, "data": data}}, **kw)
@@ -0,0 +1,125 @@
1
+ """Canonical JSON (RFC 8785 / JCS, restricted per spec/01-domain.md §1) and content hashes."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ from typing import Any
6
+
7
+ MAX_INT = 2**53 - 1
8
+
9
+
10
+ class CanonError(ValueError):
11
+ pass
12
+
13
+
14
+ def _str(s: str) -> str:
15
+ out = ['"']
16
+ if any(0xD800 <= ord(ch) <= 0xDFFF for ch in s):
17
+ # RFC 8785 relies on I-JSON (RFC 7493), which forbids lone surrogates.
18
+ raise CanonError("strings must not contain lone surrogates")
19
+ for ch in s:
20
+ o = ord(ch)
21
+ if ch == '"':
22
+ out.append('\\"')
23
+ elif ch == "\\":
24
+ out.append("\\\\")
25
+ elif ch == "\b":
26
+ out.append("\\b")
27
+ elif ch == "\f":
28
+ out.append("\\f")
29
+ elif ch == "\n":
30
+ out.append("\\n")
31
+ elif ch == "\r":
32
+ out.append("\\r")
33
+ elif ch == "\t":
34
+ out.append("\\t")
35
+ elif o < 0x20:
36
+ out.append("\\u%04x" % o)
37
+ else:
38
+ out.append(ch)
39
+ out.append('"')
40
+ return "".join(out)
41
+
42
+
43
+ def _ser(v: Any, parts: list[str]) -> None:
44
+ if v is True:
45
+ parts.append("true")
46
+ elif v is False:
47
+ parts.append("false")
48
+ elif v is None:
49
+ raise CanonError("null is not allowed in Universal Paper objects")
50
+ elif isinstance(v, int):
51
+ if abs(v) > MAX_INT:
52
+ raise CanonError(f"integer out of range: {v}")
53
+ parts.append(str(v))
54
+ elif isinstance(v, float):
55
+ # JSON does not distinguish 100 from 100.0 or 1e2, and JavaScript cannot tell them
56
+ # apart after parsing, so an integral number is canonicalized as that integer.
57
+ if v != v or v in (float("inf"), float("-inf")) or not v.is_integer():
58
+ raise CanonError("non-integer JSON numbers are not allowed; use a Decimal string")
59
+ _ser(int(v), parts)
60
+ elif isinstance(v, str):
61
+ parts.append(_str(v))
62
+ elif isinstance(v, (list, tuple)):
63
+ parts.append("[")
64
+ for i, x in enumerate(v):
65
+ if i:
66
+ parts.append(",")
67
+ _ser(x, parts)
68
+ parts.append("]")
69
+ elif isinstance(v, dict):
70
+ for k in v:
71
+ if not isinstance(k, str):
72
+ raise CanonError("object keys must be strings")
73
+ if not k.isascii():
74
+ raise CanonError("object keys must be ASCII (spec/01-domain.md §1.1)")
75
+ parts.append("{")
76
+ for i, k in enumerate(sorted(v, key=lambda k: k.encode("utf-16-be"))):
77
+ if i:
78
+ parts.append(",")
79
+ parts.append(_str(k))
80
+ parts.append(":")
81
+ _ser(v[k], parts)
82
+ parts.append("}")
83
+ else:
84
+ raise CanonError(f"unsupported type: {type(v).__name__}")
85
+
86
+
87
+ def jcs(v: Any) -> bytes:
88
+ parts: list[str] = []
89
+ _ser(v, parts)
90
+ return "".join(parts).encode("utf-8")
91
+
92
+
93
+ def normalize(v: Any) -> Any:
94
+ """Turn integral floats (from JSON text such as 100.0 or 1e2) into ints, recursively.
95
+
96
+ Bundles are normalized on load so the evaluator sees numbers exactly as the JavaScript
97
+ engine does. Non-integral floats are left alone; canonicalization rejects them.
98
+ """
99
+ if isinstance(v, float) and v == v and v not in (float("inf"), float("-inf")) and v.is_integer():
100
+ return int(v)
101
+ if isinstance(v, dict):
102
+ return {k: normalize(x) for k, x in v.items()}
103
+ if isinstance(v, list):
104
+ return [normalize(x) for x in v]
105
+ return v
106
+
107
+
108
+ def strip(o: dict) -> dict:
109
+ return {k: v for k, v in o.items() if k != "sigs"}
110
+
111
+
112
+ def digest(o: dict) -> bytes:
113
+ """The 32 raw SHA-256 bytes that signatures cover."""
114
+ return hashlib.sha256(jcs(strip(o) if isinstance(o, dict) else o)).digest()
115
+
116
+
117
+ def content_hash(o: Any) -> str:
118
+ return "sha256:" + hashlib.sha256(jcs(strip(o) if isinstance(o, dict) else o)).hexdigest()
119
+
120
+
121
+ def hash_bytes(h: str) -> bytes:
122
+ if not (isinstance(h, str) and h.startswith("sha256:") and len(h) == 71
123
+ and all(c in "0123456789abcdef" for c in h[7:])):
124
+ raise CanonError(f"not a hash: {h!r}")
125
+ return bytes.fromhex(h[7:])
@@ -0,0 +1,91 @@
1
+ """Ed25519 keys and signatures over content hashes (spec/01-domain.md §1.3)."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import re
6
+
7
+ from cryptography.exceptions import InvalidSignature
8
+ from cryptography.hazmat.primitives import serialization
9
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
10
+
11
+ from .canon import digest
12
+
13
+
14
+ class Key:
15
+ """A private signing key. Example keys are derived from a seed phrase so examples are reproducible."""
16
+
17
+ def __init__(self, priv: Ed25519PrivateKey):
18
+ self._priv = priv
19
+ raw = priv.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)
20
+ self.public = "ed25519:" + raw.hex()
21
+
22
+ @classmethod
23
+ def from_seed(cls, seed: str) -> Key:
24
+ return cls(Ed25519PrivateKey.from_private_bytes(hashlib.sha256(seed.encode()).digest()))
25
+
26
+ @classmethod
27
+ def generate(cls) -> Key:
28
+ return cls(Ed25519PrivateKey.generate())
29
+
30
+ def sign_obj(self, obj: dict, mandate: str | None = None) -> dict:
31
+ entry = {"key": self.public, "sig": self._priv.sign(digest(obj)).hex()}
32
+ if mandate:
33
+ entry["mandate"] = mandate
34
+ return entry
35
+
36
+
37
+ KEY_RE = re.compile(r"ed25519:[0-9a-f]{64}\Z")
38
+ SIG_RE = re.compile(r"[0-9a-f]{128}\Z")
39
+ _P = 2**255 - 19
40
+ _L = 2**252 + 27742317777372353535851937790883648493
41
+ # y-coordinates of the eight points of small order (order dividing 8). A key whose point has
42
+ # small order lets anyone produce "signatures" that verify on many messages, so such keys are
43
+ # never valid Party or agent keys (spec/01-domain.md §1.3). tests/test_crypto.py recomputes them.
44
+ SMALL_ORDER_Y = frozenset({
45
+ 0,
46
+ 1,
47
+ _P - 1,
48
+ 0x05FC536D880238B13933C6D305ACDFD5F098EFF289F4C345B027B2C28F95E826,
49
+ 0x7A03AC9277FDC74EC6CC392CFA53202A0F67100D760B3CBA4FD84D3D706A17C7,
50
+ })
51
+
52
+
53
+ def _y(b: bytes) -> int:
54
+ return int.from_bytes(b, "little") & ((1 << 255) - 1)
55
+
56
+
57
+ def valid_key(pub: object) -> bool:
58
+ """A public key is valid iff it is lowercase hex, canonically encoded, and not of small order."""
59
+ if not (isinstance(pub, str) and KEY_RE.match(pub)):
60
+ return False
61
+ y = _y(bytes.fromhex(pub[8:]))
62
+ return y < _P and y not in SMALL_ORDER_Y
63
+
64
+
65
+ def verify(pub: object, sig_hex: object, obj: dict) -> bool:
66
+ """Strict Ed25519 verification (spec/01-domain.md §1.3).
67
+
68
+ Encodings must be canonical: lowercase hex, a valid key (see valid_key), R with y < p,
69
+ and S < L. The equation is then checked by the cryptography package (cofactorless).
70
+ The JavaScript engine applies the same rules, so both accept exactly the same signatures.
71
+ """
72
+ if not valid_key(pub) or not (isinstance(sig_hex, str) and SIG_RE.match(sig_hex)):
73
+ return False
74
+ sig = bytes.fromhex(sig_hex)
75
+ if _y(sig[:32]) >= _P or int.from_bytes(sig[32:], "little") >= _L:
76
+ return False
77
+ try:
78
+ Ed25519PublicKey.from_public_bytes(bytes.fromhex(pub[8:])).verify(sig, digest(obj)) # type: ignore[index]
79
+ return True
80
+ except (InvalidSignature, ValueError):
81
+ return False
82
+
83
+
84
+ def attach(obj: dict, *entries: dict) -> dict:
85
+ """Return obj with signatures added, sigs sorted by key (one entry per key)."""
86
+ by_key = {s["key"]: s for s in obj.get("sigs", [])}
87
+ for e in entries:
88
+ by_key[e["key"]] = e
89
+ out = dict(obj)
90
+ out["sigs"] = [by_key[k] for k in sorted(by_key)]
91
+ return out