From 33bb73f46bc03c55efd9d8242f7b9aca68843617 Mon Sep 17 00:00:00 2001 From: Peter Rindal Date: Tue, 17 Nov 2026 04:35:55 -0800 Subject: [PATCH 1/2] Add Ribbon OKVS and harden malicious OPRF seed selection --- frontend/main.cpp | 1 + frontend/messagePassingExample.h | 4 + frontend/networkSocketExample.h | 2 + frontend/perf.cpp | 7 +- research/baxos/.gitignore | 2 + research/baxos/README.txt | 110 ++++ research/baxos/bench.cpp | 43 ++ research/baxos/peach.py | 50 ++ research/baxos/tests.cpp | 25 + research/ribbon/.gitignore | 8 + research/ribbon/DISTINCT_KEYS.txt | 175 ++++++ research/ribbon/EXTRACTION.txt | 225 ++++++++ research/ribbon/INTEGRATION.txt | 162 ++++++ research/ribbon/README.txt | 199 +++++++ research/ribbon/Ribbon.h | 557 +++++++++++++++++++ research/ribbon/bench.cpp | 190 +++++++ research/ribbon/bound.py | 50 ++ research/ribbon/differential.cpp | 44 ++ research/ribbon/extraction_bounds.py | 64 +++ research/ribbon/integration.cpp | 80 +++ research/ribbon/integration_decode.cpp | 29 + research/ribbon/integration_peach.py | 94 ++++ research/ribbon/parameters.json | 98 ++++ research/ribbon/peach.py | 136 +++++ research/ribbon/proof.txt | 104 ++++ research/ribbon/verify_distinct_key_bound.py | 54 ++ research/ribbon/verify_integration_params.py | 29 + research/ribbon/verify_parameters.py | 30 + tests/CMakeLists.txt | 1 + tests/Paxos_Tests.cpp | 116 ++++ tests/Paxos_Tests.h | 5 + tests/Ribbon_Tests.cpp | 125 +++++ tests/Ribbon_Tests.h | 5 + tests/RsOprf_Tests.cpp | 221 ++++++++ tests/RsOprf_Tests.h | 3 + tests/UnitTests.cpp | 11 + volePSI/CMakeLists.txt | 1 + volePSI/PaxosGf128.h | 94 ++++ volePSI/PaxosImpl.h | 177 +++++- volePSI/RibbonKernels.h | 548 ++++++++++++++++++ volePSI/RibbonOkvs.cpp | 152 +++++ volePSI/RibbonOkvs.h | 51 ++ volePSI/RsOprf.cpp | 114 +++- volePSI/RsOprf.h | 11 + volePSI/RsPsi.h | 2 + volePSI/fileBased.cpp | 2 + 46 files changed, 4162 insertions(+), 49 deletions(-) create mode 100644 research/baxos/.gitignore create mode 100644 research/baxos/README.txt create mode 100644 research/baxos/bench.cpp create mode 100644 research/baxos/peach.py create mode 100644 research/baxos/tests.cpp create mode 100644 research/ribbon/.gitignore create mode 100644 research/ribbon/DISTINCT_KEYS.txt create mode 100644 research/ribbon/EXTRACTION.txt create mode 100644 research/ribbon/INTEGRATION.txt create mode 100644 research/ribbon/README.txt create mode 100644 research/ribbon/Ribbon.h create mode 100644 research/ribbon/bench.cpp create mode 100644 research/ribbon/bound.py create mode 100644 research/ribbon/differential.cpp create mode 100644 research/ribbon/extraction_bounds.py create mode 100644 research/ribbon/integration.cpp create mode 100644 research/ribbon/integration_decode.cpp create mode 100644 research/ribbon/integration_peach.py create mode 100644 research/ribbon/parameters.json create mode 100644 research/ribbon/peach.py create mode 100644 research/ribbon/proof.txt create mode 100644 research/ribbon/verify_distinct_key_bound.py create mode 100644 research/ribbon/verify_integration_params.py create mode 100644 research/ribbon/verify_parameters.py create mode 100644 tests/Ribbon_Tests.cpp create mode 100644 tests/Ribbon_Tests.h create mode 100644 volePSI/PaxosGf128.h create mode 100644 volePSI/RibbonKernels.h create mode 100644 volePSI/RibbonOkvs.cpp create mode 100644 volePSI/RibbonOkvs.h diff --git a/frontend/main.cpp b/frontend/main.cpp index 42587ff..fe2cd30 100644 --- a/frontend/main.cpp +++ b/frontend/main.cpp @@ -58,6 +58,7 @@ int main(int argc, char** argv) << " -indexSet: output the index set of the intersection instead of the set element itself\n" << " -noSort: do not require the output to be in the same order and the input (slightly faster).\n" << " -malicious: run the protocol with malicious security\n" + << " -okvs : select the same OKVS on both parties (default baxos).\n" << " -ssp: Statistical Security parameter, default = 40.\n\n" << " -ip : IP address and port of the server = PSI receiver. (Default = localhost:1212)\n" diff --git a/frontend/messagePassingExample.h b/frontend/messagePassingExample.h index c408949..370c95a 100644 --- a/frontend/messagePassingExample.h +++ b/frontend/messagePassingExample.h @@ -151,6 +151,7 @@ void messagePassingExampleRun(oc::CLP& cmd) set[i] = oc::block(0, i); sender.setMultType(type); + sender.setOkvsType(volePSI::parseOkvsType(cmd.getOr("okvs", "baxos"))); sender.init(ns, nr, ssp, oc::sysRandomSeed(), mal, 1, useReducedRounds); if (verbose) @@ -174,6 +175,7 @@ void messagePassingExampleRun(oc::CLP& cmd) volePSI::RsPsiReceiver recevier; recevier.setMultType(type); + recevier.setOkvsType(volePSI::parseOkvsType(cmd.getOr("okvs", "baxos"))); recevier.init(ns, nr, ssp, oc::sysRandomSeed(), mal, 1, useReducedRounds); if (verbose) @@ -231,6 +233,7 @@ void messagePassingExampleBoth(oc::CLP& cmd) senderSet[i] = oc::block(0, i); sender.setMultType(type); + sender.setOkvsType(volePSI::parseOkvsType(cmd.getOr("okvs", "baxos"))); sender.init(ns, nr, ssp, oc::sysRandomSeed(), mal, 1, useReducedRounds); if (verbose) @@ -249,6 +252,7 @@ void messagePassingExampleBoth(oc::CLP& cmd) volePSI::RsPsiReceiver recevier; recevier.setMultType(type); + recevier.setOkvsType(volePSI::parseOkvsType(cmd.getOr("okvs", "baxos"))); recevier.init(ns, nr, ssp, oc::sysRandomSeed(), mal, 1, useReducedRounds); if (verbose) diff --git a/frontend/networkSocketExample.h b/frontend/networkSocketExample.h index c3066a2..817a7fb 100644 --- a/frontend/networkSocketExample.h +++ b/frontend/networkSocketExample.h @@ -100,6 +100,7 @@ void networkSocketExampleRun(const oc::CLP& cmd) // configure volePSI::RsPsiSender sender; sender.setMultType(type); + sender.setOkvsType(volePSI::parseOkvsType(cmd.getOr("okvs", "baxos"))); sender.init(ns, nr, ssp, oc::sysRandomSeed(), mal, 1, useReducedRounds); std::cout << "sender start\n"; @@ -121,6 +122,7 @@ void networkSocketExampleRun(const oc::CLP& cmd) // Configure. volePSI::RsPsiReceiver recevier; recevier.setMultType(type); + recevier.setOkvsType(volePSI::parseOkvsType(cmd.getOr("okvs", "baxos"))); recevier.init(ns, nr, ssp, oc::sysRandomSeed(), mal, 1, useReducedRounds); std::cout << "recver start\n"; diff --git a/frontend/perf.cpp b/frontend/perf.cpp index 9478277..160eb64 100644 --- a/frontend/perf.cpp +++ b/frontend/perf.cpp @@ -385,8 +385,11 @@ void perfPSI(oc::CLP& cmd) recv.init(n, n, 40, ZeroBlock, mal, nt); send.init(n, n, 40, ZeroBlock, mal, nt); - recv.setMultType(type); - send.setMultType(type); + recv.setMultType(type); + send.setMultType(type); + auto okvs = parseOkvsType(cmd.getOr("okvs", "baxos")); + recv.setOkvsType(okvs); + send.setOkvsType(okvs); if (noCompress) { diff --git a/research/baxos/.gitignore b/research/baxos/.gitignore new file mode 100644 index 0000000..3705353 --- /dev/null +++ b/research/baxos/.gitignore @@ -0,0 +1,2 @@ +__pycache__/ +*.tgz diff --git a/research/baxos/README.txt b/research/baxos/README.txt new file mode 100644 index 0000000..ef108ca --- /dev/null +++ b/research/baxos/README.txt @@ -0,0 +1,110 @@ +Baxos optimization pass -- 2026-11-15 +=================================== + +Result +------ +Peach, one thread, 2^20 entries (final repeat, medians after warmup): + operation preserved baseline optimized reduction + encode 104.71 ms 78.19 ms 25.3% + decode 31.98 ms 21.94 ms 31.4% + +An earlier run of the same qualified executable measured 78.17 / 21.90 +ms. Recompiling changed code layout and produced 78.44 / 22.95 ms in +an intermediate build; retain the raw data rather than attributing every +small timing difference to a specific optimization. + +All 21 registered Paxos/Baxos checks pass natively, with ASan/UBSan +(halt on first undefined behavior), and with AVX2 and forced block +arithmetic backends. Tests include GF128/binary, vector/matrix payloads, +forced gaps, randomized/nonrandomized encoding, multiple threads, tail +batches, scalar nonmember checks, add-to-decode, and parameter failures. +The new arithmetic checks compare all SIMD remainders against C++ % and +Horner results against an independent field-power sum at degrees 1, 2, 3, 7, 17, and 40. + +Final single-thread encoded tables plus mixed member/nonmember outputs +are byte-identical to the preserved binary at 2^16 and 2^20 entries, +using different matrix/free-cell seeds. Differential hashes, source +manifests, raw CSVs, profiles, and validation logs are under +results/peach-20261115. Full source/binary snapshots and exploratory logs +are archived in out/baxos-opt-20261115/results.tgz. Each manifest identifies +the exact sources used for that build. + +Scope +----- +Production Paxos/Baxos code, with unchanged row hashes, table dimensions, +field polynomial, bin assignment, pivot order, and single-thread PRNG +consumption. The Ribbon prototype is separate and was not changed. + +Changes +------- +- Remove the encoder's unused input-index mapping and its scattered writes. +- Keep 32-way remainder calculations in SIMD registers. Power-of-two + divisors use an exact mask; general divisors retain libdivide quotients. +- Evaluate the dense polynomial with Horner's rule: d field multiplies + instead of 2*d-1. Eight rows run together using AVX-512 VPCLMUL, AVX2 + VPCLMUL, or the existing block multiplication backend. Custom helpers + and matrix-valued elements retain the original generic implementation. +- Track the XOR of active row indices per column. Weight-one columns can + select their sole row without scanning stale adjacency entries. Keep + the existing weight-set order and gap handling. +- Reuse Paxos's owned arena when its capacity suffices. + +Correctness fixes found during validation +---------------------------------------- +Parallel randomized encoding previously passed the same mutable PRNG to +all workers. Workers now receive separately seeded PRNGs before launch. +Single-thread consumption is unchanged. Parallel randomized tables and +parent-PRNG consumption change from the previous racy implementation; +for a fixed thread count and seed they are now independent of scheduling. +The regression checks repeated encodes, parent state, and decoded values. + +The scalar hash row builder read a u64 at a four-byte offset through a +u64 pointer. Fixed-size memcpy loads retain the same bytes without the +alignment/aliasing violation. Scratch arenas now place pointer-aligned +span objects before narrower index arrays. This removes misalignment +for odd row counts without adding padding or changing table contents. + +Benchmark method +---------------- +Peach Ryzen 7950X, one thread pinned to CPU 2, GCC 15.2, -O3 -march=native, +2^20 keys, 128-bit values, bin target 2^14, weight 3, SSP 40, GF128 dense +columns. The resulting table has 1,411,712 cells and two dense columns +per bin. Fresh allocation and randomized free cells on every encode; +queries are half members and half independent keys. Eight trials, with +the first excluded from the reported median. All benchmarks, builds, +and tests take the shared volepsi, hypercat, and cat-blst locks. + +Timing includes initialization and output allocation for encoding, and +all hashing, binning, arithmetic, scattering, and scratch allocation / +destruction. Verification is outside timed regions. These are standalone +OKVS measurements, not PSI totals. No huge-page advice was added. + +Baseline executable and source snapshots are preserved. perf samples +identified dense decode, modular row construction, binning, and sparse +triangulation as the major costs. Raw profiles include setup overhead +and are diagnostic, not the source of reported wall timings. + +Reproduction +------------ +Working remote directory: /tmp/baxos-opt-20261115 +Dependencies: /tmp/volepsi-chosenbaa30-20261115 +Copy volePSI/, tests/Paxos_Tests.*, bench.cpp, tests.cpp, and peach.py to +that directory before running the following commands. The build links +the existing dependencies while compiling the edited template headers. + + python3 peach.py build --exe qualified + python3 peach.py bench --exe qualified --out qualified-after + python3 peach.py test --exe final-native-tests + python3 peach.py sanitize --exe final-sanitize-tests + python3 peach.py test --exe avx2-tests --isa avx2 + python3 peach.py test --exe scalar-tests --isa scalar + +The avx2 build disables AVX-512 and exercises two-lane VPCLMUL plus the +AVX2 remainder product. The scalar build forces the eight independent block evaluators +(128-bit PCLMUL on Peach). cryptoTools itself retains its configured +VPCLMUL requirements; the override affects only the new Baxos kernel. These +checks do not substitute for native ARM measurements. + +Next step +--------- +Rerun single-thread semi-honest PSI on Peach to measure the end-to-end gain. diff --git a/research/baxos/bench.cpp b/research/baxos/bench.cpp new file mode 100644 index 0000000..f6ea02d --- /dev/null +++ b/research/baxos/bench.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +#include +#include +using namespace volePSI; +using Clock=std::chrono::steady_clock; +double ms(Clock::time_point t) {return std::chrono::duration(Clock::now()-t).count();} +int main(int argc,char** argv) { + try { + unsigned logn=argc>1?std::stoul(argv[1]):20,trials=argc>2?std::stoul(argv[2]):8; + std::string mode=argc>3?argv[3]:"both"; + std::size_t n=std::size_t(1)< keys(n),values(n),queries(n),out(n); + input.get(keys.data(),n);input.get(values.data(),n);input.get(queries.data(),n); + std::copy_n(keys.data(),n/2,queries.data()); + std::cout<<"trial,n,m,dense,encode_ms,decode_ms\n"< cells(b.size());PRNG rng(oc::toBlock(trial+200)); + b.solve(keys,values,cells,&rng,1); + double enc=ms(t),dec=0; + if(mode!="encode") { + t=Clock::now();b.decode(queries,out,cells,1);dec=ms(t); + for(std::size_t i=0;i(queries,out,cells,1); + } + if(mode=="both") { + b.decode(keys,out,cells,1); + if(out!=values) throw std::runtime_error("member mismatch"); + } + std::cout<(cells.data()),cells.size()*sizeof(block)); + b.decode(queries,out,cells,1); + f.write(reinterpret_cast(out.data()),out.size()*sizeof(block)); + } + } + } catch(const std::exception& e) {std::cerr< +int main(int argc,char** argv) {try {oc::CLP cmd; cmd.parse(argc,argv); +Baxos_randomized_parallel_determinism_Test(cmd);std::cout<<"PASS Baxos_randomized_parallel_determinism_Test\n"<=t] + <= min(1, (N-1)*N^m / t!). +The statement quantifies over all tables and seeds, including choices made +after arbitrary cipher queries, inverse queries, or even complete disclosure. +It is an information-theoretic bound on effective-set size in this model. + +Proof + +First fix all permutations pi_j for j!=k. The remaining pi_k is a uniform +random permutation independent of these fixed permutations. Fix s!=k, P, +and a set T of t distinct inputs. Every x in T is a match exactly when + pi_k(x) = x + D_s(P,x). +The right-hand sides are now fixed. If two right-hand sides coincide, the +probability is zero, since a permutation cannot map distinct inputs to the +same output. Otherwise the probability is 1/(N)_t, where + (N)_t = N*(N-1)*...*(N-t+1). +There are binom(N,t) possible T. Thus the union bound for this s,P is + binom(N,t)/(N)_t = 1/t!. +There are N^m tables and N-1 admissible seeds. Union-bound over them, then +average over the previously fixed permutations. This proves the statement. +The union covers adaptive seed/table choices without conditioning on the +adversary's final choice. No permutation-to-random-function switch is used. + +Concrete consequence + +To bound failure by 2^-128, it suffices that + log2(t!) >= 128*m + 256. +We upper-bound N-1 by N here. The certified cap is t-1, not t. +verify_distinct_key_bound.py computes a conservative integer cap using + ln(t!) >= t*ln(t)-t+1 +and 80-digit arithmetic. The inequality follows by integrating the increasing +function ln(x) over [1,t]. The numerical bound includes a further full bit of +slack; the reported cap is not the tightest integer obtainable from t!. + +For the existing Baxos geometry at n=2^20, m=1,411,712, the script gives +a cap of 8,382,677 = 7.994344n, with log2 failure upper bound -131.3057. +Thus 8n is a convenient conservative rounded cap for this geometry. +This is an upper bound, not an attack reaching that size or an exact-n claim. +The old strong-extraction conjecture n'<=m is not needed for this bound. + +Why the earlier query-dependent ROM table is not automatically applicable + +AES_k(x)+x is a permutation followed by input XOR, not an independent random +function. Distinct AES keys isolate pi_k from the Baxos row permutation, but +they do not turn pi_k into a random function. For forward-only pi_k access +with at most q's +constructor. Equality is extraordinarily unlikely for an honest random seed, +but the check is required against a receiver that chooses its seed. + +For an admissible Ribbon seed, the derivation uses pi_s with s!=k. Every +actual row AES key also differs from k. Thus after fixing the entire +ideal-cipher family except pi_k, the Ribbon row function is fixed. The same +factorial proof above applies with Ribbon's m=columns. The test checks the +seed rule for widths selected at three sizes, while the existing Ribbon +protocol tests cover normal sessions. This is an ideal-cipher statement. +It does not establish a concrete-AES related-key theorem, the full OPRF +simulation, or a bound as tight as the old m-sized conjecture. No equivalent +universal-table attack on Ribbon is asserted. + +Relation to the papers + +The revised VOLE-PSI paper separates a generic random-oracle extraction bound +from Conjecture 2.1 asserting a stronger m-sized effective set (pp.11-12). +Han, Kim, Lee and Son show overfitting attacks against earlier claims and +discuss revised parameters and query budgets (sections 4-6). Seed exclusion +does not eliminate their overfitting phenomenon or prove that stronger claim. +The factorial lemma above is our separate ideal-cipher argument, not a result +attributed to either paper. + https://eprint.iacr.org/2021/266.pdf + https://eprint.iacr.org/2024/1989.pdf + +Reproduction + +RsOprf_seed_rejection_test constructs the universal table, runs a malicious +receiver with real VOLE, and checks the sender rejects before generating VOLE. +It covers one/multiple bins and both VOLE round modes. A neighboring seed +completes normally, but the same table fails to recover the probed outputs. +The mutation driver removes only the sender's seed check. The test then +verifies 2,003 matching OPRF outputs after declaring 257 inputs, before failing +with an explicit attack diagnostic. This is an end-to-end OPRF regression, +not just a test that two standalone hashes differ. + +Validation and performance + +65/65 native tests pass with the exclusion enabled. The targeted ASan+UBSan +suite passes the seed rejection, salt ordering, malicious OPRF and Ribbon +protocol tests. The sanitizer build retains the previously documented private +macoro/coproto fixes and the libOTe McRosRoy coroutine fix. It is not a claim +that unpatched dependency releases pass these checks. + +The mutation reproduces the extra evaluations and fails with the expected +diagnostic. Restoring the seed check passes all 65 tests again. Restoring the +old salt-opening order still fails its independent withholding-receiver test. + +Sequential Peach timings, n=2^20, ssp=40, malicious mode, both parties on CPU 2, +eight trials with trial zero excluded, median combined wall time: + Baxos: 490.597 ms (previous BLAKE2 implementation: 535.769 ms). + Ribbon: 455.286 ms (previous BLAKE2 implementation: 498.323 ms). +The old AES baseline was 493.163/457.069 ms; these runs are near that baseline. +Successful-session communication is identical: receiver 22,877,901 bytes for +Baxos or 21,262,038 for Ribbon; sender 16,864,109 bytes for either backend. +No new native ARM run was performed. AES uses the existing cryptoTools kernel. + +Logs and manifests: results/peach-20261116-distinct-key. Source bytes match the +restored regression manifest. The mutation driver normalizes RsOprf.cpp line +endings; the pre-mutation benchmark/sanitizer source differs only in CRLF/LF. +No PR was updated by this validation run. diff --git a/research/ribbon/EXTRACTION.txt b/research/ribbon/EXTRACTION.txt new file mode 100644 index 0000000..1a0e1be --- /dev/null +++ b/research/ribbon/EXTRACTION.txt @@ -0,0 +1,225 @@ +OKVS extraction bounds and implementation hardening (2026-11-15) + +Current decision (2026-11-16) + +The user selected AES labels with sender-side rejection of s=k for malicious +Baxos sessions. See DISTINCT_KEYS.txt for the current implementation, the +end-to-end attack regression, and an ideal-cipher extraction bound. The +BLAKE2 implementation below is historical and is no longer compiled. The +independent-random-oracle bounds below remain valid for that mathematical +model; they must not be silently assigned to the restored AES implementation. +No communication increase or wider labels were approved or implemented. + +Historical status: independent-label exploration + +No wider-label protocol has been implemented or selected. The executable +extraction_bounds.py reports a conservative trade-off for discussion. The +current hardening retains 128-bit labels and the same table/VOLE dimensions. +It changes malicious OPRF labels to a domain of cryptoTools RandomOracle, +independent of receiver-selected AES row hashing. It also defers the sender's +coin-flip opening until the complete correction table has arrived. +These changes apply to both Baxos and Ribbon. Semi-honest hashing is unchanged. +Both endpoints must upgrade together for malicious sessions; the label change +is not compatible with the previous malicious protocol. There is no negotiation. + +Why the original equal-key implementation fails + +Previously H(x) = AES_k(x) xor x for cryptoTools' public fixed key k. The +receiver chooses the Baxos seed s, and the first GF128 dense coefficient is +AES_s(x) xor x. The receiver can set s=k, set the first dense cell of every +bin to the field identity, and set all other cells to zero. Then Decode(P,x) += H(x) for every x, regardless of the declared set size. This is an algebraic +identity, not a generalized-birthday attack. The regression reproduces it +for one and many bins, then checks the independently hashed labels differ. +Replacing k with another public AES key, without a sender-side seed exclusion, +would leave the same attack available. Rejecting s=k is the current remedy; +the earlier BLAKE2 replacement was sufficient but not shown necessary. +The test establishes the identity and its removal; it is not a proof of the +random-oracle model for Blake2 or AES. No equivalent Ribbon identity is claimed. + +The old implementation also opened the final salt before receiving P xor C. +Extraction in the paper precedes that opening. The salt-order regression uses +a withholding receiver and checks that no opening arrives even when only the +last byte of the correction table is withheld, for both backends and both +round configurations. + +Game and bound + +Fix the declared set size n, the public OKVS geometry with m cells, and a +deterministic decoder for each s-bit seed. Let each cell contain L bits. +The decoder and row functions are independent of the label random oracle +H: {0,1}^128 -> {0,1}^L. The adversary may choose the seed and table adaptively +after at most q distinct H queries. All preprocessing queries count toward q. +Define X_eff as the queried keys x for which Decode(seed,P,x)=H(x). + +For any positive integer t <= q, + + Pr[|X_eff| >= t] <= min(1, 2^(s+Lm) binom(q,t) 2^(-Lt)). + +To justify the bound, fix the complete row functions, a seed and a table. +At each fresh label query the required decoding value is already determined, +and H's answer is independent and uniform. For any t query indices the +probability of t matches is 2^(-Lt), even with adaptive query selection. +Union-bound over index subsets, over all 2^(Lm) tables, and over 2^s seeds. +This covers adversarial tables, seed grinding, and arbitrary row dependencies. +It does not require random-band rank assumptions or independent dense columns. +The final union includes seeds chosen as a function of oracle answers. + +The script uses binom(q,t) <= (e*q/t)^t, yielding + + log2 Pr <= s+Lm+t*(log2(q)-L-log2(t)+log2(e)). + +It finds the first t with this upper bound <= -128 and reports t-1 as the cap. +Arithmetic uses 80 decimal digits, and small exact binomial examples verify +the relaxation. This is numerical evaluation of an analytic inequality, not +an exhaustive cryptographic security test. A simple independent certificate: +L=256, s=128, q<=2^128, and t=2m+2 give exponent <= -128 even using binom(q,t) +<= q^t. Thus the cap 2m+1 is available for every positive m in this model. + +Concrete trade-off + +For n=2^20 and the current ssp=40 geometries: + Ribbon: m=1,310,720 = 1.25n. + Baxos: m=1,411,712 = 1.3463134765625n. +Use s=128 and q<=2^128. The following cap/n values are rounded UP; the script +returns integer caps. L>128 rows describe candidate wider-value constructions, +not current protocol implementations or measured performance. + + L bits payload/VOLE blocks per cell Ribbon cap/n Baxos cap/n + 128 1 7.458 7.995 + 256 2 2.167 2.333 + 384 3 1.744 1.877 + 512 4 1.588 1.710 + 640 5 1.507 1.622 + 1024 8 1.399 1.507 + 1280 10 1.367 1.472 + +For smaller query budgets with L=128, the same calculation gives: + log2(q)=64: Ribbon <1.917n, Baxos <2.062n. + log2(q)=96: Ribbon <3.067n, Baxos <3.297n. + log2(q)=100: Ribbon <3.314n, Baxos <3.562n. + +These are conservative upper bounds, not demonstrated attack costs. Increasing +L reduces generic extraction slack but cannot take this argument below m. +With the current geometries that limiting floor is 1.25n or 1.3464n. Exact-n +enforcement needs a different argument or additional protocol machinery. + +A query budget of 2^128 and extraction failure 2^-128 do NOT mean the entire +128-bit protocol has that failure probability at that budget. VOLE, delta +guessing, final-output hashing, commitment binding, and computational hash +instantiation have their own advantages. This document only bounds overfitting. + +For a wider-value implementation, the label must actually contain L independent +RO bits, the table must encode all of them, and final OPRF evaluation must bind +all decoded lanes. Expanding a 128-bit digest or discarding lanes before the +final hash does not establish this game. Independent lanes can share elimination +and row generation. Payload/VOLE multipliers above are not wall-time multipliers. +The full protocol reduction and its final combiner still require review. + +The known attacks and the generic upper bound leave a gap. Historical PaXoS, +RR22 and RB-OKVS attack estimates must not be assigned to this implementation +without checking its binning, dense powers, band widths and hash model. Merely +raising rank-failure security or the band width does not prove a tighter cap. + +Sources + +Rindal and Schoppmann, VOLE-PSI, revised 2024-08-08, p.11 equation (1), p.12 +Conjecture 2.1: https://eprint.iacr.org/2021/266 +Han, Kim, Lee and Son, Revisiting OKVS-based OPRF and PSI, ASIACRYPT 2024, +especially section 5: https://eprint.iacr.org/2024/1989 +Our bound adds an explicit union over receiver-selected 128-bit seeds. + +Next decision: retain 128-bit independent labels with a documented loose cap, +or prototype L=256 as the first wider-value point and measure its end-to-end +cost. Do not promise an exact-n guarantee for either option. + +Validation and cost of the current reference patch + +65/65 native tests pass. Reintroducing the old salt order makes its dedicated +test fail; restoring the old label function makes the domain test fail. +The final source hashes match the files used for native timings and sanitizers. + +Sequential Peach runs, n=2^20, ssp=40, malicious mode, both parties on CPU 2, +eight trials each with trial zero excluded; median combined wall time: + Baxos: 493.163 ms before, 790.597 ms after. + Ribbon: 457.069 ms before, 766.027 ms after. +Communication is identical before/after. These are combined two-party times, +not per-party latencies. The per-key Blake2 label implementation is a costly +correctness reference and needs a separate batching/performance pass. No +wider-value candidate was benchmarked; L is still 128. + +The ASan+UBSan label-domain test passes, but the salt-order test then crashes +inside McRosRoy base OT at McRosRoy.h:267 (Point::mulGenerator). The root cause +has not been established. This is not a successful sanitizer validation and +the patch is not declared merge-ready. The existing macoro/coproto private +include fixes from integration_peach.py were active, with no checks disabled. + +Raw logs, mutation failures, source hashes, bounds and timings are under +results/peach-20261115-extraction. The original diagnostic is +hardening-sanitize.txt. No PR has been updated with this reference patch. +Next implementation work: resolve the sanitizer failure and batch a standard +independent label hash before choosing whether wider labels are worthwhile. + +Hash optimization and alignment fix (completed 2026-11-16) + +This section supersedes the reference patch's performance and sanitizer status +above. Label width remains 128 bits. The user has not approved any increase in +communication: message sizes, VOLE count and table geometry are unchanged. +Both endpoints must use the independent label function introduced above. + +RsOprfHash.cpp specializes standard BLAKE2b-128 for the fixed domain and 16-byte +key. It retains all twelve rounds and exactly matches the scalar RandomOracle +reference. It batches independent hashes in eight AVX-512, four AVX2, or two +ARM NEON lanes, with the scalar reference as the portable fallback. There is +no heap allocation or runtime dispatch in the kernel. A non-inlined ordinary +function keeps aligned SIMD scratch outside the OPRF coroutine frame. + +Sequential Peach runs use the same n=2^20, ssp=40, malicious mode, CPU 2 and +eight-trial protocol as the reference measurements above. Trial zero is +excluded. Median combined wall time for both parties: + old AES scalar independent hash batched hash + Baxos 493.163 ms 790.597 ms 535.769 ms + Ribbon 457.069 ms 766.027 ms 498.323 ms +The batched implementation is 32.2%/34.9% faster than the scalar hardening +reference. It remains 8.6%/9.0% slower than the old unsafe AES label baseline. +These are combined two-party measurements, not per-party latency estimates. +Sent bytes match all three implementations exactly: + Baxos receiver 22,877,901; Ribbon receiver 21,262,038; sender 16,864,109. +No wider-label candidate was implemented or benchmarked. + +The McRosRoy crash was an aligned AVX-512 load from a point temporary whose +address was only 32-byte aligned in a coroutine. GDB captured the faulting +vmovdqa64 instruction. The libOTe fix moves receiver point preparation, point +decoding/multiplication, sender generator encoding and sender derivation into +non-inlined ordinary helpers. PRNG order, wire encoding and batched arithmetic +are preserved; owned byte/scalar vectors survive coroutine suspensions. + +Validation: 66/66 native tests; targeted ASan+UBSan label, salt-order, malicious +OPRF and Ribbon protocol tests; AVX2 and portable hash/Ribbon fallback checks. +Both MRR POPF variants additionally pass ASan+UBSan for thirteen sizes from +zero through 128, mismatched choice/output spans and malformed point messages. +The sanitizer run still needs the private macoro/coproto include fixes described +in INTEGRATION.txt. Checks were not disabled. Those dependency fixes have not +yet been carried into their repositories; this is not a clean-dependency CI +claim. The timed native builds use the MRR fix but not those two overlays. + +The production AVX2 and NEON kernels also match 20,003 independent Python +hashlib vectors, tails, guard cells and in-place calls. NEON ran under QEMU, +not on a Mac. Fallback checks use native x86 dependency libraries and are not +whole-stack portability claims. Logs, build commands, source hashes and the +MRR diagnostic are in results/peach-20261115-hash-opt. Its summary distinguishes +the old AES baseline, scalar hardening reference and final batched hash. + +Salt decision: keep the existing salt and open it only after receiving the +entire correction table. The salt does not prevent overfitting. Its late +opening prevents a receiver from inspecting would-be OPRF outputs and choosing +its batch input set based on those outputs. The simulator in VOLE-PSI's revised +proof (eprint 2021/266, p.17) extracts the input set and obtains ideal outputs +before sampling/opening w and programming the final oracle. Removing the salt +needs a different argument, potentially for PSI specifically; the current +batch OPRF proof does not justify that removal. + +Next: carry the dependency lifetime fixes into the existing PRs and review the +full extraction reduction. Discuss a concrete communication/security tradeoff +with the user before implementing any wider labels. No label-width decision +or exact-n extraction claim follows from the optimization results. diff --git a/research/ribbon/INTEGRATION.txt b/research/ribbon/INTEGRATION.txt new file mode 100644 index 0000000..4dee195 --- /dev/null +++ b/research/ribbon/INTEGRATION.txt @@ -0,0 +1,162 @@ +Ribbon integration into volePSI (2026-11-15) + +Current hash decision (2026-11-16): AES labels are restored. Malicious Baxos +rejects the seed equal to the fixed label AES key. See DISTINCT_KEYS.txt for +the attack test and the scope of the ideal-cipher extraction argument. The +BLAKE2 timings at the end of this file are historical. The sender also validates Ribbon's derived row keys before VOLE; see DISTINCT_KEYS.txt for the extended argument. Communication is unchanged. + +The implementation is selectable through RsOprfSender/Receiver and +RsPsiSender/Receiver with setOkvsType(OkvsType::Ribbon). File PSI, the +network/message-passing examples, and the PSI benchmark accept -okvs ribbon. +Both parties must select the same backend and statistical parameter. There is +no backend negotiation. Baxos remains the default during this exploration; +its existing wire format is unchanged. ChosenBAA30 remains the VOLE encoder. + +The public RibbonOkvs API handles block payloads and arbitrary query keys. +It reads and writes exactly size() table cells, including when decoding the +external Silent VOLE arrays. It does not copy those arrays or require SIMD +padding. Width dispatch happens once per operation. The AVX-512/GFNI kernels +retain the optimized batched table sharing; other targets use the portable +block-XOR path. SIMD scratch lives in non-inlined ordinary functions. +Encoding is single-threaded; decoding partitions sufficiently large query +batches across the requested number of threads. Decode input/output buffers +must not overlap. A separate ISA performance pass remains useful before +choosing defaults on machines without AVX-512/GFNI. + +Parameter selection and failure + +RibbonParams::select(n, ssp) selects a concrete witness for the bound in +proof.txt, retaining two additional bits beyond ssp. It prefers 25% table +overhead, with compiled widths 64, 128, 256, 512 and 1024. For intermediate +sizes/high security it enlarges the table when necessary. Small sets use a +single dense random band with rank-failure bound less than 2^(n-width). +Unsupported index ranges or unattainable targets throw explicitly. + +For n=2^20 and ssp=40, selection gives m=1,310,720, width=128 and a witness +certifying about 45.46 bits. The finer research search certifies 46.97 bits +for the same geometry. These are upper bounds on failure, not measured failure +rates. The assumptions are distinct keys fixed independently of the seed, +uniform starts, and independent uniform coefficient bits. The numerical +verification does not prove an AES-to-ideal-hash reduction. + +The API returns false on rank deficiency, including duplicate rows. OPRF +uses zero free cells, matching its existing Baxos call; standalone solve can +also randomize free cells. On rank failure the parties finish the already +started VOLE, exchange a one-byte status before the correction table, and +both throw. There is no seed retry or conditioning on a successful seed. +Successful Ribbon sessions therefore add one status byte to the transcript. + +This replaces the OPRF's block-valued OKVS and thereby integrates with PSI. +It does not replace the separate variable-width programmed table in OPPRF +or the unrelated PSI intersection hash table. The former still uses Baxos. + +Validation and reproduction + +The registered tests check zero/random free cells, independent scalar +decoding including nonmembers, linearity, tail and single-key queries, +unpadded external tables, parallel decode, duplicate-row rank failure, +semi-honest/malicious PSI, both round configurations, asymmetric set sizes, +and reuse across table shapes. The failure test requires both OPRF tasks to +return the expected error. The parameter driver exports witnesses; the +independent verify_integration_params.py recomputes them at 80 decimal digits. + +The isolated Peach tree is /tmp/volepsi-ribbon-integration-20261115, with +source in src and a fresh CMake build in build. It uses the qualified libOTe +and cryptoTools install under /tmp/volepsi-chosenbaa30-20261115, and the deps +prefix from that tree. integration_peach.py acquires all three shared host +locks for builds, tests and benchmarks. All benchmarks run sequentially. + +The integration benchmark compares both backends in the same executable, +uses actual base OTs and fresh protocol objects each trial, checks a known +nonempty intersection, and reports synchronous encode/decode intervals. +Both parties execute on one pinned CPU (CPU 2); wall_both_ms is the combined +two-party wall time, not a per-party timing or a two-core latency claim. +Eight trials are run and trial zero is discarded when reporting medians. +The same input sets, seeds, security, thread count, VOLE backend, and normal +VOLE/output allocation policy are used for both backends. Ribbon scratch +allocations retain its Linux transparent-huge-page advice. + +Commands (on Peach, from the isolated tree): + python3 src/research/ribbon/integration_peach.py build + python3 src/research/ribbon/integration_peach.py test + python3 src/research/ribbon/integration_peach.py regression + python3 src/research/ribbon/integration_peach.py params + python3 src/research/ribbon/integration_peach.py sanitize + python3 src/research/ribbon/integration_peach.py avx2 + python3 src/research/ribbon/integration_peach.py portable + python3 src/research/ribbon/integration_peach.py bench --backend baxos --name baxos-sh + python3 src/research/ribbon/integration_peach.py bench --backend ribbon --name ribbon-sh + +Use --malicious 1 for the malicious benchmark. Build/test logs, binary/source +hashes, CPU/frequency metadata and raw measurements are kept with the results. + +Measured results (Peach, CPU 2, n=2^20, ssp=40) + +Medians of trials 1-7, in milliseconds: + Baxos Ribbon + Semi-honest combined wall 449.600 421.093 + Malicious combined wall 495.234 458.036 + SH receiver encode 71.309 48.211 + SH receiver decode 23.051 31.335 + SH sender decode 21.848 26.668 + Malicious receiver encode 71.405 48.411 + Malicious receiver decode 26.738 26.388 + Malicious sender decode 22.968 24.671 + +Ribbon improves combined wall time by 6.3% in SH and 7.5% in malicious +mode. It sends 1,615,863 fewer receiver bytes (about 1.54 MiB) per session +in both modes. The sender traffic is unchanged in these runs. Its table +contains 1,310,720 cells versus Baxos's 1,411,712 cells. + +The standalone encode advantage survives integration, but some decode +advantage does not. A controlled production-decoder comparison with +identical table contents and queries measures 24.305 ms with ordinary table +allocation versus 20.698 ms with an aligned, huge-page-advised allocation. +Outputs match in all 32 runs. This accounts for part of the gap; it does +not establish that page allocation explains all end-to-end decode variance. +Do not substitute the advised-buffer result for actual PSI decode timings. + +Validation completed: 63/63 native tests, the Ribbon fallback compiled +without AVX-512, the malicious reduced-round buffered-socket example, +and 70 parameter witnesses recomputed with 80-digit arithmetic. No native +Mac/ARM run was performed. The fallback check uses the existing native +x86 dependency libraries; it is not a whole-stack ARM compatibility claim. + +Full Ribbon OPRF/PSI ASan+UBSan tests pass with two narrowly scoped fixes +in a private test include overlay. Unmodified dependencies trigger vptr +checks before Ribbon protocol work can finish: + * macoro tasks_size was non-static and invoked before the base constructor; + making this object-independent helper static removes that lifetime error. + * coproto InlinePoly downcast raw storage to ModelController before its + construction; construct in mStorage and use the placement-new result. +Neither sanitizer checks nor recovery-on-error settings were relaxed. +The shared dependency installation and timed native binaries were not +modified. Both proposed patches and the original diagnostics are retained +in results/peach-20261115-integration; these fixes still need to be carried +into the dependency repositories. + +Raw runs, build/source hashes and summary.json are in that results directory. +The complete log archive is out/ribbon-integration/results.tgz; its SHA-256 +is recorded in archive-sha256.txt. The local production/test source hashes +were checked against the native build manifest. + +Recommendation: Ribbon is a useful opt-in now and a reasonable candidate +for the PSI default. Next, carry the two small lifetime fixes upstream and +improve allocation of the actual VOLE tables, then remeasure before changing +the default. Preserve Baxos as an explicit backend for comparisons and for +platforms whose Ribbon decode performance has not yet been measured. + +Extraction follow-up (2026-11-15): see EXTRACTION.txt before interpreting +malicious security. The rank-failure certificate above is not an extraction +certificate. The malicious label hash and salt-opening order have since been +hardened for both backends; both endpoints must upgrade together. Label width +remains 128 bits pending the extraction-cap/performance decision. Historical +timings above precede that hardening. Wider-label bounds in EXTRACTION.txt are +candidate constructions, not claims about the existing implementation. + +The follow-up hash optimization and McRosRoy coroutine alignment fix now pass +66 native tests and targeted sanitizer checks (with the two private dependency +fixes above). Batched independent labels give malicious combined wall medians +of 535.769 ms for Baxos and 498.323 ms for Ribbon at n=2^20 on one Peach CPU. +Communication remains unchanged. See EXTRACTION.txt and +results/peach-20261115-hash-opt for the comparison and validation limits. diff --git a/research/ribbon/README.txt b/research/ribbon/README.txt new file mode 100644 index 0000000..4d42da7 --- /dev/null +++ b/research/ribbon/README.txt @@ -0,0 +1,199 @@ +Ribbon OKVS optimization -- 2026-11-15 +===================================== + +Result +------ +Encoding is 41-43% faster than the first Ribbon prototype. Full decoding +is approximately unchanged. The matrix distribution and output format are +unchanged. Differential tests produce byte-for-byte identical tables, +including randomized free cells. + +Peach, one thread pinned to CPU 2, 2^20 keys, 128-bit values: + + Profile Previous encode New encode New decode + width 128, 1.25*n 76.10 ms 44.88 ms 26.09 ms + width 112, 1.30*n 74.32 ms 43.67 ms 24.75 ms + width 80, 1.40*n 71.77 ms 40.75 ms 23.37 ms + +Previous decode medians were 26.59, 24.93, and 23.28 ms respectively. +The preserved Baxos executable remains approximately 104 ms to encode +and 34-36 ms to decode. These are standalone OKVS timings, not PSI totals. + +The defaults request transparent huge pages for large owned buffers. +Peach has THP configured for madvise; the live width-128 output buffer +reported 20480 KiB of huge pages. No global system setting was changed. +Correctness does not depend on acceptance of the advice. With huge-page +advice disabled, encode/decode medians are: + width 128: 62.56 / 26.91 ms + width 112: 61.29 / 25.80 ms + width 80: 58.95 / 23.47 ms +The larger gain on Peach includes reduced page-fault and translation +costs; it should not be attributed entirely to arithmetic improvements. + +Measurement conditions +---------------------- +All benchmarks ran sequentially under shared volePSI, hypercat, and +cat-blst locks. Builds and tests now acquire those locks too. Final +figures are medians of seven trials after one warmup, using GCC 15.2, +-O3 and -march=native. Output and workspace are freshly allocated on +every encode. Totals include hashing, sorting, randomization, solving, +and workspace destruction. Decode includes restoring query order. + +Inputs are fixed random keys and values. Matrix and free-cell seeds +change each trial. Queries are half members and half independent keys. +Every encode is checked on all members outside the timed region. Timed +decodes check all member answers and sampled scalar nonmember answers. +Only the selected sorted decoder runs in each final-confirmation process. +Baxos runs before and after each sweep using its preserved executable. +Recompiling the shared harness was observed to change Baxos encode +performance despite unchanged Baxos source, so that was not used as the +final baseline. + +Selected changes +---------------- +- Fuse coefficient generation with elimination. Retain only normalized + masks in row order and keep each pivot value in the output table. + At width 128, per-row scratch shrinks from 32 to 16 bytes. +- Avoid initializing temporary arrays that will be overwritten. Random + output cells and padding are still explicitly initialized. +- Align large buffers and request transparent huge pages on Linux. + The ordinary-page configuration is also tested and measured. +- Expand masks with PDEP and use masked AVX-512 XORs with memory operands. + Back substitution uses exact-width 16-byte loads for its first four + cells, which can forward recent stores. +- Count both radix digits in one scan with 32-bit histograms, preserving + stable ordering, including the original order of equal-start rows. + +Defaults: RIBBON_DOT=2, RIBBON_HUGE_PAGES=1, RIBBON_FORWARDING=1, +RIBBON_RADIX_BITS=11, RIBBON_BATCH=8, RIBBON_DIRECT_PIVOTS=0. +Larger batches, direct column-indexed masks, a smaller radix, and an +exact reciprocal remainder calculation did not improve the selected +workload. The reciprocal calculation was removed; the other kernel +choices remain available for controlled experiments. + +Width-128 stage medians, milliseconds: + initialization and random output 2.31 + hash starts 1.90 + sort indices 4.59 + fused coefficient generation and elimination 22.84 + back substitution 13.24 + encode wall total 44.88 + decode allocation 0.01 + decode start hashing 2.09 + decode sorting 4.51 + coefficient hashing, evaluation, output scatter 19.51 + decode wall total 26.09 +Stage medians need not sum exactly to the median total. Fused elimination +includes first-touch memory costs. Decode still has substantial sorting +and scattered input/output costs. + +Validation and scope +-------------------- +Native and ASan/UBSan tests passed. Coverage includes partial batches, +partial words, scalar/SIMD agreement, duplicate-row rank failure, and +large allocations crossing the huge-page threshold. Differential tests +compare every output cell with the preserved encoder at widths 80, 112, +128, and 192 and n=17, 513, and 131075. They pass natively and with +ASan/UBSan. All large benchmark correctness checks passed. + +proof.txt and parameters.json retain the one-attempt rank bounds under +ideal independent random starts and coefficient bits: + width 128, 25% overhead: < 2^-46.97448 + width 112, 30% overhead: < 2^-48.76238 + width 80, 40% overhead: < 2^-42.67122 +These bounds do not complete the AES-instantiation or adaptive/malicious +PSI/OPRF audit. This is an AVX-512 research OKVS over 128-bit values, +separate from the ChosenBAA30 VOLE code. + +Reproduction and artifacts +-------------------------- +Remote directory: /tmp/ribbon-okvs-20261115/research/ribbon +Dependencies: /tmp/volepsi-chosenbaa30-20261115 + + python3 peach.py build --exe qualified --wait-lock 60 + python3 peach.py test --exe qualified --wait-lock 60 + python3 peach.py sanitize --wait-lock 60 + python3 peach.py differential-sanitize --wait-lock 60 + python3 peach.py bench --exe qualified --quick --sorted-only --trials 8 --out optimized-final --wait-lock 60 + +Build the fallback with --huge-pages 0 and a separate --exe name. +The baseline executable is optimization-baseline/bench. Differential +tests verify the preserved header's SHA-256 before generating its copy. +Each build saves source snapshots, its command, and source hashes. +Metadata records the tested executable and preserved baseline hashes. + +results/peach-20261115-optimized contains final CSVs, stage summaries, +metadata, huge-page observations, and validation results. Those manifests identify the encoder-optimization source snapshots; +the batched-decoder measurements below identify the current sources. +results/peach-20261115 retains the initial prototype measurements. +Exploration logs and source snapshots are archived locally in +out/ribbon-optimize-20261115/results.tgz; the initial prototype archive +is out/ribbon-review-20261115/results.tgz. + +Batched decoding (2026-11-15, subsequent pass) +------------------------------------------- +Order::shared evaluates eight nearby sorted queries together with AVX-512 +GFNI and VBMI. Every eight source table cells are converted into sixteen +8x8 binary matrices. Two GFNI operations apply those matrices to all eight +queries at once. The row coefficients and decoded values are unchanged. + +A mirrored rolling cache retains converted cells between neighboring +batches. At the primary widths it occupies 4 or 8 KiB on the stack, with +no extra table allocation. Each source cell is converted at most once +per decode. Queries too far apart, partial batches, and widths below 32 use the +previous SIMD dot product. The narrow-width fallback keeps the wider +GFNI loads within the existing padding contract. Builds without GFNI/VBMI use the previous sorted path. +This remains an AVX-512 research prototype, not a portable PSI backend. + +Peach, one thread pinned to CPU 2, 2^20 keys and queries, identical seeds +and workload, eight trials with trial zero excluded; medians in ms: + + width / overhead preserved sorted new shared reduction + 128 / 25% 24.86 21.14 14.9% + 112 / 30% 24.77 21.72 12.3% + 80 / 40% 23.23 21.28 8.4% + +All times include allocation/destruction, start hashing, sorting, +coefficient hashing, table conversion, evaluation, and output scatter. +No precomputed table or prepared query state is excluded from timing. +Before the final narrow-width guard, the old sorted path in the same +executable measured 25.10, 24.79, and 23.12 ms. The shared path in that +build measured 21.06, 21.58, and 20.53 ms. The table above uses the final +qualified build; earlier compiler/layout-sensitive results are retained +in the raw data. Encoding is unchanged and remains about +45, 44, and 41 ms. Runs, builds, and checks were serialized using all +three shared benchmark locks. Huge-page hints were enabled as before. + +The shared evaluation stage (including coefficient hashing, conversion, +and scatter) measured 16.22, 15.13, and 14.71 ms. Width-128 sorting now +measured 2.54 ms instead of the prior pass's 4.51 ms; the preserved binary +shows the same allocation-sensitive change, so the comparison above uses +fresh baseline measurements rather than claiming that as a decoder win. + +Rejected experiments: ordinary masked-XOR groups of two, four, or eight +queries; additional accumulators; quarter-sized query tiles; and a full +converted table. The rolling GFNI implementation was the consistent win. +The old decoder modes remain available; rejected new paths were removed. + +Reproduce the selected path: + python3 peach.py build --exe batched-qualified --wait-lock 60 + python3 peach.py test --exe batched-qualified --wait-lock 60 + python3 peach.py bench --exe batched-qualified --quick --ribbon-only --shared-only --trials 8 --out batched-qualified-results --wait-lock 60 + python3 peach.py bench --exe batched-final --quick --ribbon-only --sorted-only --trials 8 --out batched-same-binary-sorted --wait-lock 60 + +Native tests cover all coefficient positions, offsets 0 through 32, +partial words/batches, sparse fallback, members, and scalar nonmembers. +Differential tests compare every encoded cell and every decoded member +and independent nonmember against the preserved implementation, including +262147-element inputs that exercise many ring wraps and huge buffers. +Native and ASan/UBSan tests, including the differential comparisons, +passed. The AVX-512 build without GFNI/VBMI is checked separately with +--no-gfni. Validation logs and raw benchmark data are under +results/peach-20261115-batched. Source snapshots and exploration results +are archived in out/ribbon-batched-20261115/results.tgz. + +Recommended next step +--------------------- +Reduce the remaining coefficient-hashing and output-scatter costs. +Keep PSI integration separate until its protocol proof obligations +are audited. diff --git a/research/ribbon/Ribbon.h b/research/ribbon/Ribbon.h new file mode 100644 index 0000000..f2aa10d --- /dev/null +++ b/research/ribbon/Ribbon.h @@ -0,0 +1,557 @@ +#pragma once + +// Experimental random-band OKVS. The rank bound assumes ideal independent +// start/coefficient functions; this AES instantiation is for benchmarking. +// Rows have fully random coefficients, including the leading bit. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef __linux__ +#include +#endif + +namespace ribbon { +#ifndef RIBBON_DOT +#define RIBBON_DOT 2 +#endif +#ifndef RIBBON_HUGE_PAGES +#define RIBBON_HUGE_PAGES 1 +#endif +#ifndef RIBBON_FORWARDING +#define RIBBON_FORWARDING 1 +#endif +#ifndef RIBBON_RADIX_BITS +#define RIBBON_RADIX_BITS 11 +#endif +#ifndef RIBBON_BATCH +#define RIBBON_BATCH 8 +#endif +#ifndef RIBBON_DIRECT_PIVOTS +#define RIBBON_DIRECT_PIVOTS 0 +#endif +// Large scratch buffers are aligned for optional transparent huge pages. +// Default construction deliberately leaves trivial elements uninitialized; +// every read is preceded by an explicit write. No global VM setting changes. +template struct BufferAllocator { + using value_type=T; + BufferAllocator()=default; + template BufferAllocator(const BufferAllocator&) noexcept {} + static std::size_t alignment(std::size_t bytes) { + return RIBBON_HUGE_PAGES && bytes>=2*1024*1024 ? 2*1024*1024 : std::max(16,alignof(T)); + } + T* allocate(std::size_t n) { + if(n>std::size_t(-1)/sizeof(T)) throw std::bad_array_new_length(); + auto bytes=n*sizeof(T),align=alignment(bytes); + auto p=static_cast(::operator new(bytes,std::align_val_t(align))); +#if defined(__linux__) && RIBBON_HUGE_PAGES + if(align==2*1024*1024) (void)madvise(p,bytes/(2*1024*1024)*(2*1024*1024),MADV_HUGEPAGE); +#endif + return p; + } + void deallocate(T* p,std::size_t n) noexcept {::operator delete(p,std::align_val_t(alignment(n*sizeof(T))));} + template void construct(U* p,Args&&... args) { + if constexpr(sizeof...(Args)==0) ::new(static_cast(p)) U; + else ::new(static_cast(p)) U(std::forward(args)...); + } + template bool operator==(const BufferAllocator&) const noexcept {return true;} +}; +template using Buffer=std::vector>; +using oc::block; +using Clock = std::chrono::steady_clock; +inline double elapsed(Clock::time_point t) { + return std::chrono::duration(Clock::now()-t).count(); +} +struct Timings { + double init=0, starts=0, sort=0, coefficients=0, eliminate=0, backsolve=0, total=0; + std::uint64_t additions=0; +}; +struct Entry { std::uint32_t start, index; }; +enum class Order { sorted, bucket, direct, preparedSorted, preparedBucket, shared }; + +template +[[gnu::noinline]] inline void orderEntries(std::vector& entries, Order mode) { + if(mode==Order::direct) return; + std::vector temp(entries.size()); + if(mode==Order::bucket) { + std::uint32_t max=0; + for(auto e:entries) max=std::max(max,e.start>>12); + std::vector count(max+1); + for(auto e:entries) ++count[e.start>>12]; + std::size_t sum=0; + for(auto& c:count) { auto old=c; c=sum; sum+=old; } + for(auto e:entries) temp[count[e.start>>12]++]=e; + entries.swap(temp); + return; + } + // Small radix buckets keep active scatter destinations in L1. + std::uint32_t max=0; + for(auto e:entries) max=std::max(max,e.start); + constexpr unsigned buckets=1u< low{},high{}; + for(auto e:entries) {++low[e.start&2047];++high[e.start>>11];} + std::uint32_t a=0,b=0; + for(unsigned j=0;j<2048;++j) { + auto x=low[j],y=high[j];low[j]=a;high[j]=b;a+=x;b+=y; + } + for(auto e:entries) temp[low[e.start&2047]++]=e; + for(auto e:temp) entries[high[e.start>>11]++]=e; + return; + } + } + for(unsigned shift=0;shift<32 && (max>>shift);shift+=RIBBON_RADIX_BITS) { + std::array count{}; + for(auto e:entries) ++count[(e.start>>shift)&(buckets-1)]; + std::size_t sum=0; + for(auto& c:count) { auto old=c;c=sum;sum+=old; } + for(auto e:entries) temp[count[(e.start>>shift)&(buckets-1)]++]=e; + entries.swap(temp); + } +} + +template struct Mask { + static_assert(W && W % 16 == 0); + static constexpr unsigned words=(W+63)/64; + std::array v; + bool empty() const { + std::uint64_t z=0; + #pragma GCC unroll 16 + for(unsigned i=0;i>bits)|(v[i+1]<<(64-bits)); + v[words-1]>>=bits; + } + return whole+bits; + } +}; + +inline block reduce(__m512i x) { + auto lo=_mm256_xor_si256(_mm512_castsi512_si256(x), _mm512_extracti64x4_epi64(x,1)); + return block(_mm_xor_si128(_mm256_castsi256_si128(lo),_mm256_extracti128_si256(lo,1))); +} +template inline block dot(const Mask& mask, const block* cells) { + static constexpr unsigned char lane[16]={0,3,12,15,48,51,60,63,192,195,204,207,240,243,252,255}; + __m512i a=_mm512_setzero_si512(), b=a, c=a, d=a; + #pragma GCC unroll 16 + for(unsigned k=0;k::words;++k) { + auto bits=mask.v[k]; +#if RIBBON_DOT == 2 + #pragma GCC unroll 2 + for(unsigned half=0;half<2 && k*64+half*32>(half*32),0x5555555555555555ULL); + auto masks=spread|(spread<<1); + #pragma GCC unroll 2 + for(unsigned j=0;j<32 && k*64+half*32+j>(2*j)),a,_mm512_loadu_si512(p)); + b=_mm512_mask_xor_epi64(b,__mmask8(masks>>(2*j+8)),b,_mm512_loadu_si512(p+4)); + c=_mm512_mask_xor_epi64(c,__mmask8(masks>>(2*j+16)),c,_mm512_loadu_si512(p+8)); + d=_mm512_mask_xor_epi64(d,__mmask8(masks>>(2*j+24)),d,_mm512_loadu_si512(p+12)); + } + } +#else + #pragma GCC unroll 4 + for(unsigned j=0;j<64 && k*64+j>j)&15],a,_mm512_loadu_si512(cells+k*64+j)); + b=_mm512_mask_xor_epi64(b,lane[(bits>>(j+4))&15],b,_mm512_loadu_si512(cells+k*64+j+4)); + c=_mm512_mask_xor_epi64(c,lane[(bits>>(j+8))&15],c,_mm512_loadu_si512(cells+k*64+j+8)); + d=_mm512_mask_xor_epi64(d,lane[(bits>>(j+12))&15],d,_mm512_loadu_si512(cells+k*64+j+12)); +#else + a=_mm512_xor_si512(a,_mm512_maskz_loadu_epi64(lane[(bits>>j)&15],cells+k*64+j)); + b=_mm512_xor_si512(b,_mm512_maskz_loadu_epi64(lane[(bits>>(j+4))&15],cells+k*64+j+4)); + c=_mm512_xor_si512(c,_mm512_maskz_loadu_epi64(lane[(bits>>(j+8))&15],cells+k*64+j+8)); + d=_mm512_xor_si512(d,_mm512_maskz_loadu_epi64(lane[(bits>>(j+12))&15],cells+k*64+j+12)); +#endif + } +#endif + } + auto result=reduce(_mm512_xor_si512(_mm512_xor_si512(a,b),_mm512_xor_si512(c,d))); + if constexpr(Forwarding && RIBBON_DOT==2) { + // Exact-width loads can forward the most recent 16-byte stores. + // A 64-byte load overlapping those stores incurs a forwarding stall. + __m128i prefix=_mm_setzero_si128(); + #pragma GCC unroll 4 + for(unsigned j=0;j<4;++j) + prefix=_mm_mask_xor_epi64(prefix,__mmask8(((mask.v[0]>>j)&1)*3),prefix, + _mm_loadu_si128(reinterpret_cast(cells+j))); + result^=block(prefix); + } + return result; +} +#if defined(__GFNI__) && defined(__AVX512VBMI__) +// Transpose each 8x8 bit matrix within its 64-bit lane. GFNI numbers +// matrix rows in reverse byte order, so reverse the bytes after transposing. +inline __m512i gfniMatrix(__m512i x) { + auto t=_mm512_and_si512(_mm512_xor_si512(x,_mm512_srli_epi64(x,7)),_mm512_set1_epi64(0x00aa00aa00aa00aaULL)); + x=_mm512_xor_si512(x,_mm512_xor_si512(t,_mm512_slli_epi64(t,7))); + t=_mm512_and_si512(_mm512_xor_si512(x,_mm512_srli_epi64(x,14)),_mm512_set1_epi64(0x0000cccc0000ccccULL)); + x=_mm512_xor_si512(x,_mm512_xor_si512(t,_mm512_slli_epi64(t,14))); + t=_mm512_and_si512(_mm512_xor_si512(x,_mm512_srli_epi64(x,28)),_mm512_set1_epi64(0x00000000f0f0f0f0ULL)); + x=_mm512_xor_si512(x,_mm512_xor_si512(t,_mm512_slli_epi64(t,28))); + return _mm512_shuffle_epi8(x,_mm512_set4_epi64(0x08090a0b0c0d0e0fULL,0x0001020304050607ULL,0x08090a0b0c0d0e0fULL,0x0001020304050607ULL)); +} +inline void gfniTableChunk(const block* cells,block* result) { + alignas(64) std::array low,high; + for(unsigned byte=0;byte<8;++byte) for(unsigned q=0;q<8;++q) { + low[byte*8+q]=q*16+byte;high[byte*8+q]=q*16+byte+8; + } + auto il=_mm512_load_si512(low.data()),ih=_mm512_load_si512(high.data()); + auto a=_mm512_loadu_si512(cells),b=_mm512_loadu_si512(cells+4); + _mm512_storeu_si512(result,gfniMatrix(_mm512_permutex2var_epi8(a,il,b))); + _mm512_storeu_si512(result+4,gfniMatrix(_mm512_permutex2var_epi8(a,ih,b))); +} +// Eight queries share each pair of table loads and two GFNI instructions. +// All starts must be within 32 cells of the eight-cell-aligned anchor. +// The table pointer starts at that anchor and covers W+32 cells. +template inline void gfniDot(const Mask* masks,const Entry* entries, + const block* table,block* values) { + auto anchor=entries[0].start&~7u; + alignas(64) std::uint64_t shifted[Mask::words][8]; + #pragma GCC unroll 8 + for(unsigned q=0;q<8;++q) { + auto shift=entries[q].start-anchor; + #pragma GCC unroll 16 + for(unsigned k=0;k::words;++k) { + auto lo=k::words?masks[q].v[k]:0; + auto hi=k?masks[q].v[k-1]:0; + shifted[k][q]=(lo<>(64-shift):0); + } + } + __m512i a=_mm512_setzero_si512(),b=a; + auto pack=_mm512_set1_epi64(0x3830282018100800ULL); + #pragma GCC unroll 16 + for(unsigned k=0;k::words;++k) { + auto coefficients=_mm512_load_si512(shifted[k]); + #pragma GCC unroll 8 + for(unsigned j=0;j<64 && k*64+j low,high; + for(unsigned q=0;q<4;++q) for(unsigned byte=0;byte<16;++byte) { + low[q*16+byte]=byte*8+q;high[q*16+byte]=byte*8+q+4; + } + auto x=_mm512_permutex2var_epi8(a,_mm512_load_si512(low.data()),b); + auto y=_mm512_permutex2var_epi8(a,_mm512_load_si512(high.data()),b); + #pragma GCC unroll 4 + for(unsigned q=0;q<4;++q) { + values[entries[q].index]=block(_mm512_extracti32x4_epi32(x,q)); + values[entries[q+4].index]=block(_mm512_extracti32x4_epi32(y,q)); + } +} + +#endif + +template block scalarDot(const Mask& mask, const block* cells) { + block r=oc::ZeroBlock; + for(unsigned k=0;k::words;++k) { + auto bits=mask.v[k]; + while(bits) { + r^=cells[k*64+std::countr_zero(bits)]; + bits&=bits-1; + } + } + return r; +} + +template class Ribbon { +public: + using M=Mask; + struct Row { M mask; block value; }; + struct Query { Entry entry; M mask; }; + std::uint32_t columns, starts; + oc::AES startHash; + std::array coefficientHash; + explicit Ribbon(std::uint32_t m, block seed) : columns(m), starts(m-W+1) { + if(m()); + for(auto& h:coefficientHash) h.setKey(rng.get()); + } + + std::uint32_t start(block key, block hashed) const { + // Exact uniform reduction under ideal independent hashes. The rejection + // branch is exceedingly rare, but avoids a statistical modulo-bias claim. + std::uint64_t x=hashed.get(0); + std::uint64_t rejectionThreshold=(std::uint64_t(0)-starts)%starts; + std::uint64_t attempt=0; + while(x(0); + } + return x%starts; + } + void makeEntries(oc::span keys, oc::span entries) const { + std::size_t i=0; + for(;i+8<=keys.size();i+=8) { + std::array hashed; + startHash.template hashBlocks<8>(keys.data()+i,hashed.data()); + #pragma GCC unroll 8 + for(unsigned j=0;j<8;++j) entries[i+j]={start(keys[i+j],hashed[j]),std::uint32_t(i+j)}; + } + for(;i void coefficientBatches(oc::span keys, + oc::span entries,const block* valueBase,F&& consume) const { + constexpr unsigned batch=RIBBON_BATCH; + for(std::size_t i=0;i(batch,entries.size()-i); + std::array input, hashed; + if(size!=batch) std::fill(input.begin()+size,input.end(),oc::ZeroBlock); + std::array masks; + for(unsigned j=0;j(input.data(),hashed.data()); + #pragma GCC unroll 32 + for(unsigned j=0;j(0); + if(2*k+1(1); + } + } + for(unsigned j=0;j void queryBatches(oc::span keys,F&& consume) const { + for(std::size_t i=0;i(8,keys.size()-i); + std::array tail{}, hash, hashedStart; + const block* input=keys.data()+i; + if(size!=8) { std::copy_n(input,size,tail.data()); input=tail.data(); } + std::array masks; + startHash.template hashBlocks<8>(input,hashedStart.data()); + #pragma GCC unroll 8 + for(unsigned k=0;k<(W+127)/128;++k) { + coefficientHash[k].template hashBlocks<8>(input,hash.data()); + #pragma GCC unroll 8 + for(unsigned j=0;j<8;++j) { + masks[j].v[2*k]=hash[j].template get(0); + if(2*k+1(1); + } + } + std::array batch; + for(unsigned j=0;j keys, oc::span values, + Buffer& cells, block randomSeed, Timings& time) const { + auto total=Clock::now(), t=total; + Buffer entries(keys.size()); + // Values live at their pivot column in the output table. +#if RIBBON_DIRECT_PIVOTS + Buffer pivots(columns); + for(auto& pivot:pivots) pivot.v[0]=0; +#else + Buffer rows(keys.size()); + Buffer pivots(columns,UINT32_MAX); +#endif + // Extra zero cells make the fixed-width backsolve loads valid even at + // the final pivot. They are padding, not part of the encoded table. + cells.resize(std::size_t(columns)+W); + std::fill(cells.begin()+columns,cells.end(),oc::ZeroBlock); + oc::PRNG rng(randomSeed); + rng.get(cells.data(),columns); + time.init=elapsed(t); t=Clock::now(); + makeEntries(keys,entries); + time.starts=elapsed(t); t=Clock::now(); + orderEntries(entries,Order::sorted); + time.sort=elapsed(t); t=Clock::now(); + bool success=true; + coefficientBatches(keys,entries,values.data(),[&](std::size_t i,const M& inputMask) { + if(!success) return; + M mask=inputMask; + block value=values[entries[i].index]; + auto pos=entries[i].start; + for(;;) { + if(mask.empty()) {success=false;return;} + pos+=mask.normalize(); + if(pos>=columns) throw std::logic_error("pivot outside band"); + auto& pivot=pivots[pos]; +#if RIBBON_DIRECT_PIVOTS + // A stored row is normalized, so its low bit is always one. + if(pivot.v[0]==0) {pivot=mask;cells[pos]=value;break;} + mask.add(pivot); +#else + if(pivot==UINT32_MAX) { + pivot=std::uint32_t(i);rows[i]=mask;cells[pos]=value;break; + } + mask.add(rows[pivot]); +#endif + value^=cells[pos]; + ++time.additions; + } + }); + if(!success) return false; + // Includes coefficient hashing and elimination, now fused. + time.eliminate=elapsed(t); t=Clock::now(); + for(std::size_t pos=columns;pos--;) { +#if RIBBON_DIRECT_PIVOTS + auto& row=pivots[pos]; + if(row.v[0]==0) continue; +#else + if(pivots[pos]==UINT32_MAX) continue; + auto& row=rows[pivots[pos]]; +#endif + row.v[0]^=1; + cells[pos]^=dot(row,cells.data()+pos); + } + time.backsolve=elapsed(t); time.total=elapsed(total); + return true; + } + void decodePrepared(oc::span keys,oc::span values, + const Buffer& cells,Order mode,Timings& time) const { + auto total=Clock::now(), t=total; + std::unique_ptr first(new Query[keys.size()]),second(new Query[keys.size()]); + auto src=first.get(),dst=second.get(); + time.init=elapsed(t);t=Clock::now(); + queryBatches(keys,[&](const auto& batch,unsigned size) { + for(unsigned j=0;j count(((starts-1)>>12)+1); + for(std::size_t i=0;i>12]; + std::size_t sum=0; + for(auto& c:count) {auto old=c;c=sum;sum+=old;} + for(std::size_t i=0;i>12]++]=src[i]; + std::swap(src,dst); + } else { + for(unsigned shift=0;shift<32 && ((starts-1)>>shift);shift+=11) { + std::array count{}; + for(std::size_t i=0;i>shift)&2047]; + std::size_t sum=0; + for(auto& c:count) {auto old=c;c=sum;sum+=old;} + for(std::size_t i=0;i>shift)&2047]++]=src[i]; + std::swap(src,dst); + } + } + time.sort=elapsed(t);t=Clock::now(); + for(std::size_t i=0;i keys, oc::span values, + const Buffer& cells, Order mode, Timings& time) const { + auto total=Clock::now(), t=total; + if(mode==Order::preparedSorted || mode==Order::preparedBucket) { + decodePrepared(keys,values,cells,mode,time);return; + } + if(mode==Order::direct) { + queryBatches(keys,[&](const auto& batch,unsigned size) { + for(unsigned j=0;j entries(keys.size()); + time.init=elapsed(t); t=Clock::now(); + makeEntries(keys,entries); + time.starts=elapsed(t); t=Clock::now(); + orderEntries(entries,mode); + time.sort=elapsed(t); t=Clock::now(); +#if defined(__GFNI__) && defined(__AVX512VBMI__) + if(mode==Order::shared && W>=32) { + constexpr unsigned ringSize=std::bit_ceil(W+32u); + alignas(64) std::array cache; + std::size_t next=0; + coefficientBatches(keys,entries,values.data(),[&](std::size_t i,const M* masks,unsigned size) { + unsigned j=0; + for(;j+8<=size;j+=8) { + auto anchor=entries[i+j].start&~7u; + if(entries[i+j+7].start-anchor<=32) { + next=std::max(next,anchor); + for(;next(keys,entries,values.data(),[&](std::size_t i,const M& mask) { + values[entries[i].index]=dot(mask,cells.data()+entries[i].start); + }); + } + time.coefficients=elapsed(t); time.total=elapsed(total); + } + block referenceDecode(block key, const Buffer& cells) const { + M mask; + for(unsigned k=0;k<(W+127)/128;++k) { + auto hashed=coefficientHash[k].hashBlock(key); + mask.v[2*k]=hashed.template get(0); + if(2*k+1(1); + } + if constexpr(W%64) mask.v.back()&=(std::uint64_t(1)<<(W%64))-1; + return scalarDot(mask,cells.data()+start(key,startHash.hashBlock(key))); + } +}; +} diff --git a/research/ribbon/bench.cpp b/research/ribbon/bench.cpp new file mode 100644 index 0000000..be00ec2 --- /dev/null +++ b/research/ribbon/bench.cpp @@ -0,0 +1,190 @@ +#include "Ribbon.h" +#include +#include +#include +#include +#include +#include + +using namespace ribbon; +using oc::span; +static void require(bool ok, const char* reason) { + if(!ok) throw std::runtime_error(reason); +} +static void print(const char* kind,unsigned width,double overhead,unsigned trial, + std::size_t n,std::size_t m,const char* mode,const Timings& t) { + std::cout< void test() { + oc::PRNG rng(oc::toBlock(42)); + for(std::size_t n:{1,7,8,9,37,257,1024}) { + Ribbon r(n*2+W, rng.get()); + std::vector keys(n),values(n),out(n),queries(n); + Buffer cells; + rng.get(keys.data(),n);rng.get(values.data(),n);rng.get(queries.data(),n); + Timings enc; + require(r.encode(keys,values,cells,rng.get(),enc),"test encode failed"); + for(auto mode:{Order::sorted,Order::bucket,Order::direct,Order::preparedSorted,Order::preparedBucket,Order::shared}) { + Timings dec; + r.decode(keys,out,cells,mode,dec); + for(std::size_t i=0;i1) { + keys[1]=keys[0]; values[1]=values[0]; + Timings failed; + require(!r.encode(keys,values,cells,rng.get(),failed),"duplicate rank failure missed"); + } + } + // Independent mask/dot checks cover word boundaries and padding loads. + std::vector data(W+16); + rng.get(data.data(),data.size()); + for(unsigned k=0;k m{}; m.v[k/64]=std::uint64_t(1)<<(k%64); + require(dot(m,data.data())==data[k],"single-bit SIMD mask failed"); + auto shift=m.normalize(); + require(shift==k && m.v[0]==1,"mask normalize failed"); + } + for(unsigned i=0;i<1000;++i) { + Mask m; + for(auto& x:m.v) x=rng.get(); + if constexpr(W%64) m.v.back()&=(std::uint64_t(1)<<(W%64))-1; + require(dot(m,data.data()+3)==scalarDot(m,data.data()+3),"random SIMD dot failed"); + require(dot(m,data.data()+3)==scalarDot(m,data.data()+3),"forwarding SIMD dot failed"); + } +#if defined(__GFNI__) && defined(__AVX512VBMI__) + // Independent one-hot and random masks cover every shift and word boundary. + Buffer gfniCells(W+32); + rng.get(gfniCells.data(),gfniCells.size()); + Buffer transformed(gfniCells.size()); + for(unsigned i=0;i,8> gm; + std::array ge; + std::array gv; + for(unsigned offset=0;offset<=32;++offset) for(unsigned bit=0;bit<=W;++bit) { + for(unsigned q=0;q<8;++q) { + gm[q]={}; + if(bit(); + if constexpr(W%64) gm[q].v.back()&=(std::uint64_t(1)<<(W%64))-1; + } + ge[q]={q?offset:0,7-q}; + } + gfniDot(gm.data(),ge.data(),transformed.data(),gv.data()); + for(unsigned q=0;q<8;++q) + require(gv[ge[q].index]==scalarDot(gm[q],gfniCells.data()+ge[q].start),"GFNI shared dot failed"); + } + +#endif +} + +#ifndef RIBBON_TEST_ONLY +template void bench(std::size_t n,double overhead,unsigned trials,const std::string& selection) { + std::size_t m=std::ceil(n*overhead); + oc::PRNG input(oc::toBlock(20261115)); + std::vector keys(n),values(n),queries(n),out(n); + input.get(keys.data(),n);input.get(values.data(),n);input.get(queries.data(),n); + std::copy_n(keys.data(),n/2,queries.data()); + for(unsigned trial=0;trial cells; // Match Baxos: fresh output allocation each trial. + Ribbon r(m,oc::toBlock(trial+100)); + Timings enc; + require(r.encode(keys,values,cells,oc::toBlock(trial+200),enc),"benchmark rank failure"); + enc.total=elapsed(wall); // Include workspace destruction and key setup. + print("encode",W,overhead,trial,n,m,"sorted",enc); + if(trial==0) { + std::ifstream memory("/proc/self/smaps_rollup");std::string line; + while(std::getline(memory,line)) + if(line.starts_with("AnonHugePages:")) std::cerr<(1,n/1024)) + require(out[i]==r.referenceDecode(queries[i],cells),"nonmember reference failed"); + print("decode",W,overhead,trial,n,m,mode==Order::shared?"shared":mode==Order::sorted?"sorted":mode==Order::bucket?"bucket":mode==Order::direct?"direct":mode==Order::preparedSorted?"prepared_sorted":"prepared_bucket",dec); + } + } +} + +void baxos(std::size_t n,unsigned trials) { + oc::PRNG input(oc::toBlock(20261115)); + std::vector keys(n),values(n),queries(n),out(n); + input.get(keys.data(),n);input.get(values.data(),n);input.get(queries.data(),n); + std::copy_n(keys.data(),n/2,queries.data()); + for(unsigned trial=0;trial cells(b.size()); + oc::PRNG rng(oc::toBlock(trial+200)); + enc.init=elapsed(t);t=Clock::now(); + b.solve(keys,values,cells,&rng,1); + enc.eliminate=elapsed(t);enc.total=elapsed(total); + print("baxos_encode",0,double(b.size())/n,trial,n,b.size(),"native",enc); + b.decode(keys,out,cells,1); + for(std::size_t i=0;i(queries,out,cells,1); + dec.total=elapsed(t);dec.coefficients=dec.total; + for(std::size_t i=0;i();test<32>();test<48>();test<64>();test<80>();test<112>();test<128>();test<144>();test<192>();test<320>();test<640>(); + std::cout<<"PASS: members, nonmembers, tails, zero residuals, SIMD/scalar dots\n"; + return 0; + } +#ifndef RIBBON_TEST_ONLY + if(argc<5) throw std::runtime_error("usage: bench baxos|WIDTH LOG_N OVERHEAD TRIALS"); + unsigned logn=std::stoul(argv[2]); + if(logn>26) throw std::runtime_error("benchmark log_n must be <=26"); + std::size_t n=std::size_t(1)<5?argv[5]:"all"; + require(selection=="all" || selection=="sorted-only" || selection=="shared-only","unknown decode mode"); + std::cout<(n,overhead,trials,selection);break; + case 80:bench<80>(n,overhead,trials,selection);break; + case 112:bench<112>(n,overhead,trials,selection);break; + case 128:bench<128>(n,overhead,trials,selection);break; + case 144:bench<144>(n,overhead,trials,selection);break; + case 192:bench<192>(n,overhead,trials,selection);break; + case 256:bench<256>(n,overhead,trials,selection);break; + case 320:bench<320>(n,overhead,trials,selection);break; + case 384:bench<384>(n,overhead,trials,selection);break; + case 512:bench<512>(n,overhead,trials,selection);break; + case 640:bench<640>(n,overhead,trials,selection);break; + default:throw std::runtime_error("unsupported width"); + } +#endif + } catch(const std::exception& e) {std::cerr<= 0: + continue + b = (1 - 1 / t) * math.exp(rho * (t / 2 - 1)) + c = max(1, b / -math.expm1(log_a)) + log_rank = math.log(mu * c) + rho * (t - 1) - width * theta + hi, lo = max(log_delta, log_rank), min(log_delta, log_rank) + log_total = hi + math.log1p(math.exp(lo - hi)) + bits = -log_total / math.log(2) + if best is None or bits > best['bits']: + best = dict(n=n, m=m, width=width, rho=rho, theta=theta, + C=c, bits=bits, poisson_bits=-log_delta/math.log(2)) + return best + + +if __name__ == '__main__': + p = argparse.ArgumentParser() + p.add_argument('--log-n', type=int, default=20) + a = p.parse_args() + n = 1 << a.log_n + for overhead in [1.05, 1.10, 1.15, 1.20, 1.25, 1.30, 1.40, 1.50]: + for width in [64, 128, 192, 256, 320, 384, 512, 640, 768, 1024]: + r = bound(n, math.ceil(n * overhead), width) + if r and r['bits'] >= 40: + print(json.dumps(dict(overhead=overhead, **r)), flush=True) + break diff --git a/research/ribbon/differential.cpp b/research/ribbon/differential.cpp new file mode 100644 index 0000000..d223d03 --- /dev/null +++ b/research/ribbon/differential.cpp @@ -0,0 +1,44 @@ +#include "Ribbon.h" +#include "BaselineRibbon.h" // Generated from the hashed, preserved baseline. +#include + +template void compare(std::size_t n) { + oc::PRNG rng(oc::toBlock(n+W)); + std::vector keys(n),values(n),oldCells; + rng.get(keys.data(),n);rng.get(values.data(),n); + ribbon::Buffer cells; + auto seed=rng.get(),freeSeed=rng.get(); + std::uint32_t m=std::uint32_t(n*1.4)+W; + ribbon::Ribbon current(m,seed); + ribbon_baseline::Ribbon previous(m,seed); + ribbon::Timings now; + ribbon_baseline::Timings before; + bool a=current.encode(keys,values,cells,freeSeed,now); + bool b=previous.encode(keys,values,oldCells,freeSeed,before); + if(a!=b || !a || cells.size()!=oldCells.size()) throw std::runtime_error("encode status mismatch"); + for(std::size_t i=0;i out(n); + for(auto mode:{ribbon::Order::sorted,ribbon::Order::shared}) { + current.decode(keys,out,cells,mode,now); + for(std::size_t i=0;i reference(n); + previous.decode(keys,reference,oldCells,ribbon_baseline::Order::sorted,before); + for(auto mode:{ribbon::Order::shared}) { + current.decode(keys,out,cells,mode,now); + if(out!=reference) throw std::runtime_error("large nonmember decode mismatch"); + } + std::cout<<"IDENTICAL width="<= log2(q). + assert label_bits >= query_bits + lo, hi = m, max(m+1, 2*m) + while log_bound(m,label_bits,query_bits,hi,seed_bits) > -failure_bits: + hi *= 2 + while lo+1 < hi: + mid=(lo+hi)//2 + if log_bound(m,label_bits,query_bits,mid,seed_bits) <= -failure_bits: + hi=mid + else: + lo=mid + assert log_bound(m,label_bits,query_bits,hi,seed_bits) <= -failure_bits + return hi-1 # event is |X_eff| >= hi + + +def exact_small_check(): + from math import comb + # Verify the binomial relaxation independently on small integers. + with localcontext() as c: + c.prec=80 + for m in [1,2,5]: + for ell in [4,8,16]: + for t in range(m+1,17): + exact=Decimal(ell*m-ell*t)+Decimal(comb(16,t)).ln()/Decimal(2).ln() + assert exact <= log_bound(m,ell,4,t,0) + # A simple analytic certificate: with q<=2^128, L=256, s=128, + # t=2m+2 gives s+L*m+(128-L)*t=-128 even without the factorial. + for m in [1,2,64,1000,1310720,1411712]: + assert log_bound(m,256,128,2*m+2,128) < -128 + + +if __name__ == '__main__': + exact_small_check() + n=1<<20 + result=[] + for backend,m in [('ribbon',1310720),('baxos',1411712)]: + for q in [64,96,100,128]: + for ell in [128,256,384,512,640,1024,1280]: + bound=cap(m,ell,q) + result.append(dict(backend=backend,n=n,m=m,label_bits=ell, + query_bits=q,seed_bits=128,failure_bits=128,extraction_cap=bound, + cap_over_m=bound/m,cap_over_n=bound/n, + log2_probability_upper_bound=str(log_bound(m,ell,q,bound+1)))) + print(json.dumps(result,indent=2)) diff --git a/research/ribbon/integration.cpp b/research/ribbon/integration.cpp new file mode 100644 index 0000000..74cfa1f --- /dev/null +++ b/research/ribbon/integration.cpp @@ -0,0 +1,80 @@ +#include "volePSI/RsPsi.h" +#include "tests/Ribbon_Tests.h" +#include "tests/RsOprf_Tests.h" +#include +#include +#include +#include +#include +#include + +using namespace volePSI; +using namespace oc; + +double interval(const Timer& timer,const char* begin,const char* end) +{ + return std::chrono::duration(timer[end]-timer[begin]).count(); +} +int main(int argc,char** argv) +{ + try { + const std::string mode=argc>1?argv[1]:"test"; + if(mode=="test") + { + CLP cmd; + RsOprf_seed_rejection_test(cmd);std::cout<<"PASS RsOprf_seed_rejection_test\n"<2?std::stoul(argv[2]):20); + const unsigned trials=argc>3?std::stoul(argv[3]):8; + const bool malicious=argc>4?std::stoul(argv[4]):false; + PRNG rng(toBlock(193,57)); + std::vector send(n),recv(n); + rng.get(send.data(),n);rng.get(recv.data(),n); + // Verify a nonempty intersection outside the timed region. + for(u64 i=0;i(),malicious,1); + receiver.init(n,n,40,rng.get(),malicious,1); + sender.setOkvsType(backend);receiver.setOkvsType(backend); + sender.setTimer(st);receiver.setTimer(rt); + auto sockets=coproto::LocalAsyncSocket::makePair(); + const auto begin=std::chrono::steady_clock::now(); + auto result=macoro::sync_wait(macoro::when_all_ready(sender.run(send,sockets[0]),receiver.run(recv,sockets[1]))); + std::get<0>(result).result();std::get<1>(result).result(); + const auto end=std::chrono::steady_clock::now(); + if(receiver.mIntersection.size()!=(n+1023)/1024) throw RTE_LOC; + std::sort(receiver.mIntersection.begin(),receiver.mIntersection.end()); + for(u64 i=0;i(end-begin).count()<<',' + < + +int main() +{ + using namespace volePSI; + constexpr u64 n=1<<20; + RibbonOkvs code;code.init(n,40,oc::toBlock(123,45)); + PRNG rng(oc::toBlock(234,56)); + std::vector keys(n),output(n),expected(n),ordinary(code.size()); + ribbon_detail::Buffer advised(code.size()); + rng.get(keys.data(),n);rng.get(ordinary.data(),ordinary.size()); + std::copy(ordinary.begin(),ordinary.end(),advised.begin()); + code.decode(keys,expected,ordinary); + std::cout<<"allocation,trial,decode_ms\n"; + for(bool huge:{false,true,false,true}) + for(unsigned trial=0;trial<8;++trial) + { + auto table=huge?span(advised):span(ordinary); + const auto start=std::chrono::steady_clock::now(); + code.decode(keys,output,table); + const auto end=std::chrono::steady_clock::now(); + if(output!=expected) throw std::runtime_error("decode allocation mismatch"); + std::cout<<(huge?"advised":"ordinary")<<','<(end-start).count()<<'\n'; + } +} diff --git a/research/ribbon/integration_peach.py b/research/ribbon/integration_peach.py new file mode 100644 index 0000000..0aa229c --- /dev/null +++ b/research/ribbon/integration_peach.py @@ -0,0 +1,94 @@ +"""Run in an isolated source/build tree on Peach; every action takes all locks.""" +import argparse, concurrent.futures, fcntl, hashlib, json, os, shutil, subprocess, time +from pathlib import Path + +p=argparse.ArgumentParser() +p.add_argument('action',choices=['build','test','bench','params','sanitize','avx2','portable','regression','decode-build','decode-pages']) +p.add_argument('--backend',choices=['baxos','ribbon'],default='ribbon') +p.add_argument('--logn',type=int,default=20) +p.add_argument('--trials',type=int,default=8) +p.add_argument('--malicious',type=int,default=0) +p.add_argument('--name',default='') +a=p.parse_args() +root=Path('/tmp/volepsi-ribbon-integration-20261115') +src=root/'src';base=Path('/tmp/volepsi-chosenbaa30-20261115') +locks=[] +for name in ['volepsi-benchmark.lock','hypercat-global-benchmark.lock','cat-blst-benchmark.lock']: + f=open('/tmp/'+name,'a');fcntl.flock(f,fcntl.LOCK_EX|fcntl.LOCK_NB);locks.append(f) +env=dict(os.environ,LD_LIBRARY_PATH=str(base/'deps/lib'),UBSAN_OPTIONS='halt_on_error=1:print_stacktrace=1') +results=root/'results';results.mkdir(exist_ok=True) +name=a.name or a.action +exe=root/('integration-decode' if a.action in ['decode-build','decode-pages'] else 'integration') +if a.action in ['build','sanitize','avx2','portable','decode-build']: + flags=['-std=c++20','-march=native','-O3','-g1','-DNDEBUG','-pthread','-DCRYPTOTOOLS_EDWARDS25519_ASM=1', + '-I'+str(src),'-I'+str(root/'build'),'-isystem',str(base/'install/include'),'-isystem',str(base/'deps/include')] + if (root/'hardening-include/libOTe/Base/McRosRoy.h').exists(): + flags=['-I'+str(root/'hardening-include'),*flags] + sources=[str(src/('research/ribbon/integration_decode.cpp' if a.action=='decode-build' else 'research/ribbon/integration.cpp'))] + libs=[str(root/'build/tests/libvolePSI_Tests.a'),str(root/'build/volePSI/libvolePSI.a')] + if a.action=='sanitize': + # Recompile every affected translation unit, not just the harness. + sources += [str(src/x) for x in ['tests/Ribbon_Tests.cpp','tests/RsOprf_Tests.cpp','volePSI/RibbonOkvs.cpp','volePSI/RsOprf.cpp','volePSI/RsPsi.cpp']] + flags+=['-UNDEBUG'] + exe=root/('integration-'+a.action) + elif a.action in ['avx2','portable']: + sources += [str(src/'volePSI/RibbonOkvs.cpp')] + exe=root/('integration-'+a.action) + if a.action=='sanitize': flags+=['-O1','-fsanitize=address,undefined','-fno-omit-frame-pointer'] + if a.action=='avx2': flags+=['-mno-avx512f'] + if a.action=='portable': flags+=['-mno-avx512f','-DVOLEPSI_RIBBON_PORTABLE'] + libs += [str(base/'install/lib'/x) for x in ['liblibOTe.a','libcryptoTools.a']] + libs += [str(base/'deps/lib'/x) for x in ['libsodium.a','libcoproto.a','libmacoro.a','libbitpolymul.a']] + if a.action=='sanitize': + # Existing macoro bug: an object-independent helper is called before + # the base constructor. Fix only the isolated include overlay; keep + # vptr checking enabled and preserve the exact patch in the results. + overlay=root/'sanitize-include';rel=Path('macoro/detail/when_all_awaitable.h') + shutil.copytree(base/'deps/include/macoro',overlay/'macoro',dirs_exist_ok=True) + old=(base/'deps/include'/rel).read_text() + new=old.replace('size_t tasks_size(TASK_CONTAINER& tasks)','static size_t tasks_size(TASK_CONTAINER& tasks)') + assert new!=old + (overlay/rel).parent.mkdir(parents=True,exist_ok=True);(overlay/rel).write_text(new) + import difflib + (results/'macoro-static-helper.patch').write_text(''.join(difflib.unified_diff(old.splitlines(True),new.splitlines(True),fromfile='a/'+str(rel),tofile='b/'+str(rel)))) + # InlinePoly also downcasts raw storage before constructing the model. + # Construct in storage first and use the placement-new result. + shutil.copytree(base/'deps/include/coproto',overlay/'coproto',dirs_exist_ok=True) + rel=Path('coproto/Common/InlinePoly.h');old=(base/'deps/include'/rel).read_text() + new=old.replace('ModelController* ptr = (ModelController*) & getController();\n\t\t\t\tnew (ptr) ModelController(std::forward(args)...);', + 'auto* ptr = new (static_cast(&mStorage)) ModelController(std::forward(args)...);') + assert new!=old + (overlay/rel).write_text(new) + (results/'coproto-storage-construction.patch').write_text(''.join(difflib.unified_diff(old.splitlines(True),new.splitlines(True),fromfile='a/'+str(rel),tofile='b/'+str(rel)))) + flags=['-I'+str(overlay),*flags] + objects=root/(name+'-objects');objects.mkdir(exist_ok=True) + commands=[] + for i,source in enumerate(sources): + commands.append(['g++',*flags,'-c',source,'-o',str(objects/(str(i)+'.o'))]) + def compile_one(pair): + i,command=pair + with (objects/(str(i)+'.log')).open('w') as f: subprocess.run(command,env=env,stdout=f,stderr=f,check=True) + with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool: + list(pool.map(compile_one,enumerate(commands))) + command=['g++',*flags,*[str(objects/(str(i)+'.o')) for i in range(len(sources))],*libs,'-o',str(exe)] + with (results/(name+'-build.log')).open('w') as f: subprocess.run(command,env=env,stdout=f,stderr=f,check=True) + command=commands+[command] + meta={'command':command,'sources':{str(x.relative_to(src)):hashlib.sha256(x.read_bytes()).hexdigest() for x in src.rglob('*') if x.is_file() and x.suffix in ['.cpp','.h']}} + if (root/'hardening-include/libOTe/Base/McRosRoy.h').exists(): + meta['mrr_header_sha256']=hashlib.sha256((root/'hardening-include/libOTe/Base/McRosRoy.h').read_bytes()).hexdigest() + (results/(name+'-build.json')).write_text(json.dumps(meta,indent=2)) + if a.action in ['build','decode-build']: raise SystemExit(0) + command=[str(exe),'test'] +elif a.action=='regression': + exe=root/'build/frontend/frontend';command=[str(exe),'-u'] +else: + command=['taskset','-c','2',str(exe)] + if a.action=='bench': command += [a.backend,str(a.logn),str(a.trials),str(a.malicious)] + elif a.action!='decode-pages': command += [a.action] +r=subprocess.run(command,env=env,text=True,capture_output=True,timeout=600) +(results/(name+'.txt')).write_text(r.stdout+r.stderr) +meta={'command':command,'utc':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()),'binary_sha256':hashlib.sha256(exe.read_bytes()).hexdigest(), + 'cpu':subprocess.check_output(['lscpu'],text=True),'compiler':subprocess.check_output(['g++','--version'],text=True).splitlines()[0], + 'frequency':{x:Path('/sys/devices/system/cpu/cpu2/cpufreq',x).read_text().strip() for x in ['scaling_governor','scaling_min_freq','scaling_max_freq']}} +(results/(name+'.json')).write_text(json.dumps(meta,indent=2)) +print(r.stdout+r.stderr);r.check_returncode() diff --git a/research/ribbon/parameters.json b/research/ribbon/parameters.json new file mode 100644 index 0000000..433e9db --- /dev/null +++ b/research/ribbon/parameters.json @@ -0,0 +1,98 @@ +[ + { + "n": 1048576, + "m": 1101005, + "width": 640, + "rho": 0.9604876698377103, + "theta": 0.07832563140327382, + "C": 691.147299914499, + "bits": 42.701137850110264, + "poisson_bits": 47.27870648686184, + "verified_bits_decimal80": "42.701137850109844580500704662143135235624291961510899220975136942378785340500712", + "overhead": 1.05 + }, + { + "n": 1048576, + "m": 1153434, + "width": 320, + "rho": 0.9171767209410173, + "theta": 0.1670484705149468, + "C": 358.211166825246, + "bits": 48.37412278505967, + "poisson_bits": 55.82667453248071, + "verified_bits_decimal80": "48.374122785059393216272594199543803465347621988841191681581367747300212317041602", + "overhead": 1.1 + }, + { + "n": 1048576, + "m": 1205863, + "width": 192, + "rho": 0.8777455924584939, + "theta": 0.25022613218214024, + "C": 241.72385967442872, + "bits": 41.02146841282888, + "poisson_bits": 64.29504897456378, + "verified_bits_decimal80": "41.021468412828818171247765396894264864371169238914643726199587378097650439829910", + "overhead": 1.15 + }, + { + "n": 1048576, + "m": 1258292, + "width": 144, + "rho": 0.8416533208313302, + "theta": 0.32855176358541405, + "C": 182.62833590814014, + "bits": 40.25677540364339, + "poisson_bits": 73.20138622522254, + "verified_bits_decimal80": "40.256775403643333114432158037948933768053009045887017768896239287315155001163008", + "overhead": 1.2 + }, + { + "n": 1048576, + "m": 1310720, + "width": 128, + "rho": 0.8074820583761193, + "theta": 0.405491100627568, + "C": 158.6493115776819, + "bits": 46.974483275350394, + "poisson_bits": 64.38827438132382, + "verified_bits_decimal80": "46.974483275350424445123319685386244814373085847356590078032764528174962038956382", + "overhead": 1.25 + }, + { + "n": 1048576, + "m": 1363149, + "width": 112, + "rho": 0.7778379918540355, + "theta": 0.47411267150300257, + "C": 141.92462523402568, + "bits": 48.76238017591712, + "poisson_bits": 92.63015023386326, + "verified_bits_decimal80": "48.762380175917144072597095038654863685303668877052499126775118513563313334366785", + "overhead": 1.3 + }, + { + "n": 1048576, + "m": 1468007, + "width": 80, + "rho": 0.7213775950662229, + "theta": 0.6085832245316319, + "C": 102.72523627247071, + "bits": 42.67122822932351, + "poisson_bits": 73.27312226326757, + "verified_bits_decimal80": "42.671228229323533961233317834460688566563156795418478525147725449898056303799500", + "overhead": 1.4 + }, + { + "n": 1048576, + "m": 1835008, + "width": 64, + "rho": 0.5767389536249093, + "theta": 0.6924540333793854, + "C": 4.541203804078263, + "bits": 40.90872398391937, + "poisson_bits": 64.44022235999546, + "verified_bits_decimal80": "40.908723983919368921100000781171090026960745523237036529612524928027796599784455", + "overhead": 1.75 + } +] diff --git a/research/ribbon/peach.py b/research/ribbon/peach.py new file mode 100644 index 0000000..76303f1 --- /dev/null +++ b/research/ribbon/peach.py @@ -0,0 +1,136 @@ +"""Build against the existing validated Peach tree, and benchmark serially.""" +import argparse +import csv +import fcntl +import hashlib +import json +import os +from pathlib import Path +import statistics +import subprocess +import time + +p=argparse.ArgumentParser() +p.add_argument('action',choices=['build','test','bench','sanitize','differential','differential-sanitize']) +p.add_argument('--trials',type=int,default=6) +p.add_argument('--out',default='results') +p.add_argument('--quick',action='store_true') +mode=p.add_mutually_exclusive_group() +mode.add_argument('--sorted-only',action='store_true') +mode.add_argument('--shared-only',action='store_true') +p.add_argument('--ribbon-only',action='store_true') +p.add_argument('--dot',type=int,choices=[0,1,2],default=2) +p.add_argument('--exe',default='bench') +p.add_argument('--no-gfni',action='store_true',help='validate the existing AVX-512 fallback without GFNI/VBMI') +p.add_argument('--huge-pages',type=int,choices=[0,1],default=1) +p.add_argument('--forwarding',type=int,choices=[0,1],default=1) +p.add_argument('--baseline-exe',default='optimization-baseline/bench') +p.add_argument('--radix-bits',type=int,choices=[8,9,10,11],default=11) +p.add_argument('--batch',type=int,choices=[8,16,32],default=8) +p.add_argument('--direct-pivots',type=int,choices=[0,1],default=0) +p.add_argument('--wait-lock',type=int,default=0) +a=p.parse_args() +# Builds and correctness runs also avoid disturbing another timed job. +locks=[] +deadline=time.monotonic()+a.wait_lock +while True: + try: + for name in ['volepsi-benchmark.lock','hypercat-global-benchmark.lock','cat-blst-benchmark.lock']: + lock=open('/tmp/'+name,'a');locks.append(lock) + fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) + break + except BlockingIOError: + for lock in locks: lock.close() + locks=[] + if time.monotonic()>=deadline: raise + time.sleep(1) +here=Path(__file__).resolve().parent +base=Path('/tmp/volepsi-chosenbaa30-20261115') +exe=here/a.exe +flags=['-std=c++20','-march=native','-O3','-DNDEBUG','-pthread', + '-DRIBBON_DOT='+str(a.dot), + '-DRIBBON_HUGE_PAGES='+str(a.huge_pages),'-DRIBBON_FORWARDING='+str(a.forwarding), + '-DRIBBON_RADIX_BITS='+str(a.radix_bits), + '-DRIBBON_BATCH='+str(a.batch), + '-DRIBBON_DIRECT_PIVOTS='+str(a.direct_pivots), + '-DCRYPTOTOOLS_EDWARDS25519_ASM=1', + '-I'+str(base/'psi-build'),'-I'+str(base/'psi'), + '-isystem',str(base/'install/include'),'-isystem',str(base/'deps/include')] +if a.no_gfni: flags += ['-mno-gfni','-mno-avx512vbmi'] +libs=[str(base/'psi-build/volePSI/libvolePSI.a')] +libs += [str(base/'install/lib'/x) for x in ['liblibOTe.a','libcryptoTools.a']] +libs += [str(base/'deps/lib'/x) for x in ['libsodium.a','libcoproto.a','libmacoro.a','libbitpolymul.a']] +env=dict(os.environ,LD_LIBRARY_PATH=str(base/'deps/lib')) +if a.action in ['build','sanitize','differential','differential-sanitize']: + source=here/'bench.cpp' + if a.action.startswith('differential'): + reference=(here/'optimization-baseline/Ribbon.h').read_bytes() + if hashlib.sha256(reference).hexdigest()!='e0316ff5fead517ae50630798795139739180460460f3e8c0ef0bfcaeb57fc03': + raise RuntimeError('Unexpected baseline source') + (here/'BaselineRibbon.h').write_text(reference.decode().replace('namespace ribbon {','namespace ribbon_baseline {')) + source=here/'differential.cpp' + exe=here/a.action + if 'sanitize' in a.action: + flags += ['-O1','-g1','-DRIBBON_TEST_ONLY','-fsanitize=address,undefined','-fno-omit-frame-pointer'] + if a.action=='sanitize': exe=here/'bench-sanitize' + cmd=['g++',*flags,str(source),*libs,'-o',str(exe)] + (here/(exe.name+'-command.json')).write_text(json.dumps(cmd,indent=2)) + subprocess.run(cmd,env=env,check=True) + source_names=[source.name,'Ribbon.h'] + if a.action.startswith('differential'): source_names.append('BaselineRibbon.h') + snapshot=here/(exe.name+'-sources');snapshot.mkdir(exist_ok=True) + hashes={} + for name in source_names: + data=(here/name).read_bytes();(snapshot/name).write_bytes(data) + hashes[name]=hashlib.sha256(data).hexdigest() + (here/(exe.name+'-build.json')).write_text(json.dumps(dict(command=cmd,sources=hashes),indent=2)) + if a.action=='sanitize': subprocess.run([str(exe),'test'],env=env,check=True) + if a.action.startswith('differential'): subprocess.run([str(exe)],env=env,check=True) +elif a.action=='test': + subprocess.run([str(exe),'test'],env=env,check=True) +else: + out=here/a.out;out.mkdir(exist_ok=True) + meta=dict(time_utc=time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()), + binary_sha256=hashlib.sha256(exe.read_bytes()).hexdigest(), + compiler=subprocess.check_output(['g++','--version'],text=True).splitlines()[0], + cpu=subprocess.check_output(['lscpu'],text=True),affinity=[2],trials=a.trials, + input='fixed random keys/values; queries half members, half independent', + encoder='fresh randomized free cells; fresh matrix seed each trial', + sources=json.loads((here/(exe.name+'-build.json')).read_text())['sources']) + meta['sorted_only']=a.sorted_only + meta['shared_only']=a.shared_only + meta['baseline_binary_sha256']=hashlib.sha256((here/a.baseline_exe).read_bytes()).hexdigest() + meta['build_command']=json.loads((here/(exe.name+'-command.json')).read_text()) + meta['transparent_hugepages']=Path('/sys/kernel/mm/transparent_hugepage/enabled').read_text().strip() + meta['cpu2_frequency']={key:Path('/sys/devices/system/cpu/cpu2/cpufreq',key).read_text().strip() + for key in ['scaling_governor','scaling_min_freq','scaling_max_freq','scaling_cur_freq']} + (out/'metadata.json').write_text(json.dumps(meta,indent=2)) + summaries=[] + profiles=[('baxos',1),(128,1.25),(112,1.3),(80,1.4)] + if not a.quick: profiles += [(144,1.2),(192,1.15),(320,1.1),(640,1.05),(64,1.75)] + profiles += [('baxos',1)] + if a.ribbon_only: profiles=[p for p in profiles if p[0]!='baxos'] + for width,overhead in profiles: + name=f'{width}-{overhead}' + if (out/(name+'.csv')).exists(): name+='-repeat' + target=here/a.baseline_exe if width=='baxos' else exe + cmd=['taskset','-c','2',str(target),str(width),'20',str(overhead),str(a.trials)] + if a.sorted_only: cmd.append('sorted-only') + elif a.shared_only and width!='baxos': cmd.append('shared-only') + print('START',name,flush=True) + result=subprocess.run(cmd,env=env,text=True,capture_output=True,timeout=600) + (out/(name+'.csv')).write_text(result.stdout) + (out/(name+'.stderr')).write_text(result.stderr) + if result.returncode: raise RuntimeError(result.stderr) + rows=list(csv.DictReader(result.stdout.splitlines())) + for kind,order in sorted({(r['kind'],r['order']) for r in rows}): + group=[r for r in rows if r['kind']==kind and r['order']==order and int(r['trial'])>0] + summary=dict(profile=name,kind=kind,order=order) + for col in ['init_ms','start_hash_ms','sort_ms','coefficient_or_query_ms','eliminate_ms','backsolve_ms','total_ms']: + summary[col]=statistics.median(float(r[col]) for r in group) + summary['min_ms']=min(float(r['total_ms']) for r in group) + summary['max_ms']=max(float(r['total_ms']) for r in group) + summaries.append(summary) + print(json.dumps(summary),flush=True) + (out/'summary.json').write_text(json.dumps(summaries,indent=2)) + print('DONE: all benchmarks and correctness checks completed sequentially',flush=True) diff --git a/research/ribbon/proof.txt b/research/ribbon/proof.txt new file mode 100644 index 0000000..1e3510e --- /dev/null +++ b/research/ribbon/proof.txt @@ -0,0 +1,104 @@ +Random-band OKVS: a concrete rank bound (working audit, 2026-11-15) + +Construction and scope +---------------------- +Fix n distinct keys, m columns, and band width w, with M=m-w+1>n. +For every key, independently sample a uniform start in {0,...,M-1} +and w independent fair coefficient bits. All other coefficients are zero. +The key set is fixed before these random choices. Coefficients are binary; +right-hand sides and output cells may be GF(2^128) elements. The rank over +GF(2) equals the rank over GF(2^128). No leading coefficient is forced to one. + +The encoder sorts rows by their start, eliminates from left to right, and +returns failure on a zero residual row. On success it samples free cells +uniformly and back-substitutes. A retry uses an independent matrix seed. +This note bounds one attempt; it does not analyze public retry-seed leakage, +adaptive key selection, malicious OPRF security, or an AES instantiation of +the ideal random functions. A production integration must handle those. + +Claim +----- +Choose n/M < rho < 1 and 1=w. +This is the elementary elimination/coin-flipping equivalence in +Dietzfelbinger-Walzer, ESA 2019, Sections 2.2-2.4; the quantitative bound +below is derived directly instead of invoking their queue-tail constants. + +First Poissonize: put independent Z_j~Poisson(rho) arrivals at each start j. +The total N is Poisson(mu). Conditional on N, these are N uniform starts. +Couple the fixed-n experiment to the first n rows of that experiment when +N>=n, before sorting. A dependence among those rows remains a dependence +after adding rows. The exceptional probability Pr[N (A*s,s_J) is a bijection. Consequently uniform, +independent input values v and free cells r yield a uniform output s. +For arbitrary fixed v, the same algorithm samples uniformly from A*s=v. +These are different claims. A fixed nonzero query row applied to uniform +s has a uniform field value, but this does not establish independence +from known programmed values or security for adaptively selected queries. +An all-zero query row has probability 2^(-w) in the ideal model; that event +must be included whenever uniform nonmember decoding is required. + +References and audit status +--------------------------- +Dietzfelbinger and Walzer, ESA 2019: +https://drops.dagstuhl.de/entities/document/10.4230/LIPIcs.ESA.2019.39 +Bienstock, Patel, Seo and Yeo, USENIX Security 2023: +https://www.usenix.org/system/files/usenixsecurity23-bienstock.pdf +The bound above is a new derivation checked algebraically in this work, +not a claim of independent peer review or a completed PSI security proof. diff --git a/research/ribbon/verify_distinct_key_bound.py b/research/ribbon/verify_distinct_key_bound.py new file mode 100644 index 0000000..c9d6b9c --- /dev/null +++ b/research/ribbon/verify_distinct_key_bound.py @@ -0,0 +1,54 @@ +"""Evaluate the Baxos ideal-cipher factorial bound; no AES security assumption test.""" +from decimal import Decimal, localcontext +from fractions import Fraction +from math import comb, factorial +import json + + +def exponent(m,t,bits=128): + with localcontext() as c: + c.prec=80 + d=Decimal(t) + return Decimal(bits*(m+1))-(d*d.ln()-d+1)/Decimal(2).ln() + + +def cap(m): + lo,hi=1,max(2,2*m) + # Extra bit of slack beyond the requested exponent -128. + while exponent(m,hi)>-129: hi*=2 + while lo+1=t for v in counts),factorial(N)) + assert probability<=min(Fraction(1),Fraction(1,factorial(t))) + + +if __name__=='__main__': + check_identities() + n=1<<20;m=1411712;bound=cap(m) + print(json.dumps(dict(model='ideal cipher; all seeds except k; all tables and inputs', + backend='baxos',n=n,m=m,cap=bound,cap_over_n=bound/n,cap_over_m=bound/m, + log2_probability_upper_bound=str(exponent(m,bound+1)), + validation='factorial identity, integral relaxation, exhaustive N=4 target maps'),indent=2)) diff --git a/research/ribbon/verify_integration_params.py b/research/ribbon/verify_integration_params.py new file mode 100644 index 0000000..8b8f773 --- /dev/null +++ b/research/ribbon/verify_integration_params.py @@ -0,0 +1,29 @@ +"""Independently recompute the selector's exported witnesses at 80 digits.""" +import csv, decimal, json, sys +from decimal import Decimal as D + +decimal.getcontext().prec=80 +ln2=D(2).ln() +checked=0 +minimum_margin=None +for row in csv.DictReader(open(sys.argv[1])): + n,m,w,ssp=(D(row[x]) for x in ['n','columns','width','ssp']) + rho,theta=D(row['rho']),D(row['theta']) + if rho==0: + assert m==w and w>n + bits=w-n + else: + starts=m-w+1;t=theta.exp();mu=starts*rho + assert n/starts=ssp+2-D('1e-10'), row + assert abs(bits-D(row['bits'])) x, out; + std::array coefficients; + for (u64 count : {1, 2, 3, 7, 17, 40}) + { + for (unsigned trial=0; trial<200; ++trial) + { + rng.get(x.data(), x.size()); + rng.get(coefficients.data(), coefficients.size()); + x[0] = oc::ZeroBlock; + x[1] = oc::toBlock(1); + details::paxosDenseGF128Eight(x.data(), coefficients.data(), count, out.data()); + for (unsigned i=0; i<8; ++i) + { + block expected=oc::ZeroBlock, power=x[i]; + for (u64 j=0; j input, values; + const std::array divisors{1,2,3,7,64,65521,0xffffffffULL,0x100000001ULL, + 0x8000000000000000ULL,0x8000000000000001ULL,0xffffffffffffffc5ULL,0xffffffffffffffffULL}; + for (unsigned trial=0; trial<1000; ++trial) + { + auto divisor=trial()|1; + auto divider=libdivide::libdivide_u64_gen(divisor); + rng.get(input.data(),input.size()); + input[0]=0;input[1]=divisor-1;input[2]=divisor;input[3]=~u64(0); + values=input; + doMod32(values.data(),÷r,divisor); + for (unsigned i=0;i<32;++i) + if(values[i]!=input[i]%divisor) throw std::runtime_error("SIMD remainder mismatch"); + } +} + +void Baxos_dense_reference_Test(const oc::CLP&) +{ + PRNG rng(oc::toBlock(0xabcdef)); + for (u64 ssp : {20,40,80}) for (u64 weight : {2,3,4,5}) + { + constexpr u64 n=2051; + Baxos b;b.init(n,300,weight,ssp,PaxosParam::GF128,rng.get()); + std::vector keys(n), values(n), table(b.size()), queries(545), out(545), expected(545); + rng.get(keys.data(),n);rng.get(values.data(),n);rng.get(queries.data(),queries.size()); + std::copy_n(keys.data(),33,queries.data()); + for (bool randomized : {false,true}) + { + b.solve(keys,values,table,randomized?&rng:nullptr,2); + PaxosHash hasher;hasher.init(b.mSeed,weight,b.mPaxosParam.mSparseSize); + oc::AES aes(b.mSeed); + std::array row; + for (u64 i=0;i(span(queries).subspan(0,count),span(out).subspan(0,count),table,threads); + for(u64 i=0;i(span(queries).subspan(0,count),span(out).subspan(0,count),table,threads); + for(u64 i=0;i keys(8193), values(keys.size()), out(keys.size()); + input.get(keys.data(),keys.size()); input.get(values.data(),values.size()); + for (auto dt : {PaxosParam::GF128,PaxosParam::Binary}) for(u64 threads : {2,3}) + { + Baxos b;b.init(keys.size(),512,3,40,dt,oc::ZeroBlock); + std::vector reference(b.size()), result(b.size()); + block next; + for (unsigned trial=0;trial<4;++trial) + { + PRNG rng(oc::toBlock(123456)); + b.solve(keys,values,result,&rng,threads); + auto after=rng.get(); + if (trial==0) {reference=result;next=after;} + else if(result!=reference || after!=next) + throw std::runtime_error("parallel randomized encoding depends on worker scheduling"); + b.decode(keys,out,result,threads); + if(out!=values) throw std::runtime_error("parallel randomized encode mismatch"); + } + } +} diff --git a/tests/Paxos_Tests.h b/tests/Paxos_Tests.h index a8b8e70..f1bb922 100644 --- a/tests/Paxos_Tests.h +++ b/tests/Paxos_Tests.h @@ -32,3 +32,8 @@ void Baxos_idxtype_sentinel_and_params_Test(const oc::CLP& cmd); void Paxos_experiment(const oc::CLP& cmd); +void Paxos_dense_kernel_Test(const oc::CLP& cmd); +void Paxos_mod32_Test(const oc::CLP& cmd); +void Baxos_dense_reference_Test(const oc::CLP& cmd); + +void Baxos_randomized_parallel_determinism_Test(const oc::CLP& cmd); diff --git a/tests/Ribbon_Tests.cpp b/tests/Ribbon_Tests.cpp new file mode 100644 index 0000000..fd63ebf --- /dev/null +++ b/tests/Ribbon_Tests.cpp @@ -0,0 +1,125 @@ +#include "Ribbon_Tests.h" +#include "Common.h" +#include "volePSI/RsPsi.h" +#include +#include +#include + +using namespace volePSI; +using namespace oc; + +namespace { + // Independent, scalar row construction and evaluation. No shared mask, + // sorting, elimination, or SIMD decoder implementation. + block reference(block key,oc::span table,const RibbonParams& params,block seed) + { + PRNG prng(seed); + AES startHash(prng.get()); + const u64 starts=params.columns-params.width+1; + u64 x=startHash.hashBlock(key).get(0),attempt=0; + while(x<(u64(0)-starts)%starts) + x=startHash.hashBlock(key^toBlock(++attempt,0x72656a656374ULL)).get(0); + const u64 start=x%starts; + block result=ZeroBlock; + for(unsigned j=0;j()).hashBlock(key); + for(unsigned bit=0;bit<128 && j+bit(bit/64)>>(bit%64))&1) result^=table[start+j+bit]; + } + return result; + } +} + +void Ribbon_okvs_test(const CLP&) +{ + PRNG rng(toBlock(457,871)); + for(u64 ssp:{20,40,80,128}) + for(u64 n:{0,1,17,86,87,214,215,257,1001,4097,16385}) + { + auto seed=rng.get(); + RibbonOkvs code; + code.init(n,ssp,seed); + if(code.params().failureBits keys(n),vals(n),out(n),table(code.size()),a(code.size()),sum(code.size()); + rng.get(keys.data(),n);rng.get(vals.data(),n);rng.get(a.data(),a.size()); + for(bool randomized:{false,true}) + { + if(!code.solve(keys,vals,table,randomized?&rng:nullptr)) throw RTE_LOC; + code.decode(keys,out,table,3); + if(vals!=out) throw RTE_LOC; + } + // Queries include nonmembers, duplicate queries, single-query/tail + // calls and the real unpadded external-table contract. + std::vector queries(517),decoded(517),expected(517),other(517),combined(517); + rng.get(queries.data(),queries.size());queries.back()=queries.front(); + code.decode(queries,decoded,a); + for(u64 i=0;i=2) + { + keys[1]=keys[0]; + if(code.solve(keys,vals,table)) throw RTE_LOC; + } + } + auto large=RibbonParams::select(1ull<<20,40); + if(large.columns!=5*(1ull<<18) || large.width!=128 || large.failureBits<42) throw RTE_LOC; +} + +void Ribbon_protocol_test(const CLP&) +{ + PRNG rng(toBlock(891,33)); + for(bool malicious:{false,true}) + for(bool reduced:{false,true}) + for(u64 nt:{1,3}) + { + RsPsiSender sender; + RsPsiReceiver receiver; + sender.setOkvsType(OkvsType::Ribbon);receiver.setOkvsType(OkvsType::Ribbon); + // Reconfigure the same objects across dense and banded shapes. + for(u64 n:{1,37,257,4003}) + { + const u64 ns=n+9; + auto sockets=coproto::LocalAsyncSocket::makePair(); + std::vector send(ns),recv(n); + rng.get(send.data(),ns);rng.get(recv.data(),n); + send.back()=recv.back(); + sender.init(ns,n,40,rng.get(),malicious,nt,reduced); + receiver.init(ns,n,40,rng.get(),malicious,nt,reduced); + auto s=sender.run(send,sockets[0]);auto r=receiver.run(recv,sockets[1]); + eval(s,r); + if(receiver.mIntersection!=std::vector{n-1}) throw RTE_LOC; + } + } +} + +void Ribbon_failure_test(const CLP&) +{ + for(bool malicious:{false,true}) + { + RsOprfSender sender;RsOprfReceiver receiver; + sender.setOkvsType(OkvsType::Ribbon);receiver.setOkvsType(OkvsType::Ribbon); + sender.mMalicious=receiver.mMalicious=malicious; + auto sockets=coproto::LocalAsyncSocket::makePair(); + PRNG a(toBlock(11,22)),b(toBlock(33,44)); + std::vector duplicateKeys(37,ZeroBlock),out(37); + auto results=macoro::sync_wait(macoro::when_all_ready( + sender.send(37,a,sockets[0]),receiver.receive(duplicateKeys,out,b,sockets[1]))); + unsigned failed=0; + try {std::get<0>(results).result();} catch(const std::runtime_error& e) { + if(std::string(e.what())!="Ribbon OKVS encoding failed") throw; + ++failed; + } + try {std::get<1>(results).result();} catch(const std::runtime_error& e) { + if(std::string(e.what())!="Ribbon OKVS encoding failed") throw; + ++failed; + } + if(failed!=2) throw RTE_LOC; + } +} diff --git a/tests/Ribbon_Tests.h b/tests/Ribbon_Tests.h new file mode 100644 index 0000000..e9e19bc --- /dev/null +++ b/tests/Ribbon_Tests.h @@ -0,0 +1,5 @@ +#pragma once +#include +void Ribbon_okvs_test(const oc::CLP&); +void Ribbon_protocol_test(const oc::CLP&); +void Ribbon_failure_test(const oc::CLP&); diff --git a/tests/RsOprf_Tests.cpp b/tests/RsOprf_Tests.cpp index 308f59c..402f4d2 100644 --- a/tests/RsOprf_Tests.cpp +++ b/tests/RsOprf_Tests.cpp @@ -8,11 +8,232 @@ #include "Common.h" #include "cryptoTools/Crypto/MultiKeyAES.h" #include +#include "coproto/Socket/BufferingSocket.h" using coproto::LocalAsyncSocket; using namespace volePSI; using namespace oc; +namespace { +#ifdef _MSC_VER + __declspec(noinline) +#else + __attribute__((noinline)) +#endif + void verifySaltCommitment(block salt, const std::array& commitment) + { + std::array expected; + RandomOracle ro(32); + ro.Update(salt); + ro.Final(expected); + if (expected != commitment) throw RTE_LOC; + } + + // This peer deliberately waits for the salt without sending a correction. + // All SIMD work stays inside the ordinary library helpers. + Proto waitForSalt(RsOprfReceiver& receiver, Socket& sock, u64 columns, + bool ribbon, bool reduced, PRNG& rng, block& salt) + { + auto seed = block(12, 34); + auto wr = block(56, 78); + auto commitment = std::array{}; + auto fork = Socket{}; + auto success = u8{1}; + co_await sock.send(seed); + co_await sock.recv(commitment); + receiver.mVoleRecver.mSecurityType = SilentSecType::Malicious; + fork = sock.fork(); + co_await receiver.genVole(columns, rng, fork, reduced); + if (ribbon) co_await sock.send(success); + co_await sock.send(wr); + co_await sock.recv(salt); + verifySaltCommitment(salt, commitment); + } + + Proto sendCorrection(Socket& sock, volePSI::span correction) + { + co_await sock.send(correction); + } + + // Ordinary helpers keep field/SIMD temporaries outside the peer coroutine. +#ifdef _MSC_VER + __declspec(noinline) +#else + __attribute__((noinline)) +#endif + std::vector universalTable(Baxos& code) + { + std::vector table(code.size(), ZeroBlock); + for (u64 b = 0; b != code.mNumBins; ++b) + table[b * code.mPaxosParam.size() + code.mPaxosParam.mSparseSize] = block(0, 1); + return table; + } + +#ifdef _MSC_VER + __declspec(noinline) +#else + __attribute__((noinline)) +#endif + void maskCorrection(std::vector& table, volePSI::span c) + { + for (u64 i = 0; i != table.size(); ++i) table[i] ^= c[i]; + } + + // Declare n inputs, but send the universal-table candidate instead of + // encoding n labels. VOLE itself is followed honestly by this receiver. + Proto chosenSeedPeer(RsOprfReceiver& receiver, Baxos& code, + Socket& sock, PRNG& rng, bool reduced, block& w) + { + auto seed = code.mSeed; + auto commitment = std::array{}; + auto wr = block(56, 78); + auto ws = block{}; + auto fork = Socket{}; + auto table = universalTable(code); + co_await sock.send(seed); + co_await sock.recv(commitment); + receiver.mVoleRecver.mSecurityType = SilentSecType::Malicious; + fork = sock.fork(); + co_await receiver.genVole(table.size(), rng, fork, reduced); + maskCorrection(table, receiver.mVoleRecver.mC); + co_await sock.send(wr); + co_await sock.send(std::move(table)); + co_await sock.recv(ws); + verifySaltCommitment(ws, commitment); + w = ws ^ wr; + } +} + +void RsOprf_salt_order_test(const CLP&) +{ + for (auto backend : {OkvsType::Baxos, OkvsType::Ribbon}) + for (bool reduced : {false, true}) + { + RsOprfSender sender; + RsOprfReceiver receiver; + sender.setOkvsType(backend); + sender.mMalicious = true; + PRNG sRng(toBlock(719, 2)), rRng(toBlock(719, 3)); + coproto::BufferingSocket sSock, rSock; + auto s = sender.send(37, sRng, sSock, 1, reduced) | macoro::make_eager(); + block salt = ZeroBlock; + auto r = waitForSalt(receiver, rSock, sender.okvsSize(), + backend == OkvsType::Ribbon, reduced, rRng, salt) | macoro::make_eager(); + // Pump until quiescent, with a finite guard against a protocol loop. + for (unsigned round = 0; ; ++round) + { + if (round == 1000) throw RTE_LOC; + bool moved = false; + if (auto msg = rSock.getOutbound(); msg && !msg->empty()) { sSock.processInbound(*msg); moved = true; } + if (auto msg = sSock.getOutbound(); msg && !msg->empty()) { rSock.processInbound(*msg); moved = true; } + if (!moved) break; + } + const bool early = r.is_ready(); + std::vector correction(sender.okvsSize(), ZeroBlock); + auto c = sendCorrection(rSock, correction) | macoro::make_eager(); + auto wire = rSock.getOutbound(); + if (!wire || wire->size() < 2) throw RTE_LOC; + sSock.processInbound({wire->data(), wire->size() - 1}); + auto premature = sSock.getOutbound(); + if (premature) rSock.processInbound(*premature); + const bool partial = r.is_ready(); + sSock.processInbound({wire->data() + wire->size() - 1, 1}); + for (unsigned round = 0; round != 1000 && (!s.is_ready() || !r.is_ready() || !c.is_ready()); ++round) + { + if (auto msg = rSock.getOutbound()) sSock.processInbound(*msg); + if (auto msg = sSock.getOutbound()) rSock.processInbound(*msg); + } + if (!s.is_ready() || !r.is_ready() || !c.is_ready()) throw RTE_LOC; + macoro::sync_wait(s); macoro::sync_wait(r); macoro::sync_wait(c); + if (early || partial || (premature && !premature->empty())) throw RTE_LOC; + } +} + +void RsOprf_seed_rejection_test(const CLP&) +{ + const block labelKey = mAesFixedKey.getKey(); + for (u64 binSize : {128, 16384}) + for (bool reduced : {false, true}) + for (block seed : {labelKey, labelKey ^ block(0, 1)}) + { + constexpr u64 declared = 257, probes = 2003; + Baxos code; + code.init(declared, binSize, 3, 40, PaxosParam::GF128, seed); + PRNG rng(block(17, 91)), sRng(block(32, 19)), rRng(block(35, 21)); + std::vector keys(probes), labels(probes), decoded(probes); + rng.get(keys.data(), keys.size()); + mAesFixedKey.hashBlocks(keys, labels); + auto witness = universalTable(code); + code.decode(keys, decoded, witness); + const bool forbidden = seed == labelKey; + if (forbidden && decoded != labels) throw RTE_LOC; + + RsOprfSender sender; + RsOprfReceiver receiver; + sender.mMalicious = true; + sender.mBinSize = binSize; + auto sockets = LocalAsyncSocket::makePair(); + block w = ZeroBlock; + auto s = sender.send(declared, sRng, sockets[0], 1, reduced); + auto r = chosenSeedPeer(receiver, code, sockets[1], rRng, reduced, w); + auto done = macoro::sync_wait(macoro::when_all_ready(std::move(s), std::move(r))); + bool rejected = false; + try { std::get<0>(done).result(); } + catch (const std::invalid_argument& e) + { + if (std::string(e.what()) != "Baxos seed equals the OPRF label AES key") throw; + rejected = true; + } + bool peerFailed = false; + try { std::get<1>(done).result(); } + catch (const std::exception&) { if (!rejected) throw; peerFailed = true; } + if (rejected) + { + if (!forbidden || !peerFailed || !sender.mVoleSender.mB.empty()) throw RTE_LOC; + continue; + } + + // If a mutation removes the check, complete the real attack before + // failing: the receiver evaluates 2,003 keys after declaring only 257. + std::vector expected(probes), recovered(probes); + sender.eval(keys, expected); + code.decode(keys, recovered, receiver.mVoleRecver.mA); + u64 matches = 0; + for (u64 i = 0; i != probes; ++i) + { + recovered[i] = AES(recovered[i] ^ w).hashBlock(keys[i]); + matches += recovered[i] == expected[i]; + } + if (forbidden) + { + if (matches != probes) throw std::runtime_error("equal-seed attack reproduction failed"); + throw std::runtime_error("equal-seed attack accepted: 2003 OPRF outputs after declaring 257 inputs"); + } + // Control: a neighboring seed completes, but the same table no longer + // gives the attacker these outputs. This is a regression, not a proof. + if (matches != 0) throw RTE_LOC; + } +} + +void RsOprf_ribbon_seed_test(const CLP&) +{ + const block labelKey = mAesFixedKey.getKey(); + for(u64 n : {37, 257, 4097}) + { + RibbonOkvs code; + code.init(n, 40, ZeroBlock); + if(code.labelKeyIndependent(labelKey, labelKey)) throw RTE_LOC; + for(block seed : {ZeroBlock, labelKey ^ block(0, 1), block(17, 43)}) + { + PRNG rng(seed); + bool expected = seed != labelKey; + for(unsigned i=0, count=1+(code.params().width+127)/128; i() != labelKey; + if(code.labelKeyIndependent(seed, labelKey) != expected) throw RTE_LOC; + } + } +} + void RsOprf_multiKeyAES_test(const CLP&) { PRNG prng(block(0, 17)); diff --git a/tests/RsOprf_Tests.h b/tests/RsOprf_Tests.h index 6ea431a..47c683a 100644 --- a/tests/RsOprf_Tests.h +++ b/tests/RsOprf_Tests.h @@ -12,4 +12,7 @@ void RsOprf_eval_test(const oc::CLP&); void RsOprf_multiKeyAES_test(const oc::CLP&); void RsOprf_mal_test(const oc::CLP&); +void RsOprf_salt_order_test(const oc::CLP&); +void RsOprf_seed_rejection_test(const oc::CLP&); +void RsOprf_ribbon_seed_test(const oc::CLP&); void RsOprf_reduced_test(const oc::CLP&); diff --git a/tests/UnitTests.cpp b/tests/UnitTests.cpp index e5adc88..3f8d585 100644 --- a/tests/UnitTests.cpp +++ b/tests/UnitTests.cpp @@ -6,6 +6,7 @@ #include "Paxos_Tests.h" #include "RsOprf_Tests.h" +#include "Ribbon_Tests.h" #include "RsOpprf_Tests.h" #include "RsPsi_Tests.h" #include "RsCpsi_Tests.h" @@ -18,6 +19,10 @@ namespace volePSI_Tests using namespace volePSI; oc::TestCollection Tests([](oc::TestCollection& t) { + t.add("Baxos_randomized_parallel_determinism_Test", Baxos_randomized_parallel_determinism_Test); + t.add("Paxos_dense_kernel_Test", Paxos_dense_kernel_Test); + t.add("Paxos_mod32_Test", Paxos_mod32_Test); + t.add("Baxos_dense_reference_Test", Baxos_dense_reference_Test); t.add("Paxos_buildRow_Test ", Paxos_buildRow_Test); t.add("Paxos_solve_Test ", Paxos_solve_Test); t.add("Paxos_solve_u8_Test ", Paxos_solve_u8_Test); @@ -58,9 +63,15 @@ namespace volePSI_Tests t.add("Gmw_add_test ", Gmw_add_test); #endif + t.add("Ribbon_okvs_test", Ribbon_okvs_test); + t.add("Ribbon_protocol_test", Ribbon_protocol_test); + t.add("Ribbon_failure_test", Ribbon_failure_test); t.add("RsOprf_eval_test ", RsOprf_eval_test); t.add("RsOprf_multiKeyAES_test ", RsOprf_multiKeyAES_test); t.add("RsOprf_mal_test ", RsOprf_mal_test); + t.add("RsOprf_salt_order_test", RsOprf_salt_order_test); + t.add("RsOprf_seed_rejection_test", RsOprf_seed_rejection_test); + t.add("RsOprf_ribbon_seed_test", RsOprf_ribbon_seed_test); t.add("RsOprf_reduced_test ", RsOprf_reduced_test); #ifdef VOLE_PSI_ENABLE_OPPRF diff --git a/volePSI/CMakeLists.txt b/volePSI/CMakeLists.txt index 654d217..d106eb9 100644 --- a/volePSI/CMakeLists.txt +++ b/volePSI/CMakeLists.txt @@ -4,6 +4,7 @@ configure_file(config.h.in "config.h" ) set(SRCS "RsOprf.cpp" + "RibbonOkvs.cpp" "RsPsi.cpp" "SimpleIndex.cpp" "fileBased.cpp" diff --git a/volePSI/PaxosGf128.h b/volePSI/PaxosGf128.h new file mode 100644 index 0000000..1705f91 --- /dev/null +++ b/volePSI/PaxosGf128.h @@ -0,0 +1,94 @@ +#pragma once +#include "volePSI/Defines.h" + +// VOLEPSI_PAXOS_FORCE_SCALAR selects the block backend for validation. +namespace volePSI::details +{ +#if !defined(VOLEPSI_PAXOS_FORCE_SCALAR) && defined(OC_ENABLE_PCLMUL) && defined(__VPCLMULQDQ__) && defined(__AVX512F__) && defined(__AVX512BW__) + inline __m512i paxosMulGF128(__m512i x, __m512i y) + { + auto lo = _mm512_clmulepi64_epi128(x, y, 0x00); + auto hi = _mm512_clmulepi64_epi128(x, y, 0x11); + auto mid = _mm512_xor_si512(_mm512_clmulepi64_epi128(x, y, 0x01), + _mm512_clmulepi64_epi128(x, y, 0x10)); + lo = _mm512_xor_si512(lo, _mm512_bslli_epi128(mid, 8)); + hi = _mm512_xor_si512(hi, _mm512_bsrli_epi128(mid, 8)); + const auto modulus = _mm512_set1_epi64(0x87); + auto t = _mm512_clmulepi64_epi128(hi, modulus, 0x01); + lo = _mm512_xor_si512(lo, _mm512_bslli_epi128(t, 8)); + hi = _mm512_xor_si512(hi, _mm512_bsrli_epi128(t, 8)); + return _mm512_xor_si512(lo, _mm512_clmulepi64_epi128(hi, modulus, 0x00)); + } +#elif !defined(VOLEPSI_PAXOS_FORCE_SCALAR) && defined(OC_ENABLE_PCLMUL) && defined(__VPCLMULQDQ__) && defined(__AVX2__) + inline __m256i paxosMulGF128(__m256i x, __m256i y) + { + auto lo = _mm256_clmulepi64_epi128(x, y, 0x00); + auto hi = _mm256_clmulepi64_epi128(x, y, 0x11); + auto mid = _mm256_xor_si256(_mm256_clmulepi64_epi128(x, y, 0x01), + _mm256_clmulepi64_epi128(x, y, 0x10)); + lo = _mm256_xor_si256(lo, _mm256_slli_si256(mid, 8)); + hi = _mm256_xor_si256(hi, _mm256_srli_si256(mid, 8)); + const auto modulus = _mm256_set1_epi64x(0x87); + auto t = _mm256_clmulepi64_epi128(hi, modulus, 0x01); + lo = _mm256_xor_si256(lo, _mm256_slli_si256(t, 8)); + hi = _mm256_xor_si256(hi, _mm256_srli_si256(t, 8)); + return _mm256_xor_si256(lo, _mm256_clmulepi64_epi128(hi, modulus, 0x00)); + } +#endif + + // Evaluate p[0]*x + ... + p[count-1]*x^count, count >= 1. + // Horner uses count multiplications instead of 2*count-1. + inline block paxosDenseGF128(block x, const block* p, u64 count) + { + block a = p[count-1]; + for (u64 j=count-1; j; --j) a = a.gf128Mul(x) ^ p[j-1]; + return a.gf128Mul(x); + } + + inline void paxosDenseGF128Eight(const block* x, const block* p, u64 count, block* out) + { +#if !defined(VOLEPSI_PAXOS_FORCE_SCALAR) && defined(OC_ENABLE_PCLMUL) && defined(__VPCLMULQDQ__) && defined(__AVX512F__) && defined(__AVX512BW__) + auto x0 = _mm512_loadu_si512(x), x1 = _mm512_loadu_si512(x+4); + auto a = _mm512_broadcast_i32x4(p[count-1]), b = a; + for (u64 j=count-1; j; --j) + { + auto c = _mm512_broadcast_i32x4(p[j-1]); + a = _mm512_xor_si512(paxosMulGF128(a, x0), c); + b = _mm512_xor_si512(paxosMulGF128(b, x1), c); + } + _mm512_storeu_si512(out, paxosMulGF128(a, x0)); + _mm512_storeu_si512(out+4, paxosMulGF128(b, x1)); +#elif !defined(VOLEPSI_PAXOS_FORCE_SCALAR) && defined(OC_ENABLE_PCLMUL) && defined(__VPCLMULQDQ__) && defined(__AVX2__) + auto x0 = _mm256_loadu_si256(reinterpret_cast(x)); + auto x1 = _mm256_loadu_si256(reinterpret_cast(x+2)); + auto x2 = _mm256_loadu_si256(reinterpret_cast(x+4)); + auto x3 = _mm256_loadu_si256(reinterpret_cast(x+6)); + auto a = _mm256_broadcastsi128_si256(p[count-1]), b=a, c=a, d=a; + for (u64 j=count-1; j; --j) + { + auto v = _mm256_broadcastsi128_si256(p[j-1]); + a = _mm256_xor_si256(paxosMulGF128(a, x0), v); + b = _mm256_xor_si256(paxosMulGF128(b, x1), v); + c = _mm256_xor_si256(paxosMulGF128(c, x2), v); + d = _mm256_xor_si256(paxosMulGF128(d, x3), v); + } + _mm256_storeu_si256(reinterpret_cast<__m256i*>(out), paxosMulGF128(a, x0)); + _mm256_storeu_si256(reinterpret_cast<__m256i*>(out+2), paxosMulGF128(b, x1)); + _mm256_storeu_si256(reinterpret_cast<__m256i*>(out+4), paxosMulGF128(c, x2)); + _mm256_storeu_si256(reinterpret_cast<__m256i*>(out+6), paxosMulGF128(d, x3)); +#else + block a=p[count-1],b=a,c=a,d=a,e=a,f=a,g=a,h=a; + for (u64 j=count-1; j; --j) + { + a=a.gf128Mul(x[0])^p[j-1]; b=b.gf128Mul(x[1])^p[j-1]; + c=c.gf128Mul(x[2])^p[j-1]; d=d.gf128Mul(x[3])^p[j-1]; + e=e.gf128Mul(x[4])^p[j-1]; f=f.gf128Mul(x[5])^p[j-1]; + g=g.gf128Mul(x[6])^p[j-1]; h=h.gf128Mul(x[7])^p[j-1]; + } + out[0]=a.gf128Mul(x[0]); out[1]=b.gf128Mul(x[1]); + out[2]=c.gf128Mul(x[2]); out[3]=d.gf128Mul(x[3]); + out[4]=e.gf128Mul(x[4]); out[5]=f.gf128Mul(x[5]); + out[6]=g.gf128Mul(x[6]); out[7]=h.gf128Mul(x[7]); +#endif + } +} diff --git a/volePSI/PaxosImpl.h b/volePSI/PaxosImpl.h index 8295eae..07f57fd 100644 --- a/volePSI/PaxosImpl.h +++ b/volePSI/PaxosImpl.h @@ -9,6 +9,7 @@ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +#include "volePSI/PaxosGf128.h" #include #include #include @@ -266,8 +267,56 @@ namespace volePSI } #endif +#ifdef ENABLE_SSE + inline __m256i paxosMullo64(__m256i x, __m256i y) + { +#if defined(__AVX512DQ__) && defined(__AVX512VL__) + return _mm256_mullo_epi64(x, y); +#else + auto lo = _mm256_mul_epu32(x, y); + auto cross = _mm256_add_epi64( + _mm256_mul_epu32(_mm256_srli_epi64(x, 32), y), + _mm256_mul_epu32(x, _mm256_srli_epi64(y, 32))); + return _mm256_add_epi64(lo, _mm256_slli_epi64(cross, 32)); +#endif + } +#endif + inline void doMod32(u64* vals, const libdivide::libdivide_u64_t* divider, const u64& modVal) { + // Exact remainder for power-of-two bin counts, including one bin. + if (modVal && (modVal & (modVal - 1)) == 0) + { + const auto mask = modVal - 1; + for (unsigned i = 0; i < 32; i += 8) + { + vals[i+0] &= mask; vals[i+1] &= mask; + vals[i+2] &= mask; vals[i+3] &= mask; + vals[i+4] &= mask; vals[i+5] &= mask; + vals[i+6] &= mask; vals[i+7] &= mask; + } + return; + } + +#ifdef ENABLE_SSE + const auto modulus = _mm256_set1_epi64x(modVal); + for (unsigned i = 0; i < 32; i += 16) + { + auto a = _mm256_loadu_si256(reinterpret_cast(vals+i)); + auto b = _mm256_loadu_si256(reinterpret_cast(vals+i+4)); + auto c = _mm256_loadu_si256(reinterpret_cast(vals+i+8)); + auto d = _mm256_loadu_si256(reinterpret_cast(vals+i+12)); + auto qa = my_libdivide_u64_do_vec256(a, divider); + auto qb = my_libdivide_u64_do_vec256(b, divider); + auto qc = my_libdivide_u64_do_vec256(c, divider); + auto qd = my_libdivide_u64_do_vec256(d, divider); + _mm256_storeu_si256(reinterpret_cast<__m256i*>(vals+i), _mm256_sub_epi64(a, paxosMullo64(qa, modulus))); + _mm256_storeu_si256(reinterpret_cast<__m256i*>(vals+i+4), _mm256_sub_epi64(b, paxosMullo64(qb, modulus))); + _mm256_storeu_si256(reinterpret_cast<__m256i*>(vals+i+8), _mm256_sub_epi64(c, paxosMullo64(qc, modulus))); + _mm256_storeu_si256(reinterpret_cast<__m256i*>(vals+i+12), _mm256_sub_epi64(d, paxosMullo64(qd, modulus))); + } +#else + @@ -333,6 +382,7 @@ namespace volePSI vals[i + 30] -= temp64h[2] * modVal; vals[i + 31] -= temp64h[3] * modVal; } +#endif } //inline void doMod32(u64* vals, const libdivide::libdivide_u64_branchfree_t* divider, const u64& modVal) @@ -658,10 +708,13 @@ namespace volePSI if (mWeight == 3) { - u32* rr = (u32*)&hash; - auto rr0 = *(u64*)(&rr[0]); - auto rr1 = *(u64*)(&rr[1]); - auto rr2 = *(u64*)(&rr[2]); + // The middle window starts four bytes into the hash. memcpy + // expresses the unaligned load without violating alignment/aliasing. + const auto* bytes = reinterpret_cast(&hash); + u64 rr0, rr1, rr2; + std::memcpy(&rr0, bytes, 8); + std::memcpy(&rr1, bytes+4, 8); + std::memcpy(&rr2, bytes+8, 8); row[0] = (IdxType)(rr0 % mSparseSize); row[1] = (IdxType)(rr1 % (mSparseSize - 1)); row[2] = (IdxType)(rr2 % (mSparseSize - 2)); @@ -774,14 +827,16 @@ namespace volePSI { mAllocation = {}; mAllocation.reset(new u8[size]); + mAllocationSize = size; } auto iter = mAllocation.get(); + // Lay out decreasing alignments; odd row counts must not misalign spans. mDense = initSpan(iter, mNumItems); + mCols = initSpan>(iter, mSparseSize); mRows = initMV(iter, mNumItems, mWeight); mColBacking = initSpan(iter, mNumItems * mWeight); - mCols = initSpan>(iter, mSparseSize); assert(iter == mAllocation.get() + size); } @@ -1142,19 +1197,34 @@ namespace volePSI mWeightSets.init(colWeights); } + // The XOR of live row indices gives the remaining row immediately + // when a column reaches weight one; avoid scanning its stale adjacency. + std::vector liveRows(mSparseSize); + for (u64 r=0; r(r); + std::vector rowSet(mNumItems); while (mWeightSets.mWeightSets.size() > 1) { auto& col = mWeightSets.getMinWeightNode(); + const auto weight = col.mWeight; mWeightSets.popNode(col); col.mWeight = 0; auto colIdx = mWeightSets.idxOf(col); bool first = true; + auto rowIndices = mCols[colIdx]; + IdxType singleton; + if (weight == 1) + { + singleton = liveRows[colIdx]; + rowIndices = span(&singleton, 1); + } + // iterate over all the rows in the next column - for (auto rowIdx : mCols[colIdx]) + for (auto rowIdx : rowIndices) { // check if this row has already been set. if (rowSet[rowIdx] == 0) @@ -1174,6 +1244,7 @@ namespace volePSI // decrement the weight. mWeightSets.popNode(node); + liveRows[colIdx2] ^= rowIdx; --node.mWeight; mWeightSets.pushNode(node); @@ -1691,6 +1762,35 @@ namespace volePSI helper.randomize(p2[i], *prng); } + if constexpr (std::is_same_v::Helper>) + { + const bool doDense = g || prng; + for (u64 k=0; k(8, mainRows.size()-k); + std::array dense, contribution; + if (doDense) + { + for (u64 j=0; j::Helper>) + { + if (mDt == DenseType::GF128) + { + const auto* table = p_[0]; + for (unsigned i=0; i<32; i+=8) + { + details::paxosDenseGF128Eight(dense_+i, table+mSparseSize, mDenseSize, values_+i); + if (mWeight == 3) + { + for (unsigned j=0; j<8; ++j) + { + const auto* r = rows_+(i+j)*3; + values_[i+j] ^= table[r[0]] ^ table[r[1]] ^ table[r[2]]; + } + } + else for (u64 k=0; k::Helper>) + { + *values ^= details::paxosDenseGF128(*dense, p[mSparseSize], mDenseSize); + return; + } + block x = *dense; h.multAdd(values, p[mSparseSize], x); @@ -2737,20 +2867,6 @@ namespace volePSI // keeps track of the size of each bin for each thread. Additional spaces to prevent false sharing Matrix thrdBinSizes(numThreads, mNumBins); - // keeps track of input index of each item in each bin,thread. - std::unique_ptr inputMapping(new u64[totalNumBins * perThrdMaxBinSize]); - - // for the given thread, bin, return the list which map the bin - // value back to the input value. - auto getInputMapping = [&](u64 thrdIdx, u64 binIdx) - { - auto binBegin = combinedMaxBinSize * binIdx; - auto thrdBegin = perThrdMaxBinSize * thrdIdx; - span mapping(inputMapping.get() + binBegin + thrdBegin, perThrdMaxBinSize); - assert(inputMapping.get() + totalNumBins * perThrdMaxBinSize >= mapping.data() + mapping.size()); - return mapping; - }; - auto valBacking = h.newVec(totalNumBins * perThrdMaxBinSize); // get the values mapped to the given bin by the given thread. @@ -2783,8 +2899,18 @@ namespace volePSI std::promise hashingDoneProm; auto hashingDoneFu = hashingDoneProm.get_future().share(); + // PRNG mutates its buffer and counters. Give each parallel worker an + // independently seeded stream; retain the exact single-thread stream. + std::vector workerPrngs; + if (prng && numThreads > 1) + { + workerPrngs.resize(numThreads); + for (auto& rng : workerPrngs) rng.SetSeed(prng->get()); + } + auto processBins = [&](u64 thrdIdx, bool& countedDone) { + auto binPrng = workerPrngs.empty() ? prng : &workerPrngs[thrdIdx]; auto begin = (inputs_.size() * thrdIdx) / numThreads; auto end = (inputs_.size() * (thrdIdx + 1)) / numThreads; auto inputs = inputs_.subspan(begin, end - begin); @@ -2793,7 +2919,7 @@ namespace volePSI // hash all the inputs in my range [begin, end) into their bin. // Each thread will have its own set of bins. ie a total of numThreads * numBins // bins in total. These bin will need to be merged. Each thread will also - // get its own reverse mapping. + // keep its own bin counters. { auto binSizes = thrdBinSizes[thrdIdx]; //auto hashes = span(hashes_.data() + begin, end - begin); @@ -2827,7 +2953,6 @@ namespace volePSI if (binSizes[binIdx] >= perThrdMaxBinSize) throw std::runtime_error("Baxos per-thread bin overflow" LOCATION); auto bs = binSizes[binIdx]++; - getInputMapping(thrdIdx, binIdx)[bs] = inIdx; h.assign(getValues(thrdIdx, binIdx)[bs], vals_[inIdx]); getHashes(thrdIdx, binIdx)[bs] = hashes[k]; } @@ -2842,9 +2967,6 @@ namespace volePSI throw std::runtime_error("Baxos per-thread bin overflow" LOCATION); auto bs = binSizes[binIdx]++; - if (inIdx == 9355778) - std::cout << "in " << inIdx << " -> bin " << binIdx << " @ " << bs << std::endl; - getInputMapping(thrdIdx, binIdx)[bs] = inIdx; h.assign(getValues(thrdIdx, binIdx)[bs], vals_[inIdx]); getHashes(thrdIdx, binIdx)[bs] = hashes[k]; } @@ -2892,10 +3014,11 @@ namespace volePSI auto iter = allocation.get(); //span hashes = initSpan(iter, binSize); + // Put pointer-aligned spans ahead of the narrower index arrays. + span> cols = initSpan>(iter, mPaxosParam.mSparseSize); MatrixView rows = initMV(iter, binSize, mWeight); span colBacking = initSpan(iter, binSize * mWeight); span colWeights = initSpan(iter, mPaxosParam.mSparseSize); - span> cols = initSpan>(iter, mPaxosParam.mSparseSize); if (iter > allocation.get() + allocSize) throw RTE_LOC; @@ -2986,7 +3109,7 @@ namespace volePSI } paxos.setInput(rows, hashes, cols, colBacking, colWeights); - paxos.encode(values, output, h, prng); + paxos.encode(values, output, h, binPrng); } }; diff --git a/volePSI/RibbonKernels.h b/volePSI/RibbonKernels.h new file mode 100644 index 0000000..c7fcb4e --- /dev/null +++ b/volePSI/RibbonKernels.h @@ -0,0 +1,548 @@ +#pragma once + +// Random-band OKVS kernels. The rank bound models start/coefficient hashes +// as independent random functions; AES hashing is the concrete instantiation. +// Rows have fully random coefficients, including the leading bit. +#include +#include +#include +#include +#include +#include +#include +#include +#if defined(__AVX2__) || defined(_MSC_VER) && defined(_M_X64) +#include +#endif +#include +#include +#include +#ifdef __linux__ +#include +#endif + +namespace volePSI::ribbon_detail { +#ifndef RIBBON_DOT +#define RIBBON_DOT 2 +#endif +#ifndef RIBBON_HUGE_PAGES +#define RIBBON_HUGE_PAGES 1 +#endif +#ifndef RIBBON_FORWARDING +#define RIBBON_FORWARDING 1 +#endif +#ifndef RIBBON_RADIX_BITS +#define RIBBON_RADIX_BITS 11 +#endif +#ifndef RIBBON_BATCH +#define RIBBON_BATCH 8 +#endif +#ifndef RIBBON_DIRECT_PIVOTS +#define RIBBON_DIRECT_PIVOTS 0 +#endif +// Large scratch buffers are aligned for optional transparent huge pages. +// Default construction deliberately leaves trivial elements uninitialized; +// every read is preceded by an explicit write. No global VM setting changes. +template struct BufferAllocator { + using value_type=T; + BufferAllocator()=default; + template BufferAllocator(const BufferAllocator&) noexcept {} + static std::size_t alignment(std::size_t bytes) { + return RIBBON_HUGE_PAGES && bytes>=2*1024*1024 ? 2*1024*1024 : std::max(16,alignof(T)); + } + T* allocate(std::size_t n) { + if(n>std::size_t(-1)/sizeof(T)) throw std::bad_array_new_length(); + auto bytes=n*sizeof(T),align=alignment(bytes); + auto p=static_cast(::operator new(bytes,std::align_val_t(align))); +#if defined(__linux__) && RIBBON_HUGE_PAGES + if(align==2*1024*1024) (void)madvise(p,bytes/(2*1024*1024)*(2*1024*1024),MADV_HUGEPAGE); +#endif + return p; + } + void deallocate(T* p,std::size_t n) noexcept {::operator delete(p,std::align_val_t(alignment(n*sizeof(T))));} + template void construct(U* p,Args&&... args) { + if constexpr(sizeof...(Args)==0) ::new(static_cast(p)) U; + else ::new(static_cast(p)) U(std::forward(args)...); + } + template bool operator==(const BufferAllocator&) const noexcept {return true;} +}; +template using Buffer=std::vector>; +using oc::block; +template inline void prefetch(const T* p) { +#if defined(__GNUC__) || defined(__clang__) + __builtin_prefetch(p,Writing?1:0,3); +#else + (void)p; +#endif +} +using Clock = std::chrono::steady_clock; +inline double elapsed(Clock::time_point t) { + return std::chrono::duration(Clock::now()-t).count(); +} +struct Timings { + double init=0, starts=0, sort=0, coefficients=0, eliminate=0, backsolve=0, total=0; + std::uint64_t additions=0; +}; +struct Entry { std::uint32_t start, index; }; +enum class Order { sorted, bucket, direct, shared }; + +template +[[gnu::noinline]] inline void orderEntries(std::vector& entries, Order mode) { + if(mode==Order::direct) return; + std::vector temp(entries.size()); + if(mode==Order::bucket) { + std::uint32_t max=0; + for(auto e:entries) max=std::max(max,e.start>>12); + std::vector count(max+1); + for(auto e:entries) ++count[e.start>>12]; + std::size_t sum=0; + for(auto& c:count) { auto old=c; c=sum; sum+=old; } + for(auto e:entries) temp[count[e.start>>12]++]=e; + entries.swap(temp); + return; + } + // Small radix buckets keep active scatter destinations in L1. + std::uint32_t max=0; + for(auto e:entries) max=std::max(max,e.start); + constexpr unsigned buckets=1u< low{},high{}; + for(auto e:entries) {++low[e.start&2047];++high[e.start>>11];} + std::uint32_t a=0,b=0; + for(unsigned j=0;j<2048;++j) { + auto x=low[j],y=high[j];low[j]=a;high[j]=b;a+=x;b+=y; + } + for(auto e:entries) temp[low[e.start&2047]++]=e; + for(auto e:temp) entries[high[e.start>>11]++]=e; + return; + } + } + for(unsigned shift=0;shift<32 && (max>>shift);shift+=RIBBON_RADIX_BITS) { + std::array count{}; + for(auto e:entries) ++count[(e.start>>shift)&(buckets-1)]; + std::size_t sum=0; + for(auto& c:count) { auto old=c;c=sum;sum+=old; } + for(auto e:entries) temp[count[(e.start>>shift)&(buckets-1)]++]=e; + entries.swap(temp); + } +} + +template struct Mask { + static_assert(W && W % 16 == 0); + static constexpr unsigned words=(W+63)/64; + std::array v; + bool empty() const { + std::uint64_t z=0; + #pragma GCC unroll 16 + for(unsigned i=0;i>bits)|(v[i+1]<<(64-bits)); + v[words-1]>>=bits; + } + return whole+bits; + } +}; + +#if defined(__AVX512F__) && defined(__AVX512VL__) && defined(__AVX512DQ__) && defined(__BMI2__) && !defined(VOLEPSI_RIBBON_PORTABLE) +inline block reduce(__m512i x) { + auto lo=_mm256_xor_si256(_mm512_castsi512_si256(x), _mm512_extracti64x4_epi64(x,1)); + return block(_mm_xor_si128(_mm256_castsi256_si128(lo),_mm256_extracti128_si256(lo,1))); +} +template inline block dot(const Mask& mask, const block* cells) { + [[maybe_unused]] static constexpr unsigned char lane[16]={0,3,12,15,48,51,60,63,192,195,204,207,240,243,252,255}; + __m512i a=_mm512_setzero_si512(), b=a, c=a, d=a; + #pragma GCC unroll 16 + for(unsigned k=0;k::words;++k) { + auto bits=mask.v[k]; +#if RIBBON_DOT == 2 + #pragma GCC unroll 2 + for(unsigned half=0;half<2 && k*64+half*32>(half*32),0x5555555555555555ULL); + auto masks=spread|(spread<<1); + #pragma GCC unroll 2 + for(unsigned j=0;j<32 && k*64+half*32+j>(2*j)),a,_mm512_loadu_si512(p)); + b=_mm512_mask_xor_epi64(b,__mmask8(masks>>(2*j+8)),b,_mm512_loadu_si512(p+4)); + c=_mm512_mask_xor_epi64(c,__mmask8(masks>>(2*j+16)),c,_mm512_loadu_si512(p+8)); + d=_mm512_mask_xor_epi64(d,__mmask8(masks>>(2*j+24)),d,_mm512_loadu_si512(p+12)); + } + } +#else + #pragma GCC unroll 4 + for(unsigned j=0;j<64 && k*64+j>j)&15],a,_mm512_loadu_si512(cells+k*64+j)); + b=_mm512_mask_xor_epi64(b,lane[(bits>>(j+4))&15],b,_mm512_loadu_si512(cells+k*64+j+4)); + c=_mm512_mask_xor_epi64(c,lane[(bits>>(j+8))&15],c,_mm512_loadu_si512(cells+k*64+j+8)); + d=_mm512_mask_xor_epi64(d,lane[(bits>>(j+12))&15],d,_mm512_loadu_si512(cells+k*64+j+12)); +#else + a=_mm512_xor_si512(a,_mm512_maskz_loadu_epi64(lane[(bits>>j)&15],cells+k*64+j)); + b=_mm512_xor_si512(b,_mm512_maskz_loadu_epi64(lane[(bits>>(j+4))&15],cells+k*64+j+4)); + c=_mm512_xor_si512(c,_mm512_maskz_loadu_epi64(lane[(bits>>(j+8))&15],cells+k*64+j+8)); + d=_mm512_xor_si512(d,_mm512_maskz_loadu_epi64(lane[(bits>>(j+12))&15],cells+k*64+j+12)); +#endif + } +#endif + } + auto result=reduce(_mm512_xor_si512(_mm512_xor_si512(a,b),_mm512_xor_si512(c,d))); + if constexpr(Forwarding && RIBBON_DOT==2) { + // Exact-width loads can forward the most recent 16-byte stores. + // A 64-byte load overlapping those stores incurs a forwarding stall. + __m128i prefix=_mm_setzero_si128(); + #pragma GCC unroll 4 + for(unsigned j=0;j<4;++j) + prefix=_mm_mask_xor_epi64(prefix,__mmask8(((mask.v[0]>>j)&1)*3),prefix, + _mm_loadu_si128(reinterpret_cast(cells+j))); + result^=block(prefix); + } + return result; +} +#else +template inline block dot(const Mask& mask, const block* cells) { + block result=oc::ZeroBlock; + for(unsigned k=0;k::words;++k) { + auto bits=mask.v[k]; + while(bits) { + result^=cells[k*64+std::countr_zero(bits)]; + bits&=bits-1; + } + } + return result; +} +#endif +#if defined(__GFNI__) && defined(__AVX512VBMI__) && !defined(VOLEPSI_RIBBON_PORTABLE) +// Transpose each 8x8 bit matrix within its 64-bit lane. GFNI numbers +// matrix rows in reverse byte order, so reverse the bytes after transposing. +inline __m512i gfniMatrix(__m512i x) { + auto t=_mm512_and_si512(_mm512_xor_si512(x,_mm512_srli_epi64(x,7)),_mm512_set1_epi64(0x00aa00aa00aa00aaULL)); + x=_mm512_xor_si512(x,_mm512_xor_si512(t,_mm512_slli_epi64(t,7))); + t=_mm512_and_si512(_mm512_xor_si512(x,_mm512_srli_epi64(x,14)),_mm512_set1_epi64(0x0000cccc0000ccccULL)); + x=_mm512_xor_si512(x,_mm512_xor_si512(t,_mm512_slli_epi64(t,14))); + t=_mm512_and_si512(_mm512_xor_si512(x,_mm512_srli_epi64(x,28)),_mm512_set1_epi64(0x00000000f0f0f0f0ULL)); + x=_mm512_xor_si512(x,_mm512_xor_si512(t,_mm512_slli_epi64(t,28))); + return _mm512_shuffle_epi8(x,_mm512_set4_epi64(0x08090a0b0c0d0e0fULL,0x0001020304050607ULL,0x08090a0b0c0d0e0fULL,0x0001020304050607ULL)); +} +inline void gfniTableChunk(const block* cells,block* result) { + alignas(64) std::array low,high; + for(unsigned byte=0;byte<8;++byte) for(unsigned q=0;q<8;++q) { + low[byte*8+q]=q*16+byte;high[byte*8+q]=q*16+byte+8; + } + auto il=_mm512_load_si512(low.data()),ih=_mm512_load_si512(high.data()); + auto a=_mm512_loadu_si512(cells),b=_mm512_loadu_si512(cells+4); + _mm512_storeu_si512(result,gfniMatrix(_mm512_permutex2var_epi8(a,il,b))); + _mm512_storeu_si512(result+4,gfniMatrix(_mm512_permutex2var_epi8(a,ih,b))); +} +// Eight queries share each pair of table loads and two GFNI instructions. +// All starts must be within 32 cells of the eight-cell-aligned anchor. +// The table pointer starts at that anchor and covers W+32 cells. +template inline void gfniDot(const Mask* masks,const Entry* entries, + const block* table,block* values) { + auto anchor=entries[0].start&~7u; + alignas(64) std::uint64_t shifted[Mask::words][8]; + #pragma GCC unroll 8 + for(unsigned q=0;q<8;++q) { + auto shift=entries[q].start-anchor; + #pragma GCC unroll 16 + for(unsigned k=0;k::words;++k) { + auto lo=k::words?masks[q].v[k]:0; + auto hi=k?masks[q].v[k-1]:0; + shifted[k][q]=(lo<>(64-shift):0); + } + } + __m512i a=_mm512_setzero_si512(),b=a; + auto pack=_mm512_set1_epi64(0x3830282018100800ULL); + #pragma GCC unroll 16 + for(unsigned k=0;k::words;++k) { + auto coefficients=_mm512_load_si512(shifted[k]); + #pragma GCC unroll 8 + for(unsigned j=0;j<64 && k*64+j low,high; + for(unsigned q=0;q<4;++q) for(unsigned byte=0;byte<16;++byte) { + low[q*16+byte]=byte*8+q;high[q*16+byte]=byte*8+q+4; + } + auto x=_mm512_permutex2var_epi8(a,_mm512_load_si512(low.data()),b); + auto y=_mm512_permutex2var_epi8(a,_mm512_load_si512(high.data()),b); + #pragma GCC unroll 4 + for(unsigned q=0;q<4;++q) { + values[entries[q].index]=block(_mm512_extracti32x4_epi32(x,q)); + values[entries[q+4].index]=block(_mm512_extracti32x4_epi32(y,q)); + } +} + +#endif + +template block scalarDot(const Mask& mask, const block* cells) { + block r=oc::ZeroBlock; + for(unsigned k=0;k::words;++k) { + auto bits=mask.v[k]; + while(bits) { + r^=cells[k*64+std::countr_zero(bits)]; + bits&=bits-1; + } + } + return r; +} + +template class Ribbon { +public: + using M=Mask; + struct Row { M mask; block value; }; + struct Query { Entry entry; M mask; }; + std::uint32_t columns, starts; + oc::AES startHash; + std::array coefficientHash; + explicit Ribbon(std::uint32_t m, block seed) : columns(m), starts(m-W+1) { + if(m()); + for(auto& h:coefficientHash) h.setKey(rng.get()); + } + + std::uint32_t start(block key, block hashed) const { + // Exact uniform reduction under ideal independent hashes. The rejection + // branch is exceedingly rare, but avoids a statistical modulo-bias claim. + std::uint64_t x=hashed.get(0); + std::uint64_t rejectionThreshold=(std::uint64_t(0)-starts)%starts; + std::uint64_t attempt=0; + while(x(0); + } + return x%starts; + } + void makeEntries(oc::span keys, oc::span entries) const { + std::size_t i=0; + for(;i+8<=keys.size();i+=8) { + std::array hashed; + startHash.template hashBlocks<8>(keys.data()+i,hashed.data()); + #pragma GCC unroll 8 + for(unsigned j=0;j<8;++j) entries[i+j]={start(keys[i+j],hashed[j]),std::uint32_t(i+j)}; + } + for(;i void coefficientBatches(oc::span keys, + oc::span entries,const block* valueBase,F&& consume) const { + constexpr unsigned batch=RIBBON_BATCH; + for(std::size_t i=0;i(keys.data()+index); + prefetch(valueBase+index); + } + } + unsigned size=std::min(batch,entries.size()-i); + std::array input, hashed; + if(size!=batch) std::fill(input.begin()+size,input.end(),oc::ZeroBlock); + std::array masks; + for(unsigned j=0;j(input.data(),hashed.data()); + #pragma GCC unroll 32 + for(unsigned j=0;j(0); + if(2*k+1(1); + } + } + for(unsigned j=0;j void queryBatches(oc::span keys,F&& consume) const { + for(std::size_t i=0;i(8,keys.size()-i); + std::array tail{}, hash, hashedStart; + const block* input=keys.data()+i; + if(size!=8) { std::copy_n(input,size,tail.data()); input=tail.data(); } + std::array masks; + startHash.template hashBlocks<8>(input,hashedStart.data()); + #pragma GCC unroll 8 + for(unsigned k=0;k<(W+127)/128;++k) { + coefficientHash[k].template hashBlocks<8>(input,hash.data()); + #pragma GCC unroll 8 + for(unsigned j=0;j<8;++j) { + masks[j].v[2*k]=hash[j].template get(0); + if(2*k+1(1); + } + } + std::array batch; + for(unsigned j=0;j keys, oc::span values, + oc::span cells, oc::PRNG* rng, Timings& time) const { + auto total=Clock::now(), t=total; + Buffer entries(keys.size()); + // Values live at their pivot column in the output table. +#if RIBBON_DIRECT_PIVOTS + Buffer pivots(columns); + for(auto& pivot:pivots) pivot.v[0]=0; +#else + Buffer rows(keys.size()); + Buffer pivots(columns,UINT32_MAX); +#endif + if(rng) rng->get(cells.data(),columns); + else std::fill(cells.begin(),cells.end(),oc::ZeroBlock); + time.init=elapsed(t); t=Clock::now(); + makeEntries(keys,entries); + time.starts=elapsed(t); t=Clock::now(); + orderEntries(entries,Order::sorted); + time.sort=elapsed(t); t=Clock::now(); + bool success=true; + coefficientBatches(keys,entries,values.data(),[&](std::size_t i,const M& inputMask) { + if(!success) return; + M mask=inputMask; + block value=values[entries[i].index]; + auto pos=entries[i].start; + for(;;) { + if(mask.empty()) {success=false;return;} + pos+=mask.normalize(); + if(pos>=columns) throw std::logic_error("pivot outside band"); + auto& pivot=pivots[pos]; +#if RIBBON_DIRECT_PIVOTS + // A stored row is normalized, so its low bit is always one. + if(pivot.v[0]==0) {pivot=mask;cells[pos]=value;break;} + mask.add(pivot); +#else + if(pivot==UINT32_MAX) { + pivot=std::uint32_t(i);rows[i]=mask;cells[pos]=value;break; + } + mask.add(rows[pivot]); +#endif + value^=cells[pos]; + ++time.additions; + } + }); + if(!success) return false; + // Includes coefficient hashing and elimination, now fused. + time.eliminate=elapsed(t); t=Clock::now(); + for(std::size_t pos=columns;pos--;) { +#if RIBBON_DIRECT_PIVOTS + auto& row=pivots[pos]; + if(row.v[0]==0) continue; +#else + if(pivots[pos]==UINT32_MAX) continue; + auto& row=rows[pivots[pos]]; +#endif + row.v[0]^=1; + // Normalization shifts the band toward the end. Nonzero bits remain + // within the table, but a full-width SIMD load might not. + cells[pos]^=pos+W<=columns ? dot(row,cells.data()+pos) + : scalarDot(row,cells.data()+pos); + } + time.backsolve=elapsed(t); time.total=elapsed(total); + return true; + } + void decode(oc::span keys, oc::span values, + oc::span cells, Order mode, Timings& time) const { + auto total=Clock::now(), t=total; + if(mode==Order::direct) { + queryBatches(keys,[&](const auto& batch,unsigned size) { + for(unsigned j=0;j(p+k); + } + for(unsigned j=0;j entries(keys.size()); + time.init=elapsed(t); t=Clock::now(); + makeEntries(keys,entries); + time.starts=elapsed(t); t=Clock::now(); + orderEntries(entries,mode); + time.sort=elapsed(t); t=Clock::now(); +#if defined(__GFNI__) && defined(__AVX512VBMI__) && !defined(VOLEPSI_RIBBON_PORTABLE) + if(mode==Order::shared && W>=32) { + constexpr unsigned ringSize=std::bit_ceil(W+32u); + alignas(64) std::array cache; + std::size_t next=0; + coefficientBatches(keys,entries,values.data(),[&](std::size_t i,const M* masks,unsigned size) { + unsigned j=0; + for(;j+8<=size;j+=8) { + auto anchor=entries[i+j].start&~7u; + if(entries[i+j+7].start-anchor<=32) { + next=std::max(next,anchor); + for(;next tail{}; + if(next(keys,entries,values.data(),[&](std::size_t i,const M& mask) { + values[entries[i].index]=dot(mask,cells.data()+entries[i].start); + }); + } + time.coefficients=elapsed(t); time.total=elapsed(total); + } + block referenceDecode(block key, oc::span cells) const { + M mask; + for(unsigned k=0;k<(W+127)/128;++k) { + auto hashed=coefficientHash[k].hashBlock(key); + mask.v[2*k]=hashed.template get(0); + if(2*k+1(1); + } + if constexpr(W%64) mask.v.back()&=(std::uint64_t(1)<<(W%64))-1; + return scalarDot(mask,cells.data()+start(key,startHash.hashBlock(key))); + } +}; +} diff --git a/volePSI/RibbonOkvs.cpp b/volePSI/RibbonOkvs.cpp new file mode 100644 index 0000000..3762a62 --- /dev/null +++ b/volePSI/RibbonOkvs.cpp @@ -0,0 +1,152 @@ +#include "RibbonOkvs.h" +#include "RibbonKernels.h" +#include +#include +#include +#if defined(_MSC_VER) +#define VOLEPSI_RIBBON_NOINLINE __declspec(noinline) +#else +#define VOLEPSI_RIBBON_NOINLINE __attribute__((noinline)) +#endif + +namespace volePSI +{ + namespace + { + // This grid only chooses a valid witness. It does not estimate or fit + // the failure probability. Use log space and reserve two extra bits. + RibbonParams witness(u64 n, u64 m, unsigned w) + { + RibbonParams best{n,m,w}; + const long double ln2=std::log(2.L), starts=m-w+1; + if(starts<=n) return best; + for(unsigned j=1;j<32;++j) + { + const long double rho=n/starts+(1-n/starts)*j/32; + const long double mu=starts*rho; + const long double delta=-mu+n+n*std::log(mu/n); + for(unsigned k=1;k<128;++k) + { + const long double theta=ln2*k/128, t=std::exp(theta); + const long double loga=rho*(t-1)-theta; + if(loga>=0) continue; + const long double b=(1-1/t)*std::exp(rho*(t/2-1)); + const long double c=std::max(1.L,b/-std::expm1(loga)); + const long double rank=std::log(mu*c)+rho*(t-1)-w*theta; + const long double hi=std::max(delta,rank),lo=std::min(delta,rank); + const long double bits=-(hi+std::log1p(std::exp(lo-hi)))/ln2; + if(bits>best.failureBits) + { + best.failureBits=static_cast(bits); + best.rho=static_cast(rho); + best.theta=static_cast(theta); + } + } + } + return best; + } + + template decltype(auto) dispatch(unsigned width,F&& f) + { + switch(width) + { + case 64: return f(std::integral_constant{}); + case 128: return f(std::integral_constant{}); + case 256: return f(std::integral_constant{}); + case 512: return f(std::integral_constant{}); + case 1024: return f(std::integral_constant{}); + default: throw std::logic_error("Ribbon is not initialized"); + } + } + } + + RibbonParams RibbonParams::select(u64 n,u64 ssp) + { + if(n>UINT32_MAX || ssp>1022) + throw std::invalid_argument("Ribbon parameters exceed supported widths/index range"); + const u64 target=ssp+2; + if(!n) return {0,64,64,1024,0,0}; + // For small sets, a single dense band avoids loose Poissonization. + if(n<=256) + for(unsigned w:{64,128,256,512,1024}) + if(n+target<=w) return {n,w,w,double(w-n),0,0}; + + const long double L=(target+2)*std::log(2.L); + const u64 slack=static_cast(std::ceil(2*std::sqrt(n*L)+2*L)); + RibbonParams best; + // Prefer 25% overhead. For high requested security and intermediate + // sizes, widen the table if no compiled band width certifies it. + for(u64 scale:{4,5,6,8,12,16,32}) + { + for(unsigned w:{64,128,256,512,1024}) + { + const u64 m=std::max((5*n*scale+15)/16,n+w+slack); + if(m>UINT32_MAX) continue; + auto p=witness(n,m,w); + if(p.failureBits>=target && (!best.width || m's start key followed by each coefficient key. + for(unsigned i=0, count=1+(mParams.width+127)/128; i() == labelKey) return false; + return true; + } + + // These ordinary functions own all SIMD scratch; no scratch enters a + // coroutine frame. Dispatch happens once per operation, outside hot loops. + VOLEPSI_RIBBON_NOINLINE bool RibbonOkvs::solve(span keys,span values, + span table,oc::PRNG* rng) const + { + if(keys.size()!=mParams.items || keys.size()!=values.size() || table.size()!=size()) + throw std::invalid_argument("Ribbon solve dimensions"); + return dispatch(mParams.width,[&](auto width) { + ribbon_detail::Ribbon code(static_cast(size()),mSeed); + ribbon_detail::Timings timings; + return code.encode(keys,values,table,rng,timings); + }); + } + + VOLEPSI_RIBBON_NOINLINE void RibbonOkvs::decode(span keys,span values, + span table,u64 numThreads) const + { + if(keys.size()!=values.size() || table.size()!=size() || keys.size()>UINT32_MAX) + throw std::invalid_argument("Ribbon decode dimensions"); + const u64 threads=std::max(1,std::min(numThreads,keys.size()/4096)); + dispatch(mParams.width,[&](auto width) { + ribbon_detail::Ribbon code(static_cast(size()),mSeed); + auto work=[&](u64 i) { + auto begin=keys.size()*i/threads, end=keys.size()*(i+1)/threads; + ribbon_detail::Timings timings; + code.decode(keys.subspan(begin,end-begin),values.subspan(begin,end-begin),table, + end-begin<512?ribbon_detail::Order::direct:ribbon_detail::Order::shared,timings); + }; + if(threads==1) { work(0); return; } + std::vector errors(threads); + auto guarded=[&](u64 i) { try {work(i);} catch(...) {errors[i]=std::current_exception();} }; + std::vector workers; + workers.reserve(threads-1); + for(u64 i=1;i +#include +#include + +namespace volePSI +{ + enum class OkvsType { Baxos, Ribbon }; + inline OkvsType parseOkvsType(std::string_view name) + { + if(name=="baxos") return OkvsType::Baxos; + if(name=="ribbon") return OkvsType::Ribbon; + throw std::invalid_argument("OKVS must be baxos or ribbon"); + } + + // A concrete witness for the ideal random-band rank bound in + // research/ribbon/proof.txt. Dense mode uses the elementary 2^(n-width) bound. + struct RibbonParams + { + u64 items = 0, columns = 0; + unsigned width = 0; + double failureBits = 0, rho = 0, theta = 0; + static RibbonParams select(u64 items, u64 ssp); + }; + + // Linear OKVS for block payloads. Keys must be distinct and fixed + // independently of the public seed. No automatic seed retries. + // All buffers have exactly size() logical cells; no padding is required. + class RibbonOkvs + { + public: + void init(u64 n, u64 ssp, block seed); + u64 size() const { return mParams.columns; } + const RibbonParams& params() const { return mParams; } + void setSeed(block seed) { mSeed = seed; } + // The label cipher must be absent from every row-key dependency. + bool labelKeyIndependent(block seed, block labelKey) const; + + // False means rank deficiency; output is then unspecified. Zero free + // cells when rng==nullptr, otherwise uniformly random free cells. + bool solve(span keys, span values, + span table, oc::PRNG* rng = nullptr) const; + void decode(span keys, span values, + span table, u64 numThreads = 1) const; + + private: + RibbonParams mParams; + block mSeed; + }; +} diff --git a/volePSI/RsOprf.cpp b/volePSI/RsOprf.cpp index 458bc85..b2306d2 100644 --- a/volePSI/RsOprf.cpp +++ b/volePSI/RsOprf.cpp @@ -5,6 +5,8 @@ namespace volePSI Proto RsOprfSender::send(u64 n, PRNG& prng, Socket& chl, u64 numThreads, bool reducedRounds) { auto ws = block{}; + auto ribbonSeed = block{}; + auto ribbonSuccess = u8{1}; auto hBuff = std::array {}; auto ro = oc::RandomOracle(32); auto pPtr = std::unique_ptr{}; @@ -19,7 +21,10 @@ namespace volePSI setTimePoint("RsOprfSender::send-begin"); ws = prng.get(); - mPaxos.init(n, mBinSize, 3, mSsp, PaxosParam::GF128, oc::ZeroBlock); + if (mOkvsType == OkvsType::Ribbon) + mRibbon.init(n, mSsp, oc::ZeroBlock); + else + mPaxos.init(n, mBinSize, 3, mSsp, PaxosParam::GF128, oc::ZeroBlock); mD = prng.get(); @@ -36,15 +41,39 @@ namespace volePSI numThreads = std::max(1, numThreads); //mVoleSender.mNumThreads = numThreads; - // a + b = c * d - fork = chl.fork(); - fu = genVole(prng, fork, reducedRounds) - | macoro::make_eager(); - - co_await(chl.recv(mPaxos.mSeed)); + if (mOkvsType == OkvsType::Ribbon) + { + co_await chl.recv(ribbonSeed); + if (mMalicious && !mRibbon.labelKeyIndependent(ribbonSeed, oc::mAesFixedKey.getKey())) + { + co_await chl.close(); + throw std::invalid_argument("Ribbon seed depends on the OPRF label AES key"); + } + mRibbon.setSeed(ribbonSeed); + } + else + { + co_await(chl.recv(mPaxos.mSeed)); + // With this seed, the first GF128 dense coefficient is H(x). + // A table with one identity cell per bin would encode every key. + if (mMalicious && mPaxos.mSeed == oc::mAesFixedKey.getKey()) + { + co_await chl.close(); + throw std::invalid_argument("Baxos seed equals the OPRF label AES key"); + } + } setTimePoint("RsOprfSender::recv-seed"); + // Validate the seed before launching a child VOLE coroutine. + // a + b = c * d + fork = chl.fork(); + fu = genVole(prng, fork, reducedRounds) | macoro::make_eager(); co_await(fu); - mB = mVoleSender.mB; + if (mOkvsType == OkvsType::Ribbon) + { + co_await chl.recv(ribbonSuccess); + if (ribbonSuccess != 1) throw std::runtime_error("Ribbon OKVS encoding failed"); + } + mB = mVoleSender.mB; setTimePoint("RsOprfSender::send-vole"); @@ -53,13 +82,12 @@ namespace volePSI if (mMalicious) { co_await(chl.recv(mW)); - co_await(chl.send(std::move(ws))); mW = mW ^ ws; setTimePoint("RsOprfSender::recv-mal"); } - pPtr.reset(new block[mPaxos.size()]); - pp = span(pPtr.get(), mPaxos.size()); + pPtr.reset(new block[okvsSize()]); + pp = span(pPtr.get(), okvsSize()); setTimePoint("RsOprfSender::alloc "); @@ -143,6 +171,10 @@ namespace volePSI } } + // Extraction fixes P from the complete correction before the receiver + // learns the final hash salt. Do not move this opening above recv(pp). + if (mMalicious) + co_await chl.send(std::move(ws)); } block RsOprfSender::eval(block v) @@ -155,7 +187,10 @@ namespace volePSI { setTimePoint("RsOprfSender::eval-begin"); - mPaxos.decode(val, output, mB, numThreads); + if (mOkvsType == OkvsType::Ribbon) + mRibbon.decode(val, output, mB, numThreads); + else + mPaxos.decode(val, output, mB, numThreads); setTimePoint("RsOprfSender::eval-decode"); @@ -247,10 +282,10 @@ namespace volePSI Proto RsOprfSender::genVole(PRNG& prng, Socket& chl, bool reduceRounds) { if (reduceRounds) - mVoleSender.configure(mPaxos.size(), mVoleSender.mSecurityType, + mVoleSender.configure(okvsSize(), mVoleSender.mSecurityType, mVoleSender.mLpnMultType, oc::SilentBaseType::Base); - return mVoleSender.silentSendInplace(mD, mPaxos.size(), prng, chl); + return mVoleSender.silentSendInplace(mD, okvsSize(), prng, chl); } struct UninitVec : span @@ -272,6 +307,9 @@ namespace volePSI auto ws = block{}; auto Hws = std::array {}; auto paxos = Baxos{}; + auto ribbon = RibbonOkvs{}; + auto tableSize = u64{}; + auto ribbonSuccess = u8{1}; auto hPtr = std::unique_ptr{}; auto h = span{}; auto p = UninitVec{}; @@ -288,9 +326,30 @@ namespace volePSI if (values.size() != outputs.size()) throw RTE_LOC; - hashingSeed = prng.get(), wr = prng.get(); + hashingSeed = prng.get(); + if (mMalicious) + { + if (mOkvsType == OkvsType::Baxos) + while (hashingSeed == oc::mAesFixedKey.getKey()) hashingSeed = prng.get(); + else + { + ribbon.init(values.size(), mSsp, hashingSeed); + while (!ribbon.labelKeyIndependent(hashingSeed, oc::mAesFixedKey.getKey())) + hashingSeed = prng.get(); + } + } + wr = prng.get(); paxos.mDebug = mDebug; - paxos.init(values.size(), mBinSize, 3, mSsp, PaxosParam::GF128, hashingSeed); + if (mOkvsType == OkvsType::Ribbon) + { + ribbon.init(values.size(), mSsp, hashingSeed); + tableSize = ribbon.size(); + } + else + { + paxos.init(values.size(), mBinSize, 3, mSsp, PaxosParam::GF128, hashingSeed); + tableSize = paxos.size(); + } co_await(chl.send(std::move(hashingSeed))); @@ -304,7 +363,7 @@ namespace volePSI mVoleRecver.setTimer(*mTimer); fork = chl.fork(); - fu = genVole(paxos.size(), prng, fork, reducedRounds) + fu = genVole(tableSize, prng, fork, reducedRounds) | macoro::make_eager(); @@ -318,14 +377,25 @@ namespace volePSI //auto pPtr = std::make_shared>(paxos.size()); //span p = *pPtr; - p.resize(paxos.size()); + p.resize(tableSize); setTimePoint("RsOprfReceiver::receive-alloc"); - paxos.solve(values, h, p, nullptr, numThreads); + if (mOkvsType == OkvsType::Ribbon) + ribbonSuccess = ribbon.solve(values, h, p) ? 1 : 0; + else + paxos.solve(values, h, p, nullptr, numThreads); setTimePoint("RsOprfReceiver::receive-solve"); co_await(fu); + // Finish the in-flight VOLE on both parties, then report a one-shot + // rank failure before either party waits for the correction table. + if (mOkvsType == OkvsType::Ribbon) + { + co_await chl.send(ribbonSuccess); + if (!ribbonSuccess) throw std::runtime_error("Ribbon OKVS encoding failed"); + } + // a + b = c * d a = mVoleRecver.mA; c = mVoleRecver.mC; @@ -421,7 +491,11 @@ namespace volePSI } - paxos.decode(values, outputs, a, numThreads); + setTimePoint("RsOprfReceiver::decode-begin"); + if (mOkvsType == OkvsType::Ribbon) + ribbon.decode(values, outputs, a, numThreads); + else + paxos.decode(values, outputs, a, numThreads); setTimePoint("RsOprfReceiver::receive-decode"); diff --git a/volePSI/RsOprf.h b/volePSI/RsOprf.h index ad0733c..b1fcb27 100644 --- a/volePSI/RsOprf.h +++ b/volePSI/RsOprf.h @@ -9,6 +9,7 @@ #include "volePSI/Defines.h" #include "volePSI/Paxos.h" +#include "volePSI/RibbonOkvs.h" #include "libOTe/Vole/Silent/SilentVoleSender.h" #include "libOTe/Vole/Silent/SilentVoleReceiver.h" @@ -25,11 +26,17 @@ namespace volePSI span mB; block mD; Baxos mPaxos; + RibbonOkvs mRibbon; + u64 okvsSize() { return mOkvsType == OkvsType::Ribbon ? mRibbon.size() : mPaxos.size(); } bool mMalicious = false; block mW; u64 mBinSize = 1 << 14; u64 mSsp = 40; bool mDebug = false; + // Both parties must select the same backend before starting a session. + // Ribbon is currently opt-in; Baxos retains its existing wire format. + OkvsType mOkvsType = OkvsType::Baxos; + void setOkvsType(OkvsType type) { mOkvsType = type; } void setMultType(oc::MultType type) { mVoleSender.mLpnMultType = type; }; @@ -58,6 +65,10 @@ namespace volePSI u64 mBinSize = 1 << 14; u64 mSsp = 40; bool mDebug = false; + // Both parties must select the same backend before starting a session. + // Ribbon is currently opt-in; Baxos retains its existing wire format. + OkvsType mOkvsType = OkvsType::Baxos; + void setOkvsType(OkvsType type) { mOkvsType = type; } void setMultType(oc::MultType type) { mVoleRecver.mLpnMultType = type; }; diff --git a/volePSI/RsPsi.h b/volePSI/RsPsi.h index 66cb09e..d6534ae 100644 --- a/volePSI/RsPsi.h +++ b/volePSI/RsPsi.h @@ -48,6 +48,7 @@ namespace volePSI public: RsOprfSender mSender; + void setOkvsType(OkvsType type) { mSender.setOkvsType(type); } void setMultType(oc::MultType type) { mSender.setMultType(type); }; @@ -64,6 +65,7 @@ namespace volePSI { public: RsOprfReceiver mRecver; + void setOkvsType(OkvsType type) { mRecver.setOkvsType(type); } void setMultType(oc::MultType type) { mRecver.setMultType(type); }; std::vector mIntersection; diff --git a/volePSI/fileBased.cpp b/volePSI/fileBased.cpp index b894026..116890a 100644 --- a/volePSI/fileBased.cpp +++ b/volePSI/fileBased.cpp @@ -373,6 +373,7 @@ namespace volePSI sender.mDebug = debug; sender.setMultType(type); + sender.setOkvsType(volePSI::parseOkvsType(cmd.getOr("okvs", "baxos"))); sender.init(set.size(), theirSize, statSetParam, seed, mal, 1); macoro::sync_wait(sender.run(set, chl)); macoro::sync_wait(chl.flush()); @@ -388,6 +389,7 @@ namespace volePSI recver.mDebug = debug; recver.setMultType(type); + recver.setOkvsType(volePSI::parseOkvsType(cmd.getOr("okvs", "baxos"))); recver.init(theirSize, set.size(), statSetParam, seed, mal, 1); macoro::sync_wait(recver.run(set, chl)); macoro::sync_wait(chl.flush()); From a1defc3188ae77d7de7de49e9a2ea14884d53f26 Mon Sep 17 00:00:00 2001 From: Peter Rindal Date: Tue, 17 Nov 2026 04:42:04 -0800 Subject: [PATCH 2/2] Use portable thread ownership in Ribbon decode --- volePSI/RibbonOkvs.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/volePSI/RibbonOkvs.cpp b/volePSI/RibbonOkvs.cpp index 3762a62..f39e823 100644 --- a/volePSI/RibbonOkvs.cpp +++ b/volePSI/RibbonOkvs.cpp @@ -139,9 +139,14 @@ namespace volePSI if(threads==1) { work(0); return; } std::vector errors(threads); auto guarded=[&](u64 i) { try {work(i);} catch(...) {errors[i]=std::current_exception();} }; - std::vector workers; + std::vector workers; workers.reserve(threads-1); - for(u64 i=1;i