aetherproof 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,95 @@
1
+ """AetherProof — cryptographic AI execution audit.
2
+
3
+ Generates 128-byte Ed25519-signed receipts that satisfy EU AI Act §13(3)(c)
4
+ technical documentation requirements for automated decision-making systems.
5
+
6
+ Quick start::
7
+
8
+ import aetherproof
9
+
10
+ # One-liner: generate a receipt for any binary
11
+ receipt = aetherproof.generate(open("model.onnx", "rb").read())
12
+ print(receipt.verify()) # True
13
+ receipt.save("run.receipt")
14
+
15
+ # Context manager: wrap a full inference session
16
+ with aetherproof.Session(pid=1) as s:
17
+ output = my_model.predict(data)
18
+ s.record_output(output_bytes)
19
+ receipt = s.seal(model_path="model.onnx")
20
+
21
+ # Decorator: auto-generate receipt on every call
22
+ @aetherproof.audit(model_path="model.onnx")
23
+ def run_inference(data):
24
+ return model.predict(data)
25
+
26
+ Wire format (128 bytes) is identical to the AetherOS kernel — receipts generated
27
+ here can be verified by `aetherproof verify` CLI and the kernel's QEMU verifier.
28
+ """
29
+
30
+ from ._receipt import (
31
+ Receipt,
32
+ generate,
33
+ verify_bytes,
34
+ tamper_probe,
35
+ fnv1a,
36
+ RECEIPT_SIZE,
37
+ RECEIPT_MAGIC,
38
+ RECEIPT_VERSION,
39
+ )
40
+ from ._keys import (
41
+ SigningKey,
42
+ VerifyingKey,
43
+ dev_signing_key,
44
+ dev_verifying_key,
45
+ DEV_SIGNING_SEED,
46
+ )
47
+ from ._session import Session, audit
48
+ from ._watermark import embed, extract, has_watermark, verify_embedded, strip
49
+ from ._api import (
50
+ for_api_call,
51
+ for_anthropic,
52
+ for_openai,
53
+ for_gemini,
54
+ for_local_model,
55
+ for_rag_pipeline,
56
+ for_embedding,
57
+ for_image_gen,
58
+ StreamRecorder,
59
+ )
60
+ from ._integrations import (
61
+ TracedResponse,
62
+ ollama,
63
+ ollama_chat,
64
+ openai,
65
+ anthropic,
66
+ )
67
+
68
+ __version__ = "0.2.0"
69
+ __all__ = [
70
+ "Receipt",
71
+ "generate",
72
+ "verify_bytes",
73
+ "tamper_probe",
74
+ "fnv1a",
75
+ "SigningKey",
76
+ "VerifyingKey",
77
+ "dev_signing_key",
78
+ "dev_verifying_key",
79
+ "DEV_SIGNING_SEED",
80
+ "Session",
81
+ "audit",
82
+ "embed",
83
+ "extract",
84
+ "has_watermark",
85
+ "verify_embedded",
86
+ "strip",
87
+ "RECEIPT_SIZE",
88
+ "RECEIPT_MAGIC",
89
+ "RECEIPT_VERSION",
90
+ "TracedResponse",
91
+ "ollama",
92
+ "ollama_chat",
93
+ "openai",
94
+ "anthropic",
95
+ ]
aetherproof/_api.py ADDED
@@ -0,0 +1,353 @@
1
+ """AetherProof API wrappers — generate receipts for any AI deployment type.
2
+
3
+ Fixes Tiger #1: the original generate() required a model binary file.
4
+ Most AI in production runs via API (Claude, GPT-4, Gemini, Llama, etc.)
5
+ where no binary is available. These wrappers create receipts for all cases.
6
+
7
+ Receipt field mapping for API calls:
8
+ binary_hash = FNV-1a of "provider/model_id" (identifies what model ran)
9
+ memory_hash = FNV-1a of response bytes (what the model produced)
10
+ syscall_count = number of API calls in this session
11
+ binary_len = len(request_bytes) (input size)
12
+ pid = user-supplied run/session ID
13
+
14
+ All wrappers produce a 128-byte receipt that is:
15
+ - Verifiable offline with the CLI
16
+ - Embeddable in output text via aetherproof.embed()
17
+ - Cross-language compatible with the Rust library
18
+ """
19
+ from __future__ import annotations
20
+ import json
21
+ import os
22
+ from typing import Optional, Union
23
+ from ._receipt import Receipt, generate, fnv1a
24
+ from ._keys import SigningKey
25
+
26
+
27
+ # ── Generic API call receipt ──────────────────────────────────────────────────
28
+
29
+ def for_api_call(
30
+ provider: str,
31
+ model_id: str,
32
+ request: Union[str, bytes, dict],
33
+ response: Union[str, bytes, dict],
34
+ *,
35
+ pid: int = 1,
36
+ call_count: int = 1,
37
+ signing_key: Optional[SigningKey] = None,
38
+ ) -> Receipt:
39
+ """Generate a receipt for any API-based AI inference call.
40
+
41
+ Works with any provider: Anthropic, OpenAI, Google, Cohere, Mistral, etc.
42
+
43
+ Args:
44
+ provider: Provider name, e.g. "anthropic", "openai", "google"
45
+ model_id: Model identifier, e.g. "claude-3-opus-20240229"
46
+ request: The request (str, bytes, or dict serialised to JSON)
47
+ response: The response (str, bytes, or dict serialised to JSON)
48
+ pid: Session/run ID (use a UUID or sequential counter)
49
+ call_count: Number of API calls in this session
50
+ signing_key: Ed25519 signing key (uses DEV key if None)
51
+
52
+ Returns:
53
+ Signed Receipt — verify with aetherproof verify <file> or receipt.verify()
54
+
55
+ Example::
56
+
57
+ client = anthropic.Anthropic()
58
+ message = client.messages.create(model="claude-3-opus-20240229", ...)
59
+ receipt = aetherproof.for_api_call(
60
+ "anthropic", "claude-3-opus-20240229",
61
+ request={"messages": [...]},
62
+ response=message.content[0].text,
63
+ )
64
+ receipt.save("call.receipt")
65
+ """
66
+ model_key = f"{provider.lower()}/{model_id}".encode()
67
+ request_b = _to_bytes(request)
68
+ response_b = _to_bytes(response)
69
+
70
+ return generate(
71
+ binary = model_key, # binary_hash = FNV-1a of "provider/model"
72
+ pid = pid,
73
+ memory_hash = fnv1a(response_b), # what the model produced
74
+ syscall_count = call_count,
75
+ signing_key = signing_key,
76
+ )
77
+
78
+
79
+ # ── Provider-specific helpers ─────────────────────────────────────────────────
80
+
81
+ def for_anthropic(
82
+ messages_or_prompt: Union[str, list, dict],
83
+ response_text: str,
84
+ *,
85
+ model: str = "claude-3-opus-20240229",
86
+ pid: int = 1,
87
+ call_count: int = 1,
88
+ signing_key: Optional[SigningKey] = None,
89
+ ) -> Receipt:
90
+ """Receipt for a Claude / Anthropic Messages API call.
91
+
92
+ Example::
93
+
94
+ import anthropic, aetherproof
95
+
96
+ client = anthropic.Anthropic()
97
+ message = client.messages.create(
98
+ model = "claude-3-opus-20240229",
99
+ max_tokens = 1024,
100
+ messages = [{"role": "user", "content": "Explain GDPR Article 13"}],
101
+ )
102
+ receipt = aetherproof.for_anthropic(
103
+ messages_or_prompt = [{"role": "user", "content": "Explain GDPR Article 13"}],
104
+ response_text = message.content[0].text,
105
+ model = "claude-3-opus-20240229",
106
+ )
107
+ receipt.save("claude_call.receipt")
108
+ print(receipt.verify()) # True
109
+ """
110
+ return for_api_call(
111
+ "anthropic", model,
112
+ request = messages_or_prompt,
113
+ response = response_text,
114
+ pid = pid,
115
+ call_count = call_count,
116
+ signing_key = signing_key,
117
+ )
118
+
119
+
120
+ def for_openai(
121
+ messages: Union[list, str],
122
+ response_text: str,
123
+ *,
124
+ model: str = "gpt-4o",
125
+ pid: int = 1,
126
+ call_count: int = 1,
127
+ signing_key: Optional[SigningKey] = None,
128
+ ) -> Receipt:
129
+ """Receipt for an OpenAI ChatCompletion API call.
130
+
131
+ Example::
132
+
133
+ from openai import OpenAI
134
+ import aetherproof
135
+
136
+ client = OpenAI()
137
+ result = client.chat.completions.create(
138
+ model = "gpt-4o",
139
+ messages = [{"role": "user", "content": "Summarise this contract."}],
140
+ )
141
+ receipt = aetherproof.for_openai(
142
+ messages = [{"role": "user", "content": "Summarise this contract."}],
143
+ response_text = result.choices[0].message.content,
144
+ model = "gpt-4o",
145
+ )
146
+ """
147
+ return for_api_call(
148
+ "openai", model,
149
+ request = messages,
150
+ response = response_text,
151
+ pid = pid,
152
+ call_count = call_count,
153
+ signing_key = signing_key,
154
+ )
155
+
156
+
157
+ def for_gemini(
158
+ prompt: Union[str, list],
159
+ response_text: str,
160
+ *,
161
+ model: str = "gemini-1.5-pro",
162
+ pid: int = 1,
163
+ call_count: int = 1,
164
+ signing_key: Optional[SigningKey] = None,
165
+ ) -> Receipt:
166
+ """Receipt for a Google Gemini API call."""
167
+ return for_api_call(
168
+ "google", model,
169
+ request = prompt,
170
+ response = response_text,
171
+ pid = pid,
172
+ call_count = call_count,
173
+ signing_key = signing_key,
174
+ )
175
+
176
+
177
+ def for_local_model(
178
+ model_path_or_name: str,
179
+ input_text: Union[str, bytes],
180
+ output_text: Union[str, bytes],
181
+ *,
182
+ pid: int = 1,
183
+ call_count: int = 1,
184
+ signing_key: Optional[SigningKey] = None,
185
+ ) -> Receipt:
186
+ """Receipt for local model inference: HuggingFace, llama.cpp, Ollama, etc.
187
+
188
+ Example::
189
+
190
+ from transformers import pipeline
191
+ import aetherproof
192
+
193
+ pipe = pipeline("text-generation", model="mistralai/Mistral-7B-v0.1")
194
+ result = pipe("Write a GDPR compliance summary")
195
+ receipt = aetherproof.for_local_model(
196
+ "mistralai/Mistral-7B-v0.1",
197
+ input_text = "Write a GDPR compliance summary",
198
+ output_text = result[0]["generated_text"],
199
+ )
200
+ """
201
+ model_key = f"local/{model_path_or_name}".encode()
202
+ input_b = _to_bytes(input_text)
203
+ output_b = _to_bytes(output_text)
204
+
205
+ return generate(
206
+ binary = model_key,
207
+ pid = pid,
208
+ memory_hash = fnv1a(output_b),
209
+ syscall_count = call_count,
210
+ signing_key = signing_key,
211
+ )
212
+
213
+
214
+ def for_rag_pipeline(
215
+ query: Union[str, bytes],
216
+ retrieved_docs: list,
217
+ final_answer: Union[str, bytes],
218
+ *,
219
+ model_id: str,
220
+ pid: int = 1,
221
+ signing_key: Optional[SigningKey] = None,
222
+ ) -> Receipt:
223
+ """Receipt for a RAG pipeline (LangChain, LlamaIndex, etc.).
224
+
225
+ The receipt covers the full pipeline: query + retrieved context + final answer.
226
+ binary_hash = FNV-1a of (query + all retrieved doc hashes combined)
227
+ memory_hash = FNV-1a of final_answer
228
+
229
+ Example::
230
+
231
+ answer = rag_chain.invoke({"query": "What is the EU AI Act?"})
232
+ receipt = aetherproof.for_rag_pipeline(
233
+ query = "What is the EU AI Act?",
234
+ retrieved_docs = docs, # list of strings or Document objects
235
+ final_answer = answer,
236
+ model_id = "gpt-4o",
237
+ )
238
+ """
239
+ query_b = _to_bytes(query)
240
+ docs_b = b"".join(_to_bytes(d) for d in retrieved_docs)
241
+ pipeline_b = f"rag/{model_id}".encode() + query_b + docs_b
242
+ answer_b = _to_bytes(final_answer)
243
+
244
+ return generate(
245
+ binary = pipeline_b,
246
+ pid = pid,
247
+ memory_hash = fnv1a(answer_b),
248
+ syscall_count = len(retrieved_docs), # number of docs retrieved
249
+ signing_key = signing_key,
250
+ )
251
+
252
+
253
+ def for_embedding(
254
+ model_id: str,
255
+ input_text: Union[str, bytes],
256
+ embedding: Union[list, bytes],
257
+ *,
258
+ pid: int = 1,
259
+ signing_key: Optional[SigningKey] = None,
260
+ ) -> Receipt:
261
+ """Receipt for an embedding API call (OpenAI, Cohere, etc.)."""
262
+ model_key = f"embedding/{model_id}".encode()
263
+ input_b = _to_bytes(input_text)
264
+ embedding_b = _to_bytes(embedding)
265
+
266
+ return generate(
267
+ binary = model_key,
268
+ pid = pid,
269
+ memory_hash = fnv1a(input_b),
270
+ syscall_count = 1,
271
+ signing_key = signing_key,
272
+ )
273
+
274
+
275
+ def for_image_gen(
276
+ model_id: str,
277
+ prompt: Union[str, bytes],
278
+ image_bytes: bytes,
279
+ *,
280
+ pid: int = 1,
281
+ signing_key: Optional[SigningKey] = None,
282
+ ) -> Receipt:
283
+ """Receipt for image generation (DALL-E, Stable Diffusion, Midjourney, etc.)."""
284
+ model_key = f"image/{model_id}".encode()
285
+ return generate(
286
+ binary = model_key,
287
+ pid = pid,
288
+ memory_hash = fnv1a(image_bytes),
289
+ syscall_count = 1,
290
+ signing_key = signing_key,
291
+ )
292
+
293
+
294
+ # ── Streaming helper ──────────────────────────────────────────────────────────
295
+
296
+ class StreamRecorder:
297
+ """Collect streamed response chunks and generate a receipt at the end.
298
+
299
+ Works with Anthropic streaming, OpenAI streaming, and any
300
+ chunk-based streaming API.
301
+
302
+ Example::
303
+
304
+ recorder = aetherproof.StreamRecorder("anthropic", "claude-3-opus-20240229")
305
+
306
+ with client.messages.stream(...) as stream:
307
+ for text_chunk in stream.text_stream:
308
+ recorder.add_chunk(text_chunk)
309
+ print(text_chunk, end="", flush=True)
310
+
311
+ receipt = recorder.seal(pid=1)
312
+ receipt.save("stream.receipt")
313
+ """
314
+
315
+ def __init__(
316
+ self,
317
+ provider: str,
318
+ model_id: str,
319
+ signing_key: Optional[SigningKey] = None,
320
+ ) -> None:
321
+ self._model_key = f"{provider.lower()}/{model_id}".encode()
322
+ self._sk = signing_key
323
+ self._chunks: list[bytes] = []
324
+ self._call_count = 0
325
+
326
+ def add_chunk(self, chunk: Union[str, bytes]) -> None:
327
+ self._chunks.append(_to_bytes(chunk))
328
+ self._call_count += 1
329
+
330
+ def full_response(self) -> bytes:
331
+ return b"".join(self._chunks)
332
+
333
+ def seal(self, pid: int = 1) -> Receipt:
334
+ full = self.full_response()
335
+ return generate(
336
+ binary = self._model_key,
337
+ pid = pid,
338
+ memory_hash = fnv1a(full),
339
+ syscall_count = self._call_count,
340
+ signing_key = self._sk,
341
+ )
342
+
343
+
344
+ # ── Internal ──────────────────────────────────────────────────────────────────
345
+
346
+ def _to_bytes(v: Union[str, bytes, dict, list]) -> bytes:
347
+ if isinstance(v, bytes):
348
+ return v
349
+ if isinstance(v, str):
350
+ return v.encode("utf-8")
351
+ if isinstance(v, (dict, list)):
352
+ return json.dumps(v, sort_keys=True, ensure_ascii=False).encode("utf-8")
353
+ return str(v).encode("utf-8")
@@ -0,0 +1,217 @@
1
+ """AetherProof drop-in integrations — one line to a verified receipt.
2
+
3
+ The wrappers in `_api` produce a receipt from a response you already have.
4
+ These wrappers go one step further: they *make the model call for you* and
5
+ hand back the response together with a signed, tamper-evident receipt — so a
6
+ new user gets their first receipt in under ten minutes.
7
+
8
+ Quick start (local model, zero extra dependencies — uses Ollama's HTTP API)::
9
+
10
+ import aetherproof
11
+
12
+ r = aetherproof.ollama("llama3", "Explain quantum tunneling in one line")
13
+ print(r.text) # the model's answer
14
+ print(r.verify()) # True — the call is cryptographically receipted
15
+ r.save("call.receipt") # 128 bytes, verifiable offline by anyone
16
+
17
+ Cloud providers (use the official client if installed)::
18
+
19
+ r = aetherproof.openai("gpt-4o", "Summarise this contract.")
20
+ r = aetherproof.anthropic("claude-3-opus-20240229", "Explain GDPR Article 13")
21
+
22
+ Every `TracedResponse` carries a real `Receipt`: verify it offline, embed it
23
+ invisibly in the output text (`aetherproof.embed`), or check it with the Rust
24
+ CLI / the AetherOS kernel — same 128-byte wire format.
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import json
29
+ import os
30
+ import urllib.request
31
+ import urllib.error
32
+ from dataclasses import dataclass
33
+ from typing import Optional, Union, List, Dict, Any
34
+
35
+ from ._receipt import Receipt
36
+ from ._keys import SigningKey
37
+ from ._api import for_api_call
38
+
39
+
40
+ # ── Result object ──────────────────────────────────────────────────────────────
41
+
42
+ @dataclass
43
+ class TracedResponse:
44
+ """A model response paired with its AetherProof receipt.
45
+
46
+ Behaves like the text in most contexts (``str(r)`` / ``f"{r}"``), while
47
+ exposing the receipt for verification, saving, or embedding.
48
+ """
49
+ text: str
50
+ receipt: Receipt
51
+ model: str
52
+ raw: Optional[Dict[str, Any]] = None
53
+
54
+ def verify(self) -> bool:
55
+ """True iff the receipt's Ed25519 signature is valid."""
56
+ return self.receipt.verify()
57
+
58
+ def save(self, path: str) -> None:
59
+ """Write the 128-byte receipt to ``path`` (verifiable offline)."""
60
+ self.receipt.save(path)
61
+
62
+ def signed_text(self) -> str:
63
+ """Return the response with the receipt embedded invisibly (PUA watermark)."""
64
+ from ._watermark import embed
65
+ return embed(self.text, self.receipt.to_bytes())
66
+
67
+ def __str__(self) -> str:
68
+ return self.text
69
+
70
+
71
+ # ── Local models via Ollama (stdlib only — no extra pip install) ────────────────
72
+
73
+ OLLAMA_HOST = os.environ.get("OLLAMA_HOST", "http://localhost:11434")
74
+
75
+
76
+ def _http_post_json(url: str, payload: dict, timeout: int = 300) -> dict:
77
+ data = json.dumps(payload).encode("utf-8")
78
+ req = urllib.request.Request(
79
+ url, data=data, headers={"Content-Type": "application/json"}, method="POST"
80
+ )
81
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
82
+ return json.loads(resp.read().decode("utf-8"))
83
+
84
+
85
+ def ollama(
86
+ model: str,
87
+ prompt: str,
88
+ *,
89
+ host: Optional[str] = None,
90
+ pid: int = 1,
91
+ signing_key: Optional[SigningKey] = None,
92
+ timeout: int = 300,
93
+ **options: Any,
94
+ ) -> TracedResponse:
95
+ """Call a local Ollama model and return its answer + a signed receipt.
96
+
97
+ No extra dependency — talks to Ollama's HTTP API (default
98
+ ``http://localhost:11434``; override with ``host=`` or ``$OLLAMA_HOST``).
99
+
100
+ Example::
101
+
102
+ import aetherproof
103
+ r = aetherproof.ollama("llama3", "Explain quantum tunneling")
104
+ print(r.text, r.verify())
105
+
106
+ Any extra keyword args (``temperature=``, ``num_ctx=`` …) are forwarded to
107
+ Ollama as model options.
108
+ """
109
+ base = (host or OLLAMA_HOST).rstrip("/")
110
+ payload: Dict[str, Any] = {"model": model, "prompt": prompt, "stream": False}
111
+ if options:
112
+ payload["options"] = options
113
+ try:
114
+ body = _http_post_json(f"{base}/api/generate", payload, timeout=timeout)
115
+ except urllib.error.URLError as e: # pragma: no cover - network/env dependent
116
+ raise RuntimeError(
117
+ f"Could not reach Ollama at {base}. Is it running? "
118
+ f"Install from https://ollama.com and `ollama pull {model}`. ({e})"
119
+ ) from e
120
+
121
+ text = body.get("response", "")
122
+ receipt = for_api_call(
123
+ "ollama", model, request=prompt, response=text,
124
+ pid=pid, signing_key=signing_key,
125
+ )
126
+ return TracedResponse(text=text, receipt=receipt, model=model, raw=body)
127
+
128
+
129
+ def ollama_chat(
130
+ model: str,
131
+ messages: List[Dict[str, str]],
132
+ *,
133
+ host: Optional[str] = None,
134
+ pid: int = 1,
135
+ signing_key: Optional[SigningKey] = None,
136
+ timeout: int = 300,
137
+ **options: Any,
138
+ ) -> TracedResponse:
139
+ """Multi-turn chat variant of :func:`ollama` (uses ``/api/chat``)."""
140
+ base = (host or OLLAMA_HOST).rstrip("/")
141
+ payload: Dict[str, Any] = {"model": model, "messages": messages, "stream": False}
142
+ if options:
143
+ payload["options"] = options
144
+ body = _http_post_json(f"{base}/api/chat", payload, timeout=timeout)
145
+ text = (body.get("message") or {}).get("content", "")
146
+ receipt = for_api_call(
147
+ "ollama", model, request=messages, response=text,
148
+ pid=pid, signing_key=signing_key,
149
+ )
150
+ return TracedResponse(text=text, receipt=receipt, model=model, raw=body)
151
+
152
+
153
+ # ── Cloud providers (use the official client if installed) ──────────────────────
154
+
155
+ def openai(
156
+ model: str,
157
+ prompt_or_messages: Union[str, List[Dict[str, str]]],
158
+ *,
159
+ client: Any = None,
160
+ pid: int = 1,
161
+ signing_key: Optional[SigningKey] = None,
162
+ **kwargs: Any,
163
+ ) -> TracedResponse:
164
+ """Call OpenAI Chat Completions and receipt the result.
165
+
166
+ Requires ``pip install openai`` and ``OPENAI_API_KEY``. Pass ``client=`` to
167
+ reuse an existing ``OpenAI()`` instance.
168
+ """
169
+ if client is None:
170
+ from openai import OpenAI # optional dependency
171
+ client = OpenAI()
172
+ messages = (
173
+ [{"role": "user", "content": prompt_or_messages}]
174
+ if isinstance(prompt_or_messages, str) else prompt_or_messages
175
+ )
176
+ result = client.chat.completions.create(model=model, messages=messages, **kwargs)
177
+ text = result.choices[0].message.content or ""
178
+ receipt = for_api_call(
179
+ "openai", model, request=messages, response=text,
180
+ pid=pid, signing_key=signing_key,
181
+ )
182
+ return TracedResponse(text=text, receipt=receipt, model=model)
183
+
184
+
185
+ def anthropic(
186
+ model: str,
187
+ prompt_or_messages: Union[str, List[Dict[str, str]]],
188
+ *,
189
+ client: Any = None,
190
+ max_tokens: int = 1024,
191
+ pid: int = 1,
192
+ signing_key: Optional[SigningKey] = None,
193
+ **kwargs: Any,
194
+ ) -> TracedResponse:
195
+ """Call the Anthropic Messages API and receipt the result.
196
+
197
+ Requires ``pip install anthropic`` and ``ANTHROPIC_API_KEY``. Pass
198
+ ``client=`` to reuse an existing ``Anthropic()`` instance.
199
+ """
200
+ if client is None:
201
+ import anthropic as _anthropic_sdk # optional dependency
202
+ client = _anthropic_sdk.Anthropic()
203
+ messages = (
204
+ [{"role": "user", "content": prompt_or_messages}]
205
+ if isinstance(prompt_or_messages, str) else prompt_or_messages
206
+ )
207
+ msg = client.messages.create(
208
+ model=model, max_tokens=max_tokens, messages=messages, **kwargs
209
+ )
210
+ text = "".join(
211
+ block.text for block in msg.content if getattr(block, "type", None) == "text"
212
+ )
213
+ receipt = for_api_call(
214
+ "anthropic", model, request=messages, response=text,
215
+ pid=pid, signing_key=signing_key,
216
+ )
217
+ return TracedResponse(text=text, receipt=receipt, model=model)
aetherproof/_keys.py ADDED
@@ -0,0 +1,89 @@
1
+ """Key management for AetherProof."""
2
+ from __future__ import annotations
3
+ import os
4
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import (
5
+ Ed25519PrivateKey, Ed25519PublicKey,
6
+ )
7
+ from cryptography.hazmat.primitives.serialization import (
8
+ Encoding, PublicFormat, PrivateFormat, NoEncryption,
9
+ )
10
+
11
+ # Matches AetherOS kernel DEV_SIGNING_SEED — receipts generated here
12
+ # are verifiable by the Rust CLI and by the kernel itself.
13
+ DEV_SIGNING_SEED: bytes = bytes([
14
+ 0x4a, 0xe3, 0x81, 0xb9, 0x2f, 0x6c, 0x05, 0xd8,
15
+ 0x17, 0xa4, 0x9e, 0x63, 0x2b, 0x78, 0xf1, 0x5c,
16
+ 0x9d, 0x02, 0xe7, 0x48, 0xbc, 0x6a, 0x31, 0x94,
17
+ 0x5f, 0xc8, 0x7e, 0xab, 0x03, 0xd5, 0x6f, 0x22,
18
+ ])
19
+
20
+
21
+ class SigningKey:
22
+ """Ed25519 signing key wrapper."""
23
+
24
+ def __init__(self, private_key: Ed25519PrivateKey) -> None:
25
+ self._key = private_key
26
+
27
+ @classmethod
28
+ def from_seed(cls, seed: bytes) -> "SigningKey":
29
+ if len(seed) != 32:
30
+ raise ValueError(f"seed must be 32 bytes, got {len(seed)}")
31
+ return cls(Ed25519PrivateKey.from_private_bytes(seed))
32
+
33
+ @classmethod
34
+ def generate(cls) -> "SigningKey":
35
+ """Generate a new random signing key."""
36
+ return cls.from_seed(os.urandom(32))
37
+
38
+ def sign(self, message: bytes) -> bytes:
39
+ """Sign message; returns 64-byte Ed25519 signature."""
40
+ return self._key.sign(message)
41
+
42
+ def verifying_key(self) -> "VerifyingKey":
43
+ return VerifyingKey(self._key.public_key())
44
+
45
+ def seed_bytes(self) -> bytes:
46
+ return self._key.private_bytes(Encoding.Raw, PrivateFormat.Raw, NoEncryption())
47
+
48
+
49
+ class VerifyingKey:
50
+ """Ed25519 verifying (public) key wrapper."""
51
+
52
+ def __init__(self, public_key: Ed25519PublicKey) -> None:
53
+ self._key = public_key
54
+
55
+ @classmethod
56
+ def from_bytes(cls, data: bytes) -> "VerifyingKey":
57
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
58
+ from cryptography.hazmat.primitives.serialization import load_der_public_key
59
+ # raw 32-byte public key
60
+ if len(data) != 32:
61
+ raise ValueError(f"public key must be 32 bytes, got {len(data)}")
62
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
63
+ from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
64
+ # Reconstruct from raw bytes via a temporary private key isn't possible,
65
+ # so we use the cryptography utility for raw Ed25519 public keys.
66
+ pub = Ed25519PublicKey.from_public_bytes(data)
67
+ return cls(pub)
68
+
69
+ def verify(self, signature: bytes, message: bytes) -> bool:
70
+ """Returns True if signature is valid for message, False otherwise."""
71
+ from cryptography.exceptions import InvalidSignature
72
+ try:
73
+ self._key.verify(signature, message)
74
+ return True
75
+ except InvalidSignature:
76
+ return False
77
+
78
+ def public_bytes(self) -> bytes:
79
+ return self._key.public_bytes(Encoding.Raw, PublicFormat.Raw)
80
+
81
+
82
+ def dev_signing_key() -> SigningKey:
83
+ """Return the dev signing key (matches AetherOS kernel DEV_SIGNING_SEED)."""
84
+ return SigningKey.from_seed(DEV_SIGNING_SEED)
85
+
86
+
87
+ def dev_verifying_key() -> VerifyingKey:
88
+ """Return the dev verifying key."""
89
+ return dev_signing_key().verifying_key()
@@ -0,0 +1,206 @@
1
+ """AetherProof receipt serialisation, generation, and verification."""
2
+ from __future__ import annotations
3
+ import os
4
+ import struct
5
+ import time
6
+ from dataclasses import dataclass, field
7
+ from typing import Optional
8
+ from ._keys import SigningKey, VerifyingKey, dev_signing_key, dev_verifying_key
9
+
10
+ RECEIPT_MAGIC = b"AETHPRF1"
11
+ RECEIPT_VERSION = 1
12
+ RECEIPT_SIZE = 128
13
+
14
+ # Struct layout for bytes[0..64] (little-endian):
15
+ # 8s magic
16
+ # B version
17
+ # 3x padding
18
+ # I pid
19
+ # Q binary_hash
20
+ # Q memory_hash
21
+ # I syscall_count
22
+ # I entropy_seed
23
+ # Q timestamp_ns
24
+ # Q binary_len
25
+ # 8x reserved
26
+ _HEADER_FMT = "<8sBxxxIQQIIQQ8x"
27
+ _HEADER_SIZE = struct.calcsize(_HEADER_FMT) # must == 64
28
+ assert _HEADER_SIZE == 64, f"header size {_HEADER_SIZE} != 64"
29
+
30
+
31
+ def fnv1a(data: bytes) -> int:
32
+ """FNV-1a 64-bit — identical to Rust and kernel implementations."""
33
+ h = 0xcbf2_9ce4_8422_2325
34
+ for b in data:
35
+ h ^= b
36
+ h = (h * 0x0000_0100_0000_01b3) & 0xFFFF_FFFF_FFFF_FFFF
37
+ return h
38
+
39
+
40
+ @dataclass
41
+ class Receipt:
42
+ pid: int
43
+ binary_hash: int
44
+ memory_hash: int
45
+ syscall_count: int
46
+ entropy_seed: int
47
+ timestamp_ns: int
48
+ binary_len: int
49
+ sig: bytes = field(default_factory=lambda: bytes(64))
50
+
51
+ def to_bytes(self) -> bytes:
52
+ header = struct.pack(
53
+ _HEADER_FMT,
54
+ RECEIPT_MAGIC, RECEIPT_VERSION,
55
+ self.pid, self.binary_hash, self.memory_hash,
56
+ self.syscall_count, self.entropy_seed,
57
+ self.timestamp_ns, self.binary_len,
58
+ )
59
+ assert len(header) == 64
60
+ return header + self.sig
61
+
62
+ @classmethod
63
+ def from_bytes(cls, data: bytes) -> Optional["Receipt"]:
64
+ if len(data) != RECEIPT_SIZE:
65
+ return None
66
+ if data[0:8] != RECEIPT_MAGIC:
67
+ return None
68
+ if data[8] != RECEIPT_VERSION:
69
+ return None
70
+ fields = struct.unpack(_HEADER_FMT, data[:64])
71
+ # fields: magic, version, pid, binary_hash, memory_hash,
72
+ # syscall_count, entropy_seed, timestamp_ns, binary_len
73
+ return cls(
74
+ pid = fields[2],
75
+ binary_hash = fields[3],
76
+ memory_hash = fields[4],
77
+ syscall_count = fields[5],
78
+ entropy_seed = fields[6],
79
+ timestamp_ns = fields[7],
80
+ binary_len = fields[8],
81
+ sig = data[64:128],
82
+ )
83
+
84
+ def verify(self, vk: Optional[VerifyingKey] = None) -> bool:
85
+ """Verify the Ed25519 signature. Uses dev key if vk is None."""
86
+ if vk is None:
87
+ vk = dev_verifying_key()
88
+ raw = self.to_bytes()
89
+ if len(raw) != RECEIPT_SIZE:
90
+ return False
91
+ return vk.verify(raw[64:128], raw[0:64])
92
+
93
+ def save(self, path: str) -> None:
94
+ with open(path, "wb") as f:
95
+ f.write(self.to_bytes())
96
+
97
+ @classmethod
98
+ def load(cls, path: str) -> "Receipt":
99
+ with open(path, "rb") as f:
100
+ data = f.read()
101
+ r = cls.from_bytes(data)
102
+ if r is None:
103
+ raise ValueError(f"invalid AetherProof receipt: {path}")
104
+ return r
105
+
106
+ def __repr__(self) -> str:
107
+ valid = self.verify()
108
+ return (
109
+ f"Receipt(pid={self.pid}, "
110
+ f"binary_hash=0x{self.binary_hash:016X}, "
111
+ f"memory_hash=0x{self.memory_hash:016X}, "
112
+ f"syscall_count={self.syscall_count}, "
113
+ f"binary_len={self.binary_len}, "
114
+ f"valid={valid})"
115
+ )
116
+
117
+ def pretty(self) -> str:
118
+ valid = self.verify()
119
+ sig_preview = self.sig[:8].hex()
120
+ status = "✓ VALID — EU AI Act §13(3)(c)" if valid else "✗ INVALID"
121
+ return (
122
+ f"AetherProof Receipt\n"
123
+ f" pid : {self.pid}\n"
124
+ f" binary_hash : 0x{self.binary_hash:016X}\n"
125
+ f" memory_hash : 0x{self.memory_hash:016X}\n"
126
+ f" syscall_count : {self.syscall_count}\n"
127
+ f" entropy_seed : 0x{self.entropy_seed:08X}\n"
128
+ f" timestamp_ns : {self.timestamp_ns}\n"
129
+ f" binary_len : {self.binary_len}\n"
130
+ f" sig[0..8] : {sig_preview}...\n"
131
+ f" status : {'VALID -- EU AI Act s13(3)(c)' if valid else 'INVALID'}"
132
+ )
133
+
134
+
135
+ def verify_bytes(data: bytes, vk: Optional[VerifyingKey] = None) -> bool:
136
+ """Verify raw 128-byte receipt data directly — no round-trip through fields.
137
+
138
+ This is the canonical verification function. It covers every bit in
139
+ bytes[0..64] including padding and reserved bytes, matching the Rust CLI
140
+ behaviour. Use this when verifying a receipt file from disk.
141
+ """
142
+ if vk is None:
143
+ vk = dev_verifying_key()
144
+ if len(data) != RECEIPT_SIZE:
145
+ return False
146
+ if data[:8] != RECEIPT_MAGIC:
147
+ return False
148
+ if data[8] != RECEIPT_VERSION:
149
+ return False
150
+ return vk.verify(data[64:128], data[0:64])
151
+
152
+
153
+ def generate(
154
+ binary: bytes,
155
+ *,
156
+ pid: int = 1,
157
+ memory_hash: int = 0,
158
+ syscall_count: int = 0,
159
+ signing_key: Optional[SigningKey] = None,
160
+ ) -> Receipt:
161
+ """Generate and sign a receipt for one AI model run.
162
+
163
+ Args:
164
+ binary: Model bytes (ONNX, PT, weights, or any binary).
165
+ pid: Process/run ID.
166
+ memory_hash: Hash of model outputs (use fnv1a(output_bytes) or 0).
167
+ syscall_count: Number of inference calls or operations.
168
+ signing_key: Ed25519 signing key. Uses DEV key if None.
169
+
170
+ Returns:
171
+ Signed Receipt ready to verify and save.
172
+ """
173
+ if signing_key is None:
174
+ signing_key = dev_signing_key()
175
+
176
+ entropy = int.from_bytes(os.urandom(4), "little")
177
+ ts = time.time_ns()
178
+
179
+ r = Receipt(
180
+ pid = pid,
181
+ binary_hash = fnv1a(binary),
182
+ memory_hash = memory_hash,
183
+ syscall_count = syscall_count,
184
+ entropy_seed = entropy,
185
+ timestamp_ns = ts,
186
+ binary_len = len(binary),
187
+ sig = bytes(64),
188
+ )
189
+ # Sign the first 64 bytes (sig field is zero during signing).
190
+ message = r.to_bytes()[:64]
191
+ r.sig = signing_key.sign(message)
192
+ return r
193
+
194
+
195
+ def tamper_probe(receipt_bytes: bytes, vk: Optional[VerifyingKey] = None) -> bool:
196
+ """Flip one byte in binary_hash field → must be INVALID; original → VALID.
197
+
198
+ Uses verify_bytes() for raw-byte fidelity — no round-trip through fields.
199
+ """
200
+ if vk is None:
201
+ vk = dev_verifying_key()
202
+ if len(receipt_bytes) != RECEIPT_SIZE:
203
+ return False
204
+ tampered = bytearray(receipt_bytes)
205
+ tampered[20] ^= 0xFF # inside binary_hash field
206
+ return (not verify_bytes(bytes(tampered), vk)) and verify_bytes(receipt_bytes, vk)
@@ -0,0 +1,133 @@
1
+ """Session context manager and @audit decorator for automatic receipt generation."""
2
+ from __future__ import annotations
3
+ import functools
4
+ import os
5
+ import time
6
+ from typing import Optional, Callable, Any
7
+ from ._receipt import Receipt, generate, fnv1a
8
+ from ._keys import SigningKey, dev_signing_key
9
+
10
+
11
+ class Session:
12
+ """Context manager that wraps an AI model run and seals it with a receipt.
13
+
14
+ Usage::
15
+
16
+ with aetherproof.Session(pid=1) as s:
17
+ output = model.predict(input_data)
18
+ s.record_output(output_bytes)
19
+
20
+ receipt = s.seal(model_bytes=open("model.onnx", "rb").read())
21
+ receipt.save("run.receipt")
22
+ print(receipt.verify()) # True
23
+ """
24
+
25
+ def __init__(
26
+ self,
27
+ pid: int = 1,
28
+ signing_key: Optional[SigningKey] = None,
29
+ ) -> None:
30
+ self.pid = pid
31
+ self._sk = signing_key or dev_signing_key()
32
+ self._call_count = 0
33
+ self._output_hash = 0
34
+ self._start_ns = 0
35
+ self._receipt: Optional[Receipt] = None
36
+
37
+ def __enter__(self) -> "Session":
38
+ self._start_ns = time.time_ns()
39
+ self._call_count = 0
40
+ self._output_hash = 0
41
+ return self
42
+
43
+ def __exit__(self, *_: Any) -> None:
44
+ pass
45
+
46
+ def record_call(self) -> None:
47
+ """Increment the inference call counter."""
48
+ self._call_count += 1
49
+
50
+ def record_output(self, output: bytes) -> None:
51
+ """XOR-accumulate FNV-1a of output into memory_hash."""
52
+ self._output_hash ^= fnv1a(output)
53
+ self._call_count += 1
54
+
55
+ def seal(
56
+ self,
57
+ model_bytes: Optional[bytes] = None,
58
+ model_path: Optional[str] = None,
59
+ memory_hash: Optional[int] = None,
60
+ syscall_count: Optional[int] = None,
61
+ ) -> Receipt:
62
+ """Generate a signed receipt for this session.
63
+
64
+ Provide either model_bytes or model_path (not both).
65
+ """
66
+ if model_bytes is None and model_path is None:
67
+ raise ValueError("provide model_bytes or model_path")
68
+ if model_bytes is None:
69
+ with open(model_path, "rb") as f:
70
+ model_bytes = f.read()
71
+
72
+ self._receipt = generate(
73
+ binary = model_bytes,
74
+ pid = self.pid,
75
+ memory_hash = memory_hash if memory_hash is not None else self._output_hash,
76
+ syscall_count = syscall_count if syscall_count is not None else self._call_count,
77
+ signing_key = self._sk,
78
+ )
79
+ return self._receipt
80
+
81
+ @property
82
+ def receipt(self) -> Optional[Receipt]:
83
+ return self._receipt
84
+
85
+
86
+ def audit(
87
+ model_path: Optional[str] = None,
88
+ model_bytes: Optional[bytes] = None,
89
+ pid: int = 1,
90
+ signing_key: Optional[SigningKey] = None,
91
+ save_to: Optional[str] = None,
92
+ ) -> Callable:
93
+ """Decorator: wraps a function, generates a receipt after each call.
94
+
95
+ Usage::
96
+
97
+ @aetherproof.audit(model_path="model.onnx", save_to="receipts/{call}.receipt")
98
+ def run_inference(data):
99
+ return model.predict(data)
100
+
101
+ result = run_inference(my_data)
102
+ # receipt saved to receipts/0.receipt
103
+ """
104
+ _call_counter = [0]
105
+
106
+ def decorator(fn: Callable) -> Callable:
107
+ @functools.wraps(fn)
108
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
109
+ with Session(pid=pid, signing_key=signing_key) as s:
110
+ result = fn(*args, **kwargs)
111
+ # Record output if it's bytes
112
+ if isinstance(result, (bytes, bytearray)):
113
+ s.record_output(bytes(result))
114
+ else:
115
+ s.record_call()
116
+
117
+ receipt = s.seal(
118
+ model_bytes = model_bytes,
119
+ model_path = model_path,
120
+ )
121
+
122
+ if save_to is not None:
123
+ path = save_to.format(call=_call_counter[0])
124
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
125
+ receipt.save(path)
126
+ _call_counter[0] += 1
127
+ wrapper.last_receipt = receipt # type: ignore[attr-defined]
128
+ return result
129
+
130
+ wrapper.last_receipt = None # type: ignore[attr-defined]
131
+ return wrapper
132
+
133
+ return decorator
@@ -0,0 +1,149 @@
1
+ """AetherProof UVSW -- Unicode Private Use Area watermarking.
2
+
3
+ Encodes a 128-byte receipt invisibly into any Unicode string using BMP
4
+ Private Use Area codepoints (U+E000 to U+E0FF). The text remains visually
5
+ identical in all standard renderers. The receipt survives copy-paste,
6
+ JSON serialisation, and HTTP transfer.
7
+
8
+ Use cases
9
+ ---------
10
+ - AI-generated documents carry their own audit receipt invisibly
11
+ - Legal/medical AI outputs self-prove what model generated them
12
+ - The proof travels WITH the content, not on a separate server
13
+
14
+ Wire encoding (128 invisible chars between two BMP PUA markers)
15
+ -------------------------------
16
+ U+F800 start marker (BMP PUA, invisible)
17
+ U+E000 + byte one char per receipt byte, 128 chars total
18
+ U+F801 end marker (BMP PUA, invisible)
19
+
20
+ Optional visible badge:
21
+ U+27EC (open) and U+27ED (close) -- shows humans that a receipt is present
22
+
23
+ All PUA codepoints are NFC/NFD/NFKC stable -- Unicode normalisation
24
+ does not alter them, so the watermark survives normalisation passes.
25
+ """
26
+ from __future__ import annotations
27
+ from typing import Optional
28
+ from ._receipt import verify_bytes, RECEIPT_SIZE
29
+ from ._keys import VerifyingKey
30
+
31
+ # ---- codepoint constants (explicit chr() -- no invisible char literals in source) ----
32
+
33
+ _PUA_DATA_BASE = 0xE000 # U+E000: encodes byte 0x00
34
+ _PUA_DATA_END = 0xE0FF # U+E0FF: encodes byte 0xFF (256 values exactly)
35
+ _MARK_START = chr(0xF800) # BMP PUA marker: start of watermark
36
+ _MARK_END = chr(0xF801) # BMP PUA marker: end of watermark
37
+ _INVIS_SEP = chr(0x2063) # U+2063 INVISIBLE SEPARATOR (spacing hint before badge)
38
+ _BADGE_OPEN = chr(0x27EC) # U+27EC visible open bracket for badge
39
+ _BADGE_CLOSE = chr(0x27ED) # U+27ED visible close bracket for badge
40
+
41
+
42
+ # ---- public API ---------------------------------------------------------------
43
+
44
+ def embed(
45
+ text: str,
46
+ receipt_bytes: bytes,
47
+ *,
48
+ badge: bool = True,
49
+ ) -> str:
50
+ """Embed a 128-byte receipt into any Unicode text invisibly.
51
+
52
+ The text is visually unchanged (except for optional visible badge).
53
+ Works with any script: Latin, Arabic, Chinese, Devanagari, Emoji, RTL, etc.
54
+
55
+ Args:
56
+ text: Any Unicode string.
57
+ receipt_bytes: Exactly 128 bytes (from ``Receipt.to_bytes()``).
58
+ badge: If True (default), append visible bracket markers so
59
+ readers know a receipt is present.
60
+ If False, the watermark is completely invisible.
61
+
62
+ Returns:
63
+ Watermarked string. Visually: ``text`` + optional ``[invisible data]``.
64
+
65
+ Example::
66
+
67
+ r = aetherproof.generate(open("model.onnx","rb").read())
68
+ output = "AI approved this loan application."
69
+ signed = aetherproof.embed(output, r.to_bytes())
70
+ # signed looks normal; receipt is inside
71
+ print(aetherproof.verify_embedded(signed)) # True
72
+ """
73
+ if len(receipt_bytes) != RECEIPT_SIZE:
74
+ raise ValueError(f"receipt_bytes must be {RECEIPT_SIZE} bytes, got {len(receipt_bytes)}")
75
+
76
+ data = "".join(chr(_PUA_DATA_BASE + b) for b in receipt_bytes)
77
+ watermark = _MARK_START + data + _MARK_END
78
+
79
+ if badge:
80
+ return text + _INVIS_SEP + _BADGE_OPEN + watermark + _BADGE_CLOSE
81
+ return text + watermark
82
+
83
+
84
+ def extract(watermarked: str) -> bytes:
85
+ """Extract the 128-byte receipt from a watermarked string.
86
+
87
+ Raises:
88
+ ValueError: if no watermark found or length mismatch.
89
+ """
90
+ start = watermarked.find(_MARK_START)
91
+ if start == -1:
92
+ raise ValueError("no AetherProof watermark found (missing start marker)")
93
+ end = watermarked.find(_MARK_END, start + 1)
94
+ if end == -1:
95
+ raise ValueError("no AetherProof watermark found (missing end marker)")
96
+
97
+ result = []
98
+ for ch in watermarked[start + 1 : end]:
99
+ cp = ord(ch)
100
+ if _PUA_DATA_BASE <= cp <= _PUA_DATA_END:
101
+ result.append(cp - _PUA_DATA_BASE)
102
+
103
+ if len(result) != RECEIPT_SIZE:
104
+ raise ValueError(
105
+ f"watermark has {len(result)} data bytes, expected {RECEIPT_SIZE}"
106
+ )
107
+ return bytes(result)
108
+
109
+
110
+ def has_watermark(text: str) -> bool:
111
+ """Return True if text contains an AetherProof watermark."""
112
+ return _MARK_START in text and _MARK_END in text
113
+
114
+
115
+ def verify_embedded(watermarked: str, vk: Optional[VerifyingKey] = None) -> bool:
116
+ """Extract and cryptographically verify the receipt embedded in text.
117
+
118
+ Returns False (never raises) if no watermark, wrong length, or bad sig.
119
+ """
120
+ try:
121
+ raw = extract(watermarked)
122
+ except ValueError:
123
+ return False
124
+ return verify_bytes(raw, vk)
125
+
126
+
127
+ def strip(watermarked: str) -> str:
128
+ """Remove all AetherProof watermark characters, returning clean visible text."""
129
+ skip = {
130
+ ord(_MARK_START),
131
+ ord(_MARK_END),
132
+ ord(_INVIS_SEP),
133
+ ord(_BADGE_OPEN),
134
+ ord(_BADGE_CLOSE),
135
+ }
136
+ result = []
137
+ for ch in watermarked:
138
+ cp = ord(ch)
139
+ if cp in skip:
140
+ continue
141
+ if _PUA_DATA_BASE <= cp <= _PUA_DATA_END:
142
+ continue
143
+ result.append(ch)
144
+ return "".join(result)
145
+
146
+
147
+ def visible_only(text: str) -> str:
148
+ """Alias for strip() -- more readable in UI code."""
149
+ return strip(text)
@@ -0,0 +1,88 @@
1
+ Metadata-Version: 2.4
2
+ Name: aetherproof
3
+ Version: 0.2.0
4
+ Summary: Cryptographic, tamper-evident execution receipts for any AI model
5
+ Author: Pulkit
6
+ License: AGPL-3.0-or-later
7
+ Project-URL: Homepage, https://github.com/pulkit6732/aetherproof
8
+ Project-URL: Repository, https://github.com/pulkit6732/aetherproof
9
+ Project-URL: Issues, https://github.com/pulkit6732/aetherproof/issues
10
+ Keywords: ai,audit,receipt,ed25519,tamper-evident,compliance,eu-ai-act,llm,ollama
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Security :: Cryptography
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Requires-Python: >=3.9
23
+ Description-Content-Type: text/markdown
24
+ Requires-Dist: cryptography>=41.0
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest>=7; extra == "dev"
27
+ Requires-Dist: pytest-benchmark; extra == "dev"
28
+ Provides-Extra: test
29
+ Requires-Dist: pytest>=7; extra == "test"
30
+
31
+ # AetherProof
32
+
33
+ **Cryptographic, tamper-evident execution receipts for any AI model.**
34
+
35
+ One call generates a 128-byte Ed25519-signed receipt that proves what model ran
36
+ and what it produced — verifiable offline by anyone, with no server and no account.
37
+ Works with Claude, GPT, Gemini, or a local model via Ollama.
38
+
39
+ ## Install
40
+
41
+ ```bash
42
+ pip install aetherproof
43
+ ```
44
+
45
+ ## Drop-in: one line to a verified receipt
46
+
47
+ Run a local model and get its answer **plus** a signed, tamper-evident receipt —
48
+ no extra dependencies, no server:
49
+
50
+ ```python
51
+ import aetherproof
52
+
53
+ r = aetherproof.ollama("llama3", "Explain quantum tunneling")
54
+ print(r.text) # the model's answer
55
+ print(r.verify()) # True — cryptographically receipted
56
+ r.save("call.receipt")
57
+ ```
58
+
59
+ Cloud providers work the same way (`pip install openai` / `anthropic`):
60
+
61
+ ```python
62
+ r = aetherproof.openai("gpt-4o", "Summarise this contract.")
63
+ r = aetherproof.anthropic("claude-3-opus-20240229", "Explain GDPR Article 13")
64
+ ```
65
+
66
+ Already have a response? Receipt it directly:
67
+
68
+ ```python
69
+ receipt = aetherproof.for_anthropic(prompt, response_text, model="claude-3-opus-20240229")
70
+ print(receipt.verify()) # True
71
+ receipt.save("run.receipt")
72
+ ```
73
+
74
+ ## What a receipt proves
75
+
76
+ - **What ran** — a hash identifying the model.
77
+ - **What it produced** — a hash of the output; any change is detectable.
78
+ - **Tamper-evidence** — flip a single byte and verification fails.
79
+ - **Offline-verifiable** — anyone can check it with the public key; no server.
80
+ - **Portable** — the same 128-byte wire format verifies in Python, the Rust CLI,
81
+ and the AetherOS kernel.
82
+
83
+ The receipt can also ride **invisibly inside the model's own output text**
84
+ (`aetherproof.embed`), so the proof travels with the content.
85
+
86
+ ## License
87
+
88
+ AGPL-3.0-or-later. See [LICENSE](https://github.com/pulkit6732/aetherproof/blob/main/LICENSE).
@@ -0,0 +1,11 @@
1
+ aetherproof/__init__.py,sha256=kCy4uqIAVdFCfqdeLdLjVUdR_zYI0UgX8hm4QYJDGBA,2180
2
+ aetherproof/_api.py,sha256=Sfo2DfVMXZ4X9OPOwM7dfFZ9wwevHKxyfdVhZeCUukA,12047
3
+ aetherproof/_integrations.py,sha256=ccgm9qCkZqlmZKgbc7Smwva-ihEX6jwN1mwPaJ7bT30,8061
4
+ aetherproof/_keys.py,sha256=egDX7nA6Zz4s3eewkJ-xAoNu_E1Pi3ApuqWk60Shezw,3312
5
+ aetherproof/_receipt.py,sha256=-wH0lTez4pESrwnQkDghV0w_akAnu87r0pWCdc4F7xY,6773
6
+ aetherproof/_session.py,sha256=Y9qpWsIQDIVvBBeCMWK2O4M8fF5v3RNGX0RXgzHWW50,4301
7
+ aetherproof/_watermark.py,sha256=PPiwW6oIN1kR6Hyy0mJojdhVwaGr0ApM7V6xtsr5S1Y,5274
8
+ aetherproof-0.2.0.dist-info/METADATA,sha256=XeztXbSxOg7whgM_AK-ju6for0BGCYlhACuSjx0Q1sY,3263
9
+ aetherproof-0.2.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
10
+ aetherproof-0.2.0.dist-info/top_level.txt,sha256=fJ8E4WCtrHEixmgIvUH6mXNg3fCZuRaHF9yzJDHZeLU,12
11
+ aetherproof-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ aetherproof