diff --git a/README.md b/README.md index b65256d84..7b7295b0a 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,12 @@ python3 build.py The output library `secure-join` and executable `frontend` will be written to `out/build//`. The `frontend` can perform PSI based on files as input sets and communicate via sockets. See the output of `frontend` for details. +### Correlation modes + +Both peers select the noise mode in the final argument of `CorGenerator::init`. The default, `oc::SdNoiseDistribution::Regular`, samples fresh PPRF noise for each batch and shares one immutable full SPIN map per padded size within a process. Each worker owns its scratch. + +With `oc::SdNoiseDistribution::Stationary`, use the same logical worker count and batch size on both peers. Each worker keeps its own bank per padded size, and each stream refreshes its active code every round. Banked SPIN uses the heuristic setup. Reusing the generator across joins retains public banks and starts a fresh private session. To benchmark a join with stationary noise, run `secJoinfrontend -bench -join -nn 12 -nt 2 -mock 0 -stationary`. + ### Installing The library and any fetched dependancies can be installed. diff --git a/cmake/findDependancies.cmake b/cmake/findDependancies.cmake index 4124fac63..19c3d00ee 100644 --- a/cmake/findDependancies.cmake +++ b/cmake/findDependancies.cmake @@ -12,7 +12,7 @@ set(CMAKE_PREFIX_PATH "${SECUREJOIN_THIRDPARTY_DIR};${CMAKE_PREFIX_PATH}") macro(FIND_LIBOTE) set(ARGS ${ARGN}) - set(COMPS) + set(COMPS spin) if(SECUREJOIN_ENABLE_ASAN) set(COMPS ${COMPS} asan) diff --git a/frontend/benchmark.cpp b/frontend/benchmark.cpp index bc7dc6b2f..ec348a909 100644 --- a/frontend/benchmark.cpp +++ b/frontend/benchmark.cpp @@ -6,7 +6,12 @@ namespace secJoin { - void CorGen_benchmark(const oc::CLP& cmd) + static oc::SdNoiseDistribution benchmarkNoise(const oc::CLP& cmd) + { + return cmd.isSet("stationary") ? oc::SdNoiseDistribution::Stationary : oc::SdNoiseDistribution::Regular; + } + + void CorGen_benchmark(const oc::CLP& cmd) { // request size u64 n = cmd.getOr("n", 1ull << cmd.getOr("nn", 20)); @@ -35,28 +40,21 @@ namespace secJoin macoro::thread_pool pool1; auto e1 = pool1.make_work(); pool1.create_threads(nt); - auto sock = coproto::LocalAsyncSocket::makePair(); - sock[0].setExecutor(pool0); - sock[1].setExecutor(pool1); oc::Timer timer; - - - std::vector x(n); - std::vector y0(n), y1(n); - - PRNG prng0(oc::ZeroBlock); PRNG prng1(oc::OneBlock); for (u64 trial = 0; trial < trials; ++trial) { - //timer.setTimePoint("begin"); + auto sock = coproto::LocalAsyncSocket::makePair(); + sock[0].setExecutor(pool0); + sock[1].setExecutor(pool1); CorGenerator g[2]; auto begin = timer.setTimePoint("begin trial ------------- "); - g[0].init(std::move(sock[0]), prng0, 0, nt, batch, false); - g[1].init(std::move(sock[1]), prng1, 1, nt, batch, false); + g[0].init(std::move(sock[0]), prng0, 0, nt, batch, false, benchmarkNoise(cmd)); + g[1].init(std::move(sock[1]), prng1, 1, nt, batch, false, benchmarkNoise(cmd)); g[0].mGenState->mPool = &pool0; g[1].mGenState->mPool = &pool1; @@ -216,8 +214,8 @@ namespace secJoin for (u64 t = 0; t < trials; ++t) { - g[0].init(sock2[0].fork(), prng0, 0, nt, 1 << batch, mock); - g[1].init(sock2[1].fork(), prng1, 1, nt, 1 << batch, mock); + g[0].init(sock2[0].fork(), prng0, 0, nt, 1 << batch, mock, benchmarkNoise(cmd)); + g[1].init(sock2[1].fork(), prng1, 1, nt, 1 << batch, mock, benchmarkNoise(cmd)); g[0].mGenState->mPool = &pool0; g[1].mGenState->mPool = &pool1; @@ -255,8 +253,6 @@ namespace secJoin u64 nL = cmd.getOr("Ln", 1ull << cmd.getOr("Lnn", cmd.getOr("nn", 10))); u64 nR = cmd.getOr("Rn", 1ull << cmd.getOr("Rnn", cmd.getOr("nn", 10))); - u64 dL = cmd.getOr("Ld", cmd.getOr("d", 10)); - u64 dR = cmd.getOr("Rd", cmd.getOr("d", 10)); auto b = cmd.getOr("b", 16); u64 keySize = cmd.getOr("m", 32); @@ -274,6 +270,21 @@ namespace secJoin {"R2", ColumnType::Int, 7} } }); + if (!keySize || (keySize < 64 && nL > (u64(1) << keySize))) + throw std::invalid_argument("Join benchmark needs distinct left keys"); + for (u64 i = 0; i < nL; ++i) + { + oc::copyBytesMin(L.mColumns[0].mData.mData[i], i); + oc::copyBytesMin(L.mColumns[1].mData.mData[i], i); + } + for (u64 i = 0; i < nR; ++i) + { + const u64 key = i / 2; + oc::copyBytesMin(R.mColumns[0].mData.mData[i], key); + R.mColumns[1].mData.mData(i, 0) = i & 127; + } + R.mColumns[0].mData.trim(); + PRNG prng(oc::ZeroBlock); std::array Ls, Rs; L.share(Ls, prng); @@ -294,10 +305,11 @@ namespace secJoin sock2[1].setExecutor(pool1); OmJoin join0, join1; + join0.mSort.mL = join1.mSort.mL = cmd.getOr("radixBits", join0.mSort.mL); CorGenerator ole0, ole1; - ole0.init(sock2[0].fork(), prng, 0, nt, 1 << b, mock); - ole1.init(sock2[1].fork(), prng, 1, nt, 1 << b, mock); + ole0.init(sock2[0].fork(), prng, 0, nt, 1 << b, mock, benchmarkNoise(cmd)); + ole1.init(sock2[1].fork(), prng, 1, nt, 1 << b, mock, benchmarkNoise(cmd)); ole0.mGenState->mPool = &pool0; ole1.mGenState->mPool = &pool1; @@ -327,10 +339,22 @@ namespace secJoin )); auto end = timer.setTimePoint("end"); - std::cout << "OmJoin Ln:" << nL << ", Rn:" << nR << " m:" << keySize << " Ld: " << dL << ", Rd:" << dR << " ~ " << - std::chrono::duration_cast(end - begin).count() << "ms " << - sock[0].bytesSent() / double(nL + nR) << "+" << sock[0].bytesReceived() / double(nL + nR) << "=" << - (sock[0].bytesSent() + sock[0].bytesReceived()) / double(nL + nR) << " bytes/elem " << std::endl; + std::apply([](auto&... task) { (task.result(), ...); }, r); + auto actual = reveal(out[0], out[1], true); + exp.extractActive(); + exp.sort(); + actual.sort(); + if (actual != exp) + throw std::runtime_error("Secure join disagrees with the plaintext result"); + + const double rows = double(nL + nR); + const u64 online = sock[0].bytesSent() + sock[0].bytesReceived(); + const u64 preprocessing = sock2[0].bytesSent() + sock2[0].bytesReceived(); + std::cout << "OmJoin Ln:" << nL << ", Rn:" << nR << " m:" << keySize + << " radix bits:" << join0.mSort.mL << " ~ " + << std::chrono::duration_cast(end - begin).count() << "ms " + << online / rows << " online + " << preprocessing / rows << " preprocessing = " + << (online + preprocessing) / rows << " bytes/elem" << std::endl; if (cmd.isSet("timing")) std::cout << timer << std::endl; @@ -343,7 +367,7 @@ namespace secJoin u64 n = cmd.getOr("n", 1ull << cmd.getOr("nn", 10)); u64 trials = cmd.getOr("trials", 1); - bool nt = cmd.getOr("nt", 1); + u64 nt = cmd.getOr("nt", 1); auto useOle = cmd.isSet("ole"); oc::Timer timer; @@ -384,8 +408,8 @@ namespace secJoin //sender.setKey(kk); CorGenerator ole0, ole1; - ole0.init(sock2[0].fork(), prng0, 0, nt, 1 << 18, cmd.getOr("mock", 1)); - ole1.init(sock2[1].fork(), prng1, 1, nt, 1 << 18, cmd.getOr("mock", 1)); + ole0.init(sock2[0].fork(), prng0, 0, nt, 1 << 18, cmd.getOr("mock", 1), benchmarkNoise(cmd)); + ole1.init(sock2[1].fork(), prng1, 1, nt, 1 << 18, cmd.getOr("mock", 1), benchmarkNoise(cmd)); prng0.get(x.data(), x.size()); @@ -450,67 +474,73 @@ namespace secJoin { #ifdef ENABLE_SILENTOT using namespace oc; - try - { - - SilentOtExtSender sender; - SilentOtExtReceiver recver; - - u64 trials = cmd.getOr("t", 10); - - u64 n = cmd.getOr("n", 1ull << cmd.getOr("nn", 20)); - MultType multType = (MultType)cmd.getOr("m", (int)MultType::Tungsten); - std::cout << multType << std::endl; + SilentOtExtSender sender; + SilentOtExtReceiver recver; - recver.mMultType = multType; - sender.mMultType = multType; + u64 trials = cmd.getOr("t", 10); - PRNG prng0(ZeroBlock), prng1(ZeroBlock); - block delta = prng0.get(); + u64 n = cmd.getOr("n", 1ull << cmd.getOr("nn", 20)); + MultType multType = (MultType)cmd.getOr("m", (int)MultType::Spin); + std::cout << multType << std::endl; - auto sock = coproto::LocalAsyncSocket::makePair(); - Timer sTimer; - Timer rTimer; - auto s = rTimer.setTimePoint("start"); - sender.setTimer(rTimer); - recver.setTimer(rTimer); - for (u64 t = 0; t < trials; ++t) - { - sender.configure(n); - recver.configure(n); + PRNG prng0(ZeroBlock), prng1(ZeroBlock); + block delta = prng0.get(); - auto choice = recver.sampleBaseChoiceBits(prng0); - std::vector> sendBase(sender.silentBaseOtCount()); - std::vector recvBase(recver.silentBaseOtCount()); - sender.setSilentBaseOts(sendBase); - recver.setSilentBaseOts(recvBase); - - auto p0 = sender.silentSendInplace(delta, n, prng0, sock[0]); - auto p1 = recver.silentReceiveInplace(n, prng1, sock[1], oc::ChoiceBitPacking::True); + auto sock = coproto::LocalAsyncSocket::makePair(); - rTimer.setTimePoint("r start"); - coproto::sync_wait(macoro::when_all_ready( - std::move(p0), std::move(p1))); - rTimer.setTimePoint("r done"); + Timer sTimer; + Timer rTimer; + const auto noise = benchmarkNoise(cmd); + auto s = rTimer.setTimePoint("start"); + sender.setTimer(rTimer); + recver.setTimer(rTimer); + for (u64 t = 0; t < trials; ++t) + { + if (t == 0 || (noise == SdNoiseDistribution::Regular && multType != MultType::Spin)) + { + sender.configure(n, 2, 1, SilentSecType::SemiHonest, noise, multType); + recver.configure(n, 2, 1, SilentSecType::SemiHonest, noise, multType); + if (noise == SdNoiseDistribution::Regular && multType == MultType::Spin) + { + prepareRegularSpin(sender.mSpin, n); + prepareRegularSpin(recver.mSpin, n); + } + } + + auto choice = recver.sampleBaseChoiceBits(prng0); + std::vector> sendBase(sender.baseCount().mBaseOtCount); + std::vector recvBase(recver.baseCount().mBaseOtCount); + oc::BitVector c(sender.baseCount().mBaseVoleCount); + c.randomize(prng0); + std::vector b(c.size(), ZeroBlock), a(c.size()); + for (u64 i = 0; i < c.size(); ++i) + a[i] = c[i] ? delta : ZeroBlock; + sender.setBaseCors(sendBase, b, delta); + recver.setBaseCors(recvBase, choice, a, c); + + auto p0 = sender.silentSendInplace(delta, n, prng0, sock[0]); + auto p1 = recver.silentReceiveInplace(n, prng1, sock[1], oc::ChoiceBitPacking::True); + + rTimer.setTimePoint("r start"); + auto results = coproto::sync_wait(macoro::when_all_ready( + std::move(p0), std::move(p1))); + std::get<0>(results).result(); + std::get<1>(results).result(); + rTimer.setTimePoint("r done"); - } - auto e = rTimer.setTimePoint("end"); + } + auto e = rTimer.setTimePoint("end"); - auto time = std::chrono::duration_cast(e - s).count(); - auto avgTime = time / double(trials); - auto timePer512 = avgTime / n * 512; - std::cout << "OT n:" << n << ", " << - avgTime << "ms/batch, " << timePer512 << "ms/512ot" << std::endl; + auto time = std::chrono::duration_cast(e - s).count(); + auto avgTime = time / double(trials); + auto timePer512 = avgTime / n * 512; + std::cout << "OT n:" << n << ", " << + avgTime << "ms/batch, " << timePer512 << "ms/512ot" << std::endl; - std::cout << rTimer << std::endl; + std::cout << rTimer << std::endl; - std::cout << sock[0].bytesReceived() / trials << " " << sock[1].bytesReceived() / trials << " bytes per " << std::endl; - } - catch (std::exception& e) - { - std::cout << e.what() << std::endl; - } + std::cout << sock[0].bytesReceived() / trials << " " << sock[1].bytesReceived() / trials << " bytes per " << std::endl; #else std::cout << "ENABLE_SILENTOT = false" << std::endl; #endif @@ -521,82 +551,80 @@ namespace secJoin { #ifdef ENABLE_SILENTOT using namespace oc; - try - { + SilentF4VoleReceiver recver; + SilentF4VoleSender sender; - SilentF4VoleReceiver recver; - SilentF4VoleSender sender; + u64 trials = cmd.getOr("t", 10); - u64 trials = cmd.getOr("t", 10); - - u64 n = cmd.getOr("n", 1ull << cmd.getOr("nn", 20)); - MultType multType = (MultType)cmd.getOr("m", (int)MultType::Tungsten); - std::cout << multType << std::endl; + u64 n = cmd.getOr("n", 1ull << cmd.getOr("nn", 20)); + MultType multType = (MultType)cmd.getOr("m", (int)MultType::Spin); + std::cout << multType << std::endl; - recver.mMultType = multType; - sender.mMultType = multType; + recver.mMultType = multType; + sender.mMultType = multType; - PRNG prng0(ZeroBlock), prng1(ZeroBlock); - block delta = prng0.get() & block(~0ull, ~0ull << 2); + PRNG prng0(ZeroBlock), prng1(ZeroBlock); + block delta = prng0.get() & block(~0ull, ~0ull << 2); - auto sock = coproto::LocalAsyncSocket::makePair(); + auto sock = coproto::LocalAsyncSocket::makePair(); - Timer sTimer; - Timer rTimer; - auto s = rTimer.setTimePoint("start"); - sender.setTimer(rTimer); - recver.setTimer(rTimer); - for (u64 t = 0; t < trials; ++t) - { - sender.configure(n); - recver.configure(n); + Timer sTimer; + Timer rTimer; + const auto noise = benchmarkNoise(cmd); + auto s = rTimer.setTimePoint("start"); + sender.setTimer(rTimer); + recver.setTimer(rTimer); + for (u64 t = 0; t < trials; ++t) + { + if (t == 0 || noise == SdNoiseDistribution::Regular) + { + sender.configure(n, SilentBaseType::BaseExtend, 128, {}, noise); + recver.configure(n, SilentBaseType::BaseExtend, 128, {}, noise); + } - auto choice = recver.sampleBaseChoiceBits(prng0); - auto cBase = recver.sampleBaseVoleVals(prng0); + auto choice = recver.sampleBaseChoiceBits(prng0); + auto cBase = recver.sampleBaseVoleVals(prng0); - std::vector bBase(cBase.size()), aBase(cBase.size()); + std::vector bBase(cBase.size()), aBase(cBase.size()); - prng0.get(aBase.data(), aBase.size()); - CoeffCtxGF4 ctx; + prng0.get(aBase.data(), aBase.size()); + CoeffCtxGF4 ctx; - for (u64 i = 0; i < aBase.size(); ++i) - { - aBase[i] &= block(~0ull, ~0ull << 2); - ctx.mul(bBase[i], delta, cBase[i]); - ctx.plus(bBase[i], bBase[i], aBase[i]); - } + for (u64 i = 0; i < aBase.size(); ++i) + { + aBase[i] &= block(~0ull, ~0ull << 2); + ctx.mul(bBase[i], delta, cBase[i]); + ctx.plus(bBase[i], bBase[i], aBase[i]); + } - std::vector> sendBase(sender.silentBaseOtCount()); - std::vector recvBase(recver.silentBaseOtCount()); - sender.setSilentBaseOts(sendBase, bBase); - recver.setSilentBaseOts(recvBase, aBase); + std::vector> sendBase(sender.silentBaseOtCount()); + std::vector recvBase(recver.silentBaseOtCount()); + sender.setSilentBaseOts(sendBase, bBase); + recver.setSilentBaseOts(recvBase, aBase); - auto p0 = sender.silentSendInplace(delta, n, prng0, sock[0]); - auto p1 = recver.silentReceiveInplace(n, prng1, sock[1]); + auto p0 = sender.silentSendInplace(delta, n, prng0, sock[0]); + auto p1 = recver.silentReceiveInplace(n, prng1, sock[1]); - rTimer.setTimePoint("r start"); - coproto::sync_wait(macoro::when_all_ready( - std::move(p0), std::move(p1))); - rTimer.setTimePoint("r done"); + rTimer.setTimePoint("r start"); + auto results = coproto::sync_wait(macoro::when_all_ready( + std::move(p0), std::move(p1))); + std::get<0>(results).result(); + std::get<1>(results).result(); + rTimer.setTimePoint("r done"); - } - auto e = rTimer.setTimePoint("end"); + } + auto e = rTimer.setTimePoint("end"); - auto time = std::chrono::duration_cast(e - s).count(); - auto avgTime = time / double(trials); - auto timePer512 = avgTime / n * 512; - std::cout << "F4 n:" << n << ", " << - avgTime << "ms/batch, " << timePer512 << "ms/512ot" << std::endl; + auto time = std::chrono::duration_cast(e - s).count(); + auto avgTime = time / double(trials); + auto timePer512 = avgTime / n * 512; + std::cout << "F4 n:" << n << ", " << + avgTime << "ms/batch, " << timePer512 << "ms/512ot" << std::endl; - if (cmd.isSet("verbose")) - { - std::cout << rTimer << std::endl; - std::cout << sock[0].bytesReceived() / trials << " " << sock[1].bytesReceived() / trials << " bytes per " << std::endl; - } - } - catch (std::exception& e) + if (cmd.isSet("verbose")) { - std::cout << e.what() << std::endl; + std::cout << rTimer << std::endl; + std::cout << sock[0].bytesReceived() / trials << " " << sock[1].bytesReceived() / trials << " bytes per " << std::endl; } #else std::cout << "ENABLE_SILENTOT = false" << std::endl; @@ -644,8 +672,8 @@ namespace secJoin CorGenerator ole0, ole1; - ole0.init(std::move(sock2[0]), prng0, 0, nt, 1 << b, cmd.getOr("mock", 1)); - ole1.init(std::move(sock2[1]), prng1, 1, nt, 1 << b, cmd.getOr("mock", 1)); + ole0.init(std::move(sock2[0]), prng0, 0, nt, 1 << b, cmd.getOr("mock", 1), benchmarkNoise(cmd)); + ole1.init(std::move(sock2[1]), prng1, 1, nt, 1 << b, cmd.getOr("mock", 1), benchmarkNoise(cmd)); ole0.mGenState->mPool = &pool0; ole1.mGenState->mPool = &pool1; diff --git a/frontend/main.cpp b/frontend/main.cpp index 95fa8b629..8ee2a7454 100644 --- a/frontend/main.cpp +++ b/frontend/main.cpp @@ -96,9 +96,5 @@ int main(int argc, char** argv) } tests += secJoin_Tests::Tests; - tests.runIf(clp); - // secJoin_Tests::Tests.runAll(); - - return 0; - + return tests.runIf(clp) == oc::TestCollection::Result::failed ? 1 : 0; } diff --git a/secure-join/AggTree/AggTree.cpp b/secure-join/AggTree/AggTree.cpp index a3ca5187a..fc203dd39 100644 --- a/secure-join/AggTree/AggTree.cpp +++ b/secure-join/AggTree/AggTree.cpp @@ -662,12 +662,9 @@ namespace secJoin assert(srcStart + size <= src.bytesPerRow()); for (u64 k = 0; k < bitsPerEntry; ++k) { - for (u64 j = 0; j < 2; ++j) - { - auto ss0 = src[k].subspan(srcStart, size); - auto dd0 = dst[k].subspan(dstStart, size); - osuCrypto::copyBytes(dd0, ss0); - } + auto ss = src[k].subspan(srcStart, size); + auto dd = dst[k].subspan(dstStart, size); + osuCrypto::copyBytes(dd, ss); } }; diff --git a/secure-join/AggTree/Level.h b/secure-join/AggTree/Level.h index 1db5ca043..88c6749e4 100644 --- a/secure-join/AggTree/Level.h +++ b/secure-join/AggTree/Level.h @@ -229,60 +229,28 @@ namespace secJoin vals[0].resize(oc::divCeil(n, 2), bitCount); vals[1].resize(n / 2, bitCount); - auto n = available / 2; u64 i = 0, d = offset / 2; - // std::cout << "d " << d << std::endl; - for (; i < available2 - 2; i += 2, ++d) + for (; i < available2; i += 2, ++d) { - osuCrypto::copyBytes(vals[0][d], src[i + 0].subspan(0, byteCount)); - osuCrypto::copyBytes(vals[1][d], src[i + 1].subspan(0, byteCount)); + osuCrypto::copyBytes(vals[0][d], src[i].first(byteCount)); + osuCrypto::copyBytes(vals[1][d], src[i + 1].first(byteCount)); *oc::BitIterator(mLeftRight[0].mSufBit.data(), d) = controlBits[i + 1]; - *oc::BitIterator(mLeftRight[1].mSufBit.data(), d) = controlBits[i + 2]; - } - - { - osuCrypto::copyBytes(vals[0][d], src[i + 0].subspan(0, byteCount)); - osuCrypto::copyBytes(vals[1][d], src[i + 1].subspan(0, byteCount)); - - auto cLast = 0; - if (i + 2 < controlBits.size()) - { - cLast = controlBits[i + 2]; - // std::cout << "act clast " << d*2+1<< ": " << (int)cLast << " = c[" << i + 2 << "]" << std::endl; - } - - *oc::BitIterator(mLeftRight[0].mSufBit.data(), d) = controlBits[i + 1]; - *oc::BitIterator(mLeftRight[1].mSufBit.data(), d) = cLast; - - i += 2; - ++d; + *oc::BitIterator(mLeftRight[1].mSufBit.data(), d) = + i + 2 < controlBits.size() ? controlBits[i + 2] : 0; } - if (available & 1) { - osuCrypto::copyBytes(vals[0][d], src[i + 0].subspan(0, byteCount)); - osuCrypto::setBytes(vals[1][d], 0); - - auto cLast = 0; - if (i + 1 < controlBits.size()) - { - cLast = controlBits[i + 1]; - std::cout << "act clast* " << (int)cLast << std::endl; - } - - *oc::BitIterator(mLeftRight[0].mSufBit.data(), d) = cLast; + osuCrypto::copyBytes(vals[0][d], src[i].first(byteCount)); + *oc::BitIterator(mLeftRight[0].mSufBit.data(), d) = + i + 1 < controlBits.size() ? controlBits[i + 1] : 0; *oc::BitIterator(mLeftRight[1].mSufBit.data(), d) = 0; - ++d; } - - // if there is space left over fill with zeros + // vals is zero-initialized. Clear the corresponding control bits. for (; d < n / 2; ++d) { - osuCrypto::setBytes(vals[0][d], 0); - osuCrypto::setBytes(vals[1][d], 0); - *oc::BitIterator(mLeftRight[0].mPreBit.data(), d) = 0; - *oc::BitIterator(mLeftRight[1].mPreBit.data(), d) = 0; + *oc::BitIterator(mLeftRight[0].mSufBit.data(), d) = 0; + *oc::BitIterator(mLeftRight[1].mSufBit.data(), d) = 0; } vals[0].transpose(mLeftRight[0].mSufVal); diff --git a/secure-join/CMakeLists.txt b/secure-join/CMakeLists.txt index 46593542c..6487f19de 100644 --- a/secure-join/CMakeLists.txt +++ b/secure-join/CMakeLists.txt @@ -14,6 +14,7 @@ set(SRCS "CorGenerator/CorGenerator.cpp" "CorGenerator/Request.cpp" "CorGenerator/Batch.cpp" + "CorGenerator/SpinWorker.cpp" "CorGenerator/OtBatch.cpp" "CorGenerator/BinOleBatch.cpp" "CorGenerator/TritOtBatch.cpp" diff --git a/secure-join/CorGenerator/Base.h b/secure-join/CorGenerator/Base.h index 816c441ce..018a1668e 100644 --- a/secure-join/CorGenerator/Base.h +++ b/secure-join/CorGenerator/Base.h @@ -18,6 +18,13 @@ namespace secJoin { + template + void configureBatchOt(SilentOt& ot, u64 size) + { + ot.configure(size, 2, 1, oc::SilentSecType::SemiHonest, + oc::SdNoiseDistribution::Regular, oc::MultType::Spin); + } + // A struct used to track base correlations requests. // These requests will be used as inputs to the batches // that will generate the end user correlations. @@ -29,6 +36,9 @@ namespace secJoin // the number of send OTs requested u64 mSendSize = 0; + // Fresh binary VOLEs requested for stationary noise. + u64 mSendBinaryVoles = 0, mRecvBinaryVoles = 0; + // the number of F4 voles. u64 mSendVoleSize = 0; @@ -45,7 +55,11 @@ namespace secJoin { u64 s = 0; for (u64 i = 0; i < reqs.size(); ++i) + { s += reqs[i].mChoice.size(); + mSendBinaryVoles += reqs[i].mSendBinaryVoles; + mRecvBinaryVoles += reqs[i].mRecvBinaryVoles; + } mChoice.reserve(s); for (u64 i = 0; i < reqs.size(); ++i) mChoice.append(reqs[i].mChoice); @@ -88,7 +102,12 @@ namespace secJoin // the index of the next recv VOLE that can be consumed. u64 mVoleRecvIndex = 0; - // the recv VOLE delta. + u64 mBinarySendIndex = 0, mBinaryRecvIndex = 0; + block mBinaryDelta; + oc::AlignedUnVector mBinaryA, mBinaryB; + oc::BitVector mBinaryChoice; + + // the GF(4) sender delta. block mVoleDelta; // mVoleA = mVoleB + mVoleChoice * mVoleDelta @@ -119,6 +138,13 @@ namespace secJoin return get(mOtRecvMsg, mOtRecvIndex, n); } + void setOtBase(oc::SilentOtExtReceiver& receiver) + { + const auto n = receiver.baseCount().mBaseOtCount; + auto choices = mOtRecvChoice.subvec(mOtRecvIndex, n); + receiver.setBaseCors(getRecvOt(n), choices, {}, {}); + } + span getRecvVole(u64 n) { return get(mVoleA, mVoleRecvIndex, n); diff --git a/secure-join/CorGenerator/Batch.cpp b/secure-join/CorGenerator/Batch.cpp index 9d3a2c6d5..2fdddda7b 100644 --- a/secure-join/CorGenerator/Batch.cpp +++ b/secure-join/CorGenerator/Batch.cpp @@ -32,6 +32,24 @@ namespace secJoin } + macoro::task<> Batch::run(BatchThreadState& worker) + { + try + { + co_await getTask(worker); + co_return; + } + catch (...) + { + mError = std::current_exception(); + } + mGenState->abort(); + mCorReady.set(); + if (!mSock.closed()) + co_await mSock.close(); + std::rethrow_exception(mError); + } + void Batch::start() { if (mStarted.exchange(true) == false) diff --git a/secure-join/CorGenerator/Batch.h b/secure-join/CorGenerator/Batch.h index 1ac684d4c..81d5cf810 100644 --- a/secure-join/CorGenerator/Batch.h +++ b/secure-join/CorGenerator/Batch.h @@ -10,6 +10,7 @@ #include "macoro/manual_reset_event.h" #include "Correlations.h" +#include "SpinWorker.h" namespace secJoin { @@ -17,7 +18,13 @@ namespace secJoin struct BatchThreadState { - oc::AlignedUnVector mA, mB, mEncodeTemp, mPprfTemp; + oc::AlignedUnVector mA, mB; + oc::pprf::ExpandTreeBuffer mPprfTemp; + std::optional mSpin; + std::unique_ptr mStationary; + BatchThreadState() = default; + BatchThreadState(const BatchThreadState&) = delete; + BatchThreadState(BatchThreadState&&) = default; macoro::eager_task<> mTask; }; @@ -60,9 +67,12 @@ namespace secJoin // decides who is first. std::atomic_bool mStarted = false; - virtual BaseRequest getBaseRequest() = 0; + std::exception_ptr mError; + macoro::task<> run(BatchThreadState& worker); - virtual void setBase(BaseCor& cor) = 0; + virtual BaseRequest getBaseRequest(StationaryWorker* worker) = 0; + + virtual void setBase(BaseCor& cor, StationaryWorker* worker) = 0; // Get the task associated with this batch. If the task // has already been retrieved, this will be empty. diff --git a/secure-join/CorGenerator/BinOleBatch.cpp b/secure-join/CorGenerator/BinOleBatch.cpp index 8379835cf..b1d43b4b4 100644 --- a/secure-join/CorGenerator/BinOleBatch.cpp +++ b/secure-join/CorGenerator/BinOleBatch.cpp @@ -1,7 +1,7 @@ #include "BinOleBatch.h" #include "CorGenerator.h" #include "secure-join/Util/match.h" -#include "secure-join/Util/Simd.h" +#include "PackedOtHash.h" #include namespace secJoin @@ -28,39 +28,45 @@ namespace secJoin d.mMult = mMult.subspan(begin / 128, size / 128); } - BaseRequest OleBatch::getBaseRequest() + BaseRequest OleBatch::getBaseRequest(StationaryWorker* worker) { BaseRequest r; if (mGenState->mMock) return r; + if (worker) + return worker->requestOtBase(CorType::Ole, mSize, mSendRecv.index() == 0, mPrng); + mSendRecv | match{ [&](SendBatch& send) { - send.mSender.configure(mSize); - r.mSendSize = send.mSender.silentBaseOtCount(); + configureBatchOt(send.mSender, mSize); + r.mSendSize = send.mSender.baseCount().mBaseOtCount; }, [&](RecvBatch& recv) { - recv.mReceiver.configure(mSize); + configureBatchOt(recv.mReceiver, mSize); r.mChoice = recv.mReceiver.sampleBaseChoiceBits(mPrng); } }; return r; } - void OleBatch::setBase(BaseCor& sMsg) + void OleBatch::setBase(BaseCor& sMsg, StationaryWorker* worker) { if (mGenState->mMock) return; + if (worker) + return worker->setOtBase(CorType::Ole, mSize, mSendRecv.index() == 0, sMsg); + mSendRecv | match{ [&](SendBatch& send) { - send.mSender.setSilentBaseOts(sMsg.getSendOt(send.mSender.silentBaseOtCount())); + send.mSender.setBaseCors(sMsg.getSendOt(send.mSender.baseCount().mBaseOtCount), {}, mPrng.get()); }, [&](RecvBatch& recv) { - recv.mReceiver.setSilentBaseOts(sMsg.getRecvOt(recv.mReceiver.silentBaseOtCount())); + sMsg.setOtBase(recv.mReceiver); } }; } @@ -175,18 +181,26 @@ namespace secJoin { mock(batchIdx, add, mult); } + else if (threadState.mStationary) + { + auto& worker = *threadState.mStationary; + auto& protocol = worker.begin(worker.recvOt, CorType::Ole, size, false); + co_await protocol.silentReceiveInplace(size, prng, sock, oc::ChoiceBitPacking::True); + compressRecver(protocol.mA, add, mult); + worker.finish(protocol); + } else { if (state->mDebug) { - baseSend.resize(mReceiver.silentBaseOtCount()); + baseSend.resize(mReceiver.baseCount().mBaseOtCount); co_await sock.recv(baseSend); { for (u64 i = 0; i < baseSend.size(); ++i) { - if (mReceiver.mGen.mBaseOTs(i) != baseSend[i][mReceiver.mGen.mBaseChoices(i)]) + if (std::get<0>(mReceiver.mGenVar).mBaseOTs(i) != baseSend[i][std::get<0>(mReceiver.mGenVar).mBaseChoices(i)]) { std::cout << "OleBatch::getTask() base OTs do not match. " << LOCATION << std::endl; std::terminate(); @@ -195,19 +209,18 @@ namespace secJoin } } - assert(mReceiver.mGen.hasBaseOts()); - mReceiver.mMultType = oc::MultType::Tungsten; + assert(mReceiver.hasBaseCors()); mReceiver.mA = std::move(threadState.mA); - mReceiver.mEncodeTemp = std::move(threadState.mEncodeTemp); - mReceiver.mGen.mTempBuffer = std::move(threadState.mPprfTemp); - mReceiver.mGen.mEagerSend = false; + mReceiver.mSpin = std::move(threadState.mSpin); + std::get<0>(mReceiver.mGenVar).mTempBuffer = std::move(threadState.mPprfTemp); + std::get<0>(mReceiver.mGenVar).mEagerSend = false; co_await mReceiver.silentReceiveInplace(mReceiver.mRequestNumOts, prng, sock, oc::ChoiceBitPacking::True); compressRecver(mReceiver.mA, add, mult); threadState.mA = std::move(mReceiver.mA); - threadState.mEncodeTemp = std::move(mReceiver.mEncodeTemp); - threadState.mPprfTemp = std::move(mReceiver.mGen.mTempBuffer); + threadState.mSpin = std::move(mReceiver.mSpin); + threadState.mPprfTemp = std::move(std::get<0>(mReceiver.mGenVar).mTempBuffer); } @@ -232,27 +245,34 @@ namespace secJoin { mock(batchIdx, add, mult); } + else if (threadState.mStationary) + { + auto& worker = *threadState.mStationary; + auto& protocol = worker.begin(worker.sendOt, CorType::Ole, size, true); + co_await protocol.silentSendInplace(protocol.mDelta, size, prng, sock); + compressSender(*protocol.mDelta, protocol.mB, add, mult); + worker.finish(protocol); + } else { if (state->mDebug) { - co_await sock.send(coproto::copy(mSender.mGen.mBaseOTs)); + co_await sock.send(coproto::copy(std::get<0>(mSender.mGenVar).mBaseOTs)); } - assert(mSender.mGen.hasBaseOts()); - mSender.mMultType = oc::MultType::Tungsten; + assert(mSender.hasBaseCors()); mSender.mB = std::move(threadState.mB); - mSender.mEncodeTemp = std::move(threadState.mEncodeTemp); - mSender.mGen.mTempBuffer = std::move(threadState.mPprfTemp); - mSender.mGen.mEagerSend = false; + mSender.mSpin = std::move(threadState.mSpin); + std::get<0>(mSender.mGenVar).mTempBuffer = std::move(threadState.mPprfTemp); + std::get<0>(mSender.mGenVar).mEagerSend = false; - co_await mSender.silentSendInplace(prng.get(), mSender.mRequestNumOts, prng, sock); - compressSender(mSender.mDelta, mSender.mB, add, mult); + co_await mSender.silentSendInplace(mSender.mDelta, mSender.mRequestNumOts, prng, sock); + compressSender(*mSender.mDelta, mSender.mB, add, mult); threadState.mB = std::move(mSender.mB); - threadState.mEncodeTemp = std::move(mSender.mEncodeTemp); - threadState.mPprfTemp = std::move(mSender.mGen.mTempBuffer); + threadState.mSpin = std::move(mSender.mSpin); + threadState.mPprfTemp = std::move(std::get<0>(mSender.mGenVar).mTempBuffer); } corReady.set(); @@ -265,286 +285,77 @@ namespace secJoin span add, span mult) { - auto aIter = reinterpret_cast(add.data()); - auto bIter8 = (u8*)mult.data(); - - - if (add.size() * 128 != A.size()) + if (A.size() % 128 || add.size() != A.size() / 128 || mult.size() != add.size()) throw RTE_LOC; - if (mult.size() * 128 != A.size()) - throw RTE_LOC; - - auto shuffle = std::array{}; - memset(shuffle.data(), 1 << 7, sizeof(*shuffle.data()) * shuffle.size()); - for (u64 i = 0; i < 16; ++i) - shuffle[i].set(i, 0); - - auto OneBlock = block(1); - auto AllOneBlock = block(~0ull, ~0ull); - block mask = OneBlock ^ AllOneBlock; - - auto m = &A[0]; - for (u64 i = 0; i < A.size(); i += 16) +#if defined(ENABLE_SSE) && defined(__VAES__) && defined(__AVX2__) && !defined(__AVX512F__) + packedOt::compressReceiver256<1>(A, add, {&mult}); +#else + for (u64 i = 0; i < A.size(); i += packedOt::groupSize) { - for (u64 j = 0; j < 2; ++j) - { - // extract the choice bit from the LSB of m - u32 b0 = m[0].testc(OneBlock); - u32 b1 = m[1].testc(OneBlock); - u32 b2 = m[2].testc(OneBlock); - u32 b3 = m[3].testc(OneBlock); - u32 b4 = m[4].testc(OneBlock); - u32 b5 = m[5].testc(OneBlock); - u32 b6 = m[6].testc(OneBlock); - u32 b7 = m[7].testc(OneBlock); - - // pack the choice bits. - *bIter8++ = - b0 ^ - (b1 << 1) ^ - (b2 << 2) ^ - (b3 << 3) ^ - (b4 << 4) ^ - (b5 << 5) ^ - (b6 << 6) ^ - (b7 << 7); - - // mask of the choice bit which is stored in the LSB - m[0] = m[0] & mask; - m[1] = m[1] & mask; - m[2] = m[2] & mask; - m[3] = m[3] & mask; - m[4] = m[4] & mask; - m[5] = m[5] & mask; - m[6] = m[6] & mask; - m[7] = m[7] & mask; - - oc::mAesFixedKey.hashBlocks<8>(m, m); - - m += 8; - } - m -= 16; - - // _mm_shuffle_epi8(a, b): - // FOR j := 0 to 15 - // i: = j * 8 - // IF b[i + 7] == 1 - // dst[i + 7:i] : = 0 - // ELSE - // index[3:0] : = b[i + 3:i] - // dst[i + 7:i] : = a[index * 8 + 7:index * 8] - // FI - // ENDFOR - - // _mm_sll_epi16 : shifts 16 bit works left - // _mm_movemask_epi8: packs together the MSG - - block a00 = shuffle_epi8(m[0], shuffle[0]); - block a01 = shuffle_epi8(m[1], shuffle[1]); - block a02 = shuffle_epi8(m[2], shuffle[2]); - block a03 = shuffle_epi8(m[3], shuffle[3]); - block a04 = shuffle_epi8(m[4], shuffle[4]); - block a05 = shuffle_epi8(m[5], shuffle[5]); - block a06 = shuffle_epi8(m[6], shuffle[6]); - block a07 = shuffle_epi8(m[7], shuffle[7]); - block a08 = shuffle_epi8(m[8], shuffle[8]); - block a09 = shuffle_epi8(m[9], shuffle[9]); - block a10 = shuffle_epi8(m[10], shuffle[10]); - block a11 = shuffle_epi8(m[11], shuffle[11]); - block a12 = shuffle_epi8(m[12], shuffle[12]); - block a13 = shuffle_epi8(m[13], shuffle[13]); - block a14 = shuffle_epi8(m[14], shuffle[14]); - block a15 = shuffle_epi8(m[15], shuffle[15]); - - a00 = a00 ^ a08; - a01 = a01 ^ a09; - a02 = a02 ^ a10; - a03 = a03 ^ a11; - a04 = a04 ^ a12; - a05 = a05 ^ a13; - a06 = a06 ^ a14; - a07 = a07 ^ a15; - - a00 = a00 ^ a04; - a01 = a01 ^ a05; - a02 = a02 ^ a06; - a03 = a03 ^ a07; - - a00 = a00 ^ a02; - a01 = a01 ^ a03; - - a00 = a00 ^ a01; - - a00 = slli_epi16<7>(a00); - - u16 ap = movemask_epi8(a00); - - std::memcpy(aIter, &ap, sizeof(ap)); - aIter += sizeof(ap); - m += 16; - + const packedOt::Group group(A.data() + i); + const auto choices = group.choices<0>(); + const auto bits = group.hashes<1>(); + packedOt::store(mult.data(), i, choices); + packedOt::store(add.data(), i, bits); } +#endif } - void OleBatch::SendBatch::compressSender( block delta, span B, span add, span mult) { - - auto bIter = reinterpret_cast(add.data()); - auto aIter = reinterpret_cast(mult.data()); - - if (add.size() * 128 != B.size()) + if (B.size() % 128 || add.size() != B.size() / 128 || mult.size() != add.size()) throw RTE_LOC; - if (mult.size() * 128 != B.size()) - throw RTE_LOC; - using block = oc::block; - - auto shuffle = std::array{}; - memset(shuffle.data(), 1 << 7, sizeof(*shuffle.data()) * shuffle.size()); - for (u64 i = 0; i < 16; ++i) - shuffle[i].set(i, 0); - std::array sendMsg; - auto m = B.data(); - - auto OneBlock = block(1); - auto AllOneBlock = block(~0ull, ~0ull); - block mask = OneBlock ^ AllOneBlock; - delta = delta & mask; - - for (u64 i = 0; i < B.size(); i += 16) +#if defined(ENABLE_SSE) && defined(__VAES__) && defined(__AVX2__) && !defined(__AVX512F__) + const auto& keys = oc::mAesFixedKey.mRoundKey; + const block mask(~0ull, ~1ull); + const auto messageMask = _mm256_broadcastsi128_si256(mask.mData); + const auto firstZero = _mm256_broadcastsi128_si256(keys[0].mData); + const auto firstOne = _mm256_broadcastsi128_si256((keys[0] ^ (delta & mask)).mData); + __m256i roundKeys[10]; + for (unsigned r = 0; r < 10; ++r) + roundKeys[r] = _mm256_broadcastsi128_si256(keys[r + 1].mData); + + for (u64 i = 0; i < B.size(); i += 8) { - auto s = sendMsg.data(); - - for (u64 j = 0; j < 2; ++j) - { - m[0] = m[0] & mask; - m[1] = m[1] & mask; - m[2] = m[2] & mask; - m[3] = m[3] & mask; - m[4] = m[4] & mask; - m[5] = m[5] & mask; - m[6] = m[6] & mask; - m[7] = m[7] & mask; - - oc::mAesFixedKey.hashBlocks<8>(m, s); - - s += 8; - m += 8; - } - - - block a00 = shuffle_epi8(sendMsg[0], shuffle[0]); - block a01 = shuffle_epi8(sendMsg[1], shuffle[1]); - block a02 = shuffle_epi8(sendMsg[2], shuffle[2]); - block a03 = shuffle_epi8(sendMsg[3], shuffle[3]); - block a04 = shuffle_epi8(sendMsg[4], shuffle[4]); - block a05 = shuffle_epi8(sendMsg[5], shuffle[5]); - block a06 = shuffle_epi8(sendMsg[6], shuffle[6]); - block a07 = shuffle_epi8(sendMsg[7], shuffle[7]); - block a08 = shuffle_epi8(sendMsg[8], shuffle[8]); - block a09 = shuffle_epi8(sendMsg[9], shuffle[9]); - block a10 = shuffle_epi8(sendMsg[10], shuffle[10]); - block a11 = shuffle_epi8(sendMsg[11], shuffle[11]); - block a12 = shuffle_epi8(sendMsg[12], shuffle[12]); - block a13 = shuffle_epi8(sendMsg[13], shuffle[13]); - block a14 = shuffle_epi8(sendMsg[14], shuffle[14]); - block a15 = shuffle_epi8(sendMsg[15], shuffle[15]); - - s = sendMsg.data(); - m -= 16; - for (u64 j = 0; j < 2; ++j) + // Four pairs of input blocks, with both choices in flight. + __m256i state[8]; + for (unsigned j = 0; j < 4; ++j) { - s[0] = m[0] ^ delta; - s[1] = m[1] ^ delta; - s[2] = m[2] ^ delta; - s[3] = m[3] ^ delta; - s[4] = m[4] ^ delta; - s[5] = m[5] ^ delta; - s[6] = m[6] ^ delta; - s[7] = m[7] ^ delta; - - oc::mAesFixedKey.hashBlocks<8>(s, s); - - s += 8; - m += 8; + const auto x = _mm256_loadu_si256(reinterpret_cast(B.data() + i + 2 * j)); + const auto masked = _mm256_and_si256(x, messageMask); + state[j] = _mm256_xor_si256(masked, firstZero); + state[j + 4] = _mm256_xor_si256(masked, firstOne); } - - block b00 = shuffle_epi8(sendMsg[0], shuffle[0]); - block b01 = shuffle_epi8(sendMsg[1], shuffle[1]); - block b02 = shuffle_epi8(sendMsg[2], shuffle[2]); - block b03 = shuffle_epi8(sendMsg[3], shuffle[3]); - block b04 = shuffle_epi8(sendMsg[4], shuffle[4]); - block b05 = shuffle_epi8(sendMsg[5], shuffle[5]); - block b06 = shuffle_epi8(sendMsg[6], shuffle[6]); - block b07 = shuffle_epi8(sendMsg[7], shuffle[7]); - block b08 = shuffle_epi8(sendMsg[8], shuffle[8]); - block b09 = shuffle_epi8(sendMsg[9], shuffle[9]); - block b10 = shuffle_epi8(sendMsg[10], shuffle[10]); - block b11 = shuffle_epi8(sendMsg[11], shuffle[11]); - block b12 = shuffle_epi8(sendMsg[12], shuffle[12]); - block b13 = shuffle_epi8(sendMsg[13], shuffle[13]); - block b14 = shuffle_epi8(sendMsg[14], shuffle[14]); - block b15 = shuffle_epi8(sendMsg[15], shuffle[15]); - - a00 = a00 ^ a08; - a01 = a01 ^ a09; - a02 = a02 ^ a10; - a03 = a03 ^ a11; - a04 = a04 ^ a12; - a05 = a05 ^ a13; - a06 = a06 ^ a14; - a07 = a07 ^ a15; - - b00 = b00 ^ b08; - b01 = b01 ^ b09; - b02 = b02 ^ b10; - b03 = b03 ^ b11; - b04 = b04 ^ b12; - b05 = b05 ^ b13; - b06 = b06 ^ b14; - b07 = b07 ^ b15; - - a00 = a00 ^ a04; - a01 = a01 ^ a05; - a02 = a02 ^ a06; - a03 = a03 ^ a07; - - b00 = b00 ^ b04; - b01 = b01 ^ b05; - b02 = b02 ^ b06; - b03 = b03 ^ b07; - - a00 = a00 ^ a02; - a01 = a01 ^ a03; - - b00 = b00 ^ b02; - b01 = b01 ^ b03; - - a00 = a00 ^ a01; - b00 = b00 ^ b01; - - a00 = slli_epi16<7>(a00); - b00 = slli_epi16<7>(b00); - - u16 ap = movemask_epi8(a00); - u16 bp = movemask_epi8(b00); - - assert(aIter + sizeof(u16) <= reinterpret_cast(mult.data() + mult.size())); - assert(bIter + sizeof(u16) <= reinterpret_cast(add.data() + add.size())); - - u16 mixed = ap ^ bp; - std::memcpy(aIter, &mixed, sizeof(mixed)); - aIter += sizeof(mixed); - std::memcpy(bIter, &ap, sizeof(ap)); - bIter += sizeof(ap); +#pragma GCC unroll 9 + for (unsigned r = 0; r < 9; ++r) + for (auto& v : state) + v = _mm256_aesenc_epi128(v, roundKeys[r]); + for (auto& v : state) + v = _mm256_aesenclast_epi128(v, roundKeys[9]); + + // Both hash inputs have bit zero cleared, so AES supplies the output bit. + const auto zero = packedOt::lowWords(state[0], state[1], state[2], state[3]); + const auto one = packedOt::lowWords(state[4], state[5], state[6], state[7]); + const auto z = packedOt::packBit<0>(packedOt::inInputOrder(zero)); + const auto o = packedOt::packBit<0>(packedOt::inInputOrder(one)); + reinterpret_cast(add.data())[i / 8] = z; + reinterpret_cast(mult.data())[i / 8] = z ^ o; } +#else + for (u64 i = 0; i < B.size(); i += packedOt::groupSize) + { + const packedOt::Group group(B.data() + i); + const auto zero = group.hashes<1>(); + const auto one = group.hashes<1>(delta); + packedOt::store(add.data(), i, zero); + packedOt::store(mult.data(), i, zero ^ one); + } +#endif } - - -} \ No newline at end of file +} diff --git a/secure-join/CorGenerator/BinOleBatch.h b/secure-join/CorGenerator/BinOleBatch.h index ddffdf065..33a24b093 100644 --- a/secure-join/CorGenerator/BinOleBatch.h +++ b/secure-join/CorGenerator/BinOleBatch.h @@ -97,9 +97,9 @@ namespace secJoin void getCor(Cor* c, u64 begin, u64 size) override; - BaseRequest getBaseRequest() override; + BaseRequest getBaseRequest(StationaryWorker* worker) override; - void setBase(BaseCor& sMsg) override; + void setBase(BaseCor& sMsg, StationaryWorker* worker) override; // Get the task associated with this batch. macoro::task<> getTask(BatchThreadState&) override; diff --git a/secure-join/CorGenerator/CorGenerator.cpp b/secure-join/CorGenerator/CorGenerator.cpp index 9f96f6e9a..0a04207f8 100644 --- a/secure-join/CorGenerator/CorGenerator.cpp +++ b/secure-join/CorGenerator/CorGenerator.cpp @@ -6,6 +6,43 @@ namespace secJoin { + namespace + { + // The extension first produces hashed location OTs. Its subsequent raw + // correlated OTs supply A = B xor (choice * delta) for binary noise. + macoro::task<> sendOtBases(oc::SoftSpokenShOtSender<>& ot, BaseCor& base, + u64 noiseCount, PRNG& prng, oc::Socket& sock) + { + if (base.mOtSendMsg.size()) + co_await ot.send(base.mOtSendMsg, prng, sock); + if (noiseCount) + { + ot.mRandomOt = false; + oc::AlignedUnVector> noise(noiseCount); + co_await ot.send(noise, prng, sock); + base.mBinaryDelta = ot.delta(); + base.mBinaryB.resize(noiseCount); + for (u64 i = 0; i < noiseCount; ++i) + base.mBinaryB[i] = noise[i][0]; + } + } + + macoro::task<> receiveOtBases(oc::SoftSpokenShOtReceiver<>& ot, BaseCor& base, + u64 noiseCount, PRNG& prng, oc::Socket& sock) + { + if (base.mOtRecvMsg.size()) + co_await ot.receive(base.mOtRecvChoice, base.mOtRecvMsg, prng, sock); + if (noiseCount) + { + ot.mRandomOt = false; + base.mBinaryChoice.resize(noiseCount); + base.mBinaryChoice.randomize(prng); + base.mBinaryA.resize(noiseCount); + co_await ot.receive(base.mBinaryChoice, base.mBinaryA, prng, sock); + } + } + } + void CorGenerator::init( @@ -14,9 +51,18 @@ namespace secJoin u64 partyIdx, u64 numConcurrent, u64 batchSize, - bool mock) + bool mock, oc::SdNoiseDistribution noise) { - mGenState = std::make_shared(partyIdx, prng.fork(), std::move(sock), numConcurrent, batchSize, mock); + if (partyIdx > 1 || (noise != oc::SdNoiseDistribution::Regular && noise != oc::SdNoiseDistribution::Stationary)) + throw std::invalid_argument("Invalid correlation party or noise mode"); + mGenState = std::make_shared(partyIdx, prng.fork(), std::move(sock), numConcurrent, batchSize, mock); + mGenState->mNoise = noise; + if (noise == oc::SdNoiseDistribution::Stationary) + { + if (!mBanks) + mBanks = std::make_shared(); + mGenState->mBanks = mBanks; + } } @@ -148,20 +194,56 @@ namespace secJoin auto res = macoro::result{}; auto reqChecks = std::map{}; auto theirReq = std::vector{}; - auto threadState = std::vector{}; - + std::vector banks; + auto threadState = std::vector(mNumConcurrent); + std::array, 2> baseWorkers; + auto* sendVole = &mSendVoleBase; + auto* recvVole = &mRecvVoleBase; + + std::exception_ptr failure; + try + { setTimePoint("GenState::start"); mOtBatch = {}; mOleBatch = {}; - // make base OT requests + // Bind public worker IDs and the private stream lifetime to this peer session. + // The request schedule already fixes the batch index on both sides. + if (!mMock && !mBatches.empty()) + { + const u64 version = mNoise == oc::SdNoiseDistribution::Stationary ? 3 : 1; + std::array config{version, static_cast(mNoise), mNumConcurrent, mBatchSize, + mPartyIdx, mPrng.get()}; + std::array peer{}; + auto exchanged = co_await macoro::when_all_ready(mSock.send(config), mSock.recv(peer)); + std::get<0>(exchanged).result(); + std::get<1>(exchanged).result(); + if (peer[0] != config[0] || peer[1] != config[1] || peer[3] != mBatchSize || + peer[4] != 1 - mPartyIdx || (mNoise == oc::SdNoiseDistribution::Stationary && peer[2] != mNumConcurrent)) + throw std::runtime_error("Peer correlation mode, worker count, batch size or role mismatch"); + if (mNoise == oc::SdNoiseDistribution::Stationary) + { + const block session(mPartyIdx ? peer[5] : config[5], mPartyIdx ? config[5] : peer[5]); + // The base VOLE generators in opposite directions can run concurrently. + banks = mBanks->acquire(mNumConcurrent + 2); + for (u64 sender = 0; sender < 2; ++sender) + { + const u64 index = mNumConcurrent + sender; + baseWorkers[sender] = std::make_unique(index, mPartyIdx, session, banks[index]); + } + for (u64 i = 0; i < mNumConcurrent; ++i) + threadState[i].mStationary = std::make_unique(i, mPartyIdx, session, banks[i]); + } + } + + // make base OT requests reqs.reserve(mBatches.size()); for (auto i = 0ull; i < mBatches.size();++i) { auto& batch = *mBatches[i]; if (!batch.mSize) std::terminate(); - reqs.push_back(batch.getBaseRequest()); + reqs.push_back(batch.getBaseRequest(threadState[i % mNumConcurrent].mStationary.get())); } if (mDebug) @@ -230,12 +312,12 @@ namespace secJoin { if (i ^ mPartyIdx) { - if (req.mSendSize) + if (req.mSendSize || req.mSendBinaryVoles) { socks.push_back(mSock.fork()); prngs.push_back(mPrng.fork()); base.mOtSendMsg.resize(req.mSendSize); - protos.push_back(mSendOtBase.send(base.mOtSendMsg, prngs.back(), socks.back())); + protos.push_back(sendOtBases(mSendOtBase, base, req.mSendBinaryVoles, prngs.back(), socks.back())); } if (req.mSendVoleSize) @@ -244,19 +326,21 @@ namespace secJoin prngs.push_back(mPrng.fork()); base.mVoleDelta = mPrng.get(); base.mVoleB.resize(req.mSendVoleSize); - protos.push_back(mSendVoleBase.sendChosen(base.mVoleDelta, base.mVoleB, prngs.back(), socks.back())); + if (auto& w = baseWorkers[mPartyIdx]) + sendVole = &w->begin(w->sendF4, CorType::F4BitOt, req.mSendVoleSize, true); + protos.push_back(sendVole->sendChosen(base.mVoleDelta, base.mVoleB, prngs.back(), socks.back())); } } else { // perform recv base OTs - if (req.mChoice.size()) + if (req.mChoice.size() || req.mRecvBinaryVoles) { socks.push_back(mSock.fork()); prngs.push_back(mPrng.fork()); base.mOtRecvMsg.resize(req.mChoice.size()); base.mOtRecvChoice = std::move(req.mChoice); - protos.push_back(mRecvOtBase.receive(base.mOtRecvChoice, base.mOtRecvMsg, prngs.back(), socks.back())); + protos.push_back(receiveOtBases(mRecvOtBase, base, req.mRecvBinaryVoles, prngs.back(), socks.back())); } if (req.mVoleChoice.size()) @@ -265,7 +349,9 @@ namespace secJoin prngs.push_back(mPrng.fork()); base.mVoleA.resize(req.mVoleChoice.size()); base.mVoleChoice = std::move(req.mVoleChoice); - protos.push_back(mRecvVoleBase.receiveChosen(base.mVoleChoice, base.mVoleA, prngs.back(), socks.back())); + if (auto& w = baseWorkers[1 - mPartyIdx]) + recvVole = &w->begin(w->recvF4, CorType::F4BitOt, base.mVoleA.size(), false); + protos.push_back(recvVole->receiveChosen(base.mVoleChoice, base.mVoleA, prngs.back(), socks.back())); } } } @@ -285,7 +371,11 @@ namespace secJoin setTimePoint("GenState::base"); - threadState.resize(mNumConcurrent); + if (sendVole != &mSendVoleBase) + baseWorkers[mPartyIdx]->finish(*sendVole); + if (recvVole != &mRecvVoleBase) + baseWorkers[1 - mPartyIdx]->finish(*recvVole); + baseWorkers = {}; @@ -298,7 +388,10 @@ namespace secJoin if (mBatches[i]->mAbort == false) { auto& batch = *mBatches[i]; - batch.setBase(base); + auto& worker = threadState[i % mNumConcurrent]; + batch.setBase(base, worker.mStationary.get()); + if (!mMock && !worker.mStationary) + prepareRegularSpin(worker.mSpin, batch.mSize); setTimePoint("GenState::batch.begin " + std::to_string(i)); @@ -306,14 +399,14 @@ namespace secJoin { // launch the next batch threadState[i % mNumConcurrent].mTask = - mBatches[i]->getTask(threadState[i % mNumConcurrent]) | + mBatches[i]->run(threadState[i % mNumConcurrent]) | macoro::start_on(*mPool); } else { // launch the next batch threadState[i % mNumConcurrent].mTask = - mBatches[i]->getTask(threadState[i % mNumConcurrent]) | + mBatches[i]->run(threadState[i % mNumConcurrent]) | macoro::make_eager(); } } @@ -332,7 +425,35 @@ namespace secJoin } mBatches = {}; - setTimePoint("GenState::done "); + if (!banks.empty()) + mBanks->release(std::move(banks)); + setTimePoint("GenState::done "); + co_return; + } + catch (...) + { + failure = std::current_exception(); + } + + // Keep worker and base storage alive until all suspended users unwind. + abort(); + if (!mSock.closed()) + co_await mSock.close(); + for (auto& task : tasks) + if (task.handle() && !task.is_ready()) + try { co_await task; } catch (...) {} + for (auto& worker : threadState) + if (worker.mTask.handle() && !worker.mTask.is_ready()) + try { co_await worker.mTask; } catch (...) {} + for (auto& batch : mBatches) + { + if (batch && !batch->mCorReady.is_set()) + { + batch->mError = failure; + batch->mCorReady.set(); + } + } + std::rethrow_exception(failure); } //void GenState::set(SendBase& b) { auto v = b.get(); mRecvBase.setBaseOts(v); } diff --git a/secure-join/CorGenerator/CorGenerator.h b/secure-join/CorGenerator/CorGenerator.h index b6bced1ea..7b6bcf528 100644 --- a/secure-join/CorGenerator/CorGenerator.h +++ b/secure-join/CorGenerator/CorGenerator.h @@ -99,6 +99,8 @@ namespace secJoin // true if we should just fake the correlation generation bool mMock = false; + oc::SdNoiseDistribution mNoise = oc::SdNoiseDistribution::Regular; + std::shared_ptr mBanks; // used to determine which party should go first when its ambiguous. u64 mPartyIdx = -1; @@ -158,6 +160,7 @@ namespace secJoin std::shared_ptr mGenState; std::vector> mStarted; + std::shared_ptr mBanks; void init( coproto::Socket&& sock, @@ -165,7 +168,8 @@ namespace secJoin u64 partyIdx, u64 numConcurrent, u64 batchSize, - bool mock); + bool mock, + oc::SdNoiseDistribution noise = oc::SdNoiseDistribution::Regular); template diff --git a/secure-join/CorGenerator/F4BitOtBatch.cpp b/secure-join/CorGenerator/F4BitOtBatch.cpp index 87000b2dc..3b490d1bf 100644 --- a/secure-join/CorGenerator/F4BitOtBatch.cpp +++ b/secure-join/CorGenerator/F4BitOtBatch.cpp @@ -1,7 +1,7 @@ #include "F4BitOtBatch.h" #include "CorGenerator.h" #include "secure-join/Util/match.h" -#include "secure-join/Util/Simd.h" +#include "PackedOtHash.h" #include namespace secJoin @@ -47,7 +47,7 @@ namespace secJoin }; } - BaseRequest F4BitOtBatch::getBaseRequest() + BaseRequest F4BitOtBatch::getBaseRequest(StationaryWorker* worker) { BaseRequest r; @@ -56,21 +56,46 @@ namespace secJoin mSendRecv | match{ [&](SendBatch& send) { - send.mSender.configure(mSize); - r.mSendSize = send.mSender.silentBaseOtCount(); - r.mSendVoleSize = send.mSender.baseVoleCount(); + if (worker) + { + auto [protocol, fresh] = worker->stream(worker->sendF4, CorType::F4BitOt, mSize, true); + if (fresh) + r.mSendSize = protocol.silentBaseOtCount(); + r.mSendVoleSize = protocol.baseVoleCount(); + } + else + { + send.mSender.configure(mSize); + r.mSendSize = send.mSender.silentBaseOtCount(); + r.mSendVoleSize = send.mSender.baseVoleCount(); + } }, - [&](RecvBatch& recv) { - recv.mReceiver.configure(mSize); - r.mChoice = recv.mReceiver.sampleBaseChoiceBits(mPrng); - r.mVoleChoice = recv.mReceiver.sampleBaseVoleVals(mPrng); + if (worker) + { + auto [protocol, fresh] = worker->stream(worker->recvF4, CorType::F4BitOt, mSize, false); + if (fresh) + { + r.mChoice = protocol.sampleBaseChoiceBits(mPrng); + protocol.recordPoints(); + } + // Every round gets new uniform coefficients, including zero. + r.mVoleChoice.resize(protocol.baseVoleCount()); + for (auto& c : r.mVoleChoice) + c.mVal = mPrng.get() & 3; + } + else + { + recv.mReceiver.configure(mSize); + r.mChoice = recv.mReceiver.sampleBaseChoiceBits(mPrng); + r.mVoleChoice = recv.mReceiver.sampleBaseVoleVals(mPrng); + } } }; return r; } - void F4BitOtBatch::setBase(BaseCor& base) + void F4BitOtBatch::setBase(BaseCor& base, StationaryWorker* worker) { if (mGenState->mMock) @@ -79,14 +104,21 @@ namespace secJoin mSendRecv | match{ [&](SendBatch& send) { send.mDelta = base.mVoleDelta; - send.mSender.setSilentBaseOts( - base.getSendOt(send.mSender.silentBaseOtCount()), - base.getSendVole(send.mSender.baseVoleCount())); + auto& protocol = worker ? worker->sendF4.at({CorType::F4BitOt, mSize}) : send.mSender; + protocol.setSilentBaseOts(base.getSendOt(protocol.silentBaseOtCount()), + base.getSendVole(protocol.baseVoleCount())); }, [&](RecvBatch& recv) { - recv.mReceiver.setSilentBaseOts( - base.getRecvOt(recv.mReceiver.silentBaseOtCount()), - base.getRecvVole(recv.mReceiver.baseVoleCount())); + auto& protocol = worker ? worker->recvF4.at({CorType::F4BitOt, mSize}) : recv.mReceiver; + const auto count = protocol.baseVoleCount(); + const auto offset = base.mVoleRecvIndex; + auto shares = base.getRecvVole(count); + if (worker) + { + protocol.mBaseC.resize(count); + std::copy_n(base.mVoleChoice.begin() + offset, count, protocol.mBaseC.begin()); + } + protocol.setSilentBaseOts(base.getRecvOt(protocol.silentBaseOtCount()), shares); } }; } @@ -325,7 +357,15 @@ namespace secJoin { mock(batchIdx, size); } - else + else if (threadState.mStationary) + { + auto& worker = *threadState.mStationary; + auto& protocol = worker.begin(worker.recvF4, CorType::F4BitOt, size, false); + co_await protocol.silentReceiveInplace(size, prng, sock); + compressRecver(protocol.mA); + worker.finish(protocol); + } + else { if (state->mDebug) @@ -370,9 +410,8 @@ namespace secJoin } assert(mReceiver.mGen.hasBaseOts()); - mReceiver.mMultType = oc::MultType::Tungsten; mReceiver.mA = std::move(threadState.mA); - mReceiver.mEncodeTemp = std::move(threadState.mEncodeTemp); + mReceiver.mSpin = std::move(threadState.mSpin); mReceiver.mGen.mTempBuffer = std::move(threadState.mPprfTemp); mReceiver.mGen.mEagerSend = false; @@ -384,7 +423,7 @@ namespace secJoin compressRecver(mReceiver.mA); threadState.mA = std::move(mReceiver.mA); - threadState.mEncodeTemp = std::move(mReceiver.mEncodeTemp); + threadState.mSpin = std::move(mReceiver.mSpin); threadState.mPprfTemp = std::move(mReceiver.mGen.mTempBuffer); } @@ -406,7 +445,15 @@ namespace secJoin { mock(batchIdx, size); } - else + else if (threadState.mStationary) + { + auto& worker = *threadState.mStationary; + auto& protocol = worker.begin(worker.sendF4, CorType::F4BitOt, size, true); + co_await protocol.silentSendInplace(mDelta, size, prng, sock); + compressSender(protocol.mB); + worker.finish(protocol); + } + else { if (state->mDebug) @@ -418,11 +465,10 @@ namespace secJoin } assert(mSender.mGen.hasBaseOts()); - mSender.mMultType = oc::MultType::Tungsten; mSender.mB = std::move(threadState.mB); - mSender.mEncodeTemp = std::move(threadState.mEncodeTemp); + mSender.mSpin = std::move(threadState.mSpin); mSender.mGen.mTempBuffer = std::move(threadState.mPprfTemp); mSender.mGen.mEagerSend = false; @@ -434,7 +480,7 @@ namespace secJoin compressSender(mSender.mB); threadState.mB = std::move(mSender.mB); - threadState.mEncodeTemp = std::move(mSender.mEncodeTemp); + threadState.mSpin = std::move(mSender.mSpin); threadState.mPprfTemp = std::move(mSender.mGen.mTempBuffer); } @@ -442,288 +488,157 @@ namespace secJoin corReady.set(); } - // the first two bits of A is the choice bit of the VOLE. +#if defined(ENABLE_SSE) && defined(__VAES__) && defined(__AVX2__) && !defined(__AVX512F__) + using packedOt::lowWords; + using packedOt::inInputOrder; + using packedOt::packBit; +#endif void F4BitOtBatch::RecvBatch::compressRecver( span A) { - mOts.resize(A.size()); - mChoiceLsb.resize(A.size()); - mChoiceMsb.resize(A.size()); - auto aIter = reinterpret_cast(mOts.data()); - auto lsbIter8 = (u8*)mChoiceLsb.data(); - auto msbIter8 = (u8*)mChoiceMsb.data(); - - auto shuffle = std::array{}; - osuCrypto::setBytes(shuffle, static_cast(1 << 7)); - for (u64 i = 0; i < 16; ++i) - shuffle[i].set(i, 0); - - auto OneBlock = block(1); - auto TwoBlock = block(2); - block mask = block(~0ull, ~3ull); - - auto m = &A[0]; - - for (u64 i = 0; i < A.size(); i += 16) + if (A.size() % 128) + throw RTE_LOC; + mOts.resize(A.size() / 128); + mChoiceLsb.resize(A.size() / 128); + mChoiceMsb.resize(A.size() / 128); +#if defined(ENABLE_SSE) && defined(__VAES__) && defined(__AVX2__) && !defined(__AVX512F__) + packedOt::compressReceiver256<2>(A, mOts, {&mChoiceLsb, &mChoiceMsb}); +#else + for (u64 i = 0; i < A.size(); i += packedOt::groupSize) { - u32 lsb[8], msb[8]; - for (u64 j = 0; j < 2; ++j) - { - // extract the choice bit from the LSB of m - storeu_si32(&lsb[0], m[0] & OneBlock); - storeu_si32(&lsb[1], m[1] & OneBlock); - storeu_si32(&lsb[2], m[2] & OneBlock); - storeu_si32(&lsb[3], m[3] & OneBlock); - storeu_si32(&lsb[4], m[4] & OneBlock); - storeu_si32(&lsb[5], m[5] & OneBlock); - storeu_si32(&lsb[6], m[6] & OneBlock); - storeu_si32(&lsb[7], m[7] & OneBlock); - - assert(lsb[0] == (m[0].get(0) & 1)); - - // pack the choice bits. - *lsbIter8++ = - lsb[0] ^ - (lsb[1] << 1) ^ - (lsb[2] << 2) ^ - (lsb[3] << 3) ^ - (lsb[4] << 4) ^ - (lsb[5] << 5) ^ - (lsb[6] << 6) ^ - (lsb[7] << 7); - - // extract the choice bit from the MSB of m - - storeu_si32(&msb[0], m[0] & TwoBlock); - storeu_si32(&msb[1], m[1] & TwoBlock); - storeu_si32(&msb[2], m[2] & TwoBlock); - storeu_si32(&msb[3], m[3] & TwoBlock); - storeu_si32(&msb[4], m[4] & TwoBlock); - storeu_si32(&msb[5], m[5] & TwoBlock); - storeu_si32(&msb[6], m[6] & TwoBlock); - storeu_si32(&msb[7], m[7] & TwoBlock); - - assert(msb[0] == (m[0].get(0) & 2)); - - - // pack the choice bits. - *msbIter8++ = - (msb[0] >> 1) ^ - (msb[1]) ^ - (msb[2] << 1) ^ - (msb[3] << 2) ^ - (msb[4] << 3) ^ - (msb[5] << 4) ^ - (msb[6] << 5) ^ - (msb[7] << 6); - - // mask of the choice bits which is stored in the LSB - m[0] = m[0] & mask; - m[1] = m[1] & mask; - m[2] = m[2] & mask; - m[3] = m[3] & mask; - m[4] = m[4] & mask; - m[5] = m[5] & mask; - m[6] = m[6] & mask; - m[7] = m[7] & mask; - - oc::mAesFixedKey.hashBlocks<8>(m, m); - - m += 8; - - - } - m -= 16; - - block a00 = shuffle_epi8(m[0], shuffle[0]); - block a01 = shuffle_epi8(m[1], shuffle[1]); - block a02 = shuffle_epi8(m[2], shuffle[2]); - block a03 = shuffle_epi8(m[3], shuffle[3]); - block a04 = shuffle_epi8(m[4], shuffle[4]); - block a05 = shuffle_epi8(m[5], shuffle[5]); - block a06 = shuffle_epi8(m[6], shuffle[6]); - block a07 = shuffle_epi8(m[7], shuffle[7]); - block a08 = shuffle_epi8(m[8], shuffle[8]); - block a09 = shuffle_epi8(m[9], shuffle[9]); - block a10 = shuffle_epi8(m[10], shuffle[10]); - block a11 = shuffle_epi8(m[11], shuffle[11]); - block a12 = shuffle_epi8(m[12], shuffle[12]); - block a13 = shuffle_epi8(m[13], shuffle[13]); - block a14 = shuffle_epi8(m[14], shuffle[14]); - block a15 = shuffle_epi8(m[15], shuffle[15]); - - a00 = a00 ^ a08; - a01 = a01 ^ a09; - a02 = a02 ^ a10; - a03 = a03 ^ a11; - a04 = a04 ^ a12; - a05 = a05 ^ a13; - a06 = a06 ^ a14; - a07 = a07 ^ a15; - - a00 = a00 ^ a04; - a01 = a01 ^ a05; - a02 = a02 ^ a06; - a03 = a03 ^ a07; - - a00 = a00 ^ a02; - a01 = a01 ^ a03; - - a00 = a00 ^ a01; - - a00 = slli_epi16<7>(a00); - - u16 ap = movemask_epi8(a00); - - std::memcpy(aIter, &ap, sizeof(ap)); - aIter += sizeof(ap); - m += 16; - + const packedOt::Group group(A.data() + i); + const auto lsb = group.choices<0>(); + const auto msb = group.choices<1>(); + const auto bits = group.hashes<2>(); + packedOt::store(mChoiceLsb.data(), i, lsb); + packedOt::store(mChoiceMsb.data(), i, msb); + packedOt::store(mOts.data(), i, bits); } +#endif } - void F4BitOtBatch::SendBatch::compressSender( span B) { - for (u64 i = 0; i < 4; ++i) - mOts[i].resize(B.size()); + if (B.size() % 128) + throw RTE_LOC; + for (auto& ots : mOts) + ots.resize(B.size() / 128); - std::array iters - { - reinterpret_cast(mOts[0].data()), - reinterpret_cast(mOts[1].data()), - reinterpret_cast(mOts[2].data()), - reinterpret_cast(mOts[3].data()) - }; - //auto bIter16 = (u16*)add.data(); - //auto aIter16 = (u16*)mult.data(); - //if (add.size() * 128 != B.size()) - // throw RTE_LOC; - //if (mult.size() * 128 != B.size()) - // throw RTE_LOC; - using block = oc::block; - - auto shuffle = std::array{}; - osuCrypto::setBytes(shuffle, static_cast(1 << 7)); - for (u64 i = 0; i < 16; ++i) - shuffle[i].set(i, 0); - - std::array sendMsg; - //auto m = B.data(); - - block mask = block(~0ull, ~3ull);; + block mask = block(~0ull, ~3ull); std::array deltas; deltas[0] = block(0, 0); deltas[1] = mDelta & mask; CoeffCtxGF4{}.mul(deltas[2], deltas[1], F4{ 2 }); CoeffCtxGF4{}.mul(deltas[3], deltas[1], F4{ 3 }); +#if defined(ENABLE_SSE) && defined(__VAES__) && defined(__AVX512F__) && defined(__AVX512VBMI__) + // Round nine needs only bytes 0, 5, 10 and 15 of each message to + // compute byte zero. Pack four such diagonals per AES lane, arranging + // them so ShiftRows puts each message in its own MixColumns column. + alignas(64) static constexpr auto diagonal = [] { + std::array indices{}; + for (unsigned i = 0; i < indices.size(); ++i) + { + const unsigned row = i % 4, column = i / 4 % 4; + const unsigned message = (column + 4 - row) % 4; + indices[i] = 64 * (i / 16 % 2) + 16 * message + 5 * row; + } + return indices; + }(); + const auto diagonalIndex = _mm512_load_si512(diagonal.data()); + const auto lowWords = _mm512_setr_epi32(0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28); + const auto& keys = oc::mAesFixedKey.mRoundKey; + __m512i roundKeys[8]; + for (unsigned r = 0; r < 8; ++r) + roundKeys[r] = _mm512_broadcast_i32x4(keys[r + 1].mData); + __m512i first[4]; + for (unsigned choice = 0; choice < 4; ++choice) + first[choice] = _mm512_broadcast_i32x4((keys[0] ^ deltas[choice]).mData); + const auto key9 = _mm512_set1_epi32(keys[9].get(0)); + const auto key10 = _mm512_set1_epi32(keys[10].get(0)); + const auto one = _mm512_set1_epi32(1); + for (u64 i = 0; i < B.size(); i += 16) { - for (u64 b = 0; b < 4; ++b) + __m512i raw[4], state[4][4]; + for (unsigned j = 0; j < 4; ++j) + raw[j] = _mm512_loadu_si512(B.data() + i + 4 * j); + // Every offset has low bit zero, so all four hashes XOR the same input bit. + const auto lo = _mm512_permutex2var_epi32(raw[0], lowWords, raw[1]); + const auto hi = _mm512_permutex2var_epi32(raw[2], lowWords, raw[3]); + const auto inputBits = _mm512_test_epi32_mask(_mm512_shuffle_i32x4(lo, hi, 0x44), one); + + for (unsigned choice = 0; choice < 4; ++choice) + for (unsigned j = 0; j < 4; ++j) + state[choice][j] = _mm512_xor_si512(raw[j], first[choice]); +#pragma GCC unroll 8 + for (unsigned r = 0; r < 8; ++r) + { + for (auto& plane : state) + for (auto& v : plane) + v = _mm512_aesenc_epi128(v, roundKeys[r]); + } + for (unsigned choice = 0; choice < 4; ++choice) { - auto s = sendMsg.data(); - auto m = B.data() + i; + const auto& v = state[choice]; + const auto a = _mm512_permutex2var_epi8(v[0], diagonalIndex, v[1]); + const auto b = _mm512_permutex2var_epi8(v[2], diagonalIndex, v[3]); + auto columns = _mm512_shuffle_i32x4(a, b, 0x44); + columns = _mm512_aesenc_epi128(columns, key9); + // The final round leaves row zero in place and omits MixColumns. + columns = _mm512_aesenclast_epi128(columns, key10); + const u16 bits = _mm512_test_epi32_mask(columns, one) ^ inputBits; + std::memcpy(reinterpret_cast(mOts[choice].data()) + i / 8, &bits, sizeof(bits)); + } + } +#elif defined(ENABLE_SSE) && defined(__VAES__) && defined(__AVX2__) && !defined(__AVX512F__) + const auto& keys = oc::mAesFixedKey.mRoundKey; + __m256i roundKeys[10], first[4]; + for (unsigned r = 0; r < 10; ++r) + roundKeys[r] = _mm256_broadcastsi128_si256(keys[r + 1].mData); + for (unsigned choice = 0; choice < 4; ++choice) + first[choice] = _mm256_broadcastsi128_si256((keys[0] ^ deltas[choice]).mData); + + for (u64 i = 0; i < B.size(); i += 8) + { + __m256i raw[4]; + for (unsigned j = 0; j < 4; ++j) + raw[j] = _mm256_loadu_si256(reinterpret_cast(B.data() + i + 2 * j)); + const auto inputWords = lowWords(raw[0], raw[1], raw[2], raw[3]); - switch (b) - { - case 0: + // Two choices keep eight independent VAES chains in flight. + for (unsigned choice = 0; choice < 4; choice += 2) + { + __m256i state[2][4]; + for (unsigned c = 0; c < 2; ++c) + for (unsigned j = 0; j < 4; ++j) + state[c][j] = _mm256_xor_si256(raw[j], first[choice + c]); +#pragma GCC unroll 9 + for (unsigned r = 0; r < 9; ++r) + for (auto& plane : state) + for (auto& v : plane) + v = _mm256_aesenc_epi128(v, roundKeys[r]); + + for (unsigned c = 0; c < 2; ++c) { - for (u64 j = 0; j < 2; ++j) - { - assert((m[0].get(0) & 3) == 0); - - m[0] = m[0] & mask; - m[1] = m[1] & mask; - m[2] = m[2] & mask; - m[3] = m[3] & mask; - m[4] = m[4] & mask; - m[5] = m[5] & mask; - m[6] = m[6] & mask; - m[7] = m[7] & mask; - - oc::mAesFixedKey.hashBlocks<8>(m, s); - - s += 8; - m += 8; - } - - break; + auto& plane = state[c]; + for (auto& v : plane) + v = _mm256_aesenclast_epi128(v, roundKeys[9]); + // Each delta has low bit zero, so the feed-forward bit is B's bit zero. + const auto hashed = _mm256_xor_si256(lowWords(plane[0], plane[1], plane[2], plane[3]), inputWords); + reinterpret_cast(mOts[choice + c].data())[i / 8] = packBit<0>(inInputOrder(hashed)); } - case 1: - case 2: - case 3: - for (u64 j = 0; j < 2; ++j) - { - s[0] = m[0] ^ deltas[b]; - s[1] = m[1] ^ deltas[b]; - s[2] = m[2] ^ deltas[b]; - s[3] = m[3] ^ deltas[b]; - s[4] = m[4] ^ deltas[b]; - s[5] = m[5] ^ deltas[b]; - s[6] = m[6] ^ deltas[b]; - s[7] = m[7] ^ deltas[b]; - - oc::mAesFixedKey.hashBlocks<8>(s, s); - - s += 8; - m += 8; - } - break; - default: - assert(0); - //__assume(0); - break; - } - - block a00 = shuffle_epi8(sendMsg[0], shuffle[0]); - block a01 = shuffle_epi8(sendMsg[1], shuffle[1]); - block a02 = shuffle_epi8(sendMsg[2], shuffle[2]); - block a03 = shuffle_epi8(sendMsg[3], shuffle[3]); - block a04 = shuffle_epi8(sendMsg[4], shuffle[4]); - block a05 = shuffle_epi8(sendMsg[5], shuffle[5]); - block a06 = shuffle_epi8(sendMsg[6], shuffle[6]); - block a07 = shuffle_epi8(sendMsg[7], shuffle[7]); - block a08 = shuffle_epi8(sendMsg[8], shuffle[8]); - block a09 = shuffle_epi8(sendMsg[9], shuffle[9]); - block a10 = shuffle_epi8(sendMsg[10], shuffle[10]); - block a11 = shuffle_epi8(sendMsg[11], shuffle[11]); - block a12 = shuffle_epi8(sendMsg[12], shuffle[12]); - block a13 = shuffle_epi8(sendMsg[13], shuffle[13]); - block a14 = shuffle_epi8(sendMsg[14], shuffle[14]); - block a15 = shuffle_epi8(sendMsg[15], shuffle[15]); - - a00 = a00 ^ a08; - a01 = a01 ^ a09; - a02 = a02 ^ a10; - a03 = a03 ^ a11; - a04 = a04 ^ a12; - a05 = a05 ^ a13; - a06 = a06 ^ a14; - a07 = a07 ^ a15; - - a00 = a00 ^ a04; - a01 = a01 ^ a05; - a02 = a02 ^ a06; - a03 = a03 ^ a07; - - a00 = a00 ^ a02; - a01 = a01 ^ a03; - - a00 = a00 ^ a01; - - a00 = slli_epi16<7>(a00); - - u16 ap = movemask_epi8(a00); - - assert(iters[b] + sizeof(ap) <= reinterpret_cast(mOts[b].data() + mOts[b].size())); - std::memcpy(iters[b], &ap, sizeof(ap)); - iters[b] += sizeof(ap); } } +#else + for (u64 i = 0; i < B.size(); i += packedOt::groupSize) + { + const packedOt::Group group(B.data() + i); + for (unsigned choice = 0; choice < 4; ++choice) + packedOt::store(mOts[choice].data(), i, group.hashes<0>(deltas[choice])); + } +#endif } - - -} \ No newline at end of file +} diff --git a/secure-join/CorGenerator/F4BitOtBatch.h b/secure-join/CorGenerator/F4BitOtBatch.h index 8a8a8c097..c1ac6671d 100644 --- a/secure-join/CorGenerator/F4BitOtBatch.h +++ b/secure-join/CorGenerator/F4BitOtBatch.h @@ -104,9 +104,9 @@ namespace secJoin void getCor(Cor* c, u64 begin, u64 size) override; - BaseRequest getBaseRequest() override; + BaseRequest getBaseRequest(StationaryWorker* worker) override; - void setBase(BaseCor& ) override; + void setBase(BaseCor& base, StationaryWorker* worker) override; // Get the task associated with this batch. macoro::task<> getTask(BatchThreadState&) override; @@ -121,13 +121,9 @@ namespace secJoin void clear() override { - if (mSendRecv.index()) - std::get<1>(mSendRecv).clear(); - else - std::get<1>(mSendRecv).clear(); - //mSendRecv = SendBatch{}; + std::visit([](auto& side) { side.clear(); }, mSendRecv); } }; -} \ No newline at end of file +} diff --git a/secure-join/CorGenerator/F4Vole/F4CoeffCtx.h b/secure-join/CorGenerator/F4Vole/F4CoeffCtx.h index 932a2ac00..a5879eeaf 100644 --- a/secure-join/CorGenerator/F4Vole/F4CoeffCtx.h +++ b/secure-join/CorGenerator/F4Vole/F4CoeffCtx.h @@ -24,6 +24,8 @@ namespace secJoin // A coefficient context for GF4 used in the VOLE protocol. struct CoeffCtxGF4 : oc::CoeffCtxInteger { + static constexpr bool blockCopyIsTrivialAndAdditionIsXor = true; + // the subfield as GF4 using G = F4; @@ -136,7 +138,7 @@ namespace secJoin // the protocol will perform binary decomposition // of F using this many bits template - u64 bitSize() + u64 bitSize() const { if (std::is_same::value) return 2; diff --git a/secure-join/CorGenerator/F4Vole/F4VoleCode.h b/secure-join/CorGenerator/F4Vole/F4VoleCode.h new file mode 100644 index 000000000..e310084ec --- /dev/null +++ b/secure-join/CorGenerator/F4Vole/F4VoleCode.h @@ -0,0 +1,58 @@ +#pragma once +#include "secure-join/Defines.h" +#include +#include +#if defined(ENABLE_SSE) && defined(__AVX2__) +#include +#endif + +namespace secJoin +{ + // Reserve the two GF(4) choice bits in each expanded leaf. Keep this scan + // outside the protocol coroutine so the loop state stays in registers. + OC_NOINLINE inline void clearF4ChoiceBits(span leaves) + { + const block mask(~0ull, ~3ull); + u64 i = 0; +#if defined(ENABLE_SSE) && defined(__AVX2__) + const auto wideMask = _mm256_broadcastsi128_si256(mask.mData); + for (; i + 2 <= leaves.size(); i += 2) + { + auto* p = reinterpret_cast<__m256i*>(leaves.data() + i); + _mm256_storeu_si256(p, _mm256_and_si256(_mm256_loadu_si256(p), wideMask)); + } +#endif + for (; i < leaves.size(); ++i) + leaves[i] &= mask; + } + + inline oc::SdConfig configureF4Code(u64 security, u64 size, oc::MultType type, + oc::SdNoiseDistribution noise = oc::SdNoiseDistribution::Regular) + { + if (noise != oc::SdNoiseDistribution::Regular && + (noise != oc::SdNoiseDistribution::Stationary || type != oc::MultType::Spin)) + throw std::invalid_argument("Stationary GF(4) VOLE requires SPIN"); + // libOTe tunes regular binary SPIN noise with a character factor of 2. + // Uniform nonzero GF(4) coefficients give 4/3. Use its more conservative + // factor-one partition count for both modes. + if (type == oc::MultType::Spin) + return oc::SpinConfigure(security, size, oc::SdNoiseDistribution::Stationary); + return oc::syndromeDecodingConfigure(security, size, type, + oc::SdNoiseDistribution::Regular, {4.0 / 3.0}); + } + + // One immutable public regular map per padded K for the life of the process. + void prepareRegularSpin(std::optional& code, u64 size); + + inline void compressF4Spin(std::optional& code, u64 size, + span values, oc::SdNoiseDistribution noise, block& seed) + { + if (noise == oc::SdNoiseDistribution::Regular) + prepareRegularSpin(code, size); + else + oc::SpinCode::prepare(code, size, seed, noise); + code->transpose(values); + if (noise == oc::SdNoiseDistribution::Stationary) + seed = oc::mAesFixedKey.hashBlock(seed); + } +} diff --git a/secure-join/CorGenerator/F4Vole/SilentF4VoleReceiver.h b/secure-join/CorGenerator/F4Vole/SilentF4VoleReceiver.h index 9bd22ca3f..d7cf588cc 100644 --- a/secure-join/CorGenerator/F4Vole/SilentF4VoleReceiver.h +++ b/secure-join/CorGenerator/F4Vole/SilentF4VoleReceiver.h @@ -12,6 +12,7 @@ #include #include #include "libOTe/Tools/Pprf/RegularPprf.h" +#include "libOTe/Tools/Pprf/StationaryPprf.h" #include #include #include @@ -25,6 +26,7 @@ #include #include "libOTe/Tools/ExConvCode/ExConvCode.h" #include "F4CoeffCtx.h" +#include "F4VoleCode.h" namespace secJoin { @@ -80,11 +82,26 @@ namespace secJoin // The matrix multiplication type which compresses // the sparse vector. - oc::MultType mMultType = oc::DefaultMultType; + oc::MultType mMultType = oc::MultType::Spin; + std::optional mSpin; // The multi-point punctured PRF for generating // the sparse vectors. - oc::RegularPprfReceiver mGen; + oc::RegularPprfReceiver mGen; + std::unique_ptr> mStationary; + block mCodeSeed = oc::ZeroBlock; + + auto& gen() const { + using Base = oc::PprfReceiver; + return mStationary ? static_cast(*mStationary) : static_cast(mGen); + } + auto& gen() { + using Base = oc::PprfReceiver; + return mStationary ? static_cast(*mStationary) : static_cast(mGen); + } + auto format() const { + return mStationary ? oc::PprfOutputFormat::ByTreeIndex : oc::PprfOutputFormat::ByPhysicalIndex; + } // The internal buffers for holding the expanded vectors. // mA = mB + mC * delta @@ -129,7 +146,7 @@ namespace secJoin // // returns true if the silent base OTs are set. bool hasSilentBaseOts() const { - return mGen.hasBaseOts(); + return gen().hasBaseOts(); }; // // // Generate the IKNP base OTs @@ -223,7 +240,11 @@ namespace secJoin msg.resize(msg.size() - mOtExtSender->baseOtCount()); co_await nv.receive(noiseVals, baseAs, prng, *mOtExtSender, chl, mCtx); } - else + else if (msg.empty()) + { + co_await nv.receive(noiseVals, baseAs, prng, *mOtExtSender, chl, mCtx); + } + else { chl2 = chl.fork(); prng2.SetSeed(prng.get()); @@ -271,7 +292,7 @@ namespace secJoin u64 requestSize, oc::SilentBaseType type = oc::SilentBaseType::BaseExtend, u64 secParam = 128, - Ctx ctx = {}) + Ctx ctx = {}, oc::SdNoiseDistribution noise = oc::SdNoiseDistribution::Regular) { mCtx = std::move(ctx); mSecParam = secParam; @@ -280,10 +301,21 @@ namespace secJoin mBaseType = type; - syndromeDecodingConfigure(mNumPartitions, mSizePer, mNoiseVecSize, mSecParam, mRequestSize, mMultType); + const auto config = configureF4Code(mSecParam, mRequestSize, mMultType, noise); + mNumPartitions = config.mNumPartitions; + mSizePer = config.mSizePer; + mNoiseVecSize = config.mNoiseVectorSize; - mGen.configure(mSizePer, mNumPartitions); + if (noise == oc::SdNoiseDistribution::Stationary) + { + mCodeSeed = block(12528943721987127, 98743297823479812); + mSpin.reset(); + mStationary = std::make_unique>(); + } + else + mStationary.reset(); + gen().configure(mSizePer, mNumPartitions); } // return true if this instance has been configured. @@ -296,7 +328,7 @@ namespace secJoin if (isConfigured() == false) throw std::runtime_error("configure must be called first"); - return mGen.baseOtCount(); + return gen().baseOtCount(); } @@ -309,11 +341,21 @@ namespace secJoin if (isConfigured() == false) throw std::runtime_error("configure(...) must be called first"); - auto choice = mGen.sampleChoiceBits(prng); + auto choice = gen().sampleChoiceBits(prng); return choice; } + void recordPoints() + { + mS.resize(mNumPartitions); + gen().getPoints(mS, format()); + // Tree-index PPRF returns a local leaf for each contiguous tree. + if (mStationary) + for (u64 i = 0; i < mNumPartitions; ++i) + mS[i] += i * mSizePer; + } + VecG sampleBaseVoleVals(PRNG& prng) { if (isConfigured() == false) @@ -325,38 +367,14 @@ namespace secJoin mCtx.resize(mBaseC, mNumPartitions + (mMalType == oc::SilentSecType::Malicious)); - if (mCtx.template bitSize() == 1) - { - mCtx.one(mBaseC.begin(), mBaseC.begin() + mNumPartitions); - } - else + // Regular noise is uniform on the three nonzero values. Stationary includes zero. + for (u64 i = 0; i < mNumPartitions; ++i) { - VecG zero, one; - mCtx.resize(zero, 1); - mCtx.resize(one, 1); - mCtx.zero(zero.begin(), zero.end()); - mCtx.one(one.begin(), one.end()); - for (size_t i = 0; i < mNumPartitions; i++) - { - mCtx.fromBlock(mBaseC[i], prng.get()); - - // must not be zero. - while (mCtx.eq(zero[0], mBaseC[i])) - mCtx.fromBlock(mBaseC[i], prng.get()); - - // if we are not a field, then the noise should be odd. - if (mCtx.template isField() == false) - { - u8 odd = mCtx.binaryDecomposition(mBaseC[i])[0]; - if (odd) - mCtx.plus(mBaseC[i], mBaseC[i], one[0]); - } - } + do { mBaseC[i].mVal = prng.get() & 3; } while (!mStationary && !mBaseC[i].mVal); } - - mS.resize(mNumPartitions); - mGen.getPoints(mS, oc::PprfOutputFormat::Interleaved); + if (!mStationary || !mStationary->mExpanded) + recordPoints(); if (mMalType == oc::SilentSecType::Malicious) { @@ -395,13 +413,13 @@ namespace secJoin if (static_cast(recvBaseOts.size()) != silentBaseOtCount()) throw std::runtime_error("wrong number of silent base OTs"); - mGen.setBase(recvBaseOts); - - mCtx.resize(mBaseA, baseA.size()); - mCtx.copy(baseA.begin(), baseA.end(), mBaseA.begin()); + if (baseA.size() != baseVoleCount()) + throw std::invalid_argument("Wrong number of base GF(4) VOLEs"); + gen().setBase(recvBaseOts); - for (u64 i = 0; i < mBaseA.size(); ++i) - mBaseA[i] &= (block(~0ull, ~0ull << 2)); + mBaseA.resize(baseA.size()); + for (u64 i = 0; i < baseA.size(); ++i) + mBaseA[i] = baseA[i] & block(~0ull, ~3ull); mState = State::HasBase; } @@ -421,7 +439,8 @@ namespace secJoin mCtx.copy(mA.begin(), mA.begin() + a.size(), a.begin()); - clear(); + if (!mStationary) + clear(); } MACORO_CATCH(exPtr) { if(!chl.closed()) co_await chl.close(); @@ -461,7 +480,8 @@ namespace secJoin co_await chl.send(std::move(diff)); - clear(); + if (!mStationary) + clear(); } MACORO_CATCH(exPtr) { if (!chl.closed()) co_await chl.close(); @@ -492,7 +512,7 @@ namespace secJoin if (mRequestSize < n) throw std::invalid_argument("n does not match the requested number of OTs via configure(...). " LOCATION); - if (hasSilentBaseOts() == false) + if (!hasSilentBaseOts() || mBaseA.empty()) { co_await genSilentBaseOts(prng, chl); } @@ -500,14 +520,13 @@ namespace secJoin setTimePoint("SilentVoleReceiver.alloc"); // allocate mA - mCtx.resize(mA, 0); - mCtx.resize(mA, mNoiseVecSize); + mA.reserve(mNoiseVecSize); setTimePoint("SilentVoleReceiver.alloc.zero"); if (mTimer) - mGen.setTimer(*mTimer); + gen().setTimer(*mTimer); // As part of the setup, we have generated // @@ -527,7 +546,11 @@ namespace secJoin // // mA = mB + mS(mBaseC * mDelta) // - co_await mGen.expand(chl, mA, oc::PprfOutputFormat::Interleaved, true, mNumThreads); + mA.resize(mNumPartitions * mSizePer); + co_await gen().expand(chl, mA, format(), true, mNumThreads, mCtx); + clearF4ChoiceBits(mA); + mA.resize(mNoiseVecSize); + std::fill(mA.begin() + mNumPartitions * mSizePer, mA.end(), oc::ZeroBlock); setTimePoint("SilentVoleReceiver.expand.pprf_transpose"); @@ -574,6 +597,10 @@ namespace secJoin switch (mMultType) { + case oc::MultType::Spin: + compressF4Spin(mSpin, mRequestSize, mA, mStationary ? + oc::SdNoiseDistribution::Stationary : oc::SdNoiseDistribution::Regular, mCodeSeed); + break; case osuCrypto::MultType::ExConv7x24: case osuCrypto::MultType::ExConv21x24: { @@ -612,7 +639,7 @@ namespace secJoin // make the protocol as done and that // mA,mC are ready to be consumed. - mState = State::Default; + mState = mStationary ? State::Configured : State::Default; if (mDebug) { @@ -802,7 +829,8 @@ namespace secJoin mS = {}; mA = {}; //mC = {}; - mGen.clear(); + gen().clear(); + mState = State::Default; } }; } diff --git a/secure-join/CorGenerator/F4Vole/SilentF4VoleSender.h b/secure-join/CorGenerator/F4Vole/SilentF4VoleSender.h index 5441d006f..9c2b944b0 100644 --- a/secure-join/CorGenerator/F4Vole/SilentF4VoleSender.h +++ b/secure-join/CorGenerator/F4Vole/SilentF4VoleSender.h @@ -14,6 +14,7 @@ #include #include #include "libOTe/Tools/Pprf/RegularPprf.h" +#include "libOTe/Tools/Pprf/StationaryPprf.h" #include #include #include @@ -25,6 +26,7 @@ #include #include #include "F4CoeffCtx.h" +#include "F4VoleCode.h" namespace secJoin { @@ -57,7 +59,21 @@ namespace secJoin Ctx mCtx; // the pprf used to generate the noise vector. - oc::RegularPprfSender mGen; + oc::RegularPprfSender mGen; + std::unique_ptr> mStationary; + block mCodeSeed = oc::ZeroBlock; + + auto& gen() const { + using Base = oc::PprfSender; + return mStationary ? static_cast(*mStationary) : static_cast(mGen); + } + auto& gen() { + using Base = oc::PprfSender; + return mStationary ? static_cast(*mStationary) : static_cast(mGen); + } + auto format() const { + return mStationary ? oc::PprfOutputFormat::ByTreeIndex : oc::PprfOutputFormat::ByPhysicalIndex; + } // the number of correlations requested. u64 mRequestSize = 0; @@ -96,7 +112,8 @@ namespace secJoin oc::SilentSecType mMalType = oc::SilentSecType::SemiHonest; // A flag to specify the linear code to use - oc::MultType mMultType = oc::DefaultMultType; + oc::MultType mMultType = oc::MultType::Spin; + std::optional mSpin; VecF mEncodeTemp; @@ -111,7 +128,7 @@ namespace secJoin bool hasSilentBaseOts()const { - return mGen.hasBaseOts(); + return gen().hasBaseOts(); } @@ -180,6 +197,10 @@ namespace secJoin co_await nv.send(delta, b, prng, *mOtExtRecver, chl, mCtx); } + else if (msg.empty()) + { + co_await nv.send(delta, b, prng, *mOtExtRecver, chl, mCtx); + } else { chl2 = chl.fork(); @@ -225,7 +246,7 @@ namespace secJoin u64 requestSize, oc::SilentBaseType type = oc::SilentBaseType::BaseExtend, u64 secParam = 128, - Ctx ctx = {}) + Ctx ctx = {}, oc::SdNoiseDistribution noise = oc::SdNoiseDistribution::Regular) { mCtx = std::move(ctx); mSecParam = secParam; @@ -233,11 +254,20 @@ namespace secJoin mState = State::Configured; mBaseType = type; - syndromeDecodingConfigure( - mNumPartitions, mSizePer, mNoiseVecSize, - mSecParam, mRequestSize, mMultType); + const auto config = configureF4Code(mSecParam, mRequestSize, mMultType, noise); + mNumPartitions = config.mNumPartitions; + mSizePer = config.mSizePer; + mNoiseVecSize = config.mNoiseVectorSize; - mGen.configure(mSizePer, mNumPartitions); + if (noise == oc::SdNoiseDistribution::Stationary) + { + mCodeSeed = block(12528943721987127, 98743297823479812); + mSpin.reset(); + mStationary = std::make_unique>(); + } + else + mStationary.reset(); + gen().configure(mSizePer, mNumPartitions); } // return true if this instance has been configured. @@ -250,7 +280,7 @@ namespace secJoin if (isConfigured() == false) throw std::runtime_error("configure must be called first"); - return mGen.baseOtCount(); + return gen().baseOtCount(); } // Set the externally generated base OTs. This choice @@ -263,28 +293,15 @@ namespace secJoin throw RTE_LOC; if (b.size() != baseVoleCount()) - throw RTE_LOC; + throw std::invalid_argument("Wrong number of base GF(4) VOLEs"); + gen().setBase(sendBaseOts); - mGen.setBase(sendBaseOts); - - - // we store the negative of b. This is because - // we need the correlation - // - // mBaseA + mBaseB = mBaseC * delta - // - // for the pprf to expand correctly but the - // input correlation is a vole: - // - // mBaseA = b + mBaseC * delta - // - mCtx.resize(mBaseB, b.size()); - mCtx.zero(mBaseB.begin(), mBaseB.end()); - for (u64 i = 0; i < mBaseB.size(); ++i) - { - mCtx.minus(mBaseB[i], mBaseB[i], b[i]); - mBaseB[i] &= (block(~0ull, ~0ull << 2)); - } + + // Negation in characteristic two is the identity. Reserve the + // bottom two bits in each share for the receiver's coefficient. + mBaseB.resize(b.size()); + for (u64 i = 0; i < b.size(); ++i) + mBaseB[i] = b[i] & block(~0ull, ~3ull); } // The native OT extension interface of silent @@ -303,7 +320,8 @@ namespace secJoin co_await silentSendInplace(delta, b.size(), prng, chl); mCtx.copy(mB.begin(), mB.begin() + b.size(), b.begin()); - clear(); + if (!mStationary) + clear(); setTimePoint("SilentVoleSender.expand.ldpc.msgCpy"); @@ -343,7 +361,8 @@ namespace secJoin } setTimePoint("SilentVoleSender.expand.derandomize"); - clear(); + if (!mStationary) + clear(); } MACORO_CATCH(exPtr) { co_await chl.close(); @@ -380,7 +399,7 @@ namespace secJoin if (mRequestSize < n) throw std::invalid_argument("n does not match the requested number of OTs via configure(...). " LOCATION); - if (mGen.hasBaseOts() == false) + if (!gen().hasBaseOts() || mBaseB.empty()) { // recvs data co_await genSilentBaseOts(prng, chl, delta); @@ -390,11 +409,10 @@ namespace secJoin //gTimer.setTimePoint("SilentVoleSender.iknp.base2"); // allocate B - mCtx.resize(mB, 0); - mCtx.resize(mB, mNoiseVecSize); + mB.reserve(mNoiseVecSize); if (mTimer) - mGen.setTimer(*mTimer); + gen().setTimer(*mTimer); // extract just the first mNumPartitions value of mBaseB. // the last is for the malicious check (if present). @@ -405,8 +423,18 @@ namespace secJoin // our secret share of delta * noiseVals. The receiver // can then manually add their shares of this to the // output of the PPRF at the correct locations. - co_await mGen.expand(chl, baseB, prng.get(), mB, - oc::PprfOutputFormat::Interleaved, true, 1); + mB.resize(mNumPartitions * mSizePer); + co_await gen().expand(chl, baseB, prng.get(), mB, + format(), true, 1, mCtx); + // The SPIN transpose applies the same binary map to every payload bit. + // When no check reads the expanded shares, clear the two reserved + // bits on the shorter output instead. + const bool maskAfterSpin = mMultType == oc::MultType::Spin && !mDebug && + mMalType == oc::SilentSecType::SemiHonest; + if (!maskAfterSpin) + clearF4ChoiceBits(mB); + mB.resize(mNoiseVecSize); + std::fill(mB.begin() + mNumPartitions * mSizePer, mB.end(), oc::ZeroBlock); setTimePoint("SilentVoleSender.expand.pprf"); if (mDebug) @@ -429,6 +457,10 @@ namespace secJoin switch (mMultType) { + case oc::MultType::Spin: + compressF4Spin(mSpin, mRequestSize, mB, mStationary ? + oc::SdNoiseDistribution::Stationary : oc::SdNoiseDistribution::Regular, mCodeSeed); + break; case osuCrypto::MultType::ExConv7x24: case osuCrypto::MultType::ExConv21x24: { @@ -457,9 +489,11 @@ namespace secJoin } mCtx.resize(mB, mRequestSize); + if (maskAfterSpin) + clearF4ChoiceBits(mB); - mState = State::Default; + mState = mStationary ? State::Configured : State::Default; mBaseB.clear(); if (mDebug) @@ -560,7 +594,8 @@ namespace secJoin void clear() { mB = {}; - mGen.clear(); + gen().clear(); + mState = State::Default; } }; diff --git a/secure-join/CorGenerator/OtBatch.cpp b/secure-join/CorGenerator/OtBatch.cpp index 7ecb36fa3..113de34f6 100644 --- a/secure-join/CorGenerator/OtBatch.cpp +++ b/secure-join/CorGenerator/OtBatch.cpp @@ -21,10 +21,10 @@ namespace secJoin { mMsg.resize(mReceiver.mRequestNumOts); mChoice.resize(mReceiver.mRequestNumOts); - assert(mReceiver.mGen.hasBaseOts()); - mReceiver.mMultType = oc::MultType::Tungsten; + assert(mReceiver.hasBaseCors()); - return mReceiver.silentReceive(mChoice, mMsg, prng, sock); + co_await mReceiver.silentReceiveInplace(mMsg.size(), prng, sock, oc::ChoiceBitPacking::True); + mReceiver.hash(mChoice, mMsg, oc::ChoiceBitPacking::True); } void OtBatch::RecvOtBatch::mock(u64 batchIdx) @@ -46,10 +46,10 @@ namespace secJoin macoro::task<> OtBatch::SendOtBatch::sendTask(PRNG& prng, oc::Socket& sock) { mMsg2.resize(mSender.mRequestNumOts); - assert(mSender.hasSilentBaseOts()); - mSender.mMultType = oc::MultType::Tungsten; + assert(mSender.hasBaseCors()); - return mSender.silentSend(mMsg2, prng, sock); + co_await mSender.silentSendInplace(mSender.mDelta, mMsg2.size(), prng, sock); + mSender.hash(mMsg2, oc::ChoiceBitPacking::True); } void OtBatch::SendOtBatch::mock(u64 batchIdx) @@ -99,20 +99,23 @@ namespace secJoin }; } - BaseRequest OtBatch::getBaseRequest() + BaseRequest OtBatch::getBaseRequest(StationaryWorker* worker) { BaseRequest r; if (mGenState->mMock) return r; + if (worker) + return worker->requestOtBase(CorType::Ot, mSize, mSendRecv.index() == 0, mPrng); + mSendRecv | match{ [&](SendOtBatch& send) { - send.mSender.configure(mSize); - r.mSendSize = send.mSender.silentBaseOtCount(); + configureBatchOt(send.mSender, mSize); + r.mSendSize = send.mSender.baseCount().mBaseOtCount; }, [&](RecvOtBatch& recv) { - recv.mReceiver.configure(mSize); + configureBatchOt(recv.mReceiver, mSize); r.mChoice = recv.mReceiver.sampleBaseChoiceBits(mPrng); } }; @@ -120,17 +123,20 @@ namespace secJoin return r; } - void OtBatch::setBase(BaseCor& base) + void OtBatch::setBase(BaseCor& base, StationaryWorker* worker) { if (mGenState->mMock) return; + if (worker) + return worker->setOtBase(CorType::Ot, mSize, mSendRecv.index() == 0, base); + mSendRecv | match{ [&](SendOtBatch& send) { - send.mSender.setSilentBaseOts(base.getSendOt(send.mSender.silentBaseOtCount())); + send.mSender.setBaseCors(base.getSendOt(send.mSender.baseCount().mBaseOtCount), {}, mPrng.get()); }, [&](RecvOtBatch& recv) { - recv.mReceiver.setSilentBaseOts(base.getRecvOt(recv.mReceiver.silentBaseOtCount())); + base.setOtBase(recv.mReceiver); } }; } @@ -153,26 +159,49 @@ namespace secJoin } }; } + else if (threadState.mStationary) + { + auto& worker = *threadState.mStationary; + if (mSendRecv.index() == 0) + { + auto& send = std::get<0>(mSendRecv); + auto& protocol = worker.begin(worker.sendOt, CorType::Ot, mSize, true); + co_await protocol.silentSendInplace(protocol.mDelta, mSize, mPrng, mSock); + send.mMsg2.resize(mSize); + protocol.hash(send.mMsg2, oc::ChoiceBitPacking::True); + worker.finish(protocol); + } + else + { + auto& recv = std::get<1>(mSendRecv); + auto& protocol = worker.begin(worker.recvOt, CorType::Ot, mSize, false); + co_await protocol.silentReceiveInplace(mSize, mPrng, mSock, oc::ChoiceBitPacking::True); + recv.mChoice.resize(mSize); + recv.mMsg.resize(mSize); + protocol.hash(recv.mChoice, recv.mMsg, oc::ChoiceBitPacking::True); + worker.finish(protocol); + } + } else { if (mGenState->mDebug) { if (mSendRecv.index() == 0) { - co_await mSock.send(coproto::copy(std::get<0>(mSendRecv).mSender.mGen.mBaseOTs)); + co_await mSock.send(coproto::copy(std::get<0>(std::get<0>(mSendRecv).mSender.mGenVar).mBaseOTs)); } else { - msg.resize(std::get<1>(mSendRecv).mReceiver.silentBaseOtCount()); + msg.resize(std::get<1>(mSendRecv).mReceiver.baseCount().mBaseOtCount); co_await mSock.recv(msg); { auto& recv = std::get<1>(mSendRecv); for (u64 i = 0; i < msg.size(); ++i) { - if (recv.mReceiver.mGen.mBaseOTs(i) != msg[i][recv.mReceiver.mGen.mBaseChoices(i)]) + if (std::get<0>(recv.mReceiver.mGenVar).mBaseOTs(i) != msg[i][std::get<0>(recv.mReceiver.mGenVar).mBaseChoices(i)]) { std::cout << "OtBatch::getTask() base OTs do not match. " << LOCATION << std::endl; std::terminate(); @@ -185,13 +214,15 @@ namespace secJoin [&](SendOtBatch& send) { send.mSender.mB = std::move(threadState.mB); - send.mSender.mEncodeTemp = std::move(threadState.mEncodeTemp); + send.mSender.mSpin = std::move(threadState.mSpin); + std::get<0>(send.mSender.mGenVar).mTempBuffer = std::move(threadState.mPprfTemp); //send.mMsg2 = std::move(threadState.mMsg2); return send.sendTask(mPrng, mSock); }, [&](RecvOtBatch& recv) { recv.mReceiver.mA = std::move(threadState.mA); - recv.mReceiver.mEncodeTemp = std::move(threadState.mEncodeTemp); + recv.mReceiver.mSpin = std::move(threadState.mSpin); + std::get<0>(recv.mReceiver.mGenVar).mTempBuffer = std::move(threadState.mPprfTemp); //recv.mChoice = std::move(threadState.mChoice); //recv.mMsg = std::move(threadState.mMsg); return recv.recvTask(mPrng, mSock); @@ -204,12 +235,16 @@ namespace secJoin mSendRecv | match{ [&](SendOtBatch& send) { threadState.mB = std::move(send.mSender.mB); - threadState.mEncodeTemp = std::move(send.mSender.mEncodeTemp); + threadState.mSpin = std::move(send.mSender.mSpin); + threadState.mPprfTemp = std::move(std::get<0>(send.mSender.mGenVar).mTempBuffer); + send.mSender.clear(); //threadState.mMsg2 = std::move(send.mMsg2); }, [&](RecvOtBatch& recv) { threadState.mA = std::move(recv.mReceiver.mA); - threadState.mEncodeTemp = std::move(recv.mReceiver.mEncodeTemp); + threadState.mSpin = std::move(recv.mReceiver.mSpin); + threadState.mPprfTemp = std::move(std::get<0>(recv.mReceiver.mGenVar).mTempBuffer); + recv.mReceiver.clear(); //threadState.mChoice = std::move(recv.mChoice); //threadState.mMsg = std::move(recv.mMsg); } diff --git a/secure-join/CorGenerator/OtBatch.h b/secure-join/CorGenerator/OtBatch.h index dafa3cc3c..46f824fde 100644 --- a/secure-join/CorGenerator/OtBatch.h +++ b/secure-join/CorGenerator/OtBatch.h @@ -45,9 +45,9 @@ namespace secJoin void getCor(Cor* c, u64 begin, u64 size) override; - BaseRequest getBaseRequest() override; + BaseRequest getBaseRequest(StationaryWorker* worker) override; - void setBase(BaseCor& base) override; + void setBase(BaseCor& base, StationaryWorker* worker) override; // Get the task associated with this batch. macoro::task<> getTask(BatchThreadState&) override; diff --git a/secure-join/CorGenerator/PackedOtHash.h b/secure-join/CorGenerator/PackedOtHash.h new file mode 100644 index 000000000..8671a95e8 --- /dev/null +++ b/secure-join/CorGenerator/PackedOtHash.h @@ -0,0 +1,174 @@ +#pragma once +#include "secure-join/Util/Simd.h" +#include "cryptoTools/Crypto/AES.h" +#include + +// Pack one output bit per input block in the protocol's little-endian bit order. +namespace secJoin::packedOt +{ +#if defined(ENABLE_SSE) && defined(__VAES__) && defined(__AVX2__) && !defined(__AVX512F__) + // The two 128-bit lanes gather the low words of the even and odd inputs. + OC_FORCEINLINE __m256i lowWords(__m256i a, __m256i b, __m256i c, __m256i d) + { + return _mm256_unpacklo_epi64(_mm256_unpacklo_epi32(a, b), _mm256_unpacklo_epi32(c, d)); + } + + OC_FORCEINLINE __m256i inInputOrder(__m256i words) + { + return _mm256_permutevar8x32_epi32(words, _mm256_setr_epi32(0, 4, 1, 5, 2, 6, 3, 7)); + } + + template + OC_FORCEINLINE u8 packBit(__m256i ordered) + { + return static_cast(_mm256_movemask_ps(_mm256_castsi256_ps(_mm256_slli_epi32(ordered, 31 - bit)))); + } + + template + OC_FORCEINLINE void compressReceiver256(span input, Output& hashes, + std::array choices) + { + static_assert(choiceBits == 1 || choiceBits == 2); + const auto& keys = oc::mAesFixedKey.mRoundKey; + __m256i roundKeys[11]; + for (unsigned r = 0; r < 11; ++r) + roundKeys[r] = _mm256_broadcastsi128_si256(keys[r].mData); + const auto messageMask = _mm256_broadcastsi128_si256(block(~0ull, ~((1ull << choiceBits) - 1)).mData); + + for (u64 i = 0; i < input.size(); i += 16) + { + __m256i state[8]; + for (unsigned j = 0; j < 8; j += 4) + { + __m256i raw[4]; + for (unsigned k = 0; k < 4; ++k) + { + raw[k] = _mm256_loadu_si256(reinterpret_cast(input.data() + i + 2 * (j + k))); + state[j + k] = _mm256_xor_si256(_mm256_and_si256(raw[k], messageMask), roundKeys[0]); + } + const auto words = inInputOrder(lowWords(raw[0], raw[1], raw[2], raw[3])); + reinterpret_cast(choices[0]->data())[i / 8 + j / 4] = packBit<0>(words); + if constexpr (choiceBits == 2) + reinterpret_cast(choices[1]->data())[i / 8 + j / 4] = packBit<1>(words); + } +#pragma GCC unroll 9 + for (unsigned r = 1; r < 10; ++r) + for (auto& v : state) + v = _mm256_aesenc_epi128(v, roundKeys[r]); + // The cleared choice bits make the Davies-Meyer feed-forward bit zero. + for (unsigned j = 0; j < 8; j += 4) + { + for (unsigned k = 0; k < 4; ++k) + state[j + k] = _mm256_aesenclast_epi128(state[j + k], roundKeys[10]); + const auto words = lowWords(state[j], state[j + 1], state[j + 2], state[j + 3]); + reinterpret_cast(hashes.data())[i / 8 + j / 4] = packBit<0>(inInputOrder(words)); + } + } + } +#endif +#if defined(ENABLE_SSE) && defined(__VAES__) && defined(__AVX512F__) + constexpr unsigned groupSize = 32; + using Word = u32; + + template + OC_FORCEINLINE Word pack(const __m512i (&values)[8]) + { + // Select the low 64-bit word of each of eight consecutive AES blocks. + const auto lowWords = _mm512_setr_epi64(0, 2, 4, 6, 8, 10, 12, 14); + Word bits = 0; +#pragma GCC unroll 4 + for (unsigned j = 0; j < 4; ++j) + { + const auto words = _mm512_permutex2var_epi64(values[2 * j], lowWords, values[2 * j + 1]); + bits |= Word(_mm512_test_epi64_mask(words, _mm512_set1_epi64(1ull << bit))) << (8 * j); + } + return bits; + } + + struct Group + { + __m512i raw[8]; + + OC_FORCEINLINE explicit Group(const block* messages) + { +#pragma GCC unroll 8 + for (unsigned j = 0; j < 8; ++j) + raw[j] = _mm512_loadu_si512(messages + 4 * j); + } + + template + OC_FORCEINLINE Word choices() const { return pack(raw); } + + // Return bit zero of H(x) = AES(x) ^ x, where x is message ^ delta + // with the low clearBits bits cleared. + template + OC_FORCEINLINE Word hashes(block delta = block(0, 0)) const + { + const auto& keys = oc::mAesFixedKey.mRoundKey; + const block messageMask(~0ull, ~((1ull << clearBits) - 1)); + const auto mask = _mm512_broadcast_i32x4(messageMask.mData); + const auto offset = _mm512_broadcast_i32x4((delta & messageMask).mData); + const auto first = _mm512_xor_si512(offset, _mm512_broadcast_i32x4(keys[0].mData)); + __m512i state[8]; +#pragma GCC unroll 8 + for (unsigned j = 0; j < 8; ++j) + state[j] = _mm512_xor_si512(_mm512_and_si512(raw[j], mask), first); +#pragma GCC unroll 9 + for (unsigned round = 1; round < 10; ++round) + { + const auto key = _mm512_broadcast_i32x4(keys[round].mData); +#pragma GCC unroll 8 + for (unsigned j = 0; j < 8; ++j) + state[j] = _mm512_aesenc_epi128(state[j], key); + } + const auto last = _mm512_broadcast_i32x4(keys[10].mData); +#pragma GCC unroll 8 + for (unsigned j = 0; j < 8; ++j) + { + state[j] = _mm512_aesenclast_epi128(state[j], last); + // A cleared low bit contributes zero to the Davies-Meyer XOR. + if constexpr (clearBits == 0) + state[j] = _mm512_xor_si512(state[j], _mm512_xor_si512(raw[j], offset)); + } + return pack<0>(state); + } + }; +#else + constexpr unsigned groupSize = 16; + using Word = u16; + + struct Group + { + const block* messages; + explicit Group(const block* p) : messages(p) {} + + template + OC_FORCEINLINE Word choices() const { return packByteBits(gatherLowBytes(messages)); } + + template + OC_FORCEINLINE Word hashes(block delta = block(0, 0)) const + { + const block mask(~0ull, ~((1ull << clearBits) - 1)); + block hashed[groupSize]; + for (unsigned i = 0; i < groupSize; i += 8) + { + auto batch = hashed + i; +#if defined(__GNUC__) +#pragma GCC unroll 8 +#endif + for (unsigned j = 0; j < 8; ++j) + batch[j] = (messages[i + j] ^ delta) & mask; + if constexpr (clearBits == 0) + oc::mAesFixedKey.hashBlocks<8>(batch, batch); + else + oc::mAesFixedKey.ecbEncBlocks<8>(batch, batch); + } + return packByteBits<0>(gatherLowBytes(hashed)); + } + }; +#endif + OC_FORCEINLINE void store(block* output, u64 i, Word bits) + { + std::memcpy(reinterpret_cast(output) + i / 8, &bits, sizeof(bits)); + } +} diff --git a/secure-join/CorGenerator/Request.cpp b/secure-join/CorGenerator/Request.cpp index ef9941353..8ec57d76d 100644 --- a/secure-join/CorGenerator/Request.cpp +++ b/secure-join/CorGenerator/Request.cpp @@ -43,19 +43,16 @@ namespace secJoin void RequestState::startReq() { - for (u64 i = 0; i < mBatches_.size(); ++i) - { - // the batch might have already finished. lets see if it exists - // and if it needs to be started. - auto batch = mBatches_[i].mWeakBatch.lock(); - if(batch) - batch->start(); - } + // The generator starts batches in index order. Starting the last + // segment also releases every preceding segment of this request. + if (!mBatches_.empty()) + if (auto last = mBatches_.back().mWeakBatch.lock()) + last->start(); } u64 RequestState::batchCount() { - return oc::divCeil(mSize, mGenState->mBatchSize) + 1; + return mBatches_.size(); } u64 RequestState::size() { return mSize; } diff --git a/secure-join/CorGenerator/Request.h b/secure-join/CorGenerator/Request.h index 45f980804..1bb98e0b5 100644 --- a/secure-join/CorGenerator/Request.h +++ b/secure-join/CorGenerator/Request.h @@ -76,6 +76,8 @@ namespace secJoin auto batch = &mReqState->mBatches_[mReqState->mNextBatchIdx++]; co_await batch->mBatch->mCorReady; + if (batch->mBatch->mError) + std::rethrow_exception(batch->mBatch->mError); batch->mBatch->getCor(&d, batch->mBegin, batch->mSize); d.mBatch = std::move(batch->mBatch); } diff --git a/secure-join/CorGenerator/SpinWorker.cpp b/secure-join/CorGenerator/SpinWorker.cpp new file mode 100644 index 000000000..2f0a876f6 --- /dev/null +++ b/secure-join/CorGenerator/SpinWorker.cpp @@ -0,0 +1,115 @@ +#include "SpinWorker.h" +#include "Base.h" +#include + +namespace secJoin +{ + void prepareRegularSpin(std::optional& code, u64 size) + { + const auto k = oc::SpinCode::messageSize(size); + const block seed(12528943721987127, 98743297823479812); + if (code && code->messageSize() == k && + code->encoder().setup_options().mode == spin::SetupMode::Full) + { + const auto spec = code->encoder().specification(); + if (spec.route_seed == seed.get(0) && spec.inner_seed == seed.get(1)) + return; + } + static std::mutex mutex; + static std::map> plans; + std::shared_ptr plan; + { + std::lock_guard lock(mutex); + auto& entry = plans[k]; + if (!entry) + { + entry = std::make_shared(spin::CodeSpec{ + k, spin::Parameters::PacketRs8T64, seed.get(0), seed.get(1) }); + } + plan = entry; + } + code.emplace(std::move(plan)); + } + + std::vector SpinBankPool::acquire(u64 workers) + { + std::lock_guard lock(mutex); + std::vector result; + if (!idle.empty()) + { + result = std::move(idle.back()); + idle.pop_back(); + } + if (result.size() < workers) + result.resize(workers); + return result; + } + + void SpinBankPool::release(std::vector banks) + { + std::lock_guard lock(mutex); + idle.push_back(std::move(banks)); + } + + BaseRequest StationaryWorker::requestOtBase(CorType type, u64 size, bool sending, PRNG& prng) + { + BaseRequest request; + if (sending) + { + auto [protocol, fresh] = stream(sendOt, type, size, true); + const auto counts = protocol.baseCount(); + if (fresh) + request.mSendSize = counts.mBaseOtCount; + request.mSendBinaryVoles = counts.mBaseVoleCount; + } + else + { + auto [protocol, fresh] = stream(recvOt, type, size, false); + if (fresh) + request.mChoice = protocol.sampleBaseChoiceBits(prng); + request.mRecvBinaryVoles = protocol.baseCount().mBaseVoleCount; + } + return request; + } + + void StationaryWorker::setOtBase(CorType type, u64 size, bool sending, BaseCor& base) + { + if (sending) + { + auto& protocol = sendOt.at({type, size}); + const auto counts = protocol.baseCount(); + auto noise = base.get(base.mBinaryB, base.mBinarySendIndex, counts.mBaseVoleCount); + protocol.setBaseCors(base.getSendOt(counts.mBaseOtCount), noise, base.mBinaryDelta); + } + else + { + auto& protocol = recvOt.at({type, size}); + const auto counts = protocol.baseCount(); + auto points = base.mOtRecvChoice.subvec(base.mOtRecvIndex, counts.mBaseOtCount); + auto choices = base.mBinaryChoice.subvec(base.mBinaryRecvIndex, counts.mBaseVoleCount); + auto noise = base.get(base.mBinaryA, base.mBinaryRecvIndex, counts.mBaseVoleCount); + protocol.setBaseCors(base.getRecvOt(counts.mBaseOtCount), points, noise, choices); + } + } + + u64 StationaryWorker::bankSeed(u64 size) const + { + // Distinct worker indices at fixed K, with the same public bank on both peers. + return oc::mAesFixedKey.ecbEncBlock(block(0x534a2d42414e4b31ull, + oc::SpinCode::messageSize(size))).get(0) + index; + } + + block StationaryWorker::initialSeed(CorType type, u64 size, u64 senderParty) const + { + oc::RandomOracle hash(sizeof(block)); + hash.Update("secure-join/stationary/stream/v1"); + hash.Update(session); + hash.Update(index); + hash.Update(static_cast(type)); + hash.Update(size); + hash.Update(senderParty); + block seed; + hash.Final(seed); + return seed; + } +} diff --git a/secure-join/CorGenerator/SpinWorker.h b/secure-join/CorGenerator/SpinWorker.h new file mode 100644 index 000000000..f8b8c06f9 --- /dev/null +++ b/secure-join/CorGenerator/SpinWorker.h @@ -0,0 +1,107 @@ +#pragma once + +#include "Correlations.h" +#include "F4Vole/SilentF4VoleReceiver.h" +#include "F4Vole/SilentF4VoleSender.h" +#include +#include +#include +#include +#include + +namespace secJoin +{ + struct BaseRequest; + struct BaseCor; + + struct SpinBanks + { + SpinBanks() = default; + SpinBanks(SpinBanks&&) = default; + SpinBanks(const SpinBanks&) = delete; + std::map> codes; + }; + + // Only public banks survive a new peer session. Each active run leases + // its own vector, including when start() overlaps a subsequent init(). + struct SpinBankPool + { + std::mutex mutex; + std::vector> idle; + std::vector acquire(u64 workers); + void release(std::vector banks); + }; + + struct StationaryWorker + { + StationaryWorker(u64 index, u64 party, block session, SpinBanks& banks) + : index(index), party(party), session(session), banks(banks) {} + + // One stream per exact request geometry, correlation family and direction. + // The batch borrows the returned stream until its conversion finishes. + template + std::pair stream(std::map, Protocol>& streams, + CorType type, u64 size, bool sending) + { + auto [it, fresh] = streams.try_emplace({type, size}); + auto& protocol = it->second; + if (fresh) + { + if constexpr (std::is_same_v || + std::is_same_v) + protocol.configure(size, oc::SilentBaseType::BaseExtend, 128, {}, oc::SdNoiseDistribution::Stationary); + else + protocol.configure(size, 2, 1, oc::SilentSecType::SemiHonest, + oc::SdNoiseDistribution::Stationary, oc::MultType::Spin); + protocol.mCodeSeed = initialSeed(type, size, sending ? party : 1 - party); + } + return {protocol, fresh}; + } + + template + Protocol& begin(std::map, Protocol>& streams, + CorType type, u64 size, bool sending) + { + auto& protocol = stream(streams, type, size, sending).first; + auto& bank = banks.codes[oc::SpinCode::messageSize(size)]; + if (!bank) + bank.emplace(size, protocol.mCodeSeed, oc::SdNoiseDistribution::Stationary, bankSeed(size)); + protocol.mSpin = std::exchange(bank, std::nullopt); + buffer(protocol) = std::move(blocks); + return protocol; + } + + template + void finish(Protocol& protocol) + { + auto& bank = banks.codes.at(protocol.mSpin->messageSize()); + bank = std::exchange(protocol.mSpin, std::nullopt); + blocks = std::move(buffer(protocol)); + } + + BaseRequest requestOtBase(CorType type, u64 size, bool sending, PRNG& prng); + void setOtBase(CorType type, u64 size, bool sending, BaseCor& base); + + u64 bankSeed(u64 size) const; + block initialSeed(CorType type, u64 size, u64 senderParty) const; + u64 index, party; + block session; + SpinBanks& banks; + oc::AlignedUnVector blocks; + std::map, oc::SilentOtExtSender> sendOt; + std::map, oc::SilentOtExtReceiver> recvOt; + std::map, SilentF4VoleSender> sendF4; + std::map, SilentF4VoleReceiver> recvF4; + + private: + template + static auto& buffer(Protocol& protocol) + { + if constexpr (std::is_same_v || + std::is_same_v) + return protocol.mB; + else + return protocol.mA; + } + }; +} diff --git a/secure-join/CorGenerator/TritOtBatch.cpp b/secure-join/CorGenerator/TritOtBatch.cpp index bba999722..93ff8c1db 100644 --- a/secure-join/CorGenerator/TritOtBatch.cpp +++ b/secure-join/CorGenerator/TritOtBatch.cpp @@ -50,41 +50,45 @@ namespace secJoin }; } - BaseRequest TritOtBatch::getBaseRequest() + BaseRequest TritOtBatch::getBaseRequest(StationaryWorker* worker) { BaseRequest r; if (mGenState->mMock) return r; + if (worker) + return worker->requestOtBase(CorType::TritOt, mSize, mSendRecv.index() == 0, mPrng); + mSendRecv | match{ [&](SendBatch& send) { - send.mSender.configure(mSize); - r.mSendSize = send.mSender.silentBaseOtCount(); + configureBatchOt(send.mSender, mSize); + r.mSendSize = send.mSender.baseCount().mBaseOtCount; }, [&](RecvBatch& recv) { - recv.mReceiver.configure(mSize); + configureBatchOt(recv.mReceiver, mSize); r.mChoice = recv.mReceiver.sampleBaseChoiceBits(mPrng); } }; return r; } - void TritOtBatch::setBase(BaseCor& base) + void TritOtBatch::setBase(BaseCor& base, StationaryWorker* worker) { if (mGenState->mMock) return; + if (worker) + return worker->setOtBase(CorType::TritOt, mSize, mSendRecv.index() == 0, base); + mSendRecv | match{ [&](SendBatch& send) { - send.mSender.setSilentBaseOts( - base.getSendOt(send.mSender.silentBaseOtCount())); + send.mSender.setBaseCors(base.getSendOt(send.mSender.baseCount().mBaseOtCount), {}, mPrng.get()); }, [&](RecvBatch& recv) { - recv.mReceiver.setSilentBaseOts( - base.getRecvOt(recv.mReceiver.silentBaseOtCount())); + base.setOtBase(recv.mReceiver); } }; } @@ -288,18 +292,26 @@ namespace secJoin { mock(batchIdx, size); } - else + else if (threadState.mStationary) + { + auto& worker = *threadState.mStationary; + auto& protocol = worker.begin(worker.recvOt, CorType::TritOt, size, false); + co_await protocol.silentReceiveInplace(size, prng, sock, oc::ChoiceBitPacking::True); + compressRecver(protocol.mA); + worker.finish(protocol); + } + else { if (state->mDebug) { - baseSend.resize(mReceiver.silentBaseOtCount()); + baseSend.resize(mReceiver.baseCount().mBaseOtCount); co_await sock.recv(baseSend); { for (u64 i = 0; i < baseSend.size(); ++i) { - if (mReceiver.mGen.mBaseOTs(i) != baseSend[i][mReceiver.mGen.mBaseChoices(i)]) + if (std::get<0>(mReceiver.mGenVar).mBaseOTs(i) != baseSend[i][std::get<0>(mReceiver.mGenVar).mBaseChoices(i)]) { std::cout << "F4RecvOleBatch::getTask() base OTs do not match. " << LOCATION << std::endl; std::terminate(); @@ -308,12 +320,11 @@ namespace secJoin } } - assert(mReceiver.mGen.hasBaseOts()); - mReceiver.mMultType = oc::MultType::Tungsten; + assert(mReceiver.hasBaseCors()); mReceiver.mA = std::move(threadState.mA); - mReceiver.mEncodeTemp = std::move(threadState.mEncodeTemp); - mReceiver.mGen.mTempBuffer = std::move(threadState.mPprfTemp); - mReceiver.mGen.mEagerSend = false; + mReceiver.mSpin = std::move(threadState.mSpin); + std::get<0>(mReceiver.mGenVar).mTempBuffer = std::move(threadState.mPprfTemp); + std::get<0>(mReceiver.mGenVar).mEagerSend = false; mReceiver.mDebug = state->mDebug; @@ -323,8 +334,8 @@ namespace secJoin compressRecver(mReceiver.mA); threadState.mA = std::move(mReceiver.mA); - threadState.mEncodeTemp = std::move(mReceiver.mEncodeTemp); - threadState.mPprfTemp = std::move(mReceiver.mGen.mTempBuffer); + threadState.mSpin = std::move(mReceiver.mSpin); + threadState.mPprfTemp = std::move(std::get<0>(mReceiver.mGenVar).mTempBuffer); } @@ -347,34 +358,41 @@ namespace secJoin { mock(batchIdx, size); } - else + else if (threadState.mStationary) + { + auto& worker = *threadState.mStationary; + auto& protocol = worker.begin(worker.sendOt, CorType::TritOt, size, true); + co_await protocol.silentSendInplace(protocol.mDelta, size, prng, sock); + compressSender(*protocol.mDelta, protocol.mB); + worker.finish(protocol); + } + else { if (state->mDebug) { - co_await sock.send(coproto::copy(mSender.mGen.mBaseOTs)); + co_await sock.send(coproto::copy(std::get<0>(mSender.mGenVar).mBaseOTs)); } - assert(mSender.mGen.hasBaseOts()); - mSender.mMultType = oc::MultType::Tungsten; + assert(mSender.hasBaseCors()); mSender.mB = std::move(threadState.mB); - mSender.mEncodeTemp = std::move(threadState.mEncodeTemp); - mSender.mGen.mTempBuffer = std::move(threadState.mPprfTemp); - mSender.mGen.mEagerSend = false; + mSender.mSpin = std::move(threadState.mSpin); + std::get<0>(mSender.mGenVar).mTempBuffer = std::move(threadState.mPprfTemp); + std::get<0>(mSender.mGenVar).mEagerSend = false; mSender.mDebug = state->mDebug; - co_await mSender.silentSendInplace(prng.get(), mSender.mRequestNumOts, prng, sock); + co_await mSender.silentSendInplace(mSender.mDelta, mSender.mRequestNumOts, prng, sock); - compressSender(mSender.mDelta, mSender.mB); + compressSender(*mSender.mDelta, mSender.mB); threadState.mB = std::move(mSender.mB); - threadState.mEncodeTemp = std::move(mSender.mEncodeTemp); - threadState.mPprfTemp = std::move(mSender.mGen.mTempBuffer); + threadState.mSpin = std::move(mSender.mSpin); + threadState.mPprfTemp = std::move(std::get<0>(mSender.mGenVar).mTempBuffer); } diff --git a/secure-join/CorGenerator/TritOtBatch.h b/secure-join/CorGenerator/TritOtBatch.h index 5f98911ad..dff54fd60 100644 --- a/secure-join/CorGenerator/TritOtBatch.h +++ b/secure-join/CorGenerator/TritOtBatch.h @@ -93,9 +93,9 @@ namespace secJoin void getCor(Cor* c, u64 begin, u64 size) override; - BaseRequest getBaseRequest() override; + BaseRequest getBaseRequest(StationaryWorker* worker) override; - void setBase(BaseCor&) override; + void setBase(BaseCor& base, StationaryWorker* worker) override; // Get the task associated with this batch. macoro::task<> getTask(BatchThreadState&) override; diff --git a/secure-join/GMW/Gmw.cpp b/secure-join/GMW/Gmw.cpp index 3a9912622..07b719c46 100644 --- a/secure-join/GMW/Gmw.cpp +++ b/secure-join/GMW/Gmw.cpp @@ -58,7 +58,7 @@ namespace secJoin if (input.rows() != mN) throw std::runtime_error("incorrect number of input rows. " LOCATION); - oc::transpose(input, memView); + oc::transpose({ input.data(), input.rows(), input.cols() }, memView); } void Gmw::setZeroInput(u64 i) @@ -81,7 +81,7 @@ namespace secJoin if (out.rows() != mN) throw RTE_LOC; - oc::transpose(memView, out); + oc::transpose({ memView.data(), memView.rows(), memView.cols() }, out); } oc::MatrixView Gmw::getInputView(u64 i) @@ -163,11 +163,6 @@ namespace secJoin } } - struct DebugCheckSums - { - block a, b, c, d; - }; - // The basic protocol where the inputs are not shared: // Sender has // > input x @@ -213,7 +208,8 @@ namespace secJoin auto in = std::array{}; auto out = (block*)nullptr; auto ww = std::vector{}; - auto debugCheckSums = std::array{}; + auto peerC = oc::AlignedUnVector{}; + auto peerD = oc::AlignedUnVector{}; auto print = coproto::unique_function{}; auto a = oc::AlignedUnVector{}; auto b = oc::AlignedUnVector{}; @@ -255,7 +251,6 @@ namespace secJoin mO.mWords(i, j) = mO.mWords(i, j) ^ mWords[i][j]; } - memset(&debugCheckSums, 0, sizeof(debugCheckSums)); } for (roundIdx = 0; roundIdx < numRounds(); ++roundIdx) @@ -336,15 +331,17 @@ namespace secJoin j += min; } - if (mO.mDebug) + if (mO.mDebug && a.size()) { + co_await chl.send(coproto::copy(c)); + co_await chl.send(coproto::copy(d)); + peerC.resize(a.size()); + peerD.resize(a.size()); + co_await chl.recv(peerC); + co_await chl.recv(peerD); for (u64 i = 0; i < a.size(); ++i) - { - debugCheckSums[0].a ^= a[i]; - debugCheckSums[0].b ^= b[i]; - debugCheckSums[0].c ^= c[i]; - debugCheckSums[0].d ^= d[i]; - } + if ((b[i] ^ peerD[i]) != (a[i] & peerC[i])) + throw RTE_LOC; } // now process the round. @@ -574,17 +571,9 @@ namespace secJoin for (u64 j = 0; j < mN128; ++j) ww[i * mN128 + j] = mWords[i][j]; co_await chl.send(std::move(ww)); - co_await chl.send(std::move(debugCheckSums[0])); ww.resize(mWords.size() * mN128); co_await chl.recv(ww); - co_await chl.recv(debugCheckSums[1]); - - if ((debugCheckSums[0].b ^ debugCheckSums[1].d) != (debugCheckSums[0].a & debugCheckSums[1].c)) - throw RTE_LOC; - if ((debugCheckSums[1].b ^ debugCheckSums[0].d) != (debugCheckSums[1].a & debugCheckSums[0].c)) - throw RTE_LOC; - for (u64 i = 0; i < mWords.size(); ++i) { for (u64 j = 0; j < mN128; ++j) diff --git a/secure-join/Join/OmJoin.cpp b/secure-join/Join/OmJoin.cpp index 0919361c4..8ac09edbc 100644 --- a/secure-join/Join/OmJoin.cpp +++ b/secure-join/Join/OmJoin.cpp @@ -4,6 +4,17 @@ namespace secJoin { + macoro::task<> sampleCompressionSeed(u64 party, PRNG& prng, coproto::Socket& sock, block& seed) + { + if (party == 0) + { + seed = prng.get(); + co_await sock.send(coproto::copy(seed)); + } + else + co_await sock.recv(seed); + } + // output a combined table that has the leftColumn // concatenated with the rightColumn (doubling the // number of rows). THe left column will have a @@ -11,11 +22,11 @@ namespace secJoin // a one appended. BinMatrix OmJoin::loadKeys( ColRef leftJoinCol, - ColRef rightJoinCol) + ColRef rightJoinCol, block codeSeed) { auto rows0 = leftJoinCol.mCol.mData.rows(); auto rows1 = rightJoinCol.mCol.mData.rows(); - auto compressesSize = mStatSecParam + log2(rows0) + log2(rows1); + auto compressesSize = mStatSecParam + oc::log2ceil(rows0) + oc::log2ceil(rows1); auto bits = leftJoinCol.mCol.getBitCount(); if (leftJoinCol.mCol.getBitCount() != rightJoinCol.mCol.getBitCount()) @@ -38,7 +49,7 @@ namespace secJoin } else { - PRNG prng(oc::block(234234234, 564356345)); + PRNG prng(codeSeed); oc::LinearCode code; code.random(prng, bits, compressesSize); @@ -117,14 +128,12 @@ namespace secJoin coproto::Socket& sock, BinMatrix& out) { - auto cir = oc::BetaCircuit{}; auto sKeys = BinMatrix{}; auto n = u64{}; auto keyByteSize = u64{}; n = data.numEntries(); keyByteSize = oc::divCeil(keyBitCount, 8); - cir = getControlBitsCircuit(keyBitCount); sKeys.resize(data.rows() + 1, keyBitCount); for (u64 i = 0; i < n; ++i) { @@ -153,6 +162,8 @@ namespace secJoin continue; auto n = cols[j]->rows(); + if (!n) + continue; assert(n <= dst.rows()); assert(offsets[j].mStart % 8 == 0); @@ -365,7 +376,6 @@ namespace secJoin coproto::Socket& sock) { auto temp = BinMatrix{}; - auto offsets = std::vector{}; auto offset = u64{}; assert(flagBitIndex % 8 == 0); @@ -378,7 +388,6 @@ namespace secJoin mUpdateActiveFlagGmw.setInput(0, choice); mUpdateActiveFlagGmw.setInput(1, temp); - offsets.emplace_back(Offset{ 0,1 }); co_await mUpdateActiveFlagGmw.run(sock); @@ -416,7 +425,7 @@ namespace secJoin auto keySize = std::min( schema.mKey.mBitCount, - mStatSecParam + log2(schema.mLeftSize) + log2(schema.mRightSize)); + mStatSecParam + oc::log2ceil(schema.mLeftSize) + oc::log2ceil(schema.mRightSize)); mPartyIdx = ole.partyIdx(); mDataBitsPerEntry = 0; @@ -445,7 +454,8 @@ namespace secJoin mDataBitsPerEntry += 8; mOffsets.emplace_back(Offset{ mDataBitsPerEntry, keySize, "key*" }); - mDataBitsPerEntry += schema.mKey.getByteCount() * 8; + const u64 payloadBits = mDataBitsPerEntry; + mDataBitsPerEntry += oc::roundUpTo(keySize, 8); //std::cout << "sort " << rows << " rows " << keySize << " bits " << std::endl; mSort.init(mPartyIdx, rows, keySize, ole); @@ -455,13 +465,13 @@ namespace secJoin // backwards direction, we will unpermute the left table select // columns. Therefore, in total we will permute: u64 permForward = oc::divCeil(mDataBitsPerEntry, 8) + sizeof(u32); - u64 permBackward = oc::divCeil(mDataBitsPerEntry - 1 - keySize, 8); + u64 permBackward = payloadBits / 8; mPerm.init(mPartyIdx, rows, permForward + permBackward, ole); mControlBitGmw.init(rows, getControlBitsCircuit(keySize), ole); - mAggTree.init(rows, mDataBitsPerEntry, AggTreeType::Prefix, getDupCircuit(), ole); + mAggTree.init(rows, payloadBits, AggTreeType::Prefix, getDupCircuit(), ole); auto cir = *oc::BetaLibrary{}.int_int_bitwiseAnd(1, 1, 1); mUpdateActiveFlagGmw.init(rows, cir, ole); @@ -501,7 +511,12 @@ namespace secJoin setTimePoint("start"); // left keys kL followed by the right keys kR - keys = loadKeys(query.mLeftKey, query.mRightKey); + block codeSeed = oc::ZeroBlock; + if (query.mLeftKey.mCol.getBitCount() > mOffsets.back().mSize) + { + co_await sampleCompressionSeed(mPartyIdx, prng, sock, codeSeed); + } + keys = loadKeys(query.mLeftKey, query.mRightKey, codeSeed); setTimePoint("load"); if (mInsecurePrint) @@ -537,15 +552,11 @@ namespace secJoin // Apply the sortin permutation. What you end up with are the keys // in sorted order and the rows of L also in sorted order. - temp.resize(data.numEntries(), data.bitsPerEntry() + 8); temp.resize(data.numEntries(), data.bitsPerEntry()); co_await mPerm.generate(sock, prng, data.rows(), perm); setTimePoint("perm cor gen"); - co_await perm.validate(sock); - - co_await perm.derandomize(sPerm, sock); setTimePoint("perm cor derand"); diff --git a/secure-join/Join/OmJoin.h b/secure-join/Join/OmJoin.h index 402953917..f61a41f8d 100644 --- a/secure-join/Join/OmJoin.h +++ b/secure-join/Join/OmJoin.h @@ -10,6 +10,9 @@ namespace secJoin { + // Public randomness sampled after both semi-honest parties have fixed their inputs. + macoro::task<> sampleCompressionSeed(u64 party, PRNG& prng, coproto::Socket& sock, block& seed); + // one to many secure join protocol struct OmJoin : public oc::TimerAdapter { @@ -82,7 +85,7 @@ namespace secJoin // a one appended. BinMatrix loadKeys( ColRef leftJoinCol, - ColRef rightJoinCol); + ColRef rightJoinCol, block codeSeed); // this circuit compares two inputs for equality with the exception that // the first bit is ignored. diff --git a/secure-join/Perm/AltModPerm.cpp b/secure-join/Perm/AltModPerm.cpp index cf70ad26d..d8265f9c0 100644 --- a/secure-join/Perm/AltModPerm.cpp +++ b/secure-join/Perm/AltModPerm.cpp @@ -81,14 +81,15 @@ namespace secJoin // randomized the blocks using AES. We only have a weak PRF. aes.ecbEncBlocks(dst.mDelta, dst.mDelta); + oc::Matrix debugInput; + if (mDebug) + debugInput = dst.mDelta; co_await mPrfRecver.evaluate(dst.mDelta, dst.mDelta, chl, prng); if (mDebug) { auto debugB = oc::Matrix{}; - auto debugInput = oc::Matrix{}; auto debugKey = AltModPrf::KeyType{}; - debugInput = dst.mDelta; debugB.resize(dst.mDelta.rows(), dst.mDelta.cols()); co_await chl.recv(debugKey); diff --git a/secure-join/Prf/AltModPrf.cpp b/secure-join/Prf/AltModPrf.cpp index 626032de7..5d0629dec 100644 --- a/secure-join/Prf/AltModPrf.cpp +++ b/secure-join/Prf/AltModPrf.cpp @@ -23,7 +23,7 @@ namespace secJoin g.resize(128, sizeof(block)); for (u64 i = 0; i < 128; ++i) osuCrypto::copyBytes(g[i], AltModPrf::mB[i]); - oc::transpose(g, gt); + oc::transpose({ g.data(), g.rows(), g.cols() }, gt); F2LinearCode r; r.init(gt); return r; diff --git a/secure-join/Prf/AltModPrfProto.cpp b/secure-join/Prf/AltModPrfProto.cpp index 78f979015..c85d1c643 100644 --- a/secure-join/Prf/AltModPrfProto.cpp +++ b/secure-join/Prf/AltModPrfProto.cpp @@ -117,6 +117,7 @@ namespace secJoin throw std::runtime_error("do not have enough preprocessing. Call request(...) first. " LOCATION); } + preprocess(); setTimePoint("DarkMatter.sender.begin"); mKeyMultRecver.mDebug = mDebug; @@ -296,7 +297,7 @@ namespace secJoin mMod2OleReq.start(); mKeyMultRecver.preprocess(); - mKeyMultRecver.preprocess(); + mKeyMultSender.preprocess(); } @@ -327,6 +328,7 @@ namespace secJoin throw std::runtime_error("do not have enough preprocessing. Call request(...) first. " LOCATION); } + preprocess(); setTimePoint("DarkMatter.recver.begin"); if (mDebug) mDebugInput = std::vector(x.begin(), x.end()); @@ -1031,127 +1033,31 @@ namespace secJoin std::terminate(); } - auto ots = std::vector{}; - ots.reserve(mMod2F4Req.batchCount()); - - // the format of u is that it should have AltModWPrf::MidSize rows. - auto rows = u0.rows(); - - // cols should be the number of inputs. - auto cols = u0.cols(); - auto remaining = rows * cols; - - // we are performing mod 2. u0 is the lsb, u1 is the msb. these are packed into 128 bit blocks. - // we then have a matrix of these with `rows` rows and `cols` columns. We mod requires - // 2 OLEs. So in total we need rows * cols * 128 * 2 OLEs. - assert(mMod2F4Req.size() == rows * cols * 128); + if (u0.rows() != u1.rows() || u0.cols() != u1.cols() || + out.rows() != u0.rows() || out.cols() != u0.cols()) + throw RTE_LOC; - auto u0Iter = u0.data(); - auto u1Iter = u1.data(); - auto derand = (block*)nullptr; - auto derandEnd = (block*)nullptr; - auto lsbIter = (block*)nullptr; - auto msbIter = (block*)nullptr; - auto buff = oc::AlignedUnVector{}; - for (auto i = 0ull; i < rows; ++i) + F4BitOtRecv ots; + oc::AlignedUnVector correction; + for (u64 offset = 0; offset < out.size();) { - for (auto j = 0ull; j < cols;) + co_await mMod2F4Req.get(ots); + const u64 count = std::min(ots.mOts.size(), out.size() - offset); + correction.resize(2 * count); + for (u64 j = 0; j < count; ++j) { - if (derandEnd == derand) - { - ots.emplace_back(); - co_await(mMod2F4Req.get(ots.back())); - lsbIter = ots.back().mChoiceLsb.data(); - msbIter = ots.back().mChoiceMsb.data(); - - buff.resize(std::min(ots.back().mChoiceLsb.size(), remaining) * 2); - remaining -= buff.size() / 2; - derand = buff.data(); - derandEnd = derand + buff.size(); - } - - auto step = std::min(cols - j, (derandEnd - derand) / 2); - auto end = step + j; - - for (; j < end; ++j) - { - assert(u0Iter == &u0(i, j)); - assert(u1Iter == &u1(i, j)); - derand[0] = *u0Iter++ ^ *lsbIter++; - derand[1] = *u1Iter++ ^ *msbIter++; - - derand += 2; - } - - if (derandEnd == derand) - { - co_await(sock.send(std::move(buff))); - } + correction[2 * j] = u0.data()[offset + j] ^ ots.mChoiceLsb[j]; + correction[2 * j + 1] = u1.data()[offset + j] ^ ots.mChoiceMsb[j]; } - } - - assert(buff.size() == 0); - - auto tIter = ots.begin(); - auto outIter = out.data(); - auto otIter = (block*)nullptr; - u0Iter = u0.data(); - u1Iter = u1.data(); - derand = nullptr; - derandEnd = nullptr; - remaining = rows * cols; - for (auto i = 0ull; i < rows; ++i) - { - for (auto j = 0ull; j < cols; ) + co_await sock.send(correction); + co_await sock.recv(correction); + for (u64 j = 0; j < count; ++j) { - - if (derand == derandEnd) - { - otIter = tIter->mOts.data(); - buff.resize(std::min(tIter->mOts.size(), remaining) * 2); - remaining -= buff.size() / 2; - co_await(sock.recv(buff)); - - derand = buff.data(); - derandEnd = derand + buff.size(); - ++tIter; - } - - auto step = std::min(cols - j, (derandEnd - derand) / 2); - auto end = step + j; - - for (; j < end; ++j) - { - - assert((u0(i, j) & u1(i, j)) == oc::ZeroBlock); - assert(u0Iter == &u0(i, j)); - assert(u1Iter == &u1(i, j)); - assert(derand + 1 < derandEnd); - assert(outIter == &out(i, j)); - assert(otIter < (tIter[-1].mOts.data() + tIter[-1].mOts.size())); - - // if u = 0, w = hi0 - // if u = 1, w = hi1 + t1 - // if u = 2, w = m2 + t2 - block w = - (*u0Iter++ & derand[0]) ^ // t1 - (*u1Iter++ & derand[1]) ^ // t2 - *otIter++;// m_u - - //if (mDebug)// && i == mPrintI && (j == (mPrintJ / 128))) - //{ - // auto mPrintJ = 0; - // auto bitIdx = mPrintJ % 128; - // std::cout << j << " u " << bit(u1(i, j), bitIdx) << bit(u0(i, j), bitIdx) << std::endl; - // std::cout << j << " t _ " << bit(derand[0], bitIdx) << " " << bit(derand[1], bitIdx) << std::endl; - // std::cout << j << " w " << bit(w, bitIdx) << std::endl; - //} - - *outIter++ = w; - derand += 2; - - } + out.data()[offset + j] = ots.mOts[j] ^ + (u0.data()[offset + j] & correction[2 * j]) ^ + (u1.data()[offset + j] & correction[2 * j + 1]); } + offset += count; } } } \ No newline at end of file diff --git a/secure-join/Prf/mod3.cpp b/secure-join/Prf/mod3.cpp index 8215e1676..3f0088950 100644 --- a/secure-join/Prf/mod3.cpp +++ b/secure-join/Prf/mod3.cpp @@ -370,6 +370,12 @@ namespace secJoin return _mm256_testz_si256(mVal, o.mVal); } + u32 refillMask() const + { + const auto shortLanes = _mm256_cmpgt_epi32(_mm256_set1_epi32(32), mVal); + return static_cast(_mm256_movemask_ps(_mm256_castsi256_ps(shortLanes))); + } + SampleBlock256 add_epi32(const SampleBlock256& s) const { @@ -538,9 +544,13 @@ namespace secJoin auto indexes = indexBase & SampleBlock256::set32(255); indexBase = indexBase.srli_epi32<8>(); - v_[j] = SampleBlock256::i32gather_epi32<4>((const i32*)mod3TableV.data(), indexes); - lsb_[j] = SampleBlock256::i32gather_epi32<4>((const i32*)mod3TableLsb.data(), indexes); - msb_[j] = SampleBlock256::i32gather_epi32<4>((const i32*)mod3TableMsb.data(), indexes); + const auto entry = SampleBlock256::i32gather_epi32<4>( + reinterpret_cast(mod3Table.data()), indexes); + lsb_[j] = entry & SampleBlock256::set32(31); + msb_[j] = entry.srli_epi32<8>() & SampleBlock256::set32(31); + // Bits 14 and 15 are zero. Copy the valid bit (16) to bits 0 and 2 + // to append five trits for an accepted byte and zero for a rejection. + v_[j] = entry.srli_epi32<16>() | entry.srli_epi32<14>(); } // shift the sum if we have a valid sample @@ -587,49 +597,64 @@ namespace secJoin size[3] = size[3].add_epi32(v_[3]); } - for (u64 j = 0; j < lsbSum.size(); ++j) - { - auto lsbLanes = std::bit_cast>(lsbSum[j]); - auto msbLanes = std::bit_cast>(msbSum[j]); - auto sizeLanes = std::bit_cast>(size[j]); - - for (u64 k = 0; k < 8; ++k) + auto refillLane = [&](u32& lsb, u32& msb, u32 count) { + do { - auto& lsbk = lsbLanes[k]; - auto& msbk = msbLanes[k]; - auto& sizek = sizeLanes[k]; - - while (sizek < 32) + if (rands2Ptr == e2) { - if (rands2Ptr == e2) - { - prng.mAes.ecbEncCounterMode(prng.mBlockIdx, rands2.size(), rands2.data()); - prng.mBlockIdx += rands2.size(); - rands2Ptr = (u8*)rands2.data(); - } - - auto b = *rands2Ptr++; - auto v = mod3Table[b]; + prng.mAes.ecbEncCounterMode(prng.mBlockIdx, rands2.size(), rands2.data()); + prng.mBlockIdx += rands2.size(); + rands2Ptr = (u8*)rands2.data(); + } - auto lsbj = v & 255ull; - auto msbj = (v >> 8) & 255ull; - auto flag = 5 * (v >> 16); - lsbk = (lsbk << flag) | lsbj; - msbk = (msbk << flag) | msbj; + const auto entry = mod3Table[*rands2Ptr++]; + const auto trits = 5 * (entry >> 16); + lsb = (lsb << trits) | (entry & 255); + msb = (msb << trits) | ((entry >> 8) & 255); + count += trits; + } while (count < 32); + }; - sizek += flag; - } - } +#ifdef ENABLE_SSE + u32 missing = 0; + for (unsigned j = 0; j < size.size(); ++j) + missing |= size[j].refillMask() << (8 * j); + + using Lanes = std::array; + auto lsbLanes = std::bit_cast(lsbSum); + auto msbLanes = std::bit_cast(msbSum); + const auto sizeLanes = std::bit_cast(size); + // Consume refill bytes in the original group and lane order, including tail lanes. + for (; missing; missing &= missing - 1) + { + const auto lane = std::countr_zero(missing); + refillLane(lsbLanes[lane], msbLanes[lane], sizeLanes[lane]); + } + const auto* lsbData = lsbLanes.data(); + const auto* msbData = msbLanes.data(); +#else + using Lanes = std::array; + for (unsigned j = 0; j < size.size(); ++j) + { + auto lsbLanes = std::bit_cast(lsbSum[j]); + auto msbLanes = std::bit_cast(msbSum[j]); + const auto sizeLanes = std::bit_cast(size[j]); + for (unsigned lane = 0; lane < sizeLanes.size(); ++lane) + if (sizeLanes[lane] < 32) + refillLane(lsbLanes[lane], msbLanes[lane], sizeLanes[lane]); lsbSum[j] = std::bit_cast(lsbLanes); msbSum[j] = std::bit_cast(msbLanes); } + const auto* lsbData = lsbSum.data(); + const auto* msbData = msbSum.data(); +#endif auto s = std::min(msbVec.size() - i, lsbSum.size() * 2); assert(lsbIter + s <= lsbVec.data() + lsbVec.size()); assert(msbIter + s <= msbVec.data() + msbVec.size()); - std::copy((u8*)lsbSum.data(), (u8*)lsbSum.data() + s * sizeof(block), (u8*)lsbIter); - std::copy((u8*)msbSum.data(), (u8*)msbSum.data() + s * sizeof(block), (u8*)msbIter); + std::memcpy(lsbIter, lsbData, s * sizeof(block)); + std::memcpy(msbIter, msbData, s * sizeof(block)); lsbIter += s; msbIter += s; diff --git a/secure-join/Sort/RadixSort.cpp b/secure-join/Sort/RadixSort.cpp index db121e2be..6866ad187 100644 --- a/secure-join/Sort/RadixSort.cpp +++ b/secure-join/Sort/RadixSort.cpp @@ -850,16 +850,18 @@ namespace secJoin BinMatrix RadixSort::extract(u64 begin, u64 size, const BinMatrix& k) { // we assume at most a byte size. - if (size > 8) + if (size == 0 || size > 8 || begin >= k.bitsPerEntry()) throw RTE_LOC; - size = std::min(size, k.cols() * 8 - begin); + BinMatrix sk(k.rows(), size); + if (k.rows() == 0) + return sk; + size = std::min(size, k.bitsPerEntry() - begin); auto byteIdx = begin / 8; auto shift = begin % 8; auto step = k.cols(); - u64 mask = (size % 64) ? (1ull << size) - 1 : ~0ull; - BinMatrix sk(k.rows(), oc::divCeil(size, 8)); + u64 mask = (1ull << size) - 1; auto n = k.rows() - 1; auto s0 = (k.data() + byteIdx); @@ -1008,6 +1010,8 @@ namespace secJoin u64 bitCount, CorGenerator& gen) { + if (mL == 0 || mL > 8) + throw std::invalid_argument("Radix digit width must be between 1 and 8"); mRole = role; mSize = n; mBitCount = bitCount; diff --git a/secure-join/Sort/RadixSort.h b/secure-join/Sort/RadixSort.h index 46f4e0998..67eaf71bf 100644 --- a/secure-join/Sort/RadixSort.h +++ b/secure-join/Sort/RadixSort.h @@ -53,7 +53,7 @@ namespace secJoin u64 mBitCount = 0; // The bit step size of the genBitPerm protocol. - u64 mL = 2; + u64 mL = 4; // A zero one flag denoting the party index. u64 mRole = -1; diff --git a/secure-join/TableOps/GroupBy.cpp b/secure-join/TableOps/GroupBy.cpp index cb125b1ed..dfaec28ee 100644 --- a/secure-join/TableOps/GroupBy.cpp +++ b/secure-join/TableOps/GroupBy.cpp @@ -43,13 +43,13 @@ namespace secJoin void GroupBy::loadKeys( ColRef groupByCol, std::vector& actFlagVec, - BinMatrix& compressKeys) + BinMatrix& compressKeys, block codeSeed) { - auto grpByData = groupByCol.mCol.mData; + const auto& grpByData = groupByCol.mCol.mData; auto rows = grpByData.rows(); auto grpByBits = grpByData.bitsPerEntry(); auto grpByBytes = grpByData.bytesPerEntry(); - auto compressedSize = mStatSecParam + oc::log2ceil(rows); + auto compressedSize = mStatSecParam + 2 * oc::log2ceil(rows); // Appending ActiveFlagBit to the key BinMatrix keys(rows, grpByBits + 1); @@ -63,14 +63,11 @@ namespace secJoin if (keys.bitsPerEntry() <= compressedSize) { - // Make a copy of keys into compressKeys - compressKeys.resize(keys.rows(), keys.bitsPerEntry()); - std::swap(keys, compressKeys); + compressKeys = std::move(keys); } else { - PRNG prng(oc::block(234234234, 564356345)); - // PRNG prng(oc::ZeroBlock); + PRNG prng(codeSeed); oc::LinearCode code; code.random(prng, keys.bitsPerEntry(), compressedSize); @@ -254,7 +251,7 @@ namespace secJoin u64 compressKeySize = std::min( keySize, - mStatSecParam + oc::log2ceil(rows)); + mStatSecParam + 2 * oc::log2ceil(rows)); mPartyIdx = ole.partyIdx(); @@ -351,7 +348,10 @@ namespace secJoin auto perm = ComposedPerm{}; auto tempNum = u64{}; - loadKeys(groupByCol, groupByCol.mTable.mIsActive, compressKeys); + block codeSeed = oc::ZeroBlock; + if (groupByCol.mCol.getBitCount() + 1 > mOffsets[mOffsets.size() - 2].mSize) + co_await sampleCompressionSeed(mPartyIdx, prng, sock, codeSeed); + loadKeys(groupByCol, groupByCol.mTable.mIsActive, compressKeys, codeSeed); if (mInsecurePrint) { diff --git a/secure-join/TableOps/GroupBy.h b/secure-join/TableOps/GroupBy.h index fbbb239e8..ed7d2147a 100644 --- a/secure-join/TableOps/GroupBy.h +++ b/secure-join/TableOps/GroupBy.h @@ -79,7 +79,7 @@ namespace secJoin void loadKeys( ColRef groupByCol, std::vector& actFlagVec, - BinMatrix& compressKeys); + BinMatrix& compressKeys, block codeSeed); void concatColumns( ColRef groupByCol, diff --git a/secure-join/Util/Matrix.h b/secure-join/Util/Matrix.h index 3e5f1d8aa..699f33c39 100644 --- a/secure-join/Util/Matrix.h +++ b/secure-join/Util/Matrix.h @@ -264,7 +264,7 @@ namespace secJoin dst.numEntries() != numEntries()) dst.resize(numEntries(), bitsPerEntry()); - oc::transpose(mData, dst.mData); + oc::transpose({ mData.data(), mData.rows(), mData.cols() }, dst.mData); } BinMatrix transpose() const @@ -281,7 +281,7 @@ namespace secJoin dst.numEntries() != numEntries()) dst.resize(numEntries(), bitsPerEntry()); - oc::transpose(mData, dst.mData); + oc::transpose({ mData.data(), mData.rows(), mData.cols() }, dst.mData); } inline void BinMatrix::transpose(oc::MatrixView dst) const @@ -290,7 +290,7 @@ namespace secJoin dst.cols() < oc::divCeil(numEntries(), 8)) throw RTE_LOC; - oc::transpose(mData, dst); + oc::transpose({ mData.data(), mData.rows(), mData.cols() }, dst); } inline TBinMatrix BinMatrix::transpose() const diff --git a/secure-join/Util/Simd.h b/secure-join/Util/Simd.h index d11f4c90f..991bf1d9e 100644 --- a/secure-join/Util/Simd.h +++ b/secure-join/Util/Simd.h @@ -43,13 +43,8 @@ namespace secJoin block dst; for (u64 i = 0; i < 16; ++i) { - auto bi = b.get(i); - - // 0 if bi < 0. otherwise 11111111 - u8 mask = ~(-i8(bi >> 7)); - u8 idx = bi & 15; - - dst.set(i, a.get(idx) & mask); + const auto index = b.get(i); + dst.set(i, index & 0x80 ? 0 : a.get(index & 15)); } return dst; } @@ -58,23 +53,17 @@ namespace secJoin OC_FORCEINLINE block slli_epi16(const block& v) { block r; - auto rr = (i16*)&r; - auto vv = (const i16*)&v; + static_assert(s >= 0); for (u64 i = 0; i < 8; ++i) - rr[i] = vv[i] << s; + r.set(i, s < 16 ? static_cast(u32(v.get(i)) << s) : 0); return r; } OC_FORCEINLINE int movemask_epi8(const block v) { - // extract all the of MSBs if each byte. - u64 mask = 1; int r = 0; - for (i64 i = 0; i < 16; ++i) - { - r |= (v.get(0) >> i) & mask; - mask <<= 1; - } + for (u64 i = 0; i < 16; ++i) + r |= (v.get(i) >> 7) << i; return r; } @@ -82,6 +71,30 @@ namespace secJoin + // Gather byte zero of 16 consecutive blocks in lane order. + OC_FORCEINLINE block gatherLowBytes(const block* x) + { +#ifdef ENABLE_SSE + const auto a = _mm_unpacklo_epi16(_mm_unpacklo_epi8(x[0], x[1]), _mm_unpacklo_epi8(x[2], x[3])); + const auto b = _mm_unpacklo_epi16(_mm_unpacklo_epi8(x[4], x[5]), _mm_unpacklo_epi8(x[6], x[7])); + const auto c = _mm_unpacklo_epi16(_mm_unpacklo_epi8(x[8], x[9]), _mm_unpacklo_epi8(x[10], x[11])); + const auto d = _mm_unpacklo_epi16(_mm_unpacklo_epi8(x[12], x[13]), _mm_unpacklo_epi8(x[14], x[15])); + return _mm_unpacklo_epi64(_mm_unpacklo_epi32(a, b), _mm_unpacklo_epi32(c, d)); +#else + block bytes; + for (u64 i = 0; i < 16; ++i) + bytes.set(i, x[i].get(0)); + return bytes; +#endif + } + + template + OC_FORCEINLINE u16 packByteBits(block bytes) + { + static_assert(bit >= 0 && bit < 8); + return static_cast(movemask_epi8(slli_epi16<7 - bit>(bytes))); + } + //FOR j := 0 to 7 // i := j*16 // dst[i+15:i] := ( a[i+15:i] == b[i+15:i] ) ? 0xFFFF : 0 @@ -94,7 +107,7 @@ namespace secJoin block r; for (i64 i = 0; i < 8; ++i) { - r.set(i, a.get(i) == b.get(i) ? 0xFFFF : 0); + r.set(i, a.get(i) == b.get(i) ? 0xFFFF : 0); } return r; #endif // ENABLE_SSE diff --git a/tests/AltModPerm_Test.cpp b/tests/AltModPerm_Test.cpp index 2534b5634..9899f9326 100644 --- a/tests/AltModPerm_Test.cpp +++ b/tests/AltModPerm_Test.cpp @@ -34,8 +34,8 @@ void AltModPerm_setup_test(const oc::CLP& cmd) //for (auto invPerm : { PermOp::Regular,PermOp::Inverse }) { - ole0.init(sock[0].fork(), prng0, 0, 1, 1 << 18, cmd.getOr("mock", 1)); - ole1.init(sock[1].fork(), prng1, 1, 1, 1 << 18, cmd.getOr("mock", 1)); + ole0.init(sock[0].fork(), prng0, 0, 1, 1 << 18, cmd.getOr("mock", 0)); + ole1.init(sock[1].fork(), prng1, 1, 1, 1 << 18, cmd.getOr("mock", 0)); AltModPerm0.init(n, rowSize, ole0); AltModPerm1.init(n, rowSize, ole1); diff --git a/tests/AltModWPrf_Test.cpp b/tests/AltModWPrf_Test.cpp index b7e4d7c4c..53a6c26da 100644 --- a/tests/AltModWPrf_Test.cpp +++ b/tests/AltModWPrf_Test.cpp @@ -163,11 +163,24 @@ void AltModWPrf_mod3BitDecompostion_test() void AltModWPrf_sampleMod3_test(const oc::CLP& cmd) { + { + // Only lane 31 needs a refill. A one-block tail must still consume it. + PRNG prng(block(0, 7)); + const auto firstBlock = prng.mBlockIdx; + std::array msb, lsb; + sampleMod3Lookup(prng, msb, lsb); + if (prng.mBlockIdx != firstBlock + 128 + 8) + throw RTE_LOC; + } { // The 65th output block crosses the 128-block random buffer refill. PRNG prng(oc::ZeroBlock); + const auto firstBlock = prng.mBlockIdx; std::array msb, lsb; sampleMod3Lookup(prng, msb, lsb); + // This seed uses two 128-block fills and one 8-block rejection refill. + if (prng.mBlockIdx != firstBlock + 2 * 128 + 8 || prng.mBytesIdx != 0) + throw RTE_LOC; if (msb.front() != block(0x4891092ad0281014ull, 0xb804758096382277ull) || lsb.front() != block(0x1648668104450b62ull, 0x439b084468069488ull) || msb.back() != block(0x850452644220150bull, 0x089706388b014672ull) || diff --git a/tests/CorGenerator_Test.cpp b/tests/CorGenerator_Test.cpp index 5be67ac3b..056f2ae5b 100644 --- a/tests/CorGenerator_Test.cpp +++ b/tests/CorGenerator_Test.cpp @@ -1,24 +1,87 @@ #include "CorGenerator_Test.h" #include "secure-join/CorGenerator/CorGenerator.h" +#include "secure-join/CorGenerator/BinOleBatch.h" +#include "secure-join/CorGenerator/F4BitOtBatch.h" #include "secure-join/Prf/AltModPrfProto.h" #include "secure-join/Prf/AltModSimd.h" using namespace secJoin; +namespace +{ + using Noise = oc::SdNoiseDistribution; + constexpr std::pair cases[] = { + {false, Noise::Regular}, {true, Noise::Regular}, {false, Noise::Stationary} + }; + + u8 packedBit(span plane, u64 i) + { + return (plane[i / 128].get((i % 128) / 64) >> (i % 64)) & 1; + } +} + void CorGenerator_F4BitOt_Test(const oc::CLP& cmd) { + // Verify all four packed planes against single-block Davies-Meyer hashing. + { + constexpr u64 count = 384; + alignas(64) std::array storage; + span input(storage.data() + 1, count); + PRNG prng(block(13, 27)); + F4BitOtBatch batch(nullptr, true, oc::Socket{}, PRNG(oc::ZeroBlock)); + auto& sender = std::get(batch.mSendRecv); + sender.mDelta = prng.get(); + const block mask(~0ull, ~3ull); + for (auto& value : input) + value = prng.get(); + sender.compressSender(input); + for (u8 choice = 0; choice < 4; ++choice) + { + block offset = oc::ZeroBlock; + CoeffCtxGF4{}.mul(offset, sender.mDelta & mask, F4{choice}); + for (u64 i = 0; i < count; ++i) + { + const auto expected = oc::mAesFixedKey.hashBlock(input[i] ^ offset).get(0) & 1; + if (packedBit(sender.mOts[choice], i) != expected) + throw std::runtime_error("Packed GF(4) sender hash mismatch"); + } + } + batch.clear(); + if (sender.mDelta != oc::ZeroBlock) + throw std::runtime_error("GF(4) sender delta survived clear"); + for (const auto& plane : sender.mOts) + if (plane.size()) + throw std::runtime_error("GF(4) sender output survived clear"); + + F4BitOtBatch::RecvBatch receiver; + for (auto& value : input) + value = prng.get(); + receiver.compressRecver(input); + for (u64 i = 0; i < count; ++i) + { + const auto choices = input[i].get(0); + const auto expected = oc::mAesFixedKey.hashBlock(input[i] & mask).get(0) & 1; + if (packedBit(receiver.mChoiceLsb, i) != (choices & 1) || + packedBit(receiver.mChoiceMsb, i) != ((choices >> 1) & 1) || + packedBit(receiver.mOts, i) != expected) + throw std::runtime_error("Packed GF(4) receiver mismatch"); + } + } + u64 n = (1ull << 16) + 3234; - for (auto mock : { false, true }) + for (auto [mock, noise] : cases) { + const u64 batch = noise == Noise::Stationary ? 8192 : 1 << 18; PRNG prng(oc::ZeroBlock); auto sock = coproto::LocalAsyncSocket::makePair(); + auto meter = sock[0]; CorGenerator send; CorGenerator recv; - send.init(std::move(sock[0]), prng, 0, 2, 1 << 18, mock); - recv.init(std::move(sock[1]), prng, 1, 2, 1 << 18, mock); + send.init(std::move(sock[0]), prng, 0, 2, batch, mock, noise); + recv.init(std::move(sock[1]), prng, 1, 2, batch, mock, noise); send.mGenState->mDebug = cmd.isSet("debug"); recv.mGenState->mDebug = cmd.isSet("debug"); @@ -67,6 +130,16 @@ void CorGenerator_F4BitOt_Test(const oc::CLP& cmd) std::get<0>(r).result(); std::get<1>(r).result(); + if (noise == Noise::Stationary && !cmd.isSet("debug")) + { + // Direct noisy VOLE sends 128 blocks per partition on every round. + // Even including cold PPRFs, the aggregated provider should beat + // that payload alone for the eight full batches in this workload. + const auto partitions = configureF4Code(128, batch, oc::MultType::Spin, noise).mNumPartitions; + const auto direct = (n / batch) * partitions * 128 * sizeof(block); + if (meter.bytesSent() + meter.bytesReceived() >= direct) + throw std::runtime_error("Stationary GF(4) repeated the direct base-VOLE payload"); + } } @@ -77,6 +150,9 @@ void CorGenerator_F4BitOt_Test(const oc::CLP& cmd) //std::get<0>(r).result(); //std::get<1>(r).result(); + + + } void CorGenerator_Ot_Test(const oc::CLP& cmd) @@ -84,8 +160,9 @@ void CorGenerator_Ot_Test(const oc::CLP& cmd) u64 n = (1ull << 16) + 3234; - for (auto mock : { false, true }) + for (auto [mock, noise] : cases) { + const u64 batch = noise == Noise::Stationary ? 8192 : 1 << 18; PRNG prng(oc::ZeroBlock); //SendBase sBase;sBase.resize(128); @@ -101,8 +178,8 @@ void CorGenerator_Ot_Test(const oc::CLP& cmd) auto sock = coproto::LocalAsyncSocket::makePair(); CorGenerator send; CorGenerator recv; - send.init(std::move(sock[0]), prng, 0, 2, 1 << 18, mock); - recv.init(std::move(sock[1]), prng, 1, 2, 1 << 18, mock); + send.init(std::move(sock[0]), prng, 0, 2, batch, mock, noise); + recv.init(std::move(sock[1]), prng, 1, 2, batch, mock, noise); send.mGenState->mDebug = cmd.isSet("debug"); recv.mGenState->mDebug = cmd.isSet("debug"); @@ -159,11 +236,36 @@ void CorGenerator_Ot_Test(const oc::CLP& cmd) void CorGenerator_BinOle_Test(const oc::CLP& cmd) { + { + constexpr u64 count = 384; + alignas(64) std::array storage; + span input(storage.data() + 1, count); + PRNG prng(block(47, 81)); + for (auto& value : input) + value = prng.get(); + const block delta = prng.get() | oc::OneBlock; + const block mask(~0ull, ~1ull); + OleBatch::SendBatch sender; + OleBatch::RecvBatch receiver; + std::array sAdd, sMult, rAdd, rMult; + sender.compressSender(delta, input, sAdd, sMult); + receiver.compressRecver(input, rAdd, rMult); + for (u64 i = 0; i < count; ++i) + { + const auto x = input[i] & mask; + const auto zero = oc::mAesFixedKey.hashBlock(x).get(0) & 1; + const auto one = oc::mAesFixedKey.hashBlock(x ^ (delta & mask)).get(0) & 1; + if (packedBit(sAdd, i) != zero || packedBit(sMult, i) != (zero ^ one) || + packedBit(rAdd, i) != zero || packedBit(rMult, i) != (input[i].get(0) & 1)) + throw std::runtime_error("Packed binary OLE mismatch"); + } + } u64 n = cmd.getOr("n", (1ull << 16) + 3234); - for (auto mock : { false, true }) + for (auto [mock, noise] : cases) { + const u64 batch = noise == Noise::Stationary ? 8192 : 1 << 18; PRNG prng(oc::ZeroBlock); @@ -181,8 +283,8 @@ void CorGenerator_BinOle_Test(const oc::CLP& cmd) CorGenerator send; CorGenerator recv; - send.init(std::move(sock[0]), prng, 0, 1, 1 << 18, mock); - recv.init(std::move(sock[1]), prng, 1, 1, 1 << 18, mock); + send.init(std::move(sock[0]), prng, 0, 2, batch, mock, noise); + recv.init(std::move(sock[1]), prng, 1, 2, batch, mock, noise); send.mGenState->mDebug = cmd.isSet("debug"); recv.mGenState->mDebug = cmd.isSet("debug"); @@ -244,15 +346,16 @@ void CorGenerator_TritOt_Test(const oc::CLP& cmd) throw RTE_LOC; } - for (auto mock : { false, true }) + for (auto [mock, noise] : cases) { + const u64 batch = noise == Noise::Stationary ? 8192 : 1 << 18; auto sock = coproto::LocalAsyncSocket::makePair(); CorGenerator send; CorGenerator recv; - send.init(std::move(sock[0]), prng, 0, 2, 1 << 18, mock); - recv.init(std::move(sock[1]), prng, 1, 2, 1 << 18, mock); + send.init(std::move(sock[0]), prng, 0, 2, batch, mock, noise); + recv.init(std::move(sock[1]), prng, 1, 2, batch, mock, noise); send.mGenState->mDebug = cmd.isSet("debug"); recv.mGenState->mDebug = cmd.isSet("debug"); @@ -447,3 +550,153 @@ void CorGenerator_mixed_Test(const oc::CLP& cmd) } } + +void CorGenerator_SpinWorkers_Test(const oc::CLP&) +{ + constexpr u64 k = 8192; + std::optional first, second; + prepareRegularSpin(first, k - 128); + prepareRegularSpin(second, k); + if (&first->encoder() != &second->encoder()) + throw std::runtime_error("Regular workers rebuilt an identical padded code"); + + SpinBanks bank[2]; + StationaryWorker sender(0, 0, oc::OneBlock, bank[0]), receiver(0, 1, oc::OneBlock, bank[1]); + PRNG random[2]{PRNG(oc::ZeroBlock), PRNG(oc::OneBlock)}; + auto channel = coproto::LocalAsyncSocket::makePair(); + // Requests are collected for all batches before any worker expands. + for (auto type : {CorType::Ot, CorType::Ole, CorType::TritOt}) + { + for (unsigned round = 0; round < 2; ++round) + { + auto left = sender.requestOtBase(type, k, true, random[0]); + auto right = receiver.requestOtBase(type, k, false, random[1]); + if ((left.mSendSize != 0) != (round == 0) || left.mSendSize != right.mChoice.size() || + !left.mSendBinaryVoles || left.mSendBinaryVoles != right.mRecvBinaryVoles) + throw std::runtime_error("Stationary binary setup requested incorrect location OTs or noise VOLEs"); + } + } + auto nextSeed = sender.initialSeed(CorType::Ot, k, 0); + for (unsigned round = 0; round < 2; ++round) + { + auto& s = sender.begin(sender.sendOt, CorType::Ot, k, true); + auto& r = receiver.begin(receiver.recvOt, CorType::Ot, k, false); + if (s.mCodeSeed != nextSeed || r.mCodeSeed != nextSeed) + throw std::runtime_error("Stationary stream restarted"); + auto done = macoro::sync_wait(macoro::when_all_ready( + s.silentSendInplace(s.mDelta, k, random[0], channel[0]), + r.silentReceiveInplace(k, random[1], channel[1], oc::ChoiceBitPacking::True))); + std::get<0>(done).result(); + std::get<1>(done).result(); + const auto spec = s.mSpin->encoder().specification(); + if (s.mSpin->encoder().descriptor() != r.mSpin->encoder().descriptor() || + spec.route_seed != nextSeed.get(0) || spec.inner_seed != nextSeed.get(1)) + throw std::runtime_error("Peers used the wrong stationary round map"); + nextSeed = oc::mAesFixedKey.hashBlock(nextSeed); + sender.finish(s); + receiver.finish(r); + } + + // The public copying and chosen-VOLE interfaces must also resume the + // same stationary stream when callers supply their own output buffers. + { + SilentF4VoleSender s; + SilentF4VoleReceiver r; + s.configure(k, oc::SilentBaseType::BaseExtend, 128, {}, Noise::Stationary); + r.configure(k, oc::SilentBaseType::BaseExtend, 128, {}, Noise::Stationary); + SilentF4VoleSender::VecF a(k), b(k); + SilentF4VoleReceiver::VecG choices(k); + CoeffCtxGF4 ctx; + const auto delta = random[0].get() & block(~0ull, ~3ull); + for (unsigned round = 0; round < 2; ++round) + { + for (auto& c : choices) + c.mVal = random[1].get() & 3; + auto done = macoro::sync_wait(macoro::when_all_ready( + round ? s.sendChosen(delta, b, random[0], channel[0]) : s.silentSend(delta, b, random[0], channel[0]), + round ? r.receiveChosen(choices, a, random[1], channel[1]) : r.silentReceive(a, random[1], channel[1]))); + std::get<0>(done).result(); + std::get<1>(done).result(); + if (!s.isConfigured() || !r.isConfigured() || s.silentBaseOtCount() || r.silentBaseOtCount()) + throw std::runtime_error("GF(4) wrapper lost its stationary PPRF"); + for (u64 i = 0; i < k; ++i) + { + const F4 c = round ? choices[i] : F4{u8(a[i].get(0) & 3)}; + block product; + ctx.mul(product, delta, c); + if ((a[i] & block(~0ull, ~3ull)) != (b[i] ^ product)) + throw std::runtime_error("GF(4) wrapper correlation mismatch"); + } + } + } + + // Four full batches exercise two rounds on each of two workers. Keep the + // public storage across init() and check private streams start afresh. + PRNG prng(oc::ZeroBlock); + std::array peers; + std::array, 2> identity; + std::array, 2> previous{}; + for (u64 join = 0; join < 2; ++join) + { + auto sockets = coproto::LocalAsyncSocket::makePair(); + for (u64 party = 0; party < 2; ++party) + peers[party].init(std::move(sockets[party]), prng, party, 2, k, false, Noise::Stationary); + auto sendState = peers[0].mGenState; + auto recvState = peers[1].mGenState; + auto send = peers[0].sendOtRequest(4 * k); + auto recv = peers[1].recvOtRequest(4 * k); + send.start(); + recv.start(); + auto tasks = macoro::sync_wait(macoro::when_all_ready(peers[0].start(), peers[1].start())); + std::get<0>(tasks).result(); + std::get<1>(tasks).result(); + + if (!sendState->mSendOtBase.hasBaseOts() || !recvState->mRecvOtBase.hasBaseOts() || + sendState->mSendOtBase.mRandomOt || recvState->mRecvOtBase.mRandomOt) + throw std::runtime_error("Stationary binary batches bypassed the common noise provider"); + + u64 seeds[2]; + for (u64 w = 0; w < 2; ++w) + { + const auto& left = peers[0].mBanks->idle.at(0).at(w).codes.at(k)->encoder(); + const auto& right = peers[1].mBanks->idle.at(0).at(w).codes.at(k)->encoder(); + if (left.descriptor() != right.descriptor()) + throw std::runtime_error("Stationary peer maps disagree"); + if (join) + { + left.prepare_workspace(*identity[w]); // Checks the identity of the underlying bank. + if (left.descriptor() == previous[w]) + throw std::runtime_error("New peer session restarted the previous seed schedule"); + } + else + identity[w].emplace(left.make_workspace()); + previous[w] = left.descriptor(); + seeds[w] = left.setup_options().bank_seed; + } + if (seeds[0] == seeds[1]) + throw std::runtime_error("Concurrent workers sampled the same bank"); + } + + auto sockets = coproto::LocalAsyncSocket::makePair(); + peers[0].init(std::move(sockets[0]), prng, 0, 2, k, false, Noise::Stationary); + peers[1].init(std::move(sockets[1]), prng, 1, 1, k, false, Noise::Stationary); + auto send = peers[0].sendOtRequest(k); + auto recv = peers[1].recvOtRequest(k); + auto tasks = macoro::sync_wait(macoro::when_all_ready(peers[0].start(), peers[1].start())); + auto expectMismatch = [](auto& t) { + try { t.result(); } + catch (const std::runtime_error& e) { + if (std::string(e.what()).find("Peer correlation") != std::string::npos) + return; + throw; + } + throw std::runtime_error("Mismatched worker counts accepted"); + }; + expectMismatch(std::get<0>(tasks)); + expectMismatch(std::get<1>(tasks)); + OtSend out; + OtRecv in; + auto requests = macoro::sync_wait(macoro::when_all_ready(send.get(out), recv.get(in))); + expectMismatch(std::get<0>(requests)); + expectMismatch(std::get<1>(requests)); +} diff --git a/tests/CorGenerator_Test.h b/tests/CorGenerator_Test.h index 5b0856b27..2ee131b30 100644 --- a/tests/CorGenerator_Test.h +++ b/tests/CorGenerator_Test.h @@ -7,3 +7,5 @@ void CorGenerator_BinOle_Test(const oc::CLP&); void CorGenerator_F4BitOt_Test(const oc::CLP&); void CorGenerator_TritOt_Test(const oc::CLP&); void CorGenerator_mixed_Test(const oc::CLP&); + +void CorGenerator_SpinWorkers_Test(const oc::CLP&); diff --git a/tests/F4Vole_Test.cpp b/tests/F4Vole_Test.cpp index e5baeb4dd..ec8e16688 100644 --- a/tests/F4Vole_Test.cpp +++ b/tests/F4Vole_Test.cpp @@ -306,10 +306,10 @@ void F4Vole_Silent_test_chosen(u64 n, oc::MultType type, bool debug, bool doFake void F4Vole_Silent_paramSweep_test(const oc::CLP& cmd) { auto debug = cmd.isSet("debug"); - for (u64 n : {128, 4534}) + for (u64 n : {128, 4534, 8193, 65536}) { - //F4Vole_Silent_test_impl_base(n, oc::DefaultMultType, debug, true, false); - F4Vole_Silent_test_impl(n, oc::DefaultMultType, debug, true, false); - //F4Vole_Silent_test_chosen(n, oc::DefaultMultType, debug, true, false); + //F4Vole_Silent_test_impl_base(n, oc::MultType::Spin, debug, true, false); + F4Vole_Silent_test_impl(n, oc::MultType::Spin, debug, true, false); + //F4Vole_Silent_test_chosen(n, oc::MultType::Spin, debug, true, false); } } diff --git a/tests/OmJoin_Test.cpp b/tests/OmJoin_Test.cpp index c4fe5ae94..878379c73 100644 --- a/tests/OmJoin_Test.cpp +++ b/tests/OmJoin_Test.cpp @@ -33,7 +33,7 @@ void OmJoin_loadKeys_Test() ColRef left(leftTable, leftTable.mColumns[0]); ColRef right(rightTable, rightTable.mColumns[0]); - auto res = OmJoin{}.loadKeys(left, right); + auto res = OmJoin{}.loadKeys(left, right, oc::ZeroBlock); for (u64 i = 0; i < n0; ++i) { diff --git a/tests/UnitTests.cpp b/tests/UnitTests.cpp index e8c6cd39b..8e12810e3 100644 --- a/tests/UnitTests.cpp +++ b/tests/UnitTests.cpp @@ -134,6 +134,8 @@ namespace secJoin_Tests t.add("WhereParser_BoolOps_Test ", WhereParser_BoolOps_Test); t.add("WhereParser_Big_Test ", WhereParser_Big_Test); + t.add("CorGenerator_SpinWorkers_Test ", CorGenerator_SpinWorkers_Test); + //t.add("Where_genWhBundle_Test ", WhereParser_genWhBundle_Test); //t.add("WhereParser_ArrType_Equals_Test ", WhereParser_ArrType_Equals_Test); //t.add("WhereParser_ArrType_Not_Equals_Test ", WhereParser_ArrType_Not_Equals_Test); diff --git a/thirdparty/getLibOTe.cmake b/thirdparty/getLibOTe.cmake index ba9689edb..7903bf04d 100644 --- a/thirdparty/getLibOTe.cmake +++ b/thirdparty/getLibOTe.cmake @@ -2,11 +2,7 @@ set(USER_NAME ) set(TOKEN ) set(GIT_REPOSITORY "https://github.com/osu-crypto/libOTe.git") -set(GIT_TAG "657f6da90bff5774a2d01c824e997572d5e8ba00") -# Keep libOTe's PPRF API while picking up the GCC 15 fixes in cryptoTools, -# coproto, macoro and libdivide. -set(CRYPTOTOOLS_TAG "994bbfa789ff2e7f37b7d022e7667996f1c551b9") - +set(GIT_TAG "047d68e50ca28e32e121631ce6846dcb9b5bda69") set(DEP_NAME libOTe) set(CLONE_DIR "${SECUREJOIN_THIRDPARTY_CLONE_DIR}/${DEP_NAME}") #set(BUILD_DIR "${CLONE_DIR}/out/build/${SECUREJOIN_CONFIG}") @@ -36,18 +32,16 @@ if(NOT EXISTS ${CLONE_DIR}) endif() -run(NAME "libOTe Checkout ${GIT_TAG} " CMD ${CHECKOUT_CMD} WD ${CLONE_DIR}) -set(CRYPTOTOOLS_DIR "${CLONE_DIR}/cryptoTools") -if(NOT EXISTS "${CRYPTOTOOLS_DIR}/.git") - run(NAME "Initialize cryptoTools" CMD ${GIT} submodule update --init cryptoTools WD ${CLONE_DIR}) +execute_process(COMMAND ${GIT} cat-file -e ${GIT_TAG}^{commit} WORKING_DIRECTORY ${CLONE_DIR} + RESULT_VARIABLE tag_missing ERROR_QUIET) +if(tag_missing) + run(NAME "Fetch pinned libOTe" CMD ${GIT} fetch origin ${GIT_TAG} WD ${CLONE_DIR}) endif() -execute_process(COMMAND ${GIT} cat-file -e ${CRYPTOTOOLS_TAG}^{commit} - WORKING_DIRECTORY "${CRYPTOTOOLS_DIR}" RESULT_VARIABLE missing_cryptoTools ERROR_QUIET) -if(missing_cryptoTools) - run(NAME "Fetch cryptoTools" CMD ${GIT} fetch origin ${CRYPTOTOOLS_TAG} WD ${CRYPTOTOOLS_DIR}) -endif() -run(NAME "Checkout cryptoTools ${CRYPTOTOOLS_TAG}" CMD ${GIT} checkout ${CRYPTOTOOLS_TAG} WD ${CRYPTOTOOLS_DIR}) +run(NAME "libOTe Checkout ${GIT_TAG} " CMD ${CHECKOUT_CMD} WD ${CLONE_DIR}) +run(NAME "Initialize libOTe submodules" CMD ${GIT} submodule update --init --recursive WD ${CLONE_DIR}) +set(ENABLE_SPIN ON) +option(ENABLE_LOGVOLE "Build libOTe LogVOLE" OFF) option(ENABLE_CIRCUITS " " true) if(ENABLE_MOCK_OT) else()