diff --git a/README.md b/README.md index 0c66c24d..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.2 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 c4d49709..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.2 CONFIG) + find_dependency(spin 0.4.2 CONFIG) endif() diff --git a/cmake/libOTeDepHelper.cmake b/cmake/libOTeDepHelper.cmake index 88701c8a..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.2 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 1095dc13..8fba6c47 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 @@ -75,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; @@ -90,14 +91,19 @@ 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; @@ -157,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/Pprf/RegularPprf.h b/libOTe/Tools/Pprf/RegularPprf.h index b36a97de..24da969f 100644 --- a/libOTe/Tools/Pprf/RegularPprf.h +++ b/libOTe/Tools/Pprf/RegularPprf.h @@ -38,6 +38,224 @@ 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 + +#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) + { + 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 +661,9 @@ namespace osuCrypto REGULAR_PPRF_SIMD8(lane, { levels[0][0][lane] = current[lane]; }); +#ifdef OC_ENABLE_VAES + const pprfVaes::Key internalKey(mAesFixedKey); +#endif for (u64 localDepth = 0; localDepth + 1 < levels.size(); ++localDepth) { @@ -451,6 +672,15 @@ namespace osuCrypto auto parents = levels[localDepth]; auto children = levels[localDepth + 1]; const auto width = u64{ 1 } << localDepth; +#ifdef OC_ENABLE_VAES + { + 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()); + rightAccumulator = rightAccumulator ^ pprfVaes::fold8(laneSums1.data()); + } +#else for (u64 parentIdx = 0; parentIdx < width; ++parentIdx) { auto& parent = parents[parentIdx]; @@ -460,6 +690,7 @@ namespace osuCrypto mAesFixedKey, parent.data(), left.data(), right.data(), leftAccumulator, rightAccumulator); } +#endif const auto globalDepth = 3 + localDepth; (*encSumIter)[0] = leftAccumulator ^ @@ -546,6 +777,17 @@ namespace osuCrypto block leftAccumulator = ZeroBlock; block rightAccumulator = ZeroBlock; +#ifdef OC_ENABLE_VAES + { + 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(); + 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 +799,7 @@ namespace osuCrypto rightAccumulator); nativeLeaf += 8; } +#endif leafSums[0] = leftAccumulator; leafSums[1] = rightAccumulator; } @@ -974,6 +1217,9 @@ namespace osuCrypto REGULAR_PPRF_SIMD8(lane, { levels[0][0][lane] = current[lane]; }); +#ifdef OC_ENABLE_VAES + const pprfVaes::Key internalKey(mAesFixedKey); +#endif for (u64 localDepth = 0; localDepth + 1 < levels.size(); ++localDepth) { @@ -982,6 +1228,15 @@ namespace osuCrypto auto parents = levels[localDepth]; auto children = levels[localDepth + 1]; const auto width = u64{ 1 } << localDepth; +#ifdef OC_ENABLE_VAES + { + 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()); + rightAccumulator = rightAccumulator ^ pprfVaes::fold8(laneSums1.data()); + } +#else for (u64 parentIdx = 0; parentIdx < width; ++parentIdx) { auto& parent = parents[parentIdx]; @@ -991,6 +1246,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 +1354,17 @@ namespace osuCrypto block leftAccumulator = gGgmAes[0].hashBlock(ZeroBlock); block rightAccumulator = gGgmAes[1].hashBlock(ZeroBlock); +#ifdef OC_ENABLE_VAES + { + 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(); + 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 +1376,7 @@ namespace osuCrypto rightAccumulator); nativeLeaf += 8; } +#endif leafSums[0] = leftAccumulator; leafSums[1] = rightAccumulator; } diff --git a/libOTe/Tools/Spin/README.md b/libOTe/Tools/Spin/README.md index 7dda239f..79233bbf 100644 --- a/libOTe/Tools/Spin/README.md +++ b/libOTe/Tools/Spin/README.md @@ -7,95 +7,79 @@ 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. -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 -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 changes small routing parameters and IMT masks; - 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. +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. -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. +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. -## Generic coefficients +## Preparation -`SpinCode` compresses 2K coefficients to K using the same binary linear map: +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::T64S12R2, - .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. -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. +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 eaa83e89..14f14161 100644 --- a/libOTe/Tools/Spin/SpinCode.h +++ b/libOTe/Tools/Spin/SpinCode.h @@ -1,70 +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 +#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;} + // 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; + } - 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; - }; - template - using Workspace = std::conditional_t,spin::PreparedEncoder::Workspace,GenericWorkspace>; + SpinCode(u64 requested, block seed, SdNoiseDistribution noise) + : mEncoder({ messageSize(requested), parameters, seed.get(0), seed.get(1) }, setup(noise)) + , mBlocks(mEncoder.make_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)); + // 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); } - 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); + + 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); } } + +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 a69ab812..00000000 --- a/libOTe/Tools/Spin/SpinOt.cpp +++ /dev/null @@ -1,72 +0,0 @@ -#include "SpinOt.h" -#ifdef ENABLE_SPIN -#include -#include -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; - 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)}; -} -} - -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 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.make_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);} -void SpinOtState::transpose(span x) { - if(!choices) throw std::logic_error("SPIN choice workspace was not prepared"); - code.transpose_inplace(x,*choices); -} -} -#endif diff --git a/libOTe/Tools/Spin/SpinOt.h b/libOTe/Tools/Spin/SpinOt.h deleted file mode 100644 index 5718f3ea..00000000 --- a/libOTe/Tools/Spin/SpinOt.h +++ /dev/null @@ -1,30 +0,0 @@ -#pragma once -#include "libOTe/Tools/Spin/SpinCode.h" -#include "libOTe/TwoChooseOne/ConfigureCode.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; - std::optional> choices; - 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 4b322902..310aab06 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 @@ -683,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 325d2844..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 "f2010e03d2dbe5003e90c89ba346c743793536a6") +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")