From 7cd503859e67e45dd722fb72c94121000c1d90f1 Mon Sep 17 00:00:00 2001 From: Jingchen Date: Thu, 23 Apr 2026 14:59:23 +0100 Subject: [PATCH 01/34] refactor: Remove seq from TMGetObjectByHash (#6976) --- include/xrpl/proto/xrpl.proto | 4 +++- src/test/overlay/compression_test.cpp | 1 - src/xrpld/app/ledger/detail/LedgerMaster.cpp | 3 --- src/xrpld/overlay/detail/PeerImp.cpp | 5 ----- 4 files changed, 3 insertions(+), 10 deletions(-) diff --git a/include/xrpl/proto/xrpl.proto b/include/xrpl/proto/xrpl.proto index cd82ed24e6d..d49920201ed 100644 --- a/include/xrpl/proto/xrpl.proto +++ b/include/xrpl/proto/xrpl.proto @@ -234,9 +234,11 @@ message TMGetObjectByHash { otTRANSACTIONS = 7; } + // Previously used - don't reuse. + reserved 3; + required ObjectType type = 1; required bool query = 2; // is this a query or a reply? - optional uint32 seq = 3; // used to match replies to queries optional bytes ledgerHash = 4; // the hash of the ledger these queries are for optional bool fat = 5; // return related nodes repeated TMIndexedObject objects = 6; // the specific objects requested diff --git a/src/test/overlay/compression_test.cpp b/src/test/overlay/compression_test.cpp index bb4b95220ab..02a37864769 100644 --- a/src/test/overlay/compression_test.cpp +++ b/src/test/overlay/compression_test.cpp @@ -275,7 +275,6 @@ class compression_test : public beast::unit_test::suite getObject->set_type( protocol::TMGetObjectByHash_ObjectType::TMGetObjectByHash_ObjectType_otTRANSACTION); getObject->set_query(true); - getObject->set_seq(123456789); uint256 hash(xrpl::sha512Half(123456789)); getObject->set_ledgerhash(hash.data(), hash.size()); getObject->set_fat(true); diff --git a/src/xrpld/app/ledger/detail/LedgerMaster.cpp b/src/xrpld/app/ledger/detail/LedgerMaster.cpp index 880e8e9e383..c53249fa070 100644 --- a/src/xrpld/app/ledger/detail/LedgerMaster.cpp +++ b/src/xrpld/app/ledger/detail/LedgerMaster.cpp @@ -2113,9 +2113,6 @@ LedgerMaster::makeFetchPack( protocol::TMGetObjectByHash reply; reply.set_query(false); - if (request->has_seq()) - reply.set_seq(request->seq()); - reply.set_ledgerhash(request->ledgerhash()); reply.set_type(protocol::TMGetObjectByHash::otFETCH_PACK); diff --git a/src/xrpld/overlay/detail/PeerImp.cpp b/src/xrpld/overlay/detail/PeerImp.cpp index c0f21e3a5d9..5bfc33021dd 100644 --- a/src/xrpld/overlay/detail/PeerImp.cpp +++ b/src/xrpld/overlay/detail/PeerImp.cpp @@ -2595,9 +2595,6 @@ PeerImp::onMessage(std::shared_ptr const& m) reply.set_query(false); - if (packet.has_seq()) - reply.set_seq(packet.seq()); - reply.set_type(packet.type()); if (packet.has_ledgerhash()) @@ -2635,8 +2632,6 @@ PeerImp::onMessage(std::shared_ptr const& m) if (obj.has_ledgerseq()) newObj.set_ledgerseq(obj.ledgerseq()); - // VFALCO NOTE "seq" in the message is obsolete - // Check if by adding this object, reply has reached its // limit if (reply.objects_size() >= Tuning::hardMaxReplyNodes) From 19da25812bf067d2e382cecda378999714633460 Mon Sep 17 00:00:00 2001 From: Alex Kremer Date: Thu, 23 Apr 2026 17:21:01 +0100 Subject: [PATCH 02/34] fix: Remaining clang-tidy unchecked optionals (#6979) --- .clang-tidy | 2 +- .../scripts/levelization/results/ordering.txt | 1 + include/xrpl/protocol/PublicKey.h | 5 +-- include/xrpl/tx/ApplyContext.h | 8 +++-- include/xrpl/tx/paths/OfferStream.h | 3 +- include/xrpl/tx/paths/detail/StrandFlow.h | 3 ++ src/libxrpl/net/HTTPClient.cpp | 8 ++++- src/libxrpl/server/Manifest.cpp | 16 ++++++++-- src/libxrpl/shamap/SHAMapInnerNode.cpp | 13 +++++--- src/libxrpl/tx/ApplyContext.cpp | 9 +++--- src/libxrpl/tx/invariants/AMMInvariant.cpp | 6 ++++ src/libxrpl/tx/paths/BookStep.cpp | 10 +++++- src/libxrpl/tx/paths/DirectStep.cpp | 7 +++++ src/libxrpl/tx/paths/Flow.cpp | 2 +- src/libxrpl/tx/paths/MPTEndpointStep.cpp | 7 +++++ src/libxrpl/tx/paths/OfferStream.cpp | 3 ++ src/libxrpl/tx/transactors/dex/AMMBid.cpp | 2 ++ src/libxrpl/tx/transactors/dex/AMMVote.cpp | 3 ++ .../tx/transactors/payment/DepositPreauth.cpp | 1 + src/test/app/AMMMPT_test.cpp | 12 +++++++ src/test/app/AccountTxPaging_test.cpp | 2 -- src/test/app/GRPCServerTLS_test.cpp | 20 +++++++++--- src/test/core/Config_test.cpp | 1 + src/test/jtx/TrustedPublisherServer.h | 13 ++++++-- src/test/jtx/impl/TestHelpers.cpp | 18 +++++++++-- src/test/jtx/mpt.h | 2 +- src/test/protocol/Hooks_test.cpp | 3 +- src/xrpld/app/ledger/LedgerHistory.cpp | 3 +- src/xrpld/app/main/Application.cpp | 15 ++++++--- src/xrpld/app/misc/TxQ.h | 6 ++-- src/xrpld/app/misc/detail/TxQ.cpp | 11 ++++++- src/xrpld/app/misc/detail/ValidatorList.cpp | 12 ++++++- src/xrpld/app/misc/detail/ValidatorSite.cpp | 6 ++-- src/xrpld/consensus/Consensus.h | 25 +++++++++++++-- src/xrpld/consensus/LedgerTrie.h | 6 +++- src/xrpld/overlay/detail/OverlayImpl.cpp | 3 +- src/xrpld/overlay/detail/PeerImp.cpp | 2 ++ src/xrpld/perflog/detail/PerfLogImp.cpp | 1 - src/xrpld/rpc/detail/PathRequest.cpp | 31 +++++++++++++------ src/xrpld/rpc/detail/RPCLedgerHelpers.cpp | 2 ++ 40 files changed, 240 insertions(+), 63 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index 3a21eba6c00..ce12e552c44 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -66,7 +66,7 @@ Checks: "-*, bugprone-terminating-continue, bugprone-throw-keyword-missing, bugprone-too-small-loop-variable, - # bugprone-unchecked-optional-access, # see https://github.com/XRPLF/rippled/pull/6502 + bugprone-unchecked-optional-access, bugprone-undefined-memory-manipulation, bugprone-undelegated-constructor, bugprone-unhandled-exception-at-new, diff --git a/.github/scripts/levelization/results/ordering.txt b/.github/scripts/levelization/results/ordering.txt index 02a14a00772..d2a18945850 100644 --- a/.github/scripts/levelization/results/ordering.txt +++ b/.github/scripts/levelization/results/ordering.txt @@ -93,6 +93,7 @@ test.core > xrpl.basics test.core > xrpl.core test.core > xrpld.core test.core > xrpl.json +test.core > xrpl.protocol test.core > xrpl.rdb test.core > xrpl.server test.csf > xrpl.basics diff --git a/include/xrpl/protocol/PublicKey.h b/include/xrpl/protocol/PublicKey.h index 9003175f3d6..8325d2b1d2a 100644 --- a/include/xrpl/protocol/PublicKey.h +++ b/include/xrpl/protocol/PublicKey.h @@ -267,9 +267,10 @@ getOrThrow(Json::Value const& v, xrpl::SField const& field) { using namespace xrpl; std::string const b58 = getOrThrow(v, field); - if (auto pubKeyBlob = strUnHex(b58); publicKeyType(makeSlice(*pubKeyBlob))) + if (auto pubKeyBlob = strUnHex(b58); pubKeyBlob && publicKeyType(makeSlice(*pubKeyBlob))) { - return PublicKey{makeSlice(*pubKeyBlob)}; + return PublicKey{makeSlice( + *pubKeyBlob)}; // NOLINT(bugprone-unchecked-optional-access) checked in condition above } for (auto const tokenType : {TokenType::NodePublic, TokenType::AccountPublic}) { diff --git a/include/xrpl/tx/ApplyContext.h b/include/xrpl/tx/ApplyContext.h index 6341c0bcc5b..18179699783 100644 --- a/include/xrpl/tx/ApplyContext.h +++ b/include/xrpl/tx/ApplyContext.h @@ -46,20 +46,20 @@ class ApplyContext ApplyView& view() { - return *view_; + return *view_; // NOLINT(bugprone-unchecked-optional-access) view_ emplaced in constructor } ApplyView const& view() const { - return *view_; + return *view_; // NOLINT(bugprone-unchecked-optional-access) view_ emplaced in constructor } // VFALCO Unfortunately this is necessary RawView& rawView() { - return *view_; + return *view_; // NOLINT(bugprone-unchecked-optional-access) view_ emplaced in constructor } ApplyFlags const& @@ -72,6 +72,7 @@ class ApplyContext void deliver(STAmount const& amount) { + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) view_ emplaced in constructor view_->deliver(amount); } @@ -98,6 +99,7 @@ class ApplyContext void destroyXRP(XRPAmount const& fee) { + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) view_ emplaced in constructor view_->rawDestroyXRP(fee); } diff --git a/include/xrpl/tx/paths/OfferStream.h b/include/xrpl/tx/paths/OfferStream.h index e40387e3d21..84dbac9a609 100644 --- a/include/xrpl/tx/paths/OfferStream.h +++ b/include/xrpl/tx/paths/OfferStream.h @@ -103,7 +103,8 @@ class TOfferStreamBase TOut ownerFunds() const { - return *ownerFunds_; + return *ownerFunds_; // NOLINT(bugprone-unchecked-optional-access) always set after step() + // is called } }; diff --git a/include/xrpl/tx/paths/detail/StrandFlow.h b/include/xrpl/tx/paths/detail/StrandFlow.h index 52b7d944847..306a0b33e72 100644 --- a/include/xrpl/tx/paths/detail/StrandFlow.h +++ b/include/xrpl/tx/paths/detail/StrandFlow.h @@ -234,8 +234,11 @@ flow( } } + // NOLINTBEGIN(bugprone-unchecked-optional-access) cachedIn/Out set after strand is stepped + // above auto const strandIn = *strand.front()->cachedIn(); auto const strandOut = *strand.back()->cachedOut(); + // NOLINTEND(bugprone-unchecked-optional-access) #ifndef NDEBUG { diff --git a/src/libxrpl/net/HTTPClient.cpp b/src/libxrpl/net/HTTPClient.cpp index b39a6053136..028da37fa7c 100644 --- a/src/libxrpl/net/HTTPClient.cpp +++ b/src/libxrpl/net/HTTPClient.cpp @@ -65,7 +65,9 @@ class HTTPClientImp : public std::enable_shared_from_this, public unsigned short const port, std::size_t maxResponseSize, beast::Journal& j) - : mSocket(io_context, httpClientSSLContext->context()) + : mSocket( + io_context, + httpClientSSLContext->context()) // NOLINT(bugprone-unchecked-optional-access) , mResolver(io_context) , mHeader(maxClientHeaderBytes) , mPort(port) @@ -242,6 +244,8 @@ class HTTPClientImp : public std::enable_shared_from_this, public { mShutdown = ecResult ? ecResult + // httpClientSSLContext always initialized before use + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) : httpClientSSLContext->preConnectVerify(mSocket.SSLSocket(), mDeqSites[0]); } @@ -278,6 +282,8 @@ class HTTPClientImp : public std::enable_shared_from_this, public { JLOG(j_.trace()) << "Connected."; + // httpClientSSLContext always initialized before use + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) mShutdown = httpClientSSLContext->postConnectVerify(mSocket.SSLSocket(), mDeqSites[0]); if (mShutdown) diff --git a/src/libxrpl/server/Manifest.cpp b/src/libxrpl/server/Manifest.cpp index d2d7bd2e38b..0108b787827 100644 --- a/src/libxrpl/server/Manifest.cpp +++ b/src/libxrpl/server/Manifest.cpp @@ -494,7 +494,11 @@ ManifestCache::applyManifest(Manifest m) logMftAct(stream, "AcceptedNew", m.masterKey, m.sequence); if (!revoked) - signingToMasterKeys_.emplace(*m.signingKey, m.masterKey); + { + signingToMasterKeys_.emplace( + *m.signingKey, m.masterKey); // NOLINT(bugprone-unchecked-optional-access) + // non-revoked manifest always has signingKey + } auto masterKey = m.masterKey; map_.emplace(std::move(masterKey), std::move(m)); @@ -510,10 +514,16 @@ ManifestCache::applyManifest(Manifest m) if (auto stream = j_.info()) logMftAct(stream, "AcceptedUpdate", m.masterKey, m.sequence, iter->second.sequence); - signingToMasterKeys_.erase(*iter->second.signingKey); + signingToMasterKeys_.erase( + *iter->second.signingKey); // NOLINT(bugprone-unchecked-optional-access) prewriteCheck + // ensures old manifest is not revoked if (!revoked) - signingToMasterKeys_.emplace(*m.signingKey, m.masterKey); + { + signingToMasterKeys_.emplace( + *m.signingKey, m.masterKey); // NOLINT(bugprone-unchecked-optional-access) non-revoked + // manifest always has signingKey + } iter->second = std::move(m); diff --git a/src/libxrpl/shamap/SHAMapInnerNode.cpp b/src/libxrpl/shamap/SHAMapInnerNode.cpp index e501561ee49..d3324e91d05 100644 --- a/src/libxrpl/shamap/SHAMapInnerNode.cpp +++ b/src/libxrpl/shamap/SHAMapInnerNode.cpp @@ -291,7 +291,8 @@ SHAMapInnerNode::setChild(int m, intr_ptr::SharedPtr child) if (child) { - auto const childIndex = *getChildIndex(m); + auto const childIndex = + *getChildIndex(m); // NOLINT(bugprone-unchecked-optional-access) isBranch_ set above auto [_, hashes, children] = hashesAndChildren_.getHashesAndChildren(); hashes[childIndex].zero(); children[childIndex] = std::move(child); @@ -315,6 +316,7 @@ SHAMapInnerNode::shareChild(int m, intr_ptr::SharedPtr const& ch XRPL_ASSERT(child.get() != this, "xrpl::SHAMapInnerNode::shareChild : valid child input"); XRPL_ASSERT(!isEmptyBranch(m), "xrpl::SHAMapInnerNode::shareChild : non-empty branch input"); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) assert above hashesAndChildren_.getChildren()[*getChildIndex(m)] = child; } @@ -327,7 +329,8 @@ SHAMapInnerNode::getChildPointer(int branch) XRPL_ASSERT( !isEmptyBranch(branch), "xrpl::SHAMapInnerNode::getChildPointer : non-empty branch input"); - auto const index = *getChildIndex(branch); + auto const index = + *getChildIndex(branch); // NOLINT(bugprone-unchecked-optional-access) assert above packed_spinlock sl(lock_, index); std::lock_guard const lock(sl); @@ -342,7 +345,8 @@ SHAMapInnerNode::getChild(int branch) "xrpl::SHAMapInnerNode::getChild : valid branch input"); XRPL_ASSERT(!isEmptyBranch(branch), "xrpl::SHAMapInnerNode::getChild : non-empty branch input"); - auto const index = *getChildIndex(branch); + auto const index = + *getChildIndex(branch); // NOLINT(bugprone-unchecked-optional-access) assert above packed_spinlock sl(lock_, index); std::lock_guard const lock(sl); @@ -370,7 +374,8 @@ SHAMapInnerNode::canonicalizeChild(int branch, intr_ptr::SharedPtrgetHash() == hashes[childIndex], diff --git a/src/libxrpl/tx/ApplyContext.cpp b/src/libxrpl/tx/ApplyContext.cpp index fa175746165..43facecb240 100644 --- a/src/libxrpl/tx/ApplyContext.cpp +++ b/src/libxrpl/tx/ApplyContext.cpp @@ -58,13 +58,14 @@ ApplyContext::discard() std::optional ApplyContext::apply(TER ter) { + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) view_ emplaced in constructor return view_->apply(base_, tx, ter, parentBatchId_, (flags_ & tapDRY_RUN) != 0u, journal); } std::size_t ApplyContext::size() { - return view_->size(); + return view_->size(); // NOLINT(bugprone-unchecked-optional-access) } void @@ -75,7 +76,7 @@ ApplyContext::visit( std::shared_ptr const&, std::shared_ptr const&)> const& func) { - view_->visit(base_, func); + view_->visit(base_, func); // NOLINT(bugprone-unchecked-optional-access) } TER @@ -116,8 +117,8 @@ ApplyContext::checkInvariantsHelper( // short-circuits). While the logic is still correct, the log // message won't be. Every failed invariant should write to the log, // not just the first one. - std::array const finalizers{ - {std::get(checkers).finalize(tx, result, fee, *view_, journal)...}}; + std::array const finalizers{{std::get(checkers).finalize( + tx, result, fee, *view_, journal)...}}; // NOLINT(bugprone-unchecked-optional-access) // call each check's finalizer to see that it passes if (!std::all_of(finalizers.cbegin(), finalizers.cend(), [](auto const& b) { return b; })) diff --git a/src/libxrpl/tx/invariants/AMMInvariant.cpp b/src/libxrpl/tx/invariants/AMMInvariant.cpp index 3cc888dea25..30be382c91e 100644 --- a/src/libxrpl/tx/invariants/AMMInvariant.cpp +++ b/src/libxrpl/tx/invariants/AMMInvariant.cpp @@ -152,6 +152,8 @@ ValidAMM::finalizeCreate( // Create invariant: // sqrt(amount * amount2) == LPTokens // all balances are greater than zero + // NOLINTBEGIN(bugprone-unchecked-optional-access) lptAMMBalanceAfter_ set with ammAccount_ + // in visitEntry if (!validBalances(amount, amount2, *lptAMMBalanceAfter_, ZeroAllowed::No) || ammLPTokens(amount, amount2, lptAMMBalanceAfter_->get()) != *lptAMMBalanceAfter_) { @@ -160,6 +162,7 @@ ValidAMM::finalizeCreate( if (enforce) return false; } + // NOLINTEND(bugprone-unchecked-optional-access) } return true; @@ -204,6 +207,8 @@ ValidAMM::generalInvariant( ZeroAllowed zeroAllowed, beast::Journal const& j) const { + // NOLINTBEGIN(bugprone-unchecked-optional-access) ammAccount_ and lptAMMBalanceAfter_ set + // together in visitEntry; callers only invoke this inside else-of-if(!ammAccount_) auto const [amount, amount2] = ammPoolHolds( view, *ammAccount_, tx[sfAsset], tx[sfAsset2], fhIGNORE_FREEZE, ahIGNORE_AUTH, j); // Deposit and Withdrawal invariant: @@ -230,6 +235,7 @@ ValidAMM::generalInvariant( : ((*lptAMMBalanceAfter_ - poolProductMean) / poolProductMean)); return false; } + // NOLINTEND(bugprone-unchecked-optional-access) return true; } diff --git a/src/libxrpl/tx/paths/BookStep.cpp b/src/libxrpl/tx/paths/BookStep.cpp index f05460df61d..ceab3793011 100644 --- a/src/libxrpl/tx/paths/BookStep.cpp +++ b/src/libxrpl/tx/paths/BookStep.cpp @@ -610,7 +610,13 @@ BookStep::getQualityFunc(ReadView const& v, DebtDirection p // CLOB Quality const q = static_cast(this)->adjustQualityWithFees( - v, *(res->quality()), prevStepDir, WaiveTransferFee::No, OfferType::CLOB, v.rules()); + v, + *(res->quality()), // NOLINT(bugprone-unchecked-optional-access) CLOB QualityFunction + // always has quality set + prevStepDir, + WaiveTransferFee::No, + OfferType::CLOB, + v.rules()); return {QualityFunction{q, QualityFunction::CLOBLikeTag{}}, dir}; } @@ -1285,6 +1291,7 @@ BookStep::validFwd( return {false, EitherAmount(TOut(beast::zero))}; } + // NOLINTBEGIN(bugprone-unchecked-optional-access) fwdImp sets cache_ on success if (!(checkNear(savCache.in, cache_->in) && checkNear(savCache.out, cache_->out))) { JLOG(j_.warn()) << "Strand re-execute check failed." @@ -1295,6 +1302,7 @@ BookStep::validFwd( return {false, EitherAmount(cache_->out)}; } return {true, EitherAmount(cache_->out)}; + // NOLINTEND(bugprone-unchecked-optional-access) } template diff --git a/src/libxrpl/tx/paths/DirectStep.cpp b/src/libxrpl/tx/paths/DirectStep.cpp index c4b2c519340..1692f507810 100644 --- a/src/libxrpl/tx/paths/DirectStep.cpp +++ b/src/libxrpl/tx/paths/DirectStep.cpp @@ -580,6 +580,8 @@ DirectStepI::setCacheLimiting( IOUAmount const& fwdOut, DebtDirection srcDebtDir) { + // NOLINTBEGIN(bugprone-unchecked-optional-access) cache_ always set before setCacheLimiting is + // called if (cache_->in < fwdIn) { IOUAmount const smallDiff(1, -9); @@ -609,6 +611,7 @@ DirectStepI::setCacheLimiting( if (fwdOut < cache_->out) cache_->out = fwdOut; cache_->srcDebtDir = srcDebtDir; + // NOLINTEND(bugprone-unchecked-optional-access) }; template @@ -620,6 +623,7 @@ DirectStepI::fwdImp( IOUAmount const& in) { XRPL_ASSERT(cache_, "xrpl::DirectStepI::fwdImp : cache is set"); + // NOLINTBEGIN(bugprone-unchecked-optional-access) assert above auto const [maxSrcToDst, srcDebtDir] = static_cast(this)->maxFlow(sb, cache_->srcToDst); @@ -676,6 +680,7 @@ DirectStepI::fwdImp( << " srcToDst: " << to_string(srcToDst) << " out: " << to_string(out); } return {cache_->in, cache_->out}; + // NOLINTEND(bugprone-unchecked-optional-access) } template @@ -706,6 +711,7 @@ DirectStepI::validFwd(PaymentSandbox& sb, ApplyView& afView, EitherAmo return {false, EitherAmount(IOUAmount(beast::zero))}; } + // NOLINTBEGIN(bugprone-unchecked-optional-access) fwdImp sets cache_ on success if (maxSrcToDst < cache_->srcToDst) { JLOG(j_.warn()) << "DirectStepI: Strand re-execute check failed." @@ -725,6 +731,7 @@ DirectStepI::validFwd(PaymentSandbox& sb, ApplyView& afView, EitherAmo return {false, EitherAmount(cache_->out)}; } return {true, EitherAmount(cache_->out)}; + // NOLINTEND(bugprone-unchecked-optional-access) } // Returns srcQOut, dstQIn diff --git a/src/libxrpl/tx/paths/Flow.cpp b/src/libxrpl/tx/paths/Flow.cpp index 413c160c7fb..32ca39ec229 100644 --- a/src/libxrpl/tx/paths/Flow.cpp +++ b/src/libxrpl/tx/paths/Flow.cpp @@ -27,7 +27,7 @@ finishFlow(PaymentSandbox& sb, Asset const& srcAsset, Asset const& dstAsset, Flo path::RippleCalc::Output result; if (isTesSuccess(f.ter)) { - f.sandbox->apply(sb); + f.sandbox->apply(sb); // NOLINT(bugprone-unchecked-optional-access) sandbox set on success } else { diff --git a/src/libxrpl/tx/paths/MPTEndpointStep.cpp b/src/libxrpl/tx/paths/MPTEndpointStep.cpp index 7b063a39d39..aa989b27e02 100644 --- a/src/libxrpl/tx/paths/MPTEndpointStep.cpp +++ b/src/libxrpl/tx/paths/MPTEndpointStep.cpp @@ -556,6 +556,8 @@ MPTEndpointStep::setCacheLimiting( MPTAmount const& fwdOut, DebtDirection srcDebtDir) { + // NOLINTBEGIN(bugprone-unchecked-optional-access) cache_ always set before setCacheLimiting is + // called if (cache_->in < fwdIn) { MPTAmount const smallDiff(1); @@ -585,6 +587,7 @@ MPTEndpointStep::setCacheLimiting( if (fwdOut < cache_->out) cache_->out = fwdOut; cache_->srcDebtDir = srcDebtDir; + // NOLINTEND(bugprone-unchecked-optional-access) }; template @@ -596,6 +599,7 @@ MPTEndpointStep::fwdImp( MPTAmount const& in) { XRPL_ASSERT(cache_, "MPTEndpointStep::fwdImp : valid cache"); + // NOLINTBEGIN(bugprone-unchecked-optional-access) assert above auto const [maxSrcToDst, srcDebtDir] = static_cast(this)->maxPaymentFlow(sb); @@ -669,6 +673,7 @@ MPTEndpointStep::fwdImp( << " srcToDst: " << to_string(srcToDst) << " out: " << to_string(out); } return {cache_->in, cache_->out}; + // NOLINTEND(bugprone-unchecked-optional-access) } template @@ -698,6 +703,7 @@ MPTEndpointStep::validFwd(PaymentSandbox& sb, ApplyView& afView, Eithe return {false, EitherAmount(MPTAmount(beast::zero))}; } + // NOLINTBEGIN(bugprone-unchecked-optional-access) fwdImp sets cache_ on success if (maxSrcToDst < cache_->srcToDst) { JLOG(j_.warn()) << "MPTEndpointStep: Strand re-execute check failed." @@ -717,6 +723,7 @@ MPTEndpointStep::validFwd(PaymentSandbox& sb, ApplyView& afView, Eithe return {false, EitherAmount(cache_->out)}; } return {true, EitherAmount(cache_->out)}; + // NOLINTEND(bugprone-unchecked-optional-access) } // Returns srcQOut, dstQIn diff --git a/src/libxrpl/tx/paths/OfferStream.cpp b/src/libxrpl/tx/paths/OfferStream.cpp index c7e81ba2039..0d003c63f7b 100644 --- a/src/libxrpl/tx/paths/OfferStream.cpp +++ b/src/libxrpl/tx/paths/OfferStream.cpp @@ -150,6 +150,9 @@ TOfferStreamBase::shouldRmSmallIncreasedQOffer() const return false; } + if (!ownerFunds_) + return false; + TAmounts const ofrAmts{ toAmount(offer_.amount().in), toAmount(offer_.amount().out)}; diff --git a/src/libxrpl/tx/transactors/dex/AMMBid.cpp b/src/libxrpl/tx/transactors/dex/AMMBid.cpp index e878585d4cd..69fd6a651bc 100644 --- a/src/libxrpl/tx/transactors/dex/AMMBid.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMBid.cpp @@ -321,6 +321,7 @@ applyBid(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::Jour // Price the slot was purchased at. STAmount const pricePurchased = auctionSlot[sfPrice]; XRPL_ASSERT(timeSlot, "xrpl::applyBid : timeSlot is set"); + // NOLINTBEGIN(bugprone-unchecked-optional-access) auto const fractionUsed = (Number(*timeSlot) + 1) / AUCTION_SLOT_TIME_INTERVALS; auto const fractionRemaining = Number(1) - fractionUsed; auto const computedPrice = [&]() -> Number { @@ -331,6 +332,7 @@ applyBid(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::Jour // Other intervals slot price return pricePurchased * p1_05 * (1 - power(fractionUsed, 60)) + minSlotPrice; }(); + // NOLINTEND(bugprone-unchecked-optional-access) auto const payPrice = getPayPrice(computedPrice); diff --git a/src/libxrpl/tx/transactors/dex/AMMVote.cpp b/src/libxrpl/tx/transactors/dex/AMMVote.cpp index 1287c8c4283..e411a3a53ab 100644 --- a/src/libxrpl/tx/transactors/dex/AMMVote.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMVote.cpp @@ -176,6 +176,8 @@ applyVote(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::Jou // Add the entry if the account has more tokens than // the least token holder or same tokens and higher fee. } + // NOLINTBEGIN(bugprone-unchecked-optional-access) slots full means loop ran, minTokens is + // set else if (lpTokensNew > *minTokens || (lpTokensNew == *minTokens && feeNew > minFee)) { auto const entry = updatedVoteSlots.begin() + minPos; @@ -184,6 +186,7 @@ applyVote(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::Jou den -= *minTokens; update(minPos); } + // NOLINTEND(bugprone-unchecked-optional-access) // All slots are full and the account does not hold more LPTokens. // Update anyway to refresh the slots. else diff --git a/src/libxrpl/tx/transactors/payment/DepositPreauth.cpp b/src/libxrpl/tx/transactors/payment/DepositPreauth.cpp index f8dca6bb588..f770b443f7d 100644 --- a/src/libxrpl/tx/transactors/payment/DepositPreauth.cpp +++ b/src/libxrpl/tx/transactors/payment/DepositPreauth.cpp @@ -63,6 +63,7 @@ DepositPreauth::preflight(PreflightContext const& ctx) if (authPresent != 0) { // Make sure that the passed account is valid. + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) authPresent != 0 guarantees one is set AccountID const& target(optAuth ? *optAuth : *optUnauth); if (!target) { diff --git a/src/test/app/AMMMPT_test.cpp b/src/test/app/AMMMPT_test.cpp index 98846458361..f453d6cf75f 100644 --- a/src/test/app/AMMMPT_test.cpp +++ b/src/test/app/AMMMPT_test.cpp @@ -6354,8 +6354,11 @@ struct AMMMPT_test : public jtx::AMMTest // CLOB and AMM, AMM is not selected if (i == 2) { + // NOLINTBEGIN(bugprone-unchecked-optional-access) i==2 implies amm is + // emplaced (i>0) BEAST_EXPECT(amm->expectBalances( USD(1'000'000'000), ETH(1'000'000'000), amm->tokens())); + // NOLINTEND(bugprone-unchecked-optional-access) } env.require(balance(bob, USD(2'100'000'000))); q[i] = Quality( @@ -6393,8 +6396,10 @@ struct AMMMPT_test : public jtx::AMMTest // AMM is not selected if (i > 0) { + // NOLINTBEGIN(bugprone-unchecked-optional-access) emplaced when i > 0 BEAST_EXPECT( amm->expectBalances(USD(1'000'000'000), ETH(1'000'000'000), amm->tokens())); + // NOLINTEND(bugprone-unchecked-optional-access) } if (i == 0 || i == 2) { @@ -6438,8 +6443,10 @@ struct AMMMPT_test : public jtx::AMMTest // AMM and CLOB are selected if (i > 0) { + // NOLINTBEGIN(bugprone-unchecked-optional-access) emplaced when i > 0 BEAST_EXPECT(!amm->expectBalances( USD(1'000'000'000), ETH(1'000'000'000), amm->tokens())); + // NOLINTEND(bugprone-unchecked-optional-access) } if (i == 2) @@ -6500,8 +6507,10 @@ struct AMMMPT_test : public jtx::AMMTest // AMM is selected in both cases if (i > 0) { + // NOLINTBEGIN(bugprone-unchecked-optional-access) emplaced when i > 0 BEAST_EXPECT(!amm->expectBalances( USD(1'000'000'000), ETH(1'000'000'000), amm->tokens())); + // NOLINTEND(bugprone-unchecked-optional-access) } // Partially crosses, AMM is selected, CLOB fails // limitQuality @@ -6584,6 +6593,8 @@ struct AMMMPT_test : public jtx::AMMTest if (i == 2) { + // NOLINTBEGIN(bugprone-unchecked-optional-access) i==2 implies amm is + // emplaced (i>0) if (rates.first == lowRate) { // Liquidity is consumed from AMM strand only @@ -6607,6 +6618,7 @@ struct AMMMPT_test : public jtx::AMMTest USD(281'976'305), }}})); } + // NOLINTEND(bugprone-unchecked-optional-access) } q[i] = Quality( Amounts{ diff --git a/src/test/app/AccountTxPaging_test.cpp b/src/test/app/AccountTxPaging_test.cpp index d5c299b7823..b5b419f9b10 100644 --- a/src/test/app/AccountTxPaging_test.cpp +++ b/src/test/app/AccountTxPaging_test.cpp @@ -10,8 +10,6 @@ #include #include -#include - namespace xrpl { class AccountTxPaging_test : public beast::unit_test::suite diff --git a/src/test/app/GRPCServerTLS_test.cpp b/src/test/app/GRPCServerTLS_test.cpp index a421f981f7b..a3411682a24 100644 --- a/src/test/app/GRPCServerTLS_test.cpp +++ b/src/test/app/GRPCServerTLS_test.cpp @@ -370,10 +370,12 @@ class GRPCServerTLS_test : public beast::unit_test::suite, public TemporaryTLSCe // Verify the server actually started by checking the port auto const grpcPort = env.app().config()[SECTION_PORT_GRPC].get("port"); BEAST_EXPECT(grpcPort.has_value()); + // NOLINTBEGIN(bugprone-unchecked-optional-access) grpcPort.has_value() checked above BEAST_EXPECT(*grpcPort > 0); // Test 1: Plaintext client should connect successfully std::string const serverAddress = "localhost:" + std::to_string(*grpcPort); + // NOLINTEND(bugprone-unchecked-optional-access) auto plaintextStub = org::xrpl::rpc::v1::XRPLedgerAPIService::NewStub( grpc::CreateChannel(serverAddress, grpc::InsecureChannelCredentials())); BEAST_EXPECT(makeTestGRPCCall(plaintextStub)); @@ -394,9 +396,11 @@ class GRPCServerTLS_test : public beast::unit_test::suite, public TemporaryTLSCe // Verify the server actually started by checking the port auto const grpcPort = env.app().config()[SECTION_PORT_GRPC].get("port"); BEAST_EXPECT(grpcPort.has_value()); + // NOLINTBEGIN(bugprone-unchecked-optional-access) grpcPort.has_value() checked above BEAST_EXPECT(*grpcPort > 0); std::string const serverAddress = "localhost:" + std::to_string(*grpcPort); + // NOLINTEND(bugprone-unchecked-optional-access) // Test 1: Plaintext client should FAIL against TLS server auto plaintextStub = org::xrpl::rpc::v1::XRPLedgerAPIService::NewStub( @@ -429,9 +433,11 @@ class GRPCServerTLS_test : public beast::unit_test::suite, public TemporaryTLSCe // Verify the server actually started by checking the port auto const grpcPort = env.app().config()[SECTION_PORT_GRPC].get("port"); BEAST_EXPECT(grpcPort.has_value()); + // NOLINTBEGIN(bugprone-unchecked-optional-access) grpcPort.has_value() checked above BEAST_EXPECT(*grpcPort > 0); auto const serverAddress = "localhost:" + std::to_string(*grpcPort); + // NOLINTEND(bugprone-unchecked-optional-access) // Test 1: TLS client WITHOUT client certificate should FAIL (mTLS requires client cert) grpc::SslCredentialsOptions sslOptsNoClient; @@ -651,9 +657,11 @@ class GRPCServerTLS_test : public beast::unit_test::suite, public TemporaryTLSCe // Verify the server actually started by checking the port auto const grpcPort = env.app().config()[SECTION_PORT_GRPC].get("port"); BEAST_EXPECT(grpcPort.has_value()); + // NOLINTBEGIN(bugprone-unchecked-optional-access) grpcPort.has_value() checked above BEAST_EXPECT(*grpcPort > 0); auto const serverAddress = "localhost:" + std::to_string(*grpcPort); + // NOLINTEND(bugprone-unchecked-optional-access) // Test: TLS client should be able to connect (no client cert required) grpc::SslCredentialsOptions sslOpts; @@ -686,7 +694,7 @@ class GRPCServerTLS_test : public beast::unit_test::suite, public TemporaryTLSCe // Server should fail to start - verify port is 0 auto const grpcPort = env.app().config()[SECTION_PORT_GRPC].get("port"); BEAST_EXPECT(grpcPort.has_value()); - BEAST_EXPECT(*grpcPort == 0); // Server should not have started + BEAST_EXPECT(*grpcPort == 0); // NOLINT(bugprone-unchecked-optional-access) } void @@ -707,7 +715,7 @@ class GRPCServerTLS_test : public beast::unit_test::suite, public TemporaryTLSCe // Server should fail to start - verify port is 0 auto const grpcPort = env.app().config()[SECTION_PORT_GRPC].get("port"); BEAST_EXPECT(grpcPort.has_value()); - BEAST_EXPECT(*grpcPort == 0); // Server should not have started + BEAST_EXPECT(*grpcPort == 0); // NOLINT(bugprone-unchecked-optional-access) } void @@ -729,7 +737,7 @@ class GRPCServerTLS_test : public beast::unit_test::suite, public TemporaryTLSCe // Server should fail to start - verify port is 0 auto const grpcPort = env.app().config()[SECTION_PORT_GRPC].get("port"); BEAST_EXPECT(grpcPort.has_value()); - BEAST_EXPECT(*grpcPort == 0); // Server should not have started + BEAST_EXPECT(*grpcPort == 0); // NOLINT(bugprone-unchecked-optional-access) } void @@ -751,7 +759,7 @@ class GRPCServerTLS_test : public beast::unit_test::suite, public TemporaryTLSCe // Server should fail to start - verify port is 0 auto const grpcPort = env.app().config()[SECTION_PORT_GRPC].get("port"); BEAST_EXPECT(grpcPort.has_value()); - BEAST_EXPECT(*grpcPort == 0); // Server should not have started + BEAST_EXPECT(*grpcPort == 0); // NOLINT(bugprone-unchecked-optional-access) } void @@ -778,7 +786,7 @@ class GRPCServerTLS_test : public beast::unit_test::suite, public TemporaryTLSCe // Server should fail to start due to empty CA file auto const grpcPort = env.app().config()[SECTION_PORT_GRPC].get("port"); BEAST_EXPECT(grpcPort.has_value()); - BEAST_EXPECT(*grpcPort == 0); // Server should not have started + BEAST_EXPECT(*grpcPort == 0); // NOLINT(bugprone-unchecked-optional-access) } void @@ -803,9 +811,11 @@ class GRPCServerTLS_test : public beast::unit_test::suite, public TemporaryTLSCe // Verify the server started successfully auto const grpcPort = env.app().config()[SECTION_PORT_GRPC].get("port"); BEAST_EXPECT(grpcPort.has_value()); + // NOLINTBEGIN(bugprone-unchecked-optional-access) grpcPort.has_value() checked above BEAST_EXPECT(*grpcPort > 0); auto const serverAddress = "localhost:" + std::to_string(*grpcPort); + // NOLINTEND(bugprone-unchecked-optional-access) // Test 1: TLS client WITHOUT client certificate should FAIL (mTLS requires client cert) grpc::SslCredentialsOptions sslOptsNoClient; diff --git a/src/test/core/Config_test.cpp b/src/test/core/Config_test.cpp index a3137b8e69c..569a31df602 100644 --- a/src/test/core/Config_test.cpp +++ b/src/test/core/Config_test.cpp @@ -7,6 +7,7 @@ #include #include #include +#include // IWYU pragma: keep #include #include diff --git a/src/test/jtx/TrustedPublisherServer.h b/src/test/jtx/TrustedPublisherServer.h index 097dae97bbf..50045044d79 100644 --- a/src/test/jtx/TrustedPublisherServer.h +++ b/src/test/jtx/TrustedPublisherServer.h @@ -106,8 +106,11 @@ class TrustedPublisherServer : public std::enable_shared_from_thisshutdown(ec); + ssl_stream->shutdown(ec); // NOLINT(bugprone-unchecked-optional-access) ssl_stream + // emplaced when ssl==true } }; diff --git a/src/test/jtx/impl/TestHelpers.cpp b/src/test/jtx/impl/TestHelpers.cpp index 2495e151f30..f585e7b28f4 100644 --- a/src/test/jtx/impl/TestHelpers.cpp +++ b/src/test/jtx/impl/TestHelpers.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -302,7 +303,8 @@ find_paths( Json::Value p; p["Paths"] = path[jss::paths_computed]; STParsedJSONObject po("generic", p); - paths = po.object->getFieldPathSet(sfPaths); + if (po.object) + paths = po.object->getFieldPathSet(sfPaths); } } } @@ -321,8 +323,20 @@ find_paths_by_element( std::optional const& srcIssuer, std::optional const& domain) { + // srcElement is optional but is expected to always be present + XRPL_ASSERT( + srcElement.has_value(), "xrpl::test::jtx::find_paths_by_element::srcElement : nullptr"); + return find_paths( - env, src, dst, saDstAmount, saSendMax, srcElement->getPathAsset(), srcIssuer, domain); + env, + src, + dst, + saDstAmount, + saSendMax, + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + srcElement->getPathAsset(), + srcIssuer, + domain); } /******************************************************************************/ diff --git a/src/test/jtx/mpt.h b/src/test/jtx/mpt.h index 20b8f03762a..eb08de5caa6 100644 --- a/src/test/jtx/mpt.h +++ b/src/test/jtx/mpt.h @@ -259,7 +259,7 @@ class MPTTester { if (!env_.test.BEAST_EXPECT(id_)) Throw("Uninitialized issuanceID"); - return *id_; + return *id_; // NOLINT(bugprone-unchecked-optional-access) } std::int64_t diff --git a/src/test/protocol/Hooks_test.cpp b/src/test/protocol/Hooks_test.cpp index c6254d16bb3..bd6e0a1859b 100644 --- a/src/test/protocol/Hooks_test.cpp +++ b/src/test/protocol/Hooks_test.cpp @@ -142,9 +142,10 @@ class Hooks_test : public beast::unit_test::suite } case STI_ACCOUNT: { - // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + // NOLINTBEGIN(bugprone-unchecked-optional-access) AccountID const id = *parseBase58("rwfSjJNK2YQuN64bSWn7T2eY9FJAyAPYJT"); + // NOLINTEND(bugprone-unchecked-optional-access) dummy.setAccountID(f, id); BEAST_EXPECT(dummy.getAccountID(f) == id); BEAST_EXPECT(dummy.isFieldPresent(f)); diff --git a/src/xrpld/app/ledger/LedgerHistory.cpp b/src/xrpld/app/ledger/LedgerHistory.cpp index 8fd2e075c6a..535acbf63e0 100644 --- a/src/xrpld/app/ledger/LedgerHistory.cpp +++ b/src/xrpld/app/ledger/LedgerHistory.cpp @@ -485,7 +485,8 @@ LedgerHistory::validatedLedger( hash, entry->builtConsensusHash, consensusHash, - entry->consensus.value()); + entry->consensus.value()); // NOLINT(bugprone-unchecked-optional-access) consensus + // always emplaced with built } else { diff --git a/src/xrpld/app/main/Application.cpp b/src/xrpld/app/main/Application.cpp index c83b45f2474..5867f77ba0c 100644 --- a/src/xrpld/app/main/Application.cpp +++ b/src/xrpld/app/main/Application.cpp @@ -816,27 +816,29 @@ class ApplicationImp : public Application, public BasicApp OpenLedger& getOpenLedger() override { - return *openLedger_; + return *openLedger_; // NOLINT(bugprone-unchecked-optional-access) emplaced during + // initialization before any caller } OpenLedger const& getOpenLedger() const override { - return *openLedger_; + return *openLedger_; // NOLINT(bugprone-unchecked-optional-access) emplaced during + // initialization before any caller } Overlay& getOverlay() override { XRPL_ASSERT(overlay_, "xrpl::ApplicationImp::overlay : non-null overlay"); - return *overlay_; + return *overlay_; // NOLINT(bugprone-unchecked-optional-access) assert above } TxQ& getTxQ() override { XRPL_ASSERT(txQ_, "xrpl::ApplicationImp::getTxQ : non-null transaction queue"); - return *txQ_; + return *txQ_; // NOLINT(bugprone-unchecked-optional-access) assert above } RelationalDatabase& @@ -845,7 +847,7 @@ class ApplicationImp : public Application, public BasicApp XRPL_ASSERT( relationalDatabase_, "xrpl::ApplicationImp::getRelationalDatabase : non-null relational database"); - return *relationalDatabase_; + return *relationalDatabase_; // NOLINT(bugprone-unchecked-optional-access) assert above } DatabaseCon& @@ -995,6 +997,7 @@ class ApplicationImp : public Application, public BasicApp { XRPL_ASSERT( relationalDatabase_, "xrpl::ApplicationImp::doSweep : non-null relational database"); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) assert above if (!config_->standalone() && !relationalDatabase_->transactionDbHasSpace(*config_)) { signalStop("Out of transaction DB space"); @@ -2081,6 +2084,8 @@ ApplicationImp::loadOldLedger( forceValidity(getHashRouter(), txID, Validity::SigGoodOnly); + // emplaced during initialization before any caller + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) openLedger_->modify([&txID, &s](OpenView& view, beast::Journal j) { view.rawTxInsert(txID, std::move(s), nullptr); return true; diff --git a/src/xrpld/app/misc/TxQ.h b/src/xrpld/app/misc/TxQ.h index 621f3b8c602..0f734f7897f 100644 --- a/src/xrpld/app/misc/TxQ.h +++ b/src/xrpld/app/misc/TxQ.h @@ -578,7 +578,8 @@ class TxQ TxConsequences const& consequences() const { - return pfResult->consequences; + return pfResult->consequences; // NOLINT(bugprone-unchecked-optional-access) invariant: + // pfResult is never empty } /// Return a TxDetails based on contained information. @@ -593,7 +594,8 @@ class TxQ seqProxy, txn, retriesRemaining, - pfResult->ter, + pfResult->ter, // NOLINT(bugprone-unchecked-optional-access) invariant: pfResult is + // never empty lastResult}; } }; diff --git a/src/xrpld/app/misc/detail/TxQ.cpp b/src/xrpld/app/misc/detail/TxQ.cpp index eb3b7a54bed..dde0988b4ad 100644 --- a/src/xrpld/app/misc/detail/TxQ.cpp +++ b/src/xrpld/app/misc/detail/TxQ.cpp @@ -277,7 +277,8 @@ TxQ::FeeMetrics::escalatedSeriesFeeLevel( auto const totalFeeLevel = mulDiv(multiplier, sumNlast.second - sumNcurrent.second, target * target); - return {totalFeeLevel.has_value(), *totalFeeLevel}; + return { + totalFeeLevel.has_value(), *totalFeeLevel}; // NOLINT(bugprone-unchecked-optional-access) } LedgerHash TxQ::MaybeTx::parentHashComp{}; @@ -306,6 +307,7 @@ TxQ::MaybeTx::apply(Application& app, OpenView& view, beast::Journal j) XRPL_ASSERT(pfResult, "xrpl::TxQ::MaybeTx::apply : preflight result is set"); NumberSO const stNumberSO{view.rules().enabled(fixUniversalNumber)}; + // NOLINTBEGIN(bugprone-unchecked-optional-access) assert above if (pfResult->rules != view.rules() || pfResult->flags != flags) { JLOG(j.debug()) << "Queued transaction " << txID @@ -316,6 +318,7 @@ TxQ::MaybeTx::apply(Application& app, OpenView& view, beast::Journal j) } auto pcresult = preclaim(*pfResult, app, view); + // NOLINTEND(bugprone-unchecked-optional-access) return doApply(pcresult, app, view); } @@ -833,6 +836,7 @@ TxQ::apply( << ". Account has other queued transactions."; return {telCAN_NOT_QUEUE_BLOCKS, false}; } + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) acctTxCount == 1 implies txIter is set if (acctTxCount == 1 && (txSeqProx != txIter->first->first)) { // The blocker is not replacing the lone queued transaction. @@ -872,8 +876,10 @@ TxQ::apply( // // We only need to check if txIter->first is a blocker because we // require that a blocker be alone in the account's queue. + // NOLINTBEGIN(bugprone-unchecked-optional-access) acctTxCount == 1 implies txIter is set if (acctTxCount == 1 && txIter->first->second.consequences().isBlocker() && (txIter->first->first != txSeqProx)) + // NOLINTEND(bugprone-unchecked-optional-access) { return {telCAN_NOT_QUEUE_BLOCKED, false}; } @@ -988,6 +994,8 @@ TxQ::apply( // o The current first thing in the queue has a Ticket and // * The tx has a Ticket that precedes it or // * txSeqProx == acctSeqProx. + // NOLINTBEGIN(bugprone-unchecked-optional-access) acctTxCount > 0 in else branch + // implies txIter is set XRPL_ASSERT(prevIter != txIter->end, "xrpl::TxQ::apply : not end"); if (prevIter == txIter->end || txSeqProx < prevIter->first) { @@ -1040,6 +1048,7 @@ TxQ::apply( potentialSpend += pfResult.consequences.potentialSpend(); } } + // NOLINTEND(bugprone-unchecked-optional-access) /* Check if the total fees in flight are greater than the account's current balance, or the diff --git a/src/xrpld/app/misc/detail/ValidatorList.cpp b/src/xrpld/app/misc/detail/ValidatorList.cpp index a799ad48343..8a62a719729 100644 --- a/src/xrpld/app/misc/detail/ValidatorList.cpp +++ b/src/xrpld/app/misc/detail/ValidatorList.cpp @@ -948,8 +948,12 @@ ValidatorList::applyListsAndBroadcast( // in the config file (Note: Keys specified in the local config file are // stored in ValidatorList::localPublisherList data member). if (broadcast && result.status <= PublisherStatus::expired && result.publisherKey && + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) publisherKey checked in condition + // above publisherLists_[*result.publisherKey].maxSequence) { + // NOLINTBEGIN(bugprone-unchecked-optional-access) publisherKey and maxSequence checked in + // condition above auto const& pubCollection = publisherLists_[*result.publisherKey]; broadcastBlobs( @@ -960,6 +964,7 @@ ValidatorList::applyListsAndBroadcast( overlay, hashRouter, j_); + // NOLINTEND(bugprone-unchecked-optional-access) } return result; @@ -1010,6 +1015,7 @@ ValidatorList::applyLists( // inconsistent if (result.publisherKey && publisherLists_.contains(*result.publisherKey)) { + // NOLINTBEGIN(bugprone-unchecked-optional-access) publisherKey checked in condition above auto& pubCollection = publisherLists_[*result.publisherKey]; auto& remaining = pubCollection.remaining; auto const& current = pubCollection.current; @@ -1035,6 +1041,7 @@ ValidatorList::applyLists( pubCollection.fullHash = sha512Half(pubCollection); result.sequence = *pubCollection.maxSequence; + // NOLINTEND(bugprone-unchecked-optional-access) } return result; @@ -1799,9 +1806,11 @@ ValidatorList::calculateQuorum( // Use quorum if specified via command line. if (minimumQuorum_ > 0) { + // NOLINTBEGIN(bugprone-unchecked-optional-access) minimumQuorum_ > 0 implies it has a value JLOG(j_.warn()) << "Using potentially unsafe quorum of " << *minimumQuorum_ << " as specified on the command line"; return *minimumQuorum_; + // NOLINTEND(bugprone-unchecked-optional-access) } if (!publisherLists_.empty()) @@ -2012,7 +2021,8 @@ ValidatorList::updateTrusted( { std::optional const signingKey = validatorManifests_.getSigningKey(k); XRPL_ASSERT(signingKey, "xrpl::ValidatorList::updateTrusted : found signing key"); - trustedSigningKeys_.insert(*signingKey); + trustedSigningKeys_.insert( + *signingKey); // NOLINT(bugprone-unchecked-optional-access) assert above } } diff --git a/src/xrpld/app/misc/detail/ValidatorSite.cpp b/src/xrpld/app/misc/detail/ValidatorSite.cpp index ca96e0fa37e..557a4e4f25e 100644 --- a/src/xrpld/app/misc/detail/ValidatorSite.cpp +++ b/src/xrpld/app/misc/detail/ValidatorSite.cpp @@ -279,7 +279,8 @@ ValidatorSite::makeRequest( sp = std::make_shared( resource->pUrl.domain, resource->pUrl.path, - std::to_string(*resource->pUrl.port), + std::to_string(*resource->pUrl.port), // NOLINT(bugprone-unchecked-optional-access) + // port defaulted at parse time app_.getIOContext(), j_, app_.config(), @@ -292,7 +293,8 @@ ValidatorSite::makeRequest( sp = std::make_shared( resource->pUrl.domain, resource->pUrl.path, - std::to_string(*resource->pUrl.port), + std::to_string(*resource->pUrl.port), // NOLINT(bugprone-unchecked-optional-access) + // port defaulted at parse time app_.getIOContext(), sites_[siteIdx].lastRequestEndpoint, sites_[siteIdx].lastRequestSuccessful, diff --git a/src/xrpld/consensus/Consensus.h b/src/xrpld/consensus/Consensus.h index 4337e8da01b..68ea8fb4037 100644 --- a/src/xrpld/consensus/Consensus.h +++ b/src/xrpld/consensus/Consensus.h @@ -914,12 +914,14 @@ Consensus::simulate( JLOG(j_.info()) << "Simulating consensus"; now_ = now; closeLedger({}); + // NOLINTBEGIN(bugprone-unchecked-optional-access) closeLedger sets result_ result_->roundTime.tick(consensusDelay.value_or(100ms)); result_->proposers = prevProposers_ = currPeerPositions_.size(); prevRoundTime_ = result_->roundTime.read(); phase_ = ConsensusPhase::accepted; adaptor_.onForceAccept( *result_, previousLedger_, closeResolution_, rawCloseTimes_, mode_.get(), getJson(true)); + // NOLINTEND(bugprone-unchecked-optional-access) JLOG(j_.info()) << "Simulation complete"; } @@ -1209,8 +1211,13 @@ Consensus::shouldPause(std::unique_ptr const& clog) vars << " consensuslog (working seq: " << previousLedger_.seq() << ", " << "validated seq: " << adaptor_.getValidLedgerIndex() << ", " << "am validator: " << adaptor_.validator() << ", " - << "have validated: " << adaptor_.haveValidated() << ", " - << "roundTime: " << result_->roundTime.read().count() << ", " + << "have validated: " << adaptor_.haveValidated() + << ", " + // NOLINTBEGIN(bugprone-unchecked-optional-access) result_ is always set when shouldPause + // is called (from phaseEstablish after assert) + << "roundTime: " << result_->roundTime.read().count() + << ", " + // NOLINTEND(bugprone-unchecked-optional-access) << "max consensus time: " << parms.ledgerMAX_CONSENSUS.count() << ", " << "validators: " << totalValidators << ", " << "laggards: " << laggards << ", " @@ -1218,7 +1225,9 @@ Consensus::shouldPause(std::unique_ptr const& clog) << "quorum: " << quorum << ")"; if ((ahead == 0u) || (laggards == 0u) || (totalValidators == 0u) || !adaptor_.validator() || - !adaptor_.haveValidated() || result_->roundTime.read() > parms.ledgerMAX_CONSENSUS) + !adaptor_.haveValidated() || + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) result_ set as shouldPause called + result_->roundTime.read() > parms.ledgerMAX_CONSENSUS) { j_.debug() << "not pausing (early)" << vars.str(); CLOG(clog) << "Not pausing (early). "; @@ -1316,6 +1325,7 @@ Consensus::phaseEstablish(std::unique_ptr const& clo CLOG(clog) << "phaseEstablish. "; // can only establish consensus if we already took a stance XRPL_ASSERT(result_, "xrpl::Consensus::phaseEstablish : result is set"); + // NOLINTBEGIN(bugprone-unchecked-optional-access) assert above ++peerUnchangedCounter_; ++establishCounter_; @@ -1371,6 +1381,7 @@ Consensus::phaseEstablish(std::unique_ptr const& clo mode_.get(), getJson(true), adaptor_.validating()); + // NOLINTEND(bugprone-unchecked-optional-access) } template @@ -1435,6 +1446,7 @@ Consensus::updateOurPositions(std::unique_ptr const& { // We must have a position if we are updating it XRPL_ASSERT(result_, "xrpl::Consensus::updateOurPositions : result is set"); + // NOLINTBEGIN(bugprone-unchecked-optional-access) assert above ConsensusParms const& parms = adaptor_.parms(); // Compute a cutoff time @@ -1607,6 +1619,7 @@ Consensus::updateOurPositions(std::unique_ptr const& if (!result_->position.isBowOut() && (mode_.get() == ConsensusMode::proposing)) adaptor_.propose(result_->position); } + // NOLINTEND(bugprone-unchecked-optional-access) } template @@ -1615,6 +1628,7 @@ Consensus::haveConsensus(std::unique_ptr const& clog { // Must have a stance if we are checking for consensus XRPL_ASSERT(result_, "xrpl::Consensus::haveConsensus : has result"); + // NOLINTBEGIN(bugprone-unchecked-optional-access) assert above // CHECKME: should possibly count unacquired TX sets as disagreeing int agree = 0, disagree = 0; @@ -1715,6 +1729,7 @@ Consensus::haveConsensus(std::unique_ptr const& clog } CLOG(clog) << "Consensus has been reached. "; + // NOLINTEND(bugprone-unchecked-optional-access) return true; } @@ -1742,6 +1757,7 @@ Consensus::createDisputes(TxSet_t const& o, std::unique_ptrcompares.emplace(o.id()).second; @@ -1801,6 +1817,7 @@ Consensus::createDisputes(TxSet_t const& o, std::unique_ptr @@ -1809,6 +1826,7 @@ Consensus::updateDisputes(NodeID_t const& node, TxSet_t const& other) { // Cannot updateDisputes without our stance XRPL_ASSERT(result_, "xrpl::Consensus::updateDisputes : result is set"); + // NOLINTBEGIN(bugprone-unchecked-optional-access) assert above // Ensure we have created disputes against this set if we haven't seen // it before @@ -1821,6 +1839,7 @@ Consensus::updateDisputes(NodeID_t const& node, TxSet_t const& other) if (d.setVote(node, other.exists(d.tx().id()))) peerUnchangedCounter_ = 0; } + // NOLINTEND(bugprone-unchecked-optional-access) } template diff --git a/src/xrpld/consensus/LedgerTrie.h b/src/xrpld/consensus/LedgerTrie.h index 38ad0afbf94..99ddb530dfb 100644 --- a/src/xrpld/consensus/LedgerTrie.h +++ b/src/xrpld/consensus/LedgerTrie.h @@ -470,7 +470,7 @@ class LedgerTrie // Loc truncates to prefix and newNode is its child XRPL_ASSERT(prefix, "xrpl::LedgerTrie::insert : prefix is set"); - loc->span = *prefix; + loc->span = *prefix; // NOLINT(bugprone-unchecked-optional-access) assert above newNode->parent = loc; loc->children.emplace_back(std::move(newNode)); loc->tipSupport = 0; @@ -703,7 +703,11 @@ class LedgerTrie // We did not consume the entire span, so we have found the // preferred ledger if (nextSeq < curr->span.end()) + { + // nextSeq within span guarantees before() is set + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) return curr->span.before(nextSeq)->tip(); + } } // We have reached the end of the current span, so we need to diff --git a/src/xrpld/overlay/detail/OverlayImpl.cpp b/src/xrpld/overlay/detail/OverlayImpl.cpp index 30fa2587e71..f29d97cb11a 100644 --- a/src/xrpld/overlay/detail/OverlayImpl.cpp +++ b/src/xrpld/overlay/detail/OverlayImpl.cpp @@ -689,7 +689,7 @@ OverlayImpl::onManifests( mo, "xrpl::OverlayImpl::onManifests : manifest " "deserialization succeeded"); - + // NOLINTBEGIN(bugprone-unchecked-optional-access) assert above app_.getOPs().pubManifest(*mo); if (app_.getValidators().listed(mo->masterKey)) @@ -697,6 +697,7 @@ OverlayImpl::onManifests( auto db = app_.getWalletDB().checkoutDb(); addValidatorManifest(*db, serialized); } + // NOLINTEND(bugprone-unchecked-optional-access) } } else diff --git a/src/xrpld/overlay/detail/PeerImp.cpp b/src/xrpld/overlay/detail/PeerImp.cpp index 5bfc33021dd..46a640ec5cb 100644 --- a/src/xrpld/overlay/detail/PeerImp.cpp +++ b/src/xrpld/overlay/detail/PeerImp.cpp @@ -2254,6 +2254,7 @@ PeerImp::onValidatorListMessage( applyResult.publisherKey, "xrpl::PeerImp::onValidatorListMessage : publisher key is " "set"); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) assert above auto const& pubKey = *applyResult.publisherKey; #ifndef NDEBUG if (auto const iter = publisherListSequences_.find(pubKey); @@ -3463,6 +3464,7 @@ PeerImp::processLedgerRequest(std::shared_ptr const& m) try { + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) nodeids checked in onGetLedger if (map->getNodeFat(*shaMapNodeId, data, fatLeaves, queryDepth)) { JLOG(p_journal_.trace()) diff --git a/src/xrpld/perflog/detail/PerfLogImp.cpp b/src/xrpld/perflog/detail/PerfLogImp.cpp index 57e7be51561..6b80d29cc6b 100644 --- a/src/xrpld/perflog/detail/PerfLogImp.cpp +++ b/src/xrpld/perflog/detail/PerfLogImp.cpp @@ -18,7 +18,6 @@ #include #include -#include #include #include #include diff --git a/src/xrpld/rpc/detail/PathRequest.cpp b/src/xrpld/rpc/detail/PathRequest.cpp index b4ac252f104..1719567357a 100644 --- a/src/xrpld/rpc/detail/PathRequest.cpp +++ b/src/xrpld/rpc/detail/PathRequest.cpp @@ -507,6 +507,7 @@ PathRequest::getPathFinder( auto i = pathasset_map.find(asset); if (i != pathasset_map.end()) return i->second; + // NOLINTBEGIN(bugprone-unchecked-optional-access) isValid() ensures both are set auto pathfinder = std::make_unique( cache, *raSrcAccount, @@ -517,6 +518,7 @@ PathRequest::getPathFinder( saSendMax, domain, app_); + // NOLINTEND(bugprone-unchecked-optional-access) if (pathfinder->findPaths(level, continueCallback)) { pathfinder->computePathRanks(max_paths_, continueCallback); @@ -542,8 +544,10 @@ PathRequest::findPaths( } if (sourceAssets.empty()) { + // NOLINTBEGIN(bugprone-unchecked-optional-access) isValid() ensures both are set auto assets = accountSourceAssets(*raSrcAccount, cache, true); bool const sameAccount = *raSrcAccount == *raDstAccount; + // NOLINTEND(bugprone-unchecked-optional-access) for (auto const& asset : assets) { if (!std::visit( @@ -621,13 +625,15 @@ PathRequest::findPaths( auto sandbox = std::make_unique(&*cache->getLedger(), tapNONE); auto rc = path::RippleCalc::rippleCalculate( *sandbox, - saMaxAmount, // --> Amount to send is unlimited - // to get an estimate. - dst_amount, // --> Amount to deliver. + saMaxAmount, // --> Amount to send is unlimited + // to get an estimate. + dst_amount, // --> Amount to deliver. + // NOLINTBEGIN(bugprone-unchecked-optional-access) isValid() ensures both are set *raDstAccount, // --> Account to deliver to. *raSrcAccount, // --> Account sending from. - ps, // --> Path set. - domain, // --> Domain. + // NOLINTEND(bugprone-unchecked-optional-access) + ps, // --> Path set. + domain, // --> Domain. app_, &rcInput); @@ -640,13 +646,15 @@ PathRequest::findPaths( sandbox = std::make_unique(&*cache->getLedger(), tapNONE); rc = path::RippleCalc::rippleCalculate( *sandbox, - saMaxAmount, // --> Amount to send is unlimited - // to get an estimate. - dst_amount, // --> Amount to deliver. + saMaxAmount, // --> Amount to send is unlimited + // to get an estimate. + dst_amount, // --> Amount to deliver. + // NOLINTBEGIN(bugprone-unchecked-optional-access) isValid() ensures both are set *raDstAccount, // --> Account to deliver to. *raSrcAccount, // --> Account sending from. - ps, // --> Path set. - domain, // --> Domain. + // NOLINTEND(bugprone-unchecked-optional-access) + ps, // --> Path set. + domain, // --> Domain. app_); if (!isTesSuccess(rc.result())) @@ -718,13 +726,16 @@ PathRequest::doUpdate( { // Old ripple_path_find API gives destination_currencies auto& destAssets = (newStatus[jss::destination_currencies] = Json::arrayValue); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) isValid() ensures both are set auto const assets = accountDestAssets(*raDstAccount, cache, true); for (auto const& asset : assets) destAssets.append(to_string(asset)); } + // NOLINTBEGIN(bugprone-unchecked-optional-access) isValid() ensures both are set newStatus[jss::source_account] = toBase58(*raSrcAccount); newStatus[jss::destination_account] = toBase58(*raDstAccount); + // NOLINTEND(bugprone-unchecked-optional-access) newStatus[jss::destination_amount] = saDstAmount.getJson(JsonOptions::none); newStatus[jss::full_reply] = !fast; diff --git a/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp b/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp index 09342892269..b4c654e2457 100644 --- a/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp +++ b/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp @@ -440,6 +440,7 @@ getOrAcquireLedger(RPC::JsonContext const& context) auto refHash = hashOfSeq(*ledger, refIndex, j); XRPL_ASSERT(refHash, "xrpl::RPC::getOrAcquireLedger : nonzero ledger hash"); + // NOLINTBEGIN(bugprone-unchecked-optional-access) assert above ledger = ledgerMaster.getLedgerByHash(*refHash); if (!ledger) { @@ -456,6 +457,7 @@ getOrAcquireLedger(RPC::JsonContext const& context) } if (auto il = context.app.getInboundLedgers().find(*refHash)) + // NOLINTEND(bugprone-unchecked-optional-access) { Json::Value jvResult = RPC::make_error( rpcLGR_NOT_FOUND, "acquiring ledger containing requested index"); From 7a449edebbe3c40ae12ace2fda739eaefd64810b Mon Sep 17 00:00:00 2001 From: Jingchen Date: Thu, 23 Apr 2026 18:59:49 +0100 Subject: [PATCH 03/34] refactor: Clean up NetworkOPs (#6575) Signed-off-by: JCW --- src/xrpld/app/misc/NetworkOPs.cpp | 413 +++++++++++++----------------- 1 file changed, 179 insertions(+), 234 deletions(-) diff --git a/src/xrpld/app/misc/NetworkOPs.cpp b/src/xrpld/app/misc/NetworkOPs.cpp index cedc8888256..8de65d8b397 100644 --- a/src/xrpld/app/misc/NetworkOPs.cpp +++ b/src/xrpld/app/misc/NetworkOPs.cpp @@ -3653,285 +3653,230 @@ NetworkOPsImp::unsubAccountInternal( void NetworkOPsImp::addAccountHistoryJob(SubAccountHistoryInfoWeak subInfo) { - enum DatabaseType { Sqlite, None }; - static auto const databaseType = [&]() -> DatabaseType { - // Use a dynamic_cast to return DatabaseType::None - // on failure. - if (dynamic_cast(®istry_.get().getRelationalDatabase())) - { - return DatabaseType::Sqlite; - } - return DatabaseType::None; - }(); + registry_.get().getJobQueue().addJob(jtCLIENT_ACCT_HIST, "HistTxStream", [this, subInfo]() { + auto const& accountId = subInfo.index_->accountId_; + auto& lastLedgerSeq = subInfo.index_->historyLastLedgerSeq_; + auto& txHistoryIndex = subInfo.index_->historyTxIndex_; - if (databaseType == DatabaseType::None) - { - // LCOV_EXCL_START - UNREACHABLE("xrpl::NetworkOPsImp::addAccountHistoryJob : no database"); - JLOG(m_journal.error()) << "AccountHistory job for account " - << toBase58(subInfo.index_->accountId_) << " no database"; - if (auto sptr = subInfo.sinkWptr_.lock(); sptr) - { - sptr->send(rpcError(rpcINTERNAL), true); - unsubAccountHistory(sptr, subInfo.index_->accountId_, false); - } - return; - // LCOV_EXCL_STOP - } + JLOG(m_journal.trace()) << "AccountHistory job for account " << toBase58(accountId) + << " started. lastLedgerSeq=" << lastLedgerSeq; - registry_.get().getJobQueue().addJob( - jtCLIENT_ACCT_HIST, "HistTxStream", [this, dbType = databaseType, subInfo]() { - auto const& accountId = subInfo.index_->accountId_; - auto& lastLedgerSeq = subInfo.index_->historyLastLedgerSeq_; - auto& txHistoryIndex = subInfo.index_->historyTxIndex_; - - JLOG(m_journal.trace()) << "AccountHistory job for account " << toBase58(accountId) - << " started. lastLedgerSeq=" << lastLedgerSeq; - - auto isFirstTx = [&](std::shared_ptr const& tx, - std::shared_ptr const& meta) -> bool { - /* - * genesis account: first tx is the one with seq 1 - * other account: first tx is the one created the account - */ - if (accountId == genesisAccountId) - { - auto stx = tx->getSTransaction(); - if (stx->getAccountID(sfAccount) == accountId && stx->getSeqValue() == 1) - return true; - } + auto isFirstTx = [&](std::shared_ptr const& tx, + std::shared_ptr const& meta) -> bool { + /* + * genesis account: first tx is the one with seq 1 + * other account: first tx is the one created the account + */ + if (accountId == genesisAccountId) + { + auto stx = tx->getSTransaction(); + if (stx->getAccountID(sfAccount) == accountId && stx->getSeqValue() == 1) + return true; + } - for (auto& node : meta->getNodes()) - { - if (node.getFieldU16(sfLedgerEntryType) != ltACCOUNT_ROOT) - continue; + for (auto& node : meta->getNodes()) + { + if (node.getFieldU16(sfLedgerEntryType) != ltACCOUNT_ROOT) + continue; - if (node.isFieldPresent(sfNewFields)) + if (node.isFieldPresent(sfNewFields)) + { + if (auto inner = dynamic_cast(node.peekAtPField(sfNewFields)); + inner) { - if (auto inner = - dynamic_cast(node.peekAtPField(sfNewFields)); - inner) + if (inner->isFieldPresent(sfAccount) && + inner->getAccountID(sfAccount) == accountId) { - if (inner->isFieldPresent(sfAccount) && - inner->getAccountID(sfAccount) == accountId) - { - return true; - } + return true; } } } + } - return false; - }; + return false; + }; - auto send = [&](Json::Value const& jvObj, bool unsubscribe) -> bool { - if (auto sptr = subInfo.sinkWptr_.lock()) - { - sptr->send(jvObj, true); - if (unsubscribe) - unsubAccountHistory(sptr, accountId, false); - return true; - } + auto send = [&](Json::Value const& jvObj, bool unsubscribe) -> bool { + if (auto sptr = subInfo.sinkWptr_.lock()) + { + sptr->send(jvObj, true); + if (unsubscribe) + unsubAccountHistory(sptr, accountId, false); + return true; + } - return false; - }; + return false; + }; - auto sendMultiApiJson = [&](MultiApiJson const& jvObj, bool unsubscribe) -> bool { - if (auto sptr = subInfo.sinkWptr_.lock()) - { - jvObj.visit( - sptr->getApiVersion(), // - [&](Json::Value const& jv) { sptr->send(jv, true); }); + auto sendMultiApiJson = [&](MultiApiJson const& jvObj, bool unsubscribe) -> bool { + if (auto sptr = subInfo.sinkWptr_.lock()) + { + jvObj.visit( + sptr->getApiVersion(), // + [&](Json::Value const& jv) { sptr->send(jv, true); }); - if (unsubscribe) - unsubAccountHistory(sptr, accountId, false); - return true; - } + if (unsubscribe) + unsubAccountHistory(sptr, accountId, false); + return true; + } - return false; - }; + return false; + }; - auto getMoreTxns = [&](std::uint32_t minLedger, - std::uint32_t maxLedger, - std::optional marker) - -> std::optional>> { - switch (dbType) - { - case Sqlite: { - auto& db = registry_.get().getRelationalDatabase(); - RelationalDatabase::AccountTxPageOptions const options{ - .account = accountId, - .ledgerRange = {.min = minLedger, .max = maxLedger}, - .marker = marker, - .limit = 0, - .bAdmin = true}; - return db.newestAccountTxPage(options); - } - // LCOV_EXCL_START - default: { - UNREACHABLE( - "xrpl::NetworkOPsImp::addAccountHistoryJob : " - "getMoreTxns : invalid database type"); - return {}; - } - // LCOV_EXCL_STOP - } - }; + auto getMoreTxns = [&](std::uint32_t minLedger, + std::uint32_t maxLedger, + std::optional marker) + -> std::pair< + RelationalDatabase::AccountTxs, + std::optional> { + auto& db = registry_.get().getRelationalDatabase(); + RelationalDatabase::AccountTxPageOptions const options{ + .account = accountId, + .ledgerRange = {.min = minLedger, .max = maxLedger}, + .marker = marker, + .limit = 0, + .bAdmin = true}; + return db.newestAccountTxPage(options); + }; - /* - * search backward until the genesis ledger or asked to stop - */ - while (lastLedgerSeq >= 2 && !subInfo.index_->stopHistorical_) + /* + * search backward until the genesis ledger or asked to stop + */ + while (lastLedgerSeq >= 2 && !subInfo.index_->stopHistorical_) + { + int feeChargeCount = 0; + if (auto sptr = subInfo.sinkWptr_.lock(); sptr) { - int feeChargeCount = 0; - if (auto sptr = subInfo.sinkWptr_.lock(); sptr) - { - sptr->getConsumer().charge(Resource::feeMediumBurdenRPC); - ++feeChargeCount; - } - else - { - JLOG(m_journal.trace()) - << "AccountHistory job for account " << toBase58(accountId) - << " no InfoSub. Fee charged " << feeChargeCount << " times."; - return; - } + sptr->getConsumer().charge(Resource::feeMediumBurdenRPC); + ++feeChargeCount; + } + else + { + JLOG(m_journal.trace()) + << "AccountHistory job for account " << toBase58(accountId) + << " no InfoSub. Fee charged " << feeChargeCount << " times."; + return; + } - // try to search in 1024 ledgers till reaching genesis ledgers - auto startLedgerSeq = (lastLedgerSeq > 1024 + 2 ? lastLedgerSeq - 1024 : 2); - JLOG(m_journal.trace()) << "AccountHistory job for account " << toBase58(accountId) - << ", working on ledger range [" << startLedgerSeq << "," - << lastLedgerSeq << "]"; + // try to search in 1024 ledgers till reaching genesis ledgers + auto startLedgerSeq = (lastLedgerSeq > 1024 + 2 ? lastLedgerSeq - 1024 : 2); + JLOG(m_journal.trace()) + << "AccountHistory job for account " << toBase58(accountId) + << ", working on ledger range [" << startLedgerSeq << "," << lastLedgerSeq << "]"; - auto haveRange = [&]() -> bool { - std::uint32_t validatedMin = UINT_MAX; - std::uint32_t validatedMax = 0; - auto haveSomeValidatedLedgers = - registry_.get().getLedgerMaster().getValidatedRange( - validatedMin, validatedMax); + auto haveRange = [&]() -> bool { + std::uint32_t validatedMin = UINT_MAX; + std::uint32_t validatedMax = 0; + auto haveSomeValidatedLedgers = + registry_.get().getLedgerMaster().getValidatedRange(validatedMin, validatedMax); - return haveSomeValidatedLedgers && validatedMin <= startLedgerSeq && - lastLedgerSeq <= validatedMax; - }(); + return haveSomeValidatedLedgers && validatedMin <= startLedgerSeq && + lastLedgerSeq <= validatedMax; + }(); - if (!haveRange) - { - JLOG(m_journal.debug()) << "AccountHistory reschedule job for account " - << toBase58(accountId) << ", incomplete ledger range [" - << startLedgerSeq << "," << lastLedgerSeq << "]"; - setAccountHistoryJobTimer(subInfo); - return; - } + if (!haveRange) + { + JLOG(m_journal.debug()) << "AccountHistory reschedule job for account " + << toBase58(accountId) << ", incomplete ledger range [" + << startLedgerSeq << "," << lastLedgerSeq << "]"; + setAccountHistoryJobTimer(subInfo); + return; + } + + std::optional marker{}; + while (!subInfo.index_->stopHistorical_) + { + auto dbResult = getMoreTxns(startLedgerSeq, lastLedgerSeq, marker); - std::optional marker{}; - while (!subInfo.index_->stopHistorical_) + auto const& txns = dbResult.first; + marker = dbResult.second; + size_t const num_txns = txns.size(); + for (size_t i = 0; i < num_txns; ++i) { - auto dbResult = getMoreTxns(startLedgerSeq, lastLedgerSeq, marker); - if (!dbResult) + auto const& [tx, meta] = txns[i]; + + if (!tx || !meta) + { + JLOG(m_journal.debug()) << "AccountHistory job for account " + << toBase58(accountId) << " empty tx or meta."; + send(rpcError(rpcINTERNAL), true); + return; + } + auto curTxLedger = + registry_.get().getLedgerMaster().getLedgerBySeq(tx->getLedger()); + if (!curTxLedger) { // LCOV_EXCL_START UNREACHABLE( "xrpl::NetworkOPsImp::addAccountHistoryJob : " - "getMoreTxns failed"); + "getLedgerBySeq failed"); JLOG(m_journal.debug()) << "AccountHistory job for account " - << toBase58(accountId) << " getMoreTxns failed."; + << toBase58(accountId) << " no ledger."; send(rpcError(rpcINTERNAL), true); return; // LCOV_EXCL_STOP } - - auto const& txns = dbResult->first; - marker = dbResult->second; - size_t const num_txns = txns.size(); - for (size_t i = 0; i < num_txns; ++i) + std::shared_ptr const stTxn = tx->getSTransaction(); + if (!stTxn) { - auto const& [tx, meta] = txns[i]; - - if (!tx || !meta) - { - JLOG(m_journal.debug()) << "AccountHistory job for account " - << toBase58(accountId) << " empty tx or meta."; - send(rpcError(rpcINTERNAL), true); - return; - } - auto curTxLedger = - registry_.get().getLedgerMaster().getLedgerBySeq(tx->getLedger()); - if (!curTxLedger) - { - // LCOV_EXCL_START - UNREACHABLE( - "xrpl::NetworkOPsImp::addAccountHistoryJob : " - "getLedgerBySeq failed"); - JLOG(m_journal.debug()) << "AccountHistory job for account " - << toBase58(accountId) << " no ledger."; - send(rpcError(rpcINTERNAL), true); - return; - // LCOV_EXCL_STOP - } - std::shared_ptr const stTxn = tx->getSTransaction(); - if (!stTxn) - { - // LCOV_EXCL_START - UNREACHABLE( - "NetworkOPsImp::addAccountHistoryJob : " - "getSTransaction failed"); - JLOG(m_journal.debug()) - << "AccountHistory job for account " << toBase58(accountId) - << " getSTransaction failed."; - send(rpcError(rpcINTERNAL), true); - return; - // LCOV_EXCL_STOP - } - - auto const mRef = std::ref(*meta); - auto const trR = meta->getResultTER(); - MultiApiJson jvTx = transJson(stTxn, trR, true, curTxLedger, mRef); - - jvTx.set(jss::account_history_tx_index, txHistoryIndex--); - if (i + 1 == num_txns || txns[i + 1].first->getLedger() != tx->getLedger()) - jvTx.set(jss::account_history_boundary, true); + // LCOV_EXCL_START + UNREACHABLE( + "NetworkOPsImp::addAccountHistoryJob : " + "getSTransaction failed"); + JLOG(m_journal.debug()) + << "AccountHistory job for account " << toBase58(accountId) + << " getSTransaction failed."; + send(rpcError(rpcINTERNAL), true); + return; + // LCOV_EXCL_STOP + } - if (isFirstTx(tx, meta)) - { - jvTx.set(jss::account_history_tx_first, true); - sendMultiApiJson(jvTx, false); + auto const mRef = std::ref(*meta); + auto const trR = meta->getResultTER(); + MultiApiJson jvTx = transJson(stTxn, trR, true, curTxLedger, mRef); - JLOG(m_journal.trace()) - << "AccountHistory job for account " << toBase58(accountId) - << " done, found last tx."; - return; - } + jvTx.set(jss::account_history_tx_index, txHistoryIndex--); + if (i + 1 == num_txns || txns[i + 1].first->getLedger() != tx->getLedger()) + jvTx.set(jss::account_history_boundary, true); + if (isFirstTx(tx, meta)) + { + jvTx.set(jss::account_history_tx_first, true); sendMultiApiJson(jvTx, false); - } - if (marker) - { - JLOG(m_journal.trace()) - << "AccountHistory job for account " << toBase58(accountId) - << " paging, marker=" << marker->ledgerSeq << ":" << marker->txnSeq; - } - else - { - break; + JLOG(m_journal.trace()) << "AccountHistory job for account " + << toBase58(accountId) << " done, found last tx."; + return; } + + sendMultiApiJson(jvTx, false); } - if (!subInfo.index_->stopHistorical_) + if (marker) { - lastLedgerSeq = startLedgerSeq - 1; - if (lastLedgerSeq <= 1) - { - JLOG(m_journal.trace()) - << "AccountHistory job for account " << toBase58(accountId) - << " done, reached genesis ledger."; - return; - } + JLOG(m_journal.trace()) + << "AccountHistory job for account " << toBase58(accountId) + << " paging, marker=" << marker->ledgerSeq << ":" << marker->txnSeq; + } + else + { + break; } } - }); + + if (!subInfo.index_->stopHistorical_) + { + lastLedgerSeq = startLedgerSeq - 1; + if (lastLedgerSeq <= 1) + { + JLOG(m_journal.trace()) + << "AccountHistory job for account " << toBase58(accountId) + << " done, reached genesis ledger."; + return; + } + } + } + }); } void From 248cb296818091b1a5be4516ca495708f6dfe099 Mon Sep 17 00:00:00 2001 From: Mayukha Vadari Date: Fri, 24 Apr 2026 08:06:26 -0400 Subject: [PATCH 04/34] refactor: Move `LendingHelpers` into `libxrpl/ledger/helpers` (#6638) Co-authored-by: xrplf-ai-reviewer[bot] <266832837+xrplf-ai-reviewer[bot]@users.noreply.github.com> --- .../helpers}/LendingHelpers.h | 5 ++--- include/xrpl/tx/transactors/lending/LoanSet.h | 2 +- .../helpers}/LendingHelpers.cpp | 20 ++++++++++++++----- .../lending/LoanBrokerCoverClawback.cpp | 4 ++-- .../lending/LoanBrokerCoverDeposit.cpp | 4 ++-- .../lending/LoanBrokerCoverWithdraw.cpp | 4 ++-- .../transactors/lending/LoanBrokerDelete.cpp | 4 ++-- .../tx/transactors/lending/LoanBrokerSet.cpp | 4 ++-- .../tx/transactors/lending/LoanDelete.cpp | 4 ++-- .../tx/transactors/lending/LoanManage.cpp | 4 ++-- .../tx/transactors/lending/LoanPay.cpp | 4 ++-- .../tx/transactors/lending/LoanSet.cpp | 4 ++-- src/test/app/LendingHelpers_test.cpp | 2 +- src/test/app/Loan_test.cpp | 2 +- 14 files changed, 38 insertions(+), 29 deletions(-) rename include/xrpl/{tx/transactors/lending => ledger/helpers}/LendingHelpers.h (99%) rename src/libxrpl/{tx/transactors/lending => ledger/helpers}/LendingHelpers.cpp (99%) diff --git a/include/xrpl/tx/transactors/lending/LendingHelpers.h b/include/xrpl/ledger/helpers/LendingHelpers.h similarity index 99% rename from include/xrpl/tx/transactors/lending/LendingHelpers.h rename to include/xrpl/ledger/helpers/LendingHelpers.h index 1c938bbc8a8..81d14477ef1 100644 --- a/include/xrpl/tx/transactors/lending/LendingHelpers.h +++ b/include/xrpl/ledger/helpers/LendingHelpers.h @@ -1,15 +1,14 @@ #pragma once #include +#include #include namespace xrpl { -struct PreflightContext; - // Lending protocol has dependencies, so capture them here. bool -checkLendingProtocolDependencies(PreflightContext const& ctx); +checkLendingProtocolDependencies(Rules const& rules, STTx const& tx); static constexpr std::uint32_t secondsInYear = 365 * 24 * 60 * 60; diff --git a/include/xrpl/tx/transactors/lending/LoanSet.h b/include/xrpl/tx/transactors/lending/LoanSet.h index c778582ab02..3ede5adc4c6 100644 --- a/include/xrpl/tx/transactors/lending/LoanSet.h +++ b/include/xrpl/tx/transactors/lending/LoanSet.h @@ -1,7 +1,7 @@ #pragma once +#include #include -#include namespace xrpl { diff --git a/src/libxrpl/tx/transactors/lending/LendingHelpers.cpp b/src/libxrpl/ledger/helpers/LendingHelpers.cpp similarity index 99% rename from src/libxrpl/tx/transactors/lending/LendingHelpers.cpp rename to src/libxrpl/ledger/helpers/LendingHelpers.cpp index dea8dbbd344..caccca752d8 100644 --- a/src/libxrpl/tx/transactors/lending/LendingHelpers.cpp +++ b/src/libxrpl/ledger/helpers/LendingHelpers.cpp @@ -1,4 +1,4 @@ -#include +#include #include #include @@ -7,18 +7,19 @@ #include #include #include -#include #include #include #include #include #include #include +#include #include #include +#include +#include #include #include -#include #include #include @@ -28,9 +29,18 @@ namespace xrpl { bool -checkLendingProtocolDependencies(PreflightContext const& ctx) +checkLendingProtocolDependencies(Rules const& rules, STTx const& tx) { - return ctx.rules.enabled(featureSingleAssetVault) && VaultCreate::checkExtraFeatures(ctx); + if (!rules.enabled(featureSingleAssetVault)) + return false; + + if (!rules.enabled(featureMPTokensV1)) + return false; + + if (tx.isFieldPresent(sfDomainID) && !rules.enabled(featurePermissionedDomains)) + return false; + + return true; } LoanPaymentParts& diff --git a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp index 16f95dd3577..36ff1cc2de6 100644 --- a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -25,7 +26,6 @@ #include #include #include -#include #include #include @@ -36,7 +36,7 @@ namespace xrpl { bool LoanBrokerCoverClawback::checkExtraFeatures(PreflightContext const& ctx) { - return checkLendingProtocolDependencies(ctx); + return checkLendingProtocolDependencies(ctx.rules, ctx.tx); } NotTEC diff --git a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverDeposit.cpp b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverDeposit.cpp index 36b5cab618a..9b43269ec39 100644 --- a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverDeposit.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverDeposit.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -12,7 +13,6 @@ #include #include #include -#include #include @@ -21,7 +21,7 @@ namespace xrpl { bool LoanBrokerCoverDeposit::checkExtraFeatures(PreflightContext const& ctx) { - return checkLendingProtocolDependencies(ctx); + return checkLendingProtocolDependencies(ctx.rules, ctx.tx); } NotTEC diff --git a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.cpp b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.cpp index c8479e941dd..7061ec99c3a 100644 --- a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -17,7 +18,6 @@ #include #include #include -#include #include @@ -26,7 +26,7 @@ namespace xrpl { bool LoanBrokerCoverWithdraw::checkExtraFeatures(PreflightContext const& ctx) { - return checkLendingProtocolDependencies(ctx); + return checkLendingProtocolDependencies(ctx.rules, ctx.tx); } NotTEC diff --git a/src/libxrpl/tx/transactors/lending/LoanBrokerDelete.cpp b/src/libxrpl/tx/transactors/lending/LoanBrokerDelete.cpp index 6f774eaeaee..6b1abe45aac 100644 --- a/src/libxrpl/tx/transactors/lending/LoanBrokerDelete.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanBrokerDelete.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -15,7 +16,6 @@ #include #include #include -#include #include @@ -24,7 +24,7 @@ namespace xrpl { bool LoanBrokerDelete::checkExtraFeatures(PreflightContext const& ctx) { - return checkLendingProtocolDependencies(ctx); + return checkLendingProtocolDependencies(ctx.rules, ctx.tx); } NotTEC diff --git a/src/libxrpl/tx/transactors/lending/LoanBrokerSet.cpp b/src/libxrpl/tx/transactors/lending/LoanBrokerSet.cpp index 3322df9fe3f..561890abbf4 100644 --- a/src/libxrpl/tx/transactors/lending/LoanBrokerSet.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanBrokerSet.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -18,7 +19,6 @@ #include #include #include -#include #include #include @@ -28,7 +28,7 @@ namespace xrpl { bool LoanBrokerSet::checkExtraFeatures(PreflightContext const& ctx) { - return checkLendingProtocolDependencies(ctx); + return checkLendingProtocolDependencies(ctx.rules, ctx.tx); } NotTEC diff --git a/src/libxrpl/tx/transactors/lending/LoanDelete.cpp b/src/libxrpl/tx/transactors/lending/LoanDelete.cpp index 28948a4139e..784bef7d789 100644 --- a/src/libxrpl/tx/transactors/lending/LoanDelete.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanDelete.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include // IWYU pragma: keep @@ -14,7 +15,6 @@ #include #include #include -#include #include @@ -23,7 +23,7 @@ namespace xrpl { bool LoanDelete::checkExtraFeatures(PreflightContext const& ctx) { - return checkLendingProtocolDependencies(ctx); + return checkLendingProtocolDependencies(ctx.rules, ctx.tx); } NotTEC diff --git a/src/libxrpl/tx/transactors/lending/LoanManage.cpp b/src/libxrpl/tx/transactors/lending/LoanManage.cpp index 1b87421e71f..87afc2d9084 100644 --- a/src/libxrpl/tx/transactors/lending/LoanManage.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanManage.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -22,7 +23,6 @@ #include #include #include -#include #include #include @@ -33,7 +33,7 @@ namespace xrpl { bool LoanManage::checkExtraFeatures(PreflightContext const& ctx) { - return checkLendingProtocolDependencies(ctx); + return checkLendingProtocolDependencies(ctx.rules, ctx.tx); } std::uint32_t diff --git a/src/libxrpl/tx/transactors/lending/LoanPay.cpp b/src/libxrpl/tx/transactors/lending/LoanPay.cpp index 8360303fd83..c08518a93e7 100644 --- a/src/libxrpl/tx/transactors/lending/LoanPay.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanPay.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -23,7 +24,6 @@ #include #include #include -#include #include #include @@ -36,7 +36,7 @@ namespace xrpl { bool LoanPay::checkExtraFeatures(PreflightContext const& ctx) { - return checkLendingProtocolDependencies(ctx); + return checkLendingProtocolDependencies(ctx.rules, ctx.tx); } std::uint32_t diff --git a/src/libxrpl/tx/transactors/lending/LoanSet.cpp b/src/libxrpl/tx/transactors/lending/LoanSet.cpp index 1027fdea9f0..48a6005c7bc 100644 --- a/src/libxrpl/tx/transactors/lending/LoanSet.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanSet.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -25,7 +26,6 @@ #include #include #include -#include #include #include @@ -40,7 +40,7 @@ namespace xrpl { bool LoanSet::checkExtraFeatures(PreflightContext const& ctx) { - return checkLendingProtocolDependencies(ctx); + return checkLendingProtocolDependencies(ctx.rules, ctx.tx); } std::uint32_t diff --git a/src/test/app/LendingHelpers_test.cpp b/src/test/app/LendingHelpers_test.cpp index 1e43c451045..82c80f0158d 100644 --- a/src/test/app/LendingHelpers_test.cpp +++ b/src/test/app/LendingHelpers_test.cpp @@ -6,8 +6,8 @@ #include #include +#include #include -#include #include #include diff --git a/src/test/app/Loan_test.cpp b/src/test/app/Loan_test.cpp index 8d919d7dd30..a6d642badcd 100644 --- a/src/test/app/Loan_test.cpp +++ b/src/test/app/Loan_test.cpp @@ -34,6 +34,7 @@ #include #include #include +#include #include #include #include @@ -55,7 +56,6 @@ #include #include #include -#include #include #include From 7cfa5d461072381434f95188f369f4a33c11a4ef Mon Sep 17 00:00:00 2001 From: Mayukha Vadari Date: Fri, 24 Apr 2026 08:56:50 -0400 Subject: [PATCH 05/34] fix: Make assorted Payments fixes (#6585) --- include/xrpl/ledger/PaymentSandbox.h | 12 +- include/xrpl/tx/paths/detail/FlowDebugInfo.h | 23 --- include/xrpl/tx/paths/detail/StrandFlow.h | 18 --- src/libxrpl/ledger/PaymentSandbox.cpp | 149 ++---------------- src/libxrpl/ledger/helpers/MPTokenHelpers.cpp | 10 +- .../tx/transactors/dex/OfferCreate.cpp | 3 +- .../tx/transactors/payment/Payment.cpp | 1 + 7 files changed, 21 insertions(+), 195 deletions(-) diff --git a/include/xrpl/ledger/PaymentSandbox.h b/include/xrpl/ledger/PaymentSandbox.h index 223a3c0c5a2..0c4e4bcd41f 100644 --- a/include/xrpl/ledger/PaymentSandbox.h +++ b/include/xrpl/ledger/PaymentSandbox.h @@ -21,9 +21,8 @@ class DeferredCredits struct ValueIOU { explicit ValueIOU() = default; - - STAmount lowAcctCredits; - STAmount highAcctCredits; + STAmount lowAcctDebits; + STAmount highAcctDebits; STAmount lowAcctOrigBalance; }; @@ -230,13 +229,6 @@ class PaymentSandbox final : public detail::ApplyViewBase apply(PaymentSandbox& to); /** @} */ - // Return a map of balance changes on trust lines. The low account is the - // first account in the key. If the two accounts are equal, the map contains - // the total changes in currency regardless of issuer. This is useful to get - // the total change in XRP balances. - std::map, STAmount> - balanceChanges(ReadView const& view) const; - XRPAmount xrpDestroyed() const; diff --git a/include/xrpl/tx/paths/detail/FlowDebugInfo.h b/include/xrpl/tx/paths/detail/FlowDebugInfo.h index dd7a0bb9c50..0f4abae2fef 100644 --- a/include/xrpl/tx/paths/detail/FlowDebugInfo.h +++ b/include/xrpl/tx/paths/detail/FlowDebugInfo.h @@ -327,27 +327,4 @@ writeDiffs(std::ostringstream& ostr, Iter begin, Iter end) ostr << ']'; }; -using BalanceDiffs = - std::pair, STAmount>, XRPAmount>; - -inline BalanceDiffs -balanceDiffs(PaymentSandbox const& sb, ReadView const& rv) -{ - return {sb.balanceChanges(rv), sb.xrpDestroyed()}; -} - -inline std::string -balanceDiffsToString(std::optional const& bd) -{ - if (!bd) - return std::string{}; - auto const& diffs = bd->first; - auto const& xrpDestroyed = bd->second; - std::ostringstream ostr; - ostr << ", xrpDestroyed: " << to_string(xrpDestroyed); - ostr << ", balanceDiffs: "; - writeDiffs(ostr, diffs.begin(), diffs.end()); - return ostr.str(); -}; - } // namespace xrpl::path::detail diff --git a/include/xrpl/tx/paths/detail/StrandFlow.h b/include/xrpl/tx/paths/detail/StrandFlow.h index 306a0b33e72..6a8367f4dfd 100644 --- a/include/xrpl/tx/paths/detail/StrandFlow.h +++ b/include/xrpl/tx/paths/detail/StrandFlow.h @@ -527,14 +527,6 @@ class ActiveStrands { return cur_.size(); } - - void - removeIndex(std::size_t i) - { - if (i >= next_.size()) - return; - next_.erase(next_.begin() + i); - } }; /// @endcond @@ -661,11 +653,6 @@ flow( std::optional best; if (flowDebugInfo) flowDebugInfo->newLiquidityPass(); - // Index of strand to mark as inactive (remove from the active list) if - // the liquidity is used. This is used for strands that consume too many - // offers Constructed as `false,0` to workaround a gcc warning about - // uninitialized variables - std::optional markInactiveOnUse; for (size_t strandIndex = 0, sie = activeStrands.size(); strandIndex != sie; ++strandIndex) { Strand const* strand = activeStrands.get(strandIndex); @@ -729,11 +716,6 @@ flow( if (best) { - if (markInactiveOnUse) - { - activeStrands.removeIndex(*markInactiveOnUse); - markInactiveOnUse.reset(); - } savedIns.insert(best->in); savedOuts.insert(best->out); remainingOut = outReq - sum(savedOuts); diff --git a/src/libxrpl/ledger/PaymentSandbox.cpp b/src/libxrpl/ledger/PaymentSandbox.cpp index 6b38c4840cb..ef6e4be8adb 100644 --- a/src/libxrpl/ledger/PaymentSandbox.cpp +++ b/src/libxrpl/ledger/PaymentSandbox.cpp @@ -4,20 +4,16 @@ #include #include #include -#include #include #include -#include #include #include -#include #include #include #include #include #include -#include #include #include #include @@ -58,14 +54,14 @@ DeferredCredits::creditIOU( if (sender < receiver) { - v.highAcctCredits = amount; - v.lowAcctCredits = amount.zeroed(); + v.lowAcctDebits = amount; + v.highAcctDebits = amount.zeroed(); v.lowAcctOrigBalance = preCreditSenderBalance; } else { - v.highAcctCredits = amount.zeroed(); - v.lowAcctCredits = amount; + v.lowAcctDebits = amount.zeroed(); + v.highAcctDebits = amount; v.lowAcctOrigBalance = -preCreditSenderBalance; } @@ -77,11 +73,11 @@ DeferredCredits::creditIOU( auto& v = i->second; if (sender < receiver) { - v.highAcctCredits += amount; + v.lowAcctDebits += amount; } else { - v.lowAcctCredits += amount; + v.highAcctDebits += amount; } } } @@ -212,11 +208,11 @@ DeferredCredits::adjustmentsIOU( if (main < other) { - result.emplace(v.highAcctCredits, v.lowAcctCredits, v.lowAcctOrigBalance); + result.emplace(v.lowAcctDebits, v.highAcctDebits, v.lowAcctOrigBalance); return result; } - result.emplace(v.lowAcctCredits, v.highAcctCredits, -v.lowAcctOrigBalance); + result.emplace(v.highAcctDebits, v.lowAcctDebits, -v.lowAcctOrigBalance); return result; } @@ -239,8 +235,8 @@ DeferredCredits::apply(DeferredCredits& to) { auto& toVal = r.first->second; auto const& fromVal = i.second; - toVal.lowAcctCredits += fromVal.lowAcctCredits; - toVal.highAcctCredits += fromVal.highAcctCredits; + toVal.lowAcctDebits += fromVal.lowAcctDebits; + toVal.highAcctDebits += fromVal.highAcctDebits; // Do not update the orig balance, it's already correct } } @@ -467,131 +463,6 @@ PaymentSandbox::apply(PaymentSandbox& to) tab_.apply(to.tab_); } -std::map, STAmount> -PaymentSandbox::balanceChanges(ReadView const& view) const -{ - using key_t = std::tuple; - // Map of delta trust lines. As a special case, when both ends of the trust - // line are the same currency, then it's delta currency for that issuer. To - // get the change in XRP balance, Account == root, issuer == root, currency - // == XRP - std::map result; - - // populate a dictionary with low/high/currency/delta. This can be - // compared with the other versions payment code. - auto each = [&result]( - uint256 const& key, - bool isDelete, - std::shared_ptr const& before, - std::shared_ptr const& after) { - STAmount oldBalance; - STAmount newBalance; - AccountID lowID; - AccountID highID; - - // before is read from prev view - if (isDelete) - { - if (!before) - return; - - auto const bt = before->getType(); - switch (bt) - { - case ltACCOUNT_ROOT: - lowID = xrpAccount(); - highID = (*before)[sfAccount]; - oldBalance = (*before)[sfBalance]; - newBalance = oldBalance.zeroed(); - break; - case ltRIPPLE_STATE: - lowID = (*before)[sfLowLimit].getIssuer(); - highID = (*before)[sfHighLimit].getIssuer(); - oldBalance = (*before)[sfBalance]; - newBalance = oldBalance.zeroed(); - break; - case ltOFFER: - // TBD - break; - default: - break; - } - } - else if (!before) - { - // insert - auto const at = after->getType(); - switch (at) - { - case ltACCOUNT_ROOT: - lowID = xrpAccount(); - highID = (*after)[sfAccount]; - newBalance = (*after)[sfBalance]; - oldBalance = newBalance.zeroed(); - break; - case ltRIPPLE_STATE: - lowID = (*after)[sfLowLimit].getIssuer(); - highID = (*after)[sfHighLimit].getIssuer(); - newBalance = (*after)[sfBalance]; - oldBalance = newBalance.zeroed(); - break; - case ltOFFER: - // TBD - break; - default: - break; - } - } - else - { - // modify - auto const at = after->getType(); - XRPL_ASSERT( - at == before->getType(), - "xrpl::PaymentSandbox::balanceChanges : after and before " - "types matching"); - switch (at) - { - case ltACCOUNT_ROOT: - lowID = xrpAccount(); - highID = (*after)[sfAccount]; - oldBalance = (*before)[sfBalance]; - newBalance = (*after)[sfBalance]; - break; - case ltRIPPLE_STATE: - lowID = (*after)[sfLowLimit].getIssuer(); - highID = (*after)[sfHighLimit].getIssuer(); - oldBalance = (*before)[sfBalance]; - newBalance = (*after)[sfBalance]; - break; - case ltOFFER: - // TBD - break; - default: - break; - } - } - // The following are now set, put them in the map - auto delta = newBalance - oldBalance; - auto const cur = newBalance.get().currency; - result[std::make_tuple(lowID, highID, cur)] = delta; - auto r = result.emplace(std::make_tuple(lowID, lowID, cur), delta); - if (r.second) - { - r.first->second += delta; - } - - delta.negate(); - r = result.emplace(std::make_tuple(highID, highID, cur), delta); - if (r.second) - { - r.first->second += delta; - } - }; - items_.visit(view, each); - return result; -} - XRPAmount PaymentSandbox::xrpDestroyed() const { diff --git a/src/libxrpl/ledger/helpers/MPTokenHelpers.cpp b/src/libxrpl/ledger/helpers/MPTokenHelpers.cpp index d47b49e9100..c3987ddb03e 100644 --- a/src/libxrpl/ledger/helpers/MPTokenHelpers.cpp +++ b/src/libxrpl/ledger/helpers/MPTokenHelpers.cpp @@ -94,7 +94,11 @@ transferRate(ReadView const& view, MPTID const& issuanceID) // which represents 50% of 1,000,000,000 if (auto const sle = view.read(keylet::mptIssuance(issuanceID)); sle && sle->isFieldPresent(sfTransferFee)) - return Rate{1'000'000'000u + (10'000 * sle->getFieldU16(sfTransferFee))}; + { + auto const fee = sle->getFieldU16(sfTransferFee); + XRPL_ASSERT(fee <= maxTransferFee, "xrpl::transferRate : fee is too large"); + return Rate{1'000'000'000u + (10'000 * fee)}; + } return parityRate; } @@ -160,7 +164,7 @@ authorizeMPToken( // When a holder wants to unauthorize/delete a MPT, the ledger must // - delete mptokenKey from owner directory // - delete the MPToken - if ((flags & tfMPTUnauthorize) != 0) + if ((flags & tfMPTUnauthorize) != 0u) { auto const mptokenKey = keylet::mptoken(mptIssuanceID, account); auto const sleMpt = view.peek(mptokenKey); @@ -242,7 +246,7 @@ authorizeMPToken( // Issuer wants to unauthorize the holder, unset lsfMPTAuthorized on // their MPToken - if ((flags & tfMPTUnauthorize) != 0) + if ((flags & tfMPTUnauthorize) != 0u) { flagsOut &= ~lsfMPTAuthorized; } diff --git a/src/libxrpl/tx/transactors/dex/OfferCreate.cpp b/src/libxrpl/tx/transactors/dex/OfferCreate.cpp index 2d21cebbe3a..119f244185b 100644 --- a/src/libxrpl/tx/transactors/dex/OfferCreate.cpp +++ b/src/libxrpl/tx/transactors/dex/OfferCreate.cpp @@ -631,7 +631,6 @@ OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) return {tecEXPIRED, true}; } - bool const bOpenLedger = sb.open(); bool crossed = false; if (isTesSuccess(result)) @@ -720,7 +719,7 @@ OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) stream << " out: " << format_amount(place_offer.out); } - if (result == tecFAILED_PROCESSING && bOpenLedger) + if (result == tecFAILED_PROCESSING && sb.open()) result = telFAILED_PROCESSING; if (!isTesSuccess(result)) diff --git a/src/libxrpl/tx/transactors/payment/Payment.cpp b/src/libxrpl/tx/transactors/payment/Payment.cpp index 644d5210c09..8ea79e08409 100644 --- a/src/libxrpl/tx/transactors/payment/Payment.cpp +++ b/src/libxrpl/tx/transactors/payment/Payment.cpp @@ -431,6 +431,7 @@ Payment::doApply() sleDst = std::make_shared(k); sleDst->setAccountID(sfAccount, dstAccountID); sleDst->setFieldU32(sfSequence, view().seq()); + sleDst->setFieldAmount(sfBalance, XRPAmount(beast::zero)); view().insert(sleDst); } From 82abf2a84985811921e29436bdc48b03a4891833 Mon Sep 17 00:00:00 2001 From: Mayukha Vadari Date: Fri, 24 Apr 2026 09:15:12 -0400 Subject: [PATCH 06/34] docs: Update bug bounty information (#7006) --- SECURITY.md | 113 ++-------------------------------------------------- 1 file changed, 3 insertions(+), 110 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index 2e0c43a134b..d72ddcada4e 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -22,117 +22,10 @@ Responsible investigation includes, but isn't limited to, the following: - Not targeting physical security measures, or attempting to use social engineering, spam, distributed denial of service (DDOS) attacks, etc. - Investigating bugs in a way that makes a reasonable, good faith effort not to be disruptive or harmful to the XRP Ledger and the broader ecosystem. -### Responsible Disclosure - -If you discover a vulnerability or potential threat, or if you _think_ -you have, please reach out by dropping an email using the contact -information below. - -Your report should include the following: - -- Your contact information (typically, an email address); -- The description of the vulnerability; -- The attack scenario (if any); -- The steps to reproduce the vulnerability; -- Any other relevant details or artifacts, including code, scripts or patches. - -In your email, please describe the issue or potential threat. If possible, include a "repro" (code that can reproduce the issue) or describe the best way to reproduce and replicate the issue. Please make your report as detailed and comprehensive as possible. - -For more information on responsible disclosure, please read this [Wikipedia article](https://en.wikipedia.org/wiki/Responsible_disclosure). - -## Report Handling Process - -Please report the bug directly to us and limit further disclosure. If you want to prove that you knew the bug as of a given time, consider using a cryptographic pre-commitment: hash the content of your report and publish the hash on a medium of your choice (e.g. on Twitter or as a memo in a transaction) as "proof" that you had written the text at a given point in time. - -Once we receive a report, we: - -1. Assign two people to independently evaluate the report; -2. Consider their recommendations; -3. If action is necessary, formulate a plan to address the issue; -4. Communicate privately with the reporter to explain our plan. -5. Prepare, test and release a version which fixes the issue; and -6. Announce the vulnerability publicly. - -We will triage and respond to your disclosure within 24 hours. Beyond that, we will work to analyze the issue in more detail, formulate, develop and test a fix. - -While we commit to responding with 24 hours of your initial report with our triage assessment, we cannot guarantee a response time for the remaining steps. We will communicate with you throughout this process, letting you know where we are and keeping you updated on the timeframe. - ## Bug Bounty Program -[Ripple](https://ripple.com) is generously sponsoring a bug bounty program for vulnerabilities in [`xrpld`](https://github.com/XRPLF/rippled) (and other related projects, like [`xrpl.js`](https://github.com/XRPLF/xrpl.js), [`xrpl-py`](https://github.com/XRPLF/xrpl-py), [`xrpl4j`](https://github.com/XRPLF/xrpl4j)). - -This program allows us to recognize and reward individuals or groups that identify and report bugs. In summary, in order to qualify for a bounty, the bug must be: - -1. **In scope**. Only bugs in software under the scope of the program qualify. Currently, that means `xrpld`, `xrpl.js`, `xrpl-py`, `xrpl4j`. -2. **Relevant**. A security issue, posing a danger to user funds, privacy, or the operation of the XRP Ledger. -3. **Original and previously unknown**. Bugs that are already known and discussed in public do not qualify. Previously reported bugs, even if publicly unknown, are not eligible. -4. **Specific**. We welcome general security advice or recommendations, but we cannot pay bounties for that. -5. **Fixable**. There has to be something we can do to permanently fix the problem. Note that bugs in other people’s software may still qualify in some cases. For example, if you find a bug in a library that we use which can compromise the security of software that is in scope and we can get it fixed, you may qualify for a bounty. -6. **Unused**. If you use the exploit to attack the XRP Ledger, you do not qualify for a bounty. If you report a vulnerability used in an ongoing or past attack and there is specific, concrete evidence that suggests you are the attacker we reserve the right not to pay a bounty. - -The amount paid varies dramatically. Vulnerabilities that are harmless on their own, but could form part of a critical exploit will usually receive a bounty. Full-blown exploits can receive much higher bounties. Please don’t hold back partial vulnerabilities while trying to construct a full-blown exploit. We will pay a bounty to anyone who reports a complete chain of vulnerabilities even if they have reported each component of the exploit separately and those vulnerabilities have been fixed in the meantime. However, to qualify for a the full bounty, you must to have been the first to report each of the partial exploits. - -### Contacting Us - -To report a qualifying bug, please send a detailed report to: - -| Email Address | bugs@ripple.com | -| :-----------: | :-------------------------------------------------- | -| Short Key ID | `0xA9F514E0` | -| Long Key ID | `0xD900855AA9F514E0` | -| Fingerprint | `B72C 0654 2F2A E250 2763 A268 D900 855A A9F5 14E0` | +[Ripple](https://ripple.com) is generously sponsoring a bug bounty program for vulnerabilities in [`xrpld`](https://github.com/XRPLF/rippled) (and other related projects, like [`Clio`](https://github.com/XRPLF/clio), [`xrpl.js`](https://github.com/XRPLF/xrpl.js), [`xrpl-py`](https://github.com/XRPLF/xrpl-py), [`xrpl4j`](https://github.com/XRPLF/xrpl4j)). -The full PGP key for this address, which is also available on several key servers (e.g. on [keyserver.ubuntu.com](https://keyserver.ubuntu.com)), is: +This program allows us to recognize and reward individuals or groups that identify and report bugs. -``` ------BEGIN PGP PUBLIC KEY BLOCK----- -mQINBGkSZAQBEACprU199OhgdsOsygNjiQV4msuN3vDOUooehL+NwfsGfW79Tbqq -Q2u7uQ3NZjW+M2T4nsDwuhkr7pe7xSReR5W8ssaczvtUyxkvbMClilcgZ2OSCAuC -N9tzJsqOqkwBvXoNXkn//T2jnPz0ZU2wSF+NrEibq5FeuyGdoX3yXXBxq9pW9HzK -HkQll63QSl6BzVSGRQq+B6lGgaZGLwf3mzmIND9Z5VGLNK2jKynyz9z091whNG/M -kV+E7/r/bujHk7WIVId07G5/COTXmSr7kFnNEkd2Umw42dkgfiNKvlmJ9M7c1wLK -KbL9Eb4ADuW6rRc5k4s1e6GT8R4/VPliWbCl9SE32hXH8uTkqVIFZP2eyM5WRRHs -aKzitkQG9UK9gcb0kdgUkxOvvgPHAe5IuZlcHFzU4y0dBbU1VEFWVpiLU0q+IuNw -5BRemeHc59YNsngkmAZ+/9zouoShRusZmC8Wzotv75C2qVBcjijPvmjWAUz0Zunm -Lsr+O71vqHE73pERjD07wuD/ISjiYRYYE/bVrXtXLZijC7qAH4RE3nID+2ojcZyO -/2jMQvt7un56RsGH4UBHi3aBHi9bUoDGCXKiQY981cEuNaOxpou7Mh3x/ONzzSvk -sTV6nl1LOZHykN1JyKwaNbTSAiuyoN+7lOBqbV04DNYAHL88PrT21P83aQARAQAB -tB1SaXBwbGUgTGFicyA8YnVnc0ByaXBwbGUuY29tPokCTgQTAQgAOBYhBLcsBlQv -KuJQJ2OiaNkAhVqp9RTgBQJpEmQEAhsDBQsJCAcCBhUKCQgLAgQWAgMBAh4BAheA -AAoJENkAhVqp9RTgBzgP/i7y+aDWl1maig1XMdyb+o0UGusumFSW4Hmj278wlKVv -usgLPihYgHE0PKrv6WRyKOMC1tQEcYYN93M+OeQ1vFhS2YyURq6RCMmh4zq/awXG -uZbG36OURB5NH8lGBOHiN/7O+nY0CgenBT2JWm+GW3nEOAVOVm4+r5GlpPlv+Dp1 -NPBThcKXFMnH73++NpSQoDzTfRYHPxhDAX3jkLi/moXfSanOLlR6l94XNNN0jBHW -Quao0rzf4WSXq9g6AS224xhAA5JyIcFl8TX7hzj5HaFn3VWo3COoDu4U7H+BM0fl -85yqiMQypp7EhN2gxpMMWaHY5TFM85U/bFXFYfEgihZ4/gt4uoIzsNI9jlX7mYvG -KFdDij+oTlRsuOxdIy60B3dKcwOH9nZZCz0SPsN/zlRWgKzK4gDKdGhFkU9OlvPu -94ZqscanoiWKDoZkF96+sjgfjkuHsDK7Lwc1Xi+T4drHG/3aVpkYabXox+lrKB/S -yxZjeqOIQzWPhnLgCaLyvsKo5hxKzL0w3eURu8F3IS7RgOOlljv4M+Me9sEVcdNV -aN3/tQwbaomSX1X5D5YXqhBwC3rU3wXwamsscRTGEpkV+JCX6KUqGP7nWmxCpAly -FL05XuOd5SVHJjXLeuje0JqLUpN514uL+bThWwDbDTdAdwW3oK/2WbXz7IfJRLBj -uQINBGkSZAQBEADdI3SL2F72qkrgFqXWE6HSRBu9bsAvTE5QrRPWk7ux6at537r4 -S4sIw2dOwLvbyIrDgKNq3LQ5wCK88NO/NeCOFm4AiCJSl3pJHXYnTDoUxTrrxx+o -vSRI4I3fHEql/MqzgiAb0YUezjgFdh3vYheMPp/309PFbOLhiFqEcx80Mx5h06UH -gDzu1qNj3Ec+31NLic5zwkrAkvFvD54d6bqYR3SEgMau6aYEewpGHbWBi2pLqSi2 -lQcAeOFixqGpTwDmAnYR8YtjBYepy0MojEAdTHcQQlOYSDk4q4elG+io2N8vECfU -rD6ORecN48GXdZINYWTAdslrUeanmBdgQrYkSpce8TSghgT9P01SNaXxmyaehVUO -lqI4pcg5G2oojAE8ncNS3TwDtt7daTaTC3bAdr4PXDVAzNAiewjMNZPB7xidkDGQ -Y4W1LxTMXyJVWxehYOH7tsbBRKninlfRnLgYzmtIbNRAAvNcsxU6ihv3AV0WFknN -YbSzotEv1Xq/5wk309x8zCDe+sP0cQicvbXafXmUzPAZzeqFg+VLFn7F9MP1WGlW -B1u7VIvBF1Mp9Nd3EAGBAoLRdRu+0dVWIjPTQuPIuD9cCatJA0wVaKUrjYbBMl88 -a12LixNVGeSFS9N7ADHx0/o7GNT6l88YbaLP6zggUHpUD/bR+cDN7vllIQARAQAB -iQI2BBgBCAAgFiEEtywGVC8q4lAnY6Jo2QCFWqn1FOAFAmkSZAQCGwwACgkQ2QCF -Wqn1FOAfAA/8CYq4p0p4bobY20CKEMsZrkBTFJyPDqzFwMeTjgpzqbD7Y3Qq5QCK -OBbvY02GWdiIsNOzKdBxiuam2xYP9WHZj4y7/uWEvT0qlPVmDFu+HXjoJ43oxwFd -CUp2gMuQ4cSL3X94VRJ3BkVL+tgBm8CNY0vnTLLOO3kum/R69VsGJS1JSGUWjNM+ -4qwS3mz+73xJu1HmERyN2RZF/DGIZI2PyONQQ6aH85G1Dd2ohu2/DBAkQAMBrPbj -FrbDaBLyFhODxU3kTWqnfLlaElSm2EGdIU2yx7n4BggEa//NZRMm5kyeo4vzhtlQ -YIVUMLAOLZvnEqDnsLKp+22FzNR/O+htBQC4lPywl53oYSALdhz1IQlcAC1ru5KR -XPzhIXV6IIzkcx9xNkEclZxmsuy5ERXyKEmLbIHAlzFmnrldlt2ZgXDtzaorLmxj -klKibxd5tF50qOpOivz+oPtFo7n+HmFa1nlVAMxlDCUdM0pEVeYDKI5zfVwalyhZ -NnjpakdZSXMwgc7NP/hH9buF35hKDp7EckT2y3JNYwHsDdy1icXN2q40XZw5tSIn -zkPWdu3OUY8PISohN6Pw4h0RH4ZmoX97E8sEfmdKaT58U4Hf2aAv5r9IWCSrAVqY -u5jvac29CzQR9Kal0A+8phHAXHNFD83SwzIC0syaT9ficAguwGH8X6Q= -=nGuD ------END PGP PUBLIC KEY BLOCK----- -``` +We have partnered with Bugcrowd to manage this program. It is a private program, and security researchers can participate based on invitation. If you need access to the program, please email bugs@ripple.com with your Bugcrowd handle or Bugcrowd registered email, and we will get you added to the program. Once you have been added, please submit vulnerability reports through Bugcrowd, not by email. The detailed bug bounty policy is available on the Bugcrowd website. From 9ae29612ea1e2898746cbebf19b95ccdc13e9433 Mon Sep 17 00:00:00 2001 From: Mayukha Vadari Date: Fri, 24 Apr 2026 09:23:43 -0400 Subject: [PATCH 07/34] fix: Fix flaky CI tests (#7005) Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/test/app/TxQ_test.cpp | 15 ++++++++++++--- src/test/basics/PerfLog_test.cpp | 11 +++++++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/src/test/app/TxQ_test.cpp b/src/test/app/TxQ_test.cpp index 248c8121f44..844a3cd7439 100644 --- a/src/test/app/TxQ_test.cpp +++ b/src/test/app/TxQ_test.cpp @@ -3530,9 +3530,18 @@ class TxQPosNegFlows_test : public beast::unit_test::suite jv.isMember(jss::load_factor_fee_reference) && jv[jss::load_factor_fee_reference] == 256; })); - - BEAST_EXPECT( - !wsc->findMsg(1s, [&](auto const& jv) { return jv[jss::type] == "serverStatus"; })); + // Drain any extra serverStatus messages that may arrive + // asynchronously from the ledger close processing. The drain + // is bounded so the test cannot hang if serverStatus keeps + // arriving (e.g. LoadManager raising/lowering fees). + auto const drainDeadline = std::chrono::steady_clock::now() + 5s; + while (std::chrono::steady_clock::now() < drainDeadline) + { + if (!wsc->findMsg(1s, [&](auto const& jv) { return jv[jss::type] == "serverStatus"; })) + { + break; + } + } auto jv = wsc->invoke("unsubscribe", stream); BEAST_EXPECT(jv[jss::status] == "success"); diff --git a/src/test/basics/PerfLog_test.cpp b/src/test/basics/PerfLog_test.cpp index cd00b180e71..9a7d89efce3 100644 --- a/src/test/basics/PerfLog_test.cpp +++ b/src/test/basics/PerfLog_test.cpp @@ -58,6 +58,17 @@ class PerfLog_test : public beast::unit_test::suite explicit Fixture(Application& app, beast::Journal j) : app_(app), j_(j) { + // Clean up any stale state from a previous test run. On + // self-hosted CI runners the temp directory persists between + // runs, so the "nasty file" test may have left a regular file + // (or a non-empty directory) at the logDir path. + // + // The error code is intentionally ignored: if the path doesn't + // exist (the common case on a clean runner) remove_all returns + // an error, and that's fine — there's nothing to clean up. + using namespace boost::filesystem; + boost::system::error_code ec; + remove_all(logDir(), ec); } ~Fixture() From a6bd9251d269e79f17c1037caa765f88e01d0967 Mon Sep 17 00:00:00 2001 From: Zhiyuan Wang <96991820+Kassaking7@users.noreply.github.com> Date: Fri, 24 Apr 2026 12:35:10 -0400 Subject: [PATCH 08/34] docs: Update hybrid offer invariant comment (#7007) --- src/libxrpl/ledger/helpers/PermissionedDEXHelpers.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/libxrpl/ledger/helpers/PermissionedDEXHelpers.cpp b/src/libxrpl/ledger/helpers/PermissionedDEXHelpers.cpp index d65462f0cdf..456c4e95d6e 100644 --- a/src/libxrpl/ledger/helpers/PermissionedDEXHelpers.cpp +++ b/src/libxrpl/ledger/helpers/PermissionedDEXHelpers.cpp @@ -62,7 +62,8 @@ offerInDomain( if (view.rules().enabled(fixSecurity3_1_3)) { - // post-fixSecurity3_1_3: also catches empty sfAdditionalBooks (size == 0) + // post-fixSecurity3_1_3: a valid hybrid offer must have + // sfAdditionalBooks present with exactly 1 entry if (sleOffer->isFlag(lsfHybrid) && (!sleOffer->isFieldPresent(sfAdditionalBooks) || sleOffer->getFieldArray(sfAdditionalBooks).size() != 1)) @@ -74,7 +75,8 @@ offerInDomain( } else { - // pre-fixSecurity3_1_3: only check for missing sfAdditionalBooks + // pre-fixSecurity3_1_3: a valid hybrid offer must have + // sfAdditionalBooks present (size is not checked) if (sleOffer->isFlag(lsfHybrid) && !sleOffer->isFieldPresent(sfAdditionalBooks)) { JLOG(j.error()) << "Hybrid offer " << offerID << " missing AdditionalBooks field"; From 158df5394c4c480dc8571f2ed2207d77512c616e Mon Sep 17 00:00:00 2001 From: Pratik Mankawde <3397372+pratikmankawde@users.noreply.github.com> Date: Fri, 24 Apr 2026 17:47:16 +0100 Subject: [PATCH 09/34] fix: Resolve MSVC Debug build failure in JobQueue.h; re-enable _CRTDBG_MAP_ALLOC in CI (#6993) Signed-off-by: Pratik Mankawde <3397372+pratikmankawde@users.noreply.github.com> Co-authored-by: Ed Hennis --- cmake/XrplCompiler.cmake | 2 +- include/xrpl/core/JobQueue.h | 7 ++++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/cmake/XrplCompiler.cmake b/cmake/XrplCompiler.cmake index 9db754eb1dd..0b77ff35250 100644 --- a/cmake/XrplCompiler.cmake +++ b/cmake/XrplCompiler.cmake @@ -118,7 +118,7 @@ if(MSVC) NOMINMAX # TODO: Resolve these warnings, don't just silence them _SILENCE_ALL_CXX17_DEPRECATION_WARNINGS - $<$,$,$>>:_CRTDBG_MAP_ALLOC> + $<$,$>:_CRTDBG_MAP_ALLOC> ) target_link_libraries(common INTERFACE -errorreport:none -machine:X64) else() diff --git a/include/xrpl/core/JobQueue.h b/include/xrpl/core/JobQueue.h index 3c1bde89c38..bac616470a7 100644 --- a/include/xrpl/core/JobQueue.h +++ b/include/xrpl/core/JobQueue.h @@ -7,8 +7,13 @@ #include #include +// Include only the specific Boost.Coroutine2 headers actually used here. +// Avoid `boost/coroutine2/all.hpp` because it transitively pulls in +// `boost/context/pooled_fixedsize_stack.hpp`, whose `.malloc()` / `.free()` +// member calls on `boost::pool` collide with MSVC's `_CRTDBG_MAP_ALLOC` macros +// in Debug builds (see cmake/XrplCompiler.cmake). #include -#include +#include #include From 4dc923dcc5793d7c4f9a95c9a754b7a211301507 Mon Sep 17 00:00:00 2001 From: Alex Kremer Date: Fri, 24 Apr 2026 18:19:30 +0100 Subject: [PATCH 10/34] chore: Enable clang-tidy modernize-use-nodiscard check (#7015) --- .clang-tidy | 3 +- include/xrpl/basics/BasicConfig.h | 36 +++--- include/xrpl/basics/Buffer.h | 14 +-- include/xrpl/basics/CountedObject.h | 8 +- include/xrpl/basics/Expected.h | 12 +- include/xrpl/basics/IntrusivePointer.h | 24 ++-- include/xrpl/basics/IntrusiveRefCounts.h | 2 +- include/xrpl/basics/Log.h | 2 +- include/xrpl/basics/Mutex.hpp | 2 +- include/xrpl/basics/Number.h | 12 +- include/xrpl/basics/SHAMapHash.h | 8 +- include/xrpl/basics/SharedWeakCachePointer.h | 14 +-- include/xrpl/basics/SlabAllocator.h | 2 +- include/xrpl/basics/Slice.h | 12 +- include/xrpl/basics/TaggedCache.h | 6 +- include/xrpl/basics/base_uint.h | 20 ++-- include/xrpl/beast/asio/io_latency_probe.h | 2 +- include/xrpl/beast/clock/abstract_clock.h | 2 +- include/xrpl/beast/clock/manual_clock.h | 2 +- .../detail/aged_container_iterator.h | 4 +- .../container/detail/aged_ordered_container.h | 8 +- .../detail/aged_unordered_container.h | 18 +-- .../detail/empty_base_optimization.h | 2 +- include/xrpl/beast/core/List.h | 20 ++-- include/xrpl/beast/core/LockFreeStack.h | 10 +- include/xrpl/beast/core/SemanticVersion.h | 6 +- include/xrpl/beast/insight/Event.h | 2 +- include/xrpl/beast/insight/Gauge.h | 2 +- include/xrpl/beast/insight/Group.h | 2 +- include/xrpl/beast/insight/Hook.h | 2 +- include/xrpl/beast/insight/Meter.h | 2 +- include/xrpl/beast/net/IPEndpoint.h | 16 +-- .../beast/unit_test/detail/const_container.h | 14 +-- include/xrpl/beast/unit_test/recorder.h | 2 +- include/xrpl/beast/unit_test/results.h | 18 +-- include/xrpl/beast/unit_test/runner.h | 2 +- include/xrpl/beast/unit_test/suite.h | 2 +- include/xrpl/beast/unit_test/suite_info.h | 10 +- include/xrpl/beast/unit_test/thread.h | 4 +- include/xrpl/beast/utility/Journal.h | 30 ++--- include/xrpl/beast/utility/PropertyStream.h | 8 +- include/xrpl/beast/utility/WrappedSink.h | 6 +- include/xrpl/beast/utility/temp_dir.h | 4 +- include/xrpl/conditions/Fulfillment.h | 10 +- .../xrpl/conditions/detail/PreimageSha256.h | 10 +- include/xrpl/core/HashRouter.h | 4 +- include/xrpl/core/Job.h | 4 +- include/xrpl/core/JobTypeData.h | 4 +- include/xrpl/core/JobTypeInfo.h | 12 +- include/xrpl/core/JobTypes.h | 14 +-- include/xrpl/core/LoadEvent.h | 6 +- include/xrpl/core/NetworkIDService.h | 2 +- include/xrpl/core/PeerReservationTable.h | 2 +- include/xrpl/core/PerfLog.h | 4 +- include/xrpl/core/ServiceRegistry.h | 6 +- include/xrpl/core/detail/Workers.h | 4 +- include/xrpl/json/JsonPropertyStream.h | 2 +- include/xrpl/json/json_reader.h | 2 +- include/xrpl/json/json_value.h | 82 +++++++------- include/xrpl/ledger/AcceptedLedgerTx.h | 18 +-- include/xrpl/ledger/AmendmentTable.h | 20 ++-- include/xrpl/ledger/ApplyView.h | 2 +- include/xrpl/ledger/BookDirs.h | 4 +- include/xrpl/ledger/CanonicalTXSet.h | 14 +-- include/xrpl/ledger/Dir.h | 4 +- include/xrpl/ledger/PaymentSandbox.h | 16 +-- include/xrpl/ledger/ReadView.h | 54 ++++----- include/xrpl/ledger/detail/ApplyStateTable.h | 10 +- include/xrpl/ledger/detail/ApplyViewBase.h | 30 ++--- include/xrpl/ledger/detail/RawStateTable.h | 12 +- include/xrpl/ledger/detail/ReadViewFwdRange.h | 6 +- include/xrpl/ledger/helpers/LendingHelpers.h | 6 +- include/xrpl/net/AutoSocket.h | 2 +- include/xrpl/net/HTTPClientSSLContext.h | 2 +- include/xrpl/nodestore/Backend.h | 4 +- include/xrpl/nodestore/Factory.h | 2 +- include/xrpl/nodestore/NodeObject.h | 6 +- include/xrpl/nodestore/detail/DecodedBlob.h | 2 +- include/xrpl/protocol/Asset.h | 18 +-- include/xrpl/protocol/Fees.h | 2 +- include/xrpl/protocol/IOUAmount.h | 6 +- include/xrpl/protocol/InnerObjectFormats.h | 2 +- include/xrpl/protocol/Issue.h | 8 +- include/xrpl/protocol/Keylet.h | 2 +- include/xrpl/protocol/KnownFormats.h | 16 +-- include/xrpl/protocol/MPTAmount.h | 4 +- include/xrpl/protocol/MPTIssue.h | 6 +- include/xrpl/protocol/MultiApiJson.h | 4 +- include/xrpl/protocol/PathAsset.h | 6 +- include/xrpl/protocol/Permissions.h | 12 +- include/xrpl/protocol/PublicKey.h | 12 +- include/xrpl/protocol/Quality.h | 6 +- include/xrpl/protocol/QualityFunction.h | 4 +- include/xrpl/protocol/Rules.h | 4 +- include/xrpl/protocol/SField.h | 22 ++-- include/xrpl/protocol/SOTemplate.h | 20 ++-- include/xrpl/protocol/STAccount.h | 10 +- include/xrpl/protocol/STAmount.h | 42 +++---- include/xrpl/protocol/STArray.h | 22 ++-- include/xrpl/protocol/STBase.h | 16 +-- include/xrpl/protocol/STBitString.h | 10 +- include/xrpl/protocol/STBlob.h | 14 +-- include/xrpl/protocol/STCurrency.h | 14 +-- include/xrpl/protocol/STInteger.h | 12 +- include/xrpl/protocol/STIssue.h | 14 +-- include/xrpl/protocol/STLedgerEntry.h | 14 +-- include/xrpl/protocol/STNumber.h | 10 +- include/xrpl/protocol/STObject.h | 104 +++++++++--------- include/xrpl/protocol/STPathSet.h | 60 +++++----- include/xrpl/protocol/STVector256.h | 18 +-- include/xrpl/protocol/STXChainBridge.h | 26 ++--- include/xrpl/protocol/SecretKey.h | 14 +-- include/xrpl/protocol/Seed.h | 12 +- include/xrpl/protocol/SeqProxy.h | 6 +- include/xrpl/protocol/Serializer.h | 28 ++--- include/xrpl/protocol/TxMeta.h | 20 ++-- include/xrpl/protocol/Units.h | 10 +- include/xrpl/protocol/XChainAttestations.h | 16 +-- include/xrpl/protocol/XRPAmount.h | 14 +-- include/xrpl/protocol/detail/STVar.h | 4 +- include/xrpl/protocol/detail/token_errors.h | 4 +- include/xrpl/rdb/DatabaseCon.h | 3 +- include/xrpl/rdb/SociDB.h | 2 +- include/xrpl/resource/Charge.h | 6 +- include/xrpl/resource/Consumer.h | 6 +- include/xrpl/resource/detail/Entry.h | 4 +- include/xrpl/server/Handoff.h | 2 +- include/xrpl/server/InfoSub.h | 4 +- include/xrpl/server/Manifest.h | 10 +- include/xrpl/server/NetworkOPs.h | 6 +- include/xrpl/server/Port.h | 6 +- include/xrpl/server/WSSession.h | 6 +- include/xrpl/server/detail/BaseWSPeer.h | 6 +- include/xrpl/server/detail/Door.h | 2 +- include/xrpl/server/detail/io_list.h | 2 +- include/xrpl/shamap/Family.h | 2 +- include/xrpl/shamap/SHAMapAddNode.h | 10 +- include/xrpl/shamap/SHAMapNodeID.h | 10 +- include/xrpl/shamap/SHAMapSyncFilter.h | 2 +- include/xrpl/shamap/detail/TaggedPointer.h | 2 +- include/xrpl/tx/ApplyContext.h | 4 +- include/xrpl/tx/Transactor.h | 2 +- include/xrpl/tx/applySteps.h | 12 +- include/xrpl/tx/invariants/AMMInvariant.h | 16 +-- include/xrpl/tx/invariants/InvariantCheck.h | 20 ++-- include/xrpl/tx/invariants/MPTInvariant.h | 2 +- include/xrpl/tx/invariants/NFTInvariant.h | 4 +- include/xrpl/tx/paths/AMMLiquidity.h | 20 ++-- include/xrpl/tx/paths/AMMOffer.h | 24 ++-- include/xrpl/tx/paths/BookTip.h | 8 +- include/xrpl/tx/paths/Offer.h | 24 ++-- include/xrpl/tx/paths/OfferStream.h | 10 +- include/xrpl/tx/paths/RippleCalc.h | 2 +- include/xrpl/tx/paths/detail/FlowDebugInfo.h | 10 +- include/xrpl/tx/paths/detail/Steps.h | 38 +++---- include/xrpl/tx/paths/detail/StrandFlow.h | 4 +- include/xrpl/tx/transactors/dex/AMMContext.h | 8 +- src/libxrpl/basics/Number.cpp | 4 +- src/libxrpl/beast/utility/beast_Journal.cpp | 6 +- src/libxrpl/conditions/error.cpp | 10 +- src/libxrpl/json/Writer.cpp | 6 +- src/libxrpl/ledger/Ledger.cpp | 12 +- src/libxrpl/ledger/OpenView.cpp | 6 +- .../nodestore/backend/MemoryFactory.cpp | 4 +- src/libxrpl/nodestore/backend/NuDBFactory.cpp | 6 +- src/libxrpl/nodestore/backend/NullFactory.cpp | 4 +- .../nodestore/backend/RocksDBFactory.cpp | 4 +- src/libxrpl/protocol/Rules.cpp | 4 +- src/libxrpl/protocol/SecretKey.cpp | 2 +- src/libxrpl/tx/paths/BookStep.cpp | 44 ++++---- src/libxrpl/tx/paths/DirectStep.cpp | 44 ++++---- src/libxrpl/tx/paths/MPTEndpointStep.cpp | 38 +++---- src/libxrpl/tx/paths/OfferStream.cpp | 2 +- src/libxrpl/tx/paths/XRPEndpointStep.cpp | 22 ++-- .../tx/transactors/bridge/XChainBridge.cpp | 4 +- src/test/app/FlowMPT_test.cpp | 10 +- src/test/app/LedgerReplay_test.cpp | 30 ++--- src/test/app/Loan_test.cpp | 8 +- src/test/app/PayStrand_test.cpp | 10 +- src/test/app/RCLValidations_test.cpp | 4 +- src/test/app/XChain_test.cpp | 18 +-- src/test/basics/hardened_hash_test.cpp | 2 +- src/test/beast/beast_Journal_test.cpp | 2 +- src/test/beast/beast_Zero_test.cpp | 2 +- src/test/consensus/NegativeUNL_test.cpp | 2 +- src/test/consensus/Validations_test.cpp | 18 +-- src/test/core/Config_test.cpp | 17 +-- src/test/core/Workers_test.cpp | 4 +- src/test/csf/BasicNetwork.h | 2 +- src/test/csf/Digraph.h | 12 +- src/test/csf/Histogram.h | 12 +- src/test/csf/Peer.h | 6 +- src/test/csf/PeerGroup.h | 6 +- src/test/csf/Scheduler.h | 2 +- src/test/csf/TrustGraph.h | 8 +- src/test/csf/Tx.h | 12 +- src/test/csf/Validation.h | 24 ++-- src/test/csf/collectors.h | 6 +- src/test/csf/ledgers.h | 26 ++--- src/test/csf/submitters.h | 2 +- src/test/jtx/AMM.h | 20 ++-- src/test/jtx/AbstractClient.h | 2 +- src/test/jtx/Account.h | 10 +- src/test/jtx/Env.h | 30 ++--- src/test/jtx/JTx.h | 2 +- src/test/jtx/ManualTimeKeeper.h | 2 +- src/test/jtx/Oracle.h | 4 +- src/test/jtx/PathSet.h | 4 +- src/test/jtx/TestHelpers.h | 12 +- src/test/jtx/amount.h | 28 ++--- src/test/jtx/basic_prop.h | 4 +- src/test/jtx/batch.h | 2 +- src/test/jtx/deposit.h | 4 +- src/test/jtx/impl/JSONRPCClient.cpp | 2 +- src/test/jtx/impl/Oracle.cpp | 4 +- src/test/jtx/impl/WSClient.cpp | 2 +- src/test/jtx/mpt.h | 12 +- src/test/jtx/vault.h | 2 +- src/test/jtx/xchain_bridge.h | 2 +- src/test/overlay/reduce_relay_test.cpp | 26 ++--- src/test/overlay/short_read_test.cpp | 2 +- src/test/rpc/DeliveredAmount_test.cpp | 2 +- src/test/shamap/FetchPack_test.cpp | 2 +- src/test/shamap/common.h | 2 +- src/test/unit_test/FileDirGuard.h | 6 +- src/test/unit_test/SuiteJournal.h | 2 +- src/test/unit_test/multi_runner.h | 16 +-- src/tests/libxrpl/json/Value.cpp | 56 +++++----- src/tests/libxrpl/net/HTTPClient.cpp | 4 +- src/xrpld/app/consensus/RCLCxLedger.h | 16 +-- src/xrpld/app/consensus/RCLCxTx.h | 10 +- src/xrpld/app/consensus/RCLValidations.h | 32 +++--- src/xrpld/app/ledger/AcceptedLedger.h | 8 +- src/xrpld/app/ledger/AccountStateSF.h | 2 +- src/xrpld/app/ledger/ConsensusTransSetSF.h | 2 +- src/xrpld/app/ledger/LedgerReplay.h | 6 +- src/xrpld/app/ledger/LedgerReplayTask.h | 2 +- src/xrpld/app/ledger/TransactionStateSF.h | 2 +- src/xrpld/app/ledger/detail/LocalTxs.cpp | 10 +- src/xrpld/app/main/Application.cpp | 2 +- src/xrpld/app/main/Application.h | 10 +- src/xrpld/app/main/BasicApp.h | 2 +- src/xrpld/app/main/GRPCServer.h | 4 +- src/xrpld/app/main/Main.cpp | 2 +- src/xrpld/app/misc/FeeVoteImpl.cpp | 4 +- src/xrpld/app/misc/SHAMapStore.h | 8 +- src/xrpld/app/misc/Transaction.h | 4 +- src/xrpld/app/misc/TxQ.h | 12 +- src/xrpld/app/misc/ValidatorKeys.h | 2 +- src/xrpld/app/misc/ValidatorList.h | 4 +- src/xrpld/app/misc/detail/AmendmentTable.cpp | 8 +- src/xrpld/consensus/Consensus.h | 10 +- src/xrpld/consensus/ConsensusTypes.h | 2 +- src/xrpld/consensus/DisputedTx.h | 10 +- src/xrpld/consensus/LedgerTrie.h | 36 +++--- src/xrpld/consensus/Validations.h | 2 +- src/xrpld/core/Config.h | 18 +-- src/xrpld/core/NetworkIDServiceImpl.h | 2 +- src/xrpld/overlay/ClusterNode.h | 8 +- src/xrpld/overlay/Overlay.h | 16 +-- src/xrpld/overlay/Peer.h | 28 ++--- src/xrpld/overlay/PeerSet.h | 2 +- src/xrpld/overlay/Slot.h | 18 +-- src/xrpld/overlay/detail/PeerSet.cpp | 4 +- src/xrpld/overlay/detail/TrafficCount.h | 2 +- src/xrpld/overlay/detail/ZeroCopyStream.h | 4 +- src/xrpld/peerfinder/PeerfinderManager.h | 2 +- src/xrpld/peerfinder/Slot.h | 16 +-- src/xrpld/peerfinder/detail/Bootcache.h | 14 +-- src/xrpld/peerfinder/detail/Counts.h | 34 +++--- src/xrpld/peerfinder/detail/Fixed.h | 2 +- src/xrpld/peerfinder/detail/Handouts.h | 18 +-- src/xrpld/peerfinder/detail/Livecache.h | 36 +++--- src/xrpld/rpc/ServerHandler.h | 6 +- src/xrpld/rpc/Status.h | 14 +-- src/xrpld/rpc/detail/AssetCache.h | 4 +- src/xrpld/rpc/detail/LegacyPathFind.h | 2 +- src/xrpld/rpc/detail/MPT.h | 6 +- src/xrpld/rpc/detail/TransactionSign.cpp | 16 +-- src/xrpld/rpc/detail/TrustLine.h | 36 +++--- src/xrpld/rpc/detail/WSInfoSub.h | 4 +- .../server_info/ServerDefinitions.cpp | 4 +- src/xrpld/shamap/NodeFamily.h | 2 +- 283 files changed, 1496 insertions(+), 1493 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index ce12e552c44..6a967532db2 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -73,7 +73,7 @@ Checks: "-*, bugprone-unhandled-self-assignment, bugprone-unique-ptr-array-mismatch, bugprone-unsafe-functions, - bugprone-use-after-move, # has issues + bugprone-use-after-move, bugprone-unused-raii, bugprone-unused-return-value, bugprone-unused-local-non-trivial-variable, @@ -106,6 +106,7 @@ Checks: "-*, modernize-use-emplace, modernize-use-equals-default, modernize-use-equals-delete, + modernize-use-nodiscard, modernize-use-override, modernize-use-ranges, modernize-use-starts-ends-with, diff --git a/include/xrpl/basics/BasicConfig.h b/include/xrpl/basics/BasicConfig.h index e1b0af516ff..0639fb6c4d8 100644 --- a/include/xrpl/basics/BasicConfig.h +++ b/include/xrpl/basics/BasicConfig.h @@ -36,7 +36,7 @@ class Section explicit Section(std::string name = ""); /** Returns the name of this section. */ - std::string const& + [[nodiscard]] std::string const& name() const { return name_; @@ -45,7 +45,7 @@ class Section /** Returns all the lines in the section. This includes everything. */ - std::vector const& + [[nodiscard]] std::vector const& lines() const { return lines_; @@ -54,7 +54,7 @@ class Section /** Returns all the values in the section. Values are non-empty lines which are not key/value pairs. */ - std::vector const& + [[nodiscard]] std::vector const& values() const { return values_; @@ -82,7 +82,7 @@ class Section * @return The retrieved value. A section with an empty legacy value returns an empty string. */ - std::string + [[nodiscard]] std::string legacy() const { if (lines_.empty()) @@ -117,11 +117,11 @@ class Section } /** Returns `true` if a key with the given name exists. */ - bool + [[nodiscard]] bool exists(std::string const& name) const; template - std::optional + [[nodiscard]] std::optional get(std::string const& name) const { auto const iter = lookup_.find(name); @@ -132,7 +132,7 @@ class Section /// Returns a value if present, else another value. template - T + [[nodiscard]] T value_or(std::string const& name, T const& other) const { auto const v = get(name); @@ -141,7 +141,7 @@ class Section // indicates if trailing comments were seen // during the appending of any lines/values - bool + [[nodiscard]] bool had_trailing_comments() const { return had_trailing_comments_; @@ -151,42 +151,42 @@ class Section operator<<(std::ostream&, Section const& section); // Returns `true` if there are no key/value pairs. - bool + [[nodiscard]] bool empty() const { return lookup_.empty(); } // Returns the number of key/value pairs. - std::size_t + [[nodiscard]] std::size_t size() const { return lookup_.size(); } // For iteration of key/value pairs. - const_iterator + [[nodiscard]] const_iterator begin() const { return lookup_.cbegin(); } // For iteration of key/value pairs. - const_iterator + [[nodiscard]] const_iterator cbegin() const { return lookup_.cbegin(); } // For iteration of key/value pairs. - const_iterator + [[nodiscard]] const_iterator end() const { return lookup_.cend(); } // For iteration of key/value pairs. - const_iterator + [[nodiscard]] const_iterator cend() const { return lookup_.cend(); @@ -206,7 +206,7 @@ class BasicConfig public: /** Returns `true` if a section with the given name exists. */ - bool + [[nodiscard]] bool exists(std::string const& name) const; /** Returns the section with the given name. @@ -216,7 +216,7 @@ class BasicConfig Section& section(std::string const& name); - Section const& + [[nodiscard]] Section const& section(std::string const& name) const; Section const& @@ -264,7 +264,7 @@ class BasicConfig * legacy value. * @return Contents of the legacy value. */ - std::string + [[nodiscard]] std::string legacy(std::string const& sectionName) const; friend std::ostream& @@ -272,7 +272,7 @@ class BasicConfig // indicates if trailing comments were seen // in any loaded Sections - bool + [[nodiscard]] bool had_trailing_comments() const { return std::ranges::any_of(map_, [](auto s) { return s.second.had_trailing_comments(); }); diff --git a/include/xrpl/basics/Buffer.h b/include/xrpl/basics/Buffer.h index 52c092981c2..59968a4fa4d 100644 --- a/include/xrpl/basics/Buffer.h +++ b/include/xrpl/basics/Buffer.h @@ -101,13 +101,13 @@ class Buffer } /** Returns the number of bytes in the buffer. */ - std::size_t + [[nodiscard]] std::size_t size() const noexcept { return size_; } - bool + [[nodiscard]] bool empty() const noexcept { return 0 == size_; @@ -125,7 +125,7 @@ class Buffer to a single byte, to facilitate pointer arithmetic. */ /** @{ */ - std::uint8_t const* + [[nodiscard]] std::uint8_t const* data() const noexcept { return p_.get(); @@ -169,25 +169,25 @@ class Buffer return alloc(n); } - const_iterator + [[nodiscard]] const_iterator begin() const noexcept { return p_.get(); } - const_iterator + [[nodiscard]] const_iterator cbegin() const noexcept { return p_.get(); } - const_iterator + [[nodiscard]] const_iterator end() const noexcept { return p_.get() + size_; } - const_iterator + [[nodiscard]] const_iterator cend() const noexcept { return p_.get() + size_; diff --git a/include/xrpl/basics/CountedObject.h b/include/xrpl/basics/CountedObject.h index 675d1b163ba..379fd498371 100644 --- a/include/xrpl/basics/CountedObject.h +++ b/include/xrpl/basics/CountedObject.h @@ -19,7 +19,7 @@ class CountedObjects using Entry = std::pair; using List = std::vector; - List + [[nodiscard]] List getCounts(int minimumThreshold) const; public: @@ -59,19 +59,19 @@ class CountedObjects return --count_; } - int + [[nodiscard]] int getCount() const noexcept { return count_.load(); } - Counter* + [[nodiscard]] Counter* getNext() const noexcept { return next_; } - std::string const& + [[nodiscard]] std::string const& getName() const noexcept { return name_; diff --git a/include/xrpl/basics/Expected.h b/include/xrpl/basics/Expected.h index 6cba7106fb2..f4d8e5019ae 100644 --- a/include/xrpl/basics/Expected.h +++ b/include/xrpl/basics/Expected.h @@ -73,7 +73,7 @@ class Unexpected { } - constexpr E const& + [[nodiscard]] constexpr E const& value() const& { return val_; @@ -91,7 +91,7 @@ class Unexpected return std::move(val_); } - constexpr E const&& + [[nodiscard]] constexpr E const&& value() const&& { return std::move(val_); @@ -125,13 +125,13 @@ class [[nodiscard]] Expected : private boost::outcome_v2::result : private boost::outcome_v2::result @@ -181,7 +181,7 @@ class SharedIntrusive private: /** Return the raw pointer held by this object. */ - T* + [[nodiscard]] T* unsafeGetRawPtr() const; /** Exchange the current raw pointer held by this object with the given @@ -260,7 +260,7 @@ class WeakIntrusive lock() const; /** Return true if the strong count is zero. */ - bool + [[nodiscard]] bool expired() const; /** Set the pointer to null and decrement the weak count. @@ -339,7 +339,7 @@ class SharedWeakUnion don't lock the weak pointer. Use the `lock` method if that's what's needed) */ - SharedIntrusive + [[nodiscard]] SharedIntrusive getStrong() const; /** Return true if this is a strong pointer and the strong pointer is @@ -357,31 +357,31 @@ class SharedWeakUnion /** If this is a strong pointer, return the raw pointer. Otherwise return null. */ - T* + [[nodiscard]] T* get() const; /** If this is a strong pointer, return the strong count. Otherwise * return 0 */ - std::size_t + [[nodiscard]] std::size_t use_count() const; /** Return true if there is a non-zero strong count. */ - bool + [[nodiscard]] bool expired() const; /** If this is a strong pointer, return the strong pointer. Otherwise attempt to lock the weak pointer. */ - SharedIntrusive + [[nodiscard]] SharedIntrusive lock() const; /** Return true is this represents a strong pointer. */ - bool + [[nodiscard]] bool isStrong() const; /** Return true is this represents a weak pointer. */ - bool + [[nodiscard]] bool isWeak() const; /** If this is a weak pointer, attempt to convert it to a strong @@ -412,7 +412,7 @@ class SharedWeakUnion private: /** Return the raw pointer held by this object. */ - T* + [[nodiscard]] T* unsafeGetRawPtr() const; enum class RefStrength { strong, weak }; diff --git a/include/xrpl/basics/IntrusiveRefCounts.h b/include/xrpl/basics/IntrusiveRefCounts.h index ea610a521ef..e7c31bde93b 100644 --- a/include/xrpl/basics/IntrusiveRefCounts.h +++ b/include/xrpl/basics/IntrusiveRefCounts.h @@ -207,7 +207,7 @@ struct IntrusiveRefCounts RefCountPair(CountType s, CountType w) noexcept; /** Convert back to the packed integer form. */ - FieldType + [[nodiscard]] FieldType combinedValue() const noexcept; static constexpr CountType maxStrongValue = diff --git a/include/xrpl/basics/Log.h b/include/xrpl/basics/Log.h index 4efbec51994..58cca4f486f 100644 --- a/include/xrpl/basics/Log.h +++ b/include/xrpl/basics/Log.h @@ -76,7 +76,7 @@ class Logs @return `true` if a system file is associated and opened for writing. */ - bool + [[nodiscard]] bool isOpen() const noexcept; /** Associate a system file with the log. diff --git a/include/xrpl/basics/Mutex.hpp b/include/xrpl/basics/Mutex.hpp index 18c57370b18..5855ee20171 100644 --- a/include/xrpl/basics/Mutex.hpp +++ b/include/xrpl/basics/Mutex.hpp @@ -44,7 +44,7 @@ class Lock return data_; } - ProtectedDataType const& + [[nodiscard]] ProtectedDataType const& get() const { return data_; diff --git a/include/xrpl/basics/Number.h b/include/xrpl/basics/Number.h index 51ade0b5ea5..d14b17a042d 100644 --- a/include/xrpl/basics/Number.h +++ b/include/xrpl/basics/Number.h @@ -252,9 +252,9 @@ class Number // Assume unsigned values are... unsigned. i.e. positive explicit Number(internalrep mantissa, int exponent, normalized); - constexpr rep + [[nodiscard]] constexpr rep mantissa() const noexcept; - constexpr int + [[nodiscard]] constexpr int exponent() const noexcept; constexpr Number @@ -339,7 +339,7 @@ class Number } /** Return the sign of the amount */ - constexpr int + [[nodiscard]] constexpr int signum() const noexcept { if (negative_) @@ -347,7 +347,7 @@ class Number return (mantissa_ != 0u) ? 1 : 0; } - Number + [[nodiscard]] Number truncate() const noexcept; friend constexpr bool @@ -490,13 +490,13 @@ class Number MantissaRange::rep const& minMantissa, MantissaRange::rep const& maxMantissa); - bool + [[nodiscard]] bool isnormal() const noexcept; // Copy the number, but modify the exponent by "exponentDelta". Because the // mantissa doesn't change, the result will be "mostly" normalized, but the // exponent could go out of range, so it will be checked. - Number + [[nodiscard]] Number shiftExponent(int exponentDelta) const; // Safely convert rep (int64) mantissa to internalrep (uint64). If the rep diff --git a/include/xrpl/basics/SHAMapHash.h b/include/xrpl/basics/SHAMapHash.h index 22f85059126..bf688be7da4 100644 --- a/include/xrpl/basics/SHAMapHash.h +++ b/include/xrpl/basics/SHAMapHash.h @@ -20,7 +20,7 @@ class SHAMapHash { } - uint256 const& + [[nodiscard]] uint256 const& as_uint256() const { return hash_; @@ -30,17 +30,17 @@ class SHAMapHash { return hash_; } - bool + [[nodiscard]] bool isZero() const { return hash_.isZero(); } - bool + [[nodiscard]] bool isNonZero() const { return hash_.isNonZero(); } - int + [[nodiscard]] int signum() const { return hash_.signum(); diff --git a/include/xrpl/basics/SharedWeakCachePointer.h b/include/xrpl/basics/SharedWeakCachePointer.h index afc701ed5a9..05d3891e5fa 100644 --- a/include/xrpl/basics/SharedWeakCachePointer.h +++ b/include/xrpl/basics/SharedWeakCachePointer.h @@ -49,7 +49,7 @@ class SharedWeakCachePointer /** Return a strong pointer if this is already a strong pointer (i.e. don't lock the weak pointer. Use the `lock` method if that's what's needed) */ - std::shared_ptr const& + [[nodiscard]] std::shared_ptr const& getStrong() const; /** Return true if this is a strong pointer and the strong pointer is @@ -67,30 +67,30 @@ class SharedWeakCachePointer /** If this is a strong pointer, return the raw pointer. Otherwise return null. */ - T* + [[nodiscard]] T* get() const; /** If this is a strong pointer, return the strong count. Otherwise return 0 */ - std::size_t + [[nodiscard]] std::size_t use_count() const; /** Return true if there is a non-zero strong count. */ - bool + [[nodiscard]] bool expired() const; /** If this is a strong pointer, return the strong pointer. Otherwise attempt to lock the weak pointer. */ - std::shared_ptr + [[nodiscard]] std::shared_ptr lock() const; /** Return true is this represents a strong pointer. */ - bool + [[nodiscard]] bool isStrong() const; /** Return true is this represents a weak pointer. */ - bool + [[nodiscard]] bool isWeak() const; /** If this is a weak pointer, attempt to convert it to a strong pointer. diff --git a/include/xrpl/basics/SlabAllocator.h b/include/xrpl/basics/SlabAllocator.h index 5cc17858e28..39be029b421 100644 --- a/include/xrpl/basics/SlabAllocator.h +++ b/include/xrpl/basics/SlabAllocator.h @@ -180,7 +180,7 @@ class SlabAllocator ~SlabAllocator() = default; /** Returns the size of the memory block this allocator returns. */ - constexpr std::size_t + [[nodiscard]] constexpr std::size_t size() const noexcept { return itemSize_; diff --git a/include/xrpl/basics/Slice.h b/include/xrpl/basics/Slice.h index 08ee9464efa..4be7d9d0bb1 100644 --- a/include/xrpl/basics/Slice.h +++ b/include/xrpl/basics/Slice.h @@ -74,7 +74,7 @@ class Slice @note The return type is guaranteed to be a pointer to a single byte, to facilitate pointer arithmetic. */ - std::uint8_t const* + [[nodiscard]] std::uint8_t const* data() const noexcept { return data_; @@ -123,25 +123,25 @@ class Slice size_ -= n; } - const_iterator + [[nodiscard]] const_iterator begin() const noexcept { return data_; } - const_iterator + [[nodiscard]] const_iterator cbegin() const noexcept { return data_; } - const_iterator + [[nodiscard]] const_iterator end() const noexcept { return data_ + size_; } - const_iterator + [[nodiscard]] const_iterator cend() const noexcept { return data_ + size_; @@ -158,7 +158,7 @@ class Slice @returns The requested subslice, if the request is valid. @throws std::out_of_range if pos > size() */ - Slice + [[nodiscard]] Slice substr(std::size_t pos, std::size_t count = std::numeric_limits::max()) const { if (pos > size()) diff --git a/include/xrpl/basics/TaggedCache.h b/include/xrpl/basics/TaggedCache.h index d20c850bad9..8cb0c6bfdf7 100644 --- a/include/xrpl/basics/TaggedCache.h +++ b/include/xrpl/basics/TaggedCache.h @@ -222,19 +222,19 @@ class TaggedCache { } - bool + [[nodiscard]] bool isWeak() const { if (!ptr) return true; return ptr.isWeak(); } - bool + [[nodiscard]] bool isCached() const { return ptr && ptr.isStrong(); } - bool + [[nodiscard]] bool isExpired() const { return ptr.expired(); diff --git a/include/xrpl/basics/base_uint.h b/include/xrpl/basics/base_uint.h index 55b73bfb9bf..b6ff5ea9c09 100644 --- a/include/xrpl/basics/base_uint.h +++ b/include/xrpl/basics/base_uint.h @@ -102,7 +102,7 @@ class base_uint { return reinterpret_cast(data_.data()); } - const_pointer + [[nodiscard]] const_pointer data() const { return reinterpret_cast(data_.data()); @@ -118,22 +118,22 @@ class base_uint { return data() + bytes; } - const_iterator + [[nodiscard]] const_iterator begin() const { return data(); } - const_iterator + [[nodiscard]] const_iterator end() const { return data() + bytes; } - const_iterator + [[nodiscard]] const_iterator cbegin() const { return data(); } - const_iterator + [[nodiscard]] const_iterator cend() const { return data() + bytes; @@ -310,7 +310,7 @@ class base_uint return fromVoid(from.data()); } - constexpr int + [[nodiscard]] constexpr int signum() const { for (int i = 0; i < WIDTH; i++) @@ -433,14 +433,14 @@ class base_uint return ret; } - base_uint + [[nodiscard]] base_uint next() const { auto ret = *this; return ++ret; } - base_uint + [[nodiscard]] base_uint prev() const { auto ret = *this; @@ -517,12 +517,12 @@ class base_uint } // Deprecated. - bool + [[nodiscard]] bool isZero() const { return *this == beast::zero; } - bool + [[nodiscard]] bool isNonZero() const { return *this != beast::zero; diff --git a/include/xrpl/beast/asio/io_latency_probe.h b/include/xrpl/beast/asio/io_latency_probe.h index 9a8a63de4ea..dccb6d24b4a 100644 --- a/include/xrpl/beast/asio/io_latency_probe.h +++ b/include/xrpl/beast/asio/io_latency_probe.h @@ -49,7 +49,7 @@ class io_latency_probe return m_ios; } - boost::asio::io_context const& + [[nodiscard]] boost::asio::io_context const& get_io_context() const { return m_ios; diff --git a/include/xrpl/beast/clock/abstract_clock.h b/include/xrpl/beast/clock/abstract_clock.h index 41b57fdd2cb..09de3f891df 100644 --- a/include/xrpl/beast/clock/abstract_clock.h +++ b/include/xrpl/beast/clock/abstract_clock.h @@ -63,7 +63,7 @@ struct abstract_clock_wrapper : public abstract_clock using typename abstract_clock::duration; using typename abstract_clock::time_point; - time_point + [[nodiscard]] time_point now() const override { return Clock::now(); diff --git a/include/xrpl/beast/clock/manual_clock.h b/include/xrpl/beast/clock/manual_clock.h index b959a95b90b..3cabdc0ea87 100644 --- a/include/xrpl/beast/clock/manual_clock.h +++ b/include/xrpl/beast/clock/manual_clock.h @@ -32,7 +32,7 @@ class manual_clock : public abstract_clock { } - time_point + [[nodiscard]] time_point now() const override { return now_; diff --git a/include/xrpl/beast/container/detail/aged_container_iterator.h b/include/xrpl/beast/container/detail/aged_container_iterator.h index 3f12a5610a1..ffa251b7a63 100644 --- a/include/xrpl/beast/container/detail/aged_container_iterator.h +++ b/include/xrpl/beast/container/detail/aged_container_iterator.h @@ -115,7 +115,7 @@ class aged_container_iterator return &m_iter->value; } - time_point const& + [[nodiscard]] time_point const& when() const { return m_iter->when; @@ -136,7 +136,7 @@ class aged_container_iterator { } - Iterator const& + [[nodiscard]] Iterator const& iterator() const { return m_iter; diff --git a/include/xrpl/beast/container/detail/aged_ordered_container.h b/include/xrpl/beast/container/detail/aged_ordered_container.h index b20639aec40..83a2882746b 100644 --- a/include/xrpl/beast/container/detail/aged_ordered_container.h +++ b/include/xrpl/beast/container/detail/aged_ordered_container.h @@ -186,7 +186,7 @@ class aged_ordered_container return *this; } - Compare const& + [[nodiscard]] Compare const& compare() const { return *this; @@ -295,7 +295,7 @@ class aged_ordered_container return KeyValueCompare::compare(); } - Compare const& + [[nodiscard]] Compare const& compare() const { return KeyValueCompare::compare(); @@ -307,7 +307,7 @@ class aged_ordered_container return *this; } - KeyValueCompare const& + [[nodiscard]] KeyValueCompare const& key_compare() const { return *this; @@ -319,7 +319,7 @@ class aged_ordered_container return beast::detail::empty_base_optimization::member(); } - ElementAllocator const& + [[nodiscard]] ElementAllocator const& alloc() const { return beast::detail::empty_base_optimization::member(); diff --git a/include/xrpl/beast/container/detail/aged_unordered_container.h b/include/xrpl/beast/container/detail/aged_unordered_container.h index 15565bbadaf..7fe3a8b38af 100644 --- a/include/xrpl/beast/container/detail/aged_unordered_container.h +++ b/include/xrpl/beast/container/detail/aged_unordered_container.h @@ -149,7 +149,7 @@ class aged_unordered_container return *this; } - Hash const& + [[nodiscard]] Hash const& hash_function() const { return *this; @@ -195,7 +195,7 @@ class aged_unordered_container return *this; } - KeyEqual const& + [[nodiscard]] KeyEqual const& key_eq() const { return *this; @@ -348,7 +348,7 @@ class aged_unordered_container return *this; } - ValueHash const& + [[nodiscard]] ValueHash const& value_hash() const { return *this; @@ -360,7 +360,7 @@ class aged_unordered_container return ValueHash::hash_function(); } - Hash const& + [[nodiscard]] Hash const& hash_function() const { return ValueHash::hash_function(); @@ -372,7 +372,7 @@ class aged_unordered_container return *this; } - KeyValueEqual const& + [[nodiscard]] KeyValueEqual const& key_value_equal() const { return *this; @@ -384,7 +384,7 @@ class aged_unordered_container return key_value_equal().key_eq(); } - KeyEqual const& + [[nodiscard]] KeyEqual const& key_eq() const { return key_value_equal().key_eq(); @@ -396,7 +396,7 @@ class aged_unordered_container return beast::detail::empty_base_optimization::member(); } - ElementAllocator const& + [[nodiscard]] ElementAllocator const& alloc() const { return beast::detail::empty_base_optimization::member(); @@ -433,7 +433,7 @@ class aged_unordered_container m_vec.clear(); } - size_type + [[nodiscard]] size_type max_bucket_count() const { return m_vec.max_size(); @@ -445,7 +445,7 @@ class aged_unordered_container return m_max_load_factor; } - float const& + [[nodiscard]] float const& max_load_factor() const { return m_max_load_factor; diff --git a/include/xrpl/beast/container/detail/empty_base_optimization.h b/include/xrpl/beast/container/detail/empty_base_optimization.h index 337f3cf434f..230845102dc 100644 --- a/include/xrpl/beast/container/detail/empty_base_optimization.h +++ b/include/xrpl/beast/container/detail/empty_base_optimization.h @@ -43,7 +43,7 @@ class empty_base_optimization : private T return *this; } - T const& + [[nodiscard]] T const& member() const noexcept { return *this; diff --git a/include/xrpl/beast/core/List.h b/include/xrpl/beast/core/List.h index ab88eae738a..30a5166c626 100644 --- a/include/xrpl/beast/core/List.h +++ b/include/xrpl/beast/core/List.h @@ -128,7 +128,7 @@ class ListIterator } private: - reference + [[nodiscard]] reference dereference() const noexcept { return static_cast(*m_node); @@ -287,14 +287,14 @@ class List /** Determine if the list is empty. @return `true` if the list is empty. */ - bool + [[nodiscard]] bool empty() const noexcept { return size() == 0; } /** Returns the number of elements in the list. */ - size_type + [[nodiscard]] size_type size() const noexcept { return m_size; @@ -314,7 +314,7 @@ class List @invariant The list may not be empty. @return A const reference to the first element. */ - const_reference + [[nodiscard]] const_reference front() const noexcept { return element_from(m_head.m_next); @@ -334,7 +334,7 @@ class List @invariant The list may not be empty. @return A const reference to the last element. */ - const_reference + [[nodiscard]] const_reference back() const noexcept { return element_from(m_tail.m_prev); @@ -352,7 +352,7 @@ class List /** Obtain a const iterator to the beginning of the list. @return A const iterator pointing to the beginning of the list. */ - const_iterator + [[nodiscard]] const_iterator begin() const noexcept { return const_iterator(m_head.m_next); @@ -361,7 +361,7 @@ class List /** Obtain a const iterator to the beginning of the list. @return A const iterator pointing to the beginning of the list. */ - const_iterator + [[nodiscard]] const_iterator cbegin() const noexcept { return const_iterator(m_head.m_next); @@ -379,7 +379,7 @@ class List /** Obtain a const iterator to the end of the list. @return A constiterator pointing to the end of the list. */ - const_iterator + [[nodiscard]] const_iterator end() const noexcept { return const_iterator(&m_tail); @@ -388,7 +388,7 @@ class List /** Obtain a const iterator to the end of the list @return A constiterator pointing to the end of the list. */ - const_iterator + [[nodiscard]] const_iterator cend() const noexcept { return const_iterator(&m_tail); @@ -549,7 +549,7 @@ class List @param element The element to obtain an iterator for. @return A const iterator to the element. */ - const_iterator + [[nodiscard]] const_iterator const_iterator_to(T const& element) const noexcept { return const_iterator(static_cast(&element)); diff --git a/include/xrpl/beast/core/LockFreeStack.h b/include/xrpl/beast/core/LockFreeStack.h index 2c03e58f68f..03598915df1 100644 --- a/include/xrpl/beast/core/LockFreeStack.h +++ b/include/xrpl/beast/core/LockFreeStack.h @@ -162,7 +162,7 @@ class LockFreeStack operator=(LockFreeStack const&) = delete; /** Returns true if the stack is empty. */ - bool + [[nodiscard]] bool empty() const { return m_head.load() == &m_end; @@ -237,25 +237,25 @@ class LockFreeStack return iterator(&m_end); } - const_iterator + [[nodiscard]] const_iterator begin() const { return const_iterator(m_head.load()); } - const_iterator + [[nodiscard]] const_iterator end() const { return const_iterator(&m_end); } - const_iterator + [[nodiscard]] const_iterator cbegin() const { return const_iterator(m_head.load()); } - const_iterator + [[nodiscard]] const_iterator cend() const { return const_iterator(&m_end); diff --git a/include/xrpl/beast/core/SemanticVersion.h b/include/xrpl/beast/core/SemanticVersion.h index 244783234c9..826a43d3f82 100644 --- a/include/xrpl/beast/core/SemanticVersion.h +++ b/include/xrpl/beast/core/SemanticVersion.h @@ -37,15 +37,15 @@ class SemanticVersion parse(std::string_view input); /** Produce a string from semantic version components. */ - std::string + [[nodiscard]] std::string print() const; - bool + [[nodiscard]] bool isRelease() const noexcept { return preReleaseIdentifiers.empty(); } - bool + [[nodiscard]] bool isPreRelease() const noexcept { return !isRelease(); diff --git a/include/xrpl/beast/insight/Event.h b/include/xrpl/beast/insight/Event.h index ada488f134a..28994db956b 100644 --- a/include/xrpl/beast/insight/Event.h +++ b/include/xrpl/beast/insight/Event.h @@ -45,7 +45,7 @@ class Event final m_impl->notify(ceil(value)); } - std::shared_ptr const& + [[nodiscard]] std::shared_ptr const& impl() const { return m_impl; diff --git a/include/xrpl/beast/insight/Gauge.h b/include/xrpl/beast/insight/Gauge.h index b75060face3..8a7de33e2e6 100644 --- a/include/xrpl/beast/insight/Gauge.h +++ b/include/xrpl/beast/insight/Gauge.h @@ -108,7 +108,7 @@ class Gauge final } /** @} */ - std::shared_ptr const& + [[nodiscard]] std::shared_ptr const& impl() const { return m_impl; diff --git a/include/xrpl/beast/insight/Group.h b/include/xrpl/beast/insight/Group.h index 2b0d692f250..3e0eb934520 100644 --- a/include/xrpl/beast/insight/Group.h +++ b/include/xrpl/beast/insight/Group.h @@ -14,7 +14,7 @@ class Group : public Collector using ptr = std::shared_ptr; /** Returns the name of this group, for diagnostics. */ - virtual std::string const& + [[nodiscard]] virtual std::string const& name() const = 0; }; diff --git a/include/xrpl/beast/insight/Hook.h b/include/xrpl/beast/insight/Hook.h index d51a5d23009..d8734113902 100644 --- a/include/xrpl/beast/insight/Hook.h +++ b/include/xrpl/beast/insight/Hook.h @@ -24,7 +24,7 @@ class Hook final { } - std::shared_ptr const& + [[nodiscard]] std::shared_ptr const& impl() const { return m_impl; diff --git a/include/xrpl/beast/insight/Meter.h b/include/xrpl/beast/insight/Meter.h index 7685a0ec90e..93ae2379568 100644 --- a/include/xrpl/beast/insight/Meter.h +++ b/include/xrpl/beast/insight/Meter.h @@ -63,7 +63,7 @@ class Meter final } /** @} */ - std::shared_ptr const& + [[nodiscard]] std::shared_ptr const& impl() const { return m_impl; diff --git a/include/xrpl/beast/net/IPEndpoint.h b/include/xrpl/beast/net/IPEndpoint.h index 88f3d7669b1..15d86d75fec 100644 --- a/include/xrpl/beast/net/IPEndpoint.h +++ b/include/xrpl/beast/net/IPEndpoint.h @@ -32,25 +32,25 @@ class Endpoint from_string(std::string const& s); /** Returns a string representing the endpoint. */ - std::string + [[nodiscard]] std::string to_string() const; /** Returns the port number on the endpoint. */ - Port + [[nodiscard]] Port port() const { return m_port; } /** Returns a new Endpoint with a different port. */ - Endpoint + [[nodiscard]] Endpoint at_port(Port port) const { return Endpoint(m_addr, port); } /** Returns the address portion of this endpoint. */ - Address const& + [[nodiscard]] Address const& address() const { return m_addr; @@ -58,22 +58,22 @@ class Endpoint /** Convenience accessors for the address part. */ /** @{ */ - bool + [[nodiscard]] bool is_v4() const { return m_addr.is_v4(); } - bool + [[nodiscard]] bool is_v6() const { return m_addr.is_v6(); } - AddressV4 + [[nodiscard]] AddressV4 to_v4() const { return m_addr.to_v4(); } - AddressV6 + [[nodiscard]] AddressV6 to_v6() const { return m_addr.to_v6(); diff --git a/include/xrpl/beast/unit_test/detail/const_container.h b/include/xrpl/beast/unit_test/detail/const_container.h index 6a32c61b61c..a36423f0ef3 100644 --- a/include/xrpl/beast/unit_test/detail/const_container.h +++ b/include/xrpl/beast/unit_test/detail/const_container.h @@ -25,7 +25,7 @@ class const_container return m_cont; } - cont_type const& + [[nodiscard]] cont_type const& cont() const { return m_cont; @@ -39,14 +39,14 @@ class const_container using const_iterator = typename cont_type::const_iterator; /** Returns `true` if the container is empty. */ - bool + [[nodiscard]] bool empty() const { return m_cont.empty(); } /** Returns the number of items in the container. */ - size_type + [[nodiscard]] size_type size() const { return m_cont.size(); @@ -54,25 +54,25 @@ class const_container /** Returns forward iterators for traversal. */ /** @{ */ - const_iterator + [[nodiscard]] const_iterator begin() const { return m_cont.cbegin(); } - const_iterator + [[nodiscard]] const_iterator cbegin() const { return m_cont.cbegin(); } - const_iterator + [[nodiscard]] const_iterator end() const { return m_cont.cend(); } - const_iterator + [[nodiscard]] const_iterator cend() const { return m_cont.cend(); diff --git a/include/xrpl/beast/unit_test/recorder.h b/include/xrpl/beast/unit_test/recorder.h index f101d5318f0..55305a4b703 100644 --- a/include/xrpl/beast/unit_test/recorder.h +++ b/include/xrpl/beast/unit_test/recorder.h @@ -21,7 +21,7 @@ class recorder : public runner recorder() = default; /** Returns a report with the results of all completed suites. */ - results const& + [[nodiscard]] results const& report() const { return m_results; diff --git a/include/xrpl/beast/unit_test/results.h b/include/xrpl/beast/unit_test/results.h index 5607071729d..71c9aff47fc 100644 --- a/include/xrpl/beast/unit_test/results.h +++ b/include/xrpl/beast/unit_test/results.h @@ -41,14 +41,14 @@ class case_results tests_t() = default; /** Returns the total number of test conditions. */ - std::size_t + [[nodiscard]] std::size_t total() const { return cont().size(); } /** Returns the number of failed test conditions. */ - std::size_t + [[nodiscard]] std::size_t failed() const { return failed_; @@ -89,7 +89,7 @@ class case_results } /** Returns the name of this testcase. */ - std::string const& + [[nodiscard]] std::string const& name() const { return name_; @@ -118,21 +118,21 @@ class suite_results : public detail::const_container> } /** Returns the name of this suite. */ - std::string const& + [[nodiscard]] std::string const& name() const { return name_; } /** Returns the total number of test conditions. */ - std::size_t + [[nodiscard]] std::size_t total() const { return total_; } /** Returns the number of failures. */ - std::size_t + [[nodiscard]] std::size_t failed() const { return failed_; @@ -173,21 +173,21 @@ class results : public detail::const_container> results() = default; /** Returns the total number of test cases. */ - std::size_t + [[nodiscard]] std::size_t cases() const { return m_cases; } /** Returns the total number of test conditions. */ - std::size_t + [[nodiscard]] std::size_t total() const { return total_; } /** Returns the number of failures. */ - std::size_t + [[nodiscard]] std::size_t failed() const { return failed_; diff --git a/include/xrpl/beast/unit_test/runner.h b/include/xrpl/beast/unit_test/runner.h index 34433086759..2fdfbefa576 100644 --- a/include/xrpl/beast/unit_test/runner.h +++ b/include/xrpl/beast/unit_test/runner.h @@ -47,7 +47,7 @@ class runner } /** Returns the argument string. */ - std::string const& + [[nodiscard]] std::string const& arg() const { return arg_; diff --git a/include/xrpl/beast/unit_test/suite.h b/include/xrpl/beast/unit_test/suite.h index 1719c519cf7..a7b9d3bacb6 100644 --- a/include/xrpl/beast/unit_test/suite.h +++ b/include/xrpl/beast/unit_test/suite.h @@ -57,7 +57,7 @@ class suite // in the event of a failure, if the option to stop is set. struct abort_exception : public std::exception { - char const* + [[nodiscard]] char const* what() const noexcept override { return "test suite aborted"; diff --git a/include/xrpl/beast/unit_test/suite_info.h b/include/xrpl/beast/unit_test/suite_info.h index e7fa80b70ec..e814d518cbc 100644 --- a/include/xrpl/beast/unit_test/suite_info.h +++ b/include/xrpl/beast/unit_test/suite_info.h @@ -42,33 +42,33 @@ class suite_info { } - std::string const& + [[nodiscard]] std::string const& name() const { return name_; } - std::string const& + [[nodiscard]] std::string const& module() const { return module_; } - std::string const& + [[nodiscard]] std::string const& library() const { return library_; } /// Returns `true` if this suite only runs manually. - bool + [[nodiscard]] bool manual() const { return manual_; } /// Return the canonical suite name as a string. - std::string + [[nodiscard]] std::string full_name() const { return library_ + "." + module_ + "." + name_; diff --git a/include/xrpl/beast/unit_test/thread.h b/include/xrpl/beast/unit_test/thread.h index cc12380b0db..aa9ff3b0d96 100644 --- a/include/xrpl/beast/unit_test/thread.h +++ b/include/xrpl/beast/unit_test/thread.h @@ -47,13 +47,13 @@ class Thread t_ = std::thread(&Thread::run, this, std::move(b)); } - bool + [[nodiscard]] bool joinable() const { return t_.joinable(); } - std::thread::id + [[nodiscard]] std::thread::id get_id() const { return t_.get_id(); diff --git a/include/xrpl/beast/utility/Journal.h b/include/xrpl/beast/utility/Journal.h index 975169cf5fe..a056ce8d79b 100644 --- a/include/xrpl/beast/utility/Journal.h +++ b/include/xrpl/beast/utility/Journal.h @@ -66,12 +66,12 @@ class Journal operator=(Sink const& lhs) = delete; /** Returns `true` if text at the passed severity produces output. */ - virtual bool + [[nodiscard]] virtual bool active(Severity level) const; /** Returns `true` if a message is also written to the Output Window * (MSVC). */ - virtual bool + [[nodiscard]] virtual bool console() const; /** Set whether messages are also written to the Output Window (MSVC). @@ -80,7 +80,7 @@ class Journal console(bool output); /** Returns the minimum severity level this sink will report. */ - virtual Severity + [[nodiscard]] virtual Severity threshold() const; /** Set the minimum severity this sink will report. */ @@ -204,14 +204,14 @@ class Journal operator=(Stream const& other) = delete; /** Returns the Sink that this Stream writes to. */ - Sink& + [[nodiscard]] Sink& sink() const { return m_sink; } /** Returns the Severity level of messages this Stream reports. */ - Severity + [[nodiscard]] Severity level() const { return m_level; @@ -219,7 +219,7 @@ class Journal /** Returns `true` if sink logs anything at this stream's level. */ /** @{ */ - bool + [[nodiscard]] bool active() const { return m_sink.active(m_level); @@ -267,14 +267,14 @@ class Journal } /** Returns the Sink associated with this Journal. */ - Sink& + [[nodiscard]] Sink& sink() const { return *m_sink; } /** Returns a stream for this sink, with the specified severity level. */ - Stream + [[nodiscard]] Stream stream(Severity level) const { return Stream(*m_sink, level); @@ -284,7 +284,7 @@ class Journal For a message to be logged, the severity must be at or above the sink's severity threshold. */ - bool + [[nodiscard]] bool active(Severity level) const { return m_sink->active(level); @@ -292,37 +292,37 @@ class Journal /** Severity stream access functions. */ /** @{ */ - Stream + [[nodiscard]] Stream trace() const { return {*m_sink, severities::kTrace}; } - Stream + [[nodiscard]] Stream debug() const { return {*m_sink, severities::kDebug}; } - Stream + [[nodiscard]] Stream info() const { return {*m_sink, severities::kInfo}; } - Stream + [[nodiscard]] Stream warn() const { return {*m_sink, severities::kWarning}; } - Stream + [[nodiscard]] Stream error() const { return {*m_sink, severities::kError}; } - Stream + [[nodiscard]] Stream fatal() const { return {*m_sink, severities::kFatal}; diff --git a/include/xrpl/beast/utility/PropertyStream.h b/include/xrpl/beast/utility/PropertyStream.h index b2bd8c7a35a..39e354cc31a 100644 --- a/include/xrpl/beast/utility/PropertyStream.h +++ b/include/xrpl/beast/utility/PropertyStream.h @@ -149,7 +149,7 @@ class PropertyStream::Item : public List::Node { public: explicit Item(Source* source); - Source& + [[nodiscard]] Source& source() const; Source* operator->() const; @@ -217,7 +217,7 @@ class PropertyStream::Map PropertyStream& stream(); - PropertyStream const& + [[nodiscard]] PropertyStream const& stream() const; template @@ -287,7 +287,7 @@ class PropertyStream::Set PropertyStream& stream(); - PropertyStream const& + [[nodiscard]] PropertyStream const& stream() const; template @@ -323,7 +323,7 @@ class PropertyStream::Source operator=(Source const&) = delete; /** Returns the name of this source. */ - std::string const& + [[nodiscard]] std::string const& name() const; /** Add a child source. */ diff --git a/include/xrpl/beast/utility/WrappedSink.h b/include/xrpl/beast/utility/WrappedSink.h index 7e36ce99d76..57f0a02413a 100644 --- a/include/xrpl/beast/utility/WrappedSink.h +++ b/include/xrpl/beast/utility/WrappedSink.h @@ -35,13 +35,13 @@ class WrappedSink : public beast::Journal::Sink prefix_ = s; } - bool + [[nodiscard]] bool active(beast::severities::Severity level) const override { return sink_.active(level); } - bool + [[nodiscard]] bool console() const override { return sink_.console(); @@ -53,7 +53,7 @@ class WrappedSink : public beast::Journal::Sink sink_.console(output); } - beast::severities::Severity + [[nodiscard]] beast::severities::Severity threshold() const override { return sink_.threshold(); diff --git a/include/xrpl/beast/utility/temp_dir.h b/include/xrpl/beast/utility/temp_dir.h index 5aa7b28ac28..09e68c4e6b1 100644 --- a/include/xrpl/beast/utility/temp_dir.h +++ b/include/xrpl/beast/utility/temp_dir.h @@ -43,7 +43,7 @@ class temp_dir } /// Get the native path for the temporary directory - std::string + [[nodiscard]] std::string path() const { return path_.string(); @@ -53,7 +53,7 @@ class temp_dir The file does not need to exist. */ - std::string + [[nodiscard]] std::string file(std::string const& name) const { return (path_ / name).string(); diff --git a/include/xrpl/conditions/Fulfillment.h b/include/xrpl/conditions/Fulfillment.h index 71ff9d83ef6..cf28e29185a 100644 --- a/include/xrpl/conditions/Fulfillment.h +++ b/include/xrpl/conditions/Fulfillment.h @@ -41,15 +41,15 @@ struct Fulfillment with respect to other conditions of the same type. */ - virtual Buffer + [[nodiscard]] virtual Buffer fingerprint() const = 0; /** Returns the type of this condition. */ - virtual Type + [[nodiscard]] virtual Type type() const = 0; /** Validates a fulfillment. */ - virtual bool + [[nodiscard]] virtual bool validate(Slice data) const = 0; /** Calculates the cost associated with this fulfillment. * @@ -58,7 +58,7 @@ struct Fulfillment type and properties of the condition and the fulfillment that the condition is generated from. */ - virtual std::uint32_t + [[nodiscard]] virtual std::uint32_t cost() const = 0; /** Returns the condition associated with the given fulfillment. @@ -67,7 +67,7 @@ struct Fulfillment will, if compliant, produce the identical condition for the same fulfillment. */ - virtual Condition + [[nodiscard]] virtual Condition condition() const = 0; }; diff --git a/include/xrpl/conditions/detail/PreimageSha256.h b/include/xrpl/conditions/detail/PreimageSha256.h index bfa59ab749c..1e5e93eb890 100644 --- a/include/xrpl/conditions/detail/PreimageSha256.h +++ b/include/xrpl/conditions/detail/PreimageSha256.h @@ -90,13 +90,13 @@ class PreimageSha256 final : public Fulfillment { } - Type + [[nodiscard]] Type type() const override { return Type::preimageSha256; } - Buffer + [[nodiscard]] Buffer fingerprint() const override { sha256_hasher h; @@ -105,19 +105,19 @@ class PreimageSha256 final : public Fulfillment return {d.data(), d.size()}; } - std::uint32_t + [[nodiscard]] std::uint32_t cost() const override { return static_cast(payload_.size()); } - Condition + [[nodiscard]] Condition condition() const override { return {type(), cost(), fingerprint()}; } - bool + [[nodiscard]] bool validate(Slice) const override { // Perhaps counterintuitively, the message isn't diff --git a/include/xrpl/core/HashRouter.h b/include/xrpl/core/HashRouter.h index 3bc87f9524d..230fc06dbcf 100644 --- a/include/xrpl/core/HashRouter.h +++ b/include/xrpl/core/HashRouter.h @@ -118,7 +118,7 @@ class HashRouter peers_.insert(peer); } - HashRouterFlags + [[nodiscard]] HashRouterFlags getFlags(void) const { return flags_; @@ -138,7 +138,7 @@ class HashRouter } /** Return seated relay time point if the message has been relayed */ - std::optional + [[nodiscard]] std::optional relayed() const { return relayed_; diff --git a/include/xrpl/core/Job.h b/include/xrpl/core/Job.h index b01b4cd68b5..9954fc4ba4a 100644 --- a/include/xrpl/core/Job.h +++ b/include/xrpl/core/Job.h @@ -98,11 +98,11 @@ class Job : public CountedObject LoadMonitor& lm, std::function const& job); - JobType + [[nodiscard]] JobType getType() const; /** Returns the time when the job was queued. */ - clock_type::time_point const& + [[nodiscard]] clock_type::time_point const& queue_time() const; void diff --git a/include/xrpl/core/JobTypeData.h b/include/xrpl/core/JobTypeData.h index 917f838990f..20a85e04c1d 100644 --- a/include/xrpl/core/JobTypeData.h +++ b/include/xrpl/core/JobTypeData.h @@ -54,13 +54,13 @@ struct JobTypeData JobTypeData& operator=(JobTypeData const& other) = delete; - std::string + [[nodiscard]] std::string name() const { return info.name(); } - JobType + [[nodiscard]] JobType type() const { return info.type(); diff --git a/include/xrpl/core/JobTypeInfo.h b/include/xrpl/core/JobTypeInfo.h index 537656fa1da..81c4557be24 100644 --- a/include/xrpl/core/JobTypeInfo.h +++ b/include/xrpl/core/JobTypeInfo.h @@ -40,37 +40,37 @@ class JobTypeInfo { } - JobType + [[nodiscard]] JobType type() const { return m_type; } - std::string const& + [[nodiscard]] std::string const& name() const { return m_name; } - int + [[nodiscard]] int limit() const { return m_limit; } - bool + [[nodiscard]] bool special() const { return m_limit == 0; } - std::chrono::milliseconds + [[nodiscard]] std::chrono::milliseconds getAverageLatency() const { return m_avgLatency; } - std::chrono::milliseconds + [[nodiscard]] std::chrono::milliseconds getPeakLatency() const { return m_peakLatency; diff --git a/include/xrpl/core/JobTypes.h b/include/xrpl/core/JobTypes.h index 1fb6f615735..cc5b54fea7c 100644 --- a/include/xrpl/core/JobTypes.h +++ b/include/xrpl/core/JobTypes.h @@ -113,7 +113,7 @@ class JobTypes return instance().get(jt).name(); } - JobTypeInfo const& + [[nodiscard]] JobTypeInfo const& get(JobType jt) const { Map::const_iterator const iter(m_map.find(jt)); @@ -125,37 +125,37 @@ class JobTypes return m_unknown; } - JobTypeInfo const& + [[nodiscard]] JobTypeInfo const& getInvalid() const { return m_unknown; } - Map::size_type + [[nodiscard]] Map::size_type size() const { return m_map.size(); } - const_iterator + [[nodiscard]] const_iterator begin() const { return m_map.cbegin(); } - const_iterator + [[nodiscard]] const_iterator cbegin() const { return m_map.cbegin(); } - const_iterator + [[nodiscard]] const_iterator end() const { return m_map.cend(); } - const_iterator + [[nodiscard]] const_iterator cend() const { return m_map.cend(); diff --git a/include/xrpl/core/LoadEvent.h b/include/xrpl/core/LoadEvent.h index 87d4a5563dc..0536b257097 100644 --- a/include/xrpl/core/LoadEvent.h +++ b/include/xrpl/core/LoadEvent.h @@ -21,15 +21,15 @@ class LoadEvent ~LoadEvent(); - std::string const& + [[nodiscard]] std::string const& name() const; // The time spent waiting. - std::chrono::steady_clock::duration + [[nodiscard]] std::chrono::steady_clock::duration waitTime() const; // The time spent running. - std::chrono::steady_clock::duration + [[nodiscard]] std::chrono::steady_clock::duration runTime() const; void diff --git a/include/xrpl/core/NetworkIDService.h b/include/xrpl/core/NetworkIDService.h index d12fa420555..009f9ba6f88 100644 --- a/include/xrpl/core/NetworkIDService.h +++ b/include/xrpl/core/NetworkIDService.h @@ -26,7 +26,7 @@ class NetworkIDService * * @return The network ID this server is configured for */ - virtual std::uint32_t + [[nodiscard]] virtual std::uint32_t getNetworkID() const noexcept = 0; }; diff --git a/include/xrpl/core/PeerReservationTable.h b/include/xrpl/core/PeerReservationTable.h index 3fb85e392ff..0d107e879ca 100644 --- a/include/xrpl/core/PeerReservationTable.h +++ b/include/xrpl/core/PeerReservationTable.h @@ -22,7 +22,7 @@ struct PeerReservation final PublicKey nodeId; std::string description = {}; // NOLINT(readability-redundant-member-init) - auto + [[nodiscard]] auto toJson() const -> Json::Value; template diff --git a/include/xrpl/core/PerfLog.h b/include/xrpl/core/PerfLog.h index 8da6a313c8d..7151d09b083 100644 --- a/include/xrpl/core/PerfLog.h +++ b/include/xrpl/core/PerfLog.h @@ -121,7 +121,7 @@ class PerfLog * * @return Counters Json object */ - virtual Json::Value + [[nodiscard]] virtual Json::Value countersJson() const = 0; /** @@ -129,7 +129,7 @@ class PerfLog * * @return Current executing jobs and RPC calls and durations */ - virtual Json::Value + [[nodiscard]] virtual Json::Value currentJson() const = 0; /** diff --git a/include/xrpl/core/ServiceRegistry.h b/include/xrpl/core/ServiceRegistry.h index 8b7d4b44641..1d0c9e38f40 100644 --- a/include/xrpl/core/ServiceRegistry.h +++ b/include/xrpl/core/ServiceRegistry.h @@ -192,7 +192,7 @@ class ServiceRegistry virtual OpenLedger& getOpenLedger() = 0; - virtual OpenLedger const& + [[nodiscard]] virtual OpenLedger const& getOpenLedger() const = 0; // Transaction and operation services @@ -219,7 +219,7 @@ class ServiceRegistry getPerfLog() = 0; // Configuration and state - virtual bool + [[nodiscard]] virtual bool isStopping() const = 0; virtual beast::Journal @@ -231,7 +231,7 @@ class ServiceRegistry virtual Logs& getLogs() = 0; - virtual std::optional const& + [[nodiscard]] virtual std::optional const& getTrapTxID() const = 0; /** Retrieve the "wallet database" */ diff --git a/include/xrpl/core/detail/Workers.h b/include/xrpl/core/detail/Workers.h index bd82f9d57b2..fb9004a9b6d 100644 --- a/include/xrpl/core/detail/Workers.h +++ b/include/xrpl/core/detail/Workers.h @@ -106,7 +106,7 @@ class Workers @note This function is not thread-safe. */ - int + [[nodiscard]] int getNumberOfThreads() const noexcept; /** Set the desired number of threads. @@ -141,7 +141,7 @@ class Workers While this function is thread-safe, the value may not stay accurate for very long. It's mainly for diagnostic purposes. */ - int + [[nodiscard]] int numberOfCurrentlyRunningTasks() const noexcept; //-------------------------------------------------------------------------- diff --git a/include/xrpl/json/JsonPropertyStream.h b/include/xrpl/json/JsonPropertyStream.h index 510ed72950b..e0a13c40011 100644 --- a/include/xrpl/json/JsonPropertyStream.h +++ b/include/xrpl/json/JsonPropertyStream.h @@ -14,7 +14,7 @@ class JsonPropertyStream : public beast::PropertyStream public: JsonPropertyStream(); - Json::Value const& + [[nodiscard]] Json::Value const& top() const; protected: diff --git a/include/xrpl/json/json_reader.h b/include/xrpl/json/json_reader.h index dd1be76923f..d53569fb33a 100644 --- a/include/xrpl/json/json_reader.h +++ b/include/xrpl/json/json_reader.h @@ -64,7 +64,7 @@ class Reader * their location in the parsed document. An empty string is returned if no * error occurred during parsing. */ - std::string + [[nodiscard]] std::string getFormattedErrorMessages() const; static constexpr unsigned nest_limit{25}; diff --git a/include/xrpl/json/json_value.h b/include/xrpl/json/json_value.h index ef1d0fbcb8a..83b5142b279 100644 --- a/include/xrpl/json/json_value.h +++ b/include/xrpl/json/json_value.h @@ -53,7 +53,7 @@ class StaticString return str_; } - constexpr char const* + [[nodiscard]] constexpr char const* c_str() const { return str_; @@ -158,11 +158,11 @@ class Value operator<(CZString const& other) const; bool operator==(CZString const& other) const; - int + [[nodiscard]] int index() const; - char const* + [[nodiscard]] char const* c_str() const; - bool + [[nodiscard]] bool isStaticString() const; private: @@ -223,60 +223,60 @@ class Value void swap(Value& other) noexcept; - ValueType + [[nodiscard]] ValueType type() const; - char const* + [[nodiscard]] char const* asCString() const; /** Returns the unquoted string value. */ - std::string + [[nodiscard]] std::string asString() const; - Int + [[nodiscard]] Int asInt() const; - UInt + [[nodiscard]] UInt asUInt() const; - double + [[nodiscard]] double asDouble() const; - bool + [[nodiscard]] bool asBool() const; /** Correct absolute value from int or unsigned int */ - UInt + [[nodiscard]] UInt asAbsUInt() const; // TODO: What is the "empty()" method this docstring mentions? /** isNull() tests to see if this field is null. Don't use this method to test for emptiness: use empty(). */ - bool + [[nodiscard]] bool isNull() const; - bool + [[nodiscard]] bool isBool() const; - bool + [[nodiscard]] bool isInt() const; - bool + [[nodiscard]] bool isUInt() const; - bool + [[nodiscard]] bool isIntegral() const; - bool + [[nodiscard]] bool isDouble() const; - bool + [[nodiscard]] bool isNumeric() const; - bool + [[nodiscard]] bool isString() const; - bool + [[nodiscard]] bool isArray() const; - bool + [[nodiscard]] bool isArrayOrNull() const; - bool + [[nodiscard]] bool isObject() const; - bool + [[nodiscard]] bool isObjectOrNull() const; - bool + [[nodiscard]] bool isConvertibleTo(ValueType other) const; /// Number of values in array or object - UInt + [[nodiscard]] UInt size() const; /** Returns false if this is an empty array, empty object, empty string, @@ -304,10 +304,10 @@ class Value operator[](UInt index) const; /// If the array contains at least index+1 elements, returns the element /// value, otherwise returns defaultValue. - Value + [[nodiscard]] Value get(UInt index, Value const& defaultValue) const; /// Return true if index < size(). - bool + [[nodiscard]] bool isValidIndex(UInt index) const; /// \brief Append value to array at the end. /// @@ -355,7 +355,7 @@ class Value Value get(char const* key, Value const& defaultValue) const; /// Return the member named key if it exist, defaultValue otherwise. - Value + [[nodiscard]] Value get(std::string const& key, Value const& defaultValue) const; /// \brief Remove and return the named member. @@ -374,10 +374,10 @@ class Value bool isMember(char const* key) const; /// Return true if the object has a member named key. - bool + [[nodiscard]] bool isMember(std::string const& key) const; /// Return true if the object has a member named key. - bool + [[nodiscard]] bool isMember(StaticString const& key) const; /// \brief Return a list of the member names. @@ -385,15 +385,15 @@ class Value /// If null, return an empty list. /// \pre type() is objectValue or nullValue /// \post if type() was nullValue, it remains nullValue - Members + [[nodiscard]] Members getMemberNames() const; - std::string + [[nodiscard]] std::string toStyledString() const; - const_iterator + [[nodiscard]] const_iterator begin() const; - const_iterator + [[nodiscard]] const_iterator end() const; iterator @@ -513,20 +513,20 @@ class ValueIteratorBase /// Return either the index or the member name of the referenced value as a /// Value. - Value + [[nodiscard]] Value key() const; /// Return the index of the referenced Value. -1 if it is not an arrayValue. - UInt + [[nodiscard]] UInt index() const; /// Return the member name of the referenced Value. "" if it is not an /// objectValue. - char const* + [[nodiscard]] char const* memberName() const; protected: - Value& + [[nodiscard]] Value& deref() const; void @@ -535,10 +535,10 @@ class ValueIteratorBase void decrement(); - difference_type + [[nodiscard]] difference_type computeDistance(SelfType const& other) const; - bool + [[nodiscard]] bool isEqual(SelfType const& other) const; void diff --git a/include/xrpl/ledger/AcceptedLedgerTx.h b/include/xrpl/ledger/AcceptedLedgerTx.h index d07016b860f..5d6d471ba01 100644 --- a/include/xrpl/ledger/AcceptedLedgerTx.h +++ b/include/xrpl/ledger/AcceptedLedgerTx.h @@ -30,47 +30,47 @@ class AcceptedLedgerTx : public CountedObject std::shared_ptr const&, std::shared_ptr const&); - std::shared_ptr const& + [[nodiscard]] std::shared_ptr const& getTxn() const { return mTxn; } - TxMeta const& + [[nodiscard]] TxMeta const& getMeta() const { return mMeta; } - boost::container::flat_set const& + [[nodiscard]] boost::container::flat_set const& getAffected() const { return mAffected; } - TxID + [[nodiscard]] TxID getTransactionID() const { return mTxn->getTransactionID(); } - TxType + [[nodiscard]] TxType getTxnType() const { return mTxn->getTxnType(); } - TER + [[nodiscard]] TER getResult() const { return mMeta.getResultTER(); } - std::uint32_t + [[nodiscard]] std::uint32_t getTxnSeq() const { return mMeta.getIndex(); } - std::string + [[nodiscard]] std::string getEscMeta() const; - Json::Value const& + [[nodiscard]] Json::Value const& getJson() const { return mJson; diff --git a/include/xrpl/ledger/AmendmentTable.h b/include/xrpl/ledger/AmendmentTable.h index 8df09f74c36..8f40ccb4132 100644 --- a/include/xrpl/ledger/AmendmentTable.h +++ b/include/xrpl/ledger/AmendmentTable.h @@ -36,7 +36,7 @@ class AmendmentTable virtual ~AmendmentTable() = default; - virtual uint256 + [[nodiscard]] virtual uint256 find(std::string const& name) const = 0; virtual bool @@ -47,9 +47,9 @@ class AmendmentTable virtual bool enable(uint256 const& amendment) = 0; - virtual bool + [[nodiscard]] virtual bool isEnabled(uint256 const& amendment) const = 0; - virtual bool + [[nodiscard]] virtual bool isSupported(uint256 const& amendment) const = 0; /** @@ -58,17 +58,17 @@ class AmendmentTable * * @return true if an unsupported feature is enabled on the network */ - virtual bool + [[nodiscard]] virtual bool hasUnsupportedEnabled() const = 0; - virtual std::optional + [[nodiscard]] virtual std::optional firstUnsupportedExpected() const = 0; - virtual Json::Value + [[nodiscard]] virtual Json::Value getJson(bool isAdmin) const = 0; /** Returns a Json::objectValue. */ - virtual Json::Value + [[nodiscard]] virtual Json::Value getJson(uint256 const& amendment, bool isAdmin) const = 0; /** Called when a new fully-validated ledger is accepted. */ @@ -87,7 +87,7 @@ class AmendmentTable /** Called to determine whether the amendment logic needs to process a new validated ledger. (If it could have changed things.) */ - virtual bool + [[nodiscard]] virtual bool needValidatedLedger(LedgerIndex seq) const = 0; virtual void @@ -112,14 +112,14 @@ class AmendmentTable // Called by the consensus code when we need to // add feature entries to a validation - virtual std::vector + [[nodiscard]] virtual std::vector doValidation(std::set const& enabled) const = 0; // The set of amendments to enable in the genesis ledger // This will return all known, non-vetoed amendments. // If we ever have two amendments that should not both be // enabled at the same time, we should ensure one is vetoed. - virtual std::vector + [[nodiscard]] virtual std::vector getDesired() const = 0; // The function below adapts the API callers expect to the diff --git a/include/xrpl/ledger/ApplyView.h b/include/xrpl/ledger/ApplyView.h index 73161453dba..bd38b57a58a 100644 --- a/include/xrpl/ledger/ApplyView.h +++ b/include/xrpl/ledger/ApplyView.h @@ -134,7 +134,7 @@ class ApplyView : public ReadView while transactions applied to the consensus ledger produce hard failures (and claim a fee). */ - virtual ApplyFlags + [[nodiscard]] virtual ApplyFlags flags() const = 0; /** Prepare to modify the SLE associated with key. diff --git a/include/xrpl/ledger/BookDirs.h b/include/xrpl/ledger/BookDirs.h index eb1cbcbfa79..4cbbbd78ce9 100644 --- a/include/xrpl/ledger/BookDirs.h +++ b/include/xrpl/ledger/BookDirs.h @@ -22,10 +22,10 @@ class BookDirs BookDirs(ReadView const&, Book const&); - const_iterator + [[nodiscard]] const_iterator begin() const; - const_iterator + [[nodiscard]] const_iterator end() const; }; diff --git a/include/xrpl/ledger/CanonicalTXSet.h b/include/xrpl/ledger/CanonicalTXSet.h index 857b82a734b..8653816eee3 100644 --- a/include/xrpl/ledger/CanonicalTXSet.h +++ b/include/xrpl/ledger/CanonicalTXSet.h @@ -59,13 +59,13 @@ class CanonicalTXSet : public CountedObject return !(lhs == rhs); } - uint256 const& + [[nodiscard]] uint256 const& getAccount() const { return account_; } - uint256 const& + [[nodiscard]] uint256 const& getTXID() const { return txId_; @@ -118,30 +118,30 @@ class CanonicalTXSet : public CountedObject return map_.erase(it); } - const_iterator + [[nodiscard]] const_iterator begin() const { return map_.begin(); } - const_iterator + [[nodiscard]] const_iterator end() const { return map_.end(); } - size_t + [[nodiscard]] size_t size() const { return map_.size(); } - bool + [[nodiscard]] bool empty() const { return map_.empty(); } - uint256 const& + [[nodiscard]] uint256 const& key() const { return salt_; diff --git a/include/xrpl/ledger/Dir.h b/include/xrpl/ledger/Dir.h index 0c2f1e37658..940107bf93c 100644 --- a/include/xrpl/ledger/Dir.h +++ b/include/xrpl/ledger/Dir.h @@ -31,10 +31,10 @@ class Dir Dir(ReadView const&, Keylet const&); - const_iterator + [[nodiscard]] const_iterator begin() const; - const_iterator + [[nodiscard]] const_iterator end() const; }; diff --git a/include/xrpl/ledger/PaymentSandbox.h b/include/xrpl/ledger/PaymentSandbox.h index 0c4e4bcd41f..1cd89d93886 100644 --- a/include/xrpl/ledger/PaymentSandbox.h +++ b/include/xrpl/ledger/PaymentSandbox.h @@ -74,10 +74,10 @@ class DeferredCredits // Get the adjustments for the balance between main and other. // Returns the debits, credits and the original balance - std::optional + [[nodiscard]] std::optional adjustmentsIOU(AccountID const& main, AccountID const& other, Currency const& currency) const; - std::optional + [[nodiscard]] std::optional adjustmentsMPT(MPTID const& mptID) const; void @@ -104,7 +104,7 @@ class DeferredCredits // Get the adjusted owner count. Since DeferredCredits is meant to be used // in payments, and payments only decrease owner counts, return the max // remembered owner count. - std::optional + [[nodiscard]] std::optional ownerCount(AccountID const& id) const; void @@ -179,15 +179,15 @@ class PaymentSandbox final : public detail::ApplyViewBase } /** @} */ - STAmount + [[nodiscard]] STAmount balanceHookIOU(AccountID const& account, AccountID const& issuer, STAmount const& amount) const override; - STAmount + [[nodiscard]] STAmount balanceHookMPT(AccountID const& account, MPTIssue const& issue, std::int64_t amount) const override; - STAmount + [[nodiscard]] STAmount balanceHookSelfIssueMPT(MPTIssue const& issue, std::int64_t amount) const override; void @@ -212,7 +212,7 @@ class PaymentSandbox final : public detail::ApplyViewBase void adjustOwnerCountHook(AccountID const& account, std::uint32_t cur, std::uint32_t next) override; - std::uint32_t + [[nodiscard]] std::uint32_t ownerCountHook(AccountID const& account, std::uint32_t count) const override; /** Apply changes to base view. @@ -229,7 +229,7 @@ class PaymentSandbox final : public detail::ApplyViewBase apply(PaymentSandbox& to); /** @} */ - XRPAmount + [[nodiscard]] XRPAmount xrpDestroyed() const; private: diff --git a/include/xrpl/ledger/ReadView.h b/include/xrpl/ledger/ReadView.h index debf01e85f3..bb0aa56507c 100644 --- a/include/xrpl/ledger/ReadView.h +++ b/include/xrpl/ledger/ReadView.h @@ -39,22 +39,22 @@ class ReadView struct sles_type : detail::ReadViewFwdRange> { explicit sles_type(ReadView const& view); - iterator + [[nodiscard]] iterator begin() const; - iterator + [[nodiscard]] iterator end() const; - iterator + [[nodiscard]] iterator upper_bound(key_type const& key) const; }; struct txs_type : detail::ReadViewFwdRange { explicit txs_type(ReadView const& view); - bool + [[nodiscard]] bool empty() const; - iterator + [[nodiscard]] iterator begin() const; - iterator + [[nodiscard]] iterator end() const; }; @@ -78,33 +78,33 @@ class ReadView } /** Returns information about the ledger. */ - virtual LedgerHeader const& + [[nodiscard]] virtual LedgerHeader const& header() const = 0; /** Returns true if this reflects an open ledger. */ - virtual bool + [[nodiscard]] virtual bool open() const = 0; /** Returns the close time of the previous ledger. */ - NetClock::time_point + [[nodiscard]] NetClock::time_point parentCloseTime() const { return header().parentCloseTime; } /** Returns the sequence number of the base ledger. */ - LedgerIndex + [[nodiscard]] LedgerIndex seq() const { return header().seq; } /** Returns the fees for the base ledger. */ - virtual Fees const& + [[nodiscard]] virtual Fees const& fees() const = 0; /** Returns the tx processing rules. */ - virtual Rules const& + [[nodiscard]] virtual Rules const& rules() const = 0; /** Determine if a state item exists. @@ -114,7 +114,7 @@ class ReadView @return `true` if a SLE is associated with the specified key. */ - virtual bool + [[nodiscard]] virtual bool exists(Keylet const& k) const = 0; /** Return the key of the next state item. @@ -127,7 +127,7 @@ class ReadView the key returned would be outside the open interval (key, last). */ - virtual std::optional + [[nodiscard]] virtual std::optional succ(key_type const& key, std::optional const& last = std::nullopt) const = 0; /** Return the state item associated with a key. @@ -143,7 +143,7 @@ class ReadView @return `nullptr` if the key is not present or if the type does not match. */ - virtual std::shared_ptr + [[nodiscard]] virtual std::shared_ptr read(Keylet const& k) const = 0; // Accounts in a payment are not allowed to use assets acquired during that @@ -151,7 +151,7 @@ class ReadView // changes that accounts make during a payment. `balanceHookIOU` adjusts // balances so newly acquired assets are not counted toward the balance. // This is required to support PaymentSandbox. - virtual STAmount + [[nodiscard]] virtual STAmount balanceHookIOU(AccountID const& account, AccountID const& issuer, STAmount const& amount) const { XRPL_ASSERT(amount.holds(), "balanceHookIOU: amount is for Issue"); @@ -161,7 +161,7 @@ class ReadView // balanceHookMPT adjusts balances so newly acquired assets are not counted // toward the balance. - virtual STAmount + [[nodiscard]] virtual STAmount balanceHookMPT(AccountID const& account, MPTIssue const& issue, std::int64_t amount) const { return STAmount{issue, amount}; @@ -171,7 +171,7 @@ class ReadView // funds available to issue, which are originally available funds less // already self sold MPT amounts (MPT sell offer). This hook is used // by issuerFundsToSelfIssue() function. - virtual STAmount + [[nodiscard]] virtual STAmount balanceHookSelfIssueMPT(MPTIssue const& issue, std::int64_t amount) const { return STAmount{issue, amount}; @@ -182,30 +182,30 @@ class ReadView // changes that accounts make during a payment. `ownerCountHook` adjusts the // ownerCount so it returns the max value of the ownerCount so far. // This is required to support PaymentSandbox. - virtual std::uint32_t + [[nodiscard]] virtual std::uint32_t ownerCountHook(AccountID const& account, std::uint32_t count) const { return count; } // used by the implementation - virtual std::unique_ptr + [[nodiscard]] virtual std::unique_ptr slesBegin() const = 0; // used by the implementation - virtual std::unique_ptr + [[nodiscard]] virtual std::unique_ptr slesEnd() const = 0; // used by the implementation - virtual std::unique_ptr + [[nodiscard]] virtual std::unique_ptr slesUpperBound(key_type const& key) const = 0; // used by the implementation - virtual std::unique_ptr + [[nodiscard]] virtual std::unique_ptr txsBegin() const = 0; // used by the implementation - virtual std::unique_ptr + [[nodiscard]] virtual std::unique_ptr txsEnd() const = 0; /** Returns `true` if a tx exists in the tx map. @@ -213,7 +213,7 @@ class ReadView A tx exists in the map if it is part of the base ledger, or if it is a newly inserted tx. */ - virtual bool + [[nodiscard]] virtual bool txExists(key_type const& key) const = 0; /** Read a transaction from the tx map. @@ -224,7 +224,7 @@ class ReadView @return A pair of nullptr if the key is not found in the tx map. */ - virtual tx_type + [[nodiscard]] virtual tx_type txRead(key_type const& key) const = 0; // @@ -257,7 +257,7 @@ class DigestAwareReadView : public ReadView @return std::nullopt if the item does not exist. */ - virtual std::optional + [[nodiscard]] virtual std::optional digest(key_type const& key) const = 0; }; diff --git a/include/xrpl/ledger/detail/ApplyStateTable.h b/include/xrpl/ledger/detail/ApplyStateTable.h index 0ded0aa2731..93b639f54b2 100644 --- a/include/xrpl/ledger/detail/ApplyStateTable.h +++ b/include/xrpl/ledger/detail/ApplyStateTable.h @@ -54,19 +54,19 @@ class ApplyStateTable bool isDryRun, beast::Journal j); - bool + [[nodiscard]] bool exists(ReadView const& base, Keylet const& k) const; - std::optional + [[nodiscard]] std::optional succ(ReadView const& base, key_type const& key, std::optional const& last) const; - std::shared_ptr + [[nodiscard]] std::shared_ptr read(ReadView const& base, Keylet const& k) const; std::shared_ptr peek(ReadView const& base, Keylet const& k); - std::size_t + [[nodiscard]] std::size_t size() const; void @@ -97,7 +97,7 @@ class ApplyStateTable destroyXRP(XRPAmount const& fee); // For debugging - XRPAmount const& + [[nodiscard]] XRPAmount const& dropsDestroyed() const { return dropsDestroyed_; diff --git a/include/xrpl/ledger/detail/ApplyViewBase.h b/include/xrpl/ledger/detail/ApplyViewBase.h index 0e93ac5d2f3..d6a293610ad 100644 --- a/include/xrpl/ledger/detail/ApplyViewBase.h +++ b/include/xrpl/ledger/detail/ApplyViewBase.h @@ -22,51 +22,51 @@ class ApplyViewBase : public ApplyView, public RawView ApplyViewBase(ReadView const* base, ApplyFlags flags); // ReadView - bool + [[nodiscard]] bool open() const override; - LedgerHeader const& + [[nodiscard]] LedgerHeader const& header() const override; - Fees const& + [[nodiscard]] Fees const& fees() const override; - Rules const& + [[nodiscard]] Rules const& rules() const override; - bool + [[nodiscard]] bool exists(Keylet const& k) const override; - std::optional + [[nodiscard]] std::optional succ(key_type const& key, std::optional const& last = std::nullopt) const override; - std::shared_ptr + [[nodiscard]] std::shared_ptr read(Keylet const& k) const override; - std::unique_ptr + [[nodiscard]] std::unique_ptr slesBegin() const override; - std::unique_ptr + [[nodiscard]] std::unique_ptr slesEnd() const override; - std::unique_ptr + [[nodiscard]] std::unique_ptr slesUpperBound(uint256 const& key) const override; - std::unique_ptr + [[nodiscard]] std::unique_ptr txsBegin() const override; - std::unique_ptr + [[nodiscard]] std::unique_ptr txsEnd() const override; - bool + [[nodiscard]] bool txExists(key_type const& key) const override; - tx_type + [[nodiscard]] tx_type txRead(key_type const& key) const override; // ApplyView - ApplyFlags + [[nodiscard]] ApplyFlags flags() const override; std::shared_ptr diff --git a/include/xrpl/ledger/detail/RawStateTable.h b/include/xrpl/ledger/detail/RawStateTable.h index b3307b3ea4e..ec5cb059814 100644 --- a/include/xrpl/ledger/detail/RawStateTable.h +++ b/include/xrpl/ledger/detail/RawStateTable.h @@ -42,10 +42,10 @@ class RawStateTable void apply(RawView& to) const; - bool + [[nodiscard]] bool exists(ReadView const& base, Keylet const& k) const; - std::optional + [[nodiscard]] std::optional succ(ReadView const& base, key_type const& key, std::optional const& last) const; void @@ -57,19 +57,19 @@ class RawStateTable void replace(std::shared_ptr const& sle); - std::shared_ptr + [[nodiscard]] std::shared_ptr read(ReadView const& base, Keylet const& k) const; void destroyXRP(XRPAmount const& fee); - std::unique_ptr + [[nodiscard]] std::unique_ptr slesBegin(ReadView const& base) const; - std::unique_ptr + [[nodiscard]] std::unique_ptr slesEnd(ReadView const& base) const; - std::unique_ptr + [[nodiscard]] std::unique_ptr slesUpperBound(ReadView const& base, uint256 const& key) const; private: diff --git a/include/xrpl/ledger/detail/ReadViewFwdRange.h b/include/xrpl/ledger/detail/ReadViewFwdRange.h index 26ed22f11db..74fe0447dce 100644 --- a/include/xrpl/ledger/detail/ReadViewFwdRange.h +++ b/include/xrpl/ledger/detail/ReadViewFwdRange.h @@ -27,16 +27,16 @@ class ReadViewFwdIter virtual ~ReadViewFwdIter() = default; - virtual std::unique_ptr + [[nodiscard]] virtual std::unique_ptr copy() const = 0; - virtual bool + [[nodiscard]] virtual bool equal(ReadViewFwdIter const& impl) const = 0; virtual void increment() = 0; - virtual value_type + [[nodiscard]] virtual value_type dereference() const = 0; }; diff --git a/include/xrpl/ledger/helpers/LendingHelpers.h b/include/xrpl/ledger/helpers/LendingHelpers.h index 81d14477ef1..23b87de654e 100644 --- a/include/xrpl/ledger/helpers/LendingHelpers.h +++ b/include/xrpl/ledger/helpers/LendingHelpers.h @@ -104,7 +104,7 @@ struct LoanState Number managementFeeDue; // Interest still due to be paid by the borrower. - Number + [[nodiscard]] Number interestOutstanding() const { XRPL_ASSERT_PARTS( @@ -266,7 +266,7 @@ struct PaymentComponents // // @return The amount of tracked interest included in this payment that // will be paid to the vault. - Number + [[nodiscard]] Number trackedInterestPart() const; }; @@ -340,7 +340,7 @@ struct LoanStateDeltas /* Calculates the total change across all components. * @return The sum of principal, interest, and management fee deltas. */ - Number + [[nodiscard]] Number total() const { return principal + interest + managementFee; diff --git a/include/xrpl/net/AutoSocket.h b/include/xrpl/net/AutoSocket.h index 45e4919b8ad..4dc20ffc5cb 100644 --- a/include/xrpl/net/AutoSocket.h +++ b/include/xrpl/net/AutoSocket.h @@ -43,7 +43,7 @@ class AutoSocket { } - bool + [[nodiscard]] bool isSecure() const { return mSecure; diff --git a/include/xrpl/net/HTTPClientSSLContext.h b/include/xrpl/net/HTTPClientSSLContext.h index d211b21afe6..060746b7d8a 100644 --- a/include/xrpl/net/HTTPClientSSLContext.h +++ b/include/xrpl/net/HTTPClientSSLContext.h @@ -58,7 +58,7 @@ class HTTPClientSSLContext return ssl_context_; } - bool + [[nodiscard]] bool sslVerify() const { return verify_; diff --git a/include/xrpl/nodestore/Backend.h b/include/xrpl/nodestore/Backend.h index d1b0ecb6dd9..7f9dd172cc1 100644 --- a/include/xrpl/nodestore/Backend.h +++ b/include/xrpl/nodestore/Backend.h @@ -34,7 +34,7 @@ class Backend /** Get the block size for backends that support it */ - virtual std::optional + [[nodiscard]] virtual std::optional getBlockSize() const { return std::nullopt; @@ -135,7 +135,7 @@ class Backend } /** Returns the number of file descriptors the backend expects to need. */ - virtual int + [[nodiscard]] virtual int fdRequired() const = 0; }; diff --git a/include/xrpl/nodestore/Factory.h b/include/xrpl/nodestore/Factory.h index 1656e73840c..c40be62d211 100644 --- a/include/xrpl/nodestore/Factory.h +++ b/include/xrpl/nodestore/Factory.h @@ -16,7 +16,7 @@ class Factory virtual ~Factory() = default; /** Retrieve the name of this factory. */ - virtual std::string + [[nodiscard]] virtual std::string getName() const = 0; /** Create an instance of this factory's backend. diff --git a/include/xrpl/nodestore/NodeObject.h b/include/xrpl/nodestore/NodeObject.h index 2274fc8c386..6397ea2e4ec 100644 --- a/include/xrpl/nodestore/NodeObject.h +++ b/include/xrpl/nodestore/NodeObject.h @@ -59,15 +59,15 @@ class NodeObject : public CountedObject createObject(NodeObjectType type, Blob&& data, uint256 const& hash); /** Returns the type of this object. */ - NodeObjectType + [[nodiscard]] NodeObjectType getType() const; /** Returns the hash of the data. */ - uint256 const& + [[nodiscard]] uint256 const& getHash() const; /** Returns the underlying data. */ - Blob const& + [[nodiscard]] Blob const& getData() const; private: diff --git a/include/xrpl/nodestore/detail/DecodedBlob.h b/include/xrpl/nodestore/detail/DecodedBlob.h index 052c1430097..8c75e58d484 100644 --- a/include/xrpl/nodestore/detail/DecodedBlob.h +++ b/include/xrpl/nodestore/detail/DecodedBlob.h @@ -21,7 +21,7 @@ class DecodedBlob DecodedBlob(void const* key, void const* value, int valueBytes); /** Determine if the decoding was successful. */ - bool + [[nodiscard]] bool wasOk() const noexcept { return m_success; diff --git a/include/xrpl/protocol/Asset.h b/include/xrpl/protocol/Asset.h index b1f0338665b..920e62f2c45 100644 --- a/include/xrpl/protocol/Asset.h +++ b/include/xrpl/protocol/Asset.h @@ -68,7 +68,7 @@ class Asset { } - AccountID const& + [[nodiscard]] AccountID const& getIssuer() const; template @@ -80,16 +80,16 @@ class Asset get(); template - constexpr bool + [[nodiscard]] constexpr bool holds() const; - std::string + [[nodiscard]] std::string getText() const; - constexpr value_type const& + [[nodiscard]] constexpr value_type const& value() const; - constexpr token_type + [[nodiscard]] constexpr token_type token() const; void @@ -98,7 +98,7 @@ class Asset STAmount operator()(Number const&) const; - constexpr AmtType + [[nodiscard]] constexpr AmtType getAmountType() const; // Custom, generic visit implementation @@ -111,7 +111,7 @@ class Asset return detail::visit(issue_, std::forward(visitors)...); } - constexpr bool + [[nodiscard]] constexpr bool native() const { return visit( @@ -119,7 +119,7 @@ class Asset [&](MPTIssue const&) { return false; }); } - bool + [[nodiscard]] bool integral() const { return visit( @@ -169,7 +169,7 @@ Asset::holds() const } template -constexpr TIss const& +[[nodiscard]] constexpr TIss const& Asset::get() const { if (!std::holds_alternative(issue_)) diff --git a/include/xrpl/protocol/Fees.h b/include/xrpl/protocol/Fees.h index ddf4acbf67f..6c398735ad0 100644 --- a/include/xrpl/protocol/Fees.h +++ b/include/xrpl/protocol/Fees.h @@ -39,7 +39,7 @@ struct Fees The reserve is calculated as the reserve base plus the reserve increment times the number of increments. */ - XRPAmount + [[nodiscard]] XRPAmount accountReserve(std::size_t ownerCount) const { return reserve + ownerCount * increment; diff --git a/include/xrpl/protocol/IOUAmount.h b/include/xrpl/protocol/IOUAmount.h index 1744345a1b9..1654a357f16 100644 --- a/include/xrpl/protocol/IOUAmount.h +++ b/include/xrpl/protocol/IOUAmount.h @@ -71,13 +71,13 @@ class IOUAmount : private boost::totally_ordered, private boost::addi operator bool() const noexcept; /** Return the sign of the amount */ - int + [[nodiscard]] int signum() const noexcept; - exponent_type + [[nodiscard]] exponent_type exponent() const noexcept; - mantissa_type + [[nodiscard]] mantissa_type mantissa() const noexcept; static IOUAmount diff --git a/include/xrpl/protocol/InnerObjectFormats.h b/include/xrpl/protocol/InnerObjectFormats.h index a00e6e120b4..9d07a21d1c5 100644 --- a/include/xrpl/protocol/InnerObjectFormats.h +++ b/include/xrpl/protocol/InnerObjectFormats.h @@ -18,7 +18,7 @@ class InnerObjectFormats : public KnownFormats static InnerObjectFormats const& getInstance(); - SOTemplate const* + [[nodiscard]] SOTemplate const* findSOTemplateBySField(SField const& sField) const; }; diff --git a/include/xrpl/protocol/Issue.h b/include/xrpl/protocol/Issue.h index 569b01725de..fa9c4ebd1fd 100644 --- a/include/xrpl/protocol/Issue.h +++ b/include/xrpl/protocol/Issue.h @@ -21,22 +21,22 @@ class Issue { } - AccountID const& + [[nodiscard]] AccountID const& getIssuer() const { return account; } - std::string + [[nodiscard]] std::string getText() const; void setJson(Json::Value& jv) const; - bool + [[nodiscard]] bool native() const; - bool + [[nodiscard]] bool integral() const; friend constexpr std::weak_ordering diff --git a/include/xrpl/protocol/Keylet.h b/include/xrpl/protocol/Keylet.h index 2931486ac08..6795516795c 100644 --- a/include/xrpl/protocol/Keylet.h +++ b/include/xrpl/protocol/Keylet.h @@ -25,7 +25,7 @@ struct Keylet } /** Returns true if the SLE matches the type */ - bool + [[nodiscard]] bool check(STLedgerEntry const&) const; }; diff --git a/include/xrpl/protocol/KnownFormats.h b/include/xrpl/protocol/KnownFormats.h index 73bc463abe4..12d900572fc 100644 --- a/include/xrpl/protocol/KnownFormats.h +++ b/include/xrpl/protocol/KnownFormats.h @@ -44,7 +44,7 @@ class KnownFormats /** Retrieve the name of the format. */ - std::string const& + [[nodiscard]] std::string const& getName() const { return name_; @@ -52,13 +52,13 @@ class KnownFormats /** Retrieve the transaction type this format represents. */ - KeyType + [[nodiscard]] KeyType getType() const { return type_; } - SOTemplate const& + [[nodiscard]] SOTemplate const& getSOTemplate() const { return soTemplate_; @@ -96,7 +96,7 @@ class KnownFormats @param name The name of the type. @return The type. */ - KeyType + [[nodiscard]] KeyType findTypeByName(std::string const& name) const { if (auto const result = findByName(name)) @@ -108,7 +108,7 @@ class KnownFormats /** Retrieve a format based on its type. */ - Item const* + [[nodiscard]] Item const* findByType(KeyType type) const { auto const itr = types_.find(type); @@ -118,13 +118,13 @@ class KnownFormats } // begin() and end() are provided for testing purposes. - typename std::forward_list::const_iterator + [[nodiscard]] typename std::forward_list::const_iterator begin() const { return formats_.begin(); } - typename std::forward_list::const_iterator + [[nodiscard]] typename std::forward_list::const_iterator end() const { return formats_.end(); @@ -133,7 +133,7 @@ class KnownFormats protected: /** Retrieve a format based on its name. */ - Item const* + [[nodiscard]] Item const* findByName(std::string const& name) const { auto const itr = names_.find(name); diff --git a/include/xrpl/protocol/MPTAmount.h b/include/xrpl/protocol/MPTAmount.h index 4a6297cc747..9d0e0901bfa 100644 --- a/include/xrpl/protocol/MPTAmount.h +++ b/include/xrpl/protocol/MPTAmount.h @@ -68,14 +68,14 @@ class MPTAmount : private boost::totally_ordered, } /** Return the sign of the amount */ - constexpr int + [[nodiscard]] constexpr int signum() const noexcept; /** Returns the underlying value. Code SHOULD NOT call this function unless the type has been abstracted away, e.g. in a templated function. */ - constexpr value_type + [[nodiscard]] constexpr value_type value() const; static MPTAmount diff --git a/include/xrpl/protocol/MPTIssue.h b/include/xrpl/protocol/MPTIssue.h index 727aef90081..c467382f077 100644 --- a/include/xrpl/protocol/MPTIssue.h +++ b/include/xrpl/protocol/MPTIssue.h @@ -26,16 +26,16 @@ class MPTIssue return mptID_; } - AccountID const& + [[nodiscard]] AccountID const& getIssuer() const; - constexpr MPTID const& + [[nodiscard]] constexpr MPTID const& getMptID() const { return mptID_; } - std::string + [[nodiscard]] std::string getText() const; void diff --git a/include/xrpl/protocol/MultiApiJson.h b/include/xrpl/protocol/MultiApiJson.h index 8d287767a68..6a86aa35b8b 100644 --- a/include/xrpl/protocol/MultiApiJson.h +++ b/include/xrpl/protocol/MultiApiJson.h @@ -156,7 +156,7 @@ struct MultiApiJson { return visitor(*self, std::forward(args)...); }; } - auto + [[nodiscard]] auto visit() const { return [self = this](auto... args) @@ -176,7 +176,7 @@ struct MultiApiJson } template - auto + [[nodiscard]] auto visit(Args... args) const -> std::invoke_result_t requires(sizeof...(args) > 0) && requires { visitor(*this, std::forward(args)...); } diff --git a/include/xrpl/protocol/PathAsset.h b/include/xrpl/protocol/PathAsset.h index 662e568bec8..67b78f2191d 100644 --- a/include/xrpl/protocol/PathAsset.h +++ b/include/xrpl/protocol/PathAsset.h @@ -24,17 +24,17 @@ class PathAsset } template - constexpr bool + [[nodiscard]] constexpr bool holds() const; - constexpr bool + [[nodiscard]] constexpr bool isXRP() const; template T const& get() const; - constexpr std::variant const& + [[nodiscard]] constexpr std::variant const& value() const; // Custom, generic visit implementation diff --git a/include/xrpl/protocol/Permissions.h b/include/xrpl/protocol/Permissions.h index ea8bd776433..4d26ba7cf86 100644 --- a/include/xrpl/protocol/Permissions.h +++ b/include/xrpl/protocol/Permissions.h @@ -53,22 +53,22 @@ class Permission Permission& operator=(Permission const&) = delete; - std::optional + [[nodiscard]] std::optional getPermissionName(std::uint32_t const value) const; - std::optional + [[nodiscard]] std::optional getGranularValue(std::string const& name) const; - std::optional + [[nodiscard]] std::optional getGranularName(GranularPermissionType const& value) const; - std::optional + [[nodiscard]] std::optional getGranularTxType(GranularPermissionType const& gpType) const; - std::optional> + [[nodiscard]] std::optional> getTxFeature(TxType txType) const; - bool + [[nodiscard]] bool isDelegable(std::uint32_t const& permissionValue, Rules const& rules) const; // for tx level permission, permission value is equal to tx type plus one diff --git a/include/xrpl/protocol/PublicKey.h b/include/xrpl/protocol/PublicKey.h index 8325d2b1d2a..9ec82dde97d 100644 --- a/include/xrpl/protocol/PublicKey.h +++ b/include/xrpl/protocol/PublicKey.h @@ -63,7 +63,7 @@ class PublicKey */ explicit PublicKey(Slice const& slice); - std::uint8_t const* + [[nodiscard]] std::uint8_t const* data() const noexcept { return buf_; @@ -75,31 +75,31 @@ class PublicKey return size_; } - const_iterator + [[nodiscard]] const_iterator begin() const noexcept { return buf_; } - const_iterator + [[nodiscard]] const_iterator cbegin() const noexcept { return buf_; } - const_iterator + [[nodiscard]] const_iterator end() const noexcept { return buf_ + size_; } - const_iterator + [[nodiscard]] const_iterator cend() const noexcept { return buf_ + size_; } - Slice + [[nodiscard]] Slice slice() const noexcept { return {buf_, size_}; diff --git a/include/xrpl/protocol/Quality.h b/include/xrpl/protocol/Quality.h index b0e3e65d6c4..2d4ea2f652e 100644 --- a/include/xrpl/protocol/Quality.h +++ b/include/xrpl/protocol/Quality.h @@ -35,7 +35,7 @@ struct TAmounts } /** Returns `true` if either quantity is not positive. */ - bool + [[nodiscard]] bool empty() const noexcept { return in <= beast::zero || out <= beast::zero; @@ -145,7 +145,7 @@ class Quality /** @} */ /** Returns the quality as STAmount. */ - STAmount + [[nodiscard]] STAmount rate() const { return amountFromQuality(m_value); @@ -154,7 +154,7 @@ class Quality /** Returns the quality rounded up to the specified number of decimal digits. */ - Quality + [[nodiscard]] Quality round(int tickSize) const; /** Returns the scaled amount with in capped. diff --git a/include/xrpl/protocol/QualityFunction.h b/include/xrpl/protocol/QualityFunction.h index 15865a6e074..672c529c384 100644 --- a/include/xrpl/protocol/QualityFunction.h +++ b/include/xrpl/protocol/QualityFunction.h @@ -53,13 +53,13 @@ class QualityFunction /** Return true if the quality function is constant */ - bool + [[nodiscard]] bool isConst() const { return quality_.has_value(); } - std::optional const& + [[nodiscard]] std::optional const& quality() const { return quality_; diff --git a/include/xrpl/protocol/Rules.h b/include/xrpl/protocol/Rules.h index 11ca8eb72a0..7faf602cfd3 100644 --- a/include/xrpl/protocol/Rules.h +++ b/include/xrpl/protocol/Rules.h @@ -58,12 +58,12 @@ class Rules std::optional const& digest, STVector256 const& amendments); - std::unordered_set> const& + [[nodiscard]] std::unordered_set> const& presets() const; public: /** Returns `true` if a feature is enabled. */ - bool + [[nodiscard]] bool enabled(uint256 const& feature) const; /** Returns `true` if two rule sets are identical. diff --git a/include/xrpl/protocol/SField.h b/include/xrpl/protocol/SField.h index cbc2c12f4e6..7e42b9ec62e 100644 --- a/include/xrpl/protocol/SField.h +++ b/include/xrpl/protocol/SField.h @@ -189,19 +189,19 @@ class SField return getField(field_code(type, value)); } - std::string const& + [[nodiscard]] std::string const& getName() const { return fieldName; } - bool + [[nodiscard]] bool hasName() const { return fieldCode > 0; } - Json::StaticString const& + [[nodiscard]] Json::StaticString const& getJsonName() const { return jsonName; @@ -212,19 +212,19 @@ class SField return jsonName; } - bool + [[nodiscard]] bool isInvalid() const { return fieldCode == -1; } - bool + [[nodiscard]] bool isUseful() const { return fieldCode > 0; } - bool + [[nodiscard]] bool isBinary() const { return fieldValue < 256; @@ -234,18 +234,18 @@ class SField // should be discarded during serialization,like 'hash'. // You cannot serialize an object's hash inside that object, // but you can have it in the JSON representation. - bool + [[nodiscard]] bool isDiscardable() const { return fieldValue > 256; } - int + [[nodiscard]] int getCode() const { return fieldCode; } - int + [[nodiscard]] int getNum() const { return fieldNum; @@ -256,13 +256,13 @@ class SField return num; } - bool + [[nodiscard]] bool shouldMeta(int c) const { return (fieldMeta & c) != 0; } - bool + [[nodiscard]] bool shouldInclude(bool withSigningField) const { return (fieldValue < 256) && (withSigningField || (signingField == IsSigning::yes)); diff --git a/include/xrpl/protocol/SOTemplate.h b/include/xrpl/protocol/SOTemplate.h index 41cea7936c8..ca09fc3d715 100644 --- a/include/xrpl/protocol/SOTemplate.h +++ b/include/xrpl/protocol/SOTemplate.h @@ -63,19 +63,19 @@ class SOElement init(fieldName); } - SField const& + [[nodiscard]] SField const& sField() const { return sField_.get(); } - SOEStyle + [[nodiscard]] SOEStyle style() const { return style_; } - SOETxMPTIssue + [[nodiscard]] SOETxMPTIssue supportMPT() const { return supportMpt_; @@ -110,42 +110,42 @@ class SOTemplate std::initializer_list commonFields = {}); /* Provide for the enumeration of fields */ - std::vector::const_iterator + [[nodiscard]] std::vector::const_iterator begin() const { return elements_.cbegin(); } - std::vector::const_iterator + [[nodiscard]] std::vector::const_iterator cbegin() const { return begin(); } - std::vector::const_iterator + [[nodiscard]] std::vector::const_iterator end() const { return elements_.cend(); } - std::vector::const_iterator + [[nodiscard]] std::vector::const_iterator cend() const { return end(); } /** The number of entries in this template */ - std::size_t + [[nodiscard]] std::size_t size() const { return elements_.size(); } /** Retrieve the position of a named field. */ - int + [[nodiscard]] int getIndex(SField const&) const; - SOEStyle + [[nodiscard]] SOEStyle style(SField const& sf) const { return elements_[indices_[sf.getNum()]].style(); diff --git a/include/xrpl/protocol/STAccount.h b/include/xrpl/protocol/STAccount.h index b1f112fbb2a..65f404d58d3 100644 --- a/include/xrpl/protocol/STAccount.h +++ b/include/xrpl/protocol/STAccount.h @@ -28,25 +28,25 @@ class STAccount final : public STBase, public CountedObject STAccount(SerialIter& sit, SField const& name); STAccount(SField const& n, AccountID const& v); - SerializedTypeID + [[nodiscard]] SerializedTypeID getSType() const override; - std::string + [[nodiscard]] std::string getText() const override; void add(Serializer& s) const override; - bool + [[nodiscard]] bool isEquivalent(STBase const& t) const override; - bool + [[nodiscard]] bool isDefault() const override; STAccount& operator=(AccountID const& value); - AccountID const& + [[nodiscard]] AccountID const& value() const noexcept; void diff --git a/include/xrpl/protocol/STAmount.h b/include/xrpl/protocol/STAmount.h index 695bd3c0b17..06471df5c94 100644 --- a/include/xrpl/protocol/STAmount.h +++ b/include/xrpl/protocol/STAmount.h @@ -138,26 +138,26 @@ class STAmount final : public STBase, public CountedObject // //-------------------------------------------------------------------------- - int + [[nodiscard]] int exponent() const noexcept; - bool + [[nodiscard]] bool integral() const noexcept; - bool + [[nodiscard]] bool native() const noexcept; template - constexpr bool + [[nodiscard]] constexpr bool holds() const noexcept; - bool + [[nodiscard]] bool negative() const noexcept; - std::uint64_t + [[nodiscard]] std::uint64_t mantissa() const noexcept; - Asset const& + [[nodiscard]] Asset const& asset() const; template @@ -168,20 +168,20 @@ class STAmount final : public STBase, public CountedObject TIss& get(); - AccountID const& + [[nodiscard]] AccountID const& getIssuer() const; - int + [[nodiscard]] int signum() const noexcept; /** Returns a zero value with the same issuer and currency. */ - STAmount + [[nodiscard]] STAmount zeroed() const; void setJson(Json::Value&) const; - STAmount const& + [[nodiscard]] STAmount const& value() const noexcept; //-------------------------------------------------------------------------- @@ -232,31 +232,31 @@ class STAmount final : public STBase, public CountedObject // //-------------------------------------------------------------------------- - SerializedTypeID + [[nodiscard]] SerializedTypeID getSType() const override; - std::string + [[nodiscard]] std::string getFullText() const override; - std::string + [[nodiscard]] std::string getText() const override; - Json::Value getJson(JsonOptions = JsonOptions::none) const override; + [[nodiscard]] Json::Value getJson(JsonOptions = JsonOptions::none) const override; void add(Serializer& s) const override; - bool + [[nodiscard]] bool isEquivalent(STBase const& t) const override; - bool + [[nodiscard]] bool isDefault() const override; - XRPAmount + [[nodiscard]] XRPAmount xrp() const; - IOUAmount + [[nodiscard]] IOUAmount iou() const; - MPTAmount + [[nodiscard]] MPTAmount mpt() const; private: @@ -462,7 +462,7 @@ STAmount::asset() const } template -constexpr TIss const& +[[nodiscard]] constexpr TIss const& STAmount::get() const { return mAsset.get(); diff --git a/include/xrpl/protocol/STArray.h b/include/xrpl/protocol/STArray.h index 045b682f880..f1ac58075b1 100644 --- a/include/xrpl/protocol/STArray.h +++ b/include/xrpl/protocol/STArray.h @@ -53,7 +53,7 @@ class STArray final : public STBase, public CountedObject STObject& back(); - STObject const& + [[nodiscard]] STObject const& back() const; template @@ -72,16 +72,16 @@ class STArray final : public STBase, public CountedObject iterator end(); - const_iterator + [[nodiscard]] const_iterator begin() const; - const_iterator + [[nodiscard]] const_iterator end() const; - size_type + [[nodiscard]] size_type size() const; - bool + [[nodiscard]] bool empty() const; void @@ -93,13 +93,13 @@ class STArray final : public STBase, public CountedObject void swap(STArray& a) noexcept; - std::string + [[nodiscard]] std::string getFullText() const override; - std::string + [[nodiscard]] std::string getText() const override; - Json::Value + [[nodiscard]] Json::Value getJson(JsonOptions index) const override; void @@ -126,13 +126,13 @@ class STArray final : public STBase, public CountedObject iterator erase(const_iterator first, const_iterator last); - SerializedTypeID + [[nodiscard]] SerializedTypeID getSType() const override; - bool + [[nodiscard]] bool isEquivalent(STBase const& t) const override; - bool + [[nodiscard]] bool isDefault() const override; private: diff --git a/include/xrpl/protocol/STBase.h b/include/xrpl/protocol/STBase.h index 8edeb264249..0beefe45f69 100644 --- a/include/xrpl/protocol/STBase.h +++ b/include/xrpl/protocol/STBase.h @@ -137,24 +137,24 @@ class STBase D const& downcast() const; - virtual SerializedTypeID + [[nodiscard]] virtual SerializedTypeID getSType() const; - virtual std::string + [[nodiscard]] virtual std::string getFullText() const; - virtual std::string + [[nodiscard]] virtual std::string getText() const; - virtual Json::Value getJson(JsonOptions = JsonOptions::none) const; + [[nodiscard]] virtual Json::Value getJson(JsonOptions = JsonOptions::none) const; virtual void add(Serializer& s) const; - virtual bool + [[nodiscard]] virtual bool isEquivalent(STBase const& t) const; - virtual bool + [[nodiscard]] virtual bool isDefault() const; /** A STBase is a field. @@ -163,7 +163,7 @@ class STBase void setFName(SField const& n); - SField const& + [[nodiscard]] SField const& getFName() const; void @@ -199,7 +199,7 @@ STBase::downcast() } template -D const& +[[nodiscard]] D const& STBase::downcast() const { D const* ptr = dynamic_cast(this); diff --git a/include/xrpl/protocol/STBitString.h b/include/xrpl/protocol/STBitString.h index de038cce325..6f2e08e4018 100644 --- a/include/xrpl/protocol/STBitString.h +++ b/include/xrpl/protocol/STBitString.h @@ -29,26 +29,26 @@ class STBitString final : public STBase, public CountedObject> STBitString(SField const& n, value_type const& v); STBitString(SerialIter& sit, SField const& name); - SerializedTypeID + [[nodiscard]] SerializedTypeID getSType() const override; - std::string + [[nodiscard]] std::string getText() const override; - bool + [[nodiscard]] bool isEquivalent(STBase const& t) const override; void add(Serializer& s) const override; - bool + [[nodiscard]] bool isDefault() const override; template void setValue(base_uint const& v); - value_type const& + [[nodiscard]] value_type const& value() const; operator value_type() const; diff --git a/include/xrpl/protocol/STBlob.h b/include/xrpl/protocol/STBlob.h index b9dc78ffe4e..0667c54e307 100644 --- a/include/xrpl/protocol/STBlob.h +++ b/include/xrpl/protocol/STBlob.h @@ -26,31 +26,31 @@ class STBlob : public STBase, public CountedObject STBlob(SField const& n); STBlob(SerialIter&, SField const& name = sfGeneric); - std::size_t + [[nodiscard]] std::size_t size() const; - std::uint8_t const* + [[nodiscard]] std::uint8_t const* data() const; - SerializedTypeID + [[nodiscard]] SerializedTypeID getSType() const override; - std::string + [[nodiscard]] std::string getText() const override; void add(Serializer& s) const override; - bool + [[nodiscard]] bool isEquivalent(STBase const& t) const override; - bool + [[nodiscard]] bool isDefault() const override; STBlob& operator=(Slice const& slice); - value_type + [[nodiscard]] value_type value() const noexcept; STBlob& diff --git a/include/xrpl/protocol/STCurrency.h b/include/xrpl/protocol/STCurrency.h index 5fd4c08fbbb..a81b589a2c0 100644 --- a/include/xrpl/protocol/STCurrency.h +++ b/include/xrpl/protocol/STCurrency.h @@ -24,30 +24,30 @@ class STCurrency final : public STBase explicit STCurrency(SField const& name); - Currency const& + [[nodiscard]] Currency const& currency() const; - Currency const& + [[nodiscard]] Currency const& value() const noexcept; void setCurrency(Currency const& currency); - SerializedTypeID + [[nodiscard]] SerializedTypeID getSType() const override; - std::string + [[nodiscard]] std::string getText() const override; - Json::Value getJson(JsonOptions) const override; + [[nodiscard]] Json::Value getJson(JsonOptions) const override; void add(Serializer& s) const override; - bool + [[nodiscard]] bool isEquivalent(STBase const& t) const override; - bool + [[nodiscard]] bool isDefault() const override; private: diff --git a/include/xrpl/protocol/STInteger.h b/include/xrpl/protocol/STInteger.h index f4bbd6e73d2..5f6e8c8800c 100644 --- a/include/xrpl/protocol/STInteger.h +++ b/include/xrpl/protocol/STInteger.h @@ -19,27 +19,27 @@ class STInteger : public STBase, public CountedObject> STInteger(SField const& n, Integer v = 0); STInteger(SerialIter& sit, SField const& name); - SerializedTypeID + [[nodiscard]] SerializedTypeID getSType() const override; - Json::Value getJson(JsonOptions) const override; + [[nodiscard]] Json::Value getJson(JsonOptions) const override; - std::string + [[nodiscard]] std::string getText() const override; void add(Serializer& s) const override; - bool + [[nodiscard]] bool isDefault() const override; - bool + [[nodiscard]] bool isEquivalent(STBase const& t) const override; STInteger& operator=(value_type const& v); - value_type + [[nodiscard]] value_type value() const noexcept; void diff --git a/include/xrpl/protocol/STIssue.h b/include/xrpl/protocol/STIssue.h index 7491e3b3ff5..8a64f39336c 100644 --- a/include/xrpl/protocol/STIssue.h +++ b/include/xrpl/protocol/STIssue.h @@ -34,30 +34,30 @@ class STIssue final : public STBase, CountedObject get() const; template - bool + [[nodiscard]] bool holds() const; - value_type const& + [[nodiscard]] value_type const& value() const noexcept; void setIssue(Asset const& issue); - SerializedTypeID + [[nodiscard]] SerializedTypeID getSType() const override; - std::string + [[nodiscard]] std::string getText() const override; - Json::Value getJson(JsonOptions) const override; + [[nodiscard]] Json::Value getJson(JsonOptions) const override; void add(Serializer& s) const override; - bool + [[nodiscard]] bool isEquivalent(STBase const& t) const override; - bool + [[nodiscard]] bool isDefault() const override; friend constexpr bool diff --git a/include/xrpl/protocol/STLedgerEntry.h b/include/xrpl/protocol/STLedgerEntry.h index a28868cd7aa..2e884bc2bfb 100644 --- a/include/xrpl/protocol/STLedgerEntry.h +++ b/include/xrpl/protocol/STLedgerEntry.h @@ -28,30 +28,30 @@ class STLedgerEntry final : public STObject, public CountedObject STLedgerEntry(SerialIter&& sit, uint256 const& index); STLedgerEntry(STObject const& object, uint256 const& index); - SerializedTypeID + [[nodiscard]] SerializedTypeID getSType() const override; - std::string + [[nodiscard]] std::string getFullText() const override; - std::string + [[nodiscard]] std::string getText() const override; - Json::Value + [[nodiscard]] Json::Value getJson(JsonOptions options = JsonOptions::none) const override; /** Returns the 'key' (or 'index') of this item. The key identifies this entry's position in the SHAMap associative container. */ - uint256 const& + [[nodiscard]] uint256 const& key() const; - LedgerEntryType + [[nodiscard]] LedgerEntryType getType() const; // is this a ledger entry that can be threaded - bool + [[nodiscard]] bool isThreadedType(Rules const& rules) const; bool diff --git a/include/xrpl/protocol/STNumber.h b/include/xrpl/protocol/STNumber.h index 137016dfe7f..802bdf671f4 100644 --- a/include/xrpl/protocol/STNumber.h +++ b/include/xrpl/protocol/STNumber.h @@ -43,14 +43,14 @@ class STNumber : public STTakesAsset, public CountedObject explicit STNumber(SField const& field, Number const& value = Number()); STNumber(SerialIter& sit, SField const& field); - SerializedTypeID + [[nodiscard]] SerializedTypeID getSType() const override; - std::string + [[nodiscard]] std::string getText() const override; void add(Serializer& s) const override; - Number const& + [[nodiscard]] Number const& value() const; void setValue(Number const& v); @@ -62,9 +62,9 @@ class STNumber : public STTakesAsset, public CountedObject return *this; } - bool + [[nodiscard]] bool isEquivalent(STBase const& t) const override; - bool + [[nodiscard]] bool isDefault() const override; void diff --git a/include/xrpl/protocol/STObject.h b/include/xrpl/protocol/STObject.h index 34bd19b9a0c..d27112e17c4 100644 --- a/include/xrpl/protocol/STObject.h +++ b/include/xrpl/protocol/STObject.h @@ -86,13 +86,13 @@ class STObject : public STBase, public CountedObject static STObject makeInnerObject(SField const& name); - iterator + [[nodiscard]] iterator begin() const; - iterator + [[nodiscard]] iterator end() const; - bool + [[nodiscard]] bool empty() const; void @@ -104,7 +104,7 @@ class STObject : public STBase, public CountedObject void applyTemplateFromSField(SField const&); - bool + [[nodiscard]] bool isFree() const; void @@ -113,81 +113,81 @@ class STObject : public STBase, public CountedObject bool set(SerialIter& u, int depth = 0); - SerializedTypeID + [[nodiscard]] SerializedTypeID getSType() const override; - bool + [[nodiscard]] bool isEquivalent(STBase const& t) const override; - bool + [[nodiscard]] bool isDefault() const override; void add(Serializer& s) const override; - std::string + [[nodiscard]] std::string getFullText() const override; - std::string + [[nodiscard]] std::string getText() const override; // TODO(tom): options should be an enum. - Json::Value getJson(JsonOptions = JsonOptions::none) const override; + [[nodiscard]] Json::Value getJson(JsonOptions = JsonOptions::none) const override; void addWithoutSigningFields(Serializer& s) const; - Serializer + [[nodiscard]] Serializer getSerializer() const; template std::size_t emplace_back(Args&&... args); - int + [[nodiscard]] int getCount() const; bool setFlag(std::uint32_t); bool clearFlag(std::uint32_t); - bool + [[nodiscard]] bool isFlag(std::uint32_t) const; - std::uint32_t + [[nodiscard]] std::uint32_t getFlags() const; - uint256 + [[nodiscard]] uint256 getHash(HashPrefix prefix) const; - uint256 + [[nodiscard]] uint256 getSigningHash(HashPrefix prefix) const; - STBase const& + [[nodiscard]] STBase const& peekAtIndex(int offset) const; STBase& getIndex(int offset); - STBase const* + [[nodiscard]] STBase const* peekAtPIndex(int offset) const; STBase* getPIndex(int offset); - int + [[nodiscard]] int getFieldIndex(SField const& field) const; - SField const& + [[nodiscard]] SField const& getFieldSType(int index) const; - STBase const& + [[nodiscard]] STBase const& peekAtField(SField const& field) const; STBase& getField(SField const& field); - STBase const* + [[nodiscard]] STBase const* peekAtPField(SField const& field) const; STBase* @@ -195,44 +195,44 @@ class STObject : public STBase, public CountedObject // these throw if the field type doesn't match, or return default values // if the field is optional but not present - unsigned char + [[nodiscard]] unsigned char getFieldU8(SField const& field) const; - std::uint16_t + [[nodiscard]] std::uint16_t getFieldU16(SField const& field) const; - std::uint32_t + [[nodiscard]] std::uint32_t getFieldU32(SField const& field) const; - std::uint64_t + [[nodiscard]] std::uint64_t getFieldU64(SField const& field) const; - uint128 + [[nodiscard]] uint128 getFieldH128(SField const& field) const; - uint160 + [[nodiscard]] uint160 getFieldH160(SField const& field) const; - uint192 + [[nodiscard]] uint192 getFieldH192(SField const& field) const; - uint256 + [[nodiscard]] uint256 getFieldH256(SField const& field) const; - std::int32_t + [[nodiscard]] std::int32_t getFieldI32(SField const& field) const; - AccountID + [[nodiscard]] AccountID getAccountID(SField const& field) const; - Blob + [[nodiscard]] Blob getFieldVL(SField const& field) const; - STAmount const& + [[nodiscard]] STAmount const& getFieldAmount(SField const& field) const; - STPathSet const& + [[nodiscard]] STPathSet const& getFieldPathSet(SField const& field) const; - STVector256 const& + [[nodiscard]] STVector256 const& getFieldV256(SField const& field) const; // If not found, returns an object constructed with the given field - STObject + [[nodiscard]] STObject getFieldObject(SField const& field) const; - STArray const& + [[nodiscard]] STArray const& getFieldArray(SField const& field) const; - STCurrency const& + [[nodiscard]] STCurrency const& getFieldCurrency(SField const& field) const; - STNumber const& + [[nodiscard]] STNumber const& getFieldNumber(SField const& field) const; /** Get the value of a field. @@ -290,7 +290,7 @@ class STObject : public STBase, public CountedObject @throws STObject::FieldErr if the field is not present. */ template - typename T::value_type + [[nodiscard]] typename T::value_type at(TypedField const& f) const; /** Get the value of a field as std::optional @@ -302,7 +302,7 @@ class STObject : public STBase, public CountedObject the specified field. */ template - std::optional> + [[nodiscard]] std::optional> at(OptionaledField const& of) const; /** Get a modifiable field value. @@ -388,7 +388,7 @@ class STObject : public STBase, public CountedObject STArray& peekFieldArray(SField const& field); - bool + [[nodiscard]] bool isFieldPresent(SField const& field) const; STBase* makeFieldPresent(SField const& field); @@ -399,10 +399,10 @@ class STObject : public STBase, public CountedObject void delField(int index); - SOEStyle + [[nodiscard]] SOEStyle getStyle(SField const& field) const; - bool + [[nodiscard]] bool hasMatchingEntry(STBase const&) const; bool @@ -480,7 +480,7 @@ class STObject::Proxy public: using value_type = typename T::value_type; - value_type + [[nodiscard]] value_type value() const; value_type @@ -500,7 +500,7 @@ class STObject::Proxy Proxy(STObject* st, TypedField const* f); - T const* + [[nodiscard]] T const* find() const; template @@ -666,7 +666,7 @@ class STObject::OptionalProxy : public Proxy } // Emulate std::optional::value_or - value_type + [[nodiscard]] value_type value_or(value_type val) const; OptionalProxy& @@ -685,13 +685,13 @@ class STObject::OptionalProxy : public Proxy OptionalProxy(STObject* st, TypedField const* f); - bool + [[nodiscard]] bool engaged() const noexcept; void disengage(); - optional_type + [[nodiscard]] optional_type optional_value() const; }; @@ -1068,7 +1068,7 @@ STObject::operator[](OptionaledField const& of) -> OptionalProxy } template -typename T::value_type +[[nodiscard]] typename T::value_type STObject::at(TypedField const& f) const { auto const b = peekAtPField(f); @@ -1100,7 +1100,7 @@ STObject::at(TypedField const& f) const } template -std::optional> +[[nodiscard]] std::optional> STObject::at(OptionaledField const& of) const { auto const b = peekAtPField(*of.f); diff --git a/include/xrpl/protocol/STPathSet.h b/include/xrpl/protocol/STPathSet.h index 1d6fce5c18f..38f4668b5dd 100644 --- a/include/xrpl/protocol/STPathSet.h +++ b/include/xrpl/protocol/STPathSet.h @@ -59,48 +59,48 @@ class STPathElement final : public CountedObject PathAsset const& asset, AccountID const& issuer); - auto + [[nodiscard]] auto getNodeType() const; - bool + [[nodiscard]] bool isOffer() const; - bool + [[nodiscard]] bool isAccount() const; - bool + [[nodiscard]] bool hasIssuer() const; - bool + [[nodiscard]] bool hasCurrency() const; - bool + [[nodiscard]] bool hasMPT() const; - bool + [[nodiscard]] bool hasAsset() const; - bool + [[nodiscard]] bool isNone() const; // Nodes are either an account ID or a offer prefix. Offer prefixs denote a // class of offers. - AccountID const& + [[nodiscard]] AccountID const& getAccountID() const; - PathAsset const& + [[nodiscard]] PathAsset const& getPathAsset() const; - Currency const& + [[nodiscard]] Currency const& getCurrency() const; - MPTID const& + [[nodiscard]] MPTID const& getMPTID() const; - AccountID const& + [[nodiscard]] AccountID const& getIssuerID() const; - bool + [[nodiscard]] bool isType(Type const& pe) const; bool @@ -123,10 +123,10 @@ class STPath final : public CountedObject STPath(std::vector p); - std::vector::size_type + [[nodiscard]] std::vector::size_type size() const; - bool + [[nodiscard]] bool empty() const; void @@ -136,24 +136,24 @@ class STPath final : public CountedObject void emplace_back(Args&&... args); - bool + [[nodiscard]] bool hasSeen(AccountID const& account, PathAsset const& asset, AccountID const& issuer) const; - Json::Value getJson(JsonOptions) const; + [[nodiscard]] Json::Value getJson(JsonOptions) const; - std::vector::const_iterator + [[nodiscard]] std::vector::const_iterator begin() const; - std::vector::const_iterator + [[nodiscard]] std::vector::const_iterator end() const; bool operator==(STPath const& t) const; - std::vector::const_reference + [[nodiscard]] std::vector::const_reference back() const; - std::vector::const_reference + [[nodiscard]] std::vector::const_reference front() const; STPathElement& @@ -182,18 +182,18 @@ class STPathSet final : public STBase, public CountedObject void add(Serializer& s) const override; - Json::Value getJson(JsonOptions) const override; + [[nodiscard]] Json::Value getJson(JsonOptions) const override; - SerializedTypeID + [[nodiscard]] SerializedTypeID getSType() const override; bool assembleAdd(STPath const& base, STPathElement const& tail); - bool + [[nodiscard]] bool isEquivalent(STBase const& t) const override; - bool + [[nodiscard]] bool isDefault() const override; // std::vector like interface: @@ -203,16 +203,16 @@ class STPathSet final : public STBase, public CountedObject std::vector::reference operator[](std::vector::size_type n); - std::vector::const_iterator + [[nodiscard]] std::vector::const_iterator begin() const; - std::vector::const_iterator + [[nodiscard]] std::vector::const_iterator end() const; - std::vector::size_type + [[nodiscard]] std::vector::size_type size() const; - bool + [[nodiscard]] bool empty() const; void diff --git a/include/xrpl/protocol/STVector256.h b/include/xrpl/protocol/STVector256.h index 69b06ec1daf..c650c565ce9 100644 --- a/include/xrpl/protocol/STVector256.h +++ b/include/xrpl/protocol/STVector256.h @@ -21,18 +21,18 @@ class STVector256 : public STBase, public CountedObject STVector256(SField const& n, std::vector const& vector); STVector256(SerialIter& sit, SField const& name); - SerializedTypeID + [[nodiscard]] SerializedTypeID getSType() const override; void add(Serializer& s) const override; - Json::Value getJson(JsonOptions) const override; + [[nodiscard]] Json::Value getJson(JsonOptions) const override; - bool + [[nodiscard]] bool isEquivalent(STBase const& t) const override; - bool + [[nodiscard]] bool isDefault() const override; STVector256& @@ -48,13 +48,13 @@ class STVector256 : public STBase, public CountedObject explicit operator std::vector() const; - std::size_t + [[nodiscard]] std::size_t size() const; void resize(std::size_t n); - bool + [[nodiscard]] bool empty() const; std::vector::reference @@ -63,7 +63,7 @@ class STVector256 : public STBase, public CountedObject std::vector::const_reference operator[](std::vector::size_type n) const; - std::vector const& + [[nodiscard]] std::vector const& value() const; std::vector::iterator @@ -75,13 +75,13 @@ class STVector256 : public STBase, public CountedObject std::vector::iterator begin(); - std::vector::const_iterator + [[nodiscard]] std::vector::const_iterator begin() const; std::vector::iterator end(); - std::vector::const_iterator + [[nodiscard]] std::vector::const_iterator end() const; std::vector::iterator diff --git a/include/xrpl/protocol/STXChainBridge.h b/include/xrpl/protocol/STXChainBridge.h index f74cc02041f..2dc2fbce489 100644 --- a/include/xrpl/protocol/STXChainBridge.h +++ b/include/xrpl/protocol/STXChainBridge.h @@ -54,45 +54,45 @@ class STXChainBridge final : public STBase, public CountedObject STXChainBridge& operator=(STXChainBridge const& rhs) = default; - std::string + [[nodiscard]] std::string getText() const override; - STObject + [[nodiscard]] STObject toSTObject() const; - AccountID const& + [[nodiscard]] AccountID const& lockingChainDoor() const; - Issue const& + [[nodiscard]] Issue const& lockingChainIssue() const; - AccountID const& + [[nodiscard]] AccountID const& issuingChainDoor() const; - Issue const& + [[nodiscard]] Issue const& issuingChainIssue() const; - AccountID const& + [[nodiscard]] AccountID const& door(ChainType ct) const; - Issue const& + [[nodiscard]] Issue const& issue(ChainType ct) const; - SerializedTypeID + [[nodiscard]] SerializedTypeID getSType() const override; - Json::Value getJson(JsonOptions) const override; + [[nodiscard]] Json::Value getJson(JsonOptions) const override; void add(Serializer& s) const override; - bool + [[nodiscard]] bool isEquivalent(STBase const& t) const override; - bool + [[nodiscard]] bool isDefault() const override; - value_type const& + [[nodiscard]] value_type const& value() const noexcept; private: diff --git a/include/xrpl/protocol/SecretKey.h b/include/xrpl/protocol/SecretKey.h index c17b3984e97..462a48f4bd3 100644 --- a/include/xrpl/protocol/SecretKey.h +++ b/include/xrpl/protocol/SecretKey.h @@ -40,13 +40,13 @@ class SecretKey SecretKey(std::array const& data); SecretKey(Slice const& slice); - std::uint8_t const* + [[nodiscard]] std::uint8_t const* data() const { return buf_; } - std::size_t + [[nodiscard]] std::size_t size() const { return sizeof(buf_); @@ -57,28 +57,28 @@ class SecretKey @note The operator<< function is deliberately omitted to avoid accidental exposure of secret key material. */ - std::string + [[nodiscard]] std::string to_string() const; - const_iterator + [[nodiscard]] const_iterator begin() const noexcept { return buf_; } - const_iterator + [[nodiscard]] const_iterator cbegin() const noexcept { return buf_; } - const_iterator + [[nodiscard]] const_iterator end() const noexcept { return buf_ + sizeof(buf_); } - const_iterator + [[nodiscard]] const_iterator cend() const noexcept { return buf_ + sizeof(buf_); diff --git a/include/xrpl/protocol/Seed.h b/include/xrpl/protocol/Seed.h index 04e8481c8fc..0b93b845166 100644 --- a/include/xrpl/protocol/Seed.h +++ b/include/xrpl/protocol/Seed.h @@ -35,37 +35,37 @@ class Seed explicit Seed(uint128 const& seed); /** @} */ - std::uint8_t const* + [[nodiscard]] std::uint8_t const* data() const { return buf_.data(); } - std::size_t + [[nodiscard]] std::size_t size() const { return buf_.size(); } - const_iterator + [[nodiscard]] const_iterator begin() const noexcept { return buf_.begin(); } - const_iterator + [[nodiscard]] const_iterator cbegin() const noexcept { return buf_.cbegin(); } - const_iterator + [[nodiscard]] const_iterator end() const noexcept { return buf_.end(); } - const_iterator + [[nodiscard]] const_iterator cend() const noexcept { return buf_.cend(); diff --git a/include/xrpl/protocol/SeqProxy.h b/include/xrpl/protocol/SeqProxy.h index 563292f8b35..86742bacc12 100644 --- a/include/xrpl/protocol/SeqProxy.h +++ b/include/xrpl/protocol/SeqProxy.h @@ -58,19 +58,19 @@ class SeqProxy return SeqProxy{Type::seq, v}; } - constexpr std::uint32_t + [[nodiscard]] constexpr std::uint32_t value() const { return value_; } - constexpr bool + [[nodiscard]] constexpr bool isSeq() const { return type_ == seq; } - constexpr bool + [[nodiscard]] constexpr bool isTicket() const { return type_ == ticket; diff --git a/include/xrpl/protocol/Serializer.h b/include/xrpl/protocol/Serializer.h index 6ce60022e32..e14d008cd13 100644 --- a/include/xrpl/protocol/Serializer.h +++ b/include/xrpl/protocol/Serializer.h @@ -40,19 +40,19 @@ class Serializer } } - Slice + [[nodiscard]] Slice slice() const noexcept { return Slice(mData.data(), mData.size()); } - std::size_t + [[nodiscard]] std::size_t size() const noexcept { return mData.size(); } - void const* + [[nodiscard]] void const* data() const noexcept { return mData.data(); @@ -168,16 +168,16 @@ class Serializer } // DEPRECATED - uint256 + [[nodiscard]] uint256 getSHA512Half() const; // totality functions - Blob const& + [[nodiscard]] Blob const& peekData() const { return mData; } - Blob + [[nodiscard]] Blob getData() const { return mData; @@ -188,12 +188,12 @@ class Serializer return mData; } - int + [[nodiscard]] int getDataLength() const { return mData.size(); } - void const* + [[nodiscard]] void const* getDataPtr() const { return mData.data(); @@ -203,12 +203,12 @@ class Serializer { return mData.data(); } - int + [[nodiscard]] int getLength() const { return mData.size(); } - std::string + [[nodiscard]] std::string getString() const { return std::string(static_cast(getDataPtr()), size()); @@ -232,12 +232,12 @@ class Serializer { return mData.end(); } - Blob ::const_iterator + [[nodiscard]] Blob ::const_iterator begin() const { return mData.begin(); } - Blob ::const_iterator + [[nodiscard]] Blob ::const_iterator end() const { return mData.end(); @@ -252,7 +252,7 @@ class Serializer { mData.resize(n); } - size_t + [[nodiscard]] size_t capacity() const { return mData.capacity(); @@ -345,7 +345,7 @@ class SerialIter void reset() noexcept; - int + [[nodiscard]] int getBytesLeft() const noexcept { return static_cast(remain_); diff --git a/include/xrpl/protocol/TxMeta.h b/include/xrpl/protocol/TxMeta.h index a295eb4569f..31be3bdb479 100644 --- a/include/xrpl/protocol/TxMeta.h +++ b/include/xrpl/protocol/TxMeta.h @@ -18,27 +18,27 @@ class TxMeta TxMeta(uint256 const& txID, std::uint32_t ledger, Blob const&); TxMeta(uint256 const& txID, std::uint32_t ledger, STObject const&); - uint256 const& + [[nodiscard]] uint256 const& getTxID() const { return transactionID_; } - std::uint32_t + [[nodiscard]] std::uint32_t getLgrSeq() const { return ledgerSeq_; } - int + [[nodiscard]] int getResult() const { return result_; } - TER + [[nodiscard]] TER getResultTER() const { return TER::fromInt(result_); } - std::uint32_t + [[nodiscard]] std::uint32_t getIndex() const { return index_; @@ -52,10 +52,10 @@ class TxMeta getAffectedNode(uint256 const&); /** Return a list of accounts affected by this transaction */ - boost::container::flat_set + [[nodiscard]] boost::container::flat_set getAffectedAccounts() const; - Json::Value + [[nodiscard]] Json::Value getJson(JsonOptions p) const { return getAsObject().getJson(p); @@ -63,14 +63,14 @@ class TxMeta void addRaw(Serializer&, TER, std::uint32_t index); - STObject + [[nodiscard]] STObject getAsObject() const; STArray& getNodes() { return nodes_; } - STArray const& + [[nodiscard]] STArray const& getNodes() const { return nodes_; @@ -86,7 +86,7 @@ class TxMeta parentBatchID_ = obj.getFieldH256(sfParentBatchID); } - std::optional const& + [[nodiscard]] std::optional const& getDeliveredAmount() const { return deliveredAmount_; diff --git a/include/xrpl/protocol/Units.h b/include/xrpl/protocol/Units.h index b606ca2cdfa..8faabd71386 100644 --- a/include/xrpl/protocol/Units.h +++ b/include/xrpl/protocol/Units.h @@ -264,7 +264,7 @@ class ValueUnit : private boost::totally_ordered>, } /** Return the sign of the amount */ - constexpr int + [[nodiscard]] constexpr int signum() const noexcept { if (value_ < 0) @@ -274,14 +274,14 @@ class ValueUnit : private boost::totally_ordered>, /** Returns the number of drops */ // TODO: Move this to a new class, maybe with the old "TaggedFee" name - constexpr value_type + [[nodiscard]] constexpr value_type fee() const { return value_; } template - constexpr double + [[nodiscard]] constexpr double decimalFromReference(ValueUnit reference) const { return static_cast(value_) / reference.value(); @@ -291,7 +291,7 @@ class ValueUnit : private boost::totally_ordered>, // known valid type tags can be converted to JSON. At the time // of implementation, that includes all known tags, but more may // be added in the future. - Json::Value + [[nodiscard]] Json::Value jsonClipped() const requires Usable { @@ -319,7 +319,7 @@ class ValueUnit : private boost::totally_ordered>, function unless the type has been abstracted away, e.g. in a templated function. */ - constexpr value_type + [[nodiscard]] constexpr value_type value() const { return value_; diff --git a/include/xrpl/protocol/XChainAttestations.h b/include/xrpl/protocol/XChainAttestations.h index 44a2334ca09..83bb6267a24 100644 --- a/include/xrpl/protocol/XChainAttestations.h +++ b/include/xrpl/protocol/XChainAttestations.h @@ -58,7 +58,7 @@ struct AttestationBase operator=(AttestationBase const&) = default; // verify that the signature attests to the data. - bool + [[nodiscard]] bool verify(STXChainBridge const& bridge) const; protected: @@ -285,7 +285,7 @@ struct XChainClaimAttestation explicit XChainClaimAttestation(Json::Value const& v); - AttestationMatch + [[nodiscard]] AttestationMatch match(MatchFields const& rhs) const; [[nodiscard]] STObject @@ -336,7 +336,7 @@ struct XChainCreateAccountAttestation [[nodiscard]] STObject toSTObject() const; - AttestationMatch + [[nodiscard]] AttestationMatch match(MatchFields const& rhs) const; friend bool @@ -379,10 +379,10 @@ class XChainAttestationsBase [[nodiscard]] STArray toSTArray() const; - typename AttCollection::const_iterator + [[nodiscard]] typename AttCollection::const_iterator begin() const; - typename AttCollection::const_iterator + [[nodiscard]] typename AttCollection::const_iterator end() const; typename AttCollection::iterator @@ -395,13 +395,13 @@ class XChainAttestationsBase std::size_t erase_if(F&& f); - std::size_t + [[nodiscard]] std::size_t size() const; - bool + [[nodiscard]] bool empty() const; - AttCollection const& + [[nodiscard]] AttCollection const& attestations() const; template diff --git a/include/xrpl/protocol/XRPAmount.h b/include/xrpl/protocol/XRPAmount.h index 0cb5121ef1d..bc7ef891dc3 100644 --- a/include/xrpl/protocol/XRPAmount.h +++ b/include/xrpl/protocol/XRPAmount.h @@ -146,7 +146,7 @@ class XRPAmount : private boost::totally_ordered, } /** Return the sign of the amount */ - constexpr int + [[nodiscard]] constexpr int signum() const noexcept { if (drops_ < 0) @@ -155,17 +155,17 @@ class XRPAmount : private boost::totally_ordered, } /** Returns the number of drops */ - constexpr value_type + [[nodiscard]] constexpr value_type drops() const { return drops_; } - constexpr double + [[nodiscard]] constexpr double decimalXRP() const; template - std::optional + [[nodiscard]] std::optional dropsAs() const { if ((drops_ > std::numeric_limits::max()) || @@ -185,7 +185,7 @@ class XRPAmount : private boost::totally_ordered, } template - Dest + [[nodiscard]] Dest dropsAs(XRPAmount defaultValue) const { return dropsAs().value_or(defaultValue.drops()); @@ -195,7 +195,7 @@ class XRPAmount : private boost::totally_ordered, * in contexts that don't expect the value to ever approach * the 32-bit limits (i.e. fees and reserves). */ - Json::Value + [[nodiscard]] Json::Value jsonClipped() const { static_assert( @@ -216,7 +216,7 @@ class XRPAmount : private boost::totally_ordered, function unless the type has been abstracted away, e.g. in a templated function. */ - constexpr value_type + [[nodiscard]] constexpr value_type value() const { return drops_; diff --git a/include/xrpl/protocol/detail/STVar.h b/include/xrpl/protocol/detail/STVar.h index 5526aed8fa4..c819740a90d 100644 --- a/include/xrpl/protocol/detail/STVar.h +++ b/include/xrpl/protocol/detail/STVar.h @@ -78,7 +78,7 @@ class STVar { return &get(); } - STBase const& + [[nodiscard]] STBase const& get() const { return *p_; @@ -129,7 +129,7 @@ class STVar void constructST(SerializedTypeID id, int depth, Args&&... arg); - bool + [[nodiscard]] bool on_heap() const { return static_cast(p_) != static_cast(&d_); diff --git a/include/xrpl/protocol/detail/token_errors.h b/include/xrpl/protocol/detail/token_errors.h index 5511fb06b33..a663d145b16 100644 --- a/include/xrpl/protocol/detail/token_errors.h +++ b/include/xrpl/protocol/detail/token_errors.h @@ -30,13 +30,13 @@ class TokenCodecErrcCategory : public std::error_category { public: // Return a short descriptive name for the category - char const* + [[nodiscard]] char const* name() const noexcept final { return "TokenCodecError"; } // Return what each enum means in text - std::string + [[nodiscard]] std::string message(int c) const final { switch (static_cast(c)) diff --git a/include/xrpl/rdb/DatabaseCon.h b/include/xrpl/rdb/DatabaseCon.h index 579f30516b3..08376f0e718 100644 --- a/include/xrpl/rdb/DatabaseCon.h +++ b/include/xrpl/rdb/DatabaseCon.h @@ -77,7 +77,7 @@ class DatabaseCon // from commonPragma() bool useGlobalPragma = false; - std::vector const* + [[nodiscard]] std::vector const* commonPragma() const { XRPL_ASSERT( @@ -92,6 +92,7 @@ class DatabaseCon std::array lgrPragma; }; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) struct CheckpointerSetup { JobQueue* jobQueue{}; diff --git a/include/xrpl/rdb/SociDB.h b/include/xrpl/rdb/SociDB.h index 43086ed9313..e87aa2a182c 100644 --- a/include/xrpl/rdb/SociDB.h +++ b/include/xrpl/rdb/SociDB.h @@ -43,7 +43,7 @@ class DBConfig public: DBConfig(BasicConfig const& config, std::string const& dbName); - std::string + [[nodiscard]] std::string connectionString() const; void open(soci::session& s) const; diff --git a/include/xrpl/resource/Charge.h b/include/xrpl/resource/Charge.h index 436e87e158e..582688260e1 100644 --- a/include/xrpl/resource/Charge.h +++ b/include/xrpl/resource/Charge.h @@ -18,15 +18,15 @@ class Charge Charge(value_type cost, std::string label = std::string()); /** Return the human readable label associated with the charge. */ - std::string const& + [[nodiscard]] std::string const& label() const; /** Return the cost of the charge in Resource::Manager units. */ - value_type + [[nodiscard]] value_type cost() const; /** Converts this charge into a human readable string. */ - std::string + [[nodiscard]] std::string to_string() const; bool diff --git a/include/xrpl/resource/Consumer.h b/include/xrpl/resource/Consumer.h index 21d9f9c74f6..ebb214d1290 100644 --- a/include/xrpl/resource/Consumer.h +++ b/include/xrpl/resource/Consumer.h @@ -25,11 +25,11 @@ class Consumer operator=(Consumer const& other); /** Return a human readable string uniquely identifying this consumer. */ - std::string + [[nodiscard]] std::string to_string() const; /** Returns `true` if this is a privileged endpoint. */ - bool + [[nodiscard]] bool isUnlimited() const; /** Raise the Consumer's privilege level to a Named endpoint. @@ -42,7 +42,7 @@ class Consumer This should be checked upon creation to determine if the consumer should be disconnected immediately. */ - Disposition + [[nodiscard]] Disposition disposition() const; /** Apply a load charge to the consumer. */ diff --git a/include/xrpl/resource/detail/Entry.h b/include/xrpl/resource/detail/Entry.h index 5b2d8b1ba34..89f27b26727 100644 --- a/include/xrpl/resource/detail/Entry.h +++ b/include/xrpl/resource/detail/Entry.h @@ -25,7 +25,7 @@ struct Entry : public beast::List::Node { } - std::string + [[nodiscard]] std::string to_string() const { return getFingerprint(key->address, publicKey); @@ -36,7 +36,7 @@ struct Entry : public beast::List::Node * resource limits applied--it is still possible for certain RPC commands * to be forbidden, but that depends on Role. */ - bool + [[nodiscard]] bool isUnlimited() const { return key->kind == kindUnlimited; diff --git a/include/xrpl/server/Handoff.h b/include/xrpl/server/Handoff.h index 60ed16def4c..eba8c6c4dee 100644 --- a/include/xrpl/server/Handoff.h +++ b/include/xrpl/server/Handoff.h @@ -26,7 +26,7 @@ struct Handoff // When set, this will be sent back std::shared_ptr response; - bool + [[nodiscard]] bool handled() const { return moved || response; diff --git a/include/xrpl/server/InfoSub.h b/include/xrpl/server/InfoSub.h index d45f4d77406..b6dff5983d3 100644 --- a/include/xrpl/server/InfoSub.h +++ b/include/xrpl/server/InfoSub.h @@ -172,7 +172,7 @@ class InfoSub : public CountedObject virtual void send(Json::Value const& jvObj, bool broadcast) = 0; - std::uint64_t + [[nodiscard]] std::uint64_t getSeq() const; void @@ -203,7 +203,7 @@ class InfoSub : public CountedObject void setApiVersion(unsigned int apiVersion); - unsigned int + [[nodiscard]] unsigned int getApiVersion() const noexcept; protected: diff --git a/include/xrpl/server/Manifest.h b/include/xrpl/server/Manifest.h index ce97c57260e..e11d5dc0da5 100644 --- a/include/xrpl/server/Manifest.h +++ b/include/xrpl/server/Manifest.h @@ -102,11 +102,11 @@ struct Manifest operator=(Manifest&& other) = default; /// Returns `true` if manifest signature is valid - bool + [[nodiscard]] bool verify() const; /// Returns hash of serialized manifest data - uint256 + [[nodiscard]] uint256 hash() const; /// Returns `true` if manifest revokes master key @@ -116,15 +116,15 @@ struct Manifest revoked(std::uint32_t sequence); /// Returns `true` if manifest revokes master key - bool + [[nodiscard]] bool revoked() const; /// Returns manifest signature - std::optional + [[nodiscard]] std::optional getSignature() const; /// Returns manifest master key signature - Blob + [[nodiscard]] Blob getMasterSignature() const; }; diff --git a/include/xrpl/server/NetworkOPs.h b/include/xrpl/server/NetworkOPs.h index b8f50dcd42e..c449bd283b4 100644 --- a/include/xrpl/server/NetworkOPs.h +++ b/include/xrpl/server/NetworkOPs.h @@ -90,11 +90,11 @@ class NetworkOPs : public InfoSub::Source // Network information // - virtual OperatingMode + [[nodiscard]] virtual OperatingMode getOperatingMode() const = 0; - virtual std::string + [[nodiscard]] virtual std::string strOperatingMode(OperatingMode const mode, bool const admin = false) const = 0; - virtual std::string + [[nodiscard]] virtual std::string strOperatingMode(bool const admin = false) const = 0; //-------------------------------------------------------------------------- diff --git a/include/xrpl/server/Port.h b/include/xrpl/server/Port.h index 93652d422ae..515846b2a81 100644 --- a/include/xrpl/server/Port.h +++ b/include/xrpl/server/Port.h @@ -53,15 +53,15 @@ struct Port std::uint16_t ws_queue_limit{}; // Returns `true` if any websocket protocols are specified - bool + [[nodiscard]] bool websockets() const; // Returns `true` if any secure protocols are specified - bool + [[nodiscard]] bool secure() const; // Returns a string containing the list of protocols - std::string + [[nodiscard]] std::string protocols() const; }; diff --git a/include/xrpl/server/WSSession.h b/include/xrpl/server/WSSession.h index 56105739e95..01032359b32 100644 --- a/include/xrpl/server/WSSession.h +++ b/include/xrpl/server/WSSession.h @@ -96,13 +96,13 @@ struct WSSession virtual void run() = 0; - virtual Port const& + [[nodiscard]] virtual Port const& port() const = 0; - virtual http_request_type const& + [[nodiscard]] virtual http_request_type const& request() const = 0; - virtual boost::asio::ip::tcp::endpoint const& + [[nodiscard]] virtual boost::asio::ip::tcp::endpoint const& remote_endpoint() const = 0; /** Send a WebSockets message. */ diff --git a/include/xrpl/server/detail/BaseWSPeer.h b/include/xrpl/server/detail/BaseWSPeer.h index 42516172628..aaa47910598 100644 --- a/include/xrpl/server/detail/BaseWSPeer.h +++ b/include/xrpl/server/detail/BaseWSPeer.h @@ -70,19 +70,19 @@ class BaseWSPeer : public BasePeer, public WSSession // WSSession // - Port const& + [[nodiscard]] Port const& port() const override { return this->port_; } - http_request_type const& + [[nodiscard]] http_request_type const& request() const override { return this->request_; } - boost::asio::ip::tcp::endpoint const& + [[nodiscard]] boost::asio::ip::tcp::endpoint const& remote_endpoint() const override { return this->remote_address_; diff --git a/include/xrpl/server/detail/Door.h b/include/xrpl/server/detail/Door.h index 346309f0785..2d95a1c5aa7 100644 --- a/include/xrpl/server/detail/Door.h +++ b/include/xrpl/server/detail/Door.h @@ -132,7 +132,7 @@ class Door : public io_list::work, public std::enable_shared_from_this SHAMapNodeID& operator=(SHAMapNodeID const& other) = default; - bool + [[nodiscard]] bool isRoot() const { return depth_ == 0; } // Get the wire format (256-bit nodeID, 1-byte depth) - std::string + [[nodiscard]] std::string getRawString() const; - unsigned int + [[nodiscard]] unsigned int getDepth() const { return depth_; } - uint256 const& + [[nodiscard]] uint256 const& getNodeID() const { return id_; } - SHAMapNodeID + [[nodiscard]] SHAMapNodeID getChildNodeID(unsigned int m) const; /** diff --git a/include/xrpl/shamap/SHAMapSyncFilter.h b/include/xrpl/shamap/SHAMapSyncFilter.h index b34d160c25f..4104220a3ff 100644 --- a/include/xrpl/shamap/SHAMapSyncFilter.h +++ b/include/xrpl/shamap/SHAMapSyncFilter.h @@ -25,7 +25,7 @@ class SHAMapSyncFilter Blob&& nodeData, SHAMapNodeType type) const = 0; - virtual std::optional + [[nodiscard]] virtual std::optional getNode(SHAMapHash const& nodeHash) const = 0; }; diff --git a/include/xrpl/shamap/detail/TaggedPointer.h b/include/xrpl/shamap/detail/TaggedPointer.h index d7adde4b057..31d5f2ba655 100644 --- a/include/xrpl/shamap/detail/TaggedPointer.h +++ b/include/xrpl/shamap/detail/TaggedPointer.h @@ -192,7 +192,7 @@ class TaggedPointer @param i index of the requested child */ - std::optional + [[nodiscard]] std::optional getChildIndex(std::uint16_t isBranch, int i) const; }; diff --git a/include/xrpl/tx/ApplyContext.h b/include/xrpl/tx/ApplyContext.h index 18179699783..ea936017e0c 100644 --- a/include/xrpl/tx/ApplyContext.h +++ b/include/xrpl/tx/ApplyContext.h @@ -49,7 +49,7 @@ class ApplyContext return *view_; // NOLINT(bugprone-unchecked-optional-access) view_ emplaced in constructor } - ApplyView const& + [[nodiscard]] ApplyView const& view() const { return *view_; // NOLINT(bugprone-unchecked-optional-access) view_ emplaced in constructor @@ -62,7 +62,7 @@ class ApplyContext return *view_; // NOLINT(bugprone-unchecked-optional-access) view_ emplaced in constructor } - ApplyFlags const& + [[nodiscard]] ApplyFlags const& flags() const { return flags_; diff --git a/include/xrpl/tx/Transactor.h b/include/xrpl/tx/Transactor.h index a3b0af821e2..e20ac70850b 100644 --- a/include/xrpl/tx/Transactor.h +++ b/include/xrpl/tx/Transactor.h @@ -135,7 +135,7 @@ class Transactor return ctx_.view(); } - ApplyView const& + [[nodiscard]] ApplyView const& view() const { return ctx_.view(); diff --git a/include/xrpl/tx/applySteps.h b/include/xrpl/tx/applySteps.h index d42ca2c118b..4f857bb7c17 100644 --- a/include/xrpl/tx/applySteps.h +++ b/include/xrpl/tx/applySteps.h @@ -89,42 +89,42 @@ class TxConsequences operator=(TxConsequences&&) = default; /// Fee - XRPAmount + [[nodiscard]] XRPAmount fee() const { return fee_; } /// Potential Spend - XRPAmount const& + [[nodiscard]] XRPAmount const& potentialSpend() const { return potentialSpend_; } /// SeqProxy - SeqProxy + [[nodiscard]] SeqProxy seqProxy() const { return seqProx_; } /// Sequences consumed - std::uint32_t + [[nodiscard]] std::uint32_t sequencesConsumed() const { return sequencesConsumed_; } /// Returns true if the transaction is a blocker. - bool + [[nodiscard]] bool isBlocker() const { return isBlocker_; } // Return the SeqProxy that would follow this. - SeqProxy + [[nodiscard]] SeqProxy followingSeq() const { SeqProxy following = seqProx_; diff --git a/include/xrpl/tx/invariants/AMMInvariant.h b/include/xrpl/tx/invariants/AMMInvariant.h index b15b62cc931..43d9c5ad0a9 100644 --- a/include/xrpl/tx/invariants/AMMInvariant.h +++ b/include/xrpl/tx/invariants/AMMInvariant.h @@ -28,22 +28,22 @@ class ValidAMM finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); private: - bool + [[nodiscard]] bool finalizeBid(bool enforce, beast::Journal const&) const; - bool + [[nodiscard]] bool finalizeVote(bool enforce, beast::Journal const&) const; - bool + [[nodiscard]] bool finalizeCreate(STTx const&, ReadView const&, bool enforce, beast::Journal const&) const; - bool + [[nodiscard]] bool finalizeDelete(bool enforce, TER res, beast::Journal const&) const; - bool + [[nodiscard]] bool finalizeDeposit(STTx const&, ReadView const&, bool enforce, beast::Journal const&) const; // Includes clawback - bool + [[nodiscard]] bool finalizeWithdraw(STTx const&, ReadView const&, bool enforce, beast::Journal const&) const; - bool + [[nodiscard]] bool finalizeDEX(bool enforce, beast::Journal const&) const; - bool + [[nodiscard]] bool generalInvariant(STTx const&, ReadView const&, ZeroAllowed zeroAllowed, beast::Journal const&) const; }; diff --git a/include/xrpl/tx/invariants/InvariantCheck.h b/include/xrpl/tx/invariants/InvariantCheck.h index ad4c5e16c43..028a110acdb 100644 --- a/include/xrpl/tx/invariants/InvariantCheck.h +++ b/include/xrpl/tx/invariants/InvariantCheck.h @@ -132,7 +132,7 @@ class XRPNotCreated void visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); - bool + [[nodiscard]] bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; }; @@ -152,7 +152,7 @@ class AccountRootsNotDeleted void visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); - bool + [[nodiscard]] bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; }; @@ -198,7 +198,7 @@ class XRPBalanceChecks void visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); - bool + [[nodiscard]] bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; }; @@ -215,7 +215,7 @@ class LedgerEntryTypesMatch void visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); - bool + [[nodiscard]] bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; }; @@ -233,7 +233,7 @@ class NoXRPTrustLines void visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); - bool + [[nodiscard]] bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; }; @@ -252,7 +252,7 @@ class NoDeepFreezeTrustLinesWithoutFreeze void visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); - bool + [[nodiscard]] bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; }; @@ -271,7 +271,7 @@ class NoBadOffers void visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); - bool + [[nodiscard]] bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; }; @@ -287,7 +287,7 @@ class NoZeroEscrow void visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); - bool + [[nodiscard]] bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; }; @@ -307,7 +307,7 @@ class ValidNewAccountRoot void visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); - bool + [[nodiscard]] bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; }; @@ -328,7 +328,7 @@ class ValidClawback void visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); - bool + [[nodiscard]] bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; }; diff --git a/include/xrpl/tx/invariants/MPTInvariant.h b/include/xrpl/tx/invariants/MPTInvariant.h index dd064af3964..e3aa06016a8 100644 --- a/include/xrpl/tx/invariants/MPTInvariant.h +++ b/include/xrpl/tx/invariants/MPTInvariant.h @@ -24,7 +24,7 @@ class ValidMPTIssuance void visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); - bool + [[nodiscard]] bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; }; diff --git a/include/xrpl/tx/invariants/NFTInvariant.h b/include/xrpl/tx/invariants/NFTInvariant.h index 5bb5f90437a..527b0e80976 100644 --- a/include/xrpl/tx/invariants/NFTInvariant.h +++ b/include/xrpl/tx/invariants/NFTInvariant.h @@ -35,7 +35,7 @@ class ValidNFTokenPage void visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); - bool + [[nodiscard]] bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; }; @@ -63,7 +63,7 @@ class NFTokenCountTracking void visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); - bool + [[nodiscard]] bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; }; diff --git a/include/xrpl/tx/paths/AMMLiquidity.h b/include/xrpl/tx/paths/AMMLiquidity.h index 128052f8517..d7a62dce65e 100644 --- a/include/xrpl/tx/paths/AMMLiquidity.h +++ b/include/xrpl/tx/paths/AMMLiquidity.h @@ -60,40 +60,40 @@ class AMMLiquidity * If clobQuality is provided then AMM offer size is set based on the * quality. */ - std::optional> + [[nodiscard]] std::optional> getOffer(ReadView const& view, std::optional const& clobQuality) const; - AccountID const& + [[nodiscard]] AccountID const& ammAccount() const { return ammAccountID_; } - bool + [[nodiscard]] bool multiPath() const { return ammContext_.multiPath(); } - std::uint32_t + [[nodiscard]] std::uint32_t tradingFee() const { return tradingFee_; } - AMMContext& + [[nodiscard]] AMMContext& context() const { return ammContext_; } - Asset const& + [[nodiscard]] Asset const& assetIn() const { return assetIn_; } - Asset const& + [[nodiscard]] Asset const& assetOut() const { return assetOut_; @@ -102,7 +102,7 @@ class AMMLiquidity private: /** Fetches current AMM balances. */ - TAmounts + [[nodiscard]] TAmounts fetchBalances(ReadView const& view) const; /** Generate AMM offers with the offer size based on Fibonacci sequence. @@ -112,7 +112,7 @@ class AMMLiquidity * If the generated offer exceeds the pool balance then the function * throws overflow exception. */ - TAmounts + [[nodiscard]] TAmounts generateFibSeqOffer(TAmounts const& balances) const; /** Generate max offer. @@ -124,7 +124,7 @@ class AMMLiquidity * takerPays = max input amount; * takerGets = swapIn(takerPays). */ - std::optional> + [[nodiscard]] std::optional> maxOffer(TAmounts const& balances, Rules const& rules) const; }; diff --git a/include/xrpl/tx/paths/AMMOffer.h b/include/xrpl/tx/paths/AMMOffer.h index de583a60d6f..bdffec5ab97 100644 --- a/include/xrpl/tx/paths/AMMOffer.h +++ b/include/xrpl/tx/paths/AMMOffer.h @@ -47,34 +47,34 @@ class AMMOffer TAmounts const& balances, Quality const& quality); - Quality + [[nodiscard]] Quality quality() const noexcept { return quality_; } - Asset const& + [[nodiscard]] Asset const& assetIn() const; - Asset const& + [[nodiscard]] Asset const& assetOut() const; - AccountID const& + [[nodiscard]] AccountID const& owner() const; - std::optional + [[nodiscard]] std::optional key() const { return std::nullopt; } - TAmounts const& + [[nodiscard]] TAmounts const& amount() const; void consume(ApplyView& view, TAmounts const& consumed); - bool + [[nodiscard]] bool fully_consumed() const { return consumed_; @@ -84,17 +84,17 @@ class AMMOffer * using current balances. If multi-path then ceil_out using * current quality. */ - TAmounts + [[nodiscard]] TAmounts limitOut(TAmounts const& offerAmount, TOut const& limit, bool roundUp) const; /** Limit in of the provided offer. If one-path then swapIn * using current balances. If multi-path then ceil_in using * current quality. */ - TAmounts + [[nodiscard]] TAmounts limitIn(TAmounts const& offerAmount, TIn const& limit, bool roundUp) const; - QualityFunction + [[nodiscard]] QualityFunction getQualityFunc() const; /** Send funds without incurring the transfer fee @@ -107,7 +107,7 @@ class AMMOffer std::forward(args)..., WaiveTransferFee::Yes, AllowMPTOverflow::Yes); } - bool + [[nodiscard]] bool isFunded() const { // AMM offer is fully funded by the pool @@ -124,7 +124,7 @@ class AMMOffer /** Check the new pool product is greater or equal to the old pool * product or if decreases then within some threshold. */ - bool + [[nodiscard]] bool checkInvariant(TAmounts const& consumed, beast::Journal j) const; }; diff --git a/include/xrpl/tx/paths/BookTip.h b/include/xrpl/tx/paths/BookTip.h index 6a1805e83a2..2d7490d144f 100644 --- a/include/xrpl/tx/paths/BookTip.h +++ b/include/xrpl/tx/paths/BookTip.h @@ -28,25 +28,25 @@ class BookTip /** Create the iterator. */ BookTip(ApplyView& view, Book const& book); - uint256 const& + [[nodiscard]] uint256 const& dir() const noexcept { return m_dir; } - uint256 const& + [[nodiscard]] uint256 const& index() const noexcept { return m_index; } - Quality const& + [[nodiscard]] Quality const& quality() const noexcept { return m_quality; } - SLE::pointer const& + [[nodiscard]] SLE::pointer const& entry() const noexcept { return m_entry; diff --git a/include/xrpl/tx/paths/Offer.h b/include/xrpl/tx/paths/Offer.h index f79f33658bf..7e3eee0430f 100644 --- a/include/xrpl/tx/paths/Offer.h +++ b/include/xrpl/tx/paths/Offer.h @@ -43,14 +43,14 @@ class TOffer offer is partially filled; Subsequent partial fills will use the original quality. */ - Quality + [[nodiscard]] Quality quality() const noexcept { return m_quality; } /** Returns the account id of the offer's owner. */ - AccountID const& + [[nodiscard]] AccountID const& owner() const { return m_account; @@ -59,14 +59,14 @@ class TOffer /** Returns the in and out amounts. Some or all of the out amount may be unfunded. */ - TAmounts const& + [[nodiscard]] TAmounts const& amount() const { return m_amounts; } /** Returns `true` if no more funds can flow through this offer. */ - bool + [[nodiscard]] bool fully_consumed() const { if (m_amounts.in <= beast::zero) @@ -91,34 +91,34 @@ class TOffer view.update(m_entry); } - std::string + [[nodiscard]] std::string id() const { return to_string(m_entry->key()); } - std::optional + [[nodiscard]] std::optional key() const { return m_entry->key(); } - Asset const& + [[nodiscard]] Asset const& assetIn() const; - Asset const& + [[nodiscard]] Asset const& assetOut() const; - TAmounts + [[nodiscard]] TAmounts limitOut(TAmounts const& offerAmount, TOut const& limit, bool roundUp) const; - TAmounts + [[nodiscard]] TAmounts limitIn(TAmounts const& offerAmount, TIn const& limit, bool roundUp) const; template static TER send(Args&&... args); - bool + [[nodiscard]] bool isFunded() const { // Offer owner is issuer; they have unlimited funds if IOU @@ -135,7 +135,7 @@ class TOffer /** Check any required invariant. Limit order book offer * always returns true. */ - bool + [[nodiscard]] bool checkInvariant(TAmounts const& consumed, beast::Journal j) const { if (!isFeatureEnabled(fixAMMv1_3)) diff --git a/include/xrpl/tx/paths/OfferStream.h b/include/xrpl/tx/paths/OfferStream.h index 84dbac9a609..69409b9ef7b 100644 --- a/include/xrpl/tx/paths/OfferStream.h +++ b/include/xrpl/tx/paths/OfferStream.h @@ -39,7 +39,7 @@ class TOfferStreamBase count_++; return true; } - std::uint32_t + [[nodiscard]] std::uint32_t count() const { return count_; @@ -66,7 +66,7 @@ class TOfferStreamBase template requires ValidTaker - bool + [[nodiscard]] bool shouldRmSmallIncreasedQOffer() const; public: @@ -84,7 +84,7 @@ class TOfferStreamBase Offers are always presented in decreasing quality. Only valid if step() returned `true`. */ - TOffer& + [[nodiscard]] TOffer& tip() const { return const_cast(this)->offer_; @@ -100,7 +100,7 @@ class TOfferStreamBase bool step(); - TOut + [[nodiscard]] TOut ownerFunds() const { return *ownerFunds_; // NOLINT(bugprone-unchecked-optional-access) always set after step() @@ -141,7 +141,7 @@ class FlowOfferStream : public TOfferStreamBase void permRmOffer(uint256 const& offerIndex) override; - boost::container::flat_set const& + [[nodiscard]] boost::container::flat_set const& permToRemove() const { return permToRemove_; diff --git a/include/xrpl/tx/paths/RippleCalc.h b/include/xrpl/tx/paths/RippleCalc.h index 55f552a61fe..771467cdc7f 100644 --- a/include/xrpl/tx/paths/RippleCalc.h +++ b/include/xrpl/tx/paths/RippleCalc.h @@ -53,7 +53,7 @@ class RippleCalc TER calculationResult_ = temUNKNOWN; public: - TER + [[nodiscard]] TER result() const { return calculationResult_; diff --git a/include/xrpl/tx/paths/detail/FlowDebugInfo.h b/include/xrpl/tx/paths/detail/FlowDebugInfo.h index 0f4abae2fef..36c0bd7de07 100644 --- a/include/xrpl/tx/paths/detail/FlowDebugInfo.h +++ b/include/xrpl/tx/paths/detail/FlowDebugInfo.h @@ -45,7 +45,7 @@ struct FlowDebugInfo numActive.reserve(s); } - size_t + [[nodiscard]] size_t size() const { return in.size(); @@ -92,7 +92,7 @@ struct FlowDebugInfo passInfo.reserve(64); } - auto + [[nodiscard]] auto duration(std::string const& tag) const { auto i = timePoints.find(tag); @@ -109,7 +109,7 @@ struct FlowDebugInfo return std::chrono::duration_cast>(t.second - t.first); } - std::size_t + [[nodiscard]] std::size_t count(std::string const& tag) const { auto i = counts.find(tag); @@ -158,7 +158,7 @@ struct FlowDebugInfo counts[tag] = c; } - std::size_t + [[nodiscard]] std::size_t passCount() const { return passInfo.size(); @@ -182,7 +182,7 @@ struct FlowDebugInfo passInfo.newLiquidityPass(); } - std::string + [[nodiscard]] std::string to_string(bool writePassInfo) const { std::ostringstream ostr; diff --git a/include/xrpl/tx/paths/detail/Steps.h b/include/xrpl/tx/paths/detail/Steps.h index c46cebca88b..b4d9d6e0b4b 100644 --- a/include/xrpl/tx/paths/detail/Steps.h +++ b/include/xrpl/tx/paths/detail/Steps.h @@ -107,21 +107,21 @@ class Step Amount of currency computed coming into the Step the last time the step ran in reverse. */ - virtual std::optional + [[nodiscard]] virtual std::optional cachedIn() const = 0; /** Amount of currency computed coming out of the Step the last time the step ran in reverse. */ - virtual std::optional + [[nodiscard]] virtual std::optional cachedOut() const = 0; /** If this step is DirectStepI (IOU->IOU direct step), return the src account. This is needed for checkNoRipple. */ - virtual std::optional + [[nodiscard]] virtual std::optional directStepSrcAcct() const { return std::nullopt; @@ -129,7 +129,7 @@ class Step // for debugging. Return the src and dst accounts for a direct step // For XRP endpoints, one of src or dst will be the root account - virtual std::optional> + [[nodiscard]] virtual std::optional> directStepAccts() const { return std::nullopt; @@ -143,13 +143,13 @@ class Step @param sb view with the strand's state of balances and offers @param dir reverse -> called from rev(); forward -> called from fwd(). */ - virtual DebtDirection + [[nodiscard]] virtual DebtDirection debtDirection(ReadView const& sb, StrandDirection dir) const = 0; /** If this step is a DirectStepI, return the quality in of the dst account. */ - virtual std::uint32_t + [[nodiscard]] virtual std::uint32_t lineQualityIn(ReadView const&) const { return QUALITY_ONE; @@ -168,7 +168,7 @@ class Step rather than `qualityUpperBound`. It could still differ from the actual quality, but except for "dust" amounts, it should be a good estimate for the actual quality. */ - virtual std::pair, DebtDirection> + [[nodiscard]] virtual std::pair, DebtDirection> qualityUpperBound(ReadView const& v, DebtDirection prevStepDir) const = 0; /** Get QualityFunction. Used in one path optimization where @@ -178,7 +178,7 @@ class Step * All steps, except for BookStep have the default * implementation. */ - virtual std::pair, DebtDirection> + [[nodiscard]] virtual std::pair, DebtDirection> getQualityFunc(ReadView const& v, DebtDirection prevStepDir) const; /** Return the number of offers consumed or partially consumed the last time @@ -188,7 +188,7 @@ class Step entire payment, it is only the number the last time it ran. Offers may be partially consumed multiple times during a payment. */ - virtual std::uint32_t + [[nodiscard]] virtual std::uint32_t offersUsed() const { return 0; @@ -197,7 +197,7 @@ class Step /** If this step is a BookStep, return the book. */ - virtual std::optional + [[nodiscard]] virtual std::optional bookStepBook() const { return std::nullopt; @@ -206,7 +206,7 @@ class Step /** Check if amount is zero */ - virtual bool + [[nodiscard]] virtual bool isZero(EitherAmount const& out) const = 0; /** @@ -214,7 +214,7 @@ class Step A strand that has additional liquidity may be marked inactive if a step has consumed too many offers. */ - virtual bool + [[nodiscard]] virtual bool inactive() const { return false; @@ -223,13 +223,13 @@ class Step /** Return true if Out of lhs == Out of rhs. */ - virtual bool + [[nodiscard]] virtual bool equalOut(EitherAmount const& lhs, EitherAmount const& rhs) const = 0; /** Return true if In of lhs == In of rhs. */ - virtual bool + [[nodiscard]] virtual bool equalIn(EitherAmount const& lhs, EitherAmount const& rhs) const = 0; /** @@ -278,10 +278,10 @@ class Step } private: - virtual std::string + [[nodiscard]] virtual std::string logString() const = 0; - virtual bool + [[nodiscard]] virtual bool equal(Step const& rhs) const = 0; }; @@ -457,19 +457,19 @@ struct StepImp : public Step return {EitherAmount(r.first), EitherAmount(r.second)}; } - bool + [[nodiscard]] bool isZero(EitherAmount const& out) const override { return get(out) == beast::zero; } - bool + [[nodiscard]] bool equalOut(EitherAmount const& lhs, EitherAmount const& rhs) const override { return get(lhs) == get(rhs); } - bool + [[nodiscard]] bool equalIn(EitherAmount const& lhs, EitherAmount const& rhs) const override { return get(lhs) == get(rhs); diff --git a/include/xrpl/tx/paths/detail/StrandFlow.h b/include/xrpl/tx/paths/detail/StrandFlow.h index 6a8367f4dfd..ee23de27b39 100644 --- a/include/xrpl/tx/paths/detail/StrandFlow.h +++ b/include/xrpl/tx/paths/detail/StrandFlow.h @@ -494,7 +494,7 @@ class ActiveStrands std::swap(cur_, next_); } - Strand const* + [[nodiscard]] Strand const* get(size_t i) const { if (i >= cur_.size()) @@ -522,7 +522,7 @@ class ActiveStrands next_.insert(next_.end(), std::next(cur_.begin(), i), cur_.end()); } - auto + [[nodiscard]] auto size() const { return cur_.size(); diff --git a/include/xrpl/tx/transactors/dex/AMMContext.h b/include/xrpl/tx/transactors/dex/AMMContext.h index b0ff44c5ec2..f582384e128 100644 --- a/include/xrpl/tx/transactors/dex/AMMContext.h +++ b/include/xrpl/tx/transactors/dex/AMMContext.h @@ -39,7 +39,7 @@ class AMMContext AMMContext& operator=(AMMContext const&) = delete; - bool + [[nodiscard]] bool multiPath() const { return multiPath_; @@ -65,19 +65,19 @@ class AMMContext ammUsed_ = false; } - bool + [[nodiscard]] bool maxItersReached() const { return ammIters_ >= MaxIterations; } - std::uint16_t + [[nodiscard]] std::uint16_t curIters() const { return ammIters_; } - AccountID + [[nodiscard]] AccountID account() const { return account_; diff --git a/src/libxrpl/basics/Number.cpp b/src/libxrpl/basics/Number.cpp index 73ab8f63073..3b2b8670cbc 100644 --- a/src/libxrpl/basics/Number.cpp +++ b/src/libxrpl/basics/Number.cpp @@ -79,7 +79,7 @@ class Number::Guard set_positive() noexcept; void set_negative() noexcept; - bool + [[nodiscard]] bool is_negative() const noexcept; // add a digit @@ -94,7 +94,7 @@ class Number::Guard // Indicate round direction: 1 is up, -1 is down, 0 is even // This enables the client to round towards nearest, and on // tie, round towards even. - int + [[nodiscard]] int round() const noexcept; // Modify the result to the correctly rounded value diff --git a/src/libxrpl/beast/utility/beast_Journal.cpp b/src/libxrpl/beast/utility/beast_Journal.cpp index 7164fcfb06a..0d0b5a0d1d7 100644 --- a/src/libxrpl/beast/utility/beast_Journal.cpp +++ b/src/libxrpl/beast/utility/beast_Journal.cpp @@ -18,13 +18,13 @@ class NullJournalSink : public Journal::Sink ~NullJournalSink() override = default; - bool + [[nodiscard]] bool active(severities::Severity) const override { return false; } - bool + [[nodiscard]] bool console() const override { return false; @@ -35,7 +35,7 @@ class NullJournalSink : public Journal::Sink { } - severities::Severity + [[nodiscard]] severities::Severity threshold() const override { return severities::kDisabled; diff --git a/src/libxrpl/conditions/error.cpp b/src/libxrpl/conditions/error.cpp index 15ac847118d..44fc17265a3 100644 --- a/src/libxrpl/conditions/error.cpp +++ b/src/libxrpl/conditions/error.cpp @@ -14,13 +14,13 @@ class cryptoconditions_error_category : public std::error_category public: explicit cryptoconditions_error_category() = default; - char const* + [[nodiscard]] char const* name() const noexcept override { return "cryptoconditions"; } - std::string + [[nodiscard]] std::string message(int ev) const override { switch (safe_cast(ev)) @@ -79,19 +79,19 @@ class cryptoconditions_error_category : public std::error_category } } - std::error_condition + [[nodiscard]] std::error_condition default_error_condition(int ev) const noexcept override { return std::error_condition{ev, *this}; } - bool + [[nodiscard]] bool equivalent(int ev, std::error_condition const& condition) const noexcept override { return &condition.category() == this && condition.value() == ev; } - bool + [[nodiscard]] bool equivalent(std::error_code const& error, int ev) const noexcept override { return &error.category() == this && error.value() == ev; diff --git a/src/libxrpl/json/Writer.cpp b/src/libxrpl/json/Writer.cpp index 75b5bc113ca..b4a85e0170f 100644 --- a/src/libxrpl/json/Writer.cpp +++ b/src/libxrpl/json/Writer.cpp @@ -72,7 +72,7 @@ class Writer::Impl Impl& operator=(Impl&&) = delete; - bool + [[nodiscard]] bool empty() const { return stack_.empty(); @@ -160,7 +160,7 @@ class Writer::Impl output_({&colon, 1}); } - bool + [[nodiscard]] bool isFinished() const { return isStarted_ && empty(); @@ -187,7 +187,7 @@ class Writer::Impl } } - Output const& + [[nodiscard]] Output const& getOutput() const { return output_; diff --git a/src/libxrpl/ledger/Ledger.cpp b/src/libxrpl/ledger/Ledger.cpp index ab092249149..18db4825388 100644 --- a/src/libxrpl/ledger/Ledger.cpp +++ b/src/libxrpl/ledger/Ledger.cpp @@ -69,13 +69,13 @@ class Ledger::sles_iter_impl : public sles_type::iter_base { } - std::unique_ptr + [[nodiscard]] std::unique_ptr copy() const override { return std::make_unique(*this); } - bool + [[nodiscard]] bool equal(base_type const& impl) const override { if (auto const p = dynamic_cast(&impl)) @@ -89,7 +89,7 @@ class Ledger::sles_iter_impl : public sles_type::iter_base ++iter_; } - sles_type::value_type + [[nodiscard]] sles_type::value_type dereference() const override { SerialIter sit(iter_->slice()); @@ -116,13 +116,13 @@ class Ledger::txs_iter_impl : public txs_type::iter_base { } - std::unique_ptr + [[nodiscard]] std::unique_ptr copy() const override { return std::make_unique(*this); } - bool + [[nodiscard]] bool equal(base_type const& impl) const override { if (auto const p = dynamic_cast(&impl)) @@ -136,7 +136,7 @@ class Ledger::txs_iter_impl : public txs_type::iter_base ++iter_; } - txs_type::value_type + [[nodiscard]] txs_type::value_type dereference() const override { auto const& item = *iter_; diff --git a/src/libxrpl/ledger/OpenView.cpp b/src/libxrpl/ledger/OpenView.cpp index 089788d90bb..28da1aedcbf 100644 --- a/src/libxrpl/ledger/OpenView.cpp +++ b/src/libxrpl/ledger/OpenView.cpp @@ -36,13 +36,13 @@ class OpenView::txs_iter_impl : public txs_type::iter_base { } - std::unique_ptr + [[nodiscard]] std::unique_ptr copy() const override { return std::make_unique(metadata_, iter_); } - bool + [[nodiscard]] bool equal(base_type const& impl) const override { if (auto const p = dynamic_cast(&impl)) @@ -56,7 +56,7 @@ class OpenView::txs_iter_impl : public txs_type::iter_base ++iter_; } - value_type + [[nodiscard]] value_type dereference() const override { value_type result; diff --git a/src/libxrpl/nodestore/backend/MemoryFactory.cpp b/src/libxrpl/nodestore/backend/MemoryFactory.cpp index 2f94783b8be..abf25013ce6 100644 --- a/src/libxrpl/nodestore/backend/MemoryFactory.cpp +++ b/src/libxrpl/nodestore/backend/MemoryFactory.cpp @@ -45,7 +45,7 @@ class MemoryFactory : public Factory public: explicit MemoryFactory(Manager& manager); - std::string + [[nodiscard]] std::string getName() const override; std::unique_ptr @@ -207,7 +207,7 @@ class MemoryBackend : public Backend { } - int + [[nodiscard]] int fdRequired() const override { return 0; diff --git a/src/libxrpl/nodestore/backend/NuDBFactory.cpp b/src/libxrpl/nodestore/backend/NuDBFactory.cpp index 7fb3aec843f..86540016dab 100644 --- a/src/libxrpl/nodestore/backend/NuDBFactory.cpp +++ b/src/libxrpl/nodestore/backend/NuDBFactory.cpp @@ -122,7 +122,7 @@ class NuDBBackend : public Backend return name_; } - std::optional + [[nodiscard]] std::optional getBlockSize() const override { return blockSize_; @@ -364,7 +364,7 @@ class NuDBBackend : public Backend Throw(ec); } - int + [[nodiscard]] int fdRequired() const override { return 3; @@ -426,7 +426,7 @@ class NuDBFactory : public Factory manager_.insert(*this); } - std::string + [[nodiscard]] std::string getName() const override { return "NuDB"; diff --git a/src/libxrpl/nodestore/backend/NullFactory.cpp b/src/libxrpl/nodestore/backend/NullFactory.cpp index 94cd71bd11c..02e6ca4ddae 100644 --- a/src/libxrpl/nodestore/backend/NullFactory.cpp +++ b/src/libxrpl/nodestore/backend/NullFactory.cpp @@ -90,7 +90,7 @@ class NullBackend : public Backend } /** Returns the number of file descriptors the backend expects to need */ - int + [[nodiscard]] int fdRequired() const override { return 0; @@ -112,7 +112,7 @@ class NullFactory : public Factory manager_.insert(*this); } - std::string + [[nodiscard]] std::string getName() const override { return "none"; diff --git a/src/libxrpl/nodestore/backend/RocksDBFactory.cpp b/src/libxrpl/nodestore/backend/RocksDBFactory.cpp index 3e0957edeaa..86dff9240de 100644 --- a/src/libxrpl/nodestore/backend/RocksDBFactory.cpp +++ b/src/libxrpl/nodestore/backend/RocksDBFactory.cpp @@ -443,7 +443,7 @@ class RocksDBBackend : public Backend, public BatchWriter::Callback } /** Returns the number of file descriptors the backend expects to need */ - int + [[nodiscard]] int fdRequired() const override { return fdRequired_; @@ -465,7 +465,7 @@ class RocksDBFactory : public Factory manager_.insert(*this); } - std::string + [[nodiscard]] std::string getName() const override { return "RocksDB"; diff --git a/src/libxrpl/protocol/Rules.cpp b/src/libxrpl/protocol/Rules.cpp index a09afa96d8b..7a8d0144bb6 100644 --- a/src/libxrpl/protocol/Rules.cpp +++ b/src/libxrpl/protocol/Rules.cpp @@ -67,13 +67,13 @@ class Rules::Impl set_.insert(amendments.begin(), amendments.end()); } - std::unordered_set> const& + [[nodiscard]] std::unordered_set> const& presets() const { return presets_; } - bool + [[nodiscard]] bool enabled(uint256 const& feature) const { if (presets_.contains(feature)) diff --git a/src/libxrpl/protocol/SecretKey.cpp b/src/libxrpl/protocol/SecretKey.cpp index 01d3c29f9e4..19ec3267ae2 100644 --- a/src/libxrpl/protocol/SecretKey.cpp +++ b/src/libxrpl/protocol/SecretKey.cpp @@ -123,7 +123,7 @@ class Generator uint256 root_; std::array generator_{}; - uint256 + [[nodiscard]] uint256 calculateTweak(std::uint32_t seq) const { // We fill the buffer with the generator, the provided sequence diff --git a/src/libxrpl/tx/paths/BookStep.cpp b/src/libxrpl/tx/paths/BookStep.cpp index ceab3793011..49a5f480345 100644 --- a/src/libxrpl/tx/paths/BookStep.cpp +++ b/src/libxrpl/tx/paths/BookStep.cpp @@ -118,13 +118,13 @@ class BookStep : public StepImp> } public: - Book const& + [[nodiscard]] Book const& book() const { return book_; } - std::optional + [[nodiscard]] std::optional cachedIn() const override { if (!cache_) @@ -132,7 +132,7 @@ class BookStep : public StepImp> return EitherAmount(cache_->in); } - std::optional + [[nodiscard]] std::optional cachedOut() const override { if (!cache_) @@ -140,25 +140,25 @@ class BookStep : public StepImp> return EitherAmount(cache_->out); } - DebtDirection + [[nodiscard]] DebtDirection debtDirection(ReadView const& sb, StrandDirection dir) const override { return ownerPaysTransferFee_ ? DebtDirection::issues : DebtDirection::redeems; } - std::optional + [[nodiscard]] std::optional bookStepBook() const override { return book_; } - std::pair, DebtDirection> + [[nodiscard]] std::pair, DebtDirection> qualityUpperBound(ReadView const& v, DebtDirection prevStepDir) const override; - std::pair, DebtDirection> + [[nodiscard]] std::pair, DebtDirection> getQualityFunc(ReadView const& v, DebtDirection prevStepDir) const override; - std::uint32_t + [[nodiscard]] std::uint32_t offersUsed() const override; std::pair @@ -179,10 +179,10 @@ class BookStep : public StepImp> validFwd(PaymentSandbox& sb, ApplyView& afView, EitherAmount const& in) override; // Check for errors frozen constraints. - TER + [[nodiscard]] TER check(StrandContext const& ctx) const; - bool + [[nodiscard]] bool inactive() const override { return inactive_; @@ -199,7 +199,7 @@ class BookStep : public StepImp> return ostr.str(); } - Rate + [[nodiscard]] Rate rate(ReadView const& view, Asset const& asset, AccountID const& dstAccount) const; private: @@ -215,7 +215,7 @@ class BookStep : public StepImp> return !(lhs == rhs); } - bool + [[nodiscard]] bool equal(Step const& rhs) const override; // Iterate through the offers at the best quality in a book. @@ -258,12 +258,12 @@ class BookStep : public StepImp> tipOfferQuality(ReadView const& view) const; // If seated then it is either AMM or CLOB quality function, // whichever is a better quality. - std::optional + [[nodiscard]] std::optional tipOfferQualityF(ReadView const& view) const; // Check that takerPays/takerGets can be transferred/traded. // Applies to MPT assets. - bool + [[nodiscard]] bool checkMPTDEX(ReadView const& view, AccountID const& owner) const; friend TDerived; @@ -307,7 +307,7 @@ class BookPaymentStep : public BookStep> } // A payment can look at offers of any quality - bool + [[nodiscard]] bool checkQualityThreshold(Quality const& quality) const { return true; @@ -315,7 +315,7 @@ class BookPaymentStep : public BookStep> // A payment doesn't use quality threshold (limitQuality) // since the strand's quality doesn't directly relate to the step's quality. - std::optional + [[nodiscard]] std::optional qualityThreshold(Quality const& lobQuality) const { return lobQuality; @@ -335,7 +335,7 @@ class BookPaymentStep : public BookStep> return trOut; } - Quality + [[nodiscard]] Quality adjustQualityWithFees( ReadView const& v, Quality const& ofrQ, @@ -361,7 +361,7 @@ class BookPaymentStep : public BookStep> return composed_quality(q1, ofrQ); } - std::string + [[nodiscard]] std::string logString() const override { return this->logStringImpl("BookPaymentStep"); @@ -455,7 +455,7 @@ class BookOfferCrossingStep : public BookStep= qualityThreshold_; @@ -471,7 +471,7 @@ class BookOfferCrossingStep : public BookStep + [[nodiscard]] std::optional qualityThreshold(Quality const& lobQuality) const { if (this->ammLiquidity_ && !this->ammLiquidity_->multiPath() && @@ -507,7 +507,7 @@ class BookOfferCrossingStep : public BookSteplogStringImpl("BookOfferCrossingStep"); diff --git a/src/libxrpl/tx/paths/DirectStep.cpp b/src/libxrpl/tx/paths/DirectStep.cpp index 1692f507810..a6f74c9c9f4 100644 --- a/src/libxrpl/tx/paths/DirectStep.cpp +++ b/src/libxrpl/tx/paths/DirectStep.cpp @@ -70,19 +70,19 @@ class DirectStepI : public StepImp> // the best available quality. // return: first element is max amount that can flow, // second is the debt direction of the source w.r.t. the dst - std::pair + [[nodiscard]] std::pair maxPaymentFlow(ReadView const& sb) const; // Compute srcQOut and dstQIn when the source redeems. - std::pair + [[nodiscard]] std::pair qualitiesSrcRedeems(ReadView const& sb) const; // Compute srcQOut and dstQIn when the source issues. - std::pair + [[nodiscard]] std::pair qualitiesSrcIssues(ReadView const& sb, DebtDirection prevStepDebtDirection) const; // Returns srcQOut, dstQIn - std::pair + [[nodiscard]] std::pair qualities(ReadView const& sb, DebtDirection srcDebtDir, StrandDirection strandDir) const; private: @@ -101,23 +101,23 @@ class DirectStepI : public StepImp> } public: - AccountID const& + [[nodiscard]] AccountID const& src() const { return src_; } - AccountID const& + [[nodiscard]] AccountID const& dst() const { return dst_; } - Currency const& + [[nodiscard]] Currency const& currency() const { return currency_; } - std::optional + [[nodiscard]] std::optional cachedIn() const override { if (!cache_) @@ -125,7 +125,7 @@ class DirectStepI : public StepImp> return EitherAmount(cache_->in); } - std::optional + [[nodiscard]] std::optional cachedOut() const override { if (!cache_) @@ -133,25 +133,25 @@ class DirectStepI : public StepImp> return EitherAmount(cache_->out); } - std::optional + [[nodiscard]] std::optional directStepSrcAcct() const override { return src_; } - std::optional> + [[nodiscard]] std::optional> directStepAccts() const override { return std::make_pair(src_, dst_); } - DebtDirection + [[nodiscard]] DebtDirection debtDirection(ReadView const& sb, StrandDirection dir) const override; - std::uint32_t + [[nodiscard]] std::uint32_t lineQualityIn(ReadView const& v) const override; - std::pair, DebtDirection> + [[nodiscard]] std::pair, DebtDirection> qualityUpperBound(ReadView const& v, DebtDirection dir) const override; std::pair @@ -173,7 +173,7 @@ class DirectStepI : public StepImp> // Check for error, existing liquidity, and violations of auth/frozen // constraints. - TER + [[nodiscard]] TER check(StrandContext const& ctx) const; void @@ -206,7 +206,7 @@ class DirectStepI : public StepImp> } private: - bool + [[nodiscard]] bool equal(Step const& rhs) const override { if (auto ds = dynamic_cast(&rhs)) @@ -256,22 +256,22 @@ class DirectIPaymentStep : public DirectStepI return true; } - std::uint32_t + [[nodiscard]] std::uint32_t quality(ReadView const& sb, QualityDirection qDir) const; // Compute the maximum value that can flow from src->dst at // the best available quality. // return: first element is max amount that can flow, // second is the debt direction w.r.t. the source account - std::pair + [[nodiscard]] std::pair maxFlow(ReadView const& sb, IOUAmount const& desired) const; // Verify the consistency of the step. These checks are specific to // payments and assume that general checks were already performed. - TER + [[nodiscard]] TER check(StrandContext const& ctx, std::shared_ptr const& sleSrc) const; - std::string + [[nodiscard]] std::string logString() const override { return logStringImpl("DirectIPaymentStep"); @@ -321,7 +321,7 @@ class DirectIOfferCrossingStep : public DirectStepI // the best available quality. // return: first element is max amount that can flow, // second is the debt direction w.r.t the source - std::pair + [[nodiscard]] std::pair maxFlow(ReadView const& sb, IOUAmount const& desired) const; // Verify the consistency of the step. These checks are specific to @@ -329,7 +329,7 @@ class DirectIOfferCrossingStep : public DirectStepI static TER check(StrandContext const& ctx, std::shared_ptr const& sleSrc); - std::string + [[nodiscard]] std::string logString() const override { return logStringImpl("DirectIOfferCrossingStep"); diff --git a/src/libxrpl/tx/paths/MPTEndpointStep.cpp b/src/libxrpl/tx/paths/MPTEndpointStep.cpp index aa989b27e02..a79df254794 100644 --- a/src/libxrpl/tx/paths/MPTEndpointStep.cpp +++ b/src/libxrpl/tx/paths/MPTEndpointStep.cpp @@ -71,19 +71,19 @@ class MPTEndpointStep : public StepImp + [[nodiscard]] std::pair maxPaymentFlow(ReadView const& sb) const; // Compute srcQOut and dstQIn when the source redeems. - std::pair + [[nodiscard]] std::pair qualitiesSrcRedeems(ReadView const& sb) const; // Compute srcQOut and dstQIn when the source issues. - std::pair + [[nodiscard]] std::pair qualitiesSrcIssues(ReadView const& sb, DebtDirection prevStepDebtDirection) const; // Returns srcQOut, dstQIn - std::pair + [[nodiscard]] std::pair qualities(ReadView const& sb, DebtDirection srcDebtDir, StrandDirection strandDir) const; void @@ -112,23 +112,23 @@ class MPTEndpointStep : public StepImp + [[nodiscard]] std::optional cachedIn() const override { if (!cache_) @@ -136,7 +136,7 @@ class MPTEndpointStep : public StepImpin); } - std::optional + [[nodiscard]] std::optional cachedOut() const override { if (!cache_) @@ -144,25 +144,25 @@ class MPTEndpointStep : public StepImpout); } - std::optional + [[nodiscard]] std::optional directStepSrcAcct() const override { return src_; } - std::optional> + [[nodiscard]] std::optional> directStepAccts() const override { return std::make_pair(src_, dst_); } - DebtDirection + [[nodiscard]] DebtDirection debtDirection(ReadView const& sb, StrandDirection dir) const override; - std::uint32_t + [[nodiscard]] std::uint32_t lineQualityIn(ReadView const& v) const override; - std::pair, DebtDirection> + [[nodiscard]] std::pair, DebtDirection> qualityUpperBound(ReadView const& v, DebtDirection dir) const override; std::pair @@ -184,7 +184,7 @@ class MPTEndpointStep : public StepImp(&rhs)) @@ -263,10 +263,10 @@ class MPTEndpointPaymentStep : public MPTEndpointStep // Verify the consistency of the step. These checks are specific to // payments and assume that general checks were already performed. - TER + [[nodiscard]] TER check(StrandContext const& ctx, std::shared_ptr const& sleSrc) const; - std::string + [[nodiscard]] std::string logString() const override { return logStringImpl("MPTEndpointPaymentStep"); @@ -314,7 +314,7 @@ class MPTEndpointOfferCrossingStep : public MPTEndpointStep const& sleSrc); - std::string + [[nodiscard]] std::string logString() const override { return logStringImpl("MPTEndpointOfferCrossingStep"); diff --git a/src/libxrpl/tx/paths/OfferStream.cpp b/src/libxrpl/tx/paths/OfferStream.cpp index 0d003c63f7b..c2f2fed25b4 100644 --- a/src/libxrpl/tx/paths/OfferStream.cpp +++ b/src/libxrpl/tx/paths/OfferStream.cpp @@ -132,7 +132,7 @@ accountFundsHelper( template template requires ValidTaker -bool +[[nodiscard]] bool TOfferStreamBase::shouldRmSmallIncreasedQOffer() const { // Consider removing the offer if: diff --git a/src/libxrpl/tx/paths/XRPEndpointStep.cpp b/src/libxrpl/tx/paths/XRPEndpointStep.cpp index 6356eb8ded8..95228ed1588 100644 --- a/src/libxrpl/tx/paths/XRPEndpointStep.cpp +++ b/src/libxrpl/tx/paths/XRPEndpointStep.cpp @@ -45,7 +45,7 @@ class XRPEndpointStep : public StepImp cache_; - std::optional + [[nodiscard]] std::optional cached() const { if (!cache_) @@ -59,13 +59,13 @@ class XRPEndpointStep : public StepImp> + [[nodiscard]] std::optional> directStepAccts() const override { if (isLast_) @@ -73,25 +73,25 @@ class XRPEndpointStep : public StepImp + [[nodiscard]] std::optional cachedIn() const override { return cached(); } - std::optional + [[nodiscard]] std::optional cachedOut() const override { return cached(); } - DebtDirection + [[nodiscard]] DebtDirection debtDirection(ReadView const& sb, StrandDirection dir) const override { return DebtDirection::issues; } - std::pair, DebtDirection> + [[nodiscard]] std::pair, DebtDirection> qualityUpperBound(ReadView const& v, DebtDirection prevStepDir) const override; std::pair @@ -112,7 +112,7 @@ class XRPEndpointStep : public StepImp(&rhs)) @@ -179,7 +179,7 @@ class XRPEndpointPaymentStep : public XRPEndpointStep ; } - std::string + [[nodiscard]] std::string logString() const override { return logStringImpl("XRPEndpointPaymentStep"); @@ -230,7 +230,7 @@ class XRPEndpointOfferCrossingStep : public XRPEndpointStep 0 && expBobSellUSD < 100 ? 1 : 0; diff --git a/src/test/app/LedgerReplay_test.cpp b/src/test/app/LedgerReplay_test.cpp index aec0bec5922..7766be35453 100644 --- a/src/test/app/LedgerReplay_test.cpp +++ b/src/test/app/LedgerReplay_test.cpp @@ -235,7 +235,7 @@ class TestPeer : public Peer send(std::shared_ptr const& m) override { } - beast::IP::Endpoint + [[nodiscard]] beast::IP::Endpoint getRemoteAddress() const override { return {}; @@ -244,27 +244,27 @@ class TestPeer : public Peer charge(Resource::Charge const& fee, std::string const& context = {}) override { } - id_t + [[nodiscard]] id_t id() const override { return 1234; } - bool + [[nodiscard]] bool cluster() const override { return false; } - bool + [[nodiscard]] bool isHighLatency() const override { return false; } - int + [[nodiscard]] int getScore(bool) const override { return 0; } - PublicKey const& + [[nodiscard]] PublicKey const& getNodePublic() const override { return nodePublicKey_; @@ -274,12 +274,12 @@ class TestPeer : public Peer { return {}; } - bool + [[nodiscard]] bool supportsFeature(ProtocolFeature f) const override { return f == ProtocolFeature::LedgerReplay && ledgerReplayEnabled_; } - std::optional + [[nodiscard]] std::optional publisherListSequence(PublicKey const&) const override { return {}; @@ -288,13 +288,13 @@ class TestPeer : public Peer setPublisherListSequence(PublicKey const&, std::size_t const) override { } - uint256 const& + [[nodiscard]] uint256 const& getClosedLedgerHash() const override { static uint256 const hash{}; return hash; } - bool + [[nodiscard]] bool hasLedger(uint256 const& hash, std::uint32_t seq) const override { return true; @@ -303,7 +303,7 @@ class TestPeer : public Peer ledgerRange(std::uint32_t& minSeq, std::uint32_t& maxSeq) const override { } - bool + [[nodiscard]] bool hasTxSet(uint256 const& hash) const override { return false; @@ -317,7 +317,7 @@ class TestPeer : public Peer { return false; } - bool + [[nodiscard]] bool compressionEnabled() const override { return false; @@ -334,13 +334,13 @@ class TestPeer : public Peer removeTxQueue(uint256 const&) override { } - bool + [[nodiscard]] bool txReduceRelayEnabled() const override { return false; } - std::string const& + [[nodiscard]] std::string const& fingerprint() const override { return fingerprint_; @@ -440,7 +440,7 @@ struct TestPeerSet : public PeerSet } } - std::set const& + [[nodiscard]] std::set const& getPeerIds() const override { static std::set const emptyPeers; diff --git a/src/test/app/Loan_test.cpp b/src/test/app/Loan_test.cpp index a6d642badcd..3fe727e3689 100644 --- a/src/test/app/Loan_test.cpp +++ b/src/test/app/Loan_test.cpp @@ -151,7 +151,7 @@ class Loan_test : public beast::unit_test::suite std::string data = {}; // NOLINT(readability-redundant-member-init) std::uint32_t flags = 0; - Number + [[nodiscard]] Number maxCoveredLoanValue(Number const& currentDebt) const { NumberRoundModeGuard const mg(Number::downward); @@ -189,18 +189,18 @@ class Loan_test : public beast::unit_test::suite { } - Keylet + [[nodiscard]] Keylet brokerKeylet() const { return keylet::loanbroker(brokerID); } - Keylet + [[nodiscard]] Keylet vaultKeylet() const { return keylet::vault(vaultID); } - int + [[nodiscard]] int vaultScale(jtx::Env const& env) const { using namespace jtx; diff --git a/src/test/app/PayStrand_test.cpp b/src/test/app/PayStrand_test.cpp index 24efb4b1557..161903ee6d5 100644 --- a/src/test/app/PayStrand_test.cpp +++ b/src/test/app/PayStrand_test.cpp @@ -117,13 +117,13 @@ class ElementComboIter // some tests) bool const allowCompound_ = false; - bool + [[nodiscard]] bool has(SB s) const { return (state_ & (1 << safe_cast(s))) != 0; } - bool + [[nodiscard]] bool hasAny(std::initializer_list sb) const { for (auto const s : sb) @@ -134,7 +134,7 @@ class ElementComboIter return false; } - size_t + [[nodiscard]] size_t count(std::initializer_list sb) const { size_t result = 0; @@ -152,7 +152,7 @@ class ElementComboIter { } - bool + [[nodiscard]] bool valid() const { return (allowCompound_ || !(has(SB::acc) && hasAny({SB::cur, SB::iss}))) && @@ -263,7 +263,7 @@ struct ExistingElementPool size_t nextAvailCurrency = 0; using ResetState = std::tuple; - ResetState + [[nodiscard]] ResetState getResetState() const { return std::make_tuple(nextAvailAccount, nextAvailCurrency); diff --git a/src/test/app/RCLValidations_test.cpp b/src/test/app/RCLValidations_test.cpp index 164ded61388..14b9979e075 100644 --- a/src/test/app/RCLValidations_test.cpp +++ b/src/test/app/RCLValidations_test.cpp @@ -272,7 +272,7 @@ class RCLValidations_test : public beast::unit_test::suite // due to the 256 ancestry limit BEAST_EXPECT(trie.remove(ledg_258, 3)); trie.insert(ledg_259, 3); - trie.getPreferred(1); + [[maybe_unused]] auto unused1 = trie.getPreferred(1); // trie.dump(std::cout); // 000000[0,1)(T:0,B:5) // |-AB868A..37C9[1,260)(T:3,B:3) @@ -296,7 +296,7 @@ class RCLValidations_test : public beast::unit_test::suite BEAST_EXPECT(trie.remove(RCLValidatedLedger{history[257], env.journal}, 1)); trie.insert(RCLValidatedLedger{history[258], env.journal}, 1); - trie.getPreferred(1); + [[maybe_unused]] auto unused2 = trie.getPreferred(1); // trie.dump(std::cout); // 000000[0,1)(T:0,B:5) // |-AB868A..37C9[1,260)(T:4,B:4) diff --git a/src/test/app/XChain_test.cpp b/src/test/app/XChain_test.cpp index 852bbbbb8b9..3f49ab42bbb 100644 --- a/src/test/app/XChain_test.cpp +++ b/src/test/app/XChain_test.cpp @@ -120,19 +120,19 @@ struct SEnv return *this; } - TER + [[nodiscard]] TER ter() const { return env_.ter(); } - STAmount + [[nodiscard]] STAmount balance(jtx::Account const& account) const { return env_.balance(account).value(); } - STAmount + [[nodiscard]] STAmount balance(jtx::Account const& account, Issue const& issue) const { return env_.balance(account, issue).value(); @@ -250,7 +250,7 @@ struct Balance startAmount = env_.balance(account_); } - STAmount + [[nodiscard]] STAmount diff() const { return env_.balance(account_) - startAmount; @@ -303,7 +303,7 @@ struct BalanceTransfer { } - bool + [[nodiscard]] bool payees_received(STAmount const& reward) const { return std::all_of(reward_accounts.begin(), reward_accounts.end(), [&](balance const& b) { @@ -3954,7 +3954,7 @@ struct XChainSim_test : public beast::unit_test::suite, public jtx::XChainBridge spend(acct, tx_fee, times); } - bool + [[nodiscard]] bool verify() const { for (auto const& [acct, state] : accounts) @@ -4001,7 +4001,7 @@ struct XChainSim_test : public beast::unit_test::suite, public jtx::XChainBridge { } - bool + [[nodiscard]] bool verify() const { return a_.verify() && b_.verify(); @@ -4091,7 +4091,7 @@ struct XChainSim_test : public beast::unit_test::suite, public jtx::XChainBridge { } - bool + [[nodiscard]] bool a2b() const { return cr.a2b; @@ -4218,7 +4218,7 @@ struct XChainSim_test : public beast::unit_test::suite, public jtx::XChainBridge { } - bool + [[nodiscard]] bool a2b() const { return xfer.a2b; diff --git a/src/test/basics/hardened_hash_test.cpp b/src/test/basics/hardened_hash_test.cpp index 361a9613120..10e9c873093 100644 --- a/src/test/basics/hardened_hash_test.cpp +++ b/src/test/basics/hardened_hash_test.cpp @@ -115,7 +115,7 @@ class unsigned_integer return &m_vec[0]; } - void const* + [[nodiscard]] void const* data() const noexcept { return &m_vec[0]; diff --git a/src/test/beast/beast_Journal_test.cpp b/src/test/beast/beast_Journal_test.cpp index 7a96a1e2aac..f37a740e574 100644 --- a/src/test/beast/beast_Journal_test.cpp +++ b/src/test/beast/beast_Journal_test.cpp @@ -18,7 +18,7 @@ class Journal_test : public unit_test::suite { } - int + [[nodiscard]] int count() const { return m_count; diff --git a/src/test/beast/beast_Zero_test.cpp b/src/test/beast/beast_Zero_test.cpp index a5097237733..657bea70225 100644 --- a/src/test/beast/beast_Zero_test.cpp +++ b/src/test/beast/beast_Zero_test.cpp @@ -38,7 +38,7 @@ class Zero_test : public beast::unit_test::suite { } - int + [[nodiscard]] int signum() const { return value; diff --git a/src/test/consensus/NegativeUNL_test.cpp b/src/test/consensus/NegativeUNL_test.cpp index 220ca5ef123..a3987e81361 100644 --- a/src/test/consensus/NegativeUNL_test.cpp +++ b/src/test/consensus/NegativeUNL_test.cpp @@ -673,7 +673,7 @@ struct NetworkHistory } } - std::shared_ptr + [[nodiscard]] std::shared_ptr lastLedger() const { return history.back(); diff --git a/src/test/consensus/Validations_test.cpp b/src/test/consensus/Validations_test.cpp index 2cb8ae2f6c6..edb728af088 100644 --- a/src/test/consensus/Validations_test.cpp +++ b/src/test/consensus/Validations_test.cpp @@ -69,7 +69,7 @@ class Validations_test : public beast::unit_test::suite loadFee_ = fee; } - PeerID + [[nodiscard]] PeerID nodeID() const { return nodeID_; @@ -81,18 +81,18 @@ class Validations_test : public beast::unit_test::suite signIdx_++; } - PeerKey + [[nodiscard]] PeerKey currKey() const { return std::make_pair(nodeID_, signIdx_); } - PeerKey + [[nodiscard]] PeerKey masterKey() const { return std::make_pair(nodeID_, 0); } - NetClock::time_point + [[nodiscard]] NetClock::time_point now() const { return toNetClock(c_); @@ -100,7 +100,7 @@ class Validations_test : public beast::unit_test::suite // Issue a new validation with given sequence number and id and // with signing and seen times offset from the common clock - Validation + [[nodiscard]] Validation validate( Ledger::ID id, Ledger::Seq seq, @@ -122,20 +122,20 @@ class Validations_test : public beast::unit_test::suite return v; } - Validation + [[nodiscard]] Validation validate(Ledger ledger, NetClock::duration signOffset, NetClock::duration seenOffset) const { return validate(ledger.id(), ledger.seq(), signOffset, seenOffset, true); } - Validation + [[nodiscard]] Validation validate(Ledger ledger) const { return validate( ledger.id(), ledger.seq(), NetClock::duration{0}, NetClock::duration{0}, true); } - Validation + [[nodiscard]] Validation partial(Ledger ledger) const { return validate( @@ -171,7 +171,7 @@ class Validations_test : public beast::unit_test::suite { } - NetClock::time_point + [[nodiscard]] NetClock::time_point now() const { return toNetClock(c_); diff --git a/src/test/core/Config_test.cpp b/src/test/core/Config_test.cpp index 569a31df602..33ee5aa5ee7 100644 --- a/src/test/core/Config_test.cpp +++ b/src/test/core/Config_test.cpp @@ -164,25 +164,25 @@ class FileCfgGuard : public xrpl::detail::FileDirGuard /* bStandalone */ false); } - Config const& + [[nodiscard]] Config const& config() const { return config_; } - std::string + [[nodiscard]] std::string configFile() const { return file().string(); } - bool + [[nodiscard]] bool dataDirExists() const { return boost::filesystem::is_directory(dataDir_); } - bool + [[nodiscard]] bool configFileExists() const { return fileExists(); @@ -254,13 +254,13 @@ class ValidatorsTxtGuard : public detail::FileDirGuard { } - bool + [[nodiscard]] bool validatorsFileExists() const { return fileExists(); } - std::string + [[nodiscard]] std::string validatorsFile() const { return absolute(file()).string(); @@ -296,7 +296,8 @@ port_wss_admin c.loadFromString(toLoad); BEAST_EXPECT(c.legacy("ssl_verify") == "0"); - expectException([&c] { c.legacy("server"); }); // not a single line + expectException( + [&c] { [[maybe_unused]] auto _ = c.legacy("server"); }); // not a single line // set a legacy value BEAST_EXPECT(c.legacy("not_in_file").empty()); @@ -1423,7 +1424,7 @@ r.ripple.com:51235 BEAST_EXPECT(s.get("not_a_key") == std::nullopt); try { - s.get("a_string"); + [[maybe_unused]] auto _ = s.get("a_string"); fail(); } catch (boost::bad_lexical_cast&) diff --git a/src/test/core/Workers_test.cpp b/src/test/core/Workers_test.cpp index 84ff85f4ec4..a5b579e8100 100644 --- a/src/test/core/Workers_test.cpp +++ b/src/test/core/Workers_test.cpp @@ -54,13 +54,13 @@ class PerfLogTest : public PerfLog { } - Json::Value + [[nodiscard]] Json::Value countersJson() const override { return Json::Value(); } - Json::Value + [[nodiscard]] Json::Value currentJson() const override { return Json::Value(); diff --git a/src/test/csf/BasicNetwork.h b/src/test/csf/BasicNetwork.h index 63d85c3070a..8fb48ca97d6 100644 --- a/src/test/csf/BasicNetwork.h +++ b/src/test/csf/BasicNetwork.h @@ -164,7 +164,7 @@ class BasicNetwork /** Return the underlying digraph */ - Digraph const& + [[nodiscard]] Digraph const& graph() const { return links_; diff --git a/src/test/csf/Digraph.h b/src/test/csf/Digraph.h index a5678cc5396..b9fa447133e 100644 --- a/src/test/csf/Digraph.h +++ b/src/test/csf/Digraph.h @@ -94,7 +94,7 @@ class Digraph @return optional which is std::nullopt if no edge exists */ - std::optional + [[nodiscard]] std::optional edge(Vertex source, Vertex target) const { auto it = graph_.find(source); @@ -113,7 +113,7 @@ class Digraph @param target The target vertex @return true if the source has an out edge to target */ - bool + [[nodiscard]] bool connected(Vertex source, Vertex target) const { return edge(source, target) != std::nullopt; @@ -124,7 +124,7 @@ class Digraph @return A boost transformed range over the vertices with out edges in the graph */ - auto + [[nodiscard]] auto outVertices() const { return boost::adaptors::transform( @@ -136,7 +136,7 @@ class Digraph @param source The source vertex @return A boost transformed range over the target vertices of source. */ - auto + [[nodiscard]] auto outVertices(Vertex source) const { auto transform = [](typename Links::value_type const& link) { return link.first; }; @@ -162,7 +162,7 @@ class Digraph @return A boost transformed range of Edge type for all out edges of source. */ - auto + [[nodiscard]] auto outEdges(Vertex source) const { auto transform = [source](typename Links::value_type const& link) { @@ -181,7 +181,7 @@ class Digraph @param source The source vertex @return The number of outgoing edges from source */ - std::size_t + [[nodiscard]] std::size_t outDegree(Vertex source) const { auto it = graph_.find(source); diff --git a/src/test/csf/Histogram.h b/src/test/csf/Histogram.h index 6eef1b08c1e..ad3b9fd49da 100644 --- a/src/test/csf/Histogram.h +++ b/src/test/csf/Histogram.h @@ -37,35 +37,35 @@ class Histogram } /** The number of samples */ - std::size_t + [[nodiscard]] std::size_t size() const { return samples; } /** The number of distinct samples (bins) */ - std::size_t + [[nodiscard]] std::size_t numBins() const { return counts_.size(); } /** Minimum observed value */ - T + [[nodiscard]] T minValue() const { return counts_.empty() ? T{} : counts_.begin()->first; } /** Maximum observed value */ - T + [[nodiscard]] T maxValue() const { return counts_.empty() ? T{} : counts_.rbegin()->first; } /** Histogram average */ - T + [[nodiscard]] T avg() const { T tmp{}; @@ -86,7 +86,7 @@ class Histogram If the percentile falls between two bins, uses the nearest bin. @return The given percentile of the distribution */ - T + [[nodiscard]] T percentile(float p) const { assert(p >= 0 && p <= 1); diff --git a/src/test/csf/Peer.h b/src/test/csf/Peer.h index 5cf2757ab13..f0b903e69e4 100644 --- a/src/test/csf/Peer.h +++ b/src/test/csf/Peer.h @@ -87,13 +87,13 @@ struct Peer // Received delay is the time from receiving the message to actually // handling it. template - SimDuration + [[nodiscard]] SimDuration onReceive(M const&) const { return SimDuration{}; } - SimDuration + [[nodiscard]] SimDuration onReceive(Validation const&) const { return recvValidation; @@ -132,7 +132,7 @@ struct Peer { } - NetClock::time_point + [[nodiscard]] NetClock::time_point now() const { return p_.now(); diff --git a/src/test/csf/PeerGroup.h b/src/test/csf/PeerGroup.h index 6503ac62df4..87934255344 100644 --- a/src/test/csf/PeerGroup.h +++ b/src/test/csf/PeerGroup.h @@ -56,13 +56,13 @@ class PeerGroup return peers_.end(); } - const_iterator + [[nodiscard]] const_iterator begin() const { return peers_.begin(); } - const_iterator + [[nodiscard]] const_iterator end() const { return peers_.end(); @@ -87,7 +87,7 @@ class PeerGroup peers_.end(); } - std::size_t + [[nodiscard]] std::size_t size() const { return peers_.size(); diff --git a/src/test/csf/Scheduler.h b/src/test/csf/Scheduler.h index 82753124d90..d3f4a1c1c3c 100644 --- a/src/test/csf/Scheduler.h +++ b/src/test/csf/Scheduler.h @@ -104,7 +104,7 @@ class Scheduler ~queue_type(); - bool + [[nodiscard]] bool empty() const; iterator diff --git a/src/test/csf/TrustGraph.h b/src/test/csf/TrustGraph.h index 096104bc15e..202d17a6d57 100644 --- a/src/test/csf/TrustGraph.h +++ b/src/test/csf/TrustGraph.h @@ -67,7 +67,7 @@ class TrustGraph } //< Whether from trusts to - bool + [[nodiscard]] bool trusts(Peer const& from, Peer const& to) const { return graph_.connected(from, to); @@ -79,7 +79,7 @@ class TrustGraph @return boost transformed range over nodes `a` trusts, i.e. the nodes in its UNL */ - auto + [[nodiscard]] auto trustedPeers(Peer const& a) const { return graph_.outVertices(a); @@ -96,7 +96,7 @@ class TrustGraph }; //< Return nodes that fail the white-paper no-forking condition - std::vector + [[nodiscard]] std::vector forkablePairs(double quorum) const { // Check the forking condition by looking at intersection @@ -138,7 +138,7 @@ class TrustGraph /** Check whether this trust graph satisfies the whitepaper no-forking condition */ - bool + [[nodiscard]] bool canFork(double quorum) const { return !forkablePairs(quorum).empty(); diff --git a/src/test/csf/Tx.h b/src/test/csf/Tx.h index 8e8f6ea7e49..daa663af2be 100644 --- a/src/test/csf/Tx.h +++ b/src/test/csf/Tx.h @@ -31,7 +31,7 @@ class Tx { } - ID const& + [[nodiscard]] ID const& id() const { return id_; @@ -104,14 +104,14 @@ class TxSet { } - bool + [[nodiscard]] bool exists(Tx::ID const txId) const { auto it = txs_.find(Tx{txId}); return it != txs_.end(); } - Tx const* + [[nodiscard]] Tx const* find(Tx::ID const& txId) const { auto it = txs_.find(Tx{txId}); @@ -120,13 +120,13 @@ class TxSet return nullptr; } - TxSetType const& + [[nodiscard]] TxSetType const& txs() const { return txs_; } - ID + [[nodiscard]] ID id() const { return id_; @@ -136,7 +136,7 @@ class TxSet it was in this set and not other. False means it was in the other set and not this */ - std::map + [[nodiscard]] std::map compare(TxSet const& other) const { std::map res; diff --git a/src/test/csf/Validation.h b/src/test/csf/Validation.h index 2adf64196b1..df7d1ed265c 100644 --- a/src/test/csf/Validation.h +++ b/src/test/csf/Validation.h @@ -64,67 +64,67 @@ class Validation { } - Ledger::ID + [[nodiscard]] Ledger::ID ledgerID() const { return ledgerID_; } - Ledger::Seq + [[nodiscard]] Ledger::Seq seq() const { return seq_; } - NetClock::time_point + [[nodiscard]] NetClock::time_point signTime() const { return signTime_; } - NetClock::time_point + [[nodiscard]] NetClock::time_point seenTime() const { return seenTime_; } - PeerKey const& + [[nodiscard]] PeerKey const& key() const { return key_; } - PeerID const& + [[nodiscard]] PeerID const& nodeID() const { return nodeID_; } - bool + [[nodiscard]] bool trusted() const { return trusted_; } - bool + [[nodiscard]] bool full() const { return full_; } - std::uint64_t + [[nodiscard]] std::uint64_t cookie() const { return cookie_; } - std::optional + [[nodiscard]] std::optional loadFee() const { return loadFee_; } - Validation const& + [[nodiscard]] Validation const& unwrap() const { // For the xrpld implementation in which RCLValidation wraps @@ -133,7 +133,7 @@ class Validation return *this; } - auto + [[nodiscard]] auto asTie() const { // trusted is a status set by the receiver, so it is not part of the tie diff --git a/src/test/csf/collectors.h b/src/test/csf/collectors.h index 8da86cc287e..9e437eaef98 100644 --- a/src/test/csf/collectors.h +++ b/src/test/csf/collectors.h @@ -226,7 +226,7 @@ struct TxCollector } // Returns the number of txs which were never accepted - std::size_t + [[nodiscard]] std::size_t orphaned() const { return std::count_if( @@ -234,7 +234,7 @@ struct TxCollector } // Returns the number of txs which were never validated - std::size_t + [[nodiscard]] std::size_t unvalidated() const { return std::count_if( @@ -454,7 +454,7 @@ struct LedgerCollector } } - std::size_t + [[nodiscard]] std::size_t unvalidated() const { return std::count_if(ledgers_.begin(), ledgers_.end(), [](auto const& it) { diff --git a/src/test/csf/ledgers.h b/src/test/csf/ledgers.h index 3869fb7bd4e..14495f78a9a 100644 --- a/src/test/csf/ledgers.h +++ b/src/test/csf/ledgers.h @@ -85,7 +85,7 @@ class Ledger //! of the operators below. std::vector ancestors; - auto + [[nodiscard]] auto asTie() const { return std::tie( @@ -143,56 +143,56 @@ class Ledger { } - ID + [[nodiscard]] ID id() const { return id_; } - Seq + [[nodiscard]] Seq seq() const { return instance_->seq; } - NetClock::duration + [[nodiscard]] NetClock::duration closeTimeResolution() const { return instance_->closeTimeResolution; } - bool + [[nodiscard]] bool closeAgree() const { return instance_->closeTimeAgree; } - NetClock::time_point + [[nodiscard]] NetClock::time_point closeTime() const { return instance_->closeTime; } - NetClock::time_point + [[nodiscard]] NetClock::time_point parentCloseTime() const { return instance_->parentCloseTime; } - ID + [[nodiscard]] ID parentID() const { return instance_->parentID; } - TxSetType const& + [[nodiscard]] TxSetType const& txs() const { return instance_->txs; } /** Determine whether ancestor is really an ancestor of this ledger */ - bool + [[nodiscard]] bool isAncestor(Ledger const& ancestor) const; /** Return the id of the ancestor with the given seq (if exists/known) @@ -205,7 +205,7 @@ class Ledger friend Ledger::Seq mismatch(Ledger const& a, Ledger const& o); - Json::Value + [[nodiscard]] Json::Value getJson() const; friend bool @@ -232,14 +232,14 @@ class LedgerOracle InstanceMap instances_; // ID for the next unique ledger - Ledger::ID + [[nodiscard]] Ledger::ID nextID() const; public: LedgerOracle(); /** Find the ledger with the given ID */ - std::optional + [[nodiscard]] std::optional lookup(Ledger::ID const& id) const; /** Accept the given txs and generate a new ledger diff --git a/src/test/csf/submitters.h b/src/test/csf/submitters.h index be45b4ea2a0..a5c494beb02 100644 --- a/src/test/csf/submitters.h +++ b/src/test/csf/submitters.h @@ -18,7 +18,7 @@ struct Rate std::size_t count; SimDuration duration; - double + [[nodiscard]] double inv() const { return duration.count() / double(count); diff --git a/src/test/jtx/AMM.h b/src/test/jtx/AMM.h index faad982bccd..2bd3da8cf53 100644 --- a/src/test/jtx/AMM.h +++ b/src/test/jtx/AMM.h @@ -31,12 +31,12 @@ class LPToken LPToken(STAmount tokens) : tokens_(tokens), asset_(tokens.asset()) { } - STAmount + [[nodiscard]] STAmount tokens() const { return STAmount{asset_, tokens_}; } - STAmount + [[nodiscard]] STAmount tokens(Issue const& ammIssue) const { return STAmount{ammIssue, tokens_}; @@ -170,7 +170,7 @@ class AMM /** Send amm_info RPC command */ - Json::Value + [[nodiscard]] Json::Value ammRpcInfo( std::optional const& account = std::nullopt, std::optional const& ledgerIndex = std::nullopt, @@ -191,13 +191,13 @@ class AMM /** Get AMM balances for the token pair. */ - std::tuple + [[nodiscard]] std::tuple balances( Asset const& asset1, Asset const& asset2, std::optional const& account = std::nullopt) const; - std::tuple + [[nodiscard]] std::tuple balances(std::optional const& account = std::nullopt) const { return balances(asset1_.asset(), asset2_.asset(), account); @@ -340,25 +340,25 @@ class AMM void clawback(ClawbackArg const& arg); - AccountID const& + [[nodiscard]] AccountID const& ammAccount() const { return ammAccount_; } - Issue + [[nodiscard]] Issue lptIssue() const { return lptIssue_; } - IOUAmount + [[nodiscard]] IOUAmount tokens() const { return initialLPTokens_; } - IOUAmount + [[nodiscard]] IOUAmount getLPTokensBalance(std::optional const& account = std::nullopt) const; friend std::ostream& @@ -393,7 +393,7 @@ class AMM doClose_ = close; } - uint256 + [[nodiscard]] uint256 ammID() const { return ammID_; diff --git a/src/test/jtx/AbstractClient.h b/src/test/jtx/AbstractClient.h index 2002b3a7d8b..eb46788c345 100644 --- a/src/test/jtx/AbstractClient.h +++ b/src/test/jtx/AbstractClient.h @@ -33,7 +33,7 @@ class AbstractClient invoke(std::string const& cmd, Json::Value const& params = {}) = 0; /// Get RPC 1.0 or RPC 2.0 - virtual unsigned + [[nodiscard]] virtual unsigned version() const = 0; }; diff --git a/src/test/jtx/Account.h b/src/test/jtx/Account.h index 1e39f5a5464..c702bcffecd 100644 --- a/src/test/jtx/Account.h +++ b/src/test/jtx/Account.h @@ -57,21 +57,21 @@ class Account Account(AcctStringType stringType, std::string base58SeedStr); /** Return the name */ - std::string const& + [[nodiscard]] std::string const& name() const { return name_; } /** Return the public key. */ - PublicKey const& + [[nodiscard]] PublicKey const& pk() const { return pk_; } /** Return the secret key. */ - SecretKey const& + [[nodiscard]] SecretKey const& sk() const { return sk_; @@ -81,14 +81,14 @@ class Account The Account ID is the uint160 hash of the public key. */ - AccountID + [[nodiscard]] AccountID id() const { return id_; } /** Returns the human readable public key. */ - std::string const& + [[nodiscard]] std::string const& human() const { return human_; diff --git a/src/test/jtx/Env.h b/src/test/jtx/Env.h index 75c0195f409..3b55e6ef096 100644 --- a/src/test/jtx/Env.h +++ b/src/test/jtx/Env.h @@ -264,7 +264,7 @@ class Env return *bundle_.app; } - Application const& + [[nodiscard]] Application const& app() const { return *bundle_.app; @@ -331,7 +331,7 @@ class Env will not be visible. */ - std::shared_ptr + [[nodiscard]] std::shared_ptr current() const { return app().getOpenLedger().current(); @@ -479,7 +479,7 @@ class Env } // get rpc retries - unsigned + [[nodiscard]] unsigned retries() const { return retries_; @@ -491,55 +491,55 @@ class Env /** Returns the Account given the AccountID. */ /** @{ */ - Account const& + [[nodiscard]] Account const& lookup(AccountID const& id) const; - Account const& + [[nodiscard]] Account const& lookup(std::string const& base58ID) const; /** @} */ /** Returns the XRP balance on an account. Returns 0 if the account does not exist. */ - PrettyAmount + [[nodiscard]] PrettyAmount balance(Account const& account) const; /** Returns the next sequence number on account. Exceptions: Throws if the account does not exist */ - std::uint32_t + [[nodiscard]] std::uint32_t seq(Account const& account) const; /** Return the balance on an account. Returns 0 if the trust line does not exist. */ // VFALCO NOTE This should return a unit-less amount - PrettyAmount + [[nodiscard]] PrettyAmount balance(Account const& account, Asset const& asset) const; /** Returns the IOU limit on an account. Returns 0 if the trust line does not exist. */ - PrettyAmount + [[nodiscard]] PrettyAmount limit(Account const& account, Issue const& issue) const; /** Return the number of objects owned by an account. * Returns 0 if the account does not exist. */ - std::uint32_t + [[nodiscard]] std::uint32_t ownerCount(Account const& account) const; /** Return an account root. @return empty if the account does not exist. */ - std::shared_ptr + [[nodiscard]] std::shared_ptr le(Account const& account) const; /** Return a ledger entry. @return empty if the ledger entry does not exist */ - std::shared_ptr + [[nodiscard]] std::shared_ptr le(Keylet const& k) const; /** Create a JTx from parameters. */ @@ -653,7 +653,7 @@ class Env /** @} */ /** Return the TER for the last JTx. */ - TER + [[nodiscard]] TER ter() const { return ter_; @@ -684,7 +684,7 @@ class Env @note Only necessary for JTx submitted with via sign-and-submit method. */ - std::shared_ptr + [[nodiscard]] std::shared_ptr tx() const; void @@ -693,7 +693,7 @@ class Env void disableFeature(uint256 const feature); - bool + [[nodiscard]] bool enabled(uint256 feature) const { return current()->rules().enabled(feature); diff --git a/src/test/jtx/JTx.h b/src/test/jtx/JTx.h index a4db523ff52..4693c4e1a76 100644 --- a/src/test/jtx/JTx.h +++ b/src/test/jtx/JTx.h @@ -78,7 +78,7 @@ struct JTx } template - Prop const* + [[nodiscard]] Prop const* get() const { for (auto& prop : props_.list) diff --git a/src/test/jtx/ManualTimeKeeper.h b/src/test/jtx/ManualTimeKeeper.h index 1fd94858d6b..0e9da76b529 100644 --- a/src/test/jtx/ManualTimeKeeper.h +++ b/src/test/jtx/ManualTimeKeeper.h @@ -14,7 +14,7 @@ class ManualTimeKeeper : public TimeKeeper public: ManualTimeKeeper() = default; - time_point + [[nodiscard]] time_point now() const override { return now_.load(); diff --git a/src/test/jtx/Oracle.h b/src/test/jtx/Oracle.h index 42376b35990..c70bce623f2 100644 --- a/src/test/jtx/Oracle.h +++ b/src/test/jtx/Oracle.h @@ -126,7 +126,7 @@ class Oracle std::optional const& trim = std::nullopt, std::optional const& timeThreshold = std::nullopt); - std::uint32_t + [[nodiscard]] std::uint32_t documentID() const { return documentID_; @@ -154,7 +154,7 @@ class Oracle std::optional const& documentID, std::optional const& index = std::nullopt); - Json::Value + [[nodiscard]] Json::Value ledgerEntry(std::optional const& index = std::nullopt) const { return Oracle::ledgerEntry(env_, owner_, documentID_, index); diff --git a/src/test/jtx/PathSet.h b/src/test/jtx/PathSet.h index 4db3b7d62e9..fc739861cb5 100644 --- a/src/test/jtx/PathSet.h +++ b/src/test/jtx/PathSet.h @@ -88,7 +88,7 @@ class Path push_back(jtx::Account const& acc); Path& push_back(STPathElement const& pe); - Json::Value + [[nodiscard]] Json::Value json() const; private: @@ -166,7 +166,7 @@ class PathSet { addHelper(std::forward(first), std::forward(rest)...); } - Json::Value + [[nodiscard]] Json::Value json() const { Json::Value v; diff --git a/src/test/jtx/TestHelpers.h b/src/test/jtx/TestHelpers.h index 70692d16753..e3119f4c714 100644 --- a/src/test/jtx/TestHelpers.h +++ b/src/test/jtx/TestHelpers.h @@ -46,7 +46,7 @@ struct JTxField virtual ~JTxField() = default; - virtual OV + [[nodiscard]] virtual OV value() const = 0; virtual void @@ -94,7 +94,7 @@ struct timePointField : public JTxField { } - OV + [[nodiscard]] OV value() const override { return to_string(value_); @@ -138,7 +138,7 @@ struct accountIDField : public JTxField { } - OV + [[nodiscard]] OV value() const override { return toBase58(value_); @@ -160,7 +160,7 @@ struct stAmountField : public JTxField { } - OV + [[nodiscard]] OV value() const override { return value_.getJson(JsonOptions::none); @@ -202,7 +202,7 @@ struct valueUnitField : public JTxField::JTxField; - OV + [[nodiscard]] OV value() const override { return value_.value(); diff --git a/src/test/jtx/amount.h b/src/test/jtx/amount.h index 122af2faa15..4e063929483 100644 --- a/src/test/jtx/amount.h +++ b/src/test/jtx/amount.h @@ -103,25 +103,25 @@ struct PrettyAmount { } - std::string const& + [[nodiscard]] std::string const& name() const { return name_; } - STAmount const& + [[nodiscard]] STAmount const& value() const { return amount_; } - Number + [[nodiscard]] Number number() const { return amount_; } - int + [[nodiscard]] int signum() const { return amount_.signum(); @@ -172,7 +172,7 @@ struct PrettyAsset { } - Asset const& + [[nodiscard]] Asset const& raw() const { return asset_; @@ -209,20 +209,20 @@ struct PrettyAsset return {asset_}; } - bool + [[nodiscard]] bool integral() const { return asset_.integral(); } - bool + [[nodiscard]] bool native() const { return asset_.native(); } template - bool + [[nodiscard]] bool holds() const { return asset_.holds(); @@ -390,17 +390,17 @@ class IOU { } - Issue + [[nodiscard]] Issue issue() const { return {currency, account.id()}; } - Asset + [[nodiscard]] Asset asset() const { return issue(); } - bool + [[nodiscard]] bool integral() const { return issue().integral(); @@ -488,7 +488,7 @@ class MPT { } - xrpl::MPTID const& + [[nodiscard]] xrpl::MPTID const& mpt() const { return issuanceID; @@ -496,12 +496,12 @@ class MPT /** Explicit conversion to MPTIssue or asset. */ - xrpl::MPTIssue + [[nodiscard]] xrpl::MPTIssue mptIssue() const { return MPTIssue{issuanceID}; } - Asset + [[nodiscard]] Asset asset() const { return mptIssue(); diff --git a/src/test/jtx/basic_prop.h b/src/test/jtx/basic_prop.h index d2b48056511..16e1d8cd6d8 100644 --- a/src/test/jtx/basic_prop.h +++ b/src/test/jtx/basic_prop.h @@ -7,7 +7,7 @@ namespace xrpl::test::jtx { struct basic_prop { virtual ~basic_prop() = default; - virtual std::unique_ptr + [[nodiscard]] virtual std::unique_ptr clone() const = 0; virtual bool assignable(basic_prop const*) const = 0; @@ -23,7 +23,7 @@ struct prop_type : basic_prop { } - std::unique_ptr + [[nodiscard]] std::unique_ptr clone() const override { return std::make_unique>(t); diff --git a/src/test/jtx/batch.h b/src/test/jtx/batch.h index 90a7bef8cc0..846adc9adca 100644 --- a/src/test/jtx/batch.h +++ b/src/test/jtx/batch.h @@ -68,7 +68,7 @@ class inner txn_.removeMember(key); } - Json::Value const& + [[nodiscard]] Json::Value const& getTxn() const { return txn_; diff --git a/src/test/jtx/deposit.h b/src/test/jtx/deposit.h index d74db770c7f..1d032bf1e0c 100644 --- a/src/test/jtx/deposit.h +++ b/src/test/jtx/deposit.h @@ -22,7 +22,7 @@ struct AuthorizeCredentials auto operator<=>(AuthorizeCredentials const&) const = default; - Json::Value + [[nodiscard]] Json::Value toJson() const { Json::Value jv; @@ -32,7 +32,7 @@ struct AuthorizeCredentials } // "ledger_entry" uses a different naming convention - Json::Value + [[nodiscard]] Json::Value toLEJson() const { Json::Value jv; diff --git a/src/test/jtx/impl/JSONRPCClient.cpp b/src/test/jtx/impl/JSONRPCClient.cpp index c44371c13e3..5b008360897 100644 --- a/src/test/jtx/impl/JSONRPCClient.cpp +++ b/src/test/jtx/impl/JSONRPCClient.cpp @@ -145,7 +145,7 @@ class JSONRPCClient : public AbstractClient return jv; } - unsigned + [[nodiscard]] unsigned version() const override { return rpc_version_; diff --git a/src/test/jtx/impl/Oracle.cpp b/src/test/jtx/impl/Oracle.cpp index 7e49cdcd3d1..d9cace5624e 100644 --- a/src/test/jtx/impl/Oracle.cpp +++ b/src/test/jtx/impl/Oracle.cpp @@ -409,8 +409,8 @@ validDocumentID(AnyValue const& v) { Json::Value jv; toJson(jv, v); - jv.asUInt(); - jv.isNumeric(); + [[maybe_unused]] auto unused1 = jv.asUInt(); + [[maybe_unused]] auto unused2 = jv.isNumeric(); return true; } catch (...) diff --git a/src/test/jtx/impl/WSClient.cpp b/src/test/jtx/impl/WSClient.cpp index 617e2b88810..a7db5e4302c 100644 --- a/src/test/jtx/impl/WSClient.cpp +++ b/src/test/jtx/impl/WSClient.cpp @@ -281,7 +281,7 @@ class WSClientImpl : public WSClient return std::move(m->jv); } - unsigned + [[nodiscard]] unsigned version() const override { return rpc_version_; diff --git a/src/test/jtx/mpt.h b/src/test/jtx/mpt.h index eb08de5caa6..77597d795de 100644 --- a/src/test/jtx/mpt.h +++ b/src/test/jtx/mpt.h @@ -229,12 +229,12 @@ class MPTTester [[nodiscard]] bool isTransferFeePresent() const; - Account const& + [[nodiscard]] Account const& issuer() const { return issuer_; } - Account const& + [[nodiscard]] Account const& holder(std::string const& h) const; void @@ -251,10 +251,10 @@ class MPTTester std::int64_t amount, std::optional err = std::nullopt); - PrettyAmount + [[nodiscard]] PrettyAmount mpt(std::int64_t amount) const; - MPTID const& + [[nodiscard]] MPTID const& issuanceID() const { if (!env_.test.BEAST_EXPECT(id_)) @@ -262,7 +262,7 @@ class MPTTester return *id_; // NOLINT(bugprone-unchecked-optional-access) } - std::int64_t + [[nodiscard]] std::int64_t getBalance(Account const& account) const; MPT @@ -307,7 +307,7 @@ class MPTTester static std::unordered_map makeHolders(std::vector const& holders); - std::uint32_t + [[nodiscard]] std::uint32_t getFlags(std::optional const& holder) const; }; diff --git a/src/test/jtx/vault.h b/src/test/jtx/vault.h index bbd8c129ccb..f8883630c41 100644 --- a/src/test/jtx/vault.h +++ b/src/test/jtx/vault.h @@ -28,7 +28,7 @@ struct Vault }; /** Return a VaultCreate transaction and the Vault's expected keylet. */ - std::tuple + [[nodiscard]] std::tuple create(CreateArgs const& args) const; struct SetArgs diff --git a/src/test/jtx/xchain_bridge.h b/src/test/jtx/xchain_bridge.h index bb01bf17ba1..7b5b3db0c41 100644 --- a/src/test/jtx/xchain_bridge.h +++ b/src/test/jtx/xchain_bridge.h @@ -217,7 +217,7 @@ struct XChainBridgeObjects fromIdx); } - Json::Value + [[nodiscard]] Json::Value create_bridge( Account const& acc, Json::Value const& bridge = Json::nullValue, diff --git a/src/test/overlay/reduce_relay_test.cpp b/src/test/overlay/reduce_relay_test.cpp index 842511b860e..21f3482ab54 100644 --- a/src/test/overlay/reduce_relay_test.cpp +++ b/src/test/overlay/reduce_relay_test.cpp @@ -91,7 +91,7 @@ class PeerPartial : public Peer send(std::shared_ptr const& m) override { } - beast::IP::Endpoint + [[nodiscard]] beast::IP::Endpoint getRemoteAddress() const override { return {}; @@ -100,22 +100,22 @@ class PeerPartial : public Peer charge(Resource::Charge const& fee, std::string const& context = {}) override { } - bool + [[nodiscard]] bool cluster() const override { return false; } - bool + [[nodiscard]] bool isHighLatency() const override { return false; } - int + [[nodiscard]] int getScore(bool) const override { return 0; } - PublicKey const& + [[nodiscard]] PublicKey const& getNodePublic() const override { return nodePublicKey_; @@ -125,12 +125,12 @@ class PeerPartial : public Peer { return {}; } - bool + [[nodiscard]] bool supportsFeature(ProtocolFeature f) const override { return false; } - std::optional + [[nodiscard]] std::optional publisherListSequence(PublicKey const&) const override { return {}; @@ -139,13 +139,13 @@ class PeerPartial : public Peer setPublisherListSequence(PublicKey const&, std::size_t const) override { } - uint256 const& + [[nodiscard]] uint256 const& getClosedLedgerHash() const override { static uint256 const hash{}; return hash; } - bool + [[nodiscard]] bool hasLedger(uint256 const& hash, std::uint32_t seq) const override { return false; @@ -154,7 +154,7 @@ class PeerPartial : public Peer ledgerRange(std::uint32_t& minSeq, std::uint32_t& maxSeq) const override { } - bool + [[nodiscard]] bool hasTxSet(uint256 const& hash) const override { return false; @@ -168,12 +168,12 @@ class PeerPartial : public Peer { return false; } - bool + [[nodiscard]] bool compressionEnabled() const override { return false; } - bool + [[nodiscard]] bool txReduceRelayEnabled() const override { return false; @@ -421,7 +421,7 @@ class Validator return message_; } - std::uint16_t + [[nodiscard]] std::uint16_t id() const { return id_; diff --git a/src/test/overlay/short_read_test.cpp b/src/test/overlay/short_read_test.cpp index 5d145fb6b10..02c93127323 100644 --- a/src/test/overlay/short_read_test.cpp +++ b/src/test/overlay/short_read_test.cpp @@ -424,7 +424,7 @@ class short_read_test : public beast::unit_test::suite wait(); } - endpoint_type const& + [[nodiscard]] endpoint_type const& endpoint() const { return endpoint_; diff --git a/src/test/rpc/DeliveredAmount_test.cpp b/src/test/rpc/DeliveredAmount_test.cpp index 133c5771b7b..abbeb5c81ad 100644 --- a/src/test/rpc/DeliveredAmount_test.cpp +++ b/src/test/rpc/DeliveredAmount_test.cpp @@ -91,7 +91,7 @@ class CheckDeliveredAmount // After all the txns are checked, all the `numExpected` variables should be // zero. The `checkTxn` function decrements these variables. - bool + [[nodiscard]] bool checkExpectedCounters() const { return (numExpectedAvailable_ == 0) && (numExpectedNotSet_ == 0) && diff --git a/src/test/shamap/FetchPack_test.cpp b/src/test/shamap/FetchPack_test.cpp index fd44423ba8d..cd3bc99fa8b 100644 --- a/src/test/shamap/FetchPack_test.cpp +++ b/src/test/shamap/FetchPack_test.cpp @@ -64,7 +64,7 @@ class FetchPack_test : public beast::unit_test::suite { } - std::optional + [[nodiscard]] std::optional getNode(SHAMapHash const& nodeHash) const override { Map::iterator const it = mMap.find(nodeHash); diff --git a/src/test/shamap/common.h b/src/test/shamap/common.h index cd942076b80..08910b5c5d1 100644 --- a/src/test/shamap/common.h +++ b/src/test/shamap/common.h @@ -45,7 +45,7 @@ class TestNodeFamily : public Family return *db_; } - NodeStore::Database const& + [[nodiscard]] NodeStore::Database const& db() const override { return *db_; diff --git a/src/test/unit_test/FileDirGuard.h b/src/test/unit_test/FileDirGuard.h index 9d4b94d8c5c..20520eac3d5 100644 --- a/src/test/unit_test/FileDirGuard.h +++ b/src/test/unit_test/FileDirGuard.h @@ -81,7 +81,7 @@ class DirGuard }; } - path const& + [[nodiscard]] path const& subdir() const { return subDir_; @@ -147,13 +147,13 @@ class FileDirGuard : public DirGuard }; } - path const& + [[nodiscard]] path const& file() const { return file_; } - bool + [[nodiscard]] bool fileExists() const { return boost::filesystem::exists(file_); diff --git a/src/test/unit_test/SuiteJournal.h b/src/test/unit_test/SuiteJournal.h index c3820b87095..f4cbb5baa0f 100644 --- a/src/test/unit_test/SuiteJournal.h +++ b/src/test/unit_test/SuiteJournal.h @@ -21,7 +21,7 @@ class SuiteJournalSink : public beast::Journal::Sink } // For unit testing, always generate logging text. - bool + [[nodiscard]] bool active(beast::severities::Severity level) const override { return true; diff --git a/src/test/unit_test/multi_runner.h b/src/test/unit_test/multi_runner.h index 86d46990178..0f675955de4 100644 --- a/src/test/unit_test/multi_runner.h +++ b/src/test/unit_test/multi_runner.h @@ -175,13 +175,13 @@ class multi_runner_base void print_results(S& s); - bool + [[nodiscard]] bool any_failed() const; - std::size_t + [[nodiscard]] std::size_t tests() const; - std::size_t + [[nodiscard]] std::size_t suites() const; void @@ -214,13 +214,13 @@ class multi_runner_parent : private detail::multi_runner_base multi_runner_parent(); ~multi_runner_parent(); - bool + [[nodiscard]] bool any_failed() const; - std::size_t + [[nodiscard]] std::size_t tests() const; - std::size_t + [[nodiscard]] std::size_t suites() const; void @@ -254,10 +254,10 @@ class multi_runner_child : public beast::unit_test::runner, multi_runner_child(std::size_t num_jobs, bool quiet, bool print_log); ~multi_runner_child() override; - std::size_t + [[nodiscard]] std::size_t tests() const; - std::size_t + [[nodiscard]] std::size_t suites() const; void diff --git a/src/tests/libxrpl/json/Value.cpp b/src/tests/libxrpl/json/Value.cpp index a53d81b5e1e..2790f0e963d 100644 --- a/src/tests/libxrpl/json/Value.cpp +++ b/src/tests/libxrpl/json/Value.cpp @@ -660,8 +660,8 @@ TEST(json_value, edge_cases) { Json::Value intString{std::to_string(overflow)}; - EXPECT_THROW(intString.asUInt(), beast::BadLexicalCast); - EXPECT_THROW(intString.asAbsUInt(), Json::error); + EXPECT_THROW([&] { return intString.asUInt(); }(), beast::BadLexicalCast); + EXPECT_THROW([&] { return intString.asAbsUInt(); }(), Json::error); intString = "4294967295"; EXPECT_EQ(intString.asUInt(), 4294967295u); @@ -672,17 +672,17 @@ TEST(json_value, edge_cases) EXPECT_EQ(intString.asAbsUInt(), 0); intString = "-1"; - EXPECT_THROW(intString.asUInt(), beast::BadLexicalCast); + EXPECT_THROW([&] { return intString.asUInt(); }(), beast::BadLexicalCast); EXPECT_EQ(intString.asAbsUInt(), 1); intString = "-4294967295"; EXPECT_EQ(intString.asAbsUInt(), 4294967295); intString = "-4294967296"; - EXPECT_THROW(intString.asAbsUInt(), Json::error); + EXPECT_THROW([&] { return intString.asAbsUInt(); }(), Json::error); intString = "2147483648"; - EXPECT_THROW(intString.asInt(), beast::BadLexicalCast); + EXPECT_THROW([&] { return intString.asInt(); }(), beast::BadLexicalCast); EXPECT_EQ(intString.asAbsUInt(), 2147483648); intString = "2147483647"; @@ -694,14 +694,14 @@ TEST(json_value, edge_cases) EXPECT_EQ(intString.asAbsUInt(), 2147483648LL); intString = "-2147483649"; - EXPECT_THROW(intString.asInt(), beast::BadLexicalCast); + EXPECT_THROW([&] { return intString.asInt(); }(), beast::BadLexicalCast); EXPECT_EQ(intString.asAbsUInt(), 2147483649); } { Json::Value intReal{4294967297.0}; - EXPECT_THROW(intReal.asUInt(), Json::error); - EXPECT_THROW(intReal.asAbsUInt(), Json::error); + EXPECT_THROW([&] { return intReal.asUInt(); }(), Json::error); + EXPECT_THROW([&] { return intReal.asAbsUInt(); }(), Json::error); intReal = 4294967295.0; EXPECT_EQ(intReal.asUInt(), 4294967295u); @@ -712,17 +712,17 @@ TEST(json_value, edge_cases) EXPECT_EQ(intReal.asAbsUInt(), 0); intReal = -1.0; - EXPECT_THROW(intReal.asUInt(), Json::error); + EXPECT_THROW([&] { return intReal.asUInt(); }(), Json::error); EXPECT_EQ(intReal.asAbsUInt(), 1); intReal = -4294967295.0; EXPECT_EQ(intReal.asAbsUInt(), 4294967295); intReal = -4294967296.0; - EXPECT_THROW(intReal.asAbsUInt(), Json::error); + EXPECT_THROW([&] { return intReal.asAbsUInt(); }(), Json::error); intReal = 2147483648.0; - EXPECT_THROW(intReal.asInt(), Json::error); + EXPECT_THROW([&] { return intReal.asInt(); }(), Json::error); EXPECT_EQ(intReal.asAbsUInt(), 2147483648); intReal = 2147483647.0; @@ -734,7 +734,7 @@ TEST(json_value, edge_cases) EXPECT_EQ(intReal.asAbsUInt(), 2147483648LL); intReal = -2147483649.0; - EXPECT_THROW(intReal.asInt(), Json::error); + EXPECT_THROW([&] { return intReal.asInt(); }(), Json::error); EXPECT_EQ(intReal.asAbsUInt(), 2147483649); } } @@ -891,7 +891,7 @@ TEST(json_value, conversions) // val.asCString() should trigger an assertion failure EXPECT_EQ(val.asString(), "-1234"); EXPECT_EQ(val.asInt(), -1234); - EXPECT_THROW(val.asUInt(), Json::error); + EXPECT_THROW([&] { return val.asUInt(); }(), Json::error); EXPECT_EQ(val.asAbsUInt(), 1234u); EXPECT_EQ(val.asDouble(), -1234.0); EXPECT_TRUE(val.asBool()); @@ -956,7 +956,7 @@ TEST(json_value, conversions) EXPECT_EQ(val.asInt(), 54321); EXPECT_EQ(val.asUInt(), 54321u); EXPECT_EQ(val.asAbsUInt(), 54321); - EXPECT_THROW(val.asDouble(), Json::error); + EXPECT_THROW([&] { return val.asDouble(); }(), Json::error); EXPECT_TRUE(val.asBool()); EXPECT_FALSE(val.isConvertibleTo(Json::nullValue)); @@ -974,10 +974,10 @@ TEST(json_value, conversions) EXPECT_TRUE(val.isString()); EXPECT_EQ(val.asCString(), nullptr); EXPECT_EQ(val.asString(), ""); - EXPECT_THROW(val.asInt(), std::exception); - EXPECT_THROW(val.asUInt(), std::exception); - EXPECT_THROW(val.asAbsUInt(), std::exception); - EXPECT_THROW(val.asDouble(), std::exception); + EXPECT_THROW([&] { return val.asInt(); }(), std::exception); + EXPECT_THROW([&] { return val.asUInt(); }(), std::exception); + EXPECT_THROW([&] { return val.asAbsUInt(); }(), std::exception); + EXPECT_THROW([&] { return val.asDouble(); }(), std::exception); EXPECT_TRUE(val.asBool() == false); EXPECT_TRUE(val.isConvertibleTo(Json::nullValue)); @@ -1036,11 +1036,11 @@ TEST(json_value, conversions) Json::Value const val(Json::arrayValue); EXPECT_TRUE(val.isArray()); // val.asCString should trigger an assertion failure - EXPECT_THROW(val.asString(), Json::error); - EXPECT_THROW(val.asInt(), Json::error); - EXPECT_THROW(val.asUInt(), Json::error); - EXPECT_THROW(val.asAbsUInt(), Json::error); - EXPECT_THROW(val.asDouble(), Json::error); + EXPECT_THROW([&] { return val.asString(); }(), Json::error); + EXPECT_THROW([&] { return val.asInt(); }(), Json::error); + EXPECT_THROW([&] { return val.asUInt(); }(), Json::error); + EXPECT_THROW([&] { return val.asAbsUInt(); }(), Json::error); + EXPECT_THROW([&] { return val.asDouble(); }(), Json::error); EXPECT_FALSE(val.asBool()); // empty or not EXPECT_TRUE(val.isConvertibleTo(Json::nullValue)); @@ -1057,11 +1057,11 @@ TEST(json_value, conversions) Json::Value const val(Json::objectValue); EXPECT_TRUE(val.isObject()); // val.asCString should trigger an assertion failure - EXPECT_THROW(val.asString(), Json::error); - EXPECT_THROW(val.asInt(), Json::error); - EXPECT_THROW(val.asUInt(), Json::error); - EXPECT_THROW(val.asAbsUInt(), Json::error); - EXPECT_THROW(val.asDouble(), Json::error); + EXPECT_THROW([&] { return val.asString(); }(), Json::error); + EXPECT_THROW([&] { return val.asInt(); }(), Json::error); + EXPECT_THROW([&] { return val.asUInt(); }(), Json::error); + EXPECT_THROW([&] { return val.asAbsUInt(); }(), Json::error); + EXPECT_THROW([&] { return val.asDouble(); }(), Json::error); EXPECT_FALSE(val.asBool()); // empty or not EXPECT_TRUE(val.isConvertibleTo(Json::nullValue)); diff --git a/src/tests/libxrpl/net/HTTPClient.cpp b/src/tests/libxrpl/net/HTTPClient.cpp index d3dfd32361f..01de5ff9991 100644 --- a/src/tests/libxrpl/net/HTTPClient.cpp +++ b/src/tests/libxrpl/net/HTTPClient.cpp @@ -79,7 +79,7 @@ class TestHTTPServer return ioc_; } - unsigned short + [[nodiscard]] unsigned short port() const { return port_; @@ -110,7 +110,7 @@ class TestHTTPServer acceptor_.close(); } - bool + [[nodiscard]] bool finished() const { return finished_; diff --git a/src/xrpld/app/consensus/RCLCxLedger.h b/src/xrpld/app/consensus/RCLCxLedger.h index 09111ebdb60..3c5175a04de 100644 --- a/src/xrpld/app/consensus/RCLCxLedger.h +++ b/src/xrpld/app/consensus/RCLCxLedger.h @@ -37,56 +37,56 @@ class RCLCxLedger } //! Sequence number of the ledger. - Seq const& + [[nodiscard]] Seq const& seq() const { return ledger_->header().seq; } //! Unique identifier (hash) of this ledger. - ID const& + [[nodiscard]] ID const& id() const { return ledger_->header().hash; } //! Unique identifier (hash) of this ledger's parent. - ID const& + [[nodiscard]] ID const& parentID() const { return ledger_->header().parentHash; } //! Resolution used when calculating this ledger's close time. - NetClock::duration + [[nodiscard]] NetClock::duration closeTimeResolution() const { return ledger_->header().closeTimeResolution; } //! Whether consensus process agreed on close time of the ledger. - bool + [[nodiscard]] bool closeAgree() const { return xrpl::getCloseAgree(ledger_->header()); } //! The close time of this ledger - NetClock::time_point + [[nodiscard]] NetClock::time_point closeTime() const { return ledger_->header().closeTime; } //! The close time of this ledger's parent. - NetClock::time_point + [[nodiscard]] NetClock::time_point parentCloseTime() const { return ledger_->header().parentCloseTime; } //! JSON representation of this ledger. - Json::Value + [[nodiscard]] Json::Value getJson() const { return xrpl::getJson({*ledger_, {}}); diff --git a/src/xrpld/app/consensus/RCLCxTx.h b/src/xrpld/app/consensus/RCLCxTx.h index 0af43f74770..dc99ea66e37 100644 --- a/src/xrpld/app/consensus/RCLCxTx.h +++ b/src/xrpld/app/consensus/RCLCxTx.h @@ -24,7 +24,7 @@ class RCLCxTx } //! The unique identifier/hash of the transaction - ID const& + [[nodiscard]] ID const& id() const { return tx_->key(); @@ -104,7 +104,7 @@ class RCLTxSet @param entry The ID of transaction to test. @return Whether the transaction is in the set. */ - bool + [[nodiscard]] bool exists(Tx::ID const& entry) const { return map_->hasItem(entry); @@ -121,14 +121,14 @@ class RCLTxSet code uses the shared_ptr semantics to know whether the find was successful and properly creates a Tx as needed. */ - boost::intrusive_ptr const& + [[nodiscard]] boost::intrusive_ptr const& find(Tx::ID const& entry) const { return map_->peekItem(entry); } //! The unique ID/hash of the transaction set - ID + [[nodiscard]] ID id() const { return map_->getHash().as_uint256(); @@ -142,7 +142,7 @@ class RCLTxSet is the transaction ID and the value is a bool of the transaction exists in this set. */ - std::map + [[nodiscard]] std::map compare(RCLTxSet const& j) const { SHAMap::Delta delta; diff --git a/src/xrpld/app/consensus/RCLValidations.h b/src/xrpld/app/consensus/RCLValidations.h index 8da82e64258..cddcedc2242 100644 --- a/src/xrpld/app/consensus/RCLValidations.h +++ b/src/xrpld/app/consensus/RCLValidations.h @@ -37,49 +37,49 @@ class RCLValidation } /// Validated ledger's hash - uint256 + [[nodiscard]] uint256 ledgerID() const { return val_->getLedgerHash(); } /// Validated ledger's sequence number (0 if none) - std::uint32_t + [[nodiscard]] std::uint32_t seq() const { return val_->getFieldU32(sfLedgerSequence); } /// Validation's signing time - NetClock::time_point + [[nodiscard]] NetClock::time_point signTime() const { return val_->getSignTime(); } /// Validated ledger's first seen time - NetClock::time_point + [[nodiscard]] NetClock::time_point seenTime() const { return val_->getSeenTime(); } /// Public key of validator that published the validation - PublicKey + [[nodiscard]] PublicKey key() const { return val_->getSignerPublic(); } /// NodeID of validator that published the validation - NodeID + [[nodiscard]] NodeID nodeID() const { return val_->getNodeID(); } /// Whether the validation is considered trusted. - bool + [[nodiscard]] bool trusted() const { return val_->isTrusted(); @@ -98,28 +98,28 @@ class RCLValidation } /// Whether the validation is full (not-partial) - bool + [[nodiscard]] bool full() const { return val_->isFull(); } /// Get the load fee of the validation if it exists - std::optional + [[nodiscard]] std::optional loadFee() const { return ~(*val_)[~sfLoadFee]; } /// Get the cookie specified in the validation (0 if not set) - std::uint64_t + [[nodiscard]] std::uint64_t cookie() const { return (*val_)[sfCookie]; } /// Extract the underlying STValidation being wrapped - std::shared_ptr + [[nodiscard]] std::shared_ptr unwrap() const { return val_; @@ -150,11 +150,11 @@ class RCLValidatedLedger RCLValidatedLedger(std::shared_ptr const& ledger, beast::Journal j); /// The sequence (index) of the ledger - Seq + [[nodiscard]] Seq seq() const; /// The ID (hash) of the ledger - ID + [[nodiscard]] ID id() const; /** Lookup the ID of the ancestor ledger @@ -170,7 +170,7 @@ class RCLValidatedLedger friend Seq mismatch(RCLValidatedLedger const& a, RCLValidatedLedger const& b); - Seq + [[nodiscard]] Seq minSeq() const; private: @@ -197,14 +197,14 @@ class RCLValidationsAdaptor /** Current time used to determine if validations are stale. */ - NetClock::time_point + [[nodiscard]] NetClock::time_point now() const; /** Attempt to acquire the ledger with given id from the network */ std::optional acquire(LedgerHash const& id); - beast::Journal + [[nodiscard]] beast::Journal journal() const { return j_; diff --git a/src/xrpld/app/ledger/AcceptedLedger.h b/src/xrpld/app/ledger/AcceptedLedger.h index 23cee6ce352..a024e24cb2d 100644 --- a/src/xrpld/app/ledger/AcceptedLedger.h +++ b/src/xrpld/app/ledger/AcceptedLedger.h @@ -27,25 +27,25 @@ class AcceptedLedger : public CountedObject public: AcceptedLedger(std::shared_ptr const& ledger); - std::shared_ptr const& + [[nodiscard]] std::shared_ptr const& getLedger() const { return mLedger; } - std::size_t + [[nodiscard]] std::size_t size() const { return transactions_.size(); } - auto + [[nodiscard]] auto begin() const { return transactions_.begin(); } - auto + [[nodiscard]] auto end() const { return transactions_.end(); diff --git a/src/xrpld/app/ledger/AccountStateSF.h b/src/xrpld/app/ledger/AccountStateSF.h index d17f3540ea3..5d00e651208 100644 --- a/src/xrpld/app/ledger/AccountStateSF.h +++ b/src/xrpld/app/ledger/AccountStateSF.h @@ -24,7 +24,7 @@ class AccountStateSF : public SHAMapSyncFilter Blob&& nodeData, SHAMapNodeType type) const override; - std::optional + [[nodiscard]] std::optional getNode(SHAMapHash const& nodeHash) const override; private: diff --git a/src/xrpld/app/ledger/ConsensusTransSetSF.h b/src/xrpld/app/ledger/ConsensusTransSetSF.h index f439ef9cfa6..b666fbf750e 100644 --- a/src/xrpld/app/ledger/ConsensusTransSetSF.h +++ b/src/xrpld/app/ledger/ConsensusTransSetSF.h @@ -28,7 +28,7 @@ class ConsensusTransSetSF : public SHAMapSyncFilter Blob&& nodeData, SHAMapNodeType type) const override; - std::optional + [[nodiscard]] std::optional getNode(SHAMapHash const& nodeHash) const override; private: diff --git a/src/xrpld/app/ledger/LedgerReplay.h b/src/xrpld/app/ledger/LedgerReplay.h index a2b2e60e8e9..2dc4911ade5 100644 --- a/src/xrpld/app/ledger/LedgerReplay.h +++ b/src/xrpld/app/ledger/LedgerReplay.h @@ -27,7 +27,7 @@ class LedgerReplay : public CountedObject /** @return The parent of the ledger to replay */ - std::shared_ptr const& + [[nodiscard]] std::shared_ptr const& parent() const { return parent_; @@ -35,7 +35,7 @@ class LedgerReplay : public CountedObject /** @return The ledger to replay */ - std::shared_ptr const& + [[nodiscard]] std::shared_ptr const& replay() const { return replay_; @@ -43,7 +43,7 @@ class LedgerReplay : public CountedObject /** @return Transactions in the order they should be replayed */ - std::map> const& + [[nodiscard]] std::map> const& orderedTxns() const { return orderedTxns_; diff --git a/src/xrpld/app/ledger/LedgerReplayTask.h b/src/xrpld/app/ledger/LedgerReplayTask.h index 65c43edb2d9..4eaed49d1ba 100644 --- a/src/xrpld/app/ledger/LedgerReplayTask.h +++ b/src/xrpld/app/ledger/LedgerReplayTask.h @@ -60,7 +60,7 @@ class LedgerReplayTask final : public TimeoutCounter, update(uint256 const& hash, std::uint32_t seq, std::vector const& sList); /** check if this task can be merged into an existing task */ - bool + [[nodiscard]] bool canMergeInto(TaskParameter const& existingTask) const; }; diff --git a/src/xrpld/app/ledger/TransactionStateSF.h b/src/xrpld/app/ledger/TransactionStateSF.h index 9ca84c26109..c5c113be7fa 100644 --- a/src/xrpld/app/ledger/TransactionStateSF.h +++ b/src/xrpld/app/ledger/TransactionStateSF.h @@ -24,7 +24,7 @@ class TransactionStateSF : public SHAMapSyncFilter Blob&& nodeData, SHAMapNodeType type) const override; - std::optional + [[nodiscard]] std::optional getNode(SHAMapHash const& nodeHash) const override; private: diff --git a/src/xrpld/app/ledger/detail/LocalTxs.cpp b/src/xrpld/app/ledger/detail/LocalTxs.cpp index 5326568e35a..83d9c61c3c4 100644 --- a/src/xrpld/app/ledger/detail/LocalTxs.cpp +++ b/src/xrpld/app/ledger/detail/LocalTxs.cpp @@ -57,31 +57,31 @@ class LocalTx m_expire = std::min(m_expire, txn->getFieldU32(sfLastLedgerSequence) + 1); } - uint256 const& + [[nodiscard]] uint256 const& getID() const { return m_id; } - SeqProxy + [[nodiscard]] SeqProxy getSeqProxy() const { return m_seqProxy; } - bool + [[nodiscard]] bool isExpired(LedgerIndex i) const { return i > m_expire; } - std::shared_ptr const& + [[nodiscard]] std::shared_ptr const& getTX() const { return m_txn; } - AccountID const& + [[nodiscard]] AccountID const& getAccount() const { return m_account; diff --git a/src/xrpld/app/main/Application.cpp b/src/xrpld/app/main/Application.cpp index 5867f77ba0c..005586eabae 100644 --- a/src/xrpld/app/main/Application.cpp +++ b/src/xrpld/app/main/Application.cpp @@ -180,7 +180,7 @@ class ApplicationImp : public Application, public BasicApp } } - std::chrono::milliseconds + [[nodiscard]] std::chrono::milliseconds get() const { return lastSample_.load(); diff --git a/src/xrpld/app/main/Application.h b/src/xrpld/app/main/Application.h index d0437be9a66..aa1c7893810 100644 --- a/src/xrpld/app/main/Application.h +++ b/src/xrpld/app/main/Application.h @@ -112,7 +112,7 @@ class Application : public ServiceRegistry, public beast::PropertyStream::Source run() = 0; virtual void signalStop(std::string msg) = 0; - virtual bool + [[nodiscard]] virtual bool checkSigs() const = 0; virtual void checkSigs(bool) = 0; @@ -122,7 +122,7 @@ class Application : public ServiceRegistry, public beast::PropertyStream::Source // /** Returns a 64-bit instance identifier, generated at startup */ - virtual std::uint64_t + [[nodiscard]] virtual std::uint64_t instanceID() const = 0; virtual Config& @@ -131,7 +131,7 @@ class Application : public ServiceRegistry, public beast::PropertyStream::Source virtual std::pair const& nodeIdentity() = 0; - virtual std::optional + [[nodiscard]] virtual std::optional getValidationPublicKey() const = 0; virtual std::chrono::milliseconds @@ -141,7 +141,7 @@ class Application : public ServiceRegistry, public beast::PropertyStream::Source serverOkay(std::string& reason) = 0; /* Returns the number of file descriptors the application needs */ - virtual int + [[nodiscard]] virtual int fdRequired() const = 0; /** Ensure that a newly-started validator does not sign proposals older @@ -150,7 +150,7 @@ class Application : public ServiceRegistry, public beast::PropertyStream::Source getMaxDisallowedLedger() = 0; /** Returns the number of io_context (I/O worker) threads used by the application. */ - virtual size_t + [[nodiscard]] virtual size_t getNumberOfThreads() const = 0; }; diff --git a/src/xrpld/app/main/BasicApp.h b/src/xrpld/app/main/BasicApp.h index 19f07d1e5b5..62757da836b 100644 --- a/src/xrpld/app/main/BasicApp.h +++ b/src/xrpld/app/main/BasicApp.h @@ -24,7 +24,7 @@ class BasicApp return io_context_; } - size_t + [[nodiscard]] size_t get_number_of_threads() const { return threads_.size(); diff --git a/src/xrpld/app/main/GRPCServer.h b/src/xrpld/app/main/GRPCServer.h index 215c1e037d1..489a11d24a6 100644 --- a/src/xrpld/app/main/GRPCServer.h +++ b/src/xrpld/app/main/GRPCServer.h @@ -127,7 +127,7 @@ class GRPCServerImpl final setupListeners(); // Obtaining actually binded endpoint (if port 0 was used for server setup). - boost::asio::ip::tcp::endpoint + [[nodiscard]] boost::asio::ip::tcp::endpoint getEndpoint() const; private: @@ -305,7 +305,7 @@ class GRPCServer ~GRPCServer(); - boost::asio::ip::tcp::endpoint + [[nodiscard]] boost::asio::ip::tcp::endpoint getEndpoint() const; private: diff --git a/src/xrpld/app/main/Main.cpp b/src/xrpld/app/main/Main.cpp index 2ee2ac90cd0..3da6e3a2add 100644 --- a/src/xrpld/app/main/Main.cpp +++ b/src/xrpld/app/main/Main.cpp @@ -228,7 +228,7 @@ class multi_selector return false; } - std::size_t + [[nodiscard]] std::size_t size() const { return selectors_.size(); diff --git a/src/xrpld/app/misc/FeeVoteImpl.cpp b/src/xrpld/app/misc/FeeVoteImpl.cpp index 53e56286b8d..f6c60bc572c 100644 --- a/src/xrpld/app/misc/FeeVoteImpl.cpp +++ b/src/xrpld/app/misc/FeeVoteImpl.cpp @@ -58,13 +58,13 @@ class VotableValue addVote(current_); } - value_type + [[nodiscard]] value_type current() const { return current_; } - std::pair + [[nodiscard]] std::pair getVotes() const; }; diff --git a/src/xrpld/app/misc/SHAMapStore.h b/src/xrpld/app/misc/SHAMapStore.h index 6788d153928..22ba0cdbe2a 100644 --- a/src/xrpld/app/misc/SHAMapStore.h +++ b/src/xrpld/app/misc/SHAMapStore.h @@ -33,7 +33,7 @@ class SHAMapStore virtual void stop() = 0; - virtual std::uint32_t + [[nodiscard]] virtual std::uint32_t clampFetchDepth(std::uint32_t fetch_depth) const = 0; virtual std::unique_ptr @@ -44,7 +44,7 @@ class SHAMapStore setCanDelete(LedgerIndex canDelete) = 0; /** Whether advisory delete is enabled. */ - virtual bool + [[nodiscard]] virtual bool advisoryDelete() const = 0; /** Maximum ledger that has been deleted, or will be deleted if @@ -58,7 +58,7 @@ class SHAMapStore getCanDelete() = 0; /** Returns the number of file descriptors that are needed. */ - virtual int + [[nodiscard]] virtual int fdRequired() const = 0; /** The minimum ledger to try and maintain in our database. @@ -77,7 +77,7 @@ class SHAMapStore @return The minimum ledger sequence to keep online based on the description above. If not set, then an unseated optional. */ - virtual std::optional + [[nodiscard]] virtual std::optional minimumOnline() const = 0; }; diff --git a/src/xrpld/app/misc/Transaction.h b/src/xrpld/app/misc/Transaction.h index 31d899d99b2..40e0a3d10d2 100644 --- a/src/xrpld/app/misc/Transaction.h +++ b/src/xrpld/app/misc/Transaction.h @@ -174,7 +174,7 @@ class Transaction : public std::enable_shared_from_this, * @brief any Get true of any state is true * @return True if any state if true */ - bool + [[nodiscard]] bool any() const { return applied || broadcast || queued || kept; @@ -306,7 +306,7 @@ class Transaction : public std::enable_shared_from_this, // Call this function first to determine the type of the contained info. // Calling the wrong getter function will throw an exception. // See documentation for the getter functions for more details - bool + [[nodiscard]] bool isFound() const { return std::holds_alternative>(locator); diff --git a/src/xrpld/app/misc/TxQ.h b/src/xrpld/app/misc/TxQ.h index 0f734f7897f..ce32755db1b 100644 --- a/src/xrpld/app/misc/TxQ.h +++ b/src/xrpld/app/misc/TxQ.h @@ -422,7 +422,7 @@ class TxQ }; /// Get the current @ref Snapshot - Snapshot + [[nodiscard]] Snapshot getSnapshot() const { return {.txnsExpected = txnsExpected_, .escalationMultiplier = escalationMultiplier_}; @@ -575,7 +575,7 @@ class TxQ /// Potential @ref TxConsequences of applying this transaction /// to the open ledger. - TxConsequences const& + [[nodiscard]] TxConsequences const& consequences() const { return pfResult->consequences; // NOLINT(bugprone-unchecked-optional-access) invariant: @@ -583,7 +583,7 @@ class TxQ } /// Return a TxDetails based on contained information. - TxDetails + [[nodiscard]] TxDetails getTxDetails() const { return { @@ -665,21 +665,21 @@ class TxQ explicit TxQAccount(AccountID const& account); /// Return the number of transactions currently queued for this account - std::size_t + [[nodiscard]] std::size_t getTxnCount() const { return transactions.size(); } /// Checks if this account has no transactions queued - bool + [[nodiscard]] bool empty() const { return getTxnCount() == 0u; } /// Find the entry in transactions that precedes seqProx, if one does. - TxMap::const_iterator + [[nodiscard]] TxMap::const_iterator getPrevTx(SeqProxy seqProx) const; /// Add a transaction candidate to this account for queuing diff --git a/src/xrpld/app/misc/ValidatorKeys.h b/src/xrpld/app/misc/ValidatorKeys.h index 296c63e09e7..d3ce9960654 100644 --- a/src/xrpld/app/misc/ValidatorKeys.h +++ b/src/xrpld/app/misc/ValidatorKeys.h @@ -43,7 +43,7 @@ class ValidatorKeys ValidatorKeys() = delete; ValidatorKeys(Config const& config, beast::Journal j); - bool + [[nodiscard]] bool configInvalid() const { return configInvalid_; diff --git a/src/xrpld/app/misc/ValidatorList.h b/src/xrpld/app/misc/ValidatorList.h index ff5aa8c71fa..2c7900465c8 100644 --- a/src/xrpld/app/misc/ValidatorList.h +++ b/src/xrpld/app/misc/ValidatorList.h @@ -274,9 +274,9 @@ class ValidatorList explicit PublisherListStats(ListDisposition d); PublisherListStats(ListDisposition d, PublicKey key, PublisherStatus stat, std::size_t seq); - ListDisposition + [[nodiscard]] ListDisposition bestDisposition() const; - ListDisposition + [[nodiscard]] ListDisposition worstDisposition() const; void mergeDispositions(PublisherListStats const& src); diff --git a/src/xrpld/app/misc/detail/AmendmentTable.cpp b/src/xrpld/app/misc/detail/AmendmentTable.cpp index 0698230eb2f..65342dac2fa 100644 --- a/src/xrpld/app/misc/detail/AmendmentTable.cpp +++ b/src/xrpld/app/misc/detail/AmendmentTable.cpp @@ -334,7 +334,7 @@ class AmendmentSet amendmentMajorityCalcThreshold.den)); } - bool + [[nodiscard]] bool passes(uint256 const& amendment) const { auto const& it = votes_.find(amendment); @@ -350,7 +350,7 @@ class AmendmentSet return it->second > threshold_; } - int + [[nodiscard]] int votes(uint256 const& amendment) const { auto const& it = votes_.find(amendment); @@ -361,13 +361,13 @@ class AmendmentSet return it->second; } - int + [[nodiscard]] int trustedValidations() const { return trustedValidations_; } - int + [[nodiscard]] int threshold() const { return threshold_; diff --git a/src/xrpld/consensus/Consensus.h b/src/xrpld/consensus/Consensus.h index 68ea8fb4037..9edbebd429f 100644 --- a/src/xrpld/consensus/Consensus.h +++ b/src/xrpld/consensus/Consensus.h @@ -295,7 +295,7 @@ class Consensus MonitoredMode(ConsensusMode m) : mode_{m} { } - ConsensusMode + [[nodiscard]] ConsensusMode get() const { return mode_; @@ -408,7 +408,7 @@ class Consensus return prevLedgerID_; } - ConsensusPhase + [[nodiscard]] ConsensusPhase phase() const { return phase_; @@ -421,7 +421,7 @@ class Consensus @param full True if verbose response desired. @return The Json state. */ - Json::Value + [[nodiscard]] Json::Value getJson(bool full) const; private: @@ -500,7 +500,7 @@ class Consensus * * @return Whether to pause to wait for lagging proposers. */ - bool + [[nodiscard]] bool shouldPause(std::unique_ptr const& clog) const; // Close the open ledger and establish initial position. @@ -529,7 +529,7 @@ class Consensus leaveConsensus(std::unique_ptr const& clog); // The rounded or effective close time estimate from a proposer - NetClock::time_point + [[nodiscard]] NetClock::time_point asCloseTime(NetClock::time_point raw) const; private: diff --git a/src/xrpld/consensus/ConsensusTypes.h b/src/xrpld/consensus/ConsensusTypes.h index 8aba48f34e6..8a812117223 100644 --- a/src/xrpld/consensus/ConsensusTypes.h +++ b/src/xrpld/consensus/ConsensusTypes.h @@ -120,7 +120,7 @@ class ConsensusTimer std::chrono::milliseconds dur_{}; public: - std::chrono::milliseconds + [[nodiscard]] std::chrono::milliseconds read() const { return dur_; diff --git a/src/xrpld/consensus/DisputedTx.h b/src/xrpld/consensus/DisputedTx.h index 2172fd5d476..aff4ccae688 100644 --- a/src/xrpld/consensus/DisputedTx.h +++ b/src/xrpld/consensus/DisputedTx.h @@ -47,14 +47,14 @@ class DisputedTx } //! The unique id/hash of the disputed transaction. - TxID_t const& + [[nodiscard]] TxID_t const& ID() const { return tx_.id(); } //! Our vote on whether the transaction should be included. - bool + [[nodiscard]] bool getOurVote() const { return ourVote_; @@ -62,7 +62,7 @@ class DisputedTx //! Are we and our peers "stalled" where we probably won't change //! our vote? - bool + [[nodiscard]] bool stalled( ConsensusParms const& p, bool proposing, @@ -127,7 +127,7 @@ class DisputedTx } //! The disputed transaction. - Tx_t const& + [[nodiscard]] Tx_t const& tx() const { return tx_; @@ -173,7 +173,7 @@ class DisputedTx updateVote(int percentTime, bool proposing, ConsensusParms const& p); //! JSON representation of dispute, used for debugging - Json::Value + [[nodiscard]] Json::Value getJson() const; private: diff --git a/src/xrpld/consensus/LedgerTrie.h b/src/xrpld/consensus/LedgerTrie.h index 99ddb530dfb..d1518021584 100644 --- a/src/xrpld/consensus/LedgerTrie.h +++ b/src/xrpld/consensus/LedgerTrie.h @@ -41,7 +41,7 @@ class SpanTip @note s must be less than or equal to the sequence number of the tip ledger */ - ID + [[nodiscard]] ID ancestor(Seq const& s) const { XRPL_ASSERT(s <= seq, "xrpl::SpanTip::ancestor : valid input"); @@ -84,34 +84,34 @@ class Span Span& operator=(Span&&) = default; - Seq + [[nodiscard]] Seq start() const { return start_; } - Seq + [[nodiscard]] Seq end() const { return end_; } // Return the Span from [spot,end_) or none if no such valid span - std::optional + [[nodiscard]] std::optional from(Seq spot) const { return sub(spot, end_); } // Return the Span from [start_,spot) or none if no such valid span - std::optional + [[nodiscard]] std::optional before(Seq spot) const { return sub(start_, spot); } // Return the ID of the ledger that starts this span - ID + [[nodiscard]] ID startID() const { return ledger_[start_]; @@ -119,14 +119,14 @@ class Span // Return the ledger sequence number of the first possible difference // between this span and a given ledger. - Seq + [[nodiscard]] Seq diff(Ledger const& o) const { return clamp(mismatch(ledger_, o)); } // The tip of this span - SpanTip + [[nodiscard]] SpanTip tip() const { Seq const tipSeq{end_ - Seq{1}}; @@ -140,14 +140,14 @@ class Span XRPL_ASSERT(start < end, "xrpl::Span::Span : non-empty span input"); } - Seq + [[nodiscard]] Seq clamp(Seq val) const { return std::min(std::max(start_, val), end_); } // Return a span of this over the half-open interval [from,to) - std::optional + [[nodiscard]] std::optional sub(Seq from, Seq to) const { Seq const newFrom = clamp(from); @@ -219,7 +219,7 @@ struct Node return o << s.span << "(T:" << s.tipSupport << ",B:" << s.branchSupport << ")"; } - Json::Value + [[nodiscard]] Json::Value getJson() const { Json::Value res; @@ -342,7 +342,7 @@ class LedgerTrie @return Pair of the found node and the sequence number of the first ledger difference. */ - std::pair + [[nodiscard]] std::pair find(Ledger const& ledger) const { // NOLINTNEXTLINE(misc-const-correctness) @@ -567,7 +567,7 @@ class LedgerTrie @param ledger The ledger to lookup @return The number of entries in the trie for this *exact* ledger */ - std::uint32_t + [[nodiscard]] std::uint32_t tipSupport(Ledger const& ledger) const { if (auto const* loc = findByLedgerID(ledger)) @@ -581,7 +581,7 @@ class LedgerTrie @return The number of entries in the trie for this ledger or a descendant */ - std::uint32_t + [[nodiscard]] std::uint32_t branchSupport(Ledger const& ledger) const { Node const* loc = findByLedgerID(ledger); @@ -655,7 +655,7 @@ class LedgerTrie @return Pair with the sequence number and ID of the preferred ledger or std::nullopt if no preferred ledger exists */ - std::optional> + [[nodiscard]] std::optional> getPreferred(Seq const largestIssued) const { if (empty()) @@ -758,7 +758,7 @@ class LedgerTrie /** Return whether the trie is tracking any ledgers */ - bool + [[nodiscard]] bool empty() const { return !root || root->branchSupport == 0; @@ -774,7 +774,7 @@ class LedgerTrie /** Dump JSON representation of trie state */ - Json::Value + [[nodiscard]] Json::Value getJson() const { Json::Value res; @@ -787,7 +787,7 @@ class LedgerTrie /** Check the compressed trie and support invariants. */ - bool + [[nodiscard]] bool checkInvariants() const { std::map expectedSeqSupport; diff --git a/src/xrpld/consensus/Validations.h b/src/xrpld/consensus/Validations.h index 00f10f89cfa..46b0ef0b321 100644 --- a/src/xrpld/consensus/Validations.h +++ b/src/xrpld/consensus/Validations.h @@ -107,7 +107,7 @@ class SeqEnforcer return true; } - Seq + [[nodiscard]] Seq largest() const { return seq_; diff --git a/src/xrpld/core/Config.h b/src/xrpld/core/Config.h index d4d8396ba5c..5dd08de74fd 100644 --- a/src/xrpld/core/Config.h +++ b/src/xrpld/core/Config.h @@ -60,7 +60,7 @@ struct FeeSetup * values.) */ /** Convert to a Fees object for use with Ledger construction. */ - Fees + [[nodiscard]] Fees toFees() const { return Fees{reference_fee, account_reserve, owner_reserve}; @@ -82,7 +82,7 @@ class Config : public BasicConfig static char const* const validatorsFileName; /** Returns the full path and filename of the debug log file. */ - boost::filesystem::path + [[nodiscard]] boost::filesystem::path getDebugLogFile() const; private: @@ -302,29 +302,29 @@ class Config : public BasicConfig void loadFromString(std::string const& fileContents); - bool + [[nodiscard]] bool quiet() const { return QUIET; } - bool + [[nodiscard]] bool silent() const { return SILENT; } - bool + [[nodiscard]] bool standalone() const { return RUN_STANDALONE; } - bool + [[nodiscard]] bool useTxTables() const { return USE_TX_TABLES; } - bool + [[nodiscard]] bool canSign() const { return signingEnabled_; @@ -347,10 +347,10 @@ class Config : public BasicConfig the underlying system; this means that we can't provide optimal defaults in the code for every case. */ - int + [[nodiscard]] int getValueFor(SizedItem item, std::optional node = std::nullopt) const; - beast::Journal + [[nodiscard]] beast::Journal journal() const { return j_; diff --git a/src/xrpld/core/NetworkIDServiceImpl.h b/src/xrpld/core/NetworkIDServiceImpl.h index 1176f8d4acd..2236a854fff 100644 --- a/src/xrpld/core/NetworkIDServiceImpl.h +++ b/src/xrpld/core/NetworkIDServiceImpl.h @@ -22,7 +22,7 @@ class NetworkIDServiceImpl final : public NetworkIDService ~NetworkIDServiceImpl() override = default; - std::uint32_t + [[nodiscard]] std::uint32_t getNetworkID() const noexcept override; private: diff --git a/src/xrpld/overlay/ClusterNode.h b/src/xrpld/overlay/ClusterNode.h index 3e319ef8bec..3a504a57333 100644 --- a/src/xrpld/overlay/ClusterNode.h +++ b/src/xrpld/overlay/ClusterNode.h @@ -23,25 +23,25 @@ class ClusterNode { } - std::string const& + [[nodiscard]] std::string const& name() const { return name_; } - std::uint32_t + [[nodiscard]] std::uint32_t getLoadFee() const { return mLoadFee; } - NetClock::time_point + [[nodiscard]] NetClock::time_point getReportTime() const { return mReportTime; } - PublicKey const& + [[nodiscard]] PublicKey const& identity() const { return identity_; diff --git a/src/xrpld/overlay/Overlay.h b/src/xrpld/overlay/Overlay.h index 2c2371a1d15..f42ef64b9a7 100644 --- a/src/xrpld/overlay/Overlay.h +++ b/src/xrpld/overlay/Overlay.h @@ -85,7 +85,7 @@ class Overlay : public beast::PropertyStream::Source Active peers are only those peers that have completed the handshake and are using the peer protocol. */ - virtual std::size_t + [[nodiscard]] virtual std::size_t size() const = 0; /** Return diagnostics on the status of all peers. @@ -97,7 +97,7 @@ class Overlay : public beast::PropertyStream::Source /** Returns a sequence representing the current list of peers. The snapshot is made at the time of the call. */ - virtual PeerSequence + [[nodiscard]] virtual PeerSequence getActivePeers() const = 0; /** Calls the checkTracking function on each peer @@ -107,7 +107,7 @@ class Overlay : public beast::PropertyStream::Source checkTracking(std::uint32_t index) = 0; /** Returns the peer with the matching short id, or null. */ - virtual std::shared_ptr + [[nodiscard]] virtual std::shared_ptr findPeerByShortID(Peer::id_t const& id) const = 0; /** Returns the peer with the matching public key, or null. */ @@ -171,7 +171,7 @@ class Overlay : public beast::PropertyStream::Source /** Increment and retrieve counter for transaction job queue overflows. */ virtual void incJqTransOverflow() = 0; - virtual std::uint64_t + [[nodiscard]] virtual std::uint64_t getJqTransOverflow() const = 0; /** Increment and retrieve counters for total peer disconnects, and @@ -179,11 +179,11 @@ class Overlay : public beast::PropertyStream::Source */ virtual void incPeerDisconnect() = 0; - virtual std::uint64_t + [[nodiscard]] virtual std::uint64_t getPeerDisconnect() const = 0; virtual void incPeerDisconnectCharges() = 0; - virtual std::uint64_t + [[nodiscard]] virtual std::uint64_t getPeerDisconnectCharges() const = 0; /** Returns the ID of the network this server is configured for, if any. @@ -194,13 +194,13 @@ class Overlay : public beast::PropertyStream::Source @return The numerical identifier configured by the administrator of the server. An unseated optional, otherwise. */ - virtual std::optional + [[nodiscard]] virtual std::optional networkID() const = 0; /** Returns tx reduce-relay metrics @return json value of tx reduce-relay metrics */ - virtual Json::Value + [[nodiscard]] virtual Json::Value txMetrics() const = 0; }; diff --git a/src/xrpld/overlay/Peer.h b/src/xrpld/overlay/Peer.h index df2cc5bcb73..5955c978381 100644 --- a/src/xrpld/overlay/Peer.h +++ b/src/xrpld/overlay/Peer.h @@ -41,7 +41,7 @@ class Peer virtual void send(std::shared_ptr const& m) = 0; - virtual beast::IP::Endpoint + [[nodiscard]] virtual beast::IP::Endpoint getRemoteAddress() const = 0; /** Send aggregated transactions' hashes. */ @@ -64,57 +64,57 @@ class Peer // Identity // - virtual id_t + [[nodiscard]] virtual id_t id() const = 0; /** Returns `true` if this connection is a member of the cluster. */ - virtual bool + [[nodiscard]] virtual bool cluster() const = 0; - virtual bool + [[nodiscard]] virtual bool isHighLatency() const = 0; - virtual int + [[nodiscard]] virtual int getScore(bool) const = 0; - virtual PublicKey const& + [[nodiscard]] virtual PublicKey const& getNodePublic() const = 0; virtual Json::Value json() = 0; - virtual bool + [[nodiscard]] virtual bool supportsFeature(ProtocolFeature f) const = 0; - virtual std::optional + [[nodiscard]] virtual std::optional publisherListSequence(PublicKey const&) const = 0; virtual void setPublisherListSequence(PublicKey const&, std::size_t const) = 0; - virtual std::string const& + [[nodiscard]] virtual std::string const& fingerprint() const = 0; // // Ledger // - virtual uint256 const& + [[nodiscard]] virtual uint256 const& getClosedLedgerHash() const = 0; - virtual bool + [[nodiscard]] virtual bool hasLedger(uint256 const& hash, std::uint32_t seq) const = 0; virtual void ledgerRange(std::uint32_t& minSeq, std::uint32_t& maxSeq) const = 0; - virtual bool + [[nodiscard]] virtual bool hasTxSet(uint256 const& hash) const = 0; virtual void cycleStatus() = 0; virtual bool hasRange(std::uint32_t uMin, std::uint32_t uMax) = 0; - virtual bool + [[nodiscard]] virtual bool compressionEnabled() const = 0; - virtual bool + [[nodiscard]] virtual bool txReduceRelayEnabled() const = 0; }; diff --git a/src/xrpld/overlay/PeerSet.h b/src/xrpld/overlay/PeerSet.h index b69d139b4f6..83cb40d84ff 100644 --- a/src/xrpld/overlay/PeerSet.h +++ b/src/xrpld/overlay/PeerSet.h @@ -48,7 +48,7 @@ class PeerSet std::shared_ptr const& peer) = 0; /** get the set of ids of previously added peers */ - virtual std::set const& + [[nodiscard]] virtual std::set const& getPeerIds() const = 0; }; diff --git a/src/xrpld/overlay/Slot.h b/src/xrpld/overlay/Slot.h index d7f3e9b4d30..896bf566596 100644 --- a/src/xrpld/overlay/Slot.h +++ b/src/xrpld/overlay/Slot.h @@ -141,35 +141,35 @@ class Slot final deletePeer(PublicKey const& validator, id_t id, bool erase); /** Get the time of the last peer selection round */ - time_point const& + [[nodiscard]] time_point const& getLastSelected() const { return lastSelected_; } /** Return number of peers in state */ - std::uint16_t + [[nodiscard]] std::uint16_t inState(PeerState state) const; /** Return number of peers not in state */ - std::uint16_t + [[nodiscard]] std::uint16_t notInState(PeerState state) const; /** Return Slot's state */ - SlotState + [[nodiscard]] SlotState getState() const { return state_; } /** Return selected peers */ - std::set + [[nodiscard]] std::set getSelected() const; /** Get peers info. Return map of peer's state, count, squelch * expiration milsec, and last message time milsec. */ - std::unordered_map> + [[nodiscard]] std::unordered_map> getPeers() const; /** Check if peers stopped relaying messages. If a peer is @@ -609,7 +609,7 @@ class Slots final deleteIdlePeers(); /** Return number of peers in state */ - std::optional + [[nodiscard]] std::optional inState(PublicKey const& validator, PeerState state) const { auto const& it = slots_.find(validator); @@ -619,7 +619,7 @@ class Slots final } /** Return number of peers not in state */ - std::optional + [[nodiscard]] std::optional notInState(PublicKey const& validator, PeerState state) const { auto const& it = slots_.find(validator); @@ -629,7 +629,7 @@ class Slots final } /** Return true if Slot is in state */ - bool + [[nodiscard]] bool inState(PublicKey const& validator, SlotState state) const { auto const& it = slots_.find(validator); diff --git a/src/xrpld/overlay/detail/PeerSet.cpp b/src/xrpld/overlay/detail/PeerSet.cpp index 8d3d79d3584..a1eb41d0230 100644 --- a/src/xrpld/overlay/detail/PeerSet.cpp +++ b/src/xrpld/overlay/detail/PeerSet.cpp @@ -40,7 +40,7 @@ class PeerSetImpl : public PeerSet protocol::MessageType type, std::shared_ptr const& peer) override; - std::set const& + [[nodiscard]] std::set const& getPeerIds() const override; private: @@ -164,7 +164,7 @@ class DummyPeerSet : public PeerSet JLOG(j_.error()) << "DummyPeerSet sendRequest should not be called"; } - std::set const& + [[nodiscard]] std::set const& getPeerIds() const override { static std::set const emptyPeers; diff --git a/src/xrpld/overlay/detail/TrafficCount.h b/src/xrpld/overlay/detail/TrafficCount.h index bdc0729a515..736c3b76e30 100644 --- a/src/xrpld/overlay/detail/TrafficCount.h +++ b/src/xrpld/overlay/detail/TrafficCount.h @@ -217,7 +217,7 @@ class TrafficCount @return an object which satisfies the requirements of Container */ - auto const& + [[nodiscard]] auto const& getCounts() const { return counts_; diff --git a/src/xrpld/overlay/detail/ZeroCopyStream.h b/src/xrpld/overlay/detail/ZeroCopyStream.h index 034f69a8da2..d8d311105d2 100644 --- a/src/xrpld/overlay/detail/ZeroCopyStream.h +++ b/src/xrpld/overlay/detail/ZeroCopyStream.h @@ -37,7 +37,7 @@ class ZeroCopyInputStream : public ::google::protobuf::io::ZeroCopyInputStream bool Skip(int count) override; - google::protobuf::int64 + [[nodiscard]] google::protobuf::int64 ByteCount() const override { return count_; @@ -132,7 +132,7 @@ class ZeroCopyOutputStream : public ::google::protobuf::io::ZeroCopyOutputStream void BackUp(int count) override; - google::protobuf::int64 + [[nodiscard]] google::protobuf::int64 ByteCount() const override { return count_; diff --git a/src/xrpld/peerfinder/PeerfinderManager.h b/src/xrpld/peerfinder/PeerfinderManager.h index 1ceaebe04d1..f5a7b044b59 100644 --- a/src/xrpld/peerfinder/PeerfinderManager.h +++ b/src/xrpld/peerfinder/PeerfinderManager.h @@ -65,7 +65,7 @@ struct Config Config(); /** Returns a suitable value for outPeers according to the rules. */ - std::size_t + [[nodiscard]] std::size_t calcOutPeers() const; /** Adjusts the values so they follow the business rules. */ diff --git a/src/xrpld/peerfinder/Slot.h b/src/xrpld/peerfinder/Slot.h index 81249f54df4..5c459b25eaf 100644 --- a/src/xrpld/peerfinder/Slot.h +++ b/src/xrpld/peerfinder/Slot.h @@ -18,42 +18,42 @@ class Slot virtual ~Slot() = 0; /** Returns `true` if this is an inbound connection. */ - virtual bool + [[nodiscard]] virtual bool inbound() const = 0; /** Returns `true` if this is a fixed connection. A connection is fixed if its remote endpoint is in the list of remote endpoints for fixed connections. */ - virtual bool + [[nodiscard]] virtual bool fixed() const = 0; /** Returns `true` if this is a reserved connection. It might be a cluster peer, or a peer with a reservation. This is only known after then handshake completes. */ - virtual bool + [[nodiscard]] virtual bool reserved() const = 0; /** Returns the state of the connection. */ - virtual State + [[nodiscard]] virtual State state() const = 0; /** The remote endpoint of socket. */ - virtual beast::IP::Endpoint const& + [[nodiscard]] virtual beast::IP::Endpoint const& remote_endpoint() const = 0; /** The local endpoint of the socket, when known. */ - virtual std::optional const& + [[nodiscard]] virtual std::optional const& local_endpoint() const = 0; - virtual std::optional + [[nodiscard]] virtual std::optional listening_port() const = 0; /** The peer's public key, when known. The public key is established when the handshake is complete. */ - virtual std::optional const& + [[nodiscard]] virtual std::optional const& public_key() const = 0; }; diff --git a/src/xrpld/peerfinder/detail/Bootcache.h b/src/xrpld/peerfinder/detail/Bootcache.h index 5405dd3432f..0fc0be33db1 100644 --- a/src/xrpld/peerfinder/detail/Bootcache.h +++ b/src/xrpld/peerfinder/detail/Bootcache.h @@ -45,7 +45,7 @@ class Bootcache return m_valence; } - int + [[nodiscard]] int valence() const { return m_valence; @@ -108,22 +108,22 @@ class Bootcache ~Bootcache(); /** Returns `true` if the cache is empty. */ - bool + [[nodiscard]] bool empty() const; /** Returns the number of entries in the cache. */ - map_type::size_type + [[nodiscard]] map_type::size_type size() const; /** IP::Endpoint iterators that traverse in decreasing valence. */ /** @{ */ - const_iterator + [[nodiscard]] const_iterator begin() const; - const_iterator + [[nodiscard]] const_iterator cbegin() const; - const_iterator + [[nodiscard]] const_iterator end() const; - const_iterator + [[nodiscard]] const_iterator cend() const; void clear(); diff --git a/src/xrpld/peerfinder/detail/Counts.h b/src/xrpld/peerfinder/detail/Counts.h index e3d120b4142..811758b0b32 100644 --- a/src/xrpld/peerfinder/detail/Counts.h +++ b/src/xrpld/peerfinder/detail/Counts.h @@ -27,7 +27,7 @@ class Counts } /** Returns `true` if the slot can become active. */ - bool + [[nodiscard]] bool can_activate(Slot const& s) const { // Must be handshaked and in the right state @@ -45,7 +45,7 @@ class Counts } /** Returns the number of attempts needed to bring us to the max. */ - std::size_t + [[nodiscard]] std::size_t attempts_needed() const { if (m_attempts >= Tuning::maxConnectAttempts) @@ -54,14 +54,14 @@ class Counts } /** Returns the number of outbound connection attempts. */ - std::size_t + [[nodiscard]] std::size_t attempts() const { return m_attempts; } /** Returns the total number of outbound slots. */ - int + [[nodiscard]] int out_max() const { return m_out_max; @@ -70,21 +70,21 @@ class Counts /** Returns the number of outbound peers assigned an open slot. Fixed peers do not count towards outbound slots used. */ - int + [[nodiscard]] int out_active() const { return m_out_active; } /** Returns the number of fixed connections. */ - std::size_t + [[nodiscard]] std::size_t fixed() const { return m_fixed; } /** Returns the number of active fixed connections. */ - std::size_t + [[nodiscard]] std::size_t fixed_active() const { return m_fixed_active; @@ -102,42 +102,42 @@ class Counts } /** Returns the number of accepted connections that haven't handshaked. */ - int + [[nodiscard]] int acceptCount() const { return m_acceptCount; } /** Returns the number of connection attempts currently active. */ - int + [[nodiscard]] int connectCount() const { return m_attempts; } /** Returns the number of connections that are gracefully closing. */ - int + [[nodiscard]] int closingCount() const { return m_closingCount; } /** Returns the total number of inbound slots. */ - int + [[nodiscard]] int in_max() const { return m_in_max; } /** Returns the number of inbound peers assigned an open slot. */ - int + [[nodiscard]] int inboundActive() const { return m_in_active; } /** Returns the total number of active peers excluding fixed peers. */ - int + [[nodiscard]] int totalActive() const { return m_in_active + m_out_active; @@ -146,7 +146,7 @@ class Counts /** Returns the number of unused inbound slots. Fixed peers do not deduct from inbound slots or count towards totals. */ - int + [[nodiscard]] int inboundSlotsFree() const { if (m_in_active < m_in_max) @@ -157,7 +157,7 @@ class Counts /** Returns the number of unused outbound slots. Fixed peers do not deduct from outbound slots or count towards totals. */ - int + [[nodiscard]] int outboundSlotsFree() const { if (m_out_active < m_out_max) @@ -169,7 +169,7 @@ class Counts /** Returns true if the slot logic considers us "connected" to the network. */ - bool + [[nodiscard]] bool isConnectedToNetwork() const { // We will consider ourselves connected if we have reached @@ -196,7 +196,7 @@ class Counts } /** Records the state for diagnostics. */ - std::string + [[nodiscard]] std::string state_string() const { std::stringstream ss; diff --git a/src/xrpld/peerfinder/detail/Fixed.h b/src/xrpld/peerfinder/detail/Fixed.h index b898c6ce3fe..497658fd40e 100644 --- a/src/xrpld/peerfinder/detail/Fixed.h +++ b/src/xrpld/peerfinder/detail/Fixed.h @@ -15,7 +15,7 @@ class Fixed Fixed(Fixed const&) = default; /** Returns the time after which we should allow a connection attempt. */ - clock_type::time_point const& + [[nodiscard]] clock_type::time_point const& when() const { return m_when; diff --git a/src/xrpld/peerfinder/detail/Handouts.h b/src/xrpld/peerfinder/detail/Handouts.h index 0d5eae7ef72..b93b0a32b81 100644 --- a/src/xrpld/peerfinder/detail/Handouts.h +++ b/src/xrpld/peerfinder/detail/Handouts.h @@ -85,13 +85,13 @@ class RedirectHandouts bool try_insert(Endpoint const& ep); - bool + [[nodiscard]] bool full() const { return list_.size() >= Tuning::redirectEndpointCount; } - SlotImp::ptr const& + [[nodiscard]] SlotImp::ptr const& slot() const { return slot_; @@ -103,7 +103,7 @@ class RedirectHandouts return list_; } - std::vector const& + [[nodiscard]] std::vector const& list() const { return list_; @@ -169,7 +169,7 @@ class SlotHandouts bool try_insert(Endpoint const& ep); - bool + [[nodiscard]] bool full() const { return list_.size() >= Tuning::numberOfEndpoints; @@ -181,13 +181,13 @@ class SlotHandouts list_.push_back(ep); } - SlotImp::ptr const& + [[nodiscard]] SlotImp::ptr const& slot() const { return slot_; } - std::vector const& + [[nodiscard]] std::vector const& list() const { return list_; @@ -265,13 +265,13 @@ class ConnectHandouts bool try_insert(beast::IP::Endpoint const& endpoint); - bool + [[nodiscard]] bool empty() const { return m_list.empty(); } - bool + [[nodiscard]] bool full() const { return m_list.size() >= m_needed; @@ -289,7 +289,7 @@ class ConnectHandouts return m_list; } - list_type const& + [[nodiscard]] list_type const& list() const { return m_list; diff --git a/src/xrpld/peerfinder/detail/Livecache.h b/src/xrpld/peerfinder/detail/Livecache.h index 5c5ed577afb..9b177d22bcd 100644 --- a/src/xrpld/peerfinder/detail/Livecache.h +++ b/src/xrpld/peerfinder/detail/Livecache.h @@ -74,49 +74,49 @@ class LivecacheBase using const_reverse_iterator = reverse_iterator; - iterator + [[nodiscard]] iterator begin() const { return iterator(m_list.get().cbegin(), Transform()); } - iterator + [[nodiscard]] iterator cbegin() const { return iterator(m_list.get().cbegin(), Transform()); } - iterator + [[nodiscard]] iterator end() const { return iterator(m_list.get().cend(), Transform()); } - iterator + [[nodiscard]] iterator cend() const { return iterator(m_list.get().cend(), Transform()); } - reverse_iterator + [[nodiscard]] reverse_iterator rbegin() const { return reverse_iterator(m_list.get().crbegin(), Transform()); } - reverse_iterator + [[nodiscard]] reverse_iterator crbegin() const { return reverse_iterator(m_list.get().crbegin(), Transform()); } - reverse_iterator + [[nodiscard]] reverse_iterator rend() const { return reverse_iterator(m_list.get().crend(), Transform()); } - reverse_iterator + [[nodiscard]] reverse_iterator crend() const { return reverse_iterator(m_list.get().crend(), Transform()); @@ -239,13 +239,13 @@ class Livecache : protected detail::LivecacheBase return iterator(m_lists.begin(), Transform()); } - const_iterator + [[nodiscard]] const_iterator begin() const { return const_iterator(m_lists.cbegin(), Transform()); } - const_iterator + [[nodiscard]] const_iterator cbegin() const { return const_iterator(m_lists.cbegin(), Transform()); @@ -257,13 +257,13 @@ class Livecache : protected detail::LivecacheBase return iterator(m_lists.end(), Transform()); } - const_iterator + [[nodiscard]] const_iterator end() const { return const_iterator(m_lists.cend(), Transform()); } - const_iterator + [[nodiscard]] const_iterator cend() const { return const_iterator(m_lists.cend(), Transform()); @@ -275,13 +275,13 @@ class Livecache : protected detail::LivecacheBase return reverse_iterator(m_lists.rbegin(), Transform()); } - const_reverse_iterator + [[nodiscard]] const_reverse_iterator rbegin() const { return const_reverse_iterator(m_lists.crbegin(), Transform()); } - const_reverse_iterator + [[nodiscard]] const_reverse_iterator crbegin() const { return const_reverse_iterator(m_lists.crbegin(), Transform()); @@ -293,13 +293,13 @@ class Livecache : protected detail::LivecacheBase return reverse_iterator(m_lists.rend(), Transform()); } - const_reverse_iterator + [[nodiscard]] const_reverse_iterator rend() const { return const_reverse_iterator(m_lists.crend(), Transform()); } - const_reverse_iterator + [[nodiscard]] const_reverse_iterator crend() const { return const_reverse_iterator(m_lists.crend(), Transform()); @@ -309,7 +309,7 @@ class Livecache : protected detail::LivecacheBase void shuffle(); - std::string + [[nodiscard]] std::string histogram() const; private: @@ -331,7 +331,7 @@ class Livecache : protected detail::LivecacheBase } hops; /** Returns `true` if the cache is empty. */ - bool + [[nodiscard]] bool empty() const { return m_cache.empty(); diff --git a/src/xrpld/rpc/ServerHandler.h b/src/xrpld/rpc/ServerHandler.h index 2ffdc9556b9..da6e36fc330 100644 --- a/src/xrpld/rpc/ServerHandler.h +++ b/src/xrpld/rpc/ServerHandler.h @@ -115,13 +115,13 @@ class ServerHandler void setup(Setup const& setup, beast::Journal journal); - Setup const& + [[nodiscard]] Setup const& setup() const { return setup_; } - Endpoints const& + [[nodiscard]] Endpoints const& endpoints() const { return endpoints_; @@ -187,7 +187,7 @@ class ServerHandler std::string_view forwardedFor, std::string_view user); - Handoff + [[nodiscard]] Handoff statusResponse(http_request_type const& request) const; }; diff --git a/src/xrpld/rpc/Status.h b/src/xrpld/rpc/Status.h index f0c6d932e70..ecd4c2c0585 100644 --- a/src/xrpld/rpc/Status.h +++ b/src/xrpld/rpc/Status.h @@ -50,7 +50,7 @@ struct Status : public std::exception /* Returns a representation of the integer status Code as a string. If the Status is OK, the result is an empty string. */ - std::string + [[nodiscard]] std::string codeString() const; /** Returns true if the Status is *not* OK. */ @@ -68,7 +68,7 @@ struct Status : public std::exception /** Returns the Status as a TER. This may only be called if type() == Type::TER. */ - TER + [[nodiscard]] TER toTER() const { XRPL_ASSERT(type_ == Type::TER, "xrpl::RPC::Status::toTER : type is TER"); @@ -77,7 +77,7 @@ struct Status : public std::exception /** Returns the Status as an error_code_i. This may only be called if type() == Type::error_code_i. */ - error_code_i + [[nodiscard]] error_code_i toErrorCode() const { XRPL_ASSERT(type_ == Type::error_code_i, "xrpl::RPC::Status::toTER : type is error code"); @@ -102,23 +102,23 @@ struct Status : public std::exception } } - Strings const& + [[nodiscard]] Strings const& messages() const { return messages_; } /** Return the first message, if any. */ - std::string + [[nodiscard]] std::string message() const; - Type + [[nodiscard]] Type type() const { return type_; } - std::string + [[nodiscard]] std::string toString() const; /** Fill a Json::Value with an RPC 2.0 response. diff --git a/src/xrpld/rpc/detail/AssetCache.h b/src/xrpld/rpc/detail/AssetCache.h index 0709df2c5fc..0597c729f12 100644 --- a/src/xrpld/rpc/detail/AssetCache.h +++ b/src/xrpld/rpc/detail/AssetCache.h @@ -20,7 +20,7 @@ class AssetCache final : public CountedObject explicit AssetCache(std::shared_ptr const& l, beast::Journal j); ~AssetCache(); - std::shared_ptr const& + [[nodiscard]] std::shared_ptr const& getLedger() const { return ledger_; @@ -75,7 +75,7 @@ class AssetCache final : public CountedObject direction_ == lhs.direction_; } - std::size_t + [[nodiscard]] std::size_t get_hash() const { return hash_value_; diff --git a/src/xrpld/rpc/detail/LegacyPathFind.h b/src/xrpld/rpc/detail/LegacyPathFind.h index 3d45bc9cfd3..c9ac08f549f 100644 --- a/src/xrpld/rpc/detail/LegacyPathFind.h +++ b/src/xrpld/rpc/detail/LegacyPathFind.h @@ -14,7 +14,7 @@ class LegacyPathFind LegacyPathFind(bool isAdmin, Application& app); ~LegacyPathFind(); - bool + [[nodiscard]] bool isOk() const { return m_isOk; diff --git a/src/xrpld/rpc/detail/MPT.h b/src/xrpld/rpc/detail/MPT.h index 61dcb8fa7dc..5cf2d5490ff 100644 --- a/src/xrpld/rpc/detail/MPT.h +++ b/src/xrpld/rpc/detail/MPT.h @@ -25,17 +25,17 @@ class PathFindMPT final { return mptID_; } - MPTID const& + [[nodiscard]] MPTID const& getMptID() const { return mptID_; } - bool + [[nodiscard]] bool isZeroBalance() const { return zeroBalance_; } - bool + [[nodiscard]] bool isMaxedOut() const { return maxedOut_; diff --git a/src/xrpld/rpc/detail/TransactionSign.cpp b/src/xrpld/rpc/detail/TransactionSign.cpp index 92b6d730507..85d5a62efce 100644 --- a/src/xrpld/rpc/detail/TransactionSign.cpp +++ b/src/xrpld/rpc/detail/TransactionSign.cpp @@ -86,33 +86,33 @@ class SigningForParams { } - bool + [[nodiscard]] bool isMultiSigning() const { return multiSigningAcctID_ != nullptr; } - bool + [[nodiscard]] bool isSingleSigning() const { return !isMultiSigning(); } // When multi-signing we should not edit the tx_json fields. - bool + [[nodiscard]] bool editFields() const { return !isMultiSigning(); } - bool + [[nodiscard]] bool validMultiSign() const { return isMultiSigning() && multiSignPublicKey_ && !multiSignature_.empty(); } // Don't call this method unless isMultiSigning() returns true. - AccountID const& + [[nodiscard]] AccountID const& getSigner() const { if (multiSigningAcctID_ == nullptr) @@ -120,7 +120,7 @@ class SigningForParams return *multiSigningAcctID_; } - PublicKey const& + [[nodiscard]] PublicKey const& getPublicKey() const { if (!multiSignPublicKey_) @@ -128,13 +128,13 @@ class SigningForParams return *multiSignPublicKey_; } - Buffer const& + [[nodiscard]] Buffer const& getSignature() const { return multiSignature_; } - std::optional> const& + [[nodiscard]] std::optional> const& getSignatureTarget() const { return signatureTarget_; diff --git a/src/xrpld/rpc/detail/TrustLine.h b/src/xrpld/rpc/detail/TrustLine.h index 59fa2e73f35..176bea1759c 100644 --- a/src/xrpld/rpc/detail/TrustLine.h +++ b/src/xrpld/rpc/detail/TrustLine.h @@ -47,7 +47,7 @@ class TrustLineBase public: /** Returns the state map key for the ledger entry. */ - uint256 const& + [[nodiscard]] uint256 const& key() const { return key_; @@ -55,96 +55,96 @@ class TrustLineBase // VFALCO Take off the "get" from each function name - AccountID const& + [[nodiscard]] AccountID const& getAccountID() const { return mViewLowest ? mLowLimit.getIssuer() : mHighLimit.getIssuer(); } - AccountID const& + [[nodiscard]] AccountID const& getAccountIDPeer() const { return !mViewLowest ? mLowLimit.getIssuer() : mHighLimit.getIssuer(); } // True, Provided auth to peer. - bool + [[nodiscard]] bool getAuth() const { return (mFlags & (mViewLowest ? lsfLowAuth : lsfHighAuth)) != 0u; } - bool + [[nodiscard]] bool getAuthPeer() const { return (mFlags & (!mViewLowest ? lsfLowAuth : lsfHighAuth)) != 0u; } - bool + [[nodiscard]] bool getNoRipple() const { return (mFlags & (mViewLowest ? lsfLowNoRipple : lsfHighNoRipple)) != 0u; } - bool + [[nodiscard]] bool getNoRipplePeer() const { return (mFlags & (!mViewLowest ? lsfLowNoRipple : lsfHighNoRipple)) != 0u; } - LineDirection + [[nodiscard]] LineDirection getDirection() const { return getNoRipple() ? LineDirection::incoming : LineDirection::outgoing; } - LineDirection + [[nodiscard]] LineDirection getDirectionPeer() const { return getNoRipplePeer() ? LineDirection::incoming : LineDirection::outgoing; } /** Have we set the freeze flag on our peer */ - bool + [[nodiscard]] bool getFreeze() const { return (mFlags & (mViewLowest ? lsfLowFreeze : lsfHighFreeze)) != 0u; } /** Have we set the deep freeze flag on our peer */ - bool + [[nodiscard]] bool getDeepFreeze() const { return (mFlags & (mViewLowest ? lsfLowDeepFreeze : lsfHighDeepFreeze)) != 0u; } /** Has the peer set the freeze flag on us */ - bool + [[nodiscard]] bool getFreezePeer() const { return (mFlags & (!mViewLowest ? lsfLowFreeze : lsfHighFreeze)) != 0u; } /** Has the peer set the deep freeze flag on us */ - bool + [[nodiscard]] bool getDeepFreezePeer() const { return (mFlags & (!mViewLowest ? lsfLowDeepFreeze : lsfHighDeepFreeze)) != 0u; } - STAmount const& + [[nodiscard]] STAmount const& getBalance() const { return mBalance; } - STAmount const& + [[nodiscard]] STAmount const& getLimit() const { return mViewLowest ? mLowLimit : mHighLimit; } - STAmount const& + [[nodiscard]] STAmount const& getLimitPeer() const { return !mViewLowest ? mLowLimit : mHighLimit; @@ -192,13 +192,13 @@ class RPCTrustLine final : public TrustLineBase, public CountedObject const& sle, AccountID const& viewAccount); - Rate const& + [[nodiscard]] Rate const& getQualityIn() const { return mViewLowest ? lowQualityIn_ : highQualityIn_; } - Rate const& + [[nodiscard]] Rate const& getQualityOut() const { return mViewLowest ? lowQualityOut_ : highQualityOut_; diff --git a/src/xrpld/rpc/detail/WSInfoSub.h b/src/xrpld/rpc/detail/WSInfoSub.h index 4042cd54798..ec85262f61f 100644 --- a/src/xrpld/rpc/detail/WSInfoSub.h +++ b/src/xrpld/rpc/detail/WSInfoSub.h @@ -34,13 +34,13 @@ class WSInfoSub : public InfoSub } } - std::string_view + [[nodiscard]] std::string_view user() const { return user_; } - std::string_view + [[nodiscard]] std::string_view forwarded_for() const { return fwdfor_; diff --git a/src/xrpld/rpc/handlers/server_info/ServerDefinitions.cpp b/src/xrpld/rpc/handlers/server_info/ServerDefinitions.cpp index 76f123f4428..673d369690e 100644 --- a/src/xrpld/rpc/handlers/server_info/ServerDefinitions.cpp +++ b/src/xrpld/rpc/handlers/server_info/ServerDefinitions.cpp @@ -42,13 +42,13 @@ class ServerDefinitions public: ServerDefinitions(); - bool + [[nodiscard]] bool hashMatches(uint256 hash) const { return defsHash_ == hash; } - Json::Value const& + [[nodiscard]] Json::Value const& get() const { return defs_; diff --git a/src/xrpld/shamap/NodeFamily.h b/src/xrpld/shamap/NodeFamily.h index 3985a8bdf8a..e0655292a02 100644 --- a/src/xrpld/shamap/NodeFamily.h +++ b/src/xrpld/shamap/NodeFamily.h @@ -30,7 +30,7 @@ class NodeFamily : public Family return db_; } - NodeStore::Database const& + [[nodiscard]] NodeStore::Database const& db() const override { return db_; From 354711254004f160ed040d3193d12f2a4ed7fbaf Mon Sep 17 00:00:00 2001 From: Pratik Mankawde <3397372+pratikmankawde@users.noreply.github.com> Date: Mon, 27 Apr 2026 21:34:16 +0100 Subject: [PATCH 11/34] fix: Fix ubsan flagged issues (#6151) Signed-off-by: Pratik Mankawde <3397372+pratikmankawde@users.noreply.github.com> Co-authored-by: Claude Opus 4.6 Co-authored-by: xrplf-ai-reviewer[bot] <266832837+xrplf-ai-reviewer[bot]@users.noreply.github.com> --- .github/scripts/strategy-matrix/generate.py | 51 ++++-- include/xrpl/basics/DecayingSample.h | 4 +- include/xrpl/beast/test/yield_to.h | 4 +- include/xrpl/nodestore/detail/varint.h | 3 +- sanitizers/suppressions/ubsan.supp | 182 +++++--------------- src/libxrpl/basics/base64.cpp | 2 +- src/test/beast/LexicalCast_test.cpp | 2 +- src/xrpld/app/main/BasicApp.cpp | 6 +- src/xrpld/peerfinder/detail/Counts.h | 46 +++-- 9 files changed, 122 insertions(+), 178 deletions(-) diff --git a/.github/scripts/strategy-matrix/generate.py b/.github/scripts/strategy-matrix/generate.py index 4784142b7b7..dec41a2610f 100755 --- a/.github/scripts/strategy-matrix/generate.py +++ b/.github/scripts/strategy-matrix/generate.py @@ -51,20 +51,21 @@ def generate_strategy_matrix(all: bool, config: Config) -> list: # Only generate a subset of configurations in PRs. if not all: # Debian: - # - Bookworm using GCC 13: Release on linux/amd64, set the reference - # fee to 500. - # - Bookworm using GCC 15: Debug on linux/amd64, enable code - # coverage (which will be done below). + # - Bookworm using GCC 13: Debug on linux/amd64, set the reference + # fee to 500 and enable code coverage (which will be done below). + # - Bookworm using GCC 15: Debug on linux/amd64, enable Address and + # UB sanitizers (which will be done below). # - Bookworm using Clang 16: Debug on linux/amd64, enable voidstar. # - Bookworm using Clang 17: Release on linux/amd64, set the # reference fee to 1000. - # - Bookworm using Clang 20: Debug on linux/amd64. + # - Bookworm using Clang 20: Debug on linux/amd64, enable Address + # and UB sanitizers (which will be done below). if os["distro_name"] == "debian": skip = True if os["distro_version"] == "bookworm": if ( f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-13" - and build_type == "Release" + and build_type == "Debug" and architecture["platform"] == "linux/amd64" ): cmake_args = f"-DUNIT_TEST_REFERENCE_FEE=500 {cmake_args}" @@ -193,11 +194,11 @@ def generate_strategy_matrix(all: bool, config: Config) -> list: ): continue - # Enable code coverage for Debian Bookworm using GCC 15 in Debug on - # linux/amd64 + # Enable code coverage for Debian Bookworm using GCC 13 in Debug on + # linux/amd64. if ( f"{os['distro_name']}-{os['distro_version']}" == "debian-bookworm" - and f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-15" + and f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-13" and build_type == "Debug" and architecture["platform"] == "linux/amd64" ): @@ -234,23 +235,39 @@ def generate_strategy_matrix(all: bool, config: Config) -> list: # Add the configuration to the list, with the most unique fields first, # so that they are easier to identify in the GitHub Actions UI, as long # names get truncated. - # Add Address and Thread (both coupled with UB) sanitizers for specific bookworm distros. + # Add Address and UB sanitizers as separate configurations for specific + # bookworm distros. Thread sanitizer is currently disabled (see below). # GCC-Asan xrpld-embedded tests are failing because of https://github.com/google/sanitizers/issues/856 - if ( - os["distro_version"] == "bookworm" - and f"{os['compiler_name']}-{os['compiler_version']}" == "clang-20" - ): - # Add ASAN + UBSAN configuration. + if os[ + "distro_version" + ] == "bookworm" and f"{os['compiler_name']}-{os['compiler_version']}" in [ + "gcc-15", + "clang-20", + ]: + # Add ASAN configuration. + configurations.append( + { + "config_name": config_name + "-asan", + "cmake_args": cmake_args, + "cmake_target": cmake_target, + "build_only": build_only, + "build_type": build_type, + "os": os, + "architecture": architecture, + "sanitizers": "address", + } + ) + # Add UBSAN configuration. configurations.append( { - "config_name": config_name + "-asan-ubsan", + "config_name": config_name + "-ubsan", "cmake_args": cmake_args, "cmake_target": cmake_target, "build_only": build_only, "build_type": build_type, "os": os, "architecture": architecture, - "sanitizers": "address,undefinedbehavior", + "sanitizers": "undefinedbehavior", } ) # TSAN is deactivated due to seg faults with latest compilers. diff --git a/include/xrpl/basics/DecayingSample.h b/include/xrpl/basics/DecayingSample.h index d4c73880466..8f6e729acf3 100644 --- a/include/xrpl/basics/DecayingSample.h +++ b/include/xrpl/basics/DecayingSample.h @@ -67,8 +67,10 @@ class DecayingSample } else { - while ((elapsed--) != 0u) + for (; elapsed > 0; --elapsed) + { m_value -= (m_value + Window - 1) / Window; + } } } diff --git a/include/xrpl/beast/test/yield_to.h b/include/xrpl/beast/test/yield_to.h index e8db9e5864c..4723fb49b8d 100644 --- a/include/xrpl/beast/test/yield_to.h +++ b/include/xrpl/beast/test/yield_to.h @@ -43,8 +43,10 @@ class enable_yield_to : work_(boost::asio::make_work_guard(ios_)) { threads_.reserve(concurrency); - while ((concurrency--) != 0u) + for (std::size_t i = 0; i < concurrency; ++i) + { threads_.emplace_back([&] { ios_.run(); }); + } } ~enable_yield_to() diff --git a/include/xrpl/nodestore/detail/varint.h b/include/xrpl/nodestore/detail/varint.h index e63944c63b1..7c2a3756ff3 100644 --- a/include/xrpl/nodestore/detail/varint.h +++ b/include/xrpl/nodestore/detail/varint.h @@ -54,8 +54,9 @@ read_varint(void const* buf, std::size_t buflen, std::size_t& t) return 1; } auto const used = n; - while (n--) + while (n > 0) { + --n; auto const d = p[n]; auto const t0 = t; t *= 127; diff --git a/sanitizers/suppressions/ubsan.supp b/sanitizers/suppressions/ubsan.supp index 1e07065ebd6..88d8e82e337 100644 --- a/sanitizers/suppressions/ubsan.supp +++ b/sanitizers/suppressions/ubsan.supp @@ -11,7 +11,6 @@ float-cast-overflow:external float-divide-by-zero:external function:external implicit-integer-sign-change:external -implicit-signed-integer-truncation::external implicit-signed-integer-truncation:external implicit-unsigned-integer-truncation:external integer-divide-by-zero:external @@ -71,145 +70,15 @@ vla-bound:boost vptr_check:boost vptr:boost -# Google protobuf +# Google protobuf - intentional overflows in hash functions undefined:protobuf - -# Suppress UBSan errors in xrpld code by source file path -undefined:src/libxrpl/basics/base64.cpp -undefined:src/libxrpl/basics/Number.cpp -undefined:src/libxrpl/beast/utility/beast_Journal.cpp -undefined:src/libxrpl/crypto/RFC1751.cpp -undefined:src/libxrpl/ledger/ApplyView.cpp -undefined:src/libxrpl/ledger/View.cpp -undefined:src/libxrpl/protocol/Permissions.cpp -undefined:src/libxrpl/protocol/STAmount.cpp -undefined:src/libxrpl/protocol/STPathSet.cpp -undefined:src/libxrpl/protocol/tokens.cpp -undefined:src/libxrpl/shamap/SHAMap.cpp -undefined:src/test/app/Batch_test.cpp -undefined:src/test/app/Invariants_test.cpp -undefined:src/test/app/NFToken_test.cpp -undefined:src/test/app/Offer_test.cpp -undefined:src/test/app/Path_test.cpp -undefined:src/test/basics/XRPAmount_test.cpp -undefined:src/test/beast/LexicalCast_test.cpp -undefined:src/test/jtx/impl/acctdelete.cpp -undefined:src/test/ledger/SkipList_test.cpp -undefined:src/test/rpc/Subscribe_test.cpp -undefined:src/tests/libxrpl/basics/RangeSet.cpp -undefined:src/xrpld/app/main/BasicApp.cpp -undefined:src/xrpld/app/main/BasicApp.cpp -undefined:src/xrpld/app/misc/detail/AmendmentTable.cpp -undefined:src/xrpld/app/misc/NetworkOPs.cpp -undefined:src/libxrpl/json/json_value.cpp -undefined:src/xrpld/app/paths/detail/StrandFlow.h -undefined:src/xrpld/app/tx/detail/NFTokenMint.cpp -undefined:src/xrpld/app/tx/detail/OracleSet.cpp -undefined:src/xrpld/core/detail/JobQueue.cpp -undefined:src/xrpld/core/detail/Workers.cpp -undefined:src/xrpld/rpc/detail/Role.cpp -undefined:src/xrpld/rpc/handlers/GetAggregatePrice.cpp -undefined:xrpl/basics/base_uint.h -undefined:xrpl/basics/DecayingSample.h -undefined:xrpl/beast/test/yield_to.h -undefined:xrpl/beast/xor_shift_engine.h -undefined:xrpl/nodestore/detail/varint.h -undefined:xrpl/peerfinder/detail/Counts.h -undefined:xrpl/protocol/nft.h - -# basic_string.h:483:51: runtime error: unsigned integer overflow -unsigned-integer-overflow:basic_string.h -unsigned-integer-overflow:bits/chrono.h -unsigned-integer-overflow:bits/random.h -unsigned-integer-overflow:bits/random.tcc -unsigned-integer-overflow:bits/stl_algobase.h -unsigned-integer-overflow:bits/uniform_int_dist.h -unsigned-integer-overflow:string_view - -# runtime error: unsigned integer overflow: 0 - 1 cannot be represented in type 'std::size_t' (aka 'unsigned long') -unsigned-integer-overflow:src/libxrpl/basics/base64.cpp -unsigned-integer-overflow:src/libxrpl/basics/Number.cpp -unsigned-integer-overflow:src/libxrpl/crypto/RFC1751.cpp -unsigned-integer-overflow:rc/libxrpl/json/json_value.cpp -unsigned-integer-overflow:src/libxrpl/ledger/ApplyView.cpp -unsigned-integer-overflow:src/libxrpl/ledger/View.cpp -unsigned-integer-overflow:src/libxrpl/protocol/Permissions.cpp -unsigned-integer-overflow:src/libxrpl/protocol/STAmount.cpp -unsigned-integer-overflow:src/libxrpl/protocol/STPathSet.cpp -unsigned-integer-overflow:src/libxrpl/protocol/tokens.cpp -unsigned-integer-overflow:src/libxrpl/shamap/SHAMap.cpp -unsigned-integer-overflow:src/test/app/Batch_test.cpp -unsigned-integer-overflow:src/test/app/Invariants_test.cpp -unsigned-integer-overflow:src/test/app/NFToken_test.cpp -unsigned-integer-overflow:src/test/app/Offer_test.cpp -unsigned-integer-overflow:src/test/app/Path_test.cpp -unsigned-integer-overflow:src/test/basics/XRPAmount_test.cpp -unsigned-integer-overflow:src/test/beast/LexicalCast_test.cpp -unsigned-integer-overflow:src/test/jtx/impl/acctdelete.cpp -unsigned-integer-overflow:src/test/ledger/SkipList_test.cpp -unsigned-integer-overflow:src/test/rpc/Subscribe_test.cpp -unsigned-integer-overflow:src/tests/libxrpl/basics/RangeSet.cpp -unsigned-integer-overflow:src/xrpld/app/main/BasicApp.cpp -unsigned-integer-overflow:src/xrpld/app/misc/detail/AmendmentTable.cpp -unsigned-integer-overflow:src/xrpld/app/misc/NetworkOPs.cpp -unsigned-integer-overflow:src/xrpld/app/paths/detail/StrandFlow.h -unsigned-integer-overflow:src/xrpld/app/tx/detail/NFTokenMint.cpp -unsigned-integer-overflow:src/xrpld/app/tx/detail/OracleSet.cpp -unsigned-integer-overflow:src/xrpld/rpc/detail/Role.cpp -unsigned-integer-overflow:src/xrpld/rpc/handlers/GetAggregatePrice.cpp -unsigned-integer-overflow:xrpl/basics/base_uint.h -unsigned-integer-overflow:xrpl/basics/DecayingSample.h -unsigned-integer-overflow:xrpl/beast/test/yield_to.h -unsigned-integer-overflow:xrpl/beast/xor_shift_engine.h -unsigned-integer-overflow:xrpl/nodestore/detail/varint.h -unsigned-integer-overflow:xrpl/peerfinder/detail/Counts.h -unsigned-integer-overflow:xrpl/protocol/nft.h - -# Xrpld intentional overflows and operations -# STAmount uses intentional negation of INT64_MIN and overflow in arithmetic -signed-integer-overflow:src/libxrpl/protocol/STAmount.cpp -unsigned-integer-overflow:src/libxrpl/protocol/STAmount.cpp - -# XRPAmount test intentional overflows -signed-integer-overflow:src/test/basics/XRPAmount_test.cpp - -# Peerfinder intentional overflow in counter arithmetic -unsigned-integer-overflow:src/xrpld/peerfinder/detail/Counts.h - -# Signed integer overflow suppressions -signed-integer-overflow:src/test/beast/LexicalCast_test.cpp - -# External library suppressions -unsigned-integer-overflow:nudb/detail/xxhash.hpp - -# Loan_test.cpp intentional underflow in test arithmetic -unsigned-integer-overflow:src/test/app/Loan_test.cpp -undefined:src/test/app/Loan_test.cpp - -# Source tree restructured paths (libxrpl/tx/transactors/) -# These duplicate the xrpld/app/tx/detail entries above for the new layout -unsigned-integer-overflow:src/libxrpl/tx/transactors/oracle/OracleSet.cpp -undefined:src/libxrpl/tx/transactors/oracle/OracleSet.cpp -unsigned-integer-overflow:src/libxrpl/tx/transactors/nft/NFTokenMint.cpp -undefined:src/libxrpl/tx/transactors/nft/NFTokenMint.cpp - -# Protobuf intentional overflows in hash functions -# Protobuf uses intentional unsigned overflow for hash computation (stringpiece.h:393) unsigned-integer-overflow:google/protobuf/stubs/stringpiece.h -# gRPC intentional overflows -# gRPC uses intentional overflow in timer calculations +# gRPC intentional overflows in timer calculations unsigned-integer-overflow:grpc unsigned-integer-overflow:timer_manager.cc -# Standard library intentional overflows -# These are intentional overflows in random number generation and character conversion -unsigned-integer-overflow:__random/seed_seq.h -unsigned-integer-overflow:__charconv/traits.h - - -# Suppress errors in RocksDB -# RocksDB uses intentional unsigned integer overflows in hash functions and CRC calculations +# RocksDB intentional unsigned integer overflows in hash functions and CRC calculations unsigned-integer-overflow:rocks*/*/util/xxhash.h unsigned-integer-overflow:rocks*/*/util/xxph3.h unsigned-integer-overflow:rocks*/*/util/hash.cc @@ -221,13 +90,14 @@ unsigned-integer-overflow:rocks*/*/table/format.cc unsigned-integer-overflow:rocks*/*/table/block_based/block_based_table_builder.cc unsigned-integer-overflow:rocks*/*/table/block_based/reader_common.cc unsigned-integer-overflow:rocks*/*/db/version_set.cc - -# RocksDB misaligned loads (intentional for performance on ARM64) alignment:rocks*/*/util/crc32c_arm64.cc +undefined:rocks*/*/util/crc32c_arm64.cc +undefined:rocks*/*/util/xxhash.h # nudb intentional overflows in hash functions unsigned-integer-overflow:nudb/detail/xxhash.hpp alignment:nudb/detail/xxhash.hpp +undefined:nudb # Snappy compression library intentional overflows unsigned-integer-overflow:snappy.cc @@ -239,10 +109,40 @@ unsigned-integer-overflow:absl/base/internal/low_level_alloc.cc unsigned-integer-overflow:absl/hash/internal/hash.h unsigned-integer-overflow:absl/container/internal/raw_hash_set.h -# Standard library intentional overflows in chrono duration arithmetic +# Standard library intentional overflows +unsigned-integer-overflow:basic_string.h +unsigned-integer-overflow:bits/chrono.h +unsigned-integer-overflow:bits/random.h +unsigned-integer-overflow:bits/random.tcc +unsigned-integer-overflow:bits/stl_algobase.h +unsigned-integer-overflow:bits/uniform_int_dist.h +unsigned-integer-overflow:string_view +unsigned-integer-overflow:__random/seed_seq.h +unsigned-integer-overflow:__charconv/traits.h unsigned-integer-overflow:__chrono/duration.h -# Suppress undefined errors in RocksDB and nudb -undefined:rocks.*/*/util/crc32c_arm64.cc -undefined:rocks.*/*/util/xxhash.h -undefined:nudb +# ============================================================================= +# Rippled code suppressions +# ============================================================================= + +# Signed integer negation (-value) in amount types. +# INT64_MIN cannot occur in practice due to domain invariants (mantissa ranges +# are well within int64_t bounds), but UBSan flags the pattern as potential +# signed overflow. Narrowed to operator- to avoid suppressing unrelated +# overflows anywhere in a stack trace containing these type names. +signed-integer-overflow:operator-*IOUAmount* +signed-integer-overflow:operator-*XRPAmount* +signed-integer-overflow:operator-*MPTAmount* +signed-integer-overflow:operator-*STAmount* + +# STAmount::operator+ signed addition — operands are bounded by total supply +# (~10^17 for XRP, ~10^18 for MPT) so overflow cannot occur in practice. +signed-integer-overflow:operator+*STAmount* + +# STAmount::getRate uses unsigned shift and addition +unsigned-integer-overflow:*STAmount*getRate* +# STAmount::serialize uses unsigned bitwise operations +unsigned-integer-overflow:*STAmount*serialize* + +# nft::cipheredTaxon uses intentional uint32 wraparound (LCG permutation) +unsigned-integer-overflow:cipheredTaxon diff --git a/src/libxrpl/basics/base64.cpp b/src/libxrpl/basics/base64.cpp index cf6af3db70a..f266d931944 100644 --- a/src/libxrpl/basics/base64.cpp +++ b/src/libxrpl/basics/base64.cpp @@ -107,7 +107,7 @@ encode(void* dest, void const* src, std::size_t len) char const* in = static_cast(src); auto const tab = base64::get_alphabet(); - for (auto n = len / 3; n != 0u; --n) + for (auto n = len / 3; n > 0; --n) { *out++ = tab[(in[0] & 0xfc) >> 2]; *out++ = tab[((in[0] & 0x03) << 4) + ((in[1] & 0xf0) >> 4)]; diff --git a/src/test/beast/LexicalCast_test.cpp b/src/test/beast/LexicalCast_test.cpp index 410358111e0..12c2c2a4646 100644 --- a/src/test/beast/LexicalCast_test.cpp +++ b/src/test/beast/LexicalCast_test.cpp @@ -24,7 +24,7 @@ class LexicalCast_test : public unit_test::suite testInteger(IntType in) { std::string s; - IntType out(in + 1); + IntType out = static_cast(~in); // Ensure out != in expect(lexicalCastChecked(s, in)); expect(lexicalCastChecked(out, s)); diff --git a/src/xrpld/app/main/BasicApp.cpp b/src/xrpld/app/main/BasicApp.cpp index 9de7dc53d3a..71138c65172 100644 --- a/src/xrpld/app/main/BasicApp.cpp +++ b/src/xrpld/app/main/BasicApp.cpp @@ -12,10 +12,10 @@ BasicApp::BasicApp(std::size_t numberOfThreads) work_.emplace(boost::asio::make_work_guard(io_context_)); threads_.reserve(numberOfThreads); - while ((numberOfThreads--) != 0u) + for (std::size_t i = 0; i < numberOfThreads; ++i) { - threads_.emplace_back([this, numberOfThreads]() { - beast::setCurrentThreadName("io svc #" + std::to_string(numberOfThreads)); + threads_.emplace_back([this, i]() { + beast::setCurrentThreadName("io svc #" + std::to_string(i)); this->io_context_.run(); }); } diff --git a/src/xrpld/peerfinder/detail/Counts.h b/src/xrpld/peerfinder/detail/Counts.h index 811758b0b32..6d1221d331d 100644 --- a/src/xrpld/peerfinder/detail/Counts.h +++ b/src/xrpld/peerfinder/detail/Counts.h @@ -8,6 +8,9 @@ namespace xrpl::PeerFinder { +/** Direction of a slot count adjustment. */ +enum class CountAdjustment : int { Decrement = -1, Increment = 1 }; + /** Manages the count of available connections for the various slots. */ class Counts { @@ -16,14 +19,14 @@ class Counts void add(Slot const& s) { - adjust(s, 1); + adjust(s, CountAdjustment::Increment); } /** Removes the slot state and properties from the slot counts. */ void remove(Slot const& s) { - adjust(s, -1); + adjust(s, CountAdjustment::Decrement); } /** Returns `true` if the slot can become active. */ @@ -207,21 +210,40 @@ class Counts //-------------------------------------------------------------------------- private: + /** Increments or decrements a counter based on the adjustment direction. */ + template + static void + adjustCounter(T& counter, CountAdjustment dir) + { + switch (dir) + { + case CountAdjustment::Increment: + ++counter; + break; + case CountAdjustment::Decrement: + --counter; + break; + } + } + // Adjusts counts based on the specified slot, in the direction indicated. + // Using ++/-- instead of += on std::size_t counters avoids UBSan + // unsigned-integer-overflow from implicit conversion of -1 to SIZE_MAX. + // A decrement on a zero counter is a real bug that UBSan should catch. void - adjust(Slot const& s, int const n) + adjust(Slot const& s, CountAdjustment const dir) { if (s.fixed()) - m_fixed += n; + adjustCounter(m_fixed, dir); if (s.reserved()) - m_reserved += n; + adjustCounter(m_reserved, dir); switch (s.state()) { case Slot::accept: XRPL_ASSERT(s.inbound(), "xrpl::PeerFinder::Counts::adjust : input is inbound"); - m_acceptCount += n; + adjustCounter(m_acceptCount, dir); break; case Slot::connect: @@ -230,28 +252,28 @@ class Counts !s.inbound(), "xrpl::PeerFinder::Counts::adjust : input is not " "inbound"); - m_attempts += n; + adjustCounter(m_attempts, dir); break; case Slot::active: if (s.fixed()) - m_fixed_active += n; + adjustCounter(m_fixed_active, dir); if (!s.fixed() && !s.reserved()) { if (s.inbound()) { - m_in_active += n; + adjustCounter(m_in_active, dir); } else { - m_out_active += n; + adjustCounter(m_out_active, dir); } } - m_active += n; + adjustCounter(m_active, dir); break; case Slot::closing: - m_closingCount += n; + adjustCounter(m_closingCount, dir); break; // LCOV_EXCL_START From 147da573485e074e9c3e2a925134b8e07f591b3c Mon Sep 17 00:00:00 2001 From: Vito Tumas <5780819+Tapanito@users.noreply.github.com> Date: Tue, 28 Apr 2026 12:22:32 +0200 Subject: [PATCH 12/34] feat: Add cleanup amendment for 3.2.0 (#7037) --- include/xrpl/protocol/detail/features.macro | 1 + 1 file changed, 1 insertion(+) diff --git a/include/xrpl/protocol/detail/features.macro b/include/xrpl/protocol/detail/features.macro index 494b3fa6cdb..bad43dd6ed2 100644 --- a/include/xrpl/protocol/detail/features.macro +++ b/include/xrpl/protocol/detail/features.macro @@ -15,6 +15,7 @@ // Add new amendments to the top of this list. // Keep it sorted in reverse chronological order. +XRPL_FIX (Cleanup3_2_0, Supported::no, VoteBehavior::DefaultNo) XRPL_FEATURE(MPTokensV2, Supported::no, VoteBehavior::DefaultNo) XRPL_FIX (Security3_1_3, Supported::no, VoteBehavior::DefaultNo) XRPL_FIX (PermissionedDomainInvariant, Supported::yes, VoteBehavior::DefaultNo) From 46b997b774b27a1260a8085586c9d33fcdbf9c6e Mon Sep 17 00:00:00 2001 From: Jingchen Date: Tue, 28 Apr 2026 15:16:10 +0100 Subject: [PATCH 13/34] feat: Create new transaction testing framework `TxTest` (#6537) Signed-off-by: JCW Co-authored-by: xrplf-ai-reviewer[bot] <266832837+xrplf-ai-reviewer[bot]@users.noreply.github.com> Co-authored-by: Copilot --- .../scripts/levelization/results/ordering.txt | 6 + .../xrpl/protocol_autogen/LedgerEntryBase.h | 13 + src/tests/libxrpl/CMakeLists.txt | 11 +- src/tests/libxrpl/helpers/Account.cpp | 19 + src/tests/libxrpl/helpers/Account.h | 81 ++ src/tests/libxrpl/helpers/IOU.h | 132 +++ src/tests/libxrpl/helpers/TestFamily.h | 111 +++ .../libxrpl/helpers/TestServiceRegistry.h | 378 ++++++++ src/tests/libxrpl/helpers/TxTest.cpp | 252 ++++++ src/tests/libxrpl/helpers/TxTest.h | 364 ++++++++ src/tests/libxrpl/tx/AccountSet.cpp | 804 ++++++++++++++++++ src/tests/libxrpl/tx/main.cpp | 8 + 12 files changed, 2177 insertions(+), 2 deletions(-) create mode 100644 src/tests/libxrpl/helpers/Account.cpp create mode 100644 src/tests/libxrpl/helpers/Account.h create mode 100644 src/tests/libxrpl/helpers/IOU.h create mode 100644 src/tests/libxrpl/helpers/TestFamily.h create mode 100644 src/tests/libxrpl/helpers/TestServiceRegistry.h create mode 100644 src/tests/libxrpl/helpers/TxTest.cpp create mode 100644 src/tests/libxrpl/helpers/TxTest.h create mode 100644 src/tests/libxrpl/tx/AccountSet.cpp create mode 100644 src/tests/libxrpl/tx/main.cpp diff --git a/.github/scripts/levelization/results/ordering.txt b/.github/scripts/levelization/results/ordering.txt index d2a18945850..c2000d17681 100644 --- a/.github/scripts/levelization/results/ordering.txt +++ b/.github/scripts/levelization/results/ordering.txt @@ -188,10 +188,16 @@ test.toplevel > xrpl.json test.unit_test > xrpl.basics test.unit_test > xrpl.protocol tests.libxrpl > xrpl.basics +tests.libxrpl > xrpl.core tests.libxrpl > xrpl.json +tests.libxrpl > xrpl.ledger tests.libxrpl > xrpl.net +tests.libxrpl > xrpl.nodestore tests.libxrpl > xrpl.protocol tests.libxrpl > xrpl.protocol_autogen +tests.libxrpl > xrpl.server +tests.libxrpl > xrpl.shamap +tests.libxrpl > xrpl.tx xrpl.conditions > xrpl.basics xrpl.conditions > xrpl.protocol xrpl.core > xrpl.basics diff --git a/include/xrpl/protocol_autogen/LedgerEntryBase.h b/include/xrpl/protocol_autogen/LedgerEntryBase.h index 0c5b367391a..ad513992c7d 100644 --- a/include/xrpl/protocol_autogen/LedgerEntryBase.h +++ b/include/xrpl/protocol_autogen/LedgerEntryBase.h @@ -130,6 +130,19 @@ class LedgerEntryBase return sle_->at(sfFlags); } + /** + * @brief Check if a specific flag is set. + * + * @param f The flag bitmask to check + * @return true if all bits in f are set in the flags field + */ + [[nodiscard]] + bool + isFlag(std::uint32_t f) const + { + return sle_->isFlag(f); + } + /** * @brief Get the underlying SLE object. * diff --git a/src/tests/libxrpl/CMakeLists.txt b/src/tests/libxrpl/CMakeLists.txt index 0b666441d18..ee076985194 100644 --- a/src/tests/libxrpl/CMakeLists.txt +++ b/src/tests/libxrpl/CMakeLists.txt @@ -8,9 +8,12 @@ add_custom_target(xrpl.tests) # Test helpers add_library(xrpl.helpers.test STATIC) -target_sources(xrpl.helpers.test PRIVATE helpers/TestSink.cpp) +target_sources( + xrpl.helpers.test + PRIVATE helpers/Account.cpp helpers/TestSink.cpp helpers/TxTest.cpp +) target_include_directories(xrpl.helpers.test PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) -target_link_libraries(xrpl.helpers.test PRIVATE xrpl.libxrpl) +target_link_libraries(xrpl.helpers.test PUBLIC xrpl.libxrpl gtest::gtest) # Common library dependencies for the rest of the tests. add_library(xrpl.imports.test INTERFACE) @@ -32,6 +35,10 @@ xrpl_add_test(json) target_link_libraries(xrpl.test.json PRIVATE xrpl.imports.test) add_dependencies(xrpl.tests xrpl.test.json) +xrpl_add_test(tx) +target_link_libraries(xrpl.test.tx PRIVATE xrpl.imports.test) +add_dependencies(xrpl.tests xrpl.test.tx) + xrpl_add_test(protocol_autogen) target_link_libraries(xrpl.test.protocol_autogen PRIVATE xrpl.imports.test) add_dependencies(xrpl.tests xrpl.test.protocol_autogen) diff --git a/src/tests/libxrpl/helpers/Account.cpp b/src/tests/libxrpl/helpers/Account.cpp new file mode 100644 index 00000000000..736ae0a24b0 --- /dev/null +++ b/src/tests/libxrpl/helpers/Account.cpp @@ -0,0 +1,19 @@ +#include + +#include +#include +#include +#include + +namespace xrpl::test { + +Account const Account::master{"masterpassphrase"}; + +Account::Account(std::string_view name, KeyType type) + : name_(name) + , keyPair_(generateKeyPair(type, generateSeed(name_))) + , id_(calcAccountID(keyPair_.first)) +{ +} + +} // namespace xrpl::test diff --git a/src/tests/libxrpl/helpers/Account.h b/src/tests/libxrpl/helpers/Account.h new file mode 100644 index 00000000000..9c3ad19bbb6 --- /dev/null +++ b/src/tests/libxrpl/helpers/Account.h @@ -0,0 +1,81 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include + +namespace xrpl::test { + +/** + * @brief A test account with cryptographic keys. + * + * Generates keys deterministically from a name, making tests reproducible. + * The same name always produces the same AccountID and keys. + */ +class Account +{ +public: + /** + * @brief The master account that holds all XRP in genesis. + * + * This account is created in the genesis ledger with all 100 billion XRP. + * It uses the well-known seed "masterpassphrase". + */ + static Account const master; + + /** + * @brief Create an account from a name. + * + * Keys are derived deterministically from the name. + * + * @param name Human-readable name for the account. + * @param type Key type to use (defaults to secp256k1). + */ + explicit Account(std::string_view name, KeyType type = KeyType::secp256k1); + + /** @brief Return the human-readable name. */ + std::string const& + name() const noexcept + { + return name_; + } + + /** @brief Return the AccountID. */ + AccountID const& + id() const noexcept + { + return id_; + } + + /** @brief Return the public key. */ + PublicKey const& + pk() const noexcept + { + return keyPair_.first; + } + + /** @brief Return the secret key. */ + SecretKey const& + sk() const noexcept + { + return keyPair_.second; + } + + /** @brief Implicit conversion to AccountID. */ + operator AccountID const&() const noexcept + { + return id_; + } + +private: + std::string name_; + std::pair keyPair_; + AccountID id_; +}; + +} // namespace xrpl::test diff --git a/src/tests/libxrpl/helpers/IOU.h b/src/tests/libxrpl/helpers/IOU.h new file mode 100644 index 00000000000..1e845f5ae67 --- /dev/null +++ b/src/tests/libxrpl/helpers/IOU.h @@ -0,0 +1,132 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +namespace xrpl::test { + +/** + * @brief Represents an IOU (issued currency) for testing. + * + * Provides a clear, explicit API for creating currencies issued by an account. + * This replaces the cryptic `Account::operator[]` from the jtx framework. + * + * @code + * Account gw("gateway"); + * IOU USD("USD", gw); + * + * auto issue = USD.issue(); // Get the Issue + * auto asset = USD.asset(); // Get the Asset + * auto amt = USD.amount(100); // Get STAmount of 100 USD + * @endcode + */ +class IOU +{ +public: + /** + * @brief Construct an IOU from a currency code and issuing account. + * @param currencyCode A 3-character ISO currency code (e.g., "USD"). + * @param issuer The account that issues this currency. + */ + IOU(std::string_view currencyCode, Account const& issuer) + : currency_(to_currency(std::string(currencyCode))), issuer_(issuer.id()) + { + XRPL_ASSERT(!isXRP(currency_), "IOU: currency code must not resolve to XRP"); + } + + /** + * @brief Construct an IOU from a Currency and issuing account. + * @param currency The Currency object. + * @param issuer The account that issues this currency. + */ + IOU(Currency currency, Account const& issuer) + : currency_(std::move(currency)), issuer_(issuer.id()) + { + XRPL_ASSERT(!isXRP(currency_), "IOU: currency code must not resolve to XRP"); + } + + /** + * @brief Get the Issue (currency + issuer pair). + * @return An Issue object representing this IOU. + */ + [[nodiscard]] Issue + issue() const + { + return Issue{currency_, issuer_}; + } + + /** + * @brief Get the Asset. + * @return An Asset object representing this IOU. + */ + [[nodiscard]] Asset + asset() const + { + return Asset{issue()}; + } + + /** + * @brief Create an STAmount of this IOU. + * + * Works with any arithmetic type (int, double, etc.) by converting + * to string and parsing. This matches the jtx IOU behaviour. + * + * @tparam T An arithmetic type. + * @param value The amount as any arithmetic type. + * @return An STAmount representing value units of this IOU. + */ + template + requires std::is_arithmetic_v + [[nodiscard]] STAmount + amount(T value) const + { + return amountFromString(issue(), to_string(value)); + } + + /** + * @brief Create an STAmount of this IOU from a Number. + * @param value The amount as a Number. + * @return An STAmount representing value units of this IOU. + */ + [[nodiscard]] STAmount + amount(Number const& value) const + { + return STAmount{issue(), value}; + } + + /** + * @brief Get the currency. + * @return The currency. + */ + [[nodiscard]] Currency const& + currency() const + { + return currency_; + } + + /** + * @brief Get the issuer account ID. + * @return The issuer's AccountID. + */ + [[nodiscard]] AccountID const& + issuer() const + { + return issuer_; + } + +private: + Currency currency_; + AccountID issuer_; +}; + +} // namespace xrpl::test diff --git a/src/tests/libxrpl/helpers/TestFamily.h b/src/tests/libxrpl/helpers/TestFamily.h new file mode 100644 index 00000000000..98c5a379e47 --- /dev/null +++ b/src/tests/libxrpl/helpers/TestFamily.h @@ -0,0 +1,111 @@ +#pragma once + +#include +#include +#include +#include + +#include + +namespace xrpl { +namespace test { + +/** Test implementation of Family for unit tests. + + Uses an in-memory NodeStore database and simple caches. + The missingNode methods throw since tests shouldn't encounter missing nodes. +*/ +class TestFamily : public Family +{ +private: + std::unique_ptr db_; + TestStopwatch clock_; + std::shared_ptr fbCache_; + std::shared_ptr tnCache_; + NodeStore::DummyScheduler scheduler_; + beast::Journal j_; + +public: + explicit TestFamily(beast::Journal j) + : fbCache_(std::make_shared("TestFamily full below cache", clock_, j)) + , tnCache_( + std::make_shared( + "TestFamily tree node cache", + 65536, + std::chrono::minutes{1}, + clock_, + j)) + , j_(j) + { + Section config; + config.set("type", "memory"); + config.set("path", "TestFamily"); + db_ = NodeStore::Manager::instance().make_Database(megabytes(4), scheduler_, 1, config, j); + } + + NodeStore::Database& + db() override + { + return *db_; + } + + NodeStore::Database const& + db() const override + { + return *db_; + } + + beast::Journal const& + journal() override + { + return j_; + } + + std::shared_ptr + getFullBelowCache() override + { + return fbCache_; + } + + std::shared_ptr + getTreeNodeCache() override + { + return tnCache_; + } + + void + sweep() override + { + fbCache_->sweep(); + tnCache_->sweep(); + } + + void + missingNodeAcquireBySeq(std::uint32_t refNum, uint256 const& nodeHash) override + { + Throw("TestFamily: missing node (by seq)"); + } + + void + missingNodeAcquireByHash(uint256 const& refHash, std::uint32_t refNum) override + { + Throw("TestFamily: missing node (by hash)"); + } + + void + reset() override + { + fbCache_->reset(); + tnCache_->reset(); + } + + /** Access the test clock for time manipulation in tests. */ + TestStopwatch& + clock() + { + return clock_; + } +}; + +} // namespace test +} // namespace xrpl diff --git a/src/tests/libxrpl/helpers/TestServiceRegistry.h b/src/tests/libxrpl/helpers/TestServiceRegistry.h new file mode 100644 index 00000000000..4f39124087a --- /dev/null +++ b/src/tests/libxrpl/helpers/TestServiceRegistry.h @@ -0,0 +1,378 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +#include +#include + +namespace xrpl { +namespace test { + +/** Logs implementation that creates TestSink instances. */ +class TestLogs : public Logs +{ +public: + explicit TestLogs(beast::severities::Severity level = beast::severities::kWarning) : Logs(level) + { + } + + std::unique_ptr + makeSink(std::string const&, beast::severities::Severity threshold) override + { + return std::make_unique(threshold); + } +}; + +/** Simple NetworkIDService implementation for tests. */ +class TestNetworkIDService final : public NetworkIDService +{ +public: + explicit TestNetworkIDService(std::uint32_t networkID = 0) : networkID_(networkID) + { + } + + [[nodiscard]] std::uint32_t + getNetworkID() const noexcept override + { + return networkID_; + } + +private: + std::uint32_t networkID_; +}; + +/** Test implementation of ServiceRegistry for unit tests. + + This class provides real implementations for services that can be + instantiated from libxrpl (such as Logs, io_context, caches), and + throws std::logic_error for services that require the full Application. + + Tests can subclass this to provide additional services they need. +*/ +class TestServiceRegistry : public ServiceRegistry +{ + TestLogs logs_{beast::severities::kWarning}; + boost::asio::io_context io_context_; + TestFamily family_{logs_.journal("TestFamily")}; + LoadFeeTrack feeTrack_{logs_.journal("LoadFeeTrack")}; + TestNetworkIDService networkIDService_; + HashRouter hashRouter_{HashRouter::Setup{}, stopwatch()}; + NodeCache tempNodeCache_{ + "TempNodeCache", + 16384, + std::chrono::minutes{1}, + stopwatch(), + logs_.journal("TaggedCache")}; + CachedSLEs cachedSLEs_{ + "CachedSLEs", + 16384, + std::chrono::minutes{1}, + stopwatch(), + logs_.journal("TaggedCache")}; + PendingSaves pendingSaves_; + std::optional trapTxID_; + +public: + TestServiceRegistry() = default; + ~TestServiceRegistry() override = default; + + // Core infrastructure services + CollectorManager& + getCollectorManager() override + { + throw std::logic_error("TestServiceRegistry::getCollectorManager() not implemented"); + } + + Family& + getNodeFamily() override + { + return family_; + } + + TimeKeeper& + getTimeKeeper() override + { + throw std::logic_error("TestServiceRegistry::timeKeeper() not implemented"); + } + + JobQueue& + getJobQueue() override + { + throw std::logic_error("TestServiceRegistry::getJobQueue() not implemented"); + } + + NodeCache& + getTempNodeCache() override + { + return tempNodeCache_; + } + + CachedSLEs& + getCachedSLEs() override + { + return cachedSLEs_; + } + + NetworkIDService& + getNetworkIDService() override + { + return networkIDService_; + } + + // Protocol and validation services + AmendmentTable& + getAmendmentTable() override + { + throw std::logic_error("TestServiceRegistry::getAmendmentTable() not implemented"); + } + + HashRouter& + getHashRouter() override + { + return hashRouter_; + } + + LoadFeeTrack& + getFeeTrack() override + { + return feeTrack_; + } + + LoadManager& + getLoadManager() override + { + throw std::logic_error("TestServiceRegistry::getLoadManager() not implemented"); + } + + RCLValidations& + getValidations() override + { + throw std::logic_error("TestServiceRegistry::getValidations() not implemented"); + } + + ValidatorList& + getValidators() override + { + throw std::logic_error("TestServiceRegistry::validators() not implemented"); + } + + ValidatorSite& + getValidatorSites() override + { + throw std::logic_error("TestServiceRegistry::validatorSites() not implemented"); + } + + ManifestCache& + getValidatorManifests() override + { + throw std::logic_error("TestServiceRegistry::validatorManifests() not implemented"); + } + + ManifestCache& + getPublisherManifests() override + { + throw std::logic_error("TestServiceRegistry::publisherManifests() not implemented"); + } + + // Network services + Overlay& + getOverlay() override + { + throw std::logic_error("TestServiceRegistry::overlay() not implemented"); + } + + Cluster& + getCluster() override + { + throw std::logic_error("TestServiceRegistry::cluster() not implemented"); + } + + PeerReservationTable& + getPeerReservations() override + { + throw std::logic_error("TestServiceRegistry::peerReservations() not implemented"); + } + + Resource::Manager& + getResourceManager() override + { + throw std::logic_error("TestServiceRegistry::getResourceManager() not implemented"); + } + + // Storage services + NodeStore::Database& + getNodeStore() override + { + throw std::logic_error("TestServiceRegistry::getNodeStore() not implemented"); + } + + SHAMapStore& + getSHAMapStore() override + { + throw std::logic_error("TestServiceRegistry::getSHAMapStore() not implemented"); + } + + RelationalDatabase& + getRelationalDatabase() override + { + throw std::logic_error("TestServiceRegistry::getRelationalDatabase() not implemented"); + } + + // Ledger services + InboundLedgers& + getInboundLedgers() override + { + throw std::logic_error("TestServiceRegistry::getInboundLedgers() not implemented"); + } + + InboundTransactions& + getInboundTransactions() override + { + throw std::logic_error("TestServiceRegistry::getInboundTransactions() not implemented"); + } + + TaggedCache& + getAcceptedLedgerCache() override + { + throw std::logic_error("TestServiceRegistry::getAcceptedLedgerCache() not implemented"); + } + + LedgerMaster& + getLedgerMaster() override + { + throw std::logic_error("TestServiceRegistry::getLedgerMaster() not implemented"); + } + + LedgerCleaner& + getLedgerCleaner() override + { + throw std::logic_error("TestServiceRegistry::getLedgerCleaner() not implemented"); + } + + LedgerReplayer& + getLedgerReplayer() override + { + throw std::logic_error("TestServiceRegistry::getLedgerReplayer() not implemented"); + } + + PendingSaves& + getPendingSaves() override + { + return pendingSaves_; + } + + OpenLedger& + getOpenLedger() override + { + throw std::logic_error("TestServiceRegistry::openLedger() not implemented"); + } + + OpenLedger const& + getOpenLedger() const override + { + throw std::logic_error("TestServiceRegistry::openLedger() const not implemented"); + } + + // Transaction and operation services + NetworkOPs& + getOPs() override + { + throw std::logic_error("TestServiceRegistry::getOPs() not implemented"); + } + + OrderBookDB& + getOrderBookDB() override + { + throw std::logic_error("TestServiceRegistry::getOrderBookDB() not implemented"); + } + + TransactionMaster& + getMasterTransaction() override + { + throw std::logic_error("TestServiceRegistry::getMasterTransaction() not implemented"); + } + + TxQ& + getTxQ() override + { + throw std::logic_error("TestServiceRegistry::getTxQ() not implemented"); + } + + PathRequestManager& + getPathRequestManager() override + { + throw std::logic_error("TestServiceRegistry::getPathRequestManager() not implemented"); + } + + // Server services + ServerHandler& + getServerHandler() override + { + throw std::logic_error("TestServiceRegistry::getServerHandler() not implemented"); + } + + perf::PerfLog& + getPerfLog() override + { + throw std::logic_error("TestServiceRegistry::getPerfLog() not implemented"); + } + + // Configuration and state + bool + isStopping() const override + { + return false; + } + + beast::Journal + getJournal(std::string const& name) override + { + return logs_.journal(name); + } + + boost::asio::io_context& + getIOContext() override + { + return io_context_; + } + + Logs& + getLogs() override + { + return logs_; + } + + std::optional const& + getTrapTxID() const override + { + return trapTxID_; + } + + DatabaseCon& + getWalletDB() override + { + throw std::logic_error("TestServiceRegistry::getWalletDB() not implemented"); + } + + // Temporary: Get the underlying Application + Application& + getApp() override + { + throw std::logic_error( + "TestServiceRegistry::app() not implemented - no Application available in tests"); + } +}; + +} // namespace test +} // namespace xrpl diff --git a/src/tests/libxrpl/helpers/TxTest.cpp b/src/tests/libxrpl/helpers/TxTest.cpp new file mode 100644 index 00000000000..d88f7003568 --- /dev/null +++ b/src/tests/libxrpl/helpers/TxTest.cpp @@ -0,0 +1,252 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace xrpl::test { + +//------------------------------------------------------------------------------ +// Feature helpers +//------------------------------------------------------------------------------ + +FeatureBitset +allFeatures() +{ + static FeatureBitset const features = [] { + auto const& sa = allAmendments(); + std::vector feats; + feats.reserve(sa.size()); + for ([[maybe_unused]] auto const& [name, _] : sa) + { + if (auto const f = getRegisteredFeature(name); f.has_value()) + feats.push_back(*f); + } + return FeatureBitset(feats); + }(); + return features; +} + +//------------------------------------------------------------------------------ +// TxTest +//------------------------------------------------------------------------------ + +TxTest::TxTest(std::optional features) +{ + // Convert FeatureBitset to unordered_set for Rules constructor + auto const featureBits = features.value_or(allFeatures()); + foreachFeature(featureBits, [&](uint256 const& f) { featureSet_.insert(f); }); + + // Create rules with the specified features + rules_.emplace(featureSet_); + + // Default fees for testing + Fees const fees{XRPAmount{10}, XRPAmount{10000000}, XRPAmount{2000000}}; + + // Create a genesis ledger as the base + closedLedger_ = std::make_shared( + create_genesis, + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + *rules_, + fees, + std::vector{featureSet_.begin(), featureSet_.end()}, + registry_.getNodeFamily()); + + // Initialize time from the genesis ledger + now_ = closedLedger_->header().closeTime; + + // Create an open view on top of the genesis ledger + openLedger_ = + std::make_shared(open_ledger, closedLedger_.get(), *rules_, closedLedger_); +} + +bool +TxTest::isEnabled(uint256 const& feature) const +{ + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + return rules_->enabled(feature); +} + +Rules const& +TxTest::getRules() const +{ + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + return *rules_; +} + +[[nodiscard]] TxResult +TxTest::submit(std::shared_ptr stx) +{ + auto result = apply(registry_, *openLedger_, *stx, tapNONE, registry_.getJournal("apply")); + + // Track successfully applied transactions for canonical reordering on close + // We make a copy since the TransactionBase doesn't own the STTx + if (result.applied) + pendingTxs_.push_back(stx); + + return TxResult{ + .ter = result.ter, + .applied = result.applied, + .metadata = std::move(result).metadata, + .tx = std::move(stx)}; +} + +void +TxTest::createAccount(Account const& account, XRPAmount xrp, uint32_t accountFlags) +{ + auto const paymentTer = + submit(transactions::PaymentBuilder{Account::master, account, xrp}, Account::master).ter; + + if (paymentTer != tesSUCCESS) + { + throw std::runtime_error("TxTest::createAccount: failed to create account"); + } + + close(); + + if (accountFlags != 0) + { + auto const accountSetTer = + submit(transactions::AccountSetBuilder{account}.setSetFlag(accountFlags), account).ter; + if (accountSetTer != tesSUCCESS) + { + throw std::runtime_error("TxTest::createAccount: failed to set account flags"); + } + close(); + } +} + +ledger_entries::AccountRoot +TxTest::getAccountRoot(AccountID const& id) const +{ + auto const sle = getOpenLedger().read(keylet::account(id)); + if (!sle) + Throw("TxTest::getAccountRoot: account not found"); + return ledger_entries::AccountRoot{std::const_pointer_cast(sle)}; +} + +OpenView& +TxTest::getOpenLedger() +{ + return *openLedger_; +} + +OpenView const& +TxTest::getOpenLedger() const +{ + return *openLedger_; +} + +ReadView const& +TxTest::getClosedLedger() const +{ + return *closedLedger_; +} + +void +TxTest::close() +{ + // Build a new closed ledger from the previous closed ledger, + // similar to how buildLedgerImpl works: + // 1. Create a new Ledger from the previous closed ledger + // 2. Re-apply transactions in canonical order + // 3. Mark it as accepted/immutable + + auto const& prevLedger = *closedLedger_; + + auto const ledgerCloseTime = now_ + prevLedger.header().closeTimeResolution; + + now_ = ledgerCloseTime; + + auto newLedger = std::make_shared(prevLedger, ledgerCloseTime); + + CanonicalTXSet txSet(prevLedger.header().hash); + for (auto const& tx : pendingTxs_) + txSet.insert(tx); + + { + OpenView accum(&*newLedger); + for (auto const& [key, tx] : txSet) + { + auto result = apply(registry_, accum, *tx, tapNONE, registry_.getJournal("apply")); + if (!result.applied) + { + throw std::runtime_error("TxTest::close: failed to apply transaction"); + } + } + accum.apply(*newLedger); + } + + newLedger->setAccepted(ledgerCloseTime, newLedger->header().closeTimeResolution, true); + + closedLedger_ = newLedger; + + pendingTxs_.clear(); + + openLedger_ = + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + std::make_shared(open_ledger, closedLedger_.get(), *rules_, closedLedger_); +} + +void +TxTest::advanceTime(NetClock::duration duration) +{ + now_ += duration; +} + +NetClock::time_point +TxTest::getCloseTime() const +{ + return now_; +} + +STAmount +TxTest::getBalance(AccountID const& account, IOU const& iou) const +{ + auto const sle = openLedger_->read(keylet::line(account, iou.issue())); + if (!sle) + return STAmount{iou.issue(), 0}; + + auto const rippleState = ledger_entries::RippleState{sle}; + + auto balance = rippleState.getBalance(); + if (iou.issue().account == account) + { + throw std::logic_error("TxTest::getBalance: account is issuer"); + } + + balance.get().account = iou.issue().account; + if (account > iou.issue().account) + balance.negate(); + return balance; +} + +} // namespace xrpl::test diff --git a/src/tests/libxrpl/helpers/TxTest.h b/src/tests/libxrpl/helpers/TxTest.h new file mode 100644 index 00000000000..864b19c3990 --- /dev/null +++ b/src/tests/libxrpl/helpers/TxTest.h @@ -0,0 +1,364 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace xrpl::test { + +//------------------------------------------------------------------------------ +// Amount helpers +//------------------------------------------------------------------------------ + +/** + * @brief Convert XRP to drops (integral types). + * @param xrp The amount in XRP. + * @return The equivalent amount in drops as XRPAmount. + */ +template +constexpr XRPAmount +XRP(T xrp) +{ + return XRPAmount{static_cast(xrp) * DROPS_PER_XRP.drops()}; +} + +/** + * @brief Convert XRP to drops (floating point types). + * @param xrp The amount in XRP (may be fractional). + * @return The equivalent amount in drops as XRPAmount. + */ +template +XRPAmount +XRP(T xrp) +{ + return XRPAmount{static_cast(std::round(xrp * DROPS_PER_XRP.drops()))}; +} + +/** + * @brief Convert XRP to drops (Number type). + * @param xrp The amount in XRP as a Number. + * @return The equivalent amount in drops as XRPAmount. + */ +inline XRPAmount +XRP(Number const& xrp) +{ + return XRPAmount{static_cast(xrp * DROPS_PER_XRP.drops())}; +} + +//------------------------------------------------------------------------------ +// Flag helpers +//------------------------------------------------------------------------------ + +/** + * @brief Convert AccountSet flag (asf) to LedgerState flag (lsf). + * @param asf The AccountSet flag value. + * @return The corresponding LedgerState flag. + * @throws std::runtime_error if the flag is not supported. + * + * Supported flags: + * asfRequireDest, asfRequireAuth, asfDisallowXRP, asfDisableMaster, + * asfNoFreeze, asfGlobalFreeze, asfDefaultRipple, asfDepositAuth, + * asfAllowTrustLineClawback, asfDisallowIncomingCheck, + * asfDisallowIncomingNFTokenOffer, asfDisallowIncomingPayChan, + * asfDisallowIncomingTrustline, asfAllowTrustLineLocking + */ +constexpr std::uint32_t +asfToLsf(std::uint32_t asf) +{ + switch (asf) + { + case asfRequireDest: + return lsfRequireDestTag; + case asfRequireAuth: + return lsfRequireAuth; + case asfDisallowXRP: + return lsfDisallowXRP; + case asfDisableMaster: + return lsfDisableMaster; + case asfNoFreeze: + return lsfNoFreeze; + case asfGlobalFreeze: + return lsfGlobalFreeze; + case asfDefaultRipple: + return lsfDefaultRipple; + case asfDepositAuth: + return lsfDepositAuth; + case asfAllowTrustLineClawback: + return lsfAllowTrustLineClawback; + case asfDisallowIncomingCheck: + return lsfDisallowIncomingCheck; + case asfDisallowIncomingNFTokenOffer: + return lsfDisallowIncomingNFTokenOffer; + case asfDisallowIncomingPayChan: + return lsfDisallowIncomingPayChan; + case asfDisallowIncomingTrustline: + return lsfDisallowIncomingTrustline; + case asfAllowTrustLineLocking: + return lsfAllowTrustLineLocking; + default: + throw std::runtime_error("Unknown asf flag"); + } +} + +//------------------------------------------------------------------------------ +// Feature helpers +//------------------------------------------------------------------------------ + +/** + * @brief Returns all testable amendments. + * @note This is similar to jtx::testable_amendments() but for the TxTest framework. + */ +FeatureBitset +allFeatures(); + +//------------------------------------------------------------------------------ +// TxResult +//------------------------------------------------------------------------------ + +/** + * @brief Result of a transaction submission in TxTest. + * + * Contains the TER code, whether the transaction was applied, + * optional metadata, and a reference to the submitted transaction. + * Use standard gtest macros (EXPECT_EQ, EXPECT_TRUE, etc.) to verify results. + */ +struct TxResult +{ + TER ter; /**< The transaction engine result code. */ + bool applied; /**< Whether the transaction was applied to the ledger. */ + std::optional metadata; /**< Transaction metadata, if available. */ + std::shared_ptr tx; /**< Pointer to the submitted transaction. */ +}; + +/** + * @brief A lightweight transaction testing harness. + * + * Unlike the JTx framework which requires a full Application and RPC layer, + * TxTest applies transactions directly to an OpenView using the transactor + * pipeline (preflight -> preclaim -> doApply). + * + * This makes it suitable for: + * - Unit testing individual transactors + * - Testing transaction validation logic + * - Fast, focused tests without full server infrastructure + * + * @code + * TxTest env; + * env.submit(paymentTx).expectSuccess(); + * env.submit(badTx).expectTer(tecNO_ENTRY); + * @endcode + */ +class TxTest +{ +public: + /** + * @brief Construct a TxTest environment. + * + * Creates a genesis ledger and an open view on top of it. + * + * @param features Optional set of features to enable. If not specified, + * uses all testable amendments. + */ + explicit TxTest(std::optional features = std::nullopt); + + /** + * @brief Check if a feature is enabled. + * @param feature The feature to check. + * @return True if the feature is enabled. + */ + [[nodiscard]] bool + isEnabled(uint256 const& feature) const; + + /** + * @brief Get the current rules. + * @return The current consensus rules. + */ + [[nodiscard]] Rules const& + getRules() const; + + /** + * @brief Submit a transaction from a builder. + * + * Convenience overload that accepts transaction builders. + * Automatically sets sequence and fee before submission. + * + * @tparam T A type derived from TransactionBuilderBase. + * @param builder The transaction builder. + * @param signer The account to sign with. + * @return TxResult containing the result code, applied status, and metadata. + */ + template + requires std:: + derived_from, transactions::TransactionBuilderBase>> + [[nodiscard]] TxResult + submit(T&& builder, Account const& signer) + { + auto const& obj = builder.getSTObject(); + auto accountId = obj[sfAccount]; + // Only set sequence if not using a ticket (ticket sets sequence to 0) + if (!obj.isFieldPresent(sfTicketSequence)) + { + builder.setSequence(getAccountRoot(accountId).getSequence()); + } + else + { + builder.setSequence(0); + } + builder.setFee(XRPAmount(10)); + return submit(builder.build(signer.pk(), signer.sk()).getSTTx()); + } + + /** + * @brief Submit a transaction to the open ledger. + * + * Applies the transaction through the full transactor pipeline: + * preflight -> preclaim -> doApply -> invariant checks + * + * Invariant checks are automatically run after doApply. If any + * invariant fails, the result will be tecINVARIANT_FAILED. + * + * @param stx The transaction to submit. + * @return TxResult containing the result code, applied status, and metadata. + */ + [[nodiscard]] TxResult + submit(std::shared_ptr stx); + + /** + * @brief Create a new account in the ledger. + * + * Sends a Payment from the master account to create and fund the account. + * Closes the ledger after creation. If accountFlags is non-zero, submits + * an AccountSet transaction and closes again. + * + * @param account The account to create. + * @param xrp The initial XRP balance. + * @param accountFlags Optional account flags to set. Defaults to 0 + * (no flags). + */ + void + createAccount(Account const& account, XRPAmount xrp, uint32_t accountFlags = 0); + + /** + * @brief Get the account root object from the current open ledger. + * @param id The account ID. + * @return The AccountRoot ledger entry. + * @throws std::runtime_error if the account does not exist. + * @todo Once we make keylet strongly typed, we can ditch this method. + */ + [[nodiscard]] ledger_entries::AccountRoot + getAccountRoot(AccountID const& id) const; + + /** + * @brief Get the current open ledger view. + * @return A mutable reference to the open ledger. + */ + [[nodiscard]] OpenView& + getOpenLedger(); + + /** + * @brief Get the current open ledger view (const). + * @return A const reference to the open ledger. + */ + [[nodiscard]] OpenView const& + getOpenLedger() const; + + /** + * @brief Get the closed (base) ledger view. + * @return A const reference to the closed ledger. + */ + [[nodiscard]] ReadView const& + getClosedLedger() const; + + /** + * @brief Close the current ledger. + * + * Creates a new closed ledger from the current open ledger. + * All pending transactions are re-applied in canonical order. + */ + void + close(); + + /** + * @brief Advance time without closing the ledger. + * + * Useful for testing time-dependent features like escrow release + * times or offer expirations. + * + * @param duration The amount of time to advance. + */ + void + advanceTime(NetClock::duration duration); + + /** + * @brief Get the current ledger close time. + * @return The current close time. + */ + [[nodiscard]] NetClock::time_point + getCloseTime() const; + + /** + * @brief Get the balance of an IOU for an account. + * + * Returns the balance from the perspective of the specified account. + * If the trust line doesn't exist, returns zero. + * + * @param account The account to check. + * @param iou The IOU to check the balance for. + * @return The balance as an STAmount. + * @todo Once we make keylet strongly typed, we can ditch this method. + */ + [[nodiscard]] STAmount + getBalance(AccountID const& account, IOU const& iou) const; + + /** + * @brief Get the service registry. + * @return A reference to the service registry. + */ + ServiceRegistry& + getServiceRegistry() + { + return registry_; + } + +private: + TestServiceRegistry registry_; + std::unordered_set> featureSet_; + std::optional rules_; + std::shared_ptr closedLedger_; + std::shared_ptr openLedger_; + + /** Transactions submitted to the open ledger, for canonical reordering on close. */ + std::vector> pendingTxs_; + + /** Current time (can be advanced arbitrarily for testing). */ + NetClock::time_point now_; +}; + +} // namespace xrpl::test diff --git a/src/tests/libxrpl/tx/AccountSet.cpp b/src/tests/libxrpl/tx/AccountSet.cpp new file mode 100644 index 00000000000..3dbe7a49034 --- /dev/null +++ b/src/tests/libxrpl/tx/AccountSet.cpp @@ -0,0 +1,804 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace xrpl::test { + +TEST(AccountSet, NullAccountSet) +{ + TxTest env; + + Account const alice("alice"); + env.createAccount(alice, XRP(10)); + + auto& view = env.getOpenLedger(); + + // ask for the ledger entry - account root, to check its flags + auto sle = view.read(keylet::account(alice)); + + EXPECT_NE(sle, nullptr); + ledger_entries::AccountRoot const accountRoot(sle); + EXPECT_EQ(accountRoot.getFlags(), 0); +} + +TEST(AccountSet, MostFlags) +{ + Account const alice("alice"); + + TxTest env; + env.createAccount(alice, XRP(10000)); + + // Give alice a regular key so she can legally set and clear + // her asfDisableMaster flag. + Account const aliceRegularKey{"aliceRegularKey", KeyType::secp256k1}; + + env.createAccount(aliceRegularKey, XRP(10000)); + env.close(); + + EXPECT_EQ( + env.submit(transactions::SetRegularKeyBuilder{alice}.setRegularKey(aliceRegularKey), alice) + .ter, + tesSUCCESS); + env.close(); + + auto testFlags = [&alice, &aliceRegularKey, &env]( + std::initializer_list goodFlags) { + std::uint32_t const orig_flags = env.getAccountRoot(alice).getFlags(); + for (std::uint32_t flag{1u}; flag < std::numeric_limits::digits; ++flag) + { + if (flag == asfNoFreeze) + { + // The asfNoFreeze flag can't be cleared. It is tested + // elsewhere. + continue; + } + if (flag == asfAuthorizedNFTokenMinter) + { + // The asfAuthorizedNFTokenMinter flag requires the + // presence or absence of the sfNFTokenMinter field in + // the transaction. It is tested elsewhere. + continue; + } + + if (flag == asfDisallowIncomingCheck || flag == asfDisallowIncomingPayChan || + flag == asfDisallowIncomingNFTokenOffer || flag == asfDisallowIncomingTrustline) + { + // These flags are part of the DisallowIncoming amendment + // and are tested elsewhere + continue; + } + if (flag == asfAllowTrustLineClawback) + { + // The asfAllowTrustLineClawback flag can't be cleared. It + // is tested elsewhere. + continue; + } + if (flag == asfAllowTrustLineLocking) + { + // These flags are part of the AllowTokenLocking amendment + // and are tested elsewhere + continue; + } + if (std::ranges::find(goodFlags, flag) != goodFlags.end()) + { + // Good flag + EXPECT_FALSE(env.getAccountRoot(alice).isFlag(asfToLsf(flag))); + + EXPECT_EQ( + env.submit(transactions::AccountSetBuilder{alice}.setSetFlag(flag), alice).ter, + tesSUCCESS); + env.close(); + + EXPECT_TRUE(env.getAccountRoot(alice).isFlag(asfToLsf(flag))); + + EXPECT_EQ( + env.submit( + transactions::AccountSetBuilder{alice}.setClearFlag(flag), + aliceRegularKey) + .ter, + tesSUCCESS); + env.close(); + + EXPECT_FALSE(env.getAccountRoot(alice).isFlag(asfToLsf(flag))); + + std::uint32_t const now_flags = env.getAccountRoot(alice).getFlags(); + EXPECT_EQ(now_flags, orig_flags); + } + else + { + // Bad flag + EXPECT_EQ(env.getAccountRoot(alice).getFlags(), orig_flags); + EXPECT_EQ( + env.submit(transactions::AccountSetBuilder{alice}.setSetFlag(flag), alice).ter, + tesSUCCESS); + env.close(); + EXPECT_EQ(env.getAccountRoot(alice).getFlags(), orig_flags); + + EXPECT_EQ( + env.submit( + transactions::AccountSetBuilder{alice}.setClearFlag(flag), + aliceRegularKey) + .ter, + tesSUCCESS); + env.close(); + EXPECT_EQ(env.getAccountRoot(alice).getFlags(), orig_flags); + } + } + }; + testFlags({ + asfRequireDest, + asfRequireAuth, + asfDisallowXRP, + asfGlobalFreeze, + asfDisableMaster, + asfDefaultRipple, + asfDepositAuth, + }); +} + +TEST(AccountSet, SetAndResetAccountTxnID) +{ + TxTest env; + Account const alice("alice"); + + env.createAccount(alice, XRP(10000)); + + std::uint32_t const orig_flags = env.getAccountRoot(alice).getFlags(); + + // asfAccountTxnID is special and not actually set as a flag, + // so we check the field presence instead + EXPECT_FALSE(env.getAccountRoot(alice).hasAccountTxnID()); + + EXPECT_EQ( + env.submit(transactions::AccountSetBuilder{alice}.setSetFlag(asfAccountTxnID), alice).ter, + tesSUCCESS); + env.close(); + + EXPECT_TRUE(env.getAccountRoot(alice).hasAccountTxnID()); + + EXPECT_EQ( + env.submit(transactions::AccountSetBuilder{alice}.setClearFlag(asfAccountTxnID), alice).ter, + tesSUCCESS); + env.close(); + + EXPECT_FALSE(env.getAccountRoot(alice).hasAccountTxnID()); + + std::uint32_t const now_flags = env.getAccountRoot(alice).getFlags(); + EXPECT_EQ(now_flags, orig_flags); +} + +TEST(AccountSet, SetNoFreeze) +{ + TxTest env; + Account const alice("alice"); + Account const eric("eric"); + + env.createAccount(alice, XRP(10000)); + env.close(); + + // Set eric as alice's regular key (eric doesn't need to be funded) + EXPECT_EQ( + env.submit(transactions::SetRegularKeyBuilder{alice}.setRegularKey(eric), alice).ter, + tesSUCCESS); + env.close(); + + // Verify alice doesn't have NoFreeze flag + EXPECT_FALSE(env.getAccountRoot(alice).isFlag(lsfNoFreeze)); + + // Setting NoFreeze with regular key should fail - requires master key + EXPECT_EQ( + env.submit(transactions::AccountSetBuilder{alice}.setSetFlag(asfNoFreeze), eric).ter, + tecNEED_MASTER_KEY); + env.close(); + + // Setting NoFreeze with master key should succeed + EXPECT_EQ( + env.submit(transactions::AccountSetBuilder{alice}.setSetFlag(asfNoFreeze), alice).ter, + tesSUCCESS); + env.close(); + + // Verify alice now has NoFreeze flag + EXPECT_TRUE(env.getAccountRoot(alice).isFlag(lsfNoFreeze)); + + // Try to clear NoFreeze - transaction succeeds but flag remains set + EXPECT_EQ( + env.submit(transactions::AccountSetBuilder{alice}.setClearFlag(asfNoFreeze), alice).ter, + tesSUCCESS); + env.close(); + + // Verify flag is still set (NoFreeze cannot be cleared once set) + EXPECT_TRUE(env.getAccountRoot(alice).isFlag(lsfNoFreeze)); +} + +TEST(AccountSet, Domain) +{ + TxTest env; + Account const alice("alice"); + + env.createAccount(alice, XRP(10000)); + env.close(); + + // The Domain field is represented as the hex string of the lowercase + // ASCII of the domain. For example, the domain example.com would be + // represented as "6578616d706c652e636f6d". + // + // To remove the Domain field from an account, send an AccountSet with + // the Domain set to an empty string. + std::string const domain = "example.com"; + + // Set domain + EXPECT_EQ( + env.submit(transactions::AccountSetBuilder{alice}.setDomain(makeSlice(domain)), alice).ter, + tesSUCCESS); + env.close(); + + EXPECT_TRUE(env.getAccountRoot(alice).hasDomain()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + EXPECT_EQ(*env.getAccountRoot(alice).getDomain(), makeSlice(domain)); + + // Clear domain by setting empty + EXPECT_EQ( + env.submit(transactions::AccountSetBuilder{alice}.setDomain(Slice{}), alice).ter, + tesSUCCESS); + env.close(); + + EXPECT_FALSE(env.getAccountRoot(alice).hasDomain()); + + // The upper limit on the length is 256 bytes + // (defined as DOMAIN_BYTES_MAX in SetAccount) + // test the edge cases: 255, 256, 257. + std::size_t const maxLength = 256; + for (std::size_t len = maxLength - 1; len <= maxLength + 1; ++len) + { + std::string const domain2 = std::string(len - domain.length() - 1, 'a') + "." + domain; + + EXPECT_EQ(domain2.length(), len); + + if (len <= maxLength) + { + EXPECT_EQ( + env.submit( + transactions::AccountSetBuilder{alice}.setDomain(makeSlice(domain2)), alice) + .ter, + tesSUCCESS); + env.close(); + + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + EXPECT_EQ(*env.getAccountRoot(alice).getDomain(), makeSlice(domain2)); + } + else + { + EXPECT_EQ( + env.submit( + transactions::AccountSetBuilder{alice}.setDomain(makeSlice(domain2)), alice) + .ter, + telBAD_DOMAIN); + env.close(); + } + } +} + +TEST(AccountSet, MessageKey) +{ + TxTest env; + Account const alice("alice"); + + env.createAccount(alice, XRP(10000)); + env.close(); + + // Generate a random ed25519 key pair for the message key + auto const rkp = randomKeyPair(KeyType::ed25519); + + // Set the message key + EXPECT_EQ( + env.submit(transactions::AccountSetBuilder{alice}.setMessageKey(rkp.first.slice()), alice) + .ter, + tesSUCCESS); + env.close(); + + EXPECT_TRUE(env.getAccountRoot(alice).hasMessageKey()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + EXPECT_EQ(*env.getAccountRoot(alice).getMessageKey(), rkp.first.slice()); + + // Clear the message key by setting to empty + EXPECT_EQ( + env.submit(transactions::AccountSetBuilder{alice}.setMessageKey(Slice{}), alice).ter, + tesSUCCESS); + env.close(); + + EXPECT_FALSE(env.getAccountRoot(alice).hasMessageKey()); + + // Try to set an invalid public key - should fail + using namespace std::string_literals; + EXPECT_EQ( + env.submit( + transactions::AccountSetBuilder{alice}.setMessageKey( + makeSlice("NOT_REALLY_A_PUBKEY"s)), + alice) + .ter, + telBAD_PUBLIC_KEY); +} + +TEST(AccountSet, WalletID) +{ + TxTest env; + Account const alice("alice"); + + env.createAccount(alice, XRP(10000)); + env.close(); + + std::string_view const locator = + "9633EC8AF54F16B5286DB1D7B519EF49EEFC050C0C8AC4384F1D88ACD1BFDF05"; + uint256 locatorHash{}; + EXPECT_TRUE(locatorHash.parseHex(locator)); + + // Set the wallet locator + EXPECT_EQ( + env.submit(transactions::AccountSetBuilder{alice}.setWalletLocator(locatorHash), alice).ter, + tesSUCCESS); + env.close(); + + EXPECT_TRUE(env.getAccountRoot(alice).hasWalletLocator()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + EXPECT_EQ(*env.getAccountRoot(alice).getWalletLocator(), locatorHash); + + // Clear the wallet locator by setting to zero + EXPECT_EQ( + env.submit(transactions::AccountSetBuilder{alice}.setWalletLocator(beast::zero), alice).ter, + tesSUCCESS); + env.close(); + + EXPECT_FALSE(env.getAccountRoot(alice).hasWalletLocator()); +} + +TEST(AccountSet, EmailHash) +{ + TxTest env; + Account const alice("alice"); + + env.createAccount(alice, XRP(10000)); + env.close(); + + std::string_view const mh = "5F31A79367DC3137FADA860C05742EE6"; + uint128 emailHash{}; + EXPECT_TRUE(emailHash.parseHex(mh)); + + // Set the email hash + EXPECT_EQ( + env.submit(transactions::AccountSetBuilder{alice}.setEmailHash(emailHash), alice).ter, + tesSUCCESS); + env.close(); + + EXPECT_TRUE(env.getAccountRoot(alice).hasEmailHash()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + EXPECT_EQ(*env.getAccountRoot(alice).getEmailHash(), emailHash); + + // Clear the email hash by setting to zero + EXPECT_EQ( + env.submit(transactions::AccountSetBuilder{alice}.setEmailHash(beast::zero), alice).ter, + tesSUCCESS); + env.close(); + + EXPECT_FALSE(env.getAccountRoot(alice).hasEmailHash()); +} + +TEST(AccountSet, TransferRate) +{ + struct TestCase + { + double set; + TER code; + double get; + }; + + // Test data: {rate to set, expected TER, expected stored rate} + std::vector const testData = { + {1.0, tesSUCCESS, 1.0}, + {1.1, tesSUCCESS, 1.1}, + {2.0, tesSUCCESS, 2.0}, + {2.1, temBAD_TRANSFER_RATE, 2.0}, // > 2.0 is invalid + {0.0, tesSUCCESS, 1.0}, // 0 clears the rate (default = 1.0) + {2.0, tesSUCCESS, 2.0}, + {0.9, temBAD_TRANSFER_RATE, 2.0}, // < 1.0 is invalid + }; + + TxTest env; + Account const alice("alice"); + + env.createAccount(alice, XRP(10000)); + env.close(); + + for (auto const& r : testData) + { + auto const rateValue = static_cast(QUALITY_ONE * r.set); + + EXPECT_EQ( + env.submit(transactions::AccountSetBuilder{alice}.setTransferRate(rateValue), alice) + .ter, + r.code); + env.close(); + + // If the field is not present, expect the default value (1.0) + if (!env.getAccountRoot(alice).hasTransferRate()) + { + EXPECT_EQ(r.get, 1.0); + } + else + { + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + EXPECT_EQ( + *env.getAccountRoot(alice).getTransferRate(), + static_cast(r.get * QUALITY_ONE)); + } + } +} + +TEST(AccountSet, BadInputs) +{ + TxTest env; + Account const alice("alice"); + + env.createAccount(alice, XRP(10000)); + env.close(); + + // Setting and clearing the same flag is invalid + EXPECT_EQ( + env.submit( + transactions::AccountSetBuilder{alice} + .setSetFlag(asfDisallowXRP) + .setClearFlag(asfDisallowXRP), + alice) + .ter, + temINVALID_FLAG); + + EXPECT_EQ( + env.submit( + transactions::AccountSetBuilder{alice} + .setSetFlag(asfRequireAuth) + .setClearFlag(asfRequireAuth), + alice) + .ter, + temINVALID_FLAG); + + EXPECT_EQ( + env.submit( + transactions::AccountSetBuilder{alice} + .setSetFlag(asfRequireDest) + .setClearFlag(asfRequireDest), + alice) + .ter, + temINVALID_FLAG); + + // Setting asf flag while also using corresponding tf flag is invalid + EXPECT_EQ( + env.submit( + transactions::AccountSetBuilder{alice} + .setSetFlag(asfDisallowXRP) + .setFlags(tfAllowXRP), + alice) + .ter, + temINVALID_FLAG); + + EXPECT_EQ( + env.submit( + transactions::AccountSetBuilder{alice} + .setSetFlag(asfRequireAuth) + .setFlags(tfOptionalAuth), + alice) + .ter, + temINVALID_FLAG); + + EXPECT_EQ( + env.submit( + transactions::AccountSetBuilder{alice} + .setSetFlag(asfRequireDest) + .setFlags(tfOptionalDestTag), + alice) + .ter, + temINVALID_FLAG); + + // Using invalid flags (mask) is invalid + EXPECT_EQ( + env.submit( + transactions::AccountSetBuilder{alice} + .setSetFlag(asfRequireDest) + .setFlags(tfAccountSetMask), + alice) + .ter, + temINVALID_FLAG); + + // Disabling master key without an alternative key is invalid + EXPECT_EQ( + env.submit(transactions::AccountSetBuilder{alice}.setSetFlag(asfDisableMaster), alice).ter, + tecNO_ALTERNATIVE_KEY); +} + +TEST(AccountSet, RequireAuthWithDir) +{ + TxTest env; + Account const alice("alice"); + Account const bob("bob"); + + env.createAccount(alice, XRP(10000)); + env.close(); + + // alice should have an empty directory + EXPECT_TRUE(dirIsEmpty(env.getClosedLedger(), keylet::ownerDir(alice.id()))); + + // Give alice a signer list, then there will be stuff in the directory + // Build the SignerEntries array + STArray signerEntries(1); + { + signerEntries.push_back(STObject::makeInnerObject(sfSignerEntry)); + STObject& entry = signerEntries.back(); + entry[sfAccount] = bob.id(); + entry[sfSignerWeight] = std::uint16_t{1}; + } + + EXPECT_EQ( + env.submit( + transactions::SignerListSetBuilder{alice, 1}.setSignerEntries(signerEntries), alice) + .ter, + tesSUCCESS); + env.close(); + + EXPECT_FALSE(dirIsEmpty(env.getClosedLedger(), keylet::ownerDir(alice.id()))); + + // Setting RequireAuth should fail because alice has owner objects + EXPECT_EQ( + env.submit(transactions::AccountSetBuilder{alice}.setSetFlag(asfRequireAuth), alice).ter, + tecOWNERS); + + // Remove the signer list (quorum = 0, no entries) + EXPECT_EQ(env.submit(transactions::SignerListSetBuilder{alice, 0}, alice).ter, tesSUCCESS); + env.close(); + + EXPECT_TRUE(dirIsEmpty(env.getClosedLedger(), keylet::ownerDir(alice.id()))); + + // Now setting RequireAuth should succeed + EXPECT_EQ( + env.submit(transactions::AccountSetBuilder{alice}.setSetFlag(asfRequireAuth), alice).ter, + tesSUCCESS); +} + +TEST(AccountSet, Ticket) +{ + TxTest env; + Account const alice("alice"); + + env.createAccount(alice, XRP(10000)); + env.close(); + + // Get alice's current sequence - the ticket will be created at seq + 1 + std::uint32_t const aliceSeqBefore = env.getAccountRoot(alice.id()).getSequence(); + std::uint32_t const ticketSeq = aliceSeqBefore + 1; + + // Create a ticket + EXPECT_EQ(env.submit(transactions::TicketCreateBuilder{alice, 1}, alice).ter, tesSUCCESS); + env.close(); + + // Verify alice has 1 owner object (the ticket) + EXPECT_EQ(env.getAccountRoot(alice.id()).getOwnerCount(), 1u); + // Verify ticket exists + EXPECT_TRUE(env.getClosedLedger().exists(keylet::ticket(alice.id(), ticketSeq))); + + // Try using a ticket that alice doesn't have + EXPECT_EQ( + env.submit(transactions::AccountSetBuilder{alice}.setTicketSequence(ticketSeq + 1), alice) + .ter, + terPRE_TICKET); + env.close(); + + // Verify ticket still exists + EXPECT_TRUE(env.getClosedLedger().exists(keylet::ticket(alice.id(), ticketSeq))); + + // Get alice's sequence before using the ticket + std::uint32_t const aliceSeq = env.getAccountRoot(alice.id()).getSequence(); + + // Actually use alice's ticket (noop AccountSet) + EXPECT_EQ( + env.submit(transactions::AccountSetBuilder{alice}.setTicketSequence(ticketSeq), alice).ter, + tesSUCCESS); + env.close(); + + // Verify ticket is consumed (no owner objects) + EXPECT_EQ(env.getAccountRoot(alice.id()).getOwnerCount(), 0u); + EXPECT_FALSE(env.getClosedLedger().exists(keylet::ticket(alice.id(), ticketSeq))); + + // Verify alice's sequence did NOT advance (ticket use doesn't increment seq) + EXPECT_EQ(env.getAccountRoot(alice.id()).getSequence(), aliceSeq); + + // Try re-using a ticket that alice already used + EXPECT_EQ( + env.submit(transactions::AccountSetBuilder{alice}.setTicketSequence(ticketSeq), alice).ter, + tefNO_TICKET); +} + +TEST(AccountSet, BadSigningKey) +{ + TxTest env; + Account const alice("alice"); + + env.createAccount(alice, XRP(10000)); + env.close(); + + // Build a valid transaction first, then corrupt the signing key + auto stx = transactions::AccountSetBuilder{alice} + .setSequence(env.getAccountRoot(alice.id()).getSequence()) + .setFee(XRPAmount{10}) + .build(alice.pk(), alice.sk()) + .getSTTx(); + + // Create a copy with a bad signing key + STObject obj = *stx; + obj.setFieldVL(sfSigningPubKey, makeSlice(std::string("badkey"))); + + auto result = env.submit(std::make_shared(std::move(obj))); + EXPECT_EQ(result.ter, temBAD_SIGNATURE); + EXPECT_FALSE(result.applied); +} + +TEST(AccountSet, Gateway) +{ + Account const alice("alice"); + Account const bob("bob"); + Account const gw("gateway"); + IOU const USD("USD", gw); + + // Test gateway with a variety of allowed transfer rates + for (double transferRate = 1.0; transferRate <= 2.0; transferRate += 0.03125) + { + TxTest env; + + env.createAccount(gw, XRP(10000), asfDefaultRipple); + env.createAccount(alice, XRP(10000), asfDefaultRipple); + env.createAccount(bob, XRP(10000), asfDefaultRipple); + env.close(); + + // Set up trust lines: alice and bob trust gw for USD + EXPECT_EQ( + env.submit(transactions::TrustSetBuilder{alice}.setLimitAmount(USD.amount(10)), alice) + .ter, + tesSUCCESS); + EXPECT_EQ( + env.submit(transactions::TrustSetBuilder{bob}.setLimitAmount(USD.amount(10)), bob).ter, + tesSUCCESS); + env.close(); + + // Set transfer rate on the gateway + EXPECT_EQ( + env.submit( + transactions::AccountSetBuilder{gw}.setTransferRate( + static_cast(transferRate * QUALITY_ONE)), + gw) + .ter, + tesSUCCESS); + env.close(); + + // Calculate the amount with transfer rate applied + auto const amount = USD.amount(1); + Rate const rate(static_cast(transferRate * QUALITY_ONE)); + auto const amountWithRate = multiply(amount, rate); + + // Gateway pays alice 10 USD + EXPECT_EQ( + env.submit(transactions::PaymentBuilder{gw, alice, USD.amount(10)}, gw).ter, + tesSUCCESS); + env.close(); + + // Alice pays bob 1 USD (with sendmax to cover transfer fee) + EXPECT_EQ( + env.submit( + transactions::PaymentBuilder{alice, bob, USD.amount(1)}.setSendMax( + USD.amount(10)), + alice) + .ter, + tesSUCCESS); + env.close(); + + // Check balances + EXPECT_EQ(env.getBalance(alice.id(), USD), USD.amount(10) - amountWithRate); + EXPECT_EQ(env.getBalance(bob.id(), USD), USD.amount(1)); + } + + // Test out-of-bounds legacy transfer rates (4.0 and 4.294967295) + // These require direct ledger modification since the transactor blocks them + for (std::uint32_t const transferRate : {4000000000U, 4294967295U}) + { + TxTest env; + env.createAccount(gw, XRP(10000), asfDefaultRipple); + env.createAccount(alice, XRP(10000), asfDefaultRipple); + env.createAccount(bob, XRP(10000), asfDefaultRipple); + env.close(); + + // Set up trust lines + EXPECT_EQ( + env.submit(transactions::TrustSetBuilder{alice}.setLimitAmount(USD.amount(10)), alice) + .ter, + tesSUCCESS); + EXPECT_EQ( + env.submit(transactions::TrustSetBuilder{bob}.setLimitAmount(USD.amount(10)), bob).ter, + tesSUCCESS); + env.close(); + + // Set an acceptable transfer rate first (we'll hack it later) + EXPECT_EQ( + env.submit( + transactions::AccountSetBuilder{gw}.setTransferRate( + static_cast(2.0 * QUALITY_ONE)), + gw) + .ter, + tesSUCCESS); + env.close(); + + // Directly modify the ledger to set an out-of-bounds transfer rate + // This bypasses the transactor's validation + auto& view = env.getOpenLedger(); + auto slePtr = view.read(keylet::account(gw.id())); + ASSERT_NE(slePtr, nullptr); + auto sleCopy = std::make_shared(*slePtr); + (*sleCopy)[sfTransferRate] = transferRate; + view.rawReplace(sleCopy); + + // Calculate the amount with the legacy transfer rate + auto const amount = USD.amount(1); + auto const amountWithRate = multiply(amount, Rate(transferRate)); + + // Gateway pays alice 10 USD + EXPECT_EQ( + env.submit(transactions::PaymentBuilder{gw, alice, USD.amount(10)}, gw).ter, + tesSUCCESS); + + // Alice pays bob 1 USD + EXPECT_EQ( + env.submit( + transactions::PaymentBuilder{alice, bob, amount}.setSendMax(USD.amount(10)), + alice) + .ter, + tesSUCCESS); + + // Check balances + EXPECT_EQ(env.getBalance(alice.id(), USD), USD.amount(10) - amountWithRate); + EXPECT_EQ(env.getBalance(bob.id(), USD), amount); + } +} + +} // namespace xrpl::test diff --git a/src/tests/libxrpl/tx/main.cpp b/src/tests/libxrpl/tx/main.cpp new file mode 100644 index 00000000000..5142bbe08ad --- /dev/null +++ b/src/tests/libxrpl/tx/main.cpp @@ -0,0 +1,8 @@ +#include + +int +main(int argc, char** argv) +{ + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} From f7275b7ad98d54b59be8498ac2fbbf29f215f7a8 Mon Sep 17 00:00:00 2001 From: Alex Kremer Date: Wed, 29 Apr 2026 16:17:35 +0100 Subject: [PATCH 14/34] chore: Enable clang-tidy v21 new checks (#7031) --- .clang-tidy | 5 + include/xrpl/basics/Log.h | 3 + include/xrpl/basics/Mutex.hpp | 4 +- include/xrpl/basics/Number.h | 16 +- include/xrpl/basics/SlabAllocator.h | 4 +- include/xrpl/basics/TaggedCache.h | 6 +- include/xrpl/basics/TaggedCache.ipp | 40 +- include/xrpl/basics/hardened_hash.h | 2 +- include/xrpl/basics/random.h | 2 +- include/xrpl/beast/asio/io_latency_probe.h | 10 +- include/xrpl/beast/test/yield_to.h | 2 +- include/xrpl/beast/unit_test/match.h | 32 +- include/xrpl/beast/unit_test/reporter.h | 2 + include/xrpl/beast/unit_test/runner.h | 8 +- include/xrpl/beast/unit_test/suite.h | 8 +- include/xrpl/beast/utility/Journal.h | 2 + include/xrpl/core/ClosureCounter.h | 6 +- include/xrpl/core/Coro.ipp | 16 +- include/xrpl/core/Job.h | 2 + include/xrpl/core/PeerReservationTable.h | 2 +- include/xrpl/core/detail/semaphore.h | 4 +- include/xrpl/json/Writer.h | 2 +- include/xrpl/json/json_reader.h | 2 + include/xrpl/json/json_value.h | 6 + include/xrpl/ledger/ApplyView.h | 2 + include/xrpl/ledger/PendingSaves.h | 8 +- include/xrpl/ledger/helpers/AMMHelpers.h | 45 +- include/xrpl/ledger/helpers/LendingHelpers.h | 2 +- include/xrpl/ledger/helpers/TokenHelpers.h | 14 +- include/xrpl/nodestore/NodeObject.h | 2 +- include/xrpl/nodestore/Types.h | 4 +- include/xrpl/nodestore/detail/codec.h | 6 +- include/xrpl/protocol/ErrorCodes.h | 4 + include/xrpl/protocol/LedgerFormats.h | 4 + include/xrpl/protocol/MultiApiJson.h | 7 +- include/xrpl/protocol/Permissions.h | 5 + include/xrpl/protocol/SField.h | 4 + include/xrpl/protocol/SOTemplate.h | 5 +- include/xrpl/protocol/STAmount.h | 2 +- include/xrpl/protocol/STBase.h | 2 + include/xrpl/protocol/STObject.h | 8 +- include/xrpl/protocol/STPathSet.h | 2 + include/xrpl/protocol/SeqProxy.h | 6 +- include/xrpl/protocol/TER.h | 12 + include/xrpl/protocol/TxFormats.h | 2 + include/xrpl/resource/Disposition.h | 2 +- include/xrpl/resource/detail/Entry.h | 2 +- include/xrpl/resource/detail/Kind.h | 2 +- include/xrpl/resource/detail/Logic.h | 48 +- include/xrpl/resource/detail/Tuning.h | 2 + include/xrpl/server/LoadFeeTrack.h | 18 +- include/xrpl/server/detail/BaseHTTPPeer.h | 10 +- include/xrpl/server/detail/ServerImpl.h | 2 + include/xrpl/server/detail/io_list.h | 4 +- include/xrpl/shamap/FullBelowCache.h | 2 + include/xrpl/tx/Transactor.h | 2 + include/xrpl/tx/applySteps.h | 2 +- .../tx/invariants/InvariantCheckPrivilege.h | 2 + include/xrpl/tx/invariants/MPTInvariant.h | 4 +- include/xrpl/tx/paths/detail/Steps.h | 2 +- include/xrpl/tx/paths/detail/StrandFlow.h | 7 +- .../tx/transactors/account/SignerListSet.h | 4 +- .../tx/transactors/system/LedgerStateFix.h | 2 +- src/libxrpl/basics/Log.cpp | 14 +- src/libxrpl/basics/Number.cpp | 15 +- src/libxrpl/basics/ResolverAsio.cpp | 2 +- .../beast/clock/basic_seconds_clock.cpp | 2 +- src/libxrpl/beast/insight/StatsDCollector.cpp | 8 +- .../beast/utility/beast_PropertyStream.cpp | 20 +- src/libxrpl/core/HashRouter.cpp | 14 +- src/libxrpl/core/detail/JobQueue.cpp | 18 +- src/libxrpl/core/detail/LoadMonitor.cpp | 6 +- src/libxrpl/core/detail/Workers.cpp | 10 +- src/libxrpl/crypto/csprng.cpp | 4 +- src/libxrpl/json/Output.cpp | 4 +- src/libxrpl/json/Writer.cpp | 16 +- src/libxrpl/ledger/AcceptedLedgerTx.cpp | 4 +- src/libxrpl/ledger/BookListeners.cpp | 6 +- src/libxrpl/ledger/CachedView.cpp | 4 +- src/libxrpl/ledger/Ledger.cpp | 2 +- src/libxrpl/ledger/helpers/AMMHelpers.cpp | 11 +- src/libxrpl/ledger/helpers/LendingHelpers.cpp | 25 +- src/libxrpl/ledger/helpers/TokenHelpers.cpp | 20 +- src/libxrpl/nodestore/BatchWriter.cpp | 4 +- src/libxrpl/nodestore/Database.cpp | 4 +- src/libxrpl/nodestore/DatabaseNodeImp.cpp | 10 +- src/libxrpl/nodestore/DatabaseRotatingImp.cpp | 28 +- src/libxrpl/nodestore/DecodedBlob.cpp | 10 +- src/libxrpl/nodestore/ManagerImp.cpp | 6 +- .../nodestore/backend/MemoryFactory.cpp | 14 +- src/libxrpl/nodestore/backend/NuDBFactory.cpp | 12 +- src/libxrpl/nodestore/backend/NullFactory.cpp | 2 +- .../nodestore/backend/RocksDBFactory.cpp | 15 +- src/libxrpl/protocol/AccountID.cpp | 4 +- src/libxrpl/protocol/Rules.cpp | 4 +- src/libxrpl/protocol/STAmount.cpp | 2 +- src/libxrpl/protocol/STNumber.cpp | 2 +- src/libxrpl/protocol/STObject.cpp | 12 +- src/libxrpl/protocol/STTx.cpp | 2 +- src/libxrpl/rdb/DatabaseCon.cpp | 6 +- src/libxrpl/rdb/SociDB.cpp | 6 +- src/libxrpl/resource/Consumer.cpp | 4 +- src/libxrpl/resource/ResourceManager.cpp | 2 +- src/libxrpl/server/InfoSub.cpp | 8 +- src/libxrpl/server/LoadFeeTrack.cpp | 4 +- src/libxrpl/shamap/SHAMap.cpp | 2 +- src/libxrpl/shamap/SHAMapDelta.cpp | 6 +- src/libxrpl/shamap/SHAMapInnerNode.cpp | 8 +- src/libxrpl/shamap/SHAMapNodeID.cpp | 2 + src/libxrpl/tx/applySteps.cpp | 6 +- src/libxrpl/tx/invariants/AMMInvariant.cpp | 12 +- src/libxrpl/tx/invariants/InvariantCheck.cpp | 11 +- src/libxrpl/tx/invariants/MPTInvariant.cpp | 21 +- src/libxrpl/tx/paths/BookStep.cpp | 2 +- src/libxrpl/tx/paths/DirectStep.cpp | 9 +- src/libxrpl/tx/paths/MPTEndpointStep.cpp | 12 +- src/libxrpl/tx/paths/OfferStream.cpp | 12 +- src/libxrpl/tx/paths/XRPEndpointStep.cpp | 2 +- .../tx/transactors/account/AccountSet.cpp | 8 +- .../tx/transactors/account/SignerListSet.cpp | 16 +- .../tx/transactors/check/CheckCash.cpp | 4 +- .../tx/transactors/dex/OfferCreate.cpp | 23 +- .../tx/transactors/escrow/EscrowCreate.cpp | 11 +- .../lending/LoanBrokerCoverClawback.cpp | 12 +- .../lending/LoanBrokerCoverWithdraw.cpp | 2 +- .../transactors/lending/LoanBrokerDelete.cpp | 3 +- .../tx/transactors/lending/LoanDelete.cpp | 2 +- .../tx/transactors/lending/LoanManage.cpp | 6 +- .../tx/transactors/lending/LoanPay.cpp | 38 +- .../tx/transactors/lending/LoanSet.cpp | 2 +- .../tx/transactors/nft/NFTokenAcceptOffer.cpp | 11 +- .../tx/transactors/system/LedgerStateFix.cpp | 6 +- src/libxrpl/tx/transactors/token/Clawback.cpp | 22 +- src/test/app/AMMExtended_test.cpp | 2 +- src/test/app/AMM_test.cpp | 9 +- src/test/app/Delegate_test.cpp | 10 +- src/test/app/Invariants_test.cpp | 2 +- src/test/app/LedgerHistory_test.cpp | 4 +- src/test/app/LoanBroker_test.cpp | 74 +- src/test/app/Loan_test.cpp | 43 +- src/test/app/MPToken_test.cpp | 52 +- src/test/app/NFTokenBurn_test.cpp | 4 +- src/test/app/NFTokenDir_test.cpp | 14 +- src/test/app/OfferMPT_test.cpp | 64 +- src/test/app/Offer_test.cpp | 86 +-- src/test/app/Path_test.cpp | 2 +- src/test/app/XChain_test.cpp | 41 +- src/test/basics/IOUAmount_test.cpp | 3 +- src/test/basics/Number_test.cpp | 210 +++--- .../beast/beast_io_latency_probe_test.cpp | 2 +- src/test/consensus/NegativeUNL_test.cpp | 4 +- src/test/core/Coroutine_test.cpp | 2 +- src/test/core/Workers_test.cpp | 2 +- src/test/jtx/AMMTest.h | 2 +- src/test/jtx/Account.h | 2 +- src/test/jtx/CaptureLogs.h | 4 +- src/test/jtx/TestHelpers.h | 2 +- src/test/jtx/directory.h | 2 +- src/test/jtx/impl/AMMTest.cpp | 2 +- src/test/jtx/impl/Account.cpp | 9 +- src/test/jtx/impl/WSClient.cpp | 4 +- src/test/jtx/impl/directory.cpp | 14 +- src/test/jtx/impl/ledgerStateFixes.cpp | 5 +- src/test/ledger/PaymentSandbox_test.cpp | 83 ++- src/test/ledger/View_test.cpp | 65 +- src/test/nodestore/TestBase.h | 16 +- src/test/nodestore/Timing_test.cpp | 6 +- src/test/nodestore/import_test.cpp | 2 +- src/test/overlay/TMGetObjectByHash_test.cpp | 3 +- src/test/overlay/reduce_relay_test.cpp | 7 +- src/test/overlay/short_read_test.cpp | 6 +- src/test/protocol/MultiApiJson_test.cpp | 14 +- src/test/protocol/STNumber_test.cpp | 7 +- src/test/protocol/SeqProxy_test.cpp | 6 +- src/test/resource/Logic_test.cpp | 8 +- src/test/rpc/AMMInfo_test.cpp | 34 +- src/test/rpc/GetAggregatePrice_test.cpp | 3 +- src/test/rpc/RPCCall_test.cpp | 701 +++++++++--------- src/test/shamap/FetchPack_test.cpp | 2 + src/test/shamap/common.h | 4 +- src/test/unit_test/SuiteJournal.h | 2 +- src/test/unit_test/multi_runner.cpp | 10 +- src/test/unit_test/multi_runner.h | 2 + src/tests/libxrpl/basics/Mutex.cpp | 2 +- src/tests/libxrpl/json/Writer.cpp | 26 +- src/xrpld/app/consensus/RCLConsensus.cpp | 12 +- src/xrpld/app/consensus/RCLConsensus.h | 2 +- src/xrpld/app/ledger/AccountStateSF.cpp | 3 +- src/xrpld/app/ledger/LedgerHolder.h | 6 +- src/xrpld/app/ledger/LedgerMaster.h | 2 +- src/xrpld/app/ledger/LedgerReplayer.h | 6 +- src/xrpld/app/ledger/LedgerToJson.h | 2 + src/xrpld/app/ledger/OpenLedger.h | 2 +- src/xrpld/app/ledger/OrderBookDBImpl.cpp | 16 +- src/xrpld/app/ledger/TransactionStateSF.cpp | 3 +- src/xrpld/app/ledger/detail/BuildLedger.cpp | 4 +- src/xrpld/app/ledger/detail/InboundLedger.cpp | 13 +- .../app/ledger/detail/InboundLedgers.cpp | 4 +- .../app/ledger/detail/InboundTransactions.cpp | 12 +- src/xrpld/app/ledger/detail/LedgerCleaner.cpp | 14 +- src/xrpld/app/ledger/detail/LedgerMaster.cpp | 60 +- .../app/ledger/detail/LedgerReplayer.cpp | 14 +- src/xrpld/app/ledger/detail/LedgerToJson.cpp | 2 +- src/xrpld/app/ledger/detail/LocalTxs.cpp | 8 +- src/xrpld/app/ledger/detail/OpenLedger.cpp | 12 +- .../app/ledger/detail/TransactionAcquire.cpp | 2 + .../app/ledger/detail/TransactionMaster.cpp | 4 +- src/xrpld/app/main/Application.cpp | 2 +- src/xrpld/app/main/LoadManager.cpp | 6 +- src/xrpld/app/main/Main.cpp | 2 +- src/xrpld/app/misc/NegativeUNLVote.cpp | 13 +- src/xrpld/app/misc/NegativeUNLVote.h | 2 +- src/xrpld/app/misc/NetworkOPs.cpp | 115 +-- src/xrpld/app/misc/SHAMapStoreImp.cpp | 44 +- src/xrpld/app/misc/SHAMapStoreImp.h | 4 +- src/xrpld/app/misc/Transaction.h | 4 +- src/xrpld/app/misc/TxQ.h | 6 +- src/xrpld/app/misc/ValidatorList.h | 14 +- src/xrpld/app/misc/ValidatorSite.h | 12 +- src/xrpld/app/misc/detail/AmendmentTable.cpp | 56 +- src/xrpld/app/misc/detail/Transaction.cpp | 14 +- src/xrpld/app/misc/detail/TxQ.cpp | 26 +- src/xrpld/app/misc/detail/ValidatorList.cpp | 22 +- src/xrpld/app/misc/detail/ValidatorSite.cpp | 40 +- src/xrpld/app/rdb/backend/detail/Node.cpp | 3 +- src/xrpld/consensus/Consensus.h | 4 +- src/xrpld/consensus/ConsensusParms.h | 14 +- src/xrpld/consensus/DisputedTx.h | 2 +- src/xrpld/consensus/Validations.h | 52 +- src/xrpld/overlay/detail/Cluster.cpp | 8 +- src/xrpld/overlay/detail/Message.cpp | 3 +- src/xrpld/overlay/detail/OverlayImpl.cpp | 36 +- src/xrpld/overlay/detail/OverlayImpl.h | 4 +- src/xrpld/overlay/detail/PeerImp.cpp | 59 +- src/xrpld/overlay/detail/PeerImp.h | 6 +- .../overlay/detail/PeerReservationTable.cpp | 8 +- src/xrpld/overlay/detail/TrafficCount.h | 233 +++--- src/xrpld/overlay/detail/Tuning.h | 2 + src/xrpld/overlay/detail/TxMetrics.cpp | 8 +- src/xrpld/peerfinder/Slot.h | 2 +- src/xrpld/peerfinder/detail/Checker.h | 6 +- src/xrpld/peerfinder/detail/Counts.h | 12 +- src/xrpld/peerfinder/detail/Logic.h | 74 +- .../peerfinder/detail/PeerfinderManager.cpp | 2 +- src/xrpld/peerfinder/detail/SlotImp.cpp | 17 +- src/xrpld/peerfinder/detail/StoreSqdb.h | 2 + src/xrpld/peerfinder/detail/Tuning.h | 4 + src/xrpld/perflog/detail/PerfLogImp.cpp | 34 +- src/xrpld/rpc/detail/AssetCache.cpp | 4 +- src/xrpld/rpc/detail/Handler.h | 2 + src/xrpld/rpc/detail/PathRequest.cpp | 14 +- src/xrpld/rpc/detail/PathRequestManager.cpp | 12 +- src/xrpld/rpc/detail/Pathfinder.cpp | 72 +- src/xrpld/rpc/detail/Pathfinder.h | 4 +- src/xrpld/rpc/detail/RPCSub.cpp | 8 +- src/xrpld/rpc/detail/ServerHandler.cpp | 6 +- src/xrpld/rpc/detail/TransactionSign.cpp | 2 +- src/xrpld/rpc/handlers/transaction/Submit.cpp | 2 +- src/xrpld/shamap/NodeFamily.cpp | 6 +- 259 files changed, 2194 insertions(+), 1889 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index 6a967532db2..6a7005b4646 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -7,6 +7,7 @@ Checks: "-*, bugprone-bad-signal-to-kill-thread, bugprone-bool-pointer-implicit-conversion, bugprone-casting-through-void, + bugprone-capturing-this-in-member-variable, bugprone-chained-comparison, bugprone-compare-pointer-to-member-virtual-function, bugprone-copy-constructor-init, @@ -28,6 +29,7 @@ Checks: "-*, bugprone-misplaced-operator-in-strlen-in-alloc, bugprone-misplaced-pointer-arithmetic-in-alloc, bugprone-misplaced-widening-cast, + bugprone-misleading-setter-of-reference, bugprone-move-forwarding-reference, bugprone-multi-level-implicit-pointer-conversion, bugprone-multiple-new-in-one-expression, @@ -85,6 +87,7 @@ Checks: "-*, cppcoreguidelines-pro-type-static-cast-downcast, cppcoreguidelines-rvalue-reference-param-not-moved, cppcoreguidelines-use-default-member-init, + cppcoreguidelines-use-enum-class, cppcoreguidelines-virtual-class-destructor, hicpp-ignored-remove-result, misc-const-correctness, @@ -109,6 +112,7 @@ Checks: "-*, modernize-use-nodiscard, modernize-use-override, modernize-use-ranges, + modernize-use-scoped-lock, modernize-use-starts-ends-with, modernize-use-std-numbers, modernize-use-using, @@ -122,6 +126,7 @@ Checks: "-*, performance-move-constructor-init, performance-no-automatic-move, performance-trivially-destructible, + readability-ambiguous-smartptr-reset-call, readability-avoid-nested-conditional-operator, readability-avoid-return-with-void-value, readability-braces-around-statements, diff --git a/include/xrpl/basics/Log.h b/include/xrpl/basics/Log.h index 58cca4f486f..5c63166d93e 100644 --- a/include/xrpl/basics/Log.h +++ b/include/xrpl/basics/Log.h @@ -15,6 +15,7 @@ namespace xrpl { // DEPRECATED use beast::severities::Severity instead +// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) enum LogSeverity { lsINVALID = -1, // used to indicate an invalid severity lsTRACE = 0, // Very low-level progress information, details inside @@ -207,6 +208,8 @@ class Logs fromString(std::string const& s); private: + // Need to be named before converting + // NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) enum { // Maximum line length for log messages. // If the message exceeds this length it will be truncated with diff --git a/include/xrpl/basics/Mutex.hpp b/include/xrpl/basics/Mutex.hpp index 5855ee20171..4432e27b4bd 100644 --- a/include/xrpl/basics/Mutex.hpp +++ b/include/xrpl/basics/Mutex.hpp @@ -131,7 +131,7 @@ class Mutex * @tparam LockType The type of lock to use * @return A lock on the mutex and a reference to the protected data */ - template