Compare commits

..

2 Commits

Author SHA1 Message Date
Ed Hennis
8dbb933306 Ugh. This is all wrong. 2025-11-16 17:19:08 -05:00
Ed Hennis
248d267f21 Take baseline changes from original implementation
- Won't build
2025-11-16 13:10:01 -05:00
18 changed files with 402 additions and 572 deletions

View File

@@ -13,6 +13,15 @@ class Number;
std::string
to_string(Number const& amount);
template <typename T>
constexpr bool
isPowerOfTen(T value)
{
while (value >= 10 && value % 10 == 0)
value /= 10;
return value == 1;
}
class Number
{
using rep = std::int64_t;
@@ -21,8 +30,13 @@ class Number
public:
// The range for the mantissa when normalized
constexpr static std::int64_t minMantissa = 1'000'000'000'000'000LL;
constexpr static std::int64_t maxMantissa = 9'999'999'999'999'999LL;
constexpr static rep minMantissa = 1'000'000'000'000'000LL;
static_assert(isPowerOfTen(minMantissa));
constexpr static rep maxMantissa = minMantissa * 10 - 1;
static_assert(maxMantissa == 9'999'999'999'999'999LL);
constexpr static rep maxIntValue = maxMantissa / 100;
static_assert(maxIntValue == 99'999'999'999'999LL);
// The range for the exponent when normalized
constexpr static int minExponent = -32768;
@@ -404,6 +418,12 @@ public:
operator=(NumberRoundModeGuard const&) = delete;
};
class NumberOverflow : public std::overflow_error
{
public:
using overflow_error::overflow_error;
};
} // namespace ripple
#endif // XRPL_BASICS_NUMBER_H_INCLUDED

View File

@@ -84,6 +84,19 @@ public:
return holds<Issue>() && get<Issue>().native();
}
bool
integral() const
{
return std::visit(
[]<ValidIssueType TIss>(TIss const& issue) {
if constexpr (std::is_same_v<TIss, Issue>)
return issue.native();
if constexpr (std::is_same_v<TIss, MPTIssue>)
return true;
},
issue_);
}
friend constexpr bool
operator==(Asset const& lhs, Asset const& rhs);

View File

@@ -155,6 +155,9 @@ public:
int
exponent() const noexcept;
bool
integral() const noexcept;
bool
native() const noexcept;
@@ -435,6 +438,12 @@ STAmount::exponent() const noexcept
return mOffset;
}
inline bool
STAmount::integral() const noexcept
{
return mAsset.integral();
}
inline bool
STAmount::native() const noexcept
{
@@ -553,7 +562,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

@@ -24,6 +24,10 @@ class STNumber : public STBase, public CountedObject<STNumber>
{
private:
Number value_;
// isInteger_ is not serialized or transmitted in any way. It is used only
// for internal validation of integer types. It is a one-way switch. Once
// it's on, it stays on.
bool isInteger_ = false;
public:
using value_type = Number;
@@ -51,6 +55,35 @@ public:
return *this;
}
// Tell the STNumber whether the value it is holding represents an integer,
// and must fit within the allowable range.
void
usesAsset(Asset const& a);
// The asset isn't stored, only whether it's an integral type. Get that flag
// back out.
bool
isIntegral() const;
// Returns whether the value fits within Number::maxIntValue. Transactors
// should check this whenever interacting with an STNumber.
bool
safeNumber() const;
/// Combines usesAsset(a) and safeNumber()
static std::int64_t
safeNumberLimit();
bool
safeNumber(Asset const& a);
// Returns whether the value fits within Number::maxMantissa. Transactors
// may check this, too, but are not required to. It will be checked when
// serializing, and will throw if false, thus preventing the value from
// being silently truncated.
bool
validNumber() const;
/// Combines usesAsset(a) and validAsset()
bool
validNumber(Asset const& a);
static std::int64_t
validNumberLimit();
bool
isEquivalent(STBase const& t) const override;
bool

View File

@@ -482,9 +482,15 @@ public:
value_type
operator*() const;
/// Do not use operator->() unless the field is required, or you've checked
/// that it's set.
T const*
operator->() const;
/// Access the underlying STObject without necessarily dereferencing it
T*
stValue() const;
protected:
STObject* st_;
SOEStyle style_;
@@ -718,11 +724,21 @@ STObject::Proxy<T>::operator*() const -> value_type
return this->value();
}
/// Do not use operator->() unless the field is required, or you've checked that
/// it's set.
template <class T>
T const*
STObject::Proxy<T>::operator->() const
{
return this->find();
return stValue();
}
/// Access the underlying STObject without necessarily dereferencing it
template <class T>
T*
STObject::Proxy<T>::stValue() const
{
return dynamic_cast<T*>(st_->getPField(*f_));
}
template <class T>

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

@@ -479,10 +479,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

@@ -12,6 +12,7 @@
#include <xrpl/protocol/SField.h>
#include <xrpl/protocol/STBase.h>
#include <xrpl/protocol/STLedgerEntry.h>
#include <xrpl/protocol/STNumber.h>
#include <xrpl/protocol/STObject.h>
#include <xrpl/protocol/Serializer.h>
#include <xrpl/protocol/jss.h>
@@ -67,6 +68,32 @@ STLedgerEntry::setSLEType()
type_ = format->getType();
applyTemplate(format->getSOTemplate()); // May throw
// Per object type overrides
// Currently only covers STNumber fields to link them to appropriate assets
switch (type_)
{
case ltVAULT: {
auto const asset = at(sfAsset);
for (auto const& field :
{~sfAssetsAvailable,
~sfAssetsTotal,
~sfAssetsMaximum,
~sfLossUnrealized})
{
if (auto proxy = at(field))
if (auto stNumber = proxy.stValue())
stNumber->usesAsset(asset);
}
}
/*
// TODO: If possible, set up the loan-related STNumber fields, too.
// May not be possible because we don't have a view available.
case ltLOAN_BROKER:
case ltLOAN:
*/
}
}
std::string

