Compare commits

..

3 Commits

Author SHA1 Message Date
Jingchen
46b997b774 feat: Create new transaction testing framework TxTest (#6537)
Signed-off-by: JCW <a1q123456@users.noreply.github.com>
Co-authored-by: xrplf-ai-reviewer[bot] <266832837+xrplf-ai-reviewer[bot]@users.noreply.github.com>
Co-authored-by: Copilot <copilot@github.com>
2026-04-28 14:16:10 +00:00
Vito Tumas
147da57348 feat: Add cleanup amendment for 3.2.0 (#7037) 2026-04-28 10:22:32 +00:00
Pratik Mankawde
3547112540 fix: Fix ubsan flagged issues (#6151)
Signed-off-by: Pratik Mankawde <3397372+pratikmankawde@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: xrplf-ai-reviewer[bot] <266832837+xrplf-ai-reviewer[bot]@users.noreply.github.com>
2026-04-27 20:34:16 +00:00
28 changed files with 2719 additions and 1210 deletions

View File

@@ -188,10 +188,16 @@ test.toplevel > xrpl.json
test.unit_test > xrpl.basics
test.unit_test > xrpl.protocol
tests.libxrpl > xrpl.basics
tests.libxrpl > xrpl.core
tests.libxrpl > xrpl.json
tests.libxrpl > xrpl.ledger
tests.libxrpl > xrpl.net
tests.libxrpl > xrpl.nodestore
tests.libxrpl > xrpl.protocol
tests.libxrpl > xrpl.protocol_autogen
tests.libxrpl > xrpl.server
tests.libxrpl > xrpl.shamap
tests.libxrpl > xrpl.tx
xrpl.conditions > xrpl.basics
xrpl.conditions > xrpl.protocol
xrpl.core > xrpl.basics

View File

@@ -51,20 +51,21 @@ def generate_strategy_matrix(all: bool, config: Config) -> list:
# Only generate a subset of configurations in PRs.
if not all:
# Debian:
# - Bookworm using GCC 13: Release on linux/amd64, set the reference
# fee to 500.
# - Bookworm using GCC 15: Debug on linux/amd64, enable code
# coverage (which will be done below).
# - Bookworm using GCC 13: Debug on linux/amd64, set the reference
# fee to 500 and enable code coverage (which will be done below).
# - Bookworm using GCC 15: Debug on linux/amd64, enable Address and
# UB sanitizers (which will be done below).
# - Bookworm using Clang 16: Debug on linux/amd64, enable voidstar.
# - Bookworm using Clang 17: Release on linux/amd64, set the
# reference fee to 1000.
# - Bookworm using Clang 20: Debug on linux/amd64.
# - Bookworm using Clang 20: Debug on linux/amd64, enable Address
# and UB sanitizers (which will be done below).
if os["distro_name"] == "debian":
skip = True
if os["distro_version"] == "bookworm":
if (
f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-13"
and build_type == "Release"
and build_type == "Debug"
and architecture["platform"] == "linux/amd64"
):
cmake_args = f"-DUNIT_TEST_REFERENCE_FEE=500 {cmake_args}"
@@ -193,11 +194,11 @@ def generate_strategy_matrix(all: bool, config: Config) -> list:
):
continue
# Enable code coverage for Debian Bookworm using GCC 15 in Debug on
# linux/amd64
# Enable code coverage for Debian Bookworm using GCC 13 in Debug on
# linux/amd64.
if (
f"{os['distro_name']}-{os['distro_version']}" == "debian-bookworm"
and f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-15"
and f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-13"
and build_type == "Debug"
and architecture["platform"] == "linux/amd64"
):
@@ -234,23 +235,39 @@ def generate_strategy_matrix(all: bool, config: Config) -> list:
# Add the configuration to the list, with the most unique fields first,
# so that they are easier to identify in the GitHub Actions UI, as long
# names get truncated.
# Add Address and Thread (both coupled with UB) sanitizers for specific bookworm distros.
# Add Address and UB sanitizers as separate configurations for specific
# bookworm distros. Thread sanitizer is currently disabled (see below).
# GCC-Asan xrpld-embedded tests are failing because of https://github.com/google/sanitizers/issues/856
if (
os["distro_version"] == "bookworm"
and f"{os['compiler_name']}-{os['compiler_version']}" == "clang-20"
):
# Add ASAN + UBSAN configuration.
if os[
"distro_version"
] == "bookworm" and f"{os['compiler_name']}-{os['compiler_version']}" in [
"gcc-15",
"clang-20",
]:
# Add ASAN configuration.
configurations.append(
{
"config_name": config_name + "-asan-ubsan",
"config_name": config_name + "-asan",
"cmake_args": cmake_args,
"cmake_target": cmake_target,
"build_only": build_only,
"build_type": build_type,
"os": os,
"architecture": architecture,
"sanitizers": "address,undefinedbehavior",
"sanitizers": "address",
}
)
# Add UBSAN configuration.
configurations.append(
{
"config_name": config_name + "-ubsan",
"cmake_args": cmake_args,
"cmake_target": cmake_target,
"build_only": build_only,
"build_type": build_type,
"os": os,
"architecture": architecture,
"sanitizers": "undefinedbehavior",
}
)
# TSAN is deactivated due to seg faults with latest compilers.

View File

@@ -67,8 +67,10 @@ private:
}
else
{
while ((elapsed--) != 0u)
for (; elapsed > 0; --elapsed)
{
m_value -= (m_value + Window - 1) / Window;
}
}
}

View File

@@ -2,19 +2,13 @@
#include <xrpl/beast/utility/instrumentation.h>
#include <concepts>
#include <cstdint>
#include <functional>
#include <limits>
#include <optional>
#include <ostream>
#include <stdexcept>
#include <string>
#ifdef _MSC_VER
#include <boost/multiprecision/cpp_int.hpp>
#endif // !defined(_MSC_VER)
namespace xrpl {
class Number;
@@ -22,39 +16,18 @@ class Number;
std::string
to_string(Number const& amount);
/** Returns a rough estimate of log10(value).
*
* The return value is a pair (log, rem), where log is the estimated
* base-10 logarithm (roughly floor(log10(value))), and rem is value with
* all trailing 0s removed (i.e., divided by the largest power of 10 that
* evenly divides value). If rem is 1, then value is an exact power of ten, and
* log is the exact log10(value).
*
* This function only works for positive values.
*/
template <std::unsigned_integral T>
constexpr std::pair<int, T>
logTenEstimate(T value)
{
int log = 0;
T remainder = value;
while (value >= 10)
{
if (value % 10 == 0)
remainder = remainder / 10;
value /= 10;
++log;
}
return {log, remainder};
}
template <typename T>
constexpr std::optional<int>
logTen(T value)
{
auto const est = logTenEstimate(value);
if (est.second == 1)
return est.first;
int log = 0;
while (value >= 10 && value % 10 == 0)
{
value /= 10;
++log;
}
if (value == 1)
return log;
return std::nullopt;
}
@@ -68,10 +41,12 @@ isPowerOfTen(T value)
/** MantissaRange defines a range for the mantissa of a normalized Number.
*
* The mantissa is in the range [min, max], where
* * min is a power of 10, and
* * max = min * 10 - 1.
*
* The mantissa_scale enum indicates whether the range is "small" or
* "large". This intentionally prevents the creation of any
* MantissaRanges representing other values.
* The mantissa_scale enum indicates whether the range is "small" or "large".
* This intentionally restricts the number of MantissaRanges that can be
* instantiated to two: one for each scale.
*
* The "small" scale is based on the behavior of STAmount for IOUs. It has a min
* value of 10^15, and a max value of 10^16-1. This was sufficient for
@@ -85,8 +60,8 @@ isPowerOfTen(T value)
* "large" scale.
*
* The "large" scale is intended to represent all values that can be represented
* by an STAmount - IOUs, XRP, and MPTs. It has a min value of 2^63/10+1
* (truncated), and a max value of 2^63-1.
* by an STAmount - IOUs, XRP, and MPTs. It has a min value of 10^18, and a max
* value of 10^19-1.
*
* Note that if the mentioned amendments are eventually retired, this class
* should be left in place, but the "small" scale option should be removed. This
@@ -98,52 +73,25 @@ struct MantissaRange
enum mantissa_scale { small, large };
explicit constexpr MantissaRange(mantissa_scale scale_)
: max(getMax(scale_)), internalMin(getInternalMin(scale_, min)), scale(scale_)
: min(getMin(scale_)), log(logTen(min).value_or(-1)), scale(scale_)
{
// Keep the error messages terse. Since this is constexpr, if any of these throw, it won't
// compile, so there's no real need to worry about runtime exceptions here.
if (min * 10 <= max)
throw std::out_of_range("Invalid mantissa range: min * 10 <= max");
if (max / 10 >= min)
throw std::out_of_range("Invalid mantissa range: max / 10 >= min");
if ((min - 1) * 10 > max)
throw std::out_of_range("Invalid mantissa range: (min - 1) * 10 > max");
// This is a little hacky
if ((max + 10) / 10 < min)
throw std::out_of_range("Invalid mantissa range: (max + 10) / 10 < min");
if (computeLog(internalMin) != log)
throw std::out_of_range("Invalid mantissa range: computeLog(internalMin) != log");
}
// Explicitly delete copy and move operations
MantissaRange(MantissaRange const&) = delete;
MantissaRange(MantissaRange&&) = delete;
MantissaRange&
operator=(MantissaRange const&) = delete;
MantissaRange&
operator=(MantissaRange&&) = delete;
rep max;
rep min{computeMin(max)};
/* Used to determine if mantissas are in range, but have fewer digits than max.
*
* Unlike min, internalMin is always an exact power of 10, so a mantissa in the internal
* representation will always have a consistent number of digits.
*/
rep internalMin;
rep log{computeLog(min)};
rep min;
rep max{(min * 10) - 1};
int log;
mantissa_scale scale;
private:
static constexpr rep
getMax(mantissa_scale scale)
getMin(mantissa_scale scale_)
{
switch (scale)
switch (scale_)
{
case small:
return 9'999'999'999'999'999ULL;
return 1'000'000'000'000'000ULL;
case large:
return std::numeric_limits<std::int64_t>::max();
return 1'000'000'000'000'000'000ULL;
default:
// Since this can never be called outside a non-constexpr
// context, this throw assures that the build fails if an
@@ -151,59 +99,19 @@ private:
throw std::runtime_error("Unknown mantissa scale");
}
}
static constexpr rep
computeMin(rep max)
{
return (max / 10) + 1;
}
static constexpr rep
getInternalMin(mantissa_scale scale, rep min)
{
switch (scale)
{
case large:
return 1'000'000'000'000'000'000ULL;
default:
if (isPowerOfTen(min))
return min;
throw std::runtime_error("Unknown/bad mantissa scale");
}
}
static constexpr rep
computeLog(rep min)
{
auto const estimate = logTenEstimate(min);
return estimate.first + (estimate.second == 1 ? 0 : 1);
}
};
// Like std::integral, but only 64-bit integral types.
template <class T>
concept Integral64 = std::is_same_v<T, std::int64_t> || std::is_same_v<T, std::uint64_t>;
namespace detail {
#ifdef _MSC_VER
using uint128_t = boost::multiprecision::uint128_t;
using int128_t = boost::multiprecision::int128_t;
#else // !defined(_MSC_VER)
using uint128_t = __uint128_t;
using int128_t = __int128_t;
#endif // !defined(_MSC_VER)
template <class T>
concept UnsignedMantissa = std::is_unsigned_v<T> || std::is_same_v<T, uint128_t>;
} // namespace detail
/** Number is a floating point type that can represent a wide range of values.
*
* It can represent all values that can be represented by an STAmount -
* regardless of asset type - XRPAmount, MPTAmount, and IOUAmount, with at least
* as much precision as those types require.
*
* ---- Internal Operational Representation ----
* ---- Internal Representation ----
*
* Internally, Number is represented with three values:
* 1. a bool sign flag,
@@ -218,21 +126,15 @@ concept UnsignedMantissa = std::is_unsigned_v<T> || std::is_same_v<T, uint128_t>
*
* A non-zero mantissa is (almost) always normalized, meaning it and the
* exponent are grown or shrunk until the mantissa is in the range
* [MantissaRange.internalMin, MantissaRange.internalMin * 10 - 1].
*
* This internal representation is only used during some operations to ensure
* that the mantissa is a known, predictable size. The class itself stores the
* values using the external representation described below.
* [MantissaRange.min, MantissaRange.max].
*
* Note:
* 1. Normalization can be disabled by using the "unchecked" ctor tag. This
* should only be used at specific conversion points, some constexpr
* values, and in unit tests.
* 2. Unlike MantissaRange.min, internalMin is always an exact power of 10,
* so a mantissa in the internal representation will always have a
* consistent number of digits.
* 3. The functions toInternal() and fromInternal() are used to convert
* between the two representations.
* 2. The max of the "large" range, 10^19-1, is the largest 10^X-1 value that
* fits in an unsigned 64-bit number. (10^19-1 < 2^64-1 and
* 10^20-1 > 2^64-1). This avoids under- and overflows.
*
* ---- External Interface ----
*
@@ -245,12 +147,13 @@ concept UnsignedMantissa = std::is_unsigned_v<T> || std::is_same_v<T, uint128_t>
* represent the full range of valid XRP and MPT integer values accurately.
*
* Note:
* 1. The "large" mantissa range is (2^63/10+1) to 2^63-1. 2^63-1 is between
* 10^18 and 10^19-1, and (2^63/10+1) is between 10^17 and 10^18-1. Thus,
* the mantissa may have 18 or 19 digits. This value will be modified to
* always have 19 digits before some operations to ensure consistency.
* 1. 2^63-1 is between 10^18 and 10^19-1, which are the limits of the "large"
* mantissa range.
* 2. The functions mantissa() and exponent() return the external view of the
* Number value, specifically using a signed 63-bit mantissa.
* Number value, specifically using a signed 63-bit mantissa. This may
* require altering the internal representation to fit into that range
* before the value is returned. The interface guarantees consistency of
* the two values.
* 3. Number cannot represent -2^63 (std::numeric_limits<std::int64_t>::min())
* as an exact integer, but it doesn't need to, because all asset values
* on-ledger are non-negative. This is due to implementation details of
@@ -305,7 +208,8 @@ class Number
using rep = std::int64_t;
using internalrep = MantissaRange::rep;
rep mantissa_{0};
bool negative_{false};
internalrep mantissa_{0};
int exponent_{std::numeric_limits<int>::lowest()};
public:
@@ -313,6 +217,10 @@ public:
constexpr static int minExponent = -32768;
constexpr static int maxExponent = 32768;
constexpr static internalrep maxRep = std::numeric_limits<rep>::max();
static_assert(maxRep == 9'223'372'036'854'775'807);
static_assert(-maxRep == std::numeric_limits<rep>::min() + 1);
// May need to make unchecked private
struct unchecked
{
@@ -390,7 +298,8 @@ public:
friend constexpr bool
operator==(Number const& x, Number const& y) noexcept
{
return x.mantissa_ == y.mantissa_ && x.exponent_ == y.exponent_;
return x.negative_ == y.negative_ && x.mantissa_ == y.mantissa_ &&
x.exponent_ == y.exponent_;
}
friend constexpr bool
@@ -404,8 +313,8 @@ public:
{
// If the two amounts have different signs (zero is treated as positive)
// then the comparison is true iff the left is negative.
bool const lneg = x.mantissa_ < 0;
bool const rneg = y.mantissa_ < 0;
bool const lneg = x.negative_;
bool const rneg = y.negative_;
if (lneg != rneg)
return lneg;
@@ -433,11 +342,9 @@ public:
[[nodiscard]] constexpr int
signum() const noexcept
{
if (mantissa_ < 0)
{
if (negative_)
return -1;
}
return (mantissa_ != 0 ? 1 : 0);
return (mantissa_ != 0u) ? 1 : 0;
}
[[nodiscard]] Number
@@ -476,9 +383,6 @@ public:
friend Number
root2(Number f);
friend Number
power(Number const& f, unsigned n, unsigned d);
// Thread local rounding control. Default is to_nearest
enum rounding_mode { to_nearest, towards_zero, downward, upward };
static rounding_mode
@@ -543,39 +447,22 @@ private:
static_assert(isPowerOfTen(smallRange.min));
static_assert(smallRange.min == 1'000'000'000'000'000LL);
static_assert(smallRange.max == 9'999'999'999'999'999LL);
static_assert(smallRange.internalMin == smallRange.min);
static_assert(smallRange.log == 15);
static_assert(smallRange.min < maxRep);
static_assert(smallRange.max < maxRep);
constexpr static MantissaRange largeRange{MantissaRange::large};
static_assert(!isPowerOfTen(largeRange.min));
static_assert(largeRange.min == 922'337'203'685'477'581ULL);
static_assert(largeRange.max == internalrep(9'223'372'036'854'775'807ULL));
static_assert(largeRange.max == std::numeric_limits<rep>::max());
static_assert(largeRange.internalMin == 1'000'000'000'000'000'000ULL);
static_assert(isPowerOfTen(largeRange.min));
static_assert(largeRange.min == 1'000'000'000'000'000'000ULL);
static_assert(largeRange.max == internalrep(9'999'999'999'999'999'999ULL));
static_assert(largeRange.log == 18);
// There are 2 values that will not fit in largeRange without some extra
// work
// * 9223372036854775808
// * 9223372036854775809
// They both end up < min, but with a leftover. If they round up, everything
// will be fine. If they don't, we'll need to bring them up into range.
// Guard::bringIntoRange handles this situation.
static_assert(largeRange.min < maxRep);
static_assert(largeRange.max > maxRep);
// The range for the mantissa when normalized.
// Use reference_wrapper to avoid making copies, and prevent accidentally
// changing the values inside the range.
static thread_local std::reference_wrapper<MantissaRange const> range_;
// And one is needed because it needs to choose between oneSmall and
// oneLarge based on the current range
static Number
one(MantissaRange const& range);
static Number
root(MantissaRange const& range, Number f, unsigned d);
void
normalize(MantissaRange const& range);
void
normalize();
@@ -598,15 +485,11 @@ private:
friend void
doNormalize(
bool& negative,
T& mantissa,
int& exponent,
T& mantissa_,
int& exponent_,
MantissaRange::rep const& minMantissa,
MantissaRange::rep const& maxMantissa);
[[nodiscard]]
bool
isnormal(MantissaRange const& range) const noexcept;
[[nodiscard]] bool
isnormal() const noexcept;
@@ -616,69 +499,18 @@ private:
[[nodiscard]] Number
shiftExponent(int exponentDelta) const;
// Safely return the absolute value of a rep (int64) mantissa as an internalrep (uint64).
// Safely convert rep (int64) mantissa to internalrep (uint64). If the rep
// is negative, returns the positive value. This takes a little extra work
// because converting std::numeric_limits<std::int64_t>::min() flirts with
// UB, and can vary across compilers.
static internalrep
externalToInternal(rep mantissa);
/** Breaks down the number into components, potentially de-normalizing it.
*
* Ensures that the mantissa always has range_.log + 1 digits.
*
*/
template <detail::UnsignedMantissa Rep = internalrep>
std::tuple<bool, Rep, int>
toInternal(MantissaRange const& range) const;
/** Breaks down the number into components, potentially de-normalizing it.
*
* Ensures that the mantissa always has range_.log + 1 digits.
*
*/
template <detail::UnsignedMantissa Rep = internalrep>
std::tuple<bool, Rep, int>
toInternal() const;
/** Rebuilds the number from components.
*
* If "expectNormal" is true, the values are expected to be normalized - all
* in their valid ranges.
*
* If "expectNormal" is false, the values are expected to be "near
* normalized", meaning that the mantissa has to be modified at most once to
* bring it back into range.
*
*/
template <bool expectNormal = true, detail::UnsignedMantissa Rep = internalrep>
void
fromInternal(bool negative, Rep mantissa, int exponent, MantissaRange const* pRange);
/** Rebuilds the number from components.
*
* If "expectNormal" is true, the values are expected to be normalized - all
* in their valid ranges.
*
* If "expectNormal" is false, the values are expected to be "near
* normalized", meaning that the mantissa has to be modified at most once to
* bring it back into range.
*
*/
template <bool expectNormal = true, detail::UnsignedMantissa Rep = internalrep>
void
fromInternal(bool negative, Rep mantissa, int exponent);
class Guard;
public:
constexpr static internalrep largestMantissa = largeRange.max;
};
inline constexpr Number::Number(
bool negative,
internalrep mantissa,
int exponent,
unchecked) noexcept
: mantissa_{negative ? -static_cast<rep>(mantissa) : static_cast<rep>(mantissa)}
, exponent_{exponent}
constexpr Number::Number(bool negative, internalrep mantissa, int exponent, unchecked) noexcept
: negative_(negative), mantissa_{mantissa}, exponent_{exponent}
{
}
@@ -689,6 +521,12 @@ constexpr Number::Number(internalrep mantissa, int exponent, unchecked) noexcept
constexpr static Number numZero{};
inline Number::Number(bool negative, internalrep mantissa, int exponent, normalized)
: Number(negative, mantissa, exponent, unchecked{})
{
normalize();
}
inline Number::Number(internalrep mantissa, int exponent, normalized)
: Number(false, mantissa, exponent, normalized{})
{
@@ -711,7 +549,17 @@ inline Number::Number(rep mantissa) : Number{mantissa, 0}
constexpr Number::rep
Number::mantissa() const noexcept
{
return mantissa_;
auto m = mantissa_;
if (m > maxRep)
{
XRPL_ASSERT_PARTS(
!isnormal() || (m % 10 == 0 && m / 10 <= maxRep),
"xrpl::Number::mantissa",
"large normalized mantissa has no remainder");
m /= 10;
}
auto const sign = negative_ ? -1 : 1;
return sign * static_cast<Number::rep>(m);
}
/** Returns the exponent of the external view of the Number.
@@ -722,7 +570,16 @@ Number::mantissa() const noexcept
constexpr int
Number::exponent() const noexcept
{
return exponent_;
auto e = exponent_;
if (mantissa_ > maxRep)
{
XRPL_ASSERT_PARTS(
!isnormal() || (mantissa_ % 10 == 0 && mantissa_ / 10 <= maxRep),
"xrpl::Number::exponent",
"large normalized mantissa has no remainder");
++e;
}
return e;
}
constexpr Number
@@ -737,7 +594,7 @@ Number::operator-() const noexcept
if (mantissa_ == 0)
return Number{};
auto x = *this;
x.mantissa_ = -x.mantissa_;
x.negative_ = !x.negative_;
return x;
}
@@ -818,37 +675,31 @@ Number::min() noexcept
inline Number
Number::max() noexcept
{
return Number{false, range_.get().max, maxExponent, unchecked{}};
return Number{false, std::min(range_.get().max, maxRep), maxExponent, unchecked{}};
}
inline Number
Number::lowest() noexcept
{
return Number{true, range_.get().max, maxExponent, unchecked{}};
}
inline bool
Number::isnormal(MantissaRange const& range) const noexcept
{
auto const abs_m = externalToInternal(mantissa_);
return *this == Number{} ||
(range.min <= abs_m && abs_m <= range.max && //
minExponent <= exponent_ && exponent_ <= maxExponent);
return Number{true, std::min(range_.get().max, maxRep), maxExponent, unchecked{}};
}
inline bool
Number::isnormal() const noexcept
{
return isnormal(range_);
MantissaRange const& range = range_;
auto const abs_m = mantissa_;
return *this == Number{} ||
(range.min <= abs_m && abs_m <= range.max && (abs_m <= maxRep || abs_m % 10 == 0) &&
minExponent <= exponent_ && exponent_ <= maxExponent);
}
template <Integral64 T>
std::pair<T, int>
Number::normalizeToRange(T minMantissa, T maxMantissa) const
{
bool negative = mantissa_ < 0;
internalrep mantissa = externalToInternal(mantissa_);
bool negative = negative_;
internalrep mantissa = mantissa_;
int exponent = exponent_;
if constexpr (std::is_unsigned_v<T>)
@@ -857,19 +708,11 @@ Number::normalizeToRange(T minMantissa, T maxMantissa) const
!negative,
"xrpl::Number::normalizeToRange",
"Number is non-negative for unsigned range.");
// To avoid logical errors in release builds, throw if the Number is
// negative for an unsigned range.
if (negative)
throw std::runtime_error(
"Number::normalizeToRange: Number is negative for "
"unsigned range.");
}
Number::normalize(negative, mantissa, exponent, minMantissa, maxMantissa);
// Cast mantissa to signed type first (if T is a signed type) to avoid
// unsigned integer overflow when multiplying by negative sign
T signedMantissa = negative ? -static_cast<T>(mantissa) : static_cast<T>(mantissa);
return std::make_pair(signedMantissa, exponent);
auto const sign = negative ? -1 : 1;
return std::make_pair(static_cast<T>(sign * mantissa), exponent);
}
constexpr Number

View File

@@ -43,8 +43,10 @@ public:
: work_(boost::asio::make_work_guard(ios_))
{
threads_.reserve(concurrency);
while ((concurrency--) != 0u)
for (std::size_t i = 0; i < concurrency; ++i)
{
threads_.emplace_back([&] { ios_.run(); });
}
}
~enable_yield_to()

View File

@@ -54,8 +54,9 @@ read_varint(void const* buf, std::size_t buflen, std::size_t& t)
return 1;
}
auto const used = n;
while (n--)
while (n > 0)
{
--n;
auto const d = p[n];
auto const t0 = t;
t *= 127;

View File

@@ -232,7 +232,7 @@ std::size_t constexpr maxMPTokenMetadataLength = 1024;
/** The maximum amount of MPTokenIssuance */
std::uint64_t constexpr maxMPTokenAmount = 0x7FFF'FFFF'FFFF'FFFFull;
static_assert(Number::largestMantissa >= maxMPTokenAmount);
static_assert(Number::maxRep >= maxMPTokenAmount);
/** The maximum length of Data payload */
std::size_t constexpr maxDataPayloadLength = 256;

View File

@@ -540,8 +540,6 @@ STAmount::fromNumber(A const& a, Number const& number)
return STAmount{asset, intValue, 0, negative};
}
XRPL_ASSERT_PARTS(
working.signum() >= 0, "xrpl::STAmount::fromNumber", "non-negative Number to normalize");
auto const [mantissa, exponent] = working.normalizeToRange(cMinValue, cMaxValue);
return STAmount{asset, mantissa, exponent, negative};

