diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml index b41855ea..956dcbc4 100644 --- a/.github/workflows/build-test.yml +++ b/.github/workflows/build-test.yml @@ -8,6 +8,20 @@ on: workflow_dispatch: jobs: + chosen-baa-portable: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v5 + with: + submodules: recursive + - name: Build portable Silent VOLE + run: python3 build.py --par=4 -DENABLE_SILENT_VOLE=ON -DENABLE_SILENTOT=ON -DENABLE_SOFTSPOKEN_OT=ON -DENABLE_MRR=ON -DENABLE_CIRCUITS=ON -DENABLE_SSE=OFF -DENABLE_AVX=OFF -DENABLE_AVX2=OFF -DENABLE_AVX512=OFF -DENABLE_VPCLMUL=OFF -DENABLE_VAES=OFF -DENABLE_ARM_AES=OFF -DENABLE_EDWARDS25519_ASM=OFF -DENABLE_BITPOLYMUL=OFF -DENABLE_SODIUM=OFF -DENABLE_LOGVOLE=OFF -DENABLE_SPIN=OFF -DCMAKE_BUILD_TYPE=Release + - name: Test portable arithmetic and chosen BAA + run: | + ./out/build/linux/frontend/frontend_libOTe -u block_operation + ./out/build/linux/frontend/frontend_libOTe -u ChosenBaa + build-ubuntu: runs-on: ubuntu-latest timeout-minutes: 60 @@ -106,7 +120,7 @@ jobs: build-macos: needs: build-ubuntu if: ${{ !cancelled() }} - runs-on: macos-14 + runs-on: macos-15 timeout-minutes: 60 steps: - uses: actions/checkout@v5 diff --git a/cryptoTools b/cryptoTools index 12fa6f98..f30c7e8d 160000 --- a/cryptoTools +++ b/cryptoTools @@ -1 +1 @@ -Subproject commit 12fa6f985918b038cf1be111e52a050b5c871af4 +Subproject commit f30c7e8d0b762c96bf5d42d50724c4c18db7d29e diff --git a/frontend/ExampleVole.cpp b/frontend/ExampleVole.cpp index 7adcbcbe..084263a0 100644 --- a/frontend/ExampleVole.cpp +++ b/frontend/ExampleVole.cpp @@ -24,7 +24,7 @@ namespace osuCrypto // the LPN compression type. - MultType mulType = (MultType)cmd.getOr("multType", (int)DefaultMultType); + MultType mulType = (MultType)cmd.getOr("multType", (int)SilentVoleSender::DefaultCode); // regular noise or stationary noise. SdNoiseDistribution noiseType = (SdNoiseDistribution)cmd.getOr("noise", (int)SdNoiseDistribution::Regular); diff --git a/frontend/benchmark.h b/frontend/benchmark.h index 257df3c8..c8c3d543 100644 --- a/frontend/benchmark.h +++ b/frontend/benchmark.h @@ -641,7 +641,7 @@ namespace osuCrypto u64 trials = cmd.getOr("t", 10); u64 n = cmd.getOr("n", 1ull << cmd.getOr("nn", 20)); - MultType multType = (MultType)cmd.getOr("m", (int)DefaultMultType); + MultType multType = (MultType)cmd.getOr("m", (int)SilentVoleSender::DefaultCode); auto noise = (SdNoiseDistribution)cmd.getOr("noise", (int)SdNoiseDistribution::Regular); auto mal = (SilentSecType)cmd.getOr("mal", (int)SilentSecType::SemiHonest); diff --git a/libOTe/CMakeLists.txt b/libOTe/CMakeLists.txt index 893f470f..81b5225d 100644 --- a/libOTe/CMakeLists.txt +++ b/libOTe/CMakeLists.txt @@ -9,6 +9,7 @@ set(SRCS Tools/LDPC/Util.cpp Tools/LinearCode.cpp Tools/Tools.cpp + Tools/BlkAccCode/ChosenBaaCode.cpp Tools/TungstenCode/TungstenData.cpp TwoChooseOne/ConfigureCode.cpp TwoChooseOne/OTExtInterface.cpp diff --git a/libOTe/Dpf/RevCuckoo/BinarySolver.h b/libOTe/Dpf/RevCuckoo/BinarySolver.h index 0b267f64..b11d773e 100644 --- a/libOTe/Dpf/RevCuckoo/BinarySolver.h +++ b/libOTe/Dpf/RevCuckoo/BinarySolver.h @@ -937,7 +937,9 @@ namespace osuCrypto span< MatrixView> m{ &MM,1 }; span< MatrixView> y{ &YY,1 }; span< MatrixView> x{ &X,1 }; - return solve(m, y, x, prng, sock); + // Keep the by-value views in this coroutine frame while solve uses + // spans over them. The caller still owns the matrix data and socket. + co_await solve(m, y, x, prng, sock); } task<> solve( diff --git a/libOTe/Tools/BlkAccCode/AdditiveRs8.h b/libOTe/Tools/BlkAccCode/AdditiveRs8.h new file mode 100644 index 00000000..bae5cf1c --- /dev/null +++ b/libOTe/Tools/BlkAccCode/AdditiveRs8.h @@ -0,0 +1,58 @@ +#pragma once +#include "ChosenBaaField.h" +#include +#include + +namespace osuCrypto::chosen_baa_detail +{ + struct AdditivePoints : ChosenBaaField + { + static block point(u64 i) { return block(0, i); } + }; + + // For evaluation points 0..7 and 8..15 the Lagrange matrix has entries + // M[i,j]=c[i XOR j]. Translate the group algebra by t_i=x_i+1; then + // t_i^2=0. A three-bit subset convolution replaces 64 field products + // with 19 (24 SIMD slots). The transform is its own inverse in char 2. + struct AdditiveRs8 + { + std::array coefficients; + template + static OC_FORCEINLINE void zeta(block* v) + { + if constexpr (Bit < 3) + { + if constexpr (I < 8) + { + if constexpr (!(I & (1u << Bit))) v[I] ^= v[I | (1u << Bit)]; + zeta(v); + } + else zeta(v); + } + } + void init(const block* c) + { + std::array v; + std::copy_n(c, 8, v.data()); zeta(v.data()); + if (v[0] != OneBlock) throw std::logic_error("Additive RS row sum."); + coefficients = {v[1],v[2],v[3],v[4],v[5],v[6],v[7],ZeroBlock, + v[2],v[1],v[4],v[1],v[4],v[2],v[6],v[5], + v[4],v[3],v[2],v[1],ZeroBlock,ZeroBlock,ZeroBlock,ZeroBlock}; + } + OC_FORCEINLINE void apply(const block* input, block* output) const + { + std::array u; + std::copy_n(input, 8, u.data()); zeta(u.data()); + std::array a{u[0],u[0],u[0],u[0],u[0],u[0],u[0],ZeroBlock}; + std::array b{u[1],u[2],u[1],u[4],u[2],u[4],u[1],u[2]}; + std::array c{u[3],u[4],u[5],u[6],ZeroBlock,ZeroBlock,ZeroBlock,ZeroBlock}; + ChosenBaaField::mul8(a.data(), coefficients.data()); + ChosenBaaField::mul8(b.data(), coefficients.data() + 8); + ChosenBaaField::mul8(c.data(), coefficients.data() + 16); + u[1] ^= a[0]; u[2] ^= a[1]; u[3] ^= a[2] ^ b[0] ^ b[1]; + u[4] ^= a[3]; u[5] ^= a[4] ^ b[2] ^ b[3]; u[6] ^= a[5] ^ b[4] ^ b[5]; + u[7] ^= a[6] ^ b[6] ^ b[7] ^ c[0] ^ c[1] ^ c[2] ^ c[3]; + zeta(u.data()); std::copy(u.begin(), u.end(), output); + } + }; +} diff --git a/libOTe/Tools/BlkAccCode/BinaryBAA.h b/libOTe/Tools/BlkAccCode/BinaryBAA.h new file mode 100644 index 00000000..36e06dce --- /dev/null +++ b/libOTe/Tools/BlkAccCode/BinaryBAA.h @@ -0,0 +1,21 @@ +#pragma once +#include "ReedMullerBaaCode.h" +#include + +namespace osuCrypto +{ + // Each bit lane is an independent binary codeword, not a field symbol. + template + struct BinaryBAAArithmetic + { + static_assert(std::is_same_v || std::is_unsigned_v); + static Word zero() { return Word{}; } + static Word one() { return Word(1); } + static OC_FORCEINLINE Word add(Word a, Word b) { return a ^ b; } + }; + template<> inline block BinaryBAAArithmetic::one() { return OneBlock; } + + // Binary RM BAA, 10% distance tier. block stores 128 independent bit lanes. + template + using BinaryBAA = ReedMullerBaaCode>; +} diff --git a/libOTe/Tools/BlkAccCode/ChosenBAA30.h b/libOTe/Tools/BlkAccCode/ChosenBAA30.h new file mode 100644 index 00000000..a0bc8aab --- /dev/null +++ b/libOTe/Tools/BlkAccCode/ChosenBAA30.h @@ -0,0 +1,10 @@ +#pragma once +#include "SmallAlphabetBaaCode.h" + +namespace osuCrypto +{ + // Public distance tier. The >30.524% certificate is for n=2^21 with + // ideal uniform setup, not a guarantee for every supported length/field. + template> + using ChosenBAA30 = SmallAlphabetBaaCode; +} diff --git a/libOTe/Tools/BlkAccCode/ChosenBaaCode.cpp b/libOTe/Tools/BlkAccCode/ChosenBaaCode.cpp new file mode 100644 index 00000000..03d60805 --- /dev/null +++ b/libOTe/Tools/BlkAccCode/ChosenBaaCode.cpp @@ -0,0 +1,109 @@ +#include "ChosenBaaVole.h" +#include "cryptoTools/Crypto/RandomOracle.h" +#include + +namespace osuCrypto +{ + void chosenBaaCompress(MultType type, block seed, span a, span b) + { + std::unique_ptr workspace; + chosenBaaCompress(type, seed, workspace, a, b); + } + + void chosenBaaCompress(MultType type, block seed, + std::unique_ptr& workspace, span a, span b) + { + if (!b.empty() && b.size() != a.size()) + throw std::invalid_argument("Chosen BAA paired buffers differ in size."); + if (type == MultType::ChosenBAA30) + { + if (!workspace) workspace = std::make_unique(); + workspace->code.config(a.size(), seed); + workspace->scratch.resize(a.size()); + workspace->code.dualEncode(a, workspace->scratch); + if (!b.empty()) workspace->code.dualEncode(b, workspace->scratch); + } + else if (type == MultType::ChosenBaa16x8) + { + ChosenBaaCode<8> code; + code.config(a.size(), seed); + if (b.empty()) code.dualEncode(a); + else code.dualEncode2(a, b); + } + else if (type == MultType::ChosenBaa16x4) + { + ChosenBaaCode<4> code; + code.config(a.size(), seed); + if (b.empty()) code.dualEncode(a); + else code.dualEncode2(a, b); + } + else throw std::invalid_argument("Not a chosen BAA profile."); + } + + void binaryBaaCompress(block seed, span values, span choices) + { + if (!choices.empty() && choices.size() != values.size()) + throw std::invalid_argument("BinaryBAA buffer lengths differ."); + BinaryBAA<> code; + code.config(values.size(), seed); + AlignedUnVector scratch(values.size()); + code.dualEncode(values, scratch); + if (!choices.empty()) + { + BinaryBAA bits; + bits.config(choices.size(), seed); + AlignedUnVector bitScratch(choices.size()); + bits.dualEncode(choices, bitScratch); + } + } + + namespace + { + using Seed = std::array; + using Commitment = std::array; + + OC_NOINLINE Commitment commitSeed(const Seed& seed) + { + RandomOracle hash(32); + constexpr char domain[] = "libOTe/chosen-baa/seed/v1"; + hash.Update(domain, sizeof(domain)); + hash.Update(seed.data(), seed.size()); + Commitment result; + hash.Final(result.data()); + return result; + } + + OC_NOINLINE void combineSeeds(const Seed& a, const Seed& b, block& output) + { + Seed result; + for (u64 i = 0; i < result.size(); ++i) + result[i] = a[i] ^ b[i]; + std::memcpy(&output, result.data(), result.size()); + } + } + + task<> chosenBaaSeed(bool sender, PRNG& prng, Socket& chl, block& seed) + { + // Byte arrays require no SIMD alignment in a coroutine frame. Each + // send is awaited before its storage is reused or destroyed. + Seed mine{}, theirs{}; + Commitment commitment{}; + prng.get(mine.data(), mine.size()); + if (sender) + { + commitment = commitSeed(mine); + co_await chl.send(commitment); + co_await chl.recv(theirs); + co_await chl.send(mine); + } + else + { + co_await chl.recv(commitment); + co_await chl.send(mine); + co_await chl.recv(theirs); + if (commitSeed(theirs) != commitment) + throw std::runtime_error("Chosen BAA seed commitment mismatch."); + } + combineSeeds(mine, theirs, seed); + } +} diff --git a/libOTe/Tools/BlkAccCode/ChosenBaaCode.h b/libOTe/Tools/BlkAccCode/ChosenBaaCode.h new file mode 100644 index 00000000..b4b6af69 --- /dev/null +++ b/libOTe/Tools/BlkAccCode/ChosenBaaCode.h @@ -0,0 +1,297 @@ +#pragma once + +#include "cryptoTools/Common/Defines.h" +#include "cryptoTools/Common/Aligned.h" +#include "cryptoTools/Crypto/PRNG.h" +#include "libOTe/Tools/CompilerHints.h" +#include "ChosenBaaField.h" + +#include +#include + +namespace osuCrypto +{ + // Field-generic transpose encoder for chosen-block BAA, RS[16,K,17-K]. + // Ported from ladnir/libOTe chosen-block-baa, fa7bfc3c8a0178fc99b0b666d5f31fc2a9277579. + // Both interleavers are Fisher--Yates shuffles, including at power-of-two + // lengths. Each accumulator output has an independent nonzero field weight. + // Randomness is expanded by AES; see README.md for the proof boundary. + template> + class ChosenBaaCode + { + static_assert(K == 4 || K == 8); + static_assert(std::is_same_v); + using Matrix = std::array; + u64 mN = 0; + std::array, 2> mPerm; + std::array mWeightSeeds; + const Matrix* mMatrix = nullptr; + Matrix mForwardMatrix; + + static u32 sampleBelow(PRNG& prng, u32 bound) + { + u64 product = u64(prng.get()) * bound; + if (u32(product) < bound) + { + const u32 threshold = (u32(0) - bound) % bound; + while (u32(product) < threshold) + product = u64(prng.get()) * bound; + } + return u32(product >> 32); + } + + // Fixed, unrolled prefix and scatter kernels expose independent products. + template + static OC_FORCEINLINE void prefix(const F* a, const F* b, F* va, F* vb, F& sa, F& sb) + { + if constexpr (J < Count) + { + va[J] = sa = Field::add(sa, a[J]); + if constexpr (Pair) vb[J] = sb = Field::add(sb, b[J]); + prefix(a, b, va, vb, sa, sb); + } + } + template + static OC_FORCEINLINE void scatter(const u32* indices, const F* a, const F* b, F* oa, F* ob) + { + if constexpr (J < Count) + { + const auto dest = indices[J]; + oa[dest] = a[J]; + if constexpr (Pair) ob[dest] = b[J]; + scatter(indices, a, b, oa, ob); + } + } + template + static OC_FORCEINLINE void prefetchDestinations(const u32* indices, const F* a, const F* b) + { +#ifdef OC_ENABLE_SSE2 + if constexpr (J < 8) + { + const auto dest = indices[J]; + _mm_prefetch(reinterpret_cast(a + dest), _MM_HINT_T2); + if constexpr (Pair) + _mm_prefetch(reinterpret_cast(b + dest), _MM_HINT_T2); + prefetchDestinations(indices, a, b); + } +#endif + } + template + void stageImpl(const F* a, const F* b, F* outA, F* outB, u64 which) const + { + PRNG weights(mWeightSeeds[which]); + F sumA = Field::zero(), sumB = Field::zero(); + for (u64 i = 0; i < mN; i += 8) + { + // Schedule future random destination lines before their stores. + // Bound the metadata reads as well as the prefetch addresses; + // the final eight batches use the same arithmetic without hints. + if constexpr (Prefetch) + if (i + 64 + 8 <= mN) + prefetchDestinations(mPerm[which].data() + i + 64, outA, outB); + std::array coeffs, valuesA, valuesB; + Field::sample8(weights, coeffs.data()); +#if defined(OC_ENABLE_VPCLMUL) && defined(ENABLE_AVX512) + if constexpr (std::is_same_v>) + { + const F* bi = nullptr; + if constexpr (Pair) bi = b + i; + prefix(a + i, bi, valuesA.data(), valuesB.data(), sumA, sumB); + Field::mul8(valuesA.data(), coeffs.data()); + if constexpr (Pair) Field::mul8(valuesB.data(), coeffs.data()); + scatter(mPerm[which].data() + i, valuesA.data(), valuesB.data(), outA, outB); + } + else +#endif + { + // Preserve the interleaved prefix/product schedule for + // 128-bit PCLMUL, PMULL, and generic field arithmetic. + for (u64 j = 0; j < 8; ++j) + { + sumA = Field::add(sumA, a[i + j]); + valuesA[j] = Field::mul(sumA, coeffs[j]); + if constexpr (Pair) + { + sumB = Field::add(sumB, b[i + j]); + valuesB[j] = Field::mul(sumB, coeffs[j]); + } + } + for (u64 j = 0; j < 8; ++j) + { + const auto dest = mPerm[which][i + j]; + outA[dest] = valuesA[j]; + if constexpr (Pair) outB[dest] = valuesB[j]; + } + } + } + } + template + void stage(const F* a, const F* b, F* outA, F* outB, u64 which) const + { +#ifdef OC_ENABLE_SSE2 + if constexpr (std::is_same_v>) + { + // Small inputs already fit in cache; avoid issuing extra hints. + // Select the loop once rather than testing size in every batch. + if (mN >= (u64{1} << 18)) + return stageImpl(a, b, outA, outB, which); + } +#endif + stageImpl(a, b, outA, outB, which); + } + static const Matrix& matrixData() + { + // One immutable RS matrix per field/profile, independent of the seed. + // Thread-safe initialization does field inversion only on first use. + static const Matrix matrix = [] { + Matrix result; + for (u64 i = 0; i < 16; ++i) + for (u64 j = 0; j < i; ++j) + if (Field::point(i) == Field::point(j)) + throw std::invalid_argument("Chosen BAA requires sixteen distinct evaluation points."); + for (u64 row = 0; row < K; ++row) + { + const F x = Field::point(row); + F denominator = Field::one(); + for (u64 h = 0; h < K; ++h) + if (h != row) denominator = Field::mul(denominator, Field::sub(x, Field::point(h))); + const F inv = Field::inverse(denominator); + for (u64 col = 0; col < 16 - K; ++col) + { + F numerator = Field::one(); + for (u64 h = 0; h < K; ++h) + if (h != row) numerator = Field::mul(numerator, Field::sub(Field::point(K + col), Field::point(h))); + // Consecutive output rows form consecutive SIMD lanes. + result[col * K + row] = Field::mul(numerator, inv); + } + } + return result; + }(); + return matrix; + } + + template + void encode(span a, span b) const + { + if (!mN || a.size() != mN || (Pair && b.size() != mN)) + throw std::invalid_argument("Chosen BAA input size does not match configuration."); + AlignedUnVector scratchA(mN), scratchB; + if constexpr (Pair) + scratchB.resize(mN); + transposeWithScratch(a, b, scratchA, scratchB); + } + template + void transposeWithScratch(span a, span b, span scratchA, span scratchB) const + { + stage(a.data(), b.data(), scratchA.data(), scratchB.data(), 1); + stage(scratchA.data(), scratchB.data(), a.data(), b.data(), 0); + for (u64 i = 0; i < mN / 16; ++i) + { + // The output prefix cannot overwrite a future constituent. + Field::template local(a.data() + 16 * i, a.data() + K * i, mMatrix->data()); + if constexpr (Pair) + Field::template local(b.data() + 16 * i, b.data() + K * i, mMatrix->data()); + } + } + + template + static OC_FORCEINLINE void gatherForward(const F* in, const u32* perm, F* values) + { + if constexpr (J < 8) { values[J] = in[perm[J]]; gatherForward(in, perm, values); } + } + template + static OC_FORCEINLINE void suffixForward(F* values, F* out, F& sum) + { + if constexpr (J < 8) + { + out[7 - J] = sum = Field::add(sum, values[7 - J]); + suffixForward(values, out, sum); + } + } + void forwardStage(const F* in, F* out, u64 which) const + { + // The reverse traversal needs the same coefficient stream as the + // transpose. Generate it into the destination, then consume and + // overwrite each batch; no separate weight array or allocation. + PRNG random(mWeightSeeds[which]); + for (u64 i = 0; i < mN; i += 8) Field::sample8(random, out + i); + F sum = Field::zero(); + const auto* p = mPerm[which].data(); + for (u64 end = mN; end; end -= 8) + { + const auto i = end - 8; +#ifdef OC_ENABLE_SSE2 + if constexpr (std::is_same_v) + if (i >= 256) prefetchDestinations(p + i - 256, in, nullptr); +#endif + std::array v; + gatherForward(in, p + i, v.data()); + Field::mul8(v.data(), out + i); + suffixForward(v.data(), out + i, sum); + } + } + + public: + void config(u64 n, block seed) + { + if (!n || n % 16 || n > std::numeric_limits::max()) + throw std::invalid_argument("Chosen BAA length must be a positive multiple of 16 fitting u32."); + mMatrix = &matrixData(); + for (u64 row = 0; row < K; ++row) + for (u64 col = 0; col < 16 - K; ++col) + mForwardMatrix[row * (16 - K) + col] = (*mMatrix)[col * K + row]; + PRNG master(seed); + const std::array permutationSeeds{ master.get(), master.get() }; + mWeightSeeds = { master.get(), master.get() }; + for (u64 stage = 0; stage < 2; ++stage) + { + auto& perm = mPerm[stage]; + perm.resize(n); + for (u64 i = 0; i < n; ++i) + perm[i] = u32(i); + PRNG random(permutationSeeds[stage]); + for (u64 remaining = n; remaining > 1; --remaining) + std::swap(perm[remaining - 1], perm[sampleBelow(random, u32(remaining))]); + } + mN = n; + } + + u64 outputSize() const { return mN / 16 * K; } + u32 permutationIndex(u64 stage, u64 i) const + { + if (i >= mN) throw std::out_of_range("Chosen BAA permutation index."); + return mPerm.at(stage)[i]; + } + block weightSeed(u64 stage) const { return mWeightSeeds.at(stage); } + F matrix(u64 row, u64 col) const + { + if (!mMatrix || row >= K || col >= 16 - K) throw std::out_of_range("Chosen BAA matrix index."); + return (*mMatrix)[col * K + row]; + } + void dualEncode(span a) const { encode(a, {}); } + void dualEncode2(span a, span b) const { encode(a, b); } + // Caller-owned disjoint scratch removes allocation from repeated calls. + void dualEncode(span a, span scratch) const + { + if (!mN || a.size() != mN || scratch.size() != mN) + throw std::invalid_argument("Chosen BAA transpose buffer size."); + transposeWithScratch(a, {}, scratch, {}); + } + // Forward map of dualEncode: k -> n. All three buffers are disjoint. + void encode(span input, span output, span scratch) const + { + if (!mN || input.size() != outputSize() || output.size() != mN || scratch.size() != mN) + throw std::invalid_argument("Chosen BAA forward buffer size."); + for (u64 i = 0; i < mN / 16; ++i) + { + const auto* src = input.data() + K * i; + auto* dst = output.data() + 16 * i; + for (u64 j = 0; j < K; ++j) dst[j] = src[j]; + Field::template localForward(src, dst, mForwardMatrix.data()); + } + forwardStage(output.data(), scratch.data(), 0); + forwardStage(scratch.data(), output.data(), 1); + } + }; + +} diff --git a/libOTe/Tools/BlkAccCode/ChosenBaaField.h b/libOTe/Tools/BlkAccCode/ChosenBaaField.h new file mode 100644 index 00000000..435d5a30 --- /dev/null +++ b/libOTe/Tools/BlkAccCode/ChosenBaaField.h @@ -0,0 +1,239 @@ +#pragma once +#include "cryptoTools/Common/Defines.h" +#include "cryptoTools/Crypto/PRNG.h" +#include +#ifdef OC_ENABLE_VPCLMUL +#include +#endif + +namespace osuCrypto +{ + // Stateless field policy. F's PRNG::Any constructor must sample uniformly + // in F (not copy bytes into a modular representation). Override this policy + // for fields with a different representation or sampling interface. + // point(0)..point(15) must be distinct; config() checks this requirement. + template + struct ChosenBaaField + { + using Element = F; + static F zero() { return F(0); } + static F one() { return F(1); } + static F point(u64 i) { return F(i + 1); } + static F add(const F& a, const F& b) { return a + b; } + static F sub(const F& a, const F& b) { return a - b; } + static F mul(const F& a, const F& b) { return a * b; } + static F inverse(const F& a) { return a.inverse(); } + static void sample8(PRNG& random, F* out) + { + for (u64 i = 0; i < 8; ++i) + do { out[i] = F(random.get()); } while (out[i] == zero()); + } + template + static OC_FORCEINLINE void mul8Impl(F* a, const F* b, std::index_sequence) + { ((a[I] = mul(a[I], b[I])), ...); } + static OC_FORCEINLINE void mul8(F* a, const F* b) + { mul8Impl(a, b, std::make_index_sequence<8>{}); } + template + static OC_FORCEINLINE F dot(const F* in, const F* matrix, F sum) + { + if constexpr (Col == 16 - K) return sum; + else return dot(in, matrix, + add(sum, mul(in[K + Col], matrix[Col * K + Row]))); + } + template + static OC_FORCEINLINE void local(const F* in, F* out, const F* matrix) + { + if constexpr (Row < K) + { + out[Row] = dot(in, matrix, in[Row]); + local(in, out, matrix); + } + } + template + static OC_FORCEINLINE F forwardDot(const F* in, const F* matrix, F sum) + { + if constexpr (Row == K) return sum; + else return forwardDot(in, matrix, + add(sum, mul(in[Row], matrix[Row * (16 - K) + Col]))); + } + template + static OC_FORCEINLINE void localForward(const F* in, F* out, const F* matrix) + { + if constexpr (Col < 16 - K) + { + out[K + Col] = forwardDot(in, matrix, zero()); + localForward(in, out, matrix); + } + } + }; + + namespace chosen_baa_detail + { +#ifdef OC_ENABLE_VPCLMUL + // Each 128-bit lane is an independent field product. No horizontal + // reduction, gathers, or cross-lane permutations in either kernel. + struct Wide + { +#ifdef ENABLE_AVX512 + using V = __m512i; + static constexpr u64 lanes = 4; + static OC_FORCEINLINE V load(const block* p) { return _mm512_loadu_si512(p); } + static OC_FORCEINLINE void store(block* p, V x) { _mm512_storeu_si512(p, x); } + static OC_FORCEINLINE V broadcast(block x) { return _mm512_broadcast_i32x4(x); } + static OC_FORCEINLINE V bxor(V x, V y) { return _mm512_xor_si512(x, y); } + static OC_FORCEINLINE V swap(V x) { return _mm512_shuffle_epi32(x, _MM_PERM_BADC); } + template static OC_FORCEINLINE V clmul(V x, V y) { return _mm512_clmulepi64_epi128(x,y,I); } + static OC_FORCEINLINE V left(V x) { return _mm512_bslli_epi128(x,8); } + static OC_FORCEINLINE V right(V x) { return _mm512_bsrli_epi128(x,8); } +#else + using V = __m256i; + static constexpr u64 lanes = 2; + static OC_FORCEINLINE V load(const block* p) { return _mm256_loadu_si256(reinterpret_cast(p)); } + static OC_FORCEINLINE void store(block* p, V x) { _mm256_storeu_si256(reinterpret_cast(p), x); } + static OC_FORCEINLINE V broadcast(block x) { return _mm256_broadcastsi128_si256(x); } + static OC_FORCEINLINE V bxor(V x, V y) { return _mm256_xor_si256(x, y); } + static OC_FORCEINLINE V swap(V x) { return _mm256_shuffle_epi32(x, 0x4e); } + template static OC_FORCEINLINE V clmul(V x, V y) { return _mm256_clmulepi64_epi128(x,y,I); } + static OC_FORCEINLINE V left(V x) { return _mm256_slli_si256(x,8); } + static OC_FORCEINLINE V right(V x) { return _mm256_srli_si256(x,8); } +#endif + static OC_FORCEINLINE void product(V x, V y, V& lo, V& hi) + { + lo = clmul<0x00>(x,y); + hi = clmul<0x11>(x,y); + auto cross = bxor(clmul<0x00>(bxor(x,swap(x)),bxor(y,swap(y))),bxor(lo,hi)); + lo = bxor(lo,left(cross)); + hi = bxor(hi,right(cross)); + } + static OC_FORCEINLINE V reduce(V lo, V hi) + { + const auto modulus = broadcast(block(0,0x87)); + auto t = clmul<0x01>(hi,modulus); + lo = bxor(lo,left(t)); + hi = bxor(hi,right(t)); + return bxor(lo,clmul<0x00>(hi,modulus)); + } + }; +#endif + } + + // Specialize arithmetic without virtual calls or callbacks in the encoder. + // The byte stream and field representation are identical on every backend. + template<> + struct ChosenBaaField + { + using Element = block; + static block zero() { return ZeroBlock; } + static block one() { return OneBlock; } + static block point(u64 i) { return block(0, i + 1); } + static OC_FORCEINLINE block add(block a, block b) { return a ^ b; } + static OC_FORCEINLINE block sub(block a, block b) { return a ^ b; } + static OC_FORCEINLINE block mul(block a, block b) { return a.gf128Mul(b); } + static block inverse(block x) + { + block result = x; + for (u64 i = 1; i < 127; ++i) + result = mul(mul(result,result),x); + return mul(result,result); + } + static OC_FORCEINLINE void sample8(PRNG& random, block* out) + { + random.get(out,8); + // Preserve the existing draw order even on the negligible rejection + // path, so all backends instantiate precisely the same matrix. + for (u64 i = 0; i < 8; ++i) + while (out[i] == ZeroBlock) out[i] = random.get(); + } + template + static OC_FORCEINLINE void mul8(block* a, const block* b) + { + if constexpr (I < 8) + { +#ifdef OC_ENABLE_VPCLMUL + using W = chosen_baa_detail::Wide; + W::V lo, hi; + W::product(W::load(a+I), W::load(b+I), lo, hi); + W::store(a+I,W::reduce(lo,hi)); + mul8(a,b); +#else + a[I] = mul(a[I],b[I]); + mul8(a,b); +#endif + } + } + template + static OC_FORCEINLINE void dot(const block* in, const block* matrix, V& lo, V& hi) + { + if constexpr (Col < 16 - K) + { +#ifdef OC_ENABLE_VPCLMUL + using W = chosen_baa_detail::Wide; + V l,h; + W::product(W::broadcast(in[K+Col]),W::load(matrix+Col*K+Row),l,h); + lo=W::bxor(lo,l); hi=W::bxor(hi,h); +#else + block l,h; + in[K+Col].gf128Mul(matrix[Col*K+Row],l,h); + lo^=l; hi^=h; +#endif + dot(in,matrix,lo,hi); + } + } + template + static OC_FORCEINLINE void local(const block* in, block* out, const block* matrix) + { + if constexpr (Row < K) + { +#ifdef OC_ENABLE_VPCLMUL + using W = chosen_baa_detail::Wide; + auto lo=W::broadcast(ZeroBlock),hi=lo; + dot(in,matrix,lo,hi); + W::store(out+Row,W::bxor(W::load(in+Row),W::reduce(lo,hi))); + local(in,out,matrix); +#else + block lo=ZeroBlock,hi=ZeroBlock; + dot(in,matrix,lo,hi); + out[Row]=in[Row]^lo.gf128Reduce(hi); + local(in,out,matrix); +#endif + } + } + template + static OC_FORCEINLINE void forwardDot(const block* in, const block* matrix, V& lo, V& hi) + { + if constexpr (Row < K) + { +#ifdef OC_ENABLE_VPCLMUL + using W = chosen_baa_detail::Wide; + V l, h; + W::product(W::broadcast(in[Row]), W::load(matrix + Row * (16 - K) + Col), l, h); + lo = W::bxor(lo, l); hi = W::bxor(hi, h); +#else + block l, h; + in[Row].gf128Mul(matrix[Row * (16 - K) + Col], l, h); + lo ^= l; hi ^= h; +#endif + forwardDot(in, matrix, lo, hi); + } + } + template + static OC_FORCEINLINE void localForward(const block* in, block* out, const block* matrix) + { + if constexpr (Col < 16 - K) + { +#ifdef OC_ENABLE_VPCLMUL + using W = chosen_baa_detail::Wide; + auto lo = W::broadcast(ZeroBlock), hi = lo; + forwardDot(in, matrix, lo, hi); + W::store(out + K + Col, W::reduce(lo, hi)); + localForward(in, out, matrix); +#else + block lo = ZeroBlock, hi = ZeroBlock; + forwardDot(in, matrix, lo, hi); + out[K + Col] = lo.gf128Reduce(hi); + localForward(in, out, matrix); +#endif + } + } + }; +} diff --git a/libOTe/Tools/BlkAccCode/ChosenBaaVole.h b/libOTe/Tools/BlkAccCode/ChosenBaaVole.h new file mode 100644 index 00000000..2b18556b --- /dev/null +++ b/libOTe/Tools/BlkAccCode/ChosenBaaVole.h @@ -0,0 +1,25 @@ +#pragma once +#include "ChosenBaaCode.h" +#include "BinaryBAA.h" +#include "ChosenBAA30.h" +#include "libOTe/Tools/Coproto.h" +#include "libOTe/TwoChooseOne/ConfigureCode.h" + +namespace osuCrypto +{ + struct ChosenBaaWorkspace + { + ChosenBAA30<> code; + AlignedUnVector scratch; + }; + + // Keep aligned encoder state and scratch out of the caller's coroutine frame. + // The standalone encoder is field-generic; these protocol adapters use GF128. + OC_NOINLINE void chosenBaaCompress(MultType type, block seed, span a, span b = {}); + // The workspace must be heap-owned: the encoder contains over-aligned SIMD + // state. Capacity is reused, but config regenerates the code for every seed. + OC_NOINLINE void chosenBaaCompress(MultType type, block seed, + std::unique_ptr& workspace, span a, span b = {}); + OC_NOINLINE void binaryBaaCompress(block seed, span values, span choices = {}); + task<> chosenBaaSeed(bool sender, PRNG& prng, Socket& chl, block& seed); +} diff --git a/libOTe/Tools/BlkAccCode/README.md b/libOTe/Tools/BlkAccCode/README.md new file mode 100644 index 00000000..ba151811 --- /dev/null +++ b/libOTe/Tools/BlkAccCode/README.md @@ -0,0 +1,230 @@ +# BAA profiles + +Use `BinaryBAA` for binary codes and `ChosenBAA30` for large fields. +Both provide `config(n, seed)`, `encode(message, output, scratch)`, and +`dualEncode(inOut, scratch)`, with caller-owned buffers and no encoding allocations. + +```cpp +#include "libOTe/Tools/BlkAccCode/BinaryBAA.h" +#include "libOTe/Tools/BlkAccCode/ChosenBAA30.h" +osuCrypto::BinaryBAA<> binary; // block stores 128 independent binary lanes +osuCrypto::ChosenBAA30<> field; // GF(2^128) +``` + +BinaryBAA uses RM(2,5)[32,16,8] and XOR scans, with the length-specific +10% certificate at n=2^21. It supplies no extension-field lane mixing. +ChosenBAA30 uses RS[16,8,9] and 256 nonzero scan coefficients, with the +30.524% direct-rank certificate at n=2^21. Certificates assume ideal +uniform setup; the distance tiers are tuning values at other lengths. +ChosenBAA30 retains a compile-time field policy, including Goldilocks +correctness coverage. Optimized Fp128 reference timings are separate. + +`MultType::BinaryBAA` is available in binary Silent OT, including packed +and separate choice bits. Silent VOLE rejects this binary selector. +`MultType::ChosenBAA30` is the GF128 Silent VOLE and volePSI default. +Other VOLE fields and the Silent OT default retain their existing defaults. +Both protocol integrations use a joint committed seed exchange. At the default +security setting, BinaryBAA selects 200 regular or 424 stationary noise positions; +ChosenBAA30 selects 128 for either distribution. BinaryBAA lengths are +multiples of 32 fitting u32; ChosenBAA30 lengths are multiples of 16 up to +2^24. The former ChosenBaa10 field-dependent API has been removed. + +The exploratory q=1/q=2 variants, proof notes, and timing snapshots are +archived in gen-BAA under field-universality/libote-baa-exploration/2026-11-14. +The prime-field Newton low tier is preserved in that archive, not exposed as a +BinaryBAA backend. + +## Legacy full-field profiles + +The older `ChosenBaa16x8` and `ChosenBaa16x4` selections remain available with +their original code maps and seed streams. The remainder of this note describes +those profiles and their historical measurements. + +`ChosenBaa16x8` uses the systematic RS[16,8,9] constituent over GF(2^128). +`ChosenBaa16x4` uses RS[16,4,13]. Both profiles apply two independently +weighted accumulator stages and two independent Fisher--Yates shuffles. +The implementation uses the polynomial basis of cryptoTools `block::gf128Mul`. + +The transpose encoder accepts `n` field elements, where `n` is a positive +multiple of 16 below 2^32. It replaces the input prefix with `n/2` or `n/4` +outputs. The paired interface applies the same matrix to two separate buffers. +It shares permutation traversal and coefficient generation between the buffers. +The encoder modifies its input and allocates scratch once per call. + +The local RS map and fused scan/multiply/scatter follow +[the chosen-block BAA implementation](https://github.com/ladnir/libOTe/blob/fa7bfc3c8a0178fc99b0b666d5f31fc2a9277579/libOTe/Tools/Ppcg/ChosenBlockBaa.h). +The VOLE port specializes the local dimension at compile time, batches eight +scan positions, and generates weights during encoding. It does not retain +two arrays of field weights or create worker threads. The shuffle sampler uses +rejection sampling; power-of-two lengths do not select a Feistel permutation. + +## Seed exchange + +Each chosen-BAA VOLE call establishes a fresh public seed before generating +base correlations. The sender samples 16 bytes and sends their domain-separated +32-byte hash. The receiver sends its own fresh 16-byte contribution. The sender +opens its commitment, and the receiver verifies it. Both parties XOR the +contributions to obtain the code seed. An invalid opening aborts the protocol. +This adds three messages, totaling 64 payload bytes, including in reduced-round +applications. Both peers must select the same profile and protocol version. + +This exchange relies on the hash commitment's hiding and binding properties. +It prevents a party from adapting its contribution to the other contribution +without breaking those properties. It does not prevent selective aborts. +AES expands the seed into separate permutation and weight streams. Each weight +is sampled from the nonzero field elements by rejection. + +## Security scope and parameters + +[Chosen-Block BAA Codes](https://eprint.iacr.org/2026/1903) analyzes independent +uniform permutations and independent uniform nonzero field weights. Its +[finite certificates](https://github.com/ladnir/gen-BAA/tree/main/rs-certification) +give the following code-sampling bounds at message dimension `k = 2^20`: + +| Constituent | Code length | Relative distance | Sampling failure | +|---|---:|---:|---:| +| RS[16,8,9] | 2^21 | 0.30 | < 2^-137.56 | +| RS[16,4,13] | 2^22 | 0.60 | < 2^-209.60 | + +These bounds concern the ideal random code ensemble over fields of order at +least 2^127. They are not a proof for every requested length, a particular +seed, AES-expanded public randomness, or the complete VOLE protocol. +Using seeded randomness retains a cryptographic assumption about the resulting +code ensemble. A fresh joint seed alone does not remove that assumption. + +The adapter uses pseudo-distance 0.30 for RS[16,8,9] and 0.60 for RS[16,4,13]. +These are engineering choices informed by the paper, applied across supported +lengths as attack calibrations. They do not extend the finite certificates. +The 64-bit linear-character criterion gives rounded noise floors of 128 and +56 positions, respectively. The independent attack floor is `secParam` +positions at rate 1/2 and `ceil(secParam / 2)` at rate 1/4. The selector takes +the maximum of the distance requirement, attack floor, and implementation +minimum, then rounds up to eight positions. At the default `secParam = 128`, +the profiles therefore use 128 and 64 noise positions, respectively. +Increasing the pseudo-distances further would not lower this default count. +These calibrations are not a proof of 128-bit security for all sizes. +The rate-dependent floors reflect the different decoding costs; the historical +107-position SSD calibration is superseded by the stronger estimates in +[Regular Syndrome Decoding Is Easier Than Previously Estimated](https://arxiv.org/abs/2610.29175). + +The PPRF expands its physical prefix. The adapter pads that prefix with at +most 15 additional zeros when rounding to a multiple of 16, in addition to +any padding already selected by the generic adapter. Truncating the encoder's +output selects a subcode; zero-padding its input punctures the corresponding +forward code. Any finite certificate used for a concrete VOLE configuration +must account for those exact dimensions and punctured coordinates. + +Silent VOLE accepts these profiles only with `CoeffCtxGF128` and `block` for +both scalar and value types. Other field contexts require a separate port. +These legacy profiles are explicitly selected; the GF128 default is now +`ChosenBAA30` as described above. + +## Fields and arithmetic backends + +The standalone `ChosenBaaCode` encoder supports fields with sixteen +distinct evaluation points. `K` is 4 or 8. `F` defaults to `block` for GF(2^128), +and `Field` defaults to `ChosenBaaField`. For example, +`ChosenBaaCode<8, Goldilocks>` encodes over the Goldilocks prime field. The +generic policy uses field operators, `inverse()`, and a uniform `PRNG::Any` +constructor. Other representations can supply a stateless policy with the same +interface. Its `point(0)` through `point(15)` must be distinct, and `sample8` +must sample eight independent, uniform nonzero field elements. Byte copying +into modular representations does not satisfy that sampling contract. + +Field policies are selected at compile time. There are no virtual calls or +heap-allocated callbacks in the kernels. The fixed RS matrix is initialized +once per field/profile, cached immutably, and laid out by parity column so +consecutive output rows occupy consecutive SIMD lanes. Initialization is +thread-safe; configuration retains only a pointer to the matrix. The public +seed, shuffles, nonzero-weight draw order, and GF(2^128) outputs are unchanged. + +GF(2^128) has the following statically selected paths: + +* AVX-512 plus VPCLMUL: four independent field products per vector, batched + accumulator products, and four RS output rows per vector. +* AVX2 plus VPCLMUL: two RS output rows per vector. Accumulator products keep + the interleaved 128-bit schedule, which performs better on large paired + inputs than the tested two-lane accumulator schedules. +* AVX2/PCLMUL without VPCLMUL: interleaved 128-bit products and fixed RS kernels. +* Apple ARM: hardware PMULL products and ARM AES expansion. +* Portable: fixed-operation polynomial multiplication built from 32-bit integer + products, Karatsuba composition, and two fixed reduction folds. This removes + operand-dependent branches from these field-arithmetic routines; it is not a + claim about the constant-time behavior of every dependency or every CPU. + +`ENABLE_VPCLMUL` is detected on native x86 builds and can be disabled explicitly. +AVX2 and AVX-512 alone do not imply VPCLMUL support. As with the existing ISA +options, enabling it produces a binary requiring that instruction set; there is +no per-operation runtime dispatch. Cross builds default conservatively and must +select the intended target explicitly. `ENABLE_AVX512` selects the four-lane +path when VPCLMUL is enabled. + +The Silent VOLE adapter still accepts only GF(2^128). Generic encoder support +does not assign VOLE noise parameters or transfer the finite-distance +certificates to other fields. It is tested separately over Goldilocks for RS +interpolation, linearity, paired encoding, and the forward/transpose identity. + +## Reproducing encoder timings + +Configure with `-DLIBOTE_BAA_BENCHMARK=ON`, then build the +`chosen_baa_benchmark` target and run it with a physical input length, for +example `chosen_baa_benchmark 1048576`. It reports configuration, single-vector, +and paired-vector times separately, as medians of five trials after one warmup. +Allocation of encoding scratch is included; generating inputs and checking all +paired outputs against the single-vector result are outside the timed regions. +Run only one benchmark at a time. These are encoder timings, not complete VOLE +or PSI timings. + +Native measurements on November 13, 2026, used the same fixed inputs and seeds +before and after the optimization. The baseline is libOTe `1afe55bb` with +cryptoTools `12fa6f9`. All runs were sequential. Times below are milliseconds +for the half-rate profile; each row compares the same machine and input length. + +| Machine / backend | Input length | Single before | Single after | Pair before | Pair after | +| --- | ---: | ---: | ---: | ---: | ---: | +| Ryzen 7950X, AVX2/PCLMUL | 1,048,576 | 29.58 | 30.01 | 65.84 | 65.30 | +| Ryzen 7950X, AVX2 + VPCLMUL | 1,048,576 | 29.58 | 26.23 | 65.84 | 57.43 | +| Ryzen 7950X, AVX-512 + VPCLMUL | 1,048,576 | 29.58 | 24.78 | 65.84 | 53.84 | +| Apple M3, ARM AES/PMULL | 1,048,576 | 788.32 | 18.17 | 1,573.23 | 34.02 | +| Apple M3, portable arithmetic and AES | 65,536 | 74.07 | 31.18 | 127.49 | 53.55 | + +The ordinary AVX2 path is effectively unchanged in this measurement. The large +ARM improvement primarily fixes the previous accidental software-multiply +dispatch. Backend comparisons against the original encoder, plus independent +bit-polynomial arithmetic tests, check correctness separately from timings. + +### Prefetch follow-up + +The x86 GF(2^128) path now prefetches eight random destination cache lines 64 +entries ahead, retaining the eight-entry arithmetic schedule. The hint uses +`_MM_HINT_T2` and requires no additional instruction-set feature. Both the +permutation-index reads and destination addresses stay in bounds; the final +eight batches issue no hints. A single dispatch per stage enables this loop +only at physical input lengths of at least 2^18. Smaller inputs, ARM, portable, +and generic-field policies retain their previous schedule. + +The following sequential Peach measurements compare the previous PR revision +`50f27b4d` with this follow-up using the same harness, flags, seeds, and half-rate +profile. Peach was pinned to CPU 2, with boost disabled and a 4.5 GHz setting; +the compiler was GCC 15.2 at `-O3`. Length means the number of input field +elements to the transpose encoder, whose output length is half as large. +Setup is excluded and scratch allocation is included, as in the preceding table. + +| Backend | Input length | Single before | Single after | Pair before | Pair after | +| --- | ---: | ---: | ---: | ---: | ---: | +| AVX-512 + VPCLMUL | 65,536 | 0.784 | 0.790 | 1.746 | 1.747 | +| AVX-512 + VPCLMUL | 1,048,576 | 23.84 | 13.72 | 51.63 | 34.68 | +| AVX-512 + VPCLMUL | 2,097,152 | 67.74 | 40.82 | 114.19 | 74.60 | +| AVX2 + VPCLMUL | 1,048,576 | 25.32 | 15.60 | 56.33 | 43.72 | +| AVX2/PCLMUL | 1,048,576 | 29.68 | 20.00 | 65.32 | 52.36 | + +Alternating repeat runs at 1,048,576 inputs measured 13.68--13.72 ms single and +34.68--34.85 ms paired for AVX-512. The smaller input showed no material change. +Tests around the dispatch threshold cover the non-power-of-two tail and the +forward/transpose identity. Native M3 experiments found no benefit from these +hints, so ARM keeps its existing schedule. Wider scatter batches and an +additional inverse-permutation gather pass were also measured and rejected. + +A separate stage-only comparison with identical precomputed full-field weights +measured 8.86 ms transpose and 9.06 ms forward at 2,097,152 elements on Peach. +This excludes weight generation and the RS map and is not a full-encoder timing. diff --git a/libOTe/Tools/BlkAccCode/ReedMullerBaaCode.h b/libOTe/Tools/BlkAccCode/ReedMullerBaaCode.h new file mode 100644 index 00000000..ee7cbd0d --- /dev/null +++ b/libOTe/Tools/BlkAccCode/ReedMullerBaaCode.h @@ -0,0 +1,221 @@ +#pragma once +#include "ChosenBaaField.h" +#include "cryptoTools/Common/Aligned.h" +#include "libOTe/Tools/CompilerHints.h" +#include +#include +#include + +namespace osuCrypto +{ + // RM(2,5)[32,16,8], followed by two independently permuted plain + // accumulators. Valid over characteristic-two fields. Extension of the + // binary generator preserves its minimum Hamming distance exactly. + // The finite binary certificate is length-specific; see the benchmark note. + template> + class ReedMullerBaaCode + { + u64 mN = 0; + std::array, 2> mPerm; + AlignedUnVector mInverseFirst; +#if defined(__aarch64__) || defined(_M_ARM64) + // Native M3 measurements favor the direct scatter/compression path. + static constexpr bool fusedTranspose = false; +#else + static constexpr bool fusedTranspose = true; +#endif + static constexpr std::array monomials{ + 0,1,2,3,4,5,6,8,9,10,12,16,17,18,20,24 }; + + static u32 below(PRNG& random, u32 bound) + { + u64 p = u64(random.get()) * bound; + if (u32(p) < bound) + { + const auto threshold = (u32(0) - bound) % bound; + while (u32(p) < threshold) p = u64(random.get()) * bound; + } + return u32(p >> 32); + } + template + static OC_FORCEINLINE void butterfly(F* v) + { + if constexpr (I < 32) + { + if constexpr (I & (1u << Bit)) + { + if constexpr (Transpose) v[I ^ (1u << Bit)] = Field::add(v[I ^ (1u << Bit)], v[I]); + else v[I] = Field::add(v[I], v[I ^ (1u << Bit)]); + } + butterfly(v); + } + } + template + static OC_FORCEINLINE void transform(F* v) + { + // The five tensor factors commute, including after transposition. + if constexpr (Bit < 5) + { + butterfly(v); + transform(v); + } + } + template + static OC_FORCEINLINE void loadMessage(const F* in, F* v) + { + if constexpr (I < 16) { v[monomials[I]] = in[I]; loadMessage(in, v); } + } + template + static OC_FORCEINLINE void storeMessage(const F* v, F* out) + { + if constexpr (I < 16) { out[I] = v[monomials[I]]; storeMessage(v, out); } + } + template + static OC_FORCEINLINE void prefetch(const F* in, F* out, const u32* p) + { + if constexpr (J < 16) + { +#ifdef OC_ENABLE_SSE2 + const F* address = Transpose ? out + p[J] : in + p[J]; + _mm_prefetch(reinterpret_cast(address), _MM_HINT_T2); +#endif + prefetch(in, out, p); + } + } + template + static OC_FORCEINLINE void gather(const F* in, const u32* p, F* v) + { + if constexpr (J < 16) { v[J] = in[p[J]]; gather(in, p, v); } + } + template + static OC_FORCEINLINE void accumulate(const F* in, F* out, const u32* p, F& sum) + { + if constexpr (J < 16) + { + constexpr auto pos = Transpose ? 15 - J : J; + sum = Field::add(sum, in[pos]); + if constexpr (Transpose) out[p[pos]] = sum; + else out[pos] = sum; + accumulate(in, out, p, sum); + } + } + template + void stage(const F* in, F* out, unsigned which) const + { + F sum = Field::zero(); + const auto* p = mPerm[which].data(); + for (u64 j = 0; j < mN; j += 16) + { + const u64 i = Transpose ? mN - j - 16 : j; + constexpr u64 lead = 256; + if (j + lead + 16 <= mN) + { + const u64 ahead = Transpose ? i - lead : i + lead; + prefetch(in, out, p + ahead); + } + if constexpr (Transpose) accumulate(in + i, out, p + i, sum); + else + { + std::array v; + gather(in, p + i, v.data()); + accumulate(v.data(), out + i, p + i, sum); + } + } + } + template + static OC_FORCEINLINE void suffixBatch(F* in, F& sum) + { + if constexpr (J < 16) + { + constexpr unsigned pos = 15 - J; + in[pos] = sum = Field::add(sum, in[pos]); + suffixBatch(in, sum); + } + } + void finishTranspose(F* in, F* out) const + { + // Separate the contiguous suffix scan from the permutation, then + // fuse its inverse gather with local compression. This avoids a + // full random-write pass and an additional read of the codeword. + F sum = Field::zero(); + for (u64 end = mN; end; end -= 16) suffixBatch(in + end - 16, sum); + const auto* p = mInverseFirst.data(); + for (u64 i = 0; i < mN; i += 32) + { + if (i + 256 + 32 <= mN) + { + prefetch(in, out, p + i + 256); + prefetch(in, out, p + i + 272); + } + std::array v; + gather(in, p + i, v.data()); + gather(in, p + i + 16, v.data() + 16); + localTranspose(v.data(), out + i / 2); + } + } + public: + void config(u64 n, block seed) + { + if (!n || n % 32 || n > std::numeric_limits::max()) + throw std::invalid_argument("RM BAA length must be a positive multiple of 32 fitting u32."); + if (Field::add(Field::one(), Field::one()) != Field::zero()) + throw std::invalid_argument("RM BAA requires characteristic two."); + PRNG master(seed); + const std::array seeds{master.get(), master.get()}; + for (unsigned s = 0; s < 2; ++s) + { + auto& p = mPerm[s]; p.resize(n); + for (u64 i = 0; i < n; ++i) p[i] = u32(i); + PRNG random(seeds[s]); + for (u64 i = n; i > 1; --i) std::swap(p[i - 1], p[below(random, u32(i))]); + } + if constexpr (fusedTranspose) + { + mInverseFirst.resize(n); + for (u64 i = 0; i < n; ++i) mInverseFirst[mPerm[0][i]] = u32(i); + } + mN = n; + } + u64 messageSize() const { return mN / 2; } + u64 codewordSize() const { return mN; } + u32 permutationIndex(unsigned stage, u64 i) const + { + if (i >= mN) throw std::out_of_range("RM BAA permutation index."); + return mPerm.at(stage)[i]; + } + static void localEncode(const F* in, F* out) + { + std::array v; + v.fill(Field::zero()); loadMessage(in, v.data()); transform(v.data()); + std::copy(v.begin(), v.end(), out); + } + static void localTranspose(const F* in, F* out) + { + std::array v; + std::copy_n(in, 32, v.data()); transform(v.data()); storeMessage(v.data(), out); + } + // Caller-owned, disjoint buffers; no allocation during encoding. + void encode(span input, span output, span scratch) const + { + if (!mN || input.size() != messageSize() || output.size() != mN || scratch.size() != mN) + throw std::invalid_argument("RM BAA forward buffer size."); + for (u64 i = 0; i < mN / 32; ++i) localEncode(input.data() + 16 * i, output.data() + 32 * i); + stage(output.data(), scratch.data(), 0); + stage(scratch.data(), output.data(), 1); + } + // In place, producing the message-size prefix. Scratch is disjoint. + void dualEncode(span inOut, span scratch) const + { + if (!mN || inOut.size() != mN || scratch.size() != mN) + throw std::invalid_argument("RM BAA transpose buffer size."); + stage(inOut.data(), scratch.data(), 1); + if constexpr (fusedTranspose) finishTranspose(scratch.data(), inOut.data()); + else + { + stage(scratch.data(), inOut.data(), 0); + for (u64 i = 0; i < mN / 32; ++i) + localTranspose(inOut.data() + 32 * i, inOut.data() + 16 * i); + } + } + }; +} diff --git a/libOTe/Tools/BlkAccCode/SmallAlphabetBaaCode.h b/libOTe/Tools/BlkAccCode/SmallAlphabetBaaCode.h new file mode 100644 index 00000000..9a43310c --- /dev/null +++ b/libOTe/Tools/BlkAccCode/SmallAlphabetBaaCode.h @@ -0,0 +1,243 @@ +#pragma once +#include "ChosenBaaCode.h" +#include +#include "AdditiveRs8.h" +#include "SmallBaaGfni.h" + +namespace osuCrypto +{ + template> + struct SmallBaaArithmetic + { + static F madd(F state, u32 coefficient, F input) + { return Field::add(input, Field::mul(state, Field::point(coefficient - 1))); } + }; + template<> + struct SmallBaaArithmetic> + { + // Polynomial coefficient 1..256 in the canonical GF(2^128) basis. + // Two independent 64x9 carryless products; the overflow has at most + // eight bits, so multiplication by x^7+x^2+x+1 cannot overflow again. + static OC_FORCEINLINE block madd(block state, u32 coefficient, block input) + { +#if defined(OC_ENABLE_SSE2) && defined(__GFNI__) + return chosen_baa_detail::smallGfniMadd(state, coefficient, input); +#else + const block c(0, coefficient); + const auto lo = state.clmulepi64_si128<0x00>(c); + const auto hi = state.clmulepi64_si128<0x01>(c); + const auto overflow = hi.srli_si128<8>(); + return input ^ lo ^ hi.slli_si128<8>() ^ overflow ^ + overflow.slli_epi64(1) ^ overflow.slli_epi64(2) ^ overflow.slli_epi64(7); +#endif + } + }; + + // [16,8,9] RS followed by two permuted recursive scans. Independent + // coefficients use 256 distinct nonzero field elements. This is a + // different map from ChosenBaaCode's full-field weighted accumulators. + // Packed metadata supports n <= 2^24, with eight coefficient bits. + template, + typename Arithmetic = SmallBaaArithmetic> + class SmallAlphabetBaaCode + { + static constexpr u32 indexMask = (1u << 24) - 1; + u64 mN = 0; + std::array, 2> mMeta; + std::array mMatrix, mForward; + static constexpr bool additiveLocal = std::is_same_v>; +#if defined(OC_ENABLE_SSE2) && defined(OC_ENABLE_VPCLMUL) + // A short, fully unrolled GF128 recurrence schedules better than sixteen + // live steps on the measured x86 backends. Other field/backends retain + // the existing sixteen-element schedule. + static constexpr unsigned scanBatch = additiveLocal ? 4 : 16; +#else + static constexpr unsigned scanBatch = 16; +#endif + chosen_baa_detail::AdditiveRs8 mAdditive; + static u32 below(PRNG& random, u32 bound) + { + u64 p = u64(random.get()) * bound; + if (u32(p) < bound) + { + const auto threshold = (u32(0) - bound) % bound; + while (u32(p) < threshold) p = u64(random.get()) * bound; + } + return u32(p >> 32); + } + static void shuffle(AlignedUnVector& p, PRNG& random) + { + constexpr u64 batch = 64; + std::array indices; + u64 i = p.size(); + for (; i > batch; i -= batch) + { + // Draw in exactly the scalar Fisher--Yates order, including + // rejection draws. Only the memory accesses are scheduled ahead. + for (u64 j = 0; j < batch; ++j) + { + indices[j] = below(random, u32(i - j)); +#if defined(__GNUC__) || defined(__clang__) + __builtin_prefetch(p.data() + indices[j], 1, 3); +#elif defined(OC_ENABLE_SSE2) + _mm_prefetch(reinterpret_cast(p.data() + indices[j]), _MM_HINT_T0); +#endif + } + // Swaps must stay ordered: sampled indices can coincide or + // refer to another position in this batch. + for (u64 j = 0; j < batch; ++j) + std::swap(p[i - j - 1], p[indices[j]]); + } + for (; i > 1; --i) std::swap(p[i - 1], p[below(random, u32(i))]); + } + template + static OC_FORCEINLINE void prefetch(const F* in, F* out, const u32* p) + { + if constexpr (J < scanBatch) + { +#ifdef OC_ENABLE_SSE2 + const F* address = Transpose ? out + (p[J] & indexMask) : in + (p[J] & indexMask); + _mm_prefetch(reinterpret_cast(address), _MM_HINT_T2); +#endif + prefetch(in, out, p); + } + } + template + static OC_FORCEINLINE void gather(const F* in, const u32* p, F* values) + { + if constexpr (J < scanBatch) { values[J] = in[p[J] & indexMask]; gather(in, p, values); } + } + template + static OC_FORCEINLINE void forwardBatch(const F* values, F* out, const u32* p, F& sum) + { + if constexpr (J < scanBatch) + { + out[J] = sum = Arithmetic::madd(sum, (p[J] >> 24) + 1, values[J]); + forwardBatch(values, out, p, sum); + } + } + template + static OC_FORCEINLINE void transposeBatch(const F* in, F* out, const u32* p, F& sum, u32& coefficient) + { + if constexpr (J < scanBatch) + { + constexpr auto pos = scanBatch - 1 - J; + sum = Arithmetic::madd(sum, coefficient, in[pos]); + coefficient = (p[pos] >> 24) + 1; + out[p[pos] & indexMask] = sum; + transposeBatch(in, out, p, sum, coefficient); + } + } + template + void stage(const F* in, F* out, unsigned which) const + { + const auto* p = mMeta[which].data(); + F sum = Field::zero(); + u32 coefficient = 1; + for (u64 j = 0; j < mN; j += scanBatch) + { + const u64 i = Transpose ? mN - j - scanBatch : j; + constexpr u64 lead = 256; + if (j + lead + scanBatch <= mN) + prefetch(in, out, p + (Transpose ? i - lead : i + lead)); + if constexpr (Transpose) transposeBatch(in + i, out, p + i, sum, coefficient); + else + { + std::array values; + gather(in, p + i, values.data()); + forwardBatch(values.data(), out + i, p + i, sum); + } + } + } + public: + void config(u64 n, block seed) + { + if (!n || n % 16 || n > (1u << 24)) throw std::invalid_argument("Small-alphabet BAA length."); + // The proof requires distinct nonzero alphabet elements, not + // integer scalar multiples of one in positive characteristic. + for (u64 i = 0; i < 256; ++i) + { + const F c = Field::point(i); + if (c == Field::zero()) throw std::invalid_argument("BAA coefficient alphabet contains zero."); + for (u64 j = 0; j < i; ++j) + if (c == Field::point(j)) throw std::invalid_argument("BAA coefficient alphabet repeats."); + } + using LocalField = std::conditional_t; + ChosenBaaCode<8, F, LocalField> local; + local.config(16, seed); + for (u64 row = 0; row < 8; ++row) for (u64 col = 0; col < 8; ++col) + mMatrix[col * 8 + row] = mForward[row * 8 + col] = local.matrix(row, col); + if constexpr (additiveLocal) + { + for (u64 i = 0; i < 8; ++i) for (u64 j = 0; j < 8; ++j) + if (mMatrix[i * 8 + j] != mMatrix[i ^ j]) throw std::logic_error("Additive RS symmetry."); + mAdditive.init(mMatrix.data()); + } + PRNG master(seed); + const std::array permutationSeeds{master.get(), master.get()}; + const std::array coefficientSeeds{master.get(), master.get()}; + for (unsigned s = 0; s < 2; ++s) + { + auto& p = mMeta[s]; p.resize(n); + for (u64 i = 0; i < n; ++i) p[i] = u32(i); + PRNG random(permutationSeeds[s]), coefficients(coefficientSeeds[s]); + shuffle(p, random); + for (u64 i = 0; i < n; ) + { + // Consume the same byte stream in contiguous chunks, so + // packing coefficients can vectorize without per-byte PRNG + // calls. Consume the view before the next PRNG operation. + const auto bytes = coefficients.getBufferSpan(n - i); + for (u64 j = 0; j < bytes.size(); ++j) + p[i + j] |= u32(bytes[j]) << 24; + i += bytes.size(); + } + } + mN = n; + } + u64 messageSize() const { return mN / 2; } + u64 codewordSize() const { return mN; } + u32 metadata(unsigned stage, u64 i) const + { + if (i >= mN) throw std::out_of_range("Small-alphabet BAA metadata index."); + return mMeta.at(stage)[i]; + } + F matrix(u64 row, u64 col) const + { + if (row >= 8 || col >= 8 || !mN) throw std::out_of_range("Small-alphabet BAA matrix index."); + return mMatrix[col * 8 + row]; + } + // Caller-owned disjoint buffers. No allocation inside either encoder. + void encode(span input, span output, span scratch) const + { + if (!mN || input.size() != mN / 2 || output.size() != mN || scratch.size() != mN) + throw std::invalid_argument("Small-alphabet BAA forward buffer size."); + for (u64 i = 0; i < mN / 16; ++i) + { + const auto* src = input.data() + 8 * i; auto* dst = output.data() + 16 * i; + std::copy_n(src, 8, dst); + if constexpr (additiveLocal) mAdditive.apply(src, dst + 8); + else Field::template localForward<8>(src, dst, mForward.data()); + } + stage(output.data(), scratch.data(), 0); + stage(scratch.data(), output.data(), 1); + } + void dualEncode(span inOut, span scratch) const + { + if (!mN || inOut.size() != mN || scratch.size() != mN) + throw std::invalid_argument("Small-alphabet BAA transpose buffer size."); + stage(inOut.data(), scratch.data(), 1); + stage(scratch.data(), inOut.data(), 0); + for (u64 i = 0; i < mN / 16; ++i) + { + if constexpr (additiveLocal) + { + std::array values; + mAdditive.apply(inOut.data() + 16 * i + 8, values.data()); + for (u64 j = 0; j < 8; ++j) inOut[8 * i + j] = inOut[16 * i + j] ^ values[j]; + } + else Field::template local<8>(inOut.data() + 16 * i, inOut.data() + 8 * i, mMatrix.data()); + } + } + }; +} diff --git a/libOTe/Tools/BlkAccCode/SmallBaaGfni.h b/libOTe/Tools/BlkAccCode/SmallBaaGfni.h new file mode 100644 index 00000000..c568e919 --- /dev/null +++ b/libOTe/Tools/BlkAccCode/SmallBaaGfni.h @@ -0,0 +1,67 @@ +#pragma once +#include "ChosenBaaField.h" +#include + +#if defined(OC_ENABLE_SSE2) && defined(__GFNI__) +#include + +namespace osuCrypto::chosen_baa_detail +{ + // GFNI applies an 8x8 binary matrix to each byte. Its matrix row for + // output bit i occupies byte 7-i. These are polynomial products, not + // multiplication in GF(256): bytes carry into the next byte of GF(2^128). + struct alignas(64) SmallGfniMatrices + { + u64 lo, loCopy, hi, hiCopy, foldLo, foldHi; + }; + + constexpr std::array smallGfniMatrices() + { + std::array result{}; + for (unsigned c = 1; c <= 256; ++c) + { + auto& m = result[c - 1]; + for (unsigned j = 0; j < 8; ++j) + { + const unsigned product = c << j; + unsigned folded = 0; + // The highest byte's overflow is reduced modulo + // x^128 + x^7 + x^2 + x + 1. It occupies at most two bytes. + for (unsigned k = 0; k < 8; ++k) + if ((product >> 8) & (1u << k)) folded ^= 0x87u << k; + for (unsigned i = 0; i < 8; ++i) + { + const auto bit = u64{1} << (8 * (7 - i) + j); + if ((product >> i) & 1) m.lo |= bit; + if ((product >> (i + 8)) & 1) m.hi |= bit; + if ((folded >> i) & 1) m.foldLo |= bit; + if ((folded >> (i + 8)) & 1) m.foldHi |= bit; + } + } + m.loCopy = m.lo; m.hiCopy = m.hi; + } + return result; + } + + // The 16 KiB table is shared by all instances. Its layout avoids two + // broadcasts per recurrence step; each selector touches one cache line. + // Selection depends only on the code's public coefficient, never input. + inline constexpr auto smallGfniTable = smallGfniMatrices(); + + OC_FORCEINLINE block smallGfniMadd(block state, u32 coefficient, block input) + { + const auto& m = smallGfniTable[coefficient - 1]; + const auto lo = _mm_gf2p8affine_epi64_epi8(state, + _mm_loadu_si128(reinterpret_cast(&m.lo)), 0); + const auto hi = _mm_gf2p8affine_epi64_epi8(state, + _mm_loadu_si128(reinterpret_cast(&m.hi)), 0); + const auto top = _mm_shuffle_epi8(state, _mm_set1_epi8(15)); + auto fold = _mm_gf2p8affine_epi64_epi8(top, + _mm_loadu_si128(reinterpret_cast(&m.foldLo)), 0); + // Low and high reduction bytes were computed in separate quadwords. + fold = _mm_shuffle_epi8(fold, + _mm_setr_epi8(0, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1)); + return input ^ block(lo) ^ block(_mm_slli_si128(hi, 1)) ^ block(fold); + } +} +#endif diff --git a/libOTe/TwoChooseOne/ConfigureCode.cpp b/libOTe/TwoChooseOne/ConfigureCode.cpp index 503acfae..200ce9be 100644 --- a/libOTe/TwoChooseOne/ConfigureCode.cpp +++ b/libOTe/TwoChooseOne/ConfigureCode.cpp @@ -25,16 +25,18 @@ namespace osuCrypto // floor is ceil(-64/log2(1-a*delta)), where a is the applicable factor. // // Second, pseudo distance does not model the best non-linear/algebraic - // attacks. We independently require at least secParam noise positions. + // attacks. The caller supplies an independent noise-position floor: + // secParam normally, or ceil(secParam/2) for quarter-rate chosen BAA. // Current regular-LPN estimates put the small binary N=2048, t=128 case // below 128 bits, so binary regular-noise sizes through 2048 use - // ceil(9*secParam/8) instead. + // ceil(9*noisePositionFloor/8) instead. // // For stationary noise, this floor counts the secret support positions, // not the nonzero coefficients in one sampled error vector. The SSD // algebraic analysis already models coefficients uniform in the field, - // including zero, and its evaluated rate-one-half instances require at - // most 107 support positions for 128-bit security. Scaling this floor by + // including zero. The former calibration from 107 support positions is + // superseded by stronger RSD estimates (arxiv.org/abs/2610.29175). + // Scaling this floor by // the reciprocal nonzero probability would instead partially reinstate a // 128-bit linear-test requirement: the effect of zero coefficients on // linear tests (including ISD-style tests) is already captured by the @@ -48,14 +50,15 @@ namespace osuCrypto u64 getRegNoiseWeight( double pseudoMinDistRatio, u64 N, - u64 secParam, + u64 noisePositionFloor, SdNoiseDistribution nd, SdNoiseSecurityModel securityModel) { constexpr u64 pseudoDistanceSecurity = 64; - if (pseudoMinDistRatio > 0.5 || pseudoMinDistRatio <= 0) - throw RTE_LOC; + if (!std::isfinite(pseudoMinDistRatio) || + pseudoMinDistRatio > 1.0 || pseudoMinDistRatio <= 0) + throw std::invalid_argument("Pseudo distance must be in (0, 1]. " LOCATION); if (!std::isfinite(securityModel.mRegularNoiseFactor) || securityModel.mRegularNoiseFactor < 1.0 || securityModel.mRegularNoiseFactor > 2.0) @@ -70,15 +73,22 @@ namespace osuCrypto else throw RTE_LOC; - const auto bias = 1.0 - hitFactor * pseudoMinDistRatio; - const auto pseudoDistanceWeight = bias == 0.0 ? u64{ 1 } : - static_cast(std::ceil( - -double(pseudoDistanceSecurity) / std::log2(bias))); + // Large-field distances may exceed 1/2. The supported character + // bound requires nonnegative bias, so the limit depends on the noise + // distribution (1/2 for binary regular noise, 1 for stationary noise). + const auto decay = hitFactor * pseudoMinDistRatio; + if (decay > 1.0) + throw std::invalid_argument("Pseudo distance gives a negative character bias. " LOCATION); + const auto requiredWeight = decay == 1.0 ? 1.0 : std::ceil( + -double(pseudoDistanceSecurity) * std::log(2.0) / std::log1p(-decay)); + if (!std::isfinite(requiredWeight) || requiredWeight >= std::ldexp(1.0, 64)) + throw std::invalid_argument("Pseudo-distance noise weight exceeds the supported range. " LOCATION); + const auto pseudoDistanceWeight = static_cast(requiredWeight); - auto attackWeight = secParam; + auto attackWeight = noisePositionFloor; if (nd == SdNoiseDistribution::Regular && securityModel.mRegularNoiseFactor == 2.0 && N <= 2048) - attackWeight = divCeil(secParam * 9, u64{ 8 }); + attackWeight = divCeil(noisePositionFloor * 9, u64{ 8 }); auto t = std::max({ u64{ 40 }, pseudoDistanceWeight, attackWeight }); if(N < 512) diff --git a/libOTe/TwoChooseOne/ConfigureCode.h b/libOTe/TwoChooseOne/ConfigureCode.h index 67a2ad35..948e747b 100644 --- a/libOTe/TwoChooseOne/ConfigureCode.h +++ b/libOTe/TwoChooseOne/ConfigureCode.h @@ -68,6 +68,10 @@ namespace osuCrypto // experimental Tungsten = 12, // very fast, based on turbo codes. Unknown min distance. + ChosenBaa16x8 = 14, // GF(2^128), RS[16,8,9], two weighted accumulators. + ChosenBaa16x4 = 15, // GF(2^128), RS[16,4,13]. + BinaryBAA = 16, // Binary-only RM BAA, rate 1/2, 10% distance tier. + ChosenBAA30 = 17, // Rate 1/2, 30% distance tier; backend depends on field. Spin = 13 // BCH-SPIN; BAA-style 0.25 linear-attack tuning (not minimum distance). }; @@ -75,6 +79,18 @@ namespace osuCrypto { switch (m) { + case MultType::BinaryBAA: + o << "BinaryBAA"; + break; + case MultType::ChosenBAA30: + o << "ChosenBAA30"; + break; + case MultType::ChosenBaa16x8: + o << "ChosenBaa16x8"; + break; + case MultType::ChosenBaa16x4: + o << "ChosenBaa16x4"; + break; case MultType::Spin: o << "Spin"; break; @@ -108,13 +124,19 @@ namespace osuCrypto return o; } + constexpr bool isChosenBaa(MultType type) + { + return type == MultType::ChosenBAA30 || + type == MultType::ChosenBaa16x8 || type == MultType::ChosenBaa16x4; + } + constexpr MultType DefaultMultType = MultType::BlkAcc3x32; u64 getRegNoiseWeight( double pseudoMinDistRatio, u64 N, - u64 secParam, + u64 noisePositionFloor, SdNoiseDistribution noiseType, SdNoiseSecurityModel securityModel); @@ -257,6 +279,23 @@ namespace osuCrypto case MultType::QuasiCyclic: QuasiCyclicConfigure(scaler, minDist); break; + case MultType::BinaryBAA: + case MultType::ChosenBAA30: + scaler = 2; + // Distance-tier tuning at arbitrary lengths, not a finite-size + // certificate. Both retain the independent half-rate noise floor. + minDist = multType == MultType::BinaryBAA ? 0.10 : 0.30; + break; + case MultType::ChosenBaa16x8: + case MultType::ChosenBaa16x4: + scaler = multType == MultType::ChosenBaa16x8 ? 2 : 4; + // Pseudo-distance tuning informed by the RS BAA paper. These + // are attack estimates at arbitrary lengths, not an extension + // of the finite certificates at k=2^20. Keep the independent + // rate-dependent noise-position floor below, independently of + // the distance requirement in getRegNoiseWeight. + minDist = multType == MultType::ChosenBaa16x8 ? 0.30 : 0.60; + break; case MultType::BlkAcc3x8: case MultType::BlkAcc3x32: { @@ -277,6 +316,12 @@ namespace osuCrypto SdConfig config; + // Chosen BAA uses secParam positions at rate 1/2 and ceil(secParam/2) + // at rate 1/4. This is an attack-cost calibration, not a security proof. + // Only the independent attack floor scales; the distance bound does not. + const u64 noisePositionFloor = multType == MultType::ChosenBaa16x4 + ? secParam / 2 + secParam % 2 : secParam; + auto baseSize = roundUpTo(requestSize * scaler, 2); const bool preferPow2 = @@ -286,7 +331,7 @@ namespace osuCrypto if (preferPow2) { config.mNumPartitions = roundUpTo(getRegNoiseWeight( - minDist, baseSize, secParam, noiseType, securityModel), 2); + minDist, baseSize, noisePositionFloor, noiseType, securityModel), 2); config.mSizePer = std::max(4, roundUpTo(baseSize / config.mNumPartitions, 2)); config.mNoiseVectorSize = std::max(baseSize, config.mNumPartitions * config.mSizePer); @@ -304,10 +349,20 @@ namespace osuCrypto { // non power of two case. config.mNumPartitions = roundUpTo(getRegNoiseWeight( - minDist, baseSize, secParam, noiseType, securityModel), 2); + minDist, baseSize, noisePositionFloor, noiseType, securityModel), 2); config.mSizePer = std::max(4, roundUpTo(divCeil(baseSize, config.mNumPartitions), 2)); config.mNoiseVectorSize = config.mNumPartitions * config.mSizePer; } + if (isChosenBaa(multType) || multType == MultType::BinaryBAA) + { + config.mNoiseVectorSize = roundUpTo( + std::max(config.mNoiseVectorSize, config.mNumPartitions * config.mSizePer), + multType == MultType::BinaryBAA ? 32 : 16); + if (multType == MultType::ChosenBAA30 && config.mNoiseVectorSize > (u64{1} << 24)) + throw std::invalid_argument("ChosenBAA30 length exceeds its packed index space. " LOCATION); + if (config.mNoiseVectorSize > std::numeric_limits::max()) + throw std::invalid_argument("Chosen BAA length exceeds its index space. " LOCATION); + } return config; } } diff --git a/libOTe/TwoChooseOne/Silent/SilentOtExtReceiver.cpp b/libOTe/TwoChooseOne/Silent/SilentOtExtReceiver.cpp index 1aa36085..0a2b953d 100644 --- a/libOTe/TwoChooseOne/Silent/SilentOtExtReceiver.cpp +++ b/libOTe/TwoChooseOne/Silent/SilentOtExtReceiver.cpp @@ -1,3 +1,4 @@ +#include "libOTe/Tools/BlkAccCode/ChosenBaaVole.h" #include "libOTe/TwoChooseOne/Silent/SilentOtExtReceiver.h" #ifdef ENABLE_SILENTOT @@ -287,6 +288,9 @@ namespace osuCrypto if (numOTs == 0) throw std::invalid_argument("Silent OT count must be nonzero. " LOCATION); + if (isChosenBaa(multType)) + throw std::invalid_argument("Chosen BAA is a field code for Silent VOLE, not binary Silent OT. " LOCATION); + (void)scaler; if (malType != SilentSecType::SemiHonest && malType != SilentSecType::Malicious) @@ -575,6 +579,8 @@ namespace osuCrypto } // Apply compression to convert sparse to dense vector + if (mLpnMultType == MultType::BinaryBAA) + co_await chosenBaaSeed(false, prng, chl, mCodeSeed); compress(type); setTimePoint("recver.expand.dualEncode"); @@ -805,7 +811,10 @@ namespace osuCrypto mSpin->transpose(mA); break; #endif - case osuCrypto::MultType::QuasiCyclic: + case MultType::BinaryBAA: + binaryBaaCompress(mCodeSeed, mA); + break; + case osuCrypto::MultType::QuasiCyclic: { #ifdef ENABLE_BITPOLYMUL QuasiCyclicCode code; @@ -892,7 +901,10 @@ namespace osuCrypto mSpin->transpose(mC); break; #endif - case osuCrypto::MultType::QuasiCyclic: + case MultType::BinaryBAA: + binaryBaaCompress(mCodeSeed, mA, mC); + break; + case osuCrypto::MultType::QuasiCyclic: { #ifdef ENABLE_BITPOLYMUL QuasiCyclicCode code; diff --git a/libOTe/TwoChooseOne/Silent/SilentOtExtSender.cpp b/libOTe/TwoChooseOne/Silent/SilentOtExtSender.cpp index 5eb17f6b..4b322902 100644 --- a/libOTe/TwoChooseOne/Silent/SilentOtExtSender.cpp +++ b/libOTe/TwoChooseOne/Silent/SilentOtExtSender.cpp @@ -1,4 +1,5 @@ -#include "libOTe/TwoChooseOne/Silent/SilentOtExtSender.h" +#include "libOTe/Tools/BlkAccCode/ChosenBaaVole.h" +#include "libOTe/TwoChooseOne/Silent/SilentOtExtSender.h" #ifdef ENABLE_SILENTOT @@ -255,6 +256,9 @@ namespace osuCrypto if (numOTs == 0) throw std::invalid_argument("Silent OT count must be nonzero. " LOCATION); + if (isChosenBaa(mult)) + throw std::invalid_argument("Chosen BAA is a field code for Silent VOLE, not binary Silent OT. " LOCATION); + (void)scaler; if (malType != SilentSecType::SemiHonest && malType != SilentSecType::Malicious) @@ -612,6 +616,8 @@ namespace osuCrypto co_await checkRT(chl); // Apply compression to convert sparse to dense vector + if (mLpnMultType == MultType::BinaryBAA) + co_await chosenBaaSeed(true, prng, chl, mCodeSeed); compress(); setTimePoint("sender.expand.dualEncode"); @@ -681,7 +687,10 @@ namespace osuCrypto mSpin->transpose(mB); break; #endif - case osuCrypto::MultType::QuasiCyclic: + case MultType::BinaryBAA: + binaryBaaCompress(mCodeSeed, mB); + break; + case osuCrypto::MultType::QuasiCyclic: { #ifdef ENABLE_BITPOLYMUL // Use QuasiCyclic code for compression diff --git a/libOTe/Vole/Silent/SilentVoleReceiver.h b/libOTe/Vole/Silent/SilentVoleReceiver.h index 1a4ce44f..aea9b4ba 100644 --- a/libOTe/Vole/Silent/SilentVoleReceiver.h +++ b/libOTe/Vole/Silent/SilentVoleReceiver.h @@ -1,4 +1,5 @@ #pragma once +#include "libOTe/Tools/BlkAccCode/ChosenBaaVole.h" // © 2022 Visa. // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // @@ -134,7 +135,10 @@ namespace osuCrypto SdNoiseDistribution mNoiseType = SdNoiseDistribution::Regular; // The matrix multiplication type which compresses the sparse vector - MultType mLpnMultType = DefaultMultType; + static constexpr MultType DefaultCode = + std::is_same_v && std::is_same_v && std::is_same_v + ? MultType::ChosenBAA30 : DefaultMultType; + MultType mLpnMultType = DefaultCode; // The multi-point punctured PRF for generating the sparse vectors // Variant allows selecting between Regular and Stationary PPRF @@ -151,6 +155,7 @@ namespace osuCrypto // Seed for syndrome decoding block mCodeSeed = ZeroBlock; + std::unique_ptr mChosenBaaWorkspace; // Number of threads to use for parallel operations (default: 1) // this does not actually create multiple threads but determines how @@ -204,7 +209,7 @@ namespace osuCrypto void configure( u64 requestSize, SilentSecType malType = SilentSecType::SemiHonest, - MultType mult = DefaultMultType, + MultType mult = DefaultCode, SilentBaseType type = SilentBaseType::BaseExtend, SdNoiseDistribution noiseType = SdNoiseDistribution::Regular, u64 secParam = 128, @@ -618,6 +623,14 @@ namespace osuCrypto if (noiseType != SdNoiseDistribution::Regular && noiseType != SdNoiseDistribution::Stationary) throw std::invalid_argument("Unknown noise type. " LOCATION); + if (isChosenBaa(mult)) + { + if constexpr (!(std::is_same_v && std::is_same_v && + std::is_same_v)) + throw std::invalid_argument("Chosen BAA VOLE currently requires GF(2^128). " LOCATION); + } + if (mult == MultType::BinaryBAA) + throw std::invalid_argument("BinaryBAA is a binary code; use ChosenBAA30 for large-field VOLE."); if (mult == MultType::QuasiCyclic) throw std::invalid_argument( "QuasiCyclic is a binary code supported by Silent OT, not Silent VOLE. " LOCATION); @@ -657,8 +670,10 @@ namespace osuCrypto mNoiseVecSize = param.mNoiseVectorSize; mPprfFormat = format; mCodeSeed = block(12528943721987127, 98743297823479812); - mA = {}; - mC = {}; + // Invalidate old outputs while retaining capacity. Expansion overwrites + // all of A and explicitly zeros C before placing fresh noise. + mCtx.resize(mA, 0); + mCtx.resize(mC, 0); mBaseA = {}; mBaseC = {}; mMalCheckSeed.reset(); @@ -781,6 +796,9 @@ namespace osuCrypto if (mRequestSize < n) throw std::invalid_argument("n does not match the requested number of OTs via configure(...). " LOCATION); + if (isChosenBaa(mLpnMultType)) + co_await chosenBaaSeed(false, prng, chl, mCodeSeed); + // Generate base correlations if needed if (hasBaseCors() == false) co_await genBaseCors(prng, chl); @@ -920,6 +938,16 @@ namespace osuCrypto ); break; } + case MultType::ChosenBAA30: + case MultType::ChosenBaa16x8: + case MultType::ChosenBaa16x4: + { + if constexpr (std::is_same_v && std::is_same_v && + std::is_same_v) + chosenBaaCompress(mLpnMultType, mCodeSeed, mChosenBaaWorkspace, mA, mC); + else throw std::runtime_error("Chosen BAA requires GF(2^128). " LOCATION); + break; + } case MultType::BlkAcc3x8: case MultType::BlkAcc3x32: { @@ -1148,6 +1176,7 @@ namespace osuCrypto template< typename F, typename G, typename Ctx > void SilentVoleReceiver::clear() { + mChosenBaaWorkspace.reset(); mA = {}; mC = {}; mBaseA = {}; diff --git a/libOTe/Vole/Silent/SilentVoleSender.h b/libOTe/Vole/Silent/SilentVoleSender.h index ad6b4984..bb82bc78 100644 --- a/libOTe/Vole/Silent/SilentVoleSender.h +++ b/libOTe/Vole/Silent/SilentVoleSender.h @@ -1,4 +1,5 @@ #pragma once +#include "libOTe/Tools/BlkAccCode/ChosenBaaVole.h" // © 2022 Visa. // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // @@ -141,7 +142,8 @@ namespace osuCrypto SdNoiseDistribution mNoiseType = SdNoiseDistribution::Regular; // Seed for syndrome decoding - block mCodeSeed = ZeroBlock; + block mCodeSeed = ZeroBlock; + std::unique_ptr mChosenBaaWorkspace; // The base VOLE correlation vector (sender's share) // Used to initialize the non-zeros of the noisy vector @@ -154,7 +156,10 @@ namespace osuCrypto SilentSecType mSecurityType = SilentSecType::SemiHonest; // The matrix multiplication type which compresses the sparse vector - MultType mLpnMultType = DefaultMultType; + static constexpr MultType DefaultCode = + std::is_same_v && std::is_same_v && std::is_same_v + ? MultType::ChosenBAA30 : DefaultMultType; + MultType mLpnMultType = DefaultCode; // Format used for PPRF output organization PprfOutputFormat mPprfFormat = PprfOutputFormat::ByTreeIndex; @@ -227,12 +232,12 @@ namespace osuCrypto * coefficients; small-group contexts use a larger weight. * @param secParam Security parameter (typically 128) * @param ctx Context object for F, G operations (default constructed if not provided) - * @param mult the lpn compression matrix type to use (default DefaultMultType) + * @param mult the lpn compression matrix type to use (default DefaultCode) */ void configure( u64 requestSize, SilentSecType malType = SilentSecType::SemiHonest, - MultType mult = DefaultMultType, + MultType mult = DefaultCode, SilentBaseType type = SilentBaseType::BaseExtend, SdNoiseDistribution noiseType = SdNoiseDistribution::Regular, u64 secParam = 128, @@ -511,6 +516,14 @@ namespace osuCrypto if (noiseType != SdNoiseDistribution::Regular && noiseType != SdNoiseDistribution::Stationary) throw std::invalid_argument("SilentNoiseType not supported. " LOCATION); + if (isChosenBaa(mult)) + { + if constexpr (!(std::is_same_v && std::is_same_v && + std::is_same_v)) + throw std::invalid_argument("Chosen BAA VOLE currently requires GF(2^128). " LOCATION); + } + if (mult == MultType::BinaryBAA) + throw std::invalid_argument("BinaryBAA is a binary code; use ChosenBAA30 for large-field VOLE."); if (mult == MultType::QuasiCyclic) throw std::invalid_argument( "QuasiCyclic is a binary code supported by Silent OT, not Silent VOLE. " LOCATION); @@ -550,7 +563,8 @@ namespace osuCrypto mNoiseVecSize = config.mNoiseVectorSize; mPprfFormat = format; mCodeSeed = block(12528943721987127, 98743297823479812); - mB = {}; + // Expansion overwrites the output; keep its allocation across runs. + mCtx.resize(mB, 0); mBaseB = {}; mDerandomizeMalCheck = false; mState = State::Configured; @@ -646,6 +660,9 @@ namespace osuCrypto if (mRequestSize < n) throw std::invalid_argument("n does not match the requested number of OTs via configure(...). " LOCATION); + if (isChosenBaa(mLpnMultType)) + co_await chosenBaaSeed(true, prng, chl, mCodeSeed); + // Generate base correlations if needed if (hasBaseCors() == false) { @@ -756,6 +773,16 @@ namespace osuCrypto encoder.dualEncode(mB.begin(), mCtx); break; } + case MultType::ChosenBAA30: + case MultType::ChosenBaa16x8: + case MultType::ChosenBaa16x4: + { + if constexpr (std::is_same_v && std::is_same_v && + std::is_same_v) + chosenBaaCompress(mLpnMultType, mCodeSeed, mChosenBaaWorkspace, mB); + else throw std::runtime_error("Chosen BAA requires GF(2^128). " LOCATION); + break; + } case MultType::BlkAcc3x8: case MultType::BlkAcc3x32: { @@ -851,6 +878,7 @@ namespace osuCrypto template void SilentVoleSender::clear() { + mChosenBaaWorkspace.reset(); // Free active protocol state and reset the generator. mB = {}; mBaseB = {}; diff --git a/libOTe_Tests/BinarySolver_Tests.cpp b/libOTe_Tests/BinarySolver_Tests.cpp index 33fec996..c371527e 100644 --- a/libOTe_Tests/BinarySolver_Tests.cpp +++ b/libOTe_Tests/BinarySolver_Tests.cpp @@ -4,10 +4,24 @@ #if defined(ENABLE_SPARSE_DPF) #include "libOTe/Dpf/RevCuckoo/BinarySolver.h" +#include "libOTe/Tools/CompilerHints.h" namespace osuCrypto { + namespace + { + // Return the lazy task across a non-inlined call boundary. The matrix + // storage stays alive in the test, but these view descriptors do not. + // solveOne must own its descriptor copies until solve has completed. + OC_NOINLINE task<> deferredSolveOne(BinarySolver& solver, + MatrixView matrix, MatrixView rhs, + MatrixView solution, PRNG& prng, Socket& socket) + { + return solver.solveOne(matrix, rhs, solution, prng, socket); + } + } + void setBase(std::array& s) { @@ -438,10 +452,10 @@ namespace osuCrypto } auto sock = coproto::LocalAsyncSocket::makePair(); + auto solve0 = deferredSolveOne(s[0], Ms[0], ys[0], xs[0], prng, sock[0]); + auto solve1 = deferredSolveOne(s[1], Ms[1], ys[1], xs[1], prng, sock[1]); auto r = macoro::sync_wait(macoro::when_all_ready( - s[0].solveOne(Ms[0], ys[0], xs[0], prng, sock[0]), - s[1].solveOne(Ms[1], ys[1], xs[1], prng, sock[1]) - )); + std::move(solve0), std::move(solve1))); std::get<0>(r).result(); std::get<1>(r).result(); diff --git a/libOTe_Tests/CMakeLists.txt b/libOTe_Tests/CMakeLists.txt index fa375616..af1bfcea 100644 --- a/libOTe_Tests/CMakeLists.txt +++ b/libOTe_Tests/CMakeLists.txt @@ -31,6 +31,7 @@ set(SRCS UInt_Tests.cpp Permutation_Tests.cpp BlkAccCode_Tests.cpp + ChosenBaa_Tests.cpp AnyField_Tests.cpp ) @@ -42,6 +43,18 @@ target_compile_definitions(libOTe_Tests PRIVATE target_link_libraries(libOTe_Tests libOTe) + +option(LIBOTE_BAA_BENCHMARK "Build the standalone chosen BAA benchmark" OFF) +if(LIBOTE_BAA_BENCHMARK) + add_executable(chosen_baa_benchmark benchmarks/ChosenBaa.cpp) + target_include_directories(chosen_baa_benchmark PRIVATE ${CMAKE_CURRENT_LIST_DIR}/..) + target_compile_features(chosen_baa_benchmark PRIVATE cxx_std_20) + target_link_libraries(chosen_baa_benchmark PRIVATE cryptoTools) + add_executable(chosen_baa_directions benchmarks/ChosenBaaDirections.cpp) + target_include_directories(chosen_baa_directions PRIVATE ${CMAKE_CURRENT_LIST_DIR}/..) + target_compile_features(chosen_baa_directions PRIVATE cxx_std_20) + target_link_libraries(chosen_baa_directions PRIVATE cryptoTools) +endif() # make projects that include libOTe_Tests use this as an include folder diff --git a/libOTe_Tests/ChosenBaa_Tests.cpp b/libOTe_Tests/ChosenBaa_Tests.cpp new file mode 100644 index 00000000..8433c1ce --- /dev/null +++ b/libOTe_Tests/ChosenBaa_Tests.cpp @@ -0,0 +1,497 @@ +#include "libOTe/Tools/BlkAccCode/ChosenBaaVole.h" +#include "cryptoTools/Common/CLP.h" +#include "cryptoTools/Common/TestCollection.h" +#include "Common.h" +#include "libOTe/Tools/Field/Goldilocks.h" +#include "libOTe/Tools/BlkAccCode/ReedMullerBaaCode.h" +#include "libOTe/Tools/BlkAccCode/SmallAlphabetBaaCode.h" +#include +#include + +using namespace osuCrypto; + +namespace +{ + struct RepeatedPoints : ChosenBaaField + { + static Goldilocks point(u64) { return Goldilocks(1); } + }; + template + void checkPrimeField(u64 n) + { + using F = Goldilocks; + using Field = ChosenBaaField; + ChosenBaaCode code; + code.config(n, block(901, n)); + PRNG random(block(902, n)); + std::array polynomial; + for (auto& x : polynomial) x = F(random.get()); + std::array evaluated; + for (u64 i = 0; i < 16; ++i) + { + F value(0); + for (u64 j = K; j-- > 0;) value = value * Field::point(i) + polynomial[j]; + evaluated[i] = value; + } + for (u64 col = 0; col < 16 - K; ++col) + { + F value(0); + for (u64 row = 0; row < K; ++row) value += evaluated[row] * code.matrix(row, col); + if (value != evaluated[K + col]) throw RTE_LOC; + } + AlignedUnVector x(n), y(n), z(n), message(code.outputSize()), forward(n), next(n), weights(n); + for (auto* v : {&x, &y, &message}) for (auto& value : *v) value = F(random.get()); + const auto original = x, originalY = y; + const F alpha(random.get()); + for (u64 i = 0; i < n; ++i) z[i] = x[i] + alpha * y[i]; + code.dualEncode2(x,y); + code.dualEncode(z); + auto separate = originalY; + code.dualEncode(separate); + for (u64 i = 0; i < code.outputSize(); ++i) + if (z[i] != x[i] + alpha * y[i] || y[i] != separate[i]) throw RTE_LOC; + for (u64 i = 0; i < n / 16; ++i) + { + for (u64 j = 0; j < K; ++j) forward[16*i+j] = message[K*i+j]; + for (u64 col = 0; col < 16-K; ++col) + { + F value(0); + for (u64 row = 0; row < K; ++row) value += message[K*i+row] * code.matrix(row,col); + forward[16*i+K+col] = value; + } + } + for (u64 stage = 0; stage < 2; ++stage) + { + PRNG prng(code.weightSeed(stage)); + // Independent scalar sampler: uniform field elements, rejecting zero. + for (auto& w : weights) do { w = F(prng.get()); } while (w == F(0)); + F sum(0); + for (u64 i = n; i-- > 0;) + next[i] = sum += forward[code.permutationIndex(stage,i)] * weights[i]; + std::swap(next,forward); + } + F lhs(0),rhs(0); + AlignedUnVector optimized(n), workspace(n); + code.encode(message, optimized, workspace); + if (!std::equal(optimized.begin(), optimized.end(), forward.begin())) throw RTE_LOC; + optimized = original; + code.dualEncode(optimized, workspace); + for (u64 i = 0; i < code.outputSize(); ++i) if (optimized[i] != x[i]) throw RTE_LOC; + for (u64 i = 0; i < message.size(); ++i) lhs += message[i] * x[i]; + for (u64 i = 0; i < n; ++i) rhs += original[i] * forward[i]; + if (lhs != rhs) throw RTE_LOC; + } + template + void checkCode(u64 n) + { + PRNG prng(block(42, n)); + ChosenBaaCode code; + code.config(n, prng.get()); + std::array polynomial; + std::array evaluations; + prng.get(polynomial.data(), polynomial.size()); + for (u64 point = 0; point < 16; ++point) + { + block value = ZeroBlock; + for (u64 degree = K; degree-- > 0;) + value = value.gf128Mul(block(0, point + 1)) ^ polynomial[degree]; + evaluations[point] = value; + } + for (u64 col = 0; col < 16 - K; ++col) + { + block value = ZeroBlock; + for (u64 row = 0; row < K; ++row) + value ^= evaluations[row].gf128Mul(code.matrix(row, col)); + if (value != evaluations[K + col]) throw RTE_LOC; + } + for (u64 stage = 0; stage < 2; ++stage) + { + std::vector seen(n); + for (u64 i = 0; i < n; ++i) + { + auto j = code.permutationIndex(stage, i); + if (j >= n || seen[j]) throw RTE_LOC; + seen[j] = true; + } + } + + AlignedUnVector x(n), y(n), scaled(n), message(code.outputSize()); + prng.get(x.data(), n); + prng.get(y.data(), n); + prng.get(message.data(), message.size()); + const auto originalX = x, originalY = y; + const auto alpha = prng.get(); + for (u64 i = 0; i < n; ++i) + scaled[i] = x[i] ^ y[i].gf128Mul(alpha); + code.dualEncode2(x, y); + code.dualEncode(scaled); + for (u64 i = 0; i < message.size(); ++i) + if (scaled[i] != (x[i] ^ y[i].gf128Mul(alpha))) throw RTE_LOC; + + // Independent forward traversal: local RS expansion followed by + // gather/weight/suffix-sum, in the opposite order to the transpose. + AlignedUnVector forward(n), next(n), weights(n); + for (u64 i = 0; i < n / 16; ++i) + { + for (u64 row = 0; row < K; ++row) + forward[16 * i + row] = message[K * i + row]; + for (u64 col = 0; col < 16 - K; ++col) + { + block sum = ZeroBlock; + for (u64 row = 0; row < K; ++row) + sum ^= message[K * i + row].gf128Mul(code.matrix(row, col)); + forward[16 * i + K + col] = sum; + } + } + for (u64 stage = 0; stage < 2; ++stage) + { + PRNG random(code.weightSeed(stage)); + random.get(weights.data(), weights.size()); + if (std::find(weights.begin(), weights.end(), ZeroBlock) != weights.end()) + throw RTE_LOC; // Fixed test seeds have no rejection draws. + block sum = ZeroBlock; + for (u64 j = n; j-- > 0;) + { + sum ^= forward[code.permutationIndex(stage, j)].gf128Mul(weights[j]); + next[j] = sum; + } + std::swap(forward, next); + } + block lhs = ZeroBlock, rhs = ZeroBlock; + AlignedUnVector optimized(n), workspace(n); + code.encode(message, optimized, workspace); + if (!std::equal(optimized.begin(), optimized.end(), forward.begin())) throw RTE_LOC; + optimized = originalX; + code.dualEncode(optimized, workspace); + for (u64 i = 0; i < code.outputSize(); ++i) if (optimized[i] != x[i]) throw RTE_LOC; + for (u64 i = 0; i < message.size(); ++i) + lhs ^= message[i].gf128Mul(x[i]); + for (u64 i = 0; i < n; ++i) + rhs ^= forward[i].gf128Mul(originalX[i]); + if (lhs != rhs) throw RTE_LOC; + + auto separate = originalY; + code.dualEncode(separate); + for (u64 i = 0; i < message.size(); ++i) + if (separate[i] != y[i]) throw RTE_LOC; + } + + void checkSmallSetup(u64 n) + { + const block seed(216, n); + ChosenBAA30<> code; + code.config(n, seed); + PRNG master(seed); + const std::array permutations{master.get(), master.get()}; + const std::array coefficients{master.get(), master.get()}; + // The original scalar setup defines the seed-to-code mapping. Cover + // prefetch-batch tails and a large shuffle that exercises rejection. + for (unsigned stage = 0; stage < 2; ++stage) + { + PRNG random(permutations[stage]), coefficient(coefficients[stage]); + std::vector expected(n); + for (u64 i = 0; i < n; ++i) expected[i] = u32(i); + for (u32 i = u32(n); i > 1; --i) + { + u64 product = u64(random.get()) * i; + if (u32(product) < i) + { + const u32 threshold = (u32(0) - i) % i; + while (u32(product) < threshold) product = u64(random.get()) * i; + } + std::swap(expected[i - 1], expected[product >> 32]); + } + for (u64 i = 0; i < n; ++i) + if (code.metadata(stage, i) != (expected[i] | (u32(coefficient.get()) << 24))) + throw RTE_LOC; + } + } + + template + void checkSmall(u64 n) + { + using Field = ChosenBaaField; + ChosenBAA30 code; + code.config(n, block(210, n)); + PRNG random(block(211, n)); + AlignedUnVector message(n / 2), input(n), forward(n), scalar(n), next(n), scratch(n); + for (auto* v : {&message, &input}) for (auto& x : *v) x = F(random.get()); + for (u64 b = 0; b < n / 16; ++b) + { + for (u64 j = 0; j < 8; ++j) scalar[b * 16 + j] = message[b * 8 + j]; + for (u64 col = 0; col < 8; ++col) + { + F sum = Field::zero(); + for (u64 row = 0; row < 8; ++row) + sum = Field::add(sum, Field::mul(message[b * 8 + row], code.matrix(row, col))); + scalar[b * 16 + 8 + col] = sum; + } + } + for (unsigned stage = 0; stage < 2; ++stage) + { + F sum = Field::zero(); std::vector seen(n); + for (u64 i = 0; i < n; ++i) + { + const auto meta = code.metadata(stage, i), p = meta & ((1u << 24) - 1); + if (p >= n || seen[p]) throw RTE_LOC; + seen[p] = true; + next[i] = sum = Field::add(scalar[p], Field::mul(sum, Field::point(meta >> 24))); + } + std::swap(scalar, next); + } + code.encode(message, forward, scratch); + if (!std::equal(scalar.begin(), scalar.end(), forward.begin())) throw RTE_LOC; + F lhs = Field::zero(), rhs = Field::zero(); + for (u64 i = 0; i < n; ++i) lhs = Field::add(lhs, Field::mul(input[i], forward[i])); + code.dualEncode(input, scratch); + for (u64 i = 0; i < n / 2; ++i) rhs = Field::add(rhs, Field::mul(message[i], input[i])); + if (lhs != rhs) throw RTE_LOC; + } + void checkRm(u64 n) + { + BinaryBAA<> code; + code.config(n, block(109, n)); + PRNG random(block(110, n)); + AlignedUnVector message(n / 2), input(n), forward(n), scalar(n), next(n), scratch(n); + random.get(message.data(), message.size()); random.get(input.data(), n); + // Independent evaluation of all degree <= 2 Boolean monomials. + for (u64 b = 0; b < n / 32; ++b) + for (unsigned point = 0; point < 32; ++point) + { + auto value = ZeroBlock; + unsigned row = 0; + for (unsigned mask = 0; mask < 32; ++mask) + if (std::popcount(mask) <= 2) + { + if ((point & mask) == mask) value ^= message[b * 16 + row]; + ++row; + } + scalar[b * 32 + point] = value; + } + for (unsigned stage = 0; stage < 2; ++stage) + { + block sum = ZeroBlock; + std::vector seen(n); + for (u64 i = 0; i < n; ++i) + { + const auto p = code.permutationIndex(stage, i); + if (p >= n || seen[p]) throw RTE_LOC; + seen[p] = true; + next[i] = sum ^= scalar[p]; + } + std::swap(scalar, next); + } + code.encode(message, forward, scratch); + if (!std::equal(scalar.begin(), scalar.end(), forward.begin())) throw RTE_LOC; + block lhs = ZeroBlock, rhs = ZeroBlock; + for (u64 i = 0; i < n; ++i) lhs ^= input[i].gf128Mul(forward[i]); + code.dualEncode(input, scratch); + for (u64 i = 0; i < n / 2; ++i) rhs ^= message[i].gf128Mul(input[i]); + if (lhs != rhs) throw RTE_LOC; + } + template + void checkProfileAdapter(MultType type, u64 n) + { + const block seed(214, n); + Code code; code.config(n, seed); + PRNG random(block(215, n)); + AlignedUnVector a(n), b(n), scratch(n); + random.get(a.data(), n); random.get(b.data(), n); + auto expectedA = a, expectedB = b; + code.dualEncode(expectedA, scratch); code.dualEncode(expectedB, scratch); + if (type == MultType::BinaryBAA) + { + AlignedUnVector choices(n); + for (u64 i = 0; i < n; ++i) choices[i] = b[i].get(0) & 1; + binaryBaaCompress(seed, a, choices); + binaryBaaCompress(seed, b); + for (u64 i = 0; i < n / 2; ++i) + if (choices[i] != (expectedB[i].get(0) & 1)) throw RTE_LOC; + } + else + chosenBaaCompress(type, seed, a, b); + for (u64 i = 0; i < n / 2; ++i) + if (a[i] != expectedA[i] || b[i] != expectedB[i]) throw RTE_LOC; + } + task<> badOpening(Socket& socket) + { + std::array invalidCommitment{}; + std::array contribution{}; + co_await socket.send(invalidCommitment); + co_await socket.recv(contribution); + co_await socket.send(contribution); + } +} + +void ChosenBaa_Code_test(const CLP&) +{ + for (u64 n : {16, 48, 64, 80, 128, 144, 1048592}) checkSmallSetup(n); + { + std::unique_ptr workspace; + PRNG prng(block(46, 91)); + for (u64 n : {256, 64, 512, 256}) + { + AlignedUnVector a(n), c(n); + prng.get(a.data(), n); + prng.get(c.data(), n); + auto expectedA = a, expectedC = c; + auto seed = prng.get(); + auto oldCapacity = workspace ? workspace->scratch.capacity() : 0; + auto oldData = workspace ? workspace->scratch.data() : nullptr; + chosenBaaCompress(MultType::ChosenBAA30, seed, expectedA, expectedC); + chosenBaaCompress(MultType::ChosenBAA30, seed, workspace, a, c); + if (!std::equal(a.begin(), a.end(), expectedA.begin()) || + !std::equal(c.begin(), c.end(), expectedC.begin())) throw RTE_LOC; + if (oldCapacity >= n && workspace->scratch.data() != oldData) throw RTE_LOC; + } + } + for (u64 n : {32, 96, 1056, 4096}) + { + checkProfileAdapter>(MultType::BinaryBAA, n); + checkProfileAdapter>(MultType::ChosenBAA30, n); + } + for (auto type : {MultType::BinaryBAA, MultType::ChosenBAA30}) + { + for (auto noise : {SdNoiseDistribution::Regular, SdNoiseDistribution::Stationary}) + for (u64 n : {1, 129, 1024, 1048576}) + { + const auto model = type == MultType::BinaryBAA + ? SdNoiseSecurityModel::binary() : SdNoiseSecurityModel{1.0}; + const auto c = syndromeDecodingConfigure(128, n, type, noise, model); + const u64 weight = type == MultType::BinaryBAA + ? (noise == SdNoiseDistribution::Regular ? 200 : 424) : 128; + const u64 alignment = type == MultType::BinaryBAA ? 32 : 16; + if (c.mNumPartitions != weight || c.mNoiseVectorSize % alignment || + c.mNoiseVectorSize / 2 < n || c.mNoiseVectorSize < c.mNumPartitions * c.mSizePer) + throw RTE_LOC; + } + } + bool tooLarge = false; + try { syndromeDecodingConfigure(128, (u64{1} << 23) + 1, MultType::ChosenBAA30, + SdNoiseDistribution::Regular, {1.0}); } + catch (const std::invalid_argument&) { tooLarge = true; } + if (!tooLarge) throw RTE_LOC; + for (u64 bit = 0; bit < 128; ++bit) + for (u32 c = 1; c <= 256; ++c) + { + const block x = bit < 64 ? block(0, u64{1} << bit) : block(u64{1} << (bit - 64), 0); + if (SmallBaaArithmetic::madd(x, c, ZeroBlock) != x.gf128Mul(block(0, c))) throw RTE_LOC; + } + for (u64 n : {16, 32, 48, 256, 1040, 262144}) + { + checkSmall(n); + if (n < 262144) checkSmall(n); + } + for (u64 n : {32, 64, 96, 256, 1056, 262144}) checkRm(n); + // Exhaust the binary constituent: this verifies the exact RM weight + // enumerator used by the finite distance calculation, not just distance 8. + std::array spectrum{}; + std::array rmInput; + std::array rmOutput; + for (u64 word = 0; word < (1u << 16); ++word) + { + for (unsigned j = 0; j < 16; ++j) rmInput[j] = block(0, (word >> j) & 1); + ReedMullerBaaCode<>::localEncode(rmInput.data(), rmOutput.data()); + u64 weight = 0; for (auto x : rmOutput) weight += (x != ZeroBlock); + ++spectrum[weight]; + } + std::array expected{}; + expected[0] = expected[32] = 1; expected[8] = expected[24] = 620; + expected[12] = expected[20] = 13888; expected[16] = 36518; + if (spectrum != expected) throw RTE_LOC; + bool repeatedRejected = false; + try { ChosenBaaCode<8, Goldilocks, RepeatedPoints> code; code.config(16, ZeroBlock); } + catch (const std::invalid_argument&) { repeatedRejected = true; } + if (!repeatedRejected) throw RTE_LOC; + for (auto type : {MultType::ChosenBaa16x8, MultType::ChosenBaa16x4}) + { + const u64 rate = type == MultType::ChosenBaa16x8 ? 2 : 4; + for (auto noise : {SdNoiseDistribution::Regular, SdNoiseDistribution::Stationary}) + for (u64 n : {1, 7, 8, 9, 511, 512, 1023, 1024, 1048576}) + { + auto config = syndromeDecodingConfigure(128, n, type, + noise, {1.0}); + if (config.mNoiseVectorSize % 16 || + config.mNoiseVectorSize / rate < n || + config.mNoiseVectorSize < config.mNumPartitions * config.mSizePer || + config.mNumPartitions != (rate == 2 ? 128 : 64)) + throw RTE_LOC; + } + // A lower attack floor exposes the distinct distance terms. Check + // both noise distributions; stationary coefficients include zero. + for (auto noise : {SdNoiseDistribution::Regular, SdNoiseDistribution::Stationary}) + { + const auto config = syndromeDecodingConfigure(40, 4096, type, noise, {1.0}); + const u64 expected = type == MultType::ChosenBaa16x8 ? 128 : 56; + if (config.mNumPartitions != expected) throw RTE_LOC; + // Odd targets round the quarter-rate floor up before batching. + for (u64 security : {129, 256}) + { + const auto scaled = syndromeDecodingConfigure(security, 4096, type, noise, {1.0}); + const u64 floor = rate == 2 ? security : security / 2 + security % 2; + if (scaled.mNumPartitions != roundUpTo(floor, u64{8})) throw RTE_LOC; + } + } + bool rejected = false; + try { syndromeDecodingConfigure(128, u64(1) << 31, type, + SdNoiseDistribution::Regular, {1.0}); } + catch (const std::invalid_argument&) { rejected = true; } + if (!rejected) throw RTE_LOC; + } + if (getRegNoiseWeight(0.60, 4096, 40, SdNoiseDistribution::Stationary, + SdNoiseSecurityModel::binary()) != 56) + throw RTE_LOC; + for (double distance : {0.60, std::numeric_limits::quiet_NaN(), 1e-300}) + { + bool rejected = false; + try { getRegNoiseWeight(distance, 4096, 128, SdNoiseDistribution::Regular, + SdNoiseSecurityModel::binary()); } + catch (const std::invalid_argument&) { rejected = true; } + if (!rejected) throw RTE_LOC; + } + for (u64 n : {16, 32, 48, 256, 1040}) + { + checkCode<4>(n); + checkCode<8>(n); + checkPrimeField<4>(n); + checkPrimeField<8>(n); + } +#ifdef OC_ENABLE_SSE2 + // Cover both sides of the prefetch dispatch threshold and a non-power-of-two + // length. The forward/transpose check also exercises the bounded hint tail. + for (u64 n : {(u64{1} << 18) - 16, u64{1} << 18, (u64{1} << 18) + 16}) + { + checkCode<4>(n); + checkCode<8>(n); + } +#endif + for (u64 n : {u64(0), u64(17), u64(1) << 32}) + { + bool rejected = false; + try { ChosenBaaCode<8> code; code.config(n, ZeroBlock); } + catch (const std::invalid_argument&) { rejected = true; } + if (!rejected) throw RTE_LOC; + } +} + +void ChosenBaa_Seed_test(const CLP&) +{ + PRNG sender(block(1, 2)), receiver(block(3, 4)); + block a = ZeroBlock, b = OneBlock, previous = ZeroBlock; + for (u64 trial = 0; trial < 3; ++trial) + { + auto sockets = cp::LocalAsyncSocket::makePair(); + auto send = chosenBaaSeed(true, sender, sockets[0], a); + auto recv = chosenBaaSeed(false, receiver, sockets[1], b); + tests_libOTe::eval(send, recv); + if (a != b || a == previous) throw RTE_LOC; + previous = a; + } + auto sockets = cp::LocalAsyncSocket::makePair(); + auto send = badOpening(sockets[0]); + auto recv = chosenBaaSeed(false, receiver, sockets[1], b); + bool rejected = false; + try { tests_libOTe::eval(send, recv); } + catch (const std::runtime_error&) { rejected = true; } + if (!rejected) throw RTE_LOC; +} diff --git a/libOTe_Tests/SilentOT_Tests.cpp b/libOTe_Tests/SilentOT_Tests.cpp index d70cc245..8452aa60 100644 --- a/libOTe_Tests/SilentOT_Tests.cpp +++ b/libOTe_Tests/SilentOT_Tests.cpp @@ -1,4 +1,5 @@ #include "SilentOT_Tests.h" +#include "libOTe/TwoChooseOne/ConfigureCode.h" #include "libOTe/TwoChooseOne/Silent/SilentOtExtSender.h" #include "libOTe/TwoChooseOne/Silent/SilentOtExtReceiver.h" @@ -695,6 +696,12 @@ namespace { // Set receiver's base OTs and VOLEs { BitVector choices = recver.sampleBaseChoiceBits(prng); + if (recver.mSecurityType == SilentSecType::Malicious) + { + BitVector checkChoices(128); + checkChoices.randomize(prng); + choices.append(checkChoices); + } std::vector msg(choices.size()); for (u64 i = 0; i < msg.size(); ++i) msg[i] = msg2[i][choices[i]]; @@ -1175,7 +1182,7 @@ void OtExt_Silent_QuasiCyclic_Test(const oc::CLP& cmd) #endif } -void OtExt_Silent_Tungsten_Test(const oc::CLP& cmd) +static void silentBinaryCodeTest(const oc::CLP& cmd, MultType mult) { #if defined(ENABLE_SILENTOT) auto sockets = cp::LocalAsyncSocket::makePair(); @@ -1193,16 +1200,18 @@ void OtExt_Silent_Tungsten_Test(const oc::CLP& cmd) SilentOtExtSender sender; SilentOtExtReceiver recver; + for (auto noise : {SdNoiseDistribution::Regular, SdNoiseDistribution::Stationary}) + for (auto security : {SilentSecType::SemiHonest, SilentSecType::Malicious}) for (auto n : nn) { - // Test 1: Random OT with Tungsten encoding + // Test 1: Random OT with the selected binary code { std::vector> msg2(n); std::vector msg1(n); BitVector choice(n); - sender.configure(n, 2, 1, SilentSecType::SemiHonest, SdNoiseDistribution::Regular, MultType::Tungsten); - recver.configure(n, 2, 1, SilentSecType::SemiHonest, SdNoiseDistribution::Regular, MultType::Tungsten); + sender.configure(n, 2, 1, security, noise, mult); + recver.configure(n, 2, 1, security, noise, mult); fakeBase(n, s, threads, prng, recver, sender); @@ -1214,10 +1223,10 @@ void OtExt_Silent_Tungsten_Test(const oc::CLP& cmd) checkRandom(msg1, msg2, choice, n, verbose); } - // Test 2: Correlated OT with Tungsten encoding + // Test 2: Correlated OT with the selected binary code { - sender.configure(n); - recver.configure(n); + sender.configure(n, 2, 1, security, noise, mult); + recver.configure(n, 2, 1, security, noise, mult); auto type = ChoiceBitPacking::False; fakeBase(n, s, threads, prng, recver, sender); @@ -1232,10 +1241,20 @@ void OtExt_Silent_Tungsten_Test(const oc::CLP& cmd) } } #else - throw UnitTestSkipped("ENABLE_SILENTOT or ENABLE_INSECURE_SILVER are not defined."); + throw UnitTestSkipped("ENABLE_SILENTOT is not defined."); #endif } +void OtExt_Silent_Tungsten_Test(const oc::CLP& cmd) +{ + silentBinaryCodeTest(cmd, MultType::Tungsten); +} + +void OtExt_Silent_BinaryBAA_Test(const oc::CLP& cmd) +{ + silentBinaryCodeTest(cmd, MultType::BinaryBAA); +} + // Silent OT with the SPIN code (MultType::Spin). The default sizes select // both SPIN parameter sets silent OT uses (T64S12R2 up to 2^16 OTs, T128S19 // above). The SPIN encoder itself is tested by the SPIN library. diff --git a/libOTe_Tests/SilentOT_Tests.h b/libOTe_Tests/SilentOT_Tests.h index cbb0634b..17ff8fb6 100644 --- a/libOTe_Tests/SilentOT_Tests.h +++ b/libOTe_Tests/SilentOT_Tests.h @@ -16,6 +16,7 @@ void OtExt_Silent_inplace_Test(const oc::CLP& cmd); void OtExt_Silent_paramSweep_Test(const oc::CLP& cmd); void OtExt_Silent_QuasiCyclic_Test(const oc::CLP& cmd); void OtExt_Silent_Tungsten_Test(const oc::CLP& cmd); +void OtExt_Silent_BinaryBAA_Test(const oc::CLP& cmd); void OtExt_Silent_Spin_Test(const oc::CLP& cmd); void OtExt_Silent_baseOT_Test(const oc::CLP& cmd); void OtExt_Silent_stationary_Test(const oc::CLP& cmd); diff --git a/libOTe_Tests/UnitTests.cpp b/libOTe_Tests/UnitTests.cpp index 6c427fbe..49b3d267 100644 --- a/libOTe_Tests/UnitTests.cpp +++ b/libOTe_Tests/UnitTests.cpp @@ -38,11 +38,18 @@ #include "libOTe_Tests/AnyField_Tests.h" +void ChosenBaa_Code_test(const osuCrypto::CLP&); +void ChosenBaa_Seed_test(const osuCrypto::CLP&); +void Vole_Silent_ChosenBaa_test(const osuCrypto::CLP&); + using namespace osuCrypto; namespace tests_libOTe { TestCollection Tests([](TestCollection& tc) { + tc.add("ChosenBaa_Code_test", ChosenBaa_Code_test); + tc.add("ChosenBaa_Seed_test", ChosenBaa_Seed_test); + tc.add("Vole_Silent_ChosenBaa_test", Vole_Silent_ChosenBaa_test); tc.add("AnyField_F9_Test ", AnyField_F9_Test); tc.add("AnyField_F9Transform_Test ", AnyField_F9Transform_Test); tc.add("AnyField_F4_Test ", AnyField_F4_Test); @@ -247,6 +254,7 @@ namespace tests_libOTe tc.add("OtExt_Silent_paramSweep_Test ", OtExt_Silent_paramSweep_Test); tc.add("OtExt_Silent_QuasiCyclic_Test ", OtExt_Silent_QuasiCyclic_Test); tc.add("OtExt_Silent_Tungsten_Test ", OtExt_Silent_Tungsten_Test); + tc.add("OtExt_Silent_BinaryBAA_Test ", OtExt_Silent_BinaryBAA_Test); tc.add("OtExt_Silent_Spin_Test ", OtExt_Silent_Spin_Test); tc.add("OtExt_Silent_stationary_Test ", OtExt_Silent_stationary_Test); tc.add("OtExt_Silent_baseOT_Test ", OtExt_Silent_baseOT_Test); diff --git a/libOTe_Tests/Vole_Tests.cpp b/libOTe_Tests/Vole_Tests.cpp index ae40126f..b74715a0 100644 --- a/libOTe_Tests/Vole_Tests.cpp +++ b/libOTe_Tests/Vole_Tests.cpp @@ -598,6 +598,34 @@ void Vole_Silent_baseOT_test(const oc::CLP& cmd) +void Vole_Silent_ChosenBaa_test(const oc::CLP&) +{ + for (auto type : {MultType::ChosenBAA30, MultType::ChosenBaa16x8, MultType::ChosenBaa16x4}) + for (auto noise : {SdNoiseDistribution::Regular, SdNoiseDistribution::Stationary}) + for (bool malicious : {false, true}) + for (u64 n : {u64(1), u64(129), u64(2049)}) + Vole_Silent_test_impl( + n, type, false, true, malicious, noise, n >= 512); + Vole_Silent_test_impl( + 1024, MultType::ChosenBAA30, false, false, true, SdNoiseDistribution::Regular, true); + for (bool senderSide : {false, true}) { + bool rejectedBinary = false; + try { + if (senderSide) { SilentVoleSender v; v.configure(1024, SilentSecType::SemiHonest, MultType::BinaryBAA); } + else { SilentVoleReceiver v; v.configure(1024, SilentSecType::SemiHonest, MultType::BinaryBAA); } + } catch (const std::invalid_argument&) { rejectedBinary = true; } + if (!rejectedBinary) throw RTE_LOC; + } + bool rejected = false; + try + { + SilentVoleSender sender; + sender.configure(1024, SilentSecType::SemiHonest, MultType::ChosenBaa16x8); + } + catch (const std::invalid_argument&) { rejected = true; } + if (!rejected) throw RTE_LOC; +} + void Vole_Silent_mal_test(const oc::CLP& cmd) { auto debug = cmd.isSet("debug"); @@ -1093,6 +1121,7 @@ void Vole_Silent_QuasiCyclic_test(const oc::CLP& cmd) { throwDisabled(); } void Vole_Silent_paramSweep_test(const oc::CLP& cmd) { throwDisabled(); } void Vole_Silent_defaultMatrixRank_test(const oc::CLP& cmd) { throwDisabled(); } void Vole_Silent_baseOT_test(const oc::CLP& cmd) { throwDisabled(); } +void Vole_Silent_ChosenBaa_test(const oc::CLP&) { throwDisabled(); } void Vole_Silent_mal_test(const oc::CLP& cmd) { throwDisabled(); } void Vole_Silent_malBase_test(const oc::CLP& cmd) { throwDisabled(); } void Vole_Silent_Clear_test(const oc::CLP& cmd) { throwDisabled(); } diff --git a/libOTe_Tests/benchmarks/ChosenBaa.cpp b/libOTe_Tests/benchmarks/ChosenBaa.cpp new file mode 100644 index 00000000..528268a3 --- /dev/null +++ b/libOTe_Tests/benchmarks/ChosenBaa.cpp @@ -0,0 +1,45 @@ +#include "libOTe/Tools/BlkAccCode/ChosenBaaCode.h" +#include +#include +#include +using namespace osuCrypto; +template void bench(u64 n) { + PRNG p(block(12,34)); + AlignedUnVector original(n), a(n), b(n); + p.get(original.data(), n); + std::vector setup, single, pair; + block check=ZeroBlock; + for(int i=0;i<6;++i) { + ChosenBaaCode code; + auto t0=std::chrono::steady_clock::now(); code.config(n, block(56,78)); + auto t1=std::chrono::steady_clock::now(); + a=original; b=original; + auto t2=std::chrono::steady_clock::now(); code.dualEncode(a); + auto t3=std::chrono::steady_clock::now(); + auto expected=a; + a=original; + auto t4=std::chrono::steady_clock::now(); code.dualEncode2(a,b); + auto t5=std::chrono::steady_clock::now(); + check=ZeroBlock; + for(u64 j=0;j(t1-t0).count()); + single.push_back(std::chrono::duration(t3-t2).count()); + pair.push_back(std::chrono::duration(t5-t4).count()); + } + } + for(auto* x:{&setup,&single,&pair})std::sort(x->begin(),x->end()); + std::cout< 1 ? std::stoull(argv[1]) : 65536; + if (!n || n % 16 || n > std::numeric_limits::max()) + throw std::invalid_argument("Length must be a positive multiple of 16 fitting u32."); + std::cout << "K,n,config_ms,single_ms,pair_ms,checksum\n"; + bench<8>(n); + bench<4>(n); +} diff --git a/libOTe_Tests/benchmarks/ChosenBaaDirections.cpp b/libOTe_Tests/benchmarks/ChosenBaaDirections.cpp new file mode 100644 index 00000000..2b506a00 --- /dev/null +++ b/libOTe_Tests/benchmarks/ChosenBaaDirections.cpp @@ -0,0 +1,58 @@ +#include "libOTe/Tools/BlkAccCode/ChosenBaaCode.h" +#include "libOTe/Tools/BlkAccCode/BinaryBAA.h" +#include "libOTe/Tools/BlkAccCode/ChosenBAA30.h" +#include +#include +#include +using namespace osuCrypto; + +template +void run(const char* name, u64 n, u64 seed, unsigned iterations) +{ + Code code; + auto t0 = std::chrono::steady_clock::now(); + code.config(n, block(125, seed)); + const double setup = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + AlignedUnVector message(n / 2), original(n), output(n), scratch(n), transpose(n), expected(n); + PRNG random(block(126, seed)); + random.get(message.data(), message.size()); random.get(original.data(), n); + std::vector forwardTimes, transposeTimes; + code.encode(message, expected, scratch); + block check = ZeroBlock; + for (unsigned iteration = 0; iteration < iterations + 2; ++iteration) + { + const auto start = std::chrono::steady_clock::now(); + code.encode(message, output, scratch); + const auto elapsed = std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + if (iteration >= 2) forwardTimes.push_back(elapsed); + check ^= output[iteration % n]; + } + if (!std::equal(output.begin(), output.end(), expected.begin())) throw std::runtime_error("forward changed"); + for (unsigned iteration = 0; iteration < iterations + 2; ++iteration) + { + std::copy(original.begin(), original.end(), transpose.begin()); + const auto start = std::chrono::steady_clock::now(); + code.dualEncode(transpose, scratch); + const auto elapsed = std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + if (iteration >= 2) transposeTimes.push_back(elapsed); + check ^= transpose[iteration % (n / 2)]; + } + block lhs = ZeroBlock, rhs = ZeroBlock; + for (u64 i = 0; i < n; ++i) lhs ^= original[i].gf128Mul(output[i]); + for (u64 i = 0; i < n / 2; ++i) rhs ^= message[i].gf128Mul(transpose[i]); + if (lhs != rhs) throw std::runtime_error("transpose identity failed"); + std::sort(forwardTimes.begin(), forwardTimes.end()); std::sort(transposeTimes.begin(), transposeTimes.end()); + std::cout << name << ',' << n / 2 << ',' << n << ',' << seed << ',' << setup << ',' + << forwardTimes[iterations / 2] << ',' << transposeTimes[iterations / 2] << ',' << check << std::endl; +} +int main(int argc, char** argv) +{ + const u64 n = argc > 1 ? std::stoull(argv[1]) : (1u << 21); + const unsigned iterations = argc > 2 ? std::stoul(argv[2]) : 15; + const u64 seed = argc > 3 ? std::stoull(argv[3]) : 1; + if (!iterations || !n || n % 32 || n > std::numeric_limits::max()) throw std::invalid_argument("benchmark arguments"); + std::cout << "code,k,n,seed,setup_ms,forward_ms,transpose_ms,checksum\n"; + run>("binary_baa_packed128", n, seed, iterations); + run>("gf128_chosen_baa30", n, seed, iterations); + run>("gf128_rs", n, seed, iterations); +} diff --git a/libOTe_Tests/benchmarks/ChosenBaaDirections.md b/libOTe_Tests/benchmarks/ChosenBaaDirections.md new file mode 100644 index 00000000..f6963789 --- /dev/null +++ b/libOTe_Tests/benchmarks/ChosenBaaDirections.md @@ -0,0 +1,223 @@ +# BAA code distance and encoding time + +These experiments compare rate-one-half linear codes at message dimension +`k = 1,048,576` and code length `n = 2,097,152`. Forward encoding maps `k -> n`; +transpose encoding applies the same matrix transposed, `n -> k`. Distance +refers to the forward code. All performance measurements are single-threaded +and run sequentially, including across hosts. + +The public profiles are `BinaryBAA` for independent binary lanes and +`ChosenBAA30` for large fields. BinaryBAA is available in binary Silent OT +and rejected by Silent VOLE. ChosenBAA30 is the GF128 Silent VOLE default. +The historical measurements below retain their original construction labels. + +Two implementations underlie these profiles. BinaryBAA packs independent +binary lanes into 128-bit words; ChosenBAA30 operates on GF(2^128) symbols. `ReedMullerBaaCode<>` uses +RM(2,5)[32,16,8], two Fisher--Yates permutations, and two plain accumulators. +It needs only XORs during encoding. `SmallAlphabetBaaCode<>` uses RS[16,8,9], two +Fisher--Yates permutations, and two recursive scans with independently sampled +coefficients. Each scan computes `y[i] = x[perm[i]] + a[i] * y[i-1]`, starting +from zero. The alphabet consists of polynomial-basis elements with integer +encodings 1 through 256; these are 256 distinct nonzero field elements, not +integer scalar multiples of one. Metadata packs a 24-bit index and an eight-bit +coefficient selector into one word. Supported lengths are positive multiples +of 16 up to 2^24; RM lengths must instead be multiples of 32 below 2^32. + +Both profiles accept caller-owned, disjoint input/output/scratch buffers and +perform no allocation while encoding. The transpose overwrites the input +prefix. `SmallAlphabetBaaCode` also supports other fields through a +compile-time policy; Goldilocks is exercised against scalar references. +`ReedMullerBaaCode` requires characteristic two. The pre-existing +full-field `ChosenBaaCode` now also provides forward encoding and a transpose +overload accepting scratch. Its seed schedule and transpose map are unchanged. + +The Fp controls use `p = 2^128 - 159` and the existing optimized Newton +[16,8,9] reference from gen-BAA. The low-distance control has all coefficients +one; the high-distance control samples 1 through 256. `FpBaaDirections.cpp` +reuses that forward implementation and adds its transpose, including the +reversed 77-addition Newton circuit with eight-block AVX-512 batching. This +standalone comparison requires the reference sources and an AVX-512/BMI2 x86 +host; it is not part of the portable library build. + +| Code | Minimum distance at these dimensions | Setup-failure bound | +| --- | ---: | ---: | +| GF(2^128), lifted RM BAA | 209,716 (>10%) | <= 2^-47.093 | +| Fp, Newton, all-one scans | 245,367 (>11.7%) | < 2^-49.64736 | +| GF(2^128), RS, q=256 scans | 640,135 (>30.524%) | < 2^-59.13394 | +| Fp, Newton, q=256 scans | 640,135 (>30.524%) | < 2^-59.13394 | + +These are lower bounds for all nonzero messages, including messages selected +after setup. They are not measurements of actual minimum distance. The +probability space uses ideal independent uniform permutations and coefficients. +The implementations expand seeds with AES; the Fp research benchmark uses +deterministic reproducibility streams. The finite certificates do not directly +establish the same failure probabilities for those pseudorandom ensembles or +for other lengths. No protocol security claim is made here. + +For RM, the binary generator matrix is unchanged under field extension. +Expand a nonzero extension-field message in an F2 basis. At least one binary +component is nonzero, and its encoded support is contained in the support of +the extension-field codeword. Thus the extension-field distance is at least the +binary distance. Embedding binary messages gives the reverse inequality, so +the distances are equal for every fixed setup. The original first-moment +script from gen-BAA commit `568cfc7` is included with a constituent selector. +Its complete length-2^21 calculation is in `certificates/rm-2097152.txt`. +This is the paper's floating-point numerical procedure, with a one-bit +allowance on each subtotal; it is not an interval-arithmetic certificate. + +For q=256, the saved certificate's sparse leaves use the direct quotient-rank +bound, and all 349 dense leaves use that same direct bound. No leaf uses the +short-gap, triangle-free argument that depends on large characteristic. +The direct bound applies over any one fixed field with a local [16,8,9] MDS +code and 256 distinct nonzero coefficients: after conditioning on previous +coefficients and imposed zero equations, a new independent zero equation +raises rank; if the input and feedback forms are dependent, at most one of +the 256 fresh coefficients cancels them identically. This uses only field +linear algebra and the coefficient atom bound 1/256. The support polynomial +`1 + sum(d=9..16, binom(16,d) z^d tau^(d-8))` follows from the MDS shortened +dimensions and is also independent of characteristic. Permutation averaging, +the two-scan rank potential, and the final support sums therefore transfer +without changing a numerical witness. The compressed ledger, original replay, +and transfer result are stored under `certificates/`. The transfer checker +rejects any characteristic-dependent leaf before replaying the exact rational +sum. The all-one Fp proof does not transfer by this argument; its Newton circuit +also fails to be MDS if simply reduced modulo two. + +The GF small-alphabet encoder evaluates its RS polynomial at polynomial-basis +points 0 through 15, with the first eight coordinates systematic. For the +subspace U={0,...,7}, its subspace polynomial P_U is additive with constant +nonzero derivative. Lagrange coefficients on the coset 8+U therefore have the +form `M[i,j] = c[i XOR j]`. In characteristic two, changing each group-algebra +variable from x to t=x+1 gives t^2=0. A three-bit zeta transform converts this +XOR convolution into subset convolution. The constant transformed coefficient +is one, leaving 19 nontrivial products instead of 64. `AdditiveRs8` uses three +explicit batches of eight SIMD slots and fixed unrolled transforms. The same +kernel handles the transpose because M is symmetric. Independent scalar RS +evaluation checks the resulting encoder; exhaustive tests check the RM local +weight spectrum and all 256 small multipliers on all 128 basis vectors. + +Build the GF comparison with `LIBOTE_BAA_BENCHMARK=ON`, then run +`chosen_baa_directions 2097152 31 1`. Build the Fp comparison with +`python build_fp_comparison.py --reference /path/to/gen-BAA --build-dir /tmp/fp-baa`; +run `/tmp/fp-baa/fp_baa_directions --test`, followed by +`/tmp/fp-baa/fp_baa_directions 2097152 31 1`. The builder copies the reference +unchanged, extracts its shared prefixes before `main`, and records source +hashes. Pin both benchmark executables to the same CPU. Run them sequentially. +Setup, allocation, input restoration, reference comparisons, and checksums are +outside the timers. Each direction has two warmups, followed by 31 samples. +The forward and transpose phases run separately, so transpose restoration does +not change the forward cache conditions. Repeat across six seeds and alternate +the order of the GF and Fp processes. Report the median of the six per-seed +medians, retaining their range. + +Replay distance evidence with: + +``` +python certificates/binary_first_moment.py --n 2097152 --constituent rm +python certificates/verify_field_transfer.py /path/to/gen-BAA +``` + +The second command uses the original gen-BAA verifier and its numpy/scipy +dependencies. Its uncompressed ledger SHA-256 is +`45cce4c94abfbfc967eeb9c4316b75a8c497dbd75605e8fcbe7cc3ee4a4adda1`. + +The target optimization pass preserves both code matrices, coefficient streams, +and distance evidence. At the same dimensions on Peach, six seeds with two +warmups and 31 samples per direction give the following milliseconds. Old and +new executables alternate order across seeds; every per-seed checksum matches. + +| Profile | Previous forward / transpose | Current forward | Current transpose | +| --- | ---: | ---: | ---: | +| RM, >10% | 10.77 / 12.99 | 10.57 (10.56–10.62) | 9.57 (9.50–9.61) | +| RS q256, >30.524% | 19.94 / 19.44 | 17.35 (17.30–17.42) | 16.85 (16.83–16.91) | + +Thus the RM transpose beats the 10.7 ms target, and both q256 directions are +approximately 17 ms. The higher distance certificate remains 30.524%, not 32%. +`results/target-summary.json` records these aggregates; the source, scripts, +individual results, compiler flags and machine details are archived in +`results/peach-code-targets-20261114.tar.gz`. + +The RM transpose keeps the first suffix/scatter pass, then computes the final +suffix sum contiguously and fuses its inverse gather with local compression. +The inverse permutation adds 4n bytes of setup storage (8 MiB here), with no +encoding-time allocation. AArch64 retains the original scatter/compression +path: the fused version regressed the native M3 transpose from about 17.4 to +20.6 ms. It therefore allocates no inverse permutation on AArch64. + +The q256 fast path uses three GFNI bytewise affine maps for polynomial +multiplication and reduction. It computes the low and high product bytes in +parallel and folds the highest byte modulo x^128+x^7+x^2+x+1. A shared 16 KiB +constant table stores duplicated low/high matrices and the two-byte reduction +map on one cache line per coefficient. This removes broadcasts from the +recurrence. Table selection depends only on the public code coefficient. +All 256 coefficients, including polynomial x^8 (encoding 256), pass tests on +all 128 input basis vectors against full GF(2^128) multiplication. + +GFNI is selected at compile time when both `OC_ENABLE_SSE2` and `__GFNI__` are +defined. These Peach results use `-O3 -march=native`, including AVX-512, +VPCLMUL and GFNI. For a compatible GCC/Clang x86 target, `-mgfni` (for example +`-DCMAKE_CXX_FLAGS=-mgfni`) enables the new path without requiring AVX-512. +This is a static ISA requirement, not runtime CPU dispatch. Builds without +GFNI retain the two-carryless-product kernel; ARM retains PMULL, portable +builds retain scalar arithmetic, and other fields retain their compile-time +arithmetic policy. Both profiles prefetch 256 elements ahead on x86. + +Sequential full-size backend spot checks (one seed, 15 samples, five for +portable) give RM forward/transpose of 10.82/10.13 ms with AVX2+VPCLMUL, +10.87/10.47 ms with plain AVX2, and 21.37/20.71 ms with portable arithmetic. +The corresponding q256 times without GFNI are 21.14/21.87, 23.48/23.34, +and 332.68/298.76 ms. These are backend checks, not the six-seed target result. The final M3 path +measured 20.57–22.92/17.95–18.06 ms for RM and +35.54–35.99/28.11–28.42 ms for q256 across two seeds; raw results are in +`results/mac-code-targets-20261114.tar.gz`. +GFNI-enabled unit tests pass the independent scalar references, generic +Goldilocks checks, transpose identities and exhaustive multiplier tests. +ASan/UBSan also passes n=32, 96, 1056 and 262144 with GFNI enabled. + +The following tables retain the earlier comparison with Fp and the prior +backend measurements; they precede the target optimization above. + +On Peach (Ryzen 7950X, CPU 2, 4.5 GHz, boost disabled, GCC 15.2, `-O3 +-march=native`), the six-seed results are below. Times are milliseconds; +parentheses show the range of per-seed medians. The archive in +`results/peach-code-directions-20261113.tar.gz` contains the measured source, +source hashes, compiler/machine details, and per-seed results. The separate +`results/final-summary.json` records the aggregate values. + +| Code | Forward k -> n | Transpose n -> k | +| --- | ---: | ---: | +| GF(2^128), RM, >10% | 10.72 (10.70–10.78) | 12.98 (12.98–13.36) | +| Fp, all-one, >11.7% | 12.15 (12.13–12.21) | 17.15 (17.10–17.17) | +| GF(2^128), q=256, >30.524% | 19.94 (19.86–20.02) | 19.49 (19.44–19.51) | +| Fp, q=256, >30.524% | 17.36 (17.27–17.56) | 23.04 (23.01–23.12) | +| Previous GF full-field RS, 30% | 30.92 (30.80–31.01) | 28.02 (27.73–28.16) | + +In that earlier implementation, the high-distance GF forward encoder was about +15% slower than Fp. Its +transpose is about 15% faster, and its two directions are within 3%. The lower +distance GF code is faster than the corresponding Fp control, with the weaker +10% versus 11.7% distance bound. The current target measurements above close this forward-time gap; these +earlier results alone did not. The previous full-field row is measured with +the same caller-owned buffers; older timings that included allocation and +different cache preparation should not be substituted into this table. + +Backend spot checks at the same full dimensions are shown separately. Peach +AVX2 rows use 15 samples for one seed; portable uses five samples for that seed. +Apple M3 uses Apple Clang 15 and 15 samples. The M3 range covers two runs +bracketing the prefetch experiment; it is not a six-seed statistical summary. +Every run checked the full forward/transpose inner-product identity. + +| Backend | RM forward / transpose | q256 forward / transpose | +| --- | ---: | ---: | +| Peach AVX2 + VPCLMUL | 10.86 / 13.23 | 21.40 / 22.64 | +| Peach AVX2 + PCLMUL | 11.05 / 13.61 | 23.78 / 24.07 | +| Apple M3 PMULL | 20.85–22.29 / 17.72–18.05 | 35.71–35.84 / 28.14–28.25 | +| Peach portable arithmetic | 21.39 / 21.33 | 329.84 / 297.25 | + +ARM prefetch, paired-recursion expansion, and a CLMUL-only small-product +reduction were tried and not retained. The selected small-product kernel uses +two carryless products and a bounded shift/XOR reduction. Portable correctness +also passed the scalar encoder references, local RM spectrum, and all small +multiplier basis cases. ASan/UBSan passed sizes 32, 96, 1056, and 262144 on +the AVX2/VPCLMUL path. Fp transpose tests cover every local basis vector, +zero, maximal canonical values, random values, batch tails, and in-place use. diff --git a/libOTe_Tests/benchmarks/ChosenBaaSetup.cpp b/libOTe_Tests/benchmarks/ChosenBaaSetup.cpp new file mode 100644 index 00000000..928d0f1d --- /dev/null +++ b/libOTe_Tests/benchmarks/ChosenBaaSetup.cpp @@ -0,0 +1,91 @@ +#include "libOTe/Tools/BlkAccCode/ChosenBAA30.h" +#include +#include +#include +#include +#include +#include + +using namespace osuCrypto; +using Clock = std::chrono::steady_clock; + +// Isolate encoder code generation from the surrounding benchmark loops. +OC_NOINLINE void forward(const ChosenBAA30<>& code, span message, + span output, span scratch) +{ + code.encode(message, output, scratch); +} +OC_NOINLINE void transposed(const ChosenBAA30<>& code, span input, span scratch) +{ + code.dualEncode(input, scratch); +} +OC_NOINLINE void setup(ChosenBAA30<>& code, u64 n, block seed) +{ + code.config(n, seed); +} + +double elapsed(Clock::time_point start) +{ + return std::chrono::duration(Clock::now() - start).count(); +} + +double median(std::vector& times) +{ + std::sort(times.begin(), times.end()); + return times[times.size() / 2]; +} + +int main(int argc, char** argv) +{ + const u64 n = argc > 1 ? std::stoull(argv[1]) : 2823424; + const unsigned seed = argc > 2 ? std::stoul(argv[2]) : 1; + if (!n || n % 16 || n > (u64{1} << 24)) + throw std::invalid_argument("Codeword length must be a multiple of 16 in [16, 2^24]."); + constexpr unsigned samples = 11, warmups = 2; + ChosenBAA30<> code; + AlignedUnVector message(n / 2), original(n), output(n), scratch(n), transpose(n); + PRNG random(block(126, seed)); + random.get(message.data(), message.size()); + random.get(original.data(), original.size()); + std::vector setupTimes, forwardTimes, transposeTimes; + + for (unsigned i = 0; i < samples + warmups; ++i) + { + const auto start = Clock::now(); + setup(code, n, block(125, seed * 100 + i)); + const auto ms = elapsed(start); + if (i >= warmups) setupTimes.push_back(ms); + } + u64 metadata = 0; + for (unsigned stage = 0; stage < 2; ++stage) + for (u64 i = 0; i < n; ++i) + metadata = metadata * 0x9e3779b97f4a7c15ull + code.metadata(stage, i); + + for (unsigned i = 0; i < samples + warmups; ++i) + { + const auto start = Clock::now(); + forward(code, message, output, scratch); + const auto ms = elapsed(start); + if (i >= warmups) forwardTimes.push_back(ms); + } + for (unsigned i = 0; i < samples + warmups; ++i) + { + std::copy(original.begin(), original.end(), transpose.begin()); + const auto start = Clock::now(); + transposed(code, transpose, scratch); + const auto ms = elapsed(start); + if (i >= warmups) transposeTimes.push_back(ms); + } + block lhs = ZeroBlock, rhs = ZeroBlock; + for (u64 i = 0; i < n; ++i) lhs ^= original[i].gf128Mul(output[i]); + for (u64 i = 0; i < n / 2; ++i) rhs ^= message[i].gf128Mul(transpose[i]); + if (lhs != rhs) throw std::runtime_error("transpose identity failed"); + + std::printf("n=%llu seed=%u setup=%.6f forward=%.6f transpose=%.6f " + "metadata=%016llx output=%016llx/%016llx\n", + static_cast(n), seed, + median(setupTimes), median(forwardTimes), median(transposeTimes), + static_cast(metadata), + static_cast(output[0].get(0)), + static_cast(transpose[0].get(0))); +} diff --git a/libOTe_Tests/benchmarks/ChosenBaaSetup.md b/libOTe_Tests/benchmarks/ChosenBaaSetup.md new file mode 100644 index 00000000..35f2134d --- /dev/null +++ b/libOTe_Tests/benchmarks/ChosenBaaSetup.md @@ -0,0 +1,46 @@ +# ChosenBAA30 setup and scan scheduling + +November 15, 2026. Setup packs coefficient bytes from contiguous PRNG views and +prefetches Fisher--Yates destinations in batches of 64. Draws, rejection draws, +and swaps retain their original order, preserving the exact seed-to-code map. +GF128 scans on x86 VPCLMUL builds use four-element, fully unrolled batches; +ARM, portable arithmetic, and other field policies retain sixteen-element +batches. Distance, field, coefficient distribution, and noise parameters are +unchanged. + +Sequential Peach comparisons use CPU 2 on a Ryzen 7950X at 4.5 GHz, GCC 15.2, +`-O3 -march=native` (AVX-512/VPCLMUL/GFNI), three seeds, two warmups, and eleven +samples per seed. Each entry is the median of the three per-seed medians. +Setup includes fresh permutations and coefficients, reusing allocated capacity; +encoding excludes setup and uses caller-owned buffers. Times are milliseconds. + +`ChosenBaaSetup.cpp` reproduces the sampling and correctness checks. Build it +with the same Release/ISA flags and cryptoTools installation as the library; +its arguments are codeword length and seed. Run one process at a time, pinned +to CPU 2, for lengths 2097152 and 2823424 and seeds 4, 5, and 6. Setup uses a +fresh seed per sample; encoding reuses the final configured code. + +| Codeword length | Setup before / after | Forward before / after | Transpose before / after | +| --- | ---: | ---: | ---: | +| 2,097,152 (`k=2^20`) | 10.38 / 8.20 | 17.11 / 15.21 | 17.08 / 15.62 | +| 2,823,424 (2^20-item PSI shape) | 14.59 / 11.38 | 24.37 / 21.74 | 24.60 / 22.55 | + +The shorter scan also improves the AVX2/VPCLMUL paths with and without GFNI +on Peach. Other fields and the ARM/portable scan schedule are unchanged; +these measurements do not establish native Apple timings. Metadata and output +checksums match the previous implementation for every compared seed. The unit +test compares every metadata entry with scalar setup, including batch tails +and a 1,048,592-element case with rejection sampling; field-generic scalar +references and transpose identities also pass. ASan/UBSan checks pass at +lengths 16, 48, 64, 80, 144, 1040, and 262144. + +With one core per party, the dependent 2^20-item SH PSI benchmark improves from +392.8 to 377.3 ms warm median (six trials; first run 542.6 to 530.0 ms). +Both measurements include fresh BAA setup and use the default allocator. +The harness uses two processes pinned to CPUs 2 and 3 and BufferingSocket over +AF_UNIX, including IPC and copies. These are elapsed protocol times, not +per-party CPU work or TCP-network measurements. OKVS is unchanged. + +Paired scans, a 512-bit GFNI recurrence, altered encoding prefetch policies, +and delayed local-RS reductions did not improve the measured workload and +were not retained. Historical comparisons are in [ChosenBaaDirections.md](ChosenBaaDirections.md). diff --git a/libOTe_Tests/benchmarks/FpBaaDirections.cpp b/libOTe_Tests/benchmarks/FpBaaDirections.cpp new file mode 100644 index 00000000..6acc8c6f --- /dev/null +++ b/libOTe_Tests/benchmarks/FpBaaDirections.cpp @@ -0,0 +1,150 @@ +// Standalone comparison with gen-BAA's optimized prime-field reference. +// Build with its bench directory on the include path; see ChosenBaaDirections.md. +#include "width_one_small_q_shared.inc" + +namespace fp128 { +template inline void transpose_newton_steps(Batch43 (&v)[8], const Batch43* in) { + v[0]=batch_add(v[0],in[T]); + constexpr unsigned count=(15-T<7)?15-T:7; + #pragma GCC unroll 7 + for(unsigned j=count;j-- >0;)v[j+1]=batch_add(v[j+1],v[j]); + if constexpr(T>1)transpose_newton_steps(v,in); +} +inline void transpose_newton_batch8(const F* input,F* output) { + Batch43 raw[16]; + #pragma GCC unroll 4 + for(unsigned c=0;c<16;c+=4) { + __m512i a,b,d,e,f,g,h,j; + transpose128(_mm512_loadu_si512(input+c),_mm512_loadu_si512(input+16+c), + _mm512_loadu_si512(input+32+c),_mm512_loadu_si512(input+48+c),a,b,d,e); + transpose128(_mm512_loadu_si512(input+64+c),_mm512_loadu_si512(input+80+c), + _mm512_loadu_si512(input+96+c),_mm512_loadu_si512(input+112+c),f,g,h,j); + raw[c]=batch_unpack(a,f);raw[c+1]=batch_unpack(b,g); + raw[c+2]=batch_unpack(d,h);raw[c+3]=batch_unpack(e,j); + } + Batch43 v[8]{};v[7]=raw[15];transpose_newton_steps<14>(v,raw);v[0]=batch_add(v[0],raw[0]); + // Transposed coefficient sums are at most 6436, so the same unreduced + // three-limb representation stays below 2^57. Reduce each output once. + BatchPair values[8]; + #pragma GCC unroll 8 + for(unsigned j=0;j<8;++j)values[j]=batch_reduce(v[j]); + #pragma GCC unroll 2 + for(unsigned group=0;group<2;++group) { + const __m512i indices=group?_mm512_setr_epi64(4,12,5,13,6,14,7,15):_mm512_setr_epi64(0,8,1,9,2,10,3,11); + #pragma GCC unroll 2 + for(unsigned c=0;c<8;c+=4) { + const __m512i a=_mm512_permutex2var_epi64(values[c].low,indices,values[c].high); + const __m512i b=_mm512_permutex2var_epi64(values[c+1].low,indices,values[c+1].high); + const __m512i d=_mm512_permutex2var_epi64(values[c+2].low,indices,values[c+2].high); + const __m512i e=_mm512_permutex2var_epi64(values[c+3].low,indices,values[c+3].high); + __m512i r0,r1,r2,r3;transpose128(a,b,d,e,r0,r1,r2,r3); + F* dest=output+group*32+c; + _mm512_storeu_si512(dest,r0);_mm512_storeu_si512(dest+8,r1); + _mm512_storeu_si512(dest+16,r2);_mm512_storeu_si512(dest+24,r3); + } + } +} +inline void transpose_newton(const F* input,F* output,size_t n) { + size_t i=0; + for(;i+128<=n;i+=128)transpose_newton_batch8(input+i,output+i/2); + for(;i0;--t) { + v[0]=lazy_add(v[0],{input[i+t],0}); + for(unsigned j=std::min(7u,15-t);j-- >0;)v[j+1]=lazy_add(v[j+1],v[j]); + } + v[0]=lazy_add(v[0],{input[i],0}); + for(unsigned j=0;j<8;++j)output[i/2+j]=lazy_reduce(v[j]); + } +} +template inline void transpose_scan(const F* input,F* output,const uint32_t* meta,size_t n) { + F sum=0;uint32_t coefficient=1; + for(size_t end=n;end;end-=16) { + const size_t i=end-16; + if(i>=64) { + #pragma GCC unroll 16 + for(unsigned j=0;j<16;++j)__builtin_prefetch(output+(meta[i-64+j]&MASK21),0,1); + } + #pragma GCC unroll 16 + for(unsigned j=16;j-- >0;) { + if constexpr(AllOne)sum=add_asm(sum,input[i+j]); + else sum=madd_small(sum,coefficient,input[i+j]); + coefficient=(meta[i+j]>>21)+1; + output[meta[i+j]&MASK21]=sum; + } + } +} +} + +template void directions(size_t n,uint64_t seed,int iterations) { + using C=CertifiedConfig; + const size_t k=n/2; + auto stages=certified_setup(n,seed); + Rng random{seed};std::vector message(k),original(n),output(n),scratch(n),dual(n),expected(n); + for(auto& x:message)x=random.field();for(auto& x:original)x=random.field(); + auto forward=[&] { + fp128::encode_block8_16(message.data(),output.data(),k); + C::scan(output.data(),scratch.data(),stages[0].data(),n); + C::scan(scratch.data(),output.data(),stages[1].data(),n); + }; + // Independent full-vector forward reference before measurement. + certified_local_reference(message.data(),expected.data(),k); + certified_reference(expected.data(),scratch.data(),stages[0].data(),n); + certified_reference(scratch.data(),expected.data(),stages[1].data(),n); + std::vector ft,tt;uint64_t check=0; + for(int i=0;i(std::chrono::steady_clock::now()-start).count(); + if(i>=2)ft.push_back(ms);check^=uint64_t(output[i%n]); + } + if(output!=expected)throw std::runtime_error("Fp forward reference mismatch"); + for(int i=0;i(dual.data(),scratch.data(),stages[1].data(),n); + fp128::transpose_scan(scratch.data(),dual.data(),stages[0].data(),n); + fp128::transpose_newton(dual.data(),dual.data(),n); + double ms=std::chrono::duration(std::chrono::steady_clock::now()-start).count(); + if(i>=2)tt.push_back(ms);check^=uint64_t(dual[i%k]); + } + F lhs=0,rhs=0; + for(size_t i=0;i input(n),out(n/2),reference(n/2); + for(unsigned pattern=0;pattern<19;++pattern) { + for(size_t i=0;i1?std::stoull(argv[1]):1u<<21; + const int it=argc>2?std::stoi(argv[2]):15; + const uint64_t seed=argc>3?std::stoull(argv[3]):1; + if(!n||n%16||n>(1u<<21)||it<1)throw std::invalid_argument("Fp benchmark arguments"); + std::cout<<"code,k,n,seed,forward_ms,transpose_ms,checksum\n"; + directions<4>(n,seed,it);directions<0>(n,seed,it); +} diff --git a/libOTe_Tests/benchmarks/build_fp_comparison.py b/libOTe_Tests/benchmarks/build_fp_comparison.py new file mode 100644 index 00000000..789dc11c --- /dev/null +++ b/libOTe_Tests/benchmarks/build_fp_comparison.py @@ -0,0 +1,36 @@ +"""Build the AVX-512 Fp comparison against an unchanged gen-BAA reference. + +python build_fp_comparison.py --reference /path/to/gen-BAA --build-dir /tmp/fp-comparison +Requires an AVX-512/BMI2 x86 host, GCC/Clang, and Boost multiprecision headers. +Does not run a benchmark. Run the resulting executable sequentially. +""" +import argparse +import hashlib +import json +import pathlib +import shutil +import subprocess + +p = argparse.ArgumentParser() +p.add_argument('--reference', required=True, type=pathlib.Path) +p.add_argument('--build-dir', required=True, type=pathlib.Path) +p.add_argument('--cxx', default='c++') +args = p.parse_args() +source = args.reference / 'field-universality/expander-lift/bench' +build = args.build_dir.resolve() +reference = build / 'reference' +reference.mkdir(parents=True, exist_ok=True) +manifest = {} +for pattern in ('*.h', '*.cpp'): + for path in source.glob(pattern): + shutil.copy2(path, reference / path.name) + manifest[path.name] = hashlib.sha256(path.read_bytes()).hexdigest() +for stem, include in [('certified_convolution_bench', 'certified_convolution_shared'), + ('width_one_small_q_bench', 'width_one_small_q_shared')]: + text = (reference / (stem + '.cpp')).read_text() + (reference / (include + '.inc')).write_text(text[:text.index('int main(')]) +driver = pathlib.Path(__file__).with_name('FpBaaDirections.cpp') +manifest[driver.name] = hashlib.sha256(driver.read_bytes()).hexdigest() +(build / 'source-sha256.json').write_text(json.dumps(manifest, indent=2) + '\n') +subprocess.run([args.cxx, '-O3', '-march=native', '-DNDEBUG', '-std=c++20', + '-I' + str(reference), str(driver), '-o', str(build / 'fp_baa_directions')], check=True) diff --git a/libOTe_Tests/benchmarks/certificates/binary_first_moment.py b/libOTe_Tests/benchmarks/certificates/binary_first_moment.py new file mode 100644 index 00000000..d534703b --- /dev/null +++ b/libOTe_Tests/benchmarks/certificates/binary_first_moment.py @@ -0,0 +1,401 @@ +#!/usr/bin/env python3 +"""Finite-length binary chosen-block BAA first-moment certificate. + +For low outer weights the script uses exact coefficients of ``W_0(z)^B`` and +sums the binary accumulator transition over every feasible intermediate +weight. For the remaining outer weights it combines a coefficient Chernoff +bound with the maximum transition term and counts every feasible intermediate +weight. The resulting number is an upper bound on the complete sum (B4), not +only a sparse-term proxy. + +All logarithms are natural internally. Each floating-point subtotal is rounded +outward by ``SAFETY_NATS`` before it enters the reported certificate. +""" + +from __future__ import annotations + +import argparse +import math +from dataclasses import dataclass + +import numpy as np + + +LN2 = math.log(2.0) +NEG_INF = float("-inf") +# A full bit is vastly larger than the observed floating-point variation when +# changing the low-weight cutoff or the tilt-grid density. +SAFETY_NATS = LN2 + + +@dataclass(frozen=True) +class Constituent: + name: str + m: int + sigma: int + spectrum: dict[int, int] + + +CONSTITUENTS = ( + Constituent( + "Golay [24,12,8]", + 24, + 12, + {0: 1, 8: 759, 12: 2576, 16: 759, 24: 1}, + ), + Constituent( + "RM(2,5) [32,16,8]", + 32, + 16, + {0: 1, 8: 620, 12: 13_888, 16: 36_518, 20: 13_888, 24: 620, 32: 1}, + ), +) + + +def logadd(a: float, b: float) -> float: + if a == NEG_INF: + return b + if b == NEG_INF: + return a + if a < b: + a, b = b, a + return a + math.log1p(math.exp(b - a)) + + +def logsumexp(values: np.ndarray) -> float: + if values.size == 0: + return NEG_INF + maximum = float(np.max(values)) + return maximum + math.log(float(np.exp(values - maximum).sum())) + + +def log_factorials(n: int) -> np.ndarray: + result = np.empty(n + 1, dtype=np.float64) + result[0] = 0.0 + result[1:] = np.cumsum(np.log(np.arange(1, n + 1, dtype=np.float64))) + return result + + +def logchoose_from_factorials(logfac: np.ndarray, n: int, k: np.ndarray | int): + return logfac[n] - logfac[k] - logfac[n - k] + + +def local_log_enumerator(theta: np.ndarray, spectrum: dict[int, int]) -> np.ndarray: + weights = np.array(sorted(spectrum), dtype=np.float64) + logs = np.log(np.array([spectrum[int(w)] for w in weights], dtype=np.float64)) + terms = logs[:, None] + weights[:, None] * theta[None, :] + maxima = terms.max(axis=0) + return maxima + np.log(np.exp(terms - maxima).sum(axis=0)) + + +def local_tilt_mean(theta: np.ndarray, spectrum: dict[int, int]) -> np.ndarray: + weights = np.array(sorted(spectrum), dtype=np.float64) + coeffs = np.array([spectrum[int(w)] for w in weights], dtype=np.float64) + terms = np.log(coeffs)[:, None] + weights[:, None] * theta[None, :] + maxima = terms.max(axis=0) + scaled = np.exp(terms - maxima) + return (weights[:, None] * scaled).sum(axis=0) / scaled.sum(axis=0) + + +def outer_coefficient_chernoff_logs( + constituent: Constituent, + block_count: int, + weights: np.ndarray, +) -> np.ndarray: + """Upper bounds log([z^w] W(z)^B), using an explicit exponential tilt.""" + target_means = weights.astype(np.float64) / block_count + # Any theta gives a valid coefficient bound. A dense monotone grid makes + # this close to the optimizing saddle while retaining the inequality. + theta_grid = np.linspace(-24.0, 0.0, 240_001, dtype=np.float64) + means = local_tilt_mean(theta_grid, constituent.spectrum) + theta = np.interp(target_means, means, theta_grid) + log_w = local_log_enumerator(theta, constituent.spectrum) + return block_count * log_w - weights * theta + + +def hypergeometric_tail_log_bounds(logfac: np.ndarray, n: int, ell: int) -> np.ndarray: + """Upper-bound Q(h,L) by its first hypergeometric term and a geometric tail. + + The identity + + Q(h,L) = Pr[X >= ceil(h/2)], X ~ Hypergeom(n,L,h) + + turns the second accumulator tail into a hypergeometric upper tail. At and + above ``ceil(h/2)`` its successive-term ratio decreases and is below one, so + the first term divided by one minus the first ratio bounds the whole tail. + """ + h = np.arange(1, 2 * ell + 1, dtype=np.int64) + x = (h + 1) // 2 + first = ( + logchoose_from_factorials(logfac, ell, x) + + logchoose_from_factorials(logfac, n - ell, h - x) + - logchoose_from_factorials(logfac, n, h) + ) + ratio = ((ell - x) / (x + 1)) * ((h - x) / (n - ell - h + x + 1)) + result = np.empty(2 * ell + 1, dtype=np.float64) + result[0] = NEG_INF + result[1:] = first - np.log1p(-ratio) + return result + + +def pair_term_log( + logfac: np.ndarray, + log_q_upper: np.ndarray, + n: int, + w: int, + h: int, +) -> float: + r = (w + 1) // 2 + s = w // 2 + return float( + logfac[h - 1] + - logfac[r - 1] + - logfac[h - r] + + logfac[n - h] + - logfac[s] + - logfac[n - h - s] + - logchoose_from_factorials(logfac, n, w) + + log_q_upper[h] + ) + + +def pair_sum_log_bound( + logfac: np.ndarray, + log_q_upper: np.ndarray, + n: int, + ell: int, + w: int, +) -> float: + """Sum the transition bound over every feasible h for a low input weight.""" + r = (w + 1) // 2 + s = w // 2 + h = np.arange(r, min(2 * ell, n - s) + 1, dtype=np.int64) + values = ( + logfac[h - 1] + - logfac[r - 1] + - logfac[h - r] + + logfac[n - h] + - logfac[s] + - logfac[n - h - s] + - logchoose_from_factorials(logfac, n, w) + + log_q_upper[h] + ) + return logsumexp(values) + + +def exact_outer_coefficients( + spectrum: dict[int, int], block_count: int, cutoff: int +) -> list[int]: + """Compute [z^w] W_0(z)^B exactly through ``cutoff``. + + From W f' = B W' f for f=W^B and W(0)=1, + + w f_w = sum_j (((B+1)j-w) W_j f_{w-j}). + """ + coefficients = [0] * (cutoff + 1) + coefficients[0] = 1 + nonzero = [(j, a) for j, a in spectrum.items() if j] + for w in range(1, cutoff + 1): + numerator = sum( + ((block_count + 1) * j - w) * a * coefficients[w - j] + for j, a in nonzero + if j <= w + ) + coefficients[w], remainder = divmod(numerator, w) + if remainder: + raise ArithmeticError("power-series recurrence lost integrality") + return coefficients + + +def low_weight_log_bound( + constituent: Constituent, + n: int, + ell: int, + cutoff: int, + logfac: np.ndarray, + log_q_upper: np.ndarray, +) -> tuple[float, list[tuple[int, float]]]: + coefficients = exact_outer_coefficients( + constituent.spectrum, n // constituent.m, cutoff + ) + terms: list[tuple[int, float]] = [] + total = NEG_INF + for w, coefficient in enumerate(coefficients): + if w == 0 or coefficient == 0: + continue + value = math.log(coefficient) + pair_sum_log_bound( + logfac, log_q_upper, n, ell, w + ) + terms.append((w, value)) + total = logadd(total, value) + return total + SAFETY_NATS, terms + + +def maximize_pair_term_by_parity( + logfac: np.ndarray, + log_q_upper: np.ndarray, + n: int, + ell: int, + w: int, + starts: list[int], +) -> tuple[float, list[int]]: + """Find each parity subsequence's mode by discrete hill climbing. + + For the tail ranges used here, the logarithm of the product of the + accumulator transition and the hypergeometric-tail bound is strictly + unimodal on each h-parity subsequence. The neighboring-value checks below + locate those two modes; the caller carries the modes forward as w grows. + """ + lo = (w + 1) // 2 + hi = min(2 * ell, n - w // 2) + maxima: list[float] = [] + modes: list[int] = [] + for parity in (0, 1): + parity_lo = lo + ((parity - lo) & 1) + parity_hi = hi - ((hi - parity) & 1) + if parity_lo > parity_hi: + maxima.append(NEG_INF) + modes.append(parity_lo) + continue + h = min(max(starts[parity], parity_lo), parity_hi) + if (h & 1) != parity: + h += 1 if h < parity_hi else -1 + value = pair_term_log(logfac, log_q_upper, n, w, h) + while h - 2 >= parity_lo: + candidate = pair_term_log(logfac, log_q_upper, n, w, h - 2) + if candidate <= value: + break + h -= 2 + value = candidate + while h + 2 <= parity_hi: + candidate = pair_term_log(logfac, log_q_upper, n, w, h + 2) + if candidate <= value: + break + h += 2 + value = candidate + if h - 2 >= parity_lo: + assert pair_term_log(logfac, log_q_upper, n, w, h - 2) <= value + 1e-7 + if h + 2 <= parity_hi: + assert pair_term_log(logfac, log_q_upper, n, w, h + 2) <= value + 1e-7 + maxima.append(value) + modes.append(h) + return max(maxima), modes + + +def verify_tail_unimodality_boundary( + logfac: np.ndarray, + log_q_upper: np.ndarray, + n: int, + ell: int, + w: int, +) -> None: + """Check strict parity-wise log concavity at the least-curved tail weight. + + The two binomial ratios in the first-accumulator transition decrease more + strongly as w increases. Thus the first tail weight is the boundary case + for the parity-wise unimodality used by the mode search. + """ + r = (w + 1) // 2 + s = w // 2 + h = np.arange(r, min(2 * ell, n - s) + 1, dtype=np.int64) + values = ( + logfac[h - 1] + - logfac[r - 1] + - logfac[h - r] + + logfac[n - h] + - logfac[s] + - logfac[n - h - s] + - logchoose_from_factorials(logfac, n, w) + + log_q_upper[h] + ) + for parity in (0, 1): + subsequence = values[(h & 1) == parity] + if subsequence.size >= 3 and float(np.max(np.diff(subsequence, n=2))) >= -1e-7: + raise ArithmeticError("tail transition failed the unimodality check") + + +def bounded_tail( + constituent: Constituent, + n: int, + ell: int, + cutoff: int, + logfac: np.ndarray, + log_q_upper: np.ndarray, +) -> tuple[float, tuple[int, int, float]]: + block_count = n // constituent.m + first = cutoff + (4 - cutoff % 4) % 4 + if first <= cutoff: + first += 4 + last = min(n, 4 * ell) + weights = np.arange(first, last + 1, 4, dtype=np.int64) + verify_tail_unimodality_boundary(logfac, log_q_upper, n, ell, int(weights[0])) + outer = outer_coefficient_chernoff_logs(constituent, block_count, weights) + subtotal = np.empty(weights.size, dtype=np.float64) + starts = [first, first + 1] + largest = (0, 0, NEG_INF) + for index, (w_value, outer_log) in enumerate(zip(weights, outer)): + w = int(w_value) + pair_max, starts = maximize_pair_term_by_parity( + logfac, log_q_upper, n, ell, w, starts + ) + h_count = min(2 * ell, n - w // 2) - (w + 1) // 2 + 1 + subtotal[index] = float(outer_log) + pair_max + math.log(h_count) + if subtotal[index] > largest[2]: + valid_modes = [h for h in starts if (w + 1) // 2 <= h <= min(2 * ell, n - w // 2)] + best_h = max( + valid_modes, + key=lambda h: pair_term_log(logfac, log_q_upper, n, w, h), + ) + largest = (w, best_h, subtotal[index]) + return logsumexp(subtotal) + SAFETY_NATS, largest + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--n", type=int, default=2_097_024) + parser.add_argument("--delta", type=float, default=0.10) + parser.add_argument("--constituent", choices=("all", "rm", "golay"), default="all") + parser.add_argument( + "--cutoff", + type=int, + default=32, + help="largest outer weight summed directly (multiple of 4, at least 24)", + ) + args = parser.parse_args() + constituents = CONSTITUENTS if args.constituent == "all" else (CONSTITUENTS[1 if args.constituent == "rm" else 0],) + + n = args.n + ell = math.floor(args.delta * n) + if not 0 < ell < n // 2: + raise SystemExit("delta must give 0 < floor(delta*n) < n/2") + if args.cutoff < 24 or args.cutoff % 4: + raise SystemExit("cutoff must be a multiple of 4 and at least 24") + if any(n % c.m for c in constituents): + raise SystemExit("n must be divisible by every constituent block length") + logfac = log_factorials(n) + log_q_upper = hypergeometric_tail_log_bounds(logfac, n, ell) + + print(f"n={n} L={ell} delta_actual={ell/n:.17g} cutoff={args.cutoff}") + for constituent in constituents: + low, low_terms = low_weight_log_bound( + constituent, n, ell, args.cutoff, logfac, log_q_upper + ) + tail, largest = bounded_tail( + constituent, n, ell, args.cutoff, logfac, log_q_upper + ) + complete = logadd(low, tail) + print(constituent.name) + for w, value in low_terms: + print(f" exact outer coefficient w={w:2d}: bounded contribution 2^({value/LN2:.6f})") + print(f" w<={args.cutoff} subtotal upper bound: 2^({low/LN2:.6f})") + print(f" w>{args.cutoff} subtotal upper bound: 2^({tail/LN2:.6f})") + print( + f" largest tail summand bound: w={largest[0]} h={largest[1]} " + f"2^({largest[2]/LN2:.6f})" + ) + print(f" COMPLETE mu_bin upper bound: 2^({complete/LN2:.6f})") + print(f" CERTIFIED SECURITY BITS: {-complete/LN2:.6f}") + + +if __name__ == "__main__": + main() diff --git a/libOTe_Tests/benchmarks/certificates/field-transfer.json b/libOTe_Tests/benchmarks/certificates/field-transfer.json new file mode 100644 index 00000000..ac457539 --- /dev/null +++ b/libOTe_Tests/benchmarks/certificates/field-transfer.json @@ -0,0 +1,12 @@ +{ + "construction": "MDS [16,8,9]; two uniform independent permutations; two recursive scans", + "alphabet": "256 distinct nonzero elements of any one fixed field admitting the local MDS code", + "n": 2097152, + "k": 1048576, + "minimum_distance_at_least": 640135, + "failure_upper": "2310514520786904766507047478833/1461501637330902918203684832716283019655932542976", + "failure_log2_upper": "-11826788599401/200000000000", + "direct_leaves": 349, + "characteristic_dependent_leaves": 0, + "ledger_sha256": "45cce4c94abfbfc967eeb9c4316b75a8c497dbd75605e8fcbe7cc3ee4a4adda1" +} diff --git a/libOTe_Tests/benchmarks/certificates/q256-direct.json.gz b/libOTe_Tests/benchmarks/certificates/q256-direct.json.gz new file mode 100644 index 00000000..c223047d Binary files /dev/null and b/libOTe_Tests/benchmarks/certificates/q256-direct.json.gz differ diff --git a/libOTe_Tests/benchmarks/certificates/q256-replay.json b/libOTe_Tests/benchmarks/certificates/q256-replay.json new file mode 100644 index 00000000..359c93cf --- /dev/null +++ b/libOTe_Tests/benchmarks/certificates/q256-replay.json @@ -0,0 +1,23 @@ +{ + "kind": "small-q-fresh-pairs-direct-sparse-v2", + "n": 2097152, + "k": 1048576, + "prime": 340282366920938463463374607431768211297, + "q": 256, + "width": 1, + "block_k": 8, + "scans": 2, + "permutations": 2, + "precode": "extended_newton_8_16", + "minimum_distance_at_least": 640135, + "failure_upper": "2310514520786904766507047478833/1461501637330902918203684832716283019655932542976", + "failure_log2_upper": "-11826788599401/200000000000", + "sparse_failure_upper": "85834659071620047151345714481/91343852333181432387730302044767688728495783936", + "dense_leaves": { + "direct": 349, + "fresh_pairs": 0 + }, + "gap_limit": 4, + "complete_distance_certificate": true, + "scope": "All nonzero messages; uniform independent interval coefficients and two permutations; short-gap triangle-free pair bound plus exact long-gap tail; direct rank-potential sparse bound." +} diff --git a/libOTe_Tests/benchmarks/certificates/rm-2097152.txt b/libOTe_Tests/benchmarks/certificates/rm-2097152.txt new file mode 100644 index 00000000..aa2a9857 --- /dev/null +++ b/libOTe_Tests/benchmarks/certificates/rm-2097152.txt @@ -0,0 +1,14 @@ +n=2097152 L=209715 delta_actual=0.099999904632568359 cutoff=32 +RM(2,5) [32,16,8] + exact outer coefficient w= 8: bounded contribution 2^(-48.093459) + exact outer coefficient w=12: bounded contribution 2^(-76.095413) + exact outer coefficient w=16: bounded contribution 2^(-87.730642) + exact outer coefficient w=20: bounded contribution 2^(-112.898385) + exact outer coefficient w=24: bounded contribution 2^(-124.736857) + exact outer coefficient w=28: bounded contribution 2^(-148.208138) + exact outer coefficient w=32: bounded contribution 2^(-160.115887) + w<=32 subtotal upper bound: 2^(-47.093459) + w>32 subtotal upper bound: 2^(-158.898549) + largest tail summand bound: w=36 h=42 2^(-159.898560) + COMPLETE mu_bin upper bound: 2^(-47.093459) + CERTIFIED SECURITY BITS: 47.093459 diff --git a/libOTe_Tests/benchmarks/certificates/verify_field_transfer.py b/libOTe_Tests/benchmarks/certificates/verify_field_transfer.py new file mode 100644 index 00000000..a10dcc99 --- /dev/null +++ b/libOTe_Tests/benchmarks/certificates/verify_field_transfer.py @@ -0,0 +1,46 @@ +"""Replay the q256 ledger and reject any characteristic-dependent leaf. + +Usage: python verify_field_transfer.py /path/to/gen-BAA +The original verifier imports scipy/numpy for discovery helpers even on replay. +The ledger is vendored here; the mathematical field-transfer argument is in +../ChosenBaaDirections.md. Replaying numbers alone does not prove that transfer. +""" +import hashlib +import gzip +import json +import pathlib +import sys + +root = pathlib.Path(__file__).resolve().parent +research = pathlib.Path(sys.argv[1]) / 'field-universality/expander-lift' +sys.path.insert(0, str(research)) +import small_q_fresh_pair_certificate as certificate + +ledger = gzip.decompress((root / 'q256-direct.json.gz').read_bytes()) +data = json.loads(ledger) +assert data['kind'] == 'small-q-fresh-pairs-direct-sparse-v2' +assert data['n'] == 2097152 and data['q'] == 256 and data['block_k'] == 8 +assert data['source_min'] == 32 and data['steps'] == 16 + +def direct_only(node): + if 'children' in node: + for child in node['children']: + direct_only(child) + elif not node.get('empty'): + assert node['method'] == 'direct', 'Characteristic-dependent leaf cannot transfer.' + +direct_only(data['dense']) +result = certificate.verify(data) +assert result['dense_leaves'] == {'direct': 349, 'fresh_pairs': 0} +assert result['minimum_distance_at_least'] == 640135 +assert result['failure_upper'] == '2310514520786904766507047478833/1461501637330902918203684832716283019655932542976' +print(json.dumps({ + 'construction': 'MDS [16,8,9]; two uniform independent permutations; two recursive scans', + 'alphabet': '256 distinct nonzero elements of any one fixed field admitting the local MDS code', + 'n': result['n'], 'k': result['k'], + 'minimum_distance_at_least': result['minimum_distance_at_least'], + 'failure_upper': result['failure_upper'], + 'failure_log2_upper': result['failure_log2_upper'], + 'direct_leaves': 349, 'characteristic_dependent_leaves': 0, + 'ledger_sha256': hashlib.sha256(ledger).hexdigest(), +}, indent=2)) diff --git a/libOTe_Tests/benchmarks/results/final-summary.json b/libOTe_Tests/benchmarks/results/final-summary.json new file mode 100644 index 00000000..2009b23a --- /dev/null +++ b/libOTe_Tests/benchmarks/results/final-summary.json @@ -0,0 +1,62 @@ +{ + "fp_q1": { + "forward_ms": { + "median": 12.1503, + "min": 12.1258, + "max": 12.2103 + }, + "transpose_ms": { + "median": 17.1494, + "min": 17.0981, + "max": 17.1694 + } + }, + "fp_q256": { + "forward_ms": { + "median": 17.36, + "min": 17.2674, + "max": 17.56 + }, + "transpose_ms": { + "median": 23.04045, + "min": 23.0135, + "max": 23.1216 + } + }, + "gf128_q256": { + "forward_ms": { + "median": 19.94475, + "min": 19.8645, + "max": 20.0204 + }, + "transpose_ms": { + "median": 19.48625, + "min": 19.4437, + "max": 19.5071 + } + }, + "gf128_rm": { + "forward_ms": { + "median": 10.71635, + "min": 10.7043, + "max": 10.7751 + }, + "transpose_ms": { + "median": 12.9825, + "min": 12.9764, + "max": 13.3566 + } + }, + "gf128_rs": { + "forward_ms": { + "median": 30.9152, + "min": 30.797, + "max": 31.0084 + }, + "transpose_ms": { + "median": 28.023049999999998, + "min": 27.7324, + "max": 28.1616 + } + } +} diff --git a/libOTe_Tests/benchmarks/results/mac-code-targets-20261114.tar.gz b/libOTe_Tests/benchmarks/results/mac-code-targets-20261114.tar.gz new file mode 100644 index 00000000..63fb9862 Binary files /dev/null and b/libOTe_Tests/benchmarks/results/mac-code-targets-20261114.tar.gz differ diff --git a/libOTe_Tests/benchmarks/results/machine.txt b/libOTe_Tests/benchmarks/results/machine.txt new file mode 100644 index 00000000..810da931 --- /dev/null +++ b/libOTe_Tests/benchmarks/results/machine.txt @@ -0,0 +1,9 @@ +Linux peach48 6.17.0-41-generic #41-Ubuntu SMP PREEMPT_DYNAMIC Sat Jun 20 18:01:40 UTC 2026 x86_64 GNU/Linux +c++ (Ubuntu 15.2.0-4ubuntu4) 15.2.0 +Copyright (C) 2025 Free Software Foundation, Inc. +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +/sys/devices/system/cpu/cpu2/cpufreq/scaling_governor: userspace +/sys/devices/system/cpu/cpu2/cpufreq/scaling_cur_freq: 4491234 +/sys/devices/system/cpu/cpufreq/boost: 0 diff --git a/libOTe_Tests/benchmarks/results/peach-code-directions-20261113.tar.gz b/libOTe_Tests/benchmarks/results/peach-code-directions-20261113.tar.gz new file mode 100644 index 00000000..1acdb5bd Binary files /dev/null and b/libOTe_Tests/benchmarks/results/peach-code-directions-20261113.tar.gz differ diff --git a/libOTe_Tests/benchmarks/results/peach-code-targets-20261114.tar.gz b/libOTe_Tests/benchmarks/results/peach-code-targets-20261114.tar.gz new file mode 100644 index 00000000..41c5161f Binary files /dev/null and b/libOTe_Tests/benchmarks/results/peach-code-targets-20261114.tar.gz differ diff --git a/libOTe_Tests/benchmarks/results/target-summary.json b/libOTe_Tests/benchmarks/results/target-summary.json new file mode 100644 index 00000000..38ca15a6 --- /dev/null +++ b/libOTe_Tests/benchmarks/results/target-summary.json @@ -0,0 +1,78 @@ +{ + "old": { + "gf128_rm": { + "forward_ms": { + "median": 10.7691, + "min": 10.7468, + "max": 10.9369 + }, + "transpose_ms": { + "median": 12.99325, + "min": 12.9694, + "max": 13.3981 + } + }, + "gf128_q256": { + "forward_ms": { + "median": 19.9443, + "min": 19.8921, + "max": 19.9954 + }, + "transpose_ms": { + "median": 19.439700000000002, + "min": 19.423, + "max": 19.503 + } + }, + "gf128_rs": { + "forward_ms": { + "median": 30.7967, + "min": 30.692, + "max": 30.9896 + }, + "transpose_ms": { + "median": 28.0366, + "min": 27.9425, + "max": 28.0883 + } + } + }, + "new": { + "gf128_rm": { + "forward_ms": { + "median": 10.5747, + "min": 10.5556, + "max": 10.6178 + }, + "transpose_ms": { + "median": 9.569565, + "min": 9.50428, + "max": 9.61018 + } + }, + "gf128_q256": { + "forward_ms": { + "median": 17.3493, + "min": 17.3009, + "max": 17.4188 + }, + "transpose_ms": { + "median": 16.8477, + "min": 16.8345, + "max": 16.9082 + } + }, + "gf128_rs": { + "forward_ms": { + "median": 30.9894, + "min": 30.72, + "max": 31.0434 + }, + "transpose_ms": { + "median": 28.0239, + "min": 27.9369, + "max": 28.0338 + } + } + } +} \ No newline at end of file