View File

@@ -50,6 +50,8 @@ STNumber::add(Serializer& s) const
XRPL_ASSERT(
getFName().fieldType == getSType(),
"ripple::STNumber::add : field type match");
if (!validNumber())
throw NumberOverflow(to_string(value_));
s.add64(value_.mantissa());
s.add32(value_.exponent());
}
@@ -66,6 +68,87 @@ STNumber::setValue(Number const& v)
value_ = v;
}
// Tell the STNumber whether the value it is holding represents an integer, and
// must fit within the allowable range.
void
STNumber::usesAsset(Asset const& a)
{
XRPL_ASSERT_PARTS(
!isInteger_ || a.integral(),
"ripple::STNumber::value",
"asset check only gets stricter");
// isInteger_ is a one-way switch. Once it's on, it stays on.
if (isInteger_)
return;
isInteger_ = a.integral();
}
bool
STNumber::isIntegral() const
{
return isInteger_;
}
// Returns whether the value fits within Number::maxIntValue. Transactors
// should check this whenever interacting with an STNumber.
bool
STNumber::safeNumber() const
{
if (!isInteger_)
return true;
static Number const max = safeNumberLimit();
static Number const maxNeg = -max;
// Avoid making a copy
if (value_ < 0)
return value_ >= maxNeg;
return value_ <= max;
}
bool
STNumber::safeNumber(Asset const& a)
{
usesAsset(a);
return safeNumber();
}
std::int64_t
STNumber::safeNumberLimit()
{
return Number::maxIntValue;
}
// Returns whether the value fits within Number::maxMantissa. Transactors
// may check this, too, but are not required to. It will be checked when
// serializing, and will throw if false, thus preventing the value from
// being silently truncated.
bool
STNumber::validNumber() const
{
if (!isInteger_)
return true;
static Number const max = validNumberLimit();
static Number const maxNeg = -max;
// Avoid making a copy
if (value_ < 0)
return value_ >= maxNeg;
return value_ <= max;
}
bool
STNumber::validNumber(Asset const& a)
{
usesAsset(a);
return validNumber();
}
std::int64_t
STNumber::validNumberLimit()
{
return Number::maxMantissa;
}
STBase*
STNumber::copy(std::size_t n, void* buf) const
{

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

@@ -4525,7 +4525,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

@@ -5,8 +5,6 @@
#include <test/jtx/multisign.h>
#include <test/jtx/xchain_bridge.h>
#include <xrpld/app/tx/apply.h>
#include <xrpl/beast/unit_test.h>
#include <xrpl/json/json_value.h>
#include <xrpl/protocol/AccountID.h>
@@ -2010,370 +2008,6 @@ class LedgerEntry_test : public beast::unit_test::suite
}
}
/// Test the ledger entry types that don't take parameters
void
testLedgerEntryFixed()
{
using namespace test::jtx;
Account const alice{"alice"};
Account const bob{"bob"};
Env env{*this, envconfig([](auto cfg) {
cfg->START_UP = Config::FRESH;
return cfg;
})};
env.close();
/** Verifies that the RPC result has the expected data
*
* @param good: Indicates that the request should have succeeded
* and returned a ledger object of `expectedType` type.
* @param jv: The RPC result Json value
* @param expectedType: The type that the ledger object should
* have if "good".
* @param expectedError: Optional. The expected error if not
* good. Defaults to "entryNotFound".
*/
auto checkResult =
[&](bool good,
Json::Value const& jv,
Json::StaticString const& expectedType,
std::optional<std::string> const& expectedError = {}) {
if (good)
{
BEAST_EXPECTS(
jv.isObject() && jv.isMember(jss::result) &&
!jv[jss::result].isMember(jss::error) &&
jv[jss::result].isMember(jss::node) &&
jv[jss::result][jss::node].isMember(
sfLedgerEntryType.jsonName) &&
jv[jss::result][jss::node]
[sfLedgerEntryType.jsonName] == expectedType,
to_string(jv));
}
else
{
BEAST_EXPECTS(
jv.isObject() && jv.isMember(jss::result) &&
jv[jss::result].isMember(jss::error) &&
!jv[jss::result].isMember(jss::node) &&
jv[jss::result][jss::error] ==
expectedError.value_or("entryNotFound"),
to_string(jv));
}
};
/** Runs a series of tests for a given fixed-position ledger
* entry.
*
* @param field: The Json request field to use.
* @param expectedType: The type that the ledger object should
* have if "good".
* @param expectedKey: The keylet of the fixed object.
* @param good: Indicates whether the object is expected to
* exist.
*/
auto test = [&](Json::StaticString const& field,
Json::StaticString const& expectedType,
Keylet const& expectedKey,
bool good) {
testcase << "ledger_entry " << expectedType.c_str()
<< (good ? "" : " not") << " found";
auto const hexKey = strHex(expectedKey.key);
// Test bad values
// "field":null
Json::Value params;
params[jss::ledger_index] = jss::validated;
params[field] = Json::nullValue;
auto jv = env.rpc("json", "ledger_entry", to_string(params));
checkResult(false, jv, expectedType, "malformedRequest");
BEAST_EXPECT(!jv[jss::result].isMember(jss::index));
// "field":"string"
params.clear();
params[jss::ledger_index] = jss::validated;
params[field] = "arbitrary string";
jv = env.rpc("json", "ledger_entry", to_string(params));
checkResult(false, jv, expectedType, "malformedRequest");
BEAST_EXPECT(!jv[jss::result].isMember(jss::index));
// "field":false
params.clear();
params[jss::ledger_index] = jss::validated;
params[field] = false;
jv = env.rpc("json", "ledger_entry", to_string(params));
checkResult(false, jv, expectedType, "invalidParams");
BEAST_EXPECT(!jv[jss::result].isMember(jss::index));
{
// "field":[incorrect index hash]
auto const badKey = strHex(expectedKey.key + uint256{1});
params.clear();
params[jss::ledger_index] = jss::validated;
params[field] = badKey;
jv = env.rpc("json", "ledger_entry", to_string(params));
checkResult(false, jv, expectedType, "entryNotFound");
BEAST_EXPECTS(
jv[jss::result][jss::index] == badKey, to_string(jv));
}
// "index":"field" using API 2
params.clear();
params[jss::ledger_index] = jss::validated;
params[jss::index] = field;
params[jss::api_version] = 2;
jv = env.rpc("json", "ledger_entry", to_string(params));
checkResult(false, jv, expectedType, "malformedRequest");
BEAST_EXPECT(!jv[jss::result].isMember(jss::index));
// Test good values
// Use the "field":true notation
params.clear();
params[jss::ledger_index] = jss::validated;
params[field] = true;
jv = env.rpc("json", "ledger_entry", to_string(params));
// Index will always be returned for valid parameters.
std::string const pdIdx = jv[jss::result][jss::index].asString();
BEAST_EXPECTS(hexKey == pdIdx, to_string(jv));
checkResult(good, jv, expectedType);
// "field":"[index hash]"
params.clear();
params[jss::ledger_index] = jss::validated;
params[field] = hexKey;
jv = env.rpc("json", "ledger_entry", to_string(params));
checkResult(good, jv, expectedType);
BEAST_EXPECT(jv[jss::result][jss::index].asString() == hexKey);
// Use the "index":"field" notation with API 3
params.clear();
params[jss::ledger_index] = jss::validated;
params[jss::index] = field;
params[jss::api_version] = 3;
jv = env.rpc("json", "ledger_entry", to_string(params));
// Index is correct either way
BEAST_EXPECT(jv[jss::result][jss::index].asString() == hexKey);
checkResult(good, jv, expectedType);
// Use the "index":"[index hash]" notation
params.clear();
params[jss::ledger_index] = jss::validated;
params[jss::index] = pdIdx;
jv = env.rpc("json", "ledger_entry", to_string(params));
// Index is correct either way
BEAST_EXPECT(jv[jss::result][jss::index].asString() == hexKey);
checkResult(good, jv, expectedType);
};
test(jss::amendments, jss::Amendments, keylet::amendments(), true);
test(jss::fee, jss::FeeSettings, keylet::fees(), true);
// There won't be an nunl
test(jss::nunl, jss::NegativeUNL, keylet::negativeUNL(), false);
// Can only get the short skip list this way
test(jss::hashes, jss::LedgerHashes, keylet::skip(), true);
}
void
testLedgerEntryHashes()
{
using namespace test::jtx;
Account const alice{"alice"};
Account const bob{"bob"};
Env env{*this, envconfig([](auto cfg) {
cfg->START_UP = Config::FRESH;
return cfg;
})};
env.close();
/** Verifies that the RPC result has the expected data
*
* @param good: Indicates that the request should have succeeded
* and returned a ledger object of `expectedType` type.
* @param jv: The RPC result Json value
* @param expectedCount: The number of Hashes expected in the
* object if "good".
* @param expectedError: Optional. The expected error if not
* good. Defaults to "entryNotFound".
*/
auto checkResult =
[&](bool good,
Json::Value const& jv,
int expectedCount,
std::optional<std::string> const& expectedError = {}) {
if (good)
{
BEAST_EXPECTS(
jv.isObject() && jv.isMember(jss::result) &&
!jv[jss::result].isMember(jss::error) &&
jv[jss::result].isMember(jss::node) &&
jv[jss::result][jss::node].isMember(
sfLedgerEntryType.jsonName) &&
jv[jss::result][jss::node]
[sfLedgerEntryType.jsonName] == jss::LedgerHashes,
to_string(jv));
BEAST_EXPECTS(
jv[jss::result].isMember(jss::node) &&
jv[jss::result][jss::node].isMember("Hashes") &&
jv[jss::result][jss::node]["Hashes"].size() ==
expectedCount,
to_string(jv[jss::result][jss::node]["Hashes"].size()));
}
else
{
BEAST_EXPECTS(
jv.isObject() && jv.isMember(jss::result) &&
jv[jss::result].isMember(jss::error) &&
!jv[jss::result].isMember(jss::node) &&
jv[jss::result][jss::error] ==
expectedError.value_or("entryNotFound"),
to_string(jv));
}
};
/** Runs a series of tests for a given ledger index.
*
* @param ledger: The ledger index value of the "hashes" request
* parameter. May not necessarily be a number.
* @param expectedKey: The expected keylet of the object.
* @param good: Indicates whether the object is expected to
* exist.
* @param expectedCount: The number of Hashes expected in the
* object if "good".
*/
auto test = [&](Json::Value ledger,
Keylet const& expectedKey,
bool good,
int expectedCount = 0) {
testcase << "ledger_entry LedgerHashes: seq: "
<< env.current()->info().seq
<< " \"hashes\":" << to_string(ledger)
<< (good ? "" : " not") << " found";
auto const hexKey = strHex(expectedKey.key);
// Test bad values
// "hashes":null
Json::Value params;
params[jss::ledger_index] = jss::validated;
params[jss::hashes] = Json::nullValue;
auto jv = env.rpc("json", "ledger_entry", to_string(params));
checkResult(false, jv, 0, "malformedRequest");
BEAST_EXPECT(!jv[jss::result].isMember(jss::index));
// "hashes":"non-uint string"
params.clear();
params[jss::ledger_index] = jss::validated;
params[jss::hashes] = "arbitrary string";
jv = env.rpc("json", "ledger_entry", to_string(params));
checkResult(false, jv, 0, "malformedRequest");
BEAST_EXPECT(!jv[jss::result].isMember(jss::index));
// "hashes":"uint string" is invalid, too
params.clear();
params[jss::ledger_index] = jss::validated;
params[jss::hashes] = "10";
jv = env.rpc("json", "ledger_entry", to_string(params));
checkResult(false, jv, 0, "malformedRequest");
BEAST_EXPECT(!jv[jss::result].isMember(jss::index));
// "hashes":false
params.clear();
params[jss::ledger_index] = jss::validated;
params[jss::hashes] = false;
jv = env.rpc("json", "ledger_entry", to_string(params));
checkResult(false, jv, 0, "invalidParams");
BEAST_EXPECT(!jv[jss::result].isMember(jss::index));
// "hashes":-1
params.clear();
params[jss::ledger_index] = jss::validated;
params[jss::hashes] = -1;
jv = env.rpc("json", "ledger_entry", to_string(params));
checkResult(false, jv, 0, "internal");
BEAST_EXPECT(!jv[jss::result].isMember(jss::index));
// "hashes":[incorrect index hash]
{
auto const badKey = strHex(expectedKey.key + uint256{1});
params.clear();
params[jss::ledger_index] = jss::validated;
params[jss::hashes] = badKey;
jv = env.rpc("json", "ledger_entry", to_string(params));
checkResult(false, jv, 0, "entryNotFound");
BEAST_EXPECT(jv[jss::result][jss::index] == badKey);
}
// Test good values
// Use the "hashes":ledger notation
params.clear();
params[jss::ledger_index] = jss::validated;
params[jss::hashes] = ledger;
jv = env.rpc("json", "ledger_entry", to_string(params));
checkResult(good, jv, expectedCount);
// Index will always be returned for valid parameters.
std::string const pdIdx = jv[jss::result][jss::index].asString();
BEAST_EXPECTS(hexKey == pdIdx, strHex(pdIdx));
// "hashes":"[index hash]"
params.clear();
params[jss::ledger_index] = jss::validated;
params[jss::hashes] = hexKey;
jv = env.rpc("json", "ledger_entry", to_string(params));
checkResult(good, jv, expectedCount);
// Index is correct either way
BEAST_EXPECTS(
hexKey == jv[jss::result][jss::index].asString(),
strHex(jv[jss::result][jss::index].asString()));
// Use the "index":"[index hash]" notation
params.clear();
params[jss::ledger_index] = jss::validated;
params[jss::index] = hexKey;
jv = env.rpc("json", "ledger_entry", to_string(params));
checkResult(good, jv, expectedCount);
// Index is correct either way
BEAST_EXPECTS(
hexKey == jv[jss::result][jss::index].asString(),
strHex(jv[jss::result][jss::index].asString()));
};
// short skip list
test(true, keylet::skip(), true, 2);
// long skip list at index 0
test(1, keylet::skip(1), false);
// long skip list at index 1
test(1 << 17, keylet::skip(1 << 17), false);
// Close more ledgers, but stop short of the flag ledger
for (auto i = env.current()->seq(); i <= 250; ++i)
env.close();
// short skip list
test(true, keylet::skip(), true, 249);
// long skip list at index 0
test(1, keylet::skip(1), false);
// long skip list at index 1
test(1 << 17, keylet::skip(1 << 17), false);
// Close a flag ledger so the first "long" skip list is created
for (auto i = env.current()->seq(); i <= 260; ++i)
env.close();
// short skip list
test(true, keylet::skip(), true, 256);
// long skip list at index 0
test(1, keylet::skip(1), true, 1);
// long skip list at index 1
test(1 << 17, keylet::skip(1 << 17), false);
}
void
testLedgerEntryCLI()
{
@@ -2423,8 +2057,6 @@ public:
testOracleLedgerEntry();
testLedgerEntryMPT();
testLedgerEntryPermissionedDomain();
testLedgerEntryFixed();
testLedgerEntryHashes();
testLedgerEntryCLI();
}
};

