Skip to content

burin.kernel

The where-when seal primitive: sign an opaque what commitment together with an optional cell (where) and time (when) into one offline-verifiable seal, chain seals into an append-only ledger, detect equivocation / backdating fraud, and degrade a seal to 24 words or a 70-byte burst.

Everything below is the public surface (burin.kernel.__all__).

Burin kernel — the where-when self-attestation primitive everything builds on.

A single, hardware-signed, offline-verifiable seal binding what + [where] + [when], accountable by construction (where and when are symmetric optional dimensions). Witnessing (ground, sky), plurality (k-of-n), disclosure (ZK), and aggregation (fold-to-constant) are branches that clip onto this trunk — they change who co-signs the where or what you reveal, never the kernel. (KERNEL.md is the spec.)

The library, end to end::

from burin.kernel import Identity, Ledger, commit, verify_seal

me   = Identity.generate()                       # a hardware-style signing key — *self*
root = commit([('Q', 4, 5, 3), ('Q', 4, 5, 7)], depth=4)   # the 'what' (coverage root)
seal = Ledger(me).seal(root, cell=('Q', 4, 5), time_us=1_000_000)   # sign what+where+when

record = seal.to_dict()                          # travels as JSON / QR / paper
report = verify_seal(record, trusted_pubkeys=[me.pubkey])   # offline, anywhere
assert report.ok

The seal's signed core is a burin.coverage.fraud.Attestation, so seals chain (append-only) and the fraud proofs (equivocation, backdating) apply unchanged — a signer is a memory, not an authority. This package depends only on the coverage engine (burin.coverage); the satellite sim (companion testbed) is a downstream consumer of the kernel, not the other way round.

Ledger dataclass

An identity's append-only seal log — the accountability backbone. Each seal assigns the next epoch, chains prev_hash, and enforces issuance monotonicity (an honest signer never backdates). Breaking either rule is self-evident fraud (burin.coverage.fraud); a second seal at the same epoch is equivocation. The signer is a memory, not an authority.

Source code in burin/kernel/seal.py
@dataclass
class Ledger:
    """An identity's append-only seal log — the accountability backbone. Each ``seal`` assigns the
    next epoch, chains ``prev_hash``, and enforces issuance monotonicity (an honest signer never
    backdates). Breaking either rule is self-evident fraud (``burin.coverage.fraud``); a second seal at the
    same epoch is equivocation. The signer is *a memory, not an authority*."""

    identity: Identity
    log: list[Attestation] = field(default_factory=list)

    def _next_prev_hash(self) -> bytes:
        return GENESIS_PREV if not self.log else keccak(self.log[-1].message())

    def seal(self, commitment: bytes, cell, time_us: int | None) -> Seal:
        prev_t = self.log[-1].issued_at if self.log else None
        if prev_t is not None and time_us is not None and time_us < prev_t:
            raise ValueError("issuance monotonicity: time_us must not decrease with epoch")
        s = make_seal(self.identity, commitment, cell, time_us,
                      epoch=len(self.log), prev_hash=self._next_prev_hash())
        self.log.append(s.attestation)
        return s

Seal dataclass

A self-attestation: the opening (what, where, when) plus the signed, append-only Attestation over the composite. Offline-verifiable from this object alone.

