1#include <xrpld/app/ledger/OrderBookDB.h>
2#include <xrpld/app/main/Application.h>
3#include <xrpld/app/paths/Pathfinder.h>
4#include <xrpld/app/paths/RippleCalc.h>
5#include <xrpld/app/paths/RippleLineCache.h>
6#include <xrpld/app/paths/detail/PathfinderUtils.h>
8#include <xrpl/basics/Log.h>
9#include <xrpl/basics/join.h>
10#include <xrpl/core/JobQueue.h>
11#include <xrpl/json/to_string.h>
12#include <xrpl/ledger/PaymentSandbox.h>
54constexpr std::size_t PATHFINDER_MAX_COMPLETE_PATHS = 1000;
56struct AccountCandidate
61 static int const highPriority = 10000;
65compareAccountCandidate(
std::uint32_t seq, AccountCandidate
const& first, AccountCandidate
const& second)
67 if (first.priority < second.priority)
70 if (first.account > second.account)
73 return (first.priority ^ seq) < (second.priority ^ seq);
95static PathTable mPathTable;
102 for (
auto const& node : type)
133smallestUsefulAmount(STAmount
const& amount,
int maxPaths)
135 return divide(amount, STAmount(maxPaths + 2),
amount.issue());
149 : mSrcAccount(uSrcAccount)
150 , mDstAccount(uDstAccount)
151 , mEffectiveDst(
isXRP(saDstAmount.getIssuer()) ? uDstAccount : saDstAmount.getIssuer())
152 , mDstAmount(saDstAmount)
153 , mSrcCurrency(uSrcCurrency)
154 , mSrcIssuer(uSrcIssuer)
155 , mSrcAmount(srcAmount.value_or(
STAmount(
162 , mLedger(cache->getLedger())
165 , j_(app.journal(
"Pathfinder"))
168 !uSrcIssuer ||
isXRP(uSrcCurrency) ==
isXRP(uSrcIssuer.
value()),
"xrpl::Pathfinder::Pathfinder : valid inputs");
174 JLOG(
j_.
trace()) <<
"findPaths start";
178 JLOG(
j_.
debug()) <<
"Destination amount was zero.";
189 JLOG(
j_.
debug()) <<
"Tried to send to same issuer";
205 auto issuer = currencyIsXRP ?
AccountID() : account;
208 JLOG(
j_.
trace()) <<
"findPaths>"
211 <<
" mSrcIssuer=" << issuerString;
215 JLOG(
j_.
debug()) <<
"findPaths< no ledger";
225 JLOG(
j_.
debug()) <<
"invalid source account";
231 JLOG(
j_.
debug()) <<
"Non-existent gateway";
241 JLOG(
j_.
debug()) <<
"New account not being funded in XRP ";
248 JLOG(
j_.
debug()) <<
"New account not getting enough funding: " <<
mDstAmount <<
" < " << reserve;
256 if (bSrcXrp && bDstXrp)
259 JLOG(
j_.
debug()) <<
"XRP to XRP payment";
265 JLOG(
j_.
debug()) <<
"XRP to non-XRP payment";
271 JLOG(
j_.
debug()) <<
"non-XRP to XRP payment";
277 JLOG(
j_.
debug()) <<
"non-XRP to non-XRP - same currency";
283 JLOG(
j_.
debug()) <<
"non-XRP to non-XRP - cross currency";
288 for (
auto const& costedPath : mPathTable[paymentType])
290 if (continueCallback && !continueCallback())
293 if (costedPath.searchLevel <= searchLevel)
295 JLOG(
j_.
trace()) <<
"findPaths trying payment type " << paymentType;
316 uint64_t& qualityOut)
const
333 sandbox, mSrcAmount, minDstAmount, mDstAccount, mSrcAccount, pathSet, mDomain, app_.logs(), &rcInput);
338 qualityOut =
getRate(rc.actualAmountOut, rc.actualAmountIn);
339 amountOut = rc.actualAmountOut;
348 mDstAmount - amountOut,
358 amountOut += rc.actualAmountOut;
395 JLOG(
j_.
debug()) <<
"Default path contributes: " << rc.actualAmountIn;
405 JLOG(
j_.
debug()) <<
"Default path causes exception";
427 return path.
size() == 1;
437 for (
auto it = path.
begin() + 1; it != path.
end(); ++it)
452 JLOG(
j_.
trace()) <<
"rankPaths with " << paths.
size() <<
" candidates, and " << maxPaths <<
" maximum";
456 auto const saMinDstAmount = [&]() ->
STAmount {
460 return smallestUsefulAmount(
mDstAmount, maxPaths);
468 for (
int i = 0; i < paths.
size(); ++i)
470 if (continueCallback && !continueCallback())
472 auto const& currentPath = paths[i];
473 if (!currentPath.empty())
477 auto const resultCode =
getPathLiquidity(currentPath, saMinDstAmount, liquidity, uQuality);
485 JLOG(
j_.
debug()) <<
"findPaths: quality: " << uQuality <<
": "
488 rankedPaths.
push_back({uQuality, currentPath.size(), liquidity, i});
501 if (!convert_all_ && a.quality != b.quality)
502 return a.quality < b.quality;
505 if (a.liquidity != b.liquidity)
506 return a.liquidity > b.liquidity;
509 if (a.length != b.length)
510 return a.length < b.length;
513 return a.index > b.index;
520 STPath& fullLiquidityPath,
530 XRPL_ASSERT(fullLiquidityPath.
empty(),
"xrpl::Pathfinder::getBestPaths : first empty path result");
534 rankPaths(maxPaths, extraPaths, extraPathRanks, continueCallback);
544 auto extraPathsIterator = extraPathRanks.
begin();
546 while (pathsIterator !=
mPathRanks.end() || extraPathsIterator != extraPathRanks.
end())
548 if (continueCallback && !continueCallback())
550 bool usePath =
false;
551 bool useExtraPath =
false;
555 else if (extraPathsIterator == extraPathRanks.
end())
557 else if (extraPathsIterator->quality < pathsIterator->quality)
559 else if (extraPathsIterator->quality > pathsIterator->quality)
561 else if (extraPathsIterator->liquidity > pathsIterator->liquidity)
563 else if (extraPathsIterator->liquidity < pathsIterator->liquidity)
572 auto& pathRank = usePath ? *pathsIterator : *extraPathsIterator;
574 auto const& path = usePath ?
mCompletePaths[pathRank.index] : extraPaths[pathRank.index];
577 ++extraPathsIterator;
582 auto iPathsLeft = maxPaths - bestPaths.
size();
583 if (!(iPathsLeft > 0 || fullLiquidityPath.
empty()))
589 UNREACHABLE(
"xrpl::Pathfinder::getBestPaths : path not found");
594 bool startsWithIssuer =
false;
596 if (!issuerIsSender && usePath)
599 if (
isDefaultPath(path) || path.front().getAccountID() != srcIssuer)
604 startsWithIssuer =
true;
607 if (iPathsLeft > 1 || (iPathsLeft > 0 && pathRank.liquidity >= remaining))
611 remaining -= pathRank.liquidity;
614 else if (iPathsLeft == 0 && pathRank.liquidity >=
mDstAmount && fullLiquidityPath.
empty())
617 fullLiquidityPath = (startsWithIssuer ?
removeIssuer(path) : path);
626 if (remaining > beast::zero)
628 XRPL_ASSERT(fullLiquidityPath.
empty(),
"xrpl::Pathfinder::getBestPaths : second empty path result");
629 JLOG(
j_.
info()) <<
"Paths could not send " << remaining <<
" of " <<
mDstAmount;
642 bool matchingAccount =
645 return matchingCurrency && matchingAccount;
657 Issue const issue(currency, account);
670 int aFlags = sleAccount->getFieldU32(sfFlags);
680 if (
auto const lines =
mRLCache->getRippleLines(account, direction))
682 for (
auto const& rspEntry : *lines)
684 if (currency != rspEntry.getLimit().getCurrency())
688 rspEntry.getBalance() <= beast::zero &&
689 (!rspEntry.getLimitPeer() || -rspEntry.getBalance() >= rspEntry.getLimitPeer() ||
690 (bAuthRequired && !rspEntry.getAuth())))
693 else if (isDstCurrency && dstAccount == rspEntry.getAccountIDPeer())
697 else if (rspEntry.getNoRipplePeer())
701 else if (rspEntry.getFreezePeer())
723 JLOG(
j_.
debug()) <<
"addLink< on " << currentPaths.
size() <<
" source(s), flags=" << addFlags;
724 for (
auto const& path : currentPaths)
726 if (continueCallback && !continueCallback())
728 addLink(path, incompletePaths, addFlags, continueCallback);
737 auto it =
mPaths.find(pathType);
742 if (pathType.
empty())
744 if (continueCallback && !continueCallback())
755 JLOG(
j_.
debug()) <<
"getPaths< adding onto '" << pathTypeToString(parentPathType) <<
"' to get '"
756 << pathTypeToString(pathType) <<
"'";
761 auto nodeType = pathType.
back();
766 XRPL_ASSERT(pathsOut.
empty(),
"xrpl::Pathfinder::addPathsForType : empty paths");
799 JLOG(
j_.
debug()) <<
"getPaths> " << pathsOut.
size() <<
" partial paths found";
810 return sleRipple && (sleRipple->getFieldU32(sfFlags) & flag);
819 if (currentPath.
empty())
830 auto const& fromAccount = (currentPath.
size() == 1) ?
mSrcAccount : (currentPath.
end() - 2)->getAccountID();
840 for (
auto const& p : pathSet)
850 STPath const& currentPath,
856 auto const& uEndCurrency = pathEnd.getCurrency();
857 auto const& uEndIssuer = pathEnd.getIssuerID();
858 auto const& uEndAccount = pathEnd.getAccountID();
859 bool const bOnXRP = uEndCurrency.isZero();
866 JLOG(
j_.
trace()) <<
"addLink< flags=" << addFlags <<
" onXRP=" << bOnXRP
888 bool const bRequireAuth(sleEnd->getFieldU32(sfFlags) &
lsfRequireAuth);
891 bool const bDestOnly(addFlags &
afAC_LAST);
893 if (
auto const lines =
mRLCache->getRippleLines(
896 auto& rippleLines = *lines;
898 AccountCandidates candidates;
899 candidates.reserve(rippleLines.size());
901 for (
auto const& rs : rippleLines)
903 if (continueCallback && !continueCallback())
905 auto const& acct = rs.getAccountIDPeer();
908 if (hasEffectiveDestination && (acct ==
mDstAccount))
916 if (bDestOnly && !bToDestination)
921 if ((uEndCurrency == rs.getLimit().getCurrency()) &&
922 !currentPath.
hasSeen(acct, uEndCurrency, acct))
926 if (rs.getBalance() <= beast::zero &&
927 (!rs.getLimitPeer() || -rs.getBalance() >= rs.getLimitPeer() ||
928 (bRequireAuth && !rs.getAuth())))
932 else if (bIsNoRippleOut && rs.getNoRipple())
936 else if (bToDestination)
942 if (!currentPath.
empty())
952 candidates.push_back({AccountCandidate::highPriority, acct});
963 uEndCurrency, acct, direction, bIsEndCurrency,
mEffectiveDst, continueCallback);
965 candidates.push_back({
out, acct});
970 if (!candidates.empty())
976 compareAccountCandidate,
mLedger->seq(), std::placeholders::_1, std::placeholders::_2));
978 int count = candidates.size();
985 auto it = candidates.begin();
988 if (continueCallback && !continueCallback())
993 incompletePaths.
assembleAdd(currentPath, pathElement);
1001 JLOG(
j_.
warn()) <<
"Path ends on non-existent issuer";
1014 incompletePaths.
assembleAdd(currentPath, pathElement);
1019 bool bDestOnly = (addFlags &
afOB_LAST) != 0;
1021 JLOG(
j_.
trace()) << books.size() <<
" books found from this currency/issuer";
1023 for (
auto const& book : books)
1025 if (continueCallback && !continueCallback())
1030 STPath newPath(currentPath);
1032 if (book.out.currency.isZero())
1048 else if (!currentPath.
hasSeen(book.out.account, book.out.currency, book.out.account))
1052 if ((newPath.
size() >= 2) && (newPath.
back().isAccount()) &&
1053 (newPath[newPath.
size() - 2].isOffer()))
1072 if (hasEffectiveDestination && book.out.account ==
mDstAccount &&
1101makePath(
char const*
string)
1144 auto& list = mPathTable[type];
1145 XRPL_ASSERT(list.empty(),
"xrpl::fillPaths : empty paths");
1146 for (
auto& cost : costs)
1147 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.
std::vector< Book > getBooksByTakerPays(Issue const &, std::optional< Domain > const &domain=std::nullopt)
int getBookSize(Issue const &, std::optional< Domain > const &domain=std::nullopt)
bool isBookToXRP(Issue const &, std::optional< Domain > domain=std::nullopt)
void addLinks(STPathSet const ¤tPaths, STPathSet &incompletePaths, int addFlags, std::function< bool(void)> const &continueCallback)
void rankPaths(int maxPaths, STPathSet const &paths, std::vector< PathRank > &rankedPaths, std::function< bool(void)> const &continueCallback)
TER getPathLiquidity(STPath const &path, STAmount const &minDstAmount, STAmount &amountOut, uint64_t &qualityOut) const
std::shared_ptr< RippleLineCache > mRLCache
static std::uint32_t const afADD_ACCOUNTS
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, std::optional< uint256 > const &domain, Application &app)
Construct a pathfinder without an issuer.
bool issueMatchesOrigin(Issue const &)
STPathSet getBestPaths(int maxPaths, STPath &fullLiquidityPath, STPathSet const &extraPaths, AccountID const &srcIssuer, std::function< bool(void)> const &continueCallback={})
void addLink(STPath const ¤tPath, STPathSet &incompletePaths, int addFlags, std::function< bool(void)> const &continueCallback)
static std::uint32_t const afAC_LAST
std::optional< AccountID > mSrcIssuer
std::vector< NodeType > PathType
static std::uint32_t const afOB_XRP
std::map< PathType, STPathSet > mPaths
hash_map< Issue, int > mPathsOutCountMap
STPathSet & addPathsForType(PathType const &type, std::function< bool(void)> const &continueCallback)
std::optional< uint256 > mDomain
bool isNoRipple(AccountID const &fromAccount, AccountID const &toAccount, Currency const ¤cy)
bool findPaths(int searchLevel, std::function< bool(void)> const &continueCallback={})
int getPathsOut(Currency const ¤cy, AccountID const &account, LineDirection direction, bool isDestCurrency, AccountID const &dest, std::function< bool(void)> const &continueCallback)
static std::uint32_t const afOB_LAST
bool isNoRippleOut(STPath const ¤tPath)
static void initPathTable()
STAmount mRemainingAmount
The amount remaining from mSrcAccount after the default liquidity has been removed.
std::shared_ptr< ReadView const > mLedger
static std::uint32_t const afADD_BOOKS
std::vector< PathRank > mPathRanks
void computePathRanks(int maxPaths, std::function< bool(void)> const &continueCallback={})
Compute the rankings of the paths.
A wrapper which makes credits unavailable to balances.
std::string getFullText() const override
Currency const & getCurrency() const
bool native() const noexcept
AccountID const & getAccountID() const
Currency const & getCurrency() const
bool assembleAdd(STPath const &base, STPathElement const &tail)
void push_back(STPath const &e)
std::vector< STPath >::size_type size() const
Json::Value getJson(JsonOptions) const override
std::vector< STPathElement >::size_type size() const
Json::Value getJson(JsonOptions) const
void push_back(STPathElement const &e)
std::vector< STPathElement >::const_iterator end() const
bool hasSeen(AccountID const &account, Currency const ¤cy, AccountID const &issuer) const
void emplace_back(Args &&... args)
std::vector< STPathElement >::const_reference back() const
std::vector< STPathElement >::const_iterator begin() const
static Output rippleCalculate(PaymentSandbox &view, STAmount const &saMaxAmountReq, STAmount const &saDstAmountReq, AccountID const &uDstAccountID, AccountID const &uSrcAccountID, STPathSet const &spsPaths, std::optional< uint256 > const &domainID, 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.
STAmount divide(STAmount const &amount, Rate const &rate)
STAmount convertAmount(STAmount const &amt, bool all)
bool isXRP(AccountID const &c)
std::string to_string(base_uint< Bits, Tag > const &a)
STAmount largestAmount(STAmount const &amt)
base_uint< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
static STPath removeIssuer(STPath const &path)
std::string transToken(TER code)
Currency const & xrpCurrency()
XRP currency.
static bool isDefaultPath(STPath const &path)
LineDirection
Describes how an account was found in a path, and how to find the next set of paths.
std::uint64_t getRate(STAmount const &offerOut, STAmount const &offerIn)
bool convertAllCheck(STAmount const &a)
void addUniquePath(STPathSet &pathSet, STPath const &path)
AccountID const & xrpAccount()
Compute AccountID from public key.