Skip to content

Standard library and protocol stack

Complete module reference for the Lema standard library (audit/inputs/), including Core, concurrency, data structures, numeric types, cryptography, BlockStore, TLS 1.3, Noise, HTTP/1.1, S3, Web, and LemaIR semantics.

Every module in Lema’s standard library and protocol stack is published fileless from canonical JSON authoring inputs (audit/inputs/*.json) into the content-addressed store (lema.core/v4), and rendered deterministically into human-readable Lean files under audit/view/ (lema audit render, verified in cargo test by crates/lema-site/tests/audit_view.rs).

All theorems listed below are checked by the pinned Lean 4.34.1 kernel with zero sorry, zero native_decide, and within the default axiom policy (propext, Quot.sound, Classical.choice). Where a theorem is conditional on a stated mathematical or hardware premise (such as CrashIntegrity, DhCommutes, or Fermat), that premise is noted explicitly in the module description and in the Trusted base.


Core, refinement, and concurrency (audit/inputs/)

The core modules define effectful computation (Prog), protocol contracts (Contract), refinement, replacement, and concurrency combinators. See The program core for the full type signatures and theorem statements of Core.

ModuleNamespacePurpose and key declarations
CoreLemaPrograms over a command type, their contracts, traces and implementations, with the soundness, trace, linking, replacement and refinement theorems (Prog, Contract, Safe, Runs, safe_runs, link_implements, replacement, Refines, refines_covers).
ReplaceLema.ReplaceA worked replacement claim: a counter contract, the same protocol with no promise, two implementations (the second holds the count plus five) and the theorems that the second replaces the first on each contract (plain, offset, plain_offset, loose_plain_offset).
ReplaceGenericLema.ReplaceGenericThe same replacement claim for a counter whose step is a parameter, with one theorem for all steps (counter, plain, offset, generic_plain_offset).
LiftLema.CapA program over one command family run in a signature that holds it, with safety carried over in both directions (liftL, liftR, liftL_safe_iff, implements_restrictL). That the runner answers each family’s commands is tested, not proved.
HandlesLemaHandles owned in contract state: a use after close, a double close and returning with a linear handle open are unsafe (handleContract, use_after_close, double_close, leak).
TicketsLema.TicketsA model of tickets and spawned tasks over handle-map contracts, safe under any interleaving, and the lowering of the runner’s task commands to it (system_safe, overlap, lower, run_lower). That the host runs pending operations concurrently, hands spawned tasks their handles, and refuses and cancels operations is tested by a runner scenario, not proved; no test compares the runner with meaning.
ParallelLemaPrograms over disjoint handles: every schedule gives the results and final state of running one after the other, and safety composes (interleave, schedule_independent, safe_par, safe_interleave).
ActorLemaA model of one actor with a bounded mailbox: a send to a full mailbox is answered busy and changes nothing, and the step’s invariant holds in every order of events (Actor, CertifiedStep, busy_iff_full, every_order_preserves).
ActorBridgeLema.ActorBridgeThe meaning of the runner’s actor commands over a task table, with theorems that it realises the Actor and Replies models (meaning, meaning_linearizable, meaning_system_inv). That the runner realises meaning is tested, not proved; its scheduler, the compiler and the OS are assumed.
RepliesLema.RepliesA model of request and reply actors: a send returns a ticket and the reply is taken by ticket, linearizable under every interleaving (send, take, trace_linearizable, replies_invariant). That the host’s mailbox and actor loop implement it is tested, not proved.
ChannelsLema.ChannelsSession channels as pairs of dual endpoint handles, under a contract that requires every endpoint closed when a program returns (Session, dual, CSafe, client_safe, server_safe). The host’s handle tables are tested, not proved.
SessionsLema.SessionsSession fidelity and termination for every protocol, in the lock-step model of Channels only (exchange_safe, exchange_ends, exchange_total, rounds_total).
CallGraphLema.CallGraphA model of acyclic actor call graphs with bounded mailboxes: on a ranked graph no chain of waits is a cycle and no reachable state of the model is deadlocked (Graph, checkRank, no_wait_cycle, deadlock_free). A program safe under an actor’s call contract addresses only its callees (callContract, trace_edges), but no theorem composes such programs with the model.
FueledLema.FueledFueled programs: first-order programs over a vocabulary with declared costs, whose work between scheduling points and number of commands are bounded by numbers read off the program (FProg, Vocab, slices_le_gap, commands_le, runF_enough). The bounds count the declared costs only: that each member runs within its declared cost is not proved.
DurableLema.DurableA model of durable actors: an append-only log with snapshots, recovery to the live state, and idempotency keys applied at most once (recover_eq, retry, applied_at_most_once). That the runtime syncs before it replies, and that the disk keeps what was synced, are tested and assumed, not proved.
ProtectedLema.ProtectedExamples for protected references: a keyed counter, two implementations, and the replacement, conformance and refinement claims a protected reference accepts or refuses (wide, plain_offset, roomy_refines, never_unimplementable).
EscrowLema.EscrowA model of the escrow protocol for a transfer between two shards: conservation, at most one debit and one credit per transfer, and progress once the transfer’s messages are delivered in protocol order (conservation, debits_at_most_once, credits_at_most_once, progress). Its network and crash model (delay, reordering, duplication, loss) is argued, not checked.

Data, collections, numeric types, and JSON (audit/inputs/)

Pure data structures, byte slices, canonical text helpers, fixed-width and interval arithmetic, and strict JSON parsing/rendering.

ModuleNamespacePurpose and key declarations
BytesLema.Std.BytesByte slices without copying and big-endian words for byte protocols and hashing, each accessor proved against the slice’s logical bytes (ByteSlice, ByteSlice.foldBlocks_spec, bytesBE32_be32, rotr32_toBitVec).
DataBytesLema.BytesByte arrays in Lema code: total or proof-bounded access for executable code, a list view for proofs, and bridge lemmas between the two (view, at?_view, view_getElem?, view_push).
TextLema.StdText as bytes with a proof that they are UTF-8, and ASCII operations proved against three audited definitions (Text, Text.validate_isSome, Text.asciiLower_view, Text.eqIgnoreAsciiCase_iff).
CanonicalLema.Std.CanonicalRequest canonicalisation for AWS Signature Version 4 and S3 over byte strings: hex, percent-encoding, the canonical query string, canonical headers and a length-prefixed tuple encoding, with round trips and injectivity (uriEncode, canonicalQuery_perm, canonicalHeaders_injective, encodeTuple_injective).
MapLema.Std.MapA finite map contract over a lawful key order, and a sorted association list that implements it (contract, Order, impl_implements, find_insert, find_delete).
MapDetLema.Std.MapDetDeterminism of the finite map contract and the replacement theorem it gives any conforming implementation over the sorted association list (contract_deterministic, replaces_list).
MapTreeLema.Std.MapTreeAn unbalanced binary search tree over a lawful key order that implements the finite map contract and replaces the sorted association list (Tree, lookup, insert, delete, impl_implements, tree_replaces_list).
IndexedLemaIndexed inductive families: an indexed predicate and a length-indexed vector, each used by induction and a dependent match (Reach, Vec, Vec.head_cons, Vec.toList_length).
IntervalLema.Std.FixedRounding to nearest even, rescaling, square roots and interval arithmetic over the carriers of Fixed, with no floats (rescale64_nearest, sqrt64_spec, Interval64.add_encloses, Interval64.mul_encloses).
Finite64Lema.Std.Finite64Finite binary64 values with arithmetic through Lean’s pinned float model, refusing a non-finite result and division by zero (Finite, fromBits_ok_iff, add_model, div_zero). The bit conversions, equality and the arithmetic run on the VM, whose Init bundle holds Lean’s float model; the arithmetic is tested there against IEEE 754 binary64.
FixedLema.Std.FixedFixed-point carriers with operations that are exact when they succeed, two explicit wrapping operations, and a bounded dot product of 16-bit integers that agrees with the unbounded integer sum (Fixed64, add64_exact, fromInt64_exact, wrappingAdd64, dotInt64_agrees).
FixedWidthLemaLean’s semantics of fixed-width integers stated as theorems, mostly on worked values: wrapping, truncating division, shifts modulo the width, clamping conversions, and a bridge from 64-bit to unbounded integers (u8_add_wraps, i64_div_truncates, u64_shift_left_mod_width, i64_toInt_add_of_bounds).
MoneyLemaMoney as 64-bit minor units: a transfer refuses or moves the amount with no overflow, and conserves the total as an integer (Account, transfer, transfer_conserves, transfer_refuses_overdraw).
TreeLemaA binary search tree with its lookup laws and in-order list view (Tree, Tree.insert, Tree.lookup_insert_self, Tree.lookup_insert_other).
EvaluateLemaRecursion that proofs evaluate: each theorem is proved by the kernel evaluating a definition (sumTo, table, sumTo_100000_k, lookup_10000_k).
JsonLema.JsonJSON values with decimal numbers in normal form, and an executable codec for RFC 8259 text with two I-JSON rules and fixed limits, with its round trip for well-formed values (Value, Number, decode, encode, decode_encode). The decoder is not proved complete against a grammar.
StdJsonLema.Std.JsonA JSON codec on JsonValue with integer numbers, and its round trip for well-formed values (encode, decode, WF, decode_encode). It is noncomputable here: a reference, not an executable root.
DataJsonLemaJSON values as one self-recursive family with spine-encoded arrays and objects, and list views proved both ways (JsonValue, JsonValue.elements?_arr, JsonValue.arr_of_elements?, JsonValue.fields?_obj).

Pythonic

Both views below are rendered from the same accepted statement objects in the store. A sorting contract needs both laws: returning an empty list would be in order, so the second law requires every original element and its count to survive.

Pythonic contract view (Std.Canonical.sortBy)
law sortBy_sorted(le: alpha -> alpha -> Bool, l: List(alpha)):
    requires forall a: alpha, b: alpha, c: alpha :: (le(a, b) == true and le(b, c) == true) -> le(a, c) == true
    requires forall a: alpha, b: alpha :: le(a, b) == true or le(b, a) == true
    ensures Pairwise(fn(a: alpha, b: alpha) -> le(a, b) == true, sortBy(le, l))

law sortBy_perm(le: alpha -> alpha -> Bool, l: List(alpha)):
    Perm(sortBy(le, l), l)

Lean

Lean view (Std.Canonical.sortBy)
theorem sortBy_sorted {α : Type} (le : α → α → Bool)
    (trans : ∀ a b c, le a b = true → le b c = true → le a c = true)
    (total : ∀ a b, le a b = true ∨ le b a = true) :
    ∀ l : List α, (sortBy le l).Pairwise (fun a b => le a b = true)

theorem sortBy_perm {α : Type} (le : α → α → Bool) :
    ∀ l : List α, (sortBy le l).Perm l

Explanation

The first law (sortBy_sorted) promises that for any comparison function le that is transitive and total, every item in sortBy(le, l) is ordered before or equal to the items that follow it.

The second law (sortBy_perm) closes the loophole where a buggy implementation simply drops elements or returns an empty list: it promises that the output list is an exact permutation of the input list, preserving every element and its multiplicity.

Because both laws live in the content-addressed store as accepted statement objects, callers such as canonical HTTP header sorting depend only on these statement hashes, never on the internal sorting implementation or proof steps.


Cryptography (audit/inputs/)

Every cryptographic module pairs a clean mathematical specification (*Spec) with an executable fixed-width implementation and proves functional equivalence in the Lean kernel, complemented by NIST CAVP, RFC, and Wycheproof test vectors (*Report).

ModuleNamespacePurpose and key declarations
Sha256SpecLema.Std.Sha256SpecThe SHA-256 specification, transcribed from FIPS 180-4 over byte lists, with its known answers checked by kernel evaluation (digest, compress, digest_abc, digest_length).
Sha256Lema.Std.Sha256A fast SHA-256 over byte slices, proved equal to the specification for messages under 2^64 bits; the compiled code is tested on the VM (digestSlice, digestSlice_eq_spec, blockLoop_spec).
Sha256ExecLema.Std.Sha256ExecPure entry points for the SHA-256 digest and vector apps; running them is tested, not checked (digestHex, report, vectors).
Sha256UnboxedLema.Std.Sha256UnboxedSHA-256 with its hash value and schedule in one 288-byte buffer, proved equal to the specification for messages under 2^64 bits (digestSlice, Buf, digestSlice_eq_spec, wordAt_setW_same).
Sha256UnboxedExecLema.Std.Sha256UnboxedExecPure entry points for the unboxed SHA-256 digest and vector apps; running them is tested, not checked (digestHex, report, subSlices).
Sha512SpecLema.Std.Sha512SpecThe SHA-512 specification, transcribed from FIPS 180-4 over byte lists, with its known answers checked by kernel evaluation (digest, compress, digest_abc, digest_msg896).
Sha512Lema.Std.Sha512A fast SHA-512 over byte arrays, proved equal to the specification on every byte array (digest, digest_eq_spec, digest_toList).
HmacLema.Std.HmacHMAC specified once for any hash and instantiated with SHA-256, with RFC 4231’s answers checked, and a fixed-width form on byte arrays proved equal to the SHA-256 instance for keys and messages under 2^31 bytes; HMAC’s unforgeability is assumed, and constant-time execution of the fixed-width form is the VM analyser’s static check, not a theorem (hmacSpec, hmacSha256, hmacBytes, hmacBytes_toList, hmacSha256_of_fits).
SigV4Lema.Std.SigV4AWS Signature Version 4 for S3 PutObject, GetObject and HeadObject over byte lists, with theorems on what each request signs; SigV4’s and HMAC’s security, AWS’s servers and the clock are assumed, and the VM analyser’s static check refuses signingKey as not constant time (canonicalRequest, signingKey, authorization, putIfAbsent_ifNoneMatch_entry, signatureWith_of_fits).
SigV4PayloadLema.Std.SigV4PayloadSigV4’s payload hash computed by the unboxed SHA-256 over a byte slice, proved equal to SigV4’s payload hash of the slice’s bytes (payloadHash, payloadHash_eq, digestSlice_eq_old).
ChaCha20Poly1305Lema.Std.ChaCha20Poly1305.SpecChaCha20-Poly1305 per RFC 8439, a fixed-width implementation proved equal to its specification, with the AEAD’s round trip and tag check, and sealChecked and openChecked, which refuse inputs outside the RFC’s domain; constant-time execution is the VM analyser’s static check, not a theorem (seal_spec, open_spec, aead_roundtrip, open_rejects_tag_mismatch, aead_roundtrip_checked).
Field25519Lema.Std.Field25519.SpecThe field of X25519 and Ed25519, integers modulo 2^255 - 19, as fixed-width limbs proved to agree with Nat arithmetic modulo the prime within stated limb bounds; running it is tested (Std.Field25519.mul_spec, Std.Field25519.Gf.mul_spec, Std.Field25519.Gf.inv_spec, Std.Field25519.toBytes_spec).
X25519Lema.Std.X25519X25519 per RFC 7748, a Montgomery ladder on Field25519 limbs proved equal to the RFC’s own algorithm, refusing an all-zero shared secret; that the ladder is scalar multiplication on the curve is not proved (x25519L_eq, dh_eq, dh_some, publicKey_eq).
Ed25519SpecLema.Std.Ed25519SpecThe Ed25519 specification per RFC 8032 over a field given by its operations, with TEST 1’s known answers checked and non-canonical encodings refused; the base-point table is tested, and the group law and unforgeability are not proved (sign, verify, verify_test1, verify_rejects_large_s, decode_rejects_noncanonical).
Ed25519Lema.Std.Ed25519Ed25519 on byte arrays, signing on fixed-width limbs, proved to return the specification’s keys, signatures and verdicts; constant-time execution of sign and publicKey is the VM analyser’s static check, not a theorem (publicKey, sign, verify, sign_eq_spec, verify_eq_spec).
P256VerifyLema.Std.P256VerifyECDSA verification on P-256 with SHA-256 per FIPS 186-5, in Jacobian coordinates, proved to give the specification’s verdict on every input given Fermat, Fermat’s little theorem for the field’s modulus, which is assumed, not checked; the vectors are tested (verify, verify_eq_spec, jsmul_rep, Fermat).
RsaVerifyLema.Std.RsaVerifyRSA signature verification with SHA-256 per RFC 8017, PSS and PKCS #1 v1.5 for 2048- to 4096-bit moduli, proved to give the specification’s verdict on every input; the vectors are tested (verifyPss, verifyPkcs1, verifyPss_eq_spec, pkcs1With_true).
ConstantTimeLema.Std.ConstantTimeByte comparisons and a byte selection written with no branch on the bytes, with their meaning proved; constant-time execution is the VM analyser’s static check, not a theorem (ctEq16, ctEq32, ctSelect, ctEq32_iff).

Pythonic

From the cryptography library (audit/inputs/ChaCha20Poly1305.json), used by TLS 1.3 and Noise record protection.

Pythonic contract view (Std.ChaCha20Poly1305)
law aead_roundtrip_checked(key: ByteArray, nonce: ByteArray, aad: ByteArray, pt: ByteArray, ct: ByteArray):
    requires sealChecked(key, nonce, aad, pt) == some(ct)
    ensures openChecked(key, nonce, aad, ct) == some(pt)

law open_rejects_tag_mismatch(key: List(UInt8), nonce: List(UInt8), aad: List(UInt8), body: List(UInt8), tag: List(UInt8)):
    requires length(tag) == 16
    requires tag != Spec.sealTag(key, nonce, aad, body)
    ensures open(ByteArray.mk(Array.mk(key)), ByteArray.mk(Array.mk(nonce)), ByteArray.mk(Array.mk(aad)), ByteArray.mk(Array.mk(body ++ tag))) == none

Lean

Lean view (Std.ChaCha20Poly1305)
theorem aead_roundtrip_checked (key nonce aad pt ct : ByteArray)
    (h : sealChecked key nonce aad pt = some ct) :
    openChecked key nonce aad ct = some pt

theorem open_rejects_tag_mismatch (key nonce aad body tag : List UInt8)
    (ht : tag.length = 16)
    (hne : tag ≠ Spec.sealTag key nonce aad body) :
    open ⟨⟨key⟩⟩ ⟨⟨nonce⟩⟩ ⟨⟨aad⟩⟩ ⟨⟨body ++ tag⟩⟩ = none

Explanation

The first theorem proves that whenever sealChecked accepts a 32-byte key, 12-byte nonce, additional authenticated data, and plaintext within RFC 8439 bounds and produces ciphertext ct, openChecked recovers the exact original plaintext pt.

The second theorem proves that if the 16-byte authentication tag at the end of a message differs in any bit from the RFC 8439 Poly1305 tag, open returns none and releases zero plaintext bytes.

The implementation computes ChaCha20 in 16 unboxed UInt32 registers and Poly1305 in five 26-bit UInt64 limbs, proved equal to the RFC 8439 mathematical specification and checked by the VM’s ConstantTime static analyzer.


Capabilities, block storage, and durable journals (audit/inputs/)

Layer 1 byte frames (Frames), capability contracts (Capability), the copy-on-write 4 KiB block store (BlockStore, BlockCrash, BlockStoreLaws), and durable actor/operation journals (Record, ActorJournal, ActorCrash).

ModuleNamespacePurpose and key declarations
AppCmdLema.CapThe task, actor and session command families, and Plus, which joins families into an application’s signature (TaskCmd, ActorCmd, SessionCmd, Plus.Reply).
CapabilityLema.CapThe six capability tags (tcp, udp, block, random, clock, secret) as command families with contracts, with theorems that a valid request meets its precondition (for a tcp send, receive or close, when the program has its handle open) and that tcpEcho, a connect, send, receive and close, is safe from any state; that the host keeps the promises is tested and assumed (TcpCmd, tcpContract, TcpCmd.ofRequest_pre, tcpEcho_safe).
FramesLema.Cap.FramesThe typed request and reply frames of the six capability tags with their codecs, and theorems that valid frames round-trip and what decodes is valid; the host’s side is tested by shared vectors (Codec.Lawful, decodeTcpRequest_encode, TcpRequest.of_decode, Codec.decode_trailing).
SecretPolicyLema.Cap.SecretPolicyWrappers that take a secret the runner releases and give out only what their role allows, for SigV4 signing and verification and bearer headers, with theorems on what each SigV4 wrapper checks before it releases a value; HMAC’s and SigV4’s security and the clock are assumed (deriveSigV4SigningKey_some, signSigV4Request_some, verifyInboundSigV4Request_some, formatBearerHeader).
SecretExchangeLema.Cap.SecretExchangeThe opaque exchanges: an application uses a SigV4 or bearer credential only through a pinned driver it never sees inside, and a session the credential may not be used on is closed with nothing sent (ExchangeCmd, runSigned, runBearer, sessionAllowed_bound, signedCont_refused).
BlockStoreLema.Cap.BlockStoreA copy-on-write store of named files over 4 KiB blocks with alternating superblocks, its commit and recovery, and theorems on what recovery returns and on refusals; the tree codec’s agreement is tested (commitProg, recoverMain, recoverMain_sound, writeAtomic_dirty).
BlockStoreLawsLema.Cap.BlockStoreLawsWhat a write does to a store’s files: in the device model every crash image recovers to the confirmed view or to a view of the next sequence number that holds the written file, with the size and SHA-256 of what was written, and every other key as before (writeAtomic_all_or_nothing_frame, writeAtomic_ok_frame, planned_entries, decodeIndex_encodeIndex).
BlockCrashLema.Cap.BlockCrashThe crash model of BlockStore’s device and its theorems: from a confirmed engine, every crash during a commit or a write recovers to the confirmed view or to one view of the next sequence number; that block writes are atomic, that a completed flush persisted the writes before it and that no operation takes effect after it returned are assumed of the device and its host (CrashIntegrity, commit_all_or_nothing, writeAtomic_all_or_nothing, recoverAndConfirm_ok).
RecordLema.Cap.RecordThe collector’s operation record in a BlockStore file: its encoding, its phase machine and a crash model whose every reachable state keeps the invariant, under collision resistance (OpRecord, decodeRecord_encode, confirmed_only_by_match, guardedPut_intent_first, reach_inv).
ActorAppLema.Cap.ActorAppThe durable actor over the actor and block families, its journal on a BlockStore; its codec and counter theorems are checked, and its programs’ order of commands is tested (recoverProg, stepProg, shellCodec_lawful, counter_inv).
ActorJournalLema.Cap.ActorJournalA durable actor’s journal in BlockStore files, a ring of entry slots and a snapshot, with theorems that replaying what recovery reads folds the logged entries (appendEntry, readJournal, replay, recovery, decodeEntry_encode).
ActorCrashLema.Cap.ActorJournalThe crash model of the actor journal: recovery after any crash folds a prefix holding every confirmed entry, and the journaled actor of the model is linearizable; BlockCrash’s device premise is assumed, and that a run on the device is a model run is tested (crash_recovery, crash_keeps_replied, journaled_linearizable, appendEntry_all_or_nothing).
SessionAppLema.Cap.SessionAppSession programs as application programs: their lift to the task and session families and the runner’s intended semantics, with theorems that under the intended semantics lifted programs run as the lock-step model runs them; that the runner implements the intended semantics is tested (lift, appExchange, appExchange_lift, appExchange_liftMap).
SessionTotalLema.Cap.SessionTotalSession termination for lifted programs under the runner’s intended semantics: two safe programs on dual endpoints that make no new channel both end within the session’s depth plus three steps, and the rounds protocol’s asker and answerer within twice the number of requests plus three; that the runner implements the intended semantics is tested (appExchange_total, appRounds_total, demo_rounds).
StreamHubLema.Cap.StreamHubA hub actor’s topics and subscribers as pure functions, with theorems that one call of subscribe takes the topic’s snapshot and registers the subscriber, so on a topic not yet ended the next stage published is pending for it, and that a terminal stage drops a pending intermediate one (subscribe, publish, subscribe_then_publish, terminal_drops_intermediate).
ServeStreamLema.Cap.ServeStreamThe stream family: an anonymous TLS accept and a chunked HTTP/1.1 response, with theorems that the streamed plaintext parses back and each record is one send on its connection’s handle (runAccept, StreamCmd, stream_parses, runSeal_frame, head_fields).
ServeVerifiedLema.Cap.ServeVerifiedThe serve family: a pinned driver that accepts one TLS connection and verifies its request by SigV4, with theorems on when a verified request is released (ServeCmd, runServe, serveVerified, verifyReply_some, signature_spec).

Pythonic

Pythonic syntax
contract LawfulStorage(ops: Storage):
    law get_put(k: Key, v: Val):
        ops.get(ops.put(k, v), k) == v

Lean

Lean syntax
structure LawfulStorage (ops : Storage) : Prop where
  get_put : ∀ (k : Key) (v : Val),
    ops.get (ops.put k v) k = v

Explanation

For every key k and value v, storing v at k and then reading k from the resulting state must return v.

Storage, Key and Val must already be in scope, with operations of the types used here. LawfulStorage is a proposition-valued record: a proof of it must supply evidence for its get_put law.

Declaring the record does not prove that any particular storage implementation obeys it. More laws can be added when the intended behavior needs a stronger contract.


Network protocols, TLS 1.3, HTTP/1.1, S3, and applications (audit/inputs/)

Transport protocols, opaque credential sub-runs (SecretExchange and ServeVerified), and end-to-end applications (Collector and Escrow).

ModuleNamespacePurpose and key declarations
X509Lema.Cap.X509A bounded X.509 DER parser and certificate-chain validation for TLS server authentication, with the signature check a parameter (parseCert, validate, validate_sound, readTlv_split, matchName_wildcard).
Tls13KeyScheduleLema.Cap.Tls13KeyScheduleHKDF-SHA256 and the TLS 1.3 key schedule over the accepted HMAC and SHA-256, with length, label and transcript theorems; HKDF’s security is assumed (extract, expand, hkdfLabel_inj, deriveSecret_transcript).
Tls13Lema.Cap.Tls13The TLS 1.3 handshake, client and server, parametric in the cryptography: a session carries its evidence as fields, every failure closes the connection and record nonces are distinct; the cryptography’s correctness and security are hypotheses on its parameters (connectAndVerify, AuthenticatedSession, connectAndVerify_closes, nonce_fresh, request_notSent).
Tls13ConcreteLema.Cap.Tls13ConcreteTLS 1.3 on the concrete primitives: each is its module’s implementation, and a protected record reads back as itself; X25519’s commutativity and the primitives’ security are assumed (crypto, seal_spec, open_seal, wire_roundtrip, DhCommutes).
Http1Lema.Cap.Http1HTTP/1.1 over TLS 1.3, client and server, parametric in the cryptography, with theorems that each side reads back exactly what the other sends and that the outcome is not sent exactly when no send beyond the handshake’s two was made (exchange, serve, parse_respond, parseRequest_render, exchange_notSent).
S3Lema.Cap.S3A narrow S3 client over HTTP/1.1 signed with SigV4, with theorems that the bytes sent are exactly the signed request and that the outcome is not sent exactly when no send beyond the handshake’s two was made (putIfAbsent, transmission, op_notSent, op_confirmed).
NoiseLema.Cap.NoiseThe Noise XX handshake framed for TCP, parametric in the cryptography, with theorems on nonces, closing on failure and agreement after XX; its security as a key exchange is assumed (Session, xx_agree, session_xx, nonce_inj, closed_stays).
NoiseConcreteLema.Cap.NoiseConcreteNoise’s cryptography on the accepted X25519, ChaCha20-Poly1305, SHA-256 and HMAC, its laws checked except X25519’s commutativity, a hypothesis the test vector exercises (crypto, laws, X25519Comm, session_concrete).

Web documents, forms, markdown, and server components (audit/inputs/)

Typed HTML5 document construction (Web), routes and sessions (WebApp), form decoding (WebForm), Markdown rendering (WebMarkdown), and streaming server responses (HttpStream).

ModuleNamespacePurpose and key declarations
WebLema.WebThe types of a page with no script: closed lists of elements and attributes and URLs only as SafeUrl, with theorems that no element is an active one and no attribute an event handler (Html, Elem, elem_name_not_active, attr_names_not_on, encode_prefix).
WebRouteLema.Web.RouteTyped routes and forms with lawful segment codecs, and the theorem that every route and every form command decodes back from its encoding (Route, FormCmd, SegCodec, route_and_form_roundtrip).
WebViewLema.Web.ViewView tokens, the stale-view gate and what a page may read, with theorems that a stale token makes no store operation and that a page reads only authorized items (ViewToken, applyMutation, CanRead, stale_view_rejected, view_isolation_sound).
WebRenderLema.Web.RenderA page’s bytes: text and attribute values go through one escaper and tags name only the listed elements, with the theorem that every page renders as a stream of safe tokens and its byte-level corollaries (escText, SafeOutput, render_safe, textTok_bytes, attrTok_value_bytes).
WebLiveLema.Web.LiveA page sent as a stream of stages with no script, with theorems that the records join to the whole page and each is safe output (stage, records, records_join, live_safe).

LemaIR operational semantics and oracle corpus (audit/inputs/)

Kernel-checked operational semantics of lema.ir/v1 (Lema.Ir.Semantics) and its differential oracle test suites (IrOracleCore, IrOraclePrims, IrOracleCorpus).

ModuleNamespacePurpose and key declarations
IrSemanticsLema.IrA fuel-bounded small-step semantics of LemaIR as the VM’s register machine runs it, with the contracts of the primitives it models; the VM is tested against it, not proved to follow it (step, run, evalEntry, link, run_mono).
IrOracleCoreLema.Ir.Oracle.CoreOracle vectors for operations, terminators, aliasing, call-depth limits, error states and sessions, each a theorem the kernel checks by evaluating the semantics; the VM runs them as tests (v_op_call, v_alias_take_bytes_set, v_term_switch_nat_0, v_error_call_depth, v_session_two_yields).
IrOraclePrimsLema.Ir.Oracle.PrimsOracle vectors for the modelled primitives, each a theorem the kernel checks by evaluating the semantics; the VM runs them as tests (v_prim_lean_nat_add_1, v_prim_lean_uint64_add_0, v_prim_lean_string_append_0).
IrOracleCorpusLema.Ir.Oracle.CorpusOracle vectors for the corpus and bounded fixtures’ roots compiled with the optimizer off and on, each a theorem the kernel checks by evaluating the semantics; the VM runs them as tests (v_corpus_LemaIrCorpus_natSum_opt_0, v_bounded_LemaIrFixture_partialAdd_opt_0).

Lema v0.3.2 · Updated 29 October 2026 · Version and compatibility