Merge remote-tracking branch 'mywork/ximinez/lending-number' into ximinez/lending-XLS-66

* mywork/ximinez/lending-number:
  Catch up the consequences of Number changes
  Fix build error - avoid copy
  Add integer enforcement when converting to XRP/MPTAmount to Number
  Make all STNumber fields "soeDEFAULT"
  Add optional enforcement of valid integer range to Number
  fix: domain order book insertion #5998
  refactor: Retire fixTrustLinesToSelf amendment (#5989)
This commit is contained in:
Ed Hennis
2025-11-05 19:29:27 -05:00
23 changed files with 576 additions and 164 deletions

View File

@@ -24,17 +24,38 @@ isPowerOfTen(T value)
class Number
{
public:
/** Describes whether and how to enforce this number as an integer.
*
* - none: No enforcement. The value may vary freely. This is the default.
* - weak: If the absolute value is greater than maxIntValue, valid() will
* return false.
* - strong: Assignment operations will throw if the absolute value is above
* maxIntValue.
*/
enum EnforceInteger { none, weak, strong };
private:
using rep = std::int64_t;
rep mantissa_{0};
int exponent_{std::numeric_limits<int>::lowest()};
// The enforcement setting is not serialized, and does not affect the
// ledger. If not "none", the value is checked to be within the valid
// integer range. With "strong", the checks will be made as automatic as
// possible.
EnforceInteger enforceInteger_ = none;
public:
// The range for the mantissa when normalized
constexpr static std::int64_t minMantissa = 1'000'000'000'000'000LL;
constexpr static rep minMantissa = 1'000'000'000'000'000LL;
static_assert(isPowerOfTen(minMantissa));
constexpr static std::int64_t maxMantissa = minMantissa * 10 - 1;
constexpr static rep maxMantissa = minMantissa * 10 - 1;
static_assert(maxMantissa == 9'999'999'999'999'999LL);
constexpr static rep maxIntValue = maxMantissa / 10;
static_assert(maxIntValue == 999'999'999'999'999LL);
// The range for the exponent when normalized
constexpr static int minExponent = -32768;
constexpr static int maxExponent = 32768;
@@ -46,15 +67,33 @@ public:
explicit constexpr Number() = default;
Number(rep mantissa);
explicit Number(rep mantissa, int exponent);
Number(rep mantissa, EnforceInteger enforce = none);
explicit Number(rep mantissa, int exponent, EnforceInteger enforce = none);
explicit constexpr Number(rep mantissa, int exponent, unchecked) noexcept;
constexpr Number(Number const& other) = default;
constexpr Number(Number&& other) = default;
~Number() = default;
constexpr Number&
operator=(Number const& other);
constexpr Number&
operator=(Number&& other);
constexpr rep
mantissa() const noexcept;
constexpr int
exponent() const noexcept;
void
setIntegerEnforcement(EnforceInteger enforce);
EnforceInteger
integerEnforcement() const noexcept;
bool
valid() const noexcept;
constexpr Number
operator+() const noexcept;
constexpr Number
@@ -180,6 +219,9 @@ public:
private:
static thread_local rounding_mode mode_;
void
checkInteger(char const* what) const;
void
normalize();
constexpr bool
@@ -195,16 +237,52 @@ inline constexpr Number::Number(rep mantissa, int exponent, unchecked) noexcept
{
}
inline Number::Number(rep mantissa, int exponent)
: mantissa_{mantissa}, exponent_{exponent}
inline Number::Number(rep mantissa, int exponent, EnforceInteger enforce)
: mantissa_{mantissa}, exponent_{exponent}, enforceInteger_(enforce)
{
normalize();
checkInteger("Number::Number integer overflow");
}
inline Number::Number(rep mantissa) : Number{mantissa, 0}
inline Number::Number(rep mantissa, EnforceInteger enforce)
: Number{mantissa, 0, enforce}
{
}
constexpr Number&
Number::operator=(Number const& other)
{
if (this != &other)
{
mantissa_ = other.mantissa_;
exponent_ = other.exponent_;
enforceInteger_ = std::max(enforceInteger_, other.enforceInteger_);
checkInteger("Number::operator= integer overflow");
}
return *this;
}
constexpr Number&
Number::operator=(Number&& other)
{
if (this != &other)
{
// std::move doesn't really do anything for these types, but
// this is future-proof in case the types ever change
mantissa_ = std::move(other.mantissa_);
exponent_ = std::move(other.exponent_);
if (other.enforceInteger_ > enforceInteger_)
enforceInteger_ = std::move(other.enforceInteger_);
checkInteger("Number::operator= integer overflow");
}
return *this;
}
inline constexpr Number::rep
Number::mantissa() const noexcept
{
@@ -217,6 +295,20 @@ Number::exponent() const noexcept
return exponent_;
}
inline void
Number::setIntegerEnforcement(EnforceInteger enforce)
{
enforceInteger_ = enforce;
checkInteger("Number::setIntegerEnforcement integer overflow");
}
inline Number::EnforceInteger
Number::integerEnforcement() const noexcept
{
return enforceInteger_;
}
inline constexpr Number
Number::operator+() const noexcept
{

View File

@@ -62,9 +62,15 @@ public:
explicit constexpr
operator bool() const noexcept;
operator Number() const noexcept
operator Number() const
{
return value();
return {value(), Number::strong};
}
Number
toNumber(Number::EnforceInteger enforce) const
{
return {value(), enforce};
}
/** Return the sign of the amount */

View File

@@ -40,6 +40,12 @@ private:
exponent_type mOffset;
bool mIsNegative;
// The Enforce integer setting is not stored or serialized. If set, it is
// used during automatic conversions to Number. If not set, the default
// behavior is used. It can also be overridden when coverting by using
// toNumber().
std::optional<Number::EnforceInteger> enforceConversion_;
public:
using value_type = STAmount;
@@ -137,9 +143,28 @@ public:
STAmount(A const& asset, int mantissa, int exponent = 0);
template <AssetType A>
STAmount(A const& asset, Number const& number)
STAmount(
A const& asset,
Number const& number,
std::optional<Number::EnforceInteger> enforce = std::nullopt)
: STAmount(asset, number.mantissa(), number.exponent())
{
enforceConversion_ = enforce;
if (!enforce)
{
// Use the default conversion behavior
[[maybe_unused]]
Number const n = *this;
}
else if (enforce == Number::strong)
{
// Throw if it's not valid
if (!validNumber())
{
Throw<std::overflow_error>(
"STAmount::STAmount integer Number lost precision");
}
}
}
// Legacy support for new-style amounts
@@ -147,6 +172,17 @@ public:
STAmount(XRPAmount const& amount);
STAmount(MPTAmount const& amount, MPTIssue const& mptIssue);
operator Number() const;
Number
toNumber(Number::EnforceInteger enforce) const;
void
setIntegerEnforcement(std::optional<Number::EnforceInteger> enforce);
std::optional<Number::EnforceInteger>
integerEnforcement() const noexcept;
bool
validNumber() const noexcept;
//--------------------------------------------------------------------------
//
@@ -521,6 +557,8 @@ inline STAmount::operator bool() const noexcept
inline STAmount::operator Number() const
{
if (enforceConversion_)
return toNumber(*enforceConversion_);
if (native())
return xrp();
if (mAsset.holds<MPTIssue>())
@@ -528,6 +566,17 @@ inline STAmount::operator Number() const
return iou();
}
inline Number
STAmount::toNumber(Number::EnforceInteger enforce) const
{
if (native())
return xrp().toNumber(enforce);
if (mAsset.holds<MPTIssue>())
return mpt().toNumber(enforce);
// It doesn't make sense to enforce limits on IOUs
return iou();
}
inline STAmount&
STAmount::operator=(beast::Zero)
{
@@ -549,6 +598,11 @@ STAmount::operator=(Number const& number)
mValue = mIsNegative ? -number.mantissa() : number.mantissa();
mOffset = number.exponent();
canonicalize();
// Convert it back to a Number to check that it's valid
[[maybe_unused]]
Number n = *this;
return *this;
}
@@ -564,7 +618,7 @@ STAmount::clear()
{
// The -100 is used to allow 0 to sort less than a small positive values
// which have a negative exponent.
mOffset = native() ? 0 : -100;
mOffset = integral() ? 0 : -100;
mValue = 0;
mIsNegative = false;
}

View File

@@ -56,6 +56,18 @@ public:
bool
isDefault() const override;
/// Sets the flag on the underlying number
void
setIntegerEnforcement(Number::EnforceInteger enforce);
/// Gets the flag value on the underlying number
Number::EnforceInteger
integerEnforcement() const noexcept;
/// Checks the underlying number
bool
valid() const noexcept;
operator Number() const
{
return value_;

View File

@@ -23,6 +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);
/** Returns true if the amount does not exceed the initial XRP in existence. */
inline bool

View File

@@ -143,7 +143,13 @@ public:
operator Number() const noexcept
{
return drops();
return {drops(), Number::weak};
}
Number
toNumber(Number::EnforceInteger enforce) const
{
return {value(), enforce};
}
/** Return the sign of the amount */

View File

@@ -65,7 +65,6 @@ XRPL_FIX (UniversalNumber, Supported::yes, VoteBehavior::DefaultNo
XRPL_FEATURE(XRPFees, Supported::yes, VoteBehavior::DefaultNo)
XRPL_FEATURE(DisallowIncoming, Supported::yes, VoteBehavior::DefaultNo)
XRPL_FIX (RemoveNFTokenAutoTrustLine, Supported::yes, VoteBehavior::DefaultYes)
XRPL_FIX (TrustLinesToSelf, Supported::yes, VoteBehavior::DefaultNo)
XRPL_FEATURE(ExpandedSignerList, Supported::yes, VoteBehavior::DefaultNo)
XRPL_FEATURE(CheckCashMakesTrustLine, Supported::yes, VoteBehavior::DefaultNo)
XRPL_FEATURE(FlowSortStrands, Supported::yes, VoteBehavior::DefaultYes)
@@ -122,6 +121,7 @@ XRPL_RETIRE(fixReducedOffersV1)
XRPL_RETIRE(fixRmSmallIncreasedQOffers)
XRPL_RETIRE(fixSTAmountCanonicalize)
XRPL_RETIRE(fixTakerDryOfferRemoval)
XRPL_RETIRE(fixTrustLinesToSelf)
XRPL_RETIRE(CryptoConditions)
XRPL_RETIRE(Escrow)
XRPL_RETIRE(EnforceInvariants)

View File

@@ -480,10 +480,10 @@ LEDGER_ENTRY(ltVAULT, 0x0084, Vault, vault, ({
{sfAccount, soeREQUIRED},
{sfData, soeOPTIONAL},
{sfAsset, soeREQUIRED},
{sfAssetsTotal, soeREQUIRED},
{sfAssetsAvailable, soeREQUIRED},
{sfAssetsTotal, soeDEFAULT},
{sfAssetsAvailable, soeDEFAULT},
{sfAssetsMaximum, soeDEFAULT},
{sfLossUnrealized, soeREQUIRED},
{sfLossUnrealized, soeDEFAULT},
{sfShareMPTID, soeREQUIRED},
{sfWithdrawalPolicy, soeREQUIRED},
{sfScale, soeDEFAULT},

View File

@@ -222,6 +222,13 @@ Number::Guard::doRound(rep& drops)
constexpr Number one{1000000000000000, -15, Number::unchecked{}};
void
Number::checkInteger(char const* what) const
{
if (enforceInteger_ == strong && !valid())
throw std::overflow_error(what);
}
void
Number::normalize()
{
@@ -263,9 +270,27 @@ Number::normalize()
mantissa_ = -mantissa_;
}
bool
Number::valid() const noexcept
{
if (enforceInteger_ != none)
{
static Number const max = maxIntValue;
static Number const maxNeg = -maxIntValue;
// Avoid making a copy
if (mantissa_ < 0)
return *this >= maxNeg;
return *this <= max;
}
return true;
}
Number&
Number::operator+=(Number const& y)
{
// The strictest setting prevails
enforceInteger_ = std::max(enforceInteger_, y.enforceInteger_);
if (y == Number{})
return *this;
if (*this == Number{})
@@ -353,6 +378,9 @@ Number::operator+=(Number const& y)
}
mantissa_ = xm * xn;
exponent_ = xe;
checkInteger("Number::addition integer overflow");
return *this;
}
@@ -387,6 +415,9 @@ divu10(uint128_t& u)
Number&
Number::operator*=(Number const& y)
{
// The strictest setting prevails
enforceInteger_ = std::max(enforceInteger_, y.enforceInteger_);
if (*this == Number{})
return *this;
if (y == Number{})
@@ -438,12 +469,18 @@ Number::operator*=(Number const& y)
XRPL_ASSERT(
isnormal() || *this == Number{},
"ripple::Number::operator*=(Number) : result is normal");
checkInteger("Number::multiplication integer overflow");
return *this;
}
Number&
Number::operator/=(Number const& y)
{
// The strictest setting prevails
enforceInteger_ = std::max(enforceInteger_, y.enforceInteger_);
if (y == Number{})
throw std::overflow_error("Number: divide by 0");
if (*this == Number{})
@@ -471,6 +508,9 @@ Number::operator/=(Number const& y)
exponent_ = ne - de - 17;
mantissa_ *= np * dp;
normalize();
checkInteger("Number::division integer overflow");
return *this;
}

View File

@@ -3464,13 +3464,17 @@ assetsToSharesDeposit(
Number const assetTotal = vault->at(sfAssetsTotal);
STAmount shares{vault->at(sfShareMPTID)};
shares.setIntegerEnforcement(Number::weak);
if (assetTotal == 0)
return STAmount{
shares.asset(),
Number(assets.mantissa(), assets.exponent() + vault->at(sfScale))
.truncate()};
.truncate(),
Number::weak};
Number const shareTotal = issuance->at(sfOutstandingAmount);
Number const shareTotal{
unsafe_cast<std::int64_t>(issuance->at(sfOutstandingAmount)),
Number::strong};
shares = (shareTotal * (assets / assetTotal)).truncate();
return shares;
}
@@ -3492,6 +3496,7 @@ sharesToAssetsDeposit(
Number const assetTotal = vault->at(sfAssetsTotal);
STAmount assets{vault->at(sfAsset)};
assets.setIntegerEnforcement(Number::weak);
if (assetTotal == 0)
return STAmount{
assets.asset(),
@@ -3499,7 +3504,9 @@ sharesToAssetsDeposit(
shares.exponent() - vault->at(sfScale),
false};
Number const shareTotal = issuance->at(sfOutstandingAmount);
Number const shareTotal{
unsafe_cast<std::int64_t>(issuance->at(sfOutstandingAmount)),
Number::strong};
assets = assetTotal * (shares / shareTotal);
return assets;
}
@@ -3523,9 +3530,12 @@ assetsToSharesWithdraw(
Number assetTotal = vault->at(sfAssetsTotal);
assetTotal -= vault->at(sfLossUnrealized);
STAmount shares{vault->at(sfShareMPTID)};
shares.setIntegerEnforcement(Number::weak);
if (assetTotal == 0)
return shares;
Number const shareTotal = issuance->at(sfOutstandingAmount);
Number const shareTotal{
unsafe_cast<std::int64_t>(issuance->at(sfOutstandingAmount)),
Number::strong};
Number result = shareTotal * (assets / assetTotal);
if (truncate == TruncateShares::yes)
result = result.truncate();
@@ -3551,9 +3561,12 @@ sharesToAssetsWithdraw(
Number assetTotal = vault->at(sfAssetsTotal);
assetTotal -= vault->at(sfLossUnrealized);
STAmount assets{vault->at(sfAsset)};
assets.setIntegerEnforcement(Number::weak);
if (assetTotal == 0)
return assets;
Number const shareTotal = issuance->at(sfOutstandingAmount);
Number const shareTotal{
unsafe_cast<std::int64_t>(issuance->at(sfOutstandingAmount)),
Number::strong};
assets = assetTotal * (shares / shareTotal);
return assets;
}

View File

@@ -255,6 +255,25 @@ STAmount::move(std::size_t n, void* buf)
return emplace(n, buf, std::move(*this));
}
void
STAmount::setIntegerEnforcement(std::optional<Number::EnforceInteger> enforce)
{
enforceConversion_ = enforce;
}
std::optional<Number::EnforceInteger>
STAmount::integerEnforcement() const noexcept
{
return enforceConversion_;
}
bool
STAmount::validNumber() const noexcept
{
Number n = toNumber(Number::EnforceInteger::weak);
return n.valid();
}
//------------------------------------------------------------------------------
//
// Conversion

View File

@@ -94,6 +94,24 @@ STNumber::isDefault() const
return value_ == Number();
}
void
STNumber::setIntegerEnforcement(Number::EnforceInteger enforce)
{
value_.setIntegerEnforcement(enforce);
}
Number::EnforceInteger
STNumber::integerEnforcement() const noexcept
{
return value_.integerEnforcement();
}
bool
STNumber::valid() const noexcept
{
return value_.valid();
}
std::ostream&
operator<<(std::ostream& out, STNumber const& rhs)
{

View File

@@ -1384,7 +1384,7 @@ private:
// equal asset deposit: unit test to exercise the rounding-down of
// LPTokens in the AMMHelpers.cpp: adjustLPTokens calculations
// The LPTokens need to have 16 significant digits and a fractional part
for (Number const deltaLPTokens :
for (Number const& deltaLPTokens :
{Number{UINT64_C(100000'0000000009), -10},
Number{UINT64_C(100000'0000000001), -10}})
{

View File

@@ -3632,7 +3632,32 @@ class Vault_test : public beast::unit_test::suite
});
testCase(18, [&, this](Env& env, Data d) {
testcase("Scale deposit overflow on second deposit");
testcase("MPT scale deposit overflow");
// The computed number of shares can not be represented as an MPT
// without truncation
{
auto tx = d.vault.deposit(
{.depositor = d.depositor,
.id = d.keylet.key,
.amount = d.asset(5)});
env(tx, ter{tecPRECISION_LOSS});
env.close();
}
});
testCase(14, [&, this](Env& env, Data d) {
testcase("MPT scale deposit overflow on first deposit");
auto tx = d.vault.deposit(
{.depositor = d.depositor,
.id = d.keylet.key,
.amount = d.asset(10)});
env(tx, ter{tecPRECISION_LOSS});
env.close();
});
testCase(14, [&, this](Env& env, Data d) {
testcase("MPT scale deposit overflow on second deposit");
{
auto tx = d.vault.deposit(
@@ -3653,8 +3678,8 @@ class Vault_test : public beast::unit_test::suite
}
});
testCase(18, [&, this](Env& env, Data d) {
testcase("Scale deposit overflow on total shares");
testCase(14, [&, this](Env& env, Data d) {
testcase("No MPT scale deposit overflow on total shares");
{
auto tx = d.vault.deposit(
@@ -3670,7 +3695,7 @@ class Vault_test : public beast::unit_test::suite
{.depositor = d.depositor,
.id = d.keylet.key,
.amount = d.asset(5)});
env(tx, ter{tecPATH_DRY});
env(tx);
env.close();
}
});
@@ -3954,6 +3979,28 @@ class Vault_test : public beast::unit_test::suite
testCase(18, [&, this](Env& env, Data d) {
testcase("Scale withdraw overflow");
{
auto tx = d.vault.deposit(
{.depositor = d.depositor,
.id = d.keylet.key,
.amount = d.asset(5)});
env(tx, ter{tecPRECISION_LOSS});
env.close();
}
{
auto tx = d.vault.withdraw(
{.depositor = d.depositor,
.id = d.keylet.key,
.amount = STAmount(d.asset, Number(10, 0))});
env(tx, ter{tecPRECISION_LOSS});
env.close();
}
});
testCase(14, [&, this](Env& env, Data d) {
testcase("MPT scale withdraw overflow");
{
auto tx = d.vault.deposit(
{.depositor = d.depositor,
@@ -4172,6 +4219,29 @@ class Vault_test : public beast::unit_test::suite
testCase(18, [&, this](Env& env, Data d) {
testcase("Scale clawback overflow");
{
auto tx = d.vault.deposit(
{.depositor = d.depositor,
.id = d.keylet.key,
.amount = d.asset(5)});
env(tx, ter(tecPRECISION_LOSS));
env.close();
}
{
auto tx = d.vault.clawback(
{.issuer = d.issuer,
.id = d.keylet.key,
.holder = d.depositor,
.amount = STAmount(d.asset, Number(10, 0))});
env(tx, ter{tecPRECISION_LOSS});
env.close();
}
});
testCase(14, [&, this](Env& env, Data d) {
testcase("MPT Scale clawback overflow");
{
auto tx = d.vault.deposit(
{.depositor = d.depositor,
@@ -4473,7 +4543,8 @@ class Vault_test : public beast::unit_test::suite
BEAST_EXPECT(checkString(vault, sfAssetsAvailable, "50"));
BEAST_EXPECT(checkString(vault, sfAssetsMaximum, "1000"));
BEAST_EXPECT(checkString(vault, sfAssetsTotal, "50"));
BEAST_EXPECT(checkString(vault, sfLossUnrealized, "0"));
// Since this field is default, it is not returned.
BEAST_EXPECT(!vault.isMember(sfLossUnrealized.getJsonName()));
auto const strShareID = strHex(sle->at(sfShareMPTID));
BEAST_EXPECT(checkString(vault, sfShareMPTID, strShareID));

View File

@@ -2,6 +2,7 @@
#include <xrpl/beast/unit_test.h>
#include <xrpl/protocol/IOUAmount.h>
#include <xrpl/protocol/STAmount.h>
#include <xrpl/protocol/SystemParameters.h>
#include <sstream>
#include <tuple>
@@ -834,6 +835,172 @@ public:
}
}
void
testInteger()
{
testcase("Integer enforcement");
using namespace std::string_literals;
{
Number a{100};
BEAST_EXPECT(a.integerEnforcement() == Number::none);
BEAST_EXPECT(a.valid());
a = Number{1, 30};
BEAST_EXPECT(a.valid());
a = -100;
BEAST_EXPECT(a.valid());
}
{
Number a{100, Number::weak};
BEAST_EXPECT(a.integerEnforcement() == Number::weak);
BEAST_EXPECT(a.valid());
a = Number{1, 30, Number::none};
BEAST_EXPECT(!a.valid());
a = -100;
BEAST_EXPECT(a.integerEnforcement() == Number::weak);
BEAST_EXPECT(a.valid());
a = Number{5, Number::strong};
BEAST_EXPECT(a.integerEnforcement() == Number::strong);
BEAST_EXPECT(a.valid());
}
{
Number a{100, Number::strong};
BEAST_EXPECT(a.integerEnforcement() == Number::strong);
BEAST_EXPECT(a.valid());
try
{
a = Number{1, 30};
BEAST_EXPECT(false);
}
catch (std::overflow_error const& e)
{
BEAST_EXPECT(e.what() == "Number::operator= integer overflow"s);
// The throw is done _after_ the number is updated.
BEAST_EXPECT((a == Number{1, 30}));
}
BEAST_EXPECT(!a.valid());
a = -100;
BEAST_EXPECT(a.integerEnforcement() == Number::strong);
BEAST_EXPECT(a.valid());
}
{
Number a{INITIAL_XRP.drops(), Number::weak};
BEAST_EXPECT(!a.valid());
a = -a;
BEAST_EXPECT(!a.valid());
try
{
a.setIntegerEnforcement(Number::strong);
BEAST_EXPECT(false);
}
catch (std::overflow_error const& e)
{
BEAST_EXPECT(
e.what() ==
"Number::setIntegerEnforcement integer overflow"s);
// The throw is internal to the operator before the result is
// assigned to the Number
BEAST_EXPECT(a == -INITIAL_XRP);
BEAST_EXPECT(!a.valid());
}
try
{
++a;
BEAST_EXPECT(false);
}
catch (std::overflow_error const& e)
{
BEAST_EXPECT(e.what() == "Number::addition integer overflow"s);
// The throw is internal to the operator before the result is
// assigned to the Number
BEAST_EXPECT(a == -INITIAL_XRP);
BEAST_EXPECT(!a.valid());
}
a = Number::maxIntValue;
try
{
++a;
BEAST_EXPECT(false);
}
catch (std::overflow_error const& e)
{
BEAST_EXPECT(e.what() == "Number::addition integer overflow"s);
// This time, the throw is done _after_ the number is updated.
BEAST_EXPECT(a == Number::maxIntValue + 1);
BEAST_EXPECT(!a.valid());
}
a = -Number::maxIntValue;
try
{
--a;
BEAST_EXPECT(false);
}
catch (std::overflow_error const& e)
{
BEAST_EXPECT(e.what() == "Number::addition integer overflow"s);
// This time, the throw is done _after_ the number is updated.
BEAST_EXPECT(a == -Number::maxIntValue - 1);
BEAST_EXPECT(!a.valid());
}
a = Number(1, 10);
try
{
a *= Number(1, 10);
BEAST_EXPECT(false);
}
catch (std::overflow_error const& e)
{
BEAST_EXPECT(
e.what() == "Number::multiplication integer overflow"s);
// The throw is done _after_ the number is updated.
BEAST_EXPECT((a == Number{1, 20}));
BEAST_EXPECT(!a.valid());
}
try
{
a = Number::maxIntValue * 2;
BEAST_EXPECT(false);
}
catch (std::overflow_error const& e)
{
BEAST_EXPECT(e.what() == "Number::operator= integer overflow"s);
// The throw is done _after_ the number is updated.
BEAST_EXPECT((a == Number::maxIntValue * 2));
BEAST_EXPECT(!a.valid());
}
try
{
a = Number(3, 15, Number::strong);
BEAST_EXPECT(false);
}
catch (std::overflow_error const& e)
{
BEAST_EXPECT(e.what() == "Number::Number integer overflow"s);
// The Number doesn't get updated because the ctor throws
BEAST_EXPECT((a == Number::maxIntValue * 2));
BEAST_EXPECT(!a.valid());
}
a = Number(1, 10);
try
{
a /= Number(1, -10);
BEAST_EXPECT(false);
}
catch (std::overflow_error const& e)
{
BEAST_EXPECT(e.what() == "Number::division integer overflow"s);
// The throw is done _after_ the number is updated.
BEAST_EXPECT((a == Number{1, 20}));
BEAST_EXPECT(!a.valid());
}
a /= Number(1, 15);
BEAST_EXPECT((a == Number{1, 5}));
BEAST_EXPECT(a.valid());
}
}
void
run() override
{
@@ -856,6 +1023,7 @@ public:
test_toSTAmount();
test_truncate();
testRounding();
testInteger();
}
};

View File

@@ -121,7 +121,8 @@ class Feature_test : public beast::unit_test::suite
// Test a random sampling of the variables. If any of these get retired
// or removed, swap out for any other feature.
BEAST_EXPECT(
featureToName(fixTrustLinesToSelf) == "fixTrustLinesToSelf");
featureToName(fixRemoveNFTokenAutoTrustLine) ==
"fixRemoveNFTokenAutoTrustLine");
BEAST_EXPECT(featureToName(featureFlow) == "Flow");
BEAST_EXPECT(featureToName(featureNegativeUNL) == "NegativeUNL");
BEAST_EXPECT(

View File

@@ -106,7 +106,7 @@ OrderBookDB::update(std::shared_ptr<ReadView const> const& ledger)
book.domain = (*sle)[~sfDomainID];
if (book.domain)
domainBooks_[{book.in, *book.domain}].insert(book.out);
domainBooks[{book.in, *book.domain}].insert(book.out);
else
allBooks[book.in].insert(book.out);

View File

@@ -151,88 +151,6 @@ Change::preCompute()
account_ == beast::zero, "ripple::Change::preCompute : zero account");
}
void
Change::activateTrustLinesToSelfFix()
{
JLOG(j_.warn()) << "fixTrustLinesToSelf amendment activation code starting";
auto removeTrustLineToSelf = [this](Sandbox& sb, uint256 id) {
auto tl = sb.peek(keylet::child(id));
if (tl == nullptr)
{
JLOG(j_.warn()) << id << ": Unable to locate trustline";
return true;
}
if (tl->getType() != ltRIPPLE_STATE)
{
JLOG(j_.warn()) << id << ": Unexpected type "
<< static_cast<std::uint16_t>(tl->getType());
return true;
}
auto const& lo = tl->getFieldAmount(sfLowLimit);
auto const& hi = tl->getFieldAmount(sfHighLimit);
if (lo != hi)
{
JLOG(j_.warn()) << id << ": Trustline doesn't meet requirements";
return true;
}
if (auto const page = tl->getFieldU64(sfLowNode); !sb.dirRemove(
keylet::ownerDir(lo.getIssuer()), page, tl->key(), false))
{
JLOG(j_.error()) << id << ": failed to remove low entry from "
<< toBase58(lo.getIssuer()) << ":" << page
<< " owner directory";
return false;
}
if (auto const page = tl->getFieldU64(sfHighNode); !sb.dirRemove(
keylet::ownerDir(hi.getIssuer()), page, tl->key(), false))
{
JLOG(j_.error()) << id << ": failed to remove high entry from "
<< toBase58(hi.getIssuer()) << ":" << page
<< " owner directory";
return false;
}
if (tl->getFlags() & lsfLowReserve)
adjustOwnerCount(
sb, sb.peek(keylet::account(lo.getIssuer())), -1, j_);
if (tl->getFlags() & lsfHighReserve)
adjustOwnerCount(
sb, sb.peek(keylet::account(hi.getIssuer())), -1, j_);
sb.erase(tl);
JLOG(j_.warn()) << "Successfully deleted trustline " << id;
return true;
};
using namespace std::literals;
Sandbox sb(&view());
if (removeTrustLineToSelf(
sb,
uint256{
"2F8F21EFCAFD7ACFB07D5BB04F0D2E18587820C7611305BB674A64EAB0FA71E1"sv}) &&
removeTrustLineToSelf(
sb,
uint256{
"326035D5C0560A9DA8636545DD5A1B0DFCFF63E68D491B5522B767BB00564B1A"sv}))
{
JLOG(j_.warn()) << "fixTrustLinesToSelf amendment activation code "
"executed successfully";
sb.apply(ctx_.rawView());
}
}
TER
Change::applyAmendment()
{
@@ -309,9 +227,6 @@ Change::applyAmendment()
amendments.push_back(amendment);
amendmentObject->setFieldV256(sfAmendments, amendments);
if (amendment == fixTrustLinesToSelf)
activateTrustLinesToSelfFix();
ctx_.app.getAmendmentTable().enable(amendment);
if (!ctx_.app.getAmendmentTable().isSupported(amendment))

View File

@@ -29,9 +29,6 @@ public:
preclaim(PreclaimContext const& ctx);
private:
void
activateTrustLinesToSelfFix();
TER
applyAmendment();

View File

@@ -195,29 +195,8 @@ SetTrust::preclaim(PreclaimContext const& ctx)
auto const currency = saLimitAmount.getCurrency();
auto const uDstAccountID = saLimitAmount.getIssuer();
if (ctx.view.rules().enabled(fixTrustLinesToSelf))
{
if (id == uDstAccountID)
return temDST_IS_SRC;
}
else
{
if (id == uDstAccountID)
{
// Prevent trustline to self from being created,
// unless one has somehow already been created
// (in which case doApply will clean it up).
auto const sleDelete =
ctx.view.read(keylet::line(id, uDstAccountID, currency));
if (!sleDelete)
{
JLOG(ctx.j.trace())
<< "Malformed transaction: Can not extend credit to self.";
return temDST_IS_SRC;
}
}
}
// This might be nullptr
auto const sleDst = ctx.view.read(keylet::account(uDstAccountID));
@@ -405,21 +384,6 @@ SetTrust::doApply()
auto viewJ = ctx_.app.journal("View");
// Trust lines to self are impossible but because of the old bug there
// are two on 19-02-2022. This code was here to allow those trust lines
// to be deleted. The fixTrustLinesToSelf fix amendment will remove them
// when it enables so this code will no longer be needed.
if (!view().rules().enabled(fixTrustLinesToSelf) &&
account_ == uDstAccountID)
{
return trustDelete(
view(),
view().peek(keylet::line(account_, uDstAccountID, currency)),
account_,
uDstAccountID,
viewJ);
}
SLE::pointer sleDst = view().peek(keylet::account(uDstAccountID));
if (!sleDst)

View File

@@ -71,9 +71,13 @@ VaultClawback::preclaim(PreclaimContext const& ctx)
}
Asset const vaultAsset = vault->at(sfAsset);
if (auto const amount = ctx.tx[~sfAmount];
amount && vaultAsset != amount->asset())
if (auto const amount = ctx.tx[~sfAmount])
{
if (vaultAsset != amount->asset())
return tecWRONG_ASSET;
else if (!amount->validNumber())
return tecPRECISION_LOSS;
}
if (vaultAsset.native())
{
@@ -157,6 +161,8 @@ VaultClawback::doApply()
MPTIssue const share{mptIssuanceID};
STAmount sharesDestroyed = {share};
STAmount assetsRecovered;
assetsRecovered.setIntegerEnforcement(Number::weak);
sharesDestroyed.setIntegerEnforcement(Number::weak);
try
{
if (amount == beast::zero)
@@ -169,6 +175,9 @@ VaultClawback::doApply()
AuthHandling::ahIGNORE_AUTH,
j_);
if (!sharesDestroyed.validNumber())
return tecPRECISION_LOSS;
auto const maybeAssets =
sharesToAssetsWithdraw(vault, sleIssuance, sharesDestroyed);
if (!maybeAssets)
@@ -184,6 +193,8 @@ VaultClawback::doApply()
if (!maybeShares)
return tecINTERNAL; // LCOV_EXCL_LINE
sharesDestroyed = *maybeShares;
if (!sharesDestroyed.validNumber())
return tecPRECISION_LOSS;
}
auto const maybeAssets =
@@ -192,6 +203,8 @@ VaultClawback::doApply()
return tecINTERNAL; // LCOV_EXCL_LINE
assetsRecovered = *maybeAssets;
}
if (!assetsRecovered.validNumber())
return tecPRECISION_LOSS;
// Clamp to maximum.
if (assetsRecovered > *assetsAvailable)

View File

@@ -42,6 +42,9 @@ VaultDeposit::preclaim(PreclaimContext const& ctx)
if (assets.asset() != vaultAsset)
return tecWRONG_ASSET;
if (!assets.validNumber())
return tecPRECISION_LOSS;
if (vaultAsset.native())
; // No special checks for XRP
else if (vaultAsset.holds<MPTIssue>())
@@ -217,6 +220,7 @@ VaultDeposit::doApply()
}
STAmount sharesCreated = {vault->at(sfShareMPTID)}, assetsDeposited;
sharesCreated.setIntegerEnforcement(Number::weak);
try
{
// Compute exchange before transferring any amounts.
@@ -227,14 +231,14 @@ VaultDeposit::doApply()
return tecINTERNAL; // LCOV_EXCL_LINE
sharesCreated = *maybeShares;
}
if (sharesCreated == beast::zero)
if (sharesCreated == beast::zero || !sharesCreated.validNumber())
return tecPRECISION_LOSS;
auto const maybeAssets =
sharesToAssetsDeposit(vault, sleIssuance, sharesCreated);
if (!maybeAssets)
return tecINTERNAL; // LCOV_EXCL_LINE
else if (*maybeAssets > amount)
else if (*maybeAssets > amount || !maybeAssets->validNumber())
{
// LCOV_EXCL_START
JLOG(j_.error()) << "VaultDeposit: would take more than offered.";
@@ -260,13 +264,22 @@ VaultDeposit::doApply()
sharesCreated.asset() != assetsDeposited.asset(),
"ripple::VaultDeposit::doApply : assets are not shares");
vault->at(sfAssetsTotal) += assetsDeposited;
vault->at(sfAssetsAvailable) += assetsDeposited;
auto assetsTotalProxy = vault->at(sfAssetsTotal);
auto assetsAvailableProxy = vault->at(sfAssetsAvailable);
if (vault->at(sfAsset).value().integral())
{
assetsTotalProxy.value().setIntegerEnforcement(Number::weak);
assetsAvailableProxy.value().setIntegerEnforcement(Number::weak);
}
assetsTotalProxy += assetsDeposited;
assetsAvailableProxy += assetsDeposited;
if (!assetsTotalProxy->valid() || !assetsAvailableProxy->valid())
return tecLIMIT_EXCEEDED;
view().update(vault);
// A deposit must not push the vault over its limit.
auto const maximum = *vault->at(sfAssetsMaximum);
if (maximum != 0 && *vault->at(sfAssetsTotal) > maximum)
if (maximum != 0 && *assetsTotalProxy > maximum)
return tecLIMIT_EXCEEDED;
// Transfer assets from depositor to vault.

View File

@@ -47,6 +47,9 @@ VaultWithdraw::preclaim(PreclaimContext const& ctx)
if (assets.asset() != vaultAsset && assets.asset() != vaultShare)
return tecWRONG_ASSET;
if (!assets.validNumber())
return tecPRECISION_LOSS;
if (vaultAsset.native())
; // No special checks for XRP
else if (vaultAsset.holds<MPTIssue>())
@@ -139,6 +142,8 @@ VaultWithdraw::doApply()
MPTIssue const share{mptIssuanceID};
STAmount sharesRedeemed = {share};
STAmount assetsWithdrawn;
assetsWithdrawn.setIntegerEnforcement(Number::weak);
sharesRedeemed.setIntegerEnforcement(Number::weak);
try
{
if (amount.asset() == vaultAsset)
@@ -152,13 +157,15 @@ VaultWithdraw::doApply()
sharesRedeemed = *maybeShares;
}
if (sharesRedeemed == beast::zero)
if (sharesRedeemed == beast::zero || !sharesRedeemed.validNumber())
return tecPRECISION_LOSS;
auto const maybeAssets =
sharesToAssetsWithdraw(vault, sleIssuance, sharesRedeemed);
if (!maybeAssets)
return tecINTERNAL; // LCOV_EXCL_LINE
assetsWithdrawn = *maybeAssets;
if (!assetsWithdrawn.validNumber())
return tecPRECISION_LOSS;
}
else if (amount.asset() == share)
{
@@ -169,6 +176,8 @@ VaultWithdraw::doApply()
if (!maybeAssets)
return tecINTERNAL; // LCOV_EXCL_LINE
assetsWithdrawn = *maybeAssets;
if (!assetsWithdrawn.validNumber())
return tecPRECISION_LOSS;
}
else
return tefINTERNAL; // LCOV_EXCL_LINE