xrpld
Loading...
Searching...
No Matches
EscrowCreate.cpp
1#include <xrpl/tx/transactors/escrow/EscrowCreate.h>
2
3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/chrono.h>
5#include <xrpl/beast/utility/Zero.h>
6#include <xrpl/conditions/Condition.h>
7#include <xrpl/ledger/ApplyView.h>
8#include <xrpl/ledger/ReadView.h>
9#include <xrpl/ledger/View.h>
10#include <xrpl/ledger/entries/EscrowEntry.h>
11#include <xrpl/ledger/helpers/AccountRootHelpers.h>
12#include <xrpl/ledger/helpers/DirectoryHelpers.h>
13#include <xrpl/ledger/helpers/EscrowHelpers.h>
14#include <xrpl/ledger/helpers/SponsorHelpers.h>
15#include <xrpl/ledger/helpers/TokenHelpers.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/Issue.h>
22#include <xrpl/protocol/Keylet.h>
23#include <xrpl/protocol/LedgerFormats.h>
24#include <xrpl/protocol/MPTAmount.h>
25#include <xrpl/protocol/MPTIssue.h>
26#include <xrpl/protocol/Protocol.h>
27#include <xrpl/protocol/Rate.h>
28#include <xrpl/protocol/SField.h>
29#include <xrpl/protocol/STAmount.h>
30#include <xrpl/protocol/STLedgerEntry.h>
31#include <xrpl/protocol/STTx.h>
32#include <xrpl/protocol/TER.h>
33#include <xrpl/protocol/UintTypes.h>
34#include <xrpl/protocol/XRPAmount.h>
35#include <xrpl/tx/Transactor.h>
36#include <xrpl/tx/applySteps.h>
37
38#include <memory>
39#include <system_error>
40#include <variant>
41
42namespace xrpl {
43
44/*
45 Escrow
46 ======
47
48 Escrow is a feature of the XRP Ledger that allows you to send conditional
49 XRP payments. These conditional payments, called escrows, set aside XRP and
50 deliver it later when certain conditions are met. Conditions to successfully
51 finish an escrow include time-based unlocks and crypto-conditions. Escrows
52 can also be set to expire if not finished in time.
53
54 The XRP set aside in an escrow is locked up. No one can use or destroy the
55 XRP until the escrow has been successfully finished or canceled. Before the
56 expiration time, only the intended receiver can get the XRP. After the
57 expiration time, the XRP can only be returned to the sender.
58
59 For more details on escrow, including examples, diagrams and more please
60 visit https://xrpl.org/escrow.html
61
62 For details on specific transactions, including fields and validation rules
63 please see:
64
65 `EscrowCreate`
66 --------------
67 See: https://xrpl.org/escrowcreate.html
68
69 `EscrowFinish`
70 --------------
71 See: https://xrpl.org/escrowfinish.html
72
73 `EscrowCancel`
74 --------------
75 See: https://xrpl.org/escrowcancel.html
76*/
77
78//------------------------------------------------------------------------------
79
82{
83 auto const amount = ctx.tx[sfAmount];
84 return TxConsequences{ctx.tx, isXRP(amount) ? amount.xrp() : beast::kZero};
85}
86
87bool
89{
90 // Only require featureMPTokensV1 when the escrow amount is an MPT and
91 // fixCleanup3_2_0 is active; XRP/IOU escrows are unaffected by this gate.
92 if (ctx.rules.enabled(fixCleanup3_2_0) && ctx.tx[sfAmount].holds<MPTIssue>())
93 {
94 if (!ctx.rules.enabled(featureMPTokensV1))
95 return false;
96 }
97
98 return (!ctx.tx.isFieldPresent(sfBytecode) && !ctx.tx.isFieldPresent(sfData)) ||
99 ctx.rules.enabled(featureSmartEscrow);
100}
101
102template <ValidIssueType T>
103static NotTEC
105
106template <>
109{
110 STAmount const amount = ctx.tx[sfAmount];
111 if (amount.native() || amount <= beast::kZero)
112 return temBAD_AMOUNT;
113
114 if (badCurrency() == amount.get<Issue>().currency)
115 return temBAD_CURRENCY;
116
117 return tesSUCCESS;
118}
119
120template <>
123{
124 if (!ctx.rules.enabled(fixCleanup3_2_0) && !ctx.rules.enabled(featureMPTokensV1))
125 return temDISABLED;
126
127 auto const amount = ctx.tx[sfAmount];
128 if (amount.native() || amount.mpt() > MPTAmount{kMaxMpTokenAmount} || amount <= beast::kZero)
129 return temBAD_AMOUNT;
130
131 return tesSUCCESS;
132}
133
134XRPAmount
136{
138 if (tx.isFieldPresent(sfBytecode))
139 {
140 // Ten base fees in all: `Transactor::calculateBaseFee` charges one,
141 // this adds nine. Plus 5 drops per byte.
142 txnFees += 9 * view.fees().base + 5 * tx[sfBytecode].size();
143 }
144 return txnFees;
145}
146
147NotTEC
149{
150 STAmount const amount{ctx.tx[sfAmount]};
151 if (!isXRP(amount))
152 {
153 if (!ctx.rules.enabled(featureTokenEscrow))
154 return temBAD_AMOUNT;
155
156 if (auto const ret = std::visit(
157 [&]<typename T>(T const&) { return escrowCreatePreflightHelper<T>(ctx); },
158 amount.asset().value());
159 !isTesSuccess(ret))
160 return ret;
161 }
162 else
163 {
164 if (amount <= beast::kZero)
165 return temBAD_AMOUNT;
166 }
167
168 // We must specify at least one timeout value
169 if (!ctx.tx[~sfCancelAfter] && !ctx.tx[~sfFinishAfter])
170 return temBAD_EXPIRATION;
171
172 // If both finish and cancel times are specified then the cancel time must
173 // be strictly after the finish time.
174 if (ctx.tx[~sfCancelAfter] && ctx.tx[~sfFinishAfter] &&
175 ctx.tx[sfCancelAfter] <= ctx.tx[sfFinishAfter])
176 return temBAD_EXPIRATION;
177
178 if (ctx.tx.isFieldPresent(sfBytecode) && !ctx.tx.isFieldPresent(sfCancelAfter))
179 return temBAD_EXPIRATION;
180
181 // In the absence of a FinishAfter, the escrow can be finished
182 // immediately, which can be confusing. When creating an escrow,
183 // we want to ensure that either a FinishAfter time is explicitly
184 // specified or a completion condition is attached.
185 if (!ctx.tx[~sfFinishAfter] && !ctx.tx[~sfCondition] && !ctx.tx[~sfBytecode])
186 {
187 JLOG(ctx.j.debug()) << "Must have at least one of FinishAfter, "
188 "Condition, or Bytecode.";
189 return temMALFORMED;
190 }
191
192 if (auto const cb = ctx.tx[~sfCondition])
193 {
194 using namespace xrpl::cryptoconditions;
195
197
198 auto const condition = Condition::deserialize(*cb, ec);
199 if (!condition)
200 {
201 JLOG(ctx.j.debug()) << "Malformed condition during escrow creation: " << ec.message();
202 return temMALFORMED;
203 }
204 }
205
206 if (ctx.tx.isFieldPresent(sfData))
207 {
208 if (!ctx.tx.isFieldPresent(sfBytecode))
209 {
210 JLOG(ctx.j.debug()) << "EscrowCreate with Data requires Bytecode";
211 return temMALFORMED;
212 }
213 auto const data = ctx.tx.getFieldVL(sfData);
214 if (data.size() > kMaxWasmDataLength)
215 {
216 JLOG(ctx.j.debug()) << "EscrowCreate.Data bad size " << data.size();
217 return temMALFORMED;
218 }
219 }
220
221 // amendment was checked by checkExtraFeatures
222 if (ctx.tx.isFieldPresent(sfBytecode))
223 {
224 auto const code = ctx.tx.getFieldVL(sfBytecode);
225 // Protocol ceiling only; `preflight` has no view.
226 if (code.empty() || code.size() > kMaxBytecodeSizeLimit)
227 {
228 JLOG(ctx.j.debug()) << "EscrowCreate.Bytecode bad size " << code.size();
229 return temMALFORMED;
230 }
231 }
232
233 return tesSUCCESS;
234}
235
236TER
238{
239 STAmount const amount{ctx.tx[sfAmount]};
240 AccountID const account{ctx.tx[sfAccount]};
241 AccountID const dest{ctx.tx[sfDestination]};
242
243 auto const sled = ctx.view.read(keylet::account(dest));
244 if (!sled)
245 return tecNO_DST;
246
247 // Pseudo-accounts cannot receive escrow. Note, this is not amendment-gated
248 // because all writes to pseudo-account discriminator fields **are**
249 // amendment gated, hence the behaviour of this check will always match the
250 // currently active amendments.
251 if (isPseudoAccount(sled))
252 return tecNO_PERMISSION;
253
254 if (!isXRP(amount))
255 {
256 if (!ctx.view.rules().enabled(featureTokenEscrow))
257 return temDISABLED; // LCOV_EXCL_LINE
258
259 if (auto const ret = std::visit(
260 [&]<typename T>(T const&) {
261 return escrowLockPreclaimHelper<T>(ctx.view, account, dest, amount, ctx.j);
262 },
263 amount.asset().value());
264 !isTesSuccess(ret))
265 return ret;
266 }
267
268 // The limits are voted, so they can change between ledgers. A `tef`, unlike
269 // a `tem`, does not mark the transaction bad for the hold time.
270 if (ctx.tx.isFieldPresent(sfBytecode))
271 {
272 auto const& fees = ctx.view.fees();
273 if (isBytecodeUploadDisabled(fees))
274 {
275 JLOG(ctx.j.debug()) << "WASM runtime deactivated by fee voting";
276 return tefTEMP_DISABLED;
277 }
278
279 auto const code = ctx.tx.getFieldVL(sfBytecode);
280 if (code.size() > fees.bytecodeSizeLimit)
281 {
282 JLOG(ctx.j.debug()) << "EscrowCreate.Bytecode over voted limit " << code.size();
283 return tefEXCEEDS_LIMIT;
284 }
285
286 // TODO(SmartEscrow): screen the module itself here - that it compiles,
287 // and that it imports and exports what the engine can serve - once the
288 // WASM engine lands. Until then any blob of the right size is taken.
289 }
290
291 return tesSUCCESS;
292}
293
294TER
296{
297 auto const closeTime = ctx_.view().header().parentCloseTime;
298
299 if (ctx_.tx[~sfCancelAfter] && after(closeTime, ctx_.tx[sfCancelAfter]))
300 return tecNO_PERMISSION;
301
302 if (ctx_.tx[~sfFinishAfter] && after(closeTime, ctx_.tx[sfFinishAfter]))
303 return tecNO_PERMISSION;
304
305 auto const sle = ctx_.view().peek(keylet::account(accountID_));
306 if (!sle)
307 return tefINTERNAL; // LCOV_EXCL_LINE
308
309 // Check reserve and funds availability
310 STAmount const amount{ctx_.tx[sfAmount]};
311 auto const reserveToAdd = calculateAdditionalReserve(ctx_.tx[~sfBytecode]);
312
313 auto const balance = sle->getFieldAmount(sfBalance).xrp();
314 // First check: whoever is on the hook for the new owner increment
315 // can cover it. When sponsored this hits the sponsor branch and
316 // validates the sponsor's reserve + remaining credit. When
317 // unsponsored this hits the source branch and validates the
318 // source's pre-lock balance against base + (currentOC+1)*increment.
319 if (auto const ret = checkReserve(
320 ctx_.getApplyViewContext(), sle, balance, {.ownerCountDelta = reserveToAdd}, j_);
321 !isTesSuccess(ret))
322 return ret;
323
324 if (isXRP(amount))
325 {
326 // Second check (XRP escrow only): after locking the escrowed
327 // amount, the source must still meet its own reserve floor. This is
328 // always the source's own balance against the source's own reserve —
329 // the sponsor's reserve was already validated above, and a sponsor
330 // never covers the locked funds. We compare directly (rather than via
331 // checkReserve) because that helper diverts to the sponsor's balance
332 // when a sponsor is present and would ignore the source's post-lock
333 // balance entirely. ownerCountDelta differs by case:
334 // - sponsored: 0 — sponsor covers the new owner increment, so
335 // the source only owes reserve for its current owners.
336 // - unsponsored: reserveToAdd — source owes reserve including the new
337 // increment, which Bytecode can make larger than one unit.
338 auto const sourceReserve = accountReserve(
339 ctx_.view(),
340 sle,
341 j_,
342 {.ownerCountDelta = getTxReserveSponsorID(ctx_.tx) ? 0 : reserveToAdd});
343 if (balance - STAmount(amount).xrp() < sourceReserve)
344 return tecUNFUNDED;
345 }
346
347 // Check destination account
348 {
349 auto const sled = ctx_.view().read(keylet::account(ctx_.tx[sfDestination]));
350 if (!sled)
351 return tecNO_DST; // LCOV_EXCL_LINE
352 if (sled->isFlag(lsfRequireDestTag) && !ctx_.tx[~sfDestinationTag])
353 return tecDST_TAG_NEEDED;
354 }
355
356 // Create escrow in ledger. Note that we use the value from the
357 // sequence or ticket. For more explanation see comments in SeqProxy.h.
358 EscrowEntryW escrow(accountID_, ctx_.tx.getSeqProxy(), ctx_.view(), j_);
359 Keylet const escrowKeylet = escrow.keylet();
360 escrow.newSLE();
361 (*escrow)[sfAmount] = amount;
362 (*escrow)[sfAccount] = accountID_;
363 (*escrow)[~sfCondition] = ctx_.tx[~sfCondition];
364 (*escrow)[~sfSourceTag] = ctx_.tx[~sfSourceTag];
365 (*escrow)[sfDestination] = ctx_.tx[sfDestination];
366 (*escrow)[~sfCancelAfter] = ctx_.tx[~sfCancelAfter];
367 (*escrow)[~sfFinishAfter] = ctx_.tx[~sfFinishAfter];
368 (*escrow)[~sfDestinationTag] = ctx_.tx[~sfDestinationTag];
369 (*escrow)[~sfBytecode] = ctx_.tx[~sfBytecode];
370 (*escrow)[~sfData] = ctx_.tx[~sfData];
371
372 if (ctx_.view().rules().enabled(fixIncludeKeyletFields))
373 {
374 (*escrow)[sfSequence] = ctx_.tx.getSeqProxy().value();
375 }
376
377 if (ctx_.view().rules().enabled(featureTokenEscrow) && !isXRP(amount))
378 {
379 auto const xferRate = transferRate(ctx_.view(), amount);
380 if (xferRate != kParityRate)
381 (*escrow)[sfTransferRate] = xferRate.value;
382 }
383
384 escrow.insert();
385
386 // Add escrow to sender's owner directory
387 {
388 auto page = ctx_.view().dirInsert(
390 if (!page)
391 return tecDIR_FULL; // LCOV_EXCL_LINE
392 (*escrow)[sfOwnerNode] = *page;
393 }
394
395 // If it's not a self-send, add escrow to recipient's owner directory.
396 AccountID const dest = ctx_.tx[sfDestination];
397 if (dest != accountID_)
398 {
399 auto page =
400 ctx_.view().dirInsert(keylet::ownerDir(dest), escrowKeylet, describeOwnerDir(dest));
401 if (!page)
402 return tecDIR_FULL; // LCOV_EXCL_LINE
403 (*escrow)[sfDestinationNode] = *page;
404 }
405
406 // IOU escrow objects are added to the issuer's owner directory to help
407 // track the total locked balance. For MPT, this isn't necessary because the
408 // locked balance is already stored directly in the MPTokenIssuance object.
409 AccountID const issuer = amount.getIssuer();
410 if (!isXRP(amount) && issuer != accountID_ && issuer != dest && !amount.holds<MPTIssue>())
411 {
412 auto page =
413 ctx_.view().dirInsert(keylet::ownerDir(issuer), escrowKeylet, describeOwnerDir(issuer));
414 if (!page)
415 return tecDIR_FULL; // LCOV_EXCL_LINE
416 (*escrow)[sfIssuerNode] = *page;
417 }
418
419 // Deduct owner's balance
420 if (isXRP(amount))
421 {
422 (*sle)[sfBalance] = (*sle)[sfBalance] - amount;
423 }
424 else
425 {
426 if (auto const ret = std::visit(
427 [&]<typename T>(T const&) {
428 return escrowLockApplyHelper<T>(ctx_.view(), issuer, accountID_, amount, j_);
429 },
430 amount.asset().value());
431 !isTesSuccess(ret))
432 {
433 return ret; // LCOV_EXCL_LINE
434 }
435 }
436
437 // increment owner count
438 increaseOwnerCount(ctx_.getApplyViewContext(), sle, reserveToAdd, ctx_.journal);
439 addSponsorToLedgerEntry(ctx_.getApplyViewContext(), escrow.mutableRawSle());
440 ctx_.view().update(sle);
441 return tesSUCCESS;
442}
443
444void
446{
447 // No transaction-specific invariants yet (future work).
448}
449
450bool
452 STTx const&,
453 TER,
454 XRPAmount,
455 ReadView const&,
456 beast::Journal const&)
457{
458 // No transaction-specific invariants yet (future work).
459 return true;
460}
461} // namespace xrpl
A generic endpoint for log messages.
Definition Journal.h:44
Stream debug() const
Definition Journal.h:344
static bool checkExtraFeatures(PreflightContext const &ctx)
static NotTEC preflight(PreflightContext const &ctx)
static XRPAmount calculateBaseFee(ReadView const &view, STTx const &tx)
void visitInvariantEntry(bool isDelete, SLE::ConstRef before, SLE::ConstRef after) override
Inspect a single ledger entry modified by this transaction.
TER doApply() override
static TER preclaim(PreclaimContext 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 TxConsequences makeTxConsequences(PreflightContext const &ctx)
A currency issued by an account.
Definition Issue.h:18
Currency currency
Definition Issue.h:20
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.
virtual SLE::const_pointer read(Keylet const &k) const =0
Return the state item associated with a key.
bool enabled(UInt256 const &feature) const
Returns true if a feature is enabled.
Definition Rules.cpp:182
constexpr bool holds() const noexcept
Definition STAmount.h:478
constexpr TIss const & get() const
bool native() const noexcept
Definition STAmount.h:471
Asset const & asset() const
Definition STAmount.h:496
AccountID const & getIssuer() const
Definition STAmount.h:516
std::shared_ptr< STLedgerEntry const > const & ConstRef
Blob getFieldVL(SField const &field) const
Definition STObject.cpp:649
bool isFieldPresent(SField const &field) const
Definition STObject.cpp:464
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
ApplyContext & ctx_
Definition Transactor.h:162
Class describing the consequences to the account of applying a transaction if the transaction consume...
Definition applySteps.h:53
static std::unique_ptr< Condition > deserialize(Slice s, std::error_code &ec)
Load a condition from its binary form.
T message(T... args)
constexpr Zero kZero
Definition Zero.h:30
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
bool isXRP(AccountID const &c)
Definition AccountID.h:84
int32_t calculateAdditionalReserve(T const &finishFunction)
Owner count an escrow costs.
NotTEC escrowCreatePreflightHelper< Issue >(PreflightContext const &ctx)
constexpr std::size_t kMaxWasmDataLength
Maximum length of a Data field in Escrow object that can be updated by WASM code.
Definition Protocol.h:404
@ tefTEMP_DISABLED
Definition TER.h:186
@ tefEXCEEDS_LIMIT
Definition TER.h:187
@ tefINTERNAL
Definition TER.h:167
TER escrowLockApplyHelper(ApplyView &view, AccountID const &issuer, AccountID const &sender, STAmount const &amount, beast::Journal journal)
TER checkReserve(ApplyViewContext ctx, SLE::ConstRef accSle, XRPAmount accBalance, SLE::ConstRef sponsorSle, Adjustment adj, beast::Journal j, TER insufReserveCode=tecINSUFFICIENT_RESERVE)
Check if an account has sufficient reserve.
void increaseOwnerCount(ApplyView &view, SLE::Ref accountSle, SLE::Ref sponsorSle, std::uint32_t count, beast::Journal j)
Increase owner-count fields when the caller supplies the sponsor.
void addSponsorToLedgerEntry(SLE::Ref sle, SLE::ConstRef sponsorSle, SF_ACCOUNT const &field=sfSponsor)
Stamp a reserve sponsor onto a ledger entry using an explicit sponsor SLE.
TERSubset< CanCvtToNotTEC > NotTEC
Definition TER.h:617
Rate transferRate(ReadView const &view, AccountID const &issuer)
Returns IOU issuer transfer fee as Rate.
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
bool isPseudoAccount(SLE::const_pointer sleAcct)
Returns true if and only if sleAcct is a pseudo-account of any kind (i.e.
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
static NotTEC escrowCreatePreflightHelper(PreflightContext const &ctx)
TER escrowLockPreclaimHelper(ReadView const &view, AccountID const &account, AccountID const &dest, STAmount const &amount, beast::Journal j)
Validate that account may lock amount of a token for later delivery to dest.
@ temBAD_CURRENCY
Definition TER.h:78
@ temBAD_EXPIRATION
Definition TER.h:79
@ temMALFORMED
Definition TER.h:75
@ temDISABLED
Definition TER.h:102
@ temBAD_AMOUNT
Definition TER.h:77
bool isTesSuccess(TER x) noexcept
Definition TER.h:686
TERSubset< CanCvtToTER > TER
Definition TER.h:657
XRPAmount accountReserve(ReadView const &view, SLE::ConstRef sle, beast::Journal j, Adjustment adj={})
Returns the account reserve, in drops.
@ tecDIR_FULL
Definition TER.h:298
@ tecNO_PERMISSION
Definition TER.h:316
@ tecDST_TAG_NEEDED
Definition TER.h:320
@ tecNO_DST
Definition TER.h:301
@ tecUNFUNDED
Definition TER.h:306
NotTEC escrowCreatePreflightHelper< MPTIssue >(PreflightContext const &ctx)
constexpr std::uint32_t kMaxBytecodeSizeLimit
bool isBytecodeUploadDisabled(Fees const &fees)
Smart escrow kill switches, driven by the voted FeeSettings.
Currency const & badCurrency()
We deliberately disallow the currency that looks like "XRP" because too many people were using it ins...
std::function< void(SLE::Ref)> describeOwnerDir(AccountID const &account)
Returns a function that sets the owner on a directory SLE.
@ tesSUCCESS
Definition TER.h:253
A pair of SHAMap key and LedgerEntryType.
Definition Keylet.h:20
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
T visit(T... args)