Skip to content

Evidence integrity: credencestack.evidence.chain, .merkle, .signing, .verify

What makes a bundle verifiable: canonical JSON, the hash chain inside every trace file, the Merkle root over the manifest's files, Ed25519 signatures in a DSSE envelope, and verification that stops at the first failure and says where it is.

Responsibilities

  • Encode values canonically (canonical_json, canonical_bytes).
  • Chain records (chain_records) and check chains (verify_chain).
  • Compute the Merkle root over (path, SHA-256) pairs (merkle.merkle_root).
  • Generate, load and use signing keys, and build signature.json (signing).
  • Verify a bundle or zip end to end (verify.verify_bundle).

Non-goals

  • Anchoring roots in a transparency log, and zero-knowledge proofs: not in 1.0 (see the roadmap).

Public API

Signatures and purposes are generated from the code by scripts/gen_dev_reference.py; errors come from each docstring's Raises: section or from api-notes.yaml, which also holds the hand-written effects column.

Name Kind Signature Purpose Errors Effects
BundleError exception class BundleError Raised when a bundle cannot be written or read. - -
RunInfo model RunInfo(run_id, started_at, finished_at, credencestack_version, packages, python_version, platform, git_commit, …) What ran, with what (the run section of results.json). - data
build_mappings function build_mappings(results: Sequence[RunResult], stats: RunStatistics, scenarios: dict[str, Scenario], fmap: FrameworkMap \| None = None) -> dict[str, Any] mappings.json: pillars first, then every framework reference with what touched it. - pure
load_framework_map function load_framework_map() -> FrameworkMap The packaged mapping, with every reference id checked. - reads the packaged mapping files
read_manifest function read_manifest(bundle: str \| Path) -> Manifest Load manifest.json from a bundle. BundleError: missing or invalid manifest. reads manifest.json
refresh_report function refresh_report(bundle: Path, *, signer_keyid: str \| None = None, trace_url_template: str \| None = None) -> Manifest Re-render report.html from the bundle's files and rewrite the manifest. - rewrites report.html and manifest.json
write_bundle function write_bundle(out: Path, *, info: RunInfo, scenarios: Sequence[Scenario], run: Any, runtime: Mapping[str, Sequence[BaseModel]] \| None = None, reconciliation: BaseModel \| None = None, otel_ids: Mapping[str, Any] \| None = None, settings: Mapping[str, Any] \| None = None, seed_drawn: bool = False) -> Manifest Write the bundle for an Inspect run (run is a runner.inspect_runner.EvalRun). BundleError: if out holds files that are not part of this run. writes the bundle directory
pipeline.run_to_bundle function run_to_bundle(packs: Sequence[Pack], factory: ConnectorFactory, *, connector: str, agent: str, out: Path \| None = None, epochs: int = 1, seed: int = 0, max_samples: int = 8, judge: JudgeScorer \| None = None, runtime: dict[str, list[RuntimeDecision]] \| None = None, models: Sequence[str] \| None = None, run_id: str \| None = None, settings: Mapping[str, Any] \| None = None, seed_drawn: bool = False, on_episode: Callable[[str, int], None] \| None = None) -> BundleRun Run packs with agents from factory and write the bundle to out. BundleError: if out is not empty. runs every episode through Inspect; writes the bundle (and the zip)
export.export_bundle function export_bundle(bundle: Path, dest: Path, *, redact: bool = False) -> ExportResult Copy bundle into dest/bundle/ (dest is a new export-<id> directory). BundleError: the source does not verify, or dest is not empty. reads the bundle; writes the export zip
gate.evaluate_gate function evaluate_gate(bundle: str \| Path, threshold: str = 'high') -> GateResult Apply the gate to an output directory. GateError: the results cannot be read. reads results.json
merkle.merkle_root function merkle_root(files: Iterable[tuple[str, str]]) -> str Hex Merkle root over (path, sha256) pairs (sorted by path here). - pure
signing.generate_keypair function generate_keypair(out_dir: str \| Path, *, overwrite: bool = False) -> tuple[Path, Path] Write a new Ed25519 keypair into out_dir. KeyFileError: if out_dir is inside a git working tree (keys must never be committed), is not a directory, or already holds a key (without overwrite). writes signing.key (mode 0600) and signing.pub
signing.load_private_key function load_private_key(path: str \| Path) -> Ed25519PrivateKey Load a PEM Ed25519 private key. KeyFileError: missing file or not an Ed25519 private key. reads the key file
signing.load_public_key function load_public_key(path: str \| Path) -> Ed25519PublicKey Load an Ed25519 public key: PEM, or base64 of the raw 32 bytes. KeyFileError: missing file or not an Ed25519 public key. reads the key file (or parses base64)
signing.sign_statement function sign_statement(key: Ed25519PrivateKey, manifest_bytes: bytes, merkle_root: str, output_id: str) -> dict[str, Any] Return the signature.json document for a manifest. - reads the wall clock (signed_at)
verify.verify_bundle function verify_bundle(bundle: str \| Path, *, public_key: Ed25519PublicKey \| None = None, require_signature: bool = True) -> VerifyResult Check file hashes, trace hash chains, the Merkle root and the Ed25519 signature. - reads the bundle (or the zip); returns the first failure instead of raising

