Skip to content

Truly independent web browser

LibCrypto+Meta: Remove UnsignedBigInteger and libtommath

Shannon Booth4e15e7773588
diff --git a/Libraries/LibCrypto/BigInt/Tommath.h b/Libraries/LibCrypto/BigInt/Tommath.h
deleted file mode 100644
index eb1974144d7..00000000000
--- a/Libraries/LibCrypto/BigInt/Tommath.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (c) 2025, Altomani Gianluca <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Error.h>
-
-#include <tommath.h>
-
-inline ErrorOr<void> mp_error(mp_err error)
-{
- switch (error) {
- case MP_OKAY:
- return {};
- case MP_MEM:
- return Error::from_errno(ENOMEM);
- case MP_VAL:
- return Error::from_errno(EINVAL);
- case MP_ITER:
- return Error::from_string_literal("Maximum iterations reached");
- case MP_BUF:
- return Error::from_string_literal("Buffer overflow");
- default:
- return Error::from_string_literal("Unknown error");
- }
-}
-
-#define MP_TRY(...) TRY(mp_error((__VA_ARGS__)))
-
-#define MP_MUST(...) MUST(mp_error((__VA_ARGS__)))
diff --git a/Libraries/LibCrypto/BigInt/TommathForward.h b/Libraries/LibCrypto/BigInt/TommathForward.h
deleted file mode 100644
index 33def098d32..00000000000
--- a/Libraries/LibCrypto/BigInt/TommathForward.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (c) 2025, Altomani Gianluca <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Platform.h>
-#include <stdint.h>
-
-extern "C" {
-#if defined(AK_OS_WINDOWS)
-typedef uint32_t mp_digit;
-#else
-typedef uint64_t mp_digit;
-#endif
-typedef int mp_sign;
-
-// This is a workaround for the fact that Tommath doesn't have a proper
-// header file. It uses an anonymous struct to define the mp_int struct
-// which makes it impossible to forward declare.
-// Declare the mp_int struct with the same layout as the one in tommath.h
-// and check that the layout is the same while avoiding a conflicting
-// definition error (BN_H_ is defined in tommath.h).
-// When importing this file it is important to always do it AFTER tommath.h.
-
-typedef struct {
- int used, alloc;
- mp_sign sign;
- mp_digit* dp;
-} mp_int_;
-
-#ifndef BN_H_
-typedef mp_int_ mp_int;
-#else
-static_assert(sizeof(mp_int_) == sizeof(mp_int));
-static_assert(offsetof(mp_int_, used) == offsetof(mp_int, used));
-static_assert(offsetof(mp_int_, alloc) == offsetof(mp_int, alloc));
-static_assert(offsetof(mp_int_, sign) == offsetof(mp_int, sign));
-static_assert(offsetof(mp_int_, dp) == offsetof(mp_int, dp));
-#endif
-}
diff --git a/Libraries/LibCrypto/BigInt/UnsignedBigInteger.cpp b/Libraries/LibCrypto/BigInt/UnsignedBigInteger.cpp
deleted file mode 100644
index bd1dd02ca4b..00000000000
--- a/Libraries/LibCrypto/BigInt/UnsignedBigInteger.cpp
+++ /dev/null
@@ -1,634 +0,0 @@
-/*
- * Copyright (c) 2020, Itamar S. <[email protected]>
- * Copyright (c) 2022, David Tuin <[email protected]>
- * Copyright (c) 2025, Altomani Gianluca <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <math.h>
-#include <tommath.h>
-
-#include <AK/BuiltinWrappers.h>
-#include <AK/FloatingPoint.h>
-#include <AK/Memory.h>
-#include <AK/StringBuilder.h>
-#include <AK/Utf16StringBuilder.h>
-#include <LibCrypto/BigInt/Tommath.h>
-#include <LibCrypto/BigInt/UnsignedBigInteger.h>
-
-namespace Crypto {
-
-// Tommath's mp_init() reserves MP_PREC digits, which is 256 zeroed bytes for a value that is usually a handful of
-// bits wide. Ask for the smallest amount it accepts instead, covering values up to two digits before anything has to
-// grow.
-static constexpr int initial_digit_count = 2;
-
-UnsignedBigInteger::UnsignedBigInteger(ReadonlyBytes data)
-{
- MP_MUST(mp_init_size(&m_mp, initial_digit_count));
- MP_MUST(mp_from_ubin(&m_mp, data.data(), data.size()));
-}
-
-UnsignedBigInteger::UnsignedBigInteger(Vector<u32> const& words)
-{
- MP_MUST(mp_init_size(&m_mp, initial_digit_count));
- MP_MUST(mp_unpack(&m_mp, words.size(), MP_LSB_FIRST, sizeof(u32), MP_NATIVE_ENDIAN, 0, words.data()));
-}
-
-UnsignedBigInteger::UnsignedBigInteger(double value)
-{
- // Because this is currently only used for LibJS we VERIFY some preconditions
- // also these values don't have a clear BigInteger representation.
- VERIFY(!isnan(value));
- VERIFY(!isinf(value));
- VERIFY(trunc(value) == value);
- VERIFY(value >= 0.0);
-
- MP_MUST(mp_init_size(&m_mp, initial_digit_count));
- MP_MUST(mp_set_double(&m_mp, value));
-}
-
-UnsignedBigInteger::UnsignedBigInteger(u64 value)
-{
- MP_MUST(mp_init_size(&m_mp, initial_digit_count));
- mp_set_u64(&m_mp, value);
-}
-
-UnsignedBigInteger::UnsignedBigInteger(UnsignedBigInteger const& other)
- : m_hash(other.m_hash)
-{
- MP_MUST(mp_init_copy(&m_mp, &other.m_mp));
-}
-
-UnsignedBigInteger::UnsignedBigInteger(UnsignedBigInteger&& other)
- : m_mp(other.m_mp)
- , m_hash(other.m_hash)
-{
- other.m_mp = {};
- other.m_hash.clear();
-}
-
-UnsignedBigInteger& UnsignedBigInteger::operator=(UnsignedBigInteger const& other)
-{
- if (this == &other)
- return *this;
-
- mp_clear(&m_mp);
- MP_MUST(mp_init_copy(&m_mp, &other.m_mp));
- m_hash = other.m_hash;
-
- return *this;
-}
-
-UnsignedBigInteger& UnsignedBigInteger::operator=(UnsignedBigInteger&& other)
-{
- if (this == &other)
- return *this;
-
- mp_clear(&m_mp);
- m_mp = other.m_mp;
- m_hash = other.m_hash;
-
- other.m_mp = {};
- other.m_hash.clear();
-
- return *this;
-}
-
-UnsignedBigInteger::UnsignedBigInteger()
-{
- MP_MUST(mp_init_size(&m_mp, initial_digit_count));
-}
-
-UnsignedBigInteger::~UnsignedBigInteger()
-{
- mp_clear(&m_mp);
-}
-
-void UnsignedBigInteger::clear_sensitive_data()
-{
- if (m_mp.dp)
- secure_zero(m_mp.dp, static_cast<size_t>(m_mp.alloc) * sizeof(mp_digit));
- m_mp.used = 0;
- m_mp.sign = MP_ZPOS;
- m_hash.clear();
-}
-
-Bytes UnsignedBigInteger::export_data(Bytes data) const
-{
- size_t written = 0;
- MP_MUST(mp_to_ubin(&m_mp, data.data(), data.size(), &written));
- return data.slice(0, written);
-}
-
-ErrorOr<UnsignedBigInteger> UnsignedBigInteger::from_base(u16 N, StringView str)
-{
- VERIFY(N <= 36);
- if (str.is_empty())
- return UnsignedBigInteger(0);
-
- auto buffer = TRY(ByteBuffer::create_zeroed(str.length() + 1));
-
- size_t idx = 0;
- for (auto& c : str) {
- if (c == '_') {
- // Skip underscores
- continue;
- }
-
- buffer[idx++] = c;
- }
-
- UnsignedBigInteger result;
- if (mp_read_radix(&result.m_mp, reinterpret_cast<char const*>(buffer.data()), N) != MP_OKAY)
- return Error::from_string_literal("Invalid number");
- return result;
-}
-
-ErrorOr<UnsignedBigInteger> UnsignedBigInteger::from_base(u16 N, Utf16View str)
-{
- VERIFY(N <= 36);
- if (str.is_empty())
- return UnsignedBigInteger(0);
-
- auto buffer = TRY(ByteBuffer::create_zeroed(str.length_in_code_units() + 1));
-
- size_t idx = 0;
- for (size_t i = 0; i < str.length_in_code_units(); ++i) {
- auto code_unit = str.code_unit_at(i);
- if (code_unit > NumericLimits<u8>::max())
- return Error::from_string_literal("Invalid number");
- if (code_unit == '_') {
- // Skip underscores
- continue;
- }
-
- buffer[idx++] = static_cast<u8>(code_unit);
- }
-
- UnsignedBigInteger result;
- if (mp_read_radix(&result.m_mp, reinterpret_cast<char const*>(buffer.data()), N) != MP_OKAY)
- return Error::from_string_literal("Invalid number");
- return result;
-}
-
-ErrorOr<String> UnsignedBigInteger::to_base(u16 N) const
-{
- VERIFY(N <= 36);
- if (is_zero())
- return "0"_string;
-
- int size = 0;
- MP_MUST(mp_radix_size(&m_mp, N, &size));
- auto buffer = TRY(ByteBuffer::create_zeroed(size));
-
- size_t written = 0;
- MP_MUST(mp_to_radix(&m_mp, reinterpret_cast<char*>(buffer.data()), size, &written, N));
-
- return StringView(buffer.bytes().slice(0, written - 1)).to_ascii_lowercase_string();
-}
-
-ErrorOr<Utf16String> UnsignedBigInteger::to_base_utf16(u16 N) const
-{
- VERIFY(N <= 36);
- if (is_zero())
- return "0"_utf16;
-
- int size = 0;
- MP_MUST(mp_radix_size(&m_mp, N, &size));
- auto buffer = TRY(ByteBuffer::create_zeroed(size));
-
- size_t written = 0;
- MP_MUST(mp_to_radix(&m_mp, reinterpret_cast<char*>(buffer.data()), size, &written, N));
-
- Utf16StringBuilder builder(written - 1);
- for (auto character : buffer.bytes().slice(0, written - 1)) {
- if (character >= 'A' && character <= 'Z')
- character += 'a' - 'A';
- builder.append_code_unit(character);
- }
- return builder.to_string();
-}
-
-size_t UnsignedBigInteger::count_digits_in_base(u16 base) const
-{
- VERIFY(base <= 36);
-
- if (is_zero())
- return 1;
-
- int size = 0;
- MP_MUST(mp_radix_size(&m_mp, base, &size));
-
- // mp_radix_size includes a null byte.
- return static_cast<size_t>(size) - 1;
-}
-
-u64 UnsignedBigInteger::to_u64() const
-{
- return mp_get_u64(&m_mp);
-}
-
-double UnsignedBigInteger::to_double(RoundingMode rounding_mode) const
-{
- // Check if we need to truncate
- auto bitlen = mp_count_bits(&m_mp);
- if (bitlen <= 53)
- return mp_get_double(&m_mp);
-
- if (rounding_mode == RoundingMode::RoundTowardZero) {
- UnsignedBigInteger shifted;
-
- // Truncate the lower bits
- auto shift = bitlen - 53;
- MP_MUST(mp_div_2d(&m_mp, shift, &shifted.m_mp, nullptr));
-
- // Convert to double
- return ldexp(mp_get_double(&shifted.m_mp), shift);
- }
-
- if (rounding_mode == RoundingMode::IEEERoundAndTiesToEvenMantissa) {
- UnsignedBigInteger shifted, remainder, half, lsb;
-
- // Get top 53 bits (truncated)
- auto shift = bitlen - 53;
- MP_MUST(mp_div_2d(&m_mp, shift, &shifted.m_mp, &remainder.m_mp));
-
- // Check if remainder == 2^(shift - 1)
- MP_MUST(mp_2expt(&half.m_mp, shift - 1));
- int cmp = mp_cmp(&remainder.m_mp, &half.m_mp);
- if (cmp < 0) {
- // Round down (truncate)
- } else if (cmp > 0) {
- // Round up
- MP_MUST(mp_add_d(&shifted.m_mp, 1, &shifted.m_mp));
- } else {
- // Exactly halfway, check even
- MP_MUST(mp_mod_2d(&shifted.m_mp, 1, &lsb.m_mp));
- if (!mp_iszero(&lsb.m_mp)) {
- // It's odd, round to even
- MP_MUST(mp_add_d(&shifted.m_mp, 1, &shifted.m_mp));
- }
- }
-
- // Convert to double
- return ldexp(mp_get_double(&shifted.m_mp), shift);
- }
-
- VERIFY_NOT_REACHED();
-}
-
-Vector<u32> UnsignedBigInteger::words() const
-{
- auto count = mp_pack_count(&m_mp, 0, sizeof(u32));
- Vector<u32> result;
- result.resize(count);
-
- size_t written = 0;
- MP_MUST(mp_pack(result.data(), count, &written, MP_LSB_FIRST, sizeof(u32), MP_NATIVE_ENDIAN, 0, &m_mp));
-
- result.resize(written);
- return result;
-}
-
-void UnsignedBigInteger::set_to_0()
-{
- mp_zero(&m_mp);
- m_hash = {};
-}
-
-void UnsignedBigInteger::set_to(u64 other)
-{
- mp_set_u64(&m_mp, other);
- m_hash = {};
-}
-
-void UnsignedBigInteger::set_to(UnsignedBigInteger const& other)
-{
- MP_MUST(mp_copy(&other.m_mp, &m_mp));
- m_hash = {};
-}
-
-bool UnsignedBigInteger::is_zero() const
-{
- return mp_iszero(&m_mp);
-}
-
-bool UnsignedBigInteger::is_odd() const
-{
- return mp_isodd(&m_mp);
-}
-
-size_t UnsignedBigInteger::byte_length() const
-{
- return mp_ubin_size(&m_mp);
-}
-
-size_t UnsignedBigInteger::one_based_index_of_highest_set_bit() const
-{
- return mp_count_bits(&m_mp);
-}
-
-FLATTEN UnsignedBigInteger UnsignedBigInteger::plus(UnsignedBigInteger const& other) const
-{
- UnsignedBigInteger result;
- MP_MUST(mp_add(&m_mp, &other.m_mp, &result.m_mp));
- return result;
-}
-
-FLATTEN ErrorOr<UnsignedBigInteger> UnsignedBigInteger::minus(UnsignedBigInteger const& other) const
-{
- UnsignedBigInteger result;
- MP_MUST(mp_sub(&m_mp, &other.m_mp, &result.m_mp));
- if (mp_isneg(&result.m_mp))
- return Error::from_string_literal("Substraction produced a negative result");
- return result;
-}
-
-FLATTEN UnsignedBigInteger UnsignedBigInteger::bitwise_or(UnsignedBigInteger const& other) const
-{
- UnsignedBigInteger result;
- MP_MUST(mp_or(&m_mp, &other.m_mp, &result.m_mp));
- return result;
-}
-
-FLATTEN UnsignedBigInteger UnsignedBigInteger::bitwise_and(UnsignedBigInteger const& other) const
-{
- UnsignedBigInteger result;
- MP_MUST(mp_and(&m_mp, &other.m_mp, &result.m_mp));
- return result;
-}
-
-FLATTEN UnsignedBigInteger UnsignedBigInteger::bitwise_xor(UnsignedBigInteger const& other) const
-{
- UnsignedBigInteger result;
- MP_MUST(mp_xor(&m_mp, &other.m_mp, &result.m_mp));
- return result;
-}
-
-FLATTEN ErrorOr<UnsignedBigInteger> UnsignedBigInteger::bitwise_not_fill_to_one_based_index(size_t index) const
-{
- if (index == 0)
- return UnsignedBigInteger(0);
- if (index > NumericLimits<int>::max())
- return Error::from_errno(ENOMEM);
-
- UnsignedBigInteger result, mask, temp;
-
- MP_TRY(mp_2expt(&mask.m_mp, index));
- MP_TRY(mp_sub_d(&mask.m_mp, 1, &mask.m_mp));
-
- MP_TRY(mp_and(&mask.m_mp, &m_mp, &temp.m_mp));
- MP_TRY(mp_xor(&temp.m_mp, &mask.m_mp, &result.m_mp));
-
- return result;
-}
-
-FLATTEN ErrorOr<UnsignedBigInteger> UnsignedBigInteger::shift_left(size_t num_bits) const
-{
- UnsignedBigInteger result;
- MP_TRY(mp_mul_2d(&m_mp, num_bits, &result.m_mp));
- return result;
-}
-
-FLATTEN UnsignedBigInteger UnsignedBigInteger::shift_right(size_t num_bits) const
-{
- UnsignedBigInteger result;
- MP_MUST(mp_div_2d(&m_mp, num_bits, &result.m_mp, nullptr));
- return result;
-}
-
-FLATTEN UnsignedBigInteger UnsignedBigInteger::multiplied_by(UnsignedBigInteger const& other) const
-{
- UnsignedBigInteger result;
- MP_MUST(mp_mul(&m_mp, &other.m_mp, &result.m_mp));
- return result;
-}
-
-FLATTEN UnsignedDivisionResult UnsignedBigInteger::divided_by(UnsignedBigInteger const& divisor) const
-{
- UnsignedBigInteger quotient;
- UnsignedBigInteger remainder;
- MP_MUST(mp_div(&m_mp, &divisor.m_mp, &quotient.m_mp, &remainder.m_mp));
- return UnsignedDivisionResult { move(quotient), move(remainder) };
-}
-
-FLATTEN UnsignedBigInteger UnsignedBigInteger::quotient(UnsignedBigInteger const& divisor) const
-{
- UnsignedBigInteger result;
- MP_MUST(mp_div(&m_mp, &divisor.m_mp, &result.m_mp, nullptr));
- return result;
-}
-
-FLATTEN UnsignedBigInteger UnsignedBigInteger::remainder(UnsignedBigInteger const& divisor) const
-{
- UnsignedBigInteger result;
- MP_MUST(mp_div(&m_mp, &divisor.m_mp, nullptr, &result.m_mp));
- return result;
-}
-
-FLATTEN UnsignedBigInteger UnsignedBigInteger::pow(u32 exponent) const
-{
- UnsignedBigInteger result;
- MP_MUST(mp_expt_n(&m_mp, exponent, &result.m_mp));
- return result;
-}
-
-FLATTEN UnsignedBigInteger UnsignedBigInteger::gcd(UnsignedBigInteger const& other) const
-{
- UnsignedBigInteger result;
- MP_MUST(mp_gcd(&m_mp, &other.m_mp, &result.m_mp));
- return result;
-}
-
-FLATTEN UnsignedBigInteger UnsignedBigInteger::lcm(UnsignedBigInteger const& other) const
-{
- UnsignedBigInteger result;
- MP_MUST(mp_lcm(&m_mp, &other.m_mp, &result.m_mp));
- return result;
-}
-
-u32 UnsignedBigInteger::hash() const
-{
- return m_hash.ensure([&] {
- auto buffer = MUST(ByteBuffer::create_zeroed(byte_length()));
- auto result = export_data(buffer);
- return string_hash(reinterpret_cast<char const*>(result.data()), result.size());
- });
-}
-
-bool UnsignedBigInteger::operator==(UnsignedBigInteger const& other) const
-{
- return mp_cmp(&m_mp, &other.m_mp) == MP_EQ;
-}
-
-bool UnsignedBigInteger::operator!=(UnsignedBigInteger const& other) const
-{
- return !(*this == other);
-}
-
-bool UnsignedBigInteger::operator<(UnsignedBigInteger const& other) const
-{
- return mp_cmp(&m_mp, &other.m_mp) == MP_LT;
-}
-
-bool UnsignedBigInteger::operator<=(UnsignedBigInteger const& other) const
-{
- return *this < other || *this == other;
-}
-
-bool UnsignedBigInteger::operator>(UnsignedBigInteger const& other) const
-{
- return *this != other && !(*this < other);
-}
-
-bool UnsignedBigInteger::operator>=(UnsignedBigInteger const& other) const
-{
- return *this > other || *this == other;
-}
-
-UnsignedBigInteger::CompareResult UnsignedBigInteger::compare_to_double(double value) const
-{
- VERIFY(!isnan(value));
-
- if (isinf(value)) {
- bool is_positive_infinity = __builtin_isinf_sign(value) > 0;
- return is_positive_infinity ? CompareResult::DoubleGreaterThanBigInt : CompareResult::DoubleLessThanBigInt;
- }
-
- bool value_is_negative = value < 0;
-
- if (value_is_negative)
- return CompareResult::DoubleLessThanBigInt;
-
- // Value is zero.
- if (value == 0.0) {
- VERIFY(!value_is_negative);
- // Either we are also zero or value is certainly less than us.
- return is_zero() ? CompareResult::DoubleEqualsBigInt : CompareResult::DoubleLessThanBigInt;
- }
-
- // If value is not zero but we are, value must be greater.
- if (is_zero())
- return CompareResult::DoubleGreaterThanBigInt;
-
- FloatExtractor<double> extractor;
- extractor.d = value;
-
- // Value cannot be negative at this point.
- VERIFY(extractor.sign == 0);
- // Exponent cannot be all set, as then we must be NaN or infinity.
- VERIFY(extractor.exponent != (1 << extractor.exponent_bits) - 1);
-
- i32 real_exponent = extractor.exponent - extractor.exponent_bias;
- if (real_exponent < 0) {
- // value is less than 1, and we cannot be zero so value must be less.
- return CompareResult::DoubleLessThanBigInt;
- }
-
- u64 bigint_bits_needed = one_based_index_of_highest_set_bit();
- VERIFY(bigint_bits_needed > 0);
-
- // Double value is `-1^sign (1.mantissa) * 2^(exponent - bias)` so we need
- // `exponent - bias + 1` bit to represent doubles value,
- // for example `exponent - bias` = 3, sign = 0 and mantissa = 0 we get
- // `-1^0 * 2^3 * 1 = 8` which needs 4 bits to store 8 (0b1000).
- u32 double_bits_needed = real_exponent + 1;
-
- // If we need more bits to represent us, we must be of greater value.
- if (bigint_bits_needed > double_bits_needed)
- return CompareResult::DoubleLessThanBigInt;
- // If we need less bits to represent us, we must be of less value.
- if (bigint_bits_needed < double_bits_needed)
- return CompareResult::DoubleGreaterThanBigInt;
-
- u64 mantissa_bits = extractor.mantissa;
-
- // We add the bit which represents the 1. of the double value calculation.
- constexpr u64 mantissa_extended_bit = 1ull << extractor.mantissa_bits;
-
- mantissa_bits |= mantissa_extended_bit;
-
- constexpr u32 bits_in_word = sizeof(u32) * 8;
-
- // Now we shift value to the left virtually, with `exponent - bias` steps
- // we then pretend both it and the big int are extended with virtual zeros.
- auto next_bigint_word = (bits_in_word - 1 + bigint_bits_needed) / bits_in_word;
-
- auto words = this->words();
- VERIFY(next_bigint_word == words.size());
-
- auto msb_in_top_word_index = (bigint_bits_needed - 1) % bits_in_word;
- VERIFY(msb_in_top_word_index == (bits_in_word - count_leading_zeroes(words[next_bigint_word - 1]) - 1));
-
- // We will keep the bits which are still valid in the mantissa at the top of mantissa bits.
- mantissa_bits <<= 64 - (extractor.mantissa_bits + 1);
-
- auto bits_left_in_mantissa = static_cast<size_t>(extractor.mantissa_bits) + 1;
-
- auto get_next_value_bits = [&](size_t num_bits) -> u32 {
- VERIFY(num_bits < 63);
- VERIFY(bits_left_in_mantissa > 0);
- if (num_bits > bits_left_in_mantissa)
- num_bits = bits_left_in_mantissa;
-
- bits_left_in_mantissa -= num_bits;
-
- u64 extracted_bits = mantissa_bits & (((1ull << num_bits) - 1) << (64 - num_bits));
- // Now shift the bits down to put the most significant bit on the num_bits position
- // this means the rest will be "virtual" zeros.
- extracted_bits >>= bits_in_word;
-
- // Now shift away the used bits and fit the result into a Word.
- mantissa_bits <<= num_bits;
-
- VERIFY(extracted_bits <= NumericLimits<u32>::max());
- return static_cast<u32>(extracted_bits);
- };
-
- auto bits_in_next_bigint_word = msb_in_top_word_index + 1;
-
- while (next_bigint_word > 0 && bits_left_in_mantissa > 0) {
- u32 bigint_word = words[next_bigint_word - 1];
- u32 double_word = get_next_value_bits(bits_in_next_bigint_word);
-
- // For the first bit we have to align it with the top bit of bigint
- // and for all the other cases bits_in_next_bigint_word is 32 so this does nothing.
- double_word >>= bits_in_word - bits_in_next_bigint_word;
-
- if (bigint_word < double_word)
- return CompareResult::DoubleGreaterThanBigInt;
-
- if (bigint_word > double_word)
- return CompareResult::DoubleLessThanBigInt;
-
- --next_bigint_word;
- bits_in_next_bigint_word = bits_in_word;
- }
-
- // If there are still bits left in bigint than any non zero bit means it has greater value.
- if (next_bigint_word > 0) {
- VERIFY(bits_left_in_mantissa == 0);
- while (next_bigint_word > 0) {
- if (words[next_bigint_word - 1] != 0)
- return CompareResult::DoubleLessThanBigInt;
- --next_bigint_word;
- }
- } else if (bits_left_in_mantissa > 0) {
- VERIFY(next_bigint_word == 0);
- // Similarly if there are still any bits set in the mantissa it has greater value.
- if (mantissa_bits != 0)
- return CompareResult::DoubleGreaterThanBigInt;
- }
-
- // Otherwise if both don't have bits left or the rest of the bits are zero they are equal.
- return CompareResult::DoubleEqualsBigInt;
-}
-
-}
-
-ErrorOr<void> AK::Formatter<Crypto::UnsignedBigInteger>::format(FormatBuilder& fmtbuilder, Crypto::UnsignedBigInteger const& value)
-{
- return Formatter<StringView>::format(fmtbuilder, TRY(value.to_base(10)));
-}
diff --git a/Libraries/LibCrypto/BigInt/UnsignedBigInteger.h b/Libraries/LibCrypto/BigInt/UnsignedBigInteger.h
deleted file mode 100644
index f717ece2096..00000000000
--- a/Libraries/LibCrypto/BigInt/UnsignedBigInteger.h
+++ /dev/null
@@ -1,151 +0,0 @@
-/*
- * Copyright (c) 2020, Itamar S. <[email protected]>
- * Copyright (c) 2022, the SerenityOS developers.
- * Copyright (c) 2022, David Tuin <[email protected]>
- * Copyright (c) 2025, Altomani Gianluca <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/String.h>
-#include <AK/Utf16String.h>
-#include <AK/Utf16View.h>
-#include <AK/kmalloc.h>
-#include <LibCrypto/BigInt/TommathForward.h>
-
-namespace Crypto {
-
-struct UnsignedDivisionResult;
-
-class UnsignedBigInteger {
-public:
- AK_ALLOC_WITH_KMALLOC;
-
- template<Integral T>
- UnsignedBigInteger(T value)
- : UnsignedBigInteger(static_cast<u64>(value))
- {
- }
- UnsignedBigInteger(ReadonlyBytes);
-
- explicit UnsignedBigInteger(Vector<u32> const& words);
- explicit UnsignedBigInteger(double value);
- explicit UnsignedBigInteger(u64 value);
-
- UnsignedBigInteger(UnsignedBigInteger const&);
- UnsignedBigInteger(UnsignedBigInteger&&);
-
- UnsignedBigInteger& operator=(UnsignedBigInteger const&);
- UnsignedBigInteger& operator=(UnsignedBigInteger&&);
-
- UnsignedBigInteger();
- ~UnsignedBigInteger();
-
- void clear_sensitive_data();
-
- [[nodiscard]] static UnsignedBigInteger import_data(ReadonlyBytes data) { return UnsignedBigInteger(data); }
-
- // Exports in big-endian (msb stored first), trimmed (no leading zeros) format
- [[nodiscard]] Bytes export_data(Bytes) const;
-
- [[nodiscard]] static ErrorOr<UnsignedBigInteger> from_base(u16 N, StringView str);
- [[nodiscard]] static ErrorOr<UnsignedBigInteger> from_base(u16 N, Utf16View str);
- [[nodiscard]] ErrorOr<String> to_base(u16 N) const;
- [[nodiscard]] ErrorOr<Utf16String> to_base_utf16(u16 N) const;
-
- [[nodiscard]] size_t count_digits_in_base(u16 base) const;
-
- [[nodiscard]] u64 to_u64() const;
-
- enum class RoundingMode {
- IEEERoundAndTiesToEvenMantissa,
- RoundTowardZero,
- // “the Number value for x”, https://tc39.es/ecma262/#number-value-for
- ECMAScriptNumberValueFor = IEEERoundAndTiesToEvenMantissa,
- };
-
- [[nodiscard]] double to_double(RoundingMode rounding_mode = RoundingMode::IEEERoundAndTiesToEvenMantissa) const;
-
- [[nodiscard]] Vector<u32> words() const;
-
- void set_to_0();
- void set_to(u64 other);
- void set_to(UnsignedBigInteger const& other);
-
- [[nodiscard]] bool is_zero() const;
- [[nodiscard]] bool is_odd() const;
-
- [[nodiscard]] size_t byte_length() const;
- [[nodiscard]] size_t external_memory_size() const { return m_mp.alloc * sizeof(mp_digit); }
-
- size_t one_based_index_of_highest_set_bit() const;
-
- [[nodiscard]] UnsignedBigInteger plus(UnsignedBigInteger const& other) const;
- [[nodiscard]] ErrorOr<UnsignedBigInteger> minus(UnsignedBigInteger const& other) const;
- [[nodiscard]] UnsignedBigInteger bitwise_or(UnsignedBigInteger const& other) const;
- [[nodiscard]] UnsignedBigInteger bitwise_and(UnsignedBigInteger const& other) const;
- [[nodiscard]] UnsignedBigInteger bitwise_xor(UnsignedBigInteger const& other) const;
- [[nodiscard]] ErrorOr<UnsignedBigInteger> bitwise_not_fill_to_one_based_index(size_t) const;
- [[nodiscard]] ErrorOr<UnsignedBigInteger> shift_left(size_t num_bits) const;
- [[nodiscard]] UnsignedBigInteger shift_right(size_t num_bits) const;
- [[nodiscard]] UnsignedBigInteger multiplied_by(UnsignedBigInteger const& other) const;
- [[nodiscard]] UnsignedDivisionResult divided_by(UnsignedBigInteger const& divisor) const;
- [[nodiscard]] UnsignedBigInteger quotient(UnsignedBigInteger const& divisor) const;
- [[nodiscard]] UnsignedBigInteger remainder(UnsignedBigInteger const& divisor) const;
- [[nodiscard]] UnsignedBigInteger pow(u32 exponent) const;
- [[nodiscard]] UnsignedBigInteger gcd(UnsignedBigInteger const& other) const;
- [[nodiscard]] UnsignedBigInteger lcm(UnsignedBigInteger const& other) const;
-
- [[nodiscard]] u32 hash() const;
-
- [[nodiscard]] bool operator==(UnsignedBigInteger const& other) const;
- [[nodiscard]] bool operator!=(UnsignedBigInteger const& other) const;
- [[nodiscard]] bool operator<(UnsignedBigInteger const& other) const;
- [[nodiscard]] bool operator<=(UnsignedBigInteger const& other) const;
- [[nodiscard]] bool operator>(UnsignedBigInteger const& other) const;
- [[nodiscard]] bool operator>=(UnsignedBigInteger const& other) const;
-
- enum class CompareResult {
- DoubleEqualsBigInt,
- DoubleLessThanBigInt,
- DoubleGreaterThanBigInt
- };
-
- [[nodiscard]] CompareResult compare_to_double(double) const;
-
-private:
- mp_int m_mp;
- mutable Optional<u32> m_hash {};
-};
-
-struct UnsignedDivisionResult {
- Crypto::UnsignedBigInteger quotient;
- Crypto::UnsignedBigInteger remainder;
-};
-
-}
-
-template<>
-struct AK::Formatter<Crypto::UnsignedBigInteger> : Formatter<StringView> {
- ErrorOr<void> format(FormatBuilder&, Crypto::UnsignedBigInteger const&);
-};
-
-inline Crypto::UnsignedBigInteger operator""_bigint(char const* string, size_t length)
-{
- return MUST(Crypto::UnsignedBigInteger::from_base(10, StringView { string, length }));
-}
-
-inline Crypto::UnsignedBigInteger operator""_bigint(unsigned long long value)
-{
- return Crypto::UnsignedBigInteger { static_cast<u64>(value) };
-}
-
-inline Crypto::UnsignedBigInteger operator""_bigint(long double value)
-{
- VERIFY(value >= 0);
- VERIFY(value < static_cast<long double>(NumericLimits<double>::max()));
-
- return Crypto::UnsignedBigInteger { static_cast<double>(value) };
-}
diff --git a/Libraries/LibCrypto/CMakeLists.txt b/Libraries/LibCrypto/CMakeLists.txt
index 0960bb799eb..41f72565376 100644
--- a/Libraries/LibCrypto/CMakeLists.txt
+++ b/Libraries/LibCrypto/CMakeLists.txt
@@ -7,7 +7,6 @@ set(SOURCES
ASN1/DER.cpp
Authentication/HMAC.cpp
Authentication/KMAC.cpp
- BigInt/UnsignedBigInteger.cpp
Cipher/AES.cpp
Cipher/ChaCha.cpp
Curves/EdwardsCurve.cpp
@@ -27,5 +26,4 @@ set(SOURCES
ladybird_lib(LibCrypto crypto)
-target_link_libraries(LibCrypto PRIVATE PkgConfig::libtommath)
target_link_libraries(LibCrypto PUBLIC OpenSSL::Crypto)
diff --git a/Meta/CMake/check_for_dependencies.cmake b/Meta/CMake/check_for_dependencies.cmake
index dff154e2c17..17ebeca87cd 100644
--- a/Meta/CMake/check_for_dependencies.cmake
+++ b/Meta/CMake/check_for_dependencies.cmake
@@ -77,7 +77,6 @@ find_package(Threads REQUIRED)
find_package(ZLIB REQUIRED)
pkg_check_modules(LIBPSL REQUIRED IMPORTED_TARGET libpsl)
-pkg_check_modules(libtommath REQUIRED IMPORTED_TARGET libtommath)
find_package(unofficial-angle CONFIG)
if(unofficial-angle_FOUND)
diff --git a/Meta/CMake/flatpak/org.ladybird.Ladybird.json b/Meta/CMake/flatpak/org.ladybird.Ladybird.json
index f2e11f9cba9..8ca9d683023 100644
--- a/Meta/CMake/flatpak/org.ladybird.Ladybird.json
+++ b/Meta/CMake/flatpak/org.ladybird.Ladybird.json
@@ -443,23 +443,6 @@
"--libdir=/app/lib"
]
},
- {
- "name": "libtommath",
- "buildsystem": "cmake-ninja",
- "sources": [
- {
- "type": "git",
- "url": "https://github.com/libtom/libtommath.git",
- "tag": "v1.3.0"
- }
- ],
- "config-opts": [
- "-DCMAKE_BUILD_TYPE=Release",
- "-DCMAKE_PREFIX_PATH=/app",
- "-DCMAKE_INSTALL_LIBDIR=lib",
- "-DBUILD_SHARED_LIBS=ON"
- ]
- },
{
"name": "fast-float",
"buildsystem": "cmake-ninja",
diff --git a/Meta/CMake/vcpkg/overlay-ports/libtommath/bcrypt.patch b/Meta/CMake/vcpkg/overlay-ports/libtommath/bcrypt.patch
deleted file mode 100644
index 973c7e17155..00000000000
--- a/Meta/CMake/vcpkg/overlay-ports/libtommath/bcrypt.patch
+++ /dev/null
@@ -1,67 +0,0 @@
-diff --git a/CMakeLists.txt b/CMakeLists.txt
---- a/CMakeLists.txt
-+++ b/CMakeLists.txt
-@@ -22,8 +22,10 @@
- #-----------------------------------------------------------------------------
- include(GNUInstallDirs)
- include(CheckIPOSupported)
- include(CMakePackageConfigHelpers)
-+include(CMakePushCheckState)
-+include(CheckSymbolExists)
- # default is "No tests"
- option(BUILD_TESTING "" OFF)
- include(CTest)
- include(sources.cmake)
-@@ -118,8 +120,19 @@
- target_link_options(${PROJECT_NAME} BEFORE PRIVATE
- ${LTM_LD_FLAGS}
- )
-
-+if(MSVC)
-+ cmake_push_check_state()
-+ set(CMAKE_REQUIRED_LIBRARIES bcrypt)
-+ check_symbol_exists(BCryptGenRandom "Windows.h;bcrypt.h" BCRYPT_AVAILABLE)
-+ cmake_pop_check_state()
-+ if(BCRYPT_AVAILABLE)
-+ target_compile_definitions(${PROJECT_NAME} PRIVATE LTM_WIN32_BCRYPT)
-+ target_link_libraries(${PROJECT_NAME} PRIVATE bcrypt)
-+ endif()
-+endif()
-+
- set(PUBLIC_HEADERS tommath.h)
- set(C89 False CACHE BOOL "(Usually maintained automatically) Enable when the library is in c89 mode to package the correct header files on install")
- if(C89)
- list(APPEND PUBLIC_HEADERS tommath_c89.h)
-diff --git a/bn_s_mp_rand_platform.c b/bn_s_mp_rand_platform.c
---- a/bn_s_mp_rand_platform.c
-+++ b/bn_s_mp_rand_platform.c
-@@ -28,8 +28,19 @@
- #endif
-
- #define WIN32_LEAN_AND_MEAN
- #include <windows.h>
-+
-+#ifdef LTM_WIN32_BCRYPT
-+#include <bcrypt.h>
-+#pragma comment(lib, "bcrypt")
-+
-+static mp_err s_read_wincsp(void *p, size_t n)
-+{
-+ return BCRYPT_SUCCESS(BCryptGenRandom(NULL, (PUCHAR)p, (ULONG)n,
-+ BCRYPT_USE_SYSTEM_PREFERRED_RNG)) ? MP_OKAY : MP_ERR;
-+}
-+#else
- #include <wincrypt.h>
-
- static mp_err s_read_wincsp(void *p, size_t n)
- {
-@@ -45,8 +56,9 @@
- hProv = h;
- }
- return CryptGenRandom(hProv, (DWORD)n, (BYTE *)p) == TRUE ? MP_OKAY : MP_ERR;
- }
-+#endif
- #endif /* WIN32 */
-
- #if !defined(BN_S_READ_WINCSP_C) && defined(__linux__) && defined(__GLIBC_PREREQ)
- #if __GLIBC_PREREQ(2, 25)
diff --git a/Meta/CMake/vcpkg/overlay-ports/libtommath/has-set-double.patch b/Meta/CMake/vcpkg/overlay-ports/libtommath/has-set-double.patch
deleted file mode 100644
index 795aace0ba8..00000000000
--- a/Meta/CMake/vcpkg/overlay-ports/libtommath/has-set-double.patch
+++ /dev/null
@@ -1,14 +0,0 @@
-diff --git a/bn_mp_set_double.c b/bn_mp_set_double.c
---- a/bn_mp_set_double.c
-+++ b/bn_mp_set_double.c
-@@ -2,9 +2,9 @@
- #ifdef BN_MP_SET_DOUBLE_C
- /* LibTomMath, multiple-precision integer library -- Tom St Denis */
- /* SPDX-License-Identifier: Unlicense */
-
--#if defined(__STDC_IEC_559__) || defined(__GCC_IEC_559)
-+#if defined(__STDC_IEC_559__) || defined(__GCC_IEC_559) || defined(_MSC_VER)
- mp_err mp_set_double(mp_int *a, double b)
- {
- uint64_t frac;
- int exp;
diff --git a/Meta/CMake/vcpkg/overlay-ports/libtommath/import-lib.patch b/Meta/CMake/vcpkg/overlay-ports/libtommath/import-lib.patch
deleted file mode 100644
index e767fbaddd4..00000000000
--- a/Meta/CMake/vcpkg/overlay-ports/libtommath/import-lib.patch
+++ /dev/null
@@ -1,12 +0,0 @@
-diff --git a/sources.cmake b/sources.cmake
---- a/sources.cmake
-+++ b/sources.cmake
-@@ -171,4 +171,8 @@
- tommath_cutoffs.h
- tommath_private.h
- tommath_superclass.h
- )
-+
-+if(WIN32)
-+ list(APPEND SOURCES tommath.def)
-+endif()
diff --git a/Meta/CMake/vcpkg/overlay-ports/libtommath/msvc-dce.patch b/Meta/CMake/vcpkg/overlay-ports/libtommath/msvc-dce.patch
deleted file mode 100644
index ccce1143add..00000000000
--- a/Meta/CMake/vcpkg/overlay-ports/libtommath/msvc-dce.patch
+++ /dev/null
@@ -1,21 +0,0 @@
-diff --git a/bn_s_mp_rand_platform.c b/bn_s_mp_rand_platform.c
---- a/bn_s_mp_rand_platform.c
-+++ b/bn_s_mp_rand_platform.c
-@@ -136,13 +136,17 @@
-
- mp_err s_mp_rand_platform(void *p, size_t n)
- {
- mp_err err = MP_ERR;
-+ #ifndef _MSC_VER
- if ((err != MP_OKAY) && MP_HAS(S_READ_ARC4RANDOM)) err = s_read_arc4random(p, n);
-+ #endif
- if ((err != MP_OKAY) && MP_HAS(S_READ_WINCSP)) err = s_read_wincsp(p, n);
-+ #ifndef _MSC_VER
- if ((err != MP_OKAY) && MP_HAS(S_READ_GETRANDOM)) err = s_read_getrandom(p, n);
- if ((err != MP_OKAY) && MP_HAS(S_READ_URANDOM)) err = s_read_urandom(p, n);
- if ((err != MP_OKAY) && MP_HAS(S_READ_LTM_RNG)) err = s_read_ltm_rng(p, n);
-+ #endif
- return err;
- }
-
- #endif
diff --git a/Meta/CMake/vcpkg/overlay-ports/libtommath/pkgconfig.diff b/Meta/CMake/vcpkg/overlay-ports/libtommath/pkgconfig.diff
deleted file mode 100644
index b735d684416..00000000000
--- a/Meta/CMake/vcpkg/overlay-ports/libtommath/pkgconfig.diff
+++ /dev/null
@@ -1,13 +0,0 @@
-diff --git a/CMakeLists.txt b/CMakeLists.txt
-index 0b84e79..6b5c73c 100644
---- a/CMakeLists.txt
-+++ b/CMakeLists.txt
-@@ -168,7 +168,7 @@ install(TARGETS ${PROJECT_NAME}
- )
-
- # Install libtommath.pc for pkg-config if we build a shared library
--if(BUILD_SHARED_LIBS)
-+if(1)
- # Let the user override the default directory of the pkg-config file (usually this shouldn't be required to be changed)
- set(CMAKE_INSTALL_PKGCONFIGDIR "${CMAKE_INSTALL_LIBDIR}/pkgconfig" CACHE PATH "Folder where to install .pc files")
-
diff --git a/Meta/CMake/vcpkg/overlay-ports/libtommath/portfile.cmake b/Meta/CMake/vcpkg/overlay-ports/libtommath/portfile.cmake
deleted file mode 100644
index 2b2db5a36a8..00000000000
--- a/Meta/CMake/vcpkg/overlay-ports/libtommath/portfile.cmake
+++ /dev/null
@@ -1,27 +0,0 @@
-vcpkg_from_github(
- OUT_SOURCE_PATH SOURCE_PATH
- REPO libtom/libtommath
- REF "v${VERSION}"
- SHA512 3dbd7053a670afa563a069a9785f1aa4cab14a210bcd05d8fc7db25bd3dcce36b10a3f4f54ca92d75a694f891226f01bdf6ac15bacafeb93a8be6b04c579beb3
- HEAD_REF develop
- PATCHES
- pkgconfig.diff
- bcrypt.patch
- import-lib.patch
- has-set-double.patch # Remove in next release.
- msvc-dce.patch # This is a won't fix, see https://github.com/libtom/libtommath/blob/develop/s_mp_rand_platform.c#L120-L138
- stdc-iec-559.patch # Define __STDC_IEC_559__ like glibc and musl do.
-)
-
-vcpkg_cmake_configure(
- SOURCE_PATH "${SOURCE_PATH}"
-)
-vcpkg_cmake_install()
-vcpkg_copy_pdbs()
-vcpkg_cmake_config_fixup(CONFIG_PATH "lib/cmake/${PORT}")
-vcpkg_fixup_pkgconfig()
-vcpkg_install_copyright(FILE_LIST "${SOURCE_PATH}/LICENSE")
-
-file(INSTALL "${CMAKE_CURRENT_LIST_DIR}/usage" DESTINATION "${CURRENT_PACKAGES_DIR}/share/${PORT}")
-file(REMOVE_RECURSE "${CURRENT_PACKAGES_DIR}/debug/include")
-file(REMOVE_RECURSE "${CURRENT_PACKAGES_DIR}/debug/share")
diff --git a/Meta/CMake/vcpkg/overlay-ports/libtommath/stdc-iec-559.patch b/Meta/CMake/vcpkg/overlay-ports/libtommath/stdc-iec-559.patch
deleted file mode 100644
index 4441cc90fcf..00000000000
--- a/Meta/CMake/vcpkg/overlay-ports/libtommath/stdc-iec-559.patch
+++ /dev/null
@@ -1,20 +0,0 @@
-diff --git a/bn_mp_set_double.c b/bn_mp_set_double.c
---- a/bn_mp_set_double.c
-+++ b/bn_mp_set_double.c
-@@ -3,6 +3,16 @@
- /* LibTomMath, multiple-precision integer library -- Tom St Denis */
- /* SPDX-License-Identifier: Unlicense */
-
-+#ifdef __GCC_IEC_559
-+# if __GCC_IEC_559 > 0
-+# define __STDC_IEC_559__ 1
-+# define __STDC_IEC_60559_BFP__ 201404L
-+# endif
-+#else
-+# define __STDC_IEC_559__ 1
-+# define __STDC_IEC_60559_BFP__ 201404L
-+#endif
-+
- #if defined(__STDC_IEC_559__) || defined(__GCC_IEC_559) || defined(_MSC_VER)
- mp_err mp_set_double(mp_int *a, double b)
- {
diff --git a/Meta/CMake/vcpkg/overlay-ports/libtommath/usage b/Meta/CMake/vcpkg/overlay-ports/libtommath/usage
deleted file mode 100644
index 657d5e0c71f..00000000000
--- a/Meta/CMake/vcpkg/overlay-ports/libtommath/usage
+++ /dev/null
@@ -1,9 +0,0 @@
-libtommath provides CMake targets:
-
- find_package(libtommath CONFIG REQUIRED)
- target_link_libraries(main PRIVATE libtommath)
-
-libtommath provides pkg-config modules:
-
- # public domain library for manipulating large integer numbers
- libtommath
diff --git a/Meta/CMake/vcpkg/overlay-ports/libtommath/vcpkg.json b/Meta/CMake/vcpkg/overlay-ports/libtommath/vcpkg.json
deleted file mode 100644
index c2c1434c8c5..00000000000
--- a/Meta/CMake/vcpkg/overlay-ports/libtommath/vcpkg.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "name": "libtommath",
- "version": "1.3.0",
- "port-version": 3,
- "description": "LibTomMath is a free open source portable number theoretic multiple-precision integer library written entirely in C.",
- "homepage": "https://www.libtom.net/LibTomMath/",
- "dependencies": [
- {
- "name": "vcpkg-cmake",
- "host": true
- },
- {
- "name": "vcpkg-cmake-config",
- "host": true
- }
- ]
-}
diff --git a/Tests/LibCrypto/CMakeLists.txt b/Tests/LibCrypto/CMakeLists.txt
index 57e492f8fec..169bc02f5f4 100644
--- a/Tests/LibCrypto/CMakeLists.txt
+++ b/Tests/LibCrypto/CMakeLists.txt
@@ -4,7 +4,6 @@ set(TEST_SOURCES
TestAES.cpp
TestArgon2.cpp
TestASN1.cpp
- TestBigInteger.cpp
TestCurves.cpp
TestEd25519.cpp
TestEd448.cpp
diff --git a/Tests/LibCrypto/TestBigInteger.cpp b/Tests/LibCrypto/TestBigInteger.cpp
deleted file mode 100644
index c12f445bf13..00000000000
--- a/Tests/LibCrypto/TestBigInteger.cpp
+++ /dev/null
@@ -1,619 +0,0 @@
-/*
- * Copyright (c) 2021, Peter Bocan <[email protected]>
- * Copyright (c) 2025, Manuel Zahariev <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/Tuple.h>
-#include <LibCrypto/BigInt/UnsignedBigInteger.h>
-#include <LibTest/TestCase.h>
-
-#include <math.h>
-
-static Crypto::UnsignedBigInteger bigint_fibonacci(size_t n)
-{
- Crypto::UnsignedBigInteger num1(0);
- Crypto::UnsignedBigInteger num2(1);
- for (size_t i = 0; i < n; ++i) {
- Crypto::UnsignedBigInteger t = num1.plus(num2);
- num2 = num1;
- num1 = t;
- }
- return num1;
-}
-
-TEST_CASE(test_bigint_fib500)
-{
- Vector<u32> result {
- 315178285, 505575602, 1883328078, 125027121, 3649625763,
- 347570207, 74535262, 3832543808, 2472133297, 1600064941, 65273441
- };
-
- EXPECT_EQ(bigint_fibonacci(500).words(), result);
-}
-
-TEST_CASE(test_unsigned_bigint_clear_sensitive_data)
-{
- auto value = MUST(Crypto::UnsignedBigInteger::from_base(16, "fedcba98765432100123456789abcdef"sv));
- (void)value.hash();
-
- value.clear_sensitive_data();
-
- EXPECT(value.is_zero());
- EXPECT_EQ(value.hash(), Crypto::UnsignedBigInteger(0).hash());
-}
-
-TEST_CASE(test_unsigned_bigint_addition_initialization)
-{
- Crypto::UnsignedBigInteger num1;
- Crypto::UnsignedBigInteger num2(70);
- Crypto::UnsignedBigInteger num3 = num1.plus(num2);
- bool pass = (num3 == num2);
- pass &= (num1 == Crypto::UnsignedBigInteger(0));
- EXPECT(pass);
-}
-
-TEST_CASE(test_unsigned_bigint_addition_borrow_with_zero)
-{
- Crypto::UnsignedBigInteger num1({ UINT32_MAX - 3, UINT32_MAX });
- Crypto::UnsignedBigInteger num2({ UINT32_MAX - 2, 0 });
- Vector<u32> expected_result { 4294967289, 0, 1 };
- EXPECT_EQ(num1.plus(num2).words(), expected_result);
-}
-
-TEST_CASE(test_unsigned_bigint_simple_subtraction)
-{
- Crypto::UnsignedBigInteger num1(80);
- Crypto::UnsignedBigInteger num2(70);
-
- EXPECT_EQ(TRY_OR_FAIL(num1.minus(num2)), Crypto::UnsignedBigInteger(10));
-}
-
-TEST_CASE(test_unsigned_bigint_simple_subtraction_invalid)
-{
- Crypto::UnsignedBigInteger num1(50);
- Crypto::UnsignedBigInteger num2(70);
-
- EXPECT(num1.minus(num2).is_error());
-}
-
-TEST_CASE(test_unsigned_bigint_simple_subtraction_with_borrow)
-{
- Crypto::UnsignedBigInteger num1(UINT32_MAX);
- Crypto::UnsignedBigInteger num2(1);
- Crypto::UnsignedBigInteger num3 = num1.plus(num2);
- Crypto::UnsignedBigInteger result = TRY_OR_FAIL(num3.minus(num2));
- EXPECT_EQ(result, num1);
-}
-
-TEST_CASE(test_unsigned_bigint_subtraction_with_large_numbers)
-{
- Crypto::UnsignedBigInteger num1 = bigint_fibonacci(343);
- Crypto::UnsignedBigInteger num2 = bigint_fibonacci(218);
- Crypto::UnsignedBigInteger result = TRY_OR_FAIL(num1.minus(num2));
-
- Vector<u32> expected_result {
- 811430588, 2958904896, 1130908877, 2830569969, 3243275482,
- 3047460725, 774025231, 7990
- };
- EXPECT_EQ(result.plus(num2), num1);
- EXPECT_EQ(result.words(), expected_result);
-}
-
-TEST_CASE(test_unsigned_bigint_subtraction_with_large_numbers2)
-{
- Crypto::UnsignedBigInteger num1(Vector<u32> { 1483061863, 446680044, 1123294122, 191895498, 3347106536, 16, 0, 0, 0 });
- Crypto::UnsignedBigInteger num2(Vector<u32> { 4196414175, 1117247942, 1123294122, 191895498, 3347106536, 16 });
- ErrorOr<Crypto::UnsignedBigInteger> result = num1.minus(num2);
- // this test only verifies that we don't crash on an assertion
- (void)result;
-}
-
-TEST_CASE(test_unsigned_bigint_subtraction_regression_1)
-{
- auto num = TRY_OR_FAIL(Crypto::UnsignedBigInteger { 1 }.shift_left(256));
- Vector<u32> expected_result {
- 4294967295, 4294967295, 4294967295, 4294967295, 4294967295,
- 4294967295, 4294967295, 4294967295
- };
- EXPECT_EQ(TRY_OR_FAIL(num.minus(1)).words(), expected_result);
-}
-
-TEST_CASE(test_unsigned_bigint_simple_multiplication)
-{
- Crypto::UnsignedBigInteger num1(8);
- Crypto::UnsignedBigInteger num2(251);
- Crypto::UnsignedBigInteger result = num1.multiplied_by(num2);
- EXPECT_EQ(result.words(), Vector<u32> { 2008 });
-}
-
-TEST_CASE(test_unsigned_bigint_multiplication_with_big_numbers1)
-{
- Crypto::UnsignedBigInteger num1 = bigint_fibonacci(200);
- Crypto::UnsignedBigInteger num2(12345678);
- Crypto::UnsignedBigInteger result = num1.multiplied_by(num2);
- Vector<u32> expected_result { 669961318, 143970113, 4028714974, 3164551305, 1589380278, 2 };
- EXPECT_EQ(result.words(), expected_result);
-}
-
-TEST_CASE(test_unsigned_bigint_multiplication_with_big_numbers2)
-{
- Crypto::UnsignedBigInteger num1 = bigint_fibonacci(200);
- Crypto::UnsignedBigInteger num2 = bigint_fibonacci(341);
- Crypto::UnsignedBigInteger result = num1.multiplied_by(num2);
- Vector<u32> expected_result {
- 3017415433, 2741793511, 1957755698, 3731653885, 3154681877,
- 785762127, 3200178098, 4260616581, 529754471, 3632684436,
- 1073347813, 2516430
- };
- EXPECT_EQ(result.words(), expected_result);
-}
-
-TEST_CASE(test_unsigned_bigint_simple_division)
-{
- Crypto::UnsignedBigInteger num1(27194);
- Crypto::UnsignedBigInteger num2(251);
- auto result = num1.divided_by(num2);
- Crypto::UnsignedDivisionResult expected = { Crypto::UnsignedBigInteger(108), Crypto::UnsignedBigInteger(86) };
- EXPECT_EQ(result.quotient, expected.quotient);
- EXPECT_EQ(result.remainder, expected.remainder);
-}
-
-TEST_CASE(test_unsigned_bigint_division_with_big_numbers)
-{
- Crypto::UnsignedBigInteger num1 = bigint_fibonacci(386);
- Crypto::UnsignedBigInteger num2 = bigint_fibonacci(238);
- auto result = num1.divided_by(num2);
- Crypto::UnsignedDivisionResult expected = {
- Crypto::UnsignedBigInteger(Vector<u32> { 2300984486, 2637503534, 2022805584, 107 }),
- Crypto::UnsignedBigInteger(Vector<u32> { 1483061863, 446680044, 1123294122, 191895498, 3347106536, 16, 0, 0, 0 })
- };
- EXPECT_EQ(result.quotient, expected.quotient);
- EXPECT_EQ(result.remainder, expected.remainder);
-}
-
-TEST_CASE(test_unsigned_bigint_division_combined_test)
-{
- auto num1 = bigint_fibonacci(497);
- auto num2 = bigint_fibonacci(238);
- auto div_result = num1.divided_by(num2);
- EXPECT_EQ(div_result.quotient.multiplied_by(num2).plus(div_result.remainder), num1);
-}
-
-TEST_CASE(test_unsigned_bigint_base10_from_string)
-{
- auto result = TRY_OR_FAIL(Crypto::UnsignedBigInteger::from_base(10, "57195071295721390579057195715793"sv));
- Vector<u32> expected_result { 3806301393, 954919431, 3879607298, 721 };
- EXPECT_EQ(result.words(), expected_result);
-
- Vector<StringView> invalid_base10_number_strings { "1A"sv, "1:"sv, "Z1"sv, "1/"sv };
- for (auto invalid_base10_number_string : invalid_base10_number_strings)
- EXPECT_EQ(Crypto::UnsignedBigInteger::from_base(10, invalid_base10_number_string).is_error(), true);
-}
-
-TEST_CASE(test_bigint_from_utf16_string)
-{
- auto unsigned_result = TRY_OR_FAIL(Crypto::UnsignedBigInteger::from_base(16, u"ffffffffffff"sv));
- EXPECT_EQ(MUST(unsigned_result.to_base(16)), "ffffffffffff");
-
- EXPECT(Crypto::UnsignedBigInteger::from_base(10, u"12\u00a0"sv).is_error());
-}
-
-TEST_CASE(test_unsigned_bigint_base10_to_string)
-{
- auto bigint = Crypto::UnsignedBigInteger {
- Vector<u32> { 3806301393, 954919431, 3879607298, 721 }
- };
- auto result = MUST(bigint.to_base(10));
- EXPECT_EQ(result, "57195071295721390579057195715793");
-}
-
-TEST_CASE(test_unsigned_bigint_count_digits)
-{
- constexpr auto count_digits = [](u64 number, u16 base) {
- u8 digits = 0;
-
- do {
- number /= base;
- ++digits;
- } while (number > 0);
-
- return digits;
- };
-
- for (auto base : to_array<u16>({ 2, 8, 10, 16 })) {
- for (auto test : to_array<u64>({ 0, 9, 10, 19, 99, 100, 999, 1000, 9999, 10000, 99999, 10000000000, 99999999999 })) {
- auto bigint = Crypto::UnsignedBigInteger { test };
-
- auto result = bigint.count_digits_in_base(base);
- auto expected = count_digits(test, base);
-
- EXPECT_EQ(result, expected);
- }
- }
-}
-
-static size_t count_leading_zeros(Bytes data)
-{
- auto leading_zeros = 0u;
- for (auto i = 0u; i < data.size(); ++i) {
- if (data[i] == 0u)
- leading_zeros++;
- else
- break;
- }
- return leading_zeros;
-}
-
-TEST_CASE(test_bigint_import_big_endian_decode_encode_roundtrip)
-{
- u8 random_bytes[128];
- u8 target_buffer[128];
- fill_with_random(random_bytes);
- auto encoded = Crypto::UnsignedBigInteger::import_data(random_bytes);
- auto result = encoded.export_data(target_buffer);
- EXPECT_EQ(result.size(), sizeof(target_buffer) - count_leading_zeros(random_bytes));
- EXPECT(Bytes { random_bytes }.ends_with(result));
-}
-
-TEST_CASE(test_bigint_import_big_endian_encode_decode_roundtrip)
-{
- u8 target_buffer[128];
- auto encoded = "12345678901234567890"_bigint;
- auto result = encoded.export_data({ target_buffer, 128 });
- auto decoded = Crypto::UnsignedBigInteger::import_data(result);
- EXPECT_EQ(encoded, decoded);
-}
-
-TEST_CASE(test_bigint_big_endian_import)
-{
- auto number = Crypto::UnsignedBigInteger::import_data("hello"sv.bytes());
- EXPECT_EQ(number, "448378203247"_bigint);
-}
-
-TEST_CASE(test_bigint_big_endian_export)
-{
- auto number = "448378203247"_bigint;
- char exported[8] {};
- auto result = number.export_data({ exported, 8 });
- EXPECT_EQ(result.size(), 5u);
- EXPECT(memcmp(exported, "hello", 5) == 0);
-}
-
-TEST_CASE(test_bigint_one_based_index_of_highest_set_bit)
-{
- EXPECT_EQ("0"_bigint.one_based_index_of_highest_set_bit(), 0u);
- EXPECT_EQ("1"_bigint.one_based_index_of_highest_set_bit(), 1u);
- EXPECT_EQ("7"_bigint.one_based_index_of_highest_set_bit(), 3u);
- EXPECT_EQ("4294967296"_bigint.one_based_index_of_highest_set_bit(), 33u);
-}
-
-TEST_CASE(test_signed_bigint_bitwise_not_fill_to_one_based_index)
-{
- EXPECT_EQ(TRY_OR_FAIL("0"_bigint.bitwise_not_fill_to_one_based_index(0)), "0"_bigint);
- EXPECT_EQ(TRY_OR_FAIL("0"_bigint.bitwise_not_fill_to_one_based_index(1)), "1"_bigint);
- EXPECT_EQ(TRY_OR_FAIL("0"_bigint.bitwise_not_fill_to_one_based_index(2)), "3"_bigint);
- EXPECT_EQ(TRY_OR_FAIL("0"_bigint.bitwise_not_fill_to_one_based_index(4)), "15"_bigint);
- EXPECT_EQ(TRY_OR_FAIL("0"_bigint.bitwise_not_fill_to_one_based_index(32)), "4294967295"_bigint);
- EXPECT_EQ(TRY_OR_FAIL("0"_bigint.bitwise_not_fill_to_one_based_index(33)), "8589934591"_bigint);
-}
-
-TEST_CASE(test_bigint_bitwise_or)
-{
- auto num1 = "1234567"_bigint;
- auto num2 = "1234567"_bigint;
- EXPECT_EQ(num1.bitwise_or(num2), num1);
-}
-
-TEST_CASE(test_bigint_bitwise_or_different_lengths)
-{
- auto num1 = "1234567"_bigint;
- auto num2 = "123456789012345678901234567890"_bigint;
- auto expected = "123456789012345678901234622167"_bigint;
- auto result = num1.bitwise_or(num2);
- EXPECT_EQ(result, expected);
-}
-
-TEST_CASE(test_bigint_bitwise_and)
-{
- auto num1 = "1234567"_bigint;
- auto num2 = "1234561"_bigint;
- EXPECT_EQ(num1.bitwise_and(num2), "1234561"_bigint);
-}
-
-TEST_CASE(test_bigint_bitwise_and_different_lengths)
-{
- auto num1 = "1234567"_bigint;
- auto num2 = "123456789012345678901234567890"_bigint;
- EXPECT_EQ(num1.bitwise_and(num2), "1180290"_bigint);
-}
-
-TEST_CASE(test_bigint_bitwise_xor)
-{
- auto num1 = "1234567"_bigint;
- auto num2 = "1234561"_bigint;
- EXPECT_EQ(num1.bitwise_xor(num2), 6);
-}
-
-TEST_CASE(test_bigint_bitwise_xor_different_lengths)
-{
- auto num1 = "1234567"_bigint;
- auto num2 = "123456789012345678901234567890"_bigint;
- EXPECT_EQ(num1.bitwise_xor(num2), "123456789012345678901233441877"_bigint);
-}
-
-TEST_CASE(test_bigint_shift_left)
-{
- Crypto::UnsignedBigInteger const num(Vector<u32> { 0x22222222, 0xffffffff });
-
- size_t const tests = 8;
- AK::Tuple<size_t, Vector<u32>> results[] = {
- { 0, { 0x22222222, 0xffffffff } },
- { 8, { 0x22222200, 0xffffff22, 0x000000ff } },
- { 16, { 0x22220000, 0xffff2222, 0x0000ffff } },
- { 32, { 0x00000000, 0x22222222, 0xffffffff } },
- { 36, { 0x00000000, 0x22222220, 0xfffffff2, 0x0000000f } },
- { 40, { 0x00000000, 0x22222200, 0xffffff22, 0x000000ff } },
- { 64, { 0x00000000, 0x00000000, 0x22222222, 0xffffffff } },
- { 68, { 0x00000000, 0x00000000, 0x22222220, 0xfffffff2, 0x0000000f } },
- };
-
- for (size_t i = 0; i < tests; ++i)
- EXPECT_EQ(TRY_OR_FAIL(num.shift_left(results[i].get<0>())).words(), results[i].get<1>());
-}
-
-TEST_CASE(test_bigint_shift_right)
-{
- Crypto::UnsignedBigInteger const num1(Vector<u32> { 0x100, 0x20, 0x4, 0x2, 0x1 });
-
- size_t const tests1 = 11;
- AK::Tuple<size_t, Vector<u32>> results1[] = {
- { 8, { 0x20000001, 0x04000000, 0x02000000, 0x01000000 } },
- { 16, { 0x00200000, 0x00040000, 0x00020000, 0x00010000 } }, // shift by exact number of words
- { 32, { 0x00000020, 0x00000004, 0x00000002, 0x00000001 } }, // shift by exact number of words
- { 36, { 0x40000002, 0x20000000, 0x10000000 } },
- { 64, { 0x00000004, 0x00000002, 0x00000001 } }, // shift by exact number of words
- { 72, { 0x02000000, 0x01000000 } },
- { 80, { 0x00020000, 0x00010000 } },
- { 88, { 0x00000200, 0x00000100 } },
- { 128, { 0x00000001 } }, // shifted to most significant digit
- { 129, {} }, // all digits have been shifted right
- { 160, {} },
- };
-
- size_t const tests2 = 2;
- Crypto::UnsignedBigInteger const num2(Vector<u32> { 0x44444444, 0xffffffff });
-
- AK::Tuple<size_t, Vector<u32>> results2[] = {
- { 1, { 0xa2222222, 0x7fffffff } },
- { 2, { 0xd1111111, 0x3fffffff } },
- };
-
- for (size_t i = 0; i < tests1; ++i)
- EXPECT_EQ(num1.shift_right(results1[i].get<0>()).words(), results1[i].get<1>());
-
- for (size_t i = 0; i < tests2; ++i)
- EXPECT_EQ(num2.shift_right(results2[i].get<0>()).words(), results2[i].get<1>());
-}
-
-TEST_CASE(to_double)
-{
-#define EXPECT_TO_EQUAL_DOUBLE(bigint, double_value) \
- EXPECT_EQ((bigint).to_double(Crypto::UnsignedBigInteger::RoundingMode::RoundTowardZero), double_value)
-
- EXPECT_TO_EQUAL_DOUBLE(Crypto::UnsignedBigInteger(0), 0.0);
- // Make sure we don't get negative zero!
- EXPECT_EQ(signbit(Crypto::UnsignedBigInteger(0).to_double()), 0);
-
- EXPECT_TO_EQUAL_DOUBLE(Crypto::UnsignedBigInteger(9682), 9682.0);
-
- double double_max_value = NumericLimits<double>::max();
- double infinity = INFINITY;
-
- EXPECT_TO_EQUAL_DOUBLE(
- TRY_OR_FAIL(Crypto::UnsignedBigInteger::from_base(16, "fffffffffffff800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"sv)),
- double_max_value);
-
- EXPECT_TO_EQUAL_DOUBLE(
- TRY_OR_FAIL(Crypto::UnsignedBigInteger::from_base(16, "ffffffffffffff00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"sv)),
- double_max_value);
-
- EXPECT_TO_EQUAL_DOUBLE(
- TRY_OR_FAIL(Crypto::UnsignedBigInteger::from_base(16, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"sv)),
- double_max_value);
-
- EXPECT_TO_EQUAL_DOUBLE(
- TRY_OR_FAIL(Crypto::UnsignedBigInteger::from_base(16, "10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"sv)),
- infinity);
-
- EXPECT_TO_EQUAL_DOUBLE(
- TRY_OR_FAIL(Crypto::UnsignedBigInteger::from_base(16, "ffffffffffffffff"sv)),
- 18446744073709549568.0);
-
- EXPECT_TO_EQUAL_DOUBLE(
- TRY_OR_FAIL(Crypto::UnsignedBigInteger::from_base(16, "fffffffffffff800"sv)),
- 18446744073709549568.0);
-
- EXPECT_TO_EQUAL_DOUBLE(
- TRY_OR_FAIL(Crypto::UnsignedBigInteger::from_base(16, "fffffffffffff8ff"sv)),
- 18446744073709549568.0);
-
- EXPECT_EQ(
- TRY_OR_FAIL(Crypto::UnsignedBigInteger::from_base(16, "1fffffffffffff00"sv)).to_double(Crypto::UnsignedBigInteger::RoundingMode::IEEERoundAndTiesToEvenMantissa),
- 2305843009213693696.0);
-
- EXPECT_EQ(
- TRY_OR_FAIL(Crypto::UnsignedBigInteger::from_base(16, "1fffffffffffff00"sv)).to_double(Crypto::UnsignedBigInteger::RoundingMode::RoundTowardZero),
- 2305843009213693696.0);
-
- EXPECT_EQ(
- TRY_OR_FAIL(Crypto::UnsignedBigInteger::from_base(16, "1fffffffffffff80"sv)).to_double(Crypto::UnsignedBigInteger::RoundingMode::IEEERoundAndTiesToEvenMantissa),
- 2305843009213693952.0);
-
- EXPECT_EQ(TRY_OR_FAIL(Crypto::UnsignedBigInteger::from_base(16, "20000000000001"sv)).to_double(Crypto::UnsignedBigInteger::RoundingMode::IEEERoundAndTiesToEvenMantissa),
- 9007199254740992.0);
-
- EXPECT_EQ(TRY_OR_FAIL(Crypto::UnsignedBigInteger::from_base(16, "20000000000002"sv)).to_double(Crypto::UnsignedBigInteger::RoundingMode::IEEERoundAndTiesToEvenMantissa),
- 9007199254740994.0);
-
- // 2^53 = 20000000000000, +3 Rounds up because of tiesRoundToEven
- EXPECT_EQ(TRY_OR_FAIL(Crypto::UnsignedBigInteger::from_base(16, "20000000000003"sv)).to_double(Crypto::UnsignedBigInteger::RoundingMode::IEEERoundAndTiesToEvenMantissa),
- 9007199254740996.0);
-
- // +4 is exactly 9007199254740996
- EXPECT_EQ(TRY_OR_FAIL(Crypto::UnsignedBigInteger::from_base(16, "20000000000004"sv)).to_double(Crypto::UnsignedBigInteger::RoundingMode::IEEERoundAndTiesToEvenMantissa),
- 9007199254740996.0);
-
- // +5 rounds down because of tiesRoundToEven
- EXPECT_EQ(TRY_OR_FAIL(Crypto::UnsignedBigInteger::from_base(16, "20000000000005"sv)).to_double(Crypto::UnsignedBigInteger::RoundingMode::IEEERoundAndTiesToEvenMantissa),
- 9007199254740996.0);
-
- EXPECT_EQ(TRY_OR_FAIL(Crypto::UnsignedBigInteger::from_base(16, "20000000000006"sv)).to_double(Crypto::UnsignedBigInteger::RoundingMode::IEEERoundAndTiesToEvenMantissa),
- 9007199254740998.0);
-
- EXPECT_EQ(TRY_OR_FAIL(Crypto::UnsignedBigInteger::from_base(10, "98382635059784269824"sv)).to_double(Crypto::UnsignedBigInteger::RoundingMode::IEEERoundAndTiesToEvenMantissa),
- bit_cast<double>(0x4415555555555555ULL));
-
-#undef EXPECT_TO_EQUAL_DOUBLE
-}
-
-TEST_CASE(bigint_from_double)
-{
- {
- Crypto::UnsignedBigInteger from_zero { 0.0 };
- EXPECT(from_zero.is_zero());
- }
-
-#define SURVIVES_ROUND_TRIP_UNSIGNED(double_value) \
- { \
- Crypto::UnsignedBigInteger bigint { (double_value) }; \
- EXPECT_EQ(bigint.to_double(), (double_value)); \
- }
-
- SURVIVES_ROUND_TRIP_UNSIGNED(0.0);
- SURVIVES_ROUND_TRIP_UNSIGNED(1.0);
- SURVIVES_ROUND_TRIP_UNSIGNED(100000.0);
- SURVIVES_ROUND_TRIP_UNSIGNED(1000000000000.0);
- SURVIVES_ROUND_TRIP_UNSIGNED(10000000000000000000.0);
- SURVIVES_ROUND_TRIP_UNSIGNED(NumericLimits<double>::max());
-
- SURVIVES_ROUND_TRIP_UNSIGNED(bit_cast<double>(0x4340000000000002ULL));
- SURVIVES_ROUND_TRIP_UNSIGNED(bit_cast<double>(0x4340000000000001ULL));
- SURVIVES_ROUND_TRIP_UNSIGNED(bit_cast<double>(0x4340000000000000ULL));
-
- // Failed on last bits of mantissa
- SURVIVES_ROUND_TRIP_UNSIGNED(bit_cast<double>(0x7EDFFFFFFFFFFFFFULL));
- SURVIVES_ROUND_TRIP_UNSIGNED(bit_cast<double>(0x7ed5555555555555ULL));
- SURVIVES_ROUND_TRIP_UNSIGNED(bit_cast<double>(0x7EDCBA9876543210ULL));
-
- // Has exactly exponent of 32
- SURVIVES_ROUND_TRIP_UNSIGNED(bit_cast<double>(0x41f22f74e0000000ULL));
-
-#undef SURVIVES_ROUND_TRIP_UNSIGNED
-}
-
-TEST_CASE(unsigned_bigint_double_comparisons)
-{
-#define EXPECT_LESS_THAN(bigint, double_value) EXPECT_EQ(bigint.compare_to_double(double_value), Crypto::UnsignedBigInteger::CompareResult::DoubleGreaterThanBigInt)
-#define EXPECT_GREATER_THAN(bigint, double_value) EXPECT_EQ(bigint.compare_to_double(double_value), Crypto::UnsignedBigInteger::CompareResult::DoubleLessThanBigInt)
-#define EXPECT_EQUAL_TO(bigint, double_value) EXPECT_EQ(bigint.compare_to_double(double_value), Crypto::UnsignedBigInteger::CompareResult::DoubleEqualsBigInt)
-
- {
- Crypto::UnsignedBigInteger zero { 0 };
- EXPECT_EQUAL_TO(zero, 0.0);
- EXPECT_EQUAL_TO(zero, -0.0);
- }
-
- {
- Crypto::UnsignedBigInteger one { 1 };
- EXPECT_EQUAL_TO(one, 1.0);
- EXPECT_GREATER_THAN(one, -1.0);
- EXPECT_GREATER_THAN(one, 0.5);
- EXPECT_GREATER_THAN(one, -0.5);
- EXPECT_LESS_THAN(one, 1.000001);
- }
-
- {
- double double_infinity = HUGE_VAL;
- VERIFY(isinf(double_infinity));
- Crypto::UnsignedBigInteger one { 1 };
- EXPECT_LESS_THAN(one, double_infinity);
- EXPECT_GREATER_THAN(one, -double_infinity);
- }
-
- {
- double double_max_value = NumericLimits<double>::max();
- double double_below_max_value = nextafter(double_max_value, 0.0);
- VERIFY(double_below_max_value < double_max_value);
- VERIFY(double_below_max_value < (double_max_value - 1.0));
- auto max_value_in_bigint = TRY_OR_FAIL(Crypto::UnsignedBigInteger::from_base(16, "fffffffffffff800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"sv));
- auto max_value_plus_one = max_value_in_bigint.plus(Crypto::UnsignedBigInteger { 1 });
- auto max_value_minus_one = TRY_OR_FAIL(max_value_in_bigint.minus(Crypto::UnsignedBigInteger { 1 }));
-
- auto below_max_value_in_bigint = TRY_OR_FAIL(Crypto::UnsignedBigInteger::from_base(16, "fffffffffffff000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"sv));
-
- EXPECT_EQUAL_TO(max_value_in_bigint, double_max_value);
- EXPECT_LESS_THAN(max_value_minus_one, double_max_value);
- EXPECT_GREATER_THAN(max_value_plus_one, double_max_value);
- EXPECT_LESS_THAN(below_max_value_in_bigint, double_max_value);
-
- EXPECT_GREATER_THAN(max_value_in_bigint, double_below_max_value);
- EXPECT_GREATER_THAN(max_value_minus_one, double_below_max_value);
- EXPECT_GREATER_THAN(max_value_plus_one, double_below_max_value);
- EXPECT_EQUAL_TO(below_max_value_in_bigint, double_below_max_value);
- }
-
- {
- double just_above_255 = bit_cast<double>(0x406fe00000000001ULL);
- double just_below_255 = bit_cast<double>(0x406fdfffffffffffULL);
- double double_255 = 255.0;
- Crypto::UnsignedBigInteger bigint_255 { 255 };
-
- EXPECT_EQUAL_TO(bigint_255, double_255);
- EXPECT_GREATER_THAN(bigint_255, just_below_255);
- EXPECT_LESS_THAN(bigint_255, just_above_255);
- }
-
-#undef EXPECT_LESS_THAN
-#undef EXPECT_GREATER_THAN
-#undef EXPECT_EQUAL_TO
-}
-
-TEST_CASE(moving_bigints)
-{
- Crypto::UnsignedBigInteger bigint1;
- {
- auto bigint2 = "123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789"_bigint;
- bigint1 = move(bigint2);
- EXPECT(bigint2.is_zero());
- }
-
- EXPECT_EQ(MUST(bigint1.to_base(10)), "123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789"sv);
-
- Crypto::UnsignedBigInteger bigint3 { move(bigint1) };
- EXPECT(bigint1.is_zero());
-
- EXPECT_EQ(MUST(bigint3.to_base(10)), "123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789"sv);
-}
-
-namespace AK {
-
-template<>
-struct Formatter<Crypto::UnsignedBigInteger::CompareResult> : Formatter<StringView> {
- ErrorOr<void> format(FormatBuilder& builder, Crypto::UnsignedBigInteger::CompareResult const& compare_result)
- {
- switch (compare_result) {
- case Crypto::UnsignedBigInteger::CompareResult::DoubleEqualsBigInt:
- return builder.put_string("Equals"sv);
- case Crypto::UnsignedBigInteger::CompareResult::DoubleLessThanBigInt:
- return builder.put_string("LessThan"sv);
- case Crypto::UnsignedBigInteger::CompareResult::DoubleGreaterThanBigInt:
- return builder.put_string("GreaterThan"sv);
- default:
- return builder.put_string("???"sv);
- }
- }
-};
-
-}
diff --git a/Tests/LibWeb/StructuredSerializeTestHelpers.h b/Tests/LibWeb/StructuredSerializeTestHelpers.h
index 7adce81ee6d..3ee32a7563c 100644
--- a/Tests/LibWeb/StructuredSerializeTestHelpers.h
+++ b/Tests/LibWeb/StructuredSerializeTestHelpers.h
@@ -449,7 +449,7 @@ inline Web::HTML::StorageSerializationRecord crypto_key_secret_record(ReadonlyBy
return serializable_storage_record("CryptoKey"sv, 1, body);
}
-// UnsignedBigInteger stores big-endian octets in ByteBuffer form.
+// A big integer is stored as its big-endian octets.
inline void append_storage_big_integer(Vector<u8>& bytes, ReadonlyBytes big_endian_octets)
{
append_storage_bytes(bytes, big_endian_octets);
diff --git a/vcpkg.json b/vcpkg.json
index 90305770cd1..8cd73935f84 100644
--- a/vcpkg.json
+++ b/vcpkg.json
@@ -102,7 +102,6 @@
"name": "libedit",
"platform": "!windows & !android"
},
- "libtommath",
{
"name": "libwebp",
"features": [
@@ -359,10 +358,6 @@
"name": "libpsl",
"version": "0.23.3#1"
},
- {
- "name": "libtommath",
- "version": "1.3.0#3"
- },
{
"name": "libwebp",
"version": "1.6.0#3"