20 #include <ripple/app/ledger/OpenLedger.h>
21 #include <ripple/app/main/Application.h>
22 #include <ripple/app/misc/LoadFeeTrack.h>
23 #include <ripple/app/misc/TxQ.h>
24 #include <ripple/app/tx/apply.h>
25 #include <ripple/basics/mulDiv.h>
26 #include <ripple/protocol/Feature.h>
27 #include <ripple/protocol/jss.h>
28 #include <ripple/protocol/st.h>
29 #include <boost/algorithm/clamp.hpp>
41 auto const [baseFee, effectiveFeePaid] = [&view, &tx]() {
49 return std::pair{baseFee + ref, feePaid + ref};
52 assert(baseFee.signum() > 0);
53 if (effectiveFeePaid.signum() <= 0 || baseFee.signum() <= 0)
61 return feeLevelPaid.second;
66 static boost::optional<LedgerIndex>
77 return mulDiv(level, 100 + increasePercent, 100).second;
92 auto const txBegin = view.
txs.
begin();
93 auto const txEnd = view.
txs.
end();
100 assert(size == feeLevels.
size());
102 JLOG(
j_.
debug()) <<
"Ledger " << view.
info().
seq <<
" has " << size
104 <<
"Ledgers are processing "
105 << (timeLeap ?
"slowly" :
"as expected")
116 auto const upperLimit = std::max<std::uint64_t>(
130 auto const next = [&] {
158 (feeLevels[size / 2] + feeLevels[(size - 1) / 2] +
FeeLevel64{1}) /
208 return {
true, (x * (x + 1) * (2 * x + 1)) / 6};
212 static_assert(sumOfFirstSquares(1).first ==
true);
213 static_assert(sumOfFirstSquares(1).second == 1);
215 static_assert(sumOfFirstSquares(2).first ==
true);
216 static_assert(sumOfFirstSquares(2).second == 5);
218 static_assert(sumOfFirstSquares(0x1FFFFF).first ==
true,
"");
219 static_assert(sumOfFirstSquares(0x1FFFFF).second == 0x2AAAA8AAAAB00000ul,
"");
221 static_assert(sumOfFirstSquares(0x200000).first ==
false,
"");
223 sumOfFirstSquares(0x200000).second ==
244 auto const last =
current + seriesSize - 1;
263 return {sumNlast.first,
FeeLevel64{sumNlast.second}};
264 auto const totalFeeLevel =
mulDiv(
265 multiplier, sumNlast.second - sumNcurrent.second, target * target);
267 return totalFeeLevel;
277 , feeLevel(feeLevel_)
281 , seqProxy(txn_->getSeqProxy())
282 , retriesRemaining(retriesAllowed)
284 , pfresult(pfresult_)
293 if (pfresult->rules != view.
rules() || pfresult->flags != flags)
295 JLOG(j.
debug()) <<
"Queued transaction " << txID
296 <<
" rules or flags have changed. Flags from "
297 << pfresult->flags <<
" to " << flags;
303 auto pcresult =
preclaim(*pfresult, app, view);
305 return doApply(pcresult, app, view);
317 TxQ::TxQAccount::TxMap::const_iterator
322 auto sameOrPrevIter = transactions.lower_bound(seqProx);
323 if (sameOrPrevIter != transactions.begin())
325 return sameOrPrevIter;
333 auto result = transactions.emplace(seqProx, std::move(txn));
334 assert(result.second);
335 assert(&result.first->second != &txn);
337 return result.first->second;
343 return transactions.erase(seqProx) != 0;
358 template <
size_t fillPercentage>
363 fillPercentage > 0 && fillPercentage <= 100,
"Invalid fill percentage");
373 AccountMap::iterator
const& accountIter,
374 boost::optional<TxQAccount::TxMap::iterator>
const& replacementIter,
404 TxQAccount const& txQAcct = accountIter->second;
411 if (txSeqProx.isTicket())
418 if (txSeqProx != nextQueuable)
434 TxQ::erase(TxQ::FeeMultiSet::const_iterator_type candidateIter)
435 -> FeeMultiSet::iterator_type
437 auto& txQAccount = byAccount_.at(candidateIter->account);
438 auto const seqProx = candidateIter->seqProxy;
439 auto const newCandidateIter = byFee_.erase(candidateIter);
443 auto const found = txQAccount.remove(seqProx);
447 return newCandidateIter;
452 -> FeeMultiSet::iterator_type
454 auto& txQAccount = byAccount_.at(candidateIter->account);
455 auto const accountIter =
456 txQAccount.transactions.find(candidateIter->seqProxy);
457 assert(accountIter != txQAccount.transactions.end());
463 candidateIter->seqProxy.isTicket() ||
464 accountIter == txQAccount.transactions.begin());
465 assert(byFee_.iterator_to(accountIter->second) == candidateIter);
466 auto const accountNextIter =
std::next(accountIter);
486 auto const feeNextIter =
std::next(candidateIter);
487 bool const useAccountNext =
488 accountNextIter != txQAccount.transactions.end() &&
489 accountNextIter->first > candidateIter->seqProxy &&
490 (feeNextIter == byFee_.end() ||
491 accountNextIter->second.feeLevel > feeNextIter->feeLevel);
493 auto const candidateNextIter = byFee_.erase(candidateIter);
494 txQAccount.transactions.erase(accountIter);
496 return useAccountNext ? byFee_.iterator_to(accountNextIter->second)
503 TxQ::TxQAccount::TxMap::const_iterator begin,
504 TxQ::TxQAccount::TxMap::const_iterator end) -> TxQAccount::TxMap::iterator
506 for (
auto it = begin; it != end; ++it)
508 byFee_.erase(byFee_.iterator_to(it->second));
510 return txQAccount.transactions.erase(begin, end);
518 TxQ::AccountMap::iterator
const& accountIter,
519 TxQAccount::TxMap::iterator beginTxIter,
528 assert(beginTxIter != accountIter->second.transactions.end());
532 auto endTxIter = accountIter->second.transactions.lower_bound(tSeqProx);
536 metricsSnapshot, view, txExtraCount, dist + 1);
540 if (!requiredTotalFeeLevel.first)
547 [](
auto const& total,
auto const& txn) {
548 return total + txn.second.feeLevel;
552 if (totalFeeLevelPaid < requiredTotalFeeLevel.second)
557 for (
auto it = beginTxIter; it != endTxIter; ++it)
559 auto txResult = it->second.apply(app, view, j);
564 --it->second.retriesRemaining;
565 it->second.lastResult = txResult.first;
586 if (!txResult.second)
589 return {txResult.first,
false};
594 auto const txResult =
doApply(
preclaim(pfresult, app, view), app, view);
600 endTxIter =
erase(accountIter->second, beginTxIter, endTxIter);
602 if (endTxIter != accountIter->second.transactions.end() &&
603 endTxIter->first == tSeqProx)
734 return *directApplied;
746 auto const pfresult =
preflight(app, view.
rules(), *tx, flags, j);
748 return {pfresult.ter,
false};
753 auto const sleAccount = view.
read(accountKey);
759 SeqProxy const txSeqProx = tx->getSeqProxy();
777 bool const accountIsInQueue = accountIter !=
byAccount_.
end();
790 TxQAccount::TxMap::iterator first_,
791 TxQAccount::TxMap::iterator end_)
792 : first(first_), end(end_)
796 TxQAccount::TxMap::iterator first;
797 TxQAccount::TxMap::iterator end;
800 boost::optional<TxIter>
const txIter =
803 acctSeqProx]() -> boost::optional<TxIter> {
804 if (!accountIsInQueue)
809 TxQAccount::TxMap::iterator
const firstIter =
812 if (firstIter == acctTxs.
end())
817 return {TxIter{firstIter, acctTxs.
end()}};
820 auto const acctTxCount{
828 if (pfresult.consequences.isBlocker())
836 <<
". Account has other queued transactions.";
839 if (acctTxCount == 1 && (txSeqProx != txIter->first->first))
844 <<
". Blocker does not replace lone queued transaction.";
851 auto replacedTxIter = [accountIsInQueue, &accountIter, txSeqProx]()
852 -> boost::optional<TxQAccount::TxMap::iterator> {
853 if (accountIsInQueue)
867 auto const requiredFeeLevel =
879 if (acctTxCount == 1 &&
880 txIter->first->second.consequences().isBlocker() &&
881 (txIter->first->first != txSeqProx))
895 TxQAccount::TxMap::iterator
const& existingIter = *replacedTxIter;
899 <<
"Found transaction in queue for account " << account
900 <<
" with " << txSeqProx <<
" new txn fee level is "
901 << feeLevelPaid <<
", old txn fee level is "
902 << existingIter->second.feeLevel
903 <<
", new txn needs fee level of " << requiredRetryLevel;
904 if (feeLevelPaid > requiredRetryLevel)
909 JLOG(
j_.
trace()) <<
"Removing transaction from queue "
910 << existingIter->second.txID <<
" in favor of "
918 <<
" in favor of queued " << existingIter->second.txID;
930 : applyView(&view, flags), openView(&applyView)
935 boost::optional<MultiTxn> multiTxn;
937 if (acctTxCount == 0)
942 if (txSeqProx.
isSeq())
944 if (acctSeqProx > txSeqProx)
946 if (acctSeqProx < txSeqProx)
955 TxQAccount const& txQAcct = accountIter->second;
957 if (acctSeqProx > txSeqProx)
966 bool requiresMultiTxn =
false;
967 if (acctTxCount > 1 || !replacedTxIter)
982 requiresMultiTxn =
true;
985 if (requiresMultiTxn)
999 TxQAccount::TxMap::const_iterator
const prevIter =
1008 assert(prevIter != txIter->end);
1009 if (prevIter == txIter->end || txSeqProx < prevIter->first)
1013 if (txSeqProx.
isSeq())
1015 if (txSeqProx < acctSeqProx)
1017 else if (txSeqProx > acctSeqProx)
1021 else if (!replacedTxIter)
1028 if (txSeqProx.
isSeq() &&
1038 for (
auto iter = txIter->first; iter != txIter->end; ++iter)
1043 if (iter->first != txSeqProx)
1045 totalFee += iter->second.consequences().fee();
1047 iter->second.consequences().potentialSpend();
1049 else if (
std::next(iter) != txIter->end)
1054 totalFee += pfresult.consequences.fee();
1055 potentialSpend += pfresult.consequences.potentialSpend();
1088 auto const balance = (*sleAccount)[
sfBalance].xrp();
1101 if (totalFee >= balance || totalFee >= reserve)
1105 <<
". Total fees in flight too high.";
1110 multiTxn.emplace(view, flags);
1112 auto const sleBump = multiTxn->applyView.peek(accountKey);
1119 auto const potentialTotalSpend = totalFee +
1121 assert(potentialTotalSpend >
XRPAmount{0});
1122 sleBump->setFieldAmount(
sfBalance, balance - potentialTotalSpend);
1145 auto const pcresult =
1146 preclaim(pfresult, app, multiTxn ? multiTxn->openView : view);
1147 if (!pcresult.likelyToClaimFee)
1148 return {pcresult.ter,
false};
1154 << account <<
" has fee level of " << feeLevelPaid
1155 <<
" needs at least " << requiredFeeLevel
1156 <<
" to get in the open ledger, which has "
1157 << view.txCount() <<
" entries.";
1177 multiTxn.is_initialized() &&
1179 feeLevelPaid > requiredFeeLevel && requiredFeeLevel >
baseLevel)
1197 sandbox.
apply(view);
1209 *tx, flags, view, sleAccount, accountIter, replacedTxIter, lock)};
1215 return {ter,
false};
1222 if (!replacedTxIter &&
isFull())
1224 auto lastRIter =
byFee_.rbegin();
1225 if (lastRIter->account == account)
1229 <<
" would kick a transaction from the same account ("
1230 << account <<
") out of the queue.";
1233 auto const& endAccount =
byAccount_.
at(lastRIter->account);
1234 auto endEffectiveFeeLevel = [&]() {
1238 if (lastRIter->feeLevel > feeLevelPaid ||
1239 endAccount.transactions.size() == 1)
1240 return lastRIter->feeLevel;
1244 endAccount.transactions.begin(),
1245 endAccount.transactions.end(),
1247 [&](
auto const& total,
1251 txn.second.feeLevel / endAccount.transactions.size();
1253 txn.second.feeLevel % endAccount.transactions.size();
1254 if (total.first >= max - next || total.second >= max - mod)
1255 return {max, FeeLevel64{0}};
1257 return {total.first + next, total.second + mod};
1259 return endTotal.first +
1260 endTotal.second / endAccount.transactions.size();
1262 if (feeLevelPaid > endEffectiveFeeLevel)
1266 auto dropRIter = endAccount.transactions.rbegin();
1267 assert(dropRIter->second.account == lastRIter->account);
1269 <<
"Removing last item of account " << lastRIter->account
1270 <<
" from queue with average fee of " << endEffectiveFeeLevel
1273 erase(byFee_.iterator_to(dropRIter->second));
1278 <<
"Queue is full, and transaction " << transactionID
1279 <<
" fee is lower than end item's account average fee";
1287 replacedTxIter = removeFromByFee(replacedTxIter, tx);
1290 if (!accountIsInQueue)
1295 byAccount_.emplace(account, TxQAccount(tx));
1310 auto& candidate = accountIter->second.add(
1314 byFee_.insert(candidate);
1315 JLOG(j_.
debug()) <<
"Added transaction " << candidate.txID
1316 <<
" with result " <<
transToken(pfresult.ter) <<
" from "
1317 << (accountIsInQueue ?
"existing" :
"new") <<
" account "
1318 << candidate.account <<
" to queue."
1319 <<
" Flags: " << flags;
1321 return {terQUEUED,
false};
1341 feeMetrics_.update(app, view, timeLeap, setup_);
1342 auto const& snapshot = feeMetrics_.getSnapshot();
1344 auto ledgerSeq = view.
info().
seq;
1348 snapshot.txnsExpected * setup_.ledgersInQueue, setup_.queueSizeMin);
1351 for (
auto candidateIter = byFee_.begin(); candidateIter != byFee_.end();)
1353 if (candidateIter->lastValid && *candidateIter->lastValid <= ledgerSeq)
1355 byAccount_.at(candidateIter->account).dropPenalty =
true;
1356 candidateIter =
erase(candidateIter);
1366 for (
auto txQAccountIter = byAccount_.begin();
1367 txQAccountIter != byAccount_.end();)
1369 if (txQAccountIter->second.empty())
1370 txQAccountIter = byAccount_.erase(txQAccountIter);
1414 auto ledgerChanged =
false;
1418 auto const metricsSnapshot = feeMetrics_.getSnapshot();
1420 for (
auto candidateIter = byFee_.begin(); candidateIter != byFee_.end();)
1422 auto& account = byAccount_.at(candidateIter->account);
1423 auto const beginIter = account.transactions.begin();
1424 if (candidateIter->seqProxy.isSeq() &&
1425 candidateIter->seqProxy > beginIter->first)
1431 <<
"Skipping queued transaction " << candidateIter->txID
1432 <<
" from account " << candidateIter->account
1433 <<
" as it is not the first.";
1437 auto const requiredFeeLevel =
1438 getRequiredFeeLevel(view,
tapNONE, metricsSnapshot, lock);
1439 auto const feeLevelPaid = candidateIter->feeLevel;
1440 JLOG(j_.
trace()) <<
"Queued transaction " << candidateIter->txID
1441 <<
" from account " << candidateIter->account
1442 <<
" has fee level of " << feeLevelPaid
1443 <<
" needs at least " << requiredFeeLevel;
1444 if (feeLevelPaid >= requiredFeeLevel)
1446 JLOG(j_.
trace()) <<
"Applying queued transaction "
1447 << candidateIter->txID <<
" to open ledger.";
1449 auto const [txnResult, didApply] =
1450 candidateIter->apply(app, view, j_);
1456 <<
"Queued transaction " << candidateIter->txID
1457 <<
" applied successfully with " <<
transToken(txnResult)
1458 <<
". Remove from queue.";
1460 candidateIter = eraseAndAdvance(candidateIter);
1461 ledgerChanged =
true;
1465 candidateIter->retriesRemaining <= 0)
1467 if (candidateIter->retriesRemaining <= 0)
1468 account.retryPenalty =
true;
1470 account.dropPenalty =
true;
1471 JLOG(j_.
debug()) <<
"Queued transaction " << candidateIter->txID
1473 <<
". Remove from queue.";
1474 candidateIter = eraseAndAdvance(candidateIter);
1478 JLOG(j_.
debug()) <<
"Queued transaction " << candidateIter->txID
1480 <<
". Leave in queue."
1481 <<
" Applied: " << didApply
1482 <<
". Flags: " << candidateIter->flags;
1483 if (account.retryPenalty && candidateIter->retriesRemaining > 2)
1484 candidateIter->retriesRemaining = 1;
1486 --candidateIter->retriesRemaining;
1487 candidateIter->lastResult = txnResult;
1488 if (account.dropPenalty && account.transactions.size() > 1 &&
1494 if (candidateIter->seqProxy.isTicket())
1499 <<
"Queue is nearly full, and transaction "
1500 << candidateIter->txID <<
" failed with "
1502 <<
". Removing ticketed tx from account "
1504 candidateIter = eraseAndAdvance(candidateIter);
1512 auto dropRIter = account.transactions.rbegin();
1514 dropRIter->second.account ==
1515 candidateIter->account);
1518 <<
"Queue is nearly full, and transaction "
1519 << candidateIter->txID <<
" failed with "
1521 <<
". Removing last item from account "
1523 auto endIter = byFee_.iterator_to(dropRIter->second);
1524 if (endIter != candidateIter)
1539 return ledgerChanged;
1549 return nextQueuableSeqImpl(sleAccount, lock);
1559 TxQ::nextQueuableSeqImpl(
1566 return SeqProxy::sequence(0);
1571 auto const accountIter = byAccount_.find((*sleAccount)[
sfAccount]);
1572 if (accountIter == byAccount_.end() ||
1573 accountIter->second.transactions.empty())
1581 TxQAccount::TxMap::const_iterator txIter = acctTxs.
lower_bound(acctSeqProx);
1583 if (txIter == acctTxs.
end() || !txIter->first.isSeq() ||
1584 txIter->first != acctSeqProx)
1594 SeqProxy attempt = txIter->second.consequences().followingSeq();
1595 while (++txIter != acctTxs.
cend())
1597 if (attempt < txIter->first)
1600 attempt = txIter->second.consequences().followingSeq();
1606 TxQ::getRequiredFeeLevel(
1613 FeeMetrics::scaleFeeLevel(metricsSnapshot, view);
1616 return std::max(feeLevel, byFee_.begin()->feeLevel);
1622 TxQ::tryDirectApply(
1630 auto const sleAccount = view.
read(keylet::account(account));
1637 SeqProxy const txSeqProx = tx->getSeqProxy();
1641 if (txSeqProx.
isSeq() && txSeqProx != acctSeqProx)
1644 FeeLevel64 const requiredFeeLevel = [
this, &view, flags]() {
1646 return getRequiredFeeLevel(
1647 view, flags, feeMetrics_.getSnapshot(), lock);
1654 if (feeLevelPaid >= requiredFeeLevel)
1659 <<
" to open ledger.";
1661 auto const [txnResult, didApply] =
1665 << (didApply ?
" applied successfully with "
1675 AccountMap::iterator accountIter = byAccount_.find(account);
1676 if (accountIter != byAccount_.end())
1679 if (
auto const existingIter =
1683 removeFromByFee(existingIter, tx);
1687 return {
std::pair(txnResult, didApply)};
1692 boost::optional<TxQ::TxQAccount::TxMap::iterator>
1693 TxQ::removeFromByFee(
1694 boost::optional<TxQAccount::TxMap::iterator>
const& replacedTxIter,
1697 if (replacedTxIter && tx)
1701 auto deleteIter = byFee_.iterator_to((*replacedTxIter)->second);
1702 assert(deleteIter != byFee_.end());
1703 assert(&(*replacedTxIter)->second == &*deleteIter);
1704 assert(deleteIter->seqProxy == tx->getSeqProxy());
1705 assert(deleteIter->account == (*tx)[
sfAccount]);
1719 auto const snapshot = feeMetrics_.getSnapshot();
1721 result.
txCount = byFee_.size();
1727 isFull() ? byFee_.rbegin()->feeLevel +
FeeLevel64{1} : baseLevel;
1728 result.
medFeeLevel = snapshot.escalationMultiplier;
1735 TxQ::getTxRequiredFeeAndSeq(
1743 auto const snapshot = feeMetrics_.getSnapshot();
1745 auto const fee = FeeMetrics::scaleFeeLevel(snapshot, view);
1747 auto const sle = view.
read(keylet::account(account));
1750 std::uint32_t const availableSeq = nextQueuableSeqImpl(sle, lock).value();
1752 return {
mulDiv(fee, baseFee, baseLevel).second, accountSeq, availableSeq};
1762 AccountMap::const_iterator
const accountIter{byAccount_.find(account)};
1764 if (accountIter == byAccount_.end() ||
1765 accountIter->second.transactions.empty())
1768 result.
reserve(accountIter->second.transactions.size());
1769 for (
auto const& tx : accountIter->second.transactions)
1783 result.
reserve(byFee_.size());
1785 for (
auto const& tx : byFee_)
1797 BOOST_ASSERT(
false);
1801 auto const metrics = getMetrics(*view);
1807 ret[jss::ledger_current_index] = view->info().seq;
1808 ret[jss::expected_ledger_size] =
std::to_string(metrics.txPerLedger);
1809 ret[jss::current_ledger_size] =
std::to_string(metrics.txInLedger);
1811 if (metrics.txQMaxSize)
1814 levels[jss::reference_level] = to_string(metrics.referenceFeeLevel);
1815 levels[jss::minimum_level] = to_string(metrics.minProcessingFeeLevel);
1816 levels[jss::median_level] = to_string(metrics.medFeeLevel);
1817 levels[jss::open_ledger_level] = to_string(metrics.openLedgerFeeLevel);
1819 auto const baseFee = view->fees().base;
1822 drops[jss::base_fee] =
1823 to_string(
toDrops(metrics.referenceFeeLevel, baseFee));
1824 drops[jss::minimum_fee] =
1825 to_string(
toDrops(metrics.minProcessingFeeLevel, baseFee));
1826 drops[jss::median_fee] = to_string(
toDrops(metrics.medFeeLevel, baseFee));
1827 drops[jss::open_ledger_fee] = to_string(
1839 auto const& section = config.
section(
"transaction_queue");
1844 "minimum_escalation_multiplier",
1848 "minimum_txn_in_ledger_standalone",
1852 if (
set(max,
"maximum_txn_in_ledger", section))
1856 Throw<std::runtime_error>(
1857 "The minimum number of low-fee transactions allowed "
1858 "per ledger (minimum_txn_in_ledger) exceeds "
1859 "the maximum number of low-fee transactions allowed per "
1860 "ledger (maximum_txn_in_ledger).");
1864 Throw<std::runtime_error>(
1865 "The minimum number of low-fee transactions allowed "
1866 "per ledger (minimum_txn_in_ledger_standalone) exceeds "
1867 "the maximum number of low-fee transactions allowed per "
1868 "ledger (maximum_txn_in_ledger).");
1881 "normal_consensus_increase_percent",
1891 "slow_consensus_decrease_percent",