Source code in burin/kernel/seal.py
@dataclass(frozen=True)
class Seal:
    """A self-attestation: the opening (*what, where, when*) plus the signed, append-only
    ``Attestation`` over the composite. Offline-verifiable from this object alone."""

    commitment: bytes              # 32B — the opaque 'what' (mandatory)
    cell: tuple | None             # 'where' — rHEALPix suid, or None (position not bound)
    time_us: int | None            # 'when' — microseconds, or None (time not bound)
    attestation: Attestation       # signs the composite; carries pubkey/epoch/prev_hash/sig

    @property
    def composite(self) -> bytes:
        """The 32-byte field element the signature actually covers (recomputed from the opening)."""
        return seal_commitment(self.commitment, self.cell, self.time_us)

    @property
    def pubkey(self) -> bytes:
        return self.attestation.witness_pk

    @property
    def epoch(self) -> int:
        return self.attestation.epoch

    def verify(self, verify_signature=verify_sig) -> bool:
        """Offline: the opening recomputes the signed root AND the signature is valid."""
        return (self.attestation.root == self.composite
                and self.attestation.valid(verify_signature))

    def to_dict(self) -> dict:
        """A self-contained, JSON-serializable record the standalone verifier consumes."""
        return {
            "v": 1,
            "commitment": self.commitment.hex(),
            "cell": list(self.cell) if self.cell is not None else None,
            "time_us": self.time_us,
            "attestation": _att_to_dict(self.attestation),
        }

    @classmethod
    def from_dict(cls, d: dict) -> "Seal":
        cell = d.get("cell")
        time = d.get("time_us")
        return cls(
            commitment=bytes.fromhex(d["commitment"]),
            cell=tuple(cell) if cell is not None else None,
            time_us=int(time) if time is not None else None,
            attestation=_att_from_dict(d["attestation"]),
        )

composite property

composite: bytes

The 32-byte field element the signature actually covers (recomputed from the opening).

verify

verify(verify_signature=verify_sig) -> bool

Offline: the opening recomputes the signed root AND the signature is valid.

Source code in burin/kernel/seal.py
def verify(self, verify_signature=verify_sig) -> bool:
    """Offline: the opening recomputes the signed root AND the signature is valid."""
    return (self.attestation.root == self.composite
            and self.attestation.valid(verify_signature))

to_dict

to_dict() -> dict

A self-contained, JSON-serializable record the standalone verifier consumes.

Source code in burin/kernel/seal.py
def to_dict(self) -> dict:
    """A self-contained, JSON-serializable record the standalone verifier consumes."""
    return {
        "v": 1,
        "commitment": self.commitment.hex(),
        "cell": list(self.cell) if self.cell is not None else None,
        "time_us": self.time_us,
        "attestation": _att_to_dict(self.attestation),
    }

Identity dataclass

A self-attesting signer — the kernel's first-class self. Holds one SM2 keypair and signs its own seals; an external witness is the same object with a different holder. The secret never leaves this object and is never serialized or network-visible.

sign has the shape burin.coverage.fraud expects — (pubkey, msg) -> sig — so an Identity plugs straight into sign_attestation and the fraud proofs.

Source code in burin/kernel/signing.py
@dataclass
class Identity:
    """A self-attesting signer — the kernel's first-class *self*. Holds one SM2 keypair and
    signs its own seals; an external witness is the *same object* with a different holder.
    The secret never leaves this object and is never serialized or network-visible.

    ``sign`` has the shape ``burin.coverage.fraud`` expects — ``(pubkey, msg) -> sig`` — so an Identity
    plugs straight into ``sign_attestation`` and the fraud proofs."""

    pubkey: bytes
    _secret: bytes = field(repr=False)

    @classmethod
    def generate(cls) -> "Identity":
        """Mint a fresh hardware-style keypair (in production this is a secure-element key —
        Android StrongBox / Secure Enclave; here a software SM2 key)."""
        sk, pk = gmalg.SM2().generate_keypair()
        if len(pk) != SM2_PUBKEY_BYTES:
            raise AssertionError(f"unexpected SM2 pubkey length {len(pk)}")
        return cls(pk, sk)

    def sign(self, pubkey: bytes, msg: bytes) -> bytes:
        """Sign ``msg`` as this identity → 64-byte r‖s. ``pubkey`` must be our own (the
        signature is *self*-attesting); the parameter exists to match the ``SignFn`` shape."""
        if pubkey != self.pubkey:
            raise KeyError("an Identity can only sign as itself")
        r, s = gmalg.SM2(self._secret, SM2_UID, self.pubkey).sign(msg)
        sig = _fixed32(r) + _fixed32(s)
        if len(sig) != SM2_SIGNATURE_BYTES:
            raise AssertionError(f"SM2 produced {len(sig)}-byte signature")
        return sig

    # -- prototype key persistence (sensitive: a software stand-in for a secure element) --
    def keyfile_dict(self) -> dict:
        """Serialize the keypair for a prototype keyfile. Holds the SECRET — in production the
        key lives in a secure element (StrongBox / Secure Enclave) and never leaves the chip."""
        return {"pubkey": self.pubkey.hex(), "secret": self._secret.hex()}

    @classmethod
    def from_keyfile_dict(cls, d: dict) -> "Identity":
        return cls(bytes.fromhex(d["pubkey"]), bytes.fromhex(d["secret"]))

