/
Remit.cpp
632 lines (524 loc) · 20.7 KB
/
Remit.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
//------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012, 2013 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#include <ripple/app/tx/impl/Remit.h>
#include <ripple/app/tx/impl/URIToken.h>
#include <ripple/basics/Log.h>
#include <ripple/ledger/View.h>
#include <ripple/protocol/Feature.h>
#include <ripple/protocol/Indexes.h>
#include <ripple/protocol/TxFlags.h>
#include <ripple/protocol/st.h>
namespace ripple {
TxConsequences
Remit::makeTxConsequences(PreflightContext const& ctx)
{
XRPAmount native = ([&ctx]() -> XRPAmount {
if (!ctx.tx.isFieldPresent(sfAmounts))
return beast::zero;
STArray const& sEntries(ctx.tx.getFieldArray(sfAmounts));
for (STObject const& sEntry : sEntries)
{
if (!sEntry.isFieldPresent(sfAmount))
continue;
STAmount const amount = sEntry.getFieldAmount(sfAmount);
if (isXRP(amount))
return amount.xrp();
}
return beast::zero;
})();
return TxConsequences{ctx.tx, native};
}
NotTEC
Remit::preflight(PreflightContext const& ctx)
{
if (auto const ret = preflight1(ctx); !isTesSuccess(ret))
return ret;
if (ctx.tx.getFlags() & tfUniversalMask)
{
// There are no flags (other than universal).
JLOG(ctx.j.warn()) << "Malformed transaction: Invalid flags set.";
return temINVALID_FLAG;
}
AccountID const dstID = ctx.tx.getAccountID(sfDestination);
AccountID const srcID = ctx.tx.getAccountID(sfAccount);
if (dstID == srcID)
{
JLOG(ctx.j.warn()) << "Malformed transaction: Remit to self.";
return temREDUNDANT;
}
if (ctx.tx.isFieldPresent(sfInform))
{
AccountID const infID = ctx.tx.getAccountID(sfInform);
if (infID == dstID || srcID == infID)
{
JLOG(ctx.j.warn()) << "Malformed transaction: sfInform is same as "
"source or destination.";
return temMALFORMED;
}
}
if (ctx.tx.isFieldPresent(sfBlob) &&
ctx.tx.getFieldVL(sfBlob).size() > (128 * 1024))
{
JLOG(ctx.j.warn()) << "Blob was more than 128kib "
<< ctx.tx.getTransactionID();
return temMALFORMED;
}
// sanity check amounts
if (ctx.tx.isFieldPresent(sfAmounts))
{
if (ctx.tx.getFieldArray(sfAmounts).size() > 32)
{
JLOG(ctx.j.warn()) << "Malformed: AmountEntry count exceeds `32`.";
return temMALFORMED;
}
std::map<Currency, std::set<AccountID>> already;
bool nativeAlready = false;
STArray const& sEntries(ctx.tx.getFieldArray(sfAmounts));
for (STObject const& sEntry : sEntries)
{
// Validate the AmountEntry.
if (sEntry.getFName() != sfAmountEntry)
{
JLOG(ctx.j.warn()) << "Malformed: Expected AmountEntry.";
return temMALFORMED;
}
STAmount const amount = sEntry.getFieldAmount(sfAmount);
if (!isLegalNet(amount) || amount.signum() <= 0)
{
JLOG(ctx.j.warn()) << "Malformed transaction: bad amount: "
<< amount.getFullText();
return temBAD_AMOUNT;
}
if (isBadCurrency(amount.getCurrency()))
{
JLOG(ctx.j.warn()) << "Malformed transaction: Bad currency.";
return temBAD_CURRENCY;
}
if (isXRP(amount))
{
if (nativeAlready)
{
JLOG(ctx.j.warn()) << "Malformed transaction: Native "
"Currency appears more than once.";
return temMALFORMED;
}
nativeAlready = true;
continue;
}
auto found = already.find(amount.getCurrency());
if (found == already.end())
{
already.emplace(
amount.getCurrency(),
std::set<AccountID>{amount.getIssuer()});
continue;
}
if (found->second.find(amount.getIssuer()) != found->second.end())
{
JLOG(ctx.j.warn()) << "Malformed transaction: Issued Currency "
"appears more than once.";
return temMALFORMED;
}
found->second.emplace(amount.getIssuer());
}
}
// sanity check minturitoken
if (ctx.tx.isFieldPresent(sfMintURIToken))
{
STObject const& mint = const_cast<ripple::STTx&>(ctx.tx)
.getField(sfMintURIToken)
.downcast<STObject>();
for (auto const& mintElement : mint)
{
auto const& name = mintElement.getFName();
if (name != sfURI && name != sfFlags && name != sfDigest)
{
JLOG(ctx.j.trace()) << "Malformed transaction: sfMintURIToken "
"contains invalid field.";
return temMALFORMED;
}
}
if (!mint.isFieldPresent(sfURI))
{
JLOG(ctx.j.warn())
<< "Malformed transaction: URI was not provided.";
return temMALFORMED;
}
Blob const uri = mint.getFieldVL(sfURI);
if (uri.size() < 1 || uri.size() > 256)
{
JLOG(ctx.j.warn())
<< "Malformed transaction: URI was too short/long.";
return temMALFORMED;
}
if (!URIToken::validateUTF8(uri))
{
JLOG(ctx.j.warn())
<< "Malformed transaction: Invalid UTF8 inside MintURIToken.";
return temMALFORMED;
}
if (mint.isFieldPresent(sfFlags))
{
if (mint.getFieldU32(sfFlags) & tfURITokenMintMask)
return temINVALID_FLAG;
}
}
// sanity check uritokenids
if (ctx.tx.isFieldPresent(sfURITokenIDs))
{
STVector256 ids = ctx.tx.getFieldV256(sfURITokenIDs);
if (ids.size() < 1 || ids.size() > 32)
{
JLOG(ctx.j.warn()) << "Malformed transaction: URITokenIDs Invalid.";
return temMALFORMED;
}
std::sort(ids.begin(), ids.end());
if (std::adjacent_find(ids.begin(), ids.end()) != ids.end())
{
JLOG(ctx.j.warn())
<< "Malformed transaction: Duplicate URITokenID.";
return temMALFORMED;
}
}
return preflight2(ctx);
}
TER
Remit::doApply()
{
Sandbox sb(&ctx_.view());
if (!sb.rules().enabled(featureRemit))
return temDISABLED;
beast::Journal const& j = ctx_.journal;
auto const srcAccID = ctx_.tx[sfAccount];
auto sleSrcAcc = sb.peek(keylet::account(srcAccID));
if (!sleSrcAcc)
return terNO_ACCOUNT;
if (ctx_.tx.isFieldPresent(sfInform))
{
auto const informAcc = ctx_.tx.getAccountID(sfInform);
if (!sb.exists(keylet::account(informAcc)))
{
JLOG(j.warn()) << "Remit: sfInform account does not exist.";
return tecNO_TARGET;
}
}
XRPAmount const accountReserve{sb.fees().accountReserve(0)};
XRPAmount const objectReserve{sb.fees().accountReserve(1) - accountReserve};
// sanity check
if (accountReserve < beast::zero || objectReserve < beast::zero ||
objectReserve > sb.fees().accountReserve(1))
{
JLOG(j.warn())
<< "Remit: account or object reserve calculation not sane.";
return tecINTERNAL;
}
// amount of native tokens we will transfer to cover reserves for the
// tls/acc/uritokens created, and native tokens listed in amounts
XRPAmount nativeRemit{0};
AccountID const dstAccID{ctx_.tx[sfDestination]};
auto sleDstAcc = sb.peek(keylet::account(dstAccID));
auto const flags = !sleDstAcc ? 0 : sleDstAcc->getFlags();
// Check if the destination has disallowed incoming
if (sb.rules().enabled(featureDisallowIncoming) &&
(flags & lsfDisallowIncomingRemit))
return tecNO_PERMISSION;
// Check if the destination account requires deposit authorization.
bool const depositAuth{sb.rules().enabled(featureDepositAuth)};
if (depositAuth && sleDstAcc && (flags & lsfDepositAuth))
{
if (!sb.exists(keylet::depositPreauth(dstAccID, srcAccID)))
return tecNO_PERMISSION;
}
// the destination may require a dest tag
if ((flags & lsfRequireDestTag) &&
!ctx_.tx.isFieldPresent(sfDestinationTag))
{
JLOG(j.warn())
<< "Remit: DestinationTag required for this destination.";
return tecDST_TAG_NEEDED;
}
// if the destination doesn't exist, create it.
bool const createDst = !sleDstAcc;
if (createDst)
{
// sender will pay the reserve
if (nativeRemit + accountReserve < nativeRemit)
return tecINTERNAL;
nativeRemit += accountReserve;
// Create the account.
std::uint32_t const seqno{
sb.rules().enabled(featureXahauGenesis)
? sb.info().parentCloseTime.time_since_epoch().count()
: sb.rules().enabled(featureDeletableAccounts) ? sb.seq() : 1};
sleDstAcc = std::make_shared<SLE>(keylet::account(dstAccID));
sleDstAcc->setAccountID(sfAccount, dstAccID);
sleDstAcc->setFieldU32(sfSequence, seqno);
sleDstAcc->setFieldU32(sfOwnerCount, 0);
if (sb.exists(keylet::fees()) &&
sb.rules().enabled(featureXahauGenesis))
{
auto sleFees = sb.peek(keylet::fees());
uint64_t accIdx = sleFees->isFieldPresent(sfAccountCount)
? sleFees->getFieldU64(sfAccountCount)
: 0;
sleDstAcc->setFieldU64(sfAccountIndex, accIdx);
sleFees->setFieldU64(sfAccountCount, accIdx + 1);
sb.update(sleFees);
}
// we'll fix this up at the end
sleDstAcc->setFieldAmount(sfBalance, STAmount{XRPAmount{0}});
sb.insert(sleDstAcc);
}
// if theres a minted uritoken the sender pays for that
if (ctx_.tx.isFieldPresent(sfMintURIToken))
{
if (nativeRemit + objectReserve < nativeRemit)
return tecINTERNAL;
nativeRemit += objectReserve;
STObject const& mint = const_cast<ripple::STTx&>(ctx_.tx)
.getField(sfMintURIToken)
.downcast<STObject>();
Blob const& mintURI = mint.getFieldVL(sfURI);
std::optional<uint256> mintDigest;
if (mint.isFieldPresent(sfDigest))
mintDigest = mint.getFieldH256(sfDigest);
Keylet kl = keylet::uritoken(srcAccID, mintURI);
// check that it doesn't already exist
if (sb.exists(kl))
{
JLOG(j.trace()) << "Remit: tried to creat duplicate URIToken. Tx: "
<< ctx_.tx.getTransactionID();
return tecDUPLICATE;
}
auto sleMint = std::make_shared<SLE>(kl);
sleMint->setAccountID(sfOwner, dstAccID);
sleMint->setAccountID(sfIssuer, srcAccID);
sleMint->setFieldVL(sfURI, mintURI);
if (mint.isFieldPresent(sfDigest))
sleMint->setFieldH256(sfDigest, mint.getFieldH256(sfDigest));
sleMint->setFieldU32(
sfFlags,
mint.isFieldPresent(sfFlags) ? mint.getFieldU32(sfFlags) : 0);
auto const page = sb.dirInsert(
keylet::ownerDir(dstAccID), kl, describeOwnerDir(dstAccID));
JLOG(j_.trace()) << "Adding URIToken to owner directory "
<< to_string(kl.key) << ": "
<< (page ? "success" : "failure");
if (!page)
return tecDIR_FULL;
sleMint->setFieldU64(sfOwnerNode, *page);
sb.insert(sleMint);
// ensure there is a deletion blocker against the issuer now
sleSrcAcc->setFieldU32(
sfFlags, sleSrcAcc->getFlags() | lsfURITokenIssuer);
adjustOwnerCount(sb, sleDstAcc, 1, j);
}
// iterate uritokens
if (ctx_.tx.isFieldPresent(sfURITokenIDs))
{
STVector256 ids = ctx_.tx.getFieldV256(sfURITokenIDs);
for (uint256 const klRaw : ids)
{
Keylet kl = keylet::unchecked(klRaw);
auto sleU = sb.peek(kl);
// does it exist
if (!sleU)
{
JLOG(j.warn()) << "Remit: one or more uritokens did not exist "
"on the source account.";
return tecNO_ENTRY;
}
// is it a uritoken?
if (sleU->getFieldU16(sfLedgerEntryType) != ltURI_TOKEN)
{
JLOG(j.warn()) << "Remit: one or more supplied URITokenIDs was "
"not actually a uritoken.";
return tecNO_ENTRY;
}
// is it our uritoken?
if (sleU->getAccountID(sfOwner) != srcAccID)
{
JLOG(j.warn()) << "Remit: one or more supplied URITokenIDs was "
"not owned by sender.";
return tecNO_PERMISSION;
}
// erase current sale offers, if any
if (sleU->isFieldPresent(sfAmount))
sleU->makeFieldAbsent(sfAmount);
if (sleU->isFieldPresent(sfDestination))
sleU->makeFieldAbsent(sfDestination);
// pay the reserve
if (nativeRemit + objectReserve < nativeRemit)
return tecINTERNAL;
nativeRemit += objectReserve;
// remove from sender dir
{
auto const page = (*sleU)[sfOwnerNode];
if (!sb.dirRemove(
keylet::ownerDir(srcAccID), page, kl.key, true))
{
JLOG(j.fatal())
<< "Could not remove URIToken from owner directory";
return tefBAD_LEDGER;
}
adjustOwnerCount(sb, sleSrcAcc, -1, j);
}
// add to dest dir
{
auto const page = sb.dirInsert(
keylet::ownerDir(dstAccID), kl, describeOwnerDir(dstAccID));
JLOG(j_.trace()) << "Adding URIToken to owner directory "
<< to_string(kl.key) << ": "
<< (page ? "success" : "failure");
if (!page)
return tecDIR_FULL;
sleU->setFieldU64(sfOwnerNode, *page);
adjustOwnerCount(sb, sleDstAcc, 1, j);
}
// change the owner
sleU->setAccountID(sfOwner, dstAccID);
sb.update(sleU);
}
}
// iterate trustlines
if (ctx_.tx.isFieldPresent(sfAmounts))
{
// process trustline remits
STArray const& sEntries(ctx_.tx.getFieldArray(sfAmounts));
for (STObject const& sEntry : sEntries)
{
STAmount const amount = sEntry.getFieldAmount(sfAmount);
if (isXRP(amount))
{
// since we have to pay for all the created objects including
// possibly the account itself this is paid right at the end,
// and only if there is balance enough to cover.
// check for overflow
if (nativeRemit + amount.xrp() < nativeRemit)
return tecINTERNAL;
nativeRemit += amount.xrp();
continue;
}
AccountID const issuerAccID = amount.getIssuer();
// check permissions
if (issuerAccID == srcAccID || issuerAccID == dstAccID)
{
// no permission check needed when the issuer sends out or a
// subscriber sends back RH TODO: move this condition into
// trustTransferAllowed, guarded by an amendment
}
else if (TER canXfer = trustTransferAllowed(
sb,
std::vector<AccountID>{srcAccID, dstAccID},
amount.issue(),
j);
!isTesSuccess(canXfer))
return canXfer;
// compute the amount the source will need to send
// in remit the sender pays all transfer fees, so that
// the destination can always be assured they got the exact amount
// specified. therefore we need to compute the amount + transfer fee
auto const srcAmt =
issuerAccID != srcAccID && issuerAccID != dstAccID
? multiply(amount, transferRate(sb, issuerAccID))
: amount;
// sanity check this calculation
if (srcAmt < amount || srcAmt > amount + amount)
{
JLOG(j.warn()) << "Remit: srcAmt calculation not sane.";
return tecINTERNAL;
}
STAmount availableFunds{
accountFunds(sb, srcAccID, srcAmt, fhZERO_IF_FROZEN, j)};
if (availableFunds < srcAmt)
return tecUNFUNDED_PAYMENT;
// if the target trustline doesn't exist we need to create it and
// pay its reserve
if (!sb.exists(
keylet::line(dstAccID, issuerAccID, amount.getCurrency())))
{
if (nativeRemit + objectReserve < nativeRemit)
return tecINTERNAL;
nativeRemit += objectReserve;
}
// action the transfer
if (TER result =
accountSend(sb, srcAccID, dstAccID, amount, j, true);
!isTesSuccess(result))
return result;
}
}
if (nativeRemit < beast::zero)
return tecINTERNAL;
if (nativeRemit > beast::zero)
{
// ensure the account can cover the native remit
if (mSourceBalance < nativeRemit)
return tecUNFUNDED_PAYMENT;
// subtract the balance from the sender
{
STAmount bal = mSourceBalance;
bal -= nativeRemit;
if (bal < beast::zero || bal > mSourceBalance)
return tecINTERNAL;
sleSrcAcc->setFieldAmount(sfBalance, bal);
}
// add the balance to the destination
{
STAmount bal = sleDstAcc->getFieldAmount(sfBalance);
STAmount prior = bal;
bal += nativeRemit;
if (bal < beast::zero || bal < prior)
return tecINTERNAL;
sleDstAcc->setFieldAmount(sfBalance, bal);
}
}
auto hasSufficientReserve = [&](std::shared_ptr<SLE> const& sle) -> bool {
std::uint32_t const uOwnerCount = sle->getFieldU32(sfOwnerCount);
return sle->getFieldAmount(sfBalance) >=
sb.fees().accountReserve(uOwnerCount);
};
// sanity check reserves
if (!hasSufficientReserve(sleSrcAcc))
{
JLOG(j.warn()) << "Remit: sender " << srcAccID
<< " lacks reserves to cover send.";
return tecINSUFFICIENT_RESERVE;
}
// this isn't actually an error but we will print a warning
// this can occur if the destination was already below reserve level at the
// time assets were sent
if (!hasSufficientReserve(sleDstAcc))
{
JLOG(j.warn()) << "Remit: destination has insufficient reserves.";
}
// apply
sb.update(sleSrcAcc);
sb.update(sleDstAcc);
sb.apply(ctx_.rawView());
return tesSUCCESS;
}
XRPAmount
Remit::calculateBaseFee(ReadView const& view, STTx const& tx)
{
XRPAmount extraFee{0};
if (tx.isFieldPresent(sfBlob))
extraFee +=
XRPAmount{static_cast<XRPAmount>(tx.getFieldVL(sfBlob).size())};
return Transactor::calculateBaseFee(view, tx) + extraFee;
}
} // namespace ripple