xrpld
Loading...
Searching...
No Matches
AccountInfo.cpp
1#include <xrpld/rpc/handlers/account/AccountInfo.h>
2
3#include <xrpld/app/main/Application.h>
4#include <xrpld/app/misc/TxQ.h>
5#include <xrpld/rpc/Context.h>
6#include <xrpld/rpc/detail/RPCLedgerHelpers.h>
7
8#include <xrpl/basics/Blob.h>
9#include <xrpl/basics/Slice.h>
10#include <xrpl/basics/StringUtilities.h>
11#include <xrpl/basics/base_uint.h>
12#include <xrpl/basics/strHex.h>
13#include <xrpl/beast/utility/instrumentation.h>
14#include <xrpl/json/json_forwards.h>
15#include <xrpl/json/json_value.h>
16#include <xrpl/ledger/ReadView.h>
17#include <xrpl/ledger/helpers/AccountRootHelpers.h>
18#include <xrpl/protocol/AccountID.h>
19#include <xrpl/protocol/ErrorCodes.h>
20#include <xrpl/protocol/Feature.h>
21#include <xrpl/protocol/Indexes.h>
22#include <xrpl/protocol/LedgerFormats.h>
23#include <xrpl/protocol/SField.h>
24#include <xrpl/protocol/STLedgerEntry.h>
25#include <xrpl/protocol/SeqProxy.h>
26#include <xrpl/protocol/Units.h>
27#include <xrpl/protocol/XRPAmount.h>
28#include <xrpl/protocol/jss.h>
29
30#include <rpcspec/Errors.hpp>
31
32#include <array>
33#include <cstdint>
34#include <expected>
35#include <format>
36#include <optional>
37#include <string>
38#include <string_view>
39#include <tuple>
40#include <utility>
41#include <vector>
42
43namespace xrpl::rpc {
44
45namespace {
46
59void
60injectSLE(json::Value& jv, SLE const& sle)
61{
62 jv = sle.getJson(JsonOptions::Values::None);
63 XRPL_ASSERT(sle.getType() == ltACCOUNT_ROOT, "xrpl::rpc::injectSLE : sle is account root");
64 if (sle.isFieldPresent(sfEmailHash))
65 {
66 auto const& hash = sle.getFieldH128(sfEmailHash);
67 Blob const b(hash.begin(), hash.end());
68 std::string md5 = strHex(makeSlice(b));
69 md5 = toLower(md5);
70 // VFALCO TODO Give a name to this constant and move it
71 // to a more visible location.
72 jv[jss::urlgravatar] = std::format("https://www.gravatar.com/avatar/{}", md5);
73 }
74}
75
76void
77writeAccountRoot(json::Value& value, SLE const& accountRoot, ReadView const& ledger)
78{
79 // Flags that are always reported.
80 static constexpr auto kAccountRootFlags =
81 std::to_array<std::pair<std::string_view, LedgerSpecificFlags>>({
82 {"allowTrustLineClawback", lsfAllowTrustLineClawback},
83 {"defaultRipple", lsfDefaultRipple},
84 {"depositAuth", lsfDepositAuth},
85 {"disableMasterKey", lsfDisableMaster},
86 {"disallowIncomingCheck", lsfDisallowIncomingCheck},
87 {"disallowIncomingNFTokenOffer", lsfDisallowIncomingNFTokenOffer},
88 {"disallowIncomingPayChan", lsfDisallowIncomingPayChan},
89 {"disallowIncomingTrustline", lsfDisallowIncomingTrustline},
90 {"disallowIncomingXRP", lsfDisallowXRP},
91 {"globalFreeze", lsfGlobalFreeze},
92 {"noFreeze", lsfNoFreeze},
93 {"passwordSpent", lsfPasswordSpent},
94 {"requireAuthorization", lsfRequireAuth},
95 {"requireDestinationTag", lsfRequireDestTag},
96 });
97
98 // Flags that are only reported when their amendment is enabled. This can't be `constexpr`,
99 // since the amendment IDs are computed at runtime.
100 static auto const kAmendmentGatedFlags =
101 std::to_array<std::tuple<std::string_view, LedgerSpecificFlags, UInt256 const&>>(
102 {{"allowTrustLineLocking", lsfAllowTrustLineLocking, featureTokenEscrow}});
103
104 // Every `AccountRoot` flag must be reported by `account_info`, so if a new flag is added, it
105 // needs to be added to one of the arrays above. This can't be a `static_assert` because
106 // `getAccountRootFlags()` builds its map at runtime.
107 XRPL_ASSERT_PARTS(
108 kAccountRootFlags.size() + kAmendmentGatedFlags.size() == getAccountRootFlags().size(),
109 "xrpl::rpc::writeAccountRoot",
110 "number of account flags");
111
112 json::Value jvAccepted(json::ValueType::Object);
113 injectSLE(jvAccepted, accountRoot);
114 value[jss::account_data] = jvAccepted;
115
116 json::Value acctFlags{json::ValueType::Object};
117 for (auto const& [name, flag] : kAccountRootFlags)
118 acctFlags[name.data()] = accountRoot.isFlag(flag);
119
120 for (auto const& [name, flag, amendment] : kAmendmentGatedFlags)
121 {
122 if (ledger.rules().enabled(amendment))
123 acctFlags[name.data()] = accountRoot.isFlag(flag);
124 }
125
126 value[jss::account_flags] = std::move(acctFlags);
127
128 auto const pseudoFields = getPseudoAccountFields();
129 for (auto const& pseudoField : pseudoFields)
130 {
131 if (accountRoot.isFieldPresent(*pseudoField))
132 {
133 std::string name = pseudoField->fieldName;
134 if (name.ends_with("ID"))
135 {
136 // Remove the ID suffix from the field name.
137 name = name.substr(0, name.size() - 2);
138 XRPL_ASSERT_PARTS(
139 !name.empty(), "xrpl::rpc::writeAccountRoot", "name is not empty");
140 }
141 // ValidPseudoAccounts invariant guarantees that only one field
142 // can be set
143 value[jss::pseudo_account][jss::type] = name;
144 break;
145 }
146 }
147}
148
149[[nodiscard]] json::Value
150queueDataJson(std::vector<TxQ::TxDetails> const& txs)
151{
152 json::Value jvQueueData = json::ValueType::Object;
153
154 if (txs.empty())
155 {
156 jvQueueData[jss::txn_count] = 0u;
157 return jvQueueData;
158 }
159
160 jvQueueData[jss::txn_count] = static_cast<json::UInt>(txs.size());
161
162 auto& jvQueueTx = jvQueueData[jss::transactions];
163 jvQueueTx = json::ValueType::Array;
164
165 std::uint32_t seqCount = 0;
166 std::uint32_t ticketCount = 0;
167 std::optional<std::uint32_t> lowestSeq;
168 std::optional<std::uint32_t> highestSeq;
169 std::optional<std::uint32_t> lowestTicket;
170 std::optional<std::uint32_t> highestTicket;
171 bool anyAuthChanged = false;
172 XRPAmount totalSpend(0);
173
174 // We expect txs to be returned sorted by SeqProxy. Verify
175 // that with a couple of asserts.
176 SeqProxy prevSeqProxy = SeqProxy::rawSequence(0);
177 for (auto const& tx : txs)
178 {
179 json::Value jvTx = json::ValueType::Object;
180
181 if (tx.seqProxy.isSeq())
182 {
183 XRPL_ASSERT(
184 prevSeqProxy < tx.seqProxy, "xrpl::rpc::queueDataJson : first sorted proxy");
185 prevSeqProxy = tx.seqProxy;
186 jvTx[jss::seq] = tx.seqProxy.value();
187 ++seqCount;
188 if (!lowestSeq.has_value())
189 lowestSeq = tx.seqProxy.value();
190 highestSeq = tx.seqProxy.value();
191 }
192 else
193 {
194 XRPL_ASSERT(
195 prevSeqProxy < tx.seqProxy, "xrpl::rpc::queueDataJson : second sorted proxy");
196 prevSeqProxy = tx.seqProxy;
197 jvTx[jss::ticket] = tx.seqProxy.value();
198 ++ticketCount;
199 if (!lowestTicket.has_value())
200 lowestTicket = tx.seqProxy.value();
201 highestTicket = tx.seqProxy.value();
202 }
203
204 jvTx[jss::fee_level] = to_string(tx.feeLevel);
205 if (tx.lastValid.has_value())
206 jvTx[jss::LastLedgerSequence] = *tx.lastValid;
207
208 jvTx[jss::fee] = to_string(tx.consequences.fee());
209 auto const spend = tx.consequences.potentialSpend() + tx.consequences.fee();
210 jvTx[jss::max_spend_drops] = to_string(spend);
211 totalSpend += spend;
212 bool const authChanged = tx.consequences.isBlocker();
213 if (authChanged)
214 anyAuthChanged = authChanged;
215 jvTx[jss::auth_change] = authChanged;
216
217 jvQueueTx.append(std::move(jvTx));
218 }
219
220 if (seqCount != 0u)
221 jvQueueData[jss::sequence_count] = seqCount;
222 if (ticketCount != 0u)
223 jvQueueData[jss::ticket_count] = ticketCount;
224 if (lowestSeq.has_value())
225 jvQueueData[jss::lowest_sequence] = *lowestSeq;
226 if (highestSeq.has_value())
227 jvQueueData[jss::highest_sequence] = *highestSeq;
228 if (lowestTicket.has_value())
229 jvQueueData[jss::lowest_ticket] = *lowestTicket;
230 if (highestTicket.has_value())
231 jvQueueData[jss::highest_ticket] = *highestTicket;
232
233 jvQueueData[jss::auth_change_queued] = anyAuthChanged;
234 jvQueueData[jss::max_spend_drops_total] = to_string(totalSpend);
235
236 return jvQueueData;
237}
238
239} // namespace
240
244
245std::expected<AccountInfoHandler::Output, ::rpc::Status>
246AccountInfoHandler::process(Input const& input) const
247{
248 auto& context = context_.get();
249
250 Output output;
251 if (auto const status = getLedger(output.ledger, input.ledger, context);
252 status != ::rpc::Status::kOK)
253 return std::unexpected{status};
254 auto const& ledger = *output.ledger;
255
256 if (!input.account.has_value())
257 {
258 output.error = RpcActMalformed;
259 return output;
260 }
261 output.account = *input.account;
262
263 auto const accountRoot = ledger.read(keylet::account(output.account));
264 if (!accountRoot)
265 {
266 output.error = RpcActNotFound;
267 return output;
268 }
269
270 // It doesn't make sense to request the queue
271 // with any closed or validated ledger.
272 if (input.queue && !ledger.open())
273 {
274 output.error = RpcInvalidParams;
275 return output;
276 }
277
278 output.accountRoot = accountRoot;
279
280 // The document[https://xrpl.org/account_info.html#account_info] states
281 // that signer_lists is a bool, however assigning any string value
282 // works. Do not allow this. This check is for api Version 2 onwards
283 // only
284 auto const& params = context.params;
285 if (context.apiVersion > 1u && params.isMember(jss::signer_lists) &&
286 !params[jss::signer_lists].isBool())
287 {
288 output.error = RpcInvalidParams;
289 return output;
290 }
291
292 // This code will need to be revisited if in the future we support
293 // multiple SignerLists on one account.
294 if (input.signerLists)
295 output.signerList = ledger.read(keylet::signerList(output.account));
296
297 if (input.queue)
298 output.queue = context.app.getTxQ().getAccountTxs(output.account);
299
300 return output;
301}
302
303void
305{
306 auto const& context = context_.get();
307 injectLedgerFields(*output.ledger, context, value);
308
309 if (output.accountRoot)
310 writeAccountRoot(value, *output.accountRoot, *output.ledger);
311
312 if (output.error.has_value())
313 {
314 if (*output.error == RpcActNotFound)
315 value[jss::account] = toBase58(output.account);
316 injectError(*output.error, value);
317 return;
318 }
319
320 if (output.signerList.has_value())
321 {
322 // We put the SignerList in an array because of an anticipated
323 // future when we support multiple signer lists on one account.
324 json::Value jvSignerList = json::ValueType::Array;
325 if (*output.signerList)
326 jvSignerList.append((*output.signerList)->getJson(JsonOptions::Values::None));
327
328 // Documentation states this is returned as part of the account_info
329 // response, but previously the code put it under account_data. We
330 // can move this to the documented location from apiVersion 2
331 // onwards.
332 if (context.apiVersion == 1)
333 {
334 value[jss::account_data][jss::signer_lists] = std::move(jvSignerList);
335 }
336 else
337 {
338 value[jss::signer_lists] = std::move(jvSignerList);
339 }
340 }
341
342 if (output.queue.has_value())
343 value[jss::queue_data] = queueDataJson(*output.queue);
344}
345
346} // namespace xrpl::rpc
Represents a JSON value.
Definition json_value.h:121
Value & append(Value const &value)
Append value to array at the end.
static constexpr SeqProxy rawSequence(std::uint32_t v)
Factory function to return a sequence-based SeqProxy.
Definition SeqProxy.h:62
std::expected< Output, ::rpc::Status > process(Input const &input) const
Process the request.
std::reference_wrapper< JsonContext > context_
Definition AccountInfo.h:71
AccountInfoHandler(JsonContext &context)
Construct a handler for a single request.
void writeResult(json::Value &value, Output const &output) const
Write the output of process() into the response.
T empty(T... args)
T ends_with(T... args)
T format(T... args)
unsigned int UInt
@ Array
array value (ordered list)
Definition json_value.h:32
@ Object
object value (collection of name/value pairs).
Definition json_value.h:33
Keylet signerList(AccountID const &account) noexcept
A SignerList.
Definition Indexes.cpp:360
Keylet account(AccountID const &id) noexcept
AccountID root.
Definition Indexes.cpp:233
The api_version numbers this server serves.
Definition ApiVersion.h:26
void injectError(ErrorCodeI code, json::Value &json)
Add or update the json update to reflect the error code.
::rpc::Status getLedger(T &ledger, UInt256 const &ledgerHash, Context const &context)
Retrieves a ledger by its hash.
void injectLedgerFields(ReadView const &ledger, Context const &context, json::Value &result)
Writes the fields that identify a ledger into a result.
constexpr XRPAmount
Convert XRP to drops (integral types).
Definition TxTest.h:53
std::vector< SField const * > const & getPseudoAccountFields()
Returns the list of fields that define an ACCOUNT_ROOT as a pseudo-account if set.
@ RpcActNotFound
Definition ErrorCodes.h:53
@ RpcActMalformed
Definition ErrorCodes.h:73
@ RpcInvalidParams
Definition ErrorCodes.h:67
std::string toLower(std::string str)
Fold ASCII upper case letters to lower case.
std::string strHex(FwdIt begin, FwdIt end)
Definition strHex.h:13
std::string toBase58(AccountID const &v)
Convert AccountID to base58 checked string.
Definition AccountID.cpp:95
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
STLedgerEntry SLE
Slice makeSlice(std::array< T, N > const &a)
Definition Slice.h:228
std::vector< unsigned char > Blob
Storage for linear binary data.
Definition Blob.h:11
T has_value(T... args)
T size(T... args)
The data an account_info request produces, written out by writeResult().
Definition AccountInfo.h:36
std::shared_ptr< ReadView const > ledger
The ledger the request selected.
Definition AccountInfo.h:37
SLE::const_pointer accountRoot
The account root, once it was read.
Definition AccountInfo.h:40
std::optional< std::vector< TxQ::TxDetails > > queue
The requested queued transactions.
Definition AccountInfo.h:42
AccountID account
The account; written only if not found.
Definition AccountInfo.h:39
std::optional< SLE::const_pointer > signerList
The requested signer list, or null.
Definition AccountInfo.h:41
std::optional< ErrorCodeI > error
An error written with the ledger fields.
Definition AccountInfo.h:38
T substr(T... args)
T unexpected(T... args)
T value(T... args)