Skip to main content

sovereign-ledger

Immutable, local-first, hash-chained SQLite provenance engine for ForensicReceipt Write-Side Custody.

sovereign-ledger is a zero-external-dependency Python package that stores every ForensicReceipt produced by sovereign-core in a tamper-evident, append-only SQLite database. It enforces Write-Side Custody through two complementary mechanisms: engine-level SQL triggers that abort any UPDATE or DELETE at the SQLite layer, and a SHA-256 hash chain that makes out-of-band filesystem tampering mathematically detectable.

The ledger records evidence; it does not judge it. It reports whether an entry is signed, but it never verifies signatures; that remains sovereign-core's verify_receipt.


Installation

The distribution is sovereign-sdk-ledger; the import is sovereign_ledger.

pip install sovereign-sdk-ledger
uv add sovereign-sdk-ledger

Requires Python 3.12 or later. Zero runtime dependencies beyond the Python standard library.


Quick start

Runs as written; the in-memory store makes it repeatable.

import hashlib

from sovereign_ledger import IdempotencyKeyConflictError, SovereignLedger

content = "page unchanged"
receipt = {
    "payload_hash": hashlib.sha256(content.encode("utf-8")).hexdigest(),
    "timestamp": "2026-11-04T12:00:00+00:00",
    "signature": "c2lnbmF0dXJl",
}

with SovereignLedger(db_path=":memory:") as ledger:
    # Identical content is recorded once per append; the idempotency key makes a retry safe.
    monday = ledger.append_entry(receipt, content, idempotency_key="check-monday")
    ledger.append_entry(receipt, content, idempotency_key="check-friday")
    try:
        ledger.append_entry(receipt, content, idempotency_key="check-friday")
    except IdempotencyKeyConflictError as exc:
        print("retry rejected:", exc.idempotency_key)  # → retry rejected: check-friday

    # No signature recorded: an explicit, hashed UNSIGNED entry.
    ledger.append_entry({"payload_hash": receipt["payload_hash"], "timestamp": receipt["timestamp"]}, content)

    # Read back, verified from the Point of Genesis.
    for entry in ledger.iter_entries():
        print(entry.sequence, entry.signature_status.value, entry.idempotency_key)
    # → 1 SIGNED check-monday
    # → 2 SIGNED check-friday
    # → 3 UNSIGNED None

    tip = ledger.get_tip()
    print(tip.sequence)  # → 3

    # Structured verification, anchored to an externally persisted tip.
    report = ledger.verify_ledger(expected_tip=monday)
    print(report.verified, report.entries_checked, report.tip == tip)  # → True 3 True

API reference

All names are importable from sovereign_ledger. The full reference, including the entry format and the migration procedure, is in docs/sovereign-ledger.md.

SovereignLedger(db_path=".keys/sovereign_audit.db")

Opens the SQLite database at db_path, applies WAL journal mode, NORMAL synchronous enforcement, strict foreign-key constraints and a 5-second busy_timeout, then creates the forensic_ledger schema and Write-Side Custody triggers, or migrates a 1.3.0 file once (see below). Pass ":memory:" for an ephemeral in-process store.

Supports the Python context manager protocol; use a with block to guarantee all thread-local connection handles are released on exit.

append_entry(receipt, sieved_content, *, idempotency_key=None, signer_key_id=None) -> LedgerTip

Appends a format version 2 entry inside a BEGIN IMMEDIATE transaction and returns its LedgerTip (sequence number and entry hash). A missing or None receipt["signature"] records an explicitly UNSIGNED entry; an empty-string signature raises ValueError. Identical content is recorded once per append. A repeated idempotency_key raises IdempotencyKeyConflictError (an sqlite3.IntegrityError) and leaves the ledger unchanged.

append_receipt(receipt: dict, sieved_content: str) -> str

The 1.3.0 append. Writes the same format version 2 entry as append_entry and returns receipt["payload_hash"]. Identical content is no longer rejected, so the returned payload_hash does not identify an entry uniquely; use append_entry for a LedgerTip.

iter_entries(start_sequence=1, *, verify=True) -> Iterator[LedgerEntry]

Yields entries in sequence order. With verify=True every link is re-derived from the genesis constant, including links before start_sequence, and LedgerIntegrityError (carrying .sequence and .reason) is raised at the first failure; an entry that failed is never yielded. verify=False returns whatever is stored, tampered or not.

get_tip() -> LedgerTip | None

The last entry's sequence number and entry hash, as stored (unverified), or None.

verify_ledger(expected_tip=None) -> LedgerIntegrityReport

