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;
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,
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);
472 auto const feeNextIter =
std::next(candidateIter);
473 bool const useAccountNext =
474 accountNextIter != txQAccount.transactions.end() &&
475 accountNextIter->first > candidateIter->seqProxy &&
476 (feeNextIter == byFee_.end() ||
477 byFee_.value_comp()(accountNextIter->second, *feeNextIter));
479 auto const candidateNextIter = byFee_.erase(candidateIter);
480 txQAccount.transactions.erase(accountIter);
482 return useAccountNext ? byFee_.iterator_to(accountNextIter->second)
489 TxQ::TxQAccount::TxMap::const_iterator begin,
490 TxQ::TxQAccount::TxMap::const_iterator end) -> TxQAccount::TxMap::iterator
492 for (
auto it = begin; it != end; ++it)
494 byFee_.erase(byFee_.iterator_to(it->second));
496 return txQAccount.transactions.erase(begin, end);
504 TxQ::AccountMap::iterator
const& accountIter,
505 TxQAccount::TxMap::iterator beginTxIter,
514 assert(beginTxIter != accountIter->second.transactions.end());
518 auto endTxIter = accountIter->second.transactions.lower_bound(tSeqProx);
522 metricsSnapshot, view, txExtraCount, dist + 1);
526 if (!requiredTotalFeeLevel.first)
533 [](
auto const& total,
auto const& txn) {
534 return total + txn.second.feeLevel;
538 if (totalFeeLevelPaid < requiredTotalFeeLevel.second)
543 for (
auto it = beginTxIter; it != endTxIter; ++it)
545 auto txResult = it->second.apply(app, view, j);
550 --it->second.retriesRemaining;
551 it->second.lastResult = txResult.first;
572 if (!txResult.second)
575 return {txResult.first,
false};
580 auto const txResult =
doApply(
preclaim(pfresult, app, view), app, view);
586 endTxIter =
erase(accountIter->second, beginTxIter, endTxIter);
588 if (endTxIter != accountIter->second.transactions.end() &&
589 endTxIter->first == tSeqProx)
722 return *directApplied;
734 auto const pfresult =
preflight(app, view.
rules(), *tx, flags, j);
736 return {pfresult.ter,
false};
741 auto const sleAccount = view.
read(accountKey);
747 SeqProxy const txSeqProx = tx->getSeqProxy();
765 bool const accountIsInQueue = accountIter !=
byAccount_.
end();
778 TxQAccount::TxMap::iterator first_,
779 TxQAccount::TxMap::iterator end_)
780 : first(first_), end(end_)
784 TxQAccount::TxMap::iterator first;
785 TxQAccount::TxMap::iterator end;
792 if (!accountIsInQueue)
797 TxQAccount::TxMap::iterator
const firstIter =
800 if (firstIter == acctTxs.
end())
805 return {TxIter{firstIter, acctTxs.
end()}};
808 auto const acctTxCount{
816 if (pfresult.consequences.isBlocker())
824 <<
". Account has other queued transactions.";
827 if (acctTxCount == 1 && (txSeqProx != txIter->first->first))
832 <<
". Blocker does not replace lone queued transaction.";
839 auto replacedTxIter = [accountIsInQueue, &accountIter, txSeqProx]()
841 if (accountIsInQueue)
855 auto const requiredFeeLevel =
867 if (acctTxCount == 1 &&
868 txIter->first->second.consequences().isBlocker() &&
869 (txIter->first->first != txSeqProx))
883 TxQAccount::TxMap::iterator
const& existingIter = *replacedTxIter;
887 <<
"Found transaction in queue for account " << account
888 <<
" with " << txSeqProx <<
" new txn fee level is "
889 << feeLevelPaid <<
", old txn fee level is "
890 << existingIter->second.feeLevel
891 <<
", new txn needs fee level of " << requiredRetryLevel;
892 if (feeLevelPaid > requiredRetryLevel)
897 JLOG(
j_.
trace()) <<
"Removing transaction from queue "
898 << existingIter->second.txID <<
" in favor of "
906 <<
" in favor of queued " << existingIter->second.txID;
918 : applyView(&view, flags), openView(&applyView)
925 if (acctTxCount == 0)
930 if (txSeqProx.
isSeq())
932 if (acctSeqProx > txSeqProx)
934 if (acctSeqProx < txSeqProx)
943 TxQAccount const& txQAcct = accountIter->second;
945 if (acctSeqProx > txSeqProx)
954 bool requiresMultiTxn =
false;
955 if (acctTxCount > 1 || !replacedTxIter)
970 requiresMultiTxn =
true;
973 if (requiresMultiTxn)
987 TxQAccount::TxMap::const_iterator
const prevIter =
996 assert(prevIter != txIter->end);
997 if (prevIter == txIter->end || txSeqProx < prevIter->first)
1001 if (txSeqProx.
isSeq())
1003 if (txSeqProx < acctSeqProx)
1005 else if (txSeqProx > acctSeqProx)
1009 else if (!replacedTxIter)
1016 if (txSeqProx.
isSeq() &&
1026 for (
auto iter = txIter->first; iter != txIter->end; ++iter)
1031 if (iter->first != txSeqProx)
1033 totalFee += iter->second.consequences().fee();
1035 iter->second.consequences().potentialSpend();
1037 else if (
std::next(iter) != txIter->end)
1042 totalFee += pfresult.consequences.fee();
1043 potentialSpend += pfresult.consequences.potentialSpend();
1076 auto const balance = (*sleAccount)[
sfBalance].xrp();
1089 if (totalFee >= balance || totalFee >= reserve)
1093 <<
". Total fees in flight too high.";
1098 multiTxn.
emplace(view, flags);
1100 auto const sleBump = multiTxn->applyView.peek(accountKey);
1107 auto const potentialTotalSpend = totalFee +
1109 assert(potentialTotalSpend >
XRPAmount{0});
1110 sleBump->setFieldAmount(
sfBalance, balance - potentialTotalSpend);
1133 auto const pcresult =
1134 preclaim(pfresult, app, multiTxn ? multiTxn->openView : view);
1135 if (!pcresult.likelyToClaimFee)
1136 return {pcresult.ter,
false};
1142 << account <<
" has fee level of " << feeLevelPaid
1143 <<
" needs at least " << requiredFeeLevel
1144 <<
" to get in the open ledger, which has "
1145 << view.txCount() <<
" entries.";
1166 feeLevelPaid > requiredFeeLevel && requiredFeeLevel >
baseLevel)
1184 sandbox.
apply(view);
1196 *tx, flags, view, sleAccount, accountIter, replacedTxIter, lock)};
1202 return {ter,
false};
1209 if (!replacedTxIter &&
isFull())
1211 auto lastRIter =
byFee_.rbegin();
1212 while (lastRIter !=
byFee_.rend() && lastRIter->account == account)
1216 if (lastRIter ==
byFee_.rend())
1226 <<
" would kick a transaction from the same account ("
1227 << account <<
") out of the queue.";
1230 auto const& endAccount =
byAccount_.
at(lastRIter->account);
1231 auto endEffectiveFeeLevel = [&]() {
1235 if (lastRIter->feeLevel > feeLevelPaid ||
1236 endAccount.transactions.size() == 1)
1237 return lastRIter->feeLevel;
1241 endAccount.transactions.begin(),
1242 endAccount.transactions.end(),
1244 [&](
auto const& total,
1248 txn.second.feeLevel / endAccount.transactions.size();
1250 txn.second.feeLevel % endAccount.transactions.size();
1251 if (total.first >= max - next || total.second >= max - mod)
1252 return {max, FeeLevel64{0}};
1254 return {total.first + next, total.second + mod};
1256 return endTotal.first +
1257 endTotal.second / endAccount.transactions.size();
1259 if (feeLevelPaid > endEffectiveFeeLevel)
1263 auto dropRIter = endAccount.transactions.rbegin();
1264 assert(dropRIter->second.account == lastRIter->account);
1266 <<
"Removing last item of account " << lastRIter->account
1267 <<
" from queue with average fee of " << endEffectiveFeeLevel
1270 erase(byFee_.iterator_to(dropRIter->second));
1275 <<
"Queue is full, and transaction " << transactionID
1276 <<
" fee is lower than end item's account average fee";
1284 replacedTxIter = removeFromByFee(replacedTxIter, tx);
1287 if (!accountIsInQueue)
1292 byAccount_.emplace(account, TxQAccount(tx));
1304 auto& candidate = accountIter->second.add(
1308 byFee_.insert(candidate);
1309 JLOG(j_.
debug()) <<
"Added transaction " << candidate.txID
1310 <<
" with result " <<
transToken(pfresult.ter) <<
" from "
1311 << (accountIsInQueue ?
"existing" :
"new") <<
" account "
1312 << candidate.account <<
" to queue."
1313 <<
" Flags: " << flags;
1315 return {terQUEUED,
false};
1335 feeMetrics_.update(app, view, timeLeap, setup_);
1336 auto const& snapshot = feeMetrics_.getSnapshot();
1338 auto ledgerSeq = view.
info().
seq;
1342 snapshot.txnsExpected * setup_.ledgersInQueue, setup_.queueSizeMin);
1345 for (
auto candidateIter = byFee_.begin(); candidateIter != byFee_.end();)
1347 if (candidateIter->lastValid && *candidateIter->lastValid <= ledgerSeq)
1349 byAccount_.at(candidateIter->account).dropPenalty =
true;
1350 candidateIter =
erase(candidateIter);
1360 for (
auto txQAccountIter = byAccount_.begin();
1361 txQAccountIter != byAccount_.end();)
1363 if (txQAccountIter->second.empty())
1364 txQAccountIter = byAccount_.erase(txQAccountIter);
1408 auto ledgerChanged =
false;
1412 auto const metricsSnapshot = feeMetrics_.getSnapshot();
1414 for (
auto candidateIter = byFee_.begin(); candidateIter != byFee_.end();)
1416 auto& account = byAccount_.at(candidateIter->account);
1417 auto const beginIter = account.transactions.begin();
1418 if (candidateIter->seqProxy.isSeq() &&
1419 candidateIter->seqProxy > beginIter->first)
1425 <<
"Skipping queued transaction " << candidateIter->txID
1426 <<
" from account " << candidateIter->account
1427 <<
" as it is not the first.";
1431 auto const requiredFeeLevel =
1432 getRequiredFeeLevel(view,
tapNONE, metricsSnapshot, lock);
1433 auto const feeLevelPaid = candidateIter->feeLevel;
1434 JLOG(j_.
trace()) <<
"Queued transaction " << candidateIter->txID
1435 <<
" from account " << candidateIter->account
1436 <<
" has fee level of " << feeLevelPaid
1437 <<
" needs at least " << requiredFeeLevel;
1438 if (feeLevelPaid >= requiredFeeLevel)
1440 JLOG(j_.
trace()) <<
"Applying queued transaction "
1441 << candidateIter->txID <<
" to open ledger.";
1443 auto const [txnResult, didApply] =
1444 candidateIter->apply(app, view, j_);
1450 <<
"Queued transaction " << candidateIter->txID
1451 <<
" applied successfully with " <<
transToken(txnResult)
1452 <<
". Remove from queue.";
1454 candidateIter = eraseAndAdvance(candidateIter);
1455 ledgerChanged =
true;
1459 candidateIter->retriesRemaining <= 0)
1461 if (candidateIter->retriesRemaining <= 0)
1462 account.retryPenalty =
true;
1464 account.dropPenalty =
true;
1465 JLOG(j_.
debug()) <<
"Queued transaction " << candidateIter->txID
1467 <<
". Remove from queue.";
1468 candidateIter = eraseAndAdvance(candidateIter);
1472 JLOG(j_.
debug()) <<
"Queued transaction " << candidateIter->txID
1474 <<
". Leave in queue."
1475 <<
" Applied: " << didApply
1476 <<
". Flags: " << candidateIter->flags;
1477 if (account.retryPenalty && candidateIter->retriesRemaining > 2)
1478 candidateIter->retriesRemaining = 1;
1480 --candidateIter->retriesRemaining;
1481 candidateIter->lastResult = txnResult;
1482 if (account.dropPenalty && account.transactions.size() > 1 &&
1488 if (candidateIter->seqProxy.isTicket())
1493 <<
"Queue is nearly full, and transaction "
1494 << candidateIter->txID <<
" failed with "
1496 <<
". Removing ticketed tx from account "
1498 candidateIter = eraseAndAdvance(candidateIter);
1506 auto dropRIter = account.transactions.rbegin();
1508 dropRIter->second.account ==
1509 candidateIter->account);
1512 <<
"Queue is nearly full, and transaction "
1513 << candidateIter->txID <<
" failed with "
1515 <<
". Removing last item from account "
1517 auto endIter = byFee_.iterator_to(dropRIter->second);
1518 if (endIter != candidateIter)
1539 auto const startingSize = byFee_.
size();
1540 assert(parentHash != parentHash_);
1541 parentHash_ = parentHash;
1553 MaybeTx::parentHashComp = parentHash;
1555 for (
auto& [_, account] : byAccount_)
1557 for (
auto& [_, candidate] : account.transactions)
1559 byFee_.insert(candidate);
1562 assert(byFee_.size() == startingSize);
1564 return ledgerChanged;
1574 return nextQueuableSeqImpl(sleAccount, lock);
1584 TxQ::nextQueuableSeqImpl(
1591 return SeqProxy::sequence(0);
1596 auto const accountIter = byAccount_.find((*sleAccount)[
sfAccount]);
1597 if (accountIter == byAccount_.end() ||
1598 accountIter->second.transactions.empty())
1606 TxQAccount::TxMap::const_iterator txIter = acctTxs.
lower_bound(acctSeqProx);
1608 if (txIter == acctTxs.
end() || !txIter->first.isSeq() ||
1609 txIter->first != acctSeqProx)
1619 SeqProxy attempt = txIter->second.consequences().followingSeq();
1620 while (++txIter != acctTxs.
cend())
1622 if (attempt < txIter->first)
1625 attempt = txIter->second.consequences().followingSeq();
1631 TxQ::getRequiredFeeLevel(
1637 return FeeMetrics::scaleFeeLevel(metricsSnapshot, view);
1641 TxQ::tryDirectApply(
1649 auto const sleAccount = view.
read(keylet::account(account));
1656 SeqProxy const txSeqProx = tx->getSeqProxy();
1660 if (txSeqProx.
isSeq() && txSeqProx != acctSeqProx)
1663 FeeLevel64 const requiredFeeLevel = [
this, &view, flags]() {
1665 return getRequiredFeeLevel(
1666 view, flags, feeMetrics_.getSnapshot(), lock);
1673 if (feeLevelPaid >= requiredFeeLevel)
1678 <<
" to open ledger.";
1680 auto const [txnResult, didApply] =
1684 << (didApply ?
" applied successfully with "
1694 AccountMap::iterator accountIter = byAccount_.find(account);
1695 if (accountIter != byAccount_.end())
1698 if (
auto const existingIter =
1702 removeFromByFee(existingIter, tx);
1706 return {
std::pair(txnResult, didApply)};
1712 TxQ::removeFromByFee(
1716 if (replacedTxIter && tx)
1720 auto deleteIter = byFee_.iterator_to((*replacedTxIter)->second);
1721 assert(deleteIter != byFee_.end());
1722 assert(&(*replacedTxIter)->second == &*deleteIter);
1723 assert(deleteIter->seqProxy == tx->getSeqProxy());
1724 assert(deleteIter->account == (*tx)[
sfAccount]);
1728 return std::nullopt;
1738 auto const snapshot = feeMetrics_.getSnapshot();
1740 result.
txCount = byFee_.size();
1746 isFull() ? byFee_.rbegin()->feeLevel +
FeeLevel64{1} : baseLevel;
1747 result.
medFeeLevel = snapshot.escalationMultiplier;
1754 TxQ::getTxRequiredFeeAndSeq(
1762 auto const snapshot = feeMetrics_.getSnapshot();
1764 auto const fee = FeeMetrics::scaleFeeLevel(snapshot, view);
1766 auto const sle = view.
read(keylet::account(account));
1769 std::uint32_t const availableSeq = nextQueuableSeqImpl(sle, lock).value();
1771 return {
mulDiv(fee, baseFee, baseLevel).second, accountSeq, availableSeq};
1781 AccountMap::const_iterator
const accountIter{byAccount_.find(account)};
1783 if (accountIter == byAccount_.end() ||
1784 accountIter->second.transactions.empty())
1787 result.
reserve(accountIter->second.transactions.size());
1788 for (
auto const& tx : accountIter->second.transactions)
1802 result.
reserve(byFee_.size());
1804 for (
auto const& tx : byFee_)
1816 BOOST_ASSERT(
false);
1820 auto const metrics = getMetrics(*view);
1826 ret[jss::ledger_current_index] = view->info().seq;
1827 ret[jss::expected_ledger_size] =
std::to_string(metrics.txPerLedger);
1828 ret[jss::current_ledger_size] =
std::to_string(metrics.txInLedger);
1830 if (metrics.txQMaxSize)
1833 levels[jss::reference_level] = to_string(metrics.referenceFeeLevel);
1834 levels[jss::minimum_level] = to_string(metrics.minProcessingFeeLevel);
1835 levels[jss::median_level] = to_string(metrics.medFeeLevel);
1836 levels[jss::open_ledger_level] = to_string(metrics.openLedgerFeeLevel);
1838 auto const baseFee = view->fees().base;
1841 drops[jss::base_fee] =
1842 to_string(
toDrops(metrics.referenceFeeLevel, baseFee));
1843 drops[jss::minimum_fee] =
1844 to_string(
toDrops(metrics.minProcessingFeeLevel, baseFee));
1845 drops[jss::median_fee] = to_string(
toDrops(metrics.medFeeLevel, baseFee));
1846 drops[jss::open_ledger_fee] = to_string(
1858 auto const& section = config.
section(
"transaction_queue");
1863 "minimum_escalation_multiplier",
1867 "minimum_txn_in_ledger_standalone",
1871 if (
set(max,
"maximum_txn_in_ledger", section))
1875 Throw<std::runtime_error>(
1876 "The minimum number of low-fee transactions allowed "
1877 "per ledger (minimum_txn_in_ledger) exceeds "
1878 "the maximum number of low-fee transactions allowed per "
1879 "ledger (maximum_txn_in_ledger).");
1883 Throw<std::runtime_error>(
1884 "The minimum number of low-fee transactions allowed "
1885 "per ledger (minimum_txn_in_ledger_standalone) exceeds "
1886 "the maximum number of low-fee transactions allowed per "
1887 "ledger (maximum_txn_in_ledger).");
1900 "normal_consensus_increase_percent",
1910 "slow_consensus_decrease_percent",