chain-receipt 0.1.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.
- chain_receipt-0.1.0/LICENSE +21 -0
- chain_receipt-0.1.0/PKG-INFO +168 -0
- chain_receipt-0.1.0/README.md +138 -0
- chain_receipt-0.1.0/pyproject.toml +48 -0
- chain_receipt-0.1.0/setup.cfg +4 -0
- chain_receipt-0.1.0/src/chain_receipt/__init__.py +101 -0
- chain_receipt-0.1.0/src/chain_receipt/canonical.py +152 -0
- chain_receipt-0.1.0/src/chain_receipt/client.py +375 -0
- chain_receipt-0.1.0/src/chain_receipt/errors.py +27 -0
- chain_receipt-0.1.0/src/chain_receipt/hash.py +81 -0
- chain_receipt-0.1.0/src/chain_receipt/merkle.py +107 -0
- chain_receipt-0.1.0/src/chain_receipt/receipt.py +327 -0
- chain_receipt-0.1.0/src/chain_receipt/sign.py +50 -0
- chain_receipt-0.1.0/src/chain_receipt.egg-info/PKG-INFO +168 -0
- chain_receipt-0.1.0/src/chain_receipt.egg-info/SOURCES.txt +21 -0
- chain_receipt-0.1.0/src/chain_receipt.egg-info/dependency_links.txt +1 -0
- chain_receipt-0.1.0/src/chain_receipt.egg-info/requires.txt +6 -0
- chain_receipt-0.1.0/src/chain_receipt.egg-info/top_level.txt +1 -0
- chain_receipt-0.1.0/tests/test_canonical.py +79 -0
- chain_receipt-0.1.0/tests/test_client.py +145 -0
- chain_receipt-0.1.0/tests/test_golden.py +64 -0
- chain_receipt-0.1.0/tests/test_live.py +56 -0
- chain_receipt-0.1.0/tests/test_verify.py +253 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Cinian Studios Inc.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: chain-receipt
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Chain Receipt — verified AI output receipts. Client SDK for the OpenAI-compatible proxy and the offline receipt verifier.
|
|
5
|
+
Author: Cinian Studios Inc.
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://chainreceipt.link
|
|
8
|
+
Project-URL: Repository, https://github.com/CinianStudios/chain-receipt
|
|
9
|
+
Project-URL: Documentation, https://chainreceipt.link/docs
|
|
10
|
+
Project-URL: Issue Tracker, https://github.com/CinianStudios/chain-receipt/issues
|
|
11
|
+
Keywords: ai,receipts,verification,ed25519,openai,chain-receipt
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
|
19
|
+
Classifier: Topic :: Security :: Cryptography
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.11
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Requires-Dist: cryptography>=42
|
|
25
|
+
Provides-Extra: dev
|
|
26
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
27
|
+
Requires-Dist: build>=1; extra == "dev"
|
|
28
|
+
Requires-Dist: twine>=5; extra == "dev"
|
|
29
|
+
Dynamic: license-file
|
|
30
|
+
|
|
31
|
+
# chain-receipt — Python SDK
|
|
32
|
+
|
|
33
|
+
Verified AI output receipts. Every call through the Chain Receipt
|
|
34
|
+
proxy gets a signed receipt: a canonical-JSON record (schema `air/1`)
|
|
35
|
+
whose SHA-256 hash is signed with Ed25519 and anchored to Bitcoin in
|
|
36
|
+
batches. This SDK calls the proxy, fetches receipts, downloads
|
|
37
|
+
evidence bundles, and verifies receipts **offline** — the signature
|
|
38
|
+
and hash checks need no network.
|
|
39
|
+
|
|
40
|
+
## Install
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip install chain-receipt
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Requires Python 3.11+. The only runtime dependency is
|
|
47
|
+
[`cryptography`](https://cryptography.io/) (for Ed25519); HTTP uses
|
|
48
|
+
the standard library.
|
|
49
|
+
|
|
50
|
+
## Quickstart
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from chain_receipt import ChainReceiptClient
|
|
54
|
+
|
|
55
|
+
client = ChainReceiptClient(api_key="crk_live_...") # or set CHAIN_RECEIPT_API_KEY
|
|
56
|
+
|
|
57
|
+
# 1. Call any model through the OpenAI-compatible proxy.
|
|
58
|
+
resp = client.chat_completions(
|
|
59
|
+
model="openai/gpt-6-luna",
|
|
60
|
+
messages=[{"role": "user", "content": "Say the word receipt."}],
|
|
61
|
+
max_tokens=20,
|
|
62
|
+
)
|
|
63
|
+
print(resp["choices"][0]["message"]["content"])
|
|
64
|
+
receipt_id = resp["ai_receipt"]["receipt_id"] # keep the salts too:
|
|
65
|
+
salts = resp["ai_receipt"]["salts"] # returned ONCE, never stored
|
|
66
|
+
|
|
67
|
+
# 2. Fetch the receipt envelope and verify it offline.
|
|
68
|
+
result = client.verify_receipt(receipt_id)
|
|
69
|
+
print(result.valid, result.hash_ok, result.signature_ok) # True True True
|
|
70
|
+
|
|
71
|
+
# 3. Or verify an envelope you already hold, with no client at all.
|
|
72
|
+
from chain_receipt import verify_receipt, fetch_public_keys
|
|
73
|
+
|
|
74
|
+
keys = fetch_public_keys() # /.well-known/receipt-keys.json (public)
|
|
75
|
+
result = verify_receipt(envelope, public_keys=keys)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Receipts
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
# One receipt, full envelope (receipt, receipt_hash, signature, anchor, verify_url)
|
|
82
|
+
envelope = client.get_receipt("rcpt_...")
|
|
83
|
+
|
|
84
|
+
# Newest first, paginated (limit 1–100, default 50)
|
|
85
|
+
page = client.list_receipts(limit=10, status="complete")
|
|
86
|
+
for row in client.iter_receipts(): # walks every page
|
|
87
|
+
print(row["receipt_id"], row["anchor_status"])
|
|
88
|
+
|
|
89
|
+
# Evidence bundle: envelope JSON + .ots Bitcoin proof (when batched)
|
|
90
|
+
bundle = client.download_bundle("rcpt_...", path="rcpt_....zip")
|
|
91
|
+
print(bundle.ots is not None) # False until the receipt is batched
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## Verify content, not just the signature
|
|
95
|
+
|
|
96
|
+
The receipt stores hashes of your prompt and the response, salted so
|
|
97
|
+
a short prompt cannot be guessed. Re-hash your own copies to prove
|
|
98
|
+
the receipt is *about* your call:
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
from chain_receipt import build_prompt_commitment, verify_receipt_content
|
|
102
|
+
|
|
103
|
+
ok = verify_receipt_content(
|
|
104
|
+
envelope["receipt"],
|
|
105
|
+
salts, # from ai_receipt, returned once at call time
|
|
106
|
+
prompt_body=build_prompt_commitment(
|
|
107
|
+
messages=[{"role": "user", "content": "Say the word receipt."}]
|
|
108
|
+
),
|
|
109
|
+
response_json=resp, # the full provider response object
|
|
110
|
+
)
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## Streaming
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
events = client.chat_completions(
|
|
117
|
+
model="google/gemini-3.5-flash",
|
|
118
|
+
messages=[{"role": "user", "content": "Count to three."}],
|
|
119
|
+
max_tokens=30,
|
|
120
|
+
stream=True,
|
|
121
|
+
)
|
|
122
|
+
for event in events:
|
|
123
|
+
if event.get("object") == "ai_receipt":
|
|
124
|
+
print("receipt:", event["ai_receipt"]["receipt_id"])
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## Bring your own provider key
|
|
128
|
+
|
|
129
|
+
Pass it per call (never stored by the SDK) or save it on the portal
|
|
130
|
+
Keys page and omit it:
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
resp = client.chat_completions(
|
|
134
|
+
model="anthropic/claude-haiku-4-5",
|
|
135
|
+
messages=[{"role": "user", "content": "Say the word receipt."}],
|
|
136
|
+
provider_key="sk-ant-...", # sent as X-Provider-Key
|
|
137
|
+
)
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
## What is verified, exactly
|
|
141
|
+
|
|
142
|
+
`verify_receipt` checks, each reported separately:
|
|
143
|
+
|
|
144
|
+
- **hash** — `receipt_hash` recomputes from the receipt object
|
|
145
|
+
(SHA-256 over RFC 8785 canonical JSON).
|
|
146
|
+
- **signature** — Ed25519 verifies over the 32 raw hash bytes,
|
|
147
|
+
against the published public key for `signature.key_id`.
|
|
148
|
+
- **merkle** — when the envelope carries an anchor proof, the leaf +
|
|
149
|
+
proof recompute to the batch root (otherwise `None`).
|
|
150
|
+
|
|
151
|
+
`valid` is true when every check that could run passed. A genuine
|
|
152
|
+
receipt is valid before its batch confirms on Bitcoin — anchor
|
|
153
|
+
status is reported separately in the envelope.
|
|
154
|
+
|
|
155
|
+
## Golden vectors
|
|
156
|
+
|
|
157
|
+
The primitives in this SDK (JCS, Ed25519, SHA-256, Merkle root) pass
|
|
158
|
+
the same golden vectors as `@chain-receipt/core`, the verifier, and
|
|
159
|
+
the JS SDK: `packages/core/test-vectors/golden.json` (JCS from RFC
|
|
160
|
+
8785 §3.2.3, Ed25519 from RFC 8032 test 1, SHA-256 from FIPS 180-4).
|
|
161
|
+
Run them with `pytest` in `packages/sdk-py`.
|
|
162
|
+
|
|
163
|
+
## Links
|
|
164
|
+
|
|
165
|
+
- Site: https://chainreceipt.link
|
|
166
|
+
- Docs: https://chainreceipt.link/docs
|
|
167
|
+
- Verify a receipt in the browser: https://chainreceipt.link/verify
|
|
168
|
+
- Published signing keys: https://chainreceipt.link/.well-known/receipt-keys.json
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
# chain-receipt — Python SDK
|
|
2
|
+
|
|
3
|
+
Verified AI output receipts. Every call through the Chain Receipt
|
|
4
|
+
proxy gets a signed receipt: a canonical-JSON record (schema `air/1`)
|
|
5
|
+
whose SHA-256 hash is signed with Ed25519 and anchored to Bitcoin in
|
|
6
|
+
batches. This SDK calls the proxy, fetches receipts, downloads
|
|
7
|
+
evidence bundles, and verifies receipts **offline** — the signature
|
|
8
|
+
and hash checks need no network.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
pip install chain-receipt
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Requires Python 3.11+. The only runtime dependency is
|
|
17
|
+
[`cryptography`](https://cryptography.io/) (for Ed25519); HTTP uses
|
|
18
|
+
the standard library.
|
|
19
|
+
|
|
20
|
+
## Quickstart
|
|
21
|
+
|
|
22
|
+
```python
|
|
23
|
+
from chain_receipt import ChainReceiptClient
|
|
24
|
+
|
|
25
|
+
client = ChainReceiptClient(api_key="crk_live_...") # or set CHAIN_RECEIPT_API_KEY
|
|
26
|
+
|
|
27
|
+
# 1. Call any model through the OpenAI-compatible proxy.
|
|
28
|
+
resp = client.chat_completions(
|
|
29
|
+
model="openai/gpt-6-luna",
|
|
30
|
+
messages=[{"role": "user", "content": "Say the word receipt."}],
|
|
31
|
+
max_tokens=20,
|
|
32
|
+
)
|
|
33
|
+
print(resp["choices"][0]["message"]["content"])
|
|
34
|
+
receipt_id = resp["ai_receipt"]["receipt_id"] # keep the salts too:
|
|
35
|
+
salts = resp["ai_receipt"]["salts"] # returned ONCE, never stored
|
|
36
|
+
|
|
37
|
+
# 2. Fetch the receipt envelope and verify it offline.
|
|
38
|
+
result = client.verify_receipt(receipt_id)
|
|
39
|
+
print(result.valid, result.hash_ok, result.signature_ok) # True True True
|
|
40
|
+
|
|
41
|
+
# 3. Or verify an envelope you already hold, with no client at all.
|
|
42
|
+
from chain_receipt import verify_receipt, fetch_public_keys
|
|
43
|
+
|
|
44
|
+
keys = fetch_public_keys() # /.well-known/receipt-keys.json (public)
|
|
45
|
+
result = verify_receipt(envelope, public_keys=keys)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Receipts
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
# One receipt, full envelope (receipt, receipt_hash, signature, anchor, verify_url)
|
|
52
|
+
envelope = client.get_receipt("rcpt_...")
|
|
53
|
+
|
|
54
|
+
# Newest first, paginated (limit 1–100, default 50)
|
|
55
|
+
page = client.list_receipts(limit=10, status="complete")
|
|
56
|
+
for row in client.iter_receipts(): # walks every page
|
|
57
|
+
print(row["receipt_id"], row["anchor_status"])
|
|
58
|
+
|
|
59
|
+
# Evidence bundle: envelope JSON + .ots Bitcoin proof (when batched)
|
|
60
|
+
bundle = client.download_bundle("rcpt_...", path="rcpt_....zip")
|
|
61
|
+
print(bundle.ots is not None) # False until the receipt is batched
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## Verify content, not just the signature
|
|
65
|
+
|
|
66
|
+
The receipt stores hashes of your prompt and the response, salted so
|
|
67
|
+
a short prompt cannot be guessed. Re-hash your own copies to prove
|
|
68
|
+
the receipt is *about* your call:
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
from chain_receipt import build_prompt_commitment, verify_receipt_content
|
|
72
|
+
|
|
73
|
+
ok = verify_receipt_content(
|
|
74
|
+
envelope["receipt"],
|
|
75
|
+
salts, # from ai_receipt, returned once at call time
|
|
76
|
+
prompt_body=build_prompt_commitment(
|
|
77
|
+
messages=[{"role": "user", "content": "Say the word receipt."}]
|
|
78
|
+
),
|
|
79
|
+
response_json=resp, # the full provider response object
|
|
80
|
+
)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## Streaming
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
events = client.chat_completions(
|
|
87
|
+
model="google/gemini-3.5-flash",
|
|
88
|
+
messages=[{"role": "user", "content": "Count to three."}],
|
|
89
|
+
max_tokens=30,
|
|
90
|
+
stream=True,
|
|
91
|
+
)
|
|
92
|
+
for event in events:
|
|
93
|
+
if event.get("object") == "ai_receipt":
|
|
94
|
+
print("receipt:", event["ai_receipt"]["receipt_id"])
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## Bring your own provider key
|
|
98
|
+
|
|
99
|
+
Pass it per call (never stored by the SDK) or save it on the portal
|
|
100
|
+
Keys page and omit it:
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
resp = client.chat_completions(
|
|
104
|
+
model="anthropic/claude-haiku-4-5",
|
|
105
|
+
messages=[{"role": "user", "content": "Say the word receipt."}],
|
|
106
|
+
provider_key="sk-ant-...", # sent as X-Provider-Key
|
|
107
|
+
)
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## What is verified, exactly
|
|
111
|
+
|
|
112
|
+
`verify_receipt` checks, each reported separately:
|
|
113
|
+
|
|
114
|
+
- **hash** — `receipt_hash` recomputes from the receipt object
|
|
115
|
+
(SHA-256 over RFC 8785 canonical JSON).
|
|
116
|
+
- **signature** — Ed25519 verifies over the 32 raw hash bytes,
|
|
117
|
+
against the published public key for `signature.key_id`.
|
|
118
|
+
- **merkle** — when the envelope carries an anchor proof, the leaf +
|
|
119
|
+
proof recompute to the batch root (otherwise `None`).
|
|
120
|
+
|
|
121
|
+
`valid` is true when every check that could run passed. A genuine
|
|
122
|
+
receipt is valid before its batch confirms on Bitcoin — anchor
|
|
123
|
+
status is reported separately in the envelope.
|
|
124
|
+
|
|
125
|
+
## Golden vectors
|
|
126
|
+
|
|
127
|
+
The primitives in this SDK (JCS, Ed25519, SHA-256, Merkle root) pass
|
|
128
|
+
the same golden vectors as `@chain-receipt/core`, the verifier, and
|
|
129
|
+
the JS SDK: `packages/core/test-vectors/golden.json` (JCS from RFC
|
|
130
|
+
8785 §3.2.3, Ed25519 from RFC 8032 test 1, SHA-256 from FIPS 180-4).
|
|
131
|
+
Run them with `pytest` in `packages/sdk-py`.
|
|
132
|
+
|
|
133
|
+
## Links
|
|
134
|
+
|
|
135
|
+
- Site: https://chainreceipt.link
|
|
136
|
+
- Docs: https://chainreceipt.link/docs
|
|
137
|
+
- Verify a receipt in the browser: https://chainreceipt.link/verify
|
|
138
|
+
- Published signing keys: https://chainreceipt.link/.well-known/receipt-keys.json
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "chain-receipt"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Chain Receipt — verified AI output receipts. Client SDK for the OpenAI-compatible proxy and the offline receipt verifier."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "Cinian Studios Inc." },
|
|
14
|
+
]
|
|
15
|
+
keywords = ["ai", "receipts", "verification", "ed25519", "openai", "chain-receipt"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Development Status :: 3 - Alpha",
|
|
18
|
+
"Intended Audience :: Developers",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3.11",
|
|
21
|
+
"Programming Language :: Python :: 3.12",
|
|
22
|
+
"Programming Language :: Python :: 3.13",
|
|
23
|
+
"Topic :: Scientific/Engineering :: Information Analysis",
|
|
24
|
+
"Topic :: Security :: Cryptography",
|
|
25
|
+
"Typing :: Typed",
|
|
26
|
+
]
|
|
27
|
+
dependencies = [
|
|
28
|
+
"cryptography>=42",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[project.urls]
|
|
32
|
+
Homepage = "https://chainreceipt.link"
|
|
33
|
+
Repository = "https://github.com/CinianStudios/chain-receipt"
|
|
34
|
+
Documentation = "https://chainreceipt.link/docs"
|
|
35
|
+
"Issue Tracker" = "https://github.com/CinianStudios/chain-receipt/issues"
|
|
36
|
+
|
|
37
|
+
[project.optional-dependencies]
|
|
38
|
+
dev = [
|
|
39
|
+
"pytest>=8",
|
|
40
|
+
"build>=1",
|
|
41
|
+
"twine>=5",
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
[tool.setuptools.packages.find]
|
|
45
|
+
where = ["src"]
|
|
46
|
+
|
|
47
|
+
[tool.pytest.ini_options]
|
|
48
|
+
testpaths = ["tests"]
|
|
@@ -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")
|