xrpld
Loading...
Searching...
No Matches
CredentialHelpers.cpp
1#include <xrpl/ledger/helpers/CredentialHelpers.h>
2
3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/Slice.h>
5#include <xrpl/basics/base_uint.h>
6#include <xrpl/basics/chrono.h>
7#include <xrpl/beast/utility/Journal.h>
8#include <xrpl/ledger/ApplyView.h>
9#include <xrpl/ledger/ReadView.h>
10#include <xrpl/ledger/entries/DepositPreauthEntry.h>
11#include <xrpl/ledger/helpers/AccountRootHelpers.h>
12#include <xrpl/protocol/AccountID.h>
13#include <xrpl/protocol/Feature.h>
14#include <xrpl/protocol/Indexes.h>
15#include <xrpl/protocol/LedgerFormats.h>
16#include <xrpl/protocol/Protocol.h>
17#include <xrpl/protocol/SField.h>
18#include <xrpl/protocol/STArray.h>
19#include <xrpl/protocol/STLedgerEntry.h>
20#include <xrpl/protocol/STObject.h>
21#include <xrpl/protocol/STTx.h>
22#include <xrpl/protocol/STVector256.h>
23#include <xrpl/protocol/TER.h>
24#include <xrpl/protocol/digest.h>
25
26#include <algorithm>
27#include <cstdint>
28#include <expected>
29#include <limits>
30#include <set>
31#include <unordered_set>
32#include <utility>
33#include <vector>
34
35namespace xrpl {
36namespace credentials {
37
38bool
39checkExpired(SLE const& sleCredential, NetClock::time_point const& closed)
40{
41 std::uint32_t const exp =
42 sleCredential[~sfExpiration].value_or(std::numeric_limits<std::uint32_t>::max());
43 std::uint32_t const now = closed.time_since_epoch().count();
44 return now > exp;
45}
46
47[[nodiscard]]
48static std::expected<bool, TER>
50{
51 auto const closeTime = view.header().parentCloseTime;
52 bool foundExpired = false;
53
54 for (auto const& h : arr)
55 {
56 // Credentials already checked in preclaim. Look only for expired here.
57 if (view.rules().enabled(fixCleanup3_4_0) && h.isZero())
58 return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE
59
60 auto const k = keylet::credential(h);
61 auto const sleCred = view.peek(k);
62
63 if (sleCred && checkExpired(*sleCred, closeTime))
64 {
65 JLOG(j.trace()) << "Credentials are expired. Cred: " << sleCred->getText();
66 // delete expired credentials even if the transaction failed
67 auto const err = deleteSLE(view, sleCred, j);
68 if (view.rules().enabled(fixCleanup3_1_3) && !isTesSuccess(err))
69 return std::unexpected(err);
70 foundExpired = true;
71 }
72 }
73
74 return foundExpired;
75}
76
77TER
79{
80 if (!sleCredential)
81 return tecNO_ENTRY;
82
83 auto const delSLE = [&view, &sleCredential, j](
84 AccountID const& account, SField const& node, bool isOwner) -> TER {
85 auto const sleAccount = view.peek(keylet::account(account));
86 if (!sleAccount)
87 {
88 // LCOV_EXCL_START
89 JLOG(j.fatal()) << "Internal error: can't retrieve Owner account.";
90 return tecINTERNAL;
91 // LCOV_EXCL_STOP
92 }
93
94 // Remove object from owner directory
95 std::uint64_t const page = sleCredential->getFieldU64(node);
96 if (!view.dirRemove(keylet::ownerDir(account), page, sleCredential->key(), false))
97 {
98 // LCOV_EXCL_START
99 JLOG(j.fatal()) << "Unable to delete Credential from owner.";
100 return tefBAD_LEDGER;
101 // LCOV_EXCL_STOP
102 }
103
104 if (isOwner)
105 decreaseOwnerCountForObject(view, sleAccount, sleCredential, 1, j);
106
107 return tesSUCCESS;
108 };
109
110 auto const issuer = sleCredential->getAccountID(sfIssuer);
111 auto const subject = sleCredential->getAccountID(sfSubject);
112 bool const accepted = sleCredential->isFlag(lsfAccepted);
113
114 auto err = delSLE(issuer, sfIssuerNode, !accepted || (subject == issuer));
115 if (!isTesSuccess(err))
116 return err;
117
118 if (subject != issuer)
119 {
120 err = delSLE(subject, sfSubjectNode, accepted);
121 if (!isTesSuccess(err))
122 return err;
123 }
124
125 // Remove object from ledger
126 view.erase(sleCredential);
127
128 return tesSUCCESS;
129}
130
131NotTEC
132checkFields(STTx const& tx, Rules const& rules, beast::Journal j)
133{
134 if (!tx.isFieldPresent(sfCredentialIDs))
135 return tesSUCCESS;
136
137 auto const& credentials = tx.getFieldV256(sfCredentialIDs);
138 if (credentials.empty() || (credentials.size() > kMaxCredentialsArraySize))
139 {
140 JLOG(j.trace()) << "Malformed transaction: Credentials array size is invalid: "
141 << credentials.size();
142 return temMALFORMED;
143 }
144
145 if (rules.enabled(fixCleanup3_4_0) &&
146 std::ranges::any_of(credentials, [](UInt256 const& id) { return id.isZero(); }))
147 {
148 JLOG(j.trace()) << "Malformed transaction: zero credential ID.";
149 return temMALFORMED;
150 }
151
153 for (auto const& cred : credentials)
154 {
155 auto [it, ins] = duplicates.insert(cred);
156 if (!ins)
157 {
158 JLOG(j.trace()) << "Malformed transaction: duplicates in credentials.";
159 return temMALFORMED;
160 }
161 }
162
163 return tesSUCCESS;
164}
165
166TER
167valid(STTx const& tx, ReadView const& view, AccountID const& src, beast::Journal j)
168{
169 if (!tx.isFieldPresent(sfCredentialIDs))
170 return tesSUCCESS;
171
172 auto const& credIDs(tx.getFieldV256(sfCredentialIDs));
173 for (auto const& h : credIDs)
174 {
175 if (view.rules().enabled(fixCleanup3_4_0) && h.isZero())
176 {
177 // LCOV_EXCL_START
178 JLOG(j.trace()) << "Zero credential ID.";
179 return tecINTERNAL;
180 // LCOV_EXCL_STOP
181 }
182
183 auto const sleCred = view.read(keylet::credential(h));
184 if (!sleCred)
185 {
186 JLOG(j.trace()) << "Credential doesn't exist. Cred: " << h;
187 return tecBAD_CREDENTIALS;
188 }
189
190 if (sleCred->getAccountID(sfSubject) != src)
191 {
192 JLOG(j.trace()) << "Credential doesn't belong to the source account. Cred: " << h;
193 return tecBAD_CREDENTIALS;
194 }
195
196 if (!sleCred->isFlag(lsfAccepted))
197 {
198 JLOG(j.trace()) << "Credential isn't accepted. Cred: " << h;
199 return tecBAD_CREDENTIALS;
200 }
201
202 // Expiration checks are in doApply
203 }
204
205 return tesSUCCESS;
206}
207
208TER
209validDomain(ReadView const& view, UInt256 domainID, AccountID const& subject)
210{
211 // Note, permissioned domain objects can be deleted at any time
212 auto const slePD = view.read(keylet::permissionedDomain(domainID));
213 if (!slePD)
214 return tecOBJECT_NOT_FOUND;
215
216 auto const closeTime = view.header().parentCloseTime;
217 bool foundExpired = false;
218 for (auto const& h : slePD->getFieldArray(sfAcceptedCredentials))
219 {
220 auto const issuer = h.getAccountID(sfIssuer);
221 auto const type = h.getFieldVL(sfCredentialType);
222 auto const keyletCredential = keylet::credential(subject, issuer, makeSlice(type));
223 auto const sleCredential = view.read(keyletCredential);
224
225 // We cannot delete expired credentials, that would require ApplyView&
226 // However we can check if credentials are expired. Expected transaction
227 // flow is to use `validDomain` in preclaim, converting tecEXPIRED to
228 // tesSUCCESS, then proceed to call `verifyValidDomain` in doApply. This
229 // allows expired credentials to be deleted by any transaction.
230 if (sleCredential)
231 {
232 if (checkExpired(*sleCredential, closeTime))
233 {
234 foundExpired = true;
235 continue;
236 }
237 if (sleCredential->isFlag(lsfAccepted))
238 {
239 return tesSUCCESS;
240 }
241
242 continue;
243 }
244 }
245
246 return foundExpired ? tecEXPIRED : tecNO_AUTH;
247}
248
249TER
250authorizedDepositPreauth(ReadView const& view, STVector256 const& credIDs, AccountID const& dst)
251{
254 lifeExtender.reserve(credIDs.size());
255 for (auto const& h : credIDs)
256 {
257 if (view.rules().enabled(fixCleanup3_4_0) && h.isZero())
258 return tefINTERNAL; // LCOV_EXCL_LINE
259
260 auto sleCred = view.read(keylet::credential(h));
261 if (!sleCred) // already checked in preclaim
262 return tefINTERNAL; // LCOV_EXCL_LINE
263
264 auto [it, ins] = sorted.emplace((*sleCred)[sfIssuer], (*sleCred)[sfCredentialType]);
265 if (!ins)
266 return tefINTERNAL; // LCOV_EXCL_LINE
267 lifeExtender.push_back(std::move(sleCred));
268 }
269
270 if (!DepositPreauthEntryR(dst, sorted, view))
271 return tecNO_PERMISSION;
272
273 return tesSUCCESS;
274}
275
278{
280 for (auto const& cred : credentials)
281 {
282 auto [it, ins] = out.emplace(cred[sfIssuer], cred[sfCredentialType]);
283 if (!ins)
284 return {};
285 }
286 return out;
287}
288
289NotTEC
290checkArray(STArray const& credentials, unsigned maxSize, beast::Journal j)
291{
292 if (credentials.empty() || (credentials.size() > maxSize))
293 {
294 JLOG(j.trace()) << "Malformed transaction: "
295 "Invalid credentials size: "
296 << credentials.size();
298 }
299
301 for (auto const& credential : credentials)
302 {
303 auto const& issuer = credential[sfIssuer];
304 if (!issuer)
305 {
306 JLOG(j.trace()) << "Malformed transaction: "
307 "Issuer account is invalid: "
308 << to_string(issuer);
310 }
311
312 auto const ct = credential[sfCredentialType];
313 if (ct.empty() || (ct.size() > kMaxCredentialTypeLength))
314 {
315 JLOG(j.trace()) << "Malformed transaction: "
316 "Invalid credentialType size: "
317 << ct.size();
318 return temMALFORMED;
319 }
320
321 auto [it, ins] = duplicates.insert(sha512Half(issuer, ct));
322 if (!ins)
323 {
324 JLOG(j.trace()) << "Malformed transaction: "
325 "duplicates in credentials.";
326 return temMALFORMED;
327 }
328 }
329
330 return tesSUCCESS;
331}
332
333} // namespace credentials
334
335TER
336verifyValidDomain(ApplyView& view, AccountID const& account, UInt256 domainID, beast::Journal j)
337{
338 auto const slePD = view.read(keylet::permissionedDomain(domainID));
339 if (!slePD)
340 return tecOBJECT_NOT_FOUND;
341
342 // Collect all matching credentials on a side, so we can remove expired ones
343 // We may finish the loop with this collection empty, it's fine.
345 for (auto const& h : slePD->getFieldArray(sfAcceptedCredentials))
346 {
347 auto const issuer = h.getAccountID(sfIssuer);
348 auto const type = h.getFieldVL(sfCredentialType);
349 auto const keyletCredential = keylet::credential(account, issuer, makeSlice(type));
350 if (view.exists(keyletCredential))
351 credentials.pushBack(keyletCredential.key);
352 }
353
354 auto const foundExpired = credentials::removeExpired(view, credentials, j);
355 if (!foundExpired.has_value())
356 return foundExpired.error();
357
358 for (auto const& h : credentials)
359 {
360 auto const sleCredential = view.read(keylet::credential(h));
361 if (!sleCredential)
362 continue; // expired, i.e. deleted in credentials::removeExpired
363
364 if (sleCredential->isFlag(lsfAccepted))
365 return tesSUCCESS;
366 }
367
368 return *foundExpired ? tecEXPIRED : tecNO_PERMISSION;
369}
370
371TER
373 STTx const& tx,
374 ReadView const& view,
375 AccountID const& src,
376 AccountID const& dst,
377 SLE::ConstRef sleDst,
379{
380 // If depositPreauth is enabled, then an account that requires
381 // authorization has at least two ways to get a payment in:
382 // 1. If src == dst, or
383 // 2. If src is deposit preauthorized by dst (either by account or by
384 // credentials).
385
386 if (sleDst && ((sleDst->getFlags() & lsfDepositAuth) != 0u))
387 {
388 if (src != dst)
389 {
390 if (!DepositPreauthEntryR(dst, src, view))
391 {
392 return !tx.isFieldPresent(sfCredentialIDs)
395 view, tx.getFieldV256(sfCredentialIDs), dst);
396 }
397 }
398 }
399
400 return tesSUCCESS;
401}
402
403TER
405{
406 if (tx.isFieldPresent(sfCredentialIDs))
407 {
408 auto const foundExpired =
409 credentials::removeExpired(view, tx.getFieldV256(sfCredentialIDs), j);
410 if (!foundExpired.has_value())
411 return foundExpired.error();
412 if (*foundExpired)
413 return tecEXPIRED;
414 }
415
416 return tesSUCCESS;
417}
418
419TER
421 STTx const& tx,
422 ApplyView& view,
423 AccountID const& src,
424 AccountID const& dst,
425 SLE::ConstRef sleDst,
427{
428 if (auto const err = cleanupExpiredCredentials(tx, view, j); !isTesSuccess(err))
429 return err;
430
431 return checkDepositPreauth(tx, view, src, dst, sleDst, j);
432}
433
434} // namespace xrpl
T any_of(T... args)
A generic endpoint for log messages.
Definition Journal.h:44
Stream fatal() const
Definition Journal.h:368
Stream trace() const
Severity stream access functions.
Definition Journal.h:338
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.
bool dirRemove(Keylet const &directory, std::uint64_t page, UInt256 const &key, bool keepRoot)
Remove an entry from a directory.
virtual void erase(SLE::Ref sle)=0
Remove a peeked SLE.
std::chrono::time_point< NetClock > time_point
Definition chrono.h:48
A view into a ledger.
Definition ReadView.h:41
virtual Rules const & rules() const =0
Returns the tx processing rules.
virtual bool exists(Keylet const &k) const =0
Determine if a state item exists.
virtual SLE::const_pointer read(Keylet const &k) const =0
Return the state item associated with a key.
virtual LedgerHeader const & header() const =0
Returns information about the ledger.
Rules controlling protocol behavior.
Definition Rules.h:40
bool enabled(UInt256 const &feature) const
Returns true if a feature is enabled.
Definition Rules.cpp:182
Identifies fields.
Definition SField.h:131
std::shared_ptr< STLedgerEntry const > const & ConstRef
std::shared_ptr< STLedgerEntry > const & Ref
bool isFieldPresent(SField const &field) const
Definition STObject.cpp:464
STVector256 const & getFieldV256(SField const &field) const
Definition STObject.cpp:671
std::size_t size() const
T emplace(T... args)
T insert(T... args)
T max(T... args)
std::set< std::pair< AccountID, Slice > > makeSorted(STArray const &credentials)
NotTEC checkFields(STTx const &tx, Rules const &rules, beast::Journal j)
static std::expected< bool, TER > removeExpired(ApplyView &view, STVector256 const &arr, beast::Journal const j)
TER deleteSLE(ApplyView &view, SLE::Ref sleCredential, beast::Journal j)
TER valid(STTx const &tx, ReadView const &view, AccountID const &src, beast::Journal j)
NotTEC checkArray(STArray const &credentials, unsigned maxSize, beast::Journal j)
TER authorizedDepositPreauth(ReadView const &view, STVector256 const &ctx, AccountID const &dst)
TER validDomain(ReadView const &view, UInt256 domainID, AccountID const &subject)
bool checkExpired(SLE const &sleCredential, NetClock::time_point const &closed)
Keylet ownerDir(AccountID const &id) noexcept
The root page of an account's directory.
Definition Indexes.cpp:415
Keylet permissionedDomain(AccountID const &account, SeqProxy const &seq) noexcept
Definition Indexes.cpp:583
Keylet account(AccountID const &id) noexcept
AccountID root.
Definition Indexes.cpp:233
Keylet credential(AccountID const &subject, AccountID const &issuer, Slice const &credType) noexcept
Definition Indexes.cpp:559
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
constexpr std::size_t kMaxCredentialTypeLength
The maximum length of a CredentialType inside a Credential.
Definition Protocol.h:276
@ tefBAD_LEDGER
Definition TER.h:164
@ tefINTERNAL
Definition TER.h:167
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
BaseUInt< 256 > UInt256
Definition base_uint.h:581
TERSubset< CanCvtToNotTEC > NotTEC
Definition TER.h:617
constexpr std::size_t kMaxCredentialsArraySize
The maximum number of credentials can be passed in array.
Definition Protocol.h:281
void decreaseOwnerCountForObject(ApplyView &view, SLE::Ref accountSle, SLE::Ref objectSle, std::uint32_t count, beast::Journal j)
Decrease owner-count fields for an existing ledger object.
TER verifyValidDomain(ApplyView &view, AccountID const &account, UInt256 domainID, beast::Journal j)
DepositPreauthEntry< ReadView > DepositPreauthEntryR
TER cleanupExpiredCredentials(STTx const &tx, ApplyView &view, beast::Journal j)
Remove expired credentials referenced by the transaction.
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
@ temARRAY_TOO_LARGE
Definition TER.h:129
@ temMALFORMED
Definition TER.h:75
@ temARRAY_EMPTY
Definition TER.h:128
@ temINVALID_ACCOUNT_ID
Definition TER.h:107
bool isTesSuccess(TER x) noexcept
Definition TER.h:686
TERSubset< CanCvtToTER > TER
Definition TER.h:657
@ tecNO_ENTRY
Definition TER.h:317
@ tecOBJECT_NOT_FOUND
Definition TER.h:337
@ tecNO_AUTH
Definition TER.h:311
@ tecINTERNAL
Definition TER.h:321
@ tecBAD_CREDENTIALS
Definition TER.h:370
@ tecEXPIRED
Definition TER.h:325
@ tecNO_PERMISSION
Definition TER.h:316
TER verifyDepositPreauth(STTx const &tx, ApplyView &view, AccountID const &src, AccountID const &dst, SLE::ConstRef sleDst, beast::Journal j)
@ tesSUCCESS
Definition TER.h:253
TER checkDepositPreauth(STTx const &tx, ReadView const &view, AccountID const &src, AccountID const &dst, std::shared_ptr< SLE const > const &sleDst, beast::Journal j)
Check whether src is authorized to deposit to dst.
Sha512HalfHasher::result_type sha512Half(Args const &... args)
Returns the SHA512-Half of a series of objects.
Definition digest.h:215
T push_back(T... args)
T reserve(T... args)
NetClock::time_point parentCloseTime
T time_since_epoch(T... args)
T unexpected(T... args)