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