xrpld
Loading...
Searching...
No Matches
OfferStream.cpp
1#include <xrpl/tx/paths/OfferStream.h>
2
3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/Number.h>
5#include <xrpl/basics/base_uint.h>
6#include <xrpl/basics/chrono.h>
7#include <xrpl/basics/contract.h>
8#include <xrpl/beast/utility/Journal.h>
9#include <xrpl/beast/utility/Zero.h>
10#include <xrpl/beast/utility/instrumentation.h>
11#include <xrpl/ledger/ApplyView.h>
12#include <xrpl/ledger/ReadView.h>
13#include <xrpl/ledger/helpers/MPTokenHelpers.h>
14#include <xrpl/ledger/helpers/PermissionedDEXHelpers.h>
15#include <xrpl/ledger/helpers/RippleStateHelpers.h>
16#include <xrpl/ledger/helpers/TokenHelpers.h>
17#include <xrpl/protocol/AccountID.h>
18#include <xrpl/protocol/Asset.h>
19#include <xrpl/protocol/Book.h>
20#include <xrpl/protocol/Concepts.h>
21#include <xrpl/protocol/Feature.h>
22#include <xrpl/protocol/IOUAmount.h>
23#include <xrpl/protocol/Indexes.h>
24#include <xrpl/protocol/MPTAmount.h>
25#include <xrpl/protocol/MPTIssue.h>
26#include <xrpl/protocol/Quality.h>
27#include <xrpl/protocol/SField.h>
28#include <xrpl/protocol/STLedgerEntry.h>
29#include <xrpl/protocol/TER.h>
30#include <xrpl/protocol/XRPAmount.h>
31#include <xrpl/tx/paths/detail/Steps.h>
32
33#include <algorithm>
34#include <optional>
35#include <stdexcept>
36#include <type_traits>
37
38namespace xrpl {
39
40namespace {
41bool
42checkIssuers(ReadView const& view, Book const& book)
43{
44 auto issuerExists = [](ReadView const& view, Asset const& asset) -> bool {
45 auto const& issuer = asset.getIssuer();
46 return isXRP(issuer) || view.exists(keylet::account(issuer));
47 };
48 return issuerExists(view, book.in) && issuerExists(view, book.out);
49}
50} // namespace
51
52template <StepAmount TIn, StepAmount TOut>
54 ApplyView& view,
55 ApplyView& cancelView,
56 Book const& book,
58 StepCounter& counter,
59 beast::Journal journal)
60 : j_(journal)
61 , view_(view)
62 , cancelView_(cancelView)
63 , book_(book)
64 , validBook_(checkIssuers(view, book))
65 , expire_(when)
66 , tip_(view, book_)
67 , counter_(counter)
68{
69 XRPL_ASSERT(validBook_, "xrpl::TOfferStreamBase::TOfferStreamBase : valid book");
70}
71
72// Handle the case where a directory item with no corresponding ledger entry
73// is found. This shouldn't happen but if it does we clean it up.
74template <StepAmount TIn, StepAmount TOut>
75void
77{
78 // NIKB NOTE This should be using ApplyView::dirRemove, which would
79 // correctly remove the directory if its the last entry.
80 // Unfortunately this is a protocol breaking change.
81
82 auto p = view.peek(keylet::page(tip_.dir()));
83
84 if (p == nullptr)
85 {
86 JLOG(j_.error()) << "Missing directory " << tip_.dir() << " for offer " << tip_.index();
87 return;
88 }
89
90 auto v(p->getFieldV256(sfIndexes));
91 auto it(std::ranges::find(v, tip_.index()));
92
93 if (it == v.end())
94 {
95 JLOG(j_.error()) << "Missing offer " << tip_.index() << " for directory " << tip_.dir();
96 return;
97 }
98
99 v.erase(it);
100 p->setFieldV256(sfIndexes, v);
101 view.update(p);
102
103 JLOG(j_.trace()) << "Missing offer " << tip_.index() << " removed from directory "
104 << tip_.dir();
105}
106
107template <StepAmount T>
108static T
110 ReadView const& view,
111 AccountID const& id,
112 T const& amtDefault,
113 Asset const& asset,
114 FreezeHandling freezeHandling,
115 AuthHandling authHandling,
117{
118 if constexpr (std::is_same_v<T, IOUAmount>)
119 {
120 if (id == asset.getIssuer())
121 {
122 // self funded
123 return amtDefault;
124 }
125 }
126 else if constexpr (std::is_same_v<T, MPTAmount>)
127 {
128 if (id == asset.getIssuer())
129 {
130 return toAmount<T>(issuerFundsToSelfIssue(view, asset.get<MPTIssue>()));
131 }
132 }
133
134 return toAmount<T>(accountHolds(view, id, asset, freezeHandling, authHandling, j));
135}
136
137template <StepAmount TIn, StepAmount TOut>
138template <class TTakerPays, class TTakerGets>
139 requires ValidTaker<TTakerPays, TTakerGets>
140[[nodiscard]] bool
142{
143 // Consider removing the offer if:
144 // o `TakerPays` is integral (because XRP/MPT have indivisible units) or
145 // o `TakerPays` and `TakerGets` are both IOU and `TakerPays`<`TakerGets`
146 constexpr bool const kInIsIntegral = !std::is_same_v<TTakerPays, IOUAmount>;
147 constexpr bool const kOutIsIntegral = !std::is_same_v<TTakerGets, IOUAmount>;
148
149 if constexpr (!kInIsIntegral && kOutIsIntegral)
150 {
151 // If only `TakerGets` is integral, the worst this offer's quality can
152 // change is to about 10^-81 `TakerPays` and 1 unit `TakerGets`. This
153 // will be perfect quality for any realistic asset, so these
154 // offers don't need this extra check.
155 return false;
156 }
157
158 if (!ownerFunds_)
159 return false;
160
162 toAmount<TTakerPays>(offer_.amount().in), toAmount<TTakerGets>(offer_.amount().out)};
163
164 if constexpr (!kInIsIntegral && !kOutIsIntegral)
165 {
166 if (Number(ofrAmts.in) >= Number(ofrAmts.out))
167 return false;
168 }
169
170 TTakerGets const ownerFunds = toAmount<TTakerGets>(*ownerFunds_);
171
172 auto const effectiveAmounts = [&] {
173 // Issuer-owned IOU offers are self-funded without a limit. MPT issuer
174 // offers are bounded by remaining issuance capacity, so they still need
175 // to be clipped by ownerFunds.
176 bool const issuerHasUnlimitedFunds = offer_.owner() == offer_.assetOut().getIssuer() &&
177 offer_.assetOut().template holds<Issue>();
178 if (!issuerHasUnlimitedFunds && ownerFunds < ofrAmts.out)
179 {
180 // adjust the amounts by owner funds.
181 //
182 // It turns out we can prevent order book blocking by rounding down
183 // the ceil_out() result.
184 return offer_.quality().ceilOutStrict(ofrAmts, ownerFunds, /* roundUp */ false);
185 }
186 return ofrAmts;
187 }();
188
189 // If either the effective in or out are zero then remove the offer.
190 if (effectiveAmounts.in.signum() <= 0 || effectiveAmounts.out.signum() <= 0)
191 return true;
192
193 if (effectiveAmounts.in > TTakerPays::minPositiveAmount())
194 return false;
195
196 Quality const effectiveQuality{effectiveAmounts};
197 return effectiveQuality < offer_.quality();
198}
199
200template <StepAmount TIn, StepAmount TOut>
201bool
203{
204 // Modifying the order or logic of these
205 // operations causes a protocol breaking change.
206
207 if (!validBook_)
208 return false;
209
210 for (;;)
211 {
212 ownerFunds_ = std::nullopt;
213 // BookTip::step deletes the current offer from the view before
214 // advancing to the next (unless the ledger entry is missing).
215 if (!tip_.step(j_))
216 return false;
217
218 SLE::pointer const entry = tip_.entry();
219
220 // If we exceed the maximum number of allowed steps, we're done.
221 if (!counter_.step())
222 return false;
223
224 // Remove if missing
225 if (!entry)
226 {
227 erase(view_);
229 continue;
230 }
231
232 // Remove if expired
233 using D = NetClock::duration;
234 using Tp = NetClock::time_point;
235 if (entry->isFieldPresent(sfExpiration) && Tp{D{(*entry)[sfExpiration]}} <= expire_)
236 {
237 JLOG(j_.trace()) << "Removing expired offer " << entry->key();
238 permRmOffer(entry->key());
239 continue;
240 }
241
242 offer_ = TOffer<TIn, TOut>(entry, tip_.quality());
243
244 auto const amount(offer_.amount());
245
246 // Remove if either amount is zero
247 if (amount.empty())
248 {
249 JLOG(j_.warn()) << "Removing bad offer " << entry->key();
250 permRmOffer(entry->key());
252 continue;
253 }
254
255 if (isDeepFrozen(view_, offer_.owner(), offer_.assetIn()))
256 {
257 JLOG(j_.trace()) << "Removing deep frozen unfunded offer " << entry->key();
258 permRmOffer(entry->key());
260 continue;
261 }
262
263 // Post-fixCleanup3_4_0 defensive check: an offer indexed in a domain
264 // book must claim that same domain. This can only happen if the book
265 // directory is corrupt (i.e. a separate book indexing bug). An offer
266 // with no sfDomainID at all is just as wrong here: the domain
267 // membership check below is gated on that field being present, so
268 // such an offer would otherwise be consumed from a domain book
269 // without any credential check.
270 if (view_.rules().enabled(fixCleanup3_4_0) && book_.domain.has_value() &&
271 (!entry->isFieldPresent(sfDomainID) ||
272 entry->getFieldH256(sfDomainID) != *book_.domain))
273 {
274 JLOG(j_.error()) << "Offer " << entry->key()
275 << " domain missing or does not match book domain";
277 tecINTERNAL, "Offer domain missing or does not match book domain.");
278 }
279
280 // Pre-fixCleanup3_3_0: validate domain membership for any book.
281 // Post-fixCleanup3_3_0: only validate when walking a domain book.
282 // Hybrid offers carry sfDomainID but also participate in the open
283 // book; expiry of the owner's domain credential should not evict
284 // the offer from the open book.
285 if ((!view_.rules().enabled(fixCleanup3_3_0) || book_.domain.has_value()) &&
286 entry->isFieldPresent(sfDomainID) &&
288 view_, entry->key(), entry->getFieldH256(sfDomainID), j_))
289 {
290 JLOG(j_.trace()) << "Removing offer no longer in domain " << entry->key();
291 permRmOffer(entry->key());
293 continue;
294 }
295
296 // Calculate owner funds
298 view_,
299 offer_.owner(),
300 amount.out,
301 offer_.assetOut(),
304 j_);
305
306 // Check for unfunded offer
308 {
309 // If the owner's balance in the pristine view is the same,
310 // we haven't modified the balance and therefore the
311 // offer is "found unfunded" versus "became unfunded"
312 auto const originalFunds = accountFundsHelper(
314 offer_.owner(),
315 amount.out,
316 offer_.assetOut(),
319 j_);
320
321 if (originalFunds == *ownerFunds_)
322 {
323 permRmOffer(entry->key());
324 JLOG(j_.trace()) << "Removing unfunded offer " << entry->key();
325 }
326 else
327 {
328 JLOG(j_.trace()) << "Removing became unfunded offer " << entry->key();
329 }
331 // See comment at top of loop for how the offer is removed
332 continue;
333 }
334
335 // Partially funded offers can be reduced before BookStep sees them.
336 // If that strict reduction overflows under MPTokensV2, remove the
337 // unusable offer instead of leaving it at the book tip.
338 bool shouldRemoveSmallIncreasedQOffer = false;
339 try
340 {
341 shouldRemoveSmallIncreasedQOffer = shouldRmSmallIncreasedQOffer<TIn, TOut>();
342 }
343 catch (std::overflow_error const&)
344 {
345 if (view_.rules().enabled(featureMPTokensV2))
346 {
347 SOMETIMES(
348 true,
349 "OfferStream::step removed MPT offer with overflowing "
350 "reduced quality");
351 permRmOffer(entry->key());
352 JLOG(j_.warn()) << "Removing offer with overflowing reduced quality "
353 << entry->key();
355 continue;
356 }
357 // The strict reduction only overflows for a crafted MPT offer, and
358 // MPT offers require featureMPTokensV2 (enforced at OfferCreate
359 // preflight). So the amendment is always enabled here and this
360 // legacy re-throw is unreachable in practice.
361 // LCOV_EXCL_START
362 XRPL_ASSERT(
363 view_.rules().enabled(featureMPTokensV2),
364 "xrpl::TOfferStreamBase::step : overflow implies MPTokensV2");
365 throw;
366 // LCOV_EXCL_STOP
367 }
368
369 if (shouldRemoveSmallIncreasedQOffer)
370 {
371 auto const originalFunds = accountFundsHelper(
373 offer_.owner(),
374 amount.out,
375 offer_.assetOut(),
378 j_);
379
380 if (originalFunds == *ownerFunds_)
381 {
382 permRmOffer(entry->key());
383 JLOG(j_.trace()) << "Removing tiny offer due to reduced quality " << entry->key();
384 }
385 else
386 {
387 JLOG(j_.trace()) << "Removing tiny offer that became tiny due "
388 "to reduced quality "
389 << entry->key();
390 }
392 // See comment at top of loop for how the offer is removed
393 continue;
394 }
395
396 break;
397 }
398
399 return true;
400}
401
402template <StepAmount TIn, StepAmount TOut>
403void
405{
406 permToRemove_.insert(offerIndex);
407}
408
417
426} // namespace xrpl
A generic endpoint for log messages.
Definition Journal.h:44
Writeable view to a ledger, for applying a transaction.
Definition ApplyView.h:141
virtual SLE::pointer peek(Keylet const &k)=0
Prepare to modify the SLE associated with key.
virtual void update(SLE::Ref sle)=0
Indicate changes to a peeked SLE.
constexpr TIss const & get() const
AccountID const & getIssuer() const
Definition Asset.cpp:21
Specifies an order book.
Definition Book.h:28
Presents and consumes the offers in an order book.
void permRmOffer(UInt256 const &offerIndex) override
boost::container::flat_set< UInt256 > permToRemove_
std::chrono::time_point< NetClock > time_point
Definition chrono.h:48
std::chrono::duration< rep, period > duration
Definition chrono.h:47
Number is a floating point type that can represent a wide range of values.
Definition Number.h:351
Represents the logical ratio of output currency to input currency.
Definition Quality.h:90
A view into a ledger.
Definition ReadView.h:41
std::shared_ptr< STLedgerEntry > pointer
StepCounter & counter_
Definition OfferStream.h:64
std::optional< TOut > ownerFunds_
Definition OfferStream.h:63
virtual void permRmOffer(UInt256 const &offerIndex)=0
TOfferStreamBase(ApplyView &view, ApplyView &cancelView, Book const &book, NetClock::time_point when, StepCounter &counter, beast::Journal journal)
bool shouldRmSmallIncreasedQOffer() const
ApplyView & cancelView_
Definition OfferStream.h:57
TOut ownerFunds() const
NetClock::time_point const expire_
Definition OfferStream.h:60
TOffer< TIn, TOut > offer_
Definition OfferStream.h:62
beast::Journal const j_
Definition OfferStream.h:55
bool step()
Advance to the next valid offer.
void erase(ApplyView &view)
T find(T... args)
T is_same_v
constexpr Zero kZero
Definition Zero.h:30
Keylet book(Book const &b)
The beginning of an order book.
Definition Indexes.cpp:269
Keylet page(UInt256 const &root, std::uint64_t const index=0) noexcept
A page in a directory.
Definition Indexes.cpp:409
Keylet account(AccountID const &id) noexcept
AccountID root.
Definition Indexes.cpp:220
bool offerInDomain(ReadView const &view, UInt256 const &offerID, Domain const &domainID, beast::Journal j)
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
static T accountFundsHelper(ReadView const &view, AccountID const &id, T const &amtDefault, Asset const &asset, FreezeHandling freezeHandling, AuthHandling authHandling, beast::Journal j)
FreezeHandling
Controls the treatment of frozen account balances.
bool isXRP(AccountID const &c)
Definition AccountID.h:84
bool isDeepFrozen(ReadView const &view, AccountID const &account, Currency const &currency, AccountID const &issuer)
T toAmount(STAmount const &amt)=delete
BaseUInt< 256 > UInt256
Definition base_uint.h:580
AuthHandling
Controls the treatment of unauthorized MPT balances.
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
void erase(STObject &st, TypedField< U > const &f)
Remove a field in an STObject.
Definition STExchange.h:161
@ tecINTERNAL
Definition TER.h:318
STAmount issuerFundsToSelfIssue(ReadView const &view, MPTIssue const &issue)
Determine funds available for an issuer to sell in an issuer owned offer.
STAmount accountHolds(ReadView const &view, AccountID const &account, Currency const &currency, AccountID const &issuer, FreezeHandling zeroIfFrozen, beast::Journal j, SpendableHandling includeFullBalance=SpendableHandling::SimpleBalance)
XRPL_NO_SANITIZE_ADDRESS void Throw(Args &&... args)
Definition contract.h:52
Represents a pair of input and output currencies.
Definition Quality.h:29