Full chain sweep returning verified, entries_checked, failure_sequence, failure_reason (an IntegrityFailureReason: BROKEN_LINK, SEQUENCE_GAP, UNSUPPORTED_FORMAT_VERSION, MALFORMED_ENTRY, TIP_MISMATCH) and the current tip. With expected_tip, a ledger cut short fails with TIP_MISMATCH.

verify_ledger_integrity(expected_tip_hash=None) -> bool

The 1.3.0 verification, unchanged: True when the chain verifies and, if supplied, the final entry's payload_hash equals expected_tip_hash. That anchor is ambiguous once identical content exists; prefer verify_ledger(expected_tip=...).

close()

Releases all thread-local SQLite connection handles tracked by this instance.

Exceptions and types

Name Purpose
LedgerTip, LedgerEntry, LedgerIntegrityReport Frozen dataclasses returned by the API
SignatureStatus SIGNED or UNSIGNED
IntegrityFailureReason Verification reason codes
LedgerIntegrityError First failure met by iter_entries
IdempotencyKeyConflictError Repeated idempotency key
LedgerMigrationError A 1.3.0 file failed verification and was not migrated
SovereignStorageError Closed instance or unrecognized schema

Upgrading from 1.3.0

The first open of a 1.3.0 file rebuilds its table once, in one transaction, to drop the UNIQUE constraint on payload_hash and add the version 2 columns. The existing chain is verified first; a file that fails verification is left untouched and LedgerMigrationError is raised. Every existing row keeps its id, values and entry hash.

Before migrating, the ledger writes and verifies a backup of the 1.3.0 file beside it, named <name>.v1-backup (or <name>.v1-backup.1, .2, ... if that name is taken; a backup is never overwritten). If the backup cannot be written or verified, the file is not migrated.

The migration is one-way, and the backup is the only route back to 1.3.0. Version 1.3.0 can still open a migrated file, but its verify_ledger_integrity() returns False once any entry follows a version 2 entry, and its appends are refused by a database trigger. Delete the backup once you are satisfied with the migrated file.

If you run sovereign-edge, drain its off-grid buffer before the first open on the new release. Edge now deduplicates replays by the receipt's signature, and receipts committed before migration carry no idempotency key, so an already-committed buffered receipt would be recorded twice.


Integration pattern

sovereign-ledger slots into the end of the Sovereign pipeline:

[Inbound Payload]
    → sovereign-sieve  (Prose Tax reduction)
    → sovereign-core   (Ed25519 sign → ForensicReceipt)
    → sovereign-ledger (append_entry → immutable audit record)
from sovereign_core import SovereignGateway
from sovereign_ledger import SovereignLedger

gateway = SovereignGateway(signing_key=".keys/sovereign_identity.pem")

with SovereignLedger(db_path=".keys/sovereign_audit.db") as ledger:
    response = await gateway.sieve_and_sign(raw_payload)
    tip = ledger.append_entry(response.receipt, response.content)
    assert ledger.verify_ledger(expected_tip=tip).verified

Metadata

Release files for sovereign-sdk-ledger 2.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for sovereign-sdk-ledger 2.0.0
File Size Uploaded Provenance Actions
sovereign_sdk_ledger-2.0.0.tar.gz 42.4 kB With provenance Details for sovereign_sdk_ledger-2.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for sovereign-sdk-ledger 2.0.0
File Interpreter ABI Platform Actions
sovereign_sdk_ledger-2.0.0-py3-none-any.whl Python 3 none any Details for sovereign_sdk_ledger-2.0.0-py3-none-any.whl

Total release size: 65.2 kB

Release files / sovereign_sdk_ledger-2.0.0.tar.gz

Download URL sovereign_sdk_ledger-2.0.0.tar.gz
Size 42.4 kB
Tags Source
SHA-256 checksum
How to use checksums
335e143a73dc9caa71151150bc37dd2c628c3d6a4bf1e117cf680069a650be57
BLAKE2b-256 checksum
How to use checksums
9b82705115cc8a6178dc5dd48aaaeb2474072af6c357336c359f26c2d5718c4e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 4, 2026.

Transparency log

Release files / sovereign_sdk_ledger-2.0.0-py3-none-any.whl

Download URL sovereign_sdk_ledger-2.0.0-py3-none-any.whl
Size 22.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b2a2235f585aee64fbd19fbfc56c181be654e84756c4fb2c4daa5f4e7d4cc1ad
BLAKE2b-256 checksum
How to use checksums
189aa26592af98ca3cd9dc3ea7638a84cc9315a1b7b7fa60706c5eb81a46d689
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 4, 2026.

Transparency log

Security for sovereign-sdk-ledger 2.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for sovereign_sdk_ledger-2.0.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 4, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

2.0.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page