xrpld
Loading...
Searching...
No Matches
AccountDelete.cpp
1#include <xrpl/tx/transactors/account/AccountDelete.h>
2
3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/base_uint.h>
5#include <xrpl/basics/safe_cast.h>
6#include <xrpl/beast/utility/Zero.h>
7#include <xrpl/beast/utility/instrumentation.h>
8#include <xrpl/core/ServiceRegistry.h>
9#include <xrpl/ledger/ApplyView.h>
10#include <xrpl/ledger/ReadView.h>
11#include <xrpl/ledger/View.h>
12#include <xrpl/ledger/entries/DepositPreauthEntry.h>
13#include <xrpl/ledger/helpers/CredentialHelpers.h>
14#include <xrpl/ledger/helpers/DirectoryHelpers.h>
15#include <xrpl/ledger/helpers/NFTokenHelpers.h>
16#include <xrpl/ledger/helpers/OfferHelpers.h>
17#include <xrpl/protocol/AccountID.h>
18#include <xrpl/protocol/Feature.h>
19#include <xrpl/protocol/Indexes.h>
20#include <xrpl/protocol/Keylet.h>
21#include <xrpl/protocol/LedgerFormats.h>
22#include <xrpl/protocol/Protocol.h>
23#include <xrpl/protocol/SField.h>
24#include <xrpl/protocol/STLedgerEntry.h>
25#include <xrpl/protocol/STTx.h>
26#include <xrpl/protocol/TER.h>
27#include <xrpl/protocol/XRPAmount.h>
28#include <xrpl/tx/Transactor.h>
29#include <xrpl/tx/transactors/account/SignerListSet.h>
30#include <xrpl/tx/transactors/delegate/DelegateSet.h>
31#include <xrpl/tx/transactors/did/DIDDelete.h>
32#include <xrpl/tx/transactors/oracle/OracleDelete.h>
33#include <xrpl/tx/transactors/payment/DepositPreauth.h>
34
35#include <cstdint>
36#include <utility>
37
38namespace xrpl {
39bool
41{
42 return !ctx.tx.isFieldPresent(sfCredentialIDs) || ctx.rules.enabled(featureCredentials);
43}
44
47{
48 if (ctx.tx[sfAccount] == ctx.tx[sfDestination])
49 {
50 // An account cannot be deleted and give itself the resulting XRP.
51 return temDST_IS_SRC;
52 }
53
54 if (auto const err = credentials::checkFields(ctx.tx, ctx.rules, ctx.j); !isTesSuccess(err))
55 return err;
56
57 return tesSUCCESS;
58}
59
62{
63 // The fee required for AccountDelete is one owner reserve.
65}
66
67namespace {
68// Define a function pointer type that can be used to delete ledger node types.
69using DeleterFuncPtr = TER (*)(
70 ServiceRegistry& registry,
71 ApplyView& view,
72 AccountID const& account,
73 UInt256 const& delIndex,
74 SLE::Ref sleDel,
76
77// Local function definitions that provides signature compatibility.
78TER
81 ApplyView& view,
82 AccountID const& account,
83 UInt256 const& delIndex,
84 SLE::Ref sleDel,
86{
87 return offerDelete(view, sleDel, j);
88}
89
90TER
92 ServiceRegistry& registry,
93 ApplyView& view,
94 AccountID const& account,
95 UInt256 const& delIndex,
96 SLE::Ref sleDel,
98{
99 return SignerListSet::removeFromLedger(registry, view, account, j);
100}
101
102TER
103removeTicketFromLedger(
105 ApplyView& view,
106 AccountID const& account,
107 UInt256 const& delIndex,
108 SLE::Ref,
109 beast::Journal j)
110{
111 return Transactor::ticketDelete(view, account, delIndex, j);
112}
113
114TER
115removeDepositPreauthFromLedger(
117 ApplyView& view,
118 AccountID const&,
119 UInt256 const& delIndex,
120 SLE::Ref,
121 beast::Journal j)
122{
123 return DepositPreauth::removeFromLedger(view, delIndex, j);
124}
125
126TER
127removeNFTokenOfferFromLedger(
129 ApplyView& view,
130 AccountID const& account,
131 UInt256 const& delIndex,
132 SLE::Ref sleDel,
133 beast::Journal)
134{
135 if (!nft::deleteTokenOffer(view, sleDel))
136 return tefBAD_LEDGER; // LCOV_EXCL_LINE
137
138 return tesSUCCESS;
139}
140
141TER
142removeDIDFromLedger(
144 ApplyView& view,
145 AccountID const& account,
146 UInt256 const& delIndex,
147 SLE::Ref sleDel,
148 beast::Journal j)
149{
150 return DIDDelete::deleteSLE(view, sleDel, account, j);
151}
152
153TER
154removeOracleFromLedger(
156 ApplyView& view,
157 AccountID const& account,
158 UInt256 const&,
159 SLE::Ref sleDel,
160 beast::Journal j)
161{
162 return OracleDelete::deleteOracle(view, sleDel, account, j);
163}
164
165TER
166removeCredentialFromLedger(
168 ApplyView& view,
169 AccountID const&,
170 UInt256 const&,
171 SLE::Ref sleDel,
172 beast::Journal j)
173{
174 return credentials::deleteSLE(view, sleDel, j);
175}
176
177TER
178removeDelegateFromLedger(
180 ApplyView& view,
181 AccountID const&,
182 UInt256 const&,
183 SLE::Ref sleDel,
184 beast::Journal j)
185{
186 return DelegateSet::deleteDelegate(view, sleDel, j);
187}
188
189// Return nullptr if the LedgerEntryType represents an obligation that can't
190// be deleted. Otherwise return the pointer to the function that can delete
191// the non-obligation
192DeleterFuncPtr
193nonObligationDeleter(LedgerEntryType t)
194{
195 switch (t)
196 {
197 case ltOFFER:
198 return offerDelete;
199 case ltSIGNER_LIST:
201 case ltTICKET:
202 return removeTicketFromLedger;
203 case ltDEPOSIT_PREAUTH:
204 return removeDepositPreauthFromLedger;
205 case ltNFTOKEN_OFFER:
206 return removeNFTokenOfferFromLedger;
207 case ltDID:
208 return removeDIDFromLedger;
209 case ltORACLE:
210 return removeOracleFromLedger;
211 case ltCREDENTIAL:
212 return removeCredentialFromLedger;
213 case ltDELEGATE:
214 return removeDelegateFromLedger;
215 default:
216 return nullptr;
217 }
218}
219
220} // namespace
221
222TER
224{
225 AccountID const account{ctx.tx[sfAccount]};
226 AccountID const dst{ctx.tx[sfDestination]};
227
228 auto const sleDst = ctx.view.read(keylet::account(dst));
229
230 if (!sleDst)
231 return tecNO_DST;
232
233 if (sleDst->isFlag(lsfRequireDestTag) && !ctx.tx[~sfDestinationTag])
234 return tecDST_TAG_NEEDED;
235
236 // If credentials are provided - check them anyway
237 if (auto const err = credentials::valid(ctx.tx, ctx.view, account, ctx.j); !isTesSuccess(err))
238 return err;
239
240 // if credentials then postpone auth check to doApply, to check for expired
241 // credentials
242 if (!ctx.tx.isFieldPresent(sfCredentialIDs))
243 {
244 // Check whether the destination account requires deposit authorization.
245 // This also checks if destination is a pseudo-account, since pseudo-accounts have the
246 // lsfDepositAuth flag set by default
247 if (sleDst->isFlag(lsfDepositAuth))
248 {
249 if (!DepositPreauthEntryR(dst, account, ctx.view))
250 return tecNO_PERMISSION;
251 }
252 }
253
254 auto const sleAccount = ctx.view.read(keylet::account(account));
255 XRPL_ASSERT(sleAccount, "xrpl::AccountDelete::preclaim : non-null account");
256 if (!sleAccount)
257 return terNO_ACCOUNT;
258
259 // If an issuer has any issued NFTs resident in the ledger then it
260 // cannot be deleted.
261 if ((*sleAccount)[~sfMintedNFTokens] != (*sleAccount)[~sfBurnedNFTokens])
262 return tecHAS_OBLIGATIONS;
263
264 // If the account owns any NFTs it cannot be deleted.
265 Keylet const first = keylet::nftokenPageMin(account);
266 Keylet const last = keylet::nftokenPageMax(account);
267
268 auto const cp = ctx.view.read(
269 Keylet(ltNFTOKEN_PAGE, ctx.view.succ(first.key, last.key.next()).value_or(last.key)));
270 if (cp)
271 return tecHAS_OBLIGATIONS;
272
273 if (sleAccount->isFieldPresent(sfSponsor))
274 {
275 if (dst != sleAccount->getAccountID(sfSponsor))
277 }
278 if (sleAccount->isFieldPresent(sfSponsoringOwnerCount) ||
279 sleAccount->isFieldPresent(sfSponsoringAccountCount))
280 return tecHAS_OBLIGATIONS;
281
282 // We don't allow an account to be deleted if its sequence number
283 // is within 256 of the current ledger. This prevents replay of old
284 // transactions if this account is resurrected after it is deleted.
285 //
286 // We look at the account's Sequence rather than the transaction's
287 // Sequence in preparation for Tickets.
288 static constexpr std::uint32_t kSeqDelta{255};
289 if ((*sleAccount)[sfSequence] + kSeqDelta > ctx.view.seq())
290 return tecTOO_SOON;
291
292 // We don't allow an account to be deleted if
293 // <FirstNFTokenSequence + MintedNFTokens> is within 256 of the
294 // current ledger. This is to prevent having duplicate NFTokenIDs after
295 // account re-creation.
296 //
297 // Without this restriction, duplicate NFTokenIDs can be reproduced when
298 // authorized minting is involved. Because when the minter mints a NFToken,
299 // the issuer's sequence does not change. So when the issuer re-creates
300 // their account and mints a NFToken, it is possible that the
301 // NFTokenSequence of this NFToken is the same as the one that the
302 // authorized minter minted in a previous ledger.
303 if ((*sleAccount)[~sfFirstNFTokenSequence].value_or(0) +
304 (*sleAccount)[~sfMintedNFTokens].value_or(0) + kSeqDelta >
305 ctx.view.seq())
306 return tecTOO_SOON;
307
308 // Verify that the account does not own any objects that would prevent
309 // the account from being deleted.
310 Keylet const ownerDirKeylet{keylet::ownerDir(account)};
311 if (dirIsEmpty(ctx.view, ownerDirKeylet))
312 return tesSUCCESS;
313
314 SLE::const_pointer sleDirNode{};
315 unsigned int uDirEntry{0};
316 UInt256 dirEntry{beast::kZero};
317
318 // Account has no directory at all. This _should_ have been caught
319 // by the dirIsEmpty() check earlier, but it's okay to catch it here.
320 if (!cdirFirst(ctx.view, ownerDirKeylet.key, sleDirNode, uDirEntry, dirEntry))
321 return tesSUCCESS;
322
323 std::uint32_t deletableDirEntryCount{0};
324 do
325 {
326 // Make sure any directory node types that we find are the kind
327 // we can delete.
328 auto const sleItem = ctx.view.read(keylet::child(dirEntry));
329 if (!sleItem)
330 {
331 // Directory node has an invalid index. Bail out.
332 // LCOV_EXCL_START
333 JLOG(ctx.j.fatal()) << "AccountDelete: directory node in ledger " << ctx.view.seq()
334 << " has index to object that is missing: " << to_string(dirEntry);
335 return tefBAD_LEDGER;
336 // LCOV_EXCL_STOP
337 }
338
339 LedgerEntryType const nodeType{safeCast<LedgerEntryType>((*sleItem)[sfLedgerEntryType])};
340
341 if (nonObligationDeleter(nodeType) == nullptr)
342 return tecHAS_OBLIGATIONS;
343
344 // We found a deletable directory entry. Count it. If we find too
345 // many deletable directory entries then bail out.
346 if (++deletableDirEntryCount > kMaxDeletableDirEntries)
347 return tefTOO_BIG;
348
349 } while (cdirNext(ctx.view, ownerDirKeylet.key, sleDirNode, uDirEntry, dirEntry));
350
351 return tesSUCCESS;
352}
353
354TER
356{
357 auto const src = view().peek(keylet::account(accountID_));
358 XRPL_ASSERT(src, "xrpl::AccountDelete::doApply : non-null source account");
359
360 auto const dstID = ctx_.tx[sfDestination];
361 auto const dst = view().peek(keylet::account(dstID));
362 XRPL_ASSERT(dst, "xrpl::AccountDelete::doApply : non-null destination account");
363
364 if (!src || !dst)
365 return tefBAD_LEDGER; // LCOV_EXCL_LINE
366
367 if (ctx_.tx.isFieldPresent(sfCredentialIDs))
368 {
369 if (auto err =
370 verifyDepositPreauth(ctx_.tx, ctx_.view(), accountID_, dstID, dst, ctx_.journal);
371 !isTesSuccess(err))
372 return err;
373 }
374
375 Keylet const ownerDirKeylet{keylet::ownerDir(accountID_)};
376 auto const ter = cleanupOnAccountDelete(
377 view(),
378 ownerDirKeylet,
379 [&](LedgerEntryType nodeType,
380 UInt256 const& dirEntry,
382 if (auto deleter = nonObligationDeleter(nodeType))
383 {
384 TER const result{deleter(ctx_.registry, view(), accountID_, dirEntry, sleItem, j_)};
385
386 return {result, SkipEntry::No};
387 }
388
389 // LCOV_EXCL_START
390 UNREACHABLE(
391 "xrpl::AccountDelete::doApply : undeletable item not found "
392 "in preclaim");
393 JLOG(j_.error()) << "AccountDelete undeletable item not "
394 "found in preclaim.";
396 // LCOV_EXCL_STOP
397 },
398 ctx_.journal);
399 if (!isTesSuccess(ter))
400 return ter;
401
402 // Transfer any XRP remaining after the fee is paid to the destination:
403 auto const remainingBalance = src->getFieldAmount(sfBalance).xrp();
404 (*dst)[sfBalance] = (*dst)[sfBalance] + remainingBalance;
405 (*src)[sfBalance] = (*src)[sfBalance] - remainingBalance;
406 ctx_.deliver(remainingBalance);
407
408 if (src->isFieldPresent(sfSponsor))
409 {
410 auto const sponsorID = src->getAccountID(sfSponsor);
411 auto const sponsorSle = view().peek(keylet::account(sponsorID));
412
413 if (!sponsorSle)
414 return tefINTERNAL; // LCOV_EXCL_LINE
415
416 auto const sponsoringAccountCount = sponsorSle->getFieldU32(sfSponsoringAccountCount);
417
418 XRPL_ASSERT(
419 sponsoringAccountCount != 0,
420 "xrpl::AccountDelete::doApply : sponsoring account count is present");
421 if (sponsoringAccountCount == 0)
422 {
423 // sanity check
424 // Since sfSponsoringAccountCount is set to soeDEFAULT, the field will not be
425 // present with a value of 0.
426 return tefINTERNAL; // LCOV_EXCL_LINE
427 }
428 sponsorSle->at(sfSponsoringAccountCount) = sponsoringAccountCount - 1;
429 view().update(sponsorSle);
430
431 // Following line might look redundant, but without it, sfSponsor
432 // would end up remaining in after-ltAccountRoot during the
433 // InvariantCheck.
434 src->makeFieldAbsent(sfSponsor);
435 }
436
437 XRPL_ASSERT(
438 (*src)[sfBalance] == XRPAmount(0), "xrpl::AccountDelete::doApply : source balance is zero");
439
440 // If there's still an owner directory associated with the source account
441 // delete it.
442 if (view().exists(ownerDirKeylet) && !view().emptyDirDelete(ownerDirKeylet))
443 {
444 JLOG(j_.error()) << "AccountDelete cannot delete root dir node of " << toBase58(accountID_);
445 return tecHAS_OBLIGATIONS;
446 }
447
448 // Re-arm the password change fee if we can and need to.
449 if (remainingBalance > XRPAmount(0) && dst->isFlag(lsfPasswordSpent))
450 dst->clearFlag(lsfPasswordSpent);
451
452 view().update(dst);
453 view().erase(src);
454
455 return tesSUCCESS;
456}
457
458void
460{
461 // No transaction-specific invariants yet (future work).
462}
463
464bool
466 STTx const&,
467 TER,
468 XRPAmount,
469 ReadView const&,
470 beast::Journal const&)
471{
472 // No transaction-specific invariants yet (future work).
473 return true;
474}
475
476} // namespace xrpl
A generic endpoint for log messages.
Definition Journal.h:44
Stream fatal() const
Definition Journal.h:368
bool finalizeInvariants(STTx const &tx, TER result, XRPAmount fee, ReadView const &view, beast::Journal const &j) override
Check transaction-specific post-conditions after all entries have been visited.
static XRPAmount calculateBaseFee(ReadView const &view, STTx const &tx)
TER doApply() override
static NotTEC preflight(PreflightContext const &ctx)
static bool checkExtraFeatures(PreflightContext const &ctx)
static TER preclaim(PreclaimContext const &ctx)
void visitInvariantEntry(bool isDelete, SLE::ConstRef before, SLE::ConstRef after) override
Inspect a single ledger entry modified by this transaction.
Writeable view to a ledger, for applying a transaction.
Definition ApplyView.h:141
virtual SLE::pointer peek(Keylet const &k)=0
Prepare to modify the SLE associated with key.
virtual void erase(SLE::Ref sle)=0
Remove a peeked SLE.
virtual void update(SLE::Ref sle)=0
Indicate changes to a peeked SLE.
BaseUInt next() const
Definition base_uint.h:478
static TER deleteSLE(ApplyContext &ctx, Keylet sleKeylet, AccountID const owner)
Definition DIDDelete.cpp:28
static TER deleteDelegate(ApplyView &view, SLE::Ref sle, beast::Journal j)
static TER removeFromLedger(ApplyView &view, UInt256 const &delIndex, beast::Journal j)
static TER deleteOracle(ApplyView &view, SLE::Ref sle, AccountID const &account, beast::Journal j)
A view into a ledger.
Definition ReadView.h:41
virtual SLE::const_pointer read(Keylet const &k) const =0
Return the state item associated with a key.
LedgerIndex seq() const
Returns the sequence number of the base ledger.
Definition ReadView.h:115
virtual std::optional< key_type > succ(key_type const &key, std::optional< key_type > const &last=std::nullopt) const =0
Return the key of the next state item.
bool enabled(UInt256 const &feature) const
Returns true if a feature is enabled.
Definition Rules.cpp:182
std::shared_ptr< STLedgerEntry > pointer
std::shared_ptr< STLedgerEntry const > const & ConstRef
std::shared_ptr< STLedgerEntry > const & Ref
std::shared_ptr< STLedgerEntry const > const_pointer
bool isFieldPresent(SField const &field) const
Definition STObject.cpp:464
Service registry for dependency injection.
static TER removeFromLedger(ServiceRegistry &registry, ApplyView &view, AccountID const &account, beast::Journal j)
static XRPAmount calculateOwnerReserveFee(ReadView const &view, STTx const &tx)
beast::Journal const j_
Definition Transactor.h:164
ApplyView & view()
Definition Transactor.h:184
AccountID const accountID_
Definition Transactor.h:166
ApplyContext & ctx_
Definition Transactor.h:162
static TER ticketDelete(ApplyView &view, AccountID const &account, UInt256 const &ticketIndex, beast::Journal j)
This method removes one Ticket ledger-object from the ledger.
constexpr Zero kZero
Definition Zero.h:30
NotTEC checkFields(STTx const &tx, Rules const &rules, beast::Journal j)
TER deleteSLE(ApplyView &view, SLE::Ref sleCredential, beast::Journal j)
TER valid(STTx const &tx, ReadView const &view, AccountID const &src, beast::Journal j)
Keylet ownerDir(AccountID const &id) noexcept
The root page of an account's directory.
Definition Indexes.cpp:415
Keylet nftokenPageMin(AccountID const &owner)
NFT page keylets.
Definition Indexes.cpp:442
Keylet nftokenPageMax(AccountID const &owner)
A keylet for the owner's last possible NFT page.
Definition Indexes.cpp:450
Keylet account(AccountID const &id) noexcept
AccountID root.
Definition Indexes.cpp:233
Keylet child(UInt256 const &key) noexcept
Any item that can be in an owner dir.
Definition Indexes.cpp:239
bool deleteTokenOffer(ApplyView &view, SLE::Ref offer)
Deletes the given token offer.
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
bool cdirFirst(ReadView const &view, UInt256 const &root, SLE::const_pointer &page, unsigned int &index, UInt256 &entry)
Returns the first entry in the directory, advancing the index.
@ terNO_ACCOUNT
Definition TER.h:219
TER offerDelete(ApplyView &view, SLE::Ref sle, beast::Journal j)
Delete an offer.
bool dirIsEmpty(ReadView const &view, Keylet const &k)
Returns true if the directory is empty.
@ tefTOO_BIG
Definition TER.h:178
@ tefBAD_LEDGER
Definition TER.h:164
@ tefINTERNAL
Definition TER.h:167
std::string toBase58(AccountID const &v)
Convert AccountID to base58 checked string.
Definition AccountID.cpp:95
constexpr Dest safeCast(Src s) noexcept
Definition safe_cast.h:21
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
BaseUInt< 256 > UInt256
Definition base_uint.h:581
TERSubset< CanCvtToNotTEC > NotTEC
Definition TER.h:617
DepositPreauthEntry< ReadView > DepositPreauthEntryR
bool cdirNext(ReadView const &view, UInt256 const &root, SLE::const_pointer &page, unsigned int &index, UInt256 &entry)
Returns the next entry in the directory, advancing the index.
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
@ temDST_IS_SRC
Definition TER.h:96
bool isTesSuccess(TER x) noexcept
Definition TER.h:686
TERSubset< CanCvtToTER > TER
Definition TER.h:657
LedgerEntryType
Identifiers for on-ledger objects.
@ tecNO_SPONSOR_PERMISSION
Definition TER.h:380
@ tecTOO_SOON
Definition TER.h:329
@ tecNO_PERMISSION
Definition TER.h:316
@ tecDST_TAG_NEEDED
Definition TER.h:320
@ tecHAS_OBLIGATIONS
Definition TER.h:328
@ tecNO_DST
Definition TER.h:301
TER verifyDepositPreauth(STTx const &tx, ApplyView &view, AccountID const &src, AccountID const &dst, SLE::ConstRef sleDst, beast::Journal j)
static TER removeSignersFromLedger(ServiceRegistry &registry, ApplyView &view, Keylet const &accountKeylet, Keylet const &ownerDirKeylet, Keylet const &signerListKeylet, beast::Journal j)
@ tesSUCCESS
Definition TER.h:253
constexpr std::size_t kMaxDeletableDirEntries
The maximum number of owner directory entries for account to be deletable.
Definition Protocol.h:75
TER cleanupOnAccountDelete(ApplyView &view, Keylet const &ownerDirKeylet, EntryDeleter const &deleter, beast::Journal j, std::optional< std::uint16_t > maxNodesToDelete=std::nullopt)
Cleanup owner directory entries on account delete.
A pair of SHAMap key and LedgerEntryType.
Definition Keylet.h:20
UInt256 key
Definition Keylet.h:21
State information when determining if a tx is likely to claim a fee.
Definition Transactor.h:92
ReadView const & view
Definition Transactor.h:95
beast::Journal const j
Definition Transactor.h:100
State information when preflighting a tx.
Definition Transactor.h:39
beast::Journal const j
Definition Transactor.h:46