Compare commits

..

4 Commits

Author SHA1 Message Date
Bart
7c1183547a chore: Change /Zi to /Z7 for ccache, remove debug symbols in CI (#6198)
As the `/Zi` compiler flag is unsupported by ccache, this change switches it to `/Z7` instead. For CI runs all debug info is omitted.
2026-01-09 21:44:43 +00:00
Vito Tumas
14467fba5e VaultClawback: Burn shares of an empty vault (#6120)
- Adds a mechanism for the vault owner to burn user shares when the vault is stuck. If the Vault has 0 AssetsAvailable and Total, the owner may submit a VaultClawback to reclaim the worthless fees, and thus allow the Vault to be deleted. The Amount must be left off (unless the owner is the asset issuer), specified as 0 Shares, or specified as the number of Shares held.
2026-01-09 14:58:02 -05:00
Zhanibek Bakin
fc00723836 fix: Truncate thread name to 15 chars on Linux (#5758)
This change:
* Truncates thread names if more than 15 chars with `snprintf`.
* Adds warnings for truncated thread names if `-DTRUNCATED_THREAD_NAME_LOGS=ON`.
* Add a static assert for string literals to stop compiling if > 15 chars.
* Shortens `Resource::Manager` to `Resource::Mngr` to fix the static assert failure.
* Updates `CurrentThreadName_test` unit test specifically for Linux to verify truncation.
2026-01-09 13:37:55 -05:00
oncecelll
c24a6041f7 docs: Fix minor spelling issues in comments (#6194) 2026-01-09 13:15:05 -05:00
20 changed files with 1071 additions and 311 deletions

View File

@@ -51,6 +51,7 @@ words:
- Btrfs
- canonicality
- checkme
- choco
- chrono
- citardauq
- clawback

View File

@@ -100,7 +100,7 @@ jobs:
uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0
- name: Prepare runner
uses: XRPLF/actions/prepare-runner@65da1c59e81965eeb257caa3587b9d45066fb925
uses: XRPLF/actions/prepare-runner@121d1de2775d486d46140b9a91b32d5002c08153
with:
enable_ccache: ${{ inputs.ccache_enabled }}

View File

@@ -46,6 +46,12 @@ set(CMAKE_VS_GLOBALS
"TrackFileAccess=false"
"UseMultiToolTask=true")
# By default Visual Studio generators will use /Zi, which is not compatible with
# ccache, so tell it to use /Z7 instead.
set(CMAKE_MSVC_DEBUG_INFORMATION_FORMAT "$<$<CONFIG:Debug,RelWithDebInfo>:Embedded>")
# By default Visual Studio generators will use /Zi to capture debug information,
# which is not compatible with ccache, so tell it to use /Z7 instead.
if (MSVC)
foreach (var_
CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_RELEASE
CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE)
string (REPLACE "/Zi" "/Z7" ${var_} "${${var_}}")
endforeach ()
endif ()

View File

@@ -44,6 +44,7 @@ if (MSVC)
# omit debug info completely under CI (not needed)
if (is_ci)
string (REPLACE "/Zi" " " ${var_} "${${var_}}")
string (REPLACE "/Z7" " " ${var_} "${${var_}}")
endif ()
endforeach ()

View File

@@ -68,6 +68,21 @@ if(is_linux)
option(perf "Enables flags that assist with perf recording" OFF)
option(use_gold "enables detection of gold (binutils) linker" ON)
option(use_mold "enables detection of mold (binutils) linker" ON)
# Set a default value for the log flag based on the build type.
# This provides a sensible default (on for debug, off for release)
# while still allowing the user to override it for any build.
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
set(TRUNCATED_LOGS_DEFAULT ON)
else()
set(TRUNCATED_LOGS_DEFAULT OFF)
endif()
option(TRUNCATED_THREAD_NAME_LOGS
"Show warnings about truncated thread names on Linux."
${TRUNCATED_LOGS_DEFAULT}
)
if(TRUNCATED_THREAD_NAME_LOGS)
add_compile_definitions(TRUNCATED_THREAD_NAME_LOGS)
endif()
else()
# we are not ready to allow shared-libs on windows because it would require
# export declarations. On macos it's more feasible, but static openssl

View File

@@ -5,6 +5,8 @@
#ifndef BEAST_CORE_CURRENT_THREAD_NAME_H_INCLUDED
#define BEAST_CORE_CURRENT_THREAD_NAME_H_INCLUDED
#include <boost/predef.h>
#include <string>
#include <string_view>
@@ -16,6 +18,31 @@ namespace beast {
void
setCurrentThreadName(std::string_view newThreadName);
#if BOOST_OS_LINUX
// On Linux, thread names are limited to 16 bytes including the null terminator.
// Maximum number of characters is therefore 15.
constexpr std::size_t maxThreadNameLength = 15;
/** Sets the name of the caller thread with compile-time size checking.
@tparam N The size of the string literal including null terminator
@param newThreadName A string literal to set as the thread name
This template overload enforces that thread names are at most 16 characters
(including null terminator) at compile time, matching Linux's limit.
*/
template <std::size_t N>
void
setCurrentThreadName(char const (&newThreadName)[N])
{
static_assert(
N <= maxThreadNameLength + 1,
"Thread name cannot exceed 15 characters");
setCurrentThreadName(std::string_view(newThreadName, N - 1));
}
#endif
/** Returns the name of the caller thread.
The name returned is the name as set by a call to setCurrentThreadName().

View File

@@ -1,7 +1,5 @@
#include <xrpl/beast/core/CurrentThreadName.h>
#include <boost/predef.h>
#include <string>
#include <string_view>
@@ -73,12 +71,32 @@ setCurrentThreadNameImpl(std::string_view name)
#if BOOST_OS_LINUX
#include <pthread.h>
#include <iostream>
namespace beast::detail {
inline void
setCurrentThreadNameImpl(std::string_view name)
{
pthread_setname_np(pthread_self(), name.data());
// truncate and set the thread name.
char boundedName[maxThreadNameLength + 1];
std::snprintf(
boundedName,
sizeof(boundedName),
"%.*s",
static_cast<int>(maxThreadNameLength),
name.data());
pthread_setname_np(pthread_self(), boundedName);
#ifdef TRUNCATED_THREAD_NAME_LOGS
if (name.size() > maxThreadNameLength)
{
std::cerr << "WARNING: Thread name \"" << name << "\" (length "
<< name.size() << ") exceeds maximum of "
<< maxThreadNameLength << " characters on Linux.\n";
}
#endif
}
} // namespace beast::detail

View File

@@ -77,7 +77,7 @@ deriveDeterministicRootKey(Seed const& seed)
std::array<std::uint8_t, 20> buf;
std::copy(seed.begin(), seed.end(), buf.begin());
// The odds that this loop executes more than once are neglible
// The odds that this loop executes more than once are negligible
// but *just* in case someone managed to generate a key that required
// more iterations loop a few times.
for (std::uint32_t seq = 0; seq != 128; ++seq)
@@ -137,7 +137,7 @@ private:
std::copy(generator_.begin(), generator_.end(), buf.begin());
copy_uint32(buf.data() + 33, seq);
// The odds that this loop executes more than once are neglible
// The odds that this loop executes more than once are negligible
// but we impose a maximum limit just in case.
for (std::uint32_t subseq = 0; subseq != 128; ++subseq)
{

View File

@@ -140,7 +140,7 @@ private:
void
run()
{
beast::setCurrentThreadName("Resource::Manager");
beast::setCurrentThreadName("Resource::Mngr");
for (;;)
{
logic_.periodicActivity();

View File

@@ -349,7 +349,7 @@ class HashRouter_test : public beast::unit_test::suite
h.set("hold_time", "alice");
h.set("relay_time", "bob");
auto const setup = setup_HashRouter(cfg);
// The set function ignores values that don't covert, so the
// The set function ignores values that don't convert, so the
// defaults are left unchanged
BEAST_EXPECT(setup.holdTime == 300s);
BEAST_EXPECT(setup.relayTime == 30s);

View File

@@ -2651,7 +2651,7 @@ class MPToken_test : public beast::unit_test::suite
STAmount const amt3{asset3, 10'000};
{
testcase("Test STAmount MPT arithmetics");
testcase("Test STAmount MPT arithmetic");
using namespace std::string_literals;
STAmount res = multiply(amt1, amt2, asset3);
BEAST_EXPECT(res == amt3);
@@ -2688,7 +2688,7 @@ class MPToken_test : public beast::unit_test::suite
}
{
testcase("Test MPTAmount arithmetics");
testcase("Test MPTAmount arithmetic");
MPTAmount mptAmt1{100};
MPTAmount const mptAmt2{100};
BEAST_EXPECT((mptAmt1 += mptAmt2) == MPTAmount{200});

View File

@@ -708,7 +708,7 @@ public:
void
testHeterogeneousSigners(FeatureBitset features)
{
testcase("Heterogenous Signers");
testcase("Heterogeneous Signers");
using namespace jtx;
Env env{*this, features};

View File

@@ -21,7 +21,6 @@
#include <xrpl/protocol/Protocol.h>
#include <xrpl/protocol/SField.h>
#include <xrpl/protocol/STAmount.h>
#include <xrpl/protocol/STNumber.h>
#include <xrpl/protocol/TER.h>
#include <xrpl/protocol/TxFlags.h>
#include <xrpl/protocol/XRPAmount.h>
@@ -940,25 +939,6 @@ class Vault_test : public beast::unit_test::suite
}
});
testCase([&](Env& env,
Account const& issuer,
Account const& owner,
Asset const& asset,
Vault& vault) {
testcase("clawback from self");
auto [tx, keylet] = vault.create({.owner = owner, .asset = asset});
{
auto tx = vault.clawback(
{.issuer = issuer,
.id = keylet.key,
.holder = issuer,
.amount = asset(10)});
env(tx, ter{temMALFORMED});
}
});
testCase([&](Env& env,
Account const&,
Account const& owner,
@@ -1197,11 +1177,13 @@ class Vault_test : public beast::unit_test::suite
auto [tx, keylet] = vault.create({.owner = owner, .asset = asset});
// Preclaim only checks for native assets.
if (asset.native())
{
auto tx = vault.clawback(
{.issuer = owner,
{.issuer = issuer,
.id = keylet.key,
.holder = issuer,
.holder = owner,
.amount = asset(50)});
env(tx, ter(temMALFORMED));
}
@@ -1924,8 +1906,20 @@ class Vault_test : public beast::unit_test::suite
env.close();
{
auto tx = vault.clawback(
{.issuer = owner, .id = keylet.key, .holder = depositor});
auto tx = vault.clawback({
.issuer = depositor,
.id = keylet.key,
.holder = depositor,
});
env(tx, ter(tecNO_PERMISSION));
}
{
auto tx = vault.clawback({
.issuer = owner,
.id = keylet.key,
.holder = depositor,
});
env(tx, ter(tecNO_PERMISSION));
}
});
@@ -2377,6 +2371,15 @@ class Vault_test : public beast::unit_test::suite
env(tx, ter(tecNO_AUTH));
}
{
// Cannot clawback if issuer is the holder
tx = vault.clawback(
{.issuer = issuer,
.id = keylet.key,
.holder = issuer,
.amount = asset(800)});
env(tx, ter(tecNO_PERMISSION));
}
// Clawback works
tx = vault.clawback(
{.issuer = issuer,
@@ -5243,6 +5246,542 @@ class Vault_test : public beast::unit_test::suite
});
}
void
testVaultClawbackBurnShares()
{
using namespace test::jtx;
using namespace loanBroker;
using namespace loan;
Env env(*this, beast::severities::kWarning);
auto const vaultAssetBalance = [&](Keylet const& vaultKeylet) {
auto const sleVault = env.le(vaultKeylet);
BEAST_EXPECT(sleVault != nullptr);
return std::make_pair(
sleVault->at(sfAssetsAvailable), sleVault->at(sfAssetsTotal));
};
auto const vaultShareBalance = [&](Keylet const& vaultKeylet) {
auto const sleVault = env.le(vaultKeylet);
BEAST_EXPECT(sleVault != nullptr);
auto const sleIssuance =
env.le(keylet::mptIssuance(sleVault->at(sfShareMPTID)));
BEAST_EXPECT(sleIssuance != nullptr);
return sleIssuance->at(sfOutstandingAmount);
};
auto const setupVault =
[&](PrettyAsset const& asset,
Account const& owner,
Account const& depositor) -> std::pair<Vault, Keylet> {
Vault vault{env};
auto const& [tx, vaultKeylet] =
vault.create({.owner = owner, .asset = asset});
env(tx, ter(tesSUCCESS), THISLINE);
env.close();
auto const& vaultSle = env.le(vaultKeylet);
BEAST_EXPECT(vaultSle != nullptr);
Asset share = vaultSle->at(sfShareMPTID);
env(vault.deposit(
{.depositor = depositor,
.id = vaultKeylet.key,
.amount = asset(100)}),
ter(tesSUCCESS),
THISLINE);
env.close();
auto const& [availablePreDefault, totalPreDefault] =
vaultAssetBalance(vaultKeylet);
BEAST_EXPECT(availablePreDefault == totalPreDefault);
BEAST_EXPECT(availablePreDefault == asset(100).value());
// attempt to clawback shares while there are assets fails
env(vault.clawback(
{.issuer = owner,
.id = vaultKeylet.key,
.holder = depositor,
.amount = share(0).value()}),
ter(tecNO_PERMISSION),
THISLINE);
env.close();
auto const& sharesAvailable = vaultShareBalance(vaultKeylet);
auto const& brokerKeylet =
keylet::loanbroker(owner.id(), env.seq(owner));
env(set(owner, vaultKeylet.key), THISLINE);
env.close();
auto const& loanKeylet = keylet::loan(brokerKeylet.key, 1);
// Create a simple Loan for the full amount of Vault assets
env(set(depositor, brokerKeylet.key, asset(100).value()),
loan::interestRate(TenthBips32(0)),
gracePeriod(10),
paymentInterval(120),
paymentTotal(10),
sig(sfCounterpartySignature, owner),
fee(env.current()->fees().base * 2),
ter(tesSUCCESS),
THISLINE);
env.close();
// attempt to clawback shares while there assetsAvailable == 0 and
// assetsTotal > 0 fails
env(vault.clawback(
{.issuer = owner,
.id = vaultKeylet.key,
.holder = depositor,
.amount = share(0).value()}),
ter(tecNO_PERMISSION),
THISLINE);
env.close();
env.close(std::chrono::seconds{120 + 10});
env(manage(owner, loanKeylet.key, tfLoanDefault),
ter(tesSUCCESS),
THISLINE);
auto const& [availablePostDefault, totalPostDefault] =
vaultAssetBalance(vaultKeylet);
BEAST_EXPECT(availablePostDefault == totalPostDefault);
BEAST_EXPECT(availablePostDefault == asset(0).value());
BEAST_EXPECT(vaultShareBalance(vaultKeylet) == sharesAvailable);
return std::make_pair(vault, vaultKeylet);
};
auto const testCase = [&](PrettyAsset const& asset,
std::string const& prefix,
Account const& owner,
Account const& depositor) {
{
testcase(
"VaultClawback (share) - " + prefix +
" owner asset clawback fails");
auto [vault, vaultKeylet] = setupVault(asset, owner, depositor);
env(vault.clawback({
.issuer = owner,
.id = vaultKeylet.key,
.holder = depositor,
.amount = asset(100).value(),
}),
// when asset is XRP or owner is not issuer clawback fail
// when owner is issuer precision loss occurs as vault is
// empty
asset.native() ? ter(temMALFORMED)
: asset.raw().getIssuer() != owner.id()
? ter(tecNO_PERMISSION)
: ter(tecPRECISION_LOSS),
THISLINE);
env.close();
}
{
testcase(
"VaultClawback (share) - " + prefix +
" owner incomplete share clawback fails");
auto [vault, vaultKeylet] = setupVault(asset, owner, depositor);
auto const& vaultSle = env.le(vaultKeylet);
BEAST_EXPECT(vaultSle != nullptr);
if (!vaultSle)
return;
Asset share = vaultSle->at(sfShareMPTID);
env(vault.clawback({
.issuer = owner,
.id = vaultKeylet.key,
.holder = depositor,
.amount = share(1).value(),
}),
ter(tecLIMIT_EXCEEDED),
THISLINE);
env.close();
}
{
testcase(
"VaultClawback (share) - " + prefix +
" owner implicit complete share clawback");
auto [vault, vaultKeylet] = setupVault(asset, owner, depositor);
env(vault.clawback({
.issuer = owner,
.id = vaultKeylet.key,
.holder = depositor,
}),
// when owner is issuer implicit clawback fails
asset.native() || asset.raw().getIssuer() != owner.id()
? ter(tesSUCCESS)
: ter(tecWRONG_ASSET),
THISLINE);
env.close();
}
{
testcase(
"VaultClawback (share) - " + prefix +
" owner explicit complete share clawback succeeds");
auto [vault, vaultKeylet] = setupVault(asset, owner, depositor);
auto const& vaultSle = env.le(vaultKeylet);
BEAST_EXPECT(vaultSle != nullptr);
if (!vaultSle)
return;
Asset share = vaultSle->at(sfShareMPTID);
env(vault.clawback({
.issuer = owner,
.id = vaultKeylet.key,
.holder = depositor,
.amount = share(vaultShareBalance(vaultKeylet)).value(),
}),
ter(tesSUCCESS),
THISLINE);
env.close();
}
{
testcase(
"VaultClawback (share) - " + prefix +
" owner can clawback own shares");
auto [vault, vaultKeylet] = setupVault(asset, owner, owner);
auto const& vaultSle = env.le(vaultKeylet);
BEAST_EXPECT(vaultSle != nullptr);
if (!vaultSle)
return;
Asset share = vaultSle->at(sfShareMPTID);
env(vault.clawback({
.issuer = owner,
.id = vaultKeylet.key,
.holder = owner,
.amount = share(vaultShareBalance(vaultKeylet)).value(),
}),
ter(tesSUCCESS),
THISLINE);
env.close();
}
{
testcase(
"VaultClawback (share) - " + prefix +
" empty vault share clawback fails");
auto [vault, vaultKeylet] = setupVault(asset, owner, owner);
auto const& vaultSle = env.le(vaultKeylet);
if (BEAST_EXPECT(vaultSle != nullptr))
return;
Asset share = vaultSle->at(sfShareMPTID);
env(vault.clawback({
.issuer = owner,
.id = vaultKeylet.key,
.holder = owner,
.amount = share(vaultShareBalance(vaultKeylet)).value(),
}),
ter(tesSUCCESS),
THISLINE);
// Now the vault is empty, clawback again fails
env(vault.clawback({
.issuer = owner,
.id = vaultKeylet.key,
.holder = owner,
}),
ter(tecNO_PERMISSION),
THISLINE);
env.close();
}
};
Account owner{"alice"};
Account depositor{"bob"};
Account issuer{"issuer"};
env.fund(XRP(10000), issuer, owner, depositor);
env.close();
// Test XRP
PrettyAsset xrp = xrpIssue();
testCase(xrp, "XRP", owner, depositor);
testCase(xrp, "XRP (depositor is owner)", owner, owner);
// Test IOU
PrettyAsset IOU = issuer["IOU"];
env(fset(issuer, asfAllowTrustLineClawback));
env.close();
env.trust(IOU(1000), owner);
env.trust(IOU(1000), depositor);
env(pay(issuer, owner, IOU(100)));
env(pay(issuer, depositor, IOU(100)));
env.close();
testCase(IOU, "IOU", owner, depositor);
testCase(IOU, "IOU (owner is issuer)", issuer, depositor);
// Test MPT
MPTTester mptt{env, issuer, mptInitNoFund};
mptt.create(
{.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock});
PrettyAsset MPT = mptt.issuanceID();
mptt.authorize({.account = owner});
mptt.authorize({.account = depositor});
env(pay(issuer, owner, MPT(1000)));
env(pay(issuer, depositor, MPT(1000)));
env.close();
testCase(MPT, "MPT", owner, depositor);
testCase(MPT, "MPT (owner is issuer)", issuer, depositor);
}
void
testVaultClawbackAssets()
{
using namespace test::jtx;
using namespace loanBroker;
using namespace loan;
Env env(*this);
auto const setupVault =
[&](PrettyAsset const& asset,
Account const& owner,
Account const& depositor,
Account const& issuer) -> std::pair<Vault, Keylet> {
Vault vault{env};
auto const& [tx, vaultKeylet] =
vault.create({.owner = owner, .asset = asset});
env(tx, ter(tesSUCCESS), THISLINE);
env.close();
auto const& vaultSle = env.le(vaultKeylet);
BEAST_EXPECT(vaultSle != nullptr);
env(vault.deposit(
{.depositor = depositor,
.id = vaultKeylet.key,
.amount = asset(100)}),
ter(tesSUCCESS),
THISLINE);
env.close();
return std::make_pair(vault, vaultKeylet);
};
auto const testCase = [&](PrettyAsset const& asset,
std::string const& prefix,
Account const& owner,
Account const& depositor,
Account const& issuer) {
if (asset.native())
{
testcase(
"VaultClawback (asset) - " + prefix +
" issuer XRP clawback fails");
auto [vault, vaultKeylet] =
setupVault(asset, owner, depositor, issuer);
// If the asset is XRP, clawback with amount fails as malfored
// when asset is specified.
env(vault.clawback({
.issuer = issuer,
.id = vaultKeylet.key,
.holder = issuer,
.amount = asset(1).value(),
}),
ter(temMALFORMED),
THISLINE);
// When asset is implicit, clawback fails as no permission.
env(vault.clawback({
.issuer = issuer,
.id = vaultKeylet.key,
.holder = issuer,
}),
ter(tecNO_PERMISSION),
THISLINE);
return;
}
{
testcase(
"VaultClawback (asset) - " + prefix +
" clawback for different asset fails");
auto [vault, vaultKeylet] =
setupVault(asset, owner, depositor, issuer);
Account issuer2{"issuer2"};
PrettyAsset asset2 = issuer2["FOO"];
env(vault.clawback({
.issuer = issuer,
.id = vaultKeylet.key,
.holder = depositor,
.amount = asset2(1).value(),
}),
ter(tecWRONG_ASSET),
THISLINE);
}
{
testcase(
"VaultClawback (asset) - " + prefix +
" ambiguous owner/issuer asset clawback fails");
auto [vault, vaultKeylet] =
setupVault(asset, issuer, depositor, issuer);
env(vault.clawback({
.issuer = issuer,
.id = vaultKeylet.key,
.holder = issuer,
}),
ter(tecWRONG_ASSET),
THISLINE);
}
{
testcase(
"VaultClawback (asset) - " + prefix +
" non-issuer asset clawback fails");
auto [vault, vaultKeylet] =
setupVault(asset, owner, depositor, issuer);
env(vault.clawback({
.issuer = owner,
.id = vaultKeylet.key,
.holder = depositor,
}),
ter(tecNO_PERMISSION),
THISLINE);
env(vault.clawback({
.issuer = owner,
.id = vaultKeylet.key,
.holder = depositor,
.amount = asset(1).value(),
}),
ter(tecNO_PERMISSION),
THISLINE);
}
{
testcase(
"VaultClawback (asset) - " + prefix +
" issuer clawback from self fails");
auto [vault, vaultKeylet] =
setupVault(asset, owner, issuer, issuer);
env(vault.clawback({
.issuer = issuer,
.id = vaultKeylet.key,
.holder = issuer,
}),
ter(tecNO_PERMISSION),
THISLINE);
}
{
testcase(
"VaultClawback (asset) - " + prefix +
" issuer share clawback fails");
auto [vault, vaultKeylet] =
setupVault(asset, owner, depositor, issuer);
auto const& vaultSle = env.le(vaultKeylet);
BEAST_EXPECT(vaultSle != nullptr);
if (!vaultSle)
return;
Asset share = vaultSle->at(sfShareMPTID);
env(vault.clawback({
.issuer = issuer,
.id = vaultKeylet.key,
.holder = depositor,
.amount = share(1).value(),
}),
ter(tecNO_PERMISSION),
THISLINE);
}
{
testcase(
"VaultClawback (asset) - " + prefix +
" partial issuer asset clawback succeeds");
auto [vault, vaultKeylet] =
setupVault(asset, owner, depositor, issuer);
env(vault.clawback({
.issuer = issuer,
.id = vaultKeylet.key,
.holder = depositor,
.amount = asset(1).value(),
}),
ter(tesSUCCESS),
THISLINE);
}
{
testcase(
"VaultClawback (asset) - " + prefix +
" full issuer asset clawback succeeds");
auto [vault, vaultKeylet] =
setupVault(asset, owner, depositor, issuer);
env(vault.clawback({
.issuer = issuer,
.id = vaultKeylet.key,
.holder = depositor,
.amount = asset(100).value(),
}),
ter(tesSUCCESS),
THISLINE);
}
{
testcase(
"VaultClawback (asset) - " + prefix +
" implicit full issuer asset clawback succeeds");
auto [vault, vaultKeylet] =
setupVault(asset, owner, depositor, issuer);
env(vault.clawback({
.issuer = issuer,
.id = vaultKeylet.key,
.holder = depositor,
}),
ter(tesSUCCESS),
THISLINE);
}
};
Account owner{"alice"};
Account depositor{"bob"};
Account issuer{"issuer"};
env.fund(XRP(10000), issuer, owner, depositor);
env.close();
// Test XRP
PrettyAsset xrp = xrpIssue();
testCase(xrp, "XRP", owner, depositor, issuer);
// Test IOU
PrettyAsset IOU = issuer["IOU"];
env(fset(issuer, asfAllowTrustLineClawback));
env.close();
env.trust(IOU(1000), owner);
env.trust(IOU(1000), depositor);
env(pay(issuer, owner, IOU(1000)));
env(pay(issuer, depositor, IOU(1000)));
env.close();
testCase(IOU, "IOU", owner, depositor, issuer);
// Test MPT
MPTTester mptt{env, issuer, mptInitNoFund};
mptt.create(
{.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock});
PrettyAsset MPT = mptt.issuanceID();
mptt.authorize({.account = owner});
mptt.authorize({.account = depositor});
env(pay(issuer, depositor, MPT(1000)));
env.close();
testCase(MPT, "MPT", owner, depositor, issuer);
}
public:
void
run() override
@@ -5261,6 +5800,8 @@ public:
testScaleIOU();
testRPC();
testDelegate();
testVaultClawbackBurnShares();
testVaultClawbackAssets();
}
};

View File

@@ -396,7 +396,7 @@ public:
// This checks that partialDelete has run to completion
// before the destructor is called. A sleep is inserted
// inside the partial delete to make sure the destructor is
// given an opportunity to run durring partial delete.
// given an opportunity to run during partial delete.
BEAST_EXPECT(cur == partiallyDeleted);
}
if (next == partiallyDeletedStarted)

View File

@@ -1,6 +1,8 @@
#include <xrpl/beast/core/CurrentThreadName.h>
#include <xrpl/beast/unit_test.h>
#include <boost/predef/os.h>
#include <thread>
namespace xrpl {
@@ -37,33 +39,71 @@ private:
if (beast::getCurrentThreadName() == myName)
*state = 2;
}
#if BOOST_OS_LINUX
// Helper function to test a specific name.
// It creates a thread, sets the name, and checks if the OS-level
// name matches the expected (potentially truncated) name.
void
testName(std::string const& nameToSet, std::string const& expectedName)
{
std::thread t([&] {
beast::setCurrentThreadName(nameToSet);
// Initialize buffer to be safe.
char actualName[beast::maxThreadNameLength + 1] = {};
pthread_getname_np(pthread_self(), actualName, sizeof(actualName));
BEAST_EXPECT(std::string(actualName) == expectedName);
});
t.join();
}
#endif
public:
void
run() override
{
// Make two different threads with two different names. Make sure
// that the expected thread names are still there when the thread
// exits.
std::atomic<bool> stop{false};
// Make two different threads with two different names.
// Make sure that the expected thread names are still there
// when the thread exits.
{
std::atomic<bool> stop{false};
std::atomic<int> stateA{0};
std::thread tA(exerciseName, "tA", &stop, &stateA);
std::atomic<int> stateA{0};
std::thread tA(exerciseName, "tA", &stop, &stateA);
std::atomic<int> stateB{0};
std::thread tB(exerciseName, "tB", &stop, &stateB);
std::atomic<int> stateB{0};
std::thread tB(exerciseName, "tB", &stop, &stateB);
// Wait until both threads have set their names.
while (stateA == 0 || stateB == 0)
;
// Wait until both threads have set their names.
while (stateA == 0 || stateB == 0)
;
stop = true;
tA.join();
tB.join();
stop = true;
tA.join();
tB.join();
// Both threads should still have the expected name when they exit.
BEAST_EXPECT(stateA == 2);
BEAST_EXPECT(stateB == 2);
// Both threads should still have the expected name when they exit.
BEAST_EXPECT(stateA == 2);
BEAST_EXPECT(stateB == 2);
}
#if BOOST_OS_LINUX
// On Linux, verify that thread names longer than 15 characters
// are truncated to 15 characters (the 16th character is reserved for
// the null terminator).
{
testName(
"123456789012345",
"123456789012345"); // 15 chars, no truncation
testName(
"1234567890123456", "123456789012345"); // 16 chars, truncated
testName(
"ThisIsAVeryLongThreadNameExceedingLimit",
"ThisIsAVeryLong"); // 39 chars, truncated
testName("", ""); // empty name
testName("short", "short"); // short name, no truncation
}
#endif
}
};

View File

@@ -10,7 +10,6 @@
#include <doctest/doctest.h>
#include <atomic>
#include <iostream>
#include <map>
#include <thread>
@@ -18,40 +17,6 @@ using namespace xrpl;
namespace {
struct logger
{
std::string name;
logger const* const parent = nullptr;
static std::size_t depth;
logger(std::string n) : name(n)
{
std::clog << indent() << name << " begin\n";
++depth;
}
logger(logger const& p, std::string n) : parent(&p), name(n)
{
std::clog << indent() << parent->name << " : " << name << " begin\n";
++depth;
}
~logger()
{
--depth;
if (parent)
std::clog << indent() << parent->name << " : " << name << " end\n";
else
std::clog << indent() << name << " end\n";
}
std::string
indent()
{
return std::string(depth, ' ');
}
};
std::size_t logger::depth = 0;
// Simple HTTP server using Beast for testing
class TestHTTPServer
{
@@ -70,7 +35,6 @@ private:
public:
TestHTTPServer() : acceptor_(ioc_), port_(0)
{
logger l("TestHTTPServer()");
// Bind to any available port
endpoint_ = {boost::asio::ip::tcp::v4(), 0};
acceptor_.open(endpoint_.protocol());
@@ -86,7 +50,6 @@ public:
~TestHTTPServer()
{
logger l("~TestHTTPServer()");
stop();
}
@@ -124,7 +87,6 @@ private:
void
stop()
{
logger l("TestHTTPServer::stop");
running_ = false;
acceptor_.close();
}
@@ -132,7 +94,6 @@ private:
void
accept()
{
logger l("TestHTTPServer::accept");
if (!running_)
return;
@@ -154,37 +115,31 @@ private:
void
handleConnection(boost::asio::ip::tcp::socket socket)
{
logger l("TestHTTPServer::handleConnection");
try
{
std::optional<logger> r(std::in_place, l, "read the http request");
// Read the HTTP request
boost::beast::flat_buffer buffer;
boost::beast::http::request<boost::beast::http::string_body> req;
boost::beast::http::read(socket, buffer, req);
// Create response
r.emplace(l, "create response");
boost::beast::http::response<boost::beast::http::string_body> res;
res.version(req.version());
res.result(status_code_);
res.set(boost::beast::http::field::server, "TestServer");
// Add custom headers
r.emplace(l, "add custom headers");
for (auto const& [name, value] : custom_headers_)
{
res.set(name, value);
}
// Set body and prepare payload first
r.emplace(l, "set body and prepare payload");
res.body() = response_body_;
res.prepare_payload();
// Override Content-Length with custom headers after prepare_payload
// This allows us to test case-insensitive header parsing
r.emplace(l, "override content-length");
for (auto const& [name, value] : custom_headers_)
{
if (boost::iequals(name, "Content-Length"))
@@ -195,25 +150,19 @@ private:
}
// Send response
r.emplace(l, "send response");
boost::beast::http::write(socket, res);
// Shutdown socket gracefully
r.emplace(l, "shutdown socket");
boost::system::error_code ec;
socket.shutdown(boost::asio::ip::tcp::socket::shutdown_send, ec);
}
catch (std::exception const&)
{
// Connection handling errors are expected
logger c(l, "catch");
}
if (running_)
{
logger r(l, "accept");
accept();
}
}
};
@@ -227,16 +176,12 @@ runHTTPTest(
std::string& result_data,
boost::system::error_code& result_error)
{
logger l("runHTTPTest");
// Create a null journal for testing
beast::Journal j{beast::Journal::getNullSink()};
std::optional<logger> r(std::in_place, l, "initializeSSLContext");
// Initialize HTTPClient SSL context
HTTPClient::initializeSSLContext("", "", false, j);
r.emplace(l, "HTTPClient::get");
HTTPClient::get(
false, // no SSL
server.ioc(),
@@ -261,7 +206,6 @@ runHTTPTest(
while (!completed &&
std::chrono::steady_clock::now() - start < std::chrono::seconds(10))
{
r.emplace(l, "ioc.run_one");
if (server.ioc().run_one() == 0)
{
break;
@@ -275,8 +219,6 @@ runHTTPTest(
TEST_CASE("HTTPClient case insensitive Content-Length")
{
logger l("HTTPClient case insensitive Content-Length");
// Test different cases of Content-Length header
std::vector<std::string> header_cases = {
"Content-Length", // Standard case
@@ -288,7 +230,6 @@ TEST_CASE("HTTPClient case insensitive Content-Length")
for (auto const& header_name : header_cases)
{
logger h(l, header_name);
TestHTTPServer server;
std::string test_body = "Hello World!";
server.setResponseBody(test_body);
@@ -317,7 +258,6 @@ TEST_CASE("HTTPClient case insensitive Content-Length")
TEST_CASE("HTTPClient basic HTTP request")
{
logger l("HTTPClient basic HTTP request");
TestHTTPServer server;
std::string test_body = "Test response body";
server.setResponseBody(test_body);
@@ -339,7 +279,6 @@ TEST_CASE("HTTPClient basic HTTP request")
TEST_CASE("HTTPClient empty response")
{
logger l("HTTPClient empty response");
TestHTTPServer server;
server.setResponseBody(""); // Empty body
server.setHeader("Content-Length", "0");
@@ -360,7 +299,6 @@ TEST_CASE("HTTPClient empty response")
TEST_CASE("HTTPClient different status codes")
{
logger l("HTTPClient different status codes");
std::vector<unsigned int> status_codes = {200, 404, 500};
for (auto status : status_codes)

View File

@@ -95,6 +95,7 @@ hasPrivilege(STTx const& tx, Privilege priv)
switch (tx.getTxnType())
{
#include <xrpl/protocol/detail/transactions.macro>
// Deprecated types
default:
return false;
@@ -2622,6 +2623,7 @@ ValidVault::Vault::make(SLE const& from)
self.key = from.key();
self.asset = from.at(sfAsset);
self.pseudoId = from.getAccountID(sfAccount);
self.owner = from.at(sfOwner);
self.shareMPTID = from.getFieldH192(sfShareMPTID);
self.assetsTotal = from.at(sfAssetsTotal);
self.assetsAvailable = from.at(sfAssetsAvailable);
@@ -3066,6 +3068,10 @@ ValidVault::finalize(
: std::nullopt;
};
auto const vaultHoldsNoAssets = [&](Vault const& vault) {
return vault.assetsAvailable == 0 && vault.assetsTotal == 0;
};
// Technically this does not need to be a lambda, but it's more
// convenient thanks to early "return false"; the not-so-nice
// alternatives are several layers of nested if/else or more complex
@@ -3448,29 +3454,56 @@ ValidVault::finalize(
if (vaultAsset.native() ||
vaultAsset.getIssuer() != tx[sfAccount])
{
JLOG(j.fatal()) << //
"Invariant failed: clawback may only be performed by "
"the asset issuer";
return false; // That's all we can do
// The owner can use clawback to force-burn shares when the
// vault is empty but there are outstanding shares
if (!(beforeShares && beforeShares->sharesTotal > 0 &&
vaultHoldsNoAssets(beforeVault) &&
beforeVault.owner == tx[sfAccount]))
{
JLOG(j.fatal()) << //
"Invariant failed: clawback may only be performed "
"by the asset issuer, or by the vault owner of an "
"empty vault";
return false; // That's all we can do
}
}
auto const vaultDeltaAssets = deltaAssets(afterVault.pseudoId);
if (vaultDeltaAssets)
{
if (*vaultDeltaAssets >= zero)
{
JLOG(j.fatal()) << //
"Invariant failed: clawback must decrease vault "
"balance";
result = false;
}
if (!vaultDeltaAssets)
if (beforeVault.assetsTotal + *vaultDeltaAssets !=
afterVault.assetsTotal)
{
JLOG(j.fatal()) << //
"Invariant failed: clawback and assets outstanding "
"must add up";
result = false;
}
if (beforeVault.assetsAvailable + *vaultDeltaAssets !=
afterVault.assetsAvailable)
{
JLOG(j.fatal()) << //
"Invariant failed: clawback and assets available "
"must add up";
result = false;
}
}
else if (!vaultHoldsNoAssets(beforeVault))
{
JLOG(j.fatal()) << //
"Invariant failed: clawback must change vault balance";
return false; // That's all we can do
}
if (*vaultDeltaAssets >= zero)
{
JLOG(j.fatal()) << //
"Invariant failed: clawback must decrease vault "
"balance";
result = false;
}
auto const accountDeltaShares = deltaShares(tx[sfHolder]);
if (!accountDeltaShares)
{
@@ -3503,24 +3536,6 @@ ValidVault::finalize(
result = false;
}
if (beforeVault.assetsTotal + *vaultDeltaAssets !=
afterVault.assetsTotal)
{
JLOG(j.fatal()) << //
"Invariant failed: clawback and assets outstanding "
"must add up";
result = false;
}
if (beforeVault.assetsAvailable + *vaultDeltaAssets !=
afterVault.assetsAvailable)
{
JLOG(j.fatal()) << //
"Invariant failed: clawback and assets available must "
"add up";
result = false;
}
return result;
}

View File

@@ -861,6 +861,7 @@ class ValidVault
uint256 key = beast::zero;
Asset asset = {};
AccountID pseudoId = {};
AccountID owner = {};
uint192 shareMPTID = beast::zero;
Number assetsTotal = 0;
Number assetsAvailable = 0;

View File

@@ -1,18 +1,17 @@
#include <xrpld/app/tx/detail/VaultClawback.h>
//
#include <xrpl/beast/utility/instrumentation.h>
#include <xrpl/ledger/View.h>
#include <xrpl/protocol/AccountID.h>
#include <xrpl/protocol/Feature.h>
#include <xrpl/protocol/MPTIssue.h>
#include <xrpl/protocol/SField.h>
#include <xrpl/protocol/STAmount.h>
#include <xrpl/protocol/STNumber.h>
#include <xrpl/protocol/TER.h>
#include <xrpl/protocol/TxFlags.h>
#include <optional>
namespace xrpl {
NotTEC
VaultClawback::preflight(PreflightContext const& ctx)
{
@@ -22,15 +21,6 @@ VaultClawback::preflight(PreflightContext const& ctx)
return temMALFORMED;
}
AccountID const issuer = ctx.tx[sfAccount];
AccountID const holder = ctx.tx[sfHolder];
if (issuer == holder)
{
JLOG(ctx.j.debug()) << "VaultClawback: issuer cannot be holder.";
return temMALFORMED;
}
auto const amount = ctx.tx[~sfAmount];
if (amount)
{
@@ -42,17 +32,27 @@ VaultClawback::preflight(PreflightContext const& ctx)
JLOG(ctx.j.debug()) << "VaultClawback: cannot clawback XRP.";
return temMALFORMED;
}
else if (amount->asset().getIssuer() != issuer)
{
JLOG(ctx.j.debug())
<< "VaultClawback: only asset issuer can clawback.";
return temMALFORMED;
}
}
return tesSUCCESS;
}
[[nodiscard]] STAmount
clawbackAmount(
std::shared_ptr<SLE const> const& vault,
std::optional<STAmount> const& maybeAmount,
AccountID const& account)
{
if (maybeAmount)
return *maybeAmount;
Asset const share = MPTIssue{vault->at(sfShareMPTID)};
if (account == vault->at(sfOwner))
return STAmount{share};
return STAmount{vault->at(sfAsset)};
}
TER
VaultClawback::preclaim(PreclaimContext const& ctx)
{
@@ -60,61 +60,264 @@ VaultClawback::preclaim(PreclaimContext const& ctx)
if (!vault)
return tecNO_ENTRY;
auto account = ctx.tx[sfAccount];
auto const issuer = ctx.view.read(keylet::account(account));
if (!issuer)
Asset const vaultAsset = vault->at(sfAsset);
auto const account = ctx.tx[sfAccount];
auto const holder = ctx.tx[sfHolder];
auto const maybeAmount = ctx.tx[~sfAmount];
auto const mptIssuanceID = vault->at(sfShareMPTID);
auto const sleShareIssuance =
ctx.view.read(keylet::mptIssuance(mptIssuanceID));
if (!sleShareIssuance)
{
// LCOV_EXCL_START
JLOG(ctx.j.error()) << "VaultClawback: missing issuer account.";
JLOG(ctx.j.error())
<< "VaultClawback: missing issuance of vault shares.";
return tefINTERNAL;
// LCOV_EXCL_STOP
}
Asset const vaultAsset = vault->at(sfAsset);
if (auto const amount = ctx.tx[~sfAmount];
amount && vaultAsset != amount->asset())
Asset const share = MPTIssue{mptIssuanceID};
// Ambiguous case: If Issuer is Owner they must specify the asset
if (!maybeAmount && !vaultAsset.native() &&
vaultAsset.getIssuer() == vault->at(sfOwner))
{
JLOG(ctx.j.debug())
<< "VaultClawback: must specify amount when issuer is owner.";
return tecWRONG_ASSET;
if (vaultAsset.native())
{
JLOG(ctx.j.debug()) << "VaultClawback: cannot clawback XRP.";
return tecNO_PERMISSION; // Cannot clawback XRP.
}
else if (vaultAsset.getIssuer() != account)
{
JLOG(ctx.j.debug()) << "VaultClawback: only asset issuer can clawback.";
return tecNO_PERMISSION; // Only issuers can clawback.
}
if (vaultAsset.holds<MPTIssue>())
{
auto const mpt = vaultAsset.get<MPTIssue>();
auto const mptIssue =
ctx.view.read(keylet::mptIssuance(mpt.getMptID()));
if (mptIssue == nullptr)
return tecOBJECT_NOT_FOUND;
auto const amount = clawbackAmount(vault, maybeAmount, account);
std::uint32_t const issueFlags = mptIssue->getFieldU32(sfFlags);
if (!(issueFlags & lsfMPTCanClawback))
// There is a special case that allows the VaultOwner to use clawback to
// burn shares when Vault assets total and available are zero, but
// shares remain. However, that case is handled in doApply() directly,
// so here we just enforce checks.
if (amount.asset() == share)
{
// Only the Vault Owner may clawback shares
if (account != vault->at(sfOwner))
{
JLOG(ctx.j.debug())
<< "VaultClawback: cannot clawback MPT vault asset.";
<< "VaultClawback: only vault owner can clawback shares.";
return tecNO_PERMISSION;
}
}
else if (vaultAsset.holds<Issue>())
{
std::uint32_t const issuerFlags = issuer->getFieldU32(sfFlags);
if (!(issuerFlags & lsfAllowTrustLineClawback) ||
(issuerFlags & lsfNoFreeze))
auto const assetsTotal = vault->at(sfAssetsTotal);
auto const assetsAvailable = vault->at(sfAssetsAvailable);
auto const sharesTotal = sleShareIssuance->at(sfOutstandingAmount);
// Owner can clawback funds when the vault has shares but no assets
if (sharesTotal == 0 || (assetsTotal != 0 || assetsAvailable != 0))
{
JLOG(ctx.j.debug())
<< "VaultClawback: cannot clawback IOU vault asset.";
<< "VaultClawback: vault owner can clawback shares only"
" when vault has no assets.";
return tecNO_PERMISSION;
}
// If amount is non-zero, the VaultOwner must burn all shares
if (amount != beast::zero)
{
Number const& sharesHeld = accountHolds(
ctx.view,
holder,
share,
FreezeHandling::fhIGNORE_FREEZE,
AuthHandling::ahIGNORE_AUTH,
ctx.j);
// The VaultOwner must burn all shares
if (amount != sharesHeld)
{
JLOG(ctx.j.debug())
<< "VaultClawback: vault owner must clawback all "
"shares.";
return tecLIMIT_EXCEEDED;
}
}
return tesSUCCESS;
}
return tesSUCCESS;
// The asset that is being clawed back is the vault asset
if (amount.asset() == vaultAsset)
{
// XRP cannot be clawed back
if (vaultAsset.native())
{
JLOG(ctx.j.debug()) << "VaultClawback: cannot clawback XRP.";
return tecNO_PERMISSION;
}
// Only the Asset Issuer may clawback the asset
if (account != vaultAsset.getIssuer())
{
JLOG(ctx.j.debug())
<< "VaultClawback: only asset issuer can clawback asset.";
return tecNO_PERMISSION;
}
// The issuer cannot clawback from itself
if (account == holder)
{
JLOG(ctx.j.debug())
<< "VaultClawback: issuer cannot be the holder.";
return tecNO_PERMISSION;
}
return std::visit(
[&]<ValidIssueType TIss>(TIss const& issue) -> TER {
if constexpr (std::is_same_v<TIss, MPTIssue>)
{
auto const mptIssue =
ctx.view.read(keylet::mptIssuance(issue.getMptID()));
if (mptIssue == nullptr)
return tecOBJECT_NOT_FOUND;
std::uint32_t const issueFlags =
mptIssue->getFieldU32(sfFlags);
if (!(issueFlags & lsfMPTCanClawback))
{
JLOG(ctx.j.debug()) << "VaultClawback: cannot clawback "
"MPT vault asset.";
return tecNO_PERMISSION;
}
}
else if constexpr (std::is_same_v<TIss, Issue>)
{
auto const issuerSle =
ctx.view.read(keylet::account(account));
if (!issuerSle)
{
// LCOV_EXCL_START
JLOG(ctx.j.error())
<< "VaultClawback: missing submitter account.";
return tefINTERNAL;
// LCOV_EXCL_STOP
}
std::uint32_t const issuerFlags =
issuerSle->getFieldU32(sfFlags);
if (!(issuerFlags & lsfAllowTrustLineClawback) ||
(issuerFlags & lsfNoFreeze))
{
JLOG(ctx.j.debug()) << "VaultClawback: cannot clawback "
"IOU vault asset.";
return tecNO_PERMISSION;
}
}
return tesSUCCESS;
},
vaultAsset.value());
}
// Invalid asset
return tecWRONG_ASSET;
}
Expected<std::pair<STAmount, STAmount>, TER>
VaultClawback::assetsToClawback(
std::shared_ptr<SLE> const& vault,
std::shared_ptr<SLE const> const& sleShareIssuance,
AccountID const& holder,
STAmount const& clawbackAmount)
{
if (clawbackAmount.asset() != vault->at(sfAsset))
{
// preclaim should have blocked this , now it's an internal error
// LCOV_EXCL_START
JLOG(j_.error()) << "VaultClawback: asset mismatch in clawback.";
return Unexpected(tecINTERNAL);
// LCOV_EXCL_STOP
}
auto const assetsAvailable = vault->at(sfAssetsAvailable);
auto const mptIssuanceID = *vault->at(sfShareMPTID);
MPTIssue const share{mptIssuanceID};
if (clawbackAmount == beast::zero)
{
auto const sharesDestroyed = accountHolds(
view(),
holder,
share,
FreezeHandling::fhIGNORE_FREEZE,
AuthHandling::ahIGNORE_AUTH,
j_);
auto const maybeAssets =
sharesToAssetsWithdraw(vault, sleShareIssuance, sharesDestroyed);
if (!maybeAssets)
return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE
return std::make_pair(*maybeAssets, sharesDestroyed);
}
STAmount sharesDestroyed;
STAmount assetsRecovered = clawbackAmount;
try
{
{
auto const maybeShares = assetsToSharesWithdraw(
vault, sleShareIssuance, assetsRecovered);
if (!maybeShares)
return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE
sharesDestroyed = *maybeShares;
}
auto const maybeAssets =
sharesToAssetsWithdraw(vault, sleShareIssuance, sharesDestroyed);
if (!maybeAssets)
return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE
assetsRecovered = *maybeAssets;
// Clamp to maximum.
if (assetsRecovered > *assetsAvailable)
{
assetsRecovered = *assetsAvailable;
// Note, it is important to truncate the number of shares,
// otherwise the corresponding assets might breach the
// AssetsAvailable
{
auto const maybeShares = assetsToSharesWithdraw(
vault,
sleShareIssuance,
assetsRecovered,
TruncateShares::yes);
if (!maybeShares)
return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE
sharesDestroyed = *maybeShares;
}
auto const maybeAssets = sharesToAssetsWithdraw(
vault, sleShareIssuance, sharesDestroyed);
if (!maybeAssets)
return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE
assetsRecovered = *maybeAssets;
if (assetsRecovered > *assetsAvailable)
{
// LCOV_EXCL_START
JLOG(j_.error())
<< "VaultClawback: invalid rounding of shares.";
return Unexpected(tecINTERNAL);
// LCOV_EXCL_STOP
}
}
}
catch (std::overflow_error const&)
{
// It's easy to hit this exception from Number with large enough
// Scale so we avoid spamming the log and only use debug here.
JLOG(j_.debug()) //
<< "VaultClawback: overflow error with"
<< " scale=" << (int)vault->at(sfScale).value() //
<< ", assetsTotal=" << vault->at(sfAssetsTotal).value()
<< ", sharesTotal=" << sleShareIssuance->at(sfOutstandingAmount)
<< ", amount=" << clawbackAmount.value();
return Unexpected(tecPATH_DRY);
}
return std::make_pair(assetsRecovered, sharesDestroyed);
}
TER
@@ -125,7 +328,7 @@ VaultClawback::doApply()
if (!vault)
return tefINTERNAL; // LCOV_EXCL_LINE
auto const mptIssuanceID = *((*vault)[sfShareMPTID]);
auto const mptIssuanceID = *vault->at(sfShareMPTID);
auto const sleIssuance = view().read(keylet::mptIssuance(mptIssuanceID));
if (!sleIssuance)
{
@@ -134,105 +337,47 @@ VaultClawback::doApply()
return tefINTERNAL;
// LCOV_EXCL_STOP
}
MPTIssue const share{mptIssuanceID};
Asset const vaultAsset = vault->at(sfAsset);
STAmount const amount = [&]() -> STAmount {
auto const maybeAmount = tx[~sfAmount];
if (maybeAmount)
return *maybeAmount;
return {sfAmount, vaultAsset, 0};
}();
XRPL_ASSERT(
amount.asset() == vaultAsset,
"xrpl::VaultClawback::doApply : matching asset");
STAmount const amount = clawbackAmount(vault, tx[~sfAmount], account_);
auto assetsAvailable = vault->at(sfAssetsAvailable);
auto assetsTotal = vault->at(sfAssetsTotal);
[[maybe_unused]] auto const lossUnrealized = vault->at(sfLossUnrealized);
XRPL_ASSERT(
lossUnrealized <= (assetsTotal - assetsAvailable),
"xrpl::VaultClawback::doApply : loss and assets do balance");
AccountID holder = tx[sfHolder];
MPTIssue const share{mptIssuanceID};
STAmount sharesDestroyed = {share};
STAmount assetsRecovered;
try
STAmount assetsRecovered = {vault->at(sfAsset)};
// The Owner is burning shares
if (account_ == vault->at(sfOwner) && amount.asset() == share)
{
if (amount == beast::zero)
{
sharesDestroyed = accountHolds(
view(),
holder,
share,
FreezeHandling::fhIGNORE_FREEZE,
AuthHandling::ahIGNORE_AUTH,
j_);
auto const maybeAssets =
sharesToAssetsWithdraw(vault, sleIssuance, sharesDestroyed);
if (!maybeAssets)
return tecINTERNAL; // LCOV_EXCL_LINE
assetsRecovered = *maybeAssets;
}
else
{
assetsRecovered = amount;
{
auto const maybeShares =
assetsToSharesWithdraw(vault, sleIssuance, assetsRecovered);
if (!maybeShares)
return tecINTERNAL; // LCOV_EXCL_LINE
sharesDestroyed = *maybeShares;
}
auto const maybeAssets =
sharesToAssetsWithdraw(vault, sleIssuance, sharesDestroyed);
if (!maybeAssets)
return tecINTERNAL; // LCOV_EXCL_LINE
assetsRecovered = *maybeAssets;
}
// Clamp to maximum.
if (assetsRecovered > *assetsAvailable)
{
assetsRecovered = *assetsAvailable;
// Note, it is important to truncate the number of shares, otherwise
// the corresponding assets might breach the AssetsAvailable
{
auto const maybeShares = assetsToSharesWithdraw(
vault, sleIssuance, assetsRecovered, TruncateShares::yes);
if (!maybeShares)
return tecINTERNAL; // LCOV_EXCL_LINE
sharesDestroyed = *maybeShares;
}
auto const maybeAssets =
sharesToAssetsWithdraw(vault, sleIssuance, sharesDestroyed);
if (!maybeAssets)
return tecINTERNAL; // LCOV_EXCL_LINE
assetsRecovered = *maybeAssets;
if (assetsRecovered > *assetsAvailable)
{
// LCOV_EXCL_START
JLOG(j_.error())
<< "VaultClawback: invalid rounding of shares.";
return tecINTERNAL;
// LCOV_EXCL_STOP
}
}
sharesDestroyed = accountHolds(
view(),
holder,
share,
FreezeHandling::fhIGNORE_FREEZE,
AuthHandling::ahIGNORE_AUTH,
j_);
}
catch (std::overflow_error const&)
else // The Issuer is clawbacking vault assets
{
// It's easy to hit this exception from Number with large enough Scale
// so we avoid spamming the log and only use debug here.
JLOG(j_.debug()) //
<< "VaultClawback: overflow error with"
<< " scale=" << (int)vault->at(sfScale).value() //
<< ", assetsTotal=" << vault->at(sfAssetsTotal).value()
<< ", sharesTotal=" << sleIssuance->at(sfOutstandingAmount)
<< ", amount=" << amount.value();
return tecPATH_DRY;
XRPL_ASSERT(
amount.asset() == vaultAsset,
"xrpl::VaultClawback::doApply : matching asset");
auto const clawbackParts =
assetsToClawback(vault, sleIssuance, holder, amount);
if (!clawbackParts)
return clawbackParts.error();
assetsRecovered = clawbackParts->first;
sharesDestroyed = clawbackParts->second;
}
if (sharesDestroyed == beast::zero)
@@ -282,30 +427,34 @@ VaultClawback::doApply()
// else quietly ignore, holder balance is not zero
}
// Transfer assets from vault to issuer.
if (auto const ter = accountSend(
view(),
vaultAccount,
account_,
assetsRecovered,
j_,
WaiveTransferFee::Yes);
!isTesSuccess(ter))
return ter;
// Sanity check
if (accountHolds(
view(),
vaultAccount,
assetsRecovered.asset(),
FreezeHandling::fhIGNORE_FREEZE,
AuthHandling::ahIGNORE_AUTH,
j_) < beast::zero)
if (assetsRecovered > beast::zero)
{
// LCOV_EXCL_START
JLOG(j_.error()) << "VaultClawback: negative balance of vault assets.";
return tefINTERNAL;
// LCOV_EXCL_STOP
// Transfer assets from vault to issuer.
if (auto const ter = accountSend(
view(),
vaultAccount,
account_,
assetsRecovered,
j_,
WaiveTransferFee::Yes);
!isTesSuccess(ter))
return ter;
// Sanity check
if (accountHolds(
view(),
vaultAccount,
assetsRecovered.asset(),
FreezeHandling::fhIGNORE_FREEZE,
AuthHandling::ahIGNORE_AUTH,
j_) < beast::zero)
{
// LCOV_EXCL_START
JLOG(j_.error())
<< "VaultClawback: negative balance of vault assets.";
return tefINTERNAL;
// LCOV_EXCL_STOP
}
}
return tesSUCCESS;

View File

@@ -22,6 +22,14 @@ public:
TER
doApply() override;
private:
Expected<std::pair<STAmount, STAmount>, TER>
assetsToClawback(
std::shared_ptr<SLE> const& vault,
std::shared_ptr<SLE const> const& sleShareIssuance,
AccountID const& holder,
STAmount const& clawbackAmount);
};
} // namespace xrpl