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());
101 JLOG(
j_.
debug()) <<
"Ledger " << view.
info().
seq <<
" has " << size
103 <<
"Ledgers are processing "
104 << (timeLeap ?
"slowly" :
"as expected")
115 auto const upperLimit = std::max<std::uint64_t>(
129 auto const next = [&] {
157 (feeLevels[size / 2] + feeLevels[(size - 1) / 2] +
FeeLevel64{1}) /
207 return {
true, (x * (x + 1) * (2 * x + 1)) / 6};
211 static_assert(sumOfFirstSquares(1).first ==
true);
212 static_assert(sumOfFirstSquares(1).second == 1);
214 static_assert(sumOfFirstSquares(2).first ==
true);
215 static_assert(sumOfFirstSquares(2).second == 5);
217 static_assert(sumOfFirstSquares(0x1FFFFF).first ==
true,
"");
218 static_assert(sumOfFirstSquares(0x1FFFFF).second == 0x2AAAA8AAAAB00000ul,
"");
220 static_assert(sumOfFirstSquares(0x200000).first ==
false,
"");
222 sumOfFirstSquares(0x200000).second ==
243 auto const last =
current + seriesSize - 1;
262 return {sumNlast.first,
FeeLevel64{sumNlast.second}};
263 auto const totalFeeLevel =
mulDiv(
264 multiplier, sumNlast.second - sumNcurrent.second, target * target);
266 return totalFeeLevel;
276 , feeLevel(feeLevel_)
280 , seqProxy(txn_->getSeqProxy())
281 , retriesRemaining(retriesAllowed)
283 , pfresult(pfresult_)
294 if (pfresult->rules != view.
rules() || pfresult->flags != flags)
296 JLOG(j.
debug()) <<
"Queued transaction " << txID
297 <<
" rules or flags have changed. Flags from "
298 << pfresult->flags <<
" to " << flags;
304 auto pcresult =
preclaim(*pfresult, app, view);
306 return doApply(pcresult, app, view);
318 TxQ::TxQAccount::TxMap::const_iterator
323 auto sameOrPrevIter = transactions.lower_bound(seqProx);
324 if (sameOrPrevIter != transactions.begin())
326 return sameOrPrevIter;
334 auto result = transactions.emplace(seqProx, std::move(txn));
335 assert(result.second);
336 assert(&result.first->second != &txn);
338 return result.first->second;
344 return transactions.erase(seqProx) != 0;
359 template <
size_t fillPercentage>
364 fillPercentage > 0 && fillPercentage <= 100,
"Invalid fill percentage");
374 AccountMap::iterator
const& accountIter,
405 TxQAccount const& txQAcct = accountIter->second;
412 if (txSeqProx.isTicket())
419 if (txSeqProx != nextQueuable)
435 TxQ::erase(TxQ::FeeMultiSet::const_iterator_type candidateIter)
436 -> FeeMultiSet::iterator_type
438 auto& txQAccount = byAccount_.at(candidateIter->account);
439 auto const seqProx = candidateIter->seqProxy;
440 auto const newCandidateIter = byFee_.erase(candidateIter);
444 auto const found = txQAccount.remove(seqProx);
448 return newCandidateIter;
453 -> FeeMultiSet::iterator_type
455 auto& txQAccount = byAccount_.at(candidateIter->account);
456 auto const accountIter =
457 txQAccount.transactions.find(candidateIter->seqProxy);
458 assert(accountIter != txQAccount.transactions.end());
464 candidateIter->seqProxy.isTicket() ||
465 accountIter == txQAccount.transactions.begin());
466 assert(byFee_.iterator_to(accountIter->second) == candidateIter);
467 auto const accountNextIter =
std::next(accountIter);
487 auto const feeNextIter =
std::next(candidateIter);
488 bool const useAccountNext =
489 accountNextIter != txQAccount.transactions.end() &&
490 accountNextIter->first > candidateIter->seqProxy &&
491 (feeNextIter == byFee_.end() ||
492 accountNextIter->second.feeLevel > feeNextIter->feeLevel);
494 auto const candidateNextIter = byFee_.erase(candidateIter);
495 txQAccount.transactions.erase(accountIter);
497 return useAccountNext ? byFee_.iterator_to(accountNextIter->second)
504 TxQ::TxQAccount::TxMap::const_iterator begin,
505 TxQ::TxQAccount::TxMap::const_iterator end) -> TxQAccount::TxMap::iterator
507 for (
auto it = begin; it != end; ++it)
509 byFee_.erase(byFee_.iterator_to(it->second));
511 return txQAccount.transactions.erase(begin, end);
519 TxQ::AccountMap::iterator
const& accountIter,
520 TxQAccount::TxMap::iterator beginTxIter,
529 assert(beginTxIter != accountIter->second.transactions.end());
533 auto endTxIter = accountIter->second.transactions.lower_bound(tSeqProx);
537 metricsSnapshot, view, txExtraCount, dist + 1);
541 if (!requiredTotalFeeLevel.first)
548 [](
auto const& total,
auto const& txn) {
549 return total + txn.second.feeLevel;
553 if (totalFeeLevelPaid < requiredTotalFeeLevel.second)
558 for (
auto it = beginTxIter; it != endTxIter; ++it)
560 auto txResult = it->second.apply(app, view, j);
565 --it->second.retriesRemaining;
566 it->second.lastResult = txResult.first;
587 if (!txResult.second)
590 return {txResult.first,
false};
595 auto const txResult =
doApply(
preclaim(pfresult, app, view), app, view);
601 endTxIter =
erase(accountIter->second, beginTxIter, endTxIter);
603 if (endTxIter != accountIter->second.transactions.end() &&
604 endTxIter->first == tSeqProx)
737 return *directApplied;
749 auto const pfresult =
preflight(app, view.
rules(), *tx, flags, j);
751 return {pfresult.ter,
false};
756 auto const sleAccount = view.
read(accountKey);
762 SeqProxy const txSeqProx = tx->getSeqProxy();
780 bool const accountIsInQueue = accountIter !=
byAccount_.
end();
793 TxQAccount::TxMap::iterator first_,
794 TxQAccount::TxMap::iterator end_)
795 : first(first_), end(end_)
799 TxQAccount::TxMap::iterator first;
800 TxQAccount::TxMap::iterator end;
807 if (!accountIsInQueue)
812 TxQAccount::TxMap::iterator
const firstIter =
815 if (firstIter == acctTxs.
end())
820 return {TxIter{firstIter, acctTxs.
end()}};
823 auto const acctTxCount{
831 if (pfresult.consequences.isBlocker())
839 <<
". Account has other queued transactions.";
842 if (acctTxCount == 1 && (txSeqProx != txIter->first->first))
847 <<
". Blocker does not replace lone queued transaction.";
854 auto replacedTxIter = [accountIsInQueue, &accountIter, txSeqProx]()
856 if (accountIsInQueue)
870 auto const requiredFeeLevel =
882 if (acctTxCount == 1 &&
883 txIter->first->second.consequences().isBlocker() &&
884 (txIter->first->first != txSeqProx))
898 TxQAccount::TxMap::iterator
const& existingIter = *replacedTxIter;
902 <<
"Found transaction in queue for account " << account
903 <<
" with " << txSeqProx <<
" new txn fee level is "
904 << feeLevelPaid <<
", old txn fee level is "
905 << existingIter->second.feeLevel
906 <<
", new txn needs fee level of " << requiredRetryLevel;
907 if (feeLevelPaid > requiredRetryLevel)
912 JLOG(
j_.
trace()) <<
"Removing transaction from queue "
913 << existingIter->second.txID <<
" in favor of "
921 <<
" in favor of queued " << existingIter->second.txID;
933 : applyView(&view, flags), openView(&applyView)
940 if (acctTxCount == 0)
945 if (txSeqProx.
isSeq())
947 if (acctSeqProx > txSeqProx)
949 if (acctSeqProx < txSeqProx)
958 TxQAccount const& txQAcct = accountIter->second;
960 if (acctSeqProx > txSeqProx)
969 bool requiresMultiTxn =
false;
970 if (acctTxCount > 1 || !replacedTxIter)
985 requiresMultiTxn =
true;
988 if (requiresMultiTxn)
1002 TxQAccount::TxMap::const_iterator
const prevIter =
1011 assert(prevIter != txIter->end);
1012 if (prevIter == txIter->end || txSeqProx < prevIter->first)
1016 if (txSeqProx.
isSeq())
1018 if (txSeqProx < acctSeqProx)
1020 else if (txSeqProx > acctSeqProx)
1024 else if (!replacedTxIter)
1031 if (txSeqProx.
isSeq() &&
1041 for (
auto iter = txIter->first; iter != txIter->end; ++iter)
1046 if (iter->first != txSeqProx)
1048 totalFee += iter->second.consequences().fee();
1050 iter->second.consequences().potentialSpend();
1052 else if (
std::next(iter) != txIter->end)
1057 totalFee += pfresult.consequences.fee();
1058 potentialSpend += pfresult.consequences.potentialSpend();
1091 auto const balance = (*sleAccount)[
sfBalance].xrp();
1104 if (totalFee >= balance || totalFee >= reserve)
1108 <<
". Total fees in flight too high.";
1113 multiTxn.
emplace(view, flags);
1115 auto const sleBump = multiTxn->applyView.peek(accountKey);
1122 auto const potentialTotalSpend = totalFee +
1124 assert(potentialTotalSpend >
XRPAmount{0});
1125 sleBump->setFieldAmount(
sfBalance, balance - potentialTotalSpend);
1148 auto const pcresult =
1149 preclaim(pfresult, app, multiTxn ? multiTxn->openView : view);
1150 if (!pcresult.likelyToClaimFee)
1151 return {pcresult.ter,
false};
1157 << account <<
" has fee level of " << feeLevelPaid
1158 <<
" needs at least " << requiredFeeLevel
1159 <<
" to get in the open ledger, which has "
1160 << view.txCount() <<
" entries.";
1182 feeLevelPaid > requiredFeeLevel && requiredFeeLevel >
baseLevel)
1200 sandbox.
apply(view);
1212 *tx, flags, view, sleAccount, accountIter, replacedTxIter, lock)};
1218 return {ter,
false};
1225 if (!replacedTxIter &&
isFull())
1227 auto lastRIter =
byFee_.rbegin();
1228 if (lastRIter->account == account)
1232 <<
" would kick a transaction from the same account ("
1233 << account <<
") out of the queue.";
1236 auto const& endAccount =
byAccount_.
at(lastRIter->account);
1237 auto endEffectiveFeeLevel = [&]() {
1241 if (lastRIter->feeLevel > feeLevelPaid ||
1242 endAccount.transactions.size() == 1)
1243 return lastRIter->feeLevel;
1247 endAccount.transactions.begin(),
1248 endAccount.transactions.end(),
1250 [&](
auto const& total,
1254 txn.second.feeLevel / endAccount.transactions.size();
1256 txn.second.feeLevel % endAccount.transactions.size();
1257 if (total.first >= max - next || total.second >= max - mod)
1258 return {max, FeeLevel64{0}};
1260 return {total.first + next, total.second + mod};
1262 return endTotal.first +
1263 endTotal.second / endAccount.transactions.size();
1265 if (feeLevelPaid > endEffectiveFeeLevel)
1269 auto dropRIter = endAccount.transactions.rbegin();
1270 assert(dropRIter->second.account == lastRIter->account);
1272 <<
"Removing last item of account " << lastRIter->account
1273 <<
" from queue with average fee of " << endEffectiveFeeLevel
1276 erase(byFee_.iterator_to(dropRIter->second));
1281 <<
"Queue is full, and transaction " << transactionID
1282 <<
" fee is lower than end item's account average fee";
1290 replacedTxIter = removeFromByFee(replacedTxIter, tx);
1293 if (!accountIsInQueue)
1298 byAccount_.emplace(account, TxQAccount(tx));
1313 auto& candidate = accountIter->second.add(
1317 byFee_.insert(candidate);
1318 JLOG(j_.
debug()) <<
"Added transaction " << candidate.txID
1319 <<
" with result " <<
transToken(pfresult.ter) <<
" from "
1320 << (accountIsInQueue ?
"existing" :
"new") <<
" account "
1321 << candidate.account <<
" to queue."
1322 <<
" Flags: " << flags;
1324 return {terQUEUED,
false};
1344 feeMetrics_.update(app, view, timeLeap, setup_);
1345 auto const& snapshot = feeMetrics_.getSnapshot();
1347 auto ledgerSeq = view.
info().
seq;
1351 snapshot.txnsExpected * setup_.ledgersInQueue, setup_.queueSizeMin);
1354 for (
auto candidateIter = byFee_.begin(); candidateIter != byFee_.end();)
1356 if (candidateIter->lastValid && *candidateIter->lastValid <= ledgerSeq)
1358 byAccount_.at(candidateIter->account).dropPenalty =
true;
1359 candidateIter =
erase(candidateIter);
1369 for (
auto txQAccountIter = byAccount_.begin();
1370 txQAccountIter != byAccount_.end();)
1372 if (txQAccountIter->second.empty())
1373 txQAccountIter = byAccount_.erase(txQAccountIter);
1417 auto ledgerChanged =
false;
1421 auto const metricsSnapshot = feeMetrics_.getSnapshot();
1423 for (
auto candidateIter = byFee_.begin(); candidateIter != byFee_.end();)
1425 auto& account = byAccount_.at(candidateIter->account);
1426 auto const beginIter = account.transactions.begin();
1427 if (candidateIter->seqProxy.isSeq() &&
1428 candidateIter->seqProxy > beginIter->first)
1434 <<
"Skipping queued transaction " << candidateIter->txID
1435 <<
" from account " << candidateIter->account
1436 <<
" as it is not the first.";
1440 auto const requiredFeeLevel =
1441 getRequiredFeeLevel(view,
tapNONE, metricsSnapshot, lock);
1442 auto const feeLevelPaid = candidateIter->feeLevel;
1443 JLOG(j_.
trace()) <<
"Queued transaction " << candidateIter->txID
1444 <<
" from account " << candidateIter->account
1445 <<
" has fee level of " << feeLevelPaid
1446 <<
" needs at least " << requiredFeeLevel;
1447 if (feeLevelPaid >= requiredFeeLevel)
1449 JLOG(j_.
trace()) <<
"Applying queued transaction "
1450 << candidateIter->txID <<
" to open ledger.";
1452 auto const [txnResult, didApply] =
1453 candidateIter->apply(app, view, j_);
1459 <<
"Queued transaction " << candidateIter->txID
1460 <<
" applied successfully with " <<
transToken(txnResult)
1461 <<
". Remove from queue.";
1463 candidateIter = eraseAndAdvance(candidateIter);
1464 ledgerChanged =
true;
1468 candidateIter->retriesRemaining <= 0)
1470 if (candidateIter->retriesRemaining <= 0)
1471 account.retryPenalty =
true;
1473 account.dropPenalty =
true;
1474 JLOG(j_.
debug()) <<
"Queued transaction " << candidateIter->txID
1476 <<
". Remove from queue.";
1477 candidateIter = eraseAndAdvance(candidateIter);
1481 JLOG(j_.
debug()) <<
"Queued transaction " << candidateIter->txID
1483 <<
". Leave in queue."
1484 <<
" Applied: " << didApply
1485 <<
". Flags: " << candidateIter->flags;
1486 if (account.retryPenalty && candidateIter->retriesRemaining > 2)
1487 candidateIter->retriesRemaining = 1;
1489 --candidateIter->retriesRemaining;
1490 candidateIter->lastResult = txnResult;
1491 if (account.dropPenalty && account.transactions.size() > 1 &&
1497 if (candidateIter->seqProxy.isTicket())
1502 <<
"Queue is nearly full, and transaction "
1503 << candidateIter->txID <<
" failed with "
1505 <<
". Removing ticketed tx from account "
1507 candidateIter = eraseAndAdvance(candidateIter);
1515 auto dropRIter = account.transactions.rbegin();
1517 dropRIter->second.account ==
1518 candidateIter->account);
1521 <<
"Queue is nearly full, and transaction "
1522 << candidateIter->txID <<
" failed with "
1524 <<
". Removing last item from account "
1526 auto endIter = byFee_.iterator_to(dropRIter->second);
1527 if (endIter != candidateIter)
1542 return ledgerChanged;
1552 return nextQueuableSeqImpl(sleAccount, lock);
1562 TxQ::nextQueuableSeqImpl(
1569 return SeqProxy::sequence(0);
1574 auto const accountIter = byAccount_.find((*sleAccount)[
sfAccount]);
1575 if (accountIter == byAccount_.end() ||
1576 accountIter->second.transactions.empty())
1584 TxQAccount::TxMap::const_iterator txIter = acctTxs.
lower_bound(acctSeqProx);
1586 if (txIter == acctTxs.
end() || !txIter->first.isSeq() ||
1587 txIter->first != acctSeqProx)
1597 SeqProxy attempt = txIter->second.consequences().followingSeq();
1598 while (++txIter != acctTxs.
cend())
1600 if (attempt < txIter->first)
1603 attempt = txIter->second.consequences().followingSeq();
1609 TxQ::getRequiredFeeLevel(
1616 FeeMetrics::scaleFeeLevel(metricsSnapshot, view);
1619 return std::max(feeLevel, byFee_.begin()->feeLevel);
1625 TxQ::tryDirectApply(
1633 auto const sleAccount = view.
read(keylet::account(account));
1640 SeqProxy const txSeqProx = tx->getSeqProxy();
1644 if (txSeqProx.
isSeq() && txSeqProx != acctSeqProx)
1647 FeeLevel64 const requiredFeeLevel = [
this, &view, flags]() {
1649 return getRequiredFeeLevel(
1650 view, flags, feeMetrics_.getSnapshot(), lock);
1657 if (feeLevelPaid >= requiredFeeLevel)
1662 <<
" to open ledger.";
1664 auto const [txnResult, didApply] =
1668 << (didApply ?
" applied successfully with "
1678 AccountMap::iterator accountIter = byAccount_.find(account);
1679 if (accountIter != byAccount_.end())
1682 if (
auto const existingIter =
1686 removeFromByFee(existingIter, tx);
1690 return {
std::pair(txnResult, didApply)};
1696 TxQ::removeFromByFee(
1700 if (replacedTxIter && tx)
1704 auto deleteIter = byFee_.iterator_to((*replacedTxIter)->second);
1705 assert(deleteIter != byFee_.end());
1706 assert(&(*replacedTxIter)->second == &*deleteIter);
1707 assert(deleteIter->seqProxy == tx->getSeqProxy());
1708 assert(deleteIter->account == (*tx)[
sfAccount]);
1712 return std::nullopt;
1722 auto const snapshot = feeMetrics_.getSnapshot();
1724 result.
txCount = byFee_.size();
1730 isFull() ? byFee_.rbegin()->feeLevel +
FeeLevel64{1} : baseLevel;
1731 result.
medFeeLevel = snapshot.escalationMultiplier;
1738 TxQ::getTxRequiredFeeAndSeq(
1746 auto const snapshot = feeMetrics_.getSnapshot();
1748 auto const fee = FeeMetrics::scaleFeeLevel(snapshot, view);
1750 auto const sle = view.
read(keylet::account(account));
1753 std::uint32_t const availableSeq = nextQueuableSeqImpl(sle, lock).value();
1755 return {
mulDiv(fee, baseFee, baseLevel).second, accountSeq, availableSeq};
1765 AccountMap::const_iterator
const accountIter{byAccount_.find(account)};
1767 if (accountIter == byAccount_.end() ||
1768 accountIter->second.transactions.empty())
1771 result.
reserve(accountIter->second.transactions.size());
1772 for (
auto const& tx : accountIter->second.transactions)
1786 result.
reserve(byFee_.size());
1788 for (
auto const& tx : byFee_)
1800 BOOST_ASSERT(
false);
1804 auto const metrics = getMetrics(*view);
1810 ret[jss::ledger_current_index] = view->info().seq;
1811 ret[jss::expected_ledger_size] =
std::to_string(metrics.txPerLedger);
1812 ret[jss::current_ledger_size] =
std::to_string(metrics.txInLedger);
1814 if (metrics.txQMaxSize)
1817 levels[jss::reference_level] = to_string(metrics.referenceFeeLevel);
1818 levels[jss::minimum_level] = to_string(metrics.minProcessingFeeLevel);
1819 levels[jss::median_level] = to_string(metrics.medFeeLevel);
1820 levels[jss::open_ledger_level] = to_string(metrics.openLedgerFeeLevel);
1822 auto const baseFee = view->fees().base;
1825 drops[jss::base_fee] =
1826 to_string(
toDrops(metrics.referenceFeeLevel, baseFee));
1827 drops[jss::minimum_fee] =
1828 to_string(
toDrops(metrics.minProcessingFeeLevel, baseFee));
1829 drops[jss::median_fee] = to_string(
toDrops(metrics.medFeeLevel, baseFee));
1830 drops[jss::open_ledger_fee] = to_string(
1842 auto const& section = config.
section(
"transaction_queue");
1847 "minimum_escalation_multiplier",
1851 "minimum_txn_in_ledger_standalone",
1855 if (
set(max,
"maximum_txn_in_ledger", section))
1859 Throw<std::runtime_error>(
1860 "The minimum number of low-fee transactions allowed "
1861 "per ledger (minimum_txn_in_ledger) exceeds "
1862 "the maximum number of low-fee transactions allowed per "
1863 "ledger (maximum_txn_in_ledger).");
1867 Throw<std::runtime_error>(
1868 "The minimum number of low-fee transactions allowed "
1869 "per ledger (minimum_txn_in_ledger_standalone) exceeds "
1870 "the maximum number of low-fee transactions allowed per "
1871 "ledger (maximum_txn_in_ledger).");
1884 "normal_consensus_increase_percent",
1894 "slow_consensus_decrease_percent",