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>
29#include <xrpl/basics/Log.h>
30#include <xrpl/basics/join.h>
31#include <xrpl/json/to_string.h>
73constexpr std::size_t PATHFINDER_MAX_COMPLETE_PATHS = 1000;
75struct AccountCandidate
80 static const int highPriority = 10000;
84compareAccountCandidate(
86 AccountCandidate
const& first,
87 AccountCandidate
const& second)
89 if (first.priority < second.priority)
92 if (first.account > second.account)
95 return (first.priority ^ seq) < (second.priority ^ seq);
117static PathTable mPathTable;
124 for (
auto const& node : type)
155smallestUsefulAmount(STAmount
const& amount,
int maxPaths)
157 return divide(amount, STAmount(maxPaths + 2), amount.issue());
170 : mSrcAccount(uSrcAccount)
171 , mDstAccount(uDstAccount)
173 isXRP(saDstAmount.getIssuer()) ? uDstAccount
174 : saDstAmount.getIssuer())
175 , mDstAmount(saDstAmount)
176 , mSrcCurrency(uSrcCurrency)
177 , mSrcIssuer(uSrcIssuer)
178 , mSrcAmount(srcAmount.value_or(
STAmount(
187 , mLedger(cache->getLedger())
190 , j_(app.journal(
"Pathfinder"))
194 "ripple::Pathfinder::Pathfinder : valid inputs");
202 JLOG(
j_.
trace()) <<
"findPaths start";
206 JLOG(
j_.
debug()) <<
"Destination amount was zero.";
218 JLOG(
j_.
debug()) <<
"Tried to send to same issuer";
235 auto issuer = currencyIsXRP ?
AccountID() : account;
243 <<
" mSrcIssuer=" << issuerString;
247 JLOG(
j_.
debug()) <<
"findPaths< no ledger";
257 JLOG(
j_.
debug()) <<
"invalid source account";
264 JLOG(
j_.
debug()) <<
"Non-existent gateway";
274 JLOG(
j_.
debug()) <<
"New account not being funded in XRP ";
282 <<
"New account not getting enough funding: " <<
mDstAmount
291 if (bSrcXrp && bDstXrp)
294 JLOG(
j_.
debug()) <<
"XRP to XRP payment";
300 JLOG(
j_.
debug()) <<
"XRP to non-XRP payment";
306 JLOG(
j_.
debug()) <<
"non-XRP to XRP payment";
312 JLOG(
j_.
debug()) <<
"non-XRP to non-XRP - same currency";
318 JLOG(
j_.
debug()) <<
"non-XRP to non-XRP - cross currency";
323 for (
auto const& costedPath : mPathTable[paymentType])
325 if (continueCallback && !continueCallback())
328 if (costedPath.searchLevel <= searchLevel)
330 JLOG(
j_.
trace()) <<
"findPaths trying payment type " << paymentType;
351 uint64_t& qualityOut)
const
380 qualityOut =
getRate(rc.actualAmountOut, rc.actualAmountIn);
381 amountOut = rc.actualAmountOut;
390 mDstAmount - amountOut,
399 amountOut += rc.actualAmountOut;
406 JLOG(j_.
info()) <<
"checkpath: exception (" << e.
what() <<
") "
439 <<
"Default path contributes: " << rc.actualAmountIn;
445 <<
"Default path fails: " <<
transToken(rc.result());
450 JLOG(
j_.
debug()) <<
"Default path causes exception";
472 return path.size() == 1;
482 for (
auto it = path.begin() + 1; it != path.end(); ++it)
497 JLOG(
j_.
trace()) <<
"rankPaths with " << paths.
size() <<
" candidates, and "
498 << maxPaths <<
" maximum";
502 auto const saMinDstAmount = [&]() ->
STAmount {
506 return smallestUsefulAmount(
mDstAmount, maxPaths);
514 for (
int i = 0; i < paths.
size(); ++i)
516 if (continueCallback && !continueCallback())
518 auto const& currentPath = paths[i];
519 if (!currentPath.empty())
524 currentPath, saMinDstAmount, liquidity, uQuality);
528 <<
"findPaths: dropping : " <<
transToken(resultCode)
533 JLOG(
j_.
debug()) <<
"findPaths: quality: " << uQuality <<
": "
537 {uQuality, currentPath.size(), liquidity, i});
552 if (!convert_all_ && a.quality != b.quality)
553 return a.quality < b.quality;
556 if (a.liquidity != b.liquidity)
557 return a.liquidity > b.liquidity;
560 if (a.length != b.length)
561 return a.length < b.length;
564 return a.index > b.index;
571 STPath& fullLiquidityPath,
577 << extraPaths.
size() <<
" extras";
583 fullLiquidityPath.
empty(),
584 "ripple::Pathfinder::getBestPaths : first empty path result");
585 const bool issuerIsSender =
589 rankPaths(maxPaths, extraPaths, extraPathRanks, continueCallback);
599 auto extraPathsIterator = extraPathRanks.
begin();
602 extraPathsIterator != extraPathRanks.
end())
604 if (continueCallback && !continueCallback())
606 bool usePath =
false;
607 bool useExtraPath =
false;
611 else if (extraPathsIterator == extraPathRanks.
end())
613 else if (extraPathsIterator->quality < pathsIterator->quality)
615 else if (extraPathsIterator->quality > pathsIterator->quality)
617 else if (extraPathsIterator->liquidity > pathsIterator->liquidity)
619 else if (extraPathsIterator->liquidity < pathsIterator->liquidity)
628 auto& pathRank = usePath ? *pathsIterator : *extraPathsIterator;
631 : extraPaths[pathRank.index];
634 ++extraPathsIterator;
639 auto iPathsLeft = maxPaths - bestPaths.
size();
640 if (!(iPathsLeft > 0 || fullLiquidityPath.
empty()))
645 UNREACHABLE(
"ripple::Pathfinder::getBestPaths : path not found");
649 bool startsWithIssuer =
false;
651 if (!issuerIsSender && usePath)
654 if (
isDefaultPath(path) || path.front().getAccountID() != srcIssuer)
659 startsWithIssuer =
true;
662 if (iPathsLeft > 1 ||
663 (iPathsLeft > 0 && pathRank.liquidity >= remaining))
667 remaining -= pathRank.liquidity;
671 iPathsLeft == 0 && pathRank.liquidity >=
mDstAmount &&
672 fullLiquidityPath.
empty())
675 fullLiquidityPath = (startsWithIssuer ?
removeIssuer(path) : path);
676 JLOG(
j_.
debug()) <<
"Found extra full path: "
681 JLOG(
j_.
debug()) <<
"Skipping a non-filling path: "
686 if (remaining > beast::zero)
689 fullLiquidityPath.
empty(),
690 "ripple::Pathfinder::getBestPaths : second empty path result");
691 JLOG(
j_.
info()) <<
"Paths could not send " << remaining <<
" of "
696 JLOG(
j_.
debug()) <<
"findPaths: RESULTS: "
710 return matchingCurrency && matchingAccount;
722 Issue const issue(currency, account);
735 int aFlags = sleAccount->getFieldU32(sfFlags);
745 if (
auto const lines =
mRLCache->getRippleLines(account, direction))
747 for (
auto const& rspEntry : *lines)
749 if (currency != rspEntry.getLimit().getCurrency())
753 rspEntry.getBalance() <= beast::zero &&
754 (!rspEntry.getLimitPeer() ||
755 -rspEntry.getBalance() >= rspEntry.getLimitPeer() ||
756 (bAuthRequired && !rspEntry.getAuth())))
760 isDstCurrency && dstAccount == rspEntry.getAccountIDPeer())
764 else if (rspEntry.getNoRipplePeer())
768 else if (rspEntry.getFreezePeer())
790 JLOG(
j_.
debug()) <<
"addLink< on " << currentPaths.
size()
791 <<
" source(s), flags=" << addFlags;
792 for (
auto const& path : currentPaths)
794 if (continueCallback && !continueCallback())
796 addLink(path, incompletePaths, addFlags, continueCallback);
805 JLOG(
j_.
debug()) <<
"addPathsForType "
808 auto it =
mPaths.find(pathType);
813 if (pathType.
empty())
815 if (continueCallback && !continueCallback())
827 JLOG(
j_.
debug()) <<
"getPaths< adding onto '"
828 << pathTypeToString(parentPathType) <<
"' to get '"
829 << pathTypeToString(pathType) <<
"'";
834 auto nodeType = pathType.
back();
841 "ripple::Pathfinder::addPathsForType : empty paths");
884 <<
" complete paths added";
887 JLOG(
j_.
debug()) <<
"getPaths> " << pathsOut.
size()
888 <<
" partial paths found";
904 return sleRipple && (sleRipple->getFieldU32(sfFlags) & flag);
913 if (currentPath.
empty())
924 auto const& fromAccount = (currentPath.
size() == 1)
926 : (currentPath.
end() - 2)->getAccountID();
936 for (
auto const& p : pathSet)
946 const STPath& currentPath,
952 auto const& uEndCurrency = pathEnd.getCurrency();
953 auto const& uEndIssuer = pathEnd.getIssuerID();
954 auto const& uEndAccount = pathEnd.getAccountID();
955 bool const bOnXRP = uEndCurrency.isZero();
962 JLOG(
j_.
trace()) <<
"addLink< flags=" << addFlags <<
" onXRP=" << bOnXRP
973 JLOG(
j_.
trace()) <<
"complete path found ax: "
985 bool const bRequireAuth(
987 bool const bIsEndCurrency(
990 bool const bDestOnly(addFlags &
afAC_LAST);
992 if (
auto const lines =
mRLCache->getRippleLines(
997 auto& rippleLines = *lines;
999 AccountCandidates candidates;
1000 candidates.reserve(rippleLines.size());
1002 for (
auto const& rs : rippleLines)
1004 if (continueCallback && !continueCallback())
1006 auto const& acct = rs.getAccountIDPeer();
1009 if (hasEffectiveDestination && (acct ==
mDstAccount))
1017 if (bDestOnly && !bToDestination)
1022 if ((uEndCurrency == rs.getLimit().getCurrency()) &&
1023 !currentPath.
hasSeen(acct, uEndCurrency, acct))
1027 if (rs.getBalance() <= beast::zero &&
1028 (!rs.getLimitPeer() ||
1029 -rs.getBalance() >= rs.getLimitPeer() ||
1030 (bRequireAuth && !rs.getAuth())))
1034 else if (bIsNoRippleOut && rs.getNoRipple())
1038 else if (bToDestination)
1044 if (!currentPath.
empty())
1047 <<
"complete path found ae: "
1054 else if (!bDestOnly)
1057 candidates.push_back(
1058 {AccountCandidate::highPriority, acct});
1076 candidates.push_back({
out, acct});
1081 if (!candidates.empty())
1087 compareAccountCandidate,
1089 std::placeholders::_1,
1090 std::placeholders::_2));
1092 int count = candidates.size();
1096 else if (count > 50)
1099 auto it = candidates.begin();
1100 while (count-- != 0)
1102 if (continueCallback && !continueCallback())
1111 currentPath, pathElement);
1119 JLOG(
j_.
warn()) <<
"Path ends on non-existent issuer";
1137 incompletePaths.
assembleAdd(currentPath, pathElement);
1142 bool bDestOnly = (addFlags &
afOB_LAST) != 0;
1144 {uEndCurrency, uEndIssuer});
1146 << books.size() <<
" books found from this currency/issuer";
1148 for (
auto const& book : books)
1150 if (continueCallback && !continueCallback())
1153 xrpAccount(), book.out.currency, book.out.account) &&
1158 STPath newPath(currentPath);
1160 if (book.out.currency.isZero())
1175 <<
"complete path found bx: "
1182 else if (!currentPath.
hasSeen(
1189 if ((newPath.
size() >= 2) &&
1190 (newPath.
back().isAccount()) &&
1191 (newPath[newPath.
size() - 2].isOffer()))
1212 if (hasEffectiveDestination &&
1224 <<
"complete path found ba: "
1249makePath(
char const*
string)
1292 auto& list = mPathTable[type];
1293 XRPL_ASSERT(list.empty(),
"ripple::fillPaths : empty paths");
1294 for (
auto& cost : costs)
1295 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.