chain-receipt 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.
- chain_receipt/__init__.py +101 -0
- chain_receipt/canonical.py +152 -0
- chain_receipt/client.py +375 -0
- chain_receipt/errors.py +27 -0
- chain_receipt/hash.py +81 -0
- chain_receipt/merkle.py +107 -0
- chain_receipt/receipt.py +327 -0
- chain_receipt/sign.py +50 -0
- chain_receipt-0.1.0.dist-info/METADATA +168 -0
- chain_receipt-0.1.0.dist-info/RECORD +13 -0
- chain_receipt-0.1.0.dist-info/WHEEL +5 -0
- chain_receipt-0.1.0.dist-info/licenses/LICENSE +21 -0
- chain_receipt-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""chain-receipt — Python client SDK for Chain Receipt.
|
|
2
|
+
|
|
3
|
+
Every proxied AI call gets a signed receipt: a canonical-JSON
|
|
4
|
+
record (schema ``air/1``) whose SHA-256 hash is signed with Ed25519
|
|
5
|
+
and anchored to Bitcoin in batches. This SDK calls the proxy, fetches
|
|
6
|
+
receipts, and verifies them offline — no network needed for the
|
|
7
|
+
signature and hash checks.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from .canonical import canonical_json, canonical_json_bytes
|
|
13
|
+
from .client import ChainReceiptClient, Client, ReceiptBundle, fetch_public_keys
|
|
14
|
+
from .errors import (
|
|
15
|
+
ApiError,
|
|
16
|
+
AuthenticationError,
|
|
17
|
+
ChainReceiptError,
|
|
18
|
+
NotFoundError,
|
|
19
|
+
RateLimitError,
|
|
20
|
+
)
|
|
21
|
+
from .hash import (
|
|
22
|
+
base64_to_bytes,
|
|
23
|
+
bytes_to_base64,
|
|
24
|
+
bytes_to_hex,
|
|
25
|
+
hash_bytes_from_tag,
|
|
26
|
+
hex_to_bytes,
|
|
27
|
+
sha256_canonical,
|
|
28
|
+
sha256_hex,
|
|
29
|
+
sha256_tagged,
|
|
30
|
+
sha256_text,
|
|
31
|
+
tag_hash_bytes,
|
|
32
|
+
)
|
|
33
|
+
from .merkle import (
|
|
34
|
+
MerkleProofStep,
|
|
35
|
+
merkle_proof,
|
|
36
|
+
merkle_root,
|
|
37
|
+
parse_proof,
|
|
38
|
+
verify_merkle_proof,
|
|
39
|
+
)
|
|
40
|
+
from .receipt import (
|
|
41
|
+
VerificationResult,
|
|
42
|
+
build_params_commitment,
|
|
43
|
+
build_prompt_commitment,
|
|
44
|
+
params_hash,
|
|
45
|
+
receipt_hash,
|
|
46
|
+
receipt_hash_bytes,
|
|
47
|
+
salted_prompt_hash,
|
|
48
|
+
salted_response_hash,
|
|
49
|
+
sign_receipt,
|
|
50
|
+
verify_receipt,
|
|
51
|
+
verify_receipt_content,
|
|
52
|
+
verify_receipt_signature,
|
|
53
|
+
)
|
|
54
|
+
from .sign import public_key_from_seed, sign_message, verify_message
|
|
55
|
+
|
|
56
|
+
__version__ = "0.1.0"
|
|
57
|
+
|
|
58
|
+
__all__ = [
|
|
59
|
+
"__version__",
|
|
60
|
+
"ChainReceiptClient",
|
|
61
|
+
"Client",
|
|
62
|
+
"ReceiptBundle",
|
|
63
|
+
"VerificationResult",
|
|
64
|
+
"MerkleProofStep",
|
|
65
|
+
"ApiError",
|
|
66
|
+
"AuthenticationError",
|
|
67
|
+
"ChainReceiptError",
|
|
68
|
+
"NotFoundError",
|
|
69
|
+
"RateLimitError",
|
|
70
|
+
"canonical_json",
|
|
71
|
+
"canonical_json_bytes",
|
|
72
|
+
"fetch_public_keys",
|
|
73
|
+
"build_prompt_commitment",
|
|
74
|
+
"build_params_commitment",
|
|
75
|
+
"params_hash",
|
|
76
|
+
"receipt_hash",
|
|
77
|
+
"receipt_hash_bytes",
|
|
78
|
+
"salted_prompt_hash",
|
|
79
|
+
"salted_response_hash",
|
|
80
|
+
"sign_receipt",
|
|
81
|
+
"verify_receipt",
|
|
82
|
+
"verify_receipt_content",
|
|
83
|
+
"verify_receipt_signature",
|
|
84
|
+
"merkle_proof",
|
|
85
|
+
"merkle_root",
|
|
86
|
+
"parse_proof",
|
|
87
|
+
"verify_merkle_proof",
|
|
88
|
+
"public_key_from_seed",
|
|
89
|
+
"sign_message",
|
|
90
|
+
"verify_message",
|
|
91
|
+
"base64_to_bytes",
|
|
92
|
+
"bytes_to_base64",
|
|
93
|
+
"bytes_to_hex",
|
|
94
|
+
"hash_bytes_from_tag",
|
|
95
|
+
"hex_to_bytes",
|
|
96
|
+
"sha256_canonical",
|
|
97
|
+
"sha256_hex",
|
|
98
|
+
"sha256_tagged",
|
|
99
|
+
"sha256_text",
|
|
100
|
+
"tag_hash_bytes",
|
|
101
|
+
]
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""Canonical JSON — RFC 8785 (JSON Canonicalization Scheme, JCS).
|
|
2
|
+
|
|
3
|
+
Every hash Chain Receipt computes runs over canonical JSON first, so
|
|
4
|
+
the same receipt always hashes the same way regardless of key order
|
|
5
|
+
or number formatting in the source object. This is a from-scratch
|
|
6
|
+
implementation of RFC 8785 (no third-party dependency): object keys
|
|
7
|
+
sorted by UTF-16 code unit, numbers serialized per ECMAScript
|
|
8
|
+
Number::toString, strings escaped per the JCS string rule.
|
|
9
|
+
|
|
10
|
+
Values JCS cannot represent raise ValueError: non-finite numbers,
|
|
11
|
+
non-string object keys, circular references, and types that are not
|
|
12
|
+
JSON values (bytes, set, arbitrary objects).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import math
|
|
18
|
+
from decimal import Decimal
|
|
19
|
+
|
|
20
|
+
__all__ = ["canonical_json", "canonical_json_bytes"]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _utf16_key(key: str) -> bytes:
|
|
24
|
+
"""Sort key for object names: the UTF-16 code-unit sequence."""
|
|
25
|
+
return key.encode("utf-16-be")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _ecmascript_number(value: float) -> str:
|
|
29
|
+
"""ECMAScript Number::toString for a finite float.
|
|
30
|
+
|
|
31
|
+
Python's repr() gives the same shortest round-trip digits as
|
|
32
|
+
ECMAScript, but not the same notation (repr switches to exponent
|
|
33
|
+
form at 1e16 / 1e-4, ECMAScript at 1e21 / 1e-6, and repr pads
|
|
34
|
+
exponents to two digits). So the digits are taken from repr and
|
|
35
|
+
the notation is applied per the ECMAScript spec (step 5 of
|
|
36
|
+
Number::toString): with s the digit string, k its length, and n
|
|
37
|
+
the decimal-point position (value = 0.s * 10**n, s[0] != "0").
|
|
38
|
+
"""
|
|
39
|
+
if value == 0:
|
|
40
|
+
return "0" # also covers -0.0: JCS serializes -0 as 0
|
|
41
|
+
if math.isnan(value) or math.isinf(value):
|
|
42
|
+
raise ValueError("canonical_json: non-finite number")
|
|
43
|
+
|
|
44
|
+
dec = Decimal(repr(value)).normalize()
|
|
45
|
+
digits_tuple = dec.as_tuple().digits
|
|
46
|
+
digits = "".join(str(d) for d in digits_tuple)
|
|
47
|
+
k = len(digits)
|
|
48
|
+
n = dec.adjusted() + 1 # decimal-point position relative to digits
|
|
49
|
+
sign = "-" if dec.as_tuple().sign else ""
|
|
50
|
+
|
|
51
|
+
if k <= n <= 21:
|
|
52
|
+
return sign + digits + "0" * (n - k)
|
|
53
|
+
if 0 < n <= 21:
|
|
54
|
+
return sign + digits[:n] + "." + digits[n:]
|
|
55
|
+
if -6 < n <= 0:
|
|
56
|
+
return sign + "0." + "0" * (-n) + digits
|
|
57
|
+
# Exponential notation: exponent is n - 1, sign always shown.
|
|
58
|
+
exp = n - 1
|
|
59
|
+
exp_str = ("+" if exp >= 0 else "-") + str(abs(exp))
|
|
60
|
+
if k == 1:
|
|
61
|
+
return sign + digits + "e" + exp_str
|
|
62
|
+
return sign + digits[0] + "." + digits[1:] + "e" + exp_str
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _number(value: int | float) -> str:
|
|
66
|
+
if isinstance(value, bool): # bool is an int subclass; handled by caller
|
|
67
|
+
raise AssertionError("bool passed to _number")
|
|
68
|
+
if isinstance(value, int):
|
|
69
|
+
# JSON integers: ECMAScript prints whole numbers in decimal
|
|
70
|
+
# notation below 1e21 and in exponent form at/above it. Python
|
|
71
|
+
# ints are exact; a JS number is a double, so beyond 2**53 the
|
|
72
|
+
# value a JS peer sees is the nearest double anyway.
|
|
73
|
+
if -10**21 < value < 10**21:
|
|
74
|
+
return str(value)
|
|
75
|
+
return _ecmascript_number(float(value))
|
|
76
|
+
return _ecmascript_number(value)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _escape_string(value: str) -> str:
|
|
80
|
+
out = ['"']
|
|
81
|
+
for ch in value:
|
|
82
|
+
code = ord(ch)
|
|
83
|
+
if ch == '"':
|
|
84
|
+
out.append('\\"')
|
|
85
|
+
elif ch == "\\":
|
|
86
|
+
out.append("\\\\")
|
|
87
|
+
elif ch == "\b":
|
|
88
|
+
out.append("\\b")
|
|
89
|
+
elif ch == "\t":
|
|
90
|
+
out.append("\\t")
|
|
91
|
+
elif ch == "\n":
|
|
92
|
+
out.append("\\n")
|
|
93
|
+
elif ch == "\f":
|
|
94
|
+
out.append("\\f")
|
|
95
|
+
elif ch == "\r":
|
|
96
|
+
out.append("\\r")
|
|
97
|
+
elif code < 0x20:
|
|
98
|
+
out.append("\\u%04x" % code)
|
|
99
|
+
elif 0xD800 <= code <= 0xDFFF:
|
|
100
|
+
# Lone surrogate (unpaired, from a JSON \uXXXX escape):
|
|
101
|
+
# JCS emits it as a \uXXXX escape rather than raw UTF-8.
|
|
102
|
+
out.append("\\u%04x" % code)
|
|
103
|
+
else:
|
|
104
|
+
out.append(ch)
|
|
105
|
+
out.append('"')
|
|
106
|
+
return "".join(out)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _serialize(value: object, active: set[int]) -> str:
|
|
110
|
+
if value is None:
|
|
111
|
+
return "null"
|
|
112
|
+
if value is True:
|
|
113
|
+
return "true"
|
|
114
|
+
if value is False:
|
|
115
|
+
return "false"
|
|
116
|
+
if isinstance(value, (int, float)):
|
|
117
|
+
return _number(value)
|
|
118
|
+
if isinstance(value, str):
|
|
119
|
+
return _escape_string(value)
|
|
120
|
+
if isinstance(value, (list, tuple)):
|
|
121
|
+
if id(value) in active:
|
|
122
|
+
raise ValueError("canonical_json: circular reference")
|
|
123
|
+
active.add(id(value))
|
|
124
|
+
try:
|
|
125
|
+
return "[" + ",".join(_serialize(item, active) for item in value) + "]"
|
|
126
|
+
finally:
|
|
127
|
+
active.discard(id(value))
|
|
128
|
+
if isinstance(value, dict):
|
|
129
|
+
if id(value) in active:
|
|
130
|
+
raise ValueError("canonical_json: circular reference")
|
|
131
|
+
for key in value:
|
|
132
|
+
if not isinstance(key, str):
|
|
133
|
+
raise ValueError("canonical_json: object keys must be strings")
|
|
134
|
+
active.add(id(value))
|
|
135
|
+
try:
|
|
136
|
+
items = sorted(value.items(), key=lambda kv: _utf16_key(kv[0]))
|
|
137
|
+
return "{" + ",".join(
|
|
138
|
+
_escape_string(k) + ":" + _serialize(v, active) for k, v in items
|
|
139
|
+
) + "}"
|
|
140
|
+
finally:
|
|
141
|
+
active.discard(id(value))
|
|
142
|
+
raise ValueError(f"canonical_json: not a JSON value ({type(value).__name__})")
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def canonical_json(value: object) -> str:
|
|
146
|
+
"""Canonicalize a JSON value to its RFC 8785 string form."""
|
|
147
|
+
return _serialize(value, set())
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def canonical_json_bytes(value: object) -> bytes:
|
|
151
|
+
"""Canonical JSON as UTF-8 bytes, ready for hashing."""
|
|
152
|
+
return canonical_json(value).encode("utf-8")
|
chain_receipt/client.py
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
"""HTTP client for the Chain Receipt v1 API.
|
|
2
|
+
|
|
3
|
+
Standard-library only (``urllib``) plus ``cryptography`` for the
|
|
4
|
+
offline verifier. The proxy is OpenAI-compatible at
|
|
5
|
+
``POST /api/v1/chat/completions`` and returns an ``ai_receipt`` with
|
|
6
|
+
the response; receipts live at ``/api/v1/receipts``; verification at
|
|
7
|
+
``POST /api/v1/verify`` (public); signing keys at
|
|
8
|
+
``/.well-known/receipt-keys.json`` (public).
|
|
9
|
+
|
|
10
|
+
No provider key is ever embedded in this package: a provider key is
|
|
11
|
+
passed per call (``X-Provider-Key``) or stored on the portal Keys
|
|
12
|
+
page, never in the SDK.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import urllib.error
|
|
20
|
+
import urllib.parse
|
|
21
|
+
import urllib.request
|
|
22
|
+
import zipfile
|
|
23
|
+
from dataclasses import dataclass
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
|
|
26
|
+
from .errors import (
|
|
27
|
+
ApiError,
|
|
28
|
+
AuthenticationError,
|
|
29
|
+
ChainReceiptError,
|
|
30
|
+
NotFoundError,
|
|
31
|
+
RateLimitError,
|
|
32
|
+
)
|
|
33
|
+
from .receipt import VerificationResult, verify_receipt
|
|
34
|
+
|
|
35
|
+
__all__ = [
|
|
36
|
+
"ChainReceiptClient",
|
|
37
|
+
"Client",
|
|
38
|
+
"ReceiptBundle",
|
|
39
|
+
"fetch_public_keys",
|
|
40
|
+
"DEFAULT_BASE_URL",
|
|
41
|
+
]
|
|
42
|
+
|
|
43
|
+
DEFAULT_BASE_URL = "https://chainreceipt.link"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _is_json_response(resp) -> bool:
|
|
47
|
+
return "application/json" in (resp.headers.get("Content-Type") or "")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def fetch_public_keys(base_url: str = DEFAULT_BASE_URL, timeout: float = 30.0) -> dict[str, str]:
|
|
51
|
+
"""Fetch the published signing keys (``/.well-known/receipt-keys.json``).
|
|
52
|
+
|
|
53
|
+
Returns ``{key_id: public_key_base64}`` for every key ever
|
|
54
|
+
published, including retired ones, so old receipts still verify.
|
|
55
|
+
Public — no API key needed.
|
|
56
|
+
"""
|
|
57
|
+
url = base_url.rstrip("/") + "/.well-known/receipt-keys.json"
|
|
58
|
+
req = urllib.request.Request(url, headers={"Accept": "application/json"})
|
|
59
|
+
try:
|
|
60
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
61
|
+
data = json.loads(resp.read().decode("utf-8"))
|
|
62
|
+
except urllib.error.HTTPError as exc:
|
|
63
|
+
raise ApiError(f"fetching public keys failed: HTTP {exc.code}", exc.code) from exc
|
|
64
|
+
except urllib.error.URLError as exc:
|
|
65
|
+
raise ChainReceiptError(f"fetching public keys failed: {exc.reason}") from exc
|
|
66
|
+
keys: dict[str, str] = {}
|
|
67
|
+
for entry in data.get("keys", []):
|
|
68
|
+
if entry.get("key_id") and entry.get("public_key"):
|
|
69
|
+
keys[entry["key_id"]] = entry["public_key"]
|
|
70
|
+
return keys
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass
|
|
74
|
+
class ReceiptBundle:
|
|
75
|
+
"""An evidence bundle for one receipt: the full envelope plus,
|
|
76
|
+
when the receipt has been batched, its ``.ots`` Bitcoin proof."""
|
|
77
|
+
|
|
78
|
+
receipt_id: str
|
|
79
|
+
envelope: dict
|
|
80
|
+
ots: bytes | None = None
|
|
81
|
+
|
|
82
|
+
def write_zip(self, path: str | Path) -> Path:
|
|
83
|
+
"""Write the bundle as a zip: ``<id>.json`` + ``<id>.ots``
|
|
84
|
+
(when present). Returns the path written."""
|
|
85
|
+
path = Path(path)
|
|
86
|
+
with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as zf:
|
|
87
|
+
zf.writestr(
|
|
88
|
+
f"{self.receipt_id}.json",
|
|
89
|
+
json.dumps(self.envelope, indent=2) + "\n",
|
|
90
|
+
)
|
|
91
|
+
if self.ots is not None:
|
|
92
|
+
zf.writestr(f"{self.receipt_id}.ots", self.ots)
|
|
93
|
+
return path
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class ChainReceiptClient:
|
|
97
|
+
"""Client for the Chain Receipt v1 API.
|
|
98
|
+
|
|
99
|
+
``api_key`` defaults to the ``CHAIN_RECEIPT_API_KEY`` environment
|
|
100
|
+
variable. ``base_url`` defaults to https://chainreceipt.link.
|
|
101
|
+
"""
|
|
102
|
+
|
|
103
|
+
def __init__(
|
|
104
|
+
self,
|
|
105
|
+
api_key: str | None = None,
|
|
106
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
107
|
+
timeout: float = 30.0,
|
|
108
|
+
):
|
|
109
|
+
self.api_key = api_key or os.environ.get("CHAIN_RECEIPT_API_KEY", "")
|
|
110
|
+
self.base_url = base_url.rstrip("/")
|
|
111
|
+
self.timeout = timeout
|
|
112
|
+
|
|
113
|
+
# -- low-level request -------------------------------------------
|
|
114
|
+
|
|
115
|
+
def _headers(self, extra: dict | None = None) -> dict:
|
|
116
|
+
headers = {"Accept": "application/json"}
|
|
117
|
+
if self.api_key:
|
|
118
|
+
headers["Authorization"] = f"Bearer {self.api_key}"
|
|
119
|
+
if extra:
|
|
120
|
+
headers.update(extra)
|
|
121
|
+
return headers
|
|
122
|
+
|
|
123
|
+
def _request(
|
|
124
|
+
self,
|
|
125
|
+
method: str,
|
|
126
|
+
path: str,
|
|
127
|
+
*,
|
|
128
|
+
params: dict | None = None,
|
|
129
|
+
body: dict | None = None,
|
|
130
|
+
auth: bool = True,
|
|
131
|
+
extra_headers: dict | None = None,
|
|
132
|
+
):
|
|
133
|
+
url = self.base_url + path
|
|
134
|
+
if params:
|
|
135
|
+
query = urllib.parse.urlencode(
|
|
136
|
+
{k: v for k, v in params.items() if v is not None}
|
|
137
|
+
)
|
|
138
|
+
if query:
|
|
139
|
+
url += "?" + query
|
|
140
|
+
data = None
|
|
141
|
+
headers = self._headers(extra_headers)
|
|
142
|
+
if not auth:
|
|
143
|
+
headers.pop("Authorization", None)
|
|
144
|
+
if body is not None:
|
|
145
|
+
data = json.dumps(body).encode("utf-8")
|
|
146
|
+
headers["Content-Type"] = "application/json"
|
|
147
|
+
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
|
148
|
+
try:
|
|
149
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
|
150
|
+
raw = resp.read()
|
|
151
|
+
if _is_json_response(resp):
|
|
152
|
+
return json.loads(raw.decode("utf-8"))
|
|
153
|
+
return raw
|
|
154
|
+
except urllib.error.HTTPError as exc:
|
|
155
|
+
detail = ""
|
|
156
|
+
try:
|
|
157
|
+
payload = json.loads(exc.read().decode("utf-8"))
|
|
158
|
+
detail = (
|
|
159
|
+
payload.get("error", {}).get("message")
|
|
160
|
+
or payload.get("error")
|
|
161
|
+
or payload.get("message")
|
|
162
|
+
or ""
|
|
163
|
+
)
|
|
164
|
+
except Exception:
|
|
165
|
+
pass
|
|
166
|
+
message = detail or f"HTTP {exc.code}"
|
|
167
|
+
if exc.code in (401, 403):
|
|
168
|
+
raise AuthenticationError(message) from exc
|
|
169
|
+
if exc.code == 404:
|
|
170
|
+
raise NotFoundError(message) from exc
|
|
171
|
+
if exc.code == 429:
|
|
172
|
+
raise RateLimitError(message) from exc
|
|
173
|
+
raise ApiError(message, exc.code) from exc
|
|
174
|
+
except urllib.error.URLError as exc:
|
|
175
|
+
raise ChainReceiptError(f"request failed: {exc.reason}") from exc
|
|
176
|
+
|
|
177
|
+
def _require_key(self) -> None:
|
|
178
|
+
if not self.api_key:
|
|
179
|
+
raise AuthenticationError(
|
|
180
|
+
"no API key: pass api_key= or set CHAIN_RECEIPT_API_KEY"
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
# -- receipts -----------------------------------------------------
|
|
184
|
+
|
|
185
|
+
def get_receipt(self, receipt_id: str) -> dict:
|
|
186
|
+
"""The full ``air/1`` envelope for one receipt: receipt,
|
|
187
|
+
receipt_hash, signature, anchor info, verify URL."""
|
|
188
|
+
self._require_key()
|
|
189
|
+
return self._request("GET", f"/api/v1/receipts/{receipt_id}")
|
|
190
|
+
|
|
191
|
+
def list_receipts(
|
|
192
|
+
self,
|
|
193
|
+
*,
|
|
194
|
+
limit: int = 50,
|
|
195
|
+
cursor: str | None = None,
|
|
196
|
+
status: str | None = None,
|
|
197
|
+
from_: str | None = None,
|
|
198
|
+
to: str | None = None,
|
|
199
|
+
api_key: str | None = None,
|
|
200
|
+
ref: str | None = None,
|
|
201
|
+
) -> dict:
|
|
202
|
+
"""The org's receipts, newest first. Returns the list page
|
|
203
|
+
(``object: "list"``, ``data``, ``has_more``, ``next_cursor``).
|
|
204
|
+
``from_``/``to`` are ISO 8601 dates; ``status`` is one of
|
|
205
|
+
``complete`` / ``incomplete`` / ``upstream_error``."""
|
|
206
|
+
self._require_key()
|
|
207
|
+
if not 1 <= limit <= 100:
|
|
208
|
+
raise ValueError("limit must be between 1 and 100")
|
|
209
|
+
return self._request(
|
|
210
|
+
"GET",
|
|
211
|
+
"/api/v1/receipts",
|
|
212
|
+
params={
|
|
213
|
+
"limit": limit,
|
|
214
|
+
"cursor": cursor,
|
|
215
|
+
"status": status,
|
|
216
|
+
"from": from_,
|
|
217
|
+
"to": to,
|
|
218
|
+
"api_key": api_key,
|
|
219
|
+
"ref": ref,
|
|
220
|
+
},
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
def iter_receipts(self, **kwargs) -> dict:
|
|
224
|
+
"""Yield every receipt across pages (same filters as
|
|
225
|
+
:meth:`list_receipts`)."""
|
|
226
|
+
cursor = kwargs.pop("cursor", None)
|
|
227
|
+
while True:
|
|
228
|
+
page = self.list_receipts(cursor=cursor, **kwargs)
|
|
229
|
+
yield from page.get("data", [])
|
|
230
|
+
if not page.get("has_more"):
|
|
231
|
+
return
|
|
232
|
+
cursor = page.get("next_cursor")
|
|
233
|
+
|
|
234
|
+
def download_ots(self, receipt_id: str) -> bytes | None:
|
|
235
|
+
"""The batch's ``.ots`` proof as bytes, or None when the
|
|
236
|
+
receipt has not been batched yet."""
|
|
237
|
+
self._require_key()
|
|
238
|
+
try:
|
|
239
|
+
raw = self._request("GET", f"/api/v1/receipts/{receipt_id}/ots")
|
|
240
|
+
except NotFoundError:
|
|
241
|
+
return None
|
|
242
|
+
return raw if isinstance(raw, bytes) else raw.encode("utf-8")
|
|
243
|
+
|
|
244
|
+
def download_bundle(self, receipt_id: str, path: str | Path | None = None) -> ReceiptBundle:
|
|
245
|
+
"""Download the evidence bundle for a receipt: the full
|
|
246
|
+
envelope plus its ``.ots`` Bitcoin proof when batched.
|
|
247
|
+
|
|
248
|
+
With ``path``, also writes the bundle as a zip
|
|
249
|
+
(``<id>.json`` + ``<id>.ots``) and returns the bundle.
|
|
250
|
+
"""
|
|
251
|
+
envelope = self.get_receipt(receipt_id)
|
|
252
|
+
ots = self.download_ots(receipt_id)
|
|
253
|
+
bundle = ReceiptBundle(receipt_id=receipt_id, envelope=envelope, ots=ots)
|
|
254
|
+
if path is not None:
|
|
255
|
+
bundle.write_zip(path)
|
|
256
|
+
return bundle
|
|
257
|
+
|
|
258
|
+
# -- verification --------------------------------------------------
|
|
259
|
+
|
|
260
|
+
def verify_receipt_online(self, receipt_id: str | None = None, envelope: dict | None = None) -> dict:
|
|
261
|
+
"""Ask the server to verify a receipt (``POST /v1/verify``,
|
|
262
|
+
public — no API key). Pass either a ``receipt_id`` or a full
|
|
263
|
+
envelope. Returns the server verdict (``valid``, per-check
|
|
264
|
+
``checks``, ``anchor``)."""
|
|
265
|
+
if receipt_id is not None:
|
|
266
|
+
body = {"receipt_id": receipt_id}
|
|
267
|
+
elif envelope is not None:
|
|
268
|
+
body = dict(envelope)
|
|
269
|
+
else:
|
|
270
|
+
raise ValueError("pass receipt_id or envelope")
|
|
271
|
+
return self._request("POST", "/api/v1/verify", body=body, auth=False)
|
|
272
|
+
|
|
273
|
+
def verify_receipt(self, receipt_id: str) -> VerificationResult:
|
|
274
|
+
"""Fetch a receipt's envelope and verify it OFFLINE: the
|
|
275
|
+
receipt hash is recomputed and the Ed25519 signature is
|
|
276
|
+
checked against the published public key for its key id.
|
|
277
|
+
No provider content is involved — only hashes."""
|
|
278
|
+
envelope = self.get_receipt(receipt_id)
|
|
279
|
+
key_id = (envelope.get("signature") or {}).get("key_id")
|
|
280
|
+
keys = fetch_public_keys(self.base_url, timeout=self.timeout)
|
|
281
|
+
public_key = keys.get(key_id) if key_id else None
|
|
282
|
+
return verify_receipt(envelope, public_key=public_key)
|
|
283
|
+
|
|
284
|
+
def verify_envelope(self, envelope: dict) -> VerificationResult:
|
|
285
|
+
"""Verify an envelope already in hand, resolving its signing
|
|
286
|
+
key from the published key list."""
|
|
287
|
+
key_id = (envelope.get("signature") or {}).get("key_id")
|
|
288
|
+
keys = fetch_public_keys(self.base_url, timeout=self.timeout)
|
|
289
|
+
public_key = keys.get(key_id) if key_id else None
|
|
290
|
+
return verify_receipt(envelope, public_key=public_key)
|
|
291
|
+
|
|
292
|
+
# -- proxy ---------------------------------------------------------
|
|
293
|
+
|
|
294
|
+
def chat_completions(
|
|
295
|
+
self,
|
|
296
|
+
model: str,
|
|
297
|
+
messages: list,
|
|
298
|
+
*,
|
|
299
|
+
provider_key: str | None = None,
|
|
300
|
+
stream: bool = False,
|
|
301
|
+
**params,
|
|
302
|
+
):
|
|
303
|
+
"""Call the OpenAI-compatible proxy (``POST
|
|
304
|
+
/api/v1/chat/completions``). ``model`` is prefixed with the
|
|
305
|
+
provider, e.g. ``"openai/gpt-6-luna"``,
|
|
306
|
+
``"anthropic/claude-haiku-4-5"``, ``"google/gemini-3.5-flash"``.
|
|
307
|
+
|
|
308
|
+
Non-streaming returns the provider JSON plus ``ai_receipt``
|
|
309
|
+
(``receipt_id``, ``receipt_hash``, ``signature``, ``salts`` —
|
|
310
|
+
the salts are returned ONCE, keep them to re-verify content
|
|
311
|
+
later). With ``stream=True`` returns an iterator of parsed
|
|
312
|
+
SSE events; the last event carries ``ai_receipt``.
|
|
313
|
+
|
|
314
|
+
``provider_key`` is sent per call as ``X-Provider-Key``; omit
|
|
315
|
+
it when the provider key is stored on the portal Keys page.
|
|
316
|
+
"""
|
|
317
|
+
self._require_key()
|
|
318
|
+
body = {"model": model, "messages": messages, "stream": stream}
|
|
319
|
+
body.update(params)
|
|
320
|
+
if not stream:
|
|
321
|
+
return self._request(
|
|
322
|
+
"POST", "/api/v1/chat/completions", body=body,
|
|
323
|
+
extra_headers={"X-Provider-Key": provider_key} if provider_key else None,
|
|
324
|
+
)
|
|
325
|
+
# Streaming: parse SSE by hand over urllib.
|
|
326
|
+
headers = self._headers()
|
|
327
|
+
if provider_key:
|
|
328
|
+
headers["X-Provider-Key"] = provider_key
|
|
329
|
+
data = json.dumps(body).encode("utf-8")
|
|
330
|
+
headers["Content-Type"] = "application/json"
|
|
331
|
+
req = urllib.request.Request(
|
|
332
|
+
self.base_url + "/api/v1/chat/completions",
|
|
333
|
+
data=data, headers=headers, method="POST",
|
|
334
|
+
)
|
|
335
|
+
try:
|
|
336
|
+
resp = urllib.request.urlopen(req, timeout=self.timeout)
|
|
337
|
+
except urllib.error.HTTPError as exc:
|
|
338
|
+
detail = ""
|
|
339
|
+
try:
|
|
340
|
+
payload = json.loads(exc.read().decode("utf-8"))
|
|
341
|
+
detail = payload.get("error", {}).get("message") or ""
|
|
342
|
+
except Exception:
|
|
343
|
+
pass
|
|
344
|
+
if exc.code in (401, 403):
|
|
345
|
+
raise AuthenticationError(detail or f"HTTP {exc.code}") from exc
|
|
346
|
+
raise ApiError(detail or f"HTTP {exc.code}", exc.code) from exc
|
|
347
|
+
return _iter_sse(resp)
|
|
348
|
+
|
|
349
|
+
def list_models(self) -> dict:
|
|
350
|
+
"""The models the org can actually call, per provider
|
|
351
|
+
(OpenAI-shaped list)."""
|
|
352
|
+
self._require_key()
|
|
353
|
+
return self._request("GET", "/api/v1/models")
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _iter_sse(resp):
|
|
357
|
+
"""Yield parsed SSE ``data:`` payloads until ``[DONE]``."""
|
|
358
|
+
try:
|
|
359
|
+
for raw_line in resp:
|
|
360
|
+
line = raw_line.decode("utf-8").strip()
|
|
361
|
+
if not line.startswith("data:"):
|
|
362
|
+
continue
|
|
363
|
+
payload = line[5:].strip()
|
|
364
|
+
if payload == "[DONE]":
|
|
365
|
+
return
|
|
366
|
+
try:
|
|
367
|
+
yield json.loads(payload)
|
|
368
|
+
except json.JSONDecodeError:
|
|
369
|
+
continue
|
|
370
|
+
finally:
|
|
371
|
+
resp.close()
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
# Backwards-friendly alias.
|
|
375
|
+
Client = ChainReceiptClient
|
chain_receipt/errors.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Errors raised by the Chain Receipt SDK."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class ChainReceiptError(Exception):
|
|
7
|
+
"""Base class for all SDK errors."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class AuthenticationError(ChainReceiptError):
|
|
11
|
+
"""The API key was missing, invalid, or revoked (HTTP 401/403)."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class NotFoundError(ChainReceiptError):
|
|
15
|
+
"""The requested receipt (or resource) does not exist (HTTP 404)."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class RateLimitError(ChainReceiptError):
|
|
19
|
+
"""The request was rate-limited (HTTP 429)."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ApiError(ChainReceiptError):
|
|
23
|
+
"""Any other API error. ``status`` is the HTTP status code."""
|
|
24
|
+
|
|
25
|
+
def __init__(self, message: str, status: int | None = None):
|
|
26
|
+
super().__init__(message)
|
|
27
|
+
self.status = status
|