Audit, Detection, and Incident Response › Tamper-evident chaining
Language AI HandbookAll chapters A hash chain commits each record to the preceding digest. Verification can detect a payload edit or a missing interior record when the subsequent links remain in the supplied log. Use a protected checkpoint at the expected end to detect a shorter but internally consistent prefix.
Let an audit record have payload and hash . Hash the previous digest followed by the serialized payload bytes. This commits each record to the preceding one in the stored sequence.
where:
- is the serialized payload of record .
- is the stored digest of the preceding record, or at the start of the chain.
- is the digest stored for record .
- : a collision-resistant hash function (SHA-256 in practice)
- : byte concatenation
- is the fixed initial digest, called the genesis value. The independently saved checkpoint is a separate reference to a later digest.
The recursion makes each record depend on all records before it: changing any for propagates forward and changes every subsequent . Each stored record contains . Verification recomputes each from the stored and stored and checks it matches the stored , and separately checks that each record's stored equals the previous record's stored .
The two checks in verification address different failures. Recompute the digest from the stored payload and previous digest to check the record. Compare each stored previous digest with the preceding record’s digest to check the link. A missing interior record breaks a surviving neighbor’s link. If records are removed from the end, no later link remains to check. Compare the result with the checkpoint for the expected prefix or snapshot.
This chain has three properties that matter, and one limitation that matters more.
Ordering. Because record commits to , records form a strict sequence. You cannot insert a record between two existing ones without recomputing all subsequent hashes, which changes the final head hash.
Tamper evidence within the middle. Modifying the payload of record changes , which no longer matches the stored value. If the stored hash is updated alone, the next record still points to the old digest. So any edit to a middle record is locally detectable.
Save a checkpoint containing the log identity, record count, and head digest in an independently protected location. An exact snapshot can be checked against the checkpoint for the same position. A log that has grown since the checkpoint can verify its prefix up to that position, while later records remain outside that checkpoint.
For example, a checkpoint written at record 100 still verifies that prefix after the log reaches record 110. If the supplied snapshot ends at record 106, the checkpoint alone cannot establish that four later records are missing.
A hash chain proves only integrity relative to history: that the records shown are the records that were committed, in that order, up to the last pinned head. It does not prove the following:
- Truthfulness. The agent or its instrumentation can commit a false record faithfully. A record saying
decision: allowfor an action that was denied, or atool_callrecord with falsified arguments, hashes perfectly. - Completeness relative to reality. If a component never emits an event, the chain has no gap inside itself; it is silent about what it never saw. Omission of an entire class of events (say, a tool that bypasses the instrumentation wrapper) leaves a perfectly valid chain that simply does not mention those actions. Completeness must be argued at the instrumentation level and tested by probing, not proven by the chain.
- Correctness of the clock. Timestamps are attacker-influenced if the clock is. Ordering is cryptographically enforced; wall-clock times are only as trustworthy as the time source.
- Whether the emitter reported an operation accurately. An independent append-only sink can protect stored records. Corroborate the record with separately collected observations from the relevant tool or gateway, because hashing the emitter’s version preserves its contents.
Chaining raises the cost of silent tampering. It does not raise the cost of lying.
A cryptographically consistent log can contain false reports or omit an operation. Keep independent permissions on the log sink and compare key records with observations from the tools or gateway. Use collection and source-clock information to distinguish an ordering guarantee from a timing estimate.
Worked example: chaining and verifying a small trail
Let us make this concrete. We build an in-process chain over a handful of invented events, verify a clean chain, then show precisely which record detects a single-field edit and what the head hash reveals about truncation.
PythonIn [3]Expand
import hashlib
import json
def h(prev_hex: str, payload: dict) -> str:
# Canonical serialization is essential: dict ordering must not affect the hash.
body = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode(
"utf-8"
)
return hashlib.sha256(bytes.fromhex(prev_hex) + body).hexdigest()
GENESIS = hashlib.sha256(b"handbook-audit-genesis").hexdigest()
def build_chain(events):
chain, prev = [], GENESIS
for ev in events:
prev_hash, rec_hash = prev, h(prev, ev)
chain.append(
{"payload": ev, "prev_hash": prev_hash, "record_hash": rec_hash}
)
prev = rec_hash
return chain
def verify_chain(chain, pinned_head=None):
prev = GENESIS
for i, rec in enumerate(chain):
if rec["prev_hash"] != prev:
return False, f"link broken before record {i}"
if h(rec["prev_hash"], rec["payload"]) != rec["record_hash"]:
return False, f"payload altered at record {i}"
prev = rec["record_hash"]
if pinned_head is not None and prev != pinned_head:
return False, "head does not match pinned head (truncation/rewrite)"
return True, "ok"The canonical serialization step inside h is worth a note. The payload is a dictionary, and dictionaries in Python preserve insertion order, so two payloads with the same key-value pairs but different insertion orders would serialize to different byte strings and hash differently. Canonical serialization (sorted keys, compact separators, UTF-8 encoding) removes this source of spurious divergence, so the same logical payload always produces the same hash regardless of how the dictionary was constructed. Without canonical serialization, the chain would be fragile against harmless refactoring and would produce false tamper alarms, which would train responders to ignore the alarm. Canonical serialization is the audit-system equivalent of pinning a dependency version: it makes the hash a function of the content, not of incidental construction details.
We now create four invented events. The labels and IDs are deliberately generic and inert.
The events below are committed in order: a retrieval, then a model_completion, then a tool_call, then a policy_decision. Each carries a decision label and type-specific fields. build_chain serializes each payload canonically (sorted keys, compact separators), prepends the previous hash, and hashes the concatenation, producing the triples described above.
PythonIn [4]Expand
events = [
{
"trace_id": "t-001",
"action_type": "retrieval",
"decision": "allow",
"doc_ids": ["d-77"],
},
{
"trace_id": "t-001",
"action_type": "model_completion",
"decision": "allow",
"model": "demo-1",
},
{
"trace_id": "t-001",
"action_type": "tool_call",
"decision": "allow",
"tool": "mock_transfer",
},
{
"trace_id": "t-001",
"action_type": "policy_decision",
"decision": "escalate",
"policy": "egress-v2",
},
]
chain = build_chain(events)
pinned_head = chain[-1]["record_hash"]The four fictional events cover the retrieval, completion, policy decision, and tool-call labels. The following checks use them to illustrate an edited middle record and a shorter prefix.
PythonIn [5]Expand
# Deliberately change the third synthetic record without recomputing its digest.
tampered = [dict(record, payload=dict(record["payload"])) for record in chain]
tampered[2]["payload"]["decision"] = "deny"ConsoleOut [6]Expand
Clean chain : (True, 'ok') Head hash : a879e6a75ddb1496 ... Edited chain: (False, 'payload altered at record 2') Truncated : (False, 'head does not match pinned head (truncation/rewrite)')
The clean chain verifies and its head is pinned. Editing a single decision label in record 2 breaks verification at that record (payload altered), so the responder knows exactly where to look. Truncating the last record leaves a perfectly self-consistent chain with no internal error, but its head no longer equals the pinned head, so the external pin catches it. This is why the pin matters: without pinned_head, the truncated chain would have verified as "ok."
Run the same verification over the three fixtures, once without the saved digest and once with it. The shorter prefix is valid on its own and fails when compared with the head of the four-record snapshot.
PythonIn [7]Expand
chain_checks = [chain, tampered, chain[:-1]]
check_labels = ["Unchanged", "Edited record", "Shorter prefix"]
internal_checks = [int(verify_chain(records)[0]) for records in chain_checks]
pinned_checks = [
int(verify_chain(records, pinned_head)[0]) for records in chain_checks
]
internal_x = [i - 0.10 for i in range(len(check_labels))]
pinned_x = [i + 0.10 for i in range(len(check_labels))]VisualizationOut [8]Expand

Scaling tamper evidence: Merkle trees and transparency logs
Checking every record of a linear chain takes one hash per record. A Merkle tree over an ordered batch lets a verifier check one entry against a trusted root using an inclusion proof. An append-only tree can also supply a consistency proof that shows the smaller tree is a prefix of a larger tree. RFC 9162, Sections 2.1.3 and 2.1.4
For a balanced binary Merkle tree, the verifier needs at most one sibling hash per level. Doubling the number of leaves adds one level to a complete tree. Recomputing a full root from every original record still requires work proportional to the size of the batch.
Detecting inconsistent views requires observers to compare what they received or rely on an independent witness. Inclusion and consistency proofs on one observer’s view validate that view against the heads it received.
Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!