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]() {
46 XRPAmount const mod = [&view, &tx, baseFee]() {
50 return def.signum() == 0 ?
XRPAmount{1} : def;
52 return std::pair{baseFee + mod, feePaid + mod};
55 assert(baseFee.signum() > 0);
56 if (effectiveFeePaid.signum() <= 0 || baseFee.signum() <= 0)
64 return feeLevelPaid.second;
80 return mulDiv(level, 100 + increasePercent, 100).second;
93 auto const txBegin = view.
txs.
begin();
94 auto const txEnd = view.
txs.
end();
101 assert(size == feeLevels.
size());
104 <<
"Ledger " << view.
info().
seq <<
" has " << size <<
" transactions. "
105 <<
"Ledgers are processing " << (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;
279 , feeLevel(feeLevel_)
283 , seqProxy(txn_->getSeqProxy())
284 , retriesRemaining(retriesAllowed)
286 , pfresult(pfresult_)
297 if (pfresult->rules != view.
rules() || pfresult->flags != flags)
299 JLOG(j.
debug()) <<
"Queued transaction " << txID
300 <<
" rules or flags have changed. Flags from "
301 << pfresult->flags <<
" to " << flags;
307 auto pcresult =
preclaim(*pfresult, app, view);
309 return doApply(pcresult, app, view);
321 TxQ::TxQAccount::TxMap::const_iterator
326 auto sameOrPrevIter = transactions.lower_bound(seqProx);
327 if (sameOrPrevIter != transactions.begin())
329 return sameOrPrevIter;
337 auto result = transactions.emplace(seqProx, std::move(txn));
338 assert(result.second);
339 assert(&result.first->second != &txn);
341 return result.first->second;
347 return transactions.erase(seqProx) != 0;
362 template <
size_t fillPercentage>
367 fillPercentage > 0 && fillPercentage <= 100,
"Invalid fill percentage");
377 AccountMap::iterator
const& accountIter,
408 TxQAccount const& txQAcct = accountIter->second;
415 if (txSeqProx.isTicket())
422 if (txSeqProx != nextQueuable)
438 TxQ::erase(TxQ::FeeMultiSet::const_iterator_type candidateIter)
439 -> FeeMultiSet::iterator_type
441 auto& txQAccount = byAccount_.at(candidateIter->account);
442 auto const seqProx = candidateIter->seqProxy;
443 auto const newCandidateIter = byFee_.erase(candidateIter);
447 auto const found = txQAccount.remove(seqProx);
451 return newCandidateIter;
456 -> FeeMultiSet::iterator_type
458 auto& txQAccount = byAccount_.at(candidateIter->account);
459 auto const accountIter =
460 txQAccount.transactions.find(candidateIter->seqProxy);
461 assert(accountIter != txQAccount.transactions.end());
467 candidateIter->seqProxy.isTicket() ||
468 accountIter == txQAccount.transactions.begin());
469 assert(byFee_.iterator_to(accountIter->second) == candidateIter);
470 auto const accountNextIter =
std::next(accountIter);
474 auto const feeNextIter =
std::next(candidateIter);
475 bool const useAccountNext =
476 accountNextIter != txQAccount.transactions.end() &&
477 accountNextIter->first > candidateIter->seqProxy &&
478 (feeNextIter == byFee_.end() ||
479 byFee_.value_comp()(accountNextIter->second, *feeNextIter));
481 auto const candidateNextIter = byFee_.erase(candidateIter);
482 txQAccount.transactions.erase(accountIter);
484 return useAccountNext ? byFee_.iterator_to(accountNextIter->second)
491 TxQ::TxQAccount::TxMap::const_iterator begin,
492 TxQ::TxQAccount::TxMap::const_iterator end) -> TxQAccount::TxMap::iterator
494 for (
auto it = begin; it != end; ++it)
496 byFee_.erase(byFee_.iterator_to(it->second));
498 return txQAccount.transactions.erase(begin, end);
506 TxQ::AccountMap::iterator
const& accountIter,
507 TxQAccount::TxMap::iterator beginTxIter,
516 assert(beginTxIter != accountIter->second.transactions.end());
520 auto endTxIter = accountIter->second.transactions.lower_bound(tSeqProx);
524 metricsSnapshot, view, txExtraCount, dist + 1);
528 if (!requiredTotalFeeLevel.first)
535 [](
auto const& total,
auto const& txn) {
536 return total + txn.second.feeLevel;
540 if (totalFeeLevelPaid < requiredTotalFeeLevel.second)
545 for (
auto it = beginTxIter; it != endTxIter; ++it)
547 auto txResult = it->second.apply(app, view, j);
552 --it->second.retriesRemaining;
553 it->second.lastResult = txResult.first;
574 if (!txResult.second)
577 return {txResult.first,
false};
582 auto const txResult =
doApply(
preclaim(pfresult, app, view), app, view);
588 endTxIter =
erase(accountIter->second, beginTxIter, endTxIter);
590 if (endTxIter != accountIter->second.transactions.end() &&
591 endTxIter->first == tSeqProx)
724 return *directApplied;
736 auto const pfresult =
preflight(app, view.
rules(), *tx, flags, j);
738 return {pfresult.ter,
false};
743 auto const sleAccount = view.
read(accountKey);
749 SeqProxy const txSeqProx = tx->getSeqProxy();
767 bool const accountIsInQueue = accountIter !=
byAccount_.
end();
780 TxQAccount::TxMap::iterator first_,
781 TxQAccount::TxMap::iterator end_)
782 : first(first_), end(end_)
786 TxQAccount::TxMap::iterator first;
787 TxQAccount::TxMap::iterator end;
794 if (!accountIsInQueue)
799 TxQAccount::TxMap::iterator
const firstIter =
802 if (firstIter == acctTxs.
end())
807 return {TxIter{firstIter, acctTxs.
end()}};
810 auto const acctTxCount{
818 if (pfresult.consequences.isBlocker())
826 <<
". Account has other queued transactions.";
829 if (acctTxCount == 1 && (txSeqProx != txIter->first->first))
834 <<
". Blocker does not replace lone queued transaction.";
841 auto replacedTxIter = [accountIsInQueue, &accountIter, txSeqProx]()
843 if (accountIsInQueue)
857 auto const requiredFeeLevel =
869 if (acctTxCount == 1 &&
870 txIter->first->second.consequences().isBlocker() &&
871 (txIter->first->first != txSeqProx))
885 TxQAccount::TxMap::iterator
const& existingIter = *replacedTxIter;
889 <<
"Found transaction in queue for account " << account
890 <<
" with " << txSeqProx <<
" new txn fee level is "
891 << feeLevelPaid <<
", old txn fee level is "
892 << existingIter->second.feeLevel
893 <<
", new txn needs fee level of " << requiredRetryLevel;
894 if (feeLevelPaid > requiredRetryLevel)
899 JLOG(
j_.
trace()) <<
"Removing transaction from queue "
900 << existingIter->second.txID <<
" in favor of "
908 <<
" in favor of queued " << existingIter->second.txID;
920 : applyView(&view, flags), openView(&applyView)
927 if (acctTxCount == 0)
932 if (txSeqProx.
isSeq())
934 if (acctSeqProx > txSeqProx)
936 if (acctSeqProx < txSeqProx)
945 TxQAccount const& txQAcct = accountIter->second;
947 if (acctSeqProx > txSeqProx)
956 bool requiresMultiTxn =
false;
957 if (acctTxCount > 1 || !replacedTxIter)
972 requiresMultiTxn =
true;
975 if (requiresMultiTxn)
989 TxQAccount::TxMap::const_iterator
const prevIter =
998 assert(prevIter != txIter->end);
999 if (prevIter == txIter->end || txSeqProx < prevIter->first)
1003 if (txSeqProx.
isSeq())
1005 if (txSeqProx < acctSeqProx)
1007 else if (txSeqProx > acctSeqProx)
1011 else if (!replacedTxIter)
1018 if (txSeqProx.
isSeq() &&
1028 for (
auto iter = txIter->first; iter != txIter->end; ++iter)
1033 if (iter->first != txSeqProx)
1035 totalFee += iter->second.consequences().fee();
1037 iter->second.consequences().potentialSpend();
1039 else if (
std::next(iter) != txIter->end)
1044 totalFee += pfresult.consequences.fee();
1045 potentialSpend += pfresult.consequences.potentialSpend();
1078 auto const balance = (*sleAccount)[
sfBalance].xrp();
1097 auto const base = view.
fees().
base;
1098 if (totalFee >= balance ||
1099 (reserve > 10 * base && totalFee >= reserve))
1103 <<
". Total fees in flight too high.";
1108 multiTxn.
emplace(view, flags);
1110 auto const sleBump = multiTxn->applyView.peek(accountKey);
1117 auto const potentialTotalSpend = totalFee +
1122 multiTxn->applyView.fees().base == 0));
1123 sleBump->setFieldAmount(
sfBalance, balance - potentialTotalSpend);
1146 auto const pcresult =
1147 preclaim(pfresult, app, multiTxn ? multiTxn->openView : view);
1148 if (!pcresult.likelyToClaimFee)
1149 return {pcresult.ter,
false};
1155 << account <<
" has fee level of " << feeLevelPaid
1156 <<
" needs at least " << requiredFeeLevel
1157 <<
" to get in the open ledger, which has "
1158 << view.txCount() <<
" entries.";
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 while (lastRIter !=
byFee_.rend() && lastRIter->account == account)
1229 if (lastRIter ==
byFee_.rend())
1239 <<
" would kick a transaction from the same account ("
1240 << account <<
") out of the queue.";
1243 auto const& endAccount =
byAccount_.
at(lastRIter->account);
1244 auto endEffectiveFeeLevel = [&]() {
1248 if (lastRIter->feeLevel > feeLevelPaid ||
1249 endAccount.transactions.size() == 1)
1250 return lastRIter->feeLevel;
1254 endAccount.transactions.begin(),
1255 endAccount.transactions.end(),
1257 [&](
auto const& total,
1261 txn.second.feeLevel / endAccount.transactions.size();
1263 txn.second.feeLevel % endAccount.transactions.size();
1264 if (total.first >= max - next || total.second >= max - mod)
1265 return {max, FeeLevel64{0}};
1267 return {total.first + next, total.second + mod};
1269 return endTotal.first +
1270 endTotal.second / endAccount.transactions.size();
1272 if (feeLevelPaid > endEffectiveFeeLevel)
1276 auto dropRIter = endAccount.transactions.rbegin();
1277 assert(dropRIter->second.account == lastRIter->account);
1279 <<
"Removing last item of account " << lastRIter->account
1280 <<
" from queue with average fee of " << endEffectiveFeeLevel
1283 erase(byFee_.iterator_to(dropRIter->second));
1288 <<
"Queue is full, and transaction " << transactionID
1289 <<
" fee is lower than end item's account average fee";
1297 replacedTxIter = removeFromByFee(replacedTxIter, tx);
1300 if (!accountIsInQueue)
1305 byAccount_.emplace(account, TxQAccount(tx));
1317 auto& candidate = accountIter->second.add(
1321 byFee_.insert(candidate);
1322 JLOG(j_.
debug()) <<
"Added transaction " << candidate.txID
1323 <<
" with result " <<
transToken(pfresult.ter) <<
" from "
1324 << (accountIsInQueue ?
"existing" :
"new") <<
" account "
1325 << candidate.account <<
" to queue."
1326 <<
" Flags: " << flags;
1328 return {terQUEUED,
false};
1348 feeMetrics_.update(app, view, timeLeap, setup_);
1349 auto const& snapshot = feeMetrics_.getSnapshot();
1351 auto ledgerSeq = view.
info().
seq;
1355 snapshot.txnsExpected * setup_.ledgersInQueue, setup_.queueSizeMin);
1358 for (
auto candidateIter = byFee_.begin(); candidateIter != byFee_.end();)
1360 if (candidateIter->lastValid && *candidateIter->lastValid <= ledgerSeq)
1362 byAccount_.at(candidateIter->account).dropPenalty =
true;
1363 candidateIter =
erase(candidateIter);
1373 for (
auto txQAccountIter = byAccount_.begin();
1374 txQAccountIter != byAccount_.end();)
1376 if (txQAccountIter->second.empty())
1377 txQAccountIter = byAccount_.erase(txQAccountIter);
1421 auto ledgerChanged =
false;
1425 auto const metricsSnapshot = feeMetrics_.getSnapshot();
1427 for (
auto candidateIter = byFee_.begin(); candidateIter != byFee_.end();)
1429 auto& account = byAccount_.at(candidateIter->account);
1430 auto const beginIter = account.transactions.begin();
1431 if (candidateIter->seqProxy.isSeq() &&
1432 candidateIter->seqProxy > beginIter->first)
1438 <<
"Skipping queued transaction " << candidateIter->txID
1439 <<
" from account " << candidateIter->account
1440 <<
" as it is not the first.";
1444 auto const requiredFeeLevel =
1445 getRequiredFeeLevel(view,
tapNONE, metricsSnapshot, lock);
1446 auto const feeLevelPaid = candidateIter->feeLevel;
1447 JLOG(j_.
trace()) <<
"Queued transaction " << candidateIter->txID
1448 <<
" from account " << candidateIter->account
1449 <<
" has fee level of " << feeLevelPaid
1450 <<
" needs at least " << requiredFeeLevel;
1451 if (feeLevelPaid >= requiredFeeLevel)
1453 JLOG(j_.
trace()) <<
"Applying queued transaction "
1454 << candidateIter->txID <<
" to open ledger.";
1456 auto const [txnResult, didApply] =
1457 candidateIter->apply(app, view, j_);
1463 <<
"Queued transaction " << candidateIter->txID
1464 <<
" applied successfully with " <<
transToken(txnResult)
1465 <<
". Remove from queue.";
1467 candidateIter = eraseAndAdvance(candidateIter);
1468 ledgerChanged =
true;
1472 candidateIter->retriesRemaining <= 0)
1474 if (candidateIter->retriesRemaining <= 0)
1475 account.retryPenalty =
true;
1477 account.dropPenalty =
true;
1478 JLOG(j_.
debug()) <<
"Queued transaction " << candidateIter->txID
1480 <<
". Remove from queue.";
1481 candidateIter = eraseAndAdvance(candidateIter);
1485 JLOG(j_.
debug()) <<
"Queued transaction " << candidateIter->txID
1487 <<
". Leave in queue."
1488 <<
" Applied: " << didApply
1489 <<
". Flags: " << candidateIter->flags;
1490 if (account.retryPenalty && candidateIter->retriesRemaining > 2)
1491 candidateIter->retriesRemaining = 1;
1493 --candidateIter->retriesRemaining;
1494 candidateIter->lastResult = txnResult;
1495 if (account.dropPenalty && account.transactions.size() > 1 &&
1501 if (candidateIter->seqProxy.isTicket())
1506 <<
"Queue is nearly full, and transaction "
1507 << candidateIter->txID <<
" failed with "
1509 <<
". Removing ticketed tx from account "
1511 candidateIter = eraseAndAdvance(candidateIter);
1519 auto dropRIter = account.transactions.rbegin();
1521 dropRIter->second.account ==
1522 candidateIter->account);
1525 <<
"Queue is nearly full, and transaction "
1526 << candidateIter->txID <<
" failed with "
1528 <<
". Removing last item from account "
1530 auto endIter = byFee_.iterator_to(dropRIter->second);
1531 if (endIter != candidateIter)
1552 auto const startingSize = byFee_.
size();
1553 assert(parentHash != parentHash_);
1554 parentHash_ = parentHash;
1566 MaybeTx::parentHashComp = parentHash;
1568 for (
auto& [_, account] : byAccount_)
1570 for (
auto& [_, candidate] : account.transactions)
1572 byFee_.insert(candidate);
1575 assert(byFee_.size() == startingSize);
1577 return ledgerChanged;
1587 return nextQueuableSeqImpl(sleAccount, lock);
1597 TxQ::nextQueuableSeqImpl(
1604 return SeqProxy::sequence(0);
1609 auto const accountIter = byAccount_.find((*sleAccount)[
sfAccount]);
1610 if (accountIter == byAccount_.end() ||
1611 accountIter->second.transactions.empty())
1619 TxQAccount::TxMap::const_iterator txIter = acctTxs.
lower_bound(acctSeqProx);
1621 if (txIter == acctTxs.
end() || !txIter->first.isSeq() ||
1622 txIter->first != acctSeqProx)
1632 SeqProxy attempt = txIter->second.consequences().followingSeq();
1633 while (++txIter != acctTxs.
cend())
1635 if (attempt < txIter->first)
1638 attempt = txIter->second.consequences().followingSeq();
1644 TxQ::getRequiredFeeLevel(
1650 return FeeMetrics::scaleFeeLevel(metricsSnapshot, view);
1654 TxQ::tryDirectApply(
1662 auto const sleAccount = view.
read(keylet::account(account));
1669 SeqProxy const txSeqProx = tx->getSeqProxy();
1673 if (txSeqProx.
isSeq() && txSeqProx != acctSeqProx)
1676 FeeLevel64 const requiredFeeLevel = [
this, &view, flags]() {
1678 return getRequiredFeeLevel(
1679 view, flags, feeMetrics_.getSnapshot(), lock);
1686 if (feeLevelPaid >= requiredFeeLevel)
1691 <<
" to open ledger.";
1693 auto const [txnResult, didApply] =
1697 << (didApply ?
" applied successfully with "
1707 AccountMap::iterator accountIter = byAccount_.find(account);
1708 if (accountIter != byAccount_.end())
1711 if (
auto const existingIter =
1715 removeFromByFee(existingIter, tx);
1719 return {
std::pair(txnResult, didApply)};
1725 TxQ::removeFromByFee(
1729 if (replacedTxIter && tx)
1733 auto deleteIter = byFee_.iterator_to((*replacedTxIter)->second);
1734 assert(deleteIter != byFee_.end());
1735 assert(&(*replacedTxIter)->second == &*deleteIter);
1736 assert(deleteIter->seqProxy == tx->getSeqProxy());
1737 assert(deleteIter->account == (*tx)[
sfAccount]);
1741 return std::nullopt;
1751 auto const snapshot = feeMetrics_.getSnapshot();
1753 result.
txCount = byFee_.size();
1759 isFull() ? byFee_.rbegin()->feeLevel +
FeeLevel64{1} : baseLevel;
1760 result.
medFeeLevel = snapshot.escalationMultiplier;
1767 TxQ::getTxRequiredFeeAndSeq(
1775 auto const snapshot = feeMetrics_.getSnapshot();
1777 auto const fee = FeeMetrics::scaleFeeLevel(snapshot, view);
1779 auto const sle = view.
read(keylet::account(account));
1782 std::uint32_t const availableSeq = nextQueuableSeqImpl(sle, lock).value();
1784 return {
mulDiv(fee, baseFee, baseLevel).second, accountSeq, availableSeq};
1794 AccountMap::const_iterator
const accountIter{byAccount_.find(account)};
1796 if (accountIter == byAccount_.end() ||
1797 accountIter->second.transactions.empty())
1800 result.
reserve(accountIter->second.transactions.size());
1801 for (
auto const& tx : accountIter->second.transactions)
1815 result.
reserve(byFee_.size());
1817 for (
auto const& tx : byFee_)
1829 BOOST_ASSERT(
false);
1833 auto const metrics = getMetrics(*view);
1839 ret[jss::ledger_current_index] = view->info().seq;
1840 ret[jss::expected_ledger_size] =
std::to_string(metrics.txPerLedger);
1841 ret[jss::current_ledger_size] =
std::to_string(metrics.txInLedger);
1843 if (metrics.txQMaxSize)
1846 levels[jss::reference_level] = to_string(metrics.referenceFeeLevel);
1847 levels[jss::minimum_level] = to_string(metrics.minProcessingFeeLevel);
1848 levels[jss::median_level] = to_string(metrics.medFeeLevel);
1849 levels[jss::open_ledger_level] = to_string(metrics.openLedgerFeeLevel);
1851 auto const baseFee = view->fees().base;
1855 auto const effectiveBaseFee = [&baseFee, &metrics]() {
1856 if (!baseFee && metrics.openLedgerFeeLevel != metrics.referenceFeeLevel)
1862 drops[jss::base_fee] = to_string(baseFee);
1863 drops[jss::median_fee] = to_string(
toDrops(metrics.medFeeLevel, baseFee));
1864 drops[jss::minimum_fee] = to_string(
toDrops(
1865 metrics.minProcessingFeeLevel,
1866 metrics.txCount >= metrics.txQMaxSize ? effectiveBaseFee : baseFee));
1867 auto openFee =
toDrops(metrics.openLedgerFeeLevel, effectiveBaseFee);
1868 if (effectiveBaseFee &&
1869 toFeeLevel(openFee, effectiveBaseFee) < metrics.openLedgerFeeLevel)
1871 drops[jss::open_ledger_fee] = to_string(openFee);
1882 auto const& section = config.
section(
"transaction_queue");
1887 "minimum_escalation_multiplier",
1891 "minimum_txn_in_ledger_standalone",
1895 if (
set(max,
"maximum_txn_in_ledger", section))
1899 Throw<std::runtime_error>(
1900 "The minimum number of low-fee transactions allowed "
1901 "per ledger (minimum_txn_in_ledger) exceeds "
1902 "the maximum number of low-fee transactions allowed per "
1903 "ledger (maximum_txn_in_ledger).");
1907 Throw<std::runtime_error>(
1908 "The minimum number of low-fee transactions allowed "
1909 "per ledger (minimum_txn_in_ledger_standalone) exceeds "
1910 "the maximum number of low-fee transactions allowed per "
1911 "ledger (maximum_txn_in_ledger).");
1924 "normal_consensus_increase_percent",
1934 "slow_consensus_decrease_percent",