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 int const 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;
239 JLOG(
j_.
trace()) <<
"findPaths>"
244 <<
" mSrcIssuer=" << issuerString;
248 JLOG(
j_.
debug()) <<
"findPaths< no ledger";
258 JLOG(
j_.
debug()) <<
"invalid source account";
265 JLOG(
j_.
debug()) <<
"Non-existent gateway";
275 JLOG(
j_.
debug()) <<
"New account not being funded in XRP ";
283 <<
"New account not getting enough funding: " <<
mDstAmount
292 if (bSrcXrp && bDstXrp)
295 JLOG(
j_.
debug()) <<
"XRP to XRP payment";
301 JLOG(
j_.
debug()) <<
"XRP to non-XRP payment";
307 JLOG(
j_.
debug()) <<
"non-XRP to XRP payment";
313 JLOG(
j_.
debug()) <<
"non-XRP to non-XRP - same currency";
319 JLOG(
j_.
debug()) <<
"non-XRP to non-XRP - cross currency";
324 for (
auto const& costedPath : mPathTable[paymentType])
326 if (continueCallback && !continueCallback())
329 if (costedPath.searchLevel <= searchLevel)
331 JLOG(
j_.
trace()) <<
"findPaths trying payment type " << paymentType;
352 uint64_t& qualityOut)
const
381 qualityOut =
getRate(rc.actualAmountOut, rc.actualAmountIn);
382 amountOut = rc.actualAmountOut;
391 mDstAmount - amountOut,
400 amountOut += rc.actualAmountOut;
407 JLOG(j_.
info()) <<
"checkpath: exception (" << e.
what() <<
") "
440 <<
"Default path contributes: " << rc.actualAmountIn;
446 <<
"Default path fails: " <<
transToken(rc.result());
451 JLOG(
j_.
debug()) <<
"Default path causes exception";
473 return path.size() == 1;
483 for (
auto it = path.begin() + 1; it != path.end(); ++it)
498 JLOG(
j_.
trace()) <<
"rankPaths with " << paths.
size() <<
" candidates, and "
499 << maxPaths <<
" maximum";
503 auto const saMinDstAmount = [&]() ->
STAmount {
507 return smallestUsefulAmount(
mDstAmount, maxPaths);
515 for (
int i = 0; i < paths.
size(); ++i)
517 if (continueCallback && !continueCallback())
519 auto const& currentPath = paths[i];
520 if (!currentPath.empty())
525 currentPath, saMinDstAmount, liquidity, uQuality);
529 <<
"findPaths: dropping : " <<
transToken(resultCode)
534 JLOG(
j_.
debug()) <<
"findPaths: quality: " << uQuality <<
": "
538 {uQuality, currentPath.size(), liquidity, i});
553 if (!convert_all_ && a.quality != b.quality)
554 return a.quality < b.quality;
557 if (a.liquidity != b.liquidity)
558 return a.liquidity > b.liquidity;
561 if (a.length != b.length)
562 return a.length < b.length;
565 return a.index > b.index;
572 STPath& fullLiquidityPath,
578 << extraPaths.
size() <<
" extras";
584 fullLiquidityPath.
empty(),
585 "ripple::Pathfinder::getBestPaths : first empty path result");
586 bool const issuerIsSender =
590 rankPaths(maxPaths, extraPaths, extraPathRanks, continueCallback);
600 auto extraPathsIterator = extraPathRanks.
begin();
603 extraPathsIterator != extraPathRanks.
end())
605 if (continueCallback && !continueCallback())
607 bool usePath =
false;
608 bool useExtraPath =
false;
612 else if (extraPathsIterator == extraPathRanks.
end())
614 else if (extraPathsIterator->quality < pathsIterator->quality)
616 else if (extraPathsIterator->quality > pathsIterator->quality)
618 else if (extraPathsIterator->liquidity > pathsIterator->liquidity)
620 else if (extraPathsIterator->liquidity < pathsIterator->liquidity)
629 auto& pathRank = usePath ? *pathsIterator : *extraPathsIterator;
632 : extraPaths[pathRank.index];
635 ++extraPathsIterator;
640 auto iPathsLeft = maxPaths - bestPaths.
size();
641 if (!(iPathsLeft > 0 || fullLiquidityPath.
empty()))
646 UNREACHABLE(
"ripple::Pathfinder::getBestPaths : path not found");
650 bool startsWithIssuer =
false;
652 if (!issuerIsSender && usePath)
655 if (
isDefaultPath(path) || path.front().getAccountID() != srcIssuer)
660 startsWithIssuer =
true;
663 if (iPathsLeft > 1 ||
664 (iPathsLeft > 0 && pathRank.liquidity >= remaining))
668 remaining -= pathRank.liquidity;
672 iPathsLeft == 0 && pathRank.liquidity >=
mDstAmount &&
673 fullLiquidityPath.
empty())
676 fullLiquidityPath = (startsWithIssuer ?
removeIssuer(path) : path);
677 JLOG(
j_.
debug()) <<
"Found extra full path: "
682 JLOG(
j_.
debug()) <<
"Skipping a non-filling path: "
687 if (remaining > beast::zero)
690 fullLiquidityPath.
empty(),
691 "ripple::Pathfinder::getBestPaths : second empty path result");
692 JLOG(
j_.
info()) <<
"Paths could not send " << remaining <<
" of "
697 JLOG(
j_.
debug()) <<
"findPaths: RESULTS: "
711 return matchingCurrency && matchingAccount;
723 Issue const issue(currency, account);
736 int aFlags = sleAccount->getFieldU32(sfFlags);
746 if (
auto const lines =
mRLCache->getRippleLines(account, direction))
748 for (
auto const& rspEntry : *lines)
750 if (currency != rspEntry.getLimit().getCurrency())
754 rspEntry.getBalance() <= beast::zero &&
755 (!rspEntry.getLimitPeer() ||
756 -rspEntry.getBalance() >= rspEntry.getLimitPeer() ||
757 (bAuthRequired && !rspEntry.getAuth())))
761 isDstCurrency && dstAccount == rspEntry.getAccountIDPeer())
765 else if (rspEntry.getNoRipplePeer())
769 else if (rspEntry.getFreezePeer())
791 JLOG(
j_.
debug()) <<
"addLink< on " << currentPaths.
size()
792 <<
" source(s), flags=" << addFlags;
793 for (
auto const& path : currentPaths)
795 if (continueCallback && !continueCallback())
797 addLink(path, incompletePaths, addFlags, continueCallback);
806 JLOG(
j_.
debug()) <<
"addPathsForType "
809 auto it =
mPaths.find(pathType);
814 if (pathType.
empty())
816 if (continueCallback && !continueCallback())
828 JLOG(
j_.
debug()) <<
"getPaths< adding onto '"
829 << pathTypeToString(parentPathType) <<
"' to get '"
830 << pathTypeToString(pathType) <<
"'";
835 auto nodeType = pathType.
back();
842 "ripple::Pathfinder::addPathsForType : empty paths");
885 <<
" complete paths added";
888 JLOG(
j_.
debug()) <<
"getPaths> " << pathsOut.
size()
889 <<
" partial paths found";
905 return sleRipple && (sleRipple->getFieldU32(sfFlags) & flag);
914 if (currentPath.
empty())
925 auto const& fromAccount = (currentPath.
size() == 1)
927 : (currentPath.
end() - 2)->getAccountID();
937 for (
auto const& p : pathSet)
947 STPath const& currentPath,
953 auto const& uEndCurrency = pathEnd.getCurrency();
954 auto const& uEndIssuer = pathEnd.getIssuerID();
955 auto const& uEndAccount = pathEnd.getAccountID();
956 bool const bOnXRP = uEndCurrency.isZero();
963 JLOG(
j_.
trace()) <<
"addLink< flags=" << addFlags <<
" onXRP=" << bOnXRP
974 JLOG(
j_.
trace()) <<
"complete path found ax: "
986 bool const bRequireAuth(
988 bool const bIsEndCurrency(
991 bool const bDestOnly(addFlags &
afAC_LAST);
993 if (
auto const lines =
mRLCache->getRippleLines(
998 auto& rippleLines = *lines;
1000 AccountCandidates candidates;
1001 candidates.reserve(rippleLines.size());
1003 for (
auto const& rs : rippleLines)
1005 if (continueCallback && !continueCallback())
1007 auto const& acct = rs.getAccountIDPeer();
1010 if (hasEffectiveDestination && (acct ==
mDstAccount))
1018 if (bDestOnly && !bToDestination)
1023 if ((uEndCurrency == rs.getLimit().getCurrency()) &&
1024 !currentPath.
hasSeen(acct, uEndCurrency, acct))
1028 if (rs.getBalance() <= beast::zero &&
1029 (!rs.getLimitPeer() ||
1030 -rs.getBalance() >= rs.getLimitPeer() ||
1031 (bRequireAuth && !rs.getAuth())))
1035 else if (bIsNoRippleOut && rs.getNoRipple())
1039 else if (bToDestination)
1045 if (!currentPath.
empty())
1048 <<
"complete path found ae: "
1055 else if (!bDestOnly)
1058 candidates.push_back(
1059 {AccountCandidate::highPriority, acct});
1077 candidates.push_back({
out, acct});
1082 if (!candidates.empty())
1088 compareAccountCandidate,
1090 std::placeholders::_1,
1091 std::placeholders::_2));
1093 int count = candidates.size();
1097 else if (count > 50)
1100 auto it = candidates.begin();
1101 while (count-- != 0)
1103 if (continueCallback && !continueCallback())
1112 currentPath, pathElement);
1120 JLOG(
j_.
warn()) <<
"Path ends on non-existent issuer";
1138 incompletePaths.
assembleAdd(currentPath, pathElement);
1143 bool bDestOnly = (addFlags &
afOB_LAST) != 0;
1145 {uEndCurrency, uEndIssuer});
1147 << books.size() <<
" books found from this currency/issuer";
1149 for (
auto const& book : books)
1151 if (continueCallback && !continueCallback())
1154 xrpAccount(), book.out.currency, book.out.account) &&
1159 STPath newPath(currentPath);
1161 if (book.out.currency.isZero())
1176 <<
"complete path found bx: "
1183 else if (!currentPath.
hasSeen(
1190 if ((newPath.
size() >= 2) &&
1191 (newPath.
back().isAccount()) &&
1192 (newPath[newPath.
size() - 2].isOffer()))
1213 if (hasEffectiveDestination &&
1225 <<
"complete path found ba: "
1250makePath(
char const*
string)
1293 auto& list = mPathTable[type];
1294 XRPL_ASSERT(list.empty(),
"ripple::fillPaths : empty paths");
1295 for (
auto& cost : costs)
1296 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.