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;
89 auto const txBegin = view.
txs.
begin();
90 auto const txEnd = view.
txs.
end();
97 assert(size == feeLevels.
size());
100 <<
"Ledger " << view.
info().
seq <<
" has " << size <<
" transactions. "
101 <<
"Ledgers are processing " << (timeLeap ?
"slowly" :
"as expected")
112 auto const upperLimit = std::max<std::uint64_t>(
126 auto const next = [&] {
154 (feeLevels[size / 2] + feeLevels[(size - 1) / 2] +
FeeLevel64{1}) /
204 return {
true, (x * (x + 1) * (2 * x + 1)) / 6};
208 static_assert(sumOfFirstSquares(1).first ==
true);
209 static_assert(sumOfFirstSquares(1).second == 1);
211 static_assert(sumOfFirstSquares(2).first ==
true);
212 static_assert(sumOfFirstSquares(2).second == 5);
214 static_assert(sumOfFirstSquares(0x1FFFFF).first ==
true,
"");
215 static_assert(sumOfFirstSquares(0x1FFFFF).second == 0x2AAAA8AAAAB00000ul,
"");
217 static_assert(sumOfFirstSquares(0x200000).first ==
false,
"");
219 sumOfFirstSquares(0x200000).second ==
240 auto const last =
current + seriesSize - 1;
259 return {sumNlast.first,
FeeLevel64{sumNlast.second}};
260 auto const totalFeeLevel =
mulDiv(
261 multiplier, sumNlast.second - sumNcurrent.second, target * target);
263 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);
470 auto const feeNextIter =
std::next(candidateIter);
471 bool const useAccountNext =
472 accountNextIter != txQAccount.transactions.end() &&
473 accountNextIter->first > candidateIter->seqProxy &&
474 (feeNextIter == byFee_.end() ||
475 byFee_.value_comp()(accountNextIter->second, *feeNextIter));
477 auto const candidateNextIter = byFee_.erase(candidateIter);
478 txQAccount.transactions.erase(accountIter);
480 return useAccountNext ? byFee_.iterator_to(accountNextIter->second)
487 TxQ::TxQAccount::TxMap::const_iterator begin,
488 TxQ::TxQAccount::TxMap::const_iterator end) -> TxQAccount::TxMap::iterator
490 for (
auto it = begin; it != end; ++it)
492 byFee_.erase(byFee_.iterator_to(it->second));
494 return txQAccount.transactions.erase(begin, end);
502 TxQ::AccountMap::iterator
const& accountIter,
503 TxQAccount::TxMap::iterator beginTxIter,
512 assert(beginTxIter != accountIter->second.transactions.end());
516 auto endTxIter = accountIter->second.transactions.lower_bound(tSeqProx);
520 metricsSnapshot, view, txExtraCount, dist + 1);
524 if (!requiredTotalFeeLevel.first)
531 [](
auto const& total,
auto const& txn) {
532 return total + txn.second.feeLevel;
536 if (totalFeeLevelPaid < requiredTotalFeeLevel.second)
541 for (
auto it = beginTxIter; it != endTxIter; ++it)
543 auto txResult = it->second.apply(app, view, j);
548 --it->second.retriesRemaining;
549 it->second.lastResult = txResult.first;
570 if (!txResult.second)
573 return {txResult.first,
false};
578 auto const txResult =
doApply(
preclaim(pfresult, app, view), app, view);
584 endTxIter =
erase(accountIter->second, beginTxIter, endTxIter);
586 if (endTxIter != accountIter->second.transactions.end() &&
587 endTxIter->first == tSeqProx)
720 return *directApplied;
732 auto const pfresult =
preflight(app, view.
rules(), *tx, flags, j);
734 return {pfresult.ter,
false};
739 auto const sleAccount = view.
read(accountKey);
745 SeqProxy const txSeqProx = tx->getSeqProxy();
763 bool const accountIsInQueue = accountIter !=
byAccount_.
end();
776 TxQAccount::TxMap::iterator first_,
777 TxQAccount::TxMap::iterator end_)
778 : first(first_), end(end_)
782 TxQAccount::TxMap::iterator first;
783 TxQAccount::TxMap::iterator end;
790 if (!accountIsInQueue)
795 TxQAccount::TxMap::iterator
const firstIter =
798 if (firstIter == acctTxs.
end())
803 return {TxIter{firstIter, acctTxs.
end()}};
806 auto const acctTxCount{
814 if (pfresult.consequences.isBlocker())
822 <<
". Account has other queued transactions.";
825 if (acctTxCount == 1 && (txSeqProx != txIter->first->first))
830 <<
". Blocker does not replace lone queued transaction.";
837 auto replacedTxIter = [accountIsInQueue, &accountIter, txSeqProx]()
839 if (accountIsInQueue)
853 auto const requiredFeeLevel =
865 if (acctTxCount == 1 &&
866 txIter->first->second.consequences().isBlocker() &&
867 (txIter->first->first != txSeqProx))
881 TxQAccount::TxMap::iterator
const& existingIter = *replacedTxIter;
885 <<
"Found transaction in queue for account " << account
886 <<
" with " << txSeqProx <<
" new txn fee level is "
887 << feeLevelPaid <<
", old txn fee level is "
888 << existingIter->second.feeLevel
889 <<
", new txn needs fee level of " << requiredRetryLevel;
890 if (feeLevelPaid > requiredRetryLevel)
895 JLOG(
j_.
trace()) <<
"Removing transaction from queue "
896 << existingIter->second.txID <<
" in favor of "
904 <<
" in favor of queued " << existingIter->second.txID;
916 : applyView(&view, flags), openView(&applyView)
923 if (acctTxCount == 0)
928 if (txSeqProx.
isSeq())
930 if (acctSeqProx > txSeqProx)
932 if (acctSeqProx < txSeqProx)
941 TxQAccount const& txQAcct = accountIter->second;
943 if (acctSeqProx > txSeqProx)
952 bool requiresMultiTxn =
false;
953 if (acctTxCount > 1 || !replacedTxIter)
968 requiresMultiTxn =
true;
971 if (requiresMultiTxn)
985 TxQAccount::TxMap::const_iterator
const prevIter =
994 assert(prevIter != txIter->end);
995 if (prevIter == txIter->end || txSeqProx < prevIter->first)
999 if (txSeqProx.
isSeq())
1001 if (txSeqProx < acctSeqProx)
1003 else if (txSeqProx > acctSeqProx)
1007 else if (!replacedTxIter)
1014 if (txSeqProx.
isSeq() &&
1024 for (
auto iter = txIter->first; iter != txIter->end; ++iter)
1029 if (iter->first != txSeqProx)
1031 totalFee += iter->second.consequences().fee();
1033 iter->second.consequences().potentialSpend();
1035 else if (
std::next(iter) != txIter->end)
1040 totalFee += pfresult.consequences.fee();
1041 potentialSpend += pfresult.consequences.potentialSpend();
1074 auto const balance = (*sleAccount)[
sfBalance].xrp();
1087 if (totalFee >= balance || totalFee >= reserve)
1091 <<
". Total fees in flight too high.";
1096 multiTxn.
emplace(view, flags);
1098 auto const sleBump = multiTxn->applyView.peek(accountKey);
1105 auto const potentialTotalSpend = totalFee +
1107 assert(potentialTotalSpend >
XRPAmount{0});
1108 sleBump->setFieldAmount(
sfBalance, balance - potentialTotalSpend);
1131 auto const pcresult =
1132 preclaim(pfresult, app, multiTxn ? multiTxn->openView : view);
1133 if (!pcresult.likelyToClaimFee)
1134 return {pcresult.ter,
false};
1140 << account <<
" has fee level of " << feeLevelPaid
1141 <<
" needs at least " << requiredFeeLevel
1142 <<
" to get in the open ledger, which has "
1143 << view.txCount() <<
" entries.";
1164 feeLevelPaid > requiredFeeLevel && requiredFeeLevel >
baseLevel)
1182 sandbox.
apply(view);
1194 *tx, flags, view, sleAccount, accountIter, replacedTxIter, lock)};
1200 return {ter,
false};
1207 if (!replacedTxIter &&
isFull())
1209 auto lastRIter =
byFee_.rbegin();
1210 while (lastRIter !=
byFee_.rend() && lastRIter->account == account)
1214 if (lastRIter ==
byFee_.rend())
1224 <<
" would kick a transaction from the same account ("
1225 << account <<
") out of the queue.";
1228 auto const& endAccount =
byAccount_.
at(lastRIter->account);
1229 auto endEffectiveFeeLevel = [&]() {
1233 if (lastRIter->feeLevel > feeLevelPaid ||
1234 endAccount.transactions.size() == 1)
1235 return lastRIter->feeLevel;
1239 endAccount.transactions.begin(),
1240 endAccount.transactions.end(),
1242 [&](
auto const& total,
1246 txn.second.feeLevel / endAccount.transactions.size();
1248 txn.second.feeLevel % endAccount.transactions.size();
1249 if (total.first >= max - next || total.second >= max - mod)
1250 return {max, FeeLevel64{0}};
1252 return {total.first + next, total.second + mod};
1254 return endTotal.first +
1255 endTotal.second / endAccount.transactions.size();
1257 if (feeLevelPaid > endEffectiveFeeLevel)
1261 auto dropRIter = endAccount.transactions.rbegin();
1262 assert(dropRIter->second.account == lastRIter->account);
1264 <<
"Removing last item of account " << lastRIter->account
1265 <<
" from queue with average fee of " << endEffectiveFeeLevel
1268 erase(byFee_.iterator_to(dropRIter->second));
1273 <<
"Queue is full, and transaction " << transactionID
1274 <<
" fee is lower than end item's account average fee";
1282 replacedTxIter = removeFromByFee(replacedTxIter, tx);
1285 if (!accountIsInQueue)
1290 byAccount_.emplace(account, TxQAccount(tx));
1302 auto& candidate = accountIter->second.add(
1306 byFee_.insert(candidate);
1307 JLOG(j_.
debug()) <<
"Added transaction " << candidate.txID
1308 <<
" with result " <<
transToken(pfresult.ter) <<
" from "
1309 << (accountIsInQueue ?
"existing" :
"new") <<
" account "
1310 << candidate.account <<
" to queue."
1311 <<
" Flags: " << flags;
1313 return {terQUEUED,
false};
1333 feeMetrics_.update(app, view, timeLeap, setup_);
1334 auto const& snapshot = feeMetrics_.getSnapshot();
1336 auto ledgerSeq = view.
info().
seq;
1340 snapshot.txnsExpected * setup_.ledgersInQueue, setup_.queueSizeMin);
1343 for (
auto candidateIter = byFee_.begin(); candidateIter != byFee_.end();)
1345 if (candidateIter->lastValid && *candidateIter->lastValid <= ledgerSeq)
1347 byAccount_.at(candidateIter->account).dropPenalty =
true;
1348 candidateIter =
erase(candidateIter);
1358 for (
auto txQAccountIter = byAccount_.begin();
1359 txQAccountIter != byAccount_.end();)
1361 if (txQAccountIter->second.empty())
1362 txQAccountIter = byAccount_.erase(txQAccountIter);
1406 auto ledgerChanged =
false;
1410 auto const metricsSnapshot = feeMetrics_.getSnapshot();
1412 for (
auto candidateIter = byFee_.begin(); candidateIter != byFee_.end();)
1414 auto& account = byAccount_.at(candidateIter->account);
1415 auto const beginIter = account.transactions.begin();
1416 if (candidateIter->seqProxy.isSeq() &&
1417 candidateIter->seqProxy > beginIter->first)
1423 <<
"Skipping queued transaction " << candidateIter->txID
1424 <<
" from account " << candidateIter->account
1425 <<
" as it is not the first.";
1429 auto const requiredFeeLevel =
1430 getRequiredFeeLevel(view,
tapNONE, metricsSnapshot, lock);
1431 auto const feeLevelPaid = candidateIter->feeLevel;
1432 JLOG(j_.
trace()) <<
"Queued transaction " << candidateIter->txID
1433 <<
" from account " << candidateIter->account
1434 <<
" has fee level of " << feeLevelPaid
1435 <<
" needs at least " << requiredFeeLevel;
1436 if (feeLevelPaid >= requiredFeeLevel)
1438 JLOG(j_.
trace()) <<
"Applying queued transaction "
1439 << candidateIter->txID <<
" to open ledger.";
1441 auto const [txnResult, didApply] =
1442 candidateIter->apply(app, view, j_);
1448 <<
"Queued transaction " << candidateIter->txID
1449 <<
" applied successfully with " <<
transToken(txnResult)
1450 <<
". Remove from queue.";
1452 candidateIter = eraseAndAdvance(candidateIter);
1453 ledgerChanged =
true;
1457 candidateIter->retriesRemaining <= 0)
1459 if (candidateIter->retriesRemaining <= 0)
1460 account.retryPenalty =
true;
1462 account.dropPenalty =
true;
1463 JLOG(j_.
debug()) <<
"Queued transaction " << candidateIter->txID
1465 <<
". Remove from queue.";
1466 candidateIter = eraseAndAdvance(candidateIter);
1470 JLOG(j_.
debug()) <<
"Queued transaction " << candidateIter->txID
1472 <<
". Leave in queue."
1473 <<
" Applied: " << didApply
1474 <<
". Flags: " << candidateIter->flags;
1475 if (account.retryPenalty && candidateIter->retriesRemaining > 2)
1476 candidateIter->retriesRemaining = 1;
1478 --candidateIter->retriesRemaining;
1479 candidateIter->lastResult = txnResult;
1480 if (account.dropPenalty && account.transactions.size() > 1 &&
1486 if (candidateIter->seqProxy.isTicket())
1491 <<
"Queue is nearly full, and transaction "
1492 << candidateIter->txID <<
" failed with "
1494 <<
". Removing ticketed tx from account "
1496 candidateIter = eraseAndAdvance(candidateIter);
1504 auto dropRIter = account.transactions.rbegin();
1506 dropRIter->second.account ==
1507 candidateIter->account);
1510 <<
"Queue is nearly full, and transaction "
1511 << candidateIter->txID <<
" failed with "
1513 <<
". Removing last item from account "
1515 auto endIter = byFee_.iterator_to(dropRIter->second);
1516 if (endIter != candidateIter)
1537 auto const startingSize = byFee_.
size();
1538 assert(parentHash != parentHash_);
1539 parentHash_ = parentHash;
1551 MaybeTx::parentHashComp = parentHash;
1553 for (
auto& [_, account] : byAccount_)
1555 for (
auto& [_, candidate] : account.transactions)
1557 byFee_.insert(candidate);
1560 assert(byFee_.size() == startingSize);
1562 return ledgerChanged;
1572 return nextQueuableSeqImpl(sleAccount, lock);
1582 TxQ::nextQueuableSeqImpl(
1589 return SeqProxy::sequence(0);
1594 auto const accountIter = byAccount_.find((*sleAccount)[
sfAccount]);
1595 if (accountIter == byAccount_.end() ||
1596 accountIter->second.transactions.empty())
1604 TxQAccount::TxMap::const_iterator txIter = acctTxs.
lower_bound(acctSeqProx);
1606 if (txIter == acctTxs.
end() || !txIter->first.isSeq() ||
1607 txIter->first != acctSeqProx)
1617 SeqProxy attempt = txIter->second.consequences().followingSeq();
1618 while (++txIter != acctTxs.
cend())
1620 if (attempt < txIter->first)
1623 attempt = txIter->second.consequences().followingSeq();
1629 TxQ::getRequiredFeeLevel(
1635 return FeeMetrics::scaleFeeLevel(metricsSnapshot, view);
1639 TxQ::tryDirectApply(
1647 auto const sleAccount = view.
read(keylet::account(account));
1654 SeqProxy const txSeqProx = tx->getSeqProxy();
1658 if (txSeqProx.
isSeq() && txSeqProx != acctSeqProx)
1661 FeeLevel64 const requiredFeeLevel = [
this, &view, flags]() {
1663 return getRequiredFeeLevel(
1664 view, flags, feeMetrics_.getSnapshot(), lock);
1671 if (feeLevelPaid >= requiredFeeLevel)
1676 <<
" to open ledger.";
1678 auto const [txnResult, didApply] =
1682 << (didApply ?
" applied successfully with "
1692 AccountMap::iterator accountIter = byAccount_.find(account);
1693 if (accountIter != byAccount_.end())
1696 if (
auto const existingIter =
1700 removeFromByFee(existingIter, tx);
1704 return {
std::pair(txnResult, didApply)};
1710 TxQ::removeFromByFee(
1714 if (replacedTxIter && tx)
1718 auto deleteIter = byFee_.iterator_to((*replacedTxIter)->second);
1719 assert(deleteIter != byFee_.end());
1720 assert(&(*replacedTxIter)->second == &*deleteIter);
1721 assert(deleteIter->seqProxy == tx->getSeqProxy());
1722 assert(deleteIter->account == (*tx)[
sfAccount]);
1726 return std::nullopt;
1736 auto const snapshot = feeMetrics_.getSnapshot();
1738 result.
txCount = byFee_.size();
1744 isFull() ? byFee_.rbegin()->feeLevel +
FeeLevel64{1} : baseLevel;
1745 result.
medFeeLevel = snapshot.escalationMultiplier;
1752 TxQ::getTxRequiredFeeAndSeq(
1760 auto const snapshot = feeMetrics_.getSnapshot();
1762 auto const fee = FeeMetrics::scaleFeeLevel(snapshot, view);
1764 auto const sle = view.
read(keylet::account(account));
1767 std::uint32_t const availableSeq = nextQueuableSeqImpl(sle, lock).value();
1769 return {
mulDiv(fee, baseFee, baseLevel).second, accountSeq, availableSeq};
1779 AccountMap::const_iterator
const accountIter{byAccount_.find(account)};
1781 if (accountIter == byAccount_.end() ||
1782 accountIter->second.transactions.empty())
1785 result.
reserve(accountIter->second.transactions.size());
1786 for (
auto const& tx : accountIter->second.transactions)
1800 result.
reserve(byFee_.size());
1802 for (
auto const& tx : byFee_)
1814 BOOST_ASSERT(
false);
1818 auto const metrics = getMetrics(*view);
1824 ret[jss::ledger_current_index] = view->info().seq;
1825 ret[jss::expected_ledger_size] =
std::to_string(metrics.txPerLedger);
1826 ret[jss::current_ledger_size] =
std::to_string(metrics.txInLedger);
1828 if (metrics.txQMaxSize)
1831 levels[jss::reference_level] = to_string(metrics.referenceFeeLevel);
1832 levels[jss::minimum_level] = to_string(metrics.minProcessingFeeLevel);
1833 levels[jss::median_level] = to_string(metrics.medFeeLevel);
1834 levels[jss::open_ledger_level] = to_string(metrics.openLedgerFeeLevel);
1836 auto const baseFee = view->fees().base;
1839 drops[jss::base_fee] =
1840 to_string(
toDrops(metrics.referenceFeeLevel, baseFee));
1841 drops[jss::minimum_fee] =
1842 to_string(
toDrops(metrics.minProcessingFeeLevel, baseFee));
1843 drops[jss::median_fee] = to_string(
toDrops(metrics.medFeeLevel, baseFee));
1844 drops[jss::open_ledger_fee] = to_string(
1856 auto const& section = config.
section(
"transaction_queue");
1861 "minimum_escalation_multiplier",
1865 "minimum_txn_in_ledger_standalone",
1869 if (
set(max,
"maximum_txn_in_ledger", section))
1873 Throw<std::runtime_error>(
1874 "The minimum number of low-fee transactions allowed "
1875 "per ledger (minimum_txn_in_ledger) exceeds "
1876 "the maximum number of low-fee transactions allowed per "
1877 "ledger (maximum_txn_in_ledger).");
1881 Throw<std::runtime_error>(
1882 "The minimum number of low-fee transactions allowed "
1883 "per ledger (minimum_txn_in_ledger_standalone) exceeds "
1884 "the maximum number of low-fee transactions allowed per "
1885 "ledger (maximum_txn_in_ledger).");
1898 "normal_consensus_increase_percent",
1908 "slow_consensus_decrease_percent",