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>
40 auto const [baseFee, effectiveFeePaid] = [&view, &tx]() {
48 return std::pair{baseFee + ref, feePaid + ref};
51 assert(baseFee.signum() > 0);
52 if (effectiveFeePaid.signum() <= 0 || baseFee.signum() <= 0)
60 return feeLevelPaid.second;
76 return mulDiv(level, 100 + increasePercent, 100).second;
91 auto const txBegin = view.
txs.
begin();
92 auto const txEnd = view.
txs.
end();
99 assert(size == feeLevels.
size());
102 <<
"Ledger " << view.
info().
seq <<
" has " << size <<
" transactions. "
103 <<
"Ledgers are processing " << (timeLeap ?
"slowly" :
"as expected")
114 auto const upperLimit = std::max<std::uint64_t>(
128 auto const next = [&] {
156 (feeLevels[size / 2] + feeLevels[(size - 1) / 2] +
FeeLevel64{1}) /
206 return {
true, (x * (x + 1) * (2 * x + 1)) / 6};
210 static_assert(sumOfFirstSquares(1).first ==
true);
211 static_assert(sumOfFirstSquares(1).second == 1);
213 static_assert(sumOfFirstSquares(2).first ==
true);
214 static_assert(sumOfFirstSquares(2).second == 5);
216 static_assert(sumOfFirstSquares(0x1FFFFF).first ==
true,
"");
217 static_assert(sumOfFirstSquares(0x1FFFFF).second == 0x2AAAA8AAAAB00000ul,
"");
219 static_assert(sumOfFirstSquares(0x200000).first ==
false,
"");
221 sumOfFirstSquares(0x200000).second ==
242 auto const last =
current + seriesSize - 1;
261 return {sumNlast.first,
FeeLevel64{sumNlast.second}};
262 auto const totalFeeLevel =
mulDiv(
263 multiplier, sumNlast.second - sumNcurrent.second, target * target);
265 return totalFeeLevel;
275 , feeLevel(feeLevel_)
279 , seqProxy(txn_->getSeqProxy())
280 , retriesRemaining(retriesAllowed)
282 , 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,
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);
471 auto const feeNextIter =
std::next(candidateIter);
472 bool const useAccountNext =
473 accountNextIter != txQAccount.transactions.end() &&
474 accountNextIter->first > candidateIter->seqProxy &&
475 (feeNextIter == byFee_.end() ||
476 o(accountNextIter->second, *feeNextIter));
478 auto const candidateNextIter = byFee_.erase(candidateIter);
479 txQAccount.transactions.erase(accountIter);
481 return useAccountNext ? byFee_.iterator_to(accountNextIter->second)
488 TxQ::TxQAccount::TxMap::const_iterator begin,
489 TxQ::TxQAccount::TxMap::const_iterator end) -> TxQAccount::TxMap::iterator
491 for (
auto it = begin; it != end; ++it)
493 byFee_.erase(byFee_.iterator_to(it->second));
495 return txQAccount.transactions.erase(begin, end);
503 TxQ::AccountMap::iterator
const& accountIter,
504 TxQAccount::TxMap::iterator beginTxIter,
513 assert(beginTxIter != accountIter->second.transactions.end());
517 auto endTxIter = accountIter->second.transactions.lower_bound(tSeqProx);
521 metricsSnapshot, view, txExtraCount, dist + 1);
525 if (!requiredTotalFeeLevel.first)
532 [](
auto const& total,
auto const& txn) {
533 return total + txn.second.feeLevel;
537 if (totalFeeLevelPaid < requiredTotalFeeLevel.second)
542 for (
auto it = beginTxIter; it != endTxIter; ++it)
544 auto txResult = it->second.apply(app, view, j);
549 --it->second.retriesRemaining;
550 it->second.lastResult = txResult.first;
571 if (!txResult.second)
574 return {txResult.first,
false};
579 auto const txResult =
doApply(
preclaim(pfresult, app, view), app, view);
585 endTxIter =
erase(accountIter->second, beginTxIter, endTxIter);
587 if (endTxIter != accountIter->second.transactions.end() &&
588 endTxIter->first == tSeqProx)
721 return *directApplied;
733 auto const pfresult =
preflight(app, view.
rules(), *tx, flags, j);
735 return {pfresult.ter,
false};
740 auto const sleAccount = view.
read(accountKey);
746 SeqProxy const txSeqProx = tx->getSeqProxy();
764 bool const accountIsInQueue = accountIter !=
byAccount_.
end();
777 TxQAccount::TxMap::iterator first_,
778 TxQAccount::TxMap::iterator end_)
779 : first(first_), end(end_)
783 TxQAccount::TxMap::iterator first;
784 TxQAccount::TxMap::iterator end;
791 if (!accountIsInQueue)
796 TxQAccount::TxMap::iterator
const firstIter =
799 if (firstIter == acctTxs.
end())
804 return {TxIter{firstIter, acctTxs.
end()}};
807 auto const acctTxCount{
815 if (pfresult.consequences.isBlocker())
823 <<
". Account has other queued transactions.";
826 if (acctTxCount == 1 && (txSeqProx != txIter->first->first))
831 <<
". Blocker does not replace lone queued transaction.";
838 auto replacedTxIter = [accountIsInQueue, &accountIter, txSeqProx]()
840 if (accountIsInQueue)
854 auto const requiredFeeLevel =
866 if (acctTxCount == 1 &&
867 txIter->first->second.consequences().isBlocker() &&
868 (txIter->first->first != txSeqProx))
882 TxQAccount::TxMap::iterator
const& existingIter = *replacedTxIter;
886 <<
"Found transaction in queue for account " << account
887 <<
" with " << txSeqProx <<
" new txn fee level is "
888 << feeLevelPaid <<
", old txn fee level is "
889 << existingIter->second.feeLevel
890 <<
", new txn needs fee level of " << requiredRetryLevel;
891 if (feeLevelPaid > requiredRetryLevel)
896 JLOG(
j_.
trace()) <<
"Removing transaction from queue "
897 << existingIter->second.txID <<
" in favor of "
905 <<
" in favor of queued " << existingIter->second.txID;
917 : applyView(&view, flags), openView(&applyView)
924 if (acctTxCount == 0)
929 if (txSeqProx.
isSeq())
931 if (acctSeqProx > txSeqProx)
933 if (acctSeqProx < txSeqProx)
942 TxQAccount const& txQAcct = accountIter->second;
944 if (acctSeqProx > txSeqProx)
953 bool requiresMultiTxn =
false;
954 if (acctTxCount > 1 || !replacedTxIter)
969 requiresMultiTxn =
true;
972 if (requiresMultiTxn)
986 TxQAccount::TxMap::const_iterator
const prevIter =
995 assert(prevIter != txIter->end);
996 if (prevIter == txIter->end || txSeqProx < prevIter->first)
1000 if (txSeqProx.
isSeq())
1002 if (txSeqProx < acctSeqProx)
1004 else if (txSeqProx > acctSeqProx)
1008 else if (!replacedTxIter)
1015 if (txSeqProx.
isSeq() &&
1025 for (
auto iter = txIter->first; iter != txIter->end; ++iter)
1030 if (iter->first != txSeqProx)
1032 totalFee += iter->second.consequences().fee();
1034 iter->second.consequences().potentialSpend();
1036 else if (
std::next(iter) != txIter->end)
1041 totalFee += pfresult.consequences.fee();
1042 potentialSpend += pfresult.consequences.potentialSpend();
1075 auto const balance = (*sleAccount)[
sfBalance].xrp();
1088 if (totalFee >= balance || totalFee >= reserve)
1092 <<
". Total fees in flight too high.";
1097 multiTxn.
emplace(view, flags);
1099 auto const sleBump = multiTxn->applyView.peek(accountKey);
1106 auto const potentialTotalSpend = totalFee +
1108 assert(potentialTotalSpend >
XRPAmount{0});
1109 sleBump->setFieldAmount(
sfBalance, balance - potentialTotalSpend);
1132 auto const pcresult =
1133 preclaim(pfresult, app, multiTxn ? multiTxn->openView : view);
1134 if (!pcresult.likelyToClaimFee)
1135 return {pcresult.ter,
false};
1141 << account <<
" has fee level of " << feeLevelPaid
1142 <<
" needs at least " << requiredFeeLevel
1143 <<
" to get in the open ledger, which has "
1144 << view.txCount() <<
" entries.";
1165 feeLevelPaid > requiredFeeLevel && requiredFeeLevel >
baseLevel)
1183 sandbox.
apply(view);
1195 *tx, flags, view, sleAccount, accountIter, replacedTxIter, lock)};
1201 return {ter,
false};
1208 if (!replacedTxIter &&
isFull())
1210 auto lastRIter =
byFee_.rbegin();
1211 while (lastRIter !=
byFee_.rend() && lastRIter->account == account)
1215 if (lastRIter ==
byFee_.rend())
1225 <<
" would kick a transaction from the same account ("
1226 << account <<
") out of the queue.";
1229 auto const& endAccount =
byAccount_.
at(lastRIter->account);
1230 auto endEffectiveFeeLevel = [&]() {
1234 if (lastRIter->feeLevel > feeLevelPaid ||
1235 endAccount.transactions.size() == 1)
1236 return lastRIter->feeLevel;
1240 endAccount.transactions.begin(),
1241 endAccount.transactions.end(),
1243 [&](
auto const& total,
1247 txn.second.feeLevel / endAccount.transactions.size();
1249 txn.second.feeLevel % endAccount.transactions.size();
1250 if (total.first >= max - next || total.second >= max - mod)
1251 return {max, FeeLevel64{0}};
1253 return {total.first + next, total.second + mod};
1255 return endTotal.first +
1256 endTotal.second / endAccount.transactions.size();
1258 if (feeLevelPaid > endEffectiveFeeLevel)
1262 auto dropRIter = endAccount.transactions.rbegin();
1263 assert(dropRIter->second.account == lastRIter->account);
1265 <<
"Removing last item of account " << lastRIter->account
1266 <<
" from queue with average fee of " << endEffectiveFeeLevel
1269 erase(byFee_.iterator_to(dropRIter->second));
1274 <<
"Queue is full, and transaction " << transactionID
1275 <<
" fee is lower than end item's account average fee";
1283 replacedTxIter = removeFromByFee(replacedTxIter, tx);
1286 if (!accountIsInQueue)
1291 byAccount_.emplace(account, TxQAccount(tx));
1303 auto& candidate = accountIter->second.add(
1307 byFee_.insert(candidate);
1308 JLOG(j_.
debug()) <<
"Added transaction " << candidate.txID
1309 <<
" with result " <<
transToken(pfresult.ter) <<
" from "
1310 << (accountIsInQueue ?
"existing" :
"new") <<
" account "
1311 << candidate.account <<
" to queue."
1312 <<
" Flags: " << flags;
1314 return {terQUEUED,
false};
1334 feeMetrics_.update(app, view, timeLeap, setup_);
1335 auto const& snapshot = feeMetrics_.getSnapshot();
1337 auto ledgerSeq = view.
info().
seq;
1341 snapshot.txnsExpected * setup_.ledgersInQueue, setup_.queueSizeMin);
1344 for (
auto candidateIter = byFee_.begin(); candidateIter != byFee_.end();)
1346 if (candidateIter->lastValid && *candidateIter->lastValid <= ledgerSeq)
1348 byAccount_.at(candidateIter->account).dropPenalty =
true;
1349 candidateIter =
erase(candidateIter);
1359 for (
auto txQAccountIter = byAccount_.begin();
1360 txQAccountIter != byAccount_.end();)
1362 if (txQAccountIter->second.empty())
1363 txQAccountIter = byAccount_.erase(txQAccountIter);
1407 auto ledgerChanged =
false;
1411 auto const metricsSnapshot = feeMetrics_.getSnapshot();
1413 for (
auto candidateIter = byFee_.begin(); candidateIter != byFee_.end();)
1415 auto& account = byAccount_.at(candidateIter->account);
1416 auto const beginIter = account.transactions.begin();
1417 if (candidateIter->seqProxy.isSeq() &&
1418 candidateIter->seqProxy > beginIter->first)
1424 <<
"Skipping queued transaction " << candidateIter->txID
1425 <<
" from account " << candidateIter->account
1426 <<
" as it is not the first.";
1430 auto const requiredFeeLevel =
1431 getRequiredFeeLevel(view,
tapNONE, metricsSnapshot, lock);
1432 auto const feeLevelPaid = candidateIter->feeLevel;
1433 JLOG(j_.
trace()) <<
"Queued transaction " << candidateIter->txID
1434 <<
" from account " << candidateIter->account
1435 <<
" has fee level of " << feeLevelPaid
1436 <<
" needs at least " << requiredFeeLevel;
1437 if (feeLevelPaid >= requiredFeeLevel)
1439 JLOG(j_.
trace()) <<
"Applying queued transaction "
1440 << candidateIter->txID <<
" to open ledger.";
1442 auto const [txnResult, didApply] =
1443 candidateIter->apply(app, view, j_);
1449 <<
"Queued transaction " << candidateIter->txID
1450 <<
" applied successfully with " <<
transToken(txnResult)
1451 <<
". Remove from queue.";
1453 candidateIter = eraseAndAdvance(candidateIter);
1454 ledgerChanged =
true;
1458 candidateIter->retriesRemaining <= 0)
1460 if (candidateIter->retriesRemaining <= 0)
1461 account.retryPenalty =
true;
1463 account.dropPenalty =
true;
1464 JLOG(j_.
debug()) <<
"Queued transaction " << candidateIter->txID
1466 <<
". Remove from queue.";
1467 candidateIter = eraseAndAdvance(candidateIter);
1471 JLOG(j_.
debug()) <<
"Queued transaction " << candidateIter->txID
1473 <<
". Leave in queue."
1474 <<
" Applied: " << didApply
1475 <<
". Flags: " << candidateIter->flags;
1476 if (account.retryPenalty && candidateIter->retriesRemaining > 2)
1477 candidateIter->retriesRemaining = 1;
1479 --candidateIter->retriesRemaining;
1480 candidateIter->lastResult = txnResult;
1481 if (account.dropPenalty && account.transactions.size() > 1 &&
1487 if (candidateIter->seqProxy.isTicket())
1492 <<
"Queue is nearly full, and transaction "
1493 << candidateIter->txID <<
" failed with "
1495 <<
". Removing ticketed tx from account "
1497 candidateIter = eraseAndAdvance(candidateIter);
1505 auto dropRIter = account.transactions.rbegin();
1507 dropRIter->second.account ==
1508 candidateIter->account);
1511 <<
"Queue is nearly full, and transaction "
1512 << candidateIter->txID <<
" failed with "
1514 <<
". Removing last item from account "
1516 auto endIter = byFee_.iterator_to(dropRIter->second);
1517 if (endIter != candidateIter)
1532 return ledgerChanged;
1542 return nextQueuableSeqImpl(sleAccount, lock);
1552 TxQ::nextQueuableSeqImpl(
1559 return SeqProxy::sequence(0);
1564 auto const accountIter = byAccount_.find((*sleAccount)[
sfAccount]);
1565 if (accountIter == byAccount_.end() ||
1566 accountIter->second.transactions.empty())
1574 TxQAccount::TxMap::const_iterator txIter = acctTxs.
lower_bound(acctSeqProx);
1576 if (txIter == acctTxs.
end() || !txIter->first.isSeq() ||
1577 txIter->first != acctSeqProx)
1587 SeqProxy attempt = txIter->second.consequences().followingSeq();
1588 while (++txIter != acctTxs.
cend())
1590 if (attempt < txIter->first)
1593 attempt = txIter->second.consequences().followingSeq();
1599 TxQ::getRequiredFeeLevel(
1605 return FeeMetrics::scaleFeeLevel(metricsSnapshot, view);
1609 TxQ::tryDirectApply(
1617 auto const sleAccount = view.
read(keylet::account(account));
1624 SeqProxy const txSeqProx = tx->getSeqProxy();
1628 if (txSeqProx.
isSeq() && txSeqProx != acctSeqProx)
1631 FeeLevel64 const requiredFeeLevel = [
this, &view, flags]() {
1633 return getRequiredFeeLevel(
1634 view, flags, feeMetrics_.getSnapshot(), lock);
1641 if (feeLevelPaid >= requiredFeeLevel)
1646 <<
" to open ledger.";
1648 auto const [txnResult, didApply] =
1652 << (didApply ?
" applied successfully with "
1662 AccountMap::iterator accountIter = byAccount_.find(account);
1663 if (accountIter != byAccount_.end())
1666 if (
auto const existingIter =
1670 removeFromByFee(existingIter, tx);
1674 return {
std::pair(txnResult, didApply)};
1680 TxQ::removeFromByFee(
1684 if (replacedTxIter && tx)
1688 auto deleteIter = byFee_.iterator_to((*replacedTxIter)->second);
1689 assert(deleteIter != byFee_.end());
1690 assert(&(*replacedTxIter)->second == &*deleteIter);
1691 assert(deleteIter->seqProxy == tx->getSeqProxy());
1692 assert(deleteIter->account == (*tx)[
sfAccount]);
1696 return std::nullopt;
1706 auto const snapshot = feeMetrics_.getSnapshot();
1708 result.
txCount = byFee_.size();
1714 isFull() ? byFee_.rbegin()->feeLevel +
FeeLevel64{1} : baseLevel;
1715 result.
medFeeLevel = snapshot.escalationMultiplier;
1722 TxQ::getTxRequiredFeeAndSeq(
1730 auto const snapshot = feeMetrics_.getSnapshot();
1732 auto const fee = FeeMetrics::scaleFeeLevel(snapshot, view);
1734 auto const sle = view.
read(keylet::account(account));
1737 std::uint32_t const availableSeq = nextQueuableSeqImpl(sle, lock).value();
1739 return {
mulDiv(fee, baseFee, baseLevel).second, accountSeq, availableSeq};
1749 AccountMap::const_iterator
const accountIter{byAccount_.find(account)};
1751 if (accountIter == byAccount_.end() ||
1752 accountIter->second.transactions.empty())
1755 result.
reserve(accountIter->second.transactions.size());
1756 for (
auto const& tx : accountIter->second.transactions)
1770 result.
reserve(byFee_.size());
1772 for (
auto const& tx : byFee_)
1784 BOOST_ASSERT(
false);
1788 auto const metrics = getMetrics(*view);
1794 ret[jss::ledger_current_index] = view->info().seq;
1795 ret[jss::expected_ledger_size] =
std::to_string(metrics.txPerLedger);
1796 ret[jss::current_ledger_size] =
std::to_string(metrics.txInLedger);
1798 if (metrics.txQMaxSize)
1801 levels[jss::reference_level] = to_string(metrics.referenceFeeLevel);
1802 levels[jss::minimum_level] = to_string(metrics.minProcessingFeeLevel);
1803 levels[jss::median_level] = to_string(metrics.medFeeLevel);
1804 levels[jss::open_ledger_level] = to_string(metrics.openLedgerFeeLevel);
1806 auto const baseFee = view->fees().base;
1809 drops[jss::base_fee] =
1810 to_string(
toDrops(metrics.referenceFeeLevel, baseFee));
1811 drops[jss::minimum_fee] =
1812 to_string(
toDrops(metrics.minProcessingFeeLevel, baseFee));
1813 drops[jss::median_fee] = to_string(
toDrops(metrics.medFeeLevel, baseFee));
1814 drops[jss::open_ledger_fee] = to_string(
1826 auto const& section = config.
section(
"transaction_queue");
1831 "minimum_escalation_multiplier",
1835 "minimum_txn_in_ledger_standalone",
1839 if (
set(max,
"maximum_txn_in_ledger", section))
1843 Throw<std::runtime_error>(
1844 "The minimum number of low-fee transactions allowed "
1845 "per ledger (minimum_txn_in_ledger) exceeds "
1846 "the maximum number of low-fee transactions allowed per "
1847 "ledger (maximum_txn_in_ledger).");
1851 Throw<std::runtime_error>(
1852 "The minimum number of low-fee transactions allowed "
1853 "per ledger (minimum_txn_in_ledger_standalone) exceeds "
1854 "the maximum number of low-fee transactions allowed per "
1855 "ledger (maximum_txn_in_ledger).");
1868 "normal_consensus_increase_percent",
1878 "slow_consensus_decrease_percent",