generate classmethod

generate() -> 'Identity'

Mint a fresh hardware-style keypair (in production this is a secure-element key — Android StrongBox / Secure Enclave; here a software SM2 key).

Source code in burin/kernel/signing.py
@classmethod
def generate(cls) -> "Identity":
    """Mint a fresh hardware-style keypair (in production this is a secure-element key —
    Android StrongBox / Secure Enclave; here a software SM2 key)."""
    sk, pk = gmalg.SM2().generate_keypair()
    if len(pk) != SM2_PUBKEY_BYTES:
        raise AssertionError(f"unexpected SM2 pubkey length {len(pk)}")
    return cls(pk, sk)

sign

sign(pubkey: bytes, msg: bytes) -> bytes

Sign msg as this identity → 64-byte r‖s. pubkey must be our own (the signature is self-attesting); the parameter exists to match the SignFn shape.

Source code in burin/kernel/signing.py
def sign(self, pubkey: bytes, msg: bytes) -> bytes:
    """Sign ``msg`` as this identity → 64-byte r‖s. ``pubkey`` must be our own (the
    signature is *self*-attesting); the parameter exists to match the ``SignFn`` shape."""
    if pubkey != self.pubkey:
        raise KeyError("an Identity can only sign as itself")
    r, s = gmalg.SM2(self._secret, SM2_UID, self.pubkey).sign(msg)
    sig = _fixed32(r) + _fixed32(s)
    if len(sig) != SM2_SIGNATURE_BYTES:
        raise AssertionError(f"SM2 produced {len(sig)}-byte signature")
    return sig

keyfile_dict

keyfile_dict() -> dict

Serialize the keypair for a prototype keyfile. Holds the SECRET — in production the key lives in a secure element (StrongBox / Secure Enclave) and never leaves the chip.

Source code in burin/kernel/signing.py
def keyfile_dict(self) -> dict:
    """Serialize the keypair for a prototype keyfile. Holds the SECRET — in production the
    key lives in a secure element (StrongBox / Secure Enclave) and never leaves the chip."""
    return {"pubkey": self.pubkey.hex(), "secret": self._secret.hex()}

Report dataclass

The verdict on one seal (or chain). ok is the bottom line; reasons explains a No.

Source code in burin/kernel/verify.py
@dataclass
class Report:
    """The verdict on one seal (or chain). ``ok`` is the bottom line; ``reasons`` explains a No."""

    ok: bool
    signature_ok: bool = False
    composite_ok: bool = False          # the opening recomputes the signed root
    trusted: bool | None = None         # signer ∈ trust set (None = no trust set supplied)
    chain_ok: bool | None = None        # append-only chain links (None = single seal)
    reasons: list[str] = field(default_factory=list)

make_seal

make_seal(
    identity: Identity,
    commitment: bytes,
    cell,
    time_us: int | None,
    *,
    epoch: int = 0,
    prev_hash: bytes = GENESIS_PREV,
) -> Seal

Sign one self-attestation (stateless). For an append-only sequence use :class:Ledger.

Source code in burin/kernel/seal.py
def make_seal(identity: Identity, commitment: bytes, cell, time_us: int | None, *,
              epoch: int = 0, prev_hash: bytes = GENESIS_PREV) -> Seal:
    """Sign one self-attestation (stateless). For an append-only sequence use :class:`Ledger`."""
    composite = seal_commitment(commitment, cell, time_us)
    att = sign_attestation(identity.sign, identity.pubkey, epoch, prev_hash, composite, time_us)
    return Seal(commitment, cell, time_us, att)

seal_commitment