View File

@@ -2164,6 +2164,28 @@ ValidAMM::finalize(
//------------------------------------------------------------------------------
ValidVault::NumberInfo
ValidVault::NumberInfo::make(
SLE const& from,
SF_NUMBER const& field,
Asset const& asset)
{
bool valid = true;
// Poke around in the internals of STObject to get the STNumber object
if (auto const stNumber =
dynamic_cast<STNumber const*>(from.peekAtPField(field)))
valid = stNumber->isIntegral() == asset.integral() &&
stNumber->validNumber();
return {.n = from.at(field), .valid = valid};
}
ValidVault::NumberInfo::operator Number const&() const
{
return n;
}
ValidVault::Vault
ValidVault::Vault::make(SLE const& from)
{
@@ -2176,10 +2198,11 @@ ValidVault::Vault::make(SLE const& from)
self.asset = from.at(sfAsset);
self.pseudoId = from.getAccountID(sfAccount);
self.shareMPTID = from.getFieldH192(sfShareMPTID);
self.assetsTotal = from.at(sfAssetsTotal);
self.assetsAvailable = from.at(sfAssetsAvailable);
self.assetsMaximum = from.at(sfAssetsMaximum);
self.lossUnrealized = from.at(sfLossUnrealized);
self.assetsTotal = NumberInfo::make(from, sfAssetsTotal, self.asset);
self.assetsAvailable =
NumberInfo::make(from, sfAssetsAvailable, self.asset);
self.assetsMaximum = NumberInfo::make(from, sfAssetsMaximum, self.asset);
self.lossUnrealized = NumberInfo::make(from, sfLossUnrealized, self.asset);
return self;
}
@@ -2413,6 +2436,17 @@ ValidVault::finalize(
beforeVault_.empty() || beforeVault_[0].key == afterVault.key,
"ripple::ValidVault::finalize : single vault operation");
if (!afterVault.assetsTotal.valid || !afterVault.assetsAvailable.valid ||
!afterVault.assetsMaximum.valid || !afterVault.lossUnrealized.valid)
{
JLOG(j.fatal()) << "Invariant failed: vault overflowed maximum current "
"representable integer value";
XRPL_ASSERT(
enforce,
"ripple::ValidVault::finalize : vault integer limit invariant");
return !enforce; // That's all we can do here
}
auto const updatedShares = [&]() -> std::optional<Shares> {
// At this moment we only know that a vault is being updated and there
// might be some MPTokenIssuance objects which are also updated in the
@@ -2487,7 +2521,7 @@ ValidVault::finalize(
result = false;
}
if (afterVault.assetsAvailable > afterVault.assetsTotal)
if (afterVault.assetsAvailable.n > afterVault.assetsTotal)
{
JLOG(j.fatal()) << "Invariant failed: assets available must "
"not be greater than assets outstanding";
@@ -2528,7 +2562,7 @@ ValidVault::finalize(
}
if (!beforeVault_.empty() &&
afterVault.lossUnrealized != beforeVault_[0].lossUnrealized)
afterVault.lossUnrealized.n != beforeVault_[0].lossUnrealized)
{
JLOG(j.fatal()) << //
"Invariant failed: vault transaction must not change loss "
@@ -2698,7 +2732,7 @@ ValidVault::finalize(
result = false;
}
if (beforeVault.assetsTotal != afterVault.assetsTotal)
if (beforeVault.assetsTotal.n != afterVault.assetsTotal)
{
JLOG(j.fatal()) << //
"Invariant failed: set must not change assets "
@@ -2707,7 +2741,7 @@ ValidVault::finalize(
}
if (afterVault.assetsMaximum > zero &&
afterVault.assetsTotal > afterVault.assetsMaximum)
afterVault.assetsTotal.n > afterVault.assetsMaximum)
{
JLOG(j.fatal()) << //
"Invariant failed: set assets outstanding must not "
@@ -2715,7 +2749,7 @@ ValidVault::finalize(
result = false;
}
if (beforeVault.assetsAvailable != afterVault.assetsAvailable)
if (beforeVault.assetsAvailable.n != afterVault.assetsAvailable)
{
JLOG(j.fatal()) << //
"Invariant failed: set must not change assets "
@@ -2803,7 +2837,7 @@ ValidVault::finalize(
}
if (afterVault.assetsMaximum > zero &&
afterVault.assetsTotal > afterVault.assetsMaximum)
afterVault.assetsTotal.n > afterVault.assetsMaximum)
{
JLOG(j.fatal()) << //
"Invariant failed: deposit assets outstanding must not "

View File

@@ -5,6 +5,7 @@
#include <xrpl/basics/base_uint.h>
#include <xrpl/beast/utility/Journal.h>
#include <xrpl/protocol/MPTIssue.h>
#include <xrpl/protocol/SField.h>
#include <xrpl/protocol/STLedgerEntry.h>
#include <xrpl/protocol/STTx.h>
#include <xrpl/protocol/TER.h>
@@ -738,16 +739,38 @@ class ValidVault
{
Number static constexpr zero{};
struct Vault;
struct NumberInfo final
{
Number n;
bool valid;
// Make this Number wrapper as transparent as possible, except when
// checking validity. However, rather than fleshing out all the
// comparison operators, etc, a few places will still need to specify
// "n".
operator Number const&() const;
private:
friend class ValidVault::Vault;
NumberInfo static make(
SLE const& from,
SF_NUMBER const& field,
Asset const& asset);
};
struct Vault final
{
uint256 key = beast::zero;
Asset asset = {};
AccountID pseudoId = {};
uint192 shareMPTID = beast::zero;
Number assetsTotal = 0;
Number assetsAvailable = 0;
Number assetsMaximum = 0;
Number lossUnrealized = 0;
NumberInfo assetsTotal{0, true};
NumberInfo assetsAvailable{0, true};
NumberInfo assetsMaximum{0, true};
NumberInfo lossUnrealized{0, true};
Vault static make(SLE const&);
};

View File

@@ -193,7 +193,28 @@ VaultCreate::doApply()
vault->at(sfLossUnrealized) = Number(0);
// Leave default values for AssetTotal and AssetAvailable, both zero.
if (auto value = tx[~sfAssetsMaximum])
vault->at(sfAssetsMaximum) = *value;
{
auto assetsMaximumProxy = vault->at(~sfAssetsMaximum);
assetsMaximumProxy = *value;
if (auto const stNumber = assetsMaximumProxy.stValue();
stNumber && !stNumber->validNumber(asset))
{
JLOG(j_.warn()) << "VaultCreate: Invalid assets maximum value for "
"integral asset type: "
<< *value << " > " << STNumber::validNumberLimit();
return tecPRECISION_LOSS;
}
}
// TODO: Should integral types automatically set a limit to the
// Number::validNumberLimit() value? Or safeNumberLimit()?
/*
else if (asset.integral())
{
auto assetsMaximumProxy = vault->at(~sfAssetsMaximum);
assetsMaximumProxy = STNumber::validNumberLimit();
assetsMaximumProxy.stValue()->usesAsset(asset);
}
*/
vault->at(sfShareMPTID) = mptIssuanceID;
if (auto value = tx[~sfData])
vault->at(sfData) = *value;

View File

@@ -260,13 +260,43 @@ 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);
assetsTotalProxy += assetsDeposited;
assetsAvailableProxy += assetsDeposited;
view().update(vault);
auto const asset = *vault->at(sfAsset);
if (auto stNumber = assetsTotalProxy.stValue();
stNumber && !stNumber->safeNumber(asset))
{
JLOG(j_.warn()) << "VaultDeposit: Invalid assets total value for "
"integral asset type: "
<< *assetsTotalProxy << " > "
<< STNumber::safeNumberLimit();
return tecPRECISION_LOSS;
}
if (auto stNumber = assetsAvailableProxy.stValue();
stNumber && !stNumber->safeNumber(asset))
{
// LCOV_EXCL_START
// This should be impossible to reach because total should never be less
// than available, so if total is ok, available should be ok.
UNREACHABLE(
"ripple::VaultDeposit::doApply() : AssetsAvailable exceeds "
"AssetsTotal");
JLOG(j_.warn()) << "VaultDeposit: Invalid assets available value for "
"integral asset type: "
<< *assetsAvailableProxy << " > "
<< STNumber::safeNumberLimit();
return tecPRECISION_LOSS;
// LCOV_EXCL_STOP
}
// 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

@@ -143,7 +143,19 @@ VaultSet::doApply()
if (tx[sfAssetsMaximum] != 0 &&
tx[sfAssetsMaximum] < *vault->at(sfAssetsTotal))
return tecLIMIT_EXCEEDED;
vault->at(sfAssetsMaximum) = tx[sfAssetsMaximum];
auto assetsMaximumProxy = vault->at(~sfAssetsMaximum);
assetsMaximumProxy = tx[sfAssetsMaximum];
if (auto const stNumber = assetsMaximumProxy.stValue();
stNumber && !stNumber->validNumber(vault->at(sfAsset)))
{
// LCOV_EXCL_START
// This should be impossible, because invalid values would have been
// stopped by `VaultCreate`.
UNREACHABLE(
"ripple::VaultSet::doApply : invalid assets maximum value");
return tecLIMIT_EXCEEDED;
// LCOV_EXCL_STOP
}
}
if (auto const domainId = tx[~sfDomainID]; domainId)

View File

@@ -20,32 +20,6 @@
namespace ripple {
using FunctionType = std::function<Expected<uint256, Json::Value>(
Json::Value const&,
Json::StaticString const,
unsigned apiVersion)>;
static Expected<uint256, Json::Value>
parseFixed(
Keylet const& keylet,
Json::Value const& params,
Json::StaticString const& fieldName,
unsigned apiVersion);
// Helper function to return FunctionType for objects that have a fixed
// location. That is, they don't take parameters to compute the index.
// e.g. amendments, fees, negative UNL, etc.
static FunctionType
fixed(Keylet const& keylet)
{
return [&keylet](
Json::Value const& params,
Json::StaticString const fieldName,
unsigned apiVersion) -> Expected<uint256, Json::Value> {
return parseFixed(keylet, params, fieldName, apiVersion);
};
}
static Expected<uint256, Json::Value>
parseObjectID(
Json::Value const& params,
@@ -61,33 +35,13 @@ parseObjectID(
}
static Expected<uint256, Json::Value>
parseIndex(
Json::Value const& params,
Json::StaticString const fieldName,
unsigned apiVersion)
parseIndex(Json::Value const& params, Json::StaticString const fieldName)
{
if (apiVersion > 2u && params.isString())
{
std::string const index = params.asString();
if (index == jss::amendments.c_str())
return keylet::amendments().key;
if (index == jss::fee.c_str())
return keylet::fees().key;
if (index == jss::nunl)
return keylet::negativeUNL().key;
if (index == jss::hashes)
// Note this only finds the "short" skip list. Use "hashes":index to
// get the long list.
return keylet::skip().key;
}
return parseObjectID(params, fieldName, "hex string");
}
static Expected<uint256, Json::Value>
parseAccountRoot(
Json::Value const& params,
Json::StaticString const fieldName,
unsigned apiVersion)
parseAccountRoot(Json::Value const& params, Json::StaticString const fieldName)
{
if (auto const account = LedgerEntryHelpers::parse<AccountID>(params))
{
@@ -98,13 +52,14 @@ parseAccountRoot(
"malformedAddress", fieldName, "AccountID");
}
auto const parseAmendments = fixed(keylet::amendments());
static Expected<uint256, Json::Value>
parseAmendments(Json::Value const& params, Json::StaticString const fieldName)
{
return parseObjectID(params, fieldName, "hex string");
}
static Expected<uint256, Json::Value>
parseAMM(
Json::Value const& params,
Json::StaticString const fieldName,
unsigned apiVersion)
parseAMM(Json::Value const& params, Json::StaticString const fieldName)
{
if (!params.isObject())
{
@@ -131,10 +86,7 @@ parseAMM(
}
static Expected<uint256, Json::Value>
parseBridge(
Json::Value const& params,
Json::StaticString const fieldName,
unsigned apiVersion)
parseBridge(Json::Value const& params, Json::StaticString const fieldName)
{
if (!params.isMember(jss::bridge))
{
@@ -165,19 +117,13 @@ parseBridge(
}
static Expected<uint256, Json::Value>
parseCheck(
Json::Value const& params,
Json::StaticString const fieldName,
unsigned apiVersion)
parseCheck(Json::Value const& params, Json::StaticString const fieldName)
{
return parseObjectID(params, fieldName, "hex string");
}
static Expected<uint256, Json::Value>
parseCredential(
Json::Value const& cred,
Json::StaticString const fieldName,
unsigned apiVersion)
parseCredential(Json::Value const& cred, Json::StaticString const fieldName)
{
if (!cred.isObject())
{
@@ -208,10 +154,7 @@ parseCredential(
}
static Expected<uint256, Json::Value>
parseDelegate(
Json::Value const& params,
Json::StaticString const fieldName,
unsigned apiVersion)
parseDelegate(Json::Value const& params, Json::StaticString const fieldName)
{
if (!params.isObject())
{
@@ -279,10 +222,7 @@ parseAuthorizeCredentials(Json::Value const& jv)
}
static Expected<uint256, Json::Value>
parseDepositPreauth(
Json::Value const& dp,
Json::StaticString const fieldName,
unsigned apiVersion)
parseDepositPreauth(Json::Value const& dp, Json::StaticString const fieldName)
{
if (!dp.isObject())
{
@@ -342,10 +282,7 @@ parseDepositPreauth(
}
static Expected<uint256, Json::Value>
parseDID(
Json::Value const& params,
Json::StaticString const fieldName,
unsigned apiVersion)
parseDID(Json::Value const& params, Json::StaticString const fieldName)
{
auto const account = LedgerEntryHelpers::parse<AccountID>(params);
if (!account)
@@ -360,8 +297,7 @@ parseDID(
static Expected<uint256, Json::Value>
parseDirectoryNode(
Json::Value const& params,
Json::StaticString const fieldName,
unsigned apiVersion)
Json::StaticString const fieldName)
{
if (!params.isObject())
{
@@ -414,10 +350,7 @@ parseDirectoryNode(
}
static Expected<uint256, Json::Value>
parseEscrow(
Json::Value const& params,
Json::StaticString const fieldName,
unsigned apiVersion)
parseEscrow(Json::Value const& params, Json::StaticString const fieldName)
{
if (!params.isObject())
{
@@ -436,53 +369,20 @@ parseEscrow(
return keylet::escrow(*id, *seq).key;
}
auto const parseFeeSettings = fixed(keylet::fees());
static Expected<uint256, Json::Value>
parseFixed(
Keylet const& keylet,
Json::Value const& params,
Json::StaticString const& fieldName,
unsigned apiVersion)
parseFeeSettings(Json::Value const& params, Json::StaticString const fieldName)
{
if (!params.isBool())
{
return parseObjectID(params, fieldName, "hex string");
}
if (!params.asBool())
{
return LedgerEntryHelpers::invalidFieldError(
"invalidParams", fieldName, "true");
}
return keylet.key;
return parseObjectID(params, fieldName, "hex string");
}
static Expected<uint256, Json::Value>
parseLedgerHashes(
Json::Value const& params,
Json::StaticString const fieldName,
unsigned apiVersion)
parseLedgerHashes(Json::Value const& params, Json::StaticString const fieldName)
{
if (params.isUInt() || params.isInt())
{
// If the index doesn't parse as a UInt, throw
auto const index = params.asUInt();
// Return the "long" skip list for the given ledger index.
auto const keylet = keylet::skip(index);
return keylet.key;
}
// Return the key in `params` or the "short" skip list, which contains
// hashes since the last flag ledger.
return parseFixed(keylet::skip(), params, fieldName, apiVersion);
return parseObjectID(params, fieldName, "hex string");
}
static Expected<uint256, Json::Value>
parseMPToken(
Json::Value const& params,
Json::StaticString const fieldName,
unsigned apiVersion)
parseMPToken(Json::Value const& params, Json::StaticString const fieldName)
{
if (!params.isObject())
{
@@ -505,8 +405,7 @@ parseMPToken(
static Expected<uint256, Json::Value>
parseMPTokenIssuance(
Json::Value const& params,
Json::StaticString const fieldName,
unsigned apiVersion)
Json::StaticString const fieldName)
{
auto const mptIssuanceID = LedgerEntryHelpers::parse<uint192>(params);
if (!mptIssuanceID)
@@ -517,30 +416,25 @@ parseMPTokenIssuance(
}
static Expected<uint256, Json::Value>
parseNFTokenOffer(
Json::Value const& params,
Json::StaticString const fieldName,
unsigned apiVersion)
parseNFTokenOffer(Json::Value const& params, Json::StaticString const fieldName)
{
return parseObjectID(params, fieldName, "hex string");
}
static Expected<uint256, Json::Value>
parseNFTokenPage(
Json::Value const& params,
Json::StaticString const fieldName,
unsigned apiVersion)
parseNFTokenPage(Json::Value const& params, Json::StaticString const fieldName)
{
return parseObjectID(params, fieldName, "hex string");
}
auto const parseNegativeUNL = fixed(keylet::negativeUNL());
static Expected<uint256, Json::Value>
parseNegativeUNL(Json::Value const& params, Json::StaticString const fieldName)
{
return parseObjectID(params, fieldName, "hex string");
}
static Expected<uint256, Json::Value>
parseOffer(
Json::Value const& params,
Json::StaticString const fieldName,
unsigned apiVersion)
parseOffer(Json::Value const& params, Json::StaticString const fieldName)
{
if (!params.isObject())
{
@@ -561,10 +455,7 @@ parseOffer(
}
static Expected<uint256, Json::Value>
parseOracle(
Json::Value const& params,
Json::StaticString const fieldName,
unsigned apiVersion)
parseOracle(Json::Value const& params, Json::StaticString const fieldName)
{
if (!params.isObject())
{
@@ -585,10 +476,7 @@ parseOracle(
}
static Expected<uint256, Json::Value>
parsePayChannel(
Json::Value const& params,
Json::StaticString const fieldName,
unsigned apiVersion)
parsePayChannel(Json::Value const& params, Json::StaticString const fieldName)
{
return parseObjectID(params, fieldName, "hex string");
}
@@ -596,8 +484,7 @@ parsePayChannel(
static Expected<uint256, Json::Value>
parsePermissionedDomain(
Json::Value const& pd,
Json::StaticString const fieldName,
unsigned apiVersion)
Json::StaticString const fieldName)
{
if (pd.isString())
{
@@ -626,8 +513,7 @@ parsePermissionedDomain(
static Expected<uint256, Json::Value>
parseRippleState(
Json::Value const& jvRippleState,
Json::StaticString const fieldName,
unsigned apiVersion)
Json::StaticString const fieldName)
{
Currency uCurrency;
@@ -677,19 +563,13 @@ parseRippleState(
}
static Expected<uint256, Json::Value>
parseSignerList(
Json::Value const& params,
Json::StaticString const fieldName,
unsigned apiVersion)
parseSignerList(Json::Value const& params, Json::StaticString const fieldName)
{
return parseObjectID(params, fieldName, "hex string");
}
static Expected<uint256, Json::Value>
parseTicket(
Json::Value const& params,
Json::StaticString const fieldName,
unsigned apiVersion)
parseTicket(Json::Value const& params, Json::StaticString const fieldName)
{
if (!params.isObject())
{
@@ -710,10 +590,7 @@ parseTicket(
}
static Expected<uint256, Json::Value>
parseVault(
Json::Value const& params,
Json::StaticString const fieldName,
unsigned apiVersion)
parseVault(Json::Value const& params, Json::StaticString const fieldName)
{
if (!params.isObject())
{
@@ -736,8 +613,7 @@ parseVault(
static Expected<uint256, Json::Value>
parseXChainOwnedClaimID(
Json::Value const& claim_id,
Json::StaticString const fieldName,
unsigned apiVersion)
Json::StaticString const fieldName)
{
if (!claim_id.isObject())
{
@@ -762,8 +638,7 @@ parseXChainOwnedClaimID(
static Expected<uint256, Json::Value>
parseXChainOwnedCreateAccountClaimID(
Json::Value const& claim_id,
Json::StaticString const fieldName,
unsigned apiVersion)
Json::StaticString const fieldName)
{
if (!claim_id.isObject())
{
@@ -787,6 +662,10 @@ parseXChainOwnedCreateAccountClaimID(
return keylet.key;
}
using FunctionType = Expected<uint256, Json::Value> (*)(
Json::Value const&,
Json::StaticString const);
struct LedgerEntry
{
Json::StaticString fieldName;
@@ -819,7 +698,7 @@ doLedgerEntry(RPC::JsonContext& context)
{jss::ripple_state, parseRippleState, ltRIPPLE_STATE},
});
auto const hasMoreThanOneMember = [&]() {
auto hasMoreThanOneMember = [&]() {
int count = 0;
for (auto const& ledgerEntry : ledgerEntryParsers)
@@ -863,8 +742,8 @@ doLedgerEntry(RPC::JsonContext& context)
Json::Value const& params = ledgerEntry.fieldName == jss::bridge
? context.params
: context.params[ledgerEntry.fieldName];
auto const result = ledgerEntry.parseFunction(
params, ledgerEntry.fieldName, context.apiVersion);
auto const result =
ledgerEntry.parseFunction(params, ledgerEntry.fieldName);
if (!result)
return result.error();
@@ -895,13 +774,9 @@ doLedgerEntry(RPC::JsonContext& context)
throw;
}
// Return the computed index regardless of whether the node exists.
jvResult[jss::index] = to_string(uNodeIndex);
if (uNodeIndex.isZero())
{
RPC::inject_error(rpcENTRY_NOT_FOUND, jvResult);
return jvResult;
return RPC::make_error(rpcENTRY_NOT_FOUND);
}
auto const sleNode = lpLedger->read(keylet::unchecked(uNodeIndex));
@@ -913,14 +788,12 @@ doLedgerEntry(RPC::JsonContext& context)
if (!sleNode)
{
// Not found.
RPC::inject_error(rpcENTRY_NOT_FOUND, jvResult);
return jvResult;
return RPC::make_error(rpcENTRY_NOT_FOUND);
}
if ((expectedType != ltANY) && (expectedType != sleNode->getType()))
{
RPC::inject_error(rpcUNEXPECTED_LEDGER_TYPE, jvResult);
return jvResult;
return RPC::make_error(rpcUNEXPECTED_LEDGER_TYPE);
}
if (bNodeBinary)
@@ -930,10 +803,12 @@ doLedgerEntry(RPC::JsonContext& context)
sleNode->add(s);
jvResult[jss::node_binary] = strHex(s.peekData());
jvResult[jss::index] = to_string(uNodeIndex);
}
else
{
jvResult[jss::node] = sleNode->getJson(JsonOptions::none);
jvResult[jss::index] = to_string(uNodeIndex);
}
return jvResult;