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>
7#include <xrpld/core/JobQueue.h>
9#include <xrpl/basics/Log.h>
10#include <xrpl/basics/join.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(
67 AccountCandidate
const& first,
68 AccountCandidate
const& second)
70 if (first.priority < second.priority)
73 if (first.account > second.account)
76 return (first.priority ^ seq) < (second.priority ^ seq);
98static PathTable mPathTable;
105 for (
auto const& node : type)
136smallestUsefulAmount(STAmount
const& amount,
int maxPaths)
138 return divide(amount, STAmount(maxPaths + 2), amount.issue());
152 : mSrcAccount(uSrcAccount)
153 , mDstAccount(uDstAccount)
155 isXRP(saDstAmount.getIssuer()) ? uDstAccount
156 : saDstAmount.getIssuer())
157 , mDstAmount(saDstAmount)
158 , mSrcCurrency(uSrcCurrency)
159 , mSrcIssuer(uSrcIssuer)
160 , mSrcAmount(srcAmount.value_or(
STAmount(
170 , mLedger(cache->getLedger())
173 , j_(app.journal(
"Pathfinder"))
177 "ripple::Pathfinder::Pathfinder : valid inputs");
185 JLOG(
j_.
trace()) <<
"findPaths start";
189 JLOG(
j_.
debug()) <<
"Destination amount was zero.";
201 JLOG(
j_.
debug()) <<
"Tried to send to same issuer";
218 auto issuer = currencyIsXRP ?
AccountID() : account;
222 JLOG(
j_.
trace()) <<
"findPaths>"
227 <<
" mSrcIssuer=" << issuerString;
231 JLOG(
j_.
debug()) <<
"findPaths< no ledger";
241 JLOG(
j_.
debug()) <<
"invalid source account";
248 JLOG(
j_.
debug()) <<
"Non-existent gateway";
258 JLOG(
j_.
debug()) <<
"New account not being funded in XRP ";
266 <<
"New account not getting enough funding: " <<
mDstAmount
275 if (bSrcXrp && bDstXrp)
278 JLOG(
j_.
debug()) <<
"XRP to XRP payment";
284 JLOG(
j_.
debug()) <<
"XRP to non-XRP payment";
290 JLOG(
j_.
debug()) <<
"non-XRP to XRP payment";
296 JLOG(
j_.
debug()) <<
"non-XRP to non-XRP - same currency";
302 JLOG(
j_.
debug()) <<
"non-XRP to non-XRP - cross currency";
307 for (
auto const& costedPath : mPathTable[paymentType])
309 if (continueCallback && !continueCallback())
312 if (costedPath.searchLevel <= searchLevel)
314 JLOG(
j_.
trace()) <<
"findPaths trying payment type " << paymentType;
335 uint64_t& qualityOut)
const
365 qualityOut =
getRate(rc.actualAmountOut, rc.actualAmountIn);
366 amountOut = rc.actualAmountOut;
375 mDstAmount - amountOut,
385 amountOut += rc.actualAmountOut;
392 JLOG(j_.
info()) <<
"checkpath: exception (" << e.
what() <<
") "
426 <<
"Default path contributes: " << rc.actualAmountIn;
432 <<
"Default path fails: " <<
transToken(rc.result());
437 JLOG(
j_.
debug()) <<
"Default path causes exception";
459 return path.size() == 1;
469 for (
auto it = path.begin() + 1; it != path.end(); ++it)
484 JLOG(
j_.
trace()) <<
"rankPaths with " << paths.
size() <<
" candidates, and "
485 << maxPaths <<
" maximum";
489 auto const saMinDstAmount = [&]() ->
STAmount {
493 return smallestUsefulAmount(
mDstAmount, maxPaths);
501 for (
int i = 0; i < paths.
size(); ++i)
503 if (continueCallback && !continueCallback())
505 auto const& currentPath = paths[i];
506 if (!currentPath.empty())
511 currentPath, saMinDstAmount, liquidity, uQuality);
515 <<
"findPaths: dropping : " <<
transToken(resultCode)
520 JLOG(
j_.
debug()) <<
"findPaths: quality: " << uQuality <<
": "
524 {uQuality, currentPath.size(), liquidity, i});
539 if (!convert_all_ && a.quality != b.quality)
540 return a.quality < b.quality;
543 if (a.liquidity != b.liquidity)
544 return a.liquidity > b.liquidity;
547 if (a.length != b.length)
548 return a.length < b.length;
551 return a.index > b.index;
558 STPath& fullLiquidityPath,
564 << extraPaths.
size() <<
" extras";
570 fullLiquidityPath.
empty(),
571 "ripple::Pathfinder::getBestPaths : first empty path result");
572 bool const issuerIsSender =
576 rankPaths(maxPaths, extraPaths, extraPathRanks, continueCallback);
586 auto extraPathsIterator = extraPathRanks.
begin();
589 extraPathsIterator != extraPathRanks.
end())
591 if (continueCallback && !continueCallback())
593 bool usePath =
false;
594 bool useExtraPath =
false;
598 else if (extraPathsIterator == extraPathRanks.
end())
600 else if (extraPathsIterator->quality < pathsIterator->quality)
602 else if (extraPathsIterator->quality > pathsIterator->quality)
604 else if (extraPathsIterator->liquidity > pathsIterator->liquidity)
606 else if (extraPathsIterator->liquidity < pathsIterator->liquidity)
615 auto& pathRank = usePath ? *pathsIterator : *extraPathsIterator;
618 : extraPaths[pathRank.index];
621 ++extraPathsIterator;
626 auto iPathsLeft = maxPaths - bestPaths.
size();
627 if (!(iPathsLeft > 0 || fullLiquidityPath.
empty()))
633 UNREACHABLE(
"ripple::Pathfinder::getBestPaths : path not found");
638 bool startsWithIssuer =
false;
640 if (!issuerIsSender && usePath)
643 if (
isDefaultPath(path) || path.front().getAccountID() != srcIssuer)
648 startsWithIssuer =
true;
651 if (iPathsLeft > 1 ||
652 (iPathsLeft > 0 && pathRank.liquidity >= remaining))
656 remaining -= pathRank.liquidity;
660 iPathsLeft == 0 && pathRank.liquidity >=
mDstAmount &&
661 fullLiquidityPath.
empty())
664 fullLiquidityPath = (startsWithIssuer ?
removeIssuer(path) : path);
665 JLOG(
j_.
debug()) <<
"Found extra full path: "
670 JLOG(
j_.
debug()) <<
"Skipping a non-filling path: "
675 if (remaining > beast::zero)
678 fullLiquidityPath.
empty(),
679 "ripple::Pathfinder::getBestPaths : second empty path result");
680 JLOG(
j_.
info()) <<
"Paths could not send " << remaining <<
" of "
685 JLOG(
j_.
debug()) <<
"findPaths: RESULTS: "
699 return matchingCurrency && matchingAccount;
711 Issue const issue(currency, account);
724 int aFlags = sleAccount->getFieldU32(sfFlags);
734 if (
auto const lines =
mRLCache->getRippleLines(account, direction))
736 for (
auto const& rspEntry : *lines)
738 if (currency != rspEntry.getLimit().getCurrency())
742 rspEntry.getBalance() <= beast::zero &&
743 (!rspEntry.getLimitPeer() ||
744 -rspEntry.getBalance() >= rspEntry.getLimitPeer() ||
745 (bAuthRequired && !rspEntry.getAuth())))
749 isDstCurrency && dstAccount == rspEntry.getAccountIDPeer())
753 else if (rspEntry.getNoRipplePeer())
757 else if (rspEntry.getFreezePeer())
779 JLOG(
j_.
debug()) <<
"addLink< on " << currentPaths.
size()
780 <<
" source(s), flags=" << addFlags;
781 for (
auto const& path : currentPaths)
783 if (continueCallback && !continueCallback())
785 addLink(path, incompletePaths, addFlags, continueCallback);
794 JLOG(
j_.
debug()) <<
"addPathsForType "
797 auto it =
mPaths.find(pathType);
802 if (pathType.
empty())
804 if (continueCallback && !continueCallback())
816 JLOG(
j_.
debug()) <<
"getPaths< adding onto '"
817 << pathTypeToString(parentPathType) <<
"' to get '"
818 << pathTypeToString(pathType) <<
"'";
823 auto nodeType = pathType.
back();
830 "ripple::Pathfinder::addPathsForType : empty paths");
873 <<
" complete paths added";
876 JLOG(
j_.
debug()) <<
"getPaths> " << pathsOut.
size()
877 <<
" partial paths found";
893 return sleRipple && (sleRipple->getFieldU32(sfFlags) & flag);
902 if (currentPath.
empty())
913 auto const& fromAccount = (currentPath.
size() == 1)
915 : (currentPath.
end() - 2)->getAccountID();
925 for (
auto const& p : pathSet)
935 STPath const& currentPath,
941 auto const& uEndCurrency = pathEnd.getCurrency();
942 auto const& uEndIssuer = pathEnd.getIssuerID();
943 auto const& uEndAccount = pathEnd.getAccountID();
944 bool const bOnXRP = uEndCurrency.isZero();
951 JLOG(
j_.
trace()) <<
"addLink< flags=" << addFlags <<
" onXRP=" << bOnXRP
962 JLOG(
j_.
trace()) <<
"complete path found ax: "
974 bool const bRequireAuth(
976 bool const bIsEndCurrency(
979 bool const bDestOnly(addFlags &
afAC_LAST);
981 if (
auto const lines =
mRLCache->getRippleLines(
986 auto& rippleLines = *lines;
988 AccountCandidates candidates;
989 candidates.reserve(rippleLines.size());
991 for (
auto const& rs : rippleLines)
993 if (continueCallback && !continueCallback())
995 auto const& acct = rs.getAccountIDPeer();
998 if (hasEffectiveDestination && (acct ==
mDstAccount))
1006 if (bDestOnly && !bToDestination)
1011 if ((uEndCurrency == rs.getLimit().getCurrency()) &&
1012 !currentPath.
hasSeen(acct, uEndCurrency, acct))
1016 if (rs.getBalance() <= beast::zero &&
1017 (!rs.getLimitPeer() ||
1018 -rs.getBalance() >= rs.getLimitPeer() ||
1019 (bRequireAuth && !rs.getAuth())))
1023 else if (bIsNoRippleOut && rs.getNoRipple())
1027 else if (bToDestination)
1033 if (!currentPath.
empty())
1036 <<
"complete path found ae: "
1043 else if (!bDestOnly)
1046 candidates.push_back(
1047 {AccountCandidate::highPriority, acct});
1065 candidates.push_back({
out, acct});
1070 if (!candidates.empty())
1076 compareAccountCandidate,
1078 std::placeholders::_1,
1079 std::placeholders::_2));
1081 int count = candidates.size();
1085 else if (count > 50)
1088 auto it = candidates.begin();
1089 while (count-- != 0)
1091 if (continueCallback && !continueCallback())
1100 currentPath, pathElement);
1108 JLOG(
j_.
warn()) <<
"Path ends on non-existent issuer";
1120 {uEndCurrency, uEndIssuer},
mDomain))
1127 incompletePaths.
assembleAdd(currentPath, pathElement);
1132 bool bDestOnly = (addFlags &
afOB_LAST) != 0;
1134 {uEndCurrency, uEndIssuer},
mDomain);
1136 << books.size() <<
" books found from this currency/issuer";
1138 for (
auto const& book : books)
1140 if (continueCallback && !continueCallback())
1143 xrpAccount(), book.out.currency, book.out.account) &&
1148 STPath newPath(currentPath);
1150 if (book.out.currency.isZero())
1165 <<
"complete path found bx: "
1172 else if (!currentPath.
hasSeen(
1179 if ((newPath.
size() >= 2) &&
1180 (newPath.
back().isAccount()) &&
1181 (newPath[newPath.
size() - 2].isOffer()))
1202 if (hasEffectiveDestination &&
1214 <<
"complete path found ba: "
1239makePath(
char const*
string)
1282 auto& list = mPathTable[type];
1283 XRPL_ASSERT(list.empty(),
"ripple::fillPaths : empty paths");
1284 for (
auto& cost : costs)
1285 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.
int getBookSize(Issue const &, std::optional< Domain > const &domain=std::nullopt)
std::vector< Book > getBooksByTakerPays(Issue const &, std::optional< Domain > const &domain=std::nullopt)
bool isBookToXRP(Issue const &, std::optional< Domain > domain=std::nullopt)
bool issueMatchesOrigin(Issue const &)
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.
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
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
std::optional< uint256 > mDomain
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, 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.
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.