This is a DSL embedded in Lean for the finite systems algebra.
The surface uses indentation, ← for computation/assignment, ←$ for sampling,
and 𝒰[T] for the uniform law on a finite nonempty type. There are no braces,
semicolons, do blocks, or combined assignment/bind operators in the surface.
Lean remains the language for types, pure expressions, propositions, and proofs.
The 𝒰[T] notation comes from Probability and has type Distribution.ProbDist T;
direct systems can use it without importing the component DSL.
interface, system, converter and filter declarations compile to the typed systems and
typed converters of Typed at every budget (DSL);
converters are declared as arrows of the category of
interfaces,
so that components assemble with ≫ and ⊗ₘ. Citations refer to the numbered
references of THEORY.md.
System and converter declarations accept a leading /-- ... -/ docstring. State the query,
reply and sampling rule there. Lean exposes it on the component and its .perPort and .exact
forms when those forms are generated. For example:
/-- Each eval(()) queries one inside bit b and returns its negation. -/
converter Negate : Evaluation Unit Bool
inside oracle : Evaluation Unit Bool
on eval(_trigger : Unit) → Bool
b ← oracle.eval(())
return !bUse the constructor guide for laws, sources and reusable reply transformations before defining a custom component.
block(P) is a newline followed by one or more equally indented occurrences
of P. Nested blocks must be further indented. Square brackets in the grammar
denote optional syntax; quoted brackets are literal. * means repetition.
declaration ::= interface | system | converter | filter | system_definition | LeanDeclaration
docstring ::= "/--" Text "-/"
parameters ::= ("(" names ":" Type ")" | "[" Instance "]")*
arguments ::= [argument ("," argument)*]
argument ::= Name ":" Type
interface ::= "interface" Name parameters block(port)
port ::= Name "(" arguments ")" "→" Type
system ::= [docstring] "system" Name parameters [":" InterfaceApplication]
block(system_member) ["by" Proof]
system_member ::= requirement | domain | outside | initialization | reply
converter ::= [docstring] "converter" Name parameters [":" InterfaceApplication]
block(converter_member)
converter_member ::= requirement | outside | inside | initialization | reply
outside ::= "outside" Name ":" InterfaceApplication
inside ::= "inside" Name ":" InterfaceType
InterfaceType ::= Type "→" Type | InterfaceApplication
requirement ::= "requires" Name ":" Proposition
domain ::= "domain" Name "↦" Proposition
filter ::= "filter" Name parameters ":" InterfaceApplication
"domain" Name "↦" Proposition ["by" Proof]
initialization ::= "initialize" block(statement)
reply ::= "on" PortPath "(" arguments ")" "→" Type block(statement)
statement ::= assignment | sampling | conditional | iteration | matching | returning
assignment ::= target [":" Type] "←" Expression
| target [":" Type] "←" oracle_call
sampling ::= target [":" Type] "←$" Distribution
target ::= Name | "(" Name ("," Name)+ ")"
Distribution ::= "𝒰[" Type "]" | Expression
oracle_call ::= PortPath "(" [Expression ("," Expression)*] ")"
conditional ::= "if" Expression block(statement) ["else" block(statement)]
iteration ::= "for" Name "∈" Expression block(statement)
matching ::= "match" Expression block(match_case)
match_case ::= "|" Pattern "→" block(statement)
returning ::= "return" Expression
system_definition ::= [docstring] "system" Name parameters "≔" SystemExpression
SystemExpression ::= ComponentExpression | "(" SystemExpression ")"
| SystemExpression "∥" SystemExpression
| SystemExpression "≫" SystemExpression
| SystemExpression "•" SystemExpression
| SystemExpression "⊗ₘ" SystemExpression
Single-port interface declarations supply their unique label automatically.
The first assignment in a scope introduces a binding; reassignment updates the
existing binding. Bindings introduced at the outer level of initialization
persist across invocations. New bindings inside an on block belong to that
invocation. Branch and loop locals do not escape their block; assignments to
existing bindings do. Tuple assignment is simultaneous. Initialization must
define every persistent binding before use. The parameters of an on block cannot silently
shadow persistent bindings. Every reachable path of an on block returns exactly once.
Only a call to a declared inside port is an interaction. It appears as the
right-hand side of an assignment. Pure Lean expressions cannot hide such calls.
Sampling draws from the specified normalized finite-support law each time the
statement is reached. The law is closed: it may depend on declaration parameters, not on
bindings or procedure arguments; sample from a fixed law and compute from the sample. A sample
in initialization is made once; samples in on blocks are fresh on successive invocations.
Loops traverse ordered finite sequences. A finite list for each input does not
by itself establish a uniform inside-query bound. No unbounded while or
recursive effectful calls are implicit in this grammar. Ordinary terminating
Lean functions remain available in pure expressions.
Every generated object is finite: alphabets are finite types and histories have a bounded
length. Oracle names are local interface labels. Their argument types form that interface's
input type; their return type is its output type. Both must be finite (Fintype); a type
parameter of an interface carries its [Fintype] instance. Return types may depend on
component parameters, but not on the current query value. interface I declares the family
I q := Interface.queryBudget … q of its query budgets. A : InterfaceApplication annotation
selects that vocabulary. Without an annotation or named outside components, the declaration
creates its own Name.Port,
Name.Input, and Name.Output, with their finiteness at each port, Name.fintypeInput and
Name.fintypeOutput. Each alphabet takes only the parameters its ports mention (closed under the
parameters' types and instance arguments), so instance search on the alphabet at a port
determines every argument. With two or more ports these are instances, so the alphabet at a variable
port is finite by instance search; with one port the alphabet reduces to its declared type, whose
own instances apply.
A system declares a typed system for every budget: S : TypedSystem (I q) with the implicit
argument budget. Its default domain consists of the histories of one to q inputs. An
explicit domain h ↦ P is intersected with the budget and requires the nonempty-prefix
condition, proved in by. This clause belongs to a system without an interface annotation.
Private initialization does not emit a message. An error reply is an ordinary declared output
value.
Named outside components select an ordered tensor. For example:
system Store
outside read : Reading
outside write : Writing
initialize
value ← false
on read.get() → Bool
return value
on write.put(b : Bool) → Unit
value ← b
return ()With Reading exposing get() → Bool and Writing exposing put(b : Bool) → Unit,
Store (budget := (r, w)) : TypedSystem (Reading r ⊗ Writing w). The label of read.get
is Sum.inl .get, and that of write.put is Sum.inr .put. Each history projection respects
its own budget: at most r reads and at most w writes, not r + w queries of either kind.
The state value is shared by both procedures; the tensor describes the outside interface,
while the component supplies one joint system on it.
Three components a : A, b : B, c : C give A q₁ ⊗ (B q₂ ⊗ C q₃) with
budget := (q₁, q₂, q₃). One named component keeps a scalar budget and its interface's labels.
Every procedure is qualified by its component, as in read.get. Initialization, including
sampling, runs once for the whole component, so an initial sample is one draw shared by all
components. C.perPort takes one budget function q on the tagged labels, giving
A.perPort (fun i => q (.inl i)) ⊗ B.perPort (fun i => q (.inr i)) for two components.
A converter with per-invocation bound b gets the inside allowance of b times the outside
interface's total bound: b * (q₁ + q₂) at budget := (q₁, q₂), and b times the sum of all
per-port budgets for C.perPort. In the exact-cost form C.exact, queries is the tuple of
outside budgets and budget is the scalar work bound. Named outside components and an interface
annotation are alternative declarations of the outside interface.
interface I also declares I.perPort q := Interface.portBudget … q for a budget
q : I.Port → ℕ per port: at most q i queries at each port i. A system without an exact
domain also gets S.perPort : TypedSystem (I.perPort q). A converter with one annotated outside
interface and a single inside port is typed by per-port budgets along a partial port map
C.portMap : I.Port → Option J.Port, which sends each procedure to the inside label it calls, or
to none when it calls none (C.preserving, a Program.PortPreserving proof: each procedure
calls at most its own label, at most once).
- When the inside port has the outside interface
I, each procedure calling its own port, it is the endomorphismC.perPort : I.perPort q ⟶ I.perPort q. - When the inside port has another declared interface
J, each of whose labels one procedure calls, it isC.perPort : I.perPort q ⟶ J.perPort (C.insideBudget q): the budget at an inside label is that of the procedure calling it, and a procedure calling nothing needs none ($\rho^{ctxt}$ of [9], fromAE M CtoEncryption M C).
Its sources have the budget C.bound * ∑ i, q i. Converters with named outside components have
the aggregate per-port typing above; other converters have no per-port typing.
The budget is the implicit argument budget in both forms, a number for I q and a function
of the port for I.perPort q: S (budget := k), C.perPort (budget := q). C.exact also takes
the implicit queries. These two names are reserved. Every other name the generated
declarations bind is hygienic, and a system, converter or filter that mentions budget or
queries, as a parameter, a binding or a reference, is rejected; a named argument
(budget := k) is not a mention. So a component's own names keep their meaning in every
generated declaration.
requires h : P is a visible premise, supplied when the component is instantiated.
A converter's per-invocation inside-query bound is inferred from its operations. When every
loop runs over a displayed literal list, C.bound is the numeral read off the displayed calls:
a call counts one, a conditional or a match the largest count of its branches, a loop over
[a₁, …, aₙ] n times its body's count, and the bound is the largest count over the
procedures, initialization included; its proof first reduces the literal fold. Otherwise, for
finite inputs and private bindings, C.bound is the least bound, a supremum over them. The
elaborator generates C.bound,
C.bound_spec, and
C : I q ⟶ J (C.bound * q) for every budget q, where the inside interfaces J are at budget
C.bound * q. A converter without a uniform bound is rejected. When a converter samples nothing
and the number of inside calls of an invocation is a function of its input alone, the
elaborator also infers that count C.cost and generates the exact typing
C.exact : (I n).restrict (fun h => (h.map C.cost).sum ≤ q) ⟶ J q: outside histories of total
cost at most q need q inside queries. It is omitted when the count depends on inside
replies or private bindings.
A filter F : I domain h ↦ P gives F : (I q).restrict P ⟶ I q for every budget: it forwards
the queries of an admitted history and stops on the others [3, §3.4.3]. The admitted
predicate must be closed under prefixes; by supplies a proof when the default tactic does
not find one.
A component compiles to a deterministic program with sources of randomness: sampling stays in the surface, and randomness enters the generated systems only through sources of fresh samples of a closed law [4, Definition 1].
- Every sampling statement
x ←$ Pbecomes a callx ← sample_k()to a synthetic inside port whose source draws fresh samples fromP; the law isC.law_k. - The body
C.body : Program (Option S) …is a function of the inside exchanges of the current invocation, giving the next inside query or the reply and the new private bindings (a deterministic automaton [4, Definition 2]). Initialization runs in the first invocation, when no bindings are stored yet;Sis the type ofC.initial, the initial bindings with each sample replaced by a value of its law. - Computation is ordinary
letbindings; control flow is ordinary conditionals, pattern matching and list folds (forEach); a call iscallProg, a replyreturnProg. C.program : I q ⟶ J (C.bound * q)is the converter of the program (TypedConverter.ofProgram), on the outside domain ofI q.- A converter is
C.program ≫ TypedConverter.rightContext J (C.randomness k): its program with its sources attached beside the declared inside ports, each source at the inside budgetk. A converter that samples nothing isC.program. - A system is
C.program • C.randomness k. A system that samples nothing is the automaton of its program started inC.initial,TypedSystem.ofAutomaton I step (single s).
The declarations generate typed systems and typed converters at every budget. An
interface I declaration generates I q := Interface.queryBudget … q, the
query budget, and I.perPort q := Interface.portBudget … q, the
per-port budget. A system S : I generates the typed
system S : TypedSystem (I q), compiled to S.program • S.randomness k: the
converter of its program attached to its sources. A
system that samples nothing is the automaton of its program, and
a system without an exact domain also gets
S.perPort : TypedSystem (I.perPort q).
A converter C : I with inside J generates C : I q ⟶ J (C.bound * q),
compiled to C.program ≫ TypedConverter.rightContext J (C.randomness k): its program with its
sources beside the inside interface, or C.program when it
samples nothing. In that case,
C.eq_ofProgram gives C = TypedConverter.ofProgram none C.body hb hB at the chosen
budget, using its generated call-bound and domain certificates. Rewrite with this equation
under attachment to apply a program law without unfolding C.
C.bodyAt q is the same body with the interfaces at budget q, for use in program-family laws.
For a converter with fresh draws the inside interface includes its sources. With
an annotated outside interface and a single inside interface it
also has a per-port typing along a partial port
map C.portMap : I.Port → Option J.Port, through the
converter of a port-preserving program, with
C.preserving a proof of Program.PortPreserving. When J is I and
each procedure calls its own port, at most once, it is
C.perPort : I.perPort q ⟶ I.perPort q. When J is another interface, each of whose labels one
procedure calls at most once, it is C.perPort : I.perPort q ⟶ J.perPort (C.insideBudget q): an
inside label has the budget of the procedure calling it, and a procedure calling nothing maps to
none and needs no inside budget, as in the write-through cache and in
C.exact : (I n).restrict (fun h => (h.map C.cost).sum ≤ q) ⟶ J q, the
converter of the costed program.
A filter F : I domain h ↦ P generates F : (I q).restrict P ⟶ I q, the
filter admitting P.
Attaching a program to a typed system runs its body against the system
(Program.apply_ofProgram, [4, §3.3]). A transcript of C.program • R has the mass of
the system's deterministic systems on which the inlined program gives it
(TypedConverter.ofDDC_ofProgramOn_smul_ofPDS). Sources are automata whose initial state is a
table of samples (TypedSystem.ofAutomaton I step initial, [4, Definition 2], with the
randomness in the initial state); parallel automata are the automaton of both
(TypedSystem.parallel_ofAutomaton), and attaching a program to an automaton
gives the combined automaton (Program.combine),
also for port-preserving programs and
for costed programs. Every
compiled component is therefore an automaton with a sampled initial state, and compiled systems
are compared by bisimulation: bisimilar automata have the same
system. The memoryless source y ←$ ν; return y
is the memoryless system of ν, so systems built from programs
and memoryless sources are compared by the laws of one reply, through the composition laws of
typed systems:
each hop of PRG length extension rewrites with these contracts and an identity of laws.
A component declaration also generates proved equations for its procedures. For a procedure
get, a deterministic system has C.step_get; a program has C.body_get_initial and
C.body_get_resumed. The latter two distinguish none before initialization from some state
afterward. For a converter without initialize, C.body_get applies at any state.
When two ports are named get and get_initial, the latter uses C.get_initial.body
so C.body_get_initial still names the first-call equation of get.
A named outside procedure read.get puts its equations in C.read.
When the compiler proves a displayed constant call bound, it also generates
C.combine_get_initial, C.combine_get_resumed,
C.memorylessReplyLaw_get_initial and C.memorylessReplyLaw_get_resumed. The first pair gives
one invocation against an arbitrary deterministic inside transition, with the reply and both next
states; the second gives its reply law when each inside call gets a fresh sample of arbitrary
inside laws ν. Straight-line bodies and loops over displayed literal lists are fully evaluated.
A component with a symbolic loop gets only the body equations, with the existing inferred
bound: its loops are not evaluated, enumerated or given a new bound.
All these equations are ordinary kernel-checked equalities in the dedicated
component_equations simplification set. Use simp only [component_equations] to expose them.
They do not enter global simplification. Only the component's body or step and the fixed
program combinators are unfolded; other definitions and user-defined pure functions stay opaque.
-- Rewrite the attachment as the existing combined automaton; the brackets are optional aliases.
inline [Converter, System]
-- With the supplied memorylessness certificate, expose each procedure's reply law.
inline using inside_is_memoryless
-- The second certificate is for the converter's own source beside its inside system.
inline using inside_is_memoryless, source_is_memorylessThe compiler registers the wrappers each declaration newly generates (C, C.program,
C.perPort, C.perPortProgram, C.randomness, C.exact) in component_definitions, and
inline expands them itself, so a plain inline, or inline using its certificates, suffices
for a declared component. Bodies, pure functions and initial values are not registered, and a
declaration with errors gets neither equations nor registrations. The optional brackets name
further user aliases to unfold.
The attachment law is selected by the displayed constructor of the attached converter,
ofProgram, ofPreservingProgram or ofCostedProgram, so C.exact keeps its cost-restricted
domain and no other budget obligation arises. Without a certificate, inline rewrites the
attachment as the combined automaton and simplifies with the generated equations. A converter
with its own source is first reshaped by Interface.comp_smul,
TypedConverter.attach_rightContext and TypedSystem.parallel_ofAutomaton: the source runs
beside the inside automaton, and both are one automaton with step parallelStep. Direct
attachments to parallel sources use the same source and parallel normalization. With a
certificate hR : R = TypedSystem.ofMemoryless B ν, the typed memoryless contract of that
constructor reduces C • R = TypedSystem.ofMemoryless A κ to the reply law of one invocation
in every state:
Cumulative equalities are also accepted as certificates and goals.
inline then splits only the generated Option state (none before initialization, some s
after) and the procedure labels, and rewrites with the generated equations. A second
certificate is for the converter's own source beside its inside system: the two certificates
combine through TypedSystem.parallel_eq_ofMemoryless, and the program then runs against their
side-by-side laws parallelLaw ν ν'.
The command applies only the existing attachment laws and generated equations. The caller
proves the remaining identities of probability laws and any state relations. Initial-state
laws normalize with prodProbDist_map and ProbDist.map_map. In particular, a sample retained by
initialization becomes a point law at the stored value on resumed calls; inlining does not
replace it with fresh independent samples. PRG length extension defines its real world
as the mapped MemorylessSource; its two converter contracts use inline followed by
reflexivity or the product-law identity.
The assembly operators denote the existing CC operations. α • R applies a
converter, α ≫ β composes converters, and ∥ and ⊗ₘ compose systems and
converters in parallel. Parallel composition is independent; copying
a system expression does not create shared state. Sharing is expressed by
one component with multiple interfaces or by initialization enclosing all the
shared behavior. A definition system D ≔ e takes its outside interface from the outermost
component of e, at the implicit budget; the inner budgets follow from the converters' types.
There is no attach A[ports] ↔ B[ports] wiring form.
The grammar above records the implemented DSL; it makes no claim that
arbitrary feedback wiring can omit the existing domain and termination obligations.
Examples must cover persistent and fresh randomness, state across interleaved
interfaces, reassignment and tuple binding, branches and matching, bounded
multi-query iteration, exact partial domains, and typed composition. Rejection
checks must cover uninitialized variables, hidden calls, wrong message types,
missing return paths, unproved bounds, laws that depend on bindings, and inside calls in
initialization. The AES example uses AES-256 of Commons.Schemes.BlockCipher.AES.
Semantic and construction theorems are checked by Lean with the standard axiom envelope only.
Examples/DSL/Components.lean covers counters, interleaved interfaces, fresh versus persistent
bits, branches, matching, tuple assignment, list folds, an exact domain, the inferred cost of
Padding (Padding.exact), a write-through converter from Cache to Store whose reads need no
inside budget (WriteThrough.perPort), and a filter. Examples/DSL/AES.lean uses AES-256 of
Commons,
answering at the interface Evaluation, for serial converters, fresh masks, a two-key cascade,
and CBC-MAC over a finite message space M. CBC blockForm processes blockForm message, so
each invocation
can have a different number of blocks; CBC.exact types it by the total number of blocks.
These examples specify systems; they do not establish new security bounds.
Examples/DSL/AEAD.lean builds AES-CTR with PMAC authentication and associated data from
three Commons converters: CTR, PMAC and nonceEncryptThenMAC. Its complete assembly is
nonceEncryptThenMAC Nonce Message Message Block •
((CTR (2 ^ 36) • AES) ∥ (PMAC authenticationBytes • AES))The two AES systems sample independent AES-256 keys. Messages and associated data are byte strings of at most 2³⁶ bytes; each CTR call runs from the counter block of a 96-bit nonce with a 32-bit block counter. Authentication covers the nonce, both string lengths, associated data, and ciphertext. Decryption verifies the tag with PMAC before calling CTR. Nonce uniqueness for encryption is the caller's security obligation. This example specifies the composition, without claiming a security reduction or a standardized AEAD mode.
Examples/DSL/AEADTests.lean proves the generated encrypt/verify/reject interaction paths of
the program's converter (TypedConverter.ofDDC_apply), checks the encoding bounds, and checks the
combination as functions (CTR.crypt and PMAC.pmac): decryption inverts encryption, and
modified inputs are rejected. The published CTR and PMAC vectors are checked in
Commons/Tests, on the functions; they are separate from a proof that the converters
compute them, or of the scheme's security.
Tests/DSL/Semantics.lean checks behavior across calls on the inlined programs,
Tests/DSL/Diagnostics.lean checks rejected declarations, and Tests/DSL/Axioms.lean audits
the compilation and semantic results.
Import ConstructiveCryptography.DSL and open
SystemAlgebra.DSL plus open scoped SystemAlgebra.DSL to use the
declarations. Open CategoryTheory and its MonoidalCategory namespace for
the inherited composition and tensor notation, as in Examples/DSL/AES.lean.
Environment and distinguisher declarations are not syntax forms of the DSL. Environments
(DDE), distinguishers and their compatibility with a domain are systems-level definitions;
see Domain.Compatible and Domain.DecisionCompatible in
Decision. On an interface the distinguishers are
TypedDistinguisher A, in Typed/Distinguisher.
To check the DSL and its tests, run from the repository root:
lake build Tests.DSL.Diagnostics Tests.DSL.AxiomsThe proof commands are in ConstructiveCryptography.Tactics.
cc_normalize rewrites attachments to normal forms,
cc_nonexpand applies the compatibility laws, on interfaces also
with the concrete parallel composition, cc_triangle
takes a hybrid step, and cc_construct reduces a construction to its equality or
distance obligation. cc_calc constructs chains exact (—[π]→),
approximate (—[π; ε]→), and exact-equality (=) construction steps, composing converters in
attachment order (π₂ ≫ π₁) and summing scalar budgets. cc_calc relation proves = and ≃ steps,
and cc_calc counted systems builds an implication witness, whose uses
cc_usage counts. cc_calc statistical proves
≈[ε] steps, and
cc_calc mixed model using domination proves
≃[loss] and ≈[ε] steps, where domination bounds
each admitted advantage by the distance. Written without a model, cc_calc quantitative and
cc_calc mixed read the exact model of the SubstitutesWithin goal; the inferred mixed form
takes its domination law from a DominatedByDistance instance for that model and fails without
one.
Importing ConstructiveCryptography.Notation registers the typed attachment laws and the
representation equalities connecting them to categorical arrows and the selected CC instance.
Thus cc_normalize handles direct typed and categorical serial composition, binary and finite
parallel families, and the attachment goals produced by cc_construct. In particular, it proves
(⨂ₘ k, α k) • (∥ k, R k) = ∥ k, (α k • R k) and pushes attachment through initial sampling
from any normalized law. Nested laws may depend on earlier draws. Every draw stays in its
original scope: a sample shared by a whole family remains shared, rather than becoming
independent component samples. A separately supplied action is not replaced by the canonical
one. The same import makes Δ R S and R ∥ S read typed-system operands first, so that the
interfaces and budgets of DSL attachments are inferred; any other carrier keeps its own
selected metric and parallel operation. The
before/after proofs, expression guards, negative tests and exact rewrite traces are in
Tests.ProofErgonomics.