From 4f59b969dc6106e3bc49e89c4e327c3729ace5ac Mon Sep 17 00:00:00 2001 From: Peter Rindal Date: Wed, 18 Nov 2026 19:15:27 -0800 Subject: [PATCH 1/8] Use Turbo SPIN for Silent OT Silent OT's SPIN profile is now Turbo SPIN (spin::Parameters::PacketRs8T64), pinned to spin_codes main 584a7fb6 (SPIN 0.3). Under uniform setup its minimum distance exceeds N/10 at K=2^14, 2^16, ..., 2^26 (Lean-certified). Requests up to 2^14 use K=2^14; larger requests round up to a multiple of 128. Stationary noise keeps the banked heuristic refresh, now over a Turbo bank. Turbo has no generic-element transpose. Separate choice bytes therefore travel in the low byte of a block through the native transpose (exact: the binary map acts on each bit lane independently); packed choice bits are unchanged. SpinCode rejects non-128-bit element types. Tests: Spin_Integration_Test (native GF2/GF128 agreement, lifted choice bytes in both noise modes, generic-type rejection, sizes) and the OtExt_Silent tests pass on Peach; -spinOtBench -check passes for regular and stationary noise. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- cmake/Config.cmake.in | 2 +- cmake/libOTeDepHelper.cmake | 2 +- libOTe/Tools/Spin/README.md | 37 ++++++++++++++++++------------------ libOTe/Tools/Spin/SpinOt.cpp | 35 ++++++++++++++++++++-------------- libOTe/Tools/Spin/SpinOt.h | 7 ++++++- thirdparty/getSpin.cmake | 2 +- 7 files changed, 49 insertions(+), 38 deletions(-) diff --git a/README.md b/README.md index 0c66c24d..988f2561 100644 --- a/README.md +++ b/README.md @@ -135,7 +135,7 @@ Dependencies can be managed by cmake/build.py or installed via an external tool. **[SPIN](https://github.com/ladnir/spin_codes) (Silent OT encoder):** -`ENABLE_SPIN` defaults on with Silent OT or Silent VOLE. Install SPIN 0.2 or +`ENABLE_SPIN` defaults on with Silent OT or Silent VOLE. Install SPIN 0.3 or use `FETCH_SPIN=ON` / `FETCH_AUTO`. Requires CMake 3.20+ and x86-64 with AVX2; set `ENABLE_SPIN=OFF` to omit it. See the [usage guide](libOTe/Tools/Spin/README.md). diff --git a/cmake/Config.cmake.in b/cmake/Config.cmake.in index c4d49709..a5b1cc77 100644 --- a/cmake/Config.cmake.in +++ b/cmake/Config.cmake.in @@ -9,7 +9,7 @@ include("${CMAKE_CURRENT_LIST_DIR}/buildOptions.cmake") find_package(cryptoTools REQUIRED HINTS "${CMAKE_CURRENT_LIST_DIR}/.." ${CMAKE_CURRENT_LIST_DIR}) if(@ENABLE_SPIN@) include(CMakeFindDependencyMacro) - find_dependency(spin 0.2 CONFIG) + find_dependency(spin 0.3 CONFIG) endif() diff --git a/cmake/libOTeDepHelper.cmake b/cmake/libOTeDepHelper.cmake index 88701c8a..9317b157 100644 --- a/cmake/libOTeDepHelper.cmake +++ b/cmake/libOTeDepHelper.cmake @@ -146,7 +146,7 @@ macro(FIND_SPIN) else() unset(SPIN_DP) endif() - find_package(spin 0.2 CONFIG ${SPIN_DP} ${ARGN}) + find_package(spin 0.3 CONFIG ${SPIN_DP} ${ARGN}) endmacro() if(ENABLE_SPIN AND NOT TARGET spin::spin) diff --git a/libOTe/Tools/Spin/README.md b/libOTe/Tools/Spin/README.md index 7dda239f..6115af2e 100644 --- a/libOTe/Tools/Spin/README.md +++ b/libOTe/Tools/Spin/README.md @@ -7,14 +7,14 @@ sender.configure(requested, 2, 1, security, noise, osuCrypto::MultType::Spin); receiver.configure(requested, 2, 1, security, noise, osuCrypto::MultType::Spin); ``` -libOTe selects the code parameters and rounds the code size up internally. -Positive requests below 8192 use that minimum size; only the requested outputs -are returned. Zero requests are rejected. The default `MultType` is unchanged. +libOTe uses Turbo SPIN (`spin::Parameters::PacketRs8T64`) and rounds the code +size up to a multiple of 128. Positive requests below 16384 use that size, the +smallest certified length; only the requested outputs are returned. Zero requests are rejected. The default `MultType` is unchanged. Enabling the SPIN dependency does not add a Silent VOLE profile. ## Dependency -SPIN 0.2 requires CMake 3.20+ and x86-64 with AVX2. `ENABLE_SPIN` defaults on +SPIN 0.3 requires CMake 3.20+ and x86-64 with AVX2. `ENABLE_SPIN` defaults on with Silent OT or Silent VOLE; explicit `ENABLE_SPIN=OFF` is respected. Use an installed package through `CMAKE_PREFIX_PATH`, or let `FETCH_SPIN=ON` or `FETCH_AUTO=ON` fetch it. For development, `LIBOTE_SPIN_SOURCE=/path/to/spin` @@ -45,8 +45,9 @@ allocations. Preparation does not cover every protocol allocation. - Regular noise reuses the full precomputed code. Changing `mCodeSeed` rebuilds the map at the next compression, retaining compatible scratch. - Stationary noise selects banked heuristic setup and advances `mCodeSeed` - after each compression. Refresh changes small routing parameters and IMT masks; - it retains the bank and scratch without constructing a full route each batch. + after each compression. Refresh reorders the bank's routing regions and inner + updates and draws fresh outer scalars; it retains the bank and scratch without + constructing a full route each batch. - Both parties must start with matching seeds and options. Block and separate-choice encoding use the same map within a batch. - `clear()` deallocates the code, scratch, and protocol buffers. Reconfiguration @@ -54,10 +55,12 @@ allocations. Preparation does not cover every protocol allocation. methods can clear state; repeated in-place calls retain compatible preparation. Banked refresh is a heuristic permutation family outside SPIN's uniform-setup -distance certificates. The noise configurator uses a linear-attack tuning value -of 0.25, matching BAA; this is not a claim of 25% minimum distance. Uncertified -natural code lengths are allowed. See the [SPIN library](https://github.com/ladnir/spin_codes) -for construction and certificate details. +distance certificates. Under uniform setup, Turbo SPIN's minimum distance exceeds +N/10 at K=2^14, 2^16, ..., 2^26 (Lean-certified); other natural lengths are allowed +without a size-specific certificate. The noise configurator uses a linear-attack +tuning value of 0.25, matching BAA; this is not a claim of 25% minimum distance. +See the [SPIN library](https://github.com/ladnir/spin_codes) for construction and +certificate details. ## Generic coefficients @@ -65,7 +68,7 @@ for construction and certificate details. ```cpp osuCrypto::SpinCode code({.message_size=65536, - .parameters=spin::Parameters::T64S12R2, + .parameters=spin::Parameters::PacketRs8T64, .route_seed=17, .inner_seed=29}); auto workspace = code.make_workspace(); code.transpose_inplace(buffer, workspace); @@ -74,14 +77,10 @@ code.transpose_inplace(buffer, workspace); The buffer must contain exactly 2K elements; its first K elements receive the result and its suffix remains unchanged. Use one workspace per simultaneous call. `block` with `CoeffCtxGF2` or `CoeffCtxGF128` uses the optimized kernel. -Other type/context combinations use the generic circuit and `ctx.plus`. -For custom contexts, use `make_workspace(ctx)` and -`transpose_inplace(buffer, workspace)`. The context supplies -`characteristicTwo()`, `make()`, and `plus(result, lhs, rhs)`. -Values must be contiguous, default-constructible, and copyable; use bytes rather -than `bool` or proxy containers. No XOR operator is required. Prime fields are -unsupported. Value construction, copying, and addition must not allocate if -allocation-free encoding is required. +Turbo SPIN transposes only these 128-bit elements: `make_workspace` rejects other +types and contexts with `std::invalid_argument`. The map acts on each bit lane +independently, so narrower values can travel in the low bits of a `block`; +Silent OT's separate choice bytes use this path. Prime fields are unsupported. ## Profiling diff --git a/libOTe/Tools/Spin/SpinOt.cpp b/libOTe/Tools/Spin/SpinOt.cpp index a69ab812..a1723bbd 100644 --- a/libOTe/Tools/Spin/SpinOt.cpp +++ b/libOTe/Tools/Spin/SpinOt.cpp @@ -5,18 +5,20 @@ namespace osuCrypto { namespace detail { spin::CodeSpec spinProfile(u64 requested,block seed) { - // Small requests share the smallest natural code; truncate only after encoding. - constexpr u64 minimumK=8192; - // Separate distance certificates at 10%: K16, margin >=49.32 bits. - // K18/20/22/24: T128S19, margins >=50.18/50.06/48.39/46.45 bits. - // Other natural lengths are allowed without a size-specific certificate. - const auto parameters=requested<=(u64(1)<<16)? - spin::Parameters::T64S12R2:spin::Parameters::T128S19; + // Turbo SPIN. Under uniform setup its minimum distance exceeds N/10 at + // K=2^14,2^16,...,2^26 (Lean-certified; setup-failure margins 64.25 to + // 52.32 bits). Small requests share the smallest certified code; others + // round up to the next natural size (a multiple of 128), which has no + // size-specific certificate. Truncate only after encoding. + constexpr u64 minimumK=u64(1)<<14; + constexpr auto parameters=spin::Parameters::PacketRs8T64; const u64 alignment=spin::message_alignment(parameters); - const u64 maxK=((u64(1)<<31)-1)/alignment*alignment; - if(!requested || requested>maxK) - throw std::invalid_argument("SPIN OT request exceeds the routing representation"); - return {roundUpTo(std::max(requested,minimumK),alignment),parameters,seed.get(0),seed.get(1)}; + if(!requested || requested>(u64(1)<<40)) + throw std::invalid_argument("SPIN OT request exceeds the largest Turbo code"); + const u64 k=roundUpTo(std::max(requested,minimumK),alignment); + if(!spin::valid_message_size(parameters,k)) + throw std::invalid_argument("SPIN OT request exceeds the largest Turbo code"); + return {k,parameters,seed.get(0),seed.get(1)}; } } @@ -25,7 +27,7 @@ SdConfig SpinConfigure(u64 secParam,u64 requested,SdNoiseDistribution noise) { if(secParam>1024 || (noise!=SdNoiseDistribution::Regular && noise!=SdNoiseDistribution::Stationary)) throw std::invalid_argument("Invalid SPIN noise configuration"); // Same effective linear-attack tuning value as BAA. This is not a claim - // of 25% minimum distance; the 10% certificates are separate evidence. + // of 25% minimum distance; the N/10 certificates are separate evidence. constexpr double linearAttackTuning=0.25; const double fullEffectiveWeight=std::floor(linearAttackTuning*double(n)); const double multiplier=noise==SdNoiseDistribution::Regular?2:1; @@ -52,7 +54,7 @@ static spin::SetupOptions spinSetup(SdNoiseDistribution noise) { } SpinOtState::SpinOtState(u64 requested,block codeSeed,bool receiver,SdNoiseDistribution noise) :seed(codeSeed),code(detail::spinProfile(requested,codeSeed),{},spinSetup(noise)),blocks(code.make_workspace()) { - if(receiver) choices.emplace(code.make_workspace()); + if(receiver) choices.emplace(code.make_workspace()); } void prepareSpin(std::unique_ptr& state,u64 requested,block seed,bool receiver,SdNoiseDistribution noise) { const auto spec=detail::spinProfile(requested,seed); @@ -66,7 +68,12 @@ void prepareSpin(std::unique_ptr& state,u64 requested,block seed,bo void SpinOtState::transpose(span x) {code.transpose_inplace(x,blocks);} void SpinOtState::transpose(span x) { if(!choices) throw std::logic_error("SPIN choice workspace was not prepared"); - code.transpose_inplace(x,*choices); + // Reuses its capacity across batches; allocates only on first use or growth. + choiceLift.resize(x.size()); + for(u64 i=0;i(choiceLift,*choices); + // In-place contract: the first K entries receive the result, the rest are unchanged. + for(u64 i=0,k=code.messageSize();i(0); } } #endif diff --git a/libOTe/Tools/Spin/SpinOt.h b/libOTe/Tools/Spin/SpinOt.h index 5718f3ea..73846cf6 100644 --- a/libOTe/Tools/Spin/SpinOt.h +++ b/libOTe/Tools/Spin/SpinOt.h @@ -1,6 +1,7 @@ #pragma once #include "libOTe/Tools/Spin/SpinCode.h" #include "libOTe/TwoChooseOne/ConfigureCode.h" +#include "cryptoTools/Common/Aligned.h" #ifdef ENABLE_SPIN #include #include @@ -18,7 +19,11 @@ struct SpinOtState { block seed; SpinCode code; SpinCode::Workspace blocks; - std::optional> choices; + // Separate choice bytes use the native 128-bit transpose: the binary map acts + // on each bit lane independently, so each byte travels in the low byte of a + // block. Turbo SPIN has no generic-element transpose. + std::optional> choices; + AlignedUnVector choiceLift; SpinOtState(u64 requested,block codeSeed,bool receiver, SdNoiseDistribution noise=SdNoiseDistribution::Regular); void transpose(span x); diff --git a/thirdparty/getSpin.cmake b/thirdparty/getSpin.cmake index 325d2844..96192ada 100644 --- a/thirdparty/getSpin.cmake +++ b/thirdparty/getSpin.cmake @@ -1,5 +1,5 @@ set(GIT_REPOSITORY https://github.com/ladnir/spin_codes.git) -set(GIT_TAG "f2010e03d2dbe5003e90c89ba346c743793536a6") +set(GIT_TAG "584a7fb654e824bf296aeb92ef7c6edd92e63fc2") set(CLONE_DIR "${OC_THIRDPARTY_CLONE_DIR}/spin") set(BUILD_DIR "${CLONE_DIR}/out/build/${OC_CONFIG}") set(LOG_FILE "${CMAKE_CURRENT_LIST_DIR}/log-spin.txt") From 27b9f21bebcf9306cf7a2f96029427699d9935a8 Mon Sep 17 00:00:00 2001 From: Peter Rindal Date: Wed, 18 Nov 2026 20:19:07 -0800 Subject: [PATCH 2/8] SPIN Silent OT: do not tie the code size to certified lengths Turbo runs at every natural size (a positive multiple of 128). Requests round up to the next one, with the previous 8192 floor so the noise configuration has room for its partitions; the floor is not related to the distance certificates. Co-Authored-By: Claude Opus 5.5 --- libOTe/Tools/Spin/README.md | 7 ++++--- libOTe/Tools/Spin/SpinOt.cpp | 11 +++++------ 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/libOTe/Tools/Spin/README.md b/libOTe/Tools/Spin/README.md index 6115af2e..5f2b5672 100644 --- a/libOTe/Tools/Spin/README.md +++ b/libOTe/Tools/Spin/README.md @@ -7,9 +7,10 @@ sender.configure(requested, 2, 1, security, noise, osuCrypto::MultType::Spin); receiver.configure(requested, 2, 1, security, noise, osuCrypto::MultType::Spin); ``` -libOTe uses Turbo SPIN (`spin::Parameters::PacketRs8T64`) and rounds the code -size up to a multiple of 128. Positive requests below 16384 use that size, the -smallest certified length; only the requested outputs are returned. Zero requests are rejected. The default `MultType` is unchanged. +libOTe uses Turbo SPIN (`spin::Parameters::PacketRs8T64`) at every natural +size: the code size rounds up to the next multiple of 128. Positive requests +below 8192 use 8192, which leaves the noise configuration room for its +partitions; only the requested outputs are returned. Zero requests are rejected. The default `MultType` is unchanged. Enabling the SPIN dependency does not add a Silent VOLE profile. ## Dependency diff --git a/libOTe/Tools/Spin/SpinOt.cpp b/libOTe/Tools/Spin/SpinOt.cpp index a1723bbd..ee2e8789 100644 --- a/libOTe/Tools/Spin/SpinOt.cpp +++ b/libOTe/Tools/Spin/SpinOt.cpp @@ -5,12 +5,11 @@ namespace osuCrypto { namespace detail { spin::CodeSpec spinProfile(u64 requested,block seed) { - // Turbo SPIN. Under uniform setup its minimum distance exceeds N/10 at - // K=2^14,2^16,...,2^26 (Lean-certified; setup-failure margins 64.25 to - // 52.32 bits). Small requests share the smallest certified code; others - // round up to the next natural size (a multiple of 128), which has no - // size-specific certificate. Truncate only after encoding. - constexpr u64 minimumK=u64(1)<<14; + // Turbo SPIN at every natural size (a positive multiple of 128); requests + // round up to the next one. Small requests share K=8192 so the noise + // configuration has room for its partitions; this floor is not tied to + // any distance certificate. Truncate only after encoding. + constexpr u64 minimumK=8192; constexpr auto parameters=spin::Parameters::PacketRs8T64; const u64 alignment=spin::message_alignment(parameters); if(!requested || requested>(u64(1)<<40)) From 0271cf15e3eba709caab4420e7e83f7ccae6bce6 Mon Sep 17 00:00:00 2001 From: Peter Rindal Date: Fri, 20 Nov 2026 13:43:01 -0800 Subject: [PATCH 3/8] SPIN 0.4: require the Turbo-only release SPIN 0.4 drops the generic coefficient transpose, so SpinCode accepts only native 128-bit block records and rejects other element types. The package lookups and docs ask for 0.4. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- cmake/Config.cmake.in | 2 +- cmake/libOTeDepHelper.cmake | 2 +- libOTe/Tools/Spin/README.md | 2 +- libOTe/Tools/Spin/SpinCode.h | 40 +++++++----------------------------- 5 files changed, 11 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index 988f2561..a5b06254 100644 --- a/README.md +++ b/README.md @@ -135,7 +135,7 @@ Dependencies can be managed by cmake/build.py or installed via an external tool. **[SPIN](https://github.com/ladnir/spin_codes) (Silent OT encoder):** -`ENABLE_SPIN` defaults on with Silent OT or Silent VOLE. Install SPIN 0.3 or +`ENABLE_SPIN` defaults on with Silent OT or Silent VOLE. Install SPIN 0.4 or use `FETCH_SPIN=ON` / `FETCH_AUTO`. Requires CMake 3.20+ and x86-64 with AVX2; set `ENABLE_SPIN=OFF` to omit it. See the [usage guide](libOTe/Tools/Spin/README.md). diff --git a/cmake/Config.cmake.in b/cmake/Config.cmake.in index a5b1cc77..ec9b689f 100644 --- a/cmake/Config.cmake.in +++ b/cmake/Config.cmake.in @@ -9,7 +9,7 @@ include("${CMAKE_CURRENT_LIST_DIR}/buildOptions.cmake") find_package(cryptoTools REQUIRED HINTS "${CMAKE_CURRENT_LIST_DIR}/.." ${CMAKE_CURRENT_LIST_DIR}) if(@ENABLE_SPIN@) include(CMakeFindDependencyMacro) - find_dependency(spin 0.3 CONFIG) + find_dependency(spin 0.4 CONFIG) endif() diff --git a/cmake/libOTeDepHelper.cmake b/cmake/libOTeDepHelper.cmake index 9317b157..0783b6cc 100644 --- a/cmake/libOTeDepHelper.cmake +++ b/cmake/libOTeDepHelper.cmake @@ -146,7 +146,7 @@ macro(FIND_SPIN) else() unset(SPIN_DP) endif() - find_package(spin 0.3 CONFIG ${SPIN_DP} ${ARGN}) + find_package(spin 0.4 CONFIG ${SPIN_DP} ${ARGN}) endmacro() if(ENABLE_SPIN AND NOT TARGET spin::spin) diff --git a/libOTe/Tools/Spin/README.md b/libOTe/Tools/Spin/README.md index 5f2b5672..a83531dd 100644 --- a/libOTe/Tools/Spin/README.md +++ b/libOTe/Tools/Spin/README.md @@ -15,7 +15,7 @@ Enabling the SPIN dependency does not add a Silent VOLE profile. ## Dependency -SPIN 0.3 requires CMake 3.20+ and x86-64 with AVX2. `ENABLE_SPIN` defaults on +SPIN 0.4 (Turbo only) requires CMake 3.20+ and a 64-bit CPU; libOTe uses it on x86-64 with AVX2. `ENABLE_SPIN` defaults on with Silent OT or Silent VOLE; explicit `ENABLE_SPIN=OFF` is respected. Use an installed package through `CMAKE_PREFIX_PATH`, or let `FETCH_SPIN=ON` or `FETCH_AUTO=ON` fetch it. For development, `LIBOTE_SPIN_SOURCE=/path/to/spin` diff --git a/libOTe/Tools/Spin/SpinCode.h b/libOTe/Tools/Spin/SpinCode.h index eaa83e89..19eb7442 100644 --- a/libOTe/Tools/Spin/SpinCode.h +++ b/libOTe/Tools/Spin/SpinCode.h @@ -3,7 +3,6 @@ #ifdef ENABLE_SPIN #include "libOTe/Tools/CoeffCtx.h" #include -#include #include #include @@ -23,47 +22,22 @@ class SpinCode { auto descriptor() const {return mCode.descriptor();} const spin::PreparedEncoder& code() const {return mCode;} - template class GenericWorkspace { - friend class SpinCode; - Ctx ctx; - spin::GenericTranspose plan; - spin::GenericTranspose::Workspace scratch; - GenericWorkspace(const spin::PreparedEncoder& code,Ctx c) - :ctx(std::move(c)),plan(code.generic_transpose()),scratch(plan.template make_workspace()) {} - public: - GenericWorkspace(GenericWorkspace&& other) - :ctx(std::move(other.ctx)), - plan(other.plan),scratch(std::move(other.scratch)) {} - GenericWorkspace& operator=(GenericWorkspace&& other) { - if(this!=&other) { - ctx=std::move(other.ctx); - plan=other.plan;scratch=std::move(other.scratch); - } - return *this; - } - GenericWorkspace(const GenericWorkspace&)=delete; - }; + // Turbo SPIN transposes 128-bit records only. Other element types and + // coefficient contexts are rejected at runtime (std::invalid_argument); + // narrower binary values can travel in the low bits of a block. template - using Workspace = std::conditional_t,spin::PreparedEncoder::Workspace,GenericWorkspace>; + using Workspace = spin::PreparedEncoder::Workspace; template Workspace make_workspace(Ctx ctx={}) const { if(!ctx.template characteristicTwo()) throw std::invalid_argument("SPIN requires characteristic-two addition"); if constexpr(native) return mCode.make_workspace(); - else return GenericWorkspace(mCode,std::move(ctx)); + else throw std::invalid_argument("SPIN transposes 128-bit block records only"); } template void transpose_inplace(span buffer,Workspace& w) const { - if constexpr(native) - mCode.transpose_inplace(std::span(buffer.data(),buffer.size()),w); - else { - if(!mCode.owns(w.plan)) - throw std::invalid_argument("SPIN coefficient workspace belongs to another map"); - auto plus=[&](const F& a,const F& b) { - auto r=w.ctx.template make(); w.ctx.plus(r,a,b); return r; - }; - w.plan.template transpose_inplace(std::span(buffer.data(),buffer.size()),w.scratch,plus); - } + static_assert(native,"SPIN transposes 128-bit block records only"); + mCode.transpose_inplace(std::span(buffer.data(),buffer.size()),w); } }; } From ead4dc79a8fb6809dbd36e193990e281fc688383 Mon Sep 17 00:00:00 2001 From: Peter Rindal Date: Fri, 20 Nov 2026 13:43:15 -0800 Subject: [PATCH 4/8] Fetch SPIN 0.4 (permute_conv 0f0abd80ca239f377c22a53a95930f534e55aa86) Co-Authored-By: Claude Opus 5.5 --- thirdparty/getSpin.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/thirdparty/getSpin.cmake b/thirdparty/getSpin.cmake index 96192ada..a1f5bb4d 100644 --- a/thirdparty/getSpin.cmake +++ b/thirdparty/getSpin.cmake @@ -1,5 +1,5 @@ set(GIT_REPOSITORY https://github.com/ladnir/spin_codes.git) -set(GIT_TAG "584a7fb654e824bf296aeb92ef7c6edd92e63fc2") +set(GIT_TAG "0f0abd80ca239f377c22a53a95930f534e55aa86") set(CLONE_DIR "${OC_THIRDPARTY_CLONE_DIR}/spin") set(BUILD_DIR "${CLONE_DIR}/out/build/${OC_CONFIG}") set(LOG_FILE "${CMAKE_CURRENT_LIST_DIR}/log-spin.txt") From d023563374bf3cf38210bf6c70f527851e0d7c9b Mon Sep 17 00:00:00 2001 From: Peter Rindal Date: Fri, 20 Nov 2026 14:19:13 -0800 Subject: [PATCH 5/8] Silent OT: direct VAES hash and faster GGM expansion (same output) - Sender hash: build each (r, r^Delta) pair in one YMM register and store the hashed pair straight to the output; no stack batch or copy. - RegularPprf: VAES helpers for internal levels (YMM, sums in registers) and the leaf level (both keys interleaved, 8 AES chains in flight), used by sender and receiver. Non-VAES builds keep the scalar loops. - spinOtBench -check prints a fixed-seed output digest so builds can be compared bit for bit. Digests match the previous code at logN 13/18/20, regular and stationary. K=2^18 sender on a Ryzen 9 7950X core: 1.651 -> 1.373 ms with -nt, 2.152 -> 1.483 ms with cached stores. Co-Authored-By: Claude Opus 5.5 --- frontend/SpinOtBench.cpp | 9 +- libOTe/Tools/Pprf/RegularPprf.h | 164 ++++++++++++++++++ .../TwoChooseOne/Silent/SilentOtExtSender.cpp | 78 +++++++-- 3 files changed, 232 insertions(+), 19 deletions(-) diff --git a/frontend/SpinOtBench.cpp b/frontend/SpinOtBench.cpp index 1095dc13..6dbdd8cc 100644 --- a/frontend/SpinOtBench.cpp +++ b/frontend/SpinOtBench.cpp @@ -9,6 +9,7 @@ #include "coproto/Socket/BufferingSocket.h" #include "macoro/when_all.h" #include "macoro/sync_wait.h" +#include "cryptoTools/Crypto/RandomOracle.h" #include #include #include @@ -94,7 +95,13 @@ int spinOtBenchmark(CLP& cmd) {try { (regular?spin::SetupMode::Full:spin::SetupMode::BankedHeuristic)); s.hash(sent,ChoiceBitPacking::True,streaming);r.hash(choices,received,ChoiceBitPacking::True); for(u64 i=0;imShare.data():nullptr;const auto* rs=rg?rg->mShare.data():nullptr; const auto* sw=s.mSpin.get();const auto* rw=r.mSpin.get(); const auto fixedDescriptor=s.mSpin->code.descriptor(); diff --git a/libOTe/Tools/Pprf/RegularPprf.h b/libOTe/Tools/Pprf/RegularPprf.h index b36a97de..ce104b9b 100644 --- a/libOTe/Tools/Pprf/RegularPprf.h +++ b/libOTe/Tools/Pprf/RegularPprf.h @@ -38,6 +38,120 @@ namespace osuCrypto extern const std::array gGgmAes; +#ifdef OC_ENABLE_VAES + namespace pprfVaes + { + // AES-128 round keys broadcast to both YMM lanes. + struct alignas(32) YmmKey + { + __m256i k[11]; + explicit YmmKey(const AES& aes) + { + for (u64 r = 0; r < 11; ++r) + k[r] = _mm256_broadcastsi128_si256(aes.mRoundKey[r].mData); + } + }; + +#define OC_PPRF_LANES(OP) OP(0); OP(1); OP(2); OP(3) +#define OC_PPRF_LD(p, j) _mm256_loadu_si256(reinterpret_cast(p) + (j)) +#define OC_PPRF_ST(p, j, v) _mm256_storeu_si256(reinterpret_cast<__m256i*>(p) + (j), v) + + // One internal GGM level, 8 lanes per parent (4 YMM): parent p gives + // children 16p..16p+7 (left) and 16p+8..16p+15 (right). + // Same values as the scalar loop: + // a = AES(x), child0 = AESENC(a, x) = R(a) ^ x, child1 = a + x (64-bit lanes). + // The level sums stay in registers; sum0/sum1 (8 blocks each) are + // read on entry and written on exit. + OC_FORCEINLINE void internalLevel(const YmmKey& key, + const block* parents, block* children, u64 width, block* sum0, block* sum1) + { +#define OC_PPRF_SUM_IN(j) __m256i s0##j = OC_PPRF_LD(sum0, j), s1##j = OC_PPRF_LD(sum1, j) + OC_PPRF_LANES(OC_PPRF_SUM_IN); +#undef OC_PPRF_SUM_IN + for (u64 p = 0; p < width; ++p) + { + const block* in = parents + 8 * p; + block* ch = children + 16 * p; +#define OC_PPRF_IN(j) const __m256i x##j = OC_PPRF_LD(in, j); __m256i a##j = _mm256_xor_si256(x##j, key.k[0]) + OC_PPRF_LANES(OC_PPRF_IN); +#undef OC_PPRF_IN + for (u64 r = 1; r < 10; ++r) + { +#define OC_PPRF_RND(j) a##j = _mm256_aesenc_epi128(a##j, key.k[r]) + OC_PPRF_LANES(OC_PPRF_RND); +#undef OC_PPRF_RND + } +#define OC_PPRF_OUT(j) \ + a##j = _mm256_aesenclast_epi128(a##j, key.k[10]); \ + { \ + const __m256i c0 = _mm256_aesenc_epi128(a##j, x##j); \ + const __m256i c1 = _mm256_add_epi64(a##j, x##j); \ + OC_PPRF_ST(ch, j, c0); \ + OC_PPRF_ST(ch + 8, j, c1); \ + s0##j = _mm256_xor_si256(s0##j, c0); \ + s1##j = _mm256_xor_si256(s1##j, c1); \ + } + OC_PPRF_LANES(OC_PPRF_OUT); +#undef OC_PPRF_OUT + } +#define OC_PPRF_SUM_OUT(j) OC_PPRF_ST(sum0, j, s0##j); OC_PPRF_ST(sum1, j, s1##j) + OC_PPRF_LANES(OC_PPRF_SUM_OUT); +#undef OC_PPRF_SUM_OUT + } + + // The leaf GGM level, 8 lanes per parent: out[16p + 8*keep + t] = + // AES_keep(x) ^ x under gGgmAes[keep], the same layout and values as + // gGgmAes[keep].hashBlocks<8>. Both keys run interleaved so 8 YMM AES + // chains are in flight. sum0/sum1 (8 blocks each) are XOR-accumulated. + OC_FORCEINLINE void leafLevel(const YmmKey& k0, const YmmKey& k1, + const block* parents, block* out, u64 width, block* sum0, block* sum1) + { +#define OC_PPRF_SUM_IN(j) __m256i s0##j = OC_PPRF_LD(sum0, j), s1##j = OC_PPRF_LD(sum1, j) + OC_PPRF_LANES(OC_PPRF_SUM_IN); +#undef OC_PPRF_SUM_IN + for (u64 p = 0; p < width; ++p) + { + const block* in = parents + 8 * p; + block* o = out + 16 * p; +#define OC_PPRF_IN(j) \ + const __m256i x##j = OC_PPRF_LD(in, j); \ + __m256i a##j = _mm256_xor_si256(x##j, k0.k[0]); \ + __m256i b##j = _mm256_xor_si256(x##j, k1.k[0]) + OC_PPRF_LANES(OC_PPRF_IN); +#undef OC_PPRF_IN + for (u64 r = 1; r < 10; ++r) + { +#define OC_PPRF_RND(j) a##j = _mm256_aesenc_epi128(a##j, k0.k[r]); b##j = _mm256_aesenc_epi128(b##j, k1.k[r]) + OC_PPRF_LANES(OC_PPRF_RND); +#undef OC_PPRF_RND + } +#define OC_PPRF_OUT(j) \ + a##j = _mm256_xor_si256(_mm256_aesenclast_epi128(a##j, k0.k[10]), x##j); \ + b##j = _mm256_xor_si256(_mm256_aesenclast_epi128(b##j, k1.k[10]), x##j); \ + OC_PPRF_ST(o, j, a##j); \ + OC_PPRF_ST(o + 8, j, b##j); \ + s0##j = _mm256_xor_si256(s0##j, a##j); \ + s1##j = _mm256_xor_si256(s1##j, b##j) + OC_PPRF_LANES(OC_PPRF_OUT); +#undef OC_PPRF_OUT + } +#define OC_PPRF_SUM_OUT(j) OC_PPRF_ST(sum0, j, s0##j); OC_PPRF_ST(sum1, j, s1##j) + OC_PPRF_LANES(OC_PPRF_SUM_OUT); +#undef OC_PPRF_SUM_OUT + } +#undef OC_PPRF_ST +#undef OC_PPRF_LD +#undef OC_PPRF_LANES + + // The kernels keep one sum per lane (the 8 subtrees of one tree); the + // tree's level sum is their XOR. + OC_FORCEINLINE block fold8(const block* s) + { + return ((s[0] ^ s[1]) ^ (s[2] ^ s[3])) ^ ((s[4] ^ s[5]) ^ (s[6] ^ s[7])); + } + } +#endif + namespace pprf { // Expand eight GGM parents while keeping the raw AES outputs in @@ -443,6 +557,9 @@ namespace osuCrypto REGULAR_PPRF_SIMD8(lane, { levels[0][0][lane] = current[lane]; }); +#ifdef OC_ENABLE_VAES + const pprfVaes::YmmKey internalKey(mAesFixedKey); +#endif for (u64 localDepth = 0; localDepth + 1 < levels.size(); ++localDepth) { @@ -451,6 +568,15 @@ namespace osuCrypto auto parents = levels[localDepth]; auto children = levels[localDepth + 1]; const auto width = u64{ 1 } << localDepth; +#ifdef OC_ENABLE_VAES + { + alignas(32) std::array laneSums0{}, laneSums1{}; + pprfVaes::internalLevel(internalKey, parents.data()->data(), + children.data()->data(), width, laneSums0.data(), laneSums1.data()); + leftAccumulator = leftAccumulator ^ pprfVaes::fold8(laneSums0.data()); + rightAccumulator = rightAccumulator ^ pprfVaes::fold8(laneSums1.data()); + } +#else for (u64 parentIdx = 0; parentIdx < width; ++parentIdx) { auto& parent = parents[parentIdx]; @@ -460,6 +586,7 @@ namespace osuCrypto mAesFixedKey, parent.data(), left.data(), right.data(), leftAccumulator, rightAccumulator); } +#endif const auto globalDepth = 3 + localDepth; (*encSumIter)[0] = leftAccumulator ^ @@ -546,6 +673,17 @@ namespace osuCrypto block leftAccumulator = ZeroBlock; block rightAccumulator = ZeroBlock; +#ifdef OC_ENABLE_VAES + { + alignas(32) std::array laneSums0{}, laneSums1{}; + pprfVaes::leafLevel(pprfVaes::YmmKey(gGgmAes[0]), pprfVaes::YmmKey(gGgmAes[1]), + parents.data()->data(), dest, parents.size(), + laneSums0.data(), laneSums1.data()); + nativeLeaf += 16 * parents.size(); + leftAccumulator = leftAccumulator ^ pprfVaes::fold8(laneSums0.data()); + rightAccumulator = rightAccumulator ^ pprfVaes::fold8(laneSums1.data()); + } +#else for (u64 parentIdx = 0; parentIdx < parents.size(); ++parentIdx) { pprf::hashGgmLeaves8(gGgmAes[0], @@ -557,6 +695,7 @@ namespace osuCrypto rightAccumulator); nativeLeaf += 8; } +#endif leafSums[0] = leftAccumulator; leafSums[1] = rightAccumulator; } @@ -974,6 +1113,9 @@ namespace osuCrypto REGULAR_PPRF_SIMD8(lane, { levels[0][0][lane] = current[lane]; }); +#ifdef OC_ENABLE_VAES + const pprfVaes::YmmKey internalKey(mAesFixedKey); +#endif for (u64 localDepth = 0; localDepth + 1 < levels.size(); ++localDepth) { @@ -982,6 +1124,15 @@ namespace osuCrypto auto parents = levels[localDepth]; auto children = levels[localDepth + 1]; const auto width = u64{ 1 } << localDepth; +#ifdef OC_ENABLE_VAES + { + alignas(32) std::array laneSums0{}, laneSums1{}; + pprfVaes::internalLevel(internalKey, parents.data()->data(), + children.data()->data(), width, laneSums0.data(), laneSums1.data()); + leftAccumulator = leftAccumulator ^ pprfVaes::fold8(laneSums0.data()); + rightAccumulator = rightAccumulator ^ pprfVaes::fold8(laneSums1.data()); + } +#else for (u64 parentIdx = 0; parentIdx < width; ++parentIdx) { auto& parent = parents[parentIdx]; @@ -991,6 +1142,7 @@ namespace osuCrypto mAesFixedKey, parent.data(), left.data(), right.data(), leftAccumulator, rightAccumulator); } +#endif const auto globalDepth = 3 + localDepth; const auto childDepth = globalDepth + 1; @@ -1098,6 +1250,17 @@ namespace osuCrypto block leftAccumulator = gGgmAes[0].hashBlock(ZeroBlock); block rightAccumulator = gGgmAes[1].hashBlock(ZeroBlock); +#ifdef OC_ENABLE_VAES + { + alignas(32) std::array laneSums0{}, laneSums1{}; + pprfVaes::leafLevel(pprfVaes::YmmKey(gGgmAes[0]), pprfVaes::YmmKey(gGgmAes[1]), + parents.data()->data(), dest, parents.size(), + laneSums0.data(), laneSums1.data()); + nativeLeaf += 16 * parents.size(); + leftAccumulator = leftAccumulator ^ pprfVaes::fold8(laneSums0.data()); + rightAccumulator = rightAccumulator ^ pprfVaes::fold8(laneSums1.data()); + } +#else for (u64 parentIdx = 0; parentIdx < parents.size(); ++parentIdx) { pprf::hashGgmLeaves8(gGgmAes[0], @@ -1109,6 +1272,7 @@ namespace osuCrypto rightAccumulator); nativeLeaf += 8; } +#endif leafSums[0] = leftAccumulator; leafSums[1] = rightAccumulator; } diff --git a/libOTe/TwoChooseOne/Silent/SilentOtExtSender.cpp b/libOTe/TwoChooseOne/Silent/SilentOtExtSender.cpp index 4b322902..423bffe4 100644 --- a/libOTe/TwoChooseOne/Silent/SilentOtExtSender.cpp +++ b/libOTe/TwoChooseOne/Silent/SilentOtExtSender.cpp @@ -396,6 +396,58 @@ namespace osuCrypto } } + namespace + { +#ifdef OC_ENABLE_VAES + // Hashes OTs [0, n8), n8 a multiple of 8: m[i] = (H(r_i & mask), H((r_i ^ d) & mask)) + // with H(x) = AES(x) ^ x. Each (x0, x1) pair is built in one YMM register + // (broadcast r, xor (0 || delta), and the mask) and the hashed pair is + // stored straight to the output, so no stack batch or copy is needed. + // Not a coroutine: the aligned key array stays in an ordinary frame. + template + OC_FORCEINLINE void hashSenderVaes(const AES& aes, const block* r, + std::array* m, u64 n8, block delta) + { + alignas(32) __m256i key[11]; + for (u64 k = 0; k < 11; ++k) + key[k] = _mm256_broadcastsi128_si256(aes.mRoundKey[k].mData); + const __m256i mask = _mm256_set_epi64x(-1, -2, -1, -2); + const __m256i dpair = _mm256_set_m128i(delta.mData, _mm_setzero_si128()); + + for (u64 i = 0; i < n8; i += 8) + { + __m256i x0, x1, x2, x3, x4, x5, x6, x7; + __m256i a0, a1, a2, a3, a4, a5, a6, a7; +#define OC_HASH_LANES(OP) OP(0); OP(1); OP(2); OP(3); OP(4); OP(5); OP(6); OP(7) +#define OC_HASH_LOAD(j) \ + x##j = _mm256_and_si256(_mm256_xor_si256( \ + _mm256_broadcastsi128_si256(_mm_loadu_si128(&r[i + j].mData)), dpair), mask); \ + a##j = _mm256_xor_si256(x##j, key[0]) +#define OC_HASH_ROUND(j) a##j = _mm256_aesenc_epi128(a##j, key[k]) +#define OC_HASH_STORE(j) \ + a##j = _mm256_xor_si256(_mm256_aesenclast_epi128(a##j, key[10]), x##j); \ + if constexpr (streaming && aligned32) \ + _mm256_stream_si256(reinterpret_cast<__m256i*>(&m[i + j]), a##j); \ + else if constexpr (streaming) { \ + _mm_stream_si128(&m[i + j][0].mData, _mm256_castsi256_si128(a##j)); \ + _mm_stream_si128(&m[i + j][1].mData, _mm256_extracti128_si256(a##j, 1)); \ + } else \ + _mm256_storeu_si256(reinterpret_cast<__m256i*>(&m[i + j]), a##j) + OC_HASH_LANES(OC_HASH_LOAD); + for (u64 k = 1; k < 10; ++k) + { + OC_HASH_LANES(OC_HASH_ROUND); + } + OC_HASH_LANES(OC_HASH_STORE); +#undef OC_HASH_STORE +#undef OC_HASH_ROUND +#undef OC_HASH_LOAD +#undef OC_HASH_LANES + } + } +#endif + } + // Hashes the OT messages for security void SilentOtExtSender::hash( span> messages, @@ -416,11 +468,16 @@ namespace osuCrypto auto d = *mDelta & mask; auto n8 = (u64)messages.size() / 8 * 8; - alignas(32) std::array hashBatch; - std::array* m = messages.data(); auto r = mB.data(); +#ifdef OC_ENABLE_VAES + if ((u64)m % 32 == 0) + hashSenderVaes(mAesFixedKey, r, m, n8, *mDelta); + else + hashSenderVaes(mAesFixedKey, r, m, n8, *mDelta); +#else + alignas(32) std::array hashBatch; // Process in blocks of 8 for efficiency for (u64 i = 0; i < n8; i += 8) { @@ -438,22 +495,11 @@ namespace osuCrypto // std::array output objects. for (u64 j = 0; j < 8; ++j) { -#ifdef OC_ENABLE_VAES - // Pack a complete VAES lane pair. Two separate 16-byte stores - // followed by a 32-byte load incur store-forwarding stalls. - auto pair = _mm256_set_m128i((r[j] ^ d).mData, r[j].mData); - std::memcpy(hashBatch.data() + 2 * j, &pair, sizeof(pair)); -#else hashBatch[2 * j] = r[j]; hashBatch[2 * j + 1] = r[j] ^ d; -#endif } -#ifdef OC_ENABLE_VAES - mAesFixedKey.hashBlocks<16>(hashBatch.data(), hashBatch.data()); -#else mAesFixedKey.hashBlocks<8>(hashBatch.data(), hashBatch.data()); mAesFixedKey.hashBlocks<8>(hashBatch.data() + 8, hashBatch.data() + 8); -#endif #ifdef OC_ENABLE_SSE2 if constexpr(streaming) { // The API promises 16-byte, not 32-byte, output alignment. @@ -464,21 +510,17 @@ namespace osuCrypto } else #endif { -#ifdef OC_ENABLE_VAES - // Copy object representations rather than flattening nested arrays. - std::memcpy(m, hashBatch.data(), sizeof(hashBatch)); -#else for (u64 j = 0; j < 8; ++j) { m[j][0] = hashBatch[2 * j]; m[j][1] = hashBatch[2 * j + 1]; } -#endif } m += 8; r += 8; } +#endif #ifdef OC_ENABLE_SSE2 // Finish streaming stores before cached tail stores (which can share From 87ca99e604e6266a22244847af00d37b8613ce33 Mon Sep 17 00:00:00 2001 From: Peter Rindal Date: Fri, 20 Nov 2026 20:36:27 -0800 Subject: [PATCH 6/8] RegularPprf: 512-bit VAES GGM levels (same output) With ENABLE_AVX512 the internal and leaf levels run on ZMM, two parents per step: the same AES work in half the instructions, leaving the scheduler room for the stores, sums and feed-forward. AVX2-only VAES builds keep the 256-bit path. Output digests match at logN 13/18/20, regular and stationary; tests pass. K=2^18 sender expansion 0.560 -> 0.502 ms (Ryzen 9 7950X core). Co-Authored-By: Claude Opus 5.5 --- libOTe/Tools/Pprf/RegularPprf.h | 120 +++++++++++++++++++++++++++++--- 1 file changed, 112 insertions(+), 8 deletions(-) diff --git a/libOTe/Tools/Pprf/RegularPprf.h b/libOTe/Tools/Pprf/RegularPprf.h index ce104b9b..24da969f 100644 --- a/libOTe/Tools/Pprf/RegularPprf.h +++ b/libOTe/Tools/Pprf/RegularPprf.h @@ -143,6 +143,110 @@ namespace osuCrypto #undef OC_PPRF_LD #undef OC_PPRF_LANES +#ifdef ENABLE_AVX512 + // 512-bit versions: same values and layout, half the instructions. + // A parent (8 lanes) is 2 ZMM; two parents per step keep 4 (internal) + // or 8 (leaf) AES chains in flight, enough to fill both AES units. + struct alignas(64) ZmmKey + { + __m512i k[11]; + explicit ZmmKey(const AES& aes) + { + for (u64 r = 0; r < 11; ++r) + k[r] = _mm512_broadcast_i32x4(aes.mRoundKey[r].mData); + } + }; + + template + OC_FORCEINLINE void internalStep(const ZmmKey& key, const block* in, block* ch, + __m512i (&s0)[2], __m512i (&s1)[2]) + { + constexpr u64 C = 2 * NP; + __m512i x[C], a[C]; + for (u64 c = 0; c < C; ++c) + { + x[c] = _mm512_loadu_si512(in + 4 * c); + a[c] = _mm512_xor_si512(x[c], key.k[0]); + } + for (u64 r = 1; r < 10; ++r) + for (u64 c = 0; c < C; ++c) + a[c] = _mm512_aesenc_epi128(a[c], key.k[r]); + for (u64 c = 0; c < C; ++c) + { + a[c] = _mm512_aesenclast_epi128(a[c], key.k[10]); + const __m512i c0 = _mm512_aesenc_epi128(a[c], x[c]); + const __m512i c1 = _mm512_add_epi64(a[c], x[c]); + const u64 q = c / 2, v = c % 2; // parent q, lanes 4v..4v+3 + _mm512_storeu_si512(ch + 16 * q + 4 * v, c0); + _mm512_storeu_si512(ch + 16 * q + 8 + 4 * v, c1); + s0[v] = _mm512_xor_si512(s0[v], c0); + s1[v] = _mm512_xor_si512(s1[v], c1); + } + } + + OC_FORCEINLINE void internalLevel(const ZmmKey& key, + const block* parents, block* children, u64 width, block* sum0, block* sum1) + { + __m512i s0[2] = { _mm512_loadu_si512(sum0), _mm512_loadu_si512(sum0 + 4) }; + __m512i s1[2] = { _mm512_loadu_si512(sum1), _mm512_loadu_si512(sum1 + 4) }; + u64 p = 0; + for (; p + 2 <= width; p += 2) + internalStep<2>(key, parents + 8 * p, children + 16 * p, s0, s1); + if (p < width) + internalStep<1>(key, parents + 8 * p, children + 16 * p, s0, s1); + _mm512_storeu_si512(sum0, s0[0]); _mm512_storeu_si512(sum0 + 4, s0[1]); + _mm512_storeu_si512(sum1, s1[0]); _mm512_storeu_si512(sum1 + 4, s1[1]); + } + + template + OC_FORCEINLINE void leafStep(const ZmmKey& k0, const ZmmKey& k1, const block* in, block* o, + __m512i (&s0)[2], __m512i (&s1)[2]) + { + constexpr u64 C = 2 * NP; + __m512i x[C], a[C], b[C]; + for (u64 c = 0; c < C; ++c) + { + x[c] = _mm512_loadu_si512(in + 4 * c); + a[c] = _mm512_xor_si512(x[c], k0.k[0]); + b[c] = _mm512_xor_si512(x[c], k1.k[0]); + } + for (u64 r = 1; r < 10; ++r) + for (u64 c = 0; c < C; ++c) + { + a[c] = _mm512_aesenc_epi128(a[c], k0.k[r]); + b[c] = _mm512_aesenc_epi128(b[c], k1.k[r]); + } + for (u64 c = 0; c < C; ++c) + { + a[c] = _mm512_xor_si512(_mm512_aesenclast_epi128(a[c], k0.k[10]), x[c]); + b[c] = _mm512_xor_si512(_mm512_aesenclast_epi128(b[c], k1.k[10]), x[c]); + const u64 q = c / 2, v = c % 2; + _mm512_storeu_si512(o + 16 * q + 4 * v, a[c]); + _mm512_storeu_si512(o + 16 * q + 8 + 4 * v, b[c]); + s0[v] = _mm512_xor_si512(s0[v], a[c]); + s1[v] = _mm512_xor_si512(s1[v], b[c]); + } + } + + OC_FORCEINLINE void leafLevel(const ZmmKey& k0, const ZmmKey& k1, + const block* parents, block* out, u64 width, block* sum0, block* sum1) + { + __m512i s0[2] = { _mm512_loadu_si512(sum0), _mm512_loadu_si512(sum0 + 4) }; + __m512i s1[2] = { _mm512_loadu_si512(sum1), _mm512_loadu_si512(sum1 + 4) }; + u64 p = 0; + for (; p + 2 <= width; p += 2) + leafStep<2>(k0, k1, parents + 8 * p, out + 16 * p, s0, s1); + if (p < width) + leafStep<1>(k0, k1, parents + 8 * p, out + 16 * p, s0, s1); + _mm512_storeu_si512(sum0, s0[0]); _mm512_storeu_si512(sum0 + 4, s0[1]); + _mm512_storeu_si512(sum1, s1[0]); _mm512_storeu_si512(sum1 + 4, s1[1]); + } + + using Key = ZmmKey; +#else + using Key = YmmKey; +#endif + // The kernels keep one sum per lane (the 8 subtrees of one tree); the // tree's level sum is their XOR. OC_FORCEINLINE block fold8(const block* s) @@ -558,7 +662,7 @@ namespace osuCrypto levels[0][0][lane] = current[lane]; }); #ifdef OC_ENABLE_VAES - const pprfVaes::YmmKey internalKey(mAesFixedKey); + const pprfVaes::Key internalKey(mAesFixedKey); #endif for (u64 localDepth = 0; localDepth + 1 < levels.size(); ++localDepth) @@ -570,7 +674,7 @@ namespace osuCrypto const auto width = u64{ 1 } << localDepth; #ifdef OC_ENABLE_VAES { - alignas(32) std::array laneSums0{}, laneSums1{}; + alignas(64) std::array laneSums0{}, laneSums1{}; pprfVaes::internalLevel(internalKey, parents.data()->data(), children.data()->data(), width, laneSums0.data(), laneSums1.data()); leftAccumulator = leftAccumulator ^ pprfVaes::fold8(laneSums0.data()); @@ -675,8 +779,8 @@ namespace osuCrypto block rightAccumulator = ZeroBlock; #ifdef OC_ENABLE_VAES { - alignas(32) std::array laneSums0{}, laneSums1{}; - pprfVaes::leafLevel(pprfVaes::YmmKey(gGgmAes[0]), pprfVaes::YmmKey(gGgmAes[1]), + alignas(64) std::array laneSums0{}, laneSums1{}; + pprfVaes::leafLevel(pprfVaes::Key(gGgmAes[0]), pprfVaes::Key(gGgmAes[1]), parents.data()->data(), dest, parents.size(), laneSums0.data(), laneSums1.data()); nativeLeaf += 16 * parents.size(); @@ -1114,7 +1218,7 @@ namespace osuCrypto levels[0][0][lane] = current[lane]; }); #ifdef OC_ENABLE_VAES - const pprfVaes::YmmKey internalKey(mAesFixedKey); + const pprfVaes::Key internalKey(mAesFixedKey); #endif for (u64 localDepth = 0; localDepth + 1 < levels.size(); ++localDepth) @@ -1126,7 +1230,7 @@ namespace osuCrypto const auto width = u64{ 1 } << localDepth; #ifdef OC_ENABLE_VAES { - alignas(32) std::array laneSums0{}, laneSums1{}; + alignas(64) std::array laneSums0{}, laneSums1{}; pprfVaes::internalLevel(internalKey, parents.data()->data(), children.data()->data(), width, laneSums0.data(), laneSums1.data()); leftAccumulator = leftAccumulator ^ pprfVaes::fold8(laneSums0.data()); @@ -1252,8 +1356,8 @@ namespace osuCrypto block rightAccumulator = gGgmAes[1].hashBlock(ZeroBlock); #ifdef OC_ENABLE_VAES { - alignas(32) std::array laneSums0{}, laneSums1{}; - pprfVaes::leafLevel(pprfVaes::YmmKey(gGgmAes[0]), pprfVaes::YmmKey(gGgmAes[1]), + alignas(64) std::array laneSums0{}, laneSums1{}; + pprfVaes::leafLevel(pprfVaes::Key(gGgmAes[0]), pprfVaes::Key(gGgmAes[1]), parents.data()->data(), dest, parents.size(), laneSums0.data(), laneSums1.data()); nativeLeaf += 16 * parents.size(); From 5449c4af1463860d81c9e6543c74cae33907b366 Mon Sep 17 00:00:00 2001 From: Peter Rindal Date: Fri, 20 Nov 2026 20:36:28 -0800 Subject: [PATCH 7/8] Silent OT: SPIN bit-vector transpose for separate choice bits The correlated-OT receiver's choice bytes now go through SPIN 0.4.1's transpose_bits instead of widening each byte to a block for a second full record transpose. Each byte is eight bit lanes of the binary map; only the bit planes present are transposed (one for 0/1 choices), packed with pext/pdep where BMI2 is available. Outputs are unchanged. Requires SPIN 0.4.1 (pinned to spin_codes cf75e9ec). spinOtBench -choices times both paths in one binary: K=2^18 0.645 -> 0.214 ms, K=2^20 4.35 -> 0.87 ms. Spin, SilentOt and Pprf tests pass; random-OT digests match. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- cmake/Config.cmake.in | 2 +- cmake/libOTeDepHelper.cmake | 2 +- frontend/SpinOtBench.cpp | 35 +++++++++++++++++++++++ libOTe/Tools/Spin/README.md | 9 ++++-- libOTe/Tools/Spin/SpinOt.cpp | 55 ++++++++++++++++++++++++++++++++---- libOTe/Tools/Spin/SpinOt.h | 10 +++---- thirdparty/getSpin.cmake | 2 +- 8 files changed, 100 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index a5b06254..91f5b718 100644 --- a/README.md +++ b/README.md @@ -135,7 +135,7 @@ Dependencies can be managed by cmake/build.py or installed via an external tool. **[SPIN](https://github.com/ladnir/spin_codes) (Silent OT encoder):** -`ENABLE_SPIN` defaults on with Silent OT or Silent VOLE. Install SPIN 0.4 or +`ENABLE_SPIN` defaults on with Silent OT or Silent VOLE. Install SPIN 0.4.1 or use `FETCH_SPIN=ON` / `FETCH_AUTO`. Requires CMake 3.20+ and x86-64 with AVX2; set `ENABLE_SPIN=OFF` to omit it. See the [usage guide](libOTe/Tools/Spin/README.md). diff --git a/cmake/Config.cmake.in b/cmake/Config.cmake.in index ec9b689f..e4fb8a3e 100644 --- a/cmake/Config.cmake.in +++ b/cmake/Config.cmake.in @@ -9,7 +9,7 @@ include("${CMAKE_CURRENT_LIST_DIR}/buildOptions.cmake") find_package(cryptoTools REQUIRED HINTS "${CMAKE_CURRENT_LIST_DIR}/.." ${CMAKE_CURRENT_LIST_DIR}) if(@ENABLE_SPIN@) include(CMakeFindDependencyMacro) - find_dependency(spin 0.4 CONFIG) + find_dependency(spin 0.4.1 CONFIG) endif() diff --git a/cmake/libOTeDepHelper.cmake b/cmake/libOTeDepHelper.cmake index 0783b6cc..fd3a366c 100644 --- a/cmake/libOTeDepHelper.cmake +++ b/cmake/libOTeDepHelper.cmake @@ -146,7 +146,7 @@ macro(FIND_SPIN) else() unset(SPIN_DP) endif() - find_package(spin 0.4 CONFIG ${SPIN_DP} ${ARGN}) + find_package(spin 0.4.1 CONFIG ${SPIN_DP} ${ARGN}) endmacro() if(ENABLE_SPIN AND NOT TARGET spin::spin) diff --git a/frontend/SpinOtBench.cpp b/frontend/SpinOtBench.cpp index 6dbdd8cc..c2b538a5 100644 --- a/frontend/SpinOtBench.cpp +++ b/frontend/SpinOtBench.cpp @@ -62,9 +62,44 @@ static void report(const char* role,u64 k,const std::vector& samples,boo std::cout<<"]}\n"; } } // namespace +// -choices: the correlated-OT receiver's choice-bit transpose, the SPIN bit +// transpose (current) against widening each choice byte to a block and +// running the 128-bit record transpose (previous). Same binary, same input. +static int spinChoiceBench(unsigned exponent,unsigned trials) { + const u64 k=1ull< c(n,0),work(n); + PRNG rng(block(5,6)); + for(u64 i=0;i()%4096%(n-i)]=rng.getBit(); // regular-noise shape + AlignedUnVector lift(n); + auto widened=[&] { + for(u64 i=0;i(lift,state.blocks); + for(u64 i=0;i(0); + }; + std::copy(c.begin(),c.end(),work.begin());widened(); + std::vector want(work.begin(),work.begin()+k); + std::copy(c.begin(),c.end(),work.begin());state.transpose(span(work)); + require(std::equal(want.begin(),want.end(),work.begin())); + auto time=[&](auto&& f) { + std::vector t; + for(unsigned r=0;r=5)t.push_back(ms(a,b)); + } + std::sort(t.begin(),t.end());return t[t.size()/2]; + }; + const double bits=time([&]{state.transpose(span(work));}),old=time(widened); + std::cout<("logN",18); const unsigned trials=cmd.getOr("trials",31); + if(cmd.isSet("choices")) return spinChoiceBench(exponent,trials|1); const bool paired=cmd.isSet("paired"),streaming=cmd.isSet("nt"), readOutput=cmd.isSet("consume"),regular=cmd.isSet("regular"); if(exponent<13 || exponent>24 || !trials || !(trials&1)) diff --git a/libOTe/Tools/Spin/README.md b/libOTe/Tools/Spin/README.md index a83531dd..20cba5fe 100644 --- a/libOTe/Tools/Spin/README.md +++ b/libOTe/Tools/Spin/README.md @@ -15,7 +15,7 @@ Enabling the SPIN dependency does not add a Silent VOLE profile. ## Dependency -SPIN 0.4 (Turbo only) requires CMake 3.20+ and a 64-bit CPU; libOTe uses it on x86-64 with AVX2. `ENABLE_SPIN` defaults on +SPIN 0.4.1 (Turbo only) requires CMake 3.20+ and a 64-bit CPU; libOTe uses it on x86-64 with AVX2. `ENABLE_SPIN` defaults on with Silent OT or Silent VOLE; explicit `ENABLE_SPIN=OFF` is respected. Use an installed package through `CMAKE_PREFIX_PATH`, or let `FETCH_SPIN=ON` or `FETCH_AUTO=ON` fetch it. For development, `LIBOTE_SPIN_SOURCE=/path/to/spin` @@ -80,8 +80,11 @@ result and its suffix remains unchanged. Use one workspace per simultaneous call `block` with `CoeffCtxGF2` or `CoeffCtxGF128` uses the optimized kernel. Turbo SPIN transposes only these 128-bit elements: `make_workspace` rejects other types and contexts with `std::invalid_argument`. The map acts on each bit lane -independently, so narrower values can travel in the low bits of a `block`; -Silent OT's separate choice bytes use this path. Prime fields are unsupported. +independently, so narrower values can travel in the low bits of a `block`. +Prime fields are unsupported. Silent OT's separate choice bits (correlated OT) +instead use SPIN's bit-vector transpose (`transpose_bits`, SPIN 0.4.1), which +applies the same map to one bit per position at about a third of the record +cost at K = 2^18. ## Profiling diff --git a/libOTe/Tools/Spin/SpinOt.cpp b/libOTe/Tools/Spin/SpinOt.cpp index ee2e8789..f9e163c6 100644 --- a/libOTe/Tools/Spin/SpinOt.cpp +++ b/libOTe/Tools/Spin/SpinOt.cpp @@ -2,6 +2,10 @@ #ifdef ENABLE_SPIN #include #include +#include +#if defined(__BMI2__) +#include +#endif namespace osuCrypto { namespace detail { spin::CodeSpec spinProfile(u64 requested,block seed) { @@ -53,7 +57,7 @@ static spin::SetupOptions spinSetup(SdNoiseDistribution noise) { } SpinOtState::SpinOtState(u64 requested,block codeSeed,bool receiver,SdNoiseDistribution noise) :seed(codeSeed),code(detail::spinProfile(requested,codeSeed),{},spinSetup(noise)),blocks(code.make_workspace()) { - if(receiver) choices.emplace(code.make_workspace()); + if(receiver) choices.emplace(code.code().make_bit_workspace()); } void prepareSpin(std::unique_ptr& state,u64 requested,block seed,bool receiver,SdNoiseDistribution noise) { const auto spec=detail::spinProfile(requested,seed); @@ -65,14 +69,55 @@ void prepareSpin(std::unique_ptr& state,u64 requested,block seed,bo else {state->code.setCodeSeed(seed);state->seed=seed;} } void SpinOtState::transpose(span x) {code.transpose_inplace(x,blocks);} +namespace { +// Gather bit p of eight bytes into one byte, and spread it back. +inline u64 gather8(u64 v,unsigned p) { +#if defined(__BMI2__) + return _pext_u64(v,0x0101010101010101ull<>(8*j+p))&1)<>j)&1)<<(8*j+p);return r; +#endif +} +} void SpinOtState::transpose(span x) { if(!choices) throw std::logic_error("SPIN choice workspace was not prepared"); + const auto& enc=code.code(); + const u64 n=enc.code_size(),k=enc.message_size(),inWords=n/64,outWords=k/64; + if(x.size()!=n) throw std::invalid_argument("SPIN choice transpose needs 2K bytes"); + // Each byte is eight independent bit lanes of the binary map. Only the bit + // planes present are transposed; 0/1 choice bytes need one bit transpose. + u8 any=0; + for(u64 i=0;i>p)&1U) planes[count++]=p; // Reuses its capacity across batches; allocates only on first use or growth. - choiceLift.resize(x.size()); - for(u64 i=0;i(choiceLift,*choices); + choiceIn.resize(count*inWords);choiceOut.resize(count*outWords); + for(u64 w=0;w(choiceIn.data()+q*inWords,inWords), + span(choiceOut.data()+q*outWords,outWords),*choices); // In-place contract: the first K entries receive the result, the rest are unchanged. - for(u64 i=0,k=code.messageSize();i(0); + for(u64 i=0;i>(i%64))&255U,planes[q]); + std::memcpy(x.data()+i,&v,8); + } } } #endif diff --git a/libOTe/Tools/Spin/SpinOt.h b/libOTe/Tools/Spin/SpinOt.h index 73846cf6..39610eb1 100644 --- a/libOTe/Tools/Spin/SpinOt.h +++ b/libOTe/Tools/Spin/SpinOt.h @@ -19,11 +19,11 @@ struct SpinOtState { block seed; SpinCode code; SpinCode::Workspace blocks; - // Separate choice bytes use the native 128-bit transpose: the binary map acts - // on each bit lane independently, so each byte travels in the low byte of a - // block. Turbo SPIN has no generic-element transpose. - std::optional> choices; - AlignedUnVector choiceLift; + // Separate choice bytes use SPIN's bit-vector transpose: each byte is eight + // bit lanes of the binary map, and only the bit planes present are + // transposed (one for 0/1 choices). Packed words are reused across batches. + std::optional choices; + AlignedUnVector choiceIn, choiceOut; SpinOtState(u64 requested,block codeSeed,bool receiver, SdNoiseDistribution noise=SdNoiseDistribution::Regular); void transpose(span x); diff --git a/thirdparty/getSpin.cmake b/thirdparty/getSpin.cmake index a1f5bb4d..3d38486a 100644 --- a/thirdparty/getSpin.cmake +++ b/thirdparty/getSpin.cmake @@ -1,5 +1,5 @@ set(GIT_REPOSITORY https://github.com/ladnir/spin_codes.git) -set(GIT_TAG "0f0abd80ca239f377c22a53a95930f534e55aa86") +set(GIT_TAG "cf75e9ec293ba0438402d85f489cc39730210d91") set(CLONE_DIR "${OC_THIRDPARTY_CLONE_DIR}/spin") set(BUILD_DIR "${CLONE_DIR}/out/build/${OC_CONFIG}") set(LOG_FILE "${CMAKE_CURRENT_LIST_DIR}/log-spin.txt") From 63d7b5f46444c77f464e16ebd5c751eeefcb1cd5 Mon Sep 17 00:00:00 2001 From: Peter Rindal Date: Sun, 22 Nov 2026 09:45:06 -0800 Subject: [PATCH 8/8] SPIN: consolidate into SpinCode.h; SPIN 0.4.2 for ARM and portable builds - SpinCode is the only SPIN glue: messageSize, prepare (reseed or rebuild), block and choice-byte transposes, encoder(). SpinOt.h/.cpp removed. - SpinConfigure moves to ConfigureCode.cpp (avoids an include cycle). - mSpin is std::optional; the choice-bit workspace is lazy. - Choice bytes must be 0/1; portable multiply packing (no BMI2). - Drop -spinOtBench -choices; fix the installed-package consumer check; remove the AVX2 test skips and cover stationary noise. - Require and pin SPIN 0.4.2 (34a03e96): AArch64 NEON, portable fallback, MSVC. Docs: K >= 8192, platforms, ENABLE_VAES. Co-Authored-By: Claude Opus 5.5 --- README.md | 7 +- cmake/Config.cmake.in | 2 +- cmake/libOTeDepHelper.cmake | 2 +- frontend/SpinCompressionBench.cpp | 7 +- frontend/SpinOtBench.cpp | 50 +------ libOTe/CMakeLists.txt | 1 - libOTe/Tools/Spin/README.md | 131 ++++++++---------- libOTe/Tools/Spin/SpinCode.h | 127 +++++++++++++---- libOTe/Tools/Spin/SpinOt.cpp | 123 ---------------- libOTe/Tools/Spin/SpinOt.h | 35 ----- libOTe/TwoChooseOne/ConfigureCode.cpp | 32 ++++- .../Silent/SilentOtExtReceiver.cpp | 4 +- .../TwoChooseOne/Silent/SilentOtExtReceiver.h | 9 +- .../TwoChooseOne/Silent/SilentOtExtSender.cpp | 2 +- .../TwoChooseOne/Silent/SilentOtExtSender.h | 9 +- libOTe_Tests/SilentOT_Tests.cpp | 19 ++- libOTe_Tests/cmakeTests/main.cpp | 43 +++--- thirdparty/getSpin.cmake | 2 +- 18 files changed, 242 insertions(+), 363 deletions(-) delete mode 100644 libOTe/Tools/Spin/SpinOt.cpp delete mode 100644 libOTe/Tools/Spin/SpinOt.h diff --git a/README.md b/README.md index 91f5b718..01f1dced 100644 --- a/README.md +++ b/README.md @@ -135,9 +135,10 @@ Dependencies can be managed by cmake/build.py or installed via an external tool. **[SPIN](https://github.com/ladnir/spin_codes) (Silent OT encoder):** -`ENABLE_SPIN` defaults on with Silent OT or Silent VOLE. Install SPIN 0.4.1 or -use `FETCH_SPIN=ON` / `FETCH_AUTO`. Requires CMake 3.20+ and x86-64 with AVX2; -set `ENABLE_SPIN=OFF` to omit it. See the [usage guide](libOTe/Tools/Spin/README.md). +`ENABLE_SPIN` defaults on with Silent OT or Silent VOLE. Install SPIN 0.4.2 or +use `FETCH_SPIN=ON` / `FETCH_AUTO`. Requires CMake 3.20+ and a little-endian +CPU; SPIN selects x86-64, AArch64 (NEON) or portable kernels at runtime. +Set `ENABLE_SPIN=OFF` to omit it. See the [usage guide](libOTe/Tools/Spin/README.md). **Enabling/Disabling [Relic](https://github.com/relic-toolkit/relic) (for base OTs):** The library can be built with Relic as diff --git a/cmake/Config.cmake.in b/cmake/Config.cmake.in index e4fb8a3e..00c5e5ad 100644 --- a/cmake/Config.cmake.in +++ b/cmake/Config.cmake.in @@ -9,7 +9,7 @@ include("${CMAKE_CURRENT_LIST_DIR}/buildOptions.cmake") find_package(cryptoTools REQUIRED HINTS "${CMAKE_CURRENT_LIST_DIR}/.." ${CMAKE_CURRENT_LIST_DIR}) if(@ENABLE_SPIN@) include(CMakeFindDependencyMacro) - find_dependency(spin 0.4.1 CONFIG) + find_dependency(spin 0.4.2 CONFIG) endif() diff --git a/cmake/libOTeDepHelper.cmake b/cmake/libOTeDepHelper.cmake index fd3a366c..c96b408e 100644 --- a/cmake/libOTeDepHelper.cmake +++ b/cmake/libOTeDepHelper.cmake @@ -146,7 +146,7 @@ macro(FIND_SPIN) else() unset(SPIN_DP) endif() - find_package(spin 0.4.1 CONFIG ${SPIN_DP} ${ARGN}) + find_package(spin 0.4.2 CONFIG ${SPIN_DP} ${ARGN}) endmacro() if(ENABLE_SPIN AND NOT TARGET spin::spin) diff --git a/frontend/SpinCompressionBench.cpp b/frontend/SpinCompressionBench.cpp index c1c90aea..a3a69418 100644 --- a/frontend/SpinCompressionBench.cpp +++ b/frontend/SpinCompressionBench.cpp @@ -32,7 +32,7 @@ int spinCompressionBenchmark(CLP& cmd) {try { SilentOtExtSender s; // Hold stationary geometry fixed even when the encoder uses full setup. s.configure(k,2,1,SilentSecType::SemiHonest,SdNoiseDistribution::Stationary,MultType::Spin); - s.mSpin=std::make_unique(k,s.mCodeSeed,false,noise); + s.mSpin.emplace(k,s.mCodeSeed,noise); s.mB.resize(s.mNoiseVecSize); s.mDelta=block(345,679); StationaryPprfSender leaves; @@ -59,7 +59,7 @@ int spinCompressionBenchmark(CLP& cmd) {try { } if(context!="bare") std::fill(s.mB.begin()+active,s.mB.end(),ZeroBlock); auto b=Clock::now(); - prepareSpin(s.mSpin,k,s.mCodeSeed,false,noise); + SpinCode::prepare(s.mSpin,k,s.mCodeSeed,noise); auto c=Clock::now(); s.mSpin->transpose(s.mB); auto d=Clock::now(); @@ -94,8 +94,7 @@ int spinCompressionBenchmark(CLP& cmd) {try { if(messages[i][0]!=s.mB[i] || messages[i][1]!=s.mB[i]) throw std::runtime_error("output-store check failed"); std::cout<code.code().setup_bytes() - <<",\"workspace_bytes\":"<blocks.bytes() + <<"\",\"K\":"<encoder().setup_bytes() <<",\"stimulus_ms\":"<(0)^(output?messages[0][0].get(0):0))<<",\"samples\":["; diff --git a/frontend/SpinOtBench.cpp b/frontend/SpinOtBench.cpp index c2b538a5..8fba6c47 100644 --- a/frontend/SpinOtBench.cpp +++ b/frontend/SpinOtBench.cpp @@ -62,44 +62,9 @@ static void report(const char* role,u64 k,const std::vector& samples,boo std::cout<<"]}\n"; } } // namespace -// -choices: the correlated-OT receiver's choice-bit transpose, the SPIN bit -// transpose (current) against widening each choice byte to a block and -// running the 128-bit record transpose (previous). Same binary, same input. -static int spinChoiceBench(unsigned exponent,unsigned trials) { - const u64 k=1ull< c(n,0),work(n); - PRNG rng(block(5,6)); - for(u64 i=0;i()%4096%(n-i)]=rng.getBit(); // regular-noise shape - AlignedUnVector lift(n); - auto widened=[&] { - for(u64 i=0;i(lift,state.blocks); - for(u64 i=0;i(0); - }; - std::copy(c.begin(),c.end(),work.begin());widened(); - std::vector want(work.begin(),work.begin()+k); - std::copy(c.begin(),c.end(),work.begin());state.transpose(span(work)); - require(std::equal(want.begin(),want.end(),work.begin())); - auto time=[&](auto&& f) { - std::vector t; - for(unsigned r=0;r=5)t.push_back(ms(a,b)); - } - std::sort(t.begin(),t.end());return t[t.size()/2]; - }; - const double bits=time([&]{state.transpose(span(work));}),old=time(widened); - std::cout<("logN",18); const unsigned trials=cmd.getOr("trials",31); - if(cmd.isSet("choices")) return spinChoiceBench(exponent,trials|1); const bool paired=cmd.isSet("paired"),streaming=cmd.isSet("nt"), readOutput=cmd.isSet("consume"),regular=cmd.isSet("regular"); if(exponent<13 || exponent>24 || !trials || !(trials&1)) @@ -111,8 +76,8 @@ int spinOtBenchmark(CLP& cmd) {try { const auto noise=regular?SdNoiseDistribution::Regular:SdNoiseDistribution::Stationary; s.configure(k,2,1,SilentSecType::SemiHonest,noise,MultType::Spin); r.configure(k,2,1,SilentSecType::SemiHonest,noise,MultType::Spin); - s.mSpin=std::make_unique(k,s.mCodeSeed,false,s.mNoiseDist); - r.mSpin=std::make_unique(k,r.mCodeSeed,true,r.mNoiseDist); + s.mSpin.emplace(k,s.mCodeSeed,s.mNoiseDist); + r.mSpin.emplace(k,r.mCodeSeed,r.mNoiseDist); s.mB.reserve(s.mNoiseVecSize);r.mA.reserve(r.mNoiseVecSize); std::vector> sent(k);std::vector received(k);BitVector choices(k); // Untimed initial correctness check. Stationary mode also caches tree seeds; @@ -126,7 +91,7 @@ int spinOtBenchmark(CLP& cmd) {try { auto* sg=regular?nullptr:dynamic_cast*>(&s.gen()); auto* rg=regular?nullptr:dynamic_cast*>(&r.gen()); require(regular || (sg && rg && sg->mExpanded && rg->mExpanded)); - require(s.mSpin->code.code().setup_options().mode== + require(s.mSpin->encoder().setup_options().mode== (regular?spin::SetupMode::Full:spin::SetupMode::BankedHeuristic)); s.hash(sent,ChoiceBitPacking::True,streaming);r.hash(choices,received,ChoiceBitPacking::True); for(u64 i=0;imShare.data():nullptr;const auto* rs=rg?rg->mShare.data():nullptr; - const auto* sw=s.mSpin.get();const auto* rw=r.mSpin.get(); - const auto fixedDescriptor=s.mSpin->code.descriptor(); + const auto fixedDescriptor=s.mSpin->encoder().descriptor(); std::cout<<"{\"geometry\":true,\"K\":"<code.descriptor()==fixedDescriptor); + if(regular) require(s.mSpin->encoder().descriptor()==fixedDescriptor); else require(sg->mExpandCounter==counter+1 && ss==sg->mShare.data()); if(round>=5)sender.push_back(a); continue; @@ -199,8 +162,7 @@ int spinOtBenchmark(CLP& cmd) {try { Sample b{stage(rt,"recver.expand.start","recver.expand.pprf"), stage(rt,"recver.expand.pprf","recver.expand.dualEncode"),ms(encoded,end),ms(begin,end)}; require(s.mCodeSeed==r.mCodeSeed && s.mCodeSeed==(regular?seed:mAesFixedKey.hashBlock(seed))); - require(sw==s.mSpin.get() && rw==r.mSpin.get()); - if(regular) require(s.mSpin->code.descriptor()==fixedDescriptor && r.mSpin->code.descriptor()==fixedDescriptor); + if(regular) require(s.mSpin->encoder().descriptor()==fixedDescriptor && r.mSpin->encoder().descriptor()==fixedDescriptor); else { require(sg->mExpandCounter==counter+1 && rg->mExpandCounter==sg->mExpandCounter); require(ss==sg->mShare.data() && rs==rg->mShare.data()); diff --git a/libOTe/CMakeLists.txt b/libOTe/CMakeLists.txt index 81b5225d..8750a517 100644 --- a/libOTe/CMakeLists.txt +++ b/libOTe/CMakeLists.txt @@ -134,7 +134,6 @@ target_include_directories(libOTe PUBLIC target_link_libraries(libOTe cryptoTools) if(ENABLE_SPIN) - target_sources(libOTe PRIVATE Tools/Spin/SpinOt.cpp) target_link_libraries(libOTe spin::spin) endif() diff --git a/libOTe/Tools/Spin/README.md b/libOTe/Tools/Spin/README.md index 20cba5fe..79233bbf 100644 --- a/libOTe/Tools/Spin/README.md +++ b/libOTe/Tools/Spin/README.md @@ -7,98 +7,79 @@ sender.configure(requested, 2, 1, security, noise, osuCrypto::MultType::Spin); receiver.configure(requested, 2, 1, security, noise, osuCrypto::MultType::Spin); ``` -libOTe uses Turbo SPIN (`spin::Parameters::PacketRs8T64`) at every natural -size: the code size rounds up to the next multiple of 128. Positive requests -below 8192 use 8192, which leaves the noise configuration room for its -partitions; only the requested outputs are returned. Zero requests are rejected. The default `MultType` is unchanged. -Enabling the SPIN dependency does not add a Silent VOLE profile. - -## Dependency - -SPIN 0.4.1 (Turbo only) requires CMake 3.20+ and a 64-bit CPU; libOTe uses it on x86-64 with AVX2. `ENABLE_SPIN` defaults on -with Silent OT or Silent VOLE; explicit `ENABLE_SPIN=OFF` is respected. -Use an installed package through `CMAKE_PREFIX_PATH`, or let `FETCH_SPIN=ON` -or `FETCH_AUTO=ON` fetch it. For development, `LIBOTE_SPIN_SOURCE=/path/to/spin` -uses an editable source directory. External consumers link `oc::libOTe` after +libOTe uses Turbo SPIN (`spin::Parameters::PacketRs8T64`). The code size K is +the request rounded up to a multiple of 128, and at least 8192 so the noise +configuration has room for its partitions; only the requested outputs are +returned. Zero requests are rejected. The default `MultType` is unchanged, and +SPIN adds no Silent VOLE profile. + +## Dependency and platforms + +SPIN 0.4.2 needs CMake 3.20+ and a little-endian target. It runs on every CPU: +SPIN picks AVX-512, AVX2+GFNI or AVX2 kernels on x86-64, NEON on AArch64 +(including Apple silicon), and a portable C++ kernel elsewhere, all computing +the same map. `ENABLE_SPIN` defaults on with Silent OT or Silent VOLE; explicit +`ENABLE_SPIN=OFF` is respected. Use an installed package through +`CMAKE_PREFIX_PATH`, or let `FETCH_SPIN=ON` or `FETCH_AUTO=ON` fetch it. For +development, `LIBOTE_SPIN_SOURCE=/path/to/spin` uses a source directory. +External consumers link `oc::libOTe` after `find_package(libOTe CONFIG REQUIRED COMPONENTS spin)`. -## Preparation and reuse +On x86-64, configure with `-DENABLE_VAES=ON` where the CPU has VAES: the GGM +expansion and sender hash otherwise use the 128-bit AES-NI paths. -`configure()` selects parameters but does not construct the code or scratch. -The first compression prepares them lazily. To move preparation outside the -critical path, initialize the public members after configuring: +## Interface + +[`SpinCode.h`](SpinCode.h) holds everything libOTe adds on top of the SPIN +library; `SpinConfigure` (`ConfigureCode.h`) picks the noise parameters. ```cpp -// Optional: both endpoints must agree on the seed. -sender.mCodeSeed = receiver.mCodeSeed = agreedSeed; -sender.mSpin = std::make_unique( - sender.mRequestNumOts, sender.mCodeSeed, false, sender.mNoiseDist); -receiver.mSpin = std::make_unique( - receiver.mRequestNumOts, receiver.mCodeSeed, true, receiver.mNoiseDist); -sender.mB.reserve(sender.mNoiseVecSize); -receiver.mA.reserve(receiver.mNoiseVecSize); -receiver.mC.reserve(receiver.mNoiseVecSize); // Separate choices only. +osuCrypto::SpinCode code(requested, seed, noise); // one party's encoder +code.transpose(blocks); // 2K blocks -> first K, in place +code.transpose(choices); // 2K choice bytes (0 or 1) -> first K, in place ``` -The default seed needs no assignment. Buffers also accept moved `AlignedUnVector` -allocations. Preparation does not cover every protocol allocation. - -- Regular noise reuses the full precomputed code. Changing `mCodeSeed` rebuilds - the map at the next compression, retaining compatible scratch. -- Stationary noise selects banked heuristic setup and advances `mCodeSeed` - after each compression. Refresh reorders the bank's routing regions and inner - updates and draws fresh outer scalars; it retains the bank and scratch without - constructing a full route each batch. -- Both parties must start with matching seeds and options. Block and separate-choice - encoding use the same map within a batch. -- `clear()` deallocates the code, scratch, and protocol buffers. Reconfiguration - also discards prepared state, so apply overrides afterward. Copying convenience - methods can clear state; repeated in-place calls retain compatible preparation. - -Banked refresh is a heuristic permutation family outside SPIN's uniform-setup -distance certificates. Under uniform setup, Turbo SPIN's minimum distance exceeds -N/10 at K=2^14, 2^16, ..., 2^26 (Lean-certified); other natural lengths are allowed -without a size-specific certificate. The noise configurator uses a linear-attack -tuning value of 0.25, matching BAA; this is not a claim of 25% minimum distance. -See the [SPIN library](https://github.com/ladnir/spin_codes) for construction and -certificate details. - -## Generic coefficients - -`SpinCode` compresses 2K coefficients to K using the same binary linear map: +Regular noise uses the full seeded setup. Stationary noise uses SPIN's banked +heuristic refresh, which reorders a fixed bank's routing regions and inner +updates and draws fresh outer scalars per seed, without allocating. Banked +codes are outside SPIN's uniform-setup distance certificates (Turbo SPIN's +minimum distance exceeds N/10 at K = 2^14, 2^16, ..., 2^26 under uniform +setup). The noise configurator's linear-attack tuning value of 0.25 matches +BAA; it is not a claim of 25% minimum distance. See the +[SPIN library](https://github.com/ladnir/spin_codes) for the construction and +certificates. + +Choice bytes go through SPIN's bit-vector transpose: the same binary map on +one bit per position, about a third of the record cost at K = 2^18. + +## Preparation + +The sender and receiver hold a `std::optional mSpin`, prepared at the +first compression and reseeded (not rebuilt) while the size and noise +distribution match. To move preparation out of the critical path, emplace it +after `configure()`; both parties must use the same seed: ```cpp -osuCrypto::SpinCode code({.message_size=65536, - .parameters=spin::Parameters::PacketRs8T64, - .route_seed=17, .inner_seed=29}); -auto workspace = code.make_workspace(); -code.transpose_inplace(buffer, workspace); +sender.mCodeSeed = receiver.mCodeSeed = agreedSeed; // optional +sender.mSpin.emplace(sender.mRequestNumOts, sender.mCodeSeed, sender.mNoiseDist); +receiver.mSpin.emplace(receiver.mRequestNumOts, receiver.mCodeSeed, receiver.mNoiseDist); ``` -The buffer must contain exactly 2K elements; its first K elements receive the -result and its suffix remains unchanged. Use one workspace per simultaneous call. -`block` with `CoeffCtxGF2` or `CoeffCtxGF128` uses the optimized kernel. -Turbo SPIN transposes only these 128-bit elements: `make_workspace` rejects other -types and contexts with `std::invalid_argument`. The map acts on each bit lane -independently, so narrower values can travel in the low bits of a `block`. -Prime fields are unsupported. Silent OT's separate choice bits (correlated OT) -instead use SPIN's bit-vector transpose (`transpose_bits`, SPIN 0.4.1), which -applies the same map to one bit per position at about a third of the record -cost at K = 2^18. +Regular noise keeps the code fixed across batches. Stationary noise advances +`mCodeSeed` after each compression and refreshes in place. `configure()` and +`clear()` release the encoder. ## Profiling -The existing frontend provides `-spinOtBench` and `-spinCompressionBench`. -For example: - ```sh frontend_libOTe -spinOtBench -logN 18 -regular -check frontend_libOTe -spinOtBench -logN 18 -regular -trials 101 -nt ``` Omit `-regular` for stationary noise. `-check` runs a complete hashed-OT check -without timing. Timed runs report per-stage medians and throughput in C++; -`-paired` also measures the receiver serially and checks every batch. -Timings exclude initial setup, supplied base-correlation generation, and transport. -`-nt` selects streaming sender-output stores; `-consume` adds a sequential output -scan. Run benchmarks one at a time on an otherwise idle host. +and prints a fixed-seed output digest, so two builds can be compared bit for +bit. Timed runs report per-stage medians; `-paired` also measures the receiver +and checks every batch; `-nt` selects streaming sender-output stores; +`-consume` adds a sequential output scan. `-spinCompressionBench` isolates the +compression stage. Timings exclude initial setup, base correlations and +transport. Run benchmarks one at a time on an otherwise idle host. diff --git a/libOTe/Tools/Spin/SpinCode.h b/libOTe/Tools/Spin/SpinCode.h index 19eb7442..14f14161 100644 --- a/libOTe/Tools/Spin/SpinCode.h +++ b/libOTe/Tools/Spin/SpinCode.h @@ -1,44 +1,111 @@ #pragma once #include "libOTe/config.h" #ifdef ENABLE_SPIN -#include "libOTe/Tools/CoeffCtx.h" +#include "libOTe/TwoChooseOne/ConfigureCode.h" +#include "cryptoTools/Common/Aligned.h" #include #include -#include +#include +#include +#include +#include namespace osuCrypto { -// Binary SPIN map, with libOTe coefficient contexts at the arithmetic boundary. -// No field multiplication or weighting is performed by this encoder. + +// Silent OT's SPIN compression (MultType::Spin): one party's prepared Turbo +// SPIN encoder (spin::Parameters::PacketRs8T64) and its scratch. Both parties +// must construct it from the same request, seed and noise distribution. +// Regular noise uses the full seeded setup; stationary noise uses the banked +// heuristic refresh. SpinConfigure (ConfigureCode.h) picks the noise. class SpinCode { - spin::PreparedEncoder mCode; - template static constexpr bool native = - std::is_same_v && (std::is_same_v || - std::is_same_v); public: - explicit SpinCode(spin::CodeSpec spec,spin::ExecutionOptions options={},spin::SetupOptions setup={}) : mCode(spec,setup,options) {} - void setCodeSeed(block seed) {mCode.setCodeSeed({seed.get(0),seed.get(1)});} - u64 messageSize() const {return mCode.message_size();} - u64 codeSize() const {return mCode.code_size();} - auto descriptor() const {return mCode.descriptor();} - const spin::PreparedEncoder& code() const {return mCode;} - - // Turbo SPIN transposes 128-bit records only. Other element types and - // coefficient contexts are rejected at runtime (std::invalid_argument); - // narrower binary values can travel in the low bits of a block. - template - using Workspace = spin::PreparedEncoder::Workspace; - - template Workspace make_workspace(Ctx ctx={}) const { - if(!ctx.template characteristicTwo()) - throw std::invalid_argument("SPIN requires characteristic-two addition"); - if constexpr(native) return mCode.make_workspace(); - else throw std::invalid_argument("SPIN transposes 128-bit block records only"); + // K for a request: the next multiple of 128, at least 8192 so the noise + // configuration has room for its partitions. Not tied to the distance + // certificates, which cover K = 2^14, 2^16, ..., 2^26. + static u64 messageSize(u64 requested) { + constexpr u64 minimum = 8192, maximum = u64(1) << 40; + if (!requested || requested > maximum) + throw std::invalid_argument("SPIN OT request size is out of range"); + const auto k = roundUpTo(std::max(requested, minimum), spin::message_alignment(parameters)); + if (!spin::valid_message_size(parameters, k)) + throw std::invalid_argument("SPIN OT request exceeds the largest Turbo code"); + return k; + } + + SpinCode(u64 requested, block seed, SdNoiseDistribution noise) + : mEncoder({ messageSize(requested), parameters, seed.get(0), seed.get(1) }, setup(noise)) + , mBlocks(mEncoder.make_workspace()) + {} + + // Reseeds `code` when its size and noise distribution match (no allocation + // for stationary noise; a full rebuild of the map for regular noise with a + // new seed); otherwise constructs it. + static void prepare(std::optional& code, u64 requested, block seed, SdNoiseDistribution noise) { + if (code && code->messageSize() == messageSize(requested) && + code->mEncoder.setup_options().mode == setup(noise).mode) + code->mEncoder.setCodeSeed({ seed.get(0), seed.get(1) }); + else + code.emplace(requested, seed, noise); + } + + u64 messageSize() const { return mEncoder.message_size(); } + u64 codeSize() const { return mEncoder.code_size(); } + const spin::PreparedEncoder& encoder() const { return mEncoder; } + + // Transposed encoding in place: x holds 2K blocks; the first K receive the + // result and the rest are unchanged. + void transpose(span x) { + mEncoder.transpose_inplace(std::span(x.data(), x.size()), mBlocks); + } + + // The same map on 2K choice bytes, each 0 or 1 (correlated OT's separate + // choices), through SPIN's bit-vector transpose. The first K bytes receive + // the result. The first call allocates the bit workspace and scratch. + void transpose(span x) { + const u64 n = codeSize(), k = messageSize(); + if (x.size() != n) + throw std::invalid_argument("SPIN choice transpose needs 2K bytes"); + if (!mBits) { + mBits.emplace(mEncoder.make_bit_workspace()); + mBitsIn.resize(n / 64); + mBitsOut.resize(k / 64); + } + constexpr u64 low = 0x0101010101010101ull; + u64 high = 0; + for (u64 w = 0; w < n / 64; ++w) { + u64 word = 0; + for (u64 j = 0; j < 8; ++j) { + u64 v; + std::memcpy(&v, x.data() + 64 * w + 8 * j, 8); + high |= v & ~low; + word |= ((v * 0x0102040810204080ull) >> 56) << (8 * j); + } + mBitsIn[w] = word; + } + if (high) + throw std::invalid_argument("SPIN choice bytes must be 0 or 1"); + mEncoder.transpose_bits(std::span(mBitsIn.data(), mBitsIn.size()), + std::span(mBitsOut.data(), mBitsOut.size()), *mBits); + for (u64 i = 0; i < k; i += 8) { + const u64 bits = (mBitsOut[i / 64] >> (i % 64)) & 255; + const u64 v = (((bits & 127) * 0x0002040810204081ull) & low) | ((bits >> 7) << 56); + std::memcpy(x.data() + i, &v, 8); + } } - template - void transpose_inplace(span buffer,Workspace& w) const { - static_assert(native,"SPIN transposes 128-bit block records only"); - mCode.transpose_inplace(std::span(buffer.data(),buffer.size()),w); + +private: + static constexpr auto parameters = spin::Parameters::PacketRs8T64; + static spin::SetupOptions setup(SdNoiseDistribution noise) { + if (noise != SdNoiseDistribution::Regular && noise != SdNoiseDistribution::Stationary) + throw std::invalid_argument("Invalid SPIN noise distribution"); + return { noise == SdNoiseDistribution::Stationary ? spin::SetupMode::BankedHeuristic : spin::SetupMode::Full }; } + + spin::PreparedEncoder mEncoder; + spin::PreparedEncoder::Workspace mBlocks; + std::optional mBits; + AlignedUnVector mBitsIn, mBitsOut; }; + } #endif diff --git a/libOTe/Tools/Spin/SpinOt.cpp b/libOTe/Tools/Spin/SpinOt.cpp deleted file mode 100644 index f9e163c6..00000000 --- a/libOTe/Tools/Spin/SpinOt.cpp +++ /dev/null @@ -1,123 +0,0 @@ -#include "SpinOt.h" -#ifdef ENABLE_SPIN -#include -#include -#include -#if defined(__BMI2__) -#include -#endif -namespace osuCrypto { -namespace detail { -spin::CodeSpec spinProfile(u64 requested,block seed) { - // Turbo SPIN at every natural size (a positive multiple of 128); requests - // round up to the next one. Small requests share K=8192 so the noise - // configuration has room for its partitions; this floor is not tied to - // any distance certificate. Truncate only after encoding. - constexpr u64 minimumK=8192; - constexpr auto parameters=spin::Parameters::PacketRs8T64; - const u64 alignment=spin::message_alignment(parameters); - if(!requested || requested>(u64(1)<<40)) - throw std::invalid_argument("SPIN OT request exceeds the largest Turbo code"); - const u64 k=roundUpTo(std::max(requested,minimumK),alignment); - if(!spin::valid_message_size(parameters,k)) - throw std::invalid_argument("SPIN OT request exceeds the largest Turbo code"); - return {k,parameters,seed.get(0),seed.get(1)}; -} -} - -SdConfig SpinConfigure(u64 secParam,u64 requested,SdNoiseDistribution noise) { - const u64 n=2*detail::spinProfile(requested).message_size; - if(secParam>1024 || (noise!=SdNoiseDistribution::Regular && noise!=SdNoiseDistribution::Stationary)) - throw std::invalid_argument("Invalid SPIN noise configuration"); - // Same effective linear-attack tuning value as BAA. This is not a claim - // of 25% minimum distance; the N/10 certificates are separate evidence. - constexpr double linearAttackTuning=0.25; - const double fullEffectiveWeight=std::floor(linearAttackTuning*double(n)); - const double multiplier=noise==SdNoiseDistribution::Regular?2:1; - const double minimumParts=std::ceil(double(secParam)/-std::log2(1-multiplier*fullEffectiveWeight/n)); - const u64 first=std::max(40,roundUpTo(u64(minimumParts),8)); - const u64 last=std::min(n/4,first+8192); - // Retain a conservative tail adjustment within this heuristic model. - for(u64 parts=first;parts<=last;parts+=8) { - const u64 per=(n/parts)&~u64(1),active=parts*per,pad=n-active; - const double effectiveWeight=fullEffectiveWeight-double(pad); - if(effectiveWeight<=0) continue; - const double ratio=effectiveWeight/double(active); - if(ratio>=0.5) continue; - if(-double(parts)*std::log2(1-multiplier*ratio)>=secParam) - return {n,parts,per}; - } - throw std::invalid_argument("SPIN noise configuration has no supported solution"); -} - -static spin::SetupOptions spinSetup(SdNoiseDistribution noise) { - if(noise!=SdNoiseDistribution::Regular && noise!=SdNoiseDistribution::Stationary) - throw std::invalid_argument("Invalid SPIN noise configuration"); - return {noise==SdNoiseDistribution::Stationary?spin::SetupMode::BankedHeuristic:spin::SetupMode::Full}; -} -SpinOtState::SpinOtState(u64 requested,block codeSeed,bool receiver,SdNoiseDistribution noise) - :seed(codeSeed),code(detail::spinProfile(requested,codeSeed),{},spinSetup(noise)),blocks(code.make_workspace()) { - if(receiver) choices.emplace(code.code().make_bit_workspace()); -} -void prepareSpin(std::unique_ptr& state,u64 requested,block seed,bool receiver,SdNoiseDistribution noise) { - const auto spec=detail::spinProfile(requested,seed); - const auto mode=spinSetup(noise).mode; - if(!state || state->code.messageSize()!=spec.message_size || - state->code.code().specification().parameters!=spec.parameters || - state->code.code().setup_options().mode!=mode || state->choices.has_value()!=receiver) - state=std::make_unique(requested,seed,receiver,noise); - else {state->code.setCodeSeed(seed);state->seed=seed;} -} -void SpinOtState::transpose(span x) {code.transpose_inplace(x,blocks);} -namespace { -// Gather bit p of eight bytes into one byte, and spread it back. -inline u64 gather8(u64 v,unsigned p) { -#if defined(__BMI2__) - return _pext_u64(v,0x0101010101010101ull<>(8*j+p))&1)<>j)&1)<<(8*j+p);return r; -#endif -} -} -void SpinOtState::transpose(span x) { - if(!choices) throw std::logic_error("SPIN choice workspace was not prepared"); - const auto& enc=code.code(); - const u64 n=enc.code_size(),k=enc.message_size(),inWords=n/64,outWords=k/64; - if(x.size()!=n) throw std::invalid_argument("SPIN choice transpose needs 2K bytes"); - // Each byte is eight independent bit lanes of the binary map. Only the bit - // planes present are transposed; 0/1 choice bytes need one bit transpose. - u8 any=0; - for(u64 i=0;i>p)&1U) planes[count++]=p; - // Reuses its capacity across batches; allocates only on first use or growth. - choiceIn.resize(count*inWords);choiceOut.resize(count*outWords); - for(u64 w=0;w(choiceIn.data()+q*inWords,inWords), - span(choiceOut.data()+q*outWords,outWords),*choices); - // In-place contract: the first K entries receive the result, the rest are unchanged. - for(u64 i=0;i>(i%64))&255U,planes[q]); - std::memcpy(x.data()+i,&v,8); - } -} -} -#endif diff --git a/libOTe/Tools/Spin/SpinOt.h b/libOTe/Tools/Spin/SpinOt.h deleted file mode 100644 index 39610eb1..00000000 --- a/libOTe/Tools/Spin/SpinOt.h +++ /dev/null @@ -1,35 +0,0 @@ -#pragma once -#include "libOTe/Tools/Spin/SpinCode.h" -#include "libOTe/TwoChooseOne/ConfigureCode.h" -#include "cryptoTools/Common/Aligned.h" -#ifdef ENABLE_SPIN -#include -#include -namespace osuCrypto { -namespace detail { -// Internal parameter policy; not an additional caller configuration. -spin::CodeSpec spinProfile(u64 requested,block seed=ZeroBlock); -} - -// Optional caller-prepared member state. Construct after configure(), using -// the same mCodeSeed on both parties. Own scratch outside coroutine frames. -// prepareSpin reuses this object when its geometry, setup mode and role match. -// clear() releases it; no process-wide cache retains setup or allocations. -struct SpinOtState { - block seed; - SpinCode code; - SpinCode::Workspace blocks; - // Separate choice bytes use SPIN's bit-vector transpose: each byte is eight - // bit lanes of the binary map, and only the bit planes present are - // transposed (one for 0/1 choices). Packed words are reused across batches. - std::optional choices; - AlignedUnVector choiceIn, choiceOut; - SpinOtState(u64 requested,block codeSeed,bool receiver, - SdNoiseDistribution noise=SdNoiseDistribution::Regular); - void transpose(span x); - void transpose(span x); -}; -void prepareSpin(std::unique_ptr& state,u64 requested,block seed,bool receiver, - SdNoiseDistribution noise=SdNoiseDistribution::Regular); -} -#endif diff --git a/libOTe/TwoChooseOne/ConfigureCode.cpp b/libOTe/TwoChooseOne/ConfigureCode.cpp index 200ce9be..63776245 100644 --- a/libOTe/TwoChooseOne/ConfigureCode.cpp +++ b/libOTe/TwoChooseOne/ConfigureCode.cpp @@ -7,10 +7,40 @@ #include "libOTe/Tools/QuasiCyclicCode.h" #include "libOTe/Tools/EACode/EACode.h" #include "libOTe/Tools/ExConvCode/ExConvCode.h" -#include "libOTe/Tools/ExConvCode/ExConvCode.h" +#include "libOTe/Tools/Spin/SpinCode.h" #include namespace osuCrypto { +#ifdef ENABLE_SPIN + // SPIN noise: N = 2K and the fewest partitions (a multiple of 8, at least + // 40) whose linear-attack bias reaches secParam. The tuning value 0.25 + // matches BAA; it is not a claim of 25% minimum distance (Turbo SPIN's + // certificates show distance above N/10 at K = 2^14, 2^16, ..., 2^26). + SdConfig SpinConfigure(u64 secParam, u64 requestSize, SdNoiseDistribution noiseType) + { + if (secParam > 1024 || + (noiseType != SdNoiseDistribution::Regular && noiseType != SdNoiseDistribution::Stationary)) + throw std::invalid_argument("Invalid SPIN noise configuration. " LOCATION); + const u64 n = 2 * SpinCode::messageSize(requestSize); + const double weight = std::floor(0.25 * double(n)); + const double multiplier = noiseType == SdNoiseDistribution::Regular ? 2 : 1; + const double minimumParts = std::ceil(double(secParam) / -std::log2(1 - multiplier * weight / n)); + const u64 first = std::max(40, roundUpTo(u64(minimumParts), 8)); + const u64 last = std::min(n / 4, first + 8192); + for (u64 parts = first; parts <= last; parts += 8) + { + // Padding outside the partitions does not count toward the weight. + const u64 per = (n / parts) & ~u64(1), active = parts * per; + const double effective = weight - double(n - active); + if (effective <= 0) + continue; + const double ratio = effective / double(active); + if (ratio < 0.5 && -double(parts) * std::log2(1 - multiplier * ratio) >= secParam) + return { n, parts, per }; + } + throw std::invalid_argument("SPIN noise configuration has no supported solution. " LOCATION); + } +#endif // Parameter selection deliberately combines two different safeguards. // diff --git a/libOTe/TwoChooseOne/Silent/SilentOtExtReceiver.cpp b/libOTe/TwoChooseOne/Silent/SilentOtExtReceiver.cpp index 0a2b953d..9841e080 100644 --- a/libOTe/TwoChooseOne/Silent/SilentOtExtReceiver.cpp +++ b/libOTe/TwoChooseOne/Silent/SilentOtExtReceiver.cpp @@ -763,7 +763,7 @@ namespace osuCrypto auto points = getPoints(); #ifdef ENABLE_SPIN if(mLpnMultType==MultType::Spin) - prepareSpin(mSpin,mRequestNumOts,mCodeSeed,true,mNoiseDist); + SpinCode::prepare(mSpin,mRequestNumOts,mCodeSeed,mNoiseDist); #endif if (packing == ChoiceBitPacking::True) @@ -807,7 +807,6 @@ namespace osuCrypto { #ifdef ENABLE_SPIN case MultType::Spin: - if(!mSpin) throw std::logic_error("SPIN is not configured"); mSpin->transpose(mA); break; #endif @@ -896,7 +895,6 @@ namespace osuCrypto { #ifdef ENABLE_SPIN case MultType::Spin: - if(!mSpin) throw std::logic_error("SPIN is not configured"); mSpin->transpose(mA); mSpin->transpose(mC); break; diff --git a/libOTe/TwoChooseOne/Silent/SilentOtExtReceiver.h b/libOTe/TwoChooseOne/Silent/SilentOtExtReceiver.h index b610ef9a..a057f352 100644 --- a/libOTe/TwoChooseOne/Silent/SilentOtExtReceiver.h +++ b/libOTe/TwoChooseOne/Silent/SilentOtExtReceiver.h @@ -12,7 +12,7 @@ #include #ifdef ENABLE_SILENTOT #ifdef ENABLE_SPIN -#include "libOTe/Tools/Spin/SpinOt.h" +#include "libOTe/Tools/Spin/SpinCode.h" #endif #include @@ -144,9 +144,10 @@ namespace osuCrypto // dense vectors from the sparse vectors. MultType mLpnMultType = DefaultMultType; #ifdef ENABLE_SPIN - // Optional preparation after configure(): initialize from - // (mRequestNumOts, mCodeSeed, true, mNoiseDist). clear() releases it. - std::unique_ptr mSpin; + // The SPIN encoder, prepared at the first compression. To prepare it + // ahead, emplace (mRequestNumOts, mCodeSeed, mNoiseDist) after + // configure(). configure() and clear() release it. + std::optional mSpin; #endif // The flag which controls whether the malicious check is performed. diff --git a/libOTe/TwoChooseOne/Silent/SilentOtExtSender.cpp b/libOTe/TwoChooseOne/Silent/SilentOtExtSender.cpp index 423bffe4..310aab06 100644 --- a/libOTe/TwoChooseOne/Silent/SilentOtExtSender.cpp +++ b/libOTe/TwoChooseOne/Silent/SilentOtExtSender.cpp @@ -725,7 +725,7 @@ namespace osuCrypto { #ifdef ENABLE_SPIN case MultType::Spin: - prepareSpin(mSpin,mRequestNumOts,mCodeSeed,false,mNoiseDist); + SpinCode::prepare(mSpin,mRequestNumOts,mCodeSeed,mNoiseDist); mSpin->transpose(mB); break; #endif diff --git a/libOTe/TwoChooseOne/Silent/SilentOtExtSender.h b/libOTe/TwoChooseOne/Silent/SilentOtExtSender.h index 019b7c6d..14579321 100644 --- a/libOTe/TwoChooseOne/Silent/SilentOtExtSender.h +++ b/libOTe/TwoChooseOne/Silent/SilentOtExtSender.h @@ -12,7 +12,7 @@ #include #ifdef ENABLE_SILENTOT #ifdef ENABLE_SPIN -#include "libOTe/Tools/Spin/SpinOt.h" +#include "libOTe/Tools/Spin/SpinCode.h" #endif #include @@ -134,9 +134,10 @@ namespace osuCrypto // dense vectors from the sparse vectors. MultType mLpnMultType = DefaultMultType; #ifdef ENABLE_SPIN - // Optional preparation after configure(): initialize from - // (mRequestNumOts, mCodeSeed, false, mNoiseDist). clear() releases it. - std::unique_ptr mSpin; + // The SPIN encoder, prepared at the first compression. To prepare it + // ahead, emplace (mRequestNumOts, mCodeSeed, mNoiseDist) after + // configure(). configure() and clear() release it. + std::optional mSpin; #endif // The flag which controls whether the malicious check is performed. diff --git a/libOTe_Tests/SilentOT_Tests.cpp b/libOTe_Tests/SilentOT_Tests.cpp index 8452aa60..fc301812 100644 --- a/libOTe_Tests/SilentOT_Tests.cpp +++ b/libOTe_Tests/SilentOT_Tests.cpp @@ -1255,15 +1255,13 @@ 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. +// Silent OT with the SPIN code (MultType::Spin): random and correlated OT, +// regular and stationary noise, at the minimum code size (8193 rounds up to +// K = 8320) and above. Runs on every CPU; SPIN picks its kernel at runtime. +// The SPIN encoder itself is tested by the SPIN library. void OtExt_Silent_Spin_Test(const oc::CLP& cmd) { #if defined(ENABLE_SILENTOT) && defined(ENABLE_SPIN) - if (!spin::capabilities().avx2) - throw UnitTestSkipped("SPIN requires AVX2"); - auto sockets = cp::LocalAsyncSocket::makePair(); std::vector nn = cmd.getManyOr("n", { 8193, 65537 }); bool verbose = cmd.getOr("v", 0) > 1; @@ -1273,6 +1271,7 @@ void OtExt_Silent_Spin_Test(const oc::CLP& cmd) SilentOtExtSender sender; SilentOtExtReceiver recver; + for (auto noise : { SdNoiseDistribution::Regular, SdNoiseDistribution::Stationary }) for (auto n : nn) { // Random OT. @@ -1280,8 +1279,8 @@ void OtExt_Silent_Spin_Test(const oc::CLP& cmd) std::vector> msg2(n); std::vector msg1(n); BitVector choice(n); - sender.configure(n, s, threads, SilentSecType::SemiHonest, SdNoiseDistribution::Regular, MultType::Spin); - recver.configure(n, s, threads, SilentSecType::SemiHonest, SdNoiseDistribution::Regular, MultType::Spin); + sender.configure(n, s, threads, SilentSecType::SemiHonest, noise, MultType::Spin); + recver.configure(n, s, threads, SilentSecType::SemiHonest, noise, MultType::Spin); fakeBase(n, s, threads, prng, recver, sender); auto p0 = sender.silentSend(msg2, prng, sockets[0]); auto p1 = recver.silentReceive(choice, msg1, prng, sockets[1]); @@ -1291,8 +1290,8 @@ void OtExt_Silent_Spin_Test(const oc::CLP& cmd) // Correlated OT. { - sender.configure(n, s, threads, SilentSecType::SemiHonest, SdNoiseDistribution::Regular, MultType::Spin); - recver.configure(n, s, threads, SilentSecType::SemiHonest, SdNoiseDistribution::Regular, MultType::Spin); + sender.configure(n, s, threads, SilentSecType::SemiHonest, noise, MultType::Spin); + recver.configure(n, s, threads, SilentSecType::SemiHonest, noise, MultType::Spin); auto type = ChoiceBitPacking::False; fakeBase(n, s, threads, prng, recver, sender); auto delta = *sender.mDelta; diff --git a/libOTe_Tests/cmakeTests/main.cpp b/libOTe_Tests/cmakeTests/main.cpp index e7228e48..e51cbfdd 100644 --- a/libOTe_Tests/cmakeTests/main.cpp +++ b/libOTe_Tests/cmakeTests/main.cpp @@ -4,33 +4,32 @@ #include "libOTe/config.h" #ifdef ENABLE_SPIN -#include +#include #include +// Installed-package check of the SPIN interface on any CPU: sizes, noise +// configuration, and agreement of the block and choice-byte transposes +// (choice byte i equals bit 0 of block i) across reseeds in both setup modes. static int spinConsumerCheck() { - if(!spin::capabilities().avx2) return 0; - const auto spec=osuCrypto::detail::spinProfile(4096); - if(spec.message_size!=8192) return 1; - const auto cfg=osuCrypto::SpinConfigure(128,4096,osuCrypto::SdNoiseDistribution::Regular); + using namespace osuCrypto; + if(SpinCode::messageSize(4096)!=8192) return 1; + const auto cfg=SpinConfigure(128,4096,SdNoiseDistribution::Regular); if(cfg.mNumPartitions!=128 || cfg.mNoiseVectorSize!=16384) return 2; - // Exercise the public installed-package interface, including the new - // refresh API and the generic workspace's live view of each map. - for(auto mode:{spin::SetupMode::Full,spin::SetupMode::BankedHeuristic}) { - osuCrypto::SpinCode code(spec,{}, {mode}); - auto workspace=code.make_workspace(); - auto generic=code.make_workspace(); - std::vector values(code.codeSize()); - std::vector words(code.codeSize()); - for(osuCrypto::u64 round=0;round<3;++round) { - code.setCodeSeed(osuCrypto::block(29+round,17+round)); - for(std::size_t i=0;i code; + for(u64 round=0;round<3;++round) { + SpinCode::prepare(code,4096,block(29+round,17+round),noise); + std::vector values(code->codeSize()); + std::vector choices(code->codeSize()); + for(std::size_t i=0;i(values,workspace); - code.transpose_inplace(words,generic); - for(std::size_t i=0;itranspose(values); + code->transpose(choices); + for(std::size_t i=0;imessageSize();++i) + if(choices[i]!=(values[i].get(0)&1)) return 3; } } return 0; diff --git a/thirdparty/getSpin.cmake b/thirdparty/getSpin.cmake index 3d38486a..ff2eb44f 100644 --- a/thirdparty/getSpin.cmake +++ b/thirdparty/getSpin.cmake @@ -1,5 +1,5 @@ set(GIT_REPOSITORY https://github.com/ladnir/spin_codes.git) -set(GIT_TAG "cf75e9ec293ba0438402d85f489cc39730210d91") +set(GIT_TAG "34a03e96291ab1b8ecd146f1f0507b4990758036") set(CLONE_DIR "${OC_THIRDPARTY_CLONE_DIR}/spin") set(BUILD_DIR "${CLONE_DIR}/out/build/${OC_CONFIG}") set(LOG_FILE "${CMAKE_CURRENT_LIST_DIR}/log-spin.txt")