seal_commitment(
    commitment: bytes, cell, time_us: int | None
) -> bytes

The composite a signer commits to, as one Poseidon hash over BN254:

Poseidon([DOMAIN, commitment, flags, cell, time])  (arity-5 → t=6)

commitment is a canonical 32-byte field element (a coverage root or media hash). cell is a rHEALPix suid tuple or None (where); time_us is microseconds or None (when). flags is a presence bitfield (WHERE_BIT | WHEN_BIT): an absent dimension clears its bit AND contributes a 0 field element, so 'no position'/'no time' is distinct from cell 0 / time 0, and the arity is fixed regardless of which dimensions are bound.

Source code in burin/kernel/seal.py
def seal_commitment(commitment: bytes, cell, time_us: int | None) -> bytes:
    """The composite a signer commits to, as one Poseidon hash over BN254:

        Poseidon([DOMAIN, commitment, flags, cell, time])  (arity-5 → t=6)

    ``commitment`` is a canonical 32-byte field element (a coverage root or media hash). ``cell`` is a
    rHEALPix suid tuple or ``None`` (*where*); ``time_us`` is microseconds or ``None`` (*when*).
    ``flags`` is a presence bitfield (``WHERE_BIT`` | ``WHEN_BIT``): an absent dimension clears its bit
    AND contributes a 0 field element, so 'no position'/'no time' is distinct from cell 0 / time 0, and
    the arity is fixed regardless of which dimensions are bound."""
    if len(commitment) != 32:
        raise ValueError("commitment must be 32 bytes")
    commitment_fe = int.from_bytes(commitment, "big")
    flags, cell_fe, time_fe = 0, 0, 0
    if cell is not None:
        flags |= WHERE_BIT
        cell_fe = suid_to_field(cell)
    if time_us is not None:
        flags |= WHEN_BIT
        time_fe = int(time_us)
    return _pos.to_bytes32(_pos.poseidon([_DOM_FE, commitment_fe, flags, cell_fe, time_fe]))

verify_sig

verify_sig(pubkey: bytes, msg: bytes, sig: bytes) -> bool

Public SM2 verification — handed to every seal check and fraud proof. Returns False (never raises) on malformed input, so a forged/garbage signature is simply not accepted.

Source code in burin/kernel/signing.py
def verify_sig(pubkey: bytes, msg: bytes, sig: bytes) -> bool:
    """Public SM2 verification — handed to every seal check and fraud proof. Returns False
    (never raises) on malformed input, so a forged/garbage signature is simply not accepted."""
    try:
        if len(sig) != SM2_SIGNATURE_BYTES:
            return False
        r, s = sig[:32], sig[32:]
        return gmalg.SM2(b"", SM2_UID, pubkey).verify(msg, r, s)
    except Exception:
        return False

detect_fraud

detect_fraud(record_a, record_b) -> str | None

Given two seals from (allegedly) the same signer, return the name of a self-verifying fraud proof if one holds, else None. "equivocation" = two distinct attestations at one epoch (any divergent signed field — root, issued_at, subject, policy — not only a divergent root; one attestation per epoch, DECISIONS D23); "backdating" = a later epoch carries an earlier issuance time. Both verify offline against the signatures alone — no trusted clock, no consensus.

Source code in burin/kernel/verify.py
def detect_fraud(record_a, record_b) -> str | None:
    """Given two seals from (allegedly) the same signer, return the name of a self-verifying
    fraud proof if one holds, else ``None``. ``"equivocation"`` = two distinct attestations at one
    epoch (any divergent signed field — root, issued_at, subject, policy — not only a divergent root;
    one attestation per epoch, ``DECISIONS`` D23); ``"backdating"`` = a later epoch carries an earlier
    issuance time. Both verify offline against the signatures alone — no trusted clock, no consensus."""
    a, b = _as_seal(record_a).attestation, _as_seal(record_b).attestation
    if EquivocationFraud(a, b).verify(verify_sig):
        return "equivocation"
    earlier, later = (a, b) if a.epoch < b.epoch else (b, a)
    if BackdatingFraud(earlier, later).verify(verify_sig):
        return "backdating"
    return None