View File

@@ -23,7 +23,7 @@ systemName()
/** Number of drops in the genesis account. */
constexpr XRPAmount INITIAL_XRP{100'000'000'000 * DROPS_PER_XRP};
static_assert(INITIAL_XRP.drops() == 100'000'000'000'000'000);
static_assert(Number::largestMantissa >= INITIAL_XRP.drops());
static_assert(Number::maxRep >= INITIAL_XRP.drops());
/** Returns true if the amount does not exceed the initial XRP in existence. */
inline bool

View File

@@ -15,6 +15,7 @@
// Add new amendments to the top of this list.
// Keep it sorted in reverse chronological order.
XRPL_FIX (Cleanup3_2_0, Supported::no, VoteBehavior::DefaultNo)
XRPL_FEATURE(MPTokensV2, Supported::no, VoteBehavior::DefaultNo)
XRPL_FIX (Security3_1_3, Supported::no, VoteBehavior::DefaultNo)
XRPL_FIX (PermissionedDomainInvariant, Supported::yes, VoteBehavior::DefaultNo)

View File

@@ -130,6 +130,19 @@ public:
return sle_->at(sfFlags);
}
/**
* @brief Check if a specific flag is set.
*
* @param f The flag bitmask to check
* @return true if all bits in f are set in the flags field
*/
[[nodiscard]]
bool
isFlag(std::uint32_t f) const
{
return sle_->isFlag(f);
}
/**
* @brief Get the underlying SLE object.
*

View File

@@ -11,7 +11,6 @@ float-cast-overflow:external
float-divide-by-zero:external
function:external
implicit-integer-sign-change:external
implicit-signed-integer-truncation::external
implicit-signed-integer-truncation:external
implicit-unsigned-integer-truncation:external
integer-divide-by-zero:external
@@ -71,145 +70,15 @@ vla-bound:boost
vptr_check:boost
vptr:boost
# Google protobuf
# Google protobuf - intentional overflows in hash functions
undefined:protobuf
# Suppress UBSan errors in xrpld code by source file path
undefined:src/libxrpl/basics/base64.cpp
undefined:src/libxrpl/basics/Number.cpp
undefined:src/libxrpl/beast/utility/beast_Journal.cpp
undefined:src/libxrpl/crypto/RFC1751.cpp
undefined:src/libxrpl/ledger/ApplyView.cpp
undefined:src/libxrpl/ledger/View.cpp
undefined:src/libxrpl/protocol/Permissions.cpp
undefined:src/libxrpl/protocol/STAmount.cpp
undefined:src/libxrpl/protocol/STPathSet.cpp
undefined:src/libxrpl/protocol/tokens.cpp
undefined:src/libxrpl/shamap/SHAMap.cpp
undefined:src/test/app/Batch_test.cpp
undefined:src/test/app/Invariants_test.cpp
undefined:src/test/app/NFToken_test.cpp
undefined:src/test/app/Offer_test.cpp
undefined:src/test/app/Path_test.cpp
undefined:src/test/basics/XRPAmount_test.cpp
undefined:src/test/beast/LexicalCast_test.cpp
undefined:src/test/jtx/impl/acctdelete.cpp
undefined:src/test/ledger/SkipList_test.cpp
undefined:src/test/rpc/Subscribe_test.cpp
undefined:src/tests/libxrpl/basics/RangeSet.cpp
undefined:src/xrpld/app/main/BasicApp.cpp
undefined:src/xrpld/app/main/BasicApp.cpp
undefined:src/xrpld/app/misc/detail/AmendmentTable.cpp
undefined:src/xrpld/app/misc/NetworkOPs.cpp
undefined:src/libxrpl/json/json_value.cpp
undefined:src/xrpld/app/paths/detail/StrandFlow.h
undefined:src/xrpld/app/tx/detail/NFTokenMint.cpp
undefined:src/xrpld/app/tx/detail/OracleSet.cpp
undefined:src/xrpld/core/detail/JobQueue.cpp
undefined:src/xrpld/core/detail/Workers.cpp
undefined:src/xrpld/rpc/detail/Role.cpp
undefined:src/xrpld/rpc/handlers/GetAggregatePrice.cpp
undefined:xrpl/basics/base_uint.h
undefined:xrpl/basics/DecayingSample.h
undefined:xrpl/beast/test/yield_to.h
undefined:xrpl/beast/xor_shift_engine.h
undefined:xrpl/nodestore/detail/varint.h
undefined:xrpl/peerfinder/detail/Counts.h
undefined:xrpl/protocol/nft.h
# basic_string.h:483:51: runtime error: unsigned integer overflow
unsigned-integer-overflow:basic_string.h
unsigned-integer-overflow:bits/chrono.h
unsigned-integer-overflow:bits/random.h
unsigned-integer-overflow:bits/random.tcc
unsigned-integer-overflow:bits/stl_algobase.h
unsigned-integer-overflow:bits/uniform_int_dist.h
unsigned-integer-overflow:string_view
# runtime error: unsigned integer overflow: 0 - 1 cannot be represented in type 'std::size_t' (aka 'unsigned long')
unsigned-integer-overflow:src/libxrpl/basics/base64.cpp
unsigned-integer-overflow:src/libxrpl/basics/Number.cpp
unsigned-integer-overflow:src/libxrpl/crypto/RFC1751.cpp
unsigned-integer-overflow:rc/libxrpl/json/json_value.cpp
unsigned-integer-overflow:src/libxrpl/ledger/ApplyView.cpp
unsigned-integer-overflow:src/libxrpl/ledger/View.cpp
unsigned-integer-overflow:src/libxrpl/protocol/Permissions.cpp
unsigned-integer-overflow:src/libxrpl/protocol/STAmount.cpp
unsigned-integer-overflow:src/libxrpl/protocol/STPathSet.cpp
unsigned-integer-overflow:src/libxrpl/protocol/tokens.cpp
unsigned-integer-overflow:src/libxrpl/shamap/SHAMap.cpp
unsigned-integer-overflow:src/test/app/Batch_test.cpp
unsigned-integer-overflow:src/test/app/Invariants_test.cpp
unsigned-integer-overflow:src/test/app/NFToken_test.cpp
unsigned-integer-overflow:src/test/app/Offer_test.cpp
unsigned-integer-overflow:src/test/app/Path_test.cpp
unsigned-integer-overflow:src/test/basics/XRPAmount_test.cpp
unsigned-integer-overflow:src/test/beast/LexicalCast_test.cpp
unsigned-integer-overflow:src/test/jtx/impl/acctdelete.cpp
unsigned-integer-overflow:src/test/ledger/SkipList_test.cpp
unsigned-integer-overflow:src/test/rpc/Subscribe_test.cpp
unsigned-integer-overflow:src/tests/libxrpl/basics/RangeSet.cpp
unsigned-integer-overflow:src/xrpld/app/main/BasicApp.cpp
unsigned-integer-overflow:src/xrpld/app/misc/detail/AmendmentTable.cpp
unsigned-integer-overflow:src/xrpld/app/misc/NetworkOPs.cpp
unsigned-integer-overflow:src/xrpld/app/paths/detail/StrandFlow.h
unsigned-integer-overflow:src/xrpld/app/tx/detail/NFTokenMint.cpp
unsigned-integer-overflow:src/xrpld/app/tx/detail/OracleSet.cpp
unsigned-integer-overflow:src/xrpld/rpc/detail/Role.cpp
unsigned-integer-overflow:src/xrpld/rpc/handlers/GetAggregatePrice.cpp
unsigned-integer-overflow:xrpl/basics/base_uint.h
unsigned-integer-overflow:xrpl/basics/DecayingSample.h
unsigned-integer-overflow:xrpl/beast/test/yield_to.h
unsigned-integer-overflow:xrpl/beast/xor_shift_engine.h
unsigned-integer-overflow:xrpl/nodestore/detail/varint.h
unsigned-integer-overflow:xrpl/peerfinder/detail/Counts.h
unsigned-integer-overflow:xrpl/protocol/nft.h
# Xrpld intentional overflows and operations
# STAmount uses intentional negation of INT64_MIN and overflow in arithmetic
signed-integer-overflow:src/libxrpl/protocol/STAmount.cpp
unsigned-integer-overflow:src/libxrpl/protocol/STAmount.cpp
# XRPAmount test intentional overflows
signed-integer-overflow:src/test/basics/XRPAmount_test.cpp
# Peerfinder intentional overflow in counter arithmetic
unsigned-integer-overflow:src/xrpld/peerfinder/detail/Counts.h
# Signed integer overflow suppressions
signed-integer-overflow:src/test/beast/LexicalCast_test.cpp
# External library suppressions
unsigned-integer-overflow:nudb/detail/xxhash.hpp
# Loan_test.cpp intentional underflow in test arithmetic
unsigned-integer-overflow:src/test/app/Loan_test.cpp
undefined:src/test/app/Loan_test.cpp
# Source tree restructured paths (libxrpl/tx/transactors/)
# These duplicate the xrpld/app/tx/detail entries above for the new layout
unsigned-integer-overflow:src/libxrpl/tx/transactors/oracle/OracleSet.cpp
undefined:src/libxrpl/tx/transactors/oracle/OracleSet.cpp
unsigned-integer-overflow:src/libxrpl/tx/transactors/nft/NFTokenMint.cpp
undefined:src/libxrpl/tx/transactors/nft/NFTokenMint.cpp
# Protobuf intentional overflows in hash functions
# Protobuf uses intentional unsigned overflow for hash computation (stringpiece.h:393)
unsigned-integer-overflow:google/protobuf/stubs/stringpiece.h
# gRPC intentional overflows
# gRPC uses intentional overflow in timer calculations
# gRPC intentional overflows in timer calculations
unsigned-integer-overflow:grpc
unsigned-integer-overflow:timer_manager.cc
# Standard library intentional overflows
# These are intentional overflows in random number generation and character conversion
unsigned-integer-overflow:__random/seed_seq.h
unsigned-integer-overflow:__charconv/traits.h
# Suppress errors in RocksDB
# RocksDB uses intentional unsigned integer overflows in hash functions and CRC calculations
# RocksDB intentional unsigned integer overflows in hash functions and CRC calculations
unsigned-integer-overflow:rocks*/*/util/xxhash.h
unsigned-integer-overflow:rocks*/*/util/xxph3.h
unsigned-integer-overflow:rocks*/*/util/hash.cc
@@ -221,13 +90,14 @@ unsigned-integer-overflow:rocks*/*/table/format.cc
unsigned-integer-overflow:rocks*/*/table/block_based/block_based_table_builder.cc
unsigned-integer-overflow:rocks*/*/table/block_based/reader_common.cc
unsigned-integer-overflow:rocks*/*/db/version_set.cc
# RocksDB misaligned loads (intentional for performance on ARM64)
alignment:rocks*/*/util/crc32c_arm64.cc
undefined:rocks*/*/util/crc32c_arm64.cc
undefined:rocks*/*/util/xxhash.h
# nudb intentional overflows in hash functions
unsigned-integer-overflow:nudb/detail/xxhash.hpp
alignment:nudb/detail/xxhash.hpp
undefined:nudb
# Snappy compression library intentional overflows
unsigned-integer-overflow:snappy.cc
@@ -239,10 +109,40 @@ unsigned-integer-overflow:absl/base/internal/low_level_alloc.cc
unsigned-integer-overflow:absl/hash/internal/hash.h
unsigned-integer-overflow:absl/container/internal/raw_hash_set.h
# Standard library intentional overflows in chrono duration arithmetic
# Standard library intentional overflows
unsigned-integer-overflow:basic_string.h
unsigned-integer-overflow:bits/chrono.h
unsigned-integer-overflow:bits/random.h
unsigned-integer-overflow:bits/random.tcc
unsigned-integer-overflow:bits/stl_algobase.h
unsigned-integer-overflow:bits/uniform_int_dist.h
unsigned-integer-overflow:string_view
unsigned-integer-overflow:__random/seed_seq.h
unsigned-integer-overflow:__charconv/traits.h
unsigned-integer-overflow:__chrono/duration.h
# Suppress undefined errors in RocksDB and nudb
undefined:rocks.*/*/util/crc32c_arm64.cc
undefined:rocks.*/*/util/xxhash.h
undefined:nudb
# =============================================================================
# Rippled code suppressions
# =============================================================================
# Signed integer negation (-value) in amount types.
# INT64_MIN cannot occur in practice due to domain invariants (mantissa ranges
# are well within int64_t bounds), but UBSan flags the pattern as potential
# signed overflow. Narrowed to operator- to avoid suppressing unrelated
# overflows anywhere in a stack trace containing these type names.
signed-integer-overflow:operator-*IOUAmount*
signed-integer-overflow:operator-*XRPAmount*
signed-integer-overflow:operator-*MPTAmount*
signed-integer-overflow:operator-*STAmount*
# STAmount::operator+ signed addition — operands are bounded by total supply
# (~10^17 for XRP, ~10^18 for MPT) so overflow cannot occur in practice.
signed-integer-overflow:operator+*STAmount*
# STAmount::getRate uses unsigned shift and addition
unsigned-integer-overflow:*STAmount*getRate*
# STAmount::serialize uses unsigned bitwise operations
unsigned-integer-overflow:*STAmount*serialize*
# nft::cipheredTaxon uses intentional uint32 wraparound (LCG permutation)
unsigned-integer-overflow:cipheredTaxon

View File

@@ -10,17 +10,20 @@
#include <iterator>
#include <limits>
#include <numeric>
#include <stdexcept>
#include <string>
#include <string_view>
#include <type_traits>
#include <utility>
#ifdef _MSC_VER
#pragma message("Using boost::multiprecision::uint128_t and int128_t")
#endif
using uint128_t = xrpl::detail::uint128_t;
using int128_t = xrpl::detail::int128_t;
#include <boost/multiprecision/cpp_int.hpp>
using uint128_t = boost::multiprecision::uint128_t;
using int128_t = boost::multiprecision::int128_t;
#else // !defined(_MSC_VER)
using uint128_t = __uint128_t;
using int128_t = __int128_t;
#endif // !defined(_MSC_VER)
namespace xrpl {
@@ -59,6 +62,9 @@ Number::setMantissaScale(MantissaRange::mantissa_scale scale)
// precision to an operation. This enables the final result
// to be correctly rounded to the internal precision of Number.
template <class T>
concept UnsignedMantissa = std::is_unsigned_v<T> || std::is_same_v<T, uint128_t>;
class Number::Guard
{
std::uint64_t digits_{0}; // 16 decimal guard digits
@@ -92,7 +98,7 @@ public:
round() const noexcept;
// Modify the result to the correctly rounded value
template <detail::UnsignedMantissa T>
template <UnsignedMantissa T>
void
doRoundUp(
bool& negative,
@@ -100,22 +106,22 @@ public:
int& exponent,
internalrep const& minMantissa,
internalrep const& maxMantissa,
std::string_view location);
std::string location);
// Modify the result to the correctly rounded value
template <detail::UnsignedMantissa T>
template <UnsignedMantissa T>
void
doRoundDown(bool& negative, T& mantissa, int& exponent, internalrep const& minMantissa);
// Modify the result to the correctly rounded value
void
doRound(internalrep& drops, std::string_view location) const;
doRound(rep& drops, std::string location) const;
private:
void
doPush(unsigned d) noexcept;
template <detail::UnsignedMantissa T>
template <UnsignedMantissa T>
void
bringIntoRange(bool& negative, T& mantissa, int& exponent, internalrep const& minMantissa);
};
@@ -202,7 +208,7 @@ Number::Guard::round() const noexcept
return 0;
}
template <detail::UnsignedMantissa T>
template <UnsignedMantissa T>
void
Number::Guard::bringIntoRange(
bool& negative,
@@ -221,11 +227,13 @@ Number::Guard::bringIntoRange(
{
constexpr Number zero = Number{};
std::tie(negative, mantissa, exponent) = zero.toInternal();
negative = zero.negative_;
mantissa = zero.mantissa_;
exponent = zero.exponent_;
}
}
template <detail::UnsignedMantissa T>
template <UnsignedMantissa T>
void
Number::Guard::doRoundUp(
bool& negative,
@@ -233,7 +241,7 @@ Number::Guard::doRoundUp(
int& exponent,
internalrep const& minMantissa,
internalrep const& maxMantissa,
std::string_view location)
std::string location)
{
auto r = round();
if (r == 1 || (r == 0 && (mantissa & 1) == 1))
@@ -241,7 +249,7 @@ Number::Guard::doRoundUp(
++mantissa;
// Ensure mantissa after incrementing fits within both the
// min/maxMantissa range and is a valid "rep".
if (mantissa > maxMantissa)
if (mantissa > maxMantissa || mantissa > maxRep)
{
mantissa /= 10;
++exponent;
@@ -252,7 +260,7 @@ Number::Guard::doRoundUp(
Throw<std::overflow_error>(std::string(location));
}
template <detail::UnsignedMantissa T>
template <UnsignedMantissa T>
void
Number::Guard::doRoundDown(
bool& negative,
@@ -275,25 +283,26 @@ Number::Guard::doRoundDown(
// Modify the result to the correctly rounded value
void
Number::Guard::doRound(internalrep& drops, std::string_view location) const
Number::Guard::doRound(rep& drops, std::string location) const
{
auto r = round();
if (r == 1 || (r == 0 && (drops & 1) == 1))
{
auto const& range = range_.get();
if (drops >= range.max)
if (drops >= maxRep)
{
static_assert(sizeof(internalrep) == sizeof(rep));
// This should be impossible, because it's impossible to represent
// "largestMantissa + 0.6" in Number, regardless of the scale. There aren't
// enough digits available. You'd either get a mantissa of "largestMantissa"
// or "largestMantissa / 10 + 1", neither of which will round up when
// "maxRep + 0.6" in Number, regardless of the scale. There aren't
// enough digits available. You'd either get a mantissa of "maxRep"
// or "(maxRep + 1) / 10", neither of which will round up when
// converting to rep, though the latter might overflow _before_
// rounding.
Throw<std::overflow_error>(std::string(location)); // LCOV_EXCL_LINE
}
++drops;
}
if (is_negative())
drops = -drops;
}
// Number
@@ -308,6 +317,10 @@ Number::externalToInternal(rep mantissa)
// If the mantissa is already positive, just return it
if (mantissa >= 0)
return mantissa;
// If the mantissa is negative, but fits within the positive range of rep,
// return it negated
if (mantissa >= -std::numeric_limits<rep>::max())
return -mantissa;
// If the mantissa doesn't fit within the positive range, convert to
// int128_t, negate that, and cast it back down to the internalrep
@@ -317,127 +330,10 @@ Number::externalToInternal(rep mantissa)
return static_cast<internalrep>(-temp);
}
/** Breaks down the number into components, potentially de-normalizing it.
*
* Ensures that the mantissa always has range_.log + 1 digits.
*
*/
template <detail::UnsignedMantissa Rep>
std::tuple<bool, Rep, int>
Number::toInternal(MantissaRange const& range) const
{
auto exponent = exponent_;
bool const negative = mantissa_ < 0;
// It should be impossible for mantissa_ to be INT64_MIN, but use externalToInternal just in
// case.
Rep mantissa = static_cast<Rep>(externalToInternal(mantissa_));
auto const internalMin = range.internalMin;
auto const minMantissa = range.min;
if (mantissa != 0 && mantissa >= minMantissa && mantissa < internalMin)
{
// Ensure the mantissa has the correct number of digits
mantissa *= 10;
--exponent;
XRPL_ASSERT_PARTS(
mantissa >= internalMin && mantissa < internalMin * 10,
"xrpl::Number::toInternal()",
"Number is within reference range and has 'log' digits");
}
return {negative, mantissa, exponent};
}
/** Breaks down the number into components, potentially de-normalizing it.
*
* Ensures that the mantissa always has exactly range_.log + 1 digits.
*
*/
template <detail::UnsignedMantissa Rep>
std::tuple<bool, Rep, int>
Number::toInternal() const
{
return toInternal(range_);
}
/** Rebuilds the number from components.
*
* If "expectNormal" is true, the values are expected to be normalized - all
* in their valid ranges.
*
* If "expectNormal" is false, the values are expected to be "near
* normalized", meaning that the mantissa has to be modified at most once to
* bring it back into range.
*
*/
template <bool expectNormal, detail::UnsignedMantissa Rep>
void
Number::fromInternal(bool negative, Rep mantissa, int exponent, MantissaRange const* pRange)
{
if constexpr (std::is_same_v<std::bool_constant<expectNormal>, std::false_type>)
{
if (!pRange)
throw std::runtime_error("Missing range to Number::fromInternal!");
auto const& range = *pRange;
auto const maxMantissa = range.max;
auto const minMantissa = range.min;
XRPL_ASSERT_PARTS(
mantissa >= minMantissa, "xrpl::Number::fromInternal", "mantissa large enough");
if (mantissa > maxMantissa || mantissa < minMantissa)
{
normalize(negative, mantissa, exponent, range.min, maxMantissa);
}
XRPL_ASSERT_PARTS(
mantissa >= minMantissa && mantissa <= maxMantissa,
"xrpl::Number::fromInternal",
"mantissa in range");
}
// mantissa is unsigned, but it might not be uint64
mantissa_ = static_cast<rep>(static_cast<internalrep>(mantissa));
if (negative)
mantissa_ = -mantissa_;
exponent_ = exponent;
XRPL_ASSERT_PARTS(
(pRange && isnormal(*pRange)) || isnormal(),
"xrpl::Number::fromInternal",
"Number is normalized");
}
/** Rebuilds the number from components.
*
* If "expectNormal" is true, the values are expected to be normalized - all in
* their valid ranges.
*
* If "expectNormal" is false, the values are expected to be "near normalized",
* meaning that the mantissa has to be modified at most once to bring it back
* into range.
*
*/
template <bool expectNormal, detail::UnsignedMantissa Rep>
void
Number::fromInternal(bool negative, Rep mantissa, int exponent)
{
MantissaRange const* pRange = nullptr;
if constexpr (std::is_same_v<std::bool_constant<expectNormal>, std::false_type>)
{
pRange = &Number::range_.get();
}
fromInternal(negative, mantissa, exponent, pRange);
}
constexpr Number
Number::oneSmall()
{
return Number{
false, Number::smallRange.internalMin, -Number::smallRange.log, Number::unchecked{}};
return Number{false, Number::smallRange.min, -Number::smallRange.log, Number::unchecked{}};
};
constexpr Number oneSml = Number::oneSmall();
@@ -445,86 +341,103 @@ constexpr Number oneSml = Number::oneSmall();
constexpr Number
Number::oneLarge()
{
return Number{
false, Number::largeRange.internalMin, -Number::largeRange.log, Number::unchecked{}};
return Number{false, Number::largeRange.min, -Number::largeRange.log, Number::unchecked{}};
};
constexpr Number oneLrg = Number::oneLarge();
Number
Number::one(MantissaRange const& range)
Number::one()
{
if (&range == &smallRange)
if (&range_.get() == &smallRange)
return oneSml;
XRPL_ASSERT(&range == &largeRange, "Number::one() : valid range");
XRPL_ASSERT(&range_.get() == &largeRange, "Number::one() : valid range_");
return oneLrg;
}
Number
Number::one()
{
return one(range_);
}
// Use the member names in this static function for now so the diff is cleaner
// TODO: Rename the function parameters to get rid of the "_" suffix
template <class T>
void
doNormalize(
bool& negative,
T& mantissa,
int& exponent,
T& mantissa_,
int& exponent_,
MantissaRange::rep const& minMantissa,
MantissaRange::rep const& maxMantissa)
{
auto constexpr minExponent = Number::minExponent;
auto constexpr maxExponent = Number::maxExponent;
auto constexpr maxRep = Number::maxRep;
using Guard = Number::Guard;
constexpr Number zero = Number{};
auto const& range = Number::range_.get();
if (mantissa == 0 || (mantissa < minMantissa && exponent <= minExponent))
if (mantissa_ == 0)
{
std::tie(negative, mantissa, exponent) = zero.toInternal(range);
mantissa_ = zero.mantissa_;
exponent_ = zero.exponent_;
negative = zero.negative_;
return;
}
auto m = mantissa;
while ((m < minMantissa) && (exponent > minExponent))
auto m = mantissa_;
while ((m < minMantissa) && (exponent_ > minExponent))
{
m *= 10;
--exponent;
--exponent_;
}
Guard g;
if (negative)
g.set_negative();
while (m > maxMantissa)
{
if (exponent >= maxExponent)
if (exponent_ >= maxExponent)
throw std::overflow_error("Number::normalize 1");
g.push(m % 10);
m /= 10;
++exponent;
++exponent_;
}
if ((exponent < minExponent) || (m == 0))
if ((exponent_ < minExponent) || (m < minMantissa))
{
std::tie(negative, mantissa, exponent) = zero.toInternal(range);
mantissa_ = zero.mantissa_;
exponent_ = zero.exponent_;
negative = zero.negative_;
return;
}
XRPL_ASSERT_PARTS(m <= maxMantissa, "xrpl::doNormalize", "intermediate mantissa fits in int64");
mantissa = m;
g.doRoundUp(negative, mantissa, exponent, minMantissa, maxMantissa, "Number::normalize 2");
// When using the largeRange, "m" needs fit within an int64, even if
// the final mantissa_ is going to end up larger to fit within the
// MantissaRange. Cut it down here so that the rounding will be done while
// it's smaller.
//
// Example: 9,900,000,000,000,123,456 > 9,223,372,036,854,775,807,
// so "m" will be modified to 990,000,000,000,012,345. Then that value
// will be rounded to 990,000,000,000,012,345 or
// 990,000,000,000,012,346, depending on the rounding mode. Finally,
// mantissa_ will be "m*10" so it fits within the range, and end up as
// 9,900,000,000,000,123,450 or 9,900,000,000,000,123,460.
// mantissa() will return mantissa_ / 10, and exponent() will return
// exponent_ + 1.
if (m > maxRep)
{
if (exponent_ >= maxExponent)
throw std::overflow_error("Number::normalize 1.5");
g.push(m % 10);
m /= 10;
++exponent_;
}
// Before modification, m should be within the min/max range. After
// modification, it must be less than maxRep. In other words, the original
// value should have been no more than maxRep * 10.
// (maxRep * 10 > maxMantissa)
XRPL_ASSERT_PARTS(m <= maxRep, "xrpl::doNormalize", "intermediate mantissa fits in int64");
mantissa_ = m;
g.doRoundUp(negative, mantissa_, exponent_, minMantissa, maxMantissa, "Number::normalize 2");
XRPL_ASSERT_PARTS(
mantissa >= minMantissa && mantissa <= maxMantissa,
mantissa_ >= minMantissa && mantissa_ <= maxMantissa,
"xrpl::doNormalize",
"final mantissa fits in range");
XRPL_ASSERT_PARTS(
exponent >= minExponent && exponent <= maxExponent,
"xrpl::doNormalize",
"final exponent fits in range");
}
template <>
@@ -563,20 +476,11 @@ Number::normalize<unsigned long>(
doNormalize(negative, mantissa, exponent, minMantissa, maxMantissa);
}
void
Number::normalize(MantissaRange const& range)
{
auto [negative, mantissa, exponent] = toInternal(range);
normalize(negative, mantissa, exponent, range.min, range.max);
fromInternal(negative, mantissa, exponent, &range);
}
void
Number::normalize()
{
normalize(range_);
auto const& range = range_.get();
normalize(negative_, mantissa_, exponent_, range.min, range.max);
}
// Copy the number, but set a new exponent. Because the mantissa doesn't change,
@@ -586,33 +490,21 @@ Number
Number::shiftExponent(int exponentDelta) const
{
XRPL_ASSERT_PARTS(isnormal(), "xrpl::Number::shiftExponent", "normalized");
Number result = *this;
result.exponent_ += exponentDelta;
if (result.exponent_ >= maxExponent)
auto const newExponent = exponent_ + exponentDelta;
if (newExponent >= maxExponent)
throw std::overflow_error("Number::shiftExponent");
if (result.exponent_ < minExponent)
if (newExponent < minExponent)
{
return Number{};
}
Number const result{negative_, mantissa_, newExponent, unchecked{}};
XRPL_ASSERT_PARTS(result.isnormal(), "xrpl::Number::shiftExponent", "result is normalized");
return result;
}
Number::Number(bool negative, internalrep mantissa, int exponent, normalized)
{
auto const& range = range_.get();
normalize(negative, mantissa, exponent, range.min, range.max);
fromInternal(negative, mantissa, exponent, &range);
}
Number&
Number::operator+=(Number const& y)
{
auto const& range = range_.get();
constexpr Number zero = Number{};
if (y == zero)
return *this;
@@ -627,8 +519,7 @@ Number::operator+=(Number const& y)
return *this;
}
XRPL_ASSERT(
isnormal(range) && y.isnormal(range), "xrpl::Number::operator+=(Number) : is normal");
XRPL_ASSERT(isnormal() && y.isnormal(), "xrpl::Number::operator+=(Number) : is normal");
// *n = negative
// *s = sign
// *m = mantissa
@@ -636,10 +527,13 @@ Number::operator+=(Number const& y)
// Need to use uint128_t, because large mantissas can overflow when added
// together.
auto [xn, xm, xe] = toInternal<uint128_t>(range);
auto [yn, ym, ye] = y.toInternal<uint128_t>(range);
bool xn = negative_;
uint128_t xm = mantissa_;
auto xe = exponent_;
bool const yn = y.negative_;
uint128_t ym = y.mantissa_;
auto ye = y.exponent_;
Guard g;
if (xe < ye)
{
@@ -664,13 +558,14 @@ Number::operator+=(Number const& y)
} while (xe > ye);
}
auto const& range = range_.get();
auto const& minMantissa = range.min;
auto const& maxMantissa = range.max;
if (xn == yn)
{
xm += ym;
if (xm > maxMantissa)
if (xm > maxMantissa || xm > maxRep)
{
g.push(xm % 10);
xm /= 10;
@@ -690,7 +585,7 @@ Number::operator+=(Number const& y)
xe = ye;
xn = yn;
}
while (xm < minMantissa)
while (xm < minMantissa && xm * 10 <= maxRep)
{
xm *= 10;
xm -= g.pop();
@@ -699,8 +594,10 @@ Number::operator+=(Number const& y)
g.doRoundDown(xn, xm, xe, minMantissa);
}
normalize(xn, xm, xe, minMantissa, maxMantissa);
fromInternal(xn, xm, xe, &range);
negative_ = xn;
mantissa_ = static_cast<internalrep>(xm);
exponent_ = xe;
normalize();
return *this;
}
@@ -735,8 +632,6 @@ divu10(uint128_t& u)
Number&
Number::operator*=(Number const& y)
{
auto const& range = range_.get();
constexpr Number zero = Number{};
if (*this == zero)
return *this;
@@ -750,11 +645,15 @@ Number::operator*=(Number const& y)
// *m = mantissa
// *e = exponent
auto [xn, xm, xe] = toInternal(range);
bool const xn = negative_;
int const xs = xn ? -1 : 1;
internalrep xm = mantissa_;
auto xe = exponent_;
auto [yn, ym, ye] = y.toInternal(range);
bool const yn = y.negative_;
int const ys = yn ? -1 : 1;
internalrep const ym = y.mantissa_;
auto ye = y.exponent_;
auto zm = uint128_t(xm) * uint128_t(ym);
auto ze = xe + ye;
@@ -764,10 +663,11 @@ Number::operator*=(Number const& y)
if (zn)
g.set_negative();
auto const& range = range_.get();
auto const& minMantissa = range.min;
auto const& maxMantissa = range.max;
while (zm > maxMantissa)
while (zm > maxMantissa || zm > maxRep)
{
// The following is optimization for:
// g.push(static_cast<unsigned>(zm % 10));
@@ -784,17 +684,17 @@ Number::operator*=(Number const& y)
minMantissa,
maxMantissa,
"Number::multiplication overflow : exponent is " + std::to_string(xe));
negative_ = zn;
mantissa_ = xm;
exponent_ = xe;
normalize(zn, xm, xe, minMantissa, maxMantissa);
fromInternal(zn, xm, xe, &range);
normalize();
return *this;
}
Number&
Number::operator/=(Number const& y)
{
auto const& range = range_.get();
constexpr Number zero = Number{};
if (y == zero)
throw std::overflow_error("Number: divide by 0");
@@ -807,12 +707,17 @@ Number::operator/=(Number const& y)
// *m = mantissa
// *e = exponent
auto [np, nm, ne] = toInternal(range);
bool const np = negative_;
int const ns = (np ? -1 : 1);
auto nm = mantissa_;
auto ne = exponent_;
auto [dp, dm, de] = y.toInternal(range);
bool const dp = y.negative_;
int const ds = (dp ? -1 : 1);
auto dm = y.mantissa_;
auto de = y.exponent_;
auto const& range = range_.get();
auto const& minMantissa = range.min;
auto const& maxMantissa = range.max;
@@ -824,7 +729,7 @@ Number::operator/=(Number const& y)
// f can be up to 10^(38-19) = 10^19 safely
static_assert(smallRange.log == 15);
static_assert(largeRange.log == 18);
bool const small = range.scale == MantissaRange::small;
bool const small = Number::getMantissaScale() == MantissaRange::small;
uint128_t const f = small ? 100'000'000'000'000'000 : 10'000'000'000'000'000'000ULL;
XRPL_ASSERT_PARTS(f >= minMantissa * 10, "Number::operator/=", "factor expected size");
@@ -874,8 +779,10 @@ Number::operator/=(Number const& y)
}
}
normalize(zn, zm, ze, minMantissa, maxMantissa);
fromInternal(zn, zm, ze, &range);
XRPL_ASSERT_PARTS(isnormal(range), "xrpl::Number::operator/=", "result is normalized");
negative_ = zn;
mantissa_ = static_cast<internalrep>(zm);
exponent_ = ze;
XRPL_ASSERT_PARTS(isnormal(), "xrpl::Number::operator/=", "result is normalized");
return *this;
}
@@ -883,36 +790,30 @@ Number::operator/=(Number const& y)
Number::
operator rep() const
{
auto const m = mantissa();
internalrep drops = externalToInternal(m);
if (drops == 0)
return drops;
rep drops = mantissa();
int offset = exponent();
Guard g;
if (m < 0)
if (drops != 0)
{
g.set_negative();
if (negative_)
{
g.set_negative();
drops = -drops;
}
for (; offset < 0; ++offset)
{
g.push(drops % 10);
drops /= 10;
}
for (; offset > 0; --offset)
{
if (drops > maxRep / 10)
throw std::overflow_error("Number::operator rep() overflow");
drops *= 10;
}
g.doRound(drops, "Number::operator rep() rounding overflow");
}
for (; offset < 0; ++offset)
{
g.push(drops % 10);
drops /= 10;
}
for (; offset > 0; --offset)
{
if (drops >= largeRange.min)
throw std::overflow_error("Number::operator rep() overflow");
drops *= 10;
}
g.doRound(drops, "Number::operator rep() rounding overflow");
if (g.is_negative())
return -drops;
else
return drops;
return drops;
}
Number
@@ -936,22 +837,19 @@ Number::truncate() const noexcept
std::string
to_string(Number const& amount)
{
auto const& range = Number::range_.get();
// keep full internal accuracy, but make more human friendly if possible
constexpr Number zero = Number{};
if (amount == zero)
return "0";
// The mantissa must have a set number of decimal places for this to work
auto [negative, mantissa, exponent] = amount.toInternal(range);
auto exponent = amount.exponent_;
auto mantissa = amount.mantissa_;
bool const negative = amount.negative_;
// Use scientific notation for exponents that are too small or too large
auto const rangeLog = range.log;
if (((exponent != 0 && amount.exponent() != 0) &&
((exponent < -(rangeLog + 10)) || (exponent > -(rangeLog - 10)))))
auto const rangeLog = Number::mantissaLog();
if (((exponent != 0) && ((exponent < -(rangeLog + 10)) || (exponent > -(rangeLog - 10)))))
{
// Remove trailing zeroes from the mantissa.
while (mantissa != 0 && mantissa % 10 == 0 && exponent < Number::maxExponent)
{
mantissa /= 10;
@@ -959,11 +857,8 @@ to_string(Number const& amount)
}
std::string ret = negative ? "-" : "";
ret.append(std::to_string(mantissa));
if (exponent != 0)
{
ret.append(1, 'e');
ret.append(std::to_string(exponent));
}
ret.append(1, 'e');
ret.append(std::to_string(exponent));
return ret;
}
@@ -1051,11 +946,20 @@ power(Number const& f, unsigned n)
return r;
}
// Returns f^(1/d)
// Uses NewtonRaphson iterations until the result stops changing
// to find the non-negative root of the polynomial g(x) = x^d - f
// This function, and power(Number f, unsigned n, unsigned d)
// treat corner cases such as 0 roots as advised by Annex F of
// the C standard, which itself is consistent with the IEEE
// floating point standards.
Number
Number::root(MantissaRange const& range, Number f, unsigned d)
root(Number f, unsigned d)
{
constexpr Number zero = Number{};
auto const one = Number::one(range);
auto const one = Number::one();
if (f == one || d == 1)
return f;
@@ -1072,28 +976,21 @@ Number::root(MantissaRange const& range, Number f, unsigned d)
if (f == zero)
return f;
auto const [e, di] = [&]() {
auto const exponent = std::get<2>(f.toInternal(range));
// Scale f into the range (0, 1) such that the scale change (e) is a
// multiple of the root (d)
auto e = exponent + range.log + 1;
auto const di = static_cast<int>(d);
auto ex = [e = e, di = di]() // Euclidean remainder of e/d
{
int const k = (e >= 0 ? e : e - (di - 1)) / di;
int const k2 = e - (k * di);
if (k2 == 0)
return 0;
return di - k2;
}();
e += ex;
f = f.shiftExponent(-e); // f /= 10^e;
return std::make_tuple(e, di);
// Scale f into the range (0, 1) such that f's exponent is a multiple of d
auto e = f.exponent_ + Number::mantissaLog() + 1;
auto const di = static_cast<int>(d);
auto ex = [e = e, di = di]() // Euclidean remainder of e/d
{
int const k = (e >= 0 ? e : e - (di - 1)) / di;
int const k2 = e - (k * di);
if (k2 == 0)
return 0;
return di - k2;
}();
e += ex;
f = f.shiftExponent(-e); // f /= 10^e;
XRPL_ASSERT_PARTS(e % di == 0, "xrpl::root(Number, unsigned)", "e is divisible by d");
XRPL_ASSERT_PARTS(f.isnormal(range), "xrpl::root(Number, unsigned)", "f is normalized");
XRPL_ASSERT_PARTS(f.isnormal(), "xrpl::root(Number, unsigned)", "f is normalized");
bool neg = false;
if (f < zero)
{
@@ -1126,33 +1023,15 @@ Number::root(MantissaRange const& range, Number f, unsigned d)
// return r * 10^(e/d) to reverse scaling
auto const result = r.shiftExponent(e / di);
XRPL_ASSERT_PARTS(
result.isnormal(range), "xrpl::root(Number, unsigned)", "result is normalized");
XRPL_ASSERT_PARTS(result.isnormal(), "xrpl::root(Number, unsigned)", "result is normalized");
return result;
}
// Returns f^(1/d)
// Uses NewtonRaphson iterations until the result stops changing
// to find the non-negative root of the polynomial g(x) = x^d - f
// This function, and power(Number f, unsigned n, unsigned d)
// treat corner cases such as 0 roots as advised by Annex F of
// the C standard, which itself is consistent with the IEEE
// floating point standards.
Number
root(Number f, unsigned d)
{
auto const& range = Number::range_.get();
return Number::root(range, f, d);
}
Number
root2(Number f)
{
auto const& range = Number::range_.get();
constexpr Number zero = Number{};
auto const one = Number::one(range);
auto const one = Number::one();
if (f == one)
return f;
@@ -1161,18 +1040,12 @@ root2(Number f)
if (f == zero)
return f;
auto const e = [&]() {
auto const exponent = std::get<2>(f.toInternal(range));
// Scale f into the range (0, 1) such that f's exponent is a
// multiple of d
auto e = exponent + range.log + 1;
if (e % 2 != 0)
++e;
f = f.shiftExponent(-e); // f /= 10^e;
return e;
}();
XRPL_ASSERT_PARTS(f.isnormal(range), "xrpl::root2(Number)", "f is normalized");
// Scale f into the range (0, 1) such that f's exponent is a multiple of d
auto e = f.exponent_ + Number::mantissaLog() + 1;
if (e % 2 != 0)
++e;
f = f.shiftExponent(-e); // f /= 10^e;
XRPL_ASSERT_PARTS(f.isnormal(), "xrpl::root2(Number)", "f is normalized");
// Quadratic least squares curve fit of f^(1/d) in the range [0, 1]
auto const D = 105;
@@ -1194,7 +1067,7 @@ root2(Number f)
// return r * 10^(e/2) to reverse scaling
auto const result = r.shiftExponent(e / 2);
XRPL_ASSERT_PARTS(result.isnormal(range), "xrpl::root2(Number)", "result is normalized");
XRPL_ASSERT_PARTS(result.isnormal(), "xrpl::root2(Number)", "result is normalized");
return result;
}
@@ -1204,10 +1077,8 @@ root2(Number f)
Number
power(Number const& f, unsigned n, unsigned d)
{
auto const& range = Number::range_.get();
constexpr Number zero = Number{};
auto const one = Number::one(range);
auto const one = Number::one();
if (f == one)
return f;
@@ -1229,7 +1100,7 @@ power(Number const& f, unsigned n, unsigned d)
d /= g;
if ((n % 2) == 1 && (d % 2) == 0 && f < zero)
throw std::overflow_error("Number::power nan");
return Number::root(range, power(f, n), d);
return root(power(f, n), d);
}
} // namespace xrpl

View File

@@ -107,7 +107,7 @@ encode(void* dest, void const* src, std::size_t len)
char const* in = static_cast<char const*>(src);
auto const tab = base64::get_alphabet();
for (auto n = len / 3; n != 0u; --n)
for (auto n = len / 3; n > 0; --n)
{
*out++ = tab[(in[0] & 0xfc) >> 2];
*out++ = tab[((in[0] & 0x03) << 4) + ((in[1] & 0xf0) >> 4)];

View File

@@ -40,10 +40,9 @@ public:
test_limits()
{
auto const scale = Number::getMantissaScale();
auto const minMantissa = Number::minMantissa();
testcase << "test_limits " << to_string(scale) << ", " << minMantissa;
testcase << "test_limits " << to_string(scale);
bool caught = false;
auto const minMantissa = Number::minMantissa();
try
{
[[maybe_unused]] Number const x =
@@ -68,9 +67,8 @@ public:
__LINE__);
test(Number{false, minMantissa, -32769, Number::normalized{}}, Number{}, __LINE__);
test(
// Use 1501 to force rounding up
Number{false, minMantissa, 32000, Number::normalized{}} * 1'000 +
Number{false, 1'501, 32000, Number::normalized{}},
Number{false, 1'500, 32000, Number::normalized{}},
Number{false, minMantissa + 2, 32003, Number::normalized{}},
__LINE__);
// 9,223,372,036,854,775,808
@@ -179,12 +177,8 @@ public:
{Number{true, 9'999'999'999'999'999'999ULL, -37, Number::normalized{}},
Number{1'000'000'000'000'000'000, -18},
Number{false, 9'999'999'999'999'999'990ULL, -19, Number::normalized{}}},
{Number{Number::largestMantissa},
Number{6, -1},
Number{Number::largestMantissa / 10, 1}},
{Number{Number::largestMantissa - 1},
Number{1, 0},
Number{Number::largestMantissa}},
{Number{Number::maxRep}, Number{6, -1}, Number{Number::maxRep / 10, 1}},
{Number{Number::maxRep - 1}, Number{1, 0}, Number{Number::maxRep}},
// Test extremes
{
// Each Number operand rounds up, so the actual mantissa is
@@ -194,18 +188,11 @@ public:
Number{2, 19},
},
{
// Does not round. Mantissas are going to be >
// largestMantissa, so if added together as uint64_t's, the
// result will overflow. With addition using uint128_t,
// there's no problem. After normalizing, the resulting
// mantissa ends up less than largestMantissa.
Number{false, Number::largestMantissa, 0, Number::normalized{}},
Number{false, Number::largestMantissa, 0, Number::normalized{}},
Number{false, Number::largestMantissa * 2, 0, Number::normalized{}},
},
{
// These mantissas round down, so adding them together won't
// have any consequences.
// Does not round. Mantissas are going to be > maxRep, so if
// added together as uint64_t's, the result will overflow.
// With addition using uint128_t, there's no problem. After
// normalizing, the resulting mantissa ends up less than
// maxRep.
Number{false, 9'999'999'999'999'999'990ULL, 0, Number::normalized{}},
Number{false, 9'999'999'999'999'999'990ULL, 0, Number::normalized{}},
Number{false, 1'999'999'999'999'999'998ULL, 1, Number::normalized{}},
@@ -298,16 +285,14 @@ public:
{Number{1'000'000'000'000'000'001, -18},
Number{1'000'000'000'000'000'000, -18},
Number{1'000'000'000'000'000'000, -36}},
{Number{Number::largestMantissa},
Number{6, -1},
Number{Number::largestMantissa - 1}},
{Number{false, Number::largestMantissa + 1, 0, Number::normalized{}},
{Number{Number::maxRep}, Number{6, -1}, Number{Number::maxRep - 1}},
{Number{false, Number::maxRep + 1, 0, Number::normalized{}},
Number{1, 0},
Number{(Number::largestMantissa / 10) + 1, 1}},
{Number{false, Number::largestMantissa + 1, 0, Number::normalized{}},
Number{(Number::maxRep / 10) + 1, 1}},
{Number{false, Number::maxRep + 1, 0, Number::normalized{}},
Number{3, 0},
Number{Number::largestMantissa}},
{power(2, 63), Number{3, 0}, Number{Number::largestMantissa}},
Number{Number::maxRep}},
{power(2, 63), Number{3, 0}, Number{Number::maxRep}},
});
auto test = [this](auto const& c) {
for (auto const& [x, y, z] : c)
@@ -328,30 +313,20 @@ public:
}
}
static std::uint64_t
getMaxInternalMantissa()
{
return static_cast<std::uint64_t>(
static_cast<std::int64_t>(power(10, Number::mantissaLog()))) *
10 -
1;
}
void
test_mul()
{
auto const scale = Number::getMantissaScale();
testcase << "test_mul " << to_string(scale);
// Case: Factor 1, Factor 2, Expected product, Line number
using Case = std::tuple<Number, Number, Number, int>;
using Case = std::tuple<Number, Number, Number>;
auto test = [this](auto const& c) {
for (auto const& [x, y, z, line] : c)
for (auto const& [x, y, z] : c)
{
auto const result = x * y;
std::stringstream ss;
ss << x << " * " << y << " = " << result << ". Expected: " << z;
BEAST_EXPECTS(result == z, ss.str() + " line: " + std::to_string(line));
BEAST_EXPECTS(result == z, ss.str());
}
};
auto tests = [&](auto const& cSmall, auto const& cLarge) {
@@ -365,97 +340,70 @@ public:
}
};
auto const maxMantissa = Number::maxMantissa();
auto const maxInternalMantissa = getMaxInternalMantissa();
saveNumberRoundMode const save{Number::setround(Number::to_nearest)};
{
auto const cSmall = std::to_array<Case>({
{Number{7}, Number{8}, Number{56}, __LINE__},
{Number{7}, Number{8}, Number{56}},
{Number{1414213562373095, -15},
Number{1414213562373095, -15},
Number{2000000000000000, -15},
__LINE__},
Number{2000000000000000, -15}},
{Number{-1414213562373095, -15},
Number{1414213562373095, -15},
Number{-2000000000000000, -15},
__LINE__},
Number{-2000000000000000, -15}},
{Number{-1414213562373095, -15},
Number{-1414213562373095, -15},
Number{2000000000000000, -15},
__LINE__},
Number{2000000000000000, -15}},
{Number{3214285714285706, -15},
Number{3111111111111119, -15},
Number{1000000000000000, -14},
__LINE__},
{Number{1000000000000000, -32768},
Number{1000000000000000, -32768},
Number{0},
__LINE__},
Number{1000000000000000, -14}},
{Number{1000000000000000, -32768}, Number{1000000000000000, -32768}, Number{0}},
// Maximum mantissa range
{Number{9'999'999'999'999'999, 0},
Number{9'999'999'999'999'999, 0},
Number{9'999'999'999'999'998, 16},
__LINE__},
Number{9'999'999'999'999'998, 16}},
});
auto const cLarge = std::to_array<Case>({
// Note that items with extremely large mantissas need to be
// calculated, because otherwise they overflow uint64. Items
// from C with larger mantissa
{Number{7}, Number{8}, Number{56}, __LINE__},
{Number{7}, Number{8}, Number{56}},
{Number{1414213562373095, -15},
Number{1414213562373095, -15},
Number{1999999999999999862, -18},
__LINE__},
Number{1999999999999999862, -18}},
{Number{-1414213562373095, -15},
Number{1414213562373095, -15},
Number{-1999999999999999862, -18},
__LINE__},
Number{-1999999999999999862, -18}},
{Number{-1414213562373095, -15},
Number{-1414213562373095, -15},
Number{1999999999999999862, -18},
__LINE__},
Number{1999999999999999862, -18}},
{Number{3214285714285706, -15},
Number{3111111111111119, -15},
Number{false, 9'999'999'999'999'999'579ULL, -18, Number::normalized{}},
__LINE__},
Number{false, 9'999'999'999'999'999'579ULL, -18, Number::normalized{}}},
{Number{1000000000000000000, -32768},
Number{1000000000000000000, -32768},
Number{0},
__LINE__},
Number{0}},
// Items from cSmall expanded for the larger mantissa,
// except duplicates. Sadly, it looks like sqrt(2)^2 != 2
// with higher precision
{Number{1414213562373095049, -18},
Number{1414213562373095049, -18},
Number{2000000000000000001, -18},
__LINE__},
Number{2000000000000000001, -18}},
{Number{-1414213562373095048, -18},
Number{1414213562373095048, -18},
Number{-1999999999999999998, -18},
__LINE__},
Number{-1999999999999999998, -18}},
{Number{-1414213562373095048, -18},
Number{-1414213562373095049, -18},
Number{1999999999999999999, -18},
__LINE__},
{Number{3214285714285714278, -18},
Number{3111111111111111119, -18},
Number{10, 0},
__LINE__},
// Maximum internal mantissa range - rounds up to 1e19
{Number{false, maxInternalMantissa, 0, Number::normalized{}},
Number{false, maxInternalMantissa, 0, Number::normalized{}},
Number{1, 38},
__LINE__},
// Maximum actual mantissa range - same as int64 range
Number{1999999999999999999, -18}},
{Number{3214285714285714278, -18}, Number{3111111111111111119, -18}, Number{10, 0}},
// Maximum mantissa range - rounds up to 1e19
{Number{false, maxMantissa, 0, Number::normalized{}},
Number{false, maxMantissa, 0, Number::normalized{}},
Number{85'070'591'730'234'615'85, 19},
__LINE__},
Number{1, 38}},
// Maximum int64 range
{Number{Number::largestMantissa, 0},
Number{Number::largestMantissa, 0},
Number{85'070'591'730'234'615'85, 19},
__LINE__},
{Number{Number::maxRep, 0},
Number{Number::maxRep, 0},
Number{85'070'591'730'234'615'85, 19}},
});
tests(cSmall, cLarge);
}
@@ -463,90 +411,66 @@ public:
testcase << "test_mul " << to_string(Number::getMantissaScale()) << " towards_zero";
{
auto const cSmall = std::to_array<Case>(
{{Number{7}, Number{8}, Number{56}, __LINE__},
{{Number{7}, Number{8}, Number{56}},
{Number{1414213562373095, -15},
Number{1414213562373095, -15},
Number{1999999999999999, -15},
__LINE__},
Number{1999999999999999, -15}},
{Number{-1414213562373095, -15},
Number{1414213562373095, -15},
Number{-1999999999999999, -15},
__LINE__},
Number{-1999999999999999, -15}},
{Number{-1414213562373095, -15},
Number{-1414213562373095, -15},
Number{1999999999999999, -15},
__LINE__},
Number{1999999999999999, -15}},
{Number{3214285714285706, -15},
Number{3111111111111119, -15},
Number{9999999999999999, -15},
__LINE__},
{Number{1000000000000000, -32768},
Number{1000000000000000, -32768},
Number{0},
__LINE__}});
Number{9999999999999999, -15}},
{Number{1000000000000000, -32768}, Number{1000000000000000, -32768}, Number{0}}});
auto const cLarge = std::to_array<Case>(
// Note that items with extremely large mantissas need to be
// calculated, because otherwise they overflow uint64. Items
// from C with larger mantissa
{
{Number{7}, Number{8}, Number{56}, __LINE__},
{Number{7}, Number{8}, Number{56}},
{Number{1414213562373095, -15},
Number{1414213562373095, -15},
Number{1999999999999999861, -18},
__LINE__},
Number{1999999999999999861, -18}},
{Number{-1414213562373095, -15},
Number{1414213562373095, -15},
Number{-1999999999999999861, -18},
__LINE__},
Number{-1999999999999999861, -18}},
{Number{-1414213562373095, -15},
Number{-1414213562373095, -15},
Number{1999999999999999861, -18},
__LINE__},
Number{1999999999999999861, -18}},
{Number{3214285714285706, -15},
Number{3111111111111119, -15},
Number{false, 9999999999999999579ULL, -18, Number::normalized{}},
__LINE__},
Number{false, 9999999999999999579ULL, -18, Number::normalized{}}},
{Number{1000000000000000000, -32768},
Number{1000000000000000000, -32768},
Number{0},
__LINE__},
Number{0}},
// Items from cSmall expanded for the larger mantissa,
// except duplicates. Sadly, it looks like sqrt(2)^2 != 2
// with higher precision
{Number{1414213562373095049, -18},
Number{1414213562373095049, -18},
Number{2, 0},
__LINE__},
Number{2, 0}},
{Number{-1414213562373095048, -18},
Number{1414213562373095048, -18},
Number{-1999999999999999997, -18},
__LINE__},
Number{-1999999999999999997, -18}},
{Number{-1414213562373095048, -18},
Number{-1414213562373095049, -18},
Number{1999999999999999999, -18},
__LINE__},
Number{1999999999999999999, -18}},
{Number{3214285714285714278, -18},
Number{3111111111111111119, -18},
Number{10, 0},
__LINE__},
// Maximum internal mantissa range - rounds down to
// maxMantissa/10e1
Number{10, 0}},
// Maximum mantissa range - rounds down to maxMantissa/10e1
// 99'999'999'999'999'999'800'000'000'000'000'000'100
{Number{false, maxInternalMantissa, 0, Number::normalized{}},
Number{false, maxInternalMantissa, 0, Number::normalized{}},
Number{false, maxInternalMantissa / 10 - 1, 20, Number::normalized{}},
__LINE__},
// Maximum actual mantissa range - same as int64
{Number{false, maxMantissa, 0, Number::normalized{}},
Number{false, maxMantissa, 0, Number::normalized{}},
Number{85'070'591'730'234'615'84, 19},
__LINE__},
Number{false, (maxMantissa / 10) - 1, 20, Number::normalized{}}},
// Maximum int64 range
// 85'070'591'730'234'615'847'396'907'784'232'501'249
{Number{Number::largestMantissa, 0},
Number{Number::largestMantissa, 0},
Number{85'070'591'730'234'615'84, 19},
__LINE__},
{Number{Number::maxRep, 0},
Number{Number::maxRep, 0},
Number{85'070'591'730'234'615'84, 19}},
});
tests(cSmall, cLarge);
}
@@ -554,90 +478,66 @@ public:
testcase << "test_mul " << to_string(Number::getMantissaScale()) << " downward";
{
auto const cSmall = std::to_array<Case>(
{{Number{7}, Number{8}, Number{56}, __LINE__},
{{Number{7}, Number{8}, Number{56}},
{Number{1414213562373095, -15},
Number{1414213562373095, -15},
Number{1999999999999999, -15},
__LINE__},
Number{1999999999999999, -15}},
{Number{-1414213562373095, -15},
Number{1414213562373095, -15},
Number{-2000000000000000, -15},
__LINE__},
Number{-2000000000000000, -15}},
{Number{-1414213562373095, -15},
Number{-1414213562373095, -15},
Number{1999999999999999, -15},
__LINE__},
Number{1999999999999999, -15}},
{Number{3214285714285706, -15},
Number{3111111111111119, -15},
Number{9999999999999999, -15},
__LINE__},
{Number{1000000000000000, -32768},
Number{1000000000000000, -32768},
Number{0},
__LINE__}});
Number{9999999999999999, -15}},
{Number{1000000000000000, -32768}, Number{1000000000000000, -32768}, Number{0}}});
auto const cLarge = std::to_array<Case>(
// Note that items with extremely large mantissas need to be
// calculated, because otherwise they overflow uint64. Items
// from C with larger mantissa
{
{Number{7}, Number{8}, Number{56}, __LINE__},
{Number{7}, Number{8}, Number{56}},
{Number{1414213562373095, -15},
Number{1414213562373095, -15},
Number{1999999999999999861, -18},
__LINE__},
Number{1999999999999999861, -18}},
{Number{-1414213562373095, -15},
Number{1414213562373095, -15},
Number{-1999999999999999862, -18},
__LINE__},
Number{-1999999999999999862, -18}},
{Number{-1414213562373095, -15},
Number{-1414213562373095, -15},
Number{1999999999999999861, -18},
__LINE__},
Number{1999999999999999861, -18}},
{Number{3214285714285706, -15},
Number{3111111111111119, -15},
Number{false, 9'999'999'999'999'999'579ULL, -18, Number::normalized{}},
__LINE__},
Number{false, 9'999'999'999'999'999'579ULL, -18, Number::normalized{}}},
{Number{1000000000000000000, -32768},
Number{1000000000000000000, -32768},
Number{0},
__LINE__},
Number{0}},
// Items from cSmall expanded for the larger mantissa,
// except duplicates. Sadly, it looks like sqrt(2)^2 != 2
// with higher precision
{Number{1414213562373095049, -18},
Number{1414213562373095049, -18},
Number{2, 0},
__LINE__},
Number{2, 0}},
{Number{-1414213562373095048, -18},
Number{1414213562373095048, -18},
Number{-1999999999999999998, -18},
__LINE__},
Number{-1999999999999999998, -18}},
{Number{-1414213562373095048, -18},
Number{-1414213562373095049, -18},
Number{1999999999999999999, -18},
__LINE__},
Number{1999999999999999999, -18}},
{Number{3214285714285714278, -18},
Number{3111111111111111119, -18},
Number{10, 0},
__LINE__},
// Maximum internal mantissa range - rounds down to
// maxInternalMantissa/10-1
Number{10, 0}},
// Maximum mantissa range - rounds down to maxMantissa/10e1
// 99'999'999'999'999'999'800'000'000'000'000'000'100
{Number{false, maxInternalMantissa, 0, Number::normalized{}},
Number{false, maxInternalMantissa, 0, Number::normalized{}},
Number{false, maxInternalMantissa / 10 - 1, 20, Number::normalized{}},
__LINE__},
// Maximum external mantissa range - same as INT64_MAX (2^63-1)
{Number{false, maxMantissa, 0, Number::normalized{}},
Number{false, maxMantissa, 0, Number::normalized{}},
Number{85'070'591'730'234'615'84, 19},
__LINE__},
Number{false, (maxMantissa / 10) - 1, 20, Number::normalized{}}},
// Maximum int64 range
// 85'070'591'730'234'615'847'396'907'784'232'501'249
{Number{Number::largestMantissa, 0},
Number{Number::largestMantissa, 0},
Number{85'070'591'730'234'615'84, 19},
__LINE__},
{Number{Number::maxRep, 0},
Number{Number::maxRep, 0},
Number{85'070'591'730'234'615'84, 19}},
});
tests(cSmall, cLarge);
}
@@ -645,89 +545,66 @@ public:
testcase << "test_mul " << to_string(Number::getMantissaScale()) << " upward";
{
auto const cSmall = std::to_array<Case>(
{{Number{7}, Number{8}, Number{56}, __LINE__},
{{Number{7}, Number{8}, Number{56}},
{Number{1414213562373095, -15},
Number{1414213562373095, -15},
Number{2000000000000000, -15},
__LINE__},
Number{2000000000000000, -15}},
{Number{-1414213562373095, -15},
Number{1414213562373095, -15},
Number{-1999999999999999, -15},
__LINE__},
Number{-1999999999999999, -15}},
{Number{-1414213562373095, -15},
Number{-1414213562373095, -15},
Number{2000000000000000, -15},
__LINE__},
Number{2000000000000000, -15}},
{Number{3214285714285706, -15},
Number{3111111111111119, -15},
Number{1000000000000000, -14},
__LINE__},
{Number{1000000000000000, -32768},
Number{1000000000000000, -32768},
Number{0},
__LINE__}});
Number{1000000000000000, -14}},
{Number{1000000000000000, -32768}, Number{1000000000000000, -32768}, Number{0}}});
auto const cLarge = std::to_array<Case>(
// Note that items with extremely large mantissas need to be
// calculated, because otherwise they overflow uint64. Items
// from C with larger mantissa
{
{Number{7}, Number{8}, Number{56}, __LINE__},
{Number{7}, Number{8}, Number{56}},
{Number{1414213562373095, -15},
Number{1414213562373095, -15},
Number{1999999999999999862, -18},
__LINE__},
Number{1999999999999999862, -18}},
{Number{-1414213562373095, -15},
Number{1414213562373095, -15},
Number{-1999999999999999861, -18},
__LINE__},
Number{-1999999999999999861, -18}},
{Number{-1414213562373095, -15},
Number{-1414213562373095, -15},
Number{1999999999999999862, -18},
__LINE__},
Number{1999999999999999862, -18}},
{Number{3214285714285706, -15},
Number{3111111111111119, -15},
Number{999999999999999958, -17},
__LINE__},
Number{999999999999999958, -17}},
{Number{1000000000000000000, -32768},
Number{1000000000000000000, -32768},
Number{0},
__LINE__},
Number{0}},
// Items from cSmall expanded for the larger mantissa,
// except duplicates. Sadly, it looks like sqrt(2)^2 != 2
// with higher precision
{Number{1414213562373095049, -18},
Number{1414213562373095049, -18},
Number{2000000000000000001, -18},
__LINE__},
Number{2000000000000000001, -18}},
{Number{-1414213562373095048, -18},
Number{1414213562373095048, -18},
Number{-1999999999999999997, -18},
__LINE__},
Number{-1999999999999999997, -18}},
{Number{-1414213562373095048, -18},
Number{-1414213562373095049, -18},
Number{2, 0},
__LINE__},
Number{2, 0}},
{Number{3214285714285714278, -18},
Number{3111111111111111119, -18},
Number{1000000000000000001, -17},
__LINE__},
// Maximum internal mantissa range - rounds up to
// minMantissa*10 1e19*1e19=1e38
{Number{false, maxInternalMantissa, 0, Number::normalized{}},
Number{false, maxInternalMantissa, 0, Number::normalized{}},
Number{1, 38},
__LINE__},
// Maximum mantissa range - same as int64
Number{1000000000000000001, -17}},
// Maximum mantissa range - rounds up to minMantissa*10
// 1e19*1e19=1e38
{Number{false, maxMantissa, 0, Number::normalized{}},
Number{false, maxMantissa, 0, Number::normalized{}},
Number{85'070'591'730'234'615'85, 19},
__LINE__},
Number{1, 38}},
// Maximum int64 range
// 85'070'591'730'234'615'847'396'907'784'232'501'249
{Number{Number::largestMantissa, 0},
Number{Number::largestMantissa, 0},
Number{85'070'591'730'234'615'85, 19},
__LINE__},
{Number{Number::maxRep, 0},
Number{Number::maxRep, 0},
Number{85'070'591'730'234'615'85, 19}},
});
tests(cSmall, cLarge);
}
@@ -962,8 +839,6 @@ public:
};
*/
auto const maxInternalMantissa = getMaxInternalMantissa();
auto const cSmall = std::to_array<Case>(
{{Number{2}, 2, Number{1414213562373095049, -18}},
{Number{2'000'000}, 2, Number{1414213562373095049, -15}},
@@ -975,16 +850,16 @@ public:
{Number{0}, 5, Number{0}},
{Number{5625, -4}, 2, Number{75, -2}}});
auto const cLarge = std::to_array<Case>({
{Number{false, maxInternalMantissa - 9, -1, Number::normalized{}},
{Number{false, Number::maxMantissa() - 9, -1, Number::normalized{}},
2,
Number{false, 999'999'999'999'999'999, -9, Number::normalized{}}},
{Number{false, maxInternalMantissa - 9, 0, Number::normalized{}},
{Number{false, Number::maxMantissa() - 9, 0, Number::normalized{}},
2,
Number{false, 3'162'277'660'168'379'330, -9, Number::normalized{}}},
{Number{Number::largestMantissa},
{Number{Number::maxRep},
2,
Number{false, 3'037'000'499'976049692, -9, Number::normalized{}}},
{Number{Number::largestMantissa},
{Number{Number::maxRep},
4,
Number{false, 55'108'98747006743627, -14, Number::normalized{}}},
});
@@ -1033,8 +908,6 @@ public:
}
};
Number const maxInternalMantissa = power(10, Number::mantissaLog()) * 10 - 1;
auto const cSmall = std::to_array<Number>({
Number{2},
Number{2'000'000},
@@ -1044,10 +917,7 @@ public:
Number{5, -1},
Number{0},
Number{5625, -4},
Number{Number::largestMantissa},
maxInternalMantissa,
Number{Number::minMantissa(), 0, Number::unchecked{}},
Number{Number::maxMantissa(), 0, Number::unchecked{}},
Number{Number::maxRep},
});
test(cSmall);
bool caught = false;
@@ -1398,18 +1268,18 @@ public:
case MantissaRange::large:
// Test the edges
// ((exponent < -(28)) || (exponent > -(8)))))
test(Number::min(), "922337203685477581e-32768");
test(Number::min(), "1e-32750");
test(Number::max(), "9223372036854775807e32768");
test(Number::lowest(), "-9223372036854775807e32768");
{
NumberRoundModeGuard const mg(Number::towards_zero);
auto const maxMantissa = Number::maxMantissa();
BEAST_EXPECT(maxMantissa == 9'223'372'036'854'775'807ULL);
BEAST_EXPECT(maxMantissa == 9'999'999'999'999'999'999ULL);
test(
Number{false, maxMantissa, 0, Number::normalized{}}, "9223372036854775807");
Number{false, maxMantissa, 0, Number::normalized{}}, "9999999999999999990");
test(
Number{true, maxMantissa, 0, Number::normalized{}}, "-9223372036854775807");
Number{true, maxMantissa, 0, Number::normalized{}}, "-9999999999999999990");
test(
Number{std::numeric_limits<std::int64_t>::max(), 0}, "9223372036854775807");
@@ -1645,7 +1515,7 @@ public:
Number const initalXrp{INITIAL_XRP};
BEAST_EXPECT(initalXrp.exponent() > 0);
Number const maxInt64{Number::largestMantissa};
Number const maxInt64{Number::maxRep};
BEAST_EXPECT(maxInt64.exponent() > 0);
// 85'070'591'730'234'615'865'843'651'857'942'052'864 - 38 digits
BEAST_EXPECT((power(maxInt64, 2) == Number{85'070'591'730'234'62, 22}));
@@ -1662,213 +1532,21 @@ public:
Number const initalXrp{INITIAL_XRP};
BEAST_EXPECT(initalXrp.exponent() <= 0);
Number const maxInt64{Number::largestMantissa};
Number const maxInt64{Number::maxRep};
BEAST_EXPECT(maxInt64.exponent() <= 0);
// 85'070'591'730'234'615'847'396'907'784'232'501'249 - 38 digits
BEAST_EXPECT((power(maxInt64, 2) == Number{85'070'591'730'234'615'85, 19}));
NumberRoundModeGuard const mg(Number::towards_zero);
{
auto const maxInternalMantissa = getMaxInternalMantissa();
// Rounds down to fit under 2^63
Number const max = Number{false, maxInternalMantissa, 0, Number::normalized{}};
// No alterations by the accessors
BEAST_EXPECT(max.mantissa() == maxInternalMantissa / 10);
BEAST_EXPECT(max.exponent() == 1);
// 99'999'999'999'999'999'800'000'000'000'000'000'100 - also 38
// digits
BEAST_EXPECT(
(power(max, 2) ==
Number{false, maxInternalMantissa / 10 - 1, 20, Number::normalized{}}));
}
{
auto const maxMantissa = Number::maxMantissa();
Number const max = Number{false, maxMantissa, 0, Number::normalized{}};
// No alterations by the accessors
BEAST_EXPECT(max.mantissa() == maxMantissa);
BEAST_EXPECT(max.exponent() == 0);
// 85'070'591'730'234'615'847'396'907'784'232'501'249 - also 38
// digits
BEAST_EXPECT(
(power(max, 2) ==
Number{false, 85'070'591'730'234'615'84, 19, Number::normalized{}}));
}
}
}
void
testNormalizeToRange()
{
// Test edge-cases of normalizeToRange
auto const scale = Number::getMantissaScale();
testcase << "normalizeToRange " << to_string(scale);
auto test = [this](
Number const& n,
auto const rangeMin,
auto const rangeMax,
auto const expectedMantissa,
auto const expectedExponent,
auto const line) {
auto const normalized = n.normalizeToRange(rangeMin, rangeMax);
BEAST_EXPECTS(
normalized.first == expectedMantissa,
"Number " + to_string(n) + " scaled to " + std::to_string(rangeMax) +
". Expected mantissa:" + std::to_string(expectedMantissa) +
", got: " + std::to_string(normalized.first) + " @ " + std::to_string(line));
BEAST_EXPECTS(
normalized.second == expectedExponent,
"Number " + to_string(n) + " scaled to " + std::to_string(rangeMax) +
". Expected exponent:" + std::to_string(expectedExponent) +
", got: " + std::to_string(normalized.second) + " @ " + std::to_string(line));
};
std::int64_t constexpr iRangeMin = 100;
std::int64_t constexpr iRangeMax = 999;
std::uint64_t constexpr uRangeMin = 100;
std::uint64_t constexpr uRangeMax = 999;
constexpr static MantissaRange largeRange{MantissaRange::large};
std::int64_t constexpr iBigMin = largeRange.min;
std::int64_t constexpr iBigMax = largeRange.max;
auto const testSuite = [&](Number const& n,
auto const expectedSmallMantissa,
auto const expectedSmallExponent,
auto const expectedLargeMantissa,
auto const expectedLargeExponent,
auto const line) {
test(n, iRangeMin, iRangeMax, expectedSmallMantissa, expectedSmallExponent, line);
test(n, iBigMin, iBigMax, expectedLargeMantissa, expectedLargeExponent, line);
// Only test non-negative. testing a negative number with an
// unsigned range will assert, and asserts can't be tested.
if (n.signum() >= 0)
{
test(n, uRangeMin, uRangeMax, expectedSmallMantissa, expectedSmallExponent, line);
test(
n,
largeRange.min,
largeRange.max,
expectedLargeMantissa,
expectedLargeExponent,
line);
}
};
{
// zero
Number const n{0};
testSuite(
n,
0,
std::numeric_limits<int>::lowest(),
0,
std::numeric_limits<int>::lowest(),
__LINE__);
}
{
// Small positive number
Number const n{2};
testSuite(n, 200, -2, 2'000'000'000'000'000'000, -18, __LINE__);
}
{
// Negative number
Number const n{-2};
testSuite(n, -200, -2, -2'000'000'000'000'000'000, -18, __LINE__);
}
{
// Biggest valid mantissa
Number const n{Number::largestMantissa, 0, Number::normalized{}};
if (scale == MantissaRange::small)
// With the small mantissa range, the value rounds up. Because
// it rounds up, when scaling up to the full int64 range, it
// can't go over the max, so it is one digit smaller than the
// full value.
testSuite(n, 922, 16, 922'337'203'685'477'600, 1, __LINE__);
else
testSuite(n, 922, 16, Number::largestMantissa, 0, __LINE__);
}
{
// Biggest valid mantissa + 1
Number const n{Number::largestMantissa + 1, 0, Number::normalized{}};
if (scale == MantissaRange::small)
// With the small mantissa range, the value rounds up. Because
// it rounds up, when scaling up to the full int64 range, it
// can't go over the max, so it is one digit smaller than the
// full value.
testSuite(n, 922, 16, 922'337'203'685'477'600, 1, __LINE__);
else
testSuite(n, 922, 16, 922'337'203'685'477'581, 1, __LINE__);
}
{
// Biggest valid mantissa + 2
Number const n{Number::largestMantissa + 2, 0, Number::normalized{}};
if (scale == MantissaRange::small)
// With the small mantissa range, the value rounds up. Because
// it rounds up, when scaling up to the full int64 range, it
// can't go over the max, so it is one digit smaller than the
// full value.
testSuite(n, 922, 16, 922'337'203'685'477'600, 1, __LINE__);
else
testSuite(n, 922, 16, 922'337'203'685'477'581, 1, __LINE__);
}
{
// Biggest valid mantissa + 3
Number const n{Number::largestMantissa + 3, 0, Number::normalized{}};
if (scale == MantissaRange::small)
// With the small mantissa range, the value rounds up. Because
// it rounds up, when scaling up to the full int64 range, it
// can't go over the max, so it is one digit smaller than the
// full value.
testSuite(n, 922, 16, 922'337'203'685'477'600, 1, __LINE__);
else
testSuite(n, 922, 16, 922'337'203'685'477'581, 1, __LINE__);
}
{
// int64 min
Number const n{std::numeric_limits<std::int64_t>::min(), 0};
if (scale == MantissaRange::small)
testSuite(n, -922, 16, -922'337'203'685'477'600, 1, __LINE__);
else
testSuite(n, -922, 16, -922'337'203'685'477'581, 1, __LINE__);
}
{
// int64 min + 1
Number const n{std::numeric_limits<std::int64_t>::min() + 1, 0};
if (scale == MantissaRange::small)
testSuite(n, -922, 16, -922'337'203'685'477'600, 1, __LINE__);
else
testSuite(n, -922, 16, -9'223'372'036'854'775'807, 0, __LINE__);
}
{
// int64 min - 1
// Need to cast to uint, even though we're dealing with a negative
// number to avoid overflow and UB
Number const n{
true,
-static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::min()) + 1,
0,
Number::normalized{}};
if (scale == MantissaRange::small)
testSuite(n, -922, 16, -922'337'203'685'477'600, 1, __LINE__);
else
testSuite(n, -922, 16, -922'337'203'685'477'581, 1, __LINE__);
auto const maxMantissa = Number::maxMantissa();
Number const max = Number{false, maxMantissa, 0, Number::normalized{}};
BEAST_EXPECT(max.mantissa() == maxMantissa / 10);
BEAST_EXPECT(max.exponent() == 1);
// 99'999'999'999'999'999'800'000'000'000'000'000'100 - also 38
// digits
BEAST_EXPECT(
(power(max, 2) == Number{false, (maxMantissa / 10) - 1, 20, Number::normalized{}}));
}
}
@@ -1899,7 +1577,6 @@ public:
test_truncate();
testRounding();
testInt64();
testNormalizeToRange();
}
}
};

View File

@@ -24,7 +24,7 @@ public:
testInteger(IntType in)
{
std::string s;
IntType out(in + 1);
IntType out = static_cast<IntType>(~in); // Ensure out != in
expect(lexicalCastChecked(s, in));
expect(lexicalCastChecked(out, s));

View File

@@ -8,9 +8,12 @@ add_custom_target(xrpl.tests)
# Test helpers
add_library(xrpl.helpers.test STATIC)
target_sources(xrpl.helpers.test PRIVATE helpers/TestSink.cpp)
target_sources(
xrpl.helpers.test
PRIVATE helpers/Account.cpp helpers/TestSink.cpp helpers/TxTest.cpp
)
target_include_directories(xrpl.helpers.test PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(xrpl.helpers.test PRIVATE xrpl.libxrpl)
target_link_libraries(xrpl.helpers.test PUBLIC xrpl.libxrpl gtest::gtest)
# Common library dependencies for the rest of the tests.
add_library(xrpl.imports.test INTERFACE)
@@ -32,6 +35,10 @@ xrpl_add_test(json)
target_link_libraries(xrpl.test.json PRIVATE xrpl.imports.test)
add_dependencies(xrpl.tests xrpl.test.json)
xrpl_add_test(tx)
target_link_libraries(xrpl.test.tx PRIVATE xrpl.imports.test)
add_dependencies(xrpl.tests xrpl.test.tx)
xrpl_add_test(protocol_autogen)
target_link_libraries(xrpl.test.protocol_autogen PRIVATE xrpl.imports.test)
add_dependencies(xrpl.tests xrpl.test.protocol_autogen)

View File

@@ -0,0 +1,19 @@
#include <helpers/Account.h>
#include <xrpl/protocol/KeyType.h>
#include <xrpl/protocol/PublicKey.h>
#include <xrpl/protocol/SecretKey.h>
#include <xrpl/protocol/Seed.h>
namespace xrpl::test {
Account const Account::master{"masterpassphrase"};
Account::Account(std::string_view name, KeyType type)
: name_(name)
, keyPair_(generateKeyPair(type, generateSeed(name_)))
, id_(calcAccountID(keyPair_.first))
{
}
} // namespace xrpl::test

View File

@@ -0,0 +1,81 @@
#pragma once
#include <xrpl/protocol/AccountID.h>
#include <xrpl/protocol/KeyType.h>
#include <xrpl/protocol/PublicKey.h>
#include <xrpl/protocol/SecretKey.h>
#include <string>
#include <string_view>
#include <utility>
namespace xrpl::test {
/**
* @brief A test account with cryptographic keys.
*
* Generates keys deterministically from a name, making tests reproducible.
* The same name always produces the same AccountID and keys.
*/
class Account
{
public:
/**
* @brief The master account that holds all XRP in genesis.
*
* This account is created in the genesis ledger with all 100 billion XRP.
* It uses the well-known seed "masterpassphrase".
*/
static Account const master;
/**
* @brief Create an account from a name.
*
* Keys are derived deterministically from the name.
*
* @param name Human-readable name for the account.
* @param type Key type to use (defaults to secp256k1).
*/
explicit Account(std::string_view name, KeyType type = KeyType::secp256k1);
/** @brief Return the human-readable name. */
std::string const&
name() const noexcept
{
return name_;
}
/** @brief Return the AccountID. */
AccountID const&
id() const noexcept
{
return id_;
}
/** @brief Return the public key. */
PublicKey const&
pk() const noexcept
{
return keyPair_.first;
}
/** @brief Return the secret key. */
SecretKey const&
sk() const noexcept
{
return keyPair_.second;
}
/** @brief Implicit conversion to AccountID. */
operator AccountID const&() const noexcept
{
return id_;
}
private:
std::string name_;
std::pair<PublicKey, SecretKey> keyPair_;
AccountID id_;
};
} // namespace xrpl::test

View File

@@ -0,0 +1,132 @@
#pragma once
#include <xrpl/basics/Number.h>
#include <xrpl/protocol/Asset.h>
#include <xrpl/protocol/Issue.h>
#include <xrpl/protocol/STAmount.h>
#include <xrpl/protocol/UintTypes.h>
#include <helpers/Account.h>
#include <concepts>
#include <string>
#include <string_view>
#include <type_traits>
namespace xrpl::test {
/**
* @brief Represents an IOU (issued currency) for testing.
*
* Provides a clear, explicit API for creating currencies issued by an account.
* This replaces the cryptic `Account::operator[]` from the jtx framework.
*
* @code
* Account gw("gateway");
* IOU USD("USD", gw);
*
* auto issue = USD.issue(); // Get the Issue
* auto asset = USD.asset(); // Get the Asset
* auto amt = USD.amount(100); // Get STAmount of 100 USD
* @endcode
*/
class IOU
{
public:
/**
* @brief Construct an IOU from a currency code and issuing account.
* @param currencyCode A 3-character ISO currency code (e.g., "USD").
* @param issuer The account that issues this currency.
*/
IOU(std::string_view currencyCode, Account const& issuer)
: currency_(to_currency(std::string(currencyCode))), issuer_(issuer.id())
{
XRPL_ASSERT(!isXRP(currency_), "IOU: currency code must not resolve to XRP");
}
/**
* @brief Construct an IOU from a Currency and issuing account.
* @param currency The Currency object.
* @param issuer The account that issues this currency.
*/
IOU(Currency currency, Account const& issuer)
: currency_(std::move(currency)), issuer_(issuer.id())
{
XRPL_ASSERT(!isXRP(currency_), "IOU: currency code must not resolve to XRP");
}
/**
* @brief Get the Issue (currency + issuer pair).
* @return An Issue object representing this IOU.
*/
[[nodiscard]] Issue
issue() const
{
return Issue{currency_, issuer_};
}
/**
* @brief Get the Asset.
* @return An Asset object representing this IOU.
*/
[[nodiscard]] Asset
asset() const
{
return Asset{issue()};
}
/**
* @brief Create an STAmount of this IOU.
*
* Works with any arithmetic type (int, double, etc.) by converting
* to string and parsing. This matches the jtx IOU behaviour.
*
* @tparam T An arithmetic type.
* @param value The amount as any arithmetic type.
* @return An STAmount representing value units of this IOU.
*/
template <typename T>
requires std::is_arithmetic_v<T>
[[nodiscard]] STAmount
amount(T value) const
{
return amountFromString(issue(), to_string(value));
}
/**
* @brief Create an STAmount of this IOU from a Number.
* @param value The amount as a Number.
* @return An STAmount representing value units of this IOU.
*/
[[nodiscard]] STAmount
amount(Number const& value) const
{
return STAmount{issue(), value};
}
/**
* @brief Get the currency.
* @return The currency.
*/
[[nodiscard]] Currency const&
currency() const
{
return currency_;
}
/**
* @brief Get the issuer account ID.
* @return The issuer's AccountID.
*/
[[nodiscard]] AccountID const&
issuer() const
{
return issuer_;
}
private:
Currency currency_;
AccountID issuer_;
};
} // namespace xrpl::test

View File

@@ -0,0 +1,111 @@
#pragma once
#include <xrpl/basics/chrono.h>
#include <xrpl/nodestore/DummyScheduler.h>
#include <xrpl/nodestore/Manager.h>
#include <xrpl/shamap/Family.h>
#include <memory>
namespace xrpl {
namespace test {
/** Test implementation of Family for unit tests.
Uses an in-memory NodeStore database and simple caches.
The missingNode methods throw since tests shouldn't encounter missing nodes.
*/
class TestFamily : public Family
{
private:
std::unique_ptr<NodeStore::Database> db_;
TestStopwatch clock_;
std::shared_ptr<FullBelowCache> fbCache_;
std::shared_ptr<TreeNodeCache> tnCache_;
NodeStore::DummyScheduler scheduler_;
beast::Journal j_;
public:
explicit TestFamily(beast::Journal j)
: fbCache_(std::make_shared<FullBelowCache>("TestFamily full below cache", clock_, j))
, tnCache_(
std::make_shared<TreeNodeCache>(
"TestFamily tree node cache",
65536,
std::chrono::minutes{1},
clock_,
j))
, j_(j)
{
Section config;
config.set("type", "memory");
config.set("path", "TestFamily");
db_ = NodeStore::Manager::instance().make_Database(megabytes(4), scheduler_, 1, config, j);
}
NodeStore::Database&
db() override
{
return *db_;
}
NodeStore::Database const&
db() const override
{
return *db_;
}
beast::Journal const&
journal() override
{
return j_;
}
std::shared_ptr<FullBelowCache>
getFullBelowCache() override
{
return fbCache_;
}
std::shared_ptr<TreeNodeCache>
getTreeNodeCache() override
{
return tnCache_;
}
void
sweep() override
{
fbCache_->sweep();
tnCache_->sweep();
}
void
missingNodeAcquireBySeq(std::uint32_t refNum, uint256 const& nodeHash) override
{
Throw<std::runtime_error>("TestFamily: missing node (by seq)");
}
void
missingNodeAcquireByHash(uint256 const& refHash, std::uint32_t refNum) override
{
Throw<std::runtime_error>("TestFamily: missing node (by hash)");
}
void
reset() override
{
fbCache_->reset();
tnCache_->reset();
}
/** Access the test clock for time manipulation in tests. */
TestStopwatch&
clock()
{
return clock_;
}
};
} // namespace test
} // namespace xrpl

View File

@@ -0,0 +1,378 @@
#pragma once
#include <xrpl/basics/Log.h>
#include <xrpl/basics/chrono.h>
#include <xrpl/core/HashRouter.h>
#include <xrpl/core/NetworkIDService.h>
#include <xrpl/core/ServiceRegistry.h>
#include <xrpl/ledger/PendingSaves.h>
#include <xrpl/server/LoadFeeTrack.h>
#include <boost/asio/io_context.hpp>
#include <helpers/TestFamily.h>
#include <helpers/TestSink.h>
#include <optional>
#include <stdexcept>
namespace xrpl {
namespace test {
/** Logs implementation that creates TestSink instances. */
class TestLogs : public Logs
{
public:
explicit TestLogs(beast::severities::Severity level = beast::severities::kWarning) : Logs(level)
{
}
std::unique_ptr<beast::Journal::Sink>
makeSink(std::string const&, beast::severities::Severity threshold) override
{
return std::make_unique<TestSink>(threshold);
}
};
/** Simple NetworkIDService implementation for tests. */
class TestNetworkIDService final : public NetworkIDService
{
public:
explicit TestNetworkIDService(std::uint32_t networkID = 0) : networkID_(networkID)
{
}
[[nodiscard]] std::uint32_t
getNetworkID() const noexcept override
{
return networkID_;
}
private:
std::uint32_t networkID_;
};
/** Test implementation of ServiceRegistry for unit tests.
This class provides real implementations for services that can be
instantiated from libxrpl (such as Logs, io_context, caches), and
throws std::logic_error for services that require the full Application.
Tests can subclass this to provide additional services they need.
*/
class TestServiceRegistry : public ServiceRegistry
{
TestLogs logs_{beast::severities::kWarning};
boost::asio::io_context io_context_;
TestFamily family_{logs_.journal("TestFamily")};
LoadFeeTrack feeTrack_{logs_.journal("LoadFeeTrack")};
TestNetworkIDService networkIDService_;
HashRouter hashRouter_{HashRouter::Setup{}, stopwatch()};
NodeCache tempNodeCache_{
"TempNodeCache",
16384,
std::chrono::minutes{1},
stopwatch(),
logs_.journal("TaggedCache")};
CachedSLEs cachedSLEs_{
"CachedSLEs",
16384,
std::chrono::minutes{1},
stopwatch(),
logs_.journal("TaggedCache")};
PendingSaves pendingSaves_;
std::optional<uint256> trapTxID_;
public:
TestServiceRegistry() = default;
~TestServiceRegistry() override = default;
// Core infrastructure services
CollectorManager&
getCollectorManager() override
{
throw std::logic_error("TestServiceRegistry::getCollectorManager() not implemented");
}
Family&
getNodeFamily() override
{
return family_;
}
TimeKeeper&
getTimeKeeper() override
{
throw std::logic_error("TestServiceRegistry::timeKeeper() not implemented");
}
JobQueue&
getJobQueue() override
{
throw std::logic_error("TestServiceRegistry::getJobQueue() not implemented");
}
NodeCache&
getTempNodeCache() override
{
return tempNodeCache_;
}
CachedSLEs&
getCachedSLEs() override
{
return cachedSLEs_;
}
NetworkIDService&
getNetworkIDService() override
{
return networkIDService_;
}
// Protocol and validation services
AmendmentTable&
getAmendmentTable() override
{
throw std::logic_error("TestServiceRegistry::getAmendmentTable() not implemented");
}
HashRouter&
getHashRouter() override
{
return hashRouter_;
}
LoadFeeTrack&
getFeeTrack() override
{
return feeTrack_;
}
LoadManager&
getLoadManager() override
{
throw std::logic_error("TestServiceRegistry::getLoadManager() not implemented");
}
RCLValidations&
getValidations() override
{
throw std::logic_error("TestServiceRegistry::getValidations() not implemented");
}
ValidatorList&
getValidators() override
{
throw std::logic_error("TestServiceRegistry::validators() not implemented");
}
ValidatorSite&
getValidatorSites() override
{
throw std::logic_error("TestServiceRegistry::validatorSites() not implemented");
}
ManifestCache&
getValidatorManifests() override
{
throw std::logic_error("TestServiceRegistry::validatorManifests() not implemented");
}
ManifestCache&
getPublisherManifests() override
{
throw std::logic_error("TestServiceRegistry::publisherManifests() not implemented");
}
// Network services
Overlay&
getOverlay() override
{
throw std::logic_error("TestServiceRegistry::overlay() not implemented");
}
Cluster&
getCluster() override
{
throw std::logic_error("TestServiceRegistry::cluster() not implemented");
}
PeerReservationTable&
getPeerReservations() override
{
throw std::logic_error("TestServiceRegistry::peerReservations() not implemented");
}
Resource::Manager&
getResourceManager() override
{
throw std::logic_error("TestServiceRegistry::getResourceManager() not implemented");
}
// Storage services
NodeStore::Database&
getNodeStore() override
{
throw std::logic_error("TestServiceRegistry::getNodeStore() not implemented");
}
SHAMapStore&
getSHAMapStore() override
{
throw std::logic_error("TestServiceRegistry::getSHAMapStore() not implemented");
}
RelationalDatabase&
getRelationalDatabase() override
{
throw std::logic_error("TestServiceRegistry::getRelationalDatabase() not implemented");
}
// Ledger services
InboundLedgers&
getInboundLedgers() override
{
throw std::logic_error("TestServiceRegistry::getInboundLedgers() not implemented");
}
InboundTransactions&
getInboundTransactions() override
{
throw std::logic_error("TestServiceRegistry::getInboundTransactions() not implemented");
}
TaggedCache<uint256, AcceptedLedger>&
getAcceptedLedgerCache() override
{
throw std::logic_error("TestServiceRegistry::getAcceptedLedgerCache() not implemented");
}
LedgerMaster&
getLedgerMaster() override
{
throw std::logic_error("TestServiceRegistry::getLedgerMaster() not implemented");
}
LedgerCleaner&
getLedgerCleaner() override
{
throw std::logic_error("TestServiceRegistry::getLedgerCleaner() not implemented");
}
LedgerReplayer&
getLedgerReplayer() override
{
throw std::logic_error("TestServiceRegistry::getLedgerReplayer() not implemented");
}
PendingSaves&
getPendingSaves() override
{
return pendingSaves_;
}
OpenLedger&
getOpenLedger() override
{
throw std::logic_error("TestServiceRegistry::openLedger() not implemented");
}
OpenLedger const&
getOpenLedger() const override
{
throw std::logic_error("TestServiceRegistry::openLedger() const not implemented");
}
// Transaction and operation services
NetworkOPs&
getOPs() override
{
throw std::logic_error("TestServiceRegistry::getOPs() not implemented");
}
OrderBookDB&
getOrderBookDB() override
{
throw std::logic_error("TestServiceRegistry::getOrderBookDB() not implemented");
}
TransactionMaster&
getMasterTransaction() override
{
throw std::logic_error("TestServiceRegistry::getMasterTransaction() not implemented");
}
TxQ&
getTxQ() override
{
throw std::logic_error("TestServiceRegistry::getTxQ() not implemented");
}
PathRequestManager&
getPathRequestManager() override
{
throw std::logic_error("TestServiceRegistry::getPathRequestManager() not implemented");
}
// Server services
ServerHandler&
getServerHandler() override
{
throw std::logic_error("TestServiceRegistry::getServerHandler() not implemented");
}
perf::PerfLog&
getPerfLog() override
{
throw std::logic_error("TestServiceRegistry::getPerfLog() not implemented");
}
// Configuration and state
bool
isStopping() const override
{
return false;
}
beast::Journal
getJournal(std::string const& name) override
{
return logs_.journal(name);
}
boost::asio::io_context&
getIOContext() override
{
return io_context_;
}
Logs&
getLogs() override
{
return logs_;
}
std::optional<uint256> const&
getTrapTxID() const override
{
return trapTxID_;
}
DatabaseCon&
getWalletDB() override
{
throw std::logic_error("TestServiceRegistry::getWalletDB() not implemented");
}
// Temporary: Get the underlying Application
Application&
getApp() override
{
throw std::logic_error(
"TestServiceRegistry::app() not implemented - no Application available in tests");
}
};
} // namespace test
} // namespace xrpl

View File

@@ -0,0 +1,252 @@
#include <helpers/TxTest.h>
#include <xrpl/basics/base_uint.h>
#include <xrpl/basics/chrono.h>
#include <xrpl/basics/contract.h>
#include <xrpl/ledger/ApplyView.h>
#include <xrpl/ledger/CanonicalTXSet.h>
#include <xrpl/ledger/Ledger.h>
#include <xrpl/ledger/OpenView.h>
#include <xrpl/ledger/ReadView.h>
#include <xrpl/protocol/AccountID.h>
#include <xrpl/protocol/Feature.h>
#include <xrpl/protocol/Fees.h>
#include <xrpl/protocol/Indexes.h>
#include <xrpl/protocol/SField.h>
#include <xrpl/protocol/STLedgerEntry.h>
#include <xrpl/protocol/STTx.h>
#include <xrpl/protocol/TER.h>
#include <xrpl/protocol_autogen/ledger_entries/AccountRoot.h>
#include <xrpl/protocol_autogen/ledger_entries/RippleState.h>
#include <xrpl/protocol_autogen/transactions/AccountSet.h>
#include <xrpl/protocol_autogen/transactions/Payment.h>
#include <xrpl/tx/apply.h>
#include <helpers/Account.h>
#include <helpers/IOU.h>
#include <cstdint>
#include <memory>
#include <optional>
#include <stdexcept>
#include <utility>
#include <vector>
namespace xrpl::test {
//------------------------------------------------------------------------------
// Feature helpers
//------------------------------------------------------------------------------
FeatureBitset
allFeatures()
{
static FeatureBitset const features = [] {
auto const& sa = allAmendments();
std::vector<uint256> feats;
feats.reserve(sa.size());
for ([[maybe_unused]] auto const& [name, _] : sa)
{
if (auto const f = getRegisteredFeature(name); f.has_value())
feats.push_back(*f);
}
return FeatureBitset(feats);
}();
return features;
}
//------------------------------------------------------------------------------
// TxTest
//------------------------------------------------------------------------------
TxTest::TxTest(std::optional<FeatureBitset> features)
{
// Convert FeatureBitset to unordered_set for Rules constructor
auto const featureBits = features.value_or(allFeatures());
foreachFeature(featureBits, [&](uint256 const& f) { featureSet_.insert(f); });
// Create rules with the specified features
rules_.emplace(featureSet_);
// Default fees for testing
Fees const fees{XRPAmount{10}, XRPAmount{10000000}, XRPAmount{2000000}};
// Create a genesis ledger as the base
closedLedger_ = std::make_shared<Ledger>(
create_genesis,
// NOLINTNEXTLINE(bugprone-unchecked-optional-access)
*rules_,
fees,
std::vector<uint256>{featureSet_.begin(), featureSet_.end()},
registry_.getNodeFamily());
// Initialize time from the genesis ledger
now_ = closedLedger_->header().closeTime;
// Create an open view on top of the genesis ledger
openLedger_ =
std::make_shared<OpenView>(open_ledger, closedLedger_.get(), *rules_, closedLedger_);
}
bool
TxTest::isEnabled(uint256 const& feature) const
{
// NOLINTNEXTLINE(bugprone-unchecked-optional-access)
return rules_->enabled(feature);
}
Rules const&
TxTest::getRules() const
{
// NOLINTNEXTLINE(bugprone-unchecked-optional-access)
return *rules_;
}
[[nodiscard]] TxResult
TxTest::submit(std::shared_ptr<STTx const> stx)
{
auto result = apply(registry_, *openLedger_, *stx, tapNONE, registry_.getJournal("apply"));
// Track successfully applied transactions for canonical reordering on close
// We make a copy since the TransactionBase doesn't own the STTx
if (result.applied)
pendingTxs_.push_back(stx);
return TxResult{
.ter = result.ter,
.applied = result.applied,
.metadata = std::move(result).metadata,
.tx = std::move(stx)};
}
void
TxTest::createAccount(Account const& account, XRPAmount xrp, uint32_t accountFlags)
{
auto const paymentTer =
submit(transactions::PaymentBuilder{Account::master, account, xrp}, Account::master).ter;
if (paymentTer != tesSUCCESS)
{
throw std::runtime_error("TxTest::createAccount: failed to create account");
}
close();
if (accountFlags != 0)
{
auto const accountSetTer =
submit(transactions::AccountSetBuilder{account}.setSetFlag(accountFlags), account).ter;
if (accountSetTer != tesSUCCESS)
{
throw std::runtime_error("TxTest::createAccount: failed to set account flags");
}
close();
}
}
ledger_entries::AccountRoot
TxTest::getAccountRoot(AccountID const& id) const
{
auto const sle = getOpenLedger().read(keylet::account(id));
if (!sle)
Throw<std::runtime_error>("TxTest::getAccountRoot: account not found");
return ledger_entries::AccountRoot{std::const_pointer_cast<SLE const>(sle)};
}
OpenView&
TxTest::getOpenLedger()
{
return *openLedger_;
}
OpenView const&
TxTest::getOpenLedger() const
{
return *openLedger_;
}
ReadView const&
TxTest::getClosedLedger() const
{
return *closedLedger_;
}
void
TxTest::close()
{
// Build a new closed ledger from the previous closed ledger,
// similar to how buildLedgerImpl works:
// 1. Create a new Ledger from the previous closed ledger
// 2. Re-apply transactions in canonical order
// 3. Mark it as accepted/immutable
auto const& prevLedger = *closedLedger_;
auto const ledgerCloseTime = now_ + prevLedger.header().closeTimeResolution;
now_ = ledgerCloseTime;
auto newLedger = std::make_shared<Ledger>(prevLedger, ledgerCloseTime);
CanonicalTXSet txSet(prevLedger.header().hash);
for (auto const& tx : pendingTxs_)
txSet.insert(tx);
{
OpenView accum(&*newLedger);
for (auto const& [key, tx] : txSet)
{
auto result = apply(registry_, accum, *tx, tapNONE, registry_.getJournal("apply"));
if (!result.applied)
{
throw std::runtime_error("TxTest::close: failed to apply transaction");
}
}
accum.apply(*newLedger);
}
newLedger->setAccepted(ledgerCloseTime, newLedger->header().closeTimeResolution, true);
closedLedger_ = newLedger;
pendingTxs_.clear();
openLedger_ =
// NOLINTNEXTLINE(bugprone-unchecked-optional-access)
std::make_shared<OpenView>(open_ledger, closedLedger_.get(), *rules_, closedLedger_);
}
void
TxTest::advanceTime(NetClock::duration duration)
{
now_ += duration;
}
NetClock::time_point
TxTest::getCloseTime() const
{
return now_;
}
STAmount
TxTest::getBalance(AccountID const& account, IOU const& iou) const
{
auto const sle = openLedger_->read(keylet::line(account, iou.issue()));
if (!sle)
return STAmount{iou.issue(), 0};
auto const rippleState = ledger_entries::RippleState{sle};
auto balance = rippleState.getBalance();
if (iou.issue().account == account)
{
throw std::logic_error("TxTest::getBalance: account is issuer");
}
balance.get<Issue>().account = iou.issue().account;
if (account > iou.issue().account)
balance.negate();
return balance;
}
} // namespace xrpl::test

View File

@@ -0,0 +1,364 @@
#pragma once
#include <xrpl/basics/Number.h>
#include <xrpl/basics/chrono.h>
#include <xrpl/beast/utility/Journal.h>
#include <xrpl/core/ServiceRegistry.h>
#include <xrpl/ledger/ApplyViewImpl.h>
#include <xrpl/ledger/Ledger.h>
#include <xrpl/ledger/OpenView.h>
#include <xrpl/protocol/Feature.h>
#include <xrpl/protocol/LedgerFormats.h>
#include <xrpl/protocol/Rules.h>
#include <xrpl/protocol/STTx.h>
#include <xrpl/protocol/TER.h>
#include <xrpl/protocol/TxFlags.h>
#include <xrpl/protocol/XRPAmount.h>
#include <xrpl/protocol_autogen/TransactionBuilderBase.h>
#include <xrpl/protocol_autogen/ledger_entries/AccountRoot.h>
#include <xrpl/tx/applySteps.h>
#include <helpers/Account.h>
#include <helpers/IOU.h>
#include <helpers/TestServiceRegistry.h>
#include <cmath>
#include <concepts>
#include <memory>
#include <optional>
#include <stdexcept>
#include <type_traits>
#include <unordered_set>
#include <vector>
namespace xrpl::test {
//------------------------------------------------------------------------------
// Amount helpers
//------------------------------------------------------------------------------
/**
* @brief Convert XRP to drops (integral types).
* @param xrp The amount in XRP.
* @return The equivalent amount in drops as XRPAmount.
*/
template <std::integral T>
constexpr XRPAmount
XRP(T xrp)
{
return XRPAmount{static_cast<std::int64_t>(xrp) * DROPS_PER_XRP.drops()};
}
/**
* @brief Convert XRP to drops (floating point types).
* @param xrp The amount in XRP (may be fractional).
* @return The equivalent amount in drops as XRPAmount.
*/
template <std::floating_point T>
XRPAmount
XRP(T xrp)
{
return XRPAmount{static_cast<std::int64_t>(std::round(xrp * DROPS_PER_XRP.drops()))};
}
/**
* @brief Convert XRP to drops (Number type).
* @param xrp The amount in XRP as a Number.
* @return The equivalent amount in drops as XRPAmount.
*/
inline XRPAmount
XRP(Number const& xrp)
{
return XRPAmount{static_cast<std::int64_t>(xrp * DROPS_PER_XRP.drops())};
}
//------------------------------------------------------------------------------
// Flag helpers
//------------------------------------------------------------------------------
/**
* @brief Convert AccountSet flag (asf) to LedgerState flag (lsf).
* @param asf The AccountSet flag value.
* @return The corresponding LedgerState flag.
* @throws std::runtime_error if the flag is not supported.
*
* Supported flags:
* asfRequireDest, asfRequireAuth, asfDisallowXRP, asfDisableMaster,
* asfNoFreeze, asfGlobalFreeze, asfDefaultRipple, asfDepositAuth,
* asfAllowTrustLineClawback, asfDisallowIncomingCheck,
* asfDisallowIncomingNFTokenOffer, asfDisallowIncomingPayChan,
* asfDisallowIncomingTrustline, asfAllowTrustLineLocking
*/
constexpr std::uint32_t
asfToLsf(std::uint32_t asf)
{
switch (asf)
{
case asfRequireDest:
return lsfRequireDestTag;
case asfRequireAuth:
return lsfRequireAuth;
case asfDisallowXRP:
return lsfDisallowXRP;
case asfDisableMaster:
return lsfDisableMaster;
case asfNoFreeze:
return lsfNoFreeze;
case asfGlobalFreeze:
return lsfGlobalFreeze;
case asfDefaultRipple:
return lsfDefaultRipple;
case asfDepositAuth:
return lsfDepositAuth;
case asfAllowTrustLineClawback:
return lsfAllowTrustLineClawback;
case asfDisallowIncomingCheck:
return lsfDisallowIncomingCheck;
case asfDisallowIncomingNFTokenOffer:
return lsfDisallowIncomingNFTokenOffer;
case asfDisallowIncomingPayChan:
return lsfDisallowIncomingPayChan;
case asfDisallowIncomingTrustline:
return lsfDisallowIncomingTrustline;
case asfAllowTrustLineLocking:
return lsfAllowTrustLineLocking;
default:
throw std::runtime_error("Unknown asf flag");
}
}
//------------------------------------------------------------------------------
// Feature helpers
//------------------------------------------------------------------------------
/**
* @brief Returns all testable amendments.
* @note This is similar to jtx::testable_amendments() but for the TxTest framework.
*/
FeatureBitset
allFeatures();
//------------------------------------------------------------------------------
// TxResult
//------------------------------------------------------------------------------
/**
* @brief Result of a transaction submission in TxTest.
*
* Contains the TER code, whether the transaction was applied,
* optional metadata, and a reference to the submitted transaction.
* Use standard gtest macros (EXPECT_EQ, EXPECT_TRUE, etc.) to verify results.
*/
struct TxResult
{
TER ter; /**< The transaction engine result code. */
bool applied; /**< Whether the transaction was applied to the ledger. */
std::optional<TxMeta> metadata; /**< Transaction metadata, if available. */
std::shared_ptr<STTx const> tx; /**< Pointer to the submitted transaction. */
};
/**
* @brief A lightweight transaction testing harness.
*
* Unlike the JTx framework which requires a full Application and RPC layer,
* TxTest applies transactions directly to an OpenView using the transactor
* pipeline (preflight -> preclaim -> doApply).
*
* This makes it suitable for:
* - Unit testing individual transactors
* - Testing transaction validation logic
* - Fast, focused tests without full server infrastructure
*
* @code
* TxTest env;
* env.submit(paymentTx).expectSuccess();
* env.submit(badTx).expectTer(tecNO_ENTRY);
* @endcode
*/
class TxTest
{
public:
/**
* @brief Construct a TxTest environment.
*
* Creates a genesis ledger and an open view on top of it.
*
* @param features Optional set of features to enable. If not specified,
* uses all testable amendments.
*/
explicit TxTest(std::optional<FeatureBitset> features = std::nullopt);
/**
* @brief Check if a feature is enabled.
* @param feature The feature to check.
* @return True if the feature is enabled.
*/
[[nodiscard]] bool
isEnabled(uint256 const& feature) const;
/**
* @brief Get the current rules.
* @return The current consensus rules.
*/
[[nodiscard]] Rules const&
getRules() const;
/**
* @brief Submit a transaction from a builder.
*
* Convenience overload that accepts transaction builders.
* Automatically sets sequence and fee before submission.
*
* @tparam T A type derived from TransactionBuilderBase.
* @param builder The transaction builder.
* @param signer The account to sign with.
* @return TxResult containing the result code, applied status, and metadata.
*/
template <typename T>
requires std::
derived_from<std::decay_t<T>, transactions::TransactionBuilderBase<std::decay_t<T>>>
[[nodiscard]] TxResult
submit(T&& builder, Account const& signer)
{
auto const& obj = builder.getSTObject();
auto accountId = obj[sfAccount];
// Only set sequence if not using a ticket (ticket sets sequence to 0)
if (!obj.isFieldPresent(sfTicketSequence))
{
builder.setSequence(getAccountRoot(accountId).getSequence());
}
else
{
builder.setSequence(0);
}
builder.setFee(XRPAmount(10));
return submit(builder.build(signer.pk(), signer.sk()).getSTTx());
}
/**
* @brief Submit a transaction to the open ledger.
*
* Applies the transaction through the full transactor pipeline:
* preflight -> preclaim -> doApply -> invariant checks
*
* Invariant checks are automatically run after doApply. If any
* invariant fails, the result will be tecINVARIANT_FAILED.
*
* @param stx The transaction to submit.
* @return TxResult containing the result code, applied status, and metadata.
*/
[[nodiscard]] TxResult
submit(std::shared_ptr<STTx const> stx);
/**
* @brief Create a new account in the ledger.
*
* Sends a Payment from the master account to create and fund the account.
* Closes the ledger after creation. If accountFlags is non-zero, submits
* an AccountSet transaction and closes again.
*
* @param account The account to create.
* @param xrp The initial XRP balance.
* @param accountFlags Optional account flags to set. Defaults to 0
* (no flags).
*/
void
createAccount(Account const& account, XRPAmount xrp, uint32_t accountFlags = 0);
/**
* @brief Get the account root object from the current open ledger.
* @param id The account ID.
* @return The AccountRoot ledger entry.
* @throws std::runtime_error if the account does not exist.
* @todo Once we make keylet strongly typed, we can ditch this method.
*/
[[nodiscard]] ledger_entries::AccountRoot
getAccountRoot(AccountID const& id) const;
/**
* @brief Get the current open ledger view.
* @return A mutable reference to the open ledger.
*/
[[nodiscard]] OpenView&
getOpenLedger();
/**
* @brief Get the current open ledger view (const).
* @return A const reference to the open ledger.
*/
[[nodiscard]] OpenView const&
getOpenLedger() const;
/**
* @brief Get the closed (base) ledger view.
* @return A const reference to the closed ledger.
*/
[[nodiscard]] ReadView const&
getClosedLedger() const;
/**
* @brief Close the current ledger.
*
* Creates a new closed ledger from the current open ledger.
* All pending transactions are re-applied in canonical order.
*/
void
close();
/**
* @brief Advance time without closing the ledger.
*
* Useful for testing time-dependent features like escrow release
* times or offer expirations.
*
* @param duration The amount of time to advance.
*/
void
advanceTime(NetClock::duration duration);
/**
* @brief Get the current ledger close time.
* @return The current close time.
*/
[[nodiscard]] NetClock::time_point
getCloseTime() const;
/**
* @brief Get the balance of an IOU for an account.
*
* Returns the balance from the perspective of the specified account.
* If the trust line doesn't exist, returns zero.
*
* @param account The account to check.
* @param iou The IOU to check the balance for.
* @return The balance as an STAmount.
* @todo Once we make keylet strongly typed, we can ditch this method.
*/
[[nodiscard]] STAmount
getBalance(AccountID const& account, IOU const& iou) const;
/**
* @brief Get the service registry.
* @return A reference to the service registry.
*/
ServiceRegistry&
getServiceRegistry()
{
return registry_;
}
private:
TestServiceRegistry registry_;
std::unordered_set<uint256, beast::uhash<>> featureSet_;
std::optional<Rules> rules_;
std::shared_ptr<Ledger const> closedLedger_;
std::shared_ptr<OpenView> openLedger_;
/** Transactions submitted to the open ledger, for canonical reordering on close. */
std::vector<std::shared_ptr<STTx const>> pendingTxs_;
/** Current time (can be advanced arbitrarily for testing). */
NetClock::time_point now_;
};
} // namespace xrpl::test

View File

@@ -0,0 +1,804 @@
#include <xrpl/protocol_autogen/transactions/AccountSet.h>
#include <xrpl/basics/Slice.h>
#include <xrpl/basics/base_uint.h>
#include <xrpl/beast/utility/Zero.h>
#include <xrpl/core/ServiceRegistry.h>
#include <xrpl/ledger/helpers/DirectoryHelpers.h>
#include <xrpl/protocol/Indexes.h>
#include <xrpl/protocol/KeyType.h>
#include <xrpl/protocol/LedgerFormats.h>
#include <xrpl/protocol/Quality.h>
#include <xrpl/protocol/Rate.h>
#include <xrpl/protocol/SField.h>
#include <xrpl/protocol/STArray.h>
#include <xrpl/protocol/STObject.h>
#include <xrpl/protocol/STTx.h>
#include <xrpl/protocol/SecretKey.h>
#include <xrpl/protocol/TER.h>
#include <xrpl/protocol/TxFlags.h>
#include <xrpl/protocol_autogen/ledger_entries/AccountRoot.h>
#include <xrpl/protocol_autogen/transactions/Payment.h>
#include <xrpl/protocol_autogen/transactions/SetRegularKey.h>
#include <xrpl/protocol_autogen/transactions/SignerListSet.h>
#include <xrpl/protocol_autogen/transactions/TicketCreate.h>
#include <xrpl/protocol_autogen/transactions/TrustSet.h>
#include <gtest/gtest.h>
#include <helpers/Account.h>
#include <helpers/IOU.h>
#include <helpers/TxTest.h>
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <initializer_list>
#include <limits>
#include <memory>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace xrpl::test {
TEST(AccountSet, NullAccountSet)
{
TxTest env;
Account const alice("alice");
env.createAccount(alice, XRP(10));
auto& view = env.getOpenLedger();
// ask for the ledger entry - account root, to check its flags
auto sle = view.read(keylet::account(alice));
EXPECT_NE(sle, nullptr);
ledger_entries::AccountRoot const accountRoot(sle);
EXPECT_EQ(accountRoot.getFlags(), 0);
}
TEST(AccountSet, MostFlags)
{
Account const alice("alice");
TxTest env;
env.createAccount(alice, XRP(10000));
// Give alice a regular key so she can legally set and clear
// her asfDisableMaster flag.
Account const aliceRegularKey{"aliceRegularKey", KeyType::secp256k1};
env.createAccount(aliceRegularKey, XRP(10000));
env.close();
EXPECT_EQ(
env.submit(transactions::SetRegularKeyBuilder{alice}.setRegularKey(aliceRegularKey), alice)
.ter,
tesSUCCESS);
env.close();
auto testFlags = [&alice, &aliceRegularKey, &env](
std::initializer_list<std::uint32_t> goodFlags) {
std::uint32_t const orig_flags = env.getAccountRoot(alice).getFlags();
for (std::uint32_t flag{1u}; flag < std::numeric_limits<std::uint32_t>::digits; ++flag)
{
if (flag == asfNoFreeze)
{
// The asfNoFreeze flag can't be cleared. It is tested
// elsewhere.
continue;
}
if (flag == asfAuthorizedNFTokenMinter)
{
// The asfAuthorizedNFTokenMinter flag requires the
// presence or absence of the sfNFTokenMinter field in
// the transaction. It is tested elsewhere.
continue;
}
if (flag == asfDisallowIncomingCheck || flag == asfDisallowIncomingPayChan ||
flag == asfDisallowIncomingNFTokenOffer || flag == asfDisallowIncomingTrustline)
{
// These flags are part of the DisallowIncoming amendment
// and are tested elsewhere
continue;
}
if (flag == asfAllowTrustLineClawback)
{
// The asfAllowTrustLineClawback flag can't be cleared. It
// is tested elsewhere.
continue;
}
if (flag == asfAllowTrustLineLocking)
{
// These flags are part of the AllowTokenLocking amendment
// and are tested elsewhere
continue;
}
if (std::ranges::find(goodFlags, flag) != goodFlags.end())
{
// Good flag
EXPECT_FALSE(env.getAccountRoot(alice).isFlag(asfToLsf(flag)));
EXPECT_EQ(
env.submit(transactions::AccountSetBuilder{alice}.setSetFlag(flag), alice).ter,
tesSUCCESS);
env.close();
EXPECT_TRUE(env.getAccountRoot(alice).isFlag(asfToLsf(flag)));
EXPECT_EQ(
env.submit(
transactions::AccountSetBuilder{alice}.setClearFlag(flag),
aliceRegularKey)
.ter,
tesSUCCESS);
env.close();
EXPECT_FALSE(env.getAccountRoot(alice).isFlag(asfToLsf(flag)));
std::uint32_t const now_flags = env.getAccountRoot(alice).getFlags();
EXPECT_EQ(now_flags, orig_flags);
}
else
{
// Bad flag
EXPECT_EQ(env.getAccountRoot(alice).getFlags(), orig_flags);
EXPECT_EQ(
env.submit(transactions::AccountSetBuilder{alice}.setSetFlag(flag), alice).ter,
tesSUCCESS);
env.close();
EXPECT_EQ(env.getAccountRoot(alice).getFlags(), orig_flags);
EXPECT_EQ(
env.submit(
transactions::AccountSetBuilder{alice}.setClearFlag(flag),
aliceRegularKey)
.ter,
tesSUCCESS);
env.close();
EXPECT_EQ(env.getAccountRoot(alice).getFlags(), orig_flags);
}
}
};
testFlags({
asfRequireDest,
asfRequireAuth,
asfDisallowXRP,
asfGlobalFreeze,
asfDisableMaster,
asfDefaultRipple,
asfDepositAuth,
});
}
TEST(AccountSet, SetAndResetAccountTxnID)
{
TxTest env;
Account const alice("alice");
env.createAccount(alice, XRP(10000));
std::uint32_t const orig_flags = env.getAccountRoot(alice).getFlags();
// asfAccountTxnID is special and not actually set as a flag,
// so we check the field presence instead
EXPECT_FALSE(env.getAccountRoot(alice).hasAccountTxnID());
EXPECT_EQ(
env.submit(transactions::AccountSetBuilder{alice}.setSetFlag(asfAccountTxnID), alice).ter,
tesSUCCESS);
env.close();
EXPECT_TRUE(env.getAccountRoot(alice).hasAccountTxnID());
EXPECT_EQ(
env.submit(transactions::AccountSetBuilder{alice}.setClearFlag(asfAccountTxnID), alice).ter,
tesSUCCESS);
env.close();
EXPECT_FALSE(env.getAccountRoot(alice).hasAccountTxnID());
std::uint32_t const now_flags = env.getAccountRoot(alice).getFlags();
EXPECT_EQ(now_flags, orig_flags);
}
TEST(AccountSet, SetNoFreeze)
{
TxTest env;
Account const alice("alice");
Account const eric("eric");
env.createAccount(alice, XRP(10000));
env.close();
// Set eric as alice's regular key (eric doesn't need to be funded)
EXPECT_EQ(
env.submit(transactions::SetRegularKeyBuilder{alice}.setRegularKey(eric), alice).ter,
tesSUCCESS);
env.close();
// Verify alice doesn't have NoFreeze flag
EXPECT_FALSE(env.getAccountRoot(alice).isFlag(lsfNoFreeze));
// Setting NoFreeze with regular key should fail - requires master key
EXPECT_EQ(
env.submit(transactions::AccountSetBuilder{alice}.setSetFlag(asfNoFreeze), eric).ter,
tecNEED_MASTER_KEY);
env.close();
// Setting NoFreeze with master key should succeed
EXPECT_EQ(
env.submit(transactions::AccountSetBuilder{alice}.setSetFlag(asfNoFreeze), alice).ter,
tesSUCCESS);
env.close();
// Verify alice now has NoFreeze flag
EXPECT_TRUE(env.getAccountRoot(alice).isFlag(lsfNoFreeze));
// Try to clear NoFreeze - transaction succeeds but flag remains set
EXPECT_EQ(
env.submit(transactions::AccountSetBuilder{alice}.setClearFlag(asfNoFreeze), alice).ter,
tesSUCCESS);
env.close();
// Verify flag is still set (NoFreeze cannot be cleared once set)
EXPECT_TRUE(env.getAccountRoot(alice).isFlag(lsfNoFreeze));
}
TEST(AccountSet, Domain)
{
TxTest env;
Account const alice("alice");
env.createAccount(alice, XRP(10000));
env.close();
// The Domain field is represented as the hex string of the lowercase
// ASCII of the domain. For example, the domain example.com would be
// represented as "6578616d706c652e636f6d".
//
// To remove the Domain field from an account, send an AccountSet with
// the Domain set to an empty string.
std::string const domain = "example.com";
// Set domain
EXPECT_EQ(
env.submit(transactions::AccountSetBuilder{alice}.setDomain(makeSlice(domain)), alice).ter,
tesSUCCESS);
env.close();
EXPECT_TRUE(env.getAccountRoot(alice).hasDomain());
// NOLINTNEXTLINE(bugprone-unchecked-optional-access)
EXPECT_EQ(*env.getAccountRoot(alice).getDomain(), makeSlice(domain));
// Clear domain by setting empty
EXPECT_EQ(
env.submit(transactions::AccountSetBuilder{alice}.setDomain(Slice{}), alice).ter,
tesSUCCESS);
env.close();
EXPECT_FALSE(env.getAccountRoot(alice).hasDomain());
// The upper limit on the length is 256 bytes
// (defined as DOMAIN_BYTES_MAX in SetAccount)
// test the edge cases: 255, 256, 257.
std::size_t const maxLength = 256;
for (std::size_t len = maxLength - 1; len <= maxLength + 1; ++len)
{
std::string const domain2 = std::string(len - domain.length() - 1, 'a') + "." + domain;
EXPECT_EQ(domain2.length(), len);
if (len <= maxLength)
{
EXPECT_EQ(
env.submit(
transactions::AccountSetBuilder{alice}.setDomain(makeSlice(domain2)), alice)
.ter,
tesSUCCESS);
env.close();
// NOLINTNEXTLINE(bugprone-unchecked-optional-access)
EXPECT_EQ(*env.getAccountRoot(alice).getDomain(), makeSlice(domain2));
}
else
{
EXPECT_EQ(
env.submit(
transactions::AccountSetBuilder{alice}.setDomain(makeSlice(domain2)), alice)
.ter,
telBAD_DOMAIN);
env.close();
}
}
}
TEST(AccountSet, MessageKey)
{
TxTest env;
Account const alice("alice");
env.createAccount(alice, XRP(10000));
env.close();
// Generate a random ed25519 key pair for the message key
auto const rkp = randomKeyPair(KeyType::ed25519);
// Set the message key
EXPECT_EQ(
env.submit(transactions::AccountSetBuilder{alice}.setMessageKey(rkp.first.slice()), alice)
.ter,
tesSUCCESS);
env.close();
EXPECT_TRUE(env.getAccountRoot(alice).hasMessageKey());
// NOLINTNEXTLINE(bugprone-unchecked-optional-access)
EXPECT_EQ(*env.getAccountRoot(alice).getMessageKey(), rkp.first.slice());
// Clear the message key by setting to empty
EXPECT_EQ(
env.submit(transactions::AccountSetBuilder{alice}.setMessageKey(Slice{}), alice).ter,
tesSUCCESS);
env.close();
EXPECT_FALSE(env.getAccountRoot(alice).hasMessageKey());
// Try to set an invalid public key - should fail
using namespace std::string_literals;
EXPECT_EQ(
env.submit(
transactions::AccountSetBuilder{alice}.setMessageKey(
makeSlice("NOT_REALLY_A_PUBKEY"s)),
alice)
.ter,
telBAD_PUBLIC_KEY);
}
TEST(AccountSet, WalletID)
{
TxTest env;
Account const alice("alice");
env.createAccount(alice, XRP(10000));
env.close();
std::string_view const locator =
"9633EC8AF54F16B5286DB1D7B519EF49EEFC050C0C8AC4384F1D88ACD1BFDF05";
uint256 locatorHash{};
EXPECT_TRUE(locatorHash.parseHex(locator));
// Set the wallet locator
EXPECT_EQ(
env.submit(transactions::AccountSetBuilder{alice}.setWalletLocator(locatorHash), alice).ter,
tesSUCCESS);
env.close();
EXPECT_TRUE(env.getAccountRoot(alice).hasWalletLocator());
// NOLINTNEXTLINE(bugprone-unchecked-optional-access)
EXPECT_EQ(*env.getAccountRoot(alice).getWalletLocator(), locatorHash);
// Clear the wallet locator by setting to zero
EXPECT_EQ(
env.submit(transactions::AccountSetBuilder{alice}.setWalletLocator(beast::zero), alice).ter,
tesSUCCESS);
env.close();
EXPECT_FALSE(env.getAccountRoot(alice).hasWalletLocator());
}
TEST(AccountSet, EmailHash)
{
TxTest env;
Account const alice("alice");
env.createAccount(alice, XRP(10000));
env.close();
std::string_view const mh = "5F31A79367DC3137FADA860C05742EE6";
uint128 emailHash{};
EXPECT_TRUE(emailHash.parseHex(mh));
// Set the email hash
EXPECT_EQ(
env.submit(transactions::AccountSetBuilder{alice}.setEmailHash(emailHash), alice).ter,
tesSUCCESS);
env.close();
EXPECT_TRUE(env.getAccountRoot(alice).hasEmailHash());
// NOLINTNEXTLINE(bugprone-unchecked-optional-access)
EXPECT_EQ(*env.getAccountRoot(alice).getEmailHash(), emailHash);
// Clear the email hash by setting to zero
EXPECT_EQ(
env.submit(transactions::AccountSetBuilder{alice}.setEmailHash(beast::zero), alice).ter,
tesSUCCESS);
env.close();
EXPECT_FALSE(env.getAccountRoot(alice).hasEmailHash());
}
TEST(AccountSet, TransferRate)
{
struct TestCase
{
double set;
TER code;
double get;
};
// Test data: {rate to set, expected TER, expected stored rate}
std::vector<TestCase> const testData = {
{1.0, tesSUCCESS, 1.0},
{1.1, tesSUCCESS, 1.1},
{2.0, tesSUCCESS, 2.0},
{2.1, temBAD_TRANSFER_RATE, 2.0}, // > 2.0 is invalid
{0.0, tesSUCCESS, 1.0}, // 0 clears the rate (default = 1.0)
{2.0, tesSUCCESS, 2.0},
{0.9, temBAD_TRANSFER_RATE, 2.0}, // < 1.0 is invalid
};
TxTest env;
Account const alice("alice");
env.createAccount(alice, XRP(10000));
env.close();
for (auto const& r : testData)
{
auto const rateValue = static_cast<std::uint32_t>(QUALITY_ONE * r.set);
EXPECT_EQ(
env.submit(transactions::AccountSetBuilder{alice}.setTransferRate(rateValue), alice)
.ter,
r.code);
env.close();
// If the field is not present, expect the default value (1.0)
if (!env.getAccountRoot(alice).hasTransferRate())
{
EXPECT_EQ(r.get, 1.0);
}
else
{
// NOLINTNEXTLINE(bugprone-unchecked-optional-access)
EXPECT_EQ(
*env.getAccountRoot(alice).getTransferRate(),
static_cast<std::uint32_t>(r.get * QUALITY_ONE));
}
}
}
TEST(AccountSet, BadInputs)
{
TxTest env;
Account const alice("alice");
env.createAccount(alice, XRP(10000));
env.close();
// Setting and clearing the same flag is invalid
EXPECT_EQ(
env.submit(
transactions::AccountSetBuilder{alice}
.setSetFlag(asfDisallowXRP)
.setClearFlag(asfDisallowXRP),
alice)
.ter,
temINVALID_FLAG);
EXPECT_EQ(
env.submit(
transactions::AccountSetBuilder{alice}
.setSetFlag(asfRequireAuth)
.setClearFlag(asfRequireAuth),
alice)
.ter,
temINVALID_FLAG);
EXPECT_EQ(
env.submit(
transactions::AccountSetBuilder{alice}
.setSetFlag(asfRequireDest)
.setClearFlag(asfRequireDest),
alice)
.ter,
temINVALID_FLAG);
// Setting asf flag while also using corresponding tf flag is invalid
EXPECT_EQ(
env.submit(
transactions::AccountSetBuilder{alice}
.setSetFlag(asfDisallowXRP)
.setFlags(tfAllowXRP),
alice)
.ter,
temINVALID_FLAG);
EXPECT_EQ(
env.submit(
transactions::AccountSetBuilder{alice}
.setSetFlag(asfRequireAuth)
.setFlags(tfOptionalAuth),
alice)
.ter,
temINVALID_FLAG);
EXPECT_EQ(
env.submit(
transactions::AccountSetBuilder{alice}
.setSetFlag(asfRequireDest)
.setFlags(tfOptionalDestTag),
alice)
.ter,
temINVALID_FLAG);
// Using invalid flags (mask) is invalid
EXPECT_EQ(
env.submit(
transactions::AccountSetBuilder{alice}
.setSetFlag(asfRequireDest)
.setFlags(tfAccountSetMask),
alice)
.ter,
temINVALID_FLAG);
// Disabling master key without an alternative key is invalid
EXPECT_EQ(
env.submit(transactions::AccountSetBuilder{alice}.setSetFlag(asfDisableMaster), alice).ter,
tecNO_ALTERNATIVE_KEY);
}
TEST(AccountSet, RequireAuthWithDir)
{
TxTest env;
Account const alice("alice");
Account const bob("bob");
env.createAccount(alice, XRP(10000));
env.close();
// alice should have an empty directory
EXPECT_TRUE(dirIsEmpty(env.getClosedLedger(), keylet::ownerDir(alice.id())));
// Give alice a signer list, then there will be stuff in the directory
// Build the SignerEntries array
STArray signerEntries(1);
{
signerEntries.push_back(STObject::makeInnerObject(sfSignerEntry));
STObject& entry = signerEntries.back();
entry[sfAccount] = bob.id();
entry[sfSignerWeight] = std::uint16_t{1};
}
EXPECT_EQ(
env.submit(
transactions::SignerListSetBuilder{alice, 1}.setSignerEntries(signerEntries), alice)
.ter,
tesSUCCESS);
env.close();
EXPECT_FALSE(dirIsEmpty(env.getClosedLedger(), keylet::ownerDir(alice.id())));
// Setting RequireAuth should fail because alice has owner objects
EXPECT_EQ(
env.submit(transactions::AccountSetBuilder{alice}.setSetFlag(asfRequireAuth), alice).ter,
tecOWNERS);
// Remove the signer list (quorum = 0, no entries)
EXPECT_EQ(env.submit(transactions::SignerListSetBuilder{alice, 0}, alice).ter, tesSUCCESS);
env.close();
EXPECT_TRUE(dirIsEmpty(env.getClosedLedger(), keylet::ownerDir(alice.id())));
// Now setting RequireAuth should succeed
EXPECT_EQ(
env.submit(transactions::AccountSetBuilder{alice}.setSetFlag(asfRequireAuth), alice).ter,
tesSUCCESS);
}
TEST(AccountSet, Ticket)
{
TxTest env;
Account const alice("alice");
env.createAccount(alice, XRP(10000));
env.close();
// Get alice's current sequence - the ticket will be created at seq + 1
std::uint32_t const aliceSeqBefore = env.getAccountRoot(alice.id()).getSequence();
std::uint32_t const ticketSeq = aliceSeqBefore + 1;
// Create a ticket
EXPECT_EQ(env.submit(transactions::TicketCreateBuilder{alice, 1}, alice).ter, tesSUCCESS);
env.close();
// Verify alice has 1 owner object (the ticket)
EXPECT_EQ(env.getAccountRoot(alice.id()).getOwnerCount(), 1u);
// Verify ticket exists
EXPECT_TRUE(env.getClosedLedger().exists(keylet::ticket(alice.id(), ticketSeq)));
// Try using a ticket that alice doesn't have
EXPECT_EQ(
env.submit(transactions::AccountSetBuilder{alice}.setTicketSequence(ticketSeq + 1), alice)
.ter,
terPRE_TICKET);
env.close();
// Verify ticket still exists
EXPECT_TRUE(env.getClosedLedger().exists(keylet::ticket(alice.id(), ticketSeq)));
// Get alice's sequence before using the ticket
std::uint32_t const aliceSeq = env.getAccountRoot(alice.id()).getSequence();
// Actually use alice's ticket (noop AccountSet)
EXPECT_EQ(
env.submit(transactions::AccountSetBuilder{alice}.setTicketSequence(ticketSeq), alice).ter,
tesSUCCESS);
env.close();
// Verify ticket is consumed (no owner objects)
EXPECT_EQ(env.getAccountRoot(alice.id()).getOwnerCount(), 0u);
EXPECT_FALSE(env.getClosedLedger().exists(keylet::ticket(alice.id(), ticketSeq)));
// Verify alice's sequence did NOT advance (ticket use doesn't increment seq)
EXPECT_EQ(env.getAccountRoot(alice.id()).getSequence(), aliceSeq);
// Try re-using a ticket that alice already used
EXPECT_EQ(
env.submit(transactions::AccountSetBuilder{alice}.setTicketSequence(ticketSeq), alice).ter,
tefNO_TICKET);
}
TEST(AccountSet, BadSigningKey)
{
TxTest env;
Account const alice("alice");
env.createAccount(alice, XRP(10000));
env.close();
// Build a valid transaction first, then corrupt the signing key
auto stx = transactions::AccountSetBuilder{alice}
.setSequence(env.getAccountRoot(alice.id()).getSequence())
.setFee(XRPAmount{10})
.build(alice.pk(), alice.sk())
.getSTTx();
// Create a copy with a bad signing key
STObject obj = *stx;
obj.setFieldVL(sfSigningPubKey, makeSlice(std::string("badkey")));
auto result = env.submit(std::make_shared<STTx>(std::move(obj)));
EXPECT_EQ(result.ter, temBAD_SIGNATURE);
EXPECT_FALSE(result.applied);
}
TEST(AccountSet, Gateway)
{
Account const alice("alice");
Account const bob("bob");
Account const gw("gateway");
IOU const USD("USD", gw);
// Test gateway with a variety of allowed transfer rates
for (double transferRate = 1.0; transferRate <= 2.0; transferRate += 0.03125)
{
TxTest env;
env.createAccount(gw, XRP(10000), asfDefaultRipple);
env.createAccount(alice, XRP(10000), asfDefaultRipple);
env.createAccount(bob, XRP(10000), asfDefaultRipple);
env.close();
// Set up trust lines: alice and bob trust gw for USD
EXPECT_EQ(
env.submit(transactions::TrustSetBuilder{alice}.setLimitAmount(USD.amount(10)), alice)
.ter,
tesSUCCESS);
EXPECT_EQ(
env.submit(transactions::TrustSetBuilder{bob}.setLimitAmount(USD.amount(10)), bob).ter,
tesSUCCESS);
env.close();
// Set transfer rate on the gateway
EXPECT_EQ(
env.submit(
transactions::AccountSetBuilder{gw}.setTransferRate(
static_cast<std::uint32_t>(transferRate * QUALITY_ONE)),
gw)
.ter,
tesSUCCESS);
env.close();
// Calculate the amount with transfer rate applied
auto const amount = USD.amount(1);
Rate const rate(static_cast<std::uint32_t>(transferRate * QUALITY_ONE));
auto const amountWithRate = multiply(amount, rate);
// Gateway pays alice 10 USD
EXPECT_EQ(
env.submit(transactions::PaymentBuilder{gw, alice, USD.amount(10)}, gw).ter,
tesSUCCESS);
env.close();
// Alice pays bob 1 USD (with sendmax to cover transfer fee)
EXPECT_EQ(
env.submit(
transactions::PaymentBuilder{alice, bob, USD.amount(1)}.setSendMax(
USD.amount(10)),
alice)
.ter,
tesSUCCESS);
env.close();
// Check balances
EXPECT_EQ(env.getBalance(alice.id(), USD), USD.amount(10) - amountWithRate);
EXPECT_EQ(env.getBalance(bob.id(), USD), USD.amount(1));
}
// Test out-of-bounds legacy transfer rates (4.0 and 4.294967295)
// These require direct ledger modification since the transactor blocks them
for (std::uint32_t const transferRate : {4000000000U, 4294967295U})
{
TxTest env;
env.createAccount(gw, XRP(10000), asfDefaultRipple);
env.createAccount(alice, XRP(10000), asfDefaultRipple);
env.createAccount(bob, XRP(10000), asfDefaultRipple);
env.close();
// Set up trust lines
EXPECT_EQ(
env.submit(transactions::TrustSetBuilder{alice}.setLimitAmount(USD.amount(10)), alice)
.ter,
tesSUCCESS);
EXPECT_EQ(
env.submit(transactions::TrustSetBuilder{bob}.setLimitAmount(USD.amount(10)), bob).ter,
tesSUCCESS);
env.close();
// Set an acceptable transfer rate first (we'll hack it later)
EXPECT_EQ(
env.submit(
transactions::AccountSetBuilder{gw}.setTransferRate(
static_cast<std::uint32_t>(2.0 * QUALITY_ONE)),
gw)
.ter,
tesSUCCESS);
env.close();
// Directly modify the ledger to set an out-of-bounds transfer rate
// This bypasses the transactor's validation
auto& view = env.getOpenLedger();
auto slePtr = view.read(keylet::account(gw.id()));
ASSERT_NE(slePtr, nullptr);
auto sleCopy = std::make_shared<SLE>(*slePtr);
(*sleCopy)[sfTransferRate] = transferRate;
view.rawReplace(sleCopy);
// Calculate the amount with the legacy transfer rate
auto const amount = USD.amount(1);
auto const amountWithRate = multiply(amount, Rate(transferRate));
// Gateway pays alice 10 USD
EXPECT_EQ(
env.submit(transactions::PaymentBuilder{gw, alice, USD.amount(10)}, gw).ter,
tesSUCCESS);
// Alice pays bob 1 USD
EXPECT_EQ(
env.submit(
transactions::PaymentBuilder{alice, bob, amount}.setSendMax(USD.amount(10)),
alice)
.ter,
tesSUCCESS);
// Check balances
EXPECT_EQ(env.getBalance(alice.id(), USD), USD.amount(10) - amountWithRate);
EXPECT_EQ(env.getBalance(bob.id(), USD), amount);
}
}
} // namespace xrpl::test

View File

@@ -0,0 +1,8 @@
#include <gtest/gtest.h>
int
main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@@ -12,10 +12,10 @@ BasicApp::BasicApp(std::size_t numberOfThreads)
work_.emplace(boost::asio::make_work_guard(io_context_));
threads_.reserve(numberOfThreads);
while ((numberOfThreads--) != 0u)
for (std::size_t i = 0; i < numberOfThreads; ++i)
{
threads_.emplace_back([this, numberOfThreads]() {
beast::setCurrentThreadName("io svc #" + std::to_string(numberOfThreads));
threads_.emplace_back([this, i]() {
beast::setCurrentThreadName("io svc #" + std::to_string(i));
this->io_context_.run();
});
}

View File

@@ -8,6 +8,9 @@
namespace xrpl::PeerFinder {
/** Direction of a slot count adjustment. */
enum class CountAdjustment : int { Decrement = -1, Increment = 1 };
/** Manages the count of available connections for the various slots. */
class Counts
{
@@ -16,14 +19,14 @@ public:
void
add(Slot const& s)
{
adjust(s, 1);
adjust(s, CountAdjustment::Increment);
}
/** Removes the slot state and properties from the slot counts. */
void
remove(Slot const& s)
{
adjust(s, -1);
adjust(s, CountAdjustment::Decrement);
}
/** Returns `true` if the slot can become active. */
@@ -207,21 +210,40 @@ public:
//--------------------------------------------------------------------------
private:
/** Increments or decrements a counter based on the adjustment direction. */
template <typename T>
static void
adjustCounter(T& counter, CountAdjustment dir)
{
switch (dir)
{
case CountAdjustment::Increment:
++counter;
break;
case CountAdjustment::Decrement:
--counter;
break;
}
}
// Adjusts counts based on the specified slot, in the direction indicated.
// Using ++/-- instead of += on std::size_t counters avoids UBSan
// unsigned-integer-overflow from implicit conversion of -1 to SIZE_MAX.
// A decrement on a zero counter is a real bug that UBSan should catch.
void
adjust(Slot const& s, int const n)
adjust(Slot const& s, CountAdjustment const dir)
{
if (s.fixed())
m_fixed += n;
adjustCounter(m_fixed, dir);
if (s.reserved())
m_reserved += n;
adjustCounter(m_reserved, dir);
switch (s.state())
{
case Slot::accept:
XRPL_ASSERT(s.inbound(), "xrpl::PeerFinder::Counts::adjust : input is inbound");
m_acceptCount += n;
adjustCounter(m_acceptCount, dir);
break;
case Slot::connect:
@@ -230,28 +252,28 @@ private:
!s.inbound(),
"xrpl::PeerFinder::Counts::adjust : input is not "
"inbound");
m_attempts += n;
adjustCounter(m_attempts, dir);
break;
case Slot::active:
if (s.fixed())
m_fixed_active += n;
adjustCounter(m_fixed_active, dir);
if (!s.fixed() && !s.reserved())
{
if (s.inbound())
{
m_in_active += n;
adjustCounter(m_in_active, dir);
}
else
{
m_out_active += n;
adjustCounter(m_out_active, dir);
}
}
m_active += n;
adjustCounter(m_active, dir);
break;
case Slot::closing:
m_closingCount += n;
adjustCounter(m_closingCount, dir);
break;
// LCOV_EXCL_START