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_)
295 if (pfresult->rules != view.
rules() || pfresult->flags != flags)
297 JLOG(j.
debug()) <<
"Queued transaction " << txID
298 <<
" rules or flags have changed. Flags from "
299 << pfresult->flags <<
" to " << flags;
305 auto pcresult =
preclaim(*pfresult, app, view);
307 return doApply(pcresult, app, view);
319 TxQ::TxQAccount::TxMap::const_iterator
324 auto sameOrPrevIter = transactions.lower_bound(seqProx);
325 if (sameOrPrevIter != transactions.begin())
327 return sameOrPrevIter;
335 auto result = transactions.emplace(seqProx, std::move(txn));
336 assert(result.second);
337 assert(&result.first->second != &txn);
339 return result.first->second;
345 return transactions.erase(seqProx) != 0;
360 template <
size_t fillPercentage>
365 fillPercentage > 0 && fillPercentage <= 100,
"Invalid fill percentage");
375 AccountMap::iterator
const& accountIter,
376 boost::optional<TxQAccount::TxMap::iterator>
const& replacementIter,
406 TxQAccount const& txQAcct = accountIter->second;
413 if (txSeqProx.isTicket())
420 if (txSeqProx != nextQueuable)
436 TxQ::erase(TxQ::FeeMultiSet::const_iterator_type candidateIter)
437 -> FeeMultiSet::iterator_type
439 auto& txQAccount = byAccount_.at(candidateIter->account);
440 auto const seqProx = candidateIter->seqProxy;
441 auto const newCandidateIter = byFee_.erase(candidateIter);
445 auto const found = txQAccount.remove(seqProx);
449 return newCandidateIter;
454 -> FeeMultiSet::iterator_type
456 auto& txQAccount = byAccount_.at(candidateIter->account);
457 auto const accountIter =
458 txQAccount.transactions.find(candidateIter->seqProxy);
459 assert(accountIter != txQAccount.transactions.end());
465 candidateIter->seqProxy.isTicket() ||
466 accountIter == txQAccount.transactions.begin());
467 assert(byFee_.iterator_to(accountIter->second) == candidateIter);
468 auto const accountNextIter =
std::next(accountIter);
488 auto const feeNextIter =
std::next(candidateIter);
489 bool const useAccountNext =
490 accountNextIter != txQAccount.transactions.end() &&
491 accountNextIter->first > candidateIter->seqProxy &&
492 (feeNextIter == byFee_.end() ||
493 accountNextIter->second.feeLevel > feeNextIter->feeLevel);
495 auto const candidateNextIter = byFee_.erase(candidateIter);
496 txQAccount.transactions.erase(accountIter);
498 return useAccountNext ? byFee_.iterator_to(accountNextIter->second)
505 TxQ::TxQAccount::TxMap::const_iterator begin,
506 TxQ::TxQAccount::TxMap::const_iterator end) -> TxQAccount::TxMap::iterator
508 for (
auto it = begin; it != end; ++it)
510 byFee_.erase(byFee_.iterator_to(it->second));
512 return txQAccount.transactions.erase(begin, end);
520 TxQ::AccountMap::iterator
const& accountIter,
521 TxQAccount::TxMap::iterator beginTxIter,
530 assert(beginTxIter != accountIter->second.transactions.end());
534 auto endTxIter = accountIter->second.transactions.lower_bound(tSeqProx);
538 metricsSnapshot, view, txExtraCount, dist + 1);
542 if (!requiredTotalFeeLevel.first)
549 [](
auto const& total,
auto const& txn) {
550 return total + txn.second.feeLevel;
554 if (totalFeeLevelPaid < requiredTotalFeeLevel.second)
559 for (
auto it = beginTxIter; it != endTxIter; ++it)
561 auto txResult = it->second.apply(app, view, j);
566 --it->second.retriesRemaining;
567 it->second.lastResult = txResult.first;
588 if (!txResult.second)
591 return {txResult.first,
false};
596 auto const txResult =
doApply(
preclaim(pfresult, app, view), app, view);
602 endTxIter =
erase(accountIter->second, beginTxIter, endTxIter);
604 if (endTxIter != accountIter->second.transactions.end() &&
605 endTxIter->first == tSeqProx)
738 return *directApplied;
750 auto const pfresult =
preflight(app, view.
rules(), *tx, flags, j);
752 return {pfresult.ter,
false};
757 auto const sleAccount = view.
read(accountKey);
763 SeqProxy const txSeqProx = tx->getSeqProxy();
781 bool const accountIsInQueue = accountIter !=
byAccount_.
end();
794 TxQAccount::TxMap::iterator first_,
795 TxQAccount::TxMap::iterator end_)
796 : first(first_), end(end_)
800 TxQAccount::TxMap::iterator first;
801 TxQAccount::TxMap::iterator end;
804 boost::optional<TxIter>
const txIter =
807 acctSeqProx]() -> boost::optional<TxIter> {
808 if (!accountIsInQueue)
813 TxQAccount::TxMap::iterator
const firstIter =
816 if (firstIter == acctTxs.
end())
821 return {TxIter{firstIter, acctTxs.
end()}};
824 auto const acctTxCount{
832 if (pfresult.consequences.isBlocker())
840 <<
". Account has other queued transactions.";
843 if (acctTxCount == 1 && (txSeqProx != txIter->first->first))
848 <<
". Blocker does not replace lone queued transaction.";
855 auto replacedTxIter = [accountIsInQueue, &accountIter, txSeqProx]()
856 -> boost::optional<TxQAccount::TxMap::iterator> {
857 if (accountIsInQueue)
871 auto const requiredFeeLevel =
883 if (acctTxCount == 1 &&
884 txIter->first->second.consequences().isBlocker() &&
885 (txIter->first->first != txSeqProx))
899 TxQAccount::TxMap::iterator
const& existingIter = *replacedTxIter;
903 <<
"Found transaction in queue for account " << account
904 <<
" with " << txSeqProx <<
" new txn fee level is "
905 << feeLevelPaid <<
", old txn fee level is "
906 << existingIter->second.feeLevel
907 <<
", new txn needs fee level of " << requiredRetryLevel;
908 if (feeLevelPaid > requiredRetryLevel)
913 JLOG(
j_.
trace()) <<
"Removing transaction from queue "
914 << existingIter->second.txID <<
" in favor of "
922 <<
" in favor of queued " << existingIter->second.txID;
934 : applyView(&view, flags), openView(&applyView)
939 boost::optional<MultiTxn> multiTxn;
941 if (acctTxCount == 0)
946 if (txSeqProx.
isSeq())
948 if (acctSeqProx > txSeqProx)
950 if (acctSeqProx < txSeqProx)
959 TxQAccount const& txQAcct = accountIter->second;
961 if (acctSeqProx > txSeqProx)
970 bool requiresMultiTxn =
false;
971 if (acctTxCount > 1 || !replacedTxIter)
986 requiresMultiTxn =
true;
989 if (requiresMultiTxn)
1003 TxQAccount::TxMap::const_iterator
const prevIter =
1012 assert(prevIter != txIter->end);
1013 if (prevIter == txIter->end || txSeqProx < prevIter->first)
1017 if (txSeqProx.
isSeq())
1019 if (txSeqProx < acctSeqProx)
1021 else if (txSeqProx > acctSeqProx)
1025 else if (!replacedTxIter)
1032 if (txSeqProx.
isSeq() &&
1042 for (
auto iter = txIter->first; iter != txIter->end; ++iter)
1047 if (iter->first != txSeqProx)
1049 totalFee += iter->second.consequences().fee();
1051 iter->second.consequences().potentialSpend();
1053 else if (
std::next(iter) != txIter->end)
1058 totalFee += pfresult.consequences.fee();
1059 potentialSpend += pfresult.consequences.potentialSpend();
1092 auto const balance = (*sleAccount)[
sfBalance].xrp();
1105 if (totalFee >= balance || totalFee >= reserve)
1109 <<
". Total fees in flight too high.";
1114 multiTxn.emplace(view, flags);
1116 auto const sleBump = multiTxn->applyView.peek(accountKey);
1123 auto const potentialTotalSpend = totalFee +
1125 assert(potentialTotalSpend >
XRPAmount{0});
1126 sleBump->setFieldAmount(
sfBalance, balance - potentialTotalSpend);
1149 auto const pcresult =
1150 preclaim(pfresult, app, multiTxn ? multiTxn->openView : view);
1151 if (!pcresult.likelyToClaimFee)
1152 return {pcresult.ter,
false};
1158 << account <<
" has fee level of " << feeLevelPaid
1159 <<
" needs at least " << requiredFeeLevel
1160 <<
" to get in the open ledger, which has "
1161 << view.txCount() <<
" entries.";
1181 multiTxn.is_initialized() &&
1183 feeLevelPaid > requiredFeeLevel && requiredFeeLevel >
baseLevel)
1201 sandbox.
apply(view);
1213 *tx, flags, view, sleAccount, accountIter, replacedTxIter, lock)};
1219 return {ter,
false};
1226 if (!replacedTxIter &&
isFull())
1228 auto lastRIter =
byFee_.rbegin();
1229 if (lastRIter->account == account)
1233 <<
" would kick a transaction from the same account ("
1234 << account <<
") out of the queue.";
1237 auto const& endAccount =
byAccount_.
at(lastRIter->account);
1238 auto endEffectiveFeeLevel = [&]() {
1242 if (lastRIter->feeLevel > feeLevelPaid ||
1243 endAccount.transactions.size() == 1)
1244 return lastRIter->feeLevel;
1248 endAccount.transactions.begin(),
1249 endAccount.transactions.end(),
1251 [&](
auto const& total,
1255 txn.second.feeLevel / endAccount.transactions.size();
1257 txn.second.feeLevel % endAccount.transactions.size();
1258 if (total.first >= max - next || total.second >= max - mod)
1259 return {max, FeeLevel64{0}};
1261 return {total.first + next, total.second + mod};
1263 return endTotal.first +
1264 endTotal.second / endAccount.transactions.size();
1266 if (feeLevelPaid > endEffectiveFeeLevel)
1270 auto dropRIter = endAccount.transactions.rbegin();
1271 assert(dropRIter->second.account == lastRIter->account);
1273 <<
"Removing last item of account " << lastRIter->account
1274 <<
" from queue with average fee of " << endEffectiveFeeLevel
1277 erase(byFee_.iterator_to(dropRIter->second));
1282 <<
"Queue is full, and transaction " << transactionID
1283 <<
" fee is lower than end item's account average fee";
1291 replacedTxIter = removeFromByFee(replacedTxIter, tx);
1294 if (!accountIsInQueue)
1299 byAccount_.emplace(account, TxQAccount(tx));
1314 auto& candidate = accountIter->second.add(
1318 byFee_.insert(candidate);
1319 JLOG(j_.
debug()) <<
"Added transaction " << candidate.txID
1320 <<
" with result " <<
transToken(pfresult.ter) <<
" from "
1321 << (accountIsInQueue ?
"existing" :
"new") <<
" account "
1322 << candidate.account <<
" to queue."
1323 <<
" Flags: " << flags;
1325 return {terQUEUED,
false};
1345 feeMetrics_.update(app, view, timeLeap, setup_);
1346 auto const& snapshot = feeMetrics_.getSnapshot();
1348 auto ledgerSeq = view.
info().
seq;
1352 snapshot.txnsExpected * setup_.ledgersInQueue, setup_.queueSizeMin);
1355 for (
auto candidateIter = byFee_.begin(); candidateIter != byFee_.end();)
1357 if (candidateIter->lastValid && *candidateIter->lastValid <= ledgerSeq)
1359 byAccount_.at(candidateIter->account).dropPenalty =
true;
1360 candidateIter =
erase(candidateIter);
1370 for (
auto txQAccountIter = byAccount_.begin();
1371 txQAccountIter != byAccount_.end();)
1373 if (txQAccountIter->second.empty())
1374 txQAccountIter = byAccount_.erase(txQAccountIter);
1418 auto ledgerChanged =
false;
1422 auto const metricsSnapshot = feeMetrics_.getSnapshot();
1424 for (
auto candidateIter = byFee_.begin(); candidateIter != byFee_.end();)
1426 auto& account = byAccount_.at(candidateIter->account);
1427 auto const beginIter = account.transactions.begin();
1428 if (candidateIter->seqProxy.isSeq() &&
1429 candidateIter->seqProxy > beginIter->first)
1435 <<
"Skipping queued transaction " << candidateIter->txID
1436 <<
" from account " << candidateIter->account
1437 <<
" as it is not the first.";
1441 auto const requiredFeeLevel =
1442 getRequiredFeeLevel(view,
tapNONE, metricsSnapshot, lock);
1443 auto const feeLevelPaid = candidateIter->feeLevel;
1444 JLOG(j_.
trace()) <<
"Queued transaction " << candidateIter->txID
1445 <<
" from account " << candidateIter->account
1446 <<
" has fee level of " << feeLevelPaid
1447 <<
" needs at least " << requiredFeeLevel;
1448 if (feeLevelPaid >= requiredFeeLevel)
1450 JLOG(j_.
trace()) <<
"Applying queued transaction "
1451 << candidateIter->txID <<
" to open ledger.";
1453 auto const [txnResult, didApply] =
1454 candidateIter->apply(app, view, j_);
1460 <<
"Queued transaction " << candidateIter->txID
1461 <<
" applied successfully with " <<
transToken(txnResult)
1462 <<
". Remove from queue.";
1464 candidateIter = eraseAndAdvance(candidateIter);
1465 ledgerChanged =
true;
1469 candidateIter->retriesRemaining <= 0)
1471 if (candidateIter->retriesRemaining <= 0)
1472 account.retryPenalty =
true;
1474 account.dropPenalty =
true;
1475 JLOG(j_.
debug()) <<
"Queued transaction " << candidateIter->txID
1477 <<
". Remove from queue.";
1478 candidateIter = eraseAndAdvance(candidateIter);
1482 JLOG(j_.
debug()) <<
"Queued transaction " << candidateIter->txID
1484 <<
". Leave in queue."
1485 <<
" Applied: " << didApply
1486 <<
". Flags: " << candidateIter->flags;
1487 if (account.retryPenalty && candidateIter->retriesRemaining > 2)
1488 candidateIter->retriesRemaining = 1;
1490 --candidateIter->retriesRemaining;
1491 candidateIter->lastResult = txnResult;
1492 if (account.dropPenalty && account.transactions.size() > 1 &&
1498 if (candidateIter->seqProxy.isTicket())
1503 <<
"Queue is nearly full, and transaction "
1504 << candidateIter->txID <<
" failed with "
1506 <<
". Removing ticketed tx from account "
1508 candidateIter = eraseAndAdvance(candidateIter);
1516 auto dropRIter = account.transactions.rbegin();
1518 dropRIter->second.account ==
1519 candidateIter->account);
1522 <<
"Queue is nearly full, and transaction "
1523 << candidateIter->txID <<
" failed with "
1525 <<
". Removing last item from account "
1527 auto endIter = byFee_.iterator_to(dropRIter->second);
1528 if (endIter != candidateIter)
1543 return ledgerChanged;
1553 return nextQueuableSeqImpl(sleAccount, lock);
1563 TxQ::nextQueuableSeqImpl(
1570 return SeqProxy::sequence(0);
1575 auto const accountIter = byAccount_.find((*sleAccount)[
sfAccount]);
1576 if (accountIter == byAccount_.end() ||
1577 accountIter->second.transactions.empty())
1585 TxQAccount::TxMap::const_iterator txIter = acctTxs.
lower_bound(acctSeqProx);
1587 if (txIter == acctTxs.
end() || !txIter->first.isSeq() ||
1588 txIter->first != acctSeqProx)
1598 SeqProxy attempt = txIter->second.consequences().followingSeq();
1599 while (++txIter != acctTxs.
cend())
1601 if (attempt < txIter->first)
1604 attempt = txIter->second.consequences().followingSeq();
1610 TxQ::getRequiredFeeLevel(
1617 FeeMetrics::scaleFeeLevel(metricsSnapshot, view);
1620 return std::max(feeLevel, byFee_.begin()->feeLevel);
1626 TxQ::tryDirectApply(
1634 auto const sleAccount = view.
read(keylet::account(account));
1641 SeqProxy const txSeqProx = tx->getSeqProxy();
1645 if (txSeqProx.
isSeq() && txSeqProx != acctSeqProx)
1648 FeeLevel64 const requiredFeeLevel = [
this, &view, flags]() {
1650 return getRequiredFeeLevel(
1651 view, flags, feeMetrics_.getSnapshot(), lock);
1658 if (feeLevelPaid >= requiredFeeLevel)
1663 <<
" to open ledger.";
1665 auto const [txnResult, didApply] =
1669 << (didApply ?
" applied successfully with "
1679 AccountMap::iterator accountIter = byAccount_.find(account);
1680 if (accountIter != byAccount_.end())
1683 if (
auto const existingIter =
1687 removeFromByFee(existingIter, tx);
1691 return {
std::pair(txnResult, didApply)};
1696 boost::optional<TxQ::TxQAccount::TxMap::iterator>
1697 TxQ::removeFromByFee(
1698 boost::optional<TxQAccount::TxMap::iterator>
const& replacedTxIter,
1701 if (replacedTxIter && tx)
1705 auto deleteIter = byFee_.iterator_to((*replacedTxIter)->second);
1706 assert(deleteIter != byFee_.end());
1707 assert(&(*replacedTxIter)->second == &*deleteIter);
1708 assert(deleteIter->seqProxy == tx->getSeqProxy());
1709 assert(deleteIter->account == (*tx)[
sfAccount]);
1723 auto const snapshot = feeMetrics_.getSnapshot();
1725 result.
txCount = byFee_.size();
1731 isFull() ? byFee_.rbegin()->feeLevel +
FeeLevel64{1} : baseLevel;
1732 result.
medFeeLevel = snapshot.escalationMultiplier;
1739 TxQ::getTxRequiredFeeAndSeq(
1747 auto const snapshot = feeMetrics_.getSnapshot();
1749 auto const fee = FeeMetrics::scaleFeeLevel(snapshot, view);
1751 auto const sle = view.
read(keylet::account(account));
1754 std::uint32_t const availableSeq = nextQueuableSeqImpl(sle, lock).value();
1756 return {
mulDiv(fee, baseFee, baseLevel).second, accountSeq, availableSeq};
1766 AccountMap::const_iterator
const accountIter{byAccount_.find(account)};
1768 if (accountIter == byAccount_.end() ||
1769 accountIter->second.transactions.empty())
1772 result.
reserve(accountIter->second.transactions.size());
1773 for (
auto const& tx : accountIter->second.transactions)
1787 result.
reserve(byFee_.size());
1789 for (
auto const& tx : byFee_)
1801 BOOST_ASSERT(
false);
1805 auto const metrics = getMetrics(*view);
1811 ret[jss::ledger_current_index] = view->info().seq;
1812 ret[jss::expected_ledger_size] =
std::to_string(metrics.txPerLedger);
1813 ret[jss::current_ledger_size] =
std::to_string(metrics.txInLedger);
1815 if (metrics.txQMaxSize)
1818 levels[jss::reference_level] = to_string(metrics.referenceFeeLevel);
1819 levels[jss::minimum_level] = to_string(metrics.minProcessingFeeLevel);
1820 levels[jss::median_level] = to_string(metrics.medFeeLevel);
1821 levels[jss::open_ledger_level] = to_string(metrics.openLedgerFeeLevel);
1823 auto const baseFee = view->fees().base;
1826 drops[jss::base_fee] =
1827 to_string(
toDrops(metrics.referenceFeeLevel, baseFee));
1828 drops[jss::minimum_fee] =
1829 to_string(
toDrops(metrics.minProcessingFeeLevel, baseFee));
1830 drops[jss::median_fee] = to_string(
toDrops(metrics.medFeeLevel, baseFee));
1831 drops[jss::open_ledger_fee] = to_string(
1843 auto const& section = config.
section(
"transaction_queue");
1848 "minimum_escalation_multiplier",
1852 "minimum_txn_in_ledger_standalone",
1856 if (
set(max,
"maximum_txn_in_ledger", section))
1860 Throw<std::runtime_error>(
1861 "The minimum number of low-fee transactions allowed "
1862 "per ledger (minimum_txn_in_ledger) exceeds "
1863 "the maximum number of low-fee transactions allowed per "
1864 "ledger (maximum_txn_in_ledger).");
1868 Throw<std::runtime_error>(
1869 "The minimum number of low-fee transactions allowed "
1870 "per ledger (minimum_txn_in_ledger_standalone) exceeds "
1871 "the maximum number of low-fee transactions allowed per "
1872 "ledger (maximum_txn_in_ledger).");
1885 "normal_consensus_increase_percent",
1895 "slow_consensus_decrease_percent",