verify_chain

verify_chain(
    records,
    *,
    trusted_pubkeys: Iterable[bytes] | None = None,
) -> Report

Verify an append-only seal sequence from ONE signer: every seal valid, one signer, epochs 0..n-1 contiguous, prev_hash links each to the previous, issuance monotone. A broken link or a backdate is reported (and is provable fraud — see :func:detect_fraud).

Source code in burin/kernel/verify.py
def verify_chain(records, *, trusted_pubkeys: Iterable[bytes] | None = None) -> Report:
    """Verify an append-only seal sequence from ONE signer: every seal valid, one signer,
    epochs 0..n-1 contiguous, ``prev_hash`` links each to the previous, issuance monotone.
    A broken link or a backdate is reported (and is provable fraud — see :func:`detect_fraud`)."""
    seals = [_as_seal(r) for r in records]
    reasons: list[str] = []
    if not seals:
        return Report(False, reasons=["empty chain"])

    sig_ok = comp_ok = True
    for i, s in enumerate(seals):
        r = verify_seal(s, trusted_pubkeys=trusted_pubkeys)
        sig_ok = sig_ok and r.signature_ok
        comp_ok = comp_ok and r.composite_ok
        if not r.ok:
            reasons.append(f"seal[{i}] invalid: {'; '.join(r.reasons)}")

    pk0 = seals[0].pubkey
    chain_ok = True
    prev_msg_hash = GENESIS_PREV
    last_issued = None
    for i, s in enumerate(seals):
        att = s.attestation
        if att.witness_pk != pk0:
            chain_ok = False
            reasons.append(f"seal[{i}] signer differs — a chain is one signer's log")
        if att.epoch != i:
            chain_ok = False
            reasons.append(f"seal[{i}] epoch {att.epoch} ≠ position {i} (not contiguous/append-only)")
        if att.prev_hash != prev_msg_hash:
            chain_ok = False
            reasons.append(f"seal[{i}] prev_hash does not link to seal[{i-1}]")
        if last_issued is not None and att.issued_at is not None and att.issued_at < last_issued:
            chain_ok = False
            reasons.append(f"seal[{i}] issued_at {att.issued_at} < previous {last_issued} (backdated)")
        prev_msg_hash = keccak(att.message())
        if att.issued_at is not None:                   # untimed seals don't reset the running max
            last_issued = att.issued_at

    trusted = None if trusted_pubkeys is None else (pk0 in set(trusted_pubkeys))
    if trusted is False:
        reasons.append("signer is not in the trust set")
    ok = sig_ok and comp_ok and chain_ok and (trusted is not False)
    return Report(ok, sig_ok, comp_ok, trusted, chain_ok, reasons)

verify_seal

verify_seal(
    record,
    *,
    trusted_pubkeys: Iterable[bytes] | None = None,
) -> Report

Verify one seal offline: the opening recomputes the signed root, the signature is valid, and (if a trust set is given) the signer is in it. A relying party trusts keys it chose, out of band (the printable trust card) — there is no global registry.

Source code in burin/kernel/verify.py
def verify_seal(record, *, trusted_pubkeys: Iterable[bytes] | None = None) -> Report:
    """Verify one seal offline: the opening recomputes the signed root, the signature is valid,
    and (if a trust set is given) the signer is in it. A relying party trusts *keys it chose*,
    out of band (the printable trust card) — there is no global registry."""
    seal = _as_seal(record)
    composite_ok = seal.attestation.root == seal.composite
    signature_ok = seal.attestation.valid(verify_sig)
    trusted = None if trusted_pubkeys is None else (seal.pubkey in set(trusted_pubkeys))
    reasons: list[str] = []
    if not composite_ok:
        reasons.append("composite mismatch: the opening (commitment, cell, time) does not "
                       "recompute the signed root")
    if not signature_ok:
        reasons.append("signature invalid")
    if trusted is False:
        reasons.append("signer is not in the trust set")
    ok = composite_ok and signature_ok and (trusted is not False)
    return Report(ok, signature_ok, composite_ok, trusted, None, reasons)