xrpld
Loading...
Searching...
No Matches
EscrowFinish.cpp
1#include <xrpl/tx/transactors/escrow/EscrowFinish.h>
2
3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/Slice.h>
5#include <xrpl/basics/chrono.h>
6#include <xrpl/conditions/Condition.h>
7#include <xrpl/conditions/Fulfillment.h>
8#include <xrpl/core/HashRouter.h>
9#include <xrpl/ledger/ApplyView.h>
10#include <xrpl/ledger/ReadView.h>
11#include <xrpl/ledger/View.h>
12#include <xrpl/ledger/entries/EscrowEntry.h>
13#include <xrpl/ledger/helpers/AccountRootHelpers.h>
14#include <xrpl/ledger/helpers/CredentialHelpers.h>
15#include <xrpl/ledger/helpers/EscrowHelpers.h>
16#include <xrpl/protocol/AccountID.h>
17#include <xrpl/protocol/Concepts.h>
18#include <xrpl/protocol/Feature.h>
19#include <xrpl/protocol/Fees.h>
20#include <xrpl/protocol/Indexes.h>
21#include <xrpl/protocol/Rate.h>
22#include <xrpl/protocol/SField.h>
23#include <xrpl/protocol/STAmount.h>
24#include <xrpl/protocol/STLedgerEntry.h>
25#include <xrpl/protocol/STTx.h>
26#include <xrpl/protocol/SeqProxy.h>
27#include <xrpl/protocol/TER.h>
28#include <xrpl/protocol/XRPAmount.h>
29#include <xrpl/tx/Transactor.h>
30
31#include <cstdint>
32#include <optional>
33#include <system_error>
34#include <variant>
35
36namespace xrpl {
37
38// During an EscrowFinish, the transaction must specify both
39// a condition and a fulfillment. We track whether that
40// fulfillment matches and validates the condition.
43
44//------------------------------------------------------------------------------
45
46static bool
48{
49 using namespace xrpl::cryptoconditions;
50
52
53 auto const condition = Condition::deserialize(c, ec);
54 if (!condition)
55 return false;
56
57 auto const fulfillment = Fulfillment::deserialize(f, ec);
58 if (!fulfillment)
59 return false;
60
61 return validate(*fulfillment, *condition);
62}
63
64bool
66{
67 if (ctx.tx.isFieldPresent(sfCredentialIDs) && !ctx.rules.enabled(featureCredentials))
68 return false;
69
70 if (ctx.tx.isFieldPresent(sfGas) && !ctx.rules.enabled(featureSmartEscrow))
71 return false;
72
73 return true;
74}
75
78{
79 auto const cb = ctx.tx[~sfCondition];
80 auto const fb = ctx.tx[~sfFulfillment];
81
82 // If you specify a condition, then you must also specify
83 // a fulfillment.
84 if (static_cast<bool>(cb) != static_cast<bool>(fb))
85 {
86 JLOG(ctx.j.debug()) << "Condition != Fulfillment";
87 return temMALFORMED;
88 }
89
90 if (auto const allowance = ctx.tx[~sfGas]; allowance)
91 {
92 // Protocol ceiling only; `preflight` has no view.
93 if (*allowance == 0)
94 {
95 return temBAD_LIMIT;
96 }
97 if (*allowance > kMaxGasLimit)
98 {
99 JLOG(ctx.j.debug()) << "Gas too large: " << *allowance;
100 return temBAD_LIMIT;
101 }
102 }
103
104 return tesSUCCESS;
105}
106
107NotTEC
109{
110 auto const cb = ctx.tx[~sfCondition];
111 auto const fb = ctx.tx[~sfFulfillment];
112
113 if (cb && fb)
114 {
115 auto& router = ctx.registry.get().getHashRouter();
116
117 auto const id = ctx.tx.getTransactionID();
118 auto flags = router.getFlags(id);
119
120 // If we haven't checked the condition, check it
121 // now. Other than a malformed condition, whether
122 // it passes or not isn't important in preflight.
123 if (!any(flags & (kSfCfInvalid | kSfCfValid)))
124 {
125 if (checkCondition(*fb, *cb))
126 {
127 router.setFlags(id, kSfCfValid);
128 flags = kSfCfValid;
129 }
130 else
131 {
132 router.setFlags(id, kSfCfInvalid);
133 flags = kSfCfInvalid;
134 }
135 }
136
137 // The invalid flag also covers a bad fulfillment, so
138 // check the condition itself. This runs whether or not
139 // the flag was cached, so the result is the same on
140 // every node.
141 if (any(flags & kSfCfInvalid) && ctx.rules.enabled(fixCleanup3_5_0))
142 {
143 using namespace xrpl::cryptoconditions;
144
146
147 auto const condition = Condition::deserialize(*cb, ec);
148 if (!condition)
149 {
150 JLOG(ctx.j.debug()) << "Malformed condition during escrow finish: " << ec.message();
151 return temMALFORMED;
152 }
153 }
154 }
155
156 if (auto const err = credentials::checkFields(ctx.tx, ctx.rules, ctx.j); !isTesSuccess(err))
157 return err;
158
159 return tesSUCCESS;
160}
161
164{
165 XRPAmount extraFee{0};
166
167 if (auto const fb = tx[~sfFulfillment])
168 {
169 extraFee += view.fees().base * (32 + (fb->size() / 16));
170 }
171 if (auto const allowance = tx[~sfGas]; allowance)
172 {
173 // The extra fee is the allowance in drops, rounded up to the nearest
174 // whole drop. Widen before multiplying: both factors are 32-bit.
175 std::uint64_t const allowanceFee =
176 ((std::uint64_t{*allowance} * view.fees().gasPrice) + microDropsPerDrop - 1) /
178 extraFee += allowanceFee;
179 }
180 return Transactor::calculateBaseFee(view, tx) + extraFee;
181}
182
183TER
185{
186 if (ctx.view.rules().enabled(featureCredentials))
187 {
188 if (auto const err = credentials::valid(ctx.tx, ctx.view, ctx.tx[sfAccount], ctx.j);
189 !isTesSuccess(err))
190 return err;
191 }
192
193 if (ctx.view.rules().enabled(featureTokenEscrow) ||
194 ctx.view.rules().enabled(featureSmartEscrow))
195 {
196 // this check is done in doApply before this amendment is enabled
197 auto const seqProxy = SeqProxy::rawSequence(ctx.tx[sfOfferSequence]);
198 EscrowEntryR const escrow(ctx.tx[sfOwner], seqProxy, ctx.view);
199 if (!escrow)
200 return tecNO_TARGET;
201
202 if (ctx.view.rules().enabled(featureSmartEscrow))
203 {
204 if (escrow->isFieldPresent(sfBytecode))
205 {
206 if (!ctx.tx.isFieldPresent(sfGas))
207 {
208 JLOG(ctx.j.debug()) << "Bytecode requires Gas";
210 }
211
212 // The limits are voted, so they can change between ledgers.
213 // A `tef`, unlike a `tem`, does not mark the transaction bad
214 // for the hold time.
215 auto const& fees = ctx.view.fees();
217 {
218 JLOG(ctx.j.debug()) << "WASM runtime deactivated by fee voting";
219 return tefTEMP_DISABLED;
220 }
221
222 if (ctx.tx[sfGas] > fees.gasLimit)
223 {
224 JLOG(ctx.j.debug()) << "Gas over voted limit: " << ctx.tx[sfGas];
225 return tefEXCEEDS_LIMIT;
226 }
227 }
228 else
229 {
230 if (ctx.tx.isFieldPresent(sfGas))
231 {
232 JLOG(ctx.j.debug()) << "Bytecode not present, "
233 "Gas present";
234 return tefNO_BYTECODE;
235 }
236 }
237 }
238 if (ctx.view.rules().enabled(featureTokenEscrow))
239 {
240 AccountID const dest = (*escrow)[sfDestination];
241 STAmount const amount = (*escrow)[sfAmount];
242
243 if (!isXRP(amount))
244 {
245 if (auto const ret = std::visit(
246 [&]<typename T>(T const&) {
247 return escrowUnlockPreclaimHelper<T>(ctx.view, dest, amount);
248 },
249 amount.asset().value());
250 !isTesSuccess(ret))
251 return ret;
252 }
253 }
254 }
255 return tesSUCCESS;
256}
257
258TER
260{
261 auto const seqProxy = SeqProxy::rawSequence(ctx_.tx[sfOfferSequence]);
262 EscrowEntryW escrow(ctx_.tx[sfOwner], seqProxy, ctx_.view(), j_);
263 if (!escrow)
264 {
265 if (ctx_.view().rules().enabled(featureTokenEscrow) ||
266 ctx_.view().rules().enabled(featureSmartEscrow))
267 return tecINTERNAL; // LCOV_EXCL_LINE
268
269 return tecNO_TARGET;
270 }
271
272 // If a cancel time is present, a finish operation should only succeed prior
273 // to that time.
274 auto const now = ctx_.view().header().parentCloseTime;
275
276 // Too soon: can't execute before the finish time
277 if ((*escrow)[~sfFinishAfter] && !after(now, (*escrow)[sfFinishAfter]))
278 return tecNO_PERMISSION;
279
280 // Too late: can't execute after the cancel time
281 if ((*escrow)[~sfCancelAfter] && after(now, (*escrow)[sfCancelAfter]))
282 return tecNO_PERMISSION;
283
284 AccountID const destID = (*escrow)[sfDestination];
285 auto const sled = ctx_.view().peek(keylet::account(destID));
286 if (ctx_.view().rules().enabled(featureSmartEscrow))
287 {
288 // NOTE: Escrow payments cannot be used to fund accounts.
289 if (!sled)
290 return tecNO_DST;
291
292 if (auto err =
293 verifyDepositPreauth(ctx_.tx, ctx_.view(), accountID_, destID, sled, ctx_.journal);
294 !isTesSuccess(err))
295 return err;
296 }
297
298 // Check cryptocondition fulfillment
299 {
300 auto const id = ctx_.tx.getTransactionID();
301 auto flags = ctx_.registry.get().getHashRouter().getFlags(id);
302
303 auto const cb = ctx_.tx[~sfCondition];
304
305 // It's unlikely that the results of the check will
306 // expire from the hash router, but if it happens,
307 // simply re-run the check.
308 if (cb && !any(flags & (kSfCfInvalid | kSfCfValid)))
309 {
310 // LCOV_EXCL_START
311 auto const fb = ctx_.tx[~sfFulfillment];
312
313 if (!fb)
314 return tecINTERNAL;
315
316 if (checkCondition(*fb, *cb))
317 {
318 flags = kSfCfValid;
319 }
320 else
321 {
322 flags = kSfCfInvalid;
323 }
324
325 ctx_.registry.get().getHashRouter().setFlags(id, flags);
326 // LCOV_EXCL_STOP
327 }
328
329 // If the check failed, then simply return an error
330 // and don't look at anything else.
331 if (any(flags & kSfCfInvalid))
333
334 // Check against condition in the ledger entry:
335 auto const cond = (*escrow)[~sfCondition];
336
337 // If a condition wasn't specified during creation,
338 // one shouldn't be included now.
339 if (!cond && cb)
341
342 // If a condition was specified during creation of
343 // the suspended payment, the identical condition
344 // must be presented again. We don't check if the
345 // fulfillment matches the condition since we did
346 // that in preflight.
347 if (cond && (cond != cb))
349 }
350
351 if (!ctx_.view().rules().enabled(featureSmartEscrow))
352 {
353 // NOTE: Escrow payments cannot be used to fund accounts.
354 if (!sled)
355 return tecNO_DST;
356
357 if (auto err =
358 verifyDepositPreauth(ctx_.tx, ctx_.view(), accountID_, destID, sled, ctx_.journal);
359 !isTesSuccess(err))
360 return err;
361 }
362
363 // Execute custom release function
364 if ((*escrow)[~sfBytecode])
365 {
366 // TODO(SmartEscrow): run the escrow's contract here once the WASM
367 // engine lands. That change also brings with it the reporting the run
368 // produces - the gas it consumed and the code it returned, in the
369 // transaction metadata - and the tecBYTECODE_REJECTED result that lets
370 // a rejected escrow survive with the data the contract wrote.
371 //
372 // Until then an escrow carrying bytecode can be created, funded and
373 // cancelled, but not finished. Reachable only under featureSmartEscrow,
374 // which is Supported::No.
375 JLOG(j_.debug()) << "EscrowFinish: no WASM engine to run the escrow's bytecode";
377 }
378
379 AccountID const account = (*escrow)[sfAccount];
380
381 // Remove escrow from owner directory
382 {
383 auto const page = (*escrow)[sfOwnerNode];
384 if (!ctx_.view().dirRemove(keylet::ownerDir(account), page, escrow.key(), true))
385 {
386 // LCOV_EXCL_START
387 JLOG(j_.fatal()) << "Unable to delete Escrow from owner.";
388 return tefBAD_LEDGER;
389 // LCOV_EXCL_STOP
390 }
391 }
392
393 // Remove escrow from recipient's owner directory, if present.
394 if (auto const optPage = (*escrow)[~sfDestinationNode])
395 {
396 if (!ctx_.view().dirRemove(keylet::ownerDir(destID), *optPage, escrow.key(), true))
397 {
398 // LCOV_EXCL_START
399 JLOG(j_.fatal()) << "Unable to delete Escrow from recipient.";
400 return tefBAD_LEDGER;
401 // LCOV_EXCL_STOP
402 }
403 }
404
405 auto const reserveToSubtract = calculateAdditionalReserve((*escrow)[~sfBytecode]);
406
407 // Delivery can auto-create the destination's holding; the removed escrow
408 // must not be counted against its reserve. The two share a reserve payer
409 // for a self-escrow, or when one sponsor covers both.
410 bool const recycleReserve =
411 ctx_.view().rules().enabled(featureSponsor) || ctx_.view().rules().enabled(fixCleanup3_4_0);
412 if (recycleReserve)
413 {
415 ctx_.view(), account, escrow.mutableRawSle(), reserveToSubtract, ctx_.journal);
416 }
417
418 STAmount const amount = escrow->getFieldAmount(sfAmount);
419 // Transfer amount to destination
420 if (isXRP(amount))
421 {
422 (*sled)[sfBalance] = (*sled)[sfBalance] + amount;
423 }
424 else
425 {
426 if (!ctx_.view().rules().enabled(featureTokenEscrow))
427 return temDISABLED; // LCOV_EXCL_LINE
428
429 Rate lockedRate = escrow->isFieldPresent(sfTransferRate)
430 ? xrpl::Rate(escrow->getFieldU32(sfTransferRate))
431 : kParityRate;
432 auto const issuer = amount.getIssuer();
433 bool const createAsset = destID == accountID_;
434 if (auto const ret = std::visit(
435 [&]<typename T>(T const&) {
437 ctx_.getApplyViewContext(),
438 lockedRate,
439 sled,
441 amount,
442 issuer,
443 account,
444 destID,
445 createAsset,
446 j_);
447 },
448 amount.asset().value());
449 !isTesSuccess(ret))
450 return ret;
451
452 // Remove escrow from issuers owner directory, if present.
453 if (auto const optPage = (*escrow)[~sfIssuerNode]; optPage)
454 {
455 if (!ctx_.view().dirRemove(keylet::ownerDir(issuer), *optPage, escrow.key(), true))
456 {
457 // LCOV_EXCL_START
458 JLOG(j_.fatal()) << "Unable to delete Escrow from recipient.";
459 return tefBAD_LEDGER;
460 // LCOV_EXCL_STOP
461 }
462 }
463 }
464
465 ctx_.view().update(sled);
466
467 if (!recycleReserve)
468 {
470 ctx_.view(), account, escrow.mutableRawSle(), reserveToSubtract, ctx_.journal);
471 }
472
473 // Remove escrow from ledger
474 escrow.erase();
475 return tesSUCCESS;
476}
477
478void
480{
481 // No transaction-specific invariants yet (future work).
482}
483
484bool
486 STTx const&,
487 TER,
488 XRPAmount,
489 ReadView const&,
490 beast::Journal const&)
491{
492 // No transaction-specific invariants yet (future work).
493 return true;
494}
495} // namespace xrpl
A generic endpoint for log messages.
Definition Journal.h:44
Stream debug() const
Definition Journal.h:344
static XRPAmount calculateBaseFee(ReadView const &view, STTx const &tx)
static bool checkExtraFeatures(PreflightContext const &ctx)
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 TER preclaim(PreclaimContext const &ctx)
TER doApply() override
void visitInvariantEntry(bool isDelete, SLE::ConstRef before, SLE::ConstRef after) override
Inspect a single ledger entry modified by this transaction.
static NotTEC preflight(PreflightContext const &ctx)
static NotTEC preflightSigValidated(PreflightContext const &ctx)
A view into a ledger.
Definition ReadView.h:41
virtual Rules const & rules() const =0
Returns the tx processing rules.
virtual Fees const & fees() const =0
Returns the fees for the base ledger.
bool enabled(UInt256 const &feature) const
Returns true if a feature is enabled.
Definition Rules.cpp:182
Asset const & asset() const
Definition STAmount.h:496
AccountID const & getIssuer() const
Definition STAmount.h:516
std::shared_ptr< STLedgerEntry const > const & ConstRef
bool isFieldPresent(SField const &field) const
Definition STObject.cpp:464
UInt256 getTransactionID() const
Definition STTx.h:262
static constexpr SeqProxy rawSequence(std::uint32_t v)
Factory function to return a sequence-based SeqProxy.
Definition SeqProxy.h:62
An immutable linear range of bytes.
Definition Slice.h:28
beast::Journal const j_
Definition Transactor.h:164
ApplyView & view()
Definition Transactor.h:184
static XRPAmount calculateBaseFee(ReadView const &view, STTx const &tx)
AccountID const accountID_
Definition Transactor.h:166
XRPAmount preFeeBalance_
Definition Transactor.h:167
ApplyContext & ctx_
Definition Transactor.h:162
static std::unique_ptr< Condition > deserialize(Slice s, std::error_code &ec)
Load a condition from its binary form.
T message(T... args)
NotTEC checkFields(STTx const &tx, Rules const &rules, beast::Journal j)
TER valid(STTx const &tx, ReadView const &view, AccountID const &src, beast::Journal j)
bool validate(Fulfillment const &f, Condition const &c, Slice m)
Verify if the given message satisfies the fulfillment.
Keylet ownerDir(AccountID const &id) noexcept
The root page of an account's directory.
Definition Indexes.cpp:415
Keylet account(AccountID const &id) noexcept
AccountID root.
Definition Indexes.cpp:233
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
constexpr std::uint32_t microDropsPerDrop
bool isXRP(AccountID const &c)
Definition AccountID.h:84
int32_t calculateAdditionalReserve(T const &finishFunction)
Owner count an escrow costs.
@ tefTEMP_DISABLED
Definition TER.h:186
@ tefBAD_LEDGER
Definition TER.h:164
@ tefEXCEEDS_LIMIT
Definition TER.h:187
@ tefNO_BYTECODE
Definition TER.h:184
@ tefBYTECODE_NOT_INCLUDED
Definition TER.h:185
TER escrowUnlockApplyHelper(ApplyViewContext ctx, Rate lockedRate, SLE::Ref sleDest, XRPAmount xrpBalance, STAmount const &amount, AccountID const &issuer, AccountID const &sender, AccountID const &receiver, bool createAsset, beast::Journal journal)
bool isBytecodeExecutionDisabled(Fees const &fees)
constexpr HashRouterFlags kSfCfInvalid
EscrowEntry< ReadView > EscrowEntryR
Definition EscrowEntry.h:34
constexpr HashRouterFlags kSfCfValid
TERSubset< CanCvtToNotTEC > NotTEC
Definition TER.h:617
void decreaseOwnerCountForObject(ApplyView &view, SLE::Ref accountSle, SLE::Ref objectSle, std::uint32_t count, beast::Journal j)
Decrease owner-count fields for an existing ledger object.
TER escrowUnlockPreclaimHelper(ReadView const &view, AccountID const &account, STAmount const &amount, bool checkFreeze=true)
bool after(NetClock::time_point now, std::uint32_t mark)
Has the specified time passed?
Definition View.cpp:668
Rate const kParityRate
A transfer rate signifying a 1:1 exchange.
EscrowEntry< ApplyView > EscrowEntryW
Definition EscrowEntry.h:35
HashRouterFlags
Definition HashRouter.h:20
static bool checkCondition(Slice f, Slice c)
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
@ temBAD_LIMIT
Definition TER.h:82
@ temMALFORMED
Definition TER.h:75
@ temDISABLED
Definition TER.h:102
bool isTesSuccess(TER x) noexcept
Definition TER.h:686
TERSubset< CanCvtToTER > TER
Definition TER.h:657
@ tecNO_TARGET
Definition TER.h:315
@ tecINTERNAL
Definition TER.h:321
@ tecFAILED_PROCESSING
Definition TER.h:297
@ tecCRYPTOCONDITION_ERROR
Definition TER.h:323
@ tecNO_PERMISSION
Definition TER.h:316
@ tecNO_DST
Definition TER.h:301
constexpr std::uint32_t kMaxGasLimit
Hard protocol bounds on the Feature Extension fee settings.
TER verifyDepositPreauth(STTx const &tx, ApplyView &view, AccountID const &src, AccountID const &dst, SLE::ConstRef sleDst, beast::Journal j)
@ tesSUCCESS
Definition TER.h:253
constexpr bool any(HashRouterFlags flags)
Definition HashRouter.h:81
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
std::reference_wrapper< ServiceRegistry > registry
Definition Transactor.h:41
Represents a transfer rate.
Definition Rate.h:21
static std::unique_ptr< Fulfillment > deserialize(Slice s, std::error_code &ec)
Load a fulfillment from its binary form.
T visit(T... args)