Examples

Canonical JSON and hash chain

examples/dev/canonical_chain.py
"""Canonical JSON and the per-trace hash chain (and what verify_chain reports on tampering)."""

from __future__ import annotations

from credencestack._internal.canonical import canonical_json
from credencestack.evidence.chain import chain_records, dumps_chain, verify_chain

print("# canonical_json: sorted keys, no spaces, UTF-8, integral floats as integers")
print(" ", canonical_json({"b": 1.0, "a": "café", "c": [True, None]}))

records = chain_records(
    [
        {"kind": "tool_call", "tool": "lookup_invoice", "args": {"invoice_id": "INV-1042"}},
        {"kind": "tool_result", "tool": "lookup_invoice", "result": {"amount": 12000}},
        {"kind": "tool_call", "tool": "request_approval", "args": {"invoice_id": "INV-1042"}},
    ]
)
print("# chain_records: seq, prev_hash and hash (shown shortened)")
for r in records:
    print(f"  seq={r['seq']} prev={r['prev_hash'][:12]}… hash={r['hash'][:12]}… kind={r['kind']}")

text = dumps_chain(records)
print("# verify_chain(untouched) ->", verify_chain(text))
tampered = text.replace('"amount":12000', '"amount":1200')
print("# verify_chain(one amount changed) ->", verify_chain(tampered))
lines = text.splitlines(keepends=True)
print("# verify_chain(middle line deleted) ->", verify_chain(lines[0] + lines[2]))

Output (generated by scripts/gen_doc_examples.py --only dev):

# canonical_json: sorted keys, no spaces, UTF-8, integral floats as integers
  {"a":"café","b":1,"c":[true,null]}
# chain_records: seq, prev_hash and hash (shown shortened)
  seq=0 prev=000000000000… hash=5c9ec6f08315… kind=tool_call
  seq=1 prev=5c9ec6f08315… hash=b84a44cb2992… kind=tool_result
  seq=2 prev=b84a44cb2992… hash=3c32e8b06916… kind=tool_call
# verify_chain(untouched) -> None
# verify_chain(one amount changed) -> ChainFailure(line=2, seq=1, message='seq 1: record hash mismatch (content changed)')
# verify_chain(middle line deleted) -> ChainFailure(line=2, seq=2, message='line 2: expected seq 1, found 2')

Signer and verifier

Sign a bundle with a fresh key, verify it against the public key, then change one byte in a trace. Keys, signatures and times differ on every run and are replaced by placeholders.

examples/dev/sign_verify.py
"""Signer and verifier: manifest + Merkle root -> signature.json; bundle -> VerifyResult."""

from __future__ import annotations

import base64
import json
import tempfile
from pathlib import Path

from credencestack.agents import scripted_safe
from credencestack.connectors import PythonConnector
from credencestack.evidence.bundle import read_manifest
from credencestack.evidence.pipeline import run_to_bundle
from credencestack.evidence.signing import (
    dumps_signature,
    generate_keypair,
    load_private_key,
    load_public_key,
    sign_statement,
)
from credencestack.evidence.verify import verify_bundle
from credencestack.packs import load_pack
from examples.dev._common import show

pack = load_pack("payments")
pack.scenarios = [s for s in pack.scenarios if s.id == "PAY-002"]

