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