diff --git a/.github/workflows/cryptomania-assumption-audit.yml b/.github/workflows/cryptomania-assumption-audit.yml new file mode 100644 index 00000000..dd3fc65a --- /dev/null +++ b/.github/workflows/cryptomania-assumption-audit.yml @@ -0,0 +1,46 @@ +name: cryptomania-assumption-audit + +on: + push: + paths: + - "configs/cryptomania_assumptions_v1.json" + - "src/spiral_ln/cryptomania_*.py" + - "tests/test_cryptomania_audit.py" + - "scripts/verify_cryptomania_audit.py" + - "paper/cryptomania_assumption_audit.md" + - ".github/workflows/cryptomania-assumption-audit.yml" + pull_request: + paths: + - "configs/cryptomania_assumptions_v1.json" + - "src/spiral_ln/cryptomania_*.py" + - "tests/test_cryptomania_audit.py" + - "scripts/verify_cryptomania_audit.py" + - "paper/cryptomania_assumption_audit.md" + - ".github/workflows/cryptomania-assumption-audit.yml" + workflow_dispatch: + +jobs: + audit: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Install test dependencies + run: python -m pip install -e ".[test]" + - name: Adversarial logic and exact-count regression tests + run: python -m pytest -q tests/test_cryptomania_audit.py + - name: Generate independent scenario reports + run: | + mkdir -p output/cryptomania_audit + python scripts/verify_cryptomania_audit.py --scenario unadjudicated --output output/cryptomania_audit/unadjudicated.json + python scripts/verify_cryptomania_audit.py --scenario eth_only --output output/cryptomania_audit/eth_only.json + python scripts/verify_cryptomania_audit.py --scenario accept_october_2026_reports --output output/cryptomania_audit/accept_october_2026_reports.json + - uses: actions/upload-artifact@v4 + if: always() + with: + name: cryptomania-assumption-audit + path: output/cryptomania_audit/*.json + if-no-files-found: warn diff --git a/.github/workflows/eth-crypto-encoding-bridge.yml b/.github/workflows/eth-crypto-encoding-bridge.yml new file mode 100644 index 00000000..b975de9d --- /dev/null +++ b/.github/workflows/eth-crypto-encoding-bridge.yml @@ -0,0 +1,42 @@ +name: eth-crypto-encoding-bridge + +on: + push: + paths: + - "src/spiral_ln/crypto_encoding_bridge.py" + - "tests/test_crypto_encoding_bridge.py" + - "scripts/verify_crypto_encoding_bridge.py" + - "paper/crypto_encoding_bridge.md" + - ".github/workflows/eth-crypto-encoding-bridge.yml" + pull_request: + paths: + - "src/spiral_ln/crypto_encoding_bridge.py" + - "tests/test_crypto_encoding_bridge.py" + - "scripts/verify_crypto_encoding_bridge.py" + - "paper/crypto_encoding_bridge.md" + - ".github/workflows/eth-crypto-encoding-bridge.yml" + workflow_dispatch: + +jobs: + finite-encoding-audit: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Install test dependencies + run: python -m pip install -e ".[test]" + - name: Reproduce exact toy witnesses + run: python -m pytest -q tests/test_crypto_encoding_bridge.py + - name: Source-hashed crypto encoding receipt + run: | + mkdir -p output/crypto_encoding_bridge + python scripts/verify_crypto_encoding_bridge.py --output output/crypto_encoding_bridge/bridge_v1.json + - uses: actions/upload-artifact@v4 + if: always() + with: + name: eth-crypto-encoding-evidence + path: output/crypto_encoding_bridge/*.json + if-no-files-found: warn diff --git a/README.md b/README.md index f9e52987..80b44d95 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,12 @@ revocation-sufficient: a static world needs one projective likelihood per source, a Markov latent state the subset filters, none of which is redundant for two sources. No Lean theorem, no acquisition-time attestation. +**New (2026-10-27):** [Cryptomania assumption audit](paper/cryptomania_assumption_audit.md) +tracks the five-world implication graph, evidence-gated ETH/3SUM/APSP hardness routes, +exact-rational Bayesian scenarios and an exact toy-#SAT control. +Reproduce with `PYTHONPATH=src python -m pytest -q tests/test_cryptomania_audit.py` +and `PYTHONPATH=src python scripts/verify_cryptomania_audit.py`. + Reviewers: see [`REVIEW.md`](REVIEW.md). ## Layout diff --git a/configs/cryptomania_assumptions_v1.json b/configs/cryptomania_assumptions_v1.json new file mode 100644 index 00000000..4c25b611 --- /dev/null +++ b/configs/cryptomania_assumptions_v1.json @@ -0,0 +1,241 @@ +{ + "schema_version": "1.0", + "as_of": "2026-10-27", + "propositions": { + "P_NE_NP": "P differs from NP (classical, uniform deterministic time).", + "AVG_HARD": "DistNP is not contained in AvgP in the chosen classical distributional-complexity convention.", + "OWF": "Classical one-way functions exist.", + "PKE": "Classically secure public-key encryption exists.", + "ETH": "Exponential Time Hypothesis for bounded-width 3SAT (variable-based subexponential time).", + "SETH": "Strong Exponential Time Hypothesis.", + "GAP_ETH": "Gap-ETH for the corresponding classical SAT promise.", + "HASH_ETH": "Exact-counting #ETH for bounded-width 3CNF.", + "THREE_SUM_HYP": "No truly subquadratic algorithm for polynomially bounded integer 3SUM.", + "APSP_HYP": "No truly subcubic algorithm for polynomially bounded integer-weight directed APSP.", + "ZWK_HYP": "Fine-grained worst-case zero-weight fixed-k clique hardness at exponent k-o(1).", + "ZWK_AVG_HYP": "Stated average-case fine-grained zero-weight fixed-k clique hardness, for distributions in the construction.", + "LWE_HARD": "Classical average-case LWE hardness in the parameter regime of a specified scheme.", + "ECDLP_HARD": "Classical ECDLP hardness for the parameter family under review." + }, + "implications": [ + [ + "PKE", + "OWF" + ], + [ + "OWF", + "AVG_HARD" + ], + [ + "AVG_HARD", + "P_NE_NP" + ], + [ + "ETH", + "P_NE_NP" + ], + [ + "ETH", + "HASH_ETH" + ], + [ + "SETH", + "ETH" + ], + [ + "GAP_ETH", + "ETH" + ] + ], + "worlds": { + "Algorithmica": { + "P_NE_NP": false, + "AVG_HARD": false, + "OWF": false, + "PKE": false + }, + "Heuristica": { + "P_NE_NP": true, + "AVG_HARD": false, + "OWF": false, + "PKE": false + }, + "Pessiland": { + "P_NE_NP": true, + "AVG_HARD": true, + "OWF": false, + "PKE": false + }, + "Minicrypt": { + "P_NE_NP": true, + "AVG_HARD": true, + "OWF": true, + "PKE": false + }, + "Cryptomania": { + "P_NE_NP": true, + "AVG_HARD": true, + "OWF": true, + "PKE": true + } + }, + "scenarios": { + "unadjudicated": {}, + "accept_october_2026_reports": { + "ETH": false, + "HASH_ETH": false, + "THREE_SUM_HYP": false, + "APSP_HYP": false, + "ZWK_HYP": false, + "ZWK_AVG_HYP": false + }, + "eth_only": { + "ETH": false + } + }, + "routes": [ + { + "id": "fine_grained_pke_zero_k_clique", + "summary": "Original fine-grained PKE hardness route through average-case zero-weight k-clique", + "premises": [ + [ + "ZWK_AVG_HYP" + ] + ] + }, + { + "id": "fine_grained_pow_3sum", + "summary": "3SUM-based fine-grained proof-of-work hardness route", + "premises": [ + [ + "THREE_SUM_HYP" + ] + ] + }, + { + "id": "fine_grained_pow_apsp", + "summary": "APSP-based fine-grained proof-of-work hardness route", + "premises": [ + [ + "APSP_HYP" + ] + ] + }, + { + "id": "cvp_lower_bound_from_seth", + "summary": "Specified CVP lower bound conditional on SETH", + "premises": [ + [ + "SETH" + ] + ] + }, + { + "id": "svp_lower_bound_from_gap_eth", + "summary": "Specified SVP lower bound conditional on Gap-ETH", + "premises": [ + [ + "GAP_ETH" + ] + ] + }, + { + "id": "lwe_security_assumption", + "summary": "Classical LWE hardness premise for a proposed PKE parameter family", + "premises": [ + [ + "LWE_HARD" + ] + ] + }, + { + "id": "ecdlp_security_assumption", + "summary": "Classical ECDLP hardness premise for a specified curve family", + "premises": [ + [ + "ECDLP_HARD" + ] + ] + } + ], + "evidence": [ + { + "id": "openai_eth_20261026", + "proposition": "ETH", + "proposed_value": false, + "stage": "announced_formalization_independent_replay_pending", + "source": "https://openai.com/index/building-scientific-understanding-with-academic-communities/", + "scope": "Fixed-width CNF and uniform resource accounting must match the Lean endpoint; EvalMath PRs #10/#11 audit the seam." + }, + { + "id": "openai_counting_20261026", + "proposition": "HASH_ETH", + "proposed_value": false, + "stage": "announced_formalization_independent_replay_pending", + "source": "https://openai.com/index/building-scientific-understanding-with-academic-communities/", + "scope": "Exact #SAT on bounded-width 3CNF; manuscript and implemented bounds must be distinguished." + }, + { + "id": "alman_vw_20261005_3sum", + "proposition": "THREE_SUM_HYP", + "proposed_value": false, + "stage": "research_preprint", + "source": "https://arxiv.org/abs/2610.06783", + "scope": "Integer 3SUM, polynomially bounded integers; O(n^1.9992) in original announcement." + }, + { + "id": "alman_vw_20261005_apsp", + "proposition": "APSP_HYP", + "proposed_value": false, + "stage": "research_preprint", + "source": "https://arxiv.org/abs/2610.06783", + "scope": "Integer-weight directed APSP with polynomially bounded weights; O(n^2.9995)." + }, + { + "id": "alman_vw_20261005_zwk", + "proposition": "ZWK_HYP", + "proposed_value": false, + "stage": "research_preprint", + "source": "https://arxiv.org/abs/2610.06783", + "scope": "Fixed-k zero-weight k-clique with polynomially bounded integer weights; worst-case speedup." + }, + { + "id": "derived_avg_zwk_20261005", + "proposition": "ZWK_AVG_HYP", + "proposed_value": false, + "stage": "conditional_transfer_from_universal_algorithm", + "source": "https://arxiv.org/abs/2610.06783", + "scope": "Universal worst-case speedup also runs on sampled inputs in the same size and weight regime; check a construction's precise distribution and exponents." + }, + { + "id": "majdoddin_20261012_3sum", + "proposition": "THREE_SUM_HYP", + "proposed_value": false, + "stage": "followup_research_preprint", + "source": "https://arxiv.org/abs/2610.17420", + "scope": "Improves deterministic 3SUM bound to n^(1.9945+o(1)) for the specified polynomially bounded integer input setting; follow-up to Alman-VW." + }, + { + "id": "majdoddin_20261012_apsp", + "proposition": "APSP_HYP", + "proposed_value": false, + "stage": "followup_research_preprint", + "source": "https://arxiv.org/abs/2610.17420", + "scope": "Improves deterministic APSP/min-plus exponent to n^(2.9945+o(1)) in the paper's stated integer-weight setting." + }, + { + "id": "karingula_lovett_20261011_3sum", + "proposition": "THREE_SUM_HYP", + "proposed_value": false, + "stage": "independent_simplified_preprint", + "source": "https://arxiv.org/abs/2610.15663", + "scope": "Simplified independent route to truly subquadratic 3SUM and subcubic APSP with weaker exponents; not a proof of cryptographic insecurity." + } + ], + "protocol": { + "evidence_rule": "Evidence entries are inert. Scenario assumptions are explicit and optional, never silently promoted from a publication.", + "implication_rule": "A=>B propagates A=true to B=true and B=false to A=false; the reverse inferences are prohibited.", + "route_rule": "A failed premise invalidates only that listed conditional route; it is not a cryptanalytic break.", + "world_rule": "World projections contain P_NE_NP, AVG_HARD, OWF, PKE only; ETH=false imposes no five-world elimination." + } +} diff --git a/paper/crypto_encoding_bridge.md b/paper/crypto_encoding_bridge.md new file mode 100644 index 00000000..bf8308bf --- /dev/null +++ b/paper/crypto_encoding_bridge.md @@ -0,0 +1,104 @@ +# ETH counting to cipher inversion: representation audit (CA-02) + +**Date:** 2026-10-27. **Evidence levels:** cited pinned theorem statement, cited NIST circuit census, algebraic encoding identities, finite exact toy examples. No actual AES key recovery is attempted. The ETH result remains subject to independent Lean replay and expert review (EvalMath PRs #10–#11). + +## Mathematical transfer + +For any circuit on **b** Boolean input bits with **g** fan-in-two AND, XOR, or XNOR gates, introduce one fresh Boolean variable for each gate, and impose its truth table in CNF. Each AND costs three clauses, each XOR/XNOR four clauses, all of width at most three. Constrain designated output bits by unit clauses. Thus, for a chosen set of output pins, + +\[ +N=b+g,\qquad M=3g_{\wedge}+4g_{\oplus,\leftrightarrow}+h. +\] + +The encoding is *parsimonious* with respect to the b free input bits: for each input, every intermediate gate variable has exactly one consistent value. Hence each satisfying assignment of the output constraint on the original b inputs has exactly one extension to the CNF, preserving the exact preimage count. Inputs fixed as constants can be simplified, although the ledger deliberately charges all published NIST gates without simplification. + +OpenAI's October 2026 pinned Lean scope claims a deterministic exact fixed-width-CNF counter with running time + +\[ +\mathrm{poly}(L)\,2^{O_k(N(\log\log N)^2/\sqrt{\log N})}. +\] + +This implies a generic **asymptotic** subexponential inverter for circuit families with \(g=O(b)\), polynomially bounded output length and a uniformly available circuit description: adding progressively fixed input literals and testing whether the resulting count is positive reconstructs a preimage with at most b decision/counting calls. A bound of \(2^{o(b)}\) is consistent with the *polynomial-time* definition of one-way functions; it excludes a family-level \(2^{\Omega(b)}\) inversion lower bound under the stated assumptions. The fixed-density manuscript claim improves the exponent to \(O(N/\sqrt{\log N})\) for \(M\le D N\), where fixed D and the hidden constants are inherited from the encoding. These statements concern the claim in the manuscript and its pinned formalization scope; they are conditional on verification of that mathematics. + +## Compact local predicates + +For \(f:{0,1}^b\to{0,1}^m\) with each output bit determined by at most a fixed \(d\) input bits, specify each given output bit by blocking all local input tuples that would yield the wrong value. This yields at most \(m2^d\) clauses, each of width at most \(d\), directly over **b** unknown input variables. If \(d\) is fixed and \(m\) is polynomial in b, the *general-density* theorem gives a \(2^{o(b)}\)-time inverter with polynomial factor in \(b+m\). For \(m=O(b)\), the paper's stronger fixed-density theorem may apply. Goldreich's constant-locality one-way function/PRG proposal is a natural asymptotic test case: it is structurally a local CSP with a fixed predicate, and a successful algorithm would be a generic subexponential inverter, **not** a polynomial-time break of the underlying one-wayness assumption. + +## XOR elimination and sparse polynomial systems + +An AND/XOR/XNOR Boolean straight-line program can be represented without retaining any linear gate outputs. Use the original input coordinates and one variable per AND. Track each XOR/XNOR wire as an affine form over these coordinates. For every AND output \(z\) fed by forms \(A,B\), impose the quadratic Boolean equation + +\[ +z+A B=0\quad\text{in }\mathbb F_2[x_1,\ldots,x_N]/(x_i^2-x_i). +\] + +Pins become affine equations, and each complete satisfying assignment extends uniquely to the original gate wires. This reduces the *declared variables* from \(b+g\) to \(b+g_{\wedge}\). It can increase the *number of listed polynomial monomials* because products of dense affine forms expand into many quadratic terms. + +The pinned manuscript's quantitative-reduction.tex, Lemma lem:tensor-sparse-query, explicitly claims exact counting of shared zeros for \(a\le cN\) equations in **N Boolean variables**, each listed with at most \(\lceil\log_2 N\rceil^c\) monomials of degree at most fixed \(k\), in + +\[ +N^{O_{k,c}(1)}\,2^{O_{k,c}(N\log\log N/\sqrt{\log N})} +\] + +bit operations and polynomial space, for fixed positive integer \(k,c\) and \(N\ge20\). This stronger sparse-polynomial *lemma* is part of the **manuscript proof**, and does not appear in the documented Lean endpoint's statement scope. Simply saying that an equation is quadratic, or algebraically sparse in a circuit representation, does not establish its required *listed monomial* bound after elimination. In particular the degree restriction and the monomial-count restriction are separate. + +Our positive control expands a 24-input XOR parity into one 25-term linear equation, at \(N=24\), meeting \(k=c=2\), \(a\le cN\). The negative control forms the product of two disjoint 12-input parities. One fresh AND variable remains, giving \(N=25\), a quadratic equation of **145** monomials (144 cross terms plus the output), above the \(\lceil\log_2 25\rceil^2=25\) limit. Exact evaluation confirms the representation identities on finite witnesses. These are eligibility and encoding checks, not an implementation of OpenAI's counting method. + +## AES-128 census and honest bounds + +[NIST's circuit complexity catalogue](https://csrc.nist.gov/projects/circuit-complexity/list-of-circuits) publishes **AES-128(k,m)** as 6,400 AND, 21,356 XOR and 844 XNOR gates, total **28,600**. Holding one plaintext fixed and pinning 128 ciphertext bits, the unsimplified Tseitin construction above has at most **28,728** variables and **108,128** clauses, all width at most 3. The ratio is **224.4375 CNF variables per 128-bit key bit**. + +With all XOR/XNOR gate outputs *symbolically* eliminated, the 6,400 AND outputs and 128 key variables would give at most **6,528 declared coordinates** before optional linear elimination. That is only a coordinate census; the actual AES quadratic equations have not been generated or measured. The number of expanded monomials and the sparsity-lemma's fixed-c eligibility remain **unverified**. In a unit-coefficient illustration, \(N/\sqrt{\log_2 N}\) at \(N=28,728\) is **7,464.9**, compared with the 128-bit brute-force exponent. For \(N=6,528\), the corresponding sparse-lemma *scale* \(N\log_2\log_2 N/\sqrt{\log_2 N}\) is **6,718.3**. Neither value is a theorem-level finite-size runtime estimate; the big-O constants and initial thresholds are unquantified and potentially enormous. Neither encoding demonstrates any AES attack. + +### Updated NIST AES-128 full-circuit Pareto census + +NIST's current flat Encipher catalogue provides two source-pinned alternatives +to the older 28,600-gate reference. Each has 256 input bits (128 plaintext, +128 key), 128 output bits and a complete unrolled encryption + key expansion. + +| Variant | AND | XOR/XNOR | Total gates | Tseitin variables | Tseitin clauses | XOR-eliminated coordinates | +|---|---:|---:|---:|---:|---:|---:| +| Lower total gate count | 6,400 | 21,456 | 27,856 | 27,984 | 105,152 | 6,528 | +| Lower AND count | 5,800 | 27,856 | 33,656 | 33,784 | 128,952 | 5,928 | + +The full-circuit counts are sourced from these independently retrieved headers, +pinned to NIST Circuits commit 8366158a4324ef902ce740f29ddc9f7ebb1018b2: + +* [27,856-gate AES-128 Encipher](https://github.com/usnistgov/Circuits/blob/8366158a4324ef902ce740f29ddc9f7ebb1018b2/data/slp/aes/aes-encipher/aes128-encipher-a6400-ad50-g27856-gd286-xx21456-616.circ.txt), Git blob SHA-1 6875e0d6f5878f9cbab255d62ebaad6848cb6c53. +* [5,800-AND AES-128 Encipher](https://github.com/usnistgov/Circuits/blob/8366158a4324ef902ce740f29ddc9f7ebb1018b2/data/slp/aes/aes-encipher/aes128-encipher-a5800-ad50-g33656-gd388-xx27856-4016.circ.txt), Git blob SHA-1 a1dbbb143b13f8bb7c9e5f7b3e0f3d5c27785eae. + +The upper bounds charge every gate after the plaintext is substituted and +pin 128 ciphertext output bits. Gate-level simplification could reduce the +formula further. XOR elimination has 6,528 versus 5,928 declared coordinates, +but actual expanded monomial counts remain unknown. With an illustration +coefficient of one, the fixed-density CNF scales are approximately +7,280.9 and 8,710.2, respectively; corresponding sparse-polynomial +scales are approximately 6,718.3 and 6,107.9. These figures rank +representations under assumed cost functions. They provide no AES key-recovery +algorithm, since the manuscript's actual constants, finite-size applicability +and post-elimination sparsity are unverified. + +This is a Pareto comparison within two documented NIST options, not a +claim that either circuit is globally smallest. Both source blob hashes were +confirmed against the pinned NIST commit. A complete SLP execution is future +work. + + +Lightweight ciphers invite a larger version of this audit because gate counts differ greatly by construction. Care is needed with area metrics: gate equivalents (GE) for a time-multiplexed hardware core and the number of gates in a full unrolled encryption circuit measure different objects. PRESENT, for example, has 31 rounds and 16 four-bit S-box invocations per round; a fully unrolled counting formula still represents the entire computation, including its key schedule. Report exact bit-circuit counts before inferring a smaller CNF exponent. + +## Verification and review gates + +The crypto_encoding_bridge.py code provides count-preserving CNF encoding, symbolic XOR elimination over the Boolean quotient ring, direct fixed-locality CNF, bounded sparse-polynomial truth-table CNF, syntactic eligibility inventory, and an explicitly labelled NIST gate-census calculation. Twelve exact tests cover gate and witness bijections, cancellation, local predicates, polynomial multiplication, positive/negative sparsity controls, and the AES arithmetic. Source-hashed receipts are generated by scripts/verify_crypto_encoding_bridge.py. Every claimed shortcut remains conditional on the independent correctness oracle; speedups require wall-clock, memory, operation counts and held-out-scaling evidence in addition to the inequalities above. + +### Sources and reproduction + +* Upstream source pinned to [openai/math@7ef5c0c quantitative-reduction.tex](https://github.com/openai/math/blob/7ef5c0cc5ca4b0e072b7a050fca09ab24bc6fa3a/preprints/The-Exponential-Time-Hypothesis-is-False-October-25-2026/build/quantitative-reduction.tex). +* Upstream [Lean scope 378.md](https://github.com/openai/math/blob/7ef5c0cc5ca4b0e072b7a050fca09ab24bc6fa3a/lean/docs/378.md). +* [NIST published AES gate census](https://csrc.nist.gov/projects/circuit-complexity/list-of-circuits). +* [Goldreich local-function reference, O'Donnell and Witmer](https://www.cs.cmu.edu/~dwitmer/papers/csp-prg.pdf). +* [PRESENT circuit structural overview](https://ietresearch.onlinelibrary.wiley.com/doi/10.1049/iet-cds.2019.0363). + +Reproduce from EvalMath root: + + PYTHONPATH=src python -m pytest -q tests/test_crypto_encoding_bridge.py + PYTHONPATH=src python scripts/verify_crypto_encoding_bridge.py --output /tmp/crypto_bridge.json diff --git a/paper/cryptomania_assumption_audit.md b/paper/cryptomania_assumption_audit.md new file mode 100644 index 00000000..5ccaadb9 --- /dev/null +++ b/paper/cryptomania_assumption_audit.md @@ -0,0 +1,148 @@ +# Cryptomania assumption audit (CA-01, 2026-10-27) + +**Evidence level:** cited propositions, exact logical deductions within a declared +proposition vocabulary, exact rational Bayesian example, and finite toy-#SAT +tests. This note makes no cryptanalytic claim about real-world keys or +independently reproduced Lean-verification claim. + +## Boundary: five worlds versus quantitative hardness + +The canonical classical implication chain (read left to right) is + +\[ +\mathrm{PKE}\Longrightarrow\mathrm{OWF}\Longrightarrow +\mathrm{DistNP}\not\subseteq\mathrm{AvgP}\Longrightarrow\mathrm P\ne\mathrm{NP}. +\] + +The converses remain open under the conventional classical formalizations. +The five projections of these four predicates, with impossible combinations +excluded by the implications, form Algorithmica, Heuristica, Pessiland, +Minicrypt, Cryptomania. This is a logical taxonomy. Showing ETH false removes +none of the five worlds. Showing ETH true would exclude Algorithmica. + +The schema also encodes SETH => ETH and Gap-ETH => ETH. It deliberately +distinguishes decision ETH from exact-counting #ETH: + +\[ +\mathrm{ETH}\Longrightarrow\#\mathrm{ETH}. +\] + +An exact subexponential #3SAT counter refutes #ETH directly, and because +counting decides satisfiability it refutes ETH. An ETH counterexample that +only decides 3SAT says nothing about #ETH. Neither truth direction provides a +bridge to the classical existence of OWFs or PKE. + +The logical engine propagates only the forward truth and backward falsity of +each registered implication. It detects contradictions, does not turn unknown +propositions into false, and validates that every world projection satisfies +the core implications. + +## Provenance and what "reported" means + +The machine-readable ledger at +configs/cryptomania_assumptions_v1.json includes explicit proposition IDs, +assumptions for the counterfactual scenarios, source links, quantified +problem scopes, review-stage labels, and conditional argument routes. + +* unadjudicated trusts no result automatically. +* eth_only asks what follows if ETH is false, without a counting assumption. +* accept_october_2026_reports takes the announced exact #SAT and + 3SUM/APSP/zero-weight-clique algorithms at face value. It is a what-if + analysis, not a certificate that independent reviewers have accepted them. + +OpenAI's October 26 announcement reports a Lean-formalized ETH result and +names Impagliazzo, Paturi and Williams as independent shepherds. EvalMath +[PR #10](https://github.com/MoralityLabAI/EvalMath/pull/10) audits the +manuscript-to-Lean statement and quantitative constants; +[PR #11](https://github.com/MoralityLabAI/EvalMath/pull/11) undertakes an +independent pinned upstream replay. Their review gates are separate from this +assumption graph. The October 2026 3SUM/APSP paper reports polynomial +improvements, and via reductions rules out the established worst-case +zero-weight k-clique hypothesis in its stated parameter regime. + +* ETH source: https://openai.com/index/building-scientific-understanding-with-academic-communities/ +* Alman and Vassilevska Williams: https://arxiv.org/abs/2610.06783 +* Majdoddin's improved bounds (3SUM 1.9945, APSP 2.9945, plus o(1)): https://arxiv.org/abs/2610.17420 +* Karingula and Lovett's independent simplified route: https://arxiv.org/abs/2610.15663 +* Canonical five-world chain: https://researchmap.jp/shuichi.hirahara/published_papers/40816859/attachment_file.pdf +* Fine-grained PKE dependence: https://eprint.iacr.org/2019/625.pdf + +## Conditional argument routes + +The route checker records premises for named fine-grained PKE, PoW, +SETH-CVP and Gap-ETH-SVP claims and independent LWE/ECDLP hardness questions. +An all_listed_routes_invalidated result means that every listed path +has a false premise in this scenario. It has a narrower scope than "security +broken" or "no alternative theorem exists." An open route has one or more +unknown premises. premises_asserted simply describes the assigned premises; +it is never a security certificate. Unmodeled proof routes are outside scope. + +A universal worst-case zero-weight-clique algorithm also runs on instances +sampled from supported average-case distributions. The transfer requires +checking the particular fine-grained PKE construction's distributions, +weight bounds and polynomial exponents. It does not break arbitrary +public-key encryption. Loss of SETH/Gap-ETH lattice lower-bound arguments +likewise does not imply an attack against LWE or a deployed parameter set. + +## Credence is a joint distribution + +For each world \(w\) and event \(E\), a posterior needs \(P(E\mid w)\): + +\[ +P(w\mid E)= +\frac{P(E\mid w)P(w)}{\sum_v P(E\mid v)P(v)}. +\] + +The exact-rational demonstration chooses a toy prior +\(P(\mathrm{Algorithmica})=1/1000\), all other prior mass summing to +\(999/1000\), and \(P(\mathrm{ETH})=9/10\). With +\(P(\neg\mathrm{ETH}\mid\mathrm{Algorithmica})=1\) and +\(P(\neg\mathrm{ETH}\mid w)=11/111\) for every other world, +Algorithmica rises tenfold to \(1/100\). Under this particular joint model, +Cryptomania moves from \(4/5\) to \(88/111\). Alternative world-conditional +likelihoods yield different updates. The five-world marginal alone cannot +determine the direction or magnitude. + +## Tiny exact-count control + +cryptomania_toy_count.py constructs seeded 3CNFs with blocks of three +variables and an otherwise identical control joined by bridging clauses. +Two exact counters independently enumerate assignments: the baseline +enumerates all \(2^n\), while the factorized counter multiplies counts on +connected clause-hypergraph components. Eight cases at 6, 9, 12 and 15 +variables record exact solution counts, component sizes and an assignment +enumeration proxy. The proxy excludes component discovery and overhead; +it is not timing data. Joined controls remove the factorization advantage. +No general subexponential #SAT result follows from this structured family. + +This fixture is useful as a protocol check before using substantially +larger experimental systems: any purported algebraic shortcut must keep +exact count fidelity, define its operation model, survive connected or +adversarial controls, and demonstrate scaling on held-out distributions. + +For LWE, decoding, and isogeny-path experiments, preregister reductions, +bit complexity, instance distributions, memory and success probability. +Keep low-dimensional algebraic identities and solver wall-clock traces in +distinct evidence columns. The Semaev work in +patrickdugan/semaev-index-calculus already maintains a separate +count-preservation and gate-census program. No ECDLP speedup is claimed here. + +## Reproduce + +From the EvalMath root: + +~~~bash +PYTHONPATH=src python -m pytest -q tests/test_cryptomania_audit.py +PYTHONPATH=src python scripts/verify_cryptomania_audit.py +PYTHONPATH=src python scripts/verify_cryptomania_audit.py --scenario eth_only +~~~ + +The verifier emits canonical JSON with source hashes and machine-checkable +Boolean assertions. Every seeded benchmark instance is deterministic; all +arithmetic in the Bayesian example is rational. To add a new assumption, +enter its implication only after checking the exact computational model and +direction of the reduction, then add a counterexample-oriented unit test. + +## Follow-up: cipher encoding transfer + +[CA-02: ETH counting to cipher inversion](crypto_encoding_bridge.md) adds exact Boolean gate-to-CNF witnesses, XOR-eliminated quadratic systems, the manuscript-only sparse-polynomial lemma's precise syntactic gate, and a published NIST AES-128 circuit census. Review it independently of the CA-01 five-world credence ledger. diff --git a/scripts/verify_crypto_encoding_bridge.py b/scripts/verify_crypto_encoding_bridge.py new file mode 100644 index 00000000..42643577 --- /dev/null +++ b/scripts/verify_crypto_encoding_bridge.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +"""Deterministic finite evidence ledger for cipher-to-#SAT encodings.""" +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path + +from spiral_ln.crypto_encoding_bridge import ( + Circuit, count_cnf, eval_poly, local_output_cnf, matches, + nist_aes_cnf_census, nist_aes_pareto_frontier, sparse_lemma_inventory, tseitin, xor_eliminate, + zero_count, +) + +ROOT = Path(__file__).resolve().parents[1] +SOURCES = ( + "src/spiral_ln/crypto_encoding_bridge.py", + "tests/test_crypto_encoding_bridge.py", + "scripts/verify_crypto_encoding_bridge.py", + "paper/crypto_encoding_bridge.md", +) + + +def _parity_block(start: int, length: int, inputs: int, existing_gates: list) -> int: + existing_gates.append(("XOR", start, start + 1)) + for v in range(start + 2, start + length): + existing_gates.append(("XOR", inputs + len(existing_gates) - 1, v)) + return inputs + len(existing_gates) - 1 + + +def make_receipt() -> dict: + circ = Circuit(3, (("XOR", 0, 1), ("AND", 3, 2), ("XNOR", 4, 1)), ((5, 1),)) + n, cnf = tseitin(circ) + n2, polys = xor_eliminate(circ) + count_direct = sum(matches(circ, x) for x in range(1 << circ.inputs)) + count_boolean = count_cnf(n, cnf) + count_algebraic = zero_count(n2, polys) + + n_local = 6 + secret = 0b101101 + locality = (0, 2, 4) + predicate = tuple(x.bit_count() % 2 for x in range(8)) + selected = sum(((secret >> i) & 1) << j for j, i in enumerate(locality)) + target = predicate[selected] + local_cnf = local_output_cnf(n_local, locality, predicate, target) + local_direct = sum(predicate[sum(((x >> i) & 1) << j for j, i in enumerate(locality))] == target + for x in range(1 << n_local)) + + sparse_gates = [] + _parity_block(0, 24, 24, sparse_gates) + linear = Circuit(24, tuple(sparse_gates), ((24 + len(sparse_gates) - 1, 1),)) + lin_n, lin_eq = xor_eliminate(linear) + lin_inventory = sparse_lemma_inventory(lin_n, lin_eq, 2, 2) + + dense_gates = [] + first = _parity_block(0, 12, 24, dense_gates) + second = _parity_block(12, 12, 24, dense_gates) + dense_gates.append(("AND", first, second)) + nonlinear = Circuit(24, tuple(dense_gates), ((24 + len(dense_gates) - 1, 1),)) + dense_n, dense_eq = xor_eliminate(nonlinear) + dense_inventory = sparse_lemma_inventory(dense_n, dense_eq, 2, 2) + + aes = nist_aes_cnf_census() + frontier = nist_aes_pareto_frontier() + checks = { + "tseitin_toy_exact_count": count_boolean == count_direct, + "xor_eliminated_toy_exact_count": count_algebraic == count_direct, + "xor_eliminated_toy_fewer_variables": n2 < n, + "local_map_no_aux_variable": len(locality) == max(map(len, local_cnf)), + "local_map_exact_count": count_cnf(n_local, local_cnf) == local_direct, + "affine_system_meets_manuscript_syntactic_conditions": lin_inventory["eligible_on_stated_syntactic_conditions"], + "affine_system_25_terms": len(lin_eq[0]) == 25, + "quadratic_system_exceeds_fixed_sparsity": not dense_inventory["eligible_on_stated_syntactic_conditions"], + "quadratic_system_145_terms": len(dense_eq[0]) == 145, + "quadratic_system_preserves_low_degree": dense_inventory["maximum_degree"] == 2, + "nist_aes_gate_census": aes["gates"] == 28_600, + "nist_aes_tseitin_census": aes["tseitin_variables"] == 28_728 and aes["tseitin_clauses"] == 108_128, + "nist_aes_subexp_proxy_above_bruteforce": aes["optimistic_fixed_density_exponent_proxy"] > aes["key_bits"], + "nist_frontier_header_count": [(x["gates"], x["tseitin_variables"], x["tseitin_clauses"]) for x in frontier] == [ + (27856, 27984, 105152), (33656, 33784, 128952) + ], + "nist_and_minimum_changes_coordinate_budget": ( + frontier[1]["unverified_xor_elimination_variable_count"] == 5928 + and frontier[1]["gates"] > frontier[0]["gates"] + ), + } + return { + "schema_version": "crypto-encoding-bridge-v1", + "evidence_levels": { + "toy_counts": "finite_verified_example", + "aes_gate_census": "cited_from_nist_not_slp_replayed", + "sparse_poly_lemma": "manuscript_statement_only", + "formal_sat_bound": "pinned_upstream_lean_scope_claim", + }, + "source_sha256": { + path: hashlib.sha256((ROOT / path).read_bytes()).hexdigest() for path in SOURCES + }, + "checks": checks, + "all_passed": all(checks.values()), + "small_circuit_counts": { + "input_bits": circ.inputs, "tseitin_variables": n, + "xor_eliminated_variables": n2, "input_preimages": count_direct, + "tseitin_preimages": count_boolean, "polynomial_preimages": count_algebraic, + }, + "local_function": { + "input_bits": n_local, "locality": len(locality), + "clauses": len(local_cnf), "preimages": local_direct, + }, + "sparse_lemma_positive_control": lin_inventory, + "sparse_lemma_negative_control": dense_inventory, + "nist_aes_128_census": aes, + "nist_pareto_frontier_census": list(frontier), + "warning": "No real cipher cryptanalysis, executable ETH implementation, key search, or practical speedup is claimed.", + } + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path, default=None) + args = parser.parse_args() + receipt = make_receipt() + serialized = json.dumps(receipt, sort_keys=True, indent=2) + "\n" + if args.output: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(serialized, encoding="utf-8") + print(f"wrote {args.output}: {sum(receipt['checks'].values())} checks") + else: + print(serialized, end="") + return 0 if receipt["all_passed"] else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/verify_cryptomania_audit.py b/scripts/verify_cryptomania_audit.py new file mode 100644 index 00000000..5d3ecbae --- /dev/null +++ b/scripts/verify_cryptomania_audit.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +"""Emit deterministic Cryptomania Assumption Audit evidence. + +Usage: + python scripts/verify_cryptomania_audit.py [--scenario unadjudicated] [--output PATH] + +JSON has no clock time. A failed check exits nonzero. Publications are never +automatically promoted to facts; only explicit scenario literals are propagated. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path + +from spiral_ln.cryptomania_audit import ( + WORLD_ORDER, bayes_example, compatible_worlds, propagate, report, +) +from spiral_ln.cryptomania_toy_count import run_toy_suite + +ROOT = Path(__file__).resolve().parents[1] +MANIFEST = ROOT / "configs/cryptomania_assumptions_v1.json" +SOURCES = ( + "configs/cryptomania_assumptions_v1.json", + "src/spiral_ln/cryptomania_audit.py", + "src/spiral_ln/cryptomania_toy_count.py", + "tests/test_cryptomania_audit.py", + "paper/cryptomania_assumption_audit.md", + "scripts/verify_cryptomania_audit.py", +) + + +def make_receipt(scenario: str = "unadjudicated") -> dict: + data = json.loads(MANIFEST.read_text(encoding="utf-8")) + audit = report(data, scenario) + rows = run_toy_suite() + empty, _ = propagate(data, {"ETH": False}) + count, _ = propagate(data, {"HASH_ETH": False}) + reported, _ = propagate(data, data["scenarios"]["accept_october_2026_reports"]) + checks = { + "five_worlds_under_eth_false": compatible_worlds(data, {"ETH": False}) == list(WORLD_ORDER), + "eth_false_does_not_refute_count_eth": empty["HASH_ETH"] is None, + "count_eth_false_implies_eth_false": count["ETH"] is False, + "reported_lwe_remains_unadjudicated": reported["LWE_HARD"] is None, + "reported_pke_remains_unadjudicated": reported["PKE"] is None, + "no_reported_scenario_eliminates_worlds": len( + compatible_worlds(data, data["scenarios"]["accept_october_2026_reports"]) + ) == 5, + "toy_count_equivalence": all(row["exactly_equal"] for row in rows), + "connected_controls_no_assignment_proxy_gain": all( + row["baseline_assignments"] == row["factorized_assignments"] + for row in rows if row["linked_control"] + ), + "disconnected_controls_assignment_proxy_gain": all( + row["factorized_assignments"] < row["baseline_assignments"] + for row in rows if not row["linked_control"] + ), + "exact_bayesian_tenfold": bayes_example()["algorithmica_multiplier"] == "10", + "all_observations_stage_gated": audit["evidence_not_promoted"] == len(data["evidence"]), + } + receipt = { + "schema_version": "cryptomania-audit-v1", + "scenario": scenario, + "source_sha256": { + rel: hashlib.sha256((ROOT / rel).read_bytes()).hexdigest() for rel in SOURCES + }, + "checks": checks, + "all_passed": all(checks.values()), + "audit": audit, + "toy_count": rows, + "metric_caveat": "assignment enumeration proxy; no timing and no general SAT speedup", + } + return receipt + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--scenario", default="unadjudicated") + parser.add_argument("--output", type=Path, default=None) + args = parser.parse_args() + receipt = make_receipt(args.scenario) + serialized = json.dumps(receipt, sort_keys=True, indent=2) + "\n" + if args.output is None: + print(serialized, end="") + else: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(serialized, encoding="utf-8") + print(f"wrote {args.output} ({sum(receipt['checks'].values())} checks)") + return 0 if receipt["all_passed"] else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/spiral_ln/aes_slp_sparse_census.py b/src/spiral_ln/aes_slp_sparse_census.py new file mode 100644 index 00000000..62f7627a --- /dev/null +++ b/src/spiral_ln/aes_slp_sparse_census.py @@ -0,0 +1,184 @@ +"""Exact affine-support monomial census for pinned NIST AES flat circuits. + +For each AND gate z = A*B, A and B are affine Boolean functions of +128 symbolic key bits and earlier AND outputs. XOR/XNOR gate outputs are +eliminated. Quadratic monomial counts are obtained exactly using set +intersections, with no expansion or heuristic sampling. + +Usage: + python scripts/verify_nist_aes_slp.py --input aes.circ.txt --git-blob-sha1 SHA1 +""" +from __future__ import annotations + +import hashlib +import re +from dataclasses import dataclass +from math import ceil, log2 +from typing import Any + + +@dataclass(frozen=True) +class Affine: + support: int + constant: int + + def __post_init__(self) -> None: + if type(self.support) is not int or self.support < 0 or self.constant not in (0, 1): + raise ValueError("invalid affine form") + + +def monomial_counts_for_and(a: Affine, b: Affine) -> dict[str, int]: + """Counts terms in z + A*B over Boolean quotient F2[x]/(x_i^2-x_i). + + U = supp(A)\supp(B), V = supp(B)\supp(A), I = intersection. + Cross terms are U×V and I×(U union V); shared×shared cancels. + """ + common = (a.support & b.support).bit_count() + only_a = (a.support & ~b.support).bit_count() + only_b = (b.support & ~a.support).bit_count() + quadratic = only_a * only_b + common * (only_a + only_b) + linear = only_a * b.constant + only_b * a.constant + common * ( + 1 ^ a.constant ^ b.constant + ) + constant = a.constant & b.constant + return { + "quadratic": quadratic, + "linear": linear, + "constant": constant, + "fresh_nonlinear_coordinate": 1, + "total": quadratic + linear + constant + 1, + } + + +def git_blob_sha1(raw: bytes) -> str: + return hashlib.sha1(b"blob " + str(len(raw)).encode("ascii") + b"\0" + raw).hexdigest() + + +def _quantiles(values: list[int]) -> dict[str, int]: + if not values: + raise ValueError("empty sample") + s = sorted(values) + q = lambda p: s[int((len(s) - 1) * p)] + return { + "count": len(s), "minimum": s[0], "median_lower": q(0.5), + "p90": q(0.9), "p99": q(0.99), "maximum": s[-1], + "sum": sum(s), + "above_169": sum(v > 169 for v in s), + "above_2197": sum(v > 2197 for v in s), + "above_28561": sum(v > 28561 for v in s), + } + + +def slp_census( + raw: bytes, *, + key_bits: int = 128, + plaintext_bits: int = 128, + output_bits: int = 128, + plaintext_value: int = 0, + ciphertext_value: int = 0, + expected_git_blob_sha1: str | None = None, +) -> dict[str, Any]: + """Read one full NIST NCFF-2026 SLP, fail closed on unknown gates. + + ptx[i] is fixed to bit i of plaintext_value; key[i] is symbolic. + A fresh coordinate is introduced at every AND output. The ciphertext + pins only change constant terms of the output equations. + """ + sha = git_blob_sha1(raw) + if expected_git_blob_sha1 is not None and sha != expected_git_blob_sha1: + raise ValueError("NIST source blob SHA-1 mismatch") + for width in (key_bits, plaintext_bits, output_bits): + if type(width) is not int or width < 0: + raise ValueError("invalid source bit width") + if type(plaintext_value) is not int or not 0 <= plaintext_value < (1 << plaintext_bits): + raise ValueError("invalid fixed plaintext") + if type(ciphertext_value) is not int or not 0 <= ciphertext_value < (1 << output_bits): + raise ValueError("invalid pinned ciphertext") + text = raw.decode("utf-8") + lines = text.splitlines() + markers = [i for i, line in enumerate(lines) if line.strip() == "begin SLP"] + endings = [i for i, line in enumerate(lines) if line.strip() == "end SLP"] + if len(markers) != 1 or len(endings) != 1 or markers[0] >= endings[0]: + raise ValueError("expected a unique complete SLP") + header = re.search( + r"Tally of gates \(G\): (\d+) AND; (\d+) XOR; (\d+) XNOR", text + ) + if header is None: + raise ValueError("missing NIST header gate tally") + expected = dict(zip(("AND", "XOR", "XNOR"), map(int, header.groups()))) + wires = { + **{f"ptx{i}": Affine(0, (plaintext_value >> i) & 1) + for i in range(plaintext_bits)}, + **{f"key{i}": Affine(1 << i, 0) for i in range(key_bits)}, + } + counts = {"AND": 0, "XOR": 0, "XNOR": 0} + and_total: list[int] = [] + and_quadratic: list[int] = [] + and_linear: list[int] = [] + for line in lines[markers[0] + 1:endings[0]]: + stripped = line.strip() + if not stripped or stripped.startswith("%"): + continue + parts = stripped.split() + if len(parts) != 4 or parts[0] not in counts: + raise ValueError(f"unknown SLP operation: {stripped[:100]}") + op, out, left, right = parts + if out in wires: + raise ValueError(f"duplicate output wire: {out}") + if left not in wires or right not in wires: + raise ValueError(f"undefined input wire in: {stripped[:100]}") + a, b = wires[left], wires[right] + if op == "AND": + m = monomial_counts_for_and(a, b) + and_total.append(m["total"]) + and_quadratic.append(m["quadratic"]) + and_linear.append(m["linear"]) + wires[out] = Affine(1 << (key_bits + counts["AND"]), 0) + else: + wires[out] = Affine(a.support ^ b.support, + a.constant ^ b.constant ^ int(op == "XNOR")) + counts[op] += 1 + if counts != expected: + raise ValueError(f"gate tally disagrees with source header: {counts} != {expected}") + pins = [] + for j in range(output_bits): + out = wires.get(f"ctx{j}") + if out is None: + raise ValueError(f"missing ciphertext output ctx{j}") + target = (ciphertext_value >> j) & 1 + pins.append(out.support.bit_count() + (out.constant ^ target)) + n = key_bits + counts["AND"] + equations = len(and_total) + len(pins) + maximum = max(and_total + pins) + if n < 2: + raise ValueError("insufficient variables for logarithm") + lam = ceil(log2(n)) + lowest_c = next((c for c in range(1, 16) + if equations <= c * n and maximum <= lam ** c), None) + return { + "source_git_blob_sha1": sha, + "source_bytes": len(raw), + "parameterization": { + "key_bits": key_bits, "plaintext_bits": plaintext_bits, + "output_bits": output_bits, + "plaintext_value_hex": hex(plaintext_value), + "ciphertext_value_hex": hex(ciphertext_value), + }, + "gate_tally": counts, "gates": sum(counts.values()), + "xor_eliminated_coordinates": n, "equations": equations, + "degree_bound": 2, + "and_equation_monomials": _quantiles(and_total), + "and_quadratic_monomials": _quantiles(and_quadratic), + "and_linear_monomials": _quantiles(and_linear), + "ciphertext_pin_monomials": _quantiles(pins), + "max_polynomial_monomials": maximum, + "ceil_log2_coordinates": lam, + "minimum_c_at_this_fixed_size": lowest_c, + "c_bound_checks": [ + {"c": c, "max_monomials_allowed": lam ** c, + "equations_allowed": c * n, + "passes_syntactic_checks": equations <= c * n and maximum <= lam ** c} + for c in range(1, 6) + ], + "scope_note": "fixed-size syntactic census only; not a uniform family or implementation of the ETH counting theorem", + } diff --git a/src/spiral_ln/crypto_encoding_bridge.py b/src/spiral_ln/crypto_encoding_bridge.py new file mode 100644 index 00000000..a3e68f84 --- /dev/null +++ b/src/spiral_ln/crypto_encoding_bridge.py @@ -0,0 +1,296 @@ +"""Exact finite encodings for ETH-to-cryptography applicability audits. + +Counts are toy exhaustions or audited gate census, never runtime estimates. +A multilinear Boolean polynomial over F2 is a set of integer monomial masks. +Symmetric difference adds polynomials; bitwise OR multiplies monomials in +F2[x]/(x_i^2-x_i). Symbolic XOR-elimination preserves the number of solutions +when uniquely-determined gate wires are removed. +""" +from __future__ import annotations + +from dataclasses import dataclass +from math import log2, sqrt +from typing import Iterable + +Gate = tuple[str, int, int] # operation, left wire, right wire (zero-based) +Clause = tuple[int, ...] # signed one-based SAT literals +Poly = frozenset[int] # monomial bitmask; mask zero is constant 1 + + +@dataclass(frozen=True) +class Circuit: + inputs: int + gates: tuple[Gate, ...] + pins: tuple[tuple[int, int], ...] = () + + def validate(self) -> None: + if type(self.inputs) is not int or not 0 <= self.inputs <= 30: + raise ValueError("bad input count") + for i, (op, a, b) in enumerate(self.gates): + if op not in ("AND", "XOR", "XNOR") or not all( + type(t) is int and 0 <= t < self.inputs + i for t in (a, b) + ): + raise ValueError("invalid gate or forward reference") + for wire, bit in self.pins: + if type(wire) is not int or not 0 <= wire < self.inputs + len(self.gates): + raise ValueError("bad output wire") + if type(bit) is not int or bit not in (0, 1): + raise ValueError("bad output bit") + + +def execute(circuit: Circuit, input_bits: int) -> tuple[int, ...]: + circuit.validate() + if type(input_bits) is not int or not 0 <= input_bits < 1 << circuit.inputs: + raise ValueError("input outside domain") + wires = [(input_bits >> i) & 1 for i in range(circuit.inputs)] + for op, a, b in circuit.gates: + x, y = wires[a], wires[b] + wires.append((x & y) if op == "AND" else (x ^ y) if op == "XOR" else (x ^ y ^ 1)) + return tuple(wires) + + +def matches(circuit: Circuit, input_bits: int) -> bool: + wires = execute(circuit, input_bits) + return all(wires[i] == bit for i, bit in circuit.pins) + + +def _reject(a: int, b: int, z: int, first: int, second: int, output: int) -> Clause: + """CNF clause excluding exactly the indicated assignment.""" + return tuple((-v if assigned else v) for v, assigned in + ((first, a), (second, b), (output, z))) + + +def tseitin(circuit: Circuit) -> tuple[int, tuple[Clause, ...]]: + """One uniquely constrained variable per gate; <=4 3-clauses per gate.""" + circuit.validate() + clauses: list[Clause] = [] + for i, (op, a, b) in enumerate(circuit.gates): + first, second, out = a + 1, b + 1, circuit.inputs + i + 1 + if op == "AND": + clauses.extend(((-first, -second, out), (first, -out), (second, -out))) + else: + invert = 1 if op == "XNOR" else 0 + for x in (0, 1): + for y in (0, 1): + wrong = 1 ^ x ^ y ^ invert + clauses.append(_reject(x, y, wrong, first, second, out)) + for wire, bit in circuit.pins: + clauses.append(((wire + 1) if bit else -(wire + 1),)) + return circuit.inputs + len(circuit.gates), tuple(clauses) + + +def eval_cnf(clauses: Iterable[Clause], assignment: int) -> bool: + return all(any(bool(assignment & (1 << (abs(lit) - 1))) == (lit > 0) + for lit in clause) for clause in clauses) + + +def count_cnf(n: int, clauses: Iterable[Clause]) -> int: + if type(n) is not int or not 0 <= n <= 20: + raise ValueError("bounded exact witness allows <=20 Boolean variables") + clauses = tuple(clauses) + return sum(eval_cnf(clauses, assignment) for assignment in range(1 << n)) + + +def poly_add(a: Poly, b: Poly) -> Poly: + return a.symmetric_difference(b) + + +def poly_mul(a: Poly, b: Poly) -> Poly: + acc: set[int] = set() + for left in a: + for right in b: + term = left | right + if term in acc: + acc.remove(term) + else: + acc.add(term) + return frozenset(acc) + + +def eval_poly(poly: Poly, assignment: int) -> int: + return sum((assignment & term) == term for term in poly) & 1 + + +def zero_count(n: int, system: Iterable[Poly]) -> int: + if type(n) is not int or not 0 <= n <= 20: + raise ValueError("bounded exact witness allows <=20 Boolean variables") + eqs = tuple(system) + return sum(all(eval_poly(p, x) == 0 for p in eqs) for x in range(1 << n)) + + +def xor_eliminate(circuit: Circuit) -> tuple[int, tuple[Poly, ...]]: + """Eliminate XOR/XNOR outputs; leave one coordinate per AND. + + For every AND z=a*b, add z + A*B=0 over F2, where A,B are affine + expressions on initial inputs and earlier AND coordinates. Endpoint pins + add affine constraints. All assignments extend uniquely to circuit wires. + """ + circuit.validate() + affine = [frozenset((1 << i,)) for i in range(circuit.inputs)] + equations: list[Poly] = [] + next_variable = circuit.inputs + for op, a, b in circuit.gates: + if op == "AND": + z = frozenset((1 << next_variable,)) + equations.append(poly_add(z, poly_mul(affine[a], affine[b]))) + affine.append(z) + next_variable += 1 + elif op == "XOR": + affine.append(poly_add(affine[a], affine[b])) + else: + affine.append(poly_add(poly_add(affine[a], affine[b]), frozenset((0,)))) + for wire, bit in circuit.pins: + equations.append(poly_add(affine[wire], frozenset((0,)) if bit else frozenset())) + return next_variable, tuple(equations) + + +def poly_to_cnf(n: int, poly: Poly, scope_limit: int = 14) -> tuple[Clause, ...]: + """Truth-table clauses with no auxiliary variables; limited toy scope. + + Each invalid assignment to variables in the polynomial's support yields + one clause. The constant polynomial 1 produces one empty clause. + """ + if type(n) is not int or n < 0: + raise ValueError("bad variable count") + if any(type(mask) is not int or not 0 <= mask < 1 << n for mask in poly): + raise ValueError("bad polynomial monomial") + scope = sorted({i for mask in poly for i in range(n) if mask & (1 << i)}) + if len(scope) > scope_limit: + raise ValueError("truth table would exceed bounded witness scope") + clauses = [] + for bits in range(1 << len(scope)): + x = sum(((bits >> j) & 1) << i for j, i in enumerate(scope)) + if eval_poly(poly, x): + clauses.append(tuple((-(i + 1) if (x >> i) & 1 else i + 1) for i in scope)) + return tuple(clauses) + + +def system_to_cnf(n: int, system: Iterable[Poly], scope_limit: int = 14) -> tuple[Clause, ...]: + return tuple(clause for poly in system for clause in poly_to_cnf(n, poly, scope_limit)) + + +def local_output_cnf(n: int, inputs: tuple[int, ...], truth_table: tuple[int, ...], target: int) -> tuple[Clause, ...]: + """Encode one output bit of a fixed-locality map directly on key bits. + + inputs are zero-based positions; truth_table indexed by low-to-high bits. + One width-d clause excludes each local tuple with an incorrect output. + """ + if type(n) is not int or n < 0 or len(set(inputs)) != len(inputs) or any( + type(i) is not int or not 0 <= i < n for i in inputs + ) or not all(type(v) is int and v in (0, 1) for v in truth_table) or len(truth_table) != 1 << len(inputs): + raise ValueError("malformed local truth table") + if type(target) is not int or target not in (0, 1): + raise ValueError("invalid desired output") + clauses = [] + for mask, value in enumerate(truth_table): + if value != target: + clauses.append(tuple((-(index + 1) if (mask >> j) & 1 else index + 1) + for j, index in enumerate(inputs))) + return tuple(clauses) + + +def sparse_lemma_inventory(n: int, polys: tuple[Poly, ...], degree_bound: int, c: int) -> dict: + """Gate the *manuscript-only* sparse polynomial counting lemma. + + Its hypotheses: n>=20; <=c*n equations; each listed equation has + <=ceil(log2(n))**c monomials and degree <=fixed k=degree_bound. + Boolean multilinearization is already baked into bitmask monomials. + This does not certify the underlying theorem or its hidden constants. + """ + if any(type(x) is not int or x < 1 for x in (n, degree_bound, c)): + raise ValueError("n, fixed degree k, fixed c must be positive integers") + if any(any(type(m) is not int or not 0 <= m < (1 << n) for m in poly) for poly in polys): + raise ValueError("monomial outside declared variables") + lam = (n - 1).bit_length() + max_terms = max((len(p) for p in polys), default=0) + max_degree = max((mon.bit_count() for p in polys for mon in p), default=0) + failures = [] + if n < 20: + failures.append("n_below_20") + if len(polys) > c * n: + failures.append("too_many_equations") + if max_terms > lam ** c: + failures.append("monomial_bound_exceeded") + if max_degree > degree_bound: + failures.append("degree_bound_exceeded") + return { + "n": n, "equations": len(polys), "maximum_monomials": max_terms, + "maximum_degree": max_degree, "fixed_k": degree_bound, "fixed_c": c, + "monomial_limit": lam ** c, "eligible_on_stated_syntactic_conditions": not failures, + "failures": failures, "proof_level": "manuscript_only_not_lean_endpoint", + } + + +NIST_AES_128 = { + "key_bits": 128, "ciphertext_pins": 128, "and": 6400, + "xor": 21356, "xnor": 844, + "source": "https://csrc.nist.gov/projects/circuit-complexity/list-of-circuits", + "object": "AES-128(k,m) published SLP census, variable key and message", +} + + +def nist_aes_cnf_census() -> dict: + """Exact gate-count arithmetic for one published SLP, not an AES attack. + + Freeze plaintext bits as constants. No gate simplification or elimination + is assumed. Each binary gate gets a Tseitin variable. Output pins each + contribute one unit clause, and key bits remain free. An implementation + would need to instantiate the NIST SLP to validate this counting model. + """ + s = NIST_AES_128 + gates = s["and"] + s["xor"] + s["xnor"] + variables = s["key_bits"] + gates + clauses = 3 * s["and"] + 4 * (s["xor"] + s["xnor"]) + s["ciphertext_pins"] + proxy = variables / sqrt(log2(variables)) + return { + **s, "gates": gates, "tseitin_variables": variables, + "tseitin_clauses": clauses, "clauses_per_variable": clauses / variables, + "variables_per_key_bit": variables / s["key_bits"], + "optimistic_fixed_density_exponent_proxy": round(proxy, 3), + "proxy_over_bruteforce_key_exponent": round(proxy / s["key_bits"], 3), + "unverified_xor_elimination_variable_count_ceiling": s["key_bits"] + s["and"], + "proxy_warning": "C=1 exponent proxy; theorem has unknown large constants and no finite-scale efficiency guarantee; eliminating XORs may densify polynomials", + } + + +# Source-pinned Pareto points in NIST's full AES-128 Encipher circuit catalogue. +# The 256 circuit inputs split into 128 key bits and 128 plaintext bits. +NIST_AES_FRONTIER = ( + { + "id": "fewest_total_gates_in_nist_subset", + "and": 6400, "xor": 20840, "xnor": 616, + "source_blob_sha1": "6875e0d6f5878f9cbab255d62ebaad6848cb6c53", + "source": "https://github.com/usnistgov/Circuits/blob/8366158a4324ef902ce740f29ddc9f7ebb1018b2/data/slp/aes/aes-encipher/aes128-encipher-a6400-ad50-g27856-gd286-xx21456-616.circ.txt", + }, + { + "id": "fewest_and_gates_in_nist_subset", + "and": 5800, "xor": 23840, "xnor": 4016, + "source_blob_sha1": "a1dbbb143b13f8bb7c9e5f7b3e0f3d5c27785eae", + "source": "https://github.com/usnistgov/Circuits/blob/8366158a4324ef902ce740f29ddc9f7ebb1018b2/data/slp/aes/aes-encipher/aes128-encipher-a5800-ad50-g33656-gd388-xx27856-4016.circ.txt", + }, +) + + +def nist_aes_pareto_frontier() -> tuple[dict, ...]: + """Two published options, not a claim of global optimality. + + Counts use verified gate headers; full SLP replay remains outstanding. + """ + results = [] + for variant in NIST_AES_FRONTIER: + gate_count = variant["and"] + variant["xor"] + variant["xnor"] + n = 128 + gate_count + m = 3 * variant["and"] + 4 * (variant["xor"] + variant["xnor"]) + 128 + nonlinear_n = 128 + variant["and"] + results.append({ + **variant, "key_bits": 128, "output_pins": 128, + "gates": gate_count, + "tseitin_variables": n, "tseitin_clauses": m, + "unverified_xor_elimination_variable_count": nonlinear_n, + "optimistic_cnf_exponent_proxy": round(n / sqrt(log2(n)), 3), + "optimistic_sparse_exponent_proxy": round( + nonlinear_n * log2(log2(nonlinear_n)) / sqrt(log2(nonlinear_n)), 3 + ), + "warning": "header-source census, not an SLP execution or finite-time theorem bound", + }) + return tuple(results) diff --git a/src/spiral_ln/cryptomania_audit.py b/src/spiral_ln/cryptomania_audit.py new file mode 100644 index 00000000..64f1cd18 --- /dev/null +++ b/src/spiral_ln/cryptomania_audit.py @@ -0,0 +1,206 @@ +"""Auditable, three-valued logical model of Impagliazzo's five worlds. + +A recorded research announcement never becomes a theorem input on its own. +An implication A => B permits A=true -> B=true and B=false -> A=false. +Conditional cryptographic routes are evidence paths, not logical implications +from an assumption to the existence or security of a particular primitive. +All arithmetic in the illustrative Bayesian update is exact. +""" +from __future__ import annotations + +from fractions import Fraction +from typing import Any, Mapping + +WORLD_AXES = ("P_NE_NP", "AVG_HARD", "OWF", "PKE") +WORLD_ORDER = ("Algorithmica", "Heuristica", "Pessiland", "Minicrypt", "Cryptomania") + + +def validate_manifest(data: dict[str, Any]) -> None: + """Reject dangling propositions, ill-typed hypotheses and inconsistent worlds.""" + if data.get("schema_version") != "1.0": + raise ValueError("unsupported manifest schema") + props = data.get("propositions") + if not isinstance(props, dict) or not props: + raise ValueError("nonempty propositions mapping required") + if not all(isinstance(k, str) and k and isinstance(v, str) and v for k, v in props.items()): + raise ValueError("invalid proposition") + if not set(WORLD_AXES).issubset(props): + raise ValueError("missing five-world axis") + edges = data.get("implications") + if not isinstance(edges, list): + raise ValueError("implications must be a list") + for edge in edges: + if not isinstance(edge, list) or len(edge) != 2 or not all(x in props for x in edge): + raise ValueError(f"invalid implication {edge!r}") + if len({tuple(e) for e in edges}) != len(edges): + raise ValueError("duplicate implications") + worlds = data.get("worlds") + if not isinstance(worlds, dict) or set(worlds) != set(WORLD_ORDER): + raise ValueError("exactly five named worlds required") + for name, flags in worlds.items(): + if not isinstance(flags, dict) or set(flags) != set(WORLD_AXES): + raise ValueError(f"invalid world projection: {name}") + if not all(type(v) is bool for v in flags.values()): + raise ValueError(f"nonboolean world projection: {name}") + for antecedent, consequent in edges: + if antecedent in flags and consequent in flags: + if flags[antecedent] and not flags[consequent]: + raise ValueError(f"world violates implication: {name}") + if len({tuple(w[a] for a in WORLD_AXES) for w in worlds.values()}) != 5: + raise ValueError("world projections must be distinct") + scenarios = data.get("scenarios") + if not isinstance(scenarios, dict) or not scenarios: + raise ValueError("scenarios mapping required") + for name, assignments in scenarios.items(): + if not isinstance(assignments, dict): + raise ValueError(f"invalid scenario {name}") + for proposition, value in assignments.items(): + if proposition not in props or type(value) is not bool: + raise ValueError(f"invalid scenario literal {name}/{proposition}") + routes = data.get("routes") + if not isinstance(routes, list): + raise ValueError("routes must be a list") + ids = set() + for item in routes: + if not isinstance(item, dict) or not isinstance(item.get("id"), str) or item["id"] in ids: + raise ValueError("missing or duplicate route id") + ids.add(item["id"]) + if not isinstance(item.get("summary"), str) or not item["summary"]: + raise ValueError("route lacks explanation") + alternatives = item.get("premises") + if not isinstance(alternatives, list) or not alternatives: + raise ValueError("each claim requires at least one premises route") + for route in alternatives: + if not isinstance(route, list) or not route or any(x not in props for x in route): + raise ValueError("dangling or empty premise route") + observations = data.get("evidence") + if not isinstance(observations, list): + raise ValueError("evidence must be a list") + obs_ids = set() + for obs in observations: + if not isinstance(obs, dict) or not isinstance(obs.get("id"), str) or obs["id"] in obs_ids: + raise ValueError("missing or duplicate evidence id") + obs_ids.add(obs["id"]) + if obs.get("proposition") not in props or type(obs.get("proposed_value")) is not bool: + raise ValueError("invalid evidence proposition or proposed value") + if not all(isinstance(obs.get(f), str) and obs[f] for f in ("stage", "source", "scope")): + raise ValueError("evidence lacks review stage, source or scope") + + +def propagate(data: dict[str, Any], assumed: Mapping[str, bool]) -> tuple[dict[str, bool | None], dict[str, str]]: + """Compute the least fixed point of Horn implications and contrapositives.""" + validate_manifest(data) + status: dict[str, bool | None] = dict.fromkeys(data["propositions"]) + why: dict[str, str] = {} + + def place(name: str, value: bool, reason: str) -> bool: + if name not in status or type(value) is not bool: + raise ValueError(f"invalid literal {name}={value}") + old = status[name] + if old is not None and old != value: + raise ValueError(f"contradiction for {name}: {why[name]} versus {reason}") + if old is None: + status[name] = value + why[name] = reason + return True + return False + + for name, value in sorted(assumed.items()): + place(name, value, "explicit scenario/world assignment") + changed = True + while changed: + changed = False + for a, b in sorted(data["implications"]): + if status[a] is True: + changed |= place(b, True, f"{a} => {b}; {a} asserted true") + if status[b] is False: + changed |= place(a, False, f"{a} => {b}; {b} asserted false") + return status, why + + +def compatible_worlds(data: dict[str, Any], assumed: Mapping[str, bool]) -> list[str]: + """Find world projections consistent with supplied (possibly non-world) facts.""" + result = [] + for world in WORLD_ORDER: + combined = dict(assumed) + flags = data["worlds"][world] + if any(k in combined and combined[k] != value for k, value in flags.items()): + continue + combined.update(flags) + try: + propagate(data, combined) + except ValueError: + continue + result.append(world) + return result + + +def score_routes(data: dict[str, Any], status: Mapping[str, bool | None]) -> dict[str, dict[str, Any]]: + """Diagnose listed proof routes. A broken premise says nothing about a scheme break.""" + output: dict[str, dict[str, Any]] = {} + for claim in data["routes"]: + route_states = [] + for premises in claim["premises"]: + values = [status[p] for p in premises] + route_states.append("invalidated" if False in values else + "premises_asserted" if all(v is True for v in values) else "open") + overall = ("premises_asserted" if "premises_asserted" in route_states else + "all_listed_routes_invalidated" if all(x == "invalidated" for x in route_states) else + "some_routes_invalidated" if "invalidated" in route_states else "open") + output[claim["id"]] = {"status": overall, "alternative_routes": route_states} + return output + + +def bayes_worlds(priors: Mapping[str, Fraction], likelihoods: Mapping[str, Fraction]) -> dict[str, Fraction]: + """Exact posterior P(world | observed event) with an explicit joint model.""" + if set(priors) != set(WORLD_ORDER) or set(likelihoods) != set(WORLD_ORDER): + raise ValueError("world-specific priors and likelihoods required") + if any(type(x) is not Fraction or not 0 <= x <= 1 for x in (*priors.values(), *likelihoods.values())): + raise ValueError("probabilities must be exact Fractions in [0,1]") + if sum(priors.values()) != 1: + raise ValueError("world priors must sum to 1") + total = sum(priors[w] * likelihoods[w] for w in WORLD_ORDER) + if total == 0: + raise ValueError("observed event has zero likelihood") + return {w: priors[w] * likelihoods[w] / total for w in WORLD_ORDER} + + +def bayes_example() -> dict[str, Any]: + """Illustration: unconditional P(ETH)=9/10 with P(ETH|Algorithmica)=0.""" + q = Fraction + priors = dict(zip(WORLD_ORDER, (q(1, 1000), q(9, 1000), q(40, 1000), + q(150, 1000), q(800, 1000)))) + # Sum_{w != Algorithmica} P(w) * 100/111 = 9/10. + likelihoods = {w: (q(1) if w == "Algorithmica" else q(11, 111)) for w in WORLD_ORDER} + post = bayes_worlds(priors, likelihoods) + assert sum(priors[w] * likelihoods[w] for w in WORLD_ORDER) == q(1, 10) + assert post["Algorithmica"] / priors["Algorithmica"] == 10 + return { + "event": "ETH false; assumed, not independently certified by this program", + "prior_eth": str(q(9, 10)), + "prior": {w: str(priors[w]) for w in WORLD_ORDER}, + "p_event_given_world": {w: str(likelihoods[w]) for w in WORLD_ORDER}, + "posterior": {w: str(post[w]) for w in WORLD_ORDER}, + "algorithmica_multiplier": "10", + } + + +def report(data: dict[str, Any], scenario: str = "unadjudicated") -> dict[str, Any]: + """Stable machine-readable audit; no observation auto-upgrades a premise.""" + validate_manifest(data) + if scenario not in data["scenarios"]: + raise ValueError(f"unknown scenario: {scenario}") + assumed = data["scenarios"][scenario] + status, why = propagate(data, assumed) + return { + "schema_version": "1.0", + "scenario": scenario, + "scenario_literals": assumed, + "propositions": {k: ("unknown" if v is None else "true" if v else "false") + for k, v in sorted(status.items())}, + "inference_reasons": dict(sorted(why.items())), + "compatible_worlds": compatible_worlds(data, assumed), + "conditional_routes": score_routes(data, status), + "bayesian_illustration": bayes_example(), + "evidence_not_promoted": len(data["evidence"]), + } diff --git a/src/spiral_ln/cryptomania_toy_count.py b/src/spiral_ln/cryptomania_toy_count.py new file mode 100644 index 00000000..66c81770 --- /dev/null +++ b/src/spiral_ln/cryptomania_toy_count.py @@ -0,0 +1,117 @@ +"""Tiny exact #CNF benchmark: independent-component factorization versus brute force. + +The work metric counts full component assignments examined, excluding parsing, +graph traversal and fixed overhead. This is a toy control of structural reuse, +not an ETH algorithm, cryptanalytic claim or measured wall-clock speedup. +""" +from __future__ import annotations + +from random import Random + +Clause = tuple[int, ...] +CNF = tuple[Clause, ...] + + +def validate_cnf(n: int, clauses: CNF) -> None: + if type(n) is not int or not 0 <= n <= 20: + raise ValueError("toy benchmark supports 0 <= n <= 20") + for clause in clauses: + if not isinstance(clause, tuple) or not clause: + raise ValueError("nonempty tuple clause required") + if any(type(lit) is not int or lit == 0 or abs(lit) > n for lit in clause): + raise ValueError("invalid literal") + if len({abs(lit) for lit in clause}) != len(clause): + raise ValueError("one literal per variable per clause required") + + +def exact_count(n: int, clauses: CNF) -> tuple[int, int]: + """Count full satisfying assignments by exhaustive independent enumeration.""" + validate_cnf(n, clauses) + count = 0 + for mask in range(1 << n): + if all(any(bool(mask & (1 << (abs(lit) - 1))) == (lit > 0) + for lit in clause) for clause in clauses): + count += 1 + return count, 1 << n + + +def components(n: int, clauses: CNF) -> tuple[tuple[int, ...], ...]: + """Connected variable components of the clause hypergraph; isolates included.""" + validate_cnf(n, clauses) + adjacent = [set() for _ in range(n)] + for clause in clauses: + vs = [abs(x) - 1 for x in clause] + for v in vs[1:]: + adjacent[vs[0]].add(v) + adjacent[v].add(vs[0]) + seen: set[int] = set() + blocks = [] + for root in range(n): + if root in seen: + continue + seen.add(root) + stack = [root] + block = [] + while stack: + v = stack.pop() + block.append(v) + for w in sorted(adjacent[v]): + if w not in seen: + seen.add(w) + stack.append(w) + blocks.append(tuple(sorted(block))) + return tuple(blocks) + + +def factorized_count(n: int, clauses: CNF) -> tuple[int, int, tuple[int, ...]]: + """Exact product of component counts; returns counts and assignment proxy.""" + blocks = components(n, clauses) + total, work = 1, 0 + for block in blocks: + index = {v: i + 1 for i, v in enumerate(block)} + sub = tuple(tuple((1 if lit > 0 else -1) * index[abs(lit) - 1] + for lit in clause) + for clause in clauses if abs(clause[0]) - 1 in index) + partial, visited = exact_count(len(block), sub) + total *= partial + work += visited + return total, work, tuple(len(b) for b in blocks) + + +def seeded_instance(blocks: int, seed: int, connected: bool) -> tuple[int, CNF]: + """Seeded fixed-width instances with disconnected and joined control graphs.""" + if type(blocks) is not int or not 1 <= blocks <= 5: + raise ValueError("blocks must be in [1,5]") + rng = Random(seed) + clauses: list[Clause] = [] + for b in range(blocks): + vs = (3 * b + 1, 3 * b + 2, 3 * b + 3) + for _ in range(3): + clauses.append(tuple(rng.choice((-1, 1)) * x for x in vs)) + if connected: + for b in range(1, blocks): + clauses.append((3 * b, 3 * b + 1, -(3 * b + 2))) + return 3 * blocks, tuple(clauses) + + +def run_toy_suite(seed: int = 20261027) -> list[dict[str, object]]: + """Reproducible exact-count tests over connected/disconnected controls.""" + rows = [] + for blocks in (2, 3, 4, 5): + for linked in (False, True): + n, clauses = seeded_instance(blocks, seed + blocks, linked) + count, baseline = exact_count(n, clauses) + factored, work, sizes = factorized_count(n, clauses) + if factored != count: + raise AssertionError("factorization changed exact #SAT") + rows.append({ + "variables": n, + "linked_control": linked, + "solutions": count, + "components": list(sizes), + "baseline_assignments": baseline, + "factorized_assignments": work, + "assignment_proxy_ratio": f"{baseline}/{work}", + "exactly_equal": True, + }) + return rows diff --git a/tests/test_crypto_encoding_bridge.py b/tests/test_crypto_encoding_bridge.py new file mode 100644 index 00000000..7b1efd0e --- /dev/null +++ b/tests/test_crypto_encoding_bridge.py @@ -0,0 +1,203 @@ +"""Exact toy-equivalence checks; no live cryptography or key attacks.""" +from __future__ import annotations + +import itertools + +import pytest + +from spiral_ln.crypto_encoding_bridge import ( + Circuit, count_cnf, eval_cnf, eval_poly, execute, local_output_cnf, + matches, nist_aes_cnf_census, nist_aes_pareto_frontier, poly_add, poly_mul, poly_to_cnf, + sparse_lemma_inventory, system_to_cnf, tseitin, xor_eliminate, + zero_count, +) + + +def check(circuit): + n, cnf = tseitin(circuit) + n2, polys = xor_eliminate(circuit) + actual = sum(matches(circuit, bits) for bits in range(1 << circuit.inputs)) + assert count_cnf(n, cnf) == actual + assert zero_count(n2, polys) == actual + assert count_cnf(n2, system_to_cnf(n2, polys)) == actual + assert n2 == circuit.inputs + sum(op == "AND" for op, *_ in circuit.gates) + return n, n2, cnf, polys + + +def test_single_gate_truth_table_and_unique_witness(): + for op in ("AND", "XOR", "XNOR"): + for expected in (0, 1): + circ = Circuit(2, ((op, 0, 1),), ((2, expected),)) + n, n2, cnf, polys = check(circ) + assert n == 3 + assert n2 == (3 if op == "AND" else 2) + assert len(cnf) == (4 if op != "AND" else 3) + 1 + assert all(len(clause) <= 3 for clause in cnf) + + +def test_nontrivial_chained_affine_and_nonlinear(): + circuits = ( + Circuit(3, (("XOR", 0, 1), ("AND", 3, 2), ("XNOR", 4, 1)), ((5, 1),)), + Circuit(3, (("AND", 0, 1), ("XOR", 3, 2), ("AND", 4, 0)), ((5, 0), (4, 1))), + Circuit(2, (("XOR", 0, 0), ("AND", 2, 1), ("XNOR", 3, 1)), ((4, 1),)), + Circuit(3, (("XOR", 0, 1), ("XNOR", 3, 2), ("XOR", 4, 1)), ((5, 0),)), + ) + for circ in circuits: + check(circ) + + +def test_toy_exhaustive_gate_chains_with_output_pins(): + # All 3^2 gate types, all input pairs including identical wires, and + # both target values: independent enumeration checks both encodings. + for op1, op2 in itertools.product(("AND", "XOR", "XNOR"), repeat=2): + for a, b in itertools.product(range(3), repeat=2): + for expected in (0, 1): + circ = Circuit(2, ((op1, 0, 1), (op2, a, b)), ((3, expected),)) + check(circ) + + +def test_local_map_preserves_original_variables(): + n = 6 + seed = 0b101101 + specs = ( + ((0, 2, 4), tuple(x.bit_count() % 2 for x in range(8))), + ((1, 2, 5), tuple(int(x in (3, 7)) for x in range(8))), + ((0, 3), (0, 1, 1, 0)), + ((2, 3, 4), tuple((x & 1) & ((x >> 1) & 1) for x in range(8))), + ) + all_clauses = [] + for scope, table in specs: + idx = sum(((seed >> i) & 1) << j for j, i in enumerate(scope)) + target = table[idx] + clauses = local_output_cnf(n, scope, table, target) + assert all(len(c) == len(scope) for c in clauses) + assert len(clauses) <= 1 << len(scope) + all_clauses.extend(clauses) + assert eval_cnf(all_clauses, seed) + actual = 0 + for key in range(1 << n): + good = all(table[sum(((key >> i) & 1) << j for j, i in enumerate(scope))] == + table[sum(((seed >> i) & 1) << j for j, i in enumerate(scope))] + for scope, table in specs) + actual += good + assert good == eval_cnf(all_clauses, key) + assert count_cnf(n, all_clauses) == actual + + +def test_local_map_constant_and_malformed(): + assert local_output_cnf(2, (), (1,), 1) == () + assert local_output_cnf(2, (), (1,), 0) == ((),) + with pytest.raises(ValueError): + local_output_cnf(2, (0, 0), (0, 1, 0, 1), 0) + with pytest.raises(ValueError): + local_output_cnf(2, (2,), (0, 1), 0) + + +def test_boolean_polynomial_normalization_and_direct_cnf(): + a = frozenset((1, 3, 7)) + b = frozenset((1, 6)) + assert poly_add(a, b) == frozenset((3, 6, 7)) + assert poly_mul(frozenset((1,)), frozenset((1,))) == frozenset((1,)) + assert poly_mul(frozenset((0, 1)), frozenset((0, 1))) == frozenset((0, 1)) + for masks in ((), (0,), (1, 2, 0), (1, 2, 3), (3, 5, 7)): + p = frozenset(masks) + clauses = poly_to_cnf(3, p) + assert len(clauses) <= 1 << 3 + for x in range(8): + assert (eval_poly(p, x) == 0) == eval_cnf(clauses, x) + + +def test_structural_sparse_lemma_gate_fails_closed(): + linear = tuple(frozenset((1 << (i % 23),)) for i in range(30)) + ok = sparse_lemma_inventory(30, linear, degree_bound=2, c=2) + assert ok["eligible_on_stated_syntactic_conditions"] + assert ok["monomial_limit"] == 25 + assert ok["maximum_degree"] == 1 + dense = (frozenset(range(26)),) + bad = sparse_lemma_inventory(30, dense, 2, 2) + assert "monomial_bound_exceeded" in bad["failures"] + bad = sparse_lemma_inventory(30, (frozenset((1 << 0 | 1 << 1 | 1 << 2,)),), 2, 2) + assert "degree_bound_exceeded" in bad["failures"] + bad = sparse_lemma_inventory(30, linear * 3, 2, 2) + assert "too_many_equations" in bad["failures"] + assert "n_below_20" in sparse_lemma_inventory(5, (frozenset((1,)),), 2, 2)["failures"] + + +def test_nist_aes_census_is_published_gate_arithmetic(): + d = nist_aes_cnf_census() + assert d["gates"] == 28_600 + assert d["tseitin_variables"] == 28_728 + assert d["tseitin_clauses"] == 108_128 + assert d["unverified_xor_elimination_variable_count_ceiling"] == 6_528 + assert 7_460 < d["optimistic_fixed_density_exponent_proxy"] < 7_470 + assert d["variables_per_key_bit"] > 200 + + +def test_xor_elimination_preserves_affine_sparsity_positive_control(): + # Parity on 24 inputs produces one 25-term linear relation after XOR elimination. + gates = [("XOR", 0, 1)] + for v in range(2, 24): + gates.append(("XOR", 24 + len(gates) - 1, v)) + circ = Circuit(24, tuple(gates), ((24 + len(gates) - 1, 1),)) + n, polys = xor_eliminate(circ) + assert n == 24 and len(polys) == 1 + assert len(polys[0]) == 25 # 24 singleton monomials and constant 1 + eligibility = sparse_lemma_inventory(n, polys, degree_bound=2, c=2) + assert eligibility["eligible_on_stated_syntactic_conditions"] + assert eligibility["monomial_limit"] == 25 + for bits in (0, 1, 3, 7, (1 << 24) - 1, (1 << 24) - 2): + assert (eval_poly(polys[0], bits) == 0) == matches(circ, bits) + + +def test_xor_elimination_quadratic_monomial_explosion_negative_control(): + # Two 12-input parities multiplied into an AND give 12^2 distinct + # quadratic terms after the XOR wires are removed. + gates = [] + end = [] + for start in (0, 12): + gates.append(("XOR", start, start + 1)) + for v in range(start + 2, start + 12): + gates.append(("XOR", 24 + len(gates) - 1, v)) + end.append(24 + len(gates) - 1) + gates.append(("AND", end[0], end[1])) + circ = Circuit(24, tuple(gates), ((24 + len(gates) - 1, 1),)) + n, polys = xor_eliminate(circ) + assert n == 25 and len(polys) == 2 + assert len(polys[0]) == 145 # 144 cross terms and fresh AND output + assert len(polys[1]) == 2 # pin AND output to true + eligibility = sparse_lemma_inventory(n, polys, degree_bound=2, c=2) + assert "monomial_bound_exceeded" in eligibility["failures"] + assert eligibility["maximum_degree"] == 2 + for bits in (0, 1, 3, 7, 0x123456, 0xabcdef, (1 << 24) - 1): + computed = execute(circ, bits) + extension = bits | (computed[-1] << 24) + assert all(eval_poly(poly, extension) == 0 for poly in polys) == matches(circ, bits) + flipped = extension ^ (1 << 24) + assert eval_poly(polys[0], flipped) == 1 + + + +def test_nist_flat_aes_pareto_header_arithmetic(): + gate_min, and_min = nist_aes_pareto_frontier() + assert (gate_min["and"], gate_min["xor"], gate_min["xnor"]) == (6400, 20840, 616) + assert (gate_min["gates"], gate_min["tseitin_variables"], gate_min["tseitin_clauses"]) == ( + 27856, 27984, 105152 + ) + assert (and_min["and"], and_min["xor"], and_min["xnor"]) == (5800, 23840, 4016) + assert (and_min["gates"], and_min["tseitin_variables"], and_min["tseitin_clauses"]) == ( + 33656, 33784, 128952 + ) + assert gate_min["gates"] < and_min["gates"] + assert and_min["unverified_xor_elimination_variable_count"] == 5928 + assert gate_min["unverified_xor_elimination_variable_count"] == 6528 + assert all(item["optimistic_cnf_exponent_proxy"] > 128 for item in (gate_min, and_min)) + assert all(item["optimistic_sparse_exponent_proxy"] > 128 for item in (gate_min, and_min)) + + +def test_nist_published_variants_have_source_and_scope_distinctions(): + options = nist_aes_pareto_frontier() + assert len(options) == 2 + assert len({x["source_blob_sha1"] for x in options}) == 2 + assert all(len(x["source_blob_sha1"]) == 40 for x in options) + assert all("/aes128-encipher-" in x["source"] for x in options) + assert all("not an SLP execution" in x["warning"] for x in options) diff --git a/tests/test_cryptomania_audit.py b/tests/test_cryptomania_audit.py new file mode 100644 index 00000000..63040093 --- /dev/null +++ b/tests/test_cryptomania_audit.py @@ -0,0 +1,242 @@ +"""Adversarial logical controls for the Cryptomania assumption ledger.""" +from __future__ import annotations + +import copy +import json +from fractions import Fraction as Q +from pathlib import Path + +import pytest + +from spiral_ln.cryptomania_audit import ( + WORLD_ORDER, bayes_example, bayes_worlds, compatible_worlds, + propagate, report, score_routes, validate_manifest, +) +from spiral_ln.cryptomania_toy_count import ( + components, exact_count, factorized_count, run_toy_suite, + seeded_instance, validate_cnf, +) + +MANIFEST = Path(__file__).resolve().parents[1] / "configs/cryptomania_assumptions_v1.json" + + +@pytest.fixture +def data(): + return json.loads(MANIFEST.read_text(encoding="utf-8")) + + +def test_schema_and_all_five_worlds(data): + validate_manifest(data) + assert compatible_worlds(data, {}) == list(WORLD_ORDER) + + +def test_reported_eth_disproof_does_not_eliminate_any_world(data): + status, reasons = propagate(data, {"ETH": False}) + assert compatible_worlds(data, {"ETH": False}) == list(WORLD_ORDER) + assert status["P_NE_NP"] is None + assert status["HASH_ETH"] is None + assert status["SETH"] is False and status["GAP_ETH"] is False + assert "ETH" in reasons["SETH"] + + +def test_exact_count_hypothesis_falsity_forces_eth_falsity_but_not_conversely(data): + status, _ = propagate(data, {"HASH_ETH": False}) + assert status["ETH"] is False + assert status["SETH"] is False + status, _ = propagate(data, {"ETH": False}) + assert status["HASH_ETH"] is None + + +def test_eth_true_excludes_only_algorithmica(data): + assert compatible_worlds(data, {"ETH": True}) == list(WORLD_ORDER[1:]) + status, _ = propagate(data, {"ETH": True}) + assert status["P_NE_NP"] is True + assert status["HASH_ETH"] is True + + +def test_pke_implies_owf_average_hardness_and_worst_case(data): + status, _ = propagate(data, {"PKE": True}) + assert all(status[k] is True for k in ("PKE", "OWF", "AVG_HARD", "P_NE_NP")) + assert status["ETH"] is None + + +def test_owf_false_excludes_pke_without_forcing_easy_np(data): + status, _ = propagate(data, {"OWF": False}) + assert status["PKE"] is False + assert status["AVG_HARD"] is None + assert status["P_NE_NP"] is None + + +def test_average_hardness_does_not_prove_one_way_functions(data): + status, _ = propagate(data, {"AVG_HARD": True}) + assert status["P_NE_NP"] is True + assert status["OWF"] is None and status["PKE"] is None + + +def test_algorithmica_forces_all_stronger_hypotheses_false(data): + status, _ = propagate(data, {"P_NE_NP": False}) + assert all(status[k] is False for k in + ("ETH", "SETH", "GAP_ETH", "OWF", "PKE", "AVG_HARD")) + # Fast decision algorithms do not automatically supply fast exact counters. + assert status["HASH_ETH"] is None + + +def test_orthogonal_hypothesis_remains_unknown(data): + status, _ = propagate(data, data["scenarios"]["accept_october_2026_reports"]) + assert status["LWE_HARD"] is None and status["ECDLP_HARD"] is None + assert status["PKE"] is None + + +def test_reported_counteralgorithms_invalidate_only_listed_routes(data): + r = report(data, "accept_october_2026_reports") + assert r["compatible_worlds"] == list(WORLD_ORDER) + routes = r["conditional_routes"] + assert routes["fine_grained_pke_zero_k_clique"]["status"] == "all_listed_routes_invalidated" + assert routes["fine_grained_pow_3sum"]["status"] == "all_listed_routes_invalidated" + assert routes["cvp_lower_bound_from_seth"]["status"] == "all_listed_routes_invalidated" + assert routes["svp_lower_bound_from_gap_eth"]["status"] == "all_listed_routes_invalidated" + assert routes["lwe_security_assumption"]["status"] == "open" + assert routes["ecdlp_security_assumption"]["status"] == "open" + assert r["propositions"]["PKE"] == "unknown" + + +def test_publications_are_metadata_until_explicit_scenario(data): + r = report(data) + assert r["evidence_not_promoted"] == len(data["evidence"]) + assert all(x == "unknown" for x in r["propositions"].values()) + assert all(x["status"] == "open" for x in r["conditional_routes"].values()) + + +def test_independent_routes_not_silently_all_broken(data): + example = copy.deepcopy(data) + example["routes"].append({ + "id": "two_routes", "summary": "Independent premises", "premises": [["ETH"], ["LWE_HARD"]] + }) + status, _ = propagate(example, {"ETH": False}) + assert score_routes(example, status)["two_routes"] == { + "status": "some_routes_invalidated", + "alternative_routes": ["invalidated", "open"], + } + status, _ = propagate(example, {"ETH": False, "LWE_HARD": True}) + assert score_routes(example, status)["two_routes"]["status"] == "premises_asserted" + + +@pytest.mark.parametrize("seeds", [ + {"PKE": True, "OWF": False}, + {"ETH": True, "P_NE_NP": False}, + {"HASH_ETH": False, "ETH": True}, + {"SETH": True, "ETH": False}, +]) +def test_contradictory_claims_fail_closed(data, seeds): + with pytest.raises(ValueError, match="contradiction"): + propagate(data, seeds) + + +def test_dangling_edges_and_missing_provenance_rejected(data): + broken = copy.deepcopy(data) + broken["implications"].append(["PKE", "MAGIC"]) + with pytest.raises(ValueError): + validate_manifest(broken) + broken = copy.deepcopy(data) + broken["evidence"][0].pop("scope") + with pytest.raises(ValueError): + validate_manifest(broken) + + +def test_bad_world_and_schema_fail_closed(data): + bad = copy.deepcopy(data) + bad["worlds"]["Cryptomania"]["OWF"] = False + with pytest.raises(ValueError): + validate_manifest(bad) + bad = copy.deepcopy(data) + bad["schema_version"] = "999" + with pytest.raises(ValueError): + validate_manifest(bad) + + +def test_example_exact_bayes_update(): + ex = bayes_example() + assert ex["algorithmica_multiplier"] == "10" + assert Q(ex["prior"]["Algorithmica"]) == Q(1, 1000) + assert Q(ex["posterior"]["Algorithmica"]) == Q(1, 100) + assert Q(ex["posterior"]["Cryptomania"]) == Q(88, 111) + assert sum(map(Q, ex["posterior"].values())) == 1 + + +def test_cryptomania_likelihood_varies_with_joint_model(): + prior = {w: Q(1, 5) for w in WORLD_ORDER} + # ETH false is certain in Algorithmica. Other worlds remain compatible. + low = {w: Q(1) if w == "Algorithmica" else Q(1, 10) for w in WORLD_ORDER} + high = dict(low) + high["Cryptomania"] = Q(9, 10) + assert bayes_worlds(prior, high)["Cryptomania"] > bayes_worlds(prior, low)["Cryptomania"] + + +@pytest.mark.parametrize("prior,like", [ + ({w: Q(1, 4) for w in WORLD_ORDER}, {w: Q(1) for w in WORLD_ORDER}), + ({w: Q(1, 5) for w in WORLD_ORDER}, {w: Q(0) for w in WORLD_ORDER}), +]) +def test_bayesian_bad_normalization_or_zero_likelihood(prior, like): + with pytest.raises(ValueError): + bayes_worlds(prior, like) + + +def test_seeded_cnf_exact_count_equivalence_with_connected_negative_controls(): + for blocks in (1, 2, 3, 4, 5): + for seed in (0, 1, 20261027): + for linked in (False, True): + n, clauses = seeded_instance(blocks, seed, linked) + expected, baseline = exact_count(n, clauses) + value, work, sizes = factorized_count(n, clauses) + assert value == expected + assert baseline == 1 << n + assert sum(sizes) == n + assert work <= baseline + assert (len(sizes) == 1) == (linked or blocks == 1) + + +def test_zero_and_isolated_variables(): + assert exact_count(0, ()) == (1, 1) + assert factorized_count(0, ()) == (1, 0, ()) + assert exact_count(4, ((1,),)) == (8, 16) + assert factorized_count(4, ((1,),)) == (8, 8, (1, 1, 1, 1)) + + +@pytest.mark.parametrize("n, clauses", [ + (3, ((),)), (2, ((3,),)), (2, ((0,),)), (3, ((1, -1),)), + (3, ((1, 1),)), (21, ()), (-1, ()), +]) +def test_bad_cnf_rejected(n, clauses): + with pytest.raises(ValueError): + validate_cnf(n, clauses) + + +def test_benchmark_report_is_repeatable_and_control_rejoins_components(): + first = run_toy_suite() + assert first == run_toy_suite() + assert len(first) == 8 + assert all(row["exactly_equal"] for row in first) + assert all(row["components"] == [row["variables"]] for row in first if row["linked_control"]) + assert all(len(row["components"]) > 1 for row in first if not row["linked_control"]) + + +def test_receipt_regenerates_without_timestamps_or_missing_source_hashes(): + import importlib.util + import hashlib + + verifier_path = MANIFEST.parents[0].parent / "scripts/verify_cryptomania_audit.py" + spec = importlib.util.spec_from_file_location("cryptomania_verify_fixture", verifier_path) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + spec.loader.exec_module(module) + + for scenario in ("unadjudicated", "eth_only", "accept_october_2026_reports"): + a = module.make_receipt(scenario) + b = module.make_receipt(scenario) + assert a == b + assert a["all_passed"] is True + assert len(a["checks"]) >= 10 + assert "generated_at_utc" not in a + assert all((module.ROOT / rel).exists() for rel in a["source_sha256"]) + assert all(hashlib.sha256((module.ROOT / rel).read_bytes()).hexdigest() == digest + for rel, digest in a["source_sha256"].items())