pazair-verify 1.8.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.
- pazair_verify-1.8.0/LICENSE +9 -0
- pazair_verify-1.8.0/PKG-INFO +41 -0
- pazair_verify-1.8.0/README.md +22 -0
- pazair_verify-1.8.0/pyproject.toml +25 -0
- pazair_verify-1.8.0/setup.cfg +4 -0
- pazair_verify-1.8.0/src/pazair_verify/__init__.py +675 -0
- pazair_verify-1.8.0/src/pazair_verify/__main__.py +3 -0
- pazair_verify-1.8.0/src/pazair_verify/py.typed +0 -0
- pazair_verify-1.8.0/src/pazair_verify.egg-info/PKG-INFO +41 -0
- pazair_verify-1.8.0/src/pazair_verify.egg-info/SOURCES.txt +15 -0
- pazair_verify-1.8.0/src/pazair_verify.egg-info/dependency_links.txt +1 -0
- pazair_verify-1.8.0/src/pazair_verify.egg-info/entry_points.txt +2 -0
- pazair_verify-1.8.0/src/pazair_verify.egg-info/requires.txt +1 -0
- pazair_verify-1.8.0/src/pazair_verify.egg-info/top_level.txt +1 -0
- pazair_verify-1.8.0/tests/test_award.py +54 -0
- pazair_verify-1.8.0/tests/test_fingerprint.py +53 -0
- pazair_verify-1.8.0/tests/test_vectors.py +126 -0
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kula Labs
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pazair-verify
|
|
3
|
+
Version: 1.8.0
|
|
4
|
+
Summary: Check Word Passes, receipts and Merkle proofs: "May I see your Word Pass?", checked by anyone, for any issuer.
|
|
5
|
+
Author-email: Kula Labs <hallo@kulalabs.ch>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Kula-Labs/pazair/tree/main/python
|
|
8
|
+
Project-URL: Specification, https://github.com/Kula-Labs/pazair/blob/main/SPEC.md
|
|
9
|
+
Keywords: word-pass,ai-agents,agent-trust,a2a,mcp,ed25519,merkle,bitcoin,stellar
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Typing :: Typed
|
|
14
|
+
Requires-Python: >=3.9
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Requires-Dist: cryptography>=41
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# pazair-verify (Python)
|
|
21
|
+
|
|
22
|
+
"May I see your Word Pass?" Check the URL another AI agent shows you, from any issuer, without trusting anyone.
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
pip install "git+https://github.com/Kula-Labs/pazair#subdirectory=python" # PyPI release follows
|
|
26
|
+
pazair-verify https://pazair.kulalabs.ch/v1/agents/ag_xyz/pass
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
from pazair_verify import check_word_pass
|
|
31
|
+
r = check_word_pass(url_the_other_agent_gave_you)
|
|
32
|
+
if r["trust"] == "kept_its_word": # also: signed_unanchored, no_badge_yet, invalid, unreachable
|
|
33
|
+
...
|
|
34
|
+
print(r["say"]) # one sentence for your principal
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Also: `verify_pass`, `verify_receipt`, `verify_proof`, `canonical`, `stellar_has_root`, and the fingerprint of SPEC
|
|
38
|
+
section 15: `fingerprint_of(origin, agent, first_leaf)`, `fingerprint_distance(a, b)` (two agents differ in at least 55
|
|
39
|
+
of 64 symbols) and `fingerprint_svg(codeword, record)`, byte for byte the drawing the JavaScript verifier makes. Same results as the
|
|
40
|
+
JavaScript verifier, checked against the shared [test vectors](https://github.com/Kula-Labs/pazair/blob/main/vectors/word-pass-1.json).
|
|
41
|
+
[Specification](https://github.com/Kula-Labs/pazair/blob/main/SPEC.md). MIT, by Kula Labs, Switzerland.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# pazair-verify (Python)
|
|
2
|
+
|
|
3
|
+
"May I see your Word Pass?" Check the URL another AI agent shows you, from any issuer, without trusting anyone.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
pip install "git+https://github.com/Kula-Labs/pazair#subdirectory=python" # PyPI release follows
|
|
7
|
+
pazair-verify https://pazair.kulalabs.ch/v1/agents/ag_xyz/pass
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
```python
|
|
11
|
+
from pazair_verify import check_word_pass
|
|
12
|
+
r = check_word_pass(url_the_other_agent_gave_you)
|
|
13
|
+
if r["trust"] == "kept_its_word": # also: signed_unanchored, no_badge_yet, invalid, unreachable
|
|
14
|
+
...
|
|
15
|
+
print(r["say"]) # one sentence for your principal
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Also: `verify_pass`, `verify_receipt`, `verify_proof`, `canonical`, `stellar_has_root`, and the fingerprint of SPEC
|
|
19
|
+
section 15: `fingerprint_of(origin, agent, first_leaf)`, `fingerprint_distance(a, b)` (two agents differ in at least 55
|
|
20
|
+
of 64 symbols) and `fingerprint_svg(codeword, record)`, byte for byte the drawing the JavaScript verifier makes. Same results as the
|
|
21
|
+
JavaScript verifier, checked against the shared [test vectors](https://github.com/Kula-Labs/pazair/blob/main/vectors/word-pass-1.json).
|
|
22
|
+
[Specification](https://github.com/Kula-Labs/pazair/blob/main/SPEC.md). MIT, by Kula Labs, Switzerland.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "pazair-verify"
|
|
7
|
+
version = "1.8.0"
|
|
8
|
+
description = "Check Word Passes, receipts and Merkle proofs: \"May I see your Word Pass?\", checked by anyone, for any issuer."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = { text = "MIT" }
|
|
11
|
+
classifiers = ["License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Typing :: Typed"]
|
|
12
|
+
authors = [{ name = "Kula Labs", email = "hallo@kulalabs.ch" }]
|
|
13
|
+
requires-python = ">=3.9"
|
|
14
|
+
dependencies = ["cryptography>=41"]
|
|
15
|
+
keywords = ["word-pass", "ai-agents", "agent-trust", "a2a", "mcp", "ed25519", "merkle", "bitcoin", "stellar"]
|
|
16
|
+
urls = { Homepage = "https://github.com/Kula-Labs/pazair/tree/main/python", Specification = "https://github.com/Kula-Labs/pazair/blob/main/SPEC.md" }
|
|
17
|
+
|
|
18
|
+
[project.scripts]
|
|
19
|
+
pazair-verify = "pazair_verify:main"
|
|
20
|
+
|
|
21
|
+
[tool.setuptools.packages.find]
|
|
22
|
+
where = ["src"]
|
|
23
|
+
|
|
24
|
+
[tool.setuptools.package-data]
|
|
25
|
+
pazair_verify = ["py.typed"]
|
|
@@ -0,0 +1,675 @@
|
|
|
1
|
+
"""pazair-verify for Python: check Word Passes, receipts and Merkle proofs without trusting anyone.
|
|
2
|
+
|
|
3
|
+
"May I see your Word Pass?" The other agent answers with a URL; check_word_pass(url) checks it, for any issuer:
|
|
4
|
+
the pass at the URL, the issuer's keys at <origin>/.well-known/pazair-receipts.json, the Merkle proof and the
|
|
5
|
+
root on Stellar. Specification: https://github.com/Kula-Labs/pazair/blob/main/SPEC.md
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import base64
|
|
10
|
+
from decimal import Decimal
|
|
11
|
+
import hashlib
|
|
12
|
+
import math
|
|
13
|
+
import json
|
|
14
|
+
import urllib.request
|
|
15
|
+
from typing import Any, Callable, Optional
|
|
16
|
+
from urllib.parse import urlparse
|
|
17
|
+
|
|
18
|
+
from cryptography.exceptions import InvalidSignature
|
|
19
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
|
20
|
+
|
|
21
|
+
__all__ = ["canonical", "sha256hex", "verify_signature", "verify_receipt", "leaf_of", "verify_proof", "verify_pass",
|
|
22
|
+
"word_of", "stellar_has_root", "bitcoin_has_root", "read_ots", "check_word_pass", "say_pass", "fetch_keys", "fetch_keys_document", "verify_holder_proof",
|
|
23
|
+
"receipt_hash", "verify_receipt_chain", "verify_mandate", "verify_award",
|
|
24
|
+
"FINGERPRINT", "rs_encode", "fingerprint_of", "fingerprint_distance", "fingerprint_svg", "record_of", "ridges_of"]
|
|
25
|
+
__version__ = "1.8.0"
|
|
26
|
+
|
|
27
|
+
Fetch = Callable[[str], Any] # returns parsed JSON, raises on failure
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _num(v: float) -> str:
|
|
31
|
+
# As JavaScript's JSON.stringify writes numbers: 1.0 -> 1, shortest round-trip otherwise.
|
|
32
|
+
if v != v or v in (float("inf"), float("-inf")):
|
|
33
|
+
return "null"
|
|
34
|
+
if v == 0:
|
|
35
|
+
return "0"
|
|
36
|
+
sign, digits, exp = Decimal(repr(abs(v))).normalize().as_tuple()
|
|
37
|
+
ds, n = "".join(map(str, digits)), len(digits) + exp # value = 0.ds × 10^n, ds the shortest round-trip digits
|
|
38
|
+
k, s = len(ds), "-" if v < 0 else ""
|
|
39
|
+
if k <= n <= 21:
|
|
40
|
+
return s + ds + "0" * (n - k)
|
|
41
|
+
if 0 < n <= 21:
|
|
42
|
+
return s + ds[:n] + "." + ds[n:]
|
|
43
|
+
if -6 < n <= 0:
|
|
44
|
+
return s + "0." + "0" * -n + ds
|
|
45
|
+
e = n - 1
|
|
46
|
+
return s + ds[0] + ("." + ds[1:] if k > 1 else "") + "e" + ("+" if e > 0 else "-") + str(abs(e))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def canonical(v: Any) -> str:
|
|
50
|
+
"""Object keys sorted at every level, no whitespace, values as JSON.stringify writes them."""
|
|
51
|
+
if isinstance(v, dict):
|
|
52
|
+
return "{" + ",".join(f"{json.dumps(k, ensure_ascii=False)}:{canonical(v[k])}" for k in sorted(v, key=lambda s: s.encode("utf-16-be"))) + "}"
|
|
53
|
+
if isinstance(v, list):
|
|
54
|
+
return "[" + ",".join(canonical(x) for x in v) + "]"
|
|
55
|
+
if isinstance(v, bool) or v is None:
|
|
56
|
+
return json.dumps(v)
|
|
57
|
+
if isinstance(v, (int, float)):
|
|
58
|
+
# JSON.parse reads every number as a double: integers beyond 2^53 are written as JavaScript would.
|
|
59
|
+
return _num(float(v)) if isinstance(v, float) or abs(v) > 2**53 else str(v)
|
|
60
|
+
return json.dumps(v, ensure_ascii=False)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def sha256hex(s: str) -> str:
|
|
64
|
+
return hashlib.sha256(s.encode("utf-8")).hexdigest()
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _unb64u(s: str) -> bytes:
|
|
68
|
+
return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def verify_signature(obj: dict, keys: list[dict], anchored_before: Optional[str] = None) -> bool:
|
|
72
|
+
"""Ed25519 over canonical(object without "sig"), with the key whose kid the object names.
|
|
73
|
+
A revoked key (revoked_at) signs nothing new: only what anchored_before (a root day) proves older counts."""
|
|
74
|
+
if not isinstance(obj, dict) or not isinstance(obj.get("sig"), str) or not isinstance(obj.get("kid"), str):
|
|
75
|
+
return False
|
|
76
|
+
k = next((k for k in keys if k.get("kid") == obj["kid"] and isinstance(k.get("x"), str)), None)
|
|
77
|
+
if not k or sha256hex(k["x"])[:16] != k["kid"]: # SPEC section 1: kid = sha256(x)[0:16]
|
|
78
|
+
return False
|
|
79
|
+
if k.get("revoked_at") and not (anchored_before and anchored_before < str(k["revoked_at"])[:10]):
|
|
80
|
+
return False
|
|
81
|
+
body = {key: val for key, val in obj.items() if key != "sig"}
|
|
82
|
+
try:
|
|
83
|
+
Ed25519PublicKey.from_public_bytes(_unb64u(k["x"])).verify(_unb64u(obj["sig"]), canonical(body).encode("utf-8"))
|
|
84
|
+
return True
|
|
85
|
+
except (InvalidSignature, ValueError):
|
|
86
|
+
return False
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def verify_receipt(receipt: dict, keys: list[dict], delivery: Any = None) -> dict:
|
|
90
|
+
signature_valid = isinstance(receipt.get("issuer"), str) and verify_signature(receipt, keys)
|
|
91
|
+
matches = None
|
|
92
|
+
if delivery is not None:
|
|
93
|
+
text = delivery if isinstance(delivery, str) else json.dumps(delivery, separators=(",", ":"), ensure_ascii=False)
|
|
94
|
+
matches = sha256hex(text) == receipt.get("delivery_sha256")
|
|
95
|
+
return {"valid": signature_valid and matches is not False, "signature_valid": signature_valid, "delivery_matches": matches}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def receipt_hash(receipt: dict) -> str:
|
|
99
|
+
"""Section 3.1: the hash a parent receipt names in `inputs`, the child receipt with its signature."""
|
|
100
|
+
return sha256hex(canonical(receipt))
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def verify_receipt_chain(top: dict, receipts: list[dict], keys: list[dict], max_depth: int = 8) -> dict:
|
|
104
|
+
"""Section 3.1: every input of `top` (and theirs, down the chain) present, signed, placed by the parent's
|
|
105
|
+
seller for the parent's order and delivered no later than it. Returns the first broken link."""
|
|
106
|
+
by_hash = {receipt_hash(r): r for r in receipts}
|
|
107
|
+
st = {"links": 0, "depth": 0, "total_minor": {}}
|
|
108
|
+
|
|
109
|
+
def walk(p: dict, d: int) -> Optional[str]:
|
|
110
|
+
if not verify_signature(p, keys):
|
|
111
|
+
return f"{p.get('order') if isinstance(p, dict) else None}: signature"
|
|
112
|
+
if "inputs" not in p:
|
|
113
|
+
return None
|
|
114
|
+
if not isinstance(p["inputs"], list):
|
|
115
|
+
return f"{p['order']}: inputs"
|
|
116
|
+
if p["inputs"] and d >= max_depth:
|
|
117
|
+
return f"{p['order']}: deeper than {max_depth}"
|
|
118
|
+
for h in p["inputs"]:
|
|
119
|
+
c = by_hash.get(h)
|
|
120
|
+
if c is None:
|
|
121
|
+
return f"{p['order']}: input {str(h)[:12]}… missing"
|
|
122
|
+
if c.get("parent_order") != p.get("order"):
|
|
123
|
+
return f"{c.get('order')}: parent_order is not {p.get('order')}"
|
|
124
|
+
if c.get("buyer") != p.get("seller"):
|
|
125
|
+
return f"{c.get('order')}: bought by {c.get('buyer')}, not by {p.get('seller')}"
|
|
126
|
+
if not str(c.get("delivered_at")) <= str(p.get("delivered_at")):
|
|
127
|
+
return f"{c.get('order')}: delivered after {p.get('order')}"
|
|
128
|
+
st["links"] += 1
|
|
129
|
+
st["depth"] = max(st["depth"], d + 1)
|
|
130
|
+
st["total_minor"][c["currency"]] = st["total_minor"].get(c["currency"], 0) + c["amount_minor"]
|
|
131
|
+
bad = walk(c, d + 1)
|
|
132
|
+
if bad:
|
|
133
|
+
return bad
|
|
134
|
+
return None
|
|
135
|
+
|
|
136
|
+
broken = walk(top, 0)
|
|
137
|
+
return {"valid": broken is None, **st, "broken": broken}
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def verify_mandate(receipt: dict, mandate: dict, keys: list[dict], end: Optional[dict] = None) -> dict:
|
|
141
|
+
"""Section 3.2: was this receipt bought within this mandate? Returns valid, covers (what held), reasons (what did not)."""
|
|
142
|
+
covers: list[str] = []
|
|
143
|
+
reasons: list[str] = []
|
|
144
|
+
|
|
145
|
+
def ok(cond: bool, yes: str, no: str) -> None:
|
|
146
|
+
(covers if cond else reasons).append(yes if cond else no)
|
|
147
|
+
|
|
148
|
+
sc = (mandate or {}).get("scope") or {}
|
|
149
|
+
ok(isinstance(mandate, dict) and mandate.get("kind") == "mandate" and verify_signature(mandate, keys), "mandate signed", "mandate signature")
|
|
150
|
+
ok(verify_signature(receipt, keys), "receipt signed", "receipt signature")
|
|
151
|
+
ok(receipt.get("mandate") == receipt_hash(mandate), "receipt names this mandate", "receipt names another mandate")
|
|
152
|
+
ok(receipt.get("buyer") == mandate.get("agent"), "bought by the mandated agent", f"bought by {receipt.get('buyer')}, not by {mandate.get('agent')}")
|
|
153
|
+
ok(receipt.get("currency") == sc.get("currency"), "currency within the mandate", f"currency {receipt.get('currency')}, mandate {sc.get('currency')}")
|
|
154
|
+
amt, cap = receipt.get("amount_minor"), sc.get("max_order_minor")
|
|
155
|
+
ok(isinstance(amt, int) and isinstance(cap, int) and amt <= cap, "amount within the cap per order", f"amount {amt} over the cap {cap}")
|
|
156
|
+
ok(str(mandate.get("issued_at")) <= str(receipt.get("delivered_at")), "mandate older than the delivery", "delivered before the mandate existed")
|
|
157
|
+
if end is not None:
|
|
158
|
+
ok(end.get("kind") == "mandate_end" and end.get("mandate") == receipt.get("mandate") and verify_signature(end, keys), "end statement signed", "end statement")
|
|
159
|
+
ok(str(receipt.get("delivered_at")) <= str(end.get("at")), "delivered before the mandate ended", "delivered after the mandate ended")
|
|
160
|
+
return {"valid": not reasons, "covers": covers, "reasons": reasons}
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def verify_award(receipt: dict, tender: dict, award: dict, keys: list[dict], qa: Optional[list[dict]] = None) -> dict:
|
|
164
|
+
"""Section 3.3: was this receipt paid under this award, for this tender? Returns valid, covers (what held), reasons (what did not)."""
|
|
165
|
+
covers: list[str] = []
|
|
166
|
+
reasons: list[str] = []
|
|
167
|
+
|
|
168
|
+
def ok(cond: bool, yes: str, no: str) -> None:
|
|
169
|
+
(covers if cond else reasons).append(yes if cond else no)
|
|
170
|
+
|
|
171
|
+
tender, award = tender or {}, award or {}
|
|
172
|
+
tender_hash = receipt_hash(tender)
|
|
173
|
+
ok(tender.get("kind") == "tender" and verify_signature(tender, keys), "tender signed", "tender signature")
|
|
174
|
+
ok(award.get("kind") == "award" and verify_signature(award, keys), "award signed", "award signature")
|
|
175
|
+
ok(verify_signature(receipt, keys), "receipt signed", "receipt signature")
|
|
176
|
+
ok(award.get("tender") == tender_hash, "award names this tender", "award names another tender")
|
|
177
|
+
ok(receipt.get("award") == receipt_hash(award), "receipt names this award", "receipt names another award")
|
|
178
|
+
ok(receipt.get("buyer") == tender.get("buyer"), "paid by the tendering agent", f"paid by {receipt.get('buyer')}, not by {tender.get('buyer')}")
|
|
179
|
+
ok(receipt.get("seller") == award.get("seller") and award.get("seller") != tender.get("buyer"), "delivered by the awarded seller",
|
|
180
|
+
f"delivered by {receipt.get('seller')}, awarded to {award.get('seller')}")
|
|
181
|
+
ok(receipt.get("currency") == tender.get("currency"), "currency of the tender", f"currency {receipt.get('currency')}, tender {tender.get('currency')}")
|
|
182
|
+
price, budget = award.get("price_minor"), tender.get("budget_max_minor")
|
|
183
|
+
ok(_is_int(price) and _is_num(budget) and price <= budget, "price within the budget", f"price {price} over the budget {budget}")
|
|
184
|
+
m = receipt.get("milestone")
|
|
185
|
+
ms = None
|
|
186
|
+
if m is not None:
|
|
187
|
+
mss = tender.get("milestones") or []
|
|
188
|
+
ms = mss[m] if _is_int(m) and 0 <= m < len(mss) and isinstance(mss[m], dict) else None
|
|
189
|
+
cap = price if m is None else (ms or {}).get("max_minor")
|
|
190
|
+
amt = receipt.get("amount_minor")
|
|
191
|
+
ok(_is_int(amt) and _is_int(cap) and amt <= cap, f"amount within milestone {m}" if ms else "amount within the price", f"amount {amt} over {cap}")
|
|
192
|
+
ok(str(tender.get("issued_at")) <= str(award.get("at")) <= str(receipt.get("delivered_at")), "tender, award, delivery in order", "out of order in time")
|
|
193
|
+
if tender.get("deadline") is not None:
|
|
194
|
+
ok(str(receipt.get("delivered_at")) <= str(tender["deadline"]), "delivered by the deadline", "delivered after the deadline")
|
|
195
|
+
if qa is not None:
|
|
196
|
+
held = {receipt_hash(q): q for q in qa}
|
|
197
|
+
for h in award.get("qa") or []:
|
|
198
|
+
q = held.get(h)
|
|
199
|
+
ok(isinstance(q, dict) and q.get("kind") == "tender_qa" and q.get("tender") == tender_hash and str(q.get("at")) <= str(award.get("at"))
|
|
200
|
+
and verify_signature(q, keys), f"question {h[:8]} published before the award", f"question {h[:8]} missing or invalid")
|
|
201
|
+
return {"valid": not reasons, "covers": covers, "reasons": reasons}
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _is_int(x) -> bool:
|
|
205
|
+
return isinstance(x, int) and not isinstance(x, bool)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _is_num(x) -> bool:
|
|
209
|
+
return isinstance(x, (int, float)) and not isinstance(x, bool)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def leaf_of(p: dict) -> str:
|
|
213
|
+
return sha256hex(canonical(p))
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def verify_proof(leaf: str, proof: list[dict], root: str) -> bool:
|
|
217
|
+
if not isinstance(proof, list) or not all(isinstance(s, dict) and s.get("side") in ("L", "R") and isinstance(s.get("hash"), str)
|
|
218
|
+
and len(s["hash"]) == 64 and all(c in "0123456789abcdef" for c in s["hash"]) for s in proof):
|
|
219
|
+
return False
|
|
220
|
+
h = leaf
|
|
221
|
+
for s in proof:
|
|
222
|
+
h = sha256hex(s["hash"] + h) if s["side"] == "L" else sha256hex(h + s["hash"])
|
|
223
|
+
return h == root
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def word_of(p: dict) -> dict:
|
|
227
|
+
"""SPEC section 4: kept_pct and badge as they follow from the pass's own counts."""
|
|
228
|
+
s = p.get("as_seller") or {}
|
|
229
|
+
lost, d = p.get("disputes_lost") or 0, s.get("delivered") or 0
|
|
230
|
+
closed = d + (s.get("not_delivered") or 0) + lost
|
|
231
|
+
if not closed:
|
|
232
|
+
return {"kept_pct": None, "badge": None}
|
|
233
|
+
kept = int((d - min(lost, d)) / closed * 1000) / 10
|
|
234
|
+
enough = d >= 10 and (s.get("buyers") or 0) >= 5
|
|
235
|
+
return {"kept_pct": kept, "badge": "word_kept_99" if enough and kept >= 99 else "word_kept_95" if enough and kept >= 95 else None}
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def verify_pass(anchored: dict, keys: list[dict], anchored_before: Optional[str] = None) -> dict:
|
|
239
|
+
"""A revoked key counts only with anchored_before: a day you proved yourself (a Bitcoin block time), never root.day."""
|
|
240
|
+
p = anchored.get("pass", anchored)
|
|
241
|
+
root = (anchored.get("root") or {}).get("root")
|
|
242
|
+
in_root = verify_proof(leaf_of(p), anchored["proof"], root) if anchored.get("proof") is not None and root else None
|
|
243
|
+
sig = p.get("kind") == "word_pass" and verify_signature(p, keys, anchored_before if in_root else None)
|
|
244
|
+
w, pw = word_of(p), p.get("word")
|
|
245
|
+
if pw is None: # no word, no claim
|
|
246
|
+
return {"valid": sig and in_root is not False, "signature_valid": sig, "in_root": in_root, "word_consistent": True, "word": None}
|
|
247
|
+
pk = pw.get("kept_pct")
|
|
248
|
+
consistent = (pk is None) == (w["kept_pct"] is None) and (pk is None or (isinstance(pk, (int, float)) and float(pk) == w["kept_pct"])) and pw.get("badge") == w["badge"]
|
|
249
|
+
return {"valid": sig and in_root is not False and consistent, "signature_valid": sig, "in_root": in_root, "word_consistent": consistent, "word": p.get("word")}
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _get_json(url: str) -> Any:
|
|
253
|
+
req = urllib.request.Request(url, headers={"accept": "application/json", "user-agent": "pazair-verify-python"})
|
|
254
|
+
with urllib.request.urlopen(req, timeout=8) as r: # noqa: S310 (https only, checked by callers)
|
|
255
|
+
return json.loads(r.read(200_001)[:200_000])
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _get_text(url: str) -> str:
|
|
259
|
+
req = urllib.request.Request(url, headers={"user-agent": "pazair-verify-python"})
|
|
260
|
+
with urllib.request.urlopen(req, timeout=10) as r: # noqa: S310 (fixed https explorers)
|
|
261
|
+
return r.read(1000).decode("ascii", "replace")
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def fetch_keys_document(origin: str, fetch: Fetch = _get_json) -> dict:
|
|
265
|
+
return fetch(origin.rstrip("/") + "/.well-known/pazair-receipts.json")
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def fetch_keys(origin: str, fetch: Fetch = _get_json) -> list[dict]:
|
|
269
|
+
return fetch_keys_document(origin, fetch)["keys"]
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def stellar_has_root(tx: str, root: str, fetch: Fetch = _get_json, horizon: str = "https://horizon.stellar.org", account: Optional[str] = None) -> Optional[bool]:
|
|
273
|
+
"""True on the public network; False when the transaction carries something else or comes from another account
|
|
274
|
+
than the issuer's declared anchor account; None when nobody can say."""
|
|
275
|
+
if not isinstance(tx, str) or len(tx) != 64:
|
|
276
|
+
return False
|
|
277
|
+
try:
|
|
278
|
+
t = fetch(f"{horizon}/transactions/{tx.lower()}")
|
|
279
|
+
except Exception:
|
|
280
|
+
return None
|
|
281
|
+
if t.get("memo_type") != "hash" or not isinstance(t.get("memo"), str) or t.get("successful") is not True:
|
|
282
|
+
return False
|
|
283
|
+
if account and t.get("source_account") != account:
|
|
284
|
+
return False
|
|
285
|
+
return base64.b64decode(t["memo"]).hex() == root.lower()
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
_OTS_MAGIC = bytes.fromhex("004f70656e54696d657374616d7073000050726f6f6600bf89e2e884e89294")
|
|
289
|
+
_TAG_BITCOIN = bytes.fromhex("0588960d73d71901")
|
|
290
|
+
ESPLORA = ["https://blockstream.info/api", "https://mempool.space/api"]
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def read_ots(data: bytes) -> dict:
|
|
294
|
+
"""Read an OpenTimestamps proof and walk it from its digest: {"digest": hex, "claims": [{"height", "msg"}]},
|
|
295
|
+
msg being the attested commitment in raw byte order (for Bitcoin: the block's Merkle root). Raises ValueError."""
|
|
296
|
+
pos = [0]
|
|
297
|
+
|
|
298
|
+
def byte() -> int:
|
|
299
|
+
if pos[0] >= len(data):
|
|
300
|
+
raise ValueError("ots: unexpected end")
|
|
301
|
+
pos[0] += 1
|
|
302
|
+
return data[pos[0] - 1]
|
|
303
|
+
|
|
304
|
+
def take(n: int) -> bytes:
|
|
305
|
+
if pos[0] + n > len(data):
|
|
306
|
+
raise ValueError("ots: unexpected end")
|
|
307
|
+
pos[0] += n
|
|
308
|
+
return data[pos[0] - n:pos[0]]
|
|
309
|
+
|
|
310
|
+
def uint(next_byte: Callable[[], int]) -> int:
|
|
311
|
+
v, s = 0, 0
|
|
312
|
+
while True:
|
|
313
|
+
b = next_byte()
|
|
314
|
+
v += (b & 0x7F) << s
|
|
315
|
+
if not b & 0x80:
|
|
316
|
+
return v
|
|
317
|
+
s += 7
|
|
318
|
+
if s > 49:
|
|
319
|
+
raise ValueError("ots: varuint too large")
|
|
320
|
+
|
|
321
|
+
def varbytes(mx: int) -> bytes:
|
|
322
|
+
n = uint(byte)
|
|
323
|
+
if n > mx:
|
|
324
|
+
raise ValueError("ots: too long")
|
|
325
|
+
return take(n)
|
|
326
|
+
|
|
327
|
+
def apply(tag: int, arg: Optional[bytes], m: bytes) -> Optional[bytes]:
|
|
328
|
+
if tag == 0x08:
|
|
329
|
+
return hashlib.sha256(m).digest()
|
|
330
|
+
if tag == 0x02:
|
|
331
|
+
return hashlib.sha1(m).digest() # noqa: S324 (OpenTimestamps op, not used for security here)
|
|
332
|
+
if tag == 0x03:
|
|
333
|
+
try:
|
|
334
|
+
return hashlib.new("ripemd160", m).digest()
|
|
335
|
+
except ValueError:
|
|
336
|
+
return None
|
|
337
|
+
if tag == 0xF0:
|
|
338
|
+
return m + (arg or b"")
|
|
339
|
+
if tag == 0xF1:
|
|
340
|
+
return (arg or b"") + m
|
|
341
|
+
if tag == 0xF2:
|
|
342
|
+
return m[::-1]
|
|
343
|
+
if tag == 0xF3:
|
|
344
|
+
return m.hex().encode()
|
|
345
|
+
return None
|
|
346
|
+
|
|
347
|
+
claims: list[dict] = []
|
|
348
|
+
|
|
349
|
+
def walk(m: Optional[bytes], depth: int) -> None:
|
|
350
|
+
if depth > 256:
|
|
351
|
+
raise ValueError("ots: too deep")
|
|
352
|
+
|
|
353
|
+
def item(tag: int) -> None:
|
|
354
|
+
if tag == 0x00:
|
|
355
|
+
t, payload = take(8), varbytes(8192)
|
|
356
|
+
if t == _TAG_BITCOIN and m is not None:
|
|
357
|
+
it = iter(payload)
|
|
358
|
+
claims.append({"height": uint(lambda: next(it)), "msg": m.hex()})
|
|
359
|
+
return
|
|
360
|
+
arg = None
|
|
361
|
+
if tag in (0xF0, 0xF1):
|
|
362
|
+
arg = varbytes(4096)
|
|
363
|
+
elif tag not in (0x08, 0x02, 0x03, 0x67, 0xF2, 0xF3):
|
|
364
|
+
raise ValueError(f"ots: unknown op {tag:#x}")
|
|
365
|
+
walk(apply(tag, arg, m) if m is not None else None, depth + 1)
|
|
366
|
+
|
|
367
|
+
tag = byte()
|
|
368
|
+
while tag == 0xFF:
|
|
369
|
+
item(byte())
|
|
370
|
+
tag = byte()
|
|
371
|
+
item(tag)
|
|
372
|
+
|
|
373
|
+
if take(31) != _OTS_MAGIC:
|
|
374
|
+
raise ValueError("ots: not an .ots file")
|
|
375
|
+
if uint(byte) != 1:
|
|
376
|
+
raise ValueError("ots: version")
|
|
377
|
+
if byte() != 0x08:
|
|
378
|
+
raise ValueError("ots: only sha256 files")
|
|
379
|
+
digest = take(32)
|
|
380
|
+
try:
|
|
381
|
+
walk(digest, 0)
|
|
382
|
+
except StopIteration:
|
|
383
|
+
raise ValueError("ots: payload") from None
|
|
384
|
+
if pos[0] != len(data):
|
|
385
|
+
raise ValueError("ots: trailing bytes")
|
|
386
|
+
return {"digest": digest.hex(), "claims": sorted(claims, key=lambda c: c["height"])}
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def bitcoin_has_root(ots_base64: str, root: str, fetch: Fetch = _get_json, fetch_text: Callable[[str], str] = _get_text, explorers: list[str] = ESPLORA) -> dict:
|
|
390
|
+
"""Is the root in Bitcoin? The .ots must be for exactly this root and end in the Merkle root of the block it names.
|
|
391
|
+
ok True (confirmed, with block), False (unreadable, wrong_root, wrong_block), None (pending, unverified)."""
|
|
392
|
+
try:
|
|
393
|
+
ots = read_ots(base64.b64decode(ots_base64, validate=True))
|
|
394
|
+
except Exception:
|
|
395
|
+
return {"ok": False, "status": "unreadable"}
|
|
396
|
+
if ots["digest"] != str(root).lower():
|
|
397
|
+
return {"ok": False, "status": "wrong_root"}
|
|
398
|
+
if not ots["claims"]:
|
|
399
|
+
return {"ok": None, "status": "pending"}
|
|
400
|
+
wrong = 0
|
|
401
|
+
for c in ots["claims"]:
|
|
402
|
+
if len(c["msg"]) != 64:
|
|
403
|
+
wrong += 1
|
|
404
|
+
continue
|
|
405
|
+
want = bytes.fromhex(c["msg"])[::-1].hex()
|
|
406
|
+
for base in explorers:
|
|
407
|
+
try:
|
|
408
|
+
h = fetch_text(f"{base}/block-height/{c['height']}").strip()
|
|
409
|
+
if len(h) != 64 or any(x not in "0123456789abcdef" for x in h):
|
|
410
|
+
continue
|
|
411
|
+
b = fetch(f"{base}/block/{h}")
|
|
412
|
+
if not isinstance(b.get("merkle_root"), str) or not isinstance(b.get("timestamp"), int) or b.get("height") != c["height"]:
|
|
413
|
+
continue
|
|
414
|
+
except Exception:
|
|
415
|
+
continue
|
|
416
|
+
if b["merkle_root"].lower() != want:
|
|
417
|
+
wrong += 1
|
|
418
|
+
break
|
|
419
|
+
from datetime import datetime, timezone
|
|
420
|
+
t = datetime.fromtimestamp(b["timestamp"], tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")
|
|
421
|
+
return {"ok": True, "status": "confirmed", "block": {"height": c["height"], "hash": h, "time": t}}
|
|
422
|
+
return {"ok": False, "status": "wrong_block"} if wrong == len(ots["claims"]) else {"ok": None, "status": "unverified"}
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def say_pass(p: dict, by: Optional[str] = None) -> str:
|
|
426
|
+
s, w = p.get("as_seller") or {}, p.get("word") or {}
|
|
427
|
+
|
|
428
|
+
def n(x: int, one: str) -> str:
|
|
429
|
+
return f"{x} {one if x == 1 else one + 's'}"
|
|
430
|
+
|
|
431
|
+
if s.get("delivered"):
|
|
432
|
+
record = f"{n(s['delivered'], 'paid order')} delivered to {n(s.get('buyers', 0), 'buyer')}, {n(p.get('disputes_lost', 0), 'dispute')} lost"
|
|
433
|
+
else:
|
|
434
|
+
record = f"no sales yet, {n((p.get('as_buyer') or {}).get('paid_orders', 0), 'paid purchase')}"
|
|
435
|
+
b = w.get("badge")
|
|
436
|
+
head = ("kept its word on 99 % or more" if b == "word_kept_99" else "kept its word on 95 % or more" if b == "word_kept_95"
|
|
437
|
+
else f"kept its word on {_num(float(w['kept_pct']))} % (no badge yet)" if w.get("kept_pct") is not None else "new, no record yet")
|
|
438
|
+
return f"{p.get('name')} (Word Pass by {by or p.get('issuer')}): {head}; {record}."
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def verify_holder_proof(proof: Any, keys: list[dict], agent: str, nonce: str, now: Optional[float] = None, aud: Optional[str] = None) -> dict:
|
|
442
|
+
"""The issuer signed {agent, nonce} for the agent showing the pass: it is theirs, not a copied URL."""
|
|
443
|
+
import time
|
|
444
|
+
from datetime import datetime
|
|
445
|
+
if not isinstance(proof, dict) or proof.get("kind") != "word_pass_proof":
|
|
446
|
+
return {"ok": False, "reason": "not a holder proof"}
|
|
447
|
+
if not verify_signature(proof, keys):
|
|
448
|
+
return {"ok": False, "reason": "signature does not match the issuer's key"}
|
|
449
|
+
if proof.get("agent") != agent:
|
|
450
|
+
return {"ok": False, "reason": "the proof is for another agent"}
|
|
451
|
+
if not isinstance(nonce, str) or len(nonce) < 8 or proof.get("nonce") != nonce:
|
|
452
|
+
return {"ok": False, "reason": "the proof is not for the nonce you gave"}
|
|
453
|
+
if aud is not None and proof.get("aud") != aud:
|
|
454
|
+
return {"ok": False, "reason": "the proof was made for another checker"}
|
|
455
|
+
try:
|
|
456
|
+
exp = datetime.fromisoformat(str(proof.get("exp")).replace("Z", "+00:00")).timestamp()
|
|
457
|
+
except ValueError:
|
|
458
|
+
return {"ok": False, "reason": "the proof has expired"}
|
|
459
|
+
if exp < (time.time() if now is None else now):
|
|
460
|
+
return {"ok": False, "reason": "the proof has expired"}
|
|
461
|
+
return {"ok": True, "reason": "ok"}
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def check_word_pass(url: str, fetch: Fetch = _get_json, proof: Any = None, nonce: Optional[str] = None, fetch_text: Callable[[str], str] = _get_text, aud: Optional[str] = None) -> dict:
|
|
465
|
+
"""The verdict for a pass shown by URL: kept_its_word, no_badge_yet, invalid or unreachable, with one sentence."""
|
|
466
|
+
def none(say: str) -> dict:
|
|
467
|
+
return {"trust": "unreachable", "say": say, "issuer": None, "checks": None, "pass": None}
|
|
468
|
+
|
|
469
|
+
u = urlparse(url)
|
|
470
|
+
if u.scheme != "https" or not u.netloc:
|
|
471
|
+
return none("A Word Pass is shown at a public https URL.")
|
|
472
|
+
try:
|
|
473
|
+
doc = fetch(url)
|
|
474
|
+
except Exception:
|
|
475
|
+
return none(f"No Word Pass could be read at {url}.")
|
|
476
|
+
try:
|
|
477
|
+
return _check_doc(url, u, doc, fetch, proof, nonce, fetch_text, aud)
|
|
478
|
+
except (AttributeError, KeyError, TypeError, ValueError, IndexError):
|
|
479
|
+
return none(f"The document at {url} is not a valid Word Pass.")
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def _check_doc(url, u, doc, fetch, proof, nonce, fetch_text, aud=None) -> dict:
|
|
483
|
+
def none(say: str) -> dict:
|
|
484
|
+
return {"trust": "unreachable", "say": say, "issuer": None, "checks": None, "pass": None}
|
|
485
|
+
|
|
486
|
+
anchored = doc.get("anchored") if isinstance(doc.get("anchored"), dict) and doc["anchored"].get("pass") else (doc if (doc.get("pass") or {}).get("kind") == "word_pass" else None)
|
|
487
|
+
p = anchored["pass"] if anchored else (doc.get("current") if (doc.get("current") or {}).get("kind") == "word_pass" else doc if doc.get("kind") == "word_pass" else None)
|
|
488
|
+
if not p:
|
|
489
|
+
return none(f"The document at {url} is not a Word Pass.")
|
|
490
|
+
try:
|
|
491
|
+
kd = fetch_keys_document(f"{u.scheme}://{u.netloc}", fetch)
|
|
492
|
+
keys = kd["keys"]
|
|
493
|
+
except Exception:
|
|
494
|
+
return none(f"{u.netloc} publishes no keys at /.well-known/pazair-receipts.json.")
|
|
495
|
+
v = verify_pass(anchored or p, keys)
|
|
496
|
+
root = (anchored or {}).get("root") or {}
|
|
497
|
+
st = (kd.get("anchors") or {}).get("stellar") or {}
|
|
498
|
+
account = st.get("account") if st.get("network") == "mainnet" and isinstance(st.get("account"), str) else None
|
|
499
|
+
stellar = stellar_has_root(root["stellar_tx"], root["root"], fetch, account=account) if v["in_root"] and root.get("stellar_tx") and account else None
|
|
500
|
+
btc = bitcoin_has_root(root["bitcoin_ots"], root["root"], fetch, fetch_text) if v["in_root"] and root.get("bitcoin_ots") else None
|
|
501
|
+
if not v["signature_valid"] and btc and btc.get("ok") and (btc.get("block") or {}).get("time"):
|
|
502
|
+
v = verify_pass(anchored, keys, btc["block"]["time"][:10]) # revoked key: only a Bitcoin block proves "before"
|
|
503
|
+
held = verify_holder_proof(proof, keys, p.get("agent"), nonce or "", aud=aud) if proof is not None else None
|
|
504
|
+
checks = {"signature": v["signature_valid"], "in_root": v["in_root"], "day": root.get("day"), "stellar": stellar, "stellar_account_bound": bool(stellar and account),
|
|
505
|
+
"bitcoin_ots": bool(v["in_root"] and root.get("bitcoin_ots")), "bitcoin": btc["ok"] if btc else None, "holder": held["ok"] if held else None, "word": v["word_consistent"]}
|
|
506
|
+
if btc and btc.get("block"):
|
|
507
|
+
checks["bitcoin_block"] = btc["block"]
|
|
508
|
+
issuer = u.netloc
|
|
509
|
+
if not checks["signature"]:
|
|
510
|
+
return {"trust": "invalid", "issuer": issuer, "checks": checks, "pass": p, "say": f"Do not rely on this pass: its signature does not match {issuer}'s published key."}
|
|
511
|
+
if checks["in_root"] is False:
|
|
512
|
+
return {"trust": "invalid", "issuer": issuer, "checks": checks, "pass": p, "say": f"Do not rely on this pass: its Merkle proof does not lead to the root of {checks['day']}."}
|
|
513
|
+
if stellar is False:
|
|
514
|
+
return {"trust": "invalid", "issuer": issuer, "checks": checks, "pass": p, "say": f"Do not rely on this pass: the Stellar transaction it names does not carry the root of {checks['day']} from {issuer}'s anchor account."}
|
|
515
|
+
if btc and btc["ok"] is False:
|
|
516
|
+
return {"trust": "invalid", "issuer": issuer, "checks": checks, "pass": p, "say": f"Do not rely on this pass: the Bitcoin proof it names for the root of {checks['day']} is not for that root or not in the block it claims."}
|
|
517
|
+
if not v["word_consistent"]:
|
|
518
|
+
return {"trust": "invalid", "issuer": issuer, "checks": checks, "pass": p, "say": "Do not rely on this pass: its badge does not follow from its own counts (SPEC section 4)."}
|
|
519
|
+
if held and not held["ok"]:
|
|
520
|
+
return {"trust": "invalid", "issuer": issuer, "checks": checks, "pass": p, "say": f"Do not rely on this pass: the agent showing it could not prove it is {p.get('name')} ({held['reason']}). It may be someone else's pass."}
|
|
521
|
+
found = (", found on Stellar from the issuer's anchor account" if account else ", found on Stellar") if stellar else ""
|
|
522
|
+
where = (f"in the Merkle root of {checks['day']}" + found + (f", confirmed in Bitcoin block {btc['block']['height']} ({btc['block']['time'][:10]})" if btc and btc.get("block") else ", stamped in Bitcoin (block confirmation pending)" if checks["bitcoin_ots"] else "")) if checks["in_root"] else "not anchored yet"
|
|
523
|
+
whose = " The agent showing it proved it is this agent." if held and held["ok"] else " To be sure it is theirs, give them a fresh nonce and ask for a holder proof (prove_word_pass)."
|
|
524
|
+
anchored_ok = stellar is True or bool(btc and btc.get("ok") is True)
|
|
525
|
+
trust = "no_badge_yet" if not (p.get("word") or {}).get("badge") else "kept_its_word" if anchored_ok else "signed_unanchored"
|
|
526
|
+
return {"trust": trust, "issuer": issuer, "checks": checks, "pass": p,
|
|
527
|
+
"say": f"{say_pass(p, issuer)} Checked: signature of {issuer} valid, {where}.{whose}"}
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
# Fingerprint (SPEC section 15): a print no other agent can carry, provably.
|
|
532
|
+
# seed = sha256(origin "\n" agent "\n" first_leaf); its first 10 bytes are the message of a Reed-Solomon code over
|
|
533
|
+
# GF(256) with n = 64, k = 10, so any two prints differ in at least 55 of 64 symbols. Same drawing as pazair-verify (JS).
|
|
534
|
+
_N, _K, _POLY = 64, 10, 0x11D
|
|
535
|
+
_EXP, _LOG = [0] * 512, [0] * 256
|
|
536
|
+
_x = 1
|
|
537
|
+
for _i in range(255):
|
|
538
|
+
_EXP[_i], _LOG[_x] = _x, _i
|
|
539
|
+
_x <<= 1
|
|
540
|
+
if _x & 256:
|
|
541
|
+
_x ^= _POLY
|
|
542
|
+
for _i in range(255, 512):
|
|
543
|
+
_EXP[_i] = _EXP[_i - 255]
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def _mul(a: int, b: int) -> int:
|
|
547
|
+
return _EXP[_LOG[a] + _LOG[b]] if a and b else 0
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
def _gen() -> list[int]:
|
|
551
|
+
g = [1]
|
|
552
|
+
for i in range(_N - _K):
|
|
553
|
+
r, ng = _EXP[i], [0] * (len(g) + 1)
|
|
554
|
+
for j, c in enumerate(g):
|
|
555
|
+
ng[j] ^= c
|
|
556
|
+
ng[j + 1] ^= _mul(c, r)
|
|
557
|
+
g = ng
|
|
558
|
+
return g
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
_GEN = _gen()
|
|
562
|
+
FINGERPRINT = {"n": _N, "k": _K, "d": _N - _K + 1, "field": "GF(256), polynomial 0x11d", "generator": "roots α^0 … α^53"}
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
def rs_encode(msg: bytes) -> bytes:
|
|
566
|
+
"""Systematic Reed-Solomon encoding: the first 10 bytes of msg, then 54 parity bytes."""
|
|
567
|
+
buf = bytearray(_N)
|
|
568
|
+
buf[:_K] = msg[:_K]
|
|
569
|
+
for i in range(_K):
|
|
570
|
+
c = buf[i]
|
|
571
|
+
if not c:
|
|
572
|
+
continue
|
|
573
|
+
for j in range(1, len(_GEN)):
|
|
574
|
+
buf[i + j] ^= _mul(_GEN[j], c)
|
|
575
|
+
return bytes(msg[:_K]) + bytes(buf[_K:])
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
def fingerprint_of(origin: str, agent: str, first_leaf: str) -> dict:
|
|
579
|
+
"""The seed and the codeword (lowercase hex) of an agent: the issuer's origin, the agent id, the leaf of its first anchored pass."""
|
|
580
|
+
for k, v in (("origin", origin), ("agent", agent), ("first_leaf", first_leaf)):
|
|
581
|
+
if not isinstance(v, str) or not v:
|
|
582
|
+
raise TypeError(f"fingerprint_of: {k} must be a non-empty string")
|
|
583
|
+
seed = sha256hex(f"{origin.rstrip('/')}\n{agent}\n{first_leaf}")
|
|
584
|
+
return {"seed": seed, "codeword": rs_encode(bytes.fromhex(seed)).hex()}
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
def _cw(x: Any) -> bytes:
|
|
588
|
+
b = bytes.fromhex(x["codeword"] if isinstance(x, dict) else x)
|
|
589
|
+
if len(b) != _N:
|
|
590
|
+
raise TypeError("a codeword has 64 bytes")
|
|
591
|
+
return b
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
def fingerprint_distance(a: Any, b: Any) -> int:
|
|
595
|
+
"""How many of the 64 symbols differ; never below 55 for two different seeds."""
|
|
596
|
+
return sum(1 for x, y in zip(_cw(a), _cw(b)) if x != y)
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
def record_of(p: dict) -> dict:
|
|
600
|
+
s = (p or {}).get("as_seller") or {}
|
|
601
|
+
return {"delivered": int(s.get("delivered") or 0), "buyers": int(s.get("buyers") or 0), "badge": ((p or {}).get("word") or {}).get("badge"), "disputes_lost": int((p or {}).get("disputes_lost") or 0)}
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
def ridges_of(delivered: int) -> int:
|
|
605
|
+
return min(5 + max(0, int(delivered)) // 3, 26)
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
def fingerprint_svg(codeword: Any, record: Optional[dict] = None, size: int = 360, ink: str = "currentColor", gold: str = "#d1a04a", background: str = "none") -> str:
|
|
609
|
+
"""The reference drawing (SVG), byte for byte the same as pazair-verify (JS) for the same input."""
|
|
610
|
+
cw = _cw(codeword)
|
|
611
|
+
rec = {"delivered": 0, "buyers": 0, "badge": None, "disputes_lost": 0, **(record or {})}
|
|
612
|
+
W = 360
|
|
613
|
+
cx, cy, total = W / 2, W * 0.52, ridges_of(rec["delivered"])
|
|
614
|
+
gap, r0 = (W * 0.40) / (total + 1), W * 0.06
|
|
615
|
+
raw = [((s >> 5) - 3.5) / 3.5 for s in cw]
|
|
616
|
+
sm = [(raw[(j + _N - 1) % _N] + 2 * raw[j] + raw[(j + 1) % _N]) / 4 for j in range(_N)]
|
|
617
|
+
tau = math.pi * 2
|
|
618
|
+
|
|
619
|
+
def bulge_at(th: float) -> float:
|
|
620
|
+
u = ((th / tau) * _N + _N) % _N
|
|
621
|
+
j = int(math.floor(u))
|
|
622
|
+
f = (1 - math.cos((u - j) * math.pi)) / 2
|
|
623
|
+
return sm[j] * (1 - f) + sm[(j + 1) % _N] * f
|
|
624
|
+
|
|
625
|
+
p1, p2 = (cw[0] / 255) * tau, (cw[1] / 255) * tau
|
|
626
|
+
e1, e2 = 0.06 + (cw[2] / 255) * 0.08, 0.04 + (cw[3] / 255) * 0.06
|
|
627
|
+
|
|
628
|
+
def radius_at(i: int, th: float) -> float:
|
|
629
|
+
return (r0 + i * gap) * (1 + e1 * math.cos(th - p1) * (i / total) + e2 * math.cos(2 * th - p2)) * (1 + 0.06 * bulge_at(th) * min(1, i / 3))
|
|
630
|
+
|
|
631
|
+
def f1(x: float) -> str:
|
|
632
|
+
return "%.1f" % (math.floor(x * 10 + 0.5) / 10)
|
|
633
|
+
|
|
634
|
+
paths = []
|
|
635
|
+
for i in range(total):
|
|
636
|
+
last = i == total - 1 and bool(rec["badge"])
|
|
637
|
+
closed_core = rec["buyers"] >= 5 if i < 2 else True
|
|
638
|
+
width = 2.8 if last else 1.6 + ((cw[i % _N] >> 6) & 3) * 0.2
|
|
639
|
+
d, pen = "", False
|
|
640
|
+
for k in range(257):
|
|
641
|
+
th = (k / 256) * tau - math.pi / 2
|
|
642
|
+
sector = int(math.floor((((th / tau) * _N) + _N) % _N))
|
|
643
|
+
s = cw[sector]
|
|
644
|
+
ending = (s & 31) % total == i
|
|
645
|
+
open_gap = (not closed_core) and th > math.pi * 0.12 and th < math.pi * 0.5
|
|
646
|
+
r = radius_at(i, th)
|
|
647
|
+
x, y = cx + math.cos(th) * r * 0.84, cy + math.sin(th) * r
|
|
648
|
+
if ending or open_gap:
|
|
649
|
+
pen = False
|
|
650
|
+
continue
|
|
651
|
+
d += f"{'L' if pen else 'M'}{f1(x)} {f1(y)}"
|
|
652
|
+
pen = True
|
|
653
|
+
paths.append(f'<path d="{d}" stroke="{gold if last else ink}" stroke-width="{f1(width)}"/>')
|
|
654
|
+
scars = ""
|
|
655
|
+
for dd in range(rec["disputes_lost"]):
|
|
656
|
+
th = ((cw[(dd * 11) % _N] / 255) * tau) - math.pi / 2
|
|
657
|
+
ra, rb = r0 + gap * 2.5, r0 + gap * min(total - 0.5, 7.5)
|
|
658
|
+
scars += f'<path d="M{f1(cx + math.cos(th) * ra * 0.84)} {f1(cy + math.sin(th) * ra)}L{f1(cx + math.cos(th + 0.08) * rb * 0.84)} {f1(cy + math.sin(th + 0.08) * rb)}" stroke="#000" stroke-width="7.2" stroke-linecap="round"/>'
|
|
659
|
+
mask = f'<mask id="scars"><rect width="{W}" height="{W}" fill="#fff"/>{scars}</mask>' if scars else ""
|
|
660
|
+
desc = f"Word Pass fingerprint: {total} ridges from {rec['delivered']} delivered orders; core {'closed' if rec['buyers'] >= 5 else 'open'} ({rec['buyers']} buyers); {rec['disputes_lost']} disputes lost; {('badge ' + rec['badge']) if rec['badge'] else 'no badge yet'}. Codeword {cw.hex()}."
|
|
661
|
+
bg = "" if background == "none" else f'<rect width="{W}" height="{W}" fill="{background}"/>'
|
|
662
|
+
g_mask = ' mask="url(#scars)"' if scars else ""
|
|
663
|
+
return (f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {W}" width="{size}" height="{size}" role="img" aria-label="Word Pass fingerprint">'
|
|
664
|
+
f"<title>Word Pass fingerprint</title><desc>{desc}</desc>{bg}{mask}"
|
|
665
|
+
f'<g fill="none" stroke-linecap="round" stroke-linejoin="round"{g_mask}>{"".join(paths)}</g></svg>')
|
|
666
|
+
|
|
667
|
+
|
|
668
|
+
def main() -> None:
|
|
669
|
+
import sys
|
|
670
|
+
if len(sys.argv) < 2 or sys.argv[1] in ("-h", "--help"):
|
|
671
|
+
print("Usage: pazair-verify <word pass url>")
|
|
672
|
+
raise SystemExit(0 if len(sys.argv) > 1 else 2)
|
|
673
|
+
r = check_word_pass(sys.argv[1])
|
|
674
|
+
print(r["say"])
|
|
675
|
+
raise SystemExit({"kept_its_word": 0, "no_badge_yet": 0, "signed_unanchored": 0, "invalid": 1, "unreachable": 3}.get(r["trust"], 1))
|
|
File without changes
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pazair-verify
|
|
3
|
+
Version: 1.8.0
|
|
4
|
+
Summary: Check Word Passes, receipts and Merkle proofs: "May I see your Word Pass?", checked by anyone, for any issuer.
|
|
5
|
+
Author-email: Kula Labs <hallo@kulalabs.ch>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Kula-Labs/pazair/tree/main/python
|
|
8
|
+
Project-URL: Specification, https://github.com/Kula-Labs/pazair/blob/main/SPEC.md
|
|
9
|
+
Keywords: word-pass,ai-agents,agent-trust,a2a,mcp,ed25519,merkle,bitcoin,stellar
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Typing :: Typed
|
|
14
|
+
Requires-Python: >=3.9
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Requires-Dist: cryptography>=41
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# pazair-verify (Python)
|
|
21
|
+
|
|
22
|
+
"May I see your Word Pass?" Check the URL another AI agent shows you, from any issuer, without trusting anyone.
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
pip install "git+https://github.com/Kula-Labs/pazair#subdirectory=python" # PyPI release follows
|
|
26
|
+
pazair-verify https://pazair.kulalabs.ch/v1/agents/ag_xyz/pass
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
from pazair_verify import check_word_pass
|
|
31
|
+
r = check_word_pass(url_the_other_agent_gave_you)
|
|
32
|
+
if r["trust"] == "kept_its_word": # also: signed_unanchored, no_badge_yet, invalid, unreachable
|
|
33
|
+
...
|
|
34
|
+
print(r["say"]) # one sentence for your principal
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Also: `verify_pass`, `verify_receipt`, `verify_proof`, `canonical`, `stellar_has_root`, and the fingerprint of SPEC
|
|
38
|
+
section 15: `fingerprint_of(origin, agent, first_leaf)`, `fingerprint_distance(a, b)` (two agents differ in at least 55
|
|
39
|
+
of 64 symbols) and `fingerprint_svg(codeword, record)`, byte for byte the drawing the JavaScript verifier makes. Same results as the
|
|
40
|
+
JavaScript verifier, checked against the shared [test vectors](https://github.com/Kula-Labs/pazair/blob/main/vectors/word-pass-1.json).
|
|
41
|
+
[Specification](https://github.com/Kula-Labs/pazair/blob/main/SPEC.md). MIT, by Kula Labs, Switzerland.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/pazair_verify/__init__.py
|
|
5
|
+
src/pazair_verify/__main__.py
|
|
6
|
+
src/pazair_verify/py.typed
|
|
7
|
+
src/pazair_verify.egg-info/PKG-INFO
|
|
8
|
+
src/pazair_verify.egg-info/SOURCES.txt
|
|
9
|
+
src/pazair_verify.egg-info/dependency_links.txt
|
|
10
|
+
src/pazair_verify.egg-info/entry_points.txt
|
|
11
|
+
src/pazair_verify.egg-info/requires.txt
|
|
12
|
+
src/pazair_verify.egg-info/top_level.txt
|
|
13
|
+
tests/test_award.py
|
|
14
|
+
tests/test_fingerprint.py
|
|
15
|
+
tests/test_vectors.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
cryptography>=41
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pazair_verify
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import pathlib
|
|
3
|
+
import sys
|
|
4
|
+
import unittest
|
|
5
|
+
|
|
6
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
|
|
7
|
+
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
|
|
8
|
+
|
|
9
|
+
sys.path.insert(0, str(pathlib.Path(__file__).parent.parent / "src"))
|
|
10
|
+
from pazair_verify import canonical, receipt_hash, sha256hex, verify_award # noqa: E402
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def b64u(b: bytes) -> str:
|
|
14
|
+
return base64.urlsafe_b64encode(b).decode().rstrip("=")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
SK = Ed25519PrivateKey.generate()
|
|
18
|
+
X = b64u(SK.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw))
|
|
19
|
+
KID = sha256hex(X)[:16]
|
|
20
|
+
KEYS = [{"kid": KID, "kty": "OKP", "crv": "Ed25519", "x": X}]
|
|
21
|
+
BASE = {"v": 1, "issuer": "pazair", "kid": KID}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def sign(body: dict) -> dict:
|
|
25
|
+
body = {**BASE, **body}
|
|
26
|
+
return {**body, "sig": b64u(SK.sign(canonical(body).encode()))}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
TENDER = sign({"kind": "tender", "id": "td_1", "buyer": "ag_b", "task_sha256": sha256hex("translate"), "currency": "chf", "budget_max_minor": 20000,
|
|
30
|
+
"deadline": "2026-10-20T00:00:00Z", "milestones": [{"name": "draft", "max_minor": 8000}], "mandate": None, "issued_at": "2026-10-09T10:00:00Z"})
|
|
31
|
+
QA = sign({"kind": "tender_qa", "tender": receipt_hash(TENDER), "asked_by": "ag_s", "q_sha256": "q", "a_sha256": "a", "at": "2026-10-09T11:00:00Z"})
|
|
32
|
+
AWARD = sign({"kind": "award", "tender": receipt_hash(TENDER), "seller": "ag_s", "price_minor": 15000, "qa": [receipt_hash(QA)], "at": "2026-10-09T12:00:00Z"})
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def receipt(**extra) -> dict:
|
|
36
|
+
return sign({"order": "or_1", "listing": None, "seller": "ag_s", "buyer": "ag_b", "amount_minor": 7000, "currency": "chf",
|
|
37
|
+
"delivered_at": "2026-10-10T10:00:00Z", "delivery_sha256": "x", "award": receipt_hash(AWARD), "milestone": 0, **extra})
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class AwardTest(unittest.TestCase):
|
|
41
|
+
def test_holds(self):
|
|
42
|
+
r = verify_award(receipt(), TENDER, AWARD, KEYS, [QA])
|
|
43
|
+
self.assertTrue(r["valid"], r["reasons"])
|
|
44
|
+
self.assertIn("amount within milestone 0", r["covers"])
|
|
45
|
+
|
|
46
|
+
def test_caught(self):
|
|
47
|
+
self.assertIn("amount 9000 over 8000", verify_award(receipt(amount_minor=9000), TENDER, AWARD, KEYS)["reasons"])
|
|
48
|
+
self.assertIn("delivered after the deadline", verify_award(receipt(delivered_at="2026-10-21T00:00:00Z"), TENDER, AWARD, KEYS)["reasons"])
|
|
49
|
+
self.assertIn("tender signature", verify_award(receipt(), {**TENDER, "budget_max_minor": 99999}, AWARD, KEYS)["reasons"])
|
|
50
|
+
self.assertTrue(any(x.endswith("missing or invalid") for x in verify_award(receipt(), TENDER, AWARD, KEYS, [])["reasons"]))
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
if __name__ == "__main__":
|
|
54
|
+
unittest.main()
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import pathlib
|
|
5
|
+
import sys
|
|
6
|
+
import unittest
|
|
7
|
+
|
|
8
|
+
sys.path.insert(0, str(pathlib.Path(__file__).parent.parent / "src"))
|
|
9
|
+
from pazair_verify import FINGERPRINT, fingerprint_distance, fingerprint_of, fingerprint_svg, record_of, ridges_of, rs_encode # noqa: E402
|
|
10
|
+
|
|
11
|
+
V = json.loads((pathlib.Path(__file__).parent.parent.parent / "vectors" / "word-pass-1.json").read_text())
|
|
12
|
+
F = V["fingerprint"]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Fingerprint(unittest.TestCase):
|
|
16
|
+
def test_vector(self):
|
|
17
|
+
a = fingerprint_of(F["origin"], F["agent"], F["first_leaf"])
|
|
18
|
+
self.assertEqual(a, {"seed": F["seed"], "codeword": F["codeword"]})
|
|
19
|
+
b = fingerprint_of(F["origin"], F["other"]["agent"], F["other"]["first_leaf"])
|
|
20
|
+
self.assertEqual(fingerprint_distance(a, b), F["other"]["distance"])
|
|
21
|
+
svg = fingerprint_svg(a, F["record"])
|
|
22
|
+
self.assertEqual(hashlib.sha256(svg.encode("utf-8")).hexdigest(), F["svg_sha256"])
|
|
23
|
+
self.assertEqual(svg.count("<path "), ridges_of(F["record"]["delivered"]) + F["record"]["disputes_lost"])
|
|
24
|
+
self.assertEqual(fingerprint_of(F["origin"] + "/", F["agent"], F["first_leaf"]), a)
|
|
25
|
+
|
|
26
|
+
def test_theorem(self):
|
|
27
|
+
self.assertEqual((FINGERPRINT["n"], FINGERPRINT["k"], FINGERPRINT["d"]), (64, 10, 55))
|
|
28
|
+
low = 64
|
|
29
|
+
for t in range(2000):
|
|
30
|
+
m = bytearray(os.urandom(32))
|
|
31
|
+
m2 = bytearray(m)
|
|
32
|
+
m2[t % 10] ^= 1 << (t % 8)
|
|
33
|
+
x, y = rs_encode(bytes(m)), rs_encode(bytes(m2))
|
|
34
|
+
low = min(low, sum(1 for i in range(64) if x[i] != y[i]))
|
|
35
|
+
self.assertGreaterEqual(low, 55)
|
|
36
|
+
self.assertEqual(fingerprint_distance(F["codeword"], F["codeword"]), 0)
|
|
37
|
+
with self.assertRaises(TypeError):
|
|
38
|
+
fingerprint_distance("ab", F["codeword"])
|
|
39
|
+
|
|
40
|
+
def test_record(self):
|
|
41
|
+
self.assertEqual((ridges_of(0), ridges_of(3), ridges_of(1000)), (5, 6, 26))
|
|
42
|
+
self.assertEqual(record_of(V["passes"][0]), {"delivered": 12, "buyers": 6, "badge": "word_kept_99", "disputes_lost": 0})
|
|
43
|
+
young = fingerprint_svg(F["codeword"], {"delivered": 0, "buyers": 0, "badge": None, "disputes_lost": 0})
|
|
44
|
+
old = fingerprint_svg(F["codeword"], {"delivered": 60, "buyers": 9, "badge": "word_kept_95", "disputes_lost": 2})
|
|
45
|
+
self.assertEqual((young.count("<path "), old.count("<path ")), (5, 27))
|
|
46
|
+
self.assertIn('<mask id="scars">', old)
|
|
47
|
+
self.assertNotIn("<mask", young)
|
|
48
|
+
with self.assertRaises(TypeError):
|
|
49
|
+
fingerprint_of("", "ag_x", "ab")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
if __name__ == "__main__":
|
|
53
|
+
unittest.main()
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import json
|
|
3
|
+
import pathlib
|
|
4
|
+
import sys
|
|
5
|
+
import unittest
|
|
6
|
+
|
|
7
|
+
sys.path.insert(0, str(pathlib.Path(__file__).parent.parent / "src"))
|
|
8
|
+
from pazair_verify import bitcoin_has_root, canonical, read_ots, check_word_pass, leaf_of, say_pass, sha256hex, verify_holder_proof, verify_pass, verify_proof, verify_receipt, verify_signature, receipt_hash, verify_receipt_chain, verify_mandate # noqa: E402
|
|
9
|
+
|
|
10
|
+
V = json.loads((pathlib.Path(__file__).parent.parent.parent / "vectors" / "word-pass-1.json").read_text())
|
|
11
|
+
KEYS = [V["key"]]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
B = V["bitcoin"]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def cwp(url, fetch, **k):
|
|
18
|
+
return check_word_pass(url, fetch, fetch_text=text, **k)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def text(url):
|
|
22
|
+
if url == f"https://blockstream.info/api/block-height/{B['height']}":
|
|
23
|
+
return B["block_hash"]
|
|
24
|
+
raise OSError("404")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def web(memo=V["stellar_memo"]["memo_base64"], p=V["passes"][0], source="GANCHOR", ots=B["ots_base64"], merkle=B["block_merkle_root"]):
|
|
28
|
+
doc = {"current": p, "anchored": {"pass": p, "leaf": V["leaves"][0], "proof": V["tree"]["proofs"][0], "root": {"day": "2026-10-05", "root": V["tree"]["root"], "bitcoin_ots": ots, "stellar_tx": "ab" * 32}}}
|
|
29
|
+
|
|
30
|
+
def fetch(url):
|
|
31
|
+
if url == f"https://blockstream.info/api/block/{B['block_hash']}":
|
|
32
|
+
return {"height": B["height"], "merkle_root": merkle, "timestamp": B["block_time"]}
|
|
33
|
+
if "horizon.stellar.org" in url:
|
|
34
|
+
return {"successful": True, "memo_type": "hash", "memo": memo, "source_account": source}
|
|
35
|
+
if url.endswith("/.well-known/pazair-receipts.json"):
|
|
36
|
+
return {"keys": KEYS, "anchors": {"stellar": {"account": "GANCHOR", "network": "mainnet"}}}
|
|
37
|
+
if url.endswith("/v1/agents/ag_alpha/pass"):
|
|
38
|
+
return doc
|
|
39
|
+
raise OSError("404")
|
|
40
|
+
return fetch
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Vectors(unittest.TestCase):
|
|
44
|
+
def test_published_vectors(self):
|
|
45
|
+
self.assertEqual(canonical(V["canonical"]["input"]), V["canonical"]["output"])
|
|
46
|
+
for p in V["passes"]:
|
|
47
|
+
self.assertTrue(verify_signature(p, KEYS))
|
|
48
|
+
self.assertEqual([leaf_of(p) for p in V["passes"]], V["leaves"])
|
|
49
|
+
for i, leaf in enumerate(V["leaves"]):
|
|
50
|
+
self.assertTrue(verify_proof(leaf, V["tree"]["proofs"][i], V["tree"]["root"]))
|
|
51
|
+
self.assertTrue(verify_receipt(V["receipt"]["object"], KEYS, V["receipt"]["delivery"])["valid"])
|
|
52
|
+
self.assertEqual(sha256hex(V["receipt"]["delivery"]), V["receipt"]["object"]["delivery_sha256"])
|
|
53
|
+
self.assertEqual(say_pass(V["passes"][0]), V["say"])
|
|
54
|
+
self.assertEqual(canonical({"a": 1.0, "b": 0.99, "c": 99.1}), '{"a":1,"b":0.99,"c":99.1}')
|
|
55
|
+
|
|
56
|
+
def test_bitcoin(self):
|
|
57
|
+
r = read_ots(base64.b64decode(B["ots_base64"]))
|
|
58
|
+
self.assertEqual(r["digest"], V["tree"]["root"])
|
|
59
|
+
self.assertEqual([(c["height"], bytes.fromhex(c["msg"])[::-1].hex()) for c in r["claims"]], [(B["height"], B["block_merkle_root"])])
|
|
60
|
+
url = "https://issuer.example/v1/agents/ag_alpha/pass"
|
|
61
|
+
self.assertEqual(cwp(url, web(ots=B["ots_base64"].replace("KBm0", "KBm1")))["checks"]["bitcoin"], False)
|
|
62
|
+
bad = cwp(url, web(merkle="ee" * 32))
|
|
63
|
+
self.assertEqual(bad["trust"], "invalid")
|
|
64
|
+
self.assertIn("Bitcoin proof", bad["say"])
|
|
65
|
+
self.assertEqual(cwp(url, web(ots="AA=="))["trust"], "invalid")
|
|
66
|
+
|
|
67
|
+
def down(u):
|
|
68
|
+
raise OSError("503")
|
|
69
|
+
self.assertEqual(bitcoin_has_root(B["ots_base64"], V["tree"]["root"], down, down), {"ok": None, "status": "unverified"})
|
|
70
|
+
|
|
71
|
+
def test_check_word_pass(self):
|
|
72
|
+
url = "https://issuer.example/v1/agents/ag_alpha/pass"
|
|
73
|
+
ok = cwp(url, web())
|
|
74
|
+
self.assertEqual(ok["trust"], "kept_its_word")
|
|
75
|
+
self.assertEqual(ok["checks"], {"signature": True, "in_root": True, "day": "2026-10-05", "stellar": True, "stellar_account_bound": True, "bitcoin_ots": True, "bitcoin": True,
|
|
76
|
+
"bitcoin_block": {"height": B["height"], "hash": B["block_hash"], "time": "2026-10-05T00:00:00.000Z"}, "holder": None, "word": True})
|
|
77
|
+
self.assertIn("found on Stellar from the issuer's anchor account, confirmed in Bitcoin block 915102 (2026-10-05). To be sure it is theirs", ok["say"])
|
|
78
|
+
self.assertEqual(cwp(url, web(source="GOTHER"))["trust"], "invalid")
|
|
79
|
+
self.assertEqual(cwp(url, web(base64.b64encode(b"x" * 32).decode()))["trust"], "invalid")
|
|
80
|
+
forged = dict(V["passes"][0], as_seller=dict(V["passes"][0]["as_seller"], delivered=900))
|
|
81
|
+
self.assertEqual(cwp(url, web(p=forged))["trust"], "invalid")
|
|
82
|
+
self.assertEqual(cwp("http://issuer.example/x", web())["trust"], "unreachable")
|
|
83
|
+
self.assertEqual(cwp("https://issuer.example/nothing", web())["trust"], "unreachable")
|
|
84
|
+
|
|
85
|
+
def test_numbers_as_javascript_writes_them(self):
|
|
86
|
+
cases = {1e-7: "1e-7", 1.5e-7: "1.5e-7", 0.000001: "0.000001", 1e21: "1e+21", 1e20: "100000000000000000000",
|
|
87
|
+
123456789012345678901: "123456789012345680000", 2**53 + 1: "9007199254740992", -0.0: "0", 99.1: "99.1"}
|
|
88
|
+
for v, js in cases.items():
|
|
89
|
+
self.assertEqual(canonical(v), js)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def test_holder_proof_and_revocation(self):
|
|
93
|
+
from datetime import datetime
|
|
94
|
+
h = V["holder_proof"]
|
|
95
|
+
ts = lambda x: datetime.fromisoformat(x.replace("Z", "+00:00")).timestamp() # noqa: E731
|
|
96
|
+
self.assertEqual(verify_holder_proof(h["object"], KEYS, "ag_alpha", h["object"]["nonce"], ts(h["valid_at"])), {"ok": True, "reason": "ok"})
|
|
97
|
+
self.assertFalse(verify_holder_proof(h["object"], KEYS, "ag_alpha", h["object"]["nonce"], ts(h["expired_at"]))["ok"])
|
|
98
|
+
self.assertFalse(verify_holder_proof(h["object"], KEYS, "ag_beta", h["object"]["nonce"], ts(h["valid_at"]))["ok"])
|
|
99
|
+
self.assertFalse(verify_holder_proof(h["object"], KEYS, "ag_alpha", h["object"]["nonce"], ts(h["valid_at"]), aud="ag_checker")["ok"])
|
|
100
|
+
anchored = {"pass": V["passes"][0], "proof": V["tree"]["proofs"][0], "root": {"day": "2026-10-05", "root": V["tree"]["root"]}}
|
|
101
|
+
self.assertTrue(verify_pass(anchored, [dict(V["key"], revoked_at="2026-10-06T00:00:00Z")], "2026-10-05")["valid"])
|
|
102
|
+
self.assertFalse(verify_pass(anchored, [dict(V["key"], revoked_at="2026-10-06T00:00:00Z")])["valid"])
|
|
103
|
+
self.assertFalse(verify_pass(anchored, [dict(V["key"], revoked_at="2026-10-05T12:00:00Z")], "2026-10-05")["valid"])
|
|
104
|
+
self.assertFalse(verify_pass(V["passes"][0], [dict(V["key"], revoked_at="2026-10-06T00:00:00Z")])["valid"])
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class Chain(unittest.TestCase):
|
|
108
|
+
def test_chain_vector(self):
|
|
109
|
+
c = V["chain"]
|
|
110
|
+
self.assertEqual(receipt_hash(c["receipts"][0]), c["sub_hash"])
|
|
111
|
+
self.assertEqual(verify_receipt_chain(c["top"], c["receipts"], KEYS), c["result"])
|
|
112
|
+
self.assertIn("missing", verify_receipt_chain(c["top"], [], KEYS)["broken"])
|
|
113
|
+
self.assertIn("signature", verify_receipt_chain({**c["top"], "inputs": []}, c["receipts"], KEYS)["broken"])
|
|
114
|
+
self.assertFalse(verify_receipt_chain(c["top"], c["receipts"], KEYS, max_depth=0)["valid"])
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class Mandate(unittest.TestCase):
|
|
118
|
+
def test_mandate_vector(self):
|
|
119
|
+
m = V["mandate"]
|
|
120
|
+
self.assertEqual(verify_mandate(m["receipt"], m["mandate"], KEYS, m["end"]), m["result"])
|
|
121
|
+
self.assertIn("receipt signature", verify_mandate({**m["receipt"], "amount_minor": 5000}, m["mandate"], KEYS)["reasons"])
|
|
122
|
+
self.assertIn("receipt names another mandate", verify_mandate(V["receipt"]["object"], m["mandate"], KEYS)["reasons"])
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
if __name__ == "__main__":
|
|
126
|
+
unittest.main()
|