with tempfile.TemporaryDirectory() as tmp:
    root = Path(tmp)
    bundle = root / "bundle"
    run_to_bundle(
        [pack],
        lambda: PythonConnector(scripted_safe),
        connector="python",
        agent="credencestack.agents:scripted_safe",
        out=bundle,
    )
    key, pub = generate_keypair(root / "keys")
    manifest = read_manifest(bundle)
    if manifest.merkle_root is None:
        raise SystemExit("the bundle has no Merkle root")
    doc = sign_statement(
        load_private_key(key),
        (bundle / "manifest.json").read_bytes(),
        manifest.merkle_root,
        manifest.id,
    )
    (bundle / "signature.json").write_text(dumps_signature(doc), encoding="utf-8")
    shown = {**doc, "public_key": "<base64>", "signature": "<base64>"}
    shown["envelope"] = {**doc["envelope"], "payload": "<base64>", "signatures": "[<keyid, sig>]"}
    show("signature.json", shown)
    show("the signed payload (decoded)", json.loads(base64.b64decode(doc["envelope"]["payload"])))

    result = verify_bundle(bundle, public_key=load_public_key(pub))
    show("verify_bundle(signed bundle)", {"ok": result.ok, "checks": result.checks})

    trace = sorted((bundle / "traces").rglob("*.jsonl"))[0]
    trace.write_text(trace.read_text().replace('"tool_call"', '"tool_cal1"', 1))
    result = verify_bundle(bundle, public_key=load_public_key(pub))
    show(
        "verify_bundle(after one byte changed in a trace)",
        {"ok": result.ok, "failure": result.failure},
    )

Output (generated by scripts/gen_doc_examples.py --only dev):

# signature.json
{
  "alg": "Ed25519",
  "public_key": "<base64>",
  "keyid": "<sha256>",
  "merkle_root": "<sha256>",
  "signed_at": "<time>",
  "signature": "<base64>",
  "envelope": {
    "payloadType": "application/vnd.credencestack.evidence-statement+json",
    "payload": "<base64>",
    "signatures": "[<keyid, sig>]"
  }
}
# the signed payload (decoded)
{
  "id": "run-<id>",
  "manifest_sha256": "<sha256>",
  "merkle_root": "<sha256>",
  "signed_at": "<time>"
}
# verify_bundle(signed bundle)
{
  "ok": true,
  "checks": [
    "manifest parsed (6 files listed)",
    "file paths are safe (relative, unique, no symbolic links)",
    "every listed file matches its SHA-256",
    "no unlisted files",
    "every trace hash chain is intact",
    "Merkle root <sha256>",
    "Ed25519 signature valid (key <key id>…, matches --public-key)"
  ]
}
# verify_bundle(after one byte changed in a trace)
{
  "ok": false,
  "failure": "traces/PAY-002/0.jsonl: SHA-256 does not match the manifest; first broken trace record at seq 0, line 1: seq 0: record hash mismatch (content changed)"
}

Invariants and gotchas

  • Canonical JSON is close to RFC 8785 (JCS) without its full number algorithm: whole-number floats below 1e21 are written as integers (12000.0 becomes 12000).
  • Each record's hash covers the record without its hash key, plus the previous hash. The first record's prev_hash is GENESIS (64 zeros).
  • Merkle leaves are SHA-256(0x00 || path || 0x00 || sha256) and nodes SHA-256(0x01 || left || right), sorted by path, with an odd node promoted (as in RFC 6962). The root commits to names as well as contents.
  • The signed statement is the manifest's SHA-256, the Merkle root, the run id and the signing time, under DSSE v1 pre-authentication encoding.
  • generate_keypair refuses to write inside a git working tree, so a signing key cannot be committed by accident.
  • Without --public-key, verification uses the key embedded in signature.json, which proves integrity but not who signed. Pin the expected key.

Where the tests are

Test files that import this package's modules (from the file index):

  • tests/docs/test_sample_report.py
  • tests/integration/test_confidential_bundles.py
  • tests/integration/test_evidence_bundle.py
  • tests/integration/test_github_workflows.py
  • tests/integration/test_manifests.py
  • tests/unit/test_bench.py
  • tests/unit/test_canonical.py
  • tests/unit/test_gate.py
  • tests/unit/test_otel.py
  • tests/unit/test_otel_workflows.py
  • tests/unit/test_reports.py
  • tests/unit/test_verify.py