receipt-gate 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.
- receipt_gate/__init__.py +59 -0
- receipt_gate/adapters.py +213 -0
- receipt_gate/capability.py +125 -0
- receipt_gate/ledger.py +97 -0
- receipt_gate/mcp_server.py +848 -0
- receipt_gate/promise.py +92 -0
- receipt_gate/settler.py +137 -0
- receipt_gate/speech_gate.py +143 -0
- receipt_gate-0.2.0.dist-info/METADATA +244 -0
- receipt_gate-0.2.0.dist-info/RECORD +14 -0
- receipt_gate-0.2.0.dist-info/WHEEL +5 -0
- receipt_gate-0.2.0.dist-info/entry_points.txt +2 -0
- receipt_gate-0.2.0.dist-info/licenses/LICENSE +21 -0
- receipt_gate-0.2.0.dist-info/top_level.txt +1 -0
receipt_gate/__init__.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""receipt-gate — an agent cannot log "done" without an independent receipt.
|
|
2
|
+
|
|
3
|
+
Five parts:
|
|
4
|
+
Ledger append-only records with a hash chain
|
|
5
|
+
CapabilityProxy capabilities that belong to a promise, one call at a time
|
|
6
|
+
adapters readers of reality that are not the holder's report
|
|
7
|
+
Settler promise beside observation: settlement or remainder
|
|
8
|
+
SpeechGate holds "done" and unrelated new work while a debt is open
|
|
9
|
+
|
|
10
|
+
And one way in from outside:
|
|
11
|
+
Server an MCP server over stdio, where the tool surface is the
|
|
12
|
+
construction rather than a way around it
|
|
13
|
+
|
|
14
|
+
The gate is on the sentence, not on the action.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from .ledger import Ledger, canon, digest
|
|
18
|
+
from .promise import (
|
|
19
|
+
CANCELLED_BY_OWNER,
|
|
20
|
+
CLAIM_DONE,
|
|
21
|
+
FULFILLED,
|
|
22
|
+
HANDED_OVER,
|
|
23
|
+
IMPOSSIBLE_IN_SCOPE,
|
|
24
|
+
OPEN,
|
|
25
|
+
OPEN_UNRELATED_PROMISE,
|
|
26
|
+
SILENT_HANDOFF,
|
|
27
|
+
TERMINAL,
|
|
28
|
+
InadmissiblePromise,
|
|
29
|
+
Observation,
|
|
30
|
+
Promise,
|
|
31
|
+
Remainder,
|
|
32
|
+
)
|
|
33
|
+
from .capability import CapabilityProxy, Grant, Refused
|
|
34
|
+
from .adapters import (
|
|
35
|
+
CommandAdapter,
|
|
36
|
+
ManifestAdapter,
|
|
37
|
+
OwnerAcceptanceAdapter,
|
|
38
|
+
sha256_file,
|
|
39
|
+
)
|
|
40
|
+
from .settler import Settlement, Settler
|
|
41
|
+
from .speech_gate import Held, SpeechGate
|
|
42
|
+
from .mcp_server import GateService, PathOutsideRoot, Server, tool_specs
|
|
43
|
+
|
|
44
|
+
__version__ = "0.2.0"
|
|
45
|
+
__spec_version__ = "0.1"
|
|
46
|
+
|
|
47
|
+
__all__ = [
|
|
48
|
+
"Ledger", "canon", "digest",
|
|
49
|
+
"Promise", "Observation", "Remainder", "InadmissiblePromise",
|
|
50
|
+
"OPEN", "FULFILLED", "CANCELLED_BY_OWNER", "IMPOSSIBLE_IN_SCOPE",
|
|
51
|
+
"HANDED_OVER", "TERMINAL",
|
|
52
|
+
"CLAIM_DONE", "OPEN_UNRELATED_PROMISE", "SILENT_HANDOFF",
|
|
53
|
+
"CapabilityProxy", "Grant", "Refused",
|
|
54
|
+
"ManifestAdapter", "CommandAdapter", "OwnerAcceptanceAdapter", "sha256_file",
|
|
55
|
+
"Settler", "Settlement",
|
|
56
|
+
"SpeechGate", "Held",
|
|
57
|
+
"Server", "GateService", "PathOutsideRoot", "tool_specs",
|
|
58
|
+
"__version__", "__spec_version__",
|
|
59
|
+
]
|
receipt_gate/adapters.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""Receipt adapters.
|
|
2
|
+
|
|
3
|
+
An adapter knows where a promised state can appear. It does not know what
|
|
4
|
+
the holder thinks it should be. It reads reality again, from a source that
|
|
5
|
+
is not the holder's own report.
|
|
6
|
+
|
|
7
|
+
One receipt attests only what its own source can observe. A successful
|
|
8
|
+
exit code does not establish human acceptance; a human saying "fine" does
|
|
9
|
+
not establish that protected files are unchanged. Composite promises split.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import hashlib
|
|
15
|
+
import json
|
|
16
|
+
import subprocess
|
|
17
|
+
import time
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any, Dict, Iterable, List, Optional, Sequence
|
|
20
|
+
|
|
21
|
+
from .promise import Observation
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def sha256_file(path: str | Path, chunk: int = 1 << 16) -> str:
|
|
25
|
+
h = hashlib.sha256()
|
|
26
|
+
with Path(path).open("rb") as fh:
|
|
27
|
+
while True:
|
|
28
|
+
block = fh.read(chunk)
|
|
29
|
+
if not block:
|
|
30
|
+
break
|
|
31
|
+
h.update(block)
|
|
32
|
+
return h.hexdigest()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _evidence(payload: Any) -> str:
|
|
36
|
+
text = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
|
|
37
|
+
return hashlib.sha256(text.encode("utf-8")).hexdigest()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class ManifestAdapter:
|
|
41
|
+
"""Reads a manifest, then re-reads every source it names.
|
|
42
|
+
|
|
43
|
+
Checks three things independently: the manifest parses and has the
|
|
44
|
+
expected entries; every size and digest matches a fresh read; and the
|
|
45
|
+
protected sources are byte-identical to the state recorded before the
|
|
46
|
+
ride.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
name = "manifest+sha256"
|
|
50
|
+
|
|
51
|
+
def __init__(self, manifest_path: str | Path, sources: Sequence[str | Path],
|
|
52
|
+
before: Optional[Dict[str, str]] = None) -> None:
|
|
53
|
+
self.manifest_path = Path(manifest_path)
|
|
54
|
+
self.sources = [Path(p) for p in sources]
|
|
55
|
+
self.before = dict(before or {})
|
|
56
|
+
|
|
57
|
+
def snapshot(self) -> Dict[str, str]:
|
|
58
|
+
"""Digests of the sources as they are now. Taken before the ride."""
|
|
59
|
+
return {str(p): sha256_file(p) for p in self.sources}
|
|
60
|
+
|
|
61
|
+
def observe(self) -> Observation:
|
|
62
|
+
at = time.time()
|
|
63
|
+
|
|
64
|
+
if not self.manifest_path.exists():
|
|
65
|
+
return Observation(
|
|
66
|
+
source=self.name, observed_at=at,
|
|
67
|
+
observed_state={"manifest": "absent"}, matches=False,
|
|
68
|
+
note=f"{self.manifest_path} does not exist",
|
|
69
|
+
)
|
|
70
|
+
try:
|
|
71
|
+
manifest = json.loads(self.manifest_path.read_text(encoding="utf-8"))
|
|
72
|
+
except json.JSONDecodeError as exc:
|
|
73
|
+
return Observation(
|
|
74
|
+
source=self.name, observed_at=at,
|
|
75
|
+
observed_state={"manifest": "unparsable"}, matches=False,
|
|
76
|
+
note=f"invalid JSON: {exc}",
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
entries = manifest.get("entries")
|
|
80
|
+
if not isinstance(entries, list):
|
|
81
|
+
return Observation(
|
|
82
|
+
source=self.name, observed_at=at,
|
|
83
|
+
observed_state={"manifest": "no entries list"}, matches=False,
|
|
84
|
+
note="schema: entries must be a list",
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
by_path = {e.get("path"): e for e in entries if isinstance(e, dict)}
|
|
88
|
+
problems: List[str] = []
|
|
89
|
+
|
|
90
|
+
if len(by_path) != len(self.sources):
|
|
91
|
+
problems.append(
|
|
92
|
+
f"expected {len(self.sources)} unique entries, found {len(by_path)}"
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
sources_unchanged = True
|
|
96
|
+
for src in self.sources:
|
|
97
|
+
key = str(src)
|
|
98
|
+
fresh = sha256_file(src) if src.exists() else None
|
|
99
|
+
if fresh is None:
|
|
100
|
+
problems.append(f"source missing: {key}")
|
|
101
|
+
sources_unchanged = False
|
|
102
|
+
continue
|
|
103
|
+
if key in self.before and self.before[key] != fresh:
|
|
104
|
+
problems.append(f"protected source changed: {key}")
|
|
105
|
+
sources_unchanged = False
|
|
106
|
+
entry = by_path.get(key)
|
|
107
|
+
if entry is None:
|
|
108
|
+
problems.append(f"not in manifest: {key}")
|
|
109
|
+
continue
|
|
110
|
+
if entry.get("sha256") != fresh:
|
|
111
|
+
problems.append(f"digest mismatch: {key}")
|
|
112
|
+
size = src.stat().st_size
|
|
113
|
+
if entry.get("size") != size:
|
|
114
|
+
problems.append(f"size mismatch: {key}")
|
|
115
|
+
|
|
116
|
+
state = {
|
|
117
|
+
"valid": not problems,
|
|
118
|
+
"entries": len(by_path),
|
|
119
|
+
"sources_unchanged": sources_unchanged,
|
|
120
|
+
"problems": problems,
|
|
121
|
+
}
|
|
122
|
+
return Observation(
|
|
123
|
+
source=self.name, observed_at=at, observed_state=state,
|
|
124
|
+
matches=not problems, evidence_sha256=_evidence(state),
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class CommandAdapter:
|
|
129
|
+
"""Runs a command in a clean working directory and reads its result.
|
|
130
|
+
|
|
131
|
+
Attests the exit code and, when asked, that an expected string appears
|
|
132
|
+
in the output. It attests nothing about anyone's acceptance.
|
|
133
|
+
"""
|
|
134
|
+
|
|
135
|
+
name = "command+exit_code"
|
|
136
|
+
|
|
137
|
+
def __init__(self, argv: Sequence[str], cwd: Optional[str | Path] = None,
|
|
138
|
+
expect_exit: int = 0, expect_in_output: Optional[str] = None,
|
|
139
|
+
timeout: float = 60.0) -> None:
|
|
140
|
+
self.argv = list(argv)
|
|
141
|
+
self.cwd = str(cwd) if cwd else None
|
|
142
|
+
self.expect_exit = expect_exit
|
|
143
|
+
self.expect_in_output = expect_in_output
|
|
144
|
+
self.timeout = timeout
|
|
145
|
+
|
|
146
|
+
def observe(self) -> Observation:
|
|
147
|
+
at = time.time()
|
|
148
|
+
try:
|
|
149
|
+
done = subprocess.run(
|
|
150
|
+
self.argv, cwd=self.cwd, capture_output=True, text=True,
|
|
151
|
+
timeout=self.timeout, check=False,
|
|
152
|
+
)
|
|
153
|
+
except (OSError, subprocess.TimeoutExpired) as exc:
|
|
154
|
+
state = {"ran": False, "error": str(exc)}
|
|
155
|
+
return Observation(self.name, at, state, False, _evidence(state))
|
|
156
|
+
|
|
157
|
+
output = (done.stdout or "") + (done.stderr or "")
|
|
158
|
+
ok = done.returncode == self.expect_exit
|
|
159
|
+
if ok and self.expect_in_output is not None:
|
|
160
|
+
ok = self.expect_in_output in output
|
|
161
|
+
state = {
|
|
162
|
+
"ran": True,
|
|
163
|
+
"exit_code": done.returncode,
|
|
164
|
+
"expected_exit": self.expect_exit,
|
|
165
|
+
"output_tail": output[-800:],
|
|
166
|
+
}
|
|
167
|
+
return Observation(self.name, at, state, ok, _evidence(state))
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
class OwnerAcceptanceAdapter:
|
|
171
|
+
"""Reads an acceptance the result owner wrote, naming a version digest.
|
|
172
|
+
|
|
173
|
+
Attests acceptance of one named version and nothing else.
|
|
174
|
+
"""
|
|
175
|
+
|
|
176
|
+
name = "owner_acceptance"
|
|
177
|
+
|
|
178
|
+
def __init__(self, record_path: str | Path, owner: str, version_sha256: str) -> None:
|
|
179
|
+
self.record_path = Path(record_path)
|
|
180
|
+
self.owner = owner
|
|
181
|
+
self.version_sha256 = version_sha256
|
|
182
|
+
|
|
183
|
+
def observe(self) -> Observation:
|
|
184
|
+
at = time.time()
|
|
185
|
+
if not self.record_path.exists():
|
|
186
|
+
state = {"accepted": False, "reason": "no acceptance record"}
|
|
187
|
+
return Observation(self.name, at, state, False, _evidence(state))
|
|
188
|
+
try:
|
|
189
|
+
record = json.loads(self.record_path.read_text(encoding="utf-8"))
|
|
190
|
+
except json.JSONDecodeError as exc:
|
|
191
|
+
state = {"accepted": False, "reason": f"invalid JSON: {exc}"}
|
|
192
|
+
return Observation(self.name, at, state, False, _evidence(state))
|
|
193
|
+
|
|
194
|
+
ok = (record.get("accepted_by") == self.owner
|
|
195
|
+
and record.get("version_sha256") == self.version_sha256)
|
|
196
|
+
state = {
|
|
197
|
+
"accepted": bool(ok),
|
|
198
|
+
"accepted_by": record.get("accepted_by"),
|
|
199
|
+
"version_sha256": record.get("version_sha256"),
|
|
200
|
+
"expected_version": self.version_sha256,
|
|
201
|
+
}
|
|
202
|
+
return Observation(self.name, at, state, ok, _evidence(state))
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
ADAPTERS: Dict[str, type] = {
|
|
206
|
+
ManifestAdapter.name: ManifestAdapter,
|
|
207
|
+
CommandAdapter.name: CommandAdapter,
|
|
208
|
+
OwnerAcceptanceAdapter.name: OwnerAcceptanceAdapter,
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def known(names: Iterable[str]) -> List[str]:
|
|
213
|
+
return [n for n in names if n in ADAPTERS]
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""The capability proxy.
|
|
2
|
+
|
|
3
|
+
It does not solve the task. It compares a requested action with the
|
|
4
|
+
promise and opens a capability for one call, or returns the exact
|
|
5
|
+
boundary that refused it.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import secrets
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import Any, Dict, Optional
|
|
13
|
+
|
|
14
|
+
from .ledger import Ledger
|
|
15
|
+
from .promise import Promise
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Refused(PermissionError):
|
|
19
|
+
"""Raised with the exact boundary that refused the action."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class Grant:
|
|
24
|
+
token: str
|
|
25
|
+
action: str
|
|
26
|
+
promise_id: str
|
|
27
|
+
spent: bool = False
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class CapabilityProxy:
|
|
31
|
+
"""Capabilities belong to the promise, not to the holder's role."""
|
|
32
|
+
|
|
33
|
+
def __init__(self, ledger: Ledger, promise: Promise) -> None:
|
|
34
|
+
self.ledger = ledger
|
|
35
|
+
self.promise = promise
|
|
36
|
+
self._grants: Dict[str, Grant] = {}
|
|
37
|
+
|
|
38
|
+
# ---- granting ------------------------------------------------------
|
|
39
|
+
|
|
40
|
+
def open(self, action: str, target: Optional[str] = None) -> Grant:
|
|
41
|
+
if action not in self.promise.authority:
|
|
42
|
+
reason = (
|
|
43
|
+
f"action {action!r} is outside this promise's authority "
|
|
44
|
+
f"{sorted(self.promise.authority)}"
|
|
45
|
+
)
|
|
46
|
+
self.ledger.append(
|
|
47
|
+
"capability_refused",
|
|
48
|
+
{"promise_id": self.promise.promise_id, "action": action,
|
|
49
|
+
"target": target, "boundary": reason},
|
|
50
|
+
)
|
|
51
|
+
raise Refused(reason)
|
|
52
|
+
|
|
53
|
+
if target is not None:
|
|
54
|
+
for rule in self.promise.damage_ceiling:
|
|
55
|
+
if _violates(rule, action, target):
|
|
56
|
+
reason = f"damage ceiling refuses it: {rule!r}"
|
|
57
|
+
self.ledger.append(
|
|
58
|
+
"capability_refused",
|
|
59
|
+
{"promise_id": self.promise.promise_id, "action": action,
|
|
60
|
+
"target": target, "boundary": reason},
|
|
61
|
+
)
|
|
62
|
+
raise Refused(reason)
|
|
63
|
+
|
|
64
|
+
grant = Grant(token=secrets.token_hex(8), action=action,
|
|
65
|
+
promise_id=self.promise.promise_id)
|
|
66
|
+
self._grants[grant.token] = grant
|
|
67
|
+
self.ledger.append(
|
|
68
|
+
"capability_opened",
|
|
69
|
+
{"promise_id": self.promise.promise_id, "action": action,
|
|
70
|
+
"target": target, "token": grant.token},
|
|
71
|
+
)
|
|
72
|
+
return grant
|
|
73
|
+
|
|
74
|
+
# ---- spending ------------------------------------------------------
|
|
75
|
+
|
|
76
|
+
def spend(self, grant: Grant, result: Any = None) -> None:
|
|
77
|
+
"""A capability is opened for one call. A second use is refused."""
|
|
78
|
+
held = self._grants.get(grant.token)
|
|
79
|
+
if held is None or held.spent:
|
|
80
|
+
reason = "capability already spent; open a new one"
|
|
81
|
+
self.ledger.append(
|
|
82
|
+
"capability_refused",
|
|
83
|
+
{"promise_id": self.promise.promise_id, "action": grant.action,
|
|
84
|
+
"boundary": reason},
|
|
85
|
+
)
|
|
86
|
+
raise Refused(reason)
|
|
87
|
+
held.spent = True
|
|
88
|
+
self.ledger.append(
|
|
89
|
+
"action_taken",
|
|
90
|
+
{"promise_id": self.promise.promise_id, "action": grant.action,
|
|
91
|
+
"token": grant.token, "result": _short(result)},
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
WRITING = ("write", "rename", "delete", "move", "truncate")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _violates(rule: str, action: str, target: str) -> bool:
|
|
99
|
+
"""Damage ceiling rules are written as `verb:glob`, e.g. `write:sources/*`.
|
|
100
|
+
|
|
101
|
+
An action is also `verb:what`, e.g. `write:manifest.json`, so the verb
|
|
102
|
+
is taken from its prefix. A rule verb of `*` or `any` covers every
|
|
103
|
+
writing verb; a rule with no verb at all does the same.
|
|
104
|
+
"""
|
|
105
|
+
from fnmatch import fnmatch
|
|
106
|
+
|
|
107
|
+
action_verb = action.split(":", 1)[0].strip()
|
|
108
|
+
|
|
109
|
+
if ":" in rule:
|
|
110
|
+
rule_verb, pattern = rule.split(":", 1)
|
|
111
|
+
rule_verb = rule_verb.strip()
|
|
112
|
+
verbs = set(WRITING) if rule_verb in ("*", "any") else {rule_verb}
|
|
113
|
+
else:
|
|
114
|
+
verbs, pattern = set(WRITING), rule
|
|
115
|
+
|
|
116
|
+
if action_verb not in verbs:
|
|
117
|
+
return False
|
|
118
|
+
|
|
119
|
+
pattern = pattern.strip()
|
|
120
|
+
return fnmatch(target, pattern) or fnmatch(target, f"*/{pattern}")
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _short(value: Any, limit: int = 240) -> Any:
|
|
124
|
+
text = repr(value)
|
|
125
|
+
return text if len(text) <= limit else text[:limit] + "…"
|
receipt_gate/ledger.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Append-only event ledger with a hash chain.
|
|
2
|
+
|
|
3
|
+
A record is never rewritten. Correcting an earlier record is a new record
|
|
4
|
+
that names what it supersedes and on what basis.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import json
|
|
11
|
+
import time
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any, Dict, Iterator, List, Optional, Tuple
|
|
14
|
+
|
|
15
|
+
GENESIS = "0" * 64
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def canon(obj: Any) -> str:
|
|
19
|
+
"""Canonical JSON: stable key order, no insignificant whitespace."""
|
|
20
|
+
return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def digest(prev_hash: str, body: Dict[str, Any]) -> str:
|
|
24
|
+
return hashlib.sha256((prev_hash + canon(body)).encode("utf-8")).hexdigest()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Ledger:
|
|
28
|
+
"""Events are added. Nothing already written is edited.
|
|
29
|
+
|
|
30
|
+
Each record carries the hash of the one before it, so a silent edit
|
|
31
|
+
anywhere in the file is detectable by verify().
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def __init__(self, path: str | Path, clock=time.time) -> None:
|
|
35
|
+
self.path = Path(path)
|
|
36
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
37
|
+
self.path.touch(exist_ok=True)
|
|
38
|
+
self._clock = clock
|
|
39
|
+
|
|
40
|
+
# ---- reading -------------------------------------------------------
|
|
41
|
+
|
|
42
|
+
def records(self) -> Iterator[Dict[str, Any]]:
|
|
43
|
+
with self.path.open("r", encoding="utf-8") as fh:
|
|
44
|
+
for line in fh:
|
|
45
|
+
line = line.strip()
|
|
46
|
+
if line:
|
|
47
|
+
yield json.loads(line)
|
|
48
|
+
|
|
49
|
+
def all(self) -> List[Dict[str, Any]]:
|
|
50
|
+
return list(self.records())
|
|
51
|
+
|
|
52
|
+
def head(self) -> Tuple[int, str]:
|
|
53
|
+
"""(sequence of last record, its hash). (0, GENESIS) when empty."""
|
|
54
|
+
seq, last = 0, GENESIS
|
|
55
|
+
for rec in self.records():
|
|
56
|
+
seq, last = rec["seq"], rec["hash"]
|
|
57
|
+
return seq, last
|
|
58
|
+
|
|
59
|
+
def find(self, kind: Optional[str] = None, **match: Any) -> List[Dict[str, Any]]:
|
|
60
|
+
out = []
|
|
61
|
+
for rec in self.records():
|
|
62
|
+
if kind is not None and rec["kind"] != kind:
|
|
63
|
+
continue
|
|
64
|
+
body = rec.get("body", {})
|
|
65
|
+
if all(body.get(k) == v for k, v in match.items()):
|
|
66
|
+
out.append(rec)
|
|
67
|
+
return out
|
|
68
|
+
|
|
69
|
+
# ---- writing -------------------------------------------------------
|
|
70
|
+
|
|
71
|
+
def append(self, kind: str, body: Dict[str, Any]) -> Dict[str, Any]:
|
|
72
|
+
seq, prev = self.head()
|
|
73
|
+
core = {"seq": seq + 1, "kind": kind, "at": self._clock(), "body": body}
|
|
74
|
+
rec = dict(core)
|
|
75
|
+
rec["prev"] = prev
|
|
76
|
+
rec["hash"] = digest(prev, core)
|
|
77
|
+
with self.path.open("a", encoding="utf-8") as fh:
|
|
78
|
+
fh.write(canon(rec) + "\n")
|
|
79
|
+
return rec
|
|
80
|
+
|
|
81
|
+
# ---- integrity -----------------------------------------------------
|
|
82
|
+
|
|
83
|
+
def verify(self) -> Tuple[bool, Optional[str]]:
|
|
84
|
+
"""(True, None) when the chain holds; (False, reason) at the first break."""
|
|
85
|
+
prev = GENESIS
|
|
86
|
+
expected_seq = 1
|
|
87
|
+
for rec in self.records():
|
|
88
|
+
if rec.get("seq") != expected_seq:
|
|
89
|
+
return False, f"sequence break at {rec.get('seq')!r}, expected {expected_seq}"
|
|
90
|
+
if rec.get("prev") != prev:
|
|
91
|
+
return False, f"broken link at seq {expected_seq}"
|
|
92
|
+
core = {k: rec[k] for k in ("seq", "kind", "at", "body")}
|
|
93
|
+
if rec.get("hash") != digest(prev, core):
|
|
94
|
+
return False, f"record edited at seq {expected_seq}"
|
|
95
|
+
prev = rec["hash"]
|
|
96
|
+
expected_seq += 1
|
|
97
|
+
return True, None
|