xrpld
Loading...
Searching...
No Matches
AccountObjects.cpp
1#include <xrpld/rpc/Context.h>
2#include <xrpld/rpc/detail/RPCHelpers.h>
3#include <xrpld/rpc/detail/RPCLedgerHelpers.h>
4#include <xrpld/rpc/detail/SpecBridge.hpp>
5#include <xrpld/rpc/detail/Tuning.h>
6
7#include <xrpl/basics/base_uint.h>
8#include <xrpl/beast/utility/Zero.h>
9#include <xrpl/beast/utility/instrumentation.h>
10#include <xrpl/json/json_value.h>
11#include <xrpl/ledger/ReadView.h>
12#include <xrpl/ledger/helpers/SponsorHelpers.h>
13#include <xrpl/protocol/AccountID.h>
14#include <xrpl/protocol/ErrorCodes.h>
15#include <xrpl/protocol/Indexes.h>
16#include <xrpl/protocol/LedgerFormats.h>
17#include <xrpl/protocol/RPCErr.h>
18#include <xrpl/protocol/SField.h>
19#include <xrpl/protocol/jss.h>
20#include <xrpl/protocol/nftPageMask.h>
21#include <xrpl/resource/Fees.h>
22
23#include <algorithm>
24#include <cstdint>
25#include <memory>
26#include <optional>
27#include <string>
28#include <vector>
29
30namespace xrpl {
31
43bool
45 ReadView const& ledger,
46 AccountID const& account,
48 UInt256 dirIndex,
49 UInt256 entryIndex,
50 std::uint32_t const limit,
51 std::optional<bool> const sponsoredFilter,
52 json::Value& jvResult)
53{
54 // check if dirIndex is valid
55 if (!dirIndex.isZero() && !ledger.read({ltDIR_NODE, dirIndex}))
56 return false;
57
58 auto const typeMatchesFilter = [](std::vector<LedgerEntryType> const& typeFilter,
59 LedgerEntryType ledgerType) {
60 auto const it = std::ranges::find(typeFilter, ledgerType);
61 return it != typeFilter.end();
62 };
63
64 auto const sponsoredMatchesFilter =
65 [&sponsoredFilter](std::optional<AccountID> const& sponsor) {
66 if (!sponsoredFilter.has_value())
67 return true;
68 return sponsor.has_value() == *sponsoredFilter;
69 };
70
71 // if dirIndex != 0, then all NFTs have already been returned. only
72 // iterate NFT pages if the filter says so AND dirIndex == 0
73 bool iterateNFTPages =
74 (!typeFilter.has_value() || typeMatchesFilter(typeFilter.value(), ltNFTOKEN_PAGE)) &&
75 dirIndex.isZero();
76
77 Keylet const firstNFTPage = keylet::nftokenPageMin(account);
78
79 // we need to check the marker to see if it is an NFTTokenPage index.
80 if (iterateNFTPages && entryIndex.isNonZero())
81 {
82 // if it is we will try to iterate the pages up to the limit
83 // and then change over to the owner directory
84
85 if (firstNFTPage.key != (entryIndex & ~nft::kPageMask))
86 iterateNFTPages = false;
87 }
88
89 auto& jvObjects = (jvResult[jss::account_objects] = json::ValueType::Array);
90
91 // this is a mutable version of limit, used to seamlessly switch
92 // to iterating directory entries when nftokenpages are exhausted
93 uint32_t limitLeft = limit;
94
95 // iterate NFTokenPages preferentially
96 if (iterateNFTPages)
97 {
98 Keylet const first =
99 entryIndex.isZero() ? firstNFTPage : Keylet{ltNFTOKEN_PAGE, entryIndex};
100
101 Keylet const last = keylet::nftokenPageMax(account);
102
103 auto currentKey = ledger.succ(first.key, last.key.next()).value_or(last.key);
104
105 auto currentPage = ledger.read(Keylet{ltNFTOKEN_PAGE, currentKey});
106
107 while (currentPage)
108 {
109 std::optional<AccountID> const nftSponsor = currentPage->at(~sfSponsor);
110 bool const canAppendNFT = sponsoredMatchesFilter(nftSponsor);
111 if (canAppendNFT)
112 jvObjects.append(currentPage->getJson());
113 auto const npm = (*currentPage)[~sfNextPageMin];
114 if (npm)
115 {
116 currentPage = ledger.read(Keylet(ltNFTOKEN_PAGE, *npm));
117 }
118 else
119 {
120 currentPage = nullptr;
121 }
122
123 if (--limitLeft == 0 && currentPage)
124 {
125 jvResult[jss::limit] = limit;
126 jvResult[jss::marker] = std::string("0,") + to_string(currentKey);
127 return true;
128 }
129
130 if (!npm)
131 break;
132
133 currentKey = *npm;
134 }
135
136 // if execution reaches here then we're about to transition
137 // to iterating the root directory (and the conventional
138 // behaviour of this RPC function.) Therefore we should
139 // zero entryIndex so as not to terribly confuse things.
140 entryIndex = beast::kZero;
141 }
142
143 auto const root = keylet::ownerDir(account);
144 auto startEntryFound = false;
145
146 if (dirIndex.isZero())
147 {
148 dirIndex = root.key;
149 startEntryFound = true;
150 }
151
152 auto dir = ledger.read({ltDIR_NODE, dirIndex});
153 if (!dir)
154 {
155 // it's possible the user had nftoken pages but no
156 // directory entries. If there's no nftoken page, we will
157 // give empty array for account_objects.
158 if (limitLeft >= limit)
159 jvResult[jss::account_objects] = json::ValueType::Array;
160
161 // non-zero dirIndex validity was checked in the beginning of this
162 // function; by this point, it should be zero. This function returns
163 // true regardless of nftoken page presence; if absent, account_objects
164 // is already set as an empty array. Notice we will only return false in
165 // this function when entryIndex can not be found, indicating an invalid
166 // marker error.
167 return true;
168 }
169
170 std::uint32_t itemsAdded = 0;
171 for (;;)
172 {
173 auto const& dirEntries = dir->getFieldV256(sfIndexes);
174 auto entryIter = dirEntries.begin();
175
176 if (!startEntryFound)
177 {
178 entryIter = std::find(entryIter, dirEntries.end(), entryIndex);
179 if (entryIter == dirEntries.end())
180 return false;
181
182 startEntryFound = true;
183 }
184
185 // it's possible that the returned NFTPages exactly filled the
186 // response. Check for that condition.
187 if (itemsAdded == limitLeft && limitLeft < limit && entryIter != dirEntries.end())
188 {
189 jvResult[jss::limit] = limit;
190 jvResult[jss::marker] = to_string(dirIndex) + ',' + to_string(*entryIter);
191 return true;
192 }
193
194 for (; entryIter != dirEntries.end(); ++entryIter)
195 {
196 auto const sleNode = ledger.read(keylet::child(*entryIter));
197 if (!sleNode)
198 {
199 // LCOV_EXCL_START
200 UNREACHABLE("xrpl::doAccountObjects : null SLE");
201 continue;
202 // LCOV_EXCL_STOP
203 }
204
205 bool canAppend = true;
206
207 if (typeFilter.has_value() &&
208 !typeMatchesFilter(typeFilter.value(), sleNode->getType()))
209 canAppend = false;
210
211 // An object counts as sponsored no matter which party's directory
212 // it was found through; the sponsorship need not belong to
213 // `account`'s side.
215 if (sleNode->getType() == ltRIPPLE_STATE)
216 {
217 sponsor = getLedgerEntryReserveSponsorID(sleNode, sfHighSponsor);
218 if (!sponsor)
219 sponsor = getLedgerEntryReserveSponsorID(sleNode, sfLowSponsor);
220 }
221 else if (isLedgerEntrySupportedBySponsorship(*sleNode))
222 {
223 sponsor = getLedgerEntryReserveSponsorID(sleNode);
224 }
225
226 if (!sponsoredMatchesFilter(sponsor))
227 canAppend = false;
228
229 if (canAppend)
230 jvObjects.append(sleNode->getJson(JsonOptions::Values::None));
231
232 if (++itemsAdded == limitLeft)
233 {
234 if (++entryIter != dirEntries.end())
235 {
236 jvResult[jss::limit] = limit;
237 jvResult[jss::marker] = to_string(dirIndex) + ',' + to_string(*entryIter);
238 return true;
239 }
240
241 break;
242 }
243 }
244
245 auto const nodeIndex = dir->getFieldU64(sfIndexNext);
246 if (nodeIndex == 0)
247 return true;
248
249 dirIndex = keylet::page(root, nodeIndex).key;
250 dir = ledger.read({ltDIR_NODE, dirIndex});
251 if (!dir)
252 return true;
253
254 if (itemsAdded == limitLeft)
255 {
256 auto const& currentDirEntries = dir->getFieldV256(sfIndexes);
257 if (!currentDirEntries.empty())
258 {
259 jvResult[jss::limit] = limit;
260 jvResult[jss::marker] =
261 to_string(dirIndex) + ',' + to_string(*currentDirEntries.begin());
262 }
263
264 return true;
265 }
266 }
267}
268
271{
272 auto const& params = context.params;
273 if (!params.isMember(jss::account))
274 return rpc::missingFieldError(jss::account);
275
276 if (!params[jss::account].isString())
277 return rpc::invalidFieldError(jss::account);
278
280 auto result = rpc::lookupLedger(ledger, context);
281 if (ledger == nullptr)
282 return result;
283
284 auto const id = parseBase58<AccountID>(params[jss::account].asString());
285 if (!id)
286 {
288 return result;
289 }
290 auto const accountID{id.value()};
291
292 if (!ledger->exists(keylet::account(accountID)))
293 return rpcError(RpcActNotFound);
294
296
297 if (params.isMember(jss::deletion_blockers_only) &&
298 params[jss::deletion_blockers_only].asBool())
299 {
300 struct
301 {
303 LedgerEntryType type;
304 } static constexpr kDeletionBlockers[] = {
305 {.name = jss::check, .type = ltCHECK},
306 {.name = jss::escrow, .type = ltESCROW},
307 {.name = jss::nft_page, .type = ltNFTOKEN_PAGE},
308 {.name = jss::payment_channel, .type = ltPAYCHAN},
309 {.name = jss::state, .type = ltRIPPLE_STATE},
310 {.name = jss::mpt_issuance, .type = ltMPTOKEN_ISSUANCE},
311 {.name = jss::mptoken, .type = ltMPTOKEN},
312 {.name = jss::permissioned_domain, .type = ltPERMISSIONED_DOMAIN},
313 {.name = jss::vault, .type = ltVAULT},
314 {.name = jss::sponsorship, .type = ltSPONSORSHIP},
315 {.name = jss::transaction_proposal, .type = ltTRANSACTION_PROPOSAL},
316 };
317
318 typeFilter.emplace();
319 typeFilter->reserve(std::size(kDeletionBlockers));
320
321 for (auto [name, type] : kDeletionBlockers)
322 {
323 if (params.isMember(jss::type) && name != params[jss::type])
324 {
325 continue;
326 }
327
328 typeFilter->push_back(type);
329 }
330 }
331 else
332 {
333 auto [rpcStatus, type] = rpc::chooseLedgerEntryType(params);
334
336 return rpc::invalidFieldError(jss::type);
337
338 if (rpcStatus)
339 {
340 result.clear();
341 rpc::injectSpecError(result, rpcStatus);
342 return result;
343 }
344 if (type != ltANY)
345 {
346 typeFilter = std::vector<LedgerEntryType>({type});
347 }
348 }
349
350 unsigned int limit = 0;
351 if (auto err = readLimitField(limit, rpc::tuning::kAccountObjects, context))
352 return *err;
353
354 UInt256 dirIndex;
355 UInt256 entryIndex;
356 if (params.isMember(jss::marker))
357 {
358 auto const& marker = params[jss::marker];
359 if (!marker.isString())
360 return rpc::expectedFieldError(jss::marker, "string");
361
362 auto const& markerStr = marker.asString();
363 auto const& idx = markerStr.find(',');
364 if (idx == std::string::npos)
365 return rpc::invalidFieldError(jss::marker);
366
367 if (!dirIndex.parseHex(markerStr.substr(0, idx)))
368 return rpc::invalidFieldError(jss::marker);
369
370 if (!entryIndex.parseHex(markerStr.substr(idx + 1)))
371 return rpc::invalidFieldError(jss::marker);
372 }
373
374 std::optional<bool> sponsoredFilter;
375 if (params.isMember(jss::sponsored))
376 {
377 auto const& sponsoredJv = params[jss::sponsored];
378 if (!sponsoredJv.isBool())
379 return rpc::expectedFieldError(jss::sponsored, "boolean");
380
381 sponsoredFilter = sponsoredJv.asBool();
382 }
383
385 *ledger, accountID, typeFilter, dirIndex, entryIndex, limit, sponsoredFilter, result))
386 return rpc::invalidFieldError(jss::marker);
387
388 result[jss::account] = toBase58(accountID);
390 return result;
391}
392
393} // namespace xrpl
Lightweight wrapper to tag static string.
Definition json_value.h:52
Represents a JSON value.
Definition json_value.h:121
bool isZero() const
Definition base_uint.h:563
bool isNonZero() const
Definition base_uint.h:568
BaseUInt next() const
Definition base_uint.h:478
constexpr bool parseHex(std::string_view sv)
Parse a hex string into a base_uint.
Definition base_uint.h:526
A view into a ledger.
Definition ReadView.h:41
virtual SLE::const_pointer read(Keylet const &k) const =0
Return the state item associated with a key.
virtual std::optional< key_type > succ(key_type const &key, std::optional< key_type > const &last=std::nullopt) const =0
Return the key of the next state item.
T emplace(T... args)
T end(T... args)
T find(T... args)
constexpr Zero kZero
Definition Zero.h:30
@ Array
array value (ordered list)
Definition json_value.h:32
Keylet ownerDir(AccountID const &id) noexcept
The root page of an account's directory.
Definition Indexes.cpp:415
Keylet nftokenPageMin(AccountID const &owner)
NFT page keylets.
Definition Indexes.cpp:442
Keylet nftokenPageMax(AccountID const &owner)
A keylet for the owner's last possible NFT page.
Definition Indexes.cpp:450
Keylet page(UInt256 const &root, std::uint64_t const index=0) noexcept
A page in a directory.
Definition Indexes.cpp:421
Keylet account(AccountID const &id) noexcept
AccountID root.
Definition Indexes.cpp:233
Keylet child(UInt256 const &key) noexcept
Any item that can be in an owner dir.
Definition Indexes.cpp:239
constexpr UInt256 kPageMask(std::string_view("0000000000000000000000000000000000000000ffffffffffffffffffffffff"))
Charge const kFeeMediumBurdenRpc
static constexpr LimitRange kAccountObjects
Limits for the account_objects command.
json::Value expectedFieldError(std::string const &name, std::string const &type)
Definition ErrorCodes.h:309
void injectError(ErrorCodeI code, json::Value &json)
Add or update the json update to reflect the error code.
json::Value invalidFieldError(std::string const &name)
Definition ErrorCodes.h:285
::rpc::Status lookupLedger(std::shared_ptr< ReadView const > &ledger, JsonContext const &context, json::Value &result)
Looks up a ledger from a request and fills a json::Value with ledger data.
json::Value missingFieldError(std::string const &name)
Definition ErrorCodes.h:243
std::pair<::rpc::Status, LedgerEntryType > chooseLedgerEntryType(json::Value const &params)
Chooses the ledger entry type based on RPC parameters.
bool isAccountObjectsValidType(LedgerEntryType const &type)
Checks if the type is a valid filtering type for the account_objects method.
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
@ RpcActNotFound
Definition ErrorCodes.h:53
@ RpcActMalformed
Definition ErrorCodes.h:73
std::optional< AccountID > parseBase58(std::string const &s)
Parse AccountID from checked, base58 string.
std::optional< AccountID > getLedgerEntryReserveSponsorID(SLE::ConstRef sle, SF_ACCOUNT const &field=sfSponsor)
Return the AccountID stored in the given sponsor field of a ledger entry, or nullopt if absent.
std::string toBase58(AccountID const &v)
Convert AccountID to base58 checked string.
Definition AccountID.cpp:95
bool getAccountObjects(ReadView const &ledger, AccountID const &account, std::optional< std::vector< LedgerEntryType > > const &typeFilter, UInt256 dirIndex, UInt256 entryIndex, std::uint32_t const limit, std::optional< bool > const sponsoredFilter, json::Value &jvResult)
Gathers all objects for an account in a ledger.
Number root(Number f, unsigned d)
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
json::Value rpcError(ErrorCodeI iError)
Definition RPCErr.cpp:13
BaseUInt< 256 > UInt256
Definition base_uint.h:581
json::Value doAccountObjects(rpc::JsonContext &context)
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
LedgerEntryType
Identifiers for on-ledger objects.
@ ltANY
A special type, matching any ledger entry type.
bool isLedgerEntrySupportedBySponsorship(SLE const &sle)
Whether this ledger entry type can have a reserve sponsor attached to it.
T has_value(T... args)
T size(T... args)
A pair of SHAMap key and LedgerEntryType.
Definition Keylet.h:20
UInt256 key
Definition Keylet.h:21
resource::Charge & loadType
Definition Context.h:30
json::Value params
Definition Context.h:51