20#include <xrpld/app/ledger/OrderBookDB.h>
21#include <xrpld/app/main/Application.h>
22#include <xrpld/app/paths/Pathfinder.h>
23#include <xrpld/app/paths/RippleCalc.h>
24#include <xrpld/app/paths/RippleLineCache.h>
25#include <xrpld/app/paths/detail/PathfinderUtils.h>
26#include <xrpld/core/JobQueue.h>
27#include <xrpld/ledger/PaymentSandbox.h>
28#include <xrpl/basics/Log.h>
29#include <xrpl/basics/join.h>
30#include <xrpl/json/to_string.h>
72constexpr std::size_t PATHFINDER_MAX_COMPLETE_PATHS = 1000;
74struct AccountCandidate
79 static const int highPriority = 10000;
83compareAccountCandidate(
85 AccountCandidate
const& first,
86 AccountCandidate
const& second)
88 if (first.priority < second.priority)
91 if (first.account > second.account)
94 return (first.priority ^ seq) < (second.priority ^ seq);
116static PathTable mPathTable;
123 for (
auto const& node : type)
154smallestUsefulAmount(STAmount
const& amount,
int maxPaths)
156 return divide(amount, STAmount(maxPaths + 2), amount.issue());
169 : mSrcAccount(uSrcAccount)
170 , mDstAccount(uDstAccount)
172 isXRP(saDstAmount.getIssuer()) ? uDstAccount
173 : saDstAmount.getIssuer())
174 , mDstAmount(saDstAmount)
175 , mSrcCurrency(uSrcCurrency)
176 , mSrcIssuer(uSrcIssuer)
177 , mSrcAmount(srcAmount.value_or(
STAmount(
186 , mLedger(cache->getLedger())
189 , j_(app.journal(
"Pathfinder"))
193 "ripple::Pathfinder::Pathfinder : valid inputs");
201 JLOG(
j_.
trace()) <<
"findPaths start";
205 JLOG(
j_.
debug()) <<
"Destination amount was zero.";
217 JLOG(
j_.
debug()) <<
"Tried to send to same issuer";
234 auto issuer = currencyIsXRP ?
AccountID() : account;
242 <<
" mSrcIssuer=" << issuerString;
246 JLOG(
j_.
debug()) <<
"findPaths< no ledger";
256 JLOG(
j_.
debug()) <<
"invalid source account";
263 JLOG(
j_.
debug()) <<
"Non-existent gateway";
273 JLOG(
j_.
debug()) <<
"New account not being funded in XRP ";
281 <<
"New account not getting enough funding: " <<
mDstAmount
290 if (bSrcXrp && bDstXrp)
293 JLOG(
j_.
debug()) <<
"XRP to XRP payment";
299 JLOG(
j_.
debug()) <<
"XRP to non-XRP payment";
305 JLOG(
j_.
debug()) <<
"non-XRP to XRP payment";
311 JLOG(
j_.
debug()) <<
"non-XRP to non-XRP - same currency";
317 JLOG(
j_.
debug()) <<
"non-XRP to non-XRP - cross currency";
322 for (
auto const& costedPath : mPathTable[paymentType])
324 if (continueCallback && !continueCallback())
327 if (costedPath.searchLevel <= searchLevel)
329 JLOG(
j_.
trace()) <<
"findPaths trying payment type " << paymentType;
350 uint64_t& qualityOut)
const
379 qualityOut =
getRate(rc.actualAmountOut, rc.actualAmountIn);
380 amountOut = rc.actualAmountOut;
389 mDstAmount - amountOut,
398 amountOut += rc.actualAmountOut;
405 JLOG(j_.
info()) <<
"checkpath: exception (" << e.
what() <<
") "
438 <<
"Default path contributes: " << rc.actualAmountIn;
444 <<
"Default path fails: " <<
transToken(rc.result());
449 JLOG(
j_.
debug()) <<
"Default path causes exception";
471 return path.size() == 1;
481 for (
auto it = path.begin() + 1; it != path.end(); ++it)
496 JLOG(
j_.
trace()) <<
"rankPaths with " << paths.
size() <<
" candidates, and "
497 << maxPaths <<
" maximum";
501 auto const saMinDstAmount = [&]() ->
STAmount {
505 return smallestUsefulAmount(
mDstAmount, maxPaths);
513 for (
int i = 0; i < paths.
size(); ++i)
515 if (continueCallback && !continueCallback())
517 auto const& currentPath = paths[i];
518 if (!currentPath.empty())
523 currentPath, saMinDstAmount, liquidity, uQuality);
527 <<
"findPaths: dropping : " <<
transToken(resultCode)
532 JLOG(
j_.
debug()) <<
"findPaths: quality: " << uQuality <<
": "
536 {uQuality, currentPath.size(), liquidity, i});
551 if (!convert_all_ && a.quality != b.quality)
552 return a.quality < b.quality;
555 if (a.liquidity != b.liquidity)
556 return a.liquidity > b.liquidity;
559 if (a.length != b.length)
560 return a.length < b.length;
563 return a.index > b.index;
570 STPath& fullLiquidityPath,
576 << extraPaths.
size() <<
" extras";
582 fullLiquidityPath.
empty(),
583 "ripple::Pathfinder::getBestPaths : first empty path result");
584 const bool issuerIsSender =
588 rankPaths(maxPaths, extraPaths, extraPathRanks, continueCallback);
598 auto extraPathsIterator = extraPathRanks.
begin();
601 extraPathsIterator != extraPathRanks.
end())
603 if (continueCallback && !continueCallback())
605 bool usePath =
false;
606 bool useExtraPath =
false;
610 else if (extraPathsIterator == extraPathRanks.
end())
612 else if (extraPathsIterator->quality < pathsIterator->quality)
614 else if (extraPathsIterator->quality > pathsIterator->quality)
616 else if (extraPathsIterator->liquidity > pathsIterator->liquidity)
618 else if (extraPathsIterator->liquidity < pathsIterator->liquidity)
627 auto& pathRank = usePath ? *pathsIterator : *extraPathsIterator;
630 : extraPaths[pathRank.index];
633 ++extraPathsIterator;
638 auto iPathsLeft = maxPaths - bestPaths.
size();
639 if (!(iPathsLeft > 0 || fullLiquidityPath.
empty()))
644 UNREACHABLE(
"ripple::Pathfinder::getBestPaths : path not found");
648 bool startsWithIssuer =
false;
650 if (!issuerIsSender && usePath)
653 if (
isDefaultPath(path) || path.front().getAccountID() != srcIssuer)
658 startsWithIssuer =
true;
661 if (iPathsLeft > 1 ||
662 (iPathsLeft > 0 && pathRank.liquidity >= remaining))
666 remaining -= pathRank.liquidity;
670 iPathsLeft == 0 && pathRank.liquidity >=
mDstAmount &&
671 fullLiquidityPath.
empty())
674 fullLiquidityPath = (startsWithIssuer ?
removeIssuer(path) : path);
675 JLOG(
j_.
debug()) <<
"Found extra full path: "
680 JLOG(
j_.
debug()) <<
"Skipping a non-filling path: "
685 if (remaining > beast::zero)
688 fullLiquidityPath.
empty(),
689 "ripple::Pathfinder::getBestPaths : second empty path result");
690 JLOG(
j_.
info()) <<
"Paths could not send " << remaining <<
" of "
695 JLOG(
j_.
debug()) <<
"findPaths: RESULTS: "
709 return matchingCurrency && matchingAccount;
721 Issue const issue(currency, account);
734 int aFlags = sleAccount->getFieldU32(sfFlags);
744 if (
auto const lines =
mRLCache->getRippleLines(account, direction))
746 for (
auto const& rspEntry : *lines)
748 if (currency != rspEntry.getLimit().getCurrency())
752 rspEntry.getBalance() <= beast::zero &&
753 (!rspEntry.getLimitPeer() ||
754 -rspEntry.getBalance() >= rspEntry.getLimitPeer() ||
755 (bAuthRequired && !rspEntry.getAuth())))
759 isDstCurrency && dstAccount == rspEntry.getAccountIDPeer())
763 else if (rspEntry.getNoRipplePeer())
767 else if (rspEntry.getFreezePeer())
789 JLOG(
j_.
debug()) <<
"addLink< on " << currentPaths.
size()
790 <<
" source(s), flags=" << addFlags;
791 for (
auto const& path : currentPaths)
793 if (continueCallback && !continueCallback())
795 addLink(path, incompletePaths, addFlags, continueCallback);
804 JLOG(
j_.
debug()) <<
"addPathsForType "
807 auto it =
mPaths.find(pathType);
812 if (pathType.
empty())
814 if (continueCallback && !continueCallback())
826 JLOG(
j_.
debug()) <<
"getPaths< adding onto '"
827 << pathTypeToString(parentPathType) <<
"' to get '"
828 << pathTypeToString(pathType) <<
"'";
833 auto nodeType = pathType.
back();
840 "ripple::Pathfinder::addPathsForType : empty paths");
883 <<
" complete paths added";
886 JLOG(
j_.
debug()) <<
"getPaths> " << pathsOut.
size()
887 <<
" partial paths found";
903 return sleRipple && (sleRipple->getFieldU32(sfFlags) & flag);
912 if (currentPath.
empty())
923 auto const& fromAccount = (currentPath.
size() == 1)
925 : (currentPath.
end() - 2)->getAccountID();
935 for (
auto const& p : pathSet)
945 const STPath& currentPath,
951 auto const& uEndCurrency = pathEnd.getCurrency();
952 auto const& uEndIssuer = pathEnd.getIssuerID();
953 auto const& uEndAccount = pathEnd.getAccountID();
954 bool const bOnXRP = uEndCurrency.isZero();
961 JLOG(
j_.
trace()) <<
"addLink< flags=" << addFlags <<
" onXRP=" << bOnXRP
972 JLOG(
j_.
trace()) <<
"complete path found ax: "
984 bool const bRequireAuth(
986 bool const bIsEndCurrency(
989 bool const bDestOnly(addFlags &
afAC_LAST);
991 if (
auto const lines =
mRLCache->getRippleLines(
996 auto& rippleLines = *lines;
998 AccountCandidates candidates;
999 candidates.reserve(rippleLines.size());
1001 for (
auto const& rs : rippleLines)
1003 if (continueCallback && !continueCallback())
1005 auto const& acct = rs.getAccountIDPeer();
1008 if (hasEffectiveDestination && (acct ==
mDstAccount))
1016 if (bDestOnly && !bToDestination)
1021 if ((uEndCurrency == rs.getLimit().getCurrency()) &&
1022 !currentPath.
hasSeen(acct, uEndCurrency, acct))
1026 if (rs.getBalance() <= beast::zero &&
1027 (!rs.getLimitPeer() ||
1028 -rs.getBalance() >= rs.getLimitPeer() ||
1029 (bRequireAuth && !rs.getAuth())))
1033 else if (bIsNoRippleOut && rs.getNoRipple())
1037 else if (bToDestination)
1043 if (!currentPath.
empty())
1046 <<
"complete path found ae: "
1053 else if (!bDestOnly)
1056 candidates.push_back(
1057 {AccountCandidate::highPriority, acct});
1075 candidates.push_back({
out, acct});
1080 if (!candidates.empty())
1086 compareAccountCandidate,
1088 std::placeholders::_1,
1089 std::placeholders::_2));
1091 int count = candidates.size();
1095 else if (count > 50)
1098 auto it = candidates.begin();
1099 while (count-- != 0)
1101 if (continueCallback && !continueCallback())
1110 currentPath, pathElement);
1118 JLOG(
j_.
warn()) <<
"Path ends on non-existent issuer";
1136 incompletePaths.
assembleAdd(currentPath, pathElement);
1141 bool bDestOnly = (addFlags &
afOB_LAST) != 0;
1143 {uEndCurrency, uEndIssuer});
1145 << books.size() <<
" books found from this currency/issuer";
1147 for (
auto const& book : books)
1149 if (continueCallback && !continueCallback())
1152 xrpAccount(), book.out.currency, book.out.account) &&
1157 STPath newPath(currentPath);
1159 if (book.out.currency.isZero())
1174 <<
"complete path found bx: "
1181 else if (!currentPath.
hasSeen(
1188 if ((newPath.
size() >= 2) &&
1189 (newPath.
back().isAccount()) &&
1190 (newPath[newPath.
size() - 2].isOffer()))
1211 if (hasEffectiveDestination &&
1223 <<
"complete path found ba: "
1248makePath(
char const*
string)
1291 auto& list = mPathTable[type];
1292 XRPL_ASSERT(list.empty(),
"ripple::fillPaths : empty paths");
1293 for (
auto& cost : costs)
1294 list.push_back({cost.cost, makePath(cost.path)});
Stream trace() const
Severity stream access functions.
virtual OrderBookDB & getOrderBookDB()=0
virtual JobQueue & getJobQueue()=0
A currency issued by an account.
std::unique_ptr< LoadEvent > makeLoadEvent(JobType t, std::string const &name)
Return a scoped LoadEvent.
bool isBookToXRP(Issue const &)
std::vector< Book > getBooksByTakerPays(Issue const &)
int getBookSize(Issue const &)
bool issueMatchesOrigin(Issue const &)
void rankPaths(int maxPaths, STPathSet const &paths, std::vector< PathRank > &rankedPaths, std::function< bool(void)> const &continueCallback)
bool findPaths(int searchLevel, std::function< bool(void)> const &continueCallback={})
std::optional< AccountID > mSrcIssuer
std::unique_ptr< LoadEvent > m_loadEvent
Pathfinder(std::shared_ptr< RippleLineCache > const &cache, AccountID const &srcAccount, AccountID const &dstAccount, Currency const &uSrcCurrency, std::optional< AccountID > const &uSrcIssuer, STAmount const &dstAmount, std::optional< STAmount > const &srcAmount, Application &app)
Construct a pathfinder without an issuer.
std::shared_ptr< RippleLineCache > mRLCache
TER getPathLiquidity(STPath const &path, STAmount const &minDstAmount, STAmount &amountOut, uint64_t &qualityOut) const
std::map< PathType, STPathSet > mPaths
static std::uint32_t const afADD_ACCOUNTS
void computePathRanks(int maxPaths, std::function< bool(void)> const &continueCallback={})
Compute the rankings of the paths.
STAmount mRemainingAmount
The amount remaining from mSrcAccount after the default liquidity has been removed.
bool isNoRippleOut(STPath const ¤tPath)
void addLinks(STPathSet const ¤tPaths, STPathSet &incompletePaths, int addFlags, std::function< bool(void)> const &continueCallback)
static std::uint32_t const afADD_BOOKS
int getPathsOut(Currency const ¤cy, AccountID const &account, LineDirection direction, bool isDestCurrency, AccountID const &dest, std::function< bool(void)> const &continueCallback)
bool isNoRipple(AccountID const &fromAccount, AccountID const &toAccount, Currency const ¤cy)
STPathSet & addPathsForType(PathType const &type, std::function< bool(void)> const &continueCallback)
static std::uint32_t const afOB_XRP
static void initPathTable()
hash_map< Issue, int > mPathsOutCountMap
std::vector< NodeType > PathType
std::vector< PathRank > mPathRanks
void addLink(STPath const ¤tPath, STPathSet &incompletePaths, int addFlags, std::function< bool(void)> const &continueCallback)
STPathSet getBestPaths(int maxPaths, STPath &fullLiquidityPath, STPathSet const &extraPaths, AccountID const &srcIssuer, std::function< bool(void)> const &continueCallback={})
static std::uint32_t const afAC_LAST
std::shared_ptr< ReadView const > mLedger
static std::uint32_t const afOB_LAST
A wrapper which makes credits unavailable to balances.
Currency const & getCurrency() const
std::string getFullText() const override
bool native() const noexcept
Currency const & getCurrency() const
AccountID const & getAccountID() const
void push_back(STPath const &e)
bool assembleAdd(STPath const &base, STPathElement const &tail)
Json::Value getJson(JsonOptions) const override
std::vector< STPath >::size_type size() const
std::vector< STPathElement >::const_iterator end() const
Json::Value getJson(JsonOptions) const
void push_back(STPathElement const &e)
bool hasSeen(AccountID const &account, Currency const ¤cy, AccountID const &issuer) const
std::vector< STPathElement >::size_type size() const
std::vector< STPathElement >::const_reference back() const
void emplace_back(Args &&... args)
static Output rippleCalculate(PaymentSandbox &view, STAmount const &saMaxAmountReq, STAmount const &saDstAmountReq, AccountID const &uDstAccountID, AccountID const &uSrcAccountID, STPathSet const &spsPaths, Logs &l, Input const *const pInputs=nullptr)
Keylet line(AccountID const &id0, AccountID const &id1, Currency const ¤cy) noexcept
The index of a trust line for a given currency.
Keylet account(AccountID const &id) noexcept
AccountID root.
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
base_uint< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
STAmount divide(STAmount const &amount, Rate const &rate)
STAmount convertAmount(STAmount const &amt, bool all)
bool isXRP(AccountID const &c)
AccountID const & xrpAccount()
Compute AccountID from public key.
bool convertAllCheck(STAmount const &a)
static bool isDefaultPath(STPath const &path)
std::uint64_t getRate(STAmount const &offerOut, STAmount const &offerIn)
static STPath removeIssuer(STPath const &path)
std::string transToken(TER code)
Currency const & xrpCurrency()
XRP currency.
std::string to_string(base_uint< Bits, Tag > const &a)
STAmount largestAmount(STAmount const &amt)
void addUniquePath(STPathSet &pathSet, STPath const &path)
LineDirection
Describes how an account was found in a path, and how to find the next set of paths.