Skip to content

audit_trail.ledger

An append-only evidence ledger in its own tables.

A ledger holds named chains. Each chain is a log of entries the application writes explicitly, sealed in the writer's own transaction: a SECURITY DEFINER function takes the chain's lock, gives each entry the next gapless seq, reads the append time, computes the entry's RFC 6962 leaf hash and the new tree root, and returns a Head per entry. The application role may call that function and read the tables, but not write them, so it can add entries but not change, reorder or delete existing ones.

The ledger needs no AuditTrail and no extra: it can sit next to the row audit and write in the same transaction.

  • build_ledger_tables declares the tables, create_ledger_tables creates them with the functions, and ledger_grant_statements lists the grants of the application role.
  • create_chain starts a chain with its ledger.chain_started entry, which records its config.
  • add buffers an entry in a session, sync or async, to be appended at its commit; the returned PendingHead gets the head once the transaction has committed. It is the recommended way to write from a session.
  • append and append_many append entries on a connection, acreate_chain, aappend and aappend_many on an AsyncConnection.
  • verify checks a chain from its stored rows, and against the trusted checkpoints given as checkpoints=, and returns a LedgerReport; inclusion_proof and consistency_proof serve proofs from the stored nodes, which a client checks against roots it trusts with InclusionProof.verify and ConsistencyProof.verify. Async forms averify, ainclusion_proof and aconsistency_proof.
  • erase deletes an entry's payload through a second definer function and appends its receipt, ledger.erased; change_config replaces a chain's config, recorded in ledger.config_changed; aerase and achange_config are their async forms. ledger_eraser_grant_statements lists the grants of an optional eraser role, and ledger_reader_grant_statements those of a read-only verifier role.
  • Every append first checks whether the database was restored, and starts a new incarnation with a ledger.incarnation_started entry when it was (see "Restore detection" in audit_trail.ledger._migrations). record_maintenance and arecord_maintenance append ledger.maintenance with a reason code, to explain an incarnation that planned work started. A pg_upgrade gives ledger.cluster_changed and no new incarnation; confirm_upgrade and aconfirm_upgrade append ledger.upgrade_confirmed once the owner has checked the chain against a checkpoint taken before it, and until then a verifier notes it UNCONFIRMED_UPGRADE.
  • prepare_checkpoint returns the unsigned checkpoint of a verified head, a C2SP tlog-checkpoint whose origin names the chain and its incarnation, holding no lock while the host signs it; record_checkpoint checks the signed note against the key history and the tree and appends it as ledger.checkpoint, once per note. A checkpoint may commit to the erasure journal of its size (LedgerJournal, erasure_journal), and both return the consistency proof from the newest checkpoint before it. Async forms aprepare_checkpoint, arecord_checkpoint and aerasure_journal.
  • export_bundle writes a range of a chain to a bundle of stream type "ledger", which audit_trail.integrity.verify_bundle and the command line check without the database, with verify's findings; verify_bundle here is the same check, typed for a ledger bundle. record_bundle_manifest appends ledger.bundle_manifest, the digest of a bundle's host files, so that the log anchors them. Async forms aexport_bundle and arecord_bundle_manifest. The format is in docs/spec/ledger-v1.md.
  • record_restore records a database restore, run by the owner: it appends ledger.restored with a trusted signed checkpoint, the lost range and the incarnation it explains, and erases again what the checkpoint's journal erased, within the prefix proven shared with it (see audit_trail.ledger._restore). Async form arecord_restore. Each checkpoint comes with a consistency proof from the checkpoint before it; RestoreKit keeps the signed note, the journal and that proof together as JSON, off the database, and record_restore takes it as kit=.

A call denied a privilege (SQLSTATE 42501) raises LedgerPermissionError, both a PermissionError and a SQLAlchemy ProgrammingError, whose message says who may do it and the grant to run; the driver's error is its __cause__.

The integrity names a ledger caller needs are re-exported here, so that audit_trail.ledger alone is enough: Status, Anchor, KeyHistory and KeyWindow, Signer and SignatureVerifier, and the errors NoteError, BundleError and CanonicalEncodingError. The reference signers stay in audit_trail.integrity.ed25519 and audit_trail.integrity.ecdsa.

The entry body, the leaf input and the tree are described in audit_trail.ledger._entry. Types and reason codes starting with ledger. are the package's.

BUNDLE_MANIFEST module-attribute

BUNDLE_MANIFEST = 'ledger.bundle_manifest'

The type of the entry record_bundle_manifest appends.

Its attributes are {"sha256": <base64>}: the digest of the host files of a bundle (host_files_digest), so that a bundle holding the entry anchors its host files in the log.

CHAIN_STARTED module-attribute

CHAIN_STARTED = 'ledger.chain_started'

The type of a chain's first entry, which holds the chain's config.

CHECKPOINT module-attribute

CHECKPOINT = 'ledger.checkpoint'

The type of the entry record_checkpoint appends.

Its attributes are {"note": <signed note>}: a signed ledger checkpoint (_checkpoint) of a head of the chain, in the incarnation the entry is appended in.

CLUSTER_CHANGED module-attribute

CLUSTER_CHANGED = 'ledger.cluster_changed'

The type of the entry an append writes first after a pg_upgrade.

A new system identifier with a higher major version and the same state-table OID: no new incarnation. Its attributes are {"from": <identity>, "to": <identity>}, as in ledger.incarnation_started. A verifier notes it unconfirmed until a ledger.upgrade_confirmed entry names it.

CONFIG_CHANGED module-attribute

CONFIG_CHANGED = 'ledger.config_changed'

The type of the entry that records a chain's new config, whole.

ERASED module-attribute

ERASED = 'ledger.erased'

The type of an erasure's receipt.

Its attributes are entry_id, incarnation and seq of the erased entry, and the reason_code.

INCARNATION_STARTED module-attribute

INCARNATION_STARTED = 'ledger.incarnation_started'

The type of the entry an append writes first when it detects a restore.

It is the first entry of the new incarnation. Its attributes::

{"cause": "new_cluster" | "recreated" | "new_timeline",
 "from": <identity>, "to": <identity>}

where an identity is {"server_major": <int>, "system_identifier": "<decimal>", "table_oid": <int>, "timeline": <int>}: the identity stored before and the one observed. The system identifier is a string, since it does not fit a double.

MAINTENANCE module-attribute

MAINTENANCE = 'ledger.maintenance'

The type of the entry record_maintenance appends.

Its attributes are {"incarnation": <int>, "reason": <reason code>}: the incarnation it explains, the chain's incarnation when it was appended (so also the entry's own), and the host's reason code.

NEW_CLUSTER module-attribute

NEW_CLUSTER = 'new_cluster'

The cause of an incarnation: the state table's OID and the system identifier changed (a dump restored into a new cluster), or the system identifier changed without a higher major version.

NEW_TIMELINE module-attribute

NEW_TIMELINE = 'new_timeline'

The cause of an incarnation: the WAL timeline changed (point-in-time recovery, a standby promoted).

RECREATED module-attribute

RECREATED = 'recreated'

The cause of an incarnation: the state table's OID changed in the same cluster (a dump restored into it).

RESTORED module-attribute

RESTORED = 'ledger.restored'

The type of the entry record_restore appends after a restore.

Its attributes::

{"checkpoint": <signed note>, "incarnation": <int>,
 "journal": <journal text> | null,
 "lost": [<first>, <last>] | null,
 "proof": [{"path": [<b64>, ...], "root": <b64>, "size": <int>}, ...],
 "proven": {"root": <b64>, "size": <int>} | null,
 "reapplied": <int>, "restored_size": <int>}

checkpoint is the signed ledger checkpoint of the history the restore lost part of; incarnation the incarnation the entry explains, its own; journal the canonical text of the checkpoint's erasure journal when the checkpoint is above the restored size and one was given, null otherwise (at or below it, the chain's receipts are the journal); restored_size the chain's size the restore brought it back to; lost the seq range above it that the checkpoint knew, null when the checkpoint is not above it; proven the size and root of the proven-shared prefix, null when nothing is proven; proof the consistency proofs from it to the checkpoint; reapplied how many re-applied receipts follow it. See audit_trail.ledger._restore.

UPGRADE_CONFIRMED module-attribute

UPGRADE_CONFIRMED = 'ledger.upgrade_confirmed'

The type of the entry confirm_upgrade appends.

The owner's statement that a ledger.cluster_changed entry was a real pg_upgrade of this database, checked against a checkpoint taken before it, and not a data-only restore of an older dump into a fresh cluster of a higher major version, which restore detection cannot tell from one. Its attributes are {"entry_id": <uuid>, "incarnation": <int>, "seq": <int>}: those of the ledger.cluster_changed entry it confirms.

BundleError

Bases: ValueError

A bundle that cannot be read as one.

Not a zip file, an entry missing or out of order, a line that is not JSON of the format, or entries that contradict each other. The message names the entry and the line, never a stored value. A bundle that reads but does not match its chain is not an error: verify_bundle reports that as findings.

CanonicalEncodingError

Bases: ValueError

A value has no canonical encoding.

The message names the problem, never the value, which may be personal data.

KeyHistory

KeyHistory(windows: Mapping[str, KeyWindow])

The window of every signing key, by key_id.

A signature by a key the history does not name does not count either: give every key the verifier knows a window.

A window limits which blocks a key may attest, not when it signed: a checkpoint signature is judged at the seq the checkpoint names, so whoever holds a key can still sign a statement naming an earlier block inside its window. Drop a compromised key from the verifier used for newly received checkpoints (record_checkpoint).

Parameters:

Name Type Description Default
windows Mapping[str, KeyWindow]

key_id (name+hash, as Signer.key_id gives it) to its window.

required

Raises:

Type Description
ValueError

A key id is empty or a window is not a KeyWindow.

Source code in audit_trail/integrity/_history.py
def __init__(self, windows: Mapping[str, KeyWindow]) -> None:
    checked: dict[str, KeyWindow] = {}
    for key_id, window in windows.items():
        if not isinstance(key_id, str) or not key_id:
            raise ValueError("a key id is non-empty text")
        if not isinstance(window, KeyWindow):
            raise ValueError(f"the window of {key_id} is not a KeyWindow")
        checked[key_id] = window
    self._windows = checked

windows property

windows: dict[str, KeyWindow]

The windows, by key_id; a copy.

from_vkeys classmethod

from_vkeys(vkeys: Iterable[str]) -> KeyHistory

The history of keys that were never rotated: each verifier key may sign from block 1 on, with no end.

For one key, or keys none of which was retired or compromised; give it the same verifier keys as the verifier. Once a key is rotated out, build the history with its window instead.

Parameters:

Name Type Description Default
vkeys Iterable[str]

The verifier keys, as Ed25519Signer.vkey and EcdsaP256Signer.vkey give them.

required

Raises:

Type Description
ValueError

A key is not a verifier key.

Source code in audit_trail/integrity/_history.py
@classmethod
def from_vkeys(cls, vkeys: Iterable[str]) -> KeyHistory:
    """The history of keys that were never rotated: each verifier key
    may sign from block 1 on, with no end.

    For one key, or keys none of which was retired or compromised; give
    it the same verifier keys as the verifier. Once a key is rotated
    out, build the history with its window instead.

    Args:
        vkeys: The verifier keys, as ``Ed25519Signer.vkey`` and
            ``EcdsaP256Signer.vkey`` give them.

    Raises:
        ValueError: A key is not a verifier key.
    """
    windows: dict[str, KeyWindow] = {}
    for vkey in vkeys:
        if not isinstance(vkey, str):
            raise ValueError("a verifier key is text")
        key = parse_vkey(vkey, f"{vkey!r} is not a verifier key")
        windows[key.key_id] = KeyWindow()
    return cls(windows)

to_json

to_json() -> str

The history as JSON text, for a file kept with the keys.

{key_id: {"valid_from": n, "retired_at": n | null, "compromised_from": n | null}}, canonically encoded: the form the command line's --key-history file holds, and history in a bundle's keys.json. from_json reads it back.

Source code in audit_trail/integrity/_history.py
def to_json(self) -> str:
    """The history as JSON text, for a file kept with the keys.

    ``{key_id: {"valid_from": n, "retired_at": n | null,
    "compromised_from": n | null}}``, canonically encoded: the form the
    command line's ``--key-history`` file holds, and ``history`` in a
    bundle's ``keys.json``. ``from_json`` reads it back.
    """
    return canonical(history_to_mapping(self)).decode("utf-8")

from_json classmethod

from_json(text: str) -> KeyHistory

Read a history back from to_json, or a key history file.

The text need not be canonical: a file written by hand reads too. A window may leave out a field, which then takes its default.

Parameters:

Name Type Description Default
text str

The JSON text, as to_json gives it.

required

Raises:

Type Description
ValueError

The text is not JSON (the JSON error is the cause), is not the form to_json writes, or a window is not valid.

Source code in audit_trail/integrity/_history.py
@classmethod
def from_json(cls, text: str) -> KeyHistory:
    """Read a history back from ``to_json``, or a key history file.

    The text need not be canonical: a file written by hand reads too. A
    window may leave out a field, which then takes its default.

    Args:
        text: The JSON text, as ``to_json`` gives it.

    Raises:
        ValueError: The text is not JSON (the JSON error is the cause),
            is not the form ``to_json`` writes, or a window is not valid.
    """
    try:
        value = json.loads(text)
    except (ValueError, RecursionError) as exc:
        raise ValueError("a key history is JSON text") from exc
    return history_from_mapping(value)

check

check(
    key_id: str, position: int
) -> tuple[KeyProblem, str] | None

Why key_id's signature at position does not count, and a sentence saying so; None when it counts.

Source code in audit_trail/integrity/_history.py
def check(self, key_id: str, position: int) -> tuple[KeyProblem, str] | None:
    """Why ``key_id``'s signature at ``position`` does not count, and a
    sentence saying so; ``None`` when it counts."""
    window = self._windows.get(key_id)
    if window is None:
        return KeyProblem.NOT_VALID, f"the key history has no window for {key_id}"
    problem = window.problem(position)
    if problem is KeyProblem.COMPROMISED:
        return problem, (
            f"{key_id} is compromised from block {window.compromised_from}; "
            f"this signature is at {position}"
        )
    if problem is KeyProblem.NOT_VALID:
        end = "" if window.retired_at is None else f" to {window.retired_at}"
        return problem, (
            f"{key_id} may sign from block {window.valid_from}{end}; this "
            f"signature is at {position}"
        )
    return None

KeyWindow dataclass

KeyWindow(
    valid_from: int = 1,
    retired_at: int | None = None,
    compromised_from: int | None = None,
)

The blocks one key may sign.

Attributes:

Name Type Description
valid_from int

The first seq the key may sign.

retired_at int | None

The first seq it may no longer sign, after a planned rotation; None while it is in use.

compromised_from int | None

The first seq from which its signatures are not trusted, because someone else may hold it; None when it is not known to be compromised. Signatures below it still count.

Raises:

Type Description
ValueError

A position is not an integer of at least 1, or retired_at is below valid_from.

problem

problem(position: int) -> KeyProblem | None

Why a signature at position does not count; None if it does.

Source code in audit_trail/integrity/_history.py
def problem(self, position: int) -> KeyProblem | None:
    """Why a signature at ``position`` does not count; ``None`` if it does."""
    if self.compromised_from is not None and position >= self.compromised_from:
        return KeyProblem.COMPROMISED
    if position < self.valid_from or (
        self.retired_at is not None and position >= self.retired_at
    ):
        return KeyProblem.NOT_VALID
    return None

NoteError

NoteError(
    reason: Literal[
        "MALFORMED", "BAD_SIGNATURE", "UNKNOWN_KEY"
    ],
    message: str,
)

Bases: ValueError

A note that is not a well-formed signed note, or that fails to verify.

Attributes:

Name Type Description
reason

MALFORMED: not in the format. BAD_SIGNATURE: a signature of a known key does not verify. UNKNOWN_KEY: no signature is from a known key (or there is none).

Source code in audit_trail/integrity/_note.py
def __init__(
    self, reason: Literal["MALFORMED", "BAD_SIGNATURE", "UNKNOWN_KEY"], message: str
) -> None:
    super().__init__(f"{reason}: {message}")
    self.reason = reason

SignatureVerifier

Bases: Protocol

Checks signatures made by known keys.

key_algorithm

key_algorithm(key_id: str) -> str | None

The algorithm of a known key; None for an unknown one.

Source code in audit_trail/integrity/_sign.py
def key_algorithm(self, key_id: str) -> str | None:
    """The algorithm of a known key; ``None`` for an unknown one."""
    ...

verify

verify(
    key_id: str,
    algorithm: str,
    message: bytes,
    signature: bytes,
) -> bool

Whether signature is the signature of message by the key.

Source code in audit_trail/integrity/_sign.py
def verify(
    self, key_id: str, algorithm: str, message: bytes, signature: bytes
) -> bool:
    """Whether ``signature`` is the signature of ``message`` by the key."""
    ...

Signer

Bases: Protocol

Signs blocks and checkpoints.

Attributes:

Name Type Description
key_id str

<key name>+<8 hex digits of the key hash>; see the module documentation. Stored with every block it signs.

algorithm str

Name of the signature algorithm, such as "ed25519".

sign

sign(message: bytes) -> bytes

The signature of message, without the key hash.

Source code in audit_trail/integrity/_sign.py
def sign(self, message: bytes) -> bytes:
    """The signature of ``message``, without the key hash."""
    ...

Anchor

Bases: StrEnum

Whether the chain was checked against a trusted checkpoint.

Status

Bases: StrEnum

Overall result of a verification.

CheckpointRefusedError

CheckpointRefusedError(
    message: str, report: LedgerReport | None = None
)

Bases: ValueError

A checkpoint was not prepared or not recorded; nothing was written.

Attributes:

Name Type Description
report

For prepare_checkpoint, the verification that has failures or whose head is not a head of the chain as it is now; None otherwise.

Source code in audit_trail/ledger/_anchor.py
def __init__(self, message: str, report: LedgerReport | None = None) -> None:
    super().__init__(message)
    self.report = report

PreparedCheckpoint dataclass

PreparedCheckpoint(
    checkpoint: LedgerCheckpoint,
    journal: LedgerJournal | None,
    report: LedgerReport,
    proof: ConsistencyProof | None = None,
)

What prepare_checkpoint returns.

Attributes:

Name Type Description
checkpoint LedgerCheckpoint

The unsigned checkpoint: sign checkpoint.text with any C2SP note signer, or call checkpoint.signed([signer]).

journal LedgerJournal | None

The erasure journal the checkpoint commits to, or None. Keep its to_json() with the signed note, off the database.

report LedgerReport

The verification the checkpoint rests on.

proof ConsistencyProof | None

The consistency proof from the newest checkpoint recorded before (or since_size) to this one, from the stored nodes; None when there is none. Keep it with the signed note.

kit

kit(signed_note: LedgerCheckpoint | str) -> RestoreKit

The restore kit of the checkpoint once signed: the signed note, the journal and the proof. Keep its to_json() off the database.

Parameters:

Name Type Description Default
signed_note LedgerCheckpoint | str

The checkpoint signed, or its note text.

required

Raises:

Type Description
ValueError

The note is not this checkpoint (its text differs).

NoteError

The note is not a ledger checkpoint.

Source code in audit_trail/ledger/_anchor.py
def kit(self, signed_note: LedgerCheckpoint | str) -> RestoreKit:
    """The restore kit of the checkpoint once signed: the signed note,
    the journal and the proof. Keep its ``to_json()`` off the database.

    Args:
        signed_note: The checkpoint signed, or its note text.

    Raises:
        ValueError: The note is not this checkpoint (its text differs).
        NoteError: The note is not a ledger checkpoint.
    """
    signed = (
        signed_note
        if isinstance(signed_note, LedgerCheckpoint)
        else LedgerCheckpoint.from_note(signed_note)
    )
    if signed.text != self.checkpoint.text:
        raise ValueError("the signed note is not the prepared checkpoint")
    return kit_of(signed, self.journal, self.proof)

RecordedCheckpoint dataclass

RecordedCheckpoint(
    seq: int,
    incarnation: int,
    leaf_hash: bytes,
    checkpoint: LedgerCheckpoint,
    created: bool,
    head: Head | None,
    journal: LedgerJournal | None = None,
    proof: ConsistencyProof | None = None,
)

What record_checkpoint stored.

Attributes:

Name Type Description
seq int

The seq of the ledger.checkpoint entry holding the note.

incarnation int

That entry's incarnation.

leaf_hash bytes

That entry's leaf hash.

checkpoint LedgerCheckpoint

The checkpoint, with its signatures.

created bool

False when the same note was recorded before and this is the entry that holds it.

head Head | None

The head after the entry, when this call appended it; None when it was recorded before.

journal LedgerJournal | None

The journal the checkpoint commits to, or None when it has no journal line.

proof ConsistencyProof | None

The consistency proof from the newest checkpoint recorded before (or since_size) to this one; None when there is none. prepare_checkpoint returns the same one.

kit property

kit: RestoreKit

The restore kit: the signed note, the journal and the proof.

Keep its to_json() off the database, with the backups; after a restore, give it to record_restore(kit=...).

LedgerBusyError

Bases: Exception

The chain's lock was not granted within the lock_timeout.

Another transaction is appending to the chain and has not ended. The transaction that raised this is aborted: roll it back and retry later. lock_timeout bounds each lock wait, not the call: set statement_timeout to bound the total, which cancels the statement with SQLSTATE 57014 instead of raising this.

PendingHead

PendingHead(chain: str, entry: Entry)

The head of a buffered entry, set once its transaction has committed.

add returns one per entry. Until the commit, head is None: the entry has no sequence number yet, or only a provisional one that a rollback would free. After the commit, head is the entry's Head. If the entry is discarded instead (rolled back, or the session closed without committing), discarded is True and head stays None.

Attributes:

Name Type Description
chain

The chain the entry goes to.

entry

The entry.

Source code in audit_trail/ledger/_buffer.py
def __init__(self, chain: str, entry: Entry) -> None:
    self.chain = chain
    self.entry = entry
    self._head: Head | None = None
    self._provisional: Head | None = None
    self._discarded = False

head property

head: Head | None

The entry's head once its transaction has committed, else None.

discarded property

discarded: bool

Whether the entry was discarded, so it will never have a head.

EntryRange dataclass

EntryRange(first: int, last: int)

A scope of entries by seq, both ends included.

Raises:

Type Description
ValueError

An end is not an integer of at least 1, or last is below first.

LedgerBundleResult dataclass

LedgerBundleResult(
    chain: str,
    first: int,
    last: int,
    entries: int,
    context: int,
    nodes: int,
    checkpoints: int,
    files: dict[str, str],
    manifest: str,
    manifest_sha256: str,
)

What export_bundle wrote.

Attributes:

Name Type Description
chain str

The chain.

first int

The first entry in scope.

last int

The last entry in scope.

entries int

Entries in entries.jsonl.

context int

Entries in context.jsonl.

nodes int

Hashes in nodes.jsonl.

checkpoints int

Checkpoints in checkpoints.jsonl.

files dict[str, str]

The SHA-256 of every entry the manifest lists, as hex, by name.

manifest str

The manifest note, signed when a signer was given.

manifest_sha256 str

The SHA-256 of manifest.note, as hex: keep it elsewhere and pass it to verify_bundle to anchor the manifest.

LedgerCheckpoint dataclass

LedgerCheckpoint(
    origin: str,
    size: int,
    root: bytes,
    journal: bytes | None = None,
    extensions: tuple[str, ...] = (),
    signatures: tuple[NoteSignature, ...] = (),
)

A checkpoint of a ledger chain: origin, size and root, maybe signed.

Attributes:

Name Type Description
origin str

<host origin>/<chain>/i<incarnation>.

size int

The tree size, at least 1.

root bytes

The RFC 6962 root of the first size entries, 32 bytes.

journal bytes | None

The commitment of the erasure journal at size (LedgerJournal.commitment), 32 bytes, or None.

extensions tuple[str, ...]

The host's lines after the statement, signed with it.

signatures tuple[NoteSignature, ...]

The note's signature lines; empty when unsigned.

Raises:

Type Description
ValueError

A field is invalid.

host_origin property

host_origin: str

The host's part of the origin.

chain property

chain: str

The chain the origin names.

incarnation property

incarnation: int

The incarnation the origin names.

text property

text: str

The note text: origin, size, root, journal line, extension lines.

note property

note: Note

The checkpoint as a note.

to_note

to_note() -> str

The signed note to keep and record; the text alone when unsigned.

Source code in audit_trail/ledger/_checkpoint.py
def to_note(self) -> str:
    """The signed note to keep and record; the text alone when unsigned."""
    return str(self.note)

signed

signed(signers: Iterable[Signer]) -> LedgerCheckpoint

The checkpoint with a signature by each of signers added.

Raises:

Type Description
NoteError

MALFORMED: a signer's key signed it already.

Source code in audit_trail/ledger/_checkpoint.py
def signed(self, signers: Iterable[Signer]) -> LedgerCheckpoint:
    """The checkpoint with a signature by each of ``signers`` added.

    Raises:
        NoteError: ``MALFORMED``: a signer's key signed it already.
    """
    return replace(self, signatures=add_signatures(self.note, signers).signatures)

verify

verify(verifier: SignatureVerifier) -> list[str]

Check the signatures; the key_id of each that verified.

Raises:

Type Description
NoteError

BAD_SIGNATURE, UNKNOWN_KEY, or MALFORMED for two signatures of one known key.

Source code in audit_trail/ledger/_checkpoint.py
def verify(self, verifier: SignatureVerifier) -> list[str]:
    """Check the signatures; the ``key_id`` of each that verified.

    Raises:
        NoteError: ``BAD_SIGNATURE``, ``UNKNOWN_KEY``, or ``MALFORMED``
            for two signatures of one known key.
    """
    return verify_note(self.note, verifier)

from_note classmethod

from_note(note: str) -> LedgerCheckpoint

Read a checkpoint from its note, signed or not.

Signatures are read, not checked; verify checks them.

Raises:

Type Description
NoteError

MALFORMED: not a note, or not a ledger checkpoint in the form text writes.

Source code in audit_trail/ledger/_checkpoint.py
@classmethod
def from_note(cls, note: str) -> LedgerCheckpoint:
    """Read a checkpoint from its note, signed or not.

    Signatures are read, not checked; ``verify`` checks them.

    Raises:
        NoteError: ``MALFORMED``: not a note, or not a ledger checkpoint
            in the form ``text`` writes.
    """
    parsed = parse_note(note)
    lines = parsed.text[:-1].split("\n")
    if len(lines) < 3:
        raise _malformed("it has no origin, size and root lines")
    origin, size, root = lines[:3]
    rest = lines[3:]
    journal = None
    if rest and rest[0].casefold().startswith(NAMESPACE):
        journal = read_journal_line(rest[0])
        rest = rest[1:]
    try:
        split_origin(origin)
        for line in rest:
            check_extension(line)
    except ValueError as exc:
        raise _malformed(str(exc)) from None
    digest = decode_canonical(root)
    if not _SIZE.fullmatch(size) or digest is None or len(digest) != 32:
        raise _malformed("the size or the root line is invalid")
    checkpoint = cls(origin, int(size), digest, journal, tuple(rest))
    if checkpoint.text != parsed.text:  # pragma: no cover - by construction
        raise _malformed("the text is not in its canonical form")
    return replace(checkpoint, signatures=parsed.signatures)

ChainConfig dataclass

ChainConfig(
    reason_codes: tuple[str, ...] = (),
    protected_types: tuple[str, ...] = (),
    precondition: str | None = None,
    detect_restores: bool = True,
)

The config of a chain, recorded in its ledger.chain_started entry.

Attributes:

Name Type Description
reason_codes tuple[str, ...]

The reason codes an erasure of this chain may give (REASON_CODE_PATTERN, not starting with ledger.).

protected_types tuple[str, ...]

The entry types that may not be erased.

precondition str | None

The name of a SQL function an erasure must pass, optionally schema-qualified (a bare name is in the ledger's schema), or None. The function takes (chain text, entry_id uuid, reason_code text) and returns boolean; see erase.

detect_restores bool

Store the cluster identity, so that appends can tell when the database was restored. Creating a chain with it on fails where the identity functions cannot be called.

as_dict

as_dict() -> dict[str, Any]

The config as the attributes of ledger.chain_started.

Source code in audit_trail/ledger/_entry.py
def as_dict(self) -> dict[str, Any]:
    """The config as the ``attributes`` of ``ledger.chain_started``."""
    return {
        "detect_restores": self.detect_restores,
        "precondition": self.precondition,
        "protected_types": list(self.protected_types),
        "reason_codes": list(self.reason_codes),
    }

Entry dataclass

Entry(
    type: str,
    attributes: Mapping[str, Any] = dict(),
    payload: Mapping[str, Any] = dict(),
    actor: str | None = None,
    declared_at: datetime = _now(),
    type_version: int = 1,
    entry_id: UUID = uuid.uuid4(),
)

One entry to append.

Attributes:

Name Type Description
type str

The entry type, matching TYPE_PATTERN; types starting with ledger. (in any case) are the package's.

attributes Mapping[str, Any]

The never-erased fields: a JSON object the host validates. It must encode canonically.

payload Mapping[str, Any]

The erasable groups: group name (GROUP_PATTERN) to value. A group whose value is None is left out. Each value must encode canonically.

actor str | None

The submitting principal, or None; at most MAX_ACTOR_LENGTH characters.

declared_at datetime

The time the host declares for the entry; an aware datetime, stored to the microsecond. Now, by default.

type_version int

The version of the type's schema, 1 or more.

entry_id UUID

The stable id host tables can reference before the entry is appended; a random UUID by default.

Head dataclass

Head(
    incarnation: int,
    seq: int,
    leaf_hash: bytes,
    size: int,
    root: bytes,
)

The tree head after one entry was appended.

The head is provisional until the transaction that appended the entry commits: a rollback frees its seq for the next append.

Attributes:

Name Type Description
incarnation int

The chain's incarnation.

seq int

The entry's sequence number, from 1, gapless in a chain.

leaf_hash bytes

The entry's leaf hash, 32 bytes.

size int

The size of the tree with this entry, equal to seq.

root bytes

The RFC 6962 root of that tree, 32 bytes.

(seq, leaf_hash) is the writer's receipt for its own entry; what anchors the log is (size, root).

ErasureRefusedError

Bases: ValueError

The erase function refused the erasure; nothing was erased.

The message says why: the reason code is not one of the chain's, the entry's type is protected or the package's, the entry has no payload or is erased already, or the precondition refused it (or cannot be called). The transaction is aborted: roll it back.

JournalErasure dataclass

JournalErasure(
    receipt: int,
    receipt_id: UUID,
    entry_id: UUID,
    incarnation: int,
    seq: int,
    reason_code: str,
)

One receipt of a journal, ordered by its seq.

Attributes:

Name Type Description
receipt int

The receipt's seq.

receipt_id UUID

The receipt's entry_id.

entry_id UUID

The erased entry's entry_id.

incarnation int

The erased entry's incarnation.

seq int

The erased entry's seq.

reason_code str

The reason code of the erasure.

LedgerJournal dataclass

LedgerJournal(
    chain: str,
    size: int,
    erasures: tuple[JournalErasure, ...] = (),
)

The receipts of a chain up to a size: what a checkpoint commits to.

Keep its text (to_json) with the signed checkpoint, off the database: after a restore, it is what record_restore erases again.

Attributes:

Name Type Description
chain str

The chain.

size int

The checkpoint's size: every receipt with a seq up to it.

erasures tuple[JournalErasure, ...]

The receipts, by receipt.

Raises:

Type Description
ValueError

A field is invalid, a receipt is above size, or two have the same seq.

commitment property

commitment: bytes

The SHA-256 commitment a checkpoint's journal line states.

to_json

to_json() -> str

The canonical form.

Source code in audit_trail/ledger/_journal.py
def to_json(self) -> str:
    """The canonical form."""
    return self._canonical().decode()

from_json classmethod

from_json(text: str) -> LedgerJournal

Read a journal back from to_json.

Raises:

Type Description
ValueError

The text is not a journal in its canonical form.

Source code in audit_trail/ledger/_journal.py
@classmethod
def from_json(cls, text: str) -> LedgerJournal:
    """Read a journal back from ``to_json``.

    Raises:
        ValueError: The text is not a journal in its canonical form.
    """
    try:
        value: Any = json.loads(text)
        journal = _journal(value)
    except (ValueError, TypeError, KeyError, AttributeError) as exc:
        raise ValueError(f"not a ledger journal: {exc}") from None
    if journal.to_json() != text:
        raise ValueError("not a ledger journal: the text is not canonical")
    return journal

RestoreKit dataclass

RestoreKit(
    checkpoint: LedgerCheckpoint,
    journal: LedgerJournal | None = None,
    proof: tuple[ConsistencyProof, ...] = (),
)

A checkpoint's signed note, journal and consistency proof, together.

Keep to_json() off the database, next to the backups, after each checkpoint is signed (PreparedCheckpoint.kit, RecordedCheckpoint.kit). After a restore, give the newest kit to record_restore(kit=...).

A kit's journal covers the erasures up to its checkpoint's size only: an erasure made after the newest kit comes back on a restore, and record_restore does not report it. After erasures, take a checkpoint with a journal and keep its new kit, and keep a log of erasures off the database, to erase again after a restore.

Attributes:

Name Type Description
checkpoint LedgerCheckpoint

The signed checkpoint.

journal LedgerJournal | None

The journal its journal line commits to, or None when it has none.

proof tuple[ConsistencyProof, ...]

Consistency proof steps of the checkpoint's chain, each starting where the one before ends, the last at the checkpoint's size and root; empty when there is none.

Raises:

Type Description
ValueError

The parts do not belong together: the journal is missing, extra, or not the one the note commits to; a step is of another chain, does not hold between the roots it carries, does not start where the one before ends, or the last does not end at the checkpoint.

to_json

to_json() -> str

The kit as canonical JSON text.

Source code in audit_trail/ledger/_kit.py
def to_json(self) -> str:
    """The kit as canonical JSON text."""
    journal = None if self.journal is None else json.loads(self.journal.to_json())
    return canonical(
        {
            "checkpoint": self.checkpoint.to_note(),
            "journal": journal,
            "proof": [_step_form(step) for step in self.proof],
            "v": KIT_VERSION,
        }
    ).decode()

from_json classmethod

from_json(text: str) -> RestoreKit

Read a kit back from its JSON text.

Signatures, the journal's commitment and the proof are checked as the constructor checks them, not trusted: record_restore checks them against the keys and the chain.

Raises:

Type Description
ValueError

The text is not a restore kit, or its parts do not belong together.

Source code in audit_trail/ledger/_kit.py
@classmethod
def from_json(cls, text: str) -> RestoreKit:
    """Read a kit back from its JSON text.

    Signatures, the journal's commitment and the proof are checked as
    the constructor checks them, not trusted: ``record_restore`` checks
    them against the keys and the chain.

    Raises:
        ValueError: The text is not a restore kit, or its parts do not
            belong together.
    """
    if not isinstance(text, str):
        raise TypeError("a restore kit is read from its JSON text")
    try:
        value: Any = json.loads(text)
        if not isinstance(value, dict) or set(value) != _KEYS:
            raise ValueError("unexpected fields")
        if not is_int(value["v"]) or value["v"] != KIT_VERSION:
            raise ValueError("unknown kit version")
        note = value["checkpoint"]
        if not isinstance(note, str):
            raise ValueError("checkpoint is not a note")
        checkpoint = LedgerCheckpoint.from_note(note)
        journal = (
            None
            if value["journal"] is None
            else journal_from_value(value["journal"])
        )
        if not isinstance(value["proof"], list):
            raise ValueError("proof is not a list")
        steps = tuple(_step(checkpoint.chain, item) for item in value["proof"])
        return cls(checkpoint, journal, steps)
    except (ValueError, TypeError, KeyError, AttributeError, NoteError) as exc:
        raise ValueError(f"not a restore kit: {exc}") from None

LedgerPermissionError

LedgerPermissionError(
    message: str,
    statement: str | None,
    params: Any,
    orig: BaseException,
    hide_parameters: bool = False,
    connection_invalidated: bool = False,
    code: str | None = None,
    ismulti: bool | None = None,
)

Bases: PermissionError, ProgrammingError

A ledger call was denied a privilege (SQLSTATE 42501).

It is both a PermissionError and a SQLAlchemy ProgrammingError (so a DBAPIError): code that caught the driver's error around a ledger call still catches it. It keeps that error's statement, params and orig, and the error is its __cause__.

The message is the server's, followed by who may do what was denied and the fix, as in the "Permission errors" table of the ledger guide; for an object the table does not list, it points at that table. The transaction is aborted: roll it back.

Source code in audit_trail/ledger/_permissions.py
def __init__(
    self,
    message: str,
    statement: str | None,
    params: Any,
    orig: BaseException,
    hide_parameters: bool = False,
    connection_invalidated: bool = False,
    code: str | None = None,
    ismulti: bool | None = None,
) -> None:
    ProgrammingError.__init__(
        self,
        statement,
        params,
        orig,
        hide_parameters=hide_parameters,
        connection_invalidated=connection_invalidated,
        code=code,
        ismulti=ismulti,
    )
    self.args = (message,)

wrap classmethod

wrap(exc: DBAPIError) -> LedgerPermissionError

The error for a driver error of SQLSTATE 42501, explained.

Source code in audit_trail/ledger/_permissions.py
@classmethod
def wrap(cls, exc: DBAPIError) -> LedgerPermissionError:
    """The error for a driver error of SQLSTATE 42501, explained."""
    error = cls(
        explain(exc),
        exc.statement,
        exc.params,
        exc.orig if exc.orig is not None else exc,
        hide_parameters=exc.hide_parameters,
        connection_invalidated=exc.connection_invalidated,
        code=exc.__dict__.get("code"),
        ismulti=exc.ismulti,
    )
    error.detail = list(exc.detail)
    return error

RecordedRestore dataclass

RecordedRestore(
    seq: int,
    incarnation: int,
    leaf_hash: bytes,
    checkpoint: LedgerCheckpoint,
    created: bool,
    started: bool,
    restored_size: int,
    lost: tuple[int, int] | None,
    proven_size: int,
    reapplied: tuple[JournalErasure, ...],
    unproven: tuple[JournalErasure, ...],
    head: Head | None,
)

What record_restore stored.

Attributes:

Name Type Description
seq int

The seq of the ledger.restored entry.

incarnation int

The incarnation it explains, its own.

leaf_hash bytes

Its leaf hash.

checkpoint LedgerCheckpoint

The checkpoint, with its signatures.

created bool

False when the same note explained this incarnation already and this is that entry; nothing was appended or erased.

started bool

Whether the entry started its incarnation (detection was off or missed the restore), rather than explaining one that restore detection started.

restored_size int

The size the restore brought the chain back to.

lost tuple[int, int] | None

The seq range (first, last) above the restored size that the checkpoint knew; None when it is not above it.

proven_size int

The proven-shared prefix: its entries are proven to be the checkpoint's; 0 when nothing is.

reapplied tuple[JournalErasure, ...]

The journal's erasures applied again by this call.

unproven tuple[JournalErasure, ...]

The journal's erasures whose target is in the chain with payload, outside the proven prefix: not applied again.

head Head | None

The head after the last entry appended; None when nothing was.

RestoreRefusedError

RestoreRefusedError(
    message: str, report: LedgerReport | None = None
)

Bases: CheckpointRefusedError

A restore was not recorded; nothing was written or erased.

The message says why: the checkpoint is unsigned, signed outside a key window or of another chain, the journal is not the one it commits to, the proof does not lead to it, it is not of the chain's history from before the restore, or the journal names another entry than the proven prefix holds. When the function refused it, the transaction is aborted: roll it back.

Source code in audit_trail/ledger/_anchor.py
def __init__(self, message: str, report: LedgerReport | None = None) -> None:
    super().__init__(message)
    self.report = report

LedgerTables dataclass

LedgerTables(
    metadata: MetaData,
    schema: str,
    entry: Table,
    state: Table,
    payload: Table,
    node: Table,
    config: Table,
)

The ledger tables and the metadata they are bound to.

Attributes:

Name Type Description
metadata MetaData

Metadata holding the tables.

schema str

Schema of the tables and of the ledger functions.

entry Table

audit_ledger_entry, one row per entry.

state Table

audit_ledger_state, one row per chain.

payload Table

audit_ledger_payload, one row per entry and payload group.

node Table

audit_ledger_node, the closed subtrees of level 1 and up.

config Table

audit_ledger_config, one row per chain.

ConsistencyProof dataclass

ConsistencyProof(
    chain: str,
    old_size: int,
    new_size: int,
    old_root: bytes,
    new_root: bytes,
    path: tuple[bytes, ...],
)

An RFC 9162 consistency proof between two sizes of a chain's tree.

Check it with verify(old_root, new_root), giving the roots of heads you trust, never self.old_root and self.new_root.

Attributes:

Name Type Description
chain str

The chain.

old_size int

The smaller size.

new_size int

The larger size.

old_root bytes

The root of the tree of old_size, from the stored nodes.

new_root bytes

The root of the tree of new_size, from the stored nodes.

path tuple[bytes, ...]

The proof.

verify

verify(old_root: bytes, new_root: bytes) -> bool

Check that the tree of new_size with root new_root extends the tree of old_size with root old_root, by RFC 9162 section 2.1.4.2.

Parameters:

Name Type Description Default
old_root bytes

The root of a head of old_size you trust.

required
new_root bytes

The root of a head of new_size you trust.

required

Returns:

Type Description
bool

True when the proof holds; never raises, malformed input

bool

gives False.

Source code in audit_trail/ledger/_tree.py
def verify(self, old_root: bytes, new_root: bytes) -> bool:
    """Check that the tree of ``new_size`` with root ``new_root`` extends
    the tree of ``old_size`` with root ``old_root``, by RFC 9162 section
    2.1.4.2.

    Args:
        old_root: The root of a head of ``old_size`` you trust.
        new_root: The root of a head of ``new_size`` you trust.

    Returns:
        ``True`` when the proof holds; never raises, malformed input
        gives ``False``.
    """
    return _merkle.verify_consistency(
        self.old_size, self.new_size, old_root, new_root, list(self.path)
    )

InclusionProof dataclass

InclusionProof(
    chain: str,
    seq: int,
    size: int,
    leaf_hash: bytes,
    root: bytes,
    path: tuple[bytes, ...],
)

An RFC 9162 inclusion proof of one entry in a tree of a chain.

Check it with verify(root), giving the root of a head of size you trust, never self.root.

Attributes:

Name Type Description
chain str

The chain.

seq int

The entry's seq; its leaf index is seq - 1.

size int

The size of the tree.

leaf_hash bytes

The entry's stored leaf hash.

root bytes

The root of the tree of size, from the stored nodes.

path tuple[bytes, ...]

The proof, nearest the leaf first.

verify

verify(root: bytes, leaf_hash: bytes | None = None) -> bool

Check that the entry is in the tree of size whose root is root, by RFC 9162 section 2.1.3.2.

Parameters:

Name Type Description Default
root bytes

The root of a head of size you trust.

required
leaf_hash bytes | None

The entry's leaf hash as you hold it, such as the Head its append returned; self.leaf_hash by default.

None

Returns:

Type Description
bool

True when the proof leads from the leaf to root; never

bool

raises, malformed input gives False.

Source code in audit_trail/ledger/_tree.py
def verify(self, root: bytes, leaf_hash: bytes | None = None) -> bool:
    """Check that the entry is in the tree of ``size`` whose root is
    ``root``, by RFC 9162 section 2.1.3.2.

    Args:
        root: The root of a head of ``size`` you trust.
        leaf_hash: The entry's leaf hash as you hold it, such as the
            ``Head`` its append returned; ``self.leaf_hash`` by default.

    Returns:
        ``True`` when the proof leads from the leaf to ``root``; never
        raises, malformed input gives ``False``.
    """
    leaf = self.leaf_hash if leaf_hash is None else leaf_hash
    return _merkle.verify_inclusion(
        leaf, self.seq - 1, self.size, list(self.path), root
    )

LedgerFailure

Bases: StrEnum

What makes a ledger verification fail; a closed set.

LedgerFinding dataclass

LedgerFinding(
    kind: LedgerFailure | LedgerNote,
    detail: str,
    seq: int | None = None,
    entry_id: UUID | None = None,
    group: str | None = None,
    level: int | None = None,
    index: int | None = None,
    count: int | None = None,
)

One failure or note.

Attributes:

Name Type Description
kind LedgerFailure | LedgerNote

What was found.

detail str

A sentence for people; never a stored value or a salt.

seq int | None

The entry it concerns.

entry_id UUID | None

That entry's id, when it could be read.

group str | None

The payload group.

level int | None

For a node, its level.

index int | None

For a node, its index.

count int | None

How many entries it concerns, where it says.

LedgerHead dataclass

LedgerHead(
    chain: str, incarnation: int, size: int, root: bytes
)

A head of a chain: the tree of its first size entries.

Attributes:

Name Type Description
chain str

The chain.

incarnation int

The chain's incarnation at that size.

size int

The number of entries.

root bytes

The RFC 6962 root of their tree, 32 bytes.

LedgerNote

Bases: StrEnum

What a ledger verification notes without failing.

LedgerReport dataclass

LedgerReport(
    status: Status,
    chain: str,
    head: LedgerHead,
    failures: list[LedgerFinding],
    notes: list[LedgerFinding],
    since: int | None = None,
    entries: int = 0,
    anchor: Anchor | None = None,
)

What verify found.

Attributes:

Name Type Description
status Status

FAILED with any failure, else VALID_WITH_NOTES with any note, else VALID.

chain str

The chain.

head LedgerHead

The head verified up to: the state row as read at the start of the run. Keep the report to pass it to verify(since=...).

failures list[LedgerFinding]

Every failure, in the order found.

notes list[LedgerFinding]

Every note.

since int | None

The size of the earlier report's head when this run checked only the entries after it (verify(since=...)); None for a full run.

entries int

How many entries this run read.

anchor Anchor | None

ANCHORED when a trusted checkpoint given (or, in a bundle, found) matched a head of the entries, else UNANCHORED.

verified_to property

verified_to: int

The seq of the last entry verified: the head's size.

kinds

kinds() -> set[LedgerFailure | LedgerNote]

The kinds of every failure and note.

Source code in audit_trail/ledger/_verify.py
def kinds(self) -> set[LedgerFailure | LedgerNote]:
    """The kinds of every failure and note."""
    return {finding.kind for finding in (*self.failures, *self.notes)}

aerasure_journal async

aerasure_journal(
    conn: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    size: int | None = None,
) -> LedgerJournal

Async erasure_journal, on an AsyncConnection; the same arguments.

Source code in audit_trail/ledger/_anchor.py
@explains_permissions
async def aerasure_journal(
    conn: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    size: int | None = None,
) -> LedgerJournal:
    """Async ``erasure_journal``, on an ``AsyncConnection``; the same arguments."""
    return await conn.run_sync(
        lambda sync_conn: erasure_journal(sync_conn, tables, chain, size)
    )

aprepare_checkpoint async

aprepare_checkpoint(
    conn: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    *,
    origin: str,
    verify: Mapping[str, Any] | None = None,
    verified: LedgerReport | None = None,
    journal: bool = False,
    extensions: Iterable[str] = (),
    since_size: int | None = None,
) -> PreparedCheckpoint

Async prepare_checkpoint, on an AsyncConnection; the same arguments.

Source code in audit_trail/ledger/_anchor.py
@explains_permissions
async def aprepare_checkpoint(
    conn: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    *,
    origin: str,
    verify: Mapping[str, Any] | None = None,
    verified: LedgerReport | None = None,
    journal: bool = False,
    extensions: Iterable[str] = (),
    since_size: int | None = None,
) -> PreparedCheckpoint:
    """Async ``prepare_checkpoint``, on an ``AsyncConnection``; the same arguments."""
    return await conn.run_sync(
        lambda sync_conn: prepare_checkpoint(
            sync_conn,
            tables,
            chain,
            origin=origin,
            verify=verify,
            verified=verified,
            journal=journal,
            extensions=extensions,
            since_size=since_size,
        )
    )

arecord_checkpoint async

arecord_checkpoint(
    conn: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    signed_note: LedgerCheckpoint | str,
    *,
    verifier: SignatureVerifier,
    key_history: KeyHistory,
    actor: str | None = None,
    lock_timeout: str | None = None,
    since_size: int | None = None,
) -> RecordedCheckpoint

Async record_checkpoint, on an AsyncConnection; the same arguments.

Source code in audit_trail/ledger/_anchor.py
@explains_permissions
async def arecord_checkpoint(
    conn: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    signed_note: LedgerCheckpoint | str,
    *,
    verifier: SignatureVerifier,
    key_history: KeyHistory,
    actor: str | None = None,
    lock_timeout: str | None = None,
    since_size: int | None = None,
) -> RecordedCheckpoint:
    """Async ``record_checkpoint``, on an ``AsyncConnection``; the same arguments."""
    return await conn.run_sync(
        lambda sync_conn: record_checkpoint(
            sync_conn,
            tables,
            chain,
            signed_note,
            verifier=verifier,
            key_history=key_history,
            actor=actor,
            lock_timeout=lock_timeout,
            since_size=since_size,
        )
    )

erasure_journal

erasure_journal(
    conn: Connection,
    tables: LedgerTables,
    chain: str,
    size: int | None = None,
) -> LedgerJournal

The erasure journal of a chain at size.

The same journal prepare_checkpoint(..., journal=True) commits to: every ledger.erased receipt with a seq up to size. Use it to get the journal of a checkpoint again, before a restore. It reads in short READ ONLY transactions, or in the connection's when it has one.

Parameters:

Name Type Description Default
conn Connection

The connection; a role that can read the ledger tables.

required
tables LedgerTables

The ledger tables.

required
chain str

The chain.

required
size int | None

The checkpoint's size; the chain's current size by default.

None

Returns:

Type Description
LedgerJournal

The journal.

Raises:

Type Description
ValueError

There is no such chain, or size is negative or above the chain's size.

TypeError

size is not an int.

Source code in audit_trail/ledger/_anchor.py
@explains_permissions
def erasure_journal(
    conn: Connection, tables: LedgerTables, chain: str, size: int | None = None
) -> LedgerJournal:
    """The erasure journal of a chain at ``size``.

    The same journal ``prepare_checkpoint(..., journal=True)`` commits to:
    every ``ledger.erased`` receipt with a ``seq`` up to ``size``. Use it to
    get the journal of a checkpoint again, before a restore. It reads in
    short ``READ ONLY`` transactions, or in the connection's when it has
    one.

    Args:
        conn: The connection; a role that can read the ledger tables.
        tables: The ledger tables.
        chain: The chain.
        size: The checkpoint's size; the chain's current size by default.

    Returns:
        The journal.

    Raises:
        ValueError: There is no such chain, or ``size`` is negative or above
            the chain's size.
        TypeError: ``size`` is not an int.
    """
    _schema.check_chain(chain)
    own = not conn.in_transaction()
    with reading(conn, own):
        current = read_state(conn, tables, chain).size
    if size is None:
        size = current
    if not is_int(size):
        raise TypeError("size must be an int")
    if not 0 <= size <= current:
        raise ValueError(f"size {size} is not in [0, {current}]")
    return read_journal(conn, tables, chain, size, own=own)

prepare_checkpoint

prepare_checkpoint(
    conn: Connection,
    tables: LedgerTables,
    chain: str,
    *,
    origin: str,
    verify: Mapping[str, Any] | None = None,
    verified: LedgerReport | None = None,
    journal: bool = False,
    extensions: Iterable[str] = (),
    since_size: int | None = None,
) -> PreparedCheckpoint

The unsigned checkpoint of a head of the chain that verified.

The first half of a checkpoint whose signer takes its time: sign the result, then give the note to record_checkpoint. Only committed data is read, in short READ ONLY transactions; nothing is written, no lock is taken, and the connection is left with no transaction open.

Give exactly one of:

  • verify: run verify now, with these keyword arguments of it ({} for none), and prepare for the head it verified;
  • verified: the report of an earlier verify, such as a long run the host stored. It must have no failures, and its head must still be a head of the chain: the stored frontier of its size must give its root, and a consistency proof from the stored nodes must lead from it to the current root. The checkpoint is for that head, not a newer one; verify(since=report) brings a report up to date quickly.

Either way the head must be in the chain's current incarnation: a head from before an incarnation started is refused.

Parameters:

Name Type Description Default
conn Connection

A connection that can read the ledger tables, not in a transaction.

required
tables LedgerTables

The ledger tables.

required
chain str

The chain.

required
origin str

The host origin, a schema-less URL such as audit.example.org/ledger: 1 to 200 printable ASCII characters without space or +, not ending in /. The checkpoint's origin is <origin>/<chain>/i<incarnation>.

required
verify Mapping[str, Any] | None

Keyword arguments for verify: since, chunk_rows, verifier and key_history.

None
verified LedgerReport | None

The report of an earlier verify of this chain.

None
journal bool

Commit to the erasure journal at the head's size: every ledger.erased receipt up to it (LedgerJournal). It is returned with the checkpoint; keep it with the signed note.

False
extensions Iterable[str]

The host's lines after the statement, signed with it, as integrity's checkpoints take them.

()
since_size int | None

The size the returned consistency proof starts from, in [1, size); by default the size of the newest checkpoint recorded at or below the head's size, and no proof when there is none.

None

Returns:

Name Type Description
PreparedCheckpoint

The unsigned checkpoint, the journal, the report and the proof.

PreparedCheckpoint

Sign the checkpoint, then keep kit(note).to_json() off the

database PreparedCheckpoint

see "What to keep off the database" in

PreparedCheckpoint

audit_trail.ledger._anchor.

Raises:

Type Description
CheckpointRefusedError

The verification has failures, or its head is not a head of the chain as it is now, or is from before an incarnation started (report holds the report).

ValueError

Both or neither of verify and verified, an unknown verify argument, an invalid origin or extension line, a report of another chain, a connection in a transaction, or as verify.

Source code in audit_trail/ledger/_anchor.py
@explains_permissions
def prepare_checkpoint(
    conn: Connection,
    tables: LedgerTables,
    chain: str,
    *,
    origin: str,
    verify: Mapping[str, Any] | None = None,
    verified: LedgerReport | None = None,
    journal: bool = False,
    extensions: Iterable[str] = (),
    since_size: int | None = None,
) -> PreparedCheckpoint:
    """The unsigned checkpoint of a head of the chain that verified.

    The first half of a checkpoint whose signer takes its time: sign the
    result, then give the note to ``record_checkpoint``. Only committed data
    is read, in short ``READ ONLY`` transactions; nothing is written, no
    lock is taken, and the connection is left with no transaction open.

    Give exactly one of:

    - ``verify``: run ``verify`` now, with these keyword arguments of it
      (``{}`` for none), and prepare for the head it verified;
    - ``verified``: the report of an earlier ``verify``, such as a long run
      the host stored. It must have no failures, and its head must still be
      a head of the chain: the stored frontier of its size must give its
      root, and a consistency proof from the stored nodes must lead from it
      to the current root. The checkpoint is for that head, not a newer
      one; ``verify(since=report)`` brings a report up to date quickly.

    Either way the head must be in the chain's current incarnation: a head
    from before an incarnation started is refused.

    Args:
        conn: A connection that can read the ledger tables, not in a
            transaction.
        tables: The ledger tables.
        chain: The chain.
        origin: The host origin, a schema-less URL such as
            ``audit.example.org/ledger``: 1 to 200 printable ASCII
            characters without space or ``+``, not ending in ``/``. The
            checkpoint's origin is ``<origin>/<chain>/i<incarnation>``.
        verify: Keyword arguments for ``verify``: ``since``, ``chunk_rows``,
            ``verifier`` and ``key_history``.
        verified: The report of an earlier ``verify`` of this chain.
        journal: Commit to the erasure journal at the head's size: every
            ``ledger.erased`` receipt up to it (``LedgerJournal``). It is
            returned with the checkpoint; keep it with the signed note.
        extensions: The host's lines after the statement, signed with it,
            as integrity's checkpoints take them.
        since_size: The size the returned consistency proof starts from, in
            ``[1, size)``; by default the size of the newest checkpoint
            recorded at or below the head's size, and no proof when there
            is none.

    Returns:
        The unsigned checkpoint, the journal, the report and the proof.
        Sign the checkpoint, then keep ``kit(note).to_json()`` off the
        database: see "What to keep off the database" in
        ``audit_trail.ledger._anchor``.

    Raises:
        CheckpointRefusedError: The verification has failures, or its head
            is not a head of the chain as it is now, or is from before an
            incarnation started (``report`` holds the report).
        ValueError: Both or neither of ``verify`` and ``verified``, an
            unknown ``verify`` argument, an invalid origin or extension
            line, a report of another chain, a connection in a transaction,
            or as ``verify``.
    """
    _schema.check_chain(chain)
    check_host_origin(origin)
    lines = check_extensions(extensions)
    if not isinstance(journal, bool):
        raise TypeError("journal must be a bool")
    _check_since(since_size)
    if (verify is None) == (verified is None):
        raise ValueError("give either verify or verified")
    check_idle(conn, "prepare_checkpoint")
    if verify is not None:
        allowed = inspect.signature(_verify_options).parameters
        unknown = sorted(set(verify) - set(allowed))
        if unknown:
            raise ValueError(f"verify takes no argument {', '.join(unknown)}")
        report = verify_chain(conn, tables, chain, **_verify_options(**verify))
    else:
        if not isinstance(verified, LedgerReport):
            raise ValueError("verified is a LedgerReport")
        report = verified
    if report.chain != chain:
        raise ValueError(f"the report is of chain {report.chain!r}, not {chain!r}")
    if report.failures:
        kinds = ", ".join(sorted({str(f.kind) for f in report.failures}))
        raise CheckpointRefusedError(
            f"the verification has {len(report.failures)} failures ({kinds})", report
        )
    head = report.head
    if head.size < 1:  # pragma: no cover - a chain starts with one entry
        raise CheckpointRefusedError("the report's head is empty", report)
    with _pg.read_only(conn):
        state = read_state(conn, tables, chain)
        found = head_mismatch(conn, tables, chain, state, head, False)
        if isinstance(found, LedgerFinding):
            raise CheckpointRefusedError(
                f"the report's head (size {head.size}) is not a head of the chain "
                "as it is now",
                report,
            )
        if state.incarnation != head.incarnation:
            raise CheckpointRefusedError(
                _before_incarnation(head, state.incarnation), report
            )
        built = (
            read_journal(conn, tables, chain, head.size, own=False) if journal else None
        )
        proof = restore_proof(conn, tables, chain, head.size, since_size)
    checkpoint = LedgerCheckpoint(
        checkpoint_origin(origin, chain, head.incarnation),
        head.size,
        head.root,
        journal=None if built is None else built.commitment,
        extensions=lines,
    )
    return PreparedCheckpoint(checkpoint, built, report, proof)

record_checkpoint

record_checkpoint(
    conn: Connection,
    tables: LedgerTables,
    chain: str,
    signed_note: LedgerCheckpoint | str,
    *,
    verifier: SignatureVerifier,
    key_history: KeyHistory,
    actor: str | None = None,
    lock_timeout: str | None = None,
    since_size: int | None = None,
) -> RecordedCheckpoint

Append a signed checkpoint to its chain as ledger.checkpoint, once.

The second half of prepare_checkpoint. Before it writes, it checks:

  • the note reads as a ledger checkpoint, and is signed;
  • every signature of a key verifier knows verifies, at least one does, and each of those keys is valid at the checkpoint's size in key_history (windows are in chain seq);
  • the origin names this chain;
  • a journal line states the commitment of the journal of the chain's receipts up to the size.

Then audit_ledger_record_checkpoint, a SECURITY DEFINER function, takes the chain's lock (after restore detection, as an append does) and checks again what it can in SQL: that the size is at most the chain's, that the origin's incarnation is the chain's and the entry at the size is in it (a head from before an incarnation started is refused), and that the root is the root of the tree of that size, from the stored nodes. It appends the entry, whose attributes are {"note": <the note>}.

The same note, byte for byte, recorded again returns the entry holding it and appends nothing, also when two transactions record it at once: the second waits for the chain's lock and then finds the first's entry. The same head with other signatures (a cosignature added) is another note, and another entry.

Runs in the connection's current transaction, under the chain's lock, as append_many does; the caller commits. The application role may call it (ledger_grant_statements).

Parameters:

Name Type Description Default
conn Connection

Connection to run on.

required
tables LedgerTables

The ledger tables.

required
chain str

The chain.

required
signed_note LedgerCheckpoint | str

The signed checkpoint, or its note text.

required
verifier SignatureVerifier

Checks the note's signatures.

required
key_history KeyHistory

The window of each key, by chain seq.

required
actor str | None

The actor of the entry.

None
lock_timeout str | None

The lock_timeout for the call; None keeps the transaction's.

None
since_size int | None

As prepare_checkpoint's: where the returned proof starts.

None

Returns:

Type Description
RecordedCheckpoint

The entry holding the note, whether this call appended it, the

RecordedCheckpoint

journal and the consistency proof from the checkpoint before. Keep

RecordedCheckpoint

kit.to_json() off the database.

Raises:

Type Description
NoteError

The note is not a ledger checkpoint (MALFORMED), a signature does not verify (BAD_SIGNATURE), or none is of a key the verifier knows (UNKNOWN_KEY).

CheckpointRefusedError

The note is unsigned, a key is outside its window, the origin names another chain or incarnation, the head is above the chain's size, from before an incarnation started or has another root, or the journal does not match (the transaction is then aborted when the function refused it).

LedgerBusyError

The lock was not granted within lock_timeout.

ValueError

The chain name is refused, the connection is in AUTOCOMMIT, or there is no such chain.

Source code in audit_trail/ledger/_anchor.py
@explains_permissions
def record_checkpoint(
    conn: Connection,
    tables: LedgerTables,
    chain: str,
    signed_note: LedgerCheckpoint | str,
    *,
    verifier: SignatureVerifier,
    key_history: KeyHistory,
    actor: str | None = None,
    lock_timeout: str | None = None,
    since_size: int | None = None,
) -> RecordedCheckpoint:
    """Append a signed checkpoint to its chain as ``ledger.checkpoint``, once.

    The second half of ``prepare_checkpoint``. Before it writes, it checks:

    - the note reads as a ledger checkpoint, and is signed;
    - every signature of a key ``verifier`` knows verifies, at least one
      does, and each of those keys is valid at the checkpoint's size in
      ``key_history`` (windows are in chain ``seq``);
    - the origin names this chain;
    - a journal line states the commitment of the journal of the chain's
      receipts up to the size.

    Then ``audit_ledger_record_checkpoint``, a ``SECURITY DEFINER``
    function, takes the chain's lock (after restore detection, as an append
    does) and checks again what it can in SQL: that the size is at most the
    chain's, that the origin's incarnation is the chain's and the entry at
    the size is in it (a head from before an incarnation started is
    refused), and that the root is the root of the tree of that size, from
    the stored nodes. It appends the entry, whose ``attributes`` are
    ``{"note": <the note>}``.

    The same note, byte for byte, recorded again returns the entry holding
    it and appends nothing, also when two transactions record it at once:
    the second waits for the chain's lock and then finds the first's entry.
    The same head with other signatures (a cosignature added) is another
    note, and another entry.

    Runs in the connection's current transaction, under the chain's lock,
    as ``append_many`` does; the caller commits. The application role may
    call it (``ledger_grant_statements``).

    Args:
        conn: Connection to run on.
        tables: The ledger tables.
        chain: The chain.
        signed_note: The signed checkpoint, or its note text.
        verifier: Checks the note's signatures.
        key_history: The window of each key, by chain ``seq``.
        actor: The ``actor`` of the entry.
        lock_timeout: The ``lock_timeout`` for the call; ``None`` keeps the
            transaction's.
        since_size: As ``prepare_checkpoint``'s: where the returned proof
            starts.

    Returns:
        The entry holding the note, whether this call appended it, the
        journal and the consistency proof from the checkpoint before. Keep
        ``kit.to_json()`` off the database.

    Raises:
        NoteError: The note is not a ledger checkpoint (``MALFORMED``), a
            signature does not verify (``BAD_SIGNATURE``), or none is of a
            key the verifier knows (``UNKNOWN_KEY``).
        CheckpointRefusedError: The note is unsigned, a key is outside its
            window, the origin names another chain or incarnation, the head
            is above the chain's size, from before an incarnation started
            or has another root, or the journal does not match (the
            transaction is then aborted when the function refused it).
        LedgerBusyError: The lock was not granted within ``lock_timeout``.
        ValueError: The chain name is refused, the connection is in
            ``AUTOCOMMIT``, or there is no such chain.
    """
    _schema.check_chain(chain)
    _check_since(since_size)
    checkpoint = trusted_checkpoint(signed_note, chain, verifier, key_history)
    _pg.check_transactional(conn, "record_checkpoint")
    note = checkpoint.to_note()
    built: LedgerJournal | None = None
    if checkpoint.journal is not None:
        current = read_state(conn, tables, chain).size
        if checkpoint.size <= current:
            built = read_journal(conn, tables, chain, checkpoint.size, own=False)
            if not hmac.compare_digest(built.commitment, checkpoint.journal):
                raise CheckpointRefusedError(
                    "the checkpoint's journal line does not commit to the chain's "
                    f"receipts up to size {checkpoint.size}"
                )
    body = _entry.encode_entry(
        Entry(_entry.CHECKPOINT, attributes={"note": note}, actor=actor),
        package=True,
    ).body
    function = _migrations.function_name(tables, _schema.RECORD_CHECKPOINT_FUNCTION)
    statement = text(
        "SELECT incarnation, seq, leaf_hash, size, root, created FROM "
        f"{function}(CAST(:chain AS text), CAST(:body AS bytea))"
    )
    with _lock_timeout(conn, lock_timeout):
        try:
            row = conn.execute(statement, {"chain": chain, "body": body}).one()
        except DBAPIError as exc:
            if _pg.is_sqlstate(exc, _pg.LOCK_NOT_AVAILABLE):
                raise LedgerBusyError(
                    f"ledger chain {chain!r} is busy: its lock was not granted "
                    "within lock_timeout"
                ) from exc
            if _pg.is_sqlstate(exc, _NO_DATA_FOUND):
                raise ValueError(f"there is no ledger chain named {chain!r}") from exc
            if _pg.is_sqlstate(exc, _pg.OBJECT_NOT_IN_PREREQUISITE_STATE):
                raise CheckpointRefusedError(_message(exc)) from exc
            raise
    created = bool(row.created)
    return RecordedCheckpoint(
        seq=int(row.seq),
        incarnation=int(row.incarnation),
        leaf_hash=bytes(row.leaf_hash),
        checkpoint=checkpoint,
        created=created,
        head=_head(tuple(row)[:5]) if created else None,
        journal=built,
        proof=restore_proof(conn, tables, chain, checkpoint.size, since_size),
    )

aappend async

aappend(
    connection: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    entry: Entry,
    *,
    lock_timeout: str | None = None,
) -> Head

Async append, on an AsyncConnection; the same arguments.

Source code in audit_trail/ledger/_append.py
@explains_permissions
async def aappend(
    connection: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    entry: Entry,
    *,
    lock_timeout: str | None = None,
) -> Head:
    """Async ``append``, on an ``AsyncConnection``; the same arguments."""
    return await connection.run_sync(
        lambda sync_conn: append(
            sync_conn, tables, chain, entry, lock_timeout=lock_timeout
        )
    )

aappend_many async

aappend_many(
    connection: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    entries: Sequence[Entry],
    *,
    lock_timeout: str | None = None,
) -> list[Head]

Async append_many, on an AsyncConnection; the same arguments.

Source code in audit_trail/ledger/_append.py
@explains_permissions
async def aappend_many(
    connection: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    entries: Sequence[Entry],
    *,
    lock_timeout: str | None = None,
) -> list[Head]:
    """Async ``append_many``, on an ``AsyncConnection``; the same arguments."""
    if not entries:
        _schema.check_chain(chain)
        return []
    return await connection.run_sync(
        lambda sync_conn: append_many(
            sync_conn, tables, chain, entries, lock_timeout=lock_timeout
        )
    )

acreate_chain async

acreate_chain(
    connection: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    config: ChainConfig | None = None,
    *,
    actor: str | None = None,
) -> Head

Async create_chain, on an AsyncConnection; the same arguments.

Source code in audit_trail/ledger/_append.py
@explains_permissions
async def acreate_chain(
    connection: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    config: ChainConfig | None = None,
    *,
    actor: str | None = None,
) -> Head:
    """Async ``create_chain``, on an ``AsyncConnection``; the same arguments."""
    return await connection.run_sync(
        lambda sync_conn: create_chain(sync_conn, tables, chain, config, actor=actor)
    )

append

append(
    connection: Connection,
    tables: LedgerTables,
    chain: str,
    entry: Entry,
    *,
    lock_timeout: str | None = None,
) -> Head

Append one entry to a chain, in the connection's current transaction.

See append_many.

Returns:

Type Description
Head

The head after the entry.

Source code in audit_trail/ledger/_append.py
@explains_permissions
def append(
    connection: Connection,
    tables: LedgerTables,
    chain: str,
    entry: Entry,
    *,
    lock_timeout: str | None = None,
) -> Head:
    """Append one entry to a chain, in the connection's current transaction.

    See ``append_many``.

    Returns:
        The head after the entry.
    """
    return append_many(connection, tables, chain, [entry], lock_timeout=lock_timeout)[0]

append_many

append_many(
    connection: Connection,
    tables: LedgerTables,
    chain: str,
    entries: Sequence[Entry],
    *,
    lock_timeout: str | None = None,
) -> list[Head]

Append entries to a chain in one call, under one lock.

Each entry is checked and its body encoded, with fresh salts for its payload groups, before the database is called. audit_ledger_append then locks the chain's state row, gives the entries consecutive seq numbers in order, reads clock_timestamp() once as their append time, computes their leaves and the new roots, and stores the entries, their payloads and the subtree nodes they close.

With the chain's detect_restores on, the function first compares the stored cluster identity with the observed one, under the lock, and when the database was restored starts a new incarnation: it appends ledger.incarnation_started before the entries, which then go into the new incarnation (ledger.cluster_changed after a pg_upgrade). That entry gets no head here; the heads returned are the entries'. See "Restore detection" in audit_trail.ledger._migrations for the rules.

The lock is held until the transaction ends, so append last, just before commit. The heads are provisional until then: a rollback frees their numbers. An empty entries touches nothing and takes no lock.

lock_timeout bounds each lock wait, not the total: the call can wait for the row's lock, then for the transaction of each writer that held it before. Set statement_timeout to bound the whole call. The lock is not fair, so under many writers on one chain the slowest appends wait far longer than the median; spread writers over chains.

Append under READ COMMITTED. Under REPEATABLE READ or SERIALIZABLE, a transaction that waited for the lock while another appended to the chain fails with a serialization failure (SQLSTATE 40001) once the other commits; roll back and retry it. The connection must not be in AUTOCOMMIT: the lock and lock_timeout would then last only for the call.

Parameters:

Name Type Description Default
connection Connection

Connection to run on; the caller commits.

required
tables LedgerTables

The ledger tables.

required
chain str

The chain's name.

required
entries Sequence[Entry]

The entries, in order, at most MAX_BATCH. Their types may not start with ledger..

required
lock_timeout str | None

The lock_timeout for the call, such as "2s"; None keeps the transaction's. It bounds each lock wait, not the whole call.

None

Returns:

Type Description
list[Head]

One head per entry, in order.

Raises:

Type Description
LedgerBusyError

The lock was not granted within lock_timeout.

ValueError

An entry or the chain name is refused, there are more than MAX_BATCH entries, the connection is in AUTOCOMMIT, or there is no such chain (the transaction is then aborted).

TypeError

An entry field has the wrong type.

Source code in audit_trail/ledger/_append.py
@explains_permissions
def append_many(
    connection: Connection,
    tables: LedgerTables,
    chain: str,
    entries: Sequence[Entry],
    *,
    lock_timeout: str | None = None,
) -> list[Head]:
    """Append entries to a chain in one call, under one lock.

    Each entry is checked and its body encoded, with fresh salts for its
    payload groups, before the database is called. ``audit_ledger_append``
    then locks the chain's state row, gives the entries consecutive ``seq`` numbers in
    order, reads ``clock_timestamp()`` once as their append time, computes
    their leaves and the new roots, and stores the entries, their payloads
    and the subtree nodes they close.

    With the chain's ``detect_restores`` on, the function first compares
    the stored cluster identity with the observed one, under the lock, and
    when the database was restored starts a new incarnation: it appends
    ``ledger.incarnation_started`` before the entries, which then go into
    the new incarnation (``ledger.cluster_changed`` after a ``pg_upgrade``).
    That entry gets no head here; the heads returned are the entries'. See
    "Restore detection" in ``audit_trail.ledger._migrations`` for the rules.

    The lock is held until the transaction ends, so append last, just before
    commit. The heads are provisional until then: a rollback frees their
    numbers. An empty ``entries`` touches nothing and takes no lock.

    ``lock_timeout`` bounds each lock wait, not the total: the call can
    wait for the row's lock, then for the transaction of each writer that
    held it before. Set ``statement_timeout`` to bound the whole call. The
    lock is not fair, so under many writers on one chain the slowest
    appends wait far longer than the median; spread writers over chains.

    Append under ``READ COMMITTED``. Under ``REPEATABLE READ`` or
    ``SERIALIZABLE``, a transaction that waited for the lock while another
    appended to the chain fails with a serialization failure (SQLSTATE
    ``40001``) once the other commits; roll back and retry it. The
    connection must not be in ``AUTOCOMMIT``: the lock and ``lock_timeout``
    would then last only for the call.

    Args:
        connection: Connection to run on; the caller commits.
        tables: The ledger tables.
        chain: The chain's name.
        entries: The entries, in order, at most ``MAX_BATCH``. Their types
            may not start with ``ledger.``.
        lock_timeout: The ``lock_timeout`` for the call, such as ``"2s"``;
            ``None`` keeps the transaction's. It bounds each lock wait, not
            the whole call.

    Returns:
        One head per entry, in order.

    Raises:
        LedgerBusyError: The lock was not granted within ``lock_timeout``.
        ValueError: An entry or the chain name is refused, there are more
            than ``MAX_BATCH`` entries, the connection is in ``AUTOCOMMIT``,
            or there is no such chain (the transaction is then aborted).
        TypeError: An entry field has the wrong type.
    """
    _schema.check_chain(chain)
    if not entries:
        return []
    if len(entries) > _schema.MAX_BATCH:
        raise ValueError(
            f"append_many takes at most {_schema.MAX_BATCH} entries in one call"
        )
    _pg.check_transactional(connection, "append_many")
    encoded = [_entry.encode_entry(entry) for entry in entries]
    payload = [
        (index, row)
        for index, item in enumerate(encoded, start=1)
        for row in item.payload
    ]
    function = _migrations.function_name(tables, _schema.APPEND_FUNCTION)
    statement = text(
        "SELECT incarnation, seq, leaf_hash, size, root FROM "
        f"{function}(CAST(:chain AS text), CAST(:bodies AS bytea[]), "
        "CAST(:entries AS integer[]), CAST(:groups AS text[]), "
        "CAST(:salts AS bytea[]), CAST(:values AS bytea[]))"
    )
    parameters = {
        "chain": chain,
        "bodies": [item.body for item in encoded],
        "entries": [index for index, _row in payload],
        "groups": [row.group for _index, row in payload],
        "salts": [row.salt for _index, row in payload],
        "values": [row.value for _index, row in payload],
    }
    with _lock_timeout(connection, lock_timeout):
        rows = _call(connection, chain, statement, parameters)
    return [_head(row) for row in rows]

arecord_maintenance async

arecord_maintenance(
    connection: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    reason: str,
    *,
    actor: str | None = None,
    lock_timeout: str | None = None,
) -> Head

Async record_maintenance, on an AsyncConnection; the same arguments.

Source code in audit_trail/ledger/_append.py
@explains_permissions
async def arecord_maintenance(
    connection: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    reason: str,
    *,
    actor: str | None = None,
    lock_timeout: str | None = None,
) -> Head:
    """Async ``record_maintenance``, on an ``AsyncConnection``; the same arguments."""
    return await connection.run_sync(
        lambda sync_conn: record_maintenance(
            sync_conn, tables, chain, reason, actor=actor, lock_timeout=lock_timeout
        )
    )

create_chain

create_chain(
    connection: Connection,
    tables: LedgerTables,
    chain: str,
    config: ChainConfig | None = None,
    *,
    actor: str | None = None,
) -> Head

Create a chain, with ledger.chain_started as its first entry.

The entry's attributes hold the whole config, which is also stored in audit_ledger_config, so the chain never runs under a config it has not recorded. With config.detect_restores on (the default) the state row stores the cluster identity: the system identifier, the WAL timeline from pg_walfile_name(pg_current_wal_lsn()), the state table's OID and the server's major version.

Runs in the connection's current transaction; the caller commits. It calls audit_ledger_create_chain, which by default only the owner of the ledger functions may execute.

Parameters:

Name Type Description Default
connection Connection

Connection to run on.

required
tables LedgerTables

The ledger tables.

required
chain str

The new chain's name, matching CHAIN_PATTERN.

required
config ChainConfig | None

The chain's config; ChainConfig() by default.

None
actor str | None

The actor of the first entry.

None

Returns:

Type Description
Head

The head after the first entry: seq and size 1.

Raises:

Type Description
ValueError

The name is refused, the connection is in AUTOCOMMIT, or a chain of that name exists (the transaction is then aborted). Two transactions creating the same name: the second waits for the first and gets this error if it commits.

DBAPIError

The database refused it, for example because the identity functions cannot be called with detection on, or the config names a precondition function that exists and does not set a search_path ending in pg_temp (see erase).

Source code in audit_trail/ledger/_append.py
@explains_permissions
def create_chain(
    connection: Connection,
    tables: LedgerTables,
    chain: str,
    config: ChainConfig | None = None,
    *,
    actor: str | None = None,
) -> Head:
    """Create a chain, with ``ledger.chain_started`` as its first entry.

    The entry's ``attributes`` hold the whole config, which is also stored in
    ``audit_ledger_config``, so the chain never runs under a config it has
    not recorded. With ``config.detect_restores`` on (the default) the state
    row stores the cluster identity: the system identifier, the WAL timeline
    from ``pg_walfile_name(pg_current_wal_lsn())``, the state table's OID
    and the server's major version.

    Runs in the connection's current transaction; the caller commits. It
    calls ``audit_ledger_create_chain``, which by default only the owner of
    the ledger functions may execute.

    Args:
        connection: Connection to run on.
        tables: The ledger tables.
        chain: The new chain's name, matching ``CHAIN_PATTERN``.
        config: The chain's config; ``ChainConfig()`` by default.
        actor: The ``actor`` of the first entry.

    Returns:
        The head after the first entry: ``seq`` and ``size`` 1.

    Raises:
        ValueError: The name is refused, the connection is in
            ``AUTOCOMMIT``, or a chain of that name exists (the transaction
            is then aborted). Two transactions creating the same name: the
            second waits for the first and gets this error if it commits.
        DBAPIError: The database refused it, for example because the
            identity functions cannot be called with detection on, or the
            config names a precondition function that exists and does not
            set a ``search_path`` ending in ``pg_temp`` (see ``erase``).
    """
    _schema.check_chain(chain)
    _pg.check_transactional(connection, "create_chain")
    if config is None:
        config = ChainConfig()
    encoded = _entry.encode_entry(
        Entry(_entry.CHAIN_STARTED, attributes=config.as_dict(), actor=actor),
        package=True,
    )
    function = _migrations.function_name(tables, _schema.CREATE_CHAIN_FUNCTION)
    statement = text(
        "SELECT incarnation, seq, leaf_hash, size, root FROM "
        f"{function}(CAST(:chain AS text), CAST(CAST(:config AS text) AS jsonb), "
        "CAST(:body AS bytea))"
    )
    try:
        row = connection.execute(
            statement,
            {
                "chain": chain,
                "config": _entry.config_json(config),
                "body": encoded.body,
            },
        ).one()
    except DBAPIError as exc:
        if _pg.is_sqlstate(exc, _DUPLICATE_OBJECT):
            raise ValueError(
                f"there is a ledger chain named {chain!r} already"
            ) from exc
        raise
    return _head(row)

record_maintenance

record_maintenance(
    connection: Connection,
    tables: LedgerTables,
    chain: str,
    reason: str,
    *,
    actor: str | None = None,
    lock_timeout: str | None = None,
) -> Head

Append ledger.maintenance, explaining the chain's incarnation.

A restore the append function detects starts a new incarnation with a ledger.incarnation_started entry. Planned work can look the same from inside the database: a dump-and-restore upgrade, a switchover. After it, record the reason, so that a verifier can tell it from an unexplained incarnation. The entry's attributes are {"incarnation": n, "reason": reason}: n is the chain's incarnation after the append's own restore detection, so a restore detected by this call is the one it explains.

Runs in the connection's current transaction, under the chain's lock, as append_many does; the caller commits. It calls audit_ledger_record_maintenance, which by default only the owner of the ledger functions may execute.

Parameters:

Name Type Description Default
connection Connection

Connection to run on.

required
tables LedgerTables

The ledger tables.

required
chain str

The chain's name.

required
reason str

The host's reason code (REASON_CODE_PATTERN, not starting with ledger.); no free text.

required
actor str | None

The actor of the entry, at most MAX_ACTOR_LENGTH characters.

None
lock_timeout str | None

The lock_timeout for the call; None keeps the transaction's. It bounds each lock wait, not the whole call.

None

Returns:

Type Description
Head

The head after the entry.

Raises:

Type Description
LedgerBusyError

The lock was not granted within lock_timeout.

ValueError

The chain name, the reason code or the actor is refused, the connection is in AUTOCOMMIT, or there is no such chain (the transaction is then aborted).

TypeError

actor is not a str or None.

Source code in audit_trail/ledger/_append.py
@explains_permissions
def record_maintenance(
    connection: Connection,
    tables: LedgerTables,
    chain: str,
    reason: str,
    *,
    actor: str | None = None,
    lock_timeout: str | None = None,
) -> Head:
    """Append ``ledger.maintenance``, explaining the chain's incarnation.

    A restore the append function detects starts a new incarnation with a
    ``ledger.incarnation_started`` entry. Planned work can look the same
    from inside the database: a dump-and-restore upgrade, a switchover. After
    it, record the reason, so that a verifier can tell it from an
    unexplained incarnation. The entry's attributes are ``{"incarnation":
    n, "reason": reason}``: ``n`` is the chain's incarnation after the
    append's own restore detection, so a restore detected by this call is
    the one it explains.

    Runs in the connection's current transaction, under the chain's lock,
    as ``append_many`` does; the caller commits. It calls
    ``audit_ledger_record_maintenance``, which by default only the owner of
    the ledger functions may execute.

    Args:
        connection: Connection to run on.
        tables: The ledger tables.
        chain: The chain's name.
        reason: The host's reason code (``REASON_CODE_PATTERN``, not
            starting with ``ledger.``); no free text.
        actor: The ``actor`` of the entry, at most ``MAX_ACTOR_LENGTH``
            characters.
        lock_timeout: The ``lock_timeout`` for the call; ``None`` keeps the
            transaction's. It bounds each lock wait, not the whole call.

    Returns:
        The head after the entry.

    Raises:
        LedgerBusyError: The lock was not granted within ``lock_timeout``.
        ValueError: The chain name, the reason code or the actor is
            refused, the connection is in ``AUTOCOMMIT``, or there is no such chain (the
            transaction is then aborted).
        TypeError: ``actor`` is not a ``str`` or ``None``.
    """
    _schema.check_chain(chain)
    _schema.check_reason_code(reason)
    _schema.check_actor(actor)
    if actor is not None:
        canonical(actor)  # refuses what has no canonical encoding
    _pg.check_transactional(connection, "record_maintenance")
    function = _migrations.function_name(tables, _schema.RECORD_MAINTENANCE_FUNCTION)
    statement = text(
        "SELECT incarnation, seq, leaf_hash, size, root FROM "
        f"{function}(CAST(:chain AS text), CAST(:reason AS text), "
        "CAST(:actor AS text))"
    )
    parameters = {"chain": chain, "reason": reason, "actor": actor}
    with _lock_timeout(connection, lock_timeout):
        rows = _call(connection, chain, statement, parameters)
    return _head(rows[0])

add

add(
    session: Session | AsyncSession,
    tables: LedgerTables,
    chain: str,
    entry: Entry,
    *,
    lock_timeout: str | None = None,
) -> PendingHead

Buffer an entry, to be appended when the session commits.

The recommended way to write the ledger from a session. The entries of a transaction are appended at its commit, after a final flush, with one append_many call per chain (per MAX_BATCH entries of it), so the chain's lock is held only from the append to the commit (see audit_trail.ledger._buffer). The entry is checked now, and refused entries raise here.

The head comes back in the returned PendingHead, after the commit: a head handed out before it could name an entry a rollback undoes. An entry added in a savepoint that is rolled back is discarded with it.

add runs no SQL, so it is called the same way with an AsyncSession: the append then runs in await session.commit(). It begins the session's transaction if none has begun, as a query would, so session.begin() comes before it, not after.

The commit raises what the append raises, and does not commit: LedgerBusyError when a chain's lock was not granted within lock_timeout, ValueError for an unknown chain, an IntegrityError for an entry id used before, or the error of the final flush. The database transaction is then aborted: roll the session back.

Parameters:

Name Type Description Default
session Session | AsyncSession

The session, sync or async. Its transaction must not be in AUTOCOMMIT.

required
tables LedgerTables

The ledger tables. The connection is the session's for tables.state (Session.get_bind).

required
chain str

The chain's name.

required
entry Entry

The entry. Its type may not start with ledger..

required
lock_timeout str | None

The lock_timeout of the chain's append, such as "2s"; None keeps the transaction's. It bounds each lock wait, not the whole commit. A chain's entries of one transaction are appended in one call, under one lock: when they give different values, the last one given (not None) of the entries still pending at the commit applies.

None

Returns:

Type Description
PendingHead

The entry's pending head.

Raises:

Type Description
ValueError

The chain name or the entry is refused.

InvalidRequestError

No transaction has begun and the session's autobegin is off.

TypeError

An entry field has the wrong type.

Source code in audit_trail/ledger/_buffer.py
def add(
    session: Session | AsyncSession,
    tables: LedgerTables,
    chain: str,
    entry: Entry,
    *,
    lock_timeout: str | None = None,
) -> PendingHead:
    """Buffer an entry, to be appended when the session commits.

    The recommended way to write the ledger from a session. The entries of
    a transaction are appended at its commit, after a final flush, with one
    ``append_many`` call per chain (per ``MAX_BATCH`` entries of it), so
    the chain's lock is held only from the append to the commit (see
    ``audit_trail.ledger._buffer``). The entry is checked now, and refused
    entries raise here.

    The head comes back in the returned ``PendingHead``, after the commit:
    a head handed out before it could name an entry a rollback undoes. An
    entry added in a savepoint that is rolled back is discarded with it.

    ``add`` runs no SQL, so it is called the same way with an
    ``AsyncSession``: the append then runs in ``await session.commit()``.
    It begins the session's transaction if none has begun, as a query
    would, so ``session.begin()`` comes before it, not after.

    The commit raises what the append raises, and does not commit:
    ``LedgerBusyError`` when a chain's lock was not granted within
    ``lock_timeout``, ``ValueError`` for an unknown chain, an
    ``IntegrityError`` for an entry id used before, or the error of the
    final flush. The database transaction is then aborted: roll the session
    back.

    Args:
        session: The session, sync or async. Its transaction must not be in
            ``AUTOCOMMIT``.
        tables: The ledger tables. The connection is the session's for
            ``tables.state`` (``Session.get_bind``).
        chain: The chain's name.
        entry: The entry. Its type may not start with ``ledger.``.
        lock_timeout: The ``lock_timeout`` of the chain's append, such as
            ``"2s"``; ``None`` keeps the transaction's. It bounds each lock
            wait, not the whole commit. A chain's entries of one transaction
            are appended in one call, under one lock: when they give
            different values, the last one given (not ``None``) of the
            entries still pending at the commit applies.

    Returns:
        The entry's pending head.

    Raises:
        ValueError: The chain name or the entry is refused.
        InvalidRequestError: No transaction has begun and the session's
            ``autobegin`` is off.
        TypeError: An entry field has the wrong type.
    """
    sync_session = _sync_session(session)
    _schema.check_chain(chain)
    # Checked now, so a bad entry fails where it was added; encoded again,
    # with fresh salts, at the append.
    _entry.encode_entry(entry)
    buffer = _buffer(sync_session)
    # The entry belongs to the transaction: begin it, as a query would, so
    # that a rollback or a close before any SQL also discards the entry.
    # Beginning connects to nothing.
    sync_session._autobegin_t()
    pending = PendingHead(chain, entry)
    buffer.items.append(
        _Item(
            tables=tables,
            chain=chain,
            entry=entry,
            lock_timeout=lock_timeout,
            pending=pending,
            owner=sync_session.get_nested_transaction(),
        )
    )
    return pending

aexport_bundle async

aexport_bundle(
    engine_or_conn: AsyncEngine | AsyncConnection,
    tables: LedgerTables,
    chain: str,
    destination: str | PathLike[str] | BinaryIO,
    scope: EntryRange | None = None,
    *,
    checkpoints: Iterable[LedgerCheckpoint | str] = (),
    key_history: KeyHistory | None = None,
    verifier: SignatureVerifier | None = None,
    host_files: HostFiles | None = None,
    signer: Signer | None = None,
    chunk_rows: int = DEFAULT_CHUNK_ROWS,
) -> LedgerBundleResult

Async export_bundle, for an AsyncEngine or AsyncConnection; the same arguments.

Runs export_bundle's reads and writes on one connection through run_sync; the file writes block the event loop while they run.

Raises:

Type Description
TypeError

engine_or_conn is sync; use export_bundle.

ValueError

As export_bundle.

Source code in audit_trail/ledger/_bundle.py
@explains_permissions
async def aexport_bundle(
    engine_or_conn: AsyncEngine | AsyncConnection,
    tables: LedgerTables,
    chain: str,
    destination: str | os.PathLike[str] | BinaryIO,
    scope: EntryRange | None = None,
    *,
    checkpoints: Iterable[LedgerCheckpoint | str] = (),
    key_history: KeyHistory | None = None,
    verifier: SignatureVerifier | None = None,
    host_files: HostFiles | None = None,
    signer: Signer | None = None,
    chunk_rows: int = DEFAULT_CHUNK_ROWS,
) -> LedgerBundleResult:
    """Async ``export_bundle``, for an ``AsyncEngine`` or ``AsyncConnection``;
    the same arguments.

    Runs ``export_bundle``'s reads and writes on one connection through
    ``run_sync``; the file writes block the event loop while they run.

    Raises:
        TypeError: ``engine_or_conn`` is sync; use ``export_bundle``.
        ValueError: As ``export_bundle``.
    """
    from sqlalchemy.ext.asyncio import AsyncConnection, AsyncEngine

    if not isinstance(engine_or_conn, AsyncEngine | AsyncConnection):
        raise TypeError("the engine or connection is sync; use export_bundle")
    job = _job(
        tables,
        chain,
        scope,
        checkpoints,
        key_history,
        verifier,
        host_files,
        signer,
        chunk_rows,
    )
    if isinstance(engine_or_conn, AsyncConnection):
        return await engine_or_conn.run_sync(
            lambda sync_conn: _write(sync_conn, job, destination)
        )
    async with engine_or_conn.connect() as conn:
        return await conn.run_sync(
            lambda sync_conn: _write(sync_conn, job, destination)
        )

arecord_bundle_manifest async

arecord_bundle_manifest(
    connection: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    host_files: HostFiles,
    *,
    actor: str | None = None,
    lock_timeout: str | None = None,
) -> Head

Async record_bundle_manifest, on an AsyncConnection; the same arguments.

Source code in audit_trail/ledger/_bundle.py
@explains_permissions
async def arecord_bundle_manifest(
    connection: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    host_files: HostFiles,
    *,
    actor: str | None = None,
    lock_timeout: str | None = None,
) -> Head:
    """Async ``record_bundle_manifest``, on an ``AsyncConnection``; the same
    arguments."""
    return await connection.run_sync(
        lambda sync_conn: record_bundle_manifest(
            sync_conn,
            tables,
            chain,
            host_files,
            actor=actor,
            lock_timeout=lock_timeout,
        )
    )

export_bundle

export_bundle(
    engine_or_conn: Engine | Connection,
    tables: LedgerTables,
    chain: str,
    destination: str | PathLike[str] | BinaryIO,
    scope: EntryRange | None = None,
    *,
    checkpoints: Iterable[LedgerCheckpoint | str] = (),
    key_history: KeyHistory | None = None,
    verifier: SignatureVerifier | None = None,
    host_files: HostFiles | None = None,
    signer: Signer | None = None,
    chunk_rows: int = DEFAULT_CHUNK_ROWS,
) -> LedgerBundleResult

Write a range of a chain's entries to a bundle, to check offline.

The bundle is bundle version 1 with stream_type "ledger"; audit_trail.integrity.verify_bundle and python -m audit_trail.integrity verify-bundle check it without the database, with the checks and findings of verify. The layout is in the audit_trail.ledger._bundle module documentation and in docs/spec/ledger-v1.md.

It reads as verify does: the state row first, which bounds the scope, then the entries chunk_rows at a time with their payload, each chunk in a short READ ONLY transaction of its own (or in the connection's transaction), writing them as it reads them. It takes no lock, and does not verify: run verify for that.

Host files are covered by the manifest only as far as it is anchored: by signer's signature, by its hash kept elsewhere (LedgerBundleResult.manifest_sha256), or by a ledger.bundle_manifest entry in scope (record_bundle_manifest) that a trusted checkpoint covers.

A bundle holds the payload still stored, personal data among it: keep it as you keep the ledger tables.

Parameters:

Name Type Description Default
engine_or_conn Engine | Connection

An engine, or a connection, whose role can read the ledger tables.

required
tables LedgerTables

The ledger tables.

required
chain str

The chain.

required
destination str | PathLike[str] | BinaryIO

A path, or a binary file object open for writing. A path is removed again when the export fails.

required
scope EntryRange | None

The entries to include; the whole chain, up to the size the state row names, by default.

None
checkpoints Iterable[LedgerCheckpoint | str]

Checkpoints to include, as LedgerCheckpoint objects or note texts. Checkpoints recorded in the chain outside the scope that can anchor it are included as well: those after it of a size in scope, and before it the newest, and the newest trusted one when the newest is not, so that checkpoints the application role records cannot push the signed one out. Trusted means: its signatures verify under verifier, each key in its window of key_history when given; without verifier, a signature line names a key key_history gives a window at the checkpoint's size; without either, it has a signature line. Only verifier checks the signatures.

()
key_history KeyHistory | None

Included as it is; the bundle names keys only by id.

None
verifier SignatureVerifier | None

Checks the signatures of the checkpoints recorded before the scope, to find the newest trusted one; not included.

None
host_files HostFiles | None

Files to add under host/, by name, as bytes or a path to read. A name is one or more /-separated parts of letters, digits, ., _ and -, none of them . or ...

None
signer Signer | None

Signs the manifest; None leaves it unsigned.

None
chunk_rows int

Entries read per transaction, at least 1.

DEFAULT_CHUNK_ROWS

Returns:

Type Description
LedgerBundleResult

What was written.

Raises:

Type Description
TypeError

engine_or_conn is async; use aexport_bundle.

ValueError

There is no such chain, the scope ends after the chain, a checkpoint text is not a ledger checkpoint (a NoteError), a host file name is not valid, or chunk_rows is below 1.

Source code in audit_trail/ledger/_bundle.py
@explains_permissions
def export_bundle(
    engine_or_conn: Engine | Connection,
    tables: LedgerTables,
    chain: str,
    destination: str | os.PathLike[str] | BinaryIO,
    scope: EntryRange | None = None,
    *,
    checkpoints: Iterable[LedgerCheckpoint | str] = (),
    key_history: KeyHistory | None = None,
    verifier: SignatureVerifier | None = None,
    host_files: HostFiles | None = None,
    signer: Signer | None = None,
    chunk_rows: int = DEFAULT_CHUNK_ROWS,
) -> LedgerBundleResult:
    """Write a range of a chain's entries to a bundle, to check offline.

    The bundle is bundle version 1 with ``stream_type`` ``"ledger"``;
    ``audit_trail.integrity.verify_bundle`` and ``python -m
    audit_trail.integrity verify-bundle`` check it without the database,
    with the checks and findings of ``verify``. The layout is in the
    ``audit_trail.ledger._bundle`` module documentation and in
    ``docs/spec/ledger-v1.md``.

    It reads as ``verify`` does: the state row first, which bounds the
    scope, then the entries ``chunk_rows`` at a time with their payload,
    each chunk in a short ``READ ONLY`` transaction of its own (or in the
    connection's transaction), writing them as it reads them. It takes no
    lock, and does not verify: run ``verify`` for that.

    Host files are covered by the manifest only as far as it is anchored:
    by ``signer``'s signature, by its hash kept elsewhere
    (``LedgerBundleResult.manifest_sha256``), or by a
    ``ledger.bundle_manifest`` entry in scope (``record_bundle_manifest``)
    that a trusted checkpoint covers.

    A bundle holds the payload still stored, personal data among it: keep
    it as you keep the ledger tables.

    Args:
        engine_or_conn: An engine, or a connection, whose role can read the
            ledger tables.
        tables: The ledger tables.
        chain: The chain.
        destination: A path, or a binary file object open for writing. A
            path is removed again when the export fails.
        scope: The entries to include; the whole chain, up to the size the
            state row names, by default.
        checkpoints: Checkpoints to include, as ``LedgerCheckpoint`` objects
            or note texts. Checkpoints recorded in the chain outside the
            scope that can anchor it are included as well: those after it
            of a size in scope, and before it the newest, and the newest
            trusted one when the newest is not, so that checkpoints the
            application role records cannot push the signed one out.
            Trusted means: its signatures verify under ``verifier``, each
            key in its window of ``key_history`` when given; without
            ``verifier``, a signature line names a key ``key_history``
            gives a window at the checkpoint's size; without either, it has
            a signature line. Only ``verifier`` checks the signatures.
        key_history: Included as it is; the bundle names keys only by id.
        verifier: Checks the signatures of the checkpoints recorded before
            the scope, to find the newest trusted one; not included.
        host_files: Files to add under ``host/``, by name, as bytes or a
            path to read. A name is one or more ``/``-separated parts of
            letters, digits, ``.``, ``_`` and ``-``, none of them ``.`` or
            ``..``.
        signer: Signs the manifest; ``None`` leaves it unsigned.
        chunk_rows: Entries read per transaction, at least 1.

    Returns:
        What was written.

    Raises:
        TypeError: ``engine_or_conn`` is async; use ``aexport_bundle``.
        ValueError: There is no such chain, the scope ends after the chain,
            a checkpoint text is not a ledger checkpoint (a ``NoteError``), a
            host file name is not valid, or ``chunk_rows`` is below 1.
    """
    if not isinstance(engine_or_conn, Engine | Connection):
        raise TypeError("the engine or connection is async; use aexport_bundle")
    job = _job(
        tables,
        chain,
        scope,
        checkpoints,
        key_history,
        verifier,
        host_files,
        signer,
        chunk_rows,
    )
    if isinstance(engine_or_conn, Connection):
        return _write(engine_or_conn, job, destination)
    with engine_or_conn.connect() as conn:
        return _write(conn, job, destination)

record_bundle_manifest

record_bundle_manifest(
    connection: Connection,
    tables: LedgerTables,
    chain: str,
    host_files: HostFiles,
    *,
    actor: str | None = None,
    lock_timeout: str | None = None,
) -> Head

Append ledger.bundle_manifest, anchoring a bundle's host files.

The entry's attributes are {"sha256": <base64>}, the digest of the host files as a bundle lists them (name, SHA-256 and size of each, in the order of the zip, which export_bundle writes in name order; see docs/spec/ledger-v1.md). A bundle that holds the entry, exported later with the same host_files, has its host files anchored in the log: verify_bundle takes them as covered when the entry is in scope and a trusted checkpoint covers it. Record a checkpoint after this entry and before the export, so that one can.

Runs in the connection's current transaction, under the chain's lock, as append_many does; the caller commits. It calls audit_ledger_record_bundle_manifest, which ledger_grant_statements grants the application role.

Parameters:

Name Type Description Default
connection Connection

Connection to run on.

required
tables LedgerTables

The ledger tables.

required
chain str

The chain's name.

required
host_files HostFiles

The host files, as export_bundle takes them.

required
actor str | None

The actor of the entry.

None
lock_timeout str | None

The lock_timeout for the call; None keeps the transaction's.

None

Returns:

Type Description
Head

The head after the entry.

Raises:

Type Description
LedgerBusyError

The lock was not granted within lock_timeout.

ValueError

The chain name or a host file name is refused, there are no host files, the connection is in AUTOCOMMIT, or there is no such chain (the transaction is then aborted).

TypeError

actor is not a str or None.

Source code in audit_trail/ledger/_bundle.py
@explains_permissions
def record_bundle_manifest(
    connection: Connection,
    tables: LedgerTables,
    chain: str,
    host_files: HostFiles,
    *,
    actor: str | None = None,
    lock_timeout: str | None = None,
) -> Head:
    """Append ``ledger.bundle_manifest``, anchoring a bundle's host files.

    The entry's attributes are ``{"sha256": <base64>}``, the digest of the
    host files as a bundle lists them (name, SHA-256 and size of each, in
    the order of the zip, which ``export_bundle`` writes in name order; see
    ``docs/spec/ledger-v1.md``). A bundle that holds the
    entry, exported later with the same ``host_files``, has its host files
    anchored in the log: ``verify_bundle`` takes them as covered when the
    entry is in scope and a trusted checkpoint covers it. Record a
    checkpoint after this entry and before the export, so that one can.

    Runs in the connection's current transaction, under the chain's lock,
    as ``append_many`` does; the caller commits. It calls
    ``audit_ledger_record_bundle_manifest``, which
    ``ledger_grant_statements`` grants the application role.

    Args:
        connection: Connection to run on.
        tables: The ledger tables.
        chain: The chain's name.
        host_files: The host files, as ``export_bundle`` takes them.
        actor: The ``actor`` of the entry.
        lock_timeout: The ``lock_timeout`` for the call; ``None`` keeps the
            transaction's.

    Returns:
        The head after the entry.

    Raises:
        LedgerBusyError: The lock was not granted within ``lock_timeout``.
        ValueError: The chain name or a host file name is refused, there
            are no host files, the connection is in ``AUTOCOMMIT``, or there
            is no such chain (the transaction is then aborted).
        TypeError: ``actor`` is not a ``str`` or ``None``.
    """
    _schema.check_chain(chain)
    files = _host_files(host_files)
    if not files:
        raise ValueError("there are no host files to anchor")
    if actor is not None:
        if not isinstance(actor, str):
            raise TypeError("actor must be a str or None")
        canonical(actor)  # refuses what has no canonical encoding
    _pg.check_transactional(connection, "record_bundle_manifest")
    digest = host_files_digest(chain, _listing(files))
    function = _migrations.function_name(
        tables, _schema.RECORD_BUNDLE_MANIFEST_FUNCTION
    )
    statement = text(
        "SELECT incarnation, seq, leaf_hash, size, root FROM "
        f"{function}(CAST(:chain AS text), CAST(:digest AS bytea), "
        "CAST(:actor AS text))"
    )
    parameters: dict[str, Any] = {"chain": chain, "digest": digest, "actor": actor}
    with _lock_timeout(connection, lock_timeout):
        rows = _call(connection, chain, statement, parameters)
    return _head(rows[0])

verify_bundle

verify_bundle(
    bundle: str | PathLike[str] | BinaryIO,
    *,
    verifier: SignatureVerifier,
    key_history: KeyHistory | None = None,
    checkpoints: Iterable[LedgerCheckpoint | str] = (),
    require_signatures: bool = False,
    manifest_sha256: str | None = None,
) -> LedgerReport

Check a ledger bundle written by export_bundle, without the database.

audit_trail.integrity.verify_bundle with the arguments that apply to a ledger bundle, typed for it: see there.

Raises:

Type Description
BundleError

The bundle cannot be read as one, or is not a ledger bundle.

ValueError

A checkpoint text is not a ledger checkpoint (a NoteError), or manifest_sha256 is not 64 hex digits.

Source code in audit_trail/ledger/_bundle_verify.py
def verify_bundle(
    bundle: str | os.PathLike[str] | BinaryIO,
    *,
    verifier: SignatureVerifier,
    key_history: KeyHistory | None = None,
    checkpoints: Iterable[LedgerCheckpoint | str] = (),
    require_signatures: bool = False,
    manifest_sha256: str | None = None,
) -> LedgerReport:
    """Check a ledger bundle written by ``export_bundle``, without the database.

    ``audit_trail.integrity.verify_bundle`` with the arguments that apply
    to a ledger bundle, typed for it: see there.

    Raises:
        BundleError: The bundle cannot be read as one, or is not a ledger
            bundle.
        ValueError: A checkpoint text is not a ledger checkpoint (a
            ``NoteError``), or ``manifest_sha256`` is not 64 hex digits.
    """
    options = options_of(
        verifier, key_history, checkpoints, require_signatures, manifest_sha256
    )
    with _archive(bundle) as archive:
        header = peek_header(archive)
        if header is not None and header.get("stream_type") != STREAM_TYPE:
            raise BundleError(f"{HEADER}: stream_type is not {STREAM_TYPE!r}")
        return run(archive, options)

checkpoint_origin

checkpoint_origin(
    host_origin: str, chain: str, incarnation: int
) -> str

<host origin>/<chain>/i<incarnation>, each part checked.

Raises:

Type Description
ValueError

A part is invalid.

Source code in audit_trail/ledger/_checkpoint.py
def checkpoint_origin(host_origin: str, chain: str, incarnation: int) -> str:
    """``<host origin>/<chain>/i<incarnation>``, each part checked.

    Raises:
        ValueError: A part is invalid.
    """
    check_host_origin(host_origin)
    _schema.check_chain(chain)
    if not is_int(incarnation) or not 1 <= incarnation <= MAX_INCARNATION:
        raise ValueError(f"an incarnation is an integer in [1, {MAX_INCARNATION}]")
    return f"{host_origin}/{chain}/i{incarnation}"

entry_leaf_hash

entry_leaf_hash(
    chain: str,
    incarnation: int,
    seq: int,
    appended_at: datetime,
    body: bytes,
) -> bytes

The RFC 6962 leaf hash of an entry, SHA-256(0x00 || leaf_input).

Source code in audit_trail/ledger/_entry.py
def entry_leaf_hash(
    chain: str, incarnation: int, seq: int, appended_at: datetime, body: bytes
) -> bytes:
    """The RFC 6962 leaf hash of an entry, ``SHA-256(0x00 || leaf_input)``."""
    return hashlib.sha256(
        b"\x00" + leaf_input(chain, incarnation, seq, appended_at, body)
    ).digest()

leaf_input

leaf_input(
    chain: str,
    incarnation: int,
    seq: int,
    appended_at: datetime,
    body: bytes,
) -> bytes

The input of an entry's leaf hash, as the append function builds it.

Parameters:

Name Type Description Default
chain str

The chain name.

required
incarnation int

The incarnation the entry was appended in.

required
seq int

The entry's sequence number.

required
appended_at datetime

The append time, as stored in appended_at.

required
body bytes

The body bytes, as stored in body.

required
Source code in audit_trail/ledger/_entry.py
def leaf_input(
    chain: str, incarnation: int, seq: int, appended_at: datetime, body: bytes
) -> bytes:
    """The input of an entry's leaf hash, as the append function builds it.

    Args:
        chain: The chain name.
        incarnation: The incarnation the entry was appended in.
        seq: The entry's sequence number.
        appended_at: The append time, as stored in ``appended_at``.
        body: The body bytes, as stored in ``body``.
    """
    header = "\n".join(
        [
            LEAF_CONTEXT.decode(),
            chain,
            str(incarnation),
            str(seq),
            str(micros(appended_at)),
            "",
        ]
    )
    return header.encode() + body

achange_config async

achange_config(
    connection: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    config: ChainConfig,
    *,
    actor: str | None = None,
    lock_timeout: str | None = None,
) -> Head

Async change_config, on an AsyncConnection; the same arguments.

Source code in audit_trail/ledger/_erase.py
@explains_permissions
async def achange_config(
    connection: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    config: ChainConfig,
    *,
    actor: str | None = None,
    lock_timeout: str | None = None,
) -> Head:
    """Async ``change_config``, on an ``AsyncConnection``; the same arguments."""
    return await connection.run_sync(
        lambda sync_conn: change_config(
            sync_conn, tables, chain, config, actor=actor, lock_timeout=lock_timeout
        )
    )

aerase async

aerase(
    connection: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    entry_id: UUID,
    reason: str,
    *,
    actor: str | None = None,
    lock_timeout: str | None = None,
) -> Head

Async erase, on an AsyncConnection; the same arguments.

Source code in audit_trail/ledger/_erase.py
@explains_permissions
async def aerase(
    connection: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    entry_id: uuid.UUID,
    reason: str,
    *,
    actor: str | None = None,
    lock_timeout: str | None = None,
) -> Head:
    """Async ``erase``, on an ``AsyncConnection``; the same arguments."""
    return await connection.run_sync(
        lambda sync_conn: erase(
            sync_conn,
            tables,
            chain,
            entry_id,
            reason,
            actor=actor,
            lock_timeout=lock_timeout,
        )
    )

change_config

change_config(
    connection: Connection,
    tables: LedgerTables,
    chain: str,
    config: ChainConfig,
    *,
    actor: str | None = None,
    lock_timeout: str | None = None,
) -> Head

Replace a chain's config, recording it in ledger.config_changed.

audit_ledger_change_config, a SECURITY DEFINER function, locks the chain's state row, checks the config as create_chain does, appends the entry, whose attributes are the whole new config, and stores the config with that entry's seq as its recorded_seq, all under the lock: an append or erasure runs under the config before the change or after it, never a mix. detect_restores is fixed when the chain is created and cannot change.

Runs in the connection's current transaction; the caller commits. By default only the owner of the ledger functions may call it.

Parameters:

Name Type Description Default
connection Connection

Connection to run on.

required
tables LedgerTables

The ledger tables.

required
chain str

The chain's name.

required
config ChainConfig

The new config, whole.

required
actor str | None

The actor of the entry.

None
lock_timeout str | None

The lock_timeout for the call; None keeps the transaction's. It bounds each lock wait, not the whole call.

None

Returns:

Type Description
Head

The head after the entry.

Raises:

Type Description
LedgerBusyError

The lock was not granted within lock_timeout.

ValueError

The chain name is refused, the connection is in AUTOCOMMIT, there is no such chain, or the config changes detect_restores.

DBAPIError

The config names a precondition function that exists and does not set a search_path ending in pg_temp (see erase).

Source code in audit_trail/ledger/_erase.py
@explains_permissions
def change_config(
    connection: Connection,
    tables: LedgerTables,
    chain: str,
    config: ChainConfig,
    *,
    actor: str | None = None,
    lock_timeout: str | None = None,
) -> Head:
    """Replace a chain's config, recording it in ``ledger.config_changed``.

    ``audit_ledger_change_config``, a ``SECURITY DEFINER`` function, locks
    the chain's state row, checks the config as ``create_chain`` does,
    appends the entry, whose ``attributes`` are the whole new config, and
    stores the config with that entry's ``seq`` as its ``recorded_seq``,
    all under the lock: an append or erasure runs under the config before
    the change or after it, never a mix. ``detect_restores`` is fixed when
    the chain is created and cannot change.

    Runs in the connection's current transaction; the caller commits. By
    default only the owner of the ledger functions may call it.

    Args:
        connection: Connection to run on.
        tables: The ledger tables.
        chain: The chain's name.
        config: The new config, whole.
        actor: The ``actor`` of the entry.
        lock_timeout: The ``lock_timeout`` for the call; ``None`` keeps the
            transaction's. It bounds each lock wait, not the whole call.

    Returns:
        The head after the entry.

    Raises:
        LedgerBusyError: The lock was not granted within ``lock_timeout``.
        ValueError: The chain name is refused, the connection is in
            ``AUTOCOMMIT``, there is no such chain, or the config changes
            ``detect_restores``.
        DBAPIError: The config names a precondition function that exists
            and does not set a ``search_path`` ending in ``pg_temp`` (see
            ``erase``).
    """
    _schema.check_chain(chain)
    if not isinstance(config, ChainConfig):
        raise TypeError("config must be a ChainConfig")
    _pg.check_transactional(connection, "change_config")
    encoded = _entry.encode_entry(
        Entry(_entry.CONFIG_CHANGED, attributes=config.as_dict(), actor=actor),
        package=True,
    )
    function = _migrations.function_name(tables, _schema.CHANGE_CONFIG_FUNCTION)
    statement = text(
        "SELECT incarnation, seq, leaf_hash, size, root FROM "
        f"{function}(CAST(:chain AS text), CAST(CAST(:config AS text) AS jsonb), "
        "CAST(:body AS bytea))"
    )
    parameters = {
        "chain": chain,
        "config": _entry.config_json(config),
        "body": encoded.body,
    }
    return _call(connection, chain, statement, parameters, lock_timeout, ValueError)

erase

erase(
    connection: Connection,
    tables: LedgerTables,
    chain: str,
    entry_id: UUID,
    reason: str,
    *,
    actor: str | None = None,
    lock_timeout: str | None = None,
) -> Head

Erase an entry's payload, and append the receipt, ledger.erased.

audit_ledger_erase, a SECURITY DEFINER function, locks the chain's state row (each lock wait bounded by lock_timeout, not the total), then checks, under the chain's current config:

  1. that reason is one of the chain's reason codes;
  2. that the entry is in the chain, and its type is neither one of the chain's protected types nor one of the package's (ledger.), so a receipt is never erased;
  3. that the entry has a payload, not yet erased: erasing an entry twice is refused, not repeated;
  4. that the chain's precondition function, if it has one, sets a search_path ending in pg_temp and returns true for (chain, entry_id, reason).

It then deletes the entry's payload rows (values and salts) and appends the receipt, whose attributes are the entry's entry_id, incarnation and seq and the reason_code; no free text. The entry's body and its commitments stay, so the tree is unchanged.

A restore brings the payload back. record_restore erases it again only when the journal of the restore kit it is given lists the erasure, and does not report an erasure made after that kit's checkpoint. After erasures, take a checkpoint with journal=True and keep its new kit; keep a log of erasures off the database too, and after a restore erase again what it lists after the newest kit. The restore may have lost a change_config that the reason code needs: run it again first.

The precondition is the name of a function, never SQL text: the erase function quotes its parts with format('%I'), resolves the exact signature (text, uuid, text) and calls it with bound arguments. A bare name is looked up in the ledger's schema. It must return boolean and be owned by the ledger owner, so that no other role can change what runs with the owner's rights. It may read what the owner may: the entry and the other ledger tables, and host tables the owner is granted. It must set its own search_path, ending in pg_temp, or the eraser's temporary tables are searched first and could stand in for the tables it reads; qualify the names it uses, or list their schemas before pg_temp::

CREATE FUNCTION audit.may_erase(chain text, entry_id uuid, reason text)
RETURNS boolean LANGUAGE sql STABLE
SET search_path = pg_catalog, pg_temp
AS $$
    SELECT NOT EXISTS (
        SELECT FROM audit.legal_hold AS h WHERE h.entry_id = $2
    )
$$;

Runs in the connection's current transaction; the caller commits. The calling role needs EXECUTE on audit_ledger_erase and SELECT on audit_ledger_entry: see ledger_eraser_grant_statements and ledger_grant_statements(..., erase=True).

Parameters:

Name Type Description Default
connection Connection

Connection to run on.

required
tables LedgerTables

The ledger tables.

required
chain str

The chain's name.

required
entry_id UUID

The entry's id.

required
reason str

A reason code of the chain's config.

required
actor str | None

The actor of the receipt.

None
lock_timeout str | None

The lock_timeout for the call, such as "2s"; None keeps the transaction's. It bounds each lock wait, not the whole call.

None

Returns:

Type Description
Head

The head after the receipt.

Raises:

Type Description
ErasureRefusedError

A check refused the erasure.

LedgerBusyError

The lock was not granted within lock_timeout.

ValueError

The chain name or reason code is refused, the connection is in AUTOCOMMIT, or the chain or the entry does not exist.

TypeError

entry_id is not a uuid.UUID.

Source code in audit_trail/ledger/_erase.py
@explains_permissions
def erase(
    connection: Connection,
    tables: LedgerTables,
    chain: str,
    entry_id: uuid.UUID,
    reason: str,
    *,
    actor: str | None = None,
    lock_timeout: str | None = None,
) -> Head:
    """Erase an entry's payload, and append the receipt, ``ledger.erased``.

    ``audit_ledger_erase``, a ``SECURITY DEFINER`` function, locks the
    chain's state row (each lock wait bounded by ``lock_timeout``, not the
    total), then checks, under
    the chain's current config:

    1. that ``reason`` is one of the chain's reason codes;
    2. that the entry is in the chain, and its type is neither one of the
       chain's protected types nor one of the package's (``ledger.``), so a
       receipt is never erased;
    3. that the entry has a payload, not yet erased: erasing an entry twice
       is refused, not repeated;
    4. that the chain's precondition function, if it has one, sets a
       ``search_path`` ending in ``pg_temp`` and returns ``true`` for
       ``(chain, entry_id, reason)``.

    It then deletes the entry's payload rows (values and salts) and appends
    the receipt, whose ``attributes`` are the entry's ``entry_id``,
    ``incarnation`` and ``seq`` and the ``reason_code``; no free text. The
    entry's body and its commitments stay, so the tree is unchanged.

    A restore brings the payload back. ``record_restore`` erases it again
    only when the journal of the restore kit it is given lists the
    erasure, and does not report an erasure made after that kit's
    checkpoint. After erasures, take a checkpoint with ``journal=True`` and
    keep its new kit; keep a log of erasures off the database too, and
    after a restore erase again what it lists after the newest kit. The
    restore may have lost a ``change_config`` that the reason code needs:
    run it again first.

    The precondition is the name of a function, never SQL text: the erase
    function quotes its parts with ``format('%I')``, resolves the exact
    signature ``(text, uuid, text)`` and calls it with bound arguments. A
    bare name is looked up in the ledger's schema. It must return
    ``boolean`` and be owned by the ledger owner, so that no other role can
    change what runs with the owner's rights. It may read what the owner
    may: the entry and the other ledger tables, and host tables the owner
    is granted. It must set its own ``search_path``, ending in ``pg_temp``,
    or the eraser's temporary tables are searched first and could stand in
    for the tables it reads; qualify the names it uses, or list their
    schemas before ``pg_temp``::

        CREATE FUNCTION audit.may_erase(chain text, entry_id uuid, reason text)
        RETURNS boolean LANGUAGE sql STABLE
        SET search_path = pg_catalog, pg_temp
        AS $$
            SELECT NOT EXISTS (
                SELECT FROM audit.legal_hold AS h WHERE h.entry_id = $2
            )
        $$;

    Runs in the connection's current transaction; the caller commits. The
    calling role needs ``EXECUTE`` on ``audit_ledger_erase`` and ``SELECT``
    on ``audit_ledger_entry``: see ``ledger_eraser_grant_statements`` and
    ``ledger_grant_statements(..., erase=True)``.

    Args:
        connection: Connection to run on.
        tables: The ledger tables.
        chain: The chain's name.
        entry_id: The entry's id.
        reason: A reason code of the chain's config.
        actor: The ``actor`` of the receipt.
        lock_timeout: The ``lock_timeout`` for the call, such as ``"2s"``;
            ``None`` keeps the transaction's. It bounds each lock wait, not
            the whole call.

    Returns:
        The head after the receipt.

    Raises:
        ErasureRefusedError: A check refused the erasure.
        LedgerBusyError: The lock was not granted within ``lock_timeout``.
        ValueError: The chain name or reason code is refused, the
            connection is in ``AUTOCOMMIT``, or the chain or the entry does
            not exist.
        TypeError: ``entry_id`` is not a ``uuid.UUID``.
    """
    _schema.check_chain(chain)
    _schema.check_reason_code(reason)
    if not isinstance(entry_id, uuid.UUID):
        raise TypeError("entry_id must be a uuid.UUID")
    _pg.check_transactional(connection, "erase")
    entry = tables.entry
    target = connection.execute(
        select(entry.c.incarnation, entry.c.seq).where(
            entry.c.chain == chain, entry.c.entry_id == entry_id
        )
    ).one_or_none()
    if target is None:
        raise ValueError(f"ledger chain {chain!r} has no entry {entry_id}")
    receipt = _entry.encode_entry(
        Entry(
            _entry.ERASED,
            attributes={
                "entry_id": str(entry_id),
                "incarnation": int(target.incarnation),
                "reason_code": reason,
                "seq": int(target.seq),
            },
            actor=actor,
        ),
        package=True,
    )
    function = _migrations.function_name(tables, _schema.ERASE_FUNCTION)
    statement = text(
        "SELECT incarnation, seq, leaf_hash, size, root FROM "
        f"{function}(CAST(:chain AS text), CAST(:entry_id AS uuid), "
        "CAST(:reason AS text), CAST(:body AS bytea))"
    )
    parameters = {
        "chain": chain,
        "entry_id": str(entry_id),
        "reason": reason,
        "body": receipt.body,
    }
    return _call(
        connection, chain, statement, parameters, lock_timeout, ErasureRefusedError
    )

create_ledger_sql

create_ledger_sql(tables: LedgerTables) -> str

create_ledger_statements as one SQL script.

Source code in audit_trail/ledger/_migrations.py
def create_ledger_sql(tables: LedgerTables) -> str:
    """``create_ledger_statements`` as one SQL script."""
    return "".join(f"{statement};\n" for statement in create_ledger_statements(tables))

create_ledger_statements

create_ledger_statements(tables: LedgerTables) -> list[str]

DDL creating the ledger tables and functions.

The schema (IF NOT EXISTS), the five tables and their indexes (IF NOT EXISTS), a check that current_user owns each table and the schema and that no other role may create in the schema, and the SECURITY DEFINER functions (CREATE OR REPLACE), each with EXECUTE revoked from PUBLIC:

  • audit_ledger_append(chain, bodies, payload_entries, payload_groups, payload_salts, payload_values), which append calls, and which refuses the package's ledger. types;
  • audit_ledger_append_entries, with the same arguments, which does the work for it and for the package's own entries;
  • audit_ledger_create_chain(chain, config, body), which create_chain calls;
  • audit_ledger_erase(chain, entry_id, reason, body), which erase calls;
  • audit_ledger_change_config(chain, config, body), which change_config calls;
  • audit_ledger_cluster_identity(), which reads the cluster identity;
  • audit_ledger_detect_restore(chain), which every append calls first (see "Restore detection");
  • audit_ledger_record_maintenance(chain, reason, actor), which record_maintenance calls;
  • audit_ledger_record_checkpoint(chain, body), which record_checkpoint calls;
  • audit_ledger_record_bundle_manifest(chain, digest, actor), which record_bundle_manifest calls.
  • audit_ledger_record_restore(chain, note, journal, restored_size, proven_size, proven_root, proof, actor), which record_restore calls;
  • audit_ledger_confirm_upgrade(chain, seq, actor), which confirm_upgrade calls.

The role that runs them owns the tables and the functions, and the functions write as that role; grant the application what ledger_grant_statements lists. Run them in a schema that role owns, where no other role has CREATE: a table another role created there first would be kept by IF NOT EXISTS, and a role that may create there could add objects the functions would find. The check refuses a table another role owns, a schema another role owns, and a schema in which another role, or PUBLIC, has CREATE. Superusers, and roles that are members of the owner, are not checked.

Parameters:

Name Type Description Default
tables LedgerTables

The ledger tables, from build_ledger_tables.

required

Returns:

Type Description
list[str]

The statements, in order, without trailing semicolons.

Source code in audit_trail/ledger/_migrations.py
def create_ledger_statements(tables: LedgerTables) -> list[str]:
    """DDL creating the ledger tables and functions.

    The schema (``IF NOT EXISTS``), the five tables and their indexes (``IF
    NOT EXISTS``), a check that ``current_user`` owns each table and the
    schema and that no other role may create in the schema, and the
    ``SECURITY DEFINER`` functions (``CREATE OR REPLACE``), each with
    ``EXECUTE`` revoked from ``PUBLIC``:

    - ``audit_ledger_append(chain, bodies, payload_entries, payload_groups,
      payload_salts, payload_values)``, which ``append`` calls, and which
      refuses the package's ``ledger.`` types;
    - ``audit_ledger_append_entries``, with the same arguments, which does
      the work for it and for the package's own entries;
    - ``audit_ledger_create_chain(chain, config, body)``, which
      ``create_chain`` calls;
    - ``audit_ledger_erase(chain, entry_id, reason, body)``, which ``erase``
      calls;
    - ``audit_ledger_change_config(chain, config, body)``, which
      ``change_config`` calls;
    - ``audit_ledger_cluster_identity()``, which reads the cluster identity;
    - ``audit_ledger_detect_restore(chain)``, which every append calls
      first (see "Restore detection");
    - ``audit_ledger_record_maintenance(chain, reason, actor)``, which
      ``record_maintenance`` calls;
    - ``audit_ledger_record_checkpoint(chain, body)``, which
      ``record_checkpoint`` calls;
    - ``audit_ledger_record_bundle_manifest(chain, digest, actor)``, which
      ``record_bundle_manifest`` calls.
    - ``audit_ledger_record_restore(chain, note, journal, restored_size,
      proven_size, proven_root, proof, actor)``, which ``record_restore``
      calls;
    - ``audit_ledger_confirm_upgrade(chain, seq, actor)``, which
      ``confirm_upgrade`` calls.

    The role that runs them owns the tables and the functions, and the
    functions write as that role; grant the application what
    ``ledger_grant_statements`` lists. Run them in a schema that role owns,
    where no other role has ``CREATE``: a table another role created there
    first would be kept by ``IF NOT EXISTS``, and a role that may create
    there could add objects the functions would find. The check refuses a
    table another role owns, a schema another role owns, and a schema in
    which another role, or ``PUBLIC``, has ``CREATE``. Superusers, and roles
    that are members of the owner, are not checked.

    Args:
        tables: The ledger tables, from ``build_ledger_tables``.

    Returns:
        The statements, in order, without trailing semicolons.
    """
    statements = [
        f"CREATE SCHEMA IF NOT EXISTS {_PREPARER.quote_schema(tables.schema)}"
    ]
    for table in _tables(tables):
        statements.append(_compile(CreateTable(table, if_not_exists=True)))
        statements.extend(
            _compile(CreateIndex(index, if_not_exists=True))
            for index in sorted(table.indexes, key=lambda i: str(i.name))
        )
    statements.append(_owner_check(tables))
    for function, arguments, template in _FUNCTIONS:
        statements.append(_render(template, tables, function))
        statements.append(
            f"REVOKE ALL ON FUNCTION {_name(tables, function)}({arguments}) FROM PUBLIC"
        )
    return statements

create_ledger_tables

create_ledger_tables(
    connection: Connection, tables: LedgerTables
) -> None

Execute create_ledger_statements on connection.

Runs in the connection's current transaction; the caller commits. Running it again replaces the functions and keeps the tables.

Parameters:

Name Type Description Default
connection Connection

Connection to run on, such as Alembic's op.get_bind().

required
tables LedgerTables

The ledger tables, from build_ledger_tables.

required
Source code in audit_trail/ledger/_migrations.py
@explains_permissions
def create_ledger_tables(connection: Connection, tables: LedgerTables) -> None:
    """Execute ``create_ledger_statements`` on ``connection``.

    Runs in the connection's current transaction; the caller commits.
    Running it again replaces the functions and keeps the tables.

    Args:
        connection: Connection to run on, such as Alembic's ``op.get_bind()``.
        tables: The ledger tables, from ``build_ledger_tables``.
    """
    for statement in create_ledger_statements(tables):
        _pg.execute_ddl(connection, statement)

drop_ledger_statements

drop_ledger_statements(tables: LedgerTables) -> list[str]

DDL dropping the ledger functions and tables; the schema is kept.

Parameters:

Name Type Description Default
tables LedgerTables

The ledger tables.

required

Returns:

Type Description
list[str]

The statements, in order, without trailing semicolons.

Source code in audit_trail/ledger/_migrations.py
def drop_ledger_statements(tables: LedgerTables) -> list[str]:
    """DDL dropping the ledger functions and tables; the schema is kept.

    Args:
        tables: The ledger tables.

    Returns:
        The statements, in order, without trailing semicolons.
    """
    statements = [
        f"DROP FUNCTION IF EXISTS {_name(tables, function)}({arguments})"
        for function, arguments, _template in reversed(_FUNCTIONS)
    ]
    statements.extend(
        f"DROP TABLE IF EXISTS {_table(table)}" for table in reversed(_tables(tables))
    )
    return statements

drop_ledger_tables

drop_ledger_tables(
    connection: Connection, tables: LedgerTables
) -> None

Execute drop_ledger_statements on connection.

Parameters:

Name Type Description Default
connection Connection

Connection to run on.

required
tables LedgerTables

The ledger tables.

required
Source code in audit_trail/ledger/_migrations.py
@explains_permissions
def drop_ledger_tables(connection: Connection, tables: LedgerTables) -> None:
    """Execute ``drop_ledger_statements`` on ``connection``.

    Args:
        connection: Connection to run on.
        tables: The ledger tables.
    """
    for statement in drop_ledger_statements(tables):
        _pg.execute_ddl(connection, statement)

ledger_eraser_grant_statements

ledger_eraser_grant_statements(
    tables: LedgerTables, role: str
) -> list[str]

The grants of an optional eraser role, which may only erase.

USAGE on the schema, SELECT on audit_ledger_entry (erase reads the entry's incarnation and seq for the receipt) and EXECUTE on audit_ledger_erase. Nothing else: the role cannot append, record a checkpoint, delete payload rows itself, or change the config. Like ledger_grant_statements, the statements first revoke EXECUTE on the other functions it must not call, and every privilege on the five tables, which default privileges may have granted.

The eraser role is optional: ledger_grant_statements(..., erase=True) lets the application role erase instead.

Parameters:

Name Type Description Default
tables LedgerTables

The ledger tables.

required
role str

The eraser role.

required

Returns:

Type Description
list[str]

The statements, without trailing semicolons.

Source code in audit_trail/ledger/_migrations.py
def ledger_eraser_grant_statements(tables: LedgerTables, role: str) -> list[str]:
    """The grants of an optional eraser role, which may only erase.

    ``USAGE`` on the schema, ``SELECT`` on ``audit_ledger_entry`` (``erase``
    reads the entry's ``incarnation`` and ``seq`` for the receipt) and
    ``EXECUTE`` on ``audit_ledger_erase``. Nothing else: the role cannot
    append, record a checkpoint, delete payload rows itself, or change the
    config. Like
    ``ledger_grant_statements``, the statements first revoke ``EXECUTE`` on
    the other functions it must not call, and every privilege on the five
    tables, which default privileges may have granted.

    The eraser role is optional: ``ledger_grant_statements(...,
    erase=True)`` lets the application role erase instead.

    Args:
        tables: The ledger tables.
        role: The eraser role.

    Returns:
        The statements, without trailing semicolons.
    """
    grantee = _PREPARER.quote(role)
    names = ", ".join(_table(table) for table in _tables(tables))
    append = _name(tables, _schema.APPEND_FUNCTION)
    return [
        *_revoke_statements(tables, grantee),
        f"REVOKE EXECUTE ON FUNCTION {append}({_schema.APPEND_ARGUMENTS}) "
        f"FROM {grantee}",
        f"REVOKE EXECUTE ON FUNCTION {_record_checkpoint(tables)} FROM {grantee}",
        f"REVOKE EXECUTE ON FUNCTION {_record_bundle_manifest(tables)} FROM {grantee}",
        f"REVOKE ALL ON {names} FROM {grantee}",
        f"GRANT USAGE ON SCHEMA {_PREPARER.quote_schema(tables.schema)} TO {grantee}",
        f"GRANT SELECT ON {_table(tables.entry)} TO {grantee}",
        _erase_privilege(tables, grantee, grant=True),
    ]

ledger_grant_statements

ledger_grant_statements(
    tables: LedgerTables, role: str, *, erase: bool = False
) -> list[str]

The grants an application role needs to append to the ledger and read it.

USAGE on the schema, SELECT on the five tables and EXECUTE on audit_ledger_append, audit_ledger_record_checkpoint and audit_ledger_record_bundle_manifest. No INSERT, UPDATE or DELETE: the role writes only through the functions, so it can append new entries but not change, reorder or delete existing ones. The record-checkpoint function appends only a ledger.checkpoint entry naming a head of the stored tree; it cannot check the note's signatures, which record_checkpoint and verify do. The bundle-manifest function appends only a ledger.bundle_manifest entry holding a digest. Creating a chain, changing its config, recording maintenance, recording a restore or confirming an upgrade needs the owner of the functions, or EXECUTE on audit_ledger_create_chain, audit_ledger_change_config, audit_ledger_record_maintenance, audit_ledger_record_restore or audit_ledger_confirm_upgrade granted separately.

The statements also revoke EXECUTE on every other ledger function and, unless erase is set, audit_ledger_erase from the role, in case default privileges (ALTER DEFAULT PRIVILEGES ... GRANT EXECUTE ON FUNCTIONS) granted it when the functions were created, and every privilege on the five tables before granting SELECT, in case default privileges on tables granted INSERT, UPDATE, DELETE, TRUNCATE or TRIGGER (a trigger on a ledger table would run inside the functions, as their owner). The ledger has no sequences.

Run them as the owner of the ledger tables, after create_ledger_tables.

Parameters:

Name Type Description Default
tables LedgerTables

The ledger tables.

required
role str

The application role.

required
erase bool

Also grant EXECUTE on audit_ledger_erase, so that the application erases itself, with no eraser role. Without it, these statements revoke what ledger_eraser_grant_statements granted the same role.

False

Returns:

Type Description
list[str]

The statements, without trailing semicolons.

Source code in audit_trail/ledger/_migrations.py
def ledger_grant_statements(
    tables: LedgerTables, role: str, *, erase: bool = False
) -> list[str]:
    """The grants an application role needs to append to the ledger and read it.

    ``USAGE`` on the schema, ``SELECT`` on the five tables and ``EXECUTE`` on
    ``audit_ledger_append``, ``audit_ledger_record_checkpoint`` and
    ``audit_ledger_record_bundle_manifest``. No
    ``INSERT``, ``UPDATE`` or ``DELETE``: the role writes only through the
    functions, so it can append new entries but not change, reorder or
    delete existing ones. The record-checkpoint function appends only a
    ``ledger.checkpoint`` entry naming a head of the stored tree; it cannot
    check the note's signatures, which ``record_checkpoint`` and ``verify``
    do. The bundle-manifest function appends only a
    ``ledger.bundle_manifest`` entry holding a digest. Creating a chain,
    changing its config, recording maintenance, recording a restore or
    confirming an upgrade needs the owner of the functions, or ``EXECUTE``
    on ``audit_ledger_create_chain``, ``audit_ledger_change_config``,
    ``audit_ledger_record_maintenance``, ``audit_ledger_record_restore`` or
    ``audit_ledger_confirm_upgrade`` granted separately.

    The statements also revoke ``EXECUTE`` on every other ledger function
    and, unless ``erase`` is set, ``audit_ledger_erase`` from the role, in
    case default privileges (``ALTER DEFAULT PRIVILEGES ... GRANT EXECUTE ON
    FUNCTIONS``) granted it when the functions were created, and every
    privilege on the five tables before granting ``SELECT``, in case default
    privileges on tables granted ``INSERT``, ``UPDATE``, ``DELETE``,
    ``TRUNCATE`` or ``TRIGGER`` (a trigger on a ledger table would run inside
    the functions, as their owner). The ledger has no sequences.

    Run them as the owner of the ledger tables, after
    ``create_ledger_tables``.

    Args:
        tables: The ledger tables.
        role: The application role.
        erase: Also grant ``EXECUTE`` on ``audit_ledger_erase``, so that the
            application erases itself, with no eraser role. Without it,
            these statements revoke what ``ledger_eraser_grant_statements``
            granted the same role.

    Returns:
        The statements, without trailing semicolons.
    """
    grantee = _PREPARER.quote(role)
    names = ", ".join(_table(table) for table in _tables(tables))
    append = _name(tables, _schema.APPEND_FUNCTION)
    statements = _revoke_statements(tables, grantee)
    if not erase:
        statements.append(_erase_privilege(tables, grantee, grant=False))
    statements += [
        f"REVOKE ALL ON {names} FROM {grantee}",
        f"GRANT USAGE ON SCHEMA {_PREPARER.quote_schema(tables.schema)} TO {grantee}",
        f"GRANT SELECT ON {names} TO {grantee}",
        f"GRANT EXECUTE ON FUNCTION {append}({_schema.APPEND_ARGUMENTS}) TO {grantee}",
        f"GRANT EXECUTE ON FUNCTION {_record_checkpoint(tables)} TO {grantee}",
        f"GRANT EXECUTE ON FUNCTION {_record_bundle_manifest(tables)} TO {grantee}",
    ]
    if erase:
        statements.append(_erase_privilege(tables, grantee, grant=True))
    return statements

ledger_reader_grant_statements

ledger_reader_grant_statements(
    tables: LedgerTables, role: str
) -> list[str]

The grants of a read-only role, such as a verifier or an auditor.

USAGE on the schema and SELECT on the five tables: enough for verify, the proofs, prepare_checkpoint, erasure_journal and export_bundle, which only read. Nothing else: the role cannot append, record a checkpoint or a bundle manifest, erase, create a chain or change its config, or write a row itself. Like ledger_grant_statements, the statements first revoke EXECUTE on every ledger function, and every privilege on the five tables, which default privileges may have granted.

Run them as the owner of the ledger tables, after create_ledger_tables.

Parameters:

Name Type Description Default
tables LedgerTables

The ledger tables.

required
role str

The read-only role.

required

Returns:

Type Description
list[str]

The statements, without trailing semicolons.

Source code in audit_trail/ledger/_migrations.py
def ledger_reader_grant_statements(tables: LedgerTables, role: str) -> list[str]:
    """The grants of a read-only role, such as a verifier or an auditor.

    ``USAGE`` on the schema and ``SELECT`` on the five tables: enough for
    ``verify``, the proofs, ``prepare_checkpoint``, ``erasure_journal`` and
    ``export_bundle``, which only read. Nothing else: the role cannot
    append, record a checkpoint or a bundle manifest, erase, create a chain
    or change its config, or write a row itself. Like
    ``ledger_grant_statements``, the statements first revoke ``EXECUTE`` on
    every ledger function, and every privilege on the five tables, which
    default privileges may have granted.

    Run them as the owner of the ledger tables, after
    ``create_ledger_tables``.

    Args:
        tables: The ledger tables.
        role: The read-only role.

    Returns:
        The statements, without trailing semicolons.
    """
    grantee = _PREPARER.quote(role)
    names = ", ".join(_table(table) for table in _tables(tables))
    append = _name(tables, _schema.APPEND_FUNCTION)
    return [
        *_revoke_statements(tables, grantee),
        f"REVOKE EXECUTE ON FUNCTION {append}({_schema.APPEND_ARGUMENTS}) "
        f"FROM {grantee}",
        f"REVOKE EXECUTE ON FUNCTION {_record_checkpoint(tables)} FROM {grantee}",
        f"REVOKE EXECUTE ON FUNCTION {_record_bundle_manifest(tables)} FROM {grantee}",
        _erase_privilege(tables, grantee, grant=False),
        f"REVOKE ALL ON {names} FROM {grantee}",
        f"GRANT USAGE ON SCHEMA {_PREPARER.quote_schema(tables.schema)} TO {grantee}",
        f"GRANT SELECT ON {names} TO {grantee}",
    ]

aconsistency_proof async

aconsistency_proof(
    conn: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    old_size: int,
    new_size: int | None = None,
) -> ConsistencyProof

Async consistency_proof, on an AsyncConnection; the same arguments.

Source code in audit_trail/ledger/_proof.py
@explains_permissions
async def aconsistency_proof(
    conn: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    old_size: int,
    new_size: int | None = None,
) -> ConsistencyProof:
    """Async ``consistency_proof``, on an ``AsyncConnection``; the same arguments."""
    return await conn.run_sync(
        lambda sync_conn: consistency_proof(
            sync_conn, tables, chain, old_size, new_size
        )
    )

ainclusion_proof async

ainclusion_proof(
    conn: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    seq: int,
    size: int | None = None,
) -> InclusionProof

Async inclusion_proof, on an AsyncConnection; the same arguments.

Source code in audit_trail/ledger/_proof.py
@explains_permissions
async def ainclusion_proof(
    conn: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    seq: int,
    size: int | None = None,
) -> InclusionProof:
    """Async ``inclusion_proof``, on an ``AsyncConnection``; the same arguments."""
    return await conn.run_sync(
        lambda sync_conn: inclusion_proof(sync_conn, tables, chain, seq, size)
    )

consistency_proof

consistency_proof(
    conn: Connection,
    tables: LedgerTables,
    chain: str,
    old_size: int,
    new_size: int | None = None,
) -> ConsistencyProof

The consistency proof from the tree of old_size to new_size.

Reads as inclusion_proof does. The proof is empty when old_size is 0 or equals new_size.

Parameters:

Name Type Description Default
conn Connection

The connection; a role that can read the ledger tables.

required
tables LedgerTables

The ledger tables.

required
chain str

The chain.

required
old_size int

The smaller size, 0 or more.

required
new_size int | None

The larger size; the chain's current size by default.

None

Returns:

Type Description
ConsistencyProof

The proof, with the roots of both sizes.

Raises:

Type Description
ValueError

There is no such chain, old_size is negative or above new_size, new_size is above the chain's size, or a stored node is missing.

TypeError

A size is not an int.

Source code in audit_trail/ledger/_proof.py
@explains_permissions
def consistency_proof(
    conn: Connection,
    tables: LedgerTables,
    chain: str,
    old_size: int,
    new_size: int | None = None,
) -> ConsistencyProof:
    """The consistency proof from the tree of ``old_size`` to ``new_size``.

    Reads as ``inclusion_proof`` does. The proof is empty when ``old_size``
    is 0 or equals ``new_size``.

    Args:
        conn: The connection; a role that can read the ledger tables.
        tables: The ledger tables.
        chain: The chain.
        old_size: The smaller size, 0 or more.
        new_size: The larger size; the chain's current size by default.

    Returns:
        The proof, with the roots of both sizes.

    Raises:
        ValueError: There is no such chain, ``old_size`` is negative or
            above ``new_size``, ``new_size`` is above the chain's size, or a
            stored node is missing.
        TypeError: A size is not an int.
    """
    _check_int(old_size, "old_size")
    with reading(conn, not conn.in_transaction()):
        current = read_state(conn, tables, chain).size
        new_size = _bounded(new_size, current, "new_size")
        if not 0 <= old_size <= new_size:
            raise ValueError(f"old_size {old_size} is not in [0, {new_size}]")
        return serve_consistency(conn, tables, chain, old_size, new_size)

inclusion_proof

inclusion_proof(
    conn: Connection,
    tables: LedgerTables,
    chain: str,
    seq: int,
    size: int | None = None,
) -> InclusionProof

The inclusion proof of the entry at seq in the tree of size.

Reads the state row and O(log size) stored hashes, in a READ ONLY transaction of its own, or in the connection's when it has one.

Parameters:

Name Type Description Default
conn Connection

The connection; a role that can read the ledger tables.

required
tables LedgerTables

The ledger tables.

required
chain str

The chain.

required
seq int

The entry's seq, from 1.

required
size int | None

The tree's size, at least seq; the chain's current size by default.

None

Returns:

Type Description
InclusionProof

The proof, with the leaf hash and the root of that size.

Raises:

Type Description
ValueError

There is no such chain, seq is not in [1, size], size is above the chain's size, or a stored node is missing.

TypeError

seq or size is not an int.

Source code in audit_trail/ledger/_proof.py
@explains_permissions
def inclusion_proof(
    conn: Connection,
    tables: LedgerTables,
    chain: str,
    seq: int,
    size: int | None = None,
) -> InclusionProof:
    """The inclusion proof of the entry at ``seq`` in the tree of ``size``.

    Reads the state row and O(log size) stored hashes, in a ``READ ONLY``
    transaction of its own, or in the connection's when it has one.

    Args:
        conn: The connection; a role that can read the ledger tables.
        tables: The ledger tables.
        chain: The chain.
        seq: The entry's ``seq``, from 1.
        size: The tree's size, at least ``seq``; the chain's current size
            by default.

    Returns:
        The proof, with the leaf hash and the root of that size.

    Raises:
        ValueError: There is no such chain, ``seq`` is not in ``[1, size]``,
            ``size`` is above the chain's size, or a stored node is missing.
        TypeError: ``seq`` or ``size`` is not an int.
    """
    _check_int(seq, "seq")
    with reading(conn, not conn.in_transaction()):
        current = read_state(conn, tables, chain).size
        size = _bounded(size, current, "size")
        if not 1 <= seq <= size:
            raise ValueError(f"seq {seq} is not in [1, {size}]")
        return serve_inclusion(conn, tables, chain, seq, size)

arecord_restore async

arecord_restore(
    conn: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    checkpoint_note: LedgerCheckpoint | str | None = None,
    *,
    journal: LedgerJournal | str | _Unset | None = _UNSET,
    kit: RestoreKit | str | None = None,
    verifier: SignatureVerifier,
    key_history: KeyHistory,
    proof: ConsistencyProof
    | Iterable[ConsistencyProof] = (),
    restored_size: int | None = None,
    actor: str | None = None,
    lock_timeout: str | None = None,
) -> RecordedRestore

Async record_restore, on an AsyncConnection; the same arguments.

Source code in audit_trail/ledger/_restore.py
@explains_permissions
async def arecord_restore(
    conn: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    checkpoint_note: LedgerCheckpoint | str | None = None,
    *,
    journal: LedgerJournal | str | _Unset | None = _UNSET,
    kit: RestoreKit | str | None = None,
    verifier: SignatureVerifier,
    key_history: KeyHistory,
    proof: ConsistencyProof | Iterable[ConsistencyProof] = (),
    restored_size: int | None = None,
    actor: str | None = None,
    lock_timeout: str | None = None,
) -> RecordedRestore:
    """Async ``record_restore``, on an ``AsyncConnection``; the same arguments."""
    return await conn.run_sync(
        lambda sync_conn: record_restore(
            sync_conn,
            tables,
            chain,
            checkpoint_note,
            journal=journal,
            kit=kit,
            verifier=verifier,
            key_history=key_history,
            proof=proof,
            restored_size=restored_size,
            actor=actor,
            lock_timeout=lock_timeout,
        )
    )

record_restore

record_restore(
    conn: Connection,
    tables: LedgerTables,
    chain: str,
    checkpoint_note: LedgerCheckpoint | str | None = None,
    *,
    journal: LedgerJournal | str | _Unset | None = _UNSET,
    kit: RestoreKit | str | None = None,
    verifier: SignatureVerifier,
    key_history: KeyHistory,
    proof: ConsistencyProof
    | Iterable[ConsistencyProof] = (),
    restored_size: int | None = None,
    actor: str | None = None,
    lock_timeout: str | None = None,
) -> RecordedRestore

Record a database restore in a chain, and erase again what it lost.

The operator runs it as the ledger owner after a restore, as a step of the restore runbook, with the newest signed checkpoint kept off the database, its journal and its proof: its RestoreKit as kit, or each as its own argument. Record the newest kit first: a second call with another note records a second restore (pass restored_size). Appends before it are fine. Erasures made after the kit's checkpoint are not erased again or reported: erase them again from your own log. See audit_trail.ledger._restore for what is proven and what is erased again. Before it writes, it checks:

  • the note reads as a ledger checkpoint of this chain, signed, every signature of a key verifier knows verifies, and each such key is valid at the checkpoint's size in key_history;
  • the journal, when given, is the one the checkpoint's journal line commits to, of this chain at the checkpoint's size;
  • each step of proof leads from the root the step before established, the first from the stored tree's root at its old size, and the last ends at the checkpoint's root.

A role granted EXECUTE on the function can call it with any note; verify fails a ledger.restored entry whose checkpoint is not signed by a trusted key, given verifier and key_history, and each re-applied receipt that is not in the journal the checkpoint commits to.

Then audit_ledger_record_restore, a SECURITY DEFINER function, takes the chain's lock (after restore detection, as an append does), works out the incarnation, the restored size and the proven prefix, checks what it can again in SQL, and appends ledger.restored and the re-applied receipts.

Runs in the connection's current transaction; the caller commits. Only the owner of the ledger functions may call it, unless EXECUTE on audit_ledger_record_restore is granted separately: it deletes payload, and the function cannot check signatures.

Parameters:

Name Type Description Default
conn Connection

Connection to run on.

required
tables LedgerTables

The ledger tables.

required
chain str

The chain.

required
checkpoint_note LedgerCheckpoint | str | None

The signed checkpoint, or its note text; not with kit.

None
journal LedgerJournal | str | _Unset | None

The checkpoint's journal (LedgerJournal or its to_json() text), or None to erase nothing again; required without kit, not with it.

_UNSET
kit RestoreKit | str | None

The checkpoint's RestoreKit, or its to_json() text, in place of checkpoint_note and journal: its note, its journal and its proof steps.

None
verifier SignatureVerifier

Checks the note's signatures.

required
key_history KeyHistory

The window of each key, by chain seq.

required
proof ConsistencyProof | Iterable[ConsistencyProof]

Consistency proofs taken before the restore, from a size the chain still holds to the checkpoint's size, one or a chain of them in order; none proves nothing above the restored size. With kit, the steps before the kit's own, such as an older kit's, when the restore went below where the kit's proof starts.

()
restored_size int | None

The size the restore brought the chain back to, when restore detection did not see it and appends followed it: without it, the chain's size is taken, and a checkpoint at or below that size is refused as not the chain's. When detection started the incarnation, it must be the size before.

None
actor str | None

The actor of the entries appended.

None
lock_timeout str | None

The lock_timeout for the call; None keeps the transaction's. It bounds each lock wait, not the whole call.

None

Returns:

Type Description
RecordedRestore

The ledger.restored entry, what it records, and the erasures.

Raises:

Type Description
NoteError

The note is not a ledger checkpoint (MALFORMED), a signature does not verify (BAD_SIGNATURE), or none is of a key the verifier knows (UNKNOWN_KEY).

RestoreRefusedError

A check refused it, or the kit's text is not a restore kit.

LedgerBusyError

The lock was not granted within lock_timeout.

ValueError

The chain name is refused, the connection is in AUTOCOMMIT, or there is no such chain.

TypeError

An argument has the wrong type, or kit is given with checkpoint_note or journal, or neither is given.

Source code in audit_trail/ledger/_restore.py
@explains_permissions
def record_restore(
    conn: Connection,
    tables: LedgerTables,
    chain: str,
    checkpoint_note: LedgerCheckpoint | str | None = None,
    *,
    journal: LedgerJournal | str | _Unset | None = _UNSET,
    kit: RestoreKit | str | None = None,
    verifier: SignatureVerifier,
    key_history: KeyHistory,
    proof: ConsistencyProof | Iterable[ConsistencyProof] = (),
    restored_size: int | None = None,
    actor: str | None = None,
    lock_timeout: str | None = None,
) -> RecordedRestore:
    """Record a database restore in a chain, and erase again what it lost.

    The operator runs it as the ledger owner after a restore, as a step of
    the restore runbook, with the newest signed checkpoint kept off the
    database, its journal and its proof: its ``RestoreKit`` as ``kit``, or
    each as its own argument. Record the newest kit first: a second call
    with another note records a second restore (pass ``restored_size``).
    Appends before it are fine. Erasures made after the kit's checkpoint
    are not erased again or reported: erase them again from your own log.
    See ``audit_trail.ledger._restore`` for what is proven and what is
    erased again. Before it writes, it checks:

    - the note reads as a ledger checkpoint of this chain, signed, every
      signature of a key ``verifier`` knows verifies, and each such key is
      valid at the checkpoint's size in ``key_history``;
    - the journal, when given, is the one the checkpoint's journal line
      commits to, of this chain at the checkpoint's size;
    - each step of ``proof`` leads from the root the step before
      established, the first from the stored tree's root at its old size,
      and the last ends at the checkpoint's root.

    A role granted ``EXECUTE`` on the function can call it with any note;
    ``verify`` fails a ``ledger.restored`` entry whose checkpoint is not
    signed by a trusted key, given ``verifier`` and ``key_history``, and
    each re-applied receipt that is not in the journal the checkpoint
    commits to.

    Then ``audit_ledger_record_restore``, a ``SECURITY DEFINER`` function,
    takes the chain's lock (after restore detection, as an append does),
    works out the incarnation, the restored size and the proven prefix,
    checks what it can again in SQL, and appends ``ledger.restored`` and
    the re-applied receipts.

    Runs in the connection's current transaction; the caller commits. Only
    the owner of the ledger functions may call it, unless ``EXECUTE`` on
    ``audit_ledger_record_restore`` is granted separately: it deletes
    payload, and the function cannot check signatures.

    Args:
        conn: Connection to run on.
        tables: The ledger tables.
        chain: The chain.
        checkpoint_note: The signed checkpoint, or its note text; not with
            ``kit``.
        journal: The checkpoint's journal (``LedgerJournal`` or its
            ``to_json()`` text), or ``None`` to erase nothing again;
            required without ``kit``, not with it.
        kit: The checkpoint's ``RestoreKit``, or its ``to_json()`` text, in
            place of ``checkpoint_note`` and ``journal``: its note, its
            journal and its proof steps.
        verifier: Checks the note's signatures.
        key_history: The window of each key, by chain ``seq``.
        proof: Consistency proofs taken before the restore, from a size the
            chain still holds to the checkpoint's size, one or a chain of
            them in order; none proves nothing above the restored size.
            With ``kit``, the steps before the kit's own, such as an older
            kit's, when the restore went below where the kit's proof
            starts.
        restored_size: The size the restore brought the chain back to, when
            restore detection did not see it and appends followed it: without
            it, the chain's size is taken, and a checkpoint at or below that
            size is refused as not the chain's. When detection started the
            incarnation, it must be the size before.
        actor: The ``actor`` of the entries appended.
        lock_timeout: The ``lock_timeout`` for the call; ``None`` keeps the
            transaction's. It bounds each lock wait, not the whole call.

    Returns:
        The ``ledger.restored`` entry, what it records, and the erasures.

    Raises:
        NoteError: The note is not a ledger checkpoint (``MALFORMED``), a
            signature does not verify (``BAD_SIGNATURE``), or none is of a
            key the verifier knows (``UNKNOWN_KEY``).
        RestoreRefusedError: A check refused it, or the kit's text is not a
            restore kit.
        LedgerBusyError: The lock was not granted within ``lock_timeout``.
        ValueError: The chain name is refused, the connection is in
            ``AUTOCOMMIT``, or there is no such chain.
        TypeError: An argument has the wrong type, or ``kit`` is given with
            ``checkpoint_note`` or ``journal``, or neither is given.
    """
    _schema.check_chain(chain)
    checkpoint_note, journal, proof = _arguments(checkpoint_note, journal, kit, proof)
    checkpoint = trusted_checkpoint(
        checkpoint_note, chain, verifier, key_history, RestoreRefusedError
    )
    kept = _journal_of(journal, checkpoint)
    steps = _steps(proof, chain, checkpoint)
    if restored_size is not None and (not is_int(restored_size) or restored_size < 1):
        raise TypeError("restored_size must be a positive int")
    if actor is not None and not isinstance(actor, str):
        raise TypeError("actor must be a str")
    _pg.check_transactional(conn, "record_restore")
    proven_size, proven_root, proof_json = _proven(
        conn, tables, chain, checkpoint, steps
    )
    function = _migrations.function_name(tables, _schema.RECORD_RESTORE_FUNCTION)
    statement = text(
        "SELECT incarnation, seq, leaf_hash, size, root, created FROM "
        f"{function}(CAST(:chain AS text), CAST(:note AS text), "
        "CAST(:journal AS text), CAST(:restored AS bigint), "
        "CAST(:proven AS bigint), CAST(:proven_root AS bytea), "
        "CAST(:proof AS text), CAST(:actor AS text))"
    )
    parameters = {
        "chain": chain,
        "note": checkpoint.to_note(),
        "journal": None if kept is None else kept.to_json(),
        "restored": restored_size,
        "proven": proven_size,
        "proven_root": proven_root,
        "proof": proof_json,
        "actor": actor,
    }
    with _lock_timeout(conn, lock_timeout):
        try:
            rows = conn.execute(statement, parameters).all()
        except DBAPIError as exc:
            if _pg.is_sqlstate(exc, _pg.LOCK_NOT_AVAILABLE):
                raise LedgerBusyError(
                    f"ledger chain {chain!r} is busy: its lock was not granted "
                    "within lock_timeout"
                ) from exc
            if _pg.is_sqlstate(exc, _NO_DATA_FOUND):
                raise ValueError(f"there is no ledger chain named {chain!r}") from exc
            if _pg.is_sqlstate(
                exc, _pg.OBJECT_NOT_IN_PREREQUISITE_STATE
            ) or _pg.is_sqlstate(exc, _INVALID_PARAMETER_VALUE):
                raise RestoreRefusedError(_message(exc)) from exc
            raise
    return _recorded(conn, tables, chain, checkpoint, kept, rows)

build_ledger_tables

build_ledger_tables(
    metadata: MetaData | None = None,
    *,
    schema: str = "audit",
) -> LedgerTables

Declare the ledger tables in metadata.

The tables are independent of the audit tables: a ledger needs no AuditTrail, and the two can share a schema and a transaction. Create them with create_ledger_tables, which also installs the functions that write them.

  • audit_ledger_state, one row per chain: its incarnation, the tree size, root and frontier (the roots of the perfect subtrees of the tree, largest first, one per set bit of size), the last_appended_at time, and the cluster identity read when the chain was created: system_identifier (pg_control_system()), timeline (from pg_walfile_name(pg_current_wal_lsn())), table_oid (of this table) and server_major. They are null when the chain's config turns restore detection off, and are all null or all set.
  • audit_ledger_entry, one row per entry: (chain, seq) is the key, body the canonical bytes as written, leaf_hash the Merkle leaf, and entry_id, type, type_version, declared_at, actor and attributes copies of the body's fields for queries. A partial index lists the ledger.erased receipts of a chain by the entry_id they erase; create_ledger_tables adds it to an install made before it.
  • audit_ledger_payload, the erasable part: per entry and group, the salt and the canonical bytes of the value the body commits to.
  • audit_ledger_node: per chain, the hash of every closed subtree of level 1 and up. Node (level, index) is the Merkle tree hash of the leaves [index * 2**level, (index + 1) * 2**level), by 0-based leaf index (seq - 1); level 0 is the entry's leaf_hash.
  • audit_ledger_config, one row per chain: the reason codes, protected types, precondition function and restore-detection setting recorded in the chain's ledger.chain_started entry, and the recorded_seq of the entry that set them.

Parameters:

Name Type Description Default
metadata MetaData | None

Metadata to declare them in; a new one by default.

None
schema str

Schema of the tables and of the ledger functions.

'audit'

Returns:

Type Description
LedgerTables

The tables.

Raises:

Type Description
ValueError

schema is empty, longer than 63 bytes, or holds a $, which would end the dollar-quoted function bodies.

Source code in audit_trail/ledger/_schema.py
def build_ledger_tables(
    metadata: MetaData | None = None, *, schema: str = "audit"
) -> LedgerTables:
    """Declare the ledger tables in ``metadata``.

    The tables are independent of the audit tables: a ledger needs no
    ``AuditTrail``, and the two can share a schema and a transaction. Create
    them with ``create_ledger_tables``, which also installs the functions
    that write them.

    - ``audit_ledger_state``, one row per chain: its incarnation, the tree
      ``size``, ``root`` and ``frontier`` (the roots of the perfect subtrees
      of the tree, largest first, one per set bit of ``size``), the
      ``last_appended_at`` time, and the cluster identity read when the
      chain was created: ``system_identifier`` (``pg_control_system()``),
      ``timeline`` (from ``pg_walfile_name(pg_current_wal_lsn())``),
      ``table_oid`` (of this table) and ``server_major``. They are null
      when the chain's config turns restore detection off, and are all
      null or all set.
    - ``audit_ledger_entry``, one row per entry: ``(chain, seq)`` is the
      key, ``body`` the canonical bytes as written, ``leaf_hash`` the
      Merkle leaf, and ``entry_id``, ``type``, ``type_version``,
      ``declared_at``, ``actor`` and ``attributes`` copies of the body's
      fields for queries. A partial index lists the ``ledger.erased``
      receipts of a chain by the ``entry_id`` they erase;
      ``create_ledger_tables`` adds it to an install made before it.
    - ``audit_ledger_payload``, the erasable part: per entry and group, the
      salt and the canonical bytes of the value the body commits to.
    - ``audit_ledger_node``: per chain, the hash of every closed subtree of
      level 1 and up. Node ``(level, index)`` is the Merkle tree hash of the
      leaves ``[index * 2**level, (index + 1) * 2**level)``, by 0-based leaf
      index (``seq - 1``); level 0 is the entry's ``leaf_hash``.
    - ``audit_ledger_config``, one row per chain: the reason codes,
      protected types, precondition function and restore-detection setting
      recorded in the chain's ``ledger.chain_started`` entry, and the
      ``recorded_seq`` of the entry that set them.

    Args:
        metadata: Metadata to declare them in; a new one by default.
        schema: Schema of the tables and of the ledger functions.

    Returns:
        The tables.

    Raises:
        ValueError: ``schema`` is empty, longer than 63 bytes, or holds a
            ``$``, which would end the dollar-quoted function bodies.
    """
    if not schema or len(schema.encode()) > 63:
        raise ValueError("schema must be 1 to 63 bytes")
    if "$" in schema:
        raise ValueError("schema may not hold a '$'")
    if metadata is None:
        metadata = MetaData()
    state = Table(
        STATE_TABLE,
        metadata,
        Column("chain", Text, nullable=False),
        Column("incarnation", Integer, nullable=False),
        Column("size", BigInteger, nullable=False),
        Column("root", BYTEA, nullable=False),
        Column("frontier", ARRAY(BYTEA), nullable=False),
        Column("last_appended_at", DateTime(timezone=True)),
        Column("system_identifier", BigInteger),
        Column("timeline", BigInteger),
        Column("table_oid", BigInteger),
        Column("server_major", Integer),
        Column(
            "created_at",
            DateTime(timezone=True),
            nullable=False,
            server_default=text("now()"),
        ),
        PrimaryKeyConstraint("chain", name=f"{STATE_TABLE}_pkey"),
        CheckConstraint(
            f"chain ~ '{CHAIN_PATTERN}'", name=f"{STATE_TABLE}_chain_check"
        ),
        CheckConstraint("size >= 0", name=f"{STATE_TABLE}_size_check"),
        # The cluster identity is stored whole or not at all.
        CheckConstraint(
            "num_nulls(system_identifier, timeline, table_oid, server_major) IN (0, 4)",
            name=f"{STATE_TABLE}_identity_check",
        ),
        schema=schema,
    )
    entry = Table(
        ENTRY_TABLE,
        metadata,
        Column("chain", Text, nullable=False),
        Column("seq", BigInteger, nullable=False),
        Column("incarnation", Integer, nullable=False),
        Column("entry_id", UUID(as_uuid=True), nullable=False),
        Column("type", Text, nullable=False),
        Column("type_version", Integer, nullable=False),
        Column("declared_at", DateTime(timezone=True), nullable=False),
        Column("actor", Text),
        Column("appended_at", DateTime(timezone=True), nullable=False),
        Column("attributes", JSONB, nullable=False),
        Column("body", BYTEA, nullable=False),
        Column("leaf_hash", BYTEA, nullable=False),
        PrimaryKeyConstraint("chain", "seq", name=f"{ENTRY_TABLE}_pkey"),
        UniqueConstraint("entry_id", name=f"{ENTRY_TABLE}_entry_id_key"),
        ForeignKeyConstraint(
            ["chain"], [state.c.chain], name=f"{ENTRY_TABLE}_chain_fkey"
        ),
        CheckConstraint("seq >= 1", name=f"{ENTRY_TABLE}_seq_check"),
        schema=schema,
    )
    # The receipts of a chain, by the entry they erase: verify lists them,
    # and the journal of a checkpoint is built from them.
    Index(
        f"{ENTRY_TABLE}_erased_idx",
        entry.c.chain,
        entry.c.attributes["entry_id"].astext,
        postgresql_where=text("type = 'ledger.erased'"),
    )
    payload = Table(
        PAYLOAD_TABLE,
        metadata,
        Column("chain", Text, nullable=False),
        Column("seq", BigInteger, nullable=False),
        Column("group_name", Text, nullable=False),
        Column("salt", BYTEA, nullable=False),
        Column("value", BYTEA, nullable=False),
        PrimaryKeyConstraint(
            "chain", "seq", "group_name", name=f"{PAYLOAD_TABLE}_pkey"
        ),
        ForeignKeyConstraint(
            ["chain", "seq"],
            [entry.c.chain, entry.c.seq],
            name=f"{PAYLOAD_TABLE}_entry_fkey",
        ),
        schema=schema,
    )
    node = Table(
        NODE_TABLE,
        metadata,
        Column("chain", Text, nullable=False),
        Column("level", SmallInteger, nullable=False),
        Column("index", BigInteger, nullable=False),
        Column("hash", BYTEA, nullable=False),
        PrimaryKeyConstraint("chain", "level", "index", name=f"{NODE_TABLE}_pkey"),
        ForeignKeyConstraint(
            ["chain"], [state.c.chain], name=f"{NODE_TABLE}_chain_fkey"
        ),
        CheckConstraint("level >= 1 AND index >= 0", name=f"{NODE_TABLE}_check"),
        schema=schema,
    )
    config = Table(
        CONFIG_TABLE,
        metadata,
        Column("chain", Text, nullable=False),
        Column("reason_codes", ARRAY(Text), nullable=False),
        Column("protected_types", ARRAY(Text), nullable=False),
        Column("precondition", Text),
        Column("detect_restores", Boolean, nullable=False),
        Column("recorded_seq", BigInteger, nullable=False),
        PrimaryKeyConstraint("chain", name=f"{CONFIG_TABLE}_pkey"),
        ForeignKeyConstraint(
            ["chain"], [state.c.chain], name=f"{CONFIG_TABLE}_chain_fkey"
        ),
        schema=schema,
    )
    return LedgerTables(
        metadata=metadata,
        schema=schema,
        entry=entry,
        state=state,
        payload=payload,
        node=node,
        config=config,
    )

aconfirm_upgrade async

aconfirm_upgrade(
    connection: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    seq: int,
    *,
    actor: str | None = None,
    lock_timeout: str | None = None,
) -> Head

Async confirm_upgrade, on an AsyncConnection; the same arguments.

Source code in audit_trail/ledger/_upgrade.py
@explains_permissions
async def aconfirm_upgrade(
    connection: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    seq: int,
    *,
    actor: str | None = None,
    lock_timeout: str | None = None,
) -> Head:
    """Async ``confirm_upgrade``, on an ``AsyncConnection``; the same arguments."""
    return await connection.run_sync(
        lambda sync_conn: confirm_upgrade(
            sync_conn, tables, chain, seq, actor=actor, lock_timeout=lock_timeout
        )
    )

confirm_upgrade

confirm_upgrade(
    connection: Connection,
    tables: LedgerTables,
    chain: str,
    seq: int,
    *,
    actor: str | None = None,
    lock_timeout: str | None = None,
) -> Head

Append ledger.upgrade_confirmed, confirming a cluster change.

Confirm a ledger.cluster_changed entry only after checking that the chain still holds what a checkpoint taken just before the upgrade holds, with verify(..., checkpoints=[that checkpoint]): restore detection cannot tell a pg_upgrade from a data-only restore of an older dump into a fresh cluster of a higher major version, which loses the entries written after the dump. Until then a verifier notes the entry UNCONFIRMED_UPGRADE. Appends go on either way.

The entry's attributes are the entry_id, incarnation and seq of the entry it confirms. Runs in the connection's current transaction, under the chain's lock, as append_many does; the caller commits. It calls audit_ledger_confirm_upgrade, which by default only the owner of the ledger functions may execute.

Parameters:

Name Type Description Default
connection Connection

Connection to run on.

required
tables LedgerTables

The ledger tables.

required
chain str

The chain's name.

required
seq int

The seq of the ledger.cluster_changed entry.

required
actor str | None

The actor of the entry, at most MAX_ACTOR_LENGTH characters.

None
lock_timeout str | None

The lock_timeout for the call; None keeps the transaction's.

None

Returns:

Type Description
Head

The head after the entry.

Raises:

Type Description
LedgerBusyError

The lock was not granted within lock_timeout.

ValueError

The chain name, seq or the actor is refused, the connection is in AUTOCOMMIT, there is no such chain, the entry at seq is missing or not a ledger.cluster_changed, or it is confirmed already (the transaction is then aborted).

TypeError

actor is not a str or None.

Source code in audit_trail/ledger/_upgrade.py
@explains_permissions
def confirm_upgrade(
    connection: Connection,
    tables: LedgerTables,
    chain: str,
    seq: int,
    *,
    actor: str | None = None,
    lock_timeout: str | None = None,
) -> Head:
    """Append ``ledger.upgrade_confirmed``, confirming a cluster change.

    Confirm a ``ledger.cluster_changed`` entry only after checking that the
    chain still holds what a checkpoint taken just before the upgrade
    holds, with ``verify(..., checkpoints=[that checkpoint])``: restore
    detection cannot tell a ``pg_upgrade`` from a data-only restore of an
    older dump into a fresh cluster of a higher major version, which loses
    the entries written after the dump. Until then a verifier notes the
    entry ``UNCONFIRMED_UPGRADE``. Appends go on either way.

    The entry's attributes are the ``entry_id``, ``incarnation`` and
    ``seq`` of the entry it confirms. Runs in the connection's current
    transaction, under the chain's lock, as ``append_many`` does; the
    caller commits. It calls ``audit_ledger_confirm_upgrade``, which by
    default only the owner of the ledger functions may execute.

    Args:
        connection: Connection to run on.
        tables: The ledger tables.
        chain: The chain's name.
        seq: The ``seq`` of the ``ledger.cluster_changed`` entry.
        actor: The ``actor`` of the entry, at most ``MAX_ACTOR_LENGTH``
            characters.
        lock_timeout: The ``lock_timeout`` for the call; ``None`` keeps the
            transaction's.

    Returns:
        The head after the entry.

    Raises:
        LedgerBusyError: The lock was not granted within ``lock_timeout``.
        ValueError: The chain name, ``seq`` or the actor is refused, the
            connection is in ``AUTOCOMMIT``, there is no such chain, the
            entry at ``seq`` is missing or not a ``ledger.cluster_changed``,
            or it is confirmed already (the transaction is then aborted).
        TypeError: ``actor`` is not a ``str`` or ``None``.
    """
    _schema.check_chain(chain)
    if not is_int(seq) or seq < 1:
        raise ValueError(f"seq must be an integer of at least 1, not {seq!r}")
    _schema.check_actor(actor)
    if actor is not None:
        canonical(actor)  # refuses what has no canonical encoding
    _pg.check_transactional(connection, "confirm_upgrade")
    function = _migrations.function_name(tables, _schema.CONFIRM_UPGRADE_FUNCTION)
    statement = text(
        "SELECT incarnation, seq, leaf_hash, size, root FROM "
        f"{function}(CAST(:chain AS text), CAST(:seq AS bigint), "
        "CAST(:actor AS text))"
    )
    parameters = {"chain": chain, "seq": seq, "actor": actor}
    return _call(connection, chain, statement, parameters, lock_timeout, ValueError)

averify async

averify(
    conn: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    *,
    since: LedgerReport | None = None,
    checkpoints: Iterable[LedgerCheckpoint | str] = (),
    chunk_rows: int = DEFAULT_CHUNK_ROWS,
    verifier: SignatureVerifier | None = None,
    key_history: KeyHistory | None = None,
    require_signatures: bool = False,
) -> LedgerReport

Async verify, on an AsyncConnection; the same arguments.

Source code in audit_trail/ledger/_verify_db.py
@explains_permissions
async def averify(
    conn: AsyncConnection,
    tables: LedgerTables,
    chain: str,
    *,
    since: LedgerReport | None = None,
    checkpoints: Iterable[LedgerCheckpoint | str] = (),
    chunk_rows: int = DEFAULT_CHUNK_ROWS,
    verifier: SignatureVerifier | None = None,
    key_history: KeyHistory | None = None,
    require_signatures: bool = False,
) -> LedgerReport:
    """Async ``verify``, on an ``AsyncConnection``; the same arguments."""
    return await conn.run_sync(
        lambda sync_conn: verify(
            sync_conn,
            tables,
            chain,
            since=since,
            checkpoints=checkpoints,
            chunk_rows=chunk_rows,
            verifier=verifier,
            key_history=key_history,
            require_signatures=require_signatures,
        )
    )

verify

verify(
    conn: Connection,
    tables: LedgerTables,
    chain: str,
    *,
    since: LedgerReport | None = None,
    checkpoints: Iterable[LedgerCheckpoint | str] = (),
    chunk_rows: int = DEFAULT_CHUNK_ROWS,
    verifier: SignatureVerifier | None = None,
    key_history: KeyHistory | None = None,
    require_signatures: bool = False,
) -> LedgerReport

Check a chain from its stored rows; report every failure and note.

Recomputes each entry's leaf from its header columns and body bytes, the tree from the leaves, and compares them with the stored leaf hashes, every stored node the entries close, and the state row's root, frontier, incarnation and last append time. Checks that seq is gapless from a first ledger.chain_started entry, that each body is canonical and its columns copy it, that each payload row matches its commitment and a missing one has a ledger.erased receipt, the package's own entries by type (ledger.checkpoint entries: the note, the head against the tree, the journal line, and with verifier the signatures), and the config table against the newest config entry. See audit_trail.ledger._verify for every finding.

Reads the state row first, and checks the chain up to the size it names, so the report's head is a head the run verified. It takes no lock: appends may go on during the run. A connection outside a transaction is read in short READ ONLY transactions, one per chunk; one inside a transaction is read in it.

Parameters:

Name Type Description Default
conn Connection

The connection; a role that can read the ledger tables.

required
tables LedgerTables

The ledger tables.

required
chain str

The chain.

required
since LedgerReport | None

An earlier report of this chain without failures. Its head must be a head of the stored tree: the stored frontier of its size must give its root, and a consistency proof from the stored nodes must lead from it to the current root, or the run fails with CHAIN_MISMATCH (TRUNCATED when the chain is shorter now). Then only the entries after it are read and checked, from that frontier; the entries before it are left to the next full run. report.since names the size it started from.

None
checkpoints Iterable[LedgerCheckpoint | str]

Trusted checkpoints, kept off the database host, as LedgerCheckpoint objects or note texts, such as the signed notes of your restore kits. Each must name this chain and a head of the stored tree, in the incarnation its origin names, checked as since's head is: a chain shorter than one is TRUNCATED, another root or incarnation at its size is CHAIN_MISMATCH. With verifier, a signed checkpoint must verify (BAD_SIGNATURE, UNKNOWN_KEY), each key in its window of key_history (KEY_NOT_VALID, KEY_COMPROMISED), or it is not used; an unsigned one is taken on your word, unless require_signatures is set. The report is ANCHORED when one matched, and the entries after the largest one that matched are an UNANCHORED_TAIL note. This is what shows a chain rewritten whole, hashes and all: verify alone checks the chain only against itself.

()
chunk_rows int

Entries, or nodes of one level, read per transaction; at least 1.

DEFAULT_CHUNK_ROWS
verifier SignatureVerifier | None

Checks the signatures of ledger.checkpoint entries: each signature of a key it knows must verify. Without it, each checkpoint is an UNCHECKED_SIGNATURES note, as one is with no signature of a key it knows.

None
key_history KeyHistory | None

With verifier, the window of each key, by chain seq: a key must be valid at the size its checkpoint names (KEY_NOT_VALID, KEY_COMPROMISED).

None
require_signatures bool

Every checkpoint the run relies on must be signed by a key verifier knows, as with verify_bundle(require_signatures=True): an unsigned one of checkpoints fails with BAD_SIGNATURE and is not used, and the checkpoint of a ledger.restored entry, which its re-applied erasures are trusted through, fails with RESTORE_MISMATCH unless a key verifier knows signed it. A ledger.checkpoint entry is not relied on: one without a signature of a known key stays an UNCHECKED_SIGNATURES note, since the application role can record unsigned ones. Needs verifier.

False

Returns:

Type Description
LedgerReport

The report.

Raises:

Type Description
TypeError

chunk_rows is not an int.

ValueError

There is no such chain, chunk_rows is below 1, since is not a clean report of this chain, a checkpoint text is not a ledger checkpoint (a NoteError), or key_history or require_signatures is given without verifier.

Source code in audit_trail/ledger/_verify_db.py
@explains_permissions
def verify(
    conn: Connection,
    tables: LedgerTables,
    chain: str,
    *,
    since: LedgerReport | None = None,
    checkpoints: Iterable[LedgerCheckpoint | str] = (),
    chunk_rows: int = DEFAULT_CHUNK_ROWS,
    verifier: SignatureVerifier | None = None,
    key_history: KeyHistory | None = None,
    require_signatures: bool = False,
) -> LedgerReport:
    """Check a chain from its stored rows; report every failure and note.

    Recomputes each entry's leaf from its header columns and body bytes,
    the tree from the leaves, and compares them with the stored leaf
    hashes, every stored node the entries close, and the state row's root,
    frontier, incarnation and last append time. Checks that ``seq`` is
    gapless from a first ``ledger.chain_started`` entry, that each body is
    canonical and its columns copy it, that each payload row matches its
    commitment and a missing one has a ``ledger.erased`` receipt, the
    package's own entries by type (``ledger.checkpoint`` entries: the note,
    the head against the tree, the journal line, and with ``verifier`` the
    signatures), and the config table against the newest config entry. See
    ``audit_trail.ledger._verify`` for every finding.

    Reads the state row first, and checks the chain up to the size it
    names, so the report's ``head`` is a head the run verified. It takes no
    lock: appends may go on during the run. A connection outside a
    transaction is read in short ``READ ONLY`` transactions, one per chunk;
    one inside a transaction is read in it.

    Args:
        conn: The connection; a role that can read the ledger tables.
        tables: The ledger tables.
        chain: The chain.
        since: An earlier report of this chain without failures. Its head
            must be a head of the stored tree: the stored frontier of its
            size must give its root, and a consistency proof from the stored
            nodes must lead from it to the current root, or the run fails
            with ``CHAIN_MISMATCH`` (``TRUNCATED`` when the chain is shorter
            now). Then only the entries after it are read and checked, from
            that frontier; the entries before it are left to the next full
            run. ``report.since`` names the size it started from.
        checkpoints: Trusted checkpoints, kept off the database host, as
            ``LedgerCheckpoint`` objects or note texts, such as the signed
            notes of your restore kits. Each must name this chain and a
            head of the stored tree, in the incarnation its origin names,
            checked as ``since``'s head is: a chain shorter than one is
            ``TRUNCATED``, another root or incarnation at its size is
            ``CHAIN_MISMATCH``. With ``verifier``, a signed checkpoint must
            verify (``BAD_SIGNATURE``, ``UNKNOWN_KEY``), each key in its
            window of ``key_history`` (``KEY_NOT_VALID``,
            ``KEY_COMPROMISED``), or it is not used; an unsigned one is
            taken on your word, unless ``require_signatures`` is set. The
            report is ``ANCHORED`` when one matched, and the entries after
            the largest one that matched are an ``UNANCHORED_TAIL`` note.
            This is what shows a chain rewritten whole, hashes and all:
            ``verify`` alone checks the chain only against itself.
        chunk_rows: Entries, or nodes of one level, read per transaction;
            at least 1.
        verifier: Checks the signatures of ``ledger.checkpoint`` entries:
            each signature of a key it knows must verify. Without it, each
            checkpoint is an ``UNCHECKED_SIGNATURES`` note, as one is with
            no signature of a key it knows.
        key_history: With ``verifier``, the window of each key, by chain
            ``seq``: a key must be valid at the size its checkpoint names
            (``KEY_NOT_VALID``, ``KEY_COMPROMISED``).
        require_signatures: Every checkpoint the run relies on must be
            signed by a key ``verifier`` knows, as with
            ``verify_bundle(require_signatures=True)``: an unsigned one of
            ``checkpoints`` fails with ``BAD_SIGNATURE`` and is not used,
            and the checkpoint of a ``ledger.restored`` entry, which its
            re-applied erasures are trusted through, fails with
            ``RESTORE_MISMATCH`` unless a key ``verifier`` knows signed it.
            A ``ledger.checkpoint`` entry is not relied on: one without a
            signature of a known key stays an ``UNCHECKED_SIGNATURES``
            note, since the application role can record unsigned ones.
            Needs ``verifier``.

    Returns:
        The report.

    Raises:
        TypeError: ``chunk_rows`` is not an int.
        ValueError: There is no such chain, ``chunk_rows`` is below 1,
            ``since`` is not a clean report of this chain, a checkpoint text
            is not a ledger checkpoint (a ``NoteError``), or
            ``key_history`` or ``require_signatures`` is given without
            ``verifier``.
    """
    _schema.check_chain(chain)
    if isinstance(chunk_rows, bool) or not isinstance(chunk_rows, int):
        raise TypeError("chunk_rows must be an int")
    if chunk_rows < 1:
        raise ValueError("chunk_rows must be at least 1")
    if key_history is not None and verifier is None:
        raise ValueError("key_history needs a verifier")
    if require_signatures and verifier is None:
        raise ValueError("require_signatures needs a verifier")
    if key_history is not None and not isinstance(key_history, KeyHistory):
        raise ValueError("key_history is a KeyHistory")
    trusted = read_checkpoints(checkpoints)
    old = _since_head(since, chain)
    own = not conn.in_transaction()
    with reading(conn, own):
        state = read_state(conn, tables, chain)
    start = Start()
    if old is not None:
        found = _after(conn, tables, chain, state, old, own)
        if isinstance(found, LedgerFinding):
            report = make_report(chain, state, [found], [], since=old.size, entries=0)
            return dataclasses.replace(report, anchor=Anchor.UNANCHORED)
        start = found
    checker = ChainVerifier(
        chain,
        state,
        _Source(conn, tables, chain, state.size, chunk_rows, own),
        start,
        since=None if old is None else old.size,
        verifier=verifier,
        key_history=key_history,
        require_signatures=require_signatures,
    )
    for entry in read_entries(
        conn,
        tables,
        chain,
        after=start.frontier.size,
        through=state.size,
        chunk_rows=chunk_rows,
        own=own,
    ):
        checker.add(entry)
    checker.finish()
    anchor = _anchor(conn, tables, chain, state, checker, trusted, own)
    return dataclasses.replace(checker.report(), anchor=anchor)