Improve factorization tests.

This commit is contained in:
levlam 2022-03-20 00:01:07 +03:00
parent 1d15bafb50
commit 6e86faaa0f

View File

@ -14,11 +14,9 @@
#include "td/utils/logging.h"
#include "td/utils/SliceBuilder.h"
#include <algorithm>
#include <limits>
#include <utility>
#if TD_HAVE_OPENSSL
static bool is_prime(td::uint64 x) {
for (td::uint64 d = 2; d < x && d * d <= x; d++) {
if (x % d == 0) {
@ -28,9 +26,9 @@ static bool is_prime(td::uint64 x) {
return true;
}
static td::vector<td::uint64> gen_primes(td::uint64 L, td::uint64 R, int limit = 0) {
static td::vector<td::uint64> gen_primes(td::uint64 L, td::uint64 R, std::size_t limit = 0) {
td::vector<td::uint64> res;
for (auto x = L; x <= R && (limit <= 0 || res.size() < static_cast<std::size_t>(limit)); x++) {
for (auto x = L; x <= R && (limit <= 0 || res.size() < limit); x++) {
if (is_prime(x)) {
res.push_back(x);
}
@ -49,10 +47,6 @@ static td::vector<td::uint64> gen_primes() {
using PqQuery = std::pair<td::uint64, td::uint64>;
static bool cmp(const PqQuery &a, const PqQuery &b) {
return a.first * a.second < b.first * b.second;
}
static td::vector<PqQuery> gen_pq_queries() {
td::vector<PqQuery> res;
auto primes = gen_primes();
@ -64,11 +58,38 @@ static td::vector<PqQuery> gen_pq_queries() {
res.emplace_back(p, q);
}
}
std::sort(res.begin(), res.end(), cmp);
return res;
}
static void test_pq(td::uint64 first, td::uint64 second) {
static td::string to_binary(td::uint64 x) {
td::string result;
do {
result = static_cast<char>(x & 255) + result;
x >>= 8;
} while (x > 0);
return result;
}
static void test_pq_fast(td::uint64 first, td::uint64 second) {
if ((static_cast<td::uint64>(1) << 63) / first <= second) {
return;
}
td::string p_str;
td::string q_str;
int err = td::pq_factorize(to_binary(first * second), &p_str, &q_str);
ASSERT_EQ(err, 0);
ASSERT_STREQ(p_str, to_binary(first));
ASSERT_STREQ(q_str, to_binary(second));
}
#if TD_HAVE_OPENSSL
static void test_pq_slow(td::uint64 first, td::uint64 second) {
if ((static_cast<td::uint64>(1) << 63) / first > second) {
return;
}
td::BigNum p = td::BigNum::from_decimal(PSLICE() << first).move_as_ok();
td::BigNum q = td::BigNum::from_decimal(PSLICE() << second).move_as_ok();
@ -101,18 +122,28 @@ TEST(CryptoPQ, hands) {
ASSERT_EQ(179424611ull, td::pq_factorize(179424611ull * 179424673ull));
#if TD_HAVE_OPENSSL
test_pq(4294467311, 4294467449);
test_pq_slow(4294467311, 4294467449);
#endif
}
TEST(CryptoPQ, four) {
for (int i = 0; i < 100000; i++) {
test_pq_fast(2, 2);
}
}
TEST(CryptoPQ, generated_fast) {
auto queries = gen_pq_queries();
for (const auto &query : queries) {
test_pq_fast(query.first, query.second);
}
}
#if TD_HAVE_OPENSSL
TEST(CryptoPQ, generated_slow) {
for (int i = 0; i < 100000; i++) {
test_pq(2, 2);
}
auto queries = gen_pq_queries();
for (const auto &query : queries) {
test_pq(query.first, query.second);
test_pq_slow(query.first, query.second);
}
}
#endif