Skip to main content

oxilean_std/cryptographic_protocols/
functions.rs

1//! Auto-generated module
2//!
3//! ๐Ÿค– Generated with [SplitRS](https://github.com/cool-japan/splitrs)
4
5use oxilean_kernel::{BinderInfo, Declaration, Environment, Expr, Level, Name};
6
7use super::types::{
8    BlindSignatureScheme, CommitmentScheme, GarbledGate, MPCProtocol, MpcShare, OTVariant,
9    ObliviousTransfer, PaillierHomomorphic, PedersenCommitment, PedersenParams, SchnorrParams,
10    SecretSharing, ShamirSS, ShamirSecretSharingExtended, ZKProofSystem,
11};
12
13pub fn app(f: Expr, a: Expr) -> Expr {
14    Expr::App(Box::new(f), Box::new(a))
15}
16pub fn app2(f: Expr, a: Expr, b: Expr) -> Expr {
17    app(app(f, a), b)
18}
19pub fn app3(f: Expr, a: Expr, b: Expr, c: Expr) -> Expr {
20    app(app2(f, a, b), c)
21}
22pub fn cst(s: &str) -> Expr {
23    Expr::Const(Name::str(s), vec![])
24}
25pub fn prop() -> Expr {
26    Expr::Sort(Level::zero())
27}
28pub fn type0() -> Expr {
29    Expr::Sort(Level::succ(Level::zero()))
30}
31pub fn pi(bi: BinderInfo, name: &str, dom: Expr, body: Expr) -> Expr {
32    Expr::Pi(bi, Name::str(name), Box::new(dom), Box::new(body))
33}
34pub fn arrow(a: Expr, b: Expr) -> Expr {
35    pi(BinderInfo::Default, "_", a, b)
36}
37pub fn nat_ty() -> Expr {
38    cst("Nat")
39}
40pub fn bool_ty() -> Expr {
41    cst("Bool")
42}
43pub fn list_nat() -> Expr {
44    app(cst("List"), nat_ty())
45}
46pub fn msg_ty() -> Expr {
47    list_nat()
48}
49/// `DYMessage : Type`
50///
51/// The message algebra of the Dolev-Yao model:
52/// atoms (nonces, keys, identities), pairs `โŸจm1, m2โŸฉ`, symmetric
53/// encryption `{m}k`, and public-key encryption `{m}pk`.
54pub fn dy_message_ty() -> Expr {
55    type0()
56}
57/// `DYPrincipal : Type`
58///
59/// A principal (agent) in a protocol run: honest or dishonest.
60pub fn dy_principal_ty() -> Expr {
61    type0()
62}
63/// `DYKnowledge : DYPrincipal โ†’ List DYMessage โ†’ Type`
64///
65/// The knowledge set of a principal: the set of messages they can derive
66/// from a given set of intercepted messages using Dolev-Yao operations.
67pub fn dy_knowledge_ty() -> Expr {
68    arrow(
69        dy_principal_ty(),
70        arrow(app(cst("List"), dy_message_ty()), type0()),
71    )
72}
73/// `DYDerivable : List DYMessage โ†’ DYMessage โ†’ Prop`
74///
75/// `DYDerivable S m` holds iff the Dolev-Yao intruder can derive message `m`
76/// from the set `S` using the standard operations:
77/// decompose pairs, encrypt/decrypt with known keys, compose pairs.
78pub fn dy_derivable_ty() -> Expr {
79    arrow(
80        app(cst("List"), dy_message_ty()),
81        arrow(dy_message_ty(), prop()),
82    )
83}
84/// `DYAttack : Protocol โ†’ Prop`
85///
86/// A Dolev-Yao attack on a protocol: the intruder, by intercepting and
87/// replaying messages, can violate some security property.
88pub fn dy_attack_ty() -> Expr {
89    arrow(cst("Protocol"), prop())
90}
91/// `DYIntruder : Type`
92///
93/// The Dolev-Yao intruder model: full control over the network, can
94/// eavesdrop, block, replay, modify, and inject messages.
95pub fn dy_intruder_ty() -> Expr {
96    type0()
97}
98/// `Confidentiality : Protocol โ†’ Principal โ†’ Message โ†’ Prop`
99///
100/// A message `m` remains confidential in protocol `P` for principal `A`:
101/// no adversary can learn `m` by participating in or observing `P`.
102pub fn confidentiality_ty() -> Expr {
103    arrow(
104        cst("Protocol"),
105        arrow(dy_principal_ty(), arrow(msg_ty(), prop())),
106    )
107}
108/// `Integrity : Protocol โ†’ Message โ†’ Prop`
109///
110/// Message integrity in protocol `P`: the received message equals the
111/// sent message; it has not been altered in transit.
112pub fn integrity_ty() -> Expr {
113    arrow(cst("Protocol"), arrow(msg_ty(), prop()))
114}
115/// `Authentication : Protocol โ†’ Principal โ†’ Principal โ†’ Prop`
116///
117/// Entity authentication: after completing protocol `P`, principal `B`
118/// is assured they are communicating with `A` (not an impostor).
119pub fn authentication_ty() -> Expr {
120    arrow(
121        cst("Protocol"),
122        arrow(dy_principal_ty(), arrow(dy_principal_ty(), prop())),
123    )
124}
125/// `NonRepudiation : Protocol โ†’ Principal โ†’ Message โ†’ Prop`
126///
127/// Non-repudiation: principal `A` cannot later deny having sent message `m`
128/// in protocol `P` (typically achieved via digital signatures).
129pub fn non_repudiation_ty() -> Expr {
130    arrow(
131        cst("Protocol"),
132        arrow(dy_principal_ty(), arrow(msg_ty(), prop())),
133    )
134}
135/// `FreshNonce : Message โ†’ Prop`
136///
137/// A nonce is fresh: it has not appeared in any previous protocol run,
138/// making replay attacks detectable.
139pub fn fresh_nonce_ty() -> Expr {
140    arrow(msg_ty(), prop())
141}
142/// `ProtocolCompose : Protocol โ†’ Protocol โ†’ Protocol`
143///
144/// Sequential composition of two protocols: run P1 then P2.
145pub fn protocol_compose_ty() -> Expr {
146    arrow(cst("Protocol"), arrow(cst("Protocol"), cst("Protocol")))
147}
148/// `ProtocolParallel : Protocol โ†’ Protocol โ†’ Protocol`
149///
150/// Parallel composition: run P1 and P2 concurrently (possibly interleaved).
151pub fn protocol_parallel_ty() -> Expr {
152    arrow(cst("Protocol"), arrow(cst("Protocol"), cst("Protocol")))
153}
154/// `SecurityPreservedUnderComposition : Protocol โ†’ Protocol โ†’ Prop`
155///
156/// If P1 and P2 are each secure in isolation, their sequential composition
157/// is also secure (modulo the UC composition theorem).
158pub fn security_preserved_composition_ty() -> Expr {
159    arrow(cst("Protocol"), arrow(cst("Protocol"), prop()))
160}
161/// `SigmaProtocol : Type`
162///
163/// A Sigma protocol ฮฃ = (P, V, challenge_space) for a relation R:
164/// - Prover sends commitment `a`
165/// - Verifier sends random challenge `e`
166/// - Prover sends response `z`
167/// - Verifier accepts/rejects based on (x, a, e, z)
168pub fn sigma_protocol_ty() -> Expr {
169    type0()
170}
171/// `SigmaCommitment : SigmaProtocol โ†’ Type`
172///
173/// The commitment message type (first move) in a Sigma protocol.
174pub fn sigma_commitment_ty() -> Expr {
175    arrow(sigma_protocol_ty(), type0())
176}
177/// `SigmaChallenge : SigmaProtocol โ†’ Type`
178///
179/// The challenge type (second move): a random element from the challenge space.
180pub fn sigma_challenge_ty() -> Expr {
181    arrow(sigma_protocol_ty(), type0())
182}
183/// `SigmaResponse : SigmaProtocol โ†’ Type`
184///
185/// The response type (third move) in a Sigma protocol.
186pub fn sigma_response_ty() -> Expr {
187    arrow(sigma_protocol_ty(), type0())
188}
189/// `SigmaCompleteness : SigmaProtocol โ†’ Prop`
190///
191/// Completeness of a Sigma protocol: an honest prover who knows a valid
192/// witness always convinces the honest verifier.
193pub fn sigma_completeness_ty() -> Expr {
194    arrow(sigma_protocol_ty(), prop())
195}
196/// `SigmaSpecialSoundness : SigmaProtocol โ†’ Prop`
197///
198/// Special soundness: given two accepting transcripts `(a, e, z)` and
199/// `(a, e', z')` with `e โ‰  e'` and same commitment `a`, one can efficiently
200/// extract a witness for the statement.
201pub fn sigma_special_soundness_ty() -> Expr {
202    arrow(sigma_protocol_ty(), prop())
203}
204/// `SigmaHVZK : SigmaProtocol โ†’ Prop`
205///
206/// Honest-Verifier Zero-Knowledge: there exists a simulator that, given
207/// only the public input, produces transcripts indistinguishable from
208/// real ones (when the verifier behaves honestly).
209pub fn sigma_hvzk_ty() -> Expr {
210    arrow(sigma_protocol_ty(), prop())
211}
212/// `ZKProof : Type`
213///
214/// A zero-knowledge proof system (P, V) for a language L:
215/// - Completeness: honest prover convinces honest verifier for x โˆˆ L
216/// - Soundness: cheating prover fails with high probability for x โˆ‰ L
217/// - Zero-knowledge: verifier learns nothing beyond x โˆˆ L
218pub fn zk_proof_ty() -> Expr {
219    type0()
220}
221/// `ZKCompleteness : ZKProof โ†’ Prop`
222///
223/// If `x โˆˆ L` and the prover knows witness `w`, the verifier accepts.
224pub fn zk_completeness_ty() -> Expr {
225    arrow(zk_proof_ty(), prop())
226}
227/// `ZKSoundness : ZKProof โ†’ Prop`
228///
229/// If `x โˆ‰ L`, no computationally bounded cheating prover can convince
230/// the verifier to accept (except with negligible probability).
231pub fn zk_soundness_ty() -> Expr {
232    arrow(zk_proof_ty(), prop())
233}
234/// `ZKZeroKnowledge : ZKProof โ†’ Prop`
235///
236/// The verifier's view can be simulated without a witness: the interaction
237/// reveals no information about the witness beyond the statement being true.
238pub fn zk_zero_knowledge_ty() -> Expr {
239    arrow(zk_proof_ty(), prop())
240}
241/// `NIZK : Type`
242///
243/// Non-Interactive Zero-Knowledge proof in the random oracle model.
244/// Obtained from interactive ZK via the Fiat-Shamir transform:
245/// replace verifier's random challenge with a hash of the commitment.
246pub fn nizk_ty() -> Expr {
247    type0()
248}
249/// `FiatShamirTransform : SigmaProtocol โ†’ NIZK`
250///
251/// The Fiat-Shamir heuristic converts any Sigma protocol into a NIZK
252/// in the random oracle model by hashing (statement โˆฅ commitment) for the challenge.
253pub fn fiat_shamir_transform_ty() -> Expr {
254    arrow(sigma_protocol_ty(), nizk_ty())
255}
256/// `ZKSnark : Type`
257///
258/// A zk-SNARK: Succinct Non-interactive ARgument of Knowledge.
259/// - Succinct: proof size is sublinear in the circuit size
260/// - Non-interactive: single message from prover to verifier
261/// - Argument of Knowledge: knowledge extractor exists (with CRS)
262pub fn zk_snark_ty() -> Expr {
263    type0()
264}
265/// `SnarkSuccinctness : ZKSnark โ†’ Prop`
266///
267/// Succinctness: proof verification time is poly(|x|, log|C|)
268/// where |C| is the circuit size and |x| is the statement size.
269pub fn snark_succinctness_ty() -> Expr {
270    arrow(zk_snark_ty(), prop())
271}
272/// `CommitmentScheme : Type`
273///
274/// A commitment scheme (Setup, Commit, Open, Verify):
275/// - Commit(m, r) โ†’ c  (commit to m with randomness r)
276/// - Verify(c, m, r) โ†’ Bool  (verify opening)
277pub fn commitment_scheme_ty() -> Expr {
278    type0()
279}
280/// `CommitHiding : CommitmentScheme โ†’ Prop`
281///
282/// Hiding: the commitment `c = Commit(m, r)` reveals no information
283/// about `m` to a computationally bounded adversary.
284pub fn commit_hiding_ty() -> Expr {
285    arrow(commitment_scheme_ty(), prop())
286}
287/// `CommitBinding : CommitmentScheme โ†’ Prop`
288///
289/// Binding: it is computationally infeasible to open a commitment to
290/// two different values `(m, r)` and `(m', r')` with `m โ‰  m'`.
291pub fn commit_binding_ty() -> Expr {
292    arrow(commitment_scheme_ty(), prop())
293}
294/// `PedersenCommitment : CommitmentScheme`
295///
296/// Pedersen commitment in group G with generators g, h:
297/// `Commit(m, r) = g^m ยท h^r`
298/// - Perfectly hiding (information-theoretically secure)
299/// - Computationally binding (under discrete-log assumption)
300pub fn pedersen_commitment_ty() -> Expr {
301    commitment_scheme_ty()
302}
303/// `ObliviousTransfer : Type`
304///
305/// 1-of-2 Oblivious Transfer: the sender has secrets (s0, s1),
306/// the receiver has choice bit b โˆˆ {0, 1}.
307/// The receiver obtains s_b; the sender learns nothing about b.
308pub fn oblivious_transfer_ty() -> Expr {
309    type0()
310}
311/// `OTReceiverPrivacy : ObliviousTransfer โ†’ Prop`
312///
313/// Receiver privacy: the sender cannot determine which of the two
314/// secrets the receiver chose to obtain.
315pub fn ot_receiver_privacy_ty() -> Expr {
316    arrow(oblivious_transfer_ty(), prop())
317}
318/// `OTSenderPrivacy : ObliviousTransfer โ†’ Prop`
319///
320/// Sender privacy: the receiver learns exactly one secret and gains
321/// no information about the other (beyond what is leaked by s0 = s1).
322pub fn ot_sender_privacy_ty() -> Expr {
323    arrow(oblivious_transfer_ty(), prop())
324}
325/// `OTExtension : Nat โ†’ Nat โ†’ Prop`
326///
327/// OT extension: given `k` base OTs, one can realize `n >> k` OTs
328/// using only symmetric-key operations (Ishai-Kilian-Nissim-Petrank).
329pub fn ot_extension_ty() -> Expr {
330    arrow(nat_ty(), arrow(nat_ty(), prop()))
331}
332/// `ShamirSecretSharing : Nat โ†’ Nat โ†’ Type`
333///
334/// Shamir's (t, n)-threshold secret sharing scheme:
335/// - Split a secret into n shares
336/// - Any t shares suffice to reconstruct the secret
337/// - Any t-1 shares reveal nothing (information-theoretically)
338pub fn shamir_secret_sharing_ty() -> Expr {
339    arrow(nat_ty(), arrow(nat_ty(), type0()))
340}
341/// `SecretSharingThreshold : ShamirSecretSharing t n โ†’ Prop`
342///
343/// Threshold correctness: any set of t or more shares uniquely
344/// determines the secret via Lagrange interpolation over Fp.
345pub fn secret_sharing_threshold_ty() -> Expr {
346    arrow(nat_ty(), arrow(nat_ty(), prop()))
347}
348/// `SecretSharingPerfectPrivacy : ShamirSecretSharing t n โ†’ Prop`
349///
350/// Perfect privacy: any t-1 shares are identically distributed
351/// regardless of the secret value (information-theoretic security).
352pub fn secret_sharing_privacy_ty() -> Expr {
353    arrow(nat_ty(), arrow(nat_ty(), prop()))
354}
355/// `MPCProtocol : Type`
356///
357/// A multi-party computation protocol: n parties jointly compute
358/// a function f(x1, ..., xn) where each party i holds input xi.
359pub fn mpc_protocol_ty() -> Expr {
360    type0()
361}
362/// `MPCSemiHonestSecurity : MPCProtocol โ†’ Prop`
363///
364/// Semi-honest (passive) security: a simulator exists that, given
365/// a party's input and output, can reproduce its view of the protocol.
366/// Protects against adversaries who follow the protocol honestly.
367pub fn mpc_semi_honest_security_ty() -> Expr {
368    arrow(mpc_protocol_ty(), prop())
369}
370/// `MPCMaliciousSecurity : MPCProtocol โ†’ Prop`
371///
372/// Malicious (active) security: security holds even when corrupted
373/// parties deviate arbitrarily from the protocol specification.
374pub fn mpc_malicious_security_ty() -> Expr {
375    arrow(mpc_protocol_ty(), prop())
376}
377/// `GarbledCircuit : Type`
378///
379/// Yao's garbled circuit: a garbling of a boolean circuit that allows
380/// one party to learn f(x, y) without revealing their respective inputs.
381pub fn garbled_circuit_ty() -> Expr {
382    type0()
383}
384/// `GarbledCircuitCorrectness : GarbledCircuit โ†’ Prop`
385///
386/// Correctness: evaluating the garbled circuit with the garbled input
387/// produces the correct output of the underlying boolean function.
388pub fn garbled_circuit_correctness_ty() -> Expr {
389    arrow(garbled_circuit_ty(), prop())
390}
391/// `GarbledCircuitSecurity : GarbledCircuit โ†’ Prop`
392///
393/// Privacy (garbling security): the evaluator learns only the output,
394/// nothing about the garbler's input beyond what the output reveals.
395pub fn garbled_circuit_security_ty() -> Expr {
396    arrow(garbled_circuit_ty(), prop())
397}
398/// `IdealFunctionality : Type`
399///
400/// An ideal functionality F in the UC framework: a trusted third party
401/// that receives inputs from all parties and delivers outputs.
402/// Security is defined by emulating this ideal world in the real world.
403pub fn ideal_functionality_ty() -> Expr {
404    type0()
405}
406/// `UCSecure : MPCProtocol โ†’ IdealFunctionality โ†’ Prop`
407///
408/// UC security: protocol ฯ€ UC-realizes functionality F if for every
409/// real-world adversary A there exists an ideal-world simulator S such that
410/// no environment Z can distinguish the real and ideal executions.
411pub fn uc_secure_ty() -> Expr {
412    arrow(mpc_protocol_ty(), arrow(ideal_functionality_ty(), prop()))
413}
414/// `UCCompositionTheorem : Prop`
415///
416/// Universal Composition Theorem (Canetti 2001):
417/// If ฯ€ UC-realizes F and ฯ uses F as a sub-protocol, then the
418/// composed protocol ฯ^ฯ€ (replacing F-calls with ฯ€) UC-realizes
419/// the same functionality as ฯ.
420pub fn uc_composition_theorem_ty() -> Expr {
421    prop()
422}
423/// `HybridModel : IdealFunctionality โ†’ Type`
424///
425/// The hybrid model: a computational model where parties can access
426/// an ideal functionality F as a trusted oracle (sub-protocol).
427pub fn hybrid_model_ty() -> Expr {
428    arrow(ideal_functionality_ty(), type0())
429}
430/// `UCSimulator : MPCProtocol โ†’ IdealFunctionality โ†’ Type`
431///
432/// A UC simulator: given an ideal-world adversary (environment + simulator),
433/// it translates between the real and ideal executions.
434pub fn uc_simulator_ty() -> Expr {
435    arrow(mpc_protocol_ty(), arrow(ideal_functionality_ty(), type0()))
436}
437/// `UCEnvironment : Type`
438///
439/// The environment Z in the UC framework: it provides inputs to parties,
440/// observes outputs, and tries to distinguish real from ideal executions.
441pub fn uc_environment_ty() -> Expr {
442    type0()
443}
444/// `UCIndistinguishable : MPCProtocol โ†’ IdealFunctionality โ†’ Prop`
445///
446/// Computational indistinguishability between real and ideal executions:
447/// no polynomial-time environment can tell apart the two worlds.
448pub fn uc_indistinguishable_ty() -> Expr {
449    arrow(mpc_protocol_ty(), arrow(ideal_functionality_ty(), prop()))
450}
451/// `GMWProtocol : Nat โ†’ Type`
452///
453/// The GMW (Goldreich-Micali-Wigderson) n-party MPC protocol.
454/// Achieves semi-honest security for any polynomial-time function.
455pub fn gmw_protocol_ty() -> Expr {
456    arrow(nat_ty(), type0())
457}
458/// `GMWMaliciousSecure : GMWProtocol n โ†’ Prop`
459///
460/// Malicious security of GMW via zero-knowledge proofs at each gate.
461pub fn gmw_malicious_secure_ty() -> Expr {
462    arrow(nat_ty(), prop())
463}
464/// `OTExtensionCorrectness : Nat โ†’ Nat โ†’ Prop`
465///
466/// IKNP OT extension correctness: the extended OTs are functionally
467/// equivalent to base OTs from the receiver's perspective.
468pub fn ot_extension_correctness_ty() -> Expr {
469    arrow(nat_ty(), arrow(nat_ty(), prop()))
470}
471/// `YaoGarbledCircuitPrivacy : GarbledCircuit โ†’ Prop`
472///
473/// Yao's privacy theorem: the evaluator's view in a garbled circuit evaluation
474/// is simulable given only the circuit output and a "garbled input" (labels).
475pub fn yao_garbled_privacy_ty() -> Expr {
476    arrow(garbled_circuit_ty(), prop())
477}
478/// `KZGCommitment : Type`
479///
480/// KZG (Kate-Zaverucha-Goldberg) polynomial commitment scheme:
481/// - Commit to a polynomial f โˆˆ F_p[X] of degree โ‰ค d
482/// - Open at any point z with a short proof ฯ€
483/// - Verification: pairing check e(C - f(z)ยทG, H) = e(ฯ€, (ฯ„-z)ยทH)
484pub fn kzg_commitment_ty() -> Expr {
485    type0()
486}
487/// `KZGBinding : KZGCommitment โ†’ Prop`
488///
489/// Binding property of KZG under the d-Strong Diffie-Hellman assumption:
490/// a committer cannot open to two different polynomials.
491pub fn kzg_binding_ty() -> Expr {
492    arrow(kzg_commitment_ty(), prop())
493}
494/// `VectorCommitment : Type`
495///
496/// A vector commitment scheme VC = (Setup, Commit, Open, Verify):
497/// - Commit to a vector (m_1, ..., m_n) โ†’ C
498/// - Open position i with proof ฯ€_i
499/// - Binding at every position (position-binding)
500pub fn vector_commitment_ty() -> Expr {
501    type0()
502}
503/// `VectorCommitmentPositionBinding : VectorCommitment โ†’ Prop`
504///
505/// Position-binding: it is infeasible to open position i to two different values.
506pub fn vector_commitment_position_binding_ty() -> Expr {
507    arrow(vector_commitment_ty(), prop())
508}
509/// `Groth16Proof : Type`
510///
511/// Groth16 zk-SNARK: the most deployed SNARK in practice.
512/// - Trusted setup phase produces a common reference string (CRS)
513/// - Proof size: 3 group elements (โ‰ˆ192 bytes for BN254)
514/// - Verification: 3 pairing operations
515pub fn groth16_proof_ty() -> Expr {
516    type0()
517}
518/// `Groth16Soundness : Groth16Proof โ†’ Prop`
519///
520/// Computational knowledge soundness of Groth16 under the d-PKE assumption:
521/// any prover producing a valid proof must "know" a valid witness.
522pub fn groth16_soundness_ty() -> Expr {
523    arrow(groth16_proof_ty(), prop())
524}
525/// `PlonkProof : Type`
526///
527/// PLONK universal zk-SNARK: supports a universal trusted setup.
528/// Uses permutation arguments and custom gates; proof size O(log n).
529pub fn plonk_proof_ty() -> Expr {
530    type0()
531}
532/// `PlonkUniversalSetup : PlonkProof โ†’ Prop`
533///
534/// Universality of PLONK: a single structured reference string suffices
535/// for all circuits of size โ‰ค N (updateable, no per-circuit setup).
536pub fn plonk_universal_setup_ty() -> Expr {
537    arrow(plonk_proof_ty(), prop())
538}
539/// `FRIProtocol : Type`
540///
541/// FRI (Fast Reed-Solomon Interactive Oracle Proof of Proximity):
542/// the polynomial commitment underlying STARKs.
543/// Achieves transparent setup (no trusted CRS).
544pub fn fri_protocol_ty() -> Expr {
545    type0()
546}
547/// `FRISoundness : FRIProtocol โ†’ Prop`
548///
549/// FRI soundness: if the committed function is not close to a low-degree
550/// polynomial, the verifier rejects with high probability.
551pub fn fri_soundness_ty() -> Expr {
552    arrow(fri_protocol_ty(), prop())
553}
554/// `StarkProof : Type`
555///
556/// STARK (Scalable Transparent ARgument of Knowledge):
557/// - Transparent setup (no trusted ceremony)
558/// - Post-quantum secure (hash-based)
559/// - Proof size O(log^2 n), verification O(log^2 n)
560pub fn stark_proof_ty() -> Expr {
561    type0()
562}
563/// `StarkTransparency : StarkProof โ†’ Prop`
564///
565/// STARKs are transparent: all randomness comes from a public hash function
566/// (simulated via Fiat-Shamir), no trusted setup required.
567pub fn stark_transparency_ty() -> Expr {
568    arrow(stark_proof_ty(), prop())
569}
570/// `ThresholdSignature : Nat โ†’ Nat โ†’ Type`
571///
572/// A (t, n)-threshold signature scheme:
573/// - n parties hold shares of a secret key
574/// - Any t parties can jointly sign a message
575/// - Any t-1 parties learn nothing about the key or can forge signatures
576pub fn threshold_signature_ty() -> Expr {
577    arrow(nat_ty(), arrow(nat_ty(), type0()))
578}
579/// `ThresholdSignatureUnforgeability : ThresholdSignature t n โ†’ Prop`
580///
581/// Unforgeability: fewer than t parties cannot produce a valid signature.
582pub fn threshold_sig_unforgeability_ty() -> Expr {
583    arrow(nat_ty(), arrow(nat_ty(), prop()))
584}
585/// `DistributedKeyGeneration : Nat โ†’ Type`
586///
587/// DKG (Distributed Key Generation): n parties jointly generate a shared
588/// public key and distribute secret key shares, without any trusted dealer.
589pub fn distributed_key_gen_ty() -> Expr {
590    arrow(nat_ty(), type0())
591}
592/// `DKGSecrecy : DistributedKeyGeneration n โ†’ Prop`
593///
594/// Secrecy of DKG: no threshold-minus-one coalition learns the secret key.
595pub fn dkg_secrecy_ty() -> Expr {
596    arrow(nat_ty(), prop())
597}
598/// `BlindSignature : Type`
599///
600/// A blind signature scheme: signer signs a message without seeing it.
601/// The resulting signature is valid under the signer's key for the
602/// original (unblinded) message.
603pub fn blind_signature_ty() -> Expr {
604    type0()
605}
606/// `BlindnessProperty : BlindSignature โ†’ Prop`
607///
608/// Blindness: the signer's view during the signing protocol is
609/// computationally independent of the message being signed.
610pub fn blindness_property_ty() -> Expr {
611    arrow(blind_signature_ty(), prop())
612}
613/// `BlindSignatureUnforgeability : BlindSignature โ†’ Prop`
614///
615/// One-more unforgeability: a user who interacts with the signer โ„“ times
616/// cannot produce โ„“+1 valid message-signature pairs.
617pub fn blind_sig_unforgeability_ty() -> Expr {
618    arrow(blind_signature_ty(), prop())
619}
620/// `RingSignature : Type`
621///
622/// A ring signature allows any member of a group (ring) to sign on behalf
623/// of the group without revealing which member signed.
624pub fn ring_signature_ty() -> Expr {
625    type0()
626}
627/// `RingSignatureAnonymity : RingSignature โ†’ Prop`
628///
629/// Anonymity: the signer's identity is computationally hidden among all
630/// ring members (even against the other ring members).
631pub fn ring_sig_anonymity_ty() -> Expr {
632    arrow(ring_signature_ty(), prop())
633}
634/// `LinkabilityProperty : RingSignature โ†’ Prop`
635///
636/// LSAG (Linkable SAG) linkability: two signatures by the same key
637/// on different messages can be detected as linked (via a "key image").
638pub fn linkability_property_ty() -> Expr {
639    arrow(ring_signature_ty(), prop())
640}
641/// `GroupSignature : Type`
642///
643/// A group signature scheme: group members sign anonymously; a designated
644/// opener can reveal the signer's identity when needed.
645pub fn group_signature_ty() -> Expr {
646    type0()
647}
648/// `GroupSigAnonymity : GroupSignature โ†’ Prop`
649///
650/// Full anonymity: no adversary can identify the signer among group members.
651pub fn group_sig_anonymity_ty() -> Expr {
652    arrow(group_signature_ty(), prop())
653}
654/// `GroupSigUnlinkability : GroupSignature โ†’ Prop`
655///
656/// Unlinkability: two signatures by the same member cannot be linked
657/// without the opener's key.
658pub fn group_sig_unlinkability_ty() -> Expr {
659    arrow(group_signature_ty(), prop())
660}
661/// `GroupSigOpenability : GroupSignature โ†’ Prop`
662///
663/// Openability: the designated opener can always identify the signer
664/// from any valid signature.
665pub fn group_sig_openability_ty() -> Expr {
666    arrow(group_signature_ty(), prop())
667}
668/// `AnonymousCredential : Type`
669///
670/// An anonymous credential (e.g., CL credentials, BBS+):
671/// - Issuer certifies attributes (a_1, ..., a_k) to a user
672/// - User proves possession of a valid credential for attributes
673///   satisfying a predicate, without revealing the credential or linkage
674pub fn anonymous_credential_ty() -> Expr {
675    type0()
676}
677/// `CredentialUnlinkability : AnonymousCredential โ†’ Prop`
678///
679/// Unlinkability across showings: two presentations of the same credential
680/// are computationally unlinkable.
681pub fn credential_unlinkability_ty() -> Expr {
682    arrow(anonymous_credential_ty(), prop())
683}
684/// `SelectiveDisclosure : AnonymousCredential โ†’ Prop`
685///
686/// Selective disclosure: the user can prove knowledge of specific attributes
687/// without revealing the remaining attributes or the credential itself.
688pub fn selective_disclosure_ty() -> Expr {
689    arrow(anonymous_credential_ty(), prop())
690}
691/// `PrivateSetIntersection : Type`
692///
693/// PSI protocol: two parties each hold a set; at the end, one (or both)
694/// learns the intersection without revealing elements not in the intersection.
695pub fn private_set_intersection_ty() -> Expr {
696    type0()
697}
698/// `PSICorrectness : PrivateSetIntersection โ†’ Prop`
699///
700/// Correctness: the output equals the true set intersection.
701pub fn psi_correctness_ty() -> Expr {
702    arrow(private_set_intersection_ty(), prop())
703}
704/// `PSIPrivacy : PrivateSetIntersection โ†’ Prop`
705///
706/// Privacy: neither party learns elements of the other's set beyond
707/// those in the intersection.
708pub fn psi_privacy_ty() -> Expr {
709    arrow(private_set_intersection_ty(), prop())
710}
711/// `EVotingScheme : Type`
712///
713/// An electronic voting scheme with:
714/// - Ballot casting: voter encrypts and submits a ballot
715/// - Tallying: homomorphic decryption or mix-net reveals the tally
716/// - Verification: anyone can verify correctness
717pub fn e_voting_scheme_ty() -> Expr {
718    type0()
719}
720/// `VotingVerifiability : EVotingScheme โ†’ Prop`
721///
722/// End-to-end verifiability: voters can verify their ballot was counted;
723/// anyone can verify the tally is correctly computed from all ballots.
724pub fn voting_verifiability_ty() -> Expr {
725    arrow(e_voting_scheme_ty(), prop())
726}
727/// `VotingBallotPrivacy : EVotingScheme โ†’ Prop`
728///
729/// Ballot privacy: an adversary controlling the tallier learns nothing
730/// about individual votes beyond the election result.
731pub fn voting_ballot_privacy_ty() -> Expr {
732    arrow(e_voting_scheme_ty(), prop())
733}
734/// `MixNetSecurity : Type โ†’ Prop`
735///
736/// Mix-net security: a sequence of re-encryption shuffles is correct
737/// and the permutation applied is computationally hidden.
738pub fn mix_net_security_ty() -> Expr {
739    arrow(type0(), prop())
740}
741/// `AKEProtocol : Type`
742///
743/// An authenticated key exchange protocol (AKE):
744/// two parties establish a shared session key with mutual authentication.
745pub fn ake_protocol_ty() -> Expr {
746    type0()
747}
748/// `AKEForwardSecrecy : AKEProtocol โ†’ Prop`
749///
750/// Forward secrecy (perfect forward secrecy): compromise of long-term keys
751/// does not compromise past session keys.
752pub fn ake_forward_secrecy_ty() -> Expr {
753    arrow(ake_protocol_ty(), prop())
754}
755/// `AKEMutualAuthentication : AKEProtocol โ†’ Prop`
756///
757/// Mutual authentication: both parties are assured of each other's identity.
758pub fn ake_mutual_auth_ty() -> Expr {
759    arrow(ake_protocol_ty(), prop())
760}
761/// `SignalProtocolSecurity : AKEProtocol โ†’ Prop`
762///
763/// Signal protocol security: combines X3DH key agreement with the Double
764/// Ratchet algorithm for forward secrecy and break-in recovery.
765pub fn signal_protocol_security_ty() -> Expr {
766    arrow(ake_protocol_ty(), prop())
767}
768/// `MPCWithAbort : MPCProtocol โ†’ Prop`
769///
770/// Security with abort: even if corrupted parties abort after seeing output,
771/// honest parties' inputs remain hidden.
772pub fn mpc_with_abort_ty() -> Expr {
773    arrow(mpc_protocol_ty(), prop())
774}
775/// `FairMPC : MPCProtocol โ†’ Prop`
776///
777/// Fairness: either all parties receive the output or none do;
778/// a corrupted party cannot abort after seeing the result while
779/// preventing honest parties from learning it.
780pub fn fair_mpc_ty() -> Expr {
781    arrow(mpc_protocol_ty(), prop())
782}
783/// `GuaranteedOutput : MPCProtocol โ†’ Prop`
784///
785/// Guaranteed output delivery: honest parties always receive the output,
786/// regardless of adversarial behavior (stronger than fairness).
787pub fn guaranteed_output_ty() -> Expr {
788    arrow(mpc_protocol_ty(), prop())
789}
790/// `ConsensusProtocol : Type`
791///
792/// A distributed consensus protocol (e.g., Nakamoto, BFT, Tendermint):
793/// parties agree on a common value despite failures or adversarial behavior.
794pub fn consensus_protocol_ty() -> Expr {
795    type0()
796}
797/// `ConsensusConsistency : ConsensusProtocol โ†’ Prop`
798///
799/// Consistency (safety): all honest parties agree on the same value.
800pub fn consensus_consistency_ty() -> Expr {
801    arrow(consensus_protocol_ty(), prop())
802}
803/// `ConsensuLiveness : ConsensusProtocol โ†’ Prop`
804///
805/// Liveness (progress): honest parties eventually reach agreement.
806pub fn consensus_liveness_ty() -> Expr {
807    arrow(consensus_protocol_ty(), prop())
808}
809/// `NakamotoConsensus : ConsensusProtocol`
810///
811/// Nakamoto's longest-chain consensus: honest miners follow the chain
812/// with most proof-of-work; security holds when >50% hash rate is honest.
813pub fn nakamoto_consensus_ty() -> Expr {
814    consensus_protocol_ty()
815}
816/// `MLKEMScheme : Type`
817///
818/// ML-KEM (formerly Kyber): NIST-standardized lattice-based KEM.
819/// Security based on Module-LWE hardness assumption.
820pub fn ml_kem_scheme_ty() -> Expr {
821    type0()
822}
823/// `MLKEMInd_CCA2 : MLKEMScheme โ†’ Prop`
824///
825/// IND-CCA2 security of ML-KEM: ciphertext indistinguishability under
826/// adaptive chosen-ciphertext attacks, assuming Module-LWE is hard.
827pub fn ml_kem_ind_cca2_ty() -> Expr {
828    arrow(ml_kem_scheme_ty(), prop())
829}
830/// `MLDSAScheme : Type`
831///
832/// ML-DSA (formerly Dilithium): NIST-standardized lattice-based signature.
833/// Security based on Module-LWE and Module-SIS hardness.
834pub fn ml_dsa_scheme_ty() -> Expr {
835    type0()
836}
837/// `MLDSAEUFCMA : MLDSAScheme โ†’ Prop`
838///
839/// EUF-CMA security of ML-DSA: existential unforgeability under
840/// adaptive chosen-message attacks.
841pub fn ml_dsa_euf_cma_ty() -> Expr {
842    arrow(ml_dsa_scheme_ty(), prop())
843}
844/// `SPHINCSPlusScheme : Type`
845///
846/// SPHINCS+: NIST-standardized hash-based signature scheme.
847/// Stateless, based on XMSS and FORS; security reduces to hash function security.
848pub fn sphincs_plus_scheme_ty() -> Expr {
849    type0()
850}
851/// `SPHINCSPlusMinimalAssumptions : SPHINCSPlusScheme โ†’ Prop`
852///
853/// SPHINCS+ achieves EUF-CMA under minimal assumptions (collision-resistance
854/// of the underlying hash function), making it the most conservative PQ option.
855pub fn sphincs_plus_minimal_assumptions_ty() -> Expr {
856    arrow(sphincs_plus_scheme_ty(), prop())
857}
858/// `HomomorphicEncryption : Type`
859///
860/// A homomorphic encryption scheme supporting operations on ciphertexts
861/// that correspond to operations on plaintexts.
862pub fn homomorphic_encryption_ty() -> Expr {
863    type0()
864}
865/// `PHESecurity : HomomorphicEncryption โ†’ Prop`
866///
867/// Semantic security (IND-CPA) of partially homomorphic encryption.
868pub fn phe_security_ty() -> Expr {
869    arrow(homomorphic_encryption_ty(), prop())
870}
871/// `FHEBootstrapping : HomomorphicEncryption โ†’ Prop`
872///
873/// FHE bootstrapping: refreshing a ciphertext to reduce noise, enabling
874/// arbitrarily deep circuit evaluation (Gentry's blueprint).
875pub fn fhe_bootstrapping_ty() -> Expr {
876    arrow(homomorphic_encryption_ty(), prop())
877}
878/// Register all cryptographic protocol axioms into the kernel environment.
879pub fn build_cryptographic_protocols_env(env: &mut Environment) -> Result<(), String> {
880    let axioms: &[(&str, Expr)] = &[
881        ("Proto.DYMessage", dy_message_ty()),
882        ("Proto.DYPrincipal", dy_principal_ty()),
883        ("Proto.DYKnowledge", dy_knowledge_ty()),
884        ("Proto.DYDerivable", dy_derivable_ty()),
885        ("Proto.DYAttack", dy_attack_ty()),
886        ("Proto.DYIntruder", dy_intruder_ty()),
887        ("Proto.Protocol", type0()),
888        ("Proto.Confidentiality", confidentiality_ty()),
889        ("Proto.Integrity", integrity_ty()),
890        ("Proto.Authentication", authentication_ty()),
891        ("Proto.NonRepudiation", non_repudiation_ty()),
892        ("Proto.FreshNonce", fresh_nonce_ty()),
893        ("Proto.ProtocolCompose", protocol_compose_ty()),
894        ("Proto.ProtocolParallel", protocol_parallel_ty()),
895        (
896            "Proto.SecurityPreservedUnderComposition",
897            security_preserved_composition_ty(),
898        ),
899        ("Proto.SigmaProtocol", sigma_protocol_ty()),
900        ("Proto.SigmaCommitment", sigma_commitment_ty()),
901        ("Proto.SigmaChallenge", sigma_challenge_ty()),
902        ("Proto.SigmaResponse", sigma_response_ty()),
903        ("Proto.SigmaCompleteness", sigma_completeness_ty()),
904        ("Proto.SigmaSpecialSoundness", sigma_special_soundness_ty()),
905        ("Proto.SigmaHVZK", sigma_hvzk_ty()),
906        ("Proto.ZKProof", zk_proof_ty()),
907        ("Proto.ZKCompleteness", zk_completeness_ty()),
908        ("Proto.ZKSoundness", zk_soundness_ty()),
909        ("Proto.ZKZeroKnowledge", zk_zero_knowledge_ty()),
910        ("Proto.NIZK", nizk_ty()),
911        ("Proto.FiatShamirTransform", fiat_shamir_transform_ty()),
912        ("Proto.ZKSnark", zk_snark_ty()),
913        ("Proto.SnarkSuccinctness", snark_succinctness_ty()),
914        ("Proto.CommitmentScheme", commitment_scheme_ty()),
915        ("Proto.CommitHiding", commit_hiding_ty()),
916        ("Proto.CommitBinding", commit_binding_ty()),
917        ("Proto.ObliviousTransfer", oblivious_transfer_ty()),
918        ("Proto.OTReceiverPrivacy", ot_receiver_privacy_ty()),
919        ("Proto.OTSenderPrivacy", ot_sender_privacy_ty()),
920        ("Proto.OTExtension", ot_extension_ty()),
921        ("Proto.ShamirSecretSharing", shamir_secret_sharing_ty()),
922        (
923            "Proto.SecretSharingThreshold",
924            secret_sharing_threshold_ty(),
925        ),
926        (
927            "Proto.SecretSharingPerfectPrivacy",
928            secret_sharing_privacy_ty(),
929        ),
930        ("Proto.MPCProtocol", mpc_protocol_ty()),
931        ("Proto.MPCSemiHonestSecurity", mpc_semi_honest_security_ty()),
932        ("Proto.MPCMaliciousSecurity", mpc_malicious_security_ty()),
933        ("Proto.GarbledCircuit", garbled_circuit_ty()),
934        (
935            "Proto.GarbledCircuitCorrectness",
936            garbled_circuit_correctness_ty(),
937        ),
938        (
939            "Proto.GarbledCircuitSecurity",
940            garbled_circuit_security_ty(),
941        ),
942        ("Proto.IdealFunctionality", ideal_functionality_ty()),
943        ("Proto.UCSecure", uc_secure_ty()),
944        ("Proto.UCCompositionTheorem", uc_composition_theorem_ty()),
945        ("Proto.HybridModel", hybrid_model_ty()),
946        ("Proto.UCSimulator", uc_simulator_ty()),
947        ("Proto.UCEnvironment", uc_environment_ty()),
948        ("Proto.UCIndistinguishable", uc_indistinguishable_ty()),
949        ("Proto.GMWProtocol", gmw_protocol_ty()),
950        ("Proto.GMWMaliciousSecure", gmw_malicious_secure_ty()),
951        (
952            "Proto.OTExtensionCorrectness",
953            ot_extension_correctness_ty(),
954        ),
955        ("Proto.YaoGarbledCircuitPrivacy", yao_garbled_privacy_ty()),
956        ("Proto.KZGCommitment", kzg_commitment_ty()),
957        ("Proto.KZGBinding", kzg_binding_ty()),
958        ("Proto.VectorCommitment", vector_commitment_ty()),
959        (
960            "Proto.VectorCommitmentPositionBinding",
961            vector_commitment_position_binding_ty(),
962        ),
963        ("Proto.Groth16Proof", groth16_proof_ty()),
964        ("Proto.Groth16Soundness", groth16_soundness_ty()),
965        ("Proto.PlonkProof", plonk_proof_ty()),
966        ("Proto.PlonkUniversalSetup", plonk_universal_setup_ty()),
967        ("Proto.FRIProtocol", fri_protocol_ty()),
968        ("Proto.FRISoundness", fri_soundness_ty()),
969        ("Proto.StarkProof", stark_proof_ty()),
970        ("Proto.StarkTransparency", stark_transparency_ty()),
971        ("Proto.ThresholdSignature", threshold_signature_ty()),
972        (
973            "Proto.ThresholdSignatureUnforgeability",
974            threshold_sig_unforgeability_ty(),
975        ),
976        ("Proto.DistributedKeyGeneration", distributed_key_gen_ty()),
977        ("Proto.DKGSecrecy", dkg_secrecy_ty()),
978        ("Proto.BlindSignature", blind_signature_ty()),
979        ("Proto.BlindnessProperty", blindness_property_ty()),
980        (
981            "Proto.BlindSignatureUnforgeability",
982            blind_sig_unforgeability_ty(),
983        ),
984        ("Proto.RingSignature", ring_signature_ty()),
985        ("Proto.RingSignatureAnonymity", ring_sig_anonymity_ty()),
986        ("Proto.LinkabilityProperty", linkability_property_ty()),
987        ("Proto.GroupSignature", group_signature_ty()),
988        ("Proto.GroupSigAnonymity", group_sig_anonymity_ty()),
989        ("Proto.GroupSigUnlinkability", group_sig_unlinkability_ty()),
990        ("Proto.GroupSigOpenability", group_sig_openability_ty()),
991        ("Proto.AnonymousCredential", anonymous_credential_ty()),
992        (
993            "Proto.CredentialUnlinkability",
994            credential_unlinkability_ty(),
995        ),
996        ("Proto.SelectiveDisclosure", selective_disclosure_ty()),
997        (
998            "Proto.PrivateSetIntersection",
999            private_set_intersection_ty(),
1000        ),
1001        ("Proto.PSICorrectness", psi_correctness_ty()),
1002        ("Proto.PSIPrivacy", psi_privacy_ty()),
1003        ("Proto.EVotingScheme", e_voting_scheme_ty()),
1004        ("Proto.VotingVerifiability", voting_verifiability_ty()),
1005        ("Proto.VotingBallotPrivacy", voting_ballot_privacy_ty()),
1006        ("Proto.MixNetSecurity", mix_net_security_ty()),
1007        ("Proto.AKEProtocol", ake_protocol_ty()),
1008        ("Proto.AKEForwardSecrecy", ake_forward_secrecy_ty()),
1009        ("Proto.AKEMutualAuthentication", ake_mutual_auth_ty()),
1010        (
1011            "Proto.SignalProtocolSecurity",
1012            signal_protocol_security_ty(),
1013        ),
1014        ("Proto.MPCWithAbort", mpc_with_abort_ty()),
1015        ("Proto.FairMPC", fair_mpc_ty()),
1016        ("Proto.GuaranteedOutput", guaranteed_output_ty()),
1017        ("Proto.ConsensusProtocol", consensus_protocol_ty()),
1018        ("Proto.ConsensusConsistency", consensus_consistency_ty()),
1019        ("Proto.ConsensusLiveness", consensus_liveness_ty()),
1020        ("Proto.MLKEMScheme", ml_kem_scheme_ty()),
1021        ("Proto.MLKEMInd_CCA2", ml_kem_ind_cca2_ty()),
1022        ("Proto.MLDSAScheme", ml_dsa_scheme_ty()),
1023        ("Proto.MLDSAEUFCMA", ml_dsa_euf_cma_ty()),
1024        ("Proto.SPHINCSPlusScheme", sphincs_plus_scheme_ty()),
1025        (
1026            "Proto.SPHINCSPlusMinimalAssumptions",
1027            sphincs_plus_minimal_assumptions_ty(),
1028        ),
1029        ("Proto.HomomorphicEncryption", homomorphic_encryption_ty()),
1030        ("Proto.PHESecurity", phe_security_ty()),
1031        ("Proto.FHEBootstrapping", fhe_bootstrapping_ty()),
1032    ];
1033    for (name, ty) in axioms {
1034        env.add(Declaration::Axiom {
1035            name: Name::str(*name),
1036            univ_params: vec![],
1037            ty: ty.clone(),
1038        })
1039        .ok();
1040    }
1041    Ok(())
1042}
1043/// Fast modular exponentiation: `base^exp mod m`.
1044pub fn mod_exp(mut base: u64, mut exp: u64, m: u64) -> u64 {
1045    if m == 1 {
1046        return 0;
1047    }
1048    let mut result: u128 = 1;
1049    let mut b = base as u128 % m as u128;
1050    while exp > 0 {
1051        if exp & 1 == 1 {
1052            result = result * b % m as u128;
1053        }
1054        exp >>= 1;
1055        b = b * b % m as u128;
1056    }
1057    base = result as u64;
1058    base
1059}
1060/// Extended GCD: returns (gcd, x, y) with a*x + b*y = gcd.
1061pub fn ext_gcd(a: i64, b: i64) -> (i64, i64, i64) {
1062    if b == 0 {
1063        return (a, 1, 0);
1064    }
1065    let (g, x1, y1) = ext_gcd(b, a % b);
1066    (g, y1, x1 - (a / b) * y1)
1067}
1068/// Modular inverse of a mod m (if gcd(a,m)=1).
1069pub fn mod_inv(a: u64, m: u64) -> Option<u64> {
1070    let (g, x, _) = ext_gcd(a as i64, m as i64);
1071    if g != 1 {
1072        return None;
1073    }
1074    Some(((x % m as i64 + m as i64) % m as i64) as u64)
1075}
1076/// Toy "encryption": H(key_a XOR key_b) XOR plaintext (using identity hash).
1077pub fn toy_encrypt(key_a: u64, key_b: u64, plaintext: u64) -> u64 {
1078    let key = key_a
1079        .wrapping_mul(0x9e3779b97f4a7c15)
1080        .wrapping_add(key_b.wrapping_mul(0x6c62272e07bb0142));
1081    plaintext ^ key
1082}
1083/// Create a tiny Paillier instance with p=7, q=13 (n=91).
1084///
1085/// Parameters: ฮป = lcm(6, 12) = 12; g = 92; ฮผ = 38.
1086/// These satisfy gcd(ฮป, n) = 1, which is required for correct decryption.
1087///
1088/// Pre-computed: L(g^ฮป mod n^2) = 12, ฮผ = 12^{-1} mod 91 = 38.
1089pub fn tiny_paillier() -> PaillierHomomorphic {
1090    let p: u64 = 7;
1091    let q: u64 = 13;
1092    let n = p * q;
1093    let n_sq = (n as u128) * (n as u128);
1094    let g = n + 1;
1095    let lambda = 12u64;
1096    let mu = 38u64;
1097    PaillierHomomorphic {
1098        n,
1099        n_sq,
1100        g,
1101        lambda,
1102        mu,
1103    }
1104}
1105#[cfg(test)]
1106mod tests {
1107    use super::*;
1108    use oxilean_kernel::Environment;
1109    #[test]
1110    fn test_build_env() {
1111        let mut env = Environment::new();
1112        let result = build_cryptographic_protocols_env(&mut env);
1113        assert!(
1114            result.is_ok(),
1115            "build_cryptographic_protocols_env failed: {:?}",
1116            result
1117        );
1118    }
1119    #[test]
1120    fn test_schnorr_proof() {
1121        let params = SchnorrParams { p: 23, q: 11, g: 2 };
1122        let secret_x = 5u64;
1123        let y = mod_exp(params.g, secret_x, params.p);
1124        assert_eq!(y, 9);
1125        let r = 7u64;
1126        let challenge = 3u64;
1127        let transcript = params.prove(secret_x, r, challenge);
1128        assert!(
1129            params.verify(&transcript, y),
1130            "Schnorr verification failed for valid proof"
1131        );
1132    }
1133    #[test]
1134    fn test_schnorr_invalid_witness() {
1135        let params = SchnorrParams { p: 23, q: 11, g: 2 };
1136        let secret_x = 5u64;
1137        let wrong_x = 6u64;
1138        let y = mod_exp(params.g, secret_x, params.p);
1139        let r = 7u64;
1140        let challenge = 3u64;
1141        let bad_transcript = params.prove(wrong_x, r, challenge);
1142        assert!(
1143            !params.verify(&bad_transcript, y),
1144            "Schnorr should reject proof with wrong witness"
1145        );
1146    }
1147    #[test]
1148    fn test_pedersen_commitment() {
1149        let params = PedersenParams {
1150            p: 23,
1151            q: 11,
1152            g: 2,
1153            h: 3,
1154        };
1155        let m = 4u64;
1156        let r = 6u64;
1157        let c = params.commit(m, r);
1158        assert!(
1159            params.verify(c, m, r),
1160            "Pedersen commitment should verify correctly"
1161        );
1162        assert!(
1163            !params.verify(c, m + 1, r),
1164            "Different message should not verify"
1165        );
1166    }
1167    #[test]
1168    fn test_pedersen_homomorphic() {
1169        let params = PedersenParams {
1170            p: 23,
1171            q: 11,
1172            g: 2,
1173            h: 3,
1174        };
1175        let (m1, r1) = (2u64, 3u64);
1176        let (m2, r2) = (1u64, 4u64);
1177        let c1 = params.commit(m1, r1);
1178        let c2 = params.commit(m2, r2);
1179        let c_sum = params.add_commitments(c1, c2);
1180        let c_direct = params.commit((m1 + m2) % params.q, (r1 + r2) % params.q);
1181        assert_eq!(c_sum, c_direct, "Pedersen commitment should be homomorphic");
1182    }
1183    #[test]
1184    fn test_shamir_secret_sharing() {
1185        let ss = ShamirSS { p: 97, t: 3, n: 5 };
1186        let secret = 42u64;
1187        let coeffs = [7u64, 13u64];
1188        let shares = ss.split(secret, &coeffs);
1189        assert_eq!(shares.len(), 5, "Should produce 5 shares");
1190        let reconstructed = ss.reconstruct(&shares[..3]);
1191        assert_eq!(
1192            reconstructed, secret,
1193            "Reconstructed secret should match original"
1194        );
1195        let reconstructed2 = ss.reconstruct(&shares[2..5]);
1196        assert_eq!(
1197            reconstructed2, secret,
1198            "Any t shares should reconstruct secret"
1199        );
1200    }
1201    #[test]
1202    fn test_mpc_xor_share() {
1203        let s0 = MpcShare {
1204            party: 0,
1205            share: true,
1206        };
1207        let s1 = MpcShare {
1208            party: 1,
1209            share: false,
1210        };
1211        assert!(
1212            MpcShare::reconstruct(&s0, &s1),
1213            "XOR shares should reconstruct to true"
1214        );
1215        let a0 = MpcShare {
1216            party: 0,
1217            share: true,
1218        };
1219        let b0 = MpcShare {
1220            party: 0,
1221            share: false,
1222        };
1223        let result = MpcShare::xor_gate(&a0, &b0);
1224        assert!(
1225            result.share,
1226            "XOR(true, false) share for party 0 should be true"
1227        );
1228    }
1229    #[test]
1230    fn test_dy_derivable_axiom_registered() {
1231        let mut env = Environment::new();
1232        build_cryptographic_protocols_env(&mut env)
1233            .expect("build_cryptographic_protocols_env should succeed");
1234        assert!(
1235            env.get(&Name::str("Proto.DYDerivable")).is_some(),
1236            "Proto.DYDerivable should be registered"
1237        );
1238        assert!(
1239            env.get(&Name::str("Proto.UCCompositionTheorem")).is_some(),
1240            "Proto.UCCompositionTheorem should be registered"
1241        );
1242    }
1243    #[test]
1244    fn test_uc_composition_is_prop() {
1245        let ty = uc_composition_theorem_ty();
1246        assert_eq!(ty, prop(), "UC composition theorem should have type Prop");
1247    }
1248    #[test]
1249    fn test_new_axioms_registered() {
1250        let mut env = Environment::new();
1251        build_cryptographic_protocols_env(&mut env)
1252            .expect("build_cryptographic_protocols_env should succeed");
1253        assert!(env.get(&Name::str("Proto.UCSimulator")).is_some());
1254        assert!(env.get(&Name::str("Proto.UCEnvironment")).is_some());
1255        assert!(env.get(&Name::str("Proto.UCIndistinguishable")).is_some());
1256        assert!(env.get(&Name::str("Proto.Groth16Proof")).is_some());
1257        assert!(env.get(&Name::str("Proto.PlonkProof")).is_some());
1258        assert!(env.get(&Name::str("Proto.FRIProtocol")).is_some());
1259        assert!(env.get(&Name::str("Proto.StarkProof")).is_some());
1260        assert!(env.get(&Name::str("Proto.MLKEMScheme")).is_some());
1261        assert!(env.get(&Name::str("Proto.MLDSAScheme")).is_some());
1262        assert!(env.get(&Name::str("Proto.SPHINCSPlusScheme")).is_some());
1263        assert!(env.get(&Name::str("Proto.RingSignature")).is_some());
1264        assert!(env.get(&Name::str("Proto.GroupSignature")).is_some());
1265        assert!(env.get(&Name::str("Proto.BlindSignature")).is_some());
1266        assert!(env.get(&Name::str("Proto.AnonymousCredential")).is_some());
1267        assert!(env
1268            .get(&Name::str("Proto.PrivateSetIntersection"))
1269            .is_some());
1270        assert!(env.get(&Name::str("Proto.EVotingScheme")).is_some());
1271        assert!(env.get(&Name::str("Proto.ConsensusProtocol")).is_some());
1272        assert!(env.get(&Name::str("Proto.HomomorphicEncryption")).is_some());
1273        assert!(env.get(&Name::str("Proto.FHEBootstrapping")).is_some());
1274    }
1275    #[test]
1276    fn test_pedersen_commitment_struct() {
1277        let pc = PedersenCommitment {
1278            p: 23,
1279            q: 11,
1280            g: 2,
1281            h: 3,
1282        };
1283        let m = 3u64;
1284        let r = 5u64;
1285        let c = pc.commit(m, r);
1286        assert!(
1287            pc.verify(c, m, r),
1288            "PedersenCommitment verify should succeed"
1289        );
1290        assert!(
1291            !pc.verify(c, m + 1, r),
1292            "PedersenCommitment verify should fail for wrong m"
1293        );
1294    }
1295    #[test]
1296    fn test_pedersen_commitment_batch() {
1297        let pc = PedersenCommitment {
1298            p: 23,
1299            q: 11,
1300            g: 2,
1301            h: 3,
1302        };
1303        let pairs = [(1u64, 2u64), (3u64, 4u64), (5u64, 6u64)];
1304        let commitments = pc.batch_commit(&pairs);
1305        assert_eq!(commitments.len(), 3);
1306        for (i, &(m, r)) in pairs.iter().enumerate() {
1307            assert!(pc.verify(commitments[i], m, r));
1308        }
1309    }
1310    #[test]
1311    fn test_pedersen_commitment_homomorphic() {
1312        let pc = PedersenCommitment {
1313            p: 23,
1314            q: 11,
1315            g: 2,
1316            h: 3,
1317        };
1318        let (m1, r1) = (2u64, 3u64);
1319        let (m2, r2) = (1u64, 4u64);
1320        let c1 = pc.commit(m1, r1);
1321        let c2 = pc.commit(m2, r2);
1322        let c_add = pc.add(c1, c2);
1323        let c_direct = pc.commit((m1 + m2) % pc.q, (r1 + r2) % pc.q);
1324        assert_eq!(c_add, c_direct, "Homomorphic add should be correct");
1325    }
1326    #[test]
1327    fn test_shamir_extended_share_reconstruct() {
1328        let ss = ShamirSecretSharingExtended { p: 97, t: 3, n: 5 };
1329        let secret = 42u64;
1330        let coeffs = [7u64, 13u64];
1331        let shares = ss.share(secret, &coeffs);
1332        assert_eq!(shares.len(), 5);
1333        let reconstructed = ss.reconstruct(&shares[..3]);
1334        assert_eq!(
1335            reconstructed, secret,
1336            "Extended Shamir reconstruction should match secret"
1337        );
1338        let reconstructed2 = ss.reconstruct(&shares[2..5]);
1339        assert_eq!(
1340            reconstructed2, secret,
1341            "Any t shares should reconstruct the secret"
1342        );
1343    }
1344    #[test]
1345    fn test_garbled_and_gate() {
1346        let labels_a = [10u64, 20u64];
1347        let labels_b = [30u64, 40u64];
1348        let labels_out = [50u64, 60u64];
1349        let gate = GarbledGate::garble_and(labels_a, labels_b, labels_out);
1350        let out = gate
1351            .evaluate(labels_a[0], labels_b[0])
1352            .expect("evaluate should succeed");
1353        assert!(!gate.is_output_one(out), "AND(0,0) should be 0");
1354        let out = gate
1355            .evaluate(labels_a[1], labels_b[1])
1356            .expect("evaluate should succeed");
1357        assert!(gate.is_output_one(out), "AND(1,1) should be 1");
1358        let out = gate
1359            .evaluate(labels_a[1], labels_b[0])
1360            .expect("evaluate should succeed");
1361        assert!(!gate.is_output_one(out), "AND(1,0) should be 0");
1362    }
1363    #[test]
1364    fn test_garbled_or_gate() {
1365        let labels_a = [100u64, 200u64];
1366        let labels_b = [300u64, 400u64];
1367        let labels_out = [500u64, 600u64];
1368        let gate = GarbledGate::garble_or(labels_a, labels_b, labels_out);
1369        let out = gate
1370            .evaluate(labels_a[0], labels_b[0])
1371            .expect("evaluate should succeed");
1372        assert!(!gate.is_output_one(out), "OR(0,0) should be 0");
1373        let out = gate
1374            .evaluate(labels_a[0], labels_b[1])
1375            .expect("evaluate should succeed");
1376        assert!(gate.is_output_one(out), "OR(0,1) should be 1");
1377        let out = gate
1378            .evaluate(labels_a[1], labels_b[0])
1379            .expect("evaluate should succeed");
1380        assert!(gate.is_output_one(out), "OR(1,0) should be 1");
1381    }
1382    #[test]
1383    fn test_paillier_homomorphic_encrypt_decrypt() {
1384        let ph = tiny_paillier();
1385        let m = 7u64;
1386        let r = 2u64;
1387        let c = ph.encrypt(m, r);
1388        let decrypted = ph.decrypt(c);
1389        assert_eq!(
1390            decrypted,
1391            m % ph.n,
1392            "Paillier decrypt should recover plaintext"
1393        );
1394    }
1395    #[test]
1396    fn test_paillier_homomorphic_add() {
1397        let ph = tiny_paillier();
1398        let m1 = 3u64;
1399        let m2 = 4u64;
1400        let c1 = ph.encrypt(m1, 2);
1401        let c2 = ph.encrypt(m2, 3);
1402        let c_sum = ph.add_ciphertexts(c1, c2);
1403        let decrypted = ph.decrypt(c_sum);
1404        assert_eq!(
1405            decrypted,
1406            (m1 + m2) % ph.n,
1407            "Homomorphic Paillier add should recover sum"
1408        );
1409    }
1410    #[test]
1411    fn test_blind_signature_full_protocol() {
1412        let bs = BlindSignatureScheme { n: 55, e: 3, d: 27 };
1413        let m = 7u64;
1414        let r = 8u64;
1415        let blinded = bs.blind(m, r);
1416        let s_prime = bs.sign_blinded(blinded);
1417        let s = bs.unblind(s_prime, r);
1418        assert!(
1419            bs.verify(m, s),
1420            "Blind signature verification should succeed after unblinding"
1421        );
1422    }
1423    #[test]
1424    fn test_stark_and_groth16_are_type0() {
1425        assert_eq!(stark_proof_ty(), type0(), "StarkProof should be Type");
1426        assert_eq!(groth16_proof_ty(), type0(), "Groth16Proof should be Type");
1427    }
1428    #[test]
1429    fn test_consensus_liveness_is_prop() {
1430        let ty = consensus_liveness_ty();
1431        assert_ne!(ty, type0(), "ConsensusLiveness should not be Type");
1432    }
1433}
1434#[cfg(test)]
1435mod tests_crypto_extra {
1436    use super::*;
1437    #[test]
1438    fn test_zk_proof_systems() {
1439        let groth = ZKProofSystem::groth16();
1440        assert!(groth.is_non_interactive());
1441        assert!(groth.is_succinct());
1442        let plonk = ZKProofSystem::plonk();
1443        assert!(plonk.is_non_interactive());
1444        let schnorr = ZKProofSystem::schnorr();
1445        assert!(!schnorr.is_non_interactive());
1446    }
1447    #[test]
1448    fn test_commitment_scheme() {
1449        let ped = CommitmentScheme::pedersen();
1450        assert!(ped.is_perfectly_hiding);
1451        assert!(ped.is_homomorphic);
1452        let sha = CommitmentScheme::sha256_hash();
1453        assert!(!sha.is_homomorphic);
1454    }
1455    #[test]
1456    fn test_oblivious_transfer() {
1457        let ot = ObliviousTransfer::new(OTVariant::OneOutOfTwo, 128);
1458        assert!(ot.is_fundamental());
1459        assert_eq!(ot.n_messages(), 2);
1460        let ot_n = ObliviousTransfer::new(OTVariant::OneOutOfN(10), 128);
1461        assert_eq!(ot_n.n_messages(), 10);
1462    }
1463    #[test]
1464    fn test_mpc_protocol() {
1465        let bgw = MPCProtocol::bgw(4, 1);
1466        assert!(bgw.is_optimal_corruption_threshold());
1467        assert!(bgw.is_secure_against_majority_corruption());
1468    }
1469    #[test]
1470    fn test_secret_sharing() {
1471        let ss = SecretSharing::shamir_2_of_3();
1472        assert_eq!(ss.threshold, 2);
1473        assert_eq!(ss.n_shares, 3);
1474        assert!(ss.is_perfect());
1475        assert_eq!(ss.min_shares_needed(), 2);
1476    }
1477}