From be1cc48d84142e43f7a831165be43bc1865adad3 Mon Sep 17 00:00:00 2001 From: Mayukha Vadari Date: Sun, 22 Mar 2026 11:08:18 -0700 Subject: [PATCH 01/53] fix: Assorted Oracle fixes (#6570) --- src/libxrpl/tx/transactors/oracle/OracleSet.cpp | 2 +- src/xrpld/rpc/handlers/GetAggregatePrice.cpp | 15 ++++++++------- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/src/libxrpl/tx/transactors/oracle/OracleSet.cpp b/src/libxrpl/tx/transactors/oracle/OracleSet.cpp index f0fc114d7f..6b21df4d2a 100644 --- a/src/libxrpl/tx/transactors/oracle/OracleSet.cpp +++ b/src/libxrpl/tx/transactors/oracle/OracleSet.cpp @@ -98,7 +98,7 @@ OracleSet::preclaim(PreclaimContext const& ctx) return !v || *v == (*sle)[field]; }; - std::uint32_t adjustReserve = 0; + std::int8_t adjustReserve = 0; if (sle) { // update diff --git a/src/xrpld/rpc/handlers/GetAggregatePrice.cpp b/src/xrpld/rpc/handlers/GetAggregatePrice.cpp index 4fc8e360fc..cf327258a3 100644 --- a/src/xrpld/rpc/handlers/GetAggregatePrice.cpp +++ b/src/xrpld/rpc/handlers/GetAggregatePrice.cpp @@ -218,6 +218,12 @@ doGetAggregatePrice(RPC::JsonContext& context) return result; } + // Get the ledger + std::shared_ptr ledger; + result = RPC::lookupLedger(ledger, context); + if (!ledger) + return result; // LCOV_EXCL_LINE + // Collect the dataset into bimap keyed by lastUpdateTime and // STAmount (Number is int64 and price is uint64) Prices prices; @@ -238,11 +244,6 @@ doGetAggregatePrice(RPC::JsonContext& context) return result; } - std::shared_ptr ledger; - result = RPC::lookupLedger(ledger, context); - if (!ledger) - return result; // LCOV_EXCL_LINE - auto const sle = ledger->read(keylet::oracle(*account, *documentID)); iteratePriceData(context, sle, [&](STObject const& node) { auto const& series = node.getFieldArray(sfPriceDataSeries); @@ -284,8 +285,8 @@ doGetAggregatePrice(RPC::JsonContext& context) if (auto const threshold = std::get(timeThreshold)) { // threshold defines an acceptable range {max,min} of lastUpdateTime as - // {latestTime, latestTime - threshold}, the prices with lastUpdateTime - // greater than (latestTime - threshold) are erased. + // {latestTime, latestTime - threshold}. Prices with lastUpdateTime + // less than (latestTime - threshold) are erased (outdated prices). auto const oldestTime = prices.left.rbegin()->first; auto const upperBound = latestTime > threshold ? (latestTime - threshold) : oldestTime; if (upperBound > oldestTime) From c463d0ff06d18c55d8f3982597667d29fd6f6166 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 23 Mar 2026 10:04:22 -0400 Subject: [PATCH 02/53] ci: [DEPENDABOT] bump codecov/codecov-action from 5.5.2 to 5.5.3 (#6615) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/reusable-build-test-config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/reusable-build-test-config.yml b/.github/workflows/reusable-build-test-config.yml index 02a47e169d..1cc768f9fa 100644 --- a/.github/workflows/reusable-build-test-config.yml +++ b/.github/workflows/reusable-build-test-config.yml @@ -298,7 +298,7 @@ jobs: - name: Upload coverage report if: ${{ github.repository == 'XRPLF/rippled' && !inputs.build_only && env.COVERAGE_ENABLED == 'true' }} - uses: codecov/codecov-action@671740ac38dd9b0130fbe1cec585b89eea48d3de # v5.5.2 + uses: codecov/codecov-action@1af58845a975a7985b0beb0cbe6fbbb71a41dbad # v5.5.3 with: disable_search: true disable_telem: true From e0dbe9037086248dc2a5b99511953a6677fcfc6b Mon Sep 17 00:00:00 2001 From: Mayukha Vadari Date: Mon, 23 Mar 2026 08:39:58 -0700 Subject: [PATCH 03/53] refactor: Move ledger entry helper functions from View.h/View.cpp to dedicated helper files (#6453) Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- include/xrpl/ledger/Credit.h | 43 - include/xrpl/ledger/View.h | 876 +---- .../xrpl/ledger/helpers/AccountRootHelpers.h | 112 + .../ledger/{ => helpers}/CredentialHelpers.h | 0 .../xrpl/ledger/helpers/DirectoryHelpers.h | 223 ++ include/xrpl/ledger/helpers/MPTokenHelpers.h | 160 + include/xrpl/ledger/helpers/OfferHelpers.h | 28 + .../xrpl/ledger/helpers/RippleStateHelpers.h | 255 ++ include/xrpl/ledger/helpers/TokenHelpers.h | 286 ++ include/xrpl/ledger/helpers/VaultHelpers.h | 81 + include/xrpl/tx/paths/detail/StrandFlow.h | 3 +- src/libxrpl/ledger/Credit.cpp | 60 - src/libxrpl/ledger/View.cpp | 3212 +---------------- .../ledger/helpers/AccountRootHelpers.cpp | 247 ++ .../{ => helpers}/CredentialHelpers.cpp | 4 +- .../ledger/helpers/DirectoryHelpers.cpp | 177 + src/libxrpl/ledger/helpers/MPTokenHelpers.cpp | 766 ++++ src/libxrpl/ledger/helpers/OfferHelpers.cpp | 58 + .../ledger/helpers/RippleStateHelpers.cpp | 759 ++++ src/libxrpl/ledger/helpers/TokenHelpers.cpp | 1392 +++++++ src/libxrpl/ledger/helpers/VaultHelpers.cpp | 112 + src/libxrpl/tx/Transactor.cpp | 2 +- .../PermissionedDomainInvariant.cpp | 2 +- src/libxrpl/tx/paths/Flow.cpp | 2 +- .../tx/transactors/account/AccountDelete.cpp | 2 +- .../credentials/CredentialAccept.cpp | 2 +- .../credentials/CredentialCreate.cpp | 2 +- .../credentials/CredentialDelete.cpp | 2 +- .../dex/PermissionedDEXHelpers.cpp | 2 +- .../tx/transactors/escrow/EscrowFinish.cpp | 2 +- .../lending/LoanBrokerCoverWithdraw.cpp | 2 +- .../tx/transactors/payment/DepositPreauth.cpp | 2 +- .../tx/transactors/payment/Payment.cpp | 2 +- .../payment_channel/PaymentChannelClaim.cpp | 2 +- .../PermissionedDomainSet.cpp | 2 +- .../tx/transactors/vault/VaultDeposit.cpp | 2 +- .../tx/transactors/vault/VaultWithdraw.cpp | 2 +- src/test/app/Credentials_test.cpp | 2 +- src/xrpld/app/paths/detail/DirectStep.cpp | 2 +- .../app/paths/detail/XRPEndpointStep.cpp | 2 +- src/xrpld/rpc/handlers/DepositAuthorized.cpp | 2 +- src/xrpld/rpc/handlers/LedgerEntry.cpp | 2 +- 42 files changed, 4692 insertions(+), 4204 deletions(-) delete mode 100644 include/xrpl/ledger/Credit.h create mode 100644 include/xrpl/ledger/helpers/AccountRootHelpers.h rename include/xrpl/ledger/{ => helpers}/CredentialHelpers.h (100%) create mode 100644 include/xrpl/ledger/helpers/DirectoryHelpers.h create mode 100644 include/xrpl/ledger/helpers/MPTokenHelpers.h create mode 100644 include/xrpl/ledger/helpers/OfferHelpers.h create mode 100644 include/xrpl/ledger/helpers/RippleStateHelpers.h create mode 100644 include/xrpl/ledger/helpers/TokenHelpers.h create mode 100644 include/xrpl/ledger/helpers/VaultHelpers.h delete mode 100644 src/libxrpl/ledger/Credit.cpp create mode 100644 src/libxrpl/ledger/helpers/AccountRootHelpers.cpp rename src/libxrpl/ledger/{ => helpers}/CredentialHelpers.cpp (99%) create mode 100644 src/libxrpl/ledger/helpers/DirectoryHelpers.cpp create mode 100644 src/libxrpl/ledger/helpers/MPTokenHelpers.cpp create mode 100644 src/libxrpl/ledger/helpers/OfferHelpers.cpp create mode 100644 src/libxrpl/ledger/helpers/RippleStateHelpers.cpp create mode 100644 src/libxrpl/ledger/helpers/TokenHelpers.cpp create mode 100644 src/libxrpl/ledger/helpers/VaultHelpers.cpp diff --git a/include/xrpl/ledger/Credit.h b/include/xrpl/ledger/Credit.h deleted file mode 100644 index 770b82a650..0000000000 --- a/include/xrpl/ledger/Credit.h +++ /dev/null @@ -1,43 +0,0 @@ -#pragma once - -#include -#include -#include - -namespace xrpl { - -/** Calculate the maximum amount of IOUs that an account can hold - @param ledger the ledger to check against. - @param account the account of interest. - @param issuer the issuer of the IOU. - @param currency the IOU to check. - @return The maximum amount that can be held. -*/ -/** @{ */ -STAmount -creditLimit( - ReadView const& view, - AccountID const& account, - AccountID const& issuer, - Currency const& currency); - -IOUAmount -creditLimit2(ReadView const& v, AccountID const& acc, AccountID const& iss, Currency const& cur); -/** @} */ - -/** Returns the amount of IOUs issued by issuer that are held by an account - @param ledger the ledger to check against. - @param account the account of interest. - @param issuer the issuer of the IOU. - @param currency the IOU to check. -*/ -/** @{ */ -STAmount -creditBalance( - ReadView const& view, - AccountID const& account, - AccountID const& issuer, - Currency const& currency); -/** @} */ - -} // namespace xrpl diff --git a/include/xrpl/ledger/View.h b/include/xrpl/ledger/View.h index cd23cf4978..2ea38c5b8b 100644 --- a/include/xrpl/ledger/View.h +++ b/include/xrpl/ledger/View.h @@ -4,6 +4,13 @@ #include #include #include +#include +#include +#include +#include +#include +#include +#include #include #include #include @@ -21,7 +28,6 @@ namespace xrpl { -enum class WaiveTransferFee : bool { No = false, Yes }; enum class SkipEntry : bool { No = false, Yes }; //------------------------------------------------------------------------------ @@ -54,24 +60,6 @@ enum class SkipEntry : bool { No = false, Yes }; [[nodiscard]] bool hasExpired(ReadView const& view, std::optional const& exp); -/** Controls the treatment of frozen account balances */ -enum FreezeHandling { fhIGNORE_FREEZE, fhZERO_IF_FROZEN }; - -/** Controls the treatment of unauthorized MPT balances */ -enum AuthHandling { ahIGNORE_AUTH, ahZERO_IF_UNAUTHORIZED }; - -/** Controls whether to include the account's full spendable balance */ -enum SpendableHandling { shSIMPLE_BALANCE, shFULL_BALANCE }; - -[[nodiscard]] bool -isGlobalFrozen(ReadView const& view, AccountID const& issuer); - -[[nodiscard]] bool -isGlobalFrozen(ReadView const& view, MPTIssue const& mptIssue); - -[[nodiscard]] bool -isGlobalFrozen(ReadView const& view, Asset const& asset); - // Note, depth parameter is used to limit the recursion depth [[nodiscard]] bool isVaultPseudoAccountFrozen( @@ -80,175 +68,6 @@ isVaultPseudoAccountFrozen( MPTIssue const& mptShare, int depth); -[[nodiscard]] bool -isIndividualFrozen( - ReadView const& view, - AccountID const& account, - Currency const& currency, - AccountID const& issuer); - -[[nodiscard]] inline bool -isIndividualFrozen(ReadView const& view, AccountID const& account, Issue const& issue) -{ - return isIndividualFrozen(view, account, issue.currency, issue.account); -} - -[[nodiscard]] bool -isIndividualFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue); - -[[nodiscard]] inline bool -isIndividualFrozen(ReadView const& view, AccountID const& account, Asset const& asset) -{ - return std::visit( - [&](auto const& issue) { return isIndividualFrozen(view, account, issue); }, asset.value()); -} - -[[nodiscard]] bool -isFrozen( - ReadView const& view, - AccountID const& account, - Currency const& currency, - AccountID const& issuer); - -[[nodiscard]] inline bool -isFrozen(ReadView const& view, AccountID const& account, Issue const& issue, int = 0 /*ignored*/) -{ - return isFrozen(view, account, issue.currency, issue.account); -} - -[[nodiscard]] bool -isFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue, int depth = 0); - -/** - * isFrozen check is recursive for MPT shares in a vault, descending to - * assets in the vault, up to maxAssetCheckDepth recursion depth. This is - * purely defensive, as we currently do not allow such vaults to be created. - */ -[[nodiscard]] inline bool -isFrozen(ReadView const& view, AccountID const& account, Asset const& asset, int depth = 0) -{ - return std::visit( - [&](auto const& issue) { return isFrozen(view, account, issue, depth); }, asset.value()); -} - -[[nodiscard]] inline TER -checkFrozen(ReadView const& view, AccountID const& account, Issue const& issue) -{ - return isFrozen(view, account, issue) ? (TER)tecFROZEN : (TER)tesSUCCESS; -} - -[[nodiscard]] inline TER -checkFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue) -{ - return isFrozen(view, account, mptIssue) ? (TER)tecLOCKED : (TER)tesSUCCESS; -} - -[[nodiscard]] inline TER -checkFrozen(ReadView const& view, AccountID const& account, Asset const& asset) -{ - return std::visit( - [&](auto const& issue) { return checkFrozen(view, account, issue); }, asset.value()); -} - -[[nodiscard]] bool -isAnyFrozen( - ReadView const& view, - std::initializer_list const& accounts, - MPTIssue const& mptIssue, - int depth = 0); - -[[nodiscard]] inline bool -isAnyFrozen( - ReadView const& view, - std::initializer_list const& accounts, - Issue const& issue) -{ - for (auto const& account : accounts) - { - if (isFrozen(view, account, issue.currency, issue.account)) - return true; - } - return false; -} - -[[nodiscard]] inline bool -isAnyFrozen( - ReadView const& view, - std::initializer_list const& accounts, - Asset const& asset, - int depth = 0) -{ - return std::visit( - [&](TIss const& issue) { - if constexpr (std::is_same_v) - return isAnyFrozen(view, accounts, issue); - else - return isAnyFrozen(view, accounts, issue, depth); - }, - asset.value()); -} - -[[nodiscard]] bool -isDeepFrozen( - ReadView const& view, - AccountID const& account, - Currency const& currency, - AccountID const& issuer); - -[[nodiscard]] inline bool -isDeepFrozen( - ReadView const& view, - AccountID const& account, - Issue const& issue, - int = 0 /*ignored*/) -{ - return isDeepFrozen(view, account, issue.currency, issue.account); -} - -[[nodiscard]] inline bool -isDeepFrozen( - ReadView const& view, - AccountID const& account, - MPTIssue const& mptIssue, - int depth = 0) -{ - // Unlike IOUs, frozen / locked MPTs are not allowed to send or receive - // funds, so checking "deep frozen" is the same as checking "frozen". - return isFrozen(view, account, mptIssue, depth); -} - -/** - * isFrozen check is recursive for MPT shares in a vault, descending to - * assets in the vault, up to maxAssetCheckDepth recursion depth. This is - * purely defensive, as we currently do not allow such vaults to be created. - */ -[[nodiscard]] inline bool -isDeepFrozen(ReadView const& view, AccountID const& account, Asset const& asset, int depth = 0) -{ - return std::visit( - [&](auto const& issue) { return isDeepFrozen(view, account, issue, depth); }, - asset.value()); -} - -[[nodiscard]] inline TER -checkDeepFrozen(ReadView const& view, AccountID const& account, Issue const& issue) -{ - return isDeepFrozen(view, account, issue) ? (TER)tecFROZEN : (TER)tesSUCCESS; -} - -[[nodiscard]] inline TER -checkDeepFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue) -{ - return isDeepFrozen(view, account, mptIssue) ? (TER)tecLOCKED : (TER)tesSUCCESS; -} - -[[nodiscard]] inline TER -checkDeepFrozen(ReadView const& view, AccountID const& account, Asset const& asset) -{ - return std::visit( - [&](auto const& issue) { return checkDeepFrozen(view, account, issue); }, asset.value()); -} - [[nodiscard]] bool isLPTokenFrozen( ReadView const& view, @@ -256,159 +75,6 @@ isLPTokenFrozen( Issue const& asset, Issue const& asset2); -// Returns the amount an account can spend. -// -// If shSIMPLE_BALANCE is specified, this is the amount the account can spend -// without going into debt. -// -// If shFULL_BALANCE is specified, this is the amount the account can spend -// total. Specifically: -// * The account can go into debt if using a trust line, and the other side has -// a non-zero limit. -// * If the account is the asset issuer the limit is defined by the asset / -// issuance. -// -// <-- saAmount: amount of currency held by account. May be negative. -[[nodiscard]] STAmount -accountHolds( - ReadView const& view, - AccountID const& account, - Currency const& currency, - AccountID const& issuer, - FreezeHandling zeroIfFrozen, - beast::Journal j, - SpendableHandling includeFullBalance = shSIMPLE_BALANCE); - -[[nodiscard]] STAmount -accountHolds( - ReadView const& view, - AccountID const& account, - Issue const& issue, - FreezeHandling zeroIfFrozen, - beast::Journal j, - SpendableHandling includeFullBalance = shSIMPLE_BALANCE); - -[[nodiscard]] STAmount -accountHolds( - ReadView const& view, - AccountID const& account, - MPTIssue const& mptIssue, - FreezeHandling zeroIfFrozen, - AuthHandling zeroIfUnauthorized, - beast::Journal j, - SpendableHandling includeFullBalance = shSIMPLE_BALANCE); - -[[nodiscard]] STAmount -accountHolds( - ReadView const& view, - AccountID const& account, - Asset const& asset, - FreezeHandling zeroIfFrozen, - AuthHandling zeroIfUnauthorized, - beast::Journal j, - SpendableHandling includeFullBalance = shSIMPLE_BALANCE); - -// Returns the amount an account can spend of the currency type saDefault, or -// returns saDefault if this account is the issuer of the currency in -// question. Should be used in favor of accountHolds when questioning how much -// an account can spend while also allowing currency issuers to spend -// unlimited amounts of their own currency (since they can always issue more). -[[nodiscard]] STAmount -accountFunds( - ReadView const& view, - AccountID const& id, - STAmount const& saDefault, - FreezeHandling freezeHandling, - beast::Journal j); - -// Return the account's liquid (not reserved) XRP. Generally prefer -// calling accountHolds() over this interface. However, this interface -// allows the caller to temporarily adjust the owner count should that be -// necessary. -// -// @param ownerCountAdj positive to add to count, negative to reduce count. -[[nodiscard]] XRPAmount -xrpLiquid(ReadView const& view, AccountID const& id, std::int32_t ownerCountAdj, beast::Journal j); - -/** Iterate all items in the given directory. */ -void -forEachItem( - ReadView const& view, - Keylet const& root, - std::function const&)> const& f); - -/** Iterate all items after an item in the given directory. - @param after The key of the item to start after - @param hint The directory page containing `after` - @param limit The maximum number of items to return - @return `false` if the iteration failed -*/ -bool -forEachItemAfter( - ReadView const& view, - Keylet const& root, - uint256 const& after, - std::uint64_t const hint, - unsigned int limit, - std::function const&)> const& f); - -/** Iterate all items in an account's owner directory. */ -inline void -forEachItem( - ReadView const& view, - AccountID const& id, - std::function const&)> const& f) -{ - return forEachItem(view, keylet::ownerDir(id), f); -} - -/** Iterate all items after an item in an owner directory. - @param after The key of the item to start after - @param hint The directory page containing `after` - @param limit The maximum number of items to return - @return `false` if the iteration failed -*/ -inline bool -forEachItemAfter( - ReadView const& view, - AccountID const& id, - uint256 const& after, - std::uint64_t const hint, - unsigned int limit, - std::function const&)> const& f) -{ - return forEachItemAfter(view, keylet::ownerDir(id), after, hint, limit, f); -} - -/** Returns IOU issuer transfer fee as Rate. Rate specifies - * the fee as fractions of 1 billion. For example, 1% transfer rate - * is represented as 1,010,000,000. - * @param issuer The IOU issuer - */ -[[nodiscard]] Rate -transferRate(ReadView const& view, AccountID const& issuer); - -/** Returns MPT transfer fee as Rate. Rate specifies - * the fee as fractions of 1 billion. For example, 1% transfer rate - * is represented as 1,010,000,000. - * @param issuanceID MPTokenIssuanceID of MPTTokenIssuance object - */ -[[nodiscard]] Rate -transferRate(ReadView const& view, MPTID const& issuanceID); - -/** Returns the transfer fee as Rate based on the type of token - * @param view The ledger view - * @param amount The amount to transfer - */ -[[nodiscard]] Rate -transferRate(ReadView const& view, STAmount const& amount); - -/** Returns `true` if the directory is empty - @param key The key of the directory -*/ -[[nodiscard]] bool -dirIsEmpty(ReadView const& view, Keylet const& k); - // Return the list of enabled amendments [[nodiscard]] std::set getEnabledAmendments(ReadView const& view); @@ -474,81 +140,6 @@ areCompatible( // //------------------------------------------------------------------------------ -/** Adjust the owner count up or down. */ -void -adjustOwnerCount( - ApplyView& view, - std::shared_ptr const& sle, - std::int32_t amount, - beast::Journal j); - -/** @{ */ -/** Returns the first entry in the directory, advancing the index - - @deprecated These are legacy function that are considered deprecated - and will soon be replaced with an iterator-based model - that is easier to use. You should not use them in new code. - - @param view The view against which to operate - @param root The root (i.e. first page) of the directory to iterate - @param page The current page - @param index The index inside the current page - @param entry The entry at the current index - - @return true if the directory isn't empty; false otherwise - */ -bool -cdirFirst( - ReadView const& view, - uint256 const& root, - std::shared_ptr& page, - unsigned int& index, - uint256& entry); - -bool -dirFirst( - ApplyView& view, - uint256 const& root, - std::shared_ptr& page, - unsigned int& index, - uint256& entry); -/** @} */ - -/** @{ */ -/** Returns the next entry in the directory, advancing the index - - @deprecated These are legacy function that are considered deprecated - and will soon be replaced with an iterator-based model - that is easier to use. You should not use them in new code. - - @param view The view against which to operate - @param root The root (i.e. first page) of the directory to iterate - @param page The current page - @param index The index inside the current page - @param entry The entry at the current index - - @return true if the directory isn't empty; false otherwise - */ -bool -cdirNext( - ReadView const& view, - uint256 const& root, - std::shared_ptr& page, - unsigned int& index, - uint256& entry); - -bool -dirNext( - ApplyView& view, - uint256 const& root, - std::shared_ptr& page, - unsigned int& index, - uint256& entry); -/** @} */ - -[[nodiscard]] std::function -describeOwnerDir(AccountID const& account); - [[nodiscard]] TER dirLink( ApplyView& view, @@ -556,63 +147,6 @@ dirLink( std::shared_ptr& object, SF_UINT64 const& node = sfOwnerNode); -AccountID -pseudoAccountAddress(ReadView const& view, uint256 const& pseudoOwnerKey); - -/** - * - * Create pseudo-account, storing pseudoOwnerKey into ownerField. - * - * The list of valid ownerField is maintained in View.cpp and the caller to - * this function must perform necessary amendment check(s) before using a - * field. The amendment check is **not** performed in createPseudoAccount. - */ -[[nodiscard]] Expected, TER> -createPseudoAccount(ApplyView& view, uint256 const& pseudoOwnerKey, SField const& ownerField); - -// Returns true if and only if sleAcct is a pseudo-account or specific -// pseudo-accounts in pseudoFieldFilter. -// -// Returns false if sleAcct is -// * NOT a pseudo-account OR -// * NOT a ltACCOUNT_ROOT OR -// * null pointer -[[nodiscard]] bool -isPseudoAccount( - std::shared_ptr sleAcct, - std::set const& pseudoFieldFilter = {}); - -// Returns the list of fields that define an ACCOUNT_ROOT as a pseudo-account if -// set -// Pseudo-account designator fields MUST be maintained by including the -// SField::sMD_PseudoAccount flag in the SField definition. (Don't forget to -// "| SField::sMD_Default"!) The fields do NOT need to be amendment-gated, -// since a non-active amendment will not set any field, by definition. -// Specific properties of a pseudo-account are NOT checked here, that's what -// InvariantCheck is for. -[[nodiscard]] std::vector const& -getPseudoAccountFields(); - -[[nodiscard]] inline bool -isPseudoAccount( - ReadView const& view, - AccountID const& accountId, - std::set const& pseudoFieldFilter = {}) -{ - return isPseudoAccount(view.read(keylet::account(accountId)), pseudoFieldFilter); -} - -[[nodiscard]] TER -canAddHolding(ReadView const& view, Asset const& asset); - -/** Validates that the destination SLE and tag are valid - - - Checks that the SLE is not null. - - If the SLE requires a destination tag, checks that there is a tag. -*/ -[[nodiscard]] TER -checkDestinationAndTag(SLE::const_ref toSle, bool hasDestinationTag); - /** Checks that can withdraw funds from an object to itself or a destination. * * The receiver may be either the submitting account (sfAccount) or a different @@ -686,351 +220,6 @@ doWithdraw( STAmount const& amount, beast::Journal j); -/// Any transactors that call addEmptyHolding() in doApply must call -/// canAddHolding() in preflight with the same View and Asset -[[nodiscard]] TER -addEmptyHolding( - ApplyView& view, - AccountID const& accountID, - XRPAmount priorBalance, - Issue const& issue, - beast::Journal journal); - -[[nodiscard]] TER -addEmptyHolding( - ApplyView& view, - AccountID const& accountID, - XRPAmount priorBalance, - MPTIssue const& mptIssue, - beast::Journal journal); - -[[nodiscard]] inline TER -addEmptyHolding( - ApplyView& view, - AccountID const& accountID, - XRPAmount priorBalance, - Asset const& asset, - beast::Journal journal) -{ - return std::visit( - [&](TIss const& issue) -> TER { - return addEmptyHolding(view, accountID, priorBalance, issue, journal); - }, - asset.value()); -} - -[[nodiscard]] TER -authorizeMPToken( - ApplyView& view, - XRPAmount const& priorBalance, - MPTID const& mptIssuanceID, - AccountID const& account, - beast::Journal journal, - std::uint32_t flags = 0, - std::optional holderID = std::nullopt); - -// VFALCO NOTE Both STAmount parameters should just -// be "Amount", a unit-less number. -// -/** Create a trust line - - This can set an initial balance. -*/ -[[nodiscard]] TER -trustCreate( - ApplyView& view, - bool const bSrcHigh, - AccountID const& uSrcAccountID, - AccountID const& uDstAccountID, - uint256 const& uIndex, // --> ripple state entry - SLE::ref sleAccount, // --> the account being set. - bool const bAuth, // --> authorize account. - bool const bNoRipple, // --> others cannot ripple through - bool const bFreeze, // --> funds cannot leave - bool bDeepFreeze, // --> can neither receive nor send funds - STAmount const& saBalance, // --> balance of account being set. - // Issuer should be noAccount() - STAmount const& saLimit, // --> limit for account being set. - // Issuer should be the account being set. - std::uint32_t uSrcQualityIn, - std::uint32_t uSrcQualityOut, - beast::Journal j); - -[[nodiscard]] TER -removeEmptyHolding( - ApplyView& view, - AccountID const& accountID, - Issue const& issue, - beast::Journal journal); - -[[nodiscard]] TER -removeEmptyHolding( - ApplyView& view, - AccountID const& accountID, - MPTIssue const& mptIssue, - beast::Journal journal); - -[[nodiscard]] inline TER -removeEmptyHolding( - ApplyView& view, - AccountID const& accountID, - Asset const& asset, - beast::Journal journal) -{ - return std::visit( - [&](TIss const& issue) -> TER { - return removeEmptyHolding(view, accountID, issue, journal); - }, - asset.value()); -} - -[[nodiscard]] TER -trustDelete( - ApplyView& view, - std::shared_ptr const& sleRippleState, - AccountID const& uLowAccountID, - AccountID const& uHighAccountID, - beast::Journal j); - -/** Delete an offer. - - Requirements: - The passed `sle` be obtained from a prior - call to view.peek() -*/ -// [[nodiscard]] // nodiscard commented out so Flow, BookTip and others compile. -TER -offerDelete(ApplyView& view, std::shared_ptr const& sle, beast::Journal j); - -//------------------------------------------------------------------------------ - -// -// Money Transfers -// - -// Direct send w/o fees: -// - Redeeming IOUs and/or sending sender's own IOUs. -// - Create trust line of needed. -// --> bCheckIssuer : normally require issuer to be involved. -// [[nodiscard]] // nodiscard commented out so DirectStep.cpp compiles. - -/** Calls static rippleCreditIOU if saAmount represents Issue. - * Calls static rippleCreditMPT if saAmount represents MPTIssue. - */ -TER -rippleCredit( - ApplyView& view, - AccountID const& uSenderID, - AccountID const& uReceiverID, - STAmount const& saAmount, - bool bCheckIssuer, - beast::Journal j); - -TER -rippleLockEscrowMPT( - ApplyView& view, - AccountID const& uGrantorID, - STAmount const& saAmount, - beast::Journal j); - -TER -rippleUnlockEscrowMPT( - ApplyView& view, - AccountID const& uGrantorID, - AccountID const& uGranteeID, - STAmount const& netAmount, - STAmount const& grossAmount, - beast::Journal j); - -/** Calls static accountSendIOU if saAmount represents Issue. - * Calls static accountSendMPT if saAmount represents MPTIssue. - */ -[[nodiscard]] TER -accountSend( - ApplyView& view, - AccountID const& from, - AccountID const& to, - STAmount const& saAmount, - beast::Journal j, - WaiveTransferFee waiveFee = WaiveTransferFee::No); - -using MultiplePaymentDestinations = std::vector>; -/** Like accountSend, except one account is sending multiple payments (with the - * same asset!) simultaneously - * - * Calls static accountSendMultiIOU if saAmount represents Issue. - * Calls static accountSendMultiMPT if saAmount represents MPTIssue. - */ -[[nodiscard]] TER -accountSendMulti( - ApplyView& view, - AccountID const& senderID, - Asset const& asset, - MultiplePaymentDestinations const& receivers, - beast::Journal j, - WaiveTransferFee waiveFee = WaiveTransferFee::No); - -[[nodiscard]] TER -issueIOU( - ApplyView& view, - AccountID const& account, - STAmount const& amount, - Issue const& issue, - beast::Journal j); - -[[nodiscard]] TER -redeemIOU( - ApplyView& view, - AccountID const& account, - STAmount const& amount, - Issue const& issue, - beast::Journal j); - -[[nodiscard]] TER -transferXRP( - ApplyView& view, - AccountID const& from, - AccountID const& to, - STAmount const& amount, - beast::Journal j); - -/* Check if MPToken (for MPT) or trust line (for IOU) exists: - * - StrongAuth - before checking if authorization is required - * - WeakAuth - * for MPT - after checking lsfMPTRequireAuth flag - * for IOU - do not check if trust line exists - * - Legacy - * for MPT - before checking lsfMPTRequireAuth flag i.e. same as StrongAuth - * for IOU - do not check if trust line exists i.e. same as WeakAuth - */ -enum class AuthType { StrongAuth, WeakAuth, Legacy }; - -/** Check if the account lacks required authorization. - * - * Return tecNO_AUTH or tecNO_LINE if it does - * and tesSUCCESS otherwise. - * - * If StrongAuth then return tecNO_LINE if the RippleState doesn't exist. Return - * tecNO_AUTH if lsfRequireAuth is set on the issuer's AccountRoot, and the - * RippleState does exist, and the RippleState is not authorized. - * - * If WeakAuth then return tecNO_AUTH if lsfRequireAuth is set, and the - * RippleState exists, and is not authorized. Return tecNO_LINE if - * lsfRequireAuth is set and the RippleState doesn't exist. Consequently, if - * WeakAuth and lsfRequireAuth is *not* set, this function will return - * tesSUCCESS even if RippleState does *not* exist. - * - * The default "Legacy" auth type is equivalent to WeakAuth. - */ -[[nodiscard]] TER -requireAuth( - ReadView const& view, - Issue const& issue, - AccountID const& account, - AuthType authType = AuthType::Legacy); - -/** Check if the account lacks required authorization. - * - * This will also check for expired credentials. If it is called directly - * from preclaim, the user should convert result tecEXPIRED to tesSUCCESS and - * proceed to also check permissions with enforceMPTokenAuthorization inside - * doApply. This will ensure that any expired credentials are deleted. - * - * requireAuth check is recursive for MPT shares in a vault, descending to - * assets in the vault, up to maxAssetCheckDepth recursion depth. This is - * purely defensive, as we currently do not allow such vaults to be created. - * - * If StrongAuth then return tecNO_AUTH if MPToken doesn't exist or - * lsfMPTRequireAuth is set and MPToken is not authorized. Vault and LoanBroker - * pseudo-accounts are implicitly authorized. - * - * If WeakAuth then return tecNO_AUTH if lsfMPTRequireAuth is set and MPToken - * doesn't exist or is not authorized (explicitly or via credentials, if - * DomainID is set in MPTokenIssuance). Consequently, if WeakAuth and - * lsfMPTRequireAuth is *not* set, this function will return true even if - * MPToken does *not* exist. - * - * The default "Legacy" auth type is equivalent to StrongAuth. - */ -[[nodiscard]] TER -requireAuth( - ReadView const& view, - MPTIssue const& mptIssue, - AccountID const& account, - AuthType authType = AuthType::Legacy, - int depth = 0); - -[[nodiscard]] TER inline requireAuth( - ReadView const& view, - Asset const& asset, - AccountID const& account, - AuthType authType = AuthType::Legacy) -{ - return std::visit( - [&](TIss const& issue_) { - return requireAuth(view, issue_, account, authType); - }, - asset.value()); -} - -/** Enforce account has MPToken to match its authorization. - * - * Called from doApply - it will check for expired (and delete if found any) - * credentials matching DomainID set in MPTokenIssuance. Must be called if - * requireAuth(...MPTIssue...) returned tesSUCCESS or tecEXPIRED in preclaim, - * which implies that preclaim should replace `tecEXPIRED` with `tesSUCCESS` - * in order for the transactor to proceed to doApply. - * - * This function will create MPToken (if needed) on the basis of any - * non-expired credentials and will delete any expired credentials, indirectly - * via verifyValidDomain, as per DomainID (if set in MPTokenIssuance). - * - * The caller does NOT need to ensure that DomainID is actually set - this - * function handles gracefully both cases when DomainID is set and when not. - * - * The caller does NOT need to look for existing MPToken to match - * mptIssue/account - this function checks lsfMPTAuthorized of an existing - * MPToken iff DomainID is not set. - * - * Do not use for accounts which hold implied permission e.g. object owners or - * if MPTokenIssuance does not require authorization. In both cases use - * MPTokenAuthorize::authorize if MPToken does not yet exist. - */ -[[nodiscard]] TER -enforceMPTokenAuthorization( - ApplyView& view, - MPTID const& mptIssuanceID, - AccountID const& account, - XRPAmount const& priorBalance, - beast::Journal j); - -/** Check if the destination account is allowed - * to receive MPT. Return tecNO_AUTH if it doesn't - * and tesSUCCESS otherwise. - */ -[[nodiscard]] TER -canTransfer( - ReadView const& view, - MPTIssue const& mptIssue, - AccountID const& from, - AccountID const& to); - -[[nodiscard]] TER -canTransfer(ReadView const& view, Issue const& issue, AccountID const& from, AccountID const& to); - -[[nodiscard]] TER inline canTransfer( - ReadView const& view, - Asset const& asset, - AccountID const& from, - AccountID const& to) -{ - return std::visit( - [&](TIss const& issue) -> TER { - return canTransfer(view, issue, from, to); - }, - asset.value()); -} - /** Deleter function prototype. Returns the status of the entry deletion * (if should not be skipped) and if the entry should be skipped. The status * is always tesSUCCESS if the entry should be skipped. @@ -1052,57 +241,6 @@ cleanupOnAccountDelete( beast::Journal j, std::optional maxNodesToDelete = std::nullopt); -/** Delete trustline to AMM. The passed `sle` must be obtained from a prior - * call to view.peek(). Fail if neither side of the trustline is AMM or - * if ammAccountID is seated and is not one of the trustline's side. - */ -[[nodiscard]] TER -deleteAMMTrustLine( - ApplyView& view, - std::shared_ptr sleState, - std::optional const& ammAccountID, - beast::Journal j); - -// From the perspective of a vault, return the number of shares to give the -// depositor when they deposit a fixed amount of assets. Since shares are MPT -// this number is integral and always truncated in this calculation. -[[nodiscard]] std::optional -assetsToSharesDeposit( - std::shared_ptr const& vault, - std::shared_ptr const& issuance, - STAmount const& assets); - -// From the perspective of a vault, return the number of assets to take from -// depositor when they receive a fixed amount of shares. Note, since shares are -// MPT, they are always an integral number. -[[nodiscard]] std::optional -sharesToAssetsDeposit( - std::shared_ptr const& vault, - std::shared_ptr const& issuance, - STAmount const& shares); - -enum class TruncateShares : bool { no = false, yes = true }; - -// From the perspective of a vault, return the number of shares to demand from -// the depositor when they ask to withdraw a fixed amount of assets. Since -// shares are MPT this number is integral, and it will be rounded to nearest -// unless explicitly requested to be truncated instead. -[[nodiscard]] std::optional -assetsToSharesWithdraw( - std::shared_ptr const& vault, - std::shared_ptr const& issuance, - STAmount const& assets, - TruncateShares truncate = TruncateShares::no); - -// From the perspective of a vault, return the number of assets to give the -// depositor when they redeem a fixed amount of shares. Note, since shares are -// MPT, they are always an integral number. -[[nodiscard]] std::optional -sharesToAssetsWithdraw( - std::shared_ptr const& vault, - std::shared_ptr const& issuance, - STAmount const& shares); - /** Has the specified time passed? @param now the current time diff --git a/include/xrpl/ledger/helpers/AccountRootHelpers.h b/include/xrpl/ledger/helpers/AccountRootHelpers.h new file mode 100644 index 0000000000..353c27fe41 --- /dev/null +++ b/include/xrpl/ledger/helpers/AccountRootHelpers.h @@ -0,0 +1,112 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace xrpl { + +/** Check if the issuer has the global freeze flag set. + @param issuer The account to check + @return true if the account has global freeze set +*/ +[[nodiscard]] bool +isGlobalFrozen(ReadView const& view, AccountID const& issuer); + +// Calculate liquid XRP balance for an account. +// This function may be used to calculate the amount of XRP that +// the holder is able to freely spend. It subtracts reserve requirements. +// +// ownerCountAdj adjusts the owner count in case the caller calculates +// before ledger entries are added or removed. Positive to add, negative +// to subtract. +// +// @param ownerCountAdj positive to add to count, negative to reduce count. +[[nodiscard]] XRPAmount +xrpLiquid(ReadView const& view, AccountID const& id, std::int32_t ownerCountAdj, beast::Journal j); + +/** Adjust the owner count up or down. */ +void +adjustOwnerCount( + ApplyView& view, + std::shared_ptr const& sle, + std::int32_t amount, + beast::Journal j); + +/** Returns IOU issuer transfer fee as Rate. Rate specifies + * the fee as fractions of 1 billion. For example, 1% transfer rate + * is represented as 1,010,000,000. + * @param issuer The IOU issuer + */ +[[nodiscard]] Rate +transferRate(ReadView const& view, AccountID const& issuer); + +/** Generate a pseudo-account address from a pseudo owner key. + @param pseudoOwnerKey The key to generate the address from + @return The generated account ID +*/ +AccountID +pseudoAccountAddress(ReadView const& view, uint256 const& pseudoOwnerKey); + +/** Returns the list of fields that define an ACCOUNT_ROOT as a pseudo-account + if set. + + The list is constructed during initialization and is const after that. + Pseudo-account designator fields MUST be maintained by including the + SField::sMD_PseudoAccount flag in the SField definition. +*/ +[[nodiscard]] std::vector const& +getPseudoAccountFields(); + +/** Returns true if and only if sleAcct is a pseudo-account or specific + pseudo-accounts in pseudoFieldFilter. + + Returns false if sleAcct is: + - NOT a pseudo-account OR + - NOT a ltACCOUNT_ROOT OR + - null pointer +*/ +[[nodiscard]] bool +isPseudoAccount( + std::shared_ptr sleAcct, + std::set const& pseudoFieldFilter = {}); + +/** Convenience overload that reads the account from the view. */ +[[nodiscard]] inline bool +isPseudoAccount( + ReadView const& view, + AccountID const& accountId, + std::set const& pseudoFieldFilter = {}) +{ + return isPseudoAccount(view.read(keylet::account(accountId)), pseudoFieldFilter); +} + +/** + * Create pseudo-account, storing pseudoOwnerKey into ownerField. + * + * The list of valid ownerField is maintained in AccountRootHelpers.cpp and + * the caller to this function must perform necessary amendment check(s) + * before using a field. The amendment check is **not** performed in + * createPseudoAccount. + */ +[[nodiscard]] Expected, TER> +createPseudoAccount(ApplyView& view, uint256 const& pseudoOwnerKey, SField const& ownerField); + +/** Checks the destination and tag. + + - Checks that the SLE is not null. + - If the SLE requires a destination tag, checks that there is a tag. +*/ +[[nodiscard]] TER +checkDestinationAndTag(SLE::const_ref toSle, bool hasDestinationTag); + +} // namespace xrpl diff --git a/include/xrpl/ledger/CredentialHelpers.h b/include/xrpl/ledger/helpers/CredentialHelpers.h similarity index 100% rename from include/xrpl/ledger/CredentialHelpers.h rename to include/xrpl/ledger/helpers/CredentialHelpers.h diff --git a/include/xrpl/ledger/helpers/DirectoryHelpers.h b/include/xrpl/ledger/helpers/DirectoryHelpers.h new file mode 100644 index 0000000000..189dfcd263 --- /dev/null +++ b/include/xrpl/ledger/helpers/DirectoryHelpers.h @@ -0,0 +1,223 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace xrpl { + +namespace detail { + +template < + class V, + class N, + class = std::enable_if_t< + std::is_same_v, SLE> && std::is_base_of_v>> +bool +internalDirNext( + V& view, + uint256 const& root, + std::shared_ptr& page, + unsigned int& index, + uint256& entry) +{ + auto const& svIndexes = page->getFieldV256(sfIndexes); + XRPL_ASSERT(index <= svIndexes.size(), "xrpl::detail::internalDirNext : index inside range"); + + if (index >= svIndexes.size()) + { + auto const next = page->getFieldU64(sfIndexNext); + + if (!next) + { + entry.zero(); + return false; + } + + if constexpr (std::is_const_v) + { + page = view.read(keylet::page(root, next)); + } + else + { + page = view.peek(keylet::page(root, next)); + } + + XRPL_ASSERT(page, "xrpl::detail::internalDirNext : non-null root"); + + if (!page) + return false; + + index = 0; + + return internalDirNext(view, root, page, index, entry); + } + + entry = svIndexes[index++]; + return true; +} + +template < + class V, + class N, + class = std::enable_if_t< + std::is_same_v, SLE> && std::is_base_of_v>> +bool +internalDirFirst( + V& view, + uint256 const& root, + std::shared_ptr& page, + unsigned int& index, + uint256& entry) +{ + if constexpr (std::is_const_v) + { + page = view.read(keylet::page(root)); + } + else + { + page = view.peek(keylet::page(root)); + } + + if (!page) + return false; + + index = 0; + + return internalDirNext(view, root, page, index, entry); +} + +} // namespace detail + +/** @{ */ +/** Returns the first entry in the directory, advancing the index + + @deprecated These are legacy function that are considered deprecated + and will soon be replaced with an iterator-based model + that is easier to use. You should not use them in new code. + + @param view The view against which to operate + @param root The root (i.e. first page) of the directory to iterate + @param page The current page + @param index The index inside the current page + @param entry The entry at the current index + + @return true if the directory isn't empty; false otherwise + */ +bool +cdirFirst( + ReadView const& view, + uint256 const& root, + std::shared_ptr& page, + unsigned int& index, + uint256& entry); + +bool +dirFirst( + ApplyView& view, + uint256 const& root, + std::shared_ptr& page, + unsigned int& index, + uint256& entry); +/** @} */ + +/** @{ */ +/** Returns the next entry in the directory, advancing the index + + @deprecated These are legacy function that are considered deprecated + and will soon be replaced with an iterator-based model + that is easier to use. You should not use them in new code. + + @param view The view against which to operate + @param root The root (i.e. first page) of the directory to iterate + @param page The current page + @param index The index inside the current page + @param entry The entry at the current index + + @return true if the directory isn't empty; false otherwise + */ +bool +cdirNext( + ReadView const& view, + uint256 const& root, + std::shared_ptr& page, + unsigned int& index, + uint256& entry); + +bool +dirNext( + ApplyView& view, + uint256 const& root, + std::shared_ptr& page, + unsigned int& index, + uint256& entry); +/** @} */ + +/** Iterate all items in the given directory. */ +void +forEachItem( + ReadView const& view, + Keylet const& root, + std::function const&)> const& f); + +/** Iterate all items after an item in the given directory. + @param after The key of the item to start after + @param hint The directory page containing `after` + @param limit The maximum number of items to return + @return `false` if the iteration failed +*/ +bool +forEachItemAfter( + ReadView const& view, + Keylet const& root, + uint256 const& after, + std::uint64_t const hint, + unsigned int limit, + std::function const&)> const& f); + +/** Iterate all items in an account's owner directory. */ +inline void +forEachItem( + ReadView const& view, + AccountID const& id, + std::function const&)> const& f) +{ + return forEachItem(view, keylet::ownerDir(id), f); +} + +/** Iterate all items after an item in an owner directory. + @param after The key of the item to start after + @param hint The directory page containing `after` + @param limit The maximum number of items to return + @return `false` if the iteration failed +*/ +inline bool +forEachItemAfter( + ReadView const& view, + AccountID const& id, + uint256 const& after, + std::uint64_t const hint, + unsigned int limit, + std::function const&)> const& f) +{ + return forEachItemAfter(view, keylet::ownerDir(id), after, hint, limit, f); +} + +/** Returns `true` if the directory is empty + @param key The key of the directory +*/ +[[nodiscard]] bool +dirIsEmpty(ReadView const& view, Keylet const& k); + +/** Returns a function that sets the owner on a directory SLE */ +[[nodiscard]] std::function +describeOwnerDir(AccountID const& account); + +} // namespace xrpl diff --git a/include/xrpl/ledger/helpers/MPTokenHelpers.h b/include/xrpl/ledger/helpers/MPTokenHelpers.h new file mode 100644 index 0000000000..ab487280b9 --- /dev/null +++ b/include/xrpl/ledger/helpers/MPTokenHelpers.h @@ -0,0 +1,160 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace xrpl { + +//------------------------------------------------------------------------------ +// +// Freeze checking (MPT-specific) +// +//------------------------------------------------------------------------------ + +[[nodiscard]] bool +isGlobalFrozen(ReadView const& view, MPTIssue const& mptIssue); + +[[nodiscard]] bool +isIndividualFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue); + +[[nodiscard]] bool +isFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue, int depth = 0); + +[[nodiscard]] bool +isAnyFrozen( + ReadView const& view, + std::initializer_list const& accounts, + MPTIssue const& mptIssue, + int depth = 0); + +//------------------------------------------------------------------------------ +// +// Transfer rate (MPT-specific) +// +//------------------------------------------------------------------------------ + +/** Returns MPT transfer fee as Rate. Rate specifies + * the fee as fractions of 1 billion. For example, 1% transfer rate + * is represented as 1,010,000,000. + * @param issuanceID MPTokenIssuanceID of MPTTokenIssuance object + */ +[[nodiscard]] Rate +transferRate(ReadView const& view, MPTID const& issuanceID); + +//------------------------------------------------------------------------------ +// +// Holding checks (MPT-specific) +// +//------------------------------------------------------------------------------ + +[[nodiscard]] TER +canAddHolding(ReadView const& view, MPTIssue const& mptIssue); + +//------------------------------------------------------------------------------ +// +// Authorization (MPT-specific) +// +//------------------------------------------------------------------------------ + +[[nodiscard]] TER +authorizeMPToken( + ApplyView& view, + XRPAmount const& priorBalance, + MPTID const& mptIssuanceID, + AccountID const& account, + beast::Journal journal, + std::uint32_t flags = 0, + std::optional holderID = std::nullopt); + +/** Check if the account lacks required authorization for MPT. + * + * requireAuth check is recursive for MPT shares in a vault, descending to + * assets in the vault, up to maxAssetCheckDepth recursion depth. This is + * purely defensive, as we currently do not allow such vaults to be created. + */ +[[nodiscard]] TER +requireAuth( + ReadView const& view, + MPTIssue const& mptIssue, + AccountID const& account, + AuthType authType = AuthType::Legacy, + int depth = 0); + +/** Enforce account has MPToken to match its authorization. + * + * Called from doApply - it will check for expired (and delete if found any) + * credentials matching DomainID set in MPTokenIssuance. Must be called if + * requireAuth(...MPTIssue...) returned tesSUCCESS or tecEXPIRED in preclaim. + */ +[[nodiscard]] TER +enforceMPTokenAuthorization( + ApplyView& view, + MPTID const& mptIssuanceID, + AccountID const& account, + XRPAmount const& priorBalance, + beast::Journal j); + +/** Check if the destination account is allowed + * to receive MPT. Return tecNO_AUTH if it doesn't + * and tesSUCCESS otherwise. + */ +[[nodiscard]] TER +canTransfer( + ReadView const& view, + MPTIssue const& mptIssue, + AccountID const& from, + AccountID const& to); + +//------------------------------------------------------------------------------ +// +// Empty holding operations (MPT-specific) +// +//------------------------------------------------------------------------------ + +[[nodiscard]] TER +addEmptyHolding( + ApplyView& view, + AccountID const& accountID, + XRPAmount priorBalance, + MPTIssue const& mptIssue, + beast::Journal journal); + +[[nodiscard]] TER +removeEmptyHolding( + ApplyView& view, + AccountID const& accountID, + MPTIssue const& mptIssue, + beast::Journal journal); + +//------------------------------------------------------------------------------ +// +// Escrow operations (MPT-specific) +// +//------------------------------------------------------------------------------ + +TER +rippleLockEscrowMPT( + ApplyView& view, + AccountID const& uGrantorID, + STAmount const& saAmount, + beast::Journal j); + +TER +rippleUnlockEscrowMPT( + ApplyView& view, + AccountID const& uGrantorID, + AccountID const& uGranteeID, + STAmount const& netAmount, + STAmount const& grossAmount, + beast::Journal j); + +} // namespace xrpl diff --git a/include/xrpl/ledger/helpers/OfferHelpers.h b/include/xrpl/ledger/helpers/OfferHelpers.h new file mode 100644 index 0000000000..9096071811 --- /dev/null +++ b/include/xrpl/ledger/helpers/OfferHelpers.h @@ -0,0 +1,28 @@ +#pragma once + +#include +#include +#include +#include + +#include + +namespace xrpl { + +/** Delete an offer. + + Requirements: + The offer must exist. + The caller must have already checked permissions. + + @param view The ApplyView to modify. + @param sle The offer to delete. + @param j Journal for logging. + + @return tesSUCCESS on success, otherwise an error code. +*/ +// [[nodiscard]] // nodiscard commented out so Flow, BookTip and others compile. +TER +offerDelete(ApplyView& view, std::shared_ptr const& sle, beast::Journal j); + +} // namespace xrpl diff --git a/include/xrpl/ledger/helpers/RippleStateHelpers.h b/include/xrpl/ledger/helpers/RippleStateHelpers.h new file mode 100644 index 0000000000..3feba59d1f --- /dev/null +++ b/include/xrpl/ledger/helpers/RippleStateHelpers.h @@ -0,0 +1,255 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +//------------------------------------------------------------------------------ +// +// RippleState (Trustline) helpers +// +//------------------------------------------------------------------------------ + +namespace xrpl { + +//------------------------------------------------------------------------------ +// +// Credit functions (from Credit.h) +// +//------------------------------------------------------------------------------ + +/** Calculate the maximum amount of IOUs that an account can hold + @param view the ledger to check against. + @param account the account of interest. + @param issuer the issuer of the IOU. + @param currency the IOU to check. + @return The maximum amount that can be held. +*/ +/** @{ */ +STAmount +creditLimit( + ReadView const& view, + AccountID const& account, + AccountID const& issuer, + Currency const& currency); + +IOUAmount +creditLimit2(ReadView const& v, AccountID const& acc, AccountID const& iss, Currency const& cur); +/** @} */ + +/** Returns the amount of IOUs issued by issuer that are held by an account + @param view the ledger to check against. + @param account the account of interest. + @param issuer the issuer of the IOU. + @param currency the IOU to check. +*/ +/** @{ */ +STAmount +creditBalance( + ReadView const& view, + AccountID const& account, + AccountID const& issuer, + Currency const& currency); +/** @} */ + +//------------------------------------------------------------------------------ +// +// Freeze checking (IOU-specific) +// +//------------------------------------------------------------------------------ + +[[nodiscard]] bool +isIndividualFrozen( + ReadView const& view, + AccountID const& account, + Currency const& currency, + AccountID const& issuer); + +[[nodiscard]] inline bool +isIndividualFrozen(ReadView const& view, AccountID const& account, Issue const& issue) +{ + return isIndividualFrozen(view, account, issue.currency, issue.account); +} + +[[nodiscard]] bool +isFrozen( + ReadView const& view, + AccountID const& account, + Currency const& currency, + AccountID const& issuer); + +[[nodiscard]] inline bool +isFrozen(ReadView const& view, AccountID const& account, Issue const& issue) +{ + return isFrozen(view, account, issue.currency, issue.account); +} + +// Overload with depth parameter for uniformity with MPTIssue version. +// The depth parameter is ignored for IOUs since they don't have vault recursion. +[[nodiscard]] inline bool +isFrozen(ReadView const& view, AccountID const& account, Issue const& issue, int /*depth*/) +{ + return isFrozen(view, account, issue); +} + +[[nodiscard]] bool +isDeepFrozen( + ReadView const& view, + AccountID const& account, + Currency const& currency, + AccountID const& issuer); + +[[nodiscard]] inline bool +isDeepFrozen( + ReadView const& view, + AccountID const& account, + Issue const& issue, + int = 0 /*ignored*/) +{ + return isDeepFrozen(view, account, issue.currency, issue.account); +} + +[[nodiscard]] inline TER +checkDeepFrozen(ReadView const& view, AccountID const& account, Issue const& issue) +{ + return isDeepFrozen(view, account, issue) ? (TER)tecFROZEN : (TER)tesSUCCESS; +} + +//------------------------------------------------------------------------------ +// +// Trust line operations +// +//------------------------------------------------------------------------------ + +/** Create a trust line + + This can set an initial balance. +*/ +[[nodiscard]] TER +trustCreate( + ApplyView& view, + bool const bSrcHigh, + AccountID const& uSrcAccountID, + AccountID const& uDstAccountID, + uint256 const& uIndex, // --> ripple state entry + SLE::ref sleAccount, // --> the account being set. + bool const bAuth, // --> authorize account. + bool const bNoRipple, // --> others cannot ripple through + bool const bFreeze, // --> funds cannot leave + bool bDeepFreeze, // --> can neither receive nor send funds + STAmount const& saBalance, // --> balance of account being set. + // Issuer should be noAccount() + STAmount const& saLimit, // --> limit for account being set. + // Issuer should be the account being set. + std::uint32_t uQualityIn, + std::uint32_t uQualityOut, + beast::Journal j); + +[[nodiscard]] TER +trustDelete( + ApplyView& view, + std::shared_ptr const& sleRippleState, + AccountID const& uLowAccountID, + AccountID const& uHighAccountID, + beast::Journal j); + +//------------------------------------------------------------------------------ +// +// IOU issuance/redemption +// +//------------------------------------------------------------------------------ + +[[nodiscard]] TER +issueIOU( + ApplyView& view, + AccountID const& account, + STAmount const& amount, + Issue const& issue, + beast::Journal j); + +[[nodiscard]] TER +redeemIOU( + ApplyView& view, + AccountID const& account, + STAmount const& amount, + Issue const& issue, + beast::Journal j); + +//------------------------------------------------------------------------------ +// +// Authorization and transfer checks (IOU-specific) +// +//------------------------------------------------------------------------------ + +/** Check if the account lacks required authorization. + * + * Return tecNO_AUTH or tecNO_LINE if it does + * and tesSUCCESS otherwise. + * + * If StrongAuth then return tecNO_LINE if the RippleState doesn't exist. Return + * tecNO_AUTH if lsfRequireAuth is set on the issuer's AccountRoot, and the + * RippleState does exist, and the RippleState is not authorized. + * + * If WeakAuth then return tecNO_AUTH if lsfRequireAuth is set, and the + * RippleState exists, and is not authorized. Return tecNO_LINE if + * lsfRequireAuth is set and the RippleState doesn't exist. Consequently, if + * WeakAuth and lsfRequireAuth is *not* set, this function will return + * tesSUCCESS even if RippleState does *not* exist. + * + * The default "Legacy" auth type is equivalent to WeakAuth. + */ +[[nodiscard]] TER +requireAuth( + ReadView const& view, + Issue const& issue, + AccountID const& account, + AuthType authType = AuthType::Legacy); + +/** Check if the destination account is allowed + * to receive IOU. Return terNO_RIPPLE if rippling is + * disabled on both sides and tesSUCCESS otherwise. + */ +[[nodiscard]] TER +canTransfer(ReadView const& view, Issue const& issue, AccountID const& from, AccountID const& to); + +//------------------------------------------------------------------------------ +// +// Empty holding operations (IOU-specific) +// +//------------------------------------------------------------------------------ + +/// Any transactors that call addEmptyHolding() in doApply must call +/// canAddHolding() in preflight with the same View and Asset +[[nodiscard]] TER +addEmptyHolding( + ApplyView& view, + AccountID const& accountID, + XRPAmount priorBalance, + Issue const& issue, + beast::Journal journal); + +[[nodiscard]] TER +removeEmptyHolding( + ApplyView& view, + AccountID const& accountID, + Issue const& issue, + beast::Journal journal); + +/** Delete trustline to AMM. The passed `sle` must be obtained from a prior + * call to view.peek(). Fail if neither side of the trustline is AMM or + * if ammAccountID is seated and is not one of the trustline's side. + */ +[[nodiscard]] TER +deleteAMMTrustLine( + ApplyView& view, + std::shared_ptr sleState, + std::optional const& ammAccountID, + beast::Journal j); + +} // namespace xrpl diff --git a/include/xrpl/ledger/helpers/TokenHelpers.h b/include/xrpl/ledger/helpers/TokenHelpers.h new file mode 100644 index 0000000000..74d1e4848e --- /dev/null +++ b/include/xrpl/ledger/helpers/TokenHelpers.h @@ -0,0 +1,286 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace xrpl { + +//------------------------------------------------------------------------------ +// +// Enums for token handling +// +//------------------------------------------------------------------------------ + +/** Controls the treatment of frozen account balances */ +enum FreezeHandling { fhIGNORE_FREEZE, fhZERO_IF_FROZEN }; + +/** Controls the treatment of unauthorized MPT balances */ +enum AuthHandling { ahIGNORE_AUTH, ahZERO_IF_UNAUTHORIZED }; + +/** Controls whether to include the account's full spendable balance */ +enum SpendableHandling { shSIMPLE_BALANCE, shFULL_BALANCE }; + +enum class WaiveTransferFee : bool { No = false, Yes }; + +/* Check if MPToken (for MPT) or trust line (for IOU) exists: + * - StrongAuth - before checking if authorization is required + * - WeakAuth + * for MPT - after checking lsfMPTRequireAuth flag + * for IOU - do not check if trust line exists + * - Legacy + * for MPT - before checking lsfMPTRequireAuth flag i.e. same as StrongAuth + * for IOU - do not check if trust line exists i.e. same as WeakAuth + */ +enum class AuthType { StrongAuth, WeakAuth, Legacy }; + +//------------------------------------------------------------------------------ +// +// Freeze checking (Asset-based dispatchers) +// +//------------------------------------------------------------------------------ + +[[nodiscard]] bool +isGlobalFrozen(ReadView const& view, Asset const& asset); + +[[nodiscard]] bool +isIndividualFrozen(ReadView const& view, AccountID const& account, Asset const& asset); + +/** + * isFrozen check is recursive for MPT shares in a vault, descending to + * assets in the vault, up to maxAssetCheckDepth recursion depth. This is + * purely defensive, as we currently do not allow such vaults to be created. + */ +[[nodiscard]] bool +isFrozen(ReadView const& view, AccountID const& account, Asset const& asset, int depth = 0); + +[[nodiscard]] TER +checkFrozen(ReadView const& view, AccountID const& account, Issue const& issue); + +[[nodiscard]] TER +checkFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue); + +[[nodiscard]] TER +checkFrozen(ReadView const& view, AccountID const& account, Asset const& asset); + +[[nodiscard]] bool +isAnyFrozen( + ReadView const& view, + std::initializer_list const& accounts, + Issue const& issue); + +[[nodiscard]] bool +isAnyFrozen( + ReadView const& view, + std::initializer_list const& accounts, + Asset const& asset, + int depth = 0); + +[[nodiscard]] bool +isDeepFrozen( + ReadView const& view, + AccountID const& account, + MPTIssue const& mptIssue, + int depth = 0); + +/** + * isFrozen check is recursive for MPT shares in a vault, descending to + * assets in the vault, up to maxAssetCheckDepth recursion depth. This is + * purely defensive, as we currently do not allow such vaults to be created. + */ +[[nodiscard]] bool +isDeepFrozen(ReadView const& view, AccountID const& account, Asset const& asset, int depth = 0); + +[[nodiscard]] TER +checkDeepFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue); + +[[nodiscard]] TER +checkDeepFrozen(ReadView const& view, AccountID const& account, Asset const& asset); + +//------------------------------------------------------------------------------ +// +// Account balance functions (Asset-based dispatchers) +// +//------------------------------------------------------------------------------ + +// Returns the amount an account can spend. +// +// If shSIMPLE_BALANCE is specified, this is the amount the account can spend +// without going into debt. +// +// If shFULL_BALANCE is specified, this is the amount the account can spend +// total. Specifically: +// * The account can go into debt if using a trust line, and the other side has +// a non-zero limit. +// * If the account is the asset issuer the limit is defined by the asset / +// issuance. +// +// <-- saAmount: amount of currency held by account. May be negative. +[[nodiscard]] STAmount +accountHolds( + ReadView const& view, + AccountID const& account, + Currency const& currency, + AccountID const& issuer, + FreezeHandling zeroIfFrozen, + beast::Journal j, + SpendableHandling includeFullBalance = shSIMPLE_BALANCE); + +[[nodiscard]] STAmount +accountHolds( + ReadView const& view, + AccountID const& account, + Issue const& issue, + FreezeHandling zeroIfFrozen, + beast::Journal j, + SpendableHandling includeFullBalance = shSIMPLE_BALANCE); + +[[nodiscard]] STAmount +accountHolds( + ReadView const& view, + AccountID const& account, + MPTIssue const& mptIssue, + FreezeHandling zeroIfFrozen, + AuthHandling zeroIfUnauthorized, + beast::Journal j, + SpendableHandling includeFullBalance = shSIMPLE_BALANCE); + +[[nodiscard]] STAmount +accountHolds( + ReadView const& view, + AccountID const& account, + Asset const& asset, + FreezeHandling zeroIfFrozen, + AuthHandling zeroIfUnauthorized, + beast::Journal j, + SpendableHandling includeFullBalance = shSIMPLE_BALANCE); + +// Returns the amount an account can spend of the currency type saDefault, or +// returns saDefault if this account is the issuer of the currency in +// question. Should be used in favor of accountHolds when questioning how much +// an account can spend while also allowing currency issuers to spend +// unlimited amounts of their own currency (since they can always issue more). +[[nodiscard]] STAmount +accountFunds( + ReadView const& view, + AccountID const& id, + STAmount const& saDefault, + FreezeHandling freezeHandling, + beast::Journal j); + +/** Returns the transfer fee as Rate based on the type of token + * @param view The ledger view + * @param amount The amount to transfer + */ +[[nodiscard]] Rate +transferRate(ReadView const& view, STAmount const& amount); + +//------------------------------------------------------------------------------ +// +// Holding operations (Asset-based dispatchers) +// +//------------------------------------------------------------------------------ + +[[nodiscard]] TER +canAddHolding(ReadView const& view, Asset const& asset); + +[[nodiscard]] TER +addEmptyHolding( + ApplyView& view, + AccountID const& accountID, + XRPAmount priorBalance, + Asset const& asset, + beast::Journal journal); + +[[nodiscard]] TER +removeEmptyHolding( + ApplyView& view, + AccountID const& accountID, + Asset const& asset, + beast::Journal journal); + +//------------------------------------------------------------------------------ +// +// Authorization and transfer checks (Asset-based dispatchers) +// +//------------------------------------------------------------------------------ + +[[nodiscard]] TER +requireAuth( + ReadView const& view, + Asset const& asset, + AccountID const& account, + AuthType authType = AuthType::Legacy); + +[[nodiscard]] TER +canTransfer(ReadView const& view, Asset const& asset, AccountID const& from, AccountID const& to); + +//------------------------------------------------------------------------------ +// +// Money Transfers (Asset-based dispatchers) +// +//------------------------------------------------------------------------------ + +// Direct send w/o fees: +// - Redeeming IOUs and/or sending sender's own IOUs. +// - Create trust line of needed. +// --> bCheckIssuer : normally require issuer to be involved. +// [[nodiscard]] // nodiscard commented out so DirectStep.cpp compiles. + +/** Calls static rippleCreditIOU if saAmount represents Issue. + * Calls static rippleCreditMPT if saAmount represents MPTIssue. + */ +TER +rippleCredit( + ApplyView& view, + AccountID const& uSenderID, + AccountID const& uReceiverID, + STAmount const& saAmount, + bool bCheckIssuer, + beast::Journal j); + +/** Calls static accountSendIOU if saAmount represents Issue. + * Calls static accountSendMPT if saAmount represents MPTIssue. + */ +[[nodiscard]] TER +accountSend( + ApplyView& view, + AccountID const& from, + AccountID const& to, + STAmount const& saAmount, + beast::Journal j, + WaiveTransferFee waiveFee = WaiveTransferFee::No); + +using MultiplePaymentDestinations = std::vector>; +/** Like accountSend, except one account is sending multiple payments (with the + * same asset!) simultaneously + * + * Calls static accountSendMultiIOU if saAmount represents Issue. + * Calls static accountSendMultiMPT if saAmount represents MPTIssue. + */ +[[nodiscard]] TER +accountSendMulti( + ApplyView& view, + AccountID const& senderID, + Asset const& asset, + MultiplePaymentDestinations const& receivers, + beast::Journal j, + WaiveTransferFee waiveFee = WaiveTransferFee::No); + +[[nodiscard]] TER +transferXRP( + ApplyView& view, + AccountID const& from, + AccountID const& to, + STAmount const& amount, + beast::Journal j); + +} // namespace xrpl diff --git a/include/xrpl/ledger/helpers/VaultHelpers.h b/include/xrpl/ledger/helpers/VaultHelpers.h new file mode 100644 index 0000000000..8aef30aa27 --- /dev/null +++ b/include/xrpl/ledger/helpers/VaultHelpers.h @@ -0,0 +1,81 @@ +#pragma once + +#include +#include + +#include +#include + +namespace xrpl { + +/** From the perspective of a vault, return the number of shares to give + depositor when they offer a fixed amount of assets. Note, since shares are + MPT, this number is integral and always truncated in this calculation. + + @param vault The vault SLE. + @param issuance The MPTokenIssuance SLE for the vault's shares. + @param assets The amount of assets to convert. + + @return The number of shares, or nullopt on error. +*/ +[[nodiscard]] std::optional +assetsToSharesDeposit( + std::shared_ptr const& vault, + std::shared_ptr const& issuance, + STAmount const& assets); + +/** From the perspective of a vault, return the number of assets to take from + depositor when they receive a fixed amount of shares. Note, since shares are + MPT, they are always an integral number. + + @param vault The vault SLE. + @param issuance The MPTokenIssuance SLE for the vault's shares. + @param shares The amount of shares to convert. + + @return The number of assets, or nullopt on error. +*/ +[[nodiscard]] std::optional +sharesToAssetsDeposit( + std::shared_ptr const& vault, + std::shared_ptr const& issuance, + STAmount const& shares); + +/** Controls whether to truncate shares instead of rounding. */ +enum class TruncateShares : bool { no = false, yes = true }; + +/** From the perspective of a vault, return the number of shares to demand from + the depositor when they ask to withdraw a fixed amount of assets. Since + shares are MPT this number is integral, and it will be rounded to nearest + unless explicitly requested to be truncated instead. + + @param vault The vault SLE. + @param issuance The MPTokenIssuance SLE for the vault's shares. + @param assets The amount of assets to convert. + @param truncate Whether to truncate instead of rounding. + + @return The number of shares, or nullopt on error. +*/ +[[nodiscard]] std::optional +assetsToSharesWithdraw( + std::shared_ptr const& vault, + std::shared_ptr const& issuance, + STAmount const& assets, + TruncateShares truncate = TruncateShares::no); + +/** From the perspective of a vault, return the number of assets to give the + depositor when they redeem a fixed amount of shares. Note, since shares are + MPT, they are always an integral number. + + @param vault The vault SLE. + @param issuance The MPTokenIssuance SLE for the vault's shares. + @param shares The amount of shares to convert. + + @return The number of assets, or nullopt on error. +*/ +[[nodiscard]] std::optional +sharesToAssetsWithdraw( + std::shared_ptr const& vault, + std::shared_ptr const& issuance, + STAmount const& shares); + +} // namespace xrpl diff --git a/include/xrpl/tx/paths/detail/StrandFlow.h b/include/xrpl/tx/paths/detail/StrandFlow.h index 67e333f2e6..f99f54d0e8 100644 --- a/include/xrpl/tx/paths/detail/StrandFlow.h +++ b/include/xrpl/tx/paths/detail/StrandFlow.h @@ -1,7 +1,8 @@ #pragma once #include -#include +#include +#include #include #include #include diff --git a/src/libxrpl/ledger/Credit.cpp b/src/libxrpl/ledger/Credit.cpp deleted file mode 100644 index 0a0283c3b8..0000000000 --- a/src/libxrpl/ledger/Credit.cpp +++ /dev/null @@ -1,60 +0,0 @@ -#include -#include -#include -#include - -namespace xrpl { - -STAmount -creditLimit( - ReadView const& view, - AccountID const& account, - AccountID const& issuer, - Currency const& currency) -{ - STAmount result(Issue{currency, account}); - - auto sleRippleState = view.read(keylet::line(account, issuer, currency)); - - if (sleRippleState) - { - result = sleRippleState->getFieldAmount(account < issuer ? sfLowLimit : sfHighLimit); - result.setIssuer(account); - } - - XRPL_ASSERT(result.getIssuer() == account, "xrpl::creditLimit : result issuer match"); - XRPL_ASSERT(result.getCurrency() == currency, "xrpl::creditLimit : result currency match"); - return result; -} - -IOUAmount -creditLimit2(ReadView const& v, AccountID const& acc, AccountID const& iss, Currency const& cur) -{ - return toAmount(creditLimit(v, acc, iss, cur)); -} - -STAmount -creditBalance( - ReadView const& view, - AccountID const& account, - AccountID const& issuer, - Currency const& currency) -{ - STAmount result(Issue{currency, account}); - - auto sleRippleState = view.read(keylet::line(account, issuer, currency)); - - if (sleRippleState) - { - result = sleRippleState->getFieldAmount(sfBalance); - if (account < issuer) - result.negate(); - result.setIssuer(account); - } - - XRPL_ASSERT(result.getIssuer() == account, "xrpl::creditBalance : result issuer match"); - XRPL_ASSERT(result.getCurrency() == currency, "xrpl::creditBalance : result currency match"); - return result; -} - -} // namespace xrpl diff --git a/src/libxrpl/ledger/View.cpp b/src/libxrpl/ledger/View.cpp index d5c94a9981..f51fb97993 100644 --- a/src/libxrpl/ledger/View.cpp +++ b/src/libxrpl/ledger/View.cpp @@ -2,10 +2,9 @@ #include #include #include -#include -#include #include #include +#include #include #include #include @@ -22,133 +21,6 @@ namespace xrpl { -namespace detail { - -template < - class V, - class N, - class = std::enable_if_t< - std::is_same_v, SLE> && std::is_base_of_v>> -bool -internalDirNext( - V& view, - uint256 const& root, - std::shared_ptr& page, - unsigned int& index, - uint256& entry) -{ - auto const& svIndexes = page->getFieldV256(sfIndexes); - XRPL_ASSERT(index <= svIndexes.size(), "xrpl::detail::internalDirNext : index inside range"); - - if (index >= svIndexes.size()) - { - auto const next = page->getFieldU64(sfIndexNext); - - if (!next) - { - entry.zero(); - return false; - } - - if constexpr (std::is_const_v) - { - page = view.read(keylet::page(root, next)); - } - else - { - page = view.peek(keylet::page(root, next)); - } - - XRPL_ASSERT(page, "xrpl::detail::internalDirNext : non-null root"); - - if (!page) - return false; - - index = 0; - - return internalDirNext(view, root, page, index, entry); - } - - entry = svIndexes[index++]; - return true; -} - -template < - class V, - class N, - class = std::enable_if_t< - std::is_same_v, SLE> && std::is_base_of_v>> -bool -internalDirFirst( - V& view, - uint256 const& root, - std::shared_ptr& page, - unsigned int& index, - uint256& entry) -{ - if constexpr (std::is_const_v) - { - page = view.read(keylet::page(root)); - } - else - { - page = view.peek(keylet::page(root)); - } - - if (!page) - return false; - - index = 0; - - return internalDirNext(view, root, page, index, entry); -} - -} // namespace detail - -bool -dirFirst( - ApplyView& view, - uint256 const& root, - std::shared_ptr& page, - unsigned int& index, - uint256& entry) -{ - return detail::internalDirFirst(view, root, page, index, entry); -} - -bool -dirNext( - ApplyView& view, - uint256 const& root, - std::shared_ptr& page, - unsigned int& index, - uint256& entry) -{ - return detail::internalDirNext(view, root, page, index, entry); -} - -bool -cdirFirst( - ReadView const& view, - uint256 const& root, - std::shared_ptr& page, - unsigned int& index, - uint256& entry) -{ - return detail::internalDirFirst(view, root, page, index, entry); -} - -bool -cdirNext( - ReadView const& view, - uint256 const& root, - std::shared_ptr& page, - unsigned int& index, - uint256& entry) -{ - return detail::internalDirNext(view, root, page, index, entry); -} - //------------------------------------------------------------------------------ // // Observers @@ -164,124 +36,6 @@ hasExpired(ReadView const& view, std::optional const& exp) return exp && (view.parentCloseTime() >= tp{d{*exp}}); } -bool -isGlobalFrozen(ReadView const& view, AccountID const& issuer) -{ - if (isXRP(issuer)) - return false; - if (auto const sle = view.read(keylet::account(issuer))) - return sle->isFlag(lsfGlobalFreeze); - return false; -} - -bool -isGlobalFrozen(ReadView const& view, MPTIssue const& mptIssue) -{ - if (auto const sle = view.read(keylet::mptIssuance(mptIssue.getMptID()))) - return sle->isFlag(lsfMPTLocked); - return false; -} - -bool -isGlobalFrozen(ReadView const& view, Asset const& asset) -{ - return std::visit( - [&](TIss const& issue) { - if constexpr (std::is_same_v) - { - return isGlobalFrozen(view, issue.getIssuer()); - } - else - { - return isGlobalFrozen(view, issue); - } - }, - asset.value()); -} - -bool -isIndividualFrozen( - ReadView const& view, - AccountID const& account, - Currency const& currency, - AccountID const& issuer) -{ - if (isXRP(currency)) - return false; - if (issuer != account) - { - // Check if the issuer froze the line - auto const sle = view.read(keylet::line(account, issuer, currency)); - if (sle && sle->isFlag((issuer > account) ? lsfHighFreeze : lsfLowFreeze)) - return true; - } - return false; -} - -bool -isIndividualFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue) -{ - if (auto const sle = view.read(keylet::mptoken(mptIssue.getMptID(), account))) - return sle->isFlag(lsfMPTLocked); - return false; -} - -// Can the specified account spend the specified currency issued by -// the specified issuer or does the freeze flag prohibit it? -bool -isFrozen( - ReadView const& view, - AccountID const& account, - Currency const& currency, - AccountID const& issuer) -{ - if (isXRP(currency)) - return false; - auto sle = view.read(keylet::account(issuer)); - if (sle && sle->isFlag(lsfGlobalFreeze)) - return true; - if (issuer != account) - { - // Check if the issuer froze the line - sle = view.read(keylet::line(account, issuer, currency)); - if (sle && sle->isFlag((issuer > account) ? lsfHighFreeze : lsfLowFreeze)) - return true; - } - return false; -} - -bool -isFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue, int depth) -{ - return isGlobalFrozen(view, mptIssue) || isIndividualFrozen(view, account, mptIssue) || - isVaultPseudoAccountFrozen(view, account, mptIssue, depth); -} - -[[nodiscard]] bool -isAnyFrozen( - ReadView const& view, - std::initializer_list const& accounts, - MPTIssue const& mptIssue, - int depth) -{ - if (isGlobalFrozen(view, mptIssue)) - return true; - - for (auto const& account : accounts) - { - if (isIndividualFrozen(view, account, mptIssue)) - return true; - } - - for (auto const& account : accounts) - { - if (isVaultPseudoAccountFrozen(view, account, mptIssue, depth)) - return true; - } - - return false; -} - bool isVaultPseudoAccountFrozen( ReadView const& view, @@ -323,32 +77,6 @@ isVaultPseudoAccountFrozen( return isAnyFrozen(view, {issuer, account}, vault->at(sfAsset), depth + 1); } -bool -isDeepFrozen( - ReadView const& view, - AccountID const& account, - Currency const& currency, - AccountID const& issuer) -{ - if (isXRP(currency)) - { - return false; - } - - if (issuer == account) - { - return false; - } - - auto const sle = view.read(keylet::line(account, issuer, currency)); - if (!sle) - { - return false; - } - - return sle->isFlag(lsfHighDeepFreeze) || sle->isFlag(lsfLowDeepFreeze); -} - bool isLPTokenFrozen( ReadView const& view, @@ -360,468 +88,6 @@ isLPTokenFrozen( isFrozen(view, account, asset2.currency, asset2.account); } -static SLE::const_pointer -getLineIfUsable( - ReadView const& view, - AccountID const& account, - Currency const& currency, - AccountID const& issuer, - FreezeHandling zeroIfFrozen, - beast::Journal j) -{ - auto const sle = view.read(keylet::line(account, issuer, currency)); - - if (!sle) - { - return nullptr; - } - - if (zeroIfFrozen == fhZERO_IF_FROZEN) - { - if (isFrozen(view, account, currency, issuer) || - isDeepFrozen(view, account, currency, issuer)) - { - return nullptr; - } - - // when fixFrozenLPTokenTransfer is enabled, if currency is lptoken, - // we need to check if the associated assets have been frozen - if (view.rules().enabled(fixFrozenLPTokenTransfer)) - { - auto const sleIssuer = view.read(keylet::account(issuer)); - if (!sleIssuer) - { - return nullptr; // LCOV_EXCL_LINE - } - if (sleIssuer->isFieldPresent(sfAMMID)) - { - auto const sleAmm = view.read(keylet::amm((*sleIssuer)[sfAMMID])); - - if (!sleAmm || - isLPTokenFrozen( - view, - account, - (*sleAmm)[sfAsset].get(), - (*sleAmm)[sfAsset2].get())) - { - return nullptr; - } - } - } - } - - return sle; -} - -static STAmount -getTrustLineBalance( - ReadView const& view, - SLE::const_ref sle, - AccountID const& account, - Currency const& currency, - AccountID const& issuer, - bool includeOppositeLimit, - beast::Journal j) -{ - STAmount amount; - if (sle) - { - amount = sle->getFieldAmount(sfBalance); - bool const accountHigh = account > issuer; - auto const& oppositeField = accountHigh ? sfLowLimit : sfHighLimit; - if (accountHigh) - { - // Put balance in account terms. - amount.negate(); - } - if (includeOppositeLimit) - { - amount += sle->getFieldAmount(oppositeField); - } - amount.setIssuer(issuer); - } - else - { - amount.clear(Issue{currency, issuer}); - } - - JLOG(j.trace()) << "getTrustLineBalance:" << " account=" << to_string(account) - << " amount=" << amount.getFullText(); - - return view.balanceHook(account, issuer, amount); -} - -STAmount -accountHolds( - ReadView const& view, - AccountID const& account, - Currency const& currency, - AccountID const& issuer, - FreezeHandling zeroIfFrozen, - beast::Journal j, - SpendableHandling includeFullBalance) -{ - STAmount amount; - if (isXRP(currency)) - { - return {xrpLiquid(view, account, 0, j)}; - } - - bool const returnSpendable = (includeFullBalance == shFULL_BALANCE); - if (returnSpendable && account == issuer) - { - // If the account is the issuer, then their limit is effectively - // infinite - return STAmount{Issue{currency, issuer}, STAmount::cMaxValue, STAmount::cMaxOffset}; - } - - // IOU: Return balance on trust line modulo freeze - SLE::const_pointer const sle = - getLineIfUsable(view, account, currency, issuer, zeroIfFrozen, j); - - return getTrustLineBalance(view, sle, account, currency, issuer, returnSpendable, j); -} - -STAmount -accountHolds( - ReadView const& view, - AccountID const& account, - Issue const& issue, - FreezeHandling zeroIfFrozen, - beast::Journal j, - SpendableHandling includeFullBalance) -{ - return accountHolds( - view, account, issue.currency, issue.account, zeroIfFrozen, j, includeFullBalance); -} - -STAmount -accountHolds( - ReadView const& view, - AccountID const& account, - MPTIssue const& mptIssue, - FreezeHandling zeroIfFrozen, - AuthHandling zeroIfUnauthorized, - beast::Journal j, - SpendableHandling includeFullBalance) -{ - bool const returnSpendable = (includeFullBalance == shFULL_BALANCE); - - if (returnSpendable && account == mptIssue.getIssuer()) - { - // if the account is the issuer, and the issuance exists, their limit is - // the issuance limit minus the outstanding value - auto const issuance = view.read(keylet::mptIssuance(mptIssue.getMptID())); - - if (!issuance) - { - return STAmount{mptIssue}; - } - return STAmount{ - mptIssue, - issuance->at(~sfMaximumAmount).value_or(maxMPTokenAmount) - - issuance->at(sfOutstandingAmount)}; - } - - STAmount amount; - - auto const sleMpt = view.read(keylet::mptoken(mptIssue.getMptID(), account)); - - if (!sleMpt) - { - amount.clear(mptIssue); - } - else if (zeroIfFrozen == fhZERO_IF_FROZEN && isFrozen(view, account, mptIssue)) - { - amount.clear(mptIssue); - } - else - { - amount = STAmount{mptIssue, sleMpt->getFieldU64(sfMPTAmount)}; - - // Only if auth check is needed, as it needs to do an additional read - // operation. Note featureSingleAssetVault will affect error codes. - if (zeroIfUnauthorized == ahZERO_IF_UNAUTHORIZED && - view.rules().enabled(featureSingleAssetVault)) - { - if (auto const err = requireAuth(view, mptIssue, account, AuthType::StrongAuth); - !isTesSuccess(err)) - amount.clear(mptIssue); - } - else if (zeroIfUnauthorized == ahZERO_IF_UNAUTHORIZED) - { - auto const sleIssuance = view.read(keylet::mptIssuance(mptIssue.getMptID())); - - // if auth is enabled on the issuance and mpt is not authorized, - // clear amount - if (sleIssuance && sleIssuance->isFlag(lsfMPTRequireAuth) && - !sleMpt->isFlag(lsfMPTAuthorized)) - amount.clear(mptIssue); - } - } - - return amount; -} - -[[nodiscard]] STAmount -accountHolds( - ReadView const& view, - AccountID const& account, - Asset const& asset, - FreezeHandling zeroIfFrozen, - AuthHandling zeroIfUnauthorized, - beast::Journal j, - SpendableHandling includeFullBalance) -{ - return std::visit( - [&](TIss const& value) { - if constexpr (std::is_same_v) - { - return accountHolds(view, account, value, zeroIfFrozen, j, includeFullBalance); - } - else if constexpr (std::is_same_v) - { - return accountHolds( - view, account, value, zeroIfFrozen, zeroIfUnauthorized, j, includeFullBalance); - } - }, - asset.value()); -} - -STAmount -accountFunds( - ReadView const& view, - AccountID const& id, - STAmount const& saDefault, - FreezeHandling freezeHandling, - beast::Journal j) -{ - if (!saDefault.native() && saDefault.getIssuer() == id) - return saDefault; - - return accountHolds( - view, id, saDefault.getCurrency(), saDefault.getIssuer(), freezeHandling, j); -} - -// Prevent ownerCount from wrapping under error conditions. -// -// adjustment allows the ownerCount to be adjusted up or down in multiple steps. -// If id != std::nullopt, then do error reporting. -// -// Returns adjusted owner count. -static std::uint32_t -confineOwnerCount( - std::uint32_t current, - std::int32_t adjustment, - std::optional const& id = std::nullopt, - beast::Journal j = beast::Journal{beast::Journal::getNullSink()}) -{ - std::uint32_t adjusted{current + adjustment}; - if (adjustment > 0) - { - // Overflow is well defined on unsigned - if (adjusted < current) - { - if (id) - { - JLOG(j.fatal()) << "Account " << *id << " owner count exceeds max!"; - } - adjusted = std::numeric_limits::max(); - } - } - else - { - // Underflow is well defined on unsigned - if (adjusted > current) - { - if (id) - { - JLOG(j.fatal()) << "Account " << *id << " owner count set below 0!"; - } - adjusted = 0; - XRPL_ASSERT(!id, "xrpl::confineOwnerCount : id is not set"); - } - } - return adjusted; -} - -XRPAmount -xrpLiquid(ReadView const& view, AccountID const& id, std::int32_t ownerCountAdj, beast::Journal j) -{ - auto const sle = view.read(keylet::account(id)); - if (sle == nullptr) - return beast::zero; - - // Return balance minus reserve - std::uint32_t const ownerCount = - confineOwnerCount(view.ownerCountHook(id, sle->getFieldU32(sfOwnerCount)), ownerCountAdj); - - // Pseudo-accounts have no reserve requirement - auto const reserve = - isPseudoAccount(sle) ? XRPAmount{0} : view.fees().accountReserve(ownerCount); - - auto const fullBalance = sle->getFieldAmount(sfBalance); - - auto const balance = view.balanceHook(id, xrpAccount(), fullBalance); - - STAmount const amount = (balance < reserve) ? STAmount{0} : balance - reserve; - - JLOG(j.trace()) << "accountHolds:" << " account=" << to_string(id) - << " amount=" << amount.getFullText() - << " fullBalance=" << fullBalance.getFullText() - << " balance=" << balance.getFullText() << " reserve=" << reserve - << " ownerCount=" << ownerCount << " ownerCountAdj=" << ownerCountAdj; - - return amount.xrp(); -} - -void -forEachItem( - ReadView const& view, - Keylet const& root, - std::function const&)> const& f) -{ - XRPL_ASSERT(root.type == ltDIR_NODE, "xrpl::forEachItem : valid root type"); - - if (root.type != ltDIR_NODE) - return; - - auto pos = root; - - while (true) - { - auto sle = view.read(pos); - if (!sle) - return; - for (auto const& key : sle->getFieldV256(sfIndexes)) - f(view.read(keylet::child(key))); - auto const next = sle->getFieldU64(sfIndexNext); - if (!next) - return; - pos = keylet::page(root, next); - } -} - -bool -forEachItemAfter( - ReadView const& view, - Keylet const& root, - uint256 const& after, - std::uint64_t const hint, - unsigned int limit, - std::function const&)> const& f) -{ - XRPL_ASSERT(root.type == ltDIR_NODE, "xrpl::forEachItemAfter : valid root type"); - - if (root.type != ltDIR_NODE) - return false; - - auto currentIndex = root; - - // If startAfter is not zero try jumping to that page using the hint - if (after.isNonZero()) - { - auto const hintIndex = keylet::page(root, hint); - - if (auto hintDir = view.read(hintIndex)) - { - for (auto const& key : hintDir->getFieldV256(sfIndexes)) - { - if (key == after) - { - // We found the hint, we can start here - currentIndex = hintIndex; - break; - } - } - } - - bool found = false; - for (;;) - { - auto const ownerDir = view.read(currentIndex); - if (!ownerDir) - return found; - for (auto const& key : ownerDir->getFieldV256(sfIndexes)) - { - if (!found) - { - if (key == after) - found = true; - } - else if (f(view.read(keylet::child(key))) && limit-- <= 1) - { - return found; - } - } - - auto const uNodeNext = ownerDir->getFieldU64(sfIndexNext); - if (uNodeNext == 0) - return found; - currentIndex = keylet::page(root, uNodeNext); - } - } - else - { - for (;;) - { - auto const ownerDir = view.read(currentIndex); - if (!ownerDir) - return true; - for (auto const& key : ownerDir->getFieldV256(sfIndexes)) - { - if (f(view.read(keylet::child(key))) && limit-- <= 1) - return true; - } - auto const uNodeNext = ownerDir->getFieldU64(sfIndexNext); - if (uNodeNext == 0) - return true; - currentIndex = keylet::page(root, uNodeNext); - } - } -} - -Rate -transferRate(ReadView const& view, AccountID const& issuer) -{ - auto const sle = view.read(keylet::account(issuer)); - - if (sle && sle->isFieldPresent(sfTransferRate)) - return Rate{sle->getFieldU32(sfTransferRate)}; - - return parityRate; -} - -Rate -transferRate(ReadView const& view, MPTID const& issuanceID) -{ - // fee is 0-50,000 (0-50%), rate is 1,000,000,000-2,000,000,000 - // For example, if transfer fee is 50% then 10,000 * 50,000 = 500,000 - // 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)}; - - return parityRate; -} - -Rate -transferRate(ReadView const& view, STAmount const& amount) -{ - return std::visit( - [&](TIss const& issue) { - if constexpr (std::is_same_v) - { - return transferRate(view, issue.getIssuer()); - } - else - { - return transferRate(view, issue.getMptID()); - } - }, - amount.asset().value()); -} - bool areCompatible( ReadView const& validLedger, @@ -920,20 +186,6 @@ areCompatible( return ret; } -bool -dirIsEmpty(ReadView const& view, Keylet const& k) -{ - auto const sleNode = view.read(k); - if (!sleNode) - return true; - if (!sleNode->getFieldV256(sfIndexes).empty()) - return false; - // The first page of a directory may legitimately be empty even if there - // are other pages (the first page is the anchor page) so check to see if - // there is another page. If there is, the directory isn't empty. - return sleNode->getFieldU64(sfIndexNext) == 0; -} - std::set getEnabledAmendments(ReadView const& view) { @@ -1037,30 +289,6 @@ hashOfSeq(ReadView const& ledger, LedgerIndex seq, beast::Journal journal) // //------------------------------------------------------------------------------ -void -adjustOwnerCount( - ApplyView& view, - std::shared_ptr const& sle, - std::int32_t amount, - beast::Journal j) -{ - if (!sle) - return; - XRPL_ASSERT(amount, "xrpl::adjustOwnerCount : nonzero amount input"); - std::uint32_t const current{sle->getFieldU32(sfOwnerCount)}; - AccountID const id = (*sle)[sfAccount]; - std::uint32_t const adjusted = confineOwnerCount(current, amount, id, j); - view.adjustOwnerCountHook(id, current, adjusted); - sle->at(sfOwnerCount) = adjusted; - view.update(sle); -} - -std::function -describeOwnerDir(AccountID const& account) -{ - return [account](std::shared_ptr const& sle) { (*sle)[sfOwner] = account; }; -} - TER dirLink( ApplyView& view, @@ -1076,168 +304,6 @@ dirLink( return tesSUCCESS; } -AccountID -pseudoAccountAddress(ReadView const& view, uint256 const& pseudoOwnerKey) -{ - // This number must not be changed without an amendment - constexpr std::uint16_t maxAccountAttempts = 256; - for (std::uint16_t i = 0; i < maxAccountAttempts; ++i) - { - ripesha_hasher rsh; - auto const hash = sha512Half(i, view.header().parentHash, pseudoOwnerKey); - rsh(hash.data(), hash.size()); - AccountID const ret{static_cast(rsh)}; - if (!view.read(keylet::account(ret))) - return ret; - } - return beast::zero; -} - -// Pseudo-account designator fields MUST be maintained by including the -// SField::sMD_PseudoAccount flag in the SField definition. (Don't forget to -// "| SField::sMD_Default"!) The fields do NOT need to be amendment-gated, -// since a non-active amendment will not set any field, by definition. -// Specific properties of a pseudo-account are NOT checked here, that's what -// InvariantCheck is for. -[[nodiscard]] std::vector const& -getPseudoAccountFields() -{ - static std::vector const pseudoFields = []() { - auto const ar = LedgerFormats::getInstance().findByType(ltACCOUNT_ROOT); - if (!ar) - { - // LCOV_EXCL_START - LogicError( - "xrpl::getPseudoAccountFields : unable to find account root " - "ledger format"); - // LCOV_EXCL_STOP - } - auto const& soTemplate = ar->getSOTemplate(); - - std::vector pseudoFields; - for (auto const& field : soTemplate) - { - if (field.sField().shouldMeta(SField::sMD_PseudoAccount)) - pseudoFields.emplace_back(&field.sField()); - } - return pseudoFields; - }(); - return pseudoFields; -} - -[[nodiscard]] bool -isPseudoAccount( - std::shared_ptr sleAcct, - std::set const& pseudoFieldFilter) -{ - auto const& fields = getPseudoAccountFields(); - - // Intentionally use defensive coding here because it's cheap and makes the - // semantics of true return value clean. - return sleAcct && sleAcct->getType() == ltACCOUNT_ROOT && - std::count_if( - fields.begin(), fields.end(), [&sleAcct, &pseudoFieldFilter](SField const* sf) -> bool { - return sleAcct->isFieldPresent(*sf) && - (pseudoFieldFilter.empty() || pseudoFieldFilter.contains(sf)); - }) > 0; -} - -Expected, TER> -createPseudoAccount(ApplyView& view, uint256 const& pseudoOwnerKey, SField const& ownerField) -{ - [[maybe_unused]] - auto const& fields = getPseudoAccountFields(); - XRPL_ASSERT( - std::count_if( - fields.begin(), - fields.end(), - [&ownerField](SField const* sf) -> bool { return *sf == ownerField; }) == 1, - "xrpl::createPseudoAccount : valid owner field"); - - auto const accountId = pseudoAccountAddress(view, pseudoOwnerKey); - if (accountId == beast::zero) - return Unexpected(tecDUPLICATE); - - // Create pseudo-account. - auto account = std::make_shared(keylet::account(accountId)); - account->setAccountID(sfAccount, accountId); - account->setFieldAmount(sfBalance, STAmount{}); - - // Pseudo-accounts can't submit transactions, so set the sequence number - // to 0 to make them easier to spot and verify, and add an extra level - // of protection. - std::uint32_t const seqno = // - view.rules().enabled(featureSingleAssetVault) || // - view.rules().enabled(featureLendingProtocol) // - ? 0 // - : view.seq(); - account->setFieldU32(sfSequence, seqno); - // Ignore reserves requirement, disable the master key, allow default - // rippling, and enable deposit authorization to prevent payments into - // pseudo-account. - account->setFieldU32(sfFlags, lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth); - // Link the pseudo-account with its owner object. - account->setFieldH256(ownerField, pseudoOwnerKey); - - view.insert(account); - - return account; -} - -[[nodiscard]] TER -canAddHolding(ReadView const& view, Issue const& issue) -{ - if (issue.native()) - return tesSUCCESS; // No special checks for XRP - - auto const issuer = view.read(keylet::account(issue.getIssuer())); - if (!issuer) - { - return terNO_ACCOUNT; - } - if (!issuer->isFlag(lsfDefaultRipple)) - { - return terNO_RIPPLE; - } - - return tesSUCCESS; -} - -[[nodiscard]] TER -canAddHolding(ReadView const& view, MPTIssue const& mptIssue) -{ - auto mptID = mptIssue.getMptID(); - auto issuance = view.read(keylet::mptIssuance(mptID)); - if (!issuance) - return tecOBJECT_NOT_FOUND; - if (!issuance->isFlag(lsfMPTCanTransfer)) - return tecNO_AUTH; - - return tesSUCCESS; -} - -[[nodiscard]] TER -canAddHolding(ReadView const& view, Asset const& asset) -{ - return std::visit( - [&](TIss const& issue) -> TER { return canAddHolding(view, issue); }, - asset.value()); -} - -[[nodiscard]] TER -checkDestinationAndTag(SLE::const_ref toSle, bool hasDestinationTag) -{ - if (toSle == nullptr) - return tecNO_DST; - - // The tag is basically account-specific information we don't - // understand, but we can require someone to fill it in. - if (toSle->isFlag(lsfRequireDestTag) && !hasDestinationTag) - return tecDST_TAG_NEEDED; // Cannot send without a tag - - return tesSUCCESS; -} - /* * Checks if a withdrawal amount into the destination account exceeds * any applicable receiving limit. @@ -1375,1837 +441,6 @@ doWithdraw( return accountSend(view, sourceAcct, dstAcct, amount, j, WaiveTransferFee::Yes); } -[[nodiscard]] TER -addEmptyHolding( - ApplyView& view, - AccountID const& accountID, - XRPAmount priorBalance, - Issue const& issue, - beast::Journal journal) -{ - // Every account can hold XRP. An issuer can issue directly. - if (issue.native() || accountID == issue.getIssuer()) - return tesSUCCESS; - - auto const& issuerId = issue.getIssuer(); - auto const& currency = issue.currency; - if (isGlobalFrozen(view, issuerId)) - return tecFROZEN; // LCOV_EXCL_LINE - - auto const& srcId = issuerId; - auto const& dstId = accountID; - auto const high = srcId > dstId; - auto const index = keylet::line(srcId, dstId, currency); - auto const sleSrc = view.peek(keylet::account(srcId)); - auto const sleDst = view.peek(keylet::account(dstId)); - if (!sleDst || !sleSrc) - return tefINTERNAL; // LCOV_EXCL_LINE - if (!sleSrc->isFlag(lsfDefaultRipple)) - return tecINTERNAL; // LCOV_EXCL_LINE - // If the line already exists, don't create it again. - if (view.read(index)) - return tecDUPLICATE; - - // Can the account cover the trust line reserve ? - std::uint32_t const ownerCount = sleDst->at(sfOwnerCount); - if (priorBalance < view.fees().accountReserve(ownerCount + 1)) - return tecNO_LINE_INSUF_RESERVE; - - return trustCreate( - view, - high, - srcId, - dstId, - index.key, - sleDst, - /*bAuth=*/false, - /*bNoRipple=*/true, - /*bFreeze=*/false, - /*deepFreeze*/ false, - /*saBalance=*/STAmount{Issue{currency, noAccount()}}, - /*saLimit=*/STAmount{Issue{currency, dstId}}, - /*uSrcQualityIn=*/0, - /*uSrcQualityOut=*/0, - journal); -} - -[[nodiscard]] TER -addEmptyHolding( - ApplyView& view, - AccountID const& accountID, - XRPAmount priorBalance, - MPTIssue const& mptIssue, - beast::Journal journal) -{ - auto const& mptID = mptIssue.getMptID(); - auto const mpt = view.peek(keylet::mptIssuance(mptID)); - if (!mpt) - return tefINTERNAL; // LCOV_EXCL_LINE - if (mpt->isFlag(lsfMPTLocked)) - return tefINTERNAL; // LCOV_EXCL_LINE - if (view.peek(keylet::mptoken(mptID, accountID))) - return tecDUPLICATE; - if (accountID == mptIssue.getIssuer()) - return tesSUCCESS; - - return authorizeMPToken(view, priorBalance, mptID, accountID, journal); -} - -[[nodiscard]] TER -authorizeMPToken( - ApplyView& view, - XRPAmount const& priorBalance, - MPTID const& mptIssuanceID, - AccountID const& account, - beast::Journal journal, - std::uint32_t flags, - std::optional holderID) -{ - auto const sleAcct = view.peek(keylet::account(account)); - if (!sleAcct) - return tecINTERNAL; // LCOV_EXCL_LINE - - // If the account that submitted the tx is a holder - // Note: `account_` is holder's account - // `holderID` is NOT used - if (!holderID) - { - // When a holder wants to unauthorize/delete a MPT, the ledger must - // - delete mptokenKey from owner directory - // - delete the MPToken - if (flags & tfMPTUnauthorize) - { - auto const mptokenKey = keylet::mptoken(mptIssuanceID, account); - auto const sleMpt = view.peek(mptokenKey); - if (!sleMpt || (*sleMpt)[sfMPTAmount] != 0) - return tecINTERNAL; // LCOV_EXCL_LINE - - if (!view.dirRemove( - keylet::ownerDir(account), (*sleMpt)[sfOwnerNode], sleMpt->key(), false)) - return tecINTERNAL; // LCOV_EXCL_LINE - - adjustOwnerCount(view, sleAcct, -1, journal); - - view.erase(sleMpt); - return tesSUCCESS; - } - - // A potential holder wants to authorize/hold a mpt, the ledger must: - // - add the new mptokenKey to the owner directory - // - create the MPToken object for the holder - - // The reserve that is required to create the MPToken. Note - // that although the reserve increases with every item - // an account owns, in the case of MPTokens we only - // *enforce* a reserve if the user owns more than two - // items. This is similar to the reserve requirements of trust lines. - std::uint32_t const uOwnerCount = sleAcct->getFieldU32(sfOwnerCount); - XRPAmount const reserveCreate( - (uOwnerCount < 2) ? XRPAmount(beast::zero) - : view.fees().accountReserve(uOwnerCount + 1)); - - if (priorBalance < reserveCreate) - return tecINSUFFICIENT_RESERVE; - - // Defensive check before we attempt to create MPToken for the issuer - auto const mpt = view.read(keylet::mptIssuance(mptIssuanceID)); - if (!mpt || mpt->getAccountID(sfIssuer) == account) - { - // LCOV_EXCL_START - UNREACHABLE("xrpl::authorizeMPToken : invalid issuance or issuers token"); - if (view.rules().enabled(featureLendingProtocol)) - return tecINTERNAL; - // LCOV_EXCL_STOP - } - - auto const mptokenKey = keylet::mptoken(mptIssuanceID, account); - auto mptoken = std::make_shared(mptokenKey); - if (auto ter = dirLink(view, account, mptoken)) - return ter; // LCOV_EXCL_LINE - - (*mptoken)[sfAccount] = account; - (*mptoken)[sfMPTokenIssuanceID] = mptIssuanceID; - (*mptoken)[sfFlags] = 0; - view.insert(mptoken); - - // Update owner count. - adjustOwnerCount(view, sleAcct, 1, journal); - - return tesSUCCESS; - } - - auto const sleMptIssuance = view.read(keylet::mptIssuance(mptIssuanceID)); - if (!sleMptIssuance) - return tecINTERNAL; // LCOV_EXCL_LINE - - // If the account that submitted this tx is the issuer of the MPT - // Note: `account_` is issuer's account - // `holderID` is holder's account - if (account != (*sleMptIssuance)[sfIssuer]) - return tecINTERNAL; // LCOV_EXCL_LINE - - auto const sleMpt = view.peek(keylet::mptoken(mptIssuanceID, *holderID)); - if (!sleMpt) - return tecINTERNAL; // LCOV_EXCL_LINE - - std::uint32_t const flagsIn = sleMpt->getFieldU32(sfFlags); - std::uint32_t flagsOut = flagsIn; - - // Issuer wants to unauthorize the holder, unset lsfMPTAuthorized on - // their MPToken - if (flags & tfMPTUnauthorize) - { - flagsOut &= ~lsfMPTAuthorized; - } - // Issuer wants to authorize a holder, set lsfMPTAuthorized on their - // MPToken - else - { - flagsOut |= lsfMPTAuthorized; - } - - if (flagsIn != flagsOut) - sleMpt->setFieldU32(sfFlags, flagsOut); - - view.update(sleMpt); - return tesSUCCESS; -} - -TER -trustCreate( - ApplyView& view, - bool const bSrcHigh, - AccountID const& uSrcAccountID, - AccountID const& uDstAccountID, - uint256 const& uIndex, // --> ripple state entry - SLE::ref sleAccount, // --> the account being set. - bool const bAuth, // --> authorize account. - bool const bNoRipple, // --> others cannot ripple through - bool const bFreeze, // --> funds cannot leave - bool bDeepFreeze, // --> can neither receive nor send funds - STAmount const& saBalance, // --> balance of account being set. - // Issuer should be noAccount() - STAmount const& saLimit, // --> limit for account being set. - // Issuer should be the account being set. - std::uint32_t uQualityIn, - std::uint32_t uQualityOut, - beast::Journal j) -{ - JLOG(j.trace()) << "trustCreate: " << to_string(uSrcAccountID) << ", " - << to_string(uDstAccountID) << ", " << saBalance.getFullText(); - - auto const& uLowAccountID = !bSrcHigh ? uSrcAccountID : uDstAccountID; - auto const& uHighAccountID = bSrcHigh ? uSrcAccountID : uDstAccountID; - if (uLowAccountID == uHighAccountID) - { - // LCOV_EXCL_START - UNREACHABLE("xrpl::trustCreate : trust line to self"); - if (view.rules().enabled(featureLendingProtocol)) - return tecINTERNAL; - // LCOV_EXCL_STOP - } - - auto const sleRippleState = std::make_shared(ltRIPPLE_STATE, uIndex); - view.insert(sleRippleState); - - auto lowNode = view.dirInsert( - keylet::ownerDir(uLowAccountID), sleRippleState->key(), describeOwnerDir(uLowAccountID)); - - if (!lowNode) - return tecDIR_FULL; // LCOV_EXCL_LINE - - auto highNode = view.dirInsert( - keylet::ownerDir(uHighAccountID), sleRippleState->key(), describeOwnerDir(uHighAccountID)); - - if (!highNode) - return tecDIR_FULL; // LCOV_EXCL_LINE - - bool const bSetDst = saLimit.getIssuer() == uDstAccountID; - bool const bSetHigh = bSrcHigh ^ bSetDst; - - XRPL_ASSERT(sleAccount, "xrpl::trustCreate : non-null SLE"); - if (!sleAccount) - return tefINTERNAL; // LCOV_EXCL_LINE - - XRPL_ASSERT( - sleAccount->getAccountID(sfAccount) == (bSetHigh ? uHighAccountID : uLowAccountID), - "xrpl::trustCreate : matching account ID"); - auto const slePeer = view.peek(keylet::account(bSetHigh ? uLowAccountID : uHighAccountID)); - if (!slePeer) - return tecNO_TARGET; - - // Remember deletion hints. - sleRippleState->setFieldU64(sfLowNode, *lowNode); - sleRippleState->setFieldU64(sfHighNode, *highNode); - - sleRippleState->setFieldAmount(bSetHigh ? sfHighLimit : sfLowLimit, saLimit); - sleRippleState->setFieldAmount( - bSetHigh ? sfLowLimit : sfHighLimit, - STAmount(Issue{saBalance.getCurrency(), bSetDst ? uSrcAccountID : uDstAccountID})); - - if (uQualityIn) - sleRippleState->setFieldU32(bSetHigh ? sfHighQualityIn : sfLowQualityIn, uQualityIn); - - if (uQualityOut) - sleRippleState->setFieldU32(bSetHigh ? sfHighQualityOut : sfLowQualityOut, uQualityOut); - - std::uint32_t uFlags = bSetHigh ? lsfHighReserve : lsfLowReserve; - - if (bAuth) - { - uFlags |= (bSetHigh ? lsfHighAuth : lsfLowAuth); - } - if (bNoRipple) - { - uFlags |= (bSetHigh ? lsfHighNoRipple : lsfLowNoRipple); - } - if (bFreeze) - { - uFlags |= (bSetHigh ? lsfHighFreeze : lsfLowFreeze); - } - if (bDeepFreeze) - { - uFlags |= (bSetHigh ? lsfHighDeepFreeze : lsfLowDeepFreeze); - } - - if ((slePeer->getFlags() & lsfDefaultRipple) == 0) - { - // The other side's default is no rippling - uFlags |= (bSetHigh ? lsfLowNoRipple : lsfHighNoRipple); - } - - sleRippleState->setFieldU32(sfFlags, uFlags); - adjustOwnerCount(view, sleAccount, 1, j); - - // ONLY: Create ripple balance. - sleRippleState->setFieldAmount(sfBalance, bSetHigh ? -saBalance : saBalance); - - view.creditHook(uSrcAccountID, uDstAccountID, saBalance, saBalance.zeroed()); - - return tesSUCCESS; -} - -[[nodiscard]] TER -removeEmptyHolding( - ApplyView& view, - AccountID const& accountID, - Issue const& issue, - beast::Journal journal) -{ - if (issue.native()) - { - auto const sle = view.read(keylet::account(accountID)); - if (!sle) - return tecINTERNAL; // LCOV_EXCL_LINE - - auto const balance = sle->getFieldAmount(sfBalance); - if (balance.xrp() != 0) - return tecHAS_OBLIGATIONS; - - return tesSUCCESS; - } - - // `asset` is an IOU. - // If the account is the issuer, then no line should exist. Check anyway. If - // a line does exist, it will get deleted. If not, return success. - bool const accountIsIssuer = accountID == issue.account; - auto const line = view.peek(keylet::line(accountID, issue)); - if (!line) - return accountIsIssuer ? (TER)tesSUCCESS : (TER)tecOBJECT_NOT_FOUND; - if (!accountIsIssuer && line->at(sfBalance)->iou() != beast::zero) - return tecHAS_OBLIGATIONS; - - // Adjust the owner count(s) - if (line->isFlag(lsfLowReserve)) - { - // Clear reserve for low account. - auto sleLowAccount = view.peek(keylet::account(line->at(sfLowLimit)->getIssuer())); - if (!sleLowAccount) - return tecINTERNAL; // LCOV_EXCL_LINE - - adjustOwnerCount(view, sleLowAccount, -1, journal); - // It's not really necessary to clear the reserve flag, since the line - // is about to be deleted, but this will make the metadata reflect an - // accurate state at the time of deletion. - line->clearFlag(lsfLowReserve); - } - - if (line->isFlag(lsfHighReserve)) - { - // Clear reserve for high account. - auto sleHighAccount = view.peek(keylet::account(line->at(sfHighLimit)->getIssuer())); - if (!sleHighAccount) - return tecINTERNAL; // LCOV_EXCL_LINE - - adjustOwnerCount(view, sleHighAccount, -1, journal); - // It's not really necessary to clear the reserve flag, since the line - // is about to be deleted, but this will make the metadata reflect an - // accurate state at the time of deletion. - line->clearFlag(lsfHighReserve); - } - - return trustDelete( - view, line, line->at(sfLowLimit)->getIssuer(), line->at(sfHighLimit)->getIssuer(), journal); -} - -[[nodiscard]] TER -removeEmptyHolding( - ApplyView& view, - AccountID const& accountID, - MPTIssue const& mptIssue, - beast::Journal journal) -{ - // If the account is the issuer, then no token should exist. MPTs do not - // have the legacy ability to create such a situation, but check anyway. If - // a token does exist, it will get deleted. If not, return success. - bool const accountIsIssuer = accountID == mptIssue.getIssuer(); - auto const& mptID = mptIssue.getMptID(); - auto const mptoken = view.peek(keylet::mptoken(mptID, accountID)); - if (!mptoken) - return accountIsIssuer ? (TER)tesSUCCESS : (TER)tecOBJECT_NOT_FOUND; - // Unlike a trust line, if the account is the issuer, and the token has a - // balance, it can not just be deleted, because that will throw the issuance - // accounting out of balance, so fail. Since this should be impossible - // anyway, I'm not going to put any effort into it. - if (mptoken->at(sfMPTAmount) != 0) - return tecHAS_OBLIGATIONS; - - return authorizeMPToken( - view, - {}, // priorBalance - mptID, - accountID, - journal, - tfMPTUnauthorize // flags - ); -} - -TER -trustDelete( - ApplyView& view, - std::shared_ptr const& sleRippleState, - AccountID const& uLowAccountID, - AccountID const& uHighAccountID, - beast::Journal j) -{ - // Detect legacy dirs. - std::uint64_t uLowNode = sleRippleState->getFieldU64(sfLowNode); - std::uint64_t uHighNode = sleRippleState->getFieldU64(sfHighNode); - - JLOG(j.trace()) << "trustDelete: Deleting ripple line: low"; - - if (!view.dirRemove(keylet::ownerDir(uLowAccountID), uLowNode, sleRippleState->key(), false)) - { - return tefBAD_LEDGER; // LCOV_EXCL_LINE - } - - JLOG(j.trace()) << "trustDelete: Deleting ripple line: high"; - - if (!view.dirRemove(keylet::ownerDir(uHighAccountID), uHighNode, sleRippleState->key(), false)) - { - return tefBAD_LEDGER; // LCOV_EXCL_LINE - } - - JLOG(j.trace()) << "trustDelete: Deleting ripple line: state"; - view.erase(sleRippleState); - - return tesSUCCESS; -} - -TER -offerDelete(ApplyView& view, std::shared_ptr const& sle, beast::Journal j) -{ - if (!sle) - return tesSUCCESS; - auto offerIndex = sle->key(); - auto owner = sle->getAccountID(sfAccount); - - // Detect legacy directories. - uint256 uDirectory = sle->getFieldH256(sfBookDirectory); - - if (!view.dirRemove(keylet::ownerDir(owner), sle->getFieldU64(sfOwnerNode), offerIndex, false)) - { - return tefBAD_LEDGER; // LCOV_EXCL_LINE - } - - if (!view.dirRemove(keylet::page(uDirectory), sle->getFieldU64(sfBookNode), offerIndex, false)) - { - return tefBAD_LEDGER; // LCOV_EXCL_LINE - } - - if (sle->isFieldPresent(sfAdditionalBooks)) - { - XRPL_ASSERT( - sle->isFlag(lsfHybrid) && sle->isFieldPresent(sfDomainID), - "xrpl::offerDelete : should be a hybrid domain offer"); - - auto const& additionalBookDirs = sle->getFieldArray(sfAdditionalBooks); - - for (auto const& bookDir : additionalBookDirs) - { - auto const& dirIndex = bookDir.getFieldH256(sfBookDirectory); - auto const& dirNode = bookDir.getFieldU64(sfBookNode); - - if (!view.dirRemove(keylet::page(dirIndex), dirNode, offerIndex, false)) - { - return tefBAD_LEDGER; // LCOV_EXCL_LINE - } - } - } - - adjustOwnerCount(view, view.peek(keylet::account(owner)), -1, j); - - view.erase(sle); - - return tesSUCCESS; -} - -// Direct send w/o fees: -// - Redeeming IOUs and/or sending sender's own IOUs. -// - Create trust line if needed. -// --> bCheckIssuer : normally require issuer to be involved. -static TER -rippleCreditIOU( - ApplyView& view, - AccountID const& uSenderID, - AccountID const& uReceiverID, - STAmount const& saAmount, - bool bCheckIssuer, - beast::Journal j) -{ - AccountID const& issuer = saAmount.getIssuer(); - Currency const& currency = saAmount.getCurrency(); - - // Make sure issuer is involved. - XRPL_ASSERT( - !bCheckIssuer || uSenderID == issuer || uReceiverID == issuer, - "xrpl::rippleCreditIOU : matching issuer or don't care"); - (void)issuer; - - // Disallow sending to self. - XRPL_ASSERT(uSenderID != uReceiverID, "xrpl::rippleCreditIOU : sender is not receiver"); - - bool const bSenderHigh = uSenderID > uReceiverID; - auto const index = keylet::line(uSenderID, uReceiverID, currency); - - XRPL_ASSERT( - !isXRP(uSenderID) && uSenderID != noAccount(), "xrpl::rippleCreditIOU : sender is not XRP"); - XRPL_ASSERT( - !isXRP(uReceiverID) && uReceiverID != noAccount(), - "xrpl::rippleCreditIOU : receiver is not XRP"); - - // If the line exists, modify it accordingly. - if (auto const sleRippleState = view.peek(index)) - { - STAmount saBalance = sleRippleState->getFieldAmount(sfBalance); - - if (bSenderHigh) - saBalance.negate(); // Put balance in sender terms. - - view.creditHook(uSenderID, uReceiverID, saAmount, saBalance); - - STAmount const saBefore = saBalance; - - saBalance -= saAmount; - - JLOG(j.trace()) << "rippleCreditIOU: " << to_string(uSenderID) << " -> " - << to_string(uReceiverID) << " : before=" << saBefore.getFullText() - << " amount=" << saAmount.getFullText() - << " after=" << saBalance.getFullText(); - - std::uint32_t const uFlags(sleRippleState->getFieldU32(sfFlags)); - bool bDelete = false; - - // FIXME This NEEDS to be cleaned up and simplified. It's impossible - // for anyone to understand. - if (saBefore > beast::zero - // Sender balance was positive. - && saBalance <= beast::zero - // Sender is zero or negative. - && (uFlags & (!bSenderHigh ? lsfLowReserve : lsfHighReserve)) - // Sender reserve is set. - && static_cast(uFlags & (!bSenderHigh ? lsfLowNoRipple : lsfHighNoRipple)) != - static_cast( - view.read(keylet::account(uSenderID))->getFlags() & lsfDefaultRipple) && - !(uFlags & (!bSenderHigh ? lsfLowFreeze : lsfHighFreeze)) && - !sleRippleState->getFieldAmount(!bSenderHigh ? sfLowLimit : sfHighLimit) - // Sender trust limit is 0. - && !sleRippleState->getFieldU32(!bSenderHigh ? sfLowQualityIn : sfHighQualityIn) - // Sender quality in is 0. - && !sleRippleState->getFieldU32(!bSenderHigh ? sfLowQualityOut : sfHighQualityOut)) - // Sender quality out is 0. - { - // Clear the reserve of the sender, possibly delete the line! - adjustOwnerCount(view, view.peek(keylet::account(uSenderID)), -1, j); - - // Clear reserve flag. - sleRippleState->setFieldU32( - sfFlags, uFlags & (!bSenderHigh ? ~lsfLowReserve : ~lsfHighReserve)); - - // Balance is zero, receiver reserve is clear. - bDelete = !saBalance // Balance is zero. - && !(uFlags & (bSenderHigh ? lsfLowReserve : lsfHighReserve)); - // Receiver reserve is clear. - } - - if (bSenderHigh) - saBalance.negate(); - - // Want to reflect balance to zero even if we are deleting line. - sleRippleState->setFieldAmount(sfBalance, saBalance); - // ONLY: Adjust ripple balance. - - if (bDelete) - { - return trustDelete( - view, - sleRippleState, - bSenderHigh ? uReceiverID : uSenderID, - !bSenderHigh ? uReceiverID : uSenderID, - j); - } - - view.update(sleRippleState); - return tesSUCCESS; - } - - STAmount const saReceiverLimit(Issue{currency, uReceiverID}); - STAmount saBalance{saAmount}; - - saBalance.setIssuer(noAccount()); - - JLOG(j.debug()) << "rippleCreditIOU: " - "create line: " - << to_string(uSenderID) << " -> " << to_string(uReceiverID) << " : " - << saAmount.getFullText(); - - auto const sleAccount = view.peek(keylet::account(uReceiverID)); - if (!sleAccount) - return tefINTERNAL; // LCOV_EXCL_LINE - - bool const noRipple = (sleAccount->getFlags() & lsfDefaultRipple) == 0; - - return trustCreate( - view, - bSenderHigh, - uSenderID, - uReceiverID, - index.key, - sleAccount, - false, - noRipple, - false, - false, - saBalance, - saReceiverLimit, - 0, - 0, - j); -} - -// Send regardless of limits. -// --> saAmount: Amount/currency/issuer to deliver to receiver. -// <-- saActual: Amount actually cost. Sender pays fees. -static TER -rippleSendIOU( - ApplyView& view, - AccountID const& uSenderID, - AccountID const& uReceiverID, - STAmount const& saAmount, - STAmount& saActual, - beast::Journal j, - WaiveTransferFee waiveFee) -{ - auto const& issuer = saAmount.getIssuer(); - - XRPL_ASSERT( - !isXRP(uSenderID) && !isXRP(uReceiverID), - "xrpl::rippleSendIOU : neither sender nor receiver is XRP"); - XRPL_ASSERT(uSenderID != uReceiverID, "xrpl::rippleSendIOU : sender is not receiver"); - - if (uSenderID == issuer || uReceiverID == issuer || issuer == noAccount()) - { - // Direct send: redeeming IOUs and/or sending own IOUs. - auto const ter = rippleCreditIOU(view, uSenderID, uReceiverID, saAmount, false, j); - if (!isTesSuccess(ter)) - return ter; - saActual = saAmount; - return tesSUCCESS; - } - - // Sending 3rd party IOUs: transit. - - // Calculate the amount to transfer accounting - // for any transfer fees if the fee is not waived: - saActual = (waiveFee == WaiveTransferFee::Yes) ? saAmount - : multiply(saAmount, transferRate(view, issuer)); - - JLOG(j.debug()) << "rippleSendIOU> " << to_string(uSenderID) << " - > " - << to_string(uReceiverID) << " : deliver=" << saAmount.getFullText() - << " cost=" << saActual.getFullText(); - - TER terResult = rippleCreditIOU(view, issuer, uReceiverID, saAmount, true, j); - - if (tesSUCCESS == terResult) - terResult = rippleCreditIOU(view, uSenderID, issuer, saActual, true, j); - - return terResult; -} - -// Send regardless of limits. -// --> receivers: Amount/currency/issuer to deliver to receivers. -// <-- saActual: Amount actually cost to sender. Sender pays fees. -static TER -rippleSendMultiIOU( - ApplyView& view, - AccountID const& senderID, - Issue const& issue, - MultiplePaymentDestinations const& receivers, - STAmount& actual, - beast::Journal j, - WaiveTransferFee waiveFee) -{ - auto const& issuer = issue.getIssuer(); - - XRPL_ASSERT(!isXRP(senderID), "xrpl::rippleSendMultiIOU : sender is not XRP"); - - // These may diverge - STAmount takeFromSender{issue}; - actual = takeFromSender; - - // Failures return immediately. - for (auto const& r : receivers) - { - auto const& receiverID = r.first; - STAmount amount{issue, r.second}; - - /* If we aren't sending anything or if the sender is the same as the - * receiver then we don't need to do anything. - */ - if (!amount || (senderID == receiverID)) - continue; - - XRPL_ASSERT(!isXRP(receiverID), "xrpl::rippleSendMultiIOU : receiver is not XRP"); - - if (senderID == issuer || receiverID == issuer || issuer == noAccount()) - { - // Direct send: redeeming IOUs and/or sending own IOUs. - if (auto const ter = rippleCreditIOU(view, senderID, receiverID, amount, false, j)) - return ter; - actual += amount; - // Do not add amount to takeFromSender, because rippleCreditIOU took - // it. - - continue; - } - - // Sending 3rd party IOUs: transit. - - // Calculate the amount to transfer accounting - // for any transfer fees if the fee is not waived: - STAmount actualSend = (waiveFee == WaiveTransferFee::Yes) - ? amount - : multiply(amount, transferRate(view, issuer)); - actual += actualSend; - takeFromSender += actualSend; - - JLOG(j.debug()) << "rippleSendMultiIOU> " << to_string(senderID) << " - > " - << to_string(receiverID) << " : deliver=" << amount.getFullText() - << " cost=" << actual.getFullText(); - - if (TER const terResult = rippleCreditIOU(view, issuer, receiverID, amount, true, j)) - return terResult; - } - - if (senderID != issuer && takeFromSender) - { - if (TER const terResult = rippleCreditIOU(view, senderID, issuer, takeFromSender, true, j)) - return terResult; - } - - return tesSUCCESS; -} - -static TER -accountSendIOU( - ApplyView& view, - AccountID const& uSenderID, - AccountID const& uReceiverID, - STAmount const& saAmount, - beast::Journal j, - WaiveTransferFee waiveFee) -{ - if (view.rules().enabled(fixAMMv1_1)) - { - if (saAmount < beast::zero || saAmount.holds()) - { - return tecINTERNAL; // LCOV_EXCL_LINE - } - } - else - { - // LCOV_EXCL_START - XRPL_ASSERT( - saAmount >= beast::zero && !saAmount.holds(), - "xrpl::accountSendIOU : minimum amount and not MPT"); - // LCOV_EXCL_STOP - } - - /* If we aren't sending anything or if the sender is the same as the - * receiver then we don't need to do anything. - */ - if (!saAmount || (uSenderID == uReceiverID)) - return tesSUCCESS; - - if (!saAmount.native()) - { - STAmount saActual; - - JLOG(j.trace()) << "accountSendIOU: " << to_string(uSenderID) << " -> " - << to_string(uReceiverID) << " : " << saAmount.getFullText(); - - return rippleSendIOU(view, uSenderID, uReceiverID, saAmount, saActual, j, waiveFee); - } - - /* XRP send which does not check reserve and can do pure adjustment. - * Note that sender or receiver may be null and this not a mistake; this - * setup is used during pathfinding and it is carefully controlled to - * ensure that transfers are balanced. - */ - TER terResult(tesSUCCESS); - - SLE::pointer sender = - uSenderID != beast::zero ? view.peek(keylet::account(uSenderID)) : SLE::pointer(); - SLE::pointer receiver = - uReceiverID != beast::zero ? view.peek(keylet::account(uReceiverID)) : SLE::pointer(); - - if (auto stream = j.trace()) - { - std::string sender_bal("-"); - std::string receiver_bal("-"); - - if (sender) - sender_bal = sender->getFieldAmount(sfBalance).getFullText(); - - if (receiver) - receiver_bal = receiver->getFieldAmount(sfBalance).getFullText(); - - stream << "accountSendIOU> " << to_string(uSenderID) << " (" << sender_bal << ") -> " - << to_string(uReceiverID) << " (" << receiver_bal - << ") : " << saAmount.getFullText(); - } - - if (sender) - { - if (sender->getFieldAmount(sfBalance) < saAmount) - { - // VFALCO Its laborious to have to mutate the - // TER based on params everywhere - // LCOV_EXCL_START - terResult = view.open() ? TER{telFAILED_PROCESSING} : TER{tecFAILED_PROCESSING}; - // LCOV_EXCL_STOP - } - else - { - auto const sndBal = sender->getFieldAmount(sfBalance); - view.creditHook(uSenderID, xrpAccount(), saAmount, sndBal); - - // Decrement XRP balance. - sender->setFieldAmount(sfBalance, sndBal - saAmount); - view.update(sender); - } - } - - if (tesSUCCESS == terResult && receiver) - { - // Increment XRP balance. - auto const rcvBal = receiver->getFieldAmount(sfBalance); - receiver->setFieldAmount(sfBalance, rcvBal + saAmount); - view.creditHook(xrpAccount(), uReceiverID, saAmount, -rcvBal); - - view.update(receiver); - } - - if (auto stream = j.trace()) - { - std::string sender_bal("-"); - std::string receiver_bal("-"); - - if (sender) - sender_bal = sender->getFieldAmount(sfBalance).getFullText(); - - if (receiver) - receiver_bal = receiver->getFieldAmount(sfBalance).getFullText(); - - stream << "accountSendIOU< " << to_string(uSenderID) << " (" << sender_bal << ") -> " - << to_string(uReceiverID) << " (" << receiver_bal - << ") : " << saAmount.getFullText(); - } - - return terResult; -} - -static TER -accountSendMultiIOU( - ApplyView& view, - AccountID const& senderID, - Issue const& issue, - MultiplePaymentDestinations const& receivers, - beast::Journal j, - WaiveTransferFee waiveFee) -{ - XRPL_ASSERT_PARTS( - receivers.size() > 1, "xrpl::accountSendMultiIOU", "multiple recipients provided"); - - if (!issue.native()) - { - STAmount actual; - JLOG(j.trace()) << "accountSendMultiIOU: " << to_string(senderID) << " sending " - << receivers.size() << " IOUs"; - - return rippleSendMultiIOU(view, senderID, issue, receivers, actual, j, waiveFee); - } - - /* XRP send which does not check reserve and can do pure adjustment. - * Note that sender or receiver may be null and this not a mistake; this - * setup could be used during pathfinding and it is carefully controlled to - * ensure that transfers are balanced. - */ - - SLE::pointer sender = - senderID != beast::zero ? view.peek(keylet::account(senderID)) : SLE::pointer(); - - if (auto stream = j.trace()) - { - std::string sender_bal("-"); - - if (sender) - sender_bal = sender->getFieldAmount(sfBalance).getFullText(); - - stream << "accountSendMultiIOU> " << to_string(senderID) << " (" << sender_bal << ") -> " - << receivers.size() << " receivers."; - } - - // Failures return immediately. - STAmount takeFromSender{issue}; - for (auto const& r : receivers) - { - auto const& receiverID = r.first; - STAmount amount{issue, r.second}; - - if (amount < beast::zero) - { - return tecINTERNAL; // LCOV_EXCL_LINE - } - - /* If we aren't sending anything or if the sender is the same as the - * receiver then we don't need to do anything. - */ - if (!amount || (senderID == receiverID)) - continue; - - SLE::pointer receiver = - receiverID != beast::zero ? view.peek(keylet::account(receiverID)) : SLE::pointer(); - - if (auto stream = j.trace()) - { - std::string receiver_bal("-"); - - if (receiver) - receiver_bal = receiver->getFieldAmount(sfBalance).getFullText(); - - stream << "accountSendMultiIOU> " << to_string(senderID) << " -> " - << to_string(receiverID) << " (" << receiver_bal - << ") : " << amount.getFullText(); - } - - if (receiver) - { - // Increment XRP balance. - auto const rcvBal = receiver->getFieldAmount(sfBalance); - receiver->setFieldAmount(sfBalance, rcvBal + amount); - view.creditHook(xrpAccount(), receiverID, amount, -rcvBal); - - view.update(receiver); - - // Take what is actually sent - takeFromSender += amount; - } - - if (auto stream = j.trace()) - { - std::string receiver_bal("-"); - - if (receiver) - receiver_bal = receiver->getFieldAmount(sfBalance).getFullText(); - - stream << "accountSendMultiIOU< " << to_string(senderID) << " -> " - << to_string(receiverID) << " (" << receiver_bal - << ") : " << amount.getFullText(); - } - } - - if (sender) - { - if (sender->getFieldAmount(sfBalance) < takeFromSender) - { - return TER{tecFAILED_PROCESSING}; - } - - auto const sndBal = sender->getFieldAmount(sfBalance); - view.creditHook(senderID, xrpAccount(), takeFromSender, sndBal); - - // Decrement XRP balance. - sender->setFieldAmount(sfBalance, sndBal - takeFromSender); - view.update(sender); - } - - if (auto stream = j.trace()) - { - std::string sender_bal("-"); - - if (sender) - sender_bal = sender->getFieldAmount(sfBalance).getFullText(); - - stream << "accountSendMultiIOU< " << to_string(senderID) << " (" << sender_bal << ") -> " - << receivers.size() << " receivers."; - } - return tesSUCCESS; -} - -static TER -rippleCreditMPT( - ApplyView& view, - AccountID const& uSenderID, - AccountID const& uReceiverID, - STAmount const& saAmount, - beast::Journal j) -{ - // Do not check MPT authorization here - it must have been checked earlier - auto const mptID = keylet::mptIssuance(saAmount.get().getMptID()); - auto const& issuer = saAmount.getIssuer(); - auto sleIssuance = view.peek(mptID); - if (!sleIssuance) - return tecOBJECT_NOT_FOUND; - if (uSenderID == issuer) - { - (*sleIssuance)[sfOutstandingAmount] += saAmount.mpt().value(); - view.update(sleIssuance); - } - else - { - auto const mptokenID = keylet::mptoken(mptID.key, uSenderID); - if (auto sle = view.peek(mptokenID)) - { - auto const amt = sle->getFieldU64(sfMPTAmount); - auto const pay = saAmount.mpt().value(); - if (amt < pay) - return tecINSUFFICIENT_FUNDS; - (*sle)[sfMPTAmount] = amt - pay; - view.update(sle); - } - else - { - return tecNO_AUTH; - } - } - - if (uReceiverID == issuer) - { - auto const outstanding = sleIssuance->getFieldU64(sfOutstandingAmount); - auto const redeem = saAmount.mpt().value(); - if (outstanding >= redeem) - { - sleIssuance->setFieldU64(sfOutstandingAmount, outstanding - redeem); - view.update(sleIssuance); - } - else - { - return tecINTERNAL; // LCOV_EXCL_LINE - } - } - else - { - auto const mptokenID = keylet::mptoken(mptID.key, uReceiverID); - if (auto sle = view.peek(mptokenID)) - { - (*sle)[sfMPTAmount] += saAmount.mpt().value(); - view.update(sle); - } - else - { - return tecNO_AUTH; - } - } - - return tesSUCCESS; -} - -static TER -rippleSendMPT( - ApplyView& view, - AccountID const& uSenderID, - AccountID const& uReceiverID, - STAmount const& saAmount, - STAmount& saActual, - beast::Journal j, - WaiveTransferFee waiveFee) -{ - XRPL_ASSERT(uSenderID != uReceiverID, "xrpl::rippleSendMPT : sender is not receiver"); - - // Safe to get MPT since rippleSendMPT is only called by accountSendMPT - auto const& issuer = saAmount.getIssuer(); - - auto const sle = view.read(keylet::mptIssuance(saAmount.get().getMptID())); - if (!sle) - return tecOBJECT_NOT_FOUND; - - if (uSenderID == issuer || uReceiverID == issuer) - { - // if sender is issuer, check that the new OutstandingAmount will not - // exceed MaximumAmount - if (uSenderID == issuer) - { - auto const sendAmount = saAmount.mpt().value(); - auto const maximumAmount = sle->at(~sfMaximumAmount).value_or(maxMPTokenAmount); - if (sendAmount > maximumAmount || - sle->getFieldU64(sfOutstandingAmount) > maximumAmount - sendAmount) - return tecPATH_DRY; - } - - // Direct send: redeeming MPTs and/or sending own MPTs. - auto const ter = rippleCreditMPT(view, uSenderID, uReceiverID, saAmount, j); - if (!isTesSuccess(ter)) - return ter; - saActual = saAmount; - return tesSUCCESS; - } - - // Sending 3rd party MPTs: transit. - saActual = (waiveFee == WaiveTransferFee::Yes) - ? saAmount - : multiply(saAmount, transferRate(view, saAmount.get().getMptID())); - - JLOG(j.debug()) << "rippleSendMPT> " << to_string(uSenderID) << " - > " - << to_string(uReceiverID) << " : deliver=" << saAmount.getFullText() - << " cost=" << saActual.getFullText(); - - if (auto const terResult = rippleCreditMPT(view, issuer, uReceiverID, saAmount, j); - !isTesSuccess(terResult)) - return terResult; - - return rippleCreditMPT(view, uSenderID, issuer, saActual, j); -} - -static TER -rippleSendMultiMPT( - ApplyView& view, - AccountID const& senderID, - MPTIssue const& mptIssue, - MultiplePaymentDestinations const& receivers, - STAmount& actual, - beast::Journal j, - WaiveTransferFee waiveFee) -{ - // Safe to get MPT since rippleSendMultiMPT is only called by - // accountSendMultiMPT - auto const& issuer = mptIssue.getIssuer(); - - auto const sle = view.read(keylet::mptIssuance(mptIssue.getMptID())); - if (!sle) - return tecOBJECT_NOT_FOUND; - - // These may diverge - STAmount takeFromSender{mptIssue}; - actual = takeFromSender; - - for (auto const& r : receivers) - { - auto const& receiverID = r.first; - STAmount amount{mptIssue, r.second}; - - if (amount < beast::zero) - { - return tecINTERNAL; // LCOV_EXCL_LINE - } - - /* If we aren't sending anything or if the sender is the same as the - * receiver then we don't need to do anything. - */ - if (!amount || (senderID == receiverID)) - continue; - - if (senderID == issuer || receiverID == issuer) - { - // if sender is issuer, check that the new OutstandingAmount will - // not exceed MaximumAmount - if (senderID == issuer) - { - XRPL_ASSERT_PARTS( - takeFromSender == beast::zero, - "rippler::rippleSendMultiMPT", - "sender == issuer, takeFromSender == zero"); - auto const sendAmount = amount.mpt().value(); - auto const maximumAmount = sle->at(~sfMaximumAmount).value_or(maxMPTokenAmount); - if (sendAmount > maximumAmount || - sle->getFieldU64(sfOutstandingAmount) > maximumAmount - sendAmount) - return tecPATH_DRY; - } - - // Direct send: redeeming MPTs and/or sending own MPTs. - if (auto const ter = rippleCreditMPT(view, senderID, receiverID, amount, j)) - return ter; - actual += amount; - // Do not add amount to takeFromSender, because rippleCreditMPT took - // it - - continue; - } - - // Sending 3rd party MPTs: transit. - STAmount actualSend = (waiveFee == WaiveTransferFee::Yes) - ? amount - : multiply(amount, transferRate(view, amount.get().getMptID())); - actual += actualSend; - takeFromSender += actualSend; - - JLOG(j.debug()) << "rippleSendMultiMPT> " << to_string(senderID) << " - > " - << to_string(receiverID) << " : deliver=" << amount.getFullText() - << " cost=" << actualSend.getFullText(); - - if (auto const terResult = rippleCreditMPT(view, issuer, receiverID, amount, j)) - return terResult; - } - if (senderID != issuer && takeFromSender) - { - if (TER const terResult = rippleCreditMPT(view, senderID, issuer, takeFromSender, j)) - return terResult; - } - - return tesSUCCESS; -} - -static TER -accountSendMPT( - ApplyView& view, - AccountID const& uSenderID, - AccountID const& uReceiverID, - STAmount const& saAmount, - beast::Journal j, - WaiveTransferFee waiveFee) -{ - XRPL_ASSERT( - saAmount >= beast::zero && saAmount.holds(), - "xrpl::accountSendMPT : minimum amount and MPT"); - - /* If we aren't sending anything or if the sender is the same as the - * receiver then we don't need to do anything. - */ - if (!saAmount || (uSenderID == uReceiverID)) - return tesSUCCESS; - - STAmount saActual{saAmount.asset()}; - - return rippleSendMPT(view, uSenderID, uReceiverID, saAmount, saActual, j, waiveFee); -} - -static TER -accountSendMultiMPT( - ApplyView& view, - AccountID const& senderID, - MPTIssue const& mptIssue, - MultiplePaymentDestinations const& receivers, - beast::Journal j, - WaiveTransferFee waiveFee) -{ - STAmount actual; - - return rippleSendMultiMPT(view, senderID, mptIssue, receivers, actual, j, waiveFee); -} - -TER -accountSend( - ApplyView& view, - AccountID const& uSenderID, - AccountID const& uReceiverID, - STAmount const& saAmount, - beast::Journal j, - WaiveTransferFee waiveFee) -{ - return std::visit( - [&](TIss const& issue) { - if constexpr (std::is_same_v) - { - return accountSendIOU(view, uSenderID, uReceiverID, saAmount, j, waiveFee); - } - else - { - return accountSendMPT(view, uSenderID, uReceiverID, saAmount, j, waiveFee); - } - }, - saAmount.asset().value()); -} - -TER -accountSendMulti( - ApplyView& view, - AccountID const& senderID, - Asset const& asset, - MultiplePaymentDestinations const& receivers, - beast::Journal j, - WaiveTransferFee waiveFee) -{ - XRPL_ASSERT_PARTS( - receivers.size() > 1, "xrpl::accountSendMulti", "multiple recipients provided"); - return std::visit( - [&](TIss const& issue) { - if constexpr (std::is_same_v) - { - return accountSendMultiIOU(view, senderID, issue, receivers, j, waiveFee); - } - else - { - return accountSendMultiMPT(view, senderID, issue, receivers, j, waiveFee); - } - }, - asset.value()); -} - -static bool -updateTrustLine( - ApplyView& view, - SLE::pointer state, - bool bSenderHigh, - AccountID const& sender, - STAmount const& before, - STAmount const& after, - beast::Journal j) -{ - if (!state) - return false; - std::uint32_t const flags(state->getFieldU32(sfFlags)); - - auto sle = view.peek(keylet::account(sender)); - if (!sle) - return false; - - // YYY Could skip this if rippling in reverse. - if (before > beast::zero - // Sender balance was positive. - && after <= beast::zero - // Sender is zero or negative. - && (flags & (!bSenderHigh ? lsfLowReserve : lsfHighReserve)) - // Sender reserve is set. - && static_cast(flags & (!bSenderHigh ? lsfLowNoRipple : lsfHighNoRipple)) != - static_cast(sle->getFlags() & lsfDefaultRipple) && - !(flags & (!bSenderHigh ? lsfLowFreeze : lsfHighFreeze)) && - !state->getFieldAmount(!bSenderHigh ? sfLowLimit : sfHighLimit) - // Sender trust limit is 0. - && !state->getFieldU32(!bSenderHigh ? sfLowQualityIn : sfHighQualityIn) - // Sender quality in is 0. - && !state->getFieldU32(!bSenderHigh ? sfLowQualityOut : sfHighQualityOut)) - // Sender quality out is 0. - { - // VFALCO Where is the line being deleted? - // Clear the reserve of the sender, possibly delete the line! - adjustOwnerCount(view, sle, -1, j); - - // Clear reserve flag. - state->setFieldU32(sfFlags, flags & (!bSenderHigh ? ~lsfLowReserve : ~lsfHighReserve)); - - // Balance is zero, receiver reserve is clear. - if (!after // Balance is zero. - && !(flags & (bSenderHigh ? lsfLowReserve : lsfHighReserve))) - return true; - } - return false; -} - -TER -issueIOU( - ApplyView& view, - AccountID const& account, - STAmount const& amount, - Issue const& issue, - beast::Journal j) -{ - XRPL_ASSERT( - !isXRP(account) && !isXRP(issue.account), - "xrpl::issueIOU : neither account nor issuer is XRP"); - - // Consistency check - XRPL_ASSERT(issue == amount.issue(), "xrpl::issueIOU : matching issue"); - - // Can't send to self! - XRPL_ASSERT(issue.account != account, "xrpl::issueIOU : not issuer account"); - - JLOG(j.trace()) << "issueIOU: " << to_string(account) << ": " << amount.getFullText(); - - bool bSenderHigh = issue.account > account; - - auto const index = keylet::line(issue.account, account, issue.currency); - - if (auto state = view.peek(index)) - { - STAmount final_balance = state->getFieldAmount(sfBalance); - - if (bSenderHigh) - final_balance.negate(); // Put balance in sender terms. - - STAmount const start_balance = final_balance; - - final_balance -= amount; - - auto const must_delete = updateTrustLine( - view, state, bSenderHigh, issue.account, start_balance, final_balance, j); - - view.creditHook(issue.account, account, amount, start_balance); - - if (bSenderHigh) - final_balance.negate(); - - // Adjust the balance on the trust line if necessary. We do this even if - // we are going to delete the line to reflect the correct balance at the - // time of deletion. - state->setFieldAmount(sfBalance, final_balance); - if (must_delete) - { - return trustDelete( - view, - state, - bSenderHigh ? account : issue.account, - bSenderHigh ? issue.account : account, - j); - } - - view.update(state); - - return tesSUCCESS; - } - - // NIKB TODO: The limit uses the receiver's account as the issuer and - // this is unnecessarily inefficient as copying which could be avoided - // is now required. Consider available options. - STAmount const limit(Issue{issue.currency, account}); - STAmount final_balance = amount; - - final_balance.setIssuer(noAccount()); - - auto const receiverAccount = view.peek(keylet::account(account)); - if (!receiverAccount) - return tefINTERNAL; // LCOV_EXCL_LINE - - bool noRipple = (receiverAccount->getFlags() & lsfDefaultRipple) == 0; - - return trustCreate( - view, - bSenderHigh, - issue.account, - account, - index.key, - receiverAccount, - false, - noRipple, - false, - false, - final_balance, - limit, - 0, - 0, - j); -} - -TER -redeemIOU( - ApplyView& view, - AccountID const& account, - STAmount const& amount, - Issue const& issue, - beast::Journal j) -{ - XRPL_ASSERT( - !isXRP(account) && !isXRP(issue.account), - "xrpl::redeemIOU : neither account nor issuer is XRP"); - - // Consistency check - XRPL_ASSERT(issue == amount.issue(), "xrpl::redeemIOU : matching issue"); - - // Can't send to self! - XRPL_ASSERT(issue.account != account, "xrpl::redeemIOU : not issuer account"); - - JLOG(j.trace()) << "redeemIOU: " << to_string(account) << ": " << amount.getFullText(); - - bool bSenderHigh = account > issue.account; - - if (auto state = view.peek(keylet::line(account, issue.account, issue.currency))) - { - STAmount final_balance = state->getFieldAmount(sfBalance); - - if (bSenderHigh) - final_balance.negate(); // Put balance in sender terms. - - STAmount const start_balance = final_balance; - - final_balance -= amount; - - auto const must_delete = - updateTrustLine(view, state, bSenderHigh, account, start_balance, final_balance, j); - - view.creditHook(account, issue.account, amount, start_balance); - - if (bSenderHigh) - final_balance.negate(); - - // Adjust the balance on the trust line if necessary. We do this even if - // we are going to delete the line to reflect the correct balance at the - // time of deletion. - state->setFieldAmount(sfBalance, final_balance); - - if (must_delete) - { - return trustDelete( - view, - state, - bSenderHigh ? issue.account : account, - bSenderHigh ? account : issue.account, - j); - } - - view.update(state); - return tesSUCCESS; - } - - // In order to hold an IOU, a trust line *MUST* exist to track the - // balance. If it doesn't, then something is very wrong. Don't try - // to continue. - // LCOV_EXCL_START - JLOG(j.fatal()) << "redeemIOU: " << to_string(account) << " attempts to redeem " - << amount.getFullText() << " but no trust line exists!"; - - return tefINTERNAL; - // LCOV_EXCL_STOP -} - -TER -transferXRP( - ApplyView& view, - AccountID const& from, - AccountID const& to, - STAmount const& amount, - beast::Journal j) -{ - XRPL_ASSERT(from != beast::zero, "xrpl::transferXRP : nonzero from account"); - XRPL_ASSERT(to != beast::zero, "xrpl::transferXRP : nonzero to account"); - XRPL_ASSERT(from != to, "xrpl::transferXRP : sender is not receiver"); - XRPL_ASSERT(amount.native(), "xrpl::transferXRP : amount is XRP"); - - SLE::pointer const sender = view.peek(keylet::account(from)); - SLE::pointer const receiver = view.peek(keylet::account(to)); - if (!sender || !receiver) - return tefINTERNAL; // LCOV_EXCL_LINE - - JLOG(j.trace()) << "transferXRP: " << to_string(from) << " -> " << to_string(to) - << ") : " << amount.getFullText(); - - if (sender->getFieldAmount(sfBalance) < amount) - { - // VFALCO Its unfortunate we have to keep - // mutating these TER everywhere - // FIXME: this logic should be moved to callers maybe? - // LCOV_EXCL_START - return view.open() ? TER{telFAILED_PROCESSING} : TER{tecFAILED_PROCESSING}; - // LCOV_EXCL_STOP - } - - // Decrement XRP balance. - sender->setFieldAmount(sfBalance, sender->getFieldAmount(sfBalance) - amount); - view.update(sender); - - receiver->setFieldAmount(sfBalance, receiver->getFieldAmount(sfBalance) + amount); - view.update(receiver); - - return tesSUCCESS; -} - -TER -requireAuth(ReadView const& view, Issue const& issue, AccountID const& account, AuthType authType) -{ - if (isXRP(issue) || issue.account == account) - return tesSUCCESS; - - auto const trustLine = view.read(keylet::line(account, issue.account, issue.currency)); - // If account has no line, and this is a strong check, fail - if (!trustLine && authType == AuthType::StrongAuth) - return tecNO_LINE; - - // If this is a weak or legacy check, or if the account has a line, fail if - // auth is required and not set on the line - if (auto const issuerAccount = view.read(keylet::account(issue.account)); - issuerAccount && (*issuerAccount)[sfFlags] & lsfRequireAuth) - { - if (trustLine) - { - return ((*trustLine)[sfFlags] & ((account > issue.account) ? lsfLowAuth : lsfHighAuth)) - ? tesSUCCESS - : TER{tecNO_AUTH}; - } - return TER{tecNO_LINE}; - } - - return tesSUCCESS; -} - -TER -requireAuth( - ReadView const& view, - MPTIssue const& mptIssue, - AccountID const& account, - AuthType authType, - int depth) -{ - auto const mptID = keylet::mptIssuance(mptIssue.getMptID()); - auto const sleIssuance = view.read(mptID); - if (!sleIssuance) - return tecOBJECT_NOT_FOUND; - - auto const mptIssuer = sleIssuance->getAccountID(sfIssuer); - - // issuer is always "authorized" - if (mptIssuer == account) // Issuer won't have MPToken - return tesSUCCESS; - - bool const featureSAVEnabled = view.rules().enabled(featureSingleAssetVault); - - if (featureSAVEnabled) - { - if (depth >= maxAssetCheckDepth) - return tecINTERNAL; // LCOV_EXCL_LINE - - // requireAuth is recursive if the issuer is a vault pseudo-account - auto const sleIssuer = view.read(keylet::account(mptIssuer)); - if (!sleIssuer) - return tefINTERNAL; // LCOV_EXCL_LINE - - if (sleIssuer->isFieldPresent(sfVaultID)) - { - auto const sleVault = view.read(keylet::vault(sleIssuer->getFieldH256(sfVaultID))); - if (!sleVault) - return tefINTERNAL; // LCOV_EXCL_LINE - - auto const asset = sleVault->at(sfAsset); - if (auto const err = std::visit( - [&](TIss const& issue) { - if constexpr (std::is_same_v) - { - return requireAuth(view, issue, account, authType); - } - else - { - return requireAuth(view, issue, account, authType, depth + 1); - } - }, - asset.value()); - !isTesSuccess(err)) - return err; - } - } - - auto const mptokenID = keylet::mptoken(mptID.key, account); - auto const sleToken = view.read(mptokenID); - - // if account has no MPToken, fail - if (!sleToken && (authType == AuthType::StrongAuth || authType == AuthType::Legacy)) - return tecNO_AUTH; - - // Note, this check is not amendment-gated because DomainID will be always - // empty **unless** writing to it has been enabled by an amendment - auto const maybeDomainID = sleIssuance->at(~sfDomainID); - if (maybeDomainID) - { - XRPL_ASSERT( - sleIssuance->getFieldU32(sfFlags) & lsfMPTRequireAuth, - "xrpl::requireAuth : issuance requires authorization"); - // ter = tefINTERNAL | tecOBJECT_NOT_FOUND | tecNO_AUTH | tecEXPIRED - auto const ter = credentials::validDomain(view, *maybeDomainID, account); - if (isTesSuccess(ter)) - { - return ter; // Note: sleToken might be null - } - if (!sleToken) - { - return ter; - } - // We ignore error from validDomain if we found sleToken, as it could - // belong to someone who is explicitly authorized e.g. a vault owner. - } - - if (featureSAVEnabled) - { - // Implicitly authorize Vault and LoanBroker pseudo-accounts - if (isPseudoAccount(view, account, {&sfVaultID, &sfLoanBrokerID})) - return tesSUCCESS; - } - - // mptoken must be authorized if issuance enabled requireAuth - if (sleIssuance->isFlag(lsfMPTRequireAuth) && - (!sleToken || !sleToken->isFlag(lsfMPTAuthorized))) - return tecNO_AUTH; - - return tesSUCCESS; // Note: sleToken might be null -} - -[[nodiscard]] TER -enforceMPTokenAuthorization( - ApplyView& view, - MPTID const& mptIssuanceID, - AccountID const& account, - XRPAmount const& priorBalance, // for MPToken authorization - beast::Journal j) -{ - auto const sleIssuance = view.read(keylet::mptIssuance(mptIssuanceID)); - if (!sleIssuance) - return tefINTERNAL; // LCOV_EXCL_LINE - - XRPL_ASSERT( - sleIssuance->isFlag(lsfMPTRequireAuth), - "xrpl::enforceMPTokenAuthorization : authorization required"); - - if (account == sleIssuance->at(sfIssuer)) - return tefINTERNAL; // LCOV_EXCL_LINE - - auto const keylet = keylet::mptoken(mptIssuanceID, account); - auto const sleToken = view.read(keylet); // NOTE: might be null - auto const maybeDomainID = sleIssuance->at(~sfDomainID); - bool expired = false; - bool const authorizedByDomain = [&]() -> bool { - // NOTE: defensive here, should be checked in preclaim - if (!maybeDomainID.has_value()) - return false; // LCOV_EXCL_LINE - - auto const ter = verifyValidDomain(view, account, *maybeDomainID, j); - if (isTesSuccess(ter)) - return true; - if (ter == tecEXPIRED) - expired = true; - return false; - }(); - - if (!authorizedByDomain && sleToken == nullptr) - { - // Could not find MPToken and won't create one, could be either of: - // - // 1. Field sfDomainID not set in MPTokenIssuance or - // 2. Account has no matching and accepted credentials or - // 3. Account has all expired credentials (deleted in verifyValidDomain) - // - // Either way, return tecNO_AUTH and there is nothing else to do - return expired ? tecEXPIRED : tecNO_AUTH; - } - if (!authorizedByDomain && maybeDomainID.has_value()) - { - // Found an MPToken but the account is not authorized and we expect - // it to have been authorized by the domain. This could be because the - // credentials used to create the MPToken have expired or been deleted. - return expired ? tecEXPIRED : tecNO_AUTH; - } - if (!authorizedByDomain) - { - // We found an MPToken, but sfDomainID is not set, so this is a classic - // MPToken which requires authorization by the token issuer. - XRPL_ASSERT( - sleToken != nullptr && !maybeDomainID.has_value(), - "xrpl::enforceMPTokenAuthorization : found MPToken"); - if (sleToken->isFlag(lsfMPTAuthorized)) - return tesSUCCESS; - - return tecNO_AUTH; - } - if (authorizedByDomain && sleToken != nullptr) - { - // Found an MPToken, authorized by the domain. Ignore authorization flag - // lsfMPTAuthorized because it is meaningless. Return tesSUCCESS - XRPL_ASSERT( - maybeDomainID.has_value(), - "xrpl::enforceMPTokenAuthorization : found MPToken for domain"); - return tesSUCCESS; - } - if (authorizedByDomain) - { - // Could not find MPToken but there should be one because we are - // authorized by domain. Proceed to create it, then return tesSUCCESS - XRPL_ASSERT( - maybeDomainID.has_value() && sleToken == nullptr, - "xrpl::enforceMPTokenAuthorization : new MPToken for domain"); - if (auto const err = authorizeMPToken( - view, - priorBalance, // priorBalance - mptIssuanceID, // mptIssuanceID - account, // account - j); - !isTesSuccess(err)) - return err; - - return tesSUCCESS; - } - - // LCOV_EXCL_START - UNREACHABLE("xrpl::enforceMPTokenAuthorization : condition list is incomplete"); - return tefINTERNAL; - // LCOV_EXCL_STOP -} - -TER -canTransfer( - ReadView const& view, - MPTIssue const& mptIssue, - AccountID const& from, - AccountID const& to) -{ - auto const mptID = keylet::mptIssuance(mptIssue.getMptID()); - auto const sleIssuance = view.read(mptID); - if (!sleIssuance) - return tecOBJECT_NOT_FOUND; - - if (!(sleIssuance->getFieldU32(sfFlags) & lsfMPTCanTransfer)) - { - if (from != (*sleIssuance)[sfIssuer] && to != (*sleIssuance)[sfIssuer]) - return TER{tecNO_AUTH}; - } - return tesSUCCESS; -} - -[[nodiscard]] TER -canTransfer(ReadView const& view, Issue const& issue, AccountID const& from, AccountID const& to) -{ - if (issue.native()) - return tesSUCCESS; - - auto const& issuerId = issue.getIssuer(); - if (issuerId == from || issuerId == to) - return tesSUCCESS; - auto const sleIssuer = view.read(keylet::account(issuerId)); - if (sleIssuer == nullptr) - return tefINTERNAL; // LCOV_EXCL_LINE - - auto const isRippleDisabled = [&](AccountID account) -> bool { - // Line might not exist, but some transfers can create it. If this - // is the case, just check the default ripple on the issuer account. - auto const line = view.read(keylet::line(account, issue)); - if (line) - { - bool const issuerHigh = issuerId > account; - return line->isFlag(issuerHigh ? lsfHighNoRipple : lsfLowNoRipple); - } - return sleIssuer->isFlag(lsfDefaultRipple) == false; - }; - - // Fail if rippling disabled on both trust lines - if (isRippleDisabled(from) && isRippleDisabled(to)) - return terNO_RIPPLE; - - return tesSUCCESS; -} - TER cleanupOnAccountDelete( ApplyView& view, @@ -3234,7 +469,7 @@ cleanupOnAccountDelete( { // Directory node has an invalid index. Bail out. // LCOV_EXCL_START - JLOG(j.fatal()) << "AccountDelete: Directory node in ledger " << view.seq() + JLOG(j.fatal()) << "DeleteAccount: Directory node in ledger " << view.seq() << " has index to object that is missing: " << to_string(dirEntry); return tefBAD_LEDGER; // LCOV_EXCL_STOP @@ -3269,7 +504,7 @@ cleanupOnAccountDelete( if (uDirEntry == 0) { // LCOV_EXCL_START - JLOG(j.error()) << "AccountDelete iterator re-validation failed."; + JLOG(j.error()) << "DeleteAccount iterator re-validation failed."; return tefBAD_LEDGER; // LCOV_EXCL_STOP } @@ -3282,447 +517,6 @@ cleanupOnAccountDelete( return tesSUCCESS; } -TER -deleteAMMTrustLine( - ApplyView& view, - std::shared_ptr sleState, - std::optional const& ammAccountID, - beast::Journal j) -{ - if (!sleState || sleState->getType() != ltRIPPLE_STATE) - return tecINTERNAL; // LCOV_EXCL_LINE - - auto const& [low, high] = std::minmax( - sleState->getFieldAmount(sfLowLimit).getIssuer(), - sleState->getFieldAmount(sfHighLimit).getIssuer()); - auto sleLow = view.peek(keylet::account(low)); - auto sleHigh = view.peek(keylet::account(high)); - if (!sleLow || !sleHigh) - return tecINTERNAL; // LCOV_EXCL_LINE - - bool const ammLow = sleLow->isFieldPresent(sfAMMID); - bool const ammHigh = sleHigh->isFieldPresent(sfAMMID); - - // can't both be AMM - if (ammLow && ammHigh) - return tecINTERNAL; // LCOV_EXCL_LINE - - // at least one must be - if (!ammLow && !ammHigh) - return terNO_AMM; - - // one must be the target amm - if (ammAccountID && (low != *ammAccountID && high != *ammAccountID)) - return terNO_AMM; - - if (auto const ter = trustDelete(view, sleState, low, high, j); !isTesSuccess(ter)) - { - JLOG(j.error()) << "deleteAMMTrustLine: failed to delete the trustline."; - return ter; - } - - auto const uFlags = !ammLow ? lsfLowReserve : lsfHighReserve; - if (!(sleState->getFlags() & uFlags)) - return tecINTERNAL; // LCOV_EXCL_LINE - - adjustOwnerCount(view, !ammLow ? sleLow : sleHigh, -1, j); - - return tesSUCCESS; -} - -TER -rippleCredit( - ApplyView& view, - AccountID const& uSenderID, - AccountID const& uReceiverID, - STAmount const& saAmount, - bool bCheckIssuer, - beast::Journal j) -{ - return std::visit( - [&](TIss const& issue) { - if constexpr (std::is_same_v) - { - return rippleCreditIOU(view, uSenderID, uReceiverID, saAmount, bCheckIssuer, j); - } - else - { - XRPL_ASSERT(!bCheckIssuer, "xrpl::rippleCredit : not checking issuer"); - return rippleCreditMPT(view, uSenderID, uReceiverID, saAmount, j); - } - }, - saAmount.asset().value()); -} - -[[nodiscard]] std::optional -assetsToSharesDeposit( - std::shared_ptr const& vault, - std::shared_ptr const& issuance, - STAmount const& assets) -{ - XRPL_ASSERT(!assets.negative(), "xrpl::assetsToSharesDeposit : non-negative assets"); - XRPL_ASSERT( - assets.asset() == vault->at(sfAsset), - "xrpl::assetsToSharesDeposit : assets and vault match"); - if (assets.negative() || assets.asset() != vault->at(sfAsset)) - return std::nullopt; // LCOV_EXCL_LINE - - Number const assetTotal = vault->at(sfAssetsTotal); - STAmount shares{vault->at(sfShareMPTID)}; - if (assetTotal == 0) - { - return STAmount{ - shares.asset(), - Number(assets.mantissa(), assets.exponent() + vault->at(sfScale)).truncate()}; - } - - Number const shareTotal = issuance->at(sfOutstandingAmount); - shares = ((shareTotal * assets) / assetTotal).truncate(); - return shares; -} - -[[nodiscard]] std::optional -sharesToAssetsDeposit( - std::shared_ptr const& vault, - std::shared_ptr const& issuance, - STAmount const& shares) -{ - XRPL_ASSERT(!shares.negative(), "xrpl::sharesToAssetsDeposit : non-negative shares"); - XRPL_ASSERT( - shares.asset() == vault->at(sfShareMPTID), - "xrpl::sharesToAssetsDeposit : shares and vault match"); - if (shares.negative() || shares.asset() != vault->at(sfShareMPTID)) - return std::nullopt; // LCOV_EXCL_LINE - - Number const assetTotal = vault->at(sfAssetsTotal); - STAmount assets{vault->at(sfAsset)}; - if (assetTotal == 0) - { - return STAmount{ - assets.asset(), shares.mantissa(), shares.exponent() - vault->at(sfScale), false}; - } - - Number const shareTotal = issuance->at(sfOutstandingAmount); - assets = (assetTotal * shares) / shareTotal; - return assets; -} - -[[nodiscard]] std::optional -assetsToSharesWithdraw( - std::shared_ptr const& vault, - std::shared_ptr const& issuance, - STAmount const& assets, - TruncateShares truncate) -{ - XRPL_ASSERT(!assets.negative(), "xrpl::assetsToSharesDeposit : non-negative assets"); - XRPL_ASSERT( - assets.asset() == vault->at(sfAsset), - "xrpl::assetsToSharesWithdraw : assets and vault match"); - if (assets.negative() || assets.asset() != vault->at(sfAsset)) - return std::nullopt; // LCOV_EXCL_LINE - - Number assetTotal = vault->at(sfAssetsTotal); - assetTotal -= vault->at(sfLossUnrealized); - STAmount shares{vault->at(sfShareMPTID)}; - if (assetTotal == 0) - return shares; - Number const shareTotal = issuance->at(sfOutstandingAmount); - Number result = (shareTotal * assets) / assetTotal; - if (truncate == TruncateShares::yes) - result = result.truncate(); - shares = result; - return shares; -} - -[[nodiscard]] std::optional -sharesToAssetsWithdraw( - std::shared_ptr const& vault, - std::shared_ptr const& issuance, - STAmount const& shares) -{ - XRPL_ASSERT(!shares.negative(), "xrpl::sharesToAssetsDeposit : non-negative shares"); - XRPL_ASSERT( - shares.asset() == vault->at(sfShareMPTID), - "xrpl::sharesToAssetsWithdraw : shares and vault match"); - if (shares.negative() || shares.asset() != vault->at(sfShareMPTID)) - return std::nullopt; // LCOV_EXCL_LINE - - Number assetTotal = vault->at(sfAssetsTotal); - assetTotal -= vault->at(sfLossUnrealized); - STAmount assets{vault->at(sfAsset)}; - if (assetTotal == 0) - return assets; - Number const shareTotal = issuance->at(sfOutstandingAmount); - assets = (assetTotal * shares) / shareTotal; - return assets; -} - -TER -rippleLockEscrowMPT( - ApplyView& view, - AccountID const& sender, - STAmount const& amount, - beast::Journal j) -{ - auto const mptIssue = amount.get(); - auto const mptID = keylet::mptIssuance(mptIssue.getMptID()); - auto sleIssuance = view.peek(mptID); - if (!sleIssuance) - { // LCOV_EXCL_START - JLOG(j.error()) << "rippleLockEscrowMPT: MPT issuance not found for " - << mptIssue.getMptID(); - return tecOBJECT_NOT_FOUND; - } // LCOV_EXCL_STOP - - if (amount.getIssuer() == sender) - { // LCOV_EXCL_START - JLOG(j.error()) << "rippleLockEscrowMPT: sender is the issuer, cannot lock MPTs."; - return tecINTERNAL; - } // LCOV_EXCL_STOP - - // 1. Decrease the MPT Holder MPTAmount - // 2. Increase the MPT Holder EscrowedAmount - { - auto const mptokenID = keylet::mptoken(mptID.key, sender); - auto sle = view.peek(mptokenID); - if (!sle) - { // LCOV_EXCL_START - JLOG(j.error()) << "rippleLockEscrowMPT: MPToken not found for " << sender; - return tecOBJECT_NOT_FOUND; - } // LCOV_EXCL_STOP - - auto const amt = sle->getFieldU64(sfMPTAmount); - auto const pay = amount.mpt().value(); - - // Underflow check for subtraction - if (!canSubtract(STAmount(mptIssue, amt), STAmount(mptIssue, pay))) - { // LCOV_EXCL_START - JLOG(j.error()) << "rippleLockEscrowMPT: insufficient MPTAmount for " - << to_string(sender) << ": " << amt << " < " << pay; - return tecINTERNAL; - } // LCOV_EXCL_STOP - - (*sle)[sfMPTAmount] = amt - pay; - - // Overflow check for addition - uint64_t const locked = (*sle)[~sfLockedAmount].value_or(0); - - if (!canAdd(STAmount(mptIssue, locked), STAmount(mptIssue, pay))) - { // LCOV_EXCL_START - JLOG(j.error()) << "rippleLockEscrowMPT: overflow on locked amount for " - << to_string(sender) << ": " << locked << " + " << pay; - return tecINTERNAL; - } // LCOV_EXCL_STOP - - if (sle->isFieldPresent(sfLockedAmount)) - { - (*sle)[sfLockedAmount] += pay; - } - else - { - sle->setFieldU64(sfLockedAmount, pay); - } - - view.update(sle); - } - - // 1. Increase the Issuance EscrowedAmount - // 2. DO NOT change the Issuance OutstandingAmount - { - uint64_t const issuanceEscrowed = (*sleIssuance)[~sfLockedAmount].value_or(0); - auto const pay = amount.mpt().value(); - - // Overflow check for addition - if (!canAdd(STAmount(mptIssue, issuanceEscrowed), STAmount(mptIssue, pay))) - { // LCOV_EXCL_START - JLOG(j.error()) << "rippleLockEscrowMPT: overflow on issuance " - "locked amount for " - << mptIssue.getMptID() << ": " << issuanceEscrowed << " + " << pay; - return tecINTERNAL; - } // LCOV_EXCL_STOP - - if (sleIssuance->isFieldPresent(sfLockedAmount)) - { - (*sleIssuance)[sfLockedAmount] += pay; - } - else - { - sleIssuance->setFieldU64(sfLockedAmount, pay); - } - - view.update(sleIssuance); - } - return tesSUCCESS; -} - -TER -rippleUnlockEscrowMPT( - ApplyView& view, - AccountID const& sender, - AccountID const& receiver, - STAmount const& netAmount, - STAmount const& grossAmount, - beast::Journal j) -{ - if (!view.rules().enabled(fixTokenEscrowV1)) - { - XRPL_ASSERT( - netAmount == grossAmount, "xrpl::rippleUnlockEscrowMPT : netAmount == grossAmount"); - } - - auto const& issuer = netAmount.getIssuer(); - auto const& mptIssue = netAmount.get(); - auto const mptID = keylet::mptIssuance(mptIssue.getMptID()); - auto sleIssuance = view.peek(mptID); - if (!sleIssuance) - { // LCOV_EXCL_START - JLOG(j.error()) << "rippleUnlockEscrowMPT: MPT issuance not found for " - << mptIssue.getMptID(); - return tecOBJECT_NOT_FOUND; - } // LCOV_EXCL_STOP - - // Decrease the Issuance EscrowedAmount - { - if (!sleIssuance->isFieldPresent(sfLockedAmount)) - { // LCOV_EXCL_START - JLOG(j.error()) << "rippleUnlockEscrowMPT: no locked amount in issuance for " - << mptIssue.getMptID(); - return tecINTERNAL; - } // LCOV_EXCL_STOP - - auto const locked = sleIssuance->getFieldU64(sfLockedAmount); - auto const redeem = grossAmount.mpt().value(); - - // Underflow check for subtraction - if (!canSubtract(STAmount(mptIssue, locked), STAmount(mptIssue, redeem))) - { // LCOV_EXCL_START - JLOG(j.error()) << "rippleUnlockEscrowMPT: insufficient locked amount for " - << mptIssue.getMptID() << ": " << locked << " < " << redeem; - return tecINTERNAL; - } // LCOV_EXCL_STOP - - auto const newLocked = locked - redeem; - if (newLocked == 0) - { - sleIssuance->makeFieldAbsent(sfLockedAmount); - } - else - { - sleIssuance->setFieldU64(sfLockedAmount, newLocked); - } - view.update(sleIssuance); - } - - if (issuer != receiver) - { - // Increase the MPT Holder MPTAmount - auto const mptokenID = keylet::mptoken(mptID.key, receiver); - auto sle = view.peek(mptokenID); - if (!sle) - { // LCOV_EXCL_START - JLOG(j.error()) << "rippleUnlockEscrowMPT: MPToken not found for " << receiver; - return tecOBJECT_NOT_FOUND; - } // LCOV_EXCL_STOP - - auto current = sle->getFieldU64(sfMPTAmount); - auto delta = netAmount.mpt().value(); - - // Overflow check for addition - if (!canAdd(STAmount(mptIssue, current), STAmount(mptIssue, delta))) - { // LCOV_EXCL_START - JLOG(j.error()) << "rippleUnlockEscrowMPT: overflow on MPTAmount for " - << to_string(receiver) << ": " << current << " + " << delta; - return tecINTERNAL; - } // LCOV_EXCL_STOP - - (*sle)[sfMPTAmount] += delta; - view.update(sle); - } - else - { - // Decrease the Issuance OutstandingAmount - auto const outstanding = sleIssuance->getFieldU64(sfOutstandingAmount); - auto const redeem = netAmount.mpt().value(); - - // Underflow check for subtraction - if (!canSubtract(STAmount(mptIssue, outstanding), STAmount(mptIssue, redeem))) - { // LCOV_EXCL_START - JLOG(j.error()) << "rippleUnlockEscrowMPT: insufficient outstanding amount for " - << mptIssue.getMptID() << ": " << outstanding << " < " << redeem; - return tecINTERNAL; - } // LCOV_EXCL_STOP - - sleIssuance->setFieldU64(sfOutstandingAmount, outstanding - redeem); - view.update(sleIssuance); - } - - if (issuer == sender) - { // LCOV_EXCL_START - JLOG(j.error()) << "rippleUnlockEscrowMPT: sender is the issuer, " - "cannot unlock MPTs."; - return tecINTERNAL; - } // LCOV_EXCL_STOP - - // Decrease the MPT Holder EscrowedAmount - auto const mptokenID = keylet::mptoken(mptID.key, sender); - auto sle = view.peek(mptokenID); - if (!sle) - { // LCOV_EXCL_START - JLOG(j.error()) << "rippleUnlockEscrowMPT: MPToken not found for " << sender; - return tecOBJECT_NOT_FOUND; - } // LCOV_EXCL_STOP - - if (!sle->isFieldPresent(sfLockedAmount)) - { // LCOV_EXCL_START - JLOG(j.error()) << "rippleUnlockEscrowMPT: no locked amount in MPToken for " - << to_string(sender); - return tecINTERNAL; - } // LCOV_EXCL_STOP - - auto const locked = sle->getFieldU64(sfLockedAmount); - auto const delta = grossAmount.mpt().value(); - - // Underflow check for subtraction - if (!canSubtract(STAmount(mptIssue, locked), STAmount(mptIssue, delta))) - { // LCOV_EXCL_START - JLOG(j.error()) << "rippleUnlockEscrowMPT: insufficient locked amount for " - << to_string(sender) << ": " << locked << " < " << delta; - return tecINTERNAL; - } // LCOV_EXCL_STOP - - auto const newLocked = locked - delta; - if (newLocked == 0) - { - sle->makeFieldAbsent(sfLockedAmount); - } - else - { - sle->setFieldU64(sfLockedAmount, newLocked); - } - view.update(sle); - - // Note: The gross amount is the amount that was locked, the net - // amount is the amount that is being unlocked. The difference is the fee - // that was charged for the transfer. If this difference is greater than - // zero, we need to update the outstanding amount. - auto const diff = grossAmount.mpt().value() - netAmount.mpt().value(); - if (diff != 0) - { - auto const outstanding = sleIssuance->getFieldU64(sfOutstandingAmount); - // Underflow check for subtraction - if (!canSubtract(STAmount(mptIssue, outstanding), STAmount(mptIssue, diff))) - { // LCOV_EXCL_START - JLOG(j.error()) << "rippleUnlockEscrowMPT: insufficient outstanding amount for " - << mptIssue.getMptID() << ": " << outstanding << " < " << diff; - return tecINTERNAL; - } // LCOV_EXCL_STOP - - sleIssuance->setFieldU64(sfOutstandingAmount, outstanding - diff); - view.update(sleIssuance); - } - return tesSUCCESS; -} - bool after(NetClock::time_point now, std::uint32_t mark) { diff --git a/src/libxrpl/ledger/helpers/AccountRootHelpers.cpp b/src/libxrpl/ledger/helpers/AccountRootHelpers.cpp new file mode 100644 index 0000000000..399494bc5f --- /dev/null +++ b/src/libxrpl/ledger/helpers/AccountRootHelpers.cpp @@ -0,0 +1,247 @@ +#include +// +#include +#include +#include +#include +#include + +#include +#include + +namespace xrpl { + +bool +isGlobalFrozen(ReadView const& view, AccountID const& issuer) +{ + if (isXRP(issuer)) + return false; + if (auto const sle = view.read(keylet::account(issuer))) + return sle->isFlag(lsfGlobalFreeze); + return false; +} + +// An owner count cannot be negative. If adjustment would cause a negative +// owner count, clamp the owner count at 0. Similarly for overflow. This +// adjustment allows the ownerCount to be adjusted up or down in multiple steps. +// If id != std::nullopt, then do error reporting. +// +// Returns adjusted owner count. +static std::uint32_t +confineOwnerCount( + std::uint32_t current, + std::int32_t adjustment, + std::optional const& id = std::nullopt, + beast::Journal j = beast::Journal{beast::Journal::getNullSink()}) +{ + std::uint32_t adjusted{current + adjustment}; + if (adjustment > 0) + { + // Overflow is well defined on unsigned + if (adjusted < current) + { + if (id) + { + JLOG(j.fatal()) << "Account " << *id << " owner count exceeds max!"; + } + adjusted = std::numeric_limits::max(); + } + } + else + { + // Underflow is well defined on unsigned + if (adjusted > current) + { + if (id) + { + JLOG(j.fatal()) << "Account " << *id << " owner count set below 0!"; + } + adjusted = 0; + XRPL_ASSERT(!id, "xrpl::confineOwnerCount : id is not set"); + } + } + return adjusted; +} + +XRPAmount +xrpLiquid(ReadView const& view, AccountID const& id, std::int32_t ownerCountAdj, beast::Journal j) +{ + auto const sle = view.read(keylet::account(id)); + if (sle == nullptr) + return beast::zero; + + // Return balance minus reserve + std::uint32_t const ownerCount = + confineOwnerCount(view.ownerCountHook(id, sle->getFieldU32(sfOwnerCount)), ownerCountAdj); + + // Pseudo-accounts have no reserve requirement + auto const reserve = + isPseudoAccount(sle) ? XRPAmount{0} : view.fees().accountReserve(ownerCount); + + auto const fullBalance = sle->getFieldAmount(sfBalance); + + auto const balance = view.balanceHook(id, xrpAccount(), fullBalance); + + STAmount const amount = (balance < reserve) ? STAmount{0} : balance - reserve; + + JLOG(j.trace()) << "accountHolds:" << " account=" << to_string(id) + << " amount=" << amount.getFullText() + << " fullBalance=" << fullBalance.getFullText() + << " balance=" << balance.getFullText() << " reserve=" << reserve + << " ownerCount=" << ownerCount << " ownerCountAdj=" << ownerCountAdj; + + return amount.xrp(); +} + +Rate +transferRate(ReadView const& view, AccountID const& issuer) +{ + auto const sle = view.read(keylet::account(issuer)); + + if (sle && sle->isFieldPresent(sfTransferRate)) + return Rate{sle->getFieldU32(sfTransferRate)}; + + return parityRate; +} + +void +adjustOwnerCount( + ApplyView& view, + std::shared_ptr const& sle, + std::int32_t amount, + beast::Journal j) +{ + if (!sle) + return; + XRPL_ASSERT(amount, "xrpl::adjustOwnerCount : nonzero amount input"); + std::uint32_t const current{sle->getFieldU32(sfOwnerCount)}; + AccountID const id = (*sle)[sfAccount]; + std::uint32_t const adjusted = confineOwnerCount(current, amount, id, j); + view.adjustOwnerCountHook(id, current, adjusted); + sle->at(sfOwnerCount) = adjusted; + view.update(sle); +} + +AccountID +pseudoAccountAddress(ReadView const& view, uint256 const& pseudoOwnerKey) +{ + // This number must not be changed without an amendment + constexpr std::uint16_t maxAccountAttempts = 256; + for (std::uint16_t i = 0; i < maxAccountAttempts; ++i) + { + ripesha_hasher rsh; + auto const hash = sha512Half(i, view.header().parentHash, pseudoOwnerKey); + rsh(hash.data(), hash.size()); + AccountID const ret{static_cast(rsh)}; + if (!view.read(keylet::account(ret))) + return ret; + } + return beast::zero; +} + +// Pseudo-account designator fields MUST be maintained by including the +// SField::sMD_PseudoAccount flag in the SField definition. (Don't forget to +// "| SField::sMD_Default"!) The fields do NOT need to be amendment-gated, +// since a non-active amendment will not set any field, by definition. +// Specific properties of a pseudo-account are NOT checked here, that's what +// InvariantCheck is for. +[[nodiscard]] std::vector const& +getPseudoAccountFields() +{ + static std::vector const pseudoFields = []() { + auto const ar = LedgerFormats::getInstance().findByType(ltACCOUNT_ROOT); + if (!ar) + { + // LCOV_EXCL_START + LogicError( + "xrpl::getPseudoAccountFields : unable to find account root " + "ledger format"); + // LCOV_EXCL_STOP + } + auto const& soTemplate = ar->getSOTemplate(); + + std::vector pseudoFields; + for (auto const& field : soTemplate) + { + if (field.sField().shouldMeta(SField::sMD_PseudoAccount)) + pseudoFields.emplace_back(&field.sField()); + } + return pseudoFields; + }(); + return pseudoFields; +} + +[[nodiscard]] bool +isPseudoAccount( + std::shared_ptr sleAcct, + std::set const& pseudoFieldFilter) +{ + auto const& fields = getPseudoAccountFields(); + + // Intentionally use defensive coding here because it's cheap and makes the + // semantics of true return value clean. + return sleAcct && sleAcct->getType() == ltACCOUNT_ROOT && + std::count_if( + fields.begin(), fields.end(), [&sleAcct, &pseudoFieldFilter](SField const* sf) -> bool { + return sleAcct->isFieldPresent(*sf) && + (pseudoFieldFilter.empty() || pseudoFieldFilter.contains(sf)); + }) > 0; +} + +Expected, TER> +createPseudoAccount(ApplyView& view, uint256 const& pseudoOwnerKey, SField const& ownerField) +{ + [[maybe_unused]] + auto const& fields = getPseudoAccountFields(); + XRPL_ASSERT( + std::count_if( + fields.begin(), + fields.end(), + [&ownerField](SField const* sf) -> bool { return *sf == ownerField; }) == 1, + "xrpl::createPseudoAccount : valid owner field"); + + auto const accountId = pseudoAccountAddress(view, pseudoOwnerKey); + if (accountId == beast::zero) + return Unexpected(tecDUPLICATE); + + // Create pseudo-account. + auto account = std::make_shared(keylet::account(accountId)); + account->setAccountID(sfAccount, accountId); + account->setFieldAmount(sfBalance, STAmount{}); + + // Pseudo-accounts can't submit transactions, so set the sequence number + // to 0 to make them easier to spot and verify, and add an extra level + // of protection. + std::uint32_t const seqno = // + view.rules().enabled(featureSingleAssetVault) || // + view.rules().enabled(featureLendingProtocol) // + ? 0 // + : view.seq(); + account->setFieldU32(sfSequence, seqno); + // Ignore reserves requirement, disable the master key, allow default + // rippling, and enable deposit authorization to prevent payments into + // pseudo-account. + account->setFieldU32(sfFlags, lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth); + // Link the pseudo-account with its owner object. + account->setFieldH256(ownerField, pseudoOwnerKey); + + view.insert(account); + + return account; +} + +[[nodiscard]] TER +checkDestinationAndTag(SLE::const_ref toSle, bool hasDestinationTag) +{ + if (toSle == nullptr) + return tecNO_DST; + + // The tag is basically account-specific information we don't + // understand, but we can require someone to fill it in. + if (toSle->isFlag(lsfRequireDestTag) && !hasDestinationTag) + return tecDST_TAG_NEEDED; // Cannot send without a tag + + return tesSUCCESS; +} + +} // namespace xrpl diff --git a/src/libxrpl/ledger/CredentialHelpers.cpp b/src/libxrpl/ledger/helpers/CredentialHelpers.cpp similarity index 99% rename from src/libxrpl/ledger/CredentialHelpers.cpp rename to src/libxrpl/ledger/helpers/CredentialHelpers.cpp index 0782eda67d..234ca7ea17 100644 --- a/src/libxrpl/ledger/CredentialHelpers.cpp +++ b/src/libxrpl/ledger/helpers/CredentialHelpers.cpp @@ -1,5 +1,7 @@ -#include +#include +// #include +#include #include #include diff --git a/src/libxrpl/ledger/helpers/DirectoryHelpers.cpp b/src/libxrpl/ledger/helpers/DirectoryHelpers.cpp new file mode 100644 index 0000000000..f0ca83f2cd --- /dev/null +++ b/src/libxrpl/ledger/helpers/DirectoryHelpers.cpp @@ -0,0 +1,177 @@ +#include +// +#include + +namespace xrpl { + +bool +dirFirst( + ApplyView& view, + uint256 const& root, + std::shared_ptr& page, + unsigned int& index, + uint256& entry) +{ + return detail::internalDirFirst(view, root, page, index, entry); +} + +bool +dirNext( + ApplyView& view, + uint256 const& root, + std::shared_ptr& page, + unsigned int& index, + uint256& entry) +{ + return detail::internalDirNext(view, root, page, index, entry); +} + +bool +cdirFirst( + ReadView const& view, + uint256 const& root, + std::shared_ptr& page, + unsigned int& index, + uint256& entry) +{ + return detail::internalDirFirst(view, root, page, index, entry); +} + +bool +cdirNext( + ReadView const& view, + uint256 const& root, + std::shared_ptr& page, + unsigned int& index, + uint256& entry) +{ + return detail::internalDirNext(view, root, page, index, entry); +} + +void +forEachItem( + ReadView const& view, + Keylet const& root, + std::function const&)> const& f) +{ + XRPL_ASSERT(root.type == ltDIR_NODE, "xrpl::forEachItem : valid root type"); + + if (root.type != ltDIR_NODE) + return; + + auto pos = root; + + while (true) + { + auto sle = view.read(pos); + if (!sle) + return; + for (auto const& key : sle->getFieldV256(sfIndexes)) + f(view.read(keylet::child(key))); + auto const next = sle->getFieldU64(sfIndexNext); + if (!next) + return; + pos = keylet::page(root, next); + } +} + +bool +forEachItemAfter( + ReadView const& view, + Keylet const& root, + uint256 const& after, + std::uint64_t const hint, + unsigned int limit, + std::function const&)> const& f) +{ + XRPL_ASSERT(root.type == ltDIR_NODE, "xrpl::forEachItemAfter : valid root type"); + + if (root.type != ltDIR_NODE) + return false; + + auto currentIndex = root; + + // If startAfter is not zero try jumping to that page using the hint + if (after.isNonZero()) + { + auto const hintIndex = keylet::page(root, hint); + + if (auto hintDir = view.read(hintIndex)) + { + for (auto const& key : hintDir->getFieldV256(sfIndexes)) + { + if (key == after) + { + // We found the hint, we can start here + currentIndex = hintIndex; + break; + } + } + } + + bool found = false; + for (;;) + { + auto const ownerDir = view.read(currentIndex); + if (!ownerDir) + return found; + for (auto const& key : ownerDir->getFieldV256(sfIndexes)) + { + if (!found) + { + if (key == after) + found = true; + } + else if (f(view.read(keylet::child(key))) && limit-- <= 1) + { + return found; + } + } + + auto const uNodeNext = ownerDir->getFieldU64(sfIndexNext); + if (uNodeNext == 0) + return found; + currentIndex = keylet::page(root, uNodeNext); + } + } + else + { + for (;;) + { + auto const ownerDir = view.read(currentIndex); + if (!ownerDir) + return true; + for (auto const& key : ownerDir->getFieldV256(sfIndexes)) + { + if (f(view.read(keylet::child(key))) && limit-- <= 1) + return true; + } + auto const uNodeNext = ownerDir->getFieldU64(sfIndexNext); + if (uNodeNext == 0) + return true; + currentIndex = keylet::page(root, uNodeNext); + } + } +} + +bool +dirIsEmpty(ReadView const& view, Keylet const& k) +{ + auto const sleNode = view.read(k); + if (!sleNode) + return true; + if (!sleNode->getFieldV256(sfIndexes).empty()) + return false; + // The first page of a directory may legitimately be empty even if there + // are other pages (the first page is the anchor page) so check to see if + // there is another page. If there is, the directory isn't empty. + return sleNode->getFieldU64(sfIndexNext) == 0; +} + +std::function +describeOwnerDir(AccountID const& account) +{ + return [account](std::shared_ptr const& sle) { (*sle)[sfOwner] = account; }; +} + +} // namespace xrpl diff --git a/src/libxrpl/ledger/helpers/MPTokenHelpers.cpp b/src/libxrpl/ledger/helpers/MPTokenHelpers.cpp new file mode 100644 index 0000000000..cbf37a06a8 --- /dev/null +++ b/src/libxrpl/ledger/helpers/MPTokenHelpers.cpp @@ -0,0 +1,766 @@ +#include +// +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace xrpl { + +// Forward declarations for functions that remain in View.h/cpp +bool +isVaultPseudoAccountFrozen( + ReadView const& view, + AccountID const& account, + MPTIssue const& mptShare, + int depth); + +[[nodiscard]] TER +dirLink( + ApplyView& view, + AccountID const& owner, + std::shared_ptr& object, + SF_UINT64 const& node = sfOwnerNode); + +bool +isGlobalFrozen(ReadView const& view, MPTIssue const& mptIssue) +{ + if (auto const sle = view.read(keylet::mptIssuance(mptIssue.getMptID()))) + return sle->isFlag(lsfMPTLocked); + return false; +} + +bool +isIndividualFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue) +{ + if (auto const sle = view.read(keylet::mptoken(mptIssue.getMptID(), account))) + return sle->isFlag(lsfMPTLocked); + return false; +} + +bool +isFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue, int depth) +{ + return isGlobalFrozen(view, mptIssue) || isIndividualFrozen(view, account, mptIssue) || + isVaultPseudoAccountFrozen(view, account, mptIssue, depth); +} + +[[nodiscard]] bool +isAnyFrozen( + ReadView const& view, + std::initializer_list const& accounts, + MPTIssue const& mptIssue, + int depth) +{ + if (isGlobalFrozen(view, mptIssue)) + return true; + + for (auto const& account : accounts) + { + if (isIndividualFrozen(view, account, mptIssue)) + return true; + } + + for (auto const& account : accounts) + { + if (isVaultPseudoAccountFrozen(view, account, mptIssue, depth)) + return true; + } + + return false; +} + +Rate +transferRate(ReadView const& view, MPTID const& issuanceID) +{ + // fee is 0-50,000 (0-50%), rate is 1,000,000,000-2,000,000,000 + // For example, if transfer fee is 50% then 10,000 * 50,000 = 500,000 + // 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)}; + + return parityRate; +} + +[[nodiscard]] TER +canAddHolding(ReadView const& view, MPTIssue const& mptIssue) +{ + auto mptID = mptIssue.getMptID(); + auto issuance = view.read(keylet::mptIssuance(mptID)); + if (!issuance) + { + return tecOBJECT_NOT_FOUND; + } + if (!issuance->isFlag(lsfMPTCanTransfer)) + { + return tecNO_AUTH; + } + + return tesSUCCESS; +} + +[[nodiscard]] TER +addEmptyHolding( + ApplyView& view, + AccountID const& accountID, + XRPAmount priorBalance, + MPTIssue const& mptIssue, + beast::Journal journal) +{ + auto const& mptID = mptIssue.getMptID(); + auto const mpt = view.peek(keylet::mptIssuance(mptID)); + if (!mpt) + return tefINTERNAL; // LCOV_EXCL_LINE + if (mpt->isFlag(lsfMPTLocked)) + return tefINTERNAL; // LCOV_EXCL_LINE + if (view.peek(keylet::mptoken(mptID, accountID))) + return tecDUPLICATE; + if (accountID == mptIssue.getIssuer()) + return tesSUCCESS; + + return authorizeMPToken(view, priorBalance, mptID, accountID, journal); +} + +[[nodiscard]] TER +authorizeMPToken( + ApplyView& view, + XRPAmount const& priorBalance, + MPTID const& mptIssuanceID, + AccountID const& account, + beast::Journal journal, + std::uint32_t flags, + std::optional holderID) +{ + auto const sleAcct = view.peek(keylet::account(account)); + if (!sleAcct) + return tecINTERNAL; // LCOV_EXCL_LINE + + // If the account that submitted the tx is a holder + // Note: `account_` is holder's account + // `holderID` is NOT used + if (!holderID) + { + // When a holder wants to unauthorize/delete a MPT, the ledger must + // - delete mptokenKey from owner directory + // - delete the MPToken + if (flags & tfMPTUnauthorize) + { + auto const mptokenKey = keylet::mptoken(mptIssuanceID, account); + auto const sleMpt = view.peek(mptokenKey); + if (!sleMpt || (*sleMpt)[sfMPTAmount] != 0) + return tecINTERNAL; // LCOV_EXCL_LINE + + if (!view.dirRemove( + keylet::ownerDir(account), (*sleMpt)[sfOwnerNode], sleMpt->key(), false)) + return tecINTERNAL; // LCOV_EXCL_LINE + + adjustOwnerCount(view, sleAcct, -1, journal); + + view.erase(sleMpt); + return tesSUCCESS; + } + + // A potential holder wants to authorize/hold a mpt, the ledger must: + // - add the new mptokenKey to the owner directory + // - create the MPToken object for the holder + + // The reserve that is required to create the MPToken. Note + // that although the reserve increases with every item + // an account owns, in the case of MPTokens we only + // *enforce* a reserve if the user owns more than two + // items. This is similar to the reserve requirements of trust lines. + std::uint32_t const uOwnerCount = sleAcct->getFieldU32(sfOwnerCount); + XRPAmount const reserveCreate( + (uOwnerCount < 2) ? XRPAmount(beast::zero) + : view.fees().accountReserve(uOwnerCount + 1)); + + if (priorBalance < reserveCreate) + return tecINSUFFICIENT_RESERVE; + + // Defensive check before we attempt to create MPToken for the issuer + auto const mpt = view.read(keylet::mptIssuance(mptIssuanceID)); + if (!mpt || mpt->getAccountID(sfIssuer) == account) + { + // LCOV_EXCL_START + UNREACHABLE("xrpl::authorizeMPToken : invalid issuance or issuers token"); + if (view.rules().enabled(featureLendingProtocol)) + return tecINTERNAL; + // LCOV_EXCL_STOP + } + + auto const mptokenKey = keylet::mptoken(mptIssuanceID, account); + auto mptoken = std::make_shared(mptokenKey); + if (auto ter = dirLink(view, account, mptoken)) + return ter; // LCOV_EXCL_LINE + + (*mptoken)[sfAccount] = account; + (*mptoken)[sfMPTokenIssuanceID] = mptIssuanceID; + (*mptoken)[sfFlags] = 0; + view.insert(mptoken); + + // Update owner count. + adjustOwnerCount(view, sleAcct, 1, journal); + + return tesSUCCESS; + } + + auto const sleMptIssuance = view.read(keylet::mptIssuance(mptIssuanceID)); + if (!sleMptIssuance) + return tecINTERNAL; // LCOV_EXCL_LINE + + // If the account that submitted this tx is the issuer of the MPT + // Note: `account_` is issuer's account + // `holderID` is holder's account + if (account != (*sleMptIssuance)[sfIssuer]) + return tecINTERNAL; // LCOV_EXCL_LINE + + auto const sleMpt = view.peek(keylet::mptoken(mptIssuanceID, *holderID)); + if (!sleMpt) + return tecINTERNAL; // LCOV_EXCL_LINE + + std::uint32_t const flagsIn = sleMpt->getFieldU32(sfFlags); + std::uint32_t flagsOut = flagsIn; + + // Issuer wants to unauthorize the holder, unset lsfMPTAuthorized on + // their MPToken + if (flags & tfMPTUnauthorize) + { + flagsOut &= ~lsfMPTAuthorized; + } + // Issuer wants to authorize a holder, set lsfMPTAuthorized on their + // MPToken + else + { + flagsOut |= lsfMPTAuthorized; + } + + if (flagsIn != flagsOut) + sleMpt->setFieldU32(sfFlags, flagsOut); + + view.update(sleMpt); + return tesSUCCESS; +} + +[[nodiscard]] TER +removeEmptyHolding( + ApplyView& view, + AccountID const& accountID, + MPTIssue const& mptIssue, + beast::Journal journal) +{ + // If the account is the issuer, then no token should exist. MPTs do not + // have the legacy ability to create such a situation, but check anyway. If + // a token does exist, it will get deleted. If not, return success. + bool const accountIsIssuer = accountID == mptIssue.getIssuer(); + auto const& mptID = mptIssue.getMptID(); + auto const mptoken = view.peek(keylet::mptoken(mptID, accountID)); + if (!mptoken) + return accountIsIssuer ? (TER)tesSUCCESS : (TER)tecOBJECT_NOT_FOUND; + // Unlike a trust line, if the account is the issuer, and the token has a + // balance, it can not just be deleted, because that will throw the issuance + // accounting out of balance, so fail. Since this should be impossible + // anyway, I'm not going to put any effort into it. + if (mptoken->at(sfMPTAmount) != 0) + return tecHAS_OBLIGATIONS; + + return authorizeMPToken( + view, + {}, // priorBalance + mptID, + accountID, + journal, + tfMPTUnauthorize // flags + ); +} + +[[nodiscard]] TER +requireAuth( + ReadView const& view, + MPTIssue const& mptIssue, + AccountID const& account, + AuthType authType, + int depth) +{ + auto const mptID = keylet::mptIssuance(mptIssue.getMptID()); + auto const sleIssuance = view.read(mptID); + if (!sleIssuance) + return tecOBJECT_NOT_FOUND; + + auto const mptIssuer = sleIssuance->getAccountID(sfIssuer); + + // issuer is always "authorized" + if (mptIssuer == account) // Issuer won't have MPToken + return tesSUCCESS; + + bool const featureSAVEnabled = view.rules().enabled(featureSingleAssetVault); + + if (featureSAVEnabled) + { + if (depth >= maxAssetCheckDepth) + return tecINTERNAL; // LCOV_EXCL_LINE + + // requireAuth is recursive if the issuer is a vault pseudo-account + auto const sleIssuer = view.read(keylet::account(mptIssuer)); + if (!sleIssuer) + return tefINTERNAL; // LCOV_EXCL_LINE + + if (sleIssuer->isFieldPresent(sfVaultID)) + { + auto const sleVault = view.read(keylet::vault(sleIssuer->getFieldH256(sfVaultID))); + if (!sleVault) + return tefINTERNAL; // LCOV_EXCL_LINE + + auto const asset = sleVault->at(sfAsset); + if (auto const err = std::visit( + [&](TIss const& issue) { + if constexpr (std::is_same_v) + { + return requireAuth(view, issue, account, authType); + } + else + { + return requireAuth(view, issue, account, authType, depth + 1); + } + }, + asset.value()); + !isTesSuccess(err)) + return err; + } + } + + auto const mptokenID = keylet::mptoken(mptID.key, account); + auto const sleToken = view.read(mptokenID); + + // if account has no MPToken, fail + if (!sleToken && (authType == AuthType::StrongAuth || authType == AuthType::Legacy)) + return tecNO_AUTH; + + // Note, this check is not amendment-gated because DomainID will be always + // empty **unless** writing to it has been enabled by an amendment + auto const maybeDomainID = sleIssuance->at(~sfDomainID); + if (maybeDomainID) + { + XRPL_ASSERT( + sleIssuance->getFieldU32(sfFlags) & lsfMPTRequireAuth, + "xrpl::requireAuth : issuance requires authorization"); + // ter = tefINTERNAL | tecOBJECT_NOT_FOUND | tecNO_AUTH | tecEXPIRED + auto const ter = credentials::validDomain(view, *maybeDomainID, account); + if (isTesSuccess(ter)) + { + return ter; // Note: sleToken might be null + } + if (!sleToken) + { + return ter; + } + // We ignore error from validDomain if we found sleToken, as it could + // belong to someone who is explicitly authorized e.g. a vault owner. + } + + if (featureSAVEnabled) + { + // Implicitly authorize Vault and LoanBroker pseudo-accounts + if (isPseudoAccount(view, account, {&sfVaultID, &sfLoanBrokerID})) + return tesSUCCESS; + } + + // mptoken must be authorized if issuance enabled requireAuth + if (sleIssuance->isFlag(lsfMPTRequireAuth) && + (!sleToken || !sleToken->isFlag(lsfMPTAuthorized))) + return tecNO_AUTH; + + return tesSUCCESS; // Note: sleToken might be null +} + +[[nodiscard]] TER +enforceMPTokenAuthorization( + ApplyView& view, + MPTID const& mptIssuanceID, + AccountID const& account, + XRPAmount const& priorBalance, // for MPToken authorization + beast::Journal j) +{ + auto const sleIssuance = view.read(keylet::mptIssuance(mptIssuanceID)); + if (!sleIssuance) + return tefINTERNAL; // LCOV_EXCL_LINE + + XRPL_ASSERT( + sleIssuance->isFlag(lsfMPTRequireAuth), + "xrpl::enforceMPTokenAuthorization : authorization required"); + + if (account == sleIssuance->at(sfIssuer)) + return tefINTERNAL; // LCOV_EXCL_LINE + + auto const keylet = keylet::mptoken(mptIssuanceID, account); + auto const sleToken = view.read(keylet); // NOTE: might be null + auto const maybeDomainID = sleIssuance->at(~sfDomainID); + bool expired = false; + bool const authorizedByDomain = [&]() -> bool { + // NOTE: defensive here, should be checked in preclaim + if (!maybeDomainID.has_value()) + return false; // LCOV_EXCL_LINE + + auto const ter = verifyValidDomain(view, account, *maybeDomainID, j); + if (isTesSuccess(ter)) + return true; + if (ter == tecEXPIRED) + expired = true; + return false; + }(); + + if (!authorizedByDomain && sleToken == nullptr) + { + // Could not find MPToken and won't create one, could be either of: + // + // 1. Field sfDomainID not set in MPTokenIssuance or + // 2. Account has no matching and accepted credentials or + // 3. Account has all expired credentials (deleted in verifyValidDomain) + // + // Either way, return tecNO_AUTH and there is nothing else to do + return expired ? tecEXPIRED : tecNO_AUTH; + } + if (!authorizedByDomain && maybeDomainID.has_value()) + { + // Found an MPToken but the account is not authorized and we expect + // it to have been authorized by the domain. This could be because the + // credentials used to create the MPToken have expired or been deleted. + return expired ? tecEXPIRED : tecNO_AUTH; + } + if (!authorizedByDomain) + { + // We found an MPToken, but sfDomainID is not set, so this is a classic + // MPToken which requires authorization by the token issuer. + XRPL_ASSERT( + sleToken != nullptr && !maybeDomainID.has_value(), + "xrpl::enforceMPTokenAuthorization : found MPToken"); + if (sleToken->isFlag(lsfMPTAuthorized)) + return tesSUCCESS; + + return tecNO_AUTH; + } + if (authorizedByDomain && sleToken != nullptr) + { + // Found an MPToken, authorized by the domain. Ignore authorization flag + // lsfMPTAuthorized because it is meaningless. Return tesSUCCESS + XRPL_ASSERT( + maybeDomainID.has_value(), + "xrpl::enforceMPTokenAuthorization : found MPToken for domain"); + return tesSUCCESS; + } + if (authorizedByDomain) + { + // Could not find MPToken but there should be one because we are + // authorized by domain. Proceed to create it, then return tesSUCCESS + XRPL_ASSERT( + maybeDomainID.has_value() && sleToken == nullptr, + "xrpl::enforceMPTokenAuthorization : new MPToken for domain"); + if (auto const err = authorizeMPToken( + view, + priorBalance, // priorBalance + mptIssuanceID, // mptIssuanceID + account, // account + j); + !isTesSuccess(err)) + return err; + + return tesSUCCESS; + } + + // LCOV_EXCL_START + UNREACHABLE("xrpl::enforceMPTokenAuthorization : condition list is incomplete"); + return tefINTERNAL; + // LCOV_EXCL_STOP +} + +TER +canTransfer( + ReadView const& view, + MPTIssue const& mptIssue, + AccountID const& from, + AccountID const& to) +{ + auto const mptID = keylet::mptIssuance(mptIssue.getMptID()); + auto const sleIssuance = view.read(mptID); + if (!sleIssuance) + return tecOBJECT_NOT_FOUND; + + if (!(sleIssuance->getFieldU32(sfFlags) & lsfMPTCanTransfer)) + { + if (from != (*sleIssuance)[sfIssuer] && to != (*sleIssuance)[sfIssuer]) + return TER{tecNO_AUTH}; + } + return tesSUCCESS; +} + +TER +rippleLockEscrowMPT( + ApplyView& view, + AccountID const& sender, + STAmount const& amount, + beast::Journal j) +{ + auto const mptIssue = amount.get(); + auto const mptID = keylet::mptIssuance(mptIssue.getMptID()); + auto sleIssuance = view.peek(mptID); + if (!sleIssuance) + { // LCOV_EXCL_START + JLOG(j.error()) << "rippleLockEscrowMPT: MPT issuance not found for " + << mptIssue.getMptID(); + return tecOBJECT_NOT_FOUND; + } // LCOV_EXCL_STOP + + if (amount.getIssuer() == sender) + { // LCOV_EXCL_START + JLOG(j.error()) << "rippleLockEscrowMPT: sender is the issuer, cannot lock MPTs."; + return tecINTERNAL; + } // LCOV_EXCL_STOP + + // 1. Decrease the MPT Holder MPTAmount + // 2. Increase the MPT Holder EscrowedAmount + { + auto const mptokenID = keylet::mptoken(mptID.key, sender); + auto sle = view.peek(mptokenID); + if (!sle) + { // LCOV_EXCL_START + JLOG(j.error()) << "rippleLockEscrowMPT: MPToken not found for " << sender; + return tecOBJECT_NOT_FOUND; + } // LCOV_EXCL_STOP + + auto const amt = sle->getFieldU64(sfMPTAmount); + auto const pay = amount.mpt().value(); + + // Underflow check for subtraction + if (!canSubtract(STAmount(mptIssue, amt), STAmount(mptIssue, pay))) + { // LCOV_EXCL_START + JLOG(j.error()) << "rippleLockEscrowMPT: insufficient MPTAmount for " + << to_string(sender) << ": " << amt << " < " << pay; + return tecINTERNAL; + } // LCOV_EXCL_STOP + + (*sle)[sfMPTAmount] = amt - pay; + + // Overflow check for addition + uint64_t const locked = (*sle)[~sfLockedAmount].value_or(0); + + if (!canAdd(STAmount(mptIssue, locked), STAmount(mptIssue, pay))) + { // LCOV_EXCL_START + JLOG(j.error()) << "rippleLockEscrowMPT: overflow on locked amount for " + << to_string(sender) << ": " << locked << " + " << pay; + return tecINTERNAL; + } // LCOV_EXCL_STOP + + if (sle->isFieldPresent(sfLockedAmount)) + { + (*sle)[sfLockedAmount] += pay; + } + else + { + sle->setFieldU64(sfLockedAmount, pay); + } + + view.update(sle); + } + + // 1. Increase the Issuance EscrowedAmount + // 2. DO NOT change the Issuance OutstandingAmount + { + uint64_t const issuanceEscrowed = (*sleIssuance)[~sfLockedAmount].value_or(0); + auto const pay = amount.mpt().value(); + + // Overflow check for addition + if (!canAdd(STAmount(mptIssue, issuanceEscrowed), STAmount(mptIssue, pay))) + { // LCOV_EXCL_START + JLOG(j.error()) << "rippleLockEscrowMPT: overflow on issuance " + "locked amount for " + << mptIssue.getMptID() << ": " << issuanceEscrowed << " + " << pay; + return tecINTERNAL; + } // LCOV_EXCL_STOP + + if (sleIssuance->isFieldPresent(sfLockedAmount)) + { + (*sleIssuance)[sfLockedAmount] += pay; + } + else + { + sleIssuance->setFieldU64(sfLockedAmount, pay); + } + + view.update(sleIssuance); + } + return tesSUCCESS; +} + +TER +rippleUnlockEscrowMPT( + ApplyView& view, + AccountID const& sender, + AccountID const& receiver, + STAmount const& netAmount, + STAmount const& grossAmount, + beast::Journal j) +{ + if (!view.rules().enabled(fixTokenEscrowV1)) + { + XRPL_ASSERT( + netAmount == grossAmount, "xrpl::rippleUnlockEscrowMPT : netAmount == grossAmount"); + } + + auto const& issuer = netAmount.getIssuer(); + auto const& mptIssue = netAmount.get(); + auto const mptID = keylet::mptIssuance(mptIssue.getMptID()); + auto sleIssuance = view.peek(mptID); + if (!sleIssuance) + { // LCOV_EXCL_START + JLOG(j.error()) << "rippleUnlockEscrowMPT: MPT issuance not found for " + << mptIssue.getMptID(); + return tecOBJECT_NOT_FOUND; + } // LCOV_EXCL_STOP + + // Decrease the Issuance EscrowedAmount + { + if (!sleIssuance->isFieldPresent(sfLockedAmount)) + { // LCOV_EXCL_START + JLOG(j.error()) << "rippleUnlockEscrowMPT: no locked amount in issuance for " + << mptIssue.getMptID(); + return tecINTERNAL; + } // LCOV_EXCL_STOP + + auto const locked = sleIssuance->getFieldU64(sfLockedAmount); + auto const redeem = grossAmount.mpt().value(); + + // Underflow check for subtraction + if (!canSubtract(STAmount(mptIssue, locked), STAmount(mptIssue, redeem))) + { // LCOV_EXCL_START + JLOG(j.error()) << "rippleUnlockEscrowMPT: insufficient locked amount for " + << mptIssue.getMptID() << ": " << locked << " < " << redeem; + return tecINTERNAL; + } // LCOV_EXCL_STOP + + auto const newLocked = locked - redeem; + if (newLocked == 0) + { + sleIssuance->makeFieldAbsent(sfLockedAmount); + } + else + { + sleIssuance->setFieldU64(sfLockedAmount, newLocked); + } + view.update(sleIssuance); + } + + if (issuer != receiver) + { + // Increase the MPT Holder MPTAmount + auto const mptokenID = keylet::mptoken(mptID.key, receiver); + auto sle = view.peek(mptokenID); + if (!sle) + { // LCOV_EXCL_START + JLOG(j.error()) << "rippleUnlockEscrowMPT: MPToken not found for " << receiver; + return tecOBJECT_NOT_FOUND; + } // LCOV_EXCL_STOP + + auto current = sle->getFieldU64(sfMPTAmount); + auto delta = netAmount.mpt().value(); + + // Overflow check for addition + if (!canAdd(STAmount(mptIssue, current), STAmount(mptIssue, delta))) + { // LCOV_EXCL_START + JLOG(j.error()) << "rippleUnlockEscrowMPT: overflow on MPTAmount for " + << to_string(receiver) << ": " << current << " + " << delta; + return tecINTERNAL; + } // LCOV_EXCL_STOP + + (*sle)[sfMPTAmount] += delta; + view.update(sle); + } + else + { + // Decrease the Issuance OutstandingAmount + auto const outstanding = sleIssuance->getFieldU64(sfOutstandingAmount); + auto const redeem = netAmount.mpt().value(); + + // Underflow check for subtraction + if (!canSubtract(STAmount(mptIssue, outstanding), STAmount(mptIssue, redeem))) + { // LCOV_EXCL_START + JLOG(j.error()) << "rippleUnlockEscrowMPT: insufficient outstanding amount for " + << mptIssue.getMptID() << ": " << outstanding << " < " << redeem; + return tecINTERNAL; + } // LCOV_EXCL_STOP + + sleIssuance->setFieldU64(sfOutstandingAmount, outstanding - redeem); + view.update(sleIssuance); + } + + if (issuer == sender) + { // LCOV_EXCL_START + JLOG(j.error()) << "rippleUnlockEscrowMPT: sender is the issuer, " + "cannot unlock MPTs."; + return tecINTERNAL; + } // LCOV_EXCL_STOP + // Decrease the MPT Holder EscrowedAmount + auto const mptokenID = keylet::mptoken(mptID.key, sender); + auto sle = view.peek(mptokenID); + if (!sle) + { // LCOV_EXCL_START + JLOG(j.error()) << "rippleUnlockEscrowMPT: MPToken not found for " << sender; + return tecOBJECT_NOT_FOUND; + } // LCOV_EXCL_STOP + + if (!sle->isFieldPresent(sfLockedAmount)) + { // LCOV_EXCL_START + JLOG(j.error()) << "rippleUnlockEscrowMPT: no locked amount in MPToken for " + << to_string(sender); + return tecINTERNAL; + } // LCOV_EXCL_STOP + + auto const locked = sle->getFieldU64(sfLockedAmount); + auto const delta = grossAmount.mpt().value(); + + // Underflow check for subtraction + if (!canSubtract(STAmount(mptIssue, locked), STAmount(mptIssue, delta))) + { // LCOV_EXCL_START + JLOG(j.error()) << "rippleUnlockEscrowMPT: insufficient locked amount for " + << to_string(sender) << ": " << locked << " < " << delta; + return tecINTERNAL; + } // LCOV_EXCL_STOP + + auto const newLocked = locked - delta; + if (newLocked == 0) + { + sle->makeFieldAbsent(sfLockedAmount); + } + else + { + sle->setFieldU64(sfLockedAmount, newLocked); + } + view.update(sle); + + // Note: The gross amount is the amount that was locked, the net + // amount is the amount that is being unlocked. The difference is the fee + // that was charged for the transfer. If this difference is greater than + // zero, we need to update the outstanding amount. + auto const diff = grossAmount.mpt().value() - netAmount.mpt().value(); + if (diff != 0) + { + auto const outstanding = sleIssuance->getFieldU64(sfOutstandingAmount); + // Underflow check for subtraction + if (!canSubtract(STAmount(mptIssue, outstanding), STAmount(mptIssue, diff))) + { // LCOV_EXCL_START + JLOG(j.error()) << "rippleUnlockEscrowMPT: insufficient outstanding amount for " + << mptIssue.getMptID() << ": " << outstanding << " < " << diff; + return tecINTERNAL; + } // LCOV_EXCL_STOP + + sleIssuance->setFieldU64(sfOutstandingAmount, outstanding - diff); + view.update(sleIssuance); + } + return tesSUCCESS; +} + +} // namespace xrpl diff --git a/src/libxrpl/ledger/helpers/OfferHelpers.cpp b/src/libxrpl/ledger/helpers/OfferHelpers.cpp new file mode 100644 index 0000000000..9422153b10 --- /dev/null +++ b/src/libxrpl/ledger/helpers/OfferHelpers.cpp @@ -0,0 +1,58 @@ +#include +// +#include +#include +#include +#include + +namespace xrpl { + +TER +offerDelete(ApplyView& view, std::shared_ptr const& sle, beast::Journal j) +{ + if (!sle) + return tesSUCCESS; + auto offerIndex = sle->key(); + auto owner = sle->getAccountID(sfAccount); + + // Detect legacy directories. + uint256 uDirectory = sle->getFieldH256(sfBookDirectory); + + if (!view.dirRemove(keylet::ownerDir(owner), sle->getFieldU64(sfOwnerNode), offerIndex, false)) + { + return tefBAD_LEDGER; // LCOV_EXCL_LINE + } + + if (!view.dirRemove(keylet::page(uDirectory), sle->getFieldU64(sfBookNode), offerIndex, false)) + { + return tefBAD_LEDGER; // LCOV_EXCL_LINE + } + + if (sle->isFieldPresent(sfAdditionalBooks)) + { + XRPL_ASSERT( + sle->isFlag(lsfHybrid) && sle->isFieldPresent(sfDomainID), + "xrpl::offerDelete : should be a hybrid domain offer"); + + auto const& additionalBookDirs = sle->getFieldArray(sfAdditionalBooks); + + for (auto const& bookDir : additionalBookDirs) + { + auto const& dirIndex = bookDir.getFieldH256(sfBookDirectory); + auto const& dirNode = bookDir.getFieldU64(sfBookNode); + + if (!view.dirRemove(keylet::page(dirIndex), dirNode, offerIndex, false)) + { + return tefBAD_LEDGER; // LCOV_EXCL_LINE + } + } + } + + adjustOwnerCount(view, view.peek(keylet::account(owner)), -1, j); + + view.erase(sle); + + return tesSUCCESS; +} + +} // namespace xrpl diff --git a/src/libxrpl/ledger/helpers/RippleStateHelpers.cpp b/src/libxrpl/ledger/helpers/RippleStateHelpers.cpp new file mode 100644 index 0000000000..e88afe0cfb --- /dev/null +++ b/src/libxrpl/ledger/helpers/RippleStateHelpers.cpp @@ -0,0 +1,759 @@ +#include +// +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace xrpl { + +//------------------------------------------------------------------------------ +// +// Credit functions (from Credit.cpp) +// +//------------------------------------------------------------------------------ + +STAmount +creditLimit( + ReadView const& view, + AccountID const& account, + AccountID const& issuer, + Currency const& currency) +{ + STAmount result(Issue{currency, account}); + + auto sleRippleState = view.read(keylet::line(account, issuer, currency)); + + if (sleRippleState) + { + result = sleRippleState->getFieldAmount(account < issuer ? sfLowLimit : sfHighLimit); + result.setIssuer(account); + } + + XRPL_ASSERT(result.getIssuer() == account, "xrpl::creditLimit : result issuer match"); + XRPL_ASSERT(result.getCurrency() == currency, "xrpl::creditLimit : result currency match"); + return result; +} + +IOUAmount +creditLimit2(ReadView const& v, AccountID const& acc, AccountID const& iss, Currency const& cur) +{ + return toAmount(creditLimit(v, acc, iss, cur)); +} + +STAmount +creditBalance( + ReadView const& view, + AccountID const& account, + AccountID const& issuer, + Currency const& currency) +{ + STAmount result(Issue{currency, account}); + + auto sleRippleState = view.read(keylet::line(account, issuer, currency)); + + if (sleRippleState) + { + result = sleRippleState->getFieldAmount(sfBalance); + if (account < issuer) + result.negate(); + result.setIssuer(account); + } + + XRPL_ASSERT(result.getIssuer() == account, "xrpl::creditBalance : result issuer match"); + XRPL_ASSERT(result.getCurrency() == currency, "xrpl::creditBalance : result currency match"); + return result; +} + +//------------------------------------------------------------------------------ +// +// Freeze checking (IOU-specific) +// +//------------------------------------------------------------------------------ + +bool +isIndividualFrozen( + ReadView const& view, + AccountID const& account, + Currency const& currency, + AccountID const& issuer) +{ + if (isXRP(currency)) + return false; + if (issuer != account) + { + // Check if the issuer froze the line + auto const sle = view.read(keylet::line(account, issuer, currency)); + if (sle && sle->isFlag((issuer > account) ? lsfHighFreeze : lsfLowFreeze)) + return true; + } + return false; +} + +// Can the specified account spend the specified currency issued by +// the specified issuer or does the freeze flag prohibit it? +bool +isFrozen( + ReadView const& view, + AccountID const& account, + Currency const& currency, + AccountID const& issuer) +{ + if (isXRP(currency)) + return false; + auto sle = view.read(keylet::account(issuer)); + if (sle && sle->isFlag(lsfGlobalFreeze)) + return true; + if (issuer != account) + { + // Check if the issuer froze the line + sle = view.read(keylet::line(account, issuer, currency)); + if (sle && sle->isFlag((issuer > account) ? lsfHighFreeze : lsfLowFreeze)) + return true; + } + return false; +} + +bool +isDeepFrozen( + ReadView const& view, + AccountID const& account, + Currency const& currency, + AccountID const& issuer) +{ + if (isXRP(currency)) + { + return false; + } + + if (issuer == account) + { + return false; + } + + auto const sle = view.read(keylet::line(account, issuer, currency)); + if (!sle) + { + return false; + } + + return sle->isFlag(lsfHighDeepFreeze) || sle->isFlag(lsfLowDeepFreeze); +} + +//------------------------------------------------------------------------------ +// +// Trust line operations +// +//------------------------------------------------------------------------------ + +TER +trustCreate( + ApplyView& view, + bool const bSrcHigh, + AccountID const& uSrcAccountID, + AccountID const& uDstAccountID, + uint256 const& uIndex, // --> ripple state entry + SLE::ref sleAccount, // --> the account being set. + bool const bAuth, // --> authorize account. + bool const bNoRipple, // --> others cannot ripple through + bool const bFreeze, // --> funds cannot leave + bool bDeepFreeze, // --> can neither receive nor send funds + STAmount const& saBalance, // --> balance of account being set. + // Issuer should be noAccount() + STAmount const& saLimit, // --> limit for account being set. + // Issuer should be the account being set. + std::uint32_t uQualityIn, + std::uint32_t uQualityOut, + beast::Journal j) +{ + JLOG(j.trace()) << "trustCreate: " << to_string(uSrcAccountID) << ", " + << to_string(uDstAccountID) << ", " << saBalance.getFullText(); + + auto const& uLowAccountID = !bSrcHigh ? uSrcAccountID : uDstAccountID; + auto const& uHighAccountID = bSrcHigh ? uSrcAccountID : uDstAccountID; + if (uLowAccountID == uHighAccountID) + { + // LCOV_EXCL_START + UNREACHABLE("xrpl::trustCreate : trust line to self"); + if (view.rules().enabled(featureLendingProtocol)) + return tecINTERNAL; + // LCOV_EXCL_STOP + } + + auto const sleRippleState = std::make_shared(ltRIPPLE_STATE, uIndex); + view.insert(sleRippleState); + + auto lowNode = view.dirInsert( + keylet::ownerDir(uLowAccountID), sleRippleState->key(), describeOwnerDir(uLowAccountID)); + + if (!lowNode) + return tecDIR_FULL; // LCOV_EXCL_LINE + + auto highNode = view.dirInsert( + keylet::ownerDir(uHighAccountID), sleRippleState->key(), describeOwnerDir(uHighAccountID)); + + if (!highNode) + return tecDIR_FULL; // LCOV_EXCL_LINE + + bool const bSetDst = saLimit.getIssuer() == uDstAccountID; + bool const bSetHigh = bSrcHigh ^ bSetDst; + + XRPL_ASSERT(sleAccount, "xrpl::trustCreate : non-null SLE"); + if (!sleAccount) + return tefINTERNAL; // LCOV_EXCL_LINE + + XRPL_ASSERT( + sleAccount->getAccountID(sfAccount) == (bSetHigh ? uHighAccountID : uLowAccountID), + "xrpl::trustCreate : matching account ID"); + auto const slePeer = view.peek(keylet::account(bSetHigh ? uLowAccountID : uHighAccountID)); + if (!slePeer) + return tecNO_TARGET; + + // Remember deletion hints. + sleRippleState->setFieldU64(sfLowNode, *lowNode); + sleRippleState->setFieldU64(sfHighNode, *highNode); + + sleRippleState->setFieldAmount(bSetHigh ? sfHighLimit : sfLowLimit, saLimit); + sleRippleState->setFieldAmount( + bSetHigh ? sfLowLimit : sfHighLimit, + STAmount(Issue{saBalance.getCurrency(), bSetDst ? uSrcAccountID : uDstAccountID})); + + if (uQualityIn) + sleRippleState->setFieldU32(bSetHigh ? sfHighQualityIn : sfLowQualityIn, uQualityIn); + + if (uQualityOut) + sleRippleState->setFieldU32(bSetHigh ? sfHighQualityOut : sfLowQualityOut, uQualityOut); + + std::uint32_t uFlags = bSetHigh ? lsfHighReserve : lsfLowReserve; + + if (bAuth) + { + uFlags |= (bSetHigh ? lsfHighAuth : lsfLowAuth); + } + if (bNoRipple) + { + uFlags |= (bSetHigh ? lsfHighNoRipple : lsfLowNoRipple); + } + if (bFreeze) + { + uFlags |= (bSetHigh ? lsfHighFreeze : lsfLowFreeze); + } + if (bDeepFreeze) + { + uFlags |= (bSetHigh ? lsfHighDeepFreeze : lsfLowDeepFreeze); + } + + if ((slePeer->getFlags() & lsfDefaultRipple) == 0) + { + // The other side's default is no rippling + uFlags |= (bSetHigh ? lsfLowNoRipple : lsfHighNoRipple); + } + + sleRippleState->setFieldU32(sfFlags, uFlags); + adjustOwnerCount(view, sleAccount, 1, j); + + // ONLY: Create ripple balance. + sleRippleState->setFieldAmount(sfBalance, bSetHigh ? -saBalance : saBalance); + + view.creditHook(uSrcAccountID, uDstAccountID, saBalance, saBalance.zeroed()); + + return tesSUCCESS; +} + +TER +trustDelete( + ApplyView& view, + std::shared_ptr const& sleRippleState, + AccountID const& uLowAccountID, + AccountID const& uHighAccountID, + beast::Journal j) +{ + // Detect legacy dirs. + std::uint64_t uLowNode = sleRippleState->getFieldU64(sfLowNode); + std::uint64_t uHighNode = sleRippleState->getFieldU64(sfHighNode); + + JLOG(j.trace()) << "trustDelete: Deleting ripple line: low"; + + if (!view.dirRemove(keylet::ownerDir(uLowAccountID), uLowNode, sleRippleState->key(), false)) + { + return tefBAD_LEDGER; // LCOV_EXCL_LINE + } + + JLOG(j.trace()) << "trustDelete: Deleting ripple line: high"; + + if (!view.dirRemove(keylet::ownerDir(uHighAccountID), uHighNode, sleRippleState->key(), false)) + { + return tefBAD_LEDGER; // LCOV_EXCL_LINE + } + + JLOG(j.trace()) << "trustDelete: Deleting ripple line: state"; + view.erase(sleRippleState); + + return tesSUCCESS; +} + +//------------------------------------------------------------------------------ +// +// IOU issuance/redemption +// +//------------------------------------------------------------------------------ + +static bool +updateTrustLine( + ApplyView& view, + SLE::pointer state, + bool bSenderHigh, + AccountID const& sender, + STAmount const& before, + STAmount const& after, + beast::Journal j) +{ + if (!state) + return false; + std::uint32_t const flags(state->getFieldU32(sfFlags)); + + auto sle = view.peek(keylet::account(sender)); + if (!sle) + return false; + + // YYY Could skip this if rippling in reverse. + if (before > beast::zero + // Sender balance was positive. + && after <= beast::zero + // Sender is zero or negative. + && (flags & (!bSenderHigh ? lsfLowReserve : lsfHighReserve)) + // Sender reserve is set. + && static_cast(flags & (!bSenderHigh ? lsfLowNoRipple : lsfHighNoRipple)) != + static_cast(sle->getFlags() & lsfDefaultRipple) && + !(flags & (!bSenderHigh ? lsfLowFreeze : lsfHighFreeze)) && + !state->getFieldAmount(!bSenderHigh ? sfLowLimit : sfHighLimit) + // Sender trust limit is 0. + && !state->getFieldU32(!bSenderHigh ? sfLowQualityIn : sfHighQualityIn) + // Sender quality in is 0. + && !state->getFieldU32(!bSenderHigh ? sfLowQualityOut : sfHighQualityOut)) + // Sender quality out is 0. + { + // VFALCO Where is the line being deleted? + // Clear the reserve of the sender, possibly delete the line! + adjustOwnerCount(view, sle, -1, j); + + // Clear reserve flag. + state->setFieldU32(sfFlags, flags & (!bSenderHigh ? ~lsfLowReserve : ~lsfHighReserve)); + + // Balance is zero, receiver reserve is clear. + if (!after // Balance is zero. + && !(flags & (bSenderHigh ? lsfLowReserve : lsfHighReserve))) + return true; + } + return false; +} + +TER +issueIOU( + ApplyView& view, + AccountID const& account, + STAmount const& amount, + Issue const& issue, + beast::Journal j) +{ + XRPL_ASSERT( + !isXRP(account) && !isXRP(issue.account), + "xrpl::issueIOU : neither account nor issuer is XRP"); + + // Consistency check + XRPL_ASSERT(issue == amount.issue(), "xrpl::issueIOU : matching issue"); + + // Can't send to self! + XRPL_ASSERT(issue.account != account, "xrpl::issueIOU : not issuer account"); + + JLOG(j.trace()) << "issueIOU: " << to_string(account) << ": " << amount.getFullText(); + + bool bSenderHigh = issue.account > account; + + auto const index = keylet::line(issue.account, account, issue.currency); + + if (auto state = view.peek(index)) + { + STAmount final_balance = state->getFieldAmount(sfBalance); + + if (bSenderHigh) + final_balance.negate(); // Put balance in sender terms. + + STAmount const start_balance = final_balance; + + final_balance -= amount; + + auto const must_delete = updateTrustLine( + view, state, bSenderHigh, issue.account, start_balance, final_balance, j); + + view.creditHook(issue.account, account, amount, start_balance); + + if (bSenderHigh) + final_balance.negate(); + + // Adjust the balance on the trust line if necessary. We do this even + // if we are going to delete the line to reflect the correct balance + // at the time of deletion. + state->setFieldAmount(sfBalance, final_balance); + if (must_delete) + { + return trustDelete( + view, + state, + bSenderHigh ? account : issue.account, + bSenderHigh ? issue.account : account, + j); + } + + view.update(state); + + return tesSUCCESS; + } + + // NIKB TODO: The limit uses the receiver's account as the issuer and + // this is unnecessarily inefficient as copying which could be avoided + // is now required. Consider available options. + STAmount const limit(Issue{issue.currency, account}); + STAmount final_balance = amount; + + final_balance.setIssuer(noAccount()); + + auto const receiverAccount = view.peek(keylet::account(account)); + if (!receiverAccount) + return tefINTERNAL; // LCOV_EXCL_LINE + + bool noRipple = (receiverAccount->getFlags() & lsfDefaultRipple) == 0; + + return trustCreate( + view, + bSenderHigh, + issue.account, + account, + index.key, + receiverAccount, + false, + noRipple, + false, + false, + final_balance, + limit, + 0, + 0, + j); +} + +TER +redeemIOU( + ApplyView& view, + AccountID const& account, + STAmount const& amount, + Issue const& issue, + beast::Journal j) +{ + XRPL_ASSERT( + !isXRP(account) && !isXRP(issue.account), + "xrpl::redeemIOU : neither account nor issuer is XRP"); + + // Consistency check + XRPL_ASSERT(issue == amount.issue(), "xrpl::redeemIOU : matching issue"); + + // Can't send to self! + XRPL_ASSERT(issue.account != account, "xrpl::redeemIOU : not issuer account"); + + JLOG(j.trace()) << "redeemIOU: " << to_string(account) << ": " << amount.getFullText(); + + bool bSenderHigh = account > issue.account; + + if (auto state = view.peek(keylet::line(account, issue.account, issue.currency))) + { + STAmount final_balance = state->getFieldAmount(sfBalance); + + if (bSenderHigh) + final_balance.negate(); // Put balance in sender terms. + + STAmount const start_balance = final_balance; + + final_balance -= amount; + + auto const must_delete = + updateTrustLine(view, state, bSenderHigh, account, start_balance, final_balance, j); + + view.creditHook(account, issue.account, amount, start_balance); + + if (bSenderHigh) + final_balance.negate(); + + // Adjust the balance on the trust line if necessary. We do this even + // if we are going to delete the line to reflect the correct balance + // at the time of deletion. + state->setFieldAmount(sfBalance, final_balance); + + if (must_delete) + { + return trustDelete( + view, + state, + bSenderHigh ? issue.account : account, + bSenderHigh ? account : issue.account, + j); + } + + view.update(state); + return tesSUCCESS; + } + + // In order to hold an IOU, a trust line *MUST* exist to track the + // balance. If it doesn't, then something is very wrong. Don't try + // to continue. + // LCOV_EXCL_START + JLOG(j.fatal()) << "redeemIOU: " << to_string(account) << " attempts to " + << "redeem " << amount.getFullText() << " but no trust line exists!"; + + return tefINTERNAL; + // LCOV_EXCL_STOP +} + +//------------------------------------------------------------------------------ +// +// Authorization and transfer checks (IOU-specific) +// +//------------------------------------------------------------------------------ + +TER +requireAuth(ReadView const& view, Issue const& issue, AccountID const& account, AuthType authType) +{ + if (isXRP(issue) || issue.account == account) + return tesSUCCESS; + + auto const trustLine = view.read(keylet::line(account, issue.account, issue.currency)); + // If account has no line, and this is a strong check, fail + if (!trustLine && authType == AuthType::StrongAuth) + return tecNO_LINE; + + // If this is a weak or legacy check, or if the account has a line, fail if + // auth is required and not set on the line + if (auto const issuerAccount = view.read(keylet::account(issue.account)); + issuerAccount && (*issuerAccount)[sfFlags] & lsfRequireAuth) + { + if (trustLine) + { + return ((*trustLine)[sfFlags] & ((account > issue.account) ? lsfLowAuth : lsfHighAuth)) + ? tesSUCCESS + : TER{tecNO_AUTH}; + } + return TER{tecNO_LINE}; + } + + return tesSUCCESS; +} + +TER +canTransfer(ReadView const& view, Issue const& issue, AccountID const& from, AccountID const& to) +{ + if (issue.native()) + return tesSUCCESS; + + auto const& issuerId = issue.getIssuer(); + if (issuerId == from || issuerId == to) + return tesSUCCESS; + auto const sleIssuer = view.read(keylet::account(issuerId)); + if (sleIssuer == nullptr) + return tefINTERNAL; // LCOV_EXCL_LINE + + auto const isRippleDisabled = [&](AccountID account) -> bool { + // Line might not exist, but some transfers can create it. If this + // is the case, just check the default ripple on the issuer account. + auto const line = view.read(keylet::line(account, issue)); + if (line) + { + bool const issuerHigh = issuerId > account; + return line->isFlag(issuerHigh ? lsfHighNoRipple : lsfLowNoRipple); + } + return sleIssuer->isFlag(lsfDefaultRipple) == false; + }; + + // Fail if rippling disabled on both trust lines + if (isRippleDisabled(from) && isRippleDisabled(to)) + return terNO_RIPPLE; + + return tesSUCCESS; +} + +//------------------------------------------------------------------------------ +// +// Empty holding operations (IOU-specific) +// +//------------------------------------------------------------------------------ + +TER +addEmptyHolding( + ApplyView& view, + AccountID const& accountID, + XRPAmount priorBalance, + Issue const& issue, + beast::Journal journal) +{ + // Every account can hold XRP. An issuer can issue directly. + if (issue.native() || accountID == issue.getIssuer()) + return tesSUCCESS; + + auto const& issuerId = issue.getIssuer(); + auto const& currency = issue.currency; + if (isGlobalFrozen(view, issuerId)) + return tecFROZEN; // LCOV_EXCL_LINE + + auto const& srcId = issuerId; + auto const& dstId = accountID; + auto const high = srcId > dstId; + auto const index = keylet::line(srcId, dstId, currency); + auto const sleSrc = view.peek(keylet::account(srcId)); + auto const sleDst = view.peek(keylet::account(dstId)); + if (!sleDst || !sleSrc) + return tefINTERNAL; // LCOV_EXCL_LINE + if (!sleSrc->isFlag(lsfDefaultRipple)) + return tecINTERNAL; // LCOV_EXCL_LINE + // If the line already exists, don't create it again. + if (view.read(index)) + return tecDUPLICATE; + + // Can the account cover the trust line reserve ? + std::uint32_t const ownerCount = sleDst->at(sfOwnerCount); + if (priorBalance < view.fees().accountReserve(ownerCount + 1)) + return tecNO_LINE_INSUF_RESERVE; + + return trustCreate( + view, + high, + srcId, + dstId, + index.key, + sleDst, + /*bAuth=*/false, + /*bNoRipple=*/true, + /*bFreeze=*/false, + /*deepFreeze*/ false, + /*saBalance=*/STAmount{Issue{currency, noAccount()}}, + /*saLimit=*/STAmount{Issue{currency, dstId}}, + /*uQualityIn=*/0, + /*uQualityOut=*/0, + journal); +} + +TER +removeEmptyHolding( + ApplyView& view, + AccountID const& accountID, + Issue const& issue, + beast::Journal journal) +{ + if (issue.native()) + { + auto const sle = view.read(keylet::account(accountID)); + if (!sle) + return tecINTERNAL; // LCOV_EXCL_LINE + + auto const balance = sle->getFieldAmount(sfBalance); + if (balance.xrp() != 0) + return tecHAS_OBLIGATIONS; + + return tesSUCCESS; + } + + // `asset` is an IOU. + // If the account is the issuer, then no line should exist. Check anyway. + // If a line does exist, it will get deleted. If not, return success. + bool const accountIsIssuer = accountID == issue.account; + auto const line = view.peek(keylet::line(accountID, issue)); + if (!line) + return accountIsIssuer ? (TER)tesSUCCESS : (TER)tecOBJECT_NOT_FOUND; + if (!accountIsIssuer && line->at(sfBalance)->iou() != beast::zero) + return tecHAS_OBLIGATIONS; + + // Adjust the owner count(s) + if (line->isFlag(lsfLowReserve)) + { + // Clear reserve for low account. + auto sleLowAccount = view.peek(keylet::account(line->at(sfLowLimit)->getIssuer())); + if (!sleLowAccount) + return tecINTERNAL; // LCOV_EXCL_LINE + + adjustOwnerCount(view, sleLowAccount, -1, journal); + // It's not really necessary to clear the reserve flag, since the line + // is about to be deleted, but this will make the metadata reflect an + // accurate state at the time of deletion. + line->clearFlag(lsfLowReserve); + } + + if (line->isFlag(lsfHighReserve)) + { + // Clear reserve for high account. + auto sleHighAccount = view.peek(keylet::account(line->at(sfHighLimit)->getIssuer())); + if (!sleHighAccount) + return tecINTERNAL; // LCOV_EXCL_LINE + + adjustOwnerCount(view, sleHighAccount, -1, journal); + // It's not really necessary to clear the reserve flag, since the line + // is about to be deleted, but this will make the metadata reflect an + // accurate state at the time of deletion. + line->clearFlag(lsfHighReserve); + } + + return trustDelete( + view, line, line->at(sfLowLimit)->getIssuer(), line->at(sfHighLimit)->getIssuer(), journal); +} + +TER +deleteAMMTrustLine( + ApplyView& view, + std::shared_ptr sleState, + std::optional const& ammAccountID, + beast::Journal j) +{ + if (!sleState || sleState->getType() != ltRIPPLE_STATE) + return tecINTERNAL; // LCOV_EXCL_LINE + + auto const& [low, high] = std::minmax( + sleState->getFieldAmount(sfLowLimit).getIssuer(), + sleState->getFieldAmount(sfHighLimit).getIssuer()); + auto sleLow = view.peek(keylet::account(low)); + auto sleHigh = view.peek(keylet::account(high)); + if (!sleLow || !sleHigh) + return tecINTERNAL; // LCOV_EXCL_LINE + + bool const ammLow = sleLow->isFieldPresent(sfAMMID); + bool const ammHigh = sleHigh->isFieldPresent(sfAMMID); + + // can't both be AMM + if (ammLow && ammHigh) + return tecINTERNAL; // LCOV_EXCL_LINE + + // at least one must be + if (!ammLow && !ammHigh) + return terNO_AMM; + + // one must be the target amm + if (ammAccountID && (low != *ammAccountID && high != *ammAccountID)) + return terNO_AMM; + + if (auto const ter = trustDelete(view, sleState, low, high, j); !isTesSuccess(ter)) + { + JLOG(j.error()) << "deleteAMMTrustLine: failed to delete the trustline."; + return ter; + } + + auto const uFlags = !ammLow ? lsfLowReserve : lsfHighReserve; + if (!(sleState->getFlags() & uFlags)) + return tecINTERNAL; // LCOV_EXCL_LINE + + adjustOwnerCount(view, !ammLow ? sleLow : sleHigh, -1, j); + + return tesSUCCESS; +} + +} // namespace xrpl diff --git a/src/libxrpl/ledger/helpers/TokenHelpers.cpp b/src/libxrpl/ledger/helpers/TokenHelpers.cpp new file mode 100644 index 0000000000..7a98445b0a --- /dev/null +++ b/src/libxrpl/ledger/helpers/TokenHelpers.cpp @@ -0,0 +1,1392 @@ +#include +// +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace xrpl { + +// Forward declaration for function that remains in View.h/cpp +bool +isLPTokenFrozen( + ReadView const& view, + AccountID const& account, + Issue const& asset, + Issue const& asset2); + +//------------------------------------------------------------------------------ +// +// Freeze checking (Asset-based) +// +//------------------------------------------------------------------------------ + +bool +isGlobalFrozen(ReadView const& view, Asset const& asset) +{ + return std::visit( + [&](TIss const& issue) { + if constexpr (std::is_same_v) + { + return isGlobalFrozen(view, issue.getIssuer()); + } + else + { + return isGlobalFrozen(view, issue); + } + }, + asset.value()); +} + +bool +isIndividualFrozen(ReadView const& view, AccountID const& account, Asset const& asset) +{ + return std::visit( + [&](auto const& issue) { return isIndividualFrozen(view, account, issue); }, asset.value()); +} + +bool +isFrozen(ReadView const& view, AccountID const& account, Asset const& asset, int depth) +{ + return std::visit( + [&](auto const& issue) { return isFrozen(view, account, issue, depth); }, asset.value()); +} + +TER +checkFrozen(ReadView const& view, AccountID const& account, Issue const& issue) +{ + return isFrozen(view, account, issue) ? (TER)tecFROZEN : (TER)tesSUCCESS; +} + +TER +checkFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue) +{ + return isFrozen(view, account, mptIssue) ? (TER)tecLOCKED : (TER)tesSUCCESS; +} + +TER +checkFrozen(ReadView const& view, AccountID const& account, Asset const& asset) +{ + return std::visit( + [&](auto const& issue) { return checkFrozen(view, account, issue); }, asset.value()); +} + +bool +isAnyFrozen( + ReadView const& view, + std::initializer_list const& accounts, + Issue const& issue) +{ + for (auto const& account : accounts) + { + if (isFrozen(view, account, issue.currency, issue.account)) + return true; + } + return false; +} + +bool +isAnyFrozen( + ReadView const& view, + std::initializer_list const& accounts, + Asset const& asset, + int depth) +{ + return std::visit( + [&](TIss const& issue) { + if constexpr (std::is_same_v) + { + return isAnyFrozen(view, accounts, issue); + } + else + { + return isAnyFrozen(view, accounts, issue, depth); + } + }, + asset.value()); +} + +bool +isDeepFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue, int depth) +{ + // Unlike IOUs, frozen / locked MPTs are not allowed to send or receive + // funds, so checking "deep frozen" is the same as checking "frozen". + return isFrozen(view, account, mptIssue, depth); +} + +bool +isDeepFrozen(ReadView const& view, AccountID const& account, Asset const& asset, int depth) +{ + return std::visit( + [&](auto const& issue) { return isDeepFrozen(view, account, issue, depth); }, + asset.value()); +} + +TER +checkDeepFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue) +{ + return isDeepFrozen(view, account, mptIssue) ? (TER)tecLOCKED : (TER)tesSUCCESS; +} + +TER +checkDeepFrozen(ReadView const& view, AccountID const& account, Asset const& asset) +{ + return std::visit( + [&](auto const& issue) { return checkDeepFrozen(view, account, issue); }, asset.value()); +} + +//------------------------------------------------------------------------------ +// +// Account balance functions +// +//------------------------------------------------------------------------------ + +static SLE::const_pointer +getLineIfUsable( + ReadView const& view, + AccountID const& account, + Currency const& currency, + AccountID const& issuer, + FreezeHandling zeroIfFrozen, + beast::Journal j) +{ + auto const sle = view.read(keylet::line(account, issuer, currency)); + + if (!sle) + { + return nullptr; + } + + if (zeroIfFrozen == fhZERO_IF_FROZEN) + { + if (isFrozen(view, account, currency, issuer) || + isDeepFrozen(view, account, currency, issuer)) + { + return nullptr; + } + + // when fixFrozenLPTokenTransfer is enabled, if currency is lptoken, + // we need to check if the associated assets have been frozen + if (view.rules().enabled(fixFrozenLPTokenTransfer)) + { + auto const sleIssuer = view.read(keylet::account(issuer)); + if (!sleIssuer) + { + return nullptr; // LCOV_EXCL_LINE + } + if (sleIssuer->isFieldPresent(sfAMMID)) + { + auto const sleAmm = view.read(keylet::amm((*sleIssuer)[sfAMMID])); + + if (!sleAmm || + isLPTokenFrozen( + view, + account, + (*sleAmm)[sfAsset].get(), + (*sleAmm)[sfAsset2].get())) + { + return nullptr; + } + } + } + } + + return sle; +} + +static STAmount +getTrustLineBalance( + ReadView const& view, + SLE::const_ref sle, + AccountID const& account, + Currency const& currency, + AccountID const& issuer, + bool includeOppositeLimit, + beast::Journal j) +{ + STAmount amount; + if (sle) + { + amount = sle->getFieldAmount(sfBalance); + bool const accountHigh = account > issuer; + auto const& oppositeField = accountHigh ? sfLowLimit : sfHighLimit; + if (accountHigh) + { + // Put balance in account terms. + amount.negate(); + } + if (includeOppositeLimit) + { + amount += sle->getFieldAmount(oppositeField); + } + amount.setIssuer(issuer); + } + else + { + amount.clear(Issue{currency, issuer}); + } + + JLOG(j.trace()) << "getTrustLineBalance:" << " account=" << to_string(account) + << " amount=" << amount.getFullText(); + + return view.balanceHook(account, issuer, amount); +} + +STAmount +accountHolds( + ReadView const& view, + AccountID const& account, + Currency const& currency, + AccountID const& issuer, + FreezeHandling zeroIfFrozen, + beast::Journal j, + SpendableHandling includeFullBalance) +{ + STAmount amount; + if (isXRP(currency)) + { + return {xrpLiquid(view, account, 0, j)}; + } + + bool const returnSpendable = (includeFullBalance == shFULL_BALANCE); + if (returnSpendable && account == issuer) + { + // If the account is the issuer, then their limit is effectively + // infinite + return STAmount{Issue{currency, issuer}, STAmount::cMaxValue, STAmount::cMaxOffset}; + } + + // IOU: Return balance on trust line modulo freeze + SLE::const_pointer const sle = + getLineIfUsable(view, account, currency, issuer, zeroIfFrozen, j); + + return getTrustLineBalance(view, sle, account, currency, issuer, returnSpendable, j); +} + +STAmount +accountHolds( + ReadView const& view, + AccountID const& account, + Issue const& issue, + FreezeHandling zeroIfFrozen, + beast::Journal j, + SpendableHandling includeFullBalance) +{ + return accountHolds( + view, account, issue.currency, issue.account, zeroIfFrozen, j, includeFullBalance); +} + +STAmount +accountHolds( + ReadView const& view, + AccountID const& account, + MPTIssue const& mptIssue, + FreezeHandling zeroIfFrozen, + AuthHandling zeroIfUnauthorized, + beast::Journal j, + SpendableHandling includeFullBalance) +{ + bool const returnSpendable = (includeFullBalance == shFULL_BALANCE); + + if (returnSpendable && account == mptIssue.getIssuer()) + { + // if the account is the issuer, and the issuance exists, their limit is + // the issuance limit minus the outstanding value + auto const issuance = view.read(keylet::mptIssuance(mptIssue.getMptID())); + + if (!issuance) + { + return STAmount{mptIssue}; + } + return STAmount{ + mptIssue, + issuance->at(~sfMaximumAmount).value_or(maxMPTokenAmount) - + issuance->at(sfOutstandingAmount)}; + } + + STAmount amount; + + auto const sleMpt = view.read(keylet::mptoken(mptIssue.getMptID(), account)); + + if (!sleMpt) + { + amount.clear(mptIssue); + } + else if (zeroIfFrozen == fhZERO_IF_FROZEN && isFrozen(view, account, mptIssue)) + { + amount.clear(mptIssue); + } + else + { + amount = STAmount{mptIssue, sleMpt->getFieldU64(sfMPTAmount)}; + + // Only if auth check is needed, as it needs to do an additional read + // operation. Note featureSingleAssetVault will affect error codes. + if (zeroIfUnauthorized == ahZERO_IF_UNAUTHORIZED && + view.rules().enabled(featureSingleAssetVault)) + { + if (auto const err = requireAuth(view, mptIssue, account, AuthType::StrongAuth); + !isTesSuccess(err)) + amount.clear(mptIssue); + } + else if (zeroIfUnauthorized == ahZERO_IF_UNAUTHORIZED) + { + auto const sleIssuance = view.read(keylet::mptIssuance(mptIssue.getMptID())); + + // if auth is enabled on the issuance and mpt is not authorized, + // clear amount + if (sleIssuance && sleIssuance->isFlag(lsfMPTRequireAuth) && + !sleMpt->isFlag(lsfMPTAuthorized)) + amount.clear(mptIssue); + } + } + + return amount; +} + +[[nodiscard]] STAmount +accountHolds( + ReadView const& view, + AccountID const& account, + Asset const& asset, + FreezeHandling zeroIfFrozen, + AuthHandling zeroIfUnauthorized, + beast::Journal j, + SpendableHandling includeFullBalance) +{ + return std::visit( + [&](TIss const& value) { + if constexpr (std::is_same_v) + { + return accountHolds(view, account, value, zeroIfFrozen, j, includeFullBalance); + } + else if constexpr (std::is_same_v) + { + return accountHolds( + view, account, value, zeroIfFrozen, zeroIfUnauthorized, j, includeFullBalance); + } + }, + asset.value()); +} + +STAmount +accountFunds( + ReadView const& view, + AccountID const& id, + STAmount const& saDefault, + FreezeHandling freezeHandling, + beast::Journal j) +{ + if (!saDefault.native() && saDefault.getIssuer() == id) + return saDefault; + + return accountHolds( + view, id, saDefault.getCurrency(), saDefault.getIssuer(), freezeHandling, j); +} + +Rate +transferRate(ReadView const& view, STAmount const& amount) +{ + return std::visit( + [&](TIss const& issue) { + if constexpr (std::is_same_v) + { + return transferRate(view, issue.getIssuer()); + } + else + { + return transferRate(view, issue.getMptID()); + } + }, + amount.asset().value()); +} + +//------------------------------------------------------------------------------ +// +// Holding operations +// +//------------------------------------------------------------------------------ + +[[nodiscard]] TER +canAddHolding(ReadView const& view, Issue const& issue) +{ + if (issue.native()) + { + return tesSUCCESS; // No special checks for XRP + } + + auto const issuer = view.read(keylet::account(issue.getIssuer())); + if (!issuer) + { + return terNO_ACCOUNT; + } + if (!issuer->isFlag(lsfDefaultRipple)) + { + return terNO_RIPPLE; + } + + return tesSUCCESS; +} + +[[nodiscard]] TER +canAddHolding(ReadView const& view, Asset const& asset) +{ + return std::visit( + [&](TIss const& issue) -> TER { return canAddHolding(view, issue); }, + asset.value()); +} + +TER +addEmptyHolding( + ApplyView& view, + AccountID const& accountID, + XRPAmount priorBalance, + Asset const& asset, + beast::Journal journal) +{ + return std::visit( + [&](TIss const& issue) -> TER { + return addEmptyHolding(view, accountID, priorBalance, issue, journal); + }, + asset.value()); +} + +TER +removeEmptyHolding( + ApplyView& view, + AccountID const& accountID, + Asset const& asset, + beast::Journal journal) +{ + return std::visit( + [&](TIss const& issue) -> TER { + return removeEmptyHolding(view, accountID, issue, journal); + }, + asset.value()); +} + +//------------------------------------------------------------------------------ +// +// Authorization and transfer checks +// +//------------------------------------------------------------------------------ + +TER +requireAuth(ReadView const& view, Asset const& asset, AccountID const& account, AuthType authType) +{ + return std::visit( + [&](TIss const& issue_) { + return requireAuth(view, issue_, account, authType); + }, + asset.value()); +} + +TER +canTransfer(ReadView const& view, Asset const& asset, AccountID const& from, AccountID const& to) +{ + return std::visit( + [&](TIss const& issue) -> TER { + return canTransfer(view, issue, from, to); + }, + asset.value()); +} + +//------------------------------------------------------------------------------ +// +// Money Transfers +// +//------------------------------------------------------------------------------ + +// Direct send w/o fees: +// - Redeeming IOUs and/or sending sender's own IOUs. +// - Create trust line if needed. +// --> bCheckIssuer : normally require issuer to be involved. +static TER +rippleCreditIOU( + ApplyView& view, + AccountID const& uSenderID, + AccountID const& uReceiverID, + STAmount const& saAmount, + bool bCheckIssuer, + beast::Journal j) +{ + AccountID const& issuer = saAmount.getIssuer(); + Currency const& currency = saAmount.getCurrency(); + + // Make sure issuer is involved. + XRPL_ASSERT( + !bCheckIssuer || uSenderID == issuer || uReceiverID == issuer, + "xrpl::rippleCreditIOU : matching issuer or don't care"); + (void)issuer; + + // Disallow sending to self. + XRPL_ASSERT(uSenderID != uReceiverID, "xrpl::rippleCreditIOU : sender is not receiver"); + + bool const bSenderHigh = uSenderID > uReceiverID; + auto const index = keylet::line(uSenderID, uReceiverID, currency); + + XRPL_ASSERT( + !isXRP(uSenderID) && uSenderID != noAccount(), "xrpl::rippleCreditIOU : sender is not XRP"); + XRPL_ASSERT( + !isXRP(uReceiverID) && uReceiverID != noAccount(), + "xrpl::rippleCreditIOU : receiver is not XRP"); + + // If the line exists, modify it accordingly. + if (auto const sleRippleState = view.peek(index)) + { + STAmount saBalance = sleRippleState->getFieldAmount(sfBalance); + + if (bSenderHigh) + saBalance.negate(); // Put balance in sender terms. + + view.creditHook(uSenderID, uReceiverID, saAmount, saBalance); + + STAmount const saBefore = saBalance; + + saBalance -= saAmount; + + JLOG(j.trace()) << "rippleCreditIOU: " << to_string(uSenderID) << " -> " + << to_string(uReceiverID) << " : before=" << saBefore.getFullText() + << " amount=" << saAmount.getFullText() + << " after=" << saBalance.getFullText(); + + std::uint32_t const uFlags(sleRippleState->getFieldU32(sfFlags)); + bool bDelete = false; + + // FIXME This NEEDS to be cleaned up and simplified. It's impossible + // for anyone to understand. + if (saBefore > beast::zero + // Sender balance was positive. + && saBalance <= beast::zero + // Sender is zero or negative. + && (uFlags & (!bSenderHigh ? lsfLowReserve : lsfHighReserve)) + // Sender reserve is set. + && static_cast(uFlags & (!bSenderHigh ? lsfLowNoRipple : lsfHighNoRipple)) != + static_cast( + view.read(keylet::account(uSenderID))->getFlags() & lsfDefaultRipple) && + !(uFlags & (!bSenderHigh ? lsfLowFreeze : lsfHighFreeze)) && + !sleRippleState->getFieldAmount(!bSenderHigh ? sfLowLimit : sfHighLimit) + // Sender trust limit is 0. + && !sleRippleState->getFieldU32(!bSenderHigh ? sfLowQualityIn : sfHighQualityIn) + // Sender quality in is 0. + && !sleRippleState->getFieldU32(!bSenderHigh ? sfLowQualityOut : sfHighQualityOut)) + // Sender quality out is 0. + { + // Clear the reserve of the sender, possibly delete the line! + adjustOwnerCount(view, view.peek(keylet::account(uSenderID)), -1, j); + + // Clear reserve flag. + sleRippleState->setFieldU32( + sfFlags, uFlags & (!bSenderHigh ? ~lsfLowReserve : ~lsfHighReserve)); + + // Balance is zero, receiver reserve is clear. + bDelete = !saBalance // Balance is zero. + && !(uFlags & (bSenderHigh ? lsfLowReserve : lsfHighReserve)); + // Receiver reserve is clear. + } + + if (bSenderHigh) + saBalance.negate(); + + // Want to reflect balance to zero even if we are deleting line. + sleRippleState->setFieldAmount(sfBalance, saBalance); + // ONLY: Adjust ripple balance. + + if (bDelete) + { + return trustDelete( + view, + sleRippleState, + bSenderHigh ? uReceiverID : uSenderID, + !bSenderHigh ? uReceiverID : uSenderID, + j); + } + + view.update(sleRippleState); + return tesSUCCESS; + } + + STAmount const saReceiverLimit(Issue{currency, uReceiverID}); + STAmount saBalance{saAmount}; + + saBalance.setIssuer(noAccount()); + + JLOG(j.debug()) << "rippleCreditIOU: " + "create line: " + << to_string(uSenderID) << " -> " << to_string(uReceiverID) << " : " + << saAmount.getFullText(); + + auto const sleAccount = view.peek(keylet::account(uReceiverID)); + if (!sleAccount) + return tefINTERNAL; // LCOV_EXCL_LINE + + bool const noRipple = (sleAccount->getFlags() & lsfDefaultRipple) == 0; + + return trustCreate( + view, + bSenderHigh, + uSenderID, + uReceiverID, + index.key, + sleAccount, + false, + noRipple, + false, + false, + saBalance, + saReceiverLimit, + 0, + 0, + j); +} + +// Send regardless of limits. +// --> saAmount: Amount/currency/issuer to deliver to receiver. +// <-- saActual: Amount actually cost. Sender pays fees. +static TER +rippleSendIOU( + ApplyView& view, + AccountID const& uSenderID, + AccountID const& uReceiverID, + STAmount const& saAmount, + STAmount& saActual, + beast::Journal j, + WaiveTransferFee waiveFee) +{ + auto const& issuer = saAmount.getIssuer(); + + XRPL_ASSERT( + !isXRP(uSenderID) && !isXRP(uReceiverID), + "xrpl::rippleSendIOU : neither sender nor receiver is XRP"); + XRPL_ASSERT(uSenderID != uReceiverID, "xrpl::rippleSendIOU : sender is not receiver"); + + if (uSenderID == issuer || uReceiverID == issuer || issuer == noAccount()) + { + // Direct send: redeeming IOUs and/or sending own IOUs. + auto const ter = rippleCreditIOU(view, uSenderID, uReceiverID, saAmount, false, j); + if (!isTesSuccess(ter)) + return ter; + saActual = saAmount; + return tesSUCCESS; + } + + // Sending 3rd party IOUs: transit. + + // Calculate the amount to transfer accounting + // for any transfer fees if the fee is not waived: + saActual = (waiveFee == WaiveTransferFee::Yes) ? saAmount + : multiply(saAmount, transferRate(view, issuer)); + + JLOG(j.debug()) << "rippleSendIOU> " << to_string(uSenderID) << " - > " + << to_string(uReceiverID) << " : deliver=" << saAmount.getFullText() + << " cost=" << saActual.getFullText(); + + TER terResult = rippleCreditIOU(view, issuer, uReceiverID, saAmount, true, j); + + if (tesSUCCESS == terResult) + terResult = rippleCreditIOU(view, uSenderID, issuer, saActual, true, j); + + return terResult; +} + +// Send regardless of limits. +// --> receivers: Amount/currency/issuer to deliver to receivers. +// <-- saActual: Amount actually cost to sender. Sender pays fees. +static TER +rippleSendMultiIOU( + ApplyView& view, + AccountID const& senderID, + Issue const& issue, + MultiplePaymentDestinations const& receivers, + STAmount& actual, + beast::Journal j, + WaiveTransferFee waiveFee) +{ + auto const& issuer = issue.getIssuer(); + + XRPL_ASSERT(!isXRP(senderID), "xrpl::rippleSendMultiIOU : sender is not XRP"); + + // These may diverge + STAmount takeFromSender{issue}; + actual = takeFromSender; + + // Failures return immediately. + for (auto const& r : receivers) + { + auto const& receiverID = r.first; + STAmount amount{issue, r.second}; + + /* If we aren't sending anything or if the sender is the same as the + * receiver then we don't need to do anything. + */ + if (!amount || (senderID == receiverID)) + continue; + + XRPL_ASSERT(!isXRP(receiverID), "xrpl::rippleSendMultiIOU : receiver is not XRP"); + + if (senderID == issuer || receiverID == issuer || issuer == noAccount()) + { + // Direct send: redeeming IOUs and/or sending own IOUs. + if (auto const ter = rippleCreditIOU(view, senderID, receiverID, amount, false, j)) + return ter; + actual += amount; + // Do not add amount to takeFromSender, because rippleCreditIOU took + // it. + + continue; + } + + // Sending 3rd party IOUs: transit. + + // Calculate the amount to transfer accounting + // for any transfer fees if the fee is not waived: + STAmount actualSend = (waiveFee == WaiveTransferFee::Yes) + ? amount + : multiply(amount, transferRate(view, issuer)); + actual += actualSend; + takeFromSender += actualSend; + + JLOG(j.debug()) << "rippleSendMultiIOU> " << to_string(senderID) << " - > " + << to_string(receiverID) << " : deliver=" << amount.getFullText() + << " cost=" << actual.getFullText(); + + if (TER const terResult = rippleCreditIOU(view, issuer, receiverID, amount, true, j)) + return terResult; + } + + if (senderID != issuer && takeFromSender) + { + if (TER const terResult = rippleCreditIOU(view, senderID, issuer, takeFromSender, true, j)) + return terResult; + } + + return tesSUCCESS; +} + +static TER +accountSendIOU( + ApplyView& view, + AccountID const& uSenderID, + AccountID const& uReceiverID, + STAmount const& saAmount, + beast::Journal j, + WaiveTransferFee waiveFee) +{ + if (view.rules().enabled(fixAMMv1_1)) + { + if (saAmount < beast::zero || saAmount.holds()) + { + return tecINTERNAL; // LCOV_EXCL_LINE + } + } + else + { + // LCOV_EXCL_START + XRPL_ASSERT( + saAmount >= beast::zero && !saAmount.holds(), + "xrpl::accountSendIOU : minimum amount and not MPT"); + // LCOV_EXCL_STOP + } + + /* If we aren't sending anything or if the sender is the same as the + * receiver then we don't need to do anything. + */ + if (!saAmount || (uSenderID == uReceiverID)) + return tesSUCCESS; + + if (!saAmount.native()) + { + STAmount saActual; + + JLOG(j.trace()) << "accountSendIOU: " << to_string(uSenderID) << " -> " + << to_string(uReceiverID) << " : " << saAmount.getFullText(); + + return rippleSendIOU(view, uSenderID, uReceiverID, saAmount, saActual, j, waiveFee); + } + + /* XRP send which does not check reserve and can do pure adjustment. + * Note that sender or receiver may be null and this not a mistake; this + * setup is used during pathfinding and it is carefully controlled to + * ensure that transfers are balanced. + */ + TER terResult(tesSUCCESS); + + SLE::pointer sender = + uSenderID != beast::zero ? view.peek(keylet::account(uSenderID)) : SLE::pointer(); + SLE::pointer receiver = + uReceiverID != beast::zero ? view.peek(keylet::account(uReceiverID)) : SLE::pointer(); + + if (auto stream = j.trace()) + { + std::string sender_bal("-"); + std::string receiver_bal("-"); + + if (sender) + sender_bal = sender->getFieldAmount(sfBalance).getFullText(); + + if (receiver) + receiver_bal = receiver->getFieldAmount(sfBalance).getFullText(); + + stream << "accountSendIOU> " << to_string(uSenderID) << " (" << sender_bal << ") -> " + << to_string(uReceiverID) << " (" << receiver_bal + << ") : " << saAmount.getFullText(); + } + + if (sender) + { + if (sender->getFieldAmount(sfBalance) < saAmount) + { + // VFALCO Its laborious to have to mutate the + // TER based on params everywhere + // LCOV_EXCL_START + terResult = view.open() ? TER{telFAILED_PROCESSING} : TER{tecFAILED_PROCESSING}; + // LCOV_EXCL_STOP + } + else + { + auto const sndBal = sender->getFieldAmount(sfBalance); + view.creditHook(uSenderID, xrpAccount(), saAmount, sndBal); + + // Decrement XRP balance. + sender->setFieldAmount(sfBalance, sndBal - saAmount); + view.update(sender); + } + } + + if (tesSUCCESS == terResult && receiver) + { + // Increment XRP balance. + auto const rcvBal = receiver->getFieldAmount(sfBalance); + receiver->setFieldAmount(sfBalance, rcvBal + saAmount); + view.creditHook(xrpAccount(), uReceiverID, saAmount, -rcvBal); + + view.update(receiver); + } + + if (auto stream = j.trace()) + { + std::string sender_bal("-"); + std::string receiver_bal("-"); + + if (sender) + sender_bal = sender->getFieldAmount(sfBalance).getFullText(); + + if (receiver) + receiver_bal = receiver->getFieldAmount(sfBalance).getFullText(); + + stream << "accountSendIOU< " << to_string(uSenderID) << " (" << sender_bal << ") -> " + << to_string(uReceiverID) << " (" << receiver_bal + << ") : " << saAmount.getFullText(); + } + + return terResult; +} + +static TER +accountSendMultiIOU( + ApplyView& view, + AccountID const& senderID, + Issue const& issue, + MultiplePaymentDestinations const& receivers, + beast::Journal j, + WaiveTransferFee waiveFee) +{ + XRPL_ASSERT_PARTS( + receivers.size() > 1, "xrpl::accountSendMultiIOU", "multiple recipients provided"); + + if (!issue.native()) + { + STAmount actual; + JLOG(j.trace()) << "accountSendMultiIOU: " << to_string(senderID) << " sending " + << receivers.size() << " IOUs"; + + return rippleSendMultiIOU(view, senderID, issue, receivers, actual, j, waiveFee); + } + + /* XRP send which does not check reserve and can do pure adjustment. + * Note that sender or receiver may be null and this not a mistake; this + * setup could be used during pathfinding and it is carefully controlled to + * ensure that transfers are balanced. + */ + + SLE::pointer sender = + senderID != beast::zero ? view.peek(keylet::account(senderID)) : SLE::pointer(); + + if (auto stream = j.trace()) + { + std::string sender_bal("-"); + + if (sender) + sender_bal = sender->getFieldAmount(sfBalance).getFullText(); + + stream << "accountSendMultiIOU> " << to_string(senderID) << " (" << sender_bal << ") -> " + << receivers.size() << " receivers."; + } + + // Failures return immediately. + STAmount takeFromSender{issue}; + for (auto const& r : receivers) + { + auto const& receiverID = r.first; + STAmount amount{issue, r.second}; + + if (amount < beast::zero) + { + return tecINTERNAL; // LCOV_EXCL_LINE + } + + /* If we aren't sending anything or if the sender is the same as the + * receiver then we don't need to do anything. + */ + if (!amount || (senderID == receiverID)) + continue; + + SLE::pointer receiver = + receiverID != beast::zero ? view.peek(keylet::account(receiverID)) : SLE::pointer(); + + if (auto stream = j.trace()) + { + std::string receiver_bal("-"); + + if (receiver) + receiver_bal = receiver->getFieldAmount(sfBalance).getFullText(); + + stream << "accountSendMultiIOU> " << to_string(senderID) << " -> " + << to_string(receiverID) << " (" << receiver_bal + << ") : " << amount.getFullText(); + } + + if (receiver) + { + // Increment XRP balance. + auto const rcvBal = receiver->getFieldAmount(sfBalance); + receiver->setFieldAmount(sfBalance, rcvBal + amount); + view.creditHook(xrpAccount(), receiverID, amount, -rcvBal); + + view.update(receiver); + + // Take what is actually sent + takeFromSender += amount; + } + + if (auto stream = j.trace()) + { + std::string receiver_bal("-"); + + if (receiver) + receiver_bal = receiver->getFieldAmount(sfBalance).getFullText(); + + stream << "accountSendMultiIOU< " << to_string(senderID) << " -> " + << to_string(receiverID) << " (" << receiver_bal + << ") : " << amount.getFullText(); + } + } + + if (sender) + { + if (sender->getFieldAmount(sfBalance) < takeFromSender) + { + return TER{tecFAILED_PROCESSING}; + } + auto const sndBal = sender->getFieldAmount(sfBalance); + view.creditHook(senderID, xrpAccount(), takeFromSender, sndBal); + + // Decrement XRP balance. + sender->setFieldAmount(sfBalance, sndBal - takeFromSender); + view.update(sender); + } + + if (auto stream = j.trace()) + { + std::string sender_bal("-"); + + if (sender) + sender_bal = sender->getFieldAmount(sfBalance).getFullText(); + + stream << "accountSendMultiIOU< " << to_string(senderID) << " (" << sender_bal << ") -> " + << receivers.size() << " receivers."; + } + return tesSUCCESS; +} + +static TER +rippleCreditMPT( + ApplyView& view, + AccountID const& uSenderID, + AccountID const& uReceiverID, + STAmount const& saAmount, + beast::Journal j) +{ + // Do not check MPT authorization here - it must have been checked earlier + auto const mptID = keylet::mptIssuance(saAmount.get().getMptID()); + auto const& issuer = saAmount.getIssuer(); + auto sleIssuance = view.peek(mptID); + if (!sleIssuance) + return tecOBJECT_NOT_FOUND; + if (uSenderID == issuer) + { + (*sleIssuance)[sfOutstandingAmount] += saAmount.mpt().value(); + view.update(sleIssuance); + } + else + { + auto const mptokenID = keylet::mptoken(mptID.key, uSenderID); + if (auto sle = view.peek(mptokenID)) + { + auto const amt = sle->getFieldU64(sfMPTAmount); + auto const pay = saAmount.mpt().value(); + if (amt < pay) + return tecINSUFFICIENT_FUNDS; + (*sle)[sfMPTAmount] = amt - pay; + view.update(sle); + } + else + { + return tecNO_AUTH; + } + } + + if (uReceiverID == issuer) + { + auto const outstanding = sleIssuance->getFieldU64(sfOutstandingAmount); + auto const redeem = saAmount.mpt().value(); + if (outstanding >= redeem) + { + sleIssuance->setFieldU64(sfOutstandingAmount, outstanding - redeem); + view.update(sleIssuance); + } + else + { + return tecINTERNAL; // LCOV_EXCL_LINE + } + } + else + { + auto const mptokenID = keylet::mptoken(mptID.key, uReceiverID); + if (auto sle = view.peek(mptokenID)) + { + (*sle)[sfMPTAmount] += saAmount.mpt().value(); + view.update(sle); + } + else + { + return tecNO_AUTH; + } + } + + return tesSUCCESS; +} + +static TER +rippleSendMPT( + ApplyView& view, + AccountID const& uSenderID, + AccountID const& uReceiverID, + STAmount const& saAmount, + STAmount& saActual, + beast::Journal j, + WaiveTransferFee waiveFee) +{ + XRPL_ASSERT(uSenderID != uReceiverID, "xrpl::rippleSendMPT : sender is not receiver"); + + // Safe to get MPT since rippleSendMPT is only called by accountSendMPT + auto const& issuer = saAmount.getIssuer(); + + auto const sle = view.read(keylet::mptIssuance(saAmount.get().getMptID())); + if (!sle) + return tecOBJECT_NOT_FOUND; + + if (uSenderID == issuer || uReceiverID == issuer) + { + // if sender is issuer, check that the new OutstandingAmount will not + // exceed MaximumAmount + if (uSenderID == issuer) + { + auto const sendAmount = saAmount.mpt().value(); + auto const maximumAmount = sle->at(~sfMaximumAmount).value_or(maxMPTokenAmount); + if (sendAmount > maximumAmount || + sle->getFieldU64(sfOutstandingAmount) > maximumAmount - sendAmount) + return tecPATH_DRY; + } + + // Direct send: redeeming MPTs and/or sending own MPTs. + auto const ter = rippleCreditMPT(view, uSenderID, uReceiverID, saAmount, j); + if (!isTesSuccess(ter)) + return ter; + saActual = saAmount; + return tesSUCCESS; + } + + // Sending 3rd party MPTs: transit. + saActual = (waiveFee == WaiveTransferFee::Yes) + ? saAmount + : multiply(saAmount, transferRate(view, saAmount.get().getMptID())); + + JLOG(j.debug()) << "rippleSendMPT> " << to_string(uSenderID) << " - > " + << to_string(uReceiverID) << " : deliver=" << saAmount.getFullText() + << " cost=" << saActual.getFullText(); + + if (auto const terResult = rippleCreditMPT(view, issuer, uReceiverID, saAmount, j); + !isTesSuccess(terResult)) + return terResult; + + return rippleCreditMPT(view, uSenderID, issuer, saActual, j); +} + +static TER +rippleSendMultiMPT( + ApplyView& view, + AccountID const& senderID, + MPTIssue const& mptIssue, + MultiplePaymentDestinations const& receivers, + STAmount& actual, + beast::Journal j, + WaiveTransferFee waiveFee) +{ + // Safe to get MPT since rippleSendMultiMPT is only called by + // accountSendMultiMPT + auto const& issuer = mptIssue.getIssuer(); + + auto const sle = view.read(keylet::mptIssuance(mptIssue.getMptID())); + if (!sle) + return tecOBJECT_NOT_FOUND; + + // These may diverge + STAmount takeFromSender{mptIssue}; + actual = takeFromSender; + + for (auto const& r : receivers) + { + auto const& receiverID = r.first; + STAmount amount{mptIssue, r.second}; + + if (amount < beast::zero) + { + return tecINTERNAL; // LCOV_EXCL_LINE + } + + /* If we aren't sending anything or if the sender is the same as the + * receiver then we don't need to do anything. + */ + if (!amount || (senderID == receiverID)) + continue; + + if (senderID == issuer || receiverID == issuer) + { + // if sender is issuer, check that the new OutstandingAmount will + // not exceed MaximumAmount + if (senderID == issuer) + { + XRPL_ASSERT_PARTS( + takeFromSender == beast::zero, + "xrpl::rippleSendMultiMPT", + "sender == issuer, takeFromSender == zero"); + auto const sendAmount = amount.mpt().value(); + auto const maximumAmount = sle->at(~sfMaximumAmount).value_or(maxMPTokenAmount); + if (sendAmount > maximumAmount || + sle->getFieldU64(sfOutstandingAmount) > maximumAmount - sendAmount) + return tecPATH_DRY; + } + + // Direct send: redeeming MPTs and/or sending own MPTs. + if (auto const ter = rippleCreditMPT(view, senderID, receiverID, amount, j)) + return ter; + actual += amount; + // Do not add amount to takeFromSender, because rippleCreditMPT took + // it + + continue; + } + + // Sending 3rd party MPTs: transit. + STAmount actualSend = (waiveFee == WaiveTransferFee::Yes) + ? amount + : multiply(amount, transferRate(view, amount.get().getMptID())); + actual += actualSend; + takeFromSender += actualSend; + + JLOG(j.debug()) << "rippleSendMultiMPT> " << to_string(senderID) << " - > " + << to_string(receiverID) << " : deliver=" << amount.getFullText() + << " cost=" << actualSend.getFullText(); + + if (auto const terResult = rippleCreditMPT(view, issuer, receiverID, amount, j)) + return terResult; + } + if (senderID != issuer && takeFromSender) + { + if (TER const terResult = rippleCreditMPT(view, senderID, issuer, takeFromSender, j)) + return terResult; + } + + return tesSUCCESS; +} + +static TER +accountSendMPT( + ApplyView& view, + AccountID const& uSenderID, + AccountID const& uReceiverID, + STAmount const& saAmount, + beast::Journal j, + WaiveTransferFee waiveFee) +{ + XRPL_ASSERT( + saAmount >= beast::zero && saAmount.holds(), + "xrpl::accountSendMPT : minimum amount and MPT"); + + /* If we aren't sending anything or if the sender is the same as the + * receiver then we don't need to do anything. + */ + if (!saAmount || (uSenderID == uReceiverID)) + return tesSUCCESS; + + STAmount saActual{saAmount.asset()}; + + return rippleSendMPT(view, uSenderID, uReceiverID, saAmount, saActual, j, waiveFee); +} + +static TER +accountSendMultiMPT( + ApplyView& view, + AccountID const& senderID, + MPTIssue const& mptIssue, + MultiplePaymentDestinations const& receivers, + beast::Journal j, + WaiveTransferFee waiveFee) +{ + STAmount actual; + + return rippleSendMultiMPT(view, senderID, mptIssue, receivers, actual, j, waiveFee); +} + +//------------------------------------------------------------------------------ +// +// Public Dispatcher Functions +// +//------------------------------------------------------------------------------ + +TER +rippleCredit( + ApplyView& view, + AccountID const& uSenderID, + AccountID const& uReceiverID, + STAmount const& saAmount, + bool bCheckIssuer, + beast::Journal j) +{ + return std::visit( + [&](TIss const& issue) { + if constexpr (std::is_same_v) + { + return rippleCreditIOU(view, uSenderID, uReceiverID, saAmount, bCheckIssuer, j); + } + else + { + XRPL_ASSERT(!bCheckIssuer, "xrpl::rippleCredit : not checking issuer"); + return rippleCreditMPT(view, uSenderID, uReceiverID, saAmount, j); + } + }, + saAmount.asset().value()); +} + +TER +accountSend( + ApplyView& view, + AccountID const& uSenderID, + AccountID const& uReceiverID, + STAmount const& saAmount, + beast::Journal j, + WaiveTransferFee waiveFee) +{ + return std::visit( + [&](TIss const& issue) { + if constexpr (std::is_same_v) + { + return accountSendIOU(view, uSenderID, uReceiverID, saAmount, j, waiveFee); + } + else + { + return accountSendMPT(view, uSenderID, uReceiverID, saAmount, j, waiveFee); + } + }, + saAmount.asset().value()); +} + +TER +accountSendMulti( + ApplyView& view, + AccountID const& senderID, + Asset const& asset, + MultiplePaymentDestinations const& receivers, + beast::Journal j, + WaiveTransferFee waiveFee) +{ + XRPL_ASSERT_PARTS( + receivers.size() > 1, "xrpl::accountSendMulti", "multiple recipients provided"); + return std::visit( + [&](TIss const& issue) { + if constexpr (std::is_same_v) + { + return accountSendMultiIOU(view, senderID, issue, receivers, j, waiveFee); + } + else + { + return accountSendMultiMPT(view, senderID, issue, receivers, j, waiveFee); + } + }, + asset.value()); +} + +TER +transferXRP( + ApplyView& view, + AccountID const& from, + AccountID const& to, + STAmount const& amount, + beast::Journal j) +{ + XRPL_ASSERT(from != beast::zero, "xrpl::transferXRP : nonzero from account"); + XRPL_ASSERT(to != beast::zero, "xrpl::transferXRP : nonzero to account"); + XRPL_ASSERT(from != to, "xrpl::transferXRP : sender is not receiver"); + XRPL_ASSERT(amount.native(), "xrpl::transferXRP : amount is XRP"); + + SLE::pointer const sender = view.peek(keylet::account(from)); + SLE::pointer const receiver = view.peek(keylet::account(to)); + if (!sender || !receiver) + return tefINTERNAL; // LCOV_EXCL_LINE + + JLOG(j.trace()) << "transferXRP: " << to_string(from) << " -> " << to_string(to) + << ") : " << amount.getFullText(); + + if (sender->getFieldAmount(sfBalance) < amount) + { + // VFALCO Its unfortunate we have to keep + // mutating these TER everywhere + // FIXME: this logic should be moved to callers maybe? + // LCOV_EXCL_START + return view.open() ? TER{telFAILED_PROCESSING} : TER{tecFAILED_PROCESSING}; + // LCOV_EXCL_STOP + } + + // Decrement XRP balance. + sender->setFieldAmount(sfBalance, sender->getFieldAmount(sfBalance) - amount); + view.update(sender); + + receiver->setFieldAmount(sfBalance, receiver->getFieldAmount(sfBalance) + amount); + view.update(receiver); + + return tesSUCCESS; +} + +} // namespace xrpl diff --git a/src/libxrpl/ledger/helpers/VaultHelpers.cpp b/src/libxrpl/ledger/helpers/VaultHelpers.cpp new file mode 100644 index 0000000000..3ded720289 --- /dev/null +++ b/src/libxrpl/ledger/helpers/VaultHelpers.cpp @@ -0,0 +1,112 @@ +#include +// +#include +#include +#include + +namespace xrpl { + +[[nodiscard]] std::optional +assetsToSharesDeposit( + std::shared_ptr const& vault, + std::shared_ptr const& issuance, + STAmount const& assets) +{ + XRPL_ASSERT(!assets.negative(), "xrpl::assetsToSharesDeposit : non-negative assets"); + XRPL_ASSERT( + assets.asset() == vault->at(sfAsset), + "xrpl::assetsToSharesDeposit : assets and vault match"); + if (assets.negative() || assets.asset() != vault->at(sfAsset)) + return std::nullopt; // LCOV_EXCL_LINE + + Number const assetTotal = vault->at(sfAssetsTotal); + STAmount shares{vault->at(sfShareMPTID)}; + if (assetTotal == 0) + { + return STAmount{ + shares.asset(), + Number(assets.mantissa(), assets.exponent() + vault->at(sfScale)).truncate()}; + } + + Number const shareTotal = issuance->at(sfOutstandingAmount); + shares = ((shareTotal * assets) / assetTotal).truncate(); + return shares; +} + +[[nodiscard]] std::optional +sharesToAssetsDeposit( + std::shared_ptr const& vault, + std::shared_ptr const& issuance, + STAmount const& shares) +{ + XRPL_ASSERT(!shares.negative(), "xrpl::sharesToAssetsDeposit : non-negative shares"); + XRPL_ASSERT( + shares.asset() == vault->at(sfShareMPTID), + "xrpl::sharesToAssetsDeposit : shares and vault match"); + if (shares.negative() || shares.asset() != vault->at(sfShareMPTID)) + return std::nullopt; // LCOV_EXCL_LINE + + Number const assetTotal = vault->at(sfAssetsTotal); + STAmount assets{vault->at(sfAsset)}; + if (assetTotal == 0) + { + return STAmount{ + assets.asset(), shares.mantissa(), shares.exponent() - vault->at(sfScale), false}; + } + + Number const shareTotal = issuance->at(sfOutstandingAmount); + assets = (assetTotal * shares) / shareTotal; + return assets; +} + +[[nodiscard]] std::optional +assetsToSharesWithdraw( + std::shared_ptr const& vault, + std::shared_ptr const& issuance, + STAmount const& assets, + TruncateShares truncate) +{ + XRPL_ASSERT(!assets.negative(), "xrpl::assetsToSharesWithdraw : non-negative assets"); + XRPL_ASSERT( + assets.asset() == vault->at(sfAsset), + "xrpl::assetsToSharesWithdraw : assets and vault match"); + if (assets.negative() || assets.asset() != vault->at(sfAsset)) + return std::nullopt; // LCOV_EXCL_LINE + + Number assetTotal = vault->at(sfAssetsTotal); + assetTotal -= vault->at(sfLossUnrealized); + STAmount shares{vault->at(sfShareMPTID)}; + if (assetTotal == 0) + return shares; + Number const shareTotal = issuance->at(sfOutstandingAmount); + Number result = (shareTotal * assets) / assetTotal; + if (truncate == TruncateShares::yes) + result = result.truncate(); + shares = result; + return shares; +} + +[[nodiscard]] std::optional +sharesToAssetsWithdraw( + std::shared_ptr const& vault, + std::shared_ptr const& issuance, + STAmount const& shares) +{ + XRPL_ASSERT(!shares.negative(), "xrpl::sharesToAssetsDeposit : non-negative shares"); + XRPL_ASSERT( + shares.asset() == vault->at(sfShareMPTID), + "xrpl::sharesToAssetsWithdraw : shares and vault match"); + if (shares.negative() || shares.asset() != vault->at(sfShareMPTID)) + return std::nullopt; // LCOV_EXCL_LINE + + Number assetTotal = vault->at(sfAssetsTotal); + assetTotal -= vault->at(sfLossUnrealized); + STAmount assets{vault->at(sfAsset)}; + if (assetTotal == 0) + return assets; + Number const shareTotal = issuance->at(sfOutstandingAmount); + assets = (assetTotal * shares) / shareTotal; + return assets; +} + +} // namespace xrpl diff --git a/src/libxrpl/tx/Transactor.cpp b/src/libxrpl/tx/Transactor.cpp index ff42441e2f..1c937f9380 100644 --- a/src/libxrpl/tx/Transactor.cpp +++ b/src/libxrpl/tx/Transactor.cpp @@ -2,8 +2,8 @@ #include #include #include -#include #include +#include #include #include #include diff --git a/src/libxrpl/tx/invariants/PermissionedDomainInvariant.cpp b/src/libxrpl/tx/invariants/PermissionedDomainInvariant.cpp index d4cbe81f9b..02eaee0552 100644 --- a/src/libxrpl/tx/invariants/PermissionedDomainInvariant.cpp +++ b/src/libxrpl/tx/invariants/PermissionedDomainInvariant.cpp @@ -1,7 +1,7 @@ #include // #include -#include +#include #include #include #include diff --git a/src/libxrpl/tx/paths/Flow.cpp b/src/libxrpl/tx/paths/Flow.cpp index fc33585179..5a706ea812 100644 --- a/src/libxrpl/tx/paths/Flow.cpp +++ b/src/libxrpl/tx/paths/Flow.cpp @@ -1,5 +1,5 @@ #include -#include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/account/AccountDelete.cpp b/src/libxrpl/tx/transactors/account/AccountDelete.cpp index b50b254ec9..822b6121de 100644 --- a/src/libxrpl/tx/transactors/account/AccountDelete.cpp +++ b/src/libxrpl/tx/transactors/account/AccountDelete.cpp @@ -1,7 +1,7 @@ #include #include -#include #include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/credentials/CredentialAccept.cpp b/src/libxrpl/tx/transactors/credentials/CredentialAccept.cpp index 1c5608c09f..26ecf311fe 100644 --- a/src/libxrpl/tx/transactors/credentials/CredentialAccept.cpp +++ b/src/libxrpl/tx/transactors/credentials/CredentialAccept.cpp @@ -1,7 +1,7 @@ #include #include -#include #include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/credentials/CredentialCreate.cpp b/src/libxrpl/tx/transactors/credentials/CredentialCreate.cpp index 5dafd146c7..8d70e00d43 100644 --- a/src/libxrpl/tx/transactors/credentials/CredentialCreate.cpp +++ b/src/libxrpl/tx/transactors/credentials/CredentialCreate.cpp @@ -1,7 +1,7 @@ #include #include -#include #include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/credentials/CredentialDelete.cpp b/src/libxrpl/tx/transactors/credentials/CredentialDelete.cpp index d273135aa9..5f78ba6757 100644 --- a/src/libxrpl/tx/transactors/credentials/CredentialDelete.cpp +++ b/src/libxrpl/tx/transactors/credentials/CredentialDelete.cpp @@ -1,7 +1,7 @@ #include #include -#include #include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/dex/PermissionedDEXHelpers.cpp b/src/libxrpl/tx/transactors/dex/PermissionedDEXHelpers.cpp index 37db2d632f..d857795e39 100644 --- a/src/libxrpl/tx/transactors/dex/PermissionedDEXHelpers.cpp +++ b/src/libxrpl/tx/transactors/dex/PermissionedDEXHelpers.cpp @@ -1,4 +1,4 @@ -#include +#include #include namespace xrpl { diff --git a/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp b/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp index 680a20a077..e85b00e606 100644 --- a/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp +++ b/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp @@ -4,8 +4,8 @@ #include #include #include -#include #include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.cpp b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.cpp index 57d9cbc173..ca64c6bb56 100644 --- a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.cpp @@ -1,6 +1,6 @@ #include // -#include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/payment/DepositPreauth.cpp b/src/libxrpl/tx/transactors/payment/DepositPreauth.cpp index 2b9a8dfd3a..55a27e28ed 100644 --- a/src/libxrpl/tx/transactors/payment/DepositPreauth.cpp +++ b/src/libxrpl/tx/transactors/payment/DepositPreauth.cpp @@ -1,6 +1,6 @@ #include -#include #include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/payment/Payment.cpp b/src/libxrpl/tx/transactors/payment/Payment.cpp index 8bf86b7b38..6fc6d995fa 100644 --- a/src/libxrpl/tx/transactors/payment/Payment.cpp +++ b/src/libxrpl/tx/transactors/payment/Payment.cpp @@ -1,6 +1,6 @@ #include -#include #include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/payment_channel/PaymentChannelClaim.cpp b/src/libxrpl/tx/transactors/payment_channel/PaymentChannelClaim.cpp index a97b4c9e56..6ba489bbc3 100644 --- a/src/libxrpl/tx/transactors/payment_channel/PaymentChannelClaim.cpp +++ b/src/libxrpl/tx/transactors/payment_channel/PaymentChannelClaim.cpp @@ -1,7 +1,7 @@ #include #include -#include #include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainSet.cpp b/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainSet.cpp index c27c884b10..f4d4f6a805 100644 --- a/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainSet.cpp +++ b/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainSet.cpp @@ -1,7 +1,7 @@ #include // -#include #include +#include #include #include diff --git a/src/libxrpl/tx/transactors/vault/VaultDeposit.cpp b/src/libxrpl/tx/transactors/vault/VaultDeposit.cpp index 66f4fb09b8..bceaa354a1 100644 --- a/src/libxrpl/tx/transactors/vault/VaultDeposit.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultDeposit.cpp @@ -1,5 +1,5 @@ -#include #include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp b/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp index a473ac7c36..2507563bde 100644 --- a/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp @@ -1,5 +1,5 @@ -#include #include +#include #include #include #include diff --git a/src/test/app/Credentials_test.cpp b/src/test/app/Credentials_test.cpp index 3c3d8b6df8..d23431f68e 100644 --- a/src/test/app/Credentials_test.cpp +++ b/src/test/app/Credentials_test.cpp @@ -2,7 +2,7 @@ #include #include -#include +#include #include #include #include diff --git a/src/xrpld/app/paths/detail/DirectStep.cpp b/src/xrpld/app/paths/detail/DirectStep.cpp index a07e5824d6..142f07bf73 100644 --- a/src/xrpld/app/paths/detail/DirectStep.cpp +++ b/src/xrpld/app/paths/detail/DirectStep.cpp @@ -1,8 +1,8 @@ #include #include -#include #include +#include #include #include #include diff --git a/src/xrpld/app/paths/detail/XRPEndpointStep.cpp b/src/xrpld/app/paths/detail/XRPEndpointStep.cpp index 6eaa0d04c4..e37a184e07 100644 --- a/src/xrpld/app/paths/detail/XRPEndpointStep.cpp +++ b/src/xrpld/app/paths/detail/XRPEndpointStep.cpp @@ -1,8 +1,8 @@ #include #include -#include #include +#include #include #include #include diff --git a/src/xrpld/rpc/handlers/DepositAuthorized.cpp b/src/xrpld/rpc/handlers/DepositAuthorized.cpp index 7ab7e30c8a..080b136964 100644 --- a/src/xrpld/rpc/handlers/DepositAuthorized.cpp +++ b/src/xrpld/rpc/handlers/DepositAuthorized.cpp @@ -1,8 +1,8 @@ #include #include -#include #include +#include #include #include #include diff --git a/src/xrpld/rpc/handlers/LedgerEntry.cpp b/src/xrpld/rpc/handlers/LedgerEntry.cpp index 8e3b7f214d..640369c04b 100644 --- a/src/xrpld/rpc/handlers/LedgerEntry.cpp +++ b/src/xrpld/rpc/handlers/LedgerEntry.cpp @@ -7,8 +7,8 @@ #include #include #include -#include #include +#include #include #include #include From dcfcdab14e7944ac4a2a93af8844bec3ec01b7f6 Mon Sep 17 00:00:00 2001 From: Olek <115580134+oleks-rip@users.noreply.github.com> Date: Mon, 23 Mar 2026 14:29:34 -0400 Subject: [PATCH 04/53] fix: Remove superfluous view update from credentials (#6545) --- .../tx/transactors/credentials/CredentialCreate.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/libxrpl/tx/transactors/credentials/CredentialCreate.cpp b/src/libxrpl/tx/transactors/credentials/CredentialCreate.cpp index 8d70e00d43..af5c786c59 100644 --- a/src/libxrpl/tx/transactors/credentials/CredentialCreate.cpp +++ b/src/libxrpl/tx/transactors/credentials/CredentialCreate.cpp @@ -146,14 +146,15 @@ CredentialCreate::doApply() } else { + // Added to both dirs, owned only by issuer. CredentialAccept will transfer ownership to + // subject. CredentialDelete will remove from both dirs and decrement 1 ownerCount. auto const page = view().dirInsert(keylet::ownerDir(subject), credentialKey, describeOwnerDir(subject)); - JLOG(j_.trace()) << "Adding Credential to owner directory " << to_string(credentialKey.key) - << ": " << (page ? "success" : "failure"); + JLOG(j_.trace()) << "Adding Credential to subject directory " + << to_string(credentialKey.key) << ": " << (page ? "success" : "failure"); if (!page) return tecDIR_FULL; sleCred->setFieldU64(sfSubjectNode, *page); - view().update(view().peek(keylet::account(subject))); } view().insert(sleCred); From 8b986e4ab0bceae1310f10ee43bcbce35034f4c6 Mon Sep 17 00:00:00 2001 From: Mayukha Vadari Date: Tue, 24 Mar 2026 03:20:32 -0700 Subject: [PATCH 05/53] refactor: Improve imports to only call the needed helpers (#6624) --- include/xrpl/ledger/View.h | 19 +++++-------------- include/xrpl/tx/paths/detail/StrandFlow.h | 1 + include/xrpl/tx/transactors/dex/AMMUtils.h | 1 + include/xrpl/tx/transactors/dex/AMMWithdraw.h | 1 + src/libxrpl/ledger/AcceptedLedgerTx.cpp | 1 + src/libxrpl/ledger/BookDirs.cpp | 1 + src/libxrpl/ledger/View.cpp | 3 +++ src/libxrpl/tx/Transactor.cpp | 3 +++ src/libxrpl/tx/invariants/InvariantCheck.cpp | 2 ++ src/libxrpl/tx/invariants/LoanInvariant.cpp | 1 + src/libxrpl/tx/invariants/VaultInvariant.cpp | 1 + src/libxrpl/tx/paths/BookTip.cpp | 2 ++ src/libxrpl/tx/paths/OfferStream.cpp | 2 ++ .../tx/transactors/account/AccountDelete.cpp | 2 ++ .../tx/transactors/account/AccountSet.cpp | 1 + .../tx/transactors/account/SignerListSet.cpp | 3 ++- .../tx/transactors/bridge/XChainBridge.cpp | 3 ++- .../tx/transactors/check/CheckCancel.cpp | 1 + .../tx/transactors/check/CheckCash.cpp | 2 ++ .../tx/transactors/check/CheckCreate.cpp | 3 +++ .../credentials/CredentialAccept.cpp | 2 +- .../credentials/CredentialCreate.cpp | 3 ++- .../tx/transactors/delegate/DelegateSet.cpp | 2 ++ src/libxrpl/tx/transactors/dex/AMMCreate.cpp | 1 + src/libxrpl/tx/transactors/dex/AMMDeposit.cpp | 1 + .../tx/transactors/dex/OfferCancel.cpp | 1 + .../tx/transactors/dex/OfferCreate.cpp | 4 ++++ src/libxrpl/tx/transactors/did/DIDDelete.cpp | 2 +- src/libxrpl/tx/transactors/did/DIDSet.cpp | 3 ++- .../tx/transactors/escrow/EscrowCancel.cpp | 4 ++++ .../tx/transactors/escrow/EscrowCreate.cpp | 5 +++++ .../tx/transactors/escrow/EscrowFinish.cpp | 3 +++ .../tx/transactors/escrow/EscrowHelpers.h | 4 ++++ .../lending/LoanBrokerCoverClawback.cpp | 1 + .../lending/LoanBrokerCoverDeposit.cpp | 1 + .../lending/LoanBrokerCoverWithdraw.cpp | 2 ++ .../transactors/lending/LoanBrokerDelete.cpp | 2 ++ .../tx/transactors/lending/LoanBrokerSet.cpp | 2 ++ .../tx/transactors/lending/LoanDelete.cpp | 1 + .../tx/transactors/lending/LoanManage.cpp | 1 + .../tx/transactors/lending/LoanPay.cpp | 1 + .../tx/transactors/lending/LoanSet.cpp | 2 ++ .../tx/transactors/nft/NFTokenAcceptOffer.cpp | 1 + .../tx/transactors/nft/NFTokenUtils.cpp | 4 ++++ .../tx/transactors/oracle/OracleDelete.cpp | 1 + .../tx/transactors/oracle/OracleSet.cpp | 2 ++ .../tx/transactors/payment/DepositPreauth.cpp | 2 ++ .../tx/transactors/payment/Payment.cpp | 4 ++++ .../payment_channel/PaymentChannelCreate.cpp | 2 ++ .../payment_channel/PaymentChannelHelpers.cpp | 1 + .../PermissionedDomainDelete.cpp | 1 + .../PermissionedDomainSet.cpp | 2 ++ .../tx/transactors/system/TicketCreate.cpp | 2 ++ src/libxrpl/tx/transactors/token/Clawback.cpp | 2 ++ .../tx/transactors/token/MPTokenAuthorize.cpp | 3 +++ .../token/MPTokenIssuanceCreate.cpp | 2 ++ .../token/MPTokenIssuanceDestroy.cpp | 1 + src/libxrpl/tx/transactors/token/TrustSet.cpp | 2 ++ .../tx/transactors/vault/VaultClawback.cpp | 2 ++ .../tx/transactors/vault/VaultCreate.cpp | 3 +++ .../tx/transactors/vault/VaultDelete.cpp | 3 +++ .../tx/transactors/vault/VaultDeposit.cpp | 3 +++ .../tx/transactors/vault/VaultWithdraw.cpp | 2 ++ src/test/app/AMM_test.cpp | 1 + src/test/app/AccountSet_test.cpp | 1 + src/test/app/Check_test.cpp | 1 + src/test/app/FeeVote_test.cpp | 2 +- src/test/app/Flow_test.cpp | 1 + src/test/app/Invariants_test.cpp | 3 +++ src/test/app/Vault_test.cpp | 3 ++- src/test/consensus/NegativeUNL_test.cpp | 2 +- src/test/jtx/PathSet.h | 1 + src/test/jtx/impl/TestHelpers.cpp | 1 + src/test/jtx/impl/mpt.cpp | 1 + src/test/jtx/impl/owners.cpp | 2 ++ src/test/jtx/owners.h | 2 +- src/test/ledger/Directory_test.cpp | 1 + src/test/ledger/PaymentSandbox_test.cpp | 3 ++- src/test/ledger/View_test.cpp | 2 ++ src/test/rpc/Book_test.cpp | 1 + src/xrpld/app/ledger/detail/LedgerToJson.cpp | 1 + src/xrpld/app/misc/NetworkOPs.cpp | 4 ++++ src/xrpld/app/paths/AMMOffer.h | 1 + src/xrpld/app/paths/TrustLine.cpp | 1 + src/xrpld/app/paths/detail/BookStep.cpp | 1 + src/xrpld/app/paths/detail/DirectStep.cpp | 1 + .../app/paths/detail/XRPEndpointStep.cpp | 1 + src/xrpld/rpc/handlers/AccountChannels.cpp | 1 + src/xrpld/rpc/handlers/AccountInfo.cpp | 1 + src/xrpld/rpc/handlers/AccountLines.cpp | 1 + src/xrpld/rpc/handlers/AccountOffers.cpp | 1 + src/xrpld/rpc/handlers/GatewayBalances.cpp | 1 + src/xrpld/rpc/handlers/NFTOffers.cpp | 1 + src/xrpld/rpc/handlers/NoRippleCheck.cpp | 1 + 94 files changed, 166 insertions(+), 25 deletions(-) diff --git a/include/xrpl/ledger/View.h b/include/xrpl/ledger/View.h index 2ea38c5b8b..55be01d677 100644 --- a/include/xrpl/ledger/View.h +++ b/include/xrpl/ledger/View.h @@ -2,28 +2,19 @@ #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 { diff --git a/include/xrpl/tx/paths/detail/StrandFlow.h b/include/xrpl/tx/paths/detail/StrandFlow.h index f99f54d0e8..2a94b9b968 100644 --- a/include/xrpl/tx/paths/detail/StrandFlow.h +++ b/include/xrpl/tx/paths/detail/StrandFlow.h @@ -2,6 +2,7 @@ #include #include +#include #include #include #include diff --git a/include/xrpl/tx/transactors/dex/AMMUtils.h b/include/xrpl/tx/transactors/dex/AMMUtils.h index 18db7e6555..77ad18106e 100644 --- a/include/xrpl/tx/transactors/dex/AMMUtils.h +++ b/include/xrpl/tx/transactors/dex/AMMUtils.h @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include diff --git a/include/xrpl/tx/transactors/dex/AMMWithdraw.h b/include/xrpl/tx/transactors/dex/AMMWithdraw.h index c15bb68644..5328b03abb 100644 --- a/include/xrpl/tx/transactors/dex/AMMWithdraw.h +++ b/include/xrpl/tx/transactors/dex/AMMWithdraw.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include namespace xrpl { diff --git a/src/libxrpl/ledger/AcceptedLedgerTx.cpp b/src/libxrpl/ledger/AcceptedLedgerTx.cpp index f0d243f9b6..005d48e6f6 100644 --- a/src/libxrpl/ledger/AcceptedLedgerTx.cpp +++ b/src/libxrpl/ledger/AcceptedLedgerTx.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include #include diff --git a/src/libxrpl/ledger/BookDirs.cpp b/src/libxrpl/ledger/BookDirs.cpp index 699d6c2879..2bdf6ac9a5 100644 --- a/src/libxrpl/ledger/BookDirs.cpp +++ b/src/libxrpl/ledger/BookDirs.cpp @@ -1,5 +1,6 @@ #include #include +#include #include namespace xrpl { diff --git a/src/libxrpl/ledger/View.cpp b/src/libxrpl/ledger/View.cpp index f51fb97993..ef6a66744d 100644 --- a/src/libxrpl/ledger/View.cpp +++ b/src/libxrpl/ledger/View.cpp @@ -4,7 +4,10 @@ #include #include #include +#include #include +#include +#include #include #include #include diff --git a/src/libxrpl/tx/Transactor.cpp b/src/libxrpl/tx/Transactor.cpp index 1c937f9380..6e334b5563 100644 --- a/src/libxrpl/tx/Transactor.cpp +++ b/src/libxrpl/tx/Transactor.cpp @@ -3,7 +3,10 @@ #include #include #include +#include #include +#include +#include #include #include #include diff --git a/src/libxrpl/tx/invariants/InvariantCheck.cpp b/src/libxrpl/tx/invariants/InvariantCheck.cpp index 00580b2548..16108472aa 100644 --- a/src/libxrpl/tx/invariants/InvariantCheck.cpp +++ b/src/libxrpl/tx/invariants/InvariantCheck.cpp @@ -3,6 +3,8 @@ #include #include #include +#include +#include #include #include #include diff --git a/src/libxrpl/tx/invariants/LoanInvariant.cpp b/src/libxrpl/tx/invariants/LoanInvariant.cpp index 01c4da46ac..0df7e409d1 100644 --- a/src/libxrpl/tx/invariants/LoanInvariant.cpp +++ b/src/libxrpl/tx/invariants/LoanInvariant.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include diff --git a/src/libxrpl/tx/invariants/VaultInvariant.cpp b/src/libxrpl/tx/invariants/VaultInvariant.cpp index e955e00b50..f0dd82c2f8 100644 --- a/src/libxrpl/tx/invariants/VaultInvariant.cpp +++ b/src/libxrpl/tx/invariants/VaultInvariant.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include diff --git a/src/libxrpl/tx/paths/BookTip.cpp b/src/libxrpl/tx/paths/BookTip.cpp index f00da6d7c7..5611a081c3 100644 --- a/src/libxrpl/tx/paths/BookTip.cpp +++ b/src/libxrpl/tx/paths/BookTip.cpp @@ -1,3 +1,5 @@ +#include +#include #include namespace xrpl { diff --git a/src/libxrpl/tx/paths/OfferStream.cpp b/src/libxrpl/tx/paths/OfferStream.cpp index b406c27298..b7dc431b23 100644 --- a/src/libxrpl/tx/paths/OfferStream.cpp +++ b/src/libxrpl/tx/paths/OfferStream.cpp @@ -1,5 +1,7 @@ #include #include +#include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/account/AccountDelete.cpp b/src/libxrpl/tx/transactors/account/AccountDelete.cpp index 822b6121de..fed265c125 100644 --- a/src/libxrpl/tx/transactors/account/AccountDelete.cpp +++ b/src/libxrpl/tx/transactors/account/AccountDelete.cpp @@ -2,6 +2,8 @@ #include #include #include +#include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/account/AccountSet.cpp b/src/libxrpl/tx/transactors/account/AccountSet.cpp index a3afe2092c..33759c6ec4 100644 --- a/src/libxrpl/tx/transactors/account/AccountSet.cpp +++ b/src/libxrpl/tx/transactors/account/AccountSet.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/account/SignerListSet.cpp b/src/libxrpl/tx/transactors/account/SignerListSet.cpp index 399e832740..fe9e80d7e0 100644 --- a/src/libxrpl/tx/transactors/account/SignerListSet.cpp +++ b/src/libxrpl/tx/transactors/account/SignerListSet.cpp @@ -1,6 +1,7 @@ #include #include -#include +#include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp b/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp index 2e274f138d..9ac755cf4d 100644 --- a/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp +++ b/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp @@ -5,7 +5,8 @@ #include #include #include -#include +#include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/check/CheckCancel.cpp b/src/libxrpl/tx/transactors/check/CheckCancel.cpp index d2a77698e0..2d08b2f1b0 100644 --- a/src/libxrpl/tx/transactors/check/CheckCancel.cpp +++ b/src/libxrpl/tx/transactors/check/CheckCancel.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/check/CheckCash.cpp b/src/libxrpl/tx/transactors/check/CheckCash.cpp index 2edd3c3a9c..7fa53c7352 100644 --- a/src/libxrpl/tx/transactors/check/CheckCash.cpp +++ b/src/libxrpl/tx/transactors/check/CheckCash.cpp @@ -1,6 +1,8 @@ #include #include #include +#include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/check/CheckCreate.cpp b/src/libxrpl/tx/transactors/check/CheckCreate.cpp index 43e000ad5b..50554a1beb 100644 --- a/src/libxrpl/tx/transactors/check/CheckCreate.cpp +++ b/src/libxrpl/tx/transactors/check/CheckCreate.cpp @@ -1,5 +1,8 @@ #include #include +#include +#include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/credentials/CredentialAccept.cpp b/src/libxrpl/tx/transactors/credentials/CredentialAccept.cpp index 26ecf311fe..c4842b54e4 100644 --- a/src/libxrpl/tx/transactors/credentials/CredentialAccept.cpp +++ b/src/libxrpl/tx/transactors/credentials/CredentialAccept.cpp @@ -1,6 +1,6 @@ #include #include -#include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/credentials/CredentialCreate.cpp b/src/libxrpl/tx/transactors/credentials/CredentialCreate.cpp index af5c786c59..f8f0f01b63 100644 --- a/src/libxrpl/tx/transactors/credentials/CredentialCreate.cpp +++ b/src/libxrpl/tx/transactors/credentials/CredentialCreate.cpp @@ -1,7 +1,8 @@ #include #include -#include +#include #include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/delegate/DelegateSet.cpp b/src/libxrpl/tx/transactors/delegate/DelegateSet.cpp index 2a9aafc6be..9fb17c4d1f 100644 --- a/src/libxrpl/tx/transactors/delegate/DelegateSet.cpp +++ b/src/libxrpl/tx/transactors/delegate/DelegateSet.cpp @@ -1,5 +1,7 @@ #include #include +#include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/dex/AMMCreate.cpp b/src/libxrpl/tx/transactors/dex/AMMCreate.cpp index 86128ed1cd..dd717948b3 100644 --- a/src/libxrpl/tx/transactors/dex/AMMCreate.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMCreate.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/dex/AMMDeposit.cpp b/src/libxrpl/tx/transactors/dex/AMMDeposit.cpp index 9b78b9e2bf..cae83ccef1 100644 --- a/src/libxrpl/tx/transactors/dex/AMMDeposit.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMDeposit.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/dex/OfferCancel.cpp b/src/libxrpl/tx/transactors/dex/OfferCancel.cpp index 58f9525f61..9d60347778 100644 --- a/src/libxrpl/tx/transactors/dex/OfferCancel.cpp +++ b/src/libxrpl/tx/transactors/dex/OfferCancel.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include diff --git a/src/libxrpl/tx/transactors/dex/OfferCreate.cpp b/src/libxrpl/tx/transactors/dex/OfferCreate.cpp index 90c00c6280..d52fa94877 100644 --- a/src/libxrpl/tx/transactors/dex/OfferCreate.cpp +++ b/src/libxrpl/tx/transactors/dex/OfferCreate.cpp @@ -2,6 +2,10 @@ #include #include #include +#include +#include +#include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/did/DIDDelete.cpp b/src/libxrpl/tx/transactors/did/DIDDelete.cpp index e09fdd3510..0d5b63635f 100644 --- a/src/libxrpl/tx/transactors/did/DIDDelete.cpp +++ b/src/libxrpl/tx/transactors/did/DIDDelete.cpp @@ -1,6 +1,6 @@ #include #include -#include +#include #include #include diff --git a/src/libxrpl/tx/transactors/did/DIDSet.cpp b/src/libxrpl/tx/transactors/did/DIDSet.cpp index 32edbce82e..cd5c9bbc96 100644 --- a/src/libxrpl/tx/transactors/did/DIDSet.cpp +++ b/src/libxrpl/tx/transactors/did/DIDSet.cpp @@ -1,6 +1,7 @@ #include #include -#include +#include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/escrow/EscrowCancel.cpp b/src/libxrpl/tx/transactors/escrow/EscrowCancel.cpp index 61e27a7c38..1250d950cd 100644 --- a/src/libxrpl/tx/transactors/escrow/EscrowCancel.cpp +++ b/src/libxrpl/tx/transactors/escrow/EscrowCancel.cpp @@ -1,8 +1,12 @@ #include #include #include +#include +#include +#include #include #include +#include #include #include diff --git a/src/libxrpl/tx/transactors/escrow/EscrowCreate.cpp b/src/libxrpl/tx/transactors/escrow/EscrowCreate.cpp index adeee09390..8b823de160 100644 --- a/src/libxrpl/tx/transactors/escrow/EscrowCreate.cpp +++ b/src/libxrpl/tx/transactors/escrow/EscrowCreate.cpp @@ -3,9 +3,14 @@ #include #include #include +#include +#include +#include +#include #include #include #include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp b/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp index e85b00e606..8a05b2b160 100644 --- a/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp +++ b/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp @@ -6,8 +6,11 @@ #include #include #include +#include +#include #include #include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/escrow/EscrowHelpers.h b/src/libxrpl/tx/transactors/escrow/EscrowHelpers.h index 2aa6ae6db5..5fdc43c359 100644 --- a/src/libxrpl/tx/transactors/escrow/EscrowHelpers.h +++ b/src/libxrpl/tx/transactors/escrow/EscrowHelpers.h @@ -3,9 +3,13 @@ #include #include #include +#include +#include +#include #include #include #include +#include #include namespace xrpl { diff --git a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp index 4c55a7d33a..24aa3f8bf2 100644 --- a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp @@ -1,5 +1,6 @@ #include // +#include #include #include diff --git a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverDeposit.cpp b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverDeposit.cpp index 83f7d2d1c6..4630e6a360 100644 --- a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverDeposit.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverDeposit.cpp @@ -1,5 +1,6 @@ #include // +#include #include #include diff --git a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.cpp b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.cpp index ca64c6bb56..6946992376 100644 --- a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.cpp @@ -1,6 +1,8 @@ #include // +#include #include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/lending/LoanBrokerDelete.cpp b/src/libxrpl/tx/transactors/lending/LoanBrokerDelete.cpp index 85026654da..a755db7942 100644 --- a/src/libxrpl/tx/transactors/lending/LoanBrokerDelete.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanBrokerDelete.cpp @@ -1,5 +1,7 @@ #include // +#include +#include #include #include diff --git a/src/libxrpl/tx/transactors/lending/LoanBrokerSet.cpp b/src/libxrpl/tx/transactors/lending/LoanBrokerSet.cpp index 2632b55812..f8813ddbef 100644 --- a/src/libxrpl/tx/transactors/lending/LoanBrokerSet.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanBrokerSet.cpp @@ -1,5 +1,7 @@ #include // +#include +#include #include #include diff --git a/src/libxrpl/tx/transactors/lending/LoanDelete.cpp b/src/libxrpl/tx/transactors/lending/LoanDelete.cpp index e7d219d6c8..39b28f5110 100644 --- a/src/libxrpl/tx/transactors/lending/LoanDelete.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanDelete.cpp @@ -1,5 +1,6 @@ #include // +#include #include #include diff --git a/src/libxrpl/tx/transactors/lending/LoanManage.cpp b/src/libxrpl/tx/transactors/lending/LoanManage.cpp index 2dacb453b5..d507ba5499 100644 --- a/src/libxrpl/tx/transactors/lending/LoanManage.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanManage.cpp @@ -1,5 +1,6 @@ #include // +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/lending/LoanPay.cpp b/src/libxrpl/tx/transactors/lending/LoanPay.cpp index 3543b7607f..8739cb645a 100644 --- a/src/libxrpl/tx/transactors/lending/LoanPay.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanPay.cpp @@ -1,6 +1,7 @@ #include // #include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/lending/LoanSet.cpp b/src/libxrpl/tx/transactors/lending/LoanSet.cpp index 7212f079ce..f046a24961 100644 --- a/src/libxrpl/tx/transactors/lending/LoanSet.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanSet.cpp @@ -1,5 +1,7 @@ #include // +#include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/nft/NFTokenAcceptOffer.cpp b/src/libxrpl/tx/transactors/nft/NFTokenAcceptOffer.cpp index 3022188ccf..15a745b8dd 100644 --- a/src/libxrpl/tx/transactors/nft/NFTokenAcceptOffer.cpp +++ b/src/libxrpl/tx/transactors/nft/NFTokenAcceptOffer.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/nft/NFTokenUtils.cpp b/src/libxrpl/tx/transactors/nft/NFTokenUtils.cpp index 40b7171015..f7c12b5488 100644 --- a/src/libxrpl/tx/transactors/nft/NFTokenUtils.cpp +++ b/src/libxrpl/tx/transactors/nft/NFTokenUtils.cpp @@ -1,6 +1,10 @@ #include #include #include +#include +#include +#include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/oracle/OracleDelete.cpp b/src/libxrpl/tx/transactors/oracle/OracleDelete.cpp index e55d96e246..bde403f821 100644 --- a/src/libxrpl/tx/transactors/oracle/OracleDelete.cpp +++ b/src/libxrpl/tx/transactors/oracle/OracleDelete.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/oracle/OracleSet.cpp b/src/libxrpl/tx/transactors/oracle/OracleSet.cpp index 6b21df4d2a..061dd16b0c 100644 --- a/src/libxrpl/tx/transactors/oracle/OracleSet.cpp +++ b/src/libxrpl/tx/transactors/oracle/OracleSet.cpp @@ -1,5 +1,7 @@ #include #include +#include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/payment/DepositPreauth.cpp b/src/libxrpl/tx/transactors/payment/DepositPreauth.cpp index 55a27e28ed..60b8dcd823 100644 --- a/src/libxrpl/tx/transactors/payment/DepositPreauth.cpp +++ b/src/libxrpl/tx/transactors/payment/DepositPreauth.cpp @@ -1,6 +1,8 @@ #include #include +#include #include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/payment/Payment.cpp b/src/libxrpl/tx/transactors/payment/Payment.cpp index 6fc6d995fa..38765016b5 100644 --- a/src/libxrpl/tx/transactors/payment/Payment.cpp +++ b/src/libxrpl/tx/transactors/payment/Payment.cpp @@ -1,8 +1,12 @@ #include #include +#include #include +#include +#include #include #include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/payment_channel/PaymentChannelCreate.cpp b/src/libxrpl/tx/transactors/payment_channel/PaymentChannelCreate.cpp index 113dd89221..3f7e1e1814 100644 --- a/src/libxrpl/tx/transactors/payment_channel/PaymentChannelCreate.cpp +++ b/src/libxrpl/tx/transactors/payment_channel/PaymentChannelCreate.cpp @@ -1,6 +1,8 @@ #include #include #include +#include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/payment_channel/PaymentChannelHelpers.cpp b/src/libxrpl/tx/transactors/payment_channel/PaymentChannelHelpers.cpp index 75b68768ed..176b920e6b 100644 --- a/src/libxrpl/tx/transactors/payment_channel/PaymentChannelHelpers.cpp +++ b/src/libxrpl/tx/transactors/payment_channel/PaymentChannelHelpers.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include diff --git a/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainDelete.cpp b/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainDelete.cpp index 2c7e934fc0..565631b3fd 100644 --- a/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainDelete.cpp +++ b/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainDelete.cpp @@ -1,4 +1,5 @@ #include +#include #include #include diff --git a/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainSet.cpp b/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainSet.cpp index f4d4f6a805..e8df51c9d9 100644 --- a/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainSet.cpp +++ b/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainSet.cpp @@ -1,7 +1,9 @@ #include // #include +#include #include +#include #include #include diff --git a/src/libxrpl/tx/transactors/system/TicketCreate.cpp b/src/libxrpl/tx/transactors/system/TicketCreate.cpp index 8a9a5cbc93..a064c158d1 100644 --- a/src/libxrpl/tx/transactors/system/TicketCreate.cpp +++ b/src/libxrpl/tx/transactors/system/TicketCreate.cpp @@ -1,5 +1,7 @@ #include #include +#include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/token/Clawback.cpp b/src/libxrpl/tx/transactors/token/Clawback.cpp index a3ac810e90..e8ba3cc0c5 100644 --- a/src/libxrpl/tx/transactors/token/Clawback.cpp +++ b/src/libxrpl/tx/transactors/token/Clawback.cpp @@ -1,4 +1,6 @@ #include +#include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/token/MPTokenAuthorize.cpp b/src/libxrpl/tx/transactors/token/MPTokenAuthorize.cpp index 208936a5e6..77551b372b 100644 --- a/src/libxrpl/tx/transactors/token/MPTokenAuthorize.cpp +++ b/src/libxrpl/tx/transactors/token/MPTokenAuthorize.cpp @@ -1,4 +1,7 @@ #include +#include +#include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp b/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp index 9f9362da4e..58accf0271 100644 --- a/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp +++ b/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp @@ -1,4 +1,6 @@ #include +#include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/token/MPTokenIssuanceDestroy.cpp b/src/libxrpl/tx/transactors/token/MPTokenIssuanceDestroy.cpp index 1df4da47ab..8ec1f37886 100644 --- a/src/libxrpl/tx/transactors/token/MPTokenIssuanceDestroy.cpp +++ b/src/libxrpl/tx/transactors/token/MPTokenIssuanceDestroy.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/token/TrustSet.cpp b/src/libxrpl/tx/transactors/token/TrustSet.cpp index c620592619..22588b977a 100644 --- a/src/libxrpl/tx/transactors/token/TrustSet.cpp +++ b/src/libxrpl/tx/transactors/token/TrustSet.cpp @@ -1,5 +1,7 @@ #include #include +#include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/vault/VaultClawback.cpp b/src/libxrpl/tx/transactors/vault/VaultClawback.cpp index ed47dfb63d..a650aed310 100644 --- a/src/libxrpl/tx/transactors/vault/VaultClawback.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultClawback.cpp @@ -1,5 +1,7 @@ #include #include +#include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/vault/VaultCreate.cpp b/src/libxrpl/tx/transactors/vault/VaultCreate.cpp index a5b039f06b..0fc074bae2 100644 --- a/src/libxrpl/tx/transactors/vault/VaultCreate.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultCreate.cpp @@ -1,4 +1,7 @@ #include +#include +#include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/vault/VaultDelete.cpp b/src/libxrpl/tx/transactors/vault/VaultDelete.cpp index ad39ed9cf2..1e2e46e165 100644 --- a/src/libxrpl/tx/transactors/vault/VaultDelete.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultDelete.cpp @@ -1,4 +1,7 @@ #include +#include +#include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/vault/VaultDeposit.cpp b/src/libxrpl/tx/transactors/vault/VaultDeposit.cpp index bceaa354a1..04b249d211 100644 --- a/src/libxrpl/tx/transactors/vault/VaultDeposit.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultDeposit.cpp @@ -1,5 +1,8 @@ #include #include +#include +#include +#include #include #include #include diff --git a/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp b/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp index 2507563bde..e4c671b462 100644 --- a/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp @@ -1,5 +1,7 @@ #include #include +#include +#include #include #include #include diff --git a/src/test/app/AMM_test.cpp b/src/test/app/AMM_test.cpp index f84253588c..a0a38b9791 100644 --- a/src/test/app/AMM_test.cpp +++ b/src/test/app/AMM_test.cpp @@ -7,6 +7,7 @@ #include #include +#include #include #include #include diff --git a/src/test/app/AccountSet_test.cpp b/src/test/app/AccountSet_test.cpp index cfd7262a50..7af917a0b9 100644 --- a/src/test/app/AccountSet_test.cpp +++ b/src/test/app/AccountSet_test.cpp @@ -1,5 +1,6 @@ #include +#include #include #include #include diff --git a/src/test/app/Check_test.cpp b/src/test/app/Check_test.cpp index f8bb0ddcf2..671f8aab1a 100644 --- a/src/test/app/Check_test.cpp +++ b/src/test/app/Check_test.cpp @@ -1,5 +1,6 @@ #include +#include #include #include diff --git a/src/test/app/FeeVote_test.cpp b/src/test/app/FeeVote_test.cpp index f4b8c1874c..f0599b8771 100644 --- a/src/test/app/FeeVote_test.cpp +++ b/src/test/app/FeeVote_test.cpp @@ -4,7 +4,7 @@ #include #include -#include +#include #include #include #include diff --git a/src/test/app/Flow_test.cpp b/src/test/app/Flow_test.cpp index 692d9d2b50..1e9514f756 100644 --- a/src/test/app/Flow_test.cpp +++ b/src/test/app/Flow_test.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include diff --git a/src/test/app/Invariants_test.cpp b/src/test/app/Invariants_test.cpp index e17ef1fd55..8372bb340b 100644 --- a/src/test/app/Invariants_test.cpp +++ b/src/test/app/Invariants_test.cpp @@ -4,6 +4,9 @@ #include #include +#include +#include +#include #include #include #include diff --git a/src/test/app/Vault_test.cpp b/src/test/app/Vault_test.cpp index e62f7fee50..27a8d3b2e0 100644 --- a/src/test/app/Vault_test.cpp +++ b/src/test/app/Vault_test.cpp @@ -9,8 +9,9 @@ #include #include #include +#include #include -#include +#include #include #include #include diff --git a/src/test/consensus/NegativeUNL_test.cpp b/src/test/consensus/NegativeUNL_test.cpp index 23f7610300..46c6936809 100644 --- a/src/test/consensus/NegativeUNL_test.cpp +++ b/src/test/consensus/NegativeUNL_test.cpp @@ -6,7 +6,7 @@ #include #include -#include +#include #include namespace xrpl { diff --git a/src/test/jtx/PathSet.h b/src/test/jtx/PathSet.h index a363f9dff9..c522ed635e 100644 --- a/src/test/jtx/PathSet.h +++ b/src/test/jtx/PathSet.h @@ -3,6 +3,7 @@ #include #include +#include #include namespace xrpl { diff --git a/src/test/jtx/impl/TestHelpers.cpp b/src/test/jtx/impl/TestHelpers.cpp index 5e7a31adcd..e10a0c46d0 100644 --- a/src/test/jtx/impl/TestHelpers.cpp +++ b/src/test/jtx/impl/TestHelpers.cpp @@ -2,6 +2,7 @@ #include #include +#include #include namespace xrpl { diff --git a/src/test/jtx/impl/mpt.cpp b/src/test/jtx/impl/mpt.cpp index b6b08734c7..a6283bb6f9 100644 --- a/src/test/jtx/impl/mpt.cpp +++ b/src/test/jtx/impl/mpt.cpp @@ -1,5 +1,6 @@ #include +#include #include #include diff --git a/src/test/jtx/impl/owners.cpp b/src/test/jtx/impl/owners.cpp index 53f2302143..855c5b04ff 100644 --- a/src/test/jtx/impl/owners.cpp +++ b/src/test/jtx/impl/owners.cpp @@ -1,5 +1,7 @@ #include +#include + namespace xrpl { namespace detail { diff --git a/src/test/jtx/owners.h b/src/test/jtx/owners.h index 785a9347dd..3f54e0c55f 100644 --- a/src/test/jtx/owners.h +++ b/src/test/jtx/owners.h @@ -2,7 +2,7 @@ #include -#include +#include #include #include diff --git a/src/test/ledger/Directory_test.cpp b/src/test/ledger/Directory_test.cpp index ec76b67e9c..18649a20a8 100644 --- a/src/test/ledger/Directory_test.cpp +++ b/src/test/ledger/Directory_test.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include diff --git a/src/test/ledger/PaymentSandbox_test.cpp b/src/test/ledger/PaymentSandbox_test.cpp index 2a0d74e3d9..a5023aa328 100644 --- a/src/test/ledger/PaymentSandbox_test.cpp +++ b/src/test/ledger/PaymentSandbox_test.cpp @@ -2,7 +2,8 @@ #include #include -#include +#include +#include #include #include diff --git a/src/test/ledger/View_test.cpp b/src/test/ledger/View_test.cpp index bae29445c2..f57cb609cc 100644 --- a/src/test/ledger/View_test.cpp +++ b/src/test/ledger/View_test.cpp @@ -7,6 +7,8 @@ #include #include #include +#include +#include #include #include diff --git a/src/test/rpc/Book_test.cpp b/src/test/rpc/Book_test.cpp index 7ebe6e97ae..8136af310a 100644 --- a/src/test/rpc/Book_test.cpp +++ b/src/test/rpc/Book_test.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include #include diff --git a/src/xrpld/app/ledger/detail/LedgerToJson.cpp b/src/xrpld/app/ledger/detail/LedgerToJson.cpp index c0211059a1..ff8e7e55e9 100644 --- a/src/xrpld/app/ledger/detail/LedgerToJson.cpp +++ b/src/xrpld/app/ledger/detail/LedgerToJson.cpp @@ -7,6 +7,7 @@ #include #include +#include #include #include diff --git a/src/xrpld/app/misc/NetworkOPs.cpp b/src/xrpld/app/misc/NetworkOPs.cpp index d709981c46..aabb53230f 100644 --- a/src/xrpld/app/misc/NetworkOPs.cpp +++ b/src/xrpld/app/misc/NetworkOPs.cpp @@ -43,11 +43,15 @@ #include #include #include +#include +#include +#include #include #include #include #include #include +#include #include #include #include diff --git a/src/xrpld/app/paths/AMMOffer.h b/src/xrpld/app/paths/AMMOffer.h index ebaa7311c0..aa6132dfce 100644 --- a/src/xrpld/app/paths/AMMOffer.h +++ b/src/xrpld/app/paths/AMMOffer.h @@ -2,6 +2,7 @@ #include #include +#include #include #include diff --git a/src/xrpld/app/paths/TrustLine.cpp b/src/xrpld/app/paths/TrustLine.cpp index 6c54aa52d7..963e1402be 100644 --- a/src/xrpld/app/paths/TrustLine.cpp +++ b/src/xrpld/app/paths/TrustLine.cpp @@ -1,5 +1,6 @@ #include +#include #include #include diff --git a/src/xrpld/app/paths/detail/BookStep.cpp b/src/xrpld/app/paths/detail/BookStep.cpp index ae0c371e3e..e0053956a8 100644 --- a/src/xrpld/app/paths/detail/BookStep.cpp +++ b/src/xrpld/app/paths/detail/BookStep.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include diff --git a/src/xrpld/app/paths/detail/DirectStep.cpp b/src/xrpld/app/paths/detail/DirectStep.cpp index 142f07bf73..0c8693eef4 100644 --- a/src/xrpld/app/paths/detail/DirectStep.cpp +++ b/src/xrpld/app/paths/detail/DirectStep.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include #include diff --git a/src/xrpld/app/paths/detail/XRPEndpointStep.cpp b/src/xrpld/app/paths/detail/XRPEndpointStep.cpp index e37a184e07..620d901f22 100644 --- a/src/xrpld/app/paths/detail/XRPEndpointStep.cpp +++ b/src/xrpld/app/paths/detail/XRPEndpointStep.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include #include diff --git a/src/xrpld/rpc/handlers/AccountChannels.cpp b/src/xrpld/rpc/handlers/AccountChannels.cpp index d2c3d4546d..c418386a71 100644 --- a/src/xrpld/rpc/handlers/AccountChannels.cpp +++ b/src/xrpld/rpc/handlers/AccountChannels.cpp @@ -5,6 +5,7 @@ #include #include +#include #include #include #include diff --git a/src/xrpld/rpc/handlers/AccountInfo.cpp b/src/xrpld/rpc/handlers/AccountInfo.cpp index f144c934ec..15a6786e22 100644 --- a/src/xrpld/rpc/handlers/AccountInfo.cpp +++ b/src/xrpld/rpc/handlers/AccountInfo.cpp @@ -6,6 +6,7 @@ #include #include +#include #include #include #include diff --git a/src/xrpld/rpc/handlers/AccountLines.cpp b/src/xrpld/rpc/handlers/AccountLines.cpp index 952141fb8d..b3b93c0eb1 100644 --- a/src/xrpld/rpc/handlers/AccountLines.cpp +++ b/src/xrpld/rpc/handlers/AccountLines.cpp @@ -5,6 +5,7 @@ #include #include +#include #include #include #include diff --git a/src/xrpld/rpc/handlers/AccountOffers.cpp b/src/xrpld/rpc/handlers/AccountOffers.cpp index 842cac71eb..86ab140b03 100644 --- a/src/xrpld/rpc/handlers/AccountOffers.cpp +++ b/src/xrpld/rpc/handlers/AccountOffers.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include diff --git a/src/xrpld/rpc/handlers/GatewayBalances.cpp b/src/xrpld/rpc/handlers/GatewayBalances.cpp index 60e031c812..f7acbc77e6 100644 --- a/src/xrpld/rpc/handlers/GatewayBalances.cpp +++ b/src/xrpld/rpc/handlers/GatewayBalances.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include #include diff --git a/src/xrpld/rpc/handlers/NFTOffers.cpp b/src/xrpld/rpc/handlers/NFTOffers.cpp index 3af7c28f9e..5fe2e3bede 100644 --- a/src/xrpld/rpc/handlers/NFTOffers.cpp +++ b/src/xrpld/rpc/handlers/NFTOffers.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include diff --git a/src/xrpld/rpc/handlers/NoRippleCheck.cpp b/src/xrpld/rpc/handlers/NoRippleCheck.cpp index f21a67a31d..73f51fca1a 100644 --- a/src/xrpld/rpc/handlers/NoRippleCheck.cpp +++ b/src/xrpld/rpc/handlers/NoRippleCheck.cpp @@ -6,6 +6,7 @@ #include #include +#include #include #include #include From 0eedefbf455ca893fae6832f52e0aa46408b78d2 Mon Sep 17 00:00:00 2001 From: Alex Kremer Date: Tue, 24 Mar 2026 15:42:12 +0000 Subject: [PATCH 06/53] refactor: Enable more clang-tidy readability checks (#6595) Co-authored-by: Sergey Kuznetsov --- .clang-tidy | 14 ++-- include/xrpl/beast/utility/instrumentation.h | 2 +- include/xrpl/core/JobQueue.h | 2 +- include/xrpl/protocol/Permissions.h | 8 +- include/xrpl/protocol/Serializer.h | 2 +- include/xrpl/shamap/SHAMap.h | 2 +- include/xrpl/tx/ApplyContext.h | 2 +- include/xrpl/tx/invariants/FreezeInvariant.h | 6 +- include/xrpl/tx/invariants/InvariantCheck.h | 2 +- include/xrpl/tx/invariants/LoanInvariant.h | 4 +- src/libxrpl/basics/Number.cpp | 4 +- src/libxrpl/basics/ResolverAsio.cpp | 12 +-- src/libxrpl/basics/StringUtilities.cpp | 2 +- src/libxrpl/basics/base64.cpp | 6 +- src/libxrpl/basics/make_SSLContext.cpp | 2 +- src/libxrpl/beast/insight/StatsDCollector.cpp | 2 +- src/libxrpl/beast/net/IPAddressV6.cpp | 2 +- src/libxrpl/beast/net/IPEndpoint.cpp | 10 +-- src/libxrpl/core/detail/JobQueue.cpp | 3 +- src/libxrpl/core/detail/LoadMonitor.cpp | 2 +- src/libxrpl/core/detail/Workers.cpp | 2 +- src/libxrpl/crypto/RFC1751.cpp | 16 ++-- src/libxrpl/json/Writer.cpp | 2 +- src/libxrpl/json/json_reader.cpp | 6 +- src/libxrpl/json/json_value.cpp | 65 ++++++++-------- src/libxrpl/json/json_valueiterator.cpp | 6 +- src/libxrpl/json/json_writer.cpp | 8 +- src/libxrpl/ledger/ApplyStateTable.cpp | 4 +- src/libxrpl/ledger/ApplyView.cpp | 2 +- src/libxrpl/ledger/PaymentSandbox.cpp | 4 +- .../ledger/helpers/CredentialHelpers.cpp | 10 +-- src/libxrpl/net/HTTPClient.cpp | 1 + src/libxrpl/nodestore/ManagerImp.cpp | 2 +- .../nodestore/backend/RocksDBFactory.cpp | 2 +- src/libxrpl/protocol/BuildInfo.cpp | 2 +- src/libxrpl/protocol/ErrorCodes.cpp | 4 +- src/libxrpl/protocol/Feature.cpp | 8 +- src/libxrpl/protocol/IOUAmount.cpp | 2 +- src/libxrpl/protocol/InnerObjectFormats.cpp | 2 +- src/libxrpl/protocol/NFTokenOfferID.cpp | 2 +- src/libxrpl/protocol/Permissions.cpp | 4 +- src/libxrpl/protocol/PublicKey.cpp | 2 +- src/libxrpl/protocol/STAccount.cpp | 2 +- src/libxrpl/protocol/STAmount.cpp | 23 ++---- src/libxrpl/protocol/STBlob.cpp | 2 +- src/libxrpl/protocol/STCurrency.cpp | 2 +- src/libxrpl/protocol/STIssue.cpp | 2 +- src/libxrpl/protocol/STLedgerEntry.cpp | 2 +- src/libxrpl/protocol/STObject.cpp | 22 +++--- src/libxrpl/protocol/STParsedJSON.cpp | 10 +-- src/libxrpl/protocol/STPathSet.cpp | 22 +++--- src/libxrpl/protocol/STTx.cpp | 8 +- src/libxrpl/protocol/STValidation.cpp | 2 +- src/libxrpl/protocol/STVar.cpp | 2 +- src/libxrpl/protocol/STVector256.cpp | 2 +- src/libxrpl/protocol/STXChainBridge.cpp | 2 +- src/libxrpl/protocol/Serializer.cpp | 6 +- src/libxrpl/protocol/TxMeta.cpp | 4 +- src/libxrpl/protocol/UintTypes.cpp | 2 +- src/libxrpl/protocol/tokens.cpp | 14 ++-- src/libxrpl/rdb/DatabaseCon.cpp | 4 +- src/libxrpl/rdb/SociDB.cpp | 6 +- src/libxrpl/resource/Consumer.cpp | 14 ++-- src/libxrpl/server/State.cpp | 4 +- src/libxrpl/shamap/SHAMap.cpp | 34 ++++----- src/libxrpl/shamap/SHAMapDelta.cpp | 2 +- src/libxrpl/shamap/SHAMapNodeID.cpp | 4 +- src/libxrpl/shamap/SHAMapSync.cpp | 22 +++--- src/libxrpl/tx/ApplyContext.cpp | 2 +- src/libxrpl/tx/Transactor.cpp | 16 ++-- src/libxrpl/tx/apply.cpp | 8 +- src/libxrpl/tx/invariants/AMMInvariant.cpp | 2 +- src/libxrpl/tx/invariants/FreezeInvariant.cpp | 7 +- src/libxrpl/tx/invariants/InvariantCheck.cpp | 8 +- src/libxrpl/tx/invariants/LoanInvariant.cpp | 4 +- src/libxrpl/tx/paths/RippleCalc.cpp | 4 +- .../tx/transactors/account/AccountDelete.cpp | 11 +-- .../tx/transactors/account/AccountSet.cpp | 63 ++++++++-------- .../tx/transactors/account/SetRegularKey.cpp | 2 +- .../tx/transactors/account/SignerListSet.cpp | 4 +- .../tx/transactors/bridge/XChainBridge.cpp | 12 +-- .../tx/transactors/check/CheckCash.cpp | 7 +- .../tx/transactors/check/CheckCreate.cpp | 4 +- .../credentials/CredentialAccept.cpp | 2 +- .../tx/transactors/dex/AMMClawback.cpp | 7 +- src/libxrpl/tx/transactors/dex/AMMDeposit.cpp | 16 ++-- .../tx/transactors/dex/AMMWithdraw.cpp | 22 +++--- .../tx/transactors/dex/OfferCancel.cpp | 2 +- .../tx/transactors/dex/OfferCreate.cpp | 44 ++++++----- .../tx/transactors/escrow/EscrowCreate.cpp | 5 +- .../tx/transactors/lending/LoanManage.cpp | 2 +- .../tx/transactors/nft/NFTokenBurn.cpp | 2 +- .../tx/transactors/nft/NFTokenCreateOffer.cpp | 2 +- .../tx/transactors/nft/NFTokenModify.cpp | 2 +- .../tx/transactors/nft/NFTokenUtils.cpp | 23 +++--- .../tx/transactors/payment/DepositPreauth.cpp | 7 +- .../tx/transactors/payment/Payment.cpp | 20 ++--- .../payment_channel/PaymentChannelClaim.cpp | 6 +- .../payment_channel/PaymentChannelCreate.cpp | 4 +- src/libxrpl/tx/transactors/system/Batch.cpp | 4 +- src/libxrpl/tx/transactors/system/Change.cpp | 2 +- src/libxrpl/tx/transactors/token/Clawback.cpp | 5 +- .../tx/transactors/token/MPTokenAuthorize.cpp | 4 +- .../token/MPTokenIssuanceCreate.cpp | 4 +- .../transactors/token/MPTokenIssuanceSet.cpp | 24 +++--- src/libxrpl/tx/transactors/token/TrustSet.cpp | 74 +++++++++---------- .../tx/transactors/vault/VaultCreate.cpp | 6 +- src/libxrpl/tx/transactors/vault/VaultSet.cpp | 5 +- src/test/app/AMMCalc_test.cpp | 14 ++-- src/test/app/AMM_test.cpp | 20 ++--- src/test/app/AccountTxPaging_test.cpp | 4 +- src/test/app/AmendmentTable_test.cpp | 4 +- src/test/app/Batch_test.cpp | 6 +- src/test/app/Credentials_test.cpp | 1 + src/test/app/DepositAuth_test.cpp | 6 +- src/test/app/EscrowToken_test.cpp | 4 +- src/test/app/FeeVote_test.cpp | 2 +- src/test/app/FixNFTokenPageLinks_test.cpp | 2 +- src/test/app/Flow_test.cpp | 2 +- src/test/app/Freeze_test.cpp | 4 +- src/test/app/HashRouter_test.cpp | 2 +- src/test/app/Invariants_test.cpp | 2 +- src/test/app/LedgerMaster_test.cpp | 2 +- src/test/app/LedgerReplay_test.cpp | 29 +++----- src/test/app/Loan_test.cpp | 22 +++--- src/test/app/Manifest_test.cpp | 4 +- src/test/app/NFTokenAuth_test.cpp | 2 +- src/test/app/NFTokenBurn_test.cpp | 4 +- src/test/app/NFTokenDir_test.cpp | 2 +- src/test/app/NFToken_test.cpp | 11 +-- src/test/app/NetworkID_test.cpp | 2 +- src/test/app/Offer_test.cpp | 24 +++--- src/test/app/OversizeMeta_test.cpp | 6 +- src/test/app/Path_test.cpp | 2 +- src/test/app/PayChan_test.cpp | 4 +- src/test/app/PayStrand_test.cpp | 4 +- src/test/app/PermissionedDEX_test.cpp | 12 +-- src/test/app/PseudoTx_test.cpp | 4 +- src/test/app/RCLValidations_test.cpp | 2 +- src/test/app/ReducedOffer_test.cpp | 2 +- src/test/app/SHAMapStore_test.cpp | 8 +- src/test/app/TrustSet_test.cpp | 4 +- src/test/app/TxQ_test.cpp | 24 +++--- src/test/app/ValidatorList_test.cpp | 18 ++--- src/test/app/ValidatorSite_test.cpp | 2 +- src/test/app/Vault_test.cpp | 8 +- src/test/app/XChain_test.cpp | 2 +- src/test/basics/Buffer_test.cpp | 4 +- src/test/basics/Number_test.cpp | 12 +-- src/test/basics/PerfLog_test.cpp | 16 ++-- src/test/basics/base58_test.cpp | 2 +- .../beast/aged_associative_container_test.cpp | 2 +- src/test/consensus/Consensus_test.cpp | 24 +++--- src/test/consensus/NegativeUNL_test.cpp | 4 +- src/test/core/ClosureCounter_test.cpp | 2 +- src/test/core/Config_test.cpp | 8 +- src/test/core/JobQueue_test.cpp | 2 +- src/test/csf/Sim.h | 4 +- src/test/csf/impl/Sim.cpp | 2 +- src/test/csf/impl/ledgers.cpp | 2 +- src/test/csf/ledgers.h | 4 +- src/test/jtx/AMMTest.h | 8 +- src/test/jtx/Env.h | 1 + src/test/jtx/Env_test.cpp | 2 +- src/test/jtx/impl/AMM.cpp | 4 +- src/test/jtx/impl/AMMTest.cpp | 4 +- src/test/jtx/impl/Env.cpp | 5 +- src/test/jtx/impl/Oracle.cpp | 2 +- src/test/jtx/impl/mpt.cpp | 2 +- src/test/jtx/impl/multisign.cpp | 2 +- src/test/jtx/impl/offer.cpp | 2 +- src/test/jtx/impl/sig.cpp | 4 +- src/test/jtx/vault.h | 10 +-- src/test/ledger/Directory_test.cpp | 4 +- src/test/nodestore/NuDBFactory_test.cpp | 2 +- src/test/nodestore/Timing_test.cpp | 6 +- src/test/nodestore/import_test.cpp | 8 +- src/test/overlay/TMGetObjectByHash_test.cpp | 2 +- src/test/overlay/cluster_test.cpp | 2 +- src/test/overlay/compression_test.cpp | 14 ++-- src/test/overlay/reduce_relay_test.cpp | 16 ++-- src/test/protocol/PublicKey_test.cpp | 4 +- src/test/protocol/STAmount_test.cpp | 2 +- src/test/protocol/STParsedJSON_test.cpp | 2 +- src/test/protocol/SeqProxy_test.cpp | 2 +- src/test/resource/Logic_test.cpp | 4 +- src/test/rpc/AccountObjects_test.cpp | 2 +- src/test/rpc/Book_test.cpp | 4 +- src/test/rpc/DeliveredAmount_test.cpp | 3 +- src/test/rpc/LedgerEntry_test.cpp | 4 +- src/test/rpc/LedgerRPC_test.cpp | 2 +- src/test/rpc/Roles_test.cpp | 2 +- src/test/rpc/ServerInfo_test.cpp | 2 +- src/test/rpc/Simulate_test.cpp | 4 +- src/test/rpc/Transaction_test.cpp | 6 +- src/test/server/ServerStatus_test.cpp | 8 +- src/test/server/Server_test.cpp | 14 ++-- src/test/shamap/FetchPack_test.cpp | 6 +- src/tests/libxrpl/basics/RangeSet.cpp | 2 +- src/tests/libxrpl/json/Value.cpp | 4 +- src/xrpld/app/consensus/RCLConsensus.cpp | 4 +- src/xrpld/app/consensus/RCLCxPeerPos.cpp | 4 +- src/xrpld/app/ledger/detail/BuildLedger.cpp | 4 +- src/xrpld/app/ledger/detail/LedgerMaster.cpp | 4 +- src/xrpld/app/ledger/detail/LedgerToJson.cpp | 19 ++--- .../app/ledger/detail/TransactionMaster.cpp | 2 +- src/xrpld/app/main/Application.cpp | 2 +- src/xrpld/app/main/BasicApp.cpp | 2 +- src/xrpld/app/main/Main.cpp | 4 +- src/xrpld/app/misc/NegativeUNLVote.h | 2 +- src/xrpld/app/misc/NetworkOPs.cpp | 26 +++---- src/xrpld/app/misc/SHAMapStoreImp.cpp | 16 ++-- src/xrpld/app/misc/TxQ.h | 4 +- src/xrpld/app/misc/detail/AmendmentTable.cpp | 10 +-- src/xrpld/app/misc/detail/Transaction.cpp | 2 +- src/xrpld/app/misc/detail/TxQ.cpp | 17 +++-- src/xrpld/app/misc/detail/ValidatorList.cpp | 14 ++-- src/xrpld/app/paths/PathRequest.cpp | 4 +- src/xrpld/app/paths/Pathfinder.cpp | 18 ++--- src/xrpld/app/paths/RippleLineCache.cpp | 2 +- src/xrpld/app/paths/detail/BookStep.cpp | 17 +++-- src/xrpld/app/paths/detail/DirectStep.cpp | 48 ++++++------ src/xrpld/app/paths/detail/PaySteps.cpp | 24 +++--- .../app/paths/detail/XRPEndpointStep.cpp | 2 +- src/xrpld/app/rdb/backend/detail/Node.cpp | 4 +- src/xrpld/core/detail/Config.cpp | 20 ++--- src/xrpld/overlay/Message.h | 6 +- src/xrpld/overlay/detail/Message.cpp | 3 +- src/xrpld/overlay/detail/OverlayImpl.cpp | 10 +-- src/xrpld/overlay/detail/OverlayImpl.h | 2 +- src/xrpld/overlay/detail/PeerImp.cpp | 4 +- .../peerfinder/detail/PeerfinderConfig.cpp | 2 +- src/xrpld/perflog/detail/PerfLogImp.cpp | 12 +-- src/xrpld/rpc/detail/DeliveredAmount.cpp | 9 +-- src/xrpld/rpc/detail/Handler.cpp | 2 +- src/xrpld/rpc/detail/RPCCall.cpp | 58 +++++++++++---- src/xrpld/rpc/detail/RPCHandler.cpp | 4 +- src/xrpld/rpc/detail/RPCHelpers.cpp | 2 +- src/xrpld/rpc/detail/RPCLedgerHelpers.cpp | 2 +- src/xrpld/rpc/detail/ServerHandler.cpp | 10 +-- src/xrpld/rpc/detail/TransactionSign.cpp | 6 +- src/xrpld/rpc/handlers/AccountInfo.cpp | 4 +- src/xrpld/rpc/handlers/CanDelete.cpp | 2 +- src/xrpld/rpc/handlers/DepositAuthorized.cpp | 4 +- src/xrpld/rpc/handlers/GetAggregatePrice.cpp | 2 +- src/xrpld/rpc/handlers/LedgerHandler.cpp | 2 +- src/xrpld/rpc/handlers/NoRippleCheck.cpp | 6 +- src/xrpld/rpc/handlers/ServerDefinitions.cpp | 2 +- 248 files changed, 948 insertions(+), 935 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index d8a7cb1b6f..261da1e367 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -104,10 +104,13 @@ Checks: "-*, readability-const-return-type, readability-container-contains, readability-container-size-empty, + readability-convert-member-functions-to-static, readability-duplicate-include, readability-else-after-return, readability-enum-initial-value, + readability-implicit-bool-conversion, readability-make-member-function-const, + readability-math-missing-parentheses, readability-misleading-indentation, readability-non-const-parameter, readability-redundant-casting, @@ -116,7 +119,9 @@ Checks: "-*, readability-redundant-member-init, readability-redundant-string-init, readability-reference-to-constructed-temporary, + readability-simplify-boolean-expr, readability-static-definition-in-anonymous-namespace, + readability-suspicious-call-argument, readability-use-std-min-max " # --- @@ -127,14 +132,9 @@ Checks: "-*, # misc-include-cleaner, # misc-redundant-expression, # -# readability-convert-member-functions-to-static, -# readability-implicit-bool-conversion, -# readability-inconsistent-declaration-parameter-name, +# readability-inconsistent-declaration-parameter-name, # in this codebase this check will break a lot of arg names +# readability-static-accessed-through-instance, # this check is probably unnecessary. it makes the code less readable # readability-identifier-naming, -# readability-math-missing-parentheses, -# readability-simplify-boolean-expr, -# readability-suspicious-call-argument, -# readability-static-accessed-through-instance, # # modernize-concat-nested-namespaces, # modernize-pass-by-value, diff --git a/include/xrpl/beast/utility/instrumentation.h b/include/xrpl/beast/utility/instrumentation.h index 106856514b..39b80bc438 100644 --- a/include/xrpl/beast/utility/instrumentation.h +++ b/include/xrpl/beast/utility/instrumentation.h @@ -15,7 +15,7 @@ #define ALWAYS_OR_UNREACHABLE(cond, message) assert((message) && (cond)) #define SOMETIMES(cond, message, ...) #define REACHABLE(message, ...) -#define UNREACHABLE(message, ...) assert((message) && false) +#define UNREACHABLE(message, ...) assert((message) && false) // NOLINT(misc-static-assert) #endif #define XRPL_ASSERT ALWAYS_OR_UNREACHABLE diff --git a/include/xrpl/core/JobQueue.h b/include/xrpl/core/JobQueue.h index f40a892173..583e8bc26a 100644 --- a/include/xrpl/core/JobQueue.h +++ b/include/xrpl/core/JobQueue.h @@ -316,7 +316,7 @@ private: // Returns the limit of running jobs for the given job type. // For jobs with no limit, we return the largest int. Hopefully that // will be enough. - int + static int getJobLimit(JobType type); }; diff --git a/include/xrpl/protocol/Permissions.h b/include/xrpl/protocol/Permissions.h index 65861addc7..0ec4f04f1a 100644 --- a/include/xrpl/protocol/Permissions.h +++ b/include/xrpl/protocol/Permissions.h @@ -72,12 +72,12 @@ public: isDelegable(std::uint32_t const& permissionValue, Rules const& rules) const; // for tx level permission, permission value is equal to tx type plus one - uint32_t - txToPermissionType(TxType const& type) const; + static uint32_t + txToPermissionType(TxType const& type); // tx type value is permission value minus one - TxType - permissionToTxType(uint32_t const& value) const; + static TxType + permissionToTxType(uint32_t const& value); }; } // namespace xrpl diff --git a/include/xrpl/protocol/Serializer.h b/include/xrpl/protocol/Serializer.h index 98cefb4d08..75f5dbdf96 100644 --- a/include/xrpl/protocol/Serializer.h +++ b/include/xrpl/protocol/Serializer.h @@ -336,7 +336,7 @@ public: static_assert(N > 0, ""); } - std::size_t + [[nodiscard]] bool empty() const noexcept { return remain_ == 0; diff --git a/include/xrpl/shamap/SHAMap.h b/include/xrpl/shamap/SHAMap.h index 2c0910a830..213e7ce0ce 100644 --- a/include/xrpl/shamap/SHAMap.h +++ b/include/xrpl/shamap/SHAMap.h @@ -520,7 +520,7 @@ private: // getMissingNodes helper functions void gmn_ProcessNodes(MissingNodes&, MissingNodes::StackEntry& node); - void + static void gmn_ProcessDeferredReads(MissingNodes&); // fetch from DB helper function diff --git a/include/xrpl/tx/ApplyContext.h b/include/xrpl/tx/ApplyContext.h index 9e382556c2..efef568f29 100644 --- a/include/xrpl/tx/ApplyContext.h +++ b/include/xrpl/tx/ApplyContext.h @@ -111,7 +111,7 @@ public: checkInvariants(TER const result, XRPAmount const fee); private: - TER + static TER failInvariantCheck(TER const result); template diff --git a/include/xrpl/tx/invariants/FreezeInvariant.h b/include/xrpl/tx/invariants/FreezeInvariant.h index ac9d83166e..645f444462 100644 --- a/include/xrpl/tx/invariants/FreezeInvariant.h +++ b/include/xrpl/tx/invariants/FreezeInvariant.h @@ -48,7 +48,7 @@ private: bool isValidEntry(std::shared_ptr const& before, std::shared_ptr const& after); - STAmount + static STAmount calculateBalanceChange( std::shared_ptr const& before, std::shared_ptr const& after, @@ -63,7 +63,7 @@ private: std::shared_ptr findIssuer(AccountID const& issuerID, ReadView const& view); - bool + static bool validateIssuerChanges( std::shared_ptr const& issuer, IssuerChanges const& changes, @@ -71,7 +71,7 @@ private: beast::Journal const& j, bool enforce); - bool + static bool validateFrozenState( BalanceChange const& change, bool high, diff --git a/include/xrpl/tx/invariants/InvariantCheck.h b/include/xrpl/tx/invariants/InvariantCheck.h index e0ad65f14c..a053d127fb 100644 --- a/include/xrpl/tx/invariants/InvariantCheck.h +++ b/include/xrpl/tx/invariants/InvariantCheck.h @@ -111,7 +111,7 @@ public: void visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); - bool + static bool finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); }; diff --git a/include/xrpl/tx/invariants/LoanInvariant.h b/include/xrpl/tx/invariants/LoanInvariant.h index be771cd582..02e9db1698 100644 --- a/include/xrpl/tx/invariants/LoanInvariant.h +++ b/include/xrpl/tx/invariants/LoanInvariant.h @@ -41,8 +41,8 @@ class ValidLoanBroker // for LoanBroker pseudo-accounts. std::vector mpts_; - bool - goodZeroDirectory(ReadView const& view, SLE::const_ref dir, beast::Journal const& j) const; + static bool + goodZeroDirectory(ReadView const& view, SLE::const_ref dir, beast::Journal const& j); public: void diff --git a/src/libxrpl/basics/Number.cpp b/src/libxrpl/basics/Number.cpp index b520261ffe..f0655cd8a9 100644 --- a/src/libxrpl/basics/Number.cpp +++ b/src/libxrpl/basics/Number.cpp @@ -981,7 +981,7 @@ root(Number f, unsigned d) auto ex = [e = e, di = di]() // Euclidean remainder of e/d { int k = (e >= 0 ? e : e - (di - 1)) / di; - int k2 = e - k * di; + int k2 = e - (k * di); if (k2 == 0) return 0; return di - k2; @@ -998,7 +998,7 @@ root(Number f, unsigned d) } // Quadratic least squares curve fit of f^(1/d) in the range [0, 1] - auto const D = ((6 * di + 11) * di + 6) * di + 1; + auto const D = (((6 * di + 11) * di + 6) * di) + 1; auto const a0 = 3 * di * ((2 * di - 3) * di + 1); auto const a1 = 24 * di * (2 * di - 1); auto const a2 = -30 * (di - 1) * di; diff --git a/src/libxrpl/basics/ResolverAsio.cpp b/src/libxrpl/basics/ResolverAsio.cpp index b746092645..aa1cb1470d 100644 --- a/src/libxrpl/basics/ResolverAsio.cpp +++ b/src/libxrpl/basics/ResolverAsio.cpp @@ -169,7 +169,7 @@ public: XRPL_ASSERT(m_stopped == true, "xrpl::ResolverAsioImpl::start : stopped"); XRPL_ASSERT(m_stop_called == false, "xrpl::ResolverAsioImpl::start : not stopping"); - if (m_stopped.exchange(false) == true) + if (m_stopped.exchange(false)) { { std::lock_guard lk{m_mut}; @@ -182,7 +182,7 @@ public: void stop_async() override { - if (m_stop_called.exchange(true) == false) + if (!m_stop_called.exchange(true)) { boost::asio::dispatch( m_io_context, @@ -229,7 +229,7 @@ public: { XRPL_ASSERT(m_stop_called == true, "xrpl::ResolverAsioImpl::do_stop : stopping"); - if (m_stopped.exchange(true) == false) + if (!m_stopped.exchange(true)) { m_work.clear(); m_resolver.cancel(); @@ -271,7 +271,7 @@ public: m_strand, std::bind(&ResolverAsioImpl::do_work, this, CompletionCounter(this)))); } - HostAndPort + static HostAndPort parseName(std::string const& str) { // first attempt to parse as an endpoint (IP addr + port). @@ -319,7 +319,7 @@ public: void do_work(CompletionCounter) { - if (m_stop_called == true) + if (m_stop_called) return; // We don't have any work to do at this time @@ -367,7 +367,7 @@ public: { XRPL_ASSERT(!names.empty(), "xrpl::ResolverAsioImpl::do_resolve : names non-empty"); - if (m_stop_called == false) + if (!m_stop_called) { m_work.emplace_back(names, handler); diff --git a/src/libxrpl/basics/StringUtilities.cpp b/src/libxrpl/basics/StringUtilities.cpp index 0dd466c9b4..c47618db82 100644 --- a/src/libxrpl/basics/StringUtilities.cpp +++ b/src/libxrpl/basics/StringUtilities.cpp @@ -24,7 +24,7 @@ sqlBlobLiteral(Blob const& blob) { std::string j; - j.reserve(blob.size() * 2 + 3); + j.reserve((blob.size() * 2) + 3); j.push_back('X'); j.push_back('\''); boost::algorithm::hex(blob.begin(), blob.end(), std::back_inserter(j)); diff --git a/src/libxrpl/basics/base64.cpp b/src/libxrpl/basics/base64.cpp index 31888ec99c..a510fbf6c9 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--;) + for (auto n = len / 3; n != 0u; --n) { *out++ = tab[(in[0] & 0xfc) >> 2]; *out++ = tab[((in[0] & 0x03) << 4) + ((in[1] & 0xf0) >> 4)]; @@ -162,7 +162,7 @@ decode(void* dest, char const* src, std::size_t len) auto const inverse = base64::get_inverse(); - while (len-- && *in != '=') + while (((len--) != 0u) && *in != '=') { auto const v = inverse[*in]; if (v == -1) @@ -181,7 +181,7 @@ decode(void* dest, char const* src, std::size_t len) } } - if (i) + if (i != 0) { c3[0] = (c4[0] << 2) + ((c4[1] & 0x30) >> 4); c3[1] = ((c4[1] & 0xf) << 4) + ((c4[2] & 0x3c) >> 2); diff --git a/src/libxrpl/basics/make_SSLContext.cpp b/src/libxrpl/basics/make_SSLContext.cpp index 74aab709d8..de16e8c6cf 100644 --- a/src/libxrpl/basics/make_SSLContext.cpp +++ b/src/libxrpl/basics/make_SSLContext.cpp @@ -253,7 +253,7 @@ initAuthenticated( // VFALCO Replace fopen() with RAII FILE* f = fopen(chain_file.c_str(), "r"); - if (!f) + if (f == nullptr) { LogicError( "Problem opening SSL chain file" + diff --git a/src/libxrpl/beast/insight/StatsDCollector.cpp b/src/libxrpl/beast/insight/StatsDCollector.cpp index cc3bbf2861..83fc65e92c 100644 --- a/src/libxrpl/beast/insight/StatsDCollector.cpp +++ b/src/libxrpl/beast/insight/StatsDCollector.cpp @@ -352,7 +352,7 @@ public: } } - void + static void log(std::vector const& buffers) { (void)buffers; diff --git a/src/libxrpl/beast/net/IPAddressV6.cpp b/src/libxrpl/beast/net/IPAddressV6.cpp index a261002ed3..30e2eefb96 100644 --- a/src/libxrpl/beast/net/IPAddressV6.cpp +++ b/src/libxrpl/beast/net/IPAddressV6.cpp @@ -10,7 +10,7 @@ bool is_private(AddressV6 const& addr) { return ( - (addr.to_bytes()[0] & 0xfd) || // TODO fc00::/8 too ? + ((addr.to_bytes()[0] & 0xfd) != 0) || // TODO fc00::/8 too ? (addr.is_v4_mapped() && is_private(boost::asio::ip::make_address_v4(boost::asio::ip::v4_mapped, addr)))); } diff --git a/src/libxrpl/beast/net/IPEndpoint.cpp b/src/libxrpl/beast/net/IPEndpoint.cpp index f8352f4318..70e7bff2c5 100644 --- a/src/libxrpl/beast/net/IPEndpoint.cpp +++ b/src/libxrpl/beast/net/IPEndpoint.cpp @@ -57,7 +57,7 @@ Endpoint::to_string() const if (port() != 0 && address().is_v6()) s += '['; s += address().to_string(); - if (port()) + if (port() != 0u) { if (address().is_v6()) s += ']'; @@ -111,7 +111,7 @@ operator>>(std::istream& is, Endpoint& endpoint) // so we continue to honor that here by assuming we are at the end // of the address portion if we hit a space (or the separator // we were expecting to see) - if (isspace(static_cast(i)) || (readTo && i == readTo)) + if ((isspace(static_cast(i)) != 0) || ((readTo != 0) && i == readTo)) break; if ((i == '.') || (i >= '0' && i <= ':') || (i >= 'a' && i <= 'f') || @@ -121,13 +121,13 @@ operator>>(std::istream& is, Endpoint& endpoint) // don't exceed a reasonable length... if (addrStr.size() == INET6_ADDRSTRLEN || - (readTo && readTo == ':' && addrStr.size() > 15)) + ((readTo != 0) && readTo == ':' && addrStr.size() > 15)) { is.setstate(std::ios_base::failbit); return is; } - if (!readTo && (i == '.' || i == ':')) + if ((readTo == 0) && (i == '.' || i == ':')) { // if we see a dot first, must be IPv4 // otherwise must be non-bracketed IPv6 @@ -145,7 +145,7 @@ operator>>(std::istream& is, Endpoint& endpoint) if (readTo == ']' && is.rdbuf()->in_avail() > 0) { is.get(i); - if (!(isspace(static_cast(i)) || i == ':')) + if ((isspace(static_cast(i)) == 0) && i != ':') { is.unget(); is.setstate(std::ios_base::failbit); diff --git a/src/libxrpl/core/detail/JobQueue.cpp b/src/libxrpl/core/detail/JobQueue.cpp index 9adbf6312b..2fe5a5b0fd 100644 --- a/src/libxrpl/core/detail/JobQueue.cpp +++ b/src/libxrpl/core/detail/JobQueue.cpp @@ -84,8 +84,7 @@ JobQueue::addRefCountedJob(JobType type, std::string const& name, JobFunction co JobType const type(job.getType()); XRPL_ASSERT(type != jtINVALID, "xrpl::JobQueue::addRefCountedJob : has valid job type"); - XRPL_ASSERT( - m_jobSet.find(job) != m_jobSet.end(), "xrpl::JobQueue::addRefCountedJob : job found"); + XRPL_ASSERT(m_jobSet.contains(job), "xrpl::JobQueue::addRefCountedJob : job found"); perfLog_.jobQueue(type); JobTypeData& data(getJobTypeData(type)); diff --git a/src/libxrpl/core/detail/LoadMonitor.cpp b/src/libxrpl/core/detail/LoadMonitor.cpp index 89a364ca30..9891bdb8b8 100644 --- a/src/libxrpl/core/detail/LoadMonitor.cpp +++ b/src/libxrpl/core/detail/LoadMonitor.cpp @@ -141,7 +141,7 @@ LoadMonitor::isOver() update(); if (mLatencyEvents == 0) - return 0; + return false; return isOverTarget( mLatencyMSAvg / (mLatencyEvents * 4), mLatencyMSPeak / (mLatencyEvents * 4)); diff --git a/src/libxrpl/core/detail/Workers.cpp b/src/libxrpl/core/detail/Workers.cpp index c037169a29..21bf75b958 100644 --- a/src/libxrpl/core/detail/Workers.cpp +++ b/src/libxrpl/core/detail/Workers.cpp @@ -47,7 +47,7 @@ Workers::setNumberOfThreads(int numberOfThreads) if (m_numberOfThreads == numberOfThreads) return; - if (perfLog_) + if (perfLog_ != nullptr) perfLog_->resizeJobs(numberOfThreads); if (numberOfThreads > m_numberOfThreads) diff --git a/src/libxrpl/crypto/RFC1751.cpp b/src/libxrpl/crypto/RFC1751.cpp index f7c1e675cb..becd0aab8d 100644 --- a/src/libxrpl/crypto/RFC1751.cpp +++ b/src/libxrpl/crypto/RFC1751.cpp @@ -210,8 +210,8 @@ RFC1751::extract(char const* s, int start, int length) int const shiftR = 24 - (length + (start % 8)); cl = s[start / 8]; // get components - cc = (shiftR < 16) ? s[start / 8 + 1] : 0; - cr = (shiftR < 8) ? s[start / 8 + 2] : 0; + cc = (shiftR < 16) ? s[(start / 8) + 1] : 0; + cr = (shiftR < 8) ? s[(start / 8) + 2] : 0; x = ((long)(cl << 8 | cc) << 8 | cr); // Put bits together x = x >> shiftR; // Right justify number @@ -265,13 +265,13 @@ RFC1751::insert(char* s, int x, int start, int length) if (shift + length > 16) { s[start / 8] |= cl; - s[start / 8 + 1] |= cc; - s[start / 8 + 2] |= cr; + s[(start / 8) + 1] |= cc; + s[(start / 8) + 2] |= cr; } else if (shift + length > 8) { s[start / 8] |= cc; - s[start / 8 + 1] |= cr; + s[(start / 8) + 1] |= cr; } else { @@ -284,7 +284,7 @@ RFC1751::standard(std::string& strWord) { for (auto& letter : strWord) { - if (islower(static_cast(letter))) + if (islower(static_cast(letter)) != 0) { letter = toupper(static_cast(letter)); } @@ -312,10 +312,10 @@ RFC1751::wsrch(std::string const& strWord, int iMin, int iMax) while (iResult < 0 && iMin != iMax) { // Have a range to search. - int iMid = iMin + (iMax - iMin) / 2; + int iMid = iMin + ((iMax - iMin) / 2); int iDir = strWord.compare(s_dictionary[iMid]); - if (!iDir) + if (iDir == 0) { iResult = iMid; // Found it. } diff --git a/src/libxrpl/json/Writer.cpp b/src/libxrpl/json/Writer.cpp index 6ff5a130dd..796ec35dfd 100644 --- a/src/libxrpl/json/Writer.cpp +++ b/src/libxrpl/json/Writer.cpp @@ -152,7 +152,7 @@ public: #ifndef NDEBUG // Make sure we haven't already seen this tag. auto& tags = stack_.top().tags; - check(tags.find(tag) == tags.end(), "Already seen tag " + tag); + check(!tags.contains(tag), "Already seen tag " + tag); tags.insert(tag); #endif diff --git a/src/libxrpl/json/json_reader.cpp b/src/libxrpl/json/json_reader.cpp index 4c2a27400f..6475a5b68b 100644 --- a/src/libxrpl/json/json_reader.cpp +++ b/src/libxrpl/json/json_reader.cpp @@ -296,7 +296,7 @@ Reader::match(Location pattern, int patternLength) int index = patternLength; - while (index--) + while ((index--) != 0) { if (current_[index] != pattern[index]) return false; @@ -362,7 +362,7 @@ Reader::readNumber() while (current_ != end_) { - if (!std::isdigit(static_cast(*current_))) + if (std::isdigit(static_cast(*current_)) == 0) { auto ret = std::find(std::begin(extended_tokens), std::end(extended_tokens), *current_); @@ -913,7 +913,7 @@ Reader::getFormattedErrorMessages() const formattedMessage += "* " + getLocationLineAndColumn(error.token_.start_) + "\n"; formattedMessage += " " + error.message_ + "\n"; - if (error.extra_) + if (error.extra_ != nullptr) formattedMessage += "See " + getLocationLineAndColumn(error.extra_) + " for detail.\n"; } diff --git a/src/libxrpl/json/json_value.cpp b/src/libxrpl/json/json_value.cpp index 94b077d224..988a25a3ff 100644 --- a/src/libxrpl/json/json_value.cpp +++ b/src/libxrpl/json/json_value.cpp @@ -40,10 +40,10 @@ public: // return 0; if (length == unknown) - length = value ? (unsigned int)strlen(value) : 0; + length = (value != nullptr) ? (unsigned int)strlen(value) : 0; char* newString = static_cast(malloc(length + 1)); - if (value) + if (value != nullptr) memcpy(newString, value, length); newString[length] = 0; return newString; @@ -52,7 +52,7 @@ public: void releaseStringValue(char* value) override { - if (value) + if (value != nullptr) free(value); } }; @@ -108,14 +108,14 @@ Value::CZString::CZString(CZString const& other) Value::CZString::~CZString() { - if (cstr_ && index_ == duplicate) + if ((cstr_ != nullptr) && index_ == duplicate) valueAllocator()->releaseMemberName(const_cast(cstr_)); } bool Value::CZString::operator<(CZString const& other) const { - if (cstr_ && other.cstr_) + if ((cstr_ != nullptr) && (other.cstr_ != nullptr)) return strcmp(cstr_, other.cstr_) < 0; return index_ < other.index_; @@ -124,7 +124,7 @@ Value::CZString::operator<(CZString const& other) const bool Value::CZString::operator==(CZString const& other) const { - if (cstr_ && other.cstr_) + if ((cstr_ != nullptr) && (other.cstr_ != nullptr)) return strcmp(cstr_, other.cstr_) == 0; return index_ == other.index_; @@ -251,7 +251,7 @@ Value::Value(Value const& other) : type_(other.type_) break; case stringValue: - if (other.value_.string_) + if (other.value_.string_ != nullptr) { value_.string_ = valueAllocator()->duplicateStringValue(other.value_.string_); allocated_ = true; @@ -294,7 +294,7 @@ Value::~Value() case arrayValue: case objectValue: - if (value_.map_) + if (value_.map_ != nullptr) delete value_.map_; break; @@ -392,11 +392,11 @@ operator<(Value const& x, Value const& y) return x.value_.real_ < y.value_.real_; case booleanValue: - return x.value_.bool_ < y.value_.bool_; + return static_cast(x.value_.bool_) < static_cast(y.value_.bool_); case stringValue: - return (x.value_.string_ == 0 && y.value_.string_) || - (y.value_.string_ && x.value_.string_ && + return (x.value_.string_ == 0 && (y.value_.string_ != nullptr)) || + ((y.value_.string_ != nullptr) && (x.value_.string_ != nullptr) && strcmp(x.value_.string_, y.value_.string_) < 0); case arrayValue: @@ -413,7 +413,7 @@ operator<(Value const& x, Value const& y) // LCOV_EXCL_STOP } - return 0; // unreachable + return false; // unreachable } bool @@ -422,9 +422,9 @@ operator==(Value const& x, Value const& y) if (x.type_ != y.type_) { if (x.type_ == intValue && y.type_ == uintValue) - return !integerCmp(x.value_.int_, y.value_.uint_); + return integerCmp(x.value_.int_, y.value_.uint_) == 0; if (x.type_ == uintValue && y.type_ == intValue) - return !integerCmp(y.value_.int_, x.value_.uint_); + return integerCmp(y.value_.int_, x.value_.uint_) == 0; return false; } @@ -447,8 +447,8 @@ operator==(Value const& x, Value const& y) case stringValue: return x.value_.string_ == y.value_.string_ || - (y.value_.string_ && x.value_.string_ && - !strcmp(x.value_.string_, y.value_.string_)); + ((y.value_.string_ != nullptr) && (x.value_.string_ != nullptr) && + (strcmp(x.value_.string_, y.value_.string_) == 0)); case arrayValue: case objectValue: @@ -461,7 +461,7 @@ operator==(Value const& x, Value const& y) // LCOV_EXCL_STOP } - return 0; // unreachable + return false; // unreachable } char const* @@ -480,7 +480,7 @@ Value::asString() const return ""; case stringValue: - return value_.string_ ? value_.string_ : ""; + return (value_.string_ != nullptr) ? value_.string_ : ""; case booleanValue: return value_.bool_ ? "true" : "false"; @@ -525,7 +525,7 @@ Value::asInt() const case realValue: JSON_ASSERT_MESSAGE( - value_.real_ >= minInt && value_.real_ <= maxInt, + (value_.real_ >= minInt && value_.real_ <= maxInt), "Real out of signed integer range"); return Int(value_.real_); @@ -533,7 +533,7 @@ Value::asInt() const return value_.bool_ ? 1 : 0; case stringValue: { - char const* const str{value_.string_ ? value_.string_ : ""}; + char const* const str{(value_.string_ != nullptr) ? value_.string_ : ""}; return beast::lexicalCastThrow(str); } @@ -584,7 +584,7 @@ Value::asAbsUInt() const return value_.bool_ ? 1 : 0; case stringValue: { - char const* const str{value_.string_ ? value_.string_ : ""}; + char const* const str{(value_.string_ != nullptr) ? value_.string_ : ""}; auto const temp = beast::lexicalCastThrow(str); if (temp < 0) { @@ -626,14 +626,15 @@ Value::asUInt() const case realValue: JSON_ASSERT_MESSAGE( - value_.real_ >= 0 && value_.real_ <= maxUInt, "Real out of unsigned integer range"); + (value_.real_ >= 0 && value_.real_ <= maxUInt), + "Real out of unsigned integer range"); return UInt(value_.real_); case booleanValue: return value_.bool_ ? 1 : 0; case stringValue: { - char const* const str{value_.string_ ? value_.string_ : ""}; + char const* const str{(value_.string_ != nullptr) ? value_.string_ : ""}; return beast::lexicalCastThrow(str); } @@ -703,7 +704,7 @@ Value::asBool() const return value_.bool_; case stringValue: - return value_.string_ && value_.string_[0] != 0; + return (value_.string_ != nullptr) && value_.string_[0] != 0; case arrayValue: case objectValue: @@ -745,13 +746,13 @@ Value::isConvertibleTo(ValueType other) const other == realValue || other == stringValue || other == booleanValue; case booleanValue: - return (other == nullValue && value_.bool_ == false) || other == intValue || + return (other == nullValue && !value_.bool_) || other == intValue || other == uintValue || other == realValue || other == stringValue || other == booleanValue; case stringValue: return other == stringValue || - (other == nullValue && (!value_.string_ || value_.string_[0] == 0)); + (other == nullValue && ((value_.string_ == nullptr) || value_.string_[0] == 0)); case arrayValue: return other == arrayValue || (other == nullValue && value_.map_->empty()); @@ -813,10 +814,10 @@ operator bool() const if (isString()) { auto s = asCString(); - return s && s[0]; + return (s != nullptr) && (s[0] != 0); } - return !(isArray() || isObject()) || size(); + return !(isArray() || isObject()) || (size() != 0u); } void @@ -1139,7 +1140,7 @@ Value::begin() const { case arrayValue: case objectValue: - if (value_.map_) + if (value_.map_ != nullptr) return const_iterator(value_.map_->begin()); break; @@ -1157,7 +1158,7 @@ Value::end() const { case arrayValue: case objectValue: - if (value_.map_) + if (value_.map_ != nullptr) return const_iterator(value_.map_->end()); break; @@ -1175,7 +1176,7 @@ Value::begin() { case arrayValue: case objectValue: - if (value_.map_) + if (value_.map_ != nullptr) return iterator(value_.map_->begin()); break; default: @@ -1192,7 +1193,7 @@ Value::end() { case arrayValue: case objectValue: - if (value_.map_) + if (value_.map_ != nullptr) return iterator(value_.map_->end()); break; default: diff --git a/src/libxrpl/json/json_valueiterator.cpp b/src/libxrpl/json/json_valueiterator.cpp index e49ad50f9a..b3cf7e6538 100644 --- a/src/libxrpl/json/json_valueiterator.cpp +++ b/src/libxrpl/json/json_valueiterator.cpp @@ -89,7 +89,7 @@ ValueIteratorBase::key() const { Value::CZString const czString = (*current_).first; - if (czString.c_str()) + if (czString.c_str() != nullptr) { if (czString.isStaticString()) return Value(StaticString(czString.c_str())); @@ -105,7 +105,7 @@ ValueIteratorBase::index() const { Value::CZString const czString = (*current_).first; - if (!czString.c_str()) + if (czString.c_str() == nullptr) return czString.index(); return Value::UInt(-1); @@ -115,7 +115,7 @@ char const* ValueIteratorBase::memberName() const { char const* name = (*current_).first.c_str(); - return name ? name : ""; + return (name != nullptr) ? name : ""; } // ////////////////////////////////////////////////////////////////// diff --git a/src/libxrpl/json/json_writer.cpp b/src/libxrpl/json/json_writer.cpp index 66507f0111..b51da5bb68 100644 --- a/src/libxrpl/json/json_writer.cpp +++ b/src/libxrpl/json/json_writer.cpp @@ -23,7 +23,7 @@ isControlCharacter(char ch) static bool containsControlCharacter(char const* str) { - while (*str) + while (*str != 0) { if (isControlCharacter(*(str++))) return true; @@ -106,7 +106,7 @@ valueToQuotedString(char const* value) // We have to walk value and escape any special characters. // Appending to std::string is not efficient, but this should be rare. // (Note: forward slashes are *not* rare, but I am not escaping them.) - unsigned maxsize = strlen(value) * 2 + 3; // all-escaped+quotes+NULL + unsigned maxsize = (strlen(value) * 2) + 3; // all-escaped+quotes+NULL std::string result; result.reserve(maxsize); // to avoid lots of mallocs result += "\""; @@ -416,7 +416,7 @@ StyledWriter::isMultilineArray(Value const& value) { childValues_.reserve(size); addChildValues_ = true; - int lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]' + int lineLength = 4 + ((size - 1) * 2); // '[ ' + ', '*n + ' ]' for (int index = 0; index < size; ++index) { @@ -651,7 +651,7 @@ StyledStreamWriter::isMultilineArray(Value const& value) { childValues_.reserve(size); addChildValues_ = true; - int lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]' + int lineLength = 4 + ((size - 1) * 2); // '[ ' + ', '*n + ' ]' for (int index = 0; index < size; ++index) { diff --git a/src/libxrpl/ledger/ApplyStateTable.cpp b/src/libxrpl/ledger/ApplyStateTable.cpp index a0074c0b53..a48c3910e1 100644 --- a/src/libxrpl/ledger/ApplyStateTable.cpp +++ b/src/libxrpl/ledger/ApplyStateTable.cpp @@ -275,9 +275,7 @@ ApplyStateTable::exists(ReadView const& base, Keylet const& k) const case Action::modify: break; } - if (!k.check(*sle)) - return false; - return true; + return k.check(*sle); } auto diff --git a/src/libxrpl/ledger/ApplyView.cpp b/src/libxrpl/ledger/ApplyView.cpp index 463b2ba538..fe2e046b26 100644 --- a/src/libxrpl/ledger/ApplyView.cpp +++ b/src/libxrpl/ledger/ApplyView.cpp @@ -36,7 +36,7 @@ findPreviousPage(ApplyView& view, Keylet const& directory, SLE::ref start) auto node = start; - if (page) + if (page != 0u) { node = view.peek(keylet::page(directory, page)); if (!node) diff --git a/src/libxrpl/ledger/PaymentSandbox.cpp b/src/libxrpl/ledger/PaymentSandbox.cpp index 1f84da1dcb..a56d730b5a 100644 --- a/src/libxrpl/ledger/PaymentSandbox.cpp +++ b/src/libxrpl/ledger/PaymentSandbox.cpp @@ -164,7 +164,7 @@ PaymentSandbox::balanceHook( auto delta = amount.zeroed(); auto lastBal = amount; auto minBal = amount; - for (auto curSB = this; curSB; curSB = curSB->ps_) + for (auto curSB = this; curSB != nullptr; curSB = curSB->ps_) { if (auto adj = curSB->tab_.adjustments(account, issuer, currency)) { @@ -198,7 +198,7 @@ std::uint32_t PaymentSandbox::ownerCountHook(AccountID const& account, std::uint32_t count) const { std::uint32_t result = count; - for (auto curSB = this; curSB; curSB = curSB->ps_) + for (auto curSB = this; curSB != nullptr; curSB = curSB->ps_) { if (auto adj = curSB->tab_.ownerCount(account)) result = std::max(result, *adj); diff --git a/src/libxrpl/ledger/helpers/CredentialHelpers.cpp b/src/libxrpl/ledger/helpers/CredentialHelpers.cpp index 234ca7ea17..32db285f1e 100644 --- a/src/libxrpl/ledger/helpers/CredentialHelpers.cpp +++ b/src/libxrpl/ledger/helpers/CredentialHelpers.cpp @@ -78,7 +78,7 @@ deleteSLE(ApplyView& view, std::shared_ptr const& sleCredential, beast::Jou auto const issuer = sleCredential->getAccountID(sfIssuer); auto const subject = sleCredential->getAccountID(sfSubject); - bool const accepted = sleCredential->getFlags() & lsfAccepted; + bool const accepted = (sleCredential->getFlags() & lsfAccepted) != 0u; auto err = delSLE(issuer, sfIssuerNode, !accepted || (subject == issuer)); if (!isTesSuccess(err)) @@ -147,7 +147,7 @@ valid(STTx const& tx, ReadView const& view, AccountID const& src, beast::Journal return tecBAD_CREDENTIALS; } - if (!(sleCred->getFlags() & lsfAccepted)) + if ((sleCred->getFlags() & lsfAccepted) == 0u) { JLOG(j.trace()) << "Credential isn't accepted. Cred: " << h; return tecBAD_CREDENTIALS; @@ -188,7 +188,7 @@ validDomain(ReadView const& view, uint256 domainID, AccountID const& subject) foundExpired = true; continue; } - if (sleCredential->getFlags() & lsfAccepted) + if ((sleCredential->getFlags() & lsfAccepted) != 0u) { return tesSUCCESS; } @@ -309,7 +309,7 @@ verifyValidDomain(ApplyView& view, AccountID const& account, uint256 domainID, b if (!sleCredential) continue; // expired, i.e. deleted in credentials::removeExpired - if (sleCredential->getFlags() & lsfAccepted) + if ((sleCredential->getFlags() & lsfAccepted) != 0u) return tesSUCCESS; } @@ -336,7 +336,7 @@ verifyDepositPreauth( if (credentialsPresent && credentials::removeExpired(view, tx.getFieldV256(sfCredentialIDs), j)) return tecEXPIRED; - if (sleDst && (sleDst->getFlags() & lsfDepositAuth)) + if (sleDst && ((sleDst->getFlags() & lsfDepositAuth) != 0u)) { if (src != dst) { diff --git a/src/libxrpl/net/HTTPClient.cpp b/src/libxrpl/net/HTTPClient.cpp index 8ddae12a7e..65205be39c 100644 --- a/src/libxrpl/net/HTTPClient.cpp +++ b/src/libxrpl/net/HTTPClient.cpp @@ -59,6 +59,7 @@ public: //-------------------------------------------------------------------------- void + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) makeGet(std::string const& strPath, boost::asio::streambuf& sb, std::string const& strHost) { std::ostream osRequest(&sb); diff --git a/src/libxrpl/nodestore/ManagerImp.cpp b/src/libxrpl/nodestore/ManagerImp.cpp index b749a329ff..da9534f68b 100644 --- a/src/libxrpl/nodestore/ManagerImp.cpp +++ b/src/libxrpl/nodestore/ManagerImp.cpp @@ -55,7 +55,7 @@ ManagerImp::make_Backend( missing_backend(); auto factory{find(type)}; - if (!factory) + if (factory == nullptr) { missing_backend(); } diff --git a/src/libxrpl/nodestore/backend/RocksDBFactory.cpp b/src/libxrpl/nodestore/backend/RocksDBFactory.cpp index 67c329bb4a..ac040f178b 100644 --- a/src/libxrpl/nodestore/backend/RocksDBFactory.cpp +++ b/src/libxrpl/nodestore/backend/RocksDBFactory.cpp @@ -213,7 +213,7 @@ public: rocksdb::DB* db = nullptr; m_options.create_if_missing = createIfMissing; rocksdb::Status status = rocksdb::DB::Open(m_options, m_name, &db); - if (!status.ok() || !db) + if (!status.ok() || (db == nullptr)) { Throw( std::string("Unable to open/create RocksDB: ") + status.ToString()); diff --git a/src/libxrpl/protocol/BuildInfo.cpp b/src/libxrpl/protocol/BuildInfo.cpp index 7d9a2047a9..6a30a02756 100644 --- a/src/libxrpl/protocol/BuildInfo.cpp +++ b/src/libxrpl/protocol/BuildInfo.cpp @@ -140,7 +140,7 @@ encodeSoftwareVersion(std::string_view versionStr) if (x == 0) x = parsePreRelease(id, "b", 0x40, 0, 63); - if (x & 0xC0) + if ((x & 0xC0) != 0) { c |= static_cast(x) << 16; break; diff --git a/src/libxrpl/protocol/ErrorCodes.cpp b/src/libxrpl/protocol/ErrorCodes.cpp index 33ec869db6..407e1ab3f3 100644 --- a/src/libxrpl/protocol/ErrorCodes.cpp +++ b/src/libxrpl/protocol/ErrorCodes.cpp @@ -205,9 +205,7 @@ make_error(error_code_i code, std::string const& message) bool contains_error(Json::Value const& json) { - if (json.isObject() && json.isMember(jss::error)) - return true; - return false; + return json.isObject() && json.isMember(jss::error); } int diff --git a/src/libxrpl/protocol/Feature.cpp b/src/libxrpl/protocol/Feature.cpp index f91e164c92..1762d7d22d 100644 --- a/src/libxrpl/protocol/Feature.cpp +++ b/src/libxrpl/protocol/Feature.cpp @@ -209,7 +209,7 @@ FeatureCollections::getRegisteredFeature(std::string const& name) const XRPL_ASSERT( readOnly.load(), "xrpl::FeatureCollections::getRegisteredFeature : startup completed"); Feature const* feature = getByName(name); - if (feature) + if (feature != nullptr) return feature->feature; return std::nullopt; } @@ -229,7 +229,7 @@ FeatureCollections::registerFeature(std::string const& name, Supported support, support == Supported::yes || vote == VoteBehavior::DefaultNo, "Invalid feature parameters. Must be supported to be up-voted."); Feature const* i = getByName(name); - if (!i) + if (i == nullptr) { check(features.size() < detail::numFeatures, "More features defined than allocated."); @@ -283,7 +283,7 @@ FeatureCollections::featureToBitsetIndex(uint256 const& f) const readOnly.load(), "xrpl::FeatureCollections::featureToBitsetIndex : startup completed"); Feature const* feature = getByFeature(f); - if (!feature) + if (feature == nullptr) LogicError("Invalid Feature ID"); return getIndex(*feature); @@ -303,7 +303,7 @@ FeatureCollections::featureToName(uint256 const& f) const { XRPL_ASSERT(readOnly.load(), "xrpl::FeatureCollections::featureToName : startup completed"); Feature const* feature = getByFeature(f); - return feature ? feature->name : to_string(f); + return (feature != nullptr) ? feature->name : to_string(f); } FeatureCollections featureCollections; diff --git a/src/libxrpl/protocol/IOUAmount.cpp b/src/libxrpl/protocol/IOUAmount.cpp index eba78e6051..338f2c2760 100644 --- a/src/libxrpl/protocol/IOUAmount.cpp +++ b/src/libxrpl/protocol/IOUAmount.cpp @@ -186,7 +186,7 @@ mulRatio(IOUAmount const& amt, std::uint32_t num, std::uint32_t den, bool roundU { using namespace boost::multiprecision; - if (!den) + if (den == 0u) Throw("division by zero"); // A vector with the value 10^index for indexes from 0 to 29 diff --git a/src/libxrpl/protocol/InnerObjectFormats.cpp b/src/libxrpl/protocol/InnerObjectFormats.cpp index 8139ef0f55..bccfe210d1 100644 --- a/src/libxrpl/protocol/InnerObjectFormats.cpp +++ b/src/libxrpl/protocol/InnerObjectFormats.cpp @@ -172,7 +172,7 @@ SOTemplate const* InnerObjectFormats::findSOTemplateBySField(SField const& sField) const { auto itemPtr = findByType(sField.getCode()); - if (itemPtr) + if (itemPtr != nullptr) return &(itemPtr->getSOTemplate()); return nullptr; diff --git a/src/libxrpl/protocol/NFTokenOfferID.cpp b/src/libxrpl/protocol/NFTokenOfferID.cpp index e7ebbcf84b..4af589a4e9 100644 --- a/src/libxrpl/protocol/NFTokenOfferID.cpp +++ b/src/libxrpl/protocol/NFTokenOfferID.cpp @@ -24,7 +24,7 @@ canHaveNFTokenOfferID( return false; TxType const tt = serializedTx->getTxnType(); - if (!(tt == ttNFTOKEN_MINT && serializedTx->isFieldPresent(sfAmount)) && + if ((tt != ttNFTOKEN_MINT || !serializedTx->isFieldPresent(sfAmount)) && tt != ttNFTOKEN_CREATE_OFFER) return false; diff --git a/src/libxrpl/protocol/Permissions.cpp b/src/libxrpl/protocol/Permissions.cpp index 4137c73624..47fc0d28b6 100644 --- a/src/libxrpl/protocol/Permissions.cpp +++ b/src/libxrpl/protocol/Permissions.cpp @@ -176,13 +176,13 @@ Permission::isDelegable(std::uint32_t const& permissionValue, Rules const& rules } uint32_t -Permission::txToPermissionType(TxType const& type) const +Permission::txToPermissionType(TxType const& type) { return static_cast(type) + 1; } TxType -Permission::permissionToTxType(uint32_t const& value) const +Permission::permissionToTxType(uint32_t const& value) { return static_cast(value - 1); } diff --git a/src/libxrpl/protocol/PublicKey.cpp b/src/libxrpl/protocol/PublicKey.cpp index 2c63ddac64..2e08c49a4e 100644 --- a/src/libxrpl/protocol/PublicKey.cpp +++ b/src/libxrpl/protocol/PublicKey.cpp @@ -75,7 +75,7 @@ static std::string sliceToHex(Slice const& slice) { std::string s; - if (slice[0] & 0x80) + if ((slice[0] & 0x80) != 0) { s.reserve(2 * (slice.size() + 2)); s = "0x00"; diff --git a/src/libxrpl/protocol/STAccount.cpp b/src/libxrpl/protocol/STAccount.cpp index ffd0b5d3c8..2dc83cb591 100644 --- a/src/libxrpl/protocol/STAccount.cpp +++ b/src/libxrpl/protocol/STAccount.cpp @@ -84,7 +84,7 @@ bool STAccount::isEquivalent(STBase const& t) const { auto const* const tPtr = dynamic_cast(&t); - return tPtr && (default_ == tPtr->default_) && (value_ == tPtr->value_); + return (tPtr != nullptr) && (default_ == tPtr->default_) && (value_ == tPtr->value_); } bool diff --git a/src/libxrpl/protocol/STAmount.cpp b/src/libxrpl/protocol/STAmount.cpp index 92ce129825..8c0068a275 100644 --- a/src/libxrpl/protocol/STAmount.cpp +++ b/src/libxrpl/protocol/STAmount.cpp @@ -152,7 +152,7 @@ STAmount::STAmount(SerialIter& sit, SField const& name) : STBase(name) value &= ~(1023ull << (64 - 10)); - if (value) + if (value != 0u) { bool isNegative = (offset & 256) == 0; offset = (offset & 255) - 97; // center the range @@ -505,14 +505,11 @@ canAdd(STAmount const& a, STAmount const& b) XRPAmount A = a.xrp(); XRPAmount B = b.xrp(); - if ((B > XRPAmount{0} && + return !( + (B > XRPAmount{0} && A > XRPAmount{std::numeric_limits::max()} - B) || (B < XRPAmount{0} && - A < XRPAmount{std::numeric_limits::min()} - B)) - { - return false; - } - return true; + A < XRPAmount{std::numeric_limits::min()} - B)); } // IOU case (precision check) @@ -530,15 +527,11 @@ canAdd(STAmount const& a, STAmount const& b) { MPTAmount A = a.mpt(); MPTAmount B = b.mpt(); - if ((B > MPTAmount{0} && + return !( + (B > MPTAmount{0} && A > MPTAmount{std::numeric_limits::max()} - B) || (B < MPTAmount{0} && - A < MPTAmount{std::numeric_limits::min()} - B)) - { - return false; - } - - return true; + A < MPTAmount{std::numeric_limits::min()} - B)); } // LCOV_EXCL_START UNREACHABLE("STAmount::canAdd : unexpected STAmount type"); @@ -803,7 +796,7 @@ bool STAmount::isEquivalent(STBase const& t) const { STAmount const* v = dynamic_cast(&t); - return v && (*v == *this); + return (v != nullptr) && (*v == *this); } bool diff --git a/src/libxrpl/protocol/STBlob.cpp b/src/libxrpl/protocol/STBlob.cpp index 1a9dae7771..e7d45a698d 100644 --- a/src/libxrpl/protocol/STBlob.cpp +++ b/src/libxrpl/protocol/STBlob.cpp @@ -53,7 +53,7 @@ bool STBlob::isEquivalent(STBase const& t) const { STBlob const* v = dynamic_cast(&t); - return v && (value_ == v->value_); + return (v != nullptr) && (value_ == v->value_); } bool diff --git a/src/libxrpl/protocol/STCurrency.cpp b/src/libxrpl/protocol/STCurrency.cpp index 1616de59b9..3ca7b60d6b 100644 --- a/src/libxrpl/protocol/STCurrency.cpp +++ b/src/libxrpl/protocol/STCurrency.cpp @@ -56,7 +56,7 @@ bool STCurrency::isEquivalent(STBase const& t) const { STCurrency const* v = dynamic_cast(&t); - return v && (*v == *this); + return (v != nullptr) && (*v == *this); } bool diff --git a/src/libxrpl/protocol/STIssue.cpp b/src/libxrpl/protocol/STIssue.cpp index 1d37554251..bc39ea1b55 100644 --- a/src/libxrpl/protocol/STIssue.cpp +++ b/src/libxrpl/protocol/STIssue.cpp @@ -110,7 +110,7 @@ bool STIssue::isEquivalent(STBase const& t) const { STIssue const* v = dynamic_cast(&t); - return v && (*v == *this); + return (v != nullptr) && (*v == *this); } bool diff --git a/src/libxrpl/protocol/STLedgerEntry.cpp b/src/libxrpl/protocol/STLedgerEntry.cpp index aa97b6b3a2..02e5ddb451 100644 --- a/src/libxrpl/protocol/STLedgerEntry.cpp +++ b/src/libxrpl/protocol/STLedgerEntry.cpp @@ -136,7 +136,7 @@ STLedgerEntry::isThreadedType(Rules const& rules) const // Exclude PrevTxnID/PrevTxnLgrSeq if the fixPreviousTxnID amendment is not // enabled and the ledger object type is in the above set bool const excludePrevTxnID = !rules.enabled(fixPreviousTxnID) && - std::count(newPreviousTxnIDTypes.cbegin(), newPreviousTxnIDTypes.cend(), type_); + (std::count(newPreviousTxnIDTypes.cbegin(), newPreviousTxnIDTypes.cend(), type_) != 0); return !excludePrevTxnID && getFieldIndex(sfPreviousTxnID) != -1; } diff --git a/src/libxrpl/protocol/STObject.cpp b/src/libxrpl/protocol/STObject.cpp index fe9e95cc82..182653d11d 100644 --- a/src/libxrpl/protocol/STObject.cpp +++ b/src/libxrpl/protocol/STObject.cpp @@ -204,7 +204,7 @@ void STObject::applyTemplateFromSField(SField const& sField) { SOTemplate const* elements = InnerObjectFormats::getInstance().findSOTemplateBySField(sField); - if (elements) + if (elements != nullptr) applyTemplate(*elements); // May throw } @@ -276,7 +276,7 @@ STObject::hasMatchingEntry(STBase const& t) const { STBase const* o = peekAtPField(t.getFName()); - if (!o) + if (o == nullptr) return false; return t == *o; @@ -343,7 +343,7 @@ STObject::isEquivalent(STBase const& t) const { STObject const* v = dynamic_cast(&t); - if (!v) + if (v == nullptr) return false; if (mType != nullptr && v->mType == mType) @@ -480,7 +480,7 @@ STObject::setFlag(std::uint32_t f) { STUInt32* t = dynamic_cast(getPField(sfFlags, true)); - if (!t) + if (t == nullptr) return false; t->setValue(t->value() | f); @@ -492,7 +492,7 @@ STObject::clearFlag(std::uint32_t f) { STUInt32* t = dynamic_cast(getPField(sfFlags)); - if (!t) + if (t == nullptr) return false; t->setValue(t->value() & ~f); @@ -510,7 +510,7 @@ STObject::getFlags(void) const { STUInt32 const* t = dynamic_cast(peekAtPField(sfFlags)); - if (!t) + if (t == nullptr) return 0; return t->value(); @@ -574,7 +574,7 @@ STObject::delField(int index) SOEStyle STObject::getStyle(SField const& field) const { - return mType ? mType->style(field) : soeINVALID; + return (mType != nullptr) ? mType->style(field) : soeINVALID; } unsigned char @@ -877,10 +877,7 @@ STObject::operator==(STObject const& obj) const ++fields; } - if (fields != matches) - return false; - - return true; + return fields == matches; } void @@ -917,7 +914,8 @@ STObject::getSortedFields(STObject const& objToSort, WhichFields whichFields) for (detail::STVar const& elem : objToSort.v_) { STBase const& base = elem.get(); - if ((base.getSType() != STI_NOTPRESENT) && base.getFName().shouldInclude(whichFields)) + if ((base.getSType() != STI_NOTPRESENT) && + base.getFName().shouldInclude(static_cast(whichFields))) { sf.push_back(&base); } diff --git a/src/libxrpl/protocol/STParsedJSON.cpp b/src/libxrpl/protocol/STParsedJSON.cpp index 0bf0c827af..702ad28414 100644 --- a/src/libxrpl/protocol/STParsedJSON.cpp +++ b/src/libxrpl/protocol/STParsedJSON.cpp @@ -1075,20 +1075,20 @@ parseArray( // TODO: There doesn't seem to be a nice way to get just the // first/only key in an object without copying all keys into // a vector - std::string const objectName(json[i].getMemberNames()[0]); + std::string const memberName(json[i].getMemberNames()[0]); ; - auto const& nameField(SField::getField(objectName)); + auto const& nameField(SField::getField(memberName)); if (nameField == sfInvalid) { - error = unknown_field(json_name, objectName); + error = unknown_field(json_name, memberName); return std::nullopt; } - Json::Value const objectFields(json[i][objectName]); + Json::Value const objectFields(json[i][memberName]); std::stringstream ss; - ss << json_name << "." << "[" << i << "]." << objectName; + ss << json_name << "." << "[" << i << "]." << memberName; auto ret = parseObject(ss.str(), objectFields, nameField, depth + 1, error); if (!ret) diff --git a/src/libxrpl/protocol/STPathSet.cpp b/src/libxrpl/protocol/STPathSet.cpp index 060f5c4d7c..86e61e91bf 100644 --- a/src/libxrpl/protocol/STPathSet.cpp +++ b/src/libxrpl/protocol/STPathSet.cpp @@ -61,7 +61,7 @@ STPathSet::STPathSet(SerialIter& sit, SField const& name) : STBase(name) if (iType == STPathElement::typeNone) return; } - else if (iType & ~STPathElement::typeAll) + else if ((iType & ~STPathElement::typeAll) != 0) { JLOG(debugLog().error()) << "Bad path element " << iType << " in pathset"; Throw("bad path element"); @@ -76,13 +76,13 @@ STPathSet::STPathSet(SerialIter& sit, SField const& name) : STBase(name) Currency currency; AccountID issuer; - if (hasAccount) + if (hasAccount != 0) account = sit.get160(); - if (hasCurrency) + if (hasCurrency != 0) currency = sit.get160(); - if (hasIssuer) + if (hasIssuer != 0) issuer = sit.get160(); path.emplace_back(account, currency, issuer, hasCurrency); @@ -127,7 +127,7 @@ bool STPathSet::isEquivalent(STBase const& t) const { STPathSet const* v = dynamic_cast(&t); - return v && (value == v->value); + return (v != nullptr) && (value == v->value); } bool @@ -160,13 +160,13 @@ STPath::getJson(JsonOptions) const elem[jss::type] = iType; - if (iType & STPathElement::typeAccount) + if ((iType & STPathElement::typeAccount) != 0u) elem[jss::account] = to_string(it.getAccountID()); - if (iType & STPathElement::typeCurrency) + if ((iType & STPathElement::typeCurrency) != 0u) elem[jss::currency] = to_string(it.getCurrency()); - if (iType & STPathElement::typeIssuer) + if ((iType & STPathElement::typeIssuer) != 0u) elem[jss::issuer] = to_string(it.getIssuerID()); ret.append(elem); @@ -209,13 +209,13 @@ STPathSet::add(Serializer& s) const s.add8(iType); - if (iType & STPathElement::typeAccount) + if ((iType & STPathElement::typeAccount) != 0) s.addBitString(speElement.getAccountID()); - if (iType & STPathElement::typeCurrency) + if ((iType & STPathElement::typeCurrency) != 0) s.addBitString(speElement.getCurrency()); - if (iType & STPathElement::typeIssuer) + if ((iType & STPathElement::typeIssuer) != 0) s.addBitString(speElement.getIssuerID()); } diff --git a/src/libxrpl/protocol/STTx.cpp b/src/libxrpl/protocol/STTx.cpp index 00a2acd788..7da1919f35 100644 --- a/src/libxrpl/protocol/STTx.cpp +++ b/src/libxrpl/protocol/STTx.cpp @@ -574,7 +574,7 @@ STTx::getBatchTransactionIDs() const { XRPL_ASSERT(getTxnType() == ttBATCH, "STTx::getBatchTransactionIDs : not a batch transaction"); XRPL_ASSERT( - getFieldArray(sfRawTransactions).size() != 0, + !getFieldArray(sfRawTransactions).empty(), "STTx::getBatchTransactionIDs : empty raw transactions"); // The list of inner ids is built once, then reused on subsequent calls. @@ -618,7 +618,7 @@ isMemoOkay(STObject const& st, std::string& reason) { auto memoObj = dynamic_cast(&memo); - if (!memoObj || (memoObj->getFName() != sfMemo)) + if ((memoObj == nullptr) || (memoObj->getFName() != sfMemo)) { reason = "A memo array may contain only Memo objects."; return false; @@ -669,7 +669,7 @@ isMemoOkay(STObject const& st, std::string& reason) for (unsigned char c : *optData) { - if (!allowedSymbols[c]) + if (allowedSymbols[c] == 0) { reason = "The MemoType and MemoFormat fields may only " @@ -691,7 +691,7 @@ isAccountFieldOkay(STObject const& st) for (int i = 0; i < st.getCount(); ++i) { auto t = dynamic_cast(st.peekAtPIndex(i)); - if (t && t->isDefault()) + if ((t != nullptr) && t->isDefault()) return false; } diff --git a/src/libxrpl/protocol/STValidation.cpp b/src/libxrpl/protocol/STValidation.cpp index f6f89d43e9..ba6e679081 100644 --- a/src/libxrpl/protocol/STValidation.cpp +++ b/src/libxrpl/protocol/STValidation.cpp @@ -107,7 +107,7 @@ STValidation::isValid() const noexcept getSignerPublic(), getSigningHash(), makeSlice(getFieldVL(sfSignature)), - getFlags() & vfFullyCanonicalSig); + (getFlags() & vfFullyCanonicalSig) != 0u); } return valid_.value(); diff --git a/src/libxrpl/protocol/STVar.cpp b/src/libxrpl/protocol/STVar.cpp index 255514d70c..8b76d8a322 100644 --- a/src/libxrpl/protocol/STVar.cpp +++ b/src/libxrpl/protocol/STVar.cpp @@ -60,7 +60,7 @@ STVar::operator=(STVar const& rhs) if (&rhs != this) { destroy(); - if (rhs.p_) + if (rhs.p_ != nullptr) { p_ = rhs.p_->copy(max_size, &d_); } diff --git a/src/libxrpl/protocol/STVector256.cpp b/src/libxrpl/protocol/STVector256.cpp index 6357e2f2cb..2a70dd1e05 100644 --- a/src/libxrpl/protocol/STVector256.cpp +++ b/src/libxrpl/protocol/STVector256.cpp @@ -68,7 +68,7 @@ bool STVector256::isEquivalent(STBase const& t) const { STVector256 const* v = dynamic_cast(&t); - return v && (mValue == v->mValue); + return (v != nullptr) && (mValue == v->mValue); } Json::Value diff --git a/src/libxrpl/protocol/STXChainBridge.cpp b/src/libxrpl/protocol/STXChainBridge.cpp index 85d36f9b46..428e4655ff 100644 --- a/src/libxrpl/protocol/STXChainBridge.cpp +++ b/src/libxrpl/protocol/STXChainBridge.cpp @@ -167,7 +167,7 @@ bool STXChainBridge::isEquivalent(STBase const& t) const { STXChainBridge const* v = dynamic_cast(&t); - return v && (*v == *this); + return (v != nullptr) && (*v == *this); } bool diff --git a/src/libxrpl/protocol/Serializer.cpp b/src/libxrpl/protocol/Serializer.cpp index 08d221f75b..0e8beae0d9 100644 --- a/src/libxrpl/protocol/Serializer.cpp +++ b/src/libxrpl/protocol/Serializer.cpp @@ -199,7 +199,7 @@ Serializer::addVL(void const* ptr, int len) { int ret = addEncoded(len); - if (len) + if (len != 0) addRaw(ptr, len); return ret; @@ -298,7 +298,7 @@ Serializer::decodeVLLength(int b1, int b2) if (b1 > 240) Throw("b1>240"); - return 193 + (b1 - 193) * 256 + b2; + return 193 + ((b1 - 193) * 256) + b2; } int @@ -310,7 +310,7 @@ Serializer::decodeVLLength(int b1, int b2, int b3) if (b1 > 254) Throw("b1>254"); - return 12481 + (b1 - 241) * 65536 + b2 * 256 + b3; + return 12481 + ((b1 - 241) * 65536) + (b2 * 256) + b3; } //------------------------------------------------------------------------------ diff --git a/src/libxrpl/protocol/TxMeta.cpp b/src/libxrpl/protocol/TxMeta.cpp index f4932b2af4..19a2755a29 100644 --- a/src/libxrpl/protocol/TxMeta.cpp +++ b/src/libxrpl/protocol/TxMeta.cpp @@ -28,7 +28,7 @@ TxMeta::TxMeta(uint256 const& txid, std::uint32_t ledger, STObject const& obj) auto affectedNodes = dynamic_cast(obj.peekAtPField(sfAffectedNodes)); XRPL_ASSERT(affectedNodes, "xrpl::TxMeta::TxMeta(STObject) : type cast succeeded"); - if (affectedNodes) + if (affectedNodes != nullptr) nodes_ = *affectedNodes; setAdditionalFields(obj); @@ -96,7 +96,7 @@ TxMeta::getAffectedAccounts() const { auto const* inner = dynamic_cast(&node.peekAtIndex(index)); XRPL_ASSERT(inner, "xrpl::getAffectedAccounts : STObject type cast succeeded"); - if (inner) + if (inner != nullptr) { for (auto const& field : *inner) { diff --git a/src/libxrpl/protocol/UintTypes.cpp b/src/libxrpl/protocol/UintTypes.cpp index df9eadb511..5ace6c29d6 100644 --- a/src/libxrpl/protocol/UintTypes.cpp +++ b/src/libxrpl/protocol/UintTypes.cpp @@ -63,7 +63,7 @@ to_string(Currency const& currency) bool to_currency(Currency& currency, std::string const& code) { - if (code.empty() || !code.compare(systemCurrencyCode())) + if (code.empty() || (code.compare(systemCurrencyCode()) == 0)) { currency = beast::zero; return true; diff --git a/src/libxrpl/protocol/tokens.cpp b/src/libxrpl/protocol/tokens.cpp index b46591725f..bca8919c4e 100644 --- a/src/libxrpl/protocol/tokens.cpp +++ b/src/libxrpl/protocol/tokens.cpp @@ -263,7 +263,7 @@ decodeBase58(std::string const& s) // Allocate enough space in big-endian base256 representation. // log(58) / log(256), rounded up. - std::vector b256(remain * 733 / 1000 + 1); + std::vector b256((remain * 733 / 1000) + 1); while (remain > 0) { auto carry = alphabetReverse[*psz]; @@ -308,7 +308,7 @@ encodeBase58Token(TokenType type, void const* token, std::size_t size) // Lay the data out as // buf[0] = safe_cast>(type); - if (size) + if (size != 0u) std::memcpy(buf.data() + 1, token, size); checksum(buf.data() + 1 + size, buf.data(), 1 + size); @@ -383,7 +383,7 @@ b256_to_b58_be(std::span input, std::span out) { break; } - auto const src_i_end = input.size() - i * 8; + auto const src_i_end = input.size() - (i * 8); if (src_i_end >= 8) { std::memcpy(&base_2_64_coeff_buf[num_coeff], &input[src_i_end - 8], 8); @@ -450,7 +450,7 @@ b256_to_b58_be(std::span input, std::span out) { to_skip = count_leading_zeros(b58_be_s); skip_zeros = false; - if (out.size() < (i + 1) * 10 - to_skip) + if (out.size() < ((i + 1) * 10) - to_skip) { return Unexpected(TokenCodecErrc::outputTooSmall); } @@ -502,7 +502,7 @@ b58_to_b256_be(std::string_view input, std::span out) // log(2^(38*8),58^10)) ~= 5.18. So 6 coeff are enough std::array b_58_10_coeff{}; auto [num_full_coeffs, partial_coeff_len] = xrpl::b58_fast::detail::div_rem(input.size(), 10); - auto const num_partial_coeffs = partial_coeff_len ? 1 : 0; + auto const num_partial_coeffs = (partial_coeff_len != 0u) ? 1 : 0; auto const num_b_58_10_coeffs = num_full_coeffs + num_partial_coeffs; XRPL_ASSERT( num_b_58_10_coeffs <= b_58_10_coeff.size(), @@ -521,7 +521,7 @@ b58_to_b256_be(std::string_view input, std::span out) { for (int j = 0; j < num_full_coeffs; ++j) { - unsigned char c = input[partial_coeff_len + j * 10 + i]; + unsigned char c = input[partial_coeff_len + (j * 10) + i]; auto cur_val = ::xrpl::alphabetReverse[c]; if (cur_val < 0) { @@ -586,7 +586,7 @@ b58_to_b256_be(std::string_view input, std::span out) cur_out_i += 1; } } - if ((cur_out_i + 8 * (cur_result_size - 1)) > out.size()) + if ((cur_out_i + (8 * (cur_result_size - 1))) > out.size()) { return Unexpected(TokenCodecErrc::outputTooSmall); } diff --git a/src/libxrpl/rdb/DatabaseCon.cpp b/src/libxrpl/rdb/DatabaseCon.cpp index 344df85b4a..6552a1d7ce 100644 --- a/src/libxrpl/rdb/DatabaseCon.cpp +++ b/src/libxrpl/rdb/DatabaseCon.cpp @@ -72,7 +72,7 @@ DatabaseCon::~DatabaseCon() // checkpoint is currently in progress. Wait for it to end, otherwise // creating a new DatabaseCon to the same database may fail due to the // database being locked by our (now old) Checkpointer. - while (wk.use_count()) + while (wk.use_count() != 0) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } @@ -84,7 +84,7 @@ std::unique_ptr const> DatabaseCon::Setup::globalPragma void DatabaseCon::setupCheckpointing(JobQueue* q, Logs& l) { - if (!q) + if (q == nullptr) Throw("No JobQueue"); checkpointer_ = checkpointers.create(session_, *q, l); } diff --git a/src/libxrpl/rdb/SociDB.cpp b/src/libxrpl/rdb/SociDB.cpp index baadeef00a..576105016e 100644 --- a/src/libxrpl/rdb/SociDB.cpp +++ b/src/libxrpl/rdb/SociDB.cpp @@ -98,7 +98,7 @@ getConnection(soci::session& s) if (auto b = dynamic_cast(be)) result = b->conn_; - if (!result) + if (result == nullptr) Throw("Didn't get a database connection."); return result; @@ -107,7 +107,7 @@ getConnection(soci::session& s) std::uint32_t getKBUsedAll(soci::session& s) { - if (!getConnection(s)) + if (getConnection(s) == nullptr) Throw("No connection found."); return static_cast(sqlite_api::sqlite3_memory_used() / kilobytes(1)); } @@ -249,7 +249,7 @@ public: { auto [conn, keepAlive] = getConnection(); (void)keepAlive; - if (!conn) + if (conn == nullptr) return; int log = 0, ckpt = 0; diff --git a/src/libxrpl/resource/Consumer.cpp b/src/libxrpl/resource/Consumer.cpp index e9435bd340..c1cb9d4367 100644 --- a/src/libxrpl/resource/Consumer.cpp +++ b/src/libxrpl/resource/Consumer.cpp @@ -23,7 +23,7 @@ Consumer::Consumer() : m_logic(nullptr), m_entry(nullptr) Consumer::Consumer(Consumer const& other) : m_logic(other.m_logic), m_entry(nullptr) { - if (m_logic && other.m_entry) + if ((m_logic != nullptr) && (other.m_entry != nullptr)) { m_entry = other.m_entry; m_logic->acquire(*m_entry); @@ -32,7 +32,7 @@ Consumer::Consumer(Consumer const& other) : m_logic(other.m_logic), m_entry(null Consumer::~Consumer() { - if (m_logic && m_entry) + if ((m_logic != nullptr) && (m_entry != nullptr)) m_logic->release(*m_entry); } @@ -43,14 +43,14 @@ Consumer::operator=(Consumer const& other) return *this; // remove old ref - if (m_logic && m_entry) + if ((m_logic != nullptr) && (m_entry != nullptr)) m_logic->release(*m_entry); m_logic = other.m_logic; m_entry = other.m_entry; // add new ref - if (m_logic && m_entry) + if ((m_logic != nullptr) && (m_entry != nullptr)) m_logic->acquire(*m_entry); return *this; @@ -68,7 +68,7 @@ Consumer::to_string() const bool Consumer::isUnlimited() const { - if (m_entry) + if (m_entry != nullptr) return m_entry->isUnlimited(); return false; @@ -78,7 +78,7 @@ Disposition Consumer::disposition() const { Disposition d = ok; - if (m_logic && m_entry) + if ((m_logic != nullptr) && (m_entry != nullptr)) d = m_logic->charge(*m_entry, Charge(0)); return d; @@ -89,7 +89,7 @@ Consumer::charge(Charge const& what, std::string const& context) { Disposition d = ok; - if (m_logic && m_entry && !m_entry->isUnlimited()) + if ((m_logic != nullptr) && (m_entry != nullptr) && !m_entry->isUnlimited()) d = m_logic->charge(*m_entry, what, context); return d; diff --git a/src/libxrpl/server/State.cpp b/src/libxrpl/server/State.cpp index 371f2b4d0a..a7c0c0fca2 100644 --- a/src/libxrpl/server/State.cpp +++ b/src/libxrpl/server/State.cpp @@ -31,7 +31,7 @@ initStateDB(soci::session& session, BasicConfig const& config, std::string const count = *countO; } - if (!count) + if (count == 0) { session << "INSERT INTO DbState VALUES (1, '', '', 0);"; } @@ -45,7 +45,7 @@ initStateDB(soci::session& session, BasicConfig const& config, std::string const count = *countO; } - if (!count) + if (count == 0) { session << "INSERT INTO CanDelete VALUES (1, 0);"; } diff --git a/src/libxrpl/shamap/SHAMap.cpp b/src/libxrpl/shamap/SHAMap.cpp index a6aacfabc9..a9182a59cf 100644 --- a/src/libxrpl/shamap/SHAMap.cpp +++ b/src/libxrpl/shamap/SHAMap.cpp @@ -130,7 +130,7 @@ SHAMapLeafNode* SHAMap::findKey(uint256 const& id) const { SHAMapLeafNode* leaf = walkTowardsKey(id); - if (leaf && leaf->peekItem()->key() != id) + if ((leaf != nullptr) && leaf->peekItem()->key() != id) leaf = nullptr; return leaf; } @@ -221,7 +221,7 @@ SHAMap::fetchNodeNT(SHAMapHash const& hash, SHAMapSyncFilter* filter) const } } - if (filter) + if (filter != nullptr) node = checkFilter(hash, filter); return node; @@ -255,7 +255,7 @@ SHAMap::descendThrow(SHAMapInnerNode* parent, int branch) const { SHAMapTreeNode* ret = descend(parent, branch); - if (!ret && !parent->isEmptyBranch(branch)) + if ((ret == nullptr) && !parent->isEmptyBranch(branch)) Throw(type_, parent->getChildHash(branch)); return ret; @@ -276,7 +276,7 @@ SHAMapTreeNode* SHAMap::descend(SHAMapInnerNode* parent, int branch) const { SHAMapTreeNode* ret = parent->getChildPointer(branch); - if (ret || !backed_) + if ((ret != nullptr) || !backed_) return ret; intr_ptr::SharedPtr node = fetchNodeNT(parent->getChildHash(branch)); @@ -328,7 +328,7 @@ SHAMap::descend( SHAMapTreeNode* child = parent->getChildPointer(branch); - if (!child) + if (child == nullptr) { auto const& childHash = parent->getChildHash(branch); intr_ptr::SharedPtr childNode = fetchNodeNT(childHash, filter); @@ -354,7 +354,7 @@ SHAMap::descendAsync( pending = false; SHAMapTreeNode* ret = parent->getChildPointer(branch); - if (ret) + if (ret != nullptr) return ret; auto const& hash = parent->getChildHash(branch); @@ -362,7 +362,7 @@ SHAMap::descendAsync( auto ptr = cacheLookup(hash); if (!ptr) { - if (filter) + if (filter != nullptr) ptr = checkFilter(hash, filter); if (!ptr && backed_) @@ -483,14 +483,14 @@ SHAMap::onlyBelow(SHAMapTreeNode* node) const { if (!inner->isEmptyBranch(i)) { - if (nextNode) + if (nextNode != nullptr) return no_item; nextNode = descendThrow(inner, i); } } - if (!nextNode) + if (nextNode == nullptr) { // LCOV_EXCL_START UNREACHABLE("xrpl::SHAMap::onlyBelow : no next node"); @@ -514,7 +514,7 @@ SHAMap::peekFirstItem(SharedPtrNodeStack& stack) const { XRPL_ASSERT(stack.empty(), "xrpl::SHAMap::peekFirstItem : empty stack input"); SHAMapLeafNode* node = firstBelow(root_, stack); - if (!node) + if (node == nullptr) { while (!stack.empty()) stack.pop(); @@ -540,7 +540,7 @@ SHAMap::peekNextItem(uint256 const& id, SharedPtrNodeStack& stack) const { node = descendThrow(*inner, i); auto leaf = firstBelow(node, stack, i); - if (!leaf) + if (leaf == nullptr) Throw(type_, id); XRPL_ASSERT(leaf->isLeaf(), "xrpl::SHAMap::peekNextItem : leaf is valid"); return leaf; @@ -557,7 +557,7 @@ SHAMap::peekItem(uint256 const& id) const { SHAMapLeafNode* leaf = findKey(id); - if (!leaf) + if (leaf == nullptr) return no_item; return leaf->peekItem(); @@ -568,7 +568,7 @@ SHAMap::peekItem(uint256 const& id, SHAMapHash& hash) const { SHAMapLeafNode* leaf = findKey(id); - if (!leaf) + if (leaf == nullptr) return no_item; hash = leaf->getHash(); @@ -598,7 +598,7 @@ SHAMap::upper_bound(uint256 const& id) const { node = descendThrow(*inner, branch); auto leaf = firstBelow(node, stack, branch); - if (!leaf) + if (leaf == nullptr) Throw(type_, id); return const_iterator(this, leaf->peekItem().get(), std::move(stack)); } @@ -631,7 +631,7 @@ SHAMap::lower_bound(uint256 const& id) const { node = descendThrow(*inner, branch); auto leaf = lastBelow(node, stack, branch); - if (!leaf) + if (leaf == nullptr) Throw(type_, id); return const_iterator(this, leaf->peekItem().get(), std::move(stack)); } @@ -995,7 +995,7 @@ SHAMap::walkSubTree(bool doWrite, NodeObjectType t) int pos = 0; // We can't flush an inner node until we flush its children - while (1) + while (true) { while (pos < branchFactor) { @@ -1109,7 +1109,7 @@ SHAMap::dump(bool hash) const if (!inner->isEmptyBranch(i)) { auto child = inner->getChildPointer(i); - if (child) + if (child != nullptr) { XRPL_ASSERT( child->getHash() == inner->getChildHash(i), diff --git a/src/libxrpl/shamap/SHAMapDelta.cpp b/src/libxrpl/shamap/SHAMapDelta.cpp index 98a31fea55..0b5a09d4a7 100644 --- a/src/libxrpl/shamap/SHAMapDelta.cpp +++ b/src/libxrpl/shamap/SHAMapDelta.cpp @@ -136,7 +136,7 @@ SHAMap::compare(SHAMap const& otherMap, Delta& differences, int maxCount) const auto [ourNode, otherNode] = nodeStack.top(); nodeStack.pop(); - if (!ourNode || !otherNode) + if ((ourNode == nullptr) || (otherNode == nullptr)) { // LCOV_EXCL_START UNREACHABLE("xrpl::SHAMap::compare : missing a node"); diff --git a/src/libxrpl/shamap/SHAMapNodeID.cpp b/src/libxrpl/shamap/SHAMapNodeID.cpp index 6536e628ef..97a8b26a3b 100644 --- a/src/libxrpl/shamap/SHAMapNodeID.cpp +++ b/src/libxrpl/shamap/SHAMapNodeID.cpp @@ -76,7 +76,7 @@ SHAMapNodeID::getChildNodeID(unsigned int m) const Throw("Incorrect mask for " + to_string(*this)); SHAMapNodeID node{depth_ + 1, id_}; - node.id_.begin()[depth_ / 2] |= (depth_ & 1) ? m : (m << 4); + node.id_.begin()[depth_ / 2] |= ((depth_ & 1) != 0u) ? m : (m << 4); return node; } @@ -106,7 +106,7 @@ selectBranch(SHAMapNodeID const& id, uint256 const& hash) auto const depth = id.getDepth(); auto branch = static_cast(*(hash.begin() + (depth / 2))); - if (depth & 1) + if ((depth & 1) != 0u) { branch &= 0xf; } diff --git a/src/libxrpl/shamap/SHAMapSync.cpp b/src/libxrpl/shamap/SHAMapSync.cpp index c6e4c3dcb0..14ccdca2eb 100644 --- a/src/libxrpl/shamap/SHAMapSync.cpp +++ b/src/libxrpl/shamap/SHAMapSync.cpp @@ -93,13 +93,13 @@ SHAMap::visitDifferences( if (root_->getHash().isZero()) return; - if (have && (root_->getHash() == have->root_->getHash())) + if ((have != nullptr) && (root_->getHash() == have->root_->getHash())) return; if (root_->isLeaf()) { auto leaf = intr_ptr::static_pointer_cast(root_); - if (!have || !have->hasLeafNode(leaf->peekItem()->key(), leaf->getHash())) + if ((have == nullptr) || !have->hasLeafNode(leaf->peekItem()->key(), leaf->getHash())) function(*root_); return; } @@ -129,11 +129,11 @@ SHAMap::visitDifferences( if (next->isInner()) { - if (!have || !have->hasInnerNode(childID, childHash)) + if ((have == nullptr) || !have->hasInnerNode(childID, childHash)) stack.push({safe_downcast(next), childID}); } else if ( - !have || + (have == nullptr) || !have->hasLeafNode( safe_downcast(next)->peekItem()->key(), childHash)) { @@ -192,7 +192,7 @@ SHAMap::gmn_ProcessNodes(MissingNodes& mn, MissingNodes::StackEntry& se) fullBelow = false; ++mn.deferred_; } - else if (!d) + else if (d == nullptr) { // node is not in database @@ -347,7 +347,7 @@ SHAMap::getMissingNodes(int max, SHAMapSyncFilter* filter) // We have either emptied the stack or // posted as many deferred reads as we can - if (mn.deferred_) + if (mn.deferred_ != 0) gmn_ProcessDeferredReads(mn); if (mn.max_ <= 0) @@ -402,7 +402,7 @@ SHAMap::getNodeFat( auto node = root_.get(); SHAMapNodeID nodeID; - while (node && node->isInner() && (nodeID.getDepth() < wanted.getDepth())) + while ((node != nullptr) && node->isInner() && (nodeID.getDepth() < wanted.getDepth())) { int branch = selectBranch(nodeID, wanted.getNodeID()); auto inner = safe_downcast(node); @@ -509,7 +509,7 @@ SHAMap::addRootNode(SHAMapHash const& hash, Slice const& rootNode, SHAMapSyncFil if (root_->isLeaf()) clearSynching(); - if (filter) + if (filter != nullptr) { Serializer s; root_->serializeWithPrefix(s); @@ -615,7 +615,7 @@ SHAMap::addKnownNode(SHAMapNodeID const& node, Slice const& rawNode, SHAMapSyncF newNode = prevNode->canonicalizeChild(branch, std::move(newNode)); - if (filter) + if (filter != nullptr) { Serializer s; newNode->serializeWithPrefix(s); @@ -643,7 +643,7 @@ SHAMap::deepCompare(SHAMap& other) const auto const [node, otherNode] = stack.top(); stack.pop(); - if (!node || !otherNode) + if ((node == nullptr) || (otherNode == nullptr)) { JLOG(journal_.info()) << "unable to fetch node"; return false; @@ -685,7 +685,7 @@ SHAMap::deepCompare(SHAMap& other) const auto next = descend(node_inner, i); auto otherNext = other.descend(other_inner, i); - if (!next || !otherNext) + if ((next == nullptr) || (otherNext == nullptr)) { JLOG(journal_.warn()) << "unable to fetch inner node"; return false; diff --git a/src/libxrpl/tx/ApplyContext.cpp b/src/libxrpl/tx/ApplyContext.cpp index f62c63d1e6..edca31c04a 100644 --- a/src/libxrpl/tx/ApplyContext.cpp +++ b/src/libxrpl/tx/ApplyContext.cpp @@ -40,7 +40,7 @@ ApplyContext::discard() std::optional ApplyContext::apply(TER ter) { - return view_->apply(base_, tx, ter, parentBatchId_, flags_ & tapDRY_RUN, journal); + return view_->apply(base_, tx, ter, parentBatchId_, (flags_ & tapDRY_RUN) != 0u, journal); } std::size_t diff --git a/src/libxrpl/tx/Transactor.cpp b/src/libxrpl/tx/Transactor.cpp index 6e334b5563..d579d26c67 100644 --- a/src/libxrpl/tx/Transactor.cpp +++ b/src/libxrpl/tx/Transactor.cpp @@ -65,7 +65,7 @@ preflight0(PreflightContext const& ctx, std::uint32_t flagMask) return temINVALID; } - if (ctx.tx.getFlags() & flagMask) + if ((ctx.tx.getFlags() & flagMask) != 0u) { JLOG(ctx.j.debug()) << ctx.tx.peekAtField(sfTransactionType).getFullText() << ": invalid flags."; @@ -96,7 +96,7 @@ preflightCheckSigningKey(STObject const& sigObject, beast::Journal j) std::optional preflightCheckSimulateKeys(ApplyFlags flags, STObject const& sigObject, beast::Journal j) { - if (flags & tapDRY_RUN) // simulation + if ((flags & tapDRY_RUN) != 0u) // simulation { std::optional const signature = sigObject[~sfTxnSignature]; if (signature && !signature->empty()) @@ -318,7 +318,7 @@ Transactor::minimumFee( Fees const& fees, ApplyFlags flags) { - return scaleFeeLoad(baseFee, registry.getFeeTrack(), fees, flags & tapUNLIMITED); + return scaleFeeLoad(baseFee, registry.getFeeTrack(), fees, (flags & tapUNLIMITED) != 0u); } TER @@ -329,7 +329,7 @@ Transactor::checkFee(PreclaimContext const& ctx, XRPAmount baseFee) auto const feePaid = ctx.tx[sfFee].xrp(); - if (ctx.flags & tapBATCH) + if ((ctx.flags & tapBATCH) != 0u) { if (feePaid == beast::zero) return tesSUCCESS; @@ -653,7 +653,7 @@ Transactor::checkSign( return tesSUCCESS; } - if ((flags & tapDRY_RUN) && pkSigner.empty() && !sigObject.isFieldPresent(sfSigners)) + if (((flags & tapDRY_RUN) != 0u) && pkSigner.empty() && !sigObject.isFieldPresent(sfSigners)) { // simulate: skip signature validation when neither SigningPubKey nor // Signers are provided @@ -886,7 +886,7 @@ Transactor::checkMultiSign( // Master Key. Account may not have asfDisableMaster set. std::uint32_t const signerAccountFlags = sleTxSignerRoot->getFieldU32(sfFlags); - if (signerAccountFlags & lsfDisableMaster) + if ((signerAccountFlags & lsfDisableMaster) != 0u) { JLOG(j.trace()) << "applyTransaction: Signer:Account lsfDisableMaster."; return tefMASTER_DISABLED; @@ -1119,7 +1119,7 @@ Transactor::operator()() if (ctx_.size() > oversizeMetaDataCap) result = tecOVERSIZE; - if (isTecClaim(result) && (view().flags() & tapFAIL_HARD)) + if (isTecClaim(result) && ((view().flags() & tapFAIL_HARD) != 0u)) { // If the tapFAIL_HARD flag is set, a tec result // must not do anything @@ -1264,7 +1264,7 @@ Transactor::operator()() metadata = ctx_.apply(result); } - if (ctx_.flags() & tapDRY_RUN) + if ((ctx_.flags() & tapDRY_RUN) != 0u) { applied = false; } diff --git a/src/libxrpl/tx/apply.cpp b/src/libxrpl/tx/apply.cpp index 8fd898366e..caf716eda6 100644 --- a/src/libxrpl/tx/apply.cpp +++ b/src/libxrpl/tx/apply.cpp @@ -149,7 +149,7 @@ applyBatchTransactions( beast::Journal j) { XRPL_ASSERT( - batchTxn.getTxnType() == ttBATCH && batchTxn.getFieldArray(sfRawTransactions).size() != 0, + batchTxn.getTxnType() == ttBATCH && !batchTxn.getFieldArray(sfRawTransactions).empty(), "Batch transaction missing sfRawTransactions"); auto const parentBatchId = batchTxn.getTransactionID(); @@ -188,13 +188,13 @@ applyBatchTransactions( if (!isTesSuccess(result.ter)) { - if (mode & tfAllOrNothing) + if ((mode & tfAllOrNothing) != 0u) return false; - if (mode & tfUntilFailure) + if ((mode & tfUntilFailure) != 0u) break; } - else if (mode & tfOnlyOne) + else if ((mode & tfOnlyOne) != 0u) { break; } diff --git a/src/libxrpl/tx/invariants/AMMInvariant.cpp b/src/libxrpl/tx/invariants/AMMInvariant.cpp index b64be6192b..96df97016f 100644 --- a/src/libxrpl/tx/invariants/AMMInvariant.cpp +++ b/src/libxrpl/tx/invariants/AMMInvariant.cpp @@ -28,7 +28,7 @@ ValidAMM::visitEntry( } // AMM pool changed else if ( - (type == ltRIPPLE_STATE && after->getFlags() & lsfAMMNode) || + (type == ltRIPPLE_STATE && ((after->getFlags() & lsfAMMNode) != 0u)) || (type == ltACCOUNT_ROOT && after->isFieldPresent(sfAMMID))) { ammPoolChanged_ = true; diff --git a/src/libxrpl/tx/invariants/FreezeInvariant.cpp b/src/libxrpl/tx/invariants/FreezeInvariant.cpp index f38d260782..c8723b9bbf 100644 --- a/src/libxrpl/tx/invariants/FreezeInvariant.cpp +++ b/src/libxrpl/tx/invariants/FreezeInvariant.cpp @@ -271,12 +271,7 @@ TransfersNotFrozen::validateFrozenState( "xrpl::TransfersNotFrozen::validateFrozenState : enforce " "invariant."); - if (enforce) - { - return false; - } - - return true; + return !enforce; } } // namespace xrpl diff --git a/src/libxrpl/tx/invariants/InvariantCheck.cpp b/src/libxrpl/tx/invariants/InvariantCheck.cpp index 16108472aa..bf0f65f000 100644 --- a/src/libxrpl/tx/invariants/InvariantCheck.cpp +++ b/src/libxrpl/tx/invariants/InvariantCheck.cpp @@ -631,11 +631,11 @@ NoDeepFreezeTrustLinesWithoutFreeze::visitEntry( if (after && after->getType() == ltRIPPLE_STATE) { std::uint32_t const uFlags = after->getFieldU32(sfFlags); - bool const lowFreeze = uFlags & lsfLowFreeze; - bool const lowDeepFreeze = uFlags & lsfLowDeepFreeze; + bool const lowFreeze = (uFlags & lsfLowFreeze) != 0u; + bool const lowDeepFreeze = (uFlags & lsfLowDeepFreeze) != 0u; - bool const highFreeze = uFlags & lsfHighFreeze; - bool const highDeepFreeze = uFlags & lsfHighDeepFreeze; + bool const highFreeze = (uFlags & lsfHighFreeze) != 0u; + bool const highDeepFreeze = (uFlags & lsfHighDeepFreeze) != 0u; deepFreezeWithoutFreeze_ = (lowDeepFreeze && !lowFreeze) || (highDeepFreeze && !highFreeze); } diff --git a/src/libxrpl/tx/invariants/LoanInvariant.cpp b/src/libxrpl/tx/invariants/LoanInvariant.cpp index 0df7e409d1..c0ce320846 100644 --- a/src/libxrpl/tx/invariants/LoanInvariant.cpp +++ b/src/libxrpl/tx/invariants/LoanInvariant.cpp @@ -46,11 +46,11 @@ bool ValidLoanBroker::goodZeroDirectory( ReadView const& view, SLE::const_ref dir, - beast::Journal const& j) const + beast::Journal const& j) { auto const next = dir->at(~sfIndexNext); auto const prev = dir->at(~sfIndexPrevious); - if ((prev && *prev) || (next && *next)) + if ((prev && (*prev != 0u)) || (next && (*next != 0u))) { JLOG(j.fatal()) << "Invariant failed: Loan Broker with zero " "OwnerCount has multiple directory pages"; diff --git a/src/libxrpl/tx/paths/RippleCalc.cpp b/src/libxrpl/tx/paths/RippleCalc.cpp index e87ecab90f..cebb5c6dcc 100644 --- a/src/libxrpl/tx/paths/RippleCalc.cpp +++ b/src/libxrpl/tx/paths/RippleCalc.cpp @@ -43,9 +43,9 @@ RippleCalc::rippleCalculate( auto j = l.journal("Flow"); { - bool const defaultPaths = !pInputs ? true : pInputs->defaultPathsAllowed; + bool const defaultPaths = (pInputs == nullptr) ? true : pInputs->defaultPathsAllowed; - bool const partialPayment = !pInputs ? false : pInputs->partialPaymentAllowed; + bool const partialPayment = (pInputs == nullptr) ? false : pInputs->partialPaymentAllowed; auto const limitQuality = [&]() -> std::optional { if (pInputs && pInputs->limitQuality && saMaxAmountReq > beast::zero) diff --git a/src/libxrpl/tx/transactors/account/AccountDelete.cpp b/src/libxrpl/tx/transactors/account/AccountDelete.cpp index fed265c125..8c2f23b754 100644 --- a/src/libxrpl/tx/transactors/account/AccountDelete.cpp +++ b/src/libxrpl/tx/transactors/account/AccountDelete.cpp @@ -22,10 +22,7 @@ namespace xrpl { bool AccountDelete::checkExtraFeatures(PreflightContext const& ctx) { - if (ctx.tx.isFieldPresent(sfCredentialIDs) && !ctx.rules.enabled(featureCredentials)) - return false; - - return true; + return !ctx.tx.isFieldPresent(sfCredentialIDs) || ctx.rules.enabled(featureCredentials); } NotTEC @@ -216,7 +213,7 @@ AccountDelete::preclaim(PreclaimContext const& ctx) if (!sleDst) return tecNO_DST; - if ((*sleDst)[sfFlags] & lsfRequireDestTag && !ctx.tx[~sfDestinationTag]) + if ((((*sleDst)[sfFlags] & lsfRequireDestTag) != 0u) && !ctx.tx[~sfDestinationTag]) return tecDST_TAG_NEEDED; // If credentials are provided - check them anyway @@ -228,7 +225,7 @@ AccountDelete::preclaim(PreclaimContext const& ctx) if (!ctx.tx.isFieldPresent(sfCredentialIDs)) { // Check whether the destination account requires deposit authorization. - if (sleDst->getFlags() & lsfDepositAuth) + if ((sleDst->getFlags() & lsfDepositAuth) != 0u) { if (!ctx.view.exists(keylet::depositPreauth(dst, account))) return tecNO_PERMISSION; @@ -313,7 +310,7 @@ AccountDelete::preclaim(PreclaimContext const& ctx) LedgerEntryType const nodeType{safe_cast((*sleItem)[sfLedgerEntryType])}; - if (!nonObligationDeleter(nodeType)) + if (nonObligationDeleter(nodeType) == nullptr) return tecHAS_OBLIGATIONS; // We found a deletable directory entry. Count it. If we find too diff --git a/src/libxrpl/tx/transactors/account/AccountSet.cpp b/src/libxrpl/tx/transactors/account/AccountSet.cpp index 33759c6ec4..d99324f802 100644 --- a/src/libxrpl/tx/transactors/account/AccountSet.cpp +++ b/src/libxrpl/tx/transactors/account/AccountSet.cpp @@ -63,8 +63,8 @@ AccountSet::preflight(PreflightContext const& ctx) // // RequireAuth // - bool bSetRequireAuth = (uTxFlags & tfRequireAuth) || (uSetFlag == asfRequireAuth); - bool bClearRequireAuth = (uTxFlags & tfOptionalAuth) || (uClearFlag == asfRequireAuth); + bool bSetRequireAuth = ((uTxFlags & tfRequireAuth) != 0u) || (uSetFlag == asfRequireAuth); + bool bClearRequireAuth = ((uTxFlags & tfOptionalAuth) != 0u) || (uClearFlag == asfRequireAuth); if (bSetRequireAuth && bClearRequireAuth) { @@ -75,8 +75,9 @@ AccountSet::preflight(PreflightContext const& ctx) // // RequireDestTag // - bool bSetRequireDest = (uTxFlags & tfRequireDestTag) || (uSetFlag == asfRequireDest); - bool bClearRequireDest = (uTxFlags & tfOptionalDestTag) || (uClearFlag == asfRequireDest); + bool bSetRequireDest = ((uTxFlags & tfRequireDestTag) != 0u) || (uSetFlag == asfRequireDest); + bool bClearRequireDest = + ((uTxFlags & tfOptionalDestTag) != 0u) || (uClearFlag == asfRequireDest); if (bSetRequireDest && bClearRequireDest) { @@ -87,8 +88,8 @@ AccountSet::preflight(PreflightContext const& ctx) // // DisallowXRP // - bool bSetDisallowXRP = (uTxFlags & tfDisallowXRP) || (uSetFlag == asfDisallowXRP); - bool bClearDisallowXRP = (uTxFlags & tfAllowXRP) || (uClearFlag == asfDisallowXRP); + bool bSetDisallowXRP = ((uTxFlags & tfDisallowXRP) != 0u) || (uSetFlag == asfDisallowXRP); + bool bClearDisallowXRP = ((uTxFlags & tfAllowXRP) != 0u) || (uClearFlag == asfDisallowXRP); if (bSetDisallowXRP && bClearDisallowXRP) { @@ -101,7 +102,7 @@ AccountSet::preflight(PreflightContext const& ctx) { std::uint32_t uRate = tx.getFieldU32(sfTransferRate); - if (uRate && (uRate < QUALITY_ONE)) + if ((uRate != 0u) && (uRate < QUALITY_ONE)) { JLOG(j.trace()) << "Malformed transaction: Transfer rate too small."; return temBAD_TRANSFER_RATE; @@ -118,7 +119,8 @@ AccountSet::preflight(PreflightContext const& ctx) if (tx.isFieldPresent(sfTickSize)) { auto uTickSize = tx[sfTickSize]; - if (uTickSize && ((uTickSize < Quality::minTickSize) || (uTickSize > Quality::maxTickSize))) + if ((uTickSize != 0u) && + ((uTickSize < Quality::minTickSize) || (uTickSize > Quality::maxTickSize))) { JLOG(j.trace()) << "Malformed transaction: Bad tick size."; return temBAD_TICK_SIZE; @@ -175,7 +177,7 @@ AccountSet::checkPermission(ReadView const& view, STTx const& tx) // AccountSet transaction. If any delegated account is trying to // update the flag on behalf of another account, it is not // authorized. - if (uSetFlag != 0 || uClearFlag != 0 || uTxFlags & tfUniversalMask) + if (uSetFlag != 0 || uClearFlag != 0 || ((uTxFlags & tfUniversalMask) != 0u)) return terNO_DELEGATE_PERMISSION; if (tx.isFieldPresent(sfEmailHash) && !granularPermissions.contains(AccountEmailHashSet)) @@ -215,17 +217,17 @@ AccountSet::preclaim(PreclaimContext const& ctx) std::uint32_t const uSetFlag = ctx.tx.getFieldU32(sfSetFlag); // legacy AccountSet flags - bool bSetRequireAuth = (uTxFlags & tfRequireAuth) || (uSetFlag == asfRequireAuth); + bool bSetRequireAuth = ((uTxFlags & tfRequireAuth) != 0u) || (uSetFlag == asfRequireAuth); // // RequireAuth // - if (bSetRequireAuth && !(uFlagsIn & lsfRequireAuth)) + if (bSetRequireAuth && ((uFlagsIn & lsfRequireAuth) == 0u)) { if (!dirIsEmpty(ctx.view, keylet::ownerDir(id))) { JLOG(ctx.j.trace()) << "Retry: Owner directory not empty."; - return (ctx.flags & tapRETRY) ? TER{terOWNERS} : TER{tecOWNERS}; + return ((ctx.flags & tapRETRY) != 0u) ? TER{terOWNERS} : TER{tecOWNERS}; } } @@ -236,7 +238,7 @@ AccountSet::preclaim(PreclaimContext const& ctx) { if (uSetFlag == asfAllowTrustLineClawback) { - if (uFlagsIn & lsfNoFreeze) + if ((uFlagsIn & lsfNoFreeze) != 0u) { JLOG(ctx.j.trace()) << "Can't set Clawback if NoFreeze is set"; return tecNO_PERMISSION; @@ -251,7 +253,7 @@ AccountSet::preclaim(PreclaimContext const& ctx) else if (uSetFlag == asfNoFreeze) { // Cannot set NoFreeze if clawback is enabled - if (uFlagsIn & lsfAllowTrustLineClawback) + if ((uFlagsIn & lsfAllowTrustLineClawback) != 0u) { JLOG(ctx.j.trace()) << "Can't set NoFreeze if clawback is enabled"; return tecNO_PERMISSION; @@ -278,12 +280,15 @@ AccountSet::doApply() // legacy AccountSet flags std::uint32_t const uTxFlags{tx.getFlags()}; - bool const bSetRequireDest{(uTxFlags & tfRequireDestTag) || (uSetFlag == asfRequireDest)}; - bool const bClearRequireDest{(uTxFlags & tfOptionalDestTag) || (uClearFlag == asfRequireDest)}; - bool const bSetRequireAuth{(uTxFlags & tfRequireAuth) || (uSetFlag == asfRequireAuth)}; - bool const bClearRequireAuth{(uTxFlags & tfOptionalAuth) || (uClearFlag == asfRequireAuth)}; - bool const bSetDisallowXRP{(uTxFlags & tfDisallowXRP) || (uSetFlag == asfDisallowXRP)}; - bool const bClearDisallowXRP{(uTxFlags & tfAllowXRP) || (uClearFlag == asfDisallowXRP)}; + bool const bSetRequireDest{ + ((uTxFlags & tfRequireDestTag) != 0u) || (uSetFlag == asfRequireDest)}; + bool const bClearRequireDest{ + ((uTxFlags & tfOptionalDestTag) != 0u) || (uClearFlag == asfRequireDest)}; + bool const bSetRequireAuth{((uTxFlags & tfRequireAuth) != 0u) || (uSetFlag == asfRequireAuth)}; + bool const bClearRequireAuth{ + ((uTxFlags & tfOptionalAuth) != 0u) || (uClearFlag == asfRequireAuth)}; + bool const bSetDisallowXRP{((uTxFlags & tfDisallowXRP) != 0u) || (uSetFlag == asfDisallowXRP)}; + bool const bClearDisallowXRP{((uTxFlags & tfAllowXRP) != 0u) || (uClearFlag == asfDisallowXRP)}; bool const sigWithMaster{[&tx, &acct = account_]() { auto const spk = tx.getSigningPubKey(); @@ -301,13 +306,13 @@ AccountSet::doApply() // // RequireAuth // - if (bSetRequireAuth && !(uFlagsIn & lsfRequireAuth)) + if (bSetRequireAuth && ((uFlagsIn & lsfRequireAuth) == 0u)) { JLOG(j_.trace()) << "Set RequireAuth."; uFlagsOut |= lsfRequireAuth; } - if (bClearRequireAuth && (uFlagsIn & lsfRequireAuth)) + if (bClearRequireAuth && ((uFlagsIn & lsfRequireAuth) != 0u)) { JLOG(j_.trace()) << "Clear RequireAuth."; uFlagsOut &= ~lsfRequireAuth; @@ -316,13 +321,13 @@ AccountSet::doApply() // // RequireDestTag // - if (bSetRequireDest && !(uFlagsIn & lsfRequireDestTag)) + if (bSetRequireDest && ((uFlagsIn & lsfRequireDestTag) == 0u)) { JLOG(j_.trace()) << "Set lsfRequireDestTag."; uFlagsOut |= lsfRequireDestTag; } - if (bClearRequireDest && (uFlagsIn & lsfRequireDestTag)) + if (bClearRequireDest && ((uFlagsIn & lsfRequireDestTag) != 0u)) { JLOG(j_.trace()) << "Clear lsfRequireDestTag."; uFlagsOut &= ~lsfRequireDestTag; @@ -331,13 +336,13 @@ AccountSet::doApply() // // DisallowXRP // - if (bSetDisallowXRP && !(uFlagsIn & lsfDisallowXRP)) + if (bSetDisallowXRP && ((uFlagsIn & lsfDisallowXRP) == 0u)) { JLOG(j_.trace()) << "Set lsfDisallowXRP."; uFlagsOut |= lsfDisallowXRP; } - if (bClearDisallowXRP && (uFlagsIn & lsfDisallowXRP)) + if (bClearDisallowXRP && ((uFlagsIn & lsfDisallowXRP) != 0u)) { JLOG(j_.trace()) << "Clear lsfDisallowXRP."; uFlagsOut &= ~lsfDisallowXRP; @@ -346,7 +351,7 @@ AccountSet::doApply() // // DisableMaster // - if ((uSetFlag == asfDisableMaster) && !(uFlagsIn & lsfDisableMaster)) + if ((uSetFlag == asfDisableMaster) && ((uFlagsIn & lsfDisableMaster) == 0u)) { if (!sigWithMaster) { @@ -364,7 +369,7 @@ AccountSet::doApply() uFlagsOut |= lsfDisableMaster; } - if ((uClearFlag == asfDisableMaster) && (uFlagsIn & lsfDisableMaster)) + if ((uClearFlag == asfDisableMaster) && ((uFlagsIn & lsfDisableMaster) != 0u)) { JLOG(j_.trace()) << "Clear lsfDisableMaster."; uFlagsOut &= ~lsfDisableMaster; @@ -389,7 +394,7 @@ AccountSet::doApply() // if (uSetFlag == asfNoFreeze) { - if (!sigWithMaster && !(uFlagsIn & lsfDisableMaster)) + if (!sigWithMaster && ((uFlagsIn & lsfDisableMaster) == 0u)) { JLOG(j_.trace()) << "Must use master key to set NoFreeze."; return tecNEED_MASTER_KEY; diff --git a/src/libxrpl/tx/transactors/account/SetRegularKey.cpp b/src/libxrpl/tx/transactors/account/SetRegularKey.cpp index 08175b196f..471da26c88 100644 --- a/src/libxrpl/tx/transactors/account/SetRegularKey.cpp +++ b/src/libxrpl/tx/transactors/account/SetRegularKey.cpp @@ -17,7 +17,7 @@ SetRegularKey::calculateBaseFee(ReadView const& view, STTx const& tx) { auto const sle = view.read(keylet::account(id)); - if (sle && (!(sle->getFlags() & lsfPasswordSpent))) + if (sle && ((sle->getFlags() & lsfPasswordSpent) == 0u)) { // flag is armed and they signed with the right account return XRPAmount{0}; diff --git a/src/libxrpl/tx/transactors/account/SignerListSet.cpp b/src/libxrpl/tx/transactors/account/SignerListSet.cpp index fe9e80d7e0..fcc74a6b2c 100644 --- a/src/libxrpl/tx/transactors/account/SignerListSet.cpp +++ b/src/libxrpl/tx/transactors/account/SignerListSet.cpp @@ -30,7 +30,7 @@ SignerListSet::determineOperation(STTx const& tx, ApplyFlags flags, beast::Journ Operation op = unknown; bool const hasSignerEntries(tx.isFieldPresent(sfSignerEntries)); - if (quorum && hasSignerEntries) + if ((quorum != 0u) && hasSignerEntries) { auto signers = SignerEntries::deserialize(tx, j, "transaction"); @@ -363,7 +363,7 @@ SignerListSet::writeSignersToSLE(SLE::pointer const& ledgerEntry, std::uint32_t } ledgerEntry->setFieldU32(sfSignerQuorum, quorum_); ledgerEntry->setFieldU32(sfSignerListID, DEFAULT_SIGNER_LIST_ID); - if (flags) // Only set flags if they are non-default (default is zero). + if (flags != 0u) // Only set flags if they are non-default (default is zero). ledgerEntry->setFieldU32(sfFlags, flags); // Create the SignerListArray one SignerEntry at a time. diff --git a/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp b/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp index 9ac755cf4d..8c09fefe5a 100644 --- a/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp +++ b/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp @@ -109,7 +109,7 @@ checkAttestationPublicKey( if (accountFromPK == attestationSignerAccount) { // master key - if (sleAttestationSigningAccount->getFieldU32(sfFlags) & lsfDisableMaster) + if ((sleAttestationSigningAccount->getFieldU32(sfFlags) & lsfDisableMaster) != 0u) { JLOG(j.trace()) << "Attempt to add an attestation with " "disabled master key."; @@ -386,7 +386,7 @@ transferHelper( { // Check dst tag and deposit auth - if ((sleDst->getFlags() & lsfRequireDestTag) && !dstTag) + if (((sleDst->getFlags() & lsfRequireDestTag) != 0u) && !dstTag) return tecDST_TAG_NEEDED; // If the destination is the claim owner, and this is a claim @@ -395,7 +395,7 @@ transferHelper( bool const canBypassDepositAuth = dst == claimOwner && depositAuthPolicy == DepositAuthPolicy::dstCanBypass; - if (!canBypassDepositAuth && (sleDst->getFlags() & lsfDepositAuth) && + if (!canBypassDepositAuth && ((sleDst->getFlags() & lsfDepositAuth) != 0u) && !psb.exists(keylet::depositPreauth(dst, src))) { return tecNO_PERMISSION; @@ -1403,7 +1403,7 @@ XChainCreateBridge::preclaim(PreclaimContext const& ctx) // Allowing clawing back funds would break the bridge's invariant that // wrapped funds are always backed by locked funds - if (sleIssuer->getFlags() & lsfAllowTrustLineClawback) + if ((sleIssuer->getFlags() & lsfAllowTrustLineClawback) != 0u) return tecNO_PERMISSION; } @@ -1482,7 +1482,7 @@ BridgeModify::preflight(PreflightContext const& ctx) auto const reward = ctx.tx[~sfSignatureReward]; auto const minAccountCreate = ctx.tx[~sfMinAccountCreateAmount]; auto const bridgeSpec = ctx.tx[sfXChainBridge]; - bool const clearAccountCreate = ctx.tx.getFlags() & tfClearAccountCreateAmount; + bool const clearAccountCreate = (ctx.tx.getFlags() & tfClearAccountCreateAmount) != 0u; if (!reward && !minAccountCreate && !clearAccountCreate) { @@ -1540,7 +1540,7 @@ BridgeModify::doApply() auto const bridgeSpec = ctx_.tx[sfXChainBridge]; auto const reward = ctx_.tx[~sfSignatureReward]; auto const minAccountCreate = ctx_.tx[~sfMinAccountCreateAmount]; - bool const clearAccountCreate = ctx_.tx.getFlags() & tfClearAccountCreateAmount; + bool const clearAccountCreate = (ctx_.tx.getFlags() & tfClearAccountCreateAmount) != 0u; auto const sleAcct = ctx_.view().peek(keylet::account(account)); if (!sleAcct) diff --git a/src/libxrpl/tx/transactors/check/CheckCash.cpp b/src/libxrpl/tx/transactors/check/CheckCash.cpp index 7fa53c7352..2546c2635c 100644 --- a/src/libxrpl/tx/transactors/check/CheckCash.cpp +++ b/src/libxrpl/tx/transactors/check/CheckCash.cpp @@ -82,7 +82,8 @@ CheckCash::preclaim(PreclaimContext const& ctx) return tecNO_ENTRY; } - if ((sleDst->getFlags() & lsfRequireDestTag) && !sleCheck->isFieldPresent(sfDestinationTag)) + if (((sleDst->getFlags() & lsfRequireDestTag) != 0u) && + !sleCheck->isFieldPresent(sfDestinationTag)) { // The tag is basically account-specific information we don't // understand, but we can require someone to fill it in. @@ -155,7 +156,7 @@ CheckCash::preclaim(PreclaimContext const& ctx) return tecNO_ISSUER; } - if (sleIssuer->at(sfFlags) & lsfRequireAuth) + if ((sleIssuer->at(sfFlags) & lsfRequireAuth) != 0u) { auto const sleTrustLine = ctx.view.read(keylet::line(dstId, issuerId, currency)); @@ -172,7 +173,7 @@ CheckCash::preclaim(PreclaimContext const& ctx) bool const canonical_gt(dstId > issuerId); bool const is_authorized( - sleTrustLine->at(sfFlags) & (canonical_gt ? lsfLowAuth : lsfHighAuth)); + (sleTrustLine->at(sfFlags) & (canonical_gt ? lsfLowAuth : lsfHighAuth)) != 0u); if (!is_authorized) { diff --git a/src/libxrpl/tx/transactors/check/CheckCreate.cpp b/src/libxrpl/tx/transactors/check/CheckCreate.cpp index 50554a1beb..1aa4ac15ba 100644 --- a/src/libxrpl/tx/transactors/check/CheckCreate.cpp +++ b/src/libxrpl/tx/transactors/check/CheckCreate.cpp @@ -63,7 +63,7 @@ CheckCreate::preclaim(PreclaimContext const& ctx) auto const flags = sleDst->getFlags(); // Check if the destination has disallowed incoming checks - if (flags & lsfDisallowIncomingCheck) + if ((flags & lsfDisallowIncomingCheck) != 0u) return tecNO_PERMISSION; // Pseudo-accounts cannot cash checks. Note, this is not amendment-gated @@ -73,7 +73,7 @@ CheckCreate::preclaim(PreclaimContext const& ctx) if (isPseudoAccount(sleDst)) return tecNO_PERMISSION; - if ((flags & lsfRequireDestTag) && !ctx.tx.isFieldPresent(sfDestinationTag)) + if (((flags & lsfRequireDestTag) != 0u) && !ctx.tx.isFieldPresent(sfDestinationTag)) { // The tag is basically account-specific information we don't // understand, but we can require someone to fill it in. diff --git a/src/libxrpl/tx/transactors/credentials/CredentialAccept.cpp b/src/libxrpl/tx/transactors/credentials/CredentialAccept.cpp index c4842b54e4..9c0018a647 100644 --- a/src/libxrpl/tx/transactors/credentials/CredentialAccept.cpp +++ b/src/libxrpl/tx/transactors/credentials/CredentialAccept.cpp @@ -60,7 +60,7 @@ CredentialAccept::preclaim(PreclaimContext const& ctx) return tecNO_ENTRY; } - if (sleCred->getFieldU32(sfFlags) & lsfAccepted) + if ((sleCred->getFieldU32(sfFlags) & lsfAccepted) != 0u) { JLOG(ctx.j.warn()) << "Credential already accepted: " << to_string(subject) << ", " << to_string(issuer) << ", " << credType; diff --git a/src/libxrpl/tx/transactors/dex/AMMClawback.cpp b/src/libxrpl/tx/transactors/dex/AMMClawback.cpp index a5fda15033..b8f4fe4b1b 100644 --- a/src/libxrpl/tx/transactors/dex/AMMClawback.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMClawback.cpp @@ -40,7 +40,7 @@ AMMClawback::preflight(PreflightContext const& ctx) auto const flags = ctx.tx.getFlags(); - if (flags & tfClawTwoAssets && asset.account != asset2.account) + if (((flags & tfClawTwoAssets) != 0u) && asset.account != asset2.account) { JLOG(ctx.j.trace()) << "AMMClawback: tfClawTwoAssets can only be enabled when two " "assets in the AMM pool are both issued by the issuer"; @@ -90,7 +90,8 @@ AMMClawback::preclaim(PreclaimContext const& ctx) // If AllowTrustLineClawback is not set or NoFreeze is set, return no // permission - if (!(issuerFlagsIn & lsfAllowTrustLineClawback) || (issuerFlagsIn & lsfNoFreeze)) + if (((issuerFlagsIn & lsfAllowTrustLineClawback) == 0u) || + ((issuerFlagsIn & lsfNoFreeze) != 0u)) return tecNO_PERMISSION; return tesSUCCESS; @@ -215,7 +216,7 @@ AMMClawback::applyGuts(Sandbox& sb) return tecINTERNAL; // LCOV_EXCL_LINE auto const flags = ctx_.tx.getFlags(); - if (flags & tfClawTwoAssets) + if ((flags & tfClawTwoAssets) != 0u) return rippleCredit(sb, holder, issuer, *amount2Withdraw, true, j_); return tesSUCCESS; diff --git a/src/libxrpl/tx/transactors/dex/AMMDeposit.cpp b/src/libxrpl/tx/transactors/dex/AMMDeposit.cpp index cae83ccef1..eb3e61e80b 100644 --- a/src/libxrpl/tx/transactors/dex/AMMDeposit.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMDeposit.cpp @@ -44,35 +44,35 @@ AMMDeposit::preflight(PreflightContext const& ctx) JLOG(ctx.j.debug()) << "AMM Deposit: invalid flags."; return temMALFORMED; } - if (flags & tfLPToken) + if ((flags & tfLPToken) != 0u) { // if included then both amount and amount2 are deposit min if (!lpTokens || ePrice || (amount && !amount2) || (!amount && amount2) || tradingFee) return temMALFORMED; } - else if (flags & tfSingleAsset) + else if ((flags & tfSingleAsset) != 0u) { // if included then lpTokens is deposit min if (!amount || amount2 || ePrice || tradingFee) return temMALFORMED; } - else if (flags & tfTwoAsset) + else if ((flags & tfTwoAsset) != 0u) { // if included then lpTokens is deposit min if (!amount || !amount2 || ePrice || tradingFee) return temMALFORMED; } - else if (flags & tfOneAssetLPToken) + else if ((flags & tfOneAssetLPToken) != 0u) { if (!amount || !lpTokens || amount2 || ePrice || tradingFee) return temMALFORMED; } - else if (flags & tfLimitLPToken) + else if ((flags & tfLimitLPToken) != 0u) { if (!amount || !ePrice || lpTokens || amount2 || tradingFee) return temMALFORMED; } - else if (flags & tfTwoAssetIfEmpty) + else if ((flags & tfTwoAssetIfEmpty) != 0u) { if (!amount || !amount2 || ePrice || lpTokens) return temMALFORMED; @@ -156,7 +156,7 @@ AMMDeposit::preclaim(PreclaimContext const& ctx) if (!expected) return expected.error(); // LCOV_EXCL_LINE auto const [amountBalance, amount2Balance, lptAMMBalance] = *expected; - if (ctx.tx.getFlags() & tfTwoAssetIfEmpty) + if ((ctx.tx.getFlags() & tfTwoAssetIfEmpty) != 0u) { if (lptAMMBalance != beast::zero) return tecAMM_NOT_EMPTY; @@ -283,7 +283,7 @@ AMMDeposit::preclaim(PreclaimContext const& ctx) }; // amount and amount2 are deposit min in case of tfLPToken - if (!(ctx.tx.getFlags() & tfLPToken)) + if ((ctx.tx.getFlags() & tfLPToken) == 0u) { if (auto const ter = checkAmount(amount, true)) return ter; diff --git a/src/libxrpl/tx/transactors/dex/AMMWithdraw.cpp b/src/libxrpl/tx/transactors/dex/AMMWithdraw.cpp index b822ff6b84..7c87d53ea0 100644 --- a/src/libxrpl/tx/transactors/dex/AMMWithdraw.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMWithdraw.cpp @@ -42,37 +42,37 @@ AMMWithdraw::preflight(PreflightContext const& ctx) JLOG(ctx.j.debug()) << "AMM Withdraw: invalid flags."; return temMALFORMED; } - if (flags & tfLPToken) + if ((flags & tfLPToken) != 0u) { if (!lpTokens || amount || amount2 || ePrice) return temMALFORMED; } - else if (flags & tfWithdrawAll) + else if ((flags & tfWithdrawAll) != 0u) { if (lpTokens || amount || amount2 || ePrice) return temMALFORMED; } - else if (flags & tfOneAssetWithdrawAll) + else if ((flags & tfOneAssetWithdrawAll) != 0u) { if (!amount || lpTokens || amount2 || ePrice) return temMALFORMED; } - else if (flags & tfSingleAsset) + else if ((flags & tfSingleAsset) != 0u) { if (!amount || lpTokens || amount2 || ePrice) return temMALFORMED; } - else if (flags & tfTwoAsset) + else if ((flags & tfTwoAsset) != 0u) { if (!amount || !amount2 || lpTokens || ePrice) return temMALFORMED; } - else if (flags & tfOneAssetLPToken) + else if ((flags & tfOneAssetLPToken) != 0u) { if (!amount || !lpTokens || amount2 || ePrice) return temMALFORMED; } - else if (flags & tfLimitLPToken) + else if ((flags & tfLimitLPToken) != 0u) { if (!amount || !ePrice || lpTokens || amount2) return temMALFORMED; @@ -104,7 +104,7 @@ AMMWithdraw::preflight(PreflightContext const& ctx) if (auto const res = invalidAMMAmount( *amount, std::make_optional(std::make_pair(asset, asset2)), - (flags & (tfOneAssetWithdrawAll | tfOneAssetLPToken)) || ePrice)) + ((flags & (tfOneAssetWithdrawAll | tfOneAssetLPToken)) != 0u) || ePrice)) { JLOG(ctx.j.debug()) << "AMM Withdraw: invalid Asset1Out"; return res; @@ -139,7 +139,7 @@ tokensWithdraw( std::optional const& tokensIn, std::uint32_t flags) { - if (flags & (tfWithdrawAll | tfOneAssetWithdrawAll)) + if ((flags & (tfWithdrawAll | tfOneAssetWithdrawAll)) != 0u) return lpTokens; return tokensIn; } @@ -248,7 +248,7 @@ AMMWithdraw::preclaim(PreclaimContext const& ctx) return temBAD_AMM_TOKENS; } - if (ctx.tx.getFlags() & (tfLPToken | tfWithdrawAll)) + if ((ctx.tx.getFlags() & (tfLPToken | tfWithdrawAll)) != 0u) { if (auto const ter = checkAmount(amountBalance, amountBalance)) return ter; @@ -1018,7 +1018,7 @@ AMMWithdraw::singleWithdrawEPrice( WithdrawAll AMMWithdraw::isWithdrawAll(STTx const& tx) { - if (tx[sfFlags] & (tfWithdrawAll | tfOneAssetWithdrawAll)) + if ((tx[sfFlags] & (tfWithdrawAll | tfOneAssetWithdrawAll)) != 0u) return WithdrawAll::Yes; return WithdrawAll::No; } diff --git a/src/libxrpl/tx/transactors/dex/OfferCancel.cpp b/src/libxrpl/tx/transactors/dex/OfferCancel.cpp index 9d60347778..a9e7cac85a 100644 --- a/src/libxrpl/tx/transactors/dex/OfferCancel.cpp +++ b/src/libxrpl/tx/transactors/dex/OfferCancel.cpp @@ -9,7 +9,7 @@ namespace xrpl { NotTEC OfferCancel::preflight(PreflightContext const& ctx) { - if (!ctx.tx[sfOfferSequence]) + if (ctx.tx[sfOfferSequence] == 0u) { JLOG(ctx.j.trace()) << "OfferCancel::preflight: missing sequence"; return temBAD_SEQUENCE; diff --git a/src/libxrpl/tx/transactors/dex/OfferCreate.cpp b/src/libxrpl/tx/transactors/dex/OfferCreate.cpp index d52fa94877..17dd2d2c57 100644 --- a/src/libxrpl/tx/transactors/dex/OfferCreate.cpp +++ b/src/libxrpl/tx/transactors/dex/OfferCreate.cpp @@ -30,10 +30,7 @@ OfferCreate::makeTxConsequences(PreflightContext const& ctx) bool OfferCreate::checkExtraFeatures(PreflightContext const& ctx) { - if (ctx.tx.isFieldPresent(sfDomainID) && !ctx.rules.enabled(featurePermissionedDEX)) - return false; - - return true; + return !ctx.tx.isFieldPresent(sfDomainID) || ctx.rules.enabled(featurePermissionedDEX); } std::uint32_t @@ -59,8 +56,8 @@ OfferCreate::preflight(PreflightContext const& ctx) if (tx.isFlag(tfHybrid) && !tx.isFieldPresent(sfDomainID)) return temINVALID_FLAG; - bool const bImmediateOrCancel(uTxFlags & tfImmediateOrCancel); - bool const bFillOrKill(uTxFlags & tfFillOrKill); + bool const bImmediateOrCancel((uTxFlags & tfImmediateOrCancel) != 0u); + bool const bFillOrKill((uTxFlags & tfFillOrKill) != 0u); if (bImmediateOrCancel && bFillOrKill) { @@ -215,7 +212,7 @@ OfferCreate::checkAcceptAsset( JLOG(j.debug()) << "delay: can't receive IOUs from non-existent issuer: " << to_string(issue.account); - return (flags & tapRETRY) ? TER{terNO_ACCOUNT} : TER{tecNO_ISSUER}; + return ((flags & tapRETRY) != 0u) ? TER{terNO_ACCOUNT} : TER{tecNO_ISSUER}; } // An account cannot create a trustline to itself, so no line can exist @@ -224,13 +221,13 @@ OfferCreate::checkAcceptAsset( if (issue.account == id) return tesSUCCESS; - if ((*issuerAccount)[sfFlags] & lsfRequireAuth) + if (((*issuerAccount)[sfFlags] & lsfRequireAuth) != 0u) { auto const trustLine = view.read(keylet::line(id, issue.account, issue.currency)); if (!trustLine) { - return (flags & tapRETRY) ? TER{terNO_LINE} : TER{tecNO_LINE}; + return ((flags & tapRETRY) != 0u) ? TER{terNO_LINE} : TER{tecNO_LINE}; } // Entries have a canonical representation, determined by a @@ -238,13 +235,14 @@ OfferCreate::checkAcceptAsset( // ordering. Determine which entry we need to access. bool const canonical_gt(id > issue.account); - bool const is_authorized((*trustLine)[sfFlags] & (canonical_gt ? lsfLowAuth : lsfHighAuth)); + bool const is_authorized( + ((*trustLine)[sfFlags] & (canonical_gt ? lsfLowAuth : lsfHighAuth)) != 0u); if (!is_authorized) { JLOG(j.debug()) << "delay: can't receive IOUs from issuer without auth."; - return (flags & tapRETRY) ? TER{terNO_AUTH} : TER{tecNO_AUTH}; + return ((flags & tapRETRY) != 0u) ? TER{terNO_AUTH} : TER{tecNO_AUTH}; } } @@ -257,7 +255,7 @@ OfferCreate::checkAcceptAsset( // There's no difference which side enacted deep freeze, accepting // tokens shouldn't be possible. - bool const deepFrozen = (*trustLine)[sfFlags] & (lsfLowDeepFreeze | lsfHighDeepFreeze); + bool const deepFrozen = ((*trustLine)[sfFlags] & (lsfLowDeepFreeze | lsfHighDeepFreeze)) != 0u; if (deepFrozen) { @@ -313,7 +311,7 @@ OfferCreate::flowCross( // If we're creating a passive offer adjust the threshold so we only // cross offers that have a better quality than this one. std::uint32_t const txFlags = ctx_.tx.getFlags(); - if (txFlags & tfPassive) + if ((txFlags & tfPassive) != 0u) ++threshold; // Don't send more than our balance. @@ -334,7 +332,7 @@ OfferCreate::flowCross( // Special handling for the tfSell flag. STAmount deliver = takerAmount.out; OfferCrossing offerCrossing = OfferCrossing::yes; - if (txFlags & tfSell) + if ((txFlags & tfSell) != 0u) { offerCrossing = OfferCrossing::sell; // We are selling, so we will accept *more* than the offer @@ -362,9 +360,9 @@ OfferCreate::flowCross( account_, account_, paths, - true, // default path - !(txFlags & tfFillOrKill), // partial payment - true, // owner pays transfer fee + true, // default path + (txFlags & tfFillOrKill) == 0u, // partial payment + true, // owner pays transfer fee offerCrossing, threshold, sendMax, @@ -398,7 +396,7 @@ OfferCreate::flowCross( { STAmount const rate{Quality{takerAmount.out, takerAmount.in}.rate()}; - if (txFlags & tfSell) + if ((txFlags & tfSell) != 0u) { // If selling then scale the new out amount based on how // much we sold during crossing. This preserves the offer @@ -517,11 +515,11 @@ OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) std::uint32_t const uTxFlags = ctx_.tx.getFlags(); - bool const bPassive(uTxFlags & tfPassive); - bool const bImmediateOrCancel(uTxFlags & tfImmediateOrCancel); - bool const bFillOrKill(uTxFlags & tfFillOrKill); - bool const bSell(uTxFlags & tfSell); - bool const bHybrid(uTxFlags & tfHybrid); + bool const bPassive((uTxFlags & tfPassive) != 0u); + bool const bImmediateOrCancel((uTxFlags & tfImmediateOrCancel) != 0u); + bool const bFillOrKill((uTxFlags & tfFillOrKill) != 0u); + bool const bSell((uTxFlags & tfSell) != 0u); + bool const bHybrid((uTxFlags & tfHybrid) != 0u); auto saTakerPays = ctx_.tx[sfTakerPays]; auto saTakerGets = ctx_.tx[sfTakerGets]; diff --git a/src/libxrpl/tx/transactors/escrow/EscrowCreate.cpp b/src/libxrpl/tx/transactors/escrow/EscrowCreate.cpp index 8b823de160..634b9b3a06 100644 --- a/src/libxrpl/tx/transactors/escrow/EscrowCreate.cpp +++ b/src/libxrpl/tx/transactors/escrow/EscrowCreate.cpp @@ -353,8 +353,7 @@ escrowLockApplyHelper( if (issuer == sender) return tecINTERNAL; // LCOV_EXCL_LINE - auto const ter = rippleCredit( - view, sender, issuer, amount, amount.holds() ? false : true, journal); + auto const ter = rippleCredit(view, sender, issuer, amount, !amount.holds(), journal); if (!isTesSuccess(ter)) return ter; // LCOV_EXCL_LINE return tesSUCCESS; @@ -415,7 +414,7 @@ EscrowCreate::doApply() auto const sled = ctx_.view().read(keylet::account(ctx_.tx[sfDestination])); if (!sled) return tecNO_DST; // LCOV_EXCL_LINE - if (((*sled)[sfFlags] & lsfRequireDestTag) && !ctx_.tx[~sfDestinationTag]) + if ((((*sled)[sfFlags] & lsfRequireDestTag) != 0u) && !ctx_.tx[~sfDestinationTag]) return tecDST_TAG_NEEDED; } diff --git a/src/libxrpl/tx/transactors/lending/LoanManage.cpp b/src/libxrpl/tx/transactors/lending/LoanManage.cpp index d507ba5499..6cc9df1aab 100644 --- a/src/libxrpl/tx/transactors/lending/LoanManage.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanManage.cpp @@ -26,7 +26,7 @@ LoanManage::preflight(PreflightContext const& ctx) return temINVALID; // Flags are mutually exclusive - if (auto const flagField = ctx.tx[~sfFlags]; flagField && *flagField) + if (auto const flagField = ctx.tx[~sfFlags]; flagField && (*flagField != 0u)) { auto const flags = *flagField & tfUniversalMask; if ((flags & (flags - 1)) != 0) diff --git a/src/libxrpl/tx/transactors/nft/NFTokenBurn.cpp b/src/libxrpl/tx/transactors/nft/NFTokenBurn.cpp index 6d9ee56c51..5a31e35470 100644 --- a/src/libxrpl/tx/transactors/nft/NFTokenBurn.cpp +++ b/src/libxrpl/tx/transactors/nft/NFTokenBurn.cpp @@ -29,7 +29,7 @@ NFTokenBurn::preclaim(PreclaimContext const& ctx) // do so if the token is marked as burnable. if (auto const account = ctx.tx[sfAccount]; owner != account) { - if (!(nft::getFlags(ctx.tx[sfNFTokenID]) & nft::flagBurnable)) + if ((nft::getFlags(ctx.tx[sfNFTokenID]) & nft::flagBurnable) == 0) return tecNO_PERMISSION; if (auto const issuer = nft::getIssuer(ctx.tx[sfNFTokenID]); issuer != account) diff --git a/src/libxrpl/tx/transactors/nft/NFTokenCreateOffer.cpp b/src/libxrpl/tx/transactors/nft/NFTokenCreateOffer.cpp index eaca8b3380..f5fdc89550 100644 --- a/src/libxrpl/tx/transactors/nft/NFTokenCreateOffer.cpp +++ b/src/libxrpl/tx/transactors/nft/NFTokenCreateOffer.cpp @@ -45,7 +45,7 @@ NFTokenCreateOffer::preclaim(PreclaimContext const& ctx) std::uint32_t const txFlags = ctx.tx.getFlags(); if (!nft::findToken( - ctx.view, ctx.tx[(txFlags & tfSellNFToken) ? sfAccount : sfOwner], nftokenID)) + ctx.view, ctx.tx[((txFlags & tfSellNFToken) != 0u) ? sfAccount : sfOwner], nftokenID)) return tecNO_ENTRY; // Use implementation shared with NFTokenMint diff --git a/src/libxrpl/tx/transactors/nft/NFTokenModify.cpp b/src/libxrpl/tx/transactors/nft/NFTokenModify.cpp index 1b2c9c2ab0..8ccd4e9552 100644 --- a/src/libxrpl/tx/transactors/nft/NFTokenModify.cpp +++ b/src/libxrpl/tx/transactors/nft/NFTokenModify.cpp @@ -30,7 +30,7 @@ NFTokenModify::preclaim(PreclaimContext const& ctx) return tecNO_ENTRY; // Check if the NFT is mutable - if (!(nft::getFlags(ctx.tx[sfNFTokenID]) & nft::flagMutable)) + if ((nft::getFlags(ctx.tx[sfNFTokenID]) & nft::flagMutable) == 0) return tecNO_PERMISSION; // Verify permissions for the issuer diff --git a/src/libxrpl/tx/transactors/nft/NFTokenUtils.cpp b/src/libxrpl/tx/transactors/nft/NFTokenUtils.cpp index f7c12b5488..84826314e7 100644 --- a/src/libxrpl/tx/transactors/nft/NFTokenUtils.cpp +++ b/src/libxrpl/tx/transactors/nft/NFTokenUtils.cpp @@ -601,7 +601,7 @@ removeTokenOffersWithLimit(ApplyView& view, Keylet const& directory, std::size_t if (maxDeletableOffers == deletedOffersCount) break; } - } while (pageIndex.value_or(0) && maxDeletableOffers != deletedOffersCount); + } while ((pageIndex.value_or(0) != 0u) && maxDeletableOffers != deletedOffersCount); return deletedOffersCount; } @@ -647,8 +647,8 @@ deleteTokenOffer(ApplyView& view, std::shared_ptr const& offer) auto const nftokenID = (*offer)[sfNFTokenID]; if (!view.dirRemove( - ((*offer)[sfFlags] & lsfSellNFToken) ? keylet::nft_sells(nftokenID) - : keylet::nft_buys(nftokenID), + (((*offer)[sfFlags] & lsfSellNFToken) != 0u) ? keylet::nft_sells(nftokenID) + : keylet::nft_buys(nftokenID), (*offer)[sfNFTokenOfferNode], offer->key(), false)) @@ -799,7 +799,7 @@ tokenOfferCreatePreflight( if (!isXRP(amount)) { - if (nftFlags & nft::flagOnlyXRP) + if ((nftFlags & nft::flagOnlyXRP) != 0) return temBAD_AMOUNT; if (!amount) @@ -808,7 +808,7 @@ tokenOfferCreatePreflight( // If this is an offer to buy, you must offer something; if it's an // offer to sell, you can ask for nothing. - bool const isSellOffer = txFlags & tfSellNFToken; + bool const isSellOffer = (txFlags & tfSellNFToken) != 0u; if (!isSellOffer && !amount) return temBAD_AMOUNT; @@ -844,7 +844,7 @@ tokenOfferCreatePreclaim( std::optional const& owner, std::uint32_t txFlags) { - if (!(nftFlags & nft::flagCreateTrustLines) && !amount.native() && xferFee) + if (((nftFlags & nft::flagCreateTrustLines) == 0) && !amount.native() && (xferFee != 0u)) { if (!view.exists(keylet::account(nftIssuer))) return tecNO_ISSUER; @@ -866,7 +866,7 @@ tokenOfferCreatePreclaim( return tecFROZEN; } - if (nftIssuer != acctID && !(nftFlags & nft::flagTransferable)) + if (nftIssuer != acctID && ((nftFlags & nft::flagTransferable) == 0)) { auto const root = view.read(keylet::account(nftIssuer)); XRPL_ASSERT(root, "xrpl::nft::tokenOfferCreatePreclaim : non-null account"); @@ -899,7 +899,7 @@ tokenOfferCreatePreclaim( return tecNO_DST; // check if the destination has disallowed incoming offers - if (sleDst->getFlags() & lsfDisallowIncomingNFTokenOffer) + if ((sleDst->getFlags() & lsfDisallowIncomingNFTokenOffer) != 0u) return tecNO_PERMISSION; } @@ -912,7 +912,7 @@ tokenOfferCreatePreclaim( if (!sleOwner) return tecNO_TARGET; - if (sleOwner->getFlags() & lsfDisallowIncomingNFTokenOffer) + if ((sleOwner->getFlags() & lsfDisallowIncomingNFTokenOffer) != 0u) return tecNO_PERMISSION; } @@ -960,7 +960,7 @@ tokenOfferCreateApply( if (!ownerNode) return tecDIR_FULL; // LCOV_EXCL_LINE - bool const isSellOffer = txFlags & tfSellNFToken; + bool const isSellOffer = (txFlags & tfSellNFToken) != 0u; // Token offers are also added to the token's buy or sell offer // directory @@ -1094,7 +1094,8 @@ checkTrustlineDeepFrozen( // There's no difference which side enacted deep freeze, accepting // tokens shouldn't be possible. - bool const deepFrozen = (*trustLine)[sfFlags] & (lsfLowDeepFreeze | lsfHighDeepFreeze); + bool const deepFrozen = + ((*trustLine)[sfFlags] & (lsfLowDeepFreeze | lsfHighDeepFreeze)) != 0u; if (deepFrozen) { diff --git a/src/libxrpl/tx/transactors/payment/DepositPreauth.cpp b/src/libxrpl/tx/transactors/payment/DepositPreauth.cpp index 60b8dcd823..0f4681a3ad 100644 --- a/src/libxrpl/tx/transactors/payment/DepositPreauth.cpp +++ b/src/libxrpl/tx/transactors/payment/DepositPreauth.cpp @@ -19,10 +19,7 @@ DepositPreauth::checkExtraFeatures(PreflightContext const& ctx) bool const unauthArrPresent = ctx.tx.isFieldPresent(sfUnauthorizeCredentials); bool const authCredPresent = authArrPresent || unauthArrPresent; - if (authCredPresent && !ctx.rules.enabled(featureCredentials)) - return false; - - return true; + return !authCredPresent || ctx.rules.enabled(featureCredentials); } NotTEC @@ -46,7 +43,7 @@ DepositPreauth::preflight(PreflightContext const& ctx) return temMALFORMED; } - if (authPresent) + if (authPresent != 0) { // Make sure that the passed account is valid. AccountID const& target(optAuth ? *optAuth : *optUnauth); diff --git a/src/libxrpl/tx/transactors/payment/Payment.cpp b/src/libxrpl/tx/transactors/payment/Payment.cpp index 38765016b5..c95afc33f9 100644 --- a/src/libxrpl/tx/transactors/payment/Payment.cpp +++ b/src/libxrpl/tx/transactors/payment/Payment.cpp @@ -91,9 +91,9 @@ Payment::preflight(PreflightContext const& ctx) if (mptDirect && ctx.tx.isFieldPresent(sfPaths)) return temMALFORMED; - bool const partialPaymentAllowed = txFlags & tfPartialPayment; - bool const limitQuality = txFlags & tfLimitQuality; - bool const defaultPathsAllowed = !(txFlags & tfNoRippleDirect); + bool const partialPaymentAllowed = (txFlags & tfPartialPayment) != 0u; + bool const limitQuality = (txFlags & tfLimitQuality) != 0u; + bool const defaultPathsAllowed = (txFlags & tfNoRippleDirect) == 0u; bool const hasPaths = tx.isFieldPresent(sfPaths); bool const hasMax = tx.isFieldPresent(sfSendMax); @@ -269,7 +269,7 @@ Payment::preclaim(PreclaimContext const& ctx) { // Ripple if source or destination is non-native or if there are paths. std::uint32_t const txFlags = ctx.tx.getFlags(); - bool const partialPaymentAllowed = txFlags & tfPartialPayment; + bool const partialPaymentAllowed = (txFlags & tfPartialPayment) != 0u; auto const hasPaths = ctx.tx.isFieldPresent(sfPaths); auto const sendMax = ctx.tx[~sfSendMax]; @@ -314,7 +314,9 @@ Payment::preclaim(PreclaimContext const& ctx) return tecNO_DST_INSUF_XRP; } } - else if ((sleDst->getFlags() & lsfRequireDestTag) && !ctx.tx.isFieldPresent(sfDestinationTag)) + else if ( + ((sleDst->getFlags() & lsfRequireDestTag) != 0u) && + !ctx.tx.isFieldPresent(sfDestinationTag)) { // The tag is basically account-specific information we don't // understand, but we can require someone to fill it in. @@ -363,9 +365,9 @@ Payment::doApply() // Ripple if source or destination is non-native or if there are paths. std::uint32_t const txFlags = ctx_.tx.getFlags(); - bool const partialPaymentAllowed = txFlags & tfPartialPayment; - bool const limitQuality = txFlags & tfLimitQuality; - bool const defaultPathsAllowed = !(txFlags & tfNoRippleDirect); + bool const partialPaymentAllowed = (txFlags & tfPartialPayment) != 0u; + bool const limitQuality = (txFlags & tfLimitQuality) != 0u; + bool const defaultPathsAllowed = (txFlags & tfNoRippleDirect) == 0u; auto const hasPaths = ctx_.tx.isFieldPresent(sfPaths); auto const sendMax = ctx_.tx[~sfSendMax]; @@ -619,7 +621,7 @@ Payment::doApply() sleDst->setFieldAmount(sfBalance, sleDst->getFieldAmount(sfBalance) + dstAmount); // Re-arm the password change fee if we can and need to. - if ((sleDst->getFlags() & lsfPasswordSpent)) + if ((sleDst->getFlags() & lsfPasswordSpent) != 0u) sleDst->clearFlag(lsfPasswordSpent); return tesSUCCESS; diff --git a/src/libxrpl/tx/transactors/payment_channel/PaymentChannelClaim.cpp b/src/libxrpl/tx/transactors/payment_channel/PaymentChannelClaim.cpp index 6ba489bbc3..dccaf8f071 100644 --- a/src/libxrpl/tx/transactors/payment_channel/PaymentChannelClaim.cpp +++ b/src/libxrpl/tx/transactors/payment_channel/PaymentChannelClaim.cpp @@ -42,7 +42,7 @@ PaymentChannelClaim::preflight(PreflightContext const& ctx) { auto const flags = ctx.tx.getFlags(); - if ((flags & tfClose) && (flags & tfRenew)) + if (((flags & tfClose) != 0u) && ((flags & tfRenew) != 0u)) return temMALFORMED; } @@ -158,7 +158,7 @@ PaymentChannelClaim::doApply() ctx_.view().update(slep); } - if (ctx_.tx.getFlags() & tfRenew) + if ((ctx_.tx.getFlags() & tfRenew) != 0u) { if (src != txAccount) return tecNO_PERMISSION; @@ -166,7 +166,7 @@ PaymentChannelClaim::doApply() ctx_.view().update(slep); } - if (ctx_.tx.getFlags() & tfClose) + if ((ctx_.tx.getFlags() & tfClose) != 0u) { // Channel will close immediately if dry or the receiver closes if (dst == txAccount || (*slep)[sfBalance] == (*slep)[sfAmount]) diff --git a/src/libxrpl/tx/transactors/payment_channel/PaymentChannelCreate.cpp b/src/libxrpl/tx/transactors/payment_channel/PaymentChannelCreate.cpp index 3f7e1e1814..c12169fc0e 100644 --- a/src/libxrpl/tx/transactors/payment_channel/PaymentChannelCreate.cpp +++ b/src/libxrpl/tx/transactors/payment_channel/PaymentChannelCreate.cpp @@ -85,10 +85,10 @@ PaymentChannelCreate::preclaim(PreclaimContext const& ctx) auto const flags = sled->getFlags(); // Check if they have disallowed incoming payment channels - if (flags & lsfDisallowIncomingPayChan) + if ((flags & lsfDisallowIncomingPayChan) != 0u) return tecNO_PERMISSION; - if ((flags & lsfRequireDestTag) && !ctx.tx[~sfDestinationTag]) + if (((flags & lsfRequireDestTag) != 0u) && !ctx.tx[~sfDestinationTag]) return tecDST_TAG_NEEDED; // Pseudo-accounts cannot receive payment channels, other than native diff --git a/src/libxrpl/tx/transactors/system/Batch.cpp b/src/libxrpl/tx/transactors/system/Batch.cpp index b2a111a182..b8b0d3234a 100644 --- a/src/libxrpl/tx/transactors/system/Batch.cpp +++ b/src/libxrpl/tx/transactors/system/Batch.cpp @@ -270,7 +270,7 @@ Batch::preflight(PreflightContext const& ctx) return temINVALID_INNER_BATCH; } - if (!(stx.getFlags() & tfInnerBatchTxn)) + if ((stx.getFlags() & tfInnerBatchTxn) == 0u) { JLOG(ctx.j.debug()) << "BatchTrace[" << parentBatchId << "]: " << "inner txn must have the tfInnerBatchTxn flag. " @@ -335,7 +335,7 @@ Batch::preflight(PreflightContext const& ctx) } // Duplicate sequence and ticket checks - if (flags & (tfAllOrNothing | tfUntilFailure)) + if ((flags & (tfAllOrNothing | tfUntilFailure)) != 0u) { if (auto const seq = stx.getFieldU32(sfSequence); seq != 0) { diff --git a/src/libxrpl/tx/transactors/system/Change.cpp b/src/libxrpl/tx/transactors/system/Change.cpp index 5b0a431004..b863f06cad 100644 --- a/src/libxrpl/tx/transactors/system/Change.cpp +++ b/src/libxrpl/tx/transactors/system/Change.cpp @@ -292,7 +292,7 @@ Change::applyUNLModify() return tefFAILURE; } - bool const disabling = ctx_.tx.getFieldU8(sfUNLModifyDisabling); + bool const disabling = ctx_.tx.getFieldU8(sfUNLModifyDisabling) != 0u; auto const seq = ctx_.tx.getFieldU32(sfLedgerSequence); if (seq != view().seq()) { diff --git a/src/libxrpl/tx/transactors/token/Clawback.cpp b/src/libxrpl/tx/transactors/token/Clawback.cpp index e8ba3cc0c5..57175ba427 100644 --- a/src/libxrpl/tx/transactors/token/Clawback.cpp +++ b/src/libxrpl/tx/transactors/token/Clawback.cpp @@ -90,7 +90,8 @@ preclaimHelper( // If AllowTrustLineClawback is not set or NoFreeze is set, return no // permission - if (!(issuerFlagsIn & lsfAllowTrustLineClawback) || (issuerFlagsIn & lsfNoFreeze)) + if (((issuerFlagsIn & lsfAllowTrustLineClawback) == 0u) || + ((issuerFlagsIn & lsfNoFreeze) != 0u)) return tecNO_PERMISSION; auto const sleRippleState = @@ -138,7 +139,7 @@ preclaimHelper( if (!sleIssuance) return tecOBJECT_NOT_FOUND; - if (!((*sleIssuance)[sfFlags] & lsfMPTCanClawback)) + if (((*sleIssuance)[sfFlags] & lsfMPTCanClawback) == 0u) return tecNO_PERMISSION; if (sleIssuance->getAccountID(sfIssuer) != issuer) diff --git a/src/libxrpl/tx/transactors/token/MPTokenAuthorize.cpp b/src/libxrpl/tx/transactors/token/MPTokenAuthorize.cpp index 77551b372b..464ede9de7 100644 --- a/src/libxrpl/tx/transactors/token/MPTokenAuthorize.cpp +++ b/src/libxrpl/tx/transactors/token/MPTokenAuthorize.cpp @@ -48,7 +48,7 @@ MPTokenAuthorize::preclaim(PreclaimContext const& ctx) // before fetching the MPTIssuance object. // if holder wants to delete/unauthorize a mpt - if (ctx.tx.getFlags() & tfMPTUnauthorize) + if ((ctx.tx.getFlags() & tfMPTUnauthorize) != 0u) { if (!sleMpt) return tecOBJECT_NOT_FOUND; @@ -116,7 +116,7 @@ MPTokenAuthorize::preclaim(PreclaimContext const& ctx) // If tx is submitted by issuer, it only applies for MPT with // lsfMPTRequireAuth set - if (!(mptIssuanceFlags & lsfMPTRequireAuth)) + if ((mptIssuanceFlags & lsfMPTRequireAuth) == 0u) return tecNO_AUTH; // The holder must create the MPT before the issuer can authorize it. diff --git a/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp b/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp index 58accf0271..6bcb1175e8 100644 --- a/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp +++ b/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp @@ -33,8 +33,8 @@ MPTokenIssuanceCreate::preflight(PreflightContext const& ctx) { // If the mutable flags field is included, at least one flag must be // specified. - if (auto const mutableFlags = ctx.tx[~sfMutableFlags]; - mutableFlags && (!*mutableFlags || *mutableFlags & tmfMPTokenIssuanceCreateMutableMask)) + if (auto const mutableFlags = ctx.tx[~sfMutableFlags]; mutableFlags && + ((*mutableFlags == 0u) || ((*mutableFlags & tmfMPTokenIssuanceCreateMutableMask) != 0u))) return temINVALID_FLAG; if (auto const fee = ctx.tx[~sfTransferFee]) diff --git a/src/libxrpl/tx/transactors/token/MPTokenIssuanceSet.cpp b/src/libxrpl/tx/transactors/token/MPTokenIssuanceSet.cpp index dc5827419b..fc09a53ae1 100644 --- a/src/libxrpl/tx/transactors/token/MPTokenIssuanceSet.cpp +++ b/src/libxrpl/tx/transactors/token/MPTokenIssuanceSet.cpp @@ -55,7 +55,7 @@ MPTokenIssuanceSet::preflight(PreflightContext const& ctx) auto const txFlags = ctx.tx.getFlags(); // fails if both flags are set - if ((txFlags & tfMPTLock) && (txFlags & tfMPTUnlock)) + if (((txFlags & tfMPTLock) != 0u) && ((txFlags & tfMPTUnlock) != 0u)) return temINVALID_FLAG; auto const accountID = ctx.tx[sfAccount]; @@ -77,7 +77,7 @@ MPTokenIssuanceSet::preflight(PreflightContext const& ctx) return temMALFORMED; // Can not set flags when mutating MPTokenIssuance - if (isMutate && (txFlags & tfUniversalMask)) + if (isMutate && ((txFlags & tfUniversalMask) != 0u)) return temMALFORMED; if (transferFee && *transferFee > maxTransferFee) @@ -88,7 +88,7 @@ MPTokenIssuanceSet::preflight(PreflightContext const& ctx) if (mutableFlags) { - if (!*mutableFlags || (*mutableFlags & tmfMPTokenIssuanceSetMutableMask)) + if ((*mutableFlags == 0u) || ((*mutableFlags & tmfMPTokenIssuanceSetMutableMask) != 0u)) return temINVALID_FLAG; // Can not set and clear the same flag @@ -102,7 +102,7 @@ MPTokenIssuanceSet::preflight(PreflightContext const& ctx) // Trying to set a non-zero TransferFee and clear MPTCanTransfer // in the same transaction is not allowed. - if (transferFee.value_or(0) && (*mutableFlags & tmfMPTClearCanTransfer)) + if ((transferFee.value_or(0) != 0u) && ((*mutableFlags & tmfMPTClearCanTransfer) != 0u)) return temMALFORMED; } } @@ -130,16 +130,16 @@ MPTokenIssuanceSet::checkPermission(ReadView const& view, STTx const& tx) // this is added in case more flags will be added for MPTokenIssuanceSet // in the future. Currently unreachable. - if (txFlags & tfMPTokenIssuanceSetMask) + if ((txFlags & tfMPTokenIssuanceSetMask) != 0u) return terNO_DELEGATE_PERMISSION; // LCOV_EXCL_LINE std::unordered_set granularPermissions; loadGranularPermission(sle, ttMPTOKEN_ISSUANCE_SET, granularPermissions); - if (txFlags & tfMPTLock && !granularPermissions.contains(MPTokenIssuanceLock)) + if (((txFlags & tfMPTLock) != 0u) && !granularPermissions.contains(MPTokenIssuanceLock)) return terNO_DELEGATE_PERMISSION; - if (txFlags & tfMPTUnlock && !granularPermissions.contains(MPTokenIssuanceUnlock)) + if (((txFlags & tfMPTUnlock) != 0u) && !granularPermissions.contains(MPTokenIssuanceUnlock)) return terNO_DELEGATE_PERMISSION; return tesSUCCESS; @@ -258,11 +258,11 @@ MPTokenIssuanceSet::doApply() std::uint32_t const flagsIn = sle->getFieldU32(sfFlags); std::uint32_t flagsOut = flagsIn; - if (txFlags & tfMPTLock) + if ((txFlags & tfMPTLock) != 0u) { flagsOut |= lsfMPTLocked; } - else if (txFlags & tfMPTUnlock) + else if ((txFlags & tfMPTUnlock) != 0u) { flagsOut &= ~lsfMPTLocked; } @@ -271,17 +271,17 @@ MPTokenIssuanceSet::doApply() { for (auto const& f : mptMutabilityFlags) { - if (mutableFlags & f.setFlag) + if ((mutableFlags & f.setFlag) != 0u) { flagsOut |= f.canMutateFlag; } - else if (mutableFlags & f.clearFlag) + else if ((mutableFlags & f.clearFlag) != 0u) { flagsOut &= ~f.canMutateFlag; } } - if (mutableFlags & tmfMPTClearCanTransfer) + if ((mutableFlags & tmfMPTClearCanTransfer) != 0u) { // If the lsfMPTCanTransfer flag is being cleared, then also clear // the TransferFee field. diff --git a/src/libxrpl/tx/transactors/token/TrustSet.cpp b/src/libxrpl/tx/transactors/token/TrustSet.cpp index 22588b977a..918620c3de 100644 --- a/src/libxrpl/tx/transactors/token/TrustSet.cpp +++ b/src/libxrpl/tx/transactors/token/TrustSet.cpp @@ -65,7 +65,7 @@ TrustSet::preflight(PreflightContext const& ctx) { // Even though the deep freeze flags are included in the // `tfTrustSetMask`, they are not valid if the amendment is not enabled. - if (uTxFlags & (tfSetDeepFreeze | tfClearDeepFreeze)) + if ((uTxFlags & (tfSetDeepFreeze | tfClearDeepFreeze)) != 0u) { return temINVALID_FLAG; } @@ -128,7 +128,7 @@ TrustSet::checkPermission(ReadView const& view, STTx const& tx) // Currently we only support TrustlineAuthorize, TrustlineFreeze and // TrustlineUnfreeze granular permission. Setting other flags returns // error. - if (txFlags & tfTrustSetPermissionMask) + if ((txFlags & tfTrustSetPermissionMask) != 0u) return terNO_DELEGATE_PERMISSION; if (tx.isFieldPresent(sfQualityIn) || tx.isFieldPresent(sfQualityOut)) @@ -146,11 +146,11 @@ TrustSet::checkPermission(ReadView const& view, STTx const& tx) std::unordered_set granularPermissions; loadGranularPermission(sle, ttTRUST_SET, granularPermissions); - if (txFlags & tfSetfAuth && !granularPermissions.contains(TrustlineAuthorize)) + if (((txFlags & tfSetfAuth) != 0u) && !granularPermissions.contains(TrustlineAuthorize)) return terNO_DELEGATE_PERMISSION; - if (txFlags & tfSetFreeze && !granularPermissions.contains(TrustlineFreeze)) + if (((txFlags & tfSetFreeze) != 0u) && !granularPermissions.contains(TrustlineFreeze)) return terNO_DELEGATE_PERMISSION; - if (txFlags & tfClearFreeze && !granularPermissions.contains(TrustlineUnfreeze)) + if (((txFlags & tfClearFreeze) != 0u) && !granularPermissions.contains(TrustlineUnfreeze)) return terNO_DELEGATE_PERMISSION; // updating LimitAmount is not allowed only with granular permissions, @@ -179,9 +179,9 @@ TrustSet::preclaim(PreclaimContext const& ctx) std::uint32_t const uTxFlags = ctx.tx.getFlags(); - bool const bSetAuth = (uTxFlags & tfSetfAuth); + bool const bSetAuth = (uTxFlags & tfSetfAuth) != 0u; - if (bSetAuth && !(sle->getFieldU32(sfFlags) & lsfRequireAuth)) + if (bSetAuth && ((sle->getFieldU32(sfFlags) & lsfRequireAuth) == 0u)) { JLOG(ctx.j.trace()) << "Retry: Auth not required."; return tefNO_AUTH_REQUIRED; @@ -203,7 +203,7 @@ TrustSet::preclaim(PreclaimContext const& ctx) // If the destination has opted to disallow incoming trustlines // then honour that flag - if (sleDst->getFlags() & lsfDisallowIncomingTrustline) + if ((sleDst->getFlags() & lsfDisallowIncomingTrustline) != 0u) { // The original implementation of featureDisallowIncoming was // too restrictive. If @@ -268,8 +268,8 @@ TrustSet::preclaim(PreclaimContext const& ctx) if (ctx.view.rules().enabled(featureDeepFreeze)) { bool const bNoFreeze = sle->isFlag(lsfNoFreeze); - bool const bSetFreeze = (uTxFlags & tfSetFreeze); - bool const bSetDeepFreeze = (uTxFlags & tfSetDeepFreeze); + bool const bSetFreeze = (uTxFlags & tfSetFreeze) != 0u; + bool const bSetDeepFreeze = (uTxFlags & tfSetDeepFreeze) != 0u; if (bNoFreeze && (bSetFreeze || bSetDeepFreeze)) { @@ -277,8 +277,8 @@ TrustSet::preclaim(PreclaimContext const& ctx) return tecNO_PERMISSION; } - bool const bClearFreeze = (uTxFlags & tfClearFreeze); - bool const bClearDeepFreeze = (uTxFlags & tfClearDeepFreeze); + bool const bClearFreeze = (uTxFlags & tfClearFreeze) != 0u; + bool const bClearDeepFreeze = (uTxFlags & tfClearDeepFreeze) != 0u; if ((bSetFreeze || bSetDeepFreeze) && (bClearFreeze || bClearDeepFreeze)) { // Freezing and unfreezing in the same transaction should be @@ -300,7 +300,7 @@ TrustSet::preclaim(PreclaimContext const& ctx) // Trying to set deep freeze on not already frozen trust line must // fail. This also checks that clearing normal freeze while deep // frozen must not work - if (deepFrozen && !frozen) + if ((deepFrozen != 0u) && (frozen == 0u)) { return tecNO_PERMISSION; } @@ -359,13 +359,13 @@ TrustSet::doApply() std::uint32_t const uTxFlags = ctx_.tx.getFlags(); - bool const bSetAuth = (uTxFlags & tfSetfAuth); - bool const bSetNoRipple = (uTxFlags & tfSetNoRipple); - bool const bClearNoRipple = (uTxFlags & tfClearNoRipple); - bool const bSetFreeze = (uTxFlags & tfSetFreeze); - bool const bClearFreeze = (uTxFlags & tfClearFreeze); - bool const bSetDeepFreeze = (uTxFlags & tfSetDeepFreeze); - bool const bClearDeepFreeze = (uTxFlags & tfClearDeepFreeze); + bool const bSetAuth = (uTxFlags & tfSetfAuth) != 0u; + bool const bSetNoRipple = (uTxFlags & tfSetNoRipple) != 0u; + bool const bClearNoRipple = (uTxFlags & tfClearNoRipple) != 0u; + bool const bSetFreeze = (uTxFlags & tfSetFreeze) != 0u; + bool const bClearFreeze = (uTxFlags & tfClearFreeze) != 0u; + bool const bSetDeepFreeze = (uTxFlags & tfSetDeepFreeze) != 0u; + bool const bClearDeepFreeze = (uTxFlags & tfClearDeepFreeze) != 0u; auto viewJ = ctx_.registry.journal("View"); @@ -424,7 +424,7 @@ TrustSet::doApply() uLowQualityIn = sleRippleState->getFieldU32(sfLowQualityIn); uHighQualityIn = sleRippleState->getFieldU32(sfHighQualityIn); } - else if (uQualityIn) + else if (uQualityIn != 0u) { // Setting. @@ -460,7 +460,7 @@ TrustSet::doApply() uLowQualityOut = sleRippleState->getFieldU32(sfLowQualityOut); uHighQualityOut = sleRippleState->getFieldU32(sfHighQualityOut); } - else if (uQualityOut) + else if (uQualityOut != 0u) { // Setting. @@ -516,23 +516,23 @@ TrustSet::doApply() if (QUALITY_ONE == uHighQualityOut) uHighQualityOut = 0; - bool const bLowDefRipple = sleLowAccount->getFlags() & lsfDefaultRipple; - bool const bHighDefRipple = sleHighAccount->getFlags() & lsfDefaultRipple; + bool const bLowDefRipple = (sleLowAccount->getFlags() & lsfDefaultRipple) != 0u; + bool const bHighDefRipple = (sleHighAccount->getFlags() & lsfDefaultRipple) != 0u; - bool const bLowReserveSet = uLowQualityIn || uLowQualityOut || - ((uFlagsOut & lsfLowNoRipple) == 0) != bLowDefRipple || (uFlagsOut & lsfLowFreeze) || - saLowLimit || saLowBalance > beast::zero; + bool const bLowReserveSet = (uLowQualityIn != 0u) || (uLowQualityOut != 0u) || + ((uFlagsOut & lsfLowNoRipple) == 0) != bLowDefRipple || + ((uFlagsOut & lsfLowFreeze) != 0u) || saLowLimit || saLowBalance > beast::zero; bool const bLowReserveClear = !bLowReserveSet; - bool const bHighReserveSet = uHighQualityIn || uHighQualityOut || - ((uFlagsOut & lsfHighNoRipple) == 0) != bHighDefRipple || (uFlagsOut & lsfHighFreeze) || - saHighLimit || saHighBalance > beast::zero; + bool const bHighReserveSet = (uHighQualityIn != 0u) || (uHighQualityOut != 0u) || + ((uFlagsOut & lsfHighNoRipple) == 0) != bHighDefRipple || + ((uFlagsOut & lsfHighFreeze) != 0u) || saHighLimit || saHighBalance > beast::zero; bool const bHighReserveClear = !bHighReserveSet; bool const bDefault = bLowReserveClear && bHighReserveClear; - bool const bLowReserved = (uFlagsIn & lsfLowReserve); - bool const bHighReserved = (uFlagsIn & lsfHighReserve); + bool const bLowReserved = (uFlagsIn & lsfLowReserve) != 0u; + bool const bHighReserved = (uFlagsIn & lsfHighReserve) != 0u; bool bReserveIncrease = false; @@ -603,11 +603,11 @@ TrustSet::doApply() } // Line does not exist. else if ( - !saLimitAmount && // Setting default limit. - (!bQualityIn || !uQualityIn) && // Not setting quality in or - // setting default quality in. - (!bQualityOut || !uQualityOut) && // Not setting quality out or - // setting default quality out. + !saLimitAmount && // Setting default limit. + (!bQualityIn || (uQualityIn == 0u)) && // Not setting quality in or + // setting default quality in. + (!bQualityOut || (uQualityOut == 0u)) && // Not setting quality out or + // setting default quality out. (!bSetAuth)) { JLOG(j_.trace()) << "Redundant: Setting non-existent ripple line to defaults."; diff --git a/src/libxrpl/tx/transactors/vault/VaultCreate.cpp b/src/libxrpl/tx/transactors/vault/VaultCreate.cpp index 0fc074bae2..02f8ecb57b 100644 --- a/src/libxrpl/tx/transactors/vault/VaultCreate.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultCreate.cpp @@ -165,7 +165,7 @@ VaultCreate::doApply() std::uint32_t mptFlags = 0; if ((txFlags & tfVaultShareNonTransferable) == 0) mptFlags |= (lsfMPTCanEscrow | lsfMPTCanTrade | lsfMPTCanTransfer); - if (txFlags & tfVaultPrivate) + if ((txFlags & tfVaultPrivate) != 0u) mptFlags |= lsfMPTRequireAuth; // Note, here we are **not** creating an MPToken for the assets held in @@ -211,7 +211,7 @@ VaultCreate::doApply() { vault->at(sfWithdrawalPolicy) = vaultStrategyFirstComeFirstServe; } - if (scale) + if (scale != 0u) vault->at(sfScale) = scale; view().insert(vault); @@ -222,7 +222,7 @@ VaultCreate::doApply() return err; // If the vault is private, set the authorized flag for the vault owner - if (txFlags & tfVaultPrivate) + if ((txFlags & tfVaultPrivate) != 0u) { if (auto const err = authorizeMPToken( view(), preFeeBalance_, mptIssuanceID, pseudoId, ctx_.journal, {}, account_); diff --git a/src/libxrpl/tx/transactors/vault/VaultSet.cpp b/src/libxrpl/tx/transactors/vault/VaultSet.cpp index 532edcdcef..b54389bcde 100644 --- a/src/libxrpl/tx/transactors/vault/VaultSet.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultSet.cpp @@ -14,10 +14,7 @@ namespace xrpl { bool VaultSet::checkExtraFeatures(PreflightContext const& ctx) { - if (ctx.tx.isFieldPresent(sfDomainID) && !ctx.rules.enabled(featurePermissionedDomains)) - return false; - - return true; + return !ctx.tx.isFieldPresent(sfDomainID) || ctx.rules.enabled(featurePermissionedDomains); } NotTEC diff --git a/src/test/app/AMMCalc_test.cpp b/src/test/app/AMMCalc_test.cpp index c1068b08ba..b4043f239b 100644 --- a/src/test/app/AMMCalc_test.cpp +++ b/src/test/app/AMMCalc_test.cpp @@ -40,7 +40,7 @@ class AMMCalc_test : public beast::unit_test::suite boost::regex rx("^([^(]+)[(]([^)]+)[)]([)])?$"); if (boost::regex_search(str, match, rx)) { - if (delimited) + if (delimited != nullptr) *delimited = (match[3] != ""); if (match[1] == "XRP") { @@ -72,7 +72,7 @@ class AMMCalc_test : public beast::unit_test::suite // input is rate * 100, no fraction std::uint32_t rate = 10'000'000 * std::stoi(match[2].str()); // true if delimited - ) - return {{currency, rate, match[3] != "" ? true : false}}; + return {{currency, rate, match[3] != ""}}; } return std::nullopt; } @@ -94,7 +94,7 @@ class AMMCalc_test : public beast::unit_test::suite if (p == end_) return std::nullopt; std::string const s = *p; - bool const amm = s[0] == 'O' ? false : true; + bool const amm = s[0] != 'O'; auto const a1 = getAmt(p++); if (!a1 || p == end_) return std::nullopt; @@ -161,7 +161,7 @@ class AMMCalc_test : public beast::unit_test::suite return {{pairs, *swap, *rate, fee}}; } - std::string + static std::string toString(STAmount const& a) { std::stringstream str; @@ -169,7 +169,7 @@ class AMMCalc_test : public beast::unit_test::suite return str.str(); } - STAmount + static STAmount mulratio(STAmount const& amt, std::uint32_t a, std::uint32_t b, bool round) { if (a == b) @@ -179,7 +179,7 @@ class AMMCalc_test : public beast::unit_test::suite return toSTAmount(mulRatio(amt.iou(), a, b, round), amt.issue()); } - void + static void swapOut(swapargs const& args) { auto const vp = std::get(args); @@ -242,7 +242,7 @@ class AMMCalc_test : public beast::unit_test::suite std::cout << "in: " << toString(resultIn) << " out: " << toString(resultOut) << std::endl; } - void + static void swapIn(swapargs const& args) { auto const vp = std::get(args); diff --git a/src/test/app/AMM_test.cpp b/src/test/app/AMM_test.cpp index a0a38b9791..704ced2b86 100644 --- a/src/test/app/AMM_test.cpp +++ b/src/test/app/AMM_test.cpp @@ -1918,7 +1918,7 @@ private: BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount(beast::Zero()))); BEAST_EXPECT(expectHolding(env, carol, USD(30'000))); BEAST_EXPECT( - expectLedgerEntryRoot(env, carol, XRPAmount{30'000'000'000 - 2 * baseFee})); + expectLedgerEntryRoot(env, carol, XRPAmount{30'000'000'000 - (2 * baseFee)})); }); // Equal withdrawal by tokens 1000000, 10% @@ -2732,13 +2732,13 @@ private: // 10th Interval after close, price for 1st interval. env(ammAlice.bid({.account = carol})); - env.close(seconds(10 * AUCTION_SLOT_INTERVAL_DURATION + 1)); + env.close(seconds((10 * AUCTION_SLOT_INTERVAL_DURATION) + 1)); BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 10, IOUAmount{121'275, -3})); // 20th Interval (expired) after close, price for 10th interval. env(ammAlice.bid({.account = bob})); env.close( - seconds(AUCTION_SLOT_TIME_INTERVALS * AUCTION_SLOT_INTERVAL_DURATION + 1)); + seconds((AUCTION_SLOT_TIME_INTERVALS * AUCTION_SLOT_INTERVAL_DURATION) + 1)); BEAST_EXPECT(ammAlice.expectAuctionSlot(0, std::nullopt, IOUAmount{127'33875, -5})); // 0 Interval. @@ -4111,7 +4111,7 @@ private: fund(env, gw, {bob}, {EUR(400)}, Fund::IOUOnly); env(trust(alice, EUR(200))); for (int i = 0; i < 30; ++i) - env(offer(alice, EUR(1.0 + 0.01 * i), XRP(1))); + env(offer(alice, EUR(1.0 + (0.01 * i)), XRP(1))); // This is worse quality offer than 30 offers above. // It will not be consumed because of AMM offers limit. env(offer(alice, EUR(140), XRP(100))); @@ -4151,7 +4151,7 @@ private: fund(env, gw, {bob}, {EUR(400)}, Fund::IOUOnly); env(trust(alice, EUR(200))); for (int i = 0; i < 29; ++i) - env(offer(alice, EUR(1.0 + 0.01 * i), XRP(1))); + env(offer(alice, EUR(1.0 + (0.01 * i)), XRP(1))); // This is worse quality offer than 30 offers above. // It will not be consumed because of AMM offers limit. env(offer(alice, EUR(140), XRP(100))); @@ -4268,7 +4268,7 @@ private: env(ammAlice.bid({.account = carol, .bidMin = 100})); BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{4'999'900})); BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{100})); - BEAST_EXPECT(accountBalance(env, carol) == std::to_string(22500000000 - 4 * baseFee)); + BEAST_EXPECT(accountBalance(env, carol) == std::to_string(22500000000 - (4 * baseFee))); priceXRP = ammAssetOut( STAmount{XRPAmount{10'000'000'000}}, STAmount{token1, 9'999'900}, @@ -4276,7 +4276,7 @@ private: 0); // Carol withdraws ammAlice.withdrawAll(carol, XRP(0)); - BEAST_EXPECT(accountBalance(env, carol) == std::to_string(29999949999 - 5 * baseFee)); + BEAST_EXPECT(accountBalance(env, carol) == std::to_string(29999949999 - (5 * baseFee))); BEAST_EXPECT(ammAlice.expectBalances( XRPAmount{10'000'000'000} - priceXRP, USD(10'000), IOUAmount{5'000'000})); BEAST_EXPECT(ammAlice.expectLPTokens(alice, IOUAmount{5'000'000})); @@ -5040,7 +5040,7 @@ private: // 30,000 initial - (deposit+withdraw) * 10 BEAST_EXPECT( accountBalance(env, carol) == - std::to_string(30'000'000'000 - 20 * baseFee)); + std::to_string(30'000'000'000 - (20 * baseFee))); BEAST_EXPECT(accountBalance(env, ed) == xrpBalance); BEAST_EXPECT(accountBalance(env, paul) == xrpBalance); BEAST_EXPECT(accountBalance(env, natalie) == xrpBalance); @@ -5064,7 +5064,7 @@ private: BEAST_EXPECT(accountBalance(env, dan) == xrpBalanceText); BEAST_EXPECT( accountBalance(env, carol) == - std::to_string(30'000'000'000 - 20 * baseFee - 10)); + std::to_string(30'000'000'000 - (20 * baseFee) - 10)); BEAST_EXPECT(accountBalance(env, ed) == (xrpBalance + drops(2)).getText()); BEAST_EXPECT(accountBalance(env, paul) == (xrpBalance + drops(3)).getText()); BEAST_EXPECT(accountBalance(env, natalie) == (xrpBalance + drops(5)).getText()); @@ -5155,7 +5155,7 @@ private: all); fund(env, gw, {alice}, XRP(20'000), {USD(10'000)}); AMM amm(env, gw, XRP(10'000), USD(10'000)); - for (auto i = 0; i < maxDeletableAMMTrustLines * 2 + 10; ++i) + for (auto i = 0; i < (maxDeletableAMMTrustLines * 2) + 10; ++i) { Account const a{std::to_string(i)}; env.fund(XRP(1'000), a); diff --git a/src/test/app/AccountTxPaging_test.cpp b/src/test/app/AccountTxPaging_test.cpp index 5efe307812..09b517c37c 100644 --- a/src/test/app/AccountTxPaging_test.cpp +++ b/src/test/app/AccountTxPaging_test.cpp @@ -10,7 +10,7 @@ namespace xrpl { class AccountTxPaging_test : public beast::unit_test::suite { - bool + static bool checkTransaction(Json::Value const& tx, int sequence, int ledger) { return ( @@ -18,7 +18,7 @@ class AccountTxPaging_test : public beast::unit_test::suite tx[jss::tx][jss::ledger_index].asInt() == ledger); } - auto + static auto next( test::jtx::Env& env, test::jtx::Account const& account, diff --git a/src/test/app/AmendmentTable_test.cpp b/src/test/app/AmendmentTable_test.cpp index d8431e5696..39e516304b 100644 --- a/src/test/app/AmendmentTable_test.cpp +++ b/src/test/app/AmendmentTable_test.cpp @@ -439,7 +439,7 @@ public: // Make a list of trusted validators. // Register the validators with AmendmentTable and return the list. - std::vector> + static std::vector> makeValidators(int num, std::unique_ptr const& table) { std::vector> ret; @@ -462,7 +462,7 @@ public: } // Execute a pretend consensus round for a flag ledger - void + static void doRound( Rules const& rules, AmendmentTable& table, diff --git a/src/test/app/Batch_test.cpp b/src/test/app/Batch_test.cpp index ec12fbb21f..9fe9e9cd3a 100644 --- a/src/test/app/Batch_test.cpp +++ b/src/test/app/Batch_test.cpp @@ -35,7 +35,7 @@ class Batch_test : public beast::unit_test::suite std::string txHash; }; - Json::Value + static Json::Value getTxByIndex(Json::Value const& jrr, int const index) { for (auto const& txn : jrr[jss::result][jss::ledger][jss::transactions]) @@ -46,7 +46,7 @@ class Batch_test : public beast::unit_test::suite return {}; } - Json::Value + static Json::Value getLastLedger(jtx::Env& env) { Json::Value params; @@ -125,7 +125,7 @@ class Batch_test : public beast::unit_test::suite return p; } - auto + static auto openLedgerFee(jtx::Env& env, XRPAmount const& batchFee) { using namespace jtx; diff --git a/src/test/app/Credentials_test.cpp b/src/test/app/Credentials_test.cpp index d23431f68e..db09bfc0ca 100644 --- a/src/test/app/Credentials_test.cpp +++ b/src/test/app/Credentials_test.cpp @@ -522,6 +522,7 @@ struct Credentials_test : public beast::unit_test::suite directory::adjustOwnerNode); BEAST_EXPECT(res1); + // NOLINTNEXTLINE(readability-suspicious-call-argument) auto const jv = credentials::create(issuer, subject, credType); env(jv, ter(tecDIR_FULL)); // Free one directory entry by using a ticket diff --git a/src/test/app/DepositAuth_test.cpp b/src/test/app/DepositAuth_test.cpp index ad401499bc..7a8404aad8 100644 --- a/src/test/app/DepositAuth_test.cpp +++ b/src/test/app/DepositAuth_test.cpp @@ -304,9 +304,11 @@ struct DepositAuth_test : public beast::unit_test::suite auto const noRipplePrev = i & 0x1; auto const noRippleNext = i & 0x2; auto const withDepositAuth = i & 0x4; - testIssuer(testable_amendments(), noRipplePrev, noRippleNext, withDepositAuth); + testIssuer( + testable_amendments(), noRipplePrev != 0, noRippleNext != 0, withDepositAuth != 0); - testNonIssuer(testable_amendments(), noRipplePrev, noRippleNext, withDepositAuth); + testNonIssuer( + testable_amendments(), noRipplePrev != 0, noRippleNext != 0, withDepositAuth != 0); } } diff --git a/src/test/app/EscrowToken_test.cpp b/src/test/app/EscrowToken_test.cpp index 280356c494..ff537a2f5e 100644 --- a/src/test/app/EscrowToken_test.cpp +++ b/src/test/app/EscrowToken_test.cpp @@ -35,7 +35,7 @@ struct EscrowToken_test : public beast::unit_test::suite return 0; } - jtx::PrettyAmount + static jtx::PrettyAmount issuerBalance(jtx::Env& env, jtx::Account const& account, Issue const& issue) { Json::Value params; @@ -49,7 +49,7 @@ struct EscrowToken_test : public beast::unit_test::suite return {amount, account.name()}; } - jtx::PrettyAmount + static jtx::PrettyAmount issuerEscrowed(jtx::Env& env, jtx::Account const& account, Issue const& issue) { Json::Value params; diff --git a/src/test/app/FeeVote_test.cpp b/src/test/app/FeeVote_test.cpp index f0599b8771..923e7b58b2 100644 --- a/src/test/app/FeeVote_test.cpp +++ b/src/test/app/FeeVote_test.cpp @@ -642,7 +642,7 @@ class FeeVote_test : public beast::unit_test::suite v.setFieldAmount(sfReserveBaseDrops, XRPAmount{setup.account_reserve}); v.setFieldAmount(sfReserveIncrementDrops, XRPAmount{setup.owner_reserve}); }); - if (i % 2) + if ((i % 2) != 0) val->setTrusted(); validations.push_back(val); } diff --git a/src/test/app/FixNFTokenPageLinks_test.cpp b/src/test/app/FixNFTokenPageLinks_test.cpp index 8022c52a5d..25366534cd 100644 --- a/src/test/app/FixNFTokenPageLinks_test.cpp +++ b/src/test/app/FixNFTokenPageLinks_test.cpp @@ -62,7 +62,7 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite // 0, 3, 2, 5, 4, 7... // in sets of 16 NFTs we can get each page to be fully // populated. - std::uint32_t const intTaxon = (i / 16) + (i & 0b10000 ? 2 : 0); + std::uint32_t const intTaxon = (i / 16) + (((i & 0b10000) != 0u) ? 2 : 0); uint32_t const extTaxon = internalTaxon(owner, intTaxon); nfts.push_back(token::getNextID(env, owner, extTaxon, tfTransferable)); env(token::mint(owner, extTaxon), txflags(tfTransferable)); diff --git a/src/test/app/Flow_test.cpp b/src/test/app/Flow_test.cpp index 1e9514f756..473f8bce20 100644 --- a/src/test/app/Flow_test.cpp +++ b/src/test/app/Flow_test.cpp @@ -241,7 +241,7 @@ struct Flow_test : public beast::unit_test::suite env.require(balance(bob, USDA(10))); env(pay(bob, carol, USDA(5)), sendmax(USDA(10))); auto const effectiveQ = carolAliceQIn > 100 ? 1.0 : carolAliceQIn / 100.0; - env.require(balance(bob, USDA(10.0 - 5.0 / effectiveQ))); + env.require(balance(bob, USDA(10.0 - (5.0 / effectiveQ)))); } // bob -> alice -> carol; bobAliceQOut varies. diff --git a/src/test/app/Freeze_test.cpp b/src/test/app/Freeze_test.cpp index 6f89163c04..1dd0de578b 100644 --- a/src/test/app/Freeze_test.cpp +++ b/src/test/app/Freeze_test.cpp @@ -1907,13 +1907,13 @@ class Freeze_test : public beast::unit_test::suite } // Helper function that returns the index of the next check on account - uint256 + static uint256 getCheckIndex(AccountID const& account, std::uint32_t uSequence) { return keylet::check(account, uSequence).key; } - uint256 + static uint256 createNFTSellOffer( test::jtx::Env& env, test::jtx::Account const& account, diff --git a/src/test/app/HashRouter_test.cpp b/src/test/app/HashRouter_test.cpp index 58bace3ef2..a1601914cf 100644 --- a/src/test/app/HashRouter_test.cpp +++ b/src/test/app/HashRouter_test.cpp @@ -10,7 +10,7 @@ namespace test { class HashRouter_test : public beast::unit_test::suite { - HashRouter::Setup + static HashRouter::Setup getSetup(std::chrono::seconds hold, std::chrono::seconds relay) { HashRouter::Setup setup; diff --git a/src/test/app/Invariants_test.cpp b/src/test/app/Invariants_test.cpp index 8372bb340b..9653a36edf 100644 --- a/src/test/app/Invariants_test.cpp +++ b/src/test/app/Invariants_test.cpp @@ -1227,7 +1227,7 @@ class Invariants_test : public beast::unit_test::suite sle->setAccountID(sfOwner, A1); sle->setFieldU32(sfSequence, seq); - if (numCreds) + if (numCreds != 0u) { // This array is sorted naturally, but if you willing to change this // behavior don't forget to use credentials::makeSorted diff --git a/src/test/app/LedgerMaster_test.cpp b/src/test/app/LedgerMaster_test.cpp index b48579043e..3ea16b63eb 100644 --- a/src/test/app/LedgerMaster_test.cpp +++ b/src/test/app/LedgerMaster_test.cpp @@ -8,7 +8,7 @@ namespace test { class LedgerMaster_test : public beast::unit_test::suite { - std::unique_ptr + static std::unique_ptr makeNetworkConfig(uint32_t networkID) { using namespace jtx; diff --git a/src/test/app/LedgerReplay_test.cpp b/src/test/app/LedgerReplay_test.cpp index 54c12b465a..59304f1894 100644 --- a/src/test/app/LedgerReplay_test.cpp +++ b/src/test/app/LedgerReplay_test.cpp @@ -232,9 +232,7 @@ public: bool supportsFeature(ProtocolFeature f) const override { - if (f == ProtocolFeature::LedgerReplay && ledgerReplayEnabled_) - return true; - return false; + return f == ProtocolFeature::LedgerReplay && ledgerReplayEnabled_; } std::optional publisherListSequence(PublicKey const&) const override @@ -363,7 +361,7 @@ struct TestPeerSet : public PeerSet dropRate = 100; } - if ((rand() % 100 + 1) <= dropRate) + if (((rand() % 100) + 1) <= dropRate) return; switch (type) @@ -752,9 +750,7 @@ public: auto t = findTask(hash, totalReplay); if (!t) { - if (taskExpect == TaskStatus::NotExist) - return true; - return false; + return taskExpect == TaskStatus::NotExist; } return asExpected(t, taskExpect, skiplistExpect, deltaExpects); @@ -771,9 +767,7 @@ public: auto t = findTask(hash, totalReplay); if (!t) { - if (taskExpect == TaskStatus::NotExist) - return true; - return false; + return taskExpect == TaskStatus::NotExist; } return asExpected(t, taskExpect, skiplistExpect, deltaExpects); @@ -1066,10 +1060,7 @@ struct LedgerReplayer_test : public beast::unit_test::suite auto http_resp = xrpl::makeResponse( true, http_request, addr, addr, uint256{1}, 1, {1, 0}, serverEnv.app()); auto const clientResult = peerFeatureEnabled(http_resp, FEATURE_LEDGER_REPLAY, client); - if (clientResult != expecting) - return false; - - return true; + return clientResult == expecting; }; BEAST_EXPECT(handshake(false, false, false)); @@ -1301,7 +1292,7 @@ struct LedgerReplayer_test : public beast::unit_test::suite int totalReplay = 5; NetworkOfTwo net( *this, - {totalReplay * 3 + 1}, + {(totalReplay * 3) + 1}, PeerSetBehavior::Good, InboundLedgersBehavior::Good, PeerFeature::LedgerReplayEnabled); @@ -1348,11 +1339,11 @@ struct LedgerReplayer_test : public beast::unit_test::suite TaskStatus::Completed, deltaStatuses)); // deltaStatuses no change BEAST_EXPECT(net.client.waitForLedgers(finalHash_moreEarly, totalReplay)); - BEAST_EXPECT(net.client.countsAsExpected(4, 3, 2 * (totalReplay - 1) + 2)); + BEAST_EXPECT(net.client.countsAsExpected(4, 3, (2 * (totalReplay - 1)) + 2)); // cover net.client.replayer.replay(InboundLedger::Reason::GENERIC, finalHash, totalReplay * 3); - deltaStatuses = std::vector(totalReplay * 3 - 1, TaskStatus::Completed); + deltaStatuses = std::vector((totalReplay * 3) - 1, TaskStatus::Completed); BEAST_EXPECT(net.client.waitAndCheckStatus( finalHash, totalReplay * 3, @@ -1360,7 +1351,7 @@ struct LedgerReplayer_test : public beast::unit_test::suite TaskStatus::Completed, deltaStatuses)); // deltaStatuses changed BEAST_EXPECT(net.client.waitForLedgers(finalHash, totalReplay * 3)); - BEAST_EXPECT(net.client.countsAsExpected(5, 3, totalReplay * 3 - 1)); + BEAST_EXPECT(net.client.countsAsExpected(5, 3, (totalReplay * 3) - 1)); // sweep net.client.replayer.sweep(); @@ -1464,7 +1455,7 @@ struct LedgerReplayerLong_test : public beast::unit_test::suite int rounds = 4; NetworkOfTwo net( *this, - {totalReplay * rounds + 1}, + {(totalReplay * rounds) + 1}, PeerSetBehavior::Good, InboundLedgersBehavior::Good, PeerFeature::LedgerReplayEnabled); diff --git a/src/test/app/Loan_test.cpp b/src/test/app/Loan_test.cpp index 171e2eddb5..fa7befd39e 100644 --- a/src/test/app/Loan_test.cpp +++ b/src/test/app/Loan_test.cpp @@ -388,7 +388,7 @@ protected: if (auto vaultSle = env.le(keylet::vault(brokerSle->at(sfVaultID))); env.test.BEAST_EXPECT(vaultSle)) { - if ((flags & lsfLoanImpaired) && !(flags & lsfLoanDefault)) + if (((flags & lsfLoanImpaired) != 0u) && ((flags & lsfLoanDefault) == 0u)) { env.test.BEAST_EXPECT( vaultSle->at(sfLossUnrealized) == @@ -746,7 +746,7 @@ protected: return std::make_tuple(broker, loanKeylet, pseudoAcct); } - void + static void topUpBorrower( jtx::Env& env, BrokerInfo const& broker, @@ -1439,7 +1439,7 @@ protected: // Either the borrower or the lender can delete the loan. Alternate // between who does it across tests. static unsigned deleteCounter = 0; - auto const deleter = ++deleteCounter % 2 ? lender : borrower; + auto const deleter = ((++deleteCounter % 2) != 0u) ? lender : borrower; env(del(deleter, keylet.key)); env.close(); @@ -1468,7 +1468,7 @@ protected: } } - std::string + static std::string getCurrencyLabel(Asset const& asset) { if (asset.native()) @@ -2149,7 +2149,7 @@ protected: state.totalValue = 0; state.managementFeeOutstanding = 0; state.previousPaymentDate = - state.nextPaymentDate + state.paymentInterval * (numPayments - 1); + state.nextPaymentDate + (state.paymentInterval * (numPayments - 1)); state.nextPaymentDate = 0; verifyLoanStatus(state); @@ -2983,7 +2983,7 @@ protected: BEAST_EXPECT(sleMPT1 == nullptr); // Burn some XRP - env(noop(borrower), fee(XRP(acctReserve * 2 + incReserve * 2))); + env(noop(borrower), fee(XRP((acctReserve * 2) + (incReserve * 2)))); env.close(); // Cannot create loan, not enough reserve to create MPToken @@ -3007,7 +3007,7 @@ protected: BEAST_EXPECT(sleMPT2 != nullptr); }, {}, - CaseArgs{.initialXRP = acctReserve * 2 + incReserve * 8 + 1}); + CaseArgs{.initialXRP = (acctReserve * 2) + (incReserve * 8) + 1}); testCase( {}, @@ -3029,7 +3029,7 @@ protected: BEAST_EXPECT(sleLine1 == nullptr); // Burn some XRP - env(noop(borrower), fee(XRP(acctReserve * 2 + incReserve * 2))); + env(noop(borrower), fee(XRP((acctReserve * 2) + (incReserve * 2)))); env.close(); // Cannot create loan, not enough reserve to create trust line @@ -3052,7 +3052,7 @@ protected: auto const sleLine2 = env.le(trustline); BEAST_EXPECT(sleLine2 != nullptr); }, - CaseArgs{.initialXRP = acctReserve * 2 + incReserve * 8 + 1}); + CaseArgs{.initialXRP = (acctReserve * 2) + (incReserve * 8) + 1}); testCase( [&, this](Env& env, BrokerInfo const& broker, MPTTester& mptt) { @@ -3102,7 +3102,7 @@ protected: BEAST_EXPECT(sleMPT3 != nullptr); }, {}, - CaseArgs{.initialXRP = acctReserve * 2 + incReserve * 8 + 1}); + CaseArgs{.initialXRP = (acctReserve * 2) + (incReserve * 8) + 1}); testCase( {}, @@ -3152,7 +3152,7 @@ protected: auto const sleLine3 = env.le(trustline); BEAST_EXPECT(sleLine3 != nullptr); }, - CaseArgs{.initialXRP = acctReserve * 2 + incReserve * 8 + 1}); + CaseArgs{.initialXRP = (acctReserve * 2) + (incReserve * 8) + 1}); testCase( [&, this](Env& env, BrokerInfo const& broker, MPTTester& mptt) { diff --git a/src/test/app/Manifest_test.cpp b/src/test/app/Manifest_test.cpp index 609b7bdb89..7039f8df4f 100644 --- a/src/test/app/Manifest_test.cpp +++ b/src/test/app/Manifest_test.cpp @@ -87,7 +87,7 @@ public: } } - std::string + static std::string makeManifestString( PublicKey const& pk, SecretKey const& sk, @@ -190,7 +190,7 @@ public: return *deserializeManifest(std::string{}); // Silence compiler warning. } - Manifest + static Manifest clone(Manifest const& m) { Manifest m2(m.serialized, m.masterKey, m.signingKey, m.sequence, m.domain); diff --git a/src/test/app/NFTokenAuth_test.cpp b/src/test/app/NFTokenAuth_test.cpp index b973530f41..59faeb1eeb 100644 --- a/src/test/app/NFTokenAuth_test.cpp +++ b/src/test/app/NFTokenAuth_test.cpp @@ -6,7 +6,7 @@ namespace xrpl { class NFTokenAuth_test : public beast::unit_test::suite { - auto + static auto mintAndOfferNFT( test::jtx::Env& env, test::jtx::Account const& account, diff --git a/src/test/app/NFTokenBurn_test.cpp b/src/test/app/NFTokenBurn_test.cpp index 25f5a0f880..b91b245a7f 100644 --- a/src/test/app/NFTokenBurn_test.cpp +++ b/src/test/app/NFTokenBurn_test.cpp @@ -23,7 +23,7 @@ class NFTokenBurn_test : public beast::unit_test::suite // Helper function that returns new nft id for an account and create // specified number of sell offers - uint256 + static uint256 createNftAndOffers( test::jtx::Env& env, test::jtx::Account const& owner, @@ -59,7 +59,7 @@ class NFTokenBurn_test : public beast::unit_test::suite noisy = true, }; - void + static void printNFTPages(test::jtx::Env& env, Volume vol) { Json::Value jvParams; diff --git a/src/test/app/NFTokenDir_test.cpp b/src/test/app/NFTokenDir_test.cpp index 73698f1f89..70514f497f 100644 --- a/src/test/app/NFTokenDir_test.cpp +++ b/src/test/app/NFTokenDir_test.cpp @@ -20,7 +20,7 @@ class NFTokenDir_test : public beast::unit_test::suite noisy = true, }; - void + static void printNFTPages(test::jtx::Env& env, Volume vol) { Json::Value jvParams; diff --git a/src/test/app/NFToken_test.cpp b/src/test/app/NFToken_test.cpp index ba61830758..40fb78bb20 100644 --- a/src/test/app/NFToken_test.cpp +++ b/src/test/app/NFToken_test.cpp @@ -53,7 +53,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite } // Helper function returns the close time of the parent ledger. - std::uint32_t + static std::uint32_t lastClose(test::jtx::Env& env) { return env.current()->header().parentCloseTime.time_since_epoch().count(); @@ -243,7 +243,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite { env(token::burn(alice, token::getID(env, alice, 0, seq++))); env.close(); - checkAliceOwnerMintedBurned((33 - seq) ? 1 : 0, 33, seq, __LINE__); + checkAliceOwnerMintedBurned(((33 - seq) != 0u) ? 1 : 0, 33, seq, __LINE__); } // alice burns a non-existent NFT. @@ -352,7 +352,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite { env(token::burn(minter, token::getID(env, alice, 0, nftSeq++))); env.close(); - checkMintersOwnerMintedBurned(0, 66, nftSeq, (65 - seq) ? 1 : 0, 0, 0, __LINE__); + checkMintersOwnerMintedBurned( + 0, 66, nftSeq, ((65 - seq) != 0u) ? 1 : 0, 0, 0, __LINE__); } // minter has one more NFT to burn. Should take her owner count to @@ -1529,7 +1530,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); // becky attempts to sell the nft for AUD. - TER const createOfferTER = xferFee ? TER(tecNO_LINE) : TER(tesSUCCESS); + TER const createOfferTER = (xferFee != 0u) ? TER(tecNO_LINE) : TER(tesSUCCESS); uint256 const beckyOfferIndex = keylet::nftoffer(becky, env.seq(becky)).key; env(token::createOffer(becky, nftNoAutoTrustID, gwAUD(100)), txflags(tfSellNFToken), @@ -4532,7 +4533,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite }; // There are no sell offers. - checkOffers("nft_sell_offers", 0, false, __LINE__); + checkOffers("nft_sell_offers", 0, 0, __LINE__); // A lambda that generates sell offers. STAmount sellPrice = XRP(0); diff --git a/src/test/app/NetworkID_test.cpp b/src/test/app/NetworkID_test.cpp index a37f8342e1..17245f7ee5 100644 --- a/src/test/app/NetworkID_test.cpp +++ b/src/test/app/NetworkID_test.cpp @@ -18,7 +18,7 @@ public: testNetworkID(); } - std::unique_ptr + static std::unique_ptr makeNetworkConfig(uint32_t networkID) { using namespace jtx; diff --git a/src/test/app/Offer_test.cpp b/src/test/app/Offer_test.cpp index 62edc844c7..35146f5234 100644 --- a/src/test/app/Offer_test.cpp +++ b/src/test/app/Offer_test.cpp @@ -11,13 +11,13 @@ namespace test { class OfferBaseUtil_test : public beast::unit_test::suite { - XRPAmount + static XRPAmount reserve(jtx::Env& env, std::uint32_t count) { return env.current()->fees().accountReserve(count); } - std::uint32_t + static std::uint32_t lastClose(jtx::Env& env) { return env.current()->header().parentCloseTime.time_since_epoch().count(); @@ -2253,7 +2253,7 @@ public: // The gateway optionally creates an offer that would be crossed. auto const book = t.bookAmount; - if (book) + if (book != 0) env(offer(gw, XRP(book), USD(book))); env.close(); std::uint32_t const gwOfferSeq = env.seq(gw) - 1; @@ -2285,7 +2285,7 @@ public: auto acctOffers = offersOnAccount(env, acct); BEAST_EXPECT(acctOffers.size() == t.offers); - if (!acctOffers.empty() && t.offers) + if (!acctOffers.empty() && (t.offers != 0)) { auto const& acctOffer = *(acctOffers.front()); @@ -2296,7 +2296,7 @@ public: if (t.preTrust == noPreTrust) { - if (t.balanceUsd.value().signum()) + if (t.balanceUsd.value().signum() != 0) { // Verify the correct contents of the trustline verifyDefaultTrustline(env, acct, t.balanceUsd); @@ -2773,7 +2773,7 @@ public: env.require(offers(acct, t.offers)); env.require(owners(acct, t.owners)); - if (t.offers) + if (t.offers != 0) { auto const acctOffers = offersOnAccount(env, acct); if (!acctOffers.empty()) @@ -3875,10 +3875,10 @@ public: // clang-format off TestData const tests[]{ // btcStart --------------------- actor[0] --------------------- -------------------- actor[1] ------------------- - {0, 0, 1, BTC(20), {{"ann", 0, drops(3900000'000000 - 4 * baseFee), BTC(20.0), USD(3000)}, {"abe", 0, drops(4100000'000000 - 3 * baseFee), BTC( 0), USD(750)}}}, // no BTC xfer fee - {0, 1, 0, BTC(20), {{"bev", 0, drops(4100000'000000 - 4 * baseFee), BTC( 7.5), USD(2000)}, {"bob", 0, drops(3900000'000000 - 3 * baseFee), BTC(10), USD( 0)}}}, // no USD xfer fee - {0, 0, 0, BTC(20), {{"cam", 0, drops(4000000'000000 - 5 * baseFee), BTC(20.0), USD(2000)} }}, // no xfer fee - {0, 1, 0, BTC( 5), {{"deb", 1, drops(4040000'000000 - 4 * baseFee), BTC( 0.0), USD(2000)}, {"dan", 1, drops(3960000'000000 - 3 * baseFee), BTC( 4), USD( 0)}}}, // no USD xfer fee + {0, 0, 1, BTC(20), {{"ann", 0, drops(3900000'000000 - (4 * baseFee)), BTC(20.0), USD(3000)}, {"abe", 0, drops(4100000'000000 - (3 * baseFee)), BTC( 0), USD(750)}}}, // no BTC xfer fee + {0, 1, 0, BTC(20), {{"bev", 0, drops(4100000'000000 - (4 * baseFee)), BTC( 7.5), USD(2000)}, {"bob", 0, drops(3900000'000000 - (3 * baseFee)), BTC(10), USD( 0)}}}, // no USD xfer fee + {0, 0, 0, BTC(20), {{"cam", 0, drops(4000000'000000 - (5 * baseFee)), BTC(20.0), USD(2000)} }}, // no xfer fee + {0, 1, 0, BTC( 5), {{"deb", 1, drops(4040000'000000 - (4 * baseFee)), BTC( 0.0), USD(2000)}, {"dan", 1, drops(3960000'000000 - (3 * baseFee)), BTC( 4), USD( 0)}}}, // no USD xfer fee }; // clang-format on @@ -4026,8 +4026,8 @@ public: // clang-format off TestData const tests[]{ // btcStart ------------------- actor[0] -------------------- ------------------- actor[1] -------------------- - {0, 0, 1, BTC(5), {{"gay", 1, drops(3950000'000000 - 4 * baseFee), BTC(5), USD(2500)}, {"gar", 1, drops(4050000'000000 - 3 * baseFee), BTC(0), USD(1375)}}}, // no BTC xfer fee - {0, 0, 0, BTC(5), {{"hye", 2, drops(4000000'000000 - 5 * baseFee), BTC(5), USD(2000)} }} // no xfer fee + {0, 0, 1, BTC(5), {{"gay", 1, drops(3950000'000000 - (4 * baseFee)), BTC(5), USD(2500)}, {"gar", 1, drops(4050000'000000 - (3 * baseFee)), BTC(0), USD(1375)}}}, // no BTC xfer fee + {0, 0, 0, BTC(5), {{"hye", 2, drops(4000000'000000 - (5 * baseFee)), BTC(5), USD(2000)} }} // no xfer fee }; // clang-format on diff --git a/src/test/app/OversizeMeta_test.cpp b/src/test/app/OversizeMeta_test.cpp index 3831e45a78..d6305bedb6 100644 --- a/src/test/app/OversizeMeta_test.cpp +++ b/src/test/app/OversizeMeta_test.cpp @@ -9,7 +9,7 @@ namespace test { class PlumpBook_test : public beast::unit_test::suite { public: - void + static void createOffers(jtx::Env& env, jtx::IOU const& iou, std::size_t n) { using namespace jtx; @@ -64,7 +64,7 @@ BEAST_DEFINE_TESTSUITE(ThinBook, app, xrpl); class OversizeMeta_test : public beast::unit_test::suite { public: - void + static void createOffers(jtx::Env& env, jtx::IOU const& iou, std::size_t n) { using namespace jtx; @@ -130,7 +130,7 @@ public: return lo; } - void + static void createOffers(jtx::Env& env, jtx::IOU const& iou, std::size_t n) { using namespace jtx; diff --git a/src/test/app/Path_test.cpp b/src/test/app/Path_test.cpp index 9315370809..53da92ce1c 100644 --- a/src/test/app/Path_test.cpp +++ b/src/test/app/Path_test.cpp @@ -39,7 +39,7 @@ rpf(jtx::Account const& src, jtx::Account const& dst, std::uint32_t num_src) { auto& sc = (jv[jss::source_currencies] = Json::arrayValue); Json::Value j = Json::objectValue; - while (num_src--) + while ((num_src--) != 0u) { j[jss::currency] = std::to_string(num_src + 100); sc.append(j); diff --git a/src/test/app/PayChan_test.cpp b/src/test/app/PayChan_test.cpp index 5322349797..1150ae4d86 100644 --- a/src/test/app/PayChan_test.cpp +++ b/src/test/app/PayChan_test.cpp @@ -1096,7 +1096,7 @@ struct PayChan_test : public beast::unit_test::suite { auto leftToFind = bobsB58; auto const numFull = bobs.size() / limit; - auto const numNonFull = bobs.size() % limit ? 1 : 0; + auto const numNonFull = ((bobs.size() % limit) != 0u) ? 1 : 0; Json::Value marker = Json::nullValue; @@ -1122,7 +1122,7 @@ struct PayChan_test : public beast::unit_test::suite testIt(expectMarker, limit); } - if (numNonFull) + if (numNonFull != 0) { testIt(false, bobs.size() % limit); } diff --git a/src/test/app/PayStrand_test.cpp b/src/test/app/PayStrand_test.cpp index 70444637bf..d2e79a58f8 100644 --- a/src/test/app/PayStrand_test.cpp +++ b/src/test/app/PayStrand_test.cpp @@ -176,7 +176,7 @@ class ElementComboIter bool has(SB s) const { - return state_ & (1 << safe_cast(s)); + return (state_ & (1 << safe_cast(s))) != 0; } bool @@ -212,7 +212,7 @@ public: valid() const { return (allowCompound_ || !(has(SB::acc) && hasAny({SB::cur, SB::iss}))) && - (!hasAny({SB::prevAcc, SB::prevCur, SB::prevIss}) || prev_) && + (!hasAny({SB::prevAcc, SB::prevCur, SB::prevIss}) || (prev_ != nullptr)) && (!hasAny({SB::rootAcc, SB::sameAccIss, SB::existingAcc, SB::prevAcc}) || has(SB::acc)) && (!hasAny({SB::rootIss, SB::sameAccIss, SB::existingIss, SB::prevIss}) || diff --git a/src/test/app/PermissionedDEX_test.cpp b/src/test/app/PermissionedDEX_test.cpp index 2817bc0502..7b622a1256 100644 --- a/src/test/app/PermissionedDEX_test.cpp +++ b/src/test/app/PermissionedDEX_test.cpp @@ -34,13 +34,13 @@ using namespace jtx; class PermissionedDEX_test : public beast::unit_test::suite { - [[nodiscard]] bool + [[nodiscard]] static bool offerExists(Env const& env, Account const& account, std::uint32_t offerSeq) { return static_cast(env.le(keylet::offer(account.id(), offerSeq))); } - [[nodiscard]] bool + [[nodiscard]] static bool checkOffer( Env const& env, Account const& account, @@ -120,13 +120,13 @@ class PermissionedDEX_test : public beast::unit_test::suite return true; } - uint256 + static uint256 getBookDirKey(Book const& book, STAmount const& takerPays, STAmount const& takerGets) { return keylet::quality(keylet::book(book), getRate(takerGets, takerPays)).key; } - std::optional + static std::optional getDefaultOfferDirKey(Env const& env, Account const& account, std::uint32_t offerSeq) { if (auto const sle = env.le(keylet::offer(account.id(), offerSeq))) @@ -135,7 +135,7 @@ class PermissionedDEX_test : public beast::unit_test::suite return {}; } - [[nodiscard]] bool + [[nodiscard]] static bool checkDirectorySize(Env const& env, uint256 directory, std::uint32_t dirSize) { std::optional pageIndex{0}; @@ -151,7 +151,7 @@ class PermissionedDEX_test : public beast::unit_test::suite pageIndex = (*page)[~sfIndexNext]; dirCnt += (*page)[sfIndexes].size(); - } while (pageIndex.value_or(0)); + } while (pageIndex.value_or(0) != 0u); return dirCnt == dirSize; } diff --git a/src/test/app/PseudoTx_test.cpp b/src/test/app/PseudoTx_test.cpp index aa16df8e9c..79346a3fe1 100644 --- a/src/test/app/PseudoTx_test.cpp +++ b/src/test/app/PseudoTx_test.cpp @@ -11,7 +11,7 @@ namespace test { struct PseudoTx_test : public beast::unit_test::suite { - std::vector + static std::vector getPseudoTxs(Rules const& rules, std::uint32_t seq) { std::vector res; @@ -43,7 +43,7 @@ struct PseudoTx_test : public beast::unit_test::suite return res; } - std::vector + static std::vector getRealTxs() { std::vector res; diff --git a/src/test/app/RCLValidations_test.cpp b/src/test/app/RCLValidations_test.cpp index a7941ea64f..63f295e3b7 100644 --- a/src/test/app/RCLValidations_test.cpp +++ b/src/test/app/RCLValidations_test.cpp @@ -59,7 +59,7 @@ class RCLValidations_test : public beast::unit_test::suite auto prev = std::make_shared( create_genesis, config, std::vector{}, env.app().getNodeFamily()); history.push_back(prev); - for (auto i = 0; i < (2 * maxAncestors + 1); ++i) + for (auto i = 0; i < ((2 * maxAncestors) + 1); ++i) { auto next = std::make_shared(*prev, env.app().timeKeeper().closeTime()); next->updateSkipList(); diff --git a/src/test/app/ReducedOffer_test.cpp b/src/test/app/ReducedOffer_test.cpp index d0cf1b5324..46193a1544 100644 --- a/src/test/app/ReducedOffer_test.cpp +++ b/src/test/app/ReducedOffer_test.cpp @@ -491,7 +491,7 @@ public: } } - Amounts + static Amounts jsonOfferToAmounts(Json::Value const& json) { STAmount const in = amountFromJson(sfTakerPays, json[sfTakerPays.jsonName]); diff --git a/src/test/app/SHAMapStore_test.cpp b/src/test/app/SHAMapStore_test.cpp index d7d3e281f4..e5471ab74e 100644 --- a/src/test/app/SHAMapStore_test.cpp +++ b/src/test/app/SHAMapStore_test.cpp @@ -34,7 +34,7 @@ class SHAMapStore_test : public beast::unit_test::suite return cfg; } - bool + static bool goodLedger(jtx::Env& env, Json::Value const& json, std::string ledgerID, bool checkDB = false) { auto good = json.isMember(jss::result) && !RPC::contains_error(json[jss::result]) && @@ -73,7 +73,7 @@ class SHAMapStore_test : public beast::unit_test::suite outTxHash == ledger[jss::transaction_hash].asString(); } - bool + static bool bad(Json::Value const& json, error_code_i error = rpcLGR_NOT_FOUND) { return json.isMember(jss::result) && RPC::contains_error(json[jss::result]) && @@ -346,9 +346,9 @@ public: BEAST_EXPECT(lastRotated == store.getLastRotated()); // This does not kick off a cleanup - canDelete = env.rpc("can_delete", std::to_string(ledgerSeq + deleteInterval / 2)); + canDelete = env.rpc("can_delete", std::to_string(ledgerSeq + (deleteInterval / 2))); BEAST_EXPECT(!RPC::contains_error(canDelete[jss::result])); - BEAST_EXPECT(canDelete[jss::result][jss::can_delete] == ledgerSeq + deleteInterval / 2); + BEAST_EXPECT(canDelete[jss::result][jss::can_delete] == ledgerSeq + (deleteInterval / 2)); store.rendezvous(); diff --git a/src/test/app/TrustSet_test.cpp b/src/test/app/TrustSet_test.cpp index 51828fa544..d359ba1f26 100644 --- a/src/test/app/TrustSet_test.cpp +++ b/src/test/app/TrustSet_test.cpp @@ -260,7 +260,7 @@ public: env.close(); } - Json::Value + static Json::Value trust_explicit_amt(jtx::Account const& a, STAmount const& amt) { Json::Value jv; @@ -287,7 +287,7 @@ public: for (std::uint64_t badFlag = 1u; badFlag <= std::numeric_limits::max(); badFlag *= 2) { - if (badFlag & tfTrustSetMask) + if ((badFlag & tfTrustSetMask) != 0u) { env(trust(alice, gw["USD"](100), static_cast(badFlag)), ter(temINVALID_FLAG)); diff --git a/src/test/app/TxQ_test.cpp b/src/test/app/TxQ_test.cpp index 59db7e0d5d..a758167319 100644 --- a/src/test/app/TxQ_test.cpp +++ b/src/test/app/TxQ_test.cpp @@ -24,7 +24,7 @@ class TxQPosNegFlows_test : public beast::unit_test::suite static constexpr FeeLevel64 baseFeeLevel{256}; static constexpr FeeLevel64 minEscalationFeeLevel = baseFeeLevel * 500; - void + static void fillQueue(jtx::Env& env, jtx::Account const& account) { auto metrics = env.app().getTxQ().getMetrics(*env.current()); @@ -32,7 +32,7 @@ class TxQPosNegFlows_test : public beast::unit_test::suite env(noop(account)); } - auto + static auto openLedgerCost(jtx::Env& env) { using namespace jtx; @@ -52,7 +52,7 @@ class TxQPosNegFlows_test : public beast::unit_test::suite // Get a fee level of a transaction made by an account // This fee level is used to ensure we can place transaction into TxQ - auto + static auto txFeeLevelByAccount(jtx::Env& env, jtx::Account const& account) { using namespace jtx; @@ -65,7 +65,7 @@ class TxQPosNegFlows_test : public beast::unit_test::suite // Calculating expected median fee level based on known fee levels of median // transaction levels. - auto + static auto calcMedFeeLevel(FeeLevel64 const feeLevel1, FeeLevel64 const feeLevel2) { FeeLevel64 const expectedMedFeeLevel = (feeLevel1 + feeLevel2 + FeeLevel64{1}) / 2; @@ -73,7 +73,7 @@ class TxQPosNegFlows_test : public beast::unit_test::suite return std::max(expectedMedFeeLevel, minEscalationFeeLevel).fee(); } - auto + static auto calcMedFeeLevel(FeeLevel64 const feeLevel) { return calcMedFeeLevel(feeLevel, feeLevel); @@ -551,16 +551,16 @@ public: // The lowest fee ticket is baseFee * 2.1, trying to replace it env(noop(alice), ticket::use(tkt1 + 18), - fee(baseFee * 2.1 * 1.25 - 1), + fee((baseFee * 2.1 * 1.25) - 1), ter(telCAN_NOT_QUEUE_FEE)); - env(noop(alice), ticket::use(tkt1 + 18), fee(baseFee * 2.1 * 1.25 + 1), queued); + env(noop(alice), ticket::use(tkt1 + 18), fee((baseFee * 2.1 * 1.25) + 1), queued); // New lowest fee ticket is baseFee * 2.2 env(noop(alice), ticket::use(tkt250 - 4), - fee(baseFee * 2.2 * 1.25 - 1), + fee((baseFee * 2.2 * 1.25) - 1), ter(telCAN_NOT_QUEUE_FEE)); - env(noop(alice), ticket::use(tkt250 - 4), fee(baseFee * 2.2 * 1.25 + 1), queued); + env(noop(alice), ticket::use(tkt250 - 4), fee((baseFee * 2.2 * 1.25) + 1), queued); env.close(); env.require(owners(alice, 227), tickets(alice, 227)); @@ -858,7 +858,7 @@ public: ++seqCarol; } // clang-format off - checkMetrics(*this, env, 6, 6, 4, 3, baseFeeLevel.fee() * aliceFeeMultiplier + 1); + checkMetrics(*this, env, 6, 6, 4, 3, (baseFeeLevel.fee() * aliceFeeMultiplier) + 1); // clang-format on // Carol submits high enough to beat Bob's average fee which kicks @@ -2632,7 +2632,7 @@ public: // Start by procuring tickets for alice to use to keep her queue full // without affecting the sequence gap that will appear later. - env(ticket::create(alice, 11), seq(aliceSeq + 0), fee(baseFee * 20 + 1), ter(terQUEUED)); + env(ticket::create(alice, 11), seq(aliceSeq + 0), fee((baseFee * 20) + 1), ter(terQUEUED)); env(noop(alice), seq(aliceSeq + 11), last_ledger_seq(11), ter(terQUEUED)); env(noop(alice), seq(aliceSeq + 12), last_ledger_seq(11), ter(terQUEUED)); env(noop(alice), seq(aliceSeq + 13), last_ledger_seq(11), ter(terQUEUED)); @@ -4083,7 +4083,7 @@ public: // Use fees to guarantee order int txFee{static_cast(baseFee * 9)}; auto prepareFee = [&](uint64_t multiplier) { - return fee(txFee - multiplier * baseFee / 10); + return fee(txFee - (multiplier * baseFee / 10)); }; uint64_t multiplier = 0; diff --git a/src/test/app/ValidatorList_test.cpp b/src/test/app/ValidatorList_test.cpp index 32e899ad95..c4229514a1 100644 --- a/src/test/app/ValidatorList_test.cpp +++ b/src/test/app/ValidatorList_test.cpp @@ -98,7 +98,7 @@ private: masterPublic, secret, signingKeys.first, signingKeys.second, 1))}; } - std::string + static std::string makeList( std::vector const& validators, std::size_t sequence, @@ -122,7 +122,7 @@ private: return base64_encode(data); } - std::string + static std::string signList(std::string const& blob, std::pair const& keys) { auto const data = base64_decode(blob); @@ -379,7 +379,7 @@ private: BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgPublishers)); for (auto const& key : keys) BEAST_EXPECT(trustedKeys->trustedPublisher(key)); - BEAST_EXPECT(trustedKeys->getListThreshold() == keys.size() / 2 + 1); + BEAST_EXPECT(trustedKeys->getListThreshold() == (keys.size() / 2) + 1); } { ManifestCache manifests; @@ -561,10 +561,10 @@ private: auto const manifest1 = base64_encode(makeManifestString( publisherPublic, publisherSecret, pubSigningKeys1.first, pubSigningKeys1.second, 1)); - std::vector cfgKeys1({strHex(publisherPublic)}); + std::vector cfgPublisherKeys({strHex(publisherPublic)}); std::vector emptyCfgKeys; - BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgKeys1)); + BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgPublisherKeys)); std::map> const lists = []() { auto constexpr listSize = 20; @@ -907,10 +907,10 @@ private: auto const manifest = base64_encode(makeManifestString( publisherPublic, publisherSecret, pubSigningKeys1.first, pubSigningKeys1.second, 1)); - std::vector cfgKeys1({strHex(publisherPublic)}); + std::vector cfgPublisherKeys({strHex(publisherPublic)}); std::vector emptyCfgKeys; - BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgKeys1)); + BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgPublisherKeys)); std::vector const list = []() { auto constexpr listSize = 20; @@ -1324,9 +1324,9 @@ private: pubSigningKeys.second, 1)); - std::vector cfgKeys({strHex(publisherKeys.first)}); + std::vector cfgPublisherKeys({strHex(publisherKeys.first)}); - BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgKeys)); + BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgPublisherKeys)); std::vector list({randomValidator(), randomValidator()}); hash_set activeValidators( diff --git a/src/test/app/ValidatorSite_test.cpp b/src/test/app/ValidatorSite_test.cpp index c47c93c426..f1e3b57b1e 100644 --- a/src/test/app/ValidatorSite_test.cpp +++ b/src/test/app/ValidatorSite_test.cpp @@ -240,7 +240,7 @@ private: sink.messages().str()); } - if (u.cfg.expectedRefreshMin) + if (u.cfg.expectedRefreshMin != 0) { BEAST_EXPECTS( myStatus[jss::refresh_interval_min].asInt() == u.cfg.expectedRefreshMin, diff --git a/src/test/app/Vault_test.cpp b/src/test/app/Vault_test.cpp index 27a8d3b2e0..fa935eba6e 100644 --- a/src/test/app/Vault_test.cpp +++ b/src/test/app/Vault_test.cpp @@ -1898,7 +1898,7 @@ class Vault_test : public beast::unit_test::suite env.close(); } }, - {.requireAuth = false, .initialXRP = acctReserve + incReserve * 4 + 1}); + {.requireAuth = false, .initialXRP = acctReserve + (incReserve * 4) + 1}); testCase([this]( Env& env, @@ -2745,7 +2745,7 @@ class Vault_test : public beast::unit_test::suite env(vault.withdraw( {.depositor = owner, .id = keylet.key, - .amount = asset(Number(1000 + 37 * 5, -1))})); + .amount = asset(Number(1000 + (37 * 5), -1))})); { BEAST_EXPECT(env.balance(owner, asset) == startingOwnerBalance.value()); @@ -2808,7 +2808,7 @@ class Vault_test : public beast::unit_test::suite env(tx); env.close(); }, - CaseArgs{.initialXRP = acctReserve + incReserve * 4 + 1}); + CaseArgs{.initialXRP = acctReserve + (incReserve * 4) + 1}); testCase( [&, this]( @@ -2843,7 +2843,7 @@ class Vault_test : public beast::unit_test::suite env(tx); env.close(); }, - CaseArgs{.initialXRP = acctReserve + incReserve * 4 + 1}); + CaseArgs{.initialXRP = acctReserve + (incReserve * 4) + 1}); testCase([&, this]( Env& env, diff --git a/src/test/app/XChain_test.cpp b/src/test/app/XChain_test.cpp index b90ff49a84..72f2597883 100644 --- a/src/test/app/XChain_test.cpp +++ b/src/test/app/XChain_test.cpp @@ -3856,7 +3856,7 @@ private: auto& c = counters[bridge]; auto& create_claims = claims.create_claims[c.claim_count]; auto num_attns = create_claims.size(); - if (num_attns) + if (num_attns != 0u) { c.num_create_attn_sent += sendCreateAttestations(i, bridge, create_claims); diff --git a/src/test/basics/Buffer_test.cpp b/src/test/basics/Buffer_test.cpp index f5f626133f..a329e527ba 100644 --- a/src/test/basics/Buffer_test.cpp +++ b/src/test/basics/Buffer_test.cpp @@ -9,8 +9,8 @@ namespace test { struct Buffer_test : beast::unit_test::suite { - bool - sane(Buffer const& b) const + static bool + sane(Buffer const& b) { if (b.empty()) return b.data() == nullptr; diff --git a/src/test/basics/Number_test.cpp b/src/test/basics/Number_test.cpp index fb434a0182..4676884660 100644 --- a/src/test/basics/Number_test.cpp +++ b/src/test/basics/Number_test.cpp @@ -279,7 +279,7 @@ public: {Number{Number::maxRep}, Number{6, -1}, Number{Number::maxRep - 1}}, {Number{false, Number::maxRep + 1, 0, Number::normalized{}}, Number{1, 0}, - Number{Number::maxRep / 10 + 1, 1}}, + Number{(Number::maxRep / 10) + 1, 1}}, {Number{false, Number::maxRep + 1, 0, Number::normalized{}}, Number{3, 0}, Number{Number::maxRep}}, @@ -456,7 +456,7 @@ public: // 99'999'999'999'999'999'800'000'000'000'000'000'100 {Number{false, maxMantissa, 0, Number::normalized{}}, Number{false, maxMantissa, 0, Number::normalized{}}, - Number{false, maxMantissa / 10 - 1, 20, Number::normalized{}}}, + Number{false, (maxMantissa / 10) - 1, 20, Number::normalized{}}}, // Maximum int64 range // 85'070'591'730'234'615'847'396'907'784'232'501'249 {Number{Number::maxRep, 0}, @@ -523,7 +523,7 @@ public: // 99'999'999'999'999'999'800'000'000'000'000'000'100 {Number{false, maxMantissa, 0, Number::normalized{}}, Number{false, maxMantissa, 0, Number::normalized{}}, - Number{false, maxMantissa / 10 - 1, 20, Number::normalized{}}}, + Number{false, (maxMantissa / 10) - 1, 20, Number::normalized{}}}, // Maximum int64 range // 85'070'591'730'234'615'847'396'907'784'232'501'249 {Number{Number::maxRep, 0}, @@ -1238,10 +1238,10 @@ public: auto const maxMantissa = Number::maxMantissa(); BEAST_EXPECT(maxMantissa == 9'999'999'999'999'999); test( - Number{false, maxMantissa * 1000 + 999, -3, Number::normalized()}, + Number{false, (maxMantissa * 1000) + 999, -3, Number::normalized()}, "9999999999999999"); test( - Number{true, maxMantissa * 1000 + 999, -3, Number::normalized()}, + Number{true, (maxMantissa * 1000) + 999, -3, Number::normalized()}, "-9999999999999999"); test(Number{std::numeric_limits::max(), -3}, "9223372036854775"); @@ -1537,7 +1537,7 @@ public: // 99'999'999'999'999'999'800'000'000'000'000'000'100 - also 38 // digits BEAST_EXPECT( - (power(max, 2) == Number{false, maxMantissa / 10 - 1, 20, Number::normalized{}})); + (power(max, 2) == Number{false, (maxMantissa / 10) - 1, 20, Number::normalized{}})); } } diff --git a/src/test/basics/PerfLog_test.cpp b/src/test/basics/PerfLog_test.cpp index ce0109c53d..1647ce241e 100644 --- a/src/test/basics/PerfLog_test.cpp +++ b/src/test/basics/PerfLog_test.cpp @@ -63,21 +63,21 @@ class PerfLog_test : public beast::unit_test::suite stopSignaled = true; } - path - logDir() const + static path + logDir() { using namespace boost::filesystem; return temp_directory_path() / "perf_log_test_dir"; } - path - logFile() const + static path + logFile() { return logDir() / "perf_log.txt"; } - std::chrono::milliseconds - logInterval() const + static std::chrono::milliseconds + logInterval() { return std::chrono::milliseconds{10}; } @@ -96,8 +96,8 @@ class PerfLog_test : public beast::unit_test::suite // Block until the log file has grown in size, indicating that the // PerfLog has written new values to the file and _should_ have the // latest update. - void - wait() const + static void + wait() { using namespace boost::filesystem; diff --git a/src/test/basics/base58_test.cpp b/src/test/basics/base58_test.cpp index ca62ac02ef..52d06b324d 100644 --- a/src/test/basics/base58_test.cpp +++ b/src/test/basics/base58_test.cpp @@ -162,7 +162,7 @@ class base58_test : public beast::unit_test::suite for (int i = 0; i < iters; ++i) { std::uint64_t const d = dist(eng); - if (!d) + if (d == 0u) continue; auto bigInt = multiprecision_utils::randomBigInt(); auto const boostBigInt = multiprecision_utils::toBoostMP( diff --git a/src/test/beast/aged_associative_container_test.cpp b/src/test/beast/aged_associative_container_test.cpp index 690f03cd49..22b677a7e5 100644 --- a/src/test/beast/aged_associative_container_test.cpp +++ b/src/test/beast/aged_associative_container_test.cpp @@ -523,7 +523,7 @@ public: testArrayCreate(); template - typename std::enable_if::type + typename std::enable_if::type testArrayCreate() { } diff --git a/src/test/consensus/Consensus_test.cpp b/src/test/consensus/Consensus_test.cpp index a096b82365..3550717a4d 100644 --- a/src/test/consensus/Consensus_test.cpp +++ b/src/test/consensus/Consensus_test.cpp @@ -1295,10 +1295,10 @@ public: for (int i = 0; i < 1; ++i) { - BEAST_EXPECT(!proposingTrue.updateVote(250 + 10 * i, true, p)); - BEAST_EXPECT(!proposingFalse.updateVote(250 + 10 * i, true, p)); - BEAST_EXPECT(!followingTrue.updateVote(250 + 10 * i, false, p)); - BEAST_EXPECT(!followingFalse.updateVote(250 + 10 * i, false, p)); + BEAST_EXPECT(!proposingTrue.updateVote(250 + (10 * i), true, p)); + BEAST_EXPECT(!proposingFalse.updateVote(250 + (10 * i), true, p)); + BEAST_EXPECT(!followingTrue.updateVote(250 + (10 * i), false, p)); + BEAST_EXPECT(!followingFalse.updateVote(250 + (10 * i), false, p)); BEAST_EXPECT(proposingTrue.getOurVote() == true); BEAST_EXPECT(proposingFalse.getOurVote() == false); @@ -1333,10 +1333,10 @@ public: } for (int i = 1; i < 3; ++i) { - BEAST_EXPECT(!proposingTrue.updateVote(250 + 10 * i, true, p)); - BEAST_EXPECT(!proposingFalse.updateVote(250 + 10 * i, true, p)); - BEAST_EXPECT(!followingTrue.updateVote(250 + 10 * i, false, p)); - BEAST_EXPECT(!followingFalse.updateVote(250 + 10 * i, false, p)); + BEAST_EXPECT(!proposingTrue.updateVote(250 + (10 * i), true, p)); + BEAST_EXPECT(!proposingFalse.updateVote(250 + (10 * i), true, p)); + BEAST_EXPECT(!followingTrue.updateVote(250 + (10 * i), false, p)); + BEAST_EXPECT(!followingFalse.updateVote(250 + (10 * i), false, p)); BEAST_EXPECT(proposingTrue.getOurVote() == true); BEAST_EXPECT(proposingFalse.getOurVote() == false); @@ -1369,10 +1369,10 @@ public: } for (int i = 3; i < 5; ++i) { - BEAST_EXPECT(!proposingTrue.updateVote(250 + 10 * i, true, p)); - BEAST_EXPECT(!proposingFalse.updateVote(250 + 10 * i, true, p)); - BEAST_EXPECT(!followingTrue.updateVote(250 + 10 * i, false, p)); - BEAST_EXPECT(!followingFalse.updateVote(250 + 10 * i, false, p)); + BEAST_EXPECT(!proposingTrue.updateVote(250 + (10 * i), true, p)); + BEAST_EXPECT(!proposingFalse.updateVote(250 + (10 * i), true, p)); + BEAST_EXPECT(!followingTrue.updateVote(250 + (10 * i), false, p)); + BEAST_EXPECT(!followingFalse.updateVote(250 + (10 * i), false, p)); BEAST_EXPECT(proposingTrue.getOurVote() == true); BEAST_EXPECT(proposingFalse.getOurVote() == false); diff --git a/src/test/consensus/NegativeUNL_test.cpp b/src/test/consensus/NegativeUNL_test.cpp index 46c6936809..019d8ee545 100644 --- a/src/test/consensus/NegativeUNL_test.cpp +++ b/src/test/consensus/NegativeUNL_test.cpp @@ -782,7 +782,7 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite history.walkHistoryAndAddValidations( [&](std::shared_ptr const& l, std::size_t idx) -> bool { // skip half my validations. - return !(history.UNLNodeIDs[idx] == myId && l->seq() % 2 == 0); + return history.UNLNodeIDs[idx] != myId || l->seq() % 2 != 0; }); NegativeUNLVote vote(myId, history.env.journal); BEAST_EXPECT(!vote.buildScoreTable( @@ -890,7 +890,7 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite * @param numReEnable number of ReEnable candidates expected * @return true if the number of candidates meets expectation */ - bool + static bool checkCandidateSizes( NegativeUNLVote& vote, hash_set const& unl, diff --git a/src/test/core/ClosureCounter_test.cpp b/src/test/core/ClosureCounter_test.cpp index fe3f0a219f..736b833d76 100644 --- a/src/test/core/ClosureCounter_test.cpp +++ b/src/test/core/ClosureCounter_test.cpp @@ -299,7 +299,7 @@ class ClosureCounter_test : public beast::unit_test::suite BEAST_EXPECT(voidCounter.count() == 0); // Wait for the thread to exit. - while (threadExited == false) + while (!threadExited) ; localThread.join(); } diff --git a/src/test/core/Config_test.cpp b/src/test/core/Config_test.cpp index e9f7354482..edcb67b767 100644 --- a/src/test/core/Config_test.cpp +++ b/src/test/core/Config_test.cpp @@ -358,8 +358,8 @@ port_wss_admin "/Users/dummy/xrpld/config/log/debug.log"); // Restore the environment variables. - h ? setenv("HOME", h, 1) : unsetenv("HOME"); - x ? setenv("XDG_CONFIG_HOME", x, 1) : unsetenv("XDG_CONFIG_HOME"); + (h != nullptr) ? setenv("HOME", h, 1) : unsetenv("HOME"); + (x != nullptr) ? setenv("XDG_CONFIG_HOME", x, 1) : unsetenv("XDG_CONFIG_HOME"); } // The XDG config directory is not set: the config file must be in a @@ -394,8 +394,8 @@ port_wss_admin "/Users/dummy/xrpld/config/log/debug.log"); // Restore the environment variables. - h ? setenv("HOME", h, 1) : unsetenv("HOME"); - if (x) + (h != nullptr) ? setenv("HOME", h, 1) : unsetenv("HOME"); + if (x != nullptr) setenv("XDG_CONFIG_HOME", x, 1); } } diff --git a/src/test/core/JobQueue_test.cpp b/src/test/core/JobQueue_test.cpp index bf6a5590e6..13142c299f 100644 --- a/src/test/core/JobQueue_test.cpp +++ b/src/test/core/JobQueue_test.cpp @@ -23,7 +23,7 @@ class JobQueue_test : public beast::unit_test::suite jQueue.addJob(jtCLIENT, "JobAddTest1", [&jobRan]() { jobRan = true; }) == true); // Wait for the Job to run. - while (jobRan == false) + while (!jobRan) ; } { diff --git a/src/test/csf/Sim.h b/src/test/csf/Sim.h index 3525258c59..e5f64cae1f 100644 --- a/src/test/csf/Sim.h +++ b/src/test/csf/Sim.h @@ -129,8 +129,8 @@ public: Nodes in the group are synchronized if they share the same last fully validated and last generated ledger. */ - bool - synchronized(PeerGroup const& g) const; + static bool + synchronized(PeerGroup const& g); /** Check whether all peers in the network are synchronized */ diff --git a/src/test/csf/impl/Sim.cpp b/src/test/csf/impl/Sim.cpp index 4fbee56f0f..a775dd30ff 100644 --- a/src/test/csf/impl/Sim.cpp +++ b/src/test/csf/impl/Sim.cpp @@ -33,7 +33,7 @@ Sim::synchronized() const } bool -Sim::synchronized(PeerGroup const& g) const +Sim::synchronized(PeerGroup const& g) { if (g.size() < 1) return true; diff --git a/src/test/csf/impl/ledgers.cpp b/src/test/csf/impl/ledgers.cpp index 33e9b123c5..2c5bf07880 100644 --- a/src/test/csf/impl/ledgers.cpp +++ b/src/test/csf/impl/ledgers.cpp @@ -123,7 +123,7 @@ LedgerOracle::lookup(Ledger::ID const& id) const } std::size_t -LedgerOracle::branches(std::set const& ledgers) const +LedgerOracle::branches(std::set const& ledgers) { // Tips always maintains the Ledgers with largest sequence number // along all known chains. diff --git a/src/test/csf/ledgers.h b/src/test/csf/ledgers.h index 9da1c2182a..6e50f3584b 100644 --- a/src/test/csf/ledgers.h +++ b/src/test/csf/ledgers.h @@ -278,8 +278,8 @@ public: O \--> B */ - std::size_t - branches(std::set const& ledgers) const; + static std::size_t + branches(std::set const& ledgers); }; /** Helper for writing unit tests with controlled ledger histories. diff --git a/src/test/jtx/AMMTest.h b/src/test/jtx/AMMTest.h index 78e26b9e40..dd18733ffd 100644 --- a/src/test/jtx/AMMTest.h +++ b/src/test/jtx/AMMTest.h @@ -96,11 +96,11 @@ protected: class AMMTest : public jtx::AMMTestBase { protected: - XRPAmount - reserve(jtx::Env& env, std::uint32_t count) const; + static XRPAmount + reserve(jtx::Env& env, std::uint32_t count); - XRPAmount - ammCrtFee(jtx::Env& env) const; + static XRPAmount + ammCrtFee(jtx::Env& env); /* Path_test */ /************************************************/ diff --git a/src/test/jtx/Env.h b/src/test/jtx/Env.h index 2ac0ca7435..a103d42ca3 100644 --- a/src/test/jtx/Env.h +++ b/src/test/jtx/Env.h @@ -510,6 +510,7 @@ public: */ // VFALCO NOTE This should return a unit-less amount PrettyAmount + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) balance(Account const& account, Asset const& asset) const; PrettyAmount diff --git a/src/test/jtx/Env_test.cpp b/src/test/jtx/Env_test.cpp index bd40ac9a81..51abac8101 100644 --- a/src/test/jtx/Env_test.cpp +++ b/src/test/jtx/Env_test.cpp @@ -28,7 +28,7 @@ public: } // Declarations in Account.h - void + static void testAccount() { using namespace jtx; diff --git a/src/test/jtx/impl/AMM.cpp b/src/test/jtx/impl/AMM.cpp index 6b2042efda..ccad604070 100644 --- a/src/test/jtx/impl/AMM.cpp +++ b/src/test/jtx/impl/AMM.cpp @@ -443,7 +443,7 @@ AMM::deposit( // If including asset1In and asset2In or tokens as // deposit min amounts then must set the flags // explicitly instead of relying on this logic. - if (!(jvFlags & tfDepositSubTx)) + if ((jvFlags & tfDepositSubTx) == 0u) { if (tokens && !asset1In) { @@ -573,7 +573,7 @@ AMM::withdraw( std::uint32_t jvFlags = 0; if (flags) jvFlags = *flags; - if (!(jvFlags & tfWithdrawSubTx)) + if ((jvFlags & tfWithdrawSubTx) == 0u) { if (tokens && !asset1Out) { diff --git a/src/test/jtx/impl/AMMTest.cpp b/src/test/jtx/impl/AMMTest.cpp index ab8c1578a3..6b8807076a 100644 --- a/src/test/jtx/impl/AMMTest.cpp +++ b/src/test/jtx/impl/AMMTest.cpp @@ -149,13 +149,13 @@ AMMTestBase::testAMM(std::function const& cb, TestAM } XRPAmount -AMMTest::reserve(jtx::Env& env, std::uint32_t count) const +AMMTest::reserve(jtx::Env& env, std::uint32_t count) { return env.current()->fees().accountReserve(count); } XRPAmount -AMMTest::ammCrtFee(jtx::Env& env) const +AMMTest::ammCrtFee(jtx::Env& env) { return env.current()->fees().increment; } diff --git a/src/test/jtx/impl/Env.cpp b/src/test/jtx/impl/Env.cpp index 3217f67cbe..6967b48518 100644 --- a/src/test/jtx/impl/Env.cpp +++ b/src/test/jtx/impl/Env.cpp @@ -76,7 +76,7 @@ Env::AppBundle::~AppBundle() client.reset(); // Make sure all jobs finish, otherwise tests // might not get the coverage they expect. - if (app) + if (app != nullptr) { app->getJobQueue().rendezvous(); app->signalStop("~AppBundle"); @@ -218,6 +218,7 @@ Env::balance(Account const& account, MPTIssue const& mptIssue) const } PrettyAmount +// NOLINTNEXTLINE(readability-convert-member-functions-to-static) Env::balance(Account const& account, Asset const& asset) const { return std::visit([&](auto const& issue) { return balance(account, issue); }, asset.value()); @@ -468,7 +469,7 @@ Env::postconditions( // we didn't get the expected result. return; } - if (trace_) + if (trace_ != 0) { if (trace_ > 0) --trace_; diff --git a/src/test/jtx/impl/Oracle.cpp b/src/test/jtx/impl/Oracle.cpp index 8bc456cd4e..0c9ddc8f0d 100644 --- a/src/test/jtx/impl/Oracle.cpp +++ b/src/test/jtx/impl/Oracle.cpp @@ -258,7 +258,7 @@ Oracle::set(UpdateArg const& arg) return s; assert(s.size() <= 20); // anything else must be 160-bit hex string - return strHex(s).append(40 - s.size() * 2, '0'); + return strHex(s).append(40 - (s.size() * 2), '0'); }; for (auto const& data : arg.series) { diff --git a/src/test/jtx/impl/mpt.cpp b/src/test/jtx/impl/mpt.cpp index a6283bb6f9..933aabce30 100644 --- a/src/test/jtx/impl/mpt.cpp +++ b/src/test/jtx/impl/mpt.cpp @@ -370,7 +370,7 @@ MPTTester::set(MPTSet const& arg) .metadata = arg.metadata, .delegate = arg.delegate, .domainID = arg.domainID}); - if (submit(arg, jv) == tesSUCCESS && (arg.flags.value_or(0) || arg.mutableFlags)) + if (submit(arg, jv) == tesSUCCESS && ((arg.flags.value_or(0) != 0u) || arg.mutableFlags)) { auto require = [&](std::optional const& holder, bool unchanged) { auto flags = getFlags(holder); diff --git a/src/test/jtx/impl/multisign.cpp b/src/test/jtx/impl/multisign.cpp index ae39382824..02550b803c 100644 --- a/src/test/jtx/impl/multisign.cpp +++ b/src/test/jtx/impl/multisign.cpp @@ -83,7 +83,7 @@ msig::operator()(Env& env, JTx& jt) const jo[sfTxnSignature.getJsonName()] = strHex(Slice{sig.data(), sig.size()}); } }; - if (!subField) + if (subField == nullptr) { jt.mainSigners.emplace_back(callback); } diff --git a/src/test/jtx/impl/offer.cpp b/src/test/jtx/impl/offer.cpp index 251b659f3b..5a2264601a 100644 --- a/src/test/jtx/impl/offer.cpp +++ b/src/test/jtx/impl/offer.cpp @@ -17,7 +17,7 @@ offer( jv[jss::Account] = account.human(); jv[jss::TakerPays] = takerPays.getJson(JsonOptions::none); jv[jss::TakerGets] = takerGets.getJson(JsonOptions::none); - if (flags) + if (flags != 0u) jv[jss::Flags] = flags; jv[jss::TransactionType] = jss::OfferCreate; return jv; diff --git a/src/test/jtx/impl/sig.cpp b/src/test/jtx/impl/sig.cpp index 850c5af781..1bdadc0bd3 100644 --- a/src/test/jtx/impl/sig.cpp +++ b/src/test/jtx/impl/sig.cpp @@ -10,7 +10,7 @@ sig::operator()(Env&, JTx& jt) const { if (!manual_) return; - if (!subField_) + if (subField_ == nullptr) jt.fill_sig = false; if (account_) { @@ -22,7 +22,7 @@ sig::operator()(Env&, JTx& jt) const jtx::sign(jtx.jv, account, sigObject); }; - if (!subField_) + if (subField_ == nullptr) { jt.mainSigners.emplace_back(callback); } diff --git a/src/test/jtx/vault.h b/src/test/jtx/vault.h index 43f975323a..748d3341a5 100644 --- a/src/test/jtx/vault.h +++ b/src/test/jtx/vault.h @@ -38,7 +38,7 @@ struct Vault uint256 id; }; - Json::Value + static Json::Value set(SetArgs const& args); struct DeleteArgs @@ -47,7 +47,7 @@ struct Vault uint256 id; }; - Json::Value + static Json::Value del(DeleteArgs const& args); struct DepositArgs @@ -57,7 +57,7 @@ struct Vault STAmount amount; }; - Json::Value + static Json::Value deposit(DepositArgs const& args); struct WithdrawArgs @@ -67,7 +67,7 @@ struct Vault STAmount amount; }; - Json::Value + static Json::Value withdraw(WithdrawArgs const& args); struct ClawbackArgs @@ -78,7 +78,7 @@ struct Vault std::optional amount{}; }; - Json::Value + static Json::Value clawback(ClawbackArgs const& args); }; diff --git a/src/test/ledger/Directory_test.cpp b/src/test/ledger/Directory_test.cpp index 18649a20a8..b08e7daaf6 100644 --- a/src/test/ledger/Directory_test.cpp +++ b/src/test/ledger/Directory_test.cpp @@ -37,7 +37,7 @@ struct Directory_test : public beast::unit_test::suite // Insert n empty pages, numbered [0, ... n - 1], in the // specified directory: - void + static void makePages(Sandbox& sb, uint256 const& base, std::uint64_t n) { for (std::uint64_t i = 0; i < n; ++i) @@ -274,7 +274,7 @@ struct Directory_test : public beast::unit_test::suite { for (int i = 0; i < dirNodeMaxEntries; ++i) { - env(offer_cancel(alice, firstOfferSeq + page * dirNodeMaxEntries + i)); + env(offer_cancel(alice, firstOfferSeq + (page * dirNodeMaxEntries) + i)); env.close(); } } diff --git a/src/test/nodestore/NuDBFactory_test.cpp b/src/test/nodestore/NuDBFactory_test.cpp index 9a9b7d83bd..0aa910ce01 100644 --- a/src/test/nodestore/NuDBFactory_test.cpp +++ b/src/test/nodestore/NuDBFactory_test.cpp @@ -17,7 +17,7 @@ class NuDBFactory_test : public TestBase { private: // Helper function to create a Section with specified parameters - Section + static Section createSection(std::string const& path, std::string const& blockSize = "") { Section params; diff --git a/src/test/nodestore/Timing_test.cpp b/src/test/nodestore/Timing_test.cpp index d5c89dbcc9..fc8c042252 100644 --- a/src/test/nodestore/Timing_test.cpp +++ b/src/test/nodestore/Timing_test.cpp @@ -111,7 +111,7 @@ public: { b.clear(); b.reserve(size); - while (size--) + while ((size--) != 0u) b.emplace_back(obj(n++)); } }; @@ -524,7 +524,7 @@ public: , seq1_(1) , gen_(id + 1) , rand_(0, 99) - , recent_(params.items, params.items * 2 - 1) + , recent_(params.items, (params.items * 2) - 1) , older_(0, params.items - 1) { } @@ -643,7 +643,7 @@ public: Params params{}; params.items = default_items; params.threads = threads; - for (auto i = default_repeat; i--;) + for (auto i = default_repeat; (i--) != 0u;) { beast::temp_dir tempDir; Section config = parse(config_string); diff --git a/src/test/nodestore/import_test.cpp b/src/test/nodestore/import_test.cpp index e5f281486b..54d55e5ad0 100644 --- a/src/test/nodestore/import_test.cpp +++ b/src/test/nodestore/import_test.cpp @@ -333,7 +333,7 @@ public: options.max_open_files = 2000; // 5000? rocksdb::DB* pdb = nullptr; rocksdb::Status status = rocksdb::DB::OpenForReadOnly(options, from_path, &pdb); - if (!status.ok() || !pdb) + if (!status.ok() || (pdb == nullptr)) Throw("Can't open '" + from_path + "': " + status.ToString()); db.reset(pdb); } @@ -458,7 +458,7 @@ public: // Create empty buckets for (std::size_t i = 0; i < bn; ++i) { - bucket b(kh.block_size, buf.get() + i * kh.block_size, empty); + bucket b(kh.block_size, buf.get() + (i * kh.block_size), empty); } // Insert all keys into buckets // Iterate Data File @@ -484,10 +484,10 @@ public: std::uint8_t const* const key = is.data(dh.key_size); auto const h = hash(key, kh.key_size, kh.salt); auto const n = bucket_index(h, kh.buckets, kh.modulus); - p(log, npass * df_size + r.offset()); + p(log, (npass * df_size) + r.offset()); if (n < b0 || n >= b1) continue; - bucket b(kh.block_size, buf.get() + (n - b0) * kh.block_size); + bucket b(kh.block_size, buf.get() + ((n - b0) * kh.block_size)); maybe_spill(b, dw, ec); if (ec) Throw(ec); diff --git a/src/test/overlay/TMGetObjectByHash_test.cpp b/src/test/overlay/TMGetObjectByHash_test.cpp index 0624c7b088..b899ceb084 100644 --- a/src/test/overlay/TMGetObjectByHash_test.cpp +++ b/src/test/overlay/TMGetObjectByHash_test.cpp @@ -121,7 +121,7 @@ class TMGetObjectByHash_test : public beast::unit_test::suite return peer; } - std::shared_ptr + static std::shared_ptr createRequest(size_t const numObjects, Env& env) { // Store objects in the NodeStore that will be found during the query diff --git a/src/test/overlay/cluster_test.cpp b/src/test/overlay/cluster_test.cpp index 6fa4604f78..59fa22a442 100644 --- a/src/test/overlay/cluster_test.cpp +++ b/src/test/overlay/cluster_test.cpp @@ -29,7 +29,7 @@ public: return cluster; } - PublicKey + static PublicKey randomNode() { return derivePublicKey(KeyType::secp256k1, randomSecretKey()); diff --git a/src/test/overlay/compression_test.cpp b/src/test/overlay/compression_test.cpp index f784a91350..38b60c2251 100644 --- a/src/test/overlay/compression_test.cpp +++ b/src/test/overlay/compression_test.cpp @@ -117,7 +117,7 @@ public: decompressed.begin())); } - std::shared_ptr + static std::shared_ptr buildManifests(int n) { auto manifests = std::make_shared(); @@ -143,7 +143,7 @@ public: return manifests; } - std::shared_ptr + static std::shared_ptr buildEndpoints(int n) { auto endpoints = std::make_shared(); @@ -196,7 +196,7 @@ public: return transaction; } - std::shared_ptr + static std::shared_ptr buildGetLedger() { auto getLedger = std::make_shared(); @@ -213,7 +213,7 @@ public: return getLedger; } - std::shared_ptr + static std::shared_ptr buildLedgerData(uint32_t n, Logs& logs) { auto ledgerData = std::make_shared(); @@ -251,7 +251,7 @@ public: return ledgerData; } - std::shared_ptr + static std::shared_ptr buildGetObjectByHash() { auto getObject = std::make_shared(); @@ -277,7 +277,7 @@ public: return getObject; } - std::shared_ptr + static std::shared_ptr buildValidatorList() { auto list = std::make_shared(); @@ -304,7 +304,7 @@ public: return list; } - std::shared_ptr + static std::shared_ptr buildValidatorListCollection() { auto list = std::make_shared(); diff --git a/src/test/overlay/reduce_relay_test.cpp b/src/test/overlay/reduce_relay_test.cpp index 8e50415aa9..b4a47bac53 100644 --- a/src/test/overlay/reduce_relay_test.cpp +++ b/src/test/overlay/reduce_relay_test.cpp @@ -362,7 +362,7 @@ public: { for (auto id : peers) { - assert(links_.find(id) != links_.end()); + assert(links_.contains(id)); f(*links_[id], message_); } } @@ -637,7 +637,7 @@ public: getSelectedPeer(PublicKey const& validator) { auto selected = slots_.getSelected(validator); - assert(selected.size()); + assert(!selected.empty()); return *selected.begin(); } @@ -785,7 +785,7 @@ public: } } - void + static void for_rand(std::uint32_t min, std::uint32_t max, std::function f) { auto size = max - min; @@ -879,14 +879,14 @@ protected: } /** Send squelch (if duration is set) or unsquelch (if duration not set) */ - Peer::id_t + static Peer::id_t sendSquelch( PublicKey const& validator, PeerWPtr const& peerPtr, std::optional duration) { protocol::TMSquelch squelch; - bool res = duration ? true : false; + bool res = static_cast(duration); squelch.set_squelch(res); squelch.set_validatorpubkey(validator.data(), validator.size()); if (res) @@ -1004,8 +1004,8 @@ protected: // take place because there is no peers in Squelched state in // any of the slots where the peer is in Selected state // (allCounting is true) - bool handled = (event.isSelected_ == false && !event.handled_) || - (event.isSelected_ == true && (event.handled_ || allCounting)); + bool handled = (!event.isSelected_ && !event.handled_) || + (event.isSelected_ && (event.handled_ || allCounting)); BEAST_EXPECT(handled); event.state_ = State::Off; event.isSelected_ = false; @@ -1499,7 +1499,7 @@ vp_base_squelch_max_selected_peers=2 { // make unique message hash to make the // slot's internal hash router accept the message - std::uint64_t mid = m * 1000 + peer; + std::uint64_t mid = (m * 1000) + peer; uint256 const message{mid}; slots.updateSlotAndSquelch( message, validator, peer, protocol::MessageType::mtVALIDATION); diff --git a/src/test/protocol/PublicKey_test.cpp b/src/test/protocol/PublicKey_test.cpp index 053e945a7b..79c1356bb4 100644 --- a/src/test/protocol/PublicKey_test.cpp +++ b/src/test/protocol/PublicKey_test.cpp @@ -46,7 +46,7 @@ public: } } - blob + static blob sig(std::string const& hex) { blob b; @@ -54,7 +54,7 @@ public: return b; } - bool + static bool check(std::optional answer, std::string const& s) { return ecdsaCanonicality(makeSlice(sig(s))) == answer; diff --git a/src/test/protocol/STAmount_test.cpp b/src/test/protocol/STAmount_test.cpp index c9382d508a..4f652dddd9 100644 --- a/src/test/protocol/STAmount_test.cpp +++ b/src/test/protocol/STAmount_test.cpp @@ -21,7 +21,7 @@ public: } //-------------------------------------------------------------------------- - STAmount + static STAmount roundSelf(STAmount const& amount) { if (amount.native()) diff --git a/src/test/protocol/STParsedJSON_test.cpp b/src/test/protocol/STParsedJSON_test.cpp index 18e695d25d..974975d05f 100644 --- a/src/test/protocol/STParsedJSON_test.cpp +++ b/src/test/protocol/STParsedJSON_test.cpp @@ -11,7 +11,7 @@ namespace xrpl { class STParsedJSON_test : public beast::unit_test::suite { - bool + static bool parseJSONString(std::string const& json, Json::Value& to) { Json::Reader reader; diff --git a/src/test/protocol/SeqProxy_test.cpp b/src/test/protocol/SeqProxy_test.cpp index 9096fe7daf..7e7a21ab6e 100644 --- a/src/test/protocol/SeqProxy_test.cpp +++ b/src/test/protocol/SeqProxy_test.cpp @@ -42,7 +42,7 @@ struct SeqProxy_test : public beast::unit_test::suite } // Verify streaming. - bool + static bool streamTest(SeqProxy seqProx) { std::string const type{seqProx.isSeq() ? "sequence" : "ticket"}; diff --git a/src/test/resource/Logic_test.cpp b/src/test/resource/Logic_test.cpp index c555b92860..6d412b000f 100644 --- a/src/test/resource/Logic_test.cpp +++ b/src/test/resource/Logic_test.cpp @@ -44,7 +44,7 @@ public: //-------------------------------------------------------------------------- - void + static void createGossip(Gossip& gossip) { std::uint8_t const v(10 + rand_int(9)); @@ -182,7 +182,7 @@ public: } } } - if (readmitted == false) + if (!readmitted) { fail("Dropped Consumer left on blacklist too long"); return; diff --git a/src/test/rpc/AccountObjects_test.cpp b/src/test/rpc/AccountObjects_test.cpp index 435bbd37d5..905f8f2bb7 100644 --- a/src/test/rpc/AccountObjects_test.cpp +++ b/src/test/rpc/AccountObjects_test.cpp @@ -1313,7 +1313,7 @@ public: auto resp = env.rpc("json", "account_objects", to_string(params)); auto& accountObjects = resp[jss::result][jss::account_objects]; BEAST_EXPECT(!resp[jss::result].isMember(jss::error)); - BEAST_EXPECT(accountObjects.size() == accountObjectSize - limit * 2); + BEAST_EXPECT(accountObjects.size() == accountObjectSize - (limit * 2)); BEAST_EXPECT(!resp[jss::result].isMember(jss::marker)); } diff --git a/src/test/rpc/Book_test.cpp b/src/test/rpc/Book_test.cpp index 8136af310a..41442edb06 100644 --- a/src/test/rpc/Book_test.cpp +++ b/src/test/rpc/Book_test.cpp @@ -15,7 +15,7 @@ namespace test { class Book_test : public beast::unit_test::suite { - std::string + static std::string getBookDir( jtx::Env& env, Issue const& in, @@ -1524,7 +1524,7 @@ public: auto USD = gw["USD"]; for (auto i = 0; i <= RPC::Tuning::bookOffers.rmax; i++) - env(offer(gw, XRP(50 + 1 * i), USD(1.0 + 0.1 * i))); + env(offer(gw, XRP(50 + (1 * i)), USD(1.0 + (0.1 * i)))); if (asAdmin) env.close(); diff --git a/src/test/rpc/DeliveredAmount_test.cpp b/src/test/rpc/DeliveredAmount_test.cpp index 00f8c54ee5..31b9b2aebf 100644 --- a/src/test/rpc/DeliveredAmount_test.cpp +++ b/src/test/rpc/DeliveredAmount_test.cpp @@ -76,7 +76,8 @@ public: bool checkExpectedCounters() const { - return !numExpectedAvailable_ && !numExpectedNotSet_ && !numExpectedSetUnavailable_; + return (numExpectedAvailable_ == 0) && (numExpectedNotSet_ == 0) && + (numExpectedSetUnavailable_ == 0); } // Check if the transaction has `delivered_amount` in the metaData as diff --git a/src/test/rpc/LedgerEntry_test.cpp b/src/test/rpc/LedgerEntry_test.cpp index eec114b71c..8f4a096e2a 100644 --- a/src/test/rpc/LedgerEntry_test.cpp +++ b/src/test/rpc/LedgerEntry_test.cpp @@ -131,7 +131,7 @@ class LedgerEntry_test : public beast::unit_test::suite } } - std::vector + static std::vector getBadValues(FieldType fieldType) { static Json::Value const injectObject = []() { @@ -225,7 +225,7 @@ class LedgerEntry_test : public beast::unit_test::suite } } - Json::Value + static Json::Value getCorrectValue(Json::StaticString fieldName) { static Json::Value const twoAccountArray = []() { diff --git a/src/test/rpc/LedgerRPC_test.cpp b/src/test/rpc/LedgerRPC_test.cpp index 2f4a63a090..8f965aa2cf 100644 --- a/src/test/rpc/LedgerRPC_test.cpp +++ b/src/test/rpc/LedgerRPC_test.cpp @@ -40,7 +40,7 @@ class LedgerRPC_test : public beast::unit_test::suite // Corrupt a valid address by replacing the 10th character with '!'. // '!' is not part of the ripple alphabet. - std::string + static std::string makeBadAddress(std::string good) { std::string ret = std::move(good); diff --git a/src/test/rpc/Roles_test.cpp b/src/test/rpc/Roles_test.cpp index a4f9de2284..e3d90a9c56 100644 --- a/src/test/rpc/Roles_test.cpp +++ b/src/test/rpc/Roles_test.cpp @@ -12,7 +12,7 @@ namespace test { class Roles_test : public beast::unit_test::suite { - bool + static bool isValidIpAddress(std::string const& addr) { boost::system::error_code ec; diff --git a/src/test/rpc/ServerInfo_test.cpp b/src/test/rpc/ServerInfo_test.cpp index 5bb2c31757..978b995ce8 100644 --- a/src/test/rpc/ServerInfo_test.cpp +++ b/src/test/rpc/ServerInfo_test.cpp @@ -93,7 +93,7 @@ admin = 127.0.0.1 Env env(*this); // Call NetworkOPs directly and set the admin flag to false. - auto const result = env.app().getOPs().getServerInfo(true, false, 0); + auto const result = env.app().getOPs().getServerInfo(true, false, false); // Expect that the admin ports are not included in the result. auto const& ports = result[jss::ports]; BEAST_EXPECT(ports.isArray() && ports.size() == 0); diff --git a/src/test/rpc/Simulate_test.cpp b/src/test/rpc/Simulate_test.cpp index 74f9b03111..e096b0479f 100644 --- a/src/test/rpc/Simulate_test.cpp +++ b/src/test/rpc/Simulate_test.cpp @@ -131,8 +131,8 @@ class Simulate_test : public beast::unit_test::suite BEAST_EXPECTS(env.current()->txCount() == 0, std::to_string(env.current()->txCount())); } - Json::Value - getJsonMetadata(Json::Value txResult) const + static Json::Value + getJsonMetadata(Json::Value txResult) { if (txResult.isMember(jss::meta_blob)) { diff --git a/src/test/rpc/Transaction_test.cpp b/src/test/rpc/Transaction_test.cpp index 2709900bf1..c53207e04d 100644 --- a/src/test/rpc/Transaction_test.cpp +++ b/src/test/rpc/Transaction_test.cpp @@ -19,7 +19,7 @@ namespace xrpl { class Transaction_test : public beast::unit_test::suite { - std::unique_ptr + static std::unique_ptr makeNetworkConfig(uint32_t networkID) { using namespace test::jtx; @@ -91,7 +91,7 @@ class Transaction_test : public beast::unit_test::suite result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == NOT_FOUND); - if (deltaEndSeq) + if (deltaEndSeq != 0) { BEAST_EXPECT(!result[jss::result][jss::searched_all].asBool()); } @@ -332,7 +332,7 @@ class Transaction_test : public beast::unit_test::suite result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == NOT_FOUND); - if (deltaEndSeq) + if (deltaEndSeq != 0) { BEAST_EXPECT(!result[jss::result][jss::searched_all].asBool()); } diff --git a/src/test/server/ServerStatus_test.cpp b/src/test/server/ServerStatus_test.cpp index 178b85b3e4..1a5da25d65 100644 --- a/src/test/server/ServerStatus_test.cpp +++ b/src/test/server/ServerStatus_test.cpp @@ -33,7 +33,7 @@ class ServerStatus_test : public beast::unit_test::suite, public beast::test::en { }; - auto + static auto makeConfig(std::string const& proto, bool admin = true, bool credentials = false) { auto const section_name = boost::starts_with(proto, "h") ? "port_rpc" : "port_ws"; @@ -69,7 +69,7 @@ class ServerStatus_test : public beast::unit_test::suite, public beast::test::en return p; } - auto + static auto makeWSUpgrade(std::string const& host, uint16_t port) { using namespace boost::asio; @@ -97,7 +97,7 @@ class ServerStatus_test : public beast::unit_test::suite, public beast::test::en return req; } - auto + static auto makeHTTPRequest( std::string const& host, uint16_t port, @@ -217,7 +217,7 @@ class ServerStatus_test : public beast::unit_test::suite, public beast::test::en return; } - auto + static auto makeAdminRequest( jtx::Env& env, std::string const& proto, diff --git a/src/test/server/Server_test.cpp b/src/test/server/Server_test.cpp index bce8bced60..b6ff180bd4 100644 --- a/src/test/server/Server_test.cpp +++ b/src/test/server/Server_test.cpp @@ -91,13 +91,13 @@ public: struct TestHandler { - bool + static bool onAccept(Session& session, boost::asio::ip::tcp::endpoint endpoint) { return true; } - Handoff + static Handoff onHandoff( Session& session, std::unique_ptr const& bundle, @@ -107,7 +107,7 @@ public: return Handoff{}; } - Handoff + static Handoff onHandoff( Session& session, http_request_type const& request, @@ -116,7 +116,7 @@ public: return Handoff{}; } - void + static void onRequest(Session& session) { session.write(std::string("Hello, world!\n")); @@ -303,13 +303,13 @@ public: testcase("stress test"); struct NullHandler { - bool + static bool onAccept(Session& session, boost::asio::ip::tcp::endpoint endpoint) { return true; } - Handoff + static Handoff onHandoff( Session& session, std::unique_ptr const& bundle, @@ -319,7 +319,7 @@ public: return Handoff{}; } - Handoff + static Handoff onHandoff( Session& session, http_request_type const& request, diff --git a/src/test/shamap/FetchPack_test.cpp b/src/test/shamap/FetchPack_test.cpp index 471ad91e95..ad86e066af 100644 --- a/src/test/shamap/FetchPack_test.cpp +++ b/src/test/shamap/FetchPack_test.cpp @@ -66,7 +66,7 @@ public: beast::Journal mJournal; }; - boost::intrusive_ptr + static boost::intrusive_ptr make_random_item(beast::xor_shift_engine& r) { Serializer s; @@ -75,10 +75,10 @@ public: return make_shamapitem(s.getSHA512Half(), s.slice()); } - void + static void add_random_items(std::size_t n, Table& t, beast::xor_shift_engine& r) { - while (n--) + while ((n--) != 0u) { auto const result(t.addItem(SHAMapNodeType::tnACCOUNT_STATE, make_random_item(r))); assert(result); diff --git a/src/tests/libxrpl/basics/RangeSet.cpp b/src/tests/libxrpl/basics/RangeSet.cpp index d0fc656368..41a33133f2 100644 --- a/src/tests/libxrpl/basics/RangeSet.cpp +++ b/src/tests/libxrpl/basics/RangeSet.cpp @@ -17,7 +17,7 @@ TEST(RangeSet, prevMissing) RangeSet set; for (std::uint32_t i = 0; i < 10; ++i) - set.insert(range(10 * i, 10 * i + 5)); + set.insert(range(10 * i, (10 * i) + 5)); for (std::uint32_t i = 1; i < 100; ++i) { diff --git a/src/tests/libxrpl/json/Value.cpp b/src/tests/libxrpl/json/Value.cpp index a7b7387ba1..943e517669 100644 --- a/src/tests/libxrpl/json/Value.cpp +++ b/src/tests/libxrpl/json/Value.cpp @@ -209,10 +209,10 @@ TEST(json_value, compare_strings) SCOPED_TRACE(line); EXPECT_EQ((lhs == rhs), lhsEqRhs); EXPECT_NE((lhs != rhs), lhsEqRhs); - EXPECT_EQ((lhs < rhs), (!(lhsEqRhs || !lhsLtRhs))); + EXPECT_EQ((lhs < rhs), (!lhsEqRhs && lhsLtRhs)); EXPECT_EQ((lhs <= rhs), (lhsEqRhs || lhsLtRhs)); EXPECT_EQ((lhs >= rhs), (lhsEqRhs || !lhsLtRhs)); - EXPECT_EQ((lhs > rhs), (!(lhsEqRhs || lhsLtRhs))); + EXPECT_EQ((lhs > rhs), (!lhsEqRhs && !lhsLtRhs)); }; Json::Value const null0; diff --git a/src/xrpld/app/consensus/RCLConsensus.cpp b/src/xrpld/app/consensus/RCLConsensus.cpp index 5a3d53dae0..315f9f2ab5 100644 --- a/src/xrpld/app/consensus/RCLConsensus.cpp +++ b/src/xrpld/app/consensus/RCLConsensus.cpp @@ -925,7 +925,7 @@ RCLConsensus::Adaptor::preStartRound(RCLCxLedger const& prevLgr, hash_set= LEDGER_RETRY_PASSES)) + if ((changes == 0) || (pass >= LEDGER_RETRY_PASSES)) certainRetry = false; } diff --git a/src/xrpld/app/ledger/detail/LedgerMaster.cpp b/src/xrpld/app/ledger/detail/LedgerMaster.cpp index 42d7f2ec6e..320c4bc722 100644 --- a/src/xrpld/app/ledger/detail/LedgerMaster.cpp +++ b/src/xrpld/app/ledger/detail/LedgerMaster.cpp @@ -195,7 +195,7 @@ LedgerMaster::isCaughtUp(std::string& reason) } std::uint32_t validClose = mValidLedgerSign.load(); std::uint32_t pubClose = mPubLedgerClose.load(); - if (!validClose || !pubClose) + if ((validClose == 0u) || (pubClose == 0u)) { reason = "No published ledger"; return false; @@ -514,7 +514,7 @@ LedgerMaster::getFullValidatedRange(std::uint32_t& minVal, std::uint32_t& maxVal // published ledger which is. maxVal = mPubLedgerSeq.load(); - if (!maxVal) + if (maxVal == 0u) return false; std::optional maybeMin; diff --git a/src/xrpld/app/ledger/detail/LedgerToJson.cpp b/src/xrpld/app/ledger/detail/LedgerToJson.cpp index ff8e7e55e9..a48756f9b6 100644 --- a/src/xrpld/app/ledger/detail/LedgerToJson.cpp +++ b/src/xrpld/app/ledger/detail/LedgerToJson.cpp @@ -18,19 +18,19 @@ namespace { bool isFull(LedgerFill const& fill) { - return fill.options & LedgerFill::full; + return (fill.options & LedgerFill::full) != 0; } bool isExpanded(LedgerFill const& fill) { - return isFull(fill) || (fill.options & LedgerFill::expand); + return isFull(fill) || ((fill.options & LedgerFill::expand) != 0); } bool isBinary(LedgerFill const& fill) { - return fill.options & LedgerFill::binary; + return (fill.options & LedgerFill::binary) != 0; } void @@ -173,7 +173,7 @@ fillJsonTx( } } - if ((fill.options & LedgerFill::ownerFunds) && txn->getTxnType() == ttOFFER_CREATE) + if (((fill.options & LedgerFill::ownerFunds) != 0) && txn->getTxnType() == ttOFFER_CREATE) { auto const account = txn->getAccountID(sfAccount); auto const amount = txn->getFieldAmount(sfTakerGets); @@ -216,7 +216,7 @@ fillJsonTx(Json::Value& json, LedgerFill const& fill) catch (std::exception const& ex) { // Nothing the user can do about this. - if (fill.context) + if (fill.context != nullptr) { JLOG(fill.context->j.error()) << "Exception in " << __func__ << ": " << ex.what(); } @@ -304,13 +304,14 @@ fillJson(Json::Value& json, LedgerFill const& fill) !fill.ledger.open(), fill.ledger.header(), bFull, - (fill.context ? fill.context->apiVersion : RPC::apiMaximumSupportedVersion)); + ((fill.context != nullptr) ? fill.context->apiVersion + : RPC::apiMaximumSupportedVersion)); } - if (bFull || fill.options & LedgerFill::dumpTxrp) + if (bFull || ((fill.options & LedgerFill::dumpTxrp) != 0)) fillJsonTx(json, fill); - if (bFull || fill.options & LedgerFill::dumpState) + if (bFull || ((fill.options & LedgerFill::dumpState) != 0)) fillJsonState(json, fill); } @@ -322,7 +323,7 @@ addJson(Json::Value& json, LedgerFill const& fill) auto& object = json[jss::ledger] = Json::objectValue; fillJson(object, fill); - if ((fill.options & LedgerFill::dumpQueue) && !fill.txQueue.empty()) + if (((fill.options & LedgerFill::dumpQueue) != 0) && !fill.txQueue.empty()) fillJsonQueue(json, fill); } diff --git a/src/xrpld/app/ledger/detail/TransactionMaster.cpp b/src/xrpld/app/ledger/detail/TransactionMaster.cpp index b45dbd5ba9..e3ebd443f1 100644 --- a/src/xrpld/app/ledger/detail/TransactionMaster.cpp +++ b/src/xrpld/app/ledger/detail/TransactionMaster.cpp @@ -110,7 +110,7 @@ TransactionMaster::fetch( } else { - if (uCommitLedger) + if (uCommitLedger != 0u) iTx->setStatus(COMMITTED, uCommitLedger); txn = iTx->getSTransaction(); diff --git a/src/xrpld/app/main/Application.cpp b/src/xrpld/app/main/Application.cpp index 048ef0d9b4..55ba09e49e 100644 --- a/src/xrpld/app/main/Application.cpp +++ b/src/xrpld/app/main/Application.cpp @@ -2127,7 +2127,7 @@ fixConfigPorts(Config& config, Endpoints const& endpoints) if (optPort) { std::uint16_t const port = beast::lexicalCast(*optPort); - if (!port) + if (port == 0u) section.set("port", std::to_string(ep.port())); } } diff --git a/src/xrpld/app/main/BasicApp.cpp b/src/xrpld/app/main/BasicApp.cpp index be0c158b85..2c5a2b0364 100644 --- a/src/xrpld/app/main/BasicApp.cpp +++ b/src/xrpld/app/main/BasicApp.cpp @@ -9,7 +9,7 @@ BasicApp::BasicApp(std::size_t numberOfThreads) work_.emplace(boost::asio::make_work_guard(io_context_)); threads_.reserve(numberOfThreads); - while (numberOfThreads--) + while ((numberOfThreads--) != 0u) { threads_.emplace_back([this, numberOfThreads]() { beast::setCurrentThreadName("io svc #" + std::to_string(numberOfThreads)); diff --git a/src/xrpld/app/main/Main.cpp b/src/xrpld/app/main/Main.cpp index 03f8076ed1..88a335f843 100644 --- a/src/xrpld/app/main/Main.cpp +++ b/src/xrpld/app/main/Main.cpp @@ -295,7 +295,7 @@ runUnitTests( try { c.wait(); - if (c.exit_code()) + if (c.exit_code() != 0) ++bad_child_exits; } catch (...) @@ -309,7 +309,7 @@ runUnitTests( parent_runner.add_failures(terminated_child_exits); anyMissing(parent_runner, multi_selector(pattern)); - if (parent_runner.any_failed() || bad_child_exits) + if (parent_runner.any_failed() || (bad_child_exits != 0)) return EXIT_FAILURE; return EXIT_SUCCESS; } diff --git a/src/xrpld/app/misc/NegativeUNLVote.h b/src/xrpld/app/misc/NegativeUNLVote.h index 601ac7d060..7ad460cbf1 100644 --- a/src/xrpld/app/misc/NegativeUNLVote.h +++ b/src/xrpld/app/misc/NegativeUNLVote.h @@ -140,7 +140,7 @@ private: * @param candidates the vector of candidates * @return the picked candidate */ - NodeID + static NodeID choose(uint256 const& randomPadData, std::vector const& candidates); /** diff --git a/src/xrpld/app/misc/NetworkOPs.cpp b/src/xrpld/app/misc/NetworkOPs.cpp index aabb53230f..5110534efc 100644 --- a/src/xrpld/app/misc/NetworkOPs.cpp +++ b/src/xrpld/app/misc/NetworkOPs.cpp @@ -1689,12 +1689,12 @@ NetworkOPsImp::getOwnerInfo(std::shared_ptr lpLedger, AccountID uNodeDir = sleNode->getFieldU64(sfIndexNext); - if (uNodeDir) + if (uNodeDir != 0u) { sleNode = lpLedger->read(keylet::page(root, uNodeDir)); XRPL_ASSERT(sleNode, "xrpl::NetworkOPsImp::getOwnerInfo : read next page"); } - } while (uNodeDir); + } while (uNodeDir != 0u); } return jvObjects; @@ -2532,7 +2532,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) } } - if (warnings.size()) + if (warnings.size() != 0u) info[jss::warnings] = std::move(warnings); } @@ -4038,7 +4038,7 @@ bool NetworkOPsImp::unsubLedger(std::uint64_t uSeq) { std::lock_guard sl(mSubLock); - return mStreamMaps[sLedger].erase(uSeq); + return mStreamMaps[sLedger].erase(uSeq) != 0u; } // <-- bool: true=erased, false=was not there @@ -4046,7 +4046,7 @@ bool NetworkOPsImp::unsubBookChanges(std::uint64_t uSeq) { std::lock_guard sl(mSubLock); - return mStreamMaps[sBookChanges].erase(uSeq); + return mStreamMaps[sBookChanges].erase(uSeq) != 0u; } // <-- bool: true=added, false=already there @@ -4062,7 +4062,7 @@ bool NetworkOPsImp::unsubManifests(std::uint64_t uSeq) { std::lock_guard sl(mSubLock); - return mStreamMaps[sManifests].erase(uSeq); + return mStreamMaps[sManifests].erase(uSeq) != 0u; } // <-- bool: true=added, false=already there @@ -4095,7 +4095,7 @@ bool NetworkOPsImp::unsubServer(std::uint64_t uSeq) { std::lock_guard sl(mSubLock); - return mStreamMaps[sServer].erase(uSeq); + return mStreamMaps[sServer].erase(uSeq) != 0u; } // <-- bool: true=added, false=already there @@ -4111,7 +4111,7 @@ bool NetworkOPsImp::unsubTransactions(std::uint64_t uSeq) { std::lock_guard sl(mSubLock); - return mStreamMaps[sTransactions].erase(uSeq); + return mStreamMaps[sTransactions].erase(uSeq) != 0u; } // <-- bool: true=added, false=already there @@ -4127,7 +4127,7 @@ bool NetworkOPsImp::unsubRTTransactions(std::uint64_t uSeq) { std::lock_guard sl(mSubLock); - return mStreamMaps[sRTTransactions].erase(uSeq); + return mStreamMaps[sRTTransactions].erase(uSeq) != 0u; } // <-- bool: true=added, false=already there @@ -4149,7 +4149,7 @@ bool NetworkOPsImp::unsubValidations(std::uint64_t uSeq) { std::lock_guard sl(mSubLock); - return mStreamMaps[sValidations].erase(uSeq); + return mStreamMaps[sValidations].erase(uSeq) != 0u; } // <-- bool: true=added, false=already there @@ -4165,7 +4165,7 @@ bool NetworkOPsImp::unsubPeerStatus(std::uint64_t uSeq) { std::lock_guard sl(mSubLock); - return mStreamMaps[sPeerStatus].erase(uSeq); + return mStreamMaps[sPeerStatus].erase(uSeq) != 0u; } // <-- bool: true=added, false=already there @@ -4181,7 +4181,7 @@ bool NetworkOPsImp::unsubConsensus(std::uint64_t uSeq) { std::lock_guard sl(mSubLock); - return mStreamMaps[sConsensusPhase].erase(uSeq); + return mStreamMaps[sConsensusPhase].erase(uSeq) != 0u; } InfoSub::pointer @@ -4632,7 +4632,7 @@ NetworkOPsImp::StateAccounting::json(Json::Value& obj) const state[jss::duration_us] = std::to_string(counters[i].dur.count()); } obj[jss::server_state_duration_us] = std::to_string(current.count()); - if (initialSync) + if (initialSync != 0u) obj[jss::initial_sync_duration_us] = std::to_string(initialSync); } diff --git a/src/xrpld/app/misc/SHAMapStoreImp.cpp b/src/xrpld/app/misc/SHAMapStoreImp.cpp index 13746369f5..2865f964de 100644 --- a/src/xrpld/app/misc/SHAMapStoreImp.cpp +++ b/src/xrpld/app/misc/SHAMapStoreImp.cpp @@ -93,7 +93,7 @@ SHAMapStoreImp::SHAMapStoreImp( get_if_exists(section, "online_delete", deleteInterval_); - if (deleteInterval_) + if (deleteInterval_ != 0u) { // Configuration that affects the behavior of online delete get_if_exists(section, "delete_batch", deleteBatch_); @@ -138,7 +138,7 @@ SHAMapStoreImp::makeNodeStore(int readThreads) auto nscfg = app_.config().section(ConfigSection::nodeDatabase()); std::unique_ptr db; - if (deleteInterval_) + if (deleteInterval_ != 0u) { SavedState state = state_db_.getState(); auto writableBackend = makeBackendRotating(state.writableDb); @@ -209,7 +209,7 @@ SHAMapStoreImp::copyNode(std::uint64_t& nodeCount, SHAMapTreeNode const& node) // Copy a single record from node to dbRotating_ dbRotating_->fetchNodeObject( node.getHash().as_uint256(), 0, NodeStore::FetchType::synchronous, true); - if (!(++nodeCount % checkHealthInterval_)) + if ((++nodeCount % checkHealthInterval_) == 0u) { if (healthWait() == stopping) return false; @@ -254,7 +254,7 @@ SHAMapStoreImp::run() } LedgerIndex const validatedSeq = validatedLedger->header().seq; - if (!lastRotated) + if (lastRotated == 0u) { lastRotated = validatedSeq; state_db_.setLastRotated(lastRotated); @@ -386,15 +386,15 @@ SHAMapStoreImp::dbPaths() it != boost::filesystem::directory_iterator(); ++it) { - if (!state.writableDb.compare(it->path().string())) + if (state.writableDb.compare(it->path().string()) == 0) { writableDbExists = true; } - else if (!state.archiveDb.compare(it->path().string())) + else if (state.archiveDb.compare(it->path().string()) == 0) { archiveDbExists = true; } - else if (!dbPrefix_.compare(it->path().stem().string())) + else if (dbPrefix_.compare(it->path().stem().string()) == 0) { pathsToDelete.push_back(it->path()); } @@ -608,7 +608,7 @@ SHAMapStoreImp::minimumOnline() const { // minimumOnline_ with 0 value is equivalent to unknown/not set. // Don't attempt to acquire ledgers if that value is unknown. - if (deleteInterval_ && minimumOnline_) + if ((deleteInterval_ != 0u) && (minimumOnline_ != 0u)) return minimumOnline_.load(); return app_.getLedgerMaster().minSqlSeq(); } diff --git a/src/xrpld/app/misc/TxQ.h b/src/xrpld/app/misc/TxQ.h index 4f02d6d617..7c441867ea 100644 --- a/src/xrpld/app/misc/TxQ.h +++ b/src/xrpld/app/misc/TxQ.h @@ -693,12 +693,12 @@ private: }; // Helper function returns requiredFeeLevel. - FeeLevel64 + static FeeLevel64 getRequiredFeeLevel( OpenView& view, ApplyFlags flags, FeeMetrics::Snapshot const& metricsSnapshot, - std::lock_guard const& lock) const; + std::lock_guard const& lock); // Helper function for TxQ::apply. If a transaction's fee is high enough, // attempt to directly apply that transaction to the ledger. diff --git a/src/xrpld/app/misc/detail/AmendmentTable.cpp b/src/xrpld/app/misc/detail/AmendmentTable.cpp index 2b7005f4cc..7569fa13b5 100644 --- a/src/xrpld/app/misc/detail/AmendmentTable.cpp +++ b/src/xrpld/app/misc/detail/AmendmentTable.cpp @@ -675,7 +675,7 @@ AmendmentTableImpl::unVeto(uint256 const& amendment) std::lock_guard lock(mutex_); AmendmentState* const s = get(amendment, lock); - if (!s || s->vote != AmendmentVote::down) + if ((s == nullptr) || s->vote != AmendmentVote::down) return false; s->vote = AmendmentVote::up; persistVote(amendment, s->name, s->vote); @@ -707,7 +707,7 @@ AmendmentTableImpl::isEnabled(uint256 const& amendment) const { std::lock_guard lock(mutex_); AmendmentState const* s = get(amendment, lock); - return s && s->enabled; + return (s != nullptr) && s->enabled; } bool @@ -715,7 +715,7 @@ AmendmentTableImpl::isSupported(uint256 const& amendment) const { std::lock_guard lock(mutex_); AmendmentState const* s = get(amendment, lock); - return s && s->supported; + return (s != nullptr) && s->supported; } bool @@ -946,7 +946,7 @@ AmendmentTableImpl::injectJson( v[jss::count] = votesFor; v[jss::validations] = votesTotal; - if (votesNeeded) + if (votesNeeded != 0) v[jss::threshold] = votesNeeded; } } @@ -974,7 +974,7 @@ AmendmentTableImpl::getJson(uint256 const& amendmentID, bool isAdmin) const { std::lock_guard lock(mutex_); AmendmentState const* a = get(amendmentID, lock); - if (a) + if (a != nullptr) { Json::Value& jAmendment = (ret[to_string(amendmentID)] = Json::objectValue); injectJson(jAmendment, amendmentID, *a, isAdmin, lock); diff --git a/src/xrpld/app/misc/detail/Transaction.cpp b/src/xrpld/app/misc/detail/Transaction.cpp index 35b49504d5..6eefd08369 100644 --- a/src/xrpld/app/misc/detail/Transaction.cpp +++ b/src/xrpld/app/misc/detail/Transaction.cpp @@ -133,7 +133,7 @@ Transaction::getJson(JsonOptions options, bool binary) const Json::Value ret(mTransaction->getJson(options & ~JsonOptions::include_date, binary)); // NOTE Binary STTx::getJson output might not be a JSON object - if (ret.isObject() && mLedgerIndex) + if (ret.isObject() && (mLedgerIndex != 0u)) { if (!(options & JsonOptions::disable_API_prior_V2)) { diff --git a/src/xrpld/app/misc/detail/TxQ.cpp b/src/xrpld/app/misc/detail/TxQ.cpp index 020fa501d5..78e8ccdba5 100644 --- a/src/xrpld/app/misc/detail/TxQ.cpp +++ b/src/xrpld/app/misc/detail/TxQ.cpp @@ -121,7 +121,7 @@ TxQ::FeeMetrics::update( txnsExpected_ = std::min(next, maximumTxnCount_.value_or(next)); } - if (!size) + if (size == 0) { escalationMultiplier_ = setup.minimumEscalationMultiplier; } @@ -185,16 +185,16 @@ sumOfFirstSquares(std::size_t xIn) } // Unit tests for sumOfSquares() -static_assert(sumOfFirstSquares(1).first == true); +static_assert(sumOfFirstSquares(1).first); static_assert(sumOfFirstSquares(1).second == 1); -static_assert(sumOfFirstSquares(2).first == true); +static_assert(sumOfFirstSquares(2).first); static_assert(sumOfFirstSquares(2).second == 5); -static_assert(sumOfFirstSquares(0x1FFFFF).first == true, ""); +static_assert(sumOfFirstSquares(0x1FFFFF).first, ""); static_assert(sumOfFirstSquares(0x1FFFFF).second == 0x2AAAA8AAAAB00000ul, ""); -static_assert(sumOfFirstSquares(0x200000).first == false, ""); +static_assert(!sumOfFirstSquares(0x200000).first, ""); static_assert(sumOfFirstSquares(0x200000).second == std::numeric_limits::max(), ""); } // namespace detail @@ -308,10 +308,11 @@ TxQ::MaybeTx& TxQ::TxQAccount::add(MaybeTx&& txn) { auto const seqProx = txn.seqProxy; + [[maybe_unused]] auto const* txnPtr = &txn; auto result = transactions.emplace(seqProx, std::move(txn)); XRPL_ASSERT(result.second, "xrpl::TxQ::TxQAccount::add : emplace succeeded"); - XRPL_ASSERT(&result.first->second != &txn, "xrpl::TxQ::TxQAccount::add : transaction moved"); + XRPL_ASSERT(&result.first->second != txnPtr, "xrpl::TxQ::TxQAccount::add : transaction moved"); return result.first->second; } @@ -357,7 +358,7 @@ TxQ::canBeHeld( // queue yet, but should be added in the future. // tapFAIL_HARD transactions are never held if (tx.isFieldPresent(sfPreviousTxnID) || tx.isFieldPresent(sfAccountTxnID) || - (flags & tapFAIL_HARD)) + ((flags & tapFAIL_HARD) != 0u)) return telCAN_NOT_QUEUE; { @@ -1591,7 +1592,7 @@ TxQ::getRequiredFeeLevel( OpenView& view, ApplyFlags flags, FeeMetrics::Snapshot const& metricsSnapshot, - std::lock_guard const& lock) const + std::lock_guard const& lock) { return FeeMetrics::scaleFeeLevel(metricsSnapshot, view); } diff --git a/src/xrpld/app/misc/detail/ValidatorList.cpp b/src/xrpld/app/misc/detail/ValidatorList.cpp index 386b96387e..29c0e75c78 100644 --- a/src/xrpld/app/misc/detail/ValidatorList.cpp +++ b/src/xrpld/app/misc/detail/ValidatorList.cpp @@ -181,7 +181,7 @@ ValidatorList::load( { // Want truncated result when dividing an odd integer listThreshold_ = (publisherLists_.size() < 3) ? 1 // - : publisherLists_.size() / 2 + 1; + : (publisherLists_.size() / 2) + 1; JLOG(j_.debug()) << "Validator list threshold computed as " << listThreshold_; } @@ -699,11 +699,11 @@ ValidatorList::sendValidatorList( { messageVersion = 1; } - if (!messageVersion) + if (messageVersion == 0u) return; auto const [newPeerSequence, numVLs] = buildValidatorListMessages( messageVersion, peerSequence, maxSequence, rawVersion, rawManifest, blobInfos, messages); - if (newPeerSequence) + if (newPeerSequence != 0u) { XRPL_ASSERT( !messages.empty(), @@ -1256,7 +1256,7 @@ ValidatorList::loadLists() continue; auto size = file_size(fullPath, ec); - if (!ec && !size) + if (!ec && (size == 0u)) { // Treat an empty file as a missing file, because // nobody else is going to write it. @@ -1433,7 +1433,7 @@ bool ValidatorList::trustedPublisher(PublicKey const& identity) const { std::shared_lock read_lock{mutex_}; - return identity.size() && publisherLists_.contains(identity) && + return (identity.size() != 0u) && publisherLists_.contains(identity) && publisherLists_.at(identity).status < PublisherStatus::revoked; } @@ -1484,7 +1484,7 @@ ValidatorList::removePublisherList( std::size_t ValidatorList::count(ValidatorList::shared_lock const&) const { - return publisherLists_.size() + (!localPublisherList.list.empty()); + return publisherLists_.size() + static_cast(!localPublisherList.list.empty()); } std::size_t @@ -1649,7 +1649,7 @@ ValidatorList::getJson() const future.validFrom > timeKeeper_.now() + 600s, "xrpl::ValidatorList::getJson : minimum valid from"); } - if (remaining.size()) + if (remaining.size() != 0u) curr[jss::remaining] = std::move(remaining); } diff --git a/src/xrpld/app/paths/PathRequest.cpp b/src/xrpld/app/paths/PathRequest.cpp index f82a207552..0e895e66d4 100644 --- a/src/xrpld/app/paths/PathRequest.cpp +++ b/src/xrpld/app/paths/PathRequest.cpp @@ -191,7 +191,7 @@ PathRequest::isValid(std::shared_ptr const& crCache) } else { - bool const disallowXRP(sleDest->getFlags() & lsfDisallowXRP); + bool const disallowXRP((sleDest->getFlags() & lsfDisallowXRP) != 0u); auto usDestCurrID = accountDestCurrencies(*raDstAccount, crCache, !disallowXRP); @@ -609,7 +609,7 @@ PathRequest::findPaths( after four source currencies, 50 - (4 * 4) = 34. */ int const size = sourceCurrencies.size(); - consumer_.charge({std::clamp(size * size + 34, 50, 400), "path update"}); + consumer_.charge({std::clamp((size * size) + 34, 50, 400), "path update"}); return true; } diff --git a/src/xrpld/app/paths/Pathfinder.cpp b/src/xrpld/app/paths/Pathfinder.cpp index c777fcb2f7..10d69fc040 100644 --- a/src/xrpld/app/paths/Pathfinder.cpp +++ b/src/xrpld/app/paths/Pathfinder.cpp @@ -615,7 +615,7 @@ Pathfinder::getBestPaths( ++pathsIterator; auto iPathsLeft = maxPaths - bestPaths.size(); - if (!(iPathsLeft > 0 || fullLiquidityPath.empty())) + if (iPathsLeft <= 0 && !fullLiquidityPath.empty()) break; if (path.empty()) @@ -850,7 +850,7 @@ Pathfinder::isNoRipple( auto const flag((toAccount > fromAccount) ? lsfHighNoRipple : lsfLowNoRipple); - return sleRipple && (sleRipple->getFieldU32(sfFlags) & flag); + return sleRipple && ((sleRipple->getFieldU32(sfFlags) & flag) != 0u); } // Does this path end on an account-to-account link whose last account has @@ -864,7 +864,7 @@ Pathfinder::isNoRippleOut(STPath const& currentPath) // Last link must be an account. STPathElement const& endElement = currentPath.back(); - if (!(endElement.getNodeType() & STPathElement::typeAccount)) + if ((endElement.getNodeType() & STPathElement::typeAccount) == 0u) return false; // If there's only one item in the path, return true if that item specifies @@ -911,7 +911,7 @@ Pathfinder::addLink( << " completePaths size=" << mCompletePaths.size(); JLOG(j_.trace()) << currentPath.getJson(JsonOptions::none); - if (addFlags & afADD_ACCOUNTS) + if ((addFlags & afADD_ACCOUNTS) != 0u) { // add accounts if (bOnXRP) @@ -930,10 +930,10 @@ Pathfinder::addLink( if (sleEnd) { - bool const bRequireAuth(sleEnd->getFieldU32(sfFlags) & lsfRequireAuth); + bool const bRequireAuth((sleEnd->getFieldU32(sfFlags) & lsfRequireAuth) != 0u); bool const bIsEndCurrency(uEndCurrency == mDstAmount.getCurrency()); bool const bIsNoRippleOut(isNoRippleOut(currentPath)); - bool const bDestOnly(addFlags & afAC_LAST); + bool const bDestOnly((addFlags & afAC_LAST) != 0u); if (auto const lines = mRLCache->getRippleLines( uEndAccount, @@ -1012,7 +1012,7 @@ Pathfinder::addLink( bIsEndCurrency, mEffectiveDst, continueCallback); - if (out) + if (out != 0) candidates.push_back({out, acct}); } } @@ -1060,10 +1060,10 @@ Pathfinder::addLink( } } } - if (addFlags & afADD_BOOKS) + if ((addFlags & afADD_BOOKS) != 0u) { // add order books - if (addFlags & afOB_XRP) + if ((addFlags & afOB_XRP) != 0u) { // to XRP only if (!bOnXRP && app_.getOrderBookDB().isBookToXRP({uEndCurrency, uEndIssuer}, mDomain)) diff --git a/src/xrpld/app/paths/RippleLineCache.cpp b/src/xrpld/app/paths/RippleLineCache.cpp index ac3e28e579..c45c20aca8 100644 --- a/src/xrpld/app/paths/RippleLineCache.cpp +++ b/src/xrpld/app/paths/RippleLineCache.cpp @@ -84,7 +84,7 @@ RippleLineCache::getRippleLines(AccountID const& accountID, LineDirection direct } XRPL_ASSERT( - !it->second || (it->second->size() > 0), + !it->second || (!it->second->empty()), "xrpl::RippleLineCache::getRippleLines : null or nonempty lines"); auto const size = it->second ? it->second->size() : 0; JLOG(journal_.trace()) << "getRippleLines for ledger " << ledger_->header().seq << " found " diff --git a/src/xrpld/app/paths/detail/BookStep.cpp b/src/xrpld/app/paths/detail/BookStep.cpp index e0053956a8..df1e849b81 100644 --- a/src/xrpld/app/paths/detail/BookStep.cpp +++ b/src/xrpld/app/paths/detail/BookStep.cpp @@ -452,7 +452,7 @@ public: std::uint32_t getOfrInRate(Step const* prevStep, AccountID const& owner, std::uint32_t trIn) const { - auto const srcAcct = prevStep ? prevStep->directStepSrcAcct() : std::nullopt; + auto const srcAcct = (prevStep != nullptr) ? prevStep->directStepSrcAcct() : std::nullopt; return owner == srcAcct // If offer crossing && prevStep is DirectI ? QUALITY_ONE // && src is offer owner @@ -467,9 +467,9 @@ public: AccountID const& strandDst, std::uint32_t trOut) const { - return // If offer crossing - prevStep && prevStep->bookStepBook() && // && prevStep is BookStep - owner == strandDst // && dest is offer owner + return // If offer crossing + (prevStep != nullptr) && prevStep->bookStepBook() && // && prevStep is BookStep + owner == strandDst // && dest is offer owner ? QUALITY_ONE : trOut; // then rate = QUALITY_ONE } @@ -1260,13 +1260,14 @@ BookStep::check(StrandContext const& ctx) const // Do not allow two books to output the same issue. This may cause offers on // one step to unfund offers in another step. - if (!ctx.seenBookOuts.insert(book_.out).second || ctx.seenDirectIssues[0].count(book_.out)) + if (!ctx.seenBookOuts.insert(book_.out).second || + (ctx.seenDirectIssues[0].count(book_.out) != 0u)) { JLOG(j_.debug()) << "BookStep: loop detected: " << *this; return temBAD_PATH_LOOP; } - if (ctx.seenDirectIssues[1].count(book_.out)) + if (ctx.seenDirectIssues[1].count(book_.out) != 0u) { JLOG(j_.debug()) << "BookStep: loop detected: " << *this; return temBAD_PATH_LOOP; @@ -1282,7 +1283,7 @@ BookStep::check(StrandContext const& ctx) const return tecNO_ISSUER; } - if (ctx.prevStep) + if (ctx.prevStep != nullptr) { if (auto const prev = ctx.prevStep->directStepSrcAcct()) { @@ -1292,7 +1293,7 @@ BookStep::check(StrandContext const& ctx) const auto sle = view.read(keylet::line(*prev, cur, book_.in.currency)); if (!sle) return terNO_LINE; - if ((*sle)[sfFlags] & ((cur > *prev) ? lsfHighNoRipple : lsfLowNoRipple)) + if (((*sle)[sfFlags] & ((cur > *prev) ? lsfHighNoRipple : lsfLowNoRipple)) != 0u) return terNO_RIPPLE; } } diff --git a/src/xrpld/app/paths/detail/DirectStep.cpp b/src/xrpld/app/paths/detail/DirectStep.cpp index 0c8693eef4..d1d540eda5 100644 --- a/src/xrpld/app/paths/detail/DirectStep.cpp +++ b/src/xrpld/app/paths/detail/DirectStep.cpp @@ -224,15 +224,15 @@ public: using DirectStepI::check; - bool - verifyPrevStepDebtDirection(DebtDirection) const + static bool + verifyPrevStepDebtDirection(DebtDirection) { // A payment doesn't care whether or not prevStepRedeems. return true; } - bool - verifyDstQualityIn(std::uint32_t dstQIn) const + static bool + verifyDstQualityIn(std::uint32_t dstQIn) { // Payments have no particular expectations for what dstQIn will be. return true; @@ -275,8 +275,8 @@ public: using DirectStepI::check; - bool - verifyPrevStepDebtDirection(DebtDirection prevStepDir) const + static bool + verifyPrevStepDebtDirection(DebtDirection prevStepDir) { // During offer crossing we rely on the fact that prevStepRedeems // will *always* issue. That's because: @@ -288,16 +288,16 @@ public: return issues(prevStepDir); } - bool - verifyDstQualityIn(std::uint32_t dstQIn) const + static bool + verifyDstQualityIn(std::uint32_t dstQIn) { // Due to a couple of factors dstQIn is always QUALITY_ONE for // offer crossing. If that changes we need to know. return dstQIn == QUALITY_ONE; } - std::uint32_t - quality(ReadView const& sb, QualityDirection qDir) const; + static std::uint32_t + quality(ReadView const& sb, QualityDirection qDir); // Compute the maximum value that can flow from src->dst at // the best available quality. @@ -308,8 +308,8 @@ public: // Verify the consistency of the step. These checks are specific to // offer crossing and assume that general checks were already performed. - TER - check(StrandContext const& ctx, std::shared_ptr const& sleSrc) const; + static TER + check(StrandContext const& ctx, std::shared_ptr const& sleSrc); std::string logString() const override @@ -356,13 +356,13 @@ DirectIPaymentStep::quality(ReadView const& sb, QualityDirection qDir) const return QUALITY_ONE; auto const q = (*sle)[field]; - if (!q) + if (q == 0u) return QUALITY_ONE; return q; } std::uint32_t -DirectIOfferCrossingStep::quality(ReadView const&, QualityDirection qDir) const +DirectIOfferCrossingStep::quality(ReadView const&, QualityDirection qDir) { // If offer crossing then ignore trust line Quality fields. This // preserves a long-standing tradition. @@ -411,21 +411,21 @@ DirectIPaymentStep::check(StrandContext const& ctx, std::shared_ptr c auto const authField = (src_ > dst_) ? lsfHighAuth : lsfLowAuth; - if (((*sleSrc)[sfFlags] & lsfRequireAuth) && !((*sleLine)[sfFlags] & authField) && - (*sleLine)[sfBalance] == beast::zero) + if ((((*sleSrc)[sfFlags] & lsfRequireAuth) != 0u) && + (((*sleLine)[sfFlags] & authField) == 0u) && (*sleLine)[sfBalance] == beast::zero) { JLOG(j_.debug()) << "DirectStepI: can't receive IOUs from issuer without auth." << " src: " << src_; return terNO_AUTH; } - if (ctx.prevStep) + if (ctx.prevStep != nullptr) { if (ctx.prevStep->bookStepBook()) { auto const noRippleSrcToDst = ((*sleLine)[sfFlags] & ((src_ > dst_) ? lsfHighNoRipple : lsfLowNoRipple)); - if (noRippleSrcToDst) + if (noRippleSrcToDst != 0u) return terNO_RIPPLE; } } @@ -447,7 +447,7 @@ DirectIPaymentStep::check(StrandContext const& ctx, std::shared_ptr c } TER -DirectIOfferCrossingStep::check(StrandContext const&, std::shared_ptr const&) const +DirectIOfferCrossingStep::check(StrandContext const&, std::shared_ptr const&) { // The standard checks are all we can do because any remaining checks // require the existence of a trust line. Offer crossing does not @@ -714,7 +714,7 @@ template std::pair DirectStepI::qualitiesSrcRedeems(ReadView const& sb) const { - if (!prevStep_) + if (prevStep_ == nullptr) return {QUALITY_ONE, QUALITY_ONE}; auto const prevStepQIn = prevStep_->lineQualityIn(sb); @@ -829,7 +829,7 @@ DirectStepI::check(StrandContext const& ctx) const // If previous step was a direct step then we need to check // no ripple flags. - if (ctx.prevStep) + if (ctx.prevStep != nullptr) { if (auto prevSrc = ctx.prevStep->directStepSrcAcct()) { @@ -842,9 +842,9 @@ DirectStepI::check(StrandContext const& ctx) const Issue const srcIssue{currency_, src_}; Issue const dstIssue{currency_, dst_}; - if (ctx.seenBookOuts.count(srcIssue)) + if (ctx.seenBookOuts.count(srcIssue) != 0u) { - if (!ctx.prevStep) + if (ctx.prevStep == nullptr) { // LCOV_EXCL_START UNREACHABLE( @@ -905,7 +905,7 @@ make_DirectStepI( { TER ter = tefINTERNAL; std::unique_ptr r; - if (ctx.offerCrossing) + if (ctx.offerCrossing != 0u) { auto offerCrossingStep = std::make_unique(ctx, src, dst, c); ter = offerCrossingStep->check(ctx); diff --git a/src/xrpld/app/paths/detail/PaySteps.cpp b/src/xrpld/app/paths/detail/PaySteps.cpp index 9087647aeb..33b63f7714 100644 --- a/src/xrpld/app/paths/detail/PaySteps.cpp +++ b/src/xrpld/app/paths/detail/PaySteps.cpp @@ -55,8 +55,8 @@ toStep( { auto& j = ctx.j; - if (ctx.isFirst && e1->isAccount() && (e1->getNodeType() & STPathElement::typeCurrency) && - isXRP(e1->getCurrency())) + if (ctx.isFirst && e1->isAccount() && + ((e1->getNodeType() & STPathElement::typeCurrency) != 0u) && isXRP(e1->getCurrency())) { return make_XRPEndpointStep(ctx, e1->getAccountID()); } @@ -83,10 +83,12 @@ toStep( (e2->getNodeType() & STPathElement::typeCurrency) || (e2->getNodeType() & STPathElement::typeIssuer), "xrpl::toStep : currency or issuer"); - auto const outCurrency = - e2->getNodeType() & STPathElement::typeCurrency ? e2->getCurrency() : curIssue.currency; - auto const outIssuer = - e2->getNodeType() & STPathElement::typeIssuer ? e2->getIssuerID() : curIssue.account; + auto const outCurrency = ((e2->getNodeType() & STPathElement::typeCurrency) != 0u) + ? e2->getCurrency() + : curIssue.currency; + auto const outIssuer = ((e2->getNodeType() & STPathElement::typeIssuer) != 0u) + ? e2->getIssuerID() + : curIssue.account; if (isXRP(curIssue.currency) && isXRP(outCurrency)) { @@ -132,12 +134,12 @@ toStrand( { auto const t = pe.getNodeType(); - if ((t & ~STPathElement::typeAll) || !t) + if (((t & ~STPathElement::typeAll) != 0u) || (t == 0u)) return {temBAD_PATH, Strand{}}; - bool const hasAccount = t & STPathElement::typeAccount; - bool const hasIssuer = t & STPathElement::typeIssuer; - bool const hasCurrency = t & STPathElement::typeCurrency; + bool const hasAccount = (t & STPathElement::typeAccount) != 0u; + bool const hasIssuer = (t & STPathElement::typeIssuer) != 0u; + bool const hasCurrency = (t & STPathElement::typeCurrency) != 0u; if (hasAccount && (hasIssuer || hasCurrency)) return {temBAD_PATH, Strand{}}; @@ -192,7 +194,7 @@ toStrand( STPathElement const& lastCurrency = *std::find_if(normPath.rbegin(), normPath.rend(), hasCurrency); if ((lastCurrency.getCurrency() != deliver.currency) || - (offerCrossing && lastCurrency.getIssuerID() != deliver.account)) + ((offerCrossing != 0u) && lastCurrency.getIssuerID() != deliver.account)) { normPath.emplace_back(std::nullopt, deliver.currency, deliver.account); } diff --git a/src/xrpld/app/paths/detail/XRPEndpointStep.cpp b/src/xrpld/app/paths/detail/XRPEndpointStep.cpp index 620d901f22..8b1835069b 100644 --- a/src/xrpld/app/paths/detail/XRPEndpointStep.cpp +++ b/src/xrpld/app/paths/detail/XRPEndpointStep.cpp @@ -369,7 +369,7 @@ make_XRPEndpointStep(StrandContext const& ctx, AccountID const& acc) { TER ter = tefINTERNAL; std::unique_ptr r; - if (ctx.offerCrossing) + if (ctx.offerCrossing != 0u) { auto offerCrossingStep = std::make_unique(ctx, acc); ter = offerCrossingStep->check(ctx); diff --git a/src/xrpld/app/rdb/backend/detail/Node.cpp b/src/xrpld/app/rdb/backend/detail/Node.cpp index 09b4ebc241..317c4e77a1 100644 --- a/src/xrpld/app/rdb/backend/detail/Node.cpp +++ b/src/xrpld/app/rdb/backend/detail/Node.cpp @@ -674,13 +674,13 @@ transactionsSQL( std::string maxClause; std::string minClause; - if (options.maxLedger) + if (options.maxLedger != 0u) { maxClause = boost::str( boost::format("AND AccountTransactions.LedgerSeq <= '%u'") % options.maxLedger); } - if (options.minLedger) + if (options.minLedger != 0u) { minClause = boost::str( boost::format("AND AccountTransactions.LedgerSeq >= '%u'") % options.minLedger); diff --git a/src/xrpld/core/detail/Config.cpp b/src/xrpld/core/detail/Config.cpp index 52186ca9da..c7179c181b 100644 --- a/src/xrpld/core/detail/Config.cpp +++ b/src/xrpld/core/detail/Config.cpp @@ -204,13 +204,13 @@ getSingleSection( { auto const pmtEntries = getIniFileSection(secSource, strSection); - if (pmtEntries && pmtEntries->size() == 1) + if ((pmtEntries != nullptr) && pmtEntries->size() == 1) { strValue = (*pmtEntries)[0]; return true; } - if (pmtEntries) + if (pmtEntries != nullptr) { JLOG(j.warn()) << "Section '" << strSection << "': requires 1 line not " << pmtEntries->size() << " lines."; @@ -415,7 +415,7 @@ checkZeroPorts(Config const& config) if (optResult) { auto const port = beast::lexicalCast(*optResult); - if (!port) + if (port == 0u) { std::stringstream ss; ss << "Invalid value '" << *optResult << "' for key 'port' in [" << name << "]"; @@ -999,30 +999,30 @@ Config::loadFromString(std::string const& fileContents) auto entries = getIniFileSection(iniFile, SECTION_VALIDATORS); - if (entries) + if (entries != nullptr) section(SECTION_VALIDATORS).append(*entries); auto valKeyEntries = getIniFileSection(iniFile, SECTION_VALIDATOR_KEYS); - if (valKeyEntries) + if (valKeyEntries != nullptr) section(SECTION_VALIDATOR_KEYS).append(*valKeyEntries); auto valSiteEntries = getIniFileSection(iniFile, SECTION_VALIDATOR_LIST_SITES); - if (valSiteEntries) + if (valSiteEntries != nullptr) section(SECTION_VALIDATOR_LIST_SITES).append(*valSiteEntries); auto valListKeys = getIniFileSection(iniFile, SECTION_VALIDATOR_LIST_KEYS); - if (valListKeys) + if (valListKeys != nullptr) section(SECTION_VALIDATOR_LIST_KEYS).append(*valListKeys); auto valListThreshold = getIniFileSection(iniFile, SECTION_VALIDATOR_LIST_THRESHOLD); - if (valListThreshold) + if (valListThreshold != nullptr) section(SECTION_VALIDATOR_LIST_THRESHOLD).append(*valListThreshold); - if (!entries && !valKeyEntries && !valListKeys) + if ((entries == nullptr) && (valKeyEntries == nullptr) && (valListKeys == nullptr)) { Throw( "The file specified in [" SECTION_VALIDATORS_FILE @@ -1315,7 +1315,7 @@ setup_DatabaseCon(Config const& c, std::optional j) if (page_size < 512 || page_size > 65536) Throw("Invalid page_size. Must be between 512 and 65536."); - if (page_size & (page_size - 1)) + if ((page_size & (page_size - 1)) != 0) Throw("Invalid page_size. Must be a power of 2."); } diff --git a/src/xrpld/overlay/Message.h b/src/xrpld/overlay/Message.h index 30650d384c..df59656ac2 100644 --- a/src/xrpld/overlay/Message.h +++ b/src/xrpld/overlay/Message.h @@ -91,7 +91,7 @@ private: * currently LZ4 only. If None then the message is uncompressed. * @param uncompressedBytes Size of the uncompressed message */ - void + static void setHeader( std::uint8_t* in, std::uint32_t payloadBytes, @@ -112,8 +112,8 @@ private: * @param in Payload header pointer * @return Message type */ - int - getType(std::uint8_t const* in) const; + static int + getType(std::uint8_t const* in); }; } // namespace xrpl diff --git a/src/xrpld/overlay/detail/Message.cpp b/src/xrpld/overlay/detail/Message.cpp index 754545f04a..4d043500c7 100644 --- a/src/xrpld/overlay/detail/Message.cpp +++ b/src/xrpld/overlay/detail/Message.cpp @@ -103,6 +103,7 @@ Message::compress() if (compressedSize < (messageBytes - (headerBytesCompressed - headerBytes))) { bufferCompressed_.resize(headerBytesCompressed + compressedSize); + // NOLINTNEXTLINE(readability-suspicious-call-argument) setHeader(bufferCompressed_.data(), compressedSize, type, Algorithm::LZ4, messageBytes); } else @@ -199,7 +200,7 @@ Message::getBuffer(Compressed tryCompressed) } int -Message::getType(std::uint8_t const* in) const +Message::getType(std::uint8_t const* in) { int type = (static_cast(*(in + 4)) << 8) + *(in + 5); return type; diff --git a/src/xrpld/overlay/detail/OverlayImpl.cpp b/src/xrpld/overlay/detail/OverlayImpl.cpp index d9077686ec..57eddd8b2c 100644 --- a/src/xrpld/overlay/detail/OverlayImpl.cpp +++ b/src/xrpld/overlay/detail/OverlayImpl.cpp @@ -810,19 +810,19 @@ OverlayImpl::processCrawl(http_request_type const& req, Handoff& handoff) msg.insert("Connection", "close"); msg.body()["version"] = Json::Value(2u); - if (setup_.crawlOptions & CrawlOptions::Overlay) + if ((setup_.crawlOptions & CrawlOptions::Overlay) != 0u) { msg.body()["overlay"] = getOverlayInfo(); } - if (setup_.crawlOptions & CrawlOptions::ServerInfo) + if ((setup_.crawlOptions & CrawlOptions::ServerInfo) != 0u) { msg.body()["server"] = getServerInfo(); } - if (setup_.crawlOptions & CrawlOptions::ServerCounts) + if ((setup_.crawlOptions & CrawlOptions::ServerCounts) != 0u) { msg.body()["counts"] = getServerCounts(); } - if (setup_.crawlOptions & CrawlOptions::Unl) + if ((setup_.crawlOptions & CrawlOptions::Unl) != 0u) { msg.body()["unl"] = getUnlInfo(); } @@ -1222,7 +1222,7 @@ OverlayImpl::relay( // relay to all disabled and some randomly selected enabled that // do not have the transaction. auto const enabledTarget = app_.config().TX_REDUCE_RELAY_MIN_PEERS + - (total - minRelay) * app_.config().TX_RELAY_PERCENTAGE / 100; + ((total - minRelay) * app_.config().TX_RELAY_PERCENTAGE / 100); txMetrics_.addMetrics(enabledTarget, toSkip.size(), disabled); diff --git a/src/xrpld/overlay/detail/OverlayImpl.h b/src/xrpld/overlay/detail/OverlayImpl.h index b77b4e69aa..c816f24e0c 100644 --- a/src/xrpld/overlay/detail/OverlayImpl.h +++ b/src/xrpld/overlay/detail/OverlayImpl.h @@ -429,7 +429,7 @@ private: http_request_type const& request, address_type remote_address); - std::shared_ptr + static std::shared_ptr makeErrorResponse( std::shared_ptr const& slot, http_request_type const& request, diff --git a/src/xrpld/overlay/detail/PeerImp.cpp b/src/xrpld/overlay/detail/PeerImp.cpp index 7ed8c45453..767e8bfd20 100644 --- a/src/xrpld/overlay/detail/PeerImp.cpp +++ b/src/xrpld/overlay/detail/PeerImp.cpp @@ -1509,7 +1509,7 @@ PeerImp::onMessage(std::shared_ptr const& m) } } else if ( - !m->has_ledgerhash() && !m->has_ledgerseq() && !(ltype && *ltype == protocol::ltCLOSED)) + !m->has_ledgerhash() && !m->has_ledgerseq() && (!ltype || *ltype != protocol::ltCLOSED)) { badData("Invalid request"); return; @@ -3376,7 +3376,7 @@ PeerImp::processLedgerRequest(std::shared_ptr const& m) } } - if (!map) + if (map == nullptr) { JLOG(p_journal_.warn()) << "processLedgerRequest: Unable to find map"; return; diff --git a/src/xrpld/peerfinder/detail/PeerfinderConfig.cpp b/src/xrpld/peerfinder/detail/PeerfinderConfig.cpp index cc74018fc0..4de03c6ca6 100644 --- a/src/xrpld/peerfinder/detail/PeerfinderConfig.cpp +++ b/src/xrpld/peerfinder/detail/PeerfinderConfig.cpp @@ -78,7 +78,7 @@ Config::makeConfig( // Servers with peer privacy don't want to allow incoming connections config.wantIncoming = (!config.peerPrivate) && (port != 0); - if (!cfg.PEERS_OUT_MAX && !cfg.PEERS_IN_MAX) + if ((cfg.PEERS_OUT_MAX == 0u) && (cfg.PEERS_IN_MAX == 0u)) { if (cfg.PEERS_MAX != 0) config.maxPeers = cfg.PEERS_MAX; diff --git a/src/xrpld/perflog/detail/PerfLogImp.cpp b/src/xrpld/perflog/detail/PerfLogImp.cpp index fc9ef70830..960fdcb3ac 100644 --- a/src/xrpld/perflog/detail/PerfLogImp.cpp +++ b/src/xrpld/perflog/detail/PerfLogImp.cpp @@ -70,8 +70,8 @@ PerfLogImp::Counters::countersJson() const Rpc value; { std::lock_guard lock(proc.second.mutex); - if (!proc.second.value.started && !proc.second.value.finished && - !proc.second.value.errored) + if ((proc.second.value.started == 0u) && (proc.second.value.finished == 0u) && + (proc.second.value.errored == 0u)) { continue; } @@ -90,7 +90,7 @@ PerfLogImp::Counters::countersJson() const rpcobj[proc.first] = p; } - if (totalRpc.started) + if (totalRpc.started != 0u) { Json::Value totalRpcJson(Json::objectValue); totalRpcJson[jss::started] = std::to_string(totalRpc.started); @@ -108,8 +108,8 @@ PerfLogImp::Counters::countersJson() const Jq value; { std::lock_guard lock(proc.second.mutex); - if (!proc.second.value.queued && !proc.second.value.started && - !proc.second.value.finished) + if ((proc.second.value.queued == 0u) && (proc.second.value.started == 0u) && + (proc.second.value.finished == 0u)) { continue; } @@ -130,7 +130,7 @@ PerfLogImp::Counters::countersJson() const jobQueueObj[JobTypes::name(proc.first)] = j; } - if (totalJq.queued) + if (totalJq.queued != 0u) { Json::Value totalJqJson(Json::objectValue); totalJqJson[jss::queued] = std::to_string(totalJq.queued); diff --git a/src/xrpld/rpc/detail/DeliveredAmount.cpp b/src/xrpld/rpc/detail/DeliveredAmount.cpp index 3e89edc1f9..e2f5bd8cd9 100644 --- a/src/xrpld/rpc/detail/DeliveredAmount.cpp +++ b/src/xrpld/rpc/detail/DeliveredAmount.cpp @@ -71,13 +71,8 @@ canHaveDeliveredAmount( TxType const tt{serializedTx->getTxnType()}; // Transaction type should be ttPAYMENT, ttACCOUNT_DELETE or ttCHECK_CASH // and if the transaction failed nothing could have been delivered. - if ((tt == ttPAYMENT || tt == ttCHECK_CASH || tt == ttACCOUNT_DELETE) && - transactionMeta.getResultTER() == tesSUCCESS) - { - return true; - } - - return false; + return (tt == ttPAYMENT || tt == ttCHECK_CASH || tt == ttACCOUNT_DELETE) && + transactionMeta.getResultTER() == tesSUCCESS; } void diff --git a/src/xrpld/rpc/detail/Handler.cpp b/src/xrpld/rpc/detail/Handler.cpp index 04cf0420b7..0f95e69d3f 100644 --- a/src/xrpld/rpc/detail/Handler.cpp +++ b/src/xrpld/rpc/detail/Handler.cpp @@ -150,7 +150,7 @@ private: // Use with equal_range to enforce that API range of a newly added handler // does not overlap with API range of an existing handler with same name - [[nodiscard]] bool + [[nodiscard]] static bool overlappingApiVersion( std::pair range, unsigned minVer, diff --git a/src/xrpld/rpc/detail/RPCCall.cpp b/src/xrpld/rpc/detail/RPCCall.cpp index cd36208294..c9d5d67cf3 100644 --- a/src/xrpld/rpc/detail/RPCCall.cpp +++ b/src/xrpld/rpc/detail/RPCCall.cpp @@ -149,6 +149,7 @@ private: using parseFuncPtr = Json::Value (RPCParser::*)(Json::Value const& jvParams); Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseAsIs(Json::Value const& jvParams) { Json::Value v(Json::objectValue); @@ -160,6 +161,7 @@ private: } Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseInternal(Json::Value const& jvParams) { Json::Value v(Json::objectValue); @@ -176,6 +178,7 @@ private: } Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseManifest(Json::Value const& jvParams) { if (jvParams.size() == 1) @@ -196,6 +199,7 @@ private: // fetch_info [clear] Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseFetchInfo(Json::Value const& jvParams) { Json::Value jvRequest(Json::objectValue); @@ -286,6 +290,7 @@ private: // // Mnemonic: taker pays --> offer --> taker gets Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseBookOffers(Json::Value const& jvParams) { Json::Value jvRequest(Json::objectValue); @@ -335,7 +340,7 @@ private: try { int bProof = jvParams[5u].asInt(); - if (bProof) + if (bProof != 0) jvRequest[jss::proof] = true; } catch (std::exception const&) @@ -352,11 +357,12 @@ private: // can_delete [||now|always|never] Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseCanDelete(Json::Value const& jvParams) { Json::Value jvRequest(Json::objectValue); - if (!jvParams.size()) + if (jvParams.size() == 0u) return jvRequest; std::string input = jvParams[0u].asString(); @@ -374,6 +380,7 @@ private: // connect [port] Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseConnect(Json::Value const& jvParams) { Json::Value jvRequest(Json::objectValue); @@ -402,6 +409,7 @@ private: // deposit_authorized // [ [, ...]] Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseDepositAuthorized(Json::Value const& jvParams) { Json::Value jvRequest(Json::objectValue); @@ -424,6 +432,7 @@ private: // Return an error for attempting to subscribe/unsubscribe via RPC. Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseEvented(Json::Value const& jvParams) { return rpcError(rpcNO_EVENTS); @@ -431,6 +440,7 @@ private: // feature [] [accept|reject] Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseFeature(Json::Value const& jvParams) { Json::Value jvRequest(Json::objectValue); @@ -464,11 +474,12 @@ private: // get_counts [] Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseGetCounts(Json::Value const& jvParams) { Json::Value jvRequest(Json::objectValue); - if (jvParams.size()) + if (jvParams.size() != 0u) jvRequest[jss::min_count] = jvParams[0u].asUInt(); return jvRequest; @@ -477,6 +488,7 @@ private: // sign_for offline // sign_for Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseSignFor(Json::Value const& jvParams) { bool const bOffline = 4 == jvParams.size() && jvParams[3u].asString() == "offline"; @@ -546,11 +558,9 @@ private: jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0" && jv.isMember(jss::id) && jv.isMember(jss::method)) { - if (jv.isMember(jss::params) && - !(jv[jss::params].isNull() || jv[jss::params].isArray() || - jv[jss::params].isObject())) - return false; - return true; + return !jv.isMember(jss::params) || + (jv[jss::params].isNull() || jv[jss::params].isArray() || + jv[jss::params].isObject()); } } return false; @@ -608,11 +618,12 @@ private: // ledger [id|index|current|closed|validated] [full|tx] Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseLedger(Json::Value const& jvParams) { Json::Value jvRequest(Json::objectValue); - if (!jvParams.size()) + if (jvParams.size() == 0u) { return jvRequest; } @@ -637,6 +648,7 @@ private: // ledger_header | Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseLedgerId(Json::Value const& jvParams) { Json::Value jvRequest(Json::objectValue); @@ -657,6 +669,7 @@ private: // ledger_entry [id] [] Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseLedgerEntry(Json::Value const& jvParams) { Json::Value jvRequest{Json::objectValue}; @@ -674,6 +687,7 @@ private: // specified severity log_level : Set specified // partition to specified severity Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseLogLevel(Json::Value const& jvParams) { Json::Value jvRequest(Json::objectValue); @@ -722,6 +736,7 @@ private: // channel_authorize: [] Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseChannelAuthorize(Json::Value const& jvParams) { Json::Value jvRequest(Json::objectValue); @@ -765,6 +780,7 @@ private: // channel_verify Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseChannelVerify(Json::Value const& jvParams) { std::string const strPk = jvParams[0u].asString(); @@ -793,6 +809,7 @@ private: } Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseAccountRaw2(Json::Value const& jvParams, char const* const acc2Field) { std::array accFields{{jss::account, acc2Field}}; @@ -830,6 +847,7 @@ private: // TODO: Get index from an alternate syntax: rXYZ: Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseAccountRaw1(Json::Value const& jvParams) { std::string strIdent = jvParams[0u].asString(); @@ -850,6 +868,7 @@ private: } Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseVault(Json::Value const& jvParams) { std::string strVaultID = jvParams[0u].asString(); @@ -868,6 +887,7 @@ private: // peer_reservations_add [] Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parsePeerReservationsAdd(Json::Value const& jvParams) { Json::Value jvRequest; @@ -881,6 +901,7 @@ private: // peer_reservations_del Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parsePeerReservationsDel(Json::Value const& jvParams) { Json::Value jvRequest; @@ -916,6 +937,7 @@ private: // simulate [binary] // simulate [binary] Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseSimulate(Json::Value const& jvParams) { Json::Value txJSON; @@ -947,6 +969,7 @@ private: // submit // submit Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseSignSubmit(Json::Value const& jvParams) { Json::Value txJSON; @@ -996,6 +1019,7 @@ private: // // submit_multisigned Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseSubmitMultiSigned(Json::Value const& jvParams) { if (1 == jvParams.size()) @@ -1015,6 +1039,7 @@ private: // transaction_entry Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseTransactionEntry(Json::Value const& jvParams) { // Parameter count should have already been verified. @@ -1040,6 +1065,7 @@ private: // tx Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseTx(Json::Value const& jvParams) { Json::Value jvRequest{Json::objectValue}; @@ -1072,6 +1098,7 @@ private: // tx_history Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseTxHistory(Json::Value const& jvParams) { Json::Value jvRequest{Json::objectValue}; @@ -1088,11 +1115,12 @@ private: // (e.g. .bash_history) and it may be leaked via the process status command // (i.e. ps). Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseValidationCreate(Json::Value const& jvParams) { Json::Value jvRequest{Json::objectValue}; - if (jvParams.size()) + if (jvParams.size() != 0u) jvRequest[jss::secret] = jvParams[0u].asString(); return jvRequest; @@ -1102,11 +1130,12 @@ private: // is only for testing. Master seeds should only be generated // randomly. Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseWalletPropose(Json::Value const& jvParams) { Json::Value jvRequest{Json::objectValue}; - if (jvParams.size()) + if (jvParams.size() != 0u) jvRequest[jss::passphrase] = jvParams[0u].asString(); return jvRequest; @@ -1117,6 +1146,7 @@ private: // ]] Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseGatewayBalances(Json::Value const& jvParams) { unsigned int index = 0; @@ -1159,6 +1189,7 @@ private: // server_definitions [hash] Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseServerDefinitions(Json::Value const& jvParams) { Json::Value jvRequest{Json::objectValue}; @@ -1173,6 +1204,7 @@ private: // server_info [counters] Json::Value + // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseServerInfo(Json::Value const& jvParams) { Json::Value jvRequest(Json::objectValue); @@ -1542,8 +1574,8 @@ rpcClient( return jvRequest[jss::method].asString(); return jvRequest.isArray() ? "batch" : args[0]; }(), - jvParams, // Parsed, execute. - setup.client.secure != 0, // Use SSL + jvParams, // Parsed, execute. + static_cast(setup.client.secure) != 0, // Use SSL config.quiet(), logs, std::bind(RPCCallImp::callRPCHandler, &jvOutput, std::placeholders::_1), diff --git a/src/xrpld/rpc/detail/RPCHandler.cpp b/src/xrpld/rpc/detail/RPCHandler.cpp index 840ebd5946..eea24ab0c0 100644 --- a/src/xrpld/rpc/detail/RPCHandler.cpp +++ b/src/xrpld/rpc/detail/RPCHandler.cpp @@ -137,7 +137,7 @@ fillHandler(JsonContext& context, Handler const*& result) JLOG(context.j.trace()) << "REQUEST:" << context.params; auto handler = getHandler(context.apiVersion, context.app.config().BETA_RPC_API, strCommand); - if (!handler) + if (handler == nullptr) return rpcUNKNOWN_COMMAND; if (handler->role_ == Role::ADMIN && context.role != Role::ADMIN) @@ -228,7 +228,7 @@ roleRequired(unsigned int version, bool betaEnabled, std::string const& method) { auto handler = RPC::getHandler(version, betaEnabled, method); - if (!handler) + if (handler == nullptr) return Role::FORBID; return handler->role_; diff --git a/src/xrpld/rpc/detail/RPCHelpers.cpp b/src/xrpld/rpc/detail/RPCHelpers.cpp index 832ff778e1..dd363c6d76 100644 --- a/src/xrpld/rpc/detail/RPCHelpers.cpp +++ b/src/xrpld/rpc/detail/RPCHelpers.cpp @@ -100,7 +100,7 @@ readLimitField(unsigned int& limit, Tuning::LimitRange const& range, JsonContext return std::nullopt; auto const& jvLimit = context.params[jss::limit]; - if (!(jvLimit.isUInt() || (jvLimit.isInt() && jvLimit.asInt() >= 0))) + if (!jvLimit.isUInt() && (!jvLimit.isInt() || jvLimit.asInt() < 0)) return RPC::expected_field_error(jss::limit, "unsigned integer"); limit = jvLimit.asUInt(); diff --git a/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp b/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp index 54ff515894..0136d8af18 100644 --- a/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp +++ b/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp @@ -375,7 +375,7 @@ getOrAcquireLedger(RPC::JsonContext const& context) auto& ledgerMaster = context.app.getLedgerMaster(); LedgerHash ledgerHash; - if ((hasHash + hasIndex) != 1) + if ((static_cast(hasHash) + static_cast(hasIndex)) != 1) { return Unexpected( RPC::make_param_error( diff --git a/src/xrpld/rpc/detail/ServerHandler.cpp b/src/xrpld/rpc/detail/ServerHandler.cpp index f5187d6285..917a9b7609 100644 --- a/src/xrpld/rpc/detail/ServerHandler.cpp +++ b/src/xrpld/rpc/detail/ServerHandler.cpp @@ -126,14 +126,14 @@ ServerHandler::setup(Setup const& setup, beast::Journal journal) if (auto it = endpoints_.find(port.name); it != endpoints_.end()) { auto const endpointPort = it->second.port(); - if (!port.port) + if (port.port == 0u) port.port = endpointPort; - if (!setup_.client.port && + if ((setup_.client.port == 0u) && (port.protocol.count("http") > 0 || port.protocol.count("https") > 0)) setup_.client.port = endpointPort; - if (!setup_.overlay.port() && (port.protocol.count("peer") > 0)) + if ((setup_.overlay.port() == 0u) && (port.protocol.count("peer") > 0)) setup_.overlay.port(endpointPort); } } @@ -163,7 +163,7 @@ ServerHandler::onAccept(Session& session, boost::asio::ip::tcp::endpoint endpoin return ++count_[port]; }(); - if (port.limit && c >= port.limit) + if ((port.limit != 0) && c >= port.limit) { JLOG(m_journal.trace()) << port.name << " is full; dropping " << endpoint; return false; @@ -1135,7 +1135,7 @@ parse_Ports(Config const& config, std::ostream& log) // Remove the peer protocol, and if that would // leave the port empty, remove the port as well - if (p.erase("peer") && p.empty()) + if ((p.erase("peer") != 0u) && p.empty()) { it = result.erase(it); } diff --git a/src/xrpld/rpc/detail/TransactionSign.cpp b/src/xrpld/rpc/detail/TransactionSign.cpp index 80c608dbbf..73385f62ef 100644 --- a/src/xrpld/rpc/detail/TransactionSign.cpp +++ b/src/xrpld/rpc/detail/TransactionSign.cpp @@ -79,7 +79,7 @@ public: AccountID const& getSigner() const { - if (!multiSigningAcctID_) + if (multiSigningAcctID_ == nullptr) LogicError("Accessing unknown SigningForParams::getSigner()"); return *multiSigningAcctID_; } @@ -207,7 +207,7 @@ checkPayment( if (!dstAccountID) return RPC::invalid_field_error("tx_json.Destination"); - if (params.isMember(jss::build_path) && ((doPath == false) || amount.holds())) + if (params.isMember(jss::build_path) && ((!doPath) || amount.holds())) { return RPC::make_error( rpcINVALID_PARAMS, "Field 'build_path' not allowed in this context."); @@ -428,7 +428,7 @@ transactionPreProcessImpl( : nullptr; if (signatureTarget) { - if (!signatureTemplate) + if (signatureTemplate == nullptr) { // Invalid target field return RPC::make_error(rpcINVALID_PARAMS, signatureTarget->get().getName()); } diff --git a/src/xrpld/rpc/handlers/AccountInfo.cpp b/src/xrpld/rpc/handlers/AccountInfo.cpp index 15a6786e22..55f05ddcab 100644 --- a/src/xrpld/rpc/handlers/AccountInfo.cpp +++ b/src/xrpld/rpc/handlers/AccountInfo.cpp @@ -290,9 +290,9 @@ doAccountInfo(RPC::JsonContext& context) jvQueueTx.append(std::move(jvTx)); } - if (seqCount) + if (seqCount != 0u) jvQueueData[jss::sequence_count] = seqCount; - if (ticketCount) + if (ticketCount != 0u) jvQueueData[jss::ticket_count] = ticketCount; if (lowestSeq) jvQueueData[jss::lowest_sequence] = *lowestSeq; diff --git a/src/xrpld/rpc/handlers/CanDelete.cpp b/src/xrpld/rpc/handlers/CanDelete.cpp index 91466c2583..052ebdf745 100644 --- a/src/xrpld/rpc/handlers/CanDelete.cpp +++ b/src/xrpld/rpc/handlers/CanDelete.cpp @@ -49,7 +49,7 @@ doCanDelete(RPC::JsonContext& context) else if (canDeleteStr == "now") { canDeleteSeq = context.app.getSHAMapStore().getLastRotated(); - if (!canDeleteSeq) + if (canDeleteSeq == 0u) return RPC::make_error(rpcNOT_READY); } else if (uint256 lh; lh.parseHex(canDeleteStr)) diff --git a/src/xrpld/rpc/handlers/DepositAuthorized.cpp b/src/xrpld/rpc/handlers/DepositAuthorized.cpp index 080b136964..b2fc13415e 100644 --- a/src/xrpld/rpc/handlers/DepositAuthorized.cpp +++ b/src/xrpld/rpc/handlers/DepositAuthorized.cpp @@ -73,7 +73,7 @@ doDepositAuthorized(RPC::JsonContext& context) return result; } - bool const reqAuth = (sleDest->getFlags() & lsfDepositAuth) && (srcAcct != dstAcct); + bool const reqAuth = ((sleDest->getFlags() & lsfDepositAuth) != 0u) && (srcAcct != dstAcct); bool const credentialsPresent = params.isMember(jss::credentials); std::set> sorted; @@ -122,7 +122,7 @@ doDepositAuthorized(RPC::JsonContext& context) return result; } - if (!(sleCred->getFlags() & lsfAccepted)) + if ((sleCred->getFlags() & lsfAccepted) == 0u) { RPC::inject_error(rpcBAD_CREDENTIALS, "credentials aren't accepted", result); return result; diff --git a/src/xrpld/rpc/handlers/GetAggregatePrice.cpp b/src/xrpld/rpc/handlers/GetAggregatePrice.cpp index cf327258a3..4979c21f42 100644 --- a/src/xrpld/rpc/handlers/GetAggregatePrice.cpp +++ b/src/xrpld/rpc/handlers/GetAggregatePrice.cpp @@ -56,7 +56,7 @@ iteratePriceData( if (prevChain == chain) return; - if (!oracle || f(*oracle) || isNew) + if ((oracle == nullptr) || f(*oracle) || isNew) return; if (++history > maxHistory) diff --git a/src/xrpld/rpc/handlers/LedgerHandler.cpp b/src/xrpld/rpc/handlers/LedgerHandler.cpp index 43c9780bb0..cd70cb064a 100644 --- a/src/xrpld/rpc/handlers/LedgerHandler.cpp +++ b/src/xrpld/rpc/handlers/LedgerHandler.cpp @@ -103,7 +103,7 @@ LedgerHandler::writeResult(Json::Value& value) "and update your request. Field `type` is deprecated."; } - if (warnings.size()) + if (warnings.size() != 0u) value[jss::warnings] = std::move(warnings); } diff --git a/src/xrpld/rpc/handlers/NoRippleCheck.cpp b/src/xrpld/rpc/handlers/NoRippleCheck.cpp index 73f51fca1a..a0f797214d 100644 --- a/src/xrpld/rpc/handlers/NoRippleCheck.cpp +++ b/src/xrpld/rpc/handlers/NoRippleCheck.cpp @@ -107,16 +107,16 @@ doNoRippleCheck(RPC::JsonContext& context) Json::Value& problems = (result["problems"] = Json::arrayValue); - bool bDefaultRipple = sle->getFieldU32(sfFlags) & lsfDefaultRipple; + bool bDefaultRipple = (sle->getFieldU32(sfFlags) & lsfDefaultRipple) != 0u; - if (bDefaultRipple & !roleGateway) + if ((static_cast(bDefaultRipple) & static_cast(!roleGateway)) != 0) { problems.append( "You appear to have set your default ripple flag even though you " "are not a gateway. This is not recommended unless you are " "experimenting"); } - else if (roleGateway & !bDefaultRipple) + else if ((static_cast(roleGateway) & static_cast(!bDefaultRipple)) != 0) { problems.append("You should immediately set your default ripple flag"); if (transactions) diff --git a/src/xrpld/rpc/handlers/ServerDefinitions.cpp b/src/xrpld/rpc/handlers/ServerDefinitions.cpp index 24abd69a02..e4f08d6dec 100644 --- a/src/xrpld/rpc/handlers/ServerDefinitions.cpp +++ b/src/xrpld/rpc/handlers/ServerDefinitions.cpp @@ -24,7 +24,7 @@ namespace detail { class ServerDefinitions { private: - std::string + static std::string // translate e.g. STI_LEDGERENTRY to LedgerEntry translate(std::string const& inp); From f7bb4018fa4b6ecff199dd85718d9f6659b798a3 Mon Sep 17 00:00:00 2001 From: Mayukha Vadari Date: Tue, 24 Mar 2026 11:53:49 -0700 Subject: [PATCH 07/53] fix: Assorted Vault fixes (#6607) --- src/libxrpl/ledger/View.cpp | 3 +-- src/libxrpl/ledger/helpers/VaultHelpers.cpp | 2 +- src/libxrpl/tx/transactors/vault/VaultDelete.cpp | 6 ++---- 3 files changed, 4 insertions(+), 7 deletions(-) diff --git a/src/libxrpl/ledger/View.cpp b/src/libxrpl/ledger/View.cpp index ef6a66744d..227eafbec8 100644 --- a/src/libxrpl/ledger/View.cpp +++ b/src/libxrpl/ledger/View.cpp @@ -433,8 +433,7 @@ doWithdraw( j) < amount) { // LCOV_EXCL_START - JLOG(j.error()) << "LoanBrokerCoverWithdraw: negative balance of " - "broker cover assets."; + JLOG(j.error()) << "doWithdraw: negative balance of broker cover assets."; return tefINTERNAL; // LCOV_EXCL_STOP } diff --git a/src/libxrpl/ledger/helpers/VaultHelpers.cpp b/src/libxrpl/ledger/helpers/VaultHelpers.cpp index 3ded720289..83a1b9fc4f 100644 --- a/src/libxrpl/ledger/helpers/VaultHelpers.cpp +++ b/src/libxrpl/ledger/helpers/VaultHelpers.cpp @@ -92,7 +92,7 @@ sharesToAssetsWithdraw( std::shared_ptr const& issuance, STAmount const& shares) { - XRPL_ASSERT(!shares.negative(), "xrpl::sharesToAssetsDeposit : non-negative shares"); + XRPL_ASSERT(!shares.negative(), "xrpl::sharesToAssetsWithdraw : non-negative shares"); XRPL_ASSERT( shares.asset() == vault->at(sfShareMPTID), "xrpl::sharesToAssetsWithdraw : shares and vault match"); diff --git a/src/libxrpl/tx/transactors/vault/VaultDelete.cpp b/src/libxrpl/tx/transactors/vault/VaultDelete.cpp index 1e2e46e165..5a60c0032c 100644 --- a/src/libxrpl/tx/transactors/vault/VaultDelete.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultDelete.cpp @@ -55,7 +55,7 @@ VaultDelete::preclaim(PreclaimContext const& ctx) if (!sleMPT) { // LCOV_EXCL_START - JLOG(ctx.j.error()) << "VaultDeposit: missing issuance of vault shares."; + JLOG(ctx.j.error()) << "VaultDelete: missing issuance of vault shares."; return tecOBJECT_NOT_FOUND; // LCOV_EXCL_STOP } @@ -63,7 +63,7 @@ VaultDelete::preclaim(PreclaimContext const& ctx) if (sleMPT->at(sfIssuer) != vault->getAccountID(sfAccount)) { // LCOV_EXCL_START - JLOG(ctx.j.error()) << "VaultDeposit: invalid owner of vault shares."; + JLOG(ctx.j.error()) << "VaultDelete: invalid owner of vault shares."; return tecNO_PERMISSION; // LCOV_EXCL_STOP } @@ -200,8 +200,6 @@ VaultDelete::doApply() // Destroy the vault. view().erase(vault); - associateAsset(*vault, asset); - return tesSUCCESS; } From 85a4015a64b1c6246dbc44d7b828227f4f8b3f76 Mon Sep 17 00:00:00 2001 From: Mayukha Vadari Date: Tue, 24 Mar 2026 11:53:57 -0700 Subject: [PATCH 08/53] fix: Assorted Permissioned Domain fixes (#6587) --- .../transactors/permissioned_domain/PermissionedDomainSet.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainSet.cpp b/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainSet.cpp index e8df51c9d9..30f24241aa 100644 --- a/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainSet.cpp +++ b/src/libxrpl/tx/transactors/permissioned_domain/PermissionedDomainSet.cpp @@ -100,8 +100,6 @@ PermissionedDomainSet::doApply() Keylet const pdKeylet = keylet::permissionedDomain(account_, ctx_.tx.getFieldU32(sfSequence)); auto slePd = std::make_shared(pdKeylet); - if (!slePd) - return tefINTERNAL; // LCOV_EXCL_LINE slePd->setAccountID(sfOwner, account_); slePd->setFieldU32(sfSequence, ctx_.tx.getFieldU32(sfSequence)); From dda162087ff7bc3c88365739b4aee2cfd7b9b9c8 Mon Sep 17 00:00:00 2001 From: Alex Kremer Date: Tue, 24 Mar 2026 21:18:03 +0000 Subject: [PATCH 09/53] docs: Add note about `clang-tidy` installation (#6634) --- CONTRIBUTING.md | 13 +++++++++++-- docs/build/environment.md | 29 +++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 86bef765a5..8670b79db9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -259,6 +259,10 @@ There is a Continuous Integration job that runs clang-tidy on pull requests. The This ensures that configuration changes don't introduce new warnings across the codebase. +### Installing clang-tidy + +See the [environment setup guide](./docs/build/environment.md#clang-tidy) for platform-specific installation instructions. + ### Running clang-tidy locally Before running clang-tidy, you must build the project to generate required files (particularly protobuf headers). Refer to [`BUILD.md`](./BUILD.md) for build instructions. @@ -266,10 +270,15 @@ Before running clang-tidy, you must build the project to generate required files Then run clang-tidy on your local changes: ``` -run-clang-tidy -p build src tests +run-clang-tidy -p build src include tests ``` -This will check all source files in the `src` and `tests` directories using the compile commands from your `build` directory. +This will check all source files in the `src`, `include` and `tests` directories using the compile commands from your `build` directory. +If you wish to automatically fix whatever clang-tidy finds _and_ is capable of fixing, add `-fix` to the above command: + +``` +run-clang-tidy -p build -fix src include tests +``` ## Contracts and instrumentation diff --git a/docs/build/environment.md b/docs/build/environment.md index c67877a082..66bed06c26 100644 --- a/docs/build/environment.md +++ b/docs/build/environment.md @@ -109,3 +109,32 @@ Install CMake with Homebrew too: ``` brew install cmake ``` + +## Clang-tidy + +Clang-tidy is required to run static analysis checks locally (see [CONTRIBUTING.md](../../CONTRIBUTING.md)). +It is not required to build the project. Currently this project uses clang-tidy version 21. + +### Linux + +LLVM 21 is not available in the default Debian 12 (Bookworm) repositories. +Install it using the official LLVM apt installer: + +``` +wget https://apt.llvm.org/llvm.sh +chmod +x llvm.sh +sudo ./llvm.sh 21 +sudo apt install --yes clang-tidy-21 +``` + +Then use `run-clang-tidy-21` when running clang-tidy locally. + +### macOS + +Install LLVM 21 via Homebrew: + +``` +brew install llvm@21 +``` + +Then use `run-clang-tidy` from the LLVM 21 Homebrew prefix when running clang-tidy locally. From 4096623ae163d6e1ef23795726b62cf220a80abb Mon Sep 17 00:00:00 2001 From: Jingchen Date: Tue, 24 Mar 2026 23:00:41 +0000 Subject: [PATCH 10/53] chore: Remove the forward declarations that cause build errors when unity build is enabled (#6633) Signed-off-by: JCW --- src/libxrpl/ledger/helpers/MPTokenHelpers.cpp | 24 ++++--------------- 1 file changed, 5 insertions(+), 19 deletions(-) diff --git a/src/libxrpl/ledger/helpers/MPTokenHelpers.cpp b/src/libxrpl/ledger/helpers/MPTokenHelpers.cpp index cbf37a06a8..31c1d543f5 100644 --- a/src/libxrpl/ledger/helpers/MPTokenHelpers.cpp +++ b/src/libxrpl/ledger/helpers/MPTokenHelpers.cpp @@ -1,6 +1,7 @@ #include // #include +#include #include #include #include @@ -12,21 +13,6 @@ namespace xrpl { -// Forward declarations for functions that remain in View.h/cpp -bool -isVaultPseudoAccountFrozen( - ReadView const& view, - AccountID const& account, - MPTIssue const& mptShare, - int depth); - -[[nodiscard]] TER -dirLink( - ApplyView& view, - AccountID const& owner, - std::shared_ptr& object, - SF_UINT64 const& node = sfOwnerNode); - bool isGlobalFrozen(ReadView const& view, MPTIssue const& mptIssue) { @@ -83,7 +69,7 @@ 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)}; + return Rate{1'000'000'000u + (10'000 * sle->getFieldU16(sfTransferFee))}; return parityRate; } @@ -149,7 +135,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) + if ((flags & tfMPTUnauthorize) != 0) { auto const mptokenKey = keylet::mptoken(mptIssuanceID, account); auto const sleMpt = view.peek(mptokenKey); @@ -229,7 +215,7 @@ authorizeMPToken( // Issuer wants to unauthorize the holder, unset lsfMPTAuthorized on // their MPToken - if (flags & tfMPTUnauthorize) + if ((flags & tfMPTUnauthorize) != 0) { flagsOut &= ~lsfMPTAuthorized; } @@ -490,7 +476,7 @@ canTransfer( if (!sleIssuance) return tecOBJECT_NOT_FOUND; - if (!(sleIssuance->getFieldU32(sfFlags) & lsfMPTCanTransfer)) + if (!sleIssuance->isFlag(lsfMPTCanTransfer)) { if (from != (*sleIssuance)[sfIssuer] && to != (*sleIssuance)[sfIssuer]) return TER{tecNO_AUTH}; From 589c9c694ce2a7669c5bcac76e8f4de4c62e76ad Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Tue, 24 Mar 2026 23:18:41 +0000 Subject: [PATCH 11/53] chore: Update external dependencies due to upstream merge (#6630) --- conan.lock | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/conan.lock b/conan.lock index 900d3526e1..291258441f 100644 --- a/conan.lock +++ b/conan.lock @@ -6,11 +6,11 @@ "sqlite3/3.49.1#8631739a4c9b93bd3d6b753bac548a63%1765850149.926", "soci/4.0.3#a9f8d773cd33e356b5879a4b0564f287%1765850149.46", "snappy/1.1.10#968fef506ff261592ec30c574d4a7809%1765850147.878", - "secp256k1/0.7.1#3a61e95e220062ef32c48d019e9c81f7%1770306721.686", + "secp256k1/0.7.1#481881709eb0bdd0185a12b912bbe8ad%1770910500.329", "rocksdb/10.5.1#4a197eca381a3e5ae8adf8cffa5aacd0%1765850186.86", - "re2/20230301#ca3b241baec15bd31ea9187150e0b333%1765850148.103", + "re2/20251105#8579cfd0bda4daf0683f9e3898f964b4%1772560729.95", "protobuf/6.32.1#f481fd276fc23a33b85a3ed1e898b693%1765850161.038", - "openssl/3.5.5#05a4ac5b7323f7a329b2db1391d9941f%1769599205.414", + "openssl/3.5.5#e6399de266349245a4542fc5f6c71552%1774367199.56", "nudb/2.0.9#0432758a24204da08fee953ec9ea03cb%1769436073.32", "lz4/1.10.0#59fc63cac7f10fbe8e05c7e62c2f3504%1765850143.914", "libiconv/1.17#1e65319e945f2d31941a9d28cc13c058%1765842973.492", @@ -18,27 +18,27 @@ "libarchive/3.8.1#ffee18995c706e02bf96e7a2f7042e0d%1765850144.736", "jemalloc/5.3.0#e951da9cf599e956cebc117880d2d9f8%1729241615.244", "gtest/1.17.0#5224b3b3ff3b4ce1133cbdd27d53ee7d%1768312129.152", - "grpc/1.72.0#f244a57bff01e708c55a1100b12e1589%1765850193.734", + "grpc/1.72.0#500d27f2cbb105a0ffb708e64a0f1781%1774369626.679", "ed25519/2015.03#ae761bdc52730a843f0809bdf6c1b1f6%1765850143.772", "date/3.0.4#862e11e80030356b53c2c38599ceb32b%1765850143.772", "c-ares/1.34.5#5581c2b62a608b40bb85d965ab3ec7c8%1765850144.336", "bzip2/1.0.8#c470882369c2d95c5c77e970c0c7e321%1765850143.837", "boost/1.90.0#d5e8defe7355494953be18524a7f135b%1769454080.269", - "abseil/20250127.0#99262a368bd01c0ccca8790dfced9719%1766517936.993" + "abseil/20250127.0#bb0baf1f362bc4a725a24eddd419b8f7%1774365460.196" ], "build_requires": [ "zlib/1.3.1#b8bc2603263cf7eccbd6e17e66b0ed76%1765850150.075", "strawberryperl/5.32.1.1#707032463aa0620fa17ec0d887f5fe41%1765850165.196", "protobuf/6.32.1#f481fd276fc23a33b85a3ed1e898b693%1765850161.038", "nasm/2.16.01#31e26f2ee3c4346ecd347911bd126904%1765850144.707", - "msys2/cci.latest#eea83308ad7e9023f7318c60d5a9e6cb%1770199879.083", - "m4/1.4.19#70dc8bbb33e981d119d2acc0175cf381%1763158052.846", + "msys2/cci.latest#d22fe7b2808f5fd34d0a7923ace9c54f%1770657326.649", + "m4/1.4.19#5d7a4994e5875d76faf7acf3ed056036%1774365463.87", "cmake/4.2.0#ae0a44f44a1ef9ab68fd4b3e9a1f8671%1765850153.937", "cmake/3.31.10#313d16a1aa16bbdb2ca0792467214b76%1765850153.479", "b2/5.3.3#107c15377719889654eb9a162a673975%1765850144.355", "automake/1.16.5#b91b7c384c3deaa9d535be02da14d04f%1755524470.56", "autoconf/2.71#51077f068e61700d65bb05541ea1e4b0%1731054366.86", - "abseil/20250127.0#99262a368bd01c0ccca8790dfced9719%1766517936.993" + "abseil/20250127.0#bb0baf1f362bc4a725a24eddd419b8f7%1774365460.196" ], "python_requires": [], "overrides": { @@ -46,7 +46,7 @@ null, "boost/1.90.0" ], - "protobuf/5.27.0": [ + "protobuf/[>=5.27.0 <7]": [ "protobuf/6.32.1" ], "lz4/1.9.4": [ From 0510ee47d7b2832a601cd42bbb4c0997281169b3 Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Wed, 25 Mar 2026 10:44:14 +0000 Subject: [PATCH 12/53] chore: Update some external dependencies (#6642) --- conan.lock | 22 +++++++++++----------- conanfile.py | 2 +- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/conan.lock b/conan.lock index 291258441f..2460a15fb0 100644 --- a/conan.lock +++ b/conan.lock @@ -1,7 +1,7 @@ { "version": "0.5", "requires": [ - "zlib/1.3.1#b8bc2603263cf7eccbd6e17e66b0ed76%1765850150.075", + "zlib/1.3.1#cac0f6daea041b0ccf42934163defb20%1765284699.337", "xxhash/0.8.3#681d36a0a6111fc56e5e45ea182c19cc%1765850149.987", "sqlite3/3.49.1#8631739a4c9b93bd3d6b753bac548a63%1765850149.926", "soci/4.0.3#a9f8d773cd33e356b5879a4b0564f287%1765850149.46", @@ -9,7 +9,7 @@ "secp256k1/0.7.1#481881709eb0bdd0185a12b912bbe8ad%1770910500.329", "rocksdb/10.5.1#4a197eca381a3e5ae8adf8cffa5aacd0%1765850186.86", "re2/20251105#8579cfd0bda4daf0683f9e3898f964b4%1772560729.95", - "protobuf/6.32.1#f481fd276fc23a33b85a3ed1e898b693%1765850161.038", + "protobuf/6.32.1#b54f00da2e0f61d821330b5b638b0f80%1768401317.762", "openssl/3.5.5#e6399de266349245a4542fc5f6c71552%1774367199.56", "nudb/2.0.9#0432758a24204da08fee953ec9ea03cb%1769436073.32", "lz4/1.10.0#59fc63cac7f10fbe8e05c7e62c2f3504%1765850143.914", @@ -18,24 +18,24 @@ "libarchive/3.8.1#ffee18995c706e02bf96e7a2f7042e0d%1765850144.736", "jemalloc/5.3.0#e951da9cf599e956cebc117880d2d9f8%1729241615.244", "gtest/1.17.0#5224b3b3ff3b4ce1133cbdd27d53ee7d%1768312129.152", - "grpc/1.72.0#500d27f2cbb105a0ffb708e64a0f1781%1774369626.679", + "grpc/1.72.0#aaade9421980b2d926dbfb613d56c38a%1774376249.106", "ed25519/2015.03#ae761bdc52730a843f0809bdf6c1b1f6%1765850143.772", "date/3.0.4#862e11e80030356b53c2c38599ceb32b%1765850143.772", - "c-ares/1.34.5#5581c2b62a608b40bb85d965ab3ec7c8%1765850144.336", + "c-ares/1.34.6#545240bb1c40e2cacd4362d6b8967650%1766500685.317", "bzip2/1.0.8#c470882369c2d95c5c77e970c0c7e321%1765850143.837", "boost/1.90.0#d5e8defe7355494953be18524a7f135b%1769454080.269", "abseil/20250127.0#bb0baf1f362bc4a725a24eddd419b8f7%1774365460.196" ], "build_requires": [ - "zlib/1.3.1#b8bc2603263cf7eccbd6e17e66b0ed76%1765850150.075", - "strawberryperl/5.32.1.1#707032463aa0620fa17ec0d887f5fe41%1765850165.196", - "protobuf/6.32.1#f481fd276fc23a33b85a3ed1e898b693%1765850161.038", + "zlib/1.3.1#cac0f6daea041b0ccf42934163defb20%1765284699.337", + "strawberryperl/5.32.1.1#8d114504d172cfea8ea1662d09b6333e%1751971032.423", + "protobuf/6.32.1#b54f00da2e0f61d821330b5b638b0f80%1768401317.762", "nasm/2.16.01#31e26f2ee3c4346ecd347911bd126904%1765850144.707", "msys2/cci.latest#d22fe7b2808f5fd34d0a7923ace9c54f%1770657326.649", "m4/1.4.19#5d7a4994e5875d76faf7acf3ed056036%1774365463.87", - "cmake/4.2.0#ae0a44f44a1ef9ab68fd4b3e9a1f8671%1765850153.937", - "cmake/3.31.10#313d16a1aa16bbdb2ca0792467214b76%1765850153.479", - "b2/5.3.3#107c15377719889654eb9a162a673975%1765850144.355", + "cmake/4.3.0#b939a42e98f593fb34d3a8c5cc860359%1773780142.26", + "cmake/3.31.11#f325c933f618a1fcebc1e1c0babfd1ba%1769622857.944", + "b2/5.4.2#ffd6084a119587e70f11cd45d1a386e2%1766594659.866", "automake/1.16.5#b91b7c384c3deaa9d535be02da14d04f%1755524470.56", "autoconf/2.71#51077f068e61700d65bb05541ea1e4b0%1731054366.86", "abseil/20250127.0#bb0baf1f362bc4a725a24eddd419b8f7%1774365460.196" @@ -52,7 +52,7 @@ "lz4/1.9.4": [ "lz4/1.10.0" ], - "sqlite3/3.44.2": [ + "sqlite3/[>=3.44 <4]": [ "sqlite3/3.49.1" ], "boost/1.83.0": [ diff --git a/conanfile.py b/conanfile.py index e16d7eb69e..0bed2af80f 100644 --- a/conanfile.py +++ b/conanfile.py @@ -1,5 +1,5 @@ -import re import os +import re from conan.tools.cmake import CMake, CMakeToolchain, cmake_layout From 0dc0c8e912fbb709ef7eaa8dd59d51b185d633a5 Mon Sep 17 00:00:00 2001 From: Bart Date: Wed, 25 Mar 2026 10:24:10 -0400 Subject: [PATCH 13/53] docs: Update LICENSE.md year to present (#6636) Co-authored-by: Bart <11445373+bthomee@users.noreply.github.com> --- LICENSE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE.md b/LICENSE.md index c5e3ad0532..7e6e62994c 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,7 +1,7 @@ ISC License Copyright (c) 2011, Arthur Britto, David Schwartz, Jed McCaleb, Vinnie Falco, Bob Way, Eric Lombrozo, Nikolaos D. Bougalis, Howard Hinnant. -Copyright (c) 2012-2025, the XRP Ledger developers. +Copyright (c) 2012-present, the XRP Ledger developers. Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above From dfed0481f74acc3041b6f61d628c2a06ea19c499 Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Wed, 25 Mar 2026 14:25:33 +0000 Subject: [PATCH 14/53] docs: Rewrite conan docs for custom recipes (#6647) --- BUILD.md | 77 +++++++++++----------------------------------- cspell.config.yaml | 1 + 2 files changed, 19 insertions(+), 59 deletions(-) diff --git a/BUILD.md b/BUILD.md index 4d01700a61..4f709a032b 100644 --- a/BUILD.md +++ b/BUILD.md @@ -125,9 +125,9 @@ default profile. ### Patched recipes -The recipes in Conan Center occasionally need to be patched for compatibility -with the latest version of `xrpld`. We maintain a fork of the Conan Center -[here](https://github.com/XRPLF/conan-center-index/) containing the patches. +Occasionally, we need patched recipes or recipes not present in Conan Center. +We maintain a fork of the Conan Center Index +[here](https://github.com/XRPLF/conan-center-index/) containing the modified and newly added recipes. To ensure our patched recipes are used, you must add our Conan remote at a higher index than the default Conan Center remote, so it is consulted first. You @@ -137,19 +137,11 @@ can do this by running: conan remote add --index 0 xrplf https://conan.ripplex.io ``` -Alternatively, you can pull the patched recipes into the repository and use them -locally: +Alternatively, you can pull our recipes from the repository and export them locally: ```bash -# Extract the version number from the lockfile. -function extract_version { - version=$(cat conan.lock | sed -nE "s@.+${1}/(.+)#.+@\1@p" | head -n1) - echo ${version} -} - # Define which recipes to export. -recipes=('ed25519' 'grpc' 'nudb' 'openssl' 'secp256k1' 'snappy' 'soci') -folders=('all' 'all' 'all' '3.x.x' 'all' 'all' 'all') +recipes=('abseil' 'ed25519' 'grpc' 'm4' 'mpt-crypto' 'nudb' 'openssl' 'secp256k1' 'snappy' 'soci' 'wasm-xrplf' 'wasmi') # Selectively check out the recipes from our CCI fork. cd external @@ -158,29 +150,19 @@ cd conan-center-index git init git remote add origin git@github.com:XRPLF/conan-center-index.git git sparse-checkout init -for ((index = 1; index <= ${#recipes[@]}; index++)); do - recipe=${recipes[index]} - folder=${folders[index]} - echo "Checking out recipe '${recipe}' from folder '${folder}'..." - git sparse-checkout add recipes/${recipe}/${folder} +for recipe in "${recipes[@]}"; do + echo "Checking out recipe '${recipe}'..." + git sparse-checkout add recipes/${recipe} done git fetch origin master git checkout master -cd ../.. -# Export the recipes into the local cache. -for ((index = 1; index <= ${#recipes[@]}; index++)); do - recipe=${recipes[index]} - folder=${folders[index]} - version=$(extract_version ${recipe}) - echo "Exporting '${recipe}/${version}' from '${recipe}/${folder}'..." - conan export --version $(extract_version ${recipe}) \ - external/conan-center-index/recipes/${recipe}/${folder} -done +./export_all.sh +cd ../../ ``` In the case we switch to a newer version of a dependency that still requires a -patch, it will be necessary for you to pull in the changes and re-export the +patch or add a new dependency, it will be necessary for you to pull in the changes and re-export the updated dependencies with the newer version. However, if we switch to a newer version that no longer requires a patch, no action is required on your part, as the new recipe will be automatically pulled from the official Conan Center. @@ -189,6 +171,8 @@ the new recipe will be automatically pulled from the official Conan Center. > You might need to add `--lockfile=""` to your `conan install` command > to avoid automatic use of the existing `conan.lock` file when you run > `conan export` manually on your machine +> +> This is not recommended though, as you might end up using different revisions of recipes. ### Conan profile tweaks @@ -204,39 +188,14 @@ Possible values are ['5.0', '5.1', '6.0', '6.1', '7.0', '7.3', '8.0', '8.1', Read "http://docs.conan.io/2/knowledge/faq.html#error-invalid-setting" ``` -you need to amend the list of compiler versions in -`$(conan config home)/settings.yml`, by appending the required version number(s) +you need to add your compiler to the list of compiler versions in +`$(conan config home)/settings_user.yml`, by adding the required version number(s) to the `version` array specific for your compiler. For example: ```yaml -apple-clang: - version: - [ - "5.0", - "5.1", - "6.0", - "6.1", - "7.0", - "7.3", - "8.0", - "8.1", - "9.0", - "9.1", - "10.0", - "11.0", - "12.0", - "13", - "13.0", - "13.1", - "14", - "14.0", - "15", - "15.0", - "16", - "16.0", - "17", - "17.0", - ] +compiler: + apple-clang: + version: ["17.0"] ``` #### Multiple compilers diff --git a/cspell.config.yaml b/cspell.config.yaml index d1b8504021..63edba587d 100644 --- a/cspell.config.yaml +++ b/cspell.config.yaml @@ -297,6 +297,7 @@ words: - venv - vfalco - vinnie + - wasmi - wextra - wptr - writeme From 403fd7c649b804ce96b48671137d00e746e3e99b Mon Sep 17 00:00:00 2001 From: Alex Kremer Date: Wed, 25 Mar 2026 14:28:28 +0000 Subject: [PATCH 15/53] fix: More clang-tidy issues found after merging to develop (#6640) Co-authored-by: Ayaz Salikhov Co-authored-by: Bart --- .github/workflows/reusable-clang-tidy.yml | 2 +- .../ledger/helpers/DirectoryHelpers.cpp | 2 +- .../ledger/helpers/RippleStateHelpers.cpp | 23 ++++++++++--------- src/libxrpl/ledger/helpers/TokenHelpers.cpp | 11 +++++---- .../beast/beast_io_latency_probe_test.cpp | 2 +- 5 files changed, 21 insertions(+), 19 deletions(-) diff --git a/.github/workflows/reusable-clang-tidy.yml b/.github/workflows/reusable-clang-tidy.yml index 3d4bc3b2e3..4c927dec9f 100644 --- a/.github/workflows/reusable-clang-tidy.yml +++ b/.github/workflows/reusable-clang-tidy.yml @@ -51,5 +51,5 @@ jobs: if: ${{ always() && !cancelled() && (!inputs.check_only_changed || needs.determine-files.outputs.any_cpp_changed == 'true' || needs.determine-files.outputs.clang_tidy_config_changed == 'true') }} uses: ./.github/workflows/reusable-clang-tidy-files.yml with: - files: ${{ needs.determine-files.outputs.clang_tidy_config_changed == 'true' && '' || (inputs.check_only_changed && needs.determine-files.outputs.all_changed_files || '') }} + files: ${{ (needs.determine-files.outputs.clang_tidy_config_changed != 'true' && inputs.check_only_changed) && needs.determine-files.outputs.all_changed_files || '' }} create_issue_on_failure: ${{ inputs.create_issue_on_failure }} diff --git a/src/libxrpl/ledger/helpers/DirectoryHelpers.cpp b/src/libxrpl/ledger/helpers/DirectoryHelpers.cpp index f0ca83f2cd..dba71e0acd 100644 --- a/src/libxrpl/ledger/helpers/DirectoryHelpers.cpp +++ b/src/libxrpl/ledger/helpers/DirectoryHelpers.cpp @@ -69,7 +69,7 @@ forEachItem( for (auto const& key : sle->getFieldV256(sfIndexes)) f(view.read(keylet::child(key))); auto const next = sle->getFieldU64(sfIndexNext); - if (!next) + if (next == 0u) return; pos = keylet::page(root, next); } diff --git a/src/libxrpl/ledger/helpers/RippleStateHelpers.cpp b/src/libxrpl/ledger/helpers/RippleStateHelpers.cpp index e88afe0cfb..22a0967939 100644 --- a/src/libxrpl/ledger/helpers/RippleStateHelpers.cpp +++ b/src/libxrpl/ledger/helpers/RippleStateHelpers.cpp @@ -224,10 +224,10 @@ trustCreate( bSetHigh ? sfLowLimit : sfHighLimit, STAmount(Issue{saBalance.getCurrency(), bSetDst ? uSrcAccountID : uDstAccountID})); - if (uQualityIn) + if (uQualityIn != 0u) sleRippleState->setFieldU32(bSetHigh ? sfHighQualityIn : sfLowQualityIn, uQualityIn); - if (uQualityOut) + if (uQualityOut != 0u) sleRippleState->setFieldU32(bSetHigh ? sfHighQualityOut : sfLowQualityOut, uQualityOut); std::uint32_t uFlags = bSetHigh ? lsfHighReserve : lsfLowReserve; @@ -327,16 +327,16 @@ updateTrustLine( // Sender balance was positive. && after <= beast::zero // Sender is zero or negative. - && (flags & (!bSenderHigh ? lsfLowReserve : lsfHighReserve)) + && ((flags & (!bSenderHigh ? lsfLowReserve : lsfHighReserve)) != 0u) // Sender reserve is set. && static_cast(flags & (!bSenderHigh ? lsfLowNoRipple : lsfHighNoRipple)) != static_cast(sle->getFlags() & lsfDefaultRipple) && - !(flags & (!bSenderHigh ? lsfLowFreeze : lsfHighFreeze)) && + ((flags & (!bSenderHigh ? lsfLowFreeze : lsfHighFreeze)) == 0u) && !state->getFieldAmount(!bSenderHigh ? sfLowLimit : sfHighLimit) // Sender trust limit is 0. - && !state->getFieldU32(!bSenderHigh ? sfLowQualityIn : sfHighQualityIn) + && (state->getFieldU32(!bSenderHigh ? sfLowQualityIn : sfHighQualityIn) == 0u) // Sender quality in is 0. - && !state->getFieldU32(!bSenderHigh ? sfLowQualityOut : sfHighQualityOut)) + && (state->getFieldU32(!bSenderHigh ? sfLowQualityOut : sfHighQualityOut) == 0u)) // Sender quality out is 0. { // VFALCO Where is the line being deleted? @@ -348,7 +348,7 @@ updateTrustLine( // Balance is zero, receiver reserve is clear. if (!after // Balance is zero. - && !(flags & (bSenderHigh ? lsfLowReserve : lsfHighReserve))) + && ((flags & (bSenderHigh ? lsfLowReserve : lsfHighReserve)) == 0u)) return true; } return false; @@ -539,11 +539,12 @@ requireAuth(ReadView const& view, Issue const& issue, AccountID const& account, // If this is a weak or legacy check, or if the account has a line, fail if // auth is required and not set on the line if (auto const issuerAccount = view.read(keylet::account(issue.account)); - issuerAccount && (*issuerAccount)[sfFlags] & lsfRequireAuth) + issuerAccount && (((*issuerAccount)[sfFlags] & lsfRequireAuth) != 0u)) { if (trustLine) { - return ((*trustLine)[sfFlags] & ((account > issue.account) ? lsfLowAuth : lsfHighAuth)) + return (((*trustLine)[sfFlags] & + ((account > issue.account) ? lsfLowAuth : lsfHighAuth)) != 0u) ? tesSUCCESS : TER{tecNO_AUTH}; } @@ -575,7 +576,7 @@ canTransfer(ReadView const& view, Issue const& issue, AccountID const& from, Acc bool const issuerHigh = issuerId > account; return line->isFlag(issuerHigh ? lsfHighNoRipple : lsfLowNoRipple); } - return sleIssuer->isFlag(lsfDefaultRipple) == false; + return !sleIssuer->isFlag(lsfDefaultRipple); }; // Fail if rippling disabled on both trust lines @@ -748,7 +749,7 @@ deleteAMMTrustLine( } auto const uFlags = !ammLow ? lsfLowReserve : lsfHighReserve; - if (!(sleState->getFlags() & uFlags)) + if ((sleState->getFlags() & uFlags) == 0u) return tecINTERNAL; // LCOV_EXCL_LINE adjustOwnerCount(view, !ammLow ? sleLow : sleHigh, -1, j); diff --git a/src/libxrpl/ledger/helpers/TokenHelpers.cpp b/src/libxrpl/ledger/helpers/TokenHelpers.cpp index 7a98445b0a..9eb1b4bf11 100644 --- a/src/libxrpl/ledger/helpers/TokenHelpers.cpp +++ b/src/libxrpl/ledger/helpers/TokenHelpers.cpp @@ -570,17 +570,18 @@ rippleCreditIOU( // Sender balance was positive. && saBalance <= beast::zero // Sender is zero or negative. - && (uFlags & (!bSenderHigh ? lsfLowReserve : lsfHighReserve)) + && ((uFlags & (!bSenderHigh ? lsfLowReserve : lsfHighReserve)) != 0u) // Sender reserve is set. && static_cast(uFlags & (!bSenderHigh ? lsfLowNoRipple : lsfHighNoRipple)) != static_cast( view.read(keylet::account(uSenderID))->getFlags() & lsfDefaultRipple) && - !(uFlags & (!bSenderHigh ? lsfLowFreeze : lsfHighFreeze)) && + ((uFlags & (!bSenderHigh ? lsfLowFreeze : lsfHighFreeze)) == 0u) && !sleRippleState->getFieldAmount(!bSenderHigh ? sfLowLimit : sfHighLimit) // Sender trust limit is 0. - && !sleRippleState->getFieldU32(!bSenderHigh ? sfLowQualityIn : sfHighQualityIn) + && (sleRippleState->getFieldU32(!bSenderHigh ? sfLowQualityIn : sfHighQualityIn) == 0u) // Sender quality in is 0. - && !sleRippleState->getFieldU32(!bSenderHigh ? sfLowQualityOut : sfHighQualityOut)) + && + (sleRippleState->getFieldU32(!bSenderHigh ? sfLowQualityOut : sfHighQualityOut) == 0u)) // Sender quality out is 0. { // Clear the reserve of the sender, possibly delete the line! @@ -592,7 +593,7 @@ rippleCreditIOU( // Balance is zero, receiver reserve is clear. bDelete = !saBalance // Balance is zero. - && !(uFlags & (bSenderHigh ? lsfLowReserve : lsfHighReserve)); + && ((uFlags & (bSenderHigh ? lsfLowReserve : lsfHighReserve)) == 0u); // Receiver reserve is clear. } diff --git a/src/test/beast/beast_io_latency_probe_test.cpp b/src/test/beast/beast_io_latency_probe_test.cpp index f2423550d3..b2163f2630 100644 --- a/src/test/beast/beast_io_latency_probe_test.cpp +++ b/src/test/beast/beast_io_latency_probe_test.cpp @@ -50,7 +50,7 @@ class io_latency_probe_test : public beast::unit_test::suite, public beast::test bool done = false; boost::system::error_code wait_err; - while (--num_samples) + while (--num_samples > 0u) { auto const start{MeasureClock::now()}; done = false; From 2c7af360c2d370805dd770972ab5cb0b19d8f64f Mon Sep 17 00:00:00 2001 From: Mayukha Vadari Date: Wed, 25 Mar 2026 09:02:14 -0700 Subject: [PATCH 16/53] fix: Remove unused/unreachable `transactor` code (#6612) --- src/libxrpl/tx/SignerEntries.cpp | 2 -- src/libxrpl/tx/Transactor.cpp | 3 +-- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/src/libxrpl/tx/SignerEntries.cpp b/src/libxrpl/tx/SignerEntries.cpp index aca1f2c19a..75659a7f04 100644 --- a/src/libxrpl/tx/SignerEntries.cpp +++ b/src/libxrpl/tx/SignerEntries.cpp @@ -12,8 +12,6 @@ namespace xrpl { Expected, NotTEC> SignerEntries::deserialize(STObject const& obj, beast::Journal journal, std::string_view annotation) { - std::pair, NotTEC> s; - if (!obj.isFieldPresent(sfSignerEntries)) { JLOG(journal.trace()) << "Malformed " << annotation << ": Need signer entry array."; diff --git a/src/libxrpl/tx/Transactor.cpp b/src/libxrpl/tx/Transactor.cpp index d579d26c67..9c2e93fba3 100644 --- a/src/libxrpl/tx/Transactor.cpp +++ b/src/libxrpl/tx/Transactor.cpp @@ -677,8 +677,7 @@ Transactor::checkSign( } // Look up the account. - auto const idSigner = - pkSigner.empty() ? idAccount : calcAccountID(PublicKey(makeSlice(pkSigner))); + auto const idSigner = calcAccountID(PublicKey(makeSlice(pkSigner))); auto const sleAccount = view.read(keylet::account(idAccount)); if (!sleAccount) return terNO_ACCOUNT; From cd78569d944a4741ec353233434a2ad494b87441 Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Wed, 25 Mar 2026 16:06:31 +0000 Subject: [PATCH 17/53] chore: Use unpatched version of soci (#6649) --- conan.lock | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/conan.lock b/conan.lock index 2460a15fb0..d2126956fe 100644 --- a/conan.lock +++ b/conan.lock @@ -1,15 +1,15 @@ { "version": "0.5", "requires": [ - "zlib/1.3.1#cac0f6daea041b0ccf42934163defb20%1765284699.337", + "zlib/1.3.1#cac0f6daea041b0ccf42934163defb20%1774439233.809", "xxhash/0.8.3#681d36a0a6111fc56e5e45ea182c19cc%1765850149.987", "sqlite3/3.49.1#8631739a4c9b93bd3d6b753bac548a63%1765850149.926", - "soci/4.0.3#a9f8d773cd33e356b5879a4b0564f287%1765850149.46", + "soci/4.0.3#fe32b9ad5eb47e79ab9e45a68f363945%1774450067.231", "snappy/1.1.10#968fef506ff261592ec30c574d4a7809%1765850147.878", "secp256k1/0.7.1#481881709eb0bdd0185a12b912bbe8ad%1770910500.329", "rocksdb/10.5.1#4a197eca381a3e5ae8adf8cffa5aacd0%1765850186.86", - "re2/20251105#8579cfd0bda4daf0683f9e3898f964b4%1772560729.95", - "protobuf/6.32.1#b54f00da2e0f61d821330b5b638b0f80%1768401317.762", + "re2/20251105#8579cfd0bda4daf0683f9e3898f964b4%1774398111.888", + "protobuf/6.32.1#b54f00da2e0f61d821330b5b638b0f80%1774439406.061", "openssl/3.5.5#e6399de266349245a4542fc5f6c71552%1774367199.56", "nudb/2.0.9#0432758a24204da08fee953ec9ea03cb%1769436073.32", "lz4/1.10.0#59fc63cac7f10fbe8e05c7e62c2f3504%1765850143.914", @@ -21,21 +21,21 @@ "grpc/1.72.0#aaade9421980b2d926dbfb613d56c38a%1774376249.106", "ed25519/2015.03#ae761bdc52730a843f0809bdf6c1b1f6%1765850143.772", "date/3.0.4#862e11e80030356b53c2c38599ceb32b%1765850143.772", - "c-ares/1.34.6#545240bb1c40e2cacd4362d6b8967650%1766500685.317", + "c-ares/1.34.6#545240bb1c40e2cacd4362d6b8967650%1774439234.681", "bzip2/1.0.8#c470882369c2d95c5c77e970c0c7e321%1765850143.837", "boost/1.90.0#d5e8defe7355494953be18524a7f135b%1769454080.269", "abseil/20250127.0#bb0baf1f362bc4a725a24eddd419b8f7%1774365460.196" ], "build_requires": [ - "zlib/1.3.1#cac0f6daea041b0ccf42934163defb20%1765284699.337", - "strawberryperl/5.32.1.1#8d114504d172cfea8ea1662d09b6333e%1751971032.423", - "protobuf/6.32.1#b54f00da2e0f61d821330b5b638b0f80%1768401317.762", + "zlib/1.3.1#cac0f6daea041b0ccf42934163defb20%1774439233.809", + "strawberryperl/5.32.1.1#8d114504d172cfea8ea1662d09b6333e%1774447376.964", + "protobuf/6.32.1#b54f00da2e0f61d821330b5b638b0f80%1774439406.061", "nasm/2.16.01#31e26f2ee3c4346ecd347911bd126904%1765850144.707", "msys2/cci.latest#d22fe7b2808f5fd34d0a7923ace9c54f%1770657326.649", "m4/1.4.19#5d7a4994e5875d76faf7acf3ed056036%1774365463.87", - "cmake/4.3.0#b939a42e98f593fb34d3a8c5cc860359%1773780142.26", - "cmake/3.31.11#f325c933f618a1fcebc1e1c0babfd1ba%1769622857.944", - "b2/5.4.2#ffd6084a119587e70f11cd45d1a386e2%1766594659.866", + "cmake/4.3.0#b939a42e98f593fb34d3a8c5cc860359%1774439249.183", + "cmake/3.31.11#f325c933f618a1fcebc1e1c0babfd1ba%1774439246.719", + "b2/5.4.2#ffd6084a119587e70f11cd45d1a386e2%1774439233.447", "automake/1.16.5#b91b7c384c3deaa9d535be02da14d04f%1755524470.56", "autoconf/2.71#51077f068e61700d65bb05541ea1e4b0%1731054366.86", "abseil/20250127.0#bb0baf1f362bc4a725a24eddd419b8f7%1774365460.196" From 8f182e825a2402b5dbb160fd19d35475248d9de5 Mon Sep 17 00:00:00 2001 From: Jingchen Date: Wed, 25 Mar 2026 16:32:45 +0000 Subject: [PATCH 18/53] refactor: Modularise ledger (#6536) Signed-off-by: JCW Co-authored-by: Bart Co-authored-by: Pratik Mankawde <3397372+pratikmankawde@users.noreply.github.com> --- .../scripts/levelization/results/ordering.txt | 4 +- include/xrpl/core/ServiceRegistry.h | 6 +- .../xrpl/ledger}/CanonicalTXSet.h | 0 .../app => include/xrpl}/ledger/Ledger.h | 95 +++--- .../xrpl/ledger}/LedgerTiming.h | 0 .../xrpl}/ledger/PendingSaves.h | 0 include/xrpl/protocol/Fees.h | 20 +- include/xrpl/protocol/LedgerHeader.h | 4 + .../xrpl/tx}/paths/AMMLiquidity.h | 0 .../app => include/xrpl/tx}/paths/AMMOffer.h | 0 .../xrpl/tx}/paths/detail/StepChecks.h | 0 .../ledger}/CanonicalTXSet.cpp | 2 +- src/{xrpld/app => libxrpl}/ledger/Ledger.cpp | 271 +++--------------- src/libxrpl/protocol/LedgerHeader.cpp | 19 ++ .../detail => libxrpl/server}/Manifest.cpp | 0 .../tx/paths}/AMMLiquidity.cpp | 4 +- .../detail => libxrpl/tx/paths}/AMMOffer.cpp | 5 +- .../detail => libxrpl/tx/paths}/BookStep.cpp | 5 +- .../tx/paths}/DirectStep.cpp | 3 +- .../detail => libxrpl/tx/paths}/PaySteps.cpp | 0 .../tx/paths}/XRPEndpointStep.cpp | 3 +- src/test/app/AMMExtended_test.cpp | 3 +- src/test/app/FeeVote_test.cpp | 55 +++- src/test/app/LedgerHistory_test.cpp | 3 +- src/test/app/RCLValidations_test.cpp | 14 +- src/test/app/Regression_test.cpp | 6 +- src/test/consensus/LedgerTiming_test.cpp | 3 +- src/test/consensus/NegativeUNL_test.cpp | 16 +- src/test/csf/ledgers.h | 3 +- src/test/jtx/Env.h | 4 +- src/test/jtx/impl/paths.cpp | 2 +- src/test/jtx/utility.h | 3 +- src/test/ledger/PendingSaves_test.cpp | 3 +- src/test/ledger/SkipList_test.cpp | 9 +- src/test/ledger/View_test.cpp | 26 +- src/test/overlay/compression_test.cpp | 2 +- src/xrpld/app/consensus/RCLConsensus.cpp | 4 +- src/xrpld/app/consensus/RCLCxLedger.h | 2 +- src/xrpld/app/consensus/RCLValidations.h | 2 +- src/xrpld/app/ledger/InboundLedger.h | 2 +- src/xrpld/app/ledger/LedgerHistory.cpp | 10 +- src/xrpld/app/ledger/LedgerHistory.h | 2 +- src/xrpld/app/ledger/LedgerMaster.h | 5 +- src/xrpld/app/ledger/LedgerPersistence.h | 90 ++++++ src/xrpld/app/ledger/LedgerReplay.h | 1 + src/xrpld/app/ledger/LedgerToJson.h | 2 +- src/xrpld/app/ledger/LocalTxs.h | 3 +- src/xrpld/app/ledger/OpenLedger.h | 4 +- src/xrpld/app/ledger/detail/BuildLedger.cpp | 4 +- src/xrpld/app/ledger/detail/InboundLedger.cpp | 6 +- src/xrpld/app/ledger/detail/LedgerCleaner.cpp | 6 +- .../app/ledger/detail/LedgerDeltaAcquire.cpp | 3 +- .../app/ledger/detail/LedgerDeltaAcquire.h | 2 +- src/xrpld/app/ledger/detail/LedgerMaster.cpp | 11 +- .../app/ledger/detail/LedgerPersistence.cpp | 167 +++++++++++ src/xrpld/app/ledger/detail/LedgerReplay.cpp | 3 +- src/xrpld/app/ledger/detail/LocalTxs.cpp | 2 +- src/xrpld/app/ledger/detail/OpenLedger.cpp | 1 + src/xrpld/app/ledger/detail/SkipListAcquire.h | 2 +- src/xrpld/app/main/Application.cpp | 52 ++-- src/xrpld/app/main/Application.h | 2 +- src/xrpld/app/misc/FeeVoteImpl.cpp | 5 +- src/xrpld/app/misc/NegativeUNLVote.cpp | 2 +- src/xrpld/app/misc/NegativeUNLVote.h | 3 +- src/xrpld/app/misc/NetworkOPs.cpp | 4 +- src/xrpld/app/misc/SHAMapStore.h | 3 +- src/xrpld/app/misc/detail/AccountTxPaging.cpp | 1 + src/xrpld/app/rdb/backend/detail/Node.cpp | 3 +- src/xrpld/app/rdb/backend/detail/Node.h | 2 +- src/xrpld/consensus/Consensus.h | 2 +- src/xrpld/core/Config.h | 12 +- .../detail}/AccountCurrencies.cpp | 2 +- .../paths => rpc/detail}/AccountCurrencies.h | 2 +- .../{app/paths => rpc/detail}/PathRequest.cpp | 12 +- .../{app/paths => rpc/detail}/PathRequest.h | 14 +- .../detail/PathRequestManager.cpp} | 16 +- .../detail/PathRequestManager.h} | 8 +- .../{app/paths => rpc/detail}/Pathfinder.cpp | 6 +- .../{app/paths => rpc/detail}/Pathfinder.h | 4 +- .../paths => rpc}/detail/PathfinderUtils.h | 0 src/xrpld/rpc/detail/RPCHelpers.cpp | 2 +- src/xrpld/rpc/detail/RPCLedgerHelpers.h | 2 +- .../paths => rpc/detail}/RippleLineCache.cpp | 4 +- .../paths => rpc/detail}/RippleLineCache.h | 4 +- src/xrpld/rpc/detail/TransactionSign.cpp | 2 +- .../{app/paths => rpc/detail}/TrustLine.cpp | 2 +- .../{app/paths => rpc/detail}/TrustLine.h | 0 .../rpc/handlers/AccountCurrenciesHandler.cpp | 2 +- src/xrpld/rpc/handlers/AccountLines.cpp | 2 +- src/xrpld/rpc/handlers/GatewayBalances.cpp | 2 +- src/xrpld/rpc/handlers/NoRippleCheck.cpp | 2 +- src/xrpld/rpc/handlers/PathFind.cpp | 4 +- src/xrpld/rpc/handlers/RipplePathFind.cpp | 6 +- 93 files changed, 644 insertions(+), 472 deletions(-) rename {src/xrpld/app/misc => include/xrpl/ledger}/CanonicalTXSet.h (100%) rename {src/xrpld/app => include/xrpl}/ledger/Ledger.h (84%) rename {src/xrpld/consensus => include/xrpl/ledger}/LedgerTiming.h (100%) rename {src/xrpld/app => include/xrpl}/ledger/PendingSaves.h (100%) rename {src/xrpld/app => include/xrpl/tx}/paths/AMMLiquidity.h (100%) rename {src/xrpld/app => include/xrpl/tx}/paths/AMMOffer.h (100%) rename {src/xrpld/app => include/xrpl/tx}/paths/detail/StepChecks.h (100%) rename src/{xrpld/app/misc => libxrpl/ledger}/CanonicalTXSet.cpp (97%) rename src/{xrpld/app => libxrpl}/ledger/Ledger.cpp (74%) rename src/{xrpld/app/misc/detail => libxrpl/server}/Manifest.cpp (100%) rename src/{xrpld/app/paths/detail => libxrpl/tx/paths}/AMMLiquidity.cpp (99%) rename src/{xrpld/app/paths/detail => libxrpl/tx/paths}/AMMOffer.cpp (98%) rename src/{xrpld/app/paths/detail => libxrpl/tx/paths}/BookStep.cpp (99%) rename src/{xrpld/app/paths/detail => libxrpl/tx/paths}/DirectStep.cpp (99%) rename src/{xrpld/app/paths/detail => libxrpl/tx/paths}/PaySteps.cpp (100%) rename src/{xrpld/app/paths/detail => libxrpl/tx/paths}/XRPEndpointStep.cpp (99%) create mode 100644 src/xrpld/app/ledger/LedgerPersistence.h create mode 100644 src/xrpld/app/ledger/detail/LedgerPersistence.cpp rename src/xrpld/{app/paths => rpc/detail}/AccountCurrencies.cpp (97%) rename src/xrpld/{app/paths => rpc/detail}/AccountCurrencies.h (89%) rename src/xrpld/{app/paths => rpc/detail}/PathRequest.cpp (98%) rename src/xrpld/{app/paths => rpc/detail}/PathRequest.h (94%) rename src/xrpld/{app/paths/PathRequests.cpp => rpc/detail/PathRequestManager.cpp} (95%) rename src/xrpld/{app/paths/PathRequests.h => rpc/detail/PathRequestManager.h} (94%) rename src/xrpld/{app/paths => rpc/detail}/Pathfinder.cpp (99%) rename src/xrpld/{app/paths => rpc/detail}/Pathfinder.h (98%) rename src/xrpld/{app/paths => rpc}/detail/PathfinderUtils.h (100%) rename src/xrpld/{app/paths => rpc/detail}/RippleLineCache.cpp (98%) rename src/xrpld/{app/paths => rpc/detail}/RippleLineCache.h (97%) rename src/xrpld/{app/paths => rpc/detail}/TrustLine.cpp (98%) rename src/xrpld/{app/paths => rpc/detail}/TrustLine.h (100%) diff --git a/.github/scripts/levelization/results/ordering.txt b/.github/scripts/levelization/results/ordering.txt index d26a5a1963..de12bf424b 100644 --- a/.github/scripts/levelization/results/ordering.txt +++ b/.github/scripts/levelization/results/ordering.txt @@ -90,6 +90,7 @@ test.core > xrpl.server test.csf > xrpl.basics test.csf > xrpld.consensus test.csf > xrpl.json +test.csf > xrpl.ledger test.csf > xrpl.protocol test.json > test.jtx test.json > xrpl.json @@ -108,7 +109,6 @@ test.jtx > xrpl.tx test.ledger > test.jtx test.ledger > test.toplevel test.ledger > xrpl.basics -test.ledger > xrpld.app test.ledger > xrpld.core test.ledger > xrpl.ledger test.ledger > xrpl.protocol @@ -125,6 +125,7 @@ test.overlay > xrpl.basics test.overlay > xrpld.app test.overlay > xrpld.overlay test.overlay > xrpld.peerfinder +test.overlay > xrpl.ledger test.overlay > xrpl.nodestore test.overlay > xrpl.protocol test.overlay > xrpl.shamap @@ -234,6 +235,7 @@ xrpld.app > xrpl.shamap xrpld.app > xrpl.tx xrpld.consensus > xrpl.basics xrpld.consensus > xrpl.json +xrpld.consensus > xrpl.ledger xrpld.consensus > xrpl.protocol xrpld.core > xrpl.basics xrpld.core > xrpl.core diff --git a/include/xrpl/core/ServiceRegistry.h b/include/xrpl/core/ServiceRegistry.h index 1a2e33d5ee..bff475c461 100644 --- a/include/xrpl/core/ServiceRegistry.h +++ b/include/xrpl/core/ServiceRegistry.h @@ -45,7 +45,7 @@ class NetworkIDService; class OpenLedger; class OrderBookDB; class Overlay; -class PathRequests; +class PathRequestManager; class PeerReservationTable; class PendingSaves; class RelationalDatabase; @@ -195,8 +195,8 @@ public: virtual TxQ& getTxQ() = 0; - virtual PathRequests& - getPathRequests() = 0; + virtual PathRequestManager& + getPathRequestManager() = 0; // Server services virtual ServerHandler& diff --git a/src/xrpld/app/misc/CanonicalTXSet.h b/include/xrpl/ledger/CanonicalTXSet.h similarity index 100% rename from src/xrpld/app/misc/CanonicalTXSet.h rename to include/xrpl/ledger/CanonicalTXSet.h diff --git a/src/xrpld/app/ledger/Ledger.h b/include/xrpl/ledger/Ledger.h similarity index 84% rename from src/xrpld/app/ledger/Ledger.h rename to include/xrpl/ledger/Ledger.h index f040e93369..75a8f55dc0 100644 --- a/src/xrpld/app/ledger/Ledger.h +++ b/include/xrpl/ledger/Ledger.h @@ -1,13 +1,12 @@ #pragma once -#include -#include - #include #include #include #include +#include #include +#include #include #include #include @@ -15,7 +14,7 @@ namespace xrpl { -class Application; +class ServiceRegistry; class Job; class TransactionMaster; @@ -83,21 +82,26 @@ public: */ Ledger( create_genesis_t, - Config const& config, + Rules const& rules, + Fees const& fees, std::vector const& amendments, Family& family); - Ledger(LedgerHeader const& info, Config const& config, Family& family); + Ledger(LedgerHeader const& info, Rules const& rules, Family& family); /** Used for ledgers loaded from JSON files @param acquire If true, acquires the ledger if not found locally + + @note The fees parameter provides default values, but setup() may + override them from the ledger state if fee-related SLEs exist. */ Ledger( LedgerHeader const& info, bool& loaded, bool acquire, - Config const& config, + Rules const& rules, + Fees const& fees, Family& family, beast::Journal j); @@ -113,7 +117,8 @@ public: Ledger( std::uint32_t ledgerSeq, NetClock::time_point closeTime, - Config const& config, + Rules const& rules, + Fees const& fees, Family& family); ~Ledger() = default; @@ -322,7 +327,7 @@ public: walkLedger(beast::Journal j, bool parallel = false) const; bool - assertSensible(beast::Journal ledgerJ) const; + isSensible() const; void invariants() const; @@ -379,8 +384,26 @@ private: bool setup(); - void - defaultFees(Config const& config); + /** @brief Deserialize a SHAMapItem containing a single STTx. + * + * @param item The SHAMapItem to deserialize. + * @return A shared pointer to the deserialized transaction. + * @throw May throw on deserialization error. + */ + static std::shared_ptr + deserializeTx(SHAMapItem const& item); + + /** @brief Deserialize a SHAMapItem containing STTx + STObject metadata. + * + * The SHAMapItem must contain two variable length serialization objects. + * + * @param item The SHAMapItem to deserialize. + * @return A pair containing shared pointers to the deserialized transaction + * and metadata. + * @throw May throw on deserialization error. + */ + static std::pair, std::shared_ptr> + deserializeTxPlusMeta(SHAMapItem const& item); bool mImmutable; @@ -402,54 +425,4 @@ private: /** A ledger wrapped in a CachedView. */ using CachedLedger = CachedView; -//------------------------------------------------------------------------------ -// -// API -// -//------------------------------------------------------------------------------ - -extern bool -pendSaveValidated( - Application& app, - std::shared_ptr const& ledger, - bool isSynchronous, - bool isCurrent); - -std::shared_ptr -loadLedgerHelper(LedgerHeader const& sinfo, Application& app, bool acquire); - -std::shared_ptr -loadByIndex(std::uint32_t ledgerIndex, Application& app, bool acquire = true); - -std::shared_ptr -loadByHash(uint256 const& ledgerHash, Application& app, bool acquire = true); - -// Fetch the ledger with the highest sequence contained in the database -extern std::tuple, std::uint32_t, uint256> -getLatestLedger(Application& app); - -/** Deserialize a SHAMapItem containing a single STTx - - Throw: - - May throw on deserializaton error -*/ -std::shared_ptr -deserializeTx(SHAMapItem const& item); - -/** Deserialize a SHAMapItem containing STTx + STObject metadata - - The SHAMap must contain two variable length - serialization objects. - - Throw: - - May throw on deserializaton error -*/ -std::pair, std::shared_ptr> -deserializeTxPlusMeta(SHAMapItem const& item); - -uint256 -calculateLedgerHash(LedgerHeader const& info); - } // namespace xrpl diff --git a/src/xrpld/consensus/LedgerTiming.h b/include/xrpl/ledger/LedgerTiming.h similarity index 100% rename from src/xrpld/consensus/LedgerTiming.h rename to include/xrpl/ledger/LedgerTiming.h diff --git a/src/xrpld/app/ledger/PendingSaves.h b/include/xrpl/ledger/PendingSaves.h similarity index 100% rename from src/xrpld/app/ledger/PendingSaves.h rename to include/xrpl/ledger/PendingSaves.h diff --git a/include/xrpl/protocol/Fees.h b/include/xrpl/protocol/Fees.h index 84c8ffe81f..ddf4acbf67 100644 --- a/include/xrpl/protocol/Fees.h +++ b/include/xrpl/protocol/Fees.h @@ -4,6 +4,10 @@ namespace xrpl { +// Deprecated constant for backwards compatibility with pre-XRPFees amendment. +// This was the reference fee units used in the old fee calculation. +inline constexpr std::uint32_t FEE_UNITS_DEPRECATED = 10; + /** Reflects the fee settings for a particular ledger. The fees are always the same for any transactions applied @@ -11,15 +15,25 @@ namespace xrpl { */ struct Fees { - XRPAmount base{0}; // Reference tx cost (drops) - XRPAmount reserve{0}; // Reserve base (drops) - XRPAmount increment{0}; // Reserve increment (drops) + /** @brief Cost of a reference transaction in drops. */ + XRPAmount base{0}; + + /** @brief Minimum XRP an account must hold to exist on the ledger. */ + XRPAmount reserve{0}; + + /** @brief Additional XRP reserve required per owned ledger object. */ + XRPAmount increment{0}; explicit Fees() = default; Fees(Fees const&) = default; Fees& operator=(Fees const&) = default; + Fees(XRPAmount base_, XRPAmount reserve_, XRPAmount increment_) + : base(base_), reserve(reserve_), increment(increment_) + { + } + /** Returns the account reserve given the owner count, in drops. The reserve is calculated as the reserve base plus diff --git a/include/xrpl/protocol/LedgerHeader.h b/include/xrpl/protocol/LedgerHeader.h index 1dc67cada5..6e22ad268d 100644 --- a/include/xrpl/protocol/LedgerHeader.h +++ b/include/xrpl/protocol/LedgerHeader.h @@ -72,4 +72,8 @@ deserializeHeader(Slice data, bool hasHash = false); LedgerHeader deserializePrefixedHeader(Slice data, bool hasHash = false); +/** Calculate the hash of a ledger header. */ +uint256 +calculateLedgerHash(LedgerHeader const& info); + } // namespace xrpl diff --git a/src/xrpld/app/paths/AMMLiquidity.h b/include/xrpl/tx/paths/AMMLiquidity.h similarity index 100% rename from src/xrpld/app/paths/AMMLiquidity.h rename to include/xrpl/tx/paths/AMMLiquidity.h diff --git a/src/xrpld/app/paths/AMMOffer.h b/include/xrpl/tx/paths/AMMOffer.h similarity index 100% rename from src/xrpld/app/paths/AMMOffer.h rename to include/xrpl/tx/paths/AMMOffer.h diff --git a/src/xrpld/app/paths/detail/StepChecks.h b/include/xrpl/tx/paths/detail/StepChecks.h similarity index 100% rename from src/xrpld/app/paths/detail/StepChecks.h rename to include/xrpl/tx/paths/detail/StepChecks.h diff --git a/src/xrpld/app/misc/CanonicalTXSet.cpp b/src/libxrpl/ledger/CanonicalTXSet.cpp similarity index 97% rename from src/xrpld/app/misc/CanonicalTXSet.cpp rename to src/libxrpl/ledger/CanonicalTXSet.cpp index f971c100eb..72f45731fb 100644 --- a/src/xrpld/app/misc/CanonicalTXSet.cpp +++ b/src/libxrpl/ledger/CanonicalTXSet.cpp @@ -1,4 +1,4 @@ -#include +#include namespace xrpl { diff --git a/src/xrpld/app/ledger/Ledger.cpp b/src/libxrpl/ledger/Ledger.cpp similarity index 74% rename from src/xrpld/app/ledger/Ledger.cpp rename to src/libxrpl/ledger/Ledger.cpp index 7be1b5e762..47009d198a 100644 --- a/src/xrpld/app/ledger/Ledger.cpp +++ b/src/libxrpl/ledger/Ledger.cpp @@ -1,19 +1,9 @@ -#include -#include -#include -#include -#include -#include -#include - #include #include #include -#include -#include #include -#include -#include +#include +#include #include #include #include @@ -21,7 +11,6 @@ #include #include #include -#include #include #include @@ -30,23 +19,6 @@ namespace xrpl { create_genesis_t const create_genesis{}; -uint256 -calculateLedgerHash(LedgerHeader const& info) -{ - // VFALCO This has to match addRaw in View.h. - return sha512Half( - HashPrefix::ledgerMaster, - std::uint32_t(info.seq), - std::uint64_t(info.drops.drops()), - info.parentHash, - info.txHash, - info.accountHash, - std::uint32_t(info.parentCloseTime.time_since_epoch().count()), - std::uint32_t(info.closeTime.time_since_epoch().count()), - std::uint8_t(info.closeTimeResolution.count()), - std::uint8_t(info.closeFlags)); -} - //------------------------------------------------------------------------------ class Ledger::sles_iter_impl : public sles_type::iter_base @@ -138,8 +110,8 @@ public: { auto const& item = *iter_; if (metadata_) - return deserializeTxPlusMeta(item); - return {deserializeTx(item), nullptr}; + return Ledger::deserializeTxPlusMeta(item); + return {Ledger::deserializeTx(item), nullptr}; } }; @@ -147,13 +119,15 @@ public: Ledger::Ledger( create_genesis_t, - Config const& config, + Rules const& rules, + Fees const& fees, std::vector const& amendments, Family& family) : mImmutable(false) , txMap_(SHAMapType::TRANSACTION, family) , stateMap_(SHAMapType::STATE, family) - , rules_{config.features} + , fees_(fees) + , rules_(rules) , j_(beast::Journal(beast::Journal::getNullSink())) { header_.seq = 1; @@ -182,19 +156,19 @@ Ledger::Ledger( // Whether featureXRPFees is supported will depend on startup options. if (std::find(amendments.begin(), amendments.end(), featureXRPFees) != amendments.end()) { - sle->at(sfBaseFeeDrops) = config.FEES.reference_fee; - sle->at(sfReserveBaseDrops) = config.FEES.account_reserve; - sle->at(sfReserveIncrementDrops) = config.FEES.owner_reserve; + sle->at(sfBaseFeeDrops) = fees.base; + sle->at(sfReserveBaseDrops) = fees.reserve; + sle->at(sfReserveIncrementDrops) = fees.increment; } else { - if (auto const f = config.FEES.reference_fee.dropsAs()) + if (auto const f = fees.base.dropsAs()) sle->at(sfBaseFee) = *f; - if (auto const f = config.FEES.account_reserve.dropsAs()) + if (auto const f = fees.reserve.dropsAs()) sle->at(sfReserveBase) = *f; - if (auto const f = config.FEES.owner_reserve.dropsAs()) + if (auto const f = fees.increment.dropsAs()) sle->at(sfReserveIncrement) = *f; - sle->at(sfReferenceFeeUnits) = Config::FEE_UNITS_DEPRECATED; + sle->at(sfReferenceFeeUnits) = FEE_UNITS_DEPRECATED; } rawInsert(sle); } @@ -207,13 +181,15 @@ Ledger::Ledger( LedgerHeader const& info, bool& loaded, bool acquire, - Config const& config, + Rules const& rules, + Fees const& fees, Family& family, beast::Journal j) : mImmutable(true) , txMap_(SHAMapType::TRANSACTION, info.txHash, family) , stateMap_(SHAMapType::STATE, info.accountHash, family) - , rules_(config.features) + , fees_(fees) + , rules_(rules) , header_(info) , j_(j) { @@ -235,7 +211,6 @@ Ledger::Ledger( txMap_.setImmutable(); stateMap_.setImmutable(); - defaultFees(config); if (!setup()) loaded = false; @@ -275,11 +250,11 @@ Ledger::Ledger(Ledger const& prevLedger, NetClock::time_point closeTime) } } -Ledger::Ledger(LedgerHeader const& info, Config const& config, Family& family) +Ledger::Ledger(LedgerHeader const& info, Rules const& rules, Family& family) : mImmutable(true) , txMap_(SHAMapType::TRANSACTION, info.txHash, family) , stateMap_(SHAMapType::STATE, info.accountHash, family) - , rules_{config.features} + , rules_(rules) , header_(info) , j_(beast::Journal(beast::Journal::getNullSink())) { @@ -289,18 +264,19 @@ Ledger::Ledger(LedgerHeader const& info, Config const& config, Family& family) Ledger::Ledger( std::uint32_t ledgerSeq, NetClock::time_point closeTime, - Config const& config, + Rules const& rules, + Fees const& fees, Family& family) : mImmutable(false) , txMap_(SHAMapType::TRANSACTION, family) , stateMap_(SHAMapType::STATE, family) - , rules_{config.features} + , fees_(fees) + , rules_(rules) , j_(beast::Journal(beast::Journal::getNullSink())) { header_.seq = ledgerSeq; header_.closeTime = closeTime; header_.closeTimeResolution = ledgerDefaultTimeResolution; - defaultFees(config); setup(); } @@ -350,14 +326,14 @@ Ledger::addSLE(SLE const& sle) //------------------------------------------------------------------------------ std::shared_ptr -deserializeTx(SHAMapItem const& item) +Ledger::deserializeTx(SHAMapItem const& item) { SerialIter sit(item.slice()); return std::make_shared(sit); } std::pair, std::shared_ptr> -deserializeTxPlusMeta(SHAMapItem const& item) +Ledger::deserializeTxPlusMeta(SHAMapItem const& item) { std::pair, std::shared_ptr> result; SerialIter sit(item.slice()); @@ -636,20 +612,6 @@ Ledger::setup() return ret; } -void -Ledger::defaultFees(Config const& config) -{ - XRPL_ASSERT( - fees_.base == 0 && fees_.reserve == 0 && fees_.increment == 0, - "xrpl::Ledger::defaultFees : zero fees"); - if (fees_.base == 0) - fees_.base = config.FEES.reference_fee; - if (fees_.reserve == 0) - fees_.reserve = config.FEES.account_reserve; - if (fees_.increment == 0) - fees_.increment = config.FEES.owner_reserve; -} - std::shared_ptr Ledger::peek(Keylet const& k) const { @@ -816,27 +778,17 @@ Ledger::walkLedger(beast::Journal j, bool parallel) const } bool -Ledger::assertSensible(beast::Journal ledgerJ) const +Ledger::isSensible() const { - if (header_.hash.isNonZero() && header_.accountHash.isNonZero() && - (header_.accountHash == stateMap_.getHash().as_uint256()) && - (header_.txHash == txMap_.getHash().as_uint256())) - { - return true; - } - - // LCOV_EXCL_START - Json::Value j = getJson({*this, {}}); - - j[jss::accountTreeHash] = to_string(header_.accountHash); - j[jss::transTreeHash] = to_string(header_.txHash); - - JLOG(ledgerJ.fatal()) << "ledger is not sensible" << j; - - UNREACHABLE("xrpl::Ledger::assertSensible : ledger is not sensible"); - - return false; - // LCOV_EXCL_STOP + if (header_.hash.isZero()) + return false; + if (header_.accountHash.isZero()) + return false; + if (header_.accountHash != stateMap_.getHash().as_uint256()) + return false; + if (header_.txHash != txMap_.getHash().as_uint256()) + return false; + return true; } // update the skip list with the information from our previous ledger @@ -925,76 +877,6 @@ Ledger::isVotingLedger() const return ::xrpl::isVotingLedger(header_.seq + 1); } -static bool -saveValidatedLedger(Application& app, std::shared_ptr const& ledger, bool current) -{ - auto j = app.journal("Ledger"); - auto seq = ledger->header().seq; - if (!app.pendingSaves().startWork(seq)) - { - // The save was completed synchronously - JLOG(j.debug()) << "Save aborted"; - return true; - } - - auto& db = app.getRelationalDatabase(); - - auto const res = db.saveValidatedLedger(ledger, current); - - // Clients can now trust the database for - // information about this ledger sequence. - app.pendingSaves().finishWork(seq); - return res; -} - -/** Save, or arrange to save, a fully-validated ledger - Returns false on error -*/ -bool -pendSaveValidated( - Application& app, - std::shared_ptr const& ledger, - bool isSynchronous, - bool isCurrent) -{ - if (!app.getHashRouter().setFlags(ledger->header().hash, HashRouterFlags::SAVED)) - { - // We have tried to save this ledger recently - auto stream = app.journal("Ledger").debug(); - JLOG(stream) << "Double pend save for " << ledger->header().seq; - - if (!isSynchronous || !app.pendingSaves().pending(ledger->header().seq)) - { - // Either we don't need it to be finished - // or it is finished - return true; - } - } - - XRPL_ASSERT(ledger->isImmutable(), "xrpl::pendSaveValidated : immutable ledger"); - - if (!app.pendingSaves().shouldWork(ledger->header().seq, isSynchronous)) - { - auto stream = app.journal("Ledger").debug(); - JLOG(stream) << "Pend save with seq in pending saves " << ledger->header().seq; - - return true; - } - - // See if we can use the JobQueue. - if (!isSynchronous && - app.getJobQueue().addJob( - isCurrent ? jtPUBLEDGER : jtPUBOLDLEDGER, - std::to_string(ledger->seq()), - [&app, ledger, isCurrent]() { saveValidatedLedger(app, ledger, isCurrent); })) - { - return true; - } - - // The JobQueue won't do the Job. Do the save synchronously. - return saveValidatedLedger(app, ledger, isCurrent); -} - void Ledger::unshare() const { @@ -1008,84 +890,5 @@ Ledger::invariants() const stateMap_.invariants(); txMap_.invariants(); } -//------------------------------------------------------------------------------ - -/* - * Make ledger using info loaded from database. - * - * @param LedgerHeader: Ledger information. - * @param app: Link to the Application. - * @param acquire: Acquire the ledger if not found locally. - * @return Shared pointer to the ledger. - */ -std::shared_ptr -loadLedgerHelper(LedgerHeader const& info, Application& app, bool acquire) -{ - bool loaded = false; - auto ledger = std::make_shared( - info, loaded, acquire, app.config(), app.getNodeFamily(), app.journal("Ledger")); - - if (!loaded) - ledger.reset(); - - return ledger; -} - -static void -finishLoadByIndexOrHash( - std::shared_ptr const& ledger, - Config const& config, - beast::Journal j) -{ - if (!ledger) - return; - - XRPL_ASSERT( - ledger->header().seq < XRP_LEDGER_EARLIEST_FEES || ledger->read(keylet::fees()), - "xrpl::finishLoadByIndexOrHash : valid ledger fees"); - ledger->setImmutable(); - - JLOG(j.trace()) << "Loaded ledger: " << to_string(ledger->header().hash); - - ledger->setFull(); -} - -std::tuple, std::uint32_t, uint256> -getLatestLedger(Application& app) -{ - std::optional const info = app.getRelationalDatabase().getNewestLedgerInfo(); - if (!info) - return {std::shared_ptr(), {}, {}}; - return {loadLedgerHelper(*info, app, true), info->seq, info->hash}; -} - -std::shared_ptr -loadByIndex(std::uint32_t ledgerIndex, Application& app, bool acquire) -{ - if (std::optional info = - app.getRelationalDatabase().getLedgerInfoByIndex(ledgerIndex)) - { - std::shared_ptr ledger = loadLedgerHelper(*info, app, acquire); - finishLoadByIndexOrHash(ledger, app.config(), app.journal("Ledger")); - return ledger; - } - return {}; -} - -std::shared_ptr -loadByHash(uint256 const& ledgerHash, Application& app, bool acquire) -{ - if (std::optional info = - app.getRelationalDatabase().getLedgerInfoByHash(ledgerHash)) - { - std::shared_ptr ledger = loadLedgerHelper(*info, app, acquire); - finishLoadByIndexOrHash(ledger, app.config(), app.journal("Ledger")); - XRPL_ASSERT( - !ledger || ledger->header().hash == ledgerHash, - "xrpl::loadByHash : ledger hash match if loaded"); - return ledger; - } - return {}; -} } // namespace xrpl diff --git a/src/libxrpl/protocol/LedgerHeader.cpp b/src/libxrpl/protocol/LedgerHeader.cpp index 270833c6fa..38e7a7f6dd 100644 --- a/src/libxrpl/protocol/LedgerHeader.cpp +++ b/src/libxrpl/protocol/LedgerHeader.cpp @@ -1,7 +1,9 @@ #include #include +#include #include #include +#include namespace xrpl { @@ -51,4 +53,21 @@ deserializePrefixedHeader(Slice data, bool hasHash) return deserializeHeader(data + 4, hasHash); } +uint256 +calculateLedgerHash(LedgerHeader const& info) +{ + // VFALCO This has to match addRaw in View.h. + return sha512Half( + HashPrefix::ledgerMaster, + std::uint32_t(info.seq), + std::uint64_t(info.drops.drops()), + info.parentHash, + info.txHash, + info.accountHash, + std::uint32_t(info.parentCloseTime.time_since_epoch().count()), + std::uint32_t(info.closeTime.time_since_epoch().count()), + std::uint8_t(info.closeTimeResolution.count()), + std::uint8_t(info.closeFlags)); +} + } // namespace xrpl diff --git a/src/xrpld/app/misc/detail/Manifest.cpp b/src/libxrpl/server/Manifest.cpp similarity index 100% rename from src/xrpld/app/misc/detail/Manifest.cpp rename to src/libxrpl/server/Manifest.cpp diff --git a/src/xrpld/app/paths/detail/AMMLiquidity.cpp b/src/libxrpl/tx/paths/AMMLiquidity.cpp similarity index 99% rename from src/xrpld/app/paths/detail/AMMLiquidity.cpp rename to src/libxrpl/tx/paths/AMMLiquidity.cpp index 72ee8eb261..4d6b67fa68 100644 --- a/src/xrpld/app/paths/detail/AMMLiquidity.cpp +++ b/src/libxrpl/tx/paths/AMMLiquidity.cpp @@ -1,5 +1,5 @@ -#include -#include +#include +#include namespace xrpl { diff --git a/src/xrpld/app/paths/detail/AMMOffer.cpp b/src/libxrpl/tx/paths/AMMOffer.cpp similarity index 98% rename from src/xrpld/app/paths/detail/AMMOffer.cpp rename to src/libxrpl/tx/paths/AMMOffer.cpp index 4871d2251a..2168d80094 100644 --- a/src/xrpld/app/paths/detail/AMMOffer.cpp +++ b/src/libxrpl/tx/paths/AMMOffer.cpp @@ -1,7 +1,6 @@ -#include -#include - #include +#include +#include namespace xrpl { diff --git a/src/xrpld/app/paths/detail/BookStep.cpp b/src/libxrpl/tx/paths/BookStep.cpp similarity index 99% rename from src/xrpld/app/paths/detail/BookStep.cpp rename to src/libxrpl/tx/paths/BookStep.cpp index df1e849b81..3e492d8a19 100644 --- a/src/xrpld/app/paths/detail/BookStep.cpp +++ b/src/libxrpl/tx/paths/BookStep.cpp @@ -1,6 +1,3 @@ -#include -#include - #include #include #include @@ -11,6 +8,8 @@ #include #include #include +#include +#include #include #include #include diff --git a/src/xrpld/app/paths/detail/DirectStep.cpp b/src/libxrpl/tx/paths/DirectStep.cpp similarity index 99% rename from src/xrpld/app/paths/detail/DirectStep.cpp rename to src/libxrpl/tx/paths/DirectStep.cpp index d1d540eda5..9cae103d8f 100644 --- a/src/xrpld/app/paths/detail/DirectStep.cpp +++ b/src/libxrpl/tx/paths/DirectStep.cpp @@ -1,5 +1,3 @@ -#include - #include #include #include @@ -7,6 +5,7 @@ #include #include #include +#include #include #include diff --git a/src/xrpld/app/paths/detail/PaySteps.cpp b/src/libxrpl/tx/paths/PaySteps.cpp similarity index 100% rename from src/xrpld/app/paths/detail/PaySteps.cpp rename to src/libxrpl/tx/paths/PaySteps.cpp diff --git a/src/xrpld/app/paths/detail/XRPEndpointStep.cpp b/src/libxrpl/tx/paths/XRPEndpointStep.cpp similarity index 99% rename from src/xrpld/app/paths/detail/XRPEndpointStep.cpp rename to src/libxrpl/tx/paths/XRPEndpointStep.cpp index 8b1835069b..7452f57ecd 100644 --- a/src/xrpld/app/paths/detail/XRPEndpointStep.cpp +++ b/src/libxrpl/tx/paths/XRPEndpointStep.cpp @@ -1,5 +1,3 @@ -#include - #include #include #include @@ -9,6 +7,7 @@ #include #include #include +#include #include #include diff --git a/src/test/app/AMMExtended_test.cpp b/src/test/app/AMMExtended_test.cpp index 93ad92af3d..a416a2f9ee 100644 --- a/src/test/app/AMMExtended_test.cpp +++ b/src/test/app/AMMExtended_test.cpp @@ -5,11 +5,10 @@ #include #include -#include - #include #include #include +#include #include #include #include diff --git a/src/test/app/FeeVote_test.cpp b/src/test/app/FeeVote_test.cpp index 923e7b58b2..416b1ab70b 100644 --- a/src/test/app/FeeVote_test.cpp +++ b/src/test/app/FeeVote_test.cpp @@ -1,6 +1,5 @@ #include -#include #include #include @@ -251,7 +250,8 @@ class FeeVote_test : public beast::unit_test::suite jtx::Env env(*this, jtx::testable_amendments() - featureXRPFees); auto ledger = std::make_shared( create_genesis, - env.app().config(), + Rules{env.app().config().features}, + env.app().config().FEES.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -280,7 +280,8 @@ class FeeVote_test : public beast::unit_test::suite jtx::Env env(*this, jtx::testable_amendments() | featureXRPFees); auto ledger = std::make_shared( create_genesis, - env.app().config(), + Rules{env.app().config().features}, + env.app().config().FEES.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -312,7 +313,8 @@ class FeeVote_test : public beast::unit_test::suite jtx::Env env(*this, jtx::testable_amendments() - featureXRPFees); auto ledger = std::make_shared( create_genesis, - env.app().config(), + Rules{env.app().config().features}, + env.app().config().FEES.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -333,7 +335,8 @@ class FeeVote_test : public beast::unit_test::suite jtx::Env env(*this, jtx::testable_amendments() | featureXRPFees); auto ledger = std::make_shared( create_genesis, - env.app().config(), + Rules{env.app().config().features}, + env.app().config().FEES.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -358,7 +361,11 @@ class FeeVote_test : public beast::unit_test::suite jtx::Env env(*this, jtx::testable_amendments()); auto ledger = std::make_shared( - create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); + create_genesis, + Rules{env.app().config().features}, + env.app().config().FEES.toFees(), + std::vector{}, + env.app().getNodeFamily()); // Create the next ledger to apply transaction to ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); @@ -393,7 +400,11 @@ class FeeVote_test : public beast::unit_test::suite jtx::Env env(*this, jtx::testable_amendments() | featureXRPFees); auto ledger = std::make_shared( - create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); + create_genesis, + Rules{env.app().config().features}, + env.app().config().FEES.toFees(), + std::vector{}, + env.app().getNodeFamily()); ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); @@ -437,7 +448,11 @@ class FeeVote_test : public beast::unit_test::suite jtx::Env env(*this, jtx::testable_amendments() | featureXRPFees); auto ledger = std::make_shared( - create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); + create_genesis, + Rules{env.app().config().features}, + env.app().config().FEES.toFees(), + std::vector{}, + env.app().getNodeFamily()); ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); @@ -464,7 +479,11 @@ class FeeVote_test : public beast::unit_test::suite jtx::Env env(*this, jtx::testable_amendments() | featureXRPFees); auto ledger = std::make_shared( - create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); + create_genesis, + Rules{env.app().config().features}, + env.app().config().FEES.toFees(), + std::vector{}, + env.app().getNodeFamily()); ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); @@ -506,7 +525,11 @@ class FeeVote_test : public beast::unit_test::suite jtx::Env env(*this, jtx::testable_amendments() | featureXRPFees); auto ledger = std::make_shared( - create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); + create_genesis, + Rules{env.app().config().features}, + env.app().config().FEES.toFees(), + std::vector{}, + env.app().getNodeFamily()); ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); @@ -544,7 +567,8 @@ class FeeVote_test : public beast::unit_test::suite auto ledger = std::make_shared( create_genesis, - env.app().config(), + Rules{env.app().config().features}, + env.app().config().FEES.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -573,7 +597,8 @@ class FeeVote_test : public beast::unit_test::suite auto ledger = std::make_shared( create_genesis, - env.app().config(), + Rules{env.app().config().features}, + env.app().config().FEES.toFees(), std::vector{}, env.app().getNodeFamily()); @@ -616,7 +641,11 @@ class FeeVote_test : public beast::unit_test::suite auto feeVote = make_FeeVote(setup, env.app().journal("FeeVote")); auto ledger = std::make_shared( - create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); + create_genesis, + Rules{env.app().config().features}, + env.app().config().FEES.toFees(), + std::vector{}, + env.app().getNodeFamily()); // doVoting requires a flag ledger (every 256th ledger) // We need to create a ledger at sequence 256 to make it a flag ledger diff --git a/src/test/app/LedgerHistory_test.cpp b/src/test/app/LedgerHistory_test.cpp index 93ab4a6210..dbc20fe8f2 100644 --- a/src/test/app/LedgerHistory_test.cpp +++ b/src/test/app/LedgerHistory_test.cpp @@ -38,7 +38,8 @@ public: assert(!stx); return std::make_shared( create_genesis, - env.app().config(), + Rules{env.app().config().features}, + env.app().config().FEES.toFees(), std::vector{}, env.app().getNodeFamily()); } diff --git a/src/test/app/RCLValidations_test.cpp b/src/test/app/RCLValidations_test.cpp index 63f295e3b7..529e215395 100644 --- a/src/test/app/RCLValidations_test.cpp +++ b/src/test/app/RCLValidations_test.cpp @@ -1,10 +1,10 @@ #include #include -#include #include #include +#include namespace xrpl { namespace test { @@ -57,7 +57,11 @@ class RCLValidations_test : public beast::unit_test::suite jtx::Env env(*this); Config config; auto prev = std::make_shared( - create_genesis, config, std::vector{}, env.app().getNodeFamily()); + create_genesis, + Rules{config.features}, + config.FEES.toFees(), + std::vector{}, + env.app().getNodeFamily()); history.push_back(prev); for (auto i = 0; i < ((2 * maxAncestors) + 1); ++i) { @@ -219,7 +223,11 @@ class RCLValidations_test : public beast::unit_test::suite auto& j = env.journal; Config config; auto prev = std::make_shared( - create_genesis, config, std::vector{}, env.app().getNodeFamily()); + create_genesis, + Rules{config.features}, + config.FEES.toFees(), + std::vector{}, + env.app().getNodeFamily()); history.push_back(prev); for (auto i = 0; i < (maxAncestors + 10); ++i) { diff --git a/src/test/app/Regression_test.cpp b/src/test/app/Regression_test.cpp index d7535d5578..5d58f59fd7 100644 --- a/src/test/app/Regression_test.cpp +++ b/src/test/app/Regression_test.cpp @@ -45,7 +45,11 @@ struct Regression_test : public beast::unit_test::suite // be reproduced against an open ledger. Make a local // closed ledger and work with it directly. auto closed = std::make_shared( - create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); + create_genesis, + Rules{env.app().config().features}, + env.app().config().FEES.toFees(), + std::vector{}, + env.app().getNodeFamily()); auto expectedDrops = INITIAL_XRP; BEAST_EXPECT(closed->header().drops == expectedDrops); diff --git a/src/test/consensus/LedgerTiming_test.cpp b/src/test/consensus/LedgerTiming_test.cpp index 945f6b4ff0..4441184af4 100644 --- a/src/test/consensus/LedgerTiming_test.cpp +++ b/src/test/consensus/LedgerTiming_test.cpp @@ -1,6 +1,5 @@ -#include - #include +#include namespace xrpl { namespace test { diff --git a/src/test/consensus/NegativeUNL_test.cpp b/src/test/consensus/NegativeUNL_test.cpp index 019d8ee545..ddb5fef599 100644 --- a/src/test/consensus/NegativeUNL_test.cpp +++ b/src/test/consensus/NegativeUNL_test.cpp @@ -1,7 +1,6 @@ #include #include -#include #include #include @@ -211,7 +210,11 @@ class NegativeUNL_test : public beast::unit_test::suite std::vector publicKeys = createPublicKeys(3); // genesis ledger auto l = std::make_shared( - create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); + create_genesis, + Rules{env.app().config().features}, + env.app().config().FEES.toFees(), + std::vector{}, + env.app().getNodeFamily()); // Record the public keys and ledger sequences of expected negative UNL // validators when we build the ledger history @@ -543,7 +546,8 @@ struct NetworkHistory static uint256 fake_amendment; // So we have different genesis ledgers auto l = std::make_shared( create_genesis, - env.app().config(), + Rules{env.app().config().features}, + env.app().config().FEES.toFees(), std::vector{fake_amendment++}, env.app().getNodeFamily()); history.push_back(l); @@ -1670,7 +1674,11 @@ class NegativeUNLVoteFilterValidations_test : public beast::unit_test::suite testcase("Filter Validations"); jtx::Env env(*this); auto l = std::make_shared( - create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); + create_genesis, + Rules{env.app().config().features}, + env.app().config().FEES.toFees(), + std::vector{}, + env.app().getNodeFamily()); auto createSTVal = [&](std::pair const& keys) { return std::make_shared( diff --git a/src/test/csf/ledgers.h b/src/test/csf/ledgers.h index 6e50f3584b..67a7427af6 100644 --- a/src/test/csf/ledgers.h +++ b/src/test/csf/ledgers.h @@ -2,13 +2,12 @@ #include -#include - #include #include #include #include #include +#include #include diff --git a/src/test/jtx/Env.h b/src/test/jtx/Env.h index a103d42ca3..9d525f14ad 100644 --- a/src/test/jtx/Env.h +++ b/src/test/jtx/Env.h @@ -11,17 +11,17 @@ #include #include -#include #include #include -#include #include +#include #include #include #include #include #include +#include #include #include #include diff --git a/src/test/jtx/impl/paths.cpp b/src/test/jtx/impl/paths.cpp index e26f214fe4..fe9ff916bd 100644 --- a/src/test/jtx/impl/paths.cpp +++ b/src/test/jtx/impl/paths.cpp @@ -1,6 +1,6 @@ #include -#include +#include #include diff --git a/src/test/jtx/utility.h b/src/test/jtx/utility.h index 895d00f12b..15c323f047 100644 --- a/src/test/jtx/utility.h +++ b/src/test/jtx/utility.h @@ -2,9 +2,8 @@ #include -#include - #include +#include #include #include diff --git a/src/test/ledger/PendingSaves_test.cpp b/src/test/ledger/PendingSaves_test.cpp index ddf371e913..5e08fc53e4 100644 --- a/src/test/ledger/PendingSaves_test.cpp +++ b/src/test/ledger/PendingSaves_test.cpp @@ -1,6 +1,5 @@ -#include - #include +#include namespace xrpl { namespace test { diff --git a/src/test/ledger/SkipList_test.cpp b/src/test/ledger/SkipList_test.cpp index 8430db3904..9a00b1d3fe 100644 --- a/src/test/ledger/SkipList_test.cpp +++ b/src/test/ledger/SkipList_test.cpp @@ -1,8 +1,7 @@ #include -#include - #include +#include #include namespace xrpl { @@ -18,7 +17,11 @@ class SkipList_test : public beast::unit_test::suite { Config config; auto prev = std::make_shared( - create_genesis, config, std::vector{}, env.app().getNodeFamily()); + create_genesis, + Rules{config.features}, + config.FEES.toFees(), + std::vector{}, + env.app().getNodeFamily()); history.push_back(prev); for (auto i = 0; i < 1023; ++i) { diff --git a/src/test/ledger/View_test.cpp b/src/test/ledger/View_test.cpp index f57cb609cc..765d2e3ee4 100644 --- a/src/test/ledger/View_test.cpp +++ b/src/test/ledger/View_test.cpp @@ -1,9 +1,9 @@ #include -#include #include #include +#include #include #include #include @@ -116,7 +116,11 @@ class View_test : public beast::unit_test::suite Env env(*this); Config config; std::shared_ptr const genesis = std::make_shared( - create_genesis, config, std::vector{}, env.app().getNodeFamily()); + create_genesis, + Rules{config.features}, + config.FEES.toFees(), + std::vector{}, + env.app().getNodeFamily()); auto const ledger = std::make_shared(*genesis, env.app().timeKeeper().closeTime()); wipe(*ledger); ReadView& v = *ledger; @@ -379,7 +383,11 @@ class View_test : public beast::unit_test::suite Env env(*this); Config config; std::shared_ptr const genesis = std::make_shared( - create_genesis, config, std::vector{}, env.app().getNodeFamily()); + create_genesis, + Rules{config.features}, + config.FEES.toFees(), + std::vector{}, + env.app().getNodeFamily()); auto const ledger = std::make_shared(*genesis, env.app().timeKeeper().closeTime()); auto setup = [&ledger](std::vector const& vec) { @@ -583,7 +591,11 @@ class View_test : public beast::unit_test::suite Env env(*this); Config config; std::shared_ptr const genesis = std::make_shared( - create_genesis, config, std::vector{}, env.app().getNodeFamily()); + create_genesis, + Rules{config.features}, + config.FEES.toFees(), + std::vector{}, + env.app().getNodeFamily()); auto const ledger = std::make_shared(*genesis, env.app().timeKeeper().closeTime()); auto setup123 = [&ledger, this]() { // erase middle element @@ -929,7 +941,11 @@ class View_test : public beast::unit_test::suite Env env(*this); Config config; std::shared_ptr const genesis = std::make_shared( - create_genesis, config, std::vector{}, env.app().getNodeFamily()); + create_genesis, + Rules{config.features}, + config.FEES.toFees(), + std::vector{}, + env.app().getNodeFamily()); auto const ledger = std::make_shared(*genesis, env.app().timeKeeper().closeTime()); wipe(*ledger); diff --git a/src/test/overlay/compression_test.cpp b/src/test/overlay/compression_test.cpp index 38b60c2251..8cee7df7d2 100644 --- a/src/test/overlay/compression_test.cpp +++ b/src/test/overlay/compression_test.cpp @@ -4,7 +4,6 @@ #include #include -#include #include #include #include @@ -15,6 +14,7 @@ #include #include #include +#include #include #include #include diff --git a/src/xrpld/app/consensus/RCLConsensus.cpp b/src/xrpld/app/consensus/RCLConsensus.cpp index 315f9f2ab5..4921a469c5 100644 --- a/src/xrpld/app/consensus/RCLConsensus.cpp +++ b/src/xrpld/app/consensus/RCLConsensus.cpp @@ -3,7 +3,6 @@ #include #include #include -#include #include #include #include @@ -11,7 +10,6 @@ #include #include #include -#include #include #include @@ -20,6 +18,8 @@ #include #include #include +#include +#include #include #include #include diff --git a/src/xrpld/app/consensus/RCLCxLedger.h b/src/xrpld/app/consensus/RCLCxLedger.h index 6b96fc8af3..09111ebdb6 100644 --- a/src/xrpld/app/consensus/RCLCxLedger.h +++ b/src/xrpld/app/consensus/RCLCxLedger.h @@ -1,8 +1,8 @@ #pragma once -#include #include +#include #include #include diff --git a/src/xrpld/app/consensus/RCLValidations.h b/src/xrpld/app/consensus/RCLValidations.h index 35c1686f9e..8da82e6425 100644 --- a/src/xrpld/app/consensus/RCLValidations.h +++ b/src/xrpld/app/consensus/RCLValidations.h @@ -1,8 +1,8 @@ #pragma once -#include #include +#include #include #include #include diff --git a/src/xrpld/app/ledger/InboundLedger.h b/src/xrpld/app/ledger/InboundLedger.h index ef1362365d..4795ea8f9f 100644 --- a/src/xrpld/app/ledger/InboundLedger.h +++ b/src/xrpld/app/ledger/InboundLedger.h @@ -1,11 +1,11 @@ #pragma once -#include #include #include #include #include +#include #include #include diff --git a/src/xrpld/app/ledger/LedgerHistory.cpp b/src/xrpld/app/ledger/LedgerHistory.cpp index 5ff5555fff..15abd8c5c7 100644 --- a/src/xrpld/app/ledger/LedgerHistory.cpp +++ b/src/xrpld/app/ledger/LedgerHistory.cpp @@ -1,5 +1,7 @@ #include +#include #include +#include #include #include @@ -73,7 +75,9 @@ LedgerHistory::getLedgerBySeq(LedgerIndex index) } } - std::shared_ptr ret = loadByIndex(index, app_); + Rules const rules{app_.config().features}; + Fees const fees = app_.config().FEES.toFees(); + std::shared_ptr ret = loadByIndex(index, rules, fees, app_); if (!ret) return ret; @@ -111,7 +115,9 @@ LedgerHistory::getLedgerByHash(LedgerHash const& hash) return ret; } - ret = loadByHash(hash, app_); + Rules const rules{app_.config().features}; + Fees const fees = app_.config().FEES.toFees(); + ret = loadByHash(hash, rules, fees, app_); if (!ret) return ret; diff --git a/src/xrpld/app/ledger/LedgerHistory.h b/src/xrpld/app/ledger/LedgerHistory.h index 6ec279b28a..b988d152ad 100644 --- a/src/xrpld/app/ledger/LedgerHistory.h +++ b/src/xrpld/app/ledger/LedgerHistory.h @@ -1,9 +1,9 @@ #pragma once -#include #include #include +#include #include #include diff --git a/src/xrpld/app/ledger/LedgerMaster.h b/src/xrpld/app/ledger/LedgerMaster.h index c25e553455..16e35c3dcd 100644 --- a/src/xrpld/app/ledger/LedgerMaster.h +++ b/src/xrpld/app/ledger/LedgerMaster.h @@ -2,17 +2,18 @@ #include #include -#include #include #include #include #include -#include +#include #include #include #include #include +#include +#include #include #include #include diff --git a/src/xrpld/app/ledger/LedgerPersistence.h b/src/xrpld/app/ledger/LedgerPersistence.h new file mode 100644 index 0000000000..e131932af4 --- /dev/null +++ b/src/xrpld/app/ledger/LedgerPersistence.h @@ -0,0 +1,90 @@ +#pragma once + +#include + +#include +#include + +namespace xrpl { + +class ServiceRegistry; +struct Fees; + +/** Save, or arrange to save, a fully-validated ledger. + + @param registry The service registry providing access to required services. + @param ledger The fully-validated ledger to save. + @param isSynchronous If true, wait for the save to complete. + @param isCurrent If true, the ledger is the current validated ledger. + + @return false on error. +*/ +bool +pendSaveValidated( + ServiceRegistry& registry, + std::shared_ptr const& ledger, + bool isSynchronous, + bool isCurrent); + +/** Make ledger using info loaded from database. + + @param info Ledger information. + @param rules Rules to use (may be overwritten by setup()). + @param fees Fees to use (may be overwritten by setup()). + @param registry Service registry for dependency injection. + @param acquire Acquire the ledger if not found locally. + @return Shared pointer to the ledger. +*/ +std::shared_ptr +loadLedgerHelper( + LedgerHeader const& info, + Rules const& rules, + Fees const& fees, + ServiceRegistry& registry, + bool acquire); + +/** Load a ledger by its sequence number. + + @param ledgerIndex The sequence number of the ledger to load. + @param rules Rules to use (may be overwritten by setup()). + @param fees Fees to use (may be overwritten by setup()). + @param registry Service registry for dependency injection. + @param acquire Acquire the ledger if not found locally. + @return Shared pointer to the ledger, or nullptr if not found. +*/ +std::shared_ptr +loadByIndex( + std::uint32_t ledgerIndex, + Rules const& rules, + Fees const& fees, + ServiceRegistry& registry, + bool acquire = true); + +/** Load a ledger by its hash. + + @param ledgerHash The hash of the ledger to load. + @param rules Rules to use (may be overwritten by setup()). + @param fees Fees to use (may be overwritten by setup()). + @param registry Service registry for dependency injection. + @param acquire Acquire the ledger if not found locally. + @return Shared pointer to the ledger, or nullptr if not found. +*/ +std::shared_ptr +loadByHash( + uint256 const& ledgerHash, + Rules const& rules, + Fees const& fees, + ServiceRegistry& registry, + bool acquire = true); + +/** Fetch the ledger with the highest sequence contained in the database. + + @param rules Rules to use (may be overwritten by setup()). + @param fees Fees to use (may be overwritten by setup()). + @param registry Service registry for dependency injection. + @return Tuple of (ledger, sequence, hash), or empty if not found. +*/ +std::tuple, std::uint32_t, uint256> +getLatestLedger(Rules const& rules, Fees const& fees, ServiceRegistry& registry); + +} // namespace xrpl diff --git a/src/xrpld/app/ledger/LedgerReplay.h b/src/xrpld/app/ledger/LedgerReplay.h index f4cbf9c69e..a2b2e60e8e 100644 --- a/src/xrpld/app/ledger/LedgerReplay.h +++ b/src/xrpld/app/ledger/LedgerReplay.h @@ -4,6 +4,7 @@ #include #include +#include namespace xrpl { diff --git a/src/xrpld/app/ledger/LedgerToJson.h b/src/xrpld/app/ledger/LedgerToJson.h index 9def1c3826..3686311656 100644 --- a/src/xrpld/app/ledger/LedgerToJson.h +++ b/src/xrpld/app/ledger/LedgerToJson.h @@ -1,11 +1,11 @@ #pragma once -#include #include #include #include #include +#include #include namespace xrpl { diff --git a/src/xrpld/app/ledger/LocalTxs.h b/src/xrpld/app/ledger/LocalTxs.h index 34dfede40f..cb17be5bdb 100644 --- a/src/xrpld/app/ledger/LocalTxs.h +++ b/src/xrpld/app/ledger/LocalTxs.h @@ -1,7 +1,6 @@ #pragma once -#include - +#include #include #include diff --git a/src/xrpld/app/ledger/OpenLedger.h b/src/xrpld/app/ledger/OpenLedger.h index 76123bafae..5b1d611b44 100644 --- a/src/xrpld/app/ledger/OpenLedger.h +++ b/src/xrpld/app/ledger/OpenLedger.h @@ -1,7 +1,5 @@ #pragma once -#include -#include #include #include @@ -9,6 +7,8 @@ #include #include #include +#include +#include #include #include diff --git a/src/xrpld/app/ledger/detail/BuildLedger.cpp b/src/xrpld/app/ledger/detail/BuildLedger.cpp index 37325835a9..3b48ab13c5 100644 --- a/src/xrpld/app/ledger/detail/BuildLedger.cpp +++ b/src/xrpld/app/ledger/detail/BuildLedger.cpp @@ -1,10 +1,10 @@ #include -#include #include #include #include -#include +#include +#include #include #include diff --git a/src/xrpld/app/ledger/detail/InboundLedger.cpp b/src/xrpld/app/ledger/detail/InboundLedger.cpp index 9f7312ea34..764a19dd0b 100644 --- a/src/xrpld/app/ledger/detail/InboundLedger.cpp +++ b/src/xrpld/app/ledger/detail/InboundLedger.cpp @@ -224,8 +224,9 @@ InboundLedger::tryDB(NodeStore::Database& srcDB) { auto makeLedger = [&, this](Blob const& data) { JLOG(journal_.trace()) << "Ledger header found in fetch pack"; + Rules const rules{app_.config().features}; mLedger = std::make_shared( - deserializePrefixedHeader(makeSlice(data)), app_.config(), app_.getNodeFamily()); + deserializePrefixedHeader(makeSlice(data)), rules, app_.getNodeFamily()); if (mLedger->header().hash != hash_ || (mSeq != 0 && mSeq != mLedger->header().seq)) { // We know for a fact the ledger can never be acquired @@ -777,7 +778,8 @@ InboundLedger::takeHeader(std::string const& data) return true; auto* f = &app_.getNodeFamily(); - mLedger = std::make_shared(deserializeHeader(makeSlice(data)), app_.config(), *f); + Rules const rules{app_.config().features}; + mLedger = std::make_shared(deserializeHeader(makeSlice(data)), rules, *f); if (mLedger->header().hash != hash_ || (mSeq != 0 && mSeq != mLedger->header().seq)) { JLOG(journal_.warn()) << "Acquire hash mismatch: " << mLedger->header().hash diff --git a/src/xrpld/app/ledger/detail/LedgerCleaner.cpp b/src/xrpld/app/ledger/detail/LedgerCleaner.cpp index 3052f787dc..8f6e0fb188 100644 --- a/src/xrpld/app/ledger/detail/LedgerCleaner.cpp +++ b/src/xrpld/app/ledger/detail/LedgerCleaner.cpp @@ -1,6 +1,8 @@ #include #include #include +#include +#include #include #include @@ -261,7 +263,9 @@ private: return false; } - auto dbLedger = loadByIndex(ledgerIndex, app_); + Rules const rules{app_.config().features}; + Fees const fees = app_.config().FEES.toFees(); + auto const dbLedger = loadByIndex(ledgerIndex, rules, fees, app_); if (!dbLedger || (dbLedger->header().hash != ledgerHash) || (dbLedger->header().parentHash != nodeLedger->header().parentHash)) { diff --git a/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp b/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp index cb2e2e57ea..367149b9d2 100644 --- a/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp +++ b/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp @@ -124,7 +124,8 @@ LedgerDeltaAcquire::processData( if (info.seq == ledgerSeq_) { // create a temporary ledger for building a LedgerReplay object later - replayTemp_ = std::make_shared(info, app_.config(), app_.getNodeFamily()); + Rules const rules{app_.config().features}; + replayTemp_ = std::make_shared(info, rules, app_.getNodeFamily()); if (replayTemp_) { complete_ = true; diff --git a/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.h b/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.h index 2877d997e6..9ac58c2e7c 100644 --- a/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.h +++ b/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.h @@ -1,11 +1,11 @@ #pragma once #include -#include #include #include #include +#include #include diff --git a/src/xrpld/app/ledger/detail/LedgerMaster.cpp b/src/xrpld/app/ledger/detail/LedgerMaster.cpp index 320c4bc722..4d90cbddcd 100644 --- a/src/xrpld/app/ledger/detail/LedgerMaster.cpp +++ b/src/xrpld/app/ledger/detail/LedgerMaster.cpp @@ -1,18 +1,17 @@ #include -#include #include +#include #include #include -#include #include #include #include #include #include -#include #include #include #include +#include #include #include @@ -22,7 +21,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -1389,7 +1390,7 @@ LedgerMaster::updatePaths() try { - auto& pathRequests = app_.getPathRequests(); + auto& pathRequests = app_.getPathRequestManager(); { std::lock_guard ml(m_mutex); if (!pathRequests.requestsPending()) @@ -1471,7 +1472,7 @@ LedgerMaster::newOrderBookDB() bool LedgerMaster::newPFWork(char const* name, std::unique_lock&) { - if (!app_.isStopping() && mPathFindThread < 2 && app_.getPathRequests().requestsPending()) + if (!app_.isStopping() && mPathFindThread < 2 && app_.getPathRequestManager().requestsPending()) { JLOG(m_journal.debug()) << "newPFWork: Creating job. path find threads: " << mPathFindThread; diff --git a/src/xrpld/app/ledger/detail/LedgerPersistence.cpp b/src/xrpld/app/ledger/detail/LedgerPersistence.cpp new file mode 100644 index 0000000000..6ca8e3cd1b --- /dev/null +++ b/src/xrpld/app/ledger/detail/LedgerPersistence.cpp @@ -0,0 +1,167 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace xrpl { + +static bool +saveValidatedLedger( + ServiceRegistry& registry, + std::shared_ptr const& ledger, + bool current) +{ + auto j = registry.journal("Ledger"); + auto seq = ledger->header().seq; + if (!registry.pendingSaves().startWork(seq)) + { + // The save was completed synchronously + JLOG(j.debug()) << "Save aborted"; + return true; + } + + auto& db = registry.getRelationalDatabase(); + + auto const res = db.saveValidatedLedger(ledger, current); + + // Clients can now trust the database for + // information about this ledger sequence. + registry.pendingSaves().finishWork(seq); + return res; +} + +bool +pendSaveValidated( + ServiceRegistry& registry, + std::shared_ptr const& ledger, + bool isSynchronous, + bool isCurrent) +{ + if (!registry.getHashRouter().setFlags(ledger->header().hash, HashRouterFlags::SAVED)) + { + // We have tried to save this ledger recently + auto stream = registry.journal("Ledger").debug(); + JLOG(stream) << "Double pend save for " << ledger->header().seq; + + if (!isSynchronous || !registry.pendingSaves().pending(ledger->header().seq)) + { + // Either we don't need it to be finished + // or it is finished + return true; + } + } + + XRPL_ASSERT(ledger->isImmutable(), "xrpl::pendSaveValidated : immutable ledger"); + + if (!registry.pendingSaves().shouldWork(ledger->header().seq, isSynchronous)) + { + auto stream = registry.journal("Ledger").debug(); + JLOG(stream) << "Pend save with seq in pending saves " << ledger->header().seq; + + return true; + } + + // See if we can use the JobQueue. + if (!isSynchronous && + registry.getJobQueue().addJob( + isCurrent ? jtPUBLEDGER : jtPUBOLDLEDGER, + std::to_string(ledger->seq()), + [®istry, ledger, isCurrent]() { saveValidatedLedger(registry, ledger, isCurrent); })) + { + return true; + } + + // The JobQueue won't do the Job. Do the save synchronously. + return saveValidatedLedger(registry, ledger, isCurrent); +} + +std::shared_ptr +loadLedgerHelper( + LedgerHeader const& info, + Rules const& rules, + Fees const& fees, + ServiceRegistry& registry, + bool acquire) +{ + bool loaded = false; + auto ledger = std::make_shared( + info, loaded, acquire, rules, fees, registry.getNodeFamily(), registry.journal("Ledger")); + + if (!loaded) + ledger.reset(); + + return ledger; +} + +static void +finishLoadByIndexOrHash(std::shared_ptr const& ledger, beast::Journal j) +{ + if (!ledger) + return; + + XRPL_ASSERT( + ledger->header().seq < XRP_LEDGER_EARLIEST_FEES || ledger->read(keylet::fees()), + "xrpl::finishLoadByIndexOrHash : valid ledger fees"); + ledger->setImmutable(); + + JLOG(j.trace()) << "Loaded ledger: " << to_string(ledger->header().hash); + + ledger->setFull(); +} + +std::tuple, std::uint32_t, uint256> +getLatestLedger(Rules const& rules, Fees const& fees, ServiceRegistry& registry) +{ + std::optional const info = registry.getRelationalDatabase().getNewestLedgerInfo(); + if (!info) + return {std::shared_ptr(), {}, {}}; + return {loadLedgerHelper(*info, rules, fees, registry, true), info->seq, info->hash}; +} + +std::shared_ptr +loadByIndex( + std::uint32_t ledgerIndex, + Rules const& rules, + Fees const& fees, + ServiceRegistry& registry, + bool acquire) +{ + if (std::optional info = + registry.getRelationalDatabase().getLedgerInfoByIndex(ledgerIndex)) + { + std::shared_ptr ledger = loadLedgerHelper(*info, rules, fees, registry, acquire); + finishLoadByIndexOrHash(ledger, registry.journal("Ledger")); + return ledger; + } + return {}; +} + +std::shared_ptr +loadByHash( + uint256 const& ledgerHash, + Rules const& rules, + Fees const& fees, + ServiceRegistry& registry, + bool acquire) +{ + if (std::optional info = + registry.getRelationalDatabase().getLedgerInfoByHash(ledgerHash)) + { + std::shared_ptr ledger = loadLedgerHelper(*info, rules, fees, registry, acquire); + finishLoadByIndexOrHash(ledger, registry.journal("Ledger")); + XRPL_ASSERT( + !ledger || ledger->header().hash == ledgerHash, + "xrpl::loadByHash : ledger hash match if loaded"); + return ledger; + } + return {}; +} + +} // namespace xrpl diff --git a/src/xrpld/app/ledger/detail/LedgerReplay.cpp b/src/xrpld/app/ledger/detail/LedgerReplay.cpp index d115402115..a02267e4a1 100644 --- a/src/xrpld/app/ledger/detail/LedgerReplay.cpp +++ b/src/xrpld/app/ledger/detail/LedgerReplay.cpp @@ -1,6 +1,7 @@ -#include #include +#include + namespace xrpl { LedgerReplay::LedgerReplay( diff --git a/src/xrpld/app/ledger/detail/LocalTxs.cpp b/src/xrpld/app/ledger/detail/LocalTxs.cpp index 8eb821a6c9..8f04da9c2d 100644 --- a/src/xrpld/app/ledger/detail/LocalTxs.cpp +++ b/src/xrpld/app/ledger/detail/LocalTxs.cpp @@ -1,6 +1,6 @@ -#include #include +#include #include /* diff --git a/src/xrpld/app/ledger/detail/OpenLedger.cpp b/src/xrpld/app/ledger/detail/OpenLedger.cpp index a26751bc64..6e9b2c3f15 100644 --- a/src/xrpld/app/ledger/detail/OpenLedger.cpp +++ b/src/xrpld/app/ledger/detail/OpenLedger.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include diff --git a/src/xrpld/app/ledger/detail/SkipListAcquire.h b/src/xrpld/app/ledger/detail/SkipListAcquire.h index 5a79e8ae5c..da62578d41 100644 --- a/src/xrpld/app/ledger/detail/SkipListAcquire.h +++ b/src/xrpld/app/ledger/detail/SkipListAcquire.h @@ -1,10 +1,10 @@ #pragma once #include -#include #include #include +#include #include namespace xrpl { diff --git a/src/xrpld/app/main/Application.cpp b/src/xrpld/app/main/Application.cpp index 55ba09e49e..2be94d24bf 100644 --- a/src/xrpld/app/main/Application.cpp +++ b/src/xrpld/app/main/Application.cpp @@ -3,11 +3,11 @@ #include #include #include +#include #include #include #include #include -#include #include #include #include @@ -21,13 +21,13 @@ #include #include #include -#include #include #include #include #include #include #include +#include #include #include @@ -42,6 +42,7 @@ #include #include #include +#include #include #include #include @@ -170,7 +171,7 @@ public: std::unique_ptr m_nodeStore; NodeFamily nodeFamily_; std::unique_ptr m_orderBookDB; - std::unique_ptr m_pathRequests; + std::unique_ptr m_pathRequestManager; std::unique_ptr m_ledgerMaster; std::unique_ptr ledgerCleaner_; std::unique_ptr m_inboundLedgers; @@ -330,8 +331,8 @@ public: , m_orderBookDB(make_OrderBookDB(*this, {config_->PATH_SEARCH_MAX, config_->standalone()})) - , m_pathRequests( - std::make_unique( + , m_pathRequestManager( + std::make_unique( *this, logs_->journal("PathRequest"), m_collectorManager->collector())) @@ -660,10 +661,10 @@ public: return *m_orderBookDB; } - PathRequests& - getPathRequests() override + PathRequestManager& + getPathRequestManager() override { - return *m_pathRequests; + return *m_pathRequestManager; } CachedSLEs& @@ -1639,8 +1640,12 @@ ApplicationImp::startGenesisLedger() ? m_amendmentTable->getDesired() : std::vector{}; - std::shared_ptr const genesis = - std::make_shared(create_genesis, *config_, initialAmendments, nodeFamily_); + std::shared_ptr const genesis = std::make_shared( + create_genesis, + Rules{config_->features}, + config_->FEES.toFees(), + initialAmendments, + nodeFamily_); m_ledgerMaster->storeLedger(genesis); auto const next = std::make_shared(*genesis, timeKeeper().closeTime()); @@ -1661,7 +1666,8 @@ ApplicationImp::getLastFullLedger() try { - auto const [ledger, seq, hash] = getLatestLedger(*this); + auto const [ledger, seq, hash] = + getLatestLedger(Rules{config_->features}, config_->FEES.toFees(), *this); if (!ledger) return ledger; @@ -1772,7 +1778,8 @@ ApplicationImp::loadLedgerFromFile(std::string const& name) return nullptr; } - auto loadLedger = std::make_shared(seq, closeTime, *config_, nodeFamily_); + auto loadLedger = std::make_shared( + seq, closeTime, Rules{config_->features}, config_->FEES.toFees(), nodeFamily_); loadLedger->setTotalDrops(totalDrops); for (Json::UInt index = 0; index < ledger.get().size(); ++index) @@ -1852,7 +1859,8 @@ ApplicationImp::loadOldLedger( if (hash.parseHex(ledgerID)) { - loadLedger = loadByHash(hash, *this); + loadLedger = + loadByHash(hash, Rules{config_->features}, config_->FEES.toFees(), *this); if (!loadLedger) { @@ -1879,7 +1887,10 @@ ApplicationImp::loadOldLedger( std::uint32_t index = 0; if (beast::lexicalCastChecked(index, ledgerID)) - loadLedger = loadByIndex(index, *this); + { + loadLedger = + loadByIndex(index, Rules{config_->features}, config_->FEES.toFees(), *this); + } } if (!loadLedger) @@ -1894,7 +1905,11 @@ ApplicationImp::loadOldLedger( JLOG(m_journal.info()) << "Loading parent ledger"; - loadLedger = loadByHash(replayLedger->header().parentHash, *this); + loadLedger = loadByHash( + replayLedger->header().parentHash, + Rules{config_->features}, + config_->FEES.toFees(), + *this); if (!loadLedger) { JLOG(m_journal.info()) << "Loading parent ledger from node store"; @@ -1963,10 +1978,13 @@ ApplicationImp::loadOldLedger( // LCOV_EXCL_STOP } - if (!loadLedger->assertSensible(journal("Ledger"))) + if (!loadLedger->isSensible()) { // LCOV_EXCL_START - JLOG(m_journal.fatal()) << "Ledger is not sensible."; + Json::Value j = getJson({*loadLedger, {}}); + j[jss::accountTreeHash] = to_string(loadLedger->header().accountHash); + j[jss::transTreeHash] = to_string(loadLedger->header().txHash); + JLOG(m_journal.fatal()) << "Ledger is not sensible: " << j; UNREACHABLE( "xrpl::ApplicationImp::loadOldLedger : ledger is not " "sensible"); diff --git a/src/xrpld/app/main/Application.h b/src/xrpld/app/main/Application.h index 0000ae010b..9c79aabb02 100644 --- a/src/xrpld/app/main/Application.h +++ b/src/xrpld/app/main/Application.h @@ -66,7 +66,7 @@ class NetworkOPs; class OpenLedger; class OrderBookDB; class Overlay; -class PathRequests; +class PathRequestManager; class PendingSaves; class PublicKey; class ServerHandler; diff --git a/src/xrpld/app/misc/FeeVoteImpl.cpp b/src/xrpld/app/misc/FeeVoteImpl.cpp index 764a9564ad..450e53e86c 100644 --- a/src/xrpld/app/misc/FeeVoteImpl.cpp +++ b/src/xrpld/app/misc/FeeVoteImpl.cpp @@ -1,7 +1,8 @@ -#include #include +#include #include +#include #include #include @@ -272,7 +273,7 @@ FeeVoteImpl::doVoting( baseReserve.first.dropsAs(baseReserveVote.current()); obj[sfReserveIncrement] = incReserve.first.dropsAs(incReserveVote.current()); - obj[sfReferenceFeeUnits] = Config::FEE_UNITS_DEPRECATED; + obj[sfReferenceFeeUnits] = FEE_UNITS_DEPRECATED; } }); diff --git a/src/xrpld/app/misc/NegativeUNLVote.cpp b/src/xrpld/app/misc/NegativeUNLVote.cpp index 8f0ba5255a..fe031749bc 100644 --- a/src/xrpld/app/misc/NegativeUNLVote.cpp +++ b/src/xrpld/app/misc/NegativeUNLVote.cpp @@ -1,7 +1,7 @@ #include -#include #include +#include #include namespace xrpl { diff --git a/src/xrpld/app/misc/NegativeUNLVote.h b/src/xrpld/app/misc/NegativeUNLVote.h index 7ad460cbf1..2cc63cf8c5 100644 --- a/src/xrpld/app/misc/NegativeUNLVote.h +++ b/src/xrpld/app/misc/NegativeUNLVote.h @@ -1,8 +1,7 @@ #pragma once -#include - #include +#include #include #include #include diff --git a/src/xrpld/app/misc/NetworkOPs.cpp b/src/xrpld/app/misc/NetworkOPs.cpp index 5110534efc..c97eb65990 100644 --- a/src/xrpld/app/misc/NetworkOPs.cpp +++ b/src/xrpld/app/misc/NetworkOPs.cpp @@ -2985,7 +2985,7 @@ NetworkOPsImp::pubLedger(std::shared_ptr const& lpAccepted) jvObj[jss::network_id] = registry_.getNetworkIDService().getNetworkID(); if (!lpAccepted->rules().enabled(featureXRPFees)) - jvObj[jss::fee_ref] = Config::FEE_UNITS_DEPRECATED; + jvObj[jss::fee_ref] = FEE_UNITS_DEPRECATED; jvObj[jss::fee_base] = lpAccepted->fees().base.jsonClipped(); jvObj[jss::reserve_base] = lpAccepted->fees().reserve.jsonClipped(); jvObj[jss::reserve_inc] = lpAccepted->fees().increment.jsonClipped(); @@ -4009,7 +4009,7 @@ NetworkOPsImp::subLedger(InfoSub::ref isrListener, Json::Value& jvResult) jvResult[jss::ledger_time] = Json::Value::UInt(lpClosed->header().closeTime.time_since_epoch().count()); if (!lpClosed->rules().enabled(featureXRPFees)) - jvResult[jss::fee_ref] = Config::FEE_UNITS_DEPRECATED; + jvResult[jss::fee_ref] = FEE_UNITS_DEPRECATED; jvResult[jss::fee_base] = lpClosed->fees().base.jsonClipped(); jvResult[jss::reserve_base] = lpClosed->fees().reserve.jsonClipped(); jvResult[jss::reserve_inc] = lpClosed->fees().increment.jsonClipped(); diff --git a/src/xrpld/app/misc/SHAMapStore.h b/src/xrpld/app/misc/SHAMapStore.h index 67477593cb..b377538f62 100644 --- a/src/xrpld/app/misc/SHAMapStore.h +++ b/src/xrpld/app/misc/SHAMapStore.h @@ -1,7 +1,6 @@ #pragma once -#include - +#include #include #include diff --git a/src/xrpld/app/misc/detail/AccountTxPaging.cpp b/src/xrpld/app/misc/detail/AccountTxPaging.cpp index 4e79b53ed0..bb0a09426a 100644 --- a/src/xrpld/app/misc/detail/AccountTxPaging.cpp +++ b/src/xrpld/app/misc/detail/AccountTxPaging.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include diff --git a/src/xrpld/app/rdb/backend/detail/Node.cpp b/src/xrpld/app/rdb/backend/detail/Node.cpp index 317c4e77a1..b4f852a9e5 100644 --- a/src/xrpld/app/rdb/backend/detail/Node.cpp +++ b/src/xrpld/app/rdb/backend/detail/Node.cpp @@ -1,7 +1,7 @@ #include #include +#include #include -#include #include #include @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include diff --git a/src/xrpld/app/rdb/backend/detail/Node.h b/src/xrpld/app/rdb/backend/detail/Node.h index cb49a373bd..14eff07b94 100644 --- a/src/xrpld/app/rdb/backend/detail/Node.h +++ b/src/xrpld/app/rdb/backend/detail/Node.h @@ -1,8 +1,8 @@ #pragma once -#include #include +#include #include namespace xrpl { diff --git a/src/xrpld/consensus/Consensus.h b/src/xrpld/consensus/Consensus.h index 3c1e4e7dbf..2ed40cd2eb 100644 --- a/src/xrpld/consensus/Consensus.h +++ b/src/xrpld/consensus/Consensus.h @@ -4,12 +4,12 @@ #include #include #include -#include #include #include #include #include +#include #include #include diff --git a/src/xrpld/core/Config.h b/src/xrpld/core/Config.h index c40d13c83a..44509d2145 100644 --- a/src/xrpld/core/Config.h +++ b/src/xrpld/core/Config.h @@ -5,6 +5,7 @@ #include #include #include +#include #include // VFALCO Breaks levelization #include @@ -57,6 +58,13 @@ struct FeeSetup /* (Remember to update the example cfg files when changing any of these * values.) */ + + /** Convert to a Fees object for use with Ledger construction. */ + Fees + toFees() const + { + return Fees{reference_fee, account_reserve, owner_reserve}; + } }; // This entire derived class is deprecated. @@ -137,10 +145,6 @@ public: // Network parameters uint32_t NETWORK_ID = 0; - // DEPRECATED - Fee units for a reference transaction. - // Only provided for backwards compatibility in a couple of places - static constexpr std::uint32_t FEE_UNITS_DEPRECATED = 10; - // Note: The following parameters do not relate to the UNL or trust at all // Minimum number of nodes to consider the network present std::size_t NETWORK_QUORUM = 1; diff --git a/src/xrpld/app/paths/AccountCurrencies.cpp b/src/xrpld/rpc/detail/AccountCurrencies.cpp similarity index 97% rename from src/xrpld/app/paths/AccountCurrencies.cpp rename to src/xrpld/rpc/detail/AccountCurrencies.cpp index 92ba61e00e..c839b1475c 100644 --- a/src/xrpld/app/paths/AccountCurrencies.cpp +++ b/src/xrpld/rpc/detail/AccountCurrencies.cpp @@ -1,4 +1,4 @@ -#include +#include namespace xrpl { diff --git a/src/xrpld/app/paths/AccountCurrencies.h b/src/xrpld/rpc/detail/AccountCurrencies.h similarity index 89% rename from src/xrpld/app/paths/AccountCurrencies.h rename to src/xrpld/rpc/detail/AccountCurrencies.h index d8459de7f2..76c531cb9b 100644 --- a/src/xrpld/app/paths/AccountCurrencies.h +++ b/src/xrpld/rpc/detail/AccountCurrencies.h @@ -1,6 +1,6 @@ #pragma once -#include +#include #include diff --git a/src/xrpld/app/paths/PathRequest.cpp b/src/xrpld/rpc/detail/PathRequest.cpp similarity index 98% rename from src/xrpld/app/paths/PathRequest.cpp rename to src/xrpld/rpc/detail/PathRequest.cpp index 0e895e66d4..1161c1a449 100644 --- a/src/xrpld/app/paths/PathRequest.cpp +++ b/src/xrpld/rpc/detail/PathRequest.cpp @@ -1,9 +1,9 @@ #include -#include -#include -#include -#include #include +#include +#include +#include +#include #include #include @@ -24,7 +24,7 @@ PathRequest::PathRequest( Application& app, std::shared_ptr const& subscriber, int id, - PathRequests& owner, + PathRequestManager& owner, beast::Journal journal) : app_(app) , m_journal(journal) @@ -47,7 +47,7 @@ PathRequest::PathRequest( std::function const& completion, Resource::Consumer& consumer, int id, - PathRequests& owner, + PathRequestManager& owner, beast::Journal journal) : app_(app) , m_journal(journal) diff --git a/src/xrpld/app/paths/PathRequest.h b/src/xrpld/rpc/detail/PathRequest.h similarity index 94% rename from src/xrpld/app/paths/PathRequest.h rename to src/xrpld/rpc/detail/PathRequest.h index 0ffc6c6e2c..db173e307b 100644 --- a/src/xrpld/app/paths/PathRequest.h +++ b/src/xrpld/rpc/detail/PathRequest.h @@ -1,11 +1,11 @@ #pragma once -#include -#include -#include +#include +#include #include #include +#include #include #include @@ -20,7 +20,7 @@ namespace xrpl { // The request issuer must maintain a strong pointer class RippleLineCache; -class PathRequests; +class PathRequestManager; // Return values from parseJson <0 = invalid, >0 = valid #define PFR_PJ_INVALID -1 @@ -43,7 +43,7 @@ public: Application& app, std::shared_ptr const& subscriber, int id, - PathRequests&, + PathRequestManager&, beast::Journal journal); // ripple_path_find semantics @@ -53,7 +53,7 @@ public: std::function const& completion, Resource::Consumer& consumer, int id, - PathRequests&, + PathRequestManager&, beast::Journal journal); ~PathRequest(); @@ -119,7 +119,7 @@ private: std::recursive_mutex mLock; - PathRequests& mOwner; + PathRequestManager& mOwner; std::weak_ptr wpSubscriber; // Who this request came from std::function fCompletion; diff --git a/src/xrpld/app/paths/PathRequests.cpp b/src/xrpld/rpc/detail/PathRequestManager.cpp similarity index 95% rename from src/xrpld/app/paths/PathRequests.cpp rename to src/xrpld/rpc/detail/PathRequestManager.cpp index 61db1e58ef..8c42d3e83b 100644 --- a/src/xrpld/app/paths/PathRequests.cpp +++ b/src/xrpld/rpc/detail/PathRequestManager.cpp @@ -1,6 +1,6 @@ #include #include -#include +#include #include #include @@ -16,7 +16,7 @@ namespace xrpl { Get the correct ledger to use. */ std::shared_ptr -PathRequests::getLineCache(std::shared_ptr const& ledger, bool authoritative) +PathRequestManager::getLineCache(std::shared_ptr const& ledger, bool authoritative) { std::lock_guard sl(mLock); @@ -43,7 +43,7 @@ PathRequests::getLineCache(std::shared_ptr const& ledger, bool a } void -PathRequests::updateAll(std::shared_ptr const& inLedger) +PathRequestManager::updateAll(std::shared_ptr const& inLedger) { auto event = app_.getJobQueue().makeLoadEvent(jtPATH_FIND, "PathRequest::updateAll"); @@ -191,14 +191,14 @@ PathRequests::updateAll(std::shared_ptr const& inLedger) } bool -PathRequests::requestsPending() const +PathRequestManager::requestsPending() const { std::lock_guard sl(mLock); return !requests_.empty(); } void -PathRequests::insertPathRequest(PathRequest::pointer const& req) +PathRequestManager::insertPathRequest(PathRequest::pointer const& req) { std::lock_guard sl(mLock); @@ -216,7 +216,7 @@ PathRequests::insertPathRequest(PathRequest::pointer const& req) // Make a new-style path_find request Json::Value -PathRequests::makePathRequest( +PathRequestManager::makePathRequest( std::shared_ptr const& subscriber, std::shared_ptr const& inLedger, Json::Value const& requestJson) @@ -236,7 +236,7 @@ PathRequests::makePathRequest( // Make an old-style ripple_path_find request Json::Value -PathRequests::makeLegacyPathRequest( +PathRequestManager::makeLegacyPathRequest( PathRequest::pointer& req, std::function completion, Resource::Consumer& consumer, @@ -269,7 +269,7 @@ PathRequests::makeLegacyPathRequest( } Json::Value -PathRequests::doLegacyPathRequest( +PathRequestManager::doLegacyPathRequest( Resource::Consumer& consumer, std::shared_ptr const& inLedger, Json::Value const& request) diff --git a/src/xrpld/app/paths/PathRequests.h b/src/xrpld/rpc/detail/PathRequestManager.h similarity index 94% rename from src/xrpld/app/paths/PathRequests.h rename to src/xrpld/rpc/detail/PathRequestManager.h index 98f4be9fd7..0f884de5f3 100644 --- a/src/xrpld/app/paths/PathRequests.h +++ b/src/xrpld/rpc/detail/PathRequestManager.h @@ -1,8 +1,8 @@ #pragma once #include -#include -#include +#include +#include #include #include @@ -10,11 +10,11 @@ namespace xrpl { -class PathRequests +class PathRequestManager { public: /** A collection of all PathRequest instances. */ - PathRequests( + PathRequestManager( Application& app, beast::Journal journal, beast::insight::Collector::ptr const& collector) diff --git a/src/xrpld/app/paths/Pathfinder.cpp b/src/xrpld/rpc/detail/Pathfinder.cpp similarity index 99% rename from src/xrpld/app/paths/Pathfinder.cpp rename to src/xrpld/rpc/detail/Pathfinder.cpp index 10d69fc040..badec22c30 100644 --- a/src/xrpld/app/paths/Pathfinder.cpp +++ b/src/xrpld/rpc/detail/Pathfinder.cpp @@ -1,7 +1,7 @@ #include -#include -#include -#include +#include +#include +#include #include #include diff --git a/src/xrpld/app/paths/Pathfinder.h b/src/xrpld/rpc/detail/Pathfinder.h similarity index 98% rename from src/xrpld/app/paths/Pathfinder.h rename to src/xrpld/rpc/detail/Pathfinder.h index 03f2d6f038..5eaafd3370 100644 --- a/src/xrpld/app/paths/Pathfinder.h +++ b/src/xrpld/rpc/detail/Pathfinder.h @@ -1,10 +1,10 @@ #pragma once -#include -#include +#include #include #include +#include #include #include diff --git a/src/xrpld/app/paths/detail/PathfinderUtils.h b/src/xrpld/rpc/detail/PathfinderUtils.h similarity index 100% rename from src/xrpld/app/paths/detail/PathfinderUtils.h rename to src/xrpld/rpc/detail/PathfinderUtils.h diff --git a/src/xrpld/rpc/detail/RPCHelpers.cpp b/src/xrpld/rpc/detail/RPCHelpers.cpp index dd363c6d76..b4a0685bd6 100644 --- a/src/xrpld/rpc/detail/RPCHelpers.cpp +++ b/src/xrpld/rpc/detail/RPCHelpers.cpp @@ -1,8 +1,8 @@ #include -#include #include #include #include +#include #include #include diff --git a/src/xrpld/rpc/detail/RPCLedgerHelpers.h b/src/xrpld/rpc/detail/RPCLedgerHelpers.h index c60b7bc6b2..6a04ab41d6 100644 --- a/src/xrpld/rpc/detail/RPCLedgerHelpers.h +++ b/src/xrpld/rpc/detail/RPCLedgerHelpers.h @@ -1,11 +1,11 @@ #pragma once -#include #include #include #include #include +#include #include #include #include diff --git a/src/xrpld/app/paths/RippleLineCache.cpp b/src/xrpld/rpc/detail/RippleLineCache.cpp similarity index 98% rename from src/xrpld/app/paths/RippleLineCache.cpp rename to src/xrpld/rpc/detail/RippleLineCache.cpp index c45c20aca8..d6ed7b1478 100644 --- a/src/xrpld/app/paths/RippleLineCache.cpp +++ b/src/xrpld/rpc/detail/RippleLineCache.cpp @@ -1,5 +1,5 @@ -#include -#include +#include +#include namespace xrpl { diff --git a/src/xrpld/app/paths/RippleLineCache.h b/src/xrpld/rpc/detail/RippleLineCache.h similarity index 97% rename from src/xrpld/app/paths/RippleLineCache.h rename to src/xrpld/rpc/detail/RippleLineCache.h index c4ddad6c81..65607f2d25 100644 --- a/src/xrpld/app/paths/RippleLineCache.h +++ b/src/xrpld/rpc/detail/RippleLineCache.h @@ -1,10 +1,10 @@ #pragma once -#include -#include +#include #include #include +#include #include #include diff --git a/src/xrpld/rpc/detail/TransactionSign.cpp b/src/xrpld/rpc/detail/TransactionSign.cpp index 73385f62ef..027a74f2c3 100644 --- a/src/xrpld/rpc/detail/TransactionSign.cpp +++ b/src/xrpld/rpc/detail/TransactionSign.cpp @@ -3,8 +3,8 @@ #include #include #include -#include #include +#include #include #include diff --git a/src/xrpld/app/paths/TrustLine.cpp b/src/xrpld/rpc/detail/TrustLine.cpp similarity index 98% rename from src/xrpld/app/paths/TrustLine.cpp rename to src/xrpld/rpc/detail/TrustLine.cpp index 963e1402be..c2bc152448 100644 --- a/src/xrpld/app/paths/TrustLine.cpp +++ b/src/xrpld/rpc/detail/TrustLine.cpp @@ -1,4 +1,4 @@ -#include +#include #include #include diff --git a/src/xrpld/app/paths/TrustLine.h b/src/xrpld/rpc/detail/TrustLine.h similarity index 100% rename from src/xrpld/app/paths/TrustLine.h rename to src/xrpld/rpc/detail/TrustLine.h diff --git a/src/xrpld/rpc/handlers/AccountCurrenciesHandler.cpp b/src/xrpld/rpc/handlers/AccountCurrenciesHandler.cpp index 2ec1e20875..fe74c915f5 100644 --- a/src/xrpld/rpc/handlers/AccountCurrenciesHandler.cpp +++ b/src/xrpld/rpc/handlers/AccountCurrenciesHandler.cpp @@ -1,6 +1,6 @@ -#include #include #include +#include #include #include diff --git a/src/xrpld/rpc/handlers/AccountLines.cpp b/src/xrpld/rpc/handlers/AccountLines.cpp index b3b93c0eb1..396a09b082 100644 --- a/src/xrpld/rpc/handlers/AccountLines.cpp +++ b/src/xrpld/rpc/handlers/AccountLines.cpp @@ -1,7 +1,7 @@ -#include #include #include #include +#include #include #include diff --git a/src/xrpld/rpc/handlers/GatewayBalances.cpp b/src/xrpld/rpc/handlers/GatewayBalances.cpp index f7acbc77e6..914725de60 100644 --- a/src/xrpld/rpc/handlers/GatewayBalances.cpp +++ b/src/xrpld/rpc/handlers/GatewayBalances.cpp @@ -1,7 +1,7 @@ #include -#include #include #include +#include #include #include diff --git a/src/xrpld/rpc/handlers/NoRippleCheck.cpp b/src/xrpld/rpc/handlers/NoRippleCheck.cpp index a0f797214d..7b780f3b16 100644 --- a/src/xrpld/rpc/handlers/NoRippleCheck.cpp +++ b/src/xrpld/rpc/handlers/NoRippleCheck.cpp @@ -1,8 +1,8 @@ #include -#include #include #include #include +#include #include #include diff --git a/src/xrpld/rpc/handlers/PathFind.cpp b/src/xrpld/rpc/handlers/PathFind.cpp index 357cd9b91e..1b180167ea 100644 --- a/src/xrpld/rpc/handlers/PathFind.cpp +++ b/src/xrpld/rpc/handlers/PathFind.cpp @@ -1,7 +1,7 @@ #include #include -#include #include +#include #include #include @@ -34,7 +34,7 @@ doPathFind(RPC::JsonContext& context) { context.loadType = Resource::feeHeavyBurdenRPC; context.infoSub->clearRequest(); - return context.app.getPathRequests().makePathRequest( + return context.app.getPathRequestManager().makePathRequest( context.infoSub, lpLedger, context.params); } diff --git a/src/xrpld/rpc/handlers/RipplePathFind.cpp b/src/xrpld/rpc/handlers/RipplePathFind.cpp index 5f73165287..cc695908fb 100644 --- a/src/xrpld/rpc/handlers/RipplePathFind.cpp +++ b/src/xrpld/rpc/handlers/RipplePathFind.cpp @@ -1,7 +1,7 @@ #include -#include #include #include +#include #include #include @@ -105,7 +105,7 @@ doRipplePathFind(RPC::JsonContext& context) // JobQueue before letting the thread continue. // // May 2017 - jvResult = context.app.getPathRequests().makeLegacyPathRequest( + jvResult = context.app.getPathRequestManager().makeLegacyPathRequest( request, [&context]() { // Copying the shared_ptr keeps the coroutine alive up @@ -144,7 +144,7 @@ doRipplePathFind(RPC::JsonContext& context) if (!lpf.isOk()) return rpcError(rpcTOO_BUSY); - auto result = context.app.getPathRequests().doLegacyPathRequest( + auto result = context.app.getPathRequestManager().doLegacyPathRequest( context.consumer, lpLedger, context.params); for (auto& fieldName : jvResult.getMemberNames()) From 85b65c8e9a8ef94a61334476724fc88eaadbddbf Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Wed, 25 Mar 2026 18:22:50 +0000 Subject: [PATCH 19/53] chore: Update sqlite3->3.51.0, protobuf->6.33.5, openssl->3.6.1, grpc->1.78.1 (#6653) --- conan.lock | 15 +++++++-------- conanfile.py | 21 ++++++++------------- 2 files changed, 15 insertions(+), 21 deletions(-) diff --git a/conan.lock b/conan.lock index d2126956fe..575be2e071 100644 --- a/conan.lock +++ b/conan.lock @@ -3,14 +3,14 @@ "requires": [ "zlib/1.3.1#cac0f6daea041b0ccf42934163defb20%1774439233.809", "xxhash/0.8.3#681d36a0a6111fc56e5e45ea182c19cc%1765850149.987", - "sqlite3/3.49.1#8631739a4c9b93bd3d6b753bac548a63%1765850149.926", + "sqlite3/3.51.0#66aa11eabd0e34954c5c1c061ad44abe%1763899256.358", "soci/4.0.3#fe32b9ad5eb47e79ab9e45a68f363945%1774450067.231", "snappy/1.1.10#968fef506ff261592ec30c574d4a7809%1765850147.878", "secp256k1/0.7.1#481881709eb0bdd0185a12b912bbe8ad%1770910500.329", "rocksdb/10.5.1#4a197eca381a3e5ae8adf8cffa5aacd0%1765850186.86", "re2/20251105#8579cfd0bda4daf0683f9e3898f964b4%1774398111.888", - "protobuf/6.32.1#b54f00da2e0f61d821330b5b638b0f80%1774439406.061", - "openssl/3.5.5#e6399de266349245a4542fc5f6c71552%1774367199.56", + "protobuf/6.33.5#d96d52ba5baaaa532f47bda866ad87a5%1773224203.27", + "openssl/3.6.1#e6399de266349245a4542fc5f6c71552%1774458290.139", "nudb/2.0.9#0432758a24204da08fee953ec9ea03cb%1769436073.32", "lz4/1.10.0#59fc63cac7f10fbe8e05c7e62c2f3504%1765850143.914", "libiconv/1.17#1e65319e945f2d31941a9d28cc13c058%1765842973.492", @@ -18,7 +18,7 @@ "libarchive/3.8.1#ffee18995c706e02bf96e7a2f7042e0d%1765850144.736", "jemalloc/5.3.0#e951da9cf599e956cebc117880d2d9f8%1729241615.244", "gtest/1.17.0#5224b3b3ff3b4ce1133cbdd27d53ee7d%1768312129.152", - "grpc/1.72.0#aaade9421980b2d926dbfb613d56c38a%1774376249.106", + "grpc/1.78.1#b1a9e74b145cc471bed4dc64dc6eb2c1%1772623605.068", "ed25519/2015.03#ae761bdc52730a843f0809bdf6c1b1f6%1765850143.772", "date/3.0.4#862e11e80030356b53c2c38599ceb32b%1765850143.772", "c-ares/1.34.6#545240bb1c40e2cacd4362d6b8967650%1774439234.681", @@ -29,12 +29,11 @@ "build_requires": [ "zlib/1.3.1#cac0f6daea041b0ccf42934163defb20%1774439233.809", "strawberryperl/5.32.1.1#8d114504d172cfea8ea1662d09b6333e%1774447376.964", - "protobuf/6.32.1#b54f00da2e0f61d821330b5b638b0f80%1774439406.061", + "protobuf/6.33.5#d96d52ba5baaaa532f47bda866ad87a5%1773224203.27", "nasm/2.16.01#31e26f2ee3c4346ecd347911bd126904%1765850144.707", "msys2/cci.latest#d22fe7b2808f5fd34d0a7923ace9c54f%1770657326.649", "m4/1.4.19#5d7a4994e5875d76faf7acf3ed056036%1774365463.87", "cmake/4.3.0#b939a42e98f593fb34d3a8c5cc860359%1774439249.183", - "cmake/3.31.11#f325c933f618a1fcebc1e1c0babfd1ba%1774439246.719", "b2/5.4.2#ffd6084a119587e70f11cd45d1a386e2%1774439233.447", "automake/1.16.5#b91b7c384c3deaa9d535be02da14d04f%1755524470.56", "autoconf/2.71#51077f068e61700d65bb05541ea1e4b0%1731054366.86", @@ -47,13 +46,13 @@ "boost/1.90.0" ], "protobuf/[>=5.27.0 <7]": [ - "protobuf/6.32.1" + "protobuf/6.33.5" ], "lz4/1.9.4": [ "lz4/1.10.0" ], "sqlite3/[>=3.44 <4]": [ - "sqlite3/3.49.1" + "sqlite3/3.51.0" ], "boost/1.83.0": [ "boost/1.90.0" diff --git a/conanfile.py b/conanfile.py index 0bed2af80f..4949516bfe 100644 --- a/conanfile.py +++ b/conanfile.py @@ -4,7 +4,6 @@ import re from conan.tools.cmake import CMake, CMakeToolchain, cmake_layout from conan import ConanFile -from conan import __version__ as conan_version class Xrpl(ConanFile): @@ -30,10 +29,10 @@ class Xrpl(ConanFile): requires = [ "ed25519/2015.03", - "grpc/1.72.0", + "grpc/1.78.1", "libarchive/3.8.1", "nudb/2.0.9", - "openssl/3.5.5", + "openssl/3.6.1", "secp256k1/0.7.1", "soci/4.0.3", "zlib/1.3.1", @@ -44,7 +43,7 @@ class Xrpl(ConanFile): ] tool_requires = [ - "protobuf/6.32.1", + "protobuf/6.33.5", ] default_options = { @@ -137,20 +136,16 @@ class Xrpl(ConanFile): self.default_options["fPIC"] = False def requirements(self): - # Conan 2 requires transitive headers to be specified - transitive_headers_opt = ( - {"transitive_headers": True} if conan_version.split(".")[0] == "2" else {} - ) - self.requires("boost/1.90.0", force=True, **transitive_headers_opt) - self.requires("date/3.0.4", **transitive_headers_opt) + self.requires("boost/1.90.0", force=True, transitive_headers=True) + self.requires("date/3.0.4", transitive_headers=True) self.requires("lz4/1.10.0", force=True) - self.requires("protobuf/6.32.1", force=True) - self.requires("sqlite3/3.49.1", force=True) + self.requires("protobuf/6.33.5", force=True) + self.requires("sqlite3/3.51.0", force=True) if self.options.jemalloc: self.requires("jemalloc/5.3.0") if self.options.rocksdb: self.requires("rocksdb/10.5.1") - self.requires("xxhash/0.8.3", **transitive_headers_opt) + self.requires("xxhash/0.8.3", transitive_headers=True) exports_sources = ( "CMakeLists.txt", From b9d07730f35da11da2bbcb4dc68c468a4995adec Mon Sep 17 00:00:00 2001 From: Vito Tumas <5780819+Tapanito@users.noreply.github.com> Date: Thu, 26 Mar 2026 00:54:33 +0100 Subject: [PATCH 20/53] feat: Add placeholder amendment for assorted bug fixes (#6652) --- 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 a40d524c70..d8d9dc0117 100644 --- a/include/xrpl/protocol/detail/features.macro +++ b/include/xrpl/protocol/detail/features.macro @@ -16,6 +16,7 @@ // Add new amendments to the top of this list. // Keep it sorted in reverse chronological order. +XRPL_FIX (Security3_1_3, Supported::no, VoteBehavior::DefaultNo) XRPL_FIX (PermissionedDomainInvariant, Supported::yes, VoteBehavior::DefaultNo) XRPL_FIX (ExpiredNFTokenOfferRemoval, Supported::yes, VoteBehavior::DefaultNo) XRPL_FIX (BatchInnerSigs, Supported::no, VoteBehavior::DefaultNo) From 15fd9feae55bd2cf1f78e52382a3aab696346e16 Mon Sep 17 00:00:00 2001 From: Jingchen Date: Wed, 25 Mar 2026 23:54:49 +0000 Subject: [PATCH 21/53] chore: Show warning message if user may need to connect to VPN (#6619) Signed-off-by: JCW --- cmake/XrplProtocolAutogen.cmake | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/cmake/XrplProtocolAutogen.cmake b/cmake/XrplProtocolAutogen.cmake index 44857712cd..e48d28959d 100644 --- a/cmake/XrplProtocolAutogen.cmake +++ b/cmake/XrplProtocolAutogen.cmake @@ -140,6 +140,28 @@ function(setup_protocol_autogen) ) endif() + # Check pip index URL configuration + execute_process( + COMMAND ${VENV_PIP} config get global.index-url + OUTPUT_VARIABLE PIP_INDEX_URL + OUTPUT_STRIP_TRAILING_WHITESPACE + ERROR_QUIET + ) + + # Default PyPI URL + set(DEFAULT_PIP_INDEX "https://pypi.org/simple") + + # Show warning if using non-default index + if(PIP_INDEX_URL AND NOT PIP_INDEX_URL STREQUAL "") + if(NOT PIP_INDEX_URL STREQUAL DEFAULT_PIP_INDEX) + message( + WARNING + "Private pip index URL detected: ${PIP_INDEX_URL}\n" + "You may need to connect to VPN to access this URL." + ) + endif() + endif() + message(STATUS "Installing Python dependencies...") execute_process( COMMAND ${VENV_PIP} install --upgrade pip From a9269fa8463851ce85097386edc1052a326cc0c0 Mon Sep 17 00:00:00 2001 From: Mayukha Vadari Date: Wed, 25 Mar 2026 16:55:50 -0700 Subject: [PATCH 22/53] chore: Add more AI tools to .gitignore (#6658) Co-authored-by: xrplf-ai-reviewer[bot] <266832837+xrplf-ai-reviewer[bot]@users.noreply.github.com> --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index 643f0d25dc..7ee6d0c70a 100644 --- a/.gitignore +++ b/.gitignore @@ -71,6 +71,8 @@ DerivedData /.zed/ # AI tools. +/.agent +/.agents /.augment /.claude /CLAUDE.md From 2c765f6eb090866a5225257b2fd374ee6f652460 Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Thu, 26 Mar 2026 00:18:17 +0000 Subject: [PATCH 23/53] ci: Add conflicting-pr workflow (#6656) Co-authored-by: Bart --- .github/workflows/conflicting-pr.yml | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 .github/workflows/conflicting-pr.yml diff --git a/.github/workflows/conflicting-pr.yml b/.github/workflows/conflicting-pr.yml new file mode 100644 index 0000000000..6e667632a0 --- /dev/null +++ b/.github/workflows/conflicting-pr.yml @@ -0,0 +1,25 @@ +name: Label PRs with merge conflicts + +on: + # So that PRs touching the same files as the push are updated. + push: + # So that the `dirtyLabel` is removed if conflicts are resolved. + # We recommend `pull_request_target` so that github secrets are available. + # In `pull_request` we wouldn't be able to change labels of fork PRs. + pull_request_target: + types: [synchronize] + +permissions: + pull-requests: write + +jobs: + main: + runs-on: ubuntu-latest + steps: + - name: Check if PRs are dirty + uses: eps1lon/actions-label-merge-conflict@1df065ebe6e3310545d4f4c4e862e43bdca146f0 # v3.0.3 + with: + dirtyLabel: "PR: has conflicts" + repoToken: "${{ secrets.GITHUB_TOKEN }}" + commentOnDirty: "This PR has conflicts, please resolve them in order for the PR to be reviewed." + commentOnClean: "All conflicts have been resolved. Assigned reviewers can now start or resume their review." From e8bdbf975a108f56670d7823747d80ce3cfb1150 Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Thu, 26 Mar 2026 12:37:37 +0000 Subject: [PATCH 24/53] ci: Upload artifacts only in public repositories (#6670) --- .github/workflows/reusable-build-test-config.yml | 2 +- .github/workflows/reusable-clang-tidy-files.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/reusable-build-test-config.yml b/.github/workflows/reusable-build-test-config.yml index 1cc768f9fa..85a033766e 100644 --- a/.github/workflows/reusable-build-test-config.yml +++ b/.github/workflows/reusable-build-test-config.yml @@ -199,7 +199,7 @@ jobs: fi - name: Upload the binary (Linux) - if: ${{ github.repository == 'XRPLF/rippled' && runner.os == 'Linux' }} + if: ${{ github.event.repository.visibility == 'public' && runner.os == 'Linux' }} uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 with: name: xrpld-${{ inputs.config_name }} diff --git a/.github/workflows/reusable-clang-tidy-files.yml b/.github/workflows/reusable-clang-tidy-files.yml index 5d3230f7d1..2abc9de43b 100644 --- a/.github/workflows/reusable-clang-tidy-files.yml +++ b/.github/workflows/reusable-clang-tidy-files.yml @@ -83,7 +83,7 @@ jobs: run-clang-tidy -j ${{ steps.nproc.outputs.nproc }} -p "${BUILD_DIR}" ${TARGETS} 2>&1 | tee clang-tidy-output.txt - name: Upload clang-tidy output - if: steps.run_clang_tidy.outcome != 'success' + if: ${{ github.event.repository.visibility == 'public' && steps.run_clang_tidy.outcome != 'success' }} uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 with: name: clang-tidy-results From 76e3b4fb0f89d432958414cde29fd26d0c3dccae Mon Sep 17 00:00:00 2001 From: Vito Tumas <5780819+Tapanito@users.noreply.github.com> Date: Thu, 26 Mar 2026 13:40:26 +0100 Subject: [PATCH 25/53] fix: Improve loan invariant message (#6668) --- src/libxrpl/tx/invariants/LoanInvariant.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/libxrpl/tx/invariants/LoanInvariant.cpp b/src/libxrpl/tx/invariants/LoanInvariant.cpp index c0ce320846..b590eab8fd 100644 --- a/src/libxrpl/tx/invariants/LoanInvariant.cpp +++ b/src/libxrpl/tx/invariants/LoanInvariant.cpp @@ -236,8 +236,7 @@ ValidLoan::finalize( after->at(sfPrincipalOutstanding) == beast::zero && after->at(sfManagementFeeOutstanding) == beast::zero) { - JLOG(j.fatal()) << "Invariant failed: Loan with zero payments " - "remaining has not been paid off"; + JLOG(j.fatal()) << "Invariant failed: Fully paid off Loan still has payments remaining"; return false; } if (before && (before->isFlag(lsfLoanOverpayment) != after->isFlag(lsfLoanOverpayment))) From faf69da4b0ae126648567b3436df50ff45d7abcc Mon Sep 17 00:00:00 2001 From: Valentin Balaschenko <13349202+vlntb@users.noreply.github.com> Date: Thu, 26 Mar 2026 14:10:51 +0000 Subject: [PATCH 26/53] chore: Shorten job names to stay within Linux 15-char thread limit (#6669) --- src/xrpld/app/ledger/OrderBookDBImpl.cpp | 2 +- src/xrpld/app/ledger/detail/LedgerPersistence.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/xrpld/app/ledger/OrderBookDBImpl.cpp b/src/xrpld/app/ledger/OrderBookDBImpl.cpp index 2691935911..f7e531f78a 100644 --- a/src/xrpld/app/ledger/OrderBookDBImpl.cpp +++ b/src/xrpld/app/ledger/OrderBookDBImpl.cpp @@ -58,7 +58,7 @@ OrderBookDBImpl::setup(std::shared_ptr const& ledger) else { registry_.getJobQueue().addJob( - jtUPDATE_PF, "OrderBookUpd" + std::to_string(ledger->seq()), [this, ledger]() { + jtUPDATE_PF, "OBUpd" + std::to_string(ledger->seq()), [this, ledger]() { update(ledger); }); } diff --git a/src/xrpld/app/ledger/detail/LedgerPersistence.cpp b/src/xrpld/app/ledger/detail/LedgerPersistence.cpp index 6ca8e3cd1b..651af1eec6 100644 --- a/src/xrpld/app/ledger/detail/LedgerPersistence.cpp +++ b/src/xrpld/app/ledger/detail/LedgerPersistence.cpp @@ -72,7 +72,7 @@ pendSaveValidated( if (!isSynchronous && registry.getJobQueue().addJob( isCurrent ? jtPUBLEDGER : jtPUBOLDLEDGER, - std::to_string(ledger->seq()), + "Pub" + std::to_string(ledger->seq()), [®istry, ledger, isCurrent]() { saveValidatedLedger(registry, ledger, isCurrent); })) { return true; From addc1e8e25020ee297e93c366a6147d06af18ec3 Mon Sep 17 00:00:00 2001 From: Jingchen Date: Thu, 26 Mar 2026 14:11:16 +0000 Subject: [PATCH 27/53] refactor: Make function naming in ServiceRegistry consistent (#6390) Signed-off-by: JCW Co-authored-by: Ed Hennis --- .../scripts/levelization/results/ordering.txt | 2 +- include/xrpl/core/ServiceRegistry.h | 47 ++++-- include/xrpl/rdb/DatabaseCon.h | 9 +- include/xrpl/rdb/SociDB.h | 4 +- include/xrpl/tx/paths/RippleCalc.h | 4 +- src/libxrpl/rdb/DatabaseCon.cpp | 13 +- src/libxrpl/rdb/SociDB.cpp | 11 +- src/libxrpl/tx/Transactor.cpp | 22 ++- src/libxrpl/tx/paths/RippleCalc.cpp | 5 +- .../tx/transactors/account/SignerListSet.cpp | 5 +- .../tx/transactors/check/CheckCancel.cpp | 3 +- .../tx/transactors/check/CheckCash.cpp | 3 +- .../tx/transactors/check/CheckCreate.cpp | 3 +- .../tx/transactors/dex/OfferCancel.cpp | 3 +- .../tx/transactors/dex/OfferCreate.cpp | 4 +- .../tx/transactors/payment/Payment.cpp | 3 +- .../payment_channel/PaymentChannelClaim.cpp | 5 +- .../payment_channel/PaymentChannelFund.cpp | 2 +- .../tx/transactors/system/TicketCreate.cpp | 3 +- src/libxrpl/tx/transactors/token/TrustSet.cpp | 3 +- src/test/app/AMMExtended_test.cpp | 4 +- src/test/app/AccountSet_test.cpp | 4 +- src/test/app/Batch_test.cpp | 6 +- src/test/app/EscrowToken_test.cpp | 4 +- src/test/app/FeeVote_test.cpp | 36 ++-- src/test/app/Flow_test.cpp | 4 +- src/test/app/LedgerReplay_test.cpp | 6 +- src/test/app/NFTokenAuth_test.cpp | 8 +- src/test/app/NFToken_test.cpp | 2 +- src/test/app/PayStrand_test.cpp | 20 +-- src/test/app/PseudoTx_test.cpp | 2 +- src/test/app/RCLValidations_test.cpp | 6 +- src/test/app/Regression_test.cpp | 4 +- src/test/app/SHAMapStore_test.cpp | 4 +- src/test/app/TxQ_test.cpp | 6 +- src/test/app/ValidatorKeys_test.cpp | 2 +- src/test/app/ValidatorList_test.cpp | 142 ++++++++-------- src/test/app/ValidatorSite_test.cpp | 2 +- src/test/app/Vault_test.cpp | 33 ++-- src/test/basics/PerfLog_test.cpp | 2 +- src/test/consensus/NegativeUNL_test.cpp | 30 ++-- src/test/core/ClosureCounter_test.cpp | 2 +- src/test/jtx/Env.h | 4 +- src/test/jtx/impl/AMM.cpp | 2 +- src/test/jtx/impl/Env.cpp | 6 +- src/test/jtx/impl/directory.cpp | 2 +- src/test/jtx/impl/paths.cpp | 2 +- src/test/ledger/PaymentSandbox_test.cpp | 2 +- src/test/ledger/SkipList_test.cpp | 2 +- src/test/ledger/View_test.cpp | 23 +-- src/test/overlay/TMGetObjectByHash_test.cpp | 2 +- src/test/overlay/reduce_relay_test.cpp | 11 +- src/test/overlay/tx_reduce_relay_test.cpp | 4 +- src/test/rpc/LedgerEntry_test.cpp | 4 +- src/test/rpc/Peers_test.cpp | 2 +- src/test/rpc/ValidatorRPC_test.cpp | 28 +-- src/xrpld/app/consensus/RCLConsensus.cpp | 44 ++--- src/xrpld/app/consensus/RCLValidations.cpp | 7 +- src/xrpld/app/ledger/ConsensusTransSetSF.cpp | 3 +- src/xrpld/app/ledger/LedgerHistory.cpp | 7 +- src/xrpld/app/ledger/OrderBookDBImpl.cpp | 3 +- src/xrpld/app/ledger/detail/InboundLedger.cpp | 7 +- .../app/ledger/detail/InboundLedgers.cpp | 3 +- .../app/ledger/detail/InboundTransactions.cpp | 3 +- src/xrpld/app/ledger/detail/LedgerCleaner.cpp | 2 +- .../app/ledger/detail/LedgerDeltaAcquire.cpp | 2 +- src/xrpld/app/ledger/detail/LedgerMaster.cpp | 52 +++--- .../app/ledger/detail/LedgerPersistence.cpp | 27 +-- .../ledger/detail/LedgerReplayMsgHandler.cpp | 2 +- .../app/ledger/detail/LedgerReplayTask.cpp | 2 +- .../app/ledger/detail/LedgerReplayer.cpp | 2 +- src/xrpld/app/ledger/detail/OpenLedger.cpp | 4 +- .../app/ledger/detail/SkipListAcquire.cpp | 2 +- .../app/ledger/detail/TransactionAcquire.cpp | 2 +- .../app/ledger/detail/TransactionMaster.cpp | 2 +- src/xrpld/app/main/Application.cpp | 48 +++--- src/xrpld/app/main/GRPCServer.cpp | 9 +- src/xrpld/app/main/Main.cpp | 4 +- src/xrpld/app/misc/NetworkOPs.cpp | 159 +++++++++--------- src/xrpld/app/misc/SHAMapStoreImp.cpp | 6 +- src/xrpld/app/misc/detail/Transaction.cpp | 2 +- src/xrpld/app/misc/detail/TxQ.cpp | 2 +- src/xrpld/app/misc/detail/ValidatorSite.cpp | 15 +- src/xrpld/app/rdb/backend/detail/Node.cpp | 6 +- .../app/rdb/backend/detail/SQLiteDatabase.cpp | 32 ++-- src/xrpld/overlay/Slot.h | 8 +- src/xrpld/overlay/detail/ConnectAttempt.cpp | 2 +- src/xrpld/overlay/detail/Handshake.cpp | 4 +- src/xrpld/overlay/detail/OverlayImpl.cpp | 29 ++-- src/xrpld/overlay/detail/PeerImp.cpp | 46 ++--- src/xrpld/overlay/detail/PeerImp.h | 7 +- src/xrpld/overlay/detail/PeerSet.cpp | 8 +- src/xrpld/rpc/RPCCall.h | 2 +- src/xrpld/rpc/RPCSub.h | 3 +- src/xrpld/rpc/detail/PathRequest.cpp | 5 +- src/xrpld/rpc/detail/PathRequestManager.cpp | 5 +- src/xrpld/rpc/detail/Pathfinder.cpp | 9 +- src/xrpld/rpc/detail/RPCLedgerHelpers.cpp | 2 +- src/xrpld/rpc/detail/RPCSub.cpp | 10 +- src/xrpld/rpc/detail/ServerHandler.cpp | 17 +- src/xrpld/rpc/detail/TransactionSign.cpp | 35 ++-- src/xrpld/rpc/handlers/Connect.cpp | 2 +- src/xrpld/rpc/handlers/DoManifest.cpp | 10 +- src/xrpld/rpc/handlers/GetCounts.cpp | 2 +- src/xrpld/rpc/handlers/LogLevel.cpp | 10 +- src/xrpld/rpc/handlers/LogRotate.cpp | 2 +- src/xrpld/rpc/handlers/Peers.cpp | 6 +- src/xrpld/rpc/handlers/Reservations.cpp | 8 +- src/xrpld/rpc/handlers/Simulate.cpp | 6 +- src/xrpld/rpc/handlers/Subscribe.cpp | 3 +- src/xrpld/rpc/handlers/TxReduceRelay.cpp | 2 +- src/xrpld/rpc/handlers/UnlList.cpp | 2 +- src/xrpld/rpc/handlers/ValidatorInfo.cpp | 8 +- src/xrpld/rpc/handlers/ValidatorListSites.cpp | 2 +- src/xrpld/rpc/handlers/Validators.cpp | 2 +- src/xrpld/shamap/NodeFamily.cpp | 4 +- 116 files changed, 664 insertions(+), 633 deletions(-) diff --git a/.github/scripts/levelization/results/ordering.txt b/.github/scripts/levelization/results/ordering.txt index de12bf424b..38e77dedf8 100644 --- a/.github/scripts/levelization/results/ordering.txt +++ b/.github/scripts/levelization/results/ordering.txt @@ -21,6 +21,7 @@ libxrpl.protocol > xrpl.json libxrpl.protocol > xrpl.protocol libxrpl.protocol_autogen > xrpl.protocol_autogen libxrpl.rdb > xrpl.basics +libxrpl.rdb > xrpl.core libxrpl.rdb > xrpl.rdb libxrpl.resource > xrpl.basics libxrpl.resource > xrpl.json @@ -184,7 +185,6 @@ xrpl.conditions > xrpl.basics xrpl.conditions > xrpl.protocol xrpl.core > xrpl.basics xrpl.core > xrpl.json -xrpl.core > xrpl.ledger xrpl.core > xrpl.protocol xrpl.json > xrpl.basics xrpl.ledger > xrpl.basics diff --git a/include/xrpl/core/ServiceRegistry.h b/include/xrpl/core/ServiceRegistry.h index bff475c461..9f2555dc34 100644 --- a/include/xrpl/core/ServiceRegistry.h +++ b/include/xrpl/core/ServiceRegistry.h @@ -3,7 +3,6 @@ #include #include #include -#include #include @@ -23,6 +22,20 @@ class PerfLog; // This is temporary until we migrate all code to use ServiceRegistry. class Application; +template < + class Key, + class T, + bool IsKeyCache, + class SharedWeakUnionPointer, + class SharedPointerType, + class Hash, + class KeyEqual, + class Mutex> +class TaggedCache; +class STLedgerEntry; +using SLE = STLedgerEntry; +using CachedSLEs = TaggedCache; + // Forward declarations class AcceptedLedger; class AmendmentTable; @@ -89,7 +102,7 @@ public: getNodeFamily() = 0; virtual TimeKeeper& - timeKeeper() = 0; + getTimeKeeper() = 0; virtual JobQueue& getJobQueue() = 0; @@ -98,7 +111,7 @@ public: getTempNodeCache() = 0; virtual CachedSLEs& - cachedSLEs() = 0; + getCachedSLEs() = 0; virtual NetworkIDService& getNetworkIDService() = 0; @@ -120,26 +133,26 @@ public: getValidations() = 0; virtual ValidatorList& - validators() = 0; + getValidators() = 0; virtual ValidatorSite& - validatorSites() = 0; + getValidatorSites() = 0; virtual ManifestCache& - validatorManifests() = 0; + getValidatorManifests() = 0; virtual ManifestCache& - publisherManifests() = 0; + getPublisherManifests() = 0; // Network services virtual Overlay& - overlay() = 0; + getOverlay() = 0; virtual Cluster& - cluster() = 0; + getCluster() = 0; virtual PeerReservationTable& - peerReservations() = 0; + getPeerReservations() = 0; virtual Resource::Manager& getResourceManager() = 0; @@ -174,13 +187,13 @@ public: getLedgerReplayer() = 0; virtual PendingSaves& - pendingSaves() = 0; + getPendingSaves() = 0; virtual OpenLedger& - openLedger() = 0; + getOpenLedger() = 0; virtual OpenLedger const& - openLedger() const = 0; + getOpenLedger() const = 0; // Transaction and operation services virtual NetworkOPs& @@ -210,16 +223,16 @@ public: isStopping() const = 0; virtual beast::Journal - journal(std::string const& name) = 0; + getJournal(std::string const& name) = 0; virtual boost::asio::io_context& getIOContext() = 0; virtual Logs& - logs() = 0; + getLogs() = 0; virtual std::optional const& - trapTxID() const = 0; + getTrapTxID() const = 0; /** Retrieve the "wallet database" */ virtual DatabaseCon& @@ -228,7 +241,7 @@ public: // Temporary: Get the underlying Application for functions that haven't // been migrated yet. This should be removed once all code is migrated. virtual Application& - app() = 0; + getApp() = 0; }; } // namespace xrpl diff --git a/include/xrpl/rdb/DatabaseCon.h b/include/xrpl/rdb/DatabaseCon.h index d1fb7114e3..b7231f4859 100644 --- a/include/xrpl/rdb/DatabaseCon.h +++ b/include/xrpl/rdb/DatabaseCon.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include #include @@ -94,7 +95,7 @@ public: struct CheckpointerSetup { JobQueue* jobQueue; - Logs* logs; + std::reference_wrapper registry; }; template @@ -129,7 +130,7 @@ public: beast::Journal journal) : DatabaseCon(setup, dbName, pragma, initSQL, journal) { - setupCheckpointing(checkpointerSetup.jobQueue, *checkpointerSetup.logs); + setupCheckpointing(checkpointerSetup.jobQueue, checkpointerSetup.registry.get()); } template @@ -154,7 +155,7 @@ public: beast::Journal journal) : DatabaseCon(dataDir, dbName, pragma, initSQL, journal) { - setupCheckpointing(checkpointerSetup.jobQueue, *checkpointerSetup.logs); + setupCheckpointing(checkpointerSetup.jobQueue, checkpointerSetup.registry.get()); } ~DatabaseCon(); @@ -177,7 +178,7 @@ public: private: void - setupCheckpointing(JobQueue*, Logs&); + setupCheckpointing(JobQueue*, ServiceRegistry&); template DatabaseCon( diff --git a/include/xrpl/rdb/SociDB.h b/include/xrpl/rdb/SociDB.h index acfc183076..83758677b9 100644 --- a/include/xrpl/rdb/SociDB.h +++ b/include/xrpl/rdb/SociDB.h @@ -13,8 +13,8 @@ #pragma clang diagnostic ignored "-Wdeprecated" #endif -#include #include +#include #define SOCI_USE_BOOST #include @@ -111,7 +111,7 @@ public: and so must outlive them both. */ std::shared_ptr -makeCheckpointer(std::uintptr_t id, std::weak_ptr, JobQueue&, Logs&); +makeCheckpointer(std::uintptr_t id, std::weak_ptr, JobQueue&, ServiceRegistry&); } // namespace xrpl diff --git a/include/xrpl/tx/paths/RippleCalc.h b/include/xrpl/tx/paths/RippleCalc.h index a5cecc18bf..4fc4c54f2b 100644 --- a/include/xrpl/tx/paths/RippleCalc.h +++ b/include/xrpl/tx/paths/RippleCalc.h @@ -1,6 +1,6 @@ #pragma once -#include +#include #include #include #include @@ -92,7 +92,7 @@ public: STPathSet const& spsPaths, std::optional const& domainID, - Logs& l, + ServiceRegistry& registry, Input const* const pInputs = nullptr); // The view we are currently working on diff --git a/src/libxrpl/rdb/DatabaseCon.cpp b/src/libxrpl/rdb/DatabaseCon.cpp index 6552a1d7ce..81686c78a6 100644 --- a/src/libxrpl/rdb/DatabaseCon.cpp +++ b/src/libxrpl/rdb/DatabaseCon.cpp @@ -1,5 +1,5 @@ -#include #include +#include #include #include @@ -40,11 +40,14 @@ public: } std::shared_ptr - create(std::shared_ptr const& session, JobQueue& jobQueue, Logs& logs) + create( + std::shared_ptr const& session, + JobQueue& jobQueue, + ServiceRegistry& registry) { std::lock_guard lock{mutex_}; auto const id = nextId_++; - auto const r = makeCheckpointer(id, session, jobQueue, logs); + auto const r = makeCheckpointer(id, session, jobQueue, registry); checkpointers_[id] = r; return r; } @@ -82,11 +85,11 @@ DatabaseCon::~DatabaseCon() std::unique_ptr const> DatabaseCon::Setup::globalPragma; void -DatabaseCon::setupCheckpointing(JobQueue* q, Logs& l) +DatabaseCon::setupCheckpointing(JobQueue* q, ServiceRegistry& registry) { if (q == nullptr) Throw("No JobQueue"); - checkpointer_ = checkpointers.create(session_, *q, l); + checkpointer_ = checkpointers.create(session_, *q, registry); } } // namespace xrpl diff --git a/src/libxrpl/rdb/SociDB.cpp b/src/libxrpl/rdb/SociDB.cpp index 576105016e..ac96985407 100644 --- a/src/libxrpl/rdb/SociDB.cpp +++ b/src/libxrpl/rdb/SociDB.cpp @@ -187,8 +187,11 @@ public: std::uintptr_t id, std::weak_ptr session, JobQueue& q, - Logs& logs) - : id_(id), session_(std::move(session)), jobQueue_(q), j_(logs.journal("WALCheckpointer")) + ServiceRegistry& registry) + : id_(id) + , session_(std::move(session)) + , jobQueue_(q) + , j_(registry.getJournal("WALCheckpointer")) { if (auto [conn, keepAlive] = getConnection(); conn) { @@ -307,9 +310,9 @@ makeCheckpointer( std::uintptr_t id, std::weak_ptr session, JobQueue& queue, - Logs& logs) + ServiceRegistry& registry) { - return std::make_shared(id, std::move(session), queue, logs); + return std::make_shared(id, std::move(session), queue, registry); } } // namespace xrpl diff --git a/src/libxrpl/tx/Transactor.cpp b/src/libxrpl/tx/Transactor.cpp index 9c2e93fba3..5c87d4342f 100644 --- a/src/libxrpl/tx/Transactor.cpp +++ b/src/libxrpl/tx/Transactor.cpp @@ -1,4 +1,3 @@ -#include #include #include #include @@ -302,7 +301,7 @@ Transactor::calculateOwnerReserveFee(ReadView const& view, STTx const& tx) // need to rethink charging an owner reserve as a transaction fee. // TODO: This function is static, and I don't want to add more parameters. // When it is finally refactored to be in a context that has access to the - // Application, include "app().overlay().networkID() > 2 ||" in the + // Application, include "app().getOverlay().networkID() > 2 ||" in the // condition. XRPL_ASSERT( view.fees().increment > view.fees().base * 100, @@ -1096,7 +1095,7 @@ Transactor::operator()() } #endif - if (auto const& trap = ctx_.registry.trapTxID(); trap && *trap == ctx_.tx.getTransactionID()) + if (auto const& trap = ctx_.registry.getTrapTxID(); trap && *trap == ctx_.tx.getTransactionID()) { trapTransaction(*trap); } @@ -1198,16 +1197,25 @@ Transactor::operator()() // If necessary, remove any offers found unfunded during processing if ((result == tecOVERSIZE) || (result == tecKILLED)) - removeUnfundedOffers(view(), removedOffers, ctx_.registry.journal("View")); + { + removeUnfundedOffers(view(), removedOffers, ctx_.registry.getJournal("View")); + } if (result == tecEXPIRED) - removeExpiredNFTokenOffers(view(), expiredNFTokenOffers, ctx_.registry.journal("View")); + { + removeExpiredNFTokenOffers( + view(), expiredNFTokenOffers, ctx_.registry.getJournal("View")); + } if (result == tecINCOMPLETE) - removeDeletedTrustLines(view(), removedTrustLines, ctx_.registry.journal("View")); + { + removeDeletedTrustLines(view(), removedTrustLines, ctx_.registry.getJournal("View")); + } if (result == tecEXPIRED) - removeExpiredCredentials(view(), expiredCredentials, ctx_.registry.journal("View")); + { + removeExpiredCredentials(view(), expiredCredentials, ctx_.registry.getJournal("View")); + } applied = isTecClaim(result); } diff --git a/src/libxrpl/tx/paths/RippleCalc.cpp b/src/libxrpl/tx/paths/RippleCalc.cpp index cebb5c6dcc..c9f0c9e0fb 100644 --- a/src/libxrpl/tx/paths/RippleCalc.cpp +++ b/src/libxrpl/tx/paths/RippleCalc.cpp @@ -1,4 +1,3 @@ -#include #include #include #include @@ -35,12 +34,12 @@ RippleCalc::rippleCalculate( STPathSet const& spsPaths, std::optional const& domainID, - Logs& l, + ServiceRegistry& registry, Input const* const pInputs) { Output flowOut; PaymentSandbox flowSB(&view); - auto j = l.journal("Flow"); + auto j = registry.getJournal("Flow"); { bool const defaultPaths = (pInputs == nullptr) ? true : pInputs->defaultPathsAllowed; diff --git a/src/libxrpl/tx/transactors/account/SignerListSet.cpp b/src/libxrpl/tx/transactors/account/SignerListSet.cpp index fcc74a6b2c..70e8f21df5 100644 --- a/src/libxrpl/tx/transactors/account/SignerListSet.cpp +++ b/src/libxrpl/tx/transactors/account/SignerListSet.cpp @@ -1,4 +1,3 @@ -#include #include #include #include @@ -197,7 +196,7 @@ removeSignersFromLedger( } adjustOwnerCount( - view, view.peek(accountKeylet), removeFromOwnerCount, registry.journal("View")); + view, view.peek(accountKeylet), removeFromOwnerCount, registry.getJournal("View")); view.erase(signers); @@ -315,7 +314,7 @@ SignerListSet::replaceSignerList() view().insert(signerList); writeSignersToSLE(signerList, flags); - auto viewJ = ctx_.registry.journal("View"); + auto viewJ = ctx_.registry.getJournal("View"); // Add the signer list to the account's directory. auto const page = ctx_.view().dirInsert(ownerDirKeylet, signerListKeylet, describeOwnerDir(account_)); diff --git a/src/libxrpl/tx/transactors/check/CheckCancel.cpp b/src/libxrpl/tx/transactors/check/CheckCancel.cpp index 2d08b2f1b0..50aab27f2b 100644 --- a/src/libxrpl/tx/transactors/check/CheckCancel.cpp +++ b/src/libxrpl/tx/transactors/check/CheckCancel.cpp @@ -1,4 +1,3 @@ -#include #include #include #include @@ -58,7 +57,7 @@ CheckCancel::doApply() AccountID const srcId{sleCheck->getAccountID(sfAccount)}; AccountID const dstId{sleCheck->getAccountID(sfDestination)}; - auto viewJ = ctx_.registry.journal("View"); + auto viewJ = ctx_.registry.getJournal("View"); // If the check is not written to self (and it shouldn't be), remove the // check from the destination account root. diff --git a/src/libxrpl/tx/transactors/check/CheckCash.cpp b/src/libxrpl/tx/transactors/check/CheckCash.cpp index 2546c2635c..ea770bf37f 100644 --- a/src/libxrpl/tx/transactors/check/CheckCash.cpp +++ b/src/libxrpl/tx/transactors/check/CheckCash.cpp @@ -1,4 +1,3 @@ -#include #include #include #include @@ -233,7 +232,7 @@ CheckCash::doApply() // // If it is not a check to self (as should be the case), then there's // work to do... - auto viewJ = ctx_.registry.journal("View"); + auto viewJ = ctx_.registry.getJournal("View"); auto const optDeliverMin = ctx_.tx[~sfDeliverMin]; if (srcId != account_) diff --git a/src/libxrpl/tx/transactors/check/CheckCreate.cpp b/src/libxrpl/tx/transactors/check/CheckCreate.cpp index 1aa4ac15ba..dfcc528f7b 100644 --- a/src/libxrpl/tx/transactors/check/CheckCreate.cpp +++ b/src/libxrpl/tx/transactors/check/CheckCreate.cpp @@ -1,4 +1,3 @@ -#include #include #include #include @@ -169,7 +168,7 @@ CheckCreate::doApply() view().insert(sleCheck); - auto viewJ = ctx_.registry.journal("View"); + auto viewJ = ctx_.registry.getJournal("View"); // If it's not a self-send (and it shouldn't be), add Check to the // destination's owner directory. if (dstAccountId != account_) diff --git a/src/libxrpl/tx/transactors/dex/OfferCancel.cpp b/src/libxrpl/tx/transactors/dex/OfferCancel.cpp index a9e7cac85a..7e094306e9 100644 --- a/src/libxrpl/tx/transactors/dex/OfferCancel.cpp +++ b/src/libxrpl/tx/transactors/dex/OfferCancel.cpp @@ -1,4 +1,3 @@ -#include #include #include #include @@ -54,7 +53,7 @@ OfferCancel::doApply() if (auto sleOffer = view().peek(keylet::offer(account_, offerSequence))) { JLOG(j_.debug()) << "Trying to cancel offer #" << offerSequence; - return offerDelete(view(), sleOffer, ctx_.registry.journal("View")); + return offerDelete(view(), sleOffer, ctx_.registry.getJournal("View")); } JLOG(j_.debug()) << "Offer #" << offerSequence << " can't be found."; diff --git a/src/libxrpl/tx/transactors/dex/OfferCreate.cpp b/src/libxrpl/tx/transactors/dex/OfferCreate.cpp index 17dd2d2c57..602fa9f447 100644 --- a/src/libxrpl/tx/transactors/dex/OfferCreate.cpp +++ b/src/libxrpl/tx/transactors/dex/OfferCreate.cpp @@ -144,7 +144,7 @@ OfferCreate::preclaim(PreclaimContext const& ctx) std::uint32_t const uAccountSequence = sleCreator->getFieldU32(sfSequence); - auto viewJ = ctx.registry.journal("View"); + auto viewJ = ctx.registry.getJournal("View"); if (isGlobalFrozen(ctx.view, uPaysIssuerID) || isGlobalFrozen(ctx.view, uGetsIssuerID)) { @@ -536,7 +536,7 @@ OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) // end up on the books. auto uRate = getRate(saTakerGets, saTakerPays); - auto viewJ = ctx_.registry.journal("View"); + auto viewJ = ctx_.registry.getJournal("View"); TER result = tesSUCCESS; diff --git a/src/libxrpl/tx/transactors/payment/Payment.cpp b/src/libxrpl/tx/transactors/payment/Payment.cpp index c95afc33f9..5f2a78917c 100644 --- a/src/libxrpl/tx/transactors/payment/Payment.cpp +++ b/src/libxrpl/tx/transactors/payment/Payment.cpp @@ -1,4 +1,3 @@ -#include #include #include #include @@ -435,7 +434,7 @@ Payment::doApply() account_, ctx_.tx.getFieldPathSet(sfPaths), ctx_.tx[~sfDomainID], - ctx_.registry.logs(), + ctx_.registry, &rcInput); // VFALCO NOTE We might not need to apply, depending // on the TER. But always applying *should* diff --git a/src/libxrpl/tx/transactors/payment_channel/PaymentChannelClaim.cpp b/src/libxrpl/tx/transactors/payment_channel/PaymentChannelClaim.cpp index dccaf8f071..10508dda96 100644 --- a/src/libxrpl/tx/transactors/payment_channel/PaymentChannelClaim.cpp +++ b/src/libxrpl/tx/transactors/payment_channel/PaymentChannelClaim.cpp @@ -1,4 +1,3 @@ -#include #include #include #include @@ -109,7 +108,7 @@ PaymentChannelClaim::doApply() auto const closeTime = ctx_.view().header().parentCloseTime.time_since_epoch().count(); if ((cancelAfter && closeTime >= *cancelAfter) || (curExpiration && closeTime >= *curExpiration)) - return closeChannel(slep, ctx_.view(), k.key, ctx_.registry.journal("View")); + return closeChannel(slep, ctx_.view(), k.key, ctx_.registry.getJournal("View")); } if (txAccount != src && txAccount != dst) @@ -170,7 +169,7 @@ PaymentChannelClaim::doApply() { // Channel will close immediately if dry or the receiver closes if (dst == txAccount || (*slep)[sfBalance] == (*slep)[sfAmount]) - return closeChannel(slep, ctx_.view(), k.key, ctx_.registry.journal("View")); + return closeChannel(slep, ctx_.view(), k.key, ctx_.registry.getJournal("View")); auto const settleExpiration = ctx_.view().header().parentCloseTime.time_since_epoch().count() + diff --git a/src/libxrpl/tx/transactors/payment_channel/PaymentChannelFund.cpp b/src/libxrpl/tx/transactors/payment_channel/PaymentChannelFund.cpp index 6c08cc466c..1ffb19ce6f 100644 --- a/src/libxrpl/tx/transactors/payment_channel/PaymentChannelFund.cpp +++ b/src/libxrpl/tx/transactors/payment_channel/PaymentChannelFund.cpp @@ -38,7 +38,7 @@ PaymentChannelFund::doApply() auto const cancelAfter = (*slep)[~sfCancelAfter]; auto const closeTime = ctx_.view().header().parentCloseTime.time_since_epoch().count(); if ((cancelAfter && closeTime >= *cancelAfter) || (expiration && closeTime >= *expiration)) - return closeChannel(slep, ctx_.view(), k.key, ctx_.registry.journal("View")); + return closeChannel(slep, ctx_.view(), k.key, ctx_.registry.getJournal("View")); } if (src != txAccount) diff --git a/src/libxrpl/tx/transactors/system/TicketCreate.cpp b/src/libxrpl/tx/transactors/system/TicketCreate.cpp index a064c158d1..e5100164df 100644 --- a/src/libxrpl/tx/transactors/system/TicketCreate.cpp +++ b/src/libxrpl/tx/transactors/system/TicketCreate.cpp @@ -1,4 +1,3 @@ -#include #include #include #include @@ -71,7 +70,7 @@ TicketCreate::doApply() return tecINSUFFICIENT_RESERVE; } - beast::Journal viewJ{ctx_.registry.journal("View")}; + beast::Journal viewJ{ctx_.registry.getJournal("View")}; // The starting ticket sequence is the same as the current account // root sequence. Before we got here to doApply(), the transaction diff --git a/src/libxrpl/tx/transactors/token/TrustSet.cpp b/src/libxrpl/tx/transactors/token/TrustSet.cpp index 918620c3de..9602eb61d5 100644 --- a/src/libxrpl/tx/transactors/token/TrustSet.cpp +++ b/src/libxrpl/tx/transactors/token/TrustSet.cpp @@ -1,4 +1,3 @@ -#include #include #include #include @@ -367,7 +366,7 @@ TrustSet::doApply() bool const bSetDeepFreeze = (uTxFlags & tfSetDeepFreeze) != 0u; bool const bClearDeepFreeze = (uTxFlags & tfClearDeepFreeze) != 0u; - auto viewJ = ctx_.registry.journal("View"); + auto viewJ = ctx_.registry.getJournal("View"); SLE::pointer sleDst = view().peek(keylet::account(uDstAccountID)); diff --git a/src/test/app/AMMExtended_test.cpp b/src/test/app/AMMExtended_test.cpp index a416a2f9ee..9de1714389 100644 --- a/src/test/app/AMMExtended_test.cpp +++ b/src/test/app/AMMExtended_test.cpp @@ -1926,7 +1926,7 @@ private: BEAST_EXPECT(isOffer(env, carol, BTC(1'000), EUR(1))); BEAST_EXPECT(isOffer(env, bob, EUR(50), USD(50))); - auto flowJournal = env.app().logs().journal("Flow"); + auto flowJournal = env.app().getJournal("Flow"); auto const flowResult = [&] { STAmount deliver(USD(51)); STAmount smax(BTC(61)); @@ -1965,7 +1965,7 @@ private: }(); BEAST_EXPECT(flowResult.removableOffers.size() == 1); - env.app().openLedger().modify([&](OpenView& view, beast::Journal j) { + env.app().getOpenLedger().modify([&](OpenView& view, beast::Journal j) { if (flowResult.removableOffers.empty()) return false; Sandbox sb(&view, tapNONE); diff --git a/src/test/app/AccountSet_test.cpp b/src/test/app/AccountSet_test.cpp index 7af917a0b9..748f276433 100644 --- a/src/test/app/AccountSet_test.cpp +++ b/src/test/app/AccountSet_test.cpp @@ -403,7 +403,7 @@ public: // Note that we're bypassing almost all of the ledger's safety // checks with this modify() call. If you call close() between // here and the end of the test all the effort will be lost. - env.app().openLedger().modify([&gw, transferRate](OpenView& view, beast::Journal j) { + env.app().getOpenLedger().modify([&gw, transferRate](OpenView& view, beast::Journal j) { // Get the account root we want to hijack. auto const sle = view.read(keylet::account(gw.id())); if (!sle) @@ -552,7 +552,7 @@ public: auto stx = std::make_shared(*jtx.stx); stx->at(sfSigningPubKey) = makeSlice(std::string("badkey")); - env.app().openLedger().modify([&](OpenView& view, beast::Journal j) { + env.app().getOpenLedger().modify([&](OpenView& view, beast::Journal j) { auto const result = xrpl::apply(env.app(), view, *stx, tapNONE, j); BEAST_EXPECT(result.ter == temBAD_SIGNATURE); BEAST_EXPECT(!result.applied); diff --git a/src/test/app/Batch_test.cpp b/src/test/app/Batch_test.cpp index 9fe9e9cd3a..adc36e4340 100644 --- a/src/test/app/Batch_test.cpp +++ b/src/test/app/Batch_test.cpp @@ -1379,7 +1379,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(alice, bob, XRP(1)), aliceSeq), batch::inner(pay(alice, bob, XRP(1)), aliceSeq)); - env.app().openLedger().modify([&](OpenView& view, beast::Journal j) { + env.app().getOpenLedger().modify([&](OpenView& view, beast::Journal j) { auto const result = xrpl::apply(env.app(), view, *jt.stx, tapNONE, j); BEAST_EXPECT(!result.applied && result.ter == temARRAY_TOO_LARGE); return result.applied; @@ -1422,7 +1422,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(alice, bob, XRP(5)), aliceSeq + 2), batch::sig(bob, bob, bob, bob, bob, bob, bob, bob, bob, bob)); - env.app().openLedger().modify([&](OpenView& view, beast::Journal j) { + env.app().getOpenLedger().modify([&](OpenView& view, beast::Journal j) { auto const result = xrpl::apply(env.app(), view, *jt.stx, tapNONE, j); BEAST_EXPECT(!result.applied && result.ter == temARRAY_TOO_LARGE); return result.applied; @@ -3627,7 +3627,7 @@ class Batch_test : public beast::unit_test::suite BEAST_EXPECT(isPseudoTx(stx)); BEAST_EXPECT(!passesLocalChecks(stx, reason)); BEAST_EXPECT(reason == "Cannot submit pseudo transactions."); - env.app().openLedger().modify([&](OpenView& view, beast::Journal j) { + env.app().getOpenLedger().modify([&](OpenView& view, beast::Journal j) { auto const result = xrpl::apply(env.app(), view, stx, tapNONE, j); BEAST_EXPECT(!result.applied && result.ter == temINVALID_FLAG); return result.applied; diff --git a/src/test/app/EscrowToken_test.cpp b/src/test/app/EscrowToken_test.cpp index ff537a2f5e..619b584ddb 100644 --- a/src/test/app/EscrowToken_test.cpp +++ b/src/test/app/EscrowToken_test.cpp @@ -2518,7 +2518,7 @@ struct EscrowToken_test : public beast::unit_test::suite env.close(); auto const seq1 = env.seq(alice); - env.app().openLedger().modify([&](OpenView& view, beast::Journal j) { + env.app().getOpenLedger().modify([&](OpenView& view, beast::Journal j) { Sandbox sb(&view, tapNONE); auto sleNew = std::make_shared(keylet::escrow(alice, seq1)); MPTIssue const mpt{MPTIssue{makeMptID(1, AccountID(0x4985601))}}; @@ -2745,7 +2745,7 @@ struct EscrowToken_test : public beast::unit_test::suite env.fund(XRP(10'000), alice, bob); auto const seq1 = env.seq(alice); - env.app().openLedger().modify([&](OpenView& view, beast::Journal j) { + env.app().getOpenLedger().modify([&](OpenView& view, beast::Journal j) { Sandbox sb(&view, tapNONE); auto sleNew = std::make_shared(keylet::escrow(alice, seq1)); MPTIssue const mpt{MPTIssue{makeMptID(1, AccountID(0x4985601))}}; diff --git a/src/test/app/FeeVote_test.cpp b/src/test/app/FeeVote_test.cpp index 416b1ab70b..3c84f9e007 100644 --- a/src/test/app/FeeVote_test.cpp +++ b/src/test/app/FeeVote_test.cpp @@ -256,7 +256,7 @@ class FeeVote_test : public beast::unit_test::suite env.app().getNodeFamily()); // Create the next ledger to apply transaction to - ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); + ledger = std::make_shared(*ledger, env.app().getTimeKeeper().closeTime()); // Test successful fee transaction with legacy fields @@ -286,7 +286,7 @@ class FeeVote_test : public beast::unit_test::suite env.app().getNodeFamily()); // Create the next ledger to apply transaction to - ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); + ledger = std::make_shared(*ledger, env.app().getTimeKeeper().closeTime()); FeeSettingsFields fields{ .baseFeeDrops = XRPAmount{10}, @@ -319,7 +319,7 @@ class FeeVote_test : public beast::unit_test::suite env.app().getNodeFamily()); // Create the next ledger to apply transaction to - ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); + ledger = std::make_shared(*ledger, env.app().getTimeKeeper().closeTime()); // Test transaction with missing required legacy fields auto invalidTx = createInvalidFeeTx(ledger->rules(), ledger->seq(), true, false, 1); @@ -341,7 +341,7 @@ class FeeVote_test : public beast::unit_test::suite env.app().getNodeFamily()); // Create the next ledger to apply transaction to - ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); + ledger = std::make_shared(*ledger, env.app().getTimeKeeper().closeTime()); // Test transaction with missing required new fields auto invalidTx = createInvalidFeeTx(ledger->rules(), ledger->seq(), true, false, 3); @@ -368,7 +368,7 @@ class FeeVote_test : public beast::unit_test::suite env.app().getNodeFamily()); // Create the next ledger to apply transaction to - ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); + ledger = std::make_shared(*ledger, env.app().getTimeKeeper().closeTime()); auto feeTx = createFeeTx( ledger->rules(), @@ -406,7 +406,7 @@ class FeeVote_test : public beast::unit_test::suite std::vector{}, env.app().getNodeFamily()); - ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); + ledger = std::make_shared(*ledger, env.app().getTimeKeeper().closeTime()); FeeSettingsFields fields1{ .baseFeeDrops = XRPAmount{10}, @@ -423,7 +423,7 @@ class FeeVote_test : public beast::unit_test::suite BEAST_EXPECT(verifyFeeObject(ledger, ledger->rules(), fields1)); // Apply second fee transaction with different values - ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); + ledger = std::make_shared(*ledger, env.app().getTimeKeeper().closeTime()); FeeSettingsFields fields2{ .baseFeeDrops = XRPAmount{20}, @@ -454,7 +454,7 @@ class FeeVote_test : public beast::unit_test::suite std::vector{}, env.app().getNodeFamily()); - ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); + ledger = std::make_shared(*ledger, env.app().getTimeKeeper().closeTime()); // Test transaction with wrong ledger sequence auto feeTx = createFeeTx( @@ -485,7 +485,7 @@ class FeeVote_test : public beast::unit_test::suite std::vector{}, env.app().getNodeFamily()); - ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); + ledger = std::make_shared(*ledger, env.app().getTimeKeeper().closeTime()); FeeSettingsFields fields1{ .baseFeeDrops = XRPAmount{10}, @@ -501,7 +501,7 @@ class FeeVote_test : public beast::unit_test::suite BEAST_EXPECT(verifyFeeObject(ledger, ledger->rules(), fields1)); - ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); + ledger = std::make_shared(*ledger, env.app().getTimeKeeper().closeTime()); // Apply partial update (only some fields) FeeSettingsFields fields2{ @@ -531,7 +531,7 @@ class FeeVote_test : public beast::unit_test::suite std::vector{}, env.app().getNodeFamily()); - ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); + ledger = std::make_shared(*ledger, env.app().getTimeKeeper().closeTime()); // Test invalid transaction with non-zero account - this should fail // validation @@ -563,7 +563,7 @@ class FeeVote_test : public beast::unit_test::suite // Test with XRPFees enabled { Env env(*this, testable_amendments() | featureXRPFees); - auto feeVote = make_FeeVote(setup, env.app().journal("FeeVote")); + auto feeVote = make_FeeVote(setup, env.app().getJournal("FeeVote")); auto ledger = std::make_shared( create_genesis, @@ -576,7 +576,7 @@ class FeeVote_test : public beast::unit_test::suite auto pub = derivePublicKey(KeyType::secp256k1, sec); auto val = std::make_shared( - env.app().timeKeeper().now(), pub, sec, calcNodeID(pub), [](STValidation& v) { + env.app().getTimeKeeper().now(), pub, sec, calcNodeID(pub), [](STValidation& v) { v.setFieldU32(sfLedgerSequence, 12345); }); @@ -593,7 +593,7 @@ class FeeVote_test : public beast::unit_test::suite // Test with XRPFees disabled (legacy format) { Env env(*this, testable_amendments() - featureXRPFees); - auto feeVote = make_FeeVote(setup, env.app().journal("FeeVote")); + auto feeVote = make_FeeVote(setup, env.app().getJournal("FeeVote")); auto ledger = std::make_shared( create_genesis, @@ -606,7 +606,7 @@ class FeeVote_test : public beast::unit_test::suite auto pub = derivePublicKey(KeyType::secp256k1, sec); auto val = std::make_shared( - env.app().timeKeeper().now(), pub, sec, calcNodeID(pub), [](STValidation& v) { + env.app().getTimeKeeper().now(), pub, sec, calcNodeID(pub), [](STValidation& v) { v.setFieldU32(sfLedgerSequence, 12345); }); @@ -639,7 +639,7 @@ class FeeVote_test : public beast::unit_test::suite BEAST_EXPECT(env.current()->fees().reserve == XRPAmount{200'000'000}); BEAST_EXPECT(env.current()->fees().increment == XRPAmount{50'000'000}); - auto feeVote = make_FeeVote(setup, env.app().journal("FeeVote")); + auto feeVote = make_FeeVote(setup, env.app().getJournal("FeeVote")); auto ledger = std::make_shared( create_genesis, Rules{env.app().config().features}, @@ -651,7 +651,7 @@ class FeeVote_test : public beast::unit_test::suite // We need to create a ledger at sequence 256 to make it a flag ledger for (int i = 0; i < 256 - 1; ++i) { - ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); + ledger = std::make_shared(*ledger, env.app().getTimeKeeper().closeTime()); } BEAST_EXPECT(ledger->isFlagLedger()); @@ -664,7 +664,7 @@ class FeeVote_test : public beast::unit_test::suite auto pub = derivePublicKey(KeyType::secp256k1, sec); auto val = std::make_shared( - env.app().timeKeeper().now(), pub, sec, calcNodeID(pub), [&](STValidation& v) { + env.app().getTimeKeeper().now(), pub, sec, calcNodeID(pub), [&](STValidation& v) { v.setFieldU32(sfLedgerSequence, ledger->seq()); // Vote for different fees than current v.setFieldAmount(sfBaseFeeDrops, XRPAmount{setup.reference_fee}); diff --git a/src/test/app/Flow_test.cpp b/src/test/app/Flow_test.cpp index 473f8bce20..25bcb4ee64 100644 --- a/src/test/app/Flow_test.cpp +++ b/src/test/app/Flow_test.cpp @@ -435,7 +435,7 @@ struct Flow_test : public beast::unit_test::suite BEAST_EXPECT(isOffer(env, bob, BTC(60), EUR(50))); BEAST_EXPECT(isOffer(env, carol, BTC(1000), EUR(1))); - auto flowJournal = env.app().logs().journal("Flow"); + auto flowJournal = env.app().getJournal("Flow"); auto const flowResult = [&] { STAmount deliver(USD(51)); STAmount smax(BTC(61)); @@ -474,7 +474,7 @@ struct Flow_test : public beast::unit_test::suite }(); BEAST_EXPECT(flowResult.removableOffers.size() == 1); - env.app().openLedger().modify([&](OpenView& view, beast::Journal j) { + env.app().getOpenLedger().modify([&](OpenView& view, beast::Journal j) { if (flowResult.removableOffers.empty()) return false; Sandbox sb(&view, tapNONE); diff --git a/src/test/app/LedgerReplay_test.cpp b/src/test/app/LedgerReplay_test.cpp index 59304f1894..cc7cfa413c 100644 --- a/src/test/app/LedgerReplay_test.cpp +++ b/src/test/app/LedgerReplay_test.cpp @@ -464,7 +464,7 @@ struct LedgerServer assert(param.initLedgers > 0); createAccounts(param.initAccounts); createLedgerHistory(); - app.logs().threshold(beast::severities::kWarning); + app.getLogs().threshold(beast::severities::kWarning); } /** @@ -803,8 +803,8 @@ logAll( LedgerReplayClient& client, beast::severities::Severity level = Severity::kTrace) { - server.app.logs().threshold(level); - client.app.logs().threshold(level); + server.app.getLogs().threshold(level); + client.app.getLogs().threshold(level); } // logAll(net.server, net.client); diff --git a/src/test/app/NFTokenAuth_test.cpp b/src/test/app/NFTokenAuth_test.cpp index 59faeb1eeb..551882b51a 100644 --- a/src/test/app/NFTokenAuth_test.cpp +++ b/src/test/app/NFTokenAuth_test.cpp @@ -110,7 +110,7 @@ public: view.rawInsert(sleA1); return true; }; - env.app().openLedger().modify(unauthTrustline); + env.app().getOpenLedger().modify(unauthTrustline); if (features[fixEnforceNFTokenTrustlineV2]) { @@ -173,7 +173,7 @@ public: view.rawInsert(sleA1); return true; }; - env.app().openLedger().modify(unauthTrustline); + env.app().getOpenLedger().modify(unauthTrustline); if (features[fixEnforceNFTokenTrustlineV2]) { // test: check that offer can't be accepted even with balance @@ -293,7 +293,7 @@ public: view.rawInsert(sleA1); return true; }; - env.app().openLedger().modify(unauthTrustline); + env.app().getOpenLedger().modify(unauthTrustline); if (features[fixEnforceNFTokenTrustlineV2]) { env(token::acceptSellOffer(A1, sellIdx), ter(tecNO_AUTH)); @@ -412,7 +412,7 @@ public: view.rawInsert(sleA1); return true; }; - env.app().openLedger().modify(unauthTrustline); + env.app().getOpenLedger().modify(unauthTrustline); if (features[fixEnforceNFTokenTrustlineV2]) { diff --git a/src/test/app/NFToken_test.cpp b/src/test/app/NFToken_test.cpp index 40fb78bb20..bd61c959fc 100644 --- a/src/test/app/NFToken_test.cpp +++ b/src/test/app/NFToken_test.cpp @@ -399,7 +399,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Note that we're bypassing almost all of the ledger's safety // checks with this modify() call. If you call close() between // here and the end of the test all the effort will be lost. - env.app().openLedger().modify([&alice](OpenView& view, beast::Journal j) { + env.app().getOpenLedger().modify([&alice](OpenView& view, beast::Journal j) { // Get the account root we want to hijack. auto const sle = view.read(keylet::account(alice.id())); if (!sle) diff --git a/src/test/app/PayStrand_test.cpp b/src/test/app/PayStrand_test.cpp index d2e79a58f8..256c5ae716 100644 --- a/src/test/app/PayStrand_test.cpp +++ b/src/test/app/PayStrand_test.cpp @@ -623,7 +623,7 @@ struct PayStrand_test : public beast::unit_test::suite OfferCrossing::no, ammContext, std::nullopt, - env.app().logs().journal("Flow")); + env.app().getJournal("Flow")); BEAST_EXPECT(ter == expTer); if (sizeof...(expSteps) != 0) BEAST_EXPECT(equal(strand, std::forward(expSteps)...)); @@ -650,7 +650,7 @@ struct PayStrand_test : public beast::unit_test::suite OfferCrossing::no, ammContext, std::nullopt, - env.app().logs().journal("Flow")); + env.app().getJournal("Flow")); (void)_; BEAST_EXPECT(isTesSuccess(ter)); } @@ -668,7 +668,7 @@ struct PayStrand_test : public beast::unit_test::suite OfferCrossing::no, ammContext, std::nullopt, - env.app().logs().journal("Flow")); + env.app().getJournal("Flow")); (void)_; BEAST_EXPECT(isTesSuccess(ter)); } @@ -765,7 +765,7 @@ struct PayStrand_test : public beast::unit_test::suite { // The root account can't be the src or dst - auto flowJournal = env.app().logs().journal("Flow"); + auto flowJournal = env.app().getJournal("Flow"); { // The root account can't be the dst auto r = toStrand( @@ -936,7 +936,7 @@ struct PayStrand_test : public beast::unit_test::suite OfferCrossing::no, ammContext, std::nullopt, - env.app().logs().journal("Flow")); + env.app().getJournal("Flow")); BEAST_EXPECT(isTesSuccess(ter)); BEAST_EXPECT(equal(strand, D{alice, gw, usdC})); } @@ -964,7 +964,7 @@ struct PayStrand_test : public beast::unit_test::suite OfferCrossing::no, ammContext, std::nullopt, - env.app().logs().journal("Flow")); + env.app().getJournal("Flow")); BEAST_EXPECT(isTesSuccess(ter)); BEAST_EXPECT(equal( strand, D{alice, gw, usdC}, B{USD.issue(), xrpIssue(), std::nullopt}, XRPS{bob})); @@ -1145,7 +1145,7 @@ struct PayStrand_test : public beast::unit_test::suite noAccount(), pathSet, std::nullopt, - env.app().logs(), + env.app(), &inputs); BEAST_EXPECT(r.result() == temBAD_PATH); } @@ -1158,7 +1158,7 @@ struct PayStrand_test : public beast::unit_test::suite srcAcc, pathSet, std::nullopt, - env.app().logs(), + env.app(), &inputs); BEAST_EXPECT(r.result() == temBAD_PATH); } @@ -1171,7 +1171,7 @@ struct PayStrand_test : public beast::unit_test::suite srcAcc, pathSet, std::nullopt, - env.app().logs(), + env.app(), &inputs); BEAST_EXPECT(r.result() == temBAD_PATH); } @@ -1184,7 +1184,7 @@ struct PayStrand_test : public beast::unit_test::suite srcAcc, pathSet, std::nullopt, - env.app().logs(), + env.app(), &inputs); BEAST_EXPECT(r.result() == temBAD_PATH); } diff --git a/src/test/app/PseudoTx_test.cpp b/src/test/app/PseudoTx_test.cpp index 79346a3fe1..a9180d0e03 100644 --- a/src/test/app/PseudoTx_test.cpp +++ b/src/test/app/PseudoTx_test.cpp @@ -70,7 +70,7 @@ struct PseudoTx_test : public beast::unit_test::suite BEAST_EXPECT(isPseudoTx(stx)); BEAST_EXPECT(!passesLocalChecks(stx, reason)); BEAST_EXPECT(reason == "Cannot submit pseudo transactions."); - env.app().openLedger().modify([&](OpenView& view, beast::Journal j) { + env.app().getOpenLedger().modify([&](OpenView& view, beast::Journal j) { auto const result = xrpl::apply(env.app(), view, stx, tapNONE, j); BEAST_EXPECT(!result.applied && result.ter == temINVALID); return result.applied; diff --git a/src/test/app/RCLValidations_test.cpp b/src/test/app/RCLValidations_test.cpp index 529e215395..e15569102a 100644 --- a/src/test/app/RCLValidations_test.cpp +++ b/src/test/app/RCLValidations_test.cpp @@ -65,7 +65,7 @@ class RCLValidations_test : public beast::unit_test::suite history.push_back(prev); for (auto i = 0; i < ((2 * maxAncestors) + 1); ++i) { - auto next = std::make_shared(*prev, env.app().timeKeeper().closeTime()); + auto next = std::make_shared(*prev, env.app().getTimeKeeper().closeTime()); next->updateSkipList(); history.push_back(next); prev = next; @@ -82,7 +82,7 @@ class RCLValidations_test : public beast::unit_test::suite bool forceHash = true; while (altHistory.size() < history.size()) { - auto next = std::make_shared(*prev, env.app().timeKeeper().closeTime()); + auto next = std::make_shared(*prev, env.app().getTimeKeeper().closeTime()); // Force a different hash on the first iteration next->updateSkipList(); BEAST_EXPECT(next->read(keylet::fees())); @@ -231,7 +231,7 @@ class RCLValidations_test : public beast::unit_test::suite history.push_back(prev); for (auto i = 0; i < (maxAncestors + 10); ++i) { - auto next = std::make_shared(*prev, env.app().timeKeeper().closeTime()); + auto next = std::make_shared(*prev, env.app().getTimeKeeper().closeTime()); next->updateSkipList(); history.push_back(next); prev = next; diff --git a/src/test/app/Regression_test.cpp b/src/test/app/Regression_test.cpp index 5d58f59fd7..55b4b9a87c 100644 --- a/src/test/app/Regression_test.cpp +++ b/src/test/app/Regression_test.cpp @@ -56,7 +56,7 @@ struct Regression_test : public beast::unit_test::suite auto const aliceXRP = 400; auto const aliceAmount = XRP(aliceXRP); - auto next = std::make_shared(*closed, env.app().timeKeeper().closeTime()); + auto next = std::make_shared(*closed, env.app().getTimeKeeper().closeTime()); { // Fund alice auto const jt = env.jt(pay(env.master, "alice", aliceAmount)); @@ -273,7 +273,7 @@ struct Regression_test : public beast::unit_test::suite if (BEAST_EXPECT(bob_index.isNonZero()) && BEAST_EXPECT(digest.has_value())) { - auto& cache = env.app().cachedSLEs(); + auto& cache = env.app().getCachedSLEs(); cache.del(*digest, false); // NOLINT(bugprone-unchecked-optional-access) auto const beforeCounts = mapCounts(CountedObjects::getInstance().getCounts(0)); diff --git a/src/test/app/SHAMapStore_test.cpp b/src/test/app/SHAMapStore_test.cpp index e5471ab74e..73cbf1c617 100644 --- a/src/test/app/SHAMapStore_test.cpp +++ b/src/test/app/SHAMapStore_test.cpp @@ -481,7 +481,7 @@ public: section, megabytes(env.app().config().getValueFor(SizedItem::burstSize, std::nullopt)), scheduler, - env.app().logs().journal("NodeStoreTest"))}; + env.app().getJournal("NodeStoreTest"))}; backend->open(); return backend; } @@ -514,7 +514,7 @@ public: std::move(writableBackend), std::move(archiveBackend), nscfg, - env.app().logs().journal("NodeStoreTest")); + env.app().getJournal("NodeStoreTest")); ///////////////////////////////////////////////////////////// // Check basic functionality diff --git a/src/test/app/TxQ_test.cpp b/src/test/app/TxQ_test.cpp index a758167319..566551fe2a 100644 --- a/src/test/app/TxQ_test.cpp +++ b/src/test/app/TxQ_test.cpp @@ -950,7 +950,7 @@ public: Env::ParsedResult parsed; - env.app().openLedger().modify([&](OpenView& view, beast::Journal j) { + env.app().getOpenLedger().modify([&](OpenView& view, beast::Journal j) { auto const result = xrpl::apply(env.app(), view, *jt.stx, tapNONE, env.journal); parsed.ter = result.ter; return result.applied; @@ -3873,7 +3873,7 @@ public: // (This requires calling directly into the open ledger, // which won't work if unit tests are separated to only // be callable via RPC.) - env.app().openLedger().modify([&](OpenView& view, beast::Journal j) { + env.app().getOpenLedger().modify([&](OpenView& view, beast::Journal j) { auto const tx = env.jt(noop(alice), seq(aliceSeq), fee(openLedgerCost(env))); auto const result = xrpl::apply(env.app(), view, *tx.stx, tapUNLIMITED, j); BEAST_EXPECT(isTesSuccess(result.ter) && result.applied); @@ -3941,7 +3941,7 @@ public: // (This requires calling directly into the open ledger, // which won't work if unit tests are separated to only // be callable via RPC.) - env.app().openLedger().modify([&](OpenView& view, beast::Journal j) { + env.app().getOpenLedger().modify([&](OpenView& view, beast::Journal j) { auto const tx = env.jt(noop(alice), ticket::use(tktSeq0 + 1), fee(openLedgerCost(env))); auto const result = xrpl::apply(env.app(), view, *tx.stx, tapUNLIMITED, j); BEAST_EXPECT(isTesSuccess(result.ter) && result.applied); diff --git a/src/test/app/ValidatorKeys_test.cpp b/src/test/app/ValidatorKeys_test.cpp index 9efe318662..29876dea7c 100644 --- a/src/test/app/ValidatorKeys_test.cpp +++ b/src/test/app/ValidatorKeys_test.cpp @@ -59,7 +59,7 @@ public: // We're only using Env for its Journal. That Journal gives better // coverage in unit tests. test::jtx::Env env{*this, test::jtx::envconfig(), nullptr, beast::severities::kDisabled}; - beast::Journal journal{env.app().journal("ValidatorKeys_test")}; + beast::Journal journal{env.app().getJournal("ValidatorKeys_test")}; // Keys/ID when using [validation_seed] SecretKey const seedSecretKey = diff --git a/src/test/app/ValidatorList_test.cpp b/src/test/app/ValidatorList_test.cpp index c4229514a1..10e34cacad 100644 --- a/src/test/app/ValidatorList_test.cpp +++ b/src/test/app/ValidatorList_test.cpp @@ -534,7 +534,7 @@ private: auto trustedKeys = std::make_unique( manifests, manifests, - env.app().timeKeeper(), + env.app().getTimeKeeper(), app.config().legacy("database_path"), env.journal); @@ -813,7 +813,7 @@ private: {}, effective6 + 1s, env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); expectUntrusted(lists.at(3)); @@ -831,7 +831,7 @@ private: {}, effective8 + 1s, env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); expectUntrusted(lists.at(6)); @@ -896,7 +896,7 @@ private: auto trustedKeys = std::make_unique( manifests, manifests, - env.app().timeKeeper(), + env.app().getTimeKeeper(), app.config().legacy("database_path"), env.journal); @@ -1062,7 +1062,7 @@ private: activeValidatorsOuter, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); for (auto const& val : unseenValidators) @@ -1088,7 +1088,7 @@ private: activeValidatorsOuter, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(changes.added.empty()); BEAST_EXPECT(changes.removed.empty()); @@ -1112,7 +1112,7 @@ private: activeValidatorsOuter, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(changes.added == asNodeIDs({masterPublic})); BEAST_EXPECT(changes.removed.empty()); @@ -1173,7 +1173,7 @@ private: activeValidatorsOuter, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(changes.removed == asNodeIDs({masterPublic})); BEAST_EXPECT(changes.added.empty()); @@ -1208,7 +1208,7 @@ private: activeValidatorsOuter, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(changes.removed.empty()); BEAST_EXPECT(changes.added.empty()); @@ -1240,7 +1240,7 @@ private: activeValidatorsOuter, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(changes.removed.empty()); BEAST_EXPECT(changes.added.size() == 1); @@ -1287,7 +1287,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(changes.removed.empty()); BEAST_EXPECT(changes.added == expectedTrusted); @@ -1299,7 +1299,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(changes.removed.empty()); BEAST_EXPECT(changes.added.empty()); @@ -1310,7 +1310,7 @@ private: auto trustedKeys = std::make_unique( manifestsOuter, manifestsOuter, - env.app().timeKeeper(), + env.app().getTimeKeeper(), app.config().legacy("database_path"), env.journal); @@ -1349,7 +1349,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(changes.removed.empty()); BEAST_EXPECT(changes.added == activeValidators); @@ -1365,7 +1365,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(changes.removed == activeValidators); BEAST_EXPECT(changes.added.empty()); @@ -1390,7 +1390,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(changes.removed.empty()); BEAST_EXPECT( @@ -1431,7 +1431,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(changes.removed.empty()); BEAST_EXPECT(changes.added == asNodeIDs({valKey})); @@ -1468,7 +1468,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(changes.removed.empty()); if (cfgKeys.size() > 2) @@ -1560,7 +1560,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(valKeys.size() * 0.8f)); @@ -1675,7 +1675,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil((valKeys.size() - 3) * 0.8f)); @@ -1706,7 +1706,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil((valKeys.size() - 6) * 0.8f)); @@ -1739,7 +1739,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::numeric_limits::max()); @@ -1809,7 +1809,7 @@ private: auto trustedKeys = std::make_unique( manifests, manifests, - env.app().timeKeeper(), + env.app().getTimeKeeper(), app.config().legacy("database_path"), env.journal); @@ -1907,7 +1907,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT( trustedKeys->expires() && @@ -1924,7 +1924,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT( trustedKeys->expires() && @@ -1969,7 +1969,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); if (minimumQuorum == trustedKeys->quorum() || trustedKeys->quorum() == std::ceil(cfgKeys.size() * 0.8f)) @@ -2019,7 +2019,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT( validators->quorum() == @@ -2063,7 +2063,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); return validators->quorum() == quorum; } @@ -2094,7 +2094,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(validators->quorum() == 39); } @@ -2121,7 +2121,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(validators->quorum() == 30); hash_set nUnl; @@ -2136,7 +2136,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(validators->quorum() == 30); } @@ -2629,7 +2629,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); @@ -2650,7 +2650,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == 1); @@ -2688,7 +2688,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); @@ -2708,7 +2708,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().empty()); @@ -2753,7 +2753,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); @@ -2773,7 +2773,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == 1); @@ -2822,7 +2822,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); @@ -2843,7 +2843,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == 1); @@ -2889,7 +2889,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); @@ -2909,7 +2909,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == 1); @@ -2956,7 +2956,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); @@ -2976,7 +2976,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().empty()); @@ -3021,7 +3021,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); @@ -3042,7 +3042,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); @@ -3080,7 +3080,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); @@ -3101,7 +3101,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); @@ -3139,7 +3139,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); @@ -3159,7 +3159,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); @@ -3195,7 +3195,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); @@ -3215,7 +3215,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); @@ -3260,7 +3260,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); @@ -3281,7 +3281,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == 1); @@ -3327,7 +3327,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); @@ -3347,7 +3347,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == 1); @@ -3394,7 +3394,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); @@ -3414,7 +3414,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().empty()); @@ -3453,7 +3453,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); @@ -3474,7 +3474,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == 1); @@ -3514,7 +3514,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); @@ -3535,7 +3535,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == 1); @@ -3576,7 +3576,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); @@ -3596,7 +3596,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().empty()); @@ -3637,7 +3637,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); @@ -3658,7 +3658,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == 1); @@ -3700,7 +3700,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); @@ -3738,7 +3738,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); @@ -3784,7 +3784,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); @@ -3805,7 +3805,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == 1); @@ -3853,7 +3853,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); @@ -3873,7 +3873,7 @@ private: activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == 1); diff --git a/src/test/app/ValidatorSite_test.cpp b/src/test/app/ValidatorSite_test.cpp index f1e3b57b1e..160da452ee 100644 --- a/src/test/app/ValidatorSite_test.cpp +++ b/src/test/app/ValidatorSite_test.cpp @@ -139,7 +139,7 @@ private: p->legacy("database_path", good.subdir().string()); return p; }()); - auto& trustedKeys = env.app().validators(); + auto& trustedKeys = env.app().getValidators(); env.timeKeeper().set(env.timeKeeper().now() + 30s); test::StreamSink sink; diff --git a/src/test/app/Vault_test.cpp b/src/test/app/Vault_test.cpp index fa935eba6e..37ad3ae334 100644 --- a/src/test/app/Vault_test.cpp +++ b/src/test/app/Vault_test.cpp @@ -3366,23 +3366,24 @@ class Vault_test : public beast::unit_test::suite env.memoize(vaultAccount); auto const peek = [keylet, &env, this](std::function fn) -> bool { - return env.app().openLedger().modify([&](OpenView& view, beast::Journal j) -> bool { - Sandbox sb(&view, tapNONE); - auto vault = sb.peek(keylet::vault(keylet.key)); - if (!BEAST_EXPECT(vault != nullptr)) + return env.app().getOpenLedger().modify( + [&](OpenView& view, beast::Journal j) -> bool { + Sandbox sb(&view, tapNONE); + auto vault = sb.peek(keylet::vault(keylet.key)); + if (!BEAST_EXPECT(vault != nullptr)) + return false; + auto shares = sb.peek(keylet::mptIssuance(vault->at(sfShareMPTID))); + if (!BEAST_EXPECT(shares != nullptr)) + return false; + if (fn(*vault, *shares)) + { + sb.update(vault); + sb.update(shares); + sb.apply(view); + return true; + } return false; - auto shares = sb.peek(keylet::mptIssuance(vault->at(sfShareMPTID))); - if (!BEAST_EXPECT(shares != nullptr)) - return false; - if (fn(*vault, *shares)) - { - sb.update(vault); - sb.update(shares); - sb.apply(view); - return true; - } - return false; - }); + }); }; test( diff --git a/src/test/basics/PerfLog_test.cpp b/src/test/basics/PerfLog_test.cpp index 1647ce241e..470a52d220 100644 --- a/src/test/basics/PerfLog_test.cpp +++ b/src/test/basics/PerfLog_test.cpp @@ -29,7 +29,7 @@ class PerfLog_test : public beast::unit_test::suite // We're only using Env for its Journal. That Journal gives better // coverage in unit tests. test::jtx::Env env_{*this, test::jtx::envconfig(), nullptr, beast::severities::kDisabled}; - beast::Journal j_{env_.app().journal("PerfLog_test")}; + beast::Journal j_{env_.app().getJournal("PerfLog_test")}; struct Fixture { diff --git a/src/test/consensus/NegativeUNL_test.cpp b/src/test/consensus/NegativeUNL_test.cpp index ddb5fef599..cf8c8e87ef 100644 --- a/src/test/consensus/NegativeUNL_test.cpp +++ b/src/test/consensus/NegativeUNL_test.cpp @@ -222,7 +222,7 @@ class NegativeUNL_test : public beast::unit_test::suite { //(1) the ledger after genesis, not a flag ledger - l = std::make_shared(*l, env.app().timeKeeper().closeTime()); + l = std::make_shared(*l, env.app().getTimeKeeper().closeTime()); auto txDisable_0 = createTx(true, l->seq(), publicKeys[0]); auto txReEnable_1 = createTx(false, l->seq(), publicKeys[1]); @@ -239,7 +239,7 @@ class NegativeUNL_test : public beast::unit_test::suite // generate more ledgers for (auto i = 0; i < 256 - 2; ++i) { - l = std::make_shared(*l, env.app().timeKeeper().closeTime()); + l = std::make_shared(*l, env.app().getTimeKeeper().closeTime()); } BEAST_EXPECT(l->isFlagLedger()); l->updateNegativeUNL(); @@ -274,7 +274,7 @@ class NegativeUNL_test : public beast::unit_test::suite BEAST_EXPECT(good_size); if (good_size) BEAST_EXPECT(l->validatorToDisable() == publicKeys[0]); - l = std::make_shared(*l, env.app().timeKeeper().closeTime()); + l = std::make_shared(*l, env.app().getTimeKeeper().closeTime()); } BEAST_EXPECT(l->isFlagLedger()); l->updateNegativeUNL(); @@ -326,7 +326,7 @@ class NegativeUNL_test : public beast::unit_test::suite BEAST_EXPECT(l->validatorToDisable() == publicKeys[1]); BEAST_EXPECT(l->validatorToReEnable() == publicKeys[0]); } - l = std::make_shared(*l, env.app().timeKeeper().closeTime()); + l = std::make_shared(*l, env.app().getTimeKeeper().closeTime()); } BEAST_EXPECT(l->isFlagLedger()); l->updateNegativeUNL(); @@ -368,7 +368,7 @@ class NegativeUNL_test : public beast::unit_test::suite BEAST_EXPECT(l->negativeUNL().count(publicKeys[1])); BEAST_EXPECT(l->validatorToDisable() == publicKeys[0]); } - l = std::make_shared(*l, env.app().timeKeeper().closeTime()); + l = std::make_shared(*l, env.app().getTimeKeeper().closeTime()); } BEAST_EXPECT(l->isFlagLedger()); l->updateNegativeUNL(); @@ -417,7 +417,7 @@ class NegativeUNL_test : public beast::unit_test::suite BEAST_EXPECT(l->negativeUNL().count(publicKeys[1])); BEAST_EXPECT(l->validatorToReEnable() == publicKeys[0]); } - l = std::make_shared(*l, env.app().timeKeeper().closeTime()); + l = std::make_shared(*l, env.app().getTimeKeeper().closeTime()); } BEAST_EXPECT(l->isFlagLedger()); l->updateNegativeUNL(); @@ -459,7 +459,7 @@ class NegativeUNL_test : public beast::unit_test::suite BEAST_EXPECT(l->negativeUNL().count(publicKeys[1])); BEAST_EXPECT(l->validatorToReEnable() == publicKeys[1]); } - l = std::make_shared(*l, env.app().timeKeeper().closeTime()); + l = std::make_shared(*l, env.app().getTimeKeeper().closeTime()); } BEAST_EXPECT(l->isFlagLedger()); l->updateNegativeUNL(); @@ -473,7 +473,7 @@ class NegativeUNL_test : public beast::unit_test::suite for (auto i = 0; i < 256; ++i) { BEAST_EXPECT(negUnlSizeTest(l, 0, false, false)); - l = std::make_shared(*l, env.app().timeKeeper().closeTime()); + l = std::make_shared(*l, env.app().getTimeKeeper().closeTime()); } BEAST_EXPECT(l->isFlagLedger()); l->updateNegativeUNL(); @@ -557,7 +557,7 @@ struct NetworkHistory int nidx = 0; while (l->seq() <= param.numLedgers) { - l = std::make_shared(*l, env.app().timeKeeper().closeTime()); + l = std::make_shared(*l, env.app().getTimeKeeper().closeTime()); history.push_back(l); if (l->isFlagLedger()) @@ -605,7 +605,11 @@ struct NetworkHistory { static auto keyPair = randomKeyPair(KeyType::secp256k1); return std::make_shared( - env.app().timeKeeper().now(), keyPair.first, keyPair.second, v, [&](STValidation& v) { + env.app().getTimeKeeper().now(), + keyPair.first, + keyPair.second, + v, + [&](STValidation& v) { v.setFieldH256(sfLedgerHash, ledger->header().hash); v.setFieldU32(sfLedgerSequence, ledger->seq()); v.setFlag(vfFullValidation); @@ -1682,7 +1686,7 @@ class NegativeUNLVoteFilterValidations_test : public beast::unit_test::suite auto createSTVal = [&](std::pair const& keys) { return std::make_shared( - env.app().timeKeeper().now(), + env.app().getTimeKeeper().now(), keys.first, keys.second, calcNodeID(keys.first), @@ -1713,7 +1717,7 @@ class NegativeUNLVoteFilterValidations_test : public beast::unit_test::suite } // setup the ValidatorList - auto& validators = env.app().validators(); + auto& validators = env.app().getValidators(); auto& local = *nUnlKeys.begin(); std::vector cfgPublishers; validators.load(local, cfgKeys, cfgPublishers); @@ -1721,7 +1725,7 @@ class NegativeUNLVoteFilterValidations_test : public beast::unit_test::suite activeValidators, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); BEAST_EXPECT(validators.getTrustedMasterKeys().size() == numNodes); validators.setNegativeUNL(nUnlKeys); diff --git a/src/test/core/ClosureCounter_test.cpp b/src/test/core/ClosureCounter_test.cpp index 736b833d76..088b7b9ff9 100644 --- a/src/test/core/ClosureCounter_test.cpp +++ b/src/test/core/ClosureCounter_test.cpp @@ -17,7 +17,7 @@ class ClosureCounter_test : public beast::unit_test::suite // We're only using Env for its Journal. That Journal gives better // coverage in unit tests. test::jtx::Env env_{*this, jtx::envconfig(), nullptr, beast::severities::kDisabled}; - beast::Journal j{env_.app().journal("ClosureCounter_test")}; + beast::Journal j{env_.app().getJournal("ClosureCounter_test")}; void testConstruction() diff --git a/src/test/jtx/Env.h b/src/test/jtx/Env.h index 9d525f14ad..b494ade31c 100644 --- a/src/test/jtx/Env.h +++ b/src/test/jtx/Env.h @@ -189,7 +189,7 @@ public: beast::severities::Severity thresh = beast::severities::kError) : test(suite_) , bundle_(suite_, std::move(config), std::move(logs), thresh) - , journal{bundle_.app->journal("Env")} + , journal{bundle_.app->getJournal("Env")} { memoize(Account::master); Pathfinder::initPathTable(); @@ -328,7 +328,7 @@ public: std::shared_ptr current() const { - return app().openLedger().current(); + return app().getOpenLedger().current(); } /** Returns the last closed ledger. diff --git a/src/test/jtx/impl/AMM.cpp b/src/test/jtx/impl/AMM.cpp index ccad604070..7109a2131d 100644 --- a/src/test/jtx/impl/AMM.cpp +++ b/src/test/jtx/impl/AMM.cpp @@ -775,7 +775,7 @@ AMM::expectAuctionSlot(auto&& cb) const // to avoid the failure. auto const slotFee = auctionSlot[~sfDiscountedFee].value_or(0); auto const slotInterval = ammAuctionTimeSlot( - env_.app().timeKeeper().now().time_since_epoch().count(), auctionSlot); + env_.app().getTimeKeeper().now().time_since_epoch().count(), auctionSlot); auto const slotPrice = auctionSlot[sfPrice].iou(); auto const authAccounts = auctionSlot.getFieldArray(sfAuthAccounts); return cb(slotFee, slotInterval, slotPrice, authAccounts); diff --git a/src/test/jtx/impl/Env.cpp b/src/test/jtx/impl/Env.cpp index 6967b48518..3f49a54ae6 100644 --- a/src/test/jtx/impl/Env.cpp +++ b/src/test/jtx/impl/Env.cpp @@ -61,7 +61,7 @@ Env::AppBundle::AppBundle( config->SSL_VERIFY_DIR, config->SSL_VERIFY_FILE, config->SSL_VERIFY, debugLog()); owned = make_Application(std::move(config), std::move(logs), std::move(timeKeeper_)); app = owned.get(); - app->logs().threshold(thresh); + app->getLogs().threshold(thresh); if (!app->setup({})) Throw("Env::AppBundle: setup failed"); timeKeeper->set(app->getLedgerMaster().getClosedLedger()->header().closeTime); @@ -637,14 +637,14 @@ Env::do_rpc( std::vector const& args, std::unordered_map const& headers) { - auto response = rpcClient(args, app().config(), app().logs(), apiVersion, headers); + auto response = rpcClient(args, app().config(), app().getLogs(), apiVersion, headers); for (unsigned ctr = 0; (ctr < retries_) and (response.first == rpcINTERNAL); ++ctr) { JLOG(journal.error()) << "Env::do_rpc error, retrying, attempt #" << ctr + 1 << " ..."; std::this_thread::sleep_for(std::chrono::milliseconds(500)); - response = rpcClient(args, app().config(), app().logs(), apiVersion, headers); + response = rpcClient(args, app().config(), app().getLogs(), apiVersion, headers); } return response.second; diff --git a/src/test/jtx/impl/directory.cpp b/src/test/jtx/impl/directory.cpp index bf63bc523b..da0a338e7c 100644 --- a/src/test/jtx/impl/directory.cpp +++ b/src/test/jtx/impl/directory.cpp @@ -15,7 +15,7 @@ bumpLastPage( std::function adjust) -> Expected { Expected res{}; - env.app().openLedger().modify([&](OpenView& view, beast::Journal j) -> bool { + env.app().getOpenLedger().modify([&](OpenView& view, beast::Journal j) -> bool { Sandbox sb(&view, tapNONE); // Find the root page diff --git a/src/test/jtx/impl/paths.cpp b/src/test/jtx/impl/paths.cpp index fe9ff916bd..af72b8bd5a 100644 --- a/src/test/jtx/impl/paths.cpp +++ b/src/test/jtx/impl/paths.cpp @@ -30,7 +30,7 @@ paths::operator()(Env& env, JTx& jt) const } Pathfinder pf( - std::make_shared(env.current(), env.app().journal("RippleLineCache")), + std::make_shared(env.current(), env.app().getJournal("RippleLineCache")), from, to, in_.currency, diff --git a/src/test/ledger/PaymentSandbox_test.cpp b/src/test/ledger/PaymentSandbox_test.cpp index a5023aa328..df23381ed3 100644 --- a/src/test/ledger/PaymentSandbox_test.cpp +++ b/src/test/ledger/PaymentSandbox_test.cpp @@ -88,7 +88,7 @@ class PaymentSandbox_test : public beast::unit_test::suite env.fund(XRP(10000), alice, gw1, gw2); - auto j = env.app().journal("View"); + auto j = env.app().getJournal("View"); auto const USD_gw1 = gw1["USD"]; auto const USD_gw2 = gw2["USD"]; diff --git a/src/test/ledger/SkipList_test.cpp b/src/test/ledger/SkipList_test.cpp index 9a00b1d3fe..ba339878ef 100644 --- a/src/test/ledger/SkipList_test.cpp +++ b/src/test/ledger/SkipList_test.cpp @@ -25,7 +25,7 @@ class SkipList_test : public beast::unit_test::suite history.push_back(prev); for (auto i = 0; i < 1023; ++i) { - auto next = std::make_shared(*prev, env.app().timeKeeper().closeTime()); + auto next = std::make_shared(*prev, env.app().getTimeKeeper().closeTime()); next->updateSkipList(); history.push_back(next); prev = next; diff --git a/src/test/ledger/View_test.cpp b/src/test/ledger/View_test.cpp index 765d2e3ee4..6e11508156 100644 --- a/src/test/ledger/View_test.cpp +++ b/src/test/ledger/View_test.cpp @@ -121,7 +121,8 @@ class View_test : public beast::unit_test::suite config.FEES.toFees(), std::vector{}, env.app().getNodeFamily()); - auto const ledger = std::make_shared(*genesis, env.app().timeKeeper().closeTime()); + auto const ledger = + std::make_shared(*genesis, env.app().getTimeKeeper().closeTime()); wipe(*ledger); ReadView& v = *ledger; succ(v, 0, std::nullopt); @@ -151,7 +152,7 @@ class View_test : public beast::unit_test::suite using namespace jtx; Env env(*this); - wipe(env.app().openLedger()); + wipe(env.app().getOpenLedger()); auto const open = env.current(); ApplyViewImpl v(&*open, tapNONE); succ(v, 0, std::nullopt); @@ -184,7 +185,7 @@ class View_test : public beast::unit_test::suite using namespace jtx; Env env(*this); - wipe(env.app().openLedger()); + wipe(env.app().getOpenLedger()); auto const open = env.current(); ApplyViewImpl v0(&*open, tapNONE); v0.insert(sle(1)); @@ -250,7 +251,7 @@ class View_test : public beast::unit_test::suite using namespace jtx; Env env(*this); - wipe(env.app().openLedger()); + wipe(env.app().getOpenLedger()); auto const open = env.current(); ApplyViewImpl v0(&*open, tapNONE); v0.rawInsert(sle(1, 1)); @@ -319,7 +320,7 @@ class View_test : public beast::unit_test::suite using namespace std::chrono; { Env env(*this); - wipe(env.app().openLedger()); + wipe(env.app().getOpenLedger()); auto const open = env.current(); OpenView v0(open.get()); BEAST_EXPECT(v0.seq() != 98); @@ -388,7 +389,8 @@ class View_test : public beast::unit_test::suite config.FEES.toFees(), std::vector{}, env.app().getNodeFamily()); - auto const ledger = std::make_shared(*genesis, env.app().timeKeeper().closeTime()); + auto const ledger = + std::make_shared(*genesis, env.app().getTimeKeeper().closeTime()); auto setup = [&ledger](std::vector const& vec) { wipe(*ledger); @@ -596,7 +598,8 @@ class View_test : public beast::unit_test::suite config.FEES.toFees(), std::vector{}, env.app().getNodeFamily()); - auto const ledger = std::make_shared(*genesis, env.app().timeKeeper().closeTime()); + auto const ledger = + std::make_shared(*genesis, env.app().getTimeKeeper().closeTime()); auto setup123 = [&ledger, this]() { // erase middle element wipe(*ledger); @@ -947,7 +950,7 @@ class View_test : public beast::unit_test::suite std::vector{}, env.app().getNodeFamily()); auto const ledger = - std::make_shared(*genesis, env.app().timeKeeper().closeTime()); + std::make_shared(*genesis, env.app().getTimeKeeper().closeTime()); wipe(*ledger); ledger->rawInsert(sle(1)); ReadView& v0 = *ledger; @@ -963,9 +966,9 @@ class View_test : public beast::unit_test::suite // Make sure OpenLedger::empty works { Env env(*this); - BEAST_EXPECT(env.app().openLedger().empty()); + BEAST_EXPECT(env.app().getOpenLedger().empty()); env.fund(XRP(10000), Account("test")); - BEAST_EXPECT(!env.app().openLedger().empty()); + BEAST_EXPECT(!env.app().getOpenLedger().empty()); } } diff --git a/src/test/overlay/TMGetObjectByHash_test.cpp b/src/test/overlay/TMGetObjectByHash_test.cpp index b899ceb084..e4da8a28c7 100644 --- a/src/test/overlay/TMGetObjectByHash_test.cpp +++ b/src/test/overlay/TMGetObjectByHash_test.cpp @@ -95,7 +95,7 @@ class TMGetObjectByHash_test : public beast::unit_test::suite std::shared_ptr createPeer(jtx::Env& env) { - auto& overlay = dynamic_cast(env.app().overlay()); + auto& overlay = dynamic_cast(env.app().getOverlay()); boost::beast::http::request request; auto stream_ptr = std::make_unique(socket_type(env.app().getIOContext()), *context_); diff --git a/src/test/overlay/reduce_relay_test.cpp b/src/test/overlay/reduce_relay_test.cpp index b4a47bac53..895332b94f 100644 --- a/src/test/overlay/reduce_relay_test.cpp +++ b/src/test/overlay/reduce_relay_test.cpp @@ -507,7 +507,7 @@ class OverlaySim : public Overlay, public reduce_relay::SquelchHandler public: using id_t = Peer::id_t; using clock_type = ManualClock; - OverlaySim(Application& app) : slots_(app.logs(), *this, app.config()), logs_(app.logs()) + OverlaySim(Application& app) : slots_(app, *this, app.config()), registry_(app) { } @@ -561,7 +561,7 @@ public: Peer::id_t id = 0; if (peersCache_.empty() || !useCache) { - peer = std::make_shared(*this, logs_.journal("Squelch")); + peer = std::make_shared(*this, registry_.getJournal("Squelch")); id = peer->id(); } else @@ -673,7 +673,7 @@ private: Peers peers_; Peers peersCache_; reduce_relay::Slots slots_; - Logs& logs_; + ServiceRegistry& registry_; }; class Network @@ -1406,7 +1406,7 @@ vp_base_squelch_max_selected_peers=2 auto createSlots = [&](bool baseSquelchEnabled) -> reduce_relay::Slots { env_.app().config().VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = baseSquelchEnabled; return reduce_relay::Slots( - env_.app().logs(), network_.overlay(), env_.app().config()); + env_.app(), network_.overlay(), env_.app().config()); }; // base squelching must not be ready if squelching is disabled BEAST_EXPECT(!createSlots(false).baseSquelchReady()); @@ -1487,8 +1487,7 @@ vp_base_squelch_max_selected_peers=2 auto run = [&](int npeers) { handler.maxDuration_ = 0; - reduce_relay::Slots slots( - env_.app().logs(), handler, env_.app().config()); + reduce_relay::Slots slots(env_.app(), handler, env_.app().config()); // 1st message from a new peer switches the slot // to counting state and resets the counts of all peers + // MAX_MESSAGE_THRESHOLD + 1 messages to reach the threshold diff --git a/src/test/overlay/tx_reduce_relay_test.cpp b/src/test/overlay/tx_reduce_relay_test.cpp index 11b5c95a4e..04d8bae768 100644 --- a/src/test/overlay/tx_reduce_relay_test.cpp +++ b/src/test/overlay/tx_reduce_relay_test.cpp @@ -151,7 +151,7 @@ private: void addPeer(jtx::Env& env, std::vector>& peers, std::uint16_t& nDisabled) { - auto& overlay = dynamic_cast(env.app().overlay()); + auto& overlay = dynamic_cast(env.app().getOverlay()); boost::beast::http::request request; (nDisabled == 0) ? request.insert("X-Protocol-Ctl", makeFeaturesRequestHeader(false, false, true, false)) @@ -216,7 +216,7 @@ private: m.set_rawtransaction(s.data(), s.size()); m.set_deferred(false); m.set_status(protocol::TransactionStatus::tsNEW); - env.app().overlay().relay(uint256{0}, m, toSkip); + env.app().getOverlay().relay(uint256{0}, m, toSkip); BEAST_EXPECT(PeerTest::sendTx_ == expectRelay && PeerTest::queueTx_ == expectQueue); } } diff --git a/src/test/rpc/LedgerEntry_test.cpp b/src/test/rpc/LedgerEntry_test.cpp index 8f4a096e2a..fd7efaede4 100644 --- a/src/test/rpc/LedgerEntry_test.cpp +++ b/src/test/rpc/LedgerEntry_test.cpp @@ -673,7 +673,7 @@ class LedgerEntry_test : public beast::unit_test::suite view.rawInsert(sle); return true; }; - env.app().openLedger().modify(amendments); + env.app().getOpenLedger().modify(amendments); } Json::Value jvParams; @@ -1561,7 +1561,7 @@ class LedgerEntry_test : public beast::unit_test::suite view.rawInsert(sle); return true; }; - env.app().openLedger().modify(nUNL); + env.app().getOpenLedger().modify(nUNL); } Json::Value jvParams; diff --git a/src/test/rpc/Peers_test.cpp b/src/test/rpc/Peers_test.cpp index d72ad6d878..de46fd766c 100644 --- a/src/test/rpc/Peers_test.cpp +++ b/src/test/rpc/Peers_test.cpp @@ -34,7 +34,7 @@ class Peers_test : public beast::unit_test::suite std::string name = "Node " + std::to_string(i); using namespace std::chrono_literals; - env.app().cluster().update(kp.first, name, 200, env.timeKeeper().now() - 10s); + env.app().getCluster().update(kp.first, name, 200, env.timeKeeper().now() - 10s); nodes.insert(std::make_pair(toBase58(TokenType::NodePublic, kp.first), name)); } diff --git a/src/test/rpc/ValidatorRPC_test.cpp b/src/test/rpc/ValidatorRPC_test.cpp index 43ba188f6a..eece5c4448 100644 --- a/src/test/rpc/ValidatorRPC_test.cpp +++ b/src/test/rpc/ValidatorRPC_test.cpp @@ -122,7 +122,7 @@ public: auto k2 = randomKeyPair(KeyType::ed25519).first; disabledKeys.insert(k1); disabledKeys.insert(k2); - env.app().validators().setNegativeUNL(disabledKeys); + env.app().getValidators().setNegativeUNL(disabledKeys); auto const jrr = env.rpc("validators")[jss::result]; auto& jrrnUnl = jrr[jss::NegativeUNL]; @@ -138,7 +138,7 @@ public: } disabledKeys.clear(); - env.app().validators().setNegativeUNL(disabledKeys); + env.app().getValidators().setNegativeUNL(disabledKeys); auto const jrrUpdated = env.rpc("validators")[jss::result]; BEAST_EXPECT(jrrUpdated[jss::NegativeUNL].isNull()); } @@ -192,8 +192,8 @@ public: }), }; - env.app().validatorSites().start(); - env.app().validatorSites().join(); + env.app().getValidatorSites().start(); + env.app().getValidatorSites().join(); { auto const jrr = env.rpc("server_info")[jss::result]; @@ -252,8 +252,8 @@ public: }), }; - env.app().validatorSites().start(); - env.app().validatorSites().join(); + env.app().getValidatorSites().start(); + env.app().getValidatorSites().join(); { auto const jrr = env.rpc("server_info")[jss::result]; @@ -315,17 +315,17 @@ public: }), }; - env.app().validatorSites().start(); - env.app().validatorSites().join(); + env.app().getValidatorSites().start(); + env.app().getValidatorSites().join(); hash_set startKeys; for (auto const& val : validators) startKeys.insert(calcNodeID(val.masterPublic)); - env.app().validators().updateTrusted( + env.app().getValidators().updateTrusted( startKeys, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); { @@ -408,17 +408,17 @@ public: }), }; - env.app().validatorSites().start(); - env.app().validatorSites().join(); + env.app().getValidatorSites().start(); + env.app().getValidatorSites().join(); hash_set startKeys; for (auto const& val : validators) startKeys.insert(calcNodeID(val.masterPublic)); - env.app().validators().updateTrusted( + env.app().getValidators().updateTrusted( startKeys, env.timeKeeper().now(), env.app().getOPs(), - env.app().overlay(), + env.app().getOverlay(), env.app().getHashRouter()); { diff --git a/src/xrpld/app/consensus/RCLConsensus.cpp b/src/xrpld/app/consensus/RCLConsensus.cpp index 4921a469c5..71f3d1cf2a 100644 --- a/src/xrpld/app/consensus/RCLConsensus.cpp +++ b/src/xrpld/app/consensus/RCLConsensus.cpp @@ -145,7 +145,7 @@ RCLConsensus::Adaptor::share(RCLCxPeerPos const& peerPos) auto const sig = peerPos.signature(); prop.set_signature(sig.data(), sig.size()); - app_.overlay().relay(prop, peerPos.suppressionID(), peerPos.publicKey()); + app_.getOverlay().relay(prop, peerPos.suppressionID(), peerPos.publicKey()); } void @@ -159,9 +159,9 @@ RCLConsensus::Adaptor::share(RCLCxTx const& tx) protocol::TMTransaction msg; msg.set_rawtransaction(slice.data(), slice.size()); msg.set_status(protocol::tsNEW); - msg.set_receivetimestamp(app_.timeKeeper().now().time_since_epoch().count()); + msg.set_receivetimestamp(app_.getTimeKeeper().now().time_since_epoch().count()); static std::set skip{}; - app_.overlay().relay(tx.id(), msg, skip); + app_.getOverlay().relay(tx.id(), msg, skip); } else { @@ -207,7 +207,7 @@ RCLConsensus::Adaptor::propose(RCLCxPeerPos::Proposal const& proposal) app_.getHashRouter().addSuppression(suppression); - app_.overlay().broadcast(prop); + app_.getOverlay().broadcast(prop); } void @@ -229,7 +229,7 @@ RCLConsensus::Adaptor::acquireTxSet(RCLTxSet::ID const& setId) bool RCLConsensus::Adaptor::hasOpenTransactions() const { - return !app_.openLedger().empty(); + return !app_.getOpenLedger().empty(); } std::size_t @@ -284,7 +284,7 @@ RCLConsensus::Adaptor::onClose( // Tell the ledger master not to acquire the ledger we're probably building ledgerMaster_.setBuildingLedger(prevLedger->header().seq + 1); - auto initialLedger = app_.openLedger().current(); + auto initialLedger = app_.getOpenLedger().current(); auto initialSet = std::make_shared(SHAMapType::TRANSACTION, app_.getNodeFamily()); initialSet->setUnbacked(); @@ -308,9 +308,9 @@ RCLConsensus::Adaptor::onClose( // previous ledger was flag ledger, add fee and amendment // pseudo-transactions auto validations = - app_.validators().negativeUNLFilter(app_.getValidations().getTrustedForLedger( + app_.getValidators().negativeUNLFilter(app_.getValidations().getTrustedForLedger( prevLedger->header().parentHash, prevLedger->seq() - 1)); - if (validations.size() >= app_.validators().quorum()) + if (validations.size() >= app_.getValidators().quorum()) { feeVote_->doVoting(prevLedger, validations, initialSet); app_.getAmendmentTable().doVoting(prevLedger, validations, initialSet, j_); @@ -323,7 +323,7 @@ RCLConsensus::Adaptor::onClose( // add negative UNL pseudo-transactions nUnlVote_.doVoting( prevLedger, - app_.validators().getTrustedMasterKeys(), + app_.getValidators().getTrustedMasterKeys(), app_.getValidations(), initialSet); } @@ -355,7 +355,7 @@ RCLConsensus::Adaptor::onClose( RCLCxPeerPos::Proposal::seqJoin, setHash, closeTime, - app_.timeKeeper().closeTime(), + app_.getTimeKeeper().closeTime(), validatorKeys_.nodeID}}; } @@ -496,7 +496,7 @@ RCLConsensus::Adaptor::doAccept( censorshipDetector_.check( std::move(accepted), - [curr = built.seq(), j = app_.journal("CensorshipDetector"), &failed]( + [curr = built.seq(), j = app_.getJournal("CensorshipDetector"), &failed]( uint256 const& id, LedgerIndex seq) { if (failed.contains(id)) return true; @@ -592,7 +592,7 @@ RCLConsensus::Adaptor::doAccept( { rules.emplace(app_.config().features); } - app_.openLedger().accept( + app_.getOpenLedger().accept( app_, *rules, built.ledger_, @@ -620,7 +620,7 @@ RCLConsensus::Adaptor::doAccept( ledgerMaster_.getClosedLedger()->header().hash == built.id(), "xrpl::RCLConsensus::Adaptor::doAccept : ledger hash match"); XRPL_ASSERT( - app_.openLedger().current()->header().parentHash == built.id(), + app_.getOpenLedger().current()->header().parentHash == built.id(), "xrpl::RCLConsensus::Adaptor::doAccept : parent hash match"); } @@ -655,7 +655,7 @@ RCLConsensus::Adaptor::doAccept( JLOG(j_.info()) << "Our close offset is estimated at " << offset.count() << " (" << closeCount << ")"; - app_.timeKeeper().adjustCloseTime(offset); + app_.getTimeKeeper().adjustCloseTime(offset); } } @@ -677,7 +677,7 @@ RCLConsensus::Adaptor::notify( } s.set_ledgerseq(ledger.seq()); - s.set_networktime(app_.timeKeeper().now().time_since_epoch().count()); + s.set_networktime(app_.getTimeKeeper().now().time_since_epoch().count()); s.set_ledgerhashprevious( ledger.parentID().begin(), std::decay_t::bytes); s.set_ledgerhash(ledger.id().begin(), std::decay_t::bytes); @@ -695,7 +695,7 @@ RCLConsensus::Adaptor::notify( } s.set_firstseq(uMin); s.set_lastseq(uMax); - app_.overlay().foreach(send_always(std::make_shared(s, protocol::mtSTATUS_CHANGE))); + app_.getOverlay().foreach(send_always(std::make_shared(s, protocol::mtSTATUS_CHANGE))); JLOG(j_.trace()) << "send status change to peer"; } @@ -751,7 +751,7 @@ RCLConsensus::Adaptor::validate(RCLCxLedger const& ledger, RCLTxSet const& txns, { using namespace std::chrono_literals; - auto validationTime = app_.timeKeeper().closeTime(); + auto validationTime = app_.getTimeKeeper().closeTime(); if (validationTime <= lastValidationTime_) validationTime = lastValidationTime_ + 1s; lastValidationTime_ = validationTime; @@ -827,7 +827,7 @@ RCLConsensus::Adaptor::validate(RCLCxLedger const& ledger, RCLTxSet const& txns, // Broadcast to all our peers: protocol::TMValidation val; val.set_validation(serialized.data(), serialized.size()); - app_.overlay().broadcast(val); + app_.getOverlay().broadcast(val); // Publish to all our subscribers: app_.getOPs().pubValidation(v); @@ -925,11 +925,11 @@ RCLConsensus::Adaptor::preStartRound(RCLCxLedger const& prevLgr, hash_set> RCLConsensus::Adaptor::getQuorumKeys() const { - return app_.validators().getQuorumKeys(); + return app_.getValidators().getQuorumKeys(); } std::size_t diff --git a/src/xrpld/app/consensus/RCLValidations.cpp b/src/xrpld/app/consensus/RCLValidations.cpp index a968acb1a7..27fba69bb6 100644 --- a/src/xrpld/app/consensus/RCLValidations.cpp +++ b/src/xrpld/app/consensus/RCLValidations.cpp @@ -6,7 +6,6 @@ #include #include -#include #include #include #include @@ -100,7 +99,7 @@ RCLValidationsAdaptor::RCLValidationsAdaptor(Application& app, beast::Journal j) NetClock::time_point RCLValidationsAdaptor::now() const { - return app_.timeKeeper().closeTime(); + return app_.getTimeKeeper().closeTime(); } std::optional @@ -148,14 +147,14 @@ handleNewValidation( auto const seq = val->getFieldU32(sfLedgerSequence); // Ensure validation is marked as trusted if signer currently trusted - auto masterKey = app.validators().getTrustedKey(signingKey); + auto masterKey = app.getValidators().getTrustedKey(signingKey); if (!val->isTrusted() && masterKey) val->setTrusted(); // If not currently trusted, see if signer is currently listed if (!masterKey) - masterKey = app.validators().getListedKey(signingKey); + masterKey = app.getValidators().getListedKey(signingKey); auto& validations = app.getValidations(); diff --git a/src/xrpld/app/ledger/ConsensusTransSetSF.cpp b/src/xrpld/app/ledger/ConsensusTransSetSF.cpp index 48080aaedb..2313d29f86 100644 --- a/src/xrpld/app/ledger/ConsensusTransSetSF.cpp +++ b/src/xrpld/app/ledger/ConsensusTransSetSF.cpp @@ -2,7 +2,6 @@ #include #include -#include #include #include #include @@ -12,7 +11,7 @@ namespace xrpl { ConsensusTransSetSF::ConsensusTransSetSF(Application& app, NodeCache& nodeCache) - : app_(app), m_nodeCache(nodeCache), j_(app.journal("TransactionAcquire")) + : app_(app), m_nodeCache(nodeCache), j_(app.getJournal("TransactionAcquire")) { } diff --git a/src/xrpld/app/ledger/LedgerHistory.cpp b/src/xrpld/app/ledger/LedgerHistory.cpp index 15abd8c5c7..b96760f04d 100644 --- a/src/xrpld/app/ledger/LedgerHistory.cpp +++ b/src/xrpld/app/ledger/LedgerHistory.cpp @@ -3,7 +3,6 @@ #include #include -#include #include #include #include @@ -21,14 +20,14 @@ LedgerHistory::LedgerHistory(beast::insight::Collector::ptr const& collector, Ap app_.config().getValueFor(SizedItem::ledgerSize), std::chrono::seconds{app_.config().getValueFor(SizedItem::ledgerAge)}, stopwatch(), - app_.journal("TaggedCache")) + app_.getJournal("TaggedCache")) , m_consensus_validated( "ConsensusValidated", 64, std::chrono::minutes{5}, stopwatch(), - app_.journal("TaggedCache")) - , j_(app.journal("LedgerHistory")) + app_.getJournal("TaggedCache")) + , j_(app.getJournal("LedgerHistory")) { } diff --git a/src/xrpld/app/ledger/OrderBookDBImpl.cpp b/src/xrpld/app/ledger/OrderBookDBImpl.cpp index f7e531f78a..7626d148bd 100644 --- a/src/xrpld/app/ledger/OrderBookDBImpl.cpp +++ b/src/xrpld/app/ledger/OrderBookDBImpl.cpp @@ -1,7 +1,6 @@ #include #include -#include #include #include #include @@ -14,7 +13,7 @@ OrderBookDBImpl::OrderBookDBImpl(ServiceRegistry& registry, OrderBookDBConfig co , pathSearchMax_(config.pathSearchMax) , standalone_(config.standalone) , seq_(0) - , j_(registry.journal("OrderBookDB")) + , j_(registry.getJournal("OrderBookDB")) { } diff --git a/src/xrpld/app/ledger/detail/InboundLedger.cpp b/src/xrpld/app/ledger/detail/InboundLedger.cpp index 764a19dd0b..4e7190c8c8 100644 --- a/src/xrpld/app/ledger/detail/InboundLedger.cpp +++ b/src/xrpld/app/ledger/detail/InboundLedger.cpp @@ -6,7 +6,6 @@ #include #include -#include #include #include #include @@ -66,7 +65,7 @@ InboundLedger::InboundLedger( hash, ledgerAcquireTimeout, {jtLEDGER_DATA, "InboundLedger", 5}, - app.journal("InboundLedger")) + app.getJournal("InboundLedger")) , m_clock(clock) , mHaveHeader(false) , mHaveState(false) @@ -121,7 +120,7 @@ InboundLedger::getPeerCount() const { auto const& peerIds = mPeerSet->getPeerIds(); return std::count_if(peerIds.begin(), peerIds.end(), [this](auto id) { - return (app_.overlay().findPeerByShortID(id) != nullptr); + return (app_.getOverlay().findPeerByShortID(id) != nullptr); }); } @@ -530,7 +529,7 @@ InboundLedger::trigger(std::shared_ptr const& peer, TriggerReason reason) auto packet = std::make_shared(tmBH, protocol::mtGET_OBJECTS); auto const& peerIds = mPeerSet->getPeerIds(); std::for_each(peerIds.begin(), peerIds.end(), [this, &packet](auto id) { - if (auto p = app_.overlay().findPeerByShortID(id)) + if (auto p = app_.getOverlay().findPeerByShortID(id)) { mByHash = false; p->send(packet); diff --git a/src/xrpld/app/ledger/detail/InboundLedgers.cpp b/src/xrpld/app/ledger/detail/InboundLedgers.cpp index be7577a2c3..3a83aa6018 100644 --- a/src/xrpld/app/ledger/detail/InboundLedgers.cpp +++ b/src/xrpld/app/ledger/detail/InboundLedgers.cpp @@ -3,7 +3,6 @@ #include #include -#include #include #include #include @@ -38,7 +37,7 @@ public: std::unique_ptr peerSetBuilder) : app_(app) , fetchRate_(clock.now()) - , j_(app.journal("InboundLedger")) + , j_(app.getJournal("InboundLedger")) , m_clock(clock) , mRecentFailures(clock) , mCounter(collector->make_counter("ledger_fetches")) diff --git a/src/xrpld/app/ledger/detail/InboundTransactions.cpp b/src/xrpld/app/ledger/detail/InboundTransactions.cpp index f27f2c33f0..064953f665 100644 --- a/src/xrpld/app/ledger/detail/InboundTransactions.cpp +++ b/src/xrpld/app/ledger/detail/InboundTransactions.cpp @@ -3,7 +3,6 @@ #include #include -#include #include #include #include @@ -54,7 +53,7 @@ public: , m_zeroSet(m_map[uint256()]) , m_gotSet(std::move(gotSet)) , m_peerSetBuilder(std::move(peerSetBuilder)) - , j_(app_.journal("InboundTransactions")) + , j_(app_.getJournal("InboundTransactions")) { m_zeroSet.mSet = std::make_shared(SHAMapType::TRANSACTION, uint256(), app_.getNodeFamily()); diff --git a/src/xrpld/app/ledger/detail/LedgerCleaner.cpp b/src/xrpld/app/ledger/detail/LedgerCleaner.cpp index 8f6e0fb188..af358fbfc6 100644 --- a/src/xrpld/app/ledger/detail/LedgerCleaner.cpp +++ b/src/xrpld/app/ledger/detail/LedgerCleaner.cpp @@ -280,7 +280,7 @@ private: doTxns = true; } - if (doNodes && !nodeLedger->walkLedger(app_.journal("Ledger"))) + if (doNodes && !nodeLedger->walkLedger(app_.getJournal("Ledger"))) { JLOG(j_.debug()) << "Ledger " << ledgerIndex << " is missing nodes"; app_.getLedgerMaster().clearLedger(ledgerIndex); diff --git a/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp b/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp index 367149b9d2..1d48a9741d 100644 --- a/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp +++ b/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp @@ -21,7 +21,7 @@ LedgerDeltaAcquire::LedgerDeltaAcquire( ledgerHash, LedgerReplayParameters::SUB_TASK_TIMEOUT, {jtREPLAY_TASK, "LedReplDelta", LedgerReplayParameters::MAX_QUEUED_TASKS}, - app.journal("LedgerReplayDelta")) + app.getJournal("LedgerReplayDelta")) , inboundLedgers_(inboundLedgers) , ledgerSeq_(ledgerSeq) , peerSet_(std::move(peerSet)) diff --git a/src/xrpld/app/ledger/detail/LedgerMaster.cpp b/src/xrpld/app/ledger/detail/LedgerMaster.cpp index 4d90cbddcd..52ccd27ba4 100644 --- a/src/xrpld/app/ledger/detail/LedgerMaster.cpp +++ b/src/xrpld/app/ledger/detail/LedgerMaster.cpp @@ -13,7 +13,6 @@ #include #include -#include #include #include #include @@ -95,7 +94,7 @@ LedgerMaster::LedgerMaster( 65536, std::chrono::seconds{45}, stopwatch, - app_.journal("TaggedCache")) + app_.getJournal("TaggedCache")) , m_stats(std::bind(&LedgerMaster::collect_metrics, this), collector) { } @@ -103,7 +102,7 @@ LedgerMaster::LedgerMaster( LedgerIndex LedgerMaster::getCurrentLedgerIndex() { - return app_.openLedger().current()->header().seq; + return app_.getOpenLedger().current()->header().seq; } LedgerIndex @@ -146,7 +145,7 @@ LedgerMaster::getPublishedLedgerAge() return weeks{2}; } - std::chrono::seconds ret = app_.timeKeeper().closeTime().time_since_epoch(); + std::chrono::seconds ret = app_.getTimeKeeper().closeTime().time_since_epoch(); ret -= pubClose; ret = (ret > 0s) ? ret : 0s; static std::chrono::seconds lastRet = -1s; @@ -171,7 +170,7 @@ LedgerMaster::getValidatedLedgerAge() return weeks{2}; } - std::chrono::seconds ret = app_.timeKeeper().closeTime().time_since_epoch(); + std::chrono::seconds ret = app_.getTimeKeeper().closeTime().time_since_epoch(); ret -= valClose; ret = (ret > 0s) ? ret : 0s; static std::chrono::seconds lastRet = -1s; @@ -217,7 +216,7 @@ LedgerMaster::setValidLedger(std::shared_ptr const& l) if (!standalone_) { - auto validations = app_.validators().negativeUNLFilter( + auto validations = app_.getValidators().negativeUNLFilter( app_.getValidations().getTrustedForLedger(l->header().hash, l->header().seq)); times.reserve(validations.size()); for (auto const& val : validations) @@ -229,7 +228,7 @@ LedgerMaster::setValidLedger(std::shared_ptr const& l) NetClock::time_point signTime; - if (!times.empty() && times.size() >= app_.validators().quorum()) + if (!times.empty() && times.size() >= app_.getValidators().quorum()) { // Calculate the sample median std::sort(times.begin(), times.end()); @@ -330,7 +329,7 @@ LedgerMaster::canBeCurrent(std::shared_ptr const& ledger) // we perform this check. Otherwise, we only do it if we've built a // few ledgers as our clock can be off when we first start up - auto closeTime = app_.timeKeeper().closeTime(); + auto closeTime = app_.getTimeKeeper().closeTime(); auto ledgerClose = ledger->header().parentCloseTime; using namespace std::chrono_literals; @@ -426,7 +425,7 @@ LedgerMaster::applyHeldTransactions() std::lock_guard sl(m_mutex); // VFALCO NOTE The hash for an open ledger is undefined so we use // something that is a reasonable substitute. - CanonicalTXSet set(app_.openLedger().current()->header().parentHash); + CanonicalTXSet set(app_.getOpenLedger().current()->header().parentHash); std::swap(mHeldTransactions, set); return set; }(); @@ -546,7 +545,7 @@ LedgerMaster::getValidatedRange(std::uint32_t& minVal, std::uint32_t& maxVal) // Remove from the validated range any ledger sequences that may not be // fully updated in the database yet - auto const pendingSaves = app_.pendingSaves().getSnapshot(); + auto const pendingSaves = app_.getPendingSaves().getSnapshot(); if (!pendingSaves.empty() && ((minVal != 0) || (maxVal != 0))) { @@ -688,7 +687,7 @@ LedgerMaster::getFetchPack(LedgerIndex missing, InboundLedger::Reason reason) std::shared_ptr target; { int maxScore = 0; - auto peerList = app_.overlay().getActivePeers(); + auto peerList = app_.getOverlay().getActivePeers(); for (auto const& peer : peerList) { if (peer->hasRange(missing, missing + 1)) @@ -850,10 +849,10 @@ LedgerMaster::checkAccept(uint256 const& hash, std::uint32_t seq) if (seq < mValidLedgerSeq) return; - auto validations = app_.validators().negativeUNLFilter( + auto validations = app_.getValidators().negativeUNLFilter( app_.getValidations().getTrustedForLedger(hash, seq)); valCount = validations.size(); - if (valCount >= app_.validators().quorum()) + if (valCount >= app_.getValidators().quorum()) { std::lock_guard ml(m_mutex); if (seq > mLastValidLedger.second) @@ -875,8 +874,8 @@ LedgerMaster::checkAccept(uint256 const& hash, std::uint32_t seq) if ((seq != 0) && (getValidLedgerIndex() == 0)) { // Set peers converged early if we can - if (valCount >= app_.validators().quorum()) - app_.overlay().checkTracking(seq); + if (valCount >= app_.getValidators().quorum()) + app_.getOverlay().checkTracking(seq); } // FIXME: We may not want to fetch a ledger with just one @@ -896,7 +895,7 @@ LedgerMaster::checkAccept(uint256 const& hash, std::uint32_t seq) std::size_t LedgerMaster::getNeededValidations() { - return standalone_ ? 0 : app_.validators().quorum(); + return standalone_ ? 0 : app_.getValidators().quorum(); } void @@ -915,7 +914,7 @@ LedgerMaster::checkAccept(std::shared_ptr const& ledger) return; auto const minVal = getNeededValidations(); - auto validations = app_.validators().negativeUNLFilter( + auto validations = app_.getValidators().negativeUNLFilter( app_.getValidations().getTrustedForLedger(ledger->header().hash, ledger->header().seq)); auto const tvc = validations.size(); if (tvc < minVal) // nothing we can do @@ -979,7 +978,7 @@ LedgerMaster::checkAccept(std::shared_ptr const& ledger) // before checking the version information to accumulate more validation // messages. - auto currentTime = app_.timeKeeper().now(); + auto currentTime = app_.getTimeKeeper().now(); bool needPrint = false; // The variable upgradeWarningPrevTime_ will be set when and only when @@ -1008,7 +1007,7 @@ LedgerMaster::checkAccept(std::shared_ptr const& ledger) { constexpr std::size_t reportingPercent = 90; constexpr std::size_t cutoffPercent = 60; - auto const unlSize{app_.validators().getQuorumKeys().second.size()}; + auto const unlSize{app_.getValidators().getQuorumKeys().second.size()}; needPrint = unlSize > 0 && calculatePercent(vals.size(), unlSize) >= reportingPercent && calculatePercent(higherVersionCount, rippledCount) >= cutoffPercent; @@ -1055,7 +1054,7 @@ LedgerMaster::consensusBuilt( if (ledger->header().seq <= mValidLedgerSeq) { - auto stream = app_.journal("LedgerConsensus").info(); + auto stream = app_.getJournal("LedgerConsensus").info(); JLOG(stream) << "Consensus built old ledger: " << ledger->header().seq << " <= " << mValidLedgerSeq; return; @@ -1066,7 +1065,7 @@ LedgerMaster::consensusBuilt( if (ledger->header().seq <= mValidLedgerSeq) { - auto stream = app_.journal("LedgerConsensus").debug(); + auto stream = app_.getJournal("LedgerConsensus").debug(); JLOG(stream) << "Consensus ledger fully validated"; return; } @@ -1074,7 +1073,8 @@ LedgerMaster::consensusBuilt( // This ledger cannot be the new fully-validated ledger, but // maybe we saved up validations for some other ledger that can be - auto validations = app_.validators().negativeUNLFilter(app_.getValidations().currentTrusted()); + auto validations = + app_.getValidators().negativeUNLFilter(app_.getValidations().currentTrusted()); // Track validation counts with sequence numbers class valSeq @@ -1131,7 +1131,7 @@ LedgerMaster::consensusBuilt( if (maxSeq > mValidLedgerSeq) { - auto stream = app_.journal("LedgerConsensus").debug(); + auto stream = app_.getJournal("LedgerConsensus").debug(); JLOG(stream) << "Consensus triggered check of ledger"; checkAccept(maxLedger, maxSeq); } @@ -1362,7 +1362,7 @@ LedgerMaster::updatePaths() } else if (mPathFindNewRequest) { // We have a new request but no new ledger - lastLedger = app_.openLedger().current(); + lastLedger = app_.getOpenLedger().current(); } else { // Nothing to do @@ -1376,7 +1376,7 @@ LedgerMaster::updatePaths() if (!standalone_) { // don't pathfind with a ledger that's more than 60 seconds old using namespace std::chrono; - auto age = time_point_cast(app_.timeKeeper().closeTime()) - + auto age = time_point_cast(app_.getTimeKeeper().closeTime()) - lastLedger->header().closeTime; if (age > 1min) { @@ -1496,7 +1496,7 @@ LedgerMaster::peekMutex() std::shared_ptr LedgerMaster::getCurrentLedger() { - return app_.openLedger().current(); + return app_.getOpenLedger().current(); } std::shared_ptr diff --git a/src/xrpld/app/ledger/detail/LedgerPersistence.cpp b/src/xrpld/app/ledger/detail/LedgerPersistence.cpp index 651af1eec6..91de010f1d 100644 --- a/src/xrpld/app/ledger/detail/LedgerPersistence.cpp +++ b/src/xrpld/app/ledger/detail/LedgerPersistence.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -18,9 +17,9 @@ saveValidatedLedger( std::shared_ptr const& ledger, bool current) { - auto j = registry.journal("Ledger"); + auto j = registry.getJournal("Ledger"); auto seq = ledger->header().seq; - if (!registry.pendingSaves().startWork(seq)) + if (!registry.getPendingSaves().startWork(seq)) { // The save was completed synchronously JLOG(j.debug()) << "Save aborted"; @@ -33,7 +32,7 @@ saveValidatedLedger( // Clients can now trust the database for // information about this ledger sequence. - registry.pendingSaves().finishWork(seq); + registry.getPendingSaves().finishWork(seq); return res; } @@ -47,10 +46,10 @@ pendSaveValidated( if (!registry.getHashRouter().setFlags(ledger->header().hash, HashRouterFlags::SAVED)) { // We have tried to save this ledger recently - auto stream = registry.journal("Ledger").debug(); + auto stream = registry.getJournal("Ledger").debug(); JLOG(stream) << "Double pend save for " << ledger->header().seq; - if (!isSynchronous || !registry.pendingSaves().pending(ledger->header().seq)) + if (!isSynchronous || !registry.getPendingSaves().pending(ledger->header().seq)) { // Either we don't need it to be finished // or it is finished @@ -60,9 +59,9 @@ pendSaveValidated( XRPL_ASSERT(ledger->isImmutable(), "xrpl::pendSaveValidated : immutable ledger"); - if (!registry.pendingSaves().shouldWork(ledger->header().seq, isSynchronous)) + if (!registry.getPendingSaves().shouldWork(ledger->header().seq, isSynchronous)) { - auto stream = registry.journal("Ledger").debug(); + auto stream = registry.getJournal("Ledger").debug(); JLOG(stream) << "Pend save with seq in pending saves " << ledger->header().seq; return true; @@ -92,7 +91,13 @@ loadLedgerHelper( { bool loaded = false; auto ledger = std::make_shared( - info, loaded, acquire, rules, fees, registry.getNodeFamily(), registry.journal("Ledger")); + info, + loaded, + acquire, + rules, + fees, + registry.getNodeFamily(), + registry.getJournal("Ledger")); if (!loaded) ledger.reset(); @@ -137,7 +142,7 @@ loadByIndex( registry.getRelationalDatabase().getLedgerInfoByIndex(ledgerIndex)) { std::shared_ptr ledger = loadLedgerHelper(*info, rules, fees, registry, acquire); - finishLoadByIndexOrHash(ledger, registry.journal("Ledger")); + finishLoadByIndexOrHash(ledger, registry.getJournal("Ledger")); return ledger; } return {}; @@ -155,7 +160,7 @@ loadByHash( registry.getRelationalDatabase().getLedgerInfoByHash(ledgerHash)) { std::shared_ptr ledger = loadLedgerHelper(*info, rules, fees, registry, acquire); - finishLoadByIndexOrHash(ledger, registry.journal("Ledger")); + finishLoadByIndexOrHash(ledger, registry.getJournal("Ledger")); XRPL_ASSERT( !ledger || ledger->header().hash == ledgerHash, "xrpl::loadByHash : ledger hash match if loaded"); diff --git a/src/xrpld/app/ledger/detail/LedgerReplayMsgHandler.cpp b/src/xrpld/app/ledger/detail/LedgerReplayMsgHandler.cpp index 93cf0e5cce..a212629d28 100644 --- a/src/xrpld/app/ledger/detail/LedgerReplayMsgHandler.cpp +++ b/src/xrpld/app/ledger/detail/LedgerReplayMsgHandler.cpp @@ -10,7 +10,7 @@ namespace xrpl { LedgerReplayMsgHandler::LedgerReplayMsgHandler(Application& app, LedgerReplayer& replayer) - : app_(app), replayer_(replayer), journal_(app.journal("LedgerReplayMsgHandler")) + : app_(app), replayer_(replayer), journal_(app.getJournal("LedgerReplayMsgHandler")) { } diff --git a/src/xrpld/app/ledger/detail/LedgerReplayTask.cpp b/src/xrpld/app/ledger/detail/LedgerReplayTask.cpp index b878c840dd..6db0cebf1a 100644 --- a/src/xrpld/app/ledger/detail/LedgerReplayTask.cpp +++ b/src/xrpld/app/ledger/detail/LedgerReplayTask.cpp @@ -73,7 +73,7 @@ LedgerReplayTask::LedgerReplayTask( parameter.finishHash_, LedgerReplayParameters::TASK_TIMEOUT, {jtREPLAY_TASK, "LedReplTask", LedgerReplayParameters::MAX_QUEUED_TASKS}, - app.journal("LedgerReplayTask")) + app.getJournal("LedgerReplayTask")) , inboundLedgers_(inboundLedgers) , replayer_(replayer) , parameter_(parameter) diff --git a/src/xrpld/app/ledger/detail/LedgerReplayer.cpp b/src/xrpld/app/ledger/detail/LedgerReplayer.cpp index 553ff91174..9161c05d9a 100644 --- a/src/xrpld/app/ledger/detail/LedgerReplayer.cpp +++ b/src/xrpld/app/ledger/detail/LedgerReplayer.cpp @@ -11,7 +11,7 @@ LedgerReplayer::LedgerReplayer( : app_(app) , inboundLedgers_(inboundLedgers) , peerSetBuilder_(std::move(peerSetBuilder)) - , j_(app.journal("LedgerReplayer")) + , j_(app.getJournal("LedgerReplayer")) { } diff --git a/src/xrpld/app/ledger/detail/OpenLedger.cpp b/src/xrpld/app/ledger/detail/OpenLedger.cpp index 6e9b2c3f15..da35a72bbc 100644 --- a/src/xrpld/app/ledger/detail/OpenLedger.cpp +++ b/src/xrpld/app/ledger/detail/OpenLedger.cpp @@ -125,8 +125,8 @@ OpenLedger::accept( tx->add(s); msg.set_rawtransaction(s.data(), s.size()); msg.set_status(protocol::tsNEW); - msg.set_receivetimestamp(app.timeKeeper().now().time_since_epoch().count()); - app.overlay().relay(txId, msg, *toSkip); + msg.set_receivetimestamp(app.getTimeKeeper().now().time_since_epoch().count()); + app.getOverlay().relay(txId, msg, *toSkip); } } diff --git a/src/xrpld/app/ledger/detail/SkipListAcquire.cpp b/src/xrpld/app/ledger/detail/SkipListAcquire.cpp index 2191ef965a..3a60fbdc6d 100644 --- a/src/xrpld/app/ledger/detail/SkipListAcquire.cpp +++ b/src/xrpld/app/ledger/detail/SkipListAcquire.cpp @@ -16,7 +16,7 @@ SkipListAcquire::SkipListAcquire( ledgerHash, LedgerReplayParameters::SUB_TASK_TIMEOUT, {jtREPLAY_TASK, "SkipListAcq", LedgerReplayParameters::MAX_QUEUED_TASKS}, - app.journal("LedgerReplaySkipList")) + app.getJournal("LedgerReplaySkipList")) , inboundLedgers_(inboundLedgers) , peerSet_(std::move(peerSet)) { diff --git a/src/xrpld/app/ledger/detail/TransactionAcquire.cpp b/src/xrpld/app/ledger/detail/TransactionAcquire.cpp index 18c5066064..9cf35b93dc 100644 --- a/src/xrpld/app/ledger/detail/TransactionAcquire.cpp +++ b/src/xrpld/app/ledger/detail/TransactionAcquire.cpp @@ -30,7 +30,7 @@ TransactionAcquire::TransactionAcquire( hash, TX_ACQUIRE_TIMEOUT, {jtTXN_DATA, "TxAcq", {}}, - app.journal("TransactionAcquire")) + app.getJournal("TransactionAcquire")) , mHaveRoot(false) , mPeerSet(std::move(peerSet)) { diff --git a/src/xrpld/app/ledger/detail/TransactionMaster.cpp b/src/xrpld/app/ledger/detail/TransactionMaster.cpp index e3ebd443f1..4be3c95993 100644 --- a/src/xrpld/app/ledger/detail/TransactionMaster.cpp +++ b/src/xrpld/app/ledger/detail/TransactionMaster.cpp @@ -15,7 +15,7 @@ TransactionMaster::TransactionMaster(Application& app) 65536, std::chrono::minutes{30}, stopwatch(), - mApp.journal("TaggedCache")) + mApp.getJournal("TaggedCache")) { } diff --git a/src/xrpld/app/main/Application.cpp b/src/xrpld/app/main/Application.cpp index 2be94d24bf..39bb4d5b22 100644 --- a/src/xrpld/app/main/Application.cpp +++ b/src/xrpld/app/main/Application.cpp @@ -489,7 +489,7 @@ public: } Logs& - logs() override + getLogs() override { return *logs_; } @@ -513,7 +513,7 @@ public: } TimeKeeper& - timeKeeper() override + getTimeKeeper() override { return *timeKeeper_; } @@ -668,7 +668,7 @@ public: } CachedSLEs& - cachedSLEs() override + getCachedSLEs() override { return cachedSLEs_; } @@ -704,37 +704,37 @@ public: } ValidatorList& - validators() override + getValidators() override { return *validators_; } ValidatorSite& - validatorSites() override + getValidatorSites() override { return *validatorSites_; } ManifestCache& - validatorManifests() override + getValidatorManifests() override { return *validatorManifests_; } ManifestCache& - publisherManifests() override + getPublisherManifests() override { return *publisherManifests_; } Cluster& - cluster() override + getCluster() override { return *cluster_; } PeerReservationTable& - peerReservations() override + getPeerReservations() override { return *peerReservations_; } @@ -746,25 +746,25 @@ public: } PendingSaves& - pendingSaves() override + getPendingSaves() override { return pendingSaves_; } OpenLedger& - openLedger() override + getOpenLedger() override { return *openLedger_; } OpenLedger const& - openLedger() const override + getOpenLedger() const override { return *openLedger_; } Overlay& - overlay() override + getOverlay() override { XRPL_ASSERT(overlay_, "xrpl::ApplicationImp::overlay : non-null overlay"); return *overlay_; @@ -798,7 +798,7 @@ public: serverOkay(std::string& reason) override; beast::Journal - journal(std::string const& name) override; + getJournal(std::string const& name) override; //-------------------------------------------------------------------------- @@ -1074,7 +1074,7 @@ public: } virtual std::optional const& - trapTxID() const override + getTrapTxID() const override { return trapTxID_; } @@ -1110,7 +1110,7 @@ private: setMaxDisallowedLedger(); Application& - app() override + getApp() override { return *this; } @@ -1431,7 +1431,7 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) Resource::Charge loadType = Resource::feeReferenceRPC; Resource::Consumer c; RPC::JsonContext context{ - {journal("RPCHandler"), + {getJournal("RPCHandler"), *this, loadType, getOPs(), @@ -1547,11 +1547,11 @@ ApplicationImp::run() // TODO Store manifests in manifests.sqlite instead of wallet.db validatorManifests_->save(getWalletDB(), "ValidatorManifests", [this](PublicKey const& pubKey) { - return validators().listed(pubKey); + return getValidators().listed(pubKey); }); publisherManifests_->save(getWalletDB(), "PublisherManifests", [this](PublicKey const& pubKey) { - return validators().trustedPublisher(pubKey); + return getValidators().trustedPublisher(pubKey); }); // The order of these stop calls is delicate. @@ -1648,7 +1648,7 @@ ApplicationImp::startGenesisLedger() nodeFamily_); m_ledgerMaster->storeLedger(genesis); - auto const next = std::make_shared(*genesis, timeKeeper().closeTime()); + auto const next = std::make_shared(*genesis, getTimeKeeper().closeTime()); next->updateSkipList(); XRPL_ASSERT( next->header().seq < XRP_LEDGER_EARLIEST_FEES || next->read(keylet::fees()), @@ -1662,7 +1662,7 @@ ApplicationImp::startGenesisLedger() std::shared_ptr ApplicationImp::getLastFullLedger() { - auto j = journal("Ledger"); + auto j = getJournal("Ledger"); try { @@ -1735,7 +1735,7 @@ ApplicationImp::loadLedgerFromFile(std::string const& name) ledger = ledger.get()["ledger"]; std::uint32_t seq = 1; - auto closeTime = timeKeeper().closeTime(); + auto closeTime = getTimeKeeper().closeTime(); using namespace std::chrono_literals; auto closeTimeResolution = 30s; bool closeTimeEstimated = false; @@ -1967,7 +1967,7 @@ ApplicationImp::loadOldLedger( // LCOV_EXCL_STOP } - if (!loadLedger->walkLedger(journal("Ledger"), true)) + if (!loadLedger->walkLedger(getJournal("Ledger"), true)) { // LCOV_EXCL_START JLOG(m_journal.fatal()) << "Ledger is missing nodes."; @@ -2099,7 +2099,7 @@ ApplicationImp::serverOkay(std::string& reason) } beast::Journal -ApplicationImp::journal(std::string const& name) +ApplicationImp::getJournal(std::string const& name) { return logs_->journal(name); } diff --git a/src/xrpld/app/main/GRPCServer.cpp b/src/xrpld/app/main/GRPCServer.cpp index a9810ae22b..f95c20ba8c 100644 --- a/src/xrpld/app/main/GRPCServer.cpp +++ b/src/xrpld/app/main/GRPCServer.cpp @@ -120,7 +120,7 @@ GRPCServerImpl::CallData::process(std::shared_ptr::process(std::shared_ptr context{ - {app_.journal("gRPCServer"), + {app_.getJournal("gRPCServer"), app_, loadType, app_.getOPs(), @@ -285,7 +285,8 @@ GRPCServerImpl::CallData::getUsage() Throw("Failed to get client endpoint"); } -GRPCServerImpl::GRPCServerImpl(Application& app) : app_(app), journal_(app_.journal("gRPC Server")) +GRPCServerImpl::GRPCServerImpl(Application& app) + : app_(app), journal_(app_.getJournal("gRPC Server")) { // if present, get endpoint from config if (app_.config().exists(SECTION_PORT_GRPC)) diff --git a/src/xrpld/app/main/Main.cpp b/src/xrpld/app/main/Main.cpp index 88a335f843..e2bd4423d9 100644 --- a/src/xrpld/app/main/Main.cpp +++ b/src/xrpld/app/main/Main.cpp @@ -752,8 +752,6 @@ run(int argc, char** argv) // No arguments. Run server. if (!vm.contains("parameters")) { - // TODO: this comment can be removed in a future release - - // say 1.7 or higher if (config->had_trailing_comments()) { JLOG(logs->journal("Application").warn()) @@ -781,7 +779,7 @@ run(int argc, char** argv) // With our configuration parsed, ensure we have // enough file descriptors available: - if (!adjustDescriptorLimit(app->fdRequired(), app->logs().journal("Application"))) + if (!adjustDescriptorLimit(app->fdRequired(), app->getJournal("Application"))) return -1; // Start the server diff --git a/src/xrpld/app/misc/NetworkOPs.cpp b/src/xrpld/app/misc/NetworkOPs.cpp index c97eb65990..d7b42076c7 100644 --- a/src/xrpld/app/misc/NetworkOPs.cpp +++ b/src/xrpld/app/misc/NetworkOPs.cpp @@ -227,16 +227,16 @@ public: , clusterTimer_(io_svc) , accountHistoryTxTimer_(io_svc) , mConsensus( - registry_.app(), + registry_.getApp(), make_FeeVote( - setup_FeeVote(registry_.app().config().section("voting")), - registry_.logs().journal("FeeVote")), + setup_FeeVote(registry_.getApp().config().section("voting")), + registry_.getJournal("FeeVote")), ledgerMaster, *m_localTX, registry.getInboundTransactions(), beast::get_abstract_clock(), validatorKeys, - registry_.logs().journal("LedgerConsensus")) + registry_.getJournal("LedgerConsensus")) , validatorPK_( validatorKeys.keys ? validatorKeys.keys->publicKey : decltype(validatorPK_){}) , validatorMasterPK_( @@ -877,7 +877,7 @@ NetworkOPsImp::getHostId(bool forAdmin) // For non-admin uses hash the node public key into a // single RFC1751 word: static std::string const shroudedHostId = [this]() { - auto const& id = registry_.app().nodeIdentity(); + auto const& id = registry_.getApp().nodeIdentity(); return RFC1751::getWordFromBlob(id.first.data(), id.first.size()); }(); @@ -891,7 +891,7 @@ NetworkOPsImp::setStateTimer() setHeartbeatTimer(); // Only do this work if a cluster is configured - if (registry_.cluster().size() != 0) + if (registry_.getCluster().size() != 0) setClusterTimer(); } @@ -969,13 +969,13 @@ NetworkOPsImp::processHeartbeatTimer() { RclConsensusLogger clog("Heartbeat Timer", mConsensus.validating(), m_journal); { - std::unique_lock lock{registry_.app().getMasterMutex()}; + std::unique_lock lock{registry_.getApp().getMasterMutex()}; // VFALCO NOTE This is for diagnosing a crash on exit LoadManager& mgr(registry_.getLoadManager()); mgr.heartbeat(); - std::size_t const numPeers = registry_.overlay().size(); + std::size_t const numPeers = registry_.getOverlay().size(); // do we have sufficient peers? If not, we are disconnected. if (numPeers < minPeerCount_) @@ -1031,7 +1031,7 @@ NetworkOPsImp::processHeartbeatTimer() CLOG(clog.ss()) << ". "; } - mConsensus.timerEntry(registry_.timeKeeper().closeTime(), clog.ss()); + mConsensus.timerEntry(registry_.getTimeKeeper().closeTime(), clog.ss()); CLOG(clog.ss()) << "consensus phase " << to_string(mLastConsensusPhase); ConsensusPhase const currPhase = mConsensus.phase(); @@ -1049,17 +1049,17 @@ NetworkOPsImp::processHeartbeatTimer() void NetworkOPsImp::processClusterTimer() { - if (registry_.cluster().size() == 0) + if (registry_.getCluster().size() == 0) return; using namespace std::chrono_literals; - bool const update = registry_.cluster().update( - registry_.app().nodeIdentity().first, + bool const update = registry_.getCluster().update( + registry_.getApp().nodeIdentity().first, "", (m_ledgerMaster.getValidatedLedgerAge() <= 4min) ? registry_.getFeeTrack().getLocalFee() : 0, - registry_.timeKeeper().now()); + registry_.getTimeKeeper().now()); if (!update) { @@ -1069,7 +1069,7 @@ NetworkOPsImp::processClusterTimer() } protocol::TMCluster cluster; - registry_.cluster().for_each([&cluster](ClusterNode const& node) { + registry_.getCluster().for_each([&cluster](ClusterNode const& node) { protocol::TMClusterNode& n = *cluster.add_clusternodes(); n.set_publickey(toBase58(TokenType::NodePublic, node.identity())); n.set_reporttime(node.getReportTime().time_since_epoch().count()); @@ -1085,7 +1085,7 @@ NetworkOPsImp::processClusterTimer() node.set_name(to_string(item.address)); node.set_cost(item.balance); } - registry_.overlay().foreach( + registry_.getOverlay().foreach( send_if(std::make_shared(cluster, protocol::mtCLUSTER), peer_in_cluster())); setClusterTimer(); } @@ -1159,7 +1159,7 @@ NetworkOPsImp::submitTransaction(std::shared_ptr const& iTrans) std::string reason; - auto tx = std::make_shared(trans, reason, registry_.app()); + auto tx = std::make_shared(trans, reason, registry_.getApp()); m_job_queue.addJob(jtTRANSACTION, "SubmitTxn", [this, tx]() { auto t = tx; @@ -1320,7 +1320,7 @@ NetworkOPsImp::processTransactionSet(CanonicalTXSet const& set) for (auto const& [_, tx] : set) { std::string reason; - auto transaction = std::make_shared(tx, reason, registry_.app()); + auto transaction = std::make_shared(tx, reason, registry_.getApp()); if (transaction->getStatus() == INVALID) { @@ -1406,13 +1406,13 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) batchLock.unlock(); { - std::unique_lock masterLock{registry_.app().getMasterMutex(), std::defer_lock}; + std::unique_lock masterLock{registry_.getApp().getMasterMutex(), std::defer_lock}; bool changed = false; { std::unique_lock ledgerLock{m_ledgerMaster.peekMutex(), std::defer_lock}; std::lock(masterLock, ledgerLock); - registry_.openLedger().modify([&](OpenView& view, beast::Journal j) { + registry_.getOpenLedger().modify([&](OpenView& view, beast::Journal j) { for (TransactionStatus& e : transactions) { // we check before adding to the batch @@ -1424,7 +1424,7 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) flags |= tapFAIL_HARD; auto const result = registry_.getTxQ().apply( - registry_.app(), view, e.transaction->getSTransaction(), flags, j); + registry_.getApp(), view, e.transaction->getSTransaction(), flags, j); e.result = result.ter; e.applied = result.applied; changed = changed || result.applied; @@ -1439,7 +1439,7 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) if (auto const l = m_ledgerMaster.getValidatedLedger()) validatedLedgerIndex = l->header().seq; - auto newOL = registry_.openLedger().current(); + auto newOL = registry_.getOpenLedger().current(); for (TransactionStatus& e : transactions) { e.transaction->clearSubmitResult(); @@ -1488,7 +1488,7 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) batchLock.lock(); std::string reason; auto const trans = sterilize(*txNext); - auto t = std::make_shared(trans, reason, registry_.app()); + auto t = std::make_shared(trans, reason, registry_.getApp()); if (t->getApplying()) break; submit_held.emplace_back(t, false, false, FailHard::no); @@ -1594,10 +1594,10 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) tx.set_rawtransaction(s.data(), s.size()); tx.set_status(protocol::tsCURRENT); tx.set_receivetimestamp( - registry_.timeKeeper().now().time_since_epoch().count()); + registry_.getTimeKeeper().now().time_since_epoch().count()); tx.set_deferred(e.result == terQUEUED); // FIXME: This should be when we received it - registry_.overlay().relay(e.transaction->getID(), tx, *toSkip); + registry_.getOverlay().relay(e.transaction->getID(), tx, *toSkip); e.transaction->setBroadcast(); } } @@ -1874,7 +1874,7 @@ NetworkOPsImp::switchLastClosedLedger(std::shared_ptr const& newLC clearNeedNetworkLedger(); // Update fee computations. - registry_.getTxQ().processClosedLedger(registry_.app(), *newLCL, true); + registry_.getTxQ().processClosedLedger(registry_.getApp(), *newLCL, true); // Caller must own master lock { @@ -1886,14 +1886,14 @@ NetworkOPsImp::switchLastClosedLedger(std::shared_ptr const& newLC std::optional rules; if (lastVal) { - rules = makeRulesGivenLedger(*lastVal, registry_.app().config().features); + rules = makeRulesGivenLedger(*lastVal, registry_.getApp().config().features); } else { - rules.emplace(registry_.app().config().features); + rules.emplace(registry_.getApp().config().features); } - registry_.openLedger().accept( - registry_.app(), + registry_.getOpenLedger().accept( + registry_.getApp(), *rules, newLCL, OrderedTxs({}), @@ -1903,7 +1903,7 @@ NetworkOPsImp::switchLastClosedLedger(std::shared_ptr const& newLC "jump", [&](OpenView& view, beast::Journal j) { // Stuff the ledger with transactions from the queue. - return registry_.getTxQ().accept(registry_.app(), view); + return registry_.getTxQ().accept(registry_.getApp(), view); }); } @@ -1912,12 +1912,12 @@ NetworkOPsImp::switchLastClosedLedger(std::shared_ptr const& newLC protocol::TMStatusChange s; s.set_newevent(protocol::neSWITCHED_LEDGER); s.set_ledgerseq(newLCL->header().seq); - s.set_networktime(registry_.timeKeeper().now().time_since_epoch().count()); + s.set_networktime(registry_.getTimeKeeper().now().time_since_epoch().count()); s.set_ledgerhashprevious( newLCL->header().parentHash.begin(), newLCL->header().parentHash.size()); s.set_ledgerhash(newLCL->header().hash.begin(), newLCL->header().hash.size()); - registry_.overlay().foreach( + registry_.getOverlay().foreach( send_always(std::make_shared(s, protocol::mtSTATUS_CHANGE))); } @@ -1958,23 +1958,24 @@ NetworkOPsImp::beginConsensus( "xrpl::NetworkOPsImp::beginConsensus : closedLedger parent matches " "hash"); - registry_.validators().setNegativeUNL(prevLedger->negativeUNL()); - TrustChanges const changes = registry_.validators().updateTrusted( + registry_.getValidators().setNegativeUNL(prevLedger->negativeUNL()); + TrustChanges const changes = registry_.getValidators().updateTrusted( registry_.getValidations().getCurrentNodeIDs(), closingInfo.parentCloseTime, *this, - registry_.overlay(), + registry_.getOverlay(), registry_.getHashRouter()); if (!changes.added.empty() || !changes.removed.empty()) { registry_.getValidations().trustChanged(changes.added, changes.removed); // Update the AmendmentTable so it tracks the current validators. - registry_.getAmendmentTable().trustChanged(registry_.validators().getQuorumKeys().second); + registry_.getAmendmentTable().trustChanged( + registry_.getValidators().getQuorumKeys().second); } mConsensus.startRound( - registry_.timeKeeper().closeTime(), + registry_.getTimeKeeper().closeTime(), networkClosed, prevLedger, changes.removed, @@ -2014,7 +2015,7 @@ NetworkOPsImp::processTrustedProposal(RCLCxPeerPos peerPos) return false; } - return mConsensus.peerProposal(registry_.timeKeeper().closeTime(), peerPos); + return mConsensus.peerProposal(registry_.getTimeKeeper().closeTime(), peerPos); } void @@ -2028,11 +2029,12 @@ NetworkOPsImp::mapComplete(std::shared_ptr const& map, bool fromAcquire) protocol::TMHaveTransactionSet msg; msg.set_hash(map->getHash().as_uint256().begin(), 256 / 8); msg.set_status(protocol::tsHAVE); - registry_.overlay().foreach(send_always(std::make_shared(msg, protocol::mtHAVE_SET))); + registry_.getOverlay().foreach( + send_always(std::make_shared(msg, protocol::mtHAVE_SET))); // We acquired it because consensus asked us to if (fromAcquire) - mConsensus.gotTxSet(registry_.timeKeeper().closeTime(), RCLTxSet{map}); + mConsensus.gotTxSet(registry_.getTimeKeeper().closeTime(), RCLTxSet{map}); } void @@ -2040,7 +2042,7 @@ NetworkOPsImp::endConsensus(std::unique_ptr const& clog) { uint256 deadLedger = m_ledgerMaster.getClosedLedger()->header().parentHash; - for (auto const& it : registry_.overlay().getActivePeers()) + for (auto const& it : registry_.getOverlay().getActivePeers()) { if (it && (it->getClosedLedgerHash() == deadLedger)) { @@ -2050,7 +2052,8 @@ NetworkOPsImp::endConsensus(std::unique_ptr const& clog) } uint256 networkClosed; - bool ledgerChange = checkLastClosedLedger(registry_.overlay().getActivePeers(), networkClosed); + bool ledgerChange = + checkLastClosedLedger(registry_.getOverlay().getActivePeers(), networkClosed); if (networkClosed.isZero()) { @@ -2080,7 +2083,7 @@ NetworkOPsImp::endConsensus(std::unique_ptr const& clog) // Note: Do not go to FULL if we don't have the previous ledger // check if the ledger is bad enough to go to CONNECTED -- TODO auto current = m_ledgerMaster.getCurrentLedger(); - if (registry_.timeKeeper().now() < + if (registry_.getTimeKeeper().now() < (current->header().parentCloseTime + 2 * current->header().closeTimeResolution)) { setMode(OperatingMode::FULL); @@ -2188,8 +2191,8 @@ NetworkOPsImp::pubServer() Json::Value jvObj(Json::objectValue); ServerFeeSummary f{ - registry_.openLedger().current()->fees().base, - registry_.getTxQ().getMetrics(*registry_.openLedger().current()), + registry_.getOpenLedger().current()->fees().base, + registry_.getTxQ().getMetrics(*registry_.getOpenLedger().current()), registry_.getFeeTrack()}; jvObj[jss::type] = "serverStatus"; @@ -2295,7 +2298,7 @@ NetworkOPsImp::pubValidation(std::shared_ptr const& val) if (auto hash = (*val)[~sfValidatedHash]) jvObj[jss::validated_hash] = strHex(*hash); - auto const masterKey = registry_.validatorManifests().getMasterKey(signerPublic); + auto const masterKey = registry_.getValidatorManifests().getMasterKey(signerPublic); if (masterKey != signerPublic) jvObj[jss::master_key] = toBase58(TokenType::NodePublic, masterKey); @@ -2445,7 +2448,7 @@ NetworkOPsImp::recvValidation(std::shared_ptr const& val, std::str pendingValidations_.insert(val->getLedgerHash()); } scope_unlock unlock(lock); - handleNewValidation(registry_.app(), val, source, bypassAccept, m_journal); + handleNewValidation(registry_.getApp(), val, source, bypassAccept, m_journal); } catch (std::exception const& e) { @@ -2468,7 +2471,7 @@ NetworkOPsImp::recvValidation(std::shared_ptr const& val, std::str JLOG(m_journal.debug()) << [this, &val]() -> auto { std::stringstream ss; ss << "VALIDATION: " << val->render() << " master_key: "; - auto master = registry_.validators().getTrustedKey(val->getSignerPublic()); + auto master = registry_.getValidators().getTrustedKey(val->getSignerPublic()); if (master) { ss << toBase58(TokenType::NodePublic, *master); @@ -2482,7 +2485,7 @@ NetworkOPsImp::recvValidation(std::shared_ptr const& val, std::str // We will always relay trusted validations; if configured, we will // also relay all untrusted validations. - return registry_.app().config().RELAY_UNTRUSTED_VALIDATIONS == 1 || val->isTrusted(); + return registry_.getApp().config().RELAY_UNTRUSTED_VALIDATIONS == 1 || val->isTrusted(); } Json::Value @@ -2541,8 +2544,8 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) info[jss::hostid] = getHostId(admin); // domain: if configured with a domain, report it: - if (!registry_.app().config().SERVER_DOMAIN.empty()) - info[jss::server_domain] = registry_.app().config().SERVER_DOMAIN; + if (!registry_.getApp().config().SERVER_DOMAIN.empty()) + info[jss::server_domain] = registry_.getApp().config().SERVER_DOMAIN; info[jss::build_version] = BuildInfo::getVersionString(); @@ -2554,14 +2557,14 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) if (needNetworkLedger_) info[jss::network_ledger] = "waiting"; - info[jss::validation_quorum] = static_cast(registry_.validators().quorum()); + info[jss::validation_quorum] = static_cast(registry_.getValidators().quorum()); if (admin) { // Note: By default the node size is "tiny". When parsing it's an error if the final // NODE_SIZE is over 4 so below code should be safe. // NOLINTNEXTLINE(bugprone-switch-missing-default-case) - switch (registry_.app().config().NODE_SIZE) + switch (registry_.getApp().config().NODE_SIZE) { case 0: info[jss::node_size] = "tiny"; @@ -2580,7 +2583,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) break; } - auto when = registry_.validators().expires(); + auto when = registry_.getValidators().expires(); if (!human) { @@ -2598,7 +2601,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) { auto& x = (info[jss::validator_list] = Json::objectValue); - x[jss::count] = static_cast(registry_.validators().count()); + x[jss::count] = static_cast(registry_.getValidators().count()); if (when) { @@ -2611,7 +2614,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) { x[jss::expiration] = to_string(*when); - if (*when > registry_.timeKeeper().now()) + if (*when > registry_.getTimeKeeper().now()) { x[jss::status] = "active"; } @@ -2637,12 +2640,12 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) x[jss::branch] = xrpl::git::getBuildBranch(); } } - info[jss::io_latency_ms] = static_cast(registry_.app().getIOLatency().count()); + info[jss::io_latency_ms] = static_cast(registry_.getApp().getIOLatency().count()); if (admin) { - if (auto const localPubKey = registry_.validators().localPublicKey(); - localPubKey && registry_.app().getValidationPublicKey()) + if (auto const localPubKey = registry_.getValidators().localPublicKey(); + localPubKey && registry_.getApp().getValidationPublicKey()) { info[jss::pubkey_validator] = toBase58(TokenType::NodePublic, localPubKey.value()); } @@ -2662,7 +2665,8 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) info[jss::current_activities] = registry_.getPerfLog().currentJson(); } - info[jss::pubkey_node] = toBase58(TokenType::NodePublic, registry_.app().nodeIdentity().first); + info[jss::pubkey_node] = + toBase58(TokenType::NodePublic, registry_.getApp().nodeIdentity().first); info[jss::complete_ledgers] = registry_.getLedgerMaster().getCompleteLedgers(); @@ -2674,7 +2678,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) if (fp != 0) info[jss::fetch_pack] = Json::UInt(fp); - info[jss::peers] = Json::UInt(registry_.overlay().size()); + info[jss::peers] = Json::UInt(registry_.getOverlay().size()); Json::Value lastClose = Json::objectValue; lastClose[jss::proposers] = Json::UInt(mConsensus.prevProposers()); @@ -2696,10 +2700,11 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) if (admin) info[jss::load] = m_job_queue.getJson(); - if (auto const netid = registry_.overlay().networkID()) + if (auto const netid = registry_.getOverlay().networkID()) info[jss::network_id] = static_cast(*netid); - auto const escalationMetrics = registry_.getTxQ().getMetrics(*registry_.openLedger().current()); + auto const escalationMetrics = + registry_.getTxQ().getMetrics(*registry_.getOpenLedger().current()); auto const loadFactorServer = registry_.getFeeTrack().getLoadFactor(); auto const loadBaseServer = registry_.getFeeTrack().getLoadBase(); @@ -2797,7 +2802,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) l[jss::reserve_base_xrp] = lpClosed->fees().reserve.decimalXRP(); l[jss::reserve_inc_xrp] = lpClosed->fees().increment.decimalXRP(); - if (auto const closeOffset = registry_.timeKeeper().closeOffset(); + if (auto const closeOffset = registry_.getTimeKeeper().closeOffset(); std::abs(closeOffset.count()) >= 60) l[jss::close_time_offset] = static_cast(closeOffset.count()); @@ -2810,7 +2815,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) else { auto lCloseTime = lpClosed->header().closeTime; - auto closeTime = registry_.timeKeeper().closeTime(); + auto closeTime = registry_.getTimeKeeper().closeTime(); if (lCloseTime <= closeTime) { using namespace std::chrono_literals; @@ -2842,10 +2847,10 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) accounting_.json(info); info[jss::uptime] = UptimeClock::now().time_since_epoch().count(); - info[jss::jq_trans_overflow] = std::to_string(registry_.overlay().getJqTransOverflow()); - info[jss::peer_disconnects] = std::to_string(registry_.overlay().getPeerDisconnect()); + info[jss::jq_trans_overflow] = std::to_string(registry_.getOverlay().getJqTransOverflow()); + info[jss::peer_disconnects] = std::to_string(registry_.getOverlay().getPeerDisconnect()); info[jss::peer_disconnects_resources] = - std::to_string(registry_.overlay().getPeerDisconnectCharges()); + std::to_string(registry_.getOverlay().getPeerDisconnectCharges()); // This array must be sorted in increasing order. static constexpr std::array protocols{ @@ -2877,9 +2882,9 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) } } - if (registry_.app().config().exists(SECTION_PORT_GRPC)) + if (registry_.getApp().config().exists(SECTION_PORT_GRPC)) { - auto const& grpcSection = registry_.app().config().section(SECTION_PORT_GRPC); + auto const& grpcSection = registry_.getApp().config().section(SECTION_PORT_GRPC); auto const optPort = grpcSection.get("port"); if (optPort && grpcSection.get("ip")) { @@ -3066,8 +3071,8 @@ void NetworkOPsImp::reportFeeChange() { ServerFeeSummary f{ - registry_.openLedger().current()->fees().base, - registry_.getTxQ().getMetrics(*registry_.openLedger().current()), + registry_.getOpenLedger().current()->fees().base, + registry_.getTxQ().getMetrics(*registry_.getOpenLedger().current()), registry_.getFeeTrack()}; // only schedule the job if something has changed @@ -3168,8 +3173,8 @@ NetworkOPsImp::transJson( // If the offer create is not self funded then add the owner balance if (account != amount.issue().account) { - auto const ownerFunds = - accountFunds(*ledger, account, amount, fhIGNORE_FREEZE, registry_.journal("View")); + auto const ownerFunds = accountFunds( + *ledger, account, amount, fhIGNORE_FREEZE, registry_.getJournal("View")); jvObj[jss::transaction][jss::owner_funds] = ownerFunds.getText(); } } @@ -3994,7 +3999,7 @@ NetworkOPsImp::acceptLedger(std::optional consensusDe // FIXME Could we improve on this and remove the need for a specialized // API in Consensus? beginConsensus(m_ledgerMaster.getClosedLedger()->header().hash, {}); - mConsensus.simulate(registry_.timeKeeper().closeTime(), consensusDelay); + mConsensus.simulate(registry_.getTimeKeeper().closeTime(), consensusDelay); return m_ledgerMaster.getCurrentLedger()->header().seq; } @@ -4084,7 +4089,7 @@ NetworkOPsImp::subServer(InfoSub::ref isrListener, Json::Value& jvResult, bool a jvResult[jss::load_factor] = feeTrack.getLoadFactor(); jvResult[jss::hostid] = getHostId(admin); jvResult[jss::pubkey_node] = - toBase58(TokenType::NodePublic, registry_.app().nodeIdentity().first); + toBase58(TokenType::NodePublic, registry_.getApp().nodeIdentity().first); std::lock_guard sl(mSubLock); return mStreamMaps[sServer].emplace(isrListener->getSeq(), isrListener).second; @@ -4271,7 +4276,7 @@ NetworkOPsImp::getBookPage( STAmount saDirRate; auto const rate = transferRate(view, book.out.account); - auto viewJ = registry_.journal("View"); + auto viewJ = registry_.getJournal("View"); while (!bDone && iLimit-- > 0) { diff --git a/src/xrpld/app/misc/SHAMapStoreImp.cpp b/src/xrpld/app/misc/SHAMapStoreImp.cpp index 2865f964de..6460d99686 100644 --- a/src/xrpld/app/misc/SHAMapStoreImp.cpp +++ b/src/xrpld/app/misc/SHAMapStoreImp.cpp @@ -158,7 +158,7 @@ SHAMapStoreImp::makeNodeStore(int readThreads) std::move(writableBackend), std::move(archiveBackend), nscfg, - app_.logs().journal(nodeStoreName_)); + app_.getJournal(nodeStoreName_)); fdRequired_ += dbr->fdRequired(); dbRotating_ = dbr.get(); db.reset(dynamic_cast(dbr.release())); @@ -170,7 +170,7 @@ SHAMapStoreImp::makeNodeStore(int readThreads) scheduler_, readThreads, nscfg, - app_.logs().journal(nodeStoreName_)); + app_.getJournal(nodeStoreName_)); fdRequired_ += db->fdRequired(); } return db; @@ -453,7 +453,7 @@ SHAMapStoreImp::makeBackendRotating(std::string path) section, megabytes(app_.config().getValueFor(SizedItem::burstSize, std::nullopt)), scheduler_, - app_.logs().journal(nodeStoreName_))}; + app_.getJournal(nodeStoreName_))}; backend->open(); return backend; } diff --git a/src/xrpld/app/misc/detail/Transaction.cpp b/src/xrpld/app/misc/detail/Transaction.cpp index 6eefd08369..f0cabf0fa6 100644 --- a/src/xrpld/app/misc/detail/Transaction.cpp +++ b/src/xrpld/app/misc/detail/Transaction.cpp @@ -16,7 +16,7 @@ Transaction::Transaction( std::shared_ptr const& stx, std::string& reason, Application& app) noexcept - : mTransaction(stx), mApp(app), j_(app.journal("Ledger")) + : mTransaction(stx), mApp(app), j_(app.getJournal("Ledger")) { try { diff --git a/src/xrpld/app/misc/detail/TxQ.cpp b/src/xrpld/app/misc/detail/TxQ.cpp index 78e8ccdba5..c03ef6872e 100644 --- a/src/xrpld/app/misc/detail/TxQ.cpp +++ b/src/xrpld/app/misc/detail/TxQ.cpp @@ -1770,7 +1770,7 @@ TxQ::getTxs() const Json::Value TxQ::doRPC(Application& app) const { - auto const view = app.openLedger().current(); + auto const view = app.getOpenLedger().current(); if (!view) { BOOST_ASSERT(false); diff --git a/src/xrpld/app/misc/detail/ValidatorSite.cpp b/src/xrpld/app/misc/detail/ValidatorSite.cpp index 8db29c0bb0..91352cb12d 100644 --- a/src/xrpld/app/misc/detail/ValidatorSite.cpp +++ b/src/xrpld/app/misc/detail/ValidatorSite.cpp @@ -72,7 +72,7 @@ ValidatorSite::ValidatorSite( std::optional j, std::chrono::seconds timeout) : app_{app} - , j_{j ? *j : app_.logs().journal("ValidatorSite")} + , j_{j ? *j : app_.getJournal("ValidatorSite")} , timer_{app_.getIOContext()} , fetching_{false} , pending_{false} @@ -101,7 +101,7 @@ ValidatorSite::~ValidatorSite() bool ValidatorSite::missingSite(std::lock_guard const& lock_sites) { - auto const sites = app_.validators().loadLists(); + auto const sites = app_.getValidators().loadLists(); return sites.empty() || load(sites, lock_sites); } @@ -394,8 +394,15 @@ ValidatorSite::parseJsonResponse( "xrpl::ValidatorSite::parseJsonResponse : version match"); auto const& uri = sites_[siteIdx].activeResource->uri; auto const hash = sha512Half(manifest, blobs, version); - auto const applyResult = app_.validators().applyListsAndBroadcast( - manifest, version, blobs, uri, hash, app_.overlay(), app_.getHashRouter(), app_.getOPs()); + auto const applyResult = app_.getValidators().applyListsAndBroadcast( + manifest, + version, + blobs, + uri, + hash, + app_.getOverlay(), + app_.getHashRouter(), + app_.getOPs()); sites_[siteIdx].lastRefreshStatus.emplace( Site::Status{clock_type::now(), applyResult.bestDisposition(), ""}); diff --git a/src/xrpld/app/rdb/backend/detail/Node.cpp b/src/xrpld/app/rdb/backend/detail/Node.cpp index b4f852a9e5..66b75e72de 100644 --- a/src/xrpld/app/rdb/backend/detail/Node.cpp +++ b/src/xrpld/app/rdb/backend/detail/Node.cpp @@ -169,7 +169,7 @@ saveValidatedLedger( std::shared_ptr const& ledger, bool current) { - auto j = app.journal("Ledger"); + auto j = app.getJournal("Ledger"); auto seq = ledger->header().seq; // TODO(tom): Fix this hard-coded SQL! @@ -222,7 +222,7 @@ saveValidatedLedger( app.getLedgerMaster().failedSave(seq, ledger->header().hash); // Clients can now trust the database for information about this // ledger sequence. - app.pendingSaves().finishWork(seq); + app.getPendingSaves().finishWork(seq); return false; } @@ -1230,7 +1230,7 @@ getTransaction( } catch (std::exception& e) { - JLOG(app.journal("Ledger").warn()) + JLOG(app.getJournal("Ledger").warn()) << "Unable to deserialize transaction from raw SQL value. Error: " << e.what(); ec = rpcDB_DESERIALIZATION; diff --git a/src/xrpld/app/rdb/backend/detail/SQLiteDatabase.cpp b/src/xrpld/app/rdb/backend/detail/SQLiteDatabase.cpp index 4f5365ea01..e271619b8e 100644 --- a/src/xrpld/app/rdb/backend/detail/SQLiteDatabase.cpp +++ b/src/xrpld/app/rdb/backend/detail/SQLiteDatabase.cpp @@ -178,7 +178,7 @@ SQLiteDatabase::saveValidatedLedger(std::shared_ptr const& ledger, { if (existsLedger()) { - if (!detail::saveValidatedLedger(*ledgerDb_, txdb_, registry_.app(), ledger, current)) + if (!detail::saveValidatedLedger(*ledgerDb_, txdb_, registry_.getApp(), ledger, current)) return false; } @@ -314,7 +314,7 @@ SQLiteDatabase::getTxHistory(LedgerIndex startIndex) if (existsTransaction()) { auto db = checkoutTransaction(); - auto const res = detail::getTxHistory(*db, registry_.app(), startIndex, 20).first; + auto const res = detail::getTxHistory(*db, registry_.getApp(), startIndex, 20).first; if (!res.empty()) return res; @@ -334,7 +334,8 @@ SQLiteDatabase::getOldestAccountTxs(AccountTxOptions const& options) if (existsTransaction()) { auto db = checkoutTransaction(); - return detail::getOldestAccountTxs(*db, registry_.app(), ledgerMaster, options, j_).first; + return detail::getOldestAccountTxs(*db, registry_.getApp(), ledgerMaster, options, j_) + .first; } return {}; @@ -351,7 +352,8 @@ SQLiteDatabase::getNewestAccountTxs(AccountTxOptions const& options) if (existsTransaction()) { auto db = checkoutTransaction(); - return detail::getNewestAccountTxs(*db, registry_.app(), ledgerMaster, options, j_).first; + return detail::getNewestAccountTxs(*db, registry_.getApp(), ledgerMaster, options, j_) + .first; } return {}; @@ -366,7 +368,7 @@ SQLiteDatabase::getOldestAccountTxsB(AccountTxOptions const& options) if (existsTransaction()) { auto db = checkoutTransaction(); - return detail::getOldestAccountTxsB(*db, registry_.app(), options, j_).first; + return detail::getOldestAccountTxsB(*db, registry_.getApp(), options, j_).first; } return {}; @@ -381,7 +383,7 @@ SQLiteDatabase::getNewestAccountTxsB(AccountTxOptions const& options) if (existsTransaction()) { auto db = checkoutTransaction(); - return detail::getNewestAccountTxsB(*db, registry_.app(), options, j_).first; + return detail::getNewestAccountTxsB(*db, registry_.getApp(), options, j_).first; } return {}; @@ -395,10 +397,10 @@ SQLiteDatabase::oldestAccountTxPage(AccountTxPageOptions const& options) static std::uint32_t const page_length(200); auto onUnsavedLedger = - std::bind(saveLedgerAsync, std::ref(registry_.app()), std::placeholders::_1); + std::bind(saveLedgerAsync, std::ref(registry_.getApp()), std::placeholders::_1); AccountTxs ret; auto onTransaction = - [&ret, &app = registry_.app()]( + [&ret, &app = registry_.getApp()]( std::uint32_t ledger_index, std::string const& status, Blob&& rawTxn, Blob&& rawMeta) { convertBlobsToTxResult( ret, ledger_index, status, std::move(rawTxn), std::move(rawMeta), app); @@ -424,10 +426,10 @@ SQLiteDatabase::newestAccountTxPage(AccountTxPageOptions const& options) static std::uint32_t const page_length(200); auto onUnsavedLedger = - std::bind(saveLedgerAsync, std::ref(registry_.app()), std::placeholders::_1); + std::bind(saveLedgerAsync, std::ref(registry_.getApp()), std::placeholders::_1); AccountTxs ret; auto onTransaction = - [&ret, &app = registry_.app()]( + [&ret, &app = registry_.getApp()]( std::uint32_t ledger_index, std::string const& status, Blob&& rawTxn, Blob&& rawMeta) { convertBlobsToTxResult( ret, ledger_index, status, std::move(rawTxn), std::move(rawMeta), app); @@ -453,7 +455,7 @@ SQLiteDatabase::oldestAccountTxPageB(AccountTxPageOptions const& options) static std::uint32_t const page_length(500); auto onUnsavedLedger = - std::bind(saveLedgerAsync, std::ref(registry_.app()), std::placeholders::_1); + std::bind(saveLedgerAsync, std::ref(registry_.getApp()), std::placeholders::_1); MetaTxsList ret; auto onTransaction = [&ret]( @@ -481,7 +483,7 @@ SQLiteDatabase::newestAccountTxPageB(AccountTxPageOptions const& options) static std::uint32_t const page_length(500); auto onUnsavedLedger = - std::bind(saveLedgerAsync, std::ref(registry_.app()), std::placeholders::_1); + std::bind(saveLedgerAsync, std::ref(registry_.getApp()), std::placeholders::_1); MetaTxsList ret; auto onTransaction = [&ret]( @@ -513,7 +515,7 @@ SQLiteDatabase::getTransaction( if (existsTransaction()) { auto db = checkoutTransaction(); - return detail::getTransaction(*db, registry_.app(), id, range, ec); + return detail::getTransaction(*db, registry_.getApp(), id, range, ec); } return TxSearched::unknown; @@ -604,10 +606,10 @@ SQLiteDatabase::closeTransactionDB() SQLiteDatabase::SQLiteDatabase(ServiceRegistry& registry, Config const& config, JobQueue& jobQueue) : registry_(registry) , useTxTables_(config.useTxTables()) - , j_(registry.journal("SQLiteDatabase")) + , j_(registry.getJournal("SQLiteDatabase")) { DatabaseCon::Setup const setup = setup_DatabaseCon(config, j_); - if (!makeLedgerDBs(config, setup, DatabaseCon::CheckpointerSetup{&jobQueue, ®istry_.logs()})) + if (!makeLedgerDBs(config, setup, DatabaseCon::CheckpointerSetup{&jobQueue, registry_})) { std::string_view constexpr error = "Failed to create ledger databases"; diff --git a/src/xrpld/overlay/Slot.h b/src/xrpld/overlay/Slot.h index ac3c3ad49e..11cbd09e36 100644 --- a/src/xrpld/overlay/Slot.h +++ b/src/xrpld/overlay/Slot.h @@ -536,14 +536,14 @@ class Slots final public: /** - * @param logs reference to the logger + * @param registry The service registry. * @param handler Squelch/unsquelch implementation * @param config reference to the global config */ - Slots(Logs& logs, SquelchHandler const& handler, Config const& config) + Slots(ServiceRegistry& registry, SquelchHandler const& handler, Config const& config) : handler_(handler) - , logs_(logs) - , journal_(logs.journal("Slots")) + , logs_(registry.getLogs()) + , journal_(registry.getJournal("Slots")) , baseSquelchEnabled_(config.VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE) , maxSelectedPeers_(config.VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS) { diff --git a/src/xrpld/overlay/detail/ConnectAttempt.cpp b/src/xrpld/overlay/detail/ConnectAttempt.cpp index 78aee006f1..406370ff19 100644 --- a/src/xrpld/overlay/detail/ConnectAttempt.cpp +++ b/src/xrpld/overlay/detail/ConnectAttempt.cpp @@ -607,7 +607,7 @@ ConnectAttempt::processResponse() JLOG(journal_.debug()) << "Protocol: " << to_string(*negotiatedProtocol); JLOG(journal_.info()) << "Public Key: " << toBase58(TokenType::NodePublic, publicKey); - auto const member = app_.cluster().member(publicKey); + auto const member = app_.getCluster().member(publicKey); if (member) { JLOG(journal_.info()) << "Cluster name: " << *member; diff --git a/src/xrpld/overlay/detail/Handshake.cpp b/src/xrpld/overlay/detail/Handshake.cpp index e9ad25bcc4..0992d252b0 100644 --- a/src/xrpld/overlay/detail/Handshake.cpp +++ b/src/xrpld/overlay/detail/Handshake.cpp @@ -166,7 +166,7 @@ buildHandshake( h.insert("Network-ID", std::to_string(*networkID)); } - h.insert("Network-Time", std::to_string(app.timeKeeper().now().time_since_epoch().count())); + h.insert("Network-Time", std::to_string(app.getTimeKeeper().now().time_since_epoch().count())); h.insert("Public-Key", toBase58(TokenType::NodePublic, app.nodeIdentity().first)); @@ -235,7 +235,7 @@ verifyHandshake( using namespace std::chrono; - auto const ourTime = app.timeKeeper().now(); + auto const ourTime = app.getTimeKeeper().now(); auto const tolerance = 20s; // We can't blindly "return a-b;" because TimeKeeper::time_point diff --git a/src/xrpld/overlay/detail/OverlayImpl.cpp b/src/xrpld/overlay/detail/OverlayImpl.cpp index 57eddd8b2c..aa3441f389 100644 --- a/src/xrpld/overlay/detail/OverlayImpl.cpp +++ b/src/xrpld/overlay/detail/OverlayImpl.cpp @@ -114,20 +114,20 @@ OverlayImpl::OverlayImpl( , work_(std::in_place, boost::asio::make_work_guard(io_context_)) , strand_(boost::asio::make_strand(io_context_)) , setup_(setup) - , journal_(app_.journal("Overlay")) + , journal_(app_.getJournal("Overlay")) , serverHandler_(serverHandler) , m_resourceManager(resourceManager) , m_peerFinder( PeerFinder::make_Manager( io_context, stopwatch(), - app_.journal("PeerFinder"), + app_.getJournal("PeerFinder"), config, collector)) , m_resolver(resolver) , next_id_(1) , timer_count_(0) - , slots_(app.logs(), *this, app.config()) + , slots_(app, *this, app.config()) , m_stats( std::bind(&OverlayImpl::collect_metrics, this), collector, @@ -150,7 +150,8 @@ OverlayImpl::onHandoff( endpoint_type remote_endpoint) { auto const id = next_id_++; - beast::WrappedSink sink(app_.logs()["Peer"], makePrefix(id)); + auto peerJournal = app_.getJournal("Peer"); + beast::WrappedSink sink(peerJournal.sink(), makePrefix(id)); beast::Journal journal(sink); Handoff handoff; @@ -240,8 +241,8 @@ OverlayImpl::onHandoff( { // The node gets a reserved slot if it is in our cluster // or if it has a reservation. - bool const reserved = static_cast(app_.cluster().member(publicKey)) || - app_.peerReservations().contains(publicKey); + bool const reserved = static_cast(app_.getCluster().member(publicKey)) || + app_.getPeerReservations().contains(publicKey); auto const result = m_peerFinder->activate(slot, publicKey, reserved); if (result != PeerFinder::Result::success) { @@ -389,7 +390,7 @@ OverlayImpl::connect(beast::IP::Endpoint const& remote_endpoint) setup_.context, next_id_++, slot, - app_.journal("Peer"), + app_.getJournal("Peer"), *this); std::lock_guard lock(mutex_); @@ -612,7 +613,7 @@ OverlayImpl::onManifests( { auto const serialized = mo->serialized; - auto const result = app_.validatorManifests().applyManifest(std::move(*mo)); + auto const result = app_.getValidatorManifests().applyManifest(std::move(*mo)); if (result == ManifestDisposition::accepted) { @@ -629,7 +630,7 @@ OverlayImpl::onManifests( app_.getOPs().pubManifest(*mo); - if (app_.validators().listed(mo->masterKey)) + if (app_.getValidators().listed(mo->masterKey)) { auto db = app_.getWalletDB().checkoutDb(); addValidatorManifest(*db, serialized); @@ -758,7 +759,7 @@ OverlayImpl::getServerCounts() Json::Value OverlayImpl::getUnlInfo() { - Json::Value validators = app_.validators().getJson(); + Json::Value validators = app_.getValidators().getJson(); if (validators.isMember(jss::publisher_lists)) { @@ -774,7 +775,7 @@ OverlayImpl::getUnlInfo() validators.removeMember(jss::trusted_validator_keys); validators.removeMember(jss::validation_quorum); - Json::Value validatorSites = app_.validatorSites().getJson(); + Json::Value validatorSites = app_.getValidatorSites().getJson(); if (validatorSites.isMember(jss::validator_sites)) { @@ -875,7 +876,7 @@ OverlayImpl::processValidatorList(http_request_type const& req, Handoff& handoff return fail(boost::beast::http::status::bad_request); // find the list - auto vl = app_.validators().getAvailable(key, version); + auto vl = app_.getValidators().getAvailable(key, version); if (!vl) { @@ -1142,11 +1143,11 @@ OverlayImpl::getManifestsMessage() { std::lock_guard g(manifestLock_); - if (auto seq = app_.validatorManifests().sequence(); seq != manifestListSeq_) + if (auto seq = app_.getValidatorManifests().sequence(); seq != manifestListSeq_) { protocol::TMManifests tm; - app_.validatorManifests().for_each_manifest( + app_.getValidatorManifests().for_each_manifest( [&tm](std::size_t s) { tm.mutable_list()->Reserve(s); }, [&tm, &hr = app_.getHashRouter()](Manifest const& manifest) { tm.add_list()->set_stobject(manifest.serialized.data(), manifest.serialized.size()); diff --git a/src/xrpld/overlay/detail/PeerImp.cpp b/src/xrpld/overlay/detail/PeerImp.cpp index 767e8bfd20..92c5bcb221 100644 --- a/src/xrpld/overlay/detail/PeerImp.cpp +++ b/src/xrpld/overlay/detail/PeerImp.cpp @@ -65,8 +65,8 @@ PeerImp::PeerImp( , id_(id) , fingerprint_(getFingerprint(slot->remote_endpoint(), publicKey, to_string(id))) , prefix_(makePrefix(fingerprint_)) - , sink_(app_.journal("Peer"), prefix_) - , p_sink_(app_.journal("Protocol"), prefix_) + , sink_(app_.getJournal("Peer"), prefix_) + , p_sink_(app_.getJournal("Protocol"), prefix_) , journal_(sink_) , p_journal_(p_sink_) , stream_ptr_(std::move(stream_ptr)) @@ -83,7 +83,7 @@ PeerImp::PeerImp( , publicKey_(publicKey) , lastPingTime_(clock_type::now()) , creationTime_(clock_type::now()) - , squelch_(app_.journal("Squelch")) + , squelch_(app_.getJournal("Squelch")) , usage_(consumer) , fee_{Resource::feeTrivialPeer, ""} , slot_(slot) @@ -364,7 +364,7 @@ PeerImp::crawl() const bool PeerImp::cluster() const { - return static_cast(app_.cluster().member(publicKey_)); + return static_cast(app_.getCluster().member(publicKey_)); } std::string @@ -818,7 +818,7 @@ PeerImp::doAccept() JLOG(journal_.debug()) << "Protocol: " << to_string(protocol_); - if (auto member = app_.cluster().member(publicKey_)) + if (auto member = app_.getCluster().member(publicKey_)) { { std::unique_lock lock{nameMutex_}; @@ -908,7 +908,7 @@ PeerImp::doProtocolStart() // Send all the validator lists that have been loaded if (inbound_ && supportsFeature(ProtocolFeature::ValidatorListPropagation)) { - app_.validators().for_each_available( + app_.getValidators().for_each_available( [&](std::string const& manifest, std::uint32_t version, std::map const& blobInfos, @@ -1242,7 +1242,7 @@ PeerImp::onMessage(std::shared_ptr const& m) { auto const reportTime = NetClock::time_point{NetClock::duration{node.reporttime()}}; - app_.cluster().update(*publicKey, name, node.nodeload(), reportTime); + app_.getCluster().update(*publicKey, name, node.nodeload(), reportTime); } } @@ -1264,13 +1264,13 @@ PeerImp::onMessage(std::shared_ptr const& m) } // Calculate the cluster fee: - auto const thresh = app_.timeKeeper().now() - 90s; + auto const thresh = app_.getTimeKeeper().now() - 90s; std::uint32_t clusterFee = 0; std::vector fees; - fees.reserve(app_.cluster().size()); + fees.reserve(app_.getCluster().size()); - app_.cluster().for_each([&fees, thresh](ClusterNode const& status) { + app_.getCluster().for_each([&fees, thresh](ClusterNode const& status) { if (status.getReportTime() >= thresh) fees.push_back(status.getLoadFee()); }); @@ -1811,7 +1811,7 @@ PeerImp::onMessage(std::shared_ptr const& m) // suppression for 30 seconds to avoid doing a relatively expensive lookup // every time a spam packet is received PublicKey const publicKey{makeSlice(set.nodepubkey())}; - auto const isTrusted = app_.validators().trusted(publicKey); + auto const isTrusted = app_.getValidators().trusted(publicKey); // If the operator has specified that untrusted proposals be dropped then // this happens here I.e. before further wasting CPU verifying the signature @@ -1877,8 +1877,8 @@ PeerImp::onMessage(std::shared_ptr const& m) set.proposeseq(), proposeHash, closeTime, - app_.timeKeeper().closeTime(), - calcNodeID(app_.validatorManifests().getMasterKey(publicKey))}); + app_.getTimeKeeper().closeTime(), + calcNodeID(app_.getValidatorManifests().getMasterKey(publicKey))}); std::weak_ptr weak = shared_from_this(); app_.getJobQueue().addJob( @@ -1894,7 +1894,7 @@ PeerImp::onMessage(std::shared_ptr const& m) JLOG(p_journal_.trace()) << "Status: Change"; if (!m->has_networktime()) - m->set_networktime(app_.timeKeeper().now().time_since_epoch().count()); + m->set_networktime(app_.getTimeKeeper().now().time_since_epoch().count()); { std::lock_guard sl(recentLock_); @@ -2157,13 +2157,13 @@ PeerImp::onValidatorListMessage( return; } - auto const applyResult = app_.validators().applyListsAndBroadcast( + auto const applyResult = app_.getValidators().applyListsAndBroadcast( manifest, version, blobs, remote_address_.to_string(), hash, - app_.overlay(), + app_.getOverlay(), app_.getHashRouter(), app_.getOPs()); @@ -2390,7 +2390,7 @@ PeerImp::onMessage(std::shared_ptr const& m) try { - auto const closeTime = app_.timeKeeper().closeTime(); + auto const closeTime = app_.getTimeKeeper().closeTime(); std::shared_ptr val; { @@ -2398,7 +2398,7 @@ PeerImp::onMessage(std::shared_ptr const& m) val = std::make_shared( std::ref(sit), [this](PublicKey const& pk) { - return calcNodeID(app_.validatorManifests().getMasterKey(pk)); + return calcNodeID(app_.getValidatorManifests().getMasterKey(pk)); }, false); val->setSeen(closeTime); @@ -2406,7 +2406,7 @@ PeerImp::onMessage(std::shared_ptr const& m) if (!isCurrent( app_.getValidations().parms(), - app_.timeKeeper().closeTime(), + app_.getTimeKeeper().closeTime(), val->getSignTime(), val->getSeenTime())) { @@ -2418,7 +2418,7 @@ PeerImp::onMessage(std::shared_ptr const& m) // RH TODO: when isTrusted = false we should probably also cache a key // suppression for 30 seconds to avoid doing a relatively expensive // lookup every time a spam packet is received - auto const isTrusted = app_.validators().trusted(val->getSignerPublic()); + auto const isTrusted = app_.getValidators().trusted(val->getSignerPublic()); // If the operator has specified that untrusted validations be // dropped then this happens here I.e. before further wasting CPU @@ -2863,7 +2863,7 @@ PeerImp::doTransactions(std::shared_ptr const& pack sttx->add(s); tx->set_rawtransaction(s.data(), s.size()); tx->set_status(txn->getStatus() == INCLUDED ? protocol::tsCURRENT : protocol::tsNEW); - tx->set_receivetimestamp(app_.timeKeeper().now().time_since_epoch().count()); + tx->set_receivetimestamp(app_.getTimeKeeper().now().time_since_epoch().count()); tx->set_deferred(txn->getSubmitResult().queued); } @@ -2941,7 +2941,7 @@ PeerImp::checkTransaction( { JLOG(p_journal_.debug()) << "Passing skipped pseudo pseudo-transaction tx " << tx->getID(); - app_.overlay().relay(tx->getID(), {}, *toSkip); + app_.getOverlay().relay(tx->getID(), {}, *toSkip); } if (!batch) { @@ -3041,7 +3041,7 @@ PeerImp::checkPropose( // not be relayed to these peers. But the message must be counted // as part of the squelch logic. auto haveMessage = - app_.overlay().relay(*packet, peerPos.suppressionID(), peerPos.publicKey()); + app_.getOverlay().relay(*packet, peerPos.suppressionID(), peerPos.publicKey()); if (!haveMessage.empty()) { overlay_.updateSlotAndSquelch( diff --git a/src/xrpld/overlay/detail/PeerImp.h b/src/xrpld/overlay/detail/PeerImp.h index b4393ebd62..5a687a9b2a 100644 --- a/src/xrpld/overlay/detail/PeerImp.h +++ b/src/xrpld/overlay/detail/PeerImp.h @@ -7,7 +7,6 @@ #include #include -#include #include #include #include @@ -815,8 +814,8 @@ PeerImp::PeerImp( , id_(id) , fingerprint_(getFingerprint(slot->remote_endpoint(), publicKey, to_string(id_))) , prefix_(makePrefix(fingerprint_)) - , sink_(app_.journal("Peer"), prefix_) - , p_sink_(app_.journal("Protocol"), prefix_) + , sink_(app_.getJournal("Peer"), prefix_) + , p_sink_(app_.getJournal("Protocol"), prefix_) , journal_(sink_) , p_journal_(p_sink_) , stream_ptr_(std::move(stream_ptr)) @@ -833,7 +832,7 @@ PeerImp::PeerImp( , publicKey_(publicKey) , lastPingTime_(clock_type::now()) , creationTime_(clock_type::now()) - , squelch_(app_.journal("Squelch")) + , squelch_(app_.getJournal("Squelch")) , usage_(usage) , fee_{Resource::feeTrivialPeer} , slot_(std::move(slot)) diff --git a/src/xrpld/overlay/detail/PeerSet.cpp b/src/xrpld/overlay/detail/PeerSet.cpp index 1327d190c2..3329f67e7a 100644 --- a/src/xrpld/overlay/detail/PeerSet.cpp +++ b/src/xrpld/overlay/detail/PeerSet.cpp @@ -37,7 +37,7 @@ private: std::set peers_; }; -PeerSetImpl::PeerSetImpl(Application& app) : app_(app), journal_(app.journal("PeerSet")) +PeerSetImpl::PeerSetImpl(Application& app) : app_(app), journal_(app.getJournal("PeerSet")) { } @@ -49,7 +49,7 @@ PeerSetImpl::addPeers( { using ScoredPeer = std::pair>; - auto const& overlay = app_.overlay(); + auto const& overlay = app_.getOverlay(); std::vector pairs; pairs.reserve(overlay.size()); @@ -90,7 +90,7 @@ PeerSetImpl::sendRequest( for (auto id : peers_) { - if (auto p = app_.overlay().findPeerByShortID(id)) + if (auto p = app_.getOverlay().findPeerByShortID(id)) p->send(packet); } } @@ -127,7 +127,7 @@ make_PeerSetBuilder(Application& app) class DummyPeerSet : public PeerSet { public: - DummyPeerSet(Application& app) : j_(app.journal("DummyPeerSet")) + DummyPeerSet(Application& app) : j_(app.getJournal("DummyPeerSet")) { } diff --git a/src/xrpld/rpc/RPCCall.h b/src/xrpld/rpc/RPCCall.h index 54b73b65cf..6ab9f1d1fa 100644 --- a/src/xrpld/rpc/RPCCall.h +++ b/src/xrpld/rpc/RPCCall.h @@ -2,7 +2,7 @@ #include -#include +#include #include #include diff --git a/src/xrpld/rpc/RPCSub.h b/src/xrpld/rpc/RPCSub.h index e89f8f34e4..e96234ee02 100644 --- a/src/xrpld/rpc/RPCSub.h +++ b/src/xrpld/rpc/RPCSub.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include @@ -29,6 +30,6 @@ make_RPCSub( std::string const& strUrl, std::string const& strUsername, std::string const& strPassword, - Logs& logs); + ServiceRegistry& registry); } // namespace xrpl diff --git a/src/xrpld/rpc/detail/PathRequest.cpp b/src/xrpld/rpc/detail/PathRequest.cpp index 1161c1a449..f02377381c 100644 --- a/src/xrpld/rpc/detail/PathRequest.cpp +++ b/src/xrpld/rpc/detail/PathRequest.cpp @@ -6,7 +6,6 @@ #include #include -#include #include #include #include @@ -546,7 +545,7 @@ PathRequest::findPaths( *raSrcAccount, // --> Account sending from. ps, // --> Path set. domain, // --> Domain. - app_.logs(), + app_, &rcInput); if (!convert_all_ && !fullLiquidityPath.empty() && @@ -565,7 +564,7 @@ PathRequest::findPaths( *raSrcAccount, // --> Account sending from. ps, // --> Path set. domain, // --> Domain. - app_.logs()); + app_); if (!isTesSuccess(rc.result())) { diff --git a/src/xrpld/rpc/detail/PathRequestManager.cpp b/src/xrpld/rpc/detail/PathRequestManager.cpp index 8c42d3e83b..e953f1ca70 100644 --- a/src/xrpld/rpc/detail/PathRequestManager.cpp +++ b/src/xrpld/rpc/detail/PathRequestManager.cpp @@ -2,7 +2,6 @@ #include #include -#include #include #include #include @@ -37,7 +36,7 @@ PathRequestManager::getLineCache(std::shared_ptr const& ledger, // weak_ptr, and will immediately discard it if there are no other // references. lineCache_ = lineCache = - std::make_shared(ledger, app_.journal("RippleLineCache")); + std::make_shared(ledger, app_.getJournal("RippleLineCache")); } return lineCache; } @@ -274,7 +273,7 @@ PathRequestManager::doLegacyPathRequest( std::shared_ptr const& inLedger, Json::Value const& request) { - auto cache = std::make_shared(inLedger, app_.journal("RippleLineCache")); + auto cache = std::make_shared(inLedger, app_.getJournal("RippleLineCache")); auto req = std::make_shared(app_, [] {}, consumer, ++mLastIdentifier, *this, mJournal); diff --git a/src/xrpld/rpc/detail/Pathfinder.cpp b/src/xrpld/rpc/detail/Pathfinder.cpp index badec22c30..176c7f9529 100644 --- a/src/xrpld/rpc/detail/Pathfinder.cpp +++ b/src/xrpld/rpc/detail/Pathfinder.cpp @@ -3,7 +3,6 @@ #include #include -#include #include #include #include @@ -167,7 +166,7 @@ Pathfinder::Pathfinder( , mLedger(cache->getLedger()) , mRLCache(cache) , app_(app) - , j_(app.journal("Pathfinder")) + , j_(app.getJournal("Pathfinder")) { XRPL_ASSERT( !uSrcIssuer || isXRP(uSrcCurrency) == isXRP(uSrcIssuer.value()), @@ -345,7 +344,7 @@ Pathfinder::getPathLiquidity( mSrcAccount, pathSet, mDomain, - app_.logs(), + app_, &rcInput); // If we can't get even the minimum liquidity requested, we're done. if (!isTesSuccess(rc.result())) @@ -366,7 +365,7 @@ Pathfinder::getPathLiquidity( mSrcAccount, pathSet, mDomain, - app_.logs(), + app_, &rcInput); // If we found further liquidity, add it into the result. @@ -404,7 +403,7 @@ Pathfinder::computePathRanks(int maxPaths, std::function const& cont mSrcAccount, STPathSet(), mDomain, - app_.logs(), + app_, &rcInput); if (rc.result() == tesSUCCESS) diff --git a/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp b/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp index 0136d8af18..2216affa6f 100644 --- a/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp +++ b/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp @@ -411,7 +411,7 @@ getOrAcquireLedger(RPC::JsonContext const& context) if (ledgerIndex <= 0) return Unexpected(RPC::make_param_error("Ledger index too small")); - auto const j = context.app.journal("RPCHandler"); + auto const j = context.app.getJournal("RPCHandler"); // Try to get the hash of the desired ledger from the validated // ledger auto neededHash = hashOfSeq(*ledger, ledgerIndex, j); diff --git a/src/xrpld/rpc/detail/RPCSub.cpp b/src/xrpld/rpc/detail/RPCSub.cpp index 233981001a..3aa5f75f6a 100644 --- a/src/xrpld/rpc/detail/RPCSub.cpp +++ b/src/xrpld/rpc/detail/RPCSub.cpp @@ -21,15 +21,15 @@ public: std::string const& strUrl, std::string const& strUsername, std::string const& strPassword, - Logs& logs) + ServiceRegistry& registry) : RPCSub(source) , m_io_context(io_context) , m_jobQueue(jobQueue) , mUrl(strUrl) , mUsername(strUsername) , mPassword(strPassword) - , j_(logs.journal("RPCSub")) - , logs_(logs) + , j_(registry.getJournal("RPCSub")) + , logs_(registry.getLogs()) { parsedURL pUrl; @@ -199,7 +199,7 @@ make_RPCSub( std::string const& strUrl, std::string const& strUsername, std::string const& strPassword, - Logs& logs) + ServiceRegistry& registry) { return std::make_shared( std::ref(source), @@ -208,7 +208,7 @@ make_RPCSub( strUrl, strUsername, strPassword, - logs); + registry); } } // namespace xrpl diff --git a/src/xrpld/rpc/detail/ServerHandler.cpp b/src/xrpld/rpc/detail/ServerHandler.cpp index 917a9b7609..64c81ccc0a 100644 --- a/src/xrpld/rpc/detail/ServerHandler.cpp +++ b/src/xrpld/rpc/detail/ServerHandler.cpp @@ -8,7 +8,6 @@ #include #include -#include #include #include #include @@ -98,9 +97,9 @@ ServerHandler::ServerHandler( CollectorManager& cm) : app_(app) , m_resourceManager(resourceManager) - , m_journal(app_.journal("Server")) + , m_journal(app_.getJournal("Server")) , m_networkOPs(networkOPs) - , m_server(make_Server(*this, io_context, app_.journal("Server"))) + , m_server(make_Server(*this, io_context, app_.getJournal("Server"))) , m_jobQueue(jobQueue) { auto const& group(cm.group("rpc")); @@ -218,7 +217,7 @@ ServerHandler::onHandoff( } if (bundle && p.count("peer") > 0) - return app_.overlay().onHandoff(std::move(bundle), std::move(request), remote_address); + return app_.getOverlay().onHandoff(std::move(bundle), std::move(request), remote_address); if (is_ws && isStatusRequest(request)) return statusResponse(request); @@ -270,7 +269,7 @@ ServerHandler::onRequest(Session& session) // Make sure RPC is enabled on the port if (session.port().protocol.count("http") == 0 && session.port().protocol.count("https") == 0) { - HTTPReply(403, "Forbidden", makeOutput(session), app_.journal("RPC")); + HTTPReply(403, "Forbidden", makeOutput(session), app_.getJournal("RPC")); session.close(true); return; } @@ -278,7 +277,7 @@ ServerHandler::onRequest(Session& session) // Check user/password authorization if (!authorized(session.port(), build_map(session.request()))) { - HTTPReply(403, "Forbidden", makeOutput(session), app_.journal("RPC")); + HTTPReply(403, "Forbidden", makeOutput(session), app_.getJournal("RPC")); session.close(true); return; } @@ -291,7 +290,7 @@ ServerHandler::onRequest(Session& session) if (postResult == nullptr) { // The coroutine was rejected, probably because we're shutting down. - HTTPReply(503, "Service Unavailable", makeOutput(*detachedSession), app_.journal("RPC")); + HTTPReply(503, "Service Unavailable", makeOutput(*detachedSession), app_.getJournal("RPC")); detachedSession->close(true); return; } @@ -440,7 +439,7 @@ ServerHandler::processSession( else { RPC::JsonContext context{ - {app_.journal("RPCHandler"), + {app_.getJournal("RPCHandler"), app_, loadType, app_.getOPs(), @@ -574,7 +573,7 @@ ServerHandler::processRequest( std::string_view forwardedFor, std::string_view user) { - auto rpcJ = app_.journal("RPC"); + auto rpcJ = app_.getJournal("RPC"); Json::Value jsonOrig; { diff --git a/src/xrpld/rpc/detail/TransactionSign.cpp b/src/xrpld/rpc/detail/TransactionSign.cpp index 027a74f2c3..1fb6fc291f 100644 --- a/src/xrpld/rpc/detail/TransactionSign.cpp +++ b/src/xrpld/rpc/detail/TransactionSign.cpp @@ -8,7 +8,6 @@ #include #include -#include #include #include #include @@ -258,10 +257,10 @@ checkPayment( STPathSet result; - if (auto ledger = app.openLedger().current()) + if (auto ledger = app.getOpenLedger().current()) { Pathfinder pf( - std::make_shared(ledger, app.journal("RippleLineCache")), + std::make_shared(ledger, app.getJournal("RippleLineCache")), srcAddressID, *dstAccountID, sendMax.issue().currency, @@ -280,7 +279,7 @@ checkPayment( } } - auto j = app.journal("RPCHandler"); + auto j = app.getJournal("RPCHandler"); JLOG(j.debug()) << "transactionSign: build_path: " << result.getJson(JsonOptions::none); if (!result.empty()) @@ -402,7 +401,7 @@ transactionPreProcessImpl( std::chrono::seconds validatedLedgerAge, Application& app) { - auto j = app.journal("RPCHandler"); + auto j = app.getJournal("RPCHandler"); Json::Value jvResult; std::optional> keyPair = keypairForSignature(params, jvResult); @@ -461,7 +460,7 @@ transactionPreProcessImpl( std::shared_ptr sle; if (verify) - sle = app.openLedger().current()->read(keylet::account(srcAddressID)); + sle = app.getOpenLedger().current()->read(keylet::account(srcAddressID)); if (verify && !sle) { @@ -565,7 +564,7 @@ transactionPreProcessImpl( auto delegatedAddressID = *ptrDelegatedAddressID; auto delegatedSle = - app.openLedger().current()->read(keylet::account(delegatedAddressID)); + app.getOpenLedger().current()->read(keylet::account(delegatedAddressID)); if (!delegatedSle) return rpcError(rpcDELEGATE_ACT_NOT_FOUND); @@ -765,7 +764,7 @@ transactionFormatResultImpl(Transaction::pointer tpTrans, unsigned apiVersion) [[nodiscard]] static XRPAmount getTxFee(Application const& app, Config const& config, Json::Value tx) { - auto const& ledger = app.openLedger().current(); + auto const& ledger = app.getOpenLedger().current(); // autofilling only needed in this function so that the `STParsedJSONObject` // parsing works properly it should not be modifying the actual `tx` object if (!tx.isMember(jss::Fee)) @@ -827,7 +826,7 @@ getTxFee(Application const& app, Config const& config, Json::Value tx) if (!passesLocalChecks(stTx, reason)) return config.FEES.reference_fee; - return calculateBaseFee(*app.openLedger().current(), stTx); + return calculateBaseFee(*app.getOpenLedger().current(), stTx); } catch (std::exception& e) { @@ -848,7 +847,7 @@ getCurrentNetworkFee( { XRPAmount const feeDefault = getTxFee(app, config, tx); - auto ledger = app.openLedger().current(); + auto ledger = app.getOpenLedger().current(); // Administrative and identified endpoints are exempt from local fees. XRPAmount const loadFee = scaleFeeLoad(feeDefault, feeTrack, ledger->fees(), isUnlimited(role)); XRPAmount fee = loadFee; @@ -950,7 +949,7 @@ transactionSign( { using namespace detail; - auto j = app.journal("RPCHandler"); + auto j = app.getJournal("RPCHandler"); JLOG(j.debug()) << "transactionSign: " << jvRequest; // Add and amend fields based on the transaction type. @@ -961,7 +960,7 @@ transactionSign( if (!preprocResult.second) return preprocResult.first; - std::shared_ptr ledger = app.openLedger().current(); + std::shared_ptr ledger = app.getOpenLedger().current(); // Make sure the STTx makes a legitimate Transaction. std::pair txn = transactionConstructImpl(preprocResult.second, ledger->rules(), app); @@ -985,8 +984,8 @@ transactionSubmit( { using namespace detail; - auto const& ledger = app.openLedger().current(); - auto j = app.journal("RPCHandler"); + auto const& ledger = app.getOpenLedger().current(); + auto j = app.getJournal("RPCHandler"); JLOG(j.debug()) << "transactionSubmit: " << jvRequest; // Add and amend fields based on the transaction type. @@ -1107,8 +1106,8 @@ transactionSignFor( std::chrono::seconds validatedLedgerAge, Application& app) { - auto const& ledger = app.openLedger().current(); - auto j = app.journal("RPCHandler"); + auto const& ledger = app.getOpenLedger().current(); + auto j = app.getJournal("RPCHandler"); JLOG(j.debug()) << "transactionSignFor: " << jvRequest; // Verify presence of the signer's account field. @@ -1219,8 +1218,8 @@ transactionSubmitMultiSigned( Application& app, ProcessTransactionFn const& processTransaction) { - auto const& ledger = app.openLedger().current(); - auto j = app.journal("RPCHandler"); + auto const& ledger = app.getOpenLedger().current(); + auto j = app.getJournal("RPCHandler"); JLOG(j.debug()) << "transactionSubmitMultiSigned: " << jvRequest; // When multi-signing, the "Sequence" and "SigningPubKey" fields must diff --git a/src/xrpld/rpc/handlers/Connect.cpp b/src/xrpld/rpc/handlers/Connect.cpp index 292cd50cbb..fe3183484e 100644 --- a/src/xrpld/rpc/handlers/Connect.cpp +++ b/src/xrpld/rpc/handlers/Connect.cpp @@ -48,7 +48,7 @@ doConnect(RPC::JsonContext& context) auto ip = beast::IP::Endpoint::from_string(ip_str); if (!is_unspecified(ip)) - context.app.overlay().connect(ip.at_port(iPort)); + context.app.getOverlay().connect(ip.at_port(iPort)); return RPC::makeObjectValue( "attempting connection to IP:" + ip_str + " port: " + std::to_string(iPort)); diff --git a/src/xrpld/rpc/handlers/DoManifest.cpp b/src/xrpld/rpc/handlers/DoManifest.cpp index 5928947e21..ba3461033f 100644 --- a/src/xrpld/rpc/handlers/DoManifest.cpp +++ b/src/xrpld/rpc/handlers/DoManifest.cpp @@ -32,25 +32,25 @@ doManifest(RPC::JsonContext& context) // first attempt to use params as ephemeral key, // if this lookup succeeds master key will be returned, // else an unseated optional is returned - auto const mk = context.app.validatorManifests().getMasterKey(*pk); + auto const mk = context.app.getValidatorManifests().getMasterKey(*pk); - auto const ek = context.app.validatorManifests().getSigningKey(mk); + auto const ek = context.app.getValidatorManifests().getSigningKey(mk); // if ephemeral key not found, we don't have specified manifest if (!ek) return ret; - if (auto const manifest = context.app.validatorManifests().getManifest(mk)) + if (auto const manifest = context.app.getValidatorManifests().getManifest(mk)) ret[jss::manifest] = base64_encode(*manifest); Json::Value details; details[jss::master_key] = toBase58(TokenType::NodePublic, mk); details[jss::ephemeral_key] = toBase58(TokenType::NodePublic, *ek); - if (auto const seq = context.app.validatorManifests().getSequence(mk)) + if (auto const seq = context.app.getValidatorManifests().getSequence(mk)) details[jss::seq] = *seq; - if (auto const domain = context.app.validatorManifests().getDomain(mk)) + if (auto const domain = context.app.getValidatorManifests().getDomain(mk)) details[jss::domain] = *domain; ret[jss::details] = details; diff --git a/src/xrpld/rpc/handlers/GetCounts.cpp b/src/xrpld/rpc/handlers/GetCounts.cpp index f5f953046d..09a952e114 100644 --- a/src/xrpld/rpc/handlers/GetCounts.cpp +++ b/src/xrpld/rpc/handlers/GetCounts.cpp @@ -80,7 +80,7 @@ getCountsJson(Application& app, int minObjectCount) ret[jss::write_load] = app.getNodeStore().getWriteLoad(); ret[jss::historical_perminute] = static_cast(app.getInboundLedgers().fetchRate()); - ret[jss::SLE_hit_rate] = app.cachedSLEs().rate(); + ret[jss::SLE_hit_rate] = app.getCachedSLEs().rate(); ret[jss::ledger_hit_rate] = app.getLedgerMaster().getCacheHitRate(); ret[jss::AL_size] = Json::UInt(app.getAcceptedLedgerCache().size()); ret[jss::AL_hit_rate] = app.getAcceptedLedgerCache().getHitRate(); diff --git a/src/xrpld/rpc/handlers/LogLevel.cpp b/src/xrpld/rpc/handlers/LogLevel.cpp index 2bc1beb7d4..a932dfb198 100644 --- a/src/xrpld/rpc/handlers/LogLevel.cpp +++ b/src/xrpld/rpc/handlers/LogLevel.cpp @@ -21,9 +21,9 @@ doLogLevel(RPC::JsonContext& context) Json::Value ret(Json::objectValue); Json::Value lev(Json::objectValue); - lev[jss::base] = Logs::toString(Logs::fromSeverity(context.app.logs().threshold())); + lev[jss::base] = Logs::toString(Logs::fromSeverity(context.app.getLogs().threshold())); std::vector> logTable( - context.app.logs().partition_severities()); + context.app.getLogs().partition_severities()); for (auto const& [k, v] : logTable) lev[k] = v; @@ -41,7 +41,7 @@ doLogLevel(RPC::JsonContext& context) if (!context.params.isMember(jss::partition)) { // set base log threshold - context.app.logs().threshold(severity); + context.app.getLogs().threshold(severity); return Json::objectValue; } @@ -53,11 +53,11 @@ doLogLevel(RPC::JsonContext& context) if (boost::iequals(partition, "base")) { - context.app.logs().threshold(severity); + context.app.getLogs().threshold(severity); } else { - context.app.logs().get(partition).threshold(severity); + context.app.getLogs().get(partition).threshold(severity); } return Json::objectValue; diff --git a/src/xrpld/rpc/handlers/LogRotate.cpp b/src/xrpld/rpc/handlers/LogRotate.cpp index 3d52dc6538..3cc7f35381 100644 --- a/src/xrpld/rpc/handlers/LogRotate.cpp +++ b/src/xrpld/rpc/handlers/LogRotate.cpp @@ -10,7 +10,7 @@ Json::Value doLogRotate(RPC::JsonContext& context) { context.app.getPerfLog().rotate(); - return RPC::makeObjectValue(context.app.logs().rotate()); + return RPC::makeObjectValue(context.app.getLogs().rotate()); } } // namespace xrpl diff --git a/src/xrpld/rpc/handlers/Peers.cpp b/src/xrpld/rpc/handlers/Peers.cpp index b21efc01fb..ddcb674b33 100644 --- a/src/xrpld/rpc/handlers/Peers.cpp +++ b/src/xrpld/rpc/handlers/Peers.cpp @@ -15,7 +15,7 @@ doPeers(RPC::JsonContext& context) { Json::Value jvResult(Json::objectValue); - jvResult[jss::peers] = context.app.overlay().json(); + jvResult[jss::peers] = context.app.getOverlay().json(); // Legacy support if (context.apiVersion == 1) @@ -38,13 +38,13 @@ doPeers(RPC::JsonContext& context) } } - auto const now = context.app.timeKeeper().now(); + auto const now = context.app.getTimeKeeper().now(); auto const self = context.app.nodeIdentity().first; Json::Value& cluster = (jvResult[jss::cluster] = Json::objectValue); std::uint32_t ref = context.app.getFeeTrack().getLoadBase(); - context.app.cluster().for_each([&cluster, now, ref, &self](ClusterNode const& node) { + context.app.getCluster().for_each([&cluster, now, ref, &self](ClusterNode const& node) { if (node.identity() == self) return; diff --git a/src/xrpld/rpc/handlers/Reservations.cpp b/src/xrpld/rpc/handlers/Reservations.cpp index 5d9c23d46e..fb874247ad 100644 --- a/src/xrpld/rpc/handlers/Reservations.cpp +++ b/src/xrpld/rpc/handlers/Reservations.cpp @@ -56,7 +56,7 @@ doPeerReservationsAdd(RPC::JsonContext& context) PublicKey const& nodeId = *optPk; auto const previous = - context.app.peerReservations().insert_or_assign(PeerReservation{nodeId, desc}); + context.app.getPeerReservations().insert_or_assign(PeerReservation{nodeId, desc}); Json::Value result{Json::objectValue}; if (previous) @@ -83,7 +83,7 @@ doPeerReservationsDel(RPC::JsonContext& context) return rpcError(rpcPUBLIC_MALFORMED); PublicKey const& nodeId = *optPk; - auto const previous = context.app.peerReservations().erase(nodeId); + auto const previous = context.app.getPeerReservations().erase(nodeId); Json::Value result{Json::objectValue}; if (previous) @@ -96,8 +96,8 @@ doPeerReservationsDel(RPC::JsonContext& context) Json::Value doPeerReservationsList(RPC::JsonContext& context) { - auto const& reservations = context.app.peerReservations().list(); - // Enumerate the reservations in context.app.peerReservations() + auto const& reservations = context.app.getPeerReservations().list(); + // Enumerate the reservations in context.app.getPeerReservations() // as a Json::Value. Json::Value result{Json::objectValue}; Json::Value& jaReservations = result[jss::reservations] = Json::arrayValue; diff --git a/src/xrpld/rpc/handlers/Simulate.cpp b/src/xrpld/rpc/handlers/Simulate.cpp index 1d46f72425..c1d6d7f334 100644 --- a/src/xrpld/rpc/handlers/Simulate.cpp +++ b/src/xrpld/rpc/handlers/Simulate.cpp @@ -39,10 +39,10 @@ getAutofillSequence(Json::Value const& tx_json, RPC::JsonContext& context) RPC::make_error(rpcSRC_ACT_MALFORMED, RPC::invalid_field_message("tx.Account"))); } std::shared_ptr const sle = - context.app.openLedger().current()->read(keylet::account(*srcAddressID)); + context.app.getOpenLedger().current()->read(keylet::account(*srcAddressID)); if (!hasTicketSeq && !sle) { - JLOG(context.app.journal("Simulate").debug()) + JLOG(context.app.getJournal("Simulate").debug()) << "Failed to find source account " << "in current ledger: " << toBase58(*srcAddressID); @@ -210,7 +210,7 @@ simulateTxn(RPC::JsonContext& context, std::shared_ptr transaction) { Json::Value jvResult; // Process the transaction - OpenView view = *context.app.openLedger().current(); + OpenView view = *context.app.getOpenLedger().current(); auto const result = context.app.getTxQ().apply( context.app, view, transaction->getSTransaction(), tapDRY_RUN, context.j); diff --git a/src/xrpld/rpc/handlers/Subscribe.cpp b/src/xrpld/rpc/handlers/Subscribe.cpp index 6e8d9dbaa3..fc5238b37b 100644 --- a/src/xrpld/rpc/handlers/Subscribe.cpp +++ b/src/xrpld/rpc/handlers/Subscribe.cpp @@ -5,7 +5,6 @@ #include #include -#include #include #include #include @@ -62,7 +61,7 @@ doSubscribe(RPC::JsonContext& context) strUrl, strUsername, strPassword, - context.app.logs()); + context.app); ispSub = context.netOps.addRpcSub(strUrl, std::dynamic_pointer_cast(rspSub)); } diff --git a/src/xrpld/rpc/handlers/TxReduceRelay.cpp b/src/xrpld/rpc/handlers/TxReduceRelay.cpp index d269ef448e..f24f0862ef 100644 --- a/src/xrpld/rpc/handlers/TxReduceRelay.cpp +++ b/src/xrpld/rpc/handlers/TxReduceRelay.cpp @@ -9,7 +9,7 @@ namespace xrpl { Json::Value doTxReduceRelay(RPC::JsonContext& context) { - return context.app.overlay().txMetrics(); + return context.app.getOverlay().txMetrics(); } } // namespace xrpl diff --git a/src/xrpld/rpc/handlers/UnlList.cpp b/src/xrpld/rpc/handlers/UnlList.cpp index 20fb692fbb..31f41b4a33 100644 --- a/src/xrpld/rpc/handlers/UnlList.cpp +++ b/src/xrpld/rpc/handlers/UnlList.cpp @@ -12,7 +12,7 @@ doUnlList(RPC::JsonContext& context) { Json::Value obj(Json::objectValue); - context.app.validators().for_each_listed( + context.app.getValidators().for_each_listed( [&unl = obj[jss::unl]](PublicKey const& publicKey, bool trusted) { Json::Value node(Json::objectValue); diff --git a/src/xrpld/rpc/handlers/ValidatorInfo.cpp b/src/xrpld/rpc/handlers/ValidatorInfo.cpp index 4b6663b68a..aec9dba4b4 100644 --- a/src/xrpld/rpc/handlers/ValidatorInfo.cpp +++ b/src/xrpld/rpc/handlers/ValidatorInfo.cpp @@ -21,7 +21,7 @@ doValidatorInfo(RPC::JsonContext& context) Json::Value ret; // assume validationPK is ephemeral key, get master key - auto const mk = context.app.validatorManifests().getMasterKey(*validationPK); + auto const mk = context.app.getValidatorManifests().getMasterKey(*validationPK); ret[jss::master_key] = toBase58(TokenType::NodePublic, mk); // validationPK is master key, this implies that there is no ephemeral @@ -31,13 +31,13 @@ doValidatorInfo(RPC::JsonContext& context) ret[jss::ephemeral_key] = toBase58(TokenType::NodePublic, *validationPK); - if (auto const manifest = context.app.validatorManifests().getManifest(mk)) + if (auto const manifest = context.app.getValidatorManifests().getManifest(mk)) ret[jss::manifest] = base64_encode(*manifest); - if (auto const seq = context.app.validatorManifests().getSequence(mk)) + if (auto const seq = context.app.getValidatorManifests().getSequence(mk)) ret[jss::seq] = *seq; - if (auto const domain = context.app.validatorManifests().getDomain(mk)) + if (auto const domain = context.app.getValidatorManifests().getDomain(mk)) ret[jss::domain] = *domain; return ret; diff --git a/src/xrpld/rpc/handlers/ValidatorListSites.cpp b/src/xrpld/rpc/handlers/ValidatorListSites.cpp index 7acaa27168..36e2064387 100644 --- a/src/xrpld/rpc/handlers/ValidatorListSites.cpp +++ b/src/xrpld/rpc/handlers/ValidatorListSites.cpp @@ -9,7 +9,7 @@ namespace xrpl { Json::Value doValidatorListSites(RPC::JsonContext& context) { - return context.app.validatorSites().getJson(); + return context.app.getValidatorSites().getJson(); } } // namespace xrpl diff --git a/src/xrpld/rpc/handlers/Validators.cpp b/src/xrpld/rpc/handlers/Validators.cpp index a83a6fe4b0..95e6de9e68 100644 --- a/src/xrpld/rpc/handlers/Validators.cpp +++ b/src/xrpld/rpc/handlers/Validators.cpp @@ -9,7 +9,7 @@ namespace xrpl { Json::Value doValidators(RPC::JsonContext& context) { - return context.app.validators().getJson(); + return context.app.getValidators().getJson(); } } // namespace xrpl diff --git a/src/xrpld/shamap/NodeFamily.cpp b/src/xrpld/shamap/NodeFamily.cpp index a0821ea202..ec5e9eb1b2 100644 --- a/src/xrpld/shamap/NodeFamily.cpp +++ b/src/xrpld/shamap/NodeFamily.cpp @@ -9,12 +9,12 @@ namespace xrpl { NodeFamily::NodeFamily(Application& app, CollectorManager& cm) : app_(app) , db_(app.getNodeStore()) - , j_(app.journal("NodeFamily")) + , j_(app.getJournal("NodeFamily")) , fbCache_( std::make_shared( "Node family full below cache", stopwatch(), - app.journal("NodeFamilyFulLBelowCache"), + app.getJournal("NodeFamilyFulLBelowCache"), cm.collector(), fullBelowTargetSize, fullBelowExpiration)) From 509677abfd45f365cbc8723d21470abfba9a7558 Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Thu, 26 Mar 2026 14:11:37 +0000 Subject: [PATCH 28/53] ci: Don't publish docs on release branches (#6673) --- .github/workflows/publish-docs.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/publish-docs.yml b/.github/workflows/publish-docs.yml index 4b840405bb..0c706c1ba0 100644 --- a/.github/workflows/publish-docs.yml +++ b/.github/workflows/publish-docs.yml @@ -6,7 +6,6 @@ on: push: branches: - "develop" - - "release*" paths: - ".github/workflows/publish-docs.yml" - "*.md" From 9b944ee8c2d348a204fc7cff7aa1ba6874fd12f1 Mon Sep 17 00:00:00 2001 From: Vito Tumas <5780819+Tapanito@users.noreply.github.com> Date: Fri, 27 Mar 2026 19:35:42 +0100 Subject: [PATCH 29/53] refactor: Split LoanInvariant into LoanBrokerInvariant and LoanInvariant (#6674) --- include/xrpl/tx/invariants/InvariantCheck.h | 1 + .../xrpl/tx/invariants/LoanBrokerInvariant.h | 55 +++++ include/xrpl/tx/invariants/LoanInvariant.h | 43 ---- .../tx/invariants/LoanBrokerInvariant.cpp | 194 ++++++++++++++++++ src/libxrpl/tx/invariants/LoanInvariant.cpp | 186 ----------------- 5 files changed, 250 insertions(+), 229 deletions(-) create mode 100644 include/xrpl/tx/invariants/LoanBrokerInvariant.h create mode 100644 src/libxrpl/tx/invariants/LoanBrokerInvariant.cpp diff --git a/include/xrpl/tx/invariants/InvariantCheck.h b/include/xrpl/tx/invariants/InvariantCheck.h index a053d127fb..e7ced63785 100644 --- a/include/xrpl/tx/invariants/InvariantCheck.h +++ b/include/xrpl/tx/invariants/InvariantCheck.h @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include diff --git a/include/xrpl/tx/invariants/LoanBrokerInvariant.h b/include/xrpl/tx/invariants/LoanBrokerInvariant.h new file mode 100644 index 0000000000..e7d14a638b --- /dev/null +++ b/include/xrpl/tx/invariants/LoanBrokerInvariant.h @@ -0,0 +1,55 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include + +namespace xrpl { + +/** + * @brief Invariants: Loan brokers are internally consistent + * + * 1. If `LoanBroker.OwnerCount = 0` the `DirectoryNode` will have at most one + * node (the root), which will only hold entries for `RippleState` or + * `MPToken` objects. + * + */ +class ValidLoanBroker +{ + // Not all of these elements will necessarily be populated. Remaining items + // will be looked up as needed. + struct BrokerInfo + { + SLE::const_pointer brokerBefore = nullptr; + // After is used for most of the checks, except + // those that check changed values. + SLE::const_pointer brokerAfter = nullptr; + }; + // Collect all the LoanBrokers found directly or indirectly through + // pseudo-accounts. Key is the brokerID / index. It will be used to find the + // LoanBroker object if brokerBefore and brokerAfter are nullptr + std::map brokers_; + // Collect all the modified trust lines. Their high and low accounts will be + // loaded to look for LoanBroker pseudo-accounts. + std::vector lines_; + // Collect all the modified MPTokens. Their accounts will be loaded to look + // for LoanBroker pseudo-accounts. + std::vector mpts_; + + static bool + goodZeroDirectory(ReadView const& view, SLE::const_ref dir, beast::Journal const& j); + +public: + void + visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); + + bool + finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); +}; + +} // namespace xrpl diff --git a/include/xrpl/tx/invariants/LoanInvariant.h b/include/xrpl/tx/invariants/LoanInvariant.h index 02e9db1698..bda9c51653 100644 --- a/include/xrpl/tx/invariants/LoanInvariant.h +++ b/include/xrpl/tx/invariants/LoanInvariant.h @@ -1,57 +1,14 @@ #pragma once -#include #include #include #include #include -#include #include namespace xrpl { -/** - * @brief Invariants: Loan brokers are internally consistent - * - * 1. If `LoanBroker.OwnerCount = 0` the `DirectoryNode` will have at most one - * node (the root), which will only hold entries for `RippleState` or - * `MPToken` objects. - * - */ -class ValidLoanBroker -{ - // Not all of these elements will necessarily be populated. Remaining items - // will be looked up as needed. - struct BrokerInfo - { - SLE::const_pointer brokerBefore = nullptr; - // After is used for most of the checks, except - // those that check changed values. - SLE::const_pointer brokerAfter = nullptr; - }; - // Collect all the LoanBrokers found directly or indirectly through - // pseudo-accounts. Key is the brokerID / index. It will be used to find the - // LoanBroker object if brokerBefore and brokerAfter are nullptr - std::map brokers_; - // Collect all the modified trust lines. Their high and low accounts will be - // loaded to look for LoanBroker pseudo-accounts. - std::vector lines_; - // Collect all the modified MPTokens. Their accounts will be loaded to look - // for LoanBroker pseudo-accounts. - std::vector mpts_; - - static bool - goodZeroDirectory(ReadView const& view, SLE::const_ref dir, beast::Journal const& j); - -public: - void - visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); - - bool - finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); -}; - /** * @brief Invariants: Loans are internally consistent * diff --git a/src/libxrpl/tx/invariants/LoanBrokerInvariant.cpp b/src/libxrpl/tx/invariants/LoanBrokerInvariant.cpp new file mode 100644 index 0000000000..2bc9e622ad --- /dev/null +++ b/src/libxrpl/tx/invariants/LoanBrokerInvariant.cpp @@ -0,0 +1,194 @@ +#include +// +#include +#include +#include +#include +#include +#include +#include +#include + +namespace xrpl { + +void +ValidLoanBroker::visitEntry( + bool isDelete, + std::shared_ptr const& before, + std::shared_ptr const& after) +{ + if (after) + { + if (after->getType() == ltLOAN_BROKER) + { + auto& broker = brokers_[after->key()]; + broker.brokerBefore = before; + broker.brokerAfter = after; + } + else if (after->getType() == ltACCOUNT_ROOT && after->isFieldPresent(sfLoanBrokerID)) + { + auto const& loanBrokerID = after->at(sfLoanBrokerID); + // create an entry if one doesn't already exist + brokers_.emplace(loanBrokerID, BrokerInfo{}); + } + else if (after->getType() == ltRIPPLE_STATE) + { + lines_.emplace_back(after); + } + else if (after->getType() == ltMPTOKEN) + { + mpts_.emplace_back(after); + } + } +} + +bool +ValidLoanBroker::goodZeroDirectory( + ReadView const& view, + SLE::const_ref dir, + beast::Journal const& j) +{ + auto const next = dir->at(~sfIndexNext); + auto const prev = dir->at(~sfIndexPrevious); + if ((prev && (*prev != 0u)) || (next && (*next != 0u))) + { + JLOG(j.fatal()) << "Invariant failed: Loan Broker with zero " + "OwnerCount has multiple directory pages"; + return false; + } + auto indexes = dir->getFieldV256(sfIndexes); + if (indexes.size() > 1) + { + JLOG(j.fatal()) << "Invariant failed: Loan Broker with zero " + "OwnerCount has multiple indexes in the Directory root"; + return false; + } + if (indexes.size() == 1) + { + auto const index = indexes.value().front(); + auto const sle = view.read(keylet::unchecked(index)); + if (!sle) + { + JLOG(j.fatal()) << "Invariant failed: Loan Broker directory corrupt"; + return false; + } + if (sle->getType() != ltRIPPLE_STATE && sle->getType() != ltMPTOKEN) + { + JLOG(j.fatal()) << "Invariant failed: Loan Broker with zero " + "OwnerCount has an unexpected entry in the directory"; + return false; + } + } + + return true; +} + +bool +ValidLoanBroker::finalize( + STTx const& tx, + TER const, + XRPAmount const, + ReadView const& view, + beast::Journal const& j) +{ + // Loan Brokers will not exist on ledger if the Lending Protocol amendment + // is not enabled, so there's no need to check it. + + for (auto const& line : lines_) + { + for (auto const& field : {&sfLowLimit, &sfHighLimit}) + { + auto const account = view.read(keylet::account(line->at(*field).getIssuer())); + // This Invariant doesn't know about the rules for Trust Lines, so + // if the account is missing, don't treat it as an error. This + // loop is only concerned with finding Broker pseudo-accounts + if (account && account->isFieldPresent(sfLoanBrokerID)) + { + auto const& loanBrokerID = account->at(sfLoanBrokerID); + // create an entry if one doesn't already exist + brokers_.emplace(loanBrokerID, BrokerInfo{}); + } + } + } + for (auto const& mpt : mpts_) + { + auto const account = view.read(keylet::account(mpt->at(sfAccount))); + // This Invariant doesn't know about the rules for MPTokens, so + // if the account is missing, don't treat is as an error. This + // loop is only concerned with finding Broker pseudo-accounts + if (account && account->isFieldPresent(sfLoanBrokerID)) + { + auto const& loanBrokerID = account->at(sfLoanBrokerID); + // create an entry if one doesn't already exist + brokers_.emplace(loanBrokerID, BrokerInfo{}); + } + } + + for (auto const& [brokerID, broker] : brokers_) + { + auto const& after = + broker.brokerAfter ? broker.brokerAfter : view.read(keylet::loanbroker(brokerID)); + + if (!after) + { + JLOG(j.fatal()) << "Invariant failed: Loan Broker missing"; + return false; + } + + auto const& before = broker.brokerBefore; + + // https://github.com/Tapanito/XRPL-Standards/blob/xls-66-lending-protocol/XLS-0066d-lending-protocol/README.md#3123-invariants + // If `LoanBroker.OwnerCount = 0` the `DirectoryNode` will have at most + // one node (the root), which will only hold entries for `RippleState` + // or `MPToken` objects. + if (after->at(sfOwnerCount) == 0) + { + auto const dir = view.read(keylet::ownerDir(after->at(sfAccount))); + if (dir) + { + if (!goodZeroDirectory(view, dir, j)) + { + return false; + } + } + } + if (before && before->at(sfLoanSequence) > after->at(sfLoanSequence)) + { + JLOG(j.fatal()) << "Invariant failed: Loan Broker sequence number " + "decreased"; + return false; + } + if (after->at(sfDebtTotal) < 0) + { + JLOG(j.fatal()) << "Invariant failed: Loan Broker debt total is negative"; + return false; + } + if (after->at(sfCoverAvailable) < 0) + { + JLOG(j.fatal()) << "Invariant failed: Loan Broker cover available is negative"; + return false; + } + auto const vault = view.read(keylet::vault(after->at(sfVaultID))); + if (!vault) + { + JLOG(j.fatal()) << "Invariant failed: Loan Broker vault ID is invalid"; + return false; + } + auto const& vaultAsset = vault->at(sfAsset); + if (after->at(sfCoverAvailable) < accountHolds( + view, + after->at(sfAccount), + vaultAsset, + FreezeHandling::fhIGNORE_FREEZE, + AuthHandling::ahIGNORE_AUTH, + j)) + { + JLOG(j.fatal()) << "Invariant failed: Loan Broker cover available " + "is less than pseudo-account asset balance"; + return false; + } + } + return true; +} + +} // namespace xrpl diff --git a/src/libxrpl/tx/invariants/LoanInvariant.cpp b/src/libxrpl/tx/invariants/LoanInvariant.cpp index b590eab8fd..6ce1261612 100644 --- a/src/libxrpl/tx/invariants/LoanInvariant.cpp +++ b/src/libxrpl/tx/invariants/LoanInvariant.cpp @@ -2,197 +2,11 @@ // #include #include -#include -#include -#include #include #include -#include namespace xrpl { -void -ValidLoanBroker::visitEntry( - bool isDelete, - std::shared_ptr const& before, - std::shared_ptr const& after) -{ - if (after) - { - if (after->getType() == ltLOAN_BROKER) - { - auto& broker = brokers_[after->key()]; - broker.brokerBefore = before; - broker.brokerAfter = after; - } - else if (after->getType() == ltACCOUNT_ROOT && after->isFieldPresent(sfLoanBrokerID)) - { - auto const& loanBrokerID = after->at(sfLoanBrokerID); - // create an entry if one doesn't already exist - brokers_.emplace(loanBrokerID, BrokerInfo{}); - } - else if (after->getType() == ltRIPPLE_STATE) - { - lines_.emplace_back(after); - } - else if (after->getType() == ltMPTOKEN) - { - mpts_.emplace_back(after); - } - } -} - -bool -ValidLoanBroker::goodZeroDirectory( - ReadView const& view, - SLE::const_ref dir, - beast::Journal const& j) -{ - auto const next = dir->at(~sfIndexNext); - auto const prev = dir->at(~sfIndexPrevious); - if ((prev && (*prev != 0u)) || (next && (*next != 0u))) - { - JLOG(j.fatal()) << "Invariant failed: Loan Broker with zero " - "OwnerCount has multiple directory pages"; - return false; - } - auto indexes = dir->getFieldV256(sfIndexes); - if (indexes.size() > 1) - { - JLOG(j.fatal()) << "Invariant failed: Loan Broker with zero " - "OwnerCount has multiple indexes in the Directory root"; - return false; - } - if (indexes.size() == 1) - { - auto const index = indexes.value().front(); - auto const sle = view.read(keylet::unchecked(index)); - if (!sle) - { - JLOG(j.fatal()) << "Invariant failed: Loan Broker directory corrupt"; - return false; - } - if (sle->getType() != ltRIPPLE_STATE && sle->getType() != ltMPTOKEN) - { - JLOG(j.fatal()) << "Invariant failed: Loan Broker with zero " - "OwnerCount has an unexpected entry in the directory"; - return false; - } - } - - return true; -} - -bool -ValidLoanBroker::finalize( - STTx const& tx, - TER const, - XRPAmount const, - ReadView const& view, - beast::Journal const& j) -{ - // Loan Brokers will not exist on ledger if the Lending Protocol amendment - // is not enabled, so there's no need to check it. - - for (auto const& line : lines_) - { - for (auto const& field : {&sfLowLimit, &sfHighLimit}) - { - auto const account = view.read(keylet::account(line->at(*field).getIssuer())); - // This Invariant doesn't know about the rules for Trust Lines, so - // if the account is missing, don't treat it as an error. This - // loop is only concerned with finding Broker pseudo-accounts - if (account && account->isFieldPresent(sfLoanBrokerID)) - { - auto const& loanBrokerID = account->at(sfLoanBrokerID); - // create an entry if one doesn't already exist - brokers_.emplace(loanBrokerID, BrokerInfo{}); - } - } - } - for (auto const& mpt : mpts_) - { - auto const account = view.read(keylet::account(mpt->at(sfAccount))); - // This Invariant doesn't know about the rules for MPTokens, so - // if the account is missing, don't treat is as an error. This - // loop is only concerned with finding Broker pseudo-accounts - if (account && account->isFieldPresent(sfLoanBrokerID)) - { - auto const& loanBrokerID = account->at(sfLoanBrokerID); - // create an entry if one doesn't already exist - brokers_.emplace(loanBrokerID, BrokerInfo{}); - } - } - - for (auto const& [brokerID, broker] : brokers_) - { - auto const& after = - broker.brokerAfter ? broker.brokerAfter : view.read(keylet::loanbroker(brokerID)); - - if (!after) - { - JLOG(j.fatal()) << "Invariant failed: Loan Broker missing"; - return false; - } - - auto const& before = broker.brokerBefore; - - // https://github.com/Tapanito/XRPL-Standards/blob/xls-66-lending-protocol/XLS-0066d-lending-protocol/README.md#3123-invariants - // If `LoanBroker.OwnerCount = 0` the `DirectoryNode` will have at most - // one node (the root), which will only hold entries for `RippleState` - // or `MPToken` objects. - if (after->at(sfOwnerCount) == 0) - { - auto const dir = view.read(keylet::ownerDir(after->at(sfAccount))); - if (dir) - { - if (!goodZeroDirectory(view, dir, j)) - { - return false; - } - } - } - if (before && before->at(sfLoanSequence) > after->at(sfLoanSequence)) - { - JLOG(j.fatal()) << "Invariant failed: Loan Broker sequence number " - "decreased"; - return false; - } - if (after->at(sfDebtTotal) < 0) - { - JLOG(j.fatal()) << "Invariant failed: Loan Broker debt total is negative"; - return false; - } - if (after->at(sfCoverAvailable) < 0) - { - JLOG(j.fatal()) << "Invariant failed: Loan Broker cover available is negative"; - return false; - } - auto const vault = view.read(keylet::vault(after->at(sfVaultID))); - if (!vault) - { - JLOG(j.fatal()) << "Invariant failed: Loan Broker vault ID is invalid"; - return false; - } - auto const& vaultAsset = vault->at(sfAsset); - if (after->at(sfCoverAvailable) < accountHolds( - view, - after->at(sfAccount), - vaultAsset, - FreezeHandling::fhIGNORE_FREEZE, - AuthHandling::ahIGNORE_AUTH, - j)) - { - JLOG(j.fatal()) << "Invariant failed: Loan Broker cover available " - "is less than pseudo-account asset balance"; - return false; - } - } - return true; -} - -//------------------------------------------------------------------------------ - void ValidLoan::visitEntry( bool isDelete, From 3d9c545f599fbe9e83d9df04ed8735945a51840f Mon Sep 17 00:00:00 2001 From: Pratik Mankawde <3397372+pratikmankawde@users.noreply.github.com> Date: Fri, 27 Mar 2026 18:52:18 +0000 Subject: [PATCH 30/53] fix: Guard Coro::resume() against completed coroutines (#6608) Signed-off-by: Pratik Mankawde <3397372+pratikmankawde@users.noreply.github.com> Co-authored-by: Claude Opus 4.6 --- include/xrpl/core/Coro.ipp | 16 +++++++++++++--- include/xrpl/core/JobQueue.h | 10 ++++++---- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/include/xrpl/core/Coro.ipp b/include/xrpl/core/Coro.ipp index e7c08e65a6..dca9504679 100644 --- a/include/xrpl/core/Coro.ipp +++ b/include/xrpl/core/Coro.ipp @@ -70,14 +70,24 @@ JobQueue::Coro::resume() running_ = true; } { - std::lock_guard lock(jq_.m_mutex); + std::lock_guard lk(jq_.m_mutex); --jq_.nSuspend_; } auto saved = detail::getLocalValues().release(); detail::getLocalValues().reset(&lvs_); std::lock_guard lock(mutex_); - XRPL_ASSERT(static_cast(coro_), "xrpl::JobQueue::Coro::resume : is runnable"); - coro_(); + // A late resume() can arrive after the coroutine has already completed. + // This is an expected (if rare) outcome of the race condition documented + // in JobQueue.h:354-377 where post() schedules a resume job before the + // coroutine yields — the mutex serializes access, but by the time this + // resume() acquires the lock the coroutine may have already run to + // completion. Calling operator() on a completed boost::coroutine2 is + // undefined behavior, so we must check and skip invoking the coroutine + // body if it has already completed. + if (coro_) + { + coro_(); + } detail::getLocalValues().release(); detail::getLocalValues().reset(saved); std::lock_guard lk(mutex_run_); diff --git a/include/xrpl/core/JobQueue.h b/include/xrpl/core/JobQueue.h index 583e8bc26a..fdb708ee57 100644 --- a/include/xrpl/core/JobQueue.h +++ b/include/xrpl/core/JobQueue.h @@ -99,8 +99,8 @@ public: Effects: The coroutine continues execution from where it last left off using this same thread. - Undefined behavior if called after the coroutine has completed - with a return (as opposed to a yield()). + If the coroutine has already completed, returns immediately + (handles the documented post-before-yield race condition). Undefined behavior if resume() or post() called consecutively without a corresponding yield. */ @@ -357,8 +357,10 @@ private: If the post() job were to be executed before yield(), undefined behavior would occur. The lock ensures that coro_ is not called again until we exit the coroutine. At which point a scheduled resume() job waiting on the lock - would gain entry, harmlessly call coro_ and immediately return as we have - already completed the coroutine. + would gain entry. resume() checks if the coroutine has already completed + (coro_ converts to false) and, if so, skips invoking operator() since + calling operator() on a completed boost::coroutine2 pull_type is undefined + behavior. The race condition occurs as follows: From e0cabb9f8cdd31c52c539a9ccd213adf264e944b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 30 Mar 2026 09:57:32 -0400 Subject: [PATCH 31/53] ci: [DEPENDABOT] bump codecov/codecov-action from 5.5.3 to 6.0.0 (#6685) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/reusable-build-test-config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/reusable-build-test-config.yml b/.github/workflows/reusable-build-test-config.yml index 85a033766e..27dfa2fd6a 100644 --- a/.github/workflows/reusable-build-test-config.yml +++ b/.github/workflows/reusable-build-test-config.yml @@ -298,7 +298,7 @@ jobs: - name: Upload coverage report if: ${{ github.repository == 'XRPLF/rippled' && !inputs.build_only && env.COVERAGE_ENABLED == 'true' }} - uses: codecov/codecov-action@1af58845a975a7985b0beb0cbe6fbbb71a41dbad # v5.5.3 + uses: codecov/codecov-action@57e3a136b779b570ffcdbf80b3bdc90e7fab3de2 # v6.0.0 with: disable_search: true disable_telem: true From de671863e2ba867d0c68e414a5d8472ae076b49b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 30 Mar 2026 14:09:57 +0000 Subject: [PATCH 32/53] ci: [DEPENDABOT] bump actions/deploy-pages from 4.0.5 to 5.0.0 (#6684) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/publish-docs.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish-docs.yml b/.github/workflows/publish-docs.yml index 0c706c1ba0..643a02da8d 100644 --- a/.github/workflows/publish-docs.yml +++ b/.github/workflows/publish-docs.yml @@ -99,4 +99,4 @@ jobs: steps: - name: Deploy to GitHub Pages id: deploy - uses: actions/deploy-pages@d6db90164ac5ed86f2b6aed7e0febac5b3c0c03e # v4.0.5 + uses: actions/deploy-pages@cd2ce8fcbc39b97be8ca5fce6e763baed58fa128 # v5.0.0 From 96bfc32fe25ccd2892bc4dcdacfb5bf44a607e33 Mon Sep 17 00:00:00 2001 From: Alex Kremer Date: Mon, 30 Mar 2026 15:59:53 +0100 Subject: [PATCH 33/53] chore: Fix clang-tidy header filter (#6686) --- .clang-tidy | 96 ++++++++++++++++++++++++++++------------------------- 1 file changed, 50 insertions(+), 46 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index 261da1e367..449198eef8 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,4 +1,6 @@ --- +# This entire group of checks was applied to all cpp files but not all header files. +# --- Checks: "-*, bugprone-argument-comment, bugprone-assert-side-effect, @@ -8,26 +10,26 @@ Checks: "-*, bugprone-chained-comparison, bugprone-compare-pointer-to-member-virtual-function, bugprone-copy-constructor-init, - bugprone-crtp-constructor-accessibility, + # bugprone-crtp-constructor-accessibility, # has issues bugprone-dangling-handle, bugprone-dynamic-static-initializers, - bugprone-empty-catch, + # bugprone-empty-catch, # has issues bugprone-fold-init-type, - bugprone-forward-declaration-namespace, - bugprone-inaccurate-erase, - bugprone-inc-dec-in-conditions, - bugprone-incorrect-enable-if, - bugprone-incorrect-roundings, - bugprone-infinite-loop, - bugprone-integer-division, + # bugprone-forward-declaration-namespace, # has issues + # bugprone-inaccurate-erase, + # bugprone-inc-dec-in-conditions, + # bugprone-incorrect-enable-if, + # bugprone-incorrect-roundings, + # bugprone-infinite-loop, + # bugprone-integer-division, bugprone-lambda-function-name, - bugprone-macro-parentheses, + # bugprone-macro-parentheses, # has issues bugprone-macro-repeated-side-effects, bugprone-misplaced-operator-in-strlen-in-alloc, bugprone-misplaced-pointer-arithmetic-in-alloc, bugprone-misplaced-widening-cast, bugprone-move-forwarding-reference, - bugprone-multi-level-implicit-pointer-conversion, + # bugprone-multi-level-implicit-pointer-conversion, # has issues bugprone-multiple-new-in-one-expression, bugprone-multiple-statement-macro, bugprone-no-escape, @@ -37,13 +39,13 @@ Checks: "-*, bugprone-pointer-arithmetic-on-polymorphic-object, bugprone-posix-return, bugprone-redundant-branch-condition, - bugprone-reserved-identifier, - bugprone-return-const-ref-from-parameter, + # bugprone-reserved-identifier, # has issues + # bugprone-return-const-ref-from-parameter, # has issues bugprone-shared-ptr-array-mismatch, bugprone-signal-handler, bugprone-signed-char-misuse, bugprone-sizeof-container, - bugprone-sizeof-expression, + # bugprone-sizeof-expression, # has issues bugprone-spuriously-wake-up-functions, bugprone-standalone-empty, bugprone-string-constructor, @@ -60,7 +62,7 @@ Checks: "-*, bugprone-suspicious-string-compare, bugprone-suspicious-stringview-data-usage, bugprone-swapped-arguments, - bugprone-switch-missing-default-case, + # bugprone-switch-missing-default-case, # has issues bugprone-terminating-continue, bugprone-throw-keyword-missing, bugprone-too-small-loop-variable, @@ -71,25 +73,25 @@ Checks: "-*, bugprone-unhandled-self-assignment, bugprone-unique-ptr-array-mismatch, bugprone-unsafe-functions, - bugprone-use-after-move, + # bugprone-use-after-move, # has issues bugprone-unused-raii, bugprone-unused-return-value, bugprone-unused-local-non-trivial-variable, bugprone-virtual-near-miss, - cppcoreguidelines-init-variables, - cppcoreguidelines-misleading-capture-default-by-value, + # cppcoreguidelines-init-variables, # has issues + # cppcoreguidelines-misleading-capture-default-by-value, # has issues cppcoreguidelines-no-suspend-with-lock, - cppcoreguidelines-pro-type-member-init, + # cppcoreguidelines-pro-type-member-init, # has issues cppcoreguidelines-pro-type-static-cast-downcast, - cppcoreguidelines-rvalue-reference-param-not-moved, - cppcoreguidelines-use-default-member-init, - cppcoreguidelines-virtual-class-destructor, + # cppcoreguidelines-rvalue-reference-param-not-moved, # has issues + # cppcoreguidelines-use-default-member-init, # has issues + # cppcoreguidelines-virtual-class-destructor, # has issues hicpp-ignored-remove-result, - misc-definitions-in-headers, + # misc-definitions-in-headers, # has issues misc-header-include-cycle, misc-misplaced-const, misc-static-assert, - misc-throw-by-value-catch-by-reference, + # misc-throw-by-value-catch-by-reference, # has issues misc-unused-alias-decls, misc-unused-using-decls, modernize-deprecated-headers, @@ -98,34 +100,34 @@ Checks: "-*, performance-implicit-conversion-in-loop, performance-move-constructor-init, performance-trivially-destructible, - readability-avoid-nested-conditional-operator, - readability-avoid-return-with-void-value, - readability-braces-around-statements, - readability-const-return-type, - readability-container-contains, - readability-container-size-empty, - readability-convert-member-functions-to-static, + # readability-avoid-nested-conditional-operator, # has issues + # readability-avoid-return-with-void-value, # has issues + # readability-braces-around-statements, # has issues + # readability-const-return-type, # has issues + # readability-container-contains, # has issues + # readability-container-size-empty, # has issues + # readability-convert-member-functions-to-static, # has issues readability-duplicate-include, - readability-else-after-return, - readability-enum-initial-value, - readability-implicit-bool-conversion, - readability-make-member-function-const, - readability-math-missing-parentheses, + # readability-else-after-return, # has issues + # readability-enum-initial-value, # has issues + # readability-implicit-bool-conversion, # has issues + # readability-make-member-function-const, # has issues + # readability-math-missing-parentheses, # has issues readability-misleading-indentation, readability-non-const-parameter, - readability-redundant-casting, - readability-redundant-declaration, - readability-redundant-inline-specifier, - readability-redundant-member-init, + # readability-redundant-casting, # has issues + # readability-redundant-declaration, # has issues + # readability-redundant-inline-specifier, # has issues + # readability-redundant-member-init, # has issues readability-redundant-string-init, readability-reference-to-constructed-temporary, - readability-simplify-boolean-expr, - readability-static-definition-in-anonymous-namespace, - readability-suspicious-call-argument, + # readability-simplify-boolean-expr, # has issues + # readability-static-definition-in-anonymous-namespace, # has issues + # readability-suspicious-call-argument, # has issues readability-use-std-min-max " # --- -# checks that have some issues that need to be resolved: +# other checks that have issues that need to be resolved: # # llvm-namespace-comment, # misc-const-correctness, @@ -134,7 +136,7 @@ Checks: "-*, # # readability-inconsistent-declaration-parameter-name, # in this codebase this check will break a lot of arg names # readability-static-accessed-through-instance, # this check is probably unnecessary. it makes the code less readable -# readability-identifier-naming, +# readability-identifier-naming, # https://github.com/XRPLF/rippled/pull/6571 # # modernize-concat-nested-namespaces, # modernize-pass-by-value, @@ -149,6 +151,7 @@ Checks: "-*, # modernize-use-std-numbers, # modernize-use-using, # +# the following are in https://github.com/XRPLF/rippled/pull/6648 : # performance-faster-string-find, # performance-for-range-copy, # performance-inefficient-vector-operation, @@ -195,5 +198,6 @@ CheckOptions: bugprone-unused-return-value.CheckedReturnTypes: ::std::error_code;::std::error_condition;::std::errc # misc-include-cleaner.IgnoreHeaders: '.*/(detail|impl)/.*;.*(expected|unexpected).*;.*ranges_lower_bound\.h;time.h;stdlib.h;__chrono/.*;fmt/chrono.h;boost/uuid/uuid_hash.hpp' # -# HeaderFilterRegex: '^.*/(src|tests)/.*\.(h|hpp)$' +HeaderFilterRegex: '^.*/(test|xrpl|xrpld)/.*\.(h|hpp)$' +ExcludeHeaderFilterRegex: '^.*/protocol_autogen/.*\.(h|hpp)$' WarningsAsErrors: "*" From 3a477e4d0189454303ea82bac98048b4591909ff Mon Sep 17 00:00:00 2001 From: Jingchen Date: Mon, 30 Mar 2026 16:22:38 +0100 Subject: [PATCH 34/53] refactor: Address PR comments after the modularisation PRs (#6389) Signed-off-by: JCW Co-authored-by: Bart --- include/xrpl/core/StartUpType.h | 2 +- include/xrpl/ledger/OrderBookDB.h | 19 +- include/xrpl/protocol/TxSearched.h | 2 +- include/xrpl/rdb/DatabaseCon.h | 7 +- include/xrpl/rdb/RelationalDatabase.h | 19 +- include/xrpl/tx/ApplyContext.h | 2 +- include/xrpl/tx/Transactor.h | 4 +- src/libxrpl/rdb/DatabaseCon.cpp | 2 +- src/libxrpl/tx/Transactor.cpp | 17 +- .../tx/transactors/account/SignerListSet.cpp | 2 +- .../tx/transactors/check/CheckCancel.cpp | 2 +- .../tx/transactors/check/CheckCash.cpp | 2 +- .../tx/transactors/check/CheckCreate.cpp | 2 +- src/libxrpl/tx/transactors/dex/AMMCreate.cpp | 2 +- .../tx/transactors/dex/OfferCancel.cpp | 2 +- .../tx/transactors/dex/OfferCreate.cpp | 8 +- .../tx/transactors/escrow/EscrowFinish.cpp | 6 +- .../payment_channel/PaymentChannelClaim.cpp | 4 +- .../payment_channel/PaymentChannelFund.cpp | 2 +- src/libxrpl/tx/transactors/system/Change.cpp | 8 +- .../tx/transactors/system/TicketCreate.cpp | 2 +- src/libxrpl/tx/transactors/token/TrustSet.cpp | 2 +- src/test/app/LedgerLoad_test.cpp | 20 +- src/test/rpc/LedgerEntry_test.cpp | 4 +- src/xrpld/app/ledger/OrderBookDBImpl.cpp | 10 +- src/xrpld/app/ledger/OrderBookDBImpl.h | 4 +- src/xrpld/app/main/Application.cpp | 17 +- src/xrpld/app/main/Main.cpp | 14 +- src/xrpld/app/misc/NetworkOPs.cpp | 320 +++++++++--------- src/xrpld/app/misc/make_NetworkOPs.h | 6 +- src/xrpld/app/rdb/backend/SQLiteDatabase.h | 8 +- src/xrpld/app/rdb/backend/detail/Node.cpp | 30 +- src/xrpld/app/rdb/backend/detail/Node.h | 6 +- .../app/rdb/backend/detail/SQLiteDatabase.cpp | 35 +- src/xrpld/core/Config.h | 2 +- src/xrpld/rpc/handlers/AccountTx.cpp | 7 +- src/xrpld/rpc/handlers/Tx.cpp | 8 +- 37 files changed, 315 insertions(+), 294 deletions(-) diff --git a/include/xrpl/core/StartUpType.h b/include/xrpl/core/StartUpType.h index 74a1898806..46359ad7b6 100644 --- a/include/xrpl/core/StartUpType.h +++ b/include/xrpl/core/StartUpType.h @@ -5,7 +5,7 @@ namespace xrpl { -enum class StartUpType { FRESH, NORMAL, LOAD, LOAD_FILE, REPLAY, NETWORK }; +enum class StartUpType { Fresh, Normal, Load, LoadFile, Replay, Network }; inline std::ostream& operator<<(std::ostream& os, StartUpType const& type) diff --git a/include/xrpl/ledger/OrderBookDB.h b/include/xrpl/ledger/OrderBookDB.h index 3d689607bf..5bf66eb4ab 100644 --- a/include/xrpl/ledger/OrderBookDB.h +++ b/include/xrpl/ledger/OrderBookDB.h @@ -76,16 +76,33 @@ public: @return true if a book from this issue to XRP exists */ virtual bool - isBookToXRP(Issue const& issue, std::optional domain = std::nullopt) = 0; + isBookToXRP(Issue const& issue, std::optional const& domain = std::nullopt) = 0; + /** + * Process a transaction for order book tracking. + * @param ledger The ledger the transaction was applied to + * @param alTx The transaction to process + * @param jvObj The JSON object of the transaction + */ virtual void processTxn( std::shared_ptr const& ledger, AcceptedLedgerTx const& alTx, MultiApiJson const& jvObj) = 0; + /** + * Get the book listeners for a book. + * @param book The book to get the listeners for + * @return The book listeners for the book + */ virtual BookListeners::pointer getBookListeners(Book const&) = 0; + + /** + * Create a new book listeners for a book. + * @param book The book to create the listeners for + * @return The new book listeners for the book + */ virtual BookListeners::pointer makeBookListeners(Book const&) = 0; }; diff --git a/include/xrpl/protocol/TxSearched.h b/include/xrpl/protocol/TxSearched.h index e085bff315..71bd75005b 100644 --- a/include/xrpl/protocol/TxSearched.h +++ b/include/xrpl/protocol/TxSearched.h @@ -2,6 +2,6 @@ namespace xrpl { -enum class TxSearched { all, some, unknown }; +enum class TxSearched { All, Some, Unknown }; } diff --git a/include/xrpl/rdb/DatabaseCon.h b/include/xrpl/rdb/DatabaseCon.h index b7231f4859..bd7b9ca803 100644 --- a/include/xrpl/rdb/DatabaseCon.h +++ b/include/xrpl/rdb/DatabaseCon.h @@ -70,7 +70,7 @@ public: { explicit Setup() = default; - StartUpType startUp = StartUpType::NORMAL; + StartUpType startUp = StartUpType::Normal; bool standAlone = false; boost::filesystem::path dataDir; // Indicates whether or not to return the `globalPragma` @@ -107,9 +107,8 @@ public: beast::Journal journal) // Use temporary files or regular DB files? : DatabaseCon( - setup.standAlone && setup.startUp != StartUpType::LOAD && - setup.startUp != StartUpType::LOAD_FILE && - setup.startUp != StartUpType::REPLAY + setup.standAlone && setup.startUp != StartUpType::Load && + setup.startUp != StartUpType::LoadFile && setup.startUp != StartUpType::Replay ? "" : (setup.dataDir / dbName), setup.commonPragma(), diff --git a/include/xrpl/rdb/RelationalDatabase.h b/include/xrpl/rdb/RelationalDatabase.h index e728e518aa..56c20e4263 100644 --- a/include/xrpl/rdb/RelationalDatabase.h +++ b/include/xrpl/rdb/RelationalDatabase.h @@ -49,8 +49,9 @@ public: struct AccountTxOptions { AccountID const& account; - std::uint32_t minLedger; - std::uint32_t maxLedger; + /// Ledger sequence range to search. A value of 0 for min or max + /// means unbounded in that direction (no constraint applied). + LedgerRange ledgerRange; std::uint32_t offset; std::uint32_t limit; bool bUnlimited; @@ -59,8 +60,7 @@ public: struct AccountTxPageOptions { AccountID const& account; - std::uint32_t minLedger; - std::uint32_t maxLedger; + LedgerRange ledgerRange; std::optional marker; std::uint32_t limit; bool bAdmin; @@ -247,7 +247,7 @@ public: * @return Struct CountMinMax which contains the minimum sequence, * maximum sequence and number of ledgers. */ - virtual struct CountMinMax + virtual CountMinMax getLedgerCountMinMax() = 0; /** @@ -405,10 +405,10 @@ public: * @param id Hash of the transaction. * @param range Range of ledgers to check, if present. * @param ec Default error code value. - * @return Transaction and its metadata if found, otherwise TxSearched::all + * @return Transaction and its metadata if found, otherwise TxSearched::All * if a range is provided and all ledgers from the range are present - * in the database, TxSearched::some if a range is provided and not - * all ledgers are present, TxSearched::unknown if the range is not + * in the database, TxSearched::Some if a range is provided and not + * all ledgers are present, TxSearched::Unknown if the range is not * provided or a deserializing error occurred. In the last case the * error code is returned via the ec parameter, in other cases the * default error code is not changed. @@ -455,9 +455,10 @@ public: closeTransactionDB() = 0; }; -template +template T rangeCheckedCast(C c) + requires(std::is_arithmetic_v && std::is_arithmetic_v && std::convertible_to) { if ((c > std::numeric_limits::max()) || (!std::numeric_limits::is_signed && c < 0) || (std::numeric_limits::is_signed && std::numeric_limits::is_signed && diff --git a/include/xrpl/tx/ApplyContext.h b/include/xrpl/tx/ApplyContext.h index efef568f29..6341c0bcc5 100644 --- a/include/xrpl/tx/ApplyContext.h +++ b/include/xrpl/tx/ApplyContext.h @@ -37,7 +37,7 @@ public: XRPL_ASSERT((flags & tapBATCH) == 0, "Batch apply flag should not be set"); } - ServiceRegistry& registry; + std::reference_wrapper registry; STTx const& tx; TER const preclaimResult; XRPAmount const baseFee; diff --git a/include/xrpl/tx/Transactor.h b/include/xrpl/tx/Transactor.h index 8d816f60f8..e9d3159919 100644 --- a/include/xrpl/tx/Transactor.h +++ b/include/xrpl/tx/Transactor.h @@ -13,7 +13,7 @@ namespace xrpl { struct PreflightContext { public: - ServiceRegistry& registry; + std::reference_wrapper registry; STTx const& tx; Rules const rules; ApplyFlags flags; @@ -56,7 +56,7 @@ public: struct PreclaimContext { public: - ServiceRegistry& registry; + std::reference_wrapper registry; ReadView const& view; TER preflightResult; ApplyFlags flags; diff --git a/src/libxrpl/rdb/DatabaseCon.cpp b/src/libxrpl/rdb/DatabaseCon.cpp index 81686c78a6..d064192a14 100644 --- a/src/libxrpl/rdb/DatabaseCon.cpp +++ b/src/libxrpl/rdb/DatabaseCon.cpp @@ -29,7 +29,7 @@ public: auto it = checkpointers_.find(id); if (it != checkpointers_.end()) return it->second; - return {}; + return nullptr; } void diff --git a/src/libxrpl/tx/Transactor.cpp b/src/libxrpl/tx/Transactor.cpp index 5c87d4342f..9560c4e752 100644 --- a/src/libxrpl/tx/Transactor.cpp +++ b/src/libxrpl/tx/Transactor.cpp @@ -34,7 +34,7 @@ preflight0(PreflightContext const& ctx, std::uint32_t flagMask) if (!isPseudoTx(ctx.tx) || ctx.tx.isFieldPresent(sfNetworkID)) { - uint32_t nodeNID = ctx.registry.getNetworkIDService().getNetworkID(); + uint32_t nodeNID = ctx.registry.get().getNetworkIDService().getNetworkID(); std::optional txNID = ctx.tx[~sfNetworkID]; if (nodeNID <= 1024) @@ -211,7 +211,7 @@ Transactor::preflight2(PreflightContext const& ctx) // Do not add any checks after this point that are relevant for // batch inner transactions. They will be skipped. - auto const sigValid = checkValidity(ctx.registry.getHashRouter(), ctx.tx, ctx.rules); + auto const sigValid = checkValidity(ctx.registry.get().getHashRouter(), ctx.tx, ctx.rules); if (sigValid.first == Validity::SigBad) { // LCOV_EXCL_START JLOG(ctx.j.debug()) << "preflight2: bad signature. " << sigValid.second; @@ -1095,7 +1095,8 @@ Transactor::operator()() } #endif - if (auto const& trap = ctx_.registry.getTrapTxID(); trap && *trap == ctx_.tx.getTransactionID()) + if (auto const& trap = ctx_.registry.get().getTrapTxID(); + trap && *trap == ctx_.tx.getTransactionID()) { trapTransaction(*trap); } @@ -1198,23 +1199,25 @@ Transactor::operator()() // If necessary, remove any offers found unfunded during processing if ((result == tecOVERSIZE) || (result == tecKILLED)) { - removeUnfundedOffers(view(), removedOffers, ctx_.registry.getJournal("View")); + removeUnfundedOffers(view(), removedOffers, ctx_.registry.get().getJournal("View")); } if (result == tecEXPIRED) { removeExpiredNFTokenOffers( - view(), expiredNFTokenOffers, ctx_.registry.getJournal("View")); + view(), expiredNFTokenOffers, ctx_.registry.get().getJournal("View")); } if (result == tecINCOMPLETE) { - removeDeletedTrustLines(view(), removedTrustLines, ctx_.registry.getJournal("View")); + removeDeletedTrustLines( + view(), removedTrustLines, ctx_.registry.get().getJournal("View")); } if (result == tecEXPIRED) { - removeExpiredCredentials(view(), expiredCredentials, ctx_.registry.getJournal("View")); + removeExpiredCredentials( + view(), expiredCredentials, ctx_.registry.get().getJournal("View")); } applied = isTecClaim(result); diff --git a/src/libxrpl/tx/transactors/account/SignerListSet.cpp b/src/libxrpl/tx/transactors/account/SignerListSet.cpp index 70e8f21df5..22fb98afd8 100644 --- a/src/libxrpl/tx/transactors/account/SignerListSet.cpp +++ b/src/libxrpl/tx/transactors/account/SignerListSet.cpp @@ -314,7 +314,7 @@ SignerListSet::replaceSignerList() view().insert(signerList); writeSignersToSLE(signerList, flags); - auto viewJ = ctx_.registry.getJournal("View"); + auto viewJ = ctx_.registry.get().getJournal("View"); // Add the signer list to the account's directory. auto const page = ctx_.view().dirInsert(ownerDirKeylet, signerListKeylet, describeOwnerDir(account_)); diff --git a/src/libxrpl/tx/transactors/check/CheckCancel.cpp b/src/libxrpl/tx/transactors/check/CheckCancel.cpp index 50aab27f2b..be3b434fb6 100644 --- a/src/libxrpl/tx/transactors/check/CheckCancel.cpp +++ b/src/libxrpl/tx/transactors/check/CheckCancel.cpp @@ -57,7 +57,7 @@ CheckCancel::doApply() AccountID const srcId{sleCheck->getAccountID(sfAccount)}; AccountID const dstId{sleCheck->getAccountID(sfDestination)}; - auto viewJ = ctx_.registry.getJournal("View"); + auto viewJ = ctx_.registry.get().getJournal("View"); // If the check is not written to self (and it shouldn't be), remove the // check from the destination account root. diff --git a/src/libxrpl/tx/transactors/check/CheckCash.cpp b/src/libxrpl/tx/transactors/check/CheckCash.cpp index ea770bf37f..f477896cb1 100644 --- a/src/libxrpl/tx/transactors/check/CheckCash.cpp +++ b/src/libxrpl/tx/transactors/check/CheckCash.cpp @@ -232,7 +232,7 @@ CheckCash::doApply() // // If it is not a check to self (as should be the case), then there's // work to do... - auto viewJ = ctx_.registry.getJournal("View"); + auto viewJ = ctx_.registry.get().getJournal("View"); auto const optDeliverMin = ctx_.tx[~sfDeliverMin]; if (srcId != account_) diff --git a/src/libxrpl/tx/transactors/check/CheckCreate.cpp b/src/libxrpl/tx/transactors/check/CheckCreate.cpp index dfcc528f7b..fde3373691 100644 --- a/src/libxrpl/tx/transactors/check/CheckCreate.cpp +++ b/src/libxrpl/tx/transactors/check/CheckCreate.cpp @@ -168,7 +168,7 @@ CheckCreate::doApply() view().insert(sleCheck); - auto viewJ = ctx_.registry.getJournal("View"); + auto viewJ = ctx_.registry.get().getJournal("View"); // If it's not a self-send (and it shouldn't be), add Check to the // destination's owner directory. if (dstAccountId != account_) diff --git a/src/libxrpl/tx/transactors/dex/AMMCreate.cpp b/src/libxrpl/tx/transactors/dex/AMMCreate.cpp index dd717948b3..6dabf084bf 100644 --- a/src/libxrpl/tx/transactors/dex/AMMCreate.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMCreate.cpp @@ -281,7 +281,7 @@ applyCreate(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::J Book const book{issueIn, issueOut, std::nullopt}; auto const dir = keylet::quality(keylet::book(book), uRate); if (auto const bookExisted = static_cast(sb.read(dir)); !bookExisted) - ctx_.registry.getOrderBookDB().addOrderBook(book); + ctx_.registry.get().getOrderBookDB().addOrderBook(book); }; addOrderBook(amount.issue(), amount2.issue(), getRate(amount2, amount)); addOrderBook(amount2.issue(), amount.issue(), getRate(amount, amount2)); diff --git a/src/libxrpl/tx/transactors/dex/OfferCancel.cpp b/src/libxrpl/tx/transactors/dex/OfferCancel.cpp index 7e094306e9..f8164401b7 100644 --- a/src/libxrpl/tx/transactors/dex/OfferCancel.cpp +++ b/src/libxrpl/tx/transactors/dex/OfferCancel.cpp @@ -53,7 +53,7 @@ OfferCancel::doApply() if (auto sleOffer = view().peek(keylet::offer(account_, offerSequence))) { JLOG(j_.debug()) << "Trying to cancel offer #" << offerSequence; - return offerDelete(view(), sleOffer, ctx_.registry.getJournal("View")); + return offerDelete(view(), sleOffer, ctx_.registry.get().getJournal("View")); } JLOG(j_.debug()) << "Offer #" << offerSequence << " can't be found."; diff --git a/src/libxrpl/tx/transactors/dex/OfferCreate.cpp b/src/libxrpl/tx/transactors/dex/OfferCreate.cpp index 602fa9f447..76c49aee57 100644 --- a/src/libxrpl/tx/transactors/dex/OfferCreate.cpp +++ b/src/libxrpl/tx/transactors/dex/OfferCreate.cpp @@ -144,7 +144,7 @@ OfferCreate::preclaim(PreclaimContext const& ctx) std::uint32_t const uAccountSequence = sleCreator->getFieldU32(sfSequence); - auto viewJ = ctx.registry.getJournal("View"); + auto viewJ = ctx.registry.get().getJournal("View"); if (isGlobalFrozen(ctx.view, uPaysIssuerID) || isGlobalFrozen(ctx.view, uGetsIssuerID)) { @@ -502,7 +502,7 @@ OfferCreate::applyHybrid( bookArr.push_back(std::move(bookInfo)); if (!bookExists) - ctx_.registry.getOrderBookDB().addOrderBook(book); + ctx_.registry.get().getOrderBookDB().addOrderBook(book); sleOffer->setFieldArray(sfAdditionalBooks, bookArr); return tesSUCCESS; @@ -536,7 +536,7 @@ OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) // end up on the books. auto uRate = getRate(saTakerGets, saTakerPays); - auto viewJ = ctx_.registry.getJournal("View"); + auto viewJ = ctx_.registry.get().getJournal("View"); TER result = tesSUCCESS; @@ -846,7 +846,7 @@ OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) sb.insert(sleOffer); if (!bookExisted) - ctx_.registry.getOrderBookDB().addOrderBook(book); + ctx_.registry.get().getOrderBookDB().addOrderBook(book); JLOG(j_.debug()) << "final result: success"; diff --git a/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp b/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp index 8a05b2b160..f64229ff69 100644 --- a/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp +++ b/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp @@ -73,7 +73,7 @@ EscrowFinish::preflightSigValidated(PreflightContext const& ctx) if (cb && fb) { - auto& router = ctx.registry.getHashRouter(); + auto& router = ctx.registry.get().getHashRouter(); auto const id = ctx.tx.getTransactionID(); auto const flags = router.getFlags(id); @@ -237,7 +237,7 @@ EscrowFinish::doApply() // Check cryptocondition fulfillment { auto const id = ctx_.tx.getTransactionID(); - auto flags = ctx_.registry.getHashRouter().getFlags(id); + auto flags = ctx_.registry.get().getHashRouter().getFlags(id); auto const cb = ctx_.tx[~sfCondition]; @@ -261,7 +261,7 @@ EscrowFinish::doApply() flags = SF_CF_INVALID; } - ctx_.registry.getHashRouter().setFlags(id, flags); + ctx_.registry.get().getHashRouter().setFlags(id, flags); // LCOV_EXCL_STOP } diff --git a/src/libxrpl/tx/transactors/payment_channel/PaymentChannelClaim.cpp b/src/libxrpl/tx/transactors/payment_channel/PaymentChannelClaim.cpp index 10508dda96..91de511883 100644 --- a/src/libxrpl/tx/transactors/payment_channel/PaymentChannelClaim.cpp +++ b/src/libxrpl/tx/transactors/payment_channel/PaymentChannelClaim.cpp @@ -108,7 +108,7 @@ PaymentChannelClaim::doApply() auto const closeTime = ctx_.view().header().parentCloseTime.time_since_epoch().count(); if ((cancelAfter && closeTime >= *cancelAfter) || (curExpiration && closeTime >= *curExpiration)) - return closeChannel(slep, ctx_.view(), k.key, ctx_.registry.getJournal("View")); + return closeChannel(slep, ctx_.view(), k.key, ctx_.registry.get().getJournal("View")); } if (txAccount != src && txAccount != dst) @@ -169,7 +169,7 @@ PaymentChannelClaim::doApply() { // Channel will close immediately if dry or the receiver closes if (dst == txAccount || (*slep)[sfBalance] == (*slep)[sfAmount]) - return closeChannel(slep, ctx_.view(), k.key, ctx_.registry.getJournal("View")); + return closeChannel(slep, ctx_.view(), k.key, ctx_.registry.get().getJournal("View")); auto const settleExpiration = ctx_.view().header().parentCloseTime.time_since_epoch().count() + diff --git a/src/libxrpl/tx/transactors/payment_channel/PaymentChannelFund.cpp b/src/libxrpl/tx/transactors/payment_channel/PaymentChannelFund.cpp index 1ffb19ce6f..c42e8545f5 100644 --- a/src/libxrpl/tx/transactors/payment_channel/PaymentChannelFund.cpp +++ b/src/libxrpl/tx/transactors/payment_channel/PaymentChannelFund.cpp @@ -38,7 +38,7 @@ PaymentChannelFund::doApply() auto const cancelAfter = (*slep)[~sfCancelAfter]; auto const closeTime = ctx_.view().header().parentCloseTime.time_since_epoch().count(); if ((cancelAfter && closeTime >= *cancelAfter) || (expiration && closeTime >= *expiration)) - return closeChannel(slep, ctx_.view(), k.key, ctx_.registry.getJournal("View")); + return closeChannel(slep, ctx_.view(), k.key, ctx_.registry.get().getJournal("View")); } if (src != txAccount) diff --git a/src/libxrpl/tx/transactors/system/Change.cpp b/src/libxrpl/tx/transactors/system/Change.cpp index b863f06cad..2648902095 100644 --- a/src/libxrpl/tx/transactors/system/Change.cpp +++ b/src/libxrpl/tx/transactors/system/Change.cpp @@ -200,7 +200,7 @@ Change::applyAmendment() entry[sfAmendment] = amendment; entry[sfCloseTime] = view().parentCloseTime().time_since_epoch().count(); - if (!ctx_.registry.getAmendmentTable().isSupported(amendment)) + if (!ctx_.registry.get().getAmendmentTable().isSupported(amendment)) { JLOG(j_.warn()) << "Unsupported amendment " << amendment << " received a majority."; } @@ -211,13 +211,13 @@ Change::applyAmendment() amendments.push_back(amendment); amendmentObject->setFieldV256(sfAmendments, amendments); - ctx_.registry.getAmendmentTable().enable(amendment); + ctx_.registry.get().getAmendmentTable().enable(amendment); - if (!ctx_.registry.getAmendmentTable().isSupported(amendment)) + if (!ctx_.registry.get().getAmendmentTable().isSupported(amendment)) { JLOG(j_.error()) << "Unsupported amendment " << amendment << " activated: server blocked."; - ctx_.registry.getOPs().setAmendmentBlocked(); + ctx_.registry.get().getOPs().setAmendmentBlocked(); } } diff --git a/src/libxrpl/tx/transactors/system/TicketCreate.cpp b/src/libxrpl/tx/transactors/system/TicketCreate.cpp index e5100164df..0c41e503e4 100644 --- a/src/libxrpl/tx/transactors/system/TicketCreate.cpp +++ b/src/libxrpl/tx/transactors/system/TicketCreate.cpp @@ -70,7 +70,7 @@ TicketCreate::doApply() return tecINSUFFICIENT_RESERVE; } - beast::Journal viewJ{ctx_.registry.getJournal("View")}; + beast::Journal viewJ{ctx_.registry.get().getJournal("View")}; // The starting ticket sequence is the same as the current account // root sequence. Before we got here to doApply(), the transaction diff --git a/src/libxrpl/tx/transactors/token/TrustSet.cpp b/src/libxrpl/tx/transactors/token/TrustSet.cpp index 9602eb61d5..37935f07c2 100644 --- a/src/libxrpl/tx/transactors/token/TrustSet.cpp +++ b/src/libxrpl/tx/transactors/token/TrustSet.cpp @@ -366,7 +366,7 @@ TrustSet::doApply() bool const bSetDeepFreeze = (uTxFlags & tfSetDeepFreeze) != 0u; bool const bClearDeepFreeze = (uTxFlags & tfClearDeepFreeze) != 0u; - auto viewJ = ctx_.registry.getJournal("View"); + auto viewJ = ctx_.registry.get().getJournal("View"); SLE::pointer sleDst = view().peek(keylet::account(uDstAccountID)); diff --git a/src/test/app/LedgerLoad_test.cpp b/src/test/app/LedgerLoad_test.cpp index 46c372923e..2fa1193921 100644 --- a/src/test/app/LedgerLoad_test.cpp +++ b/src/test/app/LedgerLoad_test.cpp @@ -109,7 +109,7 @@ class LedgerLoad_test : public beast::unit_test::suite // create a new env with the ledger file specified for startup Env env( *this, - envconfig(ledgerConfig, sd.dbPath, sd.ledgerFile, StartUpType::LOAD_FILE, std::nullopt), + envconfig(ledgerConfig, sd.dbPath, sd.ledgerFile, StartUpType::LoadFile, std::nullopt), nullptr, beast::severities::kDisabled); auto jrb = env.rpc("ledger", "current", "full")[jss::result]; @@ -129,7 +129,7 @@ class LedgerLoad_test : public beast::unit_test::suite except([&] { Env env( *this, - envconfig(ledgerConfig, sd.dbPath, "", StartUpType::LOAD_FILE, std::nullopt), + envconfig(ledgerConfig, sd.dbPath, "", StartUpType::LoadFile, std::nullopt), nullptr, beast::severities::kDisabled); }); @@ -139,7 +139,7 @@ class LedgerLoad_test : public beast::unit_test::suite Env env( *this, envconfig( - ledgerConfig, sd.dbPath, "badfile.json", StartUpType::LOAD_FILE, std::nullopt), + ledgerConfig, sd.dbPath, "badfile.json", StartUpType::LoadFile, std::nullopt), nullptr, beast::severities::kDisabled); }); @@ -164,7 +164,7 @@ class LedgerLoad_test : public beast::unit_test::suite ledgerConfig, sd.dbPath, ledgerFileCorrupt.string(), - StartUpType::LOAD_FILE, + StartUpType::LoadFile, std::nullopt), nullptr, beast::severities::kDisabled); @@ -182,7 +182,7 @@ class LedgerLoad_test : public beast::unit_test::suite boost::erase_all(ledgerHash, "\""); Env env( *this, - envconfig(ledgerConfig, sd.dbPath, ledgerHash, StartUpType::LOAD, std::nullopt), + envconfig(ledgerConfig, sd.dbPath, ledgerHash, StartUpType::Load, std::nullopt), nullptr, beast::severities::kDisabled); auto jrb = env.rpc("ledger", "current", "full")[jss::result]; @@ -203,7 +203,7 @@ class LedgerLoad_test : public beast::unit_test::suite boost::erase_all(ledgerHash, "\""); Env env( *this, - envconfig(ledgerConfig, sd.dbPath, ledgerHash, StartUpType::REPLAY, std::nullopt), + envconfig(ledgerConfig, sd.dbPath, ledgerHash, StartUpType::Replay, std::nullopt), nullptr, beast::severities::kDisabled); auto const jrb = env.rpc("ledger", "current", "full")[jss::result]; @@ -229,7 +229,7 @@ class LedgerLoad_test : public beast::unit_test::suite boost::erase_all(ledgerHash, "\""); Env env( *this, - envconfig(ledgerConfig, sd.dbPath, ledgerHash, StartUpType::REPLAY, sd.trapTxHash), + envconfig(ledgerConfig, sd.dbPath, ledgerHash, StartUpType::Replay, sd.trapTxHash), nullptr, beast::severities::kDisabled); auto const jrb = env.rpc("ledger", "current", "full")[jss::result]; @@ -259,7 +259,7 @@ class LedgerLoad_test : public beast::unit_test::suite // replay when trapTxHash is set to an invalid transaction Env env( *this, - envconfig(ledgerConfig, sd.dbPath, ledgerHash, StartUpType::REPLAY, ~sd.trapTxHash), + envconfig(ledgerConfig, sd.dbPath, ledgerHash, StartUpType::Replay, ~sd.trapTxHash), nullptr, beast::severities::kDisabled); BEAST_EXPECT(false); @@ -283,7 +283,7 @@ class LedgerLoad_test : public beast::unit_test::suite // create a new env with the ledger "latest" specified for startup Env env( *this, - envconfig(ledgerConfig, sd.dbPath, "latest", StartUpType::LOAD, std::nullopt), + envconfig(ledgerConfig, sd.dbPath, "latest", StartUpType::Load, std::nullopt), nullptr, beast::severities::kDisabled); auto jrb = env.rpc("ledger", "current", "full")[jss::result]; @@ -301,7 +301,7 @@ class LedgerLoad_test : public beast::unit_test::suite // create a new env with specific ledger index at startup Env env( *this, - envconfig(ledgerConfig, sd.dbPath, "43", StartUpType::LOAD, std::nullopt), + envconfig(ledgerConfig, sd.dbPath, "43", StartUpType::Load, std::nullopt), nullptr, beast::severities::kDisabled); auto jrb = env.rpc("ledger", "current", "full")[jss::result]; diff --git a/src/test/rpc/LedgerEntry_test.cpp b/src/test/rpc/LedgerEntry_test.cpp index fd7efaede4..474f29da17 100644 --- a/src/test/rpc/LedgerEntry_test.cpp +++ b/src/test/rpc/LedgerEntry_test.cpp @@ -2189,7 +2189,7 @@ class LedgerEntry_test : public beast::unit_test::suite Account const bob{"bob"}; Env env{*this, envconfig([](auto cfg) { - cfg->START_UP = StartUpType::FRESH; + cfg->START_UP = StartUpType::Fresh; return cfg; })}; @@ -2382,7 +2382,7 @@ class LedgerEntry_test : public beast::unit_test::suite Account const bob{"bob"}; Env env{*this, envconfig([](auto cfg) { - cfg->START_UP = StartUpType::FRESH; + cfg->START_UP = StartUpType::Fresh; return cfg; })}; diff --git a/src/xrpld/app/ledger/OrderBookDBImpl.cpp b/src/xrpld/app/ledger/OrderBookDBImpl.cpp index 7626d148bd..c8ea46cf7f 100644 --- a/src/xrpld/app/ledger/OrderBookDBImpl.cpp +++ b/src/xrpld/app/ledger/OrderBookDBImpl.cpp @@ -26,7 +26,7 @@ make_OrderBookDB(ServiceRegistry& registry, OrderBookDBConfig const& config) void OrderBookDBImpl::setup(std::shared_ptr const& ledger) { - if (!standalone_ && registry_.getOPs().isNeedNetworkLedger()) + if (!standalone_ && registry_.get().getOPs().isNeedNetworkLedger()) { JLOG(j_.warn()) << "Eliding full order book update: no ledger"; return; @@ -56,7 +56,7 @@ OrderBookDBImpl::setup(std::shared_ptr const& ledger) } else { - registry_.getJobQueue().addJob( + registry_.get().getJobQueue().addJob( jtUPDATE_PF, "OBUpd" + std::to_string(ledger->seq()), [this, ledger]() { update(ledger); }); @@ -95,7 +95,7 @@ OrderBookDBImpl::update(std::shared_ptr const& ledger) { for (auto& sle : ledger->sles) { - if (registry_.isStopping()) + if (registry_.get().isStopping()) { JLOG(j_.info()) << "Update halted because the process is stopping"; seq_.store(0); @@ -167,7 +167,7 @@ OrderBookDBImpl::update(std::shared_ptr const& ledger) xrpDomainBooks_.swap(xrpDomainBooks); } - registry_.getLedgerMaster().newOrderBookDB(); + registry_.get().getLedgerMaster().newOrderBookDB(); } void @@ -249,7 +249,7 @@ OrderBookDBImpl::getBookSize(Issue const& issue, std::optional const& d } bool -OrderBookDBImpl::isBookToXRP(Issue const& issue, std::optional domain) +OrderBookDBImpl::isBookToXRP(Issue const& issue, std::optional const& domain) { std::lock_guard sl(mLock); if (domain) diff --git a/src/xrpld/app/ledger/OrderBookDBImpl.h b/src/xrpld/app/ledger/OrderBookDBImpl.h index d9043f942e..4dd413438e 100644 --- a/src/xrpld/app/ledger/OrderBookDBImpl.h +++ b/src/xrpld/app/ledger/OrderBookDBImpl.h @@ -48,7 +48,7 @@ public: getBookSize(Issue const& issue, std::optional const& domain = std::nullopt) override; bool - isBookToXRP(Issue const& issue, std::optional domain = std::nullopt) override; + isBookToXRP(Issue const& issue, std::optional const& domain = std::nullopt) override; // OrderBookDBImpl-specific methods void @@ -67,7 +67,7 @@ public: makeBookListeners(Book const&) override; private: - ServiceRegistry& registry_; + std::reference_wrapper registry_; int const pathSearchMax_; bool const standalone_; diff --git a/src/xrpld/app/main/Application.cpp b/src/xrpld/app/main/Application.cpp index 39bb4d5b22..76a95bd542 100644 --- a/src/xrpld/app/main/Application.cpp +++ b/src/xrpld/app/main/Application.cpp @@ -782,8 +782,7 @@ public: { XRPL_ASSERT( relationalDatabase_, - "xrpl::ApplicationImp::getRelationalDatabase : non-null " - "relational database"); + "xrpl::ApplicationImp::getRelationalDatabase : non-null relational database"); return *relationalDatabase_; } @@ -1214,22 +1213,22 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) auto const startUp = config_->START_UP; JLOG(m_journal.debug()) << "startUp: " << startUp; - if (startUp == StartUpType::FRESH) + if (startUp == StartUpType::Fresh) { JLOG(m_journal.info()) << "Starting new Ledger"; startGenesisLedger(); } else if ( - startUp == StartUpType::LOAD || startUp == StartUpType::LOAD_FILE || - startUp == StartUpType::REPLAY) + startUp == StartUpType::Load || startUp == StartUpType::LoadFile || + startUp == StartUpType::Replay) { JLOG(m_journal.info()) << "Loading specified Ledger"; if (!loadOldLedger( config_->START_LEDGER, - startUp == StartUpType::REPLAY, - startUp == StartUpType::LOAD_FILE, + startUp == StartUpType::Replay, + startUp == StartUpType::LoadFile, config_->TRAP_TX_HASH)) { JLOG(m_journal.error()) << "The specified ledger could not be loaded."; @@ -1245,7 +1244,7 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) } } } - else if (startUp == StartUpType::NETWORK) + else if (startUp == StartUpType::Network) { // This should probably become the default once we have a stable // network. @@ -1636,7 +1635,7 @@ ApplicationImp::fdRequired() const void ApplicationImp::startGenesisLedger() { - std::vector const initialAmendments = (config_->START_UP == StartUpType::FRESH) + std::vector const initialAmendments = (config_->START_UP == StartUpType::Fresh) ? m_amendmentTable->getDesired() : std::vector{}; diff --git a/src/xrpld/app/main/Main.cpp b/src/xrpld/app/main/Main.cpp index e2bd4423d9..85f6ae651a 100644 --- a/src/xrpld/app/main/Main.cpp +++ b/src/xrpld/app/main/Main.cpp @@ -613,7 +613,7 @@ run(int argc, char** argv) if (vm.contains("start")) { - config->START_UP = StartUpType::FRESH; + config->START_UP = StartUpType::Fresh; } if (vm.contains("import")) @@ -624,7 +624,7 @@ run(int argc, char** argv) config->START_LEDGER = vm["ledger"].as(); if (vm.contains("replay")) { - config->START_UP = StartUpType::REPLAY; + config->START_UP = StartUpType::Replay; if (vm.contains("trap_tx_hash")) { uint256 tmp = {}; @@ -644,17 +644,17 @@ run(int argc, char** argv) } else { - config->START_UP = StartUpType::LOAD; + config->START_UP = StartUpType::Load; } } else if (vm.contains("ledgerfile")) { config->START_LEDGER = vm["ledgerfile"].as(); - config->START_UP = StartUpType::LOAD_FILE; + config->START_UP = StartUpType::LoadFile; } else if (vm.contains("load") || config->FAST_LOAD) { - config->START_UP = StartUpType::LOAD; + config->START_UP = StartUpType::Load; } if (vm.contains("trap_tx_hash") && !vm.contains("replay")) @@ -665,13 +665,13 @@ run(int argc, char** argv) if (vm.contains("net") && !config->FAST_LOAD) { - if ((config->START_UP == StartUpType::LOAD) || (config->START_UP == StartUpType::REPLAY)) + if ((config->START_UP == StartUpType::Load) || (config->START_UP == StartUpType::Replay)) { std::cerr << "Net and load/replay options are incompatible" << std::endl; return -1; } - config->START_UP = StartUpType::NETWORK; + config->START_UP = StartUpType::Network; } if (vm.contains("valid")) diff --git a/src/xrpld/app/misc/NetworkOPs.cpp b/src/xrpld/app/misc/NetworkOPs.cpp index d7b42076c7..ffccf765f0 100644 --- a/src/xrpld/app/misc/NetworkOPs.cpp +++ b/src/xrpld/app/misc/NetworkOPs.cpp @@ -216,27 +216,27 @@ public: JobQueue& job_queue, LedgerMaster& ledgerMaster, ValidatorKeys const& validatorKeys, - boost::asio::io_context& io_svc, + boost::asio::io_context& ioCtx, beast::Journal journal, beast::insight::Collector::ptr const& collector) : registry_(registry) , m_journal(journal) , m_localTX(make_LocalTxs()) , mMode(start_valid ? OperatingMode::FULL : OperatingMode::DISCONNECTED) - , heartbeatTimer_(io_svc) - , clusterTimer_(io_svc) - , accountHistoryTxTimer_(io_svc) + , heartbeatTimer_(ioCtx) + , clusterTimer_(ioCtx) + , accountHistoryTxTimer_(ioCtx) , mConsensus( - registry_.getApp(), + registry_.get().getApp(), make_FeeVote( - setup_FeeVote(registry_.getApp().config().section("voting")), - registry_.getJournal("FeeVote")), + setup_FeeVote(registry_.get().getApp().config().section("voting")), + registry_.get().getJournal("FeeVote")), ledgerMaster, *m_localTX, registry.getInboundTransactions(), beast::get_abstract_clock(), validatorKeys, - registry_.getJournal("LedgerConsensus")) + registry_.get().getJournal("LedgerConsensus")) , validatorPK_( validatorKeys.keys ? validatorKeys.keys->publicKey : decltype(validatorPK_){}) , validatorMasterPK_( @@ -690,7 +690,7 @@ private: void setAccountHistoryJobTimer(SubAccountHistoryInfoWeak subInfo); - ServiceRegistry& registry_; + std::reference_wrapper registry_; beast::Journal m_journal; std::unique_ptr m_localTX; @@ -877,7 +877,7 @@ NetworkOPsImp::getHostId(bool forAdmin) // For non-admin uses hash the node public key into a // single RFC1751 word: static std::string const shroudedHostId = [this]() { - auto const& id = registry_.getApp().nodeIdentity(); + auto const& id = registry_.get().getApp().nodeIdentity(); return RFC1751::getWordFromBlob(id.first.data(), id.first.size()); }(); @@ -891,7 +891,7 @@ NetworkOPsImp::setStateTimer() setHeartbeatTimer(); // Only do this work if a cluster is configured - if (registry_.getCluster().size() != 0) + if (registry_.get().getCluster().size() != 0) setClusterTimer(); } @@ -969,13 +969,13 @@ NetworkOPsImp::processHeartbeatTimer() { RclConsensusLogger clog("Heartbeat Timer", mConsensus.validating(), m_journal); { - std::unique_lock lock{registry_.getApp().getMasterMutex()}; + std::unique_lock lock{registry_.get().getApp().getMasterMutex()}; // VFALCO NOTE This is for diagnosing a crash on exit - LoadManager& mgr(registry_.getLoadManager()); + LoadManager& mgr(registry_.get().getLoadManager()); mgr.heartbeat(); - std::size_t const numPeers = registry_.getOverlay().size(); + std::size_t const numPeers = registry_.get().getOverlay().size(); // do we have sufficient peers? If not, we are disconnected. if (numPeers < minPeerCount_) @@ -1031,7 +1031,7 @@ NetworkOPsImp::processHeartbeatTimer() CLOG(clog.ss()) << ". "; } - mConsensus.timerEntry(registry_.getTimeKeeper().closeTime(), clog.ss()); + mConsensus.timerEntry(registry_.get().getTimeKeeper().closeTime(), clog.ss()); CLOG(clog.ss()) << "consensus phase " << to_string(mLastConsensusPhase); ConsensusPhase const currPhase = mConsensus.phase(); @@ -1049,17 +1049,18 @@ NetworkOPsImp::processHeartbeatTimer() void NetworkOPsImp::processClusterTimer() { - if (registry_.getCluster().size() == 0) + if (registry_.get().getCluster().size() == 0) return; using namespace std::chrono_literals; - bool const update = registry_.getCluster().update( - registry_.getApp().nodeIdentity().first, + bool const update = registry_.get().getCluster().update( + registry_.get().getApp().nodeIdentity().first, "", - (m_ledgerMaster.getValidatedLedgerAge() <= 4min) ? registry_.getFeeTrack().getLocalFee() - : 0, - registry_.getTimeKeeper().now()); + (m_ledgerMaster.getValidatedLedgerAge() <= 4min) + ? registry_.get().getFeeTrack().getLocalFee() + : 0, + registry_.get().getTimeKeeper().now()); if (!update) { @@ -1069,7 +1070,7 @@ NetworkOPsImp::processClusterTimer() } protocol::TMCluster cluster; - registry_.getCluster().for_each([&cluster](ClusterNode const& node) { + registry_.get().getCluster().for_each([&cluster](ClusterNode const& node) { protocol::TMClusterNode& n = *cluster.add_clusternodes(); n.set_publickey(toBase58(TokenType::NodePublic, node.identity())); n.set_reporttime(node.getReportTime().time_since_epoch().count()); @@ -1078,14 +1079,14 @@ NetworkOPsImp::processClusterTimer() n.set_nodename(node.name()); }); - Resource::Gossip gossip = registry_.getResourceManager().exportConsumers(); + Resource::Gossip gossip = registry_.get().getResourceManager().exportConsumers(); for (auto& item : gossip.items) { protocol::TMLoadSource& node = *cluster.add_loadsources(); node.set_name(to_string(item.address)); node.set_cost(item.balance); } - registry_.getOverlay().foreach( + registry_.get().getOverlay().foreach( send_if(std::make_shared(cluster, protocol::mtCLUSTER), peer_in_cluster())); setClusterTimer(); } @@ -1131,7 +1132,7 @@ NetworkOPsImp::submitTransaction(std::shared_ptr const& iTrans) auto const trans = sterilize(*iTrans); auto const txid = trans->getTransactionID(); - auto const flags = registry_.getHashRouter().getFlags(txid); + auto const flags = registry_.get().getHashRouter().getFlags(txid); if ((flags & HashRouterFlags::BAD) != HashRouterFlags::UNDEFINED) { @@ -1141,8 +1142,8 @@ NetworkOPsImp::submitTransaction(std::shared_ptr const& iTrans) try { - auto const [validity, reason] = - checkValidity(registry_.getHashRouter(), *trans, m_ledgerMaster.getValidatedRules()); + auto const [validity, reason] = checkValidity( + registry_.get().getHashRouter(), *trans, m_ledgerMaster.getValidatedRules()); if (validity != Validity::Valid) { @@ -1159,7 +1160,7 @@ NetworkOPsImp::submitTransaction(std::shared_ptr const& iTrans) std::string reason; - auto tx = std::make_shared(trans, reason, registry_.getApp()); + auto tx = std::make_shared(trans, reason, registry_.get().getApp()); m_job_queue.addJob(jtTRANSACTION, "SubmitTxn", [this, tx]() { auto t = tx; @@ -1170,7 +1171,7 @@ NetworkOPsImp::submitTransaction(std::shared_ptr const& iTrans) bool NetworkOPsImp::preProcessTransaction(std::shared_ptr& transaction) { - auto const newFlags = registry_.getHashRouter().getFlags(transaction->getID()); + auto const newFlags = registry_.get().getHashRouter().getFlags(transaction->getID()); if ((newFlags & HashRouterFlags::BAD) != HashRouterFlags::UNDEFINED) { @@ -1191,14 +1192,15 @@ NetworkOPsImp::preProcessTransaction(std::shared_ptr& transaction) { transaction->setStatus(INVALID); transaction->setResult(temINVALID_FLAG); - registry_.getHashRouter().setFlags(transaction->getID(), HashRouterFlags::BAD); + registry_.get().getHashRouter().setFlags(transaction->getID(), HashRouterFlags::BAD); return false; } // NOTE ximinez - I think this check is redundant, // but I'm not 100% sure yet. // If so, only cost is looking up HashRouter flags. - auto const [validity, reason] = checkValidity(registry_.getHashRouter(), sttx, view->rules()); + auto const [validity, reason] = + checkValidity(registry_.get().getHashRouter(), sttx, view->rules()); XRPL_ASSERT( validity == Validity::Valid, "xrpl::NetworkOPsImp::processTransaction : valid validity"); @@ -1208,12 +1210,12 @@ NetworkOPsImp::preProcessTransaction(std::shared_ptr& transaction) JLOG(m_journal.info()) << "Transaction has bad signature: " << reason; transaction->setStatus(INVALID); transaction->setResult(temBAD_SIGNATURE); - registry_.getHashRouter().setFlags(transaction->getID(), HashRouterFlags::BAD); + registry_.get().getHashRouter().setFlags(transaction->getID(), HashRouterFlags::BAD); return false; } // canonicalize can change our pointer - registry_.getMasterTransaction().canonicalize(&transaction); + registry_.get().getMasterTransaction().canonicalize(&transaction); return true; } @@ -1320,7 +1322,7 @@ NetworkOPsImp::processTransactionSet(CanonicalTXSet const& set) for (auto const& [_, tx] : set) { std::string reason; - auto transaction = std::make_shared(tx, reason, registry_.getApp()); + auto transaction = std::make_shared(tx, reason, registry_.get().getApp()); if (transaction->getStatus() == INVALID) { @@ -1328,7 +1330,7 @@ NetworkOPsImp::processTransactionSet(CanonicalTXSet const& set) { JLOG(m_journal.trace()) << "Exception checking transaction: " << reason; } - registry_.getHashRouter().setFlags(tx->getTransactionID(), HashRouterFlags::BAD); + registry_.get().getHashRouter().setFlags(tx->getTransactionID(), HashRouterFlags::BAD); continue; } @@ -1406,13 +1408,12 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) batchLock.unlock(); { - std::unique_lock masterLock{registry_.getApp().getMasterMutex(), std::defer_lock}; + std::unique_lock masterLock{registry_.get().getApp().getMasterMutex(), std::defer_lock}; bool changed = false; { std::unique_lock ledgerLock{m_ledgerMaster.peekMutex(), std::defer_lock}; std::lock(masterLock, ledgerLock); - - registry_.getOpenLedger().modify([&](OpenView& view, beast::Journal j) { + registry_.get().getOpenLedger().modify([&](OpenView& view, beast::Journal j) { for (TransactionStatus& e : transactions) { // we check before adding to the batch @@ -1423,8 +1424,8 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) if (e.failType == FailHard::yes) flags |= tapFAIL_HARD; - auto const result = registry_.getTxQ().apply( - registry_.getApp(), view, e.transaction->getSTransaction(), flags, j); + auto const result = registry_.get().getTxQ().apply( + registry_.get().getApp(), view, e.transaction->getSTransaction(), flags, j); e.result = result.ter; e.applied = result.applied; changed = changed || result.applied; @@ -1439,7 +1440,7 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) if (auto const l = m_ledgerMaster.getValidatedLedger()) validatedLedgerIndex = l->header().seq; - auto newOL = registry_.getOpenLedger().current(); + auto newOL = registry_.get().getOpenLedger().current(); for (TransactionStatus& e : transactions) { e.transaction->clearSubmitResult(); @@ -1453,7 +1454,10 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) e.transaction->setResult(e.result); if (isTemMalformed(e.result)) - registry_.getHashRouter().setFlags(e.transaction->getID(), HashRouterFlags::BAD); + { + registry_.get().getHashRouter().setFlags( + e.transaction->getID(), HashRouterFlags::BAD); + } #ifdef DEBUG if (!isTesSuccess(e.result)) @@ -1488,7 +1492,7 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) batchLock.lock(); std::string reason; auto const trans = sterilize(*txNext); - auto t = std::make_shared(trans, reason, registry_.getApp()); + auto t = std::make_shared(trans, reason, registry_.get().getApp()); if (t->getApplying()) break; submit_held.emplace_back(t, false, false, FailHard::no); @@ -1542,7 +1546,7 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) // up!) // if (e.local || (ledgersLeft && ledgersLeft <= LocalTxs::holdLedgers) || - registry_.getHashRouter().setFlags( + registry_.get().getHashRouter().setFlags( e.transaction->getID(), HashRouterFlags::HELD)) { // transaction should be held @@ -1579,7 +1583,8 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) (e.result == terQUEUED)) && !enforceFailHard) { - auto const toSkip = registry_.getHashRouter().shouldRelay(e.transaction->getID()); + auto const toSkip = + registry_.get().getHashRouter().shouldRelay(e.transaction->getID()); if (auto const sttx = *(e.transaction->getSTransaction()); toSkip && // Skip relaying if it's an inner batch txn. The flag should // only be set if the Batch feature is enabled. If Batch is @@ -1594,18 +1599,19 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) tx.set_rawtransaction(s.data(), s.size()); tx.set_status(protocol::tsCURRENT); tx.set_receivetimestamp( - registry_.getTimeKeeper().now().time_since_epoch().count()); + registry_.get().getTimeKeeper().now().time_since_epoch().count()); tx.set_deferred(e.result == terQUEUED); // FIXME: This should be when we received it - registry_.getOverlay().relay(e.transaction->getID(), tx, *toSkip); + registry_.get().getOverlay().relay(e.transaction->getID(), tx, *toSkip); e.transaction->setBroadcast(); } } if (validatedLedgerIndex) { - auto [fee, accountSeq, availableSeq] = registry_.getTxQ().getTxRequiredFeeAndSeq( - *newOL, e.transaction->getSTransaction()); + auto [fee, accountSeq, availableSeq] = + registry_.get().getTxQ().getTxRequiredFeeAndSeq( + *newOL, e.transaction->getSTransaction()); e.transaction->setCurrentLedgerState( *validatedLedgerIndex, fee, accountSeq, availableSeq); } @@ -1783,7 +1789,7 @@ NetworkOPsImp::checkLastClosedLedger(Overlay::PeerSequence const& peerList, uint //------------------------------------------------------------------------- // Determine preferred last closed ledger - auto& validations = registry_.getValidations(); + auto& validations = registry_.get().getValidations(); JLOG(m_journal.debug()) << "ValidationTrie " << Json::Compact(validations.getJsonTrie()); // Will rely on peer LCL if no trusted validations exist @@ -1831,7 +1837,7 @@ NetworkOPsImp::checkLastClosedLedger(Overlay::PeerSequence const& peerList, uint if (!consensus) { - consensus = registry_.getInboundLedgers().acquire( + consensus = registry_.get().getInboundLedgers().acquire( closedLedger, 0, InboundLedger::Reason::CONSENSUS); } @@ -1874,7 +1880,7 @@ NetworkOPsImp::switchLastClosedLedger(std::shared_ptr const& newLC clearNeedNetworkLedger(); // Update fee computations. - registry_.getTxQ().processClosedLedger(registry_.getApp(), *newLCL, true); + registry_.get().getTxQ().processClosedLedger(registry_.get().getApp(), *newLCL, true); // Caller must own master lock { @@ -1882,18 +1888,18 @@ NetworkOPsImp::switchLastClosedLedger(std::shared_ptr const& newLC // open ledger. Then apply local tx. auto retries = m_localTX->getTxSet(); - auto const lastVal = registry_.getLedgerMaster().getValidatedLedger(); + auto const lastVal = registry_.get().getLedgerMaster().getValidatedLedger(); std::optional rules; if (lastVal) { - rules = makeRulesGivenLedger(*lastVal, registry_.getApp().config().features); + rules = makeRulesGivenLedger(*lastVal, registry_.get().getApp().config().features); } else { - rules.emplace(registry_.getApp().config().features); + rules.emplace(registry_.get().getApp().config().features); } - registry_.getOpenLedger().accept( - registry_.getApp(), + registry_.get().getOpenLedger().accept( + registry_.get().getApp(), *rules, newLCL, OrderedTxs({}), @@ -1903,7 +1909,7 @@ NetworkOPsImp::switchLastClosedLedger(std::shared_ptr const& newLC "jump", [&](OpenView& view, beast::Journal j) { // Stuff the ledger with transactions from the queue. - return registry_.getTxQ().accept(registry_.getApp(), view); + return registry_.get().getTxQ().accept(registry_.get().getApp(), view); }); } @@ -1912,12 +1918,11 @@ NetworkOPsImp::switchLastClosedLedger(std::shared_ptr const& newLC protocol::TMStatusChange s; s.set_newevent(protocol::neSWITCHED_LEDGER); s.set_ledgerseq(newLCL->header().seq); - s.set_networktime(registry_.getTimeKeeper().now().time_since_epoch().count()); + s.set_networktime(registry_.get().getTimeKeeper().now().time_since_epoch().count()); s.set_ledgerhashprevious( newLCL->header().parentHash.begin(), newLCL->header().parentHash.size()); s.set_ledgerhash(newLCL->header().hash.begin(), newLCL->header().hash.size()); - - registry_.getOverlay().foreach( + registry_.get().getOverlay().foreach( send_always(std::make_shared(s, protocol::mtSTATUS_CHANGE))); } @@ -1958,24 +1963,24 @@ NetworkOPsImp::beginConsensus( "xrpl::NetworkOPsImp::beginConsensus : closedLedger parent matches " "hash"); - registry_.getValidators().setNegativeUNL(prevLedger->negativeUNL()); - TrustChanges const changes = registry_.getValidators().updateTrusted( - registry_.getValidations().getCurrentNodeIDs(), + registry_.get().getValidators().setNegativeUNL(prevLedger->negativeUNL()); + TrustChanges const changes = registry_.get().getValidators().updateTrusted( + registry_.get().getValidations().getCurrentNodeIDs(), closingInfo.parentCloseTime, *this, - registry_.getOverlay(), - registry_.getHashRouter()); + registry_.get().getOverlay(), + registry_.get().getHashRouter()); if (!changes.added.empty() || !changes.removed.empty()) { - registry_.getValidations().trustChanged(changes.added, changes.removed); + registry_.get().getValidations().trustChanged(changes.added, changes.removed); // Update the AmendmentTable so it tracks the current validators. - registry_.getAmendmentTable().trustChanged( - registry_.getValidators().getQuorumKeys().second); + registry_.get().getAmendmentTable().trustChanged( + registry_.get().getValidators().getQuorumKeys().second); } mConsensus.startRound( - registry_.getTimeKeeper().closeTime(), + registry_.get().getTimeKeeper().closeTime(), networkClosed, prevLedger, changes.removed, @@ -2015,34 +2020,30 @@ NetworkOPsImp::processTrustedProposal(RCLCxPeerPos peerPos) return false; } - return mConsensus.peerProposal(registry_.getTimeKeeper().closeTime(), peerPos); + return mConsensus.peerProposal(registry_.get().getTimeKeeper().closeTime(), peerPos); } void NetworkOPsImp::mapComplete(std::shared_ptr const& map, bool fromAcquire) { // We now have an additional transaction set - // either created locally during the consensus process - // or acquired from a peer - // Inform peers we have this set protocol::TMHaveTransactionSet msg; msg.set_hash(map->getHash().as_uint256().begin(), 256 / 8); msg.set_status(protocol::tsHAVE); - registry_.getOverlay().foreach( + registry_.get().getOverlay().foreach( send_always(std::make_shared(msg, protocol::mtHAVE_SET))); // We acquired it because consensus asked us to if (fromAcquire) - mConsensus.gotTxSet(registry_.getTimeKeeper().closeTime(), RCLTxSet{map}); + mConsensus.gotTxSet(registry_.get().getTimeKeeper().closeTime(), RCLTxSet{map}); } void NetworkOPsImp::endConsensus(std::unique_ptr const& clog) { uint256 deadLedger = m_ledgerMaster.getClosedLedger()->header().parentHash; - - for (auto const& it : registry_.getOverlay().getActivePeers()) + for (auto const& it : registry_.get().getOverlay().getActivePeers()) { if (it && (it->getClosedLedgerHash() == deadLedger)) { @@ -2053,7 +2054,7 @@ NetworkOPsImp::endConsensus(std::unique_ptr const& clog) uint256 networkClosed; bool ledgerChange = - checkLastClosedLedger(registry_.getOverlay().getActivePeers(), networkClosed); + checkLastClosedLedger(registry_.get().getOverlay().getActivePeers(), networkClosed); if (networkClosed.isZero()) { @@ -2083,7 +2084,7 @@ NetworkOPsImp::endConsensus(std::unique_ptr const& clog) // Note: Do not go to FULL if we don't have the previous ledger // check if the ledger is bad enough to go to CONNECTED -- TODO auto current = m_ledgerMaster.getCurrentLedger(); - if (registry_.getTimeKeeper().now() < + if (registry_.get().getTimeKeeper().now() < (current->header().parentCloseTime + 2 * current->header().closeTimeResolution)) { setMode(OperatingMode::FULL); @@ -2191,9 +2192,9 @@ NetworkOPsImp::pubServer() Json::Value jvObj(Json::objectValue); ServerFeeSummary f{ - registry_.getOpenLedger().current()->fees().base, - registry_.getTxQ().getMetrics(*registry_.getOpenLedger().current()), - registry_.getFeeTrack()}; + registry_.get().getOpenLedger().current()->fees().base, + registry_.get().getTxQ().getMetrics(*registry_.get().getOpenLedger().current()), + registry_.get().getFeeTrack()}; jvObj[jss::type] = "serverStatus"; jvObj[jss::server_status] = strOperatingMode(); @@ -2287,7 +2288,7 @@ NetworkOPsImp::pubValidation(std::shared_ptr const& val) jvObj[jss::flags] = val->getFlags(); jvObj[jss::signing_time] = *(*val)[~sfSigningTime]; jvObj[jss::data] = strHex(val->getSerializer().slice()); - jvObj[jss::network_id] = registry_.getNetworkIDService().getNetworkID(); + jvObj[jss::network_id] = registry_.get().getNetworkIDService().getNetworkID(); if (auto version = (*val)[~sfServerVersion]) jvObj[jss::server_version] = std::to_string(*version); @@ -2298,7 +2299,7 @@ NetworkOPsImp::pubValidation(std::shared_ptr const& val) if (auto hash = (*val)[~sfValidatedHash]) jvObj[jss::validated_hash] = strHex(*hash); - auto const masterKey = registry_.getValidatorManifests().getMasterKey(signerPublic); + auto const masterKey = registry_.get().getValidatorManifests().getMasterKey(signerPublic); if (masterKey != signerPublic) jvObj[jss::master_key] = toBase58(TokenType::NodePublic, masterKey); @@ -2407,12 +2408,12 @@ NetworkOPsImp::setMode(OperatingMode om) using namespace std::chrono_literals; if (om == OperatingMode::CONNECTED) { - if (registry_.getLedgerMaster().getValidatedLedgerAge() < 1min) + if (registry_.get().getLedgerMaster().getValidatedLedgerAge() < 1min) om = OperatingMode::SYNCING; } else if (om == OperatingMode::SYNCING) { - if (registry_.getLedgerMaster().getValidatedLedgerAge() >= 1min) + if (registry_.get().getLedgerMaster().getValidatedLedgerAge() >= 1min) om = OperatingMode::CONNECTED; } @@ -2448,7 +2449,7 @@ NetworkOPsImp::recvValidation(std::shared_ptr const& val, std::str pendingValidations_.insert(val->getLedgerHash()); } scope_unlock unlock(lock); - handleNewValidation(registry_.getApp(), val, source, bypassAccept, m_journal); + handleNewValidation(registry_.get().getApp(), val, source, bypassAccept, m_journal); } catch (std::exception const& e) { @@ -2471,7 +2472,7 @@ NetworkOPsImp::recvValidation(std::shared_ptr const& val, std::str JLOG(m_journal.debug()) << [this, &val]() -> auto { std::stringstream ss; ss << "VALIDATION: " << val->render() << " master_key: "; - auto master = registry_.getValidators().getTrustedKey(val->getSignerPublic()); + auto master = registry_.get().getValidators().getTrustedKey(val->getSignerPublic()); if (master) { ss << toBase58(TokenType::NodePublic, *master); @@ -2485,7 +2486,7 @@ NetworkOPsImp::recvValidation(std::shared_ptr const& val, std::str // We will always relay trusted validations; if configured, we will // also relay all untrusted validations. - return registry_.getApp().config().RELAY_UNTRUSTED_VALIDATIONS == 1 || val->isTrusted(); + return registry_.get().getApp().config().RELAY_UNTRUSTED_VALIDATIONS == 1 || val->isTrusted(); } Json::Value @@ -2527,7 +2528,8 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) "One or more unsupported amendments have reached majority. " "Upgrade to the latest version before they are activated " "to avoid being amendment blocked."; - if (auto const expected = registry_.getAmendmentTable().firstUnsupportedExpected()) + if (auto const expected = + registry_.get().getAmendmentTable().firstUnsupportedExpected()) { auto& d = w[jss::details] = Json::objectValue; d[jss::expected_date] = expected->time_since_epoch().count(); @@ -2544,8 +2546,8 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) info[jss::hostid] = getHostId(admin); // domain: if configured with a domain, report it: - if (!registry_.getApp().config().SERVER_DOMAIN.empty()) - info[jss::server_domain] = registry_.getApp().config().SERVER_DOMAIN; + if (!registry_.get().getApp().config().SERVER_DOMAIN.empty()) + info[jss::server_domain] = registry_.get().getApp().config().SERVER_DOMAIN; info[jss::build_version] = BuildInfo::getVersionString(); @@ -2557,14 +2559,15 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) if (needNetworkLedger_) info[jss::network_ledger] = "waiting"; - info[jss::validation_quorum] = static_cast(registry_.getValidators().quorum()); + info[jss::validation_quorum] = + static_cast(registry_.get().getValidators().quorum()); if (admin) { // Note: By default the node size is "tiny". When parsing it's an error if the final // NODE_SIZE is over 4 so below code should be safe. // NOLINTNEXTLINE(bugprone-switch-missing-default-case) - switch (registry_.getApp().config().NODE_SIZE) + switch (registry_.get().getApp().config().NODE_SIZE) { case 0: info[jss::node_size] = "tiny"; @@ -2583,7 +2586,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) break; } - auto when = registry_.getValidators().expires(); + auto when = registry_.get().getValidators().expires(); if (!human) { @@ -2601,7 +2604,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) { auto& x = (info[jss::validator_list] = Json::objectValue); - x[jss::count] = static_cast(registry_.getValidators().count()); + x[jss::count] = static_cast(registry_.get().getValidators().count()); if (when) { @@ -2614,7 +2617,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) { x[jss::expiration] = to_string(*when); - if (*when > registry_.getTimeKeeper().now()) + if (*when > registry_.get().getTimeKeeper().now()) { x[jss::status] = "active"; } @@ -2640,12 +2643,13 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) x[jss::branch] = xrpl::git::getBuildBranch(); } } - info[jss::io_latency_ms] = static_cast(registry_.getApp().getIOLatency().count()); + info[jss::io_latency_ms] = + static_cast(registry_.get().getApp().getIOLatency().count()); if (admin) { - if (auto const localPubKey = registry_.getValidators().localPublicKey(); - localPubKey && registry_.getApp().getValidationPublicKey()) + if (auto const localPubKey = registry_.get().getValidators().localPublicKey(); + localPubKey && registry_.get().getApp().getValidationPublicKey()) { info[jss::pubkey_validator] = toBase58(TokenType::NodePublic, localPubKey.value()); } @@ -2657,18 +2661,18 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) if (counters) { - info[jss::counters] = registry_.getPerfLog().countersJson(); + info[jss::counters] = registry_.get().getPerfLog().countersJson(); Json::Value nodestore(Json::objectValue); - registry_.getNodeStore().getCountsJson(nodestore); + registry_.get().getNodeStore().getCountsJson(nodestore); info[jss::counters][jss::nodestore] = nodestore; - info[jss::current_activities] = registry_.getPerfLog().currentJson(); + info[jss::current_activities] = registry_.get().getPerfLog().currentJson(); } info[jss::pubkey_node] = - toBase58(TokenType::NodePublic, registry_.getApp().nodeIdentity().first); + toBase58(TokenType::NodePublic, registry_.get().getApp().nodeIdentity().first); - info[jss::complete_ledgers] = registry_.getLedgerMaster().getCompleteLedgers(); + info[jss::complete_ledgers] = registry_.get().getLedgerMaster().getCompleteLedgers(); if (amendmentBlocked_) info[jss::amendment_blocked] = true; @@ -2678,7 +2682,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) if (fp != 0) info[jss::fetch_pack] = Json::UInt(fp); - info[jss::peers] = Json::UInt(registry_.getOverlay().size()); + info[jss::peers] = Json::UInt(registry_.get().getOverlay().size()); Json::Value lastClose = Json::objectValue; lastClose[jss::proposers] = Json::UInt(mConsensus.prevProposers()); @@ -2700,14 +2704,14 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) if (admin) info[jss::load] = m_job_queue.getJson(); - if (auto const netid = registry_.getOverlay().networkID()) + if (auto const netid = registry_.get().getOverlay().networkID()) info[jss::network_id] = static_cast(*netid); auto const escalationMetrics = - registry_.getTxQ().getMetrics(*registry_.getOpenLedger().current()); + registry_.get().getTxQ().getMetrics(*registry_.get().getOpenLedger().current()); - auto const loadFactorServer = registry_.getFeeTrack().getLoadFactor(); - auto const loadBaseServer = registry_.getFeeTrack().getLoadBase(); + auto const loadFactorServer = registry_.get().getFeeTrack().getLoadFactor(); + auto const loadBaseServer = registry_.get().getFeeTrack().getLoadBase(); /* Scale the escalated fee level to unitless "load factor". In practice, this just strips the units, but it will continue to work correctly if either base value ever changes. */ @@ -2744,13 +2748,13 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) if (admin) { - std::uint32_t fee = registry_.getFeeTrack().getLocalFee(); + std::uint32_t fee = registry_.get().getFeeTrack().getLocalFee(); if (fee != loadBaseServer) info[jss::load_factor_local] = static_cast(fee) / loadBaseServer; - fee = registry_.getFeeTrack().getRemoteFee(); + fee = registry_.get().getFeeTrack().getRemoteFee(); if (fee != loadBaseServer) info[jss::load_factor_net] = static_cast(fee) / loadBaseServer; - fee = registry_.getFeeTrack().getClusterFee(); + fee = registry_.get().getFeeTrack().getClusterFee(); if (fee != loadBaseServer) info[jss::load_factor_cluster] = static_cast(fee) / loadBaseServer; } @@ -2802,7 +2806,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) l[jss::reserve_base_xrp] = lpClosed->fees().reserve.decimalXRP(); l[jss::reserve_inc_xrp] = lpClosed->fees().increment.decimalXRP(); - if (auto const closeOffset = registry_.getTimeKeeper().closeOffset(); + if (auto const closeOffset = registry_.get().getTimeKeeper().closeOffset(); std::abs(closeOffset.count()) >= 60) l[jss::close_time_offset] = static_cast(closeOffset.count()); @@ -2815,7 +2819,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) else { auto lCloseTime = lpClosed->header().closeTime; - auto closeTime = registry_.getTimeKeeper().closeTime(); + auto closeTime = registry_.get().getTimeKeeper().closeTime(); if (lCloseTime <= closeTime) { using namespace std::chrono_literals; @@ -2847,10 +2851,11 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) accounting_.json(info); info[jss::uptime] = UptimeClock::now().time_since_epoch().count(); - info[jss::jq_trans_overflow] = std::to_string(registry_.getOverlay().getJqTransOverflow()); - info[jss::peer_disconnects] = std::to_string(registry_.getOverlay().getPeerDisconnect()); + info[jss::jq_trans_overflow] = + std::to_string(registry_.get().getOverlay().getJqTransOverflow()); + info[jss::peer_disconnects] = std::to_string(registry_.get().getOverlay().getPeerDisconnect()); info[jss::peer_disconnects_resources] = - std::to_string(registry_.getOverlay().getPeerDisconnectCharges()); + std::to_string(registry_.get().getOverlay().getPeerDisconnectCharges()); // This array must be sorted in increasing order. static constexpr std::array protocols{ @@ -2858,7 +2863,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) static_assert(std::is_sorted(std::begin(protocols), std::end(protocols))); { Json::Value ports{Json::arrayValue}; - for (auto const& port : registry_.getServerHandler().setup().ports) + for (auto const& port : registry_.get().getServerHandler().setup().ports) { // Don't publish admin ports for non-admin users if (!admin && @@ -2882,9 +2887,9 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) } } - if (registry_.getApp().config().exists(SECTION_PORT_GRPC)) + if (registry_.get().getApp().config().exists(SECTION_PORT_GRPC)) { - auto const& grpcSection = registry_.getApp().config().section(SECTION_PORT_GRPC); + auto const& grpcSection = registry_.get().getApp().config().section(SECTION_PORT_GRPC); auto const optPort = grpcSection.get("port"); if (optPort && grpcSection.get("ip")) { @@ -2903,13 +2908,13 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) void NetworkOPsImp::clearLedgerFetch() { - registry_.getInboundLedgers().clearFailures(); + registry_.get().getInboundLedgers().clearFailures(); } Json::Value NetworkOPsImp::getLedgerFetchInfo() { - return registry_.getInboundLedgers().getInfo(); + return registry_.get().getInboundLedgers().getInfo(); } void @@ -2959,11 +2964,11 @@ NetworkOPsImp::pubLedger(std::shared_ptr const& lpAccepted) // Holes are filled across connection loss or other catastrophe std::shared_ptr alpAccepted = - registry_.getAcceptedLedgerCache().fetch(lpAccepted->header().hash); + registry_.get().getAcceptedLedgerCache().fetch(lpAccepted->header().hash); if (!alpAccepted) { alpAccepted = std::make_shared(lpAccepted); - registry_.getAcceptedLedgerCache().canonicalize_replace_client( + registry_.get().getAcceptedLedgerCache().canonicalize_replace_client( lpAccepted->header().hash, alpAccepted); } @@ -2987,7 +2992,7 @@ NetworkOPsImp::pubLedger(std::shared_ptr const& lpAccepted) jvObj[jss::ledger_time] = Json::Value::UInt(lpAccepted->header().closeTime.time_since_epoch().count()); - jvObj[jss::network_id] = registry_.getNetworkIDService().getNetworkID(); + jvObj[jss::network_id] = registry_.get().getNetworkIDService().getNetworkID(); if (!lpAccepted->rules().enabled(featureXRPFees)) jvObj[jss::fee_ref] = FEE_UNITS_DEPRECATED; @@ -2999,7 +3004,8 @@ NetworkOPsImp::pubLedger(std::shared_ptr const& lpAccepted) if (mMode >= OperatingMode::SYNCING) { - jvObj[jss::validated_ledgers] = registry_.getLedgerMaster().getCompleteLedgers(); + jvObj[jss::validated_ledgers] = + registry_.get().getLedgerMaster().getCompleteLedgers(); } auto it = mStreamMaps[sLedger].begin(); @@ -3071,9 +3077,9 @@ void NetworkOPsImp::reportFeeChange() { ServerFeeSummary f{ - registry_.getOpenLedger().current()->fees().base, - registry_.getTxQ().getMetrics(*registry_.getOpenLedger().current()), - registry_.getFeeTrack()}; + registry_.get().getOpenLedger().current()->fees().base, + registry_.get().getTxQ().getMetrics(*registry_.get().getOpenLedger().current()), + registry_.get().getFeeTrack()}; // only schedule the job if something has changed if (f != mLastFeeSummary) @@ -3134,7 +3140,7 @@ NetworkOPsImp::transJson( lookup.second && lookup.second->isFieldPresent(sfTransactionIndex)) { uint32_t const txnSeq = lookup.second->getFieldU32(sfTransactionIndex); - uint32_t netID = registry_.getNetworkIDService().getNetworkID(); + uint32_t netID = registry_.get().getNetworkIDService().getNetworkID(); if (transaction->isFieldPresent(sfNetworkID)) netID = transaction->getFieldU32(sfNetworkID); @@ -3174,7 +3180,7 @@ NetworkOPsImp::transJson( if (account != amount.issue().account) { auto const ownerFunds = accountFunds( - *ledger, account, amount, fhIGNORE_FREEZE, registry_.getJournal("View")); + *ledger, account, amount, fhIGNORE_FREEZE, registry_.get().getJournal("View")); jvObj[jss::transaction][jss::owner_funds] = ownerFunds.getText(); } } @@ -3255,7 +3261,7 @@ NetworkOPsImp::pubValidatedTransaction( } if (transaction.getResult() == tesSUCCESS) - registry_.getOrderBookDB().processTxn(ledger, transaction, jvObj); + registry_.get().getOrderBookDB().processTxn(ledger, transaction, jvObj); pubAccountTransaction(ledger, transaction, last); } @@ -3562,7 +3568,7 @@ NetworkOPsImp::addAccountHistoryJob(SubAccountHistoryInfoWeak subInfo) static auto const databaseType = [&]() -> DatabaseType { // Use a dynamic_cast to return DatabaseType::None // on failure. - if (dynamic_cast(®istry_.getRelationalDatabase())) + if (dynamic_cast(®istry_.get().getRelationalDatabase())) { return DatabaseType::Sqlite; } @@ -3584,7 +3590,7 @@ NetworkOPsImp::addAccountHistoryJob(SubAccountHistoryInfoWeak subInfo) // LCOV_EXCL_STOP } - registry_.getJobQueue().addJob( + registry_.get().getJobQueue().addJob( jtCLIENT_ACCT_HIST, "HistTxStream", [this, dbType = databaseType, subInfo]() { auto const& accountId = subInfo.index_->accountId_; auto& lastLedgerSeq = subInfo.index_->historyLastLedgerSeq_; @@ -3665,11 +3671,10 @@ NetworkOPsImp::addAccountHistoryJob(SubAccountHistoryInfoWeak subInfo) switch (dbType) { case Sqlite: { - auto db = - safe_downcast(®istry_.getRelationalDatabase()); + auto& db = registry_.get().getRelationalDatabase(); RelationalDatabase::AccountTxPageOptions options{ - accountId, minLedger, maxLedger, marker, 0, true}; - return db->newestAccountTxPage(options); + accountId, {minLedger, maxLedger}, marker, 0, true}; + return db.newestAccountTxPage(options); } // LCOV_EXCL_START default: { @@ -3711,7 +3716,8 @@ NetworkOPsImp::addAccountHistoryJob(SubAccountHistoryInfoWeak subInfo) std::uint32_t validatedMin = UINT_MAX; std::uint32_t validatedMax = 0; auto haveSomeValidatedLedgers = - registry_.getLedgerMaster().getValidatedRange(validatedMin, validatedMax); + registry_.get().getLedgerMaster().getValidatedRange( + validatedMin, validatedMax); return haveSomeValidatedLedgers && validatedMin <= startLedgerSeq && lastLedgerSeq <= validatedMax; @@ -3758,7 +3764,7 @@ NetworkOPsImp::addAccountHistoryJob(SubAccountHistoryInfoWeak subInfo) return; } auto curTxLedger = - registry_.getLedgerMaster().getLedgerBySeq(tx->getLedger()); + registry_.get().getLedgerMaster().getLedgerBySeq(tx->getLedger()); if (!curTxLedger) { // LCOV_EXCL_START @@ -3904,7 +3910,7 @@ NetworkOPsImp::subAccountHistory(InfoSub::ref isrListener, AccountID const& acco simIterator->second.emplace(isrListener->getSeq(), ahi); } - auto const ledger = registry_.getLedgerMaster().getValidatedLedger(); + auto const ledger = registry_.get().getLedgerMaster().getValidatedLedger(); if (ledger) { subAccountHistoryStart(ledger, ahi); @@ -3964,7 +3970,7 @@ NetworkOPsImp::unsubAccountHistoryInternal( bool NetworkOPsImp::subBook(InfoSub::ref isrListener, Book const& book) { - if (auto listeners = registry_.getOrderBookDB().makeBookListeners(book)) + if (auto listeners = registry_.get().getOrderBookDB().makeBookListeners(book)) { listeners->addSubscriber(isrListener); } @@ -3980,7 +3986,7 @@ NetworkOPsImp::subBook(InfoSub::ref isrListener, Book const& book) bool NetworkOPsImp::unsubBook(std::uint64_t uSeq, Book const& book) { - if (auto listeners = registry_.getOrderBookDB().getBookListeners(book)) + if (auto listeners = registry_.get().getOrderBookDB().getBookListeners(book)) listeners->removeSubscriber(uSeq); return true; @@ -3999,7 +4005,7 @@ NetworkOPsImp::acceptLedger(std::optional consensusDe // FIXME Could we improve on this and remove the need for a specialized // API in Consensus? beginConsensus(m_ledgerMaster.getClosedLedger()->header().hash, {}); - mConsensus.simulate(registry_.getTimeKeeper().closeTime(), consensusDelay); + mConsensus.simulate(registry_.get().getTimeKeeper().closeTime(), consensusDelay); return m_ledgerMaster.getCurrentLedger()->header().seq; } @@ -4018,12 +4024,12 @@ NetworkOPsImp::subLedger(InfoSub::ref isrListener, Json::Value& jvResult) jvResult[jss::fee_base] = lpClosed->fees().base.jsonClipped(); jvResult[jss::reserve_base] = lpClosed->fees().reserve.jsonClipped(); jvResult[jss::reserve_inc] = lpClosed->fees().increment.jsonClipped(); - jvResult[jss::network_id] = registry_.getNetworkIDService().getNetworkID(); + jvResult[jss::network_id] = registry_.get().getNetworkIDService().getNetworkID(); } if ((mMode >= OperatingMode::SYNCING) && !isNeedNetworkLedger()) { - jvResult[jss::validated_ledgers] = registry_.getLedgerMaster().getCompleteLedgers(); + jvResult[jss::validated_ledgers] = registry_.get().getLedgerMaster().getCompleteLedgers(); } std::lock_guard sl(mSubLock); @@ -4082,14 +4088,14 @@ NetworkOPsImp::subServer(InfoSub::ref isrListener, Json::Value& jvResult, bool a // CHECKME: is it necessary to provide a random number here? beast::rngfill(uRandom.begin(), uRandom.size(), crypto_prng()); - auto const& feeTrack = registry_.getFeeTrack(); + auto const& feeTrack = registry_.get().getFeeTrack(); jvResult[jss::random] = to_string(uRandom); jvResult[jss::server_status] = strOperatingMode(admin); jvResult[jss::load_base] = feeTrack.getLoadBase(); jvResult[jss::load_factor] = feeTrack.getLoadFactor(); jvResult[jss::hostid] = getHostId(admin); jvResult[jss::pubkey_node] = - toBase58(TokenType::NodePublic, registry_.getApp().nodeIdentity().first); + toBase58(TokenType::NodePublic, registry_.get().getApp().nodeIdentity().first); std::lock_guard sl(mSubLock); return mStreamMaps[sServer].emplace(isrListener->getSeq(), isrListener).second; @@ -4276,7 +4282,7 @@ NetworkOPsImp::getBookPage( STAmount saDirRate; auto const rate = transferRate(view, book.out.account); - auto viewJ = registry_.getJournal("View"); + auto viewJ = registry_.get().getJournal("View"); while (!bDone && iLimit-- > 0) { @@ -4649,11 +4655,11 @@ make_NetworkOPs( NetworkOPs::clock_type& clock, bool standalone, std::size_t minPeerCount, - bool startvalid, - JobQueue& job_queue, + bool startValid, + JobQueue& jobQueue, LedgerMaster& ledgerMaster, ValidatorKeys const& validatorKeys, - boost::asio::io_context& io_svc, + boost::asio::io_context& ioCtx, beast::Journal journal, beast::insight::Collector::ptr const& collector) { @@ -4662,11 +4668,11 @@ make_NetworkOPs( clock, standalone, minPeerCount, - startvalid, - job_queue, + startValid, + jobQueue, ledgerMaster, validatorKeys, - io_svc, + ioCtx, journal, collector); } diff --git a/src/xrpld/app/misc/make_NetworkOPs.h b/src/xrpld/app/misc/make_NetworkOPs.h index 7dce966f04..e250a147b7 100644 --- a/src/xrpld/app/misc/make_NetworkOPs.h +++ b/src/xrpld/app/misc/make_NetworkOPs.h @@ -21,11 +21,11 @@ make_NetworkOPs( NetworkOPs::clock_type& clock, bool standalone, std::size_t minPeerCount, - bool start_valid, - JobQueue& job_queue, + bool startValid, + JobQueue& jobQueue, LedgerMaster& ledgerMaster, ValidatorKeys const& validatorKeys, - boost::asio::io_context& io_svc, + boost::asio::io_context& ioCtx, beast::Journal journal, beast::insight::Collector::ptr const& collector); diff --git a/src/xrpld/app/rdb/backend/SQLiteDatabase.h b/src/xrpld/app/rdb/backend/SQLiteDatabase.h index 462b62de6e..05e0175732 100644 --- a/src/xrpld/app/rdb/backend/SQLiteDatabase.h +++ b/src/xrpld/app/rdb/backend/SQLiteDatabase.h @@ -327,10 +327,10 @@ public: * @param id Hash of the transaction. * @param range Range of ledgers to check, if present. * @param ec Default error code value. - * @return Transaction and its metadata if found, otherwise TxSearched::all + * @return Transaction and its metadata if found, otherwise TxSearched::All * if a range is provided and all ledgers from the range are present - * in the database, TxSearched::some if a range is provided and not - * all ledgers are present, TxSearched::unknown if the range is not + * in the database, TxSearched::Some if a range is provided and not + * all ledgers are present, TxSearched::Unknown if the range is not * provided or a deserializing error occurred. In the last case the * error code is returned via the ec parameter, in other cases the * default error code is not changed. @@ -405,7 +405,7 @@ public: transactionDbHasSpace(Config const& config); private: - ServiceRegistry& registry_; + std::reference_wrapper registry_; bool useTxTables_; beast::Journal j_; std::unique_ptr ledgerDb_, txdb_; diff --git a/src/xrpld/app/rdb/backend/detail/Node.cpp b/src/xrpld/app/rdb/backend/detail/Node.cpp index 66b75e72de..926c01b8b3 100644 --- a/src/xrpld/app/rdb/backend/detail/Node.cpp +++ b/src/xrpld/app/rdb/backend/detail/Node.cpp @@ -70,8 +70,8 @@ makeLedgerDBs( boost::format("PRAGMA cache_size=-%d;") % kilobytes(config.getValueFor(SizedItem::txnDBCache))); - if (!setup.standAlone || setup.startUp == StartUpType::LOAD || - setup.startUp == StartUpType::LOAD_FILE || setup.startUp == StartUpType::REPLAY) + if (!setup.standAlone || setup.startUp == StartUpType::Load || + setup.startUp == StartUpType::LoadFile || setup.startUp == StartUpType::Replay) { // Check if AccountTransactions has primary key std::string cid, name, type; @@ -675,16 +675,16 @@ transactionsSQL( std::string maxClause; std::string minClause; - if (options.maxLedger != 0u) + if (options.ledgerRange.max != 0u) { maxClause = boost::str( - boost::format("AND AccountTransactions.LedgerSeq <= '%u'") % options.maxLedger); + boost::format("AND AccountTransactions.LedgerSeq <= '%u'") % options.ledgerRange.max); } - if (options.minLedger != 0u) + if (options.ledgerRange.min != 0u) { minClause = boost::str( - boost::format("AND AccountTransactions.LedgerSeq >= '%u'") % options.minLedger); + boost::format("AND AccountTransactions.LedgerSeq >= '%u'") % options.ledgerRange.min); } std::string sql; @@ -1021,14 +1021,14 @@ accountTxPage( ORDER BY AccountTransactions.LedgerSeq %s, AccountTransactions.TxnSeq %s LIMIT %u;)")) % - toBase58(options.account) % options.minLedger % options.maxLedger % order % order % - queryLimit); + toBase58(options.account) % options.ledgerRange.min % options.ledgerRange.max % order % + order % queryLimit); } else { char const* const compare = forward ? ">=" : "<="; - std::uint32_t const minLedger = forward ? findLedger + 1 : options.minLedger; - std::uint32_t const maxLedger = forward ? options.maxLedger : findLedger - 1; + std::uint32_t const minLedger = forward ? findLedger + 1 : options.ledgerRange.min; + std::uint32_t const maxLedger = forward ? options.ledgerRange.max : findLedger - 1; auto b58acct = toBase58(options.account); sql = boost::str( @@ -1192,7 +1192,7 @@ getTransaction( auto const got_data = session.got_data(); if ((!got_data || txn != soci::i_ok || meta != soci::i_ok) && !range) - return TxSearched::unknown; + return TxSearched::Unknown; if (!got_data) { @@ -1205,10 +1205,10 @@ getTransaction( soci::into(count, rti); if (!session.got_data() || rti != soci::i_ok) - return TxSearched::some; + return TxSearched::Some; - return count == (range->last() - range->first() + 1) ? TxSearched::all - : TxSearched::some; + return count == (range->last() - range->first() + 1) ? TxSearched::All + : TxSearched::Some; } convert(sociRawTxnBlob, rawTxn); @@ -1236,7 +1236,7 @@ getTransaction( ec = rpcDB_DESERIALIZATION; } - return TxSearched::unknown; + return TxSearched::Unknown; } bool diff --git a/src/xrpld/app/rdb/backend/detail/Node.h b/src/xrpld/app/rdb/backend/detail/Node.h index 14eff07b94..5fbabeca47 100644 --- a/src/xrpld/app/rdb/backend/detail/Node.h +++ b/src/xrpld/app/rdb/backend/detail/Node.h @@ -377,10 +377,10 @@ newestAccountTxPage( * @param id Hash of the transaction. * @param range Range of ledgers to check, if present. * @param ec Default value of error code. - * @return Transaction and its metadata if found, TxSearched::all if range + * @return Transaction and its metadata if found, TxSearched::All if range * given and all ledgers from range are present in the database, - * TxSearched::some if range given and not all ledgers are present, - * TxSearched::unknown if range not given or deserializing error + * TxSearched::Some if range given and not all ledgers are present, + * TxSearched::Unknown if range not given or deserializing error * occurred. In the last case error code modified in ec link * parameter, in other cases default error code remained. */ diff --git a/src/xrpld/app/rdb/backend/detail/SQLiteDatabase.cpp b/src/xrpld/app/rdb/backend/detail/SQLiteDatabase.cpp index e271619b8e..ee3f9799ad 100644 --- a/src/xrpld/app/rdb/backend/detail/SQLiteDatabase.cpp +++ b/src/xrpld/app/rdb/backend/detail/SQLiteDatabase.cpp @@ -178,7 +178,8 @@ SQLiteDatabase::saveValidatedLedger(std::shared_ptr const& ledger, { if (existsLedger()) { - if (!detail::saveValidatedLedger(*ledgerDb_, txdb_, registry_.getApp(), ledger, current)) + if (!detail::saveValidatedLedger( + *ledgerDb_, txdb_, registry_.get().getApp(), ledger, current)) return false; } @@ -314,7 +315,7 @@ SQLiteDatabase::getTxHistory(LedgerIndex startIndex) if (existsTransaction()) { auto db = checkoutTransaction(); - auto const res = detail::getTxHistory(*db, registry_.getApp(), startIndex, 20).first; + auto const res = detail::getTxHistory(*db, registry_.get().getApp(), startIndex, 20).first; if (!res.empty()) return res; @@ -329,12 +330,12 @@ SQLiteDatabase::getOldestAccountTxs(AccountTxOptions const& options) if (!useTxTables_) return {}; - LedgerMaster& ledgerMaster = registry_.getLedgerMaster(); + LedgerMaster& ledgerMaster = registry_.get().getLedgerMaster(); if (existsTransaction()) { auto db = checkoutTransaction(); - return detail::getOldestAccountTxs(*db, registry_.getApp(), ledgerMaster, options, j_) + return detail::getOldestAccountTxs(*db, registry_.get().getApp(), ledgerMaster, options, j_) .first; } @@ -347,12 +348,12 @@ SQLiteDatabase::getNewestAccountTxs(AccountTxOptions const& options) if (!useTxTables_) return {}; - LedgerMaster& ledgerMaster = registry_.getLedgerMaster(); + LedgerMaster& ledgerMaster = registry_.get().getLedgerMaster(); if (existsTransaction()) { auto db = checkoutTransaction(); - return detail::getNewestAccountTxs(*db, registry_.getApp(), ledgerMaster, options, j_) + return detail::getNewestAccountTxs(*db, registry_.get().getApp(), ledgerMaster, options, j_) .first; } @@ -368,7 +369,7 @@ SQLiteDatabase::getOldestAccountTxsB(AccountTxOptions const& options) if (existsTransaction()) { auto db = checkoutTransaction(); - return detail::getOldestAccountTxsB(*db, registry_.getApp(), options, j_).first; + return detail::getOldestAccountTxsB(*db, registry_.get().getApp(), options, j_).first; } return {}; @@ -383,7 +384,7 @@ SQLiteDatabase::getNewestAccountTxsB(AccountTxOptions const& options) if (existsTransaction()) { auto db = checkoutTransaction(); - return detail::getNewestAccountTxsB(*db, registry_.getApp(), options, j_).first; + return detail::getNewestAccountTxsB(*db, registry_.get().getApp(), options, j_).first; } return {}; @@ -397,10 +398,10 @@ SQLiteDatabase::oldestAccountTxPage(AccountTxPageOptions const& options) static std::uint32_t const page_length(200); auto onUnsavedLedger = - std::bind(saveLedgerAsync, std::ref(registry_.getApp()), std::placeholders::_1); + std::bind(saveLedgerAsync, std::ref(registry_.get().getApp()), std::placeholders::_1); AccountTxs ret; auto onTransaction = - [&ret, &app = registry_.getApp()]( + [&ret, &app = registry_.get().getApp()]( std::uint32_t ledger_index, std::string const& status, Blob&& rawTxn, Blob&& rawMeta) { convertBlobsToTxResult( ret, ledger_index, status, std::move(rawTxn), std::move(rawMeta), app); @@ -426,10 +427,10 @@ SQLiteDatabase::newestAccountTxPage(AccountTxPageOptions const& options) static std::uint32_t const page_length(200); auto onUnsavedLedger = - std::bind(saveLedgerAsync, std::ref(registry_.getApp()), std::placeholders::_1); + std::bind(saveLedgerAsync, std::ref(registry_.get().getApp()), std::placeholders::_1); AccountTxs ret; auto onTransaction = - [&ret, &app = registry_.getApp()]( + [&ret, &app = registry_.get().getApp()]( std::uint32_t ledger_index, std::string const& status, Blob&& rawTxn, Blob&& rawMeta) { convertBlobsToTxResult( ret, ledger_index, status, std::move(rawTxn), std::move(rawMeta), app); @@ -455,7 +456,7 @@ SQLiteDatabase::oldestAccountTxPageB(AccountTxPageOptions const& options) static std::uint32_t const page_length(500); auto onUnsavedLedger = - std::bind(saveLedgerAsync, std::ref(registry_.getApp()), std::placeholders::_1); + std::bind(saveLedgerAsync, std::ref(registry_.get().getApp()), std::placeholders::_1); MetaTxsList ret; auto onTransaction = [&ret]( @@ -483,7 +484,7 @@ SQLiteDatabase::newestAccountTxPageB(AccountTxPageOptions const& options) static std::uint32_t const page_length(500); auto onUnsavedLedger = - std::bind(saveLedgerAsync, std::ref(registry_.getApp()), std::placeholders::_1); + std::bind(saveLedgerAsync, std::ref(registry_.get().getApp()), std::placeholders::_1); MetaTxsList ret; auto onTransaction = [&ret]( @@ -510,15 +511,15 @@ SQLiteDatabase::getTransaction( error_code_i& ec) { if (!useTxTables_) - return TxSearched::unknown; + return TxSearched::Unknown; if (existsTransaction()) { auto db = checkoutTransaction(); - return detail::getTransaction(*db, registry_.getApp(), id, range, ec); + return detail::getTransaction(*db, registry_.get().getApp(), id, range, ec); } - return TxSearched::unknown; + return TxSearched::Unknown; } SQLiteDatabase::SQLiteDatabase(SQLiteDatabase&& rhs) noexcept diff --git a/src/xrpld/core/Config.h b/src/xrpld/core/Config.h index 44509d2145..78a35c6bc1 100644 --- a/src/xrpld/core/Config.h +++ b/src/xrpld/core/Config.h @@ -134,7 +134,7 @@ public: // Entries from [ips_fixed] config stanza std::vector IPS_FIXED; - StartUpType START_UP = StartUpType::NORMAL; + StartUpType START_UP = StartUpType::Normal; bool START_VALID = false; diff --git a/src/xrpld/rpc/handlers/AccountTx.cpp b/src/xrpld/rpc/handlers/AccountTx.cpp index d7bffe5d95..9a10e49e5d 100644 --- a/src/xrpld/rpc/handlers/AccountTx.cpp +++ b/src/xrpld/rpc/handlers/AccountTx.cpp @@ -211,12 +211,7 @@ doAccountTxHelp(RPC::Context& context, AccountTxArgs const& args) result.marker = args.marker; RelationalDatabase::AccountTxPageOptions options = { - args.account, - result.ledgerRange.min, - result.ledgerRange.max, - result.marker, - args.limit, - isUnlimited(context.role)}; + args.account, result.ledgerRange, result.marker, args.limit, isUnlimited(context.role)}; auto& db = context.app.getRelationalDatabase(); diff --git a/src/xrpld/rpc/handlers/Tx.cpp b/src/xrpld/rpc/handlers/Tx.cpp index 482b7e3bf1..211372db45 100644 --- a/src/xrpld/rpc/handlers/Tx.cpp +++ b/src/xrpld/rpc/handlers/Tx.cpp @@ -42,7 +42,7 @@ struct TxResult std::optional ctid; std::optional closeTime; std::optional ledgerHash; - TxSearched searchedAll = TxSearched::unknown; + TxSearched searchedAll = TxSearched::Unknown; }; struct TxArgs @@ -77,7 +77,7 @@ doTxHelp(RPC::Context& context, TxArgs args) using TxPair = std::pair, std::shared_ptr>; - result.searchedAll = TxSearched::unknown; + result.searchedAll = TxSearched::Unknown; std::variant v; if (args.ctid) @@ -172,10 +172,10 @@ populateJsonResponse( // handle errors if (error.toErrorCode() != rpcSUCCESS) { - if (error.toErrorCode() == rpcTXN_NOT_FOUND && result.searchedAll != TxSearched::unknown) + if (error.toErrorCode() == rpcTXN_NOT_FOUND && result.searchedAll != TxSearched::Unknown) { response = Json::Value(Json::objectValue); - response[jss::searched_all] = (result.searchedAll == TxSearched::all); + response[jss::searched_all] = (result.searchedAll == TxSearched::All); error.inject(response); } else From ab8c168e3b1e45254f7a77a3d5b0ccc12a7416e1 Mon Sep 17 00:00:00 2001 From: Alex Kremer Date: Mon, 30 Mar 2026 18:08:47 +0100 Subject: [PATCH 35/53] chore: Enable remaining clang-tidy `performance` checks (#6648) Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .clang-tidy | 12 ++++----- include/xrpl/protocol/STVector256.h | 9 ------- include/xrpl/tx/transactors/dex/AMMHelpers.h | 9 +++---- src/libxrpl/basics/FileUtilities.cpp | 2 +- src/libxrpl/ledger/Ledger.cpp | 5 ++-- src/libxrpl/ledger/helpers/TokenHelpers.cpp | 2 +- src/libxrpl/protocol/BuildInfo.cpp | 2 +- src/libxrpl/protocol/STPathSet.cpp | 4 +-- src/libxrpl/shamap/SHAMap.cpp | 5 +--- .../PermissionedDomainInvariant.cpp | 2 +- src/libxrpl/tx/invariants/VaultInvariant.cpp | 4 +-- .../tx/transactors/bridge/XChainBridge.cpp | 2 +- .../tx/transactors/nft/NFTokenAcceptOffer.cpp | 2 +- .../tx/transactors/nft/NFTokenUtils.cpp | 2 +- .../tx/transactors/oracle/OracleSet.cpp | 4 +-- src/test/app/Batch_test.cpp | 1 + src/test/app/Invariants_test.cpp | 4 +-- src/test/app/LedgerReplay_test.cpp | 1 + src/test/app/Loan_test.cpp | 10 ++++--- src/test/app/Manifest_test.cpp | 11 ++++---- src/test/app/Offer_test.cpp | 6 ++--- src/test/app/RCLValidations_test.cpp | 2 +- src/test/app/Transaction_ordering_test.cpp | 10 ++++--- src/test/app/ValidatorList_test.cpp | 2 ++ src/test/app/ValidatorSite_test.cpp | 1 + src/test/app/Vault_test.cpp | 2 +- src/test/basics/IntrusiveShared_test.cpp | 3 +++ .../beast/aged_associative_container_test.cpp | 2 +- src/test/conditions/PreimageSha256_test.cpp | 2 +- src/test/consensus/Validations_test.cpp | 3 ++- src/test/jtx/TestHelpers.h | 2 +- src/test/jtx/impl/AMMTest.cpp | 2 +- src/test/jtx/impl/mpt.cpp | 4 +-- src/test/jtx/mpt.h | 2 +- src/test/jtx/multisign.h | 2 +- src/test/ledger/Directory_test.cpp | 2 +- src/test/protocol/MultiApiJson_test.cpp | 10 +++---- src/xrpld/app/consensus/RCLCxPeerPos.cpp | 4 +-- src/xrpld/app/consensus/RCLCxPeerPos.h | 2 +- src/xrpld/app/consensus/RCLValidations.cpp | 2 +- src/xrpld/app/ledger/detail/LedgerMaster.cpp | 2 +- src/xrpld/app/main/Application.cpp | 2 +- src/xrpld/app/main/GRPCServer.cpp | 6 ++--- src/xrpld/app/main/Main.cpp | 1 + src/xrpld/app/misc/NetworkOPs.cpp | 6 ++--- src/xrpld/app/misc/detail/ValidatorList.cpp | 6 ++--- src/xrpld/app/misc/detail/ValidatorSite.cpp | 13 +++++----- .../app/rdb/backend/detail/SQLiteDatabase.cpp | 26 ++++++++++--------- src/xrpld/overlay/detail/OverlayImpl.cpp | 4 +-- src/xrpld/overlay/detail/ProtocolMessage.h | 2 +- src/xrpld/peerfinder/detail/Logic.h | 4 +-- src/xrpld/rpc/detail/RPCCall.cpp | 10 ++++--- src/xrpld/rpc/detail/ServerHandler.cpp | 2 +- src/xrpld/rpc/handlers/AMMInfo.cpp | 2 +- src/xrpld/rpc/handlers/AccountChannels.cpp | 2 +- .../rpc/handlers/AccountCurrenciesHandler.cpp | 2 +- src/xrpld/rpc/handlers/AccountInfo.cpp | 2 +- src/xrpld/rpc/handlers/AccountLines.cpp | 2 +- src/xrpld/rpc/handlers/AccountOffers.cpp | 2 +- src/xrpld/rpc/handlers/AccountTx.cpp | 4 +-- src/xrpld/rpc/handlers/DepositAuthorized.cpp | 4 +-- src/xrpld/rpc/handlers/GatewayBalances.cpp | 4 +-- src/xrpld/rpc/handlers/LedgerEntry.cpp | 2 +- src/xrpld/rpc/handlers/LedgerEntryHelpers.h | 8 +++--- src/xrpld/rpc/handlers/NoRippleCheck.cpp | 2 +- src/xrpld/rpc/handlers/ServerDefinitions.cpp | 2 +- 66 files changed, 141 insertions(+), 139 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index 449198eef8..36b59f43e3 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -97,8 +97,13 @@ Checks: "-*, modernize-deprecated-headers, modernize-make-shared, modernize-make-unique, + performance-faster-string-find, + performance-for-range-copy, performance-implicit-conversion-in-loop, + performance-inefficient-vector-operation, + performance-move-const-arg, performance-move-constructor-init, + performance-no-automatic-move, performance-trivially-destructible, # readability-avoid-nested-conditional-operator, # has issues # readability-avoid-return-with-void-value, # has issues @@ -150,13 +155,6 @@ Checks: "-*, # modernize-use-starts-ends-with, # modernize-use-std-numbers, # modernize-use-using, -# -# the following are in https://github.com/XRPLF/rippled/pull/6648 : -# performance-faster-string-find, -# performance-for-range-copy, -# performance-inefficient-vector-operation, -# performance-move-const-arg, -# performance-no-automatic-move, # --- # CheckOptions: diff --git a/include/xrpl/protocol/STVector256.h b/include/xrpl/protocol/STVector256.h index dd77067b7c..815224def2 100644 --- a/include/xrpl/protocol/STVector256.h +++ b/include/xrpl/protocol/STVector256.h @@ -69,9 +69,6 @@ public: std::vector::iterator insert(std::vector::const_iterator pos, uint256 const& value); - std::vector::iterator - insert(std::vector::const_iterator pos, uint256&& value); - void push_back(uint256 const& v); @@ -184,12 +181,6 @@ STVector256::insert(std::vector::const_iterator pos, uint256 const& val return mValue.insert(pos, value); } -inline std::vector::iterator -STVector256::insert(std::vector::const_iterator pos, uint256&& value) -{ - return mValue.insert(pos, std::move(value)); -} - inline void STVector256::push_back(uint256 const& v) { diff --git a/include/xrpl/tx/transactors/dex/AMMHelpers.h b/include/xrpl/tx/transactors/dex/AMMHelpers.h index e2735ea80f..6e3957769f 100644 --- a/include/xrpl/tx/transactors/dex/AMMHelpers.h +++ b/include/xrpl/tx/transactors/dex/AMMHelpers.h @@ -203,7 +203,7 @@ getAMMOfferStartWithTakerGets( // Try to reduce the offer size to improve the quality. // The quality might still not match the targetQuality for a tiny offer. - if (auto const amounts = getAmounts(*nTakerGets); Quality{amounts} < targetQuality) + if (auto amounts = getAmounts(*nTakerGets); Quality{amounts} < targetQuality) return getAmounts(detail::reduceOffer(amounts.out)); else return amounts; @@ -270,7 +270,7 @@ getAMMOfferStartWithTakerPays( // Try to reduce the offer size to improve the quality. // The quality might still not match the targetQuality for a tiny offer. - if (auto const amounts = getAmounts(*nTakerPays); Quality{amounts} < targetQuality) + if (auto amounts = getAmounts(*nTakerPays); Quality{amounts} < targetQuality) return getAmounts(detail::reduceOffer(amounts.in)); else return amounts; @@ -335,8 +335,7 @@ changeSpotPriceQuality( } auto const takerPays = toAmount(getIssue(pool.in), nTakerPays, Number::upward); // should not fail - if (auto const amounts = - TAmounts{takerPays, swapAssetIn(pool, takerPays, tfee)}; + if (auto amounts = TAmounts{takerPays, swapAssetIn(pool, takerPays, tfee)}; Quality{amounts} < quality && !withinRelativeDistance(Quality{amounts}, quality, Number(1, -7))) { @@ -362,7 +361,7 @@ changeSpotPriceQuality( // Generate the offer starting with XRP side. Return seated offer amounts // if the offer can be generated, otherwise nullopt. - auto const amounts = [&]() { + auto amounts = [&]() { if (isXRP(getIssue(pool.out))) return getAMMOfferStartWithTakerGets(pool, quality, tfee); return getAMMOfferStartWithTakerPays(pool, quality, tfee); diff --git a/src/libxrpl/basics/FileUtilities.cpp b/src/libxrpl/basics/FileUtilities.cpp index 0f636276da..73f2c2f10d 100644 --- a/src/libxrpl/basics/FileUtilities.cpp +++ b/src/libxrpl/basics/FileUtilities.cpp @@ -45,7 +45,7 @@ getFileContents( return {}; } - std::string const result{ + std::string result{ std::istreambuf_iterator{fileStream}, std::istreambuf_iterator{}}; if (fileStream.bad()) diff --git a/src/libxrpl/ledger/Ledger.cpp b/src/libxrpl/ledger/Ledger.cpp index 47009d198a..87f6350ce1 100644 --- a/src/libxrpl/ledger/Ledger.cpp +++ b/src/libxrpl/ledger/Ledger.cpp @@ -80,8 +80,7 @@ public: txs_iter_impl(txs_iter_impl const&) = default; - txs_iter_impl(bool metadata, SHAMap::const_iterator iter) - : metadata_(metadata), iter_(std::move(iter)) + txs_iter_impl(bool metadata, SHAMap::const_iterator iter) : metadata_(metadata), iter_(iter) { } @@ -694,7 +693,7 @@ Ledger::updateNegativeUNL() if (sle->isFieldPresent(sfDisabledValidators)) { auto const& oldNUnl = sle->getFieldArray(sfDisabledValidators); - for (auto v : oldNUnl) + for (auto const& v : oldNUnl) { if (hasToReEnable && v.isFieldPresent(sfPublicKey) && v.getFieldVL(sfPublicKey) == sle->getFieldVL(sfValidatorToReEnable)) diff --git a/src/libxrpl/ledger/helpers/TokenHelpers.cpp b/src/libxrpl/ledger/helpers/TokenHelpers.cpp index 9eb1b4bf11..27ee257e64 100644 --- a/src/libxrpl/ledger/helpers/TokenHelpers.cpp +++ b/src/libxrpl/ledger/helpers/TokenHelpers.cpp @@ -161,7 +161,7 @@ getLineIfUsable( FreezeHandling zeroIfFrozen, beast::Journal j) { - auto const sle = view.read(keylet::line(account, issuer, currency)); + auto sle = view.read(keylet::line(account, issuer, currency)); if (!sle) { diff --git a/src/libxrpl/protocol/BuildInfo.cpp b/src/libxrpl/protocol/BuildInfo.cpp index 6a30a02756..0fddb9ff19 100644 --- a/src/libxrpl/protocol/BuildInfo.cpp +++ b/src/libxrpl/protocol/BuildInfo.cpp @@ -113,7 +113,7 @@ encodeSoftwareVersion(std::string_view versionStr) { std::uint8_t x = 0; - for (auto id : v.preReleaseIdentifiers) + for (auto const& id : v.preReleaseIdentifiers) { auto parsePreRelease = [](std::string_view identifier, std::string_view prefix, diff --git a/src/libxrpl/protocol/STPathSet.cpp b/src/libxrpl/protocol/STPathSet.cpp index 86e61e91bf..fde33fb58e 100644 --- a/src/libxrpl/protocol/STPathSet.cpp +++ b/src/libxrpl/protocol/STPathSet.cpp @@ -153,7 +153,7 @@ STPath::getJson(JsonOptions) const { Json::Value ret(Json::arrayValue); - for (auto it : mPath) + for (auto const& it : mPath) { Json::Value elem(Json::objectValue); auto const iType = it.getNodeType(); @@ -179,7 +179,7 @@ Json::Value STPathSet::getJson(JsonOptions options) const { Json::Value ret(Json::arrayValue); - for (auto it : value) + for (auto const& it : value) ret.append(it.getJson(options)); return ret; diff --git a/src/libxrpl/shamap/SHAMap.cpp b/src/libxrpl/shamap/SHAMap.cpp index a9182a59cf..8a853e4d1b 100644 --- a/src/libxrpl/shamap/SHAMap.cpp +++ b/src/libxrpl/shamap/SHAMap.cpp @@ -1021,10 +1021,7 @@ SHAMap::walkSubTree(bool doWrite, NodeObjectType t) // save our place and work on this node stack.emplace(std::move(node), branch); - // The semantics of this changes when we move to c++-20 - // Right now no move will occur; With c++-20 child will - // be moved from. - node = intr_ptr::static_pointer_cast(std::move(child)); + node = intr_ptr::static_pointer_cast(child); pos = 0; } else diff --git a/src/libxrpl/tx/invariants/PermissionedDomainInvariant.cpp b/src/libxrpl/tx/invariants/PermissionedDomainInvariant.cpp index 02eaee0552..7365fc7b1a 100644 --- a/src/libxrpl/tx/invariants/PermissionedDomainInvariant.cpp +++ b/src/libxrpl/tx/invariants/PermissionedDomainInvariant.cpp @@ -38,7 +38,7 @@ ValidPermissionedDomain::visitEntry( break; } } - sleStatus.emplace_back(std::move(ss)); + sleStatus.emplace_back(ss); }; if (after) diff --git a/src/libxrpl/tx/invariants/VaultInvariant.cpp b/src/libxrpl/tx/invariants/VaultInvariant.cpp index f0dd82c2f8..c6b3295569 100644 --- a/src/libxrpl/tx/invariants/VaultInvariant.cpp +++ b/src/libxrpl/tx/invariants/VaultInvariant.cpp @@ -205,7 +205,7 @@ ValidVault::finalize( for (auto const& e : beforeMPTs_) { if (e.share.getMptID() == beforeVault.shareMPTID) - return std::move(e); + return e; } return std::nullopt; }(); @@ -374,7 +374,7 @@ ValidVault::finalize( for (auto const& e : beforeMPTs_) { if (e.share.getMptID() == beforeVault.shareMPTID) - return std::move(e); + return e; } return std::nullopt; }(); diff --git a/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp b/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp index 8c09fefe5a..f0e57919d9 100644 --- a/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp +++ b/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp @@ -418,7 +418,7 @@ transferHelper( auto const reserve = psb.fees().accountReserve(ownerCount); auto const availableBalance = [&]() -> STAmount { - STAmount const curBal = (*sleSrc)[sfBalance]; + STAmount curBal = (*sleSrc)[sfBalance]; // Checking that account == src and postFeeBalance == curBal is // not strictly necessary, but helps protect against future // changes diff --git a/src/libxrpl/tx/transactors/nft/NFTokenAcceptOffer.cpp b/src/libxrpl/tx/transactors/nft/NFTokenAcceptOffer.cpp index 15a745b8dd..e061dbe7ec 100644 --- a/src/libxrpl/tx/transactors/nft/NFTokenAcceptOffer.cpp +++ b/src/libxrpl/tx/transactors/nft/NFTokenAcceptOffer.cpp @@ -344,7 +344,7 @@ NFTokenAcceptOffer::transferNFToken( if (!tokenAndPage) return tecINTERNAL; // LCOV_EXCL_LINE - if (auto const ret = nft::removeToken(view(), seller, nftokenID, std::move(tokenAndPage->page)); + if (auto const ret = nft::removeToken(view(), seller, nftokenID, tokenAndPage->page); !isTesSuccess(ret)) return ret; diff --git a/src/libxrpl/tx/transactors/nft/NFTokenUtils.cpp b/src/libxrpl/tx/transactors/nft/NFTokenUtils.cpp index 84826314e7..6a8b830bf0 100644 --- a/src/libxrpl/tx/transactors/nft/NFTokenUtils.cpp +++ b/src/libxrpl/tx/transactors/nft/NFTokenUtils.cpp @@ -344,7 +344,7 @@ removeToken(ApplyView& view, AccountID const& owner, uint256 const& nftokenID) if (!page) return tecNO_ENTRY; - return removeToken(view, owner, nftokenID, std::move(page)); + return removeToken(view, owner, nftokenID, page); } /** Remove the token from the owner's token directory. */ diff --git a/src/libxrpl/tx/transactors/oracle/OracleSet.cpp b/src/libxrpl/tx/transactors/oracle/OracleSet.cpp index 061dd16b0c..772756ad6d 100644 --- a/src/libxrpl/tx/transactors/oracle/OracleSet.cpp +++ b/src/libxrpl/tx/transactors/oracle/OracleSet.cpp @@ -236,7 +236,7 @@ OracleSet::doApply() } STArray updatedSeries; for (auto const& iter : pairs) - updatedSeries.push_back(std::move(iter.second)); + updatedSeries.push_back(iter.second); sle->setFieldArray(sfPriceDataSeries, updatedSeries); if (ctx_.tx.isFieldPresent(sfURI)) sle->setFieldVL(sfURI, ctx_.tx[sfURI]); @@ -284,7 +284,7 @@ OracleSet::doApply() pairs.emplace(key, std::move(priceData)); } for (auto const& iter : pairs) - series.push_back(std::move(iter.second)); + series.push_back(iter.second); } sle->setFieldArray(sfPriceDataSeries, series); diff --git a/src/test/app/Batch_test.cpp b/src/test/app/Batch_test.cpp index adc36e4340..a548eb6b49 100644 --- a/src/test/app/Batch_test.cpp +++ b/src/test/app/Batch_test.cpp @@ -93,6 +93,7 @@ class Batch_test : public beast::unit_test::suite auto const ids = batchTxn.stx->getBatchTransactionIDs(); std::vector txIDs; + txIDs.reserve(ids.size()); for (auto const& id : ids) txIDs.push_back(strHex(id)); TxID const batchID = batchTxn.stx->getTransactionID(); diff --git a/src/test/app/Invariants_test.cpp b/src/test/app/Invariants_test.cpp index 9653a36edf..ca63a69bc4 100644 --- a/src/test/app/Invariants_test.cpp +++ b/src/test/app/Invariants_test.cpp @@ -1193,7 +1193,7 @@ class Invariants_test : public beast::unit_test::suite STArray nfTokens = makeNFTokenIDs(1); auto nftPage = std::make_shared(keylet::nftpage( keylet::nftpage_max(A1), ++(nfTokens[0].getFieldH256(sfNFTokenID)))); - nftPage->setFieldArray(sfNFTokens, std::move(nfTokens)); + nftPage->setFieldArray(sfNFTokens, nfTokens); nftPage->setFieldH256(sfNextPageMin, keylet::nftpage_max(A2).key); ac.view().insert(nftPage); @@ -1206,7 +1206,7 @@ class Invariants_test : public beast::unit_test::suite STArray nfTokens = makeNFTokenIDs(2); auto nftPage = std::make_shared(keylet::nftpage( keylet::nftpage_max(A1), (nfTokens[1].getFieldH256(sfNFTokenID)))); - nftPage->setFieldArray(sfNFTokens, std::move(nfTokens)); + nftPage->setFieldArray(sfNFTokens, nfTokens); ac.view().insert(nftPage); return true; diff --git a/src/test/app/LedgerReplay_test.cpp b/src/test/app/LedgerReplay_test.cpp index cc7cfa413c..93811d33b0 100644 --- a/src/test/app/LedgerReplay_test.cpp +++ b/src/test/app/LedgerReplay_test.cpp @@ -968,6 +968,7 @@ struct LedgerReplayer_test : public beast::unit_test::suite auto makeSkipList = [](int count) -> std::vector { std::vector sList; + sList.reserve(count); for (int i = 0; i < count; ++i) sList.emplace_back(i); return sList; diff --git a/src/test/app/Loan_test.cpp b/src/test/app/Loan_test.cpp index fa7befd39e..4cdc62853c 100644 --- a/src/test/app/Loan_test.cpp +++ b/src/test/app/Loan_test.cpp @@ -1539,7 +1539,7 @@ protected: auto const pseudoAcct = [&]() { auto const brokerSle = env.le(keylet::loanbroker(broker.brokerID)); if (!BEAST_EXPECT(brokerSle)) - return lender; + return Account{lender}; auto const brokerPseudo = brokerSle->at(sfAccount); return Account("Broker pseudo-account", brokerPseudo); }(); @@ -1809,9 +1809,9 @@ protected: if (!BEAST_EXPECT(vaultSle)) { // This will be wrong, but the test has failed anyway. - return lender; + return Account{lender}; } - auto const vaultPseudo = Account("Vault pseudo-account", vaultSle->at(sfAccount)); + auto vaultPseudo = Account("Vault pseudo-account", vaultSle->at(sfAccount)); return vaultPseudo; }(); @@ -2875,6 +2875,7 @@ protected: // Create vaults and loan brokers std::array const assets{mptAsset, iouAsset}; std::vector brokers; + brokers.reserve(assets.size()); for (auto const& asset : assets) { brokers.emplace_back(createVaultAndBroker(env, asset, lender)); @@ -3408,6 +3409,7 @@ protected: // Create vaults and loan brokers std::vector brokers; + brokers.reserve(assets.size()); for (auto const& asset : assets) { brokers.emplace_back(createVaultAndBroker( @@ -4566,7 +4568,7 @@ protected: auto const pseudoAcct = [&]() { auto const brokerSle = env.le(keylet::loanbroker(broker.brokerID)); if (!BEAST_EXPECT(brokerSle)) - return lender; + return Account{lender}; auto const brokerPseudo = brokerSle->at(sfAccount); return Account("Broker pseudo-account", brokerPseudo); }(); diff --git a/src/test/app/Manifest_test.cpp b/src/test/app/Manifest_test.cpp index 7039f8df4f..92a10ef7fa 100644 --- a/src/test/app/Manifest_test.cpp +++ b/src/test/app/Manifest_test.cpp @@ -147,9 +147,8 @@ public: Serializer s; st.add(s); - // m is non-const so it can be moved from - std::string m(static_cast(s.data()), s.size()); - if (auto r = deserializeManifest(std::move(m))) + std::string const m(static_cast(s.data()), s.size()); + if (auto r = deserializeManifest(m)) return std::move(*r); Throw("Could not create a revocation manifest"); return *deserializeManifest(std::string{}); // Silence compiler warning. @@ -182,9 +181,8 @@ public: Serializer s; st.add(s); - std::string m(static_cast(s.data()), - s.size()); // non-const so can be moved - if (auto r = deserializeManifest(std::move(m))) + std::string const m(static_cast(s.data()), s.size()); + if (auto r = deserializeManifest(m)) return std::move(*r); Throw("Could not create a manifest"); return *deserializeManifest(std::string{}); // Silence compiler warning. @@ -252,6 +250,7 @@ public: // save should store all trusted master keys to db std::vector s1; std::vector keys; + s1.reserve(inManifests.size()); for (auto const& man : inManifests) s1.push_back(toBase58(TokenType::NodePublic, man->masterKey)); unl->load({}, s1, keys); diff --git a/src/test/app/Offer_test.cpp b/src/test/app/Offer_test.cpp index 35146f5234..57f938e399 100644 --- a/src/test/app/Offer_test.cpp +++ b/src/test/app/Offer_test.cpp @@ -863,7 +863,7 @@ public: auto const aliceOffers = offersOnAccount(env, alice); BEAST_EXPECT(aliceOffers.size() == 1); - for (auto offerPtr : aliceOffers) + for (auto const& offerPtr : aliceOffers) { auto const& offer = *offerPtr; BEAST_EXPECT(offer[sfTakerGets] == XRP(2000)); @@ -878,7 +878,7 @@ public: auto const bobOffers = offersOnAccount(env, bob); BEAST_EXPECT(bobOffers.size() == 1); - for (auto offerPtr : bobOffers) + for (auto const& offerPtr : bobOffers) { auto const& offer = *offerPtr; BEAST_EXPECT(offer[sfTakerGets] == USD(1000)); @@ -927,7 +927,7 @@ public: auto const bobOffers = offersOnAccount(env, "bob"); BEAST_EXPECT(bobOffers.size() == 1); - for (auto offerPtr : bobOffers) + for (auto const& offerPtr : bobOffers) { auto const& offer = *offerPtr; BEAST_EXPECT(offer[sfTakerGets] == USD(499.5)); diff --git a/src/test/app/RCLValidations_test.cpp b/src/test/app/RCLValidations_test.cpp index e15569102a..537563ecc4 100644 --- a/src/test/app/RCLValidations_test.cpp +++ b/src/test/app/RCLValidations_test.cpp @@ -132,7 +132,7 @@ class RCLValidations_test : public beast::unit_test::suite { RCLValidatedLedger a{RCLValidatedLedger::MakeGenesis{}}; - for (auto ledger : {history.back(), history[maxAncestors - 1]}) + for (auto const& ledger : {history.back(), history[maxAncestors - 1]}) { RCLValidatedLedger b{ledger, env.journal}; BEAST_EXPECT(mismatch(a, b) == 1); diff --git a/src/test/app/Transaction_ordering_test.cpp b/src/test/app/Transaction_ordering_test.cpp index f7d431fc90..c50fbf4e56 100644 --- a/src/test/app/Transaction_ordering_test.cpp +++ b/src/test/app/Transaction_ordering_test.cpp @@ -95,14 +95,16 @@ struct Transaction_ordering_test : public beast::unit_test::suite env.fund(XRP(1000), noripple(alice)); auto const aliceSequence = env.seq(alice); + static constexpr auto kSIZE = 5; std::vector tx; - for (auto i = 0; i < 5; ++i) + tx.reserve(kSIZE); + for (auto i = 0; i < kSIZE; ++i) { tx.emplace_back(env.jt(noop(alice), seq(aliceSequence + i), last_ledger_seq(7))); } - for (auto i = 1; i < 5; ++i) + for (auto i = 1; i < kSIZE; ++i) { env(tx[i], ter(terPRE_SEQ)); BEAST_EXPECT(env.seq(alice) == aliceSequence); @@ -110,11 +112,11 @@ struct Transaction_ordering_test : public beast::unit_test::suite env(tx[0]); env.app().getJobQueue().rendezvous(); - BEAST_EXPECT(env.seq(alice) == aliceSequence + 5); + BEAST_EXPECT(env.seq(alice) == aliceSequence + kSIZE); env.close(); - for (auto i = 0; i < 5; ++i) + for (auto i = 0; i < kSIZE; ++i) { auto const result = env.rpc("tx", to_string(tx[i].stx->getTransactionID())); BEAST_EXPECT(result["result"]["meta"]["TransactionResult"] == "tesSUCCESS"); diff --git a/src/test/app/ValidatorList_test.cpp b/src/test/app/ValidatorList_test.cpp index 10e34cacad..3f1c20ee25 100644 --- a/src/test/app/ValidatorList_test.cpp +++ b/src/test/app/ValidatorList_test.cpp @@ -373,6 +373,7 @@ private: // load should accept valid validator list publisher keys std::vector cfgPublishers; + cfgPublishers.reserve(keys.size()); for (auto const& key : keys) cfgPublishers.push_back(strHex(key)); @@ -393,6 +394,7 @@ private: std::vector keys( {randomMasterKey(), randomMasterKey(), randomMasterKey(), randomMasterKey()}); std::vector cfgPublishers; + cfgPublishers.reserve(keys.size()); for (auto const& key : keys) cfgPublishers.push_back(strHex(key)); diff --git a/src/test/app/ValidatorSite_test.cpp b/src/test/app/ValidatorSite_test.cpp index 160da452ee..ee28410d9e 100644 --- a/src/test/app/ValidatorSite_test.cpp +++ b/src/test/app/ValidatorSite_test.cpp @@ -298,6 +298,7 @@ private: auto sites = std::make_unique(env.app(), journal); std::vector uris; + uris.reserve(servers.size()); for (auto const& u : servers) uris.push_back(u.uri); sites->load(uris); diff --git a/src/test/app/Vault_test.cpp b/src/test/app/Vault_test.cpp index 37ad3ae334..54cc6646b1 100644 --- a/src/test/app/Vault_test.cpp +++ b/src/test/app/Vault_test.cpp @@ -1329,7 +1329,7 @@ class Vault_test : public beast::unit_test::suite return defXRP; return a + XRP(1000); } - auto const defIOU = STAmount{a.issue(), 30000}; + auto defIOU = STAmount{a.issue(), 30000}; if (a <= defIOU) return defIOU; return a + STAmount{a.issue(), 1000}; diff --git a/src/test/basics/IntrusiveShared_test.cpp b/src/test/basics/IntrusiveShared_test.cpp index 5a460a6044..41ecf9a7a4 100644 --- a/src/test/basics/IntrusiveShared_test.cpp +++ b/src/test/basics/IntrusiveShared_test.cpp @@ -592,6 +592,7 @@ public: } }; std::vector threads; + threads.reserve(numThreads); for (int i = 0; i < numThreads; ++i) { threads.emplace_back(cloneAndDestroy, i); @@ -737,6 +738,7 @@ public: } }; std::vector threads; + threads.reserve(numThreads); for (int i = 0; i < numThreads; ++i) { threads.emplace_back(cloneAndDestroy, i); @@ -845,6 +847,7 @@ public: } }; std::vector threads; + threads.reserve(numThreads); for (int i = 0; i < numThreads; ++i) { threads.emplace_back(lockAndDestroy, i); diff --git a/src/test/beast/aged_associative_container_test.cpp b/src/test/beast/aged_associative_container_test.cpp index 22b677a7e5..1578ffceca 100644 --- a/src/test/beast/aged_associative_container_test.cpp +++ b/src/test/beast/aged_associative_container_test.cpp @@ -1362,7 +1362,7 @@ aged_associative_container_test_base::testArrayCreate() { // Copy construct key typename Traits::template Cont<> c(clock); - for (auto e : v) + for (auto const& e : v) c[e.first] = e.second; checkContents(c, v); } diff --git a/src/test/conditions/PreimageSha256_test.cpp b/src/test/conditions/PreimageSha256_test.cpp index 973f714ba4..374b6eb925 100644 --- a/src/test/conditions/PreimageSha256_test.cpp +++ b/src/test/conditions/PreimageSha256_test.cpp @@ -149,7 +149,7 @@ class PreimageSha256_test : public beast::unit_test::suite "9CF1D5F810302" "0000"}}; - for (auto x : others) + for (auto const& x : others) { std::error_code ec; diff --git a/src/test/consensus/Validations_test.cpp b/src/test/consensus/Validations_test.cpp index cf4498bd52..dc6dfe539c 100644 --- a/src/test/consensus/Validations_test.cpp +++ b/src/test/consensus/Validations_test.cpp @@ -373,7 +373,7 @@ class Validations_test : public beast::unit_test::suite [&](TestValidations& vals) { vals.getCurrentNodeIDs(); }, [&](TestValidations& vals) { vals.getPreferred(genesisLedger); }, [&](TestValidations& vals) { vals.getNodesAfter(ledgerA, ledgerA.id()); }}; - for (Trigger trigger : triggers) + for (Trigger const& trigger : triggers) { TestHarness harness(h.oracle); Node n = harness.makeNode(); @@ -569,6 +569,7 @@ class Validations_test : public beast::unit_test::suite std::uint32_t baseFee = 0; std::vector expectedFees; + expectedFees.reserve(expectedValidations.size()); for (auto const& val : expectedValidations) { expectedFees.push_back(val.loadFee().value_or(baseFee)); diff --git a/src/test/jtx/TestHelpers.h b/src/test/jtx/TestHelpers.h index 2836748ec3..08e86b40ac 100644 --- a/src/test/jtx/TestHelpers.h +++ b/src/test/jtx/TestHelpers.h @@ -317,7 +317,7 @@ template Json::Value getAccountLines(Env& env, AccountID const& acctId, IOU... ious) { - auto const jrr = getAccountLines(env, acctId); + auto jrr = getAccountLines(env, acctId); Json::Value res; for (auto const& line : jrr[jss::lines]) { diff --git a/src/test/jtx/impl/AMMTest.cpp b/src/test/jtx/impl/AMMTest.cpp index 6b8807076a..9d9a537210 100644 --- a/src/test/jtx/impl/AMMTest.cpp +++ b/src/test/jtx/impl/AMMTest.cpp @@ -119,7 +119,7 @@ AMMTestBase::testAMM(std::function const& cb, TestAM return defXRP; return a + XRP(1000); } - auto const defIOU = STAmount{a.issue(), 30000}; + auto defIOU = STAmount{a.issue(), 30000}; if (a <= defIOU) return defIOU; return a + STAmount{a.issue(), 1000}; diff --git a/src/test/jtx/impl/mpt.cpp b/src/test/jtx/impl/mpt.cpp index 933aabce30..2b78777838 100644 --- a/src/test/jtx/impl/mpt.cpp +++ b/src/test/jtx/impl/mpt.cpp @@ -45,7 +45,7 @@ MPTTester::MPTTester(Env& env, Account const& issuer, MPTInit const& arg) if (arg.fund) { env_.fund(arg.xrp, issuer_); - for (auto it : holders_) + for (auto const& it : holders_) env_.fund(arg.xrpHolders, it.second); } if (close_) @@ -53,7 +53,7 @@ MPTTester::MPTTester(Env& env, Account const& issuer, MPTInit const& arg) if (arg.fund) { env_.require(owners(issuer_, 0)); - for (auto it : holders_) + for (auto const& it : holders_) { if (issuer_.id() == it.second.id()) Throw("Issuer can't be holder"); diff --git a/src/test/jtx/mpt.h b/src/test/jtx/mpt.h index 3368d129c1..3990dd3087 100644 --- a/src/test/jtx/mpt.h +++ b/src/test/jtx/mpt.h @@ -291,7 +291,7 @@ private: env_.require(owners(issuer_, *arg.ownerCount)); if (arg.holderCount) { - for (auto it : holders_) + for (auto const& it : holders_) env_.require(owners(it.second, *arg.holderCount)); } return err; diff --git a/src/test/jtx/multisign.h b/src/test/jtx/multisign.h index 56d0b10906..b3f38cc453 100644 --- a/src/test/jtx/multisign.h +++ b/src/test/jtx/multisign.h @@ -22,7 +22,7 @@ struct signer std::optional tag; signer(Account account_, std::uint32_t weight_ = 1, std::optional tag_ = std::nullopt) - : weight(weight_), account(std::move(account_)), tag(std::move(tag_)) + : weight(weight_), account(std::move(account_)), tag(tag_) { } }; diff --git a/src/test/ledger/Directory_test.cpp b/src/test/ledger/Directory_test.cpp index b08e7daaf6..aec472fc6f 100644 --- a/src/test/ledger/Directory_test.cpp +++ b/src/test/ledger/Directory_test.cpp @@ -204,7 +204,7 @@ struct Directory_test : public beast::unit_test::suite BEAST_EXPECT(dirIsEmpty(*env.closed(), keylet::ownerDir(alice))); - for (auto c : currencies) + for (auto const& c : currencies) { env(trust(charlie, c(50))); env.close(); diff --git a/src/test/protocol/MultiApiJson_test.cpp b/src/test/protocol/MultiApiJson_test.cpp index 0da511b976..5aafa19771 100644 --- a/src/test/protocol/MultiApiJson_test.cpp +++ b/src/test/protocol/MultiApiJson_test.cpp @@ -236,7 +236,7 @@ struct MultiApiJson_test : beast::unit_test::suite std::forward(v).visit(), // [](auto...) {}); }; - }(std::move(std::as_const(s1)))); + }(std::move(std::as_const(s1)))); // NOLINT(performance-move-const-arg) } { @@ -867,22 +867,22 @@ struct MultiApiJson_test : beast::unit_test::suite return !requires { std::forward(v).visit(1, [](Json::Value const&&) {}); }; - }(std::move(std::as_const(s1)))); + }(std::move(std::as_const(s1)))); // NOLINT(performance-move-const-arg) static_assert([](auto&& v) { return requires { std::forward(v).visit(1, [](Json::Value const&) {}); }; - }(std::move(std::as_const(s1)))); + }(std::move(std::as_const(s1)))); // NOLINT(performance-move-const-arg) static_assert([](auto&& v) { return !requires { std::forward(v).visit()(1, [](Json::Value const&&) {}); }; - }(std::move(std::as_const(s1)))); + }(std::move(std::as_const(s1)))); // NOLINT(performance-move-const-arg) static_assert([](auto&& v) { return requires { std::forward(v).visit()(1, [](Json::Value const&) {}); }; - }(std::move(std::as_const(s1)))); + }(std::move(std::as_const(s1)))); // NOLINT(performance-move-const-arg) // Missing const static_assert([](auto&& v) { diff --git a/src/xrpld/app/consensus/RCLCxPeerPos.cpp b/src/xrpld/app/consensus/RCLCxPeerPos.cpp index 18a660fcd0..8f99dceea8 100644 --- a/src/xrpld/app/consensus/RCLCxPeerPos.cpp +++ b/src/xrpld/app/consensus/RCLCxPeerPos.cpp @@ -10,8 +10,8 @@ RCLCxPeerPos::RCLCxPeerPos( PublicKey const& publicKey, Slice const& signature, uint256 const& suppression, - Proposal&& proposal) - : publicKey_(publicKey), suppression_(suppression), proposal_(std::move(proposal)) + Proposal const& proposal) // trivially copyable + : publicKey_(publicKey), suppression_(suppression), proposal_(proposal) { // The maximum allowed size of a signature is 72 bytes; we verify // this elsewhere, but we want to be extra careful here: diff --git a/src/xrpld/app/consensus/RCLCxPeerPos.h b/src/xrpld/app/consensus/RCLCxPeerPos.h index 5dad4a33eb..e334320826 100644 --- a/src/xrpld/app/consensus/RCLCxPeerPos.h +++ b/src/xrpld/app/consensus/RCLCxPeerPos.h @@ -40,7 +40,7 @@ public: PublicKey const& publicKey, Slice const& signature, uint256 const& suppress, - Proposal&& proposal); + Proposal const& proposal); // trivially copyable //! Verify the signing hash of the proposal bool diff --git a/src/xrpld/app/consensus/RCLValidations.cpp b/src/xrpld/app/consensus/RCLValidations.cpp index 27fba69bb6..7bc16f194e 100644 --- a/src/xrpld/app/consensus/RCLValidations.cpp +++ b/src/xrpld/app/consensus/RCLValidations.cpp @@ -131,7 +131,7 @@ RCLValidationsAdaptor::acquire(LedgerHash const& hash) XRPL_ASSERT( ledger->header().hash == hash, "xrpl::RCLValidationsAdaptor::acquire : ledger hash match"); - return RCLValidatedLedger(std::move(ledger), j_); + return RCLValidatedLedger(ledger, j_); } void diff --git a/src/xrpld/app/ledger/detail/LedgerMaster.cpp b/src/xrpld/app/ledger/detail/LedgerMaster.cpp index 52ccd27ba4..6253b33da3 100644 --- a/src/xrpld/app/ledger/detail/LedgerMaster.cpp +++ b/src/xrpld/app/ledger/detail/LedgerMaster.cpp @@ -410,7 +410,7 @@ LedgerMaster::storeLedger(std::shared_ptr ledger) { bool validated = ledger->header().validated; // Returns true if we already had the ledger - return mLedgerHistory.insert(std::move(ledger), validated); + return mLedgerHistory.insert(ledger, validated); } /** Apply held transactions to the open ledger diff --git a/src/xrpld/app/main/Application.cpp b/src/xrpld/app/main/Application.cpp index 76a95bd542..0d8325be54 100644 --- a/src/xrpld/app/main/Application.cpp +++ b/src/xrpld/app/main/Application.cpp @@ -1411,7 +1411,7 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) // // Execute start up rpc commands. // - for (auto cmd : config_->section(SECTION_RPC_STARTUP).lines()) + for (auto const& cmd : config_->section(SECTION_RPC_STARTUP).lines()) { Json::Reader jrReader; Json::Value jvCommand; diff --git a/src/xrpld/app/main/GRPCServer.cpp b/src/xrpld/app/main/GRPCServer.cpp index f95c20ba8c..130d0f01b9 100644 --- a/src/xrpld/app/main/GRPCServer.cpp +++ b/src/xrpld/app/main/GRPCServer.cpp @@ -16,8 +16,8 @@ getEndpoint(std::string const& peer) { try { - std::size_t first = peer.find_first_of(":"); - std::size_t last = peer.find_last_of(":"); + std::size_t first = peer.find_first_of(':'); + std::size_t last = peer.find_last_of(':'); std::string peerClean(peer); if (first != last) { @@ -56,7 +56,7 @@ GRPCServerImpl::CallData::CallData( , bindListener_(std::move(bindListener)) , handler_(std::move(handler)) , forward_(std::move(forward)) - , requiredCondition_(std::move(requiredCondition)) + , requiredCondition_(requiredCondition) , loadType_(std::move(loadType)) , secureGatewayIPs_(secureGatewayIPs) { diff --git a/src/xrpld/app/main/Main.cpp b/src/xrpld/app/main/Main.cpp index 85f6ae651a..570131b52d 100644 --- a/src/xrpld/app/main/Main.cpp +++ b/src/xrpld/app/main/Main.cpp @@ -282,6 +282,7 @@ runUnitTests( args.emplace_back("--unittest-child"); } + children.reserve(num_jobs); for (std::size_t i = 0; i < num_jobs; ++i) { children.emplace_back( diff --git a/src/xrpld/app/misc/NetworkOPs.cpp b/src/xrpld/app/misc/NetworkOPs.cpp index ffccf765f0..b323541362 100644 --- a/src/xrpld/app/misc/NetworkOPs.cpp +++ b/src/xrpld/app/misc/NetworkOPs.cpp @@ -189,7 +189,7 @@ class NetworkOPsImp final : public NetworkOPs ServerFeeSummary( XRPAmount fee, - TxQ::Metrics&& escalationMetrics, + TxQ::Metrics escalationMetrics, // trivially copyable LoadFeeTrack const& loadFeeTrack); bool operator!=(ServerFeeSummary const& b) const; @@ -2142,12 +2142,12 @@ NetworkOPsImp::pubManifest(Manifest const& mo) NetworkOPsImp::ServerFeeSummary::ServerFeeSummary( XRPAmount fee, - TxQ::Metrics&& escalationMetrics, + TxQ::Metrics escalationMetrics, // trivially copyable LoadFeeTrack const& loadFeeTrack) : loadFactorServer{loadFeeTrack.getLoadFactor()} , loadBaseServer{loadFeeTrack.getLoadBase()} , baseFee{fee} - , em{std::move(escalationMetrics)} + , em{escalationMetrics} { } diff --git a/src/xrpld/app/misc/detail/ValidatorList.cpp b/src/xrpld/app/misc/detail/ValidatorList.cpp index 29c0e75c78..abf64a4a93 100644 --- a/src/xrpld/app/misc/detail/ValidatorList.cpp +++ b/src/xrpld/app/misc/detail/ValidatorList.cpp @@ -137,7 +137,7 @@ ValidatorList::load( JLOG(j_.debug()) << "Loading configured trusted validator list publisher keys"; std::size_t count = 0; - for (auto key : publisherKeys) + for (auto const& key : publisherKeys) { JLOG(j_.trace()) << "Processing '" << key << "'"; @@ -1406,7 +1406,7 @@ ValidatorList::getListedKey(PublicKey const& identity) const { std::shared_lock read_lock{mutex_}; - auto const pubKey = validatorManifests_.getMasterKey(identity); + auto pubKey = validatorManifests_.getMasterKey(identity); if (keyListings_.contains(pubKey)) return pubKey; return std::nullopt; @@ -1415,7 +1415,7 @@ ValidatorList::getListedKey(PublicKey const& identity) const std::optional ValidatorList::getTrustedKey(ValidatorList::shared_lock const&, PublicKey const& identity) const { - auto const pubKey = validatorManifests_.getMasterKey(identity); + auto pubKey = validatorManifests_.getMasterKey(identity); if (trustedMasterKeys_.contains(pubKey)) return pubKey; return std::nullopt; diff --git a/src/xrpld/app/misc/detail/ValidatorSite.cpp b/src/xrpld/app/misc/detail/ValidatorSite.cpp index 91352cb12d..b93a1b8007 100644 --- a/src/xrpld/app/misc/detail/ValidatorSite.cpp +++ b/src/xrpld/app/misc/detail/ValidatorSite.cpp @@ -227,12 +227,13 @@ ValidatorSite::makeRequest( { } }; - auto onFetch = - [this, siteIdx, timeoutCancel]( - error_code const& err, endpoint_type const& endpoint, detail::response_type&& resp) { - timeoutCancel(); - onSiteFetch(err, endpoint, std::move(resp), siteIdx); - }; + auto onFetch = [this, siteIdx, timeoutCancel]( + error_code const& err, + endpoint_type const& endpoint, + detail::response_type const& resp) { + timeoutCancel(); + onSiteFetch(err, endpoint, resp, siteIdx); + }; auto onFetchFile = [this, siteIdx, timeoutCancel]( error_code const& err, std::string const& resp) { diff --git a/src/xrpld/app/rdb/backend/detail/SQLiteDatabase.cpp b/src/xrpld/app/rdb/backend/detail/SQLiteDatabase.cpp index ee3f9799ad..90d3b5a8e4 100644 --- a/src/xrpld/app/rdb/backend/detail/SQLiteDatabase.cpp +++ b/src/xrpld/app/rdb/backend/detail/SQLiteDatabase.cpp @@ -400,12 +400,13 @@ SQLiteDatabase::oldestAccountTxPage(AccountTxPageOptions const& options) auto onUnsavedLedger = std::bind(saveLedgerAsync, std::ref(registry_.get().getApp()), std::placeholders::_1); AccountTxs ret; - auto onTransaction = - [&ret, &app = registry_.get().getApp()]( - std::uint32_t ledger_index, std::string const& status, Blob&& rawTxn, Blob&& rawMeta) { - convertBlobsToTxResult( - ret, ledger_index, status, std::move(rawTxn), std::move(rawMeta), app); - }; + auto onTransaction = [&ret, &app = registry_.get().getApp()]( + std::uint32_t ledger_index, + std::string const& status, + Blob const& rawTxn, + Blob const& rawMeta) { + convertBlobsToTxResult(ret, ledger_index, status, rawTxn, rawMeta, app); + }; if (existsTransaction()) { @@ -429,12 +430,13 @@ SQLiteDatabase::newestAccountTxPage(AccountTxPageOptions const& options) auto onUnsavedLedger = std::bind(saveLedgerAsync, std::ref(registry_.get().getApp()), std::placeholders::_1); AccountTxs ret; - auto onTransaction = - [&ret, &app = registry_.get().getApp()]( - std::uint32_t ledger_index, std::string const& status, Blob&& rawTxn, Blob&& rawMeta) { - convertBlobsToTxResult( - ret, ledger_index, status, std::move(rawTxn), std::move(rawMeta), app); - }; + auto onTransaction = [&ret, &app = registry_.get().getApp()]( + std::uint32_t ledger_index, + std::string const& status, + Blob const& rawTxn, + Blob const& rawMeta) { + convertBlobsToTxResult(ret, ledger_index, status, rawTxn, rawMeta, app); + }; if (existsTransaction()) { diff --git a/src/xrpld/overlay/detail/OverlayImpl.cpp b/src/xrpld/overlay/detail/OverlayImpl.cpp index aa3441f389..b4b0686ac8 100644 --- a/src/xrpld/overlay/detail/OverlayImpl.cpp +++ b/src/xrpld/overlay/detail/OverlayImpl.cpp @@ -1015,7 +1015,7 @@ OverlayImpl::getActivePeers() const Overlay::PeerSequence ret; ret.reserve(size()); - for_each([&ret](std::shared_ptr const& sp) { ret.emplace_back(std::move(sp)); }); + for_each([&ret](std::shared_ptr const& sp) { ret.emplace_back(sp); }); return ret; } @@ -1302,7 +1302,7 @@ void OverlayImpl::autoConnect() { auto const result = m_peerFinder->autoconnect(); - for (auto addr : result) + for (auto const& addr : result) connect(addr); } diff --git a/src/xrpld/overlay/detail/ProtocolMessage.h b/src/xrpld/overlay/detail/ProtocolMessage.h index 2442e48031..ac06b10292 100644 --- a/src/xrpld/overlay/detail/ProtocolMessage.h +++ b/src/xrpld/overlay/detail/ProtocolMessage.h @@ -237,7 +237,7 @@ template < std::shared_ptr parseMessageContent(MessageHeader const& header, Buffers const& buffers) { - auto const m = std::make_shared(); + auto m = std::make_shared(); ZeroCopyInputStream stream(buffers); stream.Skip(header.header_size); diff --git a/src/xrpld/peerfinder/detail/Logic.h b/src/xrpld/peerfinder/detail/Logic.h index 39f1ca6ae6..8f49da6c4f 100644 --- a/src/xrpld/peerfinder/detail/Logic.h +++ b/src/xrpld/peerfinder/detail/Logic.h @@ -452,7 +452,7 @@ public: std::vector autoconnect() { - std::vector const none; + std::vector none; std::lock_guard _(lock_); @@ -1011,7 +1011,7 @@ public: { int count(0); std::lock_guard _(lock_); - for (auto addr : list) + for (auto const& addr : list) { if (bootcache_.insertStatic(addr)) ++count; diff --git a/src/xrpld/rpc/detail/RPCCall.cpp b/src/xrpld/rpc/detail/RPCCall.cpp index c9d5d67cf3..5c57f96d79 100644 --- a/src/xrpld/rpc/detail/RPCCall.cpp +++ b/src/xrpld/rpc/detail/RPCCall.cpp @@ -395,7 +395,7 @@ private: // handle case where there is one argument of the form ip:port if (std::count(ip.begin(), ip.end(), ':') == 1) { - std::size_t colon = ip.find_last_of(":"); + std::size_t colon = ip.find_last_of(':'); jvRequest[jss::ip] = std::string{ip, 0, colon}; jvRequest[jss::port] = Json::Value{std::string{ip, colon + 1}}.asUInt(); return jvRequest; @@ -817,7 +817,8 @@ private: Json::Value jvRequest(Json::objectValue); for (auto i = 0; i < nParams; ++i) { - std::string strParam = jvParams[i].asString(); + // This was non-const. see comment below + std::string const strParam = jvParams[i].asString(); if (i == 1 && strParam.empty()) continue; @@ -827,7 +828,10 @@ private: { if (parseBase58(strParam)) { - jvRequest[accFields[i]] = std::move(strParam); + // TODO: this was std::move'd before but it does not work in practice. + // We would need a Value(std::string&&) for it to work. + // See https://github.com/XRPLF/rippled/issues/6677 + jvRequest[accFields[i]] = strParam; } else { diff --git a/src/xrpld/rpc/detail/ServerHandler.cpp b/src/xrpld/rpc/detail/ServerHandler.cpp index 64c81ccc0a..ca026104cf 100644 --- a/src/xrpld/rpc/detail/ServerHandler.cpp +++ b/src/xrpld/rpc/detail/ServerHandler.cpp @@ -79,7 +79,7 @@ authorized(Port const& port, std::map const& h) std::string strUserPass64 = it->second.substr(6); boost::trim(strUserPass64); std::string strUserPass = base64_decode(strUserPass64); - std::string::size_type nColon = strUserPass.find(":"); + std::string::size_type nColon = strUserPass.find(':'); if (nColon == std::string::npos) return false; std::string strUser = strUserPass.substr(0, nColon); diff --git a/src/xrpld/rpc/handlers/AMMInfo.cpp b/src/xrpld/rpc/handlers/AMMInfo.cpp index 42e44f004d..9204f48907 100644 --- a/src/xrpld/rpc/handlers/AMMInfo.cpp +++ b/src/xrpld/rpc/handlers/AMMInfo.cpp @@ -139,7 +139,7 @@ doAMMInfo(RPC::JsonContext& context) issue2 = (*amm)[sfAsset2].get(); } - return ValuesFromContextParams{accountID, *issue1, *issue2, std::move(amm)}; + return ValuesFromContextParams{accountID, *issue1, *issue2, amm}; }; auto const r = getValuesFromContextParams(); diff --git a/src/xrpld/rpc/handlers/AccountChannels.cpp b/src/xrpld/rpc/handlers/AccountChannels.cpp index c418386a71..7bf8a03f21 100644 --- a/src/xrpld/rpc/handlers/AccountChannels.cpp +++ b/src/xrpld/rpc/handlers/AccountChannels.cpp @@ -67,7 +67,7 @@ doAccountChannels(RPC::JsonContext& context) { return rpcError(rpcACT_MALFORMED); } - AccountID const accountID{std::move(id.value())}; + AccountID const accountID{id.value()}; if (!ledger->exists(keylet::account(accountID))) return rpcError(rpcACT_NOT_FOUND); diff --git a/src/xrpld/rpc/handlers/AccountCurrenciesHandler.cpp b/src/xrpld/rpc/handlers/AccountCurrenciesHandler.cpp index fe74c915f5..e509a72862 100644 --- a/src/xrpld/rpc/handlers/AccountCurrenciesHandler.cpp +++ b/src/xrpld/rpc/handlers/AccountCurrenciesHandler.cpp @@ -44,7 +44,7 @@ doAccountCurrencies(RPC::JsonContext& context) RPC::inject_error(rpcACT_MALFORMED, result); return result; } - auto const accountID{std::move(id.value())}; + auto const accountID{id.value()}; if (!ledger->exists(keylet::account(accountID))) return rpcError(rpcACT_NOT_FOUND); diff --git a/src/xrpld/rpc/handlers/AccountInfo.cpp b/src/xrpld/rpc/handlers/AccountInfo.cpp index 55f05ddcab..becaea8a51 100644 --- a/src/xrpld/rpc/handlers/AccountInfo.cpp +++ b/src/xrpld/rpc/handlers/AccountInfo.cpp @@ -102,7 +102,7 @@ doAccountInfo(RPC::JsonContext& context) RPC::inject_error(rpcACT_MALFORMED, result); return result; } - auto const accountID{std::move(id.value())}; + auto const accountID{id.value()}; static constexpr std::array, 9> lsFlags{ {{"defaultRipple", lsfDefaultRipple}, diff --git a/src/xrpld/rpc/handlers/AccountLines.cpp b/src/xrpld/rpc/handlers/AccountLines.cpp index 396a09b082..f7fc9bdd2d 100644 --- a/src/xrpld/rpc/handlers/AccountLines.cpp +++ b/src/xrpld/rpc/handlers/AccountLines.cpp @@ -81,7 +81,7 @@ doAccountLines(RPC::JsonContext& context) RPC::inject_error(rpcACT_MALFORMED, result); return result; } - auto const accountID{std::move(id.value())}; + auto const accountID{id.value()}; if (!ledger->exists(keylet::account(accountID))) return rpcError(rpcACT_NOT_FOUND); diff --git a/src/xrpld/rpc/handlers/AccountOffers.cpp b/src/xrpld/rpc/handlers/AccountOffers.cpp index 86ab140b03..517c0728e9 100644 --- a/src/xrpld/rpc/handlers/AccountOffers.cpp +++ b/src/xrpld/rpc/handlers/AccountOffers.cpp @@ -56,7 +56,7 @@ doAccountOffers(RPC::JsonContext& context) RPC::inject_error(rpcACT_MALFORMED, result); return result; } - auto const accountID{std::move(id.value())}; + auto const accountID{id.value()}; // Get info on account. result[jss::account] = toBase58(accountID); diff --git a/src/xrpld/rpc/handlers/AccountTx.cpp b/src/xrpld/rpc/handlers/AccountTx.cpp index 9a10e49e5d..e120c98523 100644 --- a/src/xrpld/rpc/handlers/AccountTx.cpp +++ b/src/xrpld/rpc/handlers/AccountTx.cpp @@ -133,7 +133,7 @@ getLedgerRange(RPC::Context& context, std::optional const& ledg // Does request specify a ledger or ledger range? if (ledgerSpecifier) { - auto const status = std::visit( + auto status = std::visit( [&](auto const& ls) -> RPC::Status { using T = std::decay_t; if constexpr (std::is_same_v) @@ -167,7 +167,7 @@ getLedgerRange(RPC::Context& context, std::optional const& ledg else { std::shared_ptr ledgerView; - auto const status = getLedger(ledgerView, ls, context); + auto status = getLedger(ledgerView, ls, context); if (!ledgerView) { return status; diff --git a/src/xrpld/rpc/handlers/DepositAuthorized.cpp b/src/xrpld/rpc/handlers/DepositAuthorized.cpp index b2fc13415e..fb1c0db884 100644 --- a/src/xrpld/rpc/handlers/DepositAuthorized.cpp +++ b/src/xrpld/rpc/handlers/DepositAuthorized.cpp @@ -35,7 +35,7 @@ doDepositAuthorized(RPC::JsonContext& context) auto srcID = parseBase58(params[jss::source_account].asString()); if (!srcID) return rpcError(rpcACT_MALFORMED); - auto const srcAcct{std::move(srcID.value())}; + auto const srcAcct{srcID.value()}; // Validate destination_account. if (!params.isMember(jss::destination_account)) @@ -49,7 +49,7 @@ doDepositAuthorized(RPC::JsonContext& context) auto dstID = parseBase58(params[jss::destination_account].asString()); if (!dstID) return rpcError(rpcACT_MALFORMED); - auto const dstAcct{std::move(dstID.value())}; + auto const dstAcct{dstID.value()}; // Validate ledger. std::shared_ptr ledger; diff --git a/src/xrpld/rpc/handlers/GatewayBalances.cpp b/src/xrpld/rpc/handlers/GatewayBalances.cpp index 914725de60..8d03a3961d 100644 --- a/src/xrpld/rpc/handlers/GatewayBalances.cpp +++ b/src/xrpld/rpc/handlers/GatewayBalances.cpp @@ -55,7 +55,7 @@ doGatewayBalances(RPC::JsonContext& context) auto id = parseBase58(strIdent); if (!id) return rpcError(rpcACT_MALFORMED); - auto const accountID{std::move(id.value())}; + auto const accountID{id.value()}; context.loadType = Resource::feeHeavyBurdenRPC; result[jss::account] = toBase58(accountID); @@ -76,7 +76,7 @@ doGatewayBalances(RPC::JsonContext& context) { if (auto id = parseBase58(j.asString()); id) { - hotWallets.insert(std::move(id.value())); + hotWallets.insert(id.value()); return true; } } diff --git a/src/xrpld/rpc/handlers/LedgerEntry.cpp b/src/xrpld/rpc/handlers/LedgerEntry.cpp index 640369c04b..c7a47a0517 100644 --- a/src/xrpld/rpc/handlers/LedgerEntry.cpp +++ b/src/xrpld/rpc/handlers/LedgerEntry.cpp @@ -328,7 +328,7 @@ parseDepositPreauth( "malformedAuthorizedCredentials", jss::authorized_credentials, "array"); } - return keylet::depositPreauth(*owner, std::move(sorted)).key; + return keylet::depositPreauth(*owner, sorted).key; } static Expected diff --git a/src/xrpld/rpc/handlers/LedgerEntryHelpers.h b/src/xrpld/rpc/handlers/LedgerEntryHelpers.h index 683e6ebb5a..9182c9cfd7 100644 --- a/src/xrpld/rpc/handlers/LedgerEntryHelpers.h +++ b/src/xrpld/rpc/handlers/LedgerEntryHelpers.h @@ -20,10 +20,9 @@ Unexpected missingFieldError(Json::StaticString const field, std::optional err = std::nullopt) { Json::Value json = Json::objectValue; - auto error = RPC::missing_field_message(std::string(field.c_str())); json[jss::error] = err.value_or("malformedRequest"); json[jss::error_code] = rpcINVALID_PARAMS; - json[jss::error_message] = std::move(error); + json[jss::error_message] = RPC::missing_field_message(std::string(field.c_str())); return Unexpected(json); } @@ -31,10 +30,9 @@ Unexpected invalidFieldError(std::string const& err, Json::StaticString const field, std::string const& type) { Json::Value json = Json::objectValue; - auto error = RPC::expected_field_message(field, type); json[jss::error] = err; json[jss::error_code] = rpcINVALID_PARAMS; - json[jss::error_message] = std::move(error); + json[jss::error_message] = RPC::expected_field_message(field, type); return Unexpected(json); } @@ -118,7 +116,7 @@ parseHexBlob(Json::Value const& param, std::size_t maxLength) if (!param.isString()) return std::nullopt; - auto const blob = strUnHex(param.asString()); + auto blob = strUnHex(param.asString()); if (!blob || blob->empty() || blob->size() > maxLength) return std::nullopt; diff --git a/src/xrpld/rpc/handlers/NoRippleCheck.cpp b/src/xrpld/rpc/handlers/NoRippleCheck.cpp index 7b780f3b16..c3e36280a6 100644 --- a/src/xrpld/rpc/handlers/NoRippleCheck.cpp +++ b/src/xrpld/rpc/handlers/NoRippleCheck.cpp @@ -98,7 +98,7 @@ doNoRippleCheck(RPC::JsonContext& context) RPC::inject_error(rpcACT_MALFORMED, result); return result; } - auto const accountID{std::move(id.value())}; + auto const accountID{id.value()}; auto const sle = ledger->read(keylet::account(accountID)); if (!sle) return rpcError(rpcACT_NOT_FOUND); diff --git a/src/xrpld/rpc/handlers/ServerDefinitions.cpp b/src/xrpld/rpc/handlers/ServerDefinitions.cpp index e4f08d6dec..2f11e18efb 100644 --- a/src/xrpld/rpc/handlers/ServerDefinitions.cpp +++ b/src/xrpld/rpc/handlers/ServerDefinitions.cpp @@ -93,7 +93,7 @@ ServerDefinitions::translate(std::string const& inp) // convert snake_case to CamelCase for (;;) { - pos = inpToProcess.find("_"); + pos = inpToProcess.find('_'); if (pos == std::string::npos) pos = inpToProcess.size(); std::string token = inpToProcess.substr(0, pos); From 5c8dfe54567b554c84af3267cbafc1e1f1899126 Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Mon, 30 Mar 2026 18:15:40 +0100 Subject: [PATCH 36/53] ci: Only publish docs in public repos (#6687) --- .github/workflows/publish-docs.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/publish-docs.yml b/.github/workflows/publish-docs.yml index 643a02da8d..7d40ff3363 100644 --- a/.github/workflows/publish-docs.yml +++ b/.github/workflows/publish-docs.yml @@ -81,13 +81,13 @@ jobs: cmake --build . --target docs --parallel ${BUILD_NPROC} - name: Create documentation artifact - if: ${{ github.event_name == 'push' }} + if: ${{ github.event.repository.visibility == 'public' && github.event_name == 'push' }} uses: actions/upload-pages-artifact@7b1f4a764d45c48632c6b24a0339c27f5614fb0b # v4.0.0 with: path: ${{ env.BUILD_DIR }}/docs/html deploy: - if: ${{ github.event_name == 'push' }} + if: ${{ github.event.repository.visibility == 'public' && github.event_name == 'push' }} needs: build runs-on: ubuntu-latest permissions: From bb95a7d6cd796807f5098ea6bac616acef578d19 Mon Sep 17 00:00:00 2001 From: Pratik Mankawde <3397372+pratikmankawde@users.noreply.github.com> Date: Tue, 31 Mar 2026 16:06:04 +0100 Subject: [PATCH 37/53] fix: Fix Workers::stop() race between m_allPaused and m_runningTaskCount (#6574) Co-authored-by: Claude Opus 4.6 --- src/libxrpl/core/detail/Workers.cpp | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/src/libxrpl/core/detail/Workers.cpp b/src/libxrpl/core/detail/Workers.cpp index 21bf75b958..b7d962b79b 100644 --- a/src/libxrpl/core/detail/Workers.cpp +++ b/src/libxrpl/core/detail/Workers.cpp @@ -1,5 +1,4 @@ #include -#include #include #include @@ -96,11 +95,13 @@ Workers::stop() { setNumberOfThreads(0); + // Wait until all workers have paused AND no tasks are actively running. + // Both conditions are needed because m_allPaused (mutex-protected) and + // m_runningTaskCount (atomic) are not synchronized under the same lock, + // so m_allPaused can momentarily be true while a task is still finishing. std::unique_lock lk{m_mut}; - m_cv.wait(lk, [this] { return m_allPaused; }); + m_cv.wait(lk, [this] { return m_allPaused && numberOfCurrentlyRunningTasks() == 0; }); lk.unlock(); - - XRPL_ASSERT(numberOfCurrentlyRunningTasks() == 0, "xrpl::Workers::stop : zero running tasks"); } void @@ -215,7 +216,18 @@ Workers::Worker::run() // ++m_workers.m_runningTaskCount; m_workers.m_callback.processTask(instance_); - --m_workers.m_runningTaskCount; + + // When the running task count drops to zero, wake stop() which + // may be waiting for both m_allPaused and zero running tasks. + // Locking m_mut before notify_all() prevents a lost wakeup: + // it serializes against the predicate check inside stop()'s + // cv.wait(), ensuring the notification is not missed between + // the predicate evaluation and the actual sleep. + if (--m_workers.m_runningTaskCount == 0) + { + std::lock_guard lk{m_workers.m_mut}; + m_workers.m_cv.notify_all(); + } } // Any worker that goes into the paused list must From 7f53351920d400b2a7ca8a2798d1bfa1a8e4b150 Mon Sep 17 00:00:00 2001 From: Bart Date: Tue, 31 Mar 2026 11:38:04 -0400 Subject: [PATCH 38/53] chore: Remove unnecessary clang-format off/on directives (#6682) Co-authored-by: Bart <11445373+bthomee@users.noreply.github.com> --- include/xrpl/basics/IntrusivePointer.ipp | 20 +- include/xrpl/basics/SlabAllocator.h | 3 - include/xrpl/protocol/detail/STVar.h | 10 +- include/xrpl/protocol/detail/features.macro | 111 +- include/xrpl/protocol/detail/sfields.macro | 3 - include/xrpl/protocol/jss.h | 1329 ++++++++--------- include/xrpl/resource/Fees.h | 38 +- include/xrpl/tx/paths/detail/Steps.h | 21 +- include/xrpl/tx/transactors/dex/AMMHelpers.h | 2 - src/libxrpl/protocol/STValidation.cpp | 32 +- src/libxrpl/tx/applySteps.cpp | 14 +- src/libxrpl/tx/paths/AMMLiquidity.cpp | 8 +- .../tx/transactors/check/CheckCash.cpp | 32 +- .../tx/transactors/escrow/EscrowHelpers.h | 34 +- src/test/app/MultiSign_test.cpp | 21 +- src/test/app/TheoreticalQuality_test.cpp | 16 +- src/test/app/TxQ_test.cpp | 54 +- src/test/jtx/TestHelpers.h | 2 - src/test/overlay/ProtocolVersion_test.cpp | 10 +- src/test/unit_test/SuiteJournal.h | 6 +- src/xrpld/core/detail/Config.cpp | 4 +- src/xrpld/overlay/detail/ProtocolVersion.cpp | 7 +- 22 files changed, 843 insertions(+), 934 deletions(-) diff --git a/include/xrpl/basics/IntrusivePointer.ipp b/include/xrpl/basics/IntrusivePointer.ipp index de57e61ba6..59caf5a931 100644 --- a/include/xrpl/basics/IntrusivePointer.ipp +++ b/include/xrpl/basics/IntrusivePointer.ipp @@ -68,9 +68,7 @@ SharedIntrusive::operator=(SharedIntrusive const& rhs) template template -// clang-format off -requires std::convertible_to -// clang-format on + requires std::convertible_to SharedIntrusive& SharedIntrusive::operator=(SharedIntrusive const& rhs) { @@ -101,9 +99,7 @@ SharedIntrusive::operator=(SharedIntrusive&& rhs) template template -// clang-format off -requires std::convertible_to -// clang-format on + requires std::convertible_to SharedIntrusive& SharedIntrusive::operator=(SharedIntrusive&& rhs) { @@ -307,9 +303,7 @@ WeakIntrusive::WeakIntrusive(SharedIntrusive const& rhs) : ptr_{rhs.unsafe template template -// clang-format off -requires std::convertible_to -// clang-format on + requires std::convertible_to WeakIntrusive& WeakIntrusive::operator=(SharedIntrusive const& rhs) { @@ -454,9 +448,7 @@ SharedWeakUnion::operator=(SharedWeakUnion const& rhs) template template -// clang-format off -requires std::convertible_to -// clang-format on + requires std::convertible_to SharedWeakUnion& SharedWeakUnion::operator=(SharedIntrusive const& rhs) { @@ -470,9 +462,7 @@ SharedWeakUnion::operator=(SharedIntrusive const& rhs) template template -// clang-format off -requires std::convertible_to -// clang-format on + requires std::convertible_to SharedWeakUnion& SharedWeakUnion::operator=(SharedIntrusive&& rhs) { diff --git a/include/xrpl/basics/SlabAllocator.h b/include/xrpl/basics/SlabAllocator.h index d7ca3a87f1..e0c6456c0f 100644 --- a/include/xrpl/basics/SlabAllocator.h +++ b/include/xrpl/basics/SlabAllocator.h @@ -215,11 +215,8 @@ public: // We want to allocate the memory at a 2 MiB boundary, to make it // possible to use hugepage mappings on Linux: auto buf = boost::alignment::aligned_alloc(megabytes(std::size_t(2)), size); - - // clang-format off if (!buf) [[unlikely]] return nullptr; - // clang-format on #if BOOST_OS_LINUX // When allocating large blocks, attempt to leverage Linux's diff --git a/include/xrpl/protocol/detail/STVar.h b/include/xrpl/protocol/detail/STVar.h index bab2c2e024..aaf9696571 100644 --- a/include/xrpl/protocol/detail/STVar.h +++ b/include/xrpl/protocol/detail/STVar.h @@ -25,16 +25,10 @@ extern nonPresentObject_t nonPresentObject; // Concept to constrain STVar constructors, which // instantiate ST* types from SerializedTypeID -// clang-format off template concept ValidConstructSTArgs = - (std::is_same_v< - std::tuple...>, - std::tuple> || - std::is_same_v< - std::tuple...>, - std::tuple>); -// clang-format on + (std::is_same_v...>, std::tuple> || + std::is_same_v...>, std::tuple>); // "variant" that can hold any type of serialized object // and includes a small-object allocation optimization. diff --git a/include/xrpl/protocol/detail/features.macro b/include/xrpl/protocol/detail/features.macro index d8d9dc0117..c697629e59 100644 --- a/include/xrpl/protocol/detail/features.macro +++ b/include/xrpl/protocol/detail/features.macro @@ -11,66 +11,65 @@ #error "undefined macro: XRPL_RETIRE_FIX" #endif -// clang-format off // Add new amendments to the top of this list. // Keep it sorted in reverse chronological order. -XRPL_FIX (Security3_1_3, Supported::no, VoteBehavior::DefaultNo) -XRPL_FIX (PermissionedDomainInvariant, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FIX (ExpiredNFTokenOfferRemoval, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FIX (BatchInnerSigs, Supported::no, VoteBehavior::DefaultNo) -XRPL_FEATURE(LendingProtocol, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FEATURE(PermissionDelegationV1_1, Supported::no, VoteBehavior::DefaultNo) -XRPL_FIX (DirectoryLimit, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FIX (IncludeKeyletFields, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FEATURE(DynamicMPT, Supported::no, VoteBehavior::DefaultNo) -XRPL_FIX (TokenEscrowV1, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FIX (PriceOracleOrder, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FIX (MPTDeliveredAmount, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FIX (AMMClawbackRounding, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FEATURE(TokenEscrow, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FIX (EnforceNFTokenTrustlineV2, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FIX (AMMv1_3, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FEATURE(PermissionedDEX, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FEATURE(Batch, Supported::no, VoteBehavior::DefaultNo) -XRPL_FEATURE(SingleAssetVault, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FIX (PayChanCancelAfter, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FIX (Security3_1_3, Supported::no, VoteBehavior::DefaultNo) +XRPL_FIX (PermissionedDomainInvariant, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FIX (ExpiredNFTokenOfferRemoval, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FIX (BatchInnerSigs, Supported::no, VoteBehavior::DefaultNo) +XRPL_FEATURE(LendingProtocol, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FEATURE(PermissionDelegationV1_1, Supported::no, VoteBehavior::DefaultNo) +XRPL_FIX (DirectoryLimit, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FIX (IncludeKeyletFields, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FEATURE(DynamicMPT, Supported::no, VoteBehavior::DefaultNo) +XRPL_FIX (TokenEscrowV1, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FIX (PriceOracleOrder, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FIX (MPTDeliveredAmount, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FIX (AMMClawbackRounding, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FEATURE(TokenEscrow, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FIX (EnforceNFTokenTrustlineV2, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FIX (AMMv1_3, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FEATURE(PermissionedDEX, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FEATURE(Batch, Supported::no, VoteBehavior::DefaultNo) +XRPL_FEATURE(SingleAssetVault, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FIX (PayChanCancelAfter, Supported::yes, VoteBehavior::DefaultNo) // Check flags in Credential transactions -XRPL_FIX (InvalidTxFlags, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FIX (FrozenLPTokenTransfer, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FEATURE(DeepFreeze, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FEATURE(PermissionedDomains, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FEATURE(DynamicNFT, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FEATURE(Credentials, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FEATURE(AMMClawback, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FIX (AMMv1_2, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FEATURE(MPTokensV1, Supported::yes, VoteBehavior::DefaultNo) -// InvariantsV1_1 will be changes to Supported::yes when all the -// invariants expected to be included under it are complete. -XRPL_FEATURE(InvariantsV1_1, Supported::no, VoteBehavior::DefaultNo) -XRPL_FIX (NFTokenPageLinks, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FIX (InnerObjTemplate2, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FIX (EnforceNFTokenTrustline, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FIX (ReducedOffersV2, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FEATURE(NFTokenMintOffer, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FIX (AMMv1_1, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FIX (PreviousTxnID, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FIX (XChainRewardRounding, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FIX (EmptyDID, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FEATURE(PriceOracle, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FIX (AMMOverflowOffer, Supported::yes, VoteBehavior::DefaultYes) -XRPL_FIX (InnerObjTemplate, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FIX (NFTokenReserve, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FIX (FillOrKill, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FEATURE(DID, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FIX (DisallowIncomingV1, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FEATURE(XChainBridge, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FEATURE(AMM, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FEATURE(Clawback, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FIX (UniversalNumber, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FEATURE(XRPFees, Supported::yes, VoteBehavior::DefaultNo) -XRPL_FIX (RemoveNFTokenAutoTrustLine, Supported::yes, VoteBehavior::DefaultYes) +XRPL_FIX (InvalidTxFlags, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FIX (FrozenLPTokenTransfer, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FEATURE(DeepFreeze, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FEATURE(PermissionedDomains, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FEATURE(DynamicNFT, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FEATURE(Credentials, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FEATURE(AMMClawback, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FIX (AMMv1_2, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FEATURE(MPTokensV1, Supported::yes, VoteBehavior::DefaultNo) +// InvariantsV1_1 will be changed to Supported::yes when all the invariants expected to be included +// under it are complete. +XRPL_FEATURE(InvariantsV1_1, Supported::no, VoteBehavior::DefaultNo) +XRPL_FIX (NFTokenPageLinks, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FIX (InnerObjTemplate2, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FIX (EnforceNFTokenTrustline, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FIX (ReducedOffersV2, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FEATURE(NFTokenMintOffer, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FIX (AMMv1_1, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FIX (PreviousTxnID, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FIX (XChainRewardRounding, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FIX (EmptyDID, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FEATURE(PriceOracle, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FIX (AMMOverflowOffer, Supported::yes, VoteBehavior::DefaultYes) +XRPL_FIX (InnerObjTemplate, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FIX (NFTokenReserve, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FIX (FillOrKill, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FEATURE(DID, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FIX (DisallowIncomingV1, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FEATURE(XChainBridge, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FEATURE(AMM, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FEATURE(Clawback, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FIX (UniversalNumber, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FEATURE(XRPFees, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FIX (RemoveNFTokenAutoTrustLine, Supported::yes, VoteBehavior::DefaultYes) // The following amendments are obsolete, but must remain supported // because they could potentially get enabled. @@ -144,5 +143,3 @@ XRPL_RETIRE_FEATURE(SortedDirectories) XRPL_RETIRE_FEATURE(TicketBatch) XRPL_RETIRE_FEATURE(TickSize) XRPL_RETIRE_FEATURE(TrustSetAuth) - -// clang-format on diff --git a/include/xrpl/protocol/detail/sfields.macro b/include/xrpl/protocol/detail/sfields.macro index 712cf568af..a203f2fe8c 100644 --- a/include/xrpl/protocol/detail/sfields.macro +++ b/include/xrpl/protocol/detail/sfields.macro @@ -5,7 +5,6 @@ #error "undefined macro: TYPED_SFIELD" #endif -// clang-format off // untyped UNTYPED_SFIELD(sfLedgerEntry, LEDGERENTRY, 257) @@ -421,5 +420,3 @@ UNTYPED_SFIELD(sfAcceptedCredentials, ARRAY, 28) UNTYPED_SFIELD(sfPermissions, ARRAY, 29) UNTYPED_SFIELD(sfRawTransactions, ARRAY, 30) UNTYPED_SFIELD(sfBatchSigners, ARRAY, 31, SField::sMD_Default, SField::notSigning) - -// clang-format on diff --git a/include/xrpl/protocol/jss.h b/include/xrpl/protocol/jss.h index 0a877cb96a..c12600fe61 100644 --- a/include/xrpl/protocol/jss.h +++ b/include/xrpl/protocol/jss.h @@ -21,687 +21,660 @@ namespace jss { error: Common properties of RPC error responses. */ -// clang-format off -JSS(AL_size); // out: GetCounts -JSS(AL_hit_rate); // out: GetCounts -JSS(AcceptedCredentials); // out: AccountObjects -JSS(ACCOUNT_SET_FLAGS); // out: RPC server_definitions -JSS(Account); // in: TransactionSign; field. -JSS(AMMID); // field -JSS(Amount); // in: TransactionSign; field. -JSS(Amount2); // in/out: AMM IOU/XRP pool, deposit, withdraw amount -JSS(Asset); // in: AMM Asset1 -JSS(Asset2); // in: AMM Asset2 -JSS(AssetClass); // in: Oracle -JSS(AssetPrice); // in: Oracle -JSS(AuthAccount); // in: AMM Auction Slot -JSS(AuthAccounts); // in: AMM Auction Slot -JSS(BaseAsset); // in: Oracle -JSS(BidMax); // in: AMM Bid -JSS(BidMin); // in: AMM Bid -JSS(ClearFlag); // field. -JSS(Counterparty); // field. -JSS(CounterpartySignature);// field. -JSS(DeliverMax); // out: alias to Amount -JSS(DeliverMin); // in: TransactionSign -JSS(Destination); // in: TransactionSign; field. -JSS(EPrice); // in: AMM Deposit option -JSS(Fee); // in/out: TransactionSign; field. -JSS(Flags); // in/out: TransactionSign; field. -JSS(Holder); // field. -JSS(Invalid); // -JSS(Issuer); // in: Credential transactions -JSS(IssuingChainDoor); // field. -JSS(IssuingChainIssue); // field. -JSS(LastLedgerSequence); // in: TransactionSign; field -JSS(LastUpdateTime); // field. -JSS(LimitAmount); // field. -JSS(LockingChainDoor); // field. -JSS(LockingChainIssue); // field. -JSS(NetworkID); // field. -JSS(LPTokenOut); // in: AMM Liquidity Provider deposit tokens -JSS(LPTokenIn); // in: AMM Liquidity Provider withdraw tokens -JSS(LPToken); // out: AMM Liquidity Provider tokens info -JSS(OfferSequence); // field. -JSS(OracleDocumentID); // field -JSS(Owner); // field -JSS(Paths); // in/out: TransactionSign -JSS(PriceDataSeries); // field. -JSS(PriceData); // field. -JSS(Provider); // field. -JSS(QuoteAsset); // in: Oracle. -JSS(RawTransaction); // in: Batch -JSS(RawTransactions); // in: Batch -JSS(SLE_hit_rate); // out: GetCounts. -JSS(Scale); // field. -JSS(SettleDelay); // in: TransactionSign -JSS(SendMax); // in: TransactionSign -JSS(Sequence); // in/out: TransactionSign; field. -JSS(SetFlag); // field. -JSS(Signer); // field. -JSS(Signers); // field. -JSS(SigningPubKey); // field. -JSS(Subject); // in: Credential transactions -JSS(TakerGets); // field. -JSS(TakerPays); // field. -JSS(TradingFee); // in/out: AMM trading fee -JSS(TransactionType); // in: TransactionSign. -JSS(TransferRate); // in: TransferRate. -JSS(TxnSignature); // field. -JSS(URI); // field. -JSS(VoteSlots); // out: AMM Vote -JSS(aborted); // out: InboundLedger -JSS(accepted); // out: LedgerToJson, OwnerInfo, SubmitTransaction -JSS(accountState); // out: LedgerToJson -JSS(accountTreeHash); // out: ledger/Ledger.cpp -JSS(account_data); // out: AccountInfo -JSS(account_flags); // out: AccountInfo -JSS(account_hash); // out: LedgerToJson -JSS(account_id); // out: WalletPropose -JSS(account_nfts); // out: AccountNFTs -JSS(account_objects); // out: AccountObjects -JSS(account_root); // in: LedgerEntry -JSS(account_sequence_next); // out: SubmitTransaction +JSS(AL_size); // out: GetCounts +JSS(AL_hit_rate); // out: GetCounts +JSS(AcceptedCredentials); // out: AccountObjects +JSS(ACCOUNT_SET_FLAGS); // out: RPC server_definitions +JSS(Account); // in: TransactionSign; field. +JSS(AMMID); // field +JSS(Amount); // in: TransactionSign; field. +JSS(Amount2); // in/out: AMM IOU/XRP pool, deposit, withdraw amount +JSS(Asset); // in: AMM Asset1 +JSS(Asset2); // in: AMM Asset2 +JSS(AssetClass); // in: Oracle +JSS(AssetPrice); // in: Oracle +JSS(AuthAccount); // in: AMM Auction Slot +JSS(AuthAccounts); // in: AMM Auction Slot +JSS(BaseAsset); // in: Oracle +JSS(BidMax); // in: AMM Bid +JSS(BidMin); // in: AMM Bid +JSS(ClearFlag); // field. +JSS(Counterparty); // field. +JSS(CounterpartySignature); // field. +JSS(DeliverMax); // out: alias to Amount +JSS(DeliverMin); // in: TransactionSign +JSS(Destination); // in: TransactionSign; field. +JSS(EPrice); // in: AMM Deposit option +JSS(Fee); // in/out: TransactionSign; field. +JSS(Flags); // in/out: TransactionSign; field. +JSS(Holder); // field. +JSS(Invalid); // +JSS(Issuer); // in: Credential transactions +JSS(IssuingChainDoor); // field. +JSS(IssuingChainIssue); // field. +JSS(LastLedgerSequence); // in: TransactionSign; field +JSS(LastUpdateTime); // field. +JSS(LimitAmount); // field. +JSS(LockingChainDoor); // field. +JSS(LockingChainIssue); // field. +JSS(NetworkID); // field. +JSS(LPTokenOut); // in: AMM Liquidity Provider deposit tokens +JSS(LPTokenIn); // in: AMM Liquidity Provider withdraw tokens +JSS(LPToken); // out: AMM Liquidity Provider tokens info +JSS(OfferSequence); // field. +JSS(OracleDocumentID); // field +JSS(Owner); // field +JSS(Paths); // in/out: TransactionSign +JSS(PriceDataSeries); // field. +JSS(PriceData); // field. +JSS(Provider); // field. +JSS(QuoteAsset); // in: Oracle. +JSS(RawTransaction); // in: Batch +JSS(RawTransactions); // in: Batch +JSS(SLE_hit_rate); // out: GetCounts. +JSS(Scale); // field. +JSS(SettleDelay); // in: TransactionSign +JSS(SendMax); // in: TransactionSign +JSS(Sequence); // in/out: TransactionSign; field. +JSS(SetFlag); // field. +JSS(Signer); // field. +JSS(Signers); // field. +JSS(SigningPubKey); // field. +JSS(Subject); // in: Credential transactions +JSS(TakerGets); // field. +JSS(TakerPays); // field. +JSS(TradingFee); // in/out: AMM trading fee +JSS(TransactionType); // in: TransactionSign. +JSS(TransferRate); // in: TransferRate. +JSS(TxnSignature); // field. +JSS(URI); // field. +JSS(VoteSlots); // out: AMM Vote +JSS(aborted); // out: InboundLedger +JSS(accepted); // out: LedgerToJson, OwnerInfo, SubmitTransaction +JSS(accountState); // out: LedgerToJson +JSS(accountTreeHash); // out: ledger/Ledger.cpp +JSS(account_data); // out: AccountInfo +JSS(account_flags); // out: AccountInfo +JSS(account_hash); // out: LedgerToJson +JSS(account_id); // out: WalletPropose +JSS(account_nfts); // out: AccountNFTs +JSS(account_objects); // out: AccountObjects +JSS(account_root); // in: LedgerEntry +JSS(account_sequence_next); // out: SubmitTransaction JSS(account_sequence_available); // out: SubmitTransaction JSS(account_history_tx_stream); // in: Subscribe, Unsubscribe JSS(account_history_tx_index); // out: Account txn history subscribe - -JSS(account_history_tx_first); // out: Account txn history subscribe -JSS(account_history_boundary); // out: Account txn history subscribe -JSS(accounts); // in: LedgerEntry, Subscribe, - // handlers/Ledger, Unsubscribe -JSS(accounts_proposed); // in: Subscribe, Unsubscribe -JSS(action); -JSS(active); // out: OverlayImpl -JSS(acquiring); // out: LedgerRequest -JSS(address); // out: PeerImp -JSS(affected); // out: AcceptedLedgerTx -JSS(age); // out: NetworkOPs, Peers -JSS(alternatives); // out: PathRequest, RipplePathFind -JSS(amendment_blocked); // out: NetworkOPs -JSS(amm_account); // in: amm_info -JSS(amount); // out: AccountChannels, amm_info -JSS(amount2); // out: amm_info -JSS(api_version); // in: many, out: Version -JSS(api_version_low); // out: Version -JSS(applied); // out: SubmitTransaction -JSS(asks); // out: Subscribe -JSS(asset); // in: amm_info -JSS(asset2); // in: amm_info -JSS(assets); // out: GatewayBalances -JSS(asset_frozen); // out: amm_info -JSS(asset2_frozen); // out: amm_info -JSS(attestations); -JSS(attestation_reward_account); -JSS(auction_slot); // out: amm_info -JSS(authorized); // out: AccountLines -JSS(authorize); // out: delegate -JSS(authorized_credentials); // in: ledger_entry DepositPreauth -JSS(auth_accounts); // out: amm_info -JSS(auth_change); // out: AccountInfo -JSS(auth_change_queued); // out: AccountInfo -JSS(available); // out: ValidatorList -JSS(avg_bps_recv); // out: Peers -JSS(avg_bps_sent); // out: Peers -JSS(balance); // out: AccountLines -JSS(balances); // out: GatewayBalances -JSS(base); // out: LogLevel -JSS(base_asset); // in: get_aggregate_price -JSS(base_fee); // out: NetworkOPs -JSS(base_fee_xrp); // out: NetworkOPs -JSS(bids); // out: Subscribe -JSS(binary); // in: AccountTX, LedgerEntry, - // AccountTxOld, Tx LedgerData -JSS(blob); // out: ValidatorList -JSS(blobs_v2); // out: ValidatorList - // in: UNL -JSS(books); // in: Subscribe, Unsubscribe -JSS(both); // in: Subscribe, Unsubscribe -JSS(both_sides); // in: Subscribe, Unsubscribe -JSS(branch); // out: server_info -JSS(broadcast); // out: SubmitTransaction -JSS(bridge_account); // in: LedgerEntry -JSS(build_path); // in: TransactionSign -JSS(build_version); // out: NetworkOPs -JSS(cancel_after); // out: AccountChannels -JSS(can_delete); // out: CanDelete -JSS(mpt_amount); // out: mpt_holders -JSS(mpt_issuance_id); // in: Payment, mpt_holders -JSS(mptoken_index); // out: mpt_holders -JSS(changes); // out: BookChanges -JSS(channel_id); // out: AccountChannels -JSS(channels); // out: AccountChannels -JSS(check_nodes); // in: LedgerCleaner -JSS(clear); // in/out: FetchInfo -JSS(close); // out: BookChanges -JSS(close_flags); // out: LedgerToJson -JSS(close_time); // in: Application, out: NetworkOPs, - // RCLCxPeerPos, LedgerToJson -JSS(close_time_iso); // out: Tx, NetworkOPs, TransactionEntry - // AccountTx, LedgerToJson -JSS(close_time_estimated); // in: Application, out: LedgerToJson -JSS(close_time_human); // out: LedgerToJson -JSS(close_time_offset); // out: NetworkOPs -JSS(close_time_resolution); // in: Application; out: LedgerToJson -JSS(closed); // out: NetworkOPs, LedgerToJson, - // handlers/Ledger -JSS(closed_ledger); // out: NetworkOPs -JSS(cluster); // out: PeerImp -JSS(code); // out: errors -JSS(command); // in: RPCHandler -JSS(common); // out: RPC server_definitions -JSS(complete); // out: NetworkOPs, InboundLedger -JSS(complete_ledgers); // out: NetworkOPs, PeerImp -JSS(consensus); // out: NetworkOPs, LedgerConsensus -JSS(converge_time); // out: NetworkOPs -JSS(converge_time_s); // out: NetworkOPs -JSS(cookie); // out: NetworkOPs -JSS(count); // in: AccountTx*, ValidatorList -JSS(counters); // in/out: retrieve counters -JSS(credentials); // in: deposit_authorized -JSS(credential_type); // in: LedgerEntry DepositPreauth -JSS(ctid); // in/out: Tx RPC -JSS(currency_a); // out: BookChanges -JSS(currency_b); // out: BookChanges -JSS(currency); // in: paths/PathRequest, STAmount - // out: STPathSet, STAmount, - // AccountLines -JSS(current); // out: OwnerInfo -JSS(current_activities); -JSS(current_ledger_size); // out: TxQ -JSS(current_queue_size); // out: TxQ -JSS(data); // out: LedgerData -JSS(date); // out: tx/Transaction, NetworkOPs -JSS(dbKBLedger); // out: getCounts -JSS(dbKBTotal); // out: getCounts -JSS(dbKBTransaction); // out: getCounts -JSS(debug_signing); // in: TransactionSign -JSS(deletion_blockers_only); // in: AccountObjects -JSS(delivered_amount); // out: insertDeliveredAmount -JSS(deposit_authorized); // out: deposit_authorized -JSS(deprecated); // out -JSS(descending); // in: AccountTx* -JSS(description); // in/out: Reservations -JSS(destination); // in: nft_buy_offers, nft_sell_offers -JSS(destination_account); // in: PathRequest, RipplePathFind, account_lines - // out: AccountChannels -JSS(destination_amount); // in: PathRequest, RipplePathFind -JSS(destination_currencies); // in: PathRequest, RipplePathFind -JSS(destination_tag); // in: PathRequest - // out: AccountChannels -JSS(details); // out: Manifest, server_info -JSS(dir_entry); // out: DirectoryEntryIterator -JSS(dir_index); // out: DirectoryEntryIterator -JSS(dir_root); // out: DirectoryEntryIterator -JSS(discounted_fee); // out: amm_info -JSS(domain); // out: ValidatorInfo, Manifest -JSS(drops); // out: TxQ -JSS(duration_us); // out: NetworkOPs -JSS(effective); // out: ValidatorList - // in: UNL -JSS(enabled); // out: AmendmentTable -JSS(engine_result); // out: NetworkOPs, TransactionSign, Submit -JSS(engine_result_code); // out: NetworkOPs, TransactionSign, Submit -JSS(engine_result_message); // out: NetworkOPs, TransactionSign, Submit -JSS(entire_set); // out: get_aggregate_price -JSS(ephemeral_key); // out: ValidatorInfo - // in/out: Manifest -JSS(error); // out: error -JSS(errored); -JSS(error_code); // out: error -JSS(error_exception); // out: Submit -JSS(error_message); // out: error -JSS(expand); // in: handler/Ledger -JSS(expected_date); // out: any (warnings) -JSS(expected_date_UTC); // out: any (warnings) -JSS(expected_ledger_size); // out: TxQ -JSS(expiration); // out: AccountOffers, AccountChannels, - // ValidatorList, amm_info -JSS(fail_hard); // in: Sign, Submit -JSS(failed); // out: InboundLedger -JSS(feature); // in: Feature -JSS(features); // out: Feature -JSS(fee_base); // out: NetworkOPs -JSS(fee_div_max); // in: TransactionSign -JSS(fee_level); // out: AccountInfo -JSS(fee_mult_max); // in: TransactionSign -JSS(fee_ref); // out: NetworkOPs, DEPRECATED -JSS(fetch_pack); // out: NetworkOPs -JSS(FIELDS); // out: RPC server_definitions - // matches definitions.json format -JSS(first); // out: rpc/Version -JSS(finished); -JSS(fix_txns); // in: LedgerCleaner -JSS(flags); // out: AccountOffers, - // NetworkOPs -JSS(forward); // in: AccountTx -JSS(freeze); // out: AccountLines -JSS(freeze_peer); // out: AccountLines -JSS(deep_freeze); // out: AccountLines -JSS(deep_freeze_peer); // out: AccountLines -JSS(frozen_balances); // out: GatewayBalances -JSS(full); // in: LedgerClearer, handlers/Ledger -JSS(full_reply); // out: PathFind -JSS(fullbelow_size); // out: GetCounts -JSS(git); // out: server_info -JSS(good); // out: RPCVersion -JSS(hash); // out: NetworkOPs, InboundLedger, - // LedgerToJson, STTx; field -JSS(have_header); // out: InboundLedger -JSS(have_state); // out: InboundLedger -JSS(have_transactions); // out: InboundLedger -JSS(high); // out: BookChanges -JSS(highest_sequence); // out: AccountInfo -JSS(highest_ticket); // out: AccountInfo -JSS(historical_perminute); // historical_perminute. -JSS(holders); // out: MPTHolders -JSS(hostid); // out: NetworkOPs -JSS(hotwallet); // in: GatewayBalances -JSS(id); // websocket. -JSS(ident); // in: AccountCurrencies, AccountInfo, - // OwnerInfo -JSS(ignore_default); // in: AccountLines -JSS(in); // out: OverlayImpl -JSS(inLedger); // out: tx/Transaction -JSS(inbound); // out: PeerImp -JSS(index); // in: LedgerEntry - // out: STLedgerEntry, - // LedgerEntry, TxHistory, LedgerData -JSS(info); // out: ServerInfo, ConsensusInfo, FetchInfo -JSS(initial_sync_duration_us); -JSS(internal_command); // in: Internal -JSS(invalid_API_version); // out: Many, when a request has an invalid - // version -JSS(io_latency_ms); // out: NetworkOPs -JSS(ip); // in: Connect, out: OverlayImpl -JSS(is_burned); // out: nft_info (clio) -JSS(isSerialized); // out: RPC server_definitions - // matches definitions.json format -JSS(isSigningField); // out: RPC server_definitions - // matches definitions.json format -JSS(isVLEncoded); // out: RPC server_definitions - // matches definitions.json format -JSS(issuer); // in: RipplePathFind, Subscribe, - // Unsubscribe, BookOffers - // out: STPathSet, STAmount -JSS(job); -JSS(job_queue); -JSS(jobs); -JSS(jsonrpc); // json version -JSS(jq_trans_overflow); // JobQueue transaction limit overflow. -JSS(kept); // out: SubmitTransaction -JSS(key); // out -JSS(key_type); // in/out: WalletPropose, TransactionSign -JSS(latency); // out: PeerImp -JSS(last); // out: RPCVersion -JSS(last_close); // out: NetworkOPs -JSS(last_refresh_time); // out: ValidatorSite -JSS(last_refresh_status); // out: ValidatorSite -JSS(last_refresh_message); // out: ValidatorSite -JSS(ledger); // in: NetworkOPs, LedgerCleaner, - // RPCHelpers - // out: NetworkOPs, PeerImp -JSS(ledger_current_index); // out: NetworkOPs, RPCHelpers, - // LedgerCurrent, LedgerAccept, - // AccountLines -JSS(ledger_data); // out: LedgerHeader -JSS(ledger_hash); // in: RPCHelpers, LedgerRequest, - // RipplePathFind, TransactionEntry, - // handlers/Ledger - // out: NetworkOPs, RPCHelpers, - // LedgerClosed, LedgerData, - // AccountLines -JSS(ledger_hit_rate); // out: GetCounts -JSS(ledger_index); // in/out: many -JSS(ledger_index_max); // in, out: AccountTx* -JSS(ledger_index_min); // in, out: AccountTx* -JSS(ledger_max); // in, out: AccountTx* -JSS(ledger_min); // in, out: AccountTx* -JSS(ledger_time); // out: NetworkOPs -JSS(LEDGER_ENTRY_TYPES); // out: RPC server_definitions - // matches definitions.json format -JSS(LEDGER_ENTRY_FLAGS); // out: RPC server_definitions -JSS(LEDGER_ENTRY_FORMATS); // out: RPC server_definitions -JSS(levels); // LogLevels -JSS(limit); // in/out: AccountTx*, AccountOffers, - // AccountLines, AccountObjects - // in: LedgerData, BookOffers -JSS(limit_peer); // out: AccountLines -JSS(lines); // out: AccountLines -JSS(list); // out: ValidatorList -JSS(load); // out: NetworkOPs, PeerImp -JSS(load_base); // out: NetworkOPs -JSS(load_factor); // out: NetworkOPs -JSS(load_factor_cluster); // out: NetworkOPs -JSS(load_factor_fee_escalation); // out: NetworkOPs -JSS(load_factor_fee_queue); // out: NetworkOPs -JSS(load_factor_fee_reference); // out: NetworkOPs -JSS(load_factor_local); // out: NetworkOPs -JSS(load_factor_net); // out: NetworkOPs -JSS(load_factor_server); // out: NetworkOPs -JSS(load_fee); // out: LoadFeeTrackImp, NetworkOPs -JSS(loan_broker_id); // in: LedgerEntry -JSS(loan_seq); // in: LedgerEntry -JSS(local); // out: resource/Logic.h -JSS(local_txs); // out: GetCounts -JSS(local_static_keys); // out: ValidatorList -JSS(locked); // out: GatewayBalances -JSS(low); // out: BookChanges -JSS(lowest_sequence); // out: AccountInfo -JSS(lowest_ticket); // out: AccountInfo -JSS(lp_token); // out: amm_info -JSS(majority); // out: RPC feature -JSS(manifest); // out: ValidatorInfo, Manifest -JSS(marker); // in/out: AccountTx, AccountOffers, - // AccountLines, AccountObjects, - // LedgerData - // in: BookOffers -JSS(master_key); // out: WalletPropose, NetworkOPs, - // ValidatorInfo - // in/out: Manifest -JSS(master_seed); // out: WalletPropose -JSS(master_seed_hex); // out: WalletPropose -JSS(master_signature); // out: pubManifest -JSS(max_ledger); // in/out: LedgerCleaner -JSS(max_queue_size); // out: TxQ -JSS(max_spend_drops); // out: AccountInfo -JSS(max_spend_drops_total); // out: AccountInfo -JSS(mean); // out: get_aggregate_price -JSS(median); // out: get_aggregate_price -JSS(median_fee); // out: TxQ -JSS(median_level); // out: TxQ -JSS(message); // error. -JSS(meta); // out: NetworkOPs, AccountTx*, Tx -JSS(meta_blob); // out: NetworkOPs, AccountTx*, Tx -JSS(metaData); -JSS(metadata); // out: TransactionEntry -JSS(method); // RPC -JSS(methods); -JSS(metrics); // out: Peers -JSS(min_count); // in: GetCounts -JSS(min_ledger); // in: LedgerCleaner -JSS(minimum_fee); // out: TxQ -JSS(minimum_level); // out: TxQ -JSS(missingCommand); // error -JSS(name); // out: AmendmentTableImpl, PeerImp -JSS(needed_state_hashes); // out: InboundLedger -JSS(needed_transaction_hashes); // out: InboundLedger -JSS(network_id); // out: NetworkOPs -JSS(network_ledger); // out: NetworkOPs -JSS(next_refresh_time); // out: ValidatorSite -JSS(nft_id); // in: nft_sell_offers, nft_buy_offers -JSS(nft_offer_index); // out nft_buy_offers, nft_sell_offers -JSS(nft_serial); // out: account_nfts -JSS(nft_taxon); // out: nft_info (clio) -JSS(nftoken_id); // out: insertNFTokenID -JSS(nftoken_ids); // out: insertNFTokenID -JSS(no_ripple); // out: AccountLines -JSS(no_ripple_peer); // out: AccountLines -JSS(node); // out: LedgerEntry -JSS(node_binary); // out: LedgerEntry -JSS(node_read_bytes); // out: GetCounts -JSS(node_read_errors); // out: GetCounts -JSS(node_read_retries); // out: GetCounts -JSS(node_reads_hit); // out: GetCounts -JSS(node_reads_total); // out: GetCounts -JSS(node_reads_duration_us); // out: GetCounts -JSS(node_size); // out: server_info -JSS(nodes); // out: VaultInfo -JSS(nodestore); // out: GetCounts -JSS(node_writes); // out: GetCounts -JSS(node_written_bytes); // out: GetCounts -JSS(node_writes_duration_us); // out: GetCounts -JSS(node_write_retries); // out: GetCounts -JSS(node_writes_delayed); // out::GetCounts -JSS(nth); // out: RPC server_definitions -JSS(obligations); // out: GatewayBalances -JSS(offers); // out: NetworkOPs, AccountOffers, Subscribe -JSS(offer_id); // out: insertNFTokenOfferID -JSS(offline); // in: TransactionSign -JSS(offset); // in/out: AccountTxOld -JSS(open); // out: handlers/Ledger -JSS(open_ledger_cost); // out: SubmitTransaction -JSS(open_ledger_fee); // out: TxQ -JSS(open_ledger_level); // out: TxQ -JSS(optionality); // out: server_definitions -JSS(oracles); // in: get_aggregate_price -JSS(oracle_document_id); // in: get_aggregate_price -JSS(out); // out: OverlayImpl -JSS(owner); // in: LedgerEntry, out: NetworkOPs -JSS(owner_funds); // in/out: Ledger, NetworkOPs, AcceptedLedgerTx -JSS(page_index); -JSS(params); // RPC -JSS(parent_close_time); // out: LedgerToJson -JSS(parent_hash); // out: LedgerToJson -JSS(partition); // in: LogLevel -JSS(passphrase); // in: WalletPropose -JSS(password); // in: Subscribe -JSS(paths); // in: RipplePathFind -JSS(paths_canonical); // out: RipplePathFind -JSS(paths_computed); // out: PathRequest, RipplePathFind -JSS(peer); // in: AccountLines -JSS(peer_authorized); // out: AccountLines -JSS(peer_id); // out: RCLCxPeerPos -JSS(peers); // out: InboundLedger, handlers/Peers, Overlay -JSS(peer_disconnects); // Severed peer connection counter. -JSS(peer_disconnects_resources); // Severed peer connections because of - // excess resource consumption. -JSS(port); // in: Connect, out: NetworkOPs -JSS(ports); // out: NetworkOPs -JSS(previous); // out: Reservations -JSS(previous_ledger); // out: LedgerPropose -JSS(price); // out: amm_info, AuctionSlot -JSS(proof); // in: BookOffers -JSS(propose_seq); // out: LedgerPropose -JSS(proposers); // out: NetworkOPs, LedgerConsensus -JSS(protocol); // out: NetworkOPs, PeerImp -JSS(proxied); // out: RPC ping -JSS(pseudo_account); // out: AccountInfo -JSS(pubkey_node); // out: NetworkOPs -JSS(pubkey_publisher); // out: ValidatorList -JSS(pubkey_validator); // out: NetworkOPs, ValidatorList -JSS(public_key); // out: OverlayImpl, PeerImp, WalletPropose, - // ValidatorInfo - // in/out: Manifest -JSS(public_key_hex); // out: WalletPropose -JSS(published_ledger); // out: NetworkOPs -JSS(publisher_lists); // out: ValidatorList -JSS(quality); // out: NetworkOPs -JSS(quality_in); // out: AccountLines -JSS(quality_out); // out: AccountLines -JSS(queue); // in: AccountInfo -JSS(queue_data); // out: AccountInfo -JSS(queued); // out: SubmitTransaction -JSS(queued_duration_us); -JSS(quote_asset); // in: get_aggregate_price -JSS(random); // out: Random -JSS(raw_meta); // out: AcceptedLedgerTx -JSS(receive_currencies); // out: AccountCurrencies -JSS(reference_level); // out: TxQ -JSS(refresh_interval); // in: UNL -JSS(refresh_interval_min); // out: ValidatorSites -JSS(regular_seed); // in/out: LedgerEntry -JSS(remaining); // out: ValidatorList -JSS(remote); // out: Logic.h -JSS(request); // RPC -JSS(requested); // out: Manifest -JSS(reservations); // out: Reservations -JSS(reserve_base); // out: NetworkOPs -JSS(reserve_base_xrp); // out: NetworkOPs -JSS(reserve_inc); // out: NetworkOPs -JSS(reserve_inc_xrp); // out: NetworkOPs -JSS(response); // websocket -JSS(result); // RPC -JSS(ripple_lines); // out: NetworkOPs -JSS(ripple_state); // in: LedgerEntr -JSS(ripplerpc); // ripple RPC version -JSS(role); // out: Ping.cpp -JSS(rpc); -JSS(rt_accounts); // in: Subscribe, Unsubscribe -JSS(running_duration_us); -JSS(search_depth); // in: RipplePathFind -JSS(searched_all); // out: Tx -JSS(secret); // in: TransactionSign, - // ValidationCreate, ValidationSeed, - // channel_authorize -JSS(seed); // -JSS(seed_hex); // in: WalletPropose, TransactionSign -JSS(send_currencies); // out: AccountCurrencies -JSS(send_max); // in: PathRequest, RipplePathFind -JSS(seq); // in: LedgerEntry; - // out: NetworkOPs, RPCSub, AccountOffers, - // ValidatorList, ValidatorInfo, Manifest -JSS(sequence); // in: UNL -JSS(sequence_count); // out: AccountInfo -JSS(server_domain); // out: NetworkOPs -JSS(server_state); // out: NetworkOPs -JSS(server_state_duration_us);// out: NetworkOPs -JSS(server_status); // out: NetworkOPs -JSS(server_version); // out: NetworkOPs -JSS(settle_delay); // out: AccountChannels -JSS(severity); // in: LogLevel -JSS(shares); // out: VaultInfo -JSS(signature); // out: NetworkOPs, ChannelAuthorize -JSS(signature_target); // in: TransactionSign -JSS(signature_verified); // out: ChannelVerify -JSS(signing_key); // out: NetworkOPs -JSS(signing_keys); // out: ValidatorList -JSS(signing_time); // out: NetworkOPs -JSS(signer_lists); // in/out: AccountInfo -JSS(size); // out: get_aggregate_price -JSS(snapshot); // in: Subscribe -JSS(source_account); // in: PathRequest, RipplePathFind -JSS(source_amount); // in: PathRequest, RipplePathFind -JSS(source_currencies); // in: PathRequest, RipplePathFind -JSS(source_tag); // out: AccountChannels -JSS(stand_alone); // out: NetworkOPs -JSS(standard_deviation); // out: get_aggregate_price -JSS(start); // in: TxHistory -JSS(started); -JSS(state_accounting); // out: NetworkOPs -JSS(state_now); // in: Subscribe -JSS(status); // error -JSS(stop); // in: LedgerCleaner -JSS(stop_history_tx_only); // in: Unsubscribe, stop history tx stream -JSS(streams); // in: Subscribe, Unsubscribe -JSS(strict); // in: AccountCurrencies, AccountInfo -JSS(sub_index); // in: LedgerEntry -JSS(subcommand); // in: PathFind -JSS(subject); // in: LedgerEntry Credential -JSS(success); // rpc -JSS(supported); // out: AmendmentTableImpl -JSS(sync_mode); // in: Submit -JSS(system_time_offset); // out: NetworkOPs -JSS(tag); // out: Peers -JSS(taker); // in: Subscribe, BookOffers -JSS(taker_gets); // in: Subscribe, Unsubscribe, BookOffers -JSS(taker_gets_funded); // out: NetworkOPs -JSS(taker_pays); // in: Subscribe, Unsubscribe, BookOffers -JSS(taker_pays_funded); // out: NetworkOPs -JSS(threshold); // in: Blacklist -JSS(ticket_count); // out: AccountInfo -JSS(ticket_seq); // in: LedgerEntry -JSS(time); -JSS(timeouts); // out: InboundLedger -JSS(time_threshold); // in/out: Oracle aggregate -JSS(time_interval); // out: AMM Auction Slot -JSS(track); // out: PeerImp -JSS(traffic); // out: Overlay -JSS(trim); // in: get_aggregate_price -JSS(trimmed_set); // out: get_aggregate_price -JSS(total); // out: counters -JSS(total_bytes_recv); // out: Peers -JSS(total_bytes_sent); // out: Peers -JSS(total_coins); // out: LedgerToJson -JSS(trading_fee); // out: amm_info -JSS(transTreeHash); // out: ledger/Ledger.cpp -JSS(transaction); // in: Tx - // out: NetworkOPs, AcceptedLedgerTx, -JSS(transaction_hash); // out: RCLCxPeerPos, LedgerToJson -JSS(transactions); // out: LedgerToJson, - // in: AccountTx*, Unsubscribe -JSS(TRANSACTION_RESULTS); // out: RPC server_definitions - // matches definitions.json format -JSS(TRANSACTION_TYPES); // out: RPC server_definitions - // matches definitions.json format -JSS(TRANSACTION_FLAGS); // out: RPC server_definitions -JSS(TRANSACTION_FORMATS); // out: RPC server_definitions -JSS(TYPES); // out: RPC server_definitions - // matches definitions.json format -JSS(transfer_rate); // out: nft_info (clio) -JSS(transitions); // out: NetworkOPs -JSS(treenode_cache_size); // out: GetCounts -JSS(treenode_track_size); // out: GetCounts -JSS(trusted); // out: UnlList -JSS(trusted_validator_keys); // out: ValidatorList -JSS(tx); // out: STTx, AccountTx* -JSS(tx_blob); // in/out: Submit, - // in: TransactionSign, AccountTx* -JSS(tx_hash); // in: TransactionEntry -JSS(tx_json); // in/out: TransactionSign - // out: TransactionEntry -JSS(tx_signing_hash); // out: TransactionSign -JSS(tx_unsigned); // out: TransactionSign -JSS(txn_count); // out: NetworkOPs -JSS(txr_tx_cnt); // out: protocol message tx's count -JSS(txr_tx_sz); // out: protocol message tx's size -JSS(txr_have_txs_cnt); // out: protocol message have tx count -JSS(txr_have_txs_sz); // out: protocol message have tx size -JSS(txr_get_ledger_cnt); // out: protocol message get ledger count -JSS(txr_get_ledger_sz); // out: protocol message get ledger size -JSS(txr_ledger_data_cnt); // out: protocol message ledger data count -JSS(txr_ledger_data_sz); // out: protocol message ledger data size -JSS(txr_transactions_cnt); // out: protocol message get object count -JSS(txr_transactions_sz); // out: protocol message get object size -JSS(txr_selected_cnt); // out: selected peers count -JSS(txr_suppressed_cnt); // out: suppressed peers count -JSS(txr_not_enabled_cnt); // out: peers with tx reduce-relay disabled count -JSS(txr_missing_tx_freq); // out: missing tx frequency average -JSS(txs); // out: TxHistory -JSS(type); // in: AccountObjects - // out: NetworkOPs, RPC server_definitions - // OverlayImpl, Logic -JSS(type_hex); // out: STPathSet -JSS(unl); // out: UnlList -JSS(unlimited); // out: Connection.h -JSS(uptime); // out: GetCounts -JSS(uri); // out: ValidatorSites -JSS(url); // in/out: Subscribe, Unsubscribe -JSS(url_password); // in: Subscribe -JSS(url_username); // in: Subscribe -JSS(urlgravatar); // -JSS(username); // in: Subscribe -JSS(validated); // out: NetworkOPs, RPCHelpers, AccountTx* - // Tx -JSS(validator_list_expires); // out: NetworkOps, ValidatorList -JSS(validator_list); // out: NetworkOps, ValidatorList -JSS(validators); -JSS(validated_hash); // out: NetworkOPs -JSS(validated_ledger); // out: NetworkOPs -JSS(validated_ledger_index); // out: SubmitTransaction -JSS(validated_ledgers); // out: NetworkOPs -JSS(validation_key); // out: ValidationCreate, ValidationSeed -JSS(validation_private_key); // out: ValidationCreate -JSS(validation_public_key); // out: ValidationCreate, ValidationSeed -JSS(validation_quorum); // out: NetworkOPs -JSS(validation_seed); // out: ValidationCreate, ValidationSeed -JSS(validations); // out: AmendmentTableImpl -JSS(validator_list_threshold); // out: ValidatorList -JSS(validator_sites); // out: ValidatorSites -JSS(value); // out: STAmount -JSS(vault_id); // in: VaultInfo -JSS(version); // out: RPCVersion -JSS(vetoed); // out: AmendmentTableImpl -JSS(volume_a); // out: BookChanges -JSS(volume_b); // out: BookChanges -JSS(vote); // in: Feature -JSS(vote_slots); // out: amm_info -JSS(vote_weight); // out: amm_info -JSS(warning); // rpc: -JSS(warnings); // out: server_info, server_state -JSS(workers); -JSS(write_load); // out: GetCounts -// clang-format on +JSS(account_history_tx_first); // out: Account txn history subscribe +JSS(account_history_boundary); // out: Account txn history subscribe +JSS(accounts); // in: LedgerEntry, Subscribe, handlers/Ledger, Unsubscribe +JSS(accounts_proposed); // in: Subscribe, Unsubscribe +JSS(action); // +JSS(active); // out: OverlayImpl +JSS(acquiring); // out: LedgerRequest +JSS(address); // out: PeerImp +JSS(affected); // out: AcceptedLedgerTx +JSS(age); // out: NetworkOPs, Peers +JSS(alternatives); // out: PathRequest, RipplePathFind +JSS(amendment_blocked); // out: NetworkOPs +JSS(amm_account); // in: amm_info +JSS(amount); // out: AccountChannels, amm_info +JSS(amount2); // out: amm_info +JSS(api_version); // in: many, out: Version +JSS(api_version_low); // out: Version +JSS(applied); // out: SubmitTransaction +JSS(asks); // out: Subscribe +JSS(asset); // in: amm_info +JSS(asset2); // in: amm_info +JSS(assets); // out: GatewayBalances +JSS(asset_frozen); // out: amm_info +JSS(asset2_frozen); // out: amm_info +JSS(attestations); // +JSS(attestation_reward_account); // +JSS(auction_slot); // out: amm_info +JSS(authorized); // out: AccountLines +JSS(authorize); // out: delegate +JSS(authorized_credentials); // in: ledger_entry DepositPreauth +JSS(auth_accounts); // out: amm_info +JSS(auth_change); // out: AccountInfo +JSS(auth_change_queued); // out: AccountInfo +JSS(available); // out: ValidatorList +JSS(avg_bps_recv); // out: Peers +JSS(avg_bps_sent); // out: Peers +JSS(balance); // out: AccountLines +JSS(balances); // out: GatewayBalances +JSS(base); // out: LogLevel +JSS(base_asset); // in: get_aggregate_price +JSS(base_fee); // out: NetworkOPs +JSS(base_fee_xrp); // out: NetworkOPs +JSS(bids); // out: Subscribe +JSS(binary); // in: AccountTX, LedgerEntry, AccountTxOld, Tx LedgerData +JSS(blob); // out: ValidatorList +JSS(blobs_v2); // out: ValidatorList + // in: UNL +JSS(books); // in: Subscribe, Unsubscribe +JSS(both); // in: Subscribe, Unsubscribe +JSS(both_sides); // in: Subscribe, Unsubscribe +JSS(branch); // out: server_info +JSS(broadcast); // out: SubmitTransaction +JSS(bridge_account); // in: LedgerEntry +JSS(build_path); // in: TransactionSign +JSS(build_version); // out: NetworkOPs +JSS(cancel_after); // out: AccountChannels +JSS(can_delete); // out: CanDelete +JSS(mpt_amount); // out: mpt_holders +JSS(mpt_issuance_id); // in: Payment, mpt_holders +JSS(mptoken_index); // out: mpt_holders +JSS(changes); // out: BookChanges +JSS(channel_id); // out: AccountChannels +JSS(channels); // out: AccountChannels +JSS(check_nodes); // in: LedgerCleaner +JSS(clear); // in/out: FetchInfo +JSS(close); // out: BookChanges +JSS(close_flags); // out: LedgerToJson +JSS(close_time); // in: Application, out: NetworkOPs, RCLCxPeerPos, LedgerToJson +JSS(close_time_iso); // out: Tx, NetworkOPs, TransactionEntry AccountTx, LedgerToJson +JSS(close_time_estimated); // in: Application, out: LedgerToJson +JSS(close_time_human); // out: LedgerToJson +JSS(close_time_offset); // out: NetworkOPs +JSS(close_time_resolution); // in: Application; out: LedgerToJson +JSS(closed); // out: NetworkOPs, LedgerToJson, handlers/Ledger +JSS(closed_ledger); // out: NetworkOPs +JSS(cluster); // out: PeerImp +JSS(code); // out: errors +JSS(command); // in: RPCHandler +JSS(common); // out: RPC server_definitions +JSS(complete); // out: NetworkOPs, InboundLedger +JSS(complete_ledgers); // out: NetworkOPs, PeerImp +JSS(consensus); // out: NetworkOPs, LedgerConsensus +JSS(converge_time); // out: NetworkOPs +JSS(converge_time_s); // out: NetworkOPs +JSS(cookie); // out: NetworkOPs +JSS(count); // in: AccountTx*, ValidatorList +JSS(counters); // in/out: retrieve counters +JSS(credentials); // in: deposit_authorized +JSS(credential_type); // in: LedgerEntry DepositPreauth +JSS(ctid); // in/out: Tx RPC +JSS(currency_a); // out: BookChanges +JSS(currency_b); // out: BookChanges +JSS(currency); // in: paths/PathRequest, STAmount + // out: STPathSet, STAmount, AccountLines +JSS(current); // out: OwnerInfo +JSS(current_activities); // +JSS(current_ledger_size); // out: TxQ +JSS(current_queue_size); // out: TxQ +JSS(data); // out: LedgerData +JSS(date); // out: tx/Transaction, NetworkOPs +JSS(dbKBLedger); // out: getCounts +JSS(dbKBTotal); // out: getCounts +JSS(dbKBTransaction); // out: getCounts +JSS(debug_signing); // in: TransactionSign +JSS(deletion_blockers_only); // in: AccountObjects +JSS(delivered_amount); // out: insertDeliveredAmount +JSS(deposit_authorized); // out: deposit_authorized +JSS(deprecated); // +JSS(descending); // in: AccountTx* +JSS(description); // in/out: Reservations +JSS(destination); // in: nft_buy_offers, nft_sell_offers +JSS(destination_account); // in: PathRequest, RipplePathFind, account_lines + // out: AccountChannels +JSS(destination_amount); // in: PathRequest, RipplePathFind +JSS(destination_currencies); // in: PathRequest, RipplePathFind +JSS(destination_tag); // in: PathRequest + // out: AccountChannels +JSS(details); // out: Manifest, server_info +JSS(dir_entry); // out: DirectoryEntryIterator +JSS(dir_index); // out: DirectoryEntryIterator +JSS(dir_root); // out: DirectoryEntryIterator +JSS(discounted_fee); // out: amm_info +JSS(domain); // out: ValidatorInfo, Manifest +JSS(drops); // out: TxQ +JSS(duration_us); // out: NetworkOPs +JSS(effective); // out: ValidatorList + // in: UNL +JSS(enabled); // out: AmendmentTable +JSS(engine_result); // out: NetworkOPs, TransactionSign, Submit +JSS(engine_result_code); // out: NetworkOPs, TransactionSign, Submit +JSS(engine_result_message); // out: NetworkOPs, TransactionSign, Submit +JSS(entire_set); // out: get_aggregate_price +JSS(ephemeral_key); // out: ValidatorInfo + // in/out: Manifest +JSS(error); // out: error +JSS(errored); // +JSS(error_code); // out: error +JSS(error_exception); // out: Submit +JSS(error_message); // out: error +JSS(expand); // in: handler/Ledger +JSS(expected_date); // out: any (warnings) +JSS(expected_date_UTC); // out: any (warnings) +JSS(expected_ledger_size); // out: TxQ +JSS(expiration); // out: AccountOffers, AccountChannels, ValidatorList, amm_info +JSS(fail_hard); // in: Sign, Submit +JSS(failed); // out: InboundLedger +JSS(feature); // in: Feature +JSS(features); // out: Feature +JSS(fee_base); // out: NetworkOPs +JSS(fee_div_max); // in: TransactionSign +JSS(fee_level); // out: AccountInfo +JSS(fee_mult_max); // in: TransactionSign +JSS(fee_ref); // out: NetworkOPs, DEPRECATED +JSS(fetch_pack); // out: NetworkOPs +JSS(FIELDS); // out: RPC server_definitions + // matches definitions.json format +JSS(first); // out: rpc/Version +JSS(finished); // +JSS(fix_txns); // in: LedgerCleaner +JSS(flags); // out: AccountOffers, NetworkOPs +JSS(forward); // in: AccountTx +JSS(freeze); // out: AccountLines +JSS(freeze_peer); // out: AccountLines +JSS(deep_freeze); // out: AccountLines +JSS(deep_freeze_peer); // out: AccountLines +JSS(frozen_balances); // out: GatewayBalances +JSS(full); // in: LedgerClearer, handlers/Ledger +JSS(full_reply); // out: PathFind +JSS(fullbelow_size); // out: GetCounts +JSS(git); // out: server_info +JSS(good); // out: RPCVersion +JSS(hash); // out: NetworkOPs, InboundLedger, LedgerToJson, STTx; field +JSS(have_header); // out: InboundLedger +JSS(have_state); // out: InboundLedger +JSS(have_transactions); // out: InboundLedger +JSS(high); // out: BookChanges +JSS(highest_sequence); // out: AccountInfo +JSS(highest_ticket); // out: AccountInfo +JSS(historical_perminute); // historical_perminute. +JSS(holders); // out: MPTHolders +JSS(hostid); // out: NetworkOPs +JSS(hotwallet); // in: GatewayBalances +JSS(id); // websocket. +JSS(ident); // in: AccountCurrencies, AccountInfo, OwnerInfo +JSS(ignore_default); // in: AccountLines +JSS(in); // out: OverlayImpl +JSS(inLedger); // out: tx/Transaction +JSS(inbound); // out: PeerImp +JSS(index); // in: LedgerEntry + // out: STLedgerEntry, LedgerEntry, TxHistory, LedgerData +JSS(info); // out: ServerInfo, ConsensusInfo, FetchInfo +JSS(initial_sync_duration_us); // +JSS(internal_command); // in: Internal +JSS(invalid_API_version); // out: Many, when a request has an invalid version +JSS(io_latency_ms); // out: NetworkOPs +JSS(ip); // in: Connect, out: OverlayImpl +JSS(is_burned); // out: nft_info (clio) +JSS(isSerialized); // out: RPC server_definitions + // matches definitions.json format +JSS(isSigningField); // out: RPC server_definitions + // matches definitions.json format +JSS(isVLEncoded); // out: RPC server_definitions + // matches definitions.json format +JSS(issuer); // in: RipplePathFind, Subscribe, Unsubscribe, BookOffers + // out: STPathSet, STAmount +JSS(job); // +JSS(job_queue); // +JSS(jobs); // +JSS(jsonrpc); // json version +JSS(jq_trans_overflow); // JobQueue transaction limit overflow. +JSS(kept); // out: SubmitTransaction +JSS(key); // out +JSS(key_type); // in/out: WalletPropose, TransactionSign +JSS(latency); // out: PeerImp +JSS(last); // out: RPCVersion +JSS(last_close); // out: NetworkOPs +JSS(last_refresh_time); // out: ValidatorSite +JSS(last_refresh_status); // out: ValidatorSite +JSS(last_refresh_message); // out: ValidatorSite +JSS(ledger); // in: NetworkOPs, LedgerCleaner, RPCHelpers + // out: NetworkOPs, PeerImp +JSS(ledger_current_index); // out: NetworkOPs, RPCHelpers, LedgerCurrent, LedgerAccept, + // AccountLines +JSS(ledger_data); // out: LedgerHeader +JSS(ledger_hash); // in: RPCHelpers, LedgerRequest, RipplePathFind, + // TransactionEntry, handlers/Ledger + // out: NetworkOPs, RPCHelpers, LedgerClosed, LedgerData, + // AccountLines +JSS(ledger_hit_rate); // out: GetCounts +JSS(ledger_index); // in/out: many +JSS(ledger_index_max); // in, out: AccountTx* +JSS(ledger_index_min); // in, out: AccountTx* +JSS(ledger_max); // in, out: AccountTx* +JSS(ledger_min); // in, out: AccountTx* +JSS(ledger_time); // out: NetworkOPs +JSS(LEDGER_ENTRY_TYPES); // out: RPC server_definitions + // matches definitions.json format +JSS(LEDGER_ENTRY_FLAGS); // out: RPC server_definitions +JSS(LEDGER_ENTRY_FORMATS); // out: RPC server_definitions +JSS(levels); // LogLevels +JSS(limit); // in/out: AccountTx*, AccountOffers, AccountLines, AccountObjects + // in: LedgerData, BookOffers +JSS(limit_peer); // out: AccountLines +JSS(lines); // out: AccountLines +JSS(list); // out: ValidatorList +JSS(load); // out: NetworkOPs, PeerImp +JSS(load_base); // out: NetworkOPs +JSS(load_factor); // out: NetworkOPs +JSS(load_factor_cluster); // out: NetworkOPs +JSS(load_factor_fee_escalation); // out: NetworkOPs +JSS(load_factor_fee_queue); // out: NetworkOPs +JSS(load_factor_fee_reference); // out: NetworkOPs +JSS(load_factor_local); // out: NetworkOPs +JSS(load_factor_net); // out: NetworkOPs +JSS(load_factor_server); // out: NetworkOPs +JSS(load_fee); // out: LoadFeeTrackImp, NetworkOPs +JSS(loan_broker_id); // in: LedgerEntry +JSS(loan_seq); // in: LedgerEntry +JSS(local); // out: resource/Logic.h +JSS(local_txs); // out: GetCounts +JSS(local_static_keys); // out: ValidatorList +JSS(locked); // out: GatewayBalances +JSS(low); // out: BookChanges +JSS(lowest_sequence); // out: AccountInfo +JSS(lowest_ticket); // out: AccountInfo +JSS(lp_token); // out: amm_info +JSS(majority); // out: RPC feature +JSS(manifest); // out: ValidatorInfo, Manifest +JSS(marker); // in/out: AccountTx, AccountOffers, AccountLines, AccountObjects, + // LedgerData + // in: BookOffers +JSS(master_key); // out: WalletPropose, NetworkOPs, ValidatorInfo + // in/out: Manifest +JSS(master_seed); // out: WalletPropose +JSS(master_seed_hex); // out: WalletPropose +JSS(master_signature); // out: pubManifest +JSS(max_ledger); // in/out: LedgerCleaner +JSS(max_queue_size); // out: TxQ +JSS(max_spend_drops); // out: AccountInfo +JSS(max_spend_drops_total); // out: AccountInfo +JSS(mean); // out: get_aggregate_price +JSS(median); // out: get_aggregate_price +JSS(median_fee); // out: TxQ +JSS(median_level); // out: TxQ +JSS(message); // error. +JSS(meta); // out: NetworkOPs, AccountTx*, Tx +JSS(meta_blob); // out: NetworkOPs, AccountTx*, Tx +JSS(metaData); // +JSS(metadata); // out: TransactionEntry +JSS(method); // RPC +JSS(methods); // +JSS(metrics); // out: Peers +JSS(min_count); // in: GetCounts +JSS(min_ledger); // in: LedgerCleaner +JSS(minimum_fee); // out: TxQ +JSS(minimum_level); // out: TxQ +JSS(missingCommand); // error +JSS(name); // out: AmendmentTableImpl, PeerImp +JSS(needed_state_hashes); // out: InboundLedger +JSS(needed_transaction_hashes); // out: InboundLedger +JSS(network_id); // out: NetworkOPs +JSS(network_ledger); // out: NetworkOPs +JSS(next_refresh_time); // out: ValidatorSite +JSS(nft_id); // in: nft_sell_offers, nft_buy_offers +JSS(nft_offer_index); // out nft_buy_offers, nft_sell_offers +JSS(nft_serial); // out: account_nfts +JSS(nft_taxon); // out: nft_info (clio) +JSS(nftoken_id); // out: insertNFTokenID +JSS(nftoken_ids); // out: insertNFTokenID +JSS(no_ripple); // out: AccountLines +JSS(no_ripple_peer); // out: AccountLines +JSS(node); // out: LedgerEntry +JSS(node_binary); // out: LedgerEntry +JSS(node_read_bytes); // out: GetCounts +JSS(node_read_errors); // out: GetCounts +JSS(node_read_retries); // out: GetCounts +JSS(node_reads_hit); // out: GetCounts +JSS(node_reads_total); // out: GetCounts +JSS(node_reads_duration_us); // out: GetCounts +JSS(node_size); // out: server_info +JSS(nodes); // out: VaultInfo +JSS(nodestore); // out: GetCounts +JSS(node_writes); // out: GetCounts +JSS(node_written_bytes); // out: GetCounts +JSS(node_writes_duration_us); // out: GetCounts +JSS(node_write_retries); // out: GetCounts +JSS(node_writes_delayed); // out::GetCounts +JSS(nth); // out: RPC server_definitions +JSS(obligations); // out: GatewayBalances +JSS(offers); // out: NetworkOPs, AccountOffers, Subscribe +JSS(offer_id); // out: insertNFTokenOfferID +JSS(offline); // in: TransactionSign +JSS(offset); // in/out: AccountTxOld +JSS(open); // out: handlers/Ledger +JSS(open_ledger_cost); // out: SubmitTransaction +JSS(open_ledger_fee); // out: TxQ +JSS(open_ledger_level); // out: TxQ +JSS(optionality); // out: server_definitions +JSS(oracles); // in: get_aggregate_price +JSS(oracle_document_id); // in: get_aggregate_price +JSS(out); // out: OverlayImpl +JSS(owner); // in: LedgerEntry, out: NetworkOPs +JSS(owner_funds); // in/out: Ledger, NetworkOPs, AcceptedLedgerTx +JSS(page_index); // +JSS(params); // RPC +JSS(parent_close_time); // out: LedgerToJson +JSS(parent_hash); // out: LedgerToJson +JSS(partition); // in: LogLevel +JSS(passphrase); // in: WalletPropose +JSS(password); // in: Subscribe +JSS(paths); // in: RipplePathFind +JSS(paths_canonical); // out: RipplePathFind +JSS(paths_computed); // out: PathRequest, RipplePathFind +JSS(peer); // in: AccountLines +JSS(peer_authorized); // out: AccountLines +JSS(peer_id); // out: RCLCxPeerPos +JSS(peers); // out: InboundLedger, handlers/Peers, Overlay +JSS(peer_disconnects); // Severed peer connection counter. +JSS(peer_disconnects_resources); // Severed peer connections because of + // excess resource consumption. +JSS(port); // in: Connect, out: NetworkOPs +JSS(ports); // out: NetworkOPs +JSS(previous); // out: Reservations +JSS(previous_ledger); // out: LedgerPropose +JSS(price); // out: amm_info, AuctionSlot +JSS(proof); // in: BookOffers +JSS(propose_seq); // out: LedgerPropose +JSS(proposers); // out: NetworkOPs, LedgerConsensus +JSS(protocol); // out: NetworkOPs, PeerImp +JSS(proxied); // out: RPC ping +JSS(pseudo_account); // out: AccountInfo +JSS(pubkey_node); // out: NetworkOPs +JSS(pubkey_publisher); // out: ValidatorList +JSS(pubkey_validator); // out: NetworkOPs, ValidatorList +JSS(public_key); // out: OverlayImpl, PeerImp, WalletPropose, ValidatorInfo + // in/out: Manifest +JSS(public_key_hex); // out: WalletPropose +JSS(published_ledger); // out: NetworkOPs +JSS(publisher_lists); // out: ValidatorList +JSS(quality); // out: NetworkOPs +JSS(quality_in); // out: AccountLines +JSS(quality_out); // out: AccountLines +JSS(queue); // in: AccountInfo +JSS(queue_data); // out: AccountInfo +JSS(queued); // out: SubmitTransaction +JSS(queued_duration_us); // +JSS(quote_asset); // in: get_aggregate_price +JSS(random); // out: Random +JSS(raw_meta); // out: AcceptedLedgerTx +JSS(receive_currencies); // out: AccountCurrencies +JSS(reference_level); // out: TxQ +JSS(refresh_interval); // in: UNL +JSS(refresh_interval_min); // out: ValidatorSites +JSS(regular_seed); // in/out: LedgerEntry +JSS(remaining); // out: ValidatorList +JSS(remote); // out: Logic.h +JSS(request); // RPC +JSS(requested); // out: Manifest +JSS(reservations); // out: Reservations +JSS(reserve_base); // out: NetworkOPs +JSS(reserve_base_xrp); // out: NetworkOPs +JSS(reserve_inc); // out: NetworkOPs +JSS(reserve_inc_xrp); // out: NetworkOPs +JSS(response); // websocket +JSS(result); // RPC +JSS(ripple_lines); // out: NetworkOPs +JSS(ripple_state); // in: LedgerEntr +JSS(ripplerpc); // ripple RPC version +JSS(role); // out: Ping.cpp +JSS(rpc); // +JSS(rt_accounts); // in: Subscribe, Unsubscribe +JSS(running_duration_us); // +JSS(search_depth); // in: RipplePathFind +JSS(searched_all); // out: Tx +JSS(secret); // in: TransactionSign, ValidationCreate, ValidationSeed, + // channel_authorize +JSS(seed); // +JSS(seed_hex); // in: WalletPropose, TransactionSign +JSS(send_currencies); // out: AccountCurrencies +JSS(send_max); // in: PathRequest, RipplePathFind +JSS(seq); // in: LedgerEntry + // out: NetworkOPs, RPCSub, AccountOffers, ValidatorList, + // ValidatorInfo, Manifest +JSS(sequence); // in: UNL +JSS(sequence_count); // out: AccountInfo +JSS(server_domain); // out: NetworkOPs +JSS(server_state); // out: NetworkOPs +JSS(server_state_duration_us); // out: NetworkOPs +JSS(server_status); // out: NetworkOPs +JSS(server_version); // out: NetworkOPs +JSS(settle_delay); // out: AccountChannels +JSS(severity); // in: LogLevel +JSS(shares); // out: VaultInfo +JSS(signature); // out: NetworkOPs, ChannelAuthorize +JSS(signature_target); // in: TransactionSign +JSS(signature_verified); // out: ChannelVerify +JSS(signing_key); // out: NetworkOPs +JSS(signing_keys); // out: ValidatorList +JSS(signing_time); // out: NetworkOPs +JSS(signer_lists); // in/out: AccountInfo +JSS(size); // out: get_aggregate_price +JSS(snapshot); // in: Subscribe +JSS(source_account); // in: PathRequest, RipplePathFind +JSS(source_amount); // in: PathRequest, RipplePathFind +JSS(source_currencies); // in: PathRequest, RipplePathFind +JSS(source_tag); // out: AccountChannels +JSS(stand_alone); // out: NetworkOPs +JSS(standard_deviation); // out: get_aggregate_price +JSS(start); // in: TxHistory +JSS(started); // +JSS(state_accounting); // out: NetworkOPs +JSS(state_now); // in: Subscribe +JSS(status); // error +JSS(stop); // in: LedgerCleaner +JSS(stop_history_tx_only); // in: Unsubscribe, stop history tx stream +JSS(streams); // in: Subscribe, Unsubscribe +JSS(strict); // in: AccountCurrencies, AccountInfo +JSS(sub_index); // in: LedgerEntry +JSS(subcommand); // in: PathFind +JSS(subject); // in: LedgerEntry Credential +JSS(success); // rpc +JSS(supported); // out: AmendmentTableImpl +JSS(sync_mode); // in: Submit +JSS(system_time_offset); // out: NetworkOPs +JSS(tag); // out: Peers +JSS(taker); // in: Subscribe, BookOffers +JSS(taker_gets); // in: Subscribe, Unsubscribe, BookOffers +JSS(taker_gets_funded); // out: NetworkOPs +JSS(taker_pays); // in: Subscribe, Unsubscribe, BookOffers +JSS(taker_pays_funded); // out: NetworkOPs +JSS(threshold); // in: Blacklist +JSS(ticket_count); // out: AccountInfo +JSS(ticket_seq); // in: LedgerEntry +JSS(time); // +JSS(timeouts); // out: InboundLedger +JSS(time_threshold); // in/out: Oracle aggregate +JSS(time_interval); // out: AMM Auction Slot +JSS(track); // out: PeerImp +JSS(traffic); // out: Overlay +JSS(trim); // in: get_aggregate_price +JSS(trimmed_set); // out: get_aggregate_price +JSS(total); // out: counters +JSS(total_bytes_recv); // out: Peers +JSS(total_bytes_sent); // out: Peers +JSS(total_coins); // out: LedgerToJson +JSS(trading_fee); // out: amm_info +JSS(transTreeHash); // out: ledger/Ledger.cpp +JSS(transaction); // in: Tx + // out: NetworkOPs, AcceptedLedgerTx, +JSS(transaction_hash); // out: RCLCxPeerPos, LedgerToJson +JSS(transactions); // out: LedgerToJson, + // in: AccountTx*, Unsubscribe +JSS(TRANSACTION_RESULTS); // out: RPC server_definitions + // matches definitions.json format +JSS(TRANSACTION_TYPES); // out: RPC server_definitions + // matches definitions.json format +JSS(TRANSACTION_FLAGS); // out: RPC server_definitions +JSS(TRANSACTION_FORMATS); // out: RPC server_definitions +JSS(TYPES); // out: RPC server_definitions + // matches definitions.json format +JSS(transfer_rate); // out: nft_info (clio) +JSS(transitions); // out: NetworkOPs +JSS(treenode_cache_size); // out: GetCounts +JSS(treenode_track_size); // out: GetCounts +JSS(trusted); // out: UnlList +JSS(trusted_validator_keys); // out: ValidatorList +JSS(tx); // out: STTx, AccountTx* +JSS(tx_blob); // in/out: Submit, + // in: TransactionSign, AccountTx* +JSS(tx_hash); // in: TransactionEntry +JSS(tx_json); // in/out: TransactionSign + // out: TransactionEntry +JSS(tx_signing_hash); // out: TransactionSign +JSS(tx_unsigned); // out: TransactionSign +JSS(txn_count); // out: NetworkOPs +JSS(txr_tx_cnt); // out: protocol message tx's count +JSS(txr_tx_sz); // out: protocol message tx's size +JSS(txr_have_txs_cnt); // out: protocol message have tx count +JSS(txr_have_txs_sz); // out: protocol message have tx size +JSS(txr_get_ledger_cnt); // out: protocol message get ledger count +JSS(txr_get_ledger_sz); // out: protocol message get ledger size +JSS(txr_ledger_data_cnt); // out: protocol message ledger data count +JSS(txr_ledger_data_sz); // out: protocol message ledger data size +JSS(txr_transactions_cnt); // out: protocol message get object count +JSS(txr_transactions_sz); // out: protocol message get object size +JSS(txr_selected_cnt); // out: selected peers count +JSS(txr_suppressed_cnt); // out: suppressed peers count +JSS(txr_not_enabled_cnt); // out: peers with tx reduce-relay disabled count +JSS(txr_missing_tx_freq); // out: missing tx frequency average +JSS(txs); // out: TxHistory +JSS(type); // in: AccountObjects + // out: NetworkOPs, RPC server_definitions OverlayImpl, Logic +JSS(type_hex); // out: STPathSet +JSS(unl); // out: UnlList +JSS(unlimited); // out: Connection.h +JSS(uptime); // out: GetCounts +JSS(uri); // out: ValidatorSites +JSS(url); // in/out: Subscribe, Unsubscribe +JSS(url_password); // in: Subscribe +JSS(url_username); // in: Subscribe +JSS(urlgravatar); // +JSS(username); // in: Subscribe +JSS(validated); // out: NetworkOPs, RPCHelpers, AccountTx*, Tx +JSS(validator_list_expires); // out: NetworkOps, ValidatorList +JSS(validator_list); // out: NetworkOps, ValidatorList +JSS(validators); // +JSS(validated_hash); // out: NetworkOPs +JSS(validated_ledger); // out: NetworkOPs +JSS(validated_ledger_index); // out: SubmitTransaction +JSS(validated_ledgers); // out: NetworkOPs +JSS(validation_key); // out: ValidationCreate, ValidationSeed +JSS(validation_private_key); // out: ValidationCreate +JSS(validation_public_key); // out: ValidationCreate, ValidationSeed +JSS(validation_quorum); // out: NetworkOPs +JSS(validation_seed); // out: ValidationCreate, ValidationSeed +JSS(validations); // out: AmendmentTableImpl +JSS(validator_list_threshold); // out: ValidatorList +JSS(validator_sites); // out: ValidatorSites +JSS(value); // out: STAmount +JSS(vault_id); // in: VaultInfo +JSS(version); // out: RPCVersion +JSS(vetoed); // out: AmendmentTableImpl +JSS(volume_a); // out: BookChanges +JSS(volume_b); // out: BookChanges +JSS(vote); // in: Feature +JSS(vote_slots); // out: amm_info +JSS(vote_weight); // out: amm_info +JSS(warning); // rpc: +JSS(warnings); // out: server_info, server_state +JSS(workers); // +JSS(write_load); // out: GetCounts #pragma push_macro("TRANSACTION") #undef TRANSACTION diff --git a/include/xrpl/resource/Fees.h b/include/xrpl/resource/Fees.h index 0ba083d4fe..ebda0e98db 100644 --- a/include/xrpl/resource/Fees.h +++ b/include/xrpl/resource/Fees.h @@ -5,38 +5,30 @@ namespace xrpl { namespace Resource { -// clang-format off /** Schedule of fees charged for imposing load on the server. */ /** @{ */ -extern Charge const feeMalformedRequest; // A request that we can immediately - // tell is invalid -extern Charge const feeRequestNoReply; // A request that we cannot satisfy -extern Charge const feeInvalidSignature; // An object whose signature we had - // to check and it failed -extern Charge const feeUselessData; // Data we have no use for -extern Charge const feeInvalidData; // Data we have to verify before - // rejecting +extern Charge const feeMalformedRequest; // A request that we can immediately tell is invalid. +extern Charge const feeRequestNoReply; // A request that we cannot satisfy. +extern Charge const feeInvalidSignature; // An object whose signature we had to check that failed. +extern Charge const feeUselessData; // Data we have no use for. +extern Charge const feeInvalidData; // Data we have to verify before rejecting. // RPC loads -extern Charge const feeMalformedRPC; // An RPC request that we can - // immediately tell is invalid. -extern Charge const feeReferenceRPC; // A default "reference" unspecified - // load -extern Charge const feeExceptionRPC; // RPC load that causes an exception -extern Charge const feeMediumBurdenRPC; // A somewhat burdensome RPC load -extern Charge const feeHeavyBurdenRPC; // A very burdensome RPC load +extern Charge const feeMalformedRPC; // An RPC request that we can immediately tell is invalid. +extern Charge const feeReferenceRPC; // A default "reference" unspecified load. +extern Charge const feeExceptionRPC; // RPC load that causes an exception. +extern Charge const feeMediumBurdenRPC; // A somewhat burdensome RPC load. +extern Charge const feeHeavyBurdenRPC; // A very burdensome RPC load. // Peer loads -extern Charge const feeTrivialPeer; // Requires no reply -extern Charge const feeModerateBurdenPeer; // Requires some work -extern Charge const feeHeavyBurdenPeer; // Extensive work +extern Charge const feeTrivialPeer; // Requires no reply. +extern Charge const feeModerateBurdenPeer; // Requires some work. +extern Charge const feeHeavyBurdenPeer; // Extensive work. // Administrative -extern Charge const feeWarning; // The cost of receiving a warning -extern Charge const feeDrop; // The cost of being dropped for - // excess load +extern Charge const feeWarning; // The cost of receiving a warning. +extern Charge const feeDrop; // The cost of being dropped for excess load. /** @} */ -// clang-format on } // namespace Resource } // namespace xrpl diff --git a/include/xrpl/tx/paths/detail/Steps.h b/include/xrpl/tx/paths/detail/Steps.h index 53c9294155..0b75974acb 100644 --- a/include/xrpl/tx/paths/detail/Steps.h +++ b/include/xrpl/tx/paths/detail/Steps.h @@ -147,29 +147,26 @@ public: /** If this step is a DirectStepI, return the quality in of the dst account. - */ + */ virtual std::uint32_t lineQualityIn(ReadView const&) const { return QUALITY_ONE; } - // clang-format off /** Find an upper bound of quality for the step @param v view to query the ledger state from @param prevStepDir Set to DebtDirection::redeems if the previous step redeems. - @return A pair. The first element is the upper bound of quality for the step, or std::nullopt if the - step is dry. The second element will be set to DebtDirection::redeems if this steps redeems, - DebtDirection:issues if this step issues. - @note it is an upper bound because offers on the books may be unfunded. - If there is always a funded offer at the tip of the book, then we could - rename this `theoreticalQuality` 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. - */ - // clang-format on + @return A pair. The first element is the upper bound of quality for the step, or std::nullopt + if the step is dry. The second element will be set to DebtDirection::redeems if this + steps redeems, DebtDirection:issues if this step issues. + @note It is an upper bound because offers on the books may be unfunded. If there is always a + funded offer at the tip of the book, then we could rename this `theoreticalQuality` + 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> qualityUpperBound(ReadView const& v, DebtDirection prevStepDir) const = 0; diff --git a/include/xrpl/tx/transactors/dex/AMMHelpers.h b/include/xrpl/tx/transactors/dex/AMMHelpers.h index 6e3957769f..f389fd283b 100644 --- a/include/xrpl/tx/transactors/dex/AMMHelpers.h +++ b/include/xrpl/tx/transactors/dex/AMMHelpers.h @@ -121,7 +121,6 @@ withinRelativeDistance(Quality const& calcQuality, Quality const& reqQuality, Nu * @param dist requested relative distance * @return true if within dist, false otherwise */ -// clang-format off template requires( std::is_same_v || std::is_same_v || @@ -134,7 +133,6 @@ withinRelativeDistance(Amt const& calc, Amt const& req, Number const& dist) auto const [min, max] = std::minmax(calc, req); return ((max - min) / max) < dist; } -// clang-format on /** Solve quadratic equation to find takerGets or takerPays. Round * to minimize the amount in order to maximize the quality. diff --git a/src/libxrpl/protocol/STValidation.cpp b/src/libxrpl/protocol/STValidation.cpp index ba6e679081..f4042844f4 100644 --- a/src/libxrpl/protocol/STValidation.cpp +++ b/src/libxrpl/protocol/STValidation.cpp @@ -38,22 +38,22 @@ STValidation::validationFormat() // guarantee the initialization order. // clang-format off static SOTemplate const format{ - {sfFlags, soeREQUIRED}, - {sfLedgerHash, soeREQUIRED}, - {sfLedgerSequence, soeREQUIRED}, - {sfCloseTime, soeOPTIONAL}, - {sfLoadFee, soeOPTIONAL}, - {sfAmendments, soeOPTIONAL}, - {sfBaseFee, soeOPTIONAL}, - {sfReserveBase, soeOPTIONAL}, - {sfReserveIncrement, soeOPTIONAL}, - {sfSigningTime, soeREQUIRED}, - {sfSigningPubKey, soeREQUIRED}, - {sfSignature, soeREQUIRED}, - {sfConsensusHash, soeOPTIONAL}, - {sfCookie, soeDEFAULT}, - {sfValidatedHash, soeOPTIONAL}, - {sfServerVersion, soeOPTIONAL}, + {sfFlags, soeREQUIRED}, + {sfLedgerHash, soeREQUIRED}, + {sfLedgerSequence, soeREQUIRED}, + {sfCloseTime, soeOPTIONAL}, + {sfLoadFee, soeOPTIONAL}, + {sfAmendments, soeOPTIONAL}, + {sfBaseFee, soeOPTIONAL}, + {sfReserveBase, soeOPTIONAL}, + {sfReserveIncrement, soeOPTIONAL}, + {sfSigningTime, soeREQUIRED}, + {sfSigningPubKey, soeREQUIRED}, + {sfSignature, soeREQUIRED}, + {sfConsensusHash, soeOPTIONAL}, + {sfCookie, soeDEFAULT}, + {sfValidatedHash, soeOPTIONAL}, + {sfServerVersion, soeOPTIONAL}, // featureXRPFees {sfBaseFeeDrops, soeOPTIONAL}, {sfReserveBaseDrops, soeOPTIONAL}, diff --git a/src/libxrpl/tx/applySteps.cpp b/src/libxrpl/tx/applySteps.cpp index 6c6b3f8c98..447ba685cc 100644 --- a/src/libxrpl/tx/applySteps.cpp +++ b/src/libxrpl/tx/applySteps.cpp @@ -95,34 +95,32 @@ with_txn_type(Rules const& rules, TxType txnType, F&& f) // For Transactor::Normal // -// clang-format off // Current formatter for rippled is based on clang-10, which does not handle `requires` clauses template -requires(T::ConsequencesFactory == Transactor::Normal) + requires(T::ConsequencesFactory == Transactor::Normal) TxConsequences - consequences_helper(PreflightContext const& ctx) +consequences_helper(PreflightContext const& ctx) { return TxConsequences(ctx.tx); }; // For Transactor::Blocker template -requires(T::ConsequencesFactory == Transactor::Blocker) + requires(T::ConsequencesFactory == Transactor::Blocker) TxConsequences - consequences_helper(PreflightContext const& ctx) +consequences_helper(PreflightContext const& ctx) { return TxConsequences(ctx.tx, TxConsequences::blocker); }; // For Transactor::Custom template -requires(T::ConsequencesFactory == Transactor::Custom) + requires(T::ConsequencesFactory == Transactor::Custom) TxConsequences - consequences_helper(PreflightContext const& ctx) +consequences_helper(PreflightContext const& ctx) { return T::makeTxConsequences(ctx); }; -// clang-format on static std::pair invoke_preflight(PreflightContext const& ctx) diff --git a/src/libxrpl/tx/paths/AMMLiquidity.cpp b/src/libxrpl/tx/paths/AMMLiquidity.cpp index 4d6b67fa68..bb7f229374 100644 --- a/src/libxrpl/tx/paths/AMMLiquidity.cpp +++ b/src/libxrpl/tx/paths/AMMLiquidity.cpp @@ -50,12 +50,10 @@ AMMLiquidity::generateFibSeqOffer(TAmounts const& balances if (ammContext_.curIters() == 0) return cur; - // clang-format off constexpr std::uint32_t fib[AMMContext::MaxIterations] = { - 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, - 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, - 196418, 317811, 514229, 832040, 1346269}; - // clang-format on + 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, + 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, + 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269}; XRPL_ASSERT( !ammContext_.maxItersReached(), diff --git a/src/libxrpl/tx/transactors/check/CheckCash.cpp b/src/libxrpl/tx/transactors/check/CheckCash.cpp index f477896cb1..09b3177ce7 100644 --- a/src/libxrpl/tx/transactors/check/CheckCash.cpp +++ b/src/libxrpl/tx/transactors/check/CheckCash.cpp @@ -325,28 +325,26 @@ CheckCash::doApply() STAmount initialBalance(flowDeliver.issue()); initialBalance.setIssuer(noAccount()); - // clang-format off if (TER const ter = trustCreate( - psb, // payment sandbox - destLow, // is dest low? - issuer, // source - account_, // destination - trustLineKey.key, // ledger index - sleDst, // Account to add to - false, // authorize account - (sleDst->getFlags() & lsfDefaultRipple) == 0, - false, // freeze trust line - false, // deep freeze trust line - initialBalance, // zero initial balance - Issue(currency, account_), // limit of zero - 0, // quality in - 0, // quality out - viewJ); // journal + psb, // payment sandbox + destLow, // is dest low? + issuer, // source + account_, // destination + trustLineKey.key, // ledger index + sleDst, // Account to add to + false, // authorize account + (sleDst->getFlags() & lsfDefaultRipple) == 0, // + false, // freeze trust line + false, // deep freeze trust line + initialBalance, // zero initial balance + Issue(currency, account_), // limit of zero + 0, // quality in + 0, // quality out + viewJ); // journal !isTesSuccess(ter)) { return ter; } - // clang-format on psb.update(sleDst); diff --git a/src/libxrpl/tx/transactors/escrow/EscrowHelpers.h b/src/libxrpl/tx/transactors/escrow/EscrowHelpers.h index 5fdc43c359..8991fb06cc 100644 --- a/src/libxrpl/tx/transactors/escrow/EscrowHelpers.h +++ b/src/libxrpl/tx/transactors/escrow/EscrowHelpers.h @@ -69,28 +69,26 @@ escrowUnlockApplyHelper( STAmount initialBalance(amount.issue()); initialBalance.setIssuer(noAccount()); - // clang-format off if (TER const ter = trustCreate( - view, // payment sandbox - recvLow, // is dest low? - issuer, // source - receiver, // destination - trustLineKey.key, // ledger index - sleDest, // Account to add to - false, // authorize account - (sleDest->getFlags() & lsfDefaultRipple) == 0, - false, // freeze trust line - false, // deep freeze trust line - initialBalance, // zero initial balance - Issue(currency, receiver), // limit of zero - 0, // quality in - 0, // quality out - journal); // journal + view, // payment sandbox + recvLow, // is dest low? + issuer, // source + receiver, // destination + trustLineKey.key, // ledger index + sleDest, // Account to add to + false, // authorize account + (sleDest->getFlags() & lsfDefaultRipple) == 0, // + false, // freeze trust line + false, // deep freeze trust line + initialBalance, // zero initial balance + Issue(currency, receiver), // limit of zero + 0, // quality in + 0, // quality out + journal); // journal !isTesSuccess(ter)) { - return ter; // LCOV_EXCL_LINE + return ter; // LCOV_EXCL_LINE } - // clang-format on view.update(sleDest); } diff --git a/src/test/app/MultiSign_test.cpp b/src/test/app/MultiSign_test.cpp index f96bfba2d2..2bdfec2e9d 100644 --- a/src/test/app/MultiSign_test.cpp +++ b/src/test/app/MultiSign_test.cpp @@ -163,25 +163,20 @@ public: {spook, 1}}), ter(temBAD_QUORUM)); - // clang-format off // Make a signer list that's too big. Should fail. Account const spare("spare", KeyType::secp256k1); env(signers( alice, 1, - std::vector{{bogie, 1}, {demon, 1}, {ghost, 1}, - {haunt, 1}, {jinni, 1}, {phase, 1}, - {shade, 1}, {spook, 1}, {spare, 1}, - {acc10, 1}, {acc11, 1}, {acc12, 1}, - {acc13, 1}, {acc14, 1}, {acc15, 1}, - {acc16, 1}, {acc17, 1}, {acc18, 1}, - {acc19, 1}, {acc20, 1}, {acc21, 1}, - {acc22, 1}, {acc23, 1}, {acc24, 1}, - {acc25, 1}, {acc26, 1}, {acc27, 1}, - {acc28, 1}, {acc29, 1}, {acc30, 1}, - {acc31, 1}, {acc32, 1}, {acc33, 1}}), + std::vector{ + {bogie, 1}, {demon, 1}, {ghost, 1}, {haunt, 1}, {jinni, 1}, {phase, 1}, + {shade, 1}, {spook, 1}, {spare, 1}, {acc10, 1}, {acc11, 1}, {acc12, 1}, + {acc13, 1}, {acc14, 1}, {acc15, 1}, {acc16, 1}, {acc17, 1}, {acc18, 1}, + {acc19, 1}, {acc20, 1}, {acc21, 1}, {acc22, 1}, {acc23, 1}, {acc24, 1}, + {acc25, 1}, {acc26, 1}, {acc27, 1}, {acc28, 1}, {acc29, 1}, {acc30, 1}, + {acc31, 1}, {acc32, 1}, {acc33, 1}, + }), ter(temMALFORMED)); - // clang-format on env.close(); env.require(owners(alice, 0)); } diff --git a/src/test/app/TheoreticalQuality_test.cpp b/src/test/app/TheoreticalQuality_test.cpp index b4f6f3697d..1a701b8954 100644 --- a/src/test/app/TheoreticalQuality_test.cpp +++ b/src/test/app/TheoreticalQuality_test.cpp @@ -295,8 +295,6 @@ public: { testcase("Direct Step"); - // clang-format off - // Set up a payment through four accounts: alice -> bob -> carol -> dan // For each relevant trust line on the path, there are three things that can vary: // 1) input quality @@ -305,8 +303,6 @@ public: // For each account, there is one thing that can vary: // 1) transfer rate - // clang-format on - using namespace jtx; auto const currency = to_currency("USD"); @@ -385,14 +381,12 @@ public: testcase("Book Step"); using namespace jtx; - // clang-format off + // Setup a payment through an offer: + // alice (USD/bob) -> bob -> (USD/bob)|(EUR/carol) -> carol -> dan + // For each relevant trust line, vary input quality, output quality, debt direction. For + // each account, vary transfer rate. - // Setup a payment through an offer: alice (USD/bob) -> bob -> (USD/bob)|(EUR/carol) -> carol -> dan - // For each relevant trust line, vary input quality, output quality, debt direction. - // For each account, vary transfer rate. - // The USD/bob|EUR/carol offer owner is "Oscar" - - // clang-format on + // The USD/bob|EUR/carol offer owner is "Oscar". int const numTestIterations = reqNumIterations.value_or(100); diff --git a/src/test/app/TxQ_test.cpp b/src/test/app/TxQ_test.cpp index 566551fe2a..11bbd62bd5 100644 --- a/src/test/app/TxQ_test.cpp +++ b/src/test/app/TxQ_test.cpp @@ -261,9 +261,7 @@ public: env(noop(alice), fee(baseFee * 2.0), queued); // Queue is full now. - // clang-format off checkMetrics(*this, env, 6, 6, 4, 3, txFeeLevelByAccount(env, daria) + 1); - // clang-format on // Try to add another transaction with the default (low) fee, // it should fail because the queue is full. env(noop(charlie), ter(telCAN_NOT_QUEUE_FULL)); @@ -274,18 +272,22 @@ public: env(noop(charlie), fee(baseFee * 10), queued); // Queue is still full, of course, but the min fee has gone up - // clang-format off checkMetrics(*this, env, 6, 6, 4, 3, txFeeLevelByAccount(env, elmo) + 1); - // clang-format on // Close out the ledger, the transactions are accepted, the // queue is cleared, then the localTxs are retried. At this // point, daria's transaction that was dropped from the queue // is put back in. Neat. env.close(); - // clang-format off - checkMetrics(*this, env, 2, 8, 5, 4, baseFeeLevel.fee(), calcMedFeeLevel(FeeLevel64{baseFeeLevel.fee() * largeFeeMultiplier})); - // clang-format on + checkMetrics( + *this, + env, + 2, + 8, + 5, + 4, + baseFeeLevel.fee(), + calcMedFeeLevel(FeeLevel64{baseFeeLevel.fee() * largeFeeMultiplier})); env.close(); checkMetrics(*this, env, 0, 10, 2, 5); @@ -750,15 +752,13 @@ public: env.close(); // alice's transaction is still hanging around - // clang-format off - checkMetrics(*this, env, 1, 8, 5, 4, baseFeeLevel.fee(), baseFeeLevel.fee() * largeFeeMultiplier); - // clang-format on + checkMetrics( + *this, env, 1, 8, 5, 4, baseFeeLevel.fee(), baseFeeLevel.fee() * largeFeeMultiplier); BEAST_EXPECT(env.seq(alice) == 3); constexpr auto anotherLargeFeeMultiplier = 800; auto const anotherLargeFee = baseFee * anotherLargeFeeMultiplier; // Keep alice's transaction waiting. - // clang-format off env(noop(bob), fee(anotherLargeFee), queued); env(noop(charlie), fee(anotherLargeFee), queued); env(noop(daria), fee(anotherLargeFee), queued); @@ -766,24 +766,36 @@ public: env(noop(edgar), fee(anotherLargeFee), queued); env(noop(felicia), fee(anotherLargeFee - 1), queued); env(noop(felicia), fee(anotherLargeFee - 1), seq(env.seq(felicia) + 1), queued); - checkMetrics(*this, env, 8, 8, 5, 4, baseFeeLevel.fee() + 1, baseFeeLevel.fee() * largeFeeMultiplier); - // clang-format on + checkMetrics( + *this, + env, + 8, + 8, + 5, + 4, + baseFeeLevel.fee() + 1, + baseFeeLevel.fee() * largeFeeMultiplier); env.close(); // alice's transaction expired without getting // into the ledger, so her transaction is gone, // though one of felicia's is still in the queue. - // clang-format off - checkMetrics(*this, env, 1, 10, 6, 5, baseFeeLevel.fee(), baseFeeLevel.fee() * largeFeeMultiplier); - // clang-format on + checkMetrics( + *this, env, 1, 10, 6, 5, baseFeeLevel.fee(), baseFeeLevel.fee() * largeFeeMultiplier); BEAST_EXPECT(env.seq(alice) == 3); BEAST_EXPECT(env.seq(felicia) == 7); env.close(); // And now the queue is empty - // clang-format off - checkMetrics(*this, env, 0, 12, 1, 6, baseFeeLevel.fee(), baseFeeLevel.fee() * anotherLargeFeeMultiplier); - // clang-format on + checkMetrics( + *this, + env, + 0, + 12, + 1, + 6, + baseFeeLevel.fee(), + baseFeeLevel.fee() * anotherLargeFeeMultiplier); BEAST_EXPECT(env.seq(alice) == 3); BEAST_EXPECT(env.seq(felicia) == 8); } @@ -857,9 +869,7 @@ public: feeCarol = (feeCarol + 1) * 125 / 100; ++seqCarol; } - // clang-format off checkMetrics(*this, env, 6, 6, 4, 3, (baseFeeLevel.fee() * aliceFeeMultiplier) + 1); - // clang-format on // Carol submits high enough to beat Bob's average fee which kicks // out Bob's queued transaction. However Bob's transaction stays @@ -1505,9 +1515,7 @@ public: env.close(); // If not for the maximum, the per ledger would be 11. - // clang-format off checkMetrics(*this, env, 0, 10, 0, 5, baseFeeLevel.fee(), calcMedFeeLevel(medFeeLevel)); - // clang-format on } try diff --git a/src/test/jtx/TestHelpers.h b/src/test/jtx/TestHelpers.h index 08e86b40ac..e2b623911c 100644 --- a/src/test/jtx/TestHelpers.h +++ b/src/test/jtx/TestHelpers.h @@ -559,7 +559,6 @@ allPathElements(AccountID const& a, Issue const& iss); namespace check { /** Create a check. */ -// clang-format off template requires std::is_same_v Json::Value @@ -572,7 +571,6 @@ create(A const& account, A const& dest, STAmount const& sendMax) jv[sfTransactionType.jsonName] = jss::CheckCreate; return jv; } -// clang-format on inline Json::Value create(jtx::Account const& account, jtx::Account const& dest, STAmount const& sendMax) diff --git a/src/test/overlay/ProtocolVersion_test.cpp b/src/test/overlay/ProtocolVersion_test.cpp index f0d02edbca..fc25812cbb 100644 --- a/src/test/overlay/ProtocolVersion_test.cpp +++ b/src/test/overlay/ProtocolVersion_test.cpp @@ -42,20 +42,14 @@ public: // Empty string check("", ""); - // clang-format off - check( - "RTXP/1.1,RTXP/1.2,RTXP/1.3,XRPL/2.1,XRPL/2.0,/XRPL/3.0", - "XRPL/2.0,XRPL/2.1"); - check( - "RTXP/0.9,RTXP/1.01,XRPL/0.3,XRPL/2.01,websocket", - ""); + check("RTXP/1.1,RTXP/1.2,RTXP/1.3,XRPL/2.1,XRPL/2.0,/XRPL/3.0", "XRPL/2.0,XRPL/2.1"); + check("RTXP/0.9,RTXP/1.01,XRPL/0.3,XRPL/2.01,websocket", ""); check( "XRPL/2.0,XRPL/2.0,XRPL/19.4,XRPL/7.89,XRPL/XRPL/3.0,XRPL/2.01", "XRPL/2.0,XRPL/7.89,XRPL/19.4"); check( "XRPL/2.0,XRPL/3.0,XRPL/4,XRPL/,XRPL,OPT XRPL/2.2,XRPL/5.67", "XRPL/2.0,XRPL/3.0,XRPL/5.67"); - // clang-format on } { diff --git a/src/test/unit_test/SuiteJournal.h b/src/test/unit_test/SuiteJournal.h index 1eeefb68aa..08c40af43d 100644 --- a/src/test/unit_test/SuiteJournal.h +++ b/src/test/unit_test/SuiteJournal.h @@ -87,11 +87,7 @@ public: : sink_(partition, threshold, suite), journal_(sink_) { } - // Clang 10.0.0 and 10.0.1 disagree about formatting operator& - // TBD Re-enable formatting when we upgrade to clang 11 - // clang-format off - operator beast::Journal &() - // clang-format on + operator beast::Journal&() { return journal_; } diff --git a/src/xrpld/core/detail/Config.cpp b/src/xrpld/core/detail/Config.cpp index c7179c181b..270764a17b 100644 --- a/src/xrpld/core/detail/Config.cpp +++ b/src/xrpld/core/detail/Config.cpp @@ -112,11 +112,12 @@ sizedItems {SizedItem::ramSizeGB, {{ 6, 8, 12, 24, 0 }}}, {SizedItem::accountIdCacheSize, {{ 20047, 50053, 77081, 150061, 300007 }}} }}; +// clang-format on // Ensure that the order of entries in the table corresponds to the // order of entries in the enum: static_assert( - []() constexpr->bool { + []() constexpr -> bool { std::underlying_type_t idx = 0; for (auto const& i : sizedItems) @@ -130,7 +131,6 @@ static_assert( return true; }(), "Mismatch between sized item enum & array indices"); -// clang-format on // // TODO: Check permissions on config file before using it. diff --git a/src/xrpld/overlay/detail/ProtocolVersion.cpp b/src/xrpld/overlay/detail/ProtocolVersion.cpp index 29bff996a9..a8213f2824 100644 --- a/src/xrpld/overlay/detail/ProtocolVersion.cpp +++ b/src/xrpld/overlay/detail/ProtocolVersion.cpp @@ -17,13 +17,10 @@ namespace xrpl { it may not contain any duplicates!) */ -// clang-format off -constexpr ProtocolVersion const supportedProtocolList[] -{ +constexpr ProtocolVersion const supportedProtocolList[]{ {2, 1}, - {2, 2} + {2, 2}, }; -// clang-format on // This ugly construct ensures that supportedProtocolList is sorted in strictly // ascending order and doesn't contain any duplicates. From c3fae847f34e59fea8544f5d2e120a736e7ee45b Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Tue, 31 Mar 2026 18:14:41 +0100 Subject: [PATCH 39/53] ci: Use pull_request_target to check for signed commits (#6697) --- .github/workflows/check-pr-commits.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/check-pr-commits.yml b/.github/workflows/check-pr-commits.yml index 07c62c9ff5..2697a3a40e 100644 --- a/.github/workflows/check-pr-commits.yml +++ b/.github/workflows/check-pr-commits.yml @@ -1,7 +1,7 @@ name: Check PR commits on: - pull_request: + pull_request_target: # The action needs to have write permissions to post comments on the PR. permissions: From 2502befb424dc0edbf79e14c2dc70b466829ebb3 Mon Sep 17 00:00:00 2001 From: Alex Kremer Date: Tue, 31 Mar 2026 18:29:45 +0100 Subject: [PATCH 40/53] chore: Enable clang-tidy misc checks (#6655) --- .clang-tidy | 10 +- .../workflows/reusable-clang-tidy-files.yml | 2 +- CONTRIBUTING.md | 4 +- include/xrpl/basics/BasicConfig.h | 2 +- include/xrpl/basics/IntrusiveRefCounts.h | 2 +- include/xrpl/basics/SlabAllocator.h | 6 +- include/xrpl/basics/StringUtilities.h | 4 +- include/xrpl/basics/base_uint.h | 4 +- include/xrpl/basics/contract.h | 2 +- include/xrpl/basics/hardened_hash.h | 2 +- include/xrpl/basics/random.h | 4 +- include/xrpl/beast/asio/io_latency_probe.h | 10 +- include/xrpl/beast/container/aged_map.h | 2 +- include/xrpl/beast/container/aged_multimap.h | 2 +- include/xrpl/beast/container/aged_multiset.h | 2 +- include/xrpl/beast/container/aged_set.h | 2 +- .../xrpl/beast/container/aged_unordered_map.h | 2 +- .../beast/container/aged_unordered_multimap.h | 2 +- .../beast/container/aged_unordered_multiset.h | 2 +- .../xrpl/beast/container/aged_unordered_set.h | 2 +- include/xrpl/beast/core/List.h | 2 +- include/xrpl/beast/test/yield_to.h | 2 +- include/xrpl/beast/unit_test/runner.h | 8 +- include/xrpl/beast/unit_test/suite.h | 2 +- include/xrpl/beast/utility/Zero.h | 2 +- include/xrpl/core/ClosureCounter.h | 6 +- include/xrpl/core/JobQueue.h | 2 +- include/xrpl/core/JobTypes.h | 2 +- include/xrpl/core/PeerReservationTable.h | 2 +- include/xrpl/core/PerfLog.h | 2 +- include/xrpl/core/ServiceRegistry.h | 6 +- include/xrpl/core/detail/Workers.h | 2 +- include/xrpl/core/detail/semaphore.h | 2 +- include/xrpl/json/json_value.h | 4 +- include/xrpl/ledger/AmendmentTable.h | 2 +- include/xrpl/ledger/CachedSLEs.h | 2 +- include/xrpl/ledger/PendingSaves.h | 8 +- include/xrpl/nodestore/detail/varint.h | 1 + include/xrpl/protocol/AmountConversions.h | 2 +- include/xrpl/protocol/Issue.h | 4 +- include/xrpl/protocol/Quality.h | 4 +- include/xrpl/protocol/RippleLedgerHash.h | 2 +- include/xrpl/protocol/STAmount.h | 4 +- include/xrpl/protocol/STBase.h | 2 +- include/xrpl/protocol/STLedgerEntry.h | 2 +- include/xrpl/protocol/STObject.h | 4 +- include/xrpl/protocol/Serializer.h | 6 +- include/xrpl/protocol/TxSearched.h | 2 +- include/xrpl/protocol/detail/token_errors.h | 4 +- include/xrpl/protocol_autogen/.clang-tidy | 3 + include/xrpl/rdb/DatabaseCon.h | 2 +- include/xrpl/rdb/SociDB.h | 2 +- include/xrpl/resource/detail/Logic.h | 36 +- include/xrpl/server/LoadFeeTrack.h | 18 +- include/xrpl/server/Manifest.h | 4 +- include/xrpl/server/Port.h | 2 +- include/xrpl/server/detail/BaseHTTPPeer.h | 8 +- include/xrpl/server/detail/BaseWSPeer.h | 2 +- include/xrpl/server/detail/io_list.h | 4 +- include/xrpl/shamap/SHAMapItem.h | 1 + include/xrpl/tx/paths/Flow.h | 2 +- include/xrpl/tx/paths/RippleCalc.h | 2 +- include/xrpl/tx/paths/detail/StrandFlow.h | 2 +- include/xrpl/tx/transactors/dex/AMMHelpers.h | 10 +- src/libxrpl/basics/Archive.cpp | 5 +- src/libxrpl/basics/BasicConfig.cpp | 2 +- src/libxrpl/basics/FileUtilities.cpp | 2 +- src/libxrpl/basics/Log.cpp | 14 +- src/libxrpl/basics/Number.cpp | 30 +- src/libxrpl/basics/ResolverAsio.cpp | 6 +- src/libxrpl/basics/StringUtilities.cpp | 2 +- src/libxrpl/basics/base64.cpp | 4 +- src/libxrpl/basics/make_SSLContext.cpp | 2 +- .../beast/clock/basic_seconds_clock.cpp | 2 +- src/libxrpl/beast/core/SemanticVersion.cpp | 4 +- src/libxrpl/beast/insight/Collector.cpp | 2 +- src/libxrpl/beast/insight/Groups.cpp | 2 +- src/libxrpl/beast/insight/Hook.cpp | 2 +- src/libxrpl/beast/insight/StatsDCollector.cpp | 6 +- src/libxrpl/beast/net/IPEndpoint.cpp | 3 +- .../beast/utility/beast_PropertyStream.cpp | 28 +- src/libxrpl/core/HashRouter.cpp | 14 +- src/libxrpl/core/detail/JobQueue.cpp | 36 +- src/libxrpl/core/detail/LoadMonitor.cpp | 6 +- src/libxrpl/core/detail/Workers.cpp | 12 +- src/libxrpl/crypto/RFC1751.cpp | 6 +- src/libxrpl/crypto/csprng.cpp | 2 +- src/libxrpl/json/Writer.cpp | 2 +- src/libxrpl/json/json_reader.cpp | 37 +- src/libxrpl/json/json_value.cpp | 29 +- src/libxrpl/json/json_writer.cpp | 28 +- src/libxrpl/ledger/ApplyStateTable.cpp | 4 +- src/libxrpl/ledger/ApplyView.cpp | 2 +- src/libxrpl/ledger/BookListeners.cpp | 6 +- src/libxrpl/ledger/CachedView.cpp | 4 +- src/libxrpl/ledger/Ledger.cpp | 2 +- src/libxrpl/ledger/ReadView.cpp | 2 +- src/libxrpl/ledger/View.cpp | 2 +- src/libxrpl/ledger/helpers/OfferHelpers.cpp | 2 +- .../ledger/helpers/RippleStateHelpers.cpp | 10 +- src/libxrpl/ledger/helpers/TokenHelpers.cpp | 20 +- src/libxrpl/net/HTTPClient.cpp | 12 +- src/libxrpl/nodestore/BatchWriter.cpp | 4 +- src/libxrpl/nodestore/Database.cpp | 6 +- src/libxrpl/nodestore/DatabaseRotatingImp.cpp | 18 +- src/libxrpl/nodestore/ManagerImp.cpp | 6 +- .../nodestore/backend/MemoryFactory.cpp | 10 +- src/libxrpl/nodestore/backend/NuDBFactory.cpp | 8 +- src/libxrpl/nodestore/backend/NullFactory.cpp | 2 +- .../nodestore/backend/RocksDBFactory.cpp | 27 +- src/libxrpl/protocol/AccountID.cpp | 4 +- src/libxrpl/protocol/InnerObjectFormats.cpp | 2 +- src/libxrpl/protocol/LedgerFormats.cpp | 2 +- src/libxrpl/protocol/NFTokenID.cpp | 2 +- src/libxrpl/protocol/PublicKey.cpp | 4 +- src/libxrpl/protocol/QualityFunction.cpp | 2 +- src/libxrpl/protocol/Rules.cpp | 2 +- src/libxrpl/protocol/STAmount.cpp | 40 +- src/libxrpl/protocol/STIssue.cpp | 4 +- src/libxrpl/protocol/STLedgerEntry.cpp | 2 +- src/libxrpl/protocol/STNumber.cpp | 3 +- src/libxrpl/protocol/STObject.cpp | 22 +- src/libxrpl/protocol/STParsedJSON.cpp | 2 +- src/libxrpl/protocol/STPathSet.cpp | 4 +- src/libxrpl/protocol/STTx.cpp | 12 +- src/libxrpl/protocol/SecretKey.cpp | 10 +- src/libxrpl/protocol/Seed.cpp | 2 +- src/libxrpl/protocol/Serializer.cpp | 34 +- src/libxrpl/protocol/TxMeta.cpp | 6 +- src/libxrpl/protocol/XChainAttestations.cpp | 2 +- src/libxrpl/protocol/tokens.cpp | 14 +- src/libxrpl/rdb/DatabaseCon.cpp | 8 +- src/libxrpl/rdb/SociDB.cpp | 11 +- src/libxrpl/resource/ResourceManager.cpp | 2 +- src/libxrpl/server/InfoSub.cpp | 8 +- src/libxrpl/server/LoadFeeTrack.cpp | 4 +- src/libxrpl/server/Manifest.cpp | 18 +- src/libxrpl/server/Vacuum.cpp | 2 +- src/libxrpl/server/Wallet.cpp | 8 +- src/libxrpl/shamap/SHAMap.cpp | 32 +- src/libxrpl/shamap/SHAMapDelta.cpp | 15 +- src/libxrpl/shamap/SHAMapInnerNode.cpp | 8 +- src/libxrpl/shamap/SHAMapNodeID.cpp | 2 +- src/libxrpl/shamap/SHAMapSync.cpp | 18 +- src/libxrpl/tx/ApplyContext.cpp | 2 +- src/libxrpl/tx/Transactor.cpp | 10 +- src/libxrpl/tx/apply.cpp | 2 +- src/libxrpl/tx/invariants/FreezeInvariant.cpp | 2 +- src/libxrpl/tx/invariants/MPTInvariant.cpp | 2 +- src/libxrpl/tx/paths/BookStep.cpp | 4 +- src/libxrpl/tx/paths/OfferStream.cpp | 2 +- .../tx/transactors/account/AccountSet.cpp | 21 +- .../tx/transactors/account/SignerListSet.cpp | 6 +- .../tx/transactors/bridge/XChainBridge.cpp | 7 +- .../tx/transactors/check/CheckCash.cpp | 2 +- src/libxrpl/tx/transactors/dex/AMMBid.cpp | 2 +- src/libxrpl/tx/transactors/dex/AMMCreate.cpp | 2 +- src/libxrpl/tx/transactors/dex/AMMHelpers.cpp | 10 +- .../tx/transactors/dex/OfferCreate.cpp | 7 +- .../tx/transactors/escrow/EscrowCancel.cpp | 4 +- .../tx/transactors/escrow/EscrowCreate.cpp | 4 +- .../tx/transactors/escrow/EscrowFinish.cpp | 4 +- .../tx/transactors/lending/LendingHelpers.cpp | 4 +- .../lending/LoanBrokerCoverClawback.cpp | 4 +- .../lending/LoanBrokerCoverWithdraw.cpp | 2 +- .../tx/transactors/lending/LoanManage.cpp | 2 +- .../tx/transactors/lending/LoanPay.cpp | 4 +- .../tx/transactors/lending/LoanSet.cpp | 2 +- .../tx/transactors/nft/NFTokenUtils.cpp | 12 +- src/libxrpl/tx/transactors/system/Batch.cpp | 2 +- src/libxrpl/tx/transactors/system/Change.cpp | 2 +- .../tx/transactors/system/TicketCreate.cpp | 4 +- .../tx/transactors/token/MPTokenAuthorize.cpp | 2 +- src/libxrpl/tx/transactors/token/TrustSet.cpp | 11 +- .../tx/transactors/vault/VaultClawback.cpp | 2 +- src/test/app/AMMCalc_test.cpp | 10 +- src/test/app/AMMClawback_test.cpp | 144 +++--- src/test/app/AMMExtended_test.cpp | 268 +++++----- src/test/app/AMM_test.cpp | 468 ++++++++---------- src/test/app/AccountDelete_test.cpp | 12 +- src/test/app/AccountSet_test.cpp | 4 +- src/test/app/AccountTxPaging_test.cpp | 6 +- src/test/app/AmendmentTable_test.cpp | 2 +- src/test/app/Batch_test.cpp | 168 +++---- src/test/app/Check_test.cpp | 22 +- src/test/app/Clawback_test.cpp | 68 +-- src/test/app/DNS_test.cpp | 2 +- src/test/app/Delegate_test.cpp | 124 ++--- src/test/app/Discrepancy_test.cpp | 18 +- src/test/app/EscrowToken_test.cpp | 92 ++-- src/test/app/Escrow_test.cpp | 30 +- src/test/app/FeeVote_test.cpp | 14 +- src/test/app/Flow_test.cpp | 18 +- src/test/app/Freeze_test.cpp | 88 ++-- src/test/app/HashRouter_test.cpp | 32 +- src/test/app/Invariants_test.cpp | 148 +++--- src/test/app/LedgerHistory_test.cpp | 8 +- src/test/app/LedgerLoad_test.cpp | 10 +- src/test/app/LedgerMaster_test.cpp | 12 +- src/test/app/LedgerReplay_test.cpp | 83 ++-- src/test/app/LendingHelpers_test.cpp | 12 +- src/test/app/LoadFeeTrack_test.cpp | 2 +- src/test/app/LoanBroker_test.cpp | 32 +- src/test/app/Loan_test.cpp | 115 ++--- src/test/app/MPToken_test.cpp | 10 +- src/test/app/Manifest_test.cpp | 7 +- src/test/app/MultiSign_test.cpp | 32 +- src/test/app/NFTokenAuth_test.cpp | 46 +- src/test/app/NFTokenBurn_test.cpp | 20 +- src/test/app/NFTokenDir_test.cpp | 16 +- src/test/app/NFToken_test.cpp | 20 +- src/test/app/Offer_test.cpp | 4 +- src/test/app/Oracle_test.cpp | 18 +- src/test/app/Path_test.cpp | 90 ++-- src/test/app/PayChan_test.cpp | 2 +- src/test/app/PayStrand_test.cpp | 16 +- src/test/app/PermissionedDEX_test.cpp | 26 +- src/test/app/PermissionedDomains_test.cpp | 14 +- src/test/app/RCLValidations_test.cpp | 26 +- src/test/app/ReducedOffer_test.cpp | 16 +- src/test/app/Regression_test.cpp | 7 +- src/test/app/TheoreticalQuality_test.cpp | 12 +- src/test/app/Ticket_test.cpp | 24 +- src/test/app/TrustAndBalance_test.cpp | 42 +- src/test/app/TxQ_test.cpp | 12 +- src/test/app/ValidatorKeys_test.cpp | 14 +- src/test/app/ValidatorList_test.cpp | 92 ++-- src/test/app/ValidatorSite_test.cpp | 17 +- src/test/app/Vault_test.cpp | 178 +++---- src/test/app/XChain_test.cpp | 198 ++++---- src/test/app/tx/apply_test.cpp | 2 +- src/test/basics/Buffer_test.cpp | 6 +- src/test/basics/Expected_test.cpp | 2 +- src/test/basics/FileUtilities_test.cpp | 2 +- src/test/basics/IOUAmount_test.cpp | 20 +- src/test/basics/IntrusiveShared_test.cpp | 34 +- src/test/basics/Number_test.cpp | 69 +-- src/test/basics/StringUtilities_test.cpp | 2 +- src/test/basics/Units_test.cpp | 40 +- src/test/basics/XRPAmount_test.cpp | 17 +- src/test/basics/base_uint_test.cpp | 14 +- src/test/basics/hardened_hash_test.cpp | 4 +- src/test/beast/IPEndpoint_test.cpp | 10 +- src/test/beast/LexicalCast_test.cpp | 2 +- .../beast/aged_associative_container_test.cpp | 46 +- src/test/beast/beast_Journal_test.cpp | 2 +- src/test/beast/beast_PropertyStream_test.cpp | 6 +- .../beast/beast_io_latency_probe_test.cpp | 5 +- .../consensus/ByzantineFailureSim_test.cpp | 2 +- src/test/consensus/Consensus_test.cpp | 70 +-- .../DistributedValidatorsSim_test.cpp | 6 +- src/test/consensus/LedgerTiming_test.cpp | 2 +- src/test/consensus/LedgerTrie_test.cpp | 10 +- src/test/consensus/NegativeUNL_test.cpp | 94 ++-- src/test/consensus/Validations_test.cpp | 172 ++++--- src/test/core/Config_test.cpp | 44 +- src/test/core/Coroutine_test.cpp | 2 +- src/test/core/SociDB_test.cpp | 19 +- src/test/core/Workers_test.cpp | 4 +- src/test/csf/BasicNetwork.h | 2 +- src/test/csf/Digraph_test.cpp | 4 +- src/test/csf/Histogram.h | 2 +- src/test/csf/Peer.h | 6 +- src/test/csf/PeerGroup.h | 4 +- src/test/csf/TrustGraph.h | 4 +- src/test/csf/impl/ledgers.cpp | 4 +- src/test/csf/random.h | 2 +- src/test/csf/timers.h | 8 +- src/test/jtx/AMMTest.h | 2 +- src/test/jtx/CaptureLogs.h | 4 +- src/test/jtx/Env_test.cpp | 15 +- src/test/jtx/TestHelpers.h | 2 +- src/test/jtx/TrustedPublisherServer.h | 6 +- src/test/jtx/amount.h | 4 +- src/test/jtx/impl/AMM.cpp | 4 +- src/test/jtx/impl/Env.cpp | 4 +- src/test/jtx/impl/WSClient.cpp | 4 +- src/test/jtx/impl/mpt.cpp | 8 +- src/test/jtx/impl/multisign.cpp | 2 +- src/test/jtx/impl/permissioned_dex.cpp | 2 +- src/test/jtx/impl/xchain_bridge.cpp | 4 +- src/test/ledger/BookDirs_test.cpp | 2 +- src/test/ledger/Directory_test.cpp | 2 +- src/test/ledger/PaymentSandbox_test.cpp | 10 +- src/test/ledger/SkipList_test.cpp | 2 +- src/test/ledger/View_test.cpp | 16 +- src/test/nodestore/Backend_test.cpp | 2 +- src/test/nodestore/Basics_test.cpp | 2 +- src/test/nodestore/Database_test.cpp | 34 +- src/test/nodestore/NuDBFactory_test.cpp | 72 +-- src/test/nodestore/TestBase.h | 2 +- src/test/nodestore/Timing_test.cpp | 4 +- src/test/nodestore/import_test.cpp | 8 +- src/test/overlay/TMGetObjectByHash_test.cpp | 8 +- src/test/overlay/cluster_test.cpp | 2 +- src/test/overlay/compression_test.cpp | 28 +- src/test/overlay/reduce_relay_test.cpp | 38 +- src/test/overlay/short_read_test.cpp | 10 +- src/test/overlay/tx_reduce_relay_test.cpp | 9 +- src/test/peerfinder/Livecache_test.cpp | 2 +- src/test/peerfinder/PeerFinder_test.cpp | 2 +- src/test/protocol/Hooks_test.cpp | 9 +- src/test/protocol/InnerObjectFormats_test.cpp | 4 +- src/test/protocol/Issue_test.cpp | 14 +- src/test/protocol/PublicKey_test.cpp | 4 +- src/test/protocol/Quality_test.cpp | 16 +- src/test/protocol/STAmount_test.cpp | 288 +++++------ src/test/protocol/STInteger_test.cpp | 26 +- src/test/protocol/STIssue_test.cpp | 14 +- src/test/protocol/STNumber_test.cpp | 10 +- src/test/protocol/STObject_test.cpp | 18 +- src/test/protocol/STParsedJSON_test.cpp | 280 +++++------ src/test/protocol/STTx_test.cpp | 10 +- src/test/protocol/SecretKey_test.cpp | 2 +- src/test/protocol/Serializer_test.cpp | 4 +- src/test/protocol/TER_test.cpp | 8 +- src/test/resource/Logic_test.cpp | 19 +- src/test/rpc/AccountCurrencies_test.cpp | 3 +- src/test/rpc/AccountObjects_test.cpp | 6 +- src/test/rpc/AccountTx_test.cpp | 4 +- src/test/rpc/BookChanges_test.cpp | 2 +- src/test/rpc/Book_test.cpp | 16 +- src/test/rpc/DeliveredAmount_test.cpp | 2 +- src/test/rpc/DepositAuthorized_test.cpp | 10 +- src/test/rpc/Feature_test.cpp | 26 +- src/test/rpc/GatewayBalances_test.cpp | 2 +- src/test/rpc/GetAggregatePrice_test.cpp | 16 +- src/test/rpc/GetCounts_test.cpp | 4 +- src/test/rpc/JSONRPC_test.cpp | 42 +- src/test/rpc/KeyGeneration_test.cpp | 2 +- src/test/rpc/LedgerEntry_test.cpp | 16 +- src/test/rpc/LedgerRequest_test.cpp | 4 +- src/test/rpc/Peers_test.cpp | 2 +- src/test/rpc/RPCCall_test.cpp | 2 +- src/test/rpc/Simulate_test.cpp | 4 +- src/test/rpc/Status_test.cpp | 3 +- src/test/rpc/Subscribe_test.cpp | 20 +- src/test/rpc/TransactionEntry_test.cpp | 4 +- src/test/rpc/Transaction_test.cpp | 23 +- src/test/rpc/ValidatorRPC_test.cpp | 4 +- src/test/rpc/Version_test.cpp | 8 +- src/test/server/ServerStatus_test.cpp | 4 +- src/test/server/Server_test.cpp | 16 +- src/test/shamap/FetchPack_test.cpp | 4 +- src/test/shamap/SHAMapSync_test.cpp | 8 +- src/test/shamap/SHAMap_test.cpp | 6 +- src/test/unit_test/SuiteJournal.h | 2 +- src/test/unit_test/multi_runner.cpp | 12 +- src/tests/libxrpl/basics/MallocTrim.cpp | 52 +- src/tests/libxrpl/basics/Mutex.cpp | 4 +- src/tests/libxrpl/basics/scope.cpp | 12 +- src/tests/libxrpl/basics/tagged_integer.cpp | 2 +- src/tests/libxrpl/json/Value.cpp | 46 +- src/tests/libxrpl/net/HTTPClient.cpp | 16 +- .../libxrpl/protocol_autogen/.clang-tidy | 3 + .../protocol_autogen/STObjectValidation.cpp | 70 --- src/tests/libxrpl/protocol_autogen/main.cpp | 8 - src/xrpld/app/consensus/RCLConsensus.cpp | 14 +- src/xrpld/app/consensus/RCLConsensus.h | 2 +- src/xrpld/app/ledger/ConsensusTransSetSF.cpp | 2 +- src/xrpld/app/ledger/LedgerHistory.cpp | 24 +- 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/OrderBookDBImpl.cpp | 18 +- src/xrpld/app/ledger/detail/InboundLedger.cpp | 18 +- .../app/ledger/detail/InboundLedgers.cpp | 26 +- .../app/ledger/detail/InboundTransactions.cpp | 16 +- src/xrpld/app/ledger/detail/LedgerCleaner.cpp | 18 +- .../app/ledger/detail/LedgerDeltaAcquire.cpp | 2 +- src/xrpld/app/ledger/detail/LedgerMaster.cpp | 97 ++-- .../ledger/detail/LedgerReplayMsgHandler.cpp | 15 +- .../app/ledger/detail/LedgerReplayTask.cpp | 13 +- .../app/ledger/detail/LedgerReplayer.cpp | 15 +- src/xrpld/app/ledger/detail/LocalTxs.cpp | 8 +- src/xrpld/app/ledger/detail/OpenLedger.cpp | 12 +- .../app/ledger/detail/SkipListAcquire.cpp | 2 +- .../app/ledger/detail/TimeoutCounter.cpp | 2 +- .../app/ledger/detail/TransactionAcquire.cpp | 4 +- src/xrpld/app/main/Application.cpp | 2 +- src/xrpld/app/main/Application.h | 6 +- src/xrpld/app/main/GRPCServer.cpp | 22 +- src/xrpld/app/main/LoadManager.cpp | 6 +- src/xrpld/app/main/Main.cpp | 6 +- src/xrpld/app/misc/DeliverMax.h | 2 +- src/xrpld/app/misc/FeeVoteImpl.cpp | 4 +- src/xrpld/app/misc/NegativeUNLVote.cpp | 8 +- src/xrpld/app/misc/NetworkOPs.cpp | 126 ++--- src/xrpld/app/misc/SHAMapStoreImp.cpp | 20 +- src/xrpld/app/misc/ValidatorList.h | 2 +- src/xrpld/app/misc/detail/AmendmentTable.cpp | 32 +- src/xrpld/app/misc/detail/TxQ.cpp | 32 +- src/xrpld/app/misc/detail/ValidatorList.cpp | 46 +- src/xrpld/app/misc/detail/ValidatorSite.cpp | 24 +- src/xrpld/app/misc/detail/WorkFile.h | 8 +- src/xrpld/app/misc/detail/WorkPlain.h | 4 +- src/xrpld/app/rdb/backend/detail/Node.cpp | 25 +- src/xrpld/app/rdb/detail/PeerFinder.cpp | 2 +- src/xrpld/consensus/Consensus.cpp | 2 +- src/xrpld/consensus/Consensus.h | 8 +- src/xrpld/consensus/DisputedTx.h | 2 +- src/xrpld/consensus/LedgerTrie.h | 7 +- src/xrpld/consensus/Validations.h | 42 +- src/xrpld/core/detail/Config.cpp | 16 +- src/xrpld/overlay/Overlay.h | 2 +- src/xrpld/overlay/Peer.h | 2 +- src/xrpld/overlay/Slot.h | 2 +- src/xrpld/overlay/detail/Cluster.cpp | 8 +- src/xrpld/overlay/detail/ConnectAttempt.cpp | 6 +- src/xrpld/overlay/detail/Handshake.cpp | 6 +- src/xrpld/overlay/detail/Message.cpp | 2 +- src/xrpld/overlay/detail/OverlayImpl.cpp | 44 +- src/xrpld/overlay/detail/OverlayImpl.h | 4 +- src/xrpld/overlay/detail/PeerImp.cpp | 96 ++-- src/xrpld/overlay/detail/PeerImp.h | 4 +- .../overlay/detail/PeerReservationTable.cpp | 8 +- src/xrpld/overlay/detail/PeerSet.cpp | 2 +- src/xrpld/overlay/detail/ProtocolVersion.cpp | 7 +- src/xrpld/overlay/detail/TxMetrics.cpp | 8 +- src/xrpld/peerfinder/detail/Checker.h | 6 +- src/xrpld/peerfinder/detail/Logic.h | 56 +-- .../peerfinder/detail/PeerfinderConfig.cpp | 2 +- .../peerfinder/detail/PeerfinderManager.cpp | 14 +- src/xrpld/perflog/detail/PerfLogImp.cpp | 34 +- src/xrpld/rpc/BookChanges.h | 24 +- src/xrpld/rpc/CTID.h | 8 +- src/xrpld/rpc/DeliveredAmount.h | 2 +- src/xrpld/rpc/detail/Handler.h | 2 +- src/xrpld/rpc/detail/PathRequest.cpp | 18 +- src/xrpld/rpc/detail/PathRequestManager.cpp | 12 +- src/xrpld/rpc/detail/Pathfinder.cpp | 26 +- src/xrpld/rpc/detail/RPCCall.cpp | 36 +- src/xrpld/rpc/detail/RPCHandler.cpp | 4 +- src/xrpld/rpc/detail/RPCLedgerHelpers.cpp | 2 +- src/xrpld/rpc/detail/RPCSub.cpp | 8 +- src/xrpld/rpc/detail/RippleLineCache.cpp | 2 +- src/xrpld/rpc/detail/Role.cpp | 4 +- src/xrpld/rpc/detail/ServerHandler.cpp | 18 +- src/xrpld/rpc/detail/TransactionSign.cpp | 27 +- src/xrpld/rpc/handlers/AccountLines.cpp | 2 +- src/xrpld/rpc/handlers/AccountObjects.cpp | 2 +- src/xrpld/rpc/handlers/AccountOffers.cpp | 2 +- src/xrpld/rpc/handlers/AccountTx.cpp | 22 +- src/xrpld/rpc/handlers/CanDelete.cpp | 2 +- src/xrpld/rpc/handlers/GatewayBalances.cpp | 2 +- src/xrpld/rpc/handlers/GetAggregatePrice.cpp | 6 +- src/xrpld/rpc/handlers/GetCounts.cpp | 2 +- src/xrpld/rpc/handlers/GetCounts.h | 2 +- src/xrpld/rpc/handlers/LedgerAccept.cpp | 2 +- src/xrpld/rpc/handlers/LedgerData.cpp | 6 +- src/xrpld/rpc/handlers/LedgerDiff.cpp | 22 +- src/xrpld/rpc/handlers/LedgerEntry.cpp | 10 +- src/xrpld/rpc/handlers/LedgerEntryHelpers.h | 34 +- src/xrpld/rpc/handlers/LedgerHandler.cpp | 28 +- src/xrpld/rpc/handlers/LedgerHandler.h | 2 +- src/xrpld/rpc/handlers/LogLevel.cpp | 4 +- src/xrpld/rpc/handlers/NoRippleCheck.cpp | 9 +- src/xrpld/rpc/handlers/OwnerInfo.cpp | 2 +- src/xrpld/rpc/handlers/PathFind.cpp | 4 +- src/xrpld/rpc/handlers/Peers.cpp | 2 +- src/xrpld/rpc/handlers/Random.cpp | 2 +- src/xrpld/rpc/handlers/RipplePathFind.cpp | 4 +- src/xrpld/rpc/handlers/ServerDefinitions.cpp | 2 +- src/xrpld/rpc/handlers/Stop.cpp | 2 +- src/xrpld/rpc/handlers/Subscribe.cpp | 4 +- src/xrpld/rpc/handlers/Tx.cpp | 11 +- src/xrpld/rpc/handlers/TxHistory.cpp | 2 +- src/xrpld/rpc/handlers/Unsubscribe.cpp | 4 +- src/xrpld/shamap/NodeFamily.cpp | 2 +- 469 files changed, 3915 insertions(+), 3965 deletions(-) create mode 100644 include/xrpl/protocol_autogen/.clang-tidy create mode 100644 src/tests/libxrpl/protocol_autogen/.clang-tidy delete mode 100644 src/tests/libxrpl/protocol_autogen/STObjectValidation.cpp delete mode 100644 src/tests/libxrpl/protocol_autogen/main.cpp diff --git a/.clang-tidy b/.clang-tidy index 36b59f43e3..9cfc08ff5b 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -87,16 +87,19 @@ Checks: "-*, # cppcoreguidelines-use-default-member-init, # has issues # cppcoreguidelines-virtual-class-destructor, # has issues hicpp-ignored-remove-result, - # misc-definitions-in-headers, # has issues + misc-const-correctness, + misc-definitions-in-headers, misc-header-include-cycle, misc-misplaced-const, + misc-redundant-expression, misc-static-assert, - # misc-throw-by-value-catch-by-reference, # has issues + misc-throw-by-value-catch-by-reference, misc-unused-alias-decls, misc-unused-using-decls, modernize-deprecated-headers, modernize-make-shared, modernize-make-unique, + llvm-namespace-comment, performance-faster-string-find, performance-for-range-copy, performance-implicit-conversion-in-loop, @@ -134,10 +137,7 @@ Checks: "-*, # --- # other checks that have issues that need to be resolved: # -# llvm-namespace-comment, -# misc-const-correctness, # misc-include-cleaner, -# misc-redundant-expression, # # readability-inconsistent-declaration-parameter-name, # in this codebase this check will break a lot of arg names # readability-static-accessed-through-instance, # this check is probably unnecessary. it makes the code less readable diff --git a/.github/workflows/reusable-clang-tidy-files.yml b/.github/workflows/reusable-clang-tidy-files.yml index 2abc9de43b..fcbb041ed9 100644 --- a/.github/workflows/reusable-clang-tidy-files.yml +++ b/.github/workflows/reusable-clang-tidy-files.yml @@ -80,7 +80,7 @@ jobs: env: TARGETS: ${{ inputs.files != '' && inputs.files || 'src tests' }} run: | - run-clang-tidy -j ${{ steps.nproc.outputs.nproc }} -p "${BUILD_DIR}" ${TARGETS} 2>&1 | tee clang-tidy-output.txt + run-clang-tidy -j ${{ steps.nproc.outputs.nproc }} -p "${BUILD_DIR}" -quiet -allow-no-checks ${TARGETS} 2>&1 | tee clang-tidy-output.txt - name: Upload clang-tidy output if: ${{ github.event.repository.visibility == 'public' && steps.run_clang_tidy.outcome != 'success' }} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8670b79db9..d19222dbf0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -270,14 +270,14 @@ Before running clang-tidy, you must build the project to generate required files Then run clang-tidy on your local changes: ``` -run-clang-tidy -p build src include tests +run-clang-tidy -p build -allow-no-checks src tests ``` This will check all source files in the `src`, `include` and `tests` directories using the compile commands from your `build` directory. If you wish to automatically fix whatever clang-tidy finds _and_ is capable of fixing, add `-fix` to the above command: ``` -run-clang-tidy -p build -fix src include tests +run-clang-tidy -p build -quiet -fix -allow-no-checks src tests ``` ## Contracts and instrumentation diff --git a/include/xrpl/basics/BasicConfig.h b/include/xrpl/basics/BasicConfig.h index f02bf07a83..eaa53f93d6 100644 --- a/include/xrpl/basics/BasicConfig.h +++ b/include/xrpl/basics/BasicConfig.h @@ -311,7 +311,7 @@ template bool set(T& target, T const& defaultValue, std::string const& name, Section const& section) { - bool found_and_valid = set(target, name, section); + bool const found_and_valid = set(target, name, section); if (!found_and_valid) target = defaultValue; return found_and_valid; diff --git a/include/xrpl/basics/IntrusiveRefCounts.h b/include/xrpl/basics/IntrusiveRefCounts.h index 3b2be5c625..5a51b3c3bf 100644 --- a/include/xrpl/basics/IntrusiveRefCounts.h +++ b/include/xrpl/basics/IntrusiveRefCounts.h @@ -448,7 +448,7 @@ inline void partialDestructorFinished(T** o) { T& self = **o; - IntrusiveRefCounts::RefCountPair p = + IntrusiveRefCounts::RefCountPair const p = self.refCounts.fetch_or(IntrusiveRefCounts::partialDestroyFinishedMask); XRPL_ASSERT( (!p.partialDestroyFinishedBit && p.partialDestroyStartedBit && !p.strong), diff --git a/include/xrpl/basics/SlabAllocator.h b/include/xrpl/basics/SlabAllocator.h index e0c6456c0f..17acbbaa87 100644 --- a/include/xrpl/basics/SlabAllocator.h +++ b/include/xrpl/basics/SlabAllocator.h @@ -94,7 +94,7 @@ class SlabAllocator std::uint8_t* ret; { - std::lock_guard l(m_); + std::lock_guard const l(m_); ret = l_; @@ -123,7 +123,7 @@ class SlabAllocator { XRPL_ASSERT(own(ptr), "xrpl::SlabAllocator::SlabBlock::deallocate : own input"); - std::lock_guard l(m_); + std::lock_guard const l(m_); // Use memcpy to avoid unaligned UB // (will optimize to equivalent code) @@ -210,7 +210,7 @@ public: // No slab can satisfy our request, so we attempt to allocate a new // one here: - std::size_t size = slabSize_; + std::size_t const size = slabSize_; // We want to allocate the memory at a 2 MiB boundary, to make it // possible to use hugepage mappings on Linux: diff --git a/include/xrpl/basics/StringUtilities.h b/include/xrpl/basics/StringUtilities.h index 9cf6cd315d..592eee6d53 100644 --- a/include/xrpl/basics/StringUtilities.h +++ b/include/xrpl/basics/StringUtilities.h @@ -66,12 +66,12 @@ strUnHex(std::size_t strSize, Iterator begin, Iterator end) while (iter != end) { - int cHigh = digitLookupTable[*iter++]; + int const cHigh = digitLookupTable[*iter++]; if (cHigh < 0) return {}; - int cLow = digitLookupTable[*iter++]; + int const cLow = digitLookupTable[*iter++]; if (cLow < 0) return {}; diff --git a/include/xrpl/basics/base_uint.h b/include/xrpl/basics/base_uint.h index 6d2a0b9939..4ce135c036 100644 --- a/include/xrpl/basics/base_uint.h +++ b/include/xrpl/basics/base_uint.h @@ -212,7 +212,7 @@ private: while (in != sv.end()) { std::uint32_t accum = {}; - for (std::uint32_t shift : {4u, 0u, 12u, 8u, 20u, 16u, 28u, 24u}) + for (std::uint32_t const shift : {4u, 0u, 12u, 8u, 20u, 16u, 28u, 24u}) { if (auto const result = hexCharToUInt(*in++, shift, accum); result != ParseResult::okay) @@ -444,7 +444,7 @@ public: for (int i = WIDTH; i--;) { - std::uint64_t n = carry + boost::endian::big_to_native(data_[i]) + + std::uint64_t const n = carry + boost::endian::big_to_native(data_[i]) + boost::endian::big_to_native(b.data_[i]); data_[i] = boost::endian::native_to_big(static_cast(n)); diff --git a/include/xrpl/basics/contract.h b/include/xrpl/basics/contract.h index f41c272b61..e2d6dafe55 100644 --- a/include/xrpl/basics/contract.h +++ b/include/xrpl/basics/contract.h @@ -54,7 +54,7 @@ Throw(Args&&... args) E e(std::forward(args)...); LogThrow(std::string("Throwing exception of type " + beast::type_name() + ": ") + e.what()); - throw e; + throw std::move(e); } /** Called when faulty logic causes a broken invariant. */ diff --git a/include/xrpl/basics/hardened_hash.h b/include/xrpl/basics/hardened_hash.h index b05ecda7a6..05e6ab417f 100644 --- a/include/xrpl/basics/hardened_hash.h +++ b/include/xrpl/basics/hardened_hash.h @@ -32,7 +32,7 @@ make_seed_pair() noexcept // state_t& operator=(state_t const&) = delete; }; static state_t state; - std::lock_guard lock(state.mutex); + std::lock_guard const lock(state.mutex); return {state.dist(state.gen), state.dist(state.gen)}; } diff --git a/include/xrpl/basics/random.h b/include/xrpl/basics/random.h index 399439c023..ae3a8c6ec6 100644 --- a/include/xrpl/basics/random.h +++ b/include/xrpl/basics/random.h @@ -14,11 +14,13 @@ namespace xrpl { #ifndef __INTELLISENSE__ static_assert( + // NOLINTNEXTLINE(misc-redundant-expression) std::is_integral::value && std::is_unsigned::value, "The Ripple default PRNG engine must return an unsigned integral type."); static_assert( + // NOLINTNEXTLINE(misc-redundant-expression) std::numeric_limits::max() >= std::numeric_limits::max(), "The Ripple default PRNG engine return must be at least 64 bits wide."); @@ -58,7 +60,7 @@ default_prng() thread_local beast::xor_shift_engine engine = [] { std::uint64_t seed; { - std::lock_guard lk(m); + std::lock_guard const lk(m); std::uniform_int_distribution distribution{1}; seed = distribution(seeder); } diff --git a/include/xrpl/beast/asio/io_latency_probe.h b/include/xrpl/beast/asio/io_latency_probe.h index 81c8bc0dfa..0718a32af7 100644 --- a/include/xrpl/beast/asio/io_latency_probe.h +++ b/include/xrpl/beast/asio/io_latency_probe.h @@ -83,7 +83,7 @@ public: void sample_one(Handler&& handler) { - std::lock_guard lock(m_mutex); + std::lock_guard const lock(m_mutex); if (m_cancel) throw std::logic_error("io_latency_probe is canceled"); boost::asio::post( @@ -98,7 +98,7 @@ public: void sample(Handler&& handler) { - std::lock_guard lock(m_mutex); + std::lock_guard const lock(m_mutex); if (m_cancel) throw std::logic_error("io_latency_probe is canceled"); boost::asio::post( @@ -122,14 +122,14 @@ private: void addref() { - std::lock_guard lock(m_mutex); + std::lock_guard const lock(m_mutex); ++m_count; } void release() { - std::lock_guard lock(m_mutex); + std::lock_guard const lock(m_mutex); if (--m_count == 0) m_cond.notify_all(); } @@ -192,7 +192,7 @@ private: m_handler(elapsed); { - std::lock_guard lock(m_probe->m_mutex); + std::lock_guard const lock(m_probe->m_mutex); if (m_probe->m_cancel) return; } diff --git a/include/xrpl/beast/container/aged_map.h b/include/xrpl/beast/container/aged_map.h index e9505f2763..3815f44329 100644 --- a/include/xrpl/beast/container/aged_map.h +++ b/include/xrpl/beast/container/aged_map.h @@ -16,4 +16,4 @@ template < class Allocator = std::allocator>> using aged_map = detail::aged_ordered_container; -} +} // namespace beast diff --git a/include/xrpl/beast/container/aged_multimap.h b/include/xrpl/beast/container/aged_multimap.h index 7625694f66..bb098b63b2 100644 --- a/include/xrpl/beast/container/aged_multimap.h +++ b/include/xrpl/beast/container/aged_multimap.h @@ -16,4 +16,4 @@ template < class Allocator = std::allocator>> using aged_multimap = detail::aged_ordered_container; -} +} // namespace beast diff --git a/include/xrpl/beast/container/aged_multiset.h b/include/xrpl/beast/container/aged_multiset.h index 8d906c694f..60682db0ca 100644 --- a/include/xrpl/beast/container/aged_multiset.h +++ b/include/xrpl/beast/container/aged_multiset.h @@ -15,4 +15,4 @@ template < class Allocator = std::allocator> using aged_multiset = detail::aged_ordered_container; -} +} // namespace beast diff --git a/include/xrpl/beast/container/aged_set.h b/include/xrpl/beast/container/aged_set.h index 2c601f5f41..76ff40b63a 100644 --- a/include/xrpl/beast/container/aged_set.h +++ b/include/xrpl/beast/container/aged_set.h @@ -15,4 +15,4 @@ template < class Allocator = std::allocator> using aged_set = detail::aged_ordered_container; -} +} // namespace beast diff --git a/include/xrpl/beast/container/aged_unordered_map.h b/include/xrpl/beast/container/aged_unordered_map.h index 520ffe5848..ea53320e91 100644 --- a/include/xrpl/beast/container/aged_unordered_map.h +++ b/include/xrpl/beast/container/aged_unordered_map.h @@ -17,4 +17,4 @@ template < class Allocator = std::allocator>> using aged_unordered_map = detail::aged_unordered_container; -} +} // namespace beast diff --git a/include/xrpl/beast/container/aged_unordered_multimap.h b/include/xrpl/beast/container/aged_unordered_multimap.h index dc6338949b..9cb1443cad 100644 --- a/include/xrpl/beast/container/aged_unordered_multimap.h +++ b/include/xrpl/beast/container/aged_unordered_multimap.h @@ -17,4 +17,4 @@ template < class Allocator = std::allocator>> using aged_unordered_multimap = detail::aged_unordered_container; -} +} // namespace beast diff --git a/include/xrpl/beast/container/aged_unordered_multiset.h b/include/xrpl/beast/container/aged_unordered_multiset.h index b251f20077..ced01987aa 100644 --- a/include/xrpl/beast/container/aged_unordered_multiset.h +++ b/include/xrpl/beast/container/aged_unordered_multiset.h @@ -17,4 +17,4 @@ template < using aged_unordered_multiset = detail::aged_unordered_container; -} +} // namespace beast diff --git a/include/xrpl/beast/container/aged_unordered_set.h b/include/xrpl/beast/container/aged_unordered_set.h index a1c032e159..3f4575f6bc 100644 --- a/include/xrpl/beast/container/aged_unordered_set.h +++ b/include/xrpl/beast/container/aged_unordered_set.h @@ -16,4 +16,4 @@ template < class Allocator = std::allocator> using aged_unordered_set = detail::aged_unordered_container; -} +} // namespace beast diff --git a/include/xrpl/beast/core/List.h b/include/xrpl/beast/core/List.h index 504dec4c4a..560467c8dd 100644 --- a/include/xrpl/beast/core/List.h +++ b/include/xrpl/beast/core/List.h @@ -449,7 +449,7 @@ public: iterator erase(iterator pos) noexcept { - Node* node = &*pos; + Node const* node = &*pos; ++pos; node->m_next->m_prev = node->m_prev; node->m_prev->m_next = node->m_next; diff --git a/include/xrpl/beast/test/yield_to.h b/include/xrpl/beast/test/yield_to.h index 6c49c4a89c..918ca3c0cc 100644 --- a/include/xrpl/beast/test/yield_to.h +++ b/include/xrpl/beast/test/yield_to.h @@ -114,7 +114,7 @@ enable_yield_to::spawn(F0&& f, FN&&... fn) boost::context::fixedsize_stack(2 * 1024 * 1024), [&](yield_context yield) { f(yield); - std::lock_guard lock{m_}; + std::lock_guard const lock{m_}; if (--running_ == 0) cv_.notify_all(); }, diff --git a/include/xrpl/beast/unit_test/runner.h b/include/xrpl/beast/unit_test/runner.h index 90d8a2f4b5..c8a6956732 100644 --- a/include/xrpl/beast/unit_test/runner.h +++ b/include/xrpl/beast/unit_test/runner.h @@ -228,7 +228,7 @@ template void runner::testcase(std::string const& name) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); // Name may not be empty BOOST_ASSERT(default_ || !name.empty()); // Forgot to call pass or fail @@ -244,7 +244,7 @@ template void runner::pass() { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); if (default_) testcase(""); on_pass(); @@ -255,7 +255,7 @@ template void runner::fail(std::string const& reason) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); if (default_) testcase(""); on_fail(reason); @@ -267,7 +267,7 @@ template void runner::log(std::string const& s) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); if (default_) testcase(""); on_log(s); diff --git a/include/xrpl/beast/unit_test/suite.h b/include/xrpl/beast/unit_test/suite.h index 9031f9833e..fa5157e126 100644 --- a/include/xrpl/beast/unit_test/suite.h +++ b/include/xrpl/beast/unit_test/suite.h @@ -300,7 +300,7 @@ private: static suite** p_this_suite() { - static suite* pts = nullptr; + static suite* pts = nullptr; // NOLINT(misc-const-correctness) return &pts; } diff --git a/include/xrpl/beast/utility/Zero.h b/include/xrpl/beast/utility/Zero.h index 00e91a1a47..3b50b3fe00 100644 --- a/include/xrpl/beast/utility/Zero.h +++ b/include/xrpl/beast/utility/Zero.h @@ -28,7 +28,7 @@ struct Zero namespace { static constexpr Zero zero{}; -} +} // namespace /** Default implementation of signum calls the method on the class. */ template diff --git a/include/xrpl/core/ClosureCounter.h b/include/xrpl/core/ClosureCounter.h index 6802a03f3d..f0f277cc0e 100644 --- a/include/xrpl/core/ClosureCounter.h +++ b/include/xrpl/core/ClosureCounter.h @@ -56,7 +56,7 @@ private: // a lock. This removes a small timing window that occurs if the // waiting thread is handling a spurious wakeup when closureCount_ // drops to zero. - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; // Update closureCount_. Notify if stopping and closureCount_ == 0. if ((--closureCount_ == 0) && waitForClosures_) @@ -168,7 +168,7 @@ public: { std::optional> ret; - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; if (!waitForClosures_) ret.emplace(*this, std::forward(closure)); @@ -191,7 +191,7 @@ public: bool joined() const { - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; return waitForClosures_; } }; diff --git a/include/xrpl/core/JobQueue.h b/include/xrpl/core/JobQueue.h index fdb708ee57..994e2b424c 100644 --- a/include/xrpl/core/JobQueue.h +++ b/include/xrpl/core/JobQueue.h @@ -16,7 +16,7 @@ namespace xrpl { namespace perf { class PerfLog; -} +} // namespace perf class Logs; struct Coro_create_t diff --git a/include/xrpl/core/JobTypes.h b/include/xrpl/core/JobTypes.h index 4dc2fd96cd..98de97a1b4 100644 --- a/include/xrpl/core/JobTypes.h +++ b/include/xrpl/core/JobTypes.h @@ -24,7 +24,7 @@ private: std::chrono::milliseconds{0}) { using namespace std::chrono_literals; - int maxLimit = std::numeric_limits::max(); + int const maxLimit = std::numeric_limits::max(); auto add = [this]( JobType jt, diff --git a/include/xrpl/core/PeerReservationTable.h b/include/xrpl/core/PeerReservationTable.h index ffaef2fa08..6d861e5fbe 100644 --- a/include/xrpl/core/PeerReservationTable.h +++ b/include/xrpl/core/PeerReservationTable.h @@ -67,7 +67,7 @@ public: bool contains(PublicKey const& nodeId) { - std::lock_guard lock(this->mutex_); + std::lock_guard const lock(this->mutex_); return table_.find({nodeId}) != table_.end(); } diff --git a/include/xrpl/core/PerfLog.h b/include/xrpl/core/PerfLog.h index 64bdb3b625..8da6a313c8 100644 --- a/include/xrpl/core/PerfLog.h +++ b/include/xrpl/core/PerfLog.h @@ -14,7 +14,7 @@ namespace beast { class Journal; -} +} // namespace beast namespace xrpl { class Application; diff --git a/include/xrpl/core/ServiceRegistry.h b/include/xrpl/core/ServiceRegistry.h index 9f2555dc34..8b7d4b4464 100644 --- a/include/xrpl/core/ServiceRegistry.h +++ b/include/xrpl/core/ServiceRegistry.h @@ -11,13 +11,13 @@ namespace xrpl { // Forward declarations namespace NodeStore { class Database; -} +} // namespace NodeStore namespace Resource { class Manager; -} +} // namespace Resource namespace perf { class PerfLog; -} +} // namespace perf // This is temporary until we migrate all code to use ServiceRegistry. class Application; diff --git a/include/xrpl/core/detail/Workers.h b/include/xrpl/core/detail/Workers.h index 8d898e35c0..7925d11e62 100644 --- a/include/xrpl/core/detail/Workers.h +++ b/include/xrpl/core/detail/Workers.h @@ -13,7 +13,7 @@ namespace xrpl { namespace perf { class PerfLog; -} +} // namespace perf /** * `Workers` is effectively a thread pool. The constructor takes a "callback" diff --git a/include/xrpl/core/detail/semaphore.h b/include/xrpl/core/detail/semaphore.h index fad3bf5e29..b3bee00588 100644 --- a/include/xrpl/core/detail/semaphore.h +++ b/include/xrpl/core/detail/semaphore.h @@ -55,7 +55,7 @@ public: void notify() { - std::lock_guard lock{m_mutex}; + std::lock_guard const lock{m_mutex}; ++m_count; m_cond.notify_one(); } diff --git a/include/xrpl/json/json_value.h b/include/xrpl/json/json_value.h index fc7625d67a..ef1d0fbcb8 100644 --- a/include/xrpl/json/json_value.h +++ b/include/xrpl/json/json_value.h @@ -641,7 +641,7 @@ public: SelfType operator++(int) { - SelfType temp(*this); + SelfType const temp(*this); ++*this; return temp; } @@ -649,7 +649,7 @@ public: SelfType operator--(int) { - SelfType temp(*this); + SelfType const temp(*this); --*this; return temp; } diff --git a/include/xrpl/ledger/AmendmentTable.h b/include/xrpl/ledger/AmendmentTable.h index fb90d6e859..6ecfe2a240 100644 --- a/include/xrpl/ledger/AmendmentTable.h +++ b/include/xrpl/ledger/AmendmentTable.h @@ -143,7 +143,7 @@ public: // Inject appropriate pseudo-transactions for (auto const& it : actions) { - STTx amendTx(ttAMENDMENT, [&it, seq = lastClosedLedger->seq() + 1](auto& obj) { + STTx const amendTx(ttAMENDMENT, [&it, seq = lastClosedLedger->seq() + 1](auto& obj) { obj.setAccountID(sfAccount, AccountID()); obj.setFieldH256(sfAmendment, it.first); obj.setFieldU32(sfLedgerSequence, seq); diff --git a/include/xrpl/ledger/CachedSLEs.h b/include/xrpl/ledger/CachedSLEs.h index 2909501b1d..c05aab8856 100644 --- a/include/xrpl/ledger/CachedSLEs.h +++ b/include/xrpl/ledger/CachedSLEs.h @@ -6,4 +6,4 @@ namespace xrpl { using CachedSLEs = TaggedCache; -} +} // namespace xrpl diff --git a/include/xrpl/ledger/PendingSaves.h b/include/xrpl/ledger/PendingSaves.h index 76958fc78a..4e952547da 100644 --- a/include/xrpl/ledger/PendingSaves.h +++ b/include/xrpl/ledger/PendingSaves.h @@ -31,7 +31,7 @@ public: bool startWork(LedgerIndex seq) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); auto it = map_.find(seq); @@ -54,7 +54,7 @@ public: void finishWork(LedgerIndex seq) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); map_.erase(seq); await_.notify_all(); @@ -64,7 +64,7 @@ public: bool pending(LedgerIndex seq) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); return map_.find(seq) != map_.end(); } @@ -117,7 +117,7 @@ public: std::map getSnapshot() const { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); return map_; } diff --git a/include/xrpl/nodestore/detail/varint.h b/include/xrpl/nodestore/detail/varint.h index 98f8d8ff08..c84ed383ed 100644 --- a/include/xrpl/nodestore/detail/varint.h +++ b/include/xrpl/nodestore/detail/varint.h @@ -82,6 +82,7 @@ template std::size_t write_varint(void* p0, std::size_t v) { + // NOLINTNEXTLINE(misc-const-correctness) std::uint8_t* p = reinterpret_cast(p0); do { diff --git a/include/xrpl/protocol/AmountConversions.h b/include/xrpl/protocol/AmountConversions.h index e1a224dac9..7e41eff41a 100644 --- a/include/xrpl/protocol/AmountConversions.h +++ b/include/xrpl/protocol/AmountConversions.h @@ -102,7 +102,7 @@ template T toAmount(Issue const& issue, Number const& n, Number::rounding_mode mode = Number::getround()) { - saveNumberRoundMode rm(Number::getround()); + saveNumberRoundMode const rm(Number::getround()); if (isXRP(issue)) Number::setround(mode); diff --git a/include/xrpl/protocol/Issue.h b/include/xrpl/protocol/Issue.h index c8e598a540..7bd01185c9 100644 --- a/include/xrpl/protocol/Issue.h +++ b/include/xrpl/protocol/Issue.h @@ -96,7 +96,7 @@ operator<=>(Issue const& lhs, Issue const& rhs) inline Issue const& xrpIssue() { - static Issue issue{xrpCurrency(), xrpAccount()}; + static Issue const issue{xrpCurrency(), xrpAccount()}; return issue; } @@ -104,7 +104,7 @@ xrpIssue() inline Issue const& noIssue() { - static Issue issue{noCurrency(), noAccount()}; + static Issue const issue{noCurrency(), noAccount()}; return issue; } diff --git a/include/xrpl/protocol/Quality.h b/include/xrpl/protocol/Quality.h index 09b0f4e7cb..0ec797da0c 100644 --- a/include/xrpl/protocol/Quality.h +++ b/include/xrpl/protocol/Quality.h @@ -304,8 +304,8 @@ Quality::ceil_TAmounts_helper( // Use the existing STAmount implementation for now, but consider // replacing with code specific to IOUAMount and XRPAmount - Amounts stAmt(toSTAmount(amount.in), toSTAmount(amount.out)); - STAmount stLim(toSTAmount(limit)); + Amounts const stAmt(toSTAmount(amount.in), toSTAmount(amount.out)); + STAmount const stLim(toSTAmount(limit)); Amounts const stRes = ((*this).*ceil_function)(stAmt, stLim, roundUp...); return TAmounts(toAmount(stRes.in), toAmount(stRes.out)); } diff --git a/include/xrpl/protocol/RippleLedgerHash.h b/include/xrpl/protocol/RippleLedgerHash.h index 2a51298d3d..9dab644663 100644 --- a/include/xrpl/protocol/RippleLedgerHash.h +++ b/include/xrpl/protocol/RippleLedgerHash.h @@ -6,4 +6,4 @@ namespace xrpl { using LedgerHash = uint256; -} +} // namespace xrpl diff --git a/include/xrpl/protocol/STAmount.h b/include/xrpl/protocol/STAmount.h index dadeec096f..9cd7221d1e 100644 --- a/include/xrpl/protocol/STAmount.h +++ b/include/xrpl/protocol/STAmount.h @@ -532,7 +532,7 @@ STAmount::fromNumber(A const& a, Number const& number) { bool const negative = number.mantissa() < 0; Number const working{negative ? -number : number}; - Asset asset{a}; + Asset const asset{a}; if (asset.integral()) { std::uint64_t const intValue = static_cast(working); @@ -716,7 +716,7 @@ roundToAsset( std::int32_t scale, Number::rounding_mode rounding = Number::getround()) { - NumberRoundModeGuard mg(rounding); + NumberRoundModeGuard const mg(rounding); STAmount const ret{asset, value}; if (ret.integral()) return ret; diff --git a/include/xrpl/protocol/STBase.h b/include/xrpl/protocol/STBase.h index 7f06b01ca4..8edeb26424 100644 --- a/include/xrpl/protocol/STBase.h +++ b/include/xrpl/protocol/STBase.h @@ -83,7 +83,7 @@ to_json(T const& t) namespace detail { class STVar; -} +} // namespace detail // VFALCO TODO fix this restriction on copy assignment. // diff --git a/include/xrpl/protocol/STLedgerEntry.h b/include/xrpl/protocol/STLedgerEntry.h index dde7d49ebd..994a616210 100644 --- a/include/xrpl/protocol/STLedgerEntry.h +++ b/include/xrpl/protocol/STLedgerEntry.h @@ -8,7 +8,7 @@ namespace xrpl { class Rules; namespace test { class Invariants_test; -} +} // namespace test class STLedgerEntry final : public STObject, public CountedObject { diff --git a/include/xrpl/protocol/STObject.h b/include/xrpl/protocol/STObject.h index ecfae0086b..3a7d3f4b16 100644 --- a/include/xrpl/protocol/STObject.h +++ b/include/xrpl/protocol/STObject.h @@ -1153,7 +1153,7 @@ STObject::getFieldByValue(SField const& field) const if (!rf) throwFieldNotFound(field); - SerializedTypeID id = rf->getSType(); + SerializedTypeID const id = rf->getSType(); if (id == STI_NOTPRESENT) return V(); // optional field not present @@ -1180,7 +1180,7 @@ STObject::getFieldByConstRef(SField const& field, V const& empty) const if (!rf) throwFieldNotFound(field); - SerializedTypeID id = rf->getSType(); + SerializedTypeID const id = rf->getSType(); if (id == STI_NOTPRESENT) return empty; // optional field not present diff --git a/include/xrpl/protocol/Serializer.h b/include/xrpl/protocol/Serializer.h index 75f5dbdf96..2d3489fe7b 100644 --- a/include/xrpl/protocol/Serializer.h +++ b/include/xrpl/protocol/Serializer.h @@ -69,7 +69,7 @@ public: int add32(T i) { - int ret = mData.size(); + int const ret = mData.size(); mData.push_back(static_cast((i >> 24) & 0xff)); mData.push_back(static_cast((i >> 16) & 0xff)); mData.push_back(static_cast((i >> 8) & 0xff)); @@ -85,7 +85,7 @@ public: int add64(T i) { - int ret = mData.size(); + int const ret = mData.size(); mData.push_back(static_cast((i >> 56) & 0xff)); mData.push_back(static_cast((i >> 48) & 0xff)); mData.push_back(static_cast((i >> 40) & 0xff)); @@ -299,7 +299,7 @@ template int Serializer::addVL(Iter begin, Iter end, int len) { - int ret = addEncoded(len); + int const ret = addEncoded(len); for (; begin != end; ++begin) { addRaw(begin->data(), begin->size()); diff --git a/include/xrpl/protocol/TxSearched.h b/include/xrpl/protocol/TxSearched.h index 71bd75005b..c3359ee5ac 100644 --- a/include/xrpl/protocol/TxSearched.h +++ b/include/xrpl/protocol/TxSearched.h @@ -4,4 +4,4 @@ namespace xrpl { enum class TxSearched { All, Some, Unknown }; -} +} // namespace xrpl diff --git a/include/xrpl/protocol/detail/token_errors.h b/include/xrpl/protocol/detail/token_errors.h index 686851f508..54b283c41a 100644 --- a/include/xrpl/protocol/detail/token_errors.h +++ b/include/xrpl/protocol/detail/token_errors.h @@ -15,7 +15,7 @@ enum class TokenCodecErrc { overflowAdd, unknown, }; -} +} // namespace xrpl namespace std { template <> @@ -69,7 +69,7 @@ public: inline xrpl::detail::TokenCodecErrcCategory const& TokenCodecErrcCategory() { - static xrpl::detail::TokenCodecErrcCategory c; + static xrpl::detail::TokenCodecErrcCategory const c; return c; } diff --git a/include/xrpl/protocol_autogen/.clang-tidy b/include/xrpl/protocol_autogen/.clang-tidy new file mode 100644 index 0000000000..fbc003598d --- /dev/null +++ b/include/xrpl/protocol_autogen/.clang-tidy @@ -0,0 +1,3 @@ +# This disables all checks for this directory and its subdirectories +Checks: "-*" +InheritParentConfig: false diff --git a/include/xrpl/rdb/DatabaseCon.h b/include/xrpl/rdb/DatabaseCon.h index bd7b9ca803..7400593214 100644 --- a/include/xrpl/rdb/DatabaseCon.h +++ b/include/xrpl/rdb/DatabaseCon.h @@ -14,7 +14,7 @@ namespace soci { class session; -} +} // namespace soci namespace xrpl { diff --git a/include/xrpl/rdb/SociDB.h b/include/xrpl/rdb/SociDB.h index 83758677b9..9c575359c1 100644 --- a/include/xrpl/rdb/SociDB.h +++ b/include/xrpl/rdb/SociDB.h @@ -25,7 +25,7 @@ namespace sqlite_api { struct sqlite3; -} +} // namespace sqlite_api namespace xrpl { diff --git a/include/xrpl/resource/detail/Logic.h b/include/xrpl/resource/detail/Logic.h index 9a7959f481..66c47bc538 100644 --- a/include/xrpl/resource/detail/Logic.h +++ b/include/xrpl/resource/detail/Logic.h @@ -93,7 +93,7 @@ public: Entry* entry(nullptr); { - std::lock_guard _(lock_); + std::lock_guard const _(lock_); auto [resultIt, resultInserted] = table_.emplace( std::piecewise_construct, std::make_tuple(kindInbound, address.at_port(0)), // Key @@ -123,7 +123,7 @@ public: Entry* entry(nullptr); { - std::lock_guard _(lock_); + std::lock_guard const _(lock_); auto [resultIt, resultInserted] = table_.emplace( std::piecewise_construct, std::make_tuple(kindOutbound, address), // Key @@ -156,7 +156,7 @@ public: Entry* entry(nullptr); { - std::lock_guard _(lock_); + std::lock_guard const _(lock_); auto [resultIt, resultInserted] = table_.emplace( std::piecewise_construct, std::make_tuple(kindUnlimited, address.at_port(1)), // Key @@ -191,11 +191,11 @@ public: clock_type::time_point const now(m_clock.now()); Json::Value ret(Json::objectValue); - std::lock_guard _(lock_); + std::lock_guard const _(lock_); for (auto& inboundEntry : inbound_) { - int localBalance = inboundEntry.local_balance.value(now); + int const localBalance = inboundEntry.local_balance.value(now); if ((localBalance + inboundEntry.remote_balance) >= threshold) { Json::Value& entry = (ret[inboundEntry.to_string()] = Json::objectValue); @@ -206,7 +206,7 @@ public: } for (auto& outboundEntry : outbound_) { - int localBalance = outboundEntry.local_balance.value(now); + int const localBalance = outboundEntry.local_balance.value(now); if ((localBalance + outboundEntry.remote_balance) >= threshold) { Json::Value& entry = (ret[outboundEntry.to_string()] = Json::objectValue); @@ -217,7 +217,7 @@ public: } for (auto& adminEntry : admin_) { - int localBalance = adminEntry.local_balance.value(now); + int const localBalance = adminEntry.local_balance.value(now); if ((localBalance + adminEntry.remote_balance) >= threshold) { Json::Value& entry = (ret[adminEntry.to_string()] = Json::objectValue); @@ -236,7 +236,7 @@ public: clock_type::time_point const now(m_clock.now()); Gossip gossip; - std::lock_guard _(lock_); + std::lock_guard const _(lock_); gossip.items.reserve(inbound_.size()); @@ -261,7 +261,7 @@ public: { auto const elapsed = m_clock.now(); { - std::lock_guard _(lock_); + std::lock_guard const _(lock_); auto [resultIt, resultInserted] = importTable_.emplace( std::piecewise_construct, std::make_tuple(origin), // Key @@ -318,7 +318,7 @@ public: void periodicActivity() { - std::lock_guard _(lock_); + std::lock_guard const _(lock_); auto const elapsed = m_clock.now(); @@ -374,7 +374,7 @@ public: void erase(Table::iterator iter) { - std::lock_guard _(lock_); + std::lock_guard const _(lock_); Entry& entry(iter->second); XRPL_ASSERT(entry.refcount == 0, "xrpl::Resource::Logic::erase : entry not used"); inactive_.erase(inactive_.iterator_to(entry)); @@ -384,14 +384,14 @@ public: void acquire(Entry& entry) { - std::lock_guard _(lock_); + std::lock_guard const _(lock_); ++entry.refcount; } void release(Entry& entry) { - std::lock_guard _(lock_); + std::lock_guard const _(lock_); if (--entry.refcount == 0) { JLOG(m_journal.debug()) << "Inactive " << entry; @@ -442,7 +442,7 @@ public: if (!context.empty()) context = " (" + context + ")"; - std::lock_guard _(lock_); + std::lock_guard const _(lock_); clock_type::time_point const now(m_clock.now()); int const balance(entry.add(fee.cost(), now)); JLOG(getStream(fee.cost(), m_journal)) << "Charging " << entry << " for " << fee << context; @@ -455,7 +455,7 @@ public: if (entry.isUnlimited()) return false; - std::lock_guard _(lock_); + std::lock_guard const _(lock_); bool notify(false); auto const elapsed = m_clock.now(); if (entry.balance(m_clock.now()) >= warningThreshold && elapsed != entry.lastWarningTime) @@ -478,7 +478,7 @@ public: if (entry.isUnlimited()) return false; - std::lock_guard _(lock_); + std::lock_guard const _(lock_); bool drop(false); clock_type::time_point const now(m_clock.now()); int const balance(entry.balance(now)); @@ -500,7 +500,7 @@ public: int balance(Entry& entry) { - std::lock_guard _(lock_); + std::lock_guard const _(lock_); return entry.balance(m_clock.now()); } @@ -529,7 +529,7 @@ public: { clock_type::time_point const now(m_clock.now()); - std::lock_guard _(lock_); + std::lock_guard const _(lock_); { beast::PropertyStream::Set s("inbound", map); diff --git a/include/xrpl/server/LoadFeeTrack.h b/include/xrpl/server/LoadFeeTrack.h index fc031a1833..08be3e0406 100644 --- a/include/xrpl/server/LoadFeeTrack.h +++ b/include/xrpl/server/LoadFeeTrack.h @@ -39,28 +39,28 @@ public: setRemoteFee(std::uint32_t f) { JLOG(j_.trace()) << "setRemoteFee: " << f; - std::lock_guard sl(lock_); + std::lock_guard const sl(lock_); remoteTxnLoadFee_ = f; } std::uint32_t getRemoteFee() const { - std::lock_guard sl(lock_); + std::lock_guard const sl(lock_); return remoteTxnLoadFee_; } std::uint32_t getLocalFee() const { - std::lock_guard sl(lock_); + std::lock_guard const sl(lock_); return localTxnLoadFee_; } std::uint32_t getClusterFee() const { - std::lock_guard sl(lock_); + std::lock_guard const sl(lock_); return clusterTxnLoadFee_; } @@ -73,14 +73,14 @@ public: std::uint32_t getLoadFactor() const { - std::lock_guard sl(lock_); + std::lock_guard const sl(lock_); return std::max({clusterTxnLoadFee_, localTxnLoadFee_, remoteTxnLoadFee_}); } std::pair getScalingFactors() const { - std::lock_guard sl(lock_); + std::lock_guard const sl(lock_); return std::make_pair( std::max(localTxnLoadFee_, remoteTxnLoadFee_), @@ -91,7 +91,7 @@ public: setClusterFee(std::uint32_t fee) { JLOG(j_.trace()) << "setClusterFee: " << fee; - std::lock_guard sl(lock_); + std::lock_guard const sl(lock_); clusterTxnLoadFee_ = fee; } @@ -103,14 +103,14 @@ public: bool isLoadedLocal() const { - std::lock_guard sl(lock_); + std::lock_guard const sl(lock_); return (raiseCount_ != 0) || (localTxnLoadFee_ != lftNormalFee); } bool isLoadedCluster() const { - std::lock_guard sl(lock_); + std::lock_guard const sl(lock_); return (raiseCount_ != 0) || (localTxnLoadFee_ != lftNormalFee) || (clusterTxnLoadFee_ != lftNormalFee); } diff --git a/include/xrpl/server/Manifest.h b/include/xrpl/server/Manifest.h index 7f1bba921e..02c370561a 100644 --- a/include/xrpl/server/Manifest.h +++ b/include/xrpl/server/Manifest.h @@ -401,7 +401,7 @@ public: void for_each_manifest(Function&& f) const { - std::shared_lock lock{mutex_}; + std::shared_lock const lock{mutex_}; for (auto const& [_, manifest] : map_) { (void)_; @@ -429,7 +429,7 @@ public: void for_each_manifest(PreFun&& pf, EachFun&& f) const { - std::shared_lock lock{mutex_}; + std::shared_lock const lock{mutex_}; pf(map_.size()); for (auto const& [_, manifest] : map_) { diff --git a/include/xrpl/server/Port.h b/include/xrpl/server/Port.h index 1dfa93b0a7..b00f4f4041 100644 --- a/include/xrpl/server/Port.h +++ b/include/xrpl/server/Port.h @@ -19,7 +19,7 @@ namespace boost { namespace asio { namespace ssl { class context; -} +} // namespace ssl } // namespace asio } // namespace boost diff --git a/include/xrpl/server/detail/BaseHTTPPeer.h b/include/xrpl/server/detail/BaseHTTPPeer.h index f900261b84..8354e63c64 100644 --- a/include/xrpl/server/detail/BaseHTTPPeer.h +++ b/include/xrpl/server/detail/BaseHTTPPeer.h @@ -300,7 +300,7 @@ BaseHTTPPeer::on_write(error_code const& ec, std::size_t bytes_tr return fail(ec, "write"); bytes_out_ += bytes_transferred; { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); wq2_.clear(); wq2_.reserve(wq_.size()); std::swap(wq2_, wq_); @@ -392,7 +392,7 @@ BaseHTTPPeer::write(void const* buf, std::size_t bytes) if (bytes == 0) return; if ([&] { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); wq_.emplace_back(buf, bytes); return wq_.size() == 1 && wq2_.size() == 0; }()) @@ -443,7 +443,7 @@ BaseHTTPPeer::complete() complete_ = true; { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); if (!wq_.empty() && !wq2_.empty()) return; } @@ -476,7 +476,7 @@ BaseHTTPPeer::close(bool graceful) { graceful_ = true; { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); if (!wq_.empty() || !wq2_.empty()) return; } diff --git a/include/xrpl/server/detail/BaseWSPeer.h b/include/xrpl/server/detail/BaseWSPeer.h index f415520e59..9213a955f0 100644 --- a/include/xrpl/server/detail/BaseWSPeer.h +++ b/include/xrpl/server/detail/BaseWSPeer.h @@ -418,7 +418,7 @@ BaseWSPeer::on_ping_pong( { if (kind == boost::beast::websocket::frame_type::pong) { - boost::beast::string_view p(payload_.begin()); + boost::beast::string_view const p(payload_.begin()); if (payload == p) { close_on_timer_ = false; diff --git a/include/xrpl/server/detail/io_list.h b/include/xrpl/server/detail/io_list.h index 5b1a02e039..f1cc04f683 100644 --- a/include/xrpl/server/detail/io_list.h +++ b/include/xrpl/server/detail/io_list.h @@ -165,7 +165,7 @@ io_list::work::destroy() return; std::function f; { - std::lock_guard lock(ios_->m_); + std::lock_guard const lock(ios_->m_); ios_->map_.erase(this); if (--ios_->n_ == 0 && ios_->closed_) { @@ -195,7 +195,7 @@ io_list::emplace(Args&&... args) auto sp = std::make_shared(std::forward(args)...); decltype(sp) dead; - std::lock_guard lock(m_); + std::lock_guard const lock(m_); if (!closed_) { ++n_; diff --git a/include/xrpl/shamap/SHAMapItem.h b/include/xrpl/shamap/SHAMapItem.h index dd098d88aa..da70e16db3 100644 --- a/include/xrpl/shamap/SHAMapItem.h +++ b/include/xrpl/shamap/SHAMapItem.h @@ -141,6 +141,7 @@ make_shamapitem(uint256 const& tag, Slice data) XRPL_ASSERT( data.size() <= megabytes(16), "xrpl::make_shamapitem : maximum input size"); + // NOLINTNEXTLINE(misc-const-correctness) std::uint8_t* raw = detail::slabber.allocate(data.size()); // If we can't grab memory from the slab allocators, we fall back to diff --git a/include/xrpl/tx/paths/Flow.h b/include/xrpl/tx/paths/Flow.h index 32e8c3611b..f37c9d56c3 100644 --- a/include/xrpl/tx/paths/Flow.h +++ b/include/xrpl/tx/paths/Flow.h @@ -9,7 +9,7 @@ namespace xrpl { namespace path { namespace detail { struct FlowDebugInfo; -} +} // namespace detail } // namespace path /** diff --git a/include/xrpl/tx/paths/RippleCalc.h b/include/xrpl/tx/paths/RippleCalc.h index 4fc4c54f2b..55f552a61f 100644 --- a/include/xrpl/tx/paths/RippleCalc.h +++ b/include/xrpl/tx/paths/RippleCalc.h @@ -13,7 +13,7 @@ namespace path { namespace detail { struct FlowDebugInfo; -} +} // namespace detail /** RippleCalc calculates the quality of a payment path. diff --git a/include/xrpl/tx/paths/detail/StrandFlow.h b/include/xrpl/tx/paths/detail/StrandFlow.h index 2a94b9b968..a67542269e 100644 --- a/include/xrpl/tx/paths/detail/StrandFlow.h +++ b/include/xrpl/tx/paths/detail/StrandFlow.h @@ -571,7 +571,7 @@ flow( std::size_t const maxTries = 1000; std::size_t curTry = 0; - std::uint32_t maxOffersToConsider = 1500; + std::uint32_t const maxOffersToConsider = 1500; std::uint32_t offersConsidered = 0; // There is a bug in gcc that incorrectly warns about using uninitialized diff --git a/include/xrpl/tx/transactors/dex/AMMHelpers.h b/include/xrpl/tx/transactors/dex/AMMHelpers.h index f389fd283b..55f27a3f06 100644 --- a/include/xrpl/tx/transactors/dex/AMMHelpers.h +++ b/include/xrpl/tx/transactors/dex/AMMHelpers.h @@ -22,7 +22,7 @@ reduceOffer(auto const& amount) static Number const reducedOfferPct(9999, -4); // Make sure the result is always less than amount or zero. - NumberRoundModeGuard mg(Number::towards_zero); + NumberRoundModeGuard const mg(Number::towards_zero); return amount * reducedOfferPct; } @@ -173,7 +173,7 @@ getAMMOfferStartWithTakerGets( if (targetQuality.rate() == beast::zero) return std::nullopt; - NumberRoundModeGuard mg(Number::to_nearest); + NumberRoundModeGuard const mg(Number::to_nearest); auto const f = feeMult(tfee); auto const a = 1; auto const b = pool.in * (1 - 1 / f) / targetQuality.rate() - 2 * pool.out; @@ -240,7 +240,7 @@ getAMMOfferStartWithTakerPays( if (targetQuality.rate() == beast::zero) return std::nullopt; - NumberRoundModeGuard mg(Number::to_nearest); + NumberRoundModeGuard const mg(Number::to_nearest); auto const f = feeMult(tfee); auto const& a = f; auto const b = pool.in * (1 + f); @@ -435,7 +435,7 @@ swapAssetIn(TAmounts const& pool, TIn const& assetIn, std::uint16_t t // 1-fee // maximize: // fee - saveNumberRoundMode _{Number::getround()}; + saveNumberRoundMode const _{Number::getround()}; Number::setround(Number::upward); auto const numerator = pool.in * pool.out; @@ -499,7 +499,7 @@ swapAssetOut(TAmounts const& pool, TOut const& assetOut, std::uint16_ // maximize: // tfee/100000 - saveNumberRoundMode _{Number::getround()}; + saveNumberRoundMode const _{Number::getround()}; Number::setround(Number::upward); auto const numerator = pool.in * pool.out; diff --git a/src/libxrpl/basics/Archive.cpp b/src/libxrpl/basics/Archive.cpp index a09d77d794..e77dabcd68 100644 --- a/src/libxrpl/basics/Archive.cpp +++ b/src/libxrpl/basics/Archive.cpp @@ -20,7 +20,7 @@ extractTarLz4(boost::filesystem::path const& src, boost::filesystem::path const& Throw("Invalid source file"); using archive_ptr = std::unique_ptr; - archive_ptr ar{archive_read_new(), [](struct archive* a) { archive_read_free(a); }}; + archive_ptr const ar{archive_read_new(), [](struct archive* a) { archive_read_free(a); }}; if (!ar) Throw("Failed to allocate archive"); @@ -36,7 +36,8 @@ extractTarLz4(boost::filesystem::path const& src, boost::filesystem::path const& Throw(archive_error_string(ar.get())); } - archive_ptr aw{archive_write_disk_new(), [](struct archive* a) { archive_write_free(a); }}; + archive_ptr const aw{ + archive_write_disk_new(), [](struct archive* a) { archive_write_free(a); }}; if (!aw) Throw("Failed to allocate archive"); diff --git a/src/libxrpl/basics/BasicConfig.cpp b/src/libxrpl/basics/BasicConfig.cpp index edc8bea7d9..ba10a575d9 100644 --- a/src/libxrpl/basics/BasicConfig.cpp +++ b/src/libxrpl/basics/BasicConfig.cpp @@ -126,7 +126,7 @@ BasicConfig::section(std::string const& name) Section const& BasicConfig::section(std::string const& name) const { - static Section none(""); + static Section const none(""); auto const iter = map_.find(name); if (iter == map_.end()) return none; diff --git a/src/libxrpl/basics/FileUtilities.cpp b/src/libxrpl/basics/FileUtilities.cpp index 73f2c2f10d..96ec3fa3ba 100644 --- a/src/libxrpl/basics/FileUtilities.cpp +++ b/src/libxrpl/basics/FileUtilities.cpp @@ -26,7 +26,7 @@ getFileContents( using namespace boost::filesystem; using namespace boost::system::errc; - path fullPath{canonical(sourcePath, ec)}; + path const fullPath{canonical(sourcePath, ec)}; if (ec) return {}; diff --git a/src/libxrpl/basics/Log.cpp b/src/libxrpl/basics/Log.cpp index 9cebd1f04a..f0a546ee75 100644 --- a/src/libxrpl/basics/Log.cpp +++ b/src/libxrpl/basics/Log.cpp @@ -119,7 +119,7 @@ Logs::open(boost::filesystem::path const& pathToLogFile) beast::Journal::Sink& Logs::get(std::string const& name) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); auto const result = sinks_.emplace(name, makeSink(name, thresh_)); return *result.first->second; } @@ -145,7 +145,7 @@ Logs::threshold() const void Logs::threshold(beast::severities::Severity thresh) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); thresh_ = thresh; for (auto& sink : sinks_) sink.second->threshold(thresh); @@ -155,7 +155,7 @@ std::vector> Logs::partition_severities() const { std::vector> list; - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); list.reserve(sinks_.size()); for (auto const& [name, sink] : sinks_) list.emplace_back(name, toString(fromSeverity(sink->threshold()))); @@ -171,7 +171,7 @@ Logs::write( { std::string s; format(s, text, level, partition); - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); file_.writeln(s); if (!silent_) std::cerr << s << '\n'; @@ -183,7 +183,7 @@ Logs::write( std::string Logs::rotate() { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); bool const wasOpened = file_.closeAndReopen(); if (wasOpened) return "The log file was closed and reopened."; @@ -411,7 +411,7 @@ public: std::unique_ptr set(std::unique_ptr sink) { - std::lock_guard _(m_); + std::lock_guard const _(m_); using std::swap; swap(holder_, sink); @@ -431,7 +431,7 @@ public: beast::Journal::Sink& get() { - std::lock_guard _(m_); + std::lock_guard const _(m_); return sink_.get(); } }; diff --git a/src/libxrpl/basics/Number.cpp b/src/libxrpl/basics/Number.cpp index f0655cd8a9..a8adabd5de 100644 --- a/src/libxrpl/basics/Number.cpp +++ b/src/libxrpl/basics/Number.cpp @@ -161,7 +161,7 @@ Number::Guard::push(T d) noexcept inline unsigned Number::Guard::pop() noexcept { - unsigned d = (digits_ & 0xF000'0000'0000'0000) >> 60; + unsigned const d = (digits_ & 0xF000'0000'0000'0000) >> 60; digits_ <<= 4; return d; } @@ -325,7 +325,7 @@ Number::externalToInternal(rep mantissa) // int128_t, negate that, and cast it back down to the internalrep // In practice, this is only going to cover the case of // std::numeric_limits::min(). - int128_t temp = mantissa; + int128_t const temp = mantissa; return static_cast(-temp); } @@ -530,7 +530,7 @@ Number::operator+=(Number const& y) uint128_t xm = mantissa_; auto xe = exponent_; - bool yn = y.negative_; + bool const yn = y.negative_; uint128_t ym = y.mantissa_; auto ye = y.exponent_; Guard g; @@ -644,14 +644,14 @@ Number::operator*=(Number const& y) // *m = mantissa // *e = exponent - bool xn = negative_; - int xs = xn ? -1 : 1; + bool const xn = negative_; + int const xs = xn ? -1 : 1; internalrep xm = mantissa_; auto xe = exponent_; - bool yn = y.negative_; - int ys = yn ? -1 : 1; - internalrep ym = y.mantissa_; + bool const yn = y.negative_; + int const ys = yn ? -1 : 1; + internalrep const ym = y.mantissa_; auto ye = y.exponent_; auto zm = uint128_t(xm) * uint128_t(ym); @@ -706,13 +706,13 @@ Number::operator/=(Number const& y) // *m = mantissa // *e = exponent - bool np = negative_; - int ns = (np ? -1 : 1); + bool const np = negative_; + int const ns = (np ? -1 : 1); auto nm = mantissa_; auto ne = exponent_; - bool dp = y.negative_; - int ds = (dp ? -1 : 1); + bool const dp = y.negative_; + int const ds = (dp ? -1 : 1); auto dm = y.mantissa_; auto de = y.exponent_; @@ -728,7 +728,7 @@ Number::operator/=(Number const& y) // f can be up to 10^(38-19) = 10^19 safely static_assert(smallRange.log == 15); static_assert(largeRange.log == 18); - bool small = Number::getMantissaScale() == MantissaRange::small; + bool const small = Number::getMantissaScale() == MantissaRange::small; uint128_t const f = small ? 100'000'000'000'000'000 : 10'000'000'000'000'000'000ULL; XRPL_ASSERT_PARTS(f >= minMantissa * 10, "Number::operator/=", "factor expected size"); @@ -980,8 +980,8 @@ root(Number f, unsigned d) auto const di = static_cast(d); auto ex = [e = e, di = di]() // Euclidean remainder of e/d { - int k = (e >= 0 ? e : e - (di - 1)) / di; - int k2 = e - (k * di); + int const k = (e >= 0 ? e : e - (di - 1)) / di; + int const k2 = e - (k * di); if (k2 == 0) return 0; return di - k2; diff --git a/src/libxrpl/basics/ResolverAsio.cpp b/src/libxrpl/basics/ResolverAsio.cpp index aa1cb1470d..305bdb6451 100644 --- a/src/libxrpl/basics/ResolverAsio.cpp +++ b/src/libxrpl/basics/ResolverAsio.cpp @@ -152,7 +152,7 @@ public: void asyncHandlersComplete() { - std::unique_lock lk{m_mut}; + std::unique_lock const lk{m_mut}; m_asyncHandlersCompleted = true; m_cv.notify_all(); } @@ -172,7 +172,7 @@ public: if (m_stopped.exchange(false)) { { - std::lock_guard lk{m_mut}; + std::lock_guard const lk{m_mut}; m_asyncHandlersCompleted = false; } addReference(); @@ -327,7 +327,7 @@ public: return; std::string const name(m_work.front().names.back()); - HandlerType handler(m_work.front().handler); + HandlerType const handler(m_work.front().handler); m_work.front().names.pop_back(); diff --git a/src/libxrpl/basics/StringUtilities.cpp b/src/libxrpl/basics/StringUtilities.cpp index c47618db82..5e3b100b26 100644 --- a/src/libxrpl/basics/StringUtilities.cpp +++ b/src/libxrpl/basics/StringUtilities.cpp @@ -37,7 +37,7 @@ bool parseUrl(parsedURL& pUrl, std::string const& strUrl) { // scheme://username:password@hostname:port/rest - static boost::regex reUrl( + static boost::regex const reUrl( "(?i)\\`\\s*" // required scheme "([[:alpha:]][-+.[:alpha:][:digit:]]*?):" diff --git a/src/libxrpl/basics/base64.cpp b/src/libxrpl/basics/base64.cpp index a510fbf6c9..cf6af3db70 100644 --- a/src/libxrpl/basics/base64.cpp +++ b/src/libxrpl/basics/base64.cpp @@ -103,7 +103,7 @@ std::size_t constexpr decoded_size(std::size_t n) std::size_t encode(void* dest, void const* src, std::size_t len) { - char* out = static_cast(dest); + char* out = static_cast(dest); // NOLINT(misc-const-correctness) char const* in = static_cast(src); auto const tab = base64::get_alphabet(); @@ -154,7 +154,7 @@ encode(void* dest, void const* src, std::size_t len) std::pair decode(void* dest, char const* src, std::size_t len) { - char* out = static_cast(dest); + char* out = static_cast(dest); // NOLINT(misc-const-correctness) auto in = reinterpret_cast(src); unsigned char c3[3]{}, c4[4]{}; int i = 0; diff --git a/src/libxrpl/basics/make_SSLContext.cpp b/src/libxrpl/basics/make_SSLContext.cpp index de16e8c6cf..c5ff456d25 100644 --- a/src/libxrpl/basics/make_SSLContext.cpp +++ b/src/libxrpl/basics/make_SSLContext.cpp @@ -140,7 +140,7 @@ initAnonymous(boost::asio::ssl::context& context) auto const ts = std::time(nullptr) - (25 * 60 * 60); - int ret = std::strftime(buf, sizeof(buf) - 1, "%y%m%d000000Z", std::gmtime(&ts)); + int const ret = std::strftime(buf, sizeof(buf) - 1, "%y%m%d000000Z", std::gmtime(&ts)); buf[ret] = 0; diff --git a/src/libxrpl/beast/clock/basic_seconds_clock.cpp b/src/libxrpl/beast/clock/basic_seconds_clock.cpp index 4727599740..c928c8c579 100644 --- a/src/libxrpl/beast/clock/basic_seconds_clock.cpp +++ b/src/libxrpl/beast/clock/basic_seconds_clock.cpp @@ -41,7 +41,7 @@ seconds_clock_thread::~seconds_clock_thread() XRPL_ASSERT( thread_.joinable(), "beast::seconds_clock_thread::~seconds_clock_thread : thread joinable"); { - std::lock_guard lock(mut_); + std::lock_guard const lock(mut_); stop_ = true; } // publish stop_ asap so if waiting thread times-out, it will see it cv_.notify_one(); diff --git a/src/libxrpl/beast/core/SemanticVersion.cpp b/src/libxrpl/beast/core/SemanticVersion.cpp index 34bb5e3df0..0601690560 100644 --- a/src/libxrpl/beast/core/SemanticVersion.cpp +++ b/src/libxrpl/beast/core/SemanticVersion.cpp @@ -62,7 +62,7 @@ chopUInt(int& value, int limit, std::string& input) return std::isdigit(c, std::locale::classic()); }); - std::string item(input.begin(), left_iter); + std::string const item(input.begin(), left_iter); // Must not be empty if (item.empty()) @@ -320,7 +320,7 @@ compare(SemanticVersion const& lhs, SemanticVersion const& rhs) { XRPL_ASSERT(!isNumeric(right), "beast::compare : both inputs non-numeric"); - int result = left.compare(right); + int const result = left.compare(right); if (result != 0) return result; diff --git a/src/libxrpl/beast/insight/Collector.cpp b/src/libxrpl/beast/insight/Collector.cpp index 37b199fa7f..d4a528473b 100644 --- a/src/libxrpl/beast/insight/Collector.cpp +++ b/src/libxrpl/beast/insight/Collector.cpp @@ -4,5 +4,5 @@ namespace beast { namespace insight { Collector::~Collector() = default; -} +} // namespace insight } // namespace beast diff --git a/src/libxrpl/beast/insight/Groups.cpp b/src/libxrpl/beast/insight/Groups.cpp index 2b4178a9ca..393deca101 100644 --- a/src/libxrpl/beast/insight/Groups.cpp +++ b/src/libxrpl/beast/insight/Groups.cpp @@ -98,7 +98,7 @@ public: Group::ptr const& get(std::string const& name) override { - std::pair result(m_items.emplace(name, Group::ptr())); + std::pair const result(m_items.emplace(name, Group::ptr())); Group::ptr& group(result.first->second); if (result.second) group = std::make_shared(name, m_collector); diff --git a/src/libxrpl/beast/insight/Hook.cpp b/src/libxrpl/beast/insight/Hook.cpp index d5e0a3439f..f74f3e8705 100644 --- a/src/libxrpl/beast/insight/Hook.cpp +++ b/src/libxrpl/beast/insight/Hook.cpp @@ -5,5 +5,5 @@ namespace beast { namespace insight { HookImpl::~HookImpl() = default; -} +} // namespace insight } // namespace beast diff --git a/src/libxrpl/beast/insight/StatsDCollector.cpp b/src/libxrpl/beast/insight/StatsDCollector.cpp index 83fc65e92c..7d80e1a052 100644 --- a/src/libxrpl/beast/insight/StatsDCollector.cpp +++ b/src/libxrpl/beast/insight/StatsDCollector.cpp @@ -293,14 +293,14 @@ public: void add(StatsDMetricBase& metric) { - std::lock_guard _(metricsLock_); + std::lock_guard const _(metricsLock_); metrics_.push_back(metric); } void remove(StatsDMetricBase& metric) { - std::lock_guard _(metricsLock_); + std::lock_guard const _(metricsLock_); metrics_.erase(metrics_.iterator_to(metric)); } @@ -444,7 +444,7 @@ public: return; } - std::lock_guard _(metricsLock_); + std::lock_guard const _(metricsLock_); for (auto& m : metrics_) m.do_process(); diff --git a/src/libxrpl/beast/net/IPEndpoint.cpp b/src/libxrpl/beast/net/IPEndpoint.cpp index 70e7bff2c5..7e2799b46c 100644 --- a/src/libxrpl/beast/net/IPEndpoint.cpp +++ b/src/libxrpl/beast/net/IPEndpoint.cpp @@ -120,8 +120,7 @@ operator>>(std::istream& is, Endpoint& endpoint) addrStr += i; // don't exceed a reasonable length... - if (addrStr.size() == INET6_ADDRSTRLEN || - ((readTo != 0) && readTo == ':' && addrStr.size() > 15)) + if (addrStr.size() == INET6_ADDRSTRLEN || (readTo == ':' && addrStr.size() > 15)) { is.setstate(std::ios_base::failbit); return is; diff --git a/src/libxrpl/beast/utility/beast_PropertyStream.cpp b/src/libxrpl/beast/utility/beast_PropertyStream.cpp index 454b9d1323..9cf4f23065 100644 --- a/src/libxrpl/beast/utility/beast_PropertyStream.cpp +++ b/src/libxrpl/beast/utility/beast_PropertyStream.cpp @@ -158,7 +158,7 @@ PropertyStream::Source::Source(std::string const& name) PropertyStream::Source::~Source() { - std::lock_guard _(lock_); + std::lock_guard const _(lock_); if (parent_ != nullptr) parent_->remove(*this); removeAll(); @@ -174,8 +174,8 @@ void PropertyStream::Source::add(Source& source) { std::lock(lock_, source.lock_); - std::lock_guard lk1(lock_, std::adopt_lock); - std::lock_guard lk2(source.lock_, std::adopt_lock); + std::lock_guard const lk1(lock_, std::adopt_lock); + std::lock_guard const lk2(source.lock_, std::adopt_lock); XRPL_ASSERT( source.parent_ == nullptr, "beast::PropertyStream::Source::add : null source parent"); @@ -187,8 +187,8 @@ void PropertyStream::Source::remove(Source& child) { std::lock(lock_, child.lock_); - std::lock_guard lk1(lock_, std::adopt_lock); - std::lock_guard lk2(child.lock_, std::adopt_lock); + std::lock_guard const lk1(lock_, std::adopt_lock); + std::lock_guard const lk2(child.lock_, std::adopt_lock); XRPL_ASSERT( child.parent_ == this, "beast::PropertyStream::Source::remove : child parent match"); @@ -199,10 +199,10 @@ PropertyStream::Source::remove(Source& child) void PropertyStream::Source::removeAll() { - std::lock_guard _(lock_); + std::lock_guard const _(lock_); for (auto iter = children_.begin(); iter != children_.end();) { - std::lock_guard _cl((*iter)->lock_); + std::lock_guard const _cl((*iter)->lock_); remove(*(*iter)); } } @@ -222,7 +222,7 @@ PropertyStream::Source::write(PropertyStream& stream) Map map(m_name, stream); onWrite(map); - std::lock_guard _(lock_); + std::lock_guard const _(lock_); for (auto& child : children_) child.source().write(stream); @@ -299,9 +299,9 @@ PropertyStream::Source::peel_name(std::string* path) if (path->empty()) return ""; - std::string::const_iterator first = (*path).begin(); - std::string::const_iterator last = (*path).end(); - std::string::const_iterator pos = std::find(first, last, '/'); + std::string::const_iterator const first = (*path).begin(); + std::string::const_iterator const last = (*path).end(); + std::string::const_iterator const pos = std::find(first, last, '/'); std::string s(first, pos); if (pos != last) @@ -320,11 +320,11 @@ PropertyStream::Source::peel_name(std::string* path) PropertyStream::Source* PropertyStream::Source::find_one_deep(std::string const& name) { - Source* found = find_one(name); + Source* found = find_one(name); // NOLINT(misc-const-correctness) if (found != nullptr) return found; - std::lock_guard _(lock_); + std::lock_guard const _(lock_); for (auto& s : children_) { found = s.source().find_one_deep(name); @@ -355,7 +355,7 @@ PropertyStream::Source::find_path(std::string path) PropertyStream::Source* PropertyStream::Source::find_one(std::string const& name) { - std::lock_guard _(lock_); + std::lock_guard const _(lock_); for (auto& s : children_) { if (s.source().m_name == name) diff --git a/src/libxrpl/core/HashRouter.cpp b/src/libxrpl/core/HashRouter.cpp index dff1394f77..f21daf84a2 100644 --- a/src/libxrpl/core/HashRouter.cpp +++ b/src/libxrpl/core/HashRouter.cpp @@ -22,7 +22,7 @@ HashRouter::emplace(uint256 const& key) -> std::pair void HashRouter::addSuppression(uint256 const& key) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); emplace(key); } @@ -36,7 +36,7 @@ HashRouter::addSuppressionPeer(uint256 const& key, PeerShortID peer) std::pair> HashRouter::addSuppressionPeerWithStatus(uint256 const& key, PeerShortID peer) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); auto result = emplace(key); result.first.addPeer(peer); @@ -46,7 +46,7 @@ HashRouter::addSuppressionPeerWithStatus(uint256 const& key, PeerShortID peer) bool HashRouter::addSuppressionPeer(uint256 const& key, PeerShortID peer, HashRouterFlags& flags) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); auto [s, created] = emplace(key); s.addPeer(peer); @@ -61,7 +61,7 @@ HashRouter::shouldProcess( HashRouterFlags& flags, std::chrono::seconds tx_interval) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); auto result = emplace(key); auto& s = result.first; @@ -73,7 +73,7 @@ HashRouter::shouldProcess( HashRouterFlags HashRouter::getFlags(uint256 const& key) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); return emplace(key).first.getFlags(); } @@ -83,7 +83,7 @@ HashRouter::setFlags(uint256 const& key, HashRouterFlags flags) { XRPL_ASSERT(static_cast(flags), "xrpl::HashRouter::setFlags : valid input"); - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); auto& s = emplace(key).first; @@ -97,7 +97,7 @@ HashRouter::setFlags(uint256 const& key, HashRouterFlags flags) auto HashRouter::shouldRelay(uint256 const& key) -> std::optional> { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); auto& s = emplace(key).first; diff --git a/src/libxrpl/core/detail/JobQueue.cpp b/src/libxrpl/core/detail/JobQueue.cpp index 2fe5a5b0fd..434ab146bd 100644 --- a/src/libxrpl/core/detail/JobQueue.cpp +++ b/src/libxrpl/core/detail/JobQueue.cpp @@ -26,7 +26,7 @@ JobQueue::JobQueue( job_count = m_collector->make_gauge("job_count"); { - std::lock_guard lock(m_mutex); + std::lock_guard const lock(m_mutex); for (auto const& x : JobTypes::instance()) { @@ -52,7 +52,7 @@ JobQueue::~JobQueue() void JobQueue::collect() { - std::lock_guard lock(m_mutex); + std::lock_guard const lock(m_mutex); job_count = m_jobSet.size(); } @@ -78,7 +78,7 @@ JobQueue::addRefCountedJob(JobType type, std::string const& name, JobFunction co "requires no threads"); { - std::lock_guard lock(m_mutex); + std::lock_guard const lock(m_mutex); auto result = m_jobSet.emplace(type, name, ++m_lastJob, data.load(), func); auto const& job = *result.first; @@ -106,9 +106,9 @@ JobQueue::addRefCountedJob(JobType type, std::string const& name, JobFunction co int JobQueue::getJobCount(JobType t) const { - std::lock_guard lock(m_mutex); + std::lock_guard const lock(m_mutex); - JobDataMap::const_iterator c = m_jobData.find(t); + JobDataMap::const_iterator const c = m_jobData.find(t); return (c == m_jobData.end()) ? 0 : c->second.waiting; } @@ -116,9 +116,9 @@ JobQueue::getJobCount(JobType t) const int JobQueue::getJobCountTotal(JobType t) const { - std::lock_guard lock(m_mutex); + std::lock_guard const lock(m_mutex); - JobDataMap::const_iterator c = m_jobData.find(t); + JobDataMap::const_iterator const c = m_jobData.find(t); return (c == m_jobData.end()) ? 0 : (c->second.waiting + c->second.running); } @@ -129,7 +129,7 @@ JobQueue::getJobCountGE(JobType t) const // return the number of jobs at this priority level or greater int ret = 0; - std::lock_guard lock(m_mutex); + std::lock_guard const lock(m_mutex); for (auto const& x : m_jobData) { @@ -143,7 +143,7 @@ JobQueue::getJobCountGE(JobType t) const std::unique_ptr JobQueue::makeLoadEvent(JobType t, std::string const& name) { - JobDataMap::iterator iter(m_jobData.find(t)); + JobDataMap::iterator const iter(m_jobData.find(t)); XRPL_ASSERT(iter != m_jobData.end(), "xrpl::JobQueue::makeLoadEvent : valid job type input"); if (iter == m_jobData.end()) @@ -158,7 +158,7 @@ JobQueue::addLoadEvents(JobType t, int count, std::chrono::milliseconds elapsed) if (isStopped()) LogicError("JobQueue::addLoadEvents() called after JobQueue stopped"); - JobDataMap::iterator iter(m_jobData.find(t)); + JobDataMap::iterator const iter(m_jobData.find(t)); XRPL_ASSERT(iter != m_jobData.end(), "xrpl::JobQueue::addLoadEvents : valid job type input"); iter->second.load().addSamples(count, elapsed); } @@ -181,7 +181,7 @@ JobQueue::getJson(int c) Json::Value priorities = Json::arrayValue; - std::lock_guard lock(m_mutex); + std::lock_guard const lock(m_mutex); for (auto& x : m_jobData) { @@ -192,10 +192,10 @@ JobQueue::getJson(int c) JobTypeData& data(x.second); - LoadMonitor::Stats stats(data.stats()); + LoadMonitor::Stats const stats(data.stats()); - int waiting(data.waiting); - int running(data.running); + int const waiting(data.waiting); + int const running(data.running); if ((stats.count != 0) || (waiting != 0) || (stats.latencyPeak != 0ms) || (running != 0)) { @@ -238,7 +238,7 @@ JobQueue::rendezvous() JobTypeData& JobQueue::getJobTypeData(JobType type) { - JobDataMap::iterator c(m_jobData.find(type)); + JobDataMap::iterator const c(m_jobData.find(type)); XRPL_ASSERT(c != m_jobData.end(), "xrpl::JobQueue::getJobTypeData : valid job type input"); // NIKB: This is ugly and I hate it. We must remove jtINVALID completely @@ -338,12 +338,12 @@ JobQueue::processTask(int instance) { Job job; { - std::lock_guard lock(m_mutex); + std::lock_guard const lock(m_mutex); getNextJob(job); ++m_processCount; } type = job.getType(); - JobTypeData& data(getJobTypeData(type)); + JobTypeData const& data(getJobTypeData(type)); JLOG(m_journal.trace()) << "Doing " << data.name() << "job"; // The amount of time that the job was in the queue @@ -365,7 +365,7 @@ JobQueue::processTask(int instance) } { - std::lock_guard lock(m_mutex); + std::lock_guard const lock(m_mutex); // Job should be destroyed before stopping // otherwise destructors with side effects can access // parent objects that are already destroyed. diff --git a/src/libxrpl/core/detail/LoadMonitor.cpp b/src/libxrpl/core/detail/LoadMonitor.cpp index 9891bdb8b8..967947ee17 100644 --- a/src/libxrpl/core/detail/LoadMonitor.cpp +++ b/src/libxrpl/core/detail/LoadMonitor.cpp @@ -104,7 +104,7 @@ LoadMonitor::addLoadSample(LoadEvent const& s) void LoadMonitor::addSamples(int count, std::chrono::milliseconds latency) { - std::lock_guard sl(mutex_); + std::lock_guard const sl(mutex_); update(); mCounts += count; @@ -136,7 +136,7 @@ LoadMonitor::isOverTarget(std::chrono::milliseconds avg, std::chrono::millisecon bool LoadMonitor::isOver() { - std::lock_guard sl(mutex_); + std::lock_guard const sl(mutex_); update(); @@ -153,7 +153,7 @@ LoadMonitor::getStats() using namespace std::chrono_literals; Stats stats; - std::lock_guard sl(mutex_); + std::lock_guard const sl(mutex_); update(); diff --git a/src/libxrpl/core/detail/Workers.cpp b/src/libxrpl/core/detail/Workers.cpp index b7d962b79b..a654d20280 100644 --- a/src/libxrpl/core/detail/Workers.cpp +++ b/src/libxrpl/core/detail/Workers.cpp @@ -121,7 +121,7 @@ Workers::deleteWorkers(beast::LockFreeStack& stack) { for (;;) { - Worker* const worker = stack.pop_front(); + Worker const* const worker = stack.pop_front(); if (worker != nullptr) { @@ -150,7 +150,7 @@ Workers::Worker::Worker(Workers& workers, std::string const& threadName, int con Workers::Worker::~Worker() { { - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; ++wakeCount_; shouldExit_ = true; } @@ -162,7 +162,7 @@ Workers::Worker::~Worker() void Workers::Worker::notify() { - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; ++wakeCount_; wakeup_.notify_one(); } @@ -178,7 +178,7 @@ Workers::Worker::run() // if (++m_workers.m_activeCount == 1) { - std::lock_guard lk{m_workers.m_mut}; + std::lock_guard const lk{m_workers.m_mut}; m_workers.m_allPaused = false; } @@ -225,7 +225,7 @@ Workers::Worker::run() // the predicate evaluation and the actual sleep. if (--m_workers.m_runningTaskCount == 0) { - std::lock_guard lk{m_workers.m_mut}; + std::lock_guard const lk{m_workers.m_mut}; m_workers.m_cv.notify_all(); } } @@ -241,7 +241,7 @@ Workers::Worker::run() // if (--m_workers.m_activeCount == 0) { - std::lock_guard lk{m_workers.m_mut}; + std::lock_guard const lk{m_workers.m_mut}; m_workers.m_allPaused = true; m_workers.m_cv.notify_all(); } diff --git a/src/libxrpl/crypto/RFC1751.cpp b/src/libxrpl/crypto/RFC1751.cpp index becd0aab8d..f7098f3833 100644 --- a/src/libxrpl/crypto/RFC1751.cpp +++ b/src/libxrpl/crypto/RFC1751.cpp @@ -312,8 +312,8 @@ RFC1751::wsrch(std::string const& strWord, int iMin, int iMax) while (iResult < 0 && iMin != iMax) { // Have a range to search. - int iMid = iMin + ((iMax - iMin) / 2); - int iDir = strWord.compare(s_dictionary[iMid]); + int const iMid = iMin + ((iMax - iMin) / 2); + int const iDir = strWord.compare(s_dictionary[iMid]); if (iDir == 0) { @@ -349,7 +349,7 @@ RFC1751::etob(std::string& strData, std::vector vsHuman) for (auto& strWord : vsHuman) { - int l = strWord.length(); + int const l = strWord.length(); if (l > 4 || l < 1) return -1; diff --git a/src/libxrpl/crypto/csprng.cpp b/src/libxrpl/crypto/csprng.cpp index 25e24c0b08..343bed9be0 100644 --- a/src/libxrpl/crypto/csprng.cpp +++ b/src/libxrpl/crypto/csprng.cpp @@ -42,7 +42,7 @@ csprng_engine::mix_entropy(void* buffer, std::size_t count) e = rd(); } - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); // We add data to the pool, but we conservatively assume that // it contributes no actual entropy. diff --git a/src/libxrpl/json/Writer.cpp b/src/libxrpl/json/Writer.cpp index 796ec35dfd..ea7b4b51ae 100644 --- a/src/libxrpl/json/Writer.cpp +++ b/src/libxrpl/json/Writer.cpp @@ -80,7 +80,7 @@ public: void start(CollectionType ct) { - char ch = (ct == array) ? openBracket : openBrace; + char const ch = (ct == array) ? openBracket : openBrace; output({&ch, 1}); stack_.push(Collection()); stack_.top().type = ct; diff --git a/src/libxrpl/json/json_reader.cpp b/src/libxrpl/json/json_reader.cpp index 6475a5b68b..71365ba6c1 100644 --- a/src/libxrpl/json/json_reader.cpp +++ b/src/libxrpl/json/json_reader.cpp @@ -93,7 +93,7 @@ Reader::parse(char const* beginDoc, char const* endDoc, Value& root) nodes_.pop(); nodes_.push(&root); - bool successful = readValue(0); + bool const successful = readValue(0); Token token{}; skipCommentTokens(token); @@ -186,7 +186,7 @@ Reader::readToken(Token& token) { skipSpaces(); token.start_ = current_; - Char c = getNextChar(); + Char const c = getNextChar(); bool ok = true; switch (c) @@ -275,7 +275,7 @@ Reader::skipSpaces() { while (current_ != end_) { - Char c = *current_; + Char const c = *current_; if (c == ' ' || c == '\t' || c == '\r' || c == '\n') { @@ -309,7 +309,7 @@ Reader::match(Location pattern, int patternLength) bool Reader::readComment() { - Char c = getNextChar(); + Char const c = getNextChar(); if (c == '*') return readCStyleComment(); @@ -325,7 +325,7 @@ Reader::readCStyleComment() { while (current_ != end_) { - Char c = getNextChar(); + Char const c = getNextChar(); if (c == '*' && *current_ == '/') break; @@ -339,7 +339,7 @@ Reader::readCppStyleComment() { while (current_ != end_) { - Char c = getNextChar(); + Char const c = getNextChar(); if (c == '\r' || c == '\n') break; @@ -444,7 +444,7 @@ Reader::readObject(Token& tokenStart, unsigned depth) Value& value = currentValue()[name]; nodes_.push(&value); - bool ok = readValue(depth + 1); + bool const ok = readValue(depth + 1); nodes_.pop(); if (!ok) // error already set @@ -506,7 +506,8 @@ Reader::readArray(Token& tokenStart, unsigned depth) ok = readToken(token); } - bool badTokenType = (token.type_ != tokenArraySeparator && token.type_ != tokenArrayEnd); + bool const badTokenType = + (token.type_ != tokenArraySeparator && token.type_ != tokenArrayEnd); if (!ok || badTokenType) { @@ -525,7 +526,7 @@ bool Reader::decodeNumber(Token& token) { Location current = token.start_; - bool isNegative = *current == '-'; + bool const isNegative = *current == '-'; if (isNegative) ++current; @@ -546,7 +547,7 @@ Reader::decodeNumber(Token& token) while (current < token.end_ && (value <= Value::maxUInt)) { - Char c = *current++; + Char const c = *current++; if (c < '0' || c > '9') { @@ -606,7 +607,7 @@ Reader::decodeDouble(Token& token) double value = 0; int const bufferSize = 32; int count = 0; - int length = int(token.end_ - token.start_); + int const length = int(token.end_ - token.start_); // Sanity check to avoid buffer overflow exploits. if (length < 0) { @@ -627,7 +628,7 @@ Reader::decodeDouble(Token& token) } else { - std::string buffer(token.start_, token.end_); + std::string const buffer(token.start_, token.end_); count = sscanf(buffer.c_str(), format, &value); } if (count != 1) @@ -657,7 +658,7 @@ Reader::decodeString(Token& token, std::string& decoded) while (current != end) { - Char c = *current++; + Char const c = *current++; if (c == '"') { @@ -668,7 +669,7 @@ Reader::decodeString(Token& token, std::string& decoded) if (current == end) return addError("Empty escape sequence in string", token, current); - Char escape = *current++; + Char const escape = *current++; switch (escape) { @@ -783,7 +784,7 @@ Reader::decodeUnicodeEscapeSequence( for (int index = 0; index < 4; ++index) { - Char c = *current++; + Char const c = *current++; unicode *= 16; if (c >= '0' && c <= '9') @@ -825,7 +826,7 @@ Reader::addError(std::string const& message, Token& token, Location extra) bool Reader::recoverFromError(TokenType skipUntilToken) { - int errorCount = int(errors_.size()); + int const errorCount = int(errors_.size()); Token skip{}; while (true) @@ -872,7 +873,7 @@ Reader::getLocationLineAndColumn(Location location, int& line, int& column) cons while (current < location && current != end_) { - Char c = *current++; + Char const c = *current++; if (c == '\r') { @@ -924,7 +925,7 @@ std::istream& operator>>(std::istream& sin, Value& root) { Json::Reader reader; - bool ok = reader.parse(sin, root); + bool const ok = reader.parse(sin, root); // XRPL_ASSERT(ok, "Json::operator>>() : parse succeeded"); if (!ok) diff --git a/src/libxrpl/json/json_value.cpp b/src/libxrpl/json/json_value.cpp index 988a25a3ff..d4351b23ef 100644 --- a/src/libxrpl/json/json_value.cpp +++ b/src/libxrpl/json/json_value.cpp @@ -60,6 +60,7 @@ public: static ValueAllocator*& valueAllocator() { + // NOLINTNEXTLINE(misc-const-correctness) static ValueAllocator* valueAllocator = new DefaultValueAllocator; return valueAllocator; } @@ -333,11 +334,11 @@ Value::swap(Value& other) noexcept { std::swap(value_, other.value_); - ValueType temp = type_; + ValueType const temp = type_; type_ = other.type_; other.type_ = temp; - int temp2 = allocated_; + int const temp2 = allocated_; allocated_ = other.allocated_; other.allocated_ = temp2; } @@ -401,7 +402,7 @@ operator<(Value const& x, Value const& y) case arrayValue: case objectValue: { - if (int signum = int(x.value_.map_->size()) - y.value_.map_->size()) + if (int const signum = int(x.value_.map_->size()) - y.value_.map_->size()) return signum < 0; return *x.value_.map_ < *y.value_.map_; @@ -848,13 +849,13 @@ Value::operator[](UInt index) if (type_ == nullValue) *this = Value(arrayValue); - CZString key(index); + CZString const key(index); ObjectValues::iterator it = value_.map_->lower_bound(key); if (it != value_.map_->end() && (*it).first == key) return (*it).second; - ObjectValues::value_type defaultValue(key, null); + ObjectValues::value_type const defaultValue(key, null); it = value_.map_->insert(it, defaultValue); return (*it).second; } @@ -869,8 +870,8 @@ Value::operator[](UInt index) const if (type_ == nullValue) return null; - CZString key(index); - ObjectValues::const_iterator it = value_.map_->find(key); + CZString const key(index); + ObjectValues::const_iterator const it = value_.map_->find(key); if (it == value_.map_->end()) return null; @@ -893,13 +894,13 @@ Value::resolveReference(char const* key, bool isStatic) if (type_ == nullValue) *this = Value(objectValue); - CZString actualKey(key, isStatic ? CZString::noDuplication : CZString::duplicateOnCopy); + CZString const actualKey(key, isStatic ? CZString::noDuplication : CZString::duplicateOnCopy); ObjectValues::iterator it = value_.map_->lower_bound(actualKey); if (it != value_.map_->end() && (*it).first == actualKey) return (*it).second; - ObjectValues::value_type defaultValue(actualKey, null); + ObjectValues::value_type const defaultValue(actualKey, null); it = value_.map_->insert(it, defaultValue); Value& value = (*it).second; return value; @@ -928,8 +929,8 @@ Value::operator[](char const* key) const if (type_ == nullValue) return null; - CZString actualKey(key, CZString::noDuplication); - ObjectValues::const_iterator it = value_.map_->find(actualKey); + CZString const actualKey(key, CZString::noDuplication); + ObjectValues::const_iterator const it = value_.map_->find(actualKey); if (it == value_.map_->end()) return null; @@ -995,8 +996,8 @@ Value::removeMember(char const* key) if (type_ == nullValue) return null; - CZString actualKey(key, CZString::noDuplication); - ObjectValues::iterator it = value_.map_->find(actualKey); + CZString const actualKey(key, CZString::noDuplication); + ObjectValues::iterator const it = value_.map_->find(actualKey); if (it == value_.map_->end()) return null; @@ -1046,7 +1047,7 @@ Value::getMemberNames() const Members members; members.reserve(value_.map_->size()); ObjectValues::const_iterator it = value_.map_->begin(); - ObjectValues::const_iterator itEnd = value_.map_->end(); + ObjectValues::const_iterator const itEnd = value_.map_->end(); for (; it != itEnd; ++it) members.push_back(std::string((*it).first.c_str())); diff --git a/src/libxrpl/json/json_writer.cpp b/src/libxrpl/json/json_writer.cpp index b51da5bb68..2d0fc1c288 100644 --- a/src/libxrpl/json/json_writer.cpp +++ b/src/libxrpl/json/json_writer.cpp @@ -47,8 +47,8 @@ std::string valueToString(Int value) { char buffer[32]; - char* current = buffer + sizeof(buffer); - bool isNegative = value < 0; + char* current = buffer + sizeof(buffer); // NOLINT(misc-const-correctness) + bool const isNegative = value < 0; if (isNegative) value = -value; @@ -66,7 +66,7 @@ std::string valueToString(UInt value) { char buffer[32]; - char* current = buffer + sizeof(buffer); + char* current = buffer + sizeof(buffer); // NOLINT(misc-const-correctness) uintToString(value, current); XRPL_ASSERT(current >= buffer, "Json::valueToString(UInt) : buffer check"); return current; @@ -106,7 +106,7 @@ valueToQuotedString(char const* value) // We have to walk value and escape any special characters. // Appending to std::string is not efficient, but this should be rare. // (Note: forward slashes are *not* rare, but I am not escaping them.) - unsigned maxsize = (strlen(value) * 2) + 3; // all-escaped+quotes+NULL + unsigned const maxsize = (strlen(value) * 2) + 3; // all-escaped+quotes+NULL std::string result; result.reserve(maxsize); // to avoid lots of mallocs result += "\""; @@ -213,7 +213,7 @@ FastWriter::writeValue(Value const& value) case arrayValue: { document_ += "["; - int size = value.size(); + int const size = value.size(); for (int index = 0; index < size; ++index) { @@ -338,7 +338,7 @@ StyledWriter::writeValue(Value const& value) void StyledWriter::writeArrayValue(Value const& value) { - unsigned size = value.size(); + unsigned const size = value.size(); if (size == 0) { @@ -346,13 +346,13 @@ StyledWriter::writeArrayValue(Value const& value) } else { - bool isArrayMultiLine = isMultilineArray(value); + bool const isArrayMultiLine = isMultilineArray(value); if (isArrayMultiLine) { writeWithIndent("["); indent(); - bool hasChildValue = !childValues_.empty(); + bool const hasChildValue = !childValues_.empty(); unsigned index = 0; while (true) @@ -401,7 +401,7 @@ StyledWriter::writeArrayValue(Value const& value) bool StyledWriter::isMultilineArray(Value const& value) { - int size = value.size(); + int const size = value.size(); bool isMultiLine = size * 3 >= rightMargin_; childValues_.clear(); @@ -449,7 +449,7 @@ StyledWriter::writeIndent() { if (!document_.empty()) { - char last = document_[document_.length() - 1]; + char const last = document_[document_.length() - 1]; if (last == ' ') // already indented return; @@ -573,7 +573,7 @@ StyledStreamWriter::writeValue(Value const& value) void StyledStreamWriter::writeArrayValue(Value const& value) { - unsigned size = value.size(); + unsigned const size = value.size(); if (size == 0) { @@ -581,13 +581,13 @@ StyledStreamWriter::writeArrayValue(Value const& value) } else { - bool isArrayMultiLine = isMultilineArray(value); + bool const isArrayMultiLine = isMultilineArray(value); if (isArrayMultiLine) { writeWithIndent("["); indent(); - bool hasChildValue = !childValues_.empty(); + bool const hasChildValue = !childValues_.empty(); unsigned index = 0; while (true) @@ -636,7 +636,7 @@ StyledStreamWriter::writeArrayValue(Value const& value) bool StyledStreamWriter::isMultilineArray(Value const& value) { - int size = value.size(); + int const size = value.size(); bool isMultiLine = size * 3 >= rightMargin_; childValues_.clear(); diff --git a/src/libxrpl/ledger/ApplyStateTable.cpp b/src/libxrpl/ledger/ApplyStateTable.cpp index a48c3910e1..9ebbca8ac5 100644 --- a/src/libxrpl/ledger/ApplyStateTable.cpp +++ b/src/libxrpl/ledger/ApplyStateTable.cpp @@ -127,8 +127,8 @@ ApplyStateTable::apply( auto curNode = item.second.second; if ((type == &sfModifiedNode) && (*curNode == *origNode)) continue; - std::uint16_t nodeType = curNode ? curNode->getFieldU16(sfLedgerEntryType) - : origNode->getFieldU16(sfLedgerEntryType); + std::uint16_t const nodeType = curNode ? curNode->getFieldU16(sfLedgerEntryType) + : origNode->getFieldU16(sfLedgerEntryType); meta.setAffectedNode(item.first, *type, nodeType); if (type == &sfDeletedNode) { diff --git a/src/libxrpl/ledger/ApplyView.cpp b/src/libxrpl/ledger/ApplyView.cpp index fe2e046b26..476b635511 100644 --- a/src/libxrpl/ledger/ApplyView.cpp +++ b/src/libxrpl/ledger/ApplyView.cpp @@ -32,7 +32,7 @@ createRoot( auto findPreviousPage(ApplyView& view, Keylet const& directory, SLE::ref start) { - std::uint64_t page = start->getFieldU64(sfIndexPrevious); + std::uint64_t const page = start->getFieldU64(sfIndexPrevious); auto node = start; diff --git a/src/libxrpl/ledger/BookListeners.cpp b/src/libxrpl/ledger/BookListeners.cpp index 22b78e46bb..8699d891a0 100644 --- a/src/libxrpl/ledger/BookListeners.cpp +++ b/src/libxrpl/ledger/BookListeners.cpp @@ -5,21 +5,21 @@ namespace xrpl { void BookListeners::addSubscriber(InfoSub::ref sub) { - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); mListeners[sub->getSeq()] = sub; } void BookListeners::removeSubscriber(std::uint64_t seq) { - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); mListeners.erase(seq); } void BookListeners::publish(MultiApiJson const& jvObj, hash_set& havePublished) { - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); auto it = mListeners.cbegin(); while (it != mListeners.cend()) diff --git a/src/libxrpl/ledger/CachedView.cpp b/src/libxrpl/ledger/CachedView.cpp index 5c15ccdac4..aa075d69a4 100644 --- a/src/libxrpl/ledger/CachedView.cpp +++ b/src/libxrpl/ledger/CachedView.cpp @@ -21,7 +21,7 @@ CachedViewImpl::read(Keylet const& k) const auto const digest = [&]() -> std::optional { { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); auto const iter = map_.find(k.key); if (iter != map_.end()) { @@ -57,7 +57,7 @@ CachedViewImpl::read(Keylet const& k) const // Avoid acquiring this lock unless necessary. It is only necessary if // the key was not found in the map_. The lock is needed to add the key // and digest. - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); map_.emplace(k.key, *digest); } if (!sle || !k.check(*sle)) diff --git a/src/libxrpl/ledger/Ledger.cpp b/src/libxrpl/ledger/Ledger.cpp index 87f6350ce1..299a82a1f2 100644 --- a/src/libxrpl/ledger/Ledger.cpp +++ b/src/libxrpl/ledger/Ledger.cpp @@ -798,7 +798,7 @@ Ledger::updateSkipList() if (header_.seq == 0) // genesis ledger has no previous ledger return; - std::uint32_t prevIndex = header_.seq - 1; + std::uint32_t const prevIndex = header_.seq - 1; // update record of every 256th ledger if ((prevIndex & 0xff) == 0) diff --git a/src/libxrpl/ledger/ReadView.cpp b/src/libxrpl/ledger/ReadView.cpp index e0764d6c81..8e6763410c 100644 --- a/src/libxrpl/ledger/ReadView.cpp +++ b/src/libxrpl/ledger/ReadView.cpp @@ -58,7 +58,7 @@ makeRulesGivenLedger( std::unordered_set> const& presets) { Keylet const k = keylet::amendments(); - std::optional digest = ledger.digest(k.key); + std::optional const digest = ledger.digest(k.key); if (digest) { auto const sle = ledger.read(k); diff --git a/src/libxrpl/ledger/View.cpp b/src/libxrpl/ledger/View.cpp index 227eafbec8..1702d4243b 100644 --- a/src/libxrpl/ledger/View.cpp +++ b/src/libxrpl/ledger/View.cpp @@ -242,7 +242,7 @@ hashOfSeq(ReadView const& ledger, LedgerIndex seq, beast::Journal journal) if (seq == (ledger.seq() - 1)) return ledger.header().parentHash; - if (int diff = ledger.seq() - seq; diff <= 256) + if (int const diff = ledger.seq() - seq; diff <= 256) { // Within 256... auto const hashIndex = ledger.read(keylet::skip()); diff --git a/src/libxrpl/ledger/helpers/OfferHelpers.cpp b/src/libxrpl/ledger/helpers/OfferHelpers.cpp index 9422153b10..3d63240fd0 100644 --- a/src/libxrpl/ledger/helpers/OfferHelpers.cpp +++ b/src/libxrpl/ledger/helpers/OfferHelpers.cpp @@ -16,7 +16,7 @@ offerDelete(ApplyView& view, std::shared_ptr const& sle, beast::Journal j) auto owner = sle->getAccountID(sfAccount); // Detect legacy directories. - uint256 uDirectory = sle->getFieldH256(sfBookDirectory); + uint256 const uDirectory = sle->getFieldH256(sfBookDirectory); if (!view.dirRemove(keylet::ownerDir(owner), sle->getFieldU64(sfOwnerNode), offerIndex, false)) { diff --git a/src/libxrpl/ledger/helpers/RippleStateHelpers.cpp b/src/libxrpl/ledger/helpers/RippleStateHelpers.cpp index 22a0967939..697b8fc293 100644 --- a/src/libxrpl/ledger/helpers/RippleStateHelpers.cpp +++ b/src/libxrpl/ledger/helpers/RippleStateHelpers.cpp @@ -275,8 +275,8 @@ trustDelete( beast::Journal j) { // Detect legacy dirs. - std::uint64_t uLowNode = sleRippleState->getFieldU64(sfLowNode); - std::uint64_t uHighNode = sleRippleState->getFieldU64(sfHighNode); + std::uint64_t const uLowNode = sleRippleState->getFieldU64(sfLowNode); + std::uint64_t const uHighNode = sleRippleState->getFieldU64(sfHighNode); JLOG(j.trace()) << "trustDelete: Deleting ripple line: low"; @@ -374,7 +374,7 @@ issueIOU( JLOG(j.trace()) << "issueIOU: " << to_string(account) << ": " << amount.getFullText(); - bool bSenderHigh = issue.account > account; + bool const bSenderHigh = issue.account > account; auto const index = keylet::line(issue.account, account, issue.currency); @@ -428,7 +428,7 @@ issueIOU( if (!receiverAccount) return tefINTERNAL; // LCOV_EXCL_LINE - bool noRipple = (receiverAccount->getFlags() & lsfDefaultRipple) == 0; + bool const noRipple = (receiverAccount->getFlags() & lsfDefaultRipple) == 0; return trustCreate( view, @@ -468,7 +468,7 @@ redeemIOU( JLOG(j.trace()) << "redeemIOU: " << to_string(account) << ": " << amount.getFullText(); - bool bSenderHigh = account > issue.account; + bool const bSenderHigh = account > issue.account; if (auto state = view.peek(keylet::line(account, issue.account, issue.currency))) { diff --git a/src/libxrpl/ledger/helpers/TokenHelpers.cpp b/src/libxrpl/ledger/helpers/TokenHelpers.cpp index 27ee257e64..ce4ba4002a 100644 --- a/src/libxrpl/ledger/helpers/TokenHelpers.cpp +++ b/src/libxrpl/ledger/helpers/TokenHelpers.cpp @@ -253,7 +253,7 @@ accountHolds( beast::Journal j, SpendableHandling includeFullBalance) { - STAmount amount; + STAmount const amount; if (isXRP(currency)) { return {xrpLiquid(view, account, 0, j)}; @@ -726,7 +726,7 @@ rippleSendMultiIOU( for (auto const& r : receivers) { auto const& receiverID = r.first; - STAmount amount{issue, r.second}; + STAmount const amount{issue, r.second}; /* If we aren't sending anything or if the sender is the same as the * receiver then we don't need to do anything. @@ -752,7 +752,7 @@ rippleSendMultiIOU( // Calculate the amount to transfer accounting // for any transfer fees if the fee is not waived: - STAmount actualSend = (waiveFee == WaiveTransferFee::Yes) + STAmount const actualSend = (waiveFee == WaiveTransferFee::Yes) ? amount : multiply(amount, transferRate(view, issuer)); actual += actualSend; @@ -823,9 +823,9 @@ accountSendIOU( */ TER terResult(tesSUCCESS); - SLE::pointer sender = + SLE::pointer const sender = uSenderID != beast::zero ? view.peek(keylet::account(uSenderID)) : SLE::pointer(); - SLE::pointer receiver = + SLE::pointer const receiver = uReceiverID != beast::zero ? view.peek(keylet::account(uReceiverID)) : SLE::pointer(); if (auto stream = j.trace()) @@ -921,7 +921,7 @@ accountSendMultiIOU( * ensure that transfers are balanced. */ - SLE::pointer sender = + SLE::pointer const sender = senderID != beast::zero ? view.peek(keylet::account(senderID)) : SLE::pointer(); if (auto stream = j.trace()) @@ -940,7 +940,7 @@ accountSendMultiIOU( for (auto const& r : receivers) { auto const& receiverID = r.first; - STAmount amount{issue, r.second}; + STAmount const amount{issue, r.second}; if (amount < beast::zero) { @@ -953,7 +953,7 @@ accountSendMultiIOU( if (!amount || (senderID == receiverID)) continue; - SLE::pointer receiver = + SLE::pointer const receiver = receiverID != beast::zero ? view.peek(keylet::account(receiverID)) : SLE::pointer(); if (auto stream = j.trace()) @@ -1170,7 +1170,7 @@ rippleSendMultiMPT( for (auto const& r : receivers) { auto const& receiverID = r.first; - STAmount amount{mptIssue, r.second}; + STAmount const amount{mptIssue, r.second}; if (amount < beast::zero) { @@ -1211,7 +1211,7 @@ rippleSendMultiMPT( } // Sending 3rd party MPTs: transit. - STAmount actualSend = (waiveFee == WaiveTransferFee::Yes) + STAmount const actualSend = (waiveFee == WaiveTransferFee::Yes) ? amount : multiply(amount, transferRate(view, amount.get().getMptID())); actual += actualSend; diff --git a/src/libxrpl/net/HTTPClient.cpp b/src/libxrpl/net/HTTPClient.cpp index 65205be39c..5cb01cb54b 100644 --- a/src/libxrpl/net/HTTPClient.cpp +++ b/src/libxrpl/net/HTTPClient.cpp @@ -347,10 +347,10 @@ public: {std::istreambuf_iterator(&mHeader)}, std::istreambuf_iterator()}; JLOG(j_.trace()) << "Header: \"" << strHeader << "\""; - static boost::regex reStatus{"\\`HTTP/1\\S+ (\\d{3}) .*\\'"}; // HTTP/1.1 200 OK - static boost::regex reSize{ + static boost::regex const reStatus{"\\`HTTP/1\\S+ (\\d{3}) .*\\'"}; // HTTP/1.1 200 OK + static boost::regex const reSize{ "\\`.*\\r\\nContent-Length:\\s+([0-9]+).*\\'", boost::regex::icase}; - static boost::regex reBody{"\\`.*\\r\\n\\r\\n(.*)\\'"}; + static boost::regex const reBody{"\\`.*\\r\\n\\r\\n(.*)\\'"}; boost::smatch smMatch; // Match status code. @@ -428,7 +428,7 @@ public: else { mResponse.commit(bytes_transferred); - std::string strBody{ + std::string const strBody{ {std::istreambuf_iterator(&mResponse)}, std::istreambuf_iterator()}; invokeComplete(ecResult, mStatus, mBody + strBody); } @@ -547,7 +547,7 @@ HTTPClient::get( complete, beast::Journal& j) { - std::deque deqSites(1, strSite); + std::deque const deqSites(1, strSite); auto client = std::make_shared(io_context, port, responseMax, j); client->get(bSSL, deqSites, strPath, timeout, complete); @@ -567,7 +567,7 @@ HTTPClient::request( complete, beast::Journal& j) { - std::deque deqSites(1, strSite); + std::deque const deqSites(1, strSite); auto client = std::make_shared(io_context, port, responseMax, j); client->request(bSSL, deqSites, setRequest, timeout, complete); diff --git a/src/libxrpl/nodestore/BatchWriter.cpp b/src/libxrpl/nodestore/BatchWriter.cpp index 98fe78c489..50f4486f59 100644 --- a/src/libxrpl/nodestore/BatchWriter.cpp +++ b/src/libxrpl/nodestore/BatchWriter.cpp @@ -37,7 +37,7 @@ BatchWriter::store(std::shared_ptr const& object) int BatchWriter::getWriteLoad() { - std::lock_guard sl(mWriteMutex); + std::lock_guard const sl(mWriteMutex); return std::max(mWriteLoad, static_cast(mWriteSet.size())); } @@ -58,7 +58,7 @@ BatchWriter::writeBatch() set.reserve(batchWritePreallocationSize); { - std::lock_guard sl(mWriteMutex); + std::lock_guard const sl(mWriteMutex); mWriteSet.swap(set); XRPL_ASSERT( diff --git a/src/libxrpl/nodestore/Database.cpp b/src/libxrpl/nodestore/Database.cpp index 4e0d5be05d..5d9d153f57 100644 --- a/src/libxrpl/nodestore/Database.cpp +++ b/src/libxrpl/nodestore/Database.cpp @@ -122,7 +122,7 @@ void Database::stop() { { - std::lock_guard lock(readLock_); + std::lock_guard const lock(readLock_); if (!readStopping_.exchange(true, std::memory_order_relaxed)) { @@ -158,7 +158,7 @@ Database::asyncFetch( std::uint32_t ledgerSeq, std::function const&)>&& cb) { - std::lock_guard lock(readLock_); + std::lock_guard const lock(readLock_); if (!isStopping()) { @@ -238,7 +238,7 @@ Database::getCountsJson(Json::Value& obj) XRPL_ASSERT(obj.isObject(), "xrpl::NodeStore::Database::getCountsJson : valid input type"); { - std::unique_lock lock(readLock_); + std::unique_lock const lock(readLock_); obj["read_queue"] = static_cast(read_.size()); } diff --git a/src/libxrpl/nodestore/DatabaseRotatingImp.cpp b/src/libxrpl/nodestore/DatabaseRotatingImp.cpp index 6cf51fbf31..aa04b17b33 100644 --- a/src/libxrpl/nodestore/DatabaseRotatingImp.cpp +++ b/src/libxrpl/nodestore/DatabaseRotatingImp.cpp @@ -33,7 +33,7 @@ DatabaseRotatingImp::rotate( // deleted. std::shared_ptr oldArchiveBackend; { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); archiveBackend_->setDeletePath(); oldArchiveBackend = std::move(archiveBackend_); @@ -50,14 +50,14 @@ DatabaseRotatingImp::rotate( std::string DatabaseRotatingImp::getName() const { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); return writableBackend_->getName(); } std::int32_t DatabaseRotatingImp::getWriteLoad() const { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); return writableBackend_->getWriteLoad(); } @@ -65,7 +65,7 @@ void DatabaseRotatingImp::importDatabase(Database& source) { auto const backend = [&] { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); return writableBackend_; }(); @@ -75,7 +75,7 @@ DatabaseRotatingImp::importDatabase(Database& source) void DatabaseRotatingImp::sync() { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); writableBackend_->sync(); } @@ -85,7 +85,7 @@ DatabaseRotatingImp::store(NodeObjectType type, Blob&& data, uint256 const& hash auto nObj = NodeObject::createObject(type, std::move(data), hash); auto const backend = [&] { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); return writableBackend_; }(); @@ -133,7 +133,7 @@ DatabaseRotatingImp::fetchNodeObject( std::shared_ptr nodeObject; auto [writable, archive] = [&] { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); return std::make_pair(writableBackend_, archiveBackend_); }(); @@ -147,7 +147,7 @@ DatabaseRotatingImp::fetchNodeObject( { { // Refresh the writable backend pointer - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); writable = writableBackend_; } @@ -167,7 +167,7 @@ void DatabaseRotatingImp::for_each(std::function)> f) { auto [writable, archive] = [&] { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); return std::make_pair(writableBackend_, archiveBackend_); }(); diff --git a/src/libxrpl/nodestore/ManagerImp.cpp b/src/libxrpl/nodestore/ManagerImp.cpp index da9534f68b..7925ccdb91 100644 --- a/src/libxrpl/nodestore/ManagerImp.cpp +++ b/src/libxrpl/nodestore/ManagerImp.cpp @@ -80,14 +80,14 @@ ManagerImp::make_Database( void ManagerImp::insert(Factory& factory) { - std::lock_guard _(mutex_); + std::lock_guard const _(mutex_); list_.push_back(&factory); } void ManagerImp::erase(Factory& factory) { - std::lock_guard _(mutex_); + std::lock_guard const _(mutex_); auto const iter = std::find_if( list_.begin(), list_.end(), [&factory](Factory* other) { return other == &factory; }); XRPL_ASSERT(iter != list_.end(), "xrpl::NodeStore::ManagerImp::erase : valid input"); @@ -97,7 +97,7 @@ ManagerImp::erase(Factory& factory) Factory* ManagerImp::find(std::string const& name) { - std::lock_guard _(mutex_); + std::lock_guard const _(mutex_); auto const iter = std::find_if(list_.begin(), list_.end(), [&name](Factory* other) { return boost::iequals(name, other->getName()); }); diff --git a/src/libxrpl/nodestore/backend/MemoryFactory.cpp b/src/libxrpl/nodestore/backend/MemoryFactory.cpp index 0366fe3573..a245af3030 100644 --- a/src/libxrpl/nodestore/backend/MemoryFactory.cpp +++ b/src/libxrpl/nodestore/backend/MemoryFactory.cpp @@ -45,7 +45,7 @@ public: MemoryDB& open(std::string const& path) { - std::lock_guard _(mutex_); + std::lock_guard const _(mutex_); auto const result = map_.emplace(std::piecewise_construct, std::make_tuple(path), std::make_tuple()); MemoryDB& db = result.first->second; @@ -120,9 +120,9 @@ public: { XRPL_ASSERT(db_, "xrpl::NodeStore::MemoryBackend::fetch : non-null database"); - std::lock_guard _(db_->mutex); + std::lock_guard const _(db_->mutex); - Map::iterator iter = db_->table.find(hash); + Map::iterator const iter = db_->table.find(hash); if (iter == db_->table.end()) { pObject->reset(); @@ -140,7 +140,7 @@ public: for (auto const& h : hashes) { std::shared_ptr nObj; - Status status = fetch(h, &nObj); + Status const status = fetch(h, &nObj); if (status != ok) { results.push_back({}); @@ -158,7 +158,7 @@ public: store(std::shared_ptr const& object) override { XRPL_ASSERT(db_, "xrpl::NodeStore::MemoryBackend::store : non-null database"); - std::lock_guard _(db_->mutex); + std::lock_guard const _(db_->mutex); db_->table.emplace(object->getHash(), object); } diff --git a/src/libxrpl/nodestore/backend/NuDBFactory.cpp b/src/libxrpl/nodestore/backend/NuDBFactory.cpp index 2d8cffa85a..424778f280 100644 --- a/src/libxrpl/nodestore/backend/NuDBFactory.cpp +++ b/src/libxrpl/nodestore/backend/NuDBFactory.cpp @@ -214,7 +214,7 @@ public: for (auto const& h : hashes) { std::shared_ptr nObj; - Status status = fetch(h, &nObj); + Status const status = fetch(h, &nObj); if (status != ok) { results.push_back({}); @@ -231,7 +231,7 @@ public: void do_insert(std::shared_ptr const& no) { - EncodedBlob e(no); + EncodedBlob const e(no); nudb::error_code ec; nudb::detail::buffer bf; auto const result = nodeobject_compress(e.getData(), e.getSize(), bf); @@ -353,7 +353,7 @@ private: auto const kp = (folder / "nudb.key").string(); std::size_t const defaultSize = nudb::block_size(kp); // Default 4K from NuDB - std::size_t blockSize = defaultSize; + std::size_t const blockSize = defaultSize; std::string blockSizeStr; if (!get_if_exists(keyValues, "nudb_block_size", blockSizeStr)) @@ -434,7 +434,7 @@ public: void registerNuDBFactory(Manager& manager) { - static NuDBFactory instance{manager}; + static NuDBFactory const instance{manager}; } } // namespace NodeStore diff --git a/src/libxrpl/nodestore/backend/NullFactory.cpp b/src/libxrpl/nodestore/backend/NullFactory.cpp index ab5b7d0117..617dfd893d 100644 --- a/src/libxrpl/nodestore/backend/NullFactory.cpp +++ b/src/libxrpl/nodestore/backend/NullFactory.cpp @@ -117,7 +117,7 @@ public: void registerNullFactory(Manager& manager) { - static NullFactory instance{manager}; + static NullFactory const instance{manager}; } } // namespace NodeStore diff --git a/src/libxrpl/nodestore/backend/RocksDBFactory.cpp b/src/libxrpl/nodestore/backend/RocksDBFactory.cpp index ac040f178b..4ce7c3f10c 100644 --- a/src/libxrpl/nodestore/backend/RocksDBFactory.cpp +++ b/src/libxrpl/nodestore/backend/RocksDBFactory.cpp @@ -37,18 +37,17 @@ public: static void thread_entry(void* ptr) { - ThreadParams* const p(reinterpret_cast(ptr)); - void (*f)(void*) = p->f; + ThreadParams const* const p(reinterpret_cast(ptr)); + auto const f = p->f; + void* a(p->a); delete p; static std::atomic n; std::size_t const id(++n); - std::stringstream ss; - ss << "rocksdb #" << id; - beast::setCurrentThreadName(ss.str()); + beast::setCurrentThreadName("rocksdb #" + std::to_string(id)); - (*f)(a); + f(a); } void @@ -89,7 +88,7 @@ public: rocksdb::BlockBasedTableOptions table_options; m_options.env = env; - bool hard_set = keyValues.exists("hard_set") && get(keyValues, "hard_set"); + bool const hard_set = keyValues.exists("hard_set") && get(keyValues, "hard_set"); if (keyValues.exists("cache_mb")) { @@ -162,7 +161,7 @@ public: if (keyValues.exists("bbt_options")) { - rocksdb::ConfigOptions config_options; + rocksdb::ConfigOptions const config_options; auto const s = rocksdb::GetBlockBasedTableOptionsFromString( config_options, table_options, get(keyValues, "bbt_options"), &table_options); if (!s.ok()) @@ -212,7 +211,7 @@ public: } rocksdb::DB* db = nullptr; m_options.create_if_missing = createIfMissing; - rocksdb::Status status = rocksdb::DB::Open(m_options, m_name, &db); + rocksdb::Status const status = rocksdb::DB::Open(m_options, m_name, &db); if (!status.ok() || (db == nullptr)) { Throw( @@ -235,7 +234,7 @@ public: m_db.reset(); if (m_deletePath) { - boost::filesystem::path dir = m_name; + boost::filesystem::path const dir = m_name; boost::filesystem::remove_all(dir); } } @@ -262,7 +261,7 @@ public: std::string string; - rocksdb::Status getStatus = m_db->Get(options, slice, &string); + rocksdb::Status const getStatus = m_db->Get(options, slice, &string); if (getStatus.ok()) { @@ -308,7 +307,7 @@ public: for (auto const& h : hashes) { std::shared_ptr nObj; - Status status = fetch(h, &nObj); + Status const status = fetch(h, &nObj); if (status != ok) { results.push_back({}); @@ -339,7 +338,7 @@ public: for (auto const& e : batch) { - EncodedBlob encoded(e); + EncodedBlob const encoded(e); wb.Put( rocksdb::Slice(std::bit_cast(encoded.getKey()), m_keyBytes), @@ -456,7 +455,7 @@ public: void registerRocksDBFactory(Manager& manager) { - static RocksDBFactory instance{manager}; + static RocksDBFactory const instance{manager}; } } // namespace NodeStore diff --git a/src/libxrpl/protocol/AccountID.cpp b/src/libxrpl/protocol/AccountID.cpp index 4edbf5c0e7..2c64457c87 100644 --- a/src/libxrpl/protocol/AccountID.cpp +++ b/src/libxrpl/protocol/AccountID.cpp @@ -55,7 +55,7 @@ public: packed_spinlock sl(locks_, index % 64); { - std::lock_guard lock(sl); + std::lock_guard const lock(sl); // The check against the first character of the encoding ensures // that we don't mishandle the case of the all-zero account: @@ -68,7 +68,7 @@ public: XRPL_ASSERT(ret.size() <= 38, "xrpl::detail::AccountIdCache : maximum result size"); { - std::lock_guard lock(sl); + std::lock_guard const lock(sl); cache_[index].id = id; std::strcpy(cache_[index].encoding, ret.c_str()); } diff --git a/src/libxrpl/protocol/InnerObjectFormats.cpp b/src/libxrpl/protocol/InnerObjectFormats.cpp index bccfe210d1..8429c51aea 100644 --- a/src/libxrpl/protocol/InnerObjectFormats.cpp +++ b/src/libxrpl/protocol/InnerObjectFormats.cpp @@ -164,7 +164,7 @@ InnerObjectFormats::InnerObjectFormats() InnerObjectFormats const& InnerObjectFormats::getInstance() { - static InnerObjectFormats instance; + static InnerObjectFormats const instance; return instance; } diff --git a/src/libxrpl/protocol/LedgerFormats.cpp b/src/libxrpl/protocol/LedgerFormats.cpp index 30725f44a9..9f8bd6a2ba 100644 --- a/src/libxrpl/protocol/LedgerFormats.cpp +++ b/src/libxrpl/protocol/LedgerFormats.cpp @@ -40,7 +40,7 @@ LedgerFormats::LedgerFormats() LedgerFormats const& LedgerFormats::getInstance() { - static LedgerFormats instance; + static LedgerFormats const instance; return instance; } diff --git a/src/libxrpl/protocol/NFTokenID.cpp b/src/libxrpl/protocol/NFTokenID.cpp index d867cdb8c9..a808ef1fcf 100644 --- a/src/libxrpl/protocol/NFTokenID.cpp +++ b/src/libxrpl/protocol/NFTokenID.cpp @@ -159,7 +159,7 @@ insertNFTokenID( } else if (type == ttNFTOKEN_CANCEL_OFFER) { - std::vector result = getNFTokenIDFromDeletedOffer(transactionMeta); + std::vector const result = getNFTokenIDFromDeletedOffer(transactionMeta); response[jss::nftoken_ids] = Json::Value(Json::arrayValue); for (auto const& nftID : result) diff --git a/src/libxrpl/protocol/PublicKey.cpp b/src/libxrpl/protocol/PublicKey.cpp index 2e08c49a4e..fc63edd2fc 100644 --- a/src/libxrpl/protocol/PublicKey.cpp +++ b/src/libxrpl/protocol/PublicKey.cpp @@ -130,11 +130,11 @@ ecdsaCanonicality(Slice const& sig) if (!r || !s || !p.empty()) return std::nullopt; - uint264 R(sliceToHex(*r)); + uint264 const R(sliceToHex(*r)); if (R >= G) return std::nullopt; - uint264 S(sliceToHex(*s)); + uint264 const S(sliceToHex(*s)); if (S >= G) return std::nullopt; diff --git a/src/libxrpl/protocol/QualityFunction.cpp b/src/libxrpl/protocol/QualityFunction.cpp index ebc59dcc83..1774603a61 100644 --- a/src/libxrpl/protocol/QualityFunction.cpp +++ b/src/libxrpl/protocol/QualityFunction.cpp @@ -31,7 +31,7 @@ QualityFunction::outFromAvgQ(Quality const& quality) { if (m_ != 0 && quality.rate() != beast::zero) { - saveNumberRoundMode rm(Number::setround(Number::rounding_mode::upward)); + saveNumberRoundMode const rm(Number::setround(Number::rounding_mode::upward)); auto const out = (1 / quality.rate() - b_) / m_; if (out <= 0) return std::nullopt; diff --git a/src/libxrpl/protocol/Rules.cpp b/src/libxrpl/protocol/Rules.cpp index 4ef052d2cc..fd54a1eff2 100644 --- a/src/libxrpl/protocol/Rules.cpp +++ b/src/libxrpl/protocol/Rules.cpp @@ -39,7 +39,7 @@ setCurrentTransactionRules(std::optional r) // Make global changes associated with the rules before the value is moved. // Push the appropriate setting, instead of having the class pull every time // the value is needed. That could get expensive fast. - bool enableLargeNumbers = + bool const enableLargeNumbers = !r || (r->enabled(featureSingleAssetVault) || r->enabled(featureLendingProtocol)); Number::setMantissaScale(enableLargeNumbers ? MantissaRange::large : MantissaRange::small); diff --git a/src/libxrpl/protocol/STAmount.cpp b/src/libxrpl/protocol/STAmount.cpp index 8c0068a275..0a0da2193e 100644 --- a/src/libxrpl/protocol/STAmount.cpp +++ b/src/libxrpl/protocol/STAmount.cpp @@ -154,7 +154,7 @@ STAmount::STAmount(SerialIter& sit, SField const& name) : STBase(name) if (value != 0u) { - bool isNegative = (offset & 256) == 0; + bool const isNegative = (offset & 256) == 0; offset = (offset & 255) - 97; // center the range if (value < cMinValue || value > cMaxValue || offset < cMinOffset || offset > cMaxOffset) @@ -410,7 +410,7 @@ operator+(STAmount const& v1, STAmount const& v2) // This addition cannot overflow an std::int64_t. It can overflow an // STAmount and the constructor will throw. - std::int64_t fv = vv1 + vv2; + std::int64_t const fv = vv1 + vv2; if ((fv >= -10) && (fv <= 10)) return {v1.getFName(), v1.asset()}; @@ -454,13 +454,13 @@ getRate(STAmount const& offerOut, STAmount const& offerIn) try { - STAmount r = divide(offerIn, offerOut, noIssue()); + STAmount const r = divide(offerIn, offerOut, noIssue()); if (r == beast::zero) // offer is too good return 0; XRPL_ASSERT( (r.exponent() >= -100) && (r.exponent() <= 155), "xrpl::getRate : exponent inside range"); - std::uint64_t ret = r.exponent() + 100; + std::uint64_t const ret = r.exponent() + 100; return (ret << (64 - 8)) | r.mantissa(); } catch (...) @@ -502,8 +502,8 @@ canAdd(STAmount const& a, STAmount const& b) // XRP case (overflow & underflow check) if (isXRP(a) && isXRP(b)) { - XRPAmount A = a.xrp(); - XRPAmount B = b.xrp(); + XRPAmount const A = a.xrp(); + XRPAmount const B = b.xrp(); return !( (B > XRPAmount{0} && @@ -517,16 +517,16 @@ canAdd(STAmount const& a, STAmount const& b) { static STAmount const one{IOUAmount{1, 0}, noIssue()}; static STAmount const maxLoss{IOUAmount{1, -4}, noIssue()}; - STAmount lhs = divide((a - b) + b, a, noIssue()) - one; - STAmount rhs = divide((b - a) + a, b, noIssue()) - one; + STAmount const lhs = divide((a - b) + b, a, noIssue()) - one; + STAmount const rhs = divide((b - a) + a, b, noIssue()) - one; return ((rhs.negative() ? -rhs : rhs) + (lhs.negative() ? -lhs : lhs)) <= maxLoss; } // MPT (overflow & underflow check) if (a.holds() && b.holds()) { - MPTAmount A = a.mpt(); - MPTAmount B = b.mpt(); + MPTAmount const A = a.mpt(); + MPTAmount const B = b.mpt(); return !( (B > MPTAmount{0} && A > MPTAmount{std::numeric_limits::max()} - B) || @@ -570,8 +570,8 @@ canSubtract(STAmount const& a, STAmount const& b) // XRP case (underflow & overflow check) if (isXRP(a) && isXRP(b)) { - XRPAmount A = a.xrp(); - XRPAmount B = b.xrp(); + XRPAmount const A = a.xrp(); + XRPAmount const B = b.xrp(); // Check for underflow if (B > XRPAmount{0} && A < B) return false; @@ -593,8 +593,8 @@ canSubtract(STAmount const& a, STAmount const& b) // MPT case (underflow & overflow check) if (a.holds() && b.holds()) { - MPTAmount A = a.mpt(); - MPTAmount B = b.mpt(); + MPTAmount const A = a.mpt(); + MPTAmount const B = b.mpt(); // Underflow check if (B > MPTAmount{0} && A < B) @@ -847,7 +847,7 @@ STAmount::canonicalize() if (getSTNumberSwitchover()) { - Number num(mIsNegative, mValue, mOffset, Number::unchecked{}); + Number const num(mIsNegative, mValue, mOffset, Number::unchecked{}); auto set = [&](auto const& val) { auto const value = val.value(); mIsNegative = value < 0; @@ -977,8 +977,8 @@ amountFromQuality(std::uint64_t rate) if (rate == 0) return STAmount(noIssue()); - std::uint64_t mantissa = rate & ~(255ull << (64 - 8)); - int exponent = static_cast(rate >> (64 - 8)) - 100; + std::uint64_t const mantissa = rate & ~(255ull << (64 - 8)); + int const exponent = static_cast(rate >> (64 - 8)) - 100; return STAmount(noIssue(), mantissa, exponent); } @@ -1474,7 +1474,7 @@ roundToScale(STAmount const& value, std::int32_t scale, Number::rounding_mode ro STAmount const referenceValue{value.asset(), STAmount::cMinValue, scale, value.negative()}; - NumberRoundModeGuard mg(rounding); + NumberRoundModeGuard const mg(rounding); // With an IOU, the the result of addition will be truncated to the // precision of the larger value, which in this case is referenceValue. Then // remove the reference value via subtraction, and we're left with the @@ -1516,8 +1516,8 @@ mulRoundImpl(STAmount const& v1, STAmount const& v2, Asset const& asset, bool ro if (v1.native() && v2.native() && xrp) { - std::uint64_t minV = std::min(getSNValue(v1), getSNValue(v2)); - std::uint64_t maxV = std::max(getSNValue(v1), getSNValue(v2)); + std::uint64_t const minV = std::min(getSNValue(v1), getSNValue(v2)); + std::uint64_t const maxV = std::max(getSNValue(v1), getSNValue(v2)); if (minV > 3000000000ull) // sqrt(cMaxNative) Throw("Native value overflow"); diff --git a/src/libxrpl/protocol/STIssue.cpp b/src/libxrpl/protocol/STIssue.cpp index bc39ea1b55..5acf4abcb6 100644 --- a/src/libxrpl/protocol/STIssue.cpp +++ b/src/libxrpl/protocol/STIssue.cpp @@ -38,7 +38,7 @@ STIssue::STIssue(SerialIter& sit, SField const& name) : STBase{name} // - 160 bits MPT issuer account // - 160 bits black hole account // - 32 bits sequence - AccountID account = static_cast(sit.get160()); + AccountID const account = static_cast(sit.get160()); // MPT if (noAccount() == account) { @@ -50,7 +50,7 @@ STIssue::STIssue(SerialIter& sit, SField const& name) : STBase{name} mptID.data() + sizeof(sequence), currencyOrAccount.data(), sizeof(currencyOrAccount)); - MPTIssue issue{mptID}; + MPTIssue const issue{mptID}; asset_ = issue; } else diff --git a/src/libxrpl/protocol/STLedgerEntry.cpp b/src/libxrpl/protocol/STLedgerEntry.cpp index 02e5ddb451..5a80559c98 100644 --- a/src/libxrpl/protocol/STLedgerEntry.cpp +++ b/src/libxrpl/protocol/STLedgerEntry.cpp @@ -147,7 +147,7 @@ STLedgerEntry::thread( uint256& prevTxID, std::uint32_t& prevLedgerID) { - uint256 oldPrevTxID = getFieldH256(sfPreviousTxnID); + uint256 const oldPrevTxID = getFieldH256(sfPreviousTxnID); JLOG(debugLog().info()) << "Thread Tx:" << txID << " prev:" << oldPrevTxID; diff --git a/src/libxrpl/protocol/STNumber.cpp b/src/libxrpl/protocol/STNumber.cpp index aab4bdc0f5..8899a76a35 100644 --- a/src/libxrpl/protocol/STNumber.cpp +++ b/src/libxrpl/protocol/STNumber.cpp @@ -177,7 +177,7 @@ partsFromString(std::string const& number) // 6 = exponent sign // 7 = exponent number - bool negative = (match[1].matched && (match[1] == "-")); + bool const negative = (match[1].matched && (match[1] == "-")); std::uint64_t mantissa = 0; int exponent = 0; @@ -241,6 +241,7 @@ numberFromJson(SField const& field, Json::Value const& value) // Number mantissas are much bigger than the allowable parsed values, so // it can't be out of range. static_assert( + // NOLINTNEXTLINE(misc-redundant-expression) std::numeric_limits::max() >= std::numeric_limits::max()); } diff --git a/src/libxrpl/protocol/STObject.cpp b/src/libxrpl/protocol/STObject.cpp index 182653d11d..f758760337 100644 --- a/src/libxrpl/protocol/STObject.cpp +++ b/src/libxrpl/protocol/STObject.cpp @@ -156,7 +156,7 @@ STObject::applyTemplate(SOTemplate const& type) auto throwFieldErr = [](std::string const& field, char const* description) { std::stringstream ss; ss << "Field '" << field << "' " << description; - std::string text{ss.str()}; + std::string const text{ss.str()}; JLOG(debugLog().error()) << "STObject::applyTemplate failed: " << text; Throw(text); }; @@ -400,7 +400,7 @@ STObject::getFieldIndex(SField const& field) const STBase const& STObject::peekAtField(SField const& field) const { - int index = getFieldIndex(field); + int const index = getFieldIndex(field); if (index == -1) throwFieldNotFound(field); @@ -411,7 +411,7 @@ STObject::peekAtField(SField const& field) const STBase& STObject::getField(SField const& field) { - int index = getFieldIndex(field); + int const index = getFieldIndex(field); if (index == -1) throwFieldNotFound(field); @@ -428,7 +428,7 @@ STObject::getFieldSType(int index) const STBase const* STObject::peekAtPField(SField const& field) const { - int index = getFieldIndex(field); + int const index = getFieldIndex(field); if (index == -1) return nullptr; @@ -439,7 +439,7 @@ STObject::peekAtPField(SField const& field) const STBase* STObject::getPField(SField const& field, bool createOkay) { - int index = getFieldIndex(field); + int const index = getFieldIndex(field); if (index == -1) { @@ -455,7 +455,7 @@ STObject::getPField(SField const& field, bool createOkay) bool STObject::isFieldPresent(SField const& field) const { - int index = getFieldIndex(field); + int const index = getFieldIndex(field); if (index == -1) return false; @@ -519,7 +519,7 @@ STObject::getFlags(void) const STBase* STObject::makeFieldPresent(SField const& field) { - int index = getFieldIndex(field); + int const index = getFieldIndex(field); if (index == -1) { @@ -529,7 +529,7 @@ STObject::makeFieldPresent(SField const& field) return getPIndex(emplace_back(detail::nonPresentObject, field)); } - STBase* f = getPIndex(index); + STBase* f = getPIndex(index); // NOLINT(misc-const-correctness) if (f->getSType() != STI_NOTPRESENT) return f; @@ -541,7 +541,7 @@ STObject::makeFieldPresent(SField const& field) void STObject::makeFieldAbsent(SField const& field) { - int index = getFieldIndex(field); + int const index = getFieldIndex(field); if (index == -1) throwFieldNotFound(field); @@ -556,7 +556,7 @@ STObject::makeFieldAbsent(SField const& field) bool STObject::delField(SField const& field) { - int index = getFieldIndex(field); + int const index = getFieldIndex(field); if (index == -1) return false; @@ -640,7 +640,7 @@ STObject::getAccountID(SField const& field) const Blob STObject::getFieldVL(SField const& field) const { - STBlob empty; + STBlob const empty; STBlob const& b = getFieldByConstRef(field, empty); return Blob(b.data(), b.data() + b.size()); } diff --git a/src/libxrpl/protocol/STParsedJSON.cpp b/src/libxrpl/protocol/STParsedJSON.cpp index 702ad28414..c928f49375 100644 --- a/src/libxrpl/protocol/STParsedJSON.cpp +++ b/src/libxrpl/protocol/STParsedJSON.cpp @@ -1093,7 +1093,7 @@ parseArray( auto ret = parseObject(ss.str(), objectFields, nameField, depth + 1, error); if (!ret) { - std::string errMsg = error["error_message"].asString(); + std::string const errMsg = error["error_message"].asString(); error["error_message"] = "Error at '" + ss.str() + "'. " + errMsg; return std::nullopt; } diff --git a/src/libxrpl/protocol/STPathSet.cpp b/src/libxrpl/protocol/STPathSet.cpp index fde33fb58e..2536c18e4e 100644 --- a/src/libxrpl/protocol/STPathSet.cpp +++ b/src/libxrpl/protocol/STPathSet.cpp @@ -45,7 +45,7 @@ STPathSet::STPathSet(SerialIter& sit, SField const& name) : STBase(name) std::vector path; for (;;) { - int iType = sit.get8(); + int const iType = sit.get8(); if (iType == STPathElement::typeNone || iType == STPathElement::typeBoundary) { @@ -205,7 +205,7 @@ STPathSet::add(Serializer& s) const for (auto const& speElement : spPath) { - int iType = speElement.getNodeType(); + int const iType = speElement.getNodeType(); s.add8(iType); diff --git a/src/libxrpl/protocol/STTx.cpp b/src/libxrpl/protocol/STTx.cpp index 7da1919f35..f8600e167f 100644 --- a/src/libxrpl/protocol/STTx.cpp +++ b/src/libxrpl/protocol/STTx.cpp @@ -77,7 +77,7 @@ STTx::STTx(STObject&& object) : STObject(std::move(object)) STTx::STTx(SerialIter& sit) : STObject(sfTransaction) { - int length = sit.getBytesLeft(); + int const length = sit.getBytesLeft(); if ((length < txMinSizeBytes) || (length > txMaxSizeBytes)) Throw("Transaction length invalid"); @@ -329,7 +329,7 @@ STTx::getJson(JsonOptions options, bool binary) const if (binary) { - Serializer s = STObject::getSerializer(); + Serializer const s = STObject::getSerializer(); std::string const dataBin = strHex(s.peekData()); if (V1) @@ -378,7 +378,7 @@ STTx::getMetaSQL( TxnSql status, std::string const& escapedMetaData) const { - static boost::format bfTrans("('%s', '%s', '%s', '%d', '%d', '%c', %s, %s)"); + static boost::format const bfTrans("('%s', '%s', '%s', '%d', '%d', '%c', %s, %s)"); std::string rTxn = sqlBlobLiteral(rawTxn.peekData()); auto format = TxFormats::getInstance().findByType(tx_type_); @@ -656,18 +656,18 @@ isMemoOkay(STObject const& st, std::string& reason) static constexpr std::array const allowedSymbols = []() { std::array a{}; - std::string_view symbols( + std::string_view const symbols( "0123456789" "-._~:/?#[]@!$&'()*+,;=%" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"); - for (unsigned char c : symbols) + for (unsigned char const c : symbols) a[c] = 1; return a; }(); - for (unsigned char c : *optData) + for (unsigned char const c : *optData) { if (allowedSymbols[c] == 0) { diff --git a/src/libxrpl/protocol/SecretKey.cpp b/src/libxrpl/protocol/SecretKey.cpp index aa398e9fe1..f58bb81a88 100644 --- a/src/libxrpl/protocol/SecretKey.cpp +++ b/src/libxrpl/protocol/SecretKey.cpp @@ -185,7 +185,7 @@ public: if (secp256k1_ec_seckey_tweak_add(secp256k1Context(), rpk.data(), tweak.data()) == 1) { - SecretKey sk{Slice{rpk.data(), rpk.size()}}; + SecretKey const sk{Slice{rpk.data(), rpk.size()}}; secure_erase(rpk.data(), rpk.size()); return sk; } @@ -270,7 +270,7 @@ randomSecretKey() { std::uint8_t buf[32]; beast::rngfill(buf, sizeof(buf), crypto_prng()); - SecretKey sk(Slice{buf, sizeof(buf)}); + SecretKey const sk(Slice{buf, sizeof(buf)}); secure_erase(buf, sizeof(buf)); return sk; } @@ -281,7 +281,7 @@ generateSecretKey(KeyType type, Seed const& seed) if (type == KeyType::ed25519) { auto key = sha512Half_s(Slice(seed.data(), seed.size())); - SecretKey sk{Slice{key.data(), key.size()}}; + SecretKey const sk{Slice{key.data(), key.size()}}; secure_erase(key.data(), key.size()); return sk; } @@ -289,7 +289,7 @@ generateSecretKey(KeyType type, Seed const& seed) if (type == KeyType::secp256k1) { auto key = detail::deriveDeterministicRootKey(seed); - SecretKey sk{Slice{key.data(), key.size()}}; + SecretKey const sk{Slice{key.data(), key.size()}}; secure_erase(key.data(), key.size()); return sk; } @@ -335,7 +335,7 @@ generateKeyPair(KeyType type, Seed const& seed) switch (type) { case KeyType::secp256k1: { - detail::Generator g(seed); + detail::Generator const g(seed); return g(0); } default: diff --git a/src/libxrpl/protocol/Seed.cpp b/src/libxrpl/protocol/Seed.cpp index 8aa1d8b67d..6d33013f2f 100644 --- a/src/libxrpl/protocol/Seed.cpp +++ b/src/libxrpl/protocol/Seed.cpp @@ -48,7 +48,7 @@ randomSeed() { std::array buffer{}; beast::rngfill(buffer.data(), buffer.size(), crypto_prng()); - Seed seed(makeSlice(buffer)); + Seed const seed(makeSlice(buffer)); secure_erase(buffer.data(), buffer.size()); return seed; } diff --git a/src/libxrpl/protocol/Serializer.cpp b/src/libxrpl/protocol/Serializer.cpp index 0e8beae0d9..4e6a49f572 100644 --- a/src/libxrpl/protocol/Serializer.cpp +++ b/src/libxrpl/protocol/Serializer.cpp @@ -23,7 +23,7 @@ namespace xrpl { int Serializer::add16(std::uint16_t i) { - int ret = mData.size(); + int const ret = mData.size(); mData.push_back(static_cast(i >> 8)); mData.push_back(static_cast(i & 0xff)); return ret; @@ -73,7 +73,7 @@ Serializer::addInteger(std::int32_t i) int Serializer::addRaw(Blob const& vector) { - int ret = mData.size(); + int const ret = mData.size(); mData.insert(mData.end(), vector.begin(), vector.end()); return ret; } @@ -81,7 +81,7 @@ Serializer::addRaw(Blob const& vector) int Serializer::addRaw(Slice slice) { - int ret = mData.size(); + int const ret = mData.size(); mData.insert(mData.end(), slice.begin(), slice.end()); return ret; } @@ -89,7 +89,7 @@ Serializer::addRaw(Slice slice) int Serializer::addRaw(Serializer const& s) { - int ret = mData.size(); + int const ret = mData.size(); mData.insert(mData.end(), s.begin(), s.end()); return ret; } @@ -97,7 +97,7 @@ Serializer::addRaw(Serializer const& s) int Serializer::addRaw(void const* ptr, int len) { - int ret = mData.size(); + int const ret = mData.size(); mData.insert(mData.end(), (char const*)ptr, ((char const*)ptr) + len); return ret; } @@ -105,7 +105,7 @@ Serializer::addRaw(void const* ptr, int len) int Serializer::addFieldID(int type, int name) { - int ret = mData.size(); + int const ret = mData.size(); XRPL_ASSERT( (type > 0) && (type < 256) && (name > 0) && (name < 256), "xrpl::Serializer::addFieldID : inputs inside range"); @@ -143,7 +143,7 @@ Serializer::addFieldID(int type, int name) int Serializer::add8(unsigned char byte) { - int ret = mData.size(); + int const ret = mData.size(); mData.push_back(byte); return ret; } @@ -177,7 +177,7 @@ Serializer::getSHA512Half() const int Serializer::addVL(Blob const& vector) { - int ret = addEncoded(vector.size()); + int const ret = addEncoded(vector.size()); addRaw(vector); XRPL_ASSERT( mData.size() == (ret + vector.size() + encodeLengthLength(vector.size())), @@ -188,7 +188,7 @@ Serializer::addVL(Blob const& vector) int Serializer::addVL(Slice const& slice) { - int ret = addEncoded(slice.size()); + int const ret = addEncoded(slice.size()); if (!slice.empty()) addRaw(slice.data(), slice.size()); return ret; @@ -197,7 +197,7 @@ Serializer::addVL(Slice const& slice) int Serializer::addVL(void const* ptr, int len) { - int ret = addEncoded(len); + int const ret = addEncoded(len); if (len != 0) addRaw(ptr, len); @@ -343,7 +343,7 @@ SerialIter::get8() { if (remain_ < 1) Throw("invalid SerialIter get8"); - unsigned char t = *p_; + unsigned char const t = *p_; ++p_; ++used_; --remain_; @@ -469,23 +469,23 @@ SerialIter::getRaw(int size) int SerialIter::getVLDataLength() { - int b1 = get8(); + int const b1 = get8(); int datLen = 0; - int lenLen = Serializer::decodeLengthLength(b1); + int const lenLen = Serializer::decodeLengthLength(b1); if (lenLen == 1) { datLen = Serializer::decodeVLLength(b1); } else if (lenLen == 2) { - int b2 = get8(); + int const b2 = get8(); datLen = Serializer::decodeVLLength(b1, b2); } else { XRPL_ASSERT(lenLen == 3, "xrpl::SerialIter::getVLDataLength : lenLen is 3"); - int b2 = get8(); - int b3 = get8(); + int const b2 = get8(); + int const b3 = get8(); datLen = Serializer::decodeVLLength(b1, b2, b3); } return datLen; @@ -496,7 +496,7 @@ SerialIter::getSlice(std::size_t bytes) { if (bytes > remain_) Throw("invalid SerialIter getSlice"); - Slice s(p_, bytes); + Slice const s(p_, bytes); p_ += bytes; used_ += bytes; remain_ -= bytes; diff --git a/src/libxrpl/protocol/TxMeta.cpp b/src/libxrpl/protocol/TxMeta.cpp index 19a2755a29..3c797a7c8c 100644 --- a/src/libxrpl/protocol/TxMeta.cpp +++ b/src/libxrpl/protocol/TxMeta.cpp @@ -39,7 +39,7 @@ TxMeta::TxMeta(uint256 const& txid, std::uint32_t ledger, Blob const& vec) { SerialIter sit(makeSlice(vec)); - STObject obj(sit, sfMetadata); + STObject const obj(sit, sfMetadata); result_ = obj.getFieldU8(sfTransactionResult); index_ = obj.getFieldU32(sfTransactionIndex); nodes_ = obj.getFieldArray(sfAffectedNodes); @@ -89,7 +89,7 @@ TxMeta::getAffectedAccounts() const // Meta#getAffectedAccounts for (auto const& node : nodes_) { - int index = + int const index = node.getFieldIndex((node.getFName() == sfCreatedNode) ? sfNewFields : sfFinalFields); if (index != -1) @@ -146,7 +146,7 @@ TxMeta::getAffectedAccounts() const STObject& TxMeta::getAffectedNode(SLE::ref node, SField const& type) { - uint256 index = node->key(); + uint256 const index = node->key(); for (auto& n : nodes_) { if (n.getFieldH256(sfLedgerIndex) == index) diff --git a/src/libxrpl/protocol/XChainAttestations.cpp b/src/libxrpl/protocol/XChainAttestations.cpp index 314bf9f6d3..c255f743e3 100644 --- a/src/libxrpl/protocol/XChainAttestations.cpp +++ b/src/libxrpl/protocol/XChainAttestations.cpp @@ -74,7 +74,7 @@ AttestationBase::sameEventHelper(AttestationBase const& lhs, AttestationBase con bool AttestationBase::verify(STXChainBridge const& bridge) const { - std::vector msg = message(bridge); + std::vector const msg = message(bridge); return xrpl::verify(publicKey, makeSlice(msg), signature); } diff --git a/src/libxrpl/protocol/tokens.cpp b/src/libxrpl/protocol/tokens.cpp index bca8919c4e..e2a77fbf10 100644 --- a/src/libxrpl/protocol/tokens.cpp +++ b/src/libxrpl/protocol/tokens.cpp @@ -445,7 +445,7 @@ b256_to_b58_be(std::span input, std::span out) std::array const b58_be = xrpl::b58_fast::detail::b58_10_to_b58_be(base_58_10_coeff[i]); std::size_t to_skip = 0; - std::span b58_be_s{b58_be.data(), b58_be.size()}; + std::span const b58_be_s{b58_be.data(), b58_be.size()}; if (skip_zeros) { to_skip = count_leading_zeros(b58_be_s); @@ -507,7 +507,7 @@ b58_to_b256_be(std::string_view input, std::span out) XRPL_ASSERT( num_b_58_10_coeffs <= b_58_10_coeff.size(), "xrpl::b58_fast::detail::b58_to_b256_be : maximum coeff"); - for (unsigned char c : input.substr(0, partial_coeff_len)) + for (unsigned char const c : input.substr(0, partial_coeff_len)) { auto cur_val = ::xrpl::alphabetReverse[c]; if (cur_val < 0) @@ -521,7 +521,7 @@ b58_to_b256_be(std::string_view input, std::span out) { for (int j = 0; j < num_full_coeffs; ++j) { - unsigned char c = input[partial_coeff_len + (j * 10) + i]; + unsigned char const c = input[partial_coeff_len + (j * 10) + i]; auto cur_val = ::xrpl::alphabetReverse[c]; if (cur_val < 0) { @@ -626,7 +626,7 @@ encodeBase58Token( size_t const checksum_i = input.size() + 1; // buf[checksum_i..checksum_i + 4] = checksum checksum(buf.data() + checksum_i, buf.data(), checksum_i); - std::span b58Span(buf.data(), input.size() + 5); + std::span const b58Span(buf.data(), input.size() + 5); return detail::b256_to_b58_be(b58Span, out); } // Convert from base 58 to base 256, largest coefficients first @@ -680,8 +680,8 @@ encodeBase58Token(TokenType type, void const* token, std::size_t size) // over-allocation, this function uses 128 (again, over-allocation assuming // 2 base 58 char per byte) sr.resize(128); - std::span outSp(reinterpret_cast(sr.data()), sr.size()); - std::span inSp(reinterpret_cast(token), size); + std::span const outSp(reinterpret_cast(sr.data()), sr.size()); + std::span const inSp(reinterpret_cast(token), size); auto r = b58_fast::encodeBase58Token(type, inSp, outSp); if (!r) return {}; @@ -696,7 +696,7 @@ decodeBase58Token(std::string const& s, TokenType type) // The largest object encoded as base58 is 33 bytes; 64 is plenty (and // there's no benefit making it smaller) sr.resize(64); - std::span outSp(reinterpret_cast(sr.data()), sr.size()); + std::span const outSp(reinterpret_cast(sr.data()), sr.size()); auto r = b58_fast::decodeBase58Token(type, s, outSp); if (!r) return {}; diff --git a/src/libxrpl/rdb/DatabaseCon.cpp b/src/libxrpl/rdb/DatabaseCon.cpp index d064192a14..bca14f9bfa 100644 --- a/src/libxrpl/rdb/DatabaseCon.cpp +++ b/src/libxrpl/rdb/DatabaseCon.cpp @@ -25,7 +25,7 @@ public: std::shared_ptr fromId(std::uintptr_t id) { - std::lock_guard l{mutex_}; + std::lock_guard const l{mutex_}; auto it = checkpointers_.find(id); if (it != checkpointers_.end()) return it->second; @@ -35,7 +35,7 @@ public: void erase(std::uintptr_t id) { - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; checkpointers_.erase(id); } @@ -45,7 +45,7 @@ public: JobQueue& jobQueue, ServiceRegistry& registry) { - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; auto const id = nextId_++; auto const r = makeCheckpointer(id, session, jobQueue, registry); checkpointers_[id] = r; @@ -67,7 +67,7 @@ DatabaseCon::~DatabaseCon() { checkpointers.erase(checkpointer_->id()); - std::weak_ptr wk(checkpointer_); + std::weak_ptr const wk(checkpointer_); checkpointer_.reset(); // The references to our Checkpointer held by 'checkpointer_' and diff --git a/src/libxrpl/rdb/SociDB.cpp b/src/libxrpl/rdb/SociDB.cpp index ac96985407..780e05854f 100644 --- a/src/libxrpl/rdb/SociDB.cpp +++ b/src/libxrpl/rdb/SociDB.cpp @@ -93,7 +93,7 @@ open(soci::session& s, std::string const& beName, std::string const& connectionS static sqlite_api::sqlite3* getConnection(soci::session& s) { - sqlite_api::sqlite3* result = nullptr; + sqlite_api::sqlite3* result = nullptr; // NOLINT(misc-const-correctness) auto be = s.get_backend(); if (auto b = dynamic_cast(be)) result = b->conn_; @@ -222,7 +222,7 @@ public: schedule() override { { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); if (running_) return; running_ = true; @@ -242,7 +242,7 @@ public: self->checkpoint(); })) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); running_ = false; } } @@ -256,7 +256,8 @@ public: return; int log = 0, ckpt = 0; - int ret = sqlite3_wal_checkpoint_v2(conn, nullptr, SQLITE_CHECKPOINT_PASSIVE, &log, &ckpt); + int const ret = + sqlite3_wal_checkpoint_v2(conn, nullptr, SQLITE_CHECKPOINT_PASSIVE, &log, &ckpt); auto fname = sqlite3_db_filename(conn, "main"); if (ret != SQLITE_OK) @@ -269,7 +270,7 @@ public: JLOG(j_.trace()) << "WAL(" << fname << "): frames=" << log << ", written=" << ckpt; } - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); running_ = false; } diff --git a/src/libxrpl/resource/ResourceManager.cpp b/src/libxrpl/resource/ResourceManager.cpp index 1e7aadfa8d..d0e45d4c0e 100644 --- a/src/libxrpl/resource/ResourceManager.cpp +++ b/src/libxrpl/resource/ResourceManager.cpp @@ -50,7 +50,7 @@ public: ~ManagerImp() override { { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); stop_ = true; cond_.notify_one(); } diff --git a/src/libxrpl/server/InfoSub.cpp b/src/libxrpl/server/InfoSub.cpp index 5857e4d6ae..ea70dc3a83 100644 --- a/src/libxrpl/server/InfoSub.cpp +++ b/src/libxrpl/server/InfoSub.cpp @@ -65,7 +65,7 @@ InfoSub::onSendEmpty() void InfoSub::insertSubAccountInfo(AccountID const& account, bool rt) { - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); if (rt) { @@ -80,7 +80,7 @@ InfoSub::insertSubAccountInfo(AccountID const& account, bool rt) void InfoSub::deleteSubAccountInfo(AccountID const& account, bool rt) { - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); if (rt) { @@ -95,14 +95,14 @@ InfoSub::deleteSubAccountInfo(AccountID const& account, bool rt) bool InfoSub::insertSubAccountHistory(AccountID const& account) { - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); return accountHistorySubscriptions_.insert(account).second; } void InfoSub::deleteSubAccountHistory(AccountID const& account) { - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); accountHistorySubscriptions_.erase(account); } diff --git a/src/libxrpl/server/LoadFeeTrack.cpp b/src/libxrpl/server/LoadFeeTrack.cpp index e206b50863..d698e2420e 100644 --- a/src/libxrpl/server/LoadFeeTrack.cpp +++ b/src/libxrpl/server/LoadFeeTrack.cpp @@ -12,7 +12,7 @@ namespace xrpl { bool LoadFeeTrack::raiseLocalFee() { - std::lock_guard sl(lock_); + std::lock_guard const sl(lock_); if (++raiseCount_ < 2) return false; @@ -37,7 +37,7 @@ LoadFeeTrack::raiseLocalFee() bool LoadFeeTrack::lowerLocalFee() { - std::lock_guard sl(lock_); + std::lock_guard const sl(lock_); std::uint32_t const origFee = localTxnLoadFee_; raiseCount_ = 0; diff --git a/src/libxrpl/server/Manifest.cpp b/src/libxrpl/server/Manifest.cpp index 4526bf6c16..f4634982d0 100644 --- a/src/libxrpl/server/Manifest.cpp +++ b/src/libxrpl/server/Manifest.cpp @@ -279,7 +279,7 @@ loadValidatorToken(std::vector const& blob, beast::Journal journal) std::optional ManifestCache::getSigningKey(PublicKey const& pk) const { - std::shared_lock lock{mutex_}; + std::shared_lock const lock{mutex_}; auto const iter = map_.find(pk); if (iter != map_.end() && !iter->second.revoked()) @@ -291,7 +291,7 @@ ManifestCache::getSigningKey(PublicKey const& pk) const PublicKey ManifestCache::getMasterKey(PublicKey const& pk) const { - std::shared_lock lock{mutex_}; + std::shared_lock const lock{mutex_}; if (auto const iter = signingToMasterKeys_.find(pk); iter != signingToMasterKeys_.end()) return iter->second; @@ -302,7 +302,7 @@ ManifestCache::getMasterKey(PublicKey const& pk) const std::optional ManifestCache::getSequence(PublicKey const& pk) const { - std::shared_lock lock{mutex_}; + std::shared_lock const lock{mutex_}; auto const iter = map_.find(pk); if (iter != map_.end() && !iter->second.revoked()) @@ -314,7 +314,7 @@ ManifestCache::getSequence(PublicKey const& pk) const std::optional ManifestCache::getDomain(PublicKey const& pk) const { - std::shared_lock lock{mutex_}; + std::shared_lock const lock{mutex_}; auto const iter = map_.find(pk); if (iter != map_.end() && !iter->second.revoked()) @@ -326,7 +326,7 @@ ManifestCache::getDomain(PublicKey const& pk) const std::optional ManifestCache::getManifest(PublicKey const& pk) const { - std::shared_lock lock{mutex_}; + std::shared_lock const lock{mutex_}; auto const iter = map_.find(pk); if (iter != map_.end() && !iter->second.revoked()) @@ -338,7 +338,7 @@ ManifestCache::getManifest(PublicKey const& pk) const bool ManifestCache::revoked(PublicKey const& pk) const { - std::shared_lock lock{mutex_}; + std::shared_lock const lock{mutex_}; auto const iter = map_.find(pk); if (iter != map_.end()) @@ -437,12 +437,12 @@ ManifestCache::applyManifest(Manifest m) }; { - std::shared_lock sl{mutex_}; + std::shared_lock const sl{mutex_}; if (auto d = prewriteCheck(map_.find(m.masterKey), /*checkSig*/ true, sl)) return *d; } - std::unique_lock sl{mutex_}; + std::unique_lock const sl{mutex_}; auto const iter = map_.find(m.masterKey); // Since we released the previously held read lock, it's possible that the // collections have been written to. This means we need to run @@ -562,7 +562,7 @@ ManifestCache::save( std::string const& dbTable, std::function const& isTrusted) { - std::shared_lock lock{mutex_}; + std::shared_lock const lock{mutex_}; auto db = dbCon.checkoutDb(); saveManifests(*db, dbTable, isTrusted, map_, j_); diff --git a/src/libxrpl/server/Vacuum.cpp b/src/libxrpl/server/Vacuum.cpp index 89764b777a..bcf5941e95 100644 --- a/src/libxrpl/server/Vacuum.cpp +++ b/src/libxrpl/server/Vacuum.cpp @@ -9,7 +9,7 @@ namespace xrpl { bool doVacuumDB(DatabaseCon::Setup const& setup, beast::Journal j) { - boost::filesystem::path dbPath = setup.dataDir / TxDBName; + boost::filesystem::path const dbPath = setup.dataDir / TxDBName; uintmax_t const dbSize = file_size(dbPath); XRPL_ASSERT(dbSize != static_cast(-1), "ripple:doVacuumDB : file_size succeeded"); diff --git a/src/libxrpl/server/Wallet.cpp b/src/libxrpl/server/Wallet.cpp index 95c2e89a20..8da934a921 100644 --- a/src/libxrpl/server/Wallet.cpp +++ b/src/libxrpl/server/Wallet.cpp @@ -199,13 +199,13 @@ bool createFeatureVotes(soci::session& session) { soci::transaction tr(session); - std::string sql = + std::string const sql = "SELECT count(*) FROM sqlite_master " "WHERE type='table' AND name='FeatureVotes'"; // SOCI requires boost::optional (not std::optional) as the parameter. boost::optional featureVotesCount; session << sql, soci::into(featureVotesCount); - bool exists = static_cast(*featureVotesCount); + bool const exists = static_cast(*featureVotesCount); // Create FeatureVotes table in WalletDB if it doesn't exist if (!exists) @@ -232,8 +232,8 @@ readAmendments( return safe_cast(dbVote.value_or(1)); }; - soci::transaction tr(session); - std::string sql = + soci::transaction const tr(session); + std::string const sql = "SELECT AmendmentHash, AmendmentName, Veto FROM " "( SELECT AmendmentHash, AmendmentName, Veto, RANK() OVER " "( PARTITION BY AmendmentHash ORDER BY ROWID DESC ) " diff --git a/src/libxrpl/shamap/SHAMap.cpp b/src/libxrpl/shamap/SHAMap.cpp index 8a853e4d1b..505d20651e 100644 --- a/src/libxrpl/shamap/SHAMap.cpp +++ b/src/libxrpl/shamap/SHAMap.cpp @@ -85,11 +85,11 @@ SHAMap::dirtyUp( while (!stack.empty()) { auto node = intr_ptr::dynamic_pointer_cast(stack.top().first); - SHAMapNodeID nodeID = stack.top().second; + SHAMapNodeID const nodeID = stack.top().second; stack.pop(); XRPL_ASSERT(node, "xrpl::SHAMap::dirtyUp : non-null node"); - int branch = selectBranch(nodeID, target); + int const branch = selectBranch(nodeID, target); XRPL_ASSERT(branch >= 0, "xrpl::SHAMap::dirtyUp : valid branch"); node = unshareNode(std::move(node), nodeID); @@ -129,7 +129,7 @@ SHAMap::walkTowardsKey(uint256 const& id, SharedPtrNodeStack* stack) const SHAMapLeafNode* SHAMap::findKey(uint256 const& id) const { - SHAMapLeafNode* leaf = walkTowardsKey(id); + SHAMapLeafNode* leaf = walkTowardsKey(id); // NOLINT(misc-const-correctness) if ((leaf != nullptr) && leaf->peekItem()->key() != id) leaf = nullptr; return leaf; @@ -253,7 +253,7 @@ SHAMap::fetchNode(SHAMapHash const& hash) const SHAMapTreeNode* SHAMap::descendThrow(SHAMapInnerNode* parent, int branch) const { - SHAMapTreeNode* ret = descend(parent, branch); + SHAMapTreeNode* ret = descend(parent, branch); // NOLINT(misc-const-correctness) if ((ret == nullptr) && !parent->isEmptyBranch(branch)) Throw(type_, parent->getChildHash(branch)); @@ -275,7 +275,7 @@ SHAMap::descendThrow(SHAMapInnerNode& parent, int branch) const SHAMapTreeNode* SHAMap::descend(SHAMapInnerNode* parent, int branch) const { - SHAMapTreeNode* ret = parent->getChildPointer(branch); + SHAMapTreeNode* ret = parent->getChildPointer(branch); // NOLINT(misc-const-correctness) if ((ret != nullptr) || !backed_) return ret; @@ -326,7 +326,7 @@ SHAMap::descend( XRPL_ASSERT( !parent->isEmptyBranch(branch), "xrpl::SHAMap::descend : parent branch is non-empty"); - SHAMapTreeNode* child = parent->getChildPointer(branch); + SHAMapTreeNode* child = parent->getChildPointer(branch); // NOLINT(misc-const-correctness) if (child == nullptr) { @@ -353,7 +353,7 @@ SHAMap::descendAsync( { pending = false; - SHAMapTreeNode* ret = parent->getChildPointer(branch); + SHAMapTreeNode* ret = parent->getChildPointer(branch); // NOLINT(misc-const-correctness) if (ret != nullptr) return ret; @@ -513,7 +513,7 @@ SHAMapLeafNode const* SHAMap::peekFirstItem(SharedPtrNodeStack& stack) const { XRPL_ASSERT(stack.empty(), "xrpl::SHAMap::peekFirstItem : empty stack input"); - SHAMapLeafNode* node = firstBelow(root_, stack); + SHAMapLeafNode const* node = firstBelow(root_, stack); if (node == nullptr) { while (!stack.empty()) @@ -555,7 +555,7 @@ SHAMap::peekNextItem(uint256 const& id, SharedPtrNodeStack& stack) const boost::intrusive_ptr const& SHAMap::peekItem(uint256 const& id) const { - SHAMapLeafNode* leaf = findKey(id); + SHAMapLeafNode const* leaf = findKey(id); if (leaf == nullptr) return no_item; @@ -566,7 +566,7 @@ SHAMap::peekItem(uint256 const& id) const boost::intrusive_ptr const& SHAMap::peekItem(uint256 const& id, SHAMapHash& hash) const { - SHAMapLeafNode* leaf = findKey(id); + SHAMapLeafNode const* leaf = findKey(id); if (leaf == nullptr) return no_item; @@ -667,7 +667,7 @@ SHAMap::delItem(uint256 const& id) if (!leaf || (leaf->peekItem()->key() != id)) return false; - SHAMapNodeType type = leaf->getType(); + SHAMapNodeType const type = leaf->getType(); using TreeNodeType = intr_ptr::SharedPtr; @@ -677,7 +677,7 @@ SHAMap::delItem(uint256 const& id) while (!stack.empty()) { auto node = intr_ptr::static_pointer_cast(stack.top().first); - SHAMapNodeID nodeID = stack.top().second; + SHAMapNodeID const nodeID = stack.top().second; stack.pop(); node = unshareNode(std::move(node), nodeID); @@ -741,7 +741,7 @@ SHAMap::addGiveItem(SHAMapNodeType type, boost::intrusive_ptr XRPL_ASSERT(type != SHAMapNodeType::tnINNER, "xrpl::SHAMap::addGiveItem : valid type input"); // add the specified item, does not update - uint256 tag = item->key(); + uint256 const tag = item->key(); SharedPtrNodeStack stack; walkTowardsKey(tag, &stack); @@ -763,7 +763,7 @@ SHAMap::addGiveItem(SHAMapNodeType type, boost::intrusive_ptr { // easy case, we end on an inner node auto inner = intr_ptr::static_pointer_cast(node); - int branch = selectBranch(nodeID, tag); + int const branch = selectBranch(nodeID, tag); XRPL_ASSERT( inner->isEmptyBranch(branch), "xrpl::SHAMap::addGiveItem : inner branch is empty"); inner->setChild(branch, makeTypedLeaf(type, std::move(item), cowid_)); @@ -825,7 +825,7 @@ bool SHAMap::updateGiveItem(SHAMapNodeType type, boost::intrusive_ptr item) { // can't change the tag but can change the hash - uint256 tag = item->key(); + uint256 const tag = item->key(); XRPL_ASSERT(state_ != SHAMapState::Immutable, "xrpl::SHAMap::updateGiveItem : not immutable"); @@ -1007,7 +1007,7 @@ SHAMap::walkSubTree(bool doWrite, NodeObjectType t) { // No need to do I/O. If the node isn't linked, // it can't need to be flushed - int branch = pos; + int const branch = pos; auto child = node->getChild(pos++); if (child && (child->cowid() != 0)) diff --git a/src/libxrpl/shamap/SHAMapDelta.cpp b/src/libxrpl/shamap/SHAMapDelta.cpp index 0b5a09d4a7..ded57760f1 100644 --- a/src/libxrpl/shamap/SHAMapDelta.cpp +++ b/src/libxrpl/shamap/SHAMapDelta.cpp @@ -241,14 +241,14 @@ SHAMap::walkMap(std::vector& missingNodes, int maxMissing) co while (!nodeStack.empty()) { - intr_ptr::SharedPtr node = std::move(nodeStack.top()); + intr_ptr::SharedPtr const node = std::move(nodeStack.top()); nodeStack.pop(); for (int i = 0; i < 16; ++i) { if (!node->isEmptyBranch(i)) { - intr_ptr::SharedPtr nextNode = descendNoStore(*node, i); + intr_ptr::SharedPtr const nextNode = descendNoStore(*node, i); if (nextNode) { @@ -310,7 +310,8 @@ SHAMap::walkMapParallel(std::vector& missingNodes, int maxMis { while (!nodeStack.empty()) { - intr_ptr::SharedPtr node = std::move(nodeStack.top()); + intr_ptr::SharedPtr const node = + std::move(nodeStack.top()); XRPL_ASSERT(node, "xrpl::SHAMap::walkMapParallel : non-null node"); nodeStack.pop(); @@ -318,7 +319,7 @@ SHAMap::walkMapParallel(std::vector& missingNodes, int maxMis { if (node->isEmptyBranch(i)) continue; - intr_ptr::SharedPtr nextNode = + intr_ptr::SharedPtr const nextNode = descendNoStore(*node, i); if (nextNode) @@ -332,7 +333,7 @@ SHAMap::walkMapParallel(std::vector& missingNodes, int maxMis } else { - std::lock_guard l{m}; + std::lock_guard const l{m}; missingNodes.emplace_back(type_, node->getChildHash(i)); if (--maxMissing <= 0) return; @@ -342,7 +343,7 @@ SHAMap::walkMapParallel(std::vector& missingNodes, int maxMis } catch (SHAMapMissingNode const& e) { - std::lock_guard l(m); + std::lock_guard const l(m); exceptions.push_back(e); } }, @@ -352,7 +353,7 @@ SHAMap::walkMapParallel(std::vector& missingNodes, int maxMis for (std::thread& worker : workers) worker.join(); - std::lock_guard l(m); + std::lock_guard const l(m); if (exceptions.empty()) return true; std::stringstream ss; diff --git a/src/libxrpl/shamap/SHAMapInnerNode.cpp b/src/libxrpl/shamap/SHAMapInnerNode.cpp index 599d343745..91249d139e 100644 --- a/src/libxrpl/shamap/SHAMapInnerNode.cpp +++ b/src/libxrpl/shamap/SHAMapInnerNode.cpp @@ -82,7 +82,7 @@ SHAMapInnerNode::clone(std::uint32_t cowid) const } spinlock sl(lock_); - std::lock_guard lock(sl); + std::lock_guard const lock(sl); if (thisIsSparse) { @@ -313,7 +313,7 @@ SHAMapInnerNode::getChildPointer(int branch) auto const index = *getChildIndex(branch); packed_spinlock sl(lock_, index); - std::lock_guard lock(sl); + std::lock_guard const lock(sl); return hashesAndChildren_.getChildren()[index].get(); } @@ -328,7 +328,7 @@ SHAMapInnerNode::getChild(int branch) auto const index = *getChildIndex(branch); packed_spinlock sl(lock_, index); - std::lock_guard lock(sl); + std::lock_guard const lock(sl); return hashesAndChildren_.getChildren()[index]; } @@ -361,7 +361,7 @@ SHAMapInnerNode::canonicalizeChild(int branch, intr_ptr::SharedPtr(data) + 32); + unsigned int const depth = *(static_cast(data) + 32); if (depth <= SHAMap::leafDepth) { auto const id = uint256::fromVoid(data); diff --git a/src/libxrpl/shamap/SHAMapSync.cpp b/src/libxrpl/shamap/SHAMapSync.cpp index 14ccdca2eb..2074b43cb4 100644 --- a/src/libxrpl/shamap/SHAMapSync.cpp +++ b/src/libxrpl/shamap/SHAMapSync.cpp @@ -41,7 +41,7 @@ SHAMap::visitNodes(std::function const& function) const { if (!node->isEmptyBranch(pos)) { - intr_ptr::SharedPtr child = descendNoStore(*node, pos); + intr_ptr::SharedPtr const child = descendNoStore(*node, pos); if (!function(*child)) return; @@ -124,7 +124,7 @@ SHAMap::visitDifferences( if (!node->isEmptyBranch(i)) { auto const& childHash = node->getChildHash(i); - SHAMapNodeID childID = nodeID.getChildNodeID(i); + SHAMapNodeID const childID = nodeID.getChildNodeID(i); auto next = descendThrow(node, i); if (next->isInner()) @@ -160,7 +160,7 @@ SHAMap::gmn_ProcessNodes(MissingNodes& mn, MissingNodes::StackEntry& se) while (currentChild < 16) { - int branch = (firstChild + currentChild++) % 16; + int const branch = (firstChild + currentChild++) % 16; if (node->isEmptyBranch(branch)) continue; @@ -182,7 +182,7 @@ SHAMap::gmn_ProcessNodes(MissingNodes& mn, MissingNodes::StackEntry& se) [node, nodeID, branch, &mn]( intr_ptr::SharedPtr found, SHAMapHash const&) { // a read completed asynchronously - std::unique_lock lock{mn.deferLock_}; + std::unique_lock const lock{mn.deferLock_}; mn.finishedReads_.emplace_back(node, nodeID, branch, std::move(found)); mn.deferCondVar_.notify_one(); }); @@ -327,7 +327,7 @@ SHAMap::getMissingNodes(int max, SHAMapSyncFilter* filter) if ((node == nullptr) && !mn.stack_.empty()) { // Pick up where we left off with this node's parent - bool was = fullBelow; // was full below + bool const was = fullBelow; // was full below pos = mn.stack_.top(); mn.stack_.pop(); @@ -404,7 +404,7 @@ SHAMap::getNodeFat( while ((node != nullptr) && node->isInner() && (nodeID.getDepth() < wanted.getDepth())) { - int branch = selectBranch(nodeID, wanted.getNodeID()); + int const branch = selectBranch(nodeID, wanted.getNodeID()); auto inner = safe_downcast(node); if (inner->isEmptyBranch(branch)) return false; @@ -445,7 +445,7 @@ SHAMap::getNodeFat( // We descend inner nodes with only a single child // without decrementing the depth auto inner = safe_downcast(node); - int bc = inner->getBranchCount(); + int const bc = inner->getBranchCount(); if ((depth > 0) || (bc == 1)) { @@ -709,7 +709,7 @@ SHAMap::hasInnerNode(SHAMapNodeID const& targetNodeID, SHAMapHash const& targetN while (node->isInner() && (nodeID.getDepth() < targetNodeID.getDepth())) { - int branch = selectBranch(nodeID, targetNodeID.getNodeID()); + int const branch = selectBranch(nodeID, targetNodeID.getNodeID()); auto inner = safe_downcast(node); if (inner->isEmptyBranch(branch)) return false; @@ -734,7 +734,7 @@ SHAMap::hasLeafNode(uint256 const& tag, SHAMapHash const& targetNodeHash) const do { - int branch = selectBranch(nodeID, tag); + int const branch = selectBranch(nodeID, tag); auto inner = safe_downcast(node); if (inner->isEmptyBranch(branch)) return false; // Dead end, node must not be here diff --git a/src/libxrpl/tx/ApplyContext.cpp b/src/libxrpl/tx/ApplyContext.cpp index edca31c04a..d503643662 100644 --- a/src/libxrpl/tx/ApplyContext.cpp +++ b/src/libxrpl/tx/ApplyContext.cpp @@ -98,7 +98,7 @@ 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 finalizers{ + std::array const finalizers{ {std::get(checkers).finalize(tx, result, fee, *view_, journal)...}}; // call each check's finalizer to see that it passes diff --git a/src/libxrpl/tx/Transactor.cpp b/src/libxrpl/tx/Transactor.cpp index 9560c4e752..7d2ac06fc1 100644 --- a/src/libxrpl/tx/Transactor.cpp +++ b/src/libxrpl/tx/Transactor.cpp @@ -34,7 +34,7 @@ preflight0(PreflightContext const& ctx, std::uint32_t flagMask) if (!isPseudoTx(ctx.tx) || ctx.tx.isFieldPresent(sfNetworkID)) { - uint32_t nodeNID = ctx.registry.get().getNetworkIDService().getNetworkID(); + uint32_t const nodeNID = ctx.registry.get().getNetworkIDService().getNetworkID(); std::optional txNID = ctx.tx[~sfNetworkID]; if (nodeNID <= 1024) @@ -777,7 +777,7 @@ Transactor::checkMultiSign( beast::Journal const j) { // Get id's SignerList and Quorum. - std::shared_ptr sleAccountSigners = view.read(keylet::signers(id)); + std::shared_ptr const sleAccountSigners = view.read(keylet::signers(id)); // If the signer list doesn't exist the account is not multi-signing. if (!sleAccountSigners) { @@ -1073,15 +1073,15 @@ Transactor::operator()() // // raii classes for the current ledger rules. // fixUniversalNumber predate the rulesGuard and should be replaced. - NumberSO stNumberSO{view().rules().enabled(fixUniversalNumber)}; - CurrentTransactionRulesGuard currentTransactionRulesGuard(view().rules()); + NumberSO const stNumberSO{view().rules().enabled(fixUniversalNumber)}; + CurrentTransactionRulesGuard const currentTransactionRulesGuard(view().rules()); #ifdef DEBUG { Serializer ser; ctx_.tx.add(ser); SerialIter sit(ser.slice()); - STTx s2(sit); + STTx const s2(sit); if (!s2.isEquivalent(ctx_.tx)) { diff --git a/src/libxrpl/tx/apply.cpp b/src/libxrpl/tx/apply.cpp index caf716eda6..c8016002c2 100644 --- a/src/libxrpl/tx/apply.cpp +++ b/src/libxrpl/tx/apply.cpp @@ -116,7 +116,7 @@ template ApplyResult apply(ServiceRegistry& registry, OpenView& view, PreflightChecks&& preflightChecks) { - NumberSO stNumberSO{view.rules().enabled(fixUniversalNumber)}; + NumberSO const stNumberSO{view.rules().enabled(fixUniversalNumber)}; return doApply(preclaim(preflightChecks(), registry, view), registry, view); } diff --git a/src/libxrpl/tx/invariants/FreezeInvariant.cpp b/src/libxrpl/tx/invariants/FreezeInvariant.cpp index c8723b9bbf..0048da7a84 100644 --- a/src/libxrpl/tx/invariants/FreezeInvariant.cpp +++ b/src/libxrpl/tx/invariants/FreezeInvariant.cpp @@ -127,7 +127,7 @@ TransfersNotFrozen::calculateBalanceChange( bool isDelete) { auto const getBalance = [](auto const& line, auto const& other, bool zero) { - STAmount amt = line ? line->at(sfBalance) : other->at(sfBalance).zeroed(); + STAmount const amt = line ? line->at(sfBalance) : other->at(sfBalance).zeroed(); return zero ? amt.zeroed() : amt; }; diff --git a/src/libxrpl/tx/invariants/MPTInvariant.cpp b/src/libxrpl/tx/invariants/MPTInvariant.cpp index a3a5bf897d..7b76e70c86 100644 --- a/src/libxrpl/tx/invariants/MPTInvariant.cpp +++ b/src/libxrpl/tx/invariants/MPTInvariant.cpp @@ -56,7 +56,7 @@ ValidMPTIssuance::finalize( { auto const& rules = view.rules(); [[maybe_unused]] - bool enforceCreatedByIssuer = + bool const enforceCreatedByIssuer = rules.enabled(featureSingleAssetVault) || rules.enabled(featureLendingProtocol); if (mptCreatedByIssuer_) { diff --git a/src/libxrpl/tx/paths/BookStep.cpp b/src/libxrpl/tx/paths/BookStep.cpp index 3e492d8a19..ddba0c1ae9 100644 --- a/src/libxrpl/tx/paths/BookStep.cpp +++ b/src/libxrpl/tx/paths/BookStep.cpp @@ -1009,7 +1009,7 @@ BookStep::revImp( return DebtDirection::issues; }(); auto const r = forEachOffer(sb, afView, prevStepDebtDir, eachOffer); - boost::container::flat_set toRm = std::move(std::get<0>(r)); + boost::container::flat_set const toRm = std::move(std::get<0>(r)); std::uint32_t const offersConsumed = std::get<1>(r); offersUsed_ = offersConsumed; SetUnion(ofrsToRm, toRm); @@ -1171,7 +1171,7 @@ BookStep::fwdImp( return DebtDirection::issues; }(); auto const r = forEachOffer(sb, afView, prevStepDebtDir, eachOffer); - boost::container::flat_set toRm = std::move(std::get<0>(r)); + boost::container::flat_set const toRm = std::move(std::get<0>(r)); std::uint32_t const offersConsumed = std::get<1>(r); offersUsed_ = offersConsumed; SetUnion(ofrsToRm, toRm); diff --git a/src/libxrpl/tx/paths/OfferStream.cpp b/src/libxrpl/tx/paths/OfferStream.cpp index b7dc431b23..acb2df1429 100644 --- a/src/libxrpl/tx/paths/OfferStream.cpp +++ b/src/libxrpl/tx/paths/OfferStream.cpp @@ -203,7 +203,7 @@ TOfferStreamBase::step() if (!tip_.step(j_)) return false; - std::shared_ptr entry = tip_.entry(); + std::shared_ptr const entry = tip_.entry(); // If we exceed the maximum number of allowed steps, we're done. if (!counter_.step()) diff --git a/src/libxrpl/tx/transactors/account/AccountSet.cpp b/src/libxrpl/tx/transactors/account/AccountSet.cpp index d99324f802..af3edb5768 100644 --- a/src/libxrpl/tx/transactors/account/AccountSet.cpp +++ b/src/libxrpl/tx/transactors/account/AccountSet.cpp @@ -63,8 +63,9 @@ AccountSet::preflight(PreflightContext const& ctx) // // RequireAuth // - bool bSetRequireAuth = ((uTxFlags & tfRequireAuth) != 0u) || (uSetFlag == asfRequireAuth); - bool bClearRequireAuth = ((uTxFlags & tfOptionalAuth) != 0u) || (uClearFlag == asfRequireAuth); + bool const bSetRequireAuth = ((uTxFlags & tfRequireAuth) != 0u) || (uSetFlag == asfRequireAuth); + bool const bClearRequireAuth = + ((uTxFlags & tfOptionalAuth) != 0u) || (uClearFlag == asfRequireAuth); if (bSetRequireAuth && bClearRequireAuth) { @@ -75,8 +76,9 @@ AccountSet::preflight(PreflightContext const& ctx) // // RequireDestTag // - bool bSetRequireDest = ((uTxFlags & tfRequireDestTag) != 0u) || (uSetFlag == asfRequireDest); - bool bClearRequireDest = + bool const bSetRequireDest = + ((uTxFlags & tfRequireDestTag) != 0u) || (uSetFlag == asfRequireDest); + bool const bClearRequireDest = ((uTxFlags & tfOptionalDestTag) != 0u) || (uClearFlag == asfRequireDest); if (bSetRequireDest && bClearRequireDest) @@ -88,8 +90,9 @@ AccountSet::preflight(PreflightContext const& ctx) // // DisallowXRP // - bool bSetDisallowXRP = ((uTxFlags & tfDisallowXRP) != 0u) || (uSetFlag == asfDisallowXRP); - bool bClearDisallowXRP = ((uTxFlags & tfAllowXRP) != 0u) || (uClearFlag == asfDisallowXRP); + bool const bSetDisallowXRP = ((uTxFlags & tfDisallowXRP) != 0u) || (uSetFlag == asfDisallowXRP); + bool const bClearDisallowXRP = + ((uTxFlags & tfAllowXRP) != 0u) || (uClearFlag == asfDisallowXRP); if (bSetDisallowXRP && bClearDisallowXRP) { @@ -100,7 +103,7 @@ AccountSet::preflight(PreflightContext const& ctx) // TransferRate if (tx.isFieldPresent(sfTransferRate)) { - std::uint32_t uRate = tx.getFieldU32(sfTransferRate); + std::uint32_t const uRate = tx.getFieldU32(sfTransferRate); if ((uRate != 0u) && (uRate < QUALITY_ONE)) { @@ -217,7 +220,7 @@ AccountSet::preclaim(PreclaimContext const& ctx) std::uint32_t const uSetFlag = ctx.tx.getFieldU32(sfSetFlag); // legacy AccountSet flags - bool bSetRequireAuth = ((uTxFlags & tfRequireAuth) != 0u) || (uSetFlag == asfRequireAuth); + bool const bSetRequireAuth = ((uTxFlags & tfRequireAuth) != 0u) || (uSetFlag == asfRequireAuth); // // RequireAuth @@ -531,7 +534,7 @@ AccountSet::doApply() // if (tx.isFieldPresent(sfTransferRate)) { - std::uint32_t uRate = tx.getFieldU32(sfTransferRate); + std::uint32_t const uRate = tx.getFieldU32(sfTransferRate); if (uRate == 0 || uRate == QUALITY_ONE) { diff --git a/src/libxrpl/tx/transactors/account/SignerListSet.cpp b/src/libxrpl/tx/transactors/account/SignerListSet.cpp index 22fb98afd8..90ab8daf6f 100644 --- a/src/libxrpl/tx/transactors/account/SignerListSet.cpp +++ b/src/libxrpl/tx/transactors/account/SignerListSet.cpp @@ -167,7 +167,7 @@ removeSignersFromLedger( { // We have to examine the current SignerList so we know how much to // reduce the OwnerCount. - SLE::pointer signers = view.peek(signerListKeylet); + SLE::pointer const signers = view.peek(signerListKeylet); // If the signer list doesn't exist we've already succeeded in deleting it. if (!signers) @@ -299,7 +299,7 @@ SignerListSet::replaceSignerList() std::uint32_t const oldOwnerCount{(*sle)[sfOwnerCount]}; constexpr int addedOwnerCount = 1; - std::uint32_t flags{lsfOneOwnerCount}; + std::uint32_t const flags{lsfOneOwnerCount}; XRPAmount const newReserve{view().fees().accountReserve(oldOwnerCount + addedOwnerCount)}; @@ -339,7 +339,7 @@ SignerListSet::destroySignerList() auto const accountKeylet = keylet::account(account_); // Destroying the signer list is only allowed if either the master key // is enabled or there is a regular key. - SLE::pointer ledgerEntry = view().peek(accountKeylet); + SLE::pointer const ledgerEntry = view().peek(accountKeylet); if (!ledgerEntry) return tefINTERNAL; // LCOV_EXCL_LINE diff --git a/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp b/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp index f0e57919d9..9074122cdf 100644 --- a/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp +++ b/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp @@ -119,7 +119,7 @@ checkAttestationPublicKey( else { // regular key - if (std::optional regularKey = + if (std::optional const regularKey = (*sleAttestationSigningAccount)[~sfRegularKey]; regularKey != accountFromPK) { @@ -326,7 +326,8 @@ onClaim( std::unordered_map const& signersList, beast::Journal j) { - XChainClaimAttestation::MatchFields toMatch{sendingAmount, wasLockingChainSend, std::nullopt}; + XChainClaimAttestation::MatchFields const toMatch{ + sendingAmount, wasLockingChainSend, std::nullopt}; return claimHelper(attestations, view, toMatch, CheckDst::ignore, quorum, signersList, j); } @@ -638,7 +639,7 @@ finalizeClaimHelper( auto const round_mode = innerSb.rules().enabled(fixXChainRewardRounding) ? Number::rounding_mode::downward : Number::getround(); - saveNumberRoundMode _{Number::setround(round_mode)}; + saveNumberRoundMode const _{Number::setround(round_mode)}; STAmount const den{rewardAccounts.size()}; return divide(rewardPool, den, rewardPool.issue()); diff --git a/src/libxrpl/tx/transactors/check/CheckCash.cpp b/src/libxrpl/tx/transactors/check/CheckCash.cpp index 09b3177ce7..fa908c3aa3 100644 --- a/src/libxrpl/tx/transactors/check/CheckCash.cpp +++ b/src/libxrpl/tx/transactors/check/CheckCash.cpp @@ -365,7 +365,7 @@ CheckCash::doApply() STAmount const savedLimit = sleTrustLine->at(tweakedLimit); // Make sure the tweaked limits are restored when we leave scope. - scope_exit fixup([&psb, &trustLineKey, &tweakedLimit, &savedLimit]() { + scope_exit const fixup([&psb, &trustLineKey, &tweakedLimit, &savedLimit]() { if (auto const sleTrustLine = psb.peek(trustLineKey)) sleTrustLine->at(tweakedLimit) = savedLimit; }); diff --git a/src/libxrpl/tx/transactors/dex/AMMBid.cpp b/src/libxrpl/tx/transactors/dex/AMMBid.cpp index a1ace702dc..f5b9445ead 100644 --- a/src/libxrpl/tx/transactors/dex/AMMBid.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMBid.cpp @@ -54,7 +54,7 @@ AMMBid::preflight(PreflightContext const& ctx) } if (ctx.rules.enabled(fixAMMv1_3)) { - AccountID account = ctx.tx[sfAccount]; + AccountID const account = ctx.tx[sfAccount]; std::set unique; for (auto const& obj : authAccounts) { diff --git a/src/libxrpl/tx/transactors/dex/AMMCreate.cpp b/src/libxrpl/tx/transactors/dex/AMMCreate.cpp index 6dabf084bf..069fadf103 100644 --- a/src/libxrpl/tx/transactors/dex/AMMCreate.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMCreate.cpp @@ -246,7 +246,7 @@ applyCreate(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::J // Set AMM flag on AMM trustline if (!isXRP(amount)) { - SLE::pointer sleRippleState = sb.peek(keylet::line(accountId, amount.issue())); + SLE::pointer const sleRippleState = sb.peek(keylet::line(accountId, amount.issue())); if (!sleRippleState) { return tecINTERNAL; // LCOV_EXCL_LINE diff --git a/src/libxrpl/tx/transactors/dex/AMMHelpers.cpp b/src/libxrpl/tx/transactors/dex/AMMHelpers.cpp index 20ffab52ca..386608229b 100644 --- a/src/libxrpl/tx/transactors/dex/AMMHelpers.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMHelpers.cpp @@ -7,7 +7,7 @@ ammLPTokens(STAmount const& asset1, STAmount const& asset2, Issue const& lptIssu { // AMM invariant: sqrt(asset1 * asset2) >= LPTokensBalance auto const rounding = isFeatureEnabled(fixAMMv1_3) ? Number::downward : Number::getround(); - NumberRoundModeGuard g(rounding); + NumberRoundModeGuard const g(rounding); auto const tokens = root2(asset1 * asset2); return toSTAmount(lptIssue, tokens); } @@ -142,7 +142,7 @@ adjustLPTokens(STAmount const& lptAMMBalance, STAmount const& lpTokens, IsDeposi { // Force rounding downward to ensure adjusted tokens are less or equal // to requested tokens. - saveNumberRoundMode rm(Number::setround(Number::rounding_mode::downward)); + saveNumberRoundMode const rm(Number::setround(Number::rounding_mode::downward)); if (isDeposit == IsDeposit::Yes) return (lptAMMBalance + lpTokens) - lptAMMBalance; return (lpTokens - lptAMMBalance) + lptAMMBalance; @@ -251,7 +251,7 @@ solveQuadraticEqSmallest(Number const& a, Number const& b, Number const& c) STAmount multiply(STAmount const& amount, Number const& frac, Number::rounding_mode rm) { - NumberRoundModeGuard g(rm); + NumberRoundModeGuard const g(rm); auto const t = amount * frac; return toSTAmount(amount.issue(), t, rm); } @@ -270,7 +270,7 @@ getRoundedAsset( auto const rm = detail::getAssetRounding(isDeposit); if (isDeposit == IsDeposit::Yes) return multiply(balance, productCb(), rm); - NumberRoundModeGuard g(rm); + NumberRoundModeGuard const g(rm); return toSTAmount(balance.issue(), productCb(), rm); } @@ -304,7 +304,7 @@ getRoundedLPTokens( auto const rm = detail::getLPTokenRounding(isDeposit); if (isDeposit == IsDeposit::Yes) { - NumberRoundModeGuard g(rm); + NumberRoundModeGuard const g(rm); return toSTAmount(lptAMMBalance.issue(), productCb(), rm); } return multiply(lptAMMBalance, productCb(), rm); diff --git a/src/libxrpl/tx/transactors/dex/OfferCreate.cpp b/src/libxrpl/tx/transactors/dex/OfferCreate.cpp index 76c49aee57..20524f73ae 100644 --- a/src/libxrpl/tx/transactors/dex/OfferCreate.cpp +++ b/src/libxrpl/tx/transactors/dex/OfferCreate.cpp @@ -79,8 +79,8 @@ OfferCreate::preflight(PreflightContext const& ctx) return temBAD_SEQUENCE; } - STAmount saTakerPays = tx[sfTakerPays]; - STAmount saTakerGets = tx[sfTakerGets]; + STAmount const saTakerPays = tx[sfTakerPays]; + STAmount const saTakerGets = tx[sfTakerGets]; if (!isLegalNet(saTakerPays) || !isLegalNet(saTakerGets)) return temBAD_AMOUNT; @@ -737,7 +737,8 @@ OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) return {tefINTERNAL, false}; { - XRPAmount reserve = sb.fees().accountReserve(sleCreator->getFieldU32(sfOwnerCount) + 1); + XRPAmount const reserve = + sb.fees().accountReserve(sleCreator->getFieldU32(sfOwnerCount) + 1); if (preFeeBalance_ < reserve) { diff --git a/src/libxrpl/tx/transactors/escrow/EscrowCancel.cpp b/src/libxrpl/tx/transactors/escrow/EscrowCancel.cpp index 1250d950cd..e47f008357 100644 --- a/src/libxrpl/tx/transactors/escrow/EscrowCancel.cpp +++ b/src/libxrpl/tx/transactors/escrow/EscrowCancel.cpp @@ -33,7 +33,7 @@ escrowCancelPreclaimHelper( AccountID const& account, STAmount const& amount) { - AccountID issuer = amount.getIssuer(); + AccountID const issuer = amount.getIssuer(); // If the issuer is the same as the account, return tecINTERNAL if (issuer == account) return tecINTERNAL; // LCOV_EXCL_LINE @@ -52,7 +52,7 @@ escrowCancelPreclaimHelper( AccountID const& account, STAmount const& amount) { - AccountID issuer = amount.getIssuer(); + AccountID const issuer = amount.getIssuer(); // If the issuer is the same as the account, return tecINTERNAL if (issuer == account) return tecINTERNAL; // LCOV_EXCL_LINE diff --git a/src/libxrpl/tx/transactors/escrow/EscrowCreate.cpp b/src/libxrpl/tx/transactors/escrow/EscrowCreate.cpp index 634b9b3a06..ed0bbeea44 100644 --- a/src/libxrpl/tx/transactors/escrow/EscrowCreate.cpp +++ b/src/libxrpl/tx/transactors/escrow/EscrowCreate.cpp @@ -163,7 +163,7 @@ escrowCreatePreclaimHelper( AccountID const& dest, STAmount const& amount) { - AccountID issuer = amount.getIssuer(); + AccountID const issuer = amount.getIssuer(); // If the issuer is the same as the account, return tecNO_PERMISSION if (issuer == account) return tecNO_PERMISSION; @@ -233,7 +233,7 @@ escrowCreatePreclaimHelper( AccountID const& dest, STAmount const& amount) { - AccountID issuer = amount.getIssuer(); + AccountID const issuer = amount.getIssuer(); // If the issuer is the same as the account, return tecNO_PERMISSION if (issuer == account) return tecNO_PERMISSION; diff --git a/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp b/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp index f64229ff69..e05ba87bbb 100644 --- a/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp +++ b/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp @@ -127,7 +127,7 @@ escrowFinishPreclaimHelper( AccountID const& dest, STAmount const& amount) { - AccountID issuer = amount.getIssuer(); + AccountID const issuer = amount.getIssuer(); // If the issuer is the same as the account, return tesSUCCESS if (issuer == dest) return tesSUCCESS; @@ -150,7 +150,7 @@ escrowFinishPreclaimHelper( AccountID const& dest, STAmount const& amount) { - AccountID issuer = amount.getIssuer(); + AccountID const issuer = amount.getIssuer(); // If the issuer is the same as the dest, return tesSUCCESS if (issuer == dest) return tesSUCCESS; diff --git a/src/libxrpl/tx/transactors/lending/LendingHelpers.cpp b/src/libxrpl/tx/transactors/lending/LendingHelpers.cpp index ad4cd8440d..bad55e9222 100644 --- a/src/libxrpl/tx/transactors/lending/LendingHelpers.cpp +++ b/src/libxrpl/tx/transactors/lending/LendingHelpers.cpp @@ -1253,7 +1253,7 @@ checkLoanGuards( // loan can't be amortized in the specified number of payments, raise an // error { - NumberRoundModeGuard mg(Number::upward); + NumberRoundModeGuard const mg(Number::upward); if (std::int64_t const computedPayments{ properties.loanState.valueOutstanding / roundedPayment}; @@ -1486,7 +1486,7 @@ computeLoanProperties( auto const [totalValueOutstanding, loanScale] = [&]() { // only round up if there should be interest - NumberRoundModeGuard mg(periodicRate == 0 ? Number::to_nearest : Number::upward); + NumberRoundModeGuard const mg(periodicRate == 0 ? Number::to_nearest : Number::upward); // Use STAmount's internal rounding instead of roundToAsset, because // we're going to use this result to determine the scale for all the // other rounding. diff --git a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp index 24aa3f8bf2..627b16794b 100644 --- a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp @@ -137,11 +137,11 @@ determineClawAmount( { auto const maxClawAmount = [&]() { // Always round the minimum required up - NumberRoundModeGuard mg1(Number::upward); + NumberRoundModeGuard const mg1(Number::upward); auto const minRequiredCover = tenthBipsOfValue(sleBroker[sfDebtTotal], TenthBips32(sleBroker[sfCoverRateMinimum])); // The subtraction probably won't round, but round down if it does. - NumberRoundModeGuard mg2(Number::downward); + NumberRoundModeGuard const mg2(Number::downward); return sleBroker[sfCoverAvailable] - minRequiredCover; }(); if (maxClawAmount <= beast::zero) diff --git a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.cpp b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.cpp index 6946992376..d03edad0a2 100644 --- a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.cpp @@ -119,7 +119,7 @@ LoanBrokerCoverWithdraw::preclaim(PreclaimContext const& ctx) auto const minimumCover = [&]() { // Always round the minimum required up. // Applies to `tenthBipsOfValue` as well as `roundToAsset`. - NumberRoundModeGuard mg(Number::upward); + NumberRoundModeGuard const mg(Number::upward); return roundToAsset( vaultAsset, tenthBipsOfValue(currentDebtTotal, TenthBips32(sleBroker->at(sfCoverRateMinimum))), diff --git a/src/libxrpl/tx/transactors/lending/LoanManage.cpp b/src/libxrpl/tx/transactors/lending/LoanManage.cpp index 6cc9df1aab..adef5374b9 100644 --- a/src/libxrpl/tx/transactors/lending/LoanManage.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanManage.cpp @@ -144,7 +144,7 @@ LoanManage::defaultLoan( TenthBips32 const coverRateLiquidation{brokerSle->at(sfCoverRateLiquidation)}; auto const defaultCovered = [&]() { // Always round the minimum required up. - NumberRoundModeGuard mg(Number::upward); + NumberRoundModeGuard const mg(Number::upward); auto const minimumCover = tenthBipsOfValue(brokerDebtTotalProxy.value(), coverRateMinimum); // Round the liquidation amount up, too auto const covered = roundToAsset( diff --git a/src/libxrpl/tx/transactors/lending/LoanPay.cpp b/src/libxrpl/tx/transactors/lending/LoanPay.cpp index 8739cb645a..f748a670fd 100644 --- a/src/libxrpl/tx/transactors/lending/LoanPay.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanPay.cpp @@ -117,7 +117,7 @@ LoanPay::calculateBaseFee(ReadView const& view, STTx const& tx) // If making an overpayment, count it as a full payment because it will do // about the same amount of work, if not more. - NumberRoundModeGuard mg(tx.isFlag(tfLoanOverpayment) ? Number::upward : Number::downward); + NumberRoundModeGuard const mg(tx.isFlag(tfLoanOverpayment) ? Number::upward : Number::downward); // Estimate how many payments will be made Number const numPaymentEstimate = static_cast(amount / regularPayment); @@ -277,7 +277,7 @@ LoanPay::doApply() // Round the minimum required cover up to be conservative. This ensures // CoverAvailable never drops below the theoretical minimum, protecting // the broker's solvency. - NumberRoundModeGuard mg(Number::upward); + NumberRoundModeGuard const mg(Number::upward); return coverAvailableProxy >= roundToAsset( asset, tenthBipsOfValue(debtTotalProxy.value(), coverRateMinimum), loanScale) && diff --git a/src/libxrpl/tx/transactors/lending/LoanSet.cpp b/src/libxrpl/tx/transactors/lending/LoanSet.cpp index f046a24961..9cc4042365 100644 --- a/src/libxrpl/tx/transactors/lending/LoanSet.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanSet.cpp @@ -466,7 +466,7 @@ LoanSet::doApply() // Round the minimum required cover up to be conservative. This ensures // CoverAvailable never drops below the theoretical minimum, protecting // the broker's solvency. - NumberRoundModeGuard mg(Number::upward); + NumberRoundModeGuard const mg(Number::upward); if (brokerSle->at(sfCoverAvailable) < tenthBipsOfValue(newDebtTotal, coverRateMinimum)) { JLOG(j_.warn()) << "Insufficient first-loss capital to cover the loan."; diff --git a/src/libxrpl/tx/transactors/nft/NFTokenUtils.cpp b/src/libxrpl/tx/transactors/nft/NFTokenUtils.cpp index 6a8b830bf0..3368887d94 100644 --- a/src/libxrpl/tx/transactors/nft/NFTokenUtils.cpp +++ b/src/libxrpl/tx/transactors/nft/NFTokenUtils.cpp @@ -64,7 +64,7 @@ getPageForToken( // A suitable page doesn't exist; we'll have to create one. if (!cp) { - STArray arr; + STArray const arr; cp = std::make_shared(last); cp->setFieldArray(sfNFTokens, arr); view.insert(cp); @@ -245,7 +245,7 @@ insertToken(ApplyView& view, AccountID owner, STObject&& nft) // First, we need to locate the page the NFT belongs to, creating it // if necessary. This operation may fail if it is impossible to insert // the NFT. - std::shared_ptr page = + std::shared_ptr const page = getPageForToken(view, owner, nft[sfNFTokenID], [](ApplyView& view, AccountID const& owner) { adjustOwnerCount( view, @@ -338,7 +338,7 @@ mergePages(ApplyView& view, std::shared_ptr const& p1, std::shared_ptr TER removeToken(ApplyView& view, AccountID const& owner, uint256 const& nftokenID) { - std::shared_ptr page = locatePage(view, owner, nftokenID); + std::shared_ptr const page = locatePage(view, owner, nftokenID); // If the page couldn't be found, the given NFT isn't owned by this account if (!page) @@ -519,7 +519,7 @@ removeToken( std::optional findToken(ReadView const& view, AccountID const& owner, uint256 const& nftokenID) { - std::shared_ptr page = locatePage(view, owner, nftokenID); + std::shared_ptr const page = locatePage(view, owner, nftokenID); // If the page couldn't be found, the given NFT isn't owned by this account if (!page) @@ -612,7 +612,7 @@ notTooManyOffers(ReadView const& view, uint256 const& nftokenID) std::size_t totalOffers = 0; { - Dir buys(view, keylet::nft_buys(nftokenID)); + Dir const buys(view, keylet::nft_buys(nftokenID)); for (auto iter = buys.begin(); iter != buys.end(); iter.next_page()) { totalOffers += iter.page_size(); @@ -622,7 +622,7 @@ notTooManyOffers(ReadView const& view, uint256 const& nftokenID) } { - Dir sells(view, keylet::nft_sells(nftokenID)); + Dir const sells(view, keylet::nft_sells(nftokenID)); for (auto iter = sells.begin(); iter != sells.end(); iter.next_page()) { totalOffers += iter.page_size(); diff --git a/src/libxrpl/tx/transactors/system/Batch.cpp b/src/libxrpl/tx/transactors/system/Batch.cpp index b8b0d3234a..cd3ac9a16c 100644 --- a/src/libxrpl/tx/transactors/system/Batch.cpp +++ b/src/libxrpl/tx/transactors/system/Batch.cpp @@ -123,7 +123,7 @@ Batch::calculateBaseFee(ReadView const& view, STTx const& tx) } // LCOV_EXCL_STOP - XRPAmount signerFees = signerCount * view.fees().base; + XRPAmount const signerFees = signerCount * view.fees().base; // LCOV_EXCL_START if (signerFees > maxAmount - txnFees) diff --git a/src/libxrpl/tx/transactors/system/Change.cpp b/src/libxrpl/tx/transactors/system/Change.cpp index 2648902095..a1d9183ca4 100644 --- a/src/libxrpl/tx/transactors/system/Change.cpp +++ b/src/libxrpl/tx/transactors/system/Change.cpp @@ -142,7 +142,7 @@ Change::preCompute() TER Change::applyAmendment() { - uint256 amendment(ctx_.tx.getFieldH256(sfAmendment)); + uint256 const amendment(ctx_.tx.getFieldH256(sfAmendment)); auto const k = keylet::amendments(); diff --git a/src/libxrpl/tx/transactors/system/TicketCreate.cpp b/src/libxrpl/tx/transactors/system/TicketCreate.cpp index 0c41e503e4..c4e281c357 100644 --- a/src/libxrpl/tx/transactors/system/TicketCreate.cpp +++ b/src/libxrpl/tx/transactors/system/TicketCreate.cpp @@ -70,7 +70,7 @@ TicketCreate::doApply() return tecINSUFFICIENT_RESERVE; } - beast::Journal viewJ{ctx_.registry.get().getJournal("View")}; + beast::Journal const viewJ{ctx_.registry.get().getJournal("View")}; // The starting ticket sequence is the same as the current account // root sequence. Before we got here to doApply(), the transaction @@ -88,7 +88,7 @@ TicketCreate::doApply() { std::uint32_t const curTicketSeq = firstTicketSeq + i; Keylet const ticketKeylet = keylet::ticket(account_, curTicketSeq); - SLE::pointer sleTicket = std::make_shared(ticketKeylet); + SLE::pointer const sleTicket = std::make_shared(ticketKeylet); sleTicket->setAccountID(sfAccount, account_); sleTicket->setFieldU32(sfTicketSequence, curTicketSeq); diff --git a/src/libxrpl/tx/transactors/token/MPTokenAuthorize.cpp b/src/libxrpl/tx/transactors/token/MPTokenAuthorize.cpp index 464ede9de7..3ddc6d2c05 100644 --- a/src/libxrpl/tx/transactors/token/MPTokenAuthorize.cpp +++ b/src/libxrpl/tx/transactors/token/MPTokenAuthorize.cpp @@ -38,7 +38,7 @@ MPTokenAuthorize::preclaim(PreclaimContext const& ctx) // `holderID` is NOT used if (!holderID) { - std::shared_ptr sleMpt = + std::shared_ptr const sleMpt = ctx.view.read(keylet::mptoken(ctx.tx[sfMPTokenIssuanceID], accountID)); // There is an edge case where all holders have zero balance, issuance diff --git a/src/libxrpl/tx/transactors/token/TrustSet.cpp b/src/libxrpl/tx/transactors/token/TrustSet.cpp index 37935f07c2..feefa6a7ac 100644 --- a/src/libxrpl/tx/transactors/token/TrustSet.cpp +++ b/src/libxrpl/tx/transactors/token/TrustSet.cpp @@ -318,7 +318,7 @@ TrustSet::doApply() bool const bQualityOut(ctx_.tx.isFieldPresent(sfQualityOut)); Currency const currency(saLimitAmount.getCurrency()); - AccountID uDstAccountID(saLimitAmount.getIssuer()); + AccountID const uDstAccountID(saLimitAmount.getIssuer()); // true, if current is high account. bool const bHigh = account_ > uDstAccountID; @@ -350,7 +350,7 @@ TrustSet::doApply() XRPAmount const reserveCreate( (uOwnerCount < 2) ? XRPAmount(beast::zero) : view().fees().accountReserve(uOwnerCount + 1)); - std::uint32_t uQualityIn(bQualityIn ? ctx_.tx.getFieldU32(sfQualityIn) : 0); + std::uint32_t const uQualityIn(bQualityIn ? ctx_.tx.getFieldU32(sfQualityIn) : 0); std::uint32_t uQualityOut(bQualityOut ? ctx_.tx.getFieldU32(sfQualityOut) : 0); if (bQualityOut && QUALITY_ONE == uQualityOut) @@ -368,7 +368,7 @@ TrustSet::doApply() auto viewJ = ctx_.registry.get().getJournal("View"); - SLE::pointer sleDst = view().peek(keylet::account(uDstAccountID)); + SLE::pointer const sleDst = view().peek(keylet::account(uDstAccountID)); if (!sleDst) { @@ -379,7 +379,8 @@ TrustSet::doApply() STAmount saLimitAllow = saLimitAmount; saLimitAllow.setIssuer(account_); - SLE::pointer sleRippleState = view().peek(keylet::line(account_, uDstAccountID, currency)); + SLE::pointer const sleRippleState = + view().peek(keylet::line(account_, uDstAccountID, currency)); if (sleRippleState) { @@ -625,7 +626,7 @@ TrustSet::doApply() else { // Zero balance in currency. - STAmount saBalance(Issue{currency, noAccount()}); + STAmount const saBalance(Issue{currency, noAccount()}); auto const k = keylet::line(account_, uDstAccountID, currency); diff --git a/src/libxrpl/tx/transactors/vault/VaultClawback.cpp b/src/libxrpl/tx/transactors/vault/VaultClawback.cpp index a650aed310..6a4d6a579e 100644 --- a/src/libxrpl/tx/transactors/vault/VaultClawback.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultClawback.cpp @@ -334,7 +334,7 @@ VaultClawback::doApply() lossUnrealized <= (assetsTotal - assetsAvailable), "xrpl::VaultClawback::doApply : loss and assets do balance"); - AccountID holder = tx[sfHolder]; + AccountID const holder = tx[sfHolder]; STAmount sharesDestroyed = {share}; STAmount assetsRecovered = {vault->at(sfAsset)}; diff --git a/src/test/app/AMMCalc_test.cpp b/src/test/app/AMMCalc_test.cpp index b4043f239b..c3091a166d 100644 --- a/src/test/app/AMMCalc_test.cpp +++ b/src/test/app/AMMCalc_test.cpp @@ -37,7 +37,7 @@ class AMMCalc_test : public beast::unit_test::suite str = boost::regex_replace(str, boost::regex("^(A|O)[(]"), ""); boost::smatch match; // XXX(val))? - boost::regex rx("^([^(]+)[(]([^)]+)[)]([)])?$"); + boost::regex const rx("^([^(]+)[(]([^)]+)[)]([)])?$"); if (boost::regex_search(str, match, rx)) { if (delimited != nullptr) @@ -65,12 +65,12 @@ class AMMCalc_test : public beast::unit_test::suite str = boost::regex_replace(str, boost::regex("^T[(]"), ""); // XXX(rate))? boost::smatch match; - boost::regex rx("^([^(]+)[(]([^)]+)[)]([)])?$"); + boost::regex const rx("^([^(]+)[(]([^)]+)[)]([)])?$"); if (boost::regex_search(str, match, rx)) { std::string const currency = match[1]; // input is rate * 100, no fraction - std::uint32_t rate = 10'000'000 * std::stoi(match[2].str()); + std::uint32_t const rate = 10'000'000 * std::stoi(match[2].str()); // true if delimited - ) return {{currency, rate, match[3] != ""}}; } @@ -310,7 +310,7 @@ class AMMCalc_test : public beast::unit_test::suite { using namespace jtx; auto const a = arg(); - boost::regex re(","); + boost::regex const re(","); token_iter p(a.begin(), a.end(), re, -1); // Token is denoted as CUR(xxx), where CUR is the currency code // and xxx is the amount, for instance: XRP(100) or USD(11.5) @@ -391,7 +391,7 @@ class AMMCalc_test : public beast::unit_test::suite // 10 is AMM trading fee else if (*p == "changespq") { - Env env(*this); + Env const env(*this); if (auto const pool = getAmounts(++p)) { if (auto const offer = getAmounts(p)) diff --git a/src/test/app/AMMClawback_test.cpp b/src/test/app/AMMClawback_test.cpp index 9033fe2bdd..245ee38ac2 100644 --- a/src/test/app/AMMClawback_test.cpp +++ b/src/test/app/AMMClawback_test.cpp @@ -18,8 +18,8 @@ class AMMClawback_test : public beast::unit_test::suite // Test if holder does not exist. { Env env(*this); - Account gw{"gateway"}; - Account alice{"alice"}; + Account const gw{"gateway"}; + Account const alice{"alice"}; env.fund(XRP(100000), gw, alice); env.close(); @@ -32,7 +32,7 @@ class AMMClawback_test : public beast::unit_test::suite env.trust(USD(10000), alice); env(pay(gw, alice, USD(100))); - AMM amm(env, alice, XRP(100), USD(100)); + AMM const amm(env, alice, XRP(100), USD(100)); env.close(); env(amm::ammClawback(gw, Account("unknown"), USD, XRP, std::nullopt), @@ -44,7 +44,7 @@ class AMMClawback_test : public beast::unit_test::suite { Env env(*this); Account gw{"gateway"}; - Account alice{"alice"}; + Account const alice{"alice"}; env.fund(XRP(100000), gw, alice); env.close(); @@ -75,8 +75,8 @@ class AMMClawback_test : public beast::unit_test::suite // return temMALFORMED error. { Env env(*this); - Account gw{"gateway"}; - Account alice{"alice"}; + Account const gw{"gateway"}; + Account const alice{"alice"}; env.fund(XRP(10000), gw, alice); env.close(); @@ -91,7 +91,7 @@ class AMMClawback_test : public beast::unit_test::suite env(pay(gw, alice, USD(100))); env.close(); - AMM amm(env, gw, XRP(100), USD(100), ter(tesSUCCESS)); + AMM const amm(env, gw, XRP(100), USD(100), ter(tesSUCCESS)); // Issuer can not clawback from himself. env(amm::ammClawback(gw, gw, USD, XRP, std::nullopt), ter(temMALFORMED)); @@ -103,8 +103,8 @@ class AMMClawback_test : public beast::unit_test::suite // Test if the Asset field matches the Account field. { Env env(*this); - Account gw{"gateway"}; - Account alice{"alice"}; + Account const gw{"gateway"}; + Account const alice{"alice"}; env.fund(XRP(10000), gw, alice); env.close(); @@ -119,7 +119,7 @@ class AMMClawback_test : public beast::unit_test::suite env(pay(gw, alice, USD(100))); env.close(); - AMM amm(env, gw, XRP(100), USD(100), ter(tesSUCCESS)); + AMM const amm(env, gw, XRP(100), USD(100), ter(tesSUCCESS)); // The Asset's issuer field is alice, while the Account field is gw. // This should return temMALFORMED because they do not match. @@ -131,8 +131,8 @@ class AMMClawback_test : public beast::unit_test::suite // Test if the Amount field matches the Asset field. { Env env(*this); - Account gw{"gateway"}; - Account alice{"alice"}; + Account const gw{"gateway"}; + Account const alice{"alice"}; env.fund(XRP(10000), gw, alice); env.close(); @@ -147,7 +147,7 @@ class AMMClawback_test : public beast::unit_test::suite env(pay(gw, alice, USD(100))); env.close(); - AMM amm(env, gw, XRP(100), USD(100), ter(tesSUCCESS)); + AMM const amm(env, gw, XRP(100), USD(100), ter(tesSUCCESS)); // The Asset's issuer subfield is gw account and Amount's issuer // subfield is alice account. Return temBAD_AMOUNT because @@ -160,8 +160,8 @@ class AMMClawback_test : public beast::unit_test::suite // Test if the Amount is invalid, which is less than zero. { Env env(*this); - Account gw{"gateway"}; - Account alice{"alice"}; + Account const gw{"gateway"}; + Account const alice{"alice"}; env.fund(XRP(10000), gw, alice); env.close(); @@ -176,7 +176,7 @@ class AMMClawback_test : public beast::unit_test::suite env(pay(gw, alice, USD(100))); env.close(); - AMM amm(env, gw, XRP(100), USD(100), ter(tesSUCCESS)); + AMM const amm(env, gw, XRP(100), USD(100), ter(tesSUCCESS)); // Return temBAD_AMOUNT if the Amount value is less than 0. env(amm::ammClawback( @@ -193,8 +193,8 @@ class AMMClawback_test : public beast::unit_test::suite // transaction is prohibited. { Env env(*this); - Account gw{"gateway"}; - Account alice{"alice"}; + Account const gw{"gateway"}; + Account const alice{"alice"}; env.fund(XRP(10000), gw, alice); env.close(); @@ -207,7 +207,7 @@ class AMMClawback_test : public beast::unit_test::suite env.require(balance(gw, alice["USD"](-100))); // gw creates AMM pool of XRP/USD. - AMM amm(env, gw, XRP(100), USD(100), ter(tesSUCCESS)); + AMM const amm(env, gw, XRP(100), USD(100), ter(tesSUCCESS)); // If asfAllowTrustLineClawback is not set, the issuer is not // allowed to send the AMMClawback transaction. @@ -217,8 +217,8 @@ class AMMClawback_test : public beast::unit_test::suite // Test invalid flag. { Env env(*this); - Account gw{"gateway"}; - Account alice{"alice"}; + Account const gw{"gateway"}; + Account const alice{"alice"}; env.fund(XRP(10000), gw, alice); env.close(); @@ -233,7 +233,7 @@ class AMMClawback_test : public beast::unit_test::suite env(pay(gw, alice, USD(100))); env.close(); - AMM amm(env, gw, XRP(100), USD(100), ter(tesSUCCESS)); + AMM const amm(env, gw, XRP(100), USD(100), ter(tesSUCCESS)); // Return temINVALID_FLAG when providing invalid flag. env(amm::ammClawback(gw, alice, USD, XRP, std::nullopt), @@ -245,8 +245,8 @@ class AMMClawback_test : public beast::unit_test::suite // are not issued by the same issuer. { Env env(*this); - Account gw{"gateway"}; - Account alice{"alice"}; + Account const gw{"gateway"}; + Account const alice{"alice"}; env.fund(XRP(10000), gw, alice); env.close(); @@ -262,7 +262,7 @@ class AMMClawback_test : public beast::unit_test::suite env.close(); // gw creates AMM pool of XRP/USD. - AMM amm(env, gw, XRP(100), USD(100), ter(tesSUCCESS)); + AMM const amm(env, gw, XRP(100), USD(100), ter(tesSUCCESS)); // Return temINVALID_FLAG because the issuer set tfClawTwoAssets, // but the issuer only issues USD in the pool. The issuer is not @@ -276,8 +276,8 @@ class AMMClawback_test : public beast::unit_test::suite // Test clawing back XRP is being prohibited. { Env env(*this); - Account gw{"gateway"}; - Account alice{"alice"}; + Account const gw{"gateway"}; + Account const alice{"alice"}; env.fund(XRP(1000000), gw, alice); env.close(); @@ -293,7 +293,7 @@ class AMMClawback_test : public beast::unit_test::suite env.close(); // Alice creates AMM pool of XRP/USD. - AMM amm(env, alice, XRP(1000), USD(2000), ter(tesSUCCESS)); + AMM const amm(env, alice, XRP(1000), USD(2000), ter(tesSUCCESS)); env.close(); // Clawback XRP is prohibited. @@ -309,8 +309,8 @@ class AMMClawback_test : public beast::unit_test::suite if (!features[featureAMMClawback]) { Env env(*this, features); - Account gw{"gateway"}; - Account alice{"alice"}; + Account const gw{"gateway"}; + Account const alice{"alice"}; env.fund(XRP(1000000), gw, alice); env.close(); @@ -342,9 +342,9 @@ class AMMClawback_test : public beast::unit_test::suite // issuer. Claw back USD, and EUR goes back to the holder. { Env env(*this, features); - Account gw{"gateway"}; - Account gw2{"gateway2"}; - Account alice{"alice"}; + Account const gw{"gateway"}; + Account const gw2{"gateway2"}; + Account const alice{"alice"}; env.fund(XRP(1000000), gw, gw2, alice); env.close(); @@ -370,7 +370,7 @@ class AMMClawback_test : public beast::unit_test::suite env.require(balance(alice, EUR(3000))); // Alice creates AMM pool of EUR/USD. - AMM amm(env, alice, EUR(1000), USD(2000), ter(tesSUCCESS)); + AMM const amm(env, alice, EUR(1000), USD(2000), ter(tesSUCCESS)); env.close(); BEAST_EXPECT( @@ -422,8 +422,8 @@ class AMMClawback_test : public beast::unit_test::suite // to the holder. { Env env(*this, features); - Account gw{"gateway"}; - Account alice{"alice"}; + Account const gw{"gateway"}; + Account const alice{"alice"}; env.fund(XRP(1000000), gw, alice); env.close(); @@ -441,7 +441,7 @@ class AMMClawback_test : public beast::unit_test::suite env.require(balance(alice, USD(3000))); // Alice creates AMM pool of XRP/USD. - AMM amm(env, alice, XRP(1000), USD(2000), ter(tesSUCCESS)); + AMM const amm(env, alice, XRP(1000), USD(2000), ter(tesSUCCESS)); env.close(); BEAST_EXPECT(amm.expectBalances(USD(2000), XRP(1000), IOUAmount{1414213562373095, -9})); @@ -501,9 +501,9 @@ class AMMClawback_test : public beast::unit_test::suite // balance in AMM pool. { Env env(*this, features); - Account gw{"gateway"}; - Account gw2{"gateway2"}; - Account alice{"alice"}; + Account const gw{"gateway"}; + Account const gw2{"gateway2"}; + Account const alice{"alice"}; env.fund(XRP(1000000), gw, gw2, alice); env.close(); @@ -527,7 +527,7 @@ class AMMClawback_test : public beast::unit_test::suite env.require(balance(alice, EUR(6000))); // Alice creates AMM pool of EUR/USD - AMM amm(env, alice, EUR(5000), USD(4000), ter(tesSUCCESS)); + AMM const amm(env, alice, EUR(5000), USD(4000), ter(tesSUCCESS)); env.close(); if (!features[fixAMMv1_3]) @@ -672,8 +672,8 @@ class AMMClawback_test : public beast::unit_test::suite // creates the AMM pool EUR/XRP. { Env env(*this, features); - Account gw{"gateway"}; - Account gw2{"gateway2"}; + Account const gw{"gateway"}; + Account const gw2{"gateway2"}; Account alice{"alice"}; Account bob{"bob"}; env.fund(XRP(1000000), gw, gw2, alice, bob); @@ -1082,9 +1082,9 @@ class AMMClawback_test : public beast::unit_test::suite // issuer. Claw back all the USD for different users. { Env env(*this, features); - Account gw{"gateway"}; - Account gw2{"gateway2"}; - Account alice{"alice"}; + Account const gw{"gateway"}; + Account const gw2{"gateway2"}; + Account const alice{"alice"}; Account bob{"bob"}; Account carol{"carol"}; env.fund(XRP(1000000), gw, gw2, alice, bob, carol); @@ -1288,7 +1288,7 @@ class AMMClawback_test : public beast::unit_test::suite // different users. { Env env(*this, features); - Account gw{"gateway"}; + Account const gw{"gateway"}; Account alice{"alice"}; Account bob{"bob"}; env.fund(XRP(1000000), gw, alice, bob); @@ -1400,8 +1400,8 @@ class AMMClawback_test : public beast::unit_test::suite // Test AMMClawback for USD/EUR pool. The assets are issued by different // issuer. Claw back all the USD for different users. Env env(*this, features); - Account gw{"gateway"}; - Account alice{"alice"}; + Account const gw{"gateway"}; + Account const alice{"alice"}; Account bob{"bob"}; Account carol{"carol"}; env.fund(XRP(1000000), gw, alice, bob, carol); @@ -1534,9 +1534,9 @@ class AMMClawback_test : public beast::unit_test::suite // Test AMMClawback for USD/EUR pool. The assets are issued by different // issuer. Claw back all the USD for different users. Env env(*this, features); - Account gw{"gateway"}; - Account gw2{"gateway2"}; - Account alice{"alice"}; + Account const gw{"gateway"}; + Account const gw2{"gateway2"}; + Account const alice{"alice"}; Account bob{"bob"}; env.fund(XRP(1000000), gw, gw2, alice, bob); env.close(); @@ -1629,7 +1629,7 @@ class AMMClawback_test : public beast::unit_test::suite // gw and gw2 issues token for each other. Test AMMClawback from // each other. Env env(*this, features); - Account gw{"gateway"}; + Account const gw{"gateway"}; Account gw2{"gateway2"}; Account alice{"alice"}; env.fund(XRP(1000000), gw, gw2, alice); @@ -1815,8 +1815,8 @@ class AMMClawback_test : public beast::unit_test::suite using namespace jtx; Env env(*this, features); - Account gw{"gateway"}; - Account alice{"alice"}; + Account const gw{"gateway"}; + Account const alice{"alice"}; env.fund(XRP(1000000), gw, alice); env.close(); @@ -1829,7 +1829,7 @@ class AMMClawback_test : public beast::unit_test::suite env.trust(USD(100000), alice); env(pay(gw, alice, USD(5000))); - AMM amm(env, gw, USD(1000), XRP(2000), ter(tesSUCCESS)); + AMM const amm(env, gw, USD(1000), XRP(2000), ter(tesSUCCESS)); env.close(); // Alice did not deposit in the amm pool. So AMMClawback from Alice @@ -1846,9 +1846,9 @@ class AMMClawback_test : public beast::unit_test::suite // test individually frozen trustline. { Env env(*this, features); - Account gw{"gateway"}; - Account gw2{"gateway2"}; - Account alice{"alice"}; + Account const gw{"gateway"}; + Account const gw2{"gateway2"}; + Account const alice{"alice"}; env.fund(XRP(1000000), gw, gw2, alice); env.close(); @@ -1872,7 +1872,7 @@ class AMMClawback_test : public beast::unit_test::suite env.require(balance(alice, EUR(3000))); // Alice creates AMM pool of EUR/USD. - AMM amm(env, alice, EUR(1000), USD(2000), ter(tesSUCCESS)); + AMM const amm(env, alice, EUR(1000), USD(2000), ter(tesSUCCESS)); env.close(); BEAST_EXPECT( @@ -1910,9 +1910,9 @@ class AMMClawback_test : public beast::unit_test::suite // test individually frozen trustline of both USD and EUR currency. { Env env(*this, features); - Account gw{"gateway"}; - Account gw2{"gateway2"}; - Account alice{"alice"}; + Account const gw{"gateway"}; + Account const gw2{"gateway2"}; + Account const alice{"alice"}; env.fund(XRP(1000000), gw, gw2, alice); env.close(); @@ -1936,7 +1936,7 @@ class AMMClawback_test : public beast::unit_test::suite env.require(balance(alice, EUR(3000))); // Alice creates AMM pool of EUR/USD. - AMM amm(env, alice, EUR(1000), USD(2000), ter(tesSUCCESS)); + AMM const amm(env, alice, EUR(1000), USD(2000), ter(tesSUCCESS)); env.close(); BEAST_EXPECT( @@ -1960,9 +1960,9 @@ class AMMClawback_test : public beast::unit_test::suite // test gw global freeze. { Env env(*this, features); - Account gw{"gateway"}; - Account gw2{"gateway2"}; - Account alice{"alice"}; + Account const gw{"gateway"}; + Account const gw2{"gateway2"}; + Account const alice{"alice"}; env.fund(XRP(1000000), gw, gw2, alice); env.close(); @@ -1986,7 +1986,7 @@ class AMMClawback_test : public beast::unit_test::suite env.require(balance(alice, EUR(3000))); // Alice creates AMM pool of EUR/USD. - AMM amm(env, alice, EUR(1000), USD(2000), ter(tesSUCCESS)); + AMM const amm(env, alice, EUR(1000), USD(2000), ter(tesSUCCESS)); env.close(); BEAST_EXPECT( @@ -2010,8 +2010,8 @@ class AMMClawback_test : public beast::unit_test::suite // global freeze. { Env env(*this, features); - Account gw{"gateway"}; - Account alice{"alice"}; + Account const gw{"gateway"}; + Account const alice{"alice"}; Account bob{"bob"}; Account carol{"carol"}; env.fund(XRP(1000000), gw, alice, bob, carol); @@ -2149,7 +2149,7 @@ class AMMClawback_test : public beast::unit_test::suite // Test AMMClawback for USD/XRP pool. Claw back USD, and XRP goes back // to the holder. Env env(*this, features, std::make_unique(&logs)); - Account gw{"gateway"}; + Account const gw{"gateway"}; Account alice{"alice"}; env.fund(XRP(1000000000), gw, alice); env.close(); @@ -2357,7 +2357,7 @@ class AMMClawback_test : public beast::unit_test::suite Account gw{"gateway"}, alice{"alice"}, bob{"bob"}; auto const USD = setupAccounts(env, gw, alice, bob); - Account gw2{"gateway2"}; + Account const gw2{"gateway2"}; env.fund(XRP(100000), gw2); env.close(); auto const EUR = gw2["EUR"]; diff --git a/src/test/app/AMMExtended_test.cpp b/src/test/app/AMMExtended_test.cpp index 9de1714389..cc63f3d124 100644 --- a/src/test/app/AMMExtended_test.cpp +++ b/src/test/app/AMMExtended_test.cpp @@ -61,9 +61,9 @@ private: env(offer(carol, XRP(50), USD(50))); // Good quality path - AMM ammCarol(env, carol, BTC(1'000), USD(100'100)); + AMM const ammCarol(env, carol, BTC(1'000), USD(100'100)); - PathSet paths(Path(XRP, USD), Path(USD)); + PathSet const paths(Path(XRP, USD), Path(USD)); env(pay(alice, bob, USD(100)), json(paths.json()), @@ -114,7 +114,7 @@ private: env(pay(gw2, bob, USD2(50))); env.close(); - AMM ammDan(env, dan, XRP(10'000), USD1(10'000)); + AMM const ammDan(env, dan, XRP(10'000), USD1(10'000)); env(pay(alice, carol, USD2(50)), path(~USD1, bob), @@ -145,7 +145,7 @@ private: env(pay(gw2, bob, USD2(50))); env.close(); - AMM ammDan(env, dan, XRP(10'000), USD1(10'050)); + AMM const ammDan(env, dan, XRP(10'000), USD1(10'050)); env(pay(alice, carol, USD2(50)), path(~USD1, bob), @@ -269,7 +269,7 @@ private: fund(env, gw, {bob, alice}, XRP(300'000), {USD(100)}, Fund::All); - AMM ammAlice(env, alice, XRP(150'000), USD(50)); + AMM const ammAlice(env, alice, XRP(150'000), USD(50)); // Existing offer pays better than this wants. // Partially consume existing offer. @@ -302,7 +302,7 @@ private: env(pay(gw, alice, alice["USD"](500))); - AMM ammAlice(env, alice, XRP(150'000), USD(51)); + AMM const ammAlice(env, alice, XRP(150'000), USD(51)); env(offer(bob, USD(1), XRP(3'000))); BEAST_EXPECT(ammAlice.expectBalances(XRP(153'000), USD(50), ammAlice.tokens())); @@ -334,7 +334,7 @@ private: env.require(owners(alice, 1), owners(bob, 1)); env(pay(gw, alice, alice["USD"](100))); - AMM ammBob(env, bob, USD(200), XRP(1'500)); + AMM const ammBob(env, bob, USD(200), XRP(1'500)); env(pay(alice, alice, XRP(500)), sendmax(USD(100))); @@ -459,7 +459,7 @@ private: env(pay(gw2, dan, dan["EUR"](400))); env.close(); - AMM ammCarol(env, carol, USD1(5'000), XRP(50'000)); + AMM const ammCarol(env, carol, USD1(5'000), XRP(50'000)); env(offer(dan, XRP(500), EUR1(50))); env.close(); @@ -513,7 +513,7 @@ private: env(pay(gw1, bob, bob["USD"](1'200))); - AMM ammBob(env, bob, XRP(1'000), USD1(1'200)); + AMM const ammBob(env, bob, XRP(1'000), USD1(1'200)); // Alice has 350 fees - a reserve of 50 = 250 reserve = 100 available. // Ask for more than available to prove reserve works. env(offer(alice, USD1(200), XRP(200))); @@ -548,7 +548,7 @@ private: env(pay(gw, bob, USD(1))); env(pay(gw, alice, USD(200))); - AMM ammAlice(env, alice, USD(150), XRP(150'100)); + AMM const ammAlice(env, alice, USD(150), XRP(150'100)); env(offer(bob, XRP(100), USD(0.1))); BEAST_EXPECT(ammAlice.expectBalances(USD(150.1), XRP(150'000), ammAlice.tokens())); @@ -601,7 +601,7 @@ private: env(pay(gw, bob, bob["USD"](2'200))); - AMM ammBob(env, bob, XRP(1'000), USD(2'200)); + AMM const ammBob(env, bob, XRP(1'000), USD(2'200)); // Alice has 350 fees - a reserve of 50 = 250 reserve = 100 available. // Ask for more than available to prove reserve works. // Taker pays 100 USD for 100 XRP. @@ -629,7 +629,7 @@ private: auto const starting_xrp = XRP(100.1) + reserve(env, 1) + env.current()->fees().base * 2; fund(env, gw, {alice, bob}, starting_xrp, {XTS(100), XXX(100)}, Fund::All); - AMM ammAlice(env, alice, XTS(100), XXX(100)); + AMM const ammAlice(env, alice, XTS(100), XXX(100)); Json::Value payment; payment[jss::secret] = toBase58(generateSeed("bob")); @@ -677,8 +677,8 @@ private: // o carol has EUR but wants USD. // Note that carol's offer must come last. If carol's offer is // placed before AMM is created, then autobridging will not occur. - AMM ammAlice(env, alice, XRP(10'000), USD(10'100)); - AMM ammBob(env, bob, EUR(10'000), XRP(10'100)); + AMM const ammAlice(env, alice, XRP(10'000), USD(10'100)); + AMM const ammBob(env, bob, EUR(10'000), XRP(10'100)); // Carol makes an offer that consumes AMM liquidity and // fully consumes Carol's offer. @@ -704,7 +704,7 @@ private: // Note that carol's offer must come last. If carol's offer is // placed before AMM and bob's offer are created, then autobridging // will not occur. - AMM ammAlice(env, alice, XRP(10'000), USD(10'100)); + AMM const ammAlice(env, alice, XRP(10'000), USD(10'100)); env(offer(bob, EUR(100), XRP(100))); env.close(); @@ -734,7 +734,7 @@ private: // autobridging will not occur. env(offer(alice, XRP(100), USD(100))); env.close(); - AMM ammBob(env, bob, EUR(10'000), XRP(10'100)); + AMM const ammBob(env, bob, EUR(10'000), XRP(10'100)); // Carol makes an offer that consumes AMM liquidity and // fully consumes Carol's offer. @@ -764,7 +764,7 @@ private: { Env env{*this, features}; fund(env, gw, {alice, bob}, {USD(20'000)}, Fund::All); - AMM ammBob(env, bob, XRP(20'000), USD(200)); + AMM const ammBob(env, bob, XRP(20'000), USD(200)); // alice submits a tfSell | tfFillOrKill offer that does not cross. env(offer(alice, USD(2.1), XRP(210), tfSell | tfFillOrKill), ter(killedCode)); @@ -774,7 +774,7 @@ private: { Env env{*this, features}; fund(env, gw, {alice, bob}, {USD(1'000)}, Fund::All); - AMM ammBob(env, bob, XRP(20'000), USD(200)); + AMM const ammBob(env, bob, XRP(20'000), USD(200)); // alice submits a tfSell | tfFillOrKill offer that crosses. // Even though tfSell is present it doesn't matter this time. env(offer(alice, USD(2), XRP(220), tfSell | tfFillOrKill)); @@ -790,7 +790,7 @@ private: // returns more than was asked for (because of the tfSell flag). Env env{*this, features}; fund(env, gw, {alice, bob}, {USD(1'000)}, Fund::All); - AMM ammBob(env, bob, XRP(20'000), USD(200)); + AMM const ammBob(env, bob, XRP(20'000), USD(200)); env(offer(alice, USD(10), XRP(1'500), tfSell | tfFillOrKill)); env.close(); @@ -809,7 +809,7 @@ private: // which matches alice's offer quality is ~ 10XRP/0.01996USD. Env env{*this, features}; fund(env, gw, {alice, bob}, {USD(10'000)}, Fund::All); - AMM ammBob(env, bob, XRP(5000), USD(10)); + AMM const ammBob(env, bob, XRP(5000), USD(10)); env(offer(alice, USD(1), XRP(501), tfSell | tfFillOrKill), ter(tecKILLED)); env.close(); @@ -876,7 +876,7 @@ private: // o carol has EUR but wants USD. // Note that Carol's offer must come last. If Carol's offer is // placed before AMM is created, then autobridging will not occur. - AMM ammAlice(env, alice, XRP(10'000), USD(10'100)); + AMM const ammAlice(env, alice, XRP(10'000), USD(10'100)); env(offer(bob, EUR(100), XRP(100))); env.close(); @@ -907,7 +907,7 @@ private: // o carol has EUR but wants USD. // Note that Carol's offer must come last. If Carol's offer is // placed before AMM is created, then autobridging will not occur. - AMM ammAlice(env, alice, XRP(10'000), USD(10'050)); + AMM const ammAlice(env, alice, XRP(10'000), USD(10'050)); env(offer(bob, EUR(100), XRP(100))); env.close(); @@ -953,7 +953,7 @@ private: // o carol has EUR but wants USD. // Note that Carol's offer must come last. If Carol's offer is // placed before AMM is created, then autobridging will not occur. - AMM ammAlice(env, alice, XRP(10'000), USD(10'100)); + AMM const ammAlice(env, alice, XRP(10'000), USD(10'100)); env(offer(bob, EUR(100), XRP(100))); env.close(); @@ -995,7 +995,7 @@ private: // o carol has EUR but wants USD. // Note that Carol's offer must come last. If Carol's offer is // placed before AMM is created, then autobridging will not occur. - AMM ammAlice(env, alice, XRP(10'000), USD(10'100)); + AMM const ammAlice(env, alice, XRP(10'000), USD(10'100)); env(offer(bob, EUR(100), XRP(100))); env.close(); @@ -1029,7 +1029,7 @@ private: env.fund(XRP(30'000) + f, alice, bob); env.close(); - AMM ammBob(env, bob, XRP(10'000), USD_bob(10'100)); + AMM const ammBob(env, bob, XRP(10'000), USD_bob(10'100)); env(offer(alice, USD_bob(100), XRP(100))); env.close(); @@ -1086,7 +1086,7 @@ private: BEAST_EXPECT(expectHolding(env, dan, A_BUX(none))); BEAST_EXPECT(expectHolding(env, dan, D_BUX(none))); - AMM ammBob(env, bob, A_BUX(30), D_BUX(30)); + AMM const ammBob(env, bob, A_BUX(30), D_BUX(30)); env(trust(ann, D_BUX(100))); env.close(); @@ -1143,7 +1143,7 @@ private: env(pay(bob, carol, B_BUX(400))); env(pay(ann, carol, A_BUX(400))); - AMM ammCarol(env, carol, A_BUX(300), B_BUX(330)); + AMM const ammCarol(env, carol, A_BUX(300), B_BUX(330)); // cam puts an offer on the books that her upcoming offer could cross. // But this offer should be deleted, not crossed, by her upcoming @@ -1215,7 +1215,7 @@ private: env(pay(gw, alice, USD(1'000))); env.close(); // Alice is able to create AMM since the GW has authorized her - AMM ammAlice(env, alice, USD(1'000), XRP(1'050)); + AMM const ammAlice(env, alice, USD(1'000), XRP(1'050)); // Set up authorized trust line for AMM. env(trust(gw, STAmount{Issue{USD.currency, ammAlice.ammAccount()}, 10}), @@ -1250,7 +1250,7 @@ private: // Alice doesn't have the funds { - AMM ammAlice(env, alice, USD(1'000), XRP(1'000), ter(tecUNFUNDED_AMM)); + AMM const ammAlice(env, alice, USD(1'000), XRP(1'000), ter(tecUNFUNDED_AMM)); } env(fset(gw, asfRequireAuth)); @@ -1267,7 +1267,7 @@ private: // Alice should not be able to create AMM without authorization. { - AMM ammAlice(env, alice, USD(1'000), XRP(1'000), ter(tecNO_LINE)); + AMM const ammAlice(env, alice, USD(1'000), XRP(1'000), ter(tecNO_LINE)); } // Set up a trust line for Alice, but don't authorize it. Alice @@ -1276,7 +1276,7 @@ private: env.close(); { - AMM ammAlice(env, alice, USD(1'000), XRP(1'000), ter(tecNO_AUTH)); + AMM const ammAlice(env, alice, USD(1'000), XRP(1'000), ter(tecNO_AUTH)); } // Finally, set up an authorized trust line for Alice. Now Alice's @@ -1286,7 +1286,7 @@ private: env(pay(gw, alice, USD(1'000))); env.close(); - AMM ammAlice(env, alice, USD(1'000), XRP(1'050)); + AMM const ammAlice(env, alice, USD(1'000), XRP(1'050)); // Set up authorized trust line for AMM. env(trust(gw, STAmount{Issue{USD.currency, ammAlice.ammAccount()}, 10}), @@ -1349,7 +1349,7 @@ private: env.fund(XRP(100'000'250), alice); fund(env, gw, {carol, bob}, {USD(100)}, Fund::All); fund(env, gw, {alice}, {USD(100)}, Fund::IOUOnly); - AMM ammCarol(env, carol, XRP(100), USD(100)); + AMM const ammCarol(env, carol, XRP(100), USD(100)); STPathSet st; STAmount sa; @@ -1383,7 +1383,7 @@ private: env.trust(AUD(2'000), bob, carol); env(pay(gw, carol, AUD(51))); env.close(); - AMM ammCarol(env, carol, XRP(40), AUD(51)); + AMM const ammCarol(env, carol, XRP(40), AUD(51)); env(pay(alice, bob, AUD(10)), sendmax(XRP(100)), paths(XRP)); env.close(); // AMM offer is 51.282052XRP/11AUD, 11AUD/1.1 = 10AUD to bob @@ -1404,7 +1404,7 @@ private: // XRP -> IOU receive max Env env = pathTestEnv(); fund(env, gw, {alice, bob, charlie}, {USD(11)}, Fund::All); - AMM ammCharlie(env, charlie, XRP(10), USD(11)); + AMM const ammCharlie(env, charlie, XRP(10), USD(11)); auto [st, sa, da] = find_paths(env, alice, bob, USD(-1), XRP(1).value()); BEAST_EXPECT(sa == XRP(1)); BEAST_EXPECT(equal(da, USD(1))); @@ -1420,7 +1420,7 @@ private: // IOU -> XRP receive max Env env = pathTestEnv(); fund(env, gw, {alice, bob, charlie}, {USD(11)}, Fund::All); - AMM ammCharlie(env, charlie, XRP(11), USD(10)); + AMM const ammCharlie(env, charlie, XRP(11), USD(10)); env.close(); auto [st, sa, da] = find_paths(env, alice, bob, drops(-1), USD(1).value()); BEAST_EXPECT(sa == USD(1)); @@ -1441,13 +1441,13 @@ private: testcase("Path Find: XRP -> XRP and XRP -> IOU"); using namespace jtx; Env env = pathTestEnv(); - Account A1{"A1"}; - Account A2{"A2"}; - Account A3{"A3"}; - Account G1{"G1"}; - Account G2{"G2"}; - Account G3{"G3"}; - Account M1{"M1"}; + Account const A1{"A1"}; + Account const A2{"A2"}; + Account const A3{"A3"}; + Account const G1{"G1"}; + Account const G2{"G2"}; + Account const G3{"G3"}; + Account const M1{"M1"}; env.fund(XRP(100'000), A1); env.fund(XRP(10'000), A2); @@ -1472,8 +1472,8 @@ private: env(pay(G3, M1, G3["ABC"](25'000))); env.close(); - AMM ammM1_G1_G2(env, M1, G1["XYZ"](1'000), G2["XYZ"](1'000)); - AMM ammM1_XRP_G3(env, M1, XRP(10'000), G3["ABC"](1'000)); + AMM const ammM1_G1_G2(env, M1, G1["XYZ"](1'000), G2["XYZ"](1'000)); + AMM const ammM1_XRP_G3(env, M1, XRP(10'000), G3["ABC"](1'000)); STPathSet st; STAmount sa, da; @@ -1526,10 +1526,10 @@ private: testcase("Path Find: non-XRP -> XRP"); using namespace jtx; Env env = pathTestEnv(); - Account A1{"A1"}; - Account A2{"A2"}; - Account G3{"G3"}; - Account M1{"M1"}; + Account const A1{"A1"}; + Account const A2{"A2"}; + Account const G3{"G3"}; + Account const M1{"M1"}; env.fund(XRP(1'000), A1, A2, G3); env.fund(XRP(11'000), M1); @@ -1544,7 +1544,7 @@ private: env(pay(G3, M1, G3["ABC"](1'200))); env.close(); - AMM ammM1(env, M1, G3["ABC"](1'000), XRP(10'010)); + AMM const ammM1(env, M1, G3["ABC"](1'000), XRP(10'010)); STPathSet st; STAmount sa, da; @@ -1562,16 +1562,16 @@ private: testcase("Path Find: non-XRP -> non-XRP, same currency"); using namespace jtx; Env env = pathTestEnv(); - Account A1{"A1"}; - Account A2{"A2"}; - Account A3{"A3"}; - Account A4{"A4"}; - Account G1{"G1"}; - Account G2{"G2"}; - Account G3{"G3"}; - Account G4{"G4"}; - Account M1{"M1"}; - Account M2{"M2"}; + Account const A1{"A1"}; + Account const A2{"A2"}; + Account const A3{"A3"}; + Account const A4{"A4"}; + Account const G1{"G1"}; + Account const G2{"G2"}; + Account const G3{"G3"}; + Account const G4{"G4"}; + Account const M1{"M1"}; + Account const M2{"M2"}; env.fund(XRP(1'000), A1, A2, A3, G1, G2, G3, G4); env.fund(XRP(10'000), A4); @@ -1596,9 +1596,9 @@ private: env(pay(G2, M2, G2["HKD"](5'000))); env.close(); - AMM ammM1(env, M1, G1["HKD"](1'010), G2["HKD"](1'000)); - AMM ammM2XRP_G2(env, M2, XRP(10'000), G2["HKD"](1'010)); - AMM ammM2G1_XRP(env, M2, G1["HKD"](1'010), XRP(10'000)); + AMM const ammM1(env, M1, G1["HKD"](1'010), G2["HKD"](1'000)); + AMM const ammM2XRP_G2(env, M2, XRP(10'000), G2["HKD"](1'010)); + AMM const ammM2G1_XRP(env, M2, G1["HKD"](1'010), XRP(10'000)); STPathSet st; STAmount sa, da; @@ -1692,12 +1692,12 @@ private: testcase("Path Find: non-XRP -> non-XRP, same currency"); using namespace jtx; Env env = pathTestEnv(); - Account A1{"A1"}; - Account A2{"A2"}; - Account A3{"A3"}; - Account G1{"G1"}; - Account G2{"G2"}; - Account M1{"M1"}; + Account const A1{"A1"}; + Account const A2{"A2"}; + Account const A3{"A3"}; + Account const G1{"G1"}; + Account const G2{"G2"}; + Account const M1{"M1"}; env.fund(XRP(11'000), M1); env.fund(XRP(1'000), A1, A2, A3, G1, G2); @@ -1716,7 +1716,7 @@ private: env(pay(G2, M1, G2["HKD"](5'000))); env.close(); - AMM ammM1(env, M1, G1["HKD"](1'010), G2["HKD"](1'000)); + AMM const ammM1(env, M1, G1["HKD"](1'010), G2["HKD"](1'000)); // E) Gateway to user // Source -> OB -> AC -> Destination @@ -1759,7 +1759,7 @@ private: // tecPATH_DRY, but the entire path should not be marked as dry. // This is the second error case to test (when flowV1 is used). env(offer(bob, EUR(50), XRP(50))); - AMM ammBob(env, bob, ammXrpPool, USD(150)); + AMM const ammBob(env, bob, ammXrpPool, USD(150)); env(pay(alice, carol, USD(1'000'000)), path(~XRP, ~USD), @@ -1783,7 +1783,7 @@ private: fund(env, gw, {alice, bob, carol}, XRP(10'000), {BTC(100), USD(150)}, Fund::All); - AMM ammBob(env, bob, BTC(100), USD(150)); + AMM const ammBob(env, bob, BTC(100), USD(150)); env(pay(alice, carol, USD(50)), path(~USD), sendmax(BTC(50))); @@ -1799,8 +1799,8 @@ private: fund(env, gw, {alice, carol, bob}, XRP(10'000), {BTC(100), USD(150)}, Fund::All); - AMM ammBobBTC_XRP(env, bob, BTC(100), XRP(150)); - AMM ammBobXRP_USD(env, bob, XRP(100), USD(150)); + AMM const ammBobBTC_XRP(env, bob, BTC(100), XRP(150)); + AMM const ammBobXRP_USD(env, bob, XRP(100), USD(150)); env(pay(alice, carol, USD(50)), path(~XRP, ~USD), sendmax(BTC(50))); @@ -1817,7 +1817,7 @@ private: fund(env, gw, {alice, carol, bob}, XRP(10'000), {USD(150)}, Fund::All); - AMM ammBob(env, bob, XRP(100), USD(150)); + AMM const ammBob(env, bob, XRP(100), USD(150)); env(pay(alice, carol, USD(50)), path(~USD), sendmax(XRP(50))); @@ -1833,7 +1833,7 @@ private: fund(env, gw, {alice, carol, bob}, XRP(10'000), {USD(100)}, Fund::All); - AMM ammBob(env, bob, USD(100), XRP(150)); + AMM const ammBob(env, bob, USD(100), XRP(150)); env(pay(alice, carol, XRP(50)), path(~XRP), sendmax(USD(50))); @@ -1863,7 +1863,7 @@ private: env(offer(bob, BTC(50), USD(50))); env(offer(bob, BTC(40), EUR(50))); env.close(); - AMM ammBob(env, bob, EUR(100), USD(150)); + AMM const ammBob(env, bob, EUR(100), USD(150)); // unfund offer env(pay(bob, gw, EUR(50))); @@ -1914,7 +1914,7 @@ private: env.close(); // This is multiplath, which generates limited # of offers - AMM ammBobBTC_USD(env, bob, BTC(50), USD(50)); + AMM const ammBobBTC_USD(env, bob, BTC(50), USD(50)); env(offer(bob, BTC(60), EUR(50))); env(offer(carol, BTC(1'000), EUR(1))); env(offer(bob, EUR(50), USD(50))); @@ -1928,7 +1928,7 @@ private: auto flowJournal = env.app().getJournal("Flow"); auto const flowResult = [&] { - STAmount deliver(USD(51)); + STAmount const deliver(USD(51)); STAmount smax(BTC(61)); PaymentSandbox sb(env.current().get(), tapNONE); STPathSet paths; @@ -1941,10 +1941,10 @@ private: }; { // BTC -> USD - STPath p1({IPE(USD.issue())}); + STPath const p1({IPE(USD.issue())}); paths.push_back(p1); // BTC -> EUR -> USD - STPath p2({IPE(EUR.issue()), IPE(USD.issue())}); + STPath const p2({IPE(EUR.issue()), IPE(USD.issue())}); paths.push_back(p2); } @@ -2007,7 +2007,7 @@ private: env.close(); // env(offer(bob, USD(1), drops(2)), txflags(tfPassive)); - AMM ammBob(env, bob, USD(8), XRPAmount{21}); + AMM const ammBob(env, bob, USD(8), XRPAmount{21}); env(offer(bob, drops(1), EUR(1'000)), txflags(tfPassive)); env(pay(alice, carol, EUR(1)), @@ -2034,7 +2034,7 @@ private: env(rate(gw, 1.25)); env.close(); - AMM amm(env, bob, GBP(1'000), USD(1'000)); + AMM const amm(env, bob, GBP(1'000), USD(1'000)); env(pay(alice, carol, USD(100)), path(~USD), @@ -2075,7 +2075,7 @@ private: env(offer(ed, GBP(1'000), EUR(1'000)), txflags(tfPassive)); env.close(); - AMM amm(env, bob, EUR(1'000), USD(1'000)); + AMM const amm(env, bob, EUR(1'000), USD(1'000)); env(pay(alice, carol, USD(100)), path(~EUR, ~USD), @@ -2109,8 +2109,8 @@ private: env(rate(gw, 1.25)); env.close(); - AMM amm1(env, bob, GBP(1'000), EUR(1'000)); - AMM amm2(env, ed, EUR(1'000), USD(1'000)); + AMM const amm1(env, bob, GBP(1'000), EUR(1'000)); + AMM const amm2(env, ed, EUR(1'000), USD(1'000)); env(pay(alice, carol, USD(100)), path(~EUR, ~USD), @@ -2159,7 +2159,7 @@ private: env(rate(gw, 1.25)); env.close(); - AMM amm(env, bob, USD(1'000), EUR(1'100)); + AMM const amm(env, bob, USD(1'000), EUR(1'100)); env(offer(alice, EUR(100), USD(100))); env.close(); @@ -2178,7 +2178,7 @@ private: env(rate(gw, 1.25)); env.close(); - AMM amm(env, bob, GBP(1'000), USD(1'000)); + AMM const amm(env, bob, GBP(1'000), USD(1'000)); // requested quality limit is 100USD/178.58GBP = 0.55997 // trade quality is 100USD/178.5714 = 0.55999 @@ -2209,7 +2209,7 @@ private: env(rate(gw, 1.25)); env.close(); - AMM amm(env, bob, GBP(1'000), USD(1'200)); + AMM const amm(env, bob, GBP(1'000), USD(1'200)); // requested quality limit is 90USD/120GBP = 0.75 // trade quality is 22.5USD/30GBP = 0.75 @@ -2259,7 +2259,7 @@ private: env(offer(ed, GBP(1'000), EUR(1'000)), txflags(tfPassive)); env.close(); - AMM amm(env, bob, EUR(1'000), USD(1'400)); + AMM const amm(env, bob, EUR(1'000), USD(1'400)); // requested quality limit is 95USD/140GBP = 0.6785 // trade quality is 59.7321USD/88.0262GBP = 0.6785 @@ -2340,7 +2340,7 @@ private: env(rate(gw, 1.25)); env.close(); - AMM amm(env, bob, GBP(1'000), EUR(1'000)); + AMM const amm(env, bob, GBP(1'000), EUR(1'000)); env(offer(ed, EUR(1'000), USD(1'400)), txflags(tfPassive)); env.close(); @@ -2412,8 +2412,8 @@ private: env(rate(gw, 1.25)); env.close(); - AMM amm1(env, bob, GBP(1'000), EUR(1'000)); - AMM amm2(env, ed, EUR(1'000), USD(1'400)); + AMM const amm1(env, bob, GBP(1'000), EUR(1'000)); + AMM const amm2(env, ed, EUR(1'000), USD(1'400)); // requested quality limit is 90USD/145GBP = 0.6206 // trade quality is 66.7432USD/107.5308GBP = 0.6206 @@ -2474,8 +2474,8 @@ private: env(rate(gw, 1.25)); env.close(); - AMM amm1(env, alice, GBP(1'000), EUR(1'000)); - AMM amm2(env, bob, EUR(1'000), USD(1'400)); + AMM const amm1(env, alice, GBP(1'000), EUR(1'000)); + AMM const amm2(env, bob, EUR(1'000), USD(1'400)); // requested quality limit is 90USD/120GBP = 0.75 // trade quality is 81.1111USD/108.1481GBP = 0.75 @@ -2534,7 +2534,7 @@ private: fund(env, gw, {alice, bob, carol}, XRP(10'000), {USD(2'000)}); - AMM ammBob(env, bob, XRP(1'000), USD(1'050)); + AMM const ammBob(env, bob, XRP(1'000), USD(1'050)); env(offer(bob, XRP(100), USD(50))); env(pay(alice, carol, USD(100)), @@ -2561,8 +2561,8 @@ private: // fails with tecPATH_DRY. fund(env, gw, {alice, bob}, XRP(10'000), {USD(200), EUR(200)}, Fund::All); - AMM ammAliceXRP_USD(env, alice, XRP(100), USD(101)); - AMM ammAliceXRP_EUR(env, alice, XRP(100), EUR(101)); + AMM const ammAliceXRP_USD(env, alice, XRP(100), USD(101)); + AMM const ammAliceXRP_EUR(env, alice, XRP(100), EUR(101)); env.close(); TER const expectedTer = TER{temBAD_PATH_LOOP}; @@ -2579,8 +2579,8 @@ private: // with tecPATH_DRY. fund(env, gw, {alice, bob}, XRP(10'000), {USD(200), EUR(200)}, Fund::All); - AMM ammAliceXRP_USD(env, alice, XRP(100), USD(100)); - AMM ammAliceXRP_EUR(env, alice, XRP(100), EUR(100)); + AMM const ammAliceXRP_USD(env, alice, XRP(100), USD(100)); + AMM const ammAliceXRP_EUR(env, alice, XRP(100), EUR(100)); // EUR -> //XRP -> //USD ->XRP env(pay(alice, bob, XRP(1)), path(~XRP, ~USD, ~XRP), @@ -2597,9 +2597,9 @@ private: // with tecPATH_DRY. fund(env, gw, {alice, bob}, XRP(10'000), {USD(200), EUR(200), JPY(200)}, Fund::All); - AMM ammAliceXRP_USD(env, alice, XRP(100), USD(100)); - AMM ammAliceXRP_EUR(env, alice, XRP(100), EUR(100)); - AMM ammAliceXRP_JPY(env, alice, XRP(100), JPY(100)); + AMM const ammAliceXRP_USD(env, alice, XRP(100), USD(100)); + AMM const ammAliceXRP_EUR(env, alice, XRP(100), EUR(100)); + AMM const ammAliceXRP_JPY(env, alice, XRP(100), JPY(100)); env(pay(alice, bob, JPY(1)), path(~XRP, ~EUR, ~XRP, ~JPY), @@ -2628,7 +2628,7 @@ private: env(pay(gw, dan, USD(1))); n_offers(env, 2'000, bob, XRP(1), USD(1)); n_offers(env, 1, dan, XRP(1), USD(1)); - AMM ammEd(env, ed, XRP(9), USD(11)); + AMM const ammEd(env, ed, XRP(9), USD(11)); // Alice offers to buy 1000 XRP for 1000 USD. She takes Bob's first // offer, removes 999 more as unfunded, then hits the step limit. @@ -2687,7 +2687,7 @@ private: txflags(tfPartialPayment), ter(temBAD_AMOUNT)); env(pay(gw, carol, USD(50))); - AMM ammCarol(env, carol, XRP(10), USD(15)); + AMM const ammCarol(env, carol, XRP(10), USD(15)); env(pay(alice, bob, USD(10)), paths(XRP), deliver_min(USD(7)), @@ -2703,7 +2703,7 @@ private: fund(env, gw, {alice, bob}, XRP(10'000)); env.trust(USD(1'100), alice, bob); env(pay(gw, bob, USD(1'100))); - AMM ammBob(env, bob, XRP(1'000), USD(1'100)); + AMM const ammBob(env, bob, XRP(1'000), USD(1'100)); env(pay(alice, alice, USD(10'000)), paths(XRP), deliver_min(USD(100)), @@ -2717,7 +2717,7 @@ private: fund(env, gw, {alice, bob, carol}, XRP(10'000)); env.trust(USD(1'200), bob, carol); env(pay(gw, bob, USD(1'200))); - AMM ammBob(env, bob, XRP(5'500), USD(1'200)); + AMM const ammBob(env, bob, XRP(5'500), USD(1'200)); env(pay(alice, carol, USD(10'000)), paths(XRP), deliver_min(USD(200)), @@ -2743,7 +2743,7 @@ private: env(pay(gw, dan, USD(1'100))); env(offer(bob, XRP(100), USD(100))); env(offer(bob, XRP(1'000), USD(100))); - AMM ammDan(env, dan, XRP(1'000), USD(1'100)); + AMM const ammDan(env, dan, XRP(1'000), USD(1'100)); if (!features[fixAMMv1_1]) { env(pay(alice, carol, USD(10'000)), @@ -2794,7 +2794,7 @@ private: env(pay(gw, alice, USD(500))); env.close(); - AMM ammAlice(env, alice, XRP(100), USD(140)); + AMM const ammAlice(env, alice, XRP(100), USD(140)); // becky pays herself USD (10) by consuming part of alice's offer. // Make sure the payment works if PaymentAuth is not involved. @@ -2829,7 +2829,7 @@ private: env(pay(gw, alice, USD(150))); env(pay(gw, carol, USD(150))); - AMM ammCarol(env, carol, USD(100), XRPAmount(101)); + AMM const ammCarol(env, carol, USD(100), XRPAmount(101)); // Make sure bob's trust line is all set up so he can receive USD. env(pay(alice, bob, USD(50))); @@ -2926,7 +2926,7 @@ private: env(pay(G1, alice, G1["USD"](205))); env.close(); - AMM ammAlice(env, alice, XRP(500), G1["USD"](105)); + AMM const ammAlice(env, alice, XRP(500), G1["USD"](105)); { auto lines = getAccountLines(env, bob); @@ -3040,11 +3040,11 @@ private: using namespace test::jtx; Env env(*this, features); - Account G1{"G1"}; - Account A1{"A1"}; - Account A2{"A2"}; - Account A3{"A3"}; - Account A4{"A4"}; + Account const G1{"G1"}; + Account const A1{"A1"}; + Account const A2{"A2"}; + Account const A3{"A3"}; + Account const A4{"A4"}; env.fund(XRP(12'000), G1); env.fund(XRP(1'000), A1); @@ -3063,7 +3063,7 @@ private: env(pay(G1, A4, G1["BTC"](100))); env.close(); - AMM ammG1(env, G1, XRP(10'000), G1["USD"](100)); + AMM const ammG1(env, G1, XRP(10'000), G1["USD"](100)); env(offer(A1, XRP(10'000), G1["USD"](100)), txflags(tfPassive)); env(offer(A2, G1["USD"](100), XRP(10'000)), txflags(tfPassive)); env.close(); @@ -3129,7 +3129,7 @@ private: env.require(nflags(G1, asfNoFreeze)); // test: assets can't be bought on the market - AMM ammA3(env, A3, G1["BTC"](1), XRP(1), ter(tecFROZEN)); + AMM const ammA3(env, A3, G1["BTC"](1), XRP(1), ter(tecFROZEN)); // test: assets can't be sold on the market // AMM is bidirectional @@ -3170,10 +3170,10 @@ private: using namespace test::jtx; Env env(*this, features); - Account G1{"G1"}; - Account A2{"A2"}; - Account A3{"A3"}; - Account A4{"A4"}; + Account const G1{"G1"}; + Account const A2{"A2"}; + Account const A3{"A3"}; + Account const A4{"A4"}; env.fund(XRP(2'000), G1, A3, A4); env.fund(XRP(2'000), A2); @@ -3188,7 +3188,7 @@ private: env(pay(G1, A4, G1["USD"](2'001))); env.close(); - AMM ammA3(env, A3, XRP(1'000), G1["USD"](1'001)); + AMM const ammA3(env, A3, XRP(1'000), G1["USD"](1'001)); // removal after successful payment // test: make a payment with partially consuming offer @@ -3299,8 +3299,8 @@ private: fund(env, gw, {alice, bob, carol}, XRP(10'000), {USD(2'000), EUR(1'000)}); - AMM bobXRP_USD(env, bob, XRP(1'000), USD(1'000)); - AMM bobUSD_EUR(env, bob, USD(1'000), EUR(1'000)); + AMM const bobXRP_USD(env, bob, XRP(1'000), USD(1'000)); + AMM const bobUSD_EUR(env, bob, USD(1'000), EUR(1'000)); // payment path: XRP -> XRP/USD -> USD/EUR -> EUR/USD env(pay(alice, carol, USD(100)), @@ -3327,10 +3327,10 @@ private: fund(env, bob, {alice, gw}, {BobUSD(100), BobEUR(100)}, Fund::IOUOnly); env.close(); - AMM ammBobXRP_USD(env, bob, XRP(100), BobUSD(100)); + AMM const ammBobXRP_USD(env, bob, XRP(100), BobUSD(100)); env(offer(gw, XRP(100), USD(100)), txflags(tfPassive)); - AMM ammBobUSD_EUR(env, bob, BobUSD(100), BobEUR(100)); + AMM const ammBobUSD_EUR(env, bob, BobUSD(100), BobEUR(100)); env(offer(gw, USD(100), EUR(100)), txflags(tfPassive)); Path const p = [&] { @@ -3340,7 +3340,7 @@ private: return result; }(); - PathSet paths(p); + PathSet const paths(p); env(pay(alice, alice, EUR(1)), json(paths.json()), @@ -3354,7 +3354,7 @@ private: fund(env, gw, {alice, bob, carol}, XRP(10'000), {USD(100)}); - AMM ammBob(env, bob, XRP(100), USD(100)); + AMM const ammBob(env, bob, XRP(100), USD(100)); // payment path: XRP -> XRP/USD -> USD/XRP env(pay(alice, carol, XRP(100)), @@ -3368,7 +3368,7 @@ private: fund(env, gw, {alice, bob, carol}, XRP(10'000), {USD(100)}); - AMM ammBob(env, bob, XRP(100), USD(100)); + AMM const ammBob(env, bob, XRP(100), USD(100)); // payment path: XRP -> XRP/USD -> USD/XRP env(pay(alice, carol, XRP(100)), @@ -3398,7 +3398,7 @@ private: env(pay(gw, alice, USD(100))); env.close(); - AMM ammBob(env, bob, XRP(100), USD(100)); + AMM const ammBob(env, bob, XRP(100), USD(100)); // payment path: USD -> USD/XRP -> XRP/USD env(pay(alice, carol, USD(100)), @@ -3421,9 +3421,9 @@ private: env(pay(gw, bob, EUR(200))); env(pay(gw, bob, CNY(100))); - AMM ammBobXRP_USD(env, bob, XRP(100), USD(100)); - AMM ammBobUSD_EUR(env, bob, USD(100), EUR(100)); - AMM ammBobEUR_CNY(env, bob, EUR(100), CNY(100)); + AMM const ammBobXRP_USD(env, bob, XRP(100), USD(100)); + AMM const ammBobUSD_EUR(env, bob, USD(100), EUR(100)); + AMM const ammBobEUR_CNY(env, bob, EUR(100), CNY(100)); // payment path: XRP->XRP/USD->USD/EUR->USD/CNY env(pay(alice, carol, CNY(100)), diff --git a/src/test/app/AMM_test.cpp b/src/test/app/AMM_test.cpp index 704ced2b86..c19eb971a7 100644 --- a/src/test/app/AMM_test.cpp +++ b/src/test/app/AMM_test.cpp @@ -87,7 +87,7 @@ private: env(rate(gw, 1.25)); env.close(); // no transfer fee on create - AMM ammAlice(env, alice, USD(20'000), BTC(0.5)); + AMM const ammAlice(env, alice, USD(20'000), BTC(0.5)); BEAST_EXPECT(ammAlice.expectBalances(USD(20'000), BTC(0.5), IOUAmount{100, 0})); BEAST_EXPECT(expectHolding(env, alice, USD(0))); BEAST_EXPECT(expectHolding(env, alice, BTC(0))); @@ -104,7 +104,7 @@ private: env.close(); env(pay(gw, alice, USD(10'000))); env.close(); - AMM ammAlice(env, alice, XRP(10'000), USD(10'000)); + AMM const ammAlice(env, alice, XRP(10'000), USD(10'000)); } // Cleared global freeze @@ -118,10 +118,10 @@ private: env.close(); env(fset(gw, asfGlobalFreeze)); env.close(); - AMM ammAliceFail(env, alice, XRP(10'000), USD(10'000), ter(tecFROZEN)); + AMM const ammAliceFail(env, alice, XRP(10'000), USD(10'000), ter(tecFROZEN)); env(fclear(gw, asfGlobalFreeze)); env.close(); - AMM ammAlice(env, alice, XRP(10'000), USD(10'000)); + AMM const ammAlice(env, alice, XRP(10'000), USD(10'000)); } // Trading fee @@ -153,7 +153,7 @@ private: { Env env{*this}; fund(env, gw, {alice}, {USD(30'000)}, Fund::All); - AMM ammAlice(env, alice, XRP(10'000), XRP(10'000), ter(temBAD_AMM_TOKENS)); + AMM const ammAlice(env, alice, XRP(10'000), XRP(10'000), ter(temBAD_AMM_TOKENS)); BEAST_EXPECT(!ammAlice.ammExists()); } @@ -161,7 +161,7 @@ private: { Env env{*this}; fund(env, gw, {alice}, {USD(30'000)}, Fund::All); - AMM ammAlice(env, alice, USD(10'000), USD(10'000), ter(temBAD_AMM_TOKENS)); + AMM const ammAlice(env, alice, USD(10'000), USD(10'000), ter(temBAD_AMM_TOKENS)); BEAST_EXPECT(!ammAlice.ammExists()); } @@ -169,13 +169,13 @@ private: { Env env{*this}; fund(env, gw, {alice}, {USD(30'000)}, Fund::All); - AMM ammAlice(env, alice, XRP(0), USD(10'000), ter(temBAD_AMOUNT)); + AMM const ammAlice(env, alice, XRP(0), USD(10'000), ter(temBAD_AMOUNT)); BEAST_EXPECT(!ammAlice.ammExists()); - AMM ammAlice1(env, alice, XRP(10'000), USD(0), ter(temBAD_AMOUNT)); + AMM const ammAlice1(env, alice, XRP(10'000), USD(0), ter(temBAD_AMOUNT)); BEAST_EXPECT(!ammAlice1.ammExists()); - AMM ammAlice2(env, alice, XRP(10'000), USD(-10'000), ter(temBAD_AMOUNT)); + AMM const ammAlice2(env, alice, XRP(10'000), USD(-10'000), ter(temBAD_AMOUNT)); BEAST_EXPECT(!ammAlice2.ammExists()); - AMM ammAlice3(env, alice, XRP(-10'000), USD(10'000), ter(temBAD_AMOUNT)); + AMM const ammAlice3(env, alice, XRP(-10'000), USD(10'000), ter(temBAD_AMOUNT)); BEAST_EXPECT(!ammAlice3.ammExists()); } @@ -183,7 +183,7 @@ private: { Env env{*this}; fund(env, gw, {alice}, {USD(30'000)}, Fund::All); - AMM ammAlice(env, alice, XRP(10'000), BAD(10'000), ter(temBAD_CURRENCY)); + AMM const ammAlice(env, alice, XRP(10'000), BAD(10'000), ter(temBAD_CURRENCY)); BEAST_EXPECT(!ammAlice.ammExists()); } @@ -191,7 +191,7 @@ private: { Env env{*this}; fund(env, gw, {alice}, {USD(30'000)}, Fund::All); - AMM ammAlice(env, alice, XRP(10'000), USD(40'000), ter(tecUNFUNDED_AMM)); + AMM const ammAlice(env, alice, XRP(10'000), USD(40'000), ter(tecUNFUNDED_AMM)); BEAST_EXPECT(!ammAlice.ammExists()); } @@ -199,7 +199,7 @@ private: { Env env{*this}; fund(env, gw, {alice}, {USD(30'000)}, Fund::All); - AMM ammAlice(env, alice, XRP(40'000), USD(10'000), ter(tecUNFUNDED_AMM)); + AMM const ammAlice(env, alice, XRP(40'000), USD(10'000), ter(tecUNFUNDED_AMM)); BEAST_EXPECT(!ammAlice.ammExists()); } @@ -207,7 +207,7 @@ private: { Env env{*this}; fund(env, gw, {alice}, {USD(30'000)}, Fund::All); - AMM ammAlice( + AMM const ammAlice( env, alice, XRP(10'000), @@ -224,14 +224,14 @@ private: // AMM already exists testAMM([&](AMM& ammAlice, Env& env) { - AMM ammCarol(env, carol, XRP(10'000), USD(10'000), ter(tecDUPLICATE)); + AMM const ammCarol(env, carol, XRP(10'000), USD(10'000), ter(tecDUPLICATE)); }); // Invalid flags { Env env{*this}; fund(env, gw, {alice}, {USD(30'000)}, Fund::All); - AMM ammAlice( + AMM const ammAlice( env, alice, XRP(10'000), @@ -249,9 +249,9 @@ private: // Invalid Account { Env env{*this}; - Account bad("bad"); + Account const bad("bad"); env.memoize(bad); - AMM ammAlice( + AMM const ammAlice( env, bad, XRP(10'000), @@ -275,7 +275,7 @@ private: env.close(); env(trust(gw, alice["USD"](30'000))); env.close(); - AMM ammAlice(env, alice, XRP(10'000), USD(10'000), ter(tecNO_AUTH)); + AMM const ammAlice(env, alice, XRP(10'000), USD(10'000), ter(tecNO_AUTH)); BEAST_EXPECT(!ammAlice.ammExists()); } @@ -288,7 +288,7 @@ private: env.close(); env(trust(gw, alice["USD"](30'000))); env.close(); - AMM ammAlice(env, alice, XRP(10'000), USD(10'000), ter(tecFROZEN)); + AMM const ammAlice(env, alice, XRP(10'000), USD(10'000), ter(tecFROZEN)); BEAST_EXPECT(!ammAlice.ammExists()); } @@ -301,7 +301,7 @@ private: env.close(); env(trust(gw, alice["USD"](0), tfSetFreeze)); env.close(); - AMM ammAlice(env, alice, XRP(10'000), USD(10'000), ter(tecFROZEN)); + AMM const ammAlice(env, alice, XRP(10'000), USD(10'000), ter(tecFROZEN)); BEAST_EXPECT(!ammAlice.ammExists()); } @@ -317,7 +317,7 @@ private: env.close(); env(offer(alice, XRP(101), USD(100))); env(offer(alice, XRP(102), USD(100))); - AMM ammAlice(env, alice, XRP(1'000), USD(1'000), ter(tecUNFUNDED_AMM)); + AMM const ammAlice(env, alice, XRP(1'000), USD(1'000), ter(tecUNFUNDED_AMM)); } // Insufficient reserve, IOU/IOU @@ -334,14 +334,14 @@ private: env.close(); env(offer(alice, EUR(101), USD(100))); env(offer(alice, EUR(102), USD(100))); - AMM ammAlice(env, alice, EUR(1'000), USD(1'000), ter(tecINSUF_RESERVE_LINE)); + AMM const ammAlice(env, alice, EUR(1'000), USD(1'000), ter(tecINSUF_RESERVE_LINE)); } // Insufficient fee { Env env(*this); fund(env, gw, {alice}, XRP(2'000), {USD(2'000), EUR(2'000)}); - AMM ammAlice( + AMM const ammAlice( env, alice, EUR(1'000), @@ -360,13 +360,13 @@ private: // AMM with one LPToken from another AMM. testAMM([&](AMM& ammAlice, Env& env) { fund(env, gw, {alice}, {EUR(10'000)}, Fund::IOUOnly); - AMM ammAMMToken( + AMM const ammAMMToken( env, alice, EUR(10'000), STAmount{ammAlice.lptIssue(), 1'000'000}, ter(tecAMM_INVALID_TOKENS)); - AMM ammAMMToken1( + AMM const ammAMMToken1( env, alice, STAmount{ammAlice.lptIssue(), 1'000'000}, @@ -377,10 +377,10 @@ private: // AMM with two LPTokens from other AMMs. testAMM([&](AMM& ammAlice, Env& env) { fund(env, gw, {alice}, {EUR(10'000)}, Fund::IOUOnly); - AMM ammAlice1(env, alice, XRP(10'000), EUR(10'000)); + AMM const ammAlice1(env, alice, XRP(10'000), EUR(10'000)); auto const token1 = ammAlice.lptIssue(); auto const token2 = ammAlice1.lptIssue(); - AMM ammAMMTokens( + AMM const ammAMMTokens( env, alice, STAmount{token1, 1'000'000}, @@ -393,21 +393,21 @@ private: Env env(*this); env.fund(XRP(30'000), gw); env(fclear(gw, asfDefaultRipple)); - AMM ammGw(env, gw, XRP(10'000), USD(10'000), ter(terNO_RIPPLE)); + AMM const ammGw(env, gw, XRP(10'000), USD(10'000), ter(terNO_RIPPLE)); env.fund(XRP(30'000), alice); env.trust(USD(30'000), alice); env(pay(gw, alice, USD(30'000))); - AMM ammAlice(env, alice, XRP(10'000), USD(10'000), ter(terNO_RIPPLE)); + AMM const ammAlice(env, alice, XRP(10'000), USD(10'000), ter(terNO_RIPPLE)); Account const gw1("gw1"); env.fund(XRP(30'000), gw1); env(fclear(gw1, asfDefaultRipple)); env.trust(USD(30'000), gw1); env(pay(gw, gw1, USD(30'000))); auto const USD1 = gw1["USD"]; - AMM ammGwGw1(env, gw, USD(10'000), USD1(10'000), ter(terNO_RIPPLE)); + AMM const ammGwGw1(env, gw, USD(10'000), USD1(10'000), ter(terNO_RIPPLE)); env.trust(USD1(30'000), alice); env(pay(gw1, alice, USD1(30'000))); - AMM ammAlice1(env, alice, USD(10'000), USD1(10'000), ter(terNO_RIPPLE)); + AMM const ammAlice1(env, alice, USD(10'000), USD1(10'000), ter(terNO_RIPPLE)); } } @@ -429,106 +429,65 @@ private: std::optional, std::optional, std::optional, - std::optional>> - invalidOptions = { - // flags, tokens, asset1In, asset2in, EPrice, tfee - {tfLPToken, 1'000, std::nullopt, USD(100), std::nullopt, std::nullopt}, - {tfLPToken, 1'000, XRP(100), std::nullopt, std::nullopt, std::nullopt}, - {tfLPToken, - 1'000, - std::nullopt, - std::nullopt, - STAmount{USD, 1, -1}, - std::nullopt}, - {tfLPToken, - std::nullopt, - USD(100), - std::nullopt, - STAmount{USD, 1, -1}, - std::nullopt}, - {tfLPToken, 1'000, XRP(100), std::nullopt, STAmount{USD, 1, -1}, std::nullopt}, - {tfLPToken, 1'000, std::nullopt, std::nullopt, std::nullopt, 1'000}, - {tfSingleAsset, 1'000, std::nullopt, std::nullopt, std::nullopt, std::nullopt}, - {tfSingleAsset, - std::nullopt, - std::nullopt, - USD(100), - std::nullopt, - std::nullopt}, - {tfSingleAsset, - std::nullopt, - std::nullopt, - std::nullopt, - STAmount{USD, 1, -1}, - std::nullopt}, - {tfSingleAsset, std::nullopt, USD(100), std::nullopt, std::nullopt, 1'000}, - {tfTwoAsset, 1'000, std::nullopt, std::nullopt, std::nullopt, std::nullopt}, - {tfTwoAsset, - std::nullopt, - XRP(100), - USD(100), - STAmount{USD, 1, -1}, - std::nullopt}, - {tfTwoAsset, std::nullopt, XRP(100), std::nullopt, std::nullopt, std::nullopt}, - {tfTwoAsset, std::nullopt, XRP(100), USD(100), std::nullopt, 1'000}, - {tfTwoAsset, - std::nullopt, - std::nullopt, - USD(100), - STAmount{USD, 1, -1}, - std::nullopt}, - {tfOneAssetLPToken, - 1'000, - std::nullopt, - std::nullopt, - std::nullopt, - std::nullopt}, - {tfOneAssetLPToken, - std::nullopt, - XRP(100), - USD(100), - std::nullopt, - std::nullopt}, - {tfOneAssetLPToken, - std::nullopt, - XRP(100), - std::nullopt, - STAmount{USD, 1, -1}, - std::nullopt}, - {tfOneAssetLPToken, 1'000, XRP(100), std::nullopt, std::nullopt, 1'000}, - {tfLimitLPToken, 1'000, std::nullopt, std::nullopt, std::nullopt, std::nullopt}, - {tfLimitLPToken, 1'000, USD(100), std::nullopt, std::nullopt, std::nullopt}, - {tfLimitLPToken, std::nullopt, USD(100), XRP(100), std::nullopt, std::nullopt}, - {tfLimitLPToken, - std::nullopt, - XRP(100), - std::nullopt, - STAmount{USD, 1, -1}, - 1'000}, - {tfTwoAssetIfEmpty, - std::nullopt, - std::nullopt, - std::nullopt, - std::nullopt, - 1'000}, - {tfTwoAssetIfEmpty, - 1'000, - std::nullopt, - std::nullopt, - std::nullopt, - std::nullopt}, - {tfTwoAssetIfEmpty, - std::nullopt, - XRP(100), - USD(100), - STAmount{USD, 1, -1}, - std::nullopt}, - {tfTwoAssetIfEmpty | tfLPToken, - std::nullopt, - XRP(100), - USD(100), - STAmount{USD, 1, -1}, - std::nullopt}}; + std::optional>> const invalidOptions = { + // flags, tokens, asset1In, asset2in, EPrice, tfee + {tfLPToken, 1'000, std::nullopt, USD(100), std::nullopt, std::nullopt}, + {tfLPToken, 1'000, XRP(100), std::nullopt, std::nullopt, std::nullopt}, + {tfLPToken, 1'000, std::nullopt, std::nullopt, STAmount{USD, 1, -1}, std::nullopt}, + {tfLPToken, + std::nullopt, + USD(100), + std::nullopt, + STAmount{USD, 1, -1}, + std::nullopt}, + {tfLPToken, 1'000, XRP(100), std::nullopt, STAmount{USD, 1, -1}, std::nullopt}, + {tfLPToken, 1'000, std::nullopt, std::nullopt, std::nullopt, 1'000}, + {tfSingleAsset, 1'000, std::nullopt, std::nullopt, std::nullopt, std::nullopt}, + {tfSingleAsset, std::nullopt, std::nullopt, USD(100), std::nullopt, std::nullopt}, + {tfSingleAsset, + std::nullopt, + std::nullopt, + std::nullopt, + STAmount{USD, 1, -1}, + std::nullopt}, + {tfSingleAsset, std::nullopt, USD(100), std::nullopt, std::nullopt, 1'000}, + {tfTwoAsset, 1'000, std::nullopt, std::nullopt, std::nullopt, std::nullopt}, + {tfTwoAsset, std::nullopt, XRP(100), USD(100), STAmount{USD, 1, -1}, std::nullopt}, + {tfTwoAsset, std::nullopt, XRP(100), std::nullopt, std::nullopt, std::nullopt}, + {tfTwoAsset, std::nullopt, XRP(100), USD(100), std::nullopt, 1'000}, + {tfTwoAsset, + std::nullopt, + std::nullopt, + USD(100), + STAmount{USD, 1, -1}, + std::nullopt}, + {tfOneAssetLPToken, 1'000, std::nullopt, std::nullopt, std::nullopt, std::nullopt}, + {tfOneAssetLPToken, std::nullopt, XRP(100), USD(100), std::nullopt, std::nullopt}, + {tfOneAssetLPToken, + std::nullopt, + XRP(100), + std::nullopt, + STAmount{USD, 1, -1}, + std::nullopt}, + {tfOneAssetLPToken, 1'000, XRP(100), std::nullopt, std::nullopt, 1'000}, + {tfLimitLPToken, 1'000, std::nullopt, std::nullopt, std::nullopt, std::nullopt}, + {tfLimitLPToken, 1'000, USD(100), std::nullopt, std::nullopt, std::nullopt}, + {tfLimitLPToken, std::nullopt, USD(100), XRP(100), std::nullopt, std::nullopt}, + {tfLimitLPToken, std::nullopt, XRP(100), std::nullopt, STAmount{USD, 1, -1}, 1'000}, + {tfTwoAssetIfEmpty, std::nullopt, std::nullopt, std::nullopt, std::nullopt, 1'000}, + {tfTwoAssetIfEmpty, 1'000, std::nullopt, std::nullopt, std::nullopt, std::nullopt}, + {tfTwoAssetIfEmpty, + std::nullopt, + XRP(100), + USD(100), + STAmount{USD, 1, -1}, + std::nullopt}, + {tfTwoAssetIfEmpty | tfLPToken, + std::nullopt, + XRP(100), + USD(100), + STAmount{USD, 1, -1}, + std::nullopt}}; for (auto const& it : invalidOptions) { ammAlice.deposit( @@ -1445,7 +1404,7 @@ private: testAMM( [&](AMM& ammAlice, Env& env) { - WithdrawArg args{ + WithdrawArg const args{ .asset1Out = XRP(100), .err = ter(tecAMM_BALANCE), }; @@ -1455,7 +1414,7 @@ private: testAMM( [&](AMM& ammAlice, Env& env) { - WithdrawArg args{ + WithdrawArg const args{ .asset1Out = USD(100), .err = ter(tecAMM_BALANCE), }; @@ -1478,7 +1437,7 @@ private: env(pay(gw, alice, USD(10'000))); env.close(); AMM ammAlice(env, alice, XRP(10'000), USD(10'000)); - WithdrawArg args{ + WithdrawArg const args{ .account = bob, .asset1Out = USD(100), .err = ter(tecNO_AUTH), @@ -1516,79 +1475,58 @@ private: std::optional, std::optional, std::optional, - NotTEC>> - invalidOptions = { - // tokens, asset1Out, asset2Out, EPrice, flags, ter - {std::nullopt, - std::nullopt, - std::nullopt, - std::nullopt, - std::nullopt, - temMALFORMED}, - {std::nullopt, - std::nullopt, - std::nullopt, - std::nullopt, - tfSingleAsset | tfTwoAsset, - temMALFORMED}, - {1'000, std::nullopt, std::nullopt, std::nullopt, tfWithdrawAll, temMALFORMED}, - {std::nullopt, - USD(0), - XRP(100), - std::nullopt, - tfWithdrawAll | tfLPToken, - temMALFORMED}, - {std::nullopt, - std::nullopt, - USD(100), - std::nullopt, - tfWithdrawAll, - temMALFORMED}, - {std::nullopt, - std::nullopt, - std::nullopt, - std::nullopt, - tfWithdrawAll | tfOneAssetWithdrawAll, - temMALFORMED}, - {std::nullopt, - USD(100), - std::nullopt, - std::nullopt, - tfWithdrawAll, - temMALFORMED}, - {std::nullopt, - std::nullopt, - std::nullopt, - std::nullopt, - tfOneAssetWithdrawAll, - temMALFORMED}, - {1'000, std::nullopt, USD(100), std::nullopt, std::nullopt, temMALFORMED}, - {std::nullopt, - std::nullopt, - std::nullopt, - IOUAmount{250, 0}, - tfWithdrawAll, - temMALFORMED}, - {1'000, - std::nullopt, - std::nullopt, - IOUAmount{250, 0}, - std::nullopt, - temMALFORMED}, - {std::nullopt, - std::nullopt, - USD(100), - IOUAmount{250, 0}, - std::nullopt, - temMALFORMED}, - {std::nullopt, - XRP(100), - USD(100), - IOUAmount{250, 0}, - std::nullopt, - temMALFORMED}, - {1'000, XRP(100), USD(100), std::nullopt, std::nullopt, temMALFORMED}, - {std::nullopt, XRP(100), USD(100), std::nullopt, tfWithdrawAll, temMALFORMED}}; + NotTEC>> const invalidOptions = { + // tokens, asset1Out, asset2Out, EPrice, flags, ter + {std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt, + temMALFORMED}, + {std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt, + tfSingleAsset | tfTwoAsset, + temMALFORMED}, + {1'000, std::nullopt, std::nullopt, std::nullopt, tfWithdrawAll, temMALFORMED}, + {std::nullopt, + USD(0), + XRP(100), + std::nullopt, + tfWithdrawAll | tfLPToken, + temMALFORMED}, + {std::nullopt, std::nullopt, USD(100), std::nullopt, tfWithdrawAll, temMALFORMED}, + {std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt, + tfWithdrawAll | tfOneAssetWithdrawAll, + temMALFORMED}, + {std::nullopt, USD(100), std::nullopt, std::nullopt, tfWithdrawAll, temMALFORMED}, + {std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt, + tfOneAssetWithdrawAll, + temMALFORMED}, + {1'000, std::nullopt, USD(100), std::nullopt, std::nullopt, temMALFORMED}, + {std::nullopt, + std::nullopt, + std::nullopt, + IOUAmount{250, 0}, + tfWithdrawAll, + temMALFORMED}, + {1'000, std::nullopt, std::nullopt, IOUAmount{250, 0}, std::nullopt, temMALFORMED}, + {std::nullopt, + std::nullopt, + USD(100), + IOUAmount{250, 0}, + std::nullopt, + temMALFORMED}, + {std::nullopt, XRP(100), USD(100), IOUAmount{250, 0}, std::nullopt, temMALFORMED}, + {1'000, XRP(100), USD(100), std::nullopt, std::nullopt, temMALFORMED}, + {std::nullopt, XRP(100), USD(100), std::nullopt, tfWithdrawAll, temMALFORMED}}; for (auto const& it : invalidOptions) { ammAlice.withdraw( @@ -1984,7 +1922,7 @@ private: BEAST_EXPECT(!env.le(keylet::ownerDir(ammAlice.ammAccount()))); // Can create AMM for the XRP/USD pair - AMM ammCarol(env, carol, XRP(10'000), USD(10'000)); + AMM const ammCarol(env, carol, XRP(10'000), USD(10'000)); BEAST_EXPECT( ammCarol.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000, 0})); }); @@ -3147,12 +3085,12 @@ private: fund(env, gw, {alice, bob}, XRP(2'000), {USD(2'000)}); AMM amm(env, gw, XRP(1'000), USD(1'010), false, 1'000); - Json::Value tx = amm.bid({.account = alice, .bidMin = 500}); + Json::Value const tx = amm.bid({.account = alice, .bidMin = 500}); { auto jtx = env.jt(tx, seq(1), fee(baseFee)); env.app().config().features.erase(featureAMM); - PreflightContext pfCtx( + PreflightContext const pfCtx( env.app(), *jtx.stx, env.current()->rules(), tapNONE, env.journal); auto pf = Transactor::invokePreflight(pfCtx); BEAST_EXPECT(pf == temDISABLED); @@ -3163,7 +3101,7 @@ private: auto jtx = env.jt(tx, seq(1), fee(baseFee)); jtx.jv["TxnSignature"] = "deadbeef"; jtx.stx = env.ust(jtx); - PreflightContext pfCtx( + PreflightContext const pfCtx( env.app(), *jtx.stx, env.current()->rules(), tapNONE, env.journal); auto pf = Transactor::invokePreflight(pfCtx); BEAST_EXPECT(!isTesSuccess(pf)); @@ -3174,7 +3112,7 @@ private: jtx.jv["Asset2"]["currency"] = "XRP"; jtx.jv["Asset2"].removeMember("issuer"); jtx.stx = env.ust(jtx); - PreflightContext pfCtx( + PreflightContext const pfCtx( env.app(), *jtx.stx, env.current()->rules(), tapNONE, env.journal); auto pf = Transactor::invokePreflight(pfCtx); BEAST_EXPECT(pf == temBAD_AMM_TOKENS); @@ -3198,7 +3136,7 @@ private: Env env(*this); fund(env, gw, {alice, carol}, XRP(1'000), {USD(100)}); // XRP balance is below reserve - AMM ammAlice(env, acct, XRP(10), USD(10)); + AMM const ammAlice(env, acct, XRP(10), USD(10)); // Pay below reserve env(pay(carol, ammAlice.ammAccount(), XRP(10)), ter(tecNO_PERMISSION)); // Pay above reserve @@ -3210,7 +3148,7 @@ private: Env env(*this); fund(env, gw, {alice, carol}, XRP(10'000'000), {USD(10'000)}); // XRP balance is above reserve - AMM ammAlice(env, acct, XRP(1'000'000), USD(100)); + AMM const ammAlice(env, acct, XRP(1'000'000), USD(100)); // Pay below reserve env(pay(carol, ammAlice.ammAccount(), XRP(10)), ter(tecNO_PERMISSION)); // Pay above reserve @@ -3635,7 +3573,7 @@ private: env.close(); env(offer(bob, XRP(50), USD(150)), txflags(tfPassive)); env.close(); - AMM ammAlice(env, alice, XRP(1'000), USD(1'050)); + AMM const ammAlice(env, alice, XRP(1'000), USD(1'050)); env(pay(alice, carol, USD(200)), sendmax(XRP(200)), txflags(tfPartialPayment)); env.close(); BEAST_EXPECT(ammAlice.expectBalances(XRP(1'050), USD(1'000), ammAlice.tokens())); @@ -3962,13 +3900,13 @@ private: XRP(100'000), {EUR(50'000), BTC(50'000), ETH(50'000), USD(50'000)}); fund(env, gw, {carol, bob}, XRP(1'000), {USD(200)}, Fund::Acct); - AMM xrp_eur(env, alice, XRP(10'100), EUR(10'000)); - AMM eur_btc(env, alice, EUR(10'000), BTC(10'200)); - AMM btc_usd(env, alice, BTC(10'100), USD(10'000)); - AMM xrp_usd(env, alice, XRP(10'150), USD(10'200)); - AMM xrp_eth(env, alice, XRP(10'000), ETH(10'100)); - AMM eth_eur(env, alice, ETH(10'900), EUR(11'000)); - AMM eur_usd(env, alice, EUR(10'100), USD(10'000)); + AMM const xrp_eur(env, alice, XRP(10'100), EUR(10'000)); + AMM const eur_btc(env, alice, EUR(10'000), BTC(10'200)); + AMM const btc_usd(env, alice, BTC(10'100), USD(10'000)); + AMM const xrp_usd(env, alice, XRP(10'150), USD(10'200)); + AMM const xrp_eth(env, alice, XRP(10'000), ETH(10'100)); + AMM const eth_eur(env, alice, ETH(10'900), EUR(11'000)); + AMM const eur_usd(env, alice, EUR(10'100), USD(10'000)); env(pay(bob, carol, USD(100)), path(~EUR, ~BTC, ~USD), path(~USD), @@ -4043,11 +3981,11 @@ private: XRP(40'000), {EUR(50'000), BTC(50'000), ETH(50'000), USD(50'000)}); fund(env, gw, {carol, bob}, XRP(1000), {USD(200)}, Fund::Acct); - AMM xrp_eur(env, alice, XRP(10'100), EUR(10'000)); - AMM eur_btc(env, alice, EUR(10'000), BTC(10'200)); - AMM btc_usd(env, alice, BTC(10'100), USD(10'000)); - AMM xrp_eth(env, alice, XRP(10'000), ETH(10'100)); - AMM eth_eur(env, alice, ETH(10'900), EUR(11'000)); + AMM const xrp_eur(env, alice, XRP(10'100), EUR(10'000)); + AMM const eur_btc(env, alice, EUR(10'000), BTC(10'200)); + AMM const btc_usd(env, alice, BTC(10'100), USD(10'000)); + AMM const xrp_eth(env, alice, XRP(10'000), ETH(10'100)); + AMM const eth_eur(env, alice, ETH(10'900), EUR(11'000)); env(pay(bob, carol, USD(100)), path(~EUR, ~BTC, ~USD), path(~ETH, ~EUR, ~BTC, ~USD), @@ -4188,7 +4126,7 @@ private: Env env(*this, features); fund(env, gw, {alice, carol, bob}, XRP(30'000), {USD(30'000)}); env(offer(bob, XRP(100), USD(100.001))); - AMM ammAlice(env, alice, XRP(10'000), USD(10'100)); + AMM const ammAlice(env, alice, XRP(10'000), USD(10'100)); env(offer(carol, USD(100), XRP(100))); if (!features[fixAMMv1_1]) { @@ -4413,7 +4351,7 @@ private: env.trust(TSTB(10'000), C); env(pay(A, C, TSTA(10'000))); env(pay(B, C, TSTB(10'000))); - AMM amm(env, C, TSTA(5'000), TSTB(5'000)); + AMM const amm(env, C, TSTA(5'000), TSTB(5'000)); auto const ammIss = Issue(TSTA.currency, amm.ammAccount()); // Can TrustSet only for AMM LP tokens @@ -4463,7 +4401,7 @@ private: std::string lp2TakerPays; // Execute with AMM first prep( - [&](Env& env) { AMM amm(env, LP1, TST(25), XRP(250)); }, + [&](Env& env) { AMM const amm(env, LP1, TST(25), XRP(250)); }, [&](Env& env) { lp2TSTBalance = getAccountLines(env, LP2, TST)["lines"][0u]["balance"].asString(); auto const offer = getAccountOffers(env, LP2)["offers"][0u]; @@ -4767,7 +4705,7 @@ private: Account const ed("ed"); fund(env, gw, {alice, bob, carol, ed}, XRP(1'000), {USD(2'000), EUR(2'000)}); env(offer(carol, EUR(5), USD(5))); - AMM ammAlice(env, alice, USD(1'005), EUR(1'000)); + AMM const ammAlice(env, alice, USD(1'005), EUR(1'000)); env(pay(bob, ed, USD(10)), path(~USD), sendmax(EUR(15)), txflags(tfNoRippleDirect)); BEAST_EXPECT(expectHolding(env, ed, USD(2'010))); if (!features[fixAMMv1_1]) @@ -4795,7 +4733,7 @@ private: fund(env, gw, {alice, bob, carol, ed}, XRP(1'000), {USD(2'000), EUR(2'000)}); env(offer(carol, EUR(5), USD(5))); // Set 0.25% fee - AMM ammAlice(env, alice, USD(1'005), EUR(1'000), false, 250); + AMM const ammAlice(env, alice, USD(1'005), EUR(1'000), false, 250); env(pay(bob, ed, USD(10)), path(~USD), sendmax(EUR(15)), txflags(tfNoRippleDirect)); BEAST_EXPECT(expectHolding(env, ed, USD(2'010))); if (!features[fixAMMv1_1]) @@ -4828,7 +4766,7 @@ private: fund(env, gw, {alice, bob, carol, ed}, XRP(1'000), {USD(2'000), EUR(2'000)}); env(offer(carol, EUR(10), USD(10))); // Set 1% fee - AMM ammAlice(env, alice, USD(1'005), EUR(1'000), false, 1'000); + AMM const ammAlice(env, alice, USD(1'005), EUR(1'000), false, 1'000); env(pay(bob, ed, USD(10)), path(~USD), sendmax(EUR(15)), txflags(tfNoRippleDirect)); BEAST_EXPECT(expectHolding(env, ed, USD(2'010))); BEAST_EXPECT(expectHolding(env, bob, EUR(1'990))); @@ -4846,7 +4784,7 @@ private: fund(env, gw, {alice, bob, carol, ed}, XRP(1'000), {USD(2'000), EUR(2'000)}); env(offer(carol, EUR(9), USD(9))); // Set 1% fee - AMM ammAlice(env, alice, USD(1'005), EUR(1'000), false, 1'000); + AMM const ammAlice(env, alice, USD(1'005), EUR(1'000), false, 1'000); env(pay(bob, ed, USD(10)), path(~USD), sendmax(EUR(15)), txflags(tfNoRippleDirect)); BEAST_EXPECT(expectHolding(env, ed, USD(2'010))); BEAST_EXPECT(expectHolding(env, bob, STAmount{EUR, UINT64_C(1'989'993923296712), -12})); @@ -5187,7 +5125,7 @@ private: Env env(*this); env.fund(XRP(2'000), gw); env.fund(XRP(2'000), alice); - AMM amm(env, gw, XRP(1'000), USD(1'000)); + AMM const amm(env, gw, XRP(1'000), USD(1'000)); env(fset(gw, asfAllowTrustLineClawback), ter(tecOWNERS)); } @@ -5737,7 +5675,7 @@ private: auto const xrpIouAmounts10_100 = TAmounts{XRPAmount{10}, IOUAmount{100}}; auto const iouXrpAmounts10_100 = TAmounts{IOUAmount{10}, XRPAmount{100}}; // clang-format off - std::vector> tests = { + std::vector> const tests = { //Pool In , Pool Out, Quality , Fee, Status {"0.001519763260828713", "1558701", Quality{5414253689393440221}, 1000, FailShouldSucceed}, {"0.01099814367603737", "1892611", Quality{5482264816516900274}, 1000, FailShouldSucceed}, @@ -5797,14 +5735,14 @@ private: }; // clang-format on - boost::regex rx("^\\d+$"); + boost::regex const rx("^\\d+$"); boost::smatch match; // tests that succeed should have the same amounts pre-fix and post-fix - std::vector> successAmounts; - Env env(*this, features, std::make_unique(&logs)); + std::vector> const successAmounts; + Env const env(*this, features, std::make_unique(&logs)); auto rules = env.current()->rules(); - CurrentTransactionRulesGuard rg(rules); - NumberMantissaScaleGuard sg(MantissaRange::small); + CurrentTransactionRulesGuard const rg(rules); + NumberMantissaScaleGuard const sg(MantissaRange::small); for (auto const& t : tests) { @@ -5923,7 +5861,7 @@ private: using namespace jtx; testAMM([&](AMM& ammAlice, Env& env) { - WithdrawArg args{ + WithdrawArg const args{ .flags = tfSingleAsset, .err = ter(temMALFORMED), }; @@ -5931,7 +5869,7 @@ private: }); testAMM([&](AMM& ammAlice, Env& env) { - WithdrawArg args{ + WithdrawArg const args{ .flags = tfOneAssetLPToken, .err = ter(temMALFORMED), }; @@ -5939,7 +5877,7 @@ private: }); testAMM([&](AMM& ammAlice, Env& env) { - WithdrawArg args{ + WithdrawArg const args{ .flags = tfLimitLPToken, .err = ter(temMALFORMED), }; @@ -5947,7 +5885,7 @@ private: }); testAMM([&](AMM& ammAlice, Env& env) { - WithdrawArg args{ + WithdrawArg const args{ .asset1Out = XRP(100), .asset2Out = XRP(100), .err = ter(temBAD_AMM_TOKENS), @@ -5956,7 +5894,7 @@ private: }); testAMM([&](AMM& ammAlice, Env& env) { - WithdrawArg args{ + WithdrawArg const args{ .asset1Out = XRP(100), .asset2Out = BAD(100), .err = ter(temBAD_CURRENCY), @@ -6234,7 +6172,7 @@ private: env(pay(bitstamp, trader, usdBIT(100'000))); env.close(); - AMM amm{env, trader, usdGH(input.poolUsdGH), usdBIT(input.poolUsdBIT)}; + AMM const amm{env, trader, usdGH(input.poolUsdGH), usdBIT(input.poolUsdBIT)}; env.close(); IOUAmount const preSwapLPTokenBalance = amm.getLPTokensBalance(); @@ -6343,7 +6281,7 @@ private: env(offer(alice, XRP(1), USD(0.01))); env.close(); - AMM amm(env, gw, XRP(200'000), USD(100'000)); + AMM const amm(env, gw, XRP(200'000), USD(100'000)); // The offer doesn't cross AMM in pre-amendment code // It crosses AMM in post-amendment code @@ -6376,7 +6314,7 @@ private: // There is no blocking offer // env(offer(alice, XRP(1), USD(0.01))); - AMM amm(env, gw, XRP(200'000), USD(100'000)); + AMM const amm(env, gw, XRP(200'000), USD(100'000)); // The offer crosses AMM env(offer(carol, USD(0.49), XRP(1))); @@ -6398,7 +6336,7 @@ private: // It crosses AMM in post-amendment code env(offer(bob, USD(1), XRPAmount(500))); env.close(); - AMM amm(env, alice, XRP(1'000), USD(500)); + AMM const amm(env, alice, XRP(1'000), USD(500)); env(offer(carol, XRP(100), USD(55))); env.close(); if (!features[fixAMMv1_1]) @@ -6428,7 +6366,7 @@ private: Env env(*this, features); fund(env, gw, {alice, carol, bob}, XRP(10'000), {USD(1'000)}); - AMM amm(env, alice, XRP(1'000), USD(500)); + AMM const amm(env, alice, XRP(1'000), USD(500)); env(offer(carol, XRP(100), USD(55))); env.close(); BEAST_EXPECT(amm.expectBalances( @@ -6561,12 +6499,12 @@ private: // clawback-enabled issuer if (!features[featureAMMClawback]) { - AMM amm(env, gw, XRP(100), USD(100), ter(tecNO_PERMISSION)); - AMM amm1(env, alice, USD(100), XRP(100), ter(tecNO_PERMISSION)); + AMM const amm(env, gw, XRP(100), USD(100), ter(tecNO_PERMISSION)); + AMM const amm1(env, alice, USD(100), XRP(100), ter(tecNO_PERMISSION)); env(fclear(gw, asfAllowTrustLineClawback)); env.close(); // Can't be cleared - AMM amm2(env, gw, XRP(100), USD(100), ter(tecNO_PERMISSION)); + AMM const amm2(env, gw, XRP(100), USD(100), ter(tecNO_PERMISSION)); } // If featureAMMClawback is enabled, AMMCreate is allowed for // clawback-enabled issuer. Clawback from the AMM Account is not @@ -6575,8 +6513,8 @@ private: // AMMClawback transaction to claw back from AMM Account. else { - AMM amm(env, gw, XRP(100), USD(100), ter(tesSUCCESS)); - AMM amm1(env, alice, USD(100), XRP(200), ter(tecDUPLICATE)); + AMM const amm(env, gw, XRP(100), USD(100), ter(tesSUCCESS)); + AMM const amm1(env, alice, USD(100), XRP(200), ter(tecDUPLICATE)); // Construct the amount being clawed back using AMM account. // By doing this, we make the clawback transaction's Amount field's @@ -6588,7 +6526,7 @@ private: // is confusing. auto const error = features[featureSingleAssetVault] ? ter{tecPSEUDO_ACCOUNT} : ter{tecAMM_ACCOUNT}; - Issue usd(USD.issue().currency, amm.ammAccount()); + Issue const usd(USD.issue().currency, amm.ammAccount()); auto amount = amountFromString(usd, "10"); env(claw(gw, amount), error); } @@ -6712,8 +6650,8 @@ private: env(pay(gw, alice, USD(10'000))); env.close(); - STAmount amount = XRP(10'000); - STAmount amount2 = USD(10'000); + STAmount const amount = XRP(10'000); + STAmount const amount2 = USD(10'000); auto const keylet = keylet::amm(amount.issue(), amount2.issue()); for (int i = 0; i < 256; ++i) { @@ -6725,7 +6663,7 @@ private: sig(autofill)); } - AMM ammAlice( + AMM const ammAlice( env, alice, amount, @@ -6747,7 +6685,7 @@ private: STAmount xrpBalance{XRPAmount(692'614'492'126)}; STAmount xpmBalance{XPM, UINT64_C(18'610'359'80246901), -8}; STAmount amount{XPM, UINT64_C(6'566'496939465400), -12}; - std::uint16_t tfee = 941; + std::uint16_t const tfee = 941; auto test = [&](auto&& cb, std::uint16_t tfee_) { Env env(*this, features); @@ -6758,7 +6696,7 @@ private: AMM amm(env, gw, xrpBalance, xpmBalance, CreateArg{.tfee = tfee_}); // AMM LPToken balance required to replicate single deposit failure - STAmount lptAMMBalance{amm.lptIssue(), UINT64_C(3'234'987'266'485968), -6}; + STAmount const lptAMMBalance{amm.lptIssue(), UINT64_C(3'234'987'266'485968), -6}; auto const burn = IOUAmount{amm.getLPTokensBalance() - lptAMMBalance}; // burn tokens to get to the required AMM state env(amm.bid(BidArg{.account = gw, .bidMin = burn, .bidMax = burn})); @@ -6793,8 +6731,8 @@ private: { auto const [amount, amount2, lptBalance] = amm.balances(GBP, EUR); - NumberMantissaScaleGuard sg(MantissaRange::small); - NumberRoundModeGuard g(env.enabled(fixAMMv1_3) ? Number::upward : Number::getround()); + NumberMantissaScaleGuard const sg(MantissaRange::small); + NumberRoundModeGuard const g(env.enabled(fixAMMv1_3) ? Number::upward : Number::getround()); auto const res = root2(amount * amount2); if (shouldFail) diff --git a/src/test/app/AccountDelete_test.cpp b/src/test/app/AccountDelete_test.cpp index 91780800e9..4382fb27c7 100644 --- a/src/test/app/AccountDelete_test.cpp +++ b/src/test/app/AccountDelete_test.cpp @@ -452,7 +452,7 @@ public: // Verify the existence of the expected ledger entries. Keylet const aliceOwnerDirKey{keylet::ownerDir(alice.id())}; { - std::shared_ptr closed{env.closed()}; + std::shared_ptr const closed{env.closed()}; BEAST_EXPECT(closed->exists(keylet::account(alice.id()))); BEAST_EXPECT(closed->exists(aliceOwnerDirKey)); @@ -486,7 +486,7 @@ public: // Verify that alice's account root is gone as well as her directory // nodes and all of her offers. { - std::shared_ptr closed{env.closed()}; + std::shared_ptr const closed{env.closed()}; BEAST_EXPECT(!closed->exists(keylet::account(alice.id()))); BEAST_EXPECT(!closed->exists(aliceOwnerDirKey)); @@ -539,7 +539,7 @@ public: env(acctdelete(gw, alice), fee(acctDelFee), ter(tecHAS_OBLIGATIONS)); env.close(); { - std::shared_ptr closed{env.closed()}; + std::shared_ptr const closed{env.closed()}; BEAST_EXPECT(closed->exists(keylet::account(alice.id()))); BEAST_EXPECT(closed->exists(keylet::account(gw.id()))); } @@ -590,7 +590,7 @@ public: env(acctdelete(alice, env.master), fee(XRP(1)), ter(telINSUF_FEE_P)); env.close(); { - std::shared_ptr closed{env.closed()}; + std::shared_ptr const closed{env.closed()}; BEAST_EXPECT(closed->exists(keylet::account(alice.id()))); BEAST_EXPECT(env.balance(env.master) == masterBalance); } @@ -617,7 +617,7 @@ public: env.require(owners(bob, 250)); { - std::shared_ptr closed{env.closed()}; + std::shared_ptr const closed{env.closed()}; BEAST_EXPECT(closed->exists(keylet::account(bob.id()))); for (std::uint32_t i = 0; i < 250; ++i) { @@ -636,7 +636,7 @@ public: verifyDeliveredAmount(env, bobOldBalance - acctDelFee); env.close(); { - std::shared_ptr closed{env.closed()}; + std::shared_ptr const closed{env.closed()}; BEAST_EXPECT(!closed->exists(keylet::account(bob.id()))); for (std::uint32_t i = 0; i < 250; ++i) { diff --git a/src/test/app/AccountSet_test.cpp b/src/test/app/AccountSet_test.cpp index 748f276433..246f18c445 100644 --- a/src/test/app/AccountSet_test.cpp +++ b/src/test/app/AccountSet_test.cpp @@ -195,7 +195,7 @@ public: std::size_t const maxLength = 256; for (std::size_t len = maxLength - 1; len <= maxLength + 1; ++len) { - std::string domain2 = std::string(len - domain.length() - 1, 'a') + "." + domain; + std::string const domain2 = std::string(len - domain.length() - 1, 'a') + "." + domain; BEAST_EXPECT(domain2.length() == len); @@ -373,7 +373,7 @@ public: // // Two out-of-bound values are currently in the ledger (March 2020) // They are 4.0 and 4.294967295. So those are the values we test. - for (double transferRate : {4.0, 4.294967295}) + for (double const transferRate : {4.0, 4.294967295}) { Env env(*this); env.fund(XRP(10000), gw, alice, bob); diff --git a/src/test/app/AccountTxPaging_test.cpp b/src/test/app/AccountTxPaging_test.cpp index 09b517c37c..1f2e909927 100644 --- a/src/test/app/AccountTxPaging_test.cpp +++ b/src/test/app/AccountTxPaging_test.cpp @@ -47,9 +47,9 @@ class AccountTxPaging_test : public beast::unit_test::suite using namespace test::jtx; Env env(*this); - Account A1{"A1"}; - Account A2{"A2"}; - Account A3{"A3"}; + Account const A1{"A1"}; + Account const A2{"A2"}; + Account const A3{"A3"}; env.fund(XRP(10000), A1, A2, A3); env.close(); diff --git a/src/test/app/AmendmentTable_test.cpp b/src/test/app/AmendmentTable_test.cpp index 39e516304b..007715f9d1 100644 --- a/src/test/app/AmendmentTable_test.cpp +++ b/src/test/app/AmendmentTable_test.cpp @@ -1067,7 +1067,7 @@ public: // Since the local validator vote record expires after 24 hours, // with 23 hour flapping the amendment will go live. But with 25 // hour flapping the amendment will not go live. - for (int flapRateHours : {23, 25}) + for (int const flapRateHours : {23, 25}) { test::jtx::Env env{*this, feat}; auto const testAmendment = amendmentId("validatorFlapping"); diff --git a/src/test/app/Batch_test.cpp b/src/test/app/Batch_test.cpp index a548eb6b49..f301b6d60f 100644 --- a/src/test/app/Batch_test.cpp +++ b/src/test/app/Batch_test.cpp @@ -960,7 +960,7 @@ class Batch_test : public beast::unit_test::suite env.close(); { - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, }; validateClosedLedger(env, testCases); @@ -969,7 +969,7 @@ class Batch_test : public beast::unit_test::suite env.close(); { // next ledger is empty - std::vector testCases = {}; + std::vector const testCases = {}; validateClosedLedger(env, testCases); } @@ -1002,7 +1002,7 @@ class Batch_test : public beast::unit_test::suite env.close(); { - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, }; validateClosedLedger(env, testCases); @@ -1011,7 +1011,7 @@ class Batch_test : public beast::unit_test::suite env.close(); { // next ledger is empty - std::vector testCases = {}; + std::vector const testCases = {}; validateClosedLedger(env, testCases); } @@ -1044,7 +1044,7 @@ class Batch_test : public beast::unit_test::suite env.close(); { - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, }; validateClosedLedger(env, testCases); @@ -1053,7 +1053,7 @@ class Batch_test : public beast::unit_test::suite env.close(); { // next ledger is empty - std::vector testCases = {}; + std::vector const testCases = {}; validateClosedLedger(env, testCases); } @@ -1086,7 +1086,7 @@ class Batch_test : public beast::unit_test::suite env.close(); { - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, }; validateClosedLedger(env, testCases); @@ -1095,7 +1095,7 @@ class Batch_test : public beast::unit_test::suite env.close(); { // next ledger is empty - std::vector testCases = {}; + std::vector const testCases = {}; validateClosedLedger(env, testCases); } @@ -1128,7 +1128,7 @@ class Batch_test : public beast::unit_test::suite env.close(); { - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, }; validateClosedLedger(env, testCases); @@ -1137,7 +1137,7 @@ class Batch_test : public beast::unit_test::suite env.close(); { // next ledger is empty - std::vector testCases = {}; + std::vector const testCases = {}; validateClosedLedger(env, testCases); } @@ -1463,7 +1463,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(alice, bob, XRP(2)), seq + 2)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, @@ -1495,7 +1495,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(alice, bob, XRP(9999)), seq + 2)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, }; validateClosedLedger(env, testCases); @@ -1524,7 +1524,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(trust(alice, USD(1000), tfSetfAuth), seq + 2)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, }; validateClosedLedger(env, testCases); @@ -1553,7 +1553,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(trust(alice, USD(1000), tfSetfAuth), 0, seq + 2)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, }; validateClosedLedger(env, testCases); @@ -1605,7 +1605,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(alice, bob, XRP(9999)), seq + 3)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tecUNFUNDED_PAYMENT", txIDs[0], batchID}, {2, "Payment", "tecUNFUNDED_PAYMENT", txIDs[1], batchID}, @@ -1638,7 +1638,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(alice, bob, XRP(2)), seq + 3)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tecUNFUNDED_PAYMENT", txIDs[0], batchID}, {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, @@ -1670,7 +1670,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(alice, bob, XRP(2)), seq + 3)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, }; @@ -1701,7 +1701,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(alice, bob, XRP(2)), seq + 3)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tesSUCCESS", txIDs[1], batchID}, }; @@ -1732,7 +1732,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(alice, bob, XRP(2)), seq + 3)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tesSUCCESS", txIDs[1], batchID}, }; @@ -1769,7 +1769,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(alice, dave, XRP(100)), seq + 6)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "OfferCreate", "tecKILLED", txIDs[0], batchID}, {2, "OfferCreate", "tecKILLED", txIDs[1], batchID}, @@ -1821,7 +1821,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(alice, bob, XRP(3)), seq + 4)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tecUNFUNDED_PAYMENT", txIDs[0], batchID}, }; @@ -1852,7 +1852,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(alice, bob, XRP(4)), seq + 4)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, @@ -1887,7 +1887,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(alice, bob, XRP(3)), seq + 4)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, @@ -1921,7 +1921,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(alice, bob, XRP(3)), seq + 4)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, @@ -1954,7 +1954,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(alice, bob, XRP(3)), seq + 4)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, @@ -1987,7 +1987,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(alice, dave, XRP(100)), seq + 4)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, @@ -2038,7 +2038,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(alice, bob, XRP(3)), seq + 4)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, {2, "Payment", "tecUNFUNDED_PAYMENT", txIDs[1], batchID}, @@ -2073,7 +2073,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(alice, bob, XRP(3)), seq + 4)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, @@ -2108,7 +2108,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(alice, bob, XRP(3)), seq + 3)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, @@ -2142,7 +2142,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(alice, bob, XRP(3)), seq + 3)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, @@ -2175,7 +2175,7 @@ class Batch_test : public beast::unit_test::suite offer(alice, alice["USD"](100), XRP(100), tfImmediateOrCancel), seq + 3)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, @@ -2339,7 +2339,7 @@ class Batch_test : public beast::unit_test::suite // - has no `Signers` field // + has `tfInnerBatchTxn` flag { - STTx amendTx(ttAMENDMENT, [seq = env.closed()->header().seq + 1](auto& obj) { + STTx const amendTx(ttAMENDMENT, [seq = env.closed()->header().seq + 1](auto& obj) { obj.setAccountID(sfAccount, AccountID()); obj.setFieldH256(sfAmendment, fixBatchInnerSigs); obj.setFieldU32(sfLedgerSequence, seq); @@ -2397,7 +2397,7 @@ class Batch_test : public beast::unit_test::suite batch::sig(bob)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, {2, "AccountSet", "tesSUCCESS", txIDs[1], batchID}, @@ -2446,7 +2446,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(alice, bob, XRP(1)), seq + 2)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "AccountSet", "tesSUCCESS", txIDs[0], batchID}, {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, @@ -2501,7 +2501,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(alice, bob, XRP(2)), seq + 3)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, {2, "AccountDelete", "tesSUCCESS", txIDs[1], batchID}, @@ -2544,7 +2544,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(alice, bob, XRP(2)), seq + 3)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, {2, "AccountDelete", "tecHAS_OBLIGATIONS", txIDs[1], batchID}, @@ -2585,7 +2585,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(alice, bob, XRP(2)), seq + 3)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, }; validateClosedLedger(env, testCases); @@ -2626,7 +2626,7 @@ class Batch_test : public beast::unit_test::suite // Just use an XRP asset PrettyAsset const asset{xrpIssue(), 1'000'000}; - Vault vault{env}; + Vault const vault{env}; auto const deposit = asset(50'000); auto const debtMaximumValue = asset(25'000).value(); @@ -2821,7 +2821,7 @@ class Batch_test : public beast::unit_test::suite batch::sig(bob)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "CheckCreate", "tesSUCCESS", txIDs[0], batchID}, {2, "CheckCash", "tesSUCCESS", txIDs[1], batchID}, @@ -2867,7 +2867,7 @@ class Batch_test : public beast::unit_test::suite batch::sig(bob)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "CheckCreate", "tecDST_TAG_NEEDED", txIDs[0], batchID}, {2, "CheckCash", "tecNO_ENTRY", txIDs[1], batchID}, @@ -2932,7 +2932,7 @@ class Batch_test : public beast::unit_test::suite batch::sig(bob)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "TicketCreate", "tesSUCCESS", txIDs[0], batchID}, {2, "CheckCreate", "tesSUCCESS", txIDs[1], batchID}, @@ -2992,7 +2992,7 @@ class Batch_test : public beast::unit_test::suite batch::sig(alice, bob)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "CheckCreate", "tesSUCCESS", txIDs[0], batchID}, {2, "CheckCash", "tesSUCCESS", txIDs[1], batchID}, @@ -3026,7 +3026,7 @@ class Batch_test : public beast::unit_test::suite env.fund(XRP(10000), alice, bob); env.close(); - std::uint32_t aliceTicketSeq{env.seq(alice) + 1}; + std::uint32_t const aliceTicketSeq{env.seq(alice) + 1}; env(ticket::create(alice, 10)); env.close(); @@ -3044,7 +3044,7 @@ class Batch_test : public beast::unit_test::suite ticket::use(aliceTicketSeq)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, @@ -3092,7 +3092,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(alice, bob, XRP(2)), 0, aliceTicketSeq + 1)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, @@ -3123,7 +3123,7 @@ class Batch_test : public beast::unit_test::suite env.fund(XRP(10000), alice, bob); env.close(); - std::uint32_t aliceTicketSeq{env.seq(alice) + 1}; + std::uint32_t const aliceTicketSeq{env.seq(alice) + 1}; env(ticket::create(alice, 10)); env.close(); @@ -3141,7 +3141,7 @@ class Batch_test : public beast::unit_test::suite ticket::use(aliceTicketSeq)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, @@ -3202,7 +3202,7 @@ class Batch_test : public beast::unit_test::suite env.close(); { - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, @@ -3213,7 +3213,7 @@ class Batch_test : public beast::unit_test::suite env.close(); { // next ledger contains noop txn - std::vector testCases = { + std::vector const testCases = { {0, "AccountSet", "tesSUCCESS", noopTxnID, std::nullopt}, }; validateClosedLedger(env, testCases); @@ -3246,7 +3246,7 @@ class Batch_test : public beast::unit_test::suite env.close(); { - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, @@ -3257,7 +3257,7 @@ class Batch_test : public beast::unit_test::suite env.close(); { // next ledger is empty - std::vector testCases = {}; + std::vector const testCases = {}; validateClosedLedger(env, testCases); } } @@ -3285,7 +3285,7 @@ class Batch_test : public beast::unit_test::suite env.close(); { - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, @@ -3296,7 +3296,7 @@ class Batch_test : public beast::unit_test::suite env.close(); { // next ledger is empty - std::vector testCases = {}; + std::vector const testCases = {}; validateClosedLedger(env, testCases); } } @@ -3327,7 +3327,7 @@ class Batch_test : public beast::unit_test::suite env.close(); { - std::vector testCases = { + std::vector const testCases = { {0, "AccountSet", "tesSUCCESS", noopTxnID, std::nullopt}, {1, "Batch", "tesSUCCESS", batchID, std::nullopt}, {2, "Payment", "tesSUCCESS", txIDs[0], batchID}, @@ -3339,7 +3339,7 @@ class Batch_test : public beast::unit_test::suite env.close(); { // next ledger contains no transactions - std::vector testCases = {}; + std::vector const testCases = {}; validateClosedLedger(env, testCases); } } @@ -3365,7 +3365,7 @@ class Batch_test : public beast::unit_test::suite env.fund(XRP(10000), alice, bob); env.close(); - std::uint32_t aliceTicketSeq{env.seq(alice) + 1}; + std::uint32_t const aliceTicketSeq{env.seq(alice) + 1}; env(ticket::create(alice, 10)); env.close(); @@ -3387,7 +3387,7 @@ class Batch_test : public beast::unit_test::suite env.close(); { - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, @@ -3398,7 +3398,7 @@ class Batch_test : public beast::unit_test::suite env.close(); { // next ledger is empty - std::vector testCases = {}; + std::vector const testCases = {}; validateClosedLedger(env, testCases); } } @@ -3412,7 +3412,7 @@ class Batch_test : public beast::unit_test::suite env.fund(XRP(10000), alice, bob); env.close(); - std::uint32_t aliceTicketSeq{env.seq(alice) + 1}; + std::uint32_t const aliceTicketSeq{env.seq(alice) + 1}; env(ticket::create(alice, 10)); env.close(); @@ -3434,7 +3434,7 @@ class Batch_test : public beast::unit_test::suite env.close(); { - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, @@ -3445,7 +3445,7 @@ class Batch_test : public beast::unit_test::suite env.close(); { // next ledger is empty - std::vector testCases = {}; + std::vector const testCases = {}; validateClosedLedger(env, testCases); } } @@ -3473,7 +3473,7 @@ class Batch_test : public beast::unit_test::suite env.fund(XRP(10000), alice, bob); env.close(); - std::uint32_t aliceTicketSeq{env.seq(alice) + 1}; + std::uint32_t const aliceTicketSeq{env.seq(alice) + 1}; env(ticket::create(alice, 10)); env.close(); @@ -3497,7 +3497,7 @@ class Batch_test : public beast::unit_test::suite env.close(); { - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "CheckCreate", "tesSUCCESS", txIDs[0], batchID}, {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, @@ -3509,7 +3509,7 @@ class Batch_test : public beast::unit_test::suite env.close(); { // next ledger is empty - std::vector testCases = {}; + std::vector const testCases = {}; validateClosedLedger(env, testCases); } } @@ -3520,7 +3520,7 @@ class Batch_test : public beast::unit_test::suite env.fund(XRP(10000), alice, bob); env.close(); - std::uint32_t aliceTicketSeq{env.seq(alice) + 1}; + std::uint32_t const aliceTicketSeq{env.seq(alice) + 1}; env(ticket::create(alice, 10)); env.close(); @@ -3546,7 +3546,7 @@ class Batch_test : public beast::unit_test::suite env.close(); { - std::vector testCases = { + std::vector const testCases = { {0, "CheckCreate", "tesSUCCESS", objTxnID, std::nullopt}, {1, "Batch", "tesSUCCESS", batchID, std::nullopt}, {2, "CheckCash", "tesSUCCESS", txIDs[0], batchID}, @@ -3567,7 +3567,7 @@ class Batch_test : public beast::unit_test::suite env.fund(XRP(10000), alice, bob); env.close(); - std::uint32_t aliceTicketSeq{env.seq(alice) + 1}; + std::uint32_t const aliceTicketSeq{env.seq(alice) + 1}; env(ticket::create(alice, 10)); env.close(); @@ -3591,7 +3591,7 @@ class Batch_test : public beast::unit_test::suite env.close(); { - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "CheckCreate", "tesSUCCESS", txIDs[0], batchID}, {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, @@ -3687,7 +3687,7 @@ class Batch_test : public beast::unit_test::suite env(payTxn2, ter(terPRE_SEQ)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Payment", "tesSUCCESS", payTxn1ID, std::nullopt}, {1, "Batch", "tesSUCCESS", batchID, std::nullopt}, {2, "Payment", "tesSUCCESS", txIDs[0], batchID}, @@ -3698,7 +3698,7 @@ class Batch_test : public beast::unit_test::suite env.close(); { // next ledger includes the payment txn - std::vector testCases = { + std::vector const testCases = { {0, "Payment", "tesSUCCESS", payTxn2ID, std::nullopt}, }; validateClosedLedger(env, testCases); @@ -3910,7 +3910,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(alice, bob, XRP(2)), seq + 2)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, @@ -3959,7 +3959,7 @@ class Batch_test : public beast::unit_test::suite batch::sig(bob)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "Payment", "tesSUCCESS", txIDs[0], batchID}, {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, @@ -4009,7 +4009,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(alice, bob, XRP(2)), seq + 2)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "AccountSet", "tesSUCCESS", txIDs[0], batchID}, {2, "Payment", "tesSUCCESS", txIDs[1], batchID}, @@ -4029,8 +4029,8 @@ class Batch_test : public beast::unit_test::suite // MPTokenIssuanceSet with granular permission { test::jtx::Env env{*this, features}; - Account alice{"alice"}; - Account bob{"bob"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(100000), alice, bob); env.close(); @@ -4071,7 +4071,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(jv2, seq + 2)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "MPTokenIssuanceSet", "tesSUCCESS", txIDs[0], batchID}, {2, "MPTokenIssuanceSet", "tesSUCCESS", txIDs[1], batchID}, @@ -4084,9 +4084,9 @@ class Batch_test : public beast::unit_test::suite // with granular permission { test::jtx::Env env{*this, features}; - Account gw{"gw"}; - Account alice{"alice"}; - Account bob{"bob"}; + Account const gw{"gw"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(10000), gw, alice, bob); env(fset(gw, asfRequireAuth)); env.close(); @@ -4112,7 +4112,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(jv2, seq + 2)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "TrustSet", "tesSUCCESS", txIDs[0], batchID}, {2, "TrustSet", "tesSUCCESS", txIDs[1], batchID}, @@ -4123,9 +4123,9 @@ class Batch_test : public beast::unit_test::suite // inner transaction not authorized by the delegating account. { test::jtx::Env env{*this, features}; - Account gw{"gw"}; - Account alice{"alice"}; - Account bob{"bob"}; + Account const gw{"gw"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(10000), gw, alice, bob); env(fset(gw, asfRequireAuth)); env.close(); @@ -4152,7 +4152,7 @@ class Batch_test : public beast::unit_test::suite batch::inner(jv2, seq + 2)); env.close(); - std::vector testCases = { + std::vector const testCases = { {0, "Batch", "tesSUCCESS", batchID, std::nullopt}, {1, "TrustSet", "tesSUCCESS", txIDs[0], batchID}, }; diff --git a/src/test/app/Check_test.cpp b/src/test/app/Check_test.cpp index 671f8aab1a..1e5d90f650 100644 --- a/src/test/app/Check_test.cpp +++ b/src/test/app/Check_test.cpp @@ -1880,7 +1880,7 @@ class Check_test : public beast::unit_test::suite // Automatic trust line creation should fail if the check destination // can't afford the reserve for the trust line. { - AccountOwns gw1{*this, env, "gw1", 0}; + AccountOwns const gw1{*this, env, "gw1", 0}; // Fund gw1 with noripple (even though that's atypical for a // gateway) so it does not have any flags set. We'll set flags @@ -2000,7 +2000,7 @@ class Check_test : public beast::unit_test::suite { // No account root flags on any participant. // Automatic trust line from issuer to destination. - AccountOwns gw1{*this, env, "gw1", 0}; + AccountOwns const gw1{*this, env, "gw1", 0}; BEAST_EXPECT((*env.le(gw1))[sfFlags] == 0); BEAST_EXPECT((*env.le(alice))[sfFlags] == 0); @@ -2053,7 +2053,7 @@ class Check_test : public beast::unit_test::suite // Transfer of assets using offers does not require rippling. // So bob's offer is successfully crossed which creates the // trust line. - AccountOwns gw1{*this, env, "gw1", 0}; + AccountOwns const gw1{*this, env, "gw1", 0}; IOU const OF1 = gw1["OF1"]; env(offer(alice, XRP(97), OF1(97))); env.close(); @@ -2102,7 +2102,7 @@ class Check_test : public beast::unit_test::suite { // gw1 enables rippling. // Automatic trust line from issuer to non-issuer should still work. - AccountOwns gw1{*this, env, "gw1", 0}; + AccountOwns const gw1{*this, env, "gw1", 0}; env(fset(gw1, asfDefaultRipple)); env.close(); @@ -2150,7 +2150,7 @@ class Check_test : public beast::unit_test::suite // to non-issuer should work. // Use offers to automatically create the trust line. - AccountOwns gw1{*this, env, "gw1", 0}; + AccountOwns const gw1{*this, env, "gw1", 0}; IOU const OF2 = gw1["OF2"]; env(offer(alice, XRP(95), OF2(95))); env.close(); @@ -2191,7 +2191,7 @@ class Check_test : public beast::unit_test::suite // change any outcomes. // // Automatic trust line from issuer to non-issuer should still work. - AccountOwns gw1{*this, env, "gw1", 0}; + AccountOwns const gw1{*this, env, "gw1", 0}; env(fset(gw1, asfDepositAuth)); env(fset(alice, asfDepositAuth)); env(fset(bob, asfDepositAuth)); @@ -2241,7 +2241,7 @@ class Check_test : public beast::unit_test::suite // automatic trust line creation. // Use offers to automatically create the trust line. - AccountOwns gw1{*this, env, "gw1", 0}; + AccountOwns const gw1{*this, env, "gw1", 0}; IOU const OF3 = gw1["OF3"]; env(offer(alice, XRP(93), OF3(93))); env.close(); @@ -2278,7 +2278,7 @@ class Check_test : public beast::unit_test::suite { // Set lsfGlobalFreeze on gw1. That should stop any automatic // trust lines from being created. - AccountOwns gw1{*this, env, "gw1", 0}; + AccountOwns const gw1{*this, env, "gw1", 0}; env(fset(gw1, asfGlobalFreeze)); env.close(); @@ -2320,7 +2320,7 @@ class Check_test : public beast::unit_test::suite // no automatic trust line creation between non-issuers. // Use offers to automatically create the trust line. - AccountOwns gw1{*this, env, "gw1", 0}; + AccountOwns const gw1{*this, env, "gw1", 0}; IOU const OF4 = gw1["OF4"]; env(offer(alice, XRP(91), OF4(91)), ter(tecFROZEN)); env.close(); @@ -2370,7 +2370,7 @@ class Check_test : public beast::unit_test::suite // Use offers to automatically create the trust line. IOU const OF5 = gw2["OF5"]; - std::uint32_t gw2OfferSeq = {env.seq(gw2)}; + std::uint32_t const gw2OfferSeq = {env.seq(gw2)}; env(offer(gw2, XRP(92), OF5(92))); ++gw2.owners; env.close(); @@ -2423,7 +2423,7 @@ class Check_test : public beast::unit_test::suite // no automatic trust line creation between non-issuers. // Use offers to automatically create the trust line. - AccountOwns gw2{*this, env, "gw2", 0}; + AccountOwns const gw2{*this, env, "gw2", 0}; IOU const OF5 = gw2["OF5"]; env(offer(alice, XRP(91), OF5(91)), ter(tecUNFUNDED_OFFER)); env.close(); diff --git a/src/test/app/Clawback_test.cpp b/src/test/app/Clawback_test.cpp index d169e9e165..902acf3222 100644 --- a/src/test/app/Clawback_test.cpp +++ b/src/test/app/Clawback_test.cpp @@ -52,7 +52,7 @@ class Clawback_test : public beast::unit_test::suite // Also, asfAllowTrustLineClawback cannot be cleared. { Env env(*this, features); - Account alice{"alice"}; + Account const alice{"alice"}; env.fund(XRP(1000), alice); env.close(); @@ -77,7 +77,7 @@ class Clawback_test : public beast::unit_test::suite // asfNoFreeze has been set { Env env(*this, features); - Account alice{"alice"}; + Account const alice{"alice"}; env.fund(XRP(1000), alice); env.close(); @@ -103,8 +103,8 @@ class Clawback_test : public beast::unit_test::suite { Env env(*this, features); - Account alice{"alice"}; - Account bob{"bob"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(1000), alice, bob); env.close(); @@ -146,7 +146,7 @@ class Clawback_test : public beast::unit_test::suite { Env env(*this, features - featureClawback); - Account alice{"alice"}; + Account const alice{"alice"}; env.fund(XRP(1000), alice); env.close(); @@ -183,8 +183,8 @@ class Clawback_test : public beast::unit_test::suite { Env env(*this, features - featureClawback); - Account alice{"alice"}; - Account bob{"bob"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(1000), alice, bob); env.close(); @@ -228,8 +228,8 @@ class Clawback_test : public beast::unit_test::suite { Env env(*this, features); - Account alice{"alice"}; - Account bob{"bob"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(1000), alice, bob); env.close(); @@ -310,8 +310,8 @@ class Clawback_test : public beast::unit_test::suite { Env env(*this, features); - Account alice{"alice"}; - Account bob{"bob"}; + Account const alice{"alice"}; + Account const bob{"bob"}; // bob's account is not funded and does not exist env.fund(XRP(1000), alice); @@ -332,9 +332,9 @@ class Clawback_test : public beast::unit_test::suite { Env env(*this, features); - Account alice{"alice"}; - Account bob{"bob"}; - Account cindy{"cindy"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + Account const cindy{"cindy"}; env.fund(XRP(1000), alice, bob, cindy); env.close(); @@ -375,8 +375,8 @@ class Clawback_test : public beast::unit_test::suite { Env env(*this, features); - Account alice{"alice"}; - Account bob{"bob"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(1000), alice, bob); env.close(); @@ -445,8 +445,8 @@ class Clawback_test : public beast::unit_test::suite // Test that alice is able to successfully clawback tokens from bob Env env(*this, features); - Account alice{"alice"}; - Account bob{"bob"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(1000), alice, bob); env.close(); @@ -496,9 +496,9 @@ class Clawback_test : public beast::unit_test::suite { Env env(*this, features); - Account alice{"alice"}; - Account bob{"bob"}; - Account cindy{"cindy"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + Account const cindy{"cindy"}; env.fund(XRP(1000), alice, bob, cindy); env.close(); @@ -554,9 +554,9 @@ class Clawback_test : public beast::unit_test::suite { Env env(*this, features); - Account alice{"alice"}; - Account bob{"bob"}; - Account cindy{"cindy"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + Account const cindy{"cindy"}; env.fund(XRP(1000), alice, bob, cindy); env.close(); @@ -624,8 +624,8 @@ class Clawback_test : public beast::unit_test::suite // perspective is allowed to clawback Env env(*this, features); - Account alice{"alice"}; - Account bob{"bob"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(1000), alice, bob); env.close(); @@ -711,8 +711,8 @@ class Clawback_test : public beast::unit_test::suite // If clawback results the trustline to be default, // trustline should be automatically deleted Env env(*this, features); - Account alice{"alice"}; - Account bob{"bob"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(1000), alice, bob); env.close(); @@ -761,8 +761,8 @@ class Clawback_test : public beast::unit_test::suite // Claws back from frozen trustline // and the trustline should remain frozen Env env(*this, features); - Account alice{"alice"}; - Account bob{"bob"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(1000), alice, bob); env.close(); @@ -807,8 +807,8 @@ class Clawback_test : public beast::unit_test::suite // When alice tries to claw back an amount that is greater // than what bob holds, only the max available balance is clawed Env env(*this, features); - Account alice{"alice"}; - Account bob{"bob"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(1000), alice, bob); env.close(); @@ -859,8 +859,8 @@ class Clawback_test : public beast::unit_test::suite // Tests clawback with tickets Env env(*this, features); - Account alice{"alice"}; - Account bob{"bob"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(1000), alice, bob); env.close(); diff --git a/src/test/app/DNS_test.cpp b/src/test/app/DNS_test.cpp index 9b75e66b85..2273a77e09 100644 --- a/src/test/app/DNS_test.cpp +++ b/src/test/app/DNS_test.cpp @@ -62,7 +62,7 @@ public: { using boost::asio::ip::tcp; tcp::resolver resolver(env_.app().getIOContext()); - std::string port = pUrl_.port ? std::to_string(*pUrl_.port) : "443"; + std::string const port = pUrl_.port ? std::to_string(*pUrl_.port) : "443"; auto results = resolver.resolve(pUrl_.domain, port); auto it = results.begin(); auto end = results.end(); diff --git a/src/test/app/Delegate_test.cpp b/src/test/app/Delegate_test.cpp index 2618a95d0d..3f6d5e6b47 100644 --- a/src/test/app/Delegate_test.cpp +++ b/src/test/app/Delegate_test.cpp @@ -16,9 +16,9 @@ class Delegate_test : public beast::unit_test::suite using namespace jtx; Env env{*this, features}; - Account gw{"gateway"}; - Account alice{"alice"}; - Account bob{"bob"}; + Account const gw{"gateway"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(1000000), gw, alice, bob); env.close(); @@ -39,8 +39,8 @@ class Delegate_test : public beast::unit_test::suite using namespace jtx; Env env(*this); - Account gw{"gateway"}; - Account alice{"alice"}; + Account const gw{"gateway"}; + Account const alice{"alice"}; env.fund(XRP(100000), gw, alice); env.close(); @@ -112,9 +112,9 @@ class Delegate_test : public beast::unit_test::suite using namespace jtx; Env env(*this, features); - Account gw{"gateway"}; - Account alice{"alice"}; - Account bob{"bob"}; + Account const gw{"gateway"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(100000), gw, alice, bob); env.close(); @@ -203,8 +203,8 @@ class Delegate_test : public beast::unit_test::suite // reserve requirement not met { Env env(*this); - Account alice{"alice"}; - Account bob{"bob"}; + Account const alice{"alice"}; + Account const bob{"bob"}; auto const txFee = env.current()->fees().base; env.fund(env.current()->fees().accountReserve(0) + txFee, alice); @@ -218,9 +218,9 @@ class Delegate_test : public beast::unit_test::suite // reserve recovered after deleting delegation object { Env env(*this); - Account bob{"bob"}; - Account alice{"alice"}; - Account carol{"carol"}; + Account const bob{"bob"}; + Account const alice{"alice"}; + Account const carol{"carol"}; auto const txFee = env.current()->fees().base; @@ -247,8 +247,8 @@ class Delegate_test : public beast::unit_test::suite // test reserve when sending transaction on behalf of other account { Env env(*this); - Account alice{"alice"}; - Account bob{"bob"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(drops(env.current()->fees().accountReserve(1)), alice); env.fund(drops(env.current()->fees().accountReserve(2)), bob); @@ -275,9 +275,9 @@ class Delegate_test : public beast::unit_test::suite using namespace jtx; Env env(*this); - Account alice{"alice"}; - Account bob{"bob"}; - Account carol{"carol"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + Account const carol{"carol"}; env.fund(XRP(10000), alice, carol); env.fund(XRP(1000), bob); env.close(); @@ -357,9 +357,9 @@ class Delegate_test : public beast::unit_test::suite using namespace jtx; Env env(*this); - Account alice{"alice"}; - Account bob{"bob"}; - Account carol{"carol"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + Account const carol{"carol"}; env.fund(XRP(10000), alice, bob, carol); env.close(); @@ -410,8 +410,8 @@ class Delegate_test : public beast::unit_test::suite using namespace jtx; Env env(*this); - Account alice{"alice"}; - Account bob{"bob"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(100000), alice, bob); env.close(); @@ -444,9 +444,9 @@ class Delegate_test : public beast::unit_test::suite using namespace jtx; Env env(*this); - Account alice{"alice"}; - Account bob{"bob"}; - Account carol{"carol"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + Account const carol{"carol"}; XRPAmount const baseFee{env.current()->fees().base}; @@ -510,10 +510,10 @@ class Delegate_test : public beast::unit_test::suite // test PaymentMint and PaymentBurn { Env env(*this); - Account alice{"alice"}; - Account bob{"bob"}; - Account gw{"gateway"}; - Account gw2{"gateway2"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + Account const gw{"gateway"}; + Account const gw2{"gateway2"}; auto const USD = gw["USD"]; auto const EUR = gw2["EUR"]; @@ -615,9 +615,9 @@ class Delegate_test : public beast::unit_test::suite // test PaymentMint won't affect Payment transaction level delegation. { Env env(*this); - Account alice{"alice"}; - Account bob{"bob"}; - Account gw{"gateway"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + Account const gw{"gateway"}; auto const USD = gw["USD"]; env.fund(XRP(10000), alice); @@ -805,9 +805,9 @@ class Delegate_test : public beast::unit_test::suite // test TrustlineUnfreeze, TrustlineFreeze and TrustlineAuthorize { Env env(*this); - Account gw{"gw"}; - Account alice{"alice"}; - Account bob{"bob"}; + Account const gw{"gw"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(10000), gw, alice, bob); env(fset(gw, asfRequireAuth)); env.close(); @@ -917,9 +917,9 @@ class Delegate_test : public beast::unit_test::suite // test mix of transaction level delegation and granular delegation { Env env(*this); - Account gw{"gw"}; - Account alice{"alice"}; - Account bob{"bob"}; + Account const gw{"gw"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(10000), gw, alice, bob); env(fset(gw, asfRequireAuth)); env.close(); @@ -962,9 +962,9 @@ class Delegate_test : public beast::unit_test::suite // tfFullyCanonicalSig won't block delegated transaction { Env env(*this); - Account gw{"gw"}; - Account alice{"alice"}; - Account bob{"bob"}; + Account const gw{"gw"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(10000), gw, alice, bob); env(fset(gw, asfRequireAuth)); env.close(); @@ -1210,8 +1210,8 @@ class Delegate_test : public beast::unit_test::suite // tfFullyCanonicalSig won't block delegated transaction { Env env(*this); - Account alice{"alice"}; - Account bob{"bob"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(10000), alice, bob); env.close(); @@ -1356,9 +1356,9 @@ class Delegate_test : public beast::unit_test::suite using namespace jtx; Env env(*this); - Account alice{"alice"}; - Account bob{"bob"}; - Account carol{"carol"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + Account const carol{"carol"}; env.fund(XRP(100000), alice, bob, carol); env.close(); @@ -1384,9 +1384,9 @@ class Delegate_test : public beast::unit_test::suite { Env env(*this); - Account alice{"alice"}; - Account bob{"bob"}; - Account carol{"carol"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + Account const carol{"carol"}; env.fund(XRP(100000), alice, bob, carol); env.close(); @@ -1410,7 +1410,11 @@ class Delegate_test : public beast::unit_test::suite { Env env(*this); - Account alice{"alice"}, bob{"bob"}, carol{"carol"}; + + Account const alice{"alice"}; + Account const bob{"bob"}; + Account const carol{"carol"}; + env.fund(XRP(100000), alice, bob, carol); env.close(); @@ -1444,7 +1448,11 @@ class Delegate_test : public beast::unit_test::suite { Env env(*this); - Account alice{"alice"}, bob{"bob"}, carol{"carol"}; + + Account const alice{"alice"}; + Account const bob{"bob"}; + Account const carol{"carol"}; + env.fund(XRP(100000), alice, bob, carol); env.close(); @@ -1481,9 +1489,9 @@ class Delegate_test : public beast::unit_test::suite using namespace jtx; Env env(*this); - Account alice{"alice"}; - Account bob{"bob"}; - Account carol{"carol"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + Account const carol{"carol"}; Account daria{"daria"}; Account edward{"edward"}; env.fund(XRP(100000), alice, bob, carol, daria, edward); @@ -1517,9 +1525,9 @@ class Delegate_test : public beast::unit_test::suite using namespace jtx; Env env(*this); - Account alice{"alice"}; - Account bob{"bob"}; - Account carol{"carol"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + Account const carol{"carol"}; Account daria = Account{"daria"}; Account edward = Account{"edward"}; Account fred = Account{"fred"}; diff --git a/src/test/app/Discrepancy_test.cpp b/src/test/app/Discrepancy_test.cpp index 3f808b37d8..d8c14df64e 100644 --- a/src/test/app/Discrepancy_test.cpp +++ b/src/test/app/Discrepancy_test.cpp @@ -24,13 +24,13 @@ class Discrepancy_test : public beast::unit_test::suite using namespace test::jtx; Env env{*this, features}; - Account A1{"A1"}; - Account A2{"A2"}; - Account A3{"A3"}; - Account A4{"A4"}; - Account A5{"A5"}; - Account A6{"A6"}; - Account A7{"A7"}; + Account const A1{"A1"}; + Account const A2{"A2"}; + Account const A3{"A3"}; + Account const A4{"A4"}; + Account const A5{"A5"}; + Account const A6{"A6"}; + Account const A7{"A7"}; env.fund(XRP(2000), A1); env.fund(XRP(1000), A2, A6, A7); @@ -68,7 +68,7 @@ class Discrepancy_test : public beast::unit_test::suite env(offer(A7, XRP(1233), A6["CNY"](25))); env.close(); - test::PathSet payPaths{ + test::PathSet const payPaths{ test::Path{A2["JPY"], A2}, test::Path{XRP, A2["JPY"], A2}, test::Path{A6, XRP, A2["JPY"], A2}}; @@ -84,7 +84,7 @@ class Discrepancy_test : public beast::unit_test::suite jrq2[jss::transaction] = env.tx()->getJson(JsonOptions::none)[jss::hash]; jrq2[jss::id] = 3; auto jrr = env.rpc("json", "tx", to_string(jrq2))[jss::result]; - uint64_t fee{jrr[jss::Fee].asUInt()}; + uint64_t const fee{jrr[jss::Fee].asUInt()}; auto meta = jrr[jss::meta]; uint64_t sumPrev{0}; uint64_t sumFinal{0}; diff --git a/src/test/app/EscrowToken_test.cpp b/src/test/app/EscrowToken_test.cpp index 619b584ddb..6e08c3eddf 100644 --- a/src/test/app/EscrowToken_test.cpp +++ b/src/test/app/EscrowToken_test.cpp @@ -983,13 +983,13 @@ struct EscrowToken_test : public beast::unit_test::suite auto const aa = env.le(keylet::escrow(alice.id(), aseq)); BEAST_EXPECT(aa); { - xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); + xrpl::Dir const aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 2); BEAST_EXPECT(std::find(aod.begin(), aod.end(), aa) != aod.end()); } { - xrpl::Dir iod(*env.current(), keylet::ownerDir(gw.id())); + xrpl::Dir const iod(*env.current(), keylet::ownerDir(gw.id())); BEAST_EXPECT(std::distance(iod.begin(), iod.end()) == 4); BEAST_EXPECT(std::find(iod.begin(), iod.end(), aa) != iod.end()); } @@ -1004,13 +1004,13 @@ struct EscrowToken_test : public beast::unit_test::suite BEAST_EXPECT(bb); { - xrpl::Dir bod(*env.current(), keylet::ownerDir(bob.id())); + xrpl::Dir const bod(*env.current(), keylet::ownerDir(bob.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 2); BEAST_EXPECT(std::find(bod.begin(), bod.end(), bb) != bod.end()); } { - xrpl::Dir iod(*env.current(), keylet::ownerDir(gw.id())); + xrpl::Dir const iod(*env.current(), keylet::ownerDir(gw.id())); BEAST_EXPECT(std::distance(iod.begin(), iod.end()) == 5); BEAST_EXPECT(std::find(iod.begin(), iod.end(), bb) != iod.end()); } @@ -1022,15 +1022,15 @@ struct EscrowToken_test : public beast::unit_test::suite BEAST_EXPECT( (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); - xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); + xrpl::Dir const aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 1); BEAST_EXPECT(std::find(aod.begin(), aod.end(), aa) == aod.end()); - xrpl::Dir bod(*env.current(), keylet::ownerDir(bob.id())); + xrpl::Dir const bod(*env.current(), keylet::ownerDir(bob.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 2); BEAST_EXPECT(std::find(bod.begin(), bod.end(), bb) != bod.end()); - xrpl::Dir iod(*env.current(), keylet::ownerDir(gw.id())); + xrpl::Dir const iod(*env.current(), keylet::ownerDir(gw.id())); BEAST_EXPECT(std::distance(iod.begin(), iod.end()) == 4); BEAST_EXPECT(std::find(iod.begin(), iod.end(), bb) != iod.end()); } @@ -1042,11 +1042,11 @@ struct EscrowToken_test : public beast::unit_test::suite BEAST_EXPECT( (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); - xrpl::Dir bod(*env.current(), keylet::ownerDir(bob.id())); + xrpl::Dir const bod(*env.current(), keylet::ownerDir(bob.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 1); BEAST_EXPECT(std::find(bod.begin(), bod.end(), bb) == bod.end()); - xrpl::Dir iod(*env.current(), keylet::ownerDir(gw.id())); + xrpl::Dir const iod(*env.current(), keylet::ownerDir(gw.id())); BEAST_EXPECT(std::distance(iod.begin(), iod.end()) == 3); BEAST_EXPECT(std::find(iod.begin(), iod.end(), bb) == iod.end()); } @@ -1085,20 +1085,20 @@ struct EscrowToken_test : public beast::unit_test::suite BEAST_EXPECT(bc); { - xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); + xrpl::Dir const aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 2); BEAST_EXPECT(std::find(aod.begin(), aod.end(), ab) != aod.end()); - xrpl::Dir bod(*env.current(), keylet::ownerDir(bob.id())); + xrpl::Dir const bod(*env.current(), keylet::ownerDir(bob.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 3); BEAST_EXPECT(std::find(bod.begin(), bod.end(), ab) != bod.end()); BEAST_EXPECT(std::find(bod.begin(), bod.end(), bc) != bod.end()); - xrpl::Dir cod(*env.current(), keylet::ownerDir(carol.id())); + xrpl::Dir const cod(*env.current(), keylet::ownerDir(carol.id())); BEAST_EXPECT(std::distance(cod.begin(), cod.end()) == 2); BEAST_EXPECT(std::find(cod.begin(), cod.end(), bc) != cod.end()); - xrpl::Dir iod(*env.current(), keylet::ownerDir(gw.id())); + xrpl::Dir const iod(*env.current(), keylet::ownerDir(gw.id())); BEAST_EXPECT(std::distance(iod.begin(), iod.end()) == 5); BEAST_EXPECT(std::find(iod.begin(), iod.end(), ab) != iod.end()); BEAST_EXPECT(std::find(iod.begin(), iod.end(), bc) != iod.end()); @@ -1110,19 +1110,19 @@ struct EscrowToken_test : public beast::unit_test::suite BEAST_EXPECT(!env.le(keylet::escrow(alice.id(), aseq))); BEAST_EXPECT(env.le(keylet::escrow(bob.id(), bseq))); - xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); + xrpl::Dir const aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 1); BEAST_EXPECT(std::find(aod.begin(), aod.end(), ab) == aod.end()); - xrpl::Dir bod(*env.current(), keylet::ownerDir(bob.id())); + xrpl::Dir const bod(*env.current(), keylet::ownerDir(bob.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 2); BEAST_EXPECT(std::find(bod.begin(), bod.end(), ab) == bod.end()); BEAST_EXPECT(std::find(bod.begin(), bod.end(), bc) != bod.end()); - xrpl::Dir cod(*env.current(), keylet::ownerDir(carol.id())); + xrpl::Dir const cod(*env.current(), keylet::ownerDir(carol.id())); BEAST_EXPECT(std::distance(cod.begin(), cod.end()) == 2); - xrpl::Dir iod(*env.current(), keylet::ownerDir(gw.id())); + xrpl::Dir const iod(*env.current(), keylet::ownerDir(gw.id())); BEAST_EXPECT(std::distance(iod.begin(), iod.end()) == 4); BEAST_EXPECT(std::find(iod.begin(), iod.end(), ab) == iod.end()); BEAST_EXPECT(std::find(iod.begin(), iod.end(), bc) != iod.end()); @@ -1134,19 +1134,19 @@ struct EscrowToken_test : public beast::unit_test::suite BEAST_EXPECT(!env.le(keylet::escrow(alice.id(), aseq))); BEAST_EXPECT(!env.le(keylet::escrow(bob.id(), bseq))); - xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); + xrpl::Dir const aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 1); BEAST_EXPECT(std::find(aod.begin(), aod.end(), ab) == aod.end()); - xrpl::Dir bod(*env.current(), keylet::ownerDir(bob.id())); + xrpl::Dir const bod(*env.current(), keylet::ownerDir(bob.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 1); BEAST_EXPECT(std::find(bod.begin(), bod.end(), ab) == bod.end()); BEAST_EXPECT(std::find(bod.begin(), bod.end(), bc) == bod.end()); - xrpl::Dir cod(*env.current(), keylet::ownerDir(carol.id())); + xrpl::Dir const cod(*env.current(), keylet::ownerDir(carol.id())); BEAST_EXPECT(std::distance(cod.begin(), cod.end()) == 1); - xrpl::Dir iod(*env.current(), keylet::ownerDir(gw.id())); + xrpl::Dir const iod(*env.current(), keylet::ownerDir(gw.id())); BEAST_EXPECT(std::distance(iod.begin(), iod.end()) == 3); BEAST_EXPECT(std::find(iod.begin(), iod.end(), ab) == iod.end()); BEAST_EXPECT(std::find(iod.begin(), iod.end(), bc) == iod.end()); @@ -1182,14 +1182,14 @@ struct EscrowToken_test : public beast::unit_test::suite BEAST_EXPECT(ag); { - xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); + xrpl::Dir const aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 2); BEAST_EXPECT(std::find(aod.begin(), aod.end(), ag) != aod.end()); - xrpl::Dir cod(*env.current(), keylet::ownerDir(carol.id())); + xrpl::Dir const cod(*env.current(), keylet::ownerDir(carol.id())); BEAST_EXPECT(std::distance(cod.begin(), cod.end()) == 1); - xrpl::Dir iod(*env.current(), keylet::ownerDir(gw.id())); + xrpl::Dir const iod(*env.current(), keylet::ownerDir(gw.id())); BEAST_EXPECT(std::distance(iod.begin(), iod.end()) == 3); BEAST_EXPECT(std::find(iod.begin(), iod.end(), ag) != iod.end()); } @@ -1199,14 +1199,14 @@ struct EscrowToken_test : public beast::unit_test::suite { BEAST_EXPECT(!env.le(keylet::escrow(alice.id(), aseq))); - xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); + xrpl::Dir const aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 1); BEAST_EXPECT(std::find(aod.begin(), aod.end(), ag) == aod.end()); - xrpl::Dir cod(*env.current(), keylet::ownerDir(carol.id())); + xrpl::Dir const cod(*env.current(), keylet::ownerDir(carol.id())); BEAST_EXPECT(std::distance(cod.begin(), cod.end()) == 1); - xrpl::Dir iod(*env.current(), keylet::ownerDir(gw.id())); + xrpl::Dir const iod(*env.current(), keylet::ownerDir(gw.id())); BEAST_EXPECT(std::distance(iod.begin(), iod.end()) == 2); BEAST_EXPECT(std::find(iod.begin(), iod.end(), ag) == iod.end()); } @@ -1229,7 +1229,7 @@ struct EscrowToken_test : public beast::unit_test::suite bool negative; }; - std::array tests = {{ + std::array const tests = {{ // src > dst && src > issuer && dst no trustline {Account("alice2"), Account("bob0"), Account{"gw0"}, false, true}, // src < dst && src < issuer && dst no trustline @@ -1335,7 +1335,7 @@ struct EscrowToken_test : public beast::unit_test::suite env.close(); } - std::array gwDstTests = {{ + std::array const gwDstTests = {{ // src > dst && src > issuer && dst has trustline {Account("alice2"), Account{"gw0"}, true}, // src < dst && src < issuer && dst has trustline @@ -2522,7 +2522,7 @@ struct EscrowToken_test : public beast::unit_test::suite Sandbox sb(&view, tapNONE); auto sleNew = std::make_shared(keylet::escrow(alice, seq1)); MPTIssue const mpt{MPTIssue{makeMptID(1, AccountID(0x4985601))}}; - STAmount amt(mpt, 10); + STAmount const amt(mpt, 10); sleNew->setAccountID(sfDestination, bob); sleNew->setFieldAmount(sfAmount, amt); sb.insert(sleNew); @@ -2749,7 +2749,7 @@ struct EscrowToken_test : public beast::unit_test::suite Sandbox sb(&view, tapNONE); auto sleNew = std::make_shared(keylet::escrow(alice, seq1)); MPTIssue const mpt{MPTIssue{makeMptID(1, AccountID(0x4985601))}}; - STAmount amt(mpt, 10); + STAmount const amt(mpt, 10); sleNew->setAccountID(sfDestination, bob); sleNew->setFieldAmount(sfAmount, amt); sb.insert(sleNew); @@ -3100,13 +3100,13 @@ struct EscrowToken_test : public beast::unit_test::suite auto const aa = env.le(keylet::escrow(alice.id(), aseq)); BEAST_EXPECT(aa); { - xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); + xrpl::Dir const aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 2); BEAST_EXPECT(std::find(aod.begin(), aod.end(), aa) != aod.end()); } { - xrpl::Dir iod(*env.current(), keylet::ownerDir(gw.id())); + xrpl::Dir const iod(*env.current(), keylet::ownerDir(gw.id())); BEAST_EXPECT(std::distance(iod.begin(), iod.end()) == 1); BEAST_EXPECT(std::find(iod.begin(), iod.end(), aa) == iod.end()); } @@ -3121,7 +3121,7 @@ struct EscrowToken_test : public beast::unit_test::suite BEAST_EXPECT(bb); { - xrpl::Dir bod(*env.current(), keylet::ownerDir(bob.id())); + xrpl::Dir const bod(*env.current(), keylet::ownerDir(bob.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 2); BEAST_EXPECT(std::find(bod.begin(), bod.end(), bb) != bod.end()); } @@ -3133,11 +3133,11 @@ struct EscrowToken_test : public beast::unit_test::suite BEAST_EXPECT( (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); - xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); + xrpl::Dir const aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 1); BEAST_EXPECT(std::find(aod.begin(), aod.end(), aa) == aod.end()); - xrpl::Dir bod(*env.current(), keylet::ownerDir(bob.id())); + xrpl::Dir const bod(*env.current(), keylet::ownerDir(bob.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 2); BEAST_EXPECT(std::find(bod.begin(), bod.end(), bb) != bod.end()); } @@ -3149,7 +3149,7 @@ struct EscrowToken_test : public beast::unit_test::suite BEAST_EXPECT( (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); - xrpl::Dir bod(*env.current(), keylet::ownerDir(bob.id())); + xrpl::Dir const bod(*env.current(), keylet::ownerDir(bob.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 1); BEAST_EXPECT(std::find(bod.begin(), bod.end(), bb) == bod.end()); } @@ -3191,16 +3191,16 @@ struct EscrowToken_test : public beast::unit_test::suite BEAST_EXPECT(bc); { - xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); + xrpl::Dir const aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 2); BEAST_EXPECT(std::find(aod.begin(), aod.end(), ab) != aod.end()); - xrpl::Dir bod(*env.current(), keylet::ownerDir(bob.id())); + xrpl::Dir const bod(*env.current(), keylet::ownerDir(bob.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 3); BEAST_EXPECT(std::find(bod.begin(), bod.end(), ab) != bod.end()); BEAST_EXPECT(std::find(bod.begin(), bod.end(), bc) != bod.end()); - xrpl::Dir cod(*env.current(), keylet::ownerDir(carol.id())); + xrpl::Dir const cod(*env.current(), keylet::ownerDir(carol.id())); BEAST_EXPECT(std::distance(cod.begin(), cod.end()) == 2); BEAST_EXPECT(std::find(cod.begin(), cod.end(), bc) != cod.end()); } @@ -3211,16 +3211,16 @@ struct EscrowToken_test : public beast::unit_test::suite BEAST_EXPECT(!env.le(keylet::escrow(alice.id(), aseq))); BEAST_EXPECT(env.le(keylet::escrow(bob.id(), bseq))); - xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); + xrpl::Dir const aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 1); BEAST_EXPECT(std::find(aod.begin(), aod.end(), ab) == aod.end()); - xrpl::Dir bod(*env.current(), keylet::ownerDir(bob.id())); + xrpl::Dir const bod(*env.current(), keylet::ownerDir(bob.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 2); BEAST_EXPECT(std::find(bod.begin(), bod.end(), ab) == bod.end()); BEAST_EXPECT(std::find(bod.begin(), bod.end(), bc) != bod.end()); - xrpl::Dir cod(*env.current(), keylet::ownerDir(carol.id())); + xrpl::Dir const cod(*env.current(), keylet::ownerDir(carol.id())); BEAST_EXPECT(std::distance(cod.begin(), cod.end()) == 2); } @@ -3230,16 +3230,16 @@ struct EscrowToken_test : public beast::unit_test::suite BEAST_EXPECT(!env.le(keylet::escrow(alice.id(), aseq))); BEAST_EXPECT(!env.le(keylet::escrow(bob.id(), bseq))); - xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); + xrpl::Dir const aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 1); BEAST_EXPECT(std::find(aod.begin(), aod.end(), ab) == aod.end()); - xrpl::Dir bod(*env.current(), keylet::ownerDir(bob.id())); + xrpl::Dir const bod(*env.current(), keylet::ownerDir(bob.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 1); BEAST_EXPECT(std::find(bod.begin(), bod.end(), ab) == bod.end()); BEAST_EXPECT(std::find(bod.begin(), bod.end(), bc) == bod.end()); - xrpl::Dir cod(*env.current(), keylet::ownerDir(carol.id())); + xrpl::Dir const cod(*env.current(), keylet::ownerDir(carol.id())); BEAST_EXPECT(std::distance(cod.begin(), cod.end()) == 1); } } diff --git a/src/test/app/Escrow_test.cpp b/src/test/app/Escrow_test.cpp index 2e6ef718d6..05640cde01 100644 --- a/src/test/app/Escrow_test.cpp +++ b/src/test/app/Escrow_test.cpp @@ -1057,7 +1057,7 @@ struct Escrow_test : public beast::unit_test::suite Env env(*this, features); env.fund(XRP(5000), "alice", "bob"); - std::array cb = { + std::array const cb = { {0xA2, 0x2B, 0x80, 0x20, 0x42, 0x4A, 0x70, 0x49, 0x49, 0x52, 0x92, 0x67, 0xB6, 0x21, 0xB3, 0xD7, 0x91, 0x19, 0xD7, 0x29, 0xB2, 0x38, 0x2C, 0xED, 0x8B, 0x29, 0x6C, 0x3C, 0x02, 0x8F, 0xA9, 0x7D, 0x35, 0x0F, 0x6D, 0x07, @@ -1100,7 +1100,7 @@ struct Escrow_test : public beast::unit_test::suite BEAST_EXPECT(aa); { - xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); + xrpl::Dir const aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 1); BEAST_EXPECT(std::find(aod.begin(), aod.end(), aa) != aod.end()); } @@ -1115,7 +1115,7 @@ struct Escrow_test : public beast::unit_test::suite BEAST_EXPECT(bb); { - xrpl::Dir bod(*env.current(), keylet::ownerDir(bruce.id())); + xrpl::Dir const bod(*env.current(), keylet::ownerDir(bruce.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 1); BEAST_EXPECT(std::find(bod.begin(), bod.end(), bb) != bod.end()); } @@ -1127,11 +1127,11 @@ struct Escrow_test : public beast::unit_test::suite BEAST_EXPECT( (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); - xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); + xrpl::Dir const aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 0); BEAST_EXPECT(std::find(aod.begin(), aod.end(), aa) == aod.end()); - xrpl::Dir bod(*env.current(), keylet::ownerDir(bruce.id())); + xrpl::Dir const bod(*env.current(), keylet::ownerDir(bruce.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 1); BEAST_EXPECT(std::find(bod.begin(), bod.end(), bb) != bod.end()); } @@ -1143,7 +1143,7 @@ struct Escrow_test : public beast::unit_test::suite BEAST_EXPECT( (*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); - xrpl::Dir bod(*env.current(), keylet::ownerDir(bruce.id())); + xrpl::Dir const bod(*env.current(), keylet::ownerDir(bruce.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 0); BEAST_EXPECT(std::find(bod.begin(), bod.end(), bb) == bod.end()); } @@ -1174,16 +1174,16 @@ struct Escrow_test : public beast::unit_test::suite BEAST_EXPECT(bc); { - xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); + xrpl::Dir const aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 1); BEAST_EXPECT(std::find(aod.begin(), aod.end(), ab) != aod.end()); - xrpl::Dir bod(*env.current(), keylet::ownerDir(bruce.id())); + xrpl::Dir const bod(*env.current(), keylet::ownerDir(bruce.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 2); BEAST_EXPECT(std::find(bod.begin(), bod.end(), ab) != bod.end()); BEAST_EXPECT(std::find(bod.begin(), bod.end(), bc) != bod.end()); - xrpl::Dir cod(*env.current(), keylet::ownerDir(carol.id())); + xrpl::Dir const cod(*env.current(), keylet::ownerDir(carol.id())); BEAST_EXPECT(std::distance(cod.begin(), cod.end()) == 1); BEAST_EXPECT(std::find(cod.begin(), cod.end(), bc) != cod.end()); } @@ -1194,16 +1194,16 @@ struct Escrow_test : public beast::unit_test::suite BEAST_EXPECT(!env.le(keylet::escrow(alice.id(), aseq))); BEAST_EXPECT(env.le(keylet::escrow(bruce.id(), bseq))); - xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); + xrpl::Dir const aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 0); BEAST_EXPECT(std::find(aod.begin(), aod.end(), ab) == aod.end()); - xrpl::Dir bod(*env.current(), keylet::ownerDir(bruce.id())); + xrpl::Dir const bod(*env.current(), keylet::ownerDir(bruce.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 1); BEAST_EXPECT(std::find(bod.begin(), bod.end(), ab) == bod.end()); BEAST_EXPECT(std::find(bod.begin(), bod.end(), bc) != bod.end()); - xrpl::Dir cod(*env.current(), keylet::ownerDir(carol.id())); + xrpl::Dir const cod(*env.current(), keylet::ownerDir(carol.id())); BEAST_EXPECT(std::distance(cod.begin(), cod.end()) == 1); } @@ -1213,16 +1213,16 @@ struct Escrow_test : public beast::unit_test::suite BEAST_EXPECT(!env.le(keylet::escrow(alice.id(), aseq))); BEAST_EXPECT(!env.le(keylet::escrow(bruce.id(), bseq))); - xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); + xrpl::Dir const aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 0); BEAST_EXPECT(std::find(aod.begin(), aod.end(), ab) == aod.end()); - xrpl::Dir bod(*env.current(), keylet::ownerDir(bruce.id())); + xrpl::Dir const bod(*env.current(), keylet::ownerDir(bruce.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 0); BEAST_EXPECT(std::find(bod.begin(), bod.end(), ab) == bod.end()); BEAST_EXPECT(std::find(bod.begin(), bod.end(), bc) == bod.end()); - xrpl::Dir cod(*env.current(), keylet::ownerDir(carol.id())); + xrpl::Dir const cod(*env.current(), keylet::ownerDir(carol.id())); BEAST_EXPECT(std::distance(cod.begin(), cod.end()) == 0); } } diff --git a/src/test/app/FeeVote_test.cpp b/src/test/app/FeeVote_test.cpp index 3c84f9e007..62f1058de5 100644 --- a/src/test/app/FeeVote_test.cpp +++ b/src/test/app/FeeVote_test.cpp @@ -189,7 +189,7 @@ class FeeVote_test : public beast::unit_test::suite FeeSetup const defaultSetup; { // defaults - Section config; + Section const config; auto setup = setup_FeeVote(config); BEAST_EXPECT(setup.reference_fee == defaultSetup.reference_fee); BEAST_EXPECT(setup.account_reserve == defaultSetup.account_reserve); @@ -260,7 +260,7 @@ class FeeVote_test : public beast::unit_test::suite // Test successful fee transaction with legacy fields - FeeSettingsFields fields{ + FeeSettingsFields const fields{ .baseFee = 10, .reserveBase = 200000, .reserveIncrement = 50000, @@ -288,7 +288,7 @@ class FeeVote_test : public beast::unit_test::suite // Create the next ledger to apply transaction to ledger = std::make_shared(*ledger, env.app().getTimeKeeper().closeTime()); - FeeSettingsFields fields{ + FeeSettingsFields const fields{ .baseFeeDrops = XRPAmount{10}, .reserveBaseDrops = XRPAmount{200000}, .reserveIncrementDrops = XRPAmount{50000}}; @@ -408,7 +408,7 @@ class FeeVote_test : public beast::unit_test::suite ledger = std::make_shared(*ledger, env.app().getTimeKeeper().closeTime()); - FeeSettingsFields fields1{ + FeeSettingsFields const fields1{ .baseFeeDrops = XRPAmount{10}, .reserveBaseDrops = XRPAmount{200000}, .reserveIncrementDrops = XRPAmount{50000}}; @@ -425,7 +425,7 @@ class FeeVote_test : public beast::unit_test::suite // Apply second fee transaction with different values ledger = std::make_shared(*ledger, env.app().getTimeKeeper().closeTime()); - FeeSettingsFields fields2{ + FeeSettingsFields const fields2{ .baseFeeDrops = XRPAmount{20}, .reserveBaseDrops = XRPAmount{300000}, .reserveIncrementDrops = XRPAmount{75000}}; @@ -487,7 +487,7 @@ class FeeVote_test : public beast::unit_test::suite ledger = std::make_shared(*ledger, env.app().getTimeKeeper().closeTime()); - FeeSettingsFields fields1{ + FeeSettingsFields const fields1{ .baseFeeDrops = XRPAmount{10}, .reserveBaseDrops = XRPAmount{200000}, .reserveIncrementDrops = XRPAmount{50000}}; @@ -504,7 +504,7 @@ class FeeVote_test : public beast::unit_test::suite ledger = std::make_shared(*ledger, env.app().getTimeKeeper().closeTime()); // Apply partial update (only some fields) - FeeSettingsFields fields2{ + FeeSettingsFields const fields2{ .baseFeeDrops = XRPAmount{20}, .reserveBaseDrops = XRPAmount{200000}}; auto feeTx2 = createFeeTx(ledger->rules(), ledger->seq(), fields2); diff --git a/src/test/app/Flow_test.cpp b/src/test/app/Flow_test.cpp index 25bcb4ee64..0bc5bd1727 100644 --- a/src/test/app/Flow_test.cpp +++ b/src/test/app/Flow_test.cpp @@ -437,7 +437,7 @@ struct Flow_test : public beast::unit_test::suite auto flowJournal = env.app().getJournal("Flow"); auto const flowResult = [&] { - STAmount deliver(USD(51)); + STAmount const deliver(USD(51)); STAmount smax(BTC(61)); PaymentSandbox sb(env.current().get(), tapNONE); STPathSet paths; @@ -450,10 +450,10 @@ struct Flow_test : public beast::unit_test::suite }; { // BTC -> USD - STPath p1({IPE(USD.issue())}); + STPath const p1({IPE(USD.issue())}); paths.push_back(p1); // BTC -> EUR -> USD - STPath p2({IPE(EUR.issue()), IPE(USD.issue())}); + STPath const p2({IPE(EUR.issue()), IPE(USD.issue())}); paths.push_back(p2); } @@ -876,8 +876,10 @@ struct Flow_test : public beast::unit_test::suite env.close(); env(trust(bob, USD(20))); - STAmount tinyAmt1{USD.issue(), 9000000000000000ll, -17, false, STAmount::unchecked{}}; - STAmount tinyAmt3{USD.issue(), 9000000000000003ll, -17, false, STAmount::unchecked{}}; + STAmount const tinyAmt1{ + USD.issue(), 9000000000000000ll, -17, false, STAmount::unchecked{}}; + STAmount const tinyAmt3{ + USD.issue(), 9000000000000003ll, -17, false, STAmount::unchecked{}}; env(offer(gw, drops(9000000000), tinyAmt3)); env(pay(alice, bob, tinyAmt1), @@ -900,8 +902,10 @@ struct Flow_test : public beast::unit_test::suite env.close(); env(trust(alice, USD(20))); - STAmount tinyAmt1{USD.issue(), 9000000000000000ll, -17, false, STAmount::unchecked{}}; - STAmount tinyAmt3{USD.issue(), 9000000000000003ll, -17, false, STAmount::unchecked{}}; + STAmount const tinyAmt1{ + USD.issue(), 9000000000000000ll, -17, false, STAmount::unchecked{}}; + STAmount const tinyAmt3{ + USD.issue(), 9000000000000003ll, -17, false, STAmount::unchecked{}}; env(pay(gw, alice, tinyAmt1)); diff --git a/src/test/app/Freeze_test.cpp b/src/test/app/Freeze_test.cpp index 1dd0de578b..ed5ee47578 100644 --- a/src/test/app/Freeze_test.cpp +++ b/src/test/app/Freeze_test.cpp @@ -19,9 +19,9 @@ class Freeze_test : public beast::unit_test::suite using namespace test::jtx; Env env(*this, features); - Account G1{"G1"}; - Account alice{"alice"}; - Account bob{"bob"}; + Account const G1{"G1"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(1000), G1, alice, bob); env.close(); @@ -168,8 +168,8 @@ class Freeze_test : public beast::unit_test::suite using namespace test::jtx; Env env(*this, features); - Account G1{"G1"}; - Account A1{"A1"}; + Account const G1{"G1"}; + Account const A1{"A1"}; env.fund(XRP(10000), G1, A1); env.close(); @@ -259,8 +259,8 @@ class Freeze_test : public beast::unit_test::suite using namespace test::jtx; Env env(*this, features); - Account G1{"G1"}; - Account A1{"A1"}; + Account const G1{"G1"}; + Account const A1{"A1"}; env.fund(XRP(10000), G1, A1); env.close(); @@ -308,8 +308,8 @@ class Freeze_test : public beast::unit_test::suite using namespace test::jtx; Env env(*this, features); - Account G1{"G1"}; - Account A1{"A1"}; + Account const G1{"G1"}; + Account const A1{"A1"}; env.fund(XRP(10000), G1, A1); env.close(); @@ -347,11 +347,11 @@ class Freeze_test : public beast::unit_test::suite using namespace test::jtx; Env env(*this, features); - Account G1{"G1"}; - Account A1{"A1"}; - Account A2{"A2"}; - Account A3{"A3"}; - Account A4{"A4"}; + Account const G1{"G1"}; + Account const A1{"A1"}; + Account const A2{"A2"}; + Account const A3{"A3"}; + Account const A4{"A4"}; env.fund(XRP(12000), G1); env.fund(XRP(1000), A1); @@ -497,10 +497,10 @@ class Freeze_test : public beast::unit_test::suite using namespace test::jtx; Env env(*this, features); - Account G1{"G1"}; - Account A1{"A1"}; - Account frozenAcc{"A2"}; - Account deepFrozenAcc{"A3"}; + Account const G1{"G1"}; + Account const A1{"A1"}; + Account const frozenAcc{"A2"}; + Account const deepFrozenAcc{"A3"}; env.fund(XRP(12000), G1); env.fund(XRP(1000), A1); @@ -608,10 +608,10 @@ class Freeze_test : public beast::unit_test::suite using namespace test::jtx; Env env(*this, features); - Account G1{"G1"}; - Account A2{"A2"}; - Account A3{"A3"}; - Account A4{"A4"}; + Account const G1{"G1"}; + Account const A2{"A2"}; + Account const A3{"A3"}; + Account const A4{"A4"}; env.fund(XRP(1000), G1, A3, A4); env.fund(XRP(2000), A2); @@ -705,10 +705,10 @@ class Freeze_test : public beast::unit_test::suite using namespace test::jtx; Env env(*this, features); - Account G1{"G1"}; - Account A1{"A1"}; - Account A2{"A2"}; - Account A3{"A3"}; + Account const G1{"G1"}; + Account const A1{"A1"}; + Account const A2{"A2"}; + Account const A3{"A3"}; auto const USD{G1["USD"]}; env.fund(XRP(10000), G1, A1, A2, A3); @@ -935,9 +935,9 @@ class Freeze_test : public beast::unit_test::suite using path = test::jtx::path; Env env(*this, features); - Account G1{"G1"}; - Account A1{"A1"}; - Account A2{"A2"}; + Account const G1{"G1"}; + Account const A1{"A1"}; + Account const A2{"A2"}; auto const USD{G1["USD"]}; env.fund(XRP(10000), G1, A1, A2); @@ -1161,9 +1161,9 @@ class Freeze_test : public beast::unit_test::suite using namespace test::jtx; Env env(*this, features); - Account G1{"G1"}; - Account A1{"A1"}; - Account A2{"A2"}; + Account const G1{"G1"}; + Account const A1{"A1"}; + Account const A2{"A2"}; auto const USD{G1["USD"]}; env.fund(XRP(10000), G1, A1, A2); @@ -1283,9 +1283,9 @@ class Freeze_test : public beast::unit_test::suite using namespace test::jtx; Env env(*this, features); - Account G1{"G1"}; - Account A1{"A1"}; - Account A2{"A2"}; + Account const G1{"G1"}; + Account const A1{"A1"}; + Account const A2{"A2"}; auto const USD{G1["USD"]}; env.fund(XRP(10000), G1, A1, A2); @@ -1578,9 +1578,9 @@ class Freeze_test : public beast::unit_test::suite using path = test::jtx::path; Env env(*this, features); - Account G1{"G1"}; - Account A1{"A1"}; - Account A2{"A2"}; + Account const G1{"G1"}; + Account const A1{"A1"}; + Account const A2{"A2"}; auto const USD{G1["USD"]}; env.fund(XRP(10000), G1, A1, A2); @@ -1593,7 +1593,7 @@ class Freeze_test : public beast::unit_test::suite env(pay(G1, A2, USD(1000))); env.close(); - AMM ammG1(env, G1, XRP(1'000), USD(1'000)); + AMM const ammG1(env, G1, XRP(1'000), USD(1'000)); env.close(); // Testing basic payment using AMM when freezing one of the trust lines. @@ -1668,9 +1668,9 @@ class Freeze_test : public beast::unit_test::suite using namespace test::jtx; Env env(*this, features); - Account G1{"G1"}; - Account A1{"A1"}; - Account A2{"A2"}; + Account const G1{"G1"}; + Account const A1{"A1"}; + Account const A2{"A2"}; auto const USD{G1["USD"]}; env.fund(XRP(10000), G1, A1, A2); @@ -1829,7 +1829,7 @@ class Freeze_test : public beast::unit_test::suite // Testing brokered offer acceptance if (features[featureDeepFreeze] && features[fixEnforceNFTokenTrustlineV2]) { - Account broker{"broker"}; + Account const broker{"broker"}; env.fund(XRP(10000), broker); env.close(); env(trust(G1, broker["USD"](1000), tfSetFreeze | tfSetDeepFreeze)); @@ -1855,7 +1855,7 @@ class Freeze_test : public beast::unit_test::suite // Testing transfer fee if (features[featureDeepFreeze] && features[fixEnforceNFTokenTrustlineV2]) { - Account minter{"minter"}; + Account const minter{"minter"}; env.fund(XRP(10000), minter); env.close(); env(trust(G1, minter["USD"](1000))); diff --git a/src/test/app/HashRouter_test.cpp b/src/test/app/HashRouter_test.cpp index a1601914cf..e53515e421 100644 --- a/src/test/app/HashRouter_test.cpp +++ b/src/test/app/HashRouter_test.cpp @@ -27,9 +27,9 @@ class HashRouter_test : public beast::unit_test::suite TestStopwatch stopwatch; HashRouter router(getSetup(2s, 1s), stopwatch); - HashRouterFlags key1(HashRouterFlags::PRIVATE1); - HashRouterFlags key2(HashRouterFlags::PRIVATE2); - HashRouterFlags key3(HashRouterFlags::PRIVATE3); + HashRouterFlags const key1(HashRouterFlags::PRIVATE1); + HashRouterFlags const key2(HashRouterFlags::PRIVATE2); + HashRouterFlags const key3(HashRouterFlags::PRIVATE3); auto const ukey1 = uint256{static_cast(key1)}; auto const ukey2 = uint256{static_cast(key2)}; @@ -69,10 +69,10 @@ class HashRouter_test : public beast::unit_test::suite TestStopwatch stopwatch; HashRouter router(getSetup(2s, 1s), stopwatch); - HashRouterFlags key1(HashRouterFlags::PRIVATE1); - HashRouterFlags key2(HashRouterFlags::PRIVATE2); - HashRouterFlags key3(HashRouterFlags::PRIVATE3); - HashRouterFlags key4(HashRouterFlags::PRIVATE4); + HashRouterFlags const key1(HashRouterFlags::PRIVATE1); + HashRouterFlags const key2(HashRouterFlags::PRIVATE2); + HashRouterFlags const key3(HashRouterFlags::PRIVATE3); + HashRouterFlags const key4(HashRouterFlags::PRIVATE4); auto const ukey1 = uint256{static_cast(key1)}; auto const ukey2 = uint256{static_cast(key2)}; @@ -242,7 +242,7 @@ class HashRouter_test : public beast::unit_test::suite TestStopwatch stopwatch; HashRouter router(getSetup(5s, 1s), stopwatch); uint256 const key(1); - HashRouter::PeerShortID peer = 1; + HashRouter::PeerShortID const peer = 1; HashRouterFlags flags = HashRouterFlags::UNDEFINED; BEAST_EXPECT(router.shouldProcess(key, peer, flags, 1s)); @@ -259,7 +259,7 @@ class HashRouter_test : public beast::unit_test::suite using namespace std::chrono_literals; { - Config cfg; + Config const cfg; // default auto const setup = setup_HashRouter(cfg); BEAST_EXPECT(setup.holdTime == 300s); @@ -298,7 +298,7 @@ class HashRouter_test : public beast::unit_test::suite } catch (std::exception const& e) { - std::string expected = + std::string const expected = "HashRouter relay time must be less than or equal to hold " "time"; BEAST_EXPECT(e.what() == expected); @@ -317,7 +317,7 @@ class HashRouter_test : public beast::unit_test::suite } catch (std::exception const& e) { - std::string expected = + std::string const expected = "HashRouter hold time must be at least 12 seconds (the " "approximate validation time for three " "ledgers)."; @@ -337,7 +337,7 @@ class HashRouter_test : public beast::unit_test::suite } catch (std::exception const& e) { - std::string expected = + std::string const expected = "HashRouter relay time must be at least 8 seconds (the " "approximate validation time for two ledgers)."; BEAST_EXPECT(e.what() == expected); @@ -365,9 +365,9 @@ class HashRouter_test : public beast::unit_test::suite using HF = HashRouterFlags; using UHF = std::underlying_type_t; - HF f1 = HF::BAD; - HF f2 = HF::SAVED; - HF combined = f1 | f2; + HF const f1 = HF::BAD; + HF const f2 = HF::SAVED; + HF const combined = f1 | f2; BEAST_EXPECT(static_cast(combined) == (static_cast(f1) | static_cast(f2))); @@ -375,7 +375,7 @@ class HashRouter_test : public beast::unit_test::suite temp |= f2; BEAST_EXPECT(temp == combined); - HF intersect = combined & f1; + HF const intersect = combined & f1; BEAST_EXPECT(intersect == f1); HF temp2 = combined; diff --git a/src/test/app/Invariants_test.cpp b/src/test/app/Invariants_test.cpp index ca63a69bc4..ef0624b481 100644 --- a/src/test/app/Invariants_test.cpp +++ b/src/test/app/Invariants_test.cpp @@ -127,7 +127,7 @@ class Invariants_test : public beast::unit_test::suite OpenView ov{*env.current()}; test::StreamSink sink{beast::severities::kWarning}; - beast::Journal jlog{sink}; + beast::Journal const jlog{sink}; ApplyContext ac{env.app(), ov, tx, tesSUCCESS, env.current()->fees().base, tapNONE, jlog}; BEAST_EXPECT(precheck(A1, A2, ac)); @@ -845,7 +845,7 @@ class Invariants_test : public beast::unit_test::suite auto sleNew = std::make_shared(keylet::escrow(A1, (*sle)[sfSequence] + 2)); Issue const usd{Currency(0x5553440000000000), AccountID(0x4985601)}; - STAmount amt(usd, -1); + STAmount const amt(usd, -1); sleNew->setFieldAmount(sfAmount, amt); ac.view().insert(sleNew); return true; @@ -862,7 +862,7 @@ class Invariants_test : public beast::unit_test::suite auto sleNew = std::make_shared(keylet::escrow(A1, (*sle)[sfSequence] + 2)); Issue const bad{badCurrency(), AccountID(0x4985601)}; - STAmount amt(bad, 1); + STAmount const amt(bad, 1); sleNew->setFieldAmount(sfAmount, amt); ac.view().insert(sleNew); return true; @@ -879,7 +879,7 @@ class Invariants_test : public beast::unit_test::suite auto sleNew = std::make_shared(keylet::escrow(A1, (*sle)[sfSequence] + 2)); MPTIssue const mpt{MPTIssue{makeMptID(1, AccountID(0x4985601))}}; - STAmount amt(mpt, -1); + STAmount const amt(mpt, -1); sleNew->setFieldAmount(sfAmount, amt); ac.view().insert(sleNew); return true; @@ -1026,8 +1026,7 @@ class Invariants_test : public beast::unit_test::suite auto const sleNew = std::make_shared(acctKeylet); sleNew->setFieldU32(sfSequence, 0); sleNew->setFieldH256(sfAMMID, uint256(1)); - sleNew->setFieldU32( - sfFlags, lsfDisableMaster | lsfDefaultRipple | lsfDefaultRipple); + sleNew->setFieldU32(sfFlags, lsfDisableMaster | lsfDefaultRipple); ac.view().insert(sleNew); return true; }, @@ -1253,8 +1252,8 @@ class Invariants_test : public beast::unit_test::suite using namespace test::jtx; bool const fixPDEnabled = features[fixPermissionedDomainInvariant]; - std::initializer_list badTers = {tecINVARIANT_FAILED, tecINVARIANT_FAILED}; - std::initializer_list failTers = {tecINVARIANT_FAILED, tefINVARIANT_FAILED}; + std::initializer_list const badTers = {tecINVARIANT_FAILED, tecINVARIANT_FAILED}; + std::initializer_list const failTers = {tecINVARIANT_FAILED, tefINVARIANT_FAILED}; testcase << "PermissionedDomain" + std::string(fixPDEnabled ? " fix" : ""); @@ -1338,7 +1337,7 @@ class Invariants_test : public beast::unit_test::suite // update PD with empty rules { - STArray credentials(sfAcceptedCredentials, 2); + STArray const credentials(sfAcceptedCredentials, 2); slePd->setFieldArray(sfAcceptedCredentials, credentials); ac.view().update(slePd); } @@ -1438,15 +1437,16 @@ class Invariants_test : public beast::unit_test::suite STTx{ttPERMISSIONED_DOMAIN_SET, [](STObject&) {}}, fixPDEnabled ? failTers : badTers); - std::initializer_list goodTers = {tesSUCCESS, tesSUCCESS}; + std::initializer_list const goodTers = {tesSUCCESS, tesSUCCESS}; - std::vector badMoreThan1{ + std::vector const badMoreThan1{ {"transaction affected more than 1 permissioned domain entry."}}; - std::vector emptyV; - std::vector badNoDomains{{"no domain objects affected by"}}; - std::vector badNotDeleted{{"domain object modified, but not deleted by "}}; - std::vector badDeleted{{"domain object deleted by"}}; - std::vector badTx{ + std::vector const emptyV; + std::vector const badNoDomains{{"no domain objects affected by"}}; + std::vector const badNotDeleted{ + {"domain object modified, but not deleted by "}}; + std::vector const badDeleted{{"domain object deleted by"}}; + std::vector const badTx{ {"domain object(s) affected by an unauthorized transaction."}}; { @@ -1596,11 +1596,11 @@ class Invariants_test : public beast::unit_test::suite using namespace jtx; AccountID pseudoAccountID; - Preclose createPseudo = [&, this](Account const& a, Account const& b, Env& env) { + Preclose const createPseudo = [&, this](Account const& a, Account const& b, Env& env) { PrettyAsset const xrpAsset{xrpIssue(), 1'000'000}; // Create vault - Vault vault{env}; + Vault const vault{env}; auto [tx, vKeylet] = vault.create({.owner = a, .asset = xrpAsset}); env(tx); env.close(); @@ -1724,7 +1724,7 @@ class Invariants_test : public beast::unit_test::suite std::uint32_t const seq = env.seq(A1); env(pdomain::setTx(A1, credentials)); - uint256 key = pdomain::getNewDomain(env.meta()); + uint256 const key = pdomain::getNewDomain(env.meta()); // std::cout << "PD, acc: " << A1.id() << ", seq: " << seq << ", k: " << // key << std::endl; @@ -1942,7 +1942,7 @@ class Invariants_test : public beast::unit_test::suite // Create vault uint256 vaultID; - Vault vault{env}; + Vault const vault{env}; auto [tx, vKeylet] = vault.create({.owner = a, .asset = asset}); env(tx); BEAST_EXPECT(env.le(vKeylet)); @@ -1967,7 +1967,7 @@ class Invariants_test : public beast::unit_test::suite // Initialize with a placeholder value because there's no default ctor Keylet loanBrokerKeylet = keylet::amendments(); - Preclose createLoanBroker = [&, this](Account const& a, Account const& b, Env& env) { + Preclose const createLoanBroker = [&, this](Account const& a, Account const& b, Env& env) { PrettyAsset const xrpAsset{xrpIssue(), 1'000'000}; loanBrokerKeylet = this->createLoanBroker(a, env, xrpAsset); @@ -2047,38 +2047,38 @@ class Invariants_test : public beast::unit_test::suite // Initialize with a placeholder value because there's no default // ctor Keylet loanBrokerKeylet = keylet::amendments(); - Preclose createLoanBroker = [&, this]( - Account const& alice, Account const& issuer, Env& env) { - PrettyAsset const asset = [&]() { - switch (assetType) - { - case Asset::IOU: { - PrettyAsset const iouAsset = issuer["IOU"]; - env(trust(alice, iouAsset(1000))); - env(pay(issuer, alice, iouAsset(1000))); - env.close(); - return iouAsset; - } + Preclose const createLoanBroker = + [&, this](Account const& alice, Account const& issuer, Env& env) { + PrettyAsset const asset = [&]() { + switch (assetType) + { + case Asset::IOU: { + PrettyAsset const iouAsset = issuer["IOU"]; + env(trust(alice, iouAsset(1000))); + env(pay(issuer, alice, iouAsset(1000))); + env.close(); + return iouAsset; + } - case Asset::MPT: { - MPTTester mptt{env, issuer, mptInitNoFund}; - mptt.create( - {.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); - PrettyAsset const mptAsset = mptt.issuanceID(); - mptt.authorize({.account = alice}); - env(pay(issuer, alice, mptAsset(1000))); - env.close(); - return mptAsset; - } + case Asset::MPT: { + MPTTester mptt{env, issuer, mptInitNoFund}; + mptt.create( + {.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); + PrettyAsset const mptAsset = mptt.issuanceID(); + mptt.authorize({.account = alice}); + env(pay(issuer, alice, mptAsset(1000))); + env.close(); + return mptAsset; + } - case Asset::XRP: - default: - return PrettyAsset{xrpIssue(), 1'000'000}; - } - }(); - loanBrokerKeylet = this->createLoanBroker(alice, env, asset); - return BEAST_EXPECT(env.le(loanBrokerKeylet)); - }; + case Asset::XRP: + default: + return PrettyAsset{xrpIssue(), 1'000'000}; + } + }(); + loanBrokerKeylet = this->createLoanBroker(alice, env, asset); + return BEAST_EXPECT(env.le(loanBrokerKeylet)); + }; // Ensure the test scenarios are set up completely. The test cases // will need to recompute any of these values it needs for itself @@ -2393,7 +2393,7 @@ class Invariants_test : public beast::unit_test::suite Account A4{"A4"}; auto const precloseXrp = [&](Account const& A1, Account const& A2, Env& env) -> bool { env.fund(XRP(1000), A3, A4); - Vault vault{env}; + Vault const vault{env}; auto [tx, keylet] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); env(vault.deposit({.depositor = A1, .id = keylet.key, .amount = XRP(10)})); @@ -2417,7 +2417,7 @@ class Invariants_test : public beast::unit_test::suite STTx{ttVAULT_DELETE, [](STObject&) {}}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, [&](Account const& A1, Account const& A2, Env& env) { - Vault vault{env}; + Vault const vault{env}; auto [tx, _] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); return true; @@ -2437,7 +2437,7 @@ class Invariants_test : public beast::unit_test::suite STTx{ttPAYMENT, [](STObject&) {}}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, [&](Account const& A1, Account const& A2, Env& env) { - Vault vault{env}; + Vault const vault{env}; auto [tx, _] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); return true; @@ -2457,7 +2457,7 @@ class Invariants_test : public beast::unit_test::suite STTx{ttPAYMENT, [](STObject&) {}}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, [&](Account const& A1, Account const& A2, Env& env) { - Vault vault{env}; + Vault const vault{env}; auto [tx, _] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); return true; @@ -2493,7 +2493,7 @@ class Invariants_test : public beast::unit_test::suite STTx{ttVAULT_SET, [](STObject&) {}}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, [&](Account const& A1, Account const& A2, Env& env) { - Vault vault{env}; + Vault const vault{env}; auto [tx, _] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); return true; @@ -2522,7 +2522,7 @@ class Invariants_test : public beast::unit_test::suite STTx{ttVAULT_DELETE, [](STObject&) {}}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, [&](Account const& A1, Account const& A2, Env& env) { - Vault vault{env}; + Vault const vault{env}; { auto [tx, _] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); @@ -2568,7 +2568,7 @@ class Invariants_test : public beast::unit_test::suite STTx{ttVAULT_DELETE, [](STObject&) {}}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, [&](Account const& A1, Account const& A2, Env& env) { - Vault vault{env}; + Vault const vault{env}; auto [tx, _] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); return true; @@ -2594,7 +2594,7 @@ class Invariants_test : public beast::unit_test::suite STTx{ttVAULT_DELETE, [](STObject&) {}}, {tecINVARIANT_FAILED, tefINVARIANT_FAILED}, [&](Account const& A1, Account const& A2, Env& env) { - Vault vault{env}; + Vault const vault{env}; auto [tx, keylet] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); env(vault.deposit({.depositor = A1, .id = keylet.key, .amount = XRP(10)})); @@ -2630,7 +2630,7 @@ class Invariants_test : public beast::unit_test::suite STTx{ttVAULT_CREATE, [](STObject&) {}}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, [&](Account const& A1, Account const& A2, Env& env) { - Vault vault{env}; + Vault const vault{env}; auto [tx, _] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); return true; @@ -2643,7 +2643,7 @@ class Invariants_test : public beast::unit_test::suite STTx{ttVAULT_DEPOSIT, [](STObject&) {}}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, [&](Account const& A1, Account const& A2, Env& env) { - Vault vault{env}; + Vault const vault{env}; auto [tx, _] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); return true; @@ -2656,7 +2656,7 @@ class Invariants_test : public beast::unit_test::suite STTx{ttVAULT_WITHDRAW, [](STObject&) {}}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, [&](Account const& A1, Account const& A2, Env& env) { - Vault vault{env}; + Vault const vault{env}; auto [tx, _] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); return true; @@ -2669,7 +2669,7 @@ class Invariants_test : public beast::unit_test::suite STTx{ttVAULT_CLAWBACK, [](STObject&) {}}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, [&](Account const& A1, Account const& A2, Env& env) { - Vault vault{env}; + Vault const vault{env}; auto [tx, _] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); return true; @@ -2682,7 +2682,7 @@ class Invariants_test : public beast::unit_test::suite STTx{ttVAULT_DELETE, [](STObject&) {}}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, [&](Account const& A1, Account const& A2, Env& env) { - Vault vault{env}; + Vault const vault{env}; auto [tx, _] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); return true; @@ -2708,7 +2708,7 @@ class Invariants_test : public beast::unit_test::suite STTx{ttVAULT_SET, [](STObject&) {}}, {tecINVARIANT_FAILED, tefINVARIANT_FAILED}, [&](Account const& A1, Account const& A2, Env& env) { - Vault vault{env}; + Vault const vault{env}; auto [tx, _] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); return true; @@ -2730,7 +2730,7 @@ class Invariants_test : public beast::unit_test::suite STTx{ttVAULT_WITHDRAW, [](STObject&) {}}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, [&](Account const& A1, Account const& A2, Env& env) { - Vault vault{env}; + Vault const vault{env}; auto [tx, keylet] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); env(vault.deposit({.depositor = A1, .id = keylet.key, .amount = XRP(10)})); @@ -2970,7 +2970,7 @@ class Invariants_test : public beast::unit_test::suite STTx{ttVAULT_CREATE, [](STObject&) {}}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, [&](Account const& A1, Account const& A2, Env& env) { - Vault vault{env}; + Vault const vault{env}; auto [tx, keylet] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); return true; @@ -2996,7 +2996,7 @@ class Invariants_test : public beast::unit_test::suite STTx{ttVAULT_CREATE, [](STObject&) {}}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, [&](Account const& A1, Account const& A2, Env& env) { - Vault vault{env}; + Vault const vault{env}; auto [tx, keylet] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); return true; @@ -3023,7 +3023,7 @@ class Invariants_test : public beast::unit_test::suite STTx{ttVAULT_CREATE, [](STObject&) {}}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, [&](Account const& A1, Account const& A2, Env& env) { - Vault vault{env}; + Vault const vault{env}; auto [tx, keylet] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); return true; @@ -3051,7 +3051,7 @@ class Invariants_test : public beast::unit_test::suite STTx{ttVAULT_CREATE, [](STObject&) {}}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, [&](Account const& A1, Account const& A2, Env& env) { - Vault vault{env}; + Vault const vault{env}; auto [tx, keylet] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); return true; @@ -3075,7 +3075,7 @@ class Invariants_test : public beast::unit_test::suite STTx{ttVAULT_CREATE, [](STObject&) {}}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, [&](Account const& A1, Account const& A2, Env& env) { - Vault vault{env}; + Vault const vault{env}; auto [tx, keylet] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); return true; @@ -3103,7 +3103,7 @@ class Invariants_test : public beast::unit_test::suite STTx{ttVAULT_CREATE, [](STObject&) {}}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, [&](Account const& A1, Account const& A2, Env& env) { - Vault vault{env}; + Vault const vault{env}; auto [tx, keylet] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); return true; @@ -3658,7 +3658,7 @@ class Invariants_test : public beast::unit_test::suite } auto const mptID = makeMptID(env.seq(A3) - 1, A3); - Asset asset = MPTIssue(mptID); + Asset const asset = MPTIssue(mptID); // Authorize A1 A2 A4 { Json::Value jv; @@ -3681,7 +3681,7 @@ class Invariants_test : public beast::unit_test::suite env.close(); } - Vault vault{env}; + Vault const vault{env}; auto [tx, keylet] = vault.create({.owner = A1, .asset = asset}); env(tx); env(vault.deposit({.depositor = A1, .id = keylet.key, .amount = asset(10)})); diff --git a/src/test/app/LedgerHistory_test.cpp b/src/test/app/LedgerHistory_test.cpp index dbc20fe8f2..453c424251 100644 --- a/src/test/app/LedgerHistory_test.cpp +++ b/src/test/app/LedgerHistory_test.cpp @@ -138,17 +138,17 @@ public: Env env{*this, envconfig(), std::make_unique(msg, &found)}; LedgerHistory lh{beast::insight::NullCollector::New(), env.app()}; - Account alice{"A1"}; - Account bob{"A2"}; + Account const alice{"A1"}; + Account const bob{"A2"}; env.fund(XRP(1000), alice, bob); env.close(); auto const ledgerBase = env.app().getLedgerMaster().getClosedLedger(); - JTx txAlice = env.jt(noop(alice)); + JTx const txAlice = env.jt(noop(alice)); auto const ledgerA = makeLedger(ledgerBase, env, lh, 4s, txAlice.stx); - JTx txBob = env.jt(noop(bob)); + JTx const txBob = env.jt(noop(bob)); auto const ledgerB = makeLedger(ledgerBase, env, lh, 4s, txBob.stx); lh.builtLedger(ledgerA, txAlice.stx->getTransactionID(), {}); diff --git a/src/test/app/LedgerLoad_test.cpp b/src/test/app/LedgerLoad_test.cpp index 2fa1193921..1df41671fe 100644 --- a/src/test/app/LedgerLoad_test.cpp +++ b/src/test/app/LedgerLoad_test.cpp @@ -127,7 +127,7 @@ class LedgerLoad_test : public beast::unit_test::suite // empty path except([&] { - Env env( + Env const env( *this, envconfig(ledgerConfig, sd.dbPath, "", StartUpType::LoadFile, std::nullopt), nullptr, @@ -136,7 +136,7 @@ class LedgerLoad_test : public beast::unit_test::suite // file does not exist except([&] { - Env env( + Env const env( *this, envconfig( ledgerConfig, sd.dbPath, "badfile.json", StartUpType::LoadFile, std::nullopt), @@ -158,7 +158,7 @@ class LedgerLoad_test : public beast::unit_test::suite return; except([&] { - Env env( + Env const env( *this, envconfig( ledgerConfig, @@ -257,7 +257,7 @@ class LedgerLoad_test : public beast::unit_test::suite { // will throw an exception, because we cannot load a ledger for // replay when trapTxHash is set to an invalid transaction - Env env( + Env const env( *this, envconfig(ledgerConfig, sd.dbPath, ledgerHash, StartUpType::Replay, ~sd.trapTxHash), nullptr, @@ -314,7 +314,7 @@ public: void run() override { - beast::temp_dir td; + beast::temp_dir const td; auto sd = setupLedger(td); // test cases diff --git a/src/test/app/LedgerMaster_test.cpp b/src/test/app/LedgerMaster_test.cpp index 3ea16b63eb..7a8904dbd7 100644 --- a/src/test/app/LedgerMaster_test.cpp +++ b/src/test/app/LedgerMaster_test.cpp @@ -51,14 +51,14 @@ class LedgerMaster_test : public beast::unit_test::suite // test invalid range { - std::uint32_t ledgerSeq = -1; - std::uint32_t txnIndex = 0; + std::uint32_t const ledgerSeq = -1; + std::uint32_t const txnIndex = 0; auto result = env.app().getLedgerMaster().txnIdFromIndex(ledgerSeq, txnIndex); BEAST_EXPECT(!result); } // test not in ledger { - uint32_t txnIndex = metas[0]->getFieldU32(sfTransactionIndex); + uint32_t const txnIndex = metas[0]->getFieldU32(sfTransactionIndex); auto result = env.app().getLedgerMaster().txnIdFromIndex(0, txnIndex); BEAST_EXPECT(!result); } @@ -69,13 +69,13 @@ class LedgerMaster_test : public beast::unit_test::suite } // ended without result { - uint32_t txnIndex = metas[0]->getFieldU32(sfTransactionIndex); + uint32_t const txnIndex = metas[0]->getFieldU32(sfTransactionIndex); auto result = env.app().getLedgerMaster().txnIdFromIndex(endLegSeq + 1, txnIndex); BEAST_EXPECT(!result); } // success (first tx) { - uint32_t txnIndex = metas[0]->getFieldU32(sfTransactionIndex); + uint32_t const txnIndex = metas[0]->getFieldU32(sfTransactionIndex); auto result = env.app().getLedgerMaster().txnIdFromIndex(startLegSeq, txnIndex); BEAST_EXPECT( // NOLINTNEXTLINE(bugprone-unchecked-optional-access) @@ -86,7 +86,7 @@ class LedgerMaster_test : public beast::unit_test::suite } // success (second tx) { - uint32_t txnIndex = metas[1]->getFieldU32(sfTransactionIndex); + uint32_t const txnIndex = metas[1]->getFieldU32(sfTransactionIndex); auto result = env.app().getLedgerMaster().txnIdFromIndex(startLegSeq + 1, txnIndex); BEAST_EXPECT( // NOLINTNEXTLINE(bugprone-unchecked-optional-access) diff --git a/src/test/app/LedgerReplay_test.cpp b/src/test/app/LedgerReplay_test.cpp index 93811d33b0..b30dce4756 100644 --- a/src/test/app/LedgerReplay_test.cpp +++ b/src/test/app/LedgerReplay_test.cpp @@ -246,7 +246,7 @@ public: uint256 const& getClosedLedgerHash() const override { - static uint256 hash{}; + static uint256 const hash{}; return hash; } bool @@ -398,7 +398,7 @@ struct TestPeerSet : public PeerSet std::set const& getPeerIds() const override { - static std::set emptyPeers; + static std::set const emptyPeers; return emptyPeers; } @@ -605,7 +605,7 @@ public: bool waitForLedgers(uint256 const& finishLedgerHash, int totalReplay) { - int totalRound = 100; + int const totalRound = 100; for (int i = 0; i < totalRound; ++i) { if (haveLedgers(finishLedgerHash, totalReplay)) @@ -619,12 +619,12 @@ public: bool waitForDone() { - int totalRound = 100; + int const totalRound = 100; for (int i = 0; i < totalRound; ++i) { bool allDone = true; { - std::unique_lock lock(replayer.mtx_); + std::unique_lock const lock(replayer.mtx_); for (auto const& t : replayer.tasks_) { if (!t->finished()) @@ -645,14 +645,14 @@ public: std::vector> getTasks() { - std::unique_lock lock(replayer.mtx_); + std::unique_lock const lock(replayer.mtx_); return replayer.tasks_; } std::shared_ptr findTask(uint256 const& hash, int totalReplay) { - std::unique_lock lock(replayer.mtx_); + std::unique_lock const lock(replayer.mtx_); auto i = std::find_if(replayer.tasks_.begin(), replayer.tasks_.end(), [&](auto const& t) { return t->parameter_.finishHash_ == hash && t->parameter_.totalLedgers_ == totalReplay; }); @@ -664,21 +664,21 @@ public: std::size_t countDeltas() { - std::unique_lock lock(replayer.mtx_); + std::unique_lock const lock(replayer.mtx_); return replayer.deltas_.size(); } std::size_t countSkipLists() { - std::unique_lock lock(replayer.mtx_); + std::unique_lock const lock(replayer.mtx_); return replayer.skipLists_.size(); } bool countsAsExpected(std::size_t tasks, std::size_t skipLists, std::size_t deltas) { - std::unique_lock lock(replayer.mtx_); + std::unique_lock const lock(replayer.mtx_); return replayer.tasks_.size() == tasks && replayer.skipLists_.size() == skipLists && replayer.deltas_.size() == deltas; } @@ -686,7 +686,7 @@ public: std::shared_ptr findSkipListAcquire(uint256 const& hash) { - std::unique_lock lock(replayer.mtx_); + std::unique_lock const lock(replayer.mtx_); auto i = replayer.skipLists_.find(hash); if (i == replayer.skipLists_.end()) return {}; @@ -696,7 +696,7 @@ public: std::shared_ptr findLedgerDeltaAcquire(uint256 const& hash) { - std::unique_lock lock(replayer.mtx_); + std::unique_lock const lock(replayer.mtx_); auto i = replayer.deltas_.find(hash); if (i == replayer.deltas_.end()) return {}; @@ -1017,13 +1017,13 @@ struct LedgerReplayer_test : public beast::unit_test::suite { testcase("config test"); { - Config c; + Config const c; BEAST_EXPECT(c.LEDGER_REPLAY == false); } { Config c; - std::string toLoad(R"rippleConfig( + std::string const toLoad(R"rippleConfig( [ledger_replay] 1 )rippleConfig"); @@ -1033,7 +1033,7 @@ struct LedgerReplayer_test : public beast::unit_test::suite { Config c; - std::string toLoad = (R"rippleConfig( + std::string const toLoad = (R"rippleConfig( [ledger_replay] 0 )rippleConfig"); @@ -1051,11 +1051,12 @@ struct LedgerReplayer_test : public beast::unit_test::suite http_request_type http_request; http_request.version(request.version()); http_request.base() = request.base(); - bool serverResult = peerFeatureEnabled(http_request, FEATURE_LEDGER_REPLAY, server); + bool const serverResult = + peerFeatureEnabled(http_request, FEATURE_LEDGER_REPLAY, server); if (serverResult != expecting) return false; - beast::IP::Address addr = boost::asio::ip::make_address("172.1.1.100"); + beast::IP::Address const addr = boost::asio::ip::make_address("172.1.1.100"); jtx::Env serverEnv(*this); serverEnv.app().config().LEDGER_REPLAY = server; auto http_resp = xrpl::makeResponse( @@ -1081,7 +1082,7 @@ struct LedgerReplayer_test : public beast::unit_test::suite NetworkOfTwo net(*this, {totalReplay + 1}, psBhvr, ilBhvr, peerFeature); auto l = net.server.ledgerMaster.getClosedLedger(); - uint256 finalHash = l->header().hash; + uint256 const finalHash = l->header().hash; for (int i = 0; i < totalReplay; ++i) { BEAST_EXPECT(l); @@ -1098,7 +1099,7 @@ struct LedgerReplayer_test : public beast::unit_test::suite net.client.replayer.replay(InboundLedger::Reason::GENERIC, finalHash, totalReplay); - std::vector deltaStatuses(totalReplay - 1, TaskStatus::Completed); + std::vector const deltaStatuses(totalReplay - 1, TaskStatus::Completed); BEAST_EXPECT(net.client.waitAndCheckStatus( finalHash, totalReplay, TaskStatus::Completed, TaskStatus::Completed, deltaStatuses)); @@ -1119,10 +1120,10 @@ struct LedgerReplayer_test : public beast::unit_test::suite PeerFeature::None); auto l = net.server.ledgerMaster.getClosedLedger(); - uint256 finalHash = l->header().hash; + uint256 const finalHash = l->header().hash; net.client.replayer.replay(InboundLedger::Reason::GENERIC, finalHash, totalReplay); - std::vector deltaStatuses(totalReplay - 1, TaskStatus::Completed); + std::vector const deltaStatuses(totalReplay - 1, TaskStatus::Completed); BEAST_EXPECT(net.client.waitAndCheckStatus( finalHash, totalReplay, TaskStatus::Completed, TaskStatus::Completed, deltaStatuses)); @@ -1176,7 +1177,7 @@ struct LedgerReplayer_test : public beast::unit_test::suite // feed client with start ledger since InboundLedgers drops all auto l = net.server.ledgerMaster.getClosedLedger(); - uint256 finalHash = l->header().hash; + uint256 const finalHash = l->header().hash; for (int i = 0; i < totalReplay - 1; ++i) { l = net.server.ledgerMaster.getLedgerByHash(l->header().parentHash); @@ -1185,7 +1186,7 @@ struct LedgerReplayer_test : public beast::unit_test::suite net.client.replayer.replay(InboundLedger::Reason::GENERIC, finalHash, totalReplay); - std::vector deltaStatuses(totalReplay - 1, TaskStatus::Completed); + std::vector const deltaStatuses(totalReplay - 1, TaskStatus::Completed); BEAST_EXPECT(net.client.waitAndCheckStatus( finalHash, totalReplay, TaskStatus::Completed, TaskStatus::Completed, deltaStatuses)); BEAST_EXPECT(net.client.waitForLedgers(finalHash, totalReplay)); @@ -1199,7 +1200,7 @@ struct LedgerReplayer_test : public beast::unit_test::suite testStop() { testcase("stop before timeout"); - int totalReplay = 3; + int const totalReplay = 3; NetworkOfTwo net( *this, {totalReplay + 1}, @@ -1208,10 +1209,10 @@ struct LedgerReplayer_test : public beast::unit_test::suite PeerFeature::LedgerReplayEnabled); auto l = net.server.ledgerMaster.getClosedLedger(); - uint256 finalHash = l->header().hash; + uint256 const finalHash = l->header().hash; net.client.replayer.replay(InboundLedger::Reason::GENERIC, finalHash, totalReplay); - std::vector deltaStatuses; + std::vector const deltaStatuses; BEAST_EXPECT(net.client.checkStatus( finalHash, totalReplay, TaskStatus::NotDone, TaskStatus::NotDone, deltaStatuses)); @@ -1224,7 +1225,7 @@ struct LedgerReplayer_test : public beast::unit_test::suite testSkipListBadReply() { testcase("SkipListAcquire bad reply"); - int totalReplay = 3; + int const totalReplay = 3; NetworkOfTwo net( *this, {totalReplay + 1 + 1}, @@ -1233,7 +1234,7 @@ struct LedgerReplayer_test : public beast::unit_test::suite PeerFeature::LedgerReplayEnabled); auto l = net.server.ledgerMaster.getClosedLedger(); - uint256 finalHash = l->header().hash; + uint256 const finalHash = l->header().hash; net.client.replayer.replay(InboundLedger::Reason::GENERIC, finalHash, totalReplay); auto skipList = net.client.findSkipListAcquire(finalHash); @@ -1242,7 +1243,7 @@ struct LedgerReplayer_test : public beast::unit_test::suite auto item = make_shamapitem(uint256(12345), Slice(payload, sizeof(payload))); skipList->processData(l->seq(), item); - std::vector deltaStatuses; + std::vector const deltaStatuses; BEAST_EXPECT(net.client.waitAndCheckStatus( finalHash, totalReplay, TaskStatus::Failed, TaskStatus::Failed, deltaStatuses)); @@ -1257,7 +1258,7 @@ struct LedgerReplayer_test : public beast::unit_test::suite testLedgerDeltaBadReply() { testcase("LedgerDeltaAcquire bad reply"); - int totalReplay = 3; + int const totalReplay = 3; NetworkOfTwo net( *this, {totalReplay + 1}, @@ -1266,7 +1267,7 @@ struct LedgerReplayer_test : public beast::unit_test::suite PeerFeature::LedgerReplayEnabled); auto l = net.server.ledgerMaster.getClosedLedger(); - uint256 finalHash = l->header().hash; + uint256 const finalHash = l->header().hash; net.client.ledgerMaster.storeLedger(l); net.client.replayer.replay(InboundLedger::Reason::GENERIC, finalHash, totalReplay); @@ -1290,7 +1291,7 @@ struct LedgerReplayer_test : public beast::unit_test::suite testLedgerReplayOverlap() { testcase("Overlap tasks"); - int totalReplay = 5; + int const totalReplay = 5; NetworkOfTwo net( *this, {(totalReplay * 3) + 1}, @@ -1298,7 +1299,7 @@ struct LedgerReplayer_test : public beast::unit_test::suite InboundLedgersBehavior::Good, PeerFeature::LedgerReplayEnabled); auto l = net.server.ledgerMaster.getClosedLedger(); - uint256 finalHash = l->header().hash; + uint256 const finalHash = l->header().hash; net.client.replayer.replay(InboundLedger::Reason::GENERIC, finalHash, totalReplay); std::vector deltaStatuses(totalReplay - 1, TaskStatus::Completed); BEAST_EXPECT(net.client.waitAndCheckStatus( @@ -1388,7 +1389,7 @@ struct LedgerReplayerTimeout_test : public beast::unit_test::suite testSkipListTimeout() { testcase("SkipListAcquire timeout"); - int totalReplay = 3; + int const totalReplay = 3; NetworkOfTwo net( *this, {totalReplay + 1}, @@ -1397,10 +1398,10 @@ struct LedgerReplayerTimeout_test : public beast::unit_test::suite PeerFeature::LedgerReplayEnabled); auto l = net.server.ledgerMaster.getClosedLedger(); - uint256 finalHash = l->header().hash; + uint256 const finalHash = l->header().hash; net.client.replayer.replay(InboundLedger::Reason::GENERIC, finalHash, totalReplay); - std::vector deltaStatuses; + std::vector const deltaStatuses; BEAST_EXPECT(net.client.waitAndCheckStatus( finalHash, totalReplay, TaskStatus::Failed, TaskStatus::Failed, deltaStatuses)); @@ -1414,7 +1415,7 @@ struct LedgerReplayerTimeout_test : public beast::unit_test::suite testLedgerDeltaTimeout() { testcase("LedgerDeltaAcquire timeout"); - int totalReplay = 3; + int const totalReplay = 3; NetworkOfTwo net( *this, {totalReplay + 1}, @@ -1423,7 +1424,7 @@ struct LedgerReplayerTimeout_test : public beast::unit_test::suite PeerFeature::LedgerReplayEnabled); auto l = net.server.ledgerMaster.getClosedLedger(); - uint256 finalHash = l->header().hash; + uint256 const finalHash = l->header().hash; net.client.ledgerMaster.storeLedger(l); net.client.replayer.replay(InboundLedger::Reason::GENERIC, finalHash, totalReplay); @@ -1452,8 +1453,8 @@ struct LedgerReplayerLong_test : public beast::unit_test::suite run() override { testcase("Acquire 1000 ledgers"); - int totalReplay = 250; - int rounds = 4; + int const totalReplay = 250; + int const rounds = 4; NetworkOfTwo net( *this, {(totalReplay * rounds) + 1}, @@ -1479,7 +1480,7 @@ struct LedgerReplayerLong_test : public beast::unit_test::suite InboundLedger::Reason::GENERIC, finishHashes[i], totalReplay); } - std::vector deltaStatuses(totalReplay - 1, TaskStatus::Completed); + std::vector const deltaStatuses(totalReplay - 1, TaskStatus::Completed); for (int i = 0; i < rounds; ++i) { BEAST_EXPECT(net.client.waitAndCheckStatus( diff --git a/src/test/app/LendingHelpers_test.cpp b/src/test/app/LendingHelpers_test.cpp index 24661c18fb..56db553583 100644 --- a/src/test/app/LendingHelpers_test.cpp +++ b/src/test/app/LendingHelpers_test.cpp @@ -593,7 +593,7 @@ class LendingHelpers_test : public beast::unit_test::suite using namespace jtx; using namespace xrpl::detail; - Env env{*this}; + Env const env{*this}; Account const issuer{"issuer"}; PrettyAsset const asset = issuer["USD"]; std::int32_t const loanScale = -5; @@ -680,7 +680,7 @@ class LendingHelpers_test : public beast::unit_test::suite using namespace jtx; using namespace xrpl::detail; - Env env{*this}; + Env const env{*this}; Account const issuer{"issuer"}; PrettyAsset const asset = issuer["USD"]; std::int32_t const loanScale = -5; @@ -773,7 +773,7 @@ class LendingHelpers_test : public beast::unit_test::suite using namespace jtx; using namespace xrpl::detail; - Env env{*this}; + Env const env{*this}; Account const issuer{"issuer"}; PrettyAsset const asset = issuer["USD"]; std::int32_t const loanScale = -5; @@ -872,7 +872,7 @@ class LendingHelpers_test : public beast::unit_test::suite using namespace jtx; using namespace xrpl::detail; - Env env{*this}; + Env const env{*this}; Account const issuer{"issuer"}; PrettyAsset const asset = issuer["USD"]; std::int32_t const loanScale = -5; @@ -979,7 +979,7 @@ class LendingHelpers_test : public beast::unit_test::suite using namespace jtx; using namespace xrpl::detail; - Env env{*this}; + Env const env{*this}; Account const issuer{"issuer"}; PrettyAsset const asset = issuer["USD"]; std::int32_t const loanScale = -5; @@ -1086,7 +1086,7 @@ class LendingHelpers_test : public beast::unit_test::suite using namespace jtx; using namespace xrpl::detail; - Env env{*this}; + Env const env{*this}; Account const issuer{"issuer"}; PrettyAsset const asset = issuer["USD"]; std::int32_t const loanScale = -5; diff --git a/src/test/app/LoadFeeTrack_test.cpp b/src/test/app/LoadFeeTrack_test.cpp index fed76288ef..68ebcc70a1 100644 --- a/src/test/app/LoadFeeTrack_test.cpp +++ b/src/test/app/LoadFeeTrack_test.cpp @@ -13,7 +13,7 @@ public: run() override { Config d; // get a default configuration object - LoadFeeTrack l; + LoadFeeTrack const l; { Fees const fees = [&]() { Fees f; diff --git a/src/test/app/LoanBroker_test.cpp b/src/test/app/LoanBroker_test.cpp index 361f70209f..f7222aa61a 100644 --- a/src/test/app/LoanBroker_test.cpp +++ b/src/test/app/LoanBroker_test.cpp @@ -31,7 +31,7 @@ class LoanBroker_test : public beast::unit_test::suite // Try to create a vault PrettyAsset const asset{xrpIssue(), 1'000'000}; - Vault vault{env}; + Vault const vault{env}; auto const [tx, keylet] = vault.create({.owner = alice, .asset = asset}); env(tx, ter(goodVault ? ter(tesSUCCESS) : ter(temDISABLED))); env.close(); @@ -493,14 +493,14 @@ class LoanBroker_test : public beast::unit_test::suite // MPT. That'll require three corresponding SAVs. Env env(*this, all); - Account issuer{"issuer"}; + Account const issuer{"issuer"}; // For simplicity, alice will be the sole actor for the vault & brokers. Account alice{"alice"}; // Evan will attempt to be naughty Account evan{"evan"}; // Bystander doesn't have anything to do with the SAV or Broker, or any // of the relevant tokens - Account bystander{"bystander"}; + Account const bystander{"bystander"}; Vault vault{env}; // Fund the accounts and trust lines with the same amount so that tests @@ -807,7 +807,7 @@ class LoanBroker_test : public beast::unit_test::suite Account const issuer{"issuer"}; Account const alice{"alice"}; Env env(*this); - Vault vault{env}; + Vault const vault{env}; env.fund(XRP(100'000), issuer, alice); env.close(); @@ -1070,7 +1070,7 @@ class LoanBroker_test : public beast::unit_test::suite env(jtx, ter(temINVALID)); // holder == beast::zero - STAmount bad(Issue{USD.currency, beast::zero}, 100); + STAmount const bad(Issue{USD.currency, beast::zero}, 100); jtx.jv[sfAmount] = bad.getJson(); jtx.stx = env.ust(jtx); Serializer s; @@ -1091,7 +1091,7 @@ class LoanBroker_test : public beast::unit_test::suite // MPTCanClawback is not set testLoanBroker( [&](Env& env, Account const& issuer, Account const& alice) -> MPT { - MPTTester mpt({.env = env, .issuer = issuer, .holders = {alice}}); + MPTTester const mpt({.env = env, .issuer = issuer, .holders = {alice}}); return mpt; }, CoverClawback); @@ -1171,7 +1171,7 @@ class LoanBroker_test : public beast::unit_test::suite // Create a Vault owned by alice with an XRP asset PrettyAsset const asset{xrpIssue(), 1}; - Vault vault{env}; + Vault const vault{env}; auto const [createTx, vaultKeylet] = vault.create({.owner = alice, .asset = asset}); env(createTx); env.close(); @@ -1193,7 +1193,7 @@ class LoanBroker_test : public beast::unit_test::suite // vault SLE OpenView ov{*env.current()}; test::StreamSink sink{beast::severities::kWarning}; - beast::Journal jlog{sink}; + beast::Journal const jlog{sink}; ApplyContext ac{env.app(), ov, tx, tesSUCCESS, env.current()->fees().base, tapNONE, jlog}; if (auto sleBroker = ac.view().peek(keylet::loanbroker(brokerKeylet.key))) @@ -1207,7 +1207,7 @@ class LoanBroker_test : public beast::unit_test::suite // Invoke preclaim against the mutated (ApplyView) view; triggers // nullptr deref - PreclaimContext pctx{env.app(), ac.view(), tesSUCCESS, tx, tapNONE, jlog}; + PreclaimContext const pctx{env.app(), ac.view(), tesSUCCESS, tx, tapNONE, jlog}; (void)LoanBrokerCoverDeposit::preclaim(pctx); } @@ -1326,7 +1326,7 @@ class LoanBroker_test : public beast::unit_test::suite Account const issuer{"issuer"}; Account const alice{"alice"}; Env env(*this); - Vault vault{env}; + Vault const vault{env}; env.fund(XRP(100'000), issuer, alice); env.close(); @@ -1348,7 +1348,7 @@ class LoanBroker_test : public beast::unit_test::suite env(tx); env.close(); auto const le = env.le(vaultKeylet); - VaultInfo vaultInfo = [&]() { + VaultInfo const vaultInfo = [&]() { if (BEAST_EXPECT(le)) return VaultInfo{asset, vaultKeylet.key, le->at(sfAccount)}; return VaultInfo{asset, {}, {}}; @@ -1438,7 +1438,7 @@ class LoanBroker_test : public beast::unit_test::suite auto const [token, deposit, err] = getToken(env); - Vault vault(env); + Vault const vault(env); auto const [tx, keylet] = vault.create({.owner = broker, .asset = token.asset()}); env(tx); env.close(); @@ -1466,7 +1466,7 @@ class LoanBroker_test : public beast::unit_test::suite std::optional, // max amount std::uint64_t, // deposit amount TER>> // expected error - mptTests = { + const mptTests = { // issuer can issue up to 2'000 tokens {2'000, 4'000, 1'000, tesSUCCESS}, // issuer can issue 500 tokens (250 VaultDeposit + @@ -1509,7 +1509,7 @@ class LoanBroker_test : public beast::unit_test::suite env.fund(XRP(20'000), issuer, lender, borrower); auto const IOU = issuer["IOU"]; - Vault vault{env}; + Vault const vault{env}; auto [tx, vaultKeylet] = vault.create({.owner = lender, .asset = IOU.asset()}); env(tx); env.close(); @@ -1597,7 +1597,7 @@ class LoanBroker_test : public beast::unit_test::suite env(pay(issuer, broker, token(2'000))); env.close(); - Vault vault(env); + Vault const vault(env); auto const [tx, keylet] = vault.create({.owner = broker, .asset = token.asset()}); env(tx); env.close(); @@ -1718,7 +1718,7 @@ class LoanBroker_test : public beast::unit_test::suite auto const& token = *maybeToken; - Vault vault(env); + Vault const vault(env); auto const [tx, keylet] = vault.create({.owner = broker, .asset = token.asset()}); env(tx); env.close(); diff --git a/src/test/app/Loan_test.cpp b/src/test/app/Loan_test.cpp index 4cdc62853c..a63d31f030 100644 --- a/src/test/app/Loan_test.cpp +++ b/src/test/app/Loan_test.cpp @@ -87,7 +87,7 @@ protected: Number maxCoveredLoanValue(Number const& currentDebt) const { - NumberRoundModeGuard mg(Number::downward); + NumberRoundModeGuard const mg(Number::downward); auto debtLimit = coverDeposit * tenthBipsPerUnity.value() / coverRateMin.value(); return debtLimit - currentDebt; @@ -429,7 +429,7 @@ protected: { using namespace jtx; - Vault vault{env}; + Vault const vault{env}; auto const deposit = asset(params.vaultDeposit); auto const debtMaximumValue = asset(params.debtMax).value(); @@ -520,7 +520,7 @@ protected: : std::max(broker.vaultScale(env), state.principalOutstanding.exponent()))); BEAST_EXPECT(state.paymentInterval == 600); { - NumberRoundModeGuard mg(Number::upward); + NumberRoundModeGuard const mg(Number::upward); BEAST_EXPECT( state.totalValue == roundToAsset( @@ -1149,7 +1149,7 @@ protected: auto loanKeylet = std::get(*loanResult); auto pseudoAcct = std::get(*loanResult); - VerifyLoanStatus verifyLoanStatus(env, broker, pseudoAcct, loanKeylet); + VerifyLoanStatus const verifyLoanStatus(env, broker, pseudoAcct, loanKeylet); makeLoanPayments( env, @@ -1822,7 +1822,7 @@ protected: std::function, TER> { // Freeze / lock the asset - std::function empty; + std::function const empty; if (broker.asset.native()) { // XRP can't be frozen @@ -1943,7 +1943,7 @@ protected: ? 0 : std::max( broker.vaultScale(env), state.principalOutstanding.exponent()))); - NumberRoundModeGuard mg(Number::upward); + NumberRoundModeGuard const mg(Number::upward); auto const defaultAmount = roundToAsset( broker.asset, std::min( @@ -2235,7 +2235,7 @@ protected: // service fee is 2 auto const startingPayments = state.paymentRemaining; STAmount const payoffAmount = [&]() { - NumberRoundModeGuard mg(Number::upward); + NumberRoundModeGuard const mg(Number::upward); auto const rawPayoff = startingPayments * (state.periodicPayment + broker.asset(2).value()); STAmount payoffAmount{broker.asset, rawPayoff}; @@ -2835,7 +2835,7 @@ protected: {.flags = tfMPTCanTransfer | tfMPTCanLock | (args.requireAuth ? tfMPTRequireAuth : none)}); env.close(); - PrettyAsset mptAsset = mptt.issuanceID(); + PrettyAsset const mptAsset = mptt.issuanceID(); mptt.authorize({.account = lender}); mptt.authorize({.account = borrower}); env.close(); @@ -2962,7 +2962,7 @@ protected: CaseArgs{.requireAuth = true}); auto const [acctReserve, incReserve] = [this]() -> std::pair { - Env env{*this, testable_amendments()}; + Env const env{*this, testable_amendments()}; return { env.current()->fees().accountReserve(0).drops() / DROPS_PER_XRP.drops(), env.current()->fees().increment.drops() / DROPS_PER_XRP.drops()}; @@ -3247,7 +3247,7 @@ protected: jtx::Account const alice{"alice"}; jtx::Account const bella{"bella"}; auto const msigSetup = [&](Env& env, Account const& account) { - Json::Value tx1 = signers(account, 2, {{alice, 1}, {bella, 1}}); + Json::Value const tx1 = signers(account, 2, {{alice, 1}, {bella, 1}}); env(tx1); env.close(); }; @@ -3314,7 +3314,7 @@ protected: [&, this](Env& env, BrokerInfo const& broker, auto&) { using namespace loan; Number const principalRequest = broker.asset(1'000).value(); - Vault vault{env}; + Vault const vault{env}; auto tx = vault.set({.owner = lender, .id = broker.vaultID}); tx[sfAssetsMaximum] = BrokerParameters::defaults().vaultDeposit; env(tx); @@ -3334,7 +3334,7 @@ protected: [&, this](Env& env, BrokerInfo const& broker, auto&) { using namespace loan; Number const principalRequest = broker.asset(1'000).value(); - Vault vault{env}; + Vault const vault{env}; auto tx = vault.set({.owner = lender, .id = broker.vaultID}); tx[sfAssetsMaximum] = BrokerParameters::defaults().vaultDeposit + broker.asset(1).number(); @@ -3601,13 +3601,13 @@ protected: Account const lender{"lender"}; Account const borrower{"borrower"}; - BrokerParameters brokerParams; + BrokerParameters const brokerParams; env.fund(XRP(brokerParams.vaultDeposit * 100), lender, borrower); env.close(); PrettyAsset const xrpAsset{xrpIssue(), 1'000'000}; - BrokerInfo broker{createVaultAndBroker(env, xrpAsset, lender, brokerParams)}; + BrokerInfo const broker{createVaultAndBroker(env, xrpAsset, lender, brokerParams)}; using namespace loan; @@ -3664,13 +3664,13 @@ protected: Account const issuer{"issuer"}; Account const lender{"lender"}; - BrokerParameters brokerParams{.debtMax = 0}; + BrokerParameters const brokerParams{.debtMax = 0}; env.fund(XRP(brokerParams.vaultDeposit * 100), issuer, noripple(lender)); env.close(); PrettyAsset const xrpAsset{xrpIssue(), 1'000'000}; - BrokerInfo broker{createVaultAndBroker(env, xrpAsset, lender, brokerParams)}; + BrokerInfo const broker{createVaultAndBroker(env, xrpAsset, lender, brokerParams)}; if (auto const brokerSle = env.le(keylet::loanbroker(broker.brokerID)); BEAST_EXPECT(brokerSle)) @@ -3712,12 +3712,12 @@ protected: Account const lender{"lender"}; Account const borrower{"borrower"}; - BrokerParameters brokerParams; + BrokerParameters const brokerParams; env.fund(XRP(brokerParams.vaultDeposit * 100), issuer, lender, borrower); env.close(); PrettyAsset const xrpAsset{xrpIssue(), 1'000'000}; - BrokerInfo broker{createVaultAndBroker(env, xrpAsset, lender, brokerParams)}; + BrokerInfo const broker{createVaultAndBroker(env, xrpAsset, lender, brokerParams)}; using namespace loan; @@ -3786,9 +3786,9 @@ protected: Account const alice{"alice"}; std::string const borrowerPass = "borrower"; - Account borrower{borrowerPass, KeyType::ed25519}; + Account const borrower{borrowerPass, KeyType::ed25519}; auto const lenderPass = "lender"; - Account lender{lenderPass, KeyType::ed25519}; + Account const lender{lenderPass, KeyType::ed25519}; env.fund(XRP(1'000'000), alice, lender, borrower); env.close(); @@ -4169,7 +4169,8 @@ protected: env.fund(XRP(1'000), issuer, lender); std::int64_t constexpr issuerBalance = 10'000'000; - MPTTester asset({.env = env, .issuer = issuer, .holders = {lender}, .pay = issuerBalance}); + MPTTester const asset( + {.env = env, .issuer = issuer, .holders = {lender}, .pay = issuerBalance}); BrokerParameters const brokerParams{ .debtMax = 200, @@ -4319,7 +4320,7 @@ protected: env.fund(XRP(1'000), lender, issuer, borrower); env(trust(lender, IOU(10'000'000))); env(pay(issuer, lender, IOU(5'000'000))); - BrokerInfo brokerInfo{createVaultAndBroker(env, issuer["IOU"], lender)}; + BrokerInfo const brokerInfo{createVaultAndBroker(env, issuer["IOU"], lender)}; auto const loanSetFee = fee(env.current()->fees().base * 2); Number const debtMaximumRequest = brokerInfo.asset(1'000).value(); @@ -4381,7 +4382,7 @@ protected: // can it happen? the signature is checked before transactor // executes - JTx tx = env.jt( + JTx const tx = env.jt( set(borrower, brokerInfo.brokerID, debtMaximumRequest), sig(sfCounterpartySignature, lender), loanSetFee); @@ -4470,7 +4471,7 @@ protected: env(pay(issuer, borrower, mptAsset(1'000))); env.close(); - BrokerInfo broker{createVaultAndBroker(env, mptAsset, lender)}; + BrokerInfo const broker{createVaultAndBroker(env, mptAsset, lender)}; using namespace loan; @@ -4573,7 +4574,7 @@ protected: return Account("Broker pseudo-account", brokerPseudo); }(); - VerifyLoanStatus verifyLoanStatus(env, broker, pseudoAcct, keylet); + VerifyLoanStatus const verifyLoanStatus(env, broker, pseudoAcct, keylet); auto const originalState = getCurrentState(env, broker, keylet); verifyLoanStatus(originalState); @@ -4624,7 +4625,7 @@ protected: env(payIssuerTx); env.close(); - BrokerInfo broker{createVaultAndBroker(env, iouAsset, lender)}; + BrokerInfo const broker{createVaultAndBroker(env, iouAsset, lender)}; using namespace loan; @@ -4686,7 +4687,7 @@ protected: env(pay(issuer, borrower, iouAsset(1'000))); env.close(); - BrokerInfo broker{createVaultAndBroker(env, iouAsset, lender)}; + BrokerInfo const broker{createVaultAndBroker(env, iouAsset, lender)}; using namespace loan; @@ -4768,7 +4769,7 @@ protected: env(payIssuerTx); env.close(); - BrokerInfo broker{createVaultAndBroker(env, iouAsset, lender)}; + BrokerInfo const broker{createVaultAndBroker(env, iouAsset, lender)}; using namespace loan; @@ -4867,7 +4868,7 @@ protected: env(payIssuerTx); env.close(); - BrokerInfo broker{createVaultAndBroker(env, iouAsset, lender)}; + BrokerInfo const broker{createVaultAndBroker(env, iouAsset, lender)}; { auto const coverDepositValue = broker.asset(broker.params.coverDeposit * 10).value(); env(loanBroker::coverDeposit(lender, broker.brokerID, coverDepositValue)); @@ -5155,7 +5156,7 @@ protected: // pay all but the last payment { - NumberRoundModeGuard mg{Number::upward}; + NumberRoundModeGuard const mg{Number::upward}; Number const payment = beforeState.periodicPayment * (total - 1); XRPAmount const payFee{baseFee * ((total - 1) / loanPaymentsPerFeeIncrement + 1)}; STAmount const paymentAmount = @@ -5259,7 +5260,7 @@ protected: env(pay(issuer, alice, asset(100))); env.close(); - Vault vault{env}; + Vault const vault{env}; auto const [createTx, vaultKeylet] = vault.create({.owner = alice, .asset = asset}); env(createTx); env.close(); @@ -5595,7 +5596,7 @@ protected: env.close(); PrettyAsset const asset{xrpIssue(), 1'000'000}; - BrokerParameters brokerParams{}; + BrokerParameters const brokerParams{}; auto const broker = createVaultAndBroker(env, asset, lender, brokerParams); // Create a 3-payment loan so full-payment path is enabled after 1 @@ -5792,10 +5793,10 @@ protected: Env env(*this, all); // Setup: Create accounts - Account issuer{"issuer"}; - Account lender{"lender"}; - Account borrower{"borrower"}; - Account victim{"victim"}; + Account const issuer{"issuer"}; + Account const lender{"lender"}; + Account const borrower{"borrower"}; + Account const victim{"victim"}; env.fund(XRP(1'000'000'00), issuer, lender, borrower, victim); env.close(); @@ -5810,7 +5811,7 @@ protected: env(pay(issuer, victim, asset(50000))); env.close(); - BrokerParameters brokerParams{ + BrokerParameters const brokerParams{ .vaultDeposit = 10000, .debtMax = Number{0}, .coverRateMin = TenthBips32{1000}, @@ -5838,8 +5839,8 @@ protected: { auto const vaultSle = env.le(vaultKeylet); - Number assetsTotal = vaultSle->at(sfAssetsTotal); - Number assetsAvail = vaultSle->at(sfAssetsAvailable); + Number const assetsTotal = vaultSle->at(sfAssetsTotal); + Number const assetsAvail = vaultSle->at(sfAssetsAvailable); log << "Before loan creation:" << std::endl; log << " AssetsTotal: " << assetsTotal << std::endl; @@ -5871,8 +5872,8 @@ protected: { auto const vaultSle = env.le(vaultKeylet); - Number assetsTotal = vaultSle->at(sfAssetsTotal); - Number assetsAvail = vaultSle->at(sfAssetsAvailable); + Number const assetsTotal = vaultSle->at(sfAssetsTotal); + Number const assetsAvail = vaultSle->at(sfAssetsAvailable); log << "After loan creation:" << std::endl; log << " AssetsTotal: " << assetsTotal << std::endl; @@ -5909,8 +5910,8 @@ protected: // Step 8: Verify phantom assets created { auto const vaultSle2 = env.le(vaultKeylet); - Number assetsTotal2 = vaultSle2->at(sfAssetsTotal); - Number assetsAvail2 = vaultSle2->at(sfAssetsAvailable); + Number const assetsTotal2 = vaultSle2->at(sfAssetsTotal); + Number const assetsAvail2 = vaultSle2->at(sfAssetsAvailable); log << "After default:" << std::endl; log << " AssetsTotal: " << assetsTotal2 << std::endl; @@ -6033,7 +6034,7 @@ protected: auto loanKeylet = std::get(*loanResult); auto pseudoAcct = std::get(*loanResult); - VerifyLoanStatus verifyLoanStatus(env, broker, pseudoAcct, loanKeylet); + VerifyLoanStatus const verifyLoanStatus(env, broker, pseudoAcct, loanKeylet); if (auto const brokerSle = env.le(broker.brokerKeylet()); BEAST_EXPECT(brokerSle)) { @@ -6077,7 +6078,7 @@ protected: auto const txfee = fee(XRP(100)); Env env(*this); - Vault vault(env); + Vault const vault(env); env.fund(XRP(10'000), lender, issuer, borrower, depositor); env.close(); @@ -6137,7 +6138,7 @@ protected: env.close(); // Vault with XRP asset - Vault vault{env}; + Vault const vault{env}; auto [vaultCreate, vaultKeylet] = vault.create({.owner = lender, .asset = xrpIssue()}); env(vaultCreate); env.close(); @@ -6239,7 +6240,7 @@ protected: auto loanKeylet = std::get(*loanResult); auto pseudoAcct = std::get(*loanResult); - VerifyLoanStatus verifyLoanStatus(env, broker, pseudoAcct, loanKeylet); + VerifyLoanStatus const verifyLoanStatus(env, broker, pseudoAcct, loanKeylet); makeLoanPayments( env, @@ -6266,7 +6267,7 @@ protected: auto testLoanAsset = [&](auto&& getMaxDebt, auto const& borrower) { Env env(*this); - Vault vault(env); + Vault const vault(env); if (borrower == broker) { @@ -6359,7 +6360,7 @@ protected: borrowerAcct); testLoanAsset( [&](Env& env) -> STAmount { - MPTTester mpt( + MPTTester const mpt( {.env = env, .issuer = issuer, .holders = {broker, depositor}, @@ -6403,7 +6404,7 @@ protected: auto loanKeylet = std::get(*loanResult); auto pseudoAcct = std::get(*loanResult); - VerifyLoanStatus verifyLoanStatus(env, broker, pseudoAcct, loanKeylet); + VerifyLoanStatus const verifyLoanStatus(env, broker, pseudoAcct, loanKeylet); makeLoanPayments( env, @@ -6459,7 +6460,7 @@ protected: auto loanKeylet = std::get(*loanResult); auto pseudoAcct = std::get(*loanResult); - VerifyLoanStatus verifyLoanStatus(env, broker, pseudoAcct, loanKeylet); + VerifyLoanStatus const verifyLoanStatus(env, broker, pseudoAcct, loanKeylet); auto const state = getCurrentState(env, broker, loanKeylet); @@ -6470,7 +6471,7 @@ protected: tfLoanOverpayment)); env.close(); - PaymentParameters paymentParams{ + PaymentParameters const paymentParams{ .showStepBalances = false, .validateBalances = true, }; @@ -7077,20 +7078,20 @@ protected: Account const borrower("borrower"); // Determine all the random parameters at once - AssetType assetType = static_cast(assetDist(engine_)); + AssetType const assetType = static_cast(assetDist(engine_)); auto const principalRequest = principalDist(engine_); - TenthBips16 managementFeeRate{managementFeeRateDist(engine_)}; + TenthBips16 const managementFeeRate{managementFeeRateDist(engine_)}; auto const serviceFee = serviceFeeDist(engine_); TenthBips32 interest{interestRateDist(engine_)}; auto const payTotal = paymentTotalDist(engine_); auto const payInterval = paymentIntervalDist(engine_); - BrokerParameters brokerParams{ + BrokerParameters const brokerParams{ .vaultDeposit = principalRequest * 10, .debtMax = 0, .coverRateMin = TenthBips32{0}, .managementFeeRate = managementFeeRate}; - LoanParameters loanParams{ + LoanParameters const loanParams{ .account = lender, .counter = borrower, .principalRequest = principalRequest, @@ -7108,7 +7109,7 @@ public: run() override { auto const numIterations = [s = arg()]() -> int { - int defaultNum = 5; + int const defaultNum = 5; if (s.empty()) return defaultNum; try diff --git a/src/test/app/MPToken_test.cpp b/src/test/app/MPToken_test.cpp index 5a90a3a71e..6e94ffd9bc 100644 --- a/src/test/app/MPToken_test.cpp +++ b/src/test/app/MPToken_test.cpp @@ -827,7 +827,7 @@ class MPToken_test : public beast::unit_test::suite env.fund(XRP(1'000), alice); env.fund(XRP(1'000), bob); - STAmount mpt{MPTIssue{makeMptID(1, alice)}, UINT64_C(100)}; + STAmount const mpt{MPTIssue{makeMptID(1, alice)}, UINT64_C(100)}; env(pay(alice, bob, mpt), ter(temDISABLED)); } @@ -841,7 +841,7 @@ class MPToken_test : public beast::unit_test::suite env.fund(XRP(1'000), alice); env.fund(XRP(1'000), carol); - STAmount mpt{MPTIssue{makeMptID(1, alice)}, UINT64_C(100)}; + STAmount const mpt{MPTIssue{makeMptID(1, alice)}, UINT64_C(100)}; Json::Value jv; jv[jss::secret] = alice.name(); @@ -1457,7 +1457,7 @@ class MPToken_test : public beast::unit_test::suite { Env env{*this, features}; env.fund(XRP(1'000), alice, bob); - STAmount mpt{MPTIssue{makeMptID(1, alice)}, UINT64_C(100)}; + STAmount const mpt{MPTIssue{makeMptID(1, alice)}, UINT64_C(100)}; Json::Value jv; jv[jss::secret] = alice.name(); jv[jss::tx_json] = pay(alice, bob, mpt); @@ -1805,7 +1805,7 @@ class MPToken_test : public beast::unit_test::suite Account const alice("alice"); auto const USD = alice["USD"]; Account const carol("carol"); - MPTIssue issue(makeMptID(1, alice)); + MPTIssue const issue(makeMptID(1, alice)); STAmount mpt{issue, UINT64_C(100)}; auto const jvb = bridge(alice, USD, alice, USD); for (auto const& feature : {features, features - featureMPTokensV1}) @@ -2876,7 +2876,7 @@ class MPToken_test : public beast::unit_test::suite mptAlice.create( {.metadata = "test", .ownerCount = 1, .mutableFlags = tmfMPTCanMutateMetadata}); - std::vector metadatas = { + std::vector const metadatas = { "mutate metadata", "mutate metadata 2", "mutate metadata 3", diff --git a/src/test/app/Manifest_test.cpp b/src/test/app/Manifest_test.cpp index 92a10ef7fa..c2f789e80c 100644 --- a/src/test/app/Manifest_test.cpp +++ b/src/test/app/Manifest_test.cpp @@ -249,8 +249,9 @@ public: { // save should store all trusted master keys to db std::vector s1; - std::vector keys; + std::vector const keys; s1.reserve(inManifests.size()); + for (auto const& man : inManifests) s1.push_back(toBase58(TokenType::NodePublic, man->masterKey)); unl->load({}, s1, keys); @@ -602,12 +603,12 @@ public: BEAST_EXPECT(!deserializeManifest(toString(st))); } { // invalid manifest (domain too long) - std::string s(254, 'a'); + std::string const s(254, 'a'); auto const st = buildManifestObject(++sequence, s + ".example.com"); BEAST_EXPECT(!deserializeManifest(toString(st))); } { // invalid manifest (domain component too long) - std::string s(72, 'a'); + std::string const s(72, 'a'); auto const st = buildManifestObject(++sequence, s + ".example.com"); BEAST_EXPECT(!deserializeManifest(toString(st))); } diff --git a/src/test/app/MultiSign_test.cpp b/src/test/app/MultiSign_test.cpp index 2bdfec2e9d..7a5a49ca9b 100644 --- a/src/test/app/MultiSign_test.cpp +++ b/src/test/app/MultiSign_test.cpp @@ -63,7 +63,7 @@ public: { // Attach a signer list to alice. Should fail. - Json::Value signersList = signers(alice, 1, {{bogie, 1}}); + Json::Value const signersList = signers(alice, 1, {{bogie, 1}}); env(signersList, ter(tecINSUFFICIENT_RESERVE)); env.close(); env.require(owners(alice, 0)); @@ -81,7 +81,7 @@ public: env(pay(env.master, alice, fee - drops(1))); // Replace with the biggest possible signer list. Should fail. - Json::Value bigSigners = signers( + Json::Value const bigSigners = signers( alice, 1, {{bogie, 1}, @@ -1012,7 +1012,7 @@ public: auto const baseFee = env.current()->fees().base; { // Single-sign, but leave an empty SigningPubKey. - JTx tx = env.jt(noop(alice), sig(alice)); + JTx const tx = env.jt(noop(alice), sig(alice)); STTx local = *(tx.stx); local.setFieldVL(sfSigningPubKey, Blob()); // Empty SigningPubKey auto const info = submitSTTx(local); @@ -1022,7 +1022,7 @@ public: } { // Single-sign, but invalidate the signature. - JTx tx = env.jt(noop(alice), sig(alice)); + JTx const tx = env.jt(noop(alice), sig(alice)); STTx local = *(tx.stx); // Flip some bits in the signature. auto badSig = local.getFieldVL(sfTxnSignature); @@ -1036,7 +1036,7 @@ public: } { // Single-sign, but invalidate the sequence number. - JTx tx = env.jt(noop(alice), sig(alice)); + JTx const tx = env.jt(noop(alice), sig(alice)); STTx local = *(tx.stx); // Flip some bits in the signature. auto seq = local.getFieldU32(sfSequence); @@ -1049,7 +1049,7 @@ public: } { // Multisign, but leave a nonempty sfSigningPubKey. - JTx tx = env.jt(noop(alice), fee(2 * baseFee), msig(bogie)); + JTx const tx = env.jt(noop(alice), fee(2 * baseFee), msig(bogie)); STTx local = *(tx.stx); local[sfSigningPubKey] = alice.pk(); // Insert sfSigningPubKey auto const info = submitSTTx(local); @@ -1059,7 +1059,7 @@ public: } { // Both multi- and single-sign with an empty SigningPubKey. - JTx tx = env.jt(noop(alice), fee(2 * baseFee), msig(bogie)); + JTx const tx = env.jt(noop(alice), fee(2 * baseFee), msig(bogie)); STTx local = *(tx.stx); local.sign(alice.pk(), alice.sk()); local.setFieldVL(sfSigningPubKey, Blob()); // Empty SigningPubKey @@ -1070,7 +1070,7 @@ public: } { // Multisign but invalidate one of the signatures. - JTx tx = env.jt(noop(alice), fee(2 * baseFee), msig(bogie)); + JTx const tx = env.jt(noop(alice), fee(2 * baseFee), msig(bogie)); STTx local = *(tx.stx); // Flip some bits in the signature. auto& signer = local.peekFieldArray(sfSigners).back(); @@ -1085,7 +1085,7 @@ public: } { // Multisign with an empty signers array should fail. - JTx tx = env.jt(noop(alice), fee(2 * baseFee), msig(bogie)); + JTx const tx = env.jt(noop(alice), fee(2 * baseFee), msig(bogie)); STTx local = *(tx.stx); local.peekFieldArray(sfSigners).clear(); // Empty Signers array. auto const info = submitSTTx(local); @@ -1094,7 +1094,7 @@ public: "fails local checks: Invalid Signers array size."); } { - JTx tx = env.jt( + JTx const tx = env.jt( noop(alice), fee(2 * baseFee), @@ -1132,7 +1132,7 @@ public: bogie, bogie, bogie)); - STTx local = *(tx.stx); + STTx const local = *(tx.stx); auto const info = submitSTTx(local); BEAST_EXPECT( info[jss::result][jss::error_exception] == @@ -1140,8 +1140,8 @@ public: } { // The account owner may not multisign for themselves. - JTx tx = env.jt(noop(alice), fee(2 * baseFee), msig(alice)); - STTx local = *(tx.stx); + JTx const tx = env.jt(noop(alice), fee(2 * baseFee), msig(alice)); + STTx const local = *(tx.stx); auto const info = submitSTTx(local); BEAST_EXPECT( info[jss::result][jss::error_exception] == @@ -1149,8 +1149,8 @@ public: } { // No duplicate multisignatures allowed. - JTx tx = env.jt(noop(alice), fee(2 * baseFee), msig(bogie, bogie)); - STTx local = *(tx.stx); + JTx const tx = env.jt(noop(alice), fee(2 * baseFee), msig(bogie, bogie)); + STTx const local = *(tx.stx); auto const info = submitSTTx(local); BEAST_EXPECT( info[jss::result][jss::error_exception] == @@ -1158,7 +1158,7 @@ public: } { // Multisignatures must be submitted in sorted order. - JTx tx = env.jt(noop(alice), fee(2 * baseFee), msig(bogie, demon)); + JTx const tx = env.jt(noop(alice), fee(2 * baseFee), msig(bogie, demon)); STTx local = *(tx.stx); // Unsort the Signers array. auto& signers = local.peekFieldArray(sfSigners); diff --git a/src/test/app/NFTokenAuth_test.cpp b/src/test/app/NFTokenAuth_test.cpp index 551882b51a..0e3fb24305 100644 --- a/src/test/app/NFTokenAuth_test.cpp +++ b/src/test/app/NFTokenAuth_test.cpp @@ -33,9 +33,9 @@ public: using namespace test::jtx; Env env(*this, features); - Account G1{"G1"}; - Account A1{"A1"}; - Account A2{"A2"}; + Account const G1{"G1"}; + Account const A1{"A1"}; + Account const A2{"A2"}; auto const USD{G1["USD"]}; env.fund(XRP(10000), G1, A1, A2); @@ -88,7 +88,7 @@ public: Env env(*this, features); Account G1{"G1"}; Account A1{"A1"}; - Account A2{"A2"}; + Account const A2{"A2"}; auto const USD{G1["USD"]}; env.fund(XRP(10000), G1, A1, A2); @@ -134,7 +134,7 @@ public: Env env(*this, features); Account G1{"G1"}; Account A1{"A1"}; - Account A2{"A2"}; + Account const A2{"A2"}; auto const USD{G1["USD"]}; env.fund(XRP(10000), G1, A1, A2); @@ -190,9 +190,9 @@ public: using namespace test::jtx; Env env(*this, features); - Account G1{"G1"}; - Account A1{"A1"}; - Account A2{"A2"}; + Account const G1{"G1"}; + Account const A1{"A1"}; + Account const A2{"A2"}; auto const USD{G1["USD"]}; env.fund(XRP(10000), G1, A1, A2); @@ -267,7 +267,7 @@ public: Env env(*this, features); Account G1{"G1"}; Account A1{"A1"}; - Account A2{"A2"}; + Account const A2{"A2"}; auto const USD{G1["USD"]}; env.fund(XRP(10000), G1, A1, A2); @@ -307,10 +307,10 @@ public: using namespace test::jtx; Env env(*this, features); - Account G1{"G1"}; - Account A1{"A1"}; - Account A2{"A2"}; - Account broker{"broker"}; + Account const G1{"G1"}; + Account const A1{"A1"}; + Account const A2{"A2"}; + Account const broker{"broker"}; auto const USD{G1["USD"]}; env.fund(XRP(10000), G1, A1, A2, broker); @@ -375,8 +375,8 @@ public: Env env(*this, features); Account G1{"G1"}; Account A1{"A1"}; - Account A2{"A2"}; - Account broker{"broker"}; + Account const A2{"A2"}; + Account const broker{"broker"}; auto const USD{G1["USD"]}; env.fund(XRP(10000), G1, A1, A2, broker); @@ -433,10 +433,10 @@ public: using namespace test::jtx; Env env(*this, features); - Account G1{"G1"}; - Account A1{"A1"}; - Account A2{"A2"}; - Account broker{"broker"}; + Account const G1{"G1"}; + Account const A1{"A1"}; + Account const A2{"A2"}; + Account const broker{"broker"}; auto const USD{G1["USD"]}; env.fund(XRP(10000), G1, A1, A2, broker); @@ -507,10 +507,10 @@ public: using namespace test::jtx; Env env(*this, features); - Account G1{"G1"}; - Account minter{"minter"}; - Account A1{"A1"}; - Account A2{"A2"}; + Account const G1{"G1"}; + Account const minter{"minter"}; + Account const A1{"A1"}; + Account const A2{"A2"}; auto const USD{G1["USD"]}; env.fund(XRP(10000), G1, minter, A1, A2); diff --git a/src/test/app/NFTokenBurn_test.cpp b/src/test/app/NFTokenBurn_test.cpp index b91b245a7f..cd0df42c03 100644 --- a/src/test/app/NFTokenBurn_test.cpp +++ b/src/test/app/NFTokenBurn_test.cpp @@ -85,7 +85,7 @@ class NFTokenBurn_test : public beast::unit_test::suite if (state[i].isMember(sfNFTokens.jsonName) && state[i][sfNFTokens.jsonName].isArray()) { - std::uint32_t tokenCount = state[i][sfNFTokens.jsonName].size(); + std::uint32_t const tokenCount = state[i][sfNFTokens.jsonName].size(); std::cout << tokenCount << " NFtokens in page " << state[i][jss::index].asString() << std::endl; @@ -201,7 +201,7 @@ class NFTokenBurn_test : public beast::unit_test::suite { // We do the same work on alice and minter, so make a lambda. auto xferNFT = [&env, &becky](AcctStat& acct, auto& iter) { - uint256 offerIndex = keylet::nftoffer(acct.acct, env.seq(acct.acct)).key; + uint256 const offerIndex = keylet::nftoffer(acct.acct, env.seq(acct.acct)).key; env(token::createOffer(acct, *iter, XRP(0)), txflags(tfSellNFToken)); env.close(); env(token::acceptSellOffer(becky, offerIndex)); @@ -225,7 +225,7 @@ class NFTokenBurn_test : public beast::unit_test::suite // Next we'll create offers for all of those NFTs. This calls for // another lambda. auto addOffers = [&env](AcctStat& owner, AcctStat& other1, AcctStat& other2) { - for (uint256 nft : owner.nfts) + for (uint256 const nft : owner.nfts) { // Create sell offers for owner. env(token::createOffer(owner, nft, drops(1)), @@ -277,7 +277,7 @@ class NFTokenBurn_test : public beast::unit_test::suite // Decide which of the accounts should burn the nft. If the // owner is becky then any of the three accounts can burn. // Otherwise either alice or minter can burn. - AcctStat& burner = [&]() -> AcctStat& { + AcctStat const& burner = [&]() -> AcctStat& { if (owner.acct == becky.acct) return *(stats[acctDist(engine)]); return mintDist(engine) ? alice : minter; @@ -398,7 +398,7 @@ class NFTokenBurn_test : public beast::unit_test::suite // Generate three packed pages. Then burn the tokens in order from // first to last. This exercises specific cases where coalescing // pages is not possible. - std::vector nfts = genPackedTokens(); + std::vector const nfts = genPackedTokens(); BEAST_EXPECT(nftCount(env, alice) == 96); BEAST_EXPECT(ownerCount(env, alice) == 3); @@ -736,9 +736,9 @@ class NFTokenBurn_test : public beast::unit_test::suite // Create an ApplyContext we can use to run the invariant // checks. These variables must outlive the ApplyContext. OpenView ov{*env.current()}; - STTx tx{ttACCOUNT_SET, [](STObject&) {}}; + STTx const tx{ttACCOUNT_SET, [](STObject&) {}}; test::StreamSink sink{beast::severities::kWarning}; - beast::Journal jlog{sink}; + beast::Journal const jlog{sink}; ApplyContext ac{ env.app(), ov, tx, tesSUCCESS, env.current()->fees().base, tapNONE, jlog}; @@ -769,9 +769,9 @@ class NFTokenBurn_test : public beast::unit_test::suite // Create an ApplyContext we can use to run the invariant // checks. These variables must outlive the ApplyContext. OpenView ov{*env.current()}; - STTx tx{ttACCOUNT_SET, [](STObject&) {}}; + STTx const tx{ttACCOUNT_SET, [](STObject&) {}}; test::StreamSink sink{beast::severities::kWarning}; - beast::Journal jlog{sink}; + beast::Journal const jlog{sink}; ApplyContext ac{ env.app(), ov, tx, tesSUCCESS, env.current()->fees().base, tapNONE, jlog}; @@ -1114,7 +1114,7 @@ class NFTokenBurn_test : public beast::unit_test::suite env.close(); // minter sells the last 32 NFTs back to alice. - for (uint256 nftID : last32NFTs) + for (uint256 const nftID : last32NFTs) { // minter creates an offer for the NFToken. uint256 const minterOfferIndex = keylet::nftoffer(minter, env.seq(minter)).key; diff --git a/src/test/app/NFTokenDir_test.cpp b/src/test/app/NFTokenDir_test.cpp index 70514f497f..78765cb6c0 100644 --- a/src/test/app/NFTokenDir_test.cpp +++ b/src/test/app/NFTokenDir_test.cpp @@ -46,7 +46,7 @@ class NFTokenDir_test : public beast::unit_test::suite if (state[i].isMember(sfNFTokens.jsonName) && state[i][sfNFTokens.jsonName].isArray()) { - std::uint32_t tokenCount = state[i][sfNFTokens.jsonName].size(); + std::uint32_t const tokenCount = state[i][sfNFTokens.jsonName].size(); std::cout << tokenCount << " NFtokens in page " << state[i][jss::index].asString() << std::endl; @@ -104,7 +104,7 @@ class NFTokenDir_test : public beast::unit_test::suite nftIDs.reserve(nftCount); for (int i = 0; i < nftCount; ++i) { - std::uint32_t taxon = toUInt32(nft::cipheredTaxon(i, nft::toTaxon(0))); + std::uint32_t const taxon = toUInt32(nft::cipheredTaxon(i, nft::toTaxon(0))); nftIDs.emplace_back(token::getNextID(env, issuer, taxon, tfTransferable)); env(token::mint(issuer, taxon), txflags(tfTransferable)); env.close(); @@ -160,7 +160,7 @@ class NFTokenDir_test : public beast::unit_test::suite // Create accounts for all of the seeds and fund those accounts. std::vector accounts; accounts.reserve(seeds.size()); - for (std::string_view seed : seeds) + for (std::string_view const seed : seeds) { Account const& account = accounts.emplace_back(Account::base58Seed, std::string(seed)); @@ -364,7 +364,7 @@ class NFTokenDir_test : public beast::unit_test::suite // Create accounts for all of the seeds and fund those accounts. std::vector accounts; accounts.reserve(seeds.size()); - for (std::string_view seed : seeds) + for (std::string_view const seed : seeds) { Account const& account = accounts.emplace_back(Account::base58Seed, std::string(seed)); @@ -595,7 +595,7 @@ class NFTokenDir_test : public beast::unit_test::suite // Create accounts for all of the seeds and fund those accounts. std::vector accounts; accounts.reserve(seeds.size()); - for (std::string_view seed : seeds) + for (std::string_view const seed : seeds) { Account const& account = accounts.emplace_back(Account::base58Seed, std::string(seed)); env.fund(XRP(10000), account); @@ -758,7 +758,7 @@ class NFTokenDir_test : public beast::unit_test::suite // Create accounts for all of the seeds and fund those accounts. std::vector accounts; accounts.reserve(seeds.size()); - for (std::string_view seed : seeds) + for (std::string_view const seed : seeds) { Account const& account = accounts.emplace_back(Account::base58Seed, std::string(seed)); env.fund(XRP(10000), account); @@ -783,7 +783,7 @@ class NFTokenDir_test : public beast::unit_test::suite for (Account const& account : accounts) { // Mint the NFT. Tweak the taxon so zero is always stored. - std::uint32_t taxon = toUInt32(nft::cipheredTaxon(i, nft::toTaxon(0))); + std::uint32_t const taxon = toUInt32(nft::cipheredTaxon(i, nft::toTaxon(0))); uint256 const& nftID = nftIDsByPage[i].emplace_back( token::getNextID(env, account, taxon, tfTransferable)); @@ -831,7 +831,7 @@ class NFTokenDir_test : public beast::unit_test::suite // buyer accepts all of the offers that won't cause an overflow. // Fill the center and outsides first to exercise different boundary // cases. - for (int i : std::initializer_list{3, 6, 0, 1, 2, 5, 4}) + for (int const i : std::initializer_list{3, 6, 0, 1, 2, 5, 4}) { for (uint256 const& offer : offers[i]) { diff --git a/src/test/app/NFToken_test.cpp b/src/test/app/NFToken_test.cpp index bd61c959fc..0d391147a8 100644 --- a/src/test/app/NFToken_test.cpp +++ b/src/test/app/NFToken_test.cpp @@ -580,7 +580,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); BEAST_EXPECT(ownerCount(env, alice) == 1); - uint256 nftNoXferID = token::getNextID(env, alice, 0); + uint256 const nftNoXferID = token::getNextID(env, alice, 0); env(token::mint(alice, 0)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 1); @@ -849,7 +849,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // List of tokens to delete is too long. { - std::vector offers(maxTokenOfferCancelCount + 1, buyerOfferIndex); + std::vector const offers(maxTokenOfferCancelCount + 1, buyerOfferIndex); env(token::cancelOffer(buyer, offers), ter(temMALFORMED)); env.close(); @@ -936,7 +936,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); BEAST_EXPECT(ownerCount(env, alice) == aliceCount); - uint256 nftNoXferID = token::getNextID(env, alice, 0); + uint256 const nftNoXferID = token::getNextID(env, alice, 0); env(token::mint(alice, 0)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == aliceCount); @@ -1515,7 +1515,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // An nft without flagCreateTrustLines but with a non-zero transfer // fee will not allow creating offers that use IOUs for payment. - for (std::uint32_t xferFee : {0, 1}) + for (std::uint32_t const xferFee : {0, 1}) { uint256 const nftNoAutoTrustID{ token::getNextID(env, alice, 0u, tfTransferable, xferFee)}; @@ -1552,7 +1552,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // An nft with flagCreateTrustLines but with a non-zero transfer // fee allows transfers using IOUs for payment. { - std::uint16_t transferFee = 10000; // 10% + std::uint16_t const transferFee = 10000; // 10% uint256 const nftAutoTrustID{ token::getNextID(env, alice, 0u, tfTransferable | tfTrustLine, transferFee)}; @@ -1606,7 +1606,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Now that alice has trust lines preestablished, an nft without // flagCreateTrustLines will work for preestablished trust lines. { - std::uint16_t transferFee = 5000; // 5% + std::uint16_t const transferFee = 5000; // 5% uint256 const nftNoAutoTrustID{ token::getNextID(env, alice, 0u, tfTransferable, transferFee)}; env(token::mint(alice, 0u), token::xferFee(transferFee), txflags(tfTransferable)); @@ -2261,7 +2261,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); // Here is the smallest expressible gwXAU amount. - STAmount tinyXAU(gwXAU.issue(), STAmount::cMinValue, STAmount::cMinOffset); + STAmount const tinyXAU(gwXAU.issue(), STAmount::cMinValue, STAmount::cMinOffset); // minter buys the nft for tinyXAU. Since the transfer involves // alice there should be no transfer fee. @@ -3702,7 +3702,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite int line) { for (Account const& acct : accounts) { - if (std::uint32_t ownerCount = test::jtx::ownerCount(env, acct); + if (std::uint32_t const ownerCount = test::jtx::ownerCount(env, acct); ownerCount != 1) { std::stringstream ss; @@ -6596,7 +6596,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); // issuer creates two NFTs: one with and one without AutoTrustLine. - std::uint16_t xferFee = 5000; // 5% + std::uint16_t const xferFee = 5000; // 5% uint256 const nftAutoTrustID{ token::getNextID(env, issuer, 0u, tfTransferable | tfTrustLine, xferFee)}; env(token::mint(issuer, 0u), @@ -6752,7 +6752,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); // issuer creates two NFTs: one with and one without AutoTrustLine. - std::uint16_t xferFee = 5000; // 5% + std::uint16_t const xferFee = 5000; // 5% uint256 const nftAutoTrustID{ token::getNextID(env, issuer, 0u, tfTransferable | tfTrustLine, xferFee)}; env(token::mint(issuer, 0u), diff --git a/src/test/app/Offer_test.cpp b/src/test/app/Offer_test.cpp index 57f938e399..66e84360ef 100644 --- a/src/test/app/Offer_test.cpp +++ b/src/test/app/Offer_test.cpp @@ -93,7 +93,7 @@ public: // Offers for the good quality path env(offer(carol, BTC(1), USD(100))); - PathSet paths(Path(XRP, USD), Path(USD)); + PathSet const paths(Path(XRP, USD), Path(USD)); env(pay(alice, bob, USD(100)), json(paths.json()), @@ -419,7 +419,7 @@ public: auto const EUR = gw["EUR"]; auto tinyAmount = [&](IOU const& iou) -> PrettyAmount { - STAmount amt( + STAmount const amt( iou.issue(), /*mantissa*/ 1, /*exponent*/ -81); diff --git a/src/test/app/Oracle_test.cpp b/src/test/app/Oracle_test.cpp index 9da0ee3a31..83b658ac41 100644 --- a/src/test/app/Oracle_test.cpp +++ b/src/test/app/Oracle_test.cpp @@ -23,7 +23,7 @@ private: Env env(*this); Account const bad("bad"); env.memoize(bad); - Oracle oracle( + Oracle const oracle( env, {.owner = bad, .seq = seq(1), @@ -35,7 +35,7 @@ private: { Env env(*this); env.fund(env.current()->fees().accountReserve(0), owner); - Oracle oracle( + Oracle const oracle( env, {.owner = owner, .fee = static_cast(env.current()->fees().base.drops()), @@ -302,7 +302,7 @@ private: Env env(*this); auto const baseFee = static_cast(env.current()->fees().base.drops()); env.fund(XRP(1'000), owner); - Oracle oracle( + Oracle const oracle( env, {.owner = owner, .series = {{"USD", "USD", 740, 1}}, @@ -315,7 +315,7 @@ private: Env env(*this); auto const baseFee = static_cast(env.current()->fees().base.drops()); env.fund(XRP(1'000), owner); - Oracle oracle( + Oracle const oracle( env, {.owner = owner, .series = {{"USD", "BTC", 740, maxPriceScale + 1}}, @@ -354,7 +354,7 @@ private: Env env(*this); env.fund(XRP(1'000), owner); Oracle oracle(env, {.owner = owner, .fee = -1, .err = ter(temBAD_FEE)}); - Oracle oracle1( + Oracle const oracle1( env, {.owner = owner, .fee = static_cast(env.current()->fees().base.drops())}); oracle.set(UpdateArg{.owner = owner, .fee = -1, .err = ter(temBAD_FEE)}); } @@ -371,7 +371,7 @@ private: auto const baseFee = static_cast(env.current()->fees().base.drops()); env.fund(XRP(1'000), owner); auto const count = ownerCount(env, owner); - Oracle oracle(env, {.owner = owner, .series = series, .fee = baseFee}); + Oracle const oracle(env, {.owner = owner, .series = series, .fee = baseFee}); BEAST_EXPECT(oracle.exists()); BEAST_EXPECT(ownerCount(env, owner) == (count + adj)); auto const entry = oracle.ledgerEntry(); @@ -506,9 +506,9 @@ private: auto const acctDelFee{drops(env.current()->fees().increment)}; env.fund(XRP(1'000), owner); env.fund(XRP(1'000), alice); - Oracle oracle( + Oracle const oracle( env, {.owner = owner, .series = {{"XRP", "USD", 740, 1}}, .fee = baseFee}); - Oracle oracle1( + Oracle const oracle1( env, {.owner = owner, .documentID = 2, @@ -764,7 +764,7 @@ private: env.fund(XRP(1'000), owner); { - Oracle oracle(env, {.owner = owner, .fee = baseFee, .err = ter(temDISABLED)}); + Oracle const oracle(env, {.owner = owner, .fee = baseFee, .err = ter(temDISABLED)}); } { diff --git a/src/test/app/Path_test.cpp b/src/test/app/Path_test.cpp index 53da92ce1c..841847d183 100644 --- a/src/test/app/Path_test.cpp +++ b/src/test/app/Path_test.cpp @@ -100,7 +100,7 @@ public: void signal() { - std::lock_guard lk(mutex_); + std::lock_guard const lk(mutex_); signaled_ = true; cv_.notify_all(); } @@ -959,13 +959,13 @@ public: (domainEnabled ? " w/ " : " w/o ") + "domain"); using namespace jtx; Env env = pathTestEnv(); - Account A1{"A1"}; - Account A2{"A2"}; - Account A3{"A3"}; - Account G1{"G1"}; - Account G2{"G2"}; - Account G3{"G3"}; - Account M1{"M1"}; + Account const A1{"A1"}; + Account const A2{"A2"}; + Account const A3{"A3"}; + Account const G1{"G1"}; + Account const G2{"G2"}; + Account const G3{"G3"}; + Account const M1{"M1"}; env.fund(XRP(100000), A1); env.fund(XRP(10000), A2); @@ -1060,10 +1060,10 @@ public: "domain"); using namespace jtx; Env env = pathTestEnv(); - Account A1{"A1"}; - Account A2{"A2"}; - Account G3{"G3"}; - Account M1{"M1"}; + Account const A1{"A1"}; + Account const A2{"A2"}; + Account const G3{"G3"}; + Account const M1{"M1"}; env.fund(XRP(1000), A1, A2, G3); env.fund(XRP(11000), M1); @@ -1120,11 +1120,11 @@ public: (domainEnabled ? " w/ " : " w/o ") + "domain"); using namespace jtx; Env env = pathTestEnv(); - Account A1{"A1"}; - Account A2{"A2"}; - Account G1BS{"G1BS"}; - Account G2SW{"G2SW"}; - Account M1{"M1"}; + Account const A1{"A1"}; + Account const A2{"A2"}; + Account const G1BS{"G1BS"}; + Account const G2SW{"G2SW"}; + Account const M1{"M1"}; env.fund(XRP(1000), G1BS, G2SW, A1, A2); env.fund(XRP(11000), M1); @@ -1206,16 +1206,16 @@ public: (domainEnabled ? " w/ " : " w/o ") + "domain"); using namespace jtx; Env env = pathTestEnv(); - Account A1{"A1"}; - Account A2{"A2"}; - Account A3{"A3"}; - Account A4{"A4"}; - Account G1{"G1"}; - Account G2{"G2"}; - Account G3{"G3"}; - Account G4{"G4"}; - Account M1{"M1"}; - Account M2{"M2"}; + Account const A1{"A1"}; + Account const A2{"A2"}; + Account const A3{"A3"}; + Account const A4{"A4"}; + Account const G1{"G1"}; + Account const G2{"G2"}; + Account const G3{"G3"}; + Account const G4{"G4"}; + Account const M1{"M1"}; + Account const M2{"M2"}; env.fund(XRP(1000), A1, A2, A3, G1, G2, G3, G4); env.fund(XRP(10000), A4); @@ -1349,12 +1349,12 @@ public: (domainEnabled ? " w/ " : " w/o ") + "domain"); using namespace jtx; Env env = pathTestEnv(); - Account A1{"A1"}; - Account A2{"A2"}; - Account A3{"A3"}; - Account G1{"G1"}; - Account G2{"G2"}; - Account M1{"M1"}; + Account const A1{"A1"}; + Account const A2{"A2"}; + Account const A3{"A3"}; + Account const G1{"G1"}; + Account const G2{"G2"}; + Account const M1{"M1"}; env.fund(XRP(11000), M1); env.fund(XRP(1000), A1, A2, A3, G1, G2); @@ -1539,16 +1539,16 @@ public: // lambda param that creates different types of offers auto testPathfind = [&](auto func, bool const domainEnabled = false) { Env env = pathTestEnv(); - Account A1{"A1"}; - Account A2{"A2"}; - Account A3{"A3"}; - Account A4{"A4"}; - Account G1{"G1"}; - Account G2{"G2"}; - Account G3{"G3"}; - Account G4{"G4"}; - Account M1{"M1"}; - Account M2{"M2"}; + Account const A1{"A1"}; + Account const A2{"A2"}; + Account const A3{"A3"}; + Account const A4{"A4"}; + Account const G1{"G1"}; + Account const G2{"G2"}; + Account const G3{"G3"}; + Account const G4{"G4"}; + Account const M1{"M1"}; + Account const M2{"M2"}; env.fund(XRP(1000), A1, A2, A3, G1, G2, G3, G4); env.fund(XRP(10000), A4); @@ -1815,9 +1815,9 @@ public: testcase("AMM not used in domain path"); using namespace jtx; Env env = pathTestEnv(); - PermissionedDEX permDex(env); + PermissionedDEX const permDex(env); auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = permDex; - AMM amm(env, alice, XRP(10), USD(50)); + AMM const amm(env, alice, XRP(10), USD(50)); STPathSet st; STAmount sa, da; diff --git a/src/test/app/PayChan_test.cpp b/src/test/app/PayChan_test.cpp index 1150ae4d86..768031c3af 100644 --- a/src/test/app/PayChan_test.cpp +++ b/src/test/app/PayChan_test.cpp @@ -1504,7 +1504,7 @@ struct PayChan_test : public beast::unit_test::suite auto const settleDelay = 3600s; auto const channelFunds = XRP(1000); - std::optional cancelAfter; + std::optional const cancelAfter; { auto const chan = to_string(channel(alice, bob, env.seq(alice))); diff --git a/src/test/app/PayStrand_test.cpp b/src/test/app/PayStrand_test.cpp index 256c5ae716..222bc2ed07 100644 --- a/src/test/app/PayStrand_test.cpp +++ b/src/test/app/PayStrand_test.cpp @@ -559,7 +559,7 @@ struct ExistingElementPool result.reserve(resultSize); while (outer.next()) { - StateGuard og{*this}; + StateGuard const og{*this}; outerResult = prefix; outer.emplace_into( outerResult, accF, issF, currencyF, existingAcc, existingCur, existingIss); @@ -567,7 +567,7 @@ struct ExistingElementPool ElementComboIter inner(prevInner); while (inner.next()) { - StateGuard ig{*this}; + StateGuard const ig{*this}; result = outerResult; inner.emplace_into( result, accF, issF, currencyF, existingAcc, existingCur, existingIss); @@ -1006,7 +1006,7 @@ struct PayStrand_test : public beast::unit_test::suite return result; }(); - PathSet paths(p); + PathSet const paths(p); env(pay(alice, alice, EUR(1)), json(paths.json()), @@ -1125,12 +1125,12 @@ struct PayStrand_test : public beast::unit_test::suite Env env(*this, features); env.fund(XRP(10000), alice, bob, gw); - STAmount sendMax{USD.issue(), 100, 1}; - STAmount noAccountAmount{Issue{USD.currency, noAccount()}, 100, 1}; - STAmount deliver; + STAmount const sendMax{USD.issue(), 100, 1}; + STAmount const noAccountAmount{Issue{USD.currency, noAccount()}, 100, 1}; + STAmount const deliver; AccountID const srcAcc = alice.id(); - AccountID dstAcc = bob.id(); - STPathSet pathSet; + AccountID const dstAcc = bob.id(); + STPathSet const pathSet; ::xrpl::path::RippleCalc::Input inputs; inputs.defaultPathsAllowed = true; try diff --git a/src/test/app/PermissionedDEX_test.cpp b/src/test/app/PermissionedDEX_test.cpp index 7b622a1256..58a041ff56 100644 --- a/src/test/app/PermissionedDEX_test.cpp +++ b/src/test/app/PermissionedDEX_test.cpp @@ -183,7 +183,7 @@ class PermissionedDEX_test : public beast::unit_test::suite PermissionedDEX(env); // create devin account who is not part of the domain - Account devin("devin"); + Account const devin("devin"); env.fund(XRP(1000), devin); env.close(); env.trust(USD(1000), devin); @@ -216,7 +216,7 @@ class PermissionedDEX_test : public beast::unit_test::suite PermissionedDEX(env); // create devin account who is not part of the domain - Account devin("devin"); + Account const devin("devin"); env.fund(XRP(1000), devin); env.close(); env.trust(USD(1000), devin); @@ -402,7 +402,7 @@ class PermissionedDEX_test : public beast::unit_test::suite env.close(); // create devin account who is not part of the domain - Account devin("devin"); + Account const devin("devin"); env.fund(XRP(1000), devin); env.close(); env.trust(USD(1000), devin); @@ -448,7 +448,7 @@ class PermissionedDEX_test : public beast::unit_test::suite env.close(); // create devin account who is not part of the domain - Account devin("devin"); + Account const devin("devin"); env.fund(XRP(1000), devin); env.close(); env.trust(USD(1000), devin); @@ -642,7 +642,7 @@ class PermissionedDEX_test : public beast::unit_test::suite // Fund devin and create USD trustline Account badDomainOwner("badDomainOwner"); - Account devin("devin"); + Account const devin("devin"); env.fund(XRP(1000), badDomainOwner, devin); env.close(); env.trust(USD(1000), devin); @@ -651,7 +651,7 @@ class PermissionedDEX_test : public beast::unit_test::suite env.close(); auto const badCredType = "badCred"; - pdomain::Credentials credentials{{badDomainOwner, badCredType}}; + pdomain::Credentials const credentials{{badDomainOwner, badCredType}}; env(pdomain::setTx(badDomainOwner, credentials)); auto objects = pdomain::getObjects(badDomainOwner, env); @@ -698,7 +698,7 @@ class PermissionedDEX_test : public beast::unit_test::suite env.close(); // fund devin but don't create a USD trustline with gateway - Account devin("devin"); + Account const devin("devin"); env.fund(XRP(1000), devin); env.close(); @@ -721,7 +721,7 @@ class PermissionedDEX_test : public beast::unit_test::suite PermissionedDEX(env); // create devin account who is not part of the domain - Account devin("devin"); + Account const devin("devin"); env.fund(XRP(1000), devin); env.close(); env.trust(USD(1000), devin); @@ -920,7 +920,7 @@ class PermissionedDEX_test : public beast::unit_test::suite Env env(*this, features); auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - AMM amm(env, alice, XRP(10), USD(50)); + AMM const amm(env, alice, XRP(10), USD(50)); // a domain payment isn't able to consume AMM env(pay(bob, carol, USD(5)), @@ -1164,12 +1164,12 @@ class PermissionedDEX_test : public beast::unit_test::suite // Fund accounts Account badDomainOwner("badDomainOwner"); - Account devin("devin"); + Account const devin("devin"); env.fund(XRP(1000), badDomainOwner, devin); env.close(); auto const badCredType = "badCred"; - pdomain::Credentials credentials{{badDomainOwner, badCredType}}; + pdomain::Credentials const credentials{{badDomainOwner, badCredType}}; env(pdomain::setTx(badDomainOwner, credentials)); auto objects = pdomain::getObjects(badDomainOwner, env); @@ -1297,8 +1297,8 @@ class PermissionedDEX_test : public beast::unit_test::suite std::vector offerSeqs; offerSeqs.reserve(100); - Book domainBook{Issue(XRP), Issue(USD), domainID}; - Book openBook{Issue(XRP), Issue(USD), std::nullopt}; + Book const domainBook{Issue(XRP), Issue(USD), domainID}; + Book const openBook{Issue(XRP), Issue(USD), std::nullopt}; auto const domainDir = getBookDirKey(domainBook, XRP(10), USD(10)); auto const openDir = getBookDirKey(openBook, XRP(10), USD(10)); diff --git a/src/test/app/PermissionedDomains_test.cpp b/src/test/app/PermissionedDomains_test.cpp index c4bbd80e74..c4bde9831a 100644 --- a/src/test/app/PermissionedDomains_test.cpp +++ b/src/test/app/PermissionedDomains_test.cpp @@ -49,7 +49,7 @@ class PermissionedDomains_test : public beast::unit_test::suite Account const alice("alice"); Env env(*this, features); env.fund(XRP(1000), alice); - pdomain::Credentials credentials{{alice, "first credential"}}; + pdomain::Credentials const credentials{{alice, "first credential"}}; env(pdomain::setTx(alice, credentials)); BEAST_EXPECT(env.ownerCount(alice) == 1); auto objects = pdomain::getObjects(alice, env); @@ -71,7 +71,7 @@ class PermissionedDomains_test : public beast::unit_test::suite Account const alice("alice"); Env env(*this, amendments); env.fund(XRP(1000), alice); - pdomain::Credentials credentials{{alice, "first credential"}}; + pdomain::Credentials const credentials{{alice, "first credential"}}; env(pdomain::setTx(alice, credentials), ter(temDISABLED)); } @@ -83,7 +83,7 @@ class PermissionedDomains_test : public beast::unit_test::suite Account const alice("alice"); Env env(*this, withoutFeature_); env.fund(XRP(1000), alice); - pdomain::Credentials credentials{{alice, "first credential"}}; + pdomain::Credentials const credentials{{alice, "first credential"}}; env(pdomain::setTx(alice, credentials), ter(temDISABLED)); env(pdomain::deleteTx(alice, uint256(75)), ter(temDISABLED)); } @@ -391,7 +391,7 @@ class PermissionedDomains_test : public beast::unit_test::suite constexpr std::size_t deleteDelta = 255; { // Close enough ledgers to make it potentially deletable if empty. - std::size_t ownerSeq = env.seq(alice[0]); + std::size_t const ownerSeq = env.seq(alice[0]); while (deleteDelta + ownerSeq > env.current()->seq()) env.close(); env(acctdelete(alice[0], alice[2]), fee(acctDelFee), ter(tecHAS_OBLIGATIONS)); @@ -402,7 +402,7 @@ class PermissionedDomains_test : public beast::unit_test::suite for (auto const& objs : pdomain::getObjects(alice[0], env)) env(pdomain::deleteTx(alice[0], objs.first)); env.close(); - std::size_t ownerSeq = env.seq(alice[0]); + std::size_t const ownerSeq = env.seq(alice[0]); while (deleteDelta + ownerSeq > env.current()->seq()) env.close(); env(acctdelete(alice[0], alice[2]), fee(acctDelFee)); @@ -420,7 +420,7 @@ class PermissionedDomains_test : public beast::unit_test::suite env.fund(XRP(1000), alice); auto const setFee(drops(env.current()->fees().increment)); - pdomain::Credentials credentials{{alice, "first credential"}}; + pdomain::Credentials const credentials{{alice, "first credential"}}; env(pdomain::setTx(alice, credentials)); env.close(); @@ -484,7 +484,7 @@ class PermissionedDomains_test : public beast::unit_test::suite BEAST_EXPECT(env.ownerCount(alice) == 0); // alice does not have enough XRP to cover the reserve. - pdomain::Credentials credentials{{alice, "first credential"}}; + pdomain::Credentials const credentials{{alice, "first credential"}}; env(pdomain::setTx(alice, credentials), ter(tecINSUFFICIENT_RESERVE)); BEAST_EXPECT(env.ownerCount(alice) == 0); BEAST_EXPECT(pdomain::getObjects(alice, env).empty()); diff --git a/src/test/app/RCLValidations_test.cpp b/src/test/app/RCLValidations_test.cpp index 537563ecc4..32267cbf45 100644 --- a/src/test/app/RCLValidations_test.cpp +++ b/src/test/app/RCLValidations_test.cpp @@ -55,7 +55,7 @@ class RCLValidations_test : public beast::unit_test::suite std::vector> history; jtx::Env env(*this); - Config config; + Config const config; auto prev = std::make_shared( create_genesis, Rules{config.features}, @@ -100,7 +100,7 @@ class RCLValidations_test : public beast::unit_test::suite // Empty ledger { - RCLValidatedLedger a{RCLValidatedLedger::MakeGenesis{}}; + RCLValidatedLedger const a{RCLValidatedLedger::MakeGenesis{}}; BEAST_EXPECT(a.seq() == Seq{0}); BEAST_EXPECT(a[Seq{0}] == ID{0}); BEAST_EXPECT(a.minSeq() == Seq{0}); @@ -108,8 +108,8 @@ class RCLValidations_test : public beast::unit_test::suite // Full history ledgers { - std::shared_ptr ledger = history.back(); - RCLValidatedLedger a{ledger, env.journal}; + std::shared_ptr const ledger = history.back(); + RCLValidatedLedger const a{ledger, env.journal}; BEAST_EXPECT(a.seq() == ledger->header().seq); BEAST_EXPECT(a.minSeq() == a.seq() - maxAncestors); // Ensure the ancestral 256 ledgers have proper ID @@ -130,21 +130,21 @@ class RCLValidations_test : public beast::unit_test::suite // Empty with non-empty { - RCLValidatedLedger a{RCLValidatedLedger::MakeGenesis{}}; + RCLValidatedLedger const a{RCLValidatedLedger::MakeGenesis{}}; for (auto const& ledger : {history.back(), history[maxAncestors - 1]}) { - RCLValidatedLedger b{ledger, env.journal}; + RCLValidatedLedger const b{ledger, env.journal}; BEAST_EXPECT(mismatch(a, b) == 1); BEAST_EXPECT(mismatch(b, a) == 1); } } // Same chains, different seqs { - RCLValidatedLedger a{history.back(), env.journal}; + RCLValidatedLedger const a{history.back(), env.journal}; for (Seq s = a.seq(); s > 0; s--) { - RCLValidatedLedger b{history[s - 1], env.journal}; + RCLValidatedLedger const b{history[s - 1], env.journal}; if (s >= a.minSeq()) { BEAST_EXPECT(mismatch(a, b) == b.seq() + 1); @@ -162,8 +162,8 @@ class RCLValidations_test : public beast::unit_test::suite // Alt history diverged at history.size()/2 for (Seq s = 1; s < history.size(); ++s) { - RCLValidatedLedger a{history[s - 1], env.journal}; - RCLValidatedLedger b{altHistory[s - 1], env.journal}; + RCLValidatedLedger const a{history[s - 1], env.journal}; + RCLValidatedLedger const b{altHistory[s - 1], env.journal}; BEAST_EXPECT(a.seq() == b.seq()); if (s <= diverge) @@ -183,10 +183,10 @@ class RCLValidations_test : public beast::unit_test::suite // Different chains, different seqs { // Compare around the divergence point - RCLValidatedLedger a{history[diverge], env.journal}; + RCLValidatedLedger const a{history[diverge], env.journal}; for (Seq offset = diverge / 2; offset < 3 * diverge / 2; ++offset) { - RCLValidatedLedger b{altHistory[offset - 1], env.journal}; + RCLValidatedLedger const b{altHistory[offset - 1], env.journal}; if (offset <= diverge) { BEAST_EXPECT(mismatch(a, b) == b.seq() + 1); @@ -221,7 +221,7 @@ class RCLValidations_test : public beast::unit_test::suite // Generate a chain of 256 + 10 ledgers jtx::Env env(*this); auto& j = env.journal; - Config config; + Config const config; auto prev = std::make_shared( create_genesis, Rules{config.features}, diff --git a/src/test/app/ReducedOffer_test.cpp b/src/test/app/ReducedOffer_test.cpp index 46193a1544..b19999fecd 100644 --- a/src/test/app/ReducedOffer_test.cpp +++ b/src/test/app/ReducedOffer_test.cpp @@ -160,12 +160,12 @@ public: mantissaReduce <= 5'000'000'000ull; mantissaReduce += 20'000'000ull) { - STAmount aliceUSD{ + STAmount const aliceUSD{ bobOffer.out.issue(), bobOffer.out.mantissa() - mantissaReduce, bobOffer.out.exponent()}; - STAmount aliceXRP{bobOffer.in.issue(), bobOffer.in.mantissa() - 1}; - Amounts aliceOffer{aliceUSD, aliceXRP}; + STAmount const aliceXRP{bobOffer.in.issue(), bobOffer.in.mantissa() - 1}; + Amounts const aliceOffer{aliceUSD, aliceXRP}; blockedCount += exerciseOfferPair(aliceOffer, bobOffer); } @@ -292,12 +292,12 @@ public: mantissaReduce <= 4'000'000'000ull; mantissaReduce += 20'000'000ull) { - STAmount bobUSD{ + STAmount const bobUSD{ aliceOffer.out.issue(), aliceOffer.out.mantissa() - mantissaReduce, aliceOffer.out.exponent()}; - STAmount bobXRP{aliceOffer.in.issue(), aliceOffer.in.mantissa() - 1}; - Amounts bobOffer{bobUSD, bobXRP}; + STAmount const bobXRP{aliceOffer.in.issue(), aliceOffer.in.mantissa() - 1}; + Amounts const bobOffer{bobUSD, bobXRP}; blockedCount += exerciseOfferPair(aliceOffer, bobOffer); } @@ -445,7 +445,7 @@ public: // Examine the aftermath of alice's offer. { bool const bobOfferGone = !offerInLedger(env, bob, bobOfferSeq); - STAmount aliceBalanceUSD = env.balance(alice, USD); + STAmount const aliceBalanceUSD = env.balance(alice, USD); #if 0 std::cout << "bob initial: " << initialBobUSD @@ -580,7 +580,7 @@ public: { Json::Value aliceOffer = ledgerEntryOffer(env, alice, aliceOfferSeq); - Amounts aliceReducedOffer = jsonOfferToAmounts(aliceOffer[jss::node]); + Amounts const aliceReducedOffer = jsonOfferToAmounts(aliceOffer[jss::node]); BEAST_EXPECT(aliceReducedOffer.in < aliceInitialOffer.in); BEAST_EXPECT(aliceReducedOffer.out < aliceInitialOffer.out); diff --git a/src/test/app/Regression_test.cpp b/src/test/app/Regression_test.cpp index 55b4b9a87c..59ab0e427d 100644 --- a/src/test/app/Regression_test.cpp +++ b/src/test/app/Regression_test.cpp @@ -113,7 +113,8 @@ struct Regression_test : public beast::unit_test::suite auto test256r1key = [&env](Account const& acct) { auto const baseFee = env.current()->fees().base; std::uint32_t const acctSeq = env.seq(acct); - Json::Value jsonNoop = env.json(noop(acct), fee(baseFee), seq(acctSeq), sig(acct)); + Json::Value const jsonNoop = + env.json(noop(acct), fee(baseFee), seq(acctSeq), sig(acct)); JTx jt = env.jt(jsonNoop); jt.fill_sig = false; @@ -237,8 +238,8 @@ struct Regression_test : public beast::unit_test::suite using namespace jtx; Env env(*this); - Account alice("alice"); - Account bob("bob"); + Account const alice("alice"); + Account const bob("bob"); env.fund(XRP(10'000), alice, bob); env.close(); diff --git a/src/test/app/TheoreticalQuality_test.cpp b/src/test/app/TheoreticalQuality_test.cpp index 1a701b8954..d7e0882c3b 100644 --- a/src/test/app/TheoreticalQuality_test.cpp +++ b/src/test/app/TheoreticalQuality_test.cpp @@ -199,7 +199,7 @@ class TheoreticalQuality_test : public beast::unit_test::suite prettyQuality(Quality const& q) { std::stringstream sstr; - STAmount rate = q.rate(); + STAmount const rate = q.rate(); sstr << rate << " (" << q << ")"; return sstr.str(); }; @@ -220,7 +220,7 @@ class TheoreticalQuality_test : public beast::unit_test::suite std::shared_ptr closed, std::optional const& expectedQ = {}) { - PaymentSandbox sb(closed.get(), tapNONE); + PaymentSandbox const sb(closed.get(), tapNONE); AMMContext ammContext(rcp.srcAccount, false); auto const sendMaxIssue = [&rcp]() -> std::optional { @@ -229,7 +229,7 @@ class TheoreticalQuality_test : public beast::unit_test::suite return std::nullopt; }(); - beast::Journal dummyJ{beast::Journal::getNullSink()}; + beast::Journal const dummyJ{beast::Journal::getNullSink()}; auto sr = toStrands( sb, @@ -366,7 +366,7 @@ public: // Accounts are set up, make the payment IOU const iou{accounts.back(), currency}; - RippleCalcTestParams rcp{env.json( + RippleCalcTestParams const rcp{env.json( pay(accounts.front(), accounts.back(), iou(paymentAmount)), accountsPath, txflags(tfNoRippleDirect))}; @@ -413,7 +413,7 @@ public: auto const USDB = bob["USD"]; auto const EURC = carol["EUR"]; constexpr std::size_t const numAccounts = 5; - std::array accounts{{alice, bob, carol, dan, oscar}}; + std::array const accounts{{alice, bob, carol, dan, oscar}}; // sendmax should be in USDB and delivered amount should be in EURC // normalized path should be: @@ -445,7 +445,7 @@ public: // Accounts are set up, make the payment IOU const srcIOU{bob, usdCurrency}; IOU const dstIOU{carol, eurCurrency}; - RippleCalcTestParams rcp{env.json( + RippleCalcTestParams const rcp{env.json( pay(alice, dan, dstIOU(paymentAmount)), sendmax(srcIOU(100 * paymentAmount)), bookPath, diff --git a/src/test/app/Ticket_test.cpp b/src/test/app/Ticket_test.cpp index 7d300f61ca..7f96caa05f 100644 --- a/src/test/app/Ticket_test.cpp +++ b/src/test/app/Ticket_test.cpp @@ -378,7 +378,7 @@ class Ticket_test : public beast::unit_test::suite { // Create tickets on a non-existent account. Env env{*this}; - Account alice{"alice"}; + Account const alice{"alice"}; env.memoize(alice); env(ticket::create(alice, 1), json(jss::Sequence, 1), ter(terNO_ACCOUNT)); @@ -387,11 +387,11 @@ class Ticket_test : public beast::unit_test::suite // Exceed the threshold where tickets can no longer be // added to an account. Env env{*this}; - Account alice{"alice"}; + Account const alice{"alice"}; env.fund(XRP(100000), alice); - std::uint32_t ticketSeq{env.seq(alice) + 1}; + std::uint32_t const ticketSeq{env.seq(alice) + 1}; env(ticket::create(alice, 250)); checkTicketCreateMeta(env); env.close(); @@ -424,12 +424,12 @@ class Ticket_test : public beast::unit_test::suite { // Explore exceeding the ticket threshold from another angle. Env env{*this}; - Account alice{"alice"}; + Account const alice{"alice"}; env.fund(XRP(100000), alice); env.close(); - std::uint32_t ticketSeq_AB{env.seq(alice) + 1}; + std::uint32_t const ticketSeq_AB{env.seq(alice) + 1}; env(ticket::create(alice, 2)); checkTicketCreateMeta(env); env.close(); @@ -462,7 +462,7 @@ class Ticket_test : public beast::unit_test::suite using namespace test::jtx; Env env{*this}; - Account alice{"alice"}; + Account const alice{"alice"}; // Fund alice not quite enough to make the reserve for a Ticket. env.fund(env.current()->fees().accountReserve(1) - drops(1), alice); @@ -515,7 +515,7 @@ class Ticket_test : public beast::unit_test::suite using namespace test::jtx; Env env{*this}; - Account alice{"alice"}; + Account const alice{"alice"}; env.fund(XRP(10000), alice); env.close(); @@ -611,14 +611,14 @@ class Ticket_test : public beast::unit_test::suite using namespace test::jtx; Env env{*this}; - Account alice{"alice"}; + Account const alice{"alice"}; env.fund(XRP(10000), alice); env.close(); // Lambda that returns the hash of the most recent transaction. auto getTxID = [&env, this]() -> uint256 { - std::shared_ptr tx{env.tx()}; + std::shared_ptr const tx{env.tx()}; if (!BEAST_EXPECTS(tx, "Transaction not found")) Throw("Invalid transaction ID"); @@ -689,7 +689,7 @@ class Ticket_test : public beast::unit_test::suite BEAST_EXPECT(txErrCode == rpcSUCCESS); if (auto txPtr = std::get_if(&maybeTx)) { - std::shared_ptr& tx = txPtr->first; + std::shared_ptr const& tx = txPtr->first; BEAST_EXPECT(tx->getLedger() == ledgerSeq); std::shared_ptr const& sttx = tx->getSTransaction(); BEAST_EXPECT((*sttx)[sfSequence] == txSeq); @@ -726,7 +726,7 @@ class Ticket_test : public beast::unit_test::suite using namespace test::jtx; Env env{*this}; - Account alice{"alice"}; + Account const alice{"alice"}; env.fund(XRP(10000), alice); env.close(); @@ -812,7 +812,7 @@ class Ticket_test : public beast::unit_test::suite testcase("Fix both Seq and Ticket"); Env env{*this, testable_amendments()}; - Account alice{"alice"}; + Account const alice{"alice"}; env.fund(XRP(10000), alice); env.close(); diff --git a/src/test/app/TrustAndBalance_test.cpp b/src/test/app/TrustAndBalance_test.cpp index 3a2aa8e7c9..a71ddb140e 100644 --- a/src/test/app/TrustAndBalance_test.cpp +++ b/src/test/app/TrustAndBalance_test.cpp @@ -28,7 +28,7 @@ class TrustAndBalance_test : public beast::unit_test::suite using namespace test::jtx; Env env{*this}; - Account alice{"alice"}; + Account const alice{"alice"}; env(trust(env.master, alice["USD"](100)), ter(tecNO_DST)); } @@ -40,9 +40,9 @@ class TrustAndBalance_test : public beast::unit_test::suite using namespace test::jtx; Env env{*this}; - Account gw{"gateway"}; - Account alice{"alice"}; - Account bob{"bob"}; + Account const gw{"gateway"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(10000), gw, alice, bob); env.close(); @@ -112,8 +112,8 @@ class TrustAndBalance_test : public beast::unit_test::suite using namespace test::jtx; Env env{*this, features}; - Account alice{"alice"}; - Account bob{"bob"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(10000), alice, bob); env.close(); @@ -156,9 +156,9 @@ class TrustAndBalance_test : public beast::unit_test::suite Env env{*this, features}; auto wsc = test::makeWSClient(env.app().config()); - Account gw{"gateway"}; - Account alice{"alice"}; - Account bob{"bob"}; + Account const gw{"gateway"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(10000), gw, alice, bob); env.close(); @@ -229,9 +229,9 @@ class TrustAndBalance_test : public beast::unit_test::suite using namespace test::jtx; Env env{*this, features}; - Account gw{"gateway"}; - Account alice{"alice"}; - Account bob{"bob"}; + Account const gw{"gateway"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(10000), gw, alice, bob); env.close(); @@ -276,9 +276,9 @@ class TrustAndBalance_test : public beast::unit_test::suite using namespace test::jtx; Env env{*this, features}; - Account gw{"gateway"}; - Account alice{"alice"}; - Account bob{"bob"}; + Account const gw{"gateway"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(10000), gw, alice, bob); env.close(); @@ -319,11 +319,11 @@ class TrustAndBalance_test : public beast::unit_test::suite using namespace test::jtx; Env env{*this, features}; - Account gw{"gateway"}; - Account amazon{"amazon"}; - Account alice{"alice"}; - Account bob{"bob"}; - Account carol{"carol"}; + Account const gw{"gateway"}; + Account const amazon{"amazon"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + Account const carol{"carol"}; env.fund(XRP(10000), gw, amazon, alice, bob, carol); env.close(); @@ -379,7 +379,7 @@ class TrustAndBalance_test : public beast::unit_test::suite using namespace test::jtx; Env env{*this, features}; - Account alice{"alice"}; + Account const alice{"alice"}; auto wsc = test::makeWSClient(env.app().config()); env.fund(XRP(10000), alice); diff --git a/src/test/app/TxQ_test.cpp b/src/test/app/TxQ_test.cpp index 11bbd62bd5..6f13f9d419 100644 --- a/src/test/app/TxQ_test.cpp +++ b/src/test/app/TxQ_test.cpp @@ -500,7 +500,7 @@ public: // We haven't yet shown that ticket-based transactions can be added // to the queue in any order. We should do that... - std::uint32_t tkt250 = tkt1 + 249; + std::uint32_t const tkt250 = tkt1 + 249; env(noop(alice), ticket::use(tkt250 - 0), fee(baseFee * 3.0), queued); env(noop(alice), ticket::use(tkt1 + 14), fee(baseFee * 2.9), queued); env(noop(alice), ticket::use(tkt250 - 1), fee(baseFee * 2.8), queued); @@ -1520,7 +1520,7 @@ public: try { - Env env( + Env const env( *this, makeConfig( {{"minimum_txn_in_ledger", "200"}, @@ -1541,7 +1541,7 @@ public: } try { - Env env( + Env const env( *this, makeConfig( {{"minimum_txn_in_ledger", "200"}, @@ -1562,7 +1562,7 @@ public: } try { - Env env( + Env const env( *this, makeConfig( {{"minimum_txn_in_ledger", "2"}, @@ -3387,6 +3387,7 @@ public: BEAST_EXPECT(jv[jss::status] == "success"); } + // NOLINTNEXTLINE(misc-const-correctness) Account a{"a"}, b{"b"}, c{"c"}, d{"d"}, e{"e"}, f{"f"}, g{"g"}, h{"h"}, i{"i"}; // Fund the first few accounts at non escalated fee @@ -3528,7 +3529,8 @@ public: } auto const den = (metrics.txPerLedger * metrics.txPerLedger); - FeeLevel64 feeLevel = (metrics.medFeeLevel * totalFactor + FeeLevel64{den - 1}) / den; + FeeLevel64 const feeLevel = + (metrics.medFeeLevel * totalFactor + FeeLevel64{den - 1}) / den; auto result = toDrops(feeLevel, env.current()->fees().base).drops(); diff --git a/src/test/app/ValidatorKeys_test.cpp b/src/test/app/ValidatorKeys_test.cpp index 29876dea7c..3be6fcd028 100644 --- a/src/test/app/ValidatorKeys_test.cpp +++ b/src/test/app/ValidatorKeys_test.cpp @@ -59,7 +59,7 @@ public: // We're only using Env for its Journal. That Journal gives better // coverage in unit tests. test::jtx::Env env{*this, test::jtx::envconfig(), nullptr, beast::severities::kDisabled}; - beast::Journal journal{env.app().getJournal("ValidatorKeys_test")}; + beast::Journal const journal{env.app().getJournal("ValidatorKeys_test")}; // Keys/ID when using [validation_seed] SecretKey const seedSecretKey = @@ -82,8 +82,8 @@ public: { // No config -> no key but valid - Config c; - ValidatorKeys k{c, journal}; + Config const c; + ValidatorKeys const k{c, journal}; BEAST_EXPECT(!k.keys); BEAST_EXPECT(k.manifest.empty()); BEAST_EXPECT(!k.configInvalid()); @@ -109,7 +109,7 @@ public: Config c; c.section(SECTION_VALIDATION_SEED).append("badseed"); - ValidatorKeys k{c, journal}; + ValidatorKeys const k{c, journal}; BEAST_EXPECT(k.configInvalid()); BEAST_EXPECT(!k.keys); BEAST_EXPECT(k.manifest.empty()); @@ -134,7 +134,7 @@ public: // invalid validator token Config c; c.section(SECTION_VALIDATOR_TOKEN).append("badtoken"); - ValidatorKeys k{c, journal}; + ValidatorKeys const k{c, journal}; BEAST_EXPECT(k.configInvalid()); BEAST_EXPECT(!k.keys); BEAST_EXPECT(k.manifest.empty()); @@ -145,7 +145,7 @@ public: Config c; c.section(SECTION_VALIDATION_SEED).append(seed); c.section(SECTION_VALIDATOR_TOKEN).append(tokenBlob); - ValidatorKeys k{c, journal}; + ValidatorKeys const k{c, journal}; BEAST_EXPECT(k.configInvalid()); BEAST_EXPECT(!k.keys); @@ -156,7 +156,7 @@ public: // Token manifest and private key must match Config c; c.section(SECTION_VALIDATOR_TOKEN).append(invalidTokenBlob); - ValidatorKeys k{c, journal}; + ValidatorKeys const k{c, journal}; BEAST_EXPECT(k.configInvalid()); BEAST_EXPECT(!k.keys); diff --git a/src/test/app/ValidatorList_test.cpp b/src/test/app/ValidatorList_test.cpp index 3f1c20ee25..74b208e5e2 100644 --- a/src/test/app/ValidatorList_test.cpp +++ b/src/test/app/ValidatorList_test.cpp @@ -272,7 +272,7 @@ private: auto const masterNode1 = randomMasterKey(); auto const masterNode2 = randomMasterKey(); - std::vector cfgMasterKeys( + std::vector const cfgMasterKeys( {format(masterNode1), format(masterNode2, " Comment")}); BEAST_EXPECT(trustedKeys->load({}, cfgMasterKeys, emptyCfgPublishers)); BEAST_EXPECT(trustedKeys->listed(masterNode1)); @@ -362,7 +362,8 @@ private: // load should reject validator list signing keys with invalid // encoding - std::vector keys({randomMasterKey(), randomMasterKey(), randomMasterKey()}); + std::vector const keys( + {randomMasterKey(), randomMasterKey(), randomMasterKey()}); badPublishers.clear(); for (auto const& key : keys) badPublishers.push_back(toBase58(TokenType::NodePublic, key)); @@ -391,7 +392,7 @@ private: app.config().legacy("database_path"), env.journal); - std::vector keys( + std::vector const keys( {randomMasterKey(), randomMasterKey(), randomMasterKey(), randomMasterKey()}); std::vector cfgPublishers; cfgPublishers.reserve(keys.size()); @@ -433,7 +434,7 @@ private: auto legitKey1 = randomMasterKey(); auto legitKey2 = randomMasterKey(); - std::vector cfgPublishers = { + std::vector const cfgPublishers = { strHex(pubRevokedPublic), strHex(legitKey1), strHex(legitKey2)}; BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgPublishers)); @@ -471,7 +472,8 @@ private: // this one is not revoked (and not in the manifest cache at all.) auto legitKey = randomMasterKey(); - std::vector cfgPublishers = {strHex(pubRevokedPublic), strHex(legitKey)}; + std::vector const cfgPublishers = { + strHex(pubRevokedPublic), strHex(legitKey)}; BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgPublishers, std::size_t(2))); BEAST_EXPECT(!trustedKeys->trustedPublisher(pubRevokedPublic)); @@ -563,8 +565,8 @@ private: auto const manifest1 = base64_encode(makeManifestString( publisherPublic, publisherSecret, pubSigningKeys1.first, pubSigningKeys1.second, 1)); - std::vector cfgPublisherKeys({strHex(publisherPublic)}); - std::vector emptyCfgKeys; + std::vector const cfgPublisherKeys({strHex(publisherPublic)}); + std::vector const emptyCfgKeys; BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgPublisherKeys)); @@ -909,8 +911,8 @@ private: auto const manifest = base64_encode(makeManifestString( publisherPublic, publisherSecret, pubSigningKeys1.first, pubSigningKeys1.second, 1)); - std::vector cfgPublisherKeys({strHex(publisherPublic)}); - std::vector emptyCfgKeys; + std::vector const cfgPublisherKeys({strHex(publisherPublic)}); + std::vector const emptyCfgKeys; BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgPublisherKeys)); @@ -1033,7 +1035,7 @@ private: app.config().legacy("database_path"), env.journal); - std::vector cfgPublishersOuter; + std::vector const cfgPublishersOuter; hash_set activeValidatorsOuter; std::size_t const maxKeys = 40; @@ -1101,7 +1103,7 @@ private: auto const masterPrivate = randomSecretKey(); auto const masterPublic = derivePublicKey(KeyType::ed25519, masterPrivate); - std::vector cfgKeys({toBase58(TokenType::NodePublic, masterPublic)}); + std::vector const cfgKeys({toBase58(TokenType::NodePublic, masterPublic)}); BEAST_EXPECT(trustedKeysOuter->load({}, cfgKeys, cfgPublishersOuter)); @@ -1201,12 +1203,12 @@ private: auto const publisherSecret = randomSecretKey(); auto const publisherPublic = derivePublicKey(KeyType::ed25519, publisherSecret); - std::vector cfgPublishers({strHex(publisherPublic)}); - std::vector emptyCfgKeys; + std::vector const cfgPublishers({strHex(publisherPublic)}); + std::vector const emptyCfgKeys; BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgPublishers)); - TrustChanges changes = trustedKeys->updateTrusted( + TrustChanges const changes = trustedKeys->updateTrusted( activeValidatorsOuter, env.timeKeeper().now(), env.app().getOPs(), @@ -1227,18 +1229,18 @@ private: env.journal); auto const masterPrivate = randomSecretKey(); auto const masterPublic = derivePublicKey(KeyType::ed25519, masterPrivate); - std::vector cfgKeys({toBase58(TokenType::NodePublic, masterPublic)}); + std::vector const cfgKeys({toBase58(TokenType::NodePublic, masterPublic)}); auto const publisher1Secret = randomSecretKey(); auto const publisher1Public = derivePublicKey(KeyType::ed25519, publisher1Secret); auto const publisher2Secret = randomSecretKey(); auto const publisher2Public = derivePublicKey(KeyType::ed25519, publisher2Secret); - std::vector cfgPublishers( + std::vector const cfgPublishers( {strHex(publisher1Public), strHex(publisher2Public)}); BEAST_EXPECT(trustedKeys->load({}, cfgKeys, cfgPublishers, std::size_t(2))); - TrustChanges changes = trustedKeys->updateTrusted( + TrustChanges const changes = trustedKeys->updateTrusted( activeValidatorsOuter, env.timeKeeper().now(), env.app().getOPs(), @@ -1261,7 +1263,7 @@ private: env.journal, minQuorum); - std::size_t n = 10; + std::size_t const n = 10; std::vector cfgKeys; cfgKeys.reserve(n); hash_set expectedTrusted; @@ -1316,7 +1318,7 @@ private: app.config().legacy("database_path"), env.journal); - std::vector emptyCfgKeys; + std::vector const emptyCfgKeys; auto const publisherKeys = randomKeyPair(KeyType::secp256k1); auto const pubSigningKeys = randomKeyPair(KeyType::secp256k1); auto const manifest = base64_encode(makeManifestString( @@ -1326,7 +1328,7 @@ private: pubSigningKeys.second, 1)); - std::vector cfgPublisherKeys({strHex(publisherKeys.first)}); + std::vector const cfgPublisherKeys({strHex(publisherKeys.first)}); BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgPublisherKeys)); @@ -1415,7 +1417,7 @@ private: app.config().legacy("database_path"), env.journal); - std::vector cfgPublishers; + std::vector const cfgPublishers; hash_set activeValidators; hash_set activeKeys; @@ -1429,7 +1431,7 @@ private: activeValidators.emplace(calcNodeID(valKey)); activeKeys.emplace(valKey); BEAST_EXPECT(trustedKeys->load({}, cfgKeys, cfgPublishers)); - TrustChanges changes = trustedKeys->updateTrusted( + TrustChanges const changes = trustedKeys->updateTrusted( activeValidators, env.timeKeeper().now(), env.app().getOPs(), @@ -1452,7 +1454,7 @@ private: env.journal); auto const localKey = randomNode(); - std::vector cfgPublishers; + std::vector const cfgPublishers; hash_set activeValidators; hash_set activeKeys; std::vector cfgKeys{toBase58(TokenType::NodePublic, localKey)}; @@ -1466,7 +1468,7 @@ private: activeKeys.emplace(valKey); BEAST_EXPECT(trustedKeys->load(localKey, cfgKeys, cfgPublishers)); - TrustChanges changes = trustedKeys->updateTrusted( + TrustChanges const changes = trustedKeys->updateTrusted( activeValidators, env.timeKeeper().now(), env.app().getOPs(), @@ -1532,8 +1534,8 @@ private: pubSigningKeys.second, 1)); - std::vector cfgPublishers({strHex(publisherPublic)}); - std::vector emptyCfgKeys; + std::vector const cfgPublishers({strHex(publisherPublic)}); + std::vector const emptyCfgKeys; // Threshold of 1 will result in a union of all the lists BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgPublishers, std::size_t(1))); @@ -1542,7 +1544,7 @@ private: auto const sequence = 1; using namespace std::chrono_literals; NetClock::time_point const validUntil = env.timeKeeper().now() + 3600s; - std::vector localKeys{locals[i].first, locals[i].second}; + std::vector const localKeys{locals[i].first, locals[i].second}; auto const blob = makeList(localKeys, sequence, validUntil.time_since_epoch().count()); auto const sig = signList(blob, pubSigningKeys); @@ -1558,7 +1560,7 @@ private: addPublishedList(i); BEAST_EXPECT(trustedKeys->getListThreshold() == 1); - TrustChanges changes = trustedKeys->updateTrusted( + TrustChanges const changes = trustedKeys->updateTrusted( activeValidators, env.timeKeeper().now(), env.app().getOPs(), @@ -1624,8 +1626,8 @@ private: pubSigningKeys.second, 1)); - std::vector cfgPublishers({strHex(publisherPublic)}); - std::vector emptyCfgKeys; + std::vector const cfgPublishers({strHex(publisherPublic)}); + std::vector const emptyCfgKeys; BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgPublishers)); @@ -1655,7 +1657,7 @@ private: { validUntil2 = validUntil; } - std::vector localKeys{locals[i].first, locals[i].second}; + std::vector const localKeys{locals[i].first, locals[i].second}; auto const blob = makeList(localKeys, sequence, validUntil.time_since_epoch().count()); auto const sig = signList(blob, pubSigningKeys); @@ -1797,7 +1799,7 @@ private: BEAST_EXPECT(trustedKeys->expires() == std::nullopt); // Config listed keys have maximum expiry - PublicKey localCfgListed = randomNode(); + PublicKey const localCfgListed = randomNode(); trustedKeys->load({}, {toStr(localCfgListed)}, {}); BEAST_EXPECT( trustedKeys->expires() && @@ -1841,8 +1843,8 @@ private: pubSigningKeys.second, 1)); - std::vector cfgPublishers({strHex(publisherPublic)}); - std::vector emptyCfgKeys; + std::vector const cfgPublishers({strHex(publisherPublic)}); + std::vector const emptyCfgKeys; BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgPublishers)); @@ -1874,7 +1876,7 @@ private: // Configure two publishers and prepare 2 lists PreparedList prep1 = addPublishedList(); env.timeKeeper().set(env.timeKeeper().now() + 200s); - PreparedList prep2 = addPublishedList(); + PreparedList const prep2 = addPublishedList(); // Initially, no list has been published, so no known expiration BEAST_EXPECT(trustedKeys->expires() == std::nullopt); @@ -1955,7 +1957,7 @@ private: env.journal, minimumQuorum); - std::vector cfgPublishers; + std::vector const cfgPublishers; std::vector cfgKeys; hash_set activeValidators; cfgKeys.reserve(vlSize); @@ -1995,10 +1997,10 @@ private: */ { - hash_set activeValidators; + hash_set const activeValidators; //== Combinations == - std::array unlSizes = {34, 35, 39, 60}; - std::array nUnlPercent = {0, 20, 30, 50}; + std::array const unlSizes = {34, 35, 39, 60}; + std::array const nUnlPercent = {0, 20, 30, 50}; for (auto us : unlSizes) { for (auto np : nUnlPercent) @@ -2007,7 +2009,7 @@ private: BEAST_EXPECT(validators); if (validators) { - std::uint32_t nUnlSize = us * np / 100; + std::uint32_t const nUnlSize = us * np / 100; auto unl = validators->getTrustedMasterKeys(); hash_set nUnl; auto it = unl.begin(); @@ -2082,12 +2084,12 @@ private: // 18 auto nUnl = validators->getNegativeUNL(); BEAST_EXPECT(nUnl.size() == 12); - std::size_t ss = 33; + std::size_t const ss = 33; std::vector data(ss, 0); data[0] = 0xED; for (int i = 0; i < 6; ++i) { - Slice s(data.data(), ss); + Slice const s(data.data(), ss); data[1]++; nUnl.emplace(s); } @@ -2167,7 +2169,7 @@ private: BEAST_EXPECT(global != sha512Half(signature, blobVector, version)); { - std::map blobMap{{99, blobVector[0]}}; + std::map const blobMap{{99, blobVector[0]}}; BEAST_EXPECT(global == sha512Half(manifest, blobMap, version)); BEAST_EXPECT(global != sha512Half(blob, blobMap, version)); } @@ -3698,7 +3700,7 @@ private: for (auto const& p : publishers) BEAST_EXPECT(trustedKeys->trustedPublisher(p.pubKey)); - TrustChanges changes = trustedKeys->updateTrusted( + TrustChanges const changes = trustedKeys->updateTrusted( activeValidators, env.timeKeeper().now(), env.app().getOPs(), @@ -3736,7 +3738,7 @@ private: for (auto const& p : publishers) BEAST_EXPECT(trustedKeys->trustedPublisher(p.pubKey)); - TrustChanges changes = trustedKeys->updateTrusted( + TrustChanges const changes = trustedKeys->updateTrusted( activeValidators, env.timeKeeper().now(), env.app().getOPs(), diff --git a/src/test/app/ValidatorSite_test.cpp b/src/test/app/ValidatorSite_test.cpp index ee28410d9e..004c59609c 100644 --- a/src/test/app/ValidatorSite_test.cpp +++ b/src/test/app/ValidatorSite_test.cpp @@ -53,11 +53,11 @@ private: auto trustedSites = std::make_unique(env.app(), env.journal); // load should accept empty sites list - std::vector emptyCfgSites; + std::vector const emptyCfgSites; BEAST_EXPECT(trustedSites->load(emptyCfgSites)); // load should accept valid validator site uris - std::vector cfgSites( + std::vector const cfgSites( {"http://ripple.com/", "http://ripple.com/validators", "http://ripple.com:8080/validators", @@ -145,7 +145,7 @@ private: test::StreamSink sink; beast::Journal journal{sink}; - std::vector emptyCfgKeys; + std::vector const emptyCfgKeys; struct publisher { publisher(FetchListConfig const& c) : cfg{c} @@ -181,7 +181,7 @@ private: {{effective2, expires2}}, cfg.ssl, cfg.serverVersion); - std::string pubHex = strHex(item.server->publisherPublic()); + std::string const pubHex = strHex(item.server->publisherPublic()); cfgPublishers.push_back(pubHex); if (item.cfg.failFetch) @@ -337,11 +337,12 @@ private: }; { // Create a file with a real validator list - detail::FileDirGuard good(*this, "test_val", "vl.txt", detail::realValidatorContents()); + detail::FileDirGuard const good( + *this, "test_val", "vl.txt", detail::realValidatorContents()); // Create a file with arbitrary content - detail::FileDirGuard hello(*this, "test_val", "helloworld.txt", "Hello, world!"); + detail::FileDirGuard const hello(*this, "test_val", "helloworld.txt", "Hello, world!"); // Create a file with malformed Json - detail::FileDirGuard json( + detail::FileDirGuard const json( *this, "test_val", "json.txt", R"json({ "version": 2, "extra" : "value" })json"); auto const goodPath = fullPath(good); auto const helloPath = fullPath(hello); @@ -362,7 +363,7 @@ public: { testConfigLoad(); - detail::DirGuard good(*this, "test_fetch"); + detail::DirGuard const good(*this, "test_fetch"); for (auto ssl : {true, false}) { // fetch single site diff --git a/src/test/app/Vault_test.cpp b/src/test/app/Vault_test.cpp index 54cc6646b1..50417305b4 100644 --- a/src/test/app/Vault_test.cpp +++ b/src/test/app/Vault_test.cpp @@ -90,8 +90,8 @@ class Vault_test : public beast::unit_test::suite env.memoize(vaultAccount); // Several 3rd party accounts which cannot receive funds - Account alice{"alice"}; - Account erin{"erin"}; // not authorized by issuer + Account const alice{"alice"}; + Account const erin{"erin"}; // not authorized by issuer env.fund(XRP(1000), alice, erin); env(fset(alice, asfDepositAuth)); env.close(); @@ -514,14 +514,14 @@ class Vault_test : public beast::unit_test::suite env.require(flags(issuer, asfAllowTrustLineClawback)); env.require(flags(issuer, asfRequireAuth)); - PrettyAsset asset = setup(env); + PrettyAsset const asset = setup(env); testSequence(prefix, env, vault, asset); }; testCases("XRP", [&](Env& env) -> PrettyAsset { return {xrpIssue(), 1'000'000}; }); testCases("IOU", [&](Env& env) -> Asset { - PrettyAsset asset = issuer["IOU"]; + PrettyAsset const asset = issuer["IOU"]; env(trust(owner, asset(1000))); env(trust(depositor, asset(1000))); env(trust(charlie, asset(1000))); @@ -538,7 +538,7 @@ class Vault_test : public beast::unit_test::suite testCases("MPT", [&](Env& env) -> Asset { MPTTester mptt{env, issuer, mptInitNoFund}; mptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); - PrettyAsset asset = mptt.issuanceID(); + PrettyAsset const asset = mptt.issuanceID(); mptt.authorize({.account = depositor}); mptt.authorize({.account = charlie}); mptt.authorize({.account = dave}); @@ -567,8 +567,8 @@ class Vault_test : public beast::unit_test::suite Vault& vault)> test, CaseArgs args = {}) { Env env{*this, args.features}; - Account issuer{"issuer"}; - Account owner{"owner"}; + Account const issuer{"issuer"}; + Account const owner{"owner"}; Vault vault{env}; env.fund(XRP(1000), issuer, owner); env.close(); @@ -577,7 +577,7 @@ class Vault_test : public beast::unit_test::suite env(fset(issuer, asfRequireAuth)); env.close(); - PrettyAsset asset = issuer["IOU"]; + PrettyAsset const asset = issuer["IOU"]; env(trust(owner, asset(1000))); env(trust(issuer, asset(0), owner, tfSetfAuth)); env(pay(issuer, owner, asset(1000))); @@ -1081,13 +1081,13 @@ class Vault_test : public beast::unit_test::suite Asset const& asset, Vault& vault)> test) { Env env{*this, testable_amendments() | featureSingleAssetVault}; - Account issuer{"issuer"}; - Account owner{"owner"}; - Account depositor{"depositor"}; + Account const issuer{"issuer"}; + Account const owner{"owner"}; + Account const depositor{"depositor"}; env.fund(XRP(1000), issuer, owner, depositor); env.close(); Vault vault{env}; - Asset asset = xrpIssue(); + Asset const asset = xrpIssue(); test(env, issuer, owner, depositor, asset, vault); }; @@ -1246,13 +1246,13 @@ class Vault_test : public beast::unit_test::suite testcase("IOU fail because MPT is disabled"); Env env{ *this, (testable_amendments() - featureMPTokensV1) | featureSingleAssetVault}; - Account issuer{"issuer"}; - Account owner{"owner"}; + Account const issuer{"issuer"}; + Account const owner{"owner"}; env.fund(XRP(1000), issuer, owner); env.close(); - Vault vault{env}; - Asset asset = issuer["IOU"].asset(); + Vault const vault{env}; + Asset const asset = issuer["IOU"].asset(); auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); env(tx, ter(temDISABLED)); @@ -1262,15 +1262,15 @@ class Vault_test : public beast::unit_test::suite { testcase("IOU fail create frozen"); Env env{*this, testable_amendments() | featureSingleAssetVault}; - Account issuer{"issuer"}; - Account owner{"owner"}; + Account const issuer{"issuer"}; + Account const owner{"owner"}; env.fund(XRP(1000), issuer, owner); env.close(); env(fset(issuer, asfGlobalFreeze)); env.close(); - Vault vault{env}; - Asset asset = issuer["IOU"].asset(); + Vault const vault{env}; + Asset const asset = issuer["IOU"].asset(); auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); env(tx, ter(tecFROZEN)); @@ -1280,15 +1280,15 @@ class Vault_test : public beast::unit_test::suite { testcase("IOU fail create no ripling"); Env env{*this, testable_amendments() | featureSingleAssetVault}; - Account issuer{"issuer"}; - Account owner{"owner"}; + Account const issuer{"issuer"}; + Account const owner{"owner"}; env.fund(XRP(1000), issuer, owner); env.close(); env(fclear(issuer, asfDefaultRipple)); env.close(); - Vault vault{env}; - Asset asset = issuer["IOU"].asset(); + Vault const vault{env}; + Asset const asset = issuer["IOU"].asset(); auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); env(tx, ter(terNO_RIPPLE)); env.close(); @@ -1297,13 +1297,13 @@ class Vault_test : public beast::unit_test::suite { testcase("IOU no issuer"); Env env{*this, testable_amendments() | featureSingleAssetVault}; - Account issuer{"issuer"}; - Account owner{"owner"}; + Account const issuer{"issuer"}; + Account const owner{"owner"}; env.fund(XRP(1000), owner); env.close(); - Vault vault{env}; - Asset asset = issuer["IOU"].asset(); + Vault const vault{env}; + Asset const asset = issuer["IOU"].asset(); { auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); env(tx, ter(terNO_ACCOUNT)); @@ -1351,12 +1351,12 @@ class Vault_test : public beast::unit_test::suite fund(env, gw, {alice, carol}, toFund2, {toFund1}, Fund::All); } - AMM ammAlice(env, alice, asset1, asset2, CreateArg{.log = false, .tfee = 0}); + AMM const ammAlice(env, alice, asset1, asset2, CreateArg{.log = false, .tfee = 0}); Account const owner{"owner"}; env.fund(XRP(1000000), owner); - Vault vault{env}; + Vault const vault{env}; auto [tx, k] = vault.create({.owner = owner, .asset = ammAlice.lptIssue()}); env(tx, ter{tecWRONG_ASSET}); env.close(); @@ -1377,16 +1377,16 @@ class Vault_test : public beast::unit_test::suite Asset const& asset, Vault& vault)> test) { Env env{*this, testable_amendments() | featureSingleAssetVault}; - Account issuer{"issuer"}; - Account owner{"owner"}; - Account depositor{"depositor"}; + Account const issuer{"issuer"}; + Account const owner{"owner"}; + Account const depositor{"depositor"}; env.fund(XRP(1000), issuer, owner, depositor); env.close(); Vault vault{env}; MPTTester mptt{env, issuer, mptInitNoFund}; // Locked because that is the default flag. mptt.create(); - Asset asset = mptt.issuanceID(); + Asset const asset = mptt.issuanceID(); test(env, issuer, owner, depositor, asset, vault); }; @@ -1436,14 +1436,14 @@ class Vault_test : public beast::unit_test::suite using namespace test::jtx; Env env{*this, testable_amendments() | featureSingleAssetVault}; - Account issuer{"issuer"}; - Account owner{"owner"}; - Account depositor{"depositor"}; + Account const issuer{"issuer"}; + Account const owner{"owner"}; + Account const depositor{"depositor"}; env.fund(XRP(1000), issuer, owner, depositor); env.close(); - Vault vault{env}; - PrettyAsset asset = issuer["IOU"]; + Vault const vault{env}; + PrettyAsset const asset = issuer["IOU"]; env.trust(asset(1000), owner); env(pay(issuer, owner, asset(100))); env.trust(asset(1000), depositor); @@ -1480,7 +1480,7 @@ class Vault_test : public beast::unit_test::suite }(); auto const MptID = makeMptID(1, vaultAccount); - Asset shares = MptID; + Asset const shares = MptID; { testcase("nontransferable shares cannot be moved"); @@ -1563,7 +1563,7 @@ class Vault_test : public beast::unit_test::suite (args.enableClawback ? tfMPTCanClawback : none) | (args.requireAuth ? tfMPTRequireAuth : none), .mutableFlags = tmfMPTCanMutateCanTransfer}); - PrettyAsset asset = mptt.issuanceID(); + PrettyAsset const asset = mptt.issuanceID(); mptt.authorize({.account = owner}); mptt.authorize({.account = depositor}); if (args.requireAuth) @@ -1654,10 +1654,10 @@ class Vault_test : public beast::unit_test::suite // accounts for the issued shares. auto v = env.le(keylet); BEAST_EXPECT(v); - MPTID share = (*v)[sfShareMPTID]; + MPTID const share = (*v)[sfShareMPTID]; auto issuance = env.le(keylet::mptIssuance(share)); BEAST_EXPECT(issuance); - Number outstandingShares = issuance->at(sfOutstandingAmount); + Number const outstandingShares = issuance->at(sfOutstandingAmount); BEAST_EXPECT(outstandingShares == 100); mptt.set({.account = issuer, .flags = tfMPTLock}); @@ -1761,7 +1761,7 @@ class Vault_test : public beast::unit_test::suite { // Set destination to 3rd party without MPToken - Account charlie{"charlie"}; + Account const charlie{"charlie"}; env.fund(XRP(1000), charlie); env.close(); @@ -1838,7 +1838,7 @@ class Vault_test : public beast::unit_test::suite {.requireAuth = false}); auto const [acctReserve, incReserve] = [this]() -> std::pair { - Env env{*this, testable_amendments()}; + Env const env{*this, testable_amendments()}; return { env.current()->fees().accountReserve(0).drops() / DROPS_PER_XRP.drops(), env.current()->fees().increment.drops() / DROPS_PER_XRP.drops()}; @@ -1975,7 +1975,7 @@ class Vault_test : public beast::unit_test::suite auto const vault = env.le(keylet); return vault->at(sfShareMPTID); }(keylet); - PrettyAsset shares = MPTIssue(issuanceId); + PrettyAsset const shares = MPTIssue(issuanceId); { // owner has MPToken for shares they did not explicitly create @@ -2177,14 +2177,14 @@ class Vault_test : public beast::unit_test::suite Account issuer{"issuer"}; env.fund(XRP(1000000), owner, issuer); env.close(); - Vault vault{env}; + Vault const vault{env}; MPTTester mptt{env, issuer, mptInitNoFund}; mptt.create( {.flags = tfMPTCanTransfer | tfMPTCanLock | lsfMPTCanClawback | tfMPTRequireAuth}); mptt.authorize({.account = owner}); mptt.authorize({.account = issuer, .holder = owner}); - PrettyAsset asset = mptt.issuanceID(); + PrettyAsset const asset = mptt.issuanceID(); env(pay(issuer, owner, asset(100))); auto [tx1, k1] = vault.create({.owner = owner, .asset = asset}); env(tx1); @@ -2650,7 +2650,7 @@ class Vault_test : public beast::unit_test::suite } { - PrettyAsset shares = issuanceId(keylet); + PrettyAsset const shares = issuanceId(keylet); auto tx1 = vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(100)}); env(tx1); @@ -2761,7 +2761,7 @@ class Vault_test : public beast::unit_test::suite {.initialIOU = Number(11875, -2)}); auto const [acctReserve, incReserve] = [this]() -> std::pair { - Env env{*this, testable_amendments()}; + Env const env{*this, testable_amendments()}; return { env.current()->fees().accountReserve(0).drops() / DROPS_PER_XRP.drops(), env.current()->fees().increment.drops() / DROPS_PER_XRP.drops()}; @@ -2950,22 +2950,22 @@ class Vault_test : public beast::unit_test::suite testcase("private vault"); Env env{*this, testable_amendments() | featureSingleAssetVault}; - Account issuer{"issuer"}; - Account owner{"owner"}; - Account depositor{"depositor"}; - Account charlie{"charlie"}; - Account pdOwner{"pdOwner"}; - Account credIssuer1{"credIssuer1"}; - Account credIssuer2{"credIssuer2"}; + Account const issuer{"issuer"}; + Account const owner{"owner"}; + Account const depositor{"depositor"}; + Account const charlie{"charlie"}; + Account const pdOwner{"pdOwner"}; + Account const credIssuer1{"credIssuer1"}; + Account const credIssuer2{"credIssuer2"}; std::string const credType = "credential"; - Vault vault{env}; + Vault const vault{env}; env.fund(XRP(1000), issuer, owner, depositor, charlie, pdOwner, credIssuer1, credIssuer2); env.close(); env(fset(issuer, asfAllowTrustLineClawback)); env.close(); env.require(flags(issuer, asfAllowTrustLineClawback)); - PrettyAsset asset = issuer["IOU"]; + PrettyAsset const asset = issuer["IOU"]; env.trust(asset(1000), owner); env(pay(issuer, owner, asset(500))); env.trust(asset(1000), depositor); @@ -3198,15 +3198,15 @@ class Vault_test : public beast::unit_test::suite testcase("private XRP vault"); Env env{*this, testable_amendments() | featureSingleAssetVault}; - Account owner{"owner"}; - Account depositor{"depositor"}; - Account alice{"charlie"}; + Account const owner{"owner"}; + Account const depositor{"depositor"}; + Account const alice{"charlie"}; std::string const credType = "credential"; - Vault vault{env}; + Vault const vault{env}; env.fund(XRP(100000), owner, depositor, alice); env.close(); - PrettyAsset asset = xrpIssue(); + PrettyAsset const asset = xrpIssue(); auto [tx, keylet] = vault.create({.owner = owner, .asset = asset, .flags = tfVaultPrivate}); env(tx); env.close(); @@ -3219,7 +3219,7 @@ class Vault_test : public beast::unit_test::suite }(); BEAST_EXPECT(env.le(keylet::account(vaultAccount))); BEAST_EXPECT(env.le(keylet::mptIssuance(issuanceId))); - PrettyAsset shares{issuanceId}; + PrettyAsset const shares{issuanceId}; { testcase("private XRP vault owner can deposit"); @@ -3296,7 +3296,7 @@ class Vault_test : public beast::unit_test::suite testcase("fail pseudo-account allocation"); Env env{*this, testable_amendments() | featureSingleAssetVault}; Account const owner{"owner"}; - Vault vault{env}; + Vault const vault{env}; env.fund(XRP(1000), owner); auto const keylet = keylet::vault(owner.id(), env.seq(owner)); @@ -3362,7 +3362,7 @@ class Vault_test : public beast::unit_test::suite auto const vault = env.le(keylet); return {Account("vault", vault->at(sfAccount)), vault->at(sfShareMPTID)}; }(keylet); - MPTIssue shares(issuanceId); + MPTIssue const shares(issuanceId); env.memoize(vaultAccount); auto const peek = [keylet, &env, this](std::function fn) -> bool { @@ -4113,11 +4113,11 @@ class Vault_test : public beast::unit_test::suite Env env{*this, testable_amendments() | featureSingleAssetVault}; Account const owner{"owner"}; Account const issuer{"issuer"}; - Vault vault{env}; + Vault const vault{env}; env.fund(XRP(1000), issuer, owner); env.close(); - PrettyAsset asset = issuer["IOU"]; + PrettyAsset const asset = issuer["IOU"]; env.trust(asset(1000), owner); env(pay(issuer, owner, asset(200))); env.close(); @@ -4545,7 +4545,7 @@ class Vault_test : public beast::unit_test::suite auto const setupVault = [&](PrettyAsset const& asset, Account const& owner, Account const& depositor) -> std::pair { - Vault vault{env}; + Vault const vault{env}; auto const& [tx, vaultKeylet] = vault.create({.owner = owner, .asset = asset}); env(tx, ter(tesSUCCESS)); @@ -4554,7 +4554,7 @@ class Vault_test : public beast::unit_test::suite auto const& vaultSle = env.le(vaultKeylet); BEAST_EXPECT(vaultSle != nullptr); - Asset share = vaultSle->at(sfShareMPTID); + Asset const share = vaultSle->at(sfShareMPTID); env(vault.deposit( {.depositor = depositor, .id = vaultKeylet.key, .amount = asset(100)}), @@ -4651,7 +4651,7 @@ class Vault_test : public beast::unit_test::suite BEAST_EXPECT(vaultSle != nullptr); if (!vaultSle) return; - Asset share = vaultSle->at(sfShareMPTID); + Asset const share = vaultSle->at(sfShareMPTID); env(vault.clawback({ .issuer = owner, .id = vaultKeylet.key, @@ -4687,7 +4687,7 @@ class Vault_test : public beast::unit_test::suite BEAST_EXPECT(vaultSle != nullptr); if (!vaultSle) return; - Asset share = vaultSle->at(sfShareMPTID); + Asset const share = vaultSle->at(sfShareMPTID); env(vault.clawback({ .issuer = owner, .id = vaultKeylet.key, @@ -4704,7 +4704,7 @@ class Vault_test : public beast::unit_test::suite BEAST_EXPECT(vaultSle != nullptr); if (!vaultSle) return; - Asset share = vaultSle->at(sfShareMPTID); + Asset const share = vaultSle->at(sfShareMPTID); env(vault.clawback({ .issuer = owner, .id = vaultKeylet.key, @@ -4721,7 +4721,7 @@ class Vault_test : public beast::unit_test::suite auto const& vaultSle = env.le(vaultKeylet); if (BEAST_EXPECT(vaultSle != nullptr)) return; - Asset share = vaultSle->at(sfShareMPTID); + Asset const share = vaultSle->at(sfShareMPTID); env(vault.clawback({ .issuer = owner, .id = vaultKeylet.key, @@ -4743,18 +4743,18 @@ class Vault_test : public beast::unit_test::suite Account owner{"alice"}; Account depositor{"bob"}; - Account issuer{"issuer"}; + Account const issuer{"issuer"}; env.fund(XRP(10000), issuer, owner, depositor); env.close(); // Test XRP - PrettyAsset xrp = xrpIssue(); + PrettyAsset const xrp = xrpIssue(); testCase(xrp, "XRP", owner, depositor); testCase(xrp, "XRP (depositor is owner)", owner, owner); // Test IOU - PrettyAsset IOU = issuer["IOU"]; + PrettyAsset const IOU = issuer["IOU"]; env(fset(issuer, asfAllowTrustLineClawback)); env.close(); @@ -4769,7 +4769,7 @@ class Vault_test : public beast::unit_test::suite // Test MPT MPTTester mptt{env, issuer, mptInitNoFund}; mptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); - PrettyAsset MPT = mptt.issuanceID(); + PrettyAsset const MPT = mptt.issuanceID(); mptt.authorize({.account = owner}); mptt.authorize({.account = depositor}); env(pay(issuer, owner, MPT(1000))); @@ -4791,7 +4791,7 @@ class Vault_test : public beast::unit_test::suite Account const& owner, Account const& depositor, Account const& issuer) -> std::pair { - Vault vault{env}; + Vault const vault{env}; auto const& [tx, vaultKeylet] = vault.create({.owner = owner, .asset = asset}); env(tx, ter(tesSUCCESS)); @@ -4840,8 +4840,8 @@ class Vault_test : public beast::unit_test::suite "VaultClawback (asset) - " + prefix + " clawback for different asset fails"); auto [vault, vaultKeylet] = setupVault(asset, owner, depositor, issuer); - Account issuer2{"issuer2"}; - PrettyAsset asset2 = issuer2["FOO"]; + Account const issuer2{"issuer2"}; + PrettyAsset const asset2 = issuer2["FOO"]; env(vault.clawback({ .issuer = issuer, .id = vaultKeylet.key, @@ -4902,7 +4902,7 @@ class Vault_test : public beast::unit_test::suite BEAST_EXPECT(vaultSle != nullptr); if (!vaultSle) return; - Asset share = vaultSle->at(sfShareMPTID); + Asset const share = vaultSle->at(sfShareMPTID); env(vault.clawback({ .issuer = issuer, @@ -4959,17 +4959,17 @@ class Vault_test : public beast::unit_test::suite Account owner{"alice"}; Account depositor{"bob"}; - Account issuer{"issuer"}; + Account const issuer{"issuer"}; env.fund(XRP(10000), issuer, owner, depositor); env.close(); // Test XRP - PrettyAsset xrp = xrpIssue(); + PrettyAsset const xrp = xrpIssue(); testCase(xrp, "XRP", owner, depositor, issuer); // Test IOU - PrettyAsset IOU = issuer["IOU"]; + PrettyAsset const IOU = issuer["IOU"]; env(fset(issuer, asfAllowTrustLineClawback)); env.close(); env.trust(IOU(1000), owner); @@ -4982,7 +4982,7 @@ class Vault_test : public beast::unit_test::suite // Test MPT MPTTester mptt{env, issuer, mptInitNoFund}; mptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); - PrettyAsset MPT = mptt.issuanceID(); + PrettyAsset const MPT = mptt.issuanceID(); mptt.authorize({.account = owner}); mptt.authorize({.account = depositor}); env(pay(issuer, depositor, MPT(1000))); @@ -5001,7 +5001,7 @@ class Vault_test : public beast::unit_test::suite Account const owner{"owner"}; Account const issuer{"issuer"}; - Vault vault{env}; + Vault const vault{env}; env.fund(XRP(1'000'000), issuer, owner); env.close(); @@ -5116,7 +5116,7 @@ class Vault_test : public beast::unit_test::suite testcase("Assets Maximum: IOU"); // Almost anything goes with IOUs - PrettyAsset iouAsset = issuer["IOU"]; + PrettyAsset const iouAsset = issuer["IOU"]; env.trust(iouAsset(1000), owner); env(pay(issuer, owner, iouAsset(200))); env.close(); diff --git a/src/test/app/XChain_test.cpp b/src/test/app/XChain_test.cpp index 72f2597883..abaeccb4ff 100644 --- a/src/test/app/XChain_test.cpp +++ b/src/test/app/XChain_test.cpp @@ -130,7 +130,7 @@ struct SEnv std::shared_ptr bridge(Json::Value const& jvb) { - STXChainBridge b(jvb); + STXChainBridge const b(jvb); auto tryGet = [&](STXChainBridge::ChainType ct) -> std::shared_ptr { if (auto r = env_.le(keylet::bridge(b, ct))) @@ -180,7 +180,7 @@ struct XEnv : public jtx::XChainBridgeObjects, public SEnv XEnv(T& s, bool side = false) : SEnv(s, jtx::envconfig(), features) { using namespace jtx; - STAmount xrp_funds{XRP(10000)}; + STAmount const xrp_funds{XRP(10000)}; if (!side) { @@ -359,7 +359,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj try { exceptionPresent = false; - [[maybe_unused]] STXChainBridge testBridge1(jBridge); + [[maybe_unused]] STXChainBridge const testBridge1(jBridge); } catch (std::exception& ec) { @@ -372,7 +372,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj { exceptionPresent = false; jBridge["Extra"] = 1; - [[maybe_unused]] STXChainBridge testBridge2(jBridge); + [[maybe_unused]] STXChainBridge const testBridge2(jBridge); } catch ([[maybe_unused]] std::exception& ec) { @@ -385,7 +385,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj void testXChainCreateBridge() { - XRPAmount res1 = reserve(1); + XRPAmount const res1 = reserve(1); using namespace jtx; testcase("Create Bridge"); @@ -807,12 +807,12 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj auto const& expected = expected_result[test_result.size()]; mcEnv.tx(create_bridge(a, bridge(a, ia, b, ib)), ter(TER::fromInt(expected.first))); - TER mcTER = mcEnv.env_.ter(); + TER const mcTER = mcEnv.env_.ter(); scEnv.tx(create_bridge(b, bridge(a, ia, b, ib)), ter(TER::fromInt(expected.second))); - TER scTER = scEnv.env_.ter(); + TER const scTER = scEnv.env_.ter(); - bool pass = isTesSuccess(mcTER) && isTesSuccess(scTER); + bool const pass = isTesSuccess(mcTER) && isTesSuccess(scTER); test_result.emplace_back(mcTER, scTER, pass); }; @@ -1155,8 +1155,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj testXChainCreateClaimID() { using namespace jtx; - XRPAmount res1 = reserve(1); - XRPAmount tx_fee = txFee(); + XRPAmount const res1 = reserve(1); + XRPAmount const tx_fee = txFee(); testcase("Create ClaimID"); @@ -1173,7 +1173,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj { XEnv xenv(*this, true); - Balance scAlice_bal(xenv, scAlice); + Balance const scAlice_bal(xenv, scAlice); xenv.tx(create_bridge(Account::master, jvb)) .tx(xchain_create_claim_id(scAlice, jvb, reward, mcAlice)) @@ -1240,8 +1240,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj testXChainCommit() { using namespace jtx; - XRPAmount res0 = reserve(0); - XRPAmount tx_fee = txFee(); + XRPAmount const res0 = reserve(0); + XRPAmount const tx_fee = txFee(); testcase("Commit"); @@ -1252,7 +1252,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj { XEnv xenv(*this); - Balance alice_bal(xenv, mcAlice); + Balance const alice_bal(xenv, mcAlice); auto const amt = XRP(1000); xenv.tx(create_bridge(mcDoor, jvb)) @@ -1260,7 +1260,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj .tx(xchain_commit(mcAlice, jvb, 1, amt, scBob)) .close(); - STAmount claim_cost = amt; + STAmount const claim_cost = amt; BEAST_EXPECT(alice_bal.diff() == -(claim_cost + tx_fee)); } @@ -1369,7 +1369,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj using namespace jtx; testcase("Add Attestation"); - XRPAmount res0 = reserve(0); + XRPAmount const res0 = reserve(0); XRPAmount tx_fee = txFee(); auto multiTtxFee = [&](std::uint32_t m) -> STAmount { @@ -1457,7 +1457,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj std::uint32_t const quorum_7 = 7; std::vector const signers_ = [] { constexpr int numSigners = 4; - std::uint32_t weights[] = {1, 2, 4, 4}; + std::uint32_t const weights[] = {1, 2, 4, 4}; std::vector result; result.reserve(numSigners); @@ -1515,7 +1515,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj std::uint32_t const quorum_7 = 7; std::vector const signers_ = [] { constexpr int numSigners = 4; - std::uint32_t weights[] = {1, 2, 4, 4}; + std::uint32_t const weights[] = {1, 2, 4, 4}; std::vector result; result.reserve(numSigners); @@ -1575,7 +1575,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj std::uint32_t const quorum_7 = 7; std::vector const signers_ = [] { constexpr int numSigners = 4; - std::uint32_t weights[] = {1, 2, 4, 4}; + std::uint32_t const weights[] = {1, 2, 4, 4}; std::vector result; result.reserve(numSigners); @@ -1634,7 +1634,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj std::uint32_t const quorum_7 = 7; std::vector const signers_ = [] { constexpr int numSigners = 4; - std::uint32_t weights[] = {1, 2, 4, 4}; + std::uint32_t const weights[] = {1, 2, 4, 4}; std::vector result; result.reserve(numSigners); @@ -1697,8 +1697,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj auto const amt_plus_reward = amt + reward; { - Balance door(mcEnv, mcDoor); - Balance carol(mcEnv, mcCarol); + Balance const door(mcEnv, mcDoor); + Balance const carol(mcEnv, mcCarol); mcEnv.tx(create_bridge(mcDoor, jvb, reward, XRP(20))) .close() @@ -1719,8 +1719,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj { // send first batch of account create attest for all 3 // account create - Balance attester(scEnv, scAttester); - Balance door(scEnv, Account::master); + Balance const attester(scEnv, scAttester); + Balance const door(scEnv, Account::master); scEnv.multiTx(att_create_acct_vec(1, amt, scuAlice, 2)) .multiTx(att_create_acct_vec(3, amt, scuCarol, 2)) @@ -1740,8 +1740,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj { // complete attestations for 2nd account create => should // not complete - Balance attester(scEnv, scAttester); - Balance door(scEnv, Account::master); + Balance const attester(scEnv, scAttester); + Balance const door(scEnv, Account::master); scEnv.multiTx(att_create_acct_vec(2, amt, scuBob, 3, 2)).close(); @@ -1756,8 +1756,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj { // complete attestations for 3rd account create => should // not complete - Balance attester(scEnv, scAttester); - Balance door(scEnv, Account::master); + Balance const attester(scEnv, scAttester); + Balance const door(scEnv, Account::master); scEnv.multiTx(att_create_acct_vec(3, amt, scuCarol, 3, 2)).close(); @@ -1772,8 +1772,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj { // complete attestations for 1st account create => account // should be created - Balance attester(scEnv, scAttester); - Balance door(scEnv, Account::master); + Balance const attester(scEnv, scAttester); + Balance const door(scEnv, Account::master); scEnv.multiTx(att_create_acct_vec(1, amt, scuAlice, 3, 1)).close(); @@ -1791,8 +1791,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj { // resend attestations for 3rd account create => still // should not complete - Balance attester(scEnv, scAttester); - Balance door(scEnv, Account::master); + Balance const attester(scEnv, scAttester); + Balance const door(scEnv, Account::master); scEnv.multiTx(att_create_acct_vec(3, amt, scuCarol, 3, 2)).close(); @@ -1808,8 +1808,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj { // resend attestations for 2nd account create => account // should be created - Balance attester(scEnv, scAttester); - Balance door(scEnv, Account::master); + Balance const attester(scEnv, scAttester); + Balance const door(scEnv, Account::master); scEnv.multiTx(att_create_acct_vec(2, amt, scuBob, 1)).close(); @@ -1824,8 +1824,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj { // resend attestations for 3rc account create => account // should be created - Balance attester(scEnv, scAttester); - Balance door(scEnv, Account::master); + Balance const attester(scEnv, scAttester); + Balance const door(scEnv, Account::master); scEnv.multiTx(att_create_acct_vec(3, amt, scuCarol, 1)).close(); @@ -1850,8 +1850,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj mcEnv.tx(create_bridge(mcDoor, jvb, reward, XRP(20))).close(); { - Balance door(mcEnv, mcDoor); - Balance carol(mcEnv, mcCarol); + Balance const door(mcEnv, mcDoor); + Balance const carol(mcEnv, mcCarol); mcEnv.tx(sidechain_xchain_account_create(mcCarol, jvb, scuAlice, amt, reward)) .close(); @@ -1864,8 +1864,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj .tx(jtx::signers(Account::master, quorum, signers)) .close(); - Balance attester(scEnv, scAttester); - Balance door(scEnv, Account::master); + Balance const attester(scEnv, scAttester); + Balance const door(scEnv, Account::master); scEnv.multiTx(att_create_acct_vec(1, amt, scuAlice, 2)).close(); BEAST_EXPECT(!!scEnv.caClaimID(jvb, 1)); // claim id present @@ -1892,8 +1892,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj mcEnv.tx(create_bridge(mcDoor, jvb, reward, XRP(20))).close(); { - Balance door(mcEnv, mcDoor); - Balance carol(mcEnv, mcCarol); + Balance const door(mcEnv, mcDoor); + Balance const carol(mcEnv, mcCarol); mcEnv.tx(sidechain_xchain_account_create(mcCarol, jvb, scAlice, amt, reward)) .close(); @@ -1906,9 +1906,9 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj .tx(jtx::signers(Account::master, quorum, signers)) .close(); - Balance attester(scEnv, scAttester); - Balance door(scEnv, Account::master); - Balance alice(scEnv, scAlice); + Balance const attester(scEnv, scAttester); + Balance const door(scEnv, Account::master); + Balance const alice(scEnv, scAlice); scEnv.multiTx(att_create_acct_vec(1, amt, scAlice, 2)).close(); BEAST_EXPECT(!!scEnv.caClaimID(jvb, 1)); // claim id present @@ -1935,8 +1935,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj mcEnv.tx(create_bridge(mcDoor, jvb, reward, XRP(20))).close(); { - Balance door(mcEnv, mcDoor); - Balance carol(mcEnv, mcCarol); + Balance const door(mcEnv, mcDoor); + Balance const carol(mcEnv, mcCarol); mcEnv.tx(sidechain_xchain_account_create(mcCarol, jvb, scAlice, amt, reward)) .close(); @@ -1950,9 +1950,9 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj .tx(fset("scAlice", asfDepositAuth)) // set deposit auth .close(); - Balance attester(scEnv, scAttester); - Balance door(scEnv, Account::master); - Balance alice(scEnv, scAlice); + Balance const attester(scEnv, scAttester); + Balance const door(scEnv, Account::master); + Balance const alice(scEnv, scAlice); scEnv.multiTx(att_create_acct_vec(1, amt, scAlice, 2)).close(); BEAST_EXPECT(!!scEnv.caClaimID(jvb, 1)); // claim id present @@ -1979,8 +1979,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj auto const amt_plus_reward = amt + reward; { - Balance door(mcEnv, mcDoor); - Balance carol(mcEnv, mcCarol); + Balance const door(mcEnv, mcDoor); + Balance const carol(mcEnv, mcCarol); mcEnv.tx(create_bridge(mcDoor, jvb, reward, XRP(20))) .close() @@ -2002,8 +2002,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj .close(); { - Balance attester(scEnv, scAttester); - Balance door(scEnv, Account::master); + Balance const attester(scEnv, scAttester); + Balance const door(scEnv, Account::master); auto const bad_amt = XRP(10); std::uint32_t txCount = 0; @@ -2290,16 +2290,16 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj XEnv mcEnv(*this); XEnv scEnv(*this, true); - XRPAmount tx_fee = mcEnv.txFee(); + XRPAmount const tx_fee = mcEnv.txFee(); - Account a{"a"}; - Account doorA{"doorA"}; + Account const a{"a"}; + Account const doorA{"doorA"}; - STAmount funds{XRP(10000)}; + STAmount const funds{XRP(10000)}; mcEnv.fund(funds, a); mcEnv.fund(funds, doorA); - Account ua{"ua"}; // unfunded account we want to create + Account const ua{"ua"}; // unfunded account we want to create BridgeDef xrp_b{ doorA, @@ -2317,8 +2317,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj auto const amt = XRP(777); auto const amt_plus_reward = amt + xrp_b.reward; { - Balance bal_doorA(mcEnv, doorA); - Balance bal_a(mcEnv, a); + Balance const bal_doorA(mcEnv, doorA); + Balance const bal_a(mcEnv, a); mcEnv.tx(sidechain_xchain_account_create(a, xrp_b.jvb, ua, amt, xrp_b.reward)).close(); @@ -2360,8 +2360,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj { using namespace jtx; - XRPAmount res0 = reserve(0); - XRPAmount tx_fee = txFee(); + XRPAmount const res0 = reserve(0); + XRPAmount const tx_fee = txFee(); testcase("Claim"); @@ -2436,7 +2436,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj BalanceTransfer transfer( scEnv, Account::master, scBob, scAlice, &payees[0], 1, withClaim); - jtx::signer master_signer(Account::master); + jtx::signer const master_signer(Account::master); scEnv .tx(claim_attestation( scAttester, @@ -2481,7 +2481,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj BalanceTransfer transfer( scEnv, Account::master, scBob, scAlice, &payees[0], 1, withClaim); - jtx::signer master_signer(payees[0]); + jtx::signer const master_signer(payees[0]); scEnv .tx(claim_attestation( scAttester, @@ -2861,7 +2861,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj XEnv scEnv(*this, true); mcEnv.tx(create_bridge(mcDoor, jvb)).close(); - STAmount huge_reward{XRP(20000)}; + STAmount const huge_reward{XRP(20000)}; BEAST_EXPECT(huge_reward > scEnv.balance(scAlice)); scEnv.tx(create_bridge(Account::master, jvb, huge_reward)) @@ -3009,7 +3009,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj // the transfer failed, but check that we can still use the // claimID with a different account - Balance scCarol_bal(scEnv, scCarol); + Balance const scCarol_bal(scEnv, scCarol); scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scCarol)).close(); BEAST_EXPECT(scCarol_bal.diff() == amt); @@ -3026,7 +3026,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj .tx(fset("scBob", 0, asfDepositAuth)) // clear deposit auth .close(); - Balance scBob_bal(scEnv, scBob); + Balance const scBob_bal(scEnv, scBob); scEnv.tx(txns.back()).close(); BEAST_EXPECT(scBob_bal.diff() == amt); } @@ -3078,7 +3078,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj // the transfer failed, but check that we can still use the // claimID with a different account - Balance scCarol_bal(scEnv, scCarol); + Balance const scCarol_bal(scEnv, scCarol); scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scCarol)).close(); BEAST_EXPECT(scCarol_bal.diff() == amt); @@ -3095,7 +3095,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj .tx(fset("scBob", 0, asfRequireDest)) // clear dest tag .close(); - Balance scBob_bal(scEnv, scBob); + Balance const scBob_bal(scEnv, scBob); scEnv.tx(txns.back()).close(); BEAST_EXPECT(scBob_bal.diff() == amt); @@ -3126,7 +3126,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj // we should be able to submit the attestations, but the transfer // should not occur because dest account has deposit auth set - Balance scBob_bal(scEnv, scBob); + Balance const scBob_bal(scEnv, scBob); scEnv.multiTx(claim_attestations( scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)); @@ -3134,7 +3134,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj // Check that check that we still can use the claimID to transfer // the amount to a different account - Balance scCarol_bal(scEnv, scCarol); + Balance const scCarol_bal(scEnv, scCarol); scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scCarol)).close(); BEAST_EXPECT(scCarol_bal.diff() == amt); @@ -3213,7 +3213,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj &payees[0], UT_XCHAIN_DEFAULT_QUORUM, withClaim); - Balance scAlice_bal(scEnv, scAlice); + Balance const scAlice_bal(scEnv, scAlice); scEnv.multiTx(claim_attestations( scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)); @@ -3261,7 +3261,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj &payees[0], UT_XCHAIN_DEFAULT_QUORUM, withClaim); - Balance scAlice_bal(scEnv, scAlice); + Balance const scAlice_bal(scEnv, scAlice); scEnv.multiTx(claim_attestations( scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)); STAmount claim_cost = tiny_reward; @@ -3350,7 +3350,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); // balance of last signer should not change (has deposit auth) - Balance last_signer(scEnv, unpaid); + Balance const last_signer(scEnv, unpaid); // make sure all signers except the last one get the // split_reward @@ -3414,7 +3414,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj using namespace jtx; testcase("Bridge Create Account"); - XRPAmount tx_fee = txFee(); + XRPAmount const tx_fee = txFee(); // coverage test: transferHelper() - dst == src { @@ -3427,7 +3427,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj .tx(jtx::signers(Account::master, quorum, signers)) .close(); - Balance door(scEnv, Account::master); + Balance const door(scEnv, Account::master); // scEnv.tx(att_create_acct_batch1(1, amt, // Account::master)).close(); @@ -3451,8 +3451,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj mcEnv.tx(create_bridge(mcDoor, jvb, XRP(1), XRP(20))).close(); - Balance door(mcEnv, mcDoor); - Balance carol(mcEnv, mcCarol); + Balance const door(mcEnv, mcDoor); + Balance const carol(mcEnv, mcCarol); mcEnv .tx(sidechain_xchain_account_create(mcCarol, jvb, scuAlice, XRP(19), reward), @@ -3469,7 +3469,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj mcEnv.tx(create_bridge(mcDoor, jvb, XRP(1), XRP(20))).close(); - Balance door(mcEnv, mcDoor); + Balance const door(mcEnv, mcDoor); mcEnv .tx(sidechain_xchain_account_create(mcCarol, jvb, scuAlice, XRP(20), reward), @@ -3487,7 +3487,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj mcEnv.tx(create_bridge(mcDoor, jvb, XRP(1), XRP(20))).close(); - Balance door(mcEnv, mcDoor); + Balance const door(mcEnv, mcDoor); mcEnv.disableFeature(featureXChainBridge) .tx(sidechain_xchain_account_create(mcCarol, jvb, scuAlice, XRP(20), reward), @@ -3503,7 +3503,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj mcEnv.tx(create_bridge(mcDoor, jvb, XRP(1), XRP(20))).close(); - Balance door(mcEnv, mcDoor); + Balance const door(mcEnv, mcDoor); mcEnv .tx(sidechain_xchain_account_create(mcCarol, jvb, scuAlice, XRP(-20), reward), @@ -3519,7 +3519,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj mcEnv.tx(create_bridge(mcDoor, jvb, XRP(1), XRP(20))).close(); - Balance door(mcEnv, mcDoor); + Balance const door(mcEnv, mcDoor); mcEnv .tx(sidechain_xchain_account_create(mcCarol, jvb, scuAlice, XRP(20), XRP(-1)), @@ -3535,7 +3535,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj mcEnv.tx(create_bridge(mcDoor, jvb, XRP(1), XRP(20))).close(); - Balance door(mcEnv, mcDoor); + Balance const door(mcEnv, mcDoor); mcEnv .tx(sidechain_xchain_account_create(mcDoor, jvb, scuAlice, XRP(20), XRP(1)), @@ -3551,7 +3551,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj mcEnv.tx(create_bridge(mcDoor, jvb, XRP(1), XRP(20))).close(); - Balance door(mcEnv, mcDoor); + Balance const door(mcEnv, mcDoor); mcEnv .tx(sidechain_xchain_account_create(mcCarol, jvb, scuAlice, XRP(20), XRP(2)), @@ -3566,8 +3566,8 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj testFeeDipsIntoReserve() { using namespace jtx; - XRPAmount res0 = reserve(0); - XRPAmount tx_fee = txFee(); + XRPAmount const res0 = reserve(0); + XRPAmount const tx_fee = txFee(); testcase("Fee dips into reserve"); @@ -3660,7 +3660,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj // Create a bridge and add an attestation with a bad public key XEnv scEnv(*this, true); std::uint32_t const claimID = 1; - std::optional dst{scBob}; + std::optional const dst{scBob}; auto const amt = XRP(1000); scEnv.tx(create_bridge(Account::master, jvb)) .tx(jtx::signers(Account::master, quorum, signers)) @@ -3689,7 +3689,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj // public key XEnv scEnv(*this, true); std::uint32_t const createCount = 1; - Account dst{scBob}; + Account const dst{scBob}; auto const amt = XRP(1000); auto const rewardAmt = XRP(1); scEnv.tx(create_bridge(Account::master, jvb)) @@ -3789,8 +3789,8 @@ private: bool verify(ENV& env, jtx::Account const& acct) const { - STAmount diff{env.balance(acct) - startAmount}; - bool check = diff == expectedDiff; + STAmount const diff{env.balance(acct) - startAmount}; + bool const check = diff == expectedDiff; return check; } }; @@ -4093,7 +4093,7 @@ private: size_t i = 0; for (i = 0; i < num_signers; ++i) { - size_t signer_idx = (rnd + i) % num_signers; + size_t const signer_idx = (rnd + i) % num_signers; if (!(cr.attested[signer_idx])) { @@ -4251,7 +4251,7 @@ private: // check all signers, but start at a random one for (size_t i = 0; i < num_signers; ++i) { - size_t signer_idx = (rnd + i) % num_signers; + size_t const signer_idx = (rnd + i) % num_signers; if (!(xfer.attested[signer_idx])) { // enqueue one attestation for this signer @@ -4275,7 +4275,7 @@ private: } // return true if quorum was reached, false otherwise - bool quorum = + bool const quorum = std::count(xfer.attested.begin(), xfer.attested.end(), true) >= bridge_.quorum; if (quorum && xfer.with_claim == WithClaim::no) { @@ -4380,7 +4380,7 @@ public: for (auto it = sm_.begin(); it != sm_.end();) { auto vis = [&](auto& sm) { - uint32_t rnd = distrib(gen); + uint32_t const rnd = distrib(gen); return sm.advance(time, rnd); }; auto& [t, sm] = *it; @@ -4446,14 +4446,14 @@ public: for (auto& acct : a) { - STAmount amt{XRP(100000)}; + STAmount const amt{XRP(100000)}; mcEnv.fund(amt, acct); scEnv.fund(amt, acct); } - Account USDLocking{"USDLocking"}; - IOU usdLocking{USDLocking["USD"]}; - IOU usdIssuing{doorUSDIssuing["USD"]}; + Account const USDLocking{"USDLocking"}; + IOU const usdLocking{USDLocking["USD"]}; + IOU const usdIssuing{doorUSDIssuing["USD"]}; mcEnv.fund(XRP(100000), USDLocking); mcEnv.close(); diff --git a/src/test/app/tx/apply_test.cpp b/src/test/app/tx/apply_test.cpp index 10b0544f49..6d3efea5f3 100644 --- a/src/test/app/tx/apply_test.cpp +++ b/src/test/app/tx/apply_test.cpp @@ -37,7 +37,7 @@ public: { test::jtx::Env fully_canonical(*this, test::jtx::testable_amendments()); - Validity valid = + Validity const valid = checkValidity( fully_canonical.app().getHashRouter(), tx, fully_canonical.current()->rules()) .first; diff --git a/src/test/basics/Buffer_test.cpp b/src/test/basics/Buffer_test.cpp index a329e527ba..95a8853975 100644 --- a/src/test/basics/Buffer_test.cpp +++ b/src/test/basics/Buffer_test.cpp @@ -26,7 +26,7 @@ struct Buffer_test : beast::unit_test::suite 0xac, 0x2d, 0x89, 0x4d, 0x19, 0x9c, 0xf0, 0x2c, 0x15, 0xd1, 0xf9, 0x9b, 0x66, 0xd2, 0x30, 0xd3}; - Buffer b0; + Buffer const b0; BEAST_EXPECT(sane(b0)); BEAST_EXPECT(b0.empty()); @@ -105,7 +105,7 @@ struct Buffer_test : beast::unit_test::suite { // Move-construct from empty buf Buffer x; - Buffer y{std::move(x)}; + Buffer const y{std::move(x)}; BEAST_EXPECT(sane(x)); // NOLINT(bugprone-use-after-move) BEAST_EXPECT(x.empty()); // NOLINT(bugprone-use-after-move) BEAST_EXPECT(sane(y)); @@ -115,7 +115,7 @@ struct Buffer_test : beast::unit_test::suite { // Move-construct from non-empty buf Buffer x{b1}; - Buffer y{std::move(x)}; + Buffer const y{std::move(x)}; BEAST_EXPECT(sane(x)); // NOLINT(bugprone-use-after-move) BEAST_EXPECT(x.empty()); // NOLINT(bugprone-use-after-move) BEAST_EXPECT(sane(y)); diff --git a/src/test/basics/Expected_test.cpp b/src/test/basics/Expected_test.cpp index 2caa15816f..fa35946624 100644 --- a/src/test/basics/Expected_test.cpp +++ b/src/test/basics/Expected_test.cpp @@ -46,7 +46,7 @@ struct Expected_test : beast::unit_test::suite BEAST_EXPECT(expected.value() == "Valid value"); BEAST_EXPECT(*expected == "Valid value"); BEAST_EXPECT(expected->at(0) == 'V'); - std::string mv = std::move(*expected); + std::string const mv = std::move(*expected); BEAST_EXPECT(mv == "Valid value"); bool throwOccurred = false; diff --git a/src/test/basics/FileUtilities_test.cpp b/src/test/basics/FileUtilities_test.cpp index 3d6f9b754b..b63f8baf0a 100644 --- a/src/test/basics/FileUtilities_test.cpp +++ b/src/test/basics/FileUtilities_test.cpp @@ -17,7 +17,7 @@ public: constexpr char const* expectedContents = "This file is very short. That's all we need."; - FileDirGuard file( + FileDirGuard const file( *this, "test_file", "test.txt", "This is temporary text that should get overwritten"); error_code ec; diff --git a/src/test/basics/IOUAmount_test.cpp b/src/test/basics/IOUAmount_test.cpp index 73ab0343cd..d0e272c28b 100644 --- a/src/test/basics/IOUAmount_test.cpp +++ b/src/test/basics/IOUAmount_test.cpp @@ -55,7 +55,7 @@ public: using beast::zero; { - IOUAmount z(zero); + IOUAmount const z(zero); BEAST_EXPECT(z == zero); BEAST_EXPECT(z >= zero); BEAST_EXPECT(z <= zero); @@ -94,9 +94,11 @@ public: BEAST_EXPECT(z >= z); BEAST_EXPECT(z <= z); BEAST_EXPECT(z == -z); + // NOLINTBEGIN(misc-redundant-expression) unexpected(z > z); unexpected(z < z); unexpected(z != z); + // NOLINTEND(misc-redundant-expression) unexpected(z != -z); BEAST_EXPECT(n < z); @@ -150,7 +152,7 @@ public: for (auto const mantissaSize : {MantissaRange::small, MantissaRange::large}) { - NumberMantissaScaleGuard mg(mantissaSize); + NumberMantissaScaleGuard const mg(mantissaSize); test(IOUAmount(-2, 0), "-2"); test(IOUAmount(0, 0), "0"); @@ -181,14 +183,14 @@ public: { // multiply by a number that would overflow the mantissa, then // divide by the same number, and check we didn't lose any value - IOUAmount bigMan(maxMantissa, 0); + IOUAmount const bigMan(maxMantissa, 0); BEAST_EXPECT(bigMan == mulRatio(bigMan, maxUInt, maxUInt, true)); // rounding mode shouldn't matter as the result is exact BEAST_EXPECT(bigMan == mulRatio(bigMan, maxUInt, maxUInt, false)); } { // Similar test as above, but for negative values - IOUAmount bigMan(-maxMantissa, 0); + IOUAmount const bigMan(-maxMantissa, 0); BEAST_EXPECT(bigMan == mulRatio(bigMan, maxUInt, maxUInt, true)); // rounding mode shouldn't matter as the result is exact BEAST_EXPECT(bigMan == mulRatio(bigMan, maxUInt, maxUInt, false)); @@ -196,7 +198,7 @@ public: { // small amounts - IOUAmount tiny(minMantissa, minExponent); + IOUAmount const tiny(minMantissa, minExponent); // Round up should give the smallest allowable number BEAST_EXPECT(tiny == mulRatio(tiny, 1, maxUInt, true)); BEAST_EXPECT(tiny == mulRatio(tiny, maxUInt - 1, maxUInt, true)); @@ -205,7 +207,7 @@ public: BEAST_EXPECT(beast::zero == mulRatio(tiny, maxUInt - 1, maxUInt, false)); // tiny negative numbers - IOUAmount tinyNeg(-minMantissa, minExponent); + IOUAmount const tinyNeg(-minMantissa, minExponent); // Round up should give zero BEAST_EXPECT(beast::zero == mulRatio(tinyNeg, 1, maxUInt, true)); BEAST_EXPECT(beast::zero == mulRatio(tinyNeg, maxUInt - 1, maxUInt, true)); @@ -216,20 +218,20 @@ public: { // rounding { - IOUAmount one(1, 0); + IOUAmount const one(1, 0); auto const rup = mulRatio(one, maxUInt - 1, maxUInt, true); auto const rdown = mulRatio(one, maxUInt - 1, maxUInt, false); BEAST_EXPECT(rup.mantissa() - rdown.mantissa() == 1); } { - IOUAmount big(maxMantissa, maxExponent); + IOUAmount const big(maxMantissa, maxExponent); auto const rup = mulRatio(big, maxUInt - 1, maxUInt, true); auto const rdown = mulRatio(big, maxUInt - 1, maxUInt, false); BEAST_EXPECT(rup.mantissa() - rdown.mantissa() == 1); } { - IOUAmount negOne(-1, 0); + IOUAmount const negOne(-1, 0); auto const rup = mulRatio(negOne, maxUInt - 1, maxUInt, true); auto const rdown = mulRatio(negOne, maxUInt - 1, maxUInt, false); BEAST_EXPECT(rup.mantissa() - rdown.mantissa() == 1); diff --git a/src/test/basics/IntrusiveShared_test.cpp b/src/test/basics/IntrusiveShared_test.cpp index 41ecf9a7a4..52cb8f5c1c 100644 --- a/src/test/basics/IntrusiveShared_test.cpp +++ b/src/test/basics/IntrusiveShared_test.cpp @@ -191,16 +191,16 @@ public: testcase("Basics"); { - TIBase::ResetStatesGuard rsg{true}; + TIBase::ResetStatesGuard const rsg{true}; - TIBase b; + TIBase const b; BEAST_EXPECT(b.use_count() == 1); b.addWeakRef(); BEAST_EXPECT(b.use_count() == 1); auto s = b.releaseStrongRef(); BEAST_EXPECT(s == ReleaseStrongRefAction::partialDestroy); BEAST_EXPECT(b.use_count() == 0); - TIBase* pb = &b; + TIBase const* pb = &b; partialDestructorFinished(&pb); BEAST_EXPECT(!pb); auto w = b.releaseWeakRef(); @@ -210,7 +210,7 @@ public: std::vector> strong; std::vector> weak; { - TIBase::ResetStatesGuard rsg{true}; + TIBase::ResetStatesGuard const rsg{true}; using enum TrackedState; auto b = make_SharedIntrusive(); @@ -251,7 +251,7 @@ public: BEAST_EXPECT(TIBase::getState(id) == deleted); } { - TIBase::ResetStatesGuard rsg{true}; + TIBase::ResetStatesGuard const rsg{true}; using enum TrackedState; auto b = make_SharedIntrusive(); @@ -275,7 +275,7 @@ public: BEAST_EXPECT(TIBase::getState(id) == deleted); } { - TIBase::ResetStatesGuard rsg{true}; + TIBase::ResetStatesGuard const rsg{true}; using enum TrackedState; using swu = SharedWeakUnion; @@ -309,7 +309,7 @@ public: { // Testing SharedWeakUnion assignment operator - TIBase::ResetStatesGuard rsg{true}; + TIBase::ResetStatesGuard const rsg{true}; auto strong1 = make_SharedIntrusive(); auto strong2 = make_SharedIntrusive(); @@ -338,7 +338,7 @@ public: // 2) Test self-assignment BEAST_EXPECT(union1.isStrong()); BEAST_EXPECT(TIBase::getState(id1) == TrackedState::alive); - int initialRefCount = strong1->use_count(); + int const initialRefCount = strong1->use_count(); #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wself-assign-overloaded" union1 = union1; // Self-assignment @@ -374,7 +374,7 @@ public: using enum TrackedState; - TIBase::ResetStatesGuard rsg{true}; + TIBase::ResetStatesGuard const rsg{true}; auto strong = make_SharedIntrusive(); WeakIntrusive weak{strong}; @@ -441,7 +441,7 @@ public: using enum TrackedState; - TIBase::ResetStatesGuard rsg{true}; + TIBase::ResetStatesGuard const rsg{true}; auto strong = make_SharedIntrusive(); WeakIntrusive weak{strong}; @@ -486,12 +486,12 @@ public: // and check that the invariants hold. using enum TrackedState; - TIBase::ResetStatesGuard rsg{true}; + TIBase::ResetStatesGuard const rsg{true}; std::atomic destructionState{0}; // returns destructorRan and partialDestructorRan (in that order) auto getDestructorState = [&]() -> std::pair { - int s = destructionState.load(std::memory_order_relaxed); + int const s = destructionState.load(std::memory_order_relaxed); return {(s & 1) != 0, (s & 2) != 0}; }; auto setDestructorRan = [&]() -> void { @@ -620,12 +620,12 @@ public: using enum TrackedState; - TIBase::ResetStatesGuard rsg{true}; + TIBase::ResetStatesGuard const rsg{true}; std::atomic destructionState{0}; // returns destructorRan and partialDestructorRan (in that order) auto getDestructorState = [&]() -> std::pair { - int s = destructionState.load(std::memory_order_relaxed); + int const s = destructionState.load(std::memory_order_relaxed); return {(s & 1) != 0, (s & 2) != 0}; }; auto setDestructorRan = [&]() -> void { @@ -761,12 +761,12 @@ public: using enum TrackedState; - TIBase::ResetStatesGuard rsg{true}; + TIBase::ResetStatesGuard const rsg{true}; std::atomic destructionState{0}; // returns destructorRan and partialDestructorRan (in that order) auto getDestructorState = [&]() -> std::pair { - int s = destructionState.load(std::memory_order_relaxed); + int const s = destructionState.load(std::memory_order_relaxed); return {(s & 1) != 0, (s & 2) != 0}; }; auto setDestructorRan = [&]() -> void { @@ -832,7 +832,7 @@ public: // Multiple threads all create a weak pointer from the same // strong pointer - WeakIntrusive weak{toLock[threadId]}; + WeakIntrusive const weak{toLock[threadId]}; for (int wi = 0; wi < lockWeakLoopIters; ++wi) { BEAST_EXPECT(!weak.expired()); diff --git a/src/test/basics/Number_test.cpp b/src/test/basics/Number_test.cpp index 4676884660..856b379533 100644 --- a/src/test/basics/Number_test.cpp +++ b/src/test/basics/Number_test.cpp @@ -37,7 +37,8 @@ public: auto const minMantissa = Number::minMantissa(); try { - Number x = Number{false, minMantissa * 10, 32768, Number::normalized{}}; + [[maybe_unused]] Number const x = + Number{false, minMantissa * 10, 32768, Number::normalized{}}; } catch (std::overflow_error const&) { @@ -86,7 +87,7 @@ public: try { [[maybe_unused]] - Number q = Number{false, minMantissa, 32767, Number::normalized{}} * 100; + Number const q = Number{false, minMantissa, 32767, Number::normalized{}} * 100; } catch (std::overflow_error const&) { @@ -332,7 +333,7 @@ public: }; auto const maxMantissa = Number::maxMantissa(); - saveNumberRoundMode save{Number::setround(Number::to_nearest)}; + saveNumberRoundMode const save{Number::setround(Number::to_nearest)}; { auto const cSmall = std::to_array({ {Number{7}, Number{8}, Number{56}}, @@ -642,7 +643,7 @@ public: test(cLarge); } }; - saveNumberRoundMode save{Number::setround(Number::to_nearest)}; + saveNumberRoundMode const save{Number::setround(Number::to_nearest)}; { auto const cSmall = std::to_array( {{Number{1}, Number{2}, Number{5, -1}}, @@ -857,7 +858,7 @@ public: test(cSmall); if (Number::getMantissaScale() != MantissaRange::small) { - NumberRoundModeGuard mg(Number::towards_zero); + NumberRoundModeGuard const mg(Number::towards_zero); test(cLarge); } bool caught = false; @@ -928,7 +929,7 @@ public: { testcase << "test_power1 " << to_string(Number::getMantissaScale()); using Case = std::tuple; - Case c[]{ + Case const c[]{ {Number{64}, 0, Number{1}}, {Number{64}, 1, Number{64}}, {Number{64}, 2, Number{4096}}, @@ -946,7 +947,7 @@ public: { testcase << "test_power2 " << to_string(Number::getMantissaScale()); using Case = std::tuple; - Case c[]{ + Case const c[]{ {Number{1}, 3, 7, Number{1}}, {Number{-1}, 1, 0, Number{1}}, {Number{-1, -1}, 1, 0, Number{0}}, @@ -992,24 +993,24 @@ public: { testcase << "testConversions " << to_string(Number::getMantissaScale()); - IOUAmount x{5, 6}; - Number y = x; + IOUAmount const x{5, 6}; + Number const y = x; BEAST_EXPECT((y == Number{5, 6})); - IOUAmount z{y}; + IOUAmount const z{y}; BEAST_EXPECT(x == z); - XRPAmount xrp{500}; - STAmount st = xrp; - Number n = st; + XRPAmount const xrp{500}; + STAmount const st = xrp; + Number const n = st; BEAST_EXPECT(XRPAmount{n} == xrp); - IOUAmount x0{0, 0}; - Number y0 = x0; + IOUAmount const x0{0, 0}; + Number const y0 = x0; BEAST_EXPECT((y0 == Number{0})); - IOUAmount z0{y0}; + IOUAmount const z0{y0}; BEAST_EXPECT(x0 == z0); - XRPAmount xrp0{0}; - Number n0 = xrp0; + XRPAmount const xrp0{0}; + Number const n0 = xrp0; BEAST_EXPECT(n0 == Number{0}); - XRPAmount xrp1{n0}; + XRPAmount const xrp1{n0}; BEAST_EXPECT(xrp1 == xrp0); } @@ -1018,9 +1019,9 @@ public: { testcase << "test_to_integer " << to_string(Number::getMantissaScale()); using Case = std::tuple; - saveNumberRoundMode save{Number::setround(Number::to_nearest)}; + saveNumberRoundMode const save{Number::setround(Number::to_nearest)}; { - Case c[]{ + Case const c[]{ {Number{0}, 0}, {Number{1}, 1}, {Number{2}, 2}, @@ -1058,7 +1059,7 @@ public: auto prev_mode = Number::setround(Number::towards_zero); BEAST_EXPECT(prev_mode == Number::to_nearest); { - Case c[]{ + Case const c[]{ {Number{0}, 0}, {Number{1}, 1}, {Number{2}, 2}, @@ -1096,7 +1097,7 @@ public: prev_mode = Number::setround(Number::downward); BEAST_EXPECT(prev_mode == Number::towards_zero); { - Case c[]{ + Case const c[]{ {Number{0}, 0}, {Number{1}, 1}, {Number{2}, 2}, @@ -1134,7 +1135,7 @@ public: prev_mode = Number::setround(Number::upward); BEAST_EXPECT(prev_mode == Number::downward); { - Case c[]{ + Case const c[]{ {Number{0}, 0}, {Number{1}, 1}, {Number{2}, 2}, @@ -1185,7 +1186,7 @@ public: test_squelch() { testcase << "test_squelch " << to_string(Number::getMantissaScale()); - Number limit{1, -6}; + Number const limit{1, -6}; BEAST_EXPECT((squelch(Number{2, -6}, limit) == Number{2, -6})); BEAST_EXPECT((squelch(Number{1, -6}, limit) == Number{1, -6})); BEAST_EXPECT((squelch(Number{9, -7}, limit) == Number{0})); @@ -1233,7 +1234,7 @@ public: test(Number::max(), "9999999999999999e32768"); test(Number::lowest(), "-9999999999999999e32768"); { - NumberRoundModeGuard mg(Number::towards_zero); + NumberRoundModeGuard const mg(Number::towards_zero); auto const maxMantissa = Number::maxMantissa(); BEAST_EXPECT(maxMantissa == 9'999'999'999'999'999); @@ -1263,7 +1264,7 @@ public: test(Number::max(), "9223372036854775807e32768"); test(Number::lowest(), "-9223372036854775807e32768"); { - NumberRoundModeGuard mg(Number::towards_zero); + NumberRoundModeGuard const mg(Number::towards_zero); auto const maxMantissa = Number::maxMantissa(); BEAST_EXPECT(maxMantissa == 9'999'999'999'999'999'999ULL); @@ -1314,7 +1315,7 @@ public: test_stream() { testcase << "test_stream " << to_string(Number::getMantissaScale()); - Number x{100}; + Number const x{100}; std::ostringstream os; os << x; BEAST_EXPECT(os.str() == to_string(x)); @@ -1325,7 +1326,7 @@ public: { testcase << "test_inc_dec " << to_string(Number::getMantissaScale()); Number x{100}; - Number y = +x; + Number const y = +x; BEAST_EXPECT(x == y); BEAST_EXPECT(x++ == y); BEAST_EXPECT(x == Number{101}); @@ -1336,7 +1337,7 @@ public: void test_toSTAmount() { - NumberSO stNumberSO{true}; + NumberSO const stNumberSO{true}; Issue const issue; Number const n{7'518'783'80596, -5}; saveNumberRoundMode const save{Number::setround(Number::to_nearest)}; @@ -1478,7 +1479,7 @@ public: { for (auto const& [mode, val] : roundings) { - NumberRoundModeGuard g{mode}; + NumberRoundModeGuard const g{mode}; auto const res = static_cast(num); BEAST_EXPECTS( res == val, @@ -1496,7 +1497,7 @@ public: // Control case BEAST_EXPECT(Number::maxMantissa() > 10); - Number ten{10}; + Number const ten{10}; BEAST_EXPECT(ten.exponent() <= 0); if (scale == MantissaRange::small) @@ -1528,7 +1529,7 @@ public: // 85'070'591'730'234'615'847'396'907'784'232'501'249 - 38 digits BEAST_EXPECT((power(maxInt64, 2) == Number{85'070'591'730'234'615'85, 19})); - NumberRoundModeGuard mg(Number::towards_zero); + NumberRoundModeGuard const mg(Number::towards_zero); auto const maxMantissa = Number::maxMantissa(); Number const max = Number{false, maxMantissa, 0, Number::normalized{}}; @@ -1546,7 +1547,7 @@ public: { for (auto const scale : {MantissaRange::small, MantissaRange::large}) { - NumberMantissaScaleGuard sg(scale); + NumberMantissaScaleGuard const sg(scale); testZero(); test_limits(); testToString(); diff --git a/src/test/basics/StringUtilities_test.cpp b/src/test/basics/StringUtilities_test.cpp index 78719e47c6..fb7cdb3d69 100644 --- a/src/test/basics/StringUtilities_test.cpp +++ b/src/test/basics/StringUtilities_test.cpp @@ -279,7 +279,7 @@ public: } { - std::string strUrl("s://" + std::string(8192, ':')); + std::string const strUrl("s://" + std::string(8192, ':')); parsedURL pUrl; BEAST_EXPECT(!parseUrl(pUrl, strUrl)); } diff --git a/src/test/basics/Units_test.cpp b/src/test/basics/Units_test.cpp index 9693c6d181..6bb7f400cc 100644 --- a/src/test/basics/Units_test.cpp +++ b/src/test/basics/Units_test.cpp @@ -14,7 +14,7 @@ private: using FeeLevel32 = FeeLevel; { - XRPAmount x{100}; + XRPAmount const x{100}; BEAST_EXPECT(x.drops() == 100); BEAST_EXPECT((std::is_same_v)); auto y = 4u * x; @@ -25,8 +25,8 @@ private: BEAST_EXPECT(z.value() == 1600); BEAST_EXPECT((std::is_same_v)); - FeeLevel32 f{10}; - FeeLevel32 baseFee{100}; + FeeLevel32 const f{10}; + FeeLevel32 const baseFee{100}; auto drops = mulDiv(baseFee, x, f); @@ -39,15 +39,15 @@ private: BEAST_EXPECT((std::is_same_v, XRPAmount>)); } { - XRPAmount x{100}; + XRPAmount const x{100}; BEAST_EXPECT(x.value() == 100); BEAST_EXPECT((std::is_same_v)); auto y = 4u * x; BEAST_EXPECT(y.value() == 400); BEAST_EXPECT((std::is_same_v)); - FeeLevel64 f{10}; - FeeLevel64 baseFee{100}; + FeeLevel64 const f{10}; + FeeLevel64 const baseFee{100}; auto drops = mulDiv(baseFee, x, f); @@ -59,16 +59,16 @@ private: BEAST_EXPECT((std::is_same_v, XRPAmount>)); } { - FeeLevel64 x{1024}; + FeeLevel64 const x{1024}; BEAST_EXPECT(x.value() == 1024); BEAST_EXPECT((std::is_same_v)); - std::uint64_t m = 4; + std::uint64_t const m = 4; auto y = m * x; BEAST_EXPECT(y.value() == 4096); BEAST_EXPECT((std::is_same_v)); - XRPAmount basefee{10}; - FeeLevel64 referencefee{256}; + XRPAmount const basefee{10}; + FeeLevel64 const referencefee{256}; auto drops = mulDiv(x, basefee, referencefee); @@ -88,56 +88,56 @@ private: using FeeLevel32 = FeeLevel; { - FeeLevel32 x{std::numeric_limits::max()}; + FeeLevel32 const x{std::numeric_limits::max()}; auto y = x.jsonClipped(); BEAST_EXPECT(y.type() == Json::uintValue); BEAST_EXPECT(y == Json::Value{x.fee()}); } { - FeeLevel32 x{std::numeric_limits::min()}; + FeeLevel32 const x{std::numeric_limits::min()}; auto y = x.jsonClipped(); BEAST_EXPECT(y.type() == Json::uintValue); BEAST_EXPECT(y == Json::Value{x.fee()}); } { - FeeLevel64 x{std::numeric_limits::max()}; + FeeLevel64 const x{std::numeric_limits::max()}; auto y = x.jsonClipped(); BEAST_EXPECT(y.type() == Json::uintValue); BEAST_EXPECT(y == Json::Value{std::numeric_limits::max()}); } { - FeeLevel64 x{std::numeric_limits::min()}; + FeeLevel64 const x{std::numeric_limits::min()}; auto y = x.jsonClipped(); BEAST_EXPECT(y.type() == Json::uintValue); BEAST_EXPECT(y == Json::Value{0}); } { - FeeLevelDouble x{std::numeric_limits::max()}; + FeeLevelDouble const x{std::numeric_limits::max()}; auto y = x.jsonClipped(); BEAST_EXPECT(y.type() == Json::realValue); BEAST_EXPECT(y == Json::Value{std::numeric_limits::max()}); } { - FeeLevelDouble x{std::numeric_limits::min()}; + FeeLevelDouble const x{std::numeric_limits::min()}; auto y = x.jsonClipped(); BEAST_EXPECT(y.type() == Json::realValue); BEAST_EXPECT(y == Json::Value{std::numeric_limits::min()}); } { - XRPAmount x{std::numeric_limits::max()}; + XRPAmount const x{std::numeric_limits::max()}; auto y = x.jsonClipped(); BEAST_EXPECT(y.type() == Json::intValue); BEAST_EXPECT(y == Json::Value{std::numeric_limits::max()}); } { - XRPAmount x{std::numeric_limits::min()}; + XRPAmount const x{std::numeric_limits::min()}; auto y = x.jsonClipped(); BEAST_EXPECT(y.type() == Json::intValue); BEAST_EXPECT(y == Json::Value{std::numeric_limits::min()}); @@ -156,7 +156,7 @@ private: auto explicitmake = [&](auto x) -> FeeLevel64 { return FeeLevel64{x}; }; [[maybe_unused]] - FeeLevel64 defaulted; + FeeLevel64 const defaulted{}; FeeLevel64 test{0}; BEAST_EXPECT(test.fee() == 0); @@ -241,7 +241,7 @@ private: auto explicitmake = [&](auto x) -> FeeLevelDouble { return FeeLevelDouble{x}; }; [[maybe_unused]] - FeeLevelDouble defaulted; + FeeLevelDouble const defaulted{}; FeeLevelDouble test{0}; BEAST_EXPECT(test.fee() == 0); diff --git a/src/test/basics/XRPAmount_test.cpp b/src/test/basics/XRPAmount_test.cpp index 58b15b5d2d..ad81050558 100644 --- a/src/test/basics/XRPAmount_test.cpp +++ b/src/test/basics/XRPAmount_test.cpp @@ -127,7 +127,7 @@ public: // since some of them are templated, but not used anywhere else. auto make = [&](auto x) -> XRPAmount { return XRPAmount{x}; }; - XRPAmount defaulted{}; + XRPAmount const defaulted{}; (void)defaulted; XRPAmount test{0}; BEAST_EXPECT(test.drops() == 0); @@ -230,7 +230,8 @@ public: { // Similar test as above, but for negative values - XRPAmount big(minXRP); + XRPAmount big(minXRP); // NOLINT(misc-const-correctness): const breaks overflow check + // at end of this scope BEAST_EXPECT(big == mulRatio(big, maxUInt32, maxUInt32, true)); // rounding mode shouldn't matter as the result is exact BEAST_EXPECT(big == mulRatio(big, maxUInt32, maxUInt32, false)); @@ -244,7 +245,7 @@ public: { // small amounts - XRPAmount tiny(1); + XRPAmount const tiny(1); // Round up should give the smallest allowable number BEAST_EXPECT(tiny == mulRatio(tiny, 1, maxUInt32, true)); // rounding down should be zero @@ -252,7 +253,7 @@ public: BEAST_EXPECT(beast::zero == mulRatio(tiny, maxUInt32 - 1, maxUInt32, false)); // tiny negative numbers - XRPAmount tinyNeg(-1); + XRPAmount const tinyNeg(-1); // Round up should give zero BEAST_EXPECT(beast::zero == mulRatio(tinyNeg, 1, maxUInt32, true)); BEAST_EXPECT(beast::zero == mulRatio(tinyNeg, maxUInt32 - 1, maxUInt32, true)); @@ -262,21 +263,21 @@ public: { // rounding { - XRPAmount one(1); + XRPAmount const one(1); auto const rup = mulRatio(one, maxUInt32 - 1, maxUInt32, true); auto const rdown = mulRatio(one, maxUInt32 - 1, maxUInt32, false); BEAST_EXPECT(rup.drops() - rdown.drops() == 1); } { - XRPAmount big(maxXRP); + XRPAmount const big(maxXRP); auto const rup = mulRatio(big, maxUInt32 - 1, maxUInt32, true); auto const rdown = mulRatio(big, maxUInt32 - 1, maxUInt32, false); BEAST_EXPECT(rup.drops() - rdown.drops() == 1); } { - XRPAmount negOne(-1); + XRPAmount const negOne(-1); auto const rup = mulRatio(negOne, maxUInt32 - 1, maxUInt32, true); auto const rdown = mulRatio(negOne, maxUInt32 - 1, maxUInt32, false); BEAST_EXPECT(rup.drops() - rdown.drops() == 1); @@ -297,7 +298,7 @@ public: { // underflow - XRPAmount bigNegative(minXRP + 10); + XRPAmount const bigNegative(minXRP + 10); BEAST_EXPECT(mulRatio(bigNegative, 2, 1, true) == minXRP); } } // namespace xrpl diff --git a/src/test/basics/base_uint_test.cpp b/src/test/basics/base_uint_test.cpp index c8f931e2b5..139c635e5f 100644 --- a/src/test/basics/base_uint_test.cpp +++ b/src/test/basics/base_uint_test.cpp @@ -120,7 +120,7 @@ struct base_uint_test : beast::unit_test::suite // used to verify set insertion (hashing required) std::unordered_set> uset; - Blob raw{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; + Blob const raw{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; BEAST_EXPECT(test96::bytes == raw.size()); test96 u{raw}; @@ -144,7 +144,7 @@ struct base_uint_test : beast::unit_test::suite // back into another base_uint (w) for comparison with the original nonhash<96> h{}; hash_append(h, u); - test96 w{std::vector(h.data_.begin(), h.data_.end())}; + test96 const w{std::vector(h.data_.begin(), h.data_.end())}; BEAST_EXPECT(w == u); test96 v{~u}; @@ -200,7 +200,7 @@ struct base_uint_test : beast::unit_test::suite zp1++; test96 zm1{z}; zm1--; - test96 x{zm1 ^ zp1}; + test96 const x{zm1 ^ zp1}; uset.insert(x); BEAST_EXPECTS(to_string(x) == "FFFFFFFFFFFFFFFFFFFFFFFE", to_string(x)); BEAST_EXPECTS(to_short_string(x) == "FFFFFFFF...", to_short_string(x)); @@ -285,8 +285,8 @@ struct base_uint_test : beast::unit_test::suite { // Try to prevent constant evaluation. std::vector str(23, '7'); - std::string_view sView(str.data(), str.size()); - [[maybe_unused]] test96 t96(sView); + std::string_view const sView(str.data(), str.size()); + [[maybe_unused]] test96 const t96(sView); } catch (std::invalid_argument const& e) { @@ -303,8 +303,8 @@ struct base_uint_test : beast::unit_test::suite // Try to prevent constant evaluation. std::vector str(23, '7'); str.push_back('G'); - std::string_view sView(str.data(), str.size()); - [[maybe_unused]] test96 t96(sView); + std::string_view const sView(str.data(), str.size()); + [[maybe_unused]] test96 const t96(sView); } catch (std::range_error const& e) { diff --git a/src/test/basics/hardened_hash_test.cpp b/src/test/basics/hardened_hash_test.cpp index 1a6609ac29..3910e5e414 100644 --- a/src/test/basics/hardened_hash_test.cpp +++ b/src/test/basics/hardened_hash_test.cpp @@ -189,13 +189,13 @@ public: check_container() { { - C> c; + C> const c; } pass(); { - C> c; + C> const c; } pass(); diff --git a/src/test/beast/IPEndpoint_test.cpp b/src/test/beast/IPEndpoint_test.cpp index 6276f7cd96..ce01743896 100644 --- a/src/test/beast/IPEndpoint_test.cpp +++ b/src/test/beast/IPEndpoint_test.cpp @@ -51,7 +51,7 @@ public: BEAST_EXPECT(AddressV4{0x01020304}.to_uint() == 0x01020304); { - AddressV4::bytes_type d = {{1, 2, 3, 4}}; + AddressV4::bytes_type const d = {{1, 2, 3, 4}}; BEAST_EXPECT(AddressV4{d}.to_uint() == 0x01020304); unexpected(is_unspecified(AddressV4{d})); @@ -110,7 +110,7 @@ public: { testcase("AddressV4::Bytes"); - AddressV4::bytes_type d1 = {{10, 0, 0, 1}}; + AddressV4::bytes_type const d1 = {{10, 0, 0, 1}}; AddressV4 v4{d1}; BEAST_EXPECT(v4.to_bytes()[0] == 10); BEAST_EXPECT(v4.to_bytes()[1] == 0); @@ -136,8 +136,8 @@ public: testcase("Address"); boost::system::error_code ec; - Address result{boost::asio::ip::make_address("1.2.3.4", ec)}; - AddressV4::bytes_type d = {{1, 2, 3, 4}}; + Address const result{boost::asio::ip::make_address("1.2.3.4", ec)}; + AddressV4::bytes_type const d = {{1, 2, 3, 4}}; BEAST_EXPECT(!ec); BEAST_EXPECT(result.is_v4() && result.to_v4() == AddressV4{d}); } @@ -286,7 +286,7 @@ public: BEAST_EXPECTS(to_string(ep) == "::ffff:166.78.151.147", to_string(ep)); // a private IPv6 - AddressV6::bytes_type d2 = {{253, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}; + AddressV6::bytes_type const d2 = {{253, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}; ep = Endpoint(AddressV6{d2}); BEAST_EXPECT(!is_unspecified(ep)); BEAST_EXPECT(!is_public(ep)); diff --git a/src/test/beast/LexicalCast_test.cpp b/src/test/beast/LexicalCast_test.cpp index 5cfc73a6f6..aa3ccfe64e 100644 --- a/src/test/beast/LexicalCast_test.cpp +++ b/src/test/beast/LexicalCast_test.cpp @@ -224,7 +224,7 @@ public: while (i <= std::numeric_limits::max()) { - std::int16_t j = static_cast(i); + std::int16_t const j = static_cast(i); auto actual = std::to_string(j); diff --git a/src/test/beast/aged_associative_container_test.cpp b/src/test/beast/aged_associative_container_test.cpp index 1578ffceca..c47b41478b 100644 --- a/src/test/beast/aged_associative_container_test.cpp +++ b/src/test/beast/aged_associative_container_test.cpp @@ -915,7 +915,7 @@ typename std::enable_if::type aged_associative_container_test_base::testConstructInitList() { using Traits = TestTraits; - typename Traits::ManualClock clock; + typename Traits::ManualClock const clock; // testcase (Traits::name() + " init-list"); testcase("init-list"); @@ -931,7 +931,7 @@ typename std::enable_if::type aged_associative_container_test_base::testConstructInitList() { using Traits = TestTraits; - typename Traits::ManualClock clock; + typename Traits::ManualClock const clock; // testcase (Traits::name() + " init-list"); testcase("init-list"); @@ -1033,8 +1033,8 @@ aged_associative_container_test_base::testIterator() using const_iterator = decltype(c.cbegin()); // Should be able to construct or assign an iterator from an iterator. - iterator nnIt_0{c.begin()}; - iterator nnIt_1{nnIt_0}; + iterator const nnIt_0{c.begin()}; + iterator const nnIt_1{nnIt_0}; BEAST_EXPECT(nnIt_0 == nnIt_1); iterator nnIt_2; nnIt_2 = nnIt_1; @@ -1042,8 +1042,8 @@ aged_associative_container_test_base::testIterator() // Should be able to construct or assign a const_iterator from a // const_iterator. - const_iterator ccIt_0{c.cbegin()}; - const_iterator ccIt_1{ccIt_0}; + const_iterator const ccIt_0{c.cbegin()}; + const_iterator const ccIt_1{ccIt_0}; BEAST_EXPECT(ccIt_0 == ccIt_1); const_iterator ccIt_2; ccIt_2 = ccIt_1; @@ -1054,8 +1054,8 @@ aged_associative_container_test_base::testIterator() BEAST_EXPECT(ccIt_1 == nnIt_1); // Should be able to construct a const_iterator from an iterator. - const_iterator ncIt_3{c.begin()}; - const_iterator ncIt_4{nnIt_0}; + const_iterator const ncIt_3{c.begin()}; + const_iterator const ncIt_4{nnIt_0}; BEAST_EXPECT(ncIt_3 == ncIt_4); const_iterator ncIt_5; ncIt_5 = nnIt_2; @@ -1098,8 +1098,8 @@ aged_associative_container_test_base::testReverseIterator() // Should be able to construct or assign a reverse_iterator from a // reverse_iterator. - reverse_iterator rNrNit_0{c.rbegin()}; - reverse_iterator rNrNit_1{rNrNit_0}; + reverse_iterator const rNrNit_0{c.rbegin()}; + reverse_iterator const rNrNit_1{rNrNit_0}; BEAST_EXPECT(rNrNit_0 == rNrNit_1); reverse_iterator xXrNit_2; xXrNit_2 = rNrNit_1; @@ -1107,8 +1107,8 @@ aged_associative_container_test_base::testReverseIterator() // Should be able to construct or assign a const_reverse_iterator from a // const_reverse_iterator - const_reverse_iterator rCrCit_0{c.crbegin()}; - const_reverse_iterator rCrCit_1{rCrCit_0}; + const_reverse_iterator const rCrCit_0{c.crbegin()}; + const_reverse_iterator const rCrCit_1{rCrCit_0}; BEAST_EXPECT(rCrCit_0 == rCrCit_1); const_reverse_iterator xXrCit_2; xXrCit_2 = rCrCit_1; @@ -1120,8 +1120,8 @@ aged_associative_container_test_base::testReverseIterator() // Should be able to construct or assign a const_reverse_iterator from a // reverse_iterator - const_reverse_iterator rNrCit_0{c.rbegin()}; - const_reverse_iterator rNrCit_1{rNrNit_0}; + const_reverse_iterator const rNrCit_0{c.rbegin()}; + const_reverse_iterator const rNrCit_1{rNrNit_0}; BEAST_EXPECT(rNrCit_0 == rNrCit_1); xXrCit_2 = rNrNit_1; BEAST_EXPECT(rNrCit_1 == xXrCit_2); @@ -1132,10 +1132,10 @@ aged_associative_container_test_base::testReverseIterator() // const_iterator. // Should be able to construct or assign reverse_iterators from // non-reverse iterators. - reverse_iterator fNrNit_0{c.begin()}; - const_reverse_iterator fNrCit_0{c.begin()}; + reverse_iterator const fNrNit_0{c.begin()}; + const_reverse_iterator const fNrCit_0{c.begin()}; BEAST_EXPECT(fNrNit_0 == fNrCit_0); - const_reverse_iterator fCrCit_0{c.cbegin()}; + const_reverse_iterator const fCrCit_0{c.cbegin()}; BEAST_EXPECT(fNrCit_0 == fCrCit_0); // None of these should compile because they construct a non-reverse @@ -1146,7 +1146,7 @@ aged_associative_container_test_base::testReverseIterator() // You should not be able to assign an iterator to a reverse_iterator or // vise-versa. So the following lines should not compile. - iterator xXfNit_0; + iterator const xXfNit_0; // xXfNit_0 = xXrNit_2; // xXrNit_2 = xXfNit_0; } @@ -1297,7 +1297,7 @@ aged_associative_container_test_base::testChronological() for (auto iter(v.crbegin()); iter != v.crend(); ++iter) { using iterator = typename decltype(c)::iterator; - iterator found(c.find(Traits::extract(*iter))); + iterator const found(c.find(Traits::extract(*iter))); BEAST_EXPECT(found != c.cend()); if (found == c.cend()) @@ -1317,7 +1317,7 @@ aged_associative_container_test_base::testChronological() for (auto iter(v.cbegin()); iter != v.cend(); ++iter) { using const_iterator = typename decltype(c)::const_iterator; - const_iterator found(c.find(Traits::extract(*iter))); + const_iterator const found(c.find(Traits::extract(*iter))); BEAST_EXPECT(found != c.cend()); if (found == c.cend()) @@ -1642,7 +1642,7 @@ aged_associative_container_test_base::testCompare() // testcase (Traits::name() + " array create"); testcase("array create"); - typename Traits::template Cont<> c1(v.begin(), v.end(), clock); + typename Traits::template Cont<> const c1(v.begin(), v.end(), clock); typename Traits::template Cont<> c2(v.begin(), v.end(), clock); c2.erase(c2.cbegin()); @@ -1672,7 +1672,7 @@ aged_associative_container_test_base::testObservers() // testcase (Traits::name() + " observers"); testcase("observers"); - typename Traits::template Cont<> c(clock); + typename Traits::template Cont<> const c(clock); c.key_comp(); c.value_comp(); @@ -1690,7 +1690,7 @@ aged_associative_container_test_base::testObservers() // testcase (Traits::name() + " observers"); testcase("observers"); - typename Traits::template Cont<> c(clock); + typename Traits::template Cont<> const c(clock); c.hash_function(); c.key_eq(); diff --git a/src/test/beast/beast_Journal_test.cpp b/src/test/beast/beast_Journal_test.cpp index cb190e57a0..35ab3640bd 100644 --- a/src/test/beast/beast_Journal_test.cpp +++ b/src/test/beast/beast_Journal_test.cpp @@ -50,7 +50,7 @@ public: using namespace beast::severities; sink.threshold(kInfo); - Journal j(sink); + Journal const j(sink); j.trace() << " "; BEAST_EXPECT(sink.count() == 0); diff --git a/src/test/beast/beast_PropertyStream_test.cpp b/src/test/beast/beast_PropertyStream_test.cpp index 35aa91d18e..9e76749218 100644 --- a/src/test/beast/beast_PropertyStream_test.cpp +++ b/src/test/beast/beast_PropertyStream_test.cpp @@ -67,7 +67,7 @@ public: { try { - Source* source(root.find_one(name)); + Source const* source(root.find_one(name)); BEAST_EXPECT(source == expected); } catch (...) @@ -82,7 +82,7 @@ public: { try { - Source* source(root.find_path(path)); + Source const* source(root.find_path(path)); BEAST_EXPECT(source == expected); } catch (...) @@ -97,7 +97,7 @@ public: { try { - Source* source(root.find_one_deep(name)); + Source const* source(root.find_one_deep(name)); BEAST_EXPECT(source == expected); } catch (...) diff --git a/src/test/beast/beast_io_latency_probe_test.cpp b/src/test/beast/beast_io_latency_probe_test.cpp index b2163f2630..dfa18e6770 100644 --- a/src/test/beast/beast_io_latency_probe_test.cpp +++ b/src/test/beast/beast_io_latency_probe_test.cpp @@ -60,7 +60,7 @@ class io_latency_probe_test : public beast::unit_test::suite, public beast::test wait_err = ec; auto const end{MeasureClock::now()}; elapsed_times_.emplace_back(end - start); - std::lock_guard lk{mtx}; + std::lock_guard const lk{mtx}; done = true; cv.notify_one(); }); @@ -157,7 +157,8 @@ class io_latency_probe_test : public beast::unit_test::suite, public beast::test auto interval = 99ms; auto probe_duration = 1s; - size_t expected_probe_count_max = (probe_duration / interval); + size_t const expected_probe_count_max = (probe_duration / interval); + // NOLINTNEXTLINE(misc-const-correctness) size_t expected_probe_count_min = expected_probe_count_max; #ifdef XRPL_RUNNING_IN_CI // adjust min expected based on measurements diff --git a/src/test/consensus/ByzantineFailureSim_test.cpp b/src/test/consensus/ByzantineFailureSim_test.cpp index 245c52d9e3..f86ae556bf 100644 --- a/src/test/consensus/ByzantineFailureSim_test.cpp +++ b/src/test/consensus/ByzantineFailureSim_test.cpp @@ -39,7 +39,7 @@ class ByzantineFailureSim_test : public beast::unit_test::suite f.trustAndConnect(f + d + e + g, delay); g.trustAndConnect(g + a + f, delay); - PeerGroup network = a + b + c + d + e + f + g; + PeerGroup const network = a + b + c + d + e + f + g; StreamCollector sc{std::cout}; diff --git a/src/test/consensus/Consensus_test.cpp b/src/test/consensus/Consensus_test.cpp index 3550717a4d..8b562454e3 100644 --- a/src/test/consensus/Consensus_test.cpp +++ b/src/test/consensus/Consensus_test.cpp @@ -144,7 +144,7 @@ public: testcase("standalone"); Sim s; - PeerGroup peers = s.createGroup(1); + PeerGroup const peers = s.createGroup(1); Peer* peer = peers[0]; peer->targetLedgers = 1; peer->start(); @@ -235,7 +235,7 @@ public: // All peers are in sync even with a slower peer 0 if (BEAST_EXPECT(sim.synchronized())) { - for (Peer* peer : network) + for (Peer const* peer : network) { auto const& lcl = peer->lastClosedLedger; BEAST_EXPECT(lcl.id() == peer->prevLedgerID()); @@ -292,7 +292,7 @@ public: // Verify all peers have same LCL but are missing // transaction 0,1 which was not received by all peers // before the ledger closed - for (Peer* peer : network) + for (Peer const* peer : network) { // Closed ledger has all but transaction 0,1 auto const& lcl = peer->lastClosedLedger; @@ -317,7 +317,7 @@ public: BEAST_EXPECT(slowPeer->prevProposers == fast.size()); } - for (Peer* peer : fast) + for (Peer const* peer : fast) { // Due to the network link delay settings // Peer 0 initially proposes {0} @@ -388,8 +388,8 @@ public: Sim sim; PeerGroup groupA = sim.createGroup(2); - PeerGroup groupB = sim.createGroup(2); - PeerGroup groupC = sim.createGroup(2); + PeerGroup const groupB = sim.createGroup(2); + PeerGroup const groupC = sim.createGroup(2); PeerGroup network = groupA + groupB + groupC; network.trust(network); @@ -397,7 +397,7 @@ public: // Run consensus without skew until we have a short close time // resolution - Peer* firstPeer = *groupA.begin(); + Peer const* firstPeer = *groupA.begin(); while (firstPeer->lastClosedLedger.closeTimeResolution() >= parms.proposeFRESHNESS) sim.run(1); @@ -412,7 +412,7 @@ public: // All nodes agreed to disagree on the close time if (BEAST_EXPECT(sim.synchronized())) { - for (Peer* peer : network) + for (Peer const* peer : network) BEAST_EXPECT(!peer->lastClosedLedger.closeAgree()); } } @@ -457,13 +457,13 @@ public: Sim sim; PeerGroup minority = sim.createGroup(2); - PeerGroup majorityA = sim.createGroup(3); - PeerGroup majorityB = sim.createGroup(5); + PeerGroup const majorityA = sim.createGroup(3); + PeerGroup const majorityB = sim.createGroup(5); PeerGroup majority = majorityA + majorityB; - PeerGroup network = minority + majority; + PeerGroup const network = minority + majority; - SimDuration delay = round(0.2 * parms.ledgerGRANULARITY); + SimDuration const delay = round(0.2 * parms.ledgerGRANULARITY); minority.trustAndConnect(minority + majorityA, delay); majority.trustAndConnect(majority, delay); @@ -556,10 +556,10 @@ public: Sim sim; PeerGroup loner = sim.createGroup(1); - PeerGroup friends = sim.createGroup(3); + PeerGroup const friends = sim.createGroup(3); loner.trust(loner + friends); - PeerGroup others = sim.createGroup(6); + PeerGroup const others = sim.createGroup(6); PeerGroup clique = friends + others; clique.trust(clique); @@ -581,7 +581,7 @@ public: sim.run(2); // Check all peers recovered - for (Peer* p : network) + for (Peer const* p : network) BEAST_EXPECT(p->prevLedgerID() == network[0]->prevLedgerID()); } } @@ -596,7 +596,7 @@ public: // This is a specialized test engineered to yield ledgers with different // close times even though the peers believe they had close time // consensus on the ledger. - ConsensusParms parms; + ConsensusParms const parms; Sim sim; @@ -634,7 +634,7 @@ public: NetClock::duration when = network[0]->now().time_since_epoch(); // Check we are before the 30s to 20s transition - NetClock::duration resolution = network[0]->lastClosedLedger.closeTimeResolution(); + NetClock::duration const resolution = network[0]->lastClosedLedger.closeTimeResolution(); BEAST_EXPECT(resolution == NetClock::duration{30s}); while (((when % NetClock::duration{30s}) != NetClock::duration{15s}) || @@ -650,7 +650,7 @@ public: { // close time should be ahead of clock time since we engineered // the close time to round up - for (Peer* peer : network) + for (Peer const* peer : network) { BEAST_EXPECT(peer->lastClosedLedger.closeTime() > peer->now()); BEAST_EXPECT(peer->lastClosedLedger.closeAgree()); @@ -692,26 +692,26 @@ public: using namespace std::chrono; testcase("fork"); - std::uint32_t numPeers = 10; + std::uint32_t const numPeers = 10; // Vary overlap between two UNLs for (std::uint32_t overlap = 0; overlap <= numPeers; ++overlap) { ConsensusParms const parms{}; Sim sim; - std::uint32_t numA = (numPeers - overlap) / 2; - std::uint32_t numB = numPeers - numA - overlap; + std::uint32_t const numA = (numPeers - overlap) / 2; + std::uint32_t const numB = numPeers - numA - overlap; - PeerGroup aOnly = sim.createGroup(numA); - PeerGroup bOnly = sim.createGroup(numB); - PeerGroup commonOnly = sim.createGroup(overlap); + PeerGroup const aOnly = sim.createGroup(numA); + PeerGroup const bOnly = sim.createGroup(numB); + PeerGroup const commonOnly = sim.createGroup(overlap); PeerGroup a = aOnly + commonOnly; PeerGroup b = bOnly + commonOnly; - PeerGroup network = a + b; + PeerGroup const network = a + b; - SimDuration delay = round(0.2 * parms.ledgerGRANULARITY); + SimDuration const delay = round(0.2 * parms.ledgerGRANULARITY); a.trustAndConnect(a, delay); b.trustAndConnect(b, delay); @@ -721,7 +721,7 @@ public: { // Nodes have only seen transactions from their neighbors peer->openTxs.insert(Tx{static_cast(peer->id)}); - for (Peer* to : sim.trustGraph.trustedPeers(peer)) + for (Peer const* to : sim.trustGraph.trustedPeers(peer)) peer->openTxs.insert(Tx{static_cast(to->id)}); } sim.run(1); @@ -759,7 +759,7 @@ public: validators.trust(validators); center.trust(validators); - SimDuration delay = round(0.2 * parms.ledgerGRANULARITY); + SimDuration const delay = round(0.2 * parms.ledgerGRANULARITY); validators.connect(center, delay); center[0]->runAsValidator = false; @@ -866,7 +866,7 @@ public: Sim sim; // Goes A->B->D - PeerGroup groupABD = sim.createGroup(2); + PeerGroup const groupABD = sim.createGroup(2); // Single node that initially fully validates C before the split PeerGroup groupCfast = sim.createGroup(1); // Generates C, but fails to fully validate before the split @@ -875,8 +875,8 @@ public: PeerGroup groupNotFastC = groupABD + groupCsplit; PeerGroup network = groupABD + groupCsplit + groupCfast; - SimDuration delay = round(0.2 * parms.ledgerGRANULARITY); - SimDuration fDelay = round(0.1 * parms.ledgerGRANULARITY); + SimDuration const delay = round(0.2 * parms.ledgerGRANULARITY); + SimDuration const fDelay = round(0.1 * parms.ledgerGRANULARITY); network.trust(network); // C must have a shorter delay to see all the validations before the @@ -987,14 +987,14 @@ public: ConsensusParms const parms{}; Sim sim; - SimDuration delay = round(0.2 * parms.ledgerGRANULARITY); + SimDuration const delay = round(0.2 * parms.ledgerGRANULARITY); PeerGroup behind = sim.createGroup(3); - PeerGroup ahead = sim.createGroup(2); + PeerGroup const ahead = sim.createGroup(2); PeerGroup network = ahead + behind; hash_set trustedKeys; - for (Peer* p : network) + for (Peer const* p : network) trustedKeys.insert(p->key); for (Peer* p : network) p->trustedKeys = trustedKeys; @@ -1061,7 +1061,7 @@ public: Tx const txFollowingTrue{97}; Tx const txFollowingFalse{96}; int const numPeers = 100; - ConsensusParms p; + ConsensusParms const p; std::size_t peersUnchanged = 0; auto logs = std::make_unique(beast::severities::kError); diff --git a/src/test/consensus/DistributedValidatorsSim_test.cpp b/src/test/consensus/DistributedValidatorsSim_test.cpp index b430a63880..f510e00628 100644 --- a/src/test/consensus/DistributedValidatorsSim_test.cpp +++ b/src/test/consensus/DistributedValidatorsSim_test.cpp @@ -155,9 +155,9 @@ class DistributedValidators_test : public beast::unit_test::suite sim.run(1); // Run for 10 minutes, submitting 100 tx/second - std::chrono::nanoseconds simDuration = 10min; - std::chrono::nanoseconds quiet = 10s; - Rate rate{100, 1000ms}; + std::chrono::nanoseconds const simDuration = 10min; + std::chrono::nanoseconds const quiet = 10s; + Rate const rate{100, 1000ms}; // Initialize timers HeartbeatTimer heart(sim.scheduler); diff --git a/src/test/consensus/LedgerTiming_test.cpp b/src/test/consensus/LedgerTiming_test.cpp index 4441184af4..8313ffd0d4 100644 --- a/src/test/consensus/LedgerTiming_test.cpp +++ b/src/test/consensus/LedgerTiming_test.cpp @@ -66,7 +66,7 @@ class LedgerTiming_test : public beast::unit_test::suite using namespace std::chrono_literals; // A closeTime equal to the epoch is not modified using tp = NetClock::time_point; - tp def; + tp const def; BEAST_EXPECT(def == roundCloseTime(def, 30s)); // Otherwise, the closeTime is rounded to the nearest diff --git a/src/test/consensus/LedgerTrie_test.cpp b/src/test/consensus/LedgerTrie_test.cpp index 7fd8c71b64..0836b9c342 100644 --- a/src/test/consensus/LedgerTrie_test.cpp +++ b/src/test/consensus/LedgerTrie_test.cpp @@ -278,7 +278,7 @@ class LedgerTrie_test : public beast::unit_test::suite LedgerHistoryHelper h; BEAST_EXPECT(t.empty()); - Ledger genesis = h[""]; + Ledger const genesis = h[""]; t.insert(genesis); BEAST_EXPECT(!t.empty()); t.remove(genesis); @@ -344,7 +344,7 @@ class LedgerTrie_test : public beast::unit_test::suite using Seq = Ledger::Seq; // Empty { - LedgerTrie t; + LedgerTrie const t; BEAST_EXPECT(t.getPreferred(Seq{0}) == std::nullopt); BEAST_EXPECT(t.getPreferred(Seq{2}) == std::nullopt); } @@ -352,7 +352,7 @@ class LedgerTrie_test : public beast::unit_test::suite { LedgerTrie t; LedgerHistoryHelper h; - Ledger genesis = h[""]; + Ledger const genesis = h[""]; t.insert(genesis); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) @@ -670,11 +670,11 @@ class LedgerTrie_test : public beast::unit_test::suite { // pick a random ledger history std::string curr; - char depth = depthDist(gen); + char const depth = depthDist(gen); char offset = 0; for (char d = 0; d < depth; ++d) { - char a = offset + widthDist(gen); + char const a = offset + widthDist(gen); curr += a; offset = (a + 1) * width; } diff --git a/src/test/consensus/NegativeUNL_test.cpp b/src/test/consensus/NegativeUNL_test.cpp index cf8c8e87ef..0f97704755 100644 --- a/src/test/consensus/NegativeUNL_test.cpp +++ b/src/test/consensus/NegativeUNL_test.cpp @@ -261,7 +261,7 @@ class NegativeUNL_test : public beast::unit_test::suite { BEAST_EXPECT(l->validatorToDisable() == publicKeys[0]); //++ first ToDisable Tx in ledger's TxSet - uint256 txID = txDisable_0.getTransactionID(); + uint256 const txID = txDisable_0.getTransactionID(); BEAST_EXPECT(l->txExists(txID)); } } @@ -628,7 +628,7 @@ struct NetworkHistory walkHistoryAndAddValidations(NeedValidation&& needVal) { std::uint32_t curr = 0; - std::size_t need = 256 + 1; + std::size_t const need = 256 + 1; // only last 256 + 1 ledgers need validations if (history.size() > need) curr = history.size() - need; @@ -702,14 +702,14 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite testcase("Create UNLModify Tx"); jtx::Env env(*this); - NodeID myId(0xA0); + NodeID const myId(0xA0); NegativeUNLVote vote(myId, env.journal); // one add, one remove auto txSet = std::make_shared(SHAMapType::TRANSACTION, env.app().getNodeFamily()); - PublicKey toDisableKey(derivePublicKey(KeyType::ed25519, randomSecretKey())); - PublicKey toReEnableKey(derivePublicKey(KeyType::ed25519, randomSecretKey())); - LedgerIndex seq(1234); + PublicKey const toDisableKey(derivePublicKey(KeyType::ed25519, randomSecretKey())); + PublicKey const toReEnableKey(derivePublicKey(KeyType::ed25519, randomSecretKey())); + LedgerIndex const seq(1234); BEAST_EXPECT(countTx(txSet) == 0); vote.addTx(seq, toDisableKey, NegativeUNLVote::ToDisable, txSet); BEAST_EXPECT(countTx(txSet) == 1); @@ -723,16 +723,16 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite testPickOneCandidate() { testcase("Pick One Candidate"); - jtx::Env env(*this); + jtx::Env const env(*this); - NodeID myId(0xA0); - NegativeUNLVote vote(myId, env.journal); + NodeID const myId(0xA0); + NegativeUNLVote const vote(myId, env.journal); - uint256 pad_0(0); - uint256 pad_f = ~pad_0; - NodeID n_1(1); - NodeID n_2(2); - NodeID n_3(3); + uint256 const pad_0(0); + uint256 const pad_f = ~pad_0; + NodeID const n_1(1); + NodeID const n_2(2); + NodeID const n_3(3); std::vector candidates({n_1}); BEAST_EXPECT(vote.choose(pad_0, candidates) == n_1); BEAST_EXPECT(vote.choose(pad_f, candidates) == n_1); @@ -803,7 +803,7 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite // 5. local node had enough validations but on a wrong chain NetworkHistory history = {*this, {10, 0, false, false, 256 + 2}}; // We need two chains for these tests - bool wrongChainSuccess = history.goodHistory; + bool const wrongChainSuccess = history.goodHistory; BEAST_EXPECT(wrongChainSuccess); NetworkHistory::LedgerHistory wrongChain = std::move(history.history); // Create a new chain and use it as the one that majority of nodes @@ -814,7 +814,7 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite if (history.goodHistory && wrongChainSuccess) { NodeID myId = history.UNLNodeIDs[3]; - NodeID badNode = history.UNLNodeIDs[4]; + NodeID const badNode = history.UNLNodeIDs[4]; history.walkHistoryAndAddValidations( [&](std::shared_ptr const& l, std::size_t idx) -> bool { // everyone but me @@ -825,9 +825,9 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite // a node double validates for (auto& l : wrongChain) { - RCLValidation v1(history.createSTVal(l, myId)); + RCLValidation const v1(history.createSTVal(l, myId)); history.validations.add(myId, v1); - RCLValidation v2(history.createSTVal(l, badNode)); + RCLValidation const v2(history.createSTVal(l, badNode)); history.validations.add(badNode, v2); } @@ -909,8 +909,8 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite { auto [disableCandidates, reEnableCandidates] = vote.findAllCandidates(unl, negUnl, scoreTable); - bool rightDisable = disableCandidates.size() == numDisable; - bool rightReEnable = reEnableCandidates.size() == numReEnable; + bool const rightDisable = disableCandidates.size() == numDisable; + bool const rightReEnable = reEnableCandidates.size() == numReEnable; return rightDisable && rightReEnable; }; @@ -1009,9 +1009,9 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite { // 2 new validators - NodeID new_1(0xbead); - NodeID new_2(0xbeef); - hash_set nowTrusted = {new_1, new_2}; + NodeID const new_1(0xbead); + NodeID const new_2(0xbeef); + hash_set const nowTrusted = {new_1, new_2}; hash_set UNL_temp = history.UNLNodeIDSet; UNL_temp.insert(new_1); UNL_temp.insert(new_2); @@ -1065,13 +1065,13 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite * negativeUNLMinLocalValsToVote */ - jtx::Env env(*this); + jtx::Env const env(*this); - NodeID myId(0xA0); + NodeID const myId(0xA0); NegativeUNLVote vote(myId, env.journal); - std::array unlSizes = {34, 35, 80}; - std::array nUnlPercent = {0, 50, 100}; + std::array const unlSizes = {34, 35, 80}; + std::array const nUnlPercent = {0, 50, 100}; std::array scores = { 0, NegativeUNLVote::negativeUNLLowWaterMark - 1, @@ -1091,7 +1091,7 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite hash_set& negUnl, hash_map& scoreTable) { std::vector nodeIDs; - std::vector keys = createPublicKeys(unl_size); + std::vector const keys = createPublicKeys(unl_size); for (auto const& k : keys) { nodeIDs.emplace_back(calcNodeID(k)); @@ -1153,7 +1153,7 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite hash_set& negUnl, hash_map& scoreTable) { std::vector nodeIDs; - std::vector keys = createPublicKeys(unl_size); + std::vector const keys = createPublicKeys(unl_size); for (auto const& k : keys) { nodeIDs.emplace_back(calcNodeID(k)); @@ -1221,9 +1221,9 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite testNewValidators() { testcase("New Validators"); - jtx::Env env(*this); + jtx::Env const env(*this); - NodeID myId(0xA0); + NodeID const myId(0xA0); NegativeUNLVote vote(myId, env.journal); // test cases: @@ -1232,9 +1232,9 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite // add a new one and some already added // purge and see some are expired - NodeID n1(0xA1); - NodeID n2(0xA2); - NodeID n3(0xA3); + NodeID const n1(0xA1); + NodeID const n2(0xA2); + NodeID const n3(0xA3); vote.newValidators(2, {n1}); BEAST_EXPECT(vote.newValidators_.size() == 1); @@ -1301,7 +1301,7 @@ class NegativeUNLVoteScoreTable_test : public beast::unit_test::suite * -- unl size: 10, 34, 35, 50 * -- score pattern: all 0, all 50%, all 100%, two 0% two 50% rest 100% */ - std::array unlSizes = {10, 34, 35, 50}; + std::array const unlSizes = {10, 34, 35, 50}; std::array, 4> scorePattern = { {{{0, 0, 0}}, {{50, 50, 50}}, {{100, 100, 100}}, {{0, 50, 100}}}}; @@ -1330,9 +1330,9 @@ class NegativeUNLVoteScoreTable_test : public beast::unit_test::suite k = 2; } - bool add_50 = scorePattern[sp][k] == 50 && l->seq() % 2 == 0; - bool add_100 = scorePattern[sp][k] == 100; - bool add_me = history.UNLNodeIDs[idx] == myId; + bool const add_50 = scorePattern[sp][k] == 50 && l->seq() % 2 == 0; + bool const add_100 = scorePattern[sp][k] == 100; + bool const add_me = history.UNLNodeIDs[idx] == myId; return add_50 || add_100 || add_me; }); @@ -1698,8 +1698,8 @@ class NegativeUNLVoteFilterValidations_test : public beast::unit_test::suite }; // create keys and validations - std::uint32_t numNodes = 10; - std::uint32_t negUnlSize = 3; + std::uint32_t const numNodes = 10; + std::uint32_t const negUnlSize = 3; std::vector cfgKeys; hash_set activeValidators; hash_set nUnlKeys; @@ -1719,7 +1719,7 @@ class NegativeUNLVoteFilterValidations_test : public beast::unit_test::suite // setup the ValidatorList auto& validators = env.app().getValidators(); auto& local = *nUnlKeys.begin(); - std::vector cfgPublishers; + std::vector const cfgPublishers; validators.load(local, cfgKeys, cfgPublishers); validators.updateTrusted( activeValidators, @@ -1765,9 +1765,9 @@ negUnlSizeTest( bool hasToDisable, bool hasToReEnable) { - bool sameSize = l->negativeUNL().size() == size; - bool sameToDisable = (l->validatorToDisable() != std::nullopt) == hasToDisable; - bool sameToReEnable = (l->validatorToReEnable() != std::nullopt) == hasToReEnable; + bool const sameSize = l->negativeUNL().size() == size; + bool const sameToDisable = (l->validatorToDisable() != std::nullopt) == hasToDisable; + bool const sameToReEnable = (l->validatorToReEnable() != std::nullopt) == hasToReEnable; return sameSize && sameToDisable && sameToReEnable; } @@ -1809,7 +1809,7 @@ VerifyPubKeyAndSeq( auto s = makeSlice(d); if (!publicKeyType(s)) return false; - PublicKey pk(s); + PublicKey const pk(s); auto it = nUnlLedgerSeq.find(pk); if (it == nUnlLedgerSeq.end()) return false; @@ -1835,13 +1835,13 @@ std::vector createPublicKeys(std::size_t n) { std::vector keys; - std::size_t ss = 33; + std::size_t const ss = 33; std::vector data(ss, 0); data[0] = 0xED; for (int i = 0; i < n; ++i) { data[1]++; - Slice s(data.data(), ss); + Slice const s(data.data(), ss); keys.emplace_back(s); } return keys; diff --git a/src/test/consensus/Validations_test.cpp b/src/test/consensus/Validations_test.cpp index dc6dfe539c..fef6e79036 100644 --- a/src/test/consensus/Validations_test.cpp +++ b/src/test/consensus/Validations_test.cpp @@ -233,12 +233,12 @@ class Validations_test : public beast::unit_test::suite testcase("Add validation"); LedgerHistoryHelper h; - Ledger ledgerA = h["a"]; + Ledger const ledgerA = h["a"]; Ledger ledgerAB = h["ab"]; Ledger ledgerAZ = h["az"]; Ledger ledgerABC = h["abc"]; - Ledger ledgerABCD = h["abcd"]; - Ledger ledgerABCDE = h["abcde"]; + Ledger const ledgerABCD = h["abcd"]; + Ledger const ledgerABCDE = h["abcde"]; { TestHarness harness(h.oracle); @@ -296,7 +296,7 @@ class Validations_test : public beast::unit_test::suite // Process validations out of order with shifted times TestHarness harness(h.oracle); - Node n = harness.makeNode(); + Node const n = harness.makeNode(); // Establish a new current validation BEAST_EXPECT(ValStatus::current == harness.add(n.validate(ledgerA))); @@ -312,7 +312,7 @@ class Validations_test : public beast::unit_test::suite { // Test stale on arrival validations TestHarness harness(h.oracle); - Node n = harness.makeNode(); + Node const n = harness.makeNode(); BEAST_EXPECT( ValStatus::stale == @@ -364,11 +364,11 @@ class Validations_test : public beast::unit_test::suite LedgerHistoryHelper h; Ledger ledgerA = h["a"]; - Ledger ledgerAB = h["ab"]; + Ledger const ledgerAB = h["ab"]; using Trigger = std::function; - std::vector triggers = { + std::vector const triggers = { [&](TestValidations& vals) { vals.currentTrusted(); }, [&](TestValidations& vals) { vals.getCurrentNodeIDs(); }, [&](TestValidations& vals) { vals.getPreferred(genesisLedger); }, @@ -376,7 +376,7 @@ class Validations_test : public beast::unit_test::suite for (Trigger const& trigger : triggers) { TestHarness harness(h.oracle); - Node n = harness.makeNode(); + Node const n = harness.makeNode(); BEAST_EXPECT(ValStatus::current == harness.add(n.validate(ledgerAB))); trigger(harness.vals()); @@ -405,39 +405,41 @@ class Validations_test : public beast::unit_test::suite testcase("Get nodes after"); LedgerHistoryHelper h; - Ledger ledgerA = h["a"]; - Ledger ledgerAB = h["ab"]; - Ledger ledgerABC = h["abc"]; - Ledger ledgerAD = h["ad"]; + Ledger const ledgerA = h["a"]; + Ledger const ledgerAB = h["ab"]; + Ledger const ledgerABC = h["abc"]; + Ledger const ledgerAD = h["ad"]; TestHarness harness(h.oracle); - Node a = harness.makeNode(), b = harness.makeNode(), c = harness.makeNode(), - d = harness.makeNode(); - c.untrust(); + Node const trustedNode1 = harness.makeNode(); + Node const trustedNode2 = harness.makeNode(); + Node const trustedNode3 = harness.makeNode(); + + Node notTrustedNode = harness.makeNode(); + notTrustedNode.untrust(); // first round a,b,c agree, d has is partial - BEAST_EXPECT(ValStatus::current == harness.add(a.validate(ledgerA))); - BEAST_EXPECT(ValStatus::current == harness.add(b.validate(ledgerA))); - BEAST_EXPECT(ValStatus::current == harness.add(c.validate(ledgerA))); - BEAST_EXPECT(ValStatus::current == harness.add(d.partial(ledgerA))); + BEAST_EXPECT(ValStatus::current == harness.add(trustedNode1.validate(ledgerA))); + BEAST_EXPECT(ValStatus::current == harness.add(trustedNode2.validate(ledgerA))); + BEAST_EXPECT(ValStatus::current == harness.add(notTrustedNode.validate(ledgerA))); + BEAST_EXPECT(ValStatus::current == harness.add(trustedNode3.partial(ledgerA))); for (Ledger const& ledger : {ledgerA, ledgerAB, ledgerABC, ledgerAD}) BEAST_EXPECT(harness.vals().getNodesAfter(ledger, ledger.id()) == 0); harness.clock().advance(5s); - BEAST_EXPECT(ValStatus::current == harness.add(a.validate(ledgerAB))); - BEAST_EXPECT(ValStatus::current == harness.add(b.validate(ledgerABC))); - BEAST_EXPECT(ValStatus::current == harness.add(c.validate(ledgerAB))); - BEAST_EXPECT(ValStatus::current == harness.add(d.partial(ledgerABC))); + BEAST_EXPECT(ValStatus::current == harness.add(trustedNode1.validate(ledgerAB))); + BEAST_EXPECT(ValStatus::current == harness.add(trustedNode2.validate(ledgerABC))); + BEAST_EXPECT(ValStatus::current == harness.add(notTrustedNode.validate(ledgerAB))); + BEAST_EXPECT(ValStatus::current == harness.add(trustedNode3.partial(ledgerABC))); BEAST_EXPECT(harness.vals().getNodesAfter(ledgerA, ledgerA.id()) == 3); BEAST_EXPECT(harness.vals().getNodesAfter(ledgerAB, ledgerAB.id()) == 2); BEAST_EXPECT(harness.vals().getNodesAfter(ledgerABC, ledgerABC.id()) == 0); BEAST_EXPECT(harness.vals().getNodesAfter(ledgerAD, ledgerAD.id()) == 0); - // If given a ledger inconsistent with the id, is still able to check - // using slower method + // If given a ledger inconsistent with the id, is still able to check using slower method BEAST_EXPECT(harness.vals().getNodesAfter(ledgerAD, ledgerA.id()) == 1); BEAST_EXPECT(harness.vals().getNodesAfter(ledgerAD, ledgerAB.id()) == 2); } @@ -449,12 +451,13 @@ class Validations_test : public beast::unit_test::suite testcase("Current trusted validations"); LedgerHistoryHelper h; - Ledger ledgerA = h["a"]; - Ledger ledgerB = h["b"]; - Ledger ledgerAC = h["ac"]; + Ledger const ledgerA = h["a"]; + Ledger const ledgerB = h["b"]; + Ledger const ledgerAC = h["ac"]; TestHarness harness(h.oracle); - Node a = harness.makeNode(), b = harness.makeNode(); + Node const a = harness.makeNode(); + Node b = harness.makeNode(); b.untrust(); BEAST_EXPECT(ValStatus::current == harness.add(a.validate(ledgerA))); @@ -487,8 +490,8 @@ class Validations_test : public beast::unit_test::suite testcase("Current public keys"); LedgerHistoryHelper h; - Ledger ledgerA = h["a"]; - Ledger ledgerAC = h["ac"]; + Ledger const ledgerA = h["a"]; + Ledger const ledgerAC = h["ac"]; TestHarness harness(h.oracle); Node a = harness.makeNode(), b = harness.makeNode(); @@ -567,7 +570,7 @@ class Validations_test : public beast::unit_test::suite sorted(harness.vals().getTrustedForLedger(id, seq)) == sorted(expectedValidations)); - std::uint32_t baseFee = 0; + std::uint32_t const baseFee = 0; std::vector expectedFees; expectedFees.reserve(expectedValidations.size()); for (auto const& val : expectedValidations) @@ -580,9 +583,9 @@ class Validations_test : public beast::unit_test::suite }; //---------------------------------------------------------------------- - Ledger ledgerA = h["a"]; - Ledger ledgerB = h["b"]; - Ledger ledgerAC = h["ac"]; + Ledger const ledgerA = h["a"]; + Ledger const ledgerB = h["b"]; + Ledger const ledgerAC = h["ac"]; // Add a dummy ID to cover unknown ledger identifiers trustedValidations[{Ledger::ID{100}, Ledger::Seq{100}}] = {}; @@ -689,14 +692,16 @@ class Validations_test : public beast::unit_test::suite LedgerHistoryHelper h; TestHarness harness(h.oracle); - Node a = harness.makeNode(), b = harness.makeNode(), c = harness.makeNode(); - c.untrust(); + Node const trustedNode1 = harness.makeNode(); + Node const trustedNode2 = harness.makeNode(); + Node notTrustedNode = harness.makeNode(); + notTrustedNode.untrust(); - Ledger ledgerA = h["a"]; - Ledger ledgerAB = h["ab"]; + Ledger const ledgerA = h["a"]; + Ledger const ledgerAB = h["ab"]; hash_map expected; - for (auto const& node : {a, b, c}) + for (auto const& node : {trustedNode1, trustedNode2, notTrustedNode}) { auto const val = node.validate(ledgerA); BEAST_EXPECT(ValStatus::current == harness.add(val)); @@ -706,9 +711,9 @@ class Validations_test : public beast::unit_test::suite // Send in a new validation for a, saving the new one into the expected // map after setting the proper prior ledger ID it replaced harness.clock().advance(1s); - auto newVal = a.validate(ledgerAB); + auto newVal = trustedNode1.validate(ledgerAB); BEAST_EXPECT(ValStatus::current == harness.add(newVal)); - expected.find(a.nodeID())->second = newVal; + expected.find(trustedNode1.nodeID())->second = newVal; } void @@ -719,14 +724,17 @@ class Validations_test : public beast::unit_test::suite LedgerHistoryHelper h; TestHarness harness(h.oracle); - Node a = harness.makeNode(), b = harness.makeNode(), c = harness.makeNode(), - d = harness.makeNode(); - c.untrust(); + Node const trustedNode1 = harness.makeNode(); + Node const trustedNode2 = harness.makeNode(); + Node const trustedNode3 = harness.makeNode(); - Ledger ledgerA = h["a"]; - Ledger ledgerB = h["b"]; - Ledger ledgerAC = h["ac"]; - Ledger ledgerACD = h["acd"]; + Node notTrustedNode = harness.makeNode(); + notTrustedNode.untrust(); + + Ledger const ledgerA = h["a"]; + Ledger const ledgerB = h["b"]; + Ledger const ledgerAC = h["ac"]; + Ledger const ledgerACD = h["acd"]; using Seq = Ledger::Seq; @@ -736,7 +744,7 @@ class Validations_test : public beast::unit_test::suite BEAST_EXPECT(harness.vals().getPreferred(ledgerA) == std::nullopt); // Single ledger - BEAST_EXPECT(ValStatus::current == harness.add(a.validate(ledgerB))); + BEAST_EXPECT(ValStatus::current == harness.add(trustedNode1.validate(ledgerB))); BEAST_EXPECT(harness.vals().getPreferred(ledgerA) == pref(ledgerB)); BEAST_EXPECT(harness.vals().getPreferred(ledgerB) == pref(ledgerB)); @@ -745,21 +753,21 @@ class Validations_test : public beast::unit_test::suite // Untrusted doesn't impact preferred ledger // (ledgerB has tie-break over ledgerA) - BEAST_EXPECT(ValStatus::current == harness.add(b.validate(ledgerA))); - BEAST_EXPECT(ValStatus::current == harness.add(c.validate(ledgerA))); + BEAST_EXPECT(ValStatus::current == harness.add(trustedNode2.validate(ledgerA))); + BEAST_EXPECT(ValStatus::current == harness.add(notTrustedNode.validate(ledgerA))); BEAST_EXPECT(ledgerB.id() > ledgerA.id()); BEAST_EXPECT(harness.vals().getPreferred(ledgerA) == pref(ledgerB)); BEAST_EXPECT(harness.vals().getPreferred(ledgerB) == pref(ledgerB)); // Partial does break ties - BEAST_EXPECT(ValStatus::current == harness.add(d.partial(ledgerA))); + BEAST_EXPECT(ValStatus::current == harness.add(trustedNode3.partial(ledgerA))); BEAST_EXPECT(harness.vals().getPreferred(ledgerA) == pref(ledgerA)); BEAST_EXPECT(harness.vals().getPreferred(ledgerB) == pref(ledgerA)); harness.clock().advance(5s); // Parent of preferred-> stick with ledger - for (auto const& node : {a, b, c, d}) + for (auto const& node : {trustedNode1, trustedNode2, notTrustedNode, trustedNode3}) BEAST_EXPECT(ValStatus::current == harness.add(node.validate(ledgerAC))); // Parent of preferred stays put BEAST_EXPECT(harness.vals().getPreferred(ledgerA) == pref(ledgerA)); @@ -770,7 +778,7 @@ class Validations_test : public beast::unit_test::suite // Any later grandchild or different chain is preferred harness.clock().advance(5s); - for (auto const& node : {a, b, c, d}) + for (auto const& node : {trustedNode1, trustedNode2, notTrustedNode, trustedNode3}) BEAST_EXPECT(ValStatus::current == harness.add(node.validate(ledgerACD))); for (auto const& ledger : {ledgerA, ledgerB, ledgerACD}) BEAST_EXPECT(harness.vals().getPreferred(ledger) == pref(ledgerACD)); @@ -784,11 +792,11 @@ class Validations_test : public beast::unit_test::suite LedgerHistoryHelper h; TestHarness harness(h.oracle); - Node a = harness.makeNode(); + Node const a = harness.makeNode(); - Ledger ledgerA = h["a"]; - Ledger ledgerB = h["b"]; - Ledger ledgerC = h["c"]; + Ledger const ledgerA = h["a"]; + Ledger const ledgerB = h["b"]; + Ledger const ledgerC = h["c"]; using ID = Ledger::ID; using Seq = Ledger::Seq; @@ -830,14 +838,14 @@ class Validations_test : public beast::unit_test::suite LedgerHistoryHelper h; TestHarness harness(h.oracle); - Node a = harness.makeNode(); - Node b = harness.makeNode(); + Node const a = harness.makeNode(); + Node const b = harness.makeNode(); using ID = Ledger::ID; using Seq = Ledger::Seq; // Validate the ledger before it is actually available - Validation val = a.validate(ID{2}, Seq{2}, 0s, 0s, true); + Validation const val = a.validate(ID{2}, Seq{2}, 0s, 0s, true); BEAST_EXPECT(ValStatus::current == harness.add(val)); // Validation is available @@ -854,13 +862,13 @@ class Validations_test : public beast::unit_test::suite BEAST_EXPECT(harness.vals().getPreferred(genesisLedger) == std::make_pair(Seq{2}, ID{3})); // Create the ledger - Ledger ledgerAB = h["ab"]; + Ledger const ledgerAB = h["ab"]; // Now it should be available BEAST_EXPECT(harness.vals().getNodesAfter(genesisLedger, ID{0}) == 1); // Create a validation that is not available harness.clock().advance(5s); - Validation val2 = a.validate(ID{4}, Seq{4}, 0s, 0s, true); + Validation const val2 = a.validate(ID{4}, Seq{4}, 0s, 0s, true); BEAST_EXPECT(ValStatus::current == harness.add(val2)); BEAST_EXPECT(harness.vals().numTrustedForLedger(ID{4}) == 1); BEAST_EXPECT( @@ -868,7 +876,7 @@ class Validations_test : public beast::unit_test::suite std::make_pair(ledgerAB.seq(), ledgerAB.id())); // Another node requesting that ledger still doesn't change things - Validation val3 = b.validate(ID{4}, Seq{4}, 0s, 0s, true); + Validation const val3 = b.validate(ID{4}, Seq{4}, 0s, 0s, true); BEAST_EXPECT(ValStatus::current == harness.add(val3)); BEAST_EXPECT(harness.vals().numTrustedForLedger(ID{4}) == 2); BEAST_EXPECT( @@ -877,7 +885,7 @@ class Validations_test : public beast::unit_test::suite // Switch to validation that is available harness.clock().advance(5s); - Ledger ledgerABCDE = h["abcde"]; + Ledger const ledgerABCDE = h["abcde"]; BEAST_EXPECT(ValStatus::current == harness.add(a.partial(ledgerABCDE))); BEAST_EXPECT(ValStatus::current == harness.add(b.partial(ledgerABCDE))); BEAST_EXPECT( @@ -891,9 +899,9 @@ class Validations_test : public beast::unit_test::suite testcase("NumTrustedForLedger"); LedgerHistoryHelper h; TestHarness harness(h.oracle); - Node a = harness.makeNode(); - Node b = harness.makeNode(); - Ledger ledgerA = h["a"]; + Node const a = harness.makeNode(); + Node const b = harness.makeNode(); + Ledger const ledgerA = h["a"]; BEAST_EXPECT(ValStatus::current == harness.add(a.partial(ledgerA))); BEAST_EXPECT(harness.vals().numTrustedForLedger(ledgerA.id()) == 0); @@ -912,7 +920,7 @@ class Validations_test : public beast::unit_test::suite beast::manual_clock clock; SeqEnforcer enforcer; - ValidationParms p; + ValidationParms const p; BEAST_EXPECT(enforcer(clock.now(), Seq{1}, p)); BEAST_EXPECT(enforcer(clock.now(), Seq{10}, p)); @@ -934,9 +942,9 @@ class Validations_test : public beast::unit_test::suite TestValidations& vals, hash_set const& listed, std::vector const& trustedVals) { - Ledger::ID testID = + Ledger::ID const testID = trustedVals.empty() ? this->genesisLedger.id() : trustedVals[0].ledgerID(); - Ledger::Seq testSeq = + Ledger::Seq const testSeq = trustedVals.empty() ? this->genesisLedger.seq() : trustedVals[0].seq(); BEAST_EXPECT(vals.currentTrusted() == trustedVals); BEAST_EXPECT(vals.getCurrentNodeIDs() == listed); @@ -958,12 +966,12 @@ class Validations_test : public beast::unit_test::suite // Trusted to untrusted LedgerHistoryHelper h; TestHarness harness(h.oracle); - Node a = harness.makeNode(); - Ledger ledgerAB = h["ab"]; - Validation v = a.validate(ledgerAB); + Node const a = harness.makeNode(); + Ledger const ledgerAB = h["ab"]; + Validation const v = a.validate(ledgerAB); BEAST_EXPECT(ValStatus::current == harness.add(v)); - hash_set listed({a.nodeID()}); + hash_set const listed({a.nodeID()}); std::vector trustedVals({v}); checker(harness.vals(), listed, trustedVals); @@ -978,11 +986,11 @@ class Validations_test : public beast::unit_test::suite TestHarness harness(h.oracle); Node a = harness.makeNode(); a.untrust(); - Ledger ledgerAB = h["ab"]; - Validation v = a.validate(ledgerAB); + Ledger const ledgerAB = h["ab"]; + Validation const v = a.validate(ledgerAB); BEAST_EXPECT(ValStatus::current == harness.add(v)); - hash_set listed({a.nodeID()}); + hash_set const listed({a.nodeID()}); std::vector trustedVals; checker(harness.vals(), listed, trustedVals); @@ -995,11 +1003,11 @@ class Validations_test : public beast::unit_test::suite // Trusted but not acquired -> untrusted LedgerHistoryHelper h; TestHarness harness(h.oracle); - Node a = harness.makeNode(); - Validation v = a.validate(Ledger::ID{2}, Ledger::Seq{2}, 0s, 0s, true); + Node const a = harness.makeNode(); + Validation const v = a.validate(Ledger::ID{2}, Ledger::Seq{2}, 0s, 0s, true); BEAST_EXPECT(ValStatus::current == harness.add(v)); - hash_set listed({a.nodeID()}); + hash_set const listed({a.nodeID()}); std::vector trustedVals({v}); auto& vals = harness.vals(); BEAST_EXPECT(vals.currentTrusted() == trustedVals); diff --git a/src/test/core/Config_test.cpp b/src/test/core/Config_test.cpp index edcb67b767..a7f44836d5 100644 --- a/src/test/core/Config_test.cpp +++ b/src/test/core/Config_test.cpp @@ -268,7 +268,7 @@ public: Config c; - std::string toLoad(R"xrpldConfig( + std::string const toLoad(R"xrpldConfig( [server] port_rpc port_peer @@ -297,15 +297,15 @@ port_wss_admin auto const cwd = current_path(); // Test both config file names. - char const* configFiles[] = {Config::configFileName, Config::configLegacyName}; + std::string_view const configFiles[] = {Config::configFileName, Config::configLegacyName}; // Config file in current directory. for (auto const& configFile : configFiles) { // Use a temporary directory for testing. - beast::temp_dir td; + beast::temp_dir const td; current_path(td.path()); - path const f = td.file(configFile); + path const f = td.file(std::string{configFile}); std::ofstream o(f.string()); o << detail::configContents("", ""); o.close(); @@ -325,13 +325,13 @@ port_wss_admin { // Point the current working directory to a temporary directory, so // we don't pick up an actual config file from the repository root. - beast::temp_dir td; + beast::temp_dir const td; current_path(td.path()); // The XDG config directory is set: the config file must be in a // subdirectory named after the system. { - beast::temp_dir tc; + beast::temp_dir const tc; // Set the HOME and XDG_CONFIG_HOME environment variables. The // HOME variable is not used when XDG_CONFIG_HOME is set, but @@ -344,7 +344,7 @@ port_wss_admin // Create the config file in '${XDG_CONFIG_HOME}/[systemName]'. path p = tc.file(systemName()); create_directory(p); - p = tc.file(systemName() + "/" + configFile); + p = tc.file(systemName() + "/" + std::string{configFile}); std::ofstream o(p.string()); o << detail::configContents("", ""); o.close(); @@ -365,7 +365,7 @@ port_wss_admin // The XDG config directory is not set: the config file must be in a // subdirectory named .config followed by the system name. { - beast::temp_dir tc; + beast::temp_dir const tc; // Set only the HOME environment variable. char const* h = getenv("HOME"); @@ -380,7 +380,7 @@ port_wss_admin s += "/" + systemName(); p = tc.file(s); create_directory(p); - p = tc.file(s + "/" + configFile); + p = tc.file(s + "/" + std::string{configFile}); std::ofstream o(p.string()); o << detail::configContents("", ""); o.close(); @@ -626,7 +626,7 @@ main { // load validators from config into single section Config c; - std::string toLoad(R"xrpldConfig( + std::string const toLoad(R"xrpldConfig( [validators] n949f75evCHwgyP4fPVgaHqNHxUVN15PsJEZ3B3HnXPcPjcZAoy7 n9MD5h24qrQqiyBC8aeqqCWvpiBiYQ3jxSr91uiDvmrkyHRdYLUj @@ -644,7 +644,7 @@ nHBu9PTL9dn2GuZtdW4U2WzBwffyX9qsQCd9CNU4Z5YG3PQfViM8 { // load validator list sites and keys from config Config c; - std::string toLoad(R"xrpldConfig( + std::string const toLoad(R"xrpldConfig( [validator_list_sites] xrpl-validators.com trust-these-validators.gov @@ -674,7 +674,7 @@ trust-these-validators.gov { // load validator list sites and keys from config Config c; - std::string toLoad(R"xrpldConfig( + std::string const toLoad(R"xrpldConfig( [validator_list_sites] xrpl-validators.com trust-these-validators.gov @@ -705,7 +705,7 @@ trust-these-validators.gov // load should throw if [validator_list_threshold] is greater than // the number of [validator_list_keys] Config c; - std::string toLoad(R"xrpldConfig( + std::string const toLoad(R"xrpldConfig( [validator_list_sites] xrpl-validators.com trust-these-validators.gov @@ -734,7 +734,7 @@ trust-these-validators.gov { // load should throw if [validator_list_threshold] is malformed Config c; - std::string toLoad(R"xrpldConfig( + std::string const toLoad(R"xrpldConfig( [validator_list_sites] xrpl-validators.com trust-these-validators.gov @@ -763,7 +763,7 @@ value = 2 { // load should throw if [validator_list_threshold] is negative Config c; - std::string toLoad(R"xrpldConfig( + std::string const toLoad(R"xrpldConfig( [validator_list_sites] xrpl-validators.com trust-these-validators.gov @@ -790,7 +790,7 @@ trust-these-validators.gov // load should throw if [validator_list_sites] is configured but // [validator_list_keys] is not Config c; - std::string toLoad(R"xrpldConfig( + std::string const toLoad(R"xrpldConfig( [validator_list_sites] xrpl-validators.com trust-these-validators.gov @@ -958,7 +958,7 @@ trust-these-validators.gov // load should throw if [validators], [validator_keys] and // [validator_list_keys] are missing from xrpld.cfg and // validators file - Config c; + Config const c; boost::format cc("[validators_file]\n%1%\n"); std::string error; detail::ValidatorsTxtGuard const vtg(*this, "test_cfg", "validators.cfg"); @@ -968,7 +968,7 @@ trust-these-validators.gov "[validators], [validator_keys] or [validator_list_keys] " "section: " + vtg.validatorsFile(); - std::ofstream o(vtg.validatorsFile()); + std::ofstream const o(vtg.validatorsFile()); try { Config c2; @@ -1141,7 +1141,7 @@ trust-these-validators.gov Config cfg; /* NOTE: this string includes some explicit * space chars in order to verify proper trimming */ - std::string toLoad( + std::string const toLoad( R"( [port_rpc])" "\x20" @@ -1182,7 +1182,7 @@ r.ripple.com 51235 Config cfg; /* NOTE: this string includes some explicit * space chars in order to verify proper trimming */ - std::string toLoad( + std::string const toLoad( R"( [port_rpc])" "\x20" @@ -1261,7 +1261,7 @@ r.ripple.com:51235 bool had_comment; }; - std::array tests = { + std::array const tests = { {{"password = aaaa\\#bbbb", "password", "aaaa#bbbb", false}, {"password = aaaa#bbbb", "password", "aaaa", true}, {"password = aaaa #bbbb", "password", "aaaa", true}, @@ -1419,7 +1419,7 @@ r.ripple.com:51235 bool shouldPass; }; - std::vector units = { + std::vector const units = { {"seconds", 1, 15 * 60, false}, {"minutes", 60, 14, false}, {"minutes", 60, 15, true}, diff --git a/src/test/core/Coroutine_test.cpp b/src/test/core/Coroutine_test.cpp index 73dc3c2f8f..4cfb86f931 100644 --- a/src/test/core/Coroutine_test.cpp +++ b/src/test/core/Coroutine_test.cpp @@ -34,7 +34,7 @@ public: void signal() { - std::lock_guard lk(mutex_); + std::lock_guard const lk(mutex_); signaled_ = true; cv_.notify_all(); } diff --git a/src/test/core/SociDB_test.cpp b/src/test/core/SociDB_test.cpp index 66b368176d..c58c34756a 100644 --- a/src/test/core/SociDB_test.cpp +++ b/src/test/core/SociDB_test.cpp @@ -7,6 +7,8 @@ #include #include +#include + namespace xrpl { class SociDB_test final : public TestSuite { @@ -87,7 +89,7 @@ public: for (auto const& i : d) { - DBConfig sc(c, i.first); + DBConfig const sc(c, i.first); BEAST_EXPECT(boost::ends_with(sc.connectionString(), i.first + i.second)); } } @@ -97,7 +99,7 @@ public: testcase("open"); BasicConfig c; setupSQLiteConfig(c, getDatabasePath()); - DBConfig sc(c, "SociTestDB"); + DBConfig const sc(c, "SociTestDB"); std::vector const stringData({"String1", "String2", "String3"}); std::vector const intData({1, 2, 3}); auto checkValues = [this, &stringData, &intData](soci::session& s) { @@ -142,7 +144,7 @@ public: { namespace bfs = boost::filesystem; // Remove the database - bfs::path dbPath(sc.connectionString()); + bfs::path const dbPath(sc.connectionString()); if (bfs::is_regular_file(dbPath)) bfs::remove(dbPath); } @@ -154,7 +156,7 @@ public: testcase("select"); BasicConfig c; setupSQLiteConfig(c, getDatabasePath()); - DBConfig sc(c, "SociTestDB"); + DBConfig const sc(c, "SociTestDB"); std::vector const ubid( {(std::uint64_t)std::numeric_limits::max(), 20, 30}); std::vector const bid({-10, -20, -30}); @@ -272,7 +274,7 @@ public: { namespace bfs = boost::filesystem; // Remove the database - bfs::path dbPath(sc.connectionString()); + bfs::path const dbPath(sc.connectionString()); if (bfs::is_regular_file(dbPath)) bfs::remove(dbPath); } @@ -283,11 +285,12 @@ public: testcase("deleteWithSubselect"); BasicConfig c; setupSQLiteConfig(c, getDatabasePath()); - DBConfig sc(c, "SociTestDB"); + DBConfig const sc(c, "SociTestDB"); { soci::session s; sc.open(s); - char const* dbInit[] = { + + std::string_view const dbInit[] = { "BEGIN TRANSACTION;", "CREATE TABLE Ledgers ( \ LedgerHash CHARACTER(64) PRIMARY KEY, \ @@ -323,7 +326,7 @@ public: } namespace bfs = boost::filesystem; // Remove the database - bfs::path dbPath(sc.connectionString()); + bfs::path const dbPath(sc.connectionString()); if (bfs::is_regular_file(dbPath)) bfs::remove(dbPath); } diff --git a/src/test/core/Workers_test.cpp b/src/test/core/Workers_test.cpp index 65245b8c94..6631cff1c4 100644 --- a/src/test/core/Workers_test.cpp +++ b/src/test/core/Workers_test.cpp @@ -88,7 +88,7 @@ public: void processTask(int instance) override { - std::lock_guard lk{mut}; + std::lock_guard const lk{mut}; if (--count == 0) cv.notify_all(); } @@ -106,7 +106,7 @@ public: std::to_string(tc3)); TestCallback cb; - std::unique_ptr perfLog = std::make_unique(); + std::unique_ptr const perfLog = std::make_unique(); Workers w(cb, perfLog.get(), "Test", tc1); BEAST_EXPECT(w.getNumberOfThreads() == tc1); diff --git a/src/test/csf/BasicNetwork.h b/src/test/csf/BasicNetwork.h index 697b20c2c7..85c77ac47d 100644 --- a/src/test/csf/BasicNetwork.h +++ b/src/test/csf/BasicNetwork.h @@ -199,7 +199,7 @@ BasicNetwork::disconnect(Peer const& peer1, Peer const& peer2) { if (!links_.disconnect(peer1, peer2)) return false; - bool r = links_.disconnect(peer2, peer1); + bool const r = links_.disconnect(peer2, peer1); (void)r; assert(r); return true; diff --git a/src/test/csf/Digraph_test.cpp b/src/test/csf/Digraph_test.cpp index a183234903..1c34bbcfec 100644 --- a/src/test/csf/Digraph_test.cpp +++ b/src/test/csf/Digraph_test.cpp @@ -57,7 +57,7 @@ public: // only 'a' has out edges BEAST_EXPECT(graph.outVertices().size() == 1); - std::vector expected = {'b', 'c'}; + std::vector const expected = {'b', 'c'}; BEAST_EXPECT((graph.outVertices('a') == expected)); BEAST_EXPECT(graph.outVertices('b').size() == 0); @@ -66,7 +66,7 @@ public: std::stringstream ss; graph.saveDot(ss, [](char v) { return v; }); - std::string expectedDot = + std::string const expectedDot = "digraph {\n" "a -> b;\n" "a -> c;\n" diff --git a/src/test/csf/Histogram.h b/src/test/csf/Histogram.h index 9e7b471a2b..cbc2d42d6c 100644 --- a/src/test/csf/Histogram.h +++ b/src/test/csf/Histogram.h @@ -92,7 +92,7 @@ public: percentile(float p) const { assert(p >= 0 && p <= 1); - std::size_t pos = std::round(p * samples); + std::size_t const pos = std::round(p * samples); if (counts_.empty()) return T{}; diff --git a/src/test/csf/Peer.h b/src/test/csf/Peer.h index c36d600e6c..94b2c74a0b 100644 --- a/src/test/csf/Peer.h +++ b/src/test/csf/Peer.h @@ -550,9 +550,9 @@ struct Peer if (runAsValidator && isCompatible && !consensusFail && validations.canValidateSeq(newLedger.seq())) { - bool isFull = proposing; + bool const isFull = proposing; - Validation v{newLedger.id(), newLedger.seq(), now(), now(), key, id, isFull}; + Validation const v{newLedger.id(), newLedger.seq(), now(), now(), key, id, isFull}; // share the new validation; it is trusted by the receiver share(v); // we trust ourselves @@ -880,7 +880,7 @@ struct Peer issue(StartRound{bestLCL, lastClosedLedger}); // Not yet modeling dynamic UNL. - hash_set nowUntrusted; + hash_set const nowUntrusted; consensus.startRound(now(), bestLCL, lastClosedLedger, nowUntrusted, runAsValidator, {}); } diff --git a/src/test/csf/PeerGroup.h b/src/test/csf/PeerGroup.h index e900ab9934..5df6de84a6 100644 --- a/src/test/csf/PeerGroup.h +++ b/src/test/csf/PeerGroup.h @@ -313,8 +313,8 @@ randomRankedTrust( Generator& g) { std::vector const groups = randomRankedGroups(peers, ranks, numGroups, sizeDist, g); + std::uniform_int_distribution u(0, groups.size() - 1); // NOLINT(misc-const-correctness) - std::uniform_int_distribution u(0, groups.size() - 1); for (auto& peer : peers) { for (auto& target : groups[u(g)]) @@ -337,8 +337,8 @@ randomRankedConnect( SimDuration delay) { std::vector const groups = randomRankedGroups(peers, ranks, numGroups, sizeDist, g); + std::uniform_int_distribution u(0, groups.size() - 1); // NOLINT(misc-const-correctness) - std::uniform_int_distribution u(0, groups.size() - 1); for (auto& peer : peers) { for (auto& target : groups[u(g)]) diff --git a/src/test/csf/TrustGraph.h b/src/test/csf/TrustGraph.h index bae0be4af7..3f1fcae0c1 100644 --- a/src/test/csf/TrustGraph.h +++ b/src/test/csf/TrustGraph.h @@ -122,9 +122,9 @@ public: { auto const& unlA = uniqueUNLs[i]; auto const& unlB = uniqueUNLs[j]; - double rhs = 2.0 * (1. - quorum) * std::max(unlA.size(), unlB.size()); + double const rhs = 2.0 * (1. - quorum) * std::max(unlA.size(), unlB.size()); - int intersectionSize = std::count_if( + int const intersectionSize = std::count_if( unlA.begin(), unlA.end(), [&](Peer p) { return unlB.find(p) != unlB.end(); }); if (intersectionSize < rhs) diff --git a/src/test/csf/impl/ledgers.cpp b/src/test/csf/impl/ledgers.cpp index 2c5bf07880..9b0a4e3973 100644 --- a/src/test/csf/impl/ledgers.cpp +++ b/src/test/csf/impl/ledgers.cpp @@ -42,14 +42,14 @@ mismatch(Ledger const& a, Ledger const& b) // end is 1 past end of range Seq start{0}; - Seq end = std::min(a.seq() + Seq{1}, b.seq() + Seq{1}); + Seq const end = std::min(a.seq() + Seq{1}, b.seq() + Seq{1}); // Find mismatch in [start,end) // Binary search Seq count = end - start; while (count > Seq{0}) { - Seq step = count / Seq{2}; + Seq const step = count / Seq{2}; Seq curr = start + step; if (a[curr] == b[curr]) { diff --git a/src/test/csf/random.h b/src/test/csf/random.h index fc5098af32..f3ecca1dbc 100644 --- a/src/test/csf/random.h +++ b/src/test/csf/random.h @@ -25,7 +25,7 @@ random_weighted_shuffle(std::vector v, std::vector w, G& g) for (int i = 0; i < v.size() - 1; ++i) { // pick a random item weighted by w - std::discrete_distribution<> dd(w.begin() + i, w.end()); + std::discrete_distribution<> dd(w.begin() + i, w.end()); // NOLINT(misc-const-correctness) auto idx = dd(g); std::swap(v[i], v[idx]); std::swap(w[i], w[idx]); diff --git a/src/test/csf/timers.h b/src/test/csf/timers.h index c8d71d5b7a..beb4e142d9 100644 --- a/src/test/csf/timers.h +++ b/src/test/csf/timers.h @@ -47,11 +47,11 @@ public: beat(SimTime when) { using namespace std::chrono; - RealTime realTime = RealClock::now(); - SimTime simTime = when; + RealTime const realTime = RealClock::now(); + SimTime const simTime = when; - RealDuration realDuration = realTime - startRealTime_; - SimDuration simDuration = simTime - startSimTime_; + RealDuration const realDuration = realTime - startRealTime_; + SimDuration const simDuration = simTime - startSimTime_; out_ << "Heartbeat. Time Elapsed: {sim: " << duration_cast(simDuration).count() << "s | real: " << duration_cast(realDuration).count() << "s}\n" << std::flush; diff --git a/src/test/jtx/AMMTest.h b/src/test/jtx/AMMTest.h index dd18733ffd..a311d9c638 100644 --- a/src/test/jtx/AMMTest.h +++ b/src/test/jtx/AMMTest.h @@ -127,7 +127,7 @@ protected: void signal() { - std::lock_guard lk(mutex_); + std::lock_guard const lk(mutex_); signaled_ = true; cv_.notify_all(); } diff --git a/src/test/jtx/CaptureLogs.h b/src/test/jtx/CaptureLogs.h index 8419c4dc70..8c8da6817b 100644 --- a/src/test/jtx/CaptureLogs.h +++ b/src/test/jtx/CaptureLogs.h @@ -37,14 +37,14 @@ class CaptureLogs : public Logs void write(beast::severities::Severity level, std::string const& text) override { - std::lock_guard lock(strmMutex_); + std::lock_guard const lock(strmMutex_); strm_ << text; } void writeAlways(beast::severities::Severity level, std::string const& text) override { - std::lock_guard lock(strmMutex_); + std::lock_guard const lock(strmMutex_); strm_ << text; } }; diff --git a/src/test/jtx/Env_test.cpp b/src/test/jtx/Env_test.cpp index 51abac8101..4e9f0d99e2 100644 --- a/src/test/jtx/Env_test.cpp +++ b/src/test/jtx/Env_test.cpp @@ -37,7 +37,7 @@ public: Account b(a); a = b; a = std::move(b); - Account c(std::move(a)); + Account const c(std::move(a)); } Account("alice"); // NOLINT(bugprone-unused-raii) Account("alice", KeyType::secp256k1); // NOLINT(bugprone-unused-raii) @@ -635,9 +635,10 @@ public: std::uint32_t const aliceSeq = env.seq("alice"); // Sign jsonNoop. - Json::Value jsonNoop = env.json(noop("alice"), fee(baseFee), seq(aliceSeq), sig("alice")); + Json::Value const jsonNoop = + env.json(noop("alice"), fee(baseFee), seq(aliceSeq), sig("alice")); // Re-sign jsonNoop. - JTx jt = env.jt(jsonNoop); + JTx const jt = env.jt(jsonNoop); env(jt); } @@ -752,7 +753,7 @@ public: Env env{*this, missingSomeFeatures}; BEAST_EXPECT(env.app().config().features.size() == (supported.count() - 2)); foreachFeature(supported, [&](uint256 const& f) { - bool hasnot = (f == featureDynamicMPT || f == featureTokenEscrow); + bool const hasnot = (f == featureDynamicMPT || f == featureTokenEscrow); this->BEAST_EXPECT(hasnot != hasFeature(env, f)); }); } @@ -771,7 +772,7 @@ public: BEAST_EXPECT(hasFeature(env, *neverSupportedFeat)); foreachFeature(supported, [&](uint256 const& f) { - bool has = (f == featureDynamicMPT || f == featureTokenEscrow); + bool const has = (f == featureDynamicMPT || f == featureTokenEscrow); this->BEAST_EXPECT(has == hasFeature(env, f)); }); } @@ -787,7 +788,7 @@ public: BEAST_EXPECT(env.app().config().features.size() == (supported.count() - 2 + 1)); BEAST_EXPECT(hasFeature(env, *neverSupportedFeat)); foreachFeature(supported, [&](uint256 const& f) { - bool hasnot = (f == featureDynamicMPT || f == featureTokenEscrow); + bool const hasnot = (f == featureDynamicMPT || f == featureTokenEscrow); this->BEAST_EXPECT(hasnot != hasFeature(env, f)); }); } @@ -811,7 +812,7 @@ public: testExceptionalShutdown() { except([this] { - jtx::Env env{ + jtx::Env const env{ *this, jtx::envconfig([](std::unique_ptr cfg) { (*cfg).deprecatedClearSection("port_rpc"); diff --git a/src/test/jtx/TestHelpers.h b/src/test/jtx/TestHelpers.h index e2b623911c..4da086b05b 100644 --- a/src/test/jtx/TestHelpers.h +++ b/src/test/jtx/TestHelpers.h @@ -596,7 +596,7 @@ checkMetrics( std::uint64_t expectedMedFeeLevel = minEscalationFeeLevel.fee(), std::source_location const location = std::source_location::current()) { - int line = location.line(); + int const line = location.line(); char const* file = location.file_name(); FeeLevel64 const expectedMin{expectedMinFeeLevel}; FeeLevel64 const expectedMed{expectedMedFeeLevel}; diff --git a/src/test/jtx/TrustedPublisherServer.h b/src/test/jtx/TrustedPublisherServer.h index dc7682bb72..d36babf380 100644 --- a/src/test/jtx/TrustedPublisherServer.h +++ b/src/test/jtx/TrustedPublisherServer.h @@ -170,7 +170,7 @@ public: } data.pop_back(); data += "]}"; - std::string blob = base64_encode(data); + std::string const blob = base64_encode(data); return std::make_pair(data, blob); }(); auto const sig = strHex(sign(keys.first, keys.second, makeSlice(data))); @@ -198,7 +198,7 @@ public: } data.pop_back(); data += "]}"; - std::string blob = base64_encode(data); + std::string const blob = base64_encode(data); auto const sig = strHex(sign(keys.first, keys.second, makeSlice(data))); blobInfo.emplace_back(blob, sig); } @@ -562,7 +562,7 @@ private: res.result(http::status::ok); res.insert("Content-Type", "text/example"); // if huge was requested, lie about content length - std::uint64_t cl = boost::starts_with(path, "/textfile/huge") + std::uint64_t const cl = boost::starts_with(path, "/textfile/huge") ? std::numeric_limits::max() : 1024; res.content_length(cl); diff --git a/src/test/jtx/amount.h b/src/test/jtx/amount.h index c4e97502db..1912f01330 100644 --- a/src/test/jtx/amount.h +++ b/src/test/jtx/amount.h @@ -196,8 +196,8 @@ public: PrettyAmount operator()(Number v, Number::rounding_mode rounding = Number::getround()) const { - NumberRoundModeGuard mg(rounding); - STAmount amount{asset_, v * scale_}; + NumberRoundModeGuard const mg(rounding); + STAmount const amount{asset_, v * scale_}; return {amount, ""}; } diff --git a/src/test/jtx/impl/AMM.cpp b/src/test/jtx/impl/AMM.cpp index 7109a2131d..fe8fb8c443 100644 --- a/src/test/jtx/impl/AMM.cpp +++ b/src/test/jtx/impl/AMM.cpp @@ -677,13 +677,13 @@ AMM::bid(BidArg const& arg) }; if (arg.bidMin) { - STAmount saTokens = getBid(*arg.bidMin); + STAmount const saTokens = getBid(*arg.bidMin); saTokens.setJson(jv[jss::BidMin]); bidMin_ = saTokens.iou(); } if (arg.bidMax) { - STAmount saTokens = getBid(*arg.bidMax); + STAmount const saTokens = getBid(*arg.bidMax); saTokens.setJson(jv[jss::BidMax]); bidMax_ = saTokens.iou(); } diff --git a/src/test/jtx/impl/Env.cpp b/src/test/jtx/impl/Env.cpp index 3f49a54ae6..a6344b5ab1 100644 --- a/src/test/jtx/impl/Env.cpp +++ b/src/test/jtx/impl/Env.cpp @@ -512,7 +512,7 @@ Env::autofill_sig(JTx& jt) { auto& jv = jt.jv; - scope_success success([&]() { + scope_success const success([&]() { // Call all the post-signers after the main signers or autofill are done for (auto const& signer : jt.postSigners) signer(*this, jt); @@ -561,7 +561,7 @@ Env::autofill(JTx& jt) if (jt.fill_netid) { - uint32_t networkID = app().getNetworkIDService().getNetworkID(); + uint32_t const networkID = app().getNetworkIDService().getNetworkID(); if (!jv.isMember(jss::NetworkID) && networkID > 1024) jv[jss::NetworkID] = std::to_string(networkID); } diff --git a/src/test/jtx/impl/WSClient.cpp b/src/test/jtx/impl/WSClient.cpp index ebe4721d60..0c9b72c4d0 100644 --- a/src/test/jtx/impl/WSClient.cpp +++ b/src/test/jtx/impl/WSClient.cpp @@ -272,7 +272,7 @@ private: rb_.consume(rb_.size()); auto m = std::make_shared(std::move(jv)); { - std::lock_guard lock(m_); + std::lock_guard const lock(m_); msgs_.push_front(m); cv_.notify_all(); } @@ -286,7 +286,7 @@ private: void on_read_done() { - std::lock_guard lock(m0_); + std::lock_guard const lock(m0_); b0_ = true; cv0_.notify_all(); } diff --git a/src/test/jtx/impl/mpt.cpp b/src/test/jtx/impl/mpt.cpp index 2b78777838..0a6af63450 100644 --- a/src/test/jtx/impl/mpt.cpp +++ b/src/test/jtx/impl/mpt.cpp @@ -140,7 +140,7 @@ MPTTester::create(MPTCreate const& arg) if (id_) Throw("MPT can't be reused"); id_ = makeMptID(env_.seq(issuer_), issuer_); - Json::Value jv = createJV( + Json::Value const jv = createJV( {.issuer = issuer_, .maxAmt = arg.maxAmt, .assetScale = arg.assetScale, @@ -217,7 +217,7 @@ MPTTester::destroy(MPTDestroy const& arg) { if (!arg.id && !id_) Throw("MPT has not been created"); - Json::Value jv = + Json::Value const jv = destroyJV({.issuer = arg.issuer ? arg.issuer : issuer_, .id = arg.id ? arg.id : id_}); submit(arg, jv); } @@ -251,7 +251,7 @@ MPTTester::authorize(MPTAuthorize const& arg) { if (!arg.id && !id_) Throw("MPT has not been created"); - Json::Value jv = authorizeJV({ + Json::Value const jv = authorizeJV({ .account = arg.account ? arg.account : issuer_, .holder = arg.holder, .id = arg.id ? arg.id : id_, @@ -361,7 +361,7 @@ MPTTester::set(MPTSet const& arg) { if (!arg.id && !id_) Throw("MPT has not been created"); - Json::Value jv = setJV( + Json::Value const jv = setJV( {.account = arg.account ? arg.account : issuer_, .holder = arg.holder, .id = arg.id ? arg.id : id_, diff --git a/src/test/jtx/impl/multisign.cpp b/src/test/jtx/impl/multisign.cpp index 02550b803c..8e3c37f68c 100644 --- a/src/test/jtx/impl/multisign.cpp +++ b/src/test/jtx/impl/multisign.cpp @@ -78,7 +78,7 @@ msig::operator()(Env& env, JTx& jt) const jo[jss::Account] = e.acct.human(); jo[jss::SigningPubKey] = strHex(e.sig.pk().slice()); - Serializer ss{buildMultiSigningData(*st, e.acct.id())}; + Serializer const ss{buildMultiSigningData(*st, e.acct.id())}; auto const sig = xrpl::sign(*publicKeyType(e.sig.pk().slice()), e.sig.sk(), ss.slice()); jo[sfTxnSignature.getJsonName()] = strHex(Slice{sig.data(), sig.size()}); } diff --git a/src/test/jtx/impl/permissioned_dex.cpp b/src/test/jtx/impl/permissioned_dex.cpp index 87b7896663..494ea897d4 100644 --- a/src/test/jtx/impl/permissioned_dex.cpp +++ b/src/test/jtx/impl/permissioned_dex.cpp @@ -20,7 +20,7 @@ setupDomain( env.fund(XRP(100000), domainOwner); env.close(); - pdomain::Credentials credentials{{domainOwner, credType}}; + pdomain::Credentials const credentials{{domainOwner, credType}}; env(pdomain::setTx(domainOwner, credentials)); auto const objects = pdomain::getObjects(domainOwner, env); diff --git a/src/test/jtx/impl/xchain_bridge.cpp b/src/test/jtx/impl/xchain_bridge.cpp index c2617f5073..19c1b7fab5 100644 --- a/src/test/jtx/impl/xchain_bridge.cpp +++ b/src/test/jtx/impl/xchain_bridge.cpp @@ -431,7 +431,7 @@ XChainBridgeObjects::XChainBridgeObjects() void XChainBridgeObjects::createMcBridgeObjects(Env& mcEnv) { - STAmount xrp_funds{XRP(10000)}; + STAmount const xrp_funds{XRP(10000)}; mcEnv.fund(xrp_funds, mcDoor, mcAlice, mcBob, mcCarol, mcGw); // Signer's list must match the attestation signers @@ -448,7 +448,7 @@ XChainBridgeObjects::createMcBridgeObjects(Env& mcEnv) void XChainBridgeObjects::createScBridgeObjects(Env& scEnv) { - STAmount xrp_funds{XRP(10000)}; + STAmount const xrp_funds{XRP(10000)}; scEnv.fund(xrp_funds, scDoor, scAlice, scBob, scCarol, scGw, scAttester, scReward); // Signer's list must match the attestation signers diff --git a/src/test/ledger/BookDirs_test.cpp b/src/test/ledger/BookDirs_test.cpp index d7841fe502..e8733d159d 100644 --- a/src/test/ledger/BookDirs_test.cpp +++ b/src/test/ledger/BookDirs_test.cpp @@ -19,7 +19,7 @@ struct BookDirs_test : public beast::unit_test::suite env.close(); { - Book book(xrpIssue(), USD.issue(), std::nullopt); + Book const book(xrpIssue(), USD.issue(), std::nullopt); { auto d = BookDirs(*env.current(), book); BEAST_EXPECT(std::begin(d) == std::end(d)); diff --git a/src/test/ledger/Directory_test.cpp b/src/test/ledger/Directory_test.cpp index aec472fc6f..4115d03c19 100644 --- a/src/test/ledger/Directory_test.cpp +++ b/src/test/ledger/Directory_test.cpp @@ -282,7 +282,7 @@ struct Directory_test : public beast::unit_test::suite // All the offers have been cancelled, so the book // should have no entries and be empty: { - Sandbox sb(env.closed().get(), tapNONE); + Sandbox const sb(env.closed().get(), tapNONE); uint256 const bookBase = getBookBase({xrpIssue(), USD.issue(), std::nullopt}); BEAST_EXPECT(dirIsEmpty(sb, keylet::page(bookBase))); diff --git a/src/test/ledger/PaymentSandbox_test.cpp b/src/test/ledger/PaymentSandbox_test.cpp index df23381ed3..ab01c4852e 100644 --- a/src/test/ledger/PaymentSandbox_test.cpp +++ b/src/test/ledger/PaymentSandbox_test.cpp @@ -65,7 +65,7 @@ class PaymentSandbox_test : public beast::unit_test::suite env(offer(snd, USD_gw1(2), USD_gw2(2)), txflags(tfPassive)); env(offer(snd, USD_gw2(2), USD_gw1(2)), txflags(tfPassive)); - PathSet paths(Path(gw1, USD_gw2, gw2), Path(gw2, USD_gw1, gw1)); + PathSet const paths(Path(gw1, USD_gw2, gw2), Path(gw2, USD_gw1, gw1)); env(pay(snd, rcv, any(USD_gw1(4))), json(paths.json()), @@ -266,16 +266,16 @@ class PaymentSandbox_test : public beast::unit_test::suite using namespace jtx; - Env env(*this, features); + Env const env(*this, features); Account const gw("gw"); Account const alice("alice"); auto const USD = gw["USD"]; auto const issue = USD.issue(); - STAmount tinyAmt( + STAmount const tinyAmt( issue, STAmount::cMinValue, STAmount::cMinOffset + 1, false, STAmount::unchecked{}); - STAmount hugeAmt( + STAmount const hugeAmt( issue, STAmount::cMaxValue, STAmount::cMaxOffset - 1, false, STAmount::unchecked{}); ApplyViewImpl av(&*env.current(), tapNONE); @@ -333,7 +333,7 @@ class PaymentSandbox_test : public beast::unit_test::suite testcase("balanceHook"); using namespace jtx; - Env env(*this, features); + Env const env(*this, features); Account const gw("gw"); auto const USD = gw["USD"]; diff --git a/src/test/ledger/SkipList_test.cpp b/src/test/ledger/SkipList_test.cpp index ba339878ef..a2695bfce8 100644 --- a/src/test/ledger/SkipList_test.cpp +++ b/src/test/ledger/SkipList_test.cpp @@ -15,7 +15,7 @@ class SkipList_test : public beast::unit_test::suite jtx::Env env(*this); std::vector> history; { - Config config; + Config const config; auto prev = std::make_shared( create_genesis, Rules{config.features}, diff --git a/src/test/ledger/View_test.cpp b/src/test/ledger/View_test.cpp index 6e11508156..d2d930732e 100644 --- a/src/test/ledger/View_test.cpp +++ b/src/test/ledger/View_test.cpp @@ -114,7 +114,7 @@ class View_test : public beast::unit_test::suite using namespace jtx; Env env(*this); - Config config; + Config const config; std::shared_ptr const genesis = std::make_shared( create_genesis, Rules{config.features}, @@ -124,7 +124,7 @@ class View_test : public beast::unit_test::suite auto const ledger = std::make_shared(*genesis, env.app().getTimeKeeper().closeTime()); wipe(*ledger); - ReadView& v = *ledger; + ReadView const& v = *ledger; succ(v, 0, std::nullopt); ledger->rawInsert(sle(1, 1)); BEAST_EXPECT(v.exists(k(1))); @@ -338,7 +338,7 @@ class View_test : public beast::unit_test::suite BEAST_EXPECT(v2.seq() == v1.seq()); BEAST_EXPECT(v2.flags() == tapRETRY); - Sandbox v3(&v2); + Sandbox const v3(&v2); BEAST_EXPECT(v3.seq() == v2.seq()); BEAST_EXPECT(v3.parentCloseTime() == v2.parentCloseTime()); BEAST_EXPECT(v3.flags() == tapRETRY); @@ -349,7 +349,7 @@ class View_test : public beast::unit_test::suite BEAST_EXPECT(v2.seq() == v0.seq()); BEAST_EXPECT(v2.parentCloseTime() == v0.parentCloseTime()); BEAST_EXPECT(v2.flags() == tapRETRY); - PaymentSandbox v3(&v2); + PaymentSandbox const v3(&v2); BEAST_EXPECT(v3.seq() == v2.seq()); BEAST_EXPECT(v3.parentCloseTime() == v2.parentCloseTime()); BEAST_EXPECT(v3.flags() == v2.flags()); @@ -382,7 +382,7 @@ class View_test : public beast::unit_test::suite using namespace jtx; Env env(*this); - Config config; + Config const config; std::shared_ptr const genesis = std::make_shared( create_genesis, Rules{config.features}, @@ -591,7 +591,7 @@ class View_test : public beast::unit_test::suite using namespace jtx; Env env(*this); - Config config; + Config const config; std::shared_ptr const genesis = std::make_shared( create_genesis, Rules{config.features}, @@ -942,7 +942,7 @@ class View_test : public beast::unit_test::suite // erase the item, apply. { Env env(*this); - Config config; + Config const config; std::shared_ptr const genesis = std::make_shared( create_genesis, Rules{config.features}, @@ -953,7 +953,7 @@ class View_test : public beast::unit_test::suite std::make_shared(*genesis, env.app().getTimeKeeper().closeTime()); wipe(*ledger); ledger->rawInsert(sle(1)); - ReadView& v0 = *ledger; + ReadView const& v0 = *ledger; ApplyViewImpl v1(&v0, tapNONE); { Sandbox v2(&v1); diff --git a/src/test/nodestore/Backend_test.cpp b/src/test/nodestore/Backend_test.cpp index 19f3bc43e5..101138de88 100644 --- a/src/test/nodestore/Backend_test.cpp +++ b/src/test/nodestore/Backend_test.cpp @@ -26,7 +26,7 @@ public: testcase("Backend type=" + type); Section params; - beast::temp_dir tempDir; + beast::temp_dir const tempDir; params.set("type", type); params.set("path", tempDir.path()); diff --git a/src/test/nodestore/Basics_test.cpp b/src/test/nodestore/Basics_test.cpp index e37544f58e..c9755d04d7 100644 --- a/src/test/nodestore/Basics_test.cpp +++ b/src/test/nodestore/Basics_test.cpp @@ -38,7 +38,7 @@ public: for (int i = 0; i < batch.size(); ++i) { - EncodedBlob encoded(batch[i]); + EncodedBlob const encoded(batch[i]); DecodedBlob decoded(encoded.getKey(), encoded.getData(), encoded.getSize()); diff --git a/src/test/nodestore/Database_test.cpp b/src/test/nodestore/Database_test.cpp index 6943f0733e..43bda9dcae 100644 --- a/src/test/nodestore/Database_test.cpp +++ b/src/test/nodestore/Database_test.cpp @@ -191,7 +191,7 @@ public: try { - Env env( + Env const env( *this, std::move(p), std::make_unique(expected, &found), @@ -220,7 +220,7 @@ public: try { - Env env( + Env const env( *this, std::move(p), std::make_unique(expected, &found), @@ -249,7 +249,7 @@ public: try { - Env env( + Env const env( *this, std::move(p), std::make_unique(expected, &found), @@ -278,7 +278,7 @@ public: try { - Env env( + Env const env( *this, std::move(p), std::make_unique(expected, &found), @@ -306,7 +306,7 @@ public: try { - Env env( + Env const env( *this, std::move(p), std::make_unique(expected, &found), @@ -334,7 +334,7 @@ public: try { - Env env( + Env const env( *this, std::move(p), std::make_unique(expected, &found), @@ -362,7 +362,7 @@ public: try { - Env env( + Env const env( *this, std::move(p), std::make_unique(expected, &found), @@ -390,7 +390,7 @@ public: try { - Env env( + Env const env( *this, std::move(p), std::make_unique(expected, &found), @@ -445,7 +445,7 @@ public: } try { - Env env( + Env const env( *this, std::move(p), std::make_unique(expected, &found), @@ -468,7 +468,7 @@ public: } try { - Env env( + Env const env( *this, std::move(p), std::make_unique(expected, &found), @@ -491,7 +491,7 @@ public: } try { - Env env( + Env const env( *this, std::move(p), std::make_unique(expected, &found), @@ -515,7 +515,7 @@ public: { DummyScheduler scheduler; - beast::temp_dir node_db; + beast::temp_dir const node_db; Section srcParams; srcParams.set("type", srcBackendType); srcParams.set("path", node_db.path()); @@ -538,7 +538,7 @@ public: Manager::instance().make_Database(megabytes(4), scheduler, 2, srcParams, journal_); // Set up the destination database - beast::temp_dir dest_db; + beast::temp_dir const dest_db; Section destParams; destParams.set("type", destBackendType); destParams.set("path", dest_db.path()); @@ -572,11 +572,11 @@ public: { DummyScheduler scheduler; - std::string s = "NodeStore backend '" + type + "'"; + std::string const s = "NodeStore backend '" + type + "'"; testcase(s); - beast::temp_dir node_db; + beast::temp_dir const node_db; Section nodeParams; nodeParams.set("type", type); nodeParams.set("path", node_db.path()); @@ -639,7 +639,7 @@ public: try { nodeParams.set("earliest_seq", "0"); - std::unique_ptr db = Manager::instance().make_Database( + std::unique_ptr const db = Manager::instance().make_Database( megabytes(4), scheduler, 2, nodeParams, journal_); } catch (std::runtime_error const& e) @@ -662,7 +662,7 @@ public: { // Set to default earliest ledger sequence nodeParams.set("earliest_seq", std::to_string(XRP_LEDGER_EARLIEST_SEQ)); - std::unique_ptr db2 = Manager::instance().make_Database( + std::unique_ptr const db2 = Manager::instance().make_Database( megabytes(4), scheduler, 2, nodeParams, journal_); } catch (std::runtime_error const& e) diff --git a/src/test/nodestore/NuDBFactory_test.cpp b/src/test/nodestore/NuDBFactory_test.cpp index 0aa910ce01..3e6b68c9e5 100644 --- a/src/test/nodestore/NuDBFactory_test.cpp +++ b/src/test/nodestore/NuDBFactory_test.cpp @@ -76,12 +76,12 @@ private: std::string const& expectedMessage) { test::StreamSink sink(level); - beast::Journal journal(sink); + beast::Journal const journal(sink); DummyScheduler scheduler; auto backend = Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); - std::string logOutput = sink.messages().str(); + std::string const logOutput = sink.messages().str(); BEAST_EXPECT(logOutput.find(expectedMessage) != std::string::npos); } @@ -89,17 +89,17 @@ private: void testPowerOfTwoValidation(std::string const& size, bool shouldWork) { - beast::temp_dir tempDir; + beast::temp_dir const tempDir; auto params = createSection(tempDir.path(), size); test::StreamSink sink(beast::severities::kWarning); - beast::Journal journal(sink); + beast::Journal const journal(sink); DummyScheduler scheduler; auto backend = Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); - std::string logOutput = sink.messages().str(); - bool hasWarning = logOutput.find("Invalid nudb_block_size") != std::string::npos; + std::string const logOutput = sink.messages().str(); + bool const hasWarning = logOutput.find("Invalid nudb_block_size") != std::string::npos; BEAST_EXPECT(hasWarning == !shouldWork); } @@ -110,7 +110,7 @@ public: { testcase("Default block size (no nudb_block_size specified)"); - beast::temp_dir tempDir; + beast::temp_dir const tempDir; auto params = createSection(tempDir.path()); // Should work with default 4096 block size @@ -122,18 +122,18 @@ public: { testcase("Valid block sizes"); - std::vector validSizes = {4096, 8192, 16384, 32768}; + std::vector const validSizes = {4096, 8192, 16384, 32768}; for (auto const& size : validSizes) { - beast::temp_dir tempDir; + beast::temp_dir const tempDir; auto params = createSection(tempDir.path(), to_string(size)); BEAST_EXPECT(testBackendFunctionality(params, size)); } // Empty value is ignored by the config parser, so uses the // default - beast::temp_dir tempDir; + beast::temp_dir const tempDir; auto params = createSection(tempDir.path(), ""); BEAST_EXPECT(testBackendFunctionality(params, 4096)); @@ -144,7 +144,7 @@ public: { testcase("Invalid block sizes"); - std::vector invalidSizes = { + std::vector const invalidSizes = { "2048", // Too small "1024", // Too small "65536", // Too large @@ -161,7 +161,7 @@ public: for (auto const& size : invalidSizes) { - beast::temp_dir tempDir; + beast::temp_dir const tempDir; auto params = createSection(tempDir.path(), size); // Fails @@ -169,14 +169,14 @@ public: } // Test whitespace cases separately since lexical_cast may handle them - std::vector whitespaceInvalidSizes = { + std::vector const whitespaceInvalidSizes = { "4096 ", // Trailing space - might be handled by lexical_cast " 4096" // Leading space - might be handled by lexical_cast }; for (auto const& size : whitespaceInvalidSizes) { - beast::temp_dir tempDir; + beast::temp_dir const tempDir; auto params = createSection(tempDir.path(), size); // Fails @@ -191,7 +191,7 @@ public: // Test valid custom block size logging { - beast::temp_dir tempDir; + beast::temp_dir const tempDir; auto params = createSection(tempDir.path(), "8192"); testLogMessage(params, beast::severities::kInfo, "Using custom NuDB block size: 8192"); @@ -199,11 +199,11 @@ public: // Test invalid block size failure { - beast::temp_dir tempDir; + beast::temp_dir const tempDir; auto params = createSection(tempDir.path(), "5000"); test::StreamSink sink(beast::severities::kWarning); - beast::Journal journal(sink); + beast::Journal const journal(sink); DummyScheduler scheduler; try @@ -214,7 +214,7 @@ public: } catch (std::exception const& e) { - std::string logOutput{e.what()}; + std::string const logOutput{e.what()}; BEAST_EXPECT(logOutput.find("Invalid nudb_block_size: 5000") != std::string::npos); BEAST_EXPECT( logOutput.find("Must be power of 2 between 4096 and 32768") != @@ -224,11 +224,11 @@ public: // Test non-numeric value failure { - beast::temp_dir tempDir; + beast::temp_dir const tempDir; auto params = createSection(tempDir.path(), "invalid"); test::StreamSink sink(beast::severities::kWarning); - beast::Journal journal(sink); + beast::Journal const journal(sink); DummyScheduler scheduler; try @@ -240,7 +240,7 @@ public: } catch (std::exception const& e) { - std::string logOutput{e.what()}; + std::string const logOutput{e.what()}; BEAST_EXPECT( logOutput.find("Invalid nudb_block_size value: invalid") != std::string::npos); } @@ -253,7 +253,7 @@ public: testcase("Power of 2 validation logic"); // Test edge cases around valid range - std::vector> testCases = { + std::vector> const testCases = { {"4095", false}, // Just below minimum {"4096", true}, // Minimum valid {"4097", false}, // Just above minimum, not power of 2 @@ -267,13 +267,13 @@ public: for (auto const& [size, shouldWork] : testCases) { - beast::temp_dir tempDir; + beast::temp_dir const tempDir; auto params = createSection(tempDir.path(), size); // We test the validation logic by catching exceptions for invalid // values test::StreamSink sink(beast::severities::kWarning); - beast::Journal journal(sink); + beast::Journal const journal(sink); DummyScheduler scheduler; try @@ -284,7 +284,7 @@ public: } catch (std::exception const& e) { - std::string logOutput{e.what()}; + std::string const logOutput{e.what()}; BEAST_EXPECT(logOutput.find("Invalid nudb_block_size") != std::string::npos); } } @@ -295,7 +295,7 @@ public: { testcase("Both constructor variants work with custom block size"); - beast::temp_dir tempDir; + beast::temp_dir const tempDir; auto params = createSection(tempDir.path(), "16384"); DummyScheduler scheduler; @@ -321,13 +321,13 @@ public: testcase("Configuration parsing edge cases"); // Test that whitespace is handled correctly - std::vector validFormats = { + std::vector const validFormats = { "8192" // Basic valid format }; // Test whitespace handling separately since lexical_cast behavior may // vary - std::vector whitespaceFormats = { + std::vector const whitespaceFormats = { " 8192", // Leading space - may or may not be handled by // lexical_cast "8192 " // Trailing space - may or may not be handled by @@ -337,19 +337,19 @@ public: // Test basic valid format for (auto const& format : validFormats) { - beast::temp_dir tempDir; + beast::temp_dir const tempDir; auto params = createSection(tempDir.path(), format); test::StreamSink sink(beast::severities::kInfo); - beast::Journal journal(sink); + beast::Journal const journal(sink); DummyScheduler scheduler; auto backend = Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); // Should log success message for valid values - std::string logOutput = sink.messages().str(); - bool hasSuccessMessage = + std::string const logOutput = sink.messages().str(); + bool const hasSuccessMessage = logOutput.find("Using custom NuDB block size") != std::string::npos; BEAST_EXPECT(hasSuccessMessage); } @@ -358,12 +358,12 @@ public: // them for (auto const& format : whitespaceFormats) { - beast::temp_dir tempDir; + beast::temp_dir const tempDir; auto params = createSection(tempDir.path(), format); // Use a lower threshold to capture both info and warning messages test::StreamSink sink(beast::severities::kDebug); - beast::Journal journal(sink); + beast::Journal const journal(sink); DummyScheduler scheduler; try @@ -385,11 +385,11 @@ public: { testcase("Data persistence with different block sizes"); - std::vector blockSizes = {"4096", "8192", "16384", "32768"}; + std::vector const blockSizes = {"4096", "8192", "16384", "32768"}; for (auto const& size : blockSizes) { - beast::temp_dir tempDir; + beast::temp_dir const tempDir; auto params = createSection(tempDir.path(), size); DummyScheduler scheduler; diff --git a/src/test/nodestore/TestBase.h b/src/test/nodestore/TestBase.h index cb2a8e3bd5..893e06579c 100644 --- a/src/test/nodestore/TestBase.h +++ b/src/test/nodestore/TestBase.h @@ -187,7 +187,7 @@ public: for (int i = 0; i < batch.size(); ++i) { - std::shared_ptr object = db.fetchNodeObject(batch[i]->getHash(), 0); + std::shared_ptr const object = db.fetchNodeObject(batch[i]->getHash(), 0); if (object != nullptr) pCopy->push_back(object); diff --git a/src/test/nodestore/Timing_test.cpp b/src/test/nodestore/Timing_test.cpp index fc8c042252..fb60e6c7a5 100644 --- a/src/test/nodestore/Timing_test.cpp +++ b/src/test/nodestore/Timing_test.cpp @@ -645,7 +645,7 @@ public: params.threads = threads; for (auto i = default_repeat; (i--) != 0u;) { - beast::temp_dir tempDir; + beast::temp_dir const tempDir; Section config = parse(config_string); config.set("path", tempDir.path()); std::stringstream ss; @@ -672,7 +672,7 @@ public: items Number of objects to create in the database */ - std::string default_args = + std::string const default_args = "type=nudb" #if XRPL_ROCKSDB_AVAILABLE ";type=rocksdb,open_files=2000,filter_bits=12,cache_mb=256," diff --git a/src/test/nodestore/import_test.cpp b/src/test/nodestore/import_test.cpp index 54d55e5ad0..6d336c1f51 100644 --- a/src/test/nodestore/import_test.cpp +++ b/src/test/nodestore/import_test.cpp @@ -71,7 +71,7 @@ template std::ostream& pretty_time(std::ostream& os, std::chrono::duration d) { - save_stream_state _(os); + save_stream_state const _(os); using namespace std::chrono; if (d < microseconds{1}) { @@ -332,7 +332,7 @@ public: options.create_if_missing = false; options.max_open_files = 2000; // 5000? rocksdb::DB* pdb = nullptr; - rocksdb::Status status = rocksdb::DB::OpenForReadOnly(options, from_path, &pdb); + rocksdb::Status const status = rocksdb::DB::OpenForReadOnly(options, from_path, &pdb); if (!status.ok() || (pdb == nullptr)) Throw("Can't open '" + from_path + "': " + status.ToString()); db.reset(pdb); @@ -374,7 +374,7 @@ public: void const* const key = it->key().data(); void const* const data = it->value().data(); auto const size = it->value().size(); - std::unique_ptr clean(new char[size]); + std::unique_ptr const clean(new char[size]); std::memcpy(clean.get(), data, size); filter_inner(clean.get(), size); auto const out = nodeobject_compress(clean.get(), size, buf); @@ -458,7 +458,7 @@ public: // Create empty buckets for (std::size_t i = 0; i < bn; ++i) { - bucket b(kh.block_size, buf.get() + (i * kh.block_size), empty); + bucket const b(kh.block_size, buf.get() + (i * kh.block_size), empty); } // Insert all keys into buckets // Iterate Data File diff --git a/src/test/overlay/TMGetObjectByHash_test.cpp b/src/test/overlay/TMGetObjectByHash_test.cpp index e4da8a28c7..a2a934f182 100644 --- a/src/test/overlay/TMGetObjectByHash_test.cpp +++ b/src/test/overlay/TMGetObjectByHash_test.cpp @@ -100,10 +100,10 @@ class TMGetObjectByHash_test : public beast::unit_test::suite auto stream_ptr = std::make_unique(socket_type(env.app().getIOContext()), *context_); - beast::IP::Endpoint local(boost::asio::ip::make_address("172.1.1.1"), 51235); - beast::IP::Endpoint remote(boost::asio::ip::make_address("172.1.1.2"), 51235); + beast::IP::Endpoint const local(boost::asio::ip::make_address("172.1.1.1"), 51235); + beast::IP::Endpoint const remote(boost::asio::ip::make_address("172.1.1.2"), 51235); - PublicKey key(std::get<0>(randomKeyPair(KeyType::ed25519))); + PublicKey const key(std::get<0>(randomKeyPair(KeyType::ed25519))); auto consumer = overlay.resourceManager().newInboundEndpoint(remote); auto [slot, _] = overlay.peerFinder().new_inbound_slot(local, remote); @@ -132,7 +132,7 @@ class TMGetObjectByHash_test : public beast::unit_test::suite hashes.reserve(numObjects); for (int i = 0; i < numObjects; ++i) { - uint256 hash(xrpl::sha512Half(i)); + uint256 const hash(xrpl::sha512Half(i)); hashes.push_back(hash); Blob data(100, static_cast(i % 256)); diff --git a/src/test/overlay/cluster_test.cpp b/src/test/overlay/cluster_test.cpp index 59fa22a442..6fc7f3f59b 100644 --- a/src/test/overlay/cluster_test.cpp +++ b/src/test/overlay/cluster_test.cpp @@ -113,7 +113,7 @@ public: auto const node = randomNode(); auto const name = toBase58(TokenType::NodePublic, node); - std::uint32_t load = 0; + std::uint32_t const load = 0; NetClock::time_point tick = {}; // Initial update diff --git a/src/test/overlay/compression_test.cpp b/src/test/overlay/compression_test.cpp index 8cee7df7d2..4ffc805726 100644 --- a/src/test/overlay/compression_test.cpp +++ b/src/test/overlay/compression_test.cpp @@ -163,7 +163,7 @@ public: buildTransaction(Logs& logs) { Env env(*this, envconfig()); - int fund = 10000; + int const fund = 10000; auto const alice = Account("alice"); auto const bob = Account("bob"); env.fund(XRP(fund), "alice", "bob"); @@ -205,7 +205,7 @@ public: uint256 const hash(xrpl::sha512Half(123456789)); getLedger->set_ledgerhash(hash.begin(), hash.size()); getLedger->set_ledgerseq(123456789); - xrpl::SHAMapNodeID sha(64, hash); + xrpl::SHAMapNodeID const sha(64, hash); getLedger->add_nodeids(sha.getRawString()); getLedger->set_requestcookie(123456789); getLedger->set_querytype(protocol::qtINDIRECT); @@ -268,7 +268,7 @@ public: uint256 hash(xrpl::sha512Half(i)); auto object = getObject->add_objects(); object->set_hash(hash.data(), hash.size()); - xrpl::SHAMapNodeID sha(64, hash); + xrpl::SHAMapNodeID const sha(64, hash); object->set_nodeid(sha.getRawString()); object->set_index(""); object->set_data(""); @@ -295,7 +295,7 @@ public: st.add(s); list->set_manifest(s.data(), s.size()); list->set_version(3); - STObject signature(sfSignature); + STObject const signature(sfSignature); xrpl::sign(st, HashPrefix::manifest, KeyType::ed25519, std::get<1>(signing)); Serializer s1; st.add(s1); @@ -322,7 +322,7 @@ public: st.add(s); list->set_manifest(s.data(), s.size()); list->set_version(4); - STObject signature(sfSignature); + STObject const signature(sfSignature); xrpl::sign(st, HashPrefix::manifest, KeyType::ed25519, std::get<1>(signing)); Serializer s1; st.add(s1); @@ -338,14 +338,14 @@ public: auto thresh = beast::severities::Severity::kInfo; auto logs = std::make_unique(thresh); - protocol::TMManifests manifests; - protocol::TMEndpoints endpoints; - protocol::TMTransaction transaction; - protocol::TMGetLedger get_ledger; - protocol::TMLedgerData ledger_data; - protocol::TMGetObjectByHash get_object; - protocol::TMValidatorList validator_list; - protocol::TMValidatorListCollection validator_list_collection; + protocol::TMManifests const manifests; + protocol::TMEndpoints const endpoints; + protocol::TMTransaction const transaction; + protocol::TMGetLedger const get_ledger; + protocol::TMLedgerData const ledger_data; + protocol::TMGetObjectByHash const get_object; + protocol::TMValidatorList const validator_list; + protocol::TMValidatorListCollection const validator_list_collection; // 4.5KB doTest(buildManifests(20), protocol::mtMANIFESTS, 4, "TMManifests20"); @@ -399,7 +399,7 @@ public: return env; }; auto handshake = [&](int outboundEnable, int inboundEnable) { - beast::IP::Address addr = boost::asio::ip::make_address("172.1.1.100"); + beast::IP::Address const addr = boost::asio::ip::make_address("172.1.1.100"); auto env = getEnv(outboundEnable); auto request = xrpl::makeRequest( diff --git a/src/test/overlay/reduce_relay_test.cpp b/src/test/overlay/reduce_relay_test.cpp index 895332b94f..4a8d62fbc2 100644 --- a/src/test/overlay/reduce_relay_test.cpp +++ b/src/test/overlay/reduce_relay_test.cpp @@ -120,7 +120,7 @@ public: uint256 const& getClosedLedgerHash() const override { - static uint256 hash{}; + static uint256 const hash{}; return hash; } bool @@ -481,7 +481,7 @@ public: onMessage(protocol::TMSquelch const& squelch) override { auto validator = squelch.validatorpubkey(); - PublicKey key(Slice(validator.data(), validator.size())); + PublicKey const key(Slice(validator.data(), validator.size())); if (squelch.squelch()) { squelch_.addSquelch(key, std::chrono::seconds{squelch.squelchduration()}); @@ -776,7 +776,7 @@ public: squelch.set_squelch(false); for (auto& v : validators_) { - PublicKey key = v; + PublicKey const key = v; squelch.clear_validatorpubkey(); squelch.set_validatorpubkey(key.data(), key.size()); v.for_links({peer}, [&](Link& l, MessageSPtr) { @@ -886,7 +886,7 @@ protected: std::optional duration) { protocol::TMSquelch squelch; - bool res = static_cast(duration); + bool const res = static_cast(duration); squelch.set_squelch(res); squelch.set_validatorpubkey(validator.data(), validator.size()); if (res) @@ -992,7 +992,7 @@ protected: if (events[EventType::PeerDisconnected].state_ == State::On) { auto& event = events[EventType::PeerDisconnected]; - bool allCounting = network_.allCounting(event.peer_); + bool const allCounting = network_.allCounting(event.peer_); network_.overlay().deletePeer( event.peer_, [&](PublicKey const& v, PeerWPtr const& peerPtr) { if (event.isSelected_) @@ -1004,7 +1004,7 @@ protected: // take place because there is no peers in Squelched state in // any of the slots where the peer is in Selected state // (allCounting is true) - bool handled = (!event.isSelected_ && !event.handled_) || + bool const handled = (!event.isSelected_ && !event.handled_) || (event.isSelected_ && (event.handled_ || allCounting)); BEAST_EXPECT(handled); event.state_ = State::Off; @@ -1047,7 +1047,7 @@ protected: sendSquelch(validator, ptr, {}); } }); - bool handled = (event.handled_ && event.state_ == State::WaitReset) || + bool const handled = (event.handled_ && event.state_ == State::WaitReset) || (!event.handled_ && !mustHandle); BEAST_EXPECT(handled); } @@ -1055,7 +1055,7 @@ protected: (event.state_ == State::On && (now - event.time_ > (reduce_relay::IDLED + seconds(2))))) { - bool handled = event.state_ == State::WaitReset || !event.handled_; + bool const handled = event.state_ == State::WaitReset || !event.handled_; BEAST_EXPECT(handled); event.state_ = State::Off; event.isSelected_ = false; @@ -1270,7 +1270,7 @@ protected: doTest("Test Config - squelch enabled (legacy)", log, [&](bool log) { Config c; - std::string toLoad(R"rippleConfig( + std::string const toLoad(R"rippleConfig( [reduce_relay] vp_enable=1 )rippleConfig"); @@ -1303,7 +1303,7 @@ vp_enable=0 doTest("Test Config - squelch enabled", log, [&](bool log) { Config c; - std::string toLoad(R"rippleConfig( + std::string const toLoad(R"rippleConfig( [reduce_relay] vp_base_squelch_enable=1 )rippleConfig"); @@ -1315,7 +1315,7 @@ vp_base_squelch_enable=1 doTest("Test Config - squelch disabled", log, [&](bool log) { Config c; - std::string toLoad(R"rippleConfig( + std::string const toLoad(R"rippleConfig( [reduce_relay] vp_base_squelch_enable=0 )rippleConfig"); @@ -1327,7 +1327,7 @@ vp_base_squelch_enable=0 doTest("Test Config - legacy and new", log, [&](bool log) { Config c; - std::string toLoad(R"rippleConfig( + std::string const toLoad(R"rippleConfig( [reduce_relay] vp_base_squelch_enable=0 vp_enable=0 @@ -1432,10 +1432,10 @@ vp_base_squelch_max_selected_peers=2 doTest("Duplicate Message", log, [&](bool log) { network_.reset(); // update message count for the same peer/validator - std::int16_t nMessages = 5; + std::int16_t const nMessages = 5; for (int i = 0; i < nMessages; i++) { - uint256 key(i); + uint256 const key(i); network_.overlay().updateSlotAndSquelch( key, network_.validator(0), 0, [&](PublicKey const&, PeerWPtr, std::uint32_t) { }); @@ -1445,7 +1445,7 @@ vp_base_squelch_max_selected_peers=2 // hence '-1'. BEAST_EXPECT(std::get<1>(peers[0]) == (nMessages - 1)); // add duplicate - uint256 key(nMessages - 1); + uint256 const key(nMessages - 1); network_.overlay().updateSlotAndSquelch( key, network_.validator(0), 0, [&](PublicKey const&, PeerWPtr, std::uint32_t) {}); // confirm the same number of messages @@ -1498,7 +1498,7 @@ vp_base_squelch_max_selected_peers=2 { // make unique message hash to make the // slot's internal hash router accept the message - std::uint64_t mid = (m * 1000) + peer; + std::uint64_t const mid = (m * 1000) + peer; uint256 const message{mid}; slots.updateSlotAndSquelch( message, validator, peer, protocol::MessageType::mtVALIDATION); @@ -1568,7 +1568,7 @@ vp_base_squelch_max_selected_peers=2 env_.app().config().COMPRESSION = c.COMPRESSION; }; auto handshake = [&](int outboundEnable, int inboundEnable) { - beast::IP::Address addr = boost::asio::ip::make_address("172.1.1.100"); + beast::IP::Address const addr = boost::asio::ip::make_address("172.1.1.100"); setEnv(outboundEnable); auto request = xrpl::makeRequest( @@ -1622,7 +1622,7 @@ public: void run() override { - bool log = false; + bool const log = false; testConfig(log); testInitialRound(log); testPeerUnsquelchedTooSoon(log); @@ -1649,7 +1649,7 @@ class reduce_relay_simulate_test : public reduce_relay_test void run() override { - bool log = false; + bool const log = false; testRandom(log); } }; diff --git a/src/test/overlay/short_read_test.cpp b/src/test/overlay/short_read_test.cpp index d96f67c8a1..0c8b7f8a43 100644 --- a/src/test/overlay/short_read_test.cpp +++ b/src/test/overlay/short_read_test.cpp @@ -56,7 +56,7 @@ private: using boost::asio::buffer; using boost::asio::buffer_copy; using boost::asio::buffer_size; - boost::asio::const_buffer buf(s.data(), s.size()); + boost::asio::const_buffer const buf(s.data(), s.size()); sb.commit(buffer_copy(sb.prepare(buffer_size(buf)), buf)); } @@ -100,14 +100,14 @@ private: void add(std::shared_ptr const& child) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); list_.emplace(child.get(), child); } void remove(Child* child) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); list_.erase(child); if (list_.empty()) cond_.notify_one(); @@ -118,7 +118,7 @@ private: { std::vector> v; { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); v.reserve(list_.size()); if (closed_) return; @@ -636,7 +636,7 @@ public: void run() override { - Server s(*this); + Server const s(*this); Client c(*this, s.endpoint()); c.wait(); pass(); diff --git a/src/test/overlay/tx_reduce_relay_test.cpp b/src/test/overlay/tx_reduce_relay_test.cpp index 04d8bae768..abb1632858 100644 --- a/src/test/overlay/tx_reduce_relay_test.cpp +++ b/src/test/overlay/tx_reduce_relay_test.cpp @@ -159,10 +159,11 @@ private: auto stream_ptr = std::make_unique( socket_type(std::forward(env.app().getIOContext())), *context_); - beast::IP::Endpoint local(boost::asio::ip::make_address("172.1.1." + std::to_string(lid_))); - beast::IP::Endpoint remote( + beast::IP::Endpoint const local( + boost::asio::ip::make_address("172.1.1." + std::to_string(lid_))); + beast::IP::Endpoint const remote( boost::asio::ip::make_address("172.1.1." + std::to_string(rid_))); - PublicKey key(std::get<0>(randomKeyPair(KeyType::ed25519))); + PublicKey const key(std::get<0>(randomKeyPair(KeyType::ed25519))); auto consumer = overlay.resourceManager().newInboundEndpoint(remote); auto [slot, _] = overlay.peerFinder().new_inbound_slot(local, remote); auto const peer = std::make_shared( @@ -224,7 +225,7 @@ private: void run() override { - bool log = false; + bool const log = false; std::set skip = {0, 1, 2, 3, 4}; testConfig(log); // relay to all peers, no hash queue diff --git a/src/test/peerfinder/Livecache_test.cpp b/src/test/peerfinder/Livecache_test.cpp index b2d0eeeaf1..d12da84ffd 100644 --- a/src/test/peerfinder/Livecache_test.cpp +++ b/src/test/peerfinder/Livecache_test.cpp @@ -33,7 +33,7 @@ public: void add(beast::IP::Endpoint ep, C& c, std::uint32_t hops = 0) { - Endpoint cep{ep, hops}; + Endpoint const cep{ep, hops}; c.insert(cep); } diff --git a/src/test/peerfinder/PeerFinder_test.cpp b/src/test/peerfinder/PeerFinder_test.cpp index c39564c54c..a787a38e14 100644 --- a/src/test/peerfinder/PeerFinder_test.cpp +++ b/src/test/peerfinder/PeerFinder_test.cpp @@ -411,7 +411,7 @@ public: (c.PEERS_MAX == max && c.PEERS_IN_MAX == 0 && c.PEERS_OUT_MAX == 0) || (c.PEERS_IN_MAX == *maxIn && c.PEERS_OUT_MAX == *maxOut)); - Config config = Config::makeConfig(c, port, false, 0); + Config const config = Config::makeConfig(c, port, false, 0); Counts counts; counts.onConfig(config); diff --git a/src/test/protocol/Hooks_test.cpp b/src/test/protocol/Hooks_test.cpp index a280fd6bd4..53f20a2b5e 100644 --- a/src/test/protocol/Hooks_test.cpp +++ b/src/test/protocol/Hooks_test.cpp @@ -23,7 +23,7 @@ class Hooks_test : public beast::unit_test::suite using namespace test::jtx; - std::vector> fields_to_test = { + std::vector> const fields_to_test = { sfHookResult, sfHookStateChangeCount, sfHookEmitCount, @@ -116,7 +116,7 @@ class Hooks_test : public beast::unit_test::suite } case STI_UINT256: { - uint256 u = uint256::fromVoid( + uint256 const u = uint256::fromVoid( "DEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBE" "EFDEADBEEF"); dummy.setFieldH256(f, u); @@ -126,7 +126,7 @@ class Hooks_test : public beast::unit_test::suite } case STI_VL: { - std::vector v{1, 2, 3}; + std::vector const v{1, 2, 3}; dummy.setFieldVL(f, v); BEAST_EXPECT(dummy.getFieldVL(f) == v); BEAST_EXPECT(dummy.isFieldPresent(f)); @@ -135,7 +135,8 @@ class Hooks_test : public beast::unit_test::suite case STI_ACCOUNT: { // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - AccountID id = *parseBase58("rwfSjJNK2YQuN64bSWn7T2eY9FJAyAPYJT"); + AccountID const id = + *parseBase58("rwfSjJNK2YQuN64bSWn7T2eY9FJAyAPYJT"); dummy.setAccountID(f, id); BEAST_EXPECT(dummy.getAccountID(f) == id); BEAST_EXPECT(dummy.isFieldPresent(f)); diff --git a/src/test/protocol/InnerObjectFormats_test.cpp b/src/test/protocol/InnerObjectFormats_test.cpp index c06524b90e..2961e90db7 100644 --- a/src/test/protocol/InnerObjectFormats_test.cpp +++ b/src/test/protocol/InnerObjectFormats_test.cpp @@ -155,7 +155,7 @@ public: using namespace InnerObjectFormatsUnitTestDetail; // Instantiate a jtx::Env so debugLog writes are exercised. - test::jtx::Env env(*this); + test::jtx::Env const env(*this); for (auto const& test : testArray) { @@ -166,7 +166,7 @@ public: Throw( "Internal InnerObjectFormatsParsedJSON error. Bad JSON."); } - STParsedJSONObject parsed("request", req); + STParsedJSONObject const parsed("request", req); bool const noObj = !parsed.object.has_value(); if (noObj == test.expectFail) { diff --git a/src/test/protocol/Issue_test.cpp b/src/test/protocol/Issue_test.cpp index 2321da4a6e..eddaf1c6d8 100644 --- a/src/test/protocol/Issue_test.cpp +++ b/src/test/protocol/Issue_test.cpp @@ -42,7 +42,7 @@ public: BEAST_EXPECT(u3 >= u2); BEAST_EXPECT(u3 > u2); - std::hash hash; + std::hash const hash; BEAST_EXPECT(hash(u1) == hash(u1)); BEAST_EXPECT(hash(u2) == hash(u2)); @@ -83,7 +83,7 @@ public: BEAST_EXPECT(Issue(c1, i3) >= Issue(c1, i2)); BEAST_EXPECT(Issue(c1, i3) > Issue(c1, i2)); - std::hash hash; + std::hash const hash; BEAST_EXPECT(hash(Issue(c1, i1)) == hash(Issue(c1, i1))); BEAST_EXPECT(hash(Issue(c1, i2)) == hash(Issue(c1, i2))); @@ -394,10 +394,10 @@ public: Currency const c3(3); AccountID const i3(3); - Issue a1(c1, i1); - Issue a2(c1, i2); - Issue a3(c2, i2); - Issue a4(c3, i2); + Issue const a1(c1, i1); + Issue const a2(c1, i2); + Issue const a3(c2, i2); + Issue const a4(c3, i2); uint256 const domain1{1}; uint256 const domain2{2}; @@ -477,7 +477,7 @@ public: BEAST_EXPECT(Book(a3, a4, domain2) > Book(a2, a3, domain1)); } - std::hash hash; + std::hash const hash; // log << std::hex << hash (Book (a1, a2)); // log << std::hex << hash (Book (a1, a2)); diff --git a/src/test/protocol/PublicKey_test.cpp b/src/test/protocol/PublicKey_test.cpp index 79c1356bb4..79ab589404 100644 --- a/src/test/protocol/PublicKey_test.cpp +++ b/src/test/protocol/PublicKey_test.cpp @@ -304,7 +304,7 @@ public: auto s = good; // Remove all characters from the string in random order: - std::hash r; + std::hash const r; while (!s.empty()) { @@ -421,7 +421,7 @@ public: KeyType::secp256k1, generateSecretKey(KeyType::secp256k1, generateSeed("masterpassphrase"))); - PublicKey pk2(pk1); + PublicKey const pk2(pk1); BEAST_EXPECT(pk1 == pk2); BEAST_EXPECT(pk2 == pk1); diff --git a/src/test/protocol/Quality_test.cpp b/src/test/protocol/Quality_test.cpp index 1dbbbfdf3d..f421f98c94 100644 --- a/src/test/protocol/Quality_test.cpp +++ b/src/test/protocol/Quality_test.cpp @@ -66,7 +66,7 @@ public: { // 1 in, 1 out: - Quality q(Amounts(amount(1), amount(1))); + Quality const q(Amounts(amount(1), amount(1))); ceil_in( q, @@ -95,7 +95,7 @@ public: { // 1 in, 2 out: - Quality q(Amounts(amount(1), amount(2))); + Quality const q(Amounts(amount(1), amount(2))); ceil_in( q, @@ -124,7 +124,7 @@ public: { // 2 in, 1 out: - Quality q(Amounts(amount(2), amount(1))); + Quality const q(Amounts(amount(2), amount(1))); ceil_in( q, @@ -159,7 +159,7 @@ public: { // 1 in, 1 out: - Quality q(Amounts(amount(1), amount(1))); + Quality const q(Amounts(amount(1), amount(1))); ceil_out( q, @@ -188,7 +188,7 @@ public: { // 1 in, 2 out: - Quality q(Amounts(amount(1), amount(2))); + Quality const q(Amounts(amount(1), amount(2))); ceil_out( q, @@ -217,7 +217,7 @@ public: { // 2 in, 1 out: - Quality q(Amounts(amount(2), amount(1))); + Quality const q(Amounts(amount(2), amount(1))); ceil_out( q, @@ -251,7 +251,7 @@ public: testcase("raw"); { - Quality q(0x5d048191fb9130daull); // 126836389.7680090 + Quality const q(0x5d048191fb9130daull); // 126836389.7680090 Amounts const value( amount(349469768), // 349.469768 XRP raw(2755280000000000ull, -15)); // 2.75528 @@ -266,7 +266,7 @@ public: { testcase("round"); - Quality q(0x59148191fb913522ull); // 57719.63525051682 + Quality const q(0x59148191fb913522ull); // 57719.63525051682 BEAST_EXPECT(q.round(3).rate().getText() == "57800"); BEAST_EXPECT(q.round(4).rate().getText() == "57720"); BEAST_EXPECT(q.round(5).rate().getText() == "57720"); diff --git a/src/test/protocol/STAmount_test.cpp b/src/test/protocol/STAmount_test.cpp index 4f652dddd9..2c2e005146 100644 --- a/src/test/protocol/STAmount_test.cpp +++ b/src/test/protocol/STAmount_test.cpp @@ -28,7 +28,7 @@ public: return amount; std::uint64_t mantissa = amount.mantissa(); - std::uint64_t valueDigits = mantissa % 1000000000; + std::uint64_t const valueDigits = mantissa % 1000000000; if (valueDigits == 1) { @@ -67,15 +67,15 @@ public: roundTest(int n, int d, int m) { // check STAmount rounding - STAmount num(noIssue(), n); - STAmount den(noIssue(), d); - STAmount mul(noIssue(), m); - STAmount quot = divide(STAmount(n), STAmount(d), noIssue()); - STAmount res = roundSelf(multiply(quot, mul, noIssue())); + STAmount const num(noIssue(), n); + STAmount const den(noIssue(), d); + STAmount const mul(noIssue(), m); + STAmount const quot = divide(STAmount(n), STAmount(d), noIssue()); + STAmount const res = roundSelf(multiply(quot, mul, noIssue())); BEAST_EXPECT(!res.native()); - STAmount cmp(noIssue(), (n * m) / d); + STAmount const cmp(noIssue(), (n * m) / d); BEAST_EXPECT(!cmp.native()); @@ -93,13 +93,14 @@ public: void mulTest(int a, int b) { - STAmount aa(noIssue(), a); - STAmount bb(noIssue(), b); - STAmount prod1(multiply(aa, bb, noIssue())); + STAmount const aa(noIssue(), a); + STAmount const bb(noIssue(), b); + STAmount const prod1(multiply(aa, bb, noIssue())); BEAST_EXPECT(!prod1.native()); - STAmount prod2(noIssue(), static_cast(a) * static_cast(b)); + STAmount const prod2( + noIssue(), static_cast(a) * static_cast(b)); if (prod1 != prod2) { @@ -196,7 +197,11 @@ public: testNativeCurrency() { testcase("native currency"); - STAmount zeroSt, one(1), hundred(100); + + STAmount const zeroSt; + STAmount const one(1); + STAmount const hundred(100); + // VFALCO NOTE Why repeat "STAmount fail" so many times?? unexpected(serializeAndDeserialize(zeroSt) != zeroSt, "STAmount fail"); unexpected(serializeAndDeserialize(one) != one, "STAmount fail"); @@ -206,60 +211,60 @@ public: unexpected(zeroSt != beast::zero, "STAmount fail"); unexpected(one == beast::zero, "STAmount fail"); unexpected(hundred == beast::zero, "STAmount fail"); - unexpected((zeroSt < zeroSt), "STAmount fail"); + unexpected((zeroSt < zeroSt), "STAmount fail"); // NOLINT(misc-redundant-expression) unexpected(!(zeroSt < one), "STAmount fail"); unexpected(!(zeroSt < hundred), "STAmount fail"); unexpected((one < zeroSt), "STAmount fail"); - unexpected((one < one), "STAmount fail"); + unexpected((one < one), "STAmount fail"); // NOLINT(misc-redundant-expression) unexpected(!(one < hundred), "STAmount fail"); unexpected((hundred < zeroSt), "STAmount fail"); unexpected((hundred < one), "STAmount fail"); - unexpected((hundred < hundred), "STAmount fail"); - unexpected((zeroSt > zeroSt), "STAmount fail"); + unexpected((hundred < hundred), "STAmount fail"); // NOLINT(misc-redundant-expression) + unexpected((zeroSt > zeroSt), "STAmount fail"); // NOLINT(misc-redundant-expression) unexpected((zeroSt > one), "STAmount fail"); unexpected((zeroSt > hundred), "STAmount fail"); unexpected(!(one > zeroSt), "STAmount fail"); - unexpected((one > one), "STAmount fail"); + unexpected((one > one), "STAmount fail"); // NOLINT(misc-redundant-expression) unexpected((one > hundred), "STAmount fail"); unexpected(!(hundred > zeroSt), "STAmount fail"); unexpected(!(hundred > one), "STAmount fail"); - unexpected((hundred > hundred), "STAmount fail"); - unexpected(!(zeroSt <= zeroSt), "STAmount fail"); + unexpected((hundred > hundred), "STAmount fail"); // NOLINT(misc-redundant-expression) + unexpected(!(zeroSt <= zeroSt), "STAmount fail"); // NOLINT(misc-redundant-expression) unexpected(!(zeroSt <= one), "STAmount fail"); unexpected(!(zeroSt <= hundred), "STAmount fail"); unexpected((one <= zeroSt), "STAmount fail"); - unexpected(!(one <= one), "STAmount fail"); + unexpected(!(one <= one), "STAmount fail"); // NOLINT(misc-redundant-expression) unexpected(!(one <= hundred), "STAmount fail"); unexpected((hundred <= zeroSt), "STAmount fail"); unexpected((hundred <= one), "STAmount fail"); - unexpected(!(hundred <= hundred), "STAmount fail"); - unexpected(!(zeroSt >= zeroSt), "STAmount fail"); + unexpected(!(hundred <= hundred), "STAmount fail"); // NOLINT(misc-redundant-expression) + unexpected(!(zeroSt >= zeroSt), "STAmount fail"); // NOLINT(misc-redundant-expression) unexpected((zeroSt >= one), "STAmount fail"); unexpected((zeroSt >= hundred), "STAmount fail"); unexpected(!(one >= zeroSt), "STAmount fail"); - unexpected(!(one >= one), "STAmount fail"); + unexpected(!(one >= one), "STAmount fail"); // NOLINT(misc-redundant-expression) unexpected((one >= hundred), "STAmount fail"); unexpected(!(hundred >= zeroSt), "STAmount fail"); unexpected(!(hundred >= one), "STAmount fail"); - unexpected(!(hundred >= hundred), "STAmount fail"); - unexpected(!(zeroSt == zeroSt), "STAmount fail"); + unexpected(!(hundred >= hundred), "STAmount fail"); // NOLINT(misc-redundant-expression) + unexpected(!(zeroSt == zeroSt), "STAmount fail"); // NOLINT(misc-redundant-expression) unexpected((zeroSt == one), "STAmount fail"); unexpected((zeroSt == hundred), "STAmount fail"); unexpected((one == zeroSt), "STAmount fail"); - unexpected(!(one == one), "STAmount fail"); + unexpected(!(one == one), "STAmount fail"); // NOLINT(misc-redundant-expression) unexpected((one == hundred), "STAmount fail"); unexpected((hundred == zeroSt), "STAmount fail"); unexpected((hundred == one), "STAmount fail"); - unexpected(!(hundred == hundred), "STAmount fail"); - unexpected((zeroSt != zeroSt), "STAmount fail"); + unexpected(!(hundred == hundred), "STAmount fail"); // NOLINT(misc-redundant-expression) + unexpected((zeroSt != zeroSt), "STAmount fail"); // NOLINT(misc-redundant-expression) unexpected(!(zeroSt != one), "STAmount fail"); unexpected(!(zeroSt != hundred), "STAmount fail"); unexpected(!(one != zeroSt), "STAmount fail"); - unexpected((one != one), "STAmount fail"); + unexpected((one != one), "STAmount fail"); // NOLINT(misc-redundant-expression) unexpected(!(one != hundred), "STAmount fail"); unexpected(!(hundred != zeroSt), "STAmount fail"); unexpected(!(hundred != one), "STAmount fail"); - unexpected((hundred != hundred), "STAmount fail"); + unexpected((hundred != hundred), "STAmount fail"); // NOLINT(misc-redundant-expression) unexpected(STAmount().getText() != "0", "STAmount fail"); unexpected(STAmount(31).getText() != "31", "STAmount fail"); unexpected(STAmount(310).getText() != "310", "STAmount fail"); @@ -279,7 +284,11 @@ public: testCustomCurrency() { testcase("custom currency"); - STAmount zeroSt(noIssue()), one(noIssue(), 1), hundred(noIssue(), 100); + + STAmount const zeroSt(noIssue()); + STAmount const one(noIssue(), 1); + STAmount const hundred(noIssue(), 100); + unexpected(serializeAndDeserialize(zeroSt) != zeroSt, "STAmount fail"); unexpected(serializeAndDeserialize(one) != one, "STAmount fail"); unexpected(serializeAndDeserialize(hundred) != hundred, "STAmount fail"); @@ -288,60 +297,60 @@ public: unexpected(zeroSt != beast::zero, "STAmount fail"); unexpected(one == beast::zero, "STAmount fail"); unexpected(hundred == beast::zero, "STAmount fail"); - unexpected((zeroSt < zeroSt), "STAmount fail"); + unexpected((zeroSt < zeroSt), "STAmount fail"); // NOLINT(misc-redundant-expression) unexpected(!(zeroSt < one), "STAmount fail"); unexpected(!(zeroSt < hundred), "STAmount fail"); unexpected((one < zeroSt), "STAmount fail"); - unexpected((one < one), "STAmount fail"); + unexpected((one < one), "STAmount fail"); // NOLINT(misc-redundant-expression) unexpected(!(one < hundred), "STAmount fail"); unexpected((hundred < zeroSt), "STAmount fail"); unexpected((hundred < one), "STAmount fail"); - unexpected((hundred < hundred), "STAmount fail"); - unexpected((zeroSt > zeroSt), "STAmount fail"); + unexpected((hundred < hundred), "STAmount fail"); // NOLINT(misc-redundant-expression) + unexpected((zeroSt > zeroSt), "STAmount fail"); // NOLINT(misc-redundant-expression) unexpected((zeroSt > one), "STAmount fail"); unexpected((zeroSt > hundred), "STAmount fail"); unexpected(!(one > zeroSt), "STAmount fail"); - unexpected((one > one), "STAmount fail"); + unexpected((one > one), "STAmount fail"); // NOLINT(misc-redundant-expression) unexpected((one > hundred), "STAmount fail"); unexpected(!(hundred > zeroSt), "STAmount fail"); unexpected(!(hundred > one), "STAmount fail"); - unexpected((hundred > hundred), "STAmount fail"); - unexpected(!(zeroSt <= zeroSt), "STAmount fail"); + unexpected((hundred > hundred), "STAmount fail"); // NOLINT(misc-redundant-expression) + unexpected(!(zeroSt <= zeroSt), "STAmount fail"); // NOLINT(misc-redundant-expression) unexpected(!(zeroSt <= one), "STAmount fail"); unexpected(!(zeroSt <= hundred), "STAmount fail"); unexpected((one <= zeroSt), "STAmount fail"); - unexpected(!(one <= one), "STAmount fail"); + unexpected(!(one <= one), "STAmount fail"); // NOLINT(misc-redundant-expression) unexpected(!(one <= hundred), "STAmount fail"); unexpected((hundred <= zeroSt), "STAmount fail"); unexpected((hundred <= one), "STAmount fail"); - unexpected(!(hundred <= hundred), "STAmount fail"); - unexpected(!(zeroSt >= zeroSt), "STAmount fail"); + unexpected(!(hundred <= hundred), "STAmount fail"); // NOLINT(misc-redundant-expression) + unexpected(!(zeroSt >= zeroSt), "STAmount fail"); // NOLINT(misc-redundant-expression) unexpected((zeroSt >= one), "STAmount fail"); unexpected((zeroSt >= hundred), "STAmount fail"); unexpected(!(one >= zeroSt), "STAmount fail"); - unexpected(!(one >= one), "STAmount fail"); + unexpected(!(one >= one), "STAmount fail"); // NOLINT(misc-redundant-expression) unexpected((one >= hundred), "STAmount fail"); unexpected(!(hundred >= zeroSt), "STAmount fail"); unexpected(!(hundred >= one), "STAmount fail"); - unexpected(!(hundred >= hundred), "STAmount fail"); - unexpected(!(zeroSt == zeroSt), "STAmount fail"); + unexpected(!(hundred >= hundred), "STAmount fail"); // NOLINT(misc-redundant-expression) + unexpected(!(zeroSt == zeroSt), "STAmount fail"); // NOLINT(misc-redundant-expression) unexpected((zeroSt == one), "STAmount fail"); unexpected((zeroSt == hundred), "STAmount fail"); unexpected((one == zeroSt), "STAmount fail"); - unexpected(!(one == one), "STAmount fail"); + unexpected(!(one == one), "STAmount fail"); // NOLINT(misc-redundant-expression) unexpected((one == hundred), "STAmount fail"); unexpected((hundred == zeroSt), "STAmount fail"); unexpected((hundred == one), "STAmount fail"); - unexpected(!(hundred == hundred), "STAmount fail"); - unexpected((zeroSt != zeroSt), "STAmount fail"); + unexpected(!(hundred == hundred), "STAmount fail"); // NOLINT(misc-redundant-expression) + unexpected((zeroSt != zeroSt), "STAmount fail"); // NOLINT(misc-redundant-expression) unexpected(!(zeroSt != one), "STAmount fail"); unexpected(!(zeroSt != hundred), "STAmount fail"); unexpected(!(one != zeroSt), "STAmount fail"); - unexpected((one != one), "STAmount fail"); + unexpected((one != one), "STAmount fail"); // NOLINT(misc-redundant-expression) unexpected(!(one != hundred), "STAmount fail"); unexpected(!(hundred != zeroSt), "STAmount fail"); unexpected(!(hundred != one), "STAmount fail"); - unexpected((hundred != hundred), "STAmount fail"); + unexpected((hundred != hundred), "STAmount fail"); // NOLINT(misc-redundant-expression) unexpected(STAmount(noIssue()).getText() != "0", "STAmount fail"); unexpected(STAmount(noIssue(), 31).getText() != "31", "STAmount fail"); unexpected(STAmount(noIssue(), 31, 1).getText() != "310", "STAmount fail"); @@ -382,7 +391,8 @@ public: divide(STAmount(noIssue(), 60), STAmount(noIssue(), 3), xrpIssue()).getText() != "20", "STAmount divide fail"); - STAmount a1(noIssue(), 60), a2(noIssue(), 10, -1); + STAmount const a1(noIssue(), 60); + STAmount const a2(noIssue(), 10, -1); unexpected( divide(a2, a1, noIssue()) != amountFromQuality(getRate(a1, a2)), @@ -464,14 +474,14 @@ public: { testcase("underflow"); - STAmount bigNative(STAmount::cMaxNative / 2); - STAmount bigValue( + STAmount const bigNative(STAmount::cMaxNative / 2); + STAmount const bigValue( noIssue(), (STAmount::cMinValue + STAmount::cMaxValue) / 2, STAmount::cMaxOffset - 1); - STAmount smallValue( + STAmount const smallValue( noIssue(), (STAmount::cMinValue + STAmount::cMaxValue) / 2, STAmount::cMinOffset + 1); - STAmount zeroSt(noIssue(), 0); + STAmount const zeroSt(noIssue(), 0); - STAmount smallXSmall = multiply(smallValue, smallValue, noIssue()); + STAmount const smallXSmall = multiply(smallValue, smallValue, noIssue()); BEAST_EXPECT(smallXSmall == beast::zero); @@ -822,43 +832,43 @@ public: // Adding zero { - STAmount amt1(XRPAmount(0)); - STAmount amt2(XRPAmount(1000)); + STAmount const amt1(XRPAmount(0)); + STAmount const amt2(XRPAmount(1000)); BEAST_EXPECT(canAdd(amt1, amt2) == true); } // Adding zero { - STAmount amt1(XRPAmount(1000)); - STAmount amt2(XRPAmount(0)); + STAmount const amt1(XRPAmount(1000)); + STAmount const amt2(XRPAmount(0)); BEAST_EXPECT(canAdd(amt1, amt2) == true); } // Adding two positive XRP amounts { - STAmount amt1(XRPAmount(500)); - STAmount amt2(XRPAmount(1500)); + STAmount const amt1(XRPAmount(500)); + STAmount const amt2(XRPAmount(1500)); BEAST_EXPECT(canAdd(amt1, amt2) == true); } // Adding two negative XRP amounts { - STAmount amt1(XRPAmount(-500)); - STAmount amt2(XRPAmount(-1500)); + STAmount const amt1(XRPAmount(-500)); + STAmount const amt2(XRPAmount(-1500)); BEAST_EXPECT(canAdd(amt1, amt2) == true); } // Adding a positive and a negative XRP amount { - STAmount amt1(XRPAmount(1000)); - STAmount amt2(XRPAmount(-1000)); + STAmount const amt1(XRPAmount(1000)); + STAmount const amt2(XRPAmount(-1000)); BEAST_EXPECT(canAdd(amt1, amt2) == true); } // Overflow check for max XRP amounts { - STAmount amt1(std::numeric_limits::max()); - STAmount amt2(XRPAmount(1)); + STAmount const amt1(std::numeric_limits::max()); + STAmount const amt2(XRPAmount(1)); BEAST_EXPECT(canAdd(amt1, amt2) == false); } @@ -866,7 +876,7 @@ public: { STAmount amt1(std::numeric_limits::max()); amt1 += XRPAmount(1); - STAmount amt2(XRPAmount(-1)); + STAmount const amt2(XRPAmount(-1)); BEAST_EXPECT(canAdd(amt1, amt2) == false); } } @@ -881,50 +891,50 @@ public: // Adding two IOU amounts { - STAmount amt1(usd, 500); - STAmount amt2(usd, 1500); + STAmount const amt1(usd, 500); + STAmount const amt2(usd, 1500); BEAST_EXPECT(canAdd(amt1, amt2) == true); } // Adding a positive and a negative IOU amount { - STAmount amt1(usd, 1000); - STAmount amt2(usd, -1000); + STAmount const amt1(usd, 1000); + STAmount const amt2(usd, -1000); BEAST_EXPECT(canAdd(amt1, amt2) == true); } // Overflow check for max IOU amounts { - STAmount amt1(usd, std::numeric_limits::max()); - STAmount amt2(usd, 1); + STAmount const amt1(usd, std::numeric_limits::max()); + STAmount const amt2(usd, 1); BEAST_EXPECT(canAdd(amt1, amt2) == false); } // Overflow check for min IOU amounts { - STAmount amt1(usd, std::numeric_limits::min()); - STAmount amt2(usd, -1); + STAmount const amt1(usd, std::numeric_limits::min()); + STAmount const amt2(usd, -1); BEAST_EXPECT(canAdd(amt1, amt2) == false); } // Adding XRP and IOU { - STAmount amt1(XRPAmount(1)); - STAmount amt2(usd, 1); + STAmount const amt1(XRPAmount(1)); + STAmount const amt2(usd, 1); BEAST_EXPECT(canAdd(amt1, amt2) == false); } // Adding different IOU issues (non zero) { - STAmount amt1(usd, 1000); - STAmount amt2(eur, 500); + STAmount const amt1(usd, 1000); + STAmount const amt2(eur, 500); BEAST_EXPECT(canAdd(amt1, amt2) == false); } // Adding different IOU issues (zero) { - STAmount amt1(usd, 0); - STAmount amt2(eur, 500); + STAmount const amt1(usd, 0); + STAmount const amt2(eur, 500); BEAST_EXPECT(canAdd(amt1, amt2) == false); } } @@ -939,43 +949,43 @@ public: // Adding zero { - STAmount amt1(mpt, 0); - STAmount amt2(mpt, 1000); + STAmount const amt1(mpt, 0); + STAmount const amt2(mpt, 1000); BEAST_EXPECT(canAdd(amt1, amt2) == true); } // Adding zero { - STAmount amt1(mpt, 1000); - STAmount amt2(mpt, 0); + STAmount const amt1(mpt, 1000); + STAmount const amt2(mpt, 0); BEAST_EXPECT(canAdd(amt1, amt2) == true); } // Adding two positive MPT amounts { - STAmount amt1(mpt, 500); - STAmount amt2(mpt, 1500); + STAmount const amt1(mpt, 500); + STAmount const amt2(mpt, 1500); BEAST_EXPECT(canAdd(amt1, amt2) == true); } // Adding two negative MPT amounts { - STAmount amt1(mpt, -500); - STAmount amt2(mpt, -1500); + STAmount const amt1(mpt, -500); + STAmount const amt2(mpt, -1500); BEAST_EXPECT(canAdd(amt1, amt2) == true); } // Adding a positive and a negative MPT amount { - STAmount amt1(mpt, 1000); - STAmount amt2(mpt, -1000); + STAmount const amt1(mpt, 1000); + STAmount const amt2(mpt, -1000); BEAST_EXPECT(canAdd(amt1, amt2) == true); } // Overflow check for max MPT amounts { - STAmount amt1(mpt, std::numeric_limits::max()); - STAmount amt2(mpt, 1); + STAmount const amt1(mpt, std::numeric_limits::max()); + STAmount const amt2(mpt, 1); BEAST_EXPECT(canAdd(amt1, amt2) == false); } @@ -985,22 +995,22 @@ public: // Adding MPT and XRP { - STAmount amt1(XRPAmount(1000)); - STAmount amt2(mpt, 1000); + STAmount const amt1(XRPAmount(1000)); + STAmount const amt2(mpt, 1000); BEAST_EXPECT(canAdd(amt1, amt2) == false); } // Adding different MPT issues (non zero) { - STAmount amt1(mpt2, 500); - STAmount amt2(mpt, 500); + STAmount const amt1(mpt2, 500); + STAmount const amt2(mpt, 500); BEAST_EXPECT(canAdd(amt1, amt2) == false); } // Adding different MPT issues (non zero) { - STAmount amt1(mpt2, 0); - STAmount amt2(mpt, 500); + STAmount const amt1(mpt2, 0); + STAmount const amt2(mpt, 500); BEAST_EXPECT(canAdd(amt1, amt2) == false); } } @@ -1012,36 +1022,36 @@ public: // Subtracting zero { - STAmount amt1(XRPAmount(1000)); - STAmount amt2(XRPAmount(0)); + STAmount const amt1(XRPAmount(1000)); + STAmount const amt2(XRPAmount(0)); BEAST_EXPECT(canSubtract(amt1, amt2) == true); } // Subtracting zero { - STAmount amt1(XRPAmount(0)); - STAmount amt2(XRPAmount(1000)); + STAmount const amt1(XRPAmount(0)); + STAmount const amt2(XRPAmount(1000)); BEAST_EXPECT(canSubtract(amt1, amt2) == false); } // Subtracting two positive XRP amounts { - STAmount amt1(XRPAmount(1500)); - STAmount amt2(XRPAmount(500)); + STAmount const amt1(XRPAmount(1500)); + STAmount const amt2(XRPAmount(500)); BEAST_EXPECT(canSubtract(amt1, amt2) == true); } // Subtracting two negative XRP amounts { - STAmount amt1(XRPAmount(-1500)); - STAmount amt2(XRPAmount(-500)); + STAmount const amt1(XRPAmount(-1500)); + STAmount const amt2(XRPAmount(-500)); BEAST_EXPECT(canSubtract(amt1, amt2) == true); } // Subtracting a positive and a negative XRP amount { - STAmount amt1(XRPAmount(1000)); - STAmount amt2(XRPAmount(-1000)); + STAmount const amt1(XRPAmount(1000)); + STAmount const amt2(XRPAmount(-1000)); BEAST_EXPECT(canSubtract(amt1, amt2) == true); } @@ -1049,14 +1059,14 @@ public: { STAmount amt1(std::numeric_limits::max()); amt1 += XRPAmount(1); - STAmount amt2(XRPAmount(1)); + STAmount const amt2(XRPAmount(1)); BEAST_EXPECT(canSubtract(amt1, amt2) == false); } // Overflow check for max XRP amounts { - STAmount amt1(std::numeric_limits::max()); - STAmount amt2(XRPAmount(-1)); + STAmount const amt1(std::numeric_limits::max()); + STAmount const amt2(XRPAmount(-1)); BEAST_EXPECT(canSubtract(amt1, amt2) == false); } } @@ -1070,29 +1080,29 @@ public: // Subtracting two IOU amounts { - STAmount amt1(usd, 1500); - STAmount amt2(usd, 500); + STAmount const amt1(usd, 1500); + STAmount const amt2(usd, 500); BEAST_EXPECT(canSubtract(amt1, amt2) == true); } // Subtracting XRP and IOU { - STAmount amt1(XRPAmount(1000)); - STAmount amt2(usd, 1000); + STAmount const amt1(XRPAmount(1000)); + STAmount const amt2(usd, 1000); BEAST_EXPECT(canSubtract(amt1, amt2) == false); } // Subtracting different IOU issues (non zero) { - STAmount amt1(usd, 1000); - STAmount amt2(eur, 500); + STAmount const amt1(usd, 1000); + STAmount const amt2(eur, 500); BEAST_EXPECT(canSubtract(amt1, amt2) == false); } // Subtracting different IOU issues (zero) { - STAmount amt1(usd, 0); - STAmount amt2(eur, 500); + STAmount const amt1(usd, 0); + STAmount const amt2(eur, 500); BEAST_EXPECT(canSubtract(amt1, amt2) == false); } } @@ -1107,36 +1117,36 @@ public: // Subtracting zero { - STAmount amt1(mpt, 1000); - STAmount amt2(mpt, 0); + STAmount const amt1(mpt, 1000); + STAmount const amt2(mpt, 0); BEAST_EXPECT(canSubtract(amt1, amt2) == true); } // Subtracting zero { - STAmount amt1(mpt, 0); - STAmount amt2(mpt, 1000); + STAmount const amt1(mpt, 0); + STAmount const amt2(mpt, 1000); BEAST_EXPECT(canSubtract(amt1, amt2) == false); } // Subtracting two positive MPT amounts { - STAmount amt1(mpt, 1500); - STAmount amt2(mpt, 500); + STAmount const amt1(mpt, 1500); + STAmount const amt2(mpt, 500); BEAST_EXPECT(canSubtract(amt1, amt2) == true); } // Subtracting two negative MPT amounts { - STAmount amt1(mpt, -1500); - STAmount amt2(mpt, -500); + STAmount const amt1(mpt, -1500); + STAmount const amt2(mpt, -500); BEAST_EXPECT(canSubtract(amt1, amt2) == true); } // Subtracting a positive and a negative MPT amount { - STAmount amt1(mpt, 1000); - STAmount amt2(mpt, -1000); + STAmount const amt1(mpt, 1000); + STAmount const amt2(mpt, -1000); BEAST_EXPECT(canSubtract(amt1, amt2) == true); } @@ -1146,29 +1156,29 @@ public: // Overflow check for max positive MPT amounts (should fail) { - STAmount amt1(mpt, std::numeric_limits::max()); - STAmount amt2(mpt, -2); + STAmount const amt1(mpt, std::numeric_limits::max()); + STAmount const amt2(mpt, -2); BEAST_EXPECT(canSubtract(amt1, amt2) == false); } // Subtracting MPT and XRP { - STAmount amt1(XRPAmount(1000)); - STAmount amt2(mpt, 1000); + STAmount const amt1(XRPAmount(1000)); + STAmount const amt2(mpt, 1000); BEAST_EXPECT(canSubtract(amt1, amt2) == false); } // Subtracting different MPT issues (non zero) { - STAmount amt1(mpt, 1000); - STAmount amt2(mpt2, 500); + STAmount const amt1(mpt, 1000); + STAmount const amt2(mpt2, 500); BEAST_EXPECT(canSubtract(amt1, amt2) == false); } // Subtracting different MPT issues (zero) { - STAmount amt1(mpt, 0); - STAmount amt2(mpt2, 500); + STAmount const amt1(mpt, 0); + STAmount const amt2(mpt2, 500); BEAST_EXPECT(canSubtract(amt1, amt2) == false); } } diff --git a/src/test/protocol/STInteger_test.cpp b/src/test/protocol/STInteger_test.cpp index 937dbd1a7f..4a0204d349 100644 --- a/src/test/protocol/STInteger_test.cpp +++ b/src/test/protocol/STInteger_test.cpp @@ -12,14 +12,14 @@ struct STInteger_test : public beast::unit_test::suite testUInt8() { testcase("UInt8"); - STUInt8 u8(255); + STUInt8 const u8(255); BEAST_EXPECT(u8.value() == 255); BEAST_EXPECT(u8.getText() == "255"); BEAST_EXPECT(u8.getSType() == STI_UINT8); BEAST_EXPECT(u8.getJson(JsonOptions::none) == 255); // there is some special handling for sfTransactionResult - STUInt8 tr(sfTransactionResult, 0); + STUInt8 const tr(sfTransactionResult, 0); BEAST_EXPECT(tr.value() == 0); BEAST_EXPECT( tr.getText() == "The transaction was applied. Only final in a validated ledger."); @@ -27,7 +27,7 @@ struct STInteger_test : public beast::unit_test::suite BEAST_EXPECT(tr.getJson(JsonOptions::none) == "tesSUCCESS"); // invalid transaction result - STUInt8 tr2(sfTransactionResult, 255); + STUInt8 const tr2(sfTransactionResult, 255); BEAST_EXPECT(tr2.value() == 255); BEAST_EXPECT(tr2.getText() == "255"); BEAST_EXPECT(tr2.getSType() == STI_UINT8); @@ -38,21 +38,21 @@ struct STInteger_test : public beast::unit_test::suite testUInt16() { testcase("UInt16"); - STUInt16 u16(65535); + STUInt16 const u16(65535); BEAST_EXPECT(u16.value() == 65535); BEAST_EXPECT(u16.getText() == "65535"); BEAST_EXPECT(u16.getSType() == STI_UINT16); BEAST_EXPECT(u16.getJson(JsonOptions::none) == 65535); // there is some special handling for sfLedgerEntryType - STUInt16 let(sfLedgerEntryType, ltACCOUNT_ROOT); + STUInt16 const let(sfLedgerEntryType, ltACCOUNT_ROOT); BEAST_EXPECT(let.value() == ltACCOUNT_ROOT); BEAST_EXPECT(let.getText() == "AccountRoot"); BEAST_EXPECT(let.getSType() == STI_UINT16); BEAST_EXPECT(let.getJson(JsonOptions::none) == "AccountRoot"); // there is some special handling for sfTransactionType - STUInt16 tlt(sfTransactionType, ttPAYMENT); + STUInt16 const tlt(sfTransactionType, ttPAYMENT); BEAST_EXPECT(tlt.value() == ttPAYMENT); BEAST_EXPECT(tlt.getText() == "Payment"); BEAST_EXPECT(tlt.getSType() == STI_UINT16); @@ -63,19 +63,19 @@ struct STInteger_test : public beast::unit_test::suite testUInt32() { testcase("UInt32"); - STUInt32 u32(4'294'967'295u); + STUInt32 const u32(4'294'967'295u); BEAST_EXPECT(u32.value() == 4'294'967'295u); BEAST_EXPECT(u32.getText() == "4294967295"); BEAST_EXPECT(u32.getSType() == STI_UINT32); BEAST_EXPECT(u32.getJson(JsonOptions::none) == 4'294'967'295u); // there is some special handling for sfPermissionValue - STUInt32 pv(sfPermissionValue, ttPAYMENT + 1); + STUInt32 const pv(sfPermissionValue, ttPAYMENT + 1); BEAST_EXPECT(pv.value() == ttPAYMENT + 1); BEAST_EXPECT(pv.getText() == "Payment"); BEAST_EXPECT(pv.getSType() == STI_UINT32); BEAST_EXPECT(pv.getJson(JsonOptions::none) == "Payment"); - STUInt32 pv2(sfPermissionValue, PaymentMint); + STUInt32 const pv2(sfPermissionValue, PaymentMint); BEAST_EXPECT(pv2.value() == PaymentMint); BEAST_EXPECT(pv2.getText() == "PaymentMint"); BEAST_EXPECT(pv2.getSType() == STI_UINT32); @@ -86,7 +86,7 @@ struct STInteger_test : public beast::unit_test::suite testUInt64() { testcase("UInt64"); - STUInt64 u64(0xFFFFFFFFFFFFFFFFull); + STUInt64 const u64(0xFFFFFFFFFFFFFFFFull); BEAST_EXPECT(u64.value() == 0xFFFFFFFFFFFFFFFFull); BEAST_EXPECT(u64.getText() == "18446744073709551615"); BEAST_EXPECT(u64.getSType() == STI_UINT64); @@ -96,7 +96,7 @@ struct STInteger_test : public beast::unit_test::suite BEAST_EXPECT(jsonVal.isString()); BEAST_EXPECT(jsonVal.asString() == "ffffffffffffffff"); - STUInt64 u64_2(sfMaximumAmount, 0xFFFFFFFFFFFFFFFFull); + STUInt64 const u64_2(sfMaximumAmount, 0xFFFFFFFFFFFFFFFFull); BEAST_EXPECT(u64_2.value() == 0xFFFFFFFFFFFFFFFFull); BEAST_EXPECT(u64_2.getText() == "18446744073709551615"); BEAST_EXPECT(u64_2.getSType() == STI_UINT64); @@ -109,7 +109,7 @@ struct STInteger_test : public beast::unit_test::suite testcase("Int32"); { int const minInt32 = -2147483648; - STInt32 i32(minInt32); + STInt32 const i32(minInt32); BEAST_EXPECT(i32.value() == minInt32); BEAST_EXPECT(i32.getText() == "-2147483648"); BEAST_EXPECT(i32.getSType() == STI_INT32); @@ -118,7 +118,7 @@ struct STInteger_test : public beast::unit_test::suite { int const maxInt32 = 2147483647; - STInt32 i32(maxInt32); + STInt32 const i32(maxInt32); BEAST_EXPECT(i32.value() == maxInt32); BEAST_EXPECT(i32.getText() == "2147483647"); BEAST_EXPECT(i32.getSType() == STI_INT32); diff --git a/src/test/protocol/STIssue_test.cpp b/src/test/protocol/STIssue_test.cpp index 7e6fe5487c..2ffdb1d9af 100644 --- a/src/test/protocol/STIssue_test.cpp +++ b/src/test/protocol/STIssue_test.cpp @@ -22,7 +22,7 @@ public: { issue = xrpIssue(); issue.account = alice; - STIssue stissue(sfAsset, Asset{issue}); + STIssue const stissue(sfAsset, Asset{issue}); fail("Inconsistent XRP Issue doesn't fail"); } catch (...) @@ -34,7 +34,7 @@ public: { issue = USD; issue.account = xrpAccount(); - STIssue stissue(sfAsset, Asset{issue}); + STIssue const stissue(sfAsset, Asset{issue}); fail("Inconsistent IOU Issue doesn't fail"); } catch (...) @@ -51,7 +51,7 @@ public: base_uint<320> uint; (void)uint.parseHex(data); SerialIter iter(Slice(uint.data(), uint.size())); - STIssue stissue(iter, sfAsset); + STIssue const stissue(iter, sfAsset); fail("Inconsistent IOU Issue doesn't fail on serializer"); } catch (...) @@ -61,7 +61,7 @@ public: try { - STIssue stissue(sfAsset, Asset{xrpIssue()}); + STIssue const stissue(sfAsset, Asset{xrpIssue()}); } catch (...) { @@ -70,7 +70,7 @@ public: try { - STIssue stissue(sfAsset, Asset{USD}); + STIssue const stissue(sfAsset, Asset{USD}); } catch (...) { @@ -85,7 +85,7 @@ public: base_uint<320> uint; (void)uint.parseHex(data); SerialIter iter(Slice(uint.data(), uint.size())); - STIssue stissue(iter, sfAsset); + STIssue const stissue(iter, sfAsset); BEAST_EXPECT(stissue.value() == USD); } catch (...) @@ -99,7 +99,7 @@ public: base_uint<160> uint; (void)uint.parseHex(data); SerialIter iter(Slice(uint.data(), uint.size())); - STIssue stissue(iter, sfAsset); + STIssue const stissue(iter, sfAsset); BEAST_EXPECT(stissue.value() == xrpCurrency()); } catch (...) diff --git a/src/test/protocol/STNumber_test.cpp b/src/test/protocol/STNumber_test.cpp index 9d43ace638..3b794b23b5 100644 --- a/src/test/protocol/STNumber_test.cpp +++ b/src/test/protocol/STNumber_test.cpp @@ -45,19 +45,19 @@ struct STNumber_test : public beast::unit_test::suite 0, 1, std::numeric_limits::max()}; - for (std::int64_t mantissa : mantissas) + for (std::int64_t const mantissa : mantissas) testCombo(Number{mantissa}); std::initializer_list const exponents = { Number::minExponent, -1, 0, 1, Number::maxExponent - 1}; - for (std::int32_t exponent : exponents) + for (std::int32_t const exponent : exponents) testCombo(Number{123, exponent}); { STAmount const strikePrice{noIssue(), 100}; STNumber const factor{sfNumber, 100}; auto const iouValue = strikePrice.iou(); - IOUAmount totalValue{iouValue * factor}; + IOUAmount const totalValue{iouValue * factor}; STAmount const totalAmount{totalValue, strikePrice.issue()}; BEAST_EXPECT(totalAmount == Number{10'000}); } @@ -95,7 +95,7 @@ struct STNumber_test : public beast::unit_test::suite BEAST_EXPECT(numberFromJson(sfNumber, "-0.000e6") == STNumber(sfNumber, 0)); { - NumberRoundModeGuard mg(Number::towards_zero); + NumberRoundModeGuard const mg(Number::towards_zero); // maxint64 9,223,372,036,854,775,807 auto const maxInt = std::to_string(std::numeric_limits::max()); // minint64 -9,223,372,036,854,775,808 @@ -276,7 +276,7 @@ struct STNumber_test : public beast::unit_test::suite for (auto const scale : {MantissaRange::small, MantissaRange::large}) { - NumberMantissaScaleGuard sg(scale); + NumberMantissaScaleGuard const sg(scale); testcase << to_string(Number::getMantissaScale()); doRun(); } diff --git a/src/test/protocol/STObject_test.cpp b/src/test/protocol/STObject_test.cpp index 0faa1946a9..135c577fb4 100644 --- a/src/test/protocol/STObject_test.cpp +++ b/src/test/protocol/STObject_test.cpp @@ -13,7 +13,8 @@ public: unexpected(sfGeneric.isUseful(), "sfGeneric must not be useful"); { // Try to put sfGeneric in an SOTemplate. - except([&]() { SOTemplate elements{{sfGeneric, soeREQUIRED}}; }); + except( + [&]() { SOTemplate const elements{{sfGeneric, soeREQUIRED}}; }); } unexpected(sfInvalid.isUseful(), "sfInvalid must not be useful"); @@ -31,12 +32,13 @@ public: } { // Try to put sfInvalid in an SOTemplate. - except([&]() { SOTemplate elements{{sfInvalid, soeREQUIRED}}; }); + except( + [&]() { SOTemplate const elements{{sfInvalid, soeREQUIRED}}; }); } { // Try to put the same SField into an SOTemplate twice. except([&]() { - SOTemplate elements{ + SOTemplate const elements{ {sfAccount, soeREQUIRED}, {sfAccount, soeREQUIRED}, }; @@ -59,7 +61,7 @@ public: }; STObject object1(elements, sfTestObject); - STObject object2(object1); + STObject const object2(object1); unexpected(object1.getSerializer() != object2.getSerializer(), "STObject error 1"); @@ -106,7 +108,7 @@ public: for (int i = 0; i < 1000; i++) { - Blob j(i, 2); + Blob const j(i, 2); object1.setFieldVL(sfTestVL, j); @@ -114,7 +116,7 @@ public: object1.add(s); SerialIter it(s.slice()); - STObject object3(elements, it, sfTestObject); + STObject const object3(elements, it, sfTestObject); unexpected(object1.getFieldVL(sfTestVL) != j, "STObject error"); @@ -134,7 +136,7 @@ public: object1.add(s); SerialIter it(s.slice()); - STObject object3(elements, it, sfTestObject); + STObject const object3(elements, it, sfTestObject); auto const& uints1 = object1.getFieldV256(sfTestV256); auto const& uints3 = object3.getFieldV256(sfTestV256); @@ -475,7 +477,7 @@ public: run() override { // Instantiate a jtx::Env so debugLog writes are exercised. - test::jtx::Env env(*this); + test::jtx::Env const env(*this); testFields(); testSerialization(); diff --git a/src/test/protocol/STParsedJSON_test.cpp b/src/test/protocol/STParsedJSON_test.cpp index 974975d05f..1c86a90348 100644 --- a/src/test/protocol/STParsedJSON_test.cpp +++ b/src/test/protocol/STParsedJSON_test.cpp @@ -71,7 +71,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfCloseResolution] = -1; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -79,7 +79,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfCloseResolution] = 256; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -87,7 +87,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfCloseResolution] = Json::Value(Json::arrayValue); - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -95,7 +95,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfCloseResolution] = Json::Value(Json::objectValue); - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } } @@ -154,7 +154,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfLedgerEntryType] = -1; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -162,7 +162,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfLedgerEntryType] = 65536; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -170,7 +170,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfLedgerEntryType] = "65536"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -178,7 +178,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfLedgerEntryType] = Json::Value(Json::arrayValue); - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -186,7 +186,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfLedgerEntryType] = Json::Value(Json::objectValue); - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -194,7 +194,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfTransferFee] = "Payment"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } } @@ -240,7 +240,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfNetworkID] = -1; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -248,7 +248,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfNetworkID] = "4294967296"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -256,7 +256,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfNetworkID] = Json::Value(Json::arrayValue); - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -264,7 +264,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfNetworkID] = Json::Value(Json::objectValue); - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } } @@ -298,7 +298,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfIndexNext] = -1; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -309,7 +309,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfIndexNext] = "10000000000000000"; // uint64 max + 1 (in hex) - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -317,7 +317,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfIndexNext] = "0xabcdefabcdef"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -325,7 +325,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfIndexNext] = "abcdefga"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -333,7 +333,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfIndexNext] = Json::Value(Json::arrayValue); - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -341,7 +341,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfIndexNext] = Json::Value(Json::objectValue); - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } } @@ -359,7 +359,7 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(obj.object->isFieldPresent(sfEmailHash)); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) BEAST_EXPECT(obj.object->getFieldH128(sfEmailHash).size() == 16); - std::array expected = { + std::array const expected = { 0x01, 0x23, 0x45, @@ -403,7 +403,8 @@ class STParsedJSON_test : public beast::unit_test::suite // NOLINTNEXTLINE(bugprone-unchecked-optional-access) auto const& h128 = obj.object->getFieldH128(sfEmailHash); BEAST_EXPECT(h128.size() == 16); - bool allZero = std::all_of(h128.begin(), h128.end(), [](auto b) { return b == 0; }); + bool const allZero = + std::all_of(h128.begin(), h128.end(), [](auto b) { return b == 0; }); BEAST_EXPECT(allZero); } @@ -411,7 +412,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfEmailHash] = "0123456789ABCDEF0123456789ABCDE"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -419,7 +420,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfEmailHash] = "nothexstring"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -427,7 +428,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfEmailHash] = "01234567"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -435,7 +436,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfEmailHash] = "0123456789ABCDEF0123456789ABCDEF00"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -443,7 +444,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfEmailHash] = Json::Value(Json::arrayValue); - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -451,7 +452,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfEmailHash] = Json::Value(Json::objectValue); - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } } @@ -469,9 +470,9 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(obj.object->isFieldPresent(sfTakerPaysCurrency)); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) BEAST_EXPECT(obj.object->getFieldH160(sfTakerPaysCurrency).size() == 20); - std::array expected = {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, - 0xEF, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, - 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67}; + std::array const expected = {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, + 0xEF, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, + 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67}; // NOLINTNEXTLINE(bugprone-unchecked-optional-access) BEAST_EXPECT(obj.object->getFieldH160(sfTakerPaysCurrency) == uint160{expected}); } @@ -498,7 +499,8 @@ class STParsedJSON_test : public beast::unit_test::suite // NOLINTNEXTLINE(bugprone-unchecked-optional-access) auto const& h160 = obj.object->getFieldH160(sfTakerPaysCurrency); BEAST_EXPECT(h160.size() == 20); - bool allZero = std::all_of(h160.begin(), h160.end(), [](auto b) { return b == 0; }); + bool const allZero = + std::all_of(h160.begin(), h160.end(), [](auto b) { return b == 0; }); BEAST_EXPECT(allZero); } @@ -506,7 +508,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfTakerPaysCurrency] = "nothexstring"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -514,7 +516,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfTakerPaysCurrency] = "01234567"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -522,7 +524,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfTakerPaysCurrency] = "0123456789ABCDEF0123456789ABCDEF0123456789"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -530,7 +532,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfTakerPaysCurrency] = Json::Value(Json::arrayValue); - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -538,7 +540,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfTakerPaysCurrency] = Json::Value(Json::objectValue); - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } } @@ -556,9 +558,9 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(obj.object->isFieldPresent(sfMPTokenIssuanceID)); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) BEAST_EXPECT(obj.object->getFieldH192(sfMPTokenIssuanceID).size() == 24); - std::array expected = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; + std::array const expected = { + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; // NOLINTNEXTLINE(bugprone-unchecked-optional-access) BEAST_EXPECT(obj.object->getFieldH192(sfMPTokenIssuanceID) == uint192{expected}); } @@ -586,7 +588,8 @@ class STParsedJSON_test : public beast::unit_test::suite // NOLINTNEXTLINE(bugprone-unchecked-optional-access) auto const& h192 = obj.object->getFieldH192(sfMPTokenIssuanceID); BEAST_EXPECT(h192.size() == 24); - bool allZero = std::all_of(h192.begin(), h192.end(), [](auto b) { return b == 0; }); + bool const allZero = + std::all_of(h192.begin(), h192.end(), [](auto b) { return b == 0; }); BEAST_EXPECT(allZero); } @@ -594,7 +597,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfMPTokenIssuanceID] = "0123456789ABCDEF0123456789ABCDEF0123456789ABCDE"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -602,7 +605,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfMPTokenIssuanceID] = "nothexstring"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -610,7 +613,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfMPTokenIssuanceID] = "01234567"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -618,7 +621,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfMPTokenIssuanceID] = "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF00"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -626,7 +629,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfMPTokenIssuanceID] = Json::Value(Json::arrayValue); - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -634,7 +637,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfMPTokenIssuanceID] = Json::Value(Json::objectValue); - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } } @@ -655,10 +658,10 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(obj.object->isFieldPresent(sfLedgerHash)); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) BEAST_EXPECT(obj.object->getFieldH256(sfLedgerHash).size() == 32); - std::array expected = {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, - 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, - 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, - 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}; + std::array const expected = { + 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23, 0x45, + 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, + 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}; // NOLINTNEXTLINE(bugprone-unchecked-optional-access) BEAST_EXPECT(obj.object->getFieldH256(sfLedgerHash) == uint256{expected}); } @@ -687,7 +690,8 @@ class STParsedJSON_test : public beast::unit_test::suite // NOLINTNEXTLINE(bugprone-unchecked-optional-access) auto const& h256 = obj.object->getFieldH256(sfLedgerHash); BEAST_EXPECT(h256.size() == 32); - bool allZero = std::all_of(h256.begin(), h256.end(), [](auto b) { return b == 0; }); + bool const allZero = + std::all_of(h256.begin(), h256.end(), [](auto b) { return b == 0; }); BEAST_EXPECT(allZero); } @@ -697,7 +701,7 @@ class STParsedJSON_test : public beast::unit_test::suite j[sfLedgerHash] = "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCD" "E"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -705,7 +709,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfLedgerHash] = "nothexstring"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -713,7 +717,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfLedgerHash] = "01234567"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -723,7 +727,7 @@ class STParsedJSON_test : public beast::unit_test::suite j[sfLedgerHash] = "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCD" "EF00"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -731,7 +735,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfLedgerHash] = Json::Value(Json::arrayValue); - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -739,7 +743,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfLedgerHash] = Json::Value(Json::objectValue); - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } } @@ -810,7 +814,7 @@ class STParsedJSON_test : public beast::unit_test::suite // Test with string negative value { Json::Value j; - int value = -2147483648; + int const value = -2147483648; j[sfLoanScale] = std::to_string(value); STParsedJSONObject obj("Test", j); BEAST_EXPECT(obj.object.has_value()); @@ -826,7 +830,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfLoanScale] = "-2147483649"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -834,7 +838,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfLoanScale] = 2147483648u; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -842,7 +846,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfLoanScale] = "2147483648"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -850,7 +854,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfLoanScale] = Json::Value(Json::arrayValue); - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -858,7 +862,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfLoanScale] = Json::Value(Json::objectValue); - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } } @@ -918,7 +922,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfPublicKey] = "XYZ123"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -926,7 +930,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfPublicKey] = Json::Value(Json::arrayValue); - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -934,7 +938,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfPublicKey] = Json::Value(Json::objectValue); - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } } @@ -967,7 +971,7 @@ class STParsedJSON_test : public beast::unit_test::suite // Test empty array for Vector256 (should be valid, size 0) { Json::Value j; - Json::Value arr(Json::arrayValue); + Json::Value const arr(Json::arrayValue); j[sfHashes] = arr; STParsedJSONObject obj("Test", j); BEAST_EXPECT(obj.object.has_value()); @@ -984,7 +988,7 @@ class STParsedJSON_test : public beast::unit_test::suite Json::Value arr(Json::arrayValue); arr.append("nothexstring"); j[sfHashes] = arr; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -994,7 +998,7 @@ class STParsedJSON_test : public beast::unit_test::suite Json::Value arr(Json::arrayValue); arr.append("0123456789ABCDEF"); // too short for uint256 j[sfHashes] = arr; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1004,7 +1008,7 @@ class STParsedJSON_test : public beast::unit_test::suite Json::Value arr(Json::arrayValue); arr.append(12345); j[sfHashes] = arr; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1012,7 +1016,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfHashes] = "notanarray"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1024,7 +1028,7 @@ class STParsedJSON_test : public beast::unit_test::suite objElem["foo"] = "bar"; arr.append(objElem); j[sfHashes] = arr; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } } @@ -1064,7 +1068,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfAccount] = "notAValidBase58Account"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1072,7 +1076,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfAccount] = "001122334455"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1080,7 +1084,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfAccount] = "000102030405060708090A0B0C0D0E0F101112131415"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1088,7 +1092,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfAccount] = "000102030405060708090A0B0C0D0E0F1011121G"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1096,7 +1100,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfAccount] = ""; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1104,7 +1108,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfAccount] = Json::Value(Json::arrayValue); - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1112,7 +1116,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfAccount] = Json::Value(Json::objectValue); - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } } @@ -1164,7 +1168,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfBaseAsset] = "USDD"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1185,7 +1189,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfBaseAsset] = "0123456789AB"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1193,7 +1197,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfBaseAsset] = "0123456789ABCDEF0123456789"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1214,7 +1218,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfBaseAsset] = Json::Value(Json::arrayValue); - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1222,7 +1226,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfBaseAsset] = Json::Value(Json::objectValue); - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } } @@ -1259,7 +1263,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfAmount] = "123.45"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1267,7 +1271,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfAmount] = ""; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1275,7 +1279,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfAmount] = "notanumber"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1283,7 +1287,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfAmount] = Json::Value(Json::objectValue); - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } } @@ -1349,7 +1353,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfPaths] = "notanarray"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1359,7 +1363,7 @@ class STParsedJSON_test : public beast::unit_test::suite Json::Value pathset(Json::arrayValue); pathset.append("notanarray"); j[sfPaths] = pathset; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1372,7 +1376,7 @@ class STParsedJSON_test : public beast::unit_test::suite Json::Value pathset(Json::arrayValue); pathset.append(path); j[sfPaths] = pathset; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1387,7 +1391,7 @@ class STParsedJSON_test : public beast::unit_test::suite Json::Value pathset(Json::arrayValue); pathset.append(path); j[sfPaths] = pathset; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1402,7 +1406,7 @@ class STParsedJSON_test : public beast::unit_test::suite Json::Value pathset(Json::arrayValue); pathset.append(path); j[sfPaths] = pathset; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1416,7 +1420,7 @@ class STParsedJSON_test : public beast::unit_test::suite Json::Value pathset(Json::arrayValue); pathset.append(path); j[sfPaths] = pathset; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1430,7 +1434,7 @@ class STParsedJSON_test : public beast::unit_test::suite Json::Value pathset(Json::arrayValue); pathset.append(path); j[sfPaths] = pathset; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1444,7 +1448,7 @@ class STParsedJSON_test : public beast::unit_test::suite Json::Value pathset(Json::arrayValue); pathset.append(path); j[sfPaths] = pathset; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1458,7 +1462,7 @@ class STParsedJSON_test : public beast::unit_test::suite Json::Value pathset(Json::arrayValue); pathset.append(path); j[sfPaths] = pathset; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1472,7 +1476,7 @@ class STParsedJSON_test : public beast::unit_test::suite Json::Value pathset(Json::arrayValue); pathset.append(path); j[sfPaths] = pathset; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } } @@ -1544,7 +1548,7 @@ class STParsedJSON_test : public beast::unit_test::suite Json::Value issue(Json::objectValue); issue["issuer"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; j[sfAsset] = issue; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1554,7 +1558,7 @@ class STParsedJSON_test : public beast::unit_test::suite Json::Value issue(Json::objectValue); issue["currency"] = "USD"; j[sfAsset] = issue; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1565,7 +1569,7 @@ class STParsedJSON_test : public beast::unit_test::suite issue["currency"] = "USDD"; issue["issuer"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; j[sfAsset] = issue; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1576,7 +1580,7 @@ class STParsedJSON_test : public beast::unit_test::suite issue["currency"] = "USD"; issue["issuer"] = "notAValidIssuer"; j[sfAsset] = issue; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1587,7 +1591,7 @@ class STParsedJSON_test : public beast::unit_test::suite issue["currency"] = Json::Value(Json::arrayValue); issue["issuer"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; j[sfAsset] = issue; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1598,7 +1602,7 @@ class STParsedJSON_test : public beast::unit_test::suite issue["currency"] = "USD"; issue["issuer"] = Json::Value(Json::objectValue); j[sfAsset] = issue; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1606,7 +1610,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfAsset] = "notanobject"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } } @@ -1676,7 +1680,7 @@ class STParsedJSON_test : public beast::unit_test::suite bridge["LockingChainDoor"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; bridge["IssuingChainDoor"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; j[sfXChainBridge] = bridge; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1691,7 +1695,7 @@ class STParsedJSON_test : public beast::unit_test::suite bridge["LockingChainDoor"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; bridge["IssuingChainDoor"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; j[sfXChainBridge] = bridge; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1709,7 +1713,7 @@ class STParsedJSON_test : public beast::unit_test::suite bridge["LockingChainIssue"] = lockingChainIssue; bridge["IssuingChainDoor"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; j[sfXChainBridge] = bridge; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1727,7 +1731,7 @@ class STParsedJSON_test : public beast::unit_test::suite bridge["LockingChainIssue"] = lockingChainIssue; bridge["LockingChainDoor"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; j[sfXChainBridge] = bridge; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1738,7 +1742,7 @@ class STParsedJSON_test : public beast::unit_test::suite bridge["LockingChainIssue"] = "notanobject"; bridge["IssuingChainIssue"] = "notanobject"; j[sfXChainBridge] = bridge; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1754,7 +1758,7 @@ class STParsedJSON_test : public beast::unit_test::suite bridge["LockingChainIssue"] = lockingChainIssue; bridge["IssuingChainIssue"] = asset; j[sfXChainBridge] = bridge; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1770,7 +1774,7 @@ class STParsedJSON_test : public beast::unit_test::suite bridge["LockingChainIssue"] = lockingChainIssue; bridge["IssuingChainIssue"] = asset; j[sfXChainBridge] = bridge; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1787,7 +1791,7 @@ class STParsedJSON_test : public beast::unit_test::suite bridge["LockingChainIssue"] = lockingChainIssue; bridge["IssuingChainIssue"] = asset; j[sfXChainBridge] = bridge; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1795,7 +1799,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfXChainBridge] = "notanobject"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } } @@ -1880,7 +1884,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfNumber] = "notanumber"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1888,7 +1892,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfNumber] = Json::Value(Json::arrayValue); - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1896,7 +1900,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfNumber] = Json::Value(Json::objectValue); - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1904,7 +1908,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfNumber] = ""; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } } @@ -1932,7 +1936,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfTransactionMetaData] = "notanobject"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1942,7 +1946,7 @@ class STParsedJSON_test : public beast::unit_test::suite Json::Value arr(Json::arrayValue); arr.append(1); j[sfTransactionMetaData] = arr; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1950,7 +1954,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfTransactionMetaData] = Json::Value(Json::nullValue); - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -1962,7 +1966,7 @@ class STParsedJSON_test : public beast::unit_test::suite Json::Value* current = &obj; for (int i = 0; i < 63; ++i) { - Json::Value next(Json::objectValue); + Json::Value const next(Json::objectValue); (*current)[sfTransactionMetaData] = next; current = &((*current)[sfTransactionMetaData]); } @@ -1981,13 +1985,13 @@ class STParsedJSON_test : public beast::unit_test::suite Json::Value* current = &obj; for (int i = 0; i < 64; ++i) { - Json::Value next(Json::objectValue); + Json::Value const next(Json::objectValue); (*current)[sfTransactionMetaData] = next; current = &((*current)[sfTransactionMetaData]); } (*current)[sfTransactionResult.getJsonName()] = 1; j[sfTransactionMetaData] = obj; - STParsedJSONObject parsed("Test", j); + STParsedJSONObject const parsed("Test", j); BEAST_EXPECT(!parsed.object.has_value()); } } @@ -2025,7 +2029,7 @@ class STParsedJSON_test : public beast::unit_test::suite Json::Value arr(Json::arrayValue); arr.append("notanobject"); j[sfSignerEntries] = arr; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -2037,7 +2041,7 @@ class STParsedJSON_test : public beast::unit_test::suite elem["invalidField"] = 1; arr.append(elem); j[sfSignerEntries] = arr; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -2050,7 +2054,7 @@ class STParsedJSON_test : public beast::unit_test::suite elem[sfNetworkID] = 3; arr.append(elem); j[sfSignerEntries] = arr; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -2058,7 +2062,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; j[sfSignerEntries] = "notanarray"; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -2071,14 +2075,14 @@ class STParsedJSON_test : public beast::unit_test::suite elem[sfTransactionResult] = "notanint"; arr.append(elem); j[sfSignerEntries] = arr; - STParsedJSONObject obj("Test", j); + STParsedJSONObject const obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } // Test with empty array for Array (should be valid) { Json::Value j; - Json::Value arr(Json::arrayValue); + Json::Value const arr(Json::arrayValue); j[sfSignerEntries] = arr; STParsedJSONObject obj("Test", j); BEAST_EXPECT(obj.object.has_value()); @@ -2093,7 +2097,7 @@ class STParsedJSON_test : public beast::unit_test::suite obj.append(Json::Value(Json::objectValue)); obj[0u][sfTransactionResult] = 1; j[sfSignerEntries] = obj; - STParsedJSONObject parsed("Test", j); + STParsedJSONObject const parsed("Test", j); BEAST_EXPECT(!parsed.object.has_value()); } @@ -2113,22 +2117,22 @@ class STParsedJSON_test : public beast::unit_test::suite them. */ - std::string faulty( + std::string const faulty( "{\"Template\":[{" "\"ModifiedNode\":{\"Sequence\":1}, " "\"DeletedNode\":{\"Sequence\":1}" "}]}"); - std::unique_ptr so; + std::unique_ptr const so; Json::Value faultyJson; - bool parsedOK(parseJSONString(faulty, faultyJson)); + bool const parsedOK(parseJSONString(faulty, faultyJson)); unexpected(!parsedOK, "failed to parse"); - STParsedJSONObject parsed("test", faultyJson); + STParsedJSONObject const parsed("test", faultyJson); BEAST_EXPECT(!parsed.object); } catch (std::runtime_error& e) { - std::string what(e.what()); + std::string const what(e.what()); unexpected(what.find("First level children of `Template`") != 0); } } @@ -2380,7 +2384,7 @@ class STParsedJSON_test : public beast::unit_test::suite run() override { // Instantiate a jtx::Env so debugLog writes are exercised. - test::jtx::Env env(*this); + test::jtx::Env const env(*this); testUInt8(); testUInt16(); testUInt32(); diff --git a/src/test/protocol/STTx_test.cpp b/src/test/protocol/STTx_test.cpp index 93cfd16d3d..0804c89bd4 100644 --- a/src/test/protocol/STTx_test.cpp +++ b/src/test/protocol/STTx_test.cpp @@ -1149,7 +1149,7 @@ public: // Construct an SOTemplate to get the ball rolling on building // an STObject that can contain an STArray. - SOTemplate recurse{ + SOTemplate const recurse{ {sfTransactionMetaData, soeOPTIONAL}, {sfTransactionHash, soeOPTIONAL}, {sfTemplate, soeOPTIONAL}, @@ -1211,7 +1211,7 @@ public: // Make an otherwise legit STTx with a duplicate field. Should // generate an exception when we deserialize. auto const keypair = randomKeyPair(KeyType::secp256k1); - STTx acctSet(ttACCOUNT_SET, [&keypair](auto& obj) { + STTx const acctSet(ttACCOUNT_SET, [&keypair](auto& obj) { obj.setAccountID(sfAccount, calcAccountID(keypair.first)); obj.setFieldU32(sfSequence, 7); obj.setFieldAmount(sfFee, STAmount(2557891634ull)); @@ -1329,7 +1329,7 @@ public: Serializer rawTxn; j.add(rawTxn); SerialIter sit(rawTxn.slice()); - STTx copy(sit); + STTx const copy(sit); if (copy != j) { @@ -1466,7 +1466,7 @@ public: auto const id2 = calcAccountID(kp2.first); // Get the stream of the transaction for use in multi-signing. - Serializer s = buildMultiSigningData(txn, id2); + Serializer const s = buildMultiSigningData(txn, id2); auto const saMultiSignature = sign(kp2.first, kp2.second, s.slice()); @@ -1497,7 +1497,7 @@ public: bool serialized = false; try { - STTx copy(sit); + STTx const copy(sit); serialized = true; } catch (std::exception const&) diff --git a/src/test/protocol/SecretKey_test.cpp b/src/test/protocol/SecretKey_test.cpp index e42bec3363..9072f5c0d9 100644 --- a/src/test/protocol/SecretKey_test.cpp +++ b/src/test/protocol/SecretKey_test.cpp @@ -216,7 +216,7 @@ public: auto s = good; // Remove all characters from the string in random order: - std::hash r; + std::hash const r; while (!s.empty()) { diff --git a/src/test/protocol/Serializer_test.cpp b/src/test/protocol/Serializer_test.cpp index c5b56c3029..e4eaac8a58 100644 --- a/src/test/protocol/Serializer_test.cpp +++ b/src/test/protocol/Serializer_test.cpp @@ -17,7 +17,7 @@ struct Serializer_test : public beast::unit_test::suite 0, 1, std::numeric_limits::max()}; - for (std::int32_t value : values) + for (std::int32_t const value : values) { Serializer s; s.add32(value); @@ -33,7 +33,7 @@ struct Serializer_test : public beast::unit_test::suite 0, 1, std::numeric_limits::max()}; - for (std::int64_t value : values) + for (std::int64_t const value : values) { Serializer s; s.add64(value); diff --git a/src/test/protocol/TER_test.cpp b/src/test/protocol/TER_test.cpp index cf88a570c5..2ad4b634aa 100644 --- a/src/test/protocol/TER_test.cpp +++ b/src/test/protocol/TER_test.cpp @@ -13,7 +13,7 @@ struct TER_test : public beast::unit_test::suite { for (auto i = -400; i < 400; ++i) { - TER t = TER::fromInt(i); + TER const t = TER::fromInt(i); auto inRange = isTelLocal(t) || isTemMalformed(t) || isTefFailure(t) || isTerRetry(t) || isTesSuccess(t) || isTecClaim(t); @@ -75,7 +75,7 @@ struct TER_test : public beast::unit_test::suite std::enable_if_t testIterate(Tup const& tup, beast::unit_test::suite& s) { - Func func; + Func const func; func(tup, s); testIterate(tup, s); } @@ -89,7 +89,7 @@ struct TER_test : public beast::unit_test::suite std::enable_if_t testIterate(Tup const& tup, beast::unit_test::suite& s) { - Func func; + Func const func; func(tup, s); testIterate::value - 1, I2 - 1, Func>(tup, s); } @@ -103,7 +103,7 @@ struct TER_test : public beast::unit_test::suite std::enable_if_t testIterate(Tup const& tup, beast::unit_test::suite& s) { - Func func; + Func const func; func(tup, s); } diff --git a/src/test/resource/Logic_test.cpp b/src/test/resource/Logic_test.cpp index 6d412b000f..12c1e631e2 100644 --- a/src/test/resource/Logic_test.cpp +++ b/src/test/resource/Logic_test.cpp @@ -54,7 +54,8 @@ public: { Gossip::Item item; item.balance = 100 + rand_int(499); - beast::IP::AddressV4::bytes_type d = {{192, 0, 2, static_cast(v + i)}}; + beast::IP::AddressV4::bytes_type const d = { + {192, 0, 2, static_cast(v + i)}}; item.address = beast::IP::Endpoint{beast::IP::AddressV4{d}}; gossip.items.push_back(item); } @@ -79,7 +80,7 @@ public: Charge const fee(dropThreshold + 1); beast::IP::Endpoint const addr(beast::IP::Endpoint::from_string("192.0.2.2")); - std::function ep = limited + std::function const ep = limited ? std::bind(&TestLogic::newInboundEndpoint, &logic, std::placeholders::_1) : std::bind(&TestLogic::newUnlimitedEndpoint, &logic, std::placeholders::_1); @@ -147,7 +148,7 @@ public: // Make sure the consumer is on the blacklist for a while. { - Consumer c(logic.newInboundEndpoint(addr)); + Consumer const c(logic.newInboundEndpoint(addr)); logic.periodicActivity(); if (c.disposition() != drop) { @@ -174,7 +175,7 @@ public: { ++logic.clock(); logic.periodicActivity(); - Consumer c(logic.newInboundEndpoint(addr)); + Consumer const c(logic.newInboundEndpoint(addr)); if (c.disposition() != drop) { readmitted = true; @@ -218,7 +219,7 @@ public: Gossip g; Gossip::Item item; item.balance = 100; - beast::IP::AddressV4::bytes_type d = {{192, 0, 2, 1}}; + beast::IP::AddressV4::bytes_type const d = {{192, 0, 2, 1}}; item.address = beast::IP::Endpoint{beast::IP::AddressV4{d}}; g.items.push_back(item); @@ -235,9 +236,9 @@ public: TestLogic logic(j); { - beast::IP::Endpoint address(beast::IP::Endpoint::from_string("192.0.2.1")); + beast::IP::Endpoint const address(beast::IP::Endpoint::from_string("192.0.2.1")); Consumer c(logic.newInboundEndpoint(address)); - Charge fee(1000); + Charge const fee(1000); JLOG(j.info()) << "Charging " << c.to_string() << " " << fee << " per second"; c.charge(fee); for (int i = 0; i < 128; ++i) @@ -249,9 +250,9 @@ public: } { - beast::IP::Endpoint address(beast::IP::Endpoint::from_string("192.0.2.2")); + beast::IP::Endpoint const address(beast::IP::Endpoint::from_string("192.0.2.2")); Consumer c(logic.newInboundEndpoint(address)); - Charge fee(1000); + Charge const fee(1000); JLOG(j.info()) << "Charging " << c.to_string() << " " << fee << " per second"; for (int i = 0; i < 128; ++i) { diff --git a/src/test/rpc/AccountCurrencies_test.cpp b/src/test/rpc/AccountCurrencies_test.cpp index bb8ccf0a85..009af9d454 100644 --- a/src/test/rpc/AccountCurrencies_test.cpp +++ b/src/test/rpc/AccountCurrencies_test.cpp @@ -165,7 +165,8 @@ class AccountCurrencies_test : public beast::unit_test::suite env(pay(gw, alice, gw["USA"](50))); // USA should now be missing from receive_currencies result = env.rpc("json", "account_currencies", to_string(params))[jss::result]; - decltype(gwCurrencies) gwCurrenciesNoUSA(gwCurrencies.begin() + 1, gwCurrencies.end()); + decltype(gwCurrencies) + const gwCurrenciesNoUSA(gwCurrencies.begin() + 1, gwCurrencies.end()); BEAST_EXPECT(arrayCheck(jss::receive_currencies, gwCurrenciesNoUSA)); BEAST_EXPECT(arrayCheck(jss::send_currencies, gwCurrencies)); diff --git a/src/test/rpc/AccountObjects_test.cpp b/src/test/rpc/AccountObjects_test.cpp index 905f8f2bb7..b6e8f6fa76 100644 --- a/src/test/rpc/AccountObjects_test.cpp +++ b/src/test/rpc/AccountObjects_test.cpp @@ -107,7 +107,7 @@ public: // test error on no account { - Json::Value params; + Json::Value const params; auto resp = env.rpc("json", "account_objects", to_string(params)); BEAST_EXPECT(resp[jss::result][jss::error_message] == "Missing field 'account'."); } @@ -488,7 +488,7 @@ public: params[jss::type] = jss::nft_page; auto resp = env.rpc("json", "account_objects", to_string(params)); BEAST_EXPECT(!resp.isMember(jss::marker)); - Json::Value& aobjs = resp[jss::result][jss::account_objects]; + Json::Value const& aobjs = resp[jss::result][jss::account_objects]; BEAST_EXPECT(aobjs.size() == 2); } // test stepped one-at-a-time with limit=1, resume from prev marker @@ -1276,7 +1276,7 @@ public: // valid, because when dirIndex = 0, we will use root key to find // dir. { - std::string s = "0," + entryIndex; + std::string const s = "0," + entryIndex; Json::Value params; params[jss::account] = bob.human(); params[jss::limit] = limit; diff --git a/src/test/rpc/AccountTx_test.cpp b/src/test/rpc/AccountTx_test.cpp index a11f957628..2470ec3c4c 100644 --- a/src/test/rpc/AccountTx_test.cpp +++ b/src/test/rpc/AccountTx_test.cpp @@ -97,7 +97,7 @@ class AccountTx_test : public beast::unit_test::suite cfg->FEES.reference_fee = 10; return cfg; })); - Account A1{"A1"}; + Account const A1{"A1"}; env.fund(XRP(10000), A1); env.close(); @@ -541,7 +541,7 @@ class AccountTx_test : public beast::unit_test::suite // PayChan { - std::uint32_t payChanSeq{env.seq(alice)}; + std::uint32_t const payChanSeq{env.seq(alice)}; Json::Value payChanCreate; payChanCreate[jss::TransactionType] = jss::PaymentChannelCreate; payChanCreate[jss::Account] = alice.human(); diff --git a/src/test/rpc/BookChanges_test.cpp b/src/test/rpc/BookChanges_test.cpp index 6bd71b141b..0618f4e7d0 100644 --- a/src/test/rpc/BookChanges_test.cpp +++ b/src/test/rpc/BookChanges_test.cpp @@ -78,7 +78,7 @@ public: featurePermissionedDEX}; Env env(*this, all); - PermissionedDEX permDex(env); + PermissionedDEX const permDex(env); auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = permDex; auto wsc = makeWSClient(env.app().config()); diff --git a/src/test/rpc/Book_test.cpp b/src/test/rpc/Book_test.cpp index 41442edb06..5e149ebc0e 100644 --- a/src/test/rpc/Book_test.cpp +++ b/src/test/rpc/Book_test.cpp @@ -877,9 +877,9 @@ public: testcase("TrackOffers"); using namespace jtx; Env env(*this); - Account gw{"gw"}; - Account alice{"alice"}; - Account bob{"bob"}; + Account const gw{"gw"}; + Account const alice{"alice"}; + Account const bob{"bob"}; auto wsc = makeWSClient(env.app().config()); env.fund(XRP(20000), alice, bob, gw); env.close(); @@ -1186,8 +1186,8 @@ public: testcase("BookOffersRPC Errors"); using namespace jtx; Env env(*this); - Account gw{"gw"}; - Account alice{"alice"}; + Account const gw{"gw"}; + Account const alice{"alice"}; env.fund(XRP(10000), alice, gw); env.close(); auto USD = gw["USD"]; @@ -1515,7 +1515,7 @@ public: testcase("BookOffer Limits"); using namespace jtx; Env env{*this, asAdmin ? envconfig() : envconfig(no_admin)}; - Account gw{"gw"}; + Account const gw{"gw"}; env.fund(XRP(200000), gw); // Note that calls to env.close() fail without admin permission. if (asAdmin) @@ -1562,7 +1562,7 @@ public: featurePermissionedDEX}; Env env(*this, all); - PermissionedDEX permDex(env); + PermissionedDEX const permDex(env); auto const alice = permDex.alice; auto const bob = permDex.bob; auto const carol = permDex.carol; @@ -1685,7 +1685,7 @@ public: featurePermissionedDEX}; Env env(*this, all); - PermissionedDEX permDex(env); + PermissionedDEX const permDex(env); auto const alice = permDex.alice; auto const bob = permDex.bob; auto const carol = permDex.carol; diff --git a/src/test/rpc/DeliveredAmount_test.cpp b/src/test/rpc/DeliveredAmount_test.cpp index 31b9b2aebf..358657a6c3 100644 --- a/src/test/rpc/DeliveredAmount_test.cpp +++ b/src/test/rpc/DeliveredAmount_test.cpp @@ -90,7 +90,7 @@ public: if (t[jss::TransactionType].asString() != jss::Payment) return true; - bool isSet = metaData.isMember(jss::delivered_amount); + bool const isSet = metaData.isMember(jss::delivered_amount); bool isSetUnavailable = false; bool isSetAvailable = false; if (isSet) diff --git a/src/test/rpc/DepositAuthorized_test.cpp b/src/test/rpc/DepositAuthorized_test.cpp index 87951e397c..7921d063c9 100644 --- a/src/test/rpc/DepositAuthorized_test.cpp +++ b/src/test/rpc/DepositAuthorized_test.cpp @@ -191,14 +191,14 @@ public: } { // Request an invalid ledger. - Json::Value args{depositAuthArgs(alice, becky, "-1")}; + Json::Value const args{depositAuthArgs(alice, becky, "-1")}; Json::Value const result{env.rpc("json", "deposit_authorized", args.toStyledString())}; verifyErr( result, "invalidParams", "Invalid field 'ledger_index', not string or number."); } { // Request a ledger that doesn't exist yet as a string. - Json::Value args{depositAuthArgs(alice, becky, "17")}; + Json::Value const args{depositAuthArgs(alice, becky, "17")}; Json::Value const result{env.rpc("json", "deposit_authorized", args.toStyledString())}; verifyErr(result, "lgrNotFound", "ledgerNotFound"); } @@ -211,7 +211,7 @@ public: } { // alice is not yet funded. - Json::Value args{depositAuthArgs(alice, becky)}; + Json::Value const args{depositAuthArgs(alice, becky)}; Json::Value const result{env.rpc("json", "deposit_authorized", args.toStyledString())}; verifyErr(result, "srcActNotFound", "Source account not found."); } @@ -219,7 +219,7 @@ public: env.close(); { // becky is not yet funded. - Json::Value args{depositAuthArgs(alice, becky)}; + Json::Value const args{depositAuthArgs(alice, becky)}; Json::Value const result{env.rpc("json", "deposit_authorized", args.toStyledString())}; verifyErr(result, "dstActNotFound", "Destination account not found."); } @@ -227,7 +227,7 @@ public: env.close(); { // Once becky is funded try it again and see it succeed. - Json::Value args{depositAuthArgs(alice, becky)}; + Json::Value const args{depositAuthArgs(alice, becky)}; Json::Value const result{env.rpc("json", "deposit_authorized", args.toStyledString())}; validateDepositAuthResult(result, true); } diff --git a/src/test/rpc/Feature_test.cpp b/src/test/rpc/Feature_test.cpp index 0050429c99..657eda2c1c 100644 --- a/src/test/rpc/Feature_test.cpp +++ b/src/test/rpc/Feature_test.cpp @@ -105,7 +105,7 @@ class Feature_test : public beast::unit_test::suite } // Test an arbitrary unknown feature - uint256 zero{0}; + uint256 const zero{0}; BEAST_EXPECT(featureToName(zero) == to_string(zero)); BEAST_EXPECT( featureToName(zero) == @@ -143,8 +143,9 @@ class Feature_test : public beast::unit_test::suite return; // default config - so all should be disabled, and // supported. Some may be vetoed. - bool expectVeto = (votes.at(feature[jss::name].asString()) == VoteBehavior::DefaultNo); - bool expectObsolete = + bool const expectVeto = + (votes.at(feature[jss::name].asString()) == VoteBehavior::DefaultNo); + bool const expectObsolete = (votes.at(feature[jss::name].asString()) == VoteBehavior::Obsolete); BEAST_EXPECTS( feature.isMember(jss::enabled) && !feature[jss::enabled].asBool(), @@ -278,8 +279,8 @@ class Feature_test : public beast::unit_test::suite (void)id.parseHex(it.key().asString().c_str()); if (!BEAST_EXPECT((*it).isMember(jss::name))) return; - bool expectEnabled = env.app().getAmendmentTable().isEnabled(id); - bool expectSupported = env.app().getAmendmentTable().isSupported(id); + bool const expectEnabled = env.app().getAmendmentTable().isEnabled(id); + bool const expectSupported = env.app().getAmendmentTable().isSupported(id); BEAST_EXPECTS( (*it).isMember(jss::enabled) && (*it)[jss::enabled].asBool() == expectEnabled, (*it)[jss::name].asString() + " enabled"); @@ -339,10 +340,12 @@ class Feature_test : public beast::unit_test::suite (void)id.parseHex(it.key().asString().c_str()); if (!BEAST_EXPECT((*it).isMember(jss::name))) return; - bool expectEnabled = env.app().getAmendmentTable().isEnabled(id); - bool expectSupported = env.app().getAmendmentTable().isSupported(id); - bool expectVeto = (votes.at((*it)[jss::name].asString()) == VoteBehavior::DefaultNo); - bool expectObsolete = (votes.at((*it)[jss::name].asString()) == VoteBehavior::Obsolete); + bool const expectEnabled = env.app().getAmendmentTable().isEnabled(id); + bool const expectSupported = env.app().getAmendmentTable().isSupported(id); + bool const expectVeto = + (votes.at((*it)[jss::name].asString()) == VoteBehavior::DefaultNo); + bool const expectObsolete = + (votes.at((*it)[jss::name].asString()) == VoteBehavior::Obsolete); BEAST_EXPECTS( (*it).isMember(jss::enabled) && (*it)[jss::enabled].asBool() == expectEnabled, (*it)[jss::name].asString() + " enabled"); @@ -421,8 +424,9 @@ class Feature_test : public beast::unit_test::suite { if (!BEAST_EXPECT(feature.isMember(jss::name))) return; - bool expectVeto = (votes.at(feature[jss::name].asString()) == VoteBehavior::DefaultNo); - bool expectObsolete = + bool const expectVeto = + (votes.at(feature[jss::name].asString()) == VoteBehavior::DefaultNo); + bool const expectObsolete = (votes.at(feature[jss::name].asString()) == VoteBehavior::Obsolete); BEAST_EXPECTS( (expectVeto || expectObsolete) ^ feature.isMember(jss::majority), diff --git a/src/test/rpc/GatewayBalances_test.cpp b/src/test/rpc/GatewayBalances_test.cpp index 0deb1fc627..b6efea17fc 100644 --- a/src/test/rpc/GatewayBalances_test.cpp +++ b/src/test/rpc/GatewayBalances_test.cpp @@ -231,7 +231,7 @@ public: using namespace jtx; // Ensure MPT is enabled - FeatureBitset features = testable_amendments() | featureMPTokensV1; + FeatureBitset const features = testable_amendments() | featureMPTokensV1; Env env(*this, features); Account const alice{"alice"}; diff --git a/src/test/rpc/GetAggregatePrice_test.cpp b/src/test/rpc/GetAggregatePrice_test.cpp index 5facd683a5..1d14678f76 100644 --- a/src/test/rpc/GetAggregatePrice_test.cpp +++ b/src/test/rpc/GetAggregatePrice_test.cpp @@ -34,7 +34,7 @@ public: BEAST_EXPECT(ret[jss::error_message].asString() == "Missing field 'quote_asset'."); // invalid base_asset, quote_asset - std::vector invalidAsset = { + std::vector const invalidAsset = { NoneTag, 1, -1, @@ -76,7 +76,7 @@ public: ret = Oracle::aggregatePrice(env, "XRP", "USD", {{{owner, 2}}}); BEAST_EXPECT(ret[jss::error].asString() == "objectNotFound"); // invalid values - std::vector invalidDocument = {NoneTag, 1.2, -1, "", "none", "1.2"}; + std::vector const invalidDocument = {NoneTag, 1.2, -1, "", "none", "1.2"}; for (auto const& v : invalidDocument) { ret = Oracle::aggregatePrice(env, "XRP", "USD", {{{owner, v}}}); @@ -97,7 +97,7 @@ public: // oracles have wrong asset pair env.fund(XRP(1'000), owner); - Oracle oracle( + Oracle const oracle( env, {.owner = owner, .series = {{"XRP", "EUR", 740, 1}}, @@ -106,7 +106,7 @@ public: BEAST_EXPECT(ret[jss::error].asString() == "objectNotFound"); // invalid trim value - std::vector invalidTrim = {NoneTag, 0, 26, -1, 1.2, "", "none", "1.2"}; + std::vector const invalidTrim = {NoneTag, 0, 26, -1, 1.2, "", "none", "1.2"}; for (auto const& v : invalidTrim) { ret = @@ -115,7 +115,7 @@ public: } // invalid time threshold value - std::vector invalidTime = {NoneTag, -1, 1.2, "", "none", "1.2"}; + std::vector const invalidTime = {NoneTag, -1, 1.2, "", "none", "1.2"}; for (auto const& v : invalidTime) { ret = Oracle::aggregatePrice( @@ -134,7 +134,7 @@ public: { Account const owner(std::to_string(i)); env.fund(XRP(1'000), owner); - Oracle oracle(env, {.owner = owner, .documentID = i, .fee = baseFee}); + Oracle const oracle(env, {.owner = owner, .documentID = i, .fee = baseFee}); oracles.emplace_back(owner, oracle.documentID()); } auto const ret = Oracle::aggregatePrice(env, "XRP", "USD", oracles); @@ -156,7 +156,7 @@ public: Account const owner{std::to_string(i)}; env.fund(XRP(1'000), owner); - Oracle oracle( + Oracle const oracle( env, {.owner = owner, .documentID = rand(), @@ -178,7 +178,7 @@ public: // the global mantissa size. And since it's a thread-local, // overriding it locally won't make a difference either. // This will mean all RPC will use the default of "large". - NumberMantissaScaleGuard mg(mantissaSize); + NumberMantissaScaleGuard const mg(mantissaSize); Env env(*this, feats); OraclesData oracles; diff --git a/src/test/rpc/GetCounts_test.cpp b/src/test/rpc/GetCounts_test.cpp index 07c29e3648..d0729b3f56 100644 --- a/src/test/rpc/GetCounts_test.cpp +++ b/src/test/rpc/GetCounts_test.cpp @@ -32,8 +32,8 @@ class GetCounts_test : public beast::unit_test::suite // create some transactions env.close(); - Account alice{"alice"}; - Account bob{"bob"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(10000), alice, bob); env.trust(alice["USD"](1000), bob); for (auto i = 0; i < 20; ++i) diff --git a/src/test/rpc/JSONRPC_test.cpp b/src/test/rpc/JSONRPC_test.cpp index 87c7d3dcd0..b9d4ee4a98 100644 --- a/src/test/rpc/JSONRPC_test.cpp +++ b/src/test/rpc/JSONRPC_test.cpp @@ -2119,7 +2119,7 @@ public: jt.jv.removeMember(jss::Fee); jt.jv.removeMember(jss::TxnSignature); req[jss::tx_json] = jt.jv; - Json::Value result = checkFee( + Json::Value const result = checkFee( req, Role::ADMIN, true, @@ -2189,7 +2189,7 @@ public: alice)); req[jss::tx_json] = jt.jv; - Json::Value result = checkFee( + Json::Value const result = checkFee( req, Role::ADMIN, true, @@ -2216,7 +2216,7 @@ public: { Json::Value req; Json::Reader().parse("{ \"fee_mult_max\" : 1, \"tx_json\" : { } } ", req); - Json::Value result = checkFee( + Json::Value const result = checkFee( req, Role::ADMIN, true, @@ -2236,7 +2236,7 @@ public: "{ \"fee_mult_max\" : 3, \"fee_div_max\" : 2, " "\"tx_json\" : { } } ", req); - Json::Value result = checkFee( + Json::Value const result = checkFee( req, Role::ADMIN, true, @@ -2253,7 +2253,7 @@ public: { Json::Value req; Json::Reader().parse("{ \"fee_mult_max\" : 0, \"tx_json\" : { } } ", req); - Json::Value result = checkFee( + Json::Value const result = checkFee( req, Role::ADMIN, true, @@ -2274,7 +2274,7 @@ public: "{ \"fee_mult_max\" : 3, \"fee_div_max\" : 6, " "\"tx_json\" : { } } ", req); - Json::Value result = checkFee( + Json::Value const result = checkFee( req, Role::ADMIN, true, @@ -2293,7 +2293,7 @@ public: "{ \"fee_mult_max\" : 0, \"fee_div_max\" : 2, " "\"tx_json\" : { } } ", req); - Json::Value result = checkFee( + Json::Value const result = checkFee( req, Role::ADMIN, true, @@ -2312,7 +2312,7 @@ public: "{ \"fee_mult_max\" : 10, \"fee_div_max\" : 0, " "\"tx_json\" : { } } ", req); - Json::Value result = checkFee( + Json::Value const result = checkFee( req, Role::ADMIN, true, @@ -2330,7 +2330,7 @@ public: Json::Value req; test::jtx::Account const alice("alice"); req[jss::tx_json] = test::jtx::acctdelete(env.master.human(), alice.human()); - Json::Value result = checkFee( + Json::Value const result = checkFee( req, Role::ADMIN, true, @@ -2367,7 +2367,7 @@ public: "tx_json" : { } })", req); - Json::Value result = checkFee( + Json::Value const result = checkFee( req, Role::ADMIN, true, @@ -2389,7 +2389,7 @@ public: "tx_json" : { } })", req); - Json::Value result = checkFee( + Json::Value const result = checkFee( req, Role::ADMIN, true, @@ -2417,7 +2417,7 @@ public: "tx_json" : { } })", req); - Json::Value result = checkFee( + Json::Value const result = checkFee( req, Role::ADMIN, true, @@ -2440,7 +2440,7 @@ public: "tx_json" : { } })", req); - Json::Value result = checkFee( + Json::Value const result = checkFee( req, Role::ADMIN, true, @@ -2463,7 +2463,7 @@ public: "tx_json" : { } })", req); - Json::Value result = checkFee( + Json::Value const result = checkFee( req, Role::ADMIN, true, @@ -2486,7 +2486,7 @@ public: "tx_json" : { } })", req); - Json::Value result = checkFee( + Json::Value const result = checkFee( req, Role::ADMIN, true, @@ -2509,7 +2509,7 @@ public: "tx_json" : { } })", req); - Json::Value result = checkFee( + Json::Value const result = checkFee( req, Role::ADMIN, true, @@ -2530,7 +2530,7 @@ public: "tx_json" : { } })", req); - Json::Value result = checkFee( + Json::Value const result = checkFee( req, Role::ADMIN, true, @@ -2552,7 +2552,7 @@ public: "tx_json" : { } })", req); - Json::Value result = checkFee( + Json::Value const result = checkFee( req, Role::ADMIN, true, @@ -2648,7 +2648,7 @@ public: env(noop(env.master), fee(47)); } - Env_ss envs(env); + Env_ss const envs(env); Json::Value toSign; toSign[jss::tx_json] = noop(env.master); @@ -2732,7 +2732,7 @@ public: env(pay(g, env.master, USD(50))); env.close(); - ProcessTransactionFn processTxn = fakeProcessTransaction; + ProcessTransactionFn const processTxn = fakeProcessTransaction; // A list of all the functions we want to test. using signFunc = Json::Value (*)( @@ -2773,7 +2773,7 @@ public: static Role const testedRoles[] = { Role::GUEST, Role::USER, Role::ADMIN, Role::FORBID}; - for (Role testRole : testedRoles) + for (Role const testRole : testedRoles) { Json::Value result; auto const signFn = get<0>(testFunc); diff --git a/src/test/rpc/KeyGeneration_test.cpp b/src/test/rpc/KeyGeneration_test.cpp index e4af2608b7..87d2ded7ad 100644 --- a/src/test/rpc/KeyGeneration_test.cpp +++ b/src/test/rpc/KeyGeneration_test.cpp @@ -98,7 +98,7 @@ public: params.isMember(jss::key_type) ? params[jss::key_type] : "secp256k1"); BEAST_EXPECT(!result.isMember(jss::warning)); - std::string seed = result[jss::master_seed].asString(); + std::string const seed = result[jss::master_seed].asString(); result = walletPropose(params); diff --git a/src/test/rpc/LedgerEntry_test.cpp b/src/test/rpc/LedgerEntry_test.cpp index 474f29da17..bd053d71c9 100644 --- a/src/test/rpc/LedgerEntry_test.cpp +++ b/src/test/rpc/LedgerEntry_test.cpp @@ -172,7 +172,7 @@ class LedgerEntry_test : public beast::unit_test::suite }; auto remove = [&](std::vector indices) -> std::vector { - std::unordered_set indexSet(indices.begin(), indices.end()); + std::unordered_set const indexSet(indices.begin(), indices.end()); std::vector values; values.reserve(allBadValues.size() - indexSet.size()); for (std::size_t i = 0; i < allBadValues.size(); ++i) @@ -595,7 +595,7 @@ class LedgerEntry_test : public beast::unit_test::suite } { // Check malformed cases - Json::Value jvParams; + Json::Value const jvParams; testMalformedField( env, jvParams, jss::account_root, FieldType::AccountField, "malformedAddress"); } @@ -699,7 +699,7 @@ class LedgerEntry_test : public beast::unit_test::suite Account const alice{"alice"}; env.fund(XRP(10000), alice); env.close(); - AMM amm(env, alice, XRP(10), alice["USD"](1000)); + AMM const amm(env, alice, XRP(10), alice["USD"](1000)); env.close(); { @@ -1961,7 +1961,7 @@ class LedgerEntry_test : public beast::unit_test::suite } { // Malformed DID index - Json::Value jvParams; + Json::Value const jvParams; testMalformedField( env, jvParams, jss::did, FieldType::AccountField, "malformedAddress"); } @@ -1977,7 +1977,7 @@ class LedgerEntry_test : public beast::unit_test::suite Env env(*this); Account const owner("owner"); env.fund(XRP(1'000), owner); - Oracle oracle( + Oracle const oracle( env, {.owner = owner, .fee = static_cast(env.current()->fees().base.drops())}); { @@ -2008,11 +2008,11 @@ class LedgerEntry_test : public beast::unit_test::suite Account const owner(std::string("owner") + std::to_string(i)); env.fund(XRP(1'000), owner); // different accounts can have the same asset pair - Oracle oracle(env, {.owner = owner, .documentID = i, .fee = baseFee}); + Oracle const oracle(env, {.owner = owner, .documentID = i, .fee = baseFee}); accounts.push_back(owner.id()); oracles.push_back(oracle.documentID()); // same account can have different asset pair - Oracle oracle1(env, {.owner = owner, .documentID = i + 10, .fee = baseFee}); + Oracle const oracle1(env, {.owner = owner, .documentID = i + 10, .fee = baseFee}); accounts.push_back(owner.id()); oracles.push_back(oracle1.documentID()); } @@ -2102,7 +2102,7 @@ class LedgerEntry_test : public beast::unit_test::suite } { // Malformed MPTIssuance index - Json::Value jvParams; + Json::Value const jvParams; testMalformedField( env, jvParams, jss::mptoken, FieldType::HashOrObjectField, "malformedRequest"); } diff --git a/src/test/rpc/LedgerRequest_test.cpp b/src/test/rpc/LedgerRequest_test.cpp index 18c717ec19..4462c1f039 100644 --- a/src/test/rpc/LedgerRequest_test.cpp +++ b/src/test/rpc/LedgerRequest_test.cpp @@ -102,7 +102,7 @@ public: } { - std::string ledgerHash(64, 'q'); + std::string const ledgerHash(64, 'q'); auto const result = env.rpc("ledger_request", ledgerHash); @@ -113,7 +113,7 @@ public: } { - std::string ledgerHash(64, '1'); + std::string const ledgerHash(64, '1'); auto const result = env.rpc("ledger_request", ledgerHash); diff --git a/src/test/rpc/Peers_test.cpp b/src/test/rpc/Peers_test.cpp index de46fd766c..984e767516 100644 --- a/src/test/rpc/Peers_test.cpp +++ b/src/test/rpc/Peers_test.cpp @@ -31,7 +31,7 @@ class Peers_test : public beast::unit_test::suite { auto kp = generateKeyPair(KeyType::secp256k1, generateSeed("seed" + std::to_string(i))); - std::string name = "Node " + std::to_string(i); + std::string const name = "Node " + std::to_string(i); using namespace std::chrono_literals; env.app().getCluster().update(kp.first, name, 200, env.timeKeeper().now() - 10s); diff --git a/src/test/rpc/RPCCall_test.cpp b/src/test/rpc/RPCCall_test.cpp index e4ef3aca6a..ae876dded4 100644 --- a/src/test/rpc/RPCCall_test.cpp +++ b/src/test/rpc/RPCCall_test.cpp @@ -5854,7 +5854,7 @@ public: apiVersion <= RPC::apiMaximumValidVersion)) return; - test::jtx::Env env(*this, makeNetworkConfig(11111)); // Used only for its Journal. + test::jtx::Env const env(*this, makeNetworkConfig(11111)); // Used only for its Journal. // For each RPCCall test. for (RPCCallTestData const& rpcCallTest : rpcCallTestArray) diff --git a/src/test/rpc/Simulate_test.cpp b/src/test/rpc/Simulate_test.cpp index e096b0479f..0581313e7a 100644 --- a/src/test/rpc/Simulate_test.cpp +++ b/src/test/rpc/Simulate_test.cpp @@ -1127,7 +1127,7 @@ class Simulate_test : public beast::unit_test::suite tx[jss::TransactionType] = jss::NFTokenMint; tx[sfNFTokenTaxon] = 1; - Json::Value nftokenId = to_string(token::getNextID(env, alice, 1)); + Json::Value const nftokenId = to_string(token::getNextID(env, alice, 1)); // test nft synthetic testTxJsonMetadataField(env, tx, validateOutput, jss::nftoken_id, nftokenId); } @@ -1137,7 +1137,7 @@ class Simulate_test : public beast::unit_test::suite tx[jss::Account] = alice.human(); tx[jss::TransactionType] = jss::MPTokenIssuanceCreate; - Json::Value mptIssuanceId = to_string(makeMptID(env.seq(alice), alice)); + Json::Value const mptIssuanceId = to_string(makeMptID(env.seq(alice), alice)); // test mpt issuance id testTxJsonMetadataField( env, tx, validateOutput, jss::mpt_issuance_id, mptIssuanceId); diff --git a/src/test/rpc/Status_test.cpp b/src/test/rpc/Status_test.cpp index 01fc81430f..a4a7b8c961 100644 --- a/src/test/rpc/Status_test.cpp +++ b/src/test/rpc/Status_test.cpp @@ -136,7 +136,8 @@ private: expect(m == message, m + " != " + message); auto d = error[jss::data]; - size_t s1 = d.size(), s2 = messages.size(); + size_t const s1 = d.size(); + size_t const s2 = messages.size(); expect( s1 == s2, prefix + "Data sizes differ " + std::to_string(s1) + " != " + std::to_string(s2)); diff --git a/src/test/rpc/Subscribe_test.cpp b/src/test/rpc/Subscribe_test.cpp index e96286aefc..bf52bde7aa 100644 --- a/src/test/rpc/Subscribe_test.cpp +++ b/src/test/rpc/Subscribe_test.cpp @@ -461,7 +461,7 @@ public: if (!jv.isMember(jss::validated_hash)) return false; - uint32_t netID = env.app().getNetworkIDService().getNetworkID(); + uint32_t const netID = env.app().getNetworkIDService().getNetworkID(); if (!jv.isMember(jss::network_id) || jv[jss::network_id] != netID) return false; @@ -784,9 +784,9 @@ public: using IdxHashVec = std::vector>; Account alice("alice"); - Account bob("bob"); + Account const bob("bob"); Account carol("carol"); - Account david("david"); + Account const david("david"); /////////////////////////////////////////////////////////////////// /* @@ -820,8 +820,8 @@ public: idx = r[jss::account_history_tx_index].asInt(); if (r.isMember(jss::account_history_tx_first)) first_flag = true; - bool boundary = r.isMember(jss::account_history_boundary); - int ledger_idx = r[jss::ledger_index].asInt(); + bool const boundary = r.isMember(jss::account_history_boundary); + int const ledger_idx = r[jss::ledger_index].asInt(); if (r.isMember(jss::transaction) && r[jss::transaction].isMember(jss::hash)) { auto t{r[jss::transaction]}; @@ -932,7 +932,7 @@ public: // (-10, "E5B8B...", true, 4 auto checkBoundary = [](IdxHashVec const& vec, bool /* forward */) { - size_t num_tx = vec.size(); + size_t const num_tx = vec.size(); for (size_t i = 0; i < num_tx; ++i) { auto [idx, hash, boundary, ledger] = vec[i]; @@ -1075,7 +1075,7 @@ public: auto wscAccount = makeWSClient(env.app().config()); auto wscTxHistory = makeWSClient(env.app().config()); - std::array accounts = {alice, bob}; + std::array const accounts = {alice, bob}; env.fund(XRP(222222), accounts); BEAST_EXPECT(env.syncClose()); @@ -1143,7 +1143,7 @@ public: Env env(*this, single_thread_io(envconfig())); auto const USD_a = alice["USD"]; - std::array accounts = {alice, carol}; + std::array const accounts = {alice, carol}; env.fund(XRP(333333), accounts); env.trust(USD_a(20000), carol); BEAST_EXPECT(env.syncClose()); @@ -1180,7 +1180,7 @@ public: * long transaction history */ Env env(*this, single_thread_io(envconfig())); - std::array accounts = {alice, carol}; + std::array const accounts = {alice, carol}; env.fund(XRP(444444), accounts); BEAST_EXPECT(env.syncClose()); @@ -1234,7 +1234,7 @@ public: featurePermissionedDEX}; Env env(*this, single_thread_io(envconfig()), all); - PermissionedDEX permDex(env); + PermissionedDEX const permDex(env); auto const alice = permDex.alice; auto const bob = permDex.bob; auto const carol = permDex.carol; diff --git a/src/test/rpc/TransactionEntry_test.cpp b/src/test/rpc/TransactionEntry_test.cpp index 14e75d04da..6421587478 100644 --- a/src/test/rpc/TransactionEntry_test.cpp +++ b/src/test/rpc/TransactionEntry_test.cpp @@ -211,8 +211,8 @@ class TransactionEntry_test : public beast::unit_test::suite BEAST_EXPECT(clHash["result"] == resIndex); }; - Account A1{"A1"}; - Account A2{"A2"}; + Account const A1{"A1"}; + Account const A2{"A2"}; env.fund(XRP(10000), A1); auto fund_1_tx = to_string(env.tx()->getTransactionID()); diff --git a/src/test/rpc/Transaction_test.cpp b/src/test/rpc/Transaction_test.cpp index c53207e04d..9f06607729 100644 --- a/src/test/rpc/Transaction_test.cpp +++ b/src/test/rpc/Transaction_test.cpp @@ -283,7 +283,7 @@ class Transaction_test : public beast::unit_test::suite char const* EXCESSIVE = RPC::get_error_info(rpcEXCESSIVE_LGR_RANGE).token; Env env{*this, makeNetworkConfig(11111)}; - uint32_t netID = env.app().getNetworkIDService().getNetworkID(); + uint32_t const netID = env.app().getNetworkIDService().getNetworkID(); auto const alice = Account("alice"); env.fund(XRP(1000), alice); @@ -306,7 +306,7 @@ class Transaction_test : public beast::unit_test::suite { auto const& tx = txns[i]; auto const& meta = metas[i]; - uint32_t txnIdx = meta->getFieldU32(sfTransactionIndex); + uint32_t const txnIdx = meta->getFieldU32(sfTransactionIndex); auto const result = env.rpc( COMMAND, // NOLINTNEXTLINE(bugprone-unchecked-optional-access) @@ -347,7 +347,7 @@ class Transaction_test : public beast::unit_test::suite { // auto const& tx = txns[i]; auto const& meta = metas[i]; - uint32_t txnIdx = meta->getFieldU32(sfTransactionIndex); + uint32_t const txnIdx = meta->getFieldU32(sfTransactionIndex); auto const result = env.rpc( COMMAND, // NOLINTNEXTLINE(bugprone-unchecked-optional-access) @@ -407,7 +407,7 @@ class Transaction_test : public beast::unit_test::suite // field. (Tests parameter parsing) { auto const& meta = metas[0]; - uint32_t txnIdx = meta->getFieldU32(sfTransactionIndex); + uint32_t const txnIdx = meta->getFieldU32(sfTransactionIndex); auto const result = env.rpc( COMMAND, // NOLINTNEXTLINE(bugprone-unchecked-optional-access) @@ -500,7 +500,7 @@ class Transaction_test : public beast::unit_test::suite using namespace test::jtx; using std::to_string; - Env env{*this, makeNetworkConfig(11111)}; + Env const env{*this, makeNetworkConfig(11111)}; // Test case 1: Valid input values auto const expected11 = std::optional("CFFFFFFFFFFFFFFF"); @@ -583,7 +583,7 @@ class Transaction_test : public beast::unit_test::suite using namespace test::jtx; // Use a Concise Transaction Identifier to request a transaction. - for (uint32_t netID : {11111, 65535, 65536}) + for (uint32_t const netID : {11111, 65535, 65536}) { Env env{*this, makeNetworkConfig(netID)}; BEAST_EXPECT(netID == env.app().getNetworkIDService().getNetworkID()); @@ -655,7 +655,7 @@ class Transaction_test : public beast::unit_test::suite // test that if the network is 65535 the ctid is not in the response // Using a hash to request the transaction, test the network ID // boundary where the CTID is (not) in the response. - for (uint32_t netID : {2, 1024, 65535, 65536}) + for (uint32_t const netID : {2, 1024, 65535, 65536}) { Env env{*this, makeNetworkConfig(netID)}; BEAST_EXPECT(netID == env.app().getNetworkIDService().getNetworkID()); @@ -691,7 +691,7 @@ class Transaction_test : public beast::unit_test::suite // test the wrong network ID was submitted { Env env{*this, makeNetworkConfig(21337)}; - uint32_t netID = env.app().getNetworkIDService().getNetworkID(); + uint32_t const netID = env.app().getNetworkIDService().getNetworkID(); auto const alice = Account("alice"); auto const bob = Account("bob"); @@ -743,9 +743,9 @@ class Transaction_test : public beast::unit_test::suite // Payment env(pay(alice, gw, XRP(100))); - std::shared_ptr txn = env.tx(); + std::shared_ptr const txn = env.tx(); env.close(); - std::shared_ptr meta = + std::shared_ptr const meta = env.closed()->txRead(env.tx()->getTransactionID()).second; Json::Value expected = txn->getJson(JsonOptions::none); @@ -817,7 +817,8 @@ class Transaction_test : public beast::unit_test::suite to_string(txn->getTransactionID()) == "3F8BDE5A5F82C4F4708E5E9255B713E303E6E1A371FD5C7A704AFD1387C23981"); env.close(); - std::shared_ptr meta = env.closed()->txRead(txn->getTransactionID()).second; + std::shared_ptr const meta = + env.closed()->txRead(txn->getTransactionID()).second; std::string const expected_tx_blob = serializeHex(*txn); std::string const expected_meta_blob = serializeHex(*meta); diff --git a/src/test/rpc/ValidatorRPC_test.cpp b/src/test/rpc/ValidatorRPC_test.cpp index eece5c4448..6c6a75dd01 100644 --- a/src/test/rpc/ValidatorRPC_test.cpp +++ b/src/test/rpc/ValidatorRPC_test.cpp @@ -27,7 +27,7 @@ public: for (bool const isAdmin : {true, false}) { - for (std::string cmd : {"validators", "validator_list_sites"}) + for (std::string const cmd : {"validators", "validator_list_sites"}) { Env env{*this, isAdmin ? envconfig() : envconfig(no_admin)}; env.set_retries(isAdmin ? 5 : 0); @@ -154,7 +154,7 @@ public: }; // Validator keys that will be in the published list - std::vector validators = { + std::vector const validators = { TrustedPublisherServer::randomValidator(), TrustedPublisherServer::randomValidator()}; std::set expectedKeys; for (auto const& val : validators) diff --git a/src/test/rpc/Version_test.cpp b/src/test/rpc/Version_test.cpp index 7fa6720f83..c12e397459 100644 --- a/src/test/rpc/Version_test.cpp +++ b/src/test/rpc/Version_test.cpp @@ -77,13 +77,13 @@ class Version_test : public beast::unit_test::suite { testcase("test getAPIVersionNumber function"); - unsigned int versionIfUnspecified = + unsigned int const versionIfUnspecified = RPC::apiVersionIfUnspecified < RPC::apiMinimumSupportedVersion ? RPC::apiInvalidVersion : RPC::apiVersionIfUnspecified; - Json::Value j_array = Json::Value(Json::arrayValue); - Json::Value j_null = Json::Value(Json::nullValue); + Json::Value const j_array = Json::Value(Json::arrayValue); + Json::Value const j_null = Json::Value(Json::nullValue); BEAST_EXPECT(RPC::getAPIVersionNumber(j_array, false) == versionIfUnspecified); BEAST_EXPECT(RPC::getAPIVersionNumber(j_null, false) == versionIfUnspecified); @@ -185,7 +185,7 @@ class Version_test : public beast::unit_test::suite { testcase("config test"); { - Config c; + Config const c; BEAST_EXPECT(c.BETA_RPC_API == false); } diff --git a/src/test/server/ServerStatus_test.cpp b/src/test/server/ServerStatus_test.cpp index 1a5da25d65..b7c9825a55 100644 --- a/src/test/server/ServerStatus_test.cpp +++ b/src/test/server/ServerStatus_test.cpp @@ -572,7 +572,7 @@ class ServerStatus_test : public beast::unit_test::suite, public beast::test::en // for zero limit, pick an arbitrary nonzero number of clients - all // should connect fine. - int testTo = (limit == 0) ? 50 : limit + 1; + int const testTo = (limit == 0) ? 50 : limit + 1; while (connectionCount < testTo) { clients.emplace_back( @@ -1106,7 +1106,7 @@ class ServerStatus_test : public beast::unit_test::suite, public beast::test::en boost::system::error_code ec; doHTTPRequest(env, yield, false, resp, ec); BEAST_EXPECT(resp.result() == boost::beast::http::status::internal_server_error); - std::regex body{"Server cannot accept clients"}; + std::regex const body{"Server cannot accept clients"}; BEAST_EXPECT(std::regex_search(resp.body(), body)); } diff --git a/src/test/server/Server_test.cpp b/src/test/server/Server_test.cpp index b6ff180bd4..97a822fd76 100644 --- a/src/test/server/Server_test.cpp +++ b/src/test/server/Server_test.cpp @@ -282,7 +282,7 @@ public: TestSink sink{*this}; TestThread thread; sink.threshold(beast::severities::Severity::kAll); - beast::Journal journal{sink}; + beast::Journal const journal{sink}; TestHandler handler; auto s = make_Server(handler, thread.get_io_context(), journal); std::vector serverPort(1); @@ -377,7 +377,7 @@ public: std::string messages; except([&] { - Env env{ + Env const env{ *this, envconfig([](std::unique_ptr cfg) { (*cfg).deprecatedClearSection("port_rpc"); @@ -388,7 +388,7 @@ public: BEAST_EXPECT(messages.find("Missing 'ip' in [port_rpc]") != std::string::npos); except([&] { - Env env{ + Env const env{ *this, envconfig([](std::unique_ptr cfg) { (*cfg).deprecatedClearSection("port_rpc"); @@ -400,7 +400,7 @@ public: BEAST_EXPECT(messages.find("Missing 'port' in [port_rpc]") != std::string::npos); except([&] { - Env env{ + Env const env{ *this, envconfig([](std::unique_ptr cfg) { (*cfg).deprecatedClearSection("port_rpc"); @@ -414,7 +414,7 @@ public: messages.find("Invalid value '0' for key 'port' in [port_rpc]") == std::string::npos); except([&] { - Env env{ + Env const env{ *this, envconfig([](std::unique_ptr cfg) { (*cfg)["server"].set("port", "0"); @@ -426,7 +426,7 @@ public: messages.find("Invalid value '0' for key 'port' in [server]") != std::string::npos); except([&] { - Env env{ + Env const env{ *this, envconfig([](std::unique_ptr cfg) { (*cfg).deprecatedClearSection("port_rpc"); @@ -442,7 +442,7 @@ public: except([&] // this creates a standard test config without the server // section { - Env env{ + Env const env{ *this, envconfig([](std::unique_ptr cfg) { cfg = std::make_unique(); @@ -471,7 +471,7 @@ public: except([&] // this creates a standard test config without some of the // port sections { - Env env{ + Env const env{ *this, envconfig([](std::unique_ptr cfg) { cfg = std::make_unique(); diff --git a/src/test/shamap/FetchPack_test.cpp b/src/test/shamap/FetchPack_test.cpp index ad86e066af..1cf7d97b33 100644 --- a/src/test/shamap/FetchPack_test.cpp +++ b/src/test/shamap/FetchPack_test.cpp @@ -53,7 +53,7 @@ public: std::optional getNode(SHAMapHash const& nodeHash) const override { - Map::iterator it = mMap.find(nodeHash); + Map::iterator const it = mMap.find(nodeHash); if (it == mMap.end()) { JLOG(mJournal.fatal()) << "Test filter missing node"; @@ -100,7 +100,7 @@ public: test::SuiteJournal journal("FetchPack_test", *this); TestNodeFamily f(journal); - std::shared_ptr t1(std::make_shared
(SHAMapType::FREE, f)); + std::shared_ptr
const t1(std::make_shared
(SHAMapType::FREE, f)); pass(); diff --git a/src/test/shamap/SHAMapSync_test.cpp b/src/test/shamap/SHAMapSync_test.cpp index a8f3a478b2..6374e49e71 100644 --- a/src/test/shamap/SHAMapSync_test.cpp +++ b/src/test/shamap/SHAMapSync_test.cpp @@ -30,7 +30,7 @@ public: { // add a bunch of random states to a map, then remove them // map should be the same - SHAMapHash beforeHash = map.getHash(); + SHAMapHash const beforeHash = map.getHash(); std::list items; @@ -74,7 +74,7 @@ public: SHAMap source(SHAMapType::FREE, f); SHAMap destination(SHAMapType::FREE, f2); - int items = 10000; + int const items = 10000; for (int i = 0; i < items; ++i) { source.addItem(SHAMapNodeType::tnACCOUNT_STATE, makeRandomAS()); @@ -96,10 +96,6 @@ public: source.walkMap(missingNodes, 2048); BEAST_EXPECT(missingNodes.empty()); - std::vector nodeIDs, gotNodeIDs; - std::vector gotNodes; - std::vector hashes; - destination.setSynching(); { diff --git a/src/test/shamap/SHAMap_test.cpp b/src/test/shamap/SHAMap_test.cpp index b16f7b157f..1c6d62be97 100644 --- a/src/test/shamap/SHAMap_test.cpp +++ b/src/test/shamap/SHAMap_test.cpp @@ -175,8 +175,8 @@ public: testcase("snapshot unbacked"); } - SHAMapHash mapHash = sMap.getHash(); - std::shared_ptr map2 = sMap.snapShot(false); + SHAMapHash const mapHash = sMap.getHash(); + std::shared_ptr const map2 = sMap.snapShot(false); map2->invariants(); unexpected(sMap.getHash() != mapHash, "bad snapshot"); unexpected(map2->getHash() != mapHash, "bad snapshot"); @@ -370,7 +370,7 @@ class SHAMapPathProof_test : public beast::unit_test::suite path->insert(path->begin(), path->front()); BEAST_EXPECT(!map.verifyProofPath(root, k, *path)); // wrong key - uint256 wrongKey(c + 1); + uint256 const wrongKey(c + 1); BEAST_EXPECT(!map.getProofPath(wrongKey)); } if (c == 99) diff --git a/src/test/unit_test/SuiteJournal.h b/src/test/unit_test/SuiteJournal.h index 08c40af43d..93005401e6 100644 --- a/src/test/unit_test/SuiteJournal.h +++ b/src/test/unit_test/SuiteJournal.h @@ -70,7 +70,7 @@ SuiteJournalSink::writeAlways(beast::severities::Severity level, std::string con }(); static std::mutex log_mutex; - std::lock_guard lock(log_mutex); + std::lock_guard const lock(log_mutex); suite_.log << s << partition_ << text << std::endl; } diff --git a/src/test/unit_test/multi_runner.cpp b/src/test/unit_test/multi_runner.cpp index 239564bd7c..e4fb1c4f45 100644 --- a/src/test/unit_test/multi_runner.cpp +++ b/src/test/unit_test/multi_runner.cpp @@ -154,7 +154,7 @@ template std::size_t multi_runner_base::inner::tests() const { - std::lock_guard l{m_}; + std::lock_guard const l{m_}; return results_.total; } @@ -162,7 +162,7 @@ template std::size_t multi_runner_base::inner::suites() const { - std::lock_guard l{m_}; + std::lock_guard const l{m_}; return results_.suites; } @@ -184,7 +184,7 @@ template void multi_runner_base::inner::add(results const& r) { - std::lock_guard l{m_}; + std::lock_guard const l{m_}; results_.merge(r); } @@ -193,7 +193,7 @@ template void multi_runner_base::inner::print_results(S& s) { - std::lock_guard l{m_}; + std::lock_guard const l{m_}; results_.print(s); } @@ -326,7 +326,7 @@ void multi_runner_base::message_queue_send(MessageType mt, std::string const& s) { // must use a mutex since the two "sends" must happen in order - std::lock_guard l{inner_->m_}; + std::lock_guard const l{inner_->m_}; message_queue_->send(&mt, sizeof(mt), /*priority*/ 0); message_queue_->send(s.c_str(), s.size(), /*priority*/ 0); } @@ -386,7 +386,7 @@ multi_runner_parent::multi_runner_parent() : os_(std::cout) if (!recvd_size) continue; assert(recvd_size == 1); - MessageType mt{*reinterpret_cast(buf.data())}; + MessageType const mt{*reinterpret_cast(buf.data())}; this->message_queue_->receive(buf.data(), buf.size(), recvd_size, priority); if (recvd_size) diff --git a/src/tests/libxrpl/basics/MallocTrim.cpp b/src/tests/libxrpl/basics/MallocTrim.cpp index 483cf37fe2..93ed48b885 100644 --- a/src/tests/libxrpl/basics/MallocTrim.cpp +++ b/src/tests/libxrpl/basics/MallocTrim.cpp @@ -52,8 +52,8 @@ TEST(parseStatmRSSkB, standard_format) // Test standard format: size resident shared text lib data dt // Assuming 4KB page size: resident=1000 pages = 4000 KB { - std::string statm = "25365 1000 2377 0 0 5623 0"; - long result = parseStatmRSSkB(statm); + std::string const statm = "25365 1000 2377 0 0 5623 0"; + long const result = parseStatmRSSkB(statm); // Note: actual result depends on system page size // On most systems it's 4KB, so 1000 pages = 4000 KB EXPECT_GT(result, 0); @@ -61,57 +61,57 @@ TEST(parseStatmRSSkB, standard_format) // Test with newline { - std::string statm = "12345 2000 1234 0 0 3456 0\n"; - long result = parseStatmRSSkB(statm); + std::string const statm = "12345 2000 1234 0 0 3456 0\n"; + long const result = parseStatmRSSkB(statm); EXPECT_GT(result, 0); } // Test with tabs { - std::string statm = "12345\t2000\t1234\t0\t0\t3456\t0"; - long result = parseStatmRSSkB(statm); + std::string const statm = "12345\t2000\t1234\t0\t0\t3456\t0"; + long const result = parseStatmRSSkB(statm); EXPECT_GT(result, 0); } // Test zero resident pages { - std::string statm = "25365 0 2377 0 0 5623 0"; - long result = parseStatmRSSkB(statm); + std::string const statm = "25365 0 2377 0 0 5623 0"; + long const result = parseStatmRSSkB(statm); EXPECT_EQ(result, 0); } // Test with extra whitespace { - std::string statm = " 25365 1000 2377 "; - long result = parseStatmRSSkB(statm); + std::string const statm = " 25365 1000 2377 "; + long const result = parseStatmRSSkB(statm); EXPECT_GT(result, 0); } // Test empty string { - std::string statm; - long result = parseStatmRSSkB(statm); + std::string const statm; + long const result = parseStatmRSSkB(statm); EXPECT_EQ(result, -1); } // Test malformed data (only one field) { - std::string statm = "25365"; - long result = parseStatmRSSkB(statm); + std::string const statm = "25365"; + long const result = parseStatmRSSkB(statm); EXPECT_EQ(result, -1); } // Test malformed data (non-numeric) { - std::string statm = "abc def ghi"; - long result = parseStatmRSSkB(statm); + std::string const statm = "abc def ghi"; + long const result = parseStatmRSSkB(statm); EXPECT_EQ(result, -1); } // Test malformed data (second field non-numeric) { - std::string statm = "25365 abc 2377"; - long result = parseStatmRSSkB(statm); + std::string const statm = "25365 abc 2377"; + long const result = parseStatmRSSkB(statm); EXPECT_EQ(result, -1); } } @@ -119,9 +119,9 @@ TEST(parseStatmRSSkB, standard_format) TEST(mallocTrim, without_debug_logging) { - beast::Journal journal{beast::Journal::getNullSink()}; + beast::Journal const journal{beast::Journal::getNullSink()}; - MallocTrimReport report = mallocTrim("without_debug", journal); + MallocTrimReport const report = mallocTrim("without_debug", journal); #if defined(__GLIBC__) && BOOST_OS_LINUX EXPECT_EQ(report.supported, true); @@ -142,8 +142,8 @@ TEST(mallocTrim, without_debug_logging) TEST(mallocTrim, empty_tag) { - beast::Journal journal{beast::Journal::getNullSink()}; - MallocTrimReport report = mallocTrim("", journal); + beast::Journal const journal{beast::Journal::getNullSink()}; + MallocTrimReport const report = mallocTrim("", journal); #if defined(__GLIBC__) && BOOST_OS_LINUX EXPECT_EQ(report.supported, true); @@ -171,9 +171,9 @@ TEST(mallocTrim, with_debug_logging) }; DebugSink sink; - beast::Journal journal{sink}; + beast::Journal const journal{sink}; - MallocTrimReport report = mallocTrim("debug_test", journal); + MallocTrimReport const report = mallocTrim("debug_test", journal); #if defined(__GLIBC__) && BOOST_OS_LINUX EXPECT_EQ(report.supported, true); @@ -192,12 +192,12 @@ TEST(mallocTrim, with_debug_logging) TEST(mallocTrim, repeated_calls) { - beast::Journal journal{beast::Journal::getNullSink()}; + beast::Journal const journal{beast::Journal::getNullSink()}; // Call malloc_trim multiple times to ensure it's safe for (int i = 0; i < 5; ++i) { - MallocTrimReport report = mallocTrim("iteration_" + std::to_string(i), journal); + MallocTrimReport const report = mallocTrim("iteration_" + std::to_string(i), journal); #if defined(__GLIBC__) && BOOST_OS_LINUX EXPECT_EQ(report.supported, true); diff --git a/src/tests/libxrpl/basics/Mutex.cpp b/src/tests/libxrpl/basics/Mutex.cpp index 3bcee92276..9f58799fe7 100644 --- a/src/tests/libxrpl/basics/Mutex.cpp +++ b/src/tests/libxrpl/basics/Mutex.cpp @@ -183,7 +183,7 @@ TEST_F(MutexConstCorrectnessTest, non_const_allows_modification) TEST_F(MutexConstCorrectnessTest, const_reference_provides_const_access) { - Mutex> m({1, 2, 3, 4, 5, 6}); + Mutex> const m({1, 2, 3, 4, 5, 6}); Mutex> const& const_ref = m; auto lock = const_ref.lock(); static_assert(std::is_const_v>); @@ -225,7 +225,7 @@ struct MutexSharedMutexTest : ::testing::Test TEST_F(MutexSharedMutexTest, shared_lock_for_const_access) { - Mutex m(100); + Mutex const m(100); Mutex const& const_ref = m; auto lock = const_ref.lock(); EXPECT_EQ(*lock, 100); diff --git a/src/tests/libxrpl/basics/scope.cpp b/src/tests/libxrpl/basics/scope.cpp index 8efa4a84b1..067698bce4 100644 --- a/src/tests/libxrpl/basics/scope.cpp +++ b/src/tests/libxrpl/basics/scope.cpp @@ -10,7 +10,7 @@ TEST(scope, scope_exit) // unless release() is called int i = 0; { - scope_exit x{[&i]() { i = 1; }}; + scope_exit const x{[&i]() { i = 1; }}; } EXPECT_EQ(i, 1); { @@ -32,7 +32,7 @@ TEST(scope, scope_exit) { try { - scope_exit x{[&i]() { i = 5; }}; + scope_exit const x{[&i]() { i = 5; }}; throw 1; } catch (...) // NOLINT(bugprone-empty-catch) @@ -60,7 +60,7 @@ TEST(scope, scope_fail) // if an exception is unwinding, unless release() is called int i = 0; { - scope_fail x{[&i]() { i = 1; }}; + scope_fail const x{[&i]() { i = 1; }}; } EXPECT_EQ(i, 0); { @@ -82,7 +82,7 @@ TEST(scope, scope_fail) { try { - scope_fail x{[&i]() { i = 5; }}; + scope_fail const x{[&i]() { i = 5; }}; throw 1; } catch (...) // NOLINT(bugprone-empty-catch) @@ -110,7 +110,7 @@ TEST(scope, scope_success) // if an exception is not unwinding, unless release() is called int i = 0; { - scope_success x{[&i]() { i = 1; }}; + scope_success const x{[&i]() { i = 1; }}; } EXPECT_EQ(i, 1); { @@ -132,7 +132,7 @@ TEST(scope, scope_success) { try { - scope_success x{[&i]() { i = 5; }}; + scope_success const x{[&i]() { i = 5; }}; throw 1; } catch (...) // NOLINT(bugprone-empty-catch) diff --git a/src/tests/libxrpl/basics/tagged_integer.cpp b/src/tests/libxrpl/basics/tagged_integer.cpp index 09f8b6787b..85a246428b 100644 --- a/src/tests/libxrpl/basics/tagged_integer.cpp +++ b/src/tests/libxrpl/basics/tagged_integer.cpp @@ -147,7 +147,7 @@ TEST(tagged_integer, increment_decrement_operators) TEST(tagged_integer, arithmetic_operators) { - TagInt a{-2}; + TagInt const a{-2}; EXPECT_EQ(+a, TagInt{-2}); EXPECT_EQ(-a, TagInt{2}); EXPECT_EQ(TagInt{-3} + TagInt{4}, TagInt{1}); diff --git a/src/tests/libxrpl/json/Value.cpp b/src/tests/libxrpl/json/Value.cpp index 943e517669..194c677024 100644 --- a/src/tests/libxrpl/json/Value.cpp +++ b/src/tests/libxrpl/json/Value.cpp @@ -38,7 +38,7 @@ TEST(json_value, construct_and_compare_Json_StaticString) EXPECT_EQ(test1, test2); EXPECT_NE(test1, test3); - std::string str{sample}; + std::string const str{sample}; EXPECT_EQ(str, test2); EXPECT_NE(str, test3); EXPECT_EQ(test2, str); @@ -52,7 +52,7 @@ TEST(json_value, different_types) auto testCopy = [](Json::ValueType typ) { Json::Value val{typ}; - Json::Value cpy{val}; + Json::Value const cpy{val}; EXPECT_EQ(val.type(), typ); EXPECT_EQ(cpy.type(), typ); return val; @@ -135,7 +135,7 @@ TEST(json_value, different_types) { Json::Value const staticStrV{staticStr}; { - Json::Value cpy{staticStrV}; + Json::Value const cpy{staticStrV}; EXPECT_EQ(staticStrV.type(), Json::stringValue); EXPECT_EQ(cpy.type(), Json::stringValue); } @@ -588,13 +588,13 @@ TEST(json_value, bad_json) TEST(json_value, edge_cases) { - std::uint32_t max_uint = std::numeric_limits::max(); - std::int32_t max_int = std::numeric_limits::max(); - std::int32_t min_int = std::numeric_limits::min(); + std::uint32_t const max_uint = std::numeric_limits::max(); + std::int32_t const max_int = std::numeric_limits::max(); + std::int32_t const min_int = std::numeric_limits::min(); - std::uint32_t a_uint = max_uint - 1978; - std::int32_t a_large_int = max_int - 1978; - std::int32_t a_small_int = min_int + 1978; + std::uint32_t const a_uint = max_uint - 1978; + std::int32_t const a_large_int = max_int - 1978; + std::int32_t const a_small_int = min_int + 1978; { std::string json = "{\"max_uint\":" + std::to_string(max_uint); @@ -628,7 +628,7 @@ TEST(json_value, edge_cases) EXPECT_LT(j1["a_small_int"], a_uint); } - std::uint64_t overflow = std::uint64_t(max_uint) + 1; + std::uint64_t const overflow = std::uint64_t(max_uint) + 1; { std::string json = "{\"overflow\":"; json += std::to_string(overflow); @@ -640,7 +640,7 @@ TEST(json_value, edge_cases) EXPECT_FALSE(r2.parse(json, j2)); } - std::int64_t underflow = std::int64_t(min_int) - 1; + std::int64_t const underflow = std::int64_t(min_int) - 1; { std::string json = "{\"underflow\":"; json += std::to_string(underflow); @@ -739,7 +739,7 @@ TEST(json_value, copy) EXPECT_TRUE(v1.isDouble()); EXPECT_EQ(v1.asDouble(), 2.5); - Json::Value v2 = v1; + Json::Value const v2 = v1; EXPECT_TRUE(v1.isDouble()); EXPECT_EQ(v1.asDouble(), 2.5); EXPECT_TRUE(v2.isDouble()); @@ -819,7 +819,7 @@ TEST(json_value, comparisons) b["a"] = Json::Int(-1); testGreaterThan("negative"); - Json::Int big = std::numeric_limits::max(); + Json::Int const big = std::numeric_limits::max(); Json::UInt bigger = big; bigger++; @@ -859,7 +859,7 @@ TEST(json_value, conversions) // TODO: What's the thinking here? { // null - Json::Value val; + Json::Value const val; EXPECT_TRUE(val.isNull()); // val.asCString() should trigger an assertion failure EXPECT_EQ(val.asString(), ""); @@ -880,7 +880,7 @@ TEST(json_value, conversions) } { // int - Json::Value val = -1234; + Json::Value const val = -1234; EXPECT_TRUE(val.isInt()); // val.asCString() should trigger an assertion failure EXPECT_EQ(val.asString(), "-1234"); @@ -901,7 +901,7 @@ TEST(json_value, conversions) } { // uint - Json::Value val = 1234U; + Json::Value const val = 1234U; EXPECT_TRUE(val.isUInt()); // val.asCString() should trigger an assertion failure EXPECT_EQ(val.asString(), "1234"); @@ -922,7 +922,7 @@ TEST(json_value, conversions) } { // real - Json::Value val = 2.0; + Json::Value const val = 2.0; EXPECT_TRUE(val.isDouble()); // val.asCString() should trigger an assertion failure EXPECT_TRUE(std::regex_match(val.asString(), std::regex("^2\\.0*$"))); @@ -943,7 +943,7 @@ TEST(json_value, conversions) } { // numeric string - Json::Value val = "54321"; + Json::Value const val = "54321"; EXPECT_TRUE(val.isString()); EXPECT_EQ(strcmp(val.asCString(), "54321"), 0); EXPECT_EQ(val.asString(), "54321"); @@ -964,7 +964,7 @@ TEST(json_value, conversions) } { // non-numeric string - Json::Value val(Json::stringValue); + Json::Value const val(Json::stringValue); EXPECT_TRUE(val.isString()); EXPECT_EQ(val.asCString(), nullptr); EXPECT_EQ(val.asString(), ""); @@ -985,7 +985,7 @@ TEST(json_value, conversions) } { // bool false - Json::Value val = false; + Json::Value const val = false; EXPECT_TRUE(val.isBool()); // val.asCString() should trigger an assertion failure EXPECT_EQ(val.asString(), "false"); @@ -1006,7 +1006,7 @@ TEST(json_value, conversions) } { // bool true - Json::Value val = true; + Json::Value const val = true; EXPECT_TRUE(val.isBool()); // val.asCString() should trigger an assertion failure EXPECT_EQ(val.asString(), "true"); @@ -1027,7 +1027,7 @@ TEST(json_value, conversions) } { // array type - Json::Value val(Json::arrayValue); + Json::Value const val(Json::arrayValue); EXPECT_TRUE(val.isArray()); // val.asCString should trigger an assertion failure EXPECT_THROW(val.asString(), Json::error); @@ -1048,7 +1048,7 @@ TEST(json_value, conversions) } { // object type - Json::Value val(Json::objectValue); + Json::Value const val(Json::objectValue); EXPECT_TRUE(val.isObject()); // val.asCString should trigger an assertion failure EXPECT_THROW(val.asString(), Json::error); diff --git a/src/tests/libxrpl/net/HTTPClient.cpp b/src/tests/libxrpl/net/HTTPClient.cpp index 36159cb089..de567a93ab 100644 --- a/src/tests/libxrpl/net/HTTPClient.cpp +++ b/src/tests/libxrpl/net/HTTPClient.cpp @@ -267,7 +267,7 @@ protected: TEST_F(HTTPClientTest, case_insensitive_content_length) { // Test different cases of Content-Length header - std::vector headerCases = { + std::vector const headerCases = { "Content-Length", // Standard case "content-length", // Lowercase - this tests the regex icase fix "CONTENT-LENGTH", // Uppercase @@ -278,7 +278,7 @@ TEST_F(HTTPClientTest, case_insensitive_content_length) for (auto const& headerName : headerCases) { TestHTTPServer server; - std::string testBody = "Hello World!"; + std::string const testBody = "Hello World!"; server.setResponseBody(testBody); server.setHeader(headerName, std::to_string(testBody.size())); @@ -287,7 +287,7 @@ TEST_F(HTTPClientTest, case_insensitive_content_length) std::string resultData; boost::system::error_code resultError; - bool testCompleted = + bool const testCompleted = runHTTPTest(server, "/test", completed, resultStatus, resultData, resultError); // Verify results EXPECT_TRUE(testCompleted); @@ -300,7 +300,7 @@ TEST_F(HTTPClientTest, case_insensitive_content_length) TEST_F(HTTPClientTest, basic_http_request) { TestHTTPServer server; - std::string testBody = "Test response body"; + std::string const testBody = "Test response body"; server.setResponseBody(testBody); server.setHeader("Content-Type", "text/plain"); @@ -309,7 +309,7 @@ TEST_F(HTTPClientTest, basic_http_request) std::string resultData; boost::system::error_code resultError; - bool testCompleted = + bool const testCompleted = runHTTPTest(server, "/basic", completed, resultStatus, resultData, resultError); EXPECT_TRUE(testCompleted); @@ -329,7 +329,7 @@ TEST_F(HTTPClientTest, empty_response) std::string resultData; boost::system::error_code resultError; - bool testCompleted = + bool const testCompleted = runHTTPTest(server, "/empty", completed, resultStatus, resultData, resultError); EXPECT_TRUE(testCompleted); @@ -340,7 +340,7 @@ TEST_F(HTTPClientTest, empty_response) TEST_F(HTTPClientTest, different_status_codes) { - std::vector statusCodes = {200, 404, 500}; + std::vector const statusCodes = {200, 404, 500}; for (auto status : statusCodes) { @@ -353,7 +353,7 @@ TEST_F(HTTPClientTest, different_status_codes) std::string resultData; boost::system::error_code resultError; - bool testCompleted = + bool const testCompleted = runHTTPTest(server, "/status", completed, resultStatus, resultData, resultError); EXPECT_TRUE(testCompleted); diff --git a/src/tests/libxrpl/protocol_autogen/.clang-tidy b/src/tests/libxrpl/protocol_autogen/.clang-tidy new file mode 100644 index 0000000000..fbc003598d --- /dev/null +++ b/src/tests/libxrpl/protocol_autogen/.clang-tidy @@ -0,0 +1,3 @@ +# This disables all checks for this directory and its subdirectories +Checks: "-*" +InheritParentConfig: false diff --git a/src/tests/libxrpl/protocol_autogen/STObjectValidation.cpp b/src/tests/libxrpl/protocol_autogen/STObjectValidation.cpp deleted file mode 100644 index 5c100364dc..0000000000 --- a/src/tests/libxrpl/protocol_autogen/STObjectValidation.cpp +++ /dev/null @@ -1,70 +0,0 @@ -#include -#include -#include -#include - -#include - -namespace xrpl { -TEST(STObjectValidation, validate_required_field) -{ - SOTemplate format{{sfFlags, soeREQUIRED}}; - STObject obj(sfGeneric); - obj.setFieldU32(sfFlags, 0); - EXPECT_TRUE(protocol_autogen::validateSTObject(obj, format)); -} - -TEST(STObjectValidation, validate_missing_required_field) -{ - SOTemplate format{{sfFlags, soeREQUIRED}}; - STObject obj(sfGeneric); - EXPECT_FALSE(protocol_autogen::validateSTObject(obj, format)); -} - -TEST(STObjectValidation, validate_optional_field) -{ - SOTemplate format{{sfFlags, soeOPTIONAL}}; - STObject obj(sfGeneric); - obj.setFieldU32(sfFlags, 0); - EXPECT_TRUE(protocol_autogen::validateSTObject(obj, format)); -} - -TEST(STObjectValidation, validate_missing_optional_field) -{ - SOTemplate format{{sfFlags, soeOPTIONAL}}; - STObject obj(sfGeneric); - EXPECT_TRUE(protocol_autogen::validateSTObject(obj, format)); -} - -TEST(STObjectValidation, validate_mpt_amount_supported) -{ - SOTemplate format{{sfAmount, soeREQUIRED, soeMPTSupported}}; - STObject obj(sfGeneric); - obj.setFieldAmount(sfAmount, STAmount{MPTAmount{Number{1}}, MPTIssue{}}); - EXPECT_TRUE(protocol_autogen::validateSTObject(obj, format)); -} - -TEST(STObjectValidation, validate_mpt_amount_not_supported) -{ - SOTemplate format{{sfAmount, soeREQUIRED, soeMPTNotSupported}}; - STObject obj(sfGeneric); - obj.setFieldAmount(sfAmount, STAmount{MPTAmount{Number{1}}, MPTIssue{}}); - EXPECT_FALSE(protocol_autogen::validateSTObject(obj, format)); -} - -TEST(STObjectValidation, validate_mpt_issue_supported) -{ - SOTemplate format{{sfAsset, soeREQUIRED, soeMPTSupported}}; - STObject obj(sfGeneric); - obj.setFieldIssue(sfAsset, STIssue{sfAsset, MPTIssue{}}); - EXPECT_TRUE(protocol_autogen::validateSTObject(obj, format)); -} - -TEST(STObjectValidation, validate_mpt_issue_not_supported) -{ - SOTemplate format{{sfAsset, soeREQUIRED, soeMPTNotSupported}}; - STObject obj(sfGeneric); - obj.setFieldIssue(sfAsset, STIssue{sfAsset, MPTIssue{}}); - EXPECT_FALSE(protocol_autogen::validateSTObject(obj, format)); -} -} // namespace xrpl diff --git a/src/tests/libxrpl/protocol_autogen/main.cpp b/src/tests/libxrpl/protocol_autogen/main.cpp deleted file mode 100644 index 5142bbe08a..0000000000 --- a/src/tests/libxrpl/protocol_autogen/main.cpp +++ /dev/null @@ -1,8 +0,0 @@ -#include - -int -main(int argc, char** argv) -{ - ::testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); -} diff --git a/src/xrpld/app/consensus/RCLConsensus.cpp b/src/xrpld/app/consensus/RCLConsensus.cpp index 71f3d1cf2a..838529795b 100644 --- a/src/xrpld/app/consensus/RCLConsensus.cpp +++ b/src/xrpld/app/consensus/RCLConsensus.cpp @@ -160,7 +160,7 @@ RCLConsensus::Adaptor::share(RCLCxTx const& tx) msg.set_rawtransaction(slice.data(), slice.size()); msg.set_status(protocol::tsNEW); msg.set_receivetimestamp(app_.getTimeKeeper().now().time_since_epoch().count()); - static std::set skip{}; + static std::set const skip{}; app_.getOverlay().relay(tx.id(), msg, skip); } else @@ -853,7 +853,7 @@ RCLConsensus::getJson(bool full) const { Json::Value ret; { - std::lock_guard _{mutex_}; + std::lock_guard const _{mutex_}; ret = consensus_.getJson(full); } ret["validating"] = adaptor_.validating(); @@ -867,7 +867,7 @@ RCLConsensus::timerEntry( { try { - std::lock_guard _{mutex_}; + std::lock_guard const _{mutex_}; consensus_.timerEntry(now, clog); } catch (SHAMapMissingNode const& mn) @@ -886,7 +886,7 @@ RCLConsensus::gotTxSet(NetClock::time_point const& now, RCLTxSet const& txSet) { try { - std::lock_guard _{mutex_}; + std::lock_guard const _{mutex_}; consensus_.gotTxSet(now, txSet); } catch (SHAMapMissingNode const& mn) @@ -904,14 +904,14 @@ RCLConsensus::simulate( NetClock::time_point const& now, std::optional consensusDelay) { - std::lock_guard _{mutex_}; + std::lock_guard const _{mutex_}; consensus_.simulate(now, consensusDelay); } bool RCLConsensus::peerProposal(NetClock::time_point const& now, RCLCxPeerPos const& newProposal) { - std::lock_guard _{mutex_}; + std::lock_guard const _{mutex_}; return consensus_.peerProposal(now, newProposal); } @@ -1010,7 +1010,7 @@ RCLConsensus::startRound( hash_set const& nowTrusted, std::unique_ptr const& clog) { - std::lock_guard _{mutex_}; + std::lock_guard const _{mutex_}; consensus_.startRound( now, prevLgrId, prevLgr, nowUntrusted, adaptor_.preStartRound(prevLgr, nowTrusted), clog); } diff --git a/src/xrpld/app/consensus/RCLConsensus.h b/src/xrpld/app/consensus/RCLConsensus.h index 15d36a1aa6..c965ed3d87 100644 --- a/src/xrpld/app/consensus/RCLConsensus.h +++ b/src/xrpld/app/consensus/RCLConsensus.h @@ -472,7 +472,7 @@ public: RCLCxLedger::ID prevLedgerID() const { - std::lock_guard _{mutex_}; + std::lock_guard const _{mutex_}; return consensus_.prevLedgerID(); } diff --git a/src/xrpld/app/ledger/ConsensusTransSetSF.cpp b/src/xrpld/app/ledger/ConsensusTransSetSF.cpp index 2313d29f86..5fd614a1d9 100644 --- a/src/xrpld/app/ledger/ConsensusTransSetSF.cpp +++ b/src/xrpld/app/ledger/ConsensusTransSetSF.cpp @@ -36,7 +36,7 @@ ConsensusTransSetSF::gotNode( try { // skip prefix - Serializer s(nodeData.data() + 4, nodeData.size() - 4); + Serializer const s(nodeData.data() + 4, nodeData.size() - 4); SerialIter sit(s.slice()); auto stx = std::make_shared(std::ref(sit)); XRPL_ASSERT( diff --git a/src/xrpld/app/ledger/LedgerHistory.cpp b/src/xrpld/app/ledger/LedgerHistory.cpp index b96760f04d..969511db4c 100644 --- a/src/xrpld/app/ledger/LedgerHistory.cpp +++ b/src/xrpld/app/ledger/LedgerHistory.cpp @@ -40,7 +40,7 @@ LedgerHistory::insert(std::shared_ptr const& ledger, bool validate XRPL_ASSERT( ledger->stateMap().getHash().isNonZero(), "xrpl::LedgerHistory::insert : nonzero hash"); - std::unique_lock sl(m_ledgers_by_hash.peekMutex()); + std::unique_lock const sl(m_ledgers_by_hash.peekMutex()); bool const alreadyHad = m_ledgers_by_hash.canonicalize_replace_cache(ledger->header().hash, ledger); @@ -53,7 +53,7 @@ LedgerHistory::insert(std::shared_ptr const& ledger, bool validate LedgerHash LedgerHistory::getLedgerHash(LedgerIndex index) { - std::unique_lock sl(m_ledgers_by_hash.peekMutex()); + std::unique_lock const sl(m_ledgers_by_hash.peekMutex()); if (auto it = mLedgersByIndex.find(index); it != mLedgersByIndex.end()) return it->second; return {}; @@ -68,7 +68,7 @@ LedgerHistory::getLedgerBySeq(LedgerIndex index) if (it != mLedgersByIndex.end()) { - uint256 hash = it->second; + uint256 const hash = it->second; sl.unlock(); return getLedgerByHash(hash); } @@ -86,7 +86,7 @@ LedgerHistory::getLedgerBySeq(LedgerIndex index) { // Add this ledger to the local tracking by index - std::unique_lock sl(m_ledgers_by_hash.peekMutex()); + std::unique_lock const sl(m_ledgers_by_hash.peekMutex()); XRPL_ASSERT( ret->isImmutable(), "xrpl::LedgerHistory::getLedgerBySeq : immutable result ledger"); @@ -405,11 +405,11 @@ LedgerHistory::builtLedger( uint256 const& consensusHash, Json::Value consensus) { - LedgerIndex index = ledger->header().seq; - LedgerHash hash = ledger->header().hash; + LedgerIndex const index = ledger->header().seq; + LedgerHash const hash = ledger->header().hash; XRPL_ASSERT(!hash.isZero(), "xrpl::LedgerHistory::builtLedger : nonzero hash"); - std::unique_lock sl(m_consensus_validated.peekMutex()); + std::unique_lock const sl(m_consensus_validated.peekMutex()); auto entry = std::make_shared(); m_consensus_validated.canonicalize_replace_client(index, entry); @@ -444,11 +444,11 @@ LedgerHistory::validatedLedger( std::shared_ptr const& ledger, std::optional const& consensusHash) { - LedgerIndex index = ledger->header().seq; - LedgerHash hash = ledger->header().hash; + LedgerIndex const index = ledger->header().seq; + LedgerHash const hash = ledger->header().hash; XRPL_ASSERT(!hash.isZero(), "xrpl::LedgerHistory::validatedLedger : nonzero hash"); - std::unique_lock sl(m_consensus_validated.peekMutex()); + std::unique_lock const sl(m_consensus_validated.peekMutex()); auto entry = std::make_shared(); m_consensus_validated.canonicalize_replace_client(index, entry); @@ -482,7 +482,7 @@ LedgerHistory::validatedLedger( bool LedgerHistory::fixIndex(LedgerIndex ledgerIndex, LedgerHash const& ledgerHash) { - std::unique_lock sl(m_ledgers_by_hash.peekMutex()); + std::unique_lock const sl(m_ledgers_by_hash.peekMutex()); auto it = mLedgersByIndex.find(ledgerIndex); if ((it != mLedgersByIndex.end()) && (it->second != ledgerHash)) @@ -496,7 +496,7 @@ LedgerHistory::fixIndex(LedgerIndex ledgerIndex, LedgerHash const& ledgerHash) void LedgerHistory::clearLedgerCachePrior(LedgerIndex seq) { - for (LedgerHash it : m_ledgers_by_hash.getKeys()) + for (LedgerHash const it : m_ledgers_by_hash.getKeys()) { auto const ledger = getLedgerByHash(it); if (!ledger || ledger->header().seq < seq) diff --git a/src/xrpld/app/ledger/LedgerHolder.h b/src/xrpld/app/ledger/LedgerHolder.h index 8d2ac9f308..bf9d478c40 100644 --- a/src/xrpld/app/ledger/LedgerHolder.h +++ b/src/xrpld/app/ledger/LedgerHolder.h @@ -28,7 +28,7 @@ public: LogicError("LedgerHolder::set with nullptr"); if (!ledger->isImmutable()) LogicError("LedgerHolder::set with mutable Ledger"); - std::lock_guard sl(m_lock); + std::lock_guard const sl(m_lock); m_heldLedger = std::move(ledger); } @@ -36,14 +36,14 @@ public: std::shared_ptr get() { - std::lock_guard sl(m_lock); + std::lock_guard const sl(m_lock); return m_heldLedger; } bool empty() { - std::lock_guard sl(m_lock); + std::lock_guard const sl(m_lock); return m_heldLedger == nullptr; } diff --git a/src/xrpld/app/ledger/LedgerMaster.h b/src/xrpld/app/ledger/LedgerMaster.h index 16e35c3dcd..e598787047 100644 --- a/src/xrpld/app/ledger/LedgerMaster.h +++ b/src/xrpld/app/ledger/LedgerMaster.h @@ -387,7 +387,7 @@ private: void collect_metrics() { - std::lock_guard lock(m_mutex); + std::lock_guard const lock(m_mutex); m_stats.validatedLedgerAge.set(getValidatedLedgerAge().count()); m_stats.publishedLedgerAge.set(getPublishedLedgerAge().count()); } diff --git a/src/xrpld/app/ledger/LedgerReplayer.h b/src/xrpld/app/ledger/LedgerReplayer.h index 218d22fb07..ce2acb0699 100644 --- a/src/xrpld/app/ledger/LedgerReplayer.h +++ b/src/xrpld/app/ledger/LedgerReplayer.h @@ -103,21 +103,21 @@ public: std::size_t tasksSize() const { - std::lock_guard lock(mtx_); + std::lock_guard const lock(mtx_); return tasks_.size(); } std::size_t deltasSize() const { - std::lock_guard lock(mtx_); + std::lock_guard const lock(mtx_); return deltas_.size(); } std::size_t skipListsSize() const { - std::lock_guard lock(mtx_); + std::lock_guard const lock(mtx_); return skipLists_.size(); } diff --git a/src/xrpld/app/ledger/OrderBookDBImpl.cpp b/src/xrpld/app/ledger/OrderBookDBImpl.cpp index c8ea46cf7f..229110fa04 100644 --- a/src/xrpld/app/ledger/OrderBookDBImpl.cpp +++ b/src/xrpld/app/ledger/OrderBookDBImpl.cpp @@ -160,7 +160,7 @@ OrderBookDBImpl::update(std::shared_ptr const& ledger) JLOG(j_.debug()) << "Update completed (" << ledger->seq() << "): " << cnt << " books found"; { - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); allBooks_.swap(allBooks); xrpBooks_.swap(xrpBooks); domainBooks_.swap(domainBooks); @@ -173,9 +173,9 @@ OrderBookDBImpl::update(std::shared_ptr const& ledger) void OrderBookDBImpl::addOrderBook(Book const& book) { - bool toXRP = isXRP(book.out); + bool const toXRP = isXRP(book.out); - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); if (book.domain) { @@ -203,7 +203,7 @@ OrderBookDBImpl::getBooksByTakerPays(Issue const& issue, std::optional std::vector ret; { - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); auto getBooks = [&](auto const& container, auto const& key) { if (auto it = container.find(key); it != container.end()) @@ -232,7 +232,7 @@ OrderBookDBImpl::getBooksByTakerPays(Issue const& issue, std::optional int OrderBookDBImpl::getBookSize(Issue const& issue, std::optional const& domain) { - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); if (!domain) { @@ -251,7 +251,7 @@ OrderBookDBImpl::getBookSize(Issue const& issue, std::optional const& d bool OrderBookDBImpl::isBookToXRP(Issue const& issue, std::optional const& domain) { - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); if (domain) return xrpDomainBooks_.contains({issue, *domain}); return xrpBooks_.contains(issue); @@ -260,7 +260,7 @@ OrderBookDBImpl::isBookToXRP(Issue const& issue, std::optional const& do BookListeners::pointer OrderBookDBImpl::makeBookListeners(Book const& book) { - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); auto ret = getBookListeners(book); if (!ret) @@ -281,7 +281,7 @@ BookListeners::pointer OrderBookDBImpl::getBookListeners(Book const& book) { BookListeners::pointer ret; - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); auto it0 = mListeners.find(book); if (it0 != mListeners.end()) @@ -298,7 +298,7 @@ OrderBookDBImpl::processTxn( AcceptedLedgerTx const& alTx, MultiApiJson const& jvObj) { - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); // For this particular transaction, maintain the set of unique // subscriptions that have already published it. This prevents sending diff --git a/src/xrpld/app/ledger/detail/InboundLedger.cpp b/src/xrpld/app/ledger/detail/InboundLedger.cpp index 4e7190c8c8..69af55b8f3 100644 --- a/src/xrpld/app/ledger/detail/InboundLedger.cpp +++ b/src/xrpld/app/ledger/detail/InboundLedger.cpp @@ -127,7 +127,7 @@ InboundLedger::getPeerCount() const void InboundLedger::update(std::uint32_t seq) { - ScopedLockType sl(mtx_); + ScopedLockType const sl(mtx_); // If we didn't know the sequence number, but now do, save it if ((seq != 0) && (mSeq == 0)) @@ -140,7 +140,7 @@ InboundLedger::update(std::uint32_t seq) bool InboundLedger::checkLocal() { - ScopedLockType sl(mtx_); + ScopedLockType const sl(mtx_); if (!isDone()) { if (mLedger) @@ -363,7 +363,7 @@ InboundLedger::onTimer(bool wasProgress, ScopedLockType&) mByHash = true; - std::size_t pc = getPeerCount(); + std::size_t const pc = getPeerCount(); JLOG(journal_.debug()) << "No progress(" << pc << ") for ledger " << hash_; // addPeers triggers if the reason is not HISTORY @@ -996,7 +996,7 @@ InboundLedger::gotData( std::weak_ptr peer, std::shared_ptr const& data) { - std::lock_guard sl(mReceivedDataLock); + std::lock_guard const sl(mReceivedDataLock); if (isDone()) return false; @@ -1032,7 +1032,7 @@ InboundLedger::processData(std::shared_ptr peer, protocol::TMLedgerData& p SHAMapAddNode san; - ScopedLockType sl(mtx_); + ScopedLockType const sl(mtx_); try { @@ -1084,7 +1084,7 @@ InboundLedger::processData(std::shared_ptr peer, protocol::TMLedgerData& p return -1; } - ScopedLockType sl(mtx_); + ScopedLockType const sl(mtx_); // Verify node IDs and data are complete for (auto const& node : packet.nodes()) @@ -1208,7 +1208,7 @@ InboundLedger::runData() data.clear(); { - std::lock_guard sl(mReceivedDataLock); + std::lock_guard const sl(mReceivedDataLock); if (mReceivedData.empty()) { @@ -1223,7 +1223,7 @@ InboundLedger::runData() { if (auto peer = entry.first.lock()) { - int count = processData(peer, *(entry.second)); + int const count = processData(peer, *(entry.second)); dataCounts.update(std::move(peer), count); } } @@ -1242,7 +1242,7 @@ InboundLedger::getJson(int) { Json::Value ret(Json::objectValue); - ScopedLockType sl(mtx_); + ScopedLockType const sl(mtx_); ret[jss::hash] = to_string(hash_); diff --git a/src/xrpld/app/ledger/detail/InboundLedgers.cpp b/src/xrpld/app/ledger/detail/InboundLedgers.cpp index 3a83aa6018..f147a35ca4 100644 --- a/src/xrpld/app/ledger/detail/InboundLedgers.cpp +++ b/src/xrpld/app/ledger/detail/InboundLedgers.cpp @@ -110,7 +110,7 @@ public: if (pendingAcquires_.contains(hash)) return; pendingAcquires_.insert(hash); - scope_unlock unlock(lock); + scope_unlock const unlock(lock); acquire(hash, seq, reason); } catch (std::exception const& e) @@ -133,7 +133,7 @@ public: std::shared_ptr ret; { - ScopedLockType sl(mLock); + ScopedLockType const sl(mLock); auto it = mLedgers.find(hash); if (it != mLedgers.end()) @@ -197,7 +197,7 @@ public: void logFailure(uint256 const& h, std::uint32_t seq) override { - ScopedLockType sl(mLock); + ScopedLockType const sl(mLock); mRecentFailures.emplace(h, seq); } @@ -205,7 +205,7 @@ public: bool isFailure(uint256 const& h) override { - ScopedLockType sl(mLock); + ScopedLockType const sl(mLock); beast::expire(mRecentFailures, kReacquireInterval); return mRecentFailures.find(h) != mRecentFailures.end(); @@ -250,7 +250,7 @@ public: void clearFailures() override { - ScopedLockType sl(mLock); + ScopedLockType const sl(mLock); mRecentFailures.clear(); mLedgers.clear(); @@ -259,7 +259,7 @@ public: std::size_t fetchRate() override { - std::lock_guard lock(fetchRateMutex_); + std::lock_guard const lock(fetchRateMutex_); return 60 * fetchRate_.value(m_clock.now()); } @@ -268,7 +268,7 @@ public: void onLedgerFetched() override { - std::lock_guard lock(fetchRateMutex_); + std::lock_guard const lock(fetchRateMutex_); fetchRate_.add(1, m_clock.now()); } @@ -280,7 +280,7 @@ public: std::vector>> acqs; { - ScopedLockType sl(mLock); + ScopedLockType const sl(mLock); acqs.reserve(mLedgers.size()); for (auto const& it : mLedgers) @@ -304,7 +304,7 @@ public: for (auto const& it : acqs) { // getJson is expensive, so call without the lock - std::uint32_t seq = it.second->getSeq(); + std::uint32_t const seq = it.second->getSeq(); if (seq > 1) { ret[std::to_string(seq)] = it.second->getJson(0); @@ -323,7 +323,7 @@ public: { std::vector> acquires; { - ScopedLockType sl(mLock); + ScopedLockType const sl(mLock); acquires.reserve(mLedgers.size()); for (auto const& it : mLedgers) @@ -352,7 +352,7 @@ public: std::size_t total = 0; { - ScopedLockType sl(mLock); + ScopedLockType const sl(mLock); MapType::iterator it(mLedgers.begin()); total = mLedgers.size(); @@ -393,7 +393,7 @@ public: void stop() override { - ScopedLockType lock(mLock); + ScopedLockType const lock(mLock); stopping_ = true; mLedgers.clear(); mRecentFailures.clear(); @@ -402,7 +402,7 @@ public: std::size_t cacheSize() override { - ScopedLockType lock(mLock); + ScopedLockType const lock(mLock); return mLedgers.size(); } diff --git a/src/xrpld/app/ledger/detail/InboundTransactions.cpp b/src/xrpld/app/ledger/detail/InboundTransactions.cpp index 064953f665..cc3585a3fb 100644 --- a/src/xrpld/app/ledger/detail/InboundTransactions.cpp +++ b/src/xrpld/app/ledger/detail/InboundTransactions.cpp @@ -64,7 +64,7 @@ public: getAcquire(uint256 const& hash) { { - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); auto it = m_map.find(hash); @@ -80,7 +80,7 @@ public: TransactionAcquire::pointer ta; { - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); if (auto it = m_map.find(hash); it != m_map.end()) { @@ -118,12 +118,12 @@ public: std::shared_ptr peer, std::shared_ptr packet_ptr) override { - protocol::TMLedgerData& packet = *packet_ptr; + protocol::TMLedgerData const& packet = *packet_ptr; JLOG(j_.trace()) << "Got data (" << packet.nodes().size() << ") for acquiring ledger: " << hash; - TransactionAcquire::pointer ta = getAcquire(hash); + TransactionAcquire::pointer const ta = getAcquire(hash); if (ta == nullptr) { @@ -163,7 +163,7 @@ public: bool isNew = true; { - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); auto& inboundSet = m_map[hash]; @@ -188,7 +188,7 @@ public: void newRound(std::uint32_t seq) override { - std::lock_guard lock(mLock); + std::lock_guard const lock(mLock); // Protect zero set from expiration m_zeroSet.mSeq = seq; @@ -200,7 +200,7 @@ public: auto it = m_map.begin(); std::uint32_t const minSeq = (seq < setKeepRounds) ? 0 : (seq - setKeepRounds); - std::uint32_t maxSeq = seq + setKeepRounds; + std::uint32_t const maxSeq = seq + setKeepRounds; while (it != m_map.end()) { @@ -219,7 +219,7 @@ public: void stop() override { - std::lock_guard lock(mLock); + std::lock_guard const lock(mLock); stopping_ = true; m_map.clear(); } diff --git a/src/xrpld/app/ledger/detail/LedgerCleaner.cpp b/src/xrpld/app/ledger/detail/LedgerCleaner.cpp index af358fbfc6..a0d168f299 100644 --- a/src/xrpld/app/ledger/detail/LedgerCleaner.cpp +++ b/src/xrpld/app/ledger/detail/LedgerCleaner.cpp @@ -76,7 +76,7 @@ public: { JLOG(j_.info()) << "Stopping"; { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); shouldExit_ = true; wakeup_.notify_one(); } @@ -92,7 +92,7 @@ public: void onWrite(beast::PropertyStream::Map& map) override { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); if (maxRange_ == 0) { @@ -124,7 +124,7 @@ public: app_.getLedgerMaster().getFullValidatedRange(minRange, maxRange); { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); maxRange_ = maxRange; minRange_ = minRange; @@ -327,8 +327,8 @@ private: // No. Try to get another ledger that might have the hash we // need: compute the index and hash of a ledger that will have // the hash we need. - LedgerIndex refIndex = getCandidateLedger(ledgerIndex); - LedgerHash refHash = getLedgerHash(referenceLedger, refIndex); + LedgerIndex const refIndex = getCandidateLedger(ledgerIndex); + LedgerHash const refHash = getLedgerHash(referenceLedger, refIndex); bool const nonzero(refHash.isNonZero()); XRPL_ASSERT(nonzero, "xrpl::LedgerCleanerImp::getHash : nonzero hash"); @@ -354,7 +354,7 @@ private: doLedgerCleaner() { auto shouldExit = [this] { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); return shouldExit_; }; @@ -375,7 +375,7 @@ private: } { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); if ((minRange_ > maxRange_) || (maxRange_ == 0) || (minRange_ == 0)) { minRange_ = maxRange_ = 0; @@ -403,7 +403,7 @@ private: if (fail) { { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); ++failures_; } // Wait for acquiring to catch up to us @@ -412,7 +412,7 @@ private: else { { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); if (ledgerIndex == minRange_) ++minRange_; if (ledgerIndex == maxRange_) diff --git a/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp b/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp index 1d48a9741d..f829e58830 100644 --- a/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp +++ b/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp @@ -178,7 +178,7 @@ LedgerDeltaAcquire::tryBuild(std::shared_ptr const& parent) parent->header().hash == replayTemp_->header().parentHash, "xrpl::LedgerDeltaAcquire::tryBuild : parent hash match"); // build ledger - LedgerReplay replayData(parent, replayTemp_, std::move(orderedTxns_)); + LedgerReplay const replayData(parent, replayTemp_, std::move(orderedTxns_)); fullLedger_ = buildLedger(replayData, tapNONE, app_, journal_); if (fullLedger_ && fullLedger_->header().hash == hash_) { diff --git a/src/xrpld/app/ledger/detail/LedgerMaster.cpp b/src/xrpld/app/ledger/detail/LedgerMaster.cpp index 6253b33da3..876a7e0578 100644 --- a/src/xrpld/app/ledger/detail/LedgerMaster.cpp +++ b/src/xrpld/app/ledger/detail/LedgerMaster.cpp @@ -122,7 +122,7 @@ LedgerMaster::isCompatible(ReadView const& view, beast::Journal::Stream s, char } { - std::lock_guard sl(m_mutex); + std::lock_guard const sl(m_mutex); if ((mLastValidLedger.second != 0) && !areCompatible(mLastValidLedger.first, mLastValidLedger.second, view, s, reason)) @@ -138,7 +138,7 @@ std::chrono::seconds LedgerMaster::getPublishedLedgerAge() { using namespace std::chrono_literals; - std::chrono::seconds pubClose{mPubLedgerClose.load()}; + std::chrono::seconds const pubClose{mPubLedgerClose.load()}; if (pubClose == 0s) { JLOG(m_journal.debug()) << "No published ledger"; @@ -163,7 +163,7 @@ LedgerMaster::getValidatedLedgerAge() { using namespace std::chrono_literals; - std::chrono::seconds valClose{mValidLedgerSign.load()}; + std::chrono::seconds const valClose{mValidLedgerSign.load()}; if (valClose == 0s) { JLOG(m_journal.debug()) << "No validated ledger"; @@ -193,8 +193,8 @@ LedgerMaster::isCaughtUp(std::string& reason) reason = "No recently-published ledger"; return false; } - std::uint32_t validClose = mValidLedgerSign.load(); - std::uint32_t pubClose = mPubLedgerClose.load(); + std::uint32_t const validClose = mValidLedgerSign.load(); + std::uint32_t const pubClose = mPubLedgerClose.load(); if ((validClose == 0u) || (pubClose == 0u)) { reason = "No published ledger"; @@ -301,7 +301,7 @@ LedgerMaster::setPubLedger(std::shared_ptr const& l) void LedgerMaster::addHeldTransaction(std::shared_ptr const& transaction) { - std::lock_guard ml(m_mutex); + std::lock_guard const ml(m_mutex); mHeldTransactions.insert(transaction->getSTransaction()); } @@ -384,7 +384,7 @@ LedgerMaster::switchLCL(std::shared_ptr const& lastClosed) LogicError("The new last closed ledger is open!"); { - std::lock_guard ml(m_mutex); + std::lock_guard const ml(m_mutex); mClosedLedger.set(lastClosed); } @@ -408,7 +408,7 @@ LedgerMaster::fixIndex(LedgerIndex ledgerIndex, LedgerHash const& ledgerHash) bool LedgerMaster::storeLedger(std::shared_ptr ledger) { - bool validated = ledger->header().validated; + bool const validated = ledger->header().validated; // Returns true if we already had the ledger return mLedgerHistory.insert(ledger, validated); } @@ -422,7 +422,7 @@ void LedgerMaster::applyHeldTransactions() { CanonicalTXSet const set = [this]() { - std::lock_guard sl(m_mutex); + std::lock_guard const sl(m_mutex); // VFALCO NOTE The hash for an open ledger is undefined so we use // something that is a reasonable substitute. CanonicalTXSet set(app_.getOpenLedger().current()->header().parentHash); @@ -437,7 +437,7 @@ LedgerMaster::applyHeldTransactions() std::shared_ptr LedgerMaster::popAcctTransaction(std::shared_ptr const& tx) { - std::lock_guard sl(m_mutex); + std::lock_guard const sl(m_mutex); return mHeldTransactions.popAcctTransaction(tx); } @@ -451,14 +451,14 @@ LedgerMaster::setBuildingLedger(LedgerIndex i) bool LedgerMaster::haveLedger(std::uint32_t seq) { - std::lock_guard sl(mCompleteLock); + std::lock_guard const sl(mCompleteLock); return boost::icl::contains(mCompleteLedgers, seq); } void LedgerMaster::clearLedger(std::uint32_t seq) { - std::lock_guard sl(mCompleteLock); + std::lock_guard const sl(mCompleteLock); mCompleteLedgers.erase(seq); } @@ -485,7 +485,7 @@ LedgerMaster::isValidated(ReadView const& ledger) if (hash) { XRPL_ASSERT(hash->isNonZero(), "xrpl::LedgerMaster::isValidated : nonzero hash"); - uint256 valHash = app_.getRelationalDatabase().getHashByIndex(seq); + uint256 const valHash = app_.getRelationalDatabase().getHashByIndex(seq); if (valHash == ledger.header().hash) { // SQL database doesn't match ledger chain @@ -519,7 +519,7 @@ LedgerMaster::getFullValidatedRange(std::uint32_t& minVal, std::uint32_t& maxVal std::optional maybeMin; { - std::lock_guard sl(mCompleteLock); + std::lock_guard const sl(mCompleteLock); maybeMin = prevMissing(mCompleteLedgers, maxVal); } @@ -614,7 +614,7 @@ LedgerMaster::tryFill(std::shared_ptr ledger) while (!app_.getJobQueue().isStopping() && seq > 0) { { - std::lock_guard ml(m_mutex); + std::lock_guard const ml(m_mutex); minHas = seq; --seq; @@ -630,7 +630,7 @@ LedgerMaster::tryFill(std::shared_ptr ledger) return; { - std::lock_guard ml(mCompleteLock); + std::lock_guard const ml(mCompleteLock); mCompleteLedgers.insert(range(minHas, maxHas)); } maxHas = minHas; @@ -658,11 +658,11 @@ LedgerMaster::tryFill(std::shared_ptr ledger) } { - std::lock_guard ml(mCompleteLock); + std::lock_guard const ml(mCompleteLock); mCompleteLedgers.insert(range(minHas, maxHas)); } { - std::lock_guard ml(m_mutex); + std::lock_guard const ml(m_mutex); mFillInProgress = 0; tryAdvance(); } @@ -692,7 +692,7 @@ LedgerMaster::getFetchPack(LedgerIndex missing, InboundLedger::Reason reason) { if (peer->hasRange(missing, missing + 1)) { - int score = peer->getScore(true); + int const score = peer->getScore(true); if (!target || (score > maxScore)) { target = peer; @@ -791,7 +791,8 @@ LedgerMaster::setFullLedger( { // Check the SQL database's entry for the sequence before this // ledger, if it's not this ledger's parent, invalidate it - uint256 prevHash = app_.getRelationalDatabase().getHashByIndex(ledger->header().seq - 1); + uint256 const prevHash = + app_.getRelationalDatabase().getHashByIndex(ledger->header().seq - 1); if (prevHash.isNonZero() && prevHash != ledger->header().parentHash) clearLedger(ledger->header().seq - 1); } @@ -799,12 +800,12 @@ LedgerMaster::setFullLedger( pendSaveValidated(app_, ledger, isSynchronous, isCurrent); { - std::lock_guard ml(mCompleteLock); + std::lock_guard const ml(mCompleteLock); mCompleteLedgers.insert(ledger->header().seq); } { - std::lock_guard ml(m_mutex); + std::lock_guard const ml(m_mutex); if (ledger->header().seq > mValidLedgerSeq) setValidLedger(ledger); @@ -854,7 +855,7 @@ LedgerMaster::checkAccept(uint256 const& hash, std::uint32_t seq) valCount = validations.size(); if (valCount >= app_.getValidators().quorum()) { - std::lock_guard ml(m_mutex); + std::lock_guard const ml(m_mutex); if (seq > mLastValidLedger.second) mLastValidLedger = std::make_pair(hash, seq); } @@ -908,7 +909,7 @@ LedgerMaster::checkAccept(std::shared_ptr const& ledger) // Can we advance the last fully-validated ledger? If so, can we // publish? - std::lock_guard ml(m_mutex); + std::lock_guard const ml(m_mutex); if (ledger->header().seq <= mValidLedgerSeq) return; @@ -1200,9 +1201,9 @@ LedgerMaster::findNewLedgersToPublish(std::unique_lock& sl auto pubSeq = mPubLedgerSeq + 1; // Next sequence to publish auto valLedger = mValidLedger.get(); - std::uint32_t valSeq = valLedger->header().seq; + std::uint32_t const valSeq = valLedger->header().seq; - scope_unlock sul{sl}; + scope_unlock const sul{sl}; try { for (std::uint32_t seq = pubSeq; seq <= valSeq; ++seq) @@ -1302,7 +1303,7 @@ LedgerMaster::findNewLedgersToPublish(std::unique_lock& sl void LedgerMaster::tryAdvance() { - std::lock_guard ml(m_mutex); + std::lock_guard const ml(m_mutex); // Can't advance without at least one fully-valid ledger mAdvanceWork = true; @@ -1337,7 +1338,7 @@ void LedgerMaster::updatePaths() { { - std::lock_guard ml(m_mutex); + std::lock_guard const ml(m_mutex); if (app_.getOPs().isNeedNetworkLedger()) { --mPathFindThread; @@ -1352,7 +1353,7 @@ LedgerMaster::updatePaths() JLOG(m_journal.debug()) << "updatePaths running"; std::shared_ptr lastLedger; { - std::lock_guard ml(m_mutex); + std::lock_guard const ml(m_mutex); if (!mValidLedger.empty() && (!mPathLedger || (mPathLedger->header().seq != mValidLedgerSeq))) @@ -1381,7 +1382,7 @@ LedgerMaster::updatePaths() if (age > 1min) { JLOG(m_journal.debug()) << "Published ledger too old for updating paths"; - std::lock_guard ml(m_mutex); + std::lock_guard const ml(m_mutex); --mPathFindThread; mPathLedger.reset(); return; @@ -1392,7 +1393,7 @@ LedgerMaster::updatePaths() { auto& pathRequests = app_.getPathRequestManager(); { - std::lock_guard ml(m_mutex); + std::lock_guard const ml(m_mutex); if (!pathRequests.requestsPending()) { --mPathFindThread; @@ -1406,7 +1407,7 @@ LedgerMaster::updatePaths() JLOG(m_journal.debug()) << "Updating paths"; pathRequests.updateAll(lastLedger); - std::lock_guard ml(m_mutex); + std::lock_guard const ml(m_mutex); if (!pathRequests.requestsPending()) { JLOG(m_journal.debug()) << "No path requests left. No need for further updating " @@ -1450,7 +1451,7 @@ LedgerMaster::newPathRequest() bool LedgerMaster::isNewPathRequest() { - std::lock_guard ml(m_mutex); + std::lock_guard const ml(m_mutex); bool const ret = mPathFindNewRequest; mPathFindNewRequest = false; return ret; @@ -1523,21 +1524,21 @@ LedgerMaster::getValidatedRules() std::shared_ptr LedgerMaster::getPublishedLedger() { - std::lock_guard lock(m_mutex); + std::lock_guard const lock(m_mutex); return mPubLedger; } std::string LedgerMaster::getCompleteLedgers() { - std::lock_guard sl(mCompleteLock); + std::lock_guard const sl(mCompleteLock); return to_string(mCompleteLedgers); } std::optional LedgerMaster::getCloseTimeBySeq(LedgerIndex ledgerIndex) { - uint256 hash = getHashBySeq(ledgerIndex); + uint256 const hash = getHashBySeq(ledgerIndex); return hash.isNonZero() ? getCloseTimeByHash(hash, ledgerIndex) : std::nullopt; } @@ -1601,7 +1602,7 @@ LedgerMaster::walkHashBySeq( // The hash is not in the reference ledger. Get another ledger which can // be located easily and should contain the hash. - LedgerIndex refIndex = getCandidateLedger(index); + LedgerIndex const refIndex = getCandidateLedger(index); auto const refHash = hashOfSeq(*referenceLedger, refIndex, m_journal); XRPL_ASSERT(refHash, "xrpl::LedgerMaster::walkHashBySeq : found ledger"); if (refHash) @@ -1689,7 +1690,7 @@ LedgerMaster::getLedgerByHash(uint256 const& hash) void LedgerMaster::setLedgerRangePresent(std::uint32_t minV, std::uint32_t maxV) { - std::lock_guard sl(mCompleteLock); + std::lock_guard const sl(mCompleteLock); mCompleteLedgers.insert(range(minV, maxV)); } @@ -1709,7 +1710,7 @@ LedgerMaster::getCacheHitRate() void LedgerMaster::clearPriorLedgers(LedgerIndex seq) { - std::lock_guard sl(mCompleteLock); + std::lock_guard const sl(mCompleteLock); if (seq > 0) mCompleteLedgers.erase(range(0u, seq - 1)); } @@ -1739,7 +1740,7 @@ LedgerMaster::fetchForHistory( InboundLedger::Reason reason, std::unique_lock& sl) { - scope_unlock sul{sl}; + scope_unlock const sul{sl}; if (auto hash = getLedgerHashForHistory(missing, reason)) { XRPL_ASSERT(hash->isNonZero(), "xrpl::LedgerMaster::fetchForHistory : found ledger"); @@ -1770,7 +1771,7 @@ LedgerMaster::fetchForHistory( setFullLedger(ledger, false, false); int fillInProgress = 0; { - std::lock_guard lock(m_mutex); + std::lock_guard const lock(m_mutex); mHistLedger = ledger; fillInProgress = mFillInProgress; } @@ -1779,7 +1780,7 @@ LedgerMaster::fetchForHistory( { { // Previous ledger is in DB - std::lock_guard lock(m_mutex); + std::lock_guard const lock(m_mutex); mFillInProgress = seq; } app_.getJobQueue().addJob( @@ -1799,7 +1800,7 @@ LedgerMaster::fetchForHistory( { for (std::uint32_t i = 0; i < fetchSz; ++i) { - std::uint32_t seq = missing - i; + std::uint32_t const seq = missing - i; if (auto h = getLedgerHashForHistory(seq, reason)) { XRPL_ASSERT( @@ -1848,10 +1849,10 @@ LedgerMaster::doAdvance(std::unique_lock& sl) (app_.getNodeStore().getWriteLoad() < MAX_WRITE_LOAD_ACQUIRE)) { // We are in sync, so can acquire - InboundLedger::Reason reason = InboundLedger::Reason::HISTORY; + InboundLedger::Reason const reason = InboundLedger::Reason::HISTORY; std::optional missing; { - std::lock_guard sll(mCompleteLock); + std::lock_guard const sll(mCompleteLock); missing = prevMissing( mCompleteLedgers, mPubLedger->header().seq, @@ -1898,7 +1899,7 @@ LedgerMaster::doAdvance(std::unique_lock& sl) for (auto const& ledger : pubLedgers) { { - scope_unlock sul{sl}; + scope_unlock const sul{sl}; JLOG(m_journal.debug()) << "tryAdvance publishing seq " << ledger->header().seq; setFullLedger(ledger, true, true); } @@ -1906,7 +1907,7 @@ LedgerMaster::doAdvance(std::unique_lock& sl) setPubLedger(ledger); { - scope_unlock sul{sl}; + scope_unlock const sul{sl}; app_.getOPs().pubLedger(ledger); } } @@ -2087,7 +2088,7 @@ LedgerMaster::makeFetchPack( // the same process adding the previous ledger to the FetchPack. do { - std::uint32_t lSeq = want->header().seq; + std::uint32_t const lSeq = want->header().seq; { // Serialize the ledger header: diff --git a/src/xrpld/app/ledger/detail/LedgerReplayMsgHandler.cpp b/src/xrpld/app/ledger/detail/LedgerReplayMsgHandler.cpp index a212629d28..93d7ac0d2f 100644 --- a/src/xrpld/app/ledger/detail/LedgerReplayMsgHandler.cpp +++ b/src/xrpld/app/ledger/detail/LedgerReplayMsgHandler.cpp @@ -82,7 +82,7 @@ bool LedgerReplayMsgHandler::processProofPathResponse( std::shared_ptr const& msg) { - protocol::TMProofPathResponse& reply = *msg; + protocol::TMProofPathResponse const& reply = *msg; if (reply.has_error() || !reply.has_key() || !reply.has_ledgerhash() || !reply.has_type() || !reply.has_ledgerheader() || reply.path_size() == 0) { @@ -98,7 +98,7 @@ LedgerReplayMsgHandler::processProofPathResponse( // deserialize the header auto info = deserializeHeader({reply.ledgerheader().data(), reply.ledgerheader().size()}); - uint256 replyHash(reply.ledgerhash()); + uint256 const replyHash(reply.ledgerhash()); if (calculateLedgerHash(info) != replyHash) { JLOG(journal_.debug()) << "Bad message: Hash mismatch"; @@ -106,7 +106,7 @@ LedgerReplayMsgHandler::processProofPathResponse( } info.hash = replyHash; - uint256 key(reply.key()); + uint256 const key(reply.key()); if (key != keylet::skip().key) { JLOG(journal_.debug()) << "Bad message: we only support the short skip list for now. " @@ -151,7 +151,7 @@ protocol::TMReplayDeltaResponse LedgerReplayMsgHandler::processReplayDeltaRequest( std::shared_ptr const& msg) { - protocol::TMReplayDeltaRequest& packet = *msg; + protocol::TMReplayDeltaRequest const& packet = *msg; protocol::TMReplayDeltaResponse reply; if (!packet.has_ledgerhash() || packet.ledgerhash().size() != uint256::size()) @@ -190,7 +190,7 @@ bool LedgerReplayMsgHandler::processReplayDeltaResponse( std::shared_ptr const& msg) { - protocol::TMReplayDeltaResponse& reply = *msg; + protocol::TMReplayDeltaResponse const& reply = *msg; if (reply.has_error() || !reply.has_ledgerheader()) { JLOG(journal_.debug()) << "Bad message: Error reply"; @@ -198,7 +198,7 @@ LedgerReplayMsgHandler::processReplayDeltaResponse( } auto info = deserializeHeader({reply.ledgerheader().data(), reply.ledgerheader().size()}); - uint256 replyHash(reply.ledgerhash()); + uint256 const replyHash(reply.ledgerhash()); if (calculateLedgerHash(info) != replyHash) { JLOG(journal_.debug()) << "Bad message: Hash mismatch"; @@ -217,7 +217,8 @@ LedgerReplayMsgHandler::processReplayDeltaResponse( // -- TxShaMapItem for building a ShaMap for verification // -- Tx // -- TxMetaData for Tx ordering - Serializer shaMapItemData(reply.transaction(i).data(), reply.transaction(i).size()); + Serializer const shaMapItemData( + reply.transaction(i).data(), reply.transaction(i).size()); SerialIter txMetaSit(makeSlice(reply.transaction(i))); SerialIter txSit(txMetaSit.getSlice(txMetaSit.getVLDataLength())); diff --git a/src/xrpld/app/ledger/detail/LedgerReplayTask.cpp b/src/xrpld/app/ledger/detail/LedgerReplayTask.cpp index 6db0cebf1a..f393c7fca8 100644 --- a/src/xrpld/app/ledger/detail/LedgerReplayTask.cpp +++ b/src/xrpld/app/ledger/detail/LedgerReplayTask.cpp @@ -96,7 +96,7 @@ LedgerReplayTask::init() { JLOG(journal_.debug()) << "Task start " << hash_; - std::weak_ptr wptr = shared_from_this(); + std::weak_ptr const wptr = shared_from_this(); skipListAcquirer_->addDataCallback([wptr](bool good, uint256 const& hash) { if (auto sptr = wptr.lock(); sptr) { @@ -163,7 +163,8 @@ LedgerReplayTask::tryAdvance(ScopedLockType& sl) << ", deltaIndex=" << deltaToBuild_ << ", totalDeltas=" << deltas_.size() << ", parent " << (parent_ ? parent_->header().hash : uint256()); - bool shouldTry = parent_ && parameter_.full_ && parameter_.totalLedgers_ - 1 == deltas_.size(); + bool const shouldTry = + parent_ && parameter_.full_ && parameter_.totalLedgers_ - 1 == deltas_.size(); if (!shouldTry) return; @@ -204,7 +205,7 @@ LedgerReplayTask::updateSkipList( std::vector const& sList) { { - ScopedLockType sl(mtx_); + ScopedLockType const sl(mtx_); if (isDone()) return; if (!parameter_.update(hash, seq, sList)) @@ -245,7 +246,7 @@ LedgerReplayTask::pmDowncast() void LedgerReplayTask::addDelta(std::shared_ptr const& delta) { - std::weak_ptr wptr = shared_from_this(); + std::weak_ptr const wptr = shared_from_this(); delta->addDataCallback(parameter_.reason_, [wptr](bool good, uint256 const& hash) { if (auto sptr = wptr.lock(); sptr) { @@ -260,7 +261,7 @@ LedgerReplayTask::addDelta(std::shared_ptr const& delta) } }); - ScopedLockType sl(mtx_); + ScopedLockType const sl(mtx_); if (!isDone()) { JLOG(journal_.trace()) << "addDelta task " << hash_ << " deltaIndex=" << deltaToBuild_ @@ -276,7 +277,7 @@ LedgerReplayTask::addDelta(std::shared_ptr const& delta) bool LedgerReplayTask::finished() const { - ScopedLockType sl(mtx_); + ScopedLockType const sl(mtx_); return isDone(); } diff --git a/src/xrpld/app/ledger/detail/LedgerReplayer.cpp b/src/xrpld/app/ledger/detail/LedgerReplayer.cpp index 9161c05d9a..ae3552f258 100644 --- a/src/xrpld/app/ledger/detail/LedgerReplayer.cpp +++ b/src/xrpld/app/ledger/detail/LedgerReplayer.cpp @@ -17,7 +17,7 @@ LedgerReplayer::LedgerReplayer( LedgerReplayer::~LedgerReplayer() { - std::lock_guard lock(mtx_); + std::lock_guard const lock(mtx_); tasks_.clear(); } @@ -32,13 +32,14 @@ LedgerReplayer::replay( totalNumLedgers <= LedgerReplayParameters::MAX_TASK_SIZE, "xrpl::LedgerReplayer::replay : valid inputs"); + // NOLINTNEXTLINE(misc-const-correctness) LedgerReplayTask::TaskParameter parameter(r, finishLedgerHash, totalNumLedgers); std::shared_ptr task; std::shared_ptr skipList; bool newSkipList = false; { - std::lock_guard lock(mtx_); + std::lock_guard const lock(mtx_); if (app_.isStopping()) return; if (tasks_.size() >= LedgerReplayParameters::MAX_TASKS) @@ -117,7 +118,7 @@ LedgerReplayer::createDeltas(std::shared_ptr task) std::shared_ptr delta; bool newDelta = false; { - std::lock_guard lock(mtx_); + std::lock_guard const lock(mtx_); if (app_.isStopping()) return; auto i = deltas_.find(*skipListItem); @@ -147,7 +148,7 @@ LedgerReplayer::gotSkipList( { std::shared_ptr skipList = {}; { - std::lock_guard lock(mtx_); + std::lock_guard const lock(mtx_); auto i = skipLists_.find(info.hash); if (i == skipLists_.end()) return; @@ -170,7 +171,7 @@ LedgerReplayer::gotReplayDelta( { std::shared_ptr delta = {}; { - std::lock_guard lock(mtx_); + std::lock_guard const lock(mtx_); auto i = deltas_.find(info.hash); if (i == deltas_.end()) return; @@ -191,7 +192,7 @@ LedgerReplayer::sweep() { auto const start = std::chrono::steady_clock::now(); { - std::lock_guard lock(mtx_); + std::lock_guard const lock(mtx_); JLOG(j_.debug()) << "Sweeping, LedgerReplayer has " << tasks_.size() << " tasks, " << skipLists_.size() << " skipLists, and " << deltas_.size() << " deltas."; @@ -237,7 +238,7 @@ LedgerReplayer::stop() { JLOG(j_.info()) << "Stopping..."; { - std::lock_guard lock(mtx_); + std::lock_guard const lock(mtx_); std::for_each(tasks_.begin(), tasks_.end(), [](auto& i) { i->cancel(); }); tasks_.clear(); auto lockAndCancel = [](auto& i) { diff --git a/src/xrpld/app/ledger/detail/LocalTxs.cpp b/src/xrpld/app/ledger/detail/LocalTxs.cpp index 8f04da9c2d..38969a092c 100644 --- a/src/xrpld/app/ledger/detail/LocalTxs.cpp +++ b/src/xrpld/app/ledger/detail/LocalTxs.cpp @@ -94,7 +94,7 @@ public: void push_back(LedgerIndex index, std::shared_ptr const& txn) override { - std::lock_guard lock(m_lock); + std::lock_guard const lock(m_lock); m_txns.emplace_back(index, txn); } @@ -107,7 +107,7 @@ public: // Get the set of local transactions as a canonical // set (so they apply in a valid order) { - std::lock_guard lock(m_lock); + std::lock_guard const lock(m_lock); for (auto const& it : m_txns) tset.insert(it.getTX()); @@ -121,7 +121,7 @@ public: void sweep(ReadView const& view) override { - std::lock_guard lock(m_lock); + std::lock_guard const lock(m_lock); m_txns.remove_if([&view](auto const& txn) { if (txn.isExpired(view.header().seq)) @@ -158,7 +158,7 @@ public: std::size_t size() override { - std::lock_guard lock(m_lock); + std::lock_guard const lock(m_lock); return m_txns.size(); } diff --git a/src/xrpld/app/ledger/detail/OpenLedger.cpp b/src/xrpld/app/ledger/detail/OpenLedger.cpp index da35a72bbc..dfce2278a5 100644 --- a/src/xrpld/app/ledger/detail/OpenLedger.cpp +++ b/src/xrpld/app/ledger/detail/OpenLedger.cpp @@ -25,26 +25,26 @@ OpenLedger::OpenLedger( bool OpenLedger::empty() const { - std::lock_guard lock(modify_mutex_); + std::lock_guard const lock(modify_mutex_); return current_->txCount() == 0; } std::shared_ptr OpenLedger::current() const { - std::lock_guard lock(current_mutex_); + std::lock_guard const lock(current_mutex_); return current_; } bool OpenLedger::modify(modify_type const& f) { - std::lock_guard lock1(modify_mutex_); + std::lock_guard const lock1(modify_mutex_); auto next = std::make_shared(*current_); auto const changed = f(*next, j_); if (changed) { - std::lock_guard lock2(current_mutex_); + std::lock_guard const lock2(current_mutex_); current_ = std::move(next); } return changed; @@ -73,7 +73,7 @@ OpenLedger::accept( // Block calls to modify, otherwise // new tx going into the open ledger // would get lost. - std::lock_guard lock1(modify_mutex_); + std::lock_guard const lock1(modify_mutex_); // Apply tx from the current open view if (!current_->txs.empty()) { @@ -131,7 +131,7 @@ OpenLedger::accept( } // Switch to the new open view - std::lock_guard lock2(current_mutex_); + std::lock_guard const lock2(current_mutex_); current_ = std::move(next); } diff --git a/src/xrpld/app/ledger/detail/SkipListAcquire.cpp b/src/xrpld/app/ledger/detail/SkipListAcquire.cpp index 3a60fbdc6d..20d63bcb64 100644 --- a/src/xrpld/app/ledger/detail/SkipListAcquire.cpp +++ b/src/xrpld/app/ledger/detail/SkipListAcquire.cpp @@ -151,7 +151,7 @@ SkipListAcquire::addDataCallback(OnSkipListDataCB&& cb) std::shared_ptr SkipListAcquire::getData() const { - ScopedLockType sl(mtx_); + ScopedLockType const sl(mtx_); return data_; } diff --git a/src/xrpld/app/ledger/detail/TimeoutCounter.cpp b/src/xrpld/app/ledger/detail/TimeoutCounter.cpp index e2d4409717..f329665031 100644 --- a/src/xrpld/app/ledger/detail/TimeoutCounter.cpp +++ b/src/xrpld/app/ledger/detail/TimeoutCounter.cpp @@ -96,7 +96,7 @@ TimeoutCounter::invokeOnTimer() void TimeoutCounter::cancel() { - ScopedLockType sl(mtx_); + ScopedLockType const sl(mtx_); if (!isDone()) { failed_ = true; diff --git a/src/xrpld/app/ledger/detail/TransactionAcquire.cpp b/src/xrpld/app/ledger/detail/TransactionAcquire.cpp index 9cf35b93dc..0dd654d80b 100644 --- a/src/xrpld/app/ledger/detail/TransactionAcquire.cpp +++ b/src/xrpld/app/ledger/detail/TransactionAcquire.cpp @@ -162,7 +162,7 @@ TransactionAcquire::takeNodes( std::vector> const& data, std::shared_ptr const& peer) { - ScopedLockType sl(mtx_); + ScopedLockType const sl(mtx_); if (complete_) { @@ -241,7 +241,7 @@ TransactionAcquire::init(int numPeers) void TransactionAcquire::stillNeed() { - ScopedLockType sl(mtx_); + ScopedLockType const sl(mtx_); timeouts_ = std::min(timeouts_, NORM_TIMEOUTS); failed_ = false; diff --git a/src/xrpld/app/main/Application.cpp b/src/xrpld/app/main/Application.cpp index 0d8325be54..6d02ea38ae 100644 --- a/src/xrpld/app/main/Application.cpp +++ b/src/xrpld/app/main/Application.cpp @@ -1811,7 +1811,7 @@ ApplicationImp::loadLedgerFromFile(std::string const& name) // VFALCO TODO This is the only place that // constructor is used, try to remove it - STLedgerEntry sle(*stp.object, uIndex); + STLedgerEntry const sle(*stp.object, uIndex); if (!loadLedger->addSLE(sle)) { diff --git a/src/xrpld/app/main/Application.h b/src/xrpld/app/main/Application.h index 9c79aabb02..45bd94adce 100644 --- a/src/xrpld/app/main/Application.h +++ b/src/xrpld/app/main/Application.h @@ -18,16 +18,16 @@ namespace xrpl { namespace unl { class Manager; -} +} // namespace unl namespace Resource { class Manager; -} +} // namespace Resource namespace NodeStore { class Database; } // namespace NodeStore namespace perf { class PerfLog; -} +} // namespace perf // VFALCO TODO Fix forward declares required for header dependency loops class AmendmentTable; diff --git a/src/xrpld/app/main/GRPCServer.cpp b/src/xrpld/app/main/GRPCServer.cpp index 130d0f01b9..a6c0c933be 100644 --- a/src/xrpld/app/main/GRPCServer.cpp +++ b/src/xrpld/app/main/GRPCServer.cpp @@ -16,8 +16,8 @@ getEndpoint(std::string const& peer) { try { - std::size_t first = peer.find_first_of(':'); - std::size_t last = peer.find_last_of(':'); + std::size_t const first = peer.find_first_of(':'); + std::size_t const last = peer.find_last_of(':'); std::string peerClean(peer); if (first != last) { @@ -88,7 +88,7 @@ GRPCServerImpl::CallData::process() // sanity check BOOST_ASSERT(!finished_); - std::shared_ptr> thisShared = this->shared_from_this(); + std::shared_ptr> const thisShared = this->shared_from_this(); // Need to set finished to true before processing the response, // because as soon as the response is posted to the completion @@ -107,7 +107,7 @@ GRPCServerImpl::CallData::process() // If coro is null, then the JobQueue has already been shutdown if (!coro) { - grpc::Status status{grpc::StatusCode::INTERNAL, "Job Queue is already stopped"}; + grpc::Status const status{grpc::StatusCode::INTERNAL, "Job Queue is already stopped"}; responder_.FinishWithError(status, this); } } @@ -119,10 +119,10 @@ GRPCServerImpl::CallData::process(std::shared_ptr::process(std::shared_ptr::process(std::shared_ptr envUseIPv4; -} +} // namespace test template static bool @@ -257,11 +257,11 @@ runUnitTests( if (!child && num_jobs == 1) { - multi_runner_parent parent_runner; + multi_runner_parent const parent_runner; multi_runner_child child_runner{num_jobs, quiet, log}; child_runner.arg(argument); - multi_selector pred(pattern); + multi_selector const pred(pattern); auto const any_failed = child_runner.run_multi(pred) || anyMissing(child_runner, pred); if (any_failed) diff --git a/src/xrpld/app/misc/DeliverMax.h b/src/xrpld/app/misc/DeliverMax.h index 1b4241f091..7fec517d28 100644 --- a/src/xrpld/app/misc/DeliverMax.h +++ b/src/xrpld/app/misc/DeliverMax.h @@ -4,7 +4,7 @@ namespace Json { class Value; -} +} // namespace Json namespace xrpl { diff --git a/src/xrpld/app/misc/FeeVoteImpl.cpp b/src/xrpld/app/misc/FeeVoteImpl.cpp index 450e53e86c..414d8d7421 100644 --- a/src/xrpld/app/misc/FeeVoteImpl.cpp +++ b/src/xrpld/app/misc/FeeVoteImpl.cpp @@ -255,7 +255,7 @@ FeeVoteImpl::doVoting( JLOG(journal_.warn()) << "We are voting for a fee change: " << baseFee.first << "/" << baseReserve.first << "/" << incReserve.first; - STTx feeTx(ttFEE, [=, &rules](auto& obj) { + STTx const feeTx(ttFEE, [=, &rules](auto& obj) { obj[sfAccount] = AccountID(); obj[sfLedgerSequence] = seq; if (rules.enabled(featureXRPFees)) @@ -277,7 +277,7 @@ FeeVoteImpl::doVoting( } }); - uint256 txID = feeTx.getTransactionID(); + uint256 const txID = feeTx.getTransactionID(); JLOG(journal_.warn()) << "Vote: " << txID; diff --git a/src/xrpld/app/misc/NegativeUNLVote.cpp b/src/xrpld/app/misc/NegativeUNLVote.cpp index fe031749bc..212cfaa2e9 100644 --- a/src/xrpld/app/misc/NegativeUNLVote.cpp +++ b/src/xrpld/app/misc/NegativeUNLVote.cpp @@ -90,7 +90,7 @@ NegativeUNLVote::addTx( NegativeUNLModify modify, std::shared_ptr const& initialSet) { - STTx negUnlTx(ttUNL_MODIFY, [&](auto& obj) { + STTx const negUnlTx(ttUNL_MODIFY, [&](auto& obj) { obj.setFieldU8(sfUNLModifyDisabling, modify == ToDisable ? 1 : 0); obj.setFieldU32(sfLedgerSequence, seq); obj.setFieldVL(sfUNLModifyValidator, vp.slice()); @@ -118,7 +118,7 @@ NegativeUNLVote::choose(uint256 const& randomPadData, std::vector const& { XRPL_ASSERT(!candidates.empty(), "xrpl::NegativeUNLVote::choose : non-empty input"); static_assert(NodeID::bytes <= uint256::bytes); - NodeID randomPad = NodeID::fromVoid(randomPadData.data()); + NodeID const randomPad = NodeID::fromVoid(randomPadData.data()); NodeID txNodeID = candidates[0]; for (int j = 1; j < candidates.size(); ++j) { @@ -285,7 +285,7 @@ NegativeUNLVote::findAllCandidates( void NegativeUNLVote::newValidators(LedgerIndex seq, hash_set const& nowTrusted) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); for (auto const& n : nowTrusted) { if (!newValidators_.contains(n)) @@ -299,7 +299,7 @@ NegativeUNLVote::newValidators(LedgerIndex seq, hash_set const& nowTrust void NegativeUNLVote::purgeNewValidators(LedgerIndex seq) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); auto i = newValidators_.begin(); while (i != newValidators_.end()) { diff --git a/src/xrpld/app/misc/NetworkOPs.cpp b/src/xrpld/app/misc/NetworkOPs.cpp index b323541362..361eada455 100644 --- a/src/xrpld/app/misc/NetworkOPs.cpp +++ b/src/xrpld/app/misc/NetworkOPs.cpp @@ -177,7 +177,7 @@ class NetworkOPsImp final : public NetworkOPs CounterData getCounterData() const { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); return {counters_, mode_, start_, initialSyncUs_}; } }; @@ -1079,7 +1079,7 @@ NetworkOPsImp::processClusterTimer() n.set_nodename(node.name()); }); - Resource::Gossip gossip = registry_.get().getResourceManager().exportConsumers(); + Resource::Gossip const gossip = registry_.get().getResourceManager().exportConsumers(); for (auto& item : gossip.items) { protocol::TMLoadSource& node = *cluster.add_loadsources(); @@ -1249,7 +1249,7 @@ NetworkOPsImp::doTransactionAsync( bool bUnlimited, FailHard failType) { - std::lock_guard lock(mMutex); + std::lock_guard const lock(mMutex); if (transaction->getApplying()) return; @@ -1441,7 +1441,7 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) validatedLedgerIndex = l->header().seq; auto newOL = registry_.get().getOpenLedger().current(); - for (TransactionStatus& e : transactions) + for (TransactionStatus const& e : transactions) { e.transaction->clearSubmitResult(); @@ -1471,7 +1471,7 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) } #endif - bool addLocal = e.local; + bool const addLocal = e.local; if (isTesSuccess(e.result)) { @@ -1620,7 +1620,7 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) batchLock.lock(); - for (TransactionStatus& e : transactions) + for (TransactionStatus const& e : transactions) e.transaction->clearApplying(); if (!submit_held.empty()) @@ -1782,7 +1782,7 @@ NetworkOPsImp::checkLastClosedLedger(Overlay::PeerSequence const& peerList, uint return false; uint256 closedLedger = ourClosed->header().hash; - uint256 prevClosedLedger = ourClosed->header().parentHash; + uint256 const prevClosedLedger = ourClosed->header().parentHash; JLOG(m_journal.trace()) << "OurClosed: " << closedLedger; JLOG(m_journal.trace()) << "PrevClosed: " << prevClosedLedger; @@ -1800,7 +1800,7 @@ NetworkOPsImp::checkLastClosedLedger(Overlay::PeerSequence const& peerList, uint for (auto& peer : peerList) { - uint256 peerLedger = peer->getClosedLedgerHash(); + uint256 const peerLedger = peer->getClosedLedgerHash(); if (peerLedger.isNonZero()) ++peerCounts[peerLedger]; @@ -1809,7 +1809,7 @@ NetworkOPsImp::checkLastClosedLedger(Overlay::PeerSequence const& peerList, uint for (auto const& it : peerCounts) JLOG(m_journal.debug()) << "L: " << it.first << " n=" << it.second; - uint256 preferredLCL = validations.getPreferredLCL( + uint256 const preferredLCL = validations.getPreferredLCL( RCLValidatedLedger{ourClosed, validations.adaptor().journal()}, m_ledgerMaster.getValidLedgerIndex(), peerCounts); @@ -2042,7 +2042,7 @@ NetworkOPsImp::mapComplete(std::shared_ptr const& map, bool fromAcquire) void NetworkOPsImp::endConsensus(std::unique_ptr const& clog) { - uint256 deadLedger = m_ledgerMaster.getClosedLedger()->header().parentHash; + uint256 const deadLedger = m_ledgerMaster.getClosedLedger()->header().parentHash; for (auto const& it : registry_.get().getOverlay().getActivePeers()) { if (it && (it->getClosedLedgerHash() == deadLedger)) @@ -2053,7 +2053,7 @@ NetworkOPsImp::endConsensus(std::unique_ptr const& clog) } uint256 networkClosed; - bool ledgerChange = + bool const ledgerChange = checkLastClosedLedger(registry_.get().getOverlay().getActivePeers(), networkClosed); if (networkClosed.isZero()) @@ -2107,7 +2107,7 @@ void NetworkOPsImp::pubManifest(Manifest const& mo) { // VFALCO consider std::shared_mutex - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); if (!mStreamMaps[sManifests].empty()) { @@ -2185,7 +2185,7 @@ NetworkOPsImp::pubServer() // list into a local array while holding the lock then release // the lock and call send on everyone. // - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); if (!mStreamMaps[sServer].empty()) { @@ -2223,7 +2223,7 @@ NetworkOPsImp::pubServer() for (auto i = mStreamMaps[sServer].begin(); i != mStreamMaps[sServer].end();) { - InfoSub::pointer p = i->second.lock(); + InfoSub::pointer const p = i->second.lock(); // VFALCO TODO research the possibility of using thread queues and // linearizing the deletion of subscribers with the @@ -2244,7 +2244,7 @@ NetworkOPsImp::pubServer() void NetworkOPsImp::pubConsensus(ConsensusPhase phase) { - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); auto& streamMap = mStreamMaps[sConsensusPhase]; if (!streamMap.empty()) @@ -2272,7 +2272,7 @@ void NetworkOPsImp::pubValidation(std::shared_ptr const& val) { // VFALCO consider std::shared_mutex - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); if (!mStreamMaps[sValidations].empty()) { @@ -2377,7 +2377,7 @@ NetworkOPsImp::pubValidation(std::shared_ptr const& val) void NetworkOPsImp::pubPeerStatus(std::function const& func) { - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); if (!mStreamMaps[sPeerStatus].empty()) { @@ -2387,7 +2387,7 @@ NetworkOPsImp::pubPeerStatus(std::function const& func) for (auto i = mStreamMaps[sPeerStatus].begin(); i != mStreamMaps[sPeerStatus].end();) { - InfoSub::pointer p = i->second.lock(); + InfoSub::pointer const p = i->second.lock(); if (p) { @@ -2448,7 +2448,7 @@ NetworkOPsImp::recvValidation(std::shared_ptr const& val, std::str { pendingValidations_.insert(val->getLedgerHash()); } - scope_unlock unlock(lock); + scope_unlock const unlock(lock); handleNewValidation(registry_.get().getApp(), val, source, bypassAccept, m_journal); } catch (std::exception const& e) @@ -2933,7 +2933,7 @@ NetworkOPsImp::pubProposedTransaction( MultiApiJson jvObj = transJson(transaction, result, false, ledger, std::nullopt); { - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); auto it = mStreamMaps[sRTTransactions].begin(); while (it != mStreamMaps[sRTTransactions].end()) @@ -2980,7 +2980,7 @@ NetworkOPsImp::pubLedger(std::shared_ptr const& lpAccepted) JLOG(m_journal.debug()) << "Publishing ledger " << lpAccepted->header().seq << " " << lpAccepted->header().hash; - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); if (!mStreamMaps[sLedger].empty()) { @@ -3011,7 +3011,7 @@ NetworkOPsImp::pubLedger(std::shared_ptr const& lpAccepted) auto it = mStreamMaps[sLedger].begin(); while (it != mStreamMaps[sLedger].end()) { - InfoSub::pointer p = it->second.lock(); + InfoSub::pointer const p = it->second.lock(); if (p) { p->send(jvObj, true); @@ -3026,12 +3026,12 @@ NetworkOPsImp::pubLedger(std::shared_ptr const& lpAccepted) if (!mStreamMaps[sBookChanges].empty()) { - Json::Value jvObj = xrpl::RPC::computeBookChanges(lpAccepted); + Json::Value const jvObj = xrpl::RPC::computeBookChanges(lpAccepted); auto it = mStreamMaps[sBookChanges].begin(); while (it != mStreamMaps[sBookChanges].end()) { - InfoSub::pointer p = it->second.lock(); + InfoSub::pointer const p = it->second.lock(); if (p) { p->send(jvObj, true); @@ -3076,7 +3076,7 @@ NetworkOPsImp::pubLedger(std::shared_ptr const& lpAccepted) void NetworkOPsImp::reportFeeChange() { - ServerFeeSummary f{ + ServerFeeSummary const f{ registry_.get().getOpenLedger().current()->fees().base, registry_.get().getTxQ().getMetrics(*registry_.get().getOpenLedger().current()), registry_.get().getFeeTrack()}; @@ -3220,7 +3220,7 @@ NetworkOPsImp::pubValidatedTransaction( MultiApiJson jvObj = transJson(stTxn, trResult, true, ledger, metaRef); { - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); auto it = mStreamMaps[sTransactions].begin(); while (it != mStreamMaps[sTransactions].end()) @@ -3279,7 +3279,7 @@ NetworkOPsImp::pubAccountTransaction( std::vector accountHistoryNotify; auto const currLedgerSeq = ledger->seq(); { - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); if (!mSubAccount.empty() || !mSubRTAccount.empty() || !mSubAccountHistory.empty()) { @@ -3292,7 +3292,7 @@ NetworkOPsImp::pubAccountTransaction( while (it != simiIt->second.end()) { - InfoSub::pointer p = it->second.lock(); + InfoSub::pointer const p = it->second.lock(); if (p) { @@ -3312,7 +3312,7 @@ NetworkOPsImp::pubAccountTransaction( auto it = simiIt->second.begin(); while (it != simiIt->second.end()) { - InfoSub::pointer p = it->second.lock(); + InfoSub::pointer const p = it->second.lock(); if (p) { @@ -3412,7 +3412,7 @@ NetworkOPsImp::pubProposedAccountTransaction( std::vector accountHistoryNotify; { - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); if (mSubRTAccount.empty()) return; @@ -3428,7 +3428,7 @@ NetworkOPsImp::pubProposedAccountTransaction( while (it != simiIt->second.end()) { - InfoSub::pointer p = it->second.lock(); + InfoSub::pointer const p = it->second.lock(); if (p) { @@ -3496,7 +3496,7 @@ NetworkOPsImp::subAccount( isrListener->insertSubAccountInfo(naAccountID, rt); } - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); for (auto const& naAccountID : vnaAccountIDs) { @@ -3539,7 +3539,7 @@ NetworkOPsImp::unsubAccountInternal( hash_set const& vnaAccountIDs, bool rt) { - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); SubInfoMapType& subMap = rt ? mSubRTAccount : mSubAccount; @@ -3672,7 +3672,7 @@ NetworkOPsImp::addAccountHistoryJob(SubAccountHistoryInfoWeak subInfo) { case Sqlite: { auto& db = registry_.get().getRelationalDatabase(); - RelationalDatabase::AccountTxPageOptions options{ + RelationalDatabase::AccountTxPageOptions const options{ accountId, {minLedger, maxLedger}, marker, 0, true}; return db.newestAccountTxPage(options); } @@ -3751,7 +3751,7 @@ NetworkOPsImp::addAccountHistoryJob(SubAccountHistoryInfoWeak subInfo) auto const& txns = dbResult->first; marker = dbResult->second; - size_t num_txns = txns.size(); + size_t const num_txns = txns.size(); for (size_t i = 0; i < num_txns; ++i) { auto const& [tx, meta] = txns[i]; @@ -3777,7 +3777,7 @@ NetworkOPsImp::addAccountHistoryJob(SubAccountHistoryInfoWeak subInfo) return; // LCOV_EXCL_STOP } - std::shared_ptr stTxn = tx->getSTransaction(); + std::shared_ptr const stTxn = tx->getSTransaction(); if (!stTxn) { // LCOV_EXCL_START @@ -3896,7 +3896,7 @@ NetworkOPsImp::subAccountHistory(InfoSub::ref isrListener, AccountID const& acco return rpcINVALID_PARAMS; } - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); SubAccountHistoryInfoWeak ahi{isrListener, std::make_shared(accountId)}; auto simIterator = mSubAccountHistory.find(accountId); if (simIterator == mSubAccountHistory.end()) @@ -3943,7 +3943,7 @@ NetworkOPsImp::unsubAccountHistoryInternal( AccountID const& account, bool historyOnly) { - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); auto simIterator = mSubAccountHistory.find(account); if (simIterator != mSubAccountHistory.end()) { @@ -4032,7 +4032,7 @@ NetworkOPsImp::subLedger(InfoSub::ref isrListener, Json::Value& jvResult) jvResult[jss::validated_ledgers] = registry_.get().getLedgerMaster().getCompleteLedgers(); } - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); return mStreamMaps[sLedger].emplace(isrListener->getSeq(), isrListener).second; } @@ -4040,7 +4040,7 @@ NetworkOPsImp::subLedger(InfoSub::ref isrListener, Json::Value& jvResult) bool NetworkOPsImp::subBookChanges(InfoSub::ref isrListener) { - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); return mStreamMaps[sBookChanges].emplace(isrListener->getSeq(), isrListener).second; } @@ -4048,7 +4048,7 @@ NetworkOPsImp::subBookChanges(InfoSub::ref isrListener) bool NetworkOPsImp::unsubLedger(std::uint64_t uSeq) { - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); return mStreamMaps[sLedger].erase(uSeq) != 0u; } @@ -4056,7 +4056,7 @@ NetworkOPsImp::unsubLedger(std::uint64_t uSeq) bool NetworkOPsImp::unsubBookChanges(std::uint64_t uSeq) { - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); return mStreamMaps[sBookChanges].erase(uSeq) != 0u; } @@ -4064,7 +4064,7 @@ NetworkOPsImp::unsubBookChanges(std::uint64_t uSeq) bool NetworkOPsImp::subManifests(InfoSub::ref isrListener) { - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); return mStreamMaps[sManifests].emplace(isrListener->getSeq(), isrListener).second; } @@ -4072,7 +4072,7 @@ NetworkOPsImp::subManifests(InfoSub::ref isrListener) bool NetworkOPsImp::unsubManifests(std::uint64_t uSeq) { - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); return mStreamMaps[sManifests].erase(uSeq) != 0u; } @@ -4097,7 +4097,7 @@ NetworkOPsImp::subServer(InfoSub::ref isrListener, Json::Value& jvResult, bool a jvResult[jss::pubkey_node] = toBase58(TokenType::NodePublic, registry_.get().getApp().nodeIdentity().first); - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); return mStreamMaps[sServer].emplace(isrListener->getSeq(), isrListener).second; } @@ -4105,7 +4105,7 @@ NetworkOPsImp::subServer(InfoSub::ref isrListener, Json::Value& jvResult, bool a bool NetworkOPsImp::unsubServer(std::uint64_t uSeq) { - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); return mStreamMaps[sServer].erase(uSeq) != 0u; } @@ -4113,7 +4113,7 @@ NetworkOPsImp::unsubServer(std::uint64_t uSeq) bool NetworkOPsImp::subTransactions(InfoSub::ref isrListener) { - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); return mStreamMaps[sTransactions].emplace(isrListener->getSeq(), isrListener).second; } @@ -4121,7 +4121,7 @@ NetworkOPsImp::subTransactions(InfoSub::ref isrListener) bool NetworkOPsImp::unsubTransactions(std::uint64_t uSeq) { - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); return mStreamMaps[sTransactions].erase(uSeq) != 0u; } @@ -4129,7 +4129,7 @@ NetworkOPsImp::unsubTransactions(std::uint64_t uSeq) bool NetworkOPsImp::subRTTransactions(InfoSub::ref isrListener) { - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); return mStreamMaps[sRTTransactions].emplace(isrListener->getSeq(), isrListener).second; } @@ -4137,7 +4137,7 @@ NetworkOPsImp::subRTTransactions(InfoSub::ref isrListener) bool NetworkOPsImp::unsubRTTransactions(std::uint64_t uSeq) { - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); return mStreamMaps[sRTTransactions].erase(uSeq) != 0u; } @@ -4145,7 +4145,7 @@ NetworkOPsImp::unsubRTTransactions(std::uint64_t uSeq) bool NetworkOPsImp::subValidations(InfoSub::ref isrListener) { - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); return mStreamMaps[sValidations].emplace(isrListener->getSeq(), isrListener).second; } @@ -4159,7 +4159,7 @@ NetworkOPsImp::stateAccounting(Json::Value& obj) bool NetworkOPsImp::unsubValidations(std::uint64_t uSeq) { - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); return mStreamMaps[sValidations].erase(uSeq) != 0u; } @@ -4167,7 +4167,7 @@ NetworkOPsImp::unsubValidations(std::uint64_t uSeq) bool NetworkOPsImp::subPeerStatus(InfoSub::ref isrListener) { - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); return mStreamMaps[sPeerStatus].emplace(isrListener->getSeq(), isrListener).second; } @@ -4175,7 +4175,7 @@ NetworkOPsImp::subPeerStatus(InfoSub::ref isrListener) bool NetworkOPsImp::unsubPeerStatus(std::uint64_t uSeq) { - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); return mStreamMaps[sPeerStatus].erase(uSeq) != 0u; } @@ -4183,7 +4183,7 @@ NetworkOPsImp::unsubPeerStatus(std::uint64_t uSeq) bool NetworkOPsImp::subConsensus(InfoSub::ref isrListener) { - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); return mStreamMaps[sConsensusPhase].emplace(isrListener->getSeq(), isrListener).second; } @@ -4191,16 +4191,16 @@ NetworkOPsImp::subConsensus(InfoSub::ref isrListener) bool NetworkOPsImp::unsubConsensus(std::uint64_t uSeq) { - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); return mStreamMaps[sConsensusPhase].erase(uSeq) != 0u; } InfoSub::pointer NetworkOPsImp::findRpcSub(std::string const& strUrl) { - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); - subRpcMapType::iterator it = mRpcSubMap.find(strUrl); + subRpcMapType::iterator const it = mRpcSubMap.find(strUrl); if (it != mRpcSubMap.end()) return it->second; @@ -4211,7 +4211,7 @@ NetworkOPsImp::findRpcSub(std::string const& strUrl) InfoSub::pointer NetworkOPsImp::addRpcSub(std::string const& strUrl, InfoSub::ref rspEntry) { - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); mRpcSubMap.emplace(strUrl, rspEntry); @@ -4221,7 +4221,7 @@ NetworkOPsImp::addRpcSub(std::string const& strUrl, InfoSub::ref rspEntry) bool NetworkOPsImp::tryRemoveRpcSub(std::string const& strUrl) { - std::lock_guard sl(mSubLock); + std::lock_guard const sl(mSubLock); auto pInfo = findRpcSub(strUrl); if (!pInfo) @@ -4409,7 +4409,7 @@ NetworkOPsImp::getBookPage( .setJson(jvOffer[jss::taker_pays_funded]); } - STAmount saOwnerPays = (parityRate == offerRate) + STAmount const saOwnerPays = (parityRate == offerRate) ? saTakerGetsFunded : std::min(saOwnerFunds, multiply(saTakerGetsFunded, offerRate)); @@ -4582,7 +4582,7 @@ NetworkOPsImp::collect_metrics() std::chrono::steady_clock::now() - start); counters[static_cast(mode)].dur += current; - std::lock_guard lock(m_statsMutex); + std::lock_guard const lock(m_statsMutex); m_stats.disconnected_duration.set( counters[static_cast(OperatingMode::DISCONNECTED)].dur.count()); m_stats.connected_duration.set( @@ -4610,7 +4610,7 @@ NetworkOPsImp::StateAccounting::mode(OperatingMode om) { auto now = std::chrono::steady_clock::now(); - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); ++counters_[static_cast(om)].transitions; if (om == OperatingMode::FULL && counters_[static_cast(om)].transitions == 1) { diff --git a/src/xrpld/app/misc/SHAMapStoreImp.cpp b/src/xrpld/app/misc/SHAMapStoreImp.cpp index 6460d99686..140f260d56 100644 --- a/src/xrpld/app/misc/SHAMapStoreImp.cpp +++ b/src/xrpld/app/misc/SHAMapStoreImp.cpp @@ -16,14 +16,14 @@ namespace xrpl { void SHAMapStoreImp::SavedStateDB::init(BasicConfig const& config, std::string const& dbName) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); initStateDB(sqlDb_, config, dbName); } LedgerIndex SHAMapStoreImp::SavedStateDB::getCanDelete() { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); return xrpl::getCanDelete(sqlDb_); } @@ -31,7 +31,7 @@ SHAMapStoreImp::SavedStateDB::getCanDelete() LedgerIndex SHAMapStoreImp::SavedStateDB::setCanDelete(LedgerIndex canDelete) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); return xrpl::setCanDelete(sqlDb_, canDelete); } @@ -39,7 +39,7 @@ SHAMapStoreImp::SavedStateDB::setCanDelete(LedgerIndex canDelete) SavedState SHAMapStoreImp::SavedStateDB::getState() { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); return xrpl::getSavedState(sqlDb_); } @@ -47,14 +47,14 @@ SHAMapStoreImp::SavedStateDB::getState() void SHAMapStoreImp::SavedStateDB::setState(SavedState const& state) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); xrpl::setSavedState(sqlDb_, state); } void SHAMapStoreImp::SavedStateDB::setLastRotated(LedgerIndex seq) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); xrpl::setLastRotated(sqlDb_, seq); } @@ -180,7 +180,7 @@ void SHAMapStoreImp::onLedgerClosed(std::shared_ptr const& ledger) { { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); newLedger_ = ledger; working_ = true; } @@ -338,7 +338,7 @@ SHAMapStoreImp::run() void SHAMapStoreImp::dbPaths() { - Section section{app_.config().section(ConfigSection::nodeDatabase())}; + Section const section{app_.config().section(ConfigSection::nodeDatabase())}; boost::filesystem::path dbPath = get(section, "path"); if (boost::filesystem::exists(dbPath)) @@ -426,7 +426,7 @@ SHAMapStoreImp::dbPaths() } // The necessary directories exist. Now, remove any others. - for (boost::filesystem::path& p : pathsToDelete) + for (boost::filesystem::path const& p : pathsToDelete) boost::filesystem::remove_all(p); } @@ -595,7 +595,7 @@ SHAMapStoreImp::stop() if (thread_.joinable()) { { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); stop_ = true; cond_.notify_one(); } diff --git a/src/xrpld/app/misc/ValidatorList.h b/src/xrpld/app/misc/ValidatorList.h index e774da4713..c10561b6e7 100644 --- a/src/xrpld/app/misc/ValidatorList.h +++ b/src/xrpld/app/misc/ValidatorList.h @@ -646,7 +646,7 @@ public: QuorumKeys getQuorumKeys() const { - shared_lock read_lock{mutex_}; + shared_lock const read_lock{mutex_}; return {quorum_, trustedSigningKeys_}; } diff --git a/src/xrpld/app/misc/detail/AmendmentTable.cpp b/src/xrpld/app/misc/detail/AmendmentTable.cpp index 7569fa13b5..afecb08b24 100644 --- a/src/xrpld/app/misc/detail/AmendmentTable.cpp +++ b/src/xrpld/app/misc/detail/AmendmentTable.cpp @@ -632,7 +632,7 @@ AmendmentTableImpl::get(uint256 const& amendmentHash, std::lock_guardvote != AmendmentVote::down) @@ -685,7 +685,7 @@ AmendmentTableImpl::unVeto(uint256 const& amendment) bool AmendmentTableImpl::enable(uint256 const& amendment) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); AmendmentState& s = add(amendment, lock); if (s.enabled) @@ -705,7 +705,7 @@ AmendmentTableImpl::enable(uint256 const& amendment) bool AmendmentTableImpl::isEnabled(uint256 const& amendment) const { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); AmendmentState const* s = get(amendment, lock); return (s != nullptr) && s->enabled; } @@ -713,7 +713,7 @@ AmendmentTableImpl::isEnabled(uint256 const& amendment) const bool AmendmentTableImpl::isSupported(uint256 const& amendment) const { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); AmendmentState const* s = get(amendment, lock); return (s != nullptr) && s->supported; } @@ -721,14 +721,14 @@ AmendmentTableImpl::isSupported(uint256 const& amendment) const bool AmendmentTableImpl::hasUnsupportedEnabled() const { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); return unsupportedEnabled_; } std::optional AmendmentTableImpl::firstUnsupportedExpected() const { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); return firstUnsupportedExpected_; } @@ -740,7 +740,7 @@ AmendmentTableImpl::doValidation(std::set const& enabled) const std::vector amendments; { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); amendments.reserve(amendmentMap_.size()); for (auto const& e : amendmentMap_) { @@ -778,7 +778,7 @@ AmendmentTableImpl::doVoting( << enabledAmendments.size() << ", " << majorityAmendments.size() << ", " << valSet.size(); - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); // Keep a record of the votes we received. previousTrustedVotes_.recordVotes(rules, valSet, closeTime, j_, lock); @@ -860,7 +860,7 @@ AmendmentTableImpl::doVoting( bool AmendmentTableImpl::needValidatedLedger(LedgerIndex ledgerSeq) const { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); // Is there a ledger in which an amendment could have been enabled // between these two ledger sequences? @@ -877,7 +877,7 @@ AmendmentTableImpl::doValidatedLedger( for (auto& e : enabled) enable(e); - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); // Remember the ledger sequence of this update. lastUpdateSeq_ = ledgerSeq; @@ -888,7 +888,7 @@ AmendmentTableImpl::doValidatedLedger( firstUnsupportedExpected_.reset(); for (auto const& [hash, time] : majority) { - AmendmentState& s = add(hash, lock); + AmendmentState const& s = add(hash, lock); if (s.enabled) continue; @@ -908,7 +908,7 @@ AmendmentTableImpl::doValidatedLedger( void AmendmentTableImpl::trustChanged(hash_set const& allTrusted) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); previousTrustedVotes_.trustChanged(allTrusted, lock); } @@ -956,7 +956,7 @@ AmendmentTableImpl::getJson(bool isAdmin) const { Json::Value ret(Json::objectValue); { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); for (auto const& e : amendmentMap_) { injectJson( @@ -972,7 +972,7 @@ AmendmentTableImpl::getJson(uint256 const& amendmentID, bool isAdmin) const Json::Value ret = Json::objectValue; { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); AmendmentState const* a = get(amendmentID, lock); if (a != nullptr) { diff --git a/src/xrpld/app/misc/detail/TxQ.cpp b/src/xrpld/app/misc/detail/TxQ.cpp index c03ef6872e..8f8f14d5a7 100644 --- a/src/xrpld/app/misc/detail/TxQ.cpp +++ b/src/xrpld/app/misc/detail/TxQ.cpp @@ -20,8 +20,8 @@ static FeeLevel64 getFeeLevelPaid(ReadView const& view, STTx const& tx) { auto const [baseFee, effectiveFeePaid] = [&view, &tx]() { - XRPAmount baseFee = calculateBaseFee(view, tx); - XRPAmount feePaid = tx[sfFee].xrp(); + XRPAmount const baseFee = calculateBaseFee(view, tx); + XRPAmount const feePaid = tx[sfFee].xrp(); // If baseFee is 0 then the cost of a basic transaction is free, but we // need the effective fee level to be non-zero. @@ -172,7 +172,7 @@ sumOfFirstSquares(std::size_t xIn) // We expect that size_t == std::uint64_t but, just in case, guarantee // we lose no bits. - std::uint64_t x{xIn}; + std::uint64_t const x{xIn}; // If x is anywhere on the order of 2^^21, it's going // to completely dominate the computation and is likely @@ -268,7 +268,7 @@ TxQ::MaybeTx::apply(Application& app, OpenView& view, beast::Journal j) { // If the rules or flags change, preflight again XRPL_ASSERT(pfResult, "xrpl::TxQ::MaybeTx::apply : preflight result is set"); - NumberSO stNumberSO{view.rules().enabled(fixUniversalNumber)}; + NumberSO const stNumberSO{view.rules().enabled(fixUniversalNumber)}; if (pfResult->rules != view.rules() || pfResult->flags != flags) { @@ -691,7 +691,7 @@ TxQ::apply( ApplyFlags flags, beast::Journal j) { - NumberSO stNumberSO{view.rules().enabled(fixUniversalNumber)}; + NumberSO const stNumberSO{view.rules().enabled(fixUniversalNumber)}; // See if the transaction is valid, properly formed, // etc. before doing potentially expensive queue @@ -736,7 +736,7 @@ TxQ::apply( return {terPRE_TICKET, false}; } - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); // accountIter is not const because it may be updated further down. AccountMap::iterator accountIter = byAccount_.find(account); @@ -1287,7 +1287,7 @@ TxQ::apply( void TxQ::processClosedLedger(Application& app, ReadView const& view, bool timeLeap) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); feeMetrics_.update(app, view, timeLeap, setup_); auto const& snapshot = feeMetrics_.getSnapshot(); @@ -1366,7 +1366,7 @@ TxQ::accept(Application& app, OpenView& view) auto ledgerChanged = false; - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); auto const metricsSnapshot = feeMetrics_.getSnapshot(); @@ -1530,7 +1530,7 @@ TxQ::accept(Application& app, OpenView& view) SeqProxy TxQ::nextQueuableSeq(std::shared_ptr const& sleAccount) const { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); return nextQueuableSeqImpl(sleAccount, lock); } @@ -1621,7 +1621,7 @@ TxQ::tryDirectApply( return {}; FeeLevel64 const requiredFeeLevel = [this, &view, flags]() { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); return getRequiredFeeLevel(view, flags, feeMetrics_.getSnapshot(), lock); }(); @@ -1645,9 +1645,9 @@ TxQ::tryDirectApply( { // If the applied transaction replaced a transaction in the // queue then remove the replaced transaction. - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); - AccountMap::iterator accountIter = byAccount_.find(account); + AccountMap::iterator const accountIter = byAccount_.find(account); if (accountIter != byAccount_.end()) { TxQAccount& txQAcct = accountIter->second; @@ -1694,7 +1694,7 @@ TxQ::getMetrics(OpenView const& view) const { Metrics result; - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); auto const snapshot = feeMetrics_.getSnapshot(); @@ -1715,7 +1715,7 @@ TxQ::getTxRequiredFeeAndSeq(OpenView const& view, std::shared_ptr co { auto const account = (*tx)[sfAccount]; - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); auto const snapshot = feeMetrics_.getSnapshot(); auto const baseFee = calculateBaseFee(view, *tx); @@ -1737,7 +1737,7 @@ TxQ::getAccountTxs(AccountID const& account) const { std::vector result; - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); AccountMap::const_iterator const accountIter{byAccount_.find(account)}; @@ -1757,7 +1757,7 @@ TxQ::getTxs() const { std::vector result; - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); result.reserve(byFee_.size()); diff --git a/src/xrpld/app/misc/detail/ValidatorList.cpp b/src/xrpld/app/misc/detail/ValidatorList.cpp index abf64a4a93..5543d0029f 100644 --- a/src/xrpld/app/misc/detail/ValidatorList.cpp +++ b/src/xrpld/app/misc/detail/ValidatorList.cpp @@ -132,7 +132,7 @@ ValidatorList::load( ")?" // end optional comment block ); - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; JLOG(j_.debug()) << "Loading configured trusted validator list publisher keys"; @@ -901,7 +901,7 @@ ValidatorList::applyListsAndBroadcast( networkOPs.clearUNLBlocked(); } } - bool broadcast = disposition <= ListDisposition::known_sequence; + bool const broadcast = disposition <= ListDisposition::known_sequence; // this function is only called for PublicKeys which are not specified // in the config file (Note: Keys specified in the local config file are @@ -936,7 +936,7 @@ ValidatorList::applyLists( 1) return PublisherListStats{ListDisposition::unsupported_version}; - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; PublisherListStats result; for (auto const& blobInfo : blobs) @@ -1106,7 +1106,7 @@ ValidatorList::applyList( // LCOV_EXCL_STOP } - PublicKey pubKey = *pubKeyOpt; + PublicKey const pubKey = *pubKeyOpt; if (result > ListDisposition::pending) { if (publisherLists_.contains(pubKey)) @@ -1238,7 +1238,7 @@ ValidatorList::loadLists() using namespace boost::filesystem; using namespace boost::system::errc; - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; std::vector sites; sites.reserve(publisherLists_.size()); @@ -1381,7 +1381,7 @@ ValidatorList::verify( bool ValidatorList::listed(PublicKey const& identity) const { - std::shared_lock read_lock{mutex_}; + std::shared_lock const read_lock{mutex_}; auto const pubKey = validatorManifests_.getMasterKey(identity); return keyListings_.contains(pubKey); @@ -1397,14 +1397,14 @@ ValidatorList::trusted(ValidatorList::shared_lock const&, PublicKey const& ident bool ValidatorList::trusted(PublicKey const& identity) const { - std::shared_lock read_lock{mutex_}; + std::shared_lock const read_lock{mutex_}; return trusted(read_lock, identity); } std::optional ValidatorList::getListedKey(PublicKey const& identity) const { - std::shared_lock read_lock{mutex_}; + std::shared_lock const read_lock{mutex_}; auto pubKey = validatorManifests_.getMasterKey(identity); if (keyListings_.contains(pubKey)) @@ -1424,7 +1424,7 @@ ValidatorList::getTrustedKey(ValidatorList::shared_lock const&, PublicKey const& std::optional ValidatorList::getTrustedKey(PublicKey const& identity) const { - std::shared_lock read_lock{mutex_}; + std::shared_lock const read_lock{mutex_}; return getTrustedKey(read_lock, identity); } @@ -1432,7 +1432,7 @@ ValidatorList::getTrustedKey(PublicKey const& identity) const bool ValidatorList::trustedPublisher(PublicKey const& identity) const { - std::shared_lock read_lock{mutex_}; + std::shared_lock const read_lock{mutex_}; return (identity.size() != 0u) && publisherLists_.contains(identity) && publisherLists_.at(identity).status < PublisherStatus::revoked; } @@ -1440,7 +1440,7 @@ ValidatorList::trustedPublisher(PublicKey const& identity) const std::optional ValidatorList::localPublicKey() const { - std::shared_lock read_lock{mutex_}; + std::shared_lock const read_lock{mutex_}; return localPubKey_; } @@ -1490,7 +1490,7 @@ ValidatorList::count(ValidatorList::shared_lock const&) const std::size_t ValidatorList::count() const { - std::shared_lock read_lock{mutex_}; + std::shared_lock const read_lock{mutex_}; return count(read_lock); } @@ -1533,7 +1533,7 @@ ValidatorList::expires(ValidatorList::shared_lock const&) const if (!localPublisherList.list.empty()) { - PublisherList collection = localPublisherList; + PublisherList const collection = localPublisherList; // Unfetched auto const& current = collection; auto chainedExpiration = current.validUntil; @@ -1550,7 +1550,7 @@ ValidatorList::expires(ValidatorList::shared_lock const&) const std::optional ValidatorList::expires() const { - std::shared_lock read_lock{mutex_}; + std::shared_lock const read_lock{mutex_}; return expires(read_lock); } @@ -1559,7 +1559,7 @@ ValidatorList::getJson() const { Json::Value res(Json::objectValue); - std::shared_lock read_lock{mutex_}; + std::shared_lock const read_lock{mutex_}; res[jss::validation_quorum] = static_cast(quorum_); @@ -1687,7 +1687,7 @@ ValidatorList::getJson() const void ValidatorList::for_each_listed(std::function func) const { - std::shared_lock read_lock{mutex_}; + std::shared_lock const read_lock{mutex_}; for (auto const& v : keyListings_) func(v.first, trusted(read_lock, v.first)); @@ -1703,7 +1703,7 @@ ValidatorList::for_each_available( std::size_t maxSequence, uint256 const& hash)> func) const { - std::shared_lock read_lock{mutex_}; + std::shared_lock const read_lock{mutex_}; for (auto const& [key, plCollection] : publisherLists_) { @@ -1727,7 +1727,7 @@ ValidatorList::getAvailable( std::string_view pubKey, std::optional forceVersion /* = {} */) { - std::shared_lock read_lock{mutex_}; + std::shared_lock const read_lock{mutex_}; auto const keyBlob = strViewUnHex(pubKey); @@ -1851,7 +1851,7 @@ ValidatorList::updateTrusted( if (timeKeeper_.now() > closeTime + 30s) closeTime = timeKeeper_.now(); - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; // Rotate pending and remove expired published lists bool good = true; @@ -2023,28 +2023,28 @@ ValidatorList::updateTrusted( hash_set ValidatorList::getTrustedMasterKeys() const { - std::shared_lock read_lock{mutex_}; + std::shared_lock const read_lock{mutex_}; return trustedMasterKeys_; } std::size_t ValidatorList::getListThreshold() const { - std::shared_lock read_lock{mutex_}; + std::shared_lock const read_lock{mutex_}; return listThreshold_; } hash_set ValidatorList::getNegativeUNL() const { - std::shared_lock read_lock{mutex_}; + std::shared_lock const read_lock{mutex_}; return negativeUNL_; } void ValidatorList::setNegativeUNL(hash_set const& negUnl) { - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; negativeUNL_ = negUnl; } diff --git a/src/xrpld/app/misc/detail/ValidatorSite.cpp b/src/xrpld/app/misc/detail/ValidatorSite.cpp index b93a1b8007..f9b6553fc2 100644 --- a/src/xrpld/app/misc/detail/ValidatorSite.cpp +++ b/src/xrpld/app/misc/detail/ValidatorSite.cpp @@ -110,7 +110,7 @@ ValidatorSite::load(std::vector const& siteURIs) { JLOG(j_.debug()) << "Loading configured validator list sites"; - std::lock_guard lock{sites_mutex_}; + std::lock_guard const lock{sites_mutex_}; return load(siteURIs, lock); } @@ -147,8 +147,8 @@ ValidatorSite::load( void ValidatorSite::start() { - std::lock_guard l0{sites_mutex_}; - std::lock_guard l1{state_mutex_}; + std::lock_guard const l0{sites_mutex_}; + std::lock_guard const l1{state_mutex_}; if (timer_.expiry() == clock_type::time_point{}) setTimer(l0, l1); } @@ -216,7 +216,7 @@ ValidatorSite::makeRequest( sites_[siteIdx].activeResource = resource; std::shared_ptr sp; auto timeoutCancel = [this]() { - std::lock_guard lock_state{state_mutex_}; + std::lock_guard const lock_state{state_mutex_}; // docs indicate cancel_one() can throw, but this // should be reconsidered if it changes to noexcept try @@ -280,7 +280,7 @@ ValidatorSite::makeRequest( sp->run(); // start a timer for the request, which shouldn't take more // than requestTimeout_ to complete - std::lock_guard lock_state{state_mutex_}; + std::lock_guard const lock_state{state_mutex_}; timer_.expires_after(requestTimeout_); timer_.async_wait([this, siteIdx](boost::system::error_code const& ec) { this->onRequestTimeout(siteIdx, ec); @@ -294,7 +294,7 @@ ValidatorSite::onRequestTimeout(std::size_t siteIdx, error_code const& ec) return; { - std::lock_guard lock_site{sites_mutex_}; + std::lock_guard const lock_site{sites_mutex_}; // In some circumstances, both this function and the response // handler (onSiteFetch or onTextFetch) can get queued and // processed. In all observed cases, the response handler @@ -311,7 +311,7 @@ ValidatorSite::onRequestTimeout(std::size_t siteIdx, error_code const& ec) "already been processed"; } - std::lock_guard lock_state{state_mutex_}; + std::lock_guard const lock_state{state_mutex_}; if (auto sp = work_.lock()) sp->cancel(); } @@ -330,7 +330,7 @@ ValidatorSite::onTimer(std::size_t siteIdx, error_code const& ec) try { - std::lock_guard lock{sites_mutex_}; + std::lock_guard const lock{sites_mutex_}; sites_[siteIdx].nextRefresh = clock_type::now() + sites_[siteIdx].refreshInterval; sites_[siteIdx].redirCount = 0; // the WorkSSL client ctor can throw if SSL init fails @@ -579,7 +579,7 @@ ValidatorSite::onSiteFetch( sites_[siteIdx].activeResource.reset(); } - std::lock_guard lock_state{state_mutex_}; + std::lock_guard const lock_state{state_mutex_}; fetching_ = false; if (!stopping_) setTimer(lock_sites, lock_state); @@ -592,7 +592,7 @@ ValidatorSite::onTextFetch( std::string const& res, std::size_t siteIdx) { - std::lock_guard lock_sites{sites_mutex_}; + std::lock_guard const lock_sites{sites_mutex_}; { try { @@ -616,7 +616,7 @@ ValidatorSite::onTextFetch( sites_[siteIdx].activeResource.reset(); } - std::lock_guard lock_state{state_mutex_}; + std::lock_guard const lock_state{state_mutex_}; fetching_ = false; if (!stopping_) setTimer(lock_sites, lock_state); @@ -632,7 +632,7 @@ ValidatorSite::getJson() const Json::Value jrr(Json::objectValue); Json::Value& jSites = (jrr[jss::validator_sites] = Json::arrayValue); { - std::lock_guard lock{sites_mutex_}; + std::lock_guard const lock{sites_mutex_}; for (Site const& site : sites_) { Json::Value& v = jSites.append(Json::objectValue); diff --git a/src/xrpld/app/misc/detail/WorkFile.h b/src/xrpld/app/misc/detail/WorkFile.h index 896d7ddc71..5113ec5f3a 100644 --- a/src/xrpld/app/misc/detail/WorkFile.h +++ b/src/xrpld/app/misc/detail/WorkFile.h @@ -44,18 +44,18 @@ private: //------------------------------------------------------------------------------ -WorkFile::WorkFile(std::string const& path, boost::asio::io_context& ios, callback_type cb) +inline WorkFile::WorkFile(std::string const& path, boost::asio::io_context& ios, callback_type cb) : path_(path), cb_(std::move(cb)), ios_(ios), strand_(boost::asio::make_strand(ios)) { } -WorkFile::~WorkFile() +inline WorkFile::~WorkFile() { if (cb_) cb_(make_error_code(boost::system::errc::interrupted), {}); } -void +inline void WorkFile::run() { if (!strand_.running_in_this_thread()) @@ -71,7 +71,7 @@ WorkFile::run() cb_ = nullptr; } -void +inline void WorkFile::cancel() { // Nothing to do. Either it finished in run, or it didn't start. diff --git a/src/xrpld/app/misc/detail/WorkPlain.h b/src/xrpld/app/misc/detail/WorkPlain.h index d1df5b4b3b..361a7b4513 100644 --- a/src/xrpld/app/misc/detail/WorkPlain.h +++ b/src/xrpld/app/misc/detail/WorkPlain.h @@ -35,7 +35,7 @@ private: //------------------------------------------------------------------------------ -WorkPlain::WorkPlain( +inline WorkPlain::WorkPlain( std::string const& host, std::string const& path, std::string const& port, @@ -47,7 +47,7 @@ WorkPlain::WorkPlain( { } -void +inline void WorkPlain::onConnect(error_code const& ec) { if (ec) diff --git a/src/xrpld/app/rdb/backend/detail/Node.cpp b/src/xrpld/app/rdb/backend/detail/Node.cpp index 926c01b8b3..b176588771 100644 --- a/src/xrpld/app/rdb/backend/detail/Node.cpp +++ b/src/xrpld/app/rdb/backend/detail/Node.cpp @@ -105,7 +105,7 @@ makeLedgerDBs( std::optional getMinLedgerSeq(soci::session& session, TableType type) { - std::string query = "SELECT MIN(LedgerSeq) FROM " + to_string(type) + ";"; + std::string const query = "SELECT MIN(LedgerSeq) FROM " + to_string(type) + ";"; // SOCI requires boost::optional (not std::optional) as the parameter. boost::optional m; session << query, soci::into(m); @@ -115,7 +115,7 @@ getMinLedgerSeq(soci::session& session, TableType type) std::optional getMaxLedgerSeq(soci::session& session, TableType type) { - std::string query = "SELECT MAX(LedgerSeq) FROM " + to_string(type) + ";"; + std::string const query = "SELECT MAX(LedgerSeq) FROM " + to_string(type) + ";"; // SOCI requires boost::optional (not std::optional) as the parameter. boost::optional m; session << query, soci::into(m); @@ -330,7 +330,7 @@ saveValidatedLedger( } { - static std::string addLedger( + static std::string const addLedger( R"sql(INSERT OR REPLACE INTO Ledgers (LedgerHash,LedgerSeq,PrevHash,TotalCoins,ClosingTime,PrevClosingTime, CloseTimeRes,CloseFlags,AccountSetHash,TransSetHash) @@ -576,7 +576,7 @@ getHashesByIndex(soci::session& session, LedgerIndex minSeq, LedgerIndex maxSeq, std::pair>, int> getTxHistory(soci::session& session, Application& app, LedgerIndex startIndex, int quantity) { - std::string sql = boost::str( + std::string const sql = boost::str( boost::format( "SELECT LedgerSeq, Status, RawTxn " "FROM Transactions ORDER BY LedgerSeq DESC LIMIT %u,%u;") % @@ -749,7 +749,7 @@ getAccountTxs( { RelationalDatabase::AccountTxs ret; - std::string sql = transactionsSQL( + std::string const sql = transactionsSQL( app, "AccountTransactions.LedgerSeq,Status,RawTxn,TxnMeta", options, @@ -873,7 +873,7 @@ getAccountTxsB( { std::vector ret; - std::string sql = transactionsSQL( + std::string const sql = transactionsSQL( app, "AccountTransactions.LedgerSeq,Status,RawTxn,TxnMeta", options, @@ -1222,7 +1222,7 @@ getTransaction( if (!ledgerSeq) return std::pair{std::move(txn), nullptr}; - std::uint32_t inLedger = rangeCheckedCast(ledgerSeq.value()); + std::uint32_t const inLedger = rangeCheckedCast(ledgerSeq.value()); auto txMeta = std::make_shared(id, inLedger, rawMeta); @@ -1242,7 +1242,8 @@ getTransaction( bool dbHasSpace(soci::session& session, Config const& config, beast::Journal j) { - boost::filesystem::space_info space = boost::filesystem::space(config.legacy("database_path")); + boost::filesystem::space_info const space = + boost::filesystem::space(config.legacy("database_path")); if (space.available < megabytes(512)) { @@ -1252,8 +1253,8 @@ dbHasSpace(soci::session& session, Config const& config, beast::Journal j) if (config.useTxTables()) { - DatabaseCon::Setup dbSetup = setup_DatabaseCon(config); - boost::filesystem::path dbPath = dbSetup.dataDir / TxDBName; + DatabaseCon::Setup const dbSetup = setup_DatabaseCon(config); + boost::filesystem::path const dbPath = dbSetup.dataDir / TxDBName; boost::system::error_code ec; std::optional dbSize = boost::filesystem::file_size(dbPath, ec); if (ec) @@ -1274,8 +1275,8 @@ dbHasSpace(soci::session& session, Config const& config, beast::Journal j) }(); std::uint32_t pageCount = 0; session << "PRAGMA page_count;", soci::into(pageCount); - std::uint32_t freePages = maxPages - pageCount; - std::uint64_t freeSpace = safe_cast(freePages) * pageSize; + std::uint32_t const freePages = maxPages - pageCount; + std::uint64_t const freeSpace = safe_cast(freePages) * pageSize; JLOG(j.info()) << "Transaction DB pathname: " << dbPath.string() << "; file size: " << dbSize.value_or(-1) << " bytes" << "; SQLite page size: " << pageSize << " bytes" diff --git a/src/xrpld/app/rdb/detail/PeerFinder.cpp b/src/xrpld/app/rdb/detail/PeerFinder.cpp index d619d4bb85..a568461fb7 100644 --- a/src/xrpld/app/rdb/detail/PeerFinder.cpp +++ b/src/xrpld/app/rdb/detail/PeerFinder.cpp @@ -5,7 +5,7 @@ namespace xrpl { void initPeerFinderDB(soci::session& session, BasicConfig const& config, beast::Journal j) { - DBConfig m_sociConfig(config, "peerfinder"); + DBConfig const m_sociConfig(config, "peerfinder"); m_sociConfig.open(session); JLOG(j.info()) << "Opening database at '" << m_sociConfig.connectionString() << "'"; diff --git a/src/xrpld/consensus/Consensus.cpp b/src/xrpld/consensus/Consensus.cpp index 29d0e9db1c..9ad7e677ad 100644 --- a/src/xrpld/consensus/Consensus.cpp +++ b/src/xrpld/consensus/Consensus.cpp @@ -132,7 +132,7 @@ checkConsensusReached( CLOG(clog) << "agreeing and total adjusted: " << agreeing << ',' << total << ". "; } - std::size_t currentPercentage = (agreeing * 100) / total; + std::size_t const currentPercentage = (agreeing * 100) / total; CLOG(clog) << "currentPercentage: " << currentPercentage; bool const ret = currentPercentage >= minConsensusPct; diff --git a/src/xrpld/consensus/Consensus.h b/src/xrpld/consensus/Consensus.h index 2ed40cd2eb..d5441dc1c4 100644 --- a/src/xrpld/consensus/Consensus.h +++ b/src/xrpld/consensus/Consensus.h @@ -1116,7 +1116,7 @@ Consensus::phaseOpen(std::unique_ptr const& clog) using namespace std::chrono; // it is shortly before ledger close time - bool anyTransactions = adaptor_.hasOpenTransactions(); + bool const anyTransactions = adaptor_.hasOpenTransactions(); auto proposersClosed = currPeerPositions_.size(); auto proposersValidated = adaptor_.proposersValidated(prevLedgerID_); @@ -1186,7 +1186,7 @@ Consensus::shouldPause(std::unique_ptr const& clog) previousLedger_.seq() - std::min(adaptor_.getValidLedgerIndex(), previousLedger_.seq())); auto [quorum, trustedKeys] = adaptor_.getQuorumKeys(); std::size_t const totalValidators = trustedKeys.size(); - std::size_t laggards = adaptor_.laggards(previousLedger_.seq(), trustedKeys); + std::size_t const laggards = adaptor_.laggards(previousLedger_.seq(), trustedKeys); std::size_t const offline = trustedKeys.size(); std::stringstream vars; @@ -1408,7 +1408,7 @@ this. inline int participantsNeeded(int participants, int percent) { - int result = ((participants * percent) + (percent / 2)) / 100; + int const result = ((participants * percent) + (percent / 2)) / 100; return (result == 0) ? 1 : result; } @@ -1757,7 +1757,7 @@ Consensus::createDisputes(TxSet_t const& o, std::unique_ptrtxns.find(txId) && o.find(txId)), "xrpl::Consensus::createDisputes : has disputed transactions"); - Tx_t tx = inThisSet ? result_->txns.find(txId) : o.find(txId); + Tx_t const tx = inThisSet ? result_->txns.find(txId) : o.find(txId); auto txID = tx.id(); if (result_->disputes.find(txID) != result_->disputes.end()) diff --git a/src/xrpld/consensus/DisputedTx.h b/src/xrpld/consensus/DisputedTx.h index 89cb5115bb..0657ad7ac2 100644 --- a/src/xrpld/consensus/DisputedTx.h +++ b/src/xrpld/consensus/DisputedTx.h @@ -97,7 +97,7 @@ public: // Compute the percentage of nodes voting 'yes' (possibly including us) int const support = (yays_ + (proposing && ourVote_ ? 1 : 0)) * 100; - int total = nays_ + yays_ + (proposing ? 1 : 0); + int const total = nays_ + yays_ + (proposing ? 1 : 0); if (!total) // There are no votes, so we know nothing return false; diff --git a/src/xrpld/consensus/LedgerTrie.h b/src/xrpld/consensus/LedgerTrie.h index d34dda8e1b..335c2cae7f 100644 --- a/src/xrpld/consensus/LedgerTrie.h +++ b/src/xrpld/consensus/LedgerTrie.h @@ -128,7 +128,7 @@ public: SpanTip tip() const { - Seq tipSeq{end_ - Seq{1}}; + Seq const tipSeq{end_ - Seq{1}}; return SpanTip{tipSeq, ledger_[tipSeq], ledger_}; } @@ -149,8 +149,8 @@ private: std::optional sub(Seq from, Seq to) const { - Seq newFrom = clamp(from); - Seq newTo = clamp(to); + Seq const newFrom = clamp(from); + Seq const newTo = clamp(to); if (newFrom < newTo) return Span(newFrom, newTo, ledger_); return std::nullopt; @@ -344,6 +344,7 @@ class LedgerTrie std::pair find(Ledger const& ledger) const { + // NOLINTNEXTLINE(misc-const-correctness) Node* curr = root.get(); // Root is always defined and is in common with all ledgers diff --git a/src/xrpld/consensus/Validations.h b/src/xrpld/consensus/Validations.h index 4cd922d6b2..4d0b64a350 100644 --- a/src/xrpld/consensus/Validations.h +++ b/src/xrpld/consensus/Validations.h @@ -422,7 +422,7 @@ private: checkAcquired(lock); - std::pair valPair{val.seq(), val.ledgerID()}; + std::pair const valPair{val.seq(), val.ledgerID()}; auto it = acquiring_.find(valPair); if (it != acquiring_.end()) { @@ -479,7 +479,7 @@ private: void current(std::lock_guard const& lock, Pre&& pre, F&& f) { - NetClock::time_point t = adaptor_.now(); + NetClock::time_point const t = adaptor_.now(); pre(current_.size()); auto it = current_.begin(); while (it != current_.end()) @@ -569,7 +569,7 @@ public: bool canValidateSeq(Seq const s) { - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; return localSeqEnforcer_(byLedger_.clock().now(), s, parms_); } @@ -588,7 +588,7 @@ public: return ValStatus::stale; { - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; // Check that validation sequence is greater than any non-expired // validations sequence from that validator; if it's not, perform @@ -645,7 +645,7 @@ public: if (!inserted) { // Replace existing only if this one is newer - Validation& oldVal = it->second; + Validation const& oldVal = it->second; if (val.signTime() > oldVal.signTime()) { std::pair old(oldVal.seq(), oldVal.ledgerID()); @@ -674,7 +674,7 @@ public: void setSeqToKeep(Seq const& low, Seq const& high) { - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; XRPL_ASSERT(low < high, "xrpl::Validations::setSeqToKeep : valid inputs"); toKeep_ = {low, high}; } @@ -689,7 +689,7 @@ public: { auto const start = std::chrono::steady_clock::now(); { - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; if (toKeep_) { // We only need to refresh the keep range when it's just about @@ -746,7 +746,7 @@ public: void trustChanged(hash_set const& added, hash_set const& removed) { - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; for (auto& [nodeId, validation] : current_) { @@ -782,7 +782,7 @@ public: Json::Value getJsonTrie() const { - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; return trie_.getJson(); } @@ -801,7 +801,7 @@ public: std::optional> getPreferred(Ledger const& curr) { - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; std::optional> preferred = withTrie(lock, [this](LedgerTrie& trie) { return trie.getPreferred(localSeqEnforcer_.largest()); }); @@ -913,7 +913,7 @@ public: std::size_t getNodesAfter(Ledger const& ledger, ID const& ledgerID) { - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; // Use trie if ledger is the right one if (ledger.id() == ledgerID) @@ -936,7 +936,7 @@ public: currentTrusted() { std::vector ret; - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; current( lock, [&](std::size_t numValidations) { ret.reserve(numValidations); }, @@ -955,7 +955,7 @@ public: getCurrentNodeIDs() -> hash_set { hash_set ret; - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; current( lock, [&](std::size_t numValidations) { ret.reserve(numValidations); }, @@ -973,7 +973,7 @@ public: numTrustedForLedger(ID const& ledgerID) { std::size_t count = 0; - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; byLedger( lock, ledgerID, @@ -995,7 +995,7 @@ public: getTrustedForLedger(ID const& ledgerID, Seq const& seq) { std::vector res; - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; byLedger( lock, ledgerID, @@ -1018,7 +1018,7 @@ public: fees(ID const& ledgerID, std::uint32_t baseFee) { std::vector res; - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; byLedger( lock, ledgerID, @@ -1041,7 +1041,7 @@ public: void flush() { - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; current_.clear(); } @@ -1084,28 +1084,28 @@ public: std::size_t sizeOfCurrentCache() const { - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; return current_.size(); } std::size_t sizeOfSeqEnforcersCache() const { - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; return seqEnforcers_.size(); } std::size_t sizeOfByLedgerCache() const { - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; return byLedger_.size(); } std::size_t sizeOfBySequenceCache() const { - std::lock_guard lock{mutex_}; + std::lock_guard const lock{mutex_}; return bySequence_.size(); } }; diff --git a/src/xrpld/core/detail/Config.cpp b/src/xrpld/core/detail/Config.cpp index 270764a17b..204b29ad30 100644 --- a/src/xrpld/core/detail/Config.cpp +++ b/src/xrpld/core/detail/Config.cpp @@ -390,10 +390,10 @@ Config::setup(std::string const& strConf, bool bQuiet, bool bSilent, bool bStand if (RUN_STANDALONE) LEDGER_HISTORY = 0; - Section ledgerTxTablesSection = section("ledger_tx_tables"); + Section const ledgerTxTablesSection = section("ledger_tx_tables"); get_if_exists(ledgerTxTablesSection, "use_tx_tables", USE_TX_TABLES); - Section& nodeDbSection{section(ConfigSection::nodeDatabase())}; + Section const& nodeDbSection{section(ConfigSection::nodeDatabase())}; get_if_exists(nodeDbSection, "fast_load", FAST_LOAD); } @@ -471,7 +471,7 @@ Config::loadFromString(std::string const& fileContents) if (std::count(line.begin(), line.end(), ':') != 1) continue; - std::string result = std::regex_replace(line, e, " $1"); + std::string const result = std::regex_replace(line, e, " $1"); // sanity check the result of the replace, should be same length // as input if (result.size() == line.size()) @@ -487,7 +487,7 @@ Config::loadFromString(std::string const& fileContents) std::string dbPath; if (getSingleSection(secConfig, "database_path", dbPath, j_)) { - boost::filesystem::path p(dbPath); + boost::filesystem::path const p(dbPath); legacy("database_path", boost::filesystem::absolute(p).string()); } } @@ -890,7 +890,7 @@ Config::loadFromString(std::string const& fileContents) ", must be: [0-9]+ [minutes|hours|days|weeks]"); } - std::uint32_t duration = beast::lexicalCastThrow(match[1].str()); + std::uint32_t const duration = beast::lexicalCastThrow(match[1].str()); if (boost::iequals(match[2], "minutes")) { @@ -1226,7 +1226,7 @@ setup_DatabaseCon(Config const& c, std::optional j) "Configuration file may not define both " "\"safety_level\" and \"journal_mode\""); } - bool higherRisk = + bool const higherRisk = boost::iequals(journal_mode, "memory") || boost::iequals(journal_mode, "off"); showRiskWarning = showRiskWarning || higherRisk; if (higherRisk || boost::iequals(journal_mode, "delete") || @@ -1250,7 +1250,7 @@ setup_DatabaseCon(Config const& c, std::optional j) "Configuration file may not define both " "\"safety_level\" and \"synchronous\""); } - bool higherRisk = boost::iequals(synchronous, "off"); + bool const higherRisk = boost::iequals(synchronous, "off"); showRiskWarning = showRiskWarning || higherRisk; if (higherRisk || boost::iequals(synchronous, "normal") || boost::iequals(synchronous, "full") || boost::iequals(synchronous, "extra")) @@ -1271,7 +1271,7 @@ setup_DatabaseCon(Config const& c, std::optional j) "Configuration file may not define both " "\"safety_level\" and \"temp_store\""); } - bool higherRisk = boost::iequals(temp_store, "memory"); + bool const higherRisk = boost::iequals(temp_store, "memory"); showRiskWarning = showRiskWarning || higherRisk; if (higherRisk || boost::iequals(temp_store, "default") || boost::iequals(temp_store, "file")) diff --git a/src/xrpld/overlay/Overlay.h b/src/xrpld/overlay/Overlay.h index f1d1104d4e..7d2508a584 100644 --- a/src/xrpld/overlay/Overlay.h +++ b/src/xrpld/overlay/Overlay.h @@ -18,7 +18,7 @@ namespace boost { namespace asio { namespace ssl { class context; -} +} // namespace ssl } // namespace asio } // namespace boost diff --git a/src/xrpld/overlay/Peer.h b/src/xrpld/overlay/Peer.h index a0e4c040fd..df2cc5bcb7 100644 --- a/src/xrpld/overlay/Peer.h +++ b/src/xrpld/overlay/Peer.h @@ -11,7 +11,7 @@ namespace xrpl { namespace Resource { class Charge; -} +} // namespace Resource enum class ProtocolFeature { ValidatorListPropagation, diff --git a/src/xrpld/overlay/Slot.h b/src/xrpld/overlay/Slot.h index 11cbd09e36..44a2e7afad 100644 --- a/src/xrpld/overlay/Slot.h +++ b/src/xrpld/overlay/Slot.h @@ -374,7 +374,7 @@ Slot::update( if (journal_.trace()) str << k << " "; v.state = PeerState::Squelched; - std::chrono::seconds duration = + std::chrono::seconds const duration = getSquelchDuration(peers_.size() - maxSelectedPeers_); v.expire = now + duration; handler_.squelch(validator, k, duration.count()); diff --git a/src/xrpld/overlay/detail/Cluster.cpp b/src/xrpld/overlay/detail/Cluster.cpp index 0ee633fb90..72b7ef5147 100644 --- a/src/xrpld/overlay/detail/Cluster.cpp +++ b/src/xrpld/overlay/detail/Cluster.cpp @@ -18,7 +18,7 @@ Cluster::Cluster(beast::Journal j) : j_(j) std::optional Cluster::member(PublicKey const& identity) const { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); auto iter = nodes_.find(identity); if (iter == nodes_.end()) @@ -29,7 +29,7 @@ Cluster::member(PublicKey const& identity) const std::size_t Cluster::size() const { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); return nodes_.size(); } @@ -41,7 +41,7 @@ Cluster::update( std::uint32_t loadFee, NetClock::time_point reportTime) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); auto iter = nodes_.find(identity); @@ -63,7 +63,7 @@ Cluster::update( void Cluster::for_each(std::function func) const { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); for (auto const& ni : nodes_) func(ni); } diff --git a/src/xrpld/overlay/detail/ConnectAttempt.cpp b/src/xrpld/overlay/detail/ConnectAttempt.cpp index 406370ff19..40466f19b9 100644 --- a/src/xrpld/overlay/detail/ConnectAttempt.cpp +++ b/src/xrpld/overlay/detail/ConnectAttempt.cpp @@ -143,7 +143,7 @@ ConnectAttempt::onShutdown(error_code ec) // occur if a peer does not perform a graceful disconnect // - broken_pipe: the peer is gone // - application data after close notify: benign SSL shutdown condition - bool shouldLog = + bool const shouldLog = (ec != boost::asio::error::eof && ec != boost::asio::error::operation_aborted && ec.message().find("application data after close notify") == std::string::npos); @@ -287,8 +287,8 @@ ConnectAttempt::onTimer(error_code ec) // Determine which timer expired by checking their expiry times auto const now = std::chrono::steady_clock::now(); - bool globalExpired = (timer_.expiry() <= now); - bool stepExpired = (stepTimer_.expiry() <= now); + bool const globalExpired = (timer_.expiry() <= now); + bool const stepExpired = (stepTimer_.expiry() <= now); if (globalExpired) { diff --git a/src/xrpld/overlay/detail/Handshake.cpp b/src/xrpld/overlay/detail/Handshake.cpp index 0992d252b0..f70ec864da 100644 --- a/src/xrpld/overlay/detail/Handshake.cpp +++ b/src/xrpld/overlay/detail/Handshake.cpp @@ -23,7 +23,7 @@ getFeatureValue(boost::beast::http::fields const& headers, std::string const& fe if (header == headers.end()) return {}; boost::smatch match; - boost::regex rx(feature + "=([^;\\s]+)"); + boost::regex const rx(feature + "=([^;\\s]+)"); std::string const allFeatures(header->value()); if (boost::regex_search(allFeatures, match, rx)) return {match[1]}; @@ -107,12 +107,12 @@ hashLastMessage(SSL const* ssl, size_t (*get)(const SSL*, void*, size_t)) constexpr std::size_t sslMinimumFinishedLength = 12; unsigned char buf[1024]; - size_t len = get(ssl, buf, sizeof(buf)); + size_t const len = get(ssl, buf, sizeof(buf)); if (len < sslMinimumFinishedLength) return std::nullopt; - sha512_hasher h; + sha512_hasher const h; base_uint<512> cookie; SHA512(buf, len, cookie.data()); diff --git a/src/xrpld/overlay/detail/Message.cpp b/src/xrpld/overlay/detail/Message.cpp index 4d043500c7..1f0c6f608d 100644 --- a/src/xrpld/overlay/detail/Message.cpp +++ b/src/xrpld/overlay/detail/Message.cpp @@ -202,7 +202,7 @@ Message::getBuffer(Compressed tryCompressed) int Message::getType(std::uint8_t const* in) { - int type = (static_cast(*(in + 4)) << 8) + *(in + 5); + int const type = (static_cast(*(in + 4)) << 8) + *(in + 5); return type; } diff --git a/src/xrpld/overlay/detail/OverlayImpl.cpp b/src/xrpld/overlay/detail/OverlayImpl.cpp index b4b0686ac8..a1edfe4e33 100644 --- a/src/xrpld/overlay/detail/OverlayImpl.cpp +++ b/src/xrpld/overlay/detail/OverlayImpl.cpp @@ -36,7 +36,7 @@ enum { ServerCounts = (1 << 2), Unl = (1 << 3) }; -} +} // namespace CrawlOptions //------------------------------------------------------------------------------ @@ -152,7 +152,7 @@ OverlayImpl::onHandoff( auto const id = next_id_++; auto peerJournal = app_.getJournal("Peer"); beast::WrappedSink sink(peerJournal.sink(), makePrefix(id)); - beast::Journal journal(sink); + beast::Journal const journal(sink); Handoff handoff; if (processRequest(request, handoff)) @@ -270,7 +270,7 @@ OverlayImpl::onHandoff( // As we are not on the strand, run() must be called // while holding the lock, otherwise new I/O can be // queued after a call to stop(). - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); { auto const result = m_peers.emplace(peer->slot(), peer); XRPL_ASSERT(result.second, "xrpl::OverlayImpl::onHandoff : peer is inserted"); @@ -393,7 +393,7 @@ OverlayImpl::connect(beast::IP::Endpoint const& remote_endpoint) app_.getJournal("Peer"), *this); - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); list_.emplace(p.get(), p); p->run(); } @@ -405,9 +405,9 @@ void OverlayImpl::add_active(std::shared_ptr const& peer) { beast::WrappedSink sink{journal_.sink(), peer->prefix()}; - beast::Journal journal{sink}; + beast::Journal const journal{sink}; - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); { auto const result = m_peers.emplace(peer->slot(), peer); @@ -435,7 +435,7 @@ OverlayImpl::add_active(std::shared_ptr const& peer) void OverlayImpl::remove(std::shared_ptr const& slot) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); auto const iter = m_peers.find(slot); XRPL_ASSERT(iter != m_peers.end(), "xrpl::OverlayImpl::remove : valid input"); m_peers.erase(iter); @@ -444,7 +444,7 @@ OverlayImpl::remove(std::shared_ptr const& slot) void OverlayImpl::start() { - PeerFinder::Config config = PeerFinder::Config::makeConfig( + PeerFinder::Config const config = PeerFinder::Config::makeConfig( app_.config(), serverHandler_.setup().overlay.port(), app_.getValidationPublicKey().has_value(), @@ -522,7 +522,7 @@ OverlayImpl::start() }); } auto const timer = std::make_shared(*this); - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); list_.emplace(timer.get(), timer); timer_ = timer; timer->async_wait(); @@ -571,11 +571,11 @@ void OverlayImpl::activate(std::shared_ptr const& peer) { beast::WrappedSink sink{journal_.sink(), peer->prefix()}; - beast::Journal journal{sink}; + beast::Journal const journal{sink}; // Now track this peer { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); auto const result(ids_.emplace( std::piecewise_construct, std::make_tuple(peer->id()), std::make_tuple(peer))); XRPL_ASSERT(result.second, "xrpl::OverlayImpl::activate : peer ID is inserted"); @@ -591,7 +591,7 @@ OverlayImpl::activate(std::shared_ptr const& peer) void OverlayImpl::onPeerDeactivate(Peer::id_t id) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); ids_.erase(id); } @@ -669,7 +669,7 @@ OverlayImpl::reportOutboundTraffic(TrafficCount::category cat, int size) std::size_t OverlayImpl::size() const { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); return ids_.size(); } @@ -916,8 +916,8 @@ OverlayImpl::processHealth(http_request_type const& req, Handoff& handoff) bool amendment_blocked = false; if (info.isMember(jss::amendment_blocked)) amendment_blocked = true; - int number_peers = info[jss::peers].asInt(); - std::string server_state = info[jss::server_state].asString(); + int const number_peers = info[jss::peers].asInt(); + std::string const server_state = info[jss::server_state].asString(); auto load_factor = info[jss::load_factor_server].asDouble() / info[jss::load_base].asDouble(); enum class HealthState { healthy, warning, critical }; @@ -1028,7 +1028,7 @@ OverlayImpl::getActivePeers( std::size_t& enabledInSkip) const { Overlay::PeerSequence ret; - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); active = ids_.size(); disabled = enabledInSkip = 0; @@ -1068,7 +1068,7 @@ OverlayImpl::checkTracking(std::uint32_t index) std::shared_ptr OverlayImpl::findPeerByShortID(Peer::id_t const& id) const { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); auto const iter = ids_.find(id); if (iter != ids_.end()) return iter->second.lock(); @@ -1080,7 +1080,7 @@ OverlayImpl::findPeerByShortID(Peer::id_t const& id) const std::shared_ptr OverlayImpl::findPeerByPublicKey(PublicKey const& pubKey) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); // NOTE The purpose of peer is to delay the destruction of PeerImp std::shared_ptr peer; for (auto const& e : ids_) @@ -1141,7 +1141,7 @@ OverlayImpl::relay(protocol::TMValidation& m, uint256 const& uid, PublicKey cons std::shared_ptr OverlayImpl::getManifestsMessage() { - std::lock_guard g(manifestLock_); + std::lock_guard const g(manifestLock_); if (auto seq = app_.getValidatorManifests().sequence(); seq != manifestListSeq_) { @@ -1260,7 +1260,7 @@ OverlayImpl::relay( void OverlayImpl::remove(Child& child) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); list_.erase(&child); if (list_.empty()) cond_.notify_all(); @@ -1279,7 +1279,7 @@ OverlayImpl::stopChildren() // won't be called until vector<> children leaves scope. std::vector> children; { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); if (!work_) return; work_ = std::nullopt; @@ -1314,7 +1314,7 @@ OverlayImpl::sendEndpoints() { std::shared_ptr peer; { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); auto const iter = m_peers.find(e.first); if (iter != m_peers.end()) peer = iter->second.lock(); diff --git a/src/xrpld/overlay/detail/OverlayImpl.h b/src/xrpld/overlay/detail/OverlayImpl.h index c816f24e0c..26b5a77371 100644 --- a/src/xrpld/overlay/detail/OverlayImpl.h +++ b/src/xrpld/overlay/detail/OverlayImpl.h @@ -255,7 +255,7 @@ public: { std::vector> wp; { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); // Iterate over a copy of the peer list because peer // destruction can invalidate iterators. @@ -573,7 +573,7 @@ private: collect_metrics() { auto counts = m_traffic.getCounts(); - std::lock_guard lock(m_statsMutex); + std::lock_guard const lock(m_statsMutex); XRPL_ASSERT( counts.size() == m_stats.trafficGauges.size(), "xrpl::OverlayImpl::collect_metrics : counts size do match"); diff --git a/src/xrpld/overlay/detail/PeerImp.cpp b/src/xrpld/overlay/detail/PeerImp.cpp index 92c5bcb221..13fe0c571c 100644 --- a/src/xrpld/overlay/detail/PeerImp.cpp +++ b/src/xrpld/overlay/detail/PeerImp.cpp @@ -172,7 +172,7 @@ PeerImp::run() fail("Malformed handshake data (3)"); { - std::lock_guard sl(recentLock_); + std::lock_guard const sl(recentLock_); if (closed) closedLedgerHash_ = *closed; if (previous) @@ -411,7 +411,7 @@ PeerImp::json() ret[jss::protocol] = to_string(protocol_); { - std::lock_guard sl(recentLock_); + std::lock_guard const sl(recentLock_); if (latency_) ret[jss::latency] = static_cast(latency_->count()); } @@ -443,7 +443,7 @@ PeerImp::json() uint256 closedLedgerHash; protocol::TMStatusChange last_status; { - std::lock_guard sl(recentLock_); + std::lock_guard const sl(recentLock_); closedLedgerHash = closedLedgerHash_; last_status = last_status_; } @@ -510,7 +510,7 @@ bool PeerImp::hasLedger(uint256 const& hash, std::uint32_t seq) const { { - std::lock_guard sl(recentLock_); + std::lock_guard const sl(recentLock_); if ((seq != 0) && (seq >= minLedger_) && (seq <= maxLedger_) && (tracking_.load() == Tracking::converged)) return true; @@ -523,7 +523,7 @@ PeerImp::hasLedger(uint256 const& hash, std::uint32_t seq) const void PeerImp::ledgerRange(std::uint32_t& minSeq, std::uint32_t& maxSeq) const { - std::lock_guard sl(recentLock_); + std::lock_guard const sl(recentLock_); minSeq = minLedger_; maxSeq = maxLedger_; @@ -532,7 +532,7 @@ PeerImp::ledgerRange(std::uint32_t& minSeq, std::uint32_t& maxSeq) const bool PeerImp::hasTxSet(uint256 const& hash) const { - std::lock_guard sl(recentLock_); + std::lock_guard const sl(recentLock_); return std::find(recentTxSets_.begin(), recentTxSets_.end(), hash) != recentTxSets_.end(); } @@ -541,7 +541,7 @@ PeerImp::cycleStatus() { // Operations on closedLedgerHash_ and previousLedgerHash_ must be // guarded by recentLock_. - std::lock_guard sl(recentLock_); + std::lock_guard const sl(recentLock_); previousLedgerHash_ = closedLedgerHash_; closedLedgerHash_.zero(); } @@ -549,7 +549,7 @@ PeerImp::cycleStatus() bool PeerImp::hasRange(std::uint32_t uMin, std::uint32_t uMax) { - std::lock_guard sl(recentLock_); + std::lock_guard const sl(recentLock_); return (tracking_ != Tracking::diverged) && (uMin >= minLedger_) && (uMax <= maxLedger_); } @@ -641,7 +641,7 @@ PeerImp::onShutdown(error_code ec) // - stream_truncated: the tcp connection closed (no handshake) it could // occur if a peer does not perform a graceful disconnect // - broken_pipe: the peer is gone - bool shouldLog = + bool const shouldLog = (ec != boost::asio::error::eof && ec != boost::asio::error::operation_aborted && ec.message().find("application data after close notify") == std::string::npos); @@ -746,7 +746,7 @@ PeerImp::onTimer(error_code const& ec) clock_type::duration duration; { - std::lock_guard sl(recentLock_); + std::lock_guard const sl(recentLock_); duration = clock_type::now() - trackingTime_; } @@ -821,7 +821,7 @@ PeerImp::doAccept() if (auto member = app_.getCluster().member(publicKey_)) { { - std::unique_lock lock{nameMutex_}; + std::unique_lock const lock{nameMutex_}; name_ = *member; } JLOG(journal_.info()) << "Cluster name: " << *member; @@ -879,7 +879,7 @@ PeerImp::doAccept() std::string PeerImp::name() const { - std::shared_lock read_lock{nameMutex_}; + std::shared_lock const read_lock{nameMutex_}; return name_; } @@ -1200,7 +1200,7 @@ PeerImp::onMessage(std::shared_ptr const& m) auto const rtt = std::chrono::round(clock_type::now() - lastPingTime_); - std::lock_guard sl(recentLock_); + std::lock_guard const sl(recentLock_); if (latency_) { @@ -1246,7 +1246,7 @@ PeerImp::onMessage(std::shared_ptr const& m) } } - int loadSources = m->loadsources().size(); + int const loadSources = m->loadsources().size(); if (loadSources != 0) { Resource::Gossip gossip; @@ -1371,7 +1371,7 @@ PeerImp::handleTransaction( try { auto stx = std::make_shared(sit); - uint256 txID = stx->getTransactionID(); + uint256 const txID = stx->getTransactionID(); // Charge strongly for attempting to relay a txn with tfInnerBatchTxn // LCOV_EXCL_START @@ -1581,7 +1581,7 @@ PeerImp::onMessage(std::shared_ptr const& m) } // Queue a job to process the request - std::weak_ptr weak = shared_from_this(); + std::weak_ptr const weak = shared_from_this(); app_.getJobQueue().addJob(jtLEDGER_REQ, "RcvGetLedger", [weak, m]() { if (auto peer = weak.lock()) peer->processLedgerRequest(m); @@ -1599,7 +1599,7 @@ PeerImp::onMessage(std::shared_ptr const& m) } fee_.update(Resource::feeModerateBurdenPeer, "received a proof path request"); - std::weak_ptr weak = shared_from_this(); + std::weak_ptr const weak = shared_from_this(); app_.getJobQueue().addJob(jtREPLAY_REQ, "RcvProofPReq", [weak, m]() { if (auto peer = weak.lock()) { @@ -1649,7 +1649,7 @@ PeerImp::onMessage(std::shared_ptr const& m) } fee_.fee = Resource::feeModerateBurdenPeer; - std::weak_ptr weak = shared_from_this(); + std::weak_ptr const weak = shared_from_this(); app_.getJobQueue().addJob(jtREPLAY_REQ, "RcvReplDReq", [weak, m]() { if (auto peer = weak.lock()) { @@ -1769,7 +1769,7 @@ PeerImp::onMessage(std::shared_ptr const& m) // Otherwise check if received data for a candidate transaction set if (m->type() == protocol::liTS_CANDIDATE) { - std::weak_ptr weak{shared_from_this()}; + std::weak_ptr const weak{shared_from_this()}; app_.getJobQueue().addJob(jtTXN_DATA, "RcvPeerData", [weak, ledgerHash, m]() { if (auto peer = weak.lock()) { @@ -1786,7 +1786,7 @@ PeerImp::onMessage(std::shared_ptr const& m) void PeerImp::onMessage(std::shared_ptr const& m) { - protocol::TMProposeSet& set = *m; + protocol::TMProposeSet const& set = *m; auto const sig = makeSlice(set.signature()); @@ -1880,7 +1880,7 @@ PeerImp::onMessage(std::shared_ptr const& m) app_.getTimeKeeper().closeTime(), calcNodeID(app_.getValidatorManifests().getMasterKey(publicKey))}); - std::weak_ptr weak = shared_from_this(); + std::weak_ptr const weak = shared_from_this(); app_.getJobQueue().addJob( isTrusted ? jtPROPOSAL_t : jtPROPOSAL_ut, "checkPropose", [weak, isTrusted, m, proposal]() { if (auto peer = weak.lock()) @@ -1897,7 +1897,7 @@ PeerImp::onMessage(std::shared_ptr const& m) m->set_networktime(app_.getTimeKeeper().now().time_since_epoch().count()); { - std::lock_guard sl(recentLock_); + std::lock_guard const sl(recentLock_); if (!last_status_.has_newstatus() || m->has_newstatus()) { last_status_ = *m; @@ -1905,7 +1905,7 @@ PeerImp::onMessage(std::shared_ptr const& m) else { // preserve old status - protocol::NodeStatus status = last_status_.newstatus(); + protocol::NodeStatus const status = last_status_.newstatus(); last_status_ = *m; m->set_newstatus(status); } @@ -1917,7 +1917,7 @@ PeerImp::onMessage(std::shared_ptr const& m) { // Operations on closedLedgerHash_ and previousLedgerHash_ must be // guarded by recentLock_. - std::lock_guard sl(recentLock_); + std::lock_guard const sl(recentLock_); if (!closedLedgerHash_.isZero()) { outOfSync = true; @@ -1939,7 +1939,7 @@ PeerImp::onMessage(std::shared_ptr const& m) { // Operations on closedLedgerHash_ and previousLedgerHash_ must be // guarded by recentLock_. - std::lock_guard sl(recentLock_); + std::lock_guard const sl(recentLock_); if (peerChangedLedgers) { closedLedgerHash_ = m->ledgerhash(); @@ -1973,7 +1973,7 @@ PeerImp::onMessage(std::shared_ptr const& m) if (m->has_firstseq() && m->has_lastseq()) { - std::lock_guard sl(recentLock_); + std::lock_guard const sl(recentLock_); minLedger_ = m->firstseq(); maxLedger_ = m->lastseq(); @@ -2040,7 +2040,7 @@ PeerImp::onMessage(std::shared_ptr const& m) { uint256 closedLedgerHash{}; { - std::lock_guard sl(recentLock_); + std::lock_guard const sl(recentLock_); closedLedgerHash = closedLedgerHash_; } j[jss::ledger_hash] = to_string(closedLedgerHash); @@ -2068,7 +2068,7 @@ PeerImp::checkTracking(std::uint32_t validationSeq) { // Extract the sequence number of the highest // ledger this peer has - std::lock_guard sl(recentLock_); + std::lock_guard const sl(recentLock_); serverSeq = maxLedger_; } @@ -2083,7 +2083,7 @@ PeerImp::checkTracking(std::uint32_t validationSeq) void PeerImp::checkTracking(std::uint32_t seq1, std::uint32_t seq2) { - int diff = std::max(seq1, seq2) - std::min(seq1, seq2); + int const diff = std::max(seq1, seq2) - std::min(seq1, seq2); if (diff < Tuning::convergedLedgerLimit) { @@ -2094,7 +2094,7 @@ PeerImp::checkTracking(std::uint32_t seq1, std::uint32_t seq2) if ((diff > Tuning::divergedLedgerLimit) && (tracking_.load() != Tracking::diverged)) { // The peer's ledger sequence is way off the validation's - std::lock_guard sl(recentLock_); + std::lock_guard const sl(recentLock_); tracking_ = Tracking::diverged; trackingTime_ = clock_type::now(); @@ -2114,7 +2114,7 @@ PeerImp::onMessage(std::shared_ptr const& m) if (m->status() == protocol::tsHAVE) { - std::lock_guard sl(recentLock_); + std::lock_guard const sl(recentLock_); if (std::find(recentTxSets_.begin(), recentTxSets_.end(), hash) != recentTxSets_.end()) { @@ -2181,7 +2181,7 @@ PeerImp::onValidatorListMessage( case ListDisposition::expired: // Future list case ListDisposition::pending: { - std::lock_guard sl(recentLock_); + std::lock_guard const sl(recentLock_); XRPL_ASSERT( applyResult.publisherKey, @@ -2204,7 +2204,7 @@ PeerImp::onValidatorListMessage( case ListDisposition::known_sequence: #ifndef NDEBUG { - std::lock_guard sl(recentLock_); + std::lock_guard const sl(recentLock_); XRPL_ASSERT( applyResult.sequence && applyResult.publisherKey, "xrpl::PeerImp::onValidatorListMessage : nonzero sequence " @@ -2464,7 +2464,7 @@ PeerImp::onMessage(std::shared_ptr const& m) { std::string const name = isTrusted ? "ChkTrust" : "ChkUntrust"; - std::weak_ptr weak = shared_from_this(); + std::weak_ptr const weak = shared_from_this(); app_.getJobQueue().addJob( isTrusted ? jtVALIDATION_t : jtVALIDATION_ut, name, [weak, val, m, key]() { if (auto peer = weak.lock()) @@ -2487,7 +2487,7 @@ PeerImp::onMessage(std::shared_ptr const& m) void PeerImp::onMessage(std::shared_ptr const& m) { - protocol::TMGetObjectByHash& packet = *m; + protocol::TMGetObjectByHash const& packet = *m; JLOG(p_journal_.trace()) << "received TMGetObjectByHash " << packet.type() << " " << packet.objects_size(); @@ -2516,7 +2516,7 @@ PeerImp::onMessage(std::shared_ptr const& m) return; } - std::weak_ptr weak = shared_from_this(); + std::weak_ptr const weak = shared_from_this(); app_.getJobQueue().addJob(jtREQUESTED_TXN, "DoTxs", [weak, m]() { if (auto peer = weak.lock()) peer->doTransactions(m); @@ -2555,7 +2555,7 @@ PeerImp::onMessage(std::shared_ptr const& m) uint256 const hash{obj.hash()}; // VFALCO TODO Move this someplace more sensible so we dont // need to inject the NodeStore interfaces. - std::uint32_t seq{obj.has_ledgerseq() ? obj.ledgerseq() : 0}; + std::uint32_t const seq{obj.has_ledgerseq() ? obj.ledgerseq() : 0}; auto nodeObject{app_.getNodeStore().fetchNodeObject(hash, seq)}; if (nodeObject) { @@ -2651,7 +2651,7 @@ PeerImp::onMessage(std::shared_ptr const& m) return; } - std::weak_ptr weak = shared_from_this(); + std::weak_ptr const weak = shared_from_this(); app_.getJobQueue().addJob(jtMISSING_TXN, "HandleHaveTxs", [weak, m]() { if (auto peer = weak.lock()) peer->handleHaveTransactions(m); @@ -2750,7 +2750,7 @@ PeerImp::onMessage(std::shared_ptr const& m) fee_.update(Resource::feeInvalidData, "squelch bad pubkey"); return; } - PublicKey key(slice); + PublicKey const key(slice); // Ignore the squelch for validator's own messages. if (key == app_.getValidationPublicKey()) @@ -2759,7 +2759,7 @@ PeerImp::onMessage(std::shared_ptr const& m) return; } - std::uint32_t duration = m->has_squelchduration() ? m->squelchduration() : 0; + std::uint32_t const duration = m->has_squelchduration() ? m->squelchduration() : 0; if (!m->squelch()) { squelch_.removeSquelch(key); @@ -2812,7 +2812,7 @@ PeerImp::doFetchPack(std::shared_ptr const& packet) uint256 const hash{packet->ledgerhash()}; - std::weak_ptr weak = shared_from_this(); + std::weak_ptr const weak = shared_from_this(); auto elapsed = UptimeClock::now(); auto const pap = &app_; app_.getJobQueue().addJob(jtPACK, "MakeFetchPack", [pap, weak, packet, hash, elapsed]() { @@ -3017,7 +3017,7 @@ PeerImp::checkPropose( if (!cluster() && !peerPos.checkSign()) { - std::string desc{"Proposal fails sig check"}; + std::string const desc{"Proposal fails sig check"}; JLOG(p_journal_.warn()) << desc; charge(Resource::feeInvalidSignature, desc); return; @@ -3061,7 +3061,7 @@ PeerImp::checkValidation( { if (!val->isValid()) { - std::string desc{"Validation forwarded by peer is invalid"}; + std::string const desc{"Validation forwarded by peer is invalid"}; JLOG(p_journal_.debug()) << desc; charge(Resource::feeInvalidSignature, desc); return; @@ -3493,7 +3493,7 @@ PeerImp::getScore(bool haveItem) const std::optional latency; { - std::lock_guard sl(recentLock_); + std::lock_guard const sl(recentLock_); latency = latency_; } @@ -3512,7 +3512,7 @@ PeerImp::getScore(bool haveItem) const bool PeerImp::isHighLatency() const { - std::lock_guard sl(recentLock_); + std::lock_guard const sl(recentLock_); return latency_ >= peerHighLatency; } @@ -3520,7 +3520,7 @@ void PeerImp::Metrics::add_message(std::uint64_t bytes) { using namespace std::chrono_literals; - std::unique_lock lock{mutex_}; + std::unique_lock const lock{mutex_}; totalBytes_ += bytes; accumBytes_ += bytes; @@ -3543,14 +3543,14 @@ PeerImp::Metrics::add_message(std::uint64_t bytes) std::uint64_t PeerImp::Metrics::average_bytes() const { - std::shared_lock lock{mutex_}; + std::shared_lock const lock{mutex_}; return rollingAvgBytes_; } std::uint64_t PeerImp::Metrics::total_bytes() const { - std::shared_lock lock{mutex_}; + std::shared_lock const lock{mutex_}; return totalBytes_; } diff --git a/src/xrpld/overlay/detail/PeerImp.h b/src/xrpld/overlay/detail/PeerImp.h index 5a687a9b2a..61b8e1e758 100644 --- a/src/xrpld/overlay/detail/PeerImp.h +++ b/src/xrpld/overlay/detail/PeerImp.h @@ -428,7 +428,7 @@ public: std::optional publisherListSequence(PublicKey const& pubKey) const override { - std::lock_guard sl(recentLock_); + std::lock_guard const sl(recentLock_); auto iter = publisherListSequences_.find(pubKey); if (iter != publisherListSequences_.end()) @@ -439,7 +439,7 @@ public: void setPublisherListSequence(PublicKey const& pubKey, std::size_t const seq) override { - std::lock_guard sl(recentLock_); + std::lock_guard const sl(recentLock_); publisherListSequences_[pubKey] = seq; } diff --git a/src/xrpld/overlay/detail/PeerReservationTable.cpp b/src/xrpld/overlay/detail/PeerReservationTable.cpp index 78f29ad155..8f90848954 100644 --- a/src/xrpld/overlay/detail/PeerReservationTable.cpp +++ b/src/xrpld/overlay/detail/PeerReservationTable.cpp @@ -30,7 +30,7 @@ PeerReservationTable::list() const -> std::vector { std::vector list; { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); list.reserve(table_.size()); std::copy(table_.begin(), table_.end(), std::back_inserter(list)); } @@ -47,7 +47,7 @@ PeerReservationTable::list() const -> std::vector bool PeerReservationTable::load(DatabaseCon& connection) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); connection_ = &connection; auto db = connection.checkoutDb(); @@ -62,7 +62,7 @@ PeerReservationTable::insert_or_assign(PeerReservation const& reservation) { std::optional previous; - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); auto hint = table_.find(reservation); if (hint != table_.end()) @@ -96,7 +96,7 @@ PeerReservationTable::erase(PublicKey const& nodeId) { std::optional previous; - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); auto const it = table_.find({nodeId}); if (it != table_.end()) diff --git a/src/xrpld/overlay/detail/PeerSet.cpp b/src/xrpld/overlay/detail/PeerSet.cpp index 3329f67e7a..391fb6d3ca 100644 --- a/src/xrpld/overlay/detail/PeerSet.cpp +++ b/src/xrpld/overlay/detail/PeerSet.cpp @@ -152,7 +152,7 @@ public: std::set const& getPeerIds() const override { - static std::set emptyPeers; + static std::set const emptyPeers; JLOG(j_.error()) << "DummyPeerSet getPeerIds should not be called"; return emptyPeers; } diff --git a/src/xrpld/overlay/detail/ProtocolVersion.cpp b/src/xrpld/overlay/detail/ProtocolVersion.cpp index a8213f2824..1a55030cd4 100644 --- a/src/xrpld/overlay/detail/ProtocolVersion.cpp +++ b/src/xrpld/overlay/detail/ProtocolVersion.cpp @@ -58,7 +58,7 @@ to_string(ProtocolVersion const& p) std::vector parseProtocolVersions(boost::beast::string_view const& value) { - static boost::regex re( + static boost::regex const re( "^" // start of line "XRPL/" // The string "XRPL/" "([2-9]|(?:[1-9][0-9]+))" // a number (greater than 2 with no leading @@ -112,9 +112,8 @@ negotiateProtocolVersion(std::vector const& versions) // output of std::set_intersection is sorted, that item is always going // to be the last one. So we get a little clever and avoid the need for // a container: - std::function pickVersion = [&result](ProtocolVersion const& v) { - result = v; - }; + std::function const pickVersion = + [&result](ProtocolVersion const& v) { result = v; }; std::set_intersection( std::begin(versions), diff --git a/src/xrpld/overlay/detail/TxMetrics.cpp b/src/xrpld/overlay/detail/TxMetrics.cpp index 72cd9d6fa2..ee0e42e5d6 100644 --- a/src/xrpld/overlay/detail/TxMetrics.cpp +++ b/src/xrpld/overlay/detail/TxMetrics.cpp @@ -12,7 +12,7 @@ void TxMetrics::addMetrics(protocol::MessageType type, std::uint32_t val) { auto add = [&](auto& m, std::uint32_t val) { - std::lock_guard lock(mutex); + std::lock_guard const lock(mutex); m.addMetrics(val); }; @@ -41,7 +41,7 @@ TxMetrics::addMetrics(protocol::MessageType type, std::uint32_t val) void TxMetrics::addMetrics(std::uint32_t selected, std::uint32_t suppressed, std::uint32_t notenabled) { - std::lock_guard lock(mutex); + std::lock_guard const lock(mutex); selectedPeers.addMetrics(selected); suppressedPeers.addMetrics(suppressed); notEnabled.addMetrics(notenabled); @@ -50,7 +50,7 @@ TxMetrics::addMetrics(std::uint32_t selected, std::uint32_t suppressed, std::uin void TxMetrics::addMetrics(std::uint32_t missing) { - std::lock_guard lock(mutex); + std::lock_guard const lock(mutex); missingTx.addMetrics(missing); } @@ -94,7 +94,7 @@ SingleMetrics::addMetrics(std::uint32_t val) Json::Value TxMetrics::json() const { - std::lock_guard l(mutex); + std::lock_guard const l(mutex); Json::Value ret(Json::objectValue); diff --git a/src/xrpld/peerfinder/detail/Checker.h b/src/xrpld/peerfinder/detail/Checker.h index 3e67754db9..ccc395f053 100644 --- a/src/xrpld/peerfinder/detail/Checker.h +++ b/src/xrpld/peerfinder/detail/Checker.h @@ -154,7 +154,7 @@ template void Checker::stop() { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); if (!stop_) { stop_ = true; @@ -180,7 +180,7 @@ Checker::async_connect(beast::IP::Endpoint const& endpoint, Handler&& auto const op = std::make_shared>(*this, io_context_, std::forward(handler)); { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); list_.push_back(*op); } op->socket_.async_connect( @@ -192,7 +192,7 @@ template void Checker::remove(basic_async_op& op) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); list_.erase(list_.iterator_to(op)); if (list_.size() == 0) cond_.notify_all(); diff --git a/src/xrpld/peerfinder/detail/Logic.h b/src/xrpld/peerfinder/detail/Logic.h index 8f49da6c4f..ad0a2f8b96 100644 --- a/src/xrpld/peerfinder/detail/Logic.h +++ b/src/xrpld/peerfinder/detail/Logic.h @@ -106,7 +106,7 @@ public: void load() { - std::lock_guard _(lock_); + std::lock_guard const _(lock_); bootcache_.load(); } @@ -119,7 +119,7 @@ public: void stop() { - std::lock_guard _(lock_); + std::lock_guard const _(lock_); stopping_ = true; if (fetchSource_ != nullptr) fetchSource_->cancel(); @@ -134,7 +134,7 @@ public: void config(Config const& c) { - std::lock_guard _(lock_); + std::lock_guard const _(lock_); config_ = c; counts_.onConfig(config_); } @@ -142,7 +142,7 @@ public: Config config() { - std::lock_guard _(lock_); + std::lock_guard const _(lock_); return config_; } @@ -155,7 +155,7 @@ public: void addFixedPeer(std::string const& name, std::vector const& addresses) { - std::lock_guard _(lock_); + std::lock_guard const _(lock_); if (addresses.empty()) { @@ -197,7 +197,7 @@ public: if (ec == boost::asio::error::operation_aborted) return; - std::lock_guard _(lock_); + std::lock_guard const _(lock_); auto const iter(slots_.find(remoteAddress)); if (iter == slots_.end()) { @@ -212,7 +212,7 @@ public: slot.connectivityCheckInProgress = false; beast::WrappedSink sink{m_journal.sink(), slot.prefix()}; - beast::Journal journal{sink}; + beast::Journal const journal{sink}; if (ec) { @@ -239,7 +239,7 @@ public: JLOG(m_journal.debug()) << beast::leftw(18) << "Logic accept" << remote_endpoint << " on local " << local_endpoint; - std::lock_guard _(lock_); + std::lock_guard const _(lock_); // Check for connection limit per address if (is_public(remote_endpoint)) @@ -287,7 +287,7 @@ public: { JLOG(m_journal.debug()) << beast::leftw(18) << "Logic connect " << remote_endpoint; - std::lock_guard _(lock_); + std::lock_guard const _(lock_); // Check for duplicate connection if (slots_.find(remote_endpoint) != slots_.end()) @@ -322,11 +322,11 @@ public: onConnected(SlotImp::ptr const& slot, beast::IP::Endpoint const& local_endpoint) { beast::WrappedSink sink{m_journal.sink(), slot->prefix()}; - beast::Journal journal{sink}; + beast::Journal const journal{sink}; JLOG(journal.trace()) << "Logic connected on local " << local_endpoint; - std::lock_guard _(lock_); + std::lock_guard const _(lock_); // The object must exist in our table XRPL_ASSERT( @@ -360,12 +360,12 @@ public: activate(SlotImp::ptr const& slot, PublicKey const& key, bool reserved) { beast::WrappedSink sink{m_journal.sink(), slot->prefix()}; - beast::Journal journal{sink}; + beast::Journal const journal{sink}; JLOG(journal.debug()) << "Logic handshake " << slot->remote_endpoint() << " with " << (reserved ? "reserved " : "") << "key " << key; - std::lock_guard _(lock_); + std::lock_guard const _(lock_); // The object must exist in our table XRPL_ASSERT( @@ -436,7 +436,7 @@ public: std::vector redirect(SlotImp::ptr const& slot) { - std::lock_guard _(lock_); + std::lock_guard const _(lock_); RedirectHandouts h(slot); livecache_.hops.shuffle(); handout(&h, (&h) + 1, livecache_.hops.begin(), livecache_.hops.end()); @@ -454,7 +454,7 @@ public: { std::vector none; - std::lock_guard _(lock_); + std::lock_guard const _(lock_); // Count how many more outbound attempts to make // @@ -560,7 +560,7 @@ public: { std::vector, std::vector>> result; - std::lock_guard _(lock_); + std::lock_guard const _(lock_); clock_type::time_point const now = m_clock.now(); if (m_whenBroadcast <= now) @@ -624,7 +624,7 @@ public: SlotImp::ptr const& slot = t.slot(); auto const& list = t.list(); beast::WrappedSink sink{m_journal.sink(), slot->prefix()}; - beast::Journal journal{sink}; + beast::Journal const journal{sink}; JLOG(journal.trace()) << "Logic sending " << list.size() << ((list.size() == 1) ? " endpoint" : " endpoints"); result.push_back(std::make_pair(slot, list)); @@ -639,7 +639,7 @@ public: void once_per_second() { - std::lock_guard _(lock_); + std::lock_guard const _(lock_); // Expire the Livecache livecache_.expire(); @@ -725,7 +725,7 @@ public: on_endpoints(SlotImp::ptr const& slot, Endpoints list) { beast::WrappedSink sink{m_journal.sink(), slot->prefix()}; - beast::Journal journal{sink}; + beast::Journal const journal{sink}; // If we're sent too many endpoints, sample them at random: if (list.size() > Tuning::numberOfEndpointsMax) @@ -737,7 +737,7 @@ public: JLOG(journal.trace()) << "Endpoints contained " << list.size() << ((list.size() > 1) ? " entries" : " entry"); - std::lock_guard _(lock_); + std::lock_guard const _(lock_); // The object must exist in our table XRPL_ASSERT( @@ -863,12 +863,12 @@ public: void on_closed(SlotImp::ptr const& slot) { - std::lock_guard _(lock_); + std::lock_guard const _(lock_); remove(slot); beast::WrappedSink sink{m_journal.sink(), slot->prefix()}; - beast::Journal journal{sink}; + beast::Journal const journal{sink}; // Mark fixed slot failure if (slot->fixed() && !slot->inbound() && slot->state() != Slot::active) @@ -921,7 +921,7 @@ public: void on_failure(SlotImp::ptr const& slot) { - std::lock_guard _(lock_); + std::lock_guard const _(lock_); bootcache_.on_failure(slot->remote_endpoint()); } @@ -1010,7 +1010,7 @@ public: addBootcacheAddresses(IPAddresses const& list) { int count(0); - std::lock_guard _(lock_); + std::lock_guard const _(lock_); for (auto const& addr : list) { if (bootcache_.insertStatic(addr)) @@ -1027,7 +1027,7 @@ public: { { - std::lock_guard _(lock_); + std::lock_guard const _(lock_); if (stopping_) return; fetchSource_ = source; @@ -1039,7 +1039,7 @@ public: source->fetch(results, m_journal); { - std::lock_guard _(lock_); + std::lock_guard const _(lock_); if (stopping_) return; fetchSource_ = nullptr; @@ -1110,7 +1110,7 @@ public: void onWrite(beast::PropertyStream::Map& map) { - std::lock_guard _(lock_); + std::lock_guard const _(lock_); // VFALCO NOTE These ugly casts are needed because // of how std::size_t is declared on some linuxes @@ -1188,7 +1188,7 @@ Logic::onRedirects( FwdIter last, boost::asio::ip::tcp::endpoint const& remote_address) { - std::lock_guard _(lock_); + std::lock_guard const _(lock_); std::size_t n = 0; for (; first != last && n < Tuning::maxRedirects; ++first, ++n) bootcache_.insert(beast::IPAddressConversion::from_asio(*first)); diff --git a/src/xrpld/peerfinder/detail/PeerfinderConfig.cpp b/src/xrpld/peerfinder/detail/PeerfinderConfig.cpp index 4de03c6ca6..a94dbdfbd9 100644 --- a/src/xrpld/peerfinder/detail/PeerfinderConfig.cpp +++ b/src/xrpld/peerfinder/detail/PeerfinderConfig.cpp @@ -23,7 +23,7 @@ operator==(Config const& lhs, Config const& rhs) return lhs.autoConnect == rhs.autoConnect && lhs.peerPrivate == rhs.peerPrivate && lhs.wantIncoming == rhs.wantIncoming && lhs.inPeers == rhs.inPeers && lhs.maxPeers == rhs.maxPeers && lhs.outPeers == rhs.outPeers && - lhs.features == lhs.features && lhs.ipLimit == rhs.ipLimit && + lhs.features == rhs.features && lhs.ipLimit == rhs.ipLimit && lhs.listeningPort == rhs.listeningPort; } diff --git a/src/xrpld/peerfinder/detail/PeerfinderManager.cpp b/src/xrpld/peerfinder/detail/PeerfinderManager.cpp index 70f082c0d5..e9c42b7eb5 100644 --- a/src/xrpld/peerfinder/detail/PeerfinderManager.cpp +++ b/src/xrpld/peerfinder/detail/PeerfinderManager.cpp @@ -117,21 +117,21 @@ public: void on_endpoints(std::shared_ptr const& slot, Endpoints const& endpoints) override { - SlotImp::ptr impl(std::dynamic_pointer_cast(slot)); + SlotImp::ptr const impl(std::dynamic_pointer_cast(slot)); m_logic.on_endpoints(impl, endpoints); } void on_closed(std::shared_ptr const& slot) override { - SlotImp::ptr impl(std::dynamic_pointer_cast(slot)); + SlotImp::ptr const impl(std::dynamic_pointer_cast(slot)); m_logic.on_closed(impl); } void on_failure(std::shared_ptr const& slot) override { - SlotImp::ptr impl(std::dynamic_pointer_cast(slot)); + SlotImp::ptr const impl(std::dynamic_pointer_cast(slot)); m_logic.on_failure(impl); } @@ -149,21 +149,21 @@ public: onConnected(std::shared_ptr const& slot, beast::IP::Endpoint const& local_endpoint) override { - SlotImp::ptr impl(std::dynamic_pointer_cast(slot)); + SlotImp::ptr const impl(std::dynamic_pointer_cast(slot)); return m_logic.onConnected(impl, local_endpoint); } Result activate(std::shared_ptr const& slot, PublicKey const& key, bool reserved) override { - SlotImp::ptr impl(std::dynamic_pointer_cast(slot)); + SlotImp::ptr const impl(std::dynamic_pointer_cast(slot)); return m_logic.activate(impl, key, reserved); } std::vector redirect(std::shared_ptr const& slot) override { - SlotImp::ptr impl(std::dynamic_pointer_cast(slot)); + SlotImp::ptr const impl(std::dynamic_pointer_cast(slot)); return m_logic.redirect(impl); } @@ -226,7 +226,7 @@ private: void collect_metrics() { - std::lock_guard lock(m_statsMutex); + std::lock_guard const lock(m_statsMutex); m_stats.activeInboundPeers = m_logic.counts_.inboundActive(); m_stats.activeOutboundPeers = m_logic.counts_.out_active(); } diff --git a/src/xrpld/perflog/detail/PerfLogImp.cpp b/src/xrpld/perflog/detail/PerfLogImp.cpp index 960fdcb3ac..266c99a147 100644 --- a/src/xrpld/perflog/detail/PerfLogImp.cpp +++ b/src/xrpld/perflog/detail/PerfLogImp.cpp @@ -69,7 +69,7 @@ PerfLogImp::Counters::countersJson() const { Rpc value; { - std::lock_guard lock(proc.second.mutex); + std::lock_guard const lock(proc.second.mutex); if ((proc.second.value.started == 0u) && (proc.second.value.finished == 0u) && (proc.second.value.errored == 0u)) { @@ -107,7 +107,7 @@ PerfLogImp::Counters::countersJson() const { Jq value; { - std::lock_guard lock(proc.second.mutex); + std::lock_guard const lock(proc.second.mutex); if ((proc.second.value.queued == 0u) && (proc.second.value.started == 0u) && (proc.second.value.finished == 0u)) { @@ -156,7 +156,7 @@ PerfLogImp::Counters::currentJson() const Json::Value jobsArray(Json::arrayValue); auto const jobs = [this] { - std::lock_guard lock(jobsMutex_); + std::lock_guard const lock(jobsMutex_); return jobs_; }(); @@ -174,7 +174,7 @@ PerfLogImp::Counters::currentJson() const Json::Value methodsArray(Json::arrayValue); std::vector methods; { - std::lock_guard lock(methodsMutex_); + std::lock_guard const lock(methodsMutex_); methods.reserve(methods_.size()); for (auto const& m : methods_) methods.push_back(m.second); @@ -270,7 +270,7 @@ PerfLogImp::report() Json::Value report(Json::objectValue); report[jss::time] = to_string(std::chrono::floor(present)); { - std::lock_guard lock{counters_.jobsMutex_}; + std::lock_guard const lock{counters_.jobsMutex_}; report[jss::workers] = static_cast(counters_.jobs_.size()); } report[jss::hostid] = hostname_; @@ -311,10 +311,10 @@ PerfLogImp::rpcStart(std::string const& method, std::uint64_t const requestId) } { - std::lock_guard lock(counter->second.mutex); + std::lock_guard const lock(counter->second.mutex); ++counter->second.value.started; } - std::lock_guard lock(counters_.methodsMutex_); + std::lock_guard const lock(counters_.methodsMutex_); counters_.methods_[requestId] = {counter->first.c_str(), steady_clock::now()}; } @@ -331,7 +331,7 @@ PerfLogImp::rpcEnd(std::string const& method, std::uint64_t const requestId, boo } steady_time_point startTime; { - std::lock_guard lock(counters_.methodsMutex_); + std::lock_guard const lock(counters_.methodsMutex_); auto const e = counters_.methods_.find(requestId); if (e != counters_.methods_.end()) { @@ -345,7 +345,7 @@ PerfLogImp::rpcEnd(std::string const& method, std::uint64_t const requestId, boo // LCOV_EXCL_STOP } } - std::lock_guard lock(counter->second.mutex); + std::lock_guard const lock(counter->second.mutex); if (finish) { ++counter->second.value.finished; @@ -369,7 +369,7 @@ PerfLogImp::jobQueue(JobType const type) return; // LCOV_EXCL_STOP } - std::lock_guard lock(counter->second.mutex); + std::lock_guard const lock(counter->second.mutex); ++counter->second.value.queued; } @@ -390,11 +390,11 @@ PerfLogImp::jobStart( } { - std::lock_guard lock(counter->second.mutex); + std::lock_guard const lock(counter->second.mutex); ++counter->second.value.started; counter->second.value.queuedDuration += dur; } - std::lock_guard lock(counters_.jobsMutex_); + std::lock_guard const lock(counters_.jobsMutex_); if (instance >= 0 && instance < counters_.jobs_.size()) counters_.jobs_[instance] = {type, startTime}; } @@ -412,11 +412,11 @@ PerfLogImp::jobFinish(JobType const type, microseconds dur, int instance) } { - std::lock_guard lock(counter->second.mutex); + std::lock_guard const lock(counter->second.mutex); ++counter->second.value.finished; counter->second.value.runningDuration += dur; } - std::lock_guard lock(counters_.jobsMutex_); + std::lock_guard const lock(counters_.jobsMutex_); if (instance >= 0 && instance < counters_.jobs_.size()) counters_.jobs_[instance] = {jtINVALID, steady_time_point()}; } @@ -424,7 +424,7 @@ PerfLogImp::jobFinish(JobType const type, microseconds dur, int instance) void PerfLogImp::resizeJobs(int const resize) { - std::lock_guard lock(counters_.jobsMutex_); + std::lock_guard const lock(counters_.jobsMutex_); if (resize > counters_.jobs_.size()) counters_.jobs_.resize(resize, {jtINVALID, steady_time_point()}); } @@ -435,7 +435,7 @@ PerfLogImp::rotate() if (setup_.perfLog.empty()) return; - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); rotate_ = true; cond_.notify_one(); } @@ -453,7 +453,7 @@ PerfLogImp::stop() if (thread_.joinable()) { { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); stop_ = true; cond_.notify_one(); } diff --git a/src/xrpld/rpc/BookChanges.h b/src/xrpld/rpc/BookChanges.h index b2b1ae793b..a318c80221 100644 --- a/src/xrpld/rpc/BookChanges.h +++ b/src/xrpld/rpc/BookChanges.h @@ -11,7 +11,7 @@ namespace Json { class Value; -} +} // namespace Json namespace xrpl { @@ -44,7 +44,7 @@ computeBookChanges(std::shared_ptr const& lpAccepted) continue; std::optional offerCancel; - uint16_t tt = tx.first->getFieldU16(sfTransactionType); + uint16_t const tt = tx.first->getFieldU16(sfTransactionType); switch (tt) { case ttOFFER_CANCEL: @@ -62,7 +62,7 @@ computeBookChanges(std::shared_ptr const& lpAccepted) for (auto const& node : tx.second->getFieldArray(sfAffectedNodes)) { SField const& metaType = node.getFName(); - uint16_t nodeType = node.getFieldU16(sfLedgerEntryType); + uint16_t const nodeType = node.getFieldU16(sfLedgerEntryType); // we only care about ltOFFER objects being modified or // deleted @@ -94,13 +94,13 @@ computeBookChanges(std::shared_ptr const& lpAccepted) // compute the difference in gets and pays actually // affected onto the offer - STAmount deltaGets = finalFields.getFieldAmount(sfTakerGets) - + STAmount const deltaGets = finalFields.getFieldAmount(sfTakerGets) - previousFields.getFieldAmount(sfTakerGets); - STAmount deltaPays = finalFields.getFieldAmount(sfTakerPays) - + STAmount const deltaPays = finalFields.getFieldAmount(sfTakerPays) - previousFields.getFieldAmount(sfTakerPays); - std::string g{to_string(deltaGets.issue())}; - std::string p{to_string(deltaPays.issue())}; + std::string const g{to_string(deltaGets.issue())}; + std::string const p{to_string(deltaPays.issue())}; bool const noswap = isXRP(deltaGets) ? true : (isXRP(deltaPays) ? false : (g < p)); @@ -111,7 +111,7 @@ computeBookChanges(std::shared_ptr const& lpAccepted) if (second == beast::zero) continue; - STAmount rate = divide(first, second, noIssue()); + STAmount const rate = divide(first, second, noIssue()); if (first < beast::zero) first = -first; @@ -125,9 +125,9 @@ computeBookChanges(std::shared_ptr const& lpAccepted) else ss << p << "|" << g; - std::optional domain = finalFields[~sfDomainID]; + std::optional const domain = finalFields[~sfDomainID]; - std::string key{ss.str()}; + std::string const key{ss.str()}; if (tally.find(key) == tally.end()) tally[key] = { @@ -174,8 +174,8 @@ computeBookChanges(std::shared_ptr const& lpAccepted) { Json::Value& inner = jvObj[jss::changes].append(Json::objectValue); - STAmount volA = std::get<0>(entry.second); - STAmount volB = std::get<1>(entry.second); + STAmount const volA = std::get<0>(entry.second); + STAmount const volB = std::get<1>(entry.second); inner[jss::currency_a] = (isXRP(volA) ? "XRP_drops" : to_string(volA.issue())); inner[jss::currency_b] = (isXRP(volB) ? "XRP_drops" : to_string(volB.issue())); diff --git a/src/xrpld/rpc/CTID.h b/src/xrpld/rpc/CTID.h index cbae1f4498..42efb4c157 100644 --- a/src/xrpld/rpc/CTID.h +++ b/src/xrpld/rpc/CTID.h @@ -39,7 +39,7 @@ encodeCTID(uint32_t ledgerSeq, uint32_t txnIndex, uint32_t networkID) noexcept if (ledgerSeq > maxLedgerSeq || txnIndex > maxTxnIndex || networkID > maxNetworkID) return std::nullopt; - uint64_t ctidValue = ((0xC000'0000ULL + static_cast(ledgerSeq)) << 32) | + uint64_t const ctidValue = ((0xC000'0000ULL + static_cast(ledgerSeq)) << 32) | ((static_cast(txnIndex) << 16) | networkID); std::stringstream buffer; @@ -101,9 +101,9 @@ decodeCTID(T const ctid) noexcept if ((ctidValue & ctidPrefixMask) != ctidPrefix) return std::nullopt; - uint32_t ledgerSeq = static_cast((ctidValue >> 32) & 0x0FFF'FFFF); - uint16_t txnIndex = static_cast((ctidValue >> 16) & 0xFFFF); - uint16_t networkID = static_cast(ctidValue & 0xFFFF); + uint32_t const ledgerSeq = static_cast((ctidValue >> 32) & 0x0FFF'FFFF); + uint16_t const txnIndex = static_cast((ctidValue >> 16) & 0xFFFF); + uint16_t const networkID = static_cast(ctidValue & 0xFFFF); return std::make_tuple(ledgerSeq, txnIndex, networkID); } diff --git a/src/xrpld/rpc/DeliveredAmount.h b/src/xrpld/rpc/DeliveredAmount.h index c882190ade..65f11e9736 100644 --- a/src/xrpld/rpc/DeliveredAmount.h +++ b/src/xrpld/rpc/DeliveredAmount.h @@ -8,7 +8,7 @@ namespace Json { class Value; -} +} // namespace Json namespace xrpl { diff --git a/src/xrpld/rpc/detail/Handler.h b/src/xrpld/rpc/detail/Handler.h index 908cb67750..3628962a69 100644 --- a/src/xrpld/rpc/detail/Handler.h +++ b/src/xrpld/rpc/detail/Handler.h @@ -10,7 +10,7 @@ namespace Json { class Object; -} +} // namespace Json namespace xrpl { namespace RPC { diff --git a/src/xrpld/rpc/detail/PathRequest.cpp b/src/xrpld/rpc/detail/PathRequest.cpp index f02377381c..fe85c519eb 100644 --- a/src/xrpld/rpc/detail/PathRequest.cpp +++ b/src/xrpld/rpc/detail/PathRequest.cpp @@ -92,7 +92,7 @@ PathRequest::~PathRequest() bool PathRequest::isNew() { - std::lock_guard sl(mIndexLock); + std::lock_guard const sl(mIndexLock); // does this path request still need its first full path return mLastIndex == 0; @@ -101,7 +101,7 @@ PathRequest::isNew() bool PathRequest::needsUpdate(bool newOnly, LedgerIndex index) { - std::lock_guard sl(mIndexLock); + std::lock_guard const sl(mIndexLock); if (mInProgress) { @@ -133,7 +133,7 @@ PathRequest::hasCompletion() void PathRequest::updateComplete() { - std::lock_guard sl(mIndexLock); + std::lock_guard const sl(mIndexLock); XRPL_ASSERT(mInProgress, "xrpl::PathRequest::updateComplete : in progress"); mInProgress = false; @@ -416,7 +416,7 @@ Json::Value PathRequest::doClose() { JLOG(m_journal.debug()) << iIdentifier << " closed"; - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); jvStatus[jss::closed] = true; return jvStatus; } @@ -424,7 +424,7 @@ PathRequest::doClose() Json::Value PathRequest::doStatus(Json::Value const&) { - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); jvStatus[jss::status] = jss::success; return jvStatus; } @@ -527,7 +527,7 @@ PathRequest::findPaths( return *raSrcAccount; }(); - STAmount saMaxAmount = + STAmount const saMaxAmount = saSendMax.value_or(STAmount(Issue{issue.currency, sourceAccount}, 1u, 0, true)); JLOG(m_journal.debug()) << iIdentifier << " Paths found, calling rippleCalc"; @@ -622,7 +622,7 @@ PathRequest::doUpdate( JLOG(m_journal.debug()) << iIdentifier << " update " << (fast ? "fast" : "normal"); { - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); if (!isValid(cache)) return jvStatus; @@ -647,7 +647,7 @@ PathRequest::doUpdate( if (jvId) newStatus[jss::id] = jvId; - bool loaded = app_.getFeeTrack().isLoadedLocal(); + bool const loaded = app_.getFeeTrack().isLoadedLocal(); if (iLevel == 0) { @@ -710,7 +710,7 @@ PathRequest::doUpdate( } { - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); jvStatus = newStatus; } diff --git a/src/xrpld/rpc/detail/PathRequestManager.cpp b/src/xrpld/rpc/detail/PathRequestManager.cpp index e953f1ca70..4455e304e5 100644 --- a/src/xrpld/rpc/detail/PathRequestManager.cpp +++ b/src/xrpld/rpc/detail/PathRequestManager.cpp @@ -17,7 +17,7 @@ namespace xrpl { std::shared_ptr PathRequestManager::getLineCache(std::shared_ptr const& ledger, bool authoritative) { - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); auto lineCache = lineCache_.lock(); @@ -51,7 +51,7 @@ PathRequestManager::updateAll(std::shared_ptr const& inLedger) // Get the ledger and cache we should be using { - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); requests = requests_; cache = getLineCache(inLedger, true); } @@ -130,7 +130,7 @@ PathRequestManager::updateAll(std::shared_ptr const& inLedger) if (remove) { - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); // Remove any dangling weak pointers or weak // pointers that refer to this path request. @@ -175,7 +175,7 @@ PathRequestManager::updateAll(std::shared_ptr const& inLedger) std::shared_ptr lastCache; { // Get the latest requests, cache, and ledger for next pass - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); if (requests_.empty()) break; @@ -192,14 +192,14 @@ PathRequestManager::updateAll(std::shared_ptr const& inLedger) bool PathRequestManager::requestsPending() const { - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); return !requests_.empty(); } void PathRequestManager::insertPathRequest(PathRequest::pointer const& req) { - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); // Insert after any older unserviced requests but before // any serviced requests diff --git a/src/xrpld/rpc/detail/Pathfinder.cpp b/src/xrpld/rpc/detail/Pathfinder.cpp index 176c7f9529..4749caaccb 100644 --- a/src/xrpld/rpc/detail/Pathfinder.cpp +++ b/src/xrpld/rpc/detail/Pathfinder.cpp @@ -206,7 +206,7 @@ Pathfinder::findPaths(int searchLevel, std::function const& continue m_loadEvent = app_.getJobQueue().makeLoadEvent(jtPATH_FIND, "FindPath"); auto currencyIsXRP = isXRP(mSrcCurrency); - bool useIssuerAccount = mSrcIssuer && !currencyIsXRP && !isXRP(*mSrcIssuer); + bool const useIssuerAccount = mSrcIssuer && !currencyIsXRP && !isXRP(*mSrcIssuer); auto& account = useIssuerAccount ? *mSrcIssuer : mSrcAccount; auto issuer = currencyIsXRP ? AccountID() : account; mSource = STPathElement(account, mSrcCurrency, issuer); @@ -222,8 +222,8 @@ Pathfinder::findPaths(int searchLevel, std::function const& continue return false; } - bool bSrcXrp = isXRP(mSrcCurrency); - bool bDstXrp = isXRP(mDstAmount.getCurrency()); + bool const bSrcXrp = isXRP(mSrcCurrency); + bool const bDstXrp = isXRP(mDstAmount.getCurrency()); if (!mLedger->exists(keylet::account(mSrcAccount))) { @@ -674,9 +674,9 @@ Pathfinder::getBestPaths( bool Pathfinder::issueMatchesOrigin(Issue const& issue) { - bool matchingCurrency = (issue.currency == mSrcCurrency); - bool matchingAccount = isXRP(issue.currency) || (mSrcIssuer && issue.account == mSrcIssuer) || - issue.account == mSrcAccount; + bool const matchingCurrency = (issue.currency == mSrcCurrency); + bool const matchingAccount = isXRP(issue.currency) || + (mSrcIssuer && issue.account == mSrcIssuer) || issue.account == mSrcAccount; return matchingCurrency && matchingAccount; } @@ -703,7 +703,7 @@ Pathfinder::getPathsOut( if (!sleAccount) return 0; - int aFlags = sleAccount->getFieldU32(sfFlags); + int const aFlags = sleAccount->getFieldU32(sfFlags); bool const bAuthRequired = (aFlags & lsfRequireAuth) != 0; bool const bFrozen = ((aFlags & lsfGlobalFreeze) != 0); @@ -794,7 +794,7 @@ Pathfinder::addPathsForType( JLOG(j_.debug()) << "getPaths< adding onto '" << pathTypeToString(parentPathType) << "' to get '" << pathTypeToString(pathType) << "'"; - int initialSize = mCompletePaths.size(); + int const initialSize = mCompletePaths.size(); // Add the last NodeType to the lists. auto nodeType = pathType.back(); @@ -956,7 +956,7 @@ Pathfinder::addLink( continue; } - bool bToDestination = acct == mEffectiveDst; + bool const bToDestination = acct == mEffectiveDst; if (bDestOnly && !bToDestination) { @@ -1004,7 +1004,7 @@ Pathfinder::addLink( else { // save this candidate - int out = getPathsOut( + int const out = getPathsOut( uEndCurrency, acct, direction, @@ -1045,7 +1045,7 @@ Pathfinder::addLink( if (continueCallback && !continueCallback()) return; // Add accounts to incompletePaths - STPathElement pathElement( + STPathElement const pathElement( STPathElement::typeAccount, it->account, uEndCurrency, it->account); incompletePaths.assembleAdd(currentPath, pathElement); ++it; @@ -1067,14 +1067,14 @@ Pathfinder::addLink( // to XRP only if (!bOnXRP && app_.getOrderBookDB().isBookToXRP({uEndCurrency, uEndIssuer}, mDomain)) { - STPathElement pathElement( + STPathElement const pathElement( STPathElement::typeCurrency, xrpAccount(), xrpCurrency(), xrpAccount()); incompletePaths.assembleAdd(currentPath, pathElement); } } else { - bool bDestOnly = (addFlags & afOB_LAST) != 0; + bool const bDestOnly = (addFlags & afOB_LAST) != 0; auto books = app_.getOrderBookDB().getBooksByTakerPays({uEndCurrency, uEndIssuer}, mDomain); JLOG(j_.trace()) << books.size() << " books found from this currency/issuer"; diff --git a/src/xrpld/rpc/detail/RPCCall.cpp b/src/xrpld/rpc/detail/RPCCall.cpp index 5c57f96d79..f4613a3e72 100644 --- a/src/xrpld/rpc/detail/RPCCall.cpp +++ b/src/xrpld/rpc/detail/RPCCall.cpp @@ -104,15 +104,15 @@ private: // optionally followed by a forward slash and some other characters // (the issuer). // https://www.boost.org/doc/libs/1_82_0/libs/regex/doc/html/boost_regex/syntax/perl_syntax.html - static boost::regex reCurIss("\\`([][:alnum:]<>(){}[|?!@#$%^&*]{3})(?:/(.+))?\\'"); + static boost::regex const reCurIss("\\`([][:alnum:]<>(){}[|?!@#$%^&*]{3})(?:/(.+))?\\'"); boost::smatch smMatch; if (boost::regex_match(strCurrencyIssuer, smMatch, reCurIss)) { Json::Value jvResult(Json::objectValue); - std::string strCurrency = smMatch[1]; - std::string strIssuer = smMatch[2]; + std::string const strCurrency = smMatch[1]; + std::string const strIssuer = smMatch[2]; jvResult[jss::currency] = strCurrency; @@ -203,7 +203,7 @@ private: parseFetchInfo(Json::Value const& jvParams) { Json::Value jvRequest(Json::objectValue); - unsigned int iParams = jvParams.size(); + unsigned int const iParams = jvParams.size(); if (iParams != 0) jvRequest[jvParams[0u].asString()] = true; @@ -262,8 +262,8 @@ private: } else { - std::int64_t uLedgerMin = jvParams[1u].asInt(); - std::int64_t uLedgerMax = jvParams[2u].asInt(); + std::int64_t const uLedgerMin = jvParams[1u].asInt(); + std::int64_t const uLedgerMax = jvParams[2u].asInt(); if (uLedgerMax != -1 && uLedgerMax < uLedgerMin) { @@ -324,7 +324,7 @@ private: { try { - int iLimit = jvParams[4u].asInt(); + int const iLimit = jvParams[4u].asInt(); if (iLimit > 0) jvRequest[jss::limit] = iLimit; @@ -339,7 +339,7 @@ private: { try { - int bProof = jvParams[5u].asInt(); + int const bProof = jvParams[5u].asInt(); if (bProof != 0) jvRequest[jss::proof] = true; } @@ -365,7 +365,7 @@ private: if (jvParams.size() == 0u) return jvRequest; - std::string input = jvParams[0u].asString(); + std::string const input = jvParams[0u].asString(); if (input.find_first_not_of("0123456789") == std::string::npos) { jvRequest["can_delete"] = jvParams[0u].asUInt(); @@ -395,7 +395,7 @@ private: // handle case where there is one argument of the form ip:port if (std::count(ip.begin(), ip.end(), ':') == 1) { - std::size_t colon = ip.find_last_of(':'); + std::size_t const colon = ip.find_last_of(':'); jvRequest[jss::ip] = std::string{ip, 0, colon}; jvRequest[jss::port] = Json::Value{std::string{ip, colon + 1}}.asUInt(); return jvRequest; @@ -571,7 +571,7 @@ private: { Json::Reader reader; Json::Value jv; - bool valid_parse = reader.parse(jvParams[0u].asString(), jv); + bool const valid_parse = reader.parse(jvParams[0u].asString(), jv); if (valid_parse && isValidJson2(jv)) { if (jv.isObject()) @@ -653,7 +653,7 @@ private: { Json::Value jvRequest(Json::objectValue); - std::string strLedger = jvParams[0u].asString(); + std::string const strLedger = jvParams[0u].asString(); if (strLedger.length() == 64) { @@ -854,8 +854,8 @@ private: // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseAccountRaw1(Json::Value const& jvParams) { - std::string strIdent = jvParams[0u].asString(); - unsigned int iCursor = jvParams.size(); + std::string const strIdent = jvParams[0u].asString(); + unsigned int const iCursor = jvParams.size(); if (!parseBase58(strIdent)) return rpcError(rpcACT_MALFORMED); @@ -875,7 +875,7 @@ private: // NOLINTNEXTLINE(readability-convert-member-functions-to-static) parseVault(Json::Value const& jvParams) { - std::string strVaultID = jvParams[0u].asString(); + std::string const strVaultID = jvParams[0u].asString(); uint256 id = beast::zero; if (!id.parseHex(strVaultID)) return rpcError(rpcINVALID_PARAMS); @@ -919,7 +919,7 @@ private: { Json::Reader reader; Json::Value jvRequest{Json::objectValue}; - bool bLedger = 2 == jvParams.size(); + bool const bLedger = 2 == jvParams.size(); JLOG(j_.trace()) << "RPC json: " << jvParams[0u]; @@ -985,7 +985,7 @@ private: return std::nullopt; if (jvParams.size() < 4 && bOffline) return std::nullopt; - Json::UInt index = bOffline ? 3u : 2u; + Json::UInt const index = bOffline ? 3u : 2u; return jvParams[index].asString(); }(); @@ -1598,7 +1598,7 @@ rpcClient( else { // Transport error. - Json::Value jvRpcError = jvOutput; + Json::Value const jvRpcError = jvOutput; jvOutput = rpcError(rpcJSON_RPC); jvOutput["result"] = jvRpcError; diff --git a/src/xrpld/rpc/detail/RPCHandler.cpp b/src/xrpld/rpc/detail/RPCHandler.cpp index eea24ab0c0..1d8e1168b4 100644 --- a/src/xrpld/rpc/detail/RPCHandler.cpp +++ b/src/xrpld/rpc/detail/RPCHandler.cpp @@ -129,7 +129,7 @@ fillHandler(JsonContext& context, Handler const*& result) return rpcUNKNOWN_COMMAND; } - std::string strCommand = context.params.isMember(jss::command) + std::string const strCommand = context.params.isMember(jss::command) ? context.params[jss::command].asString() : context.params[jss::method].asString(); @@ -143,7 +143,7 @@ fillHandler(JsonContext& context, Handler const*& result) if (handler->role_ == Role::ADMIN && context.role != Role::ADMIN) return rpcNO_PERMISSION; - error_code_i res = conditionMet(handler->condition_, context); + error_code_i const res = conditionMet(handler->condition_, context); if (res != rpcSUCCESS) { return res; diff --git a/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp b/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp index 2216affa6f..955533c776 100644 --- a/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp +++ b/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp @@ -166,7 +166,7 @@ ledgerFromSpecifier( ledger.reset(); using LedgerCase = org::xrpl::rpc::v1::LedgerSpecifier::LedgerCase; - LedgerCase ledgerCase = specifier.ledger_case(); + LedgerCase const ledgerCase = specifier.ledger_case(); switch (ledgerCase) { case LedgerCase::kHash: { diff --git a/src/xrpld/rpc/detail/RPCSub.cpp b/src/xrpld/rpc/detail/RPCSub.cpp index 3aa5f75f6a..3b5b56d937 100644 --- a/src/xrpld/rpc/detail/RPCSub.cpp +++ b/src/xrpld/rpc/detail/RPCSub.cpp @@ -68,7 +68,7 @@ public: void send(Json::Value const& jvObj, bool broadcast) override { - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); auto jm = broadcast ? j_.debug() : j_.info(); JLOG(jm) << "RPCCall::fromNetwork push: " << jvObj; @@ -88,7 +88,7 @@ public: void setUsername(std::string const& strUsername) override { - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); mUsername = strUsername; } @@ -96,7 +96,7 @@ public: void setPassword(std::string const& strPassword) override { - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); mPassword = strPassword; } @@ -114,7 +114,7 @@ private: { { // Obtain the lock to manipulate the queue and change sending. - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); if (mDeque.empty()) { diff --git a/src/xrpld/rpc/detail/RippleLineCache.cpp b/src/xrpld/rpc/detail/RippleLineCache.cpp index d6ed7b1478..7cc77f9b8b 100644 --- a/src/xrpld/rpc/detail/RippleLineCache.cpp +++ b/src/xrpld/rpc/detail/RippleLineCache.cpp @@ -26,7 +26,7 @@ RippleLineCache::getRippleLines(AccountID const& accountID, LineDirection direct direction == LineDirection::outgoing ? LineDirection::incoming : LineDirection::outgoing, hash); - std::lock_guard sl(mLock); + std::lock_guard const sl(mLock); auto [it, inserted] = [&]() { diff --git a/src/xrpld/rpc/detail/Role.cpp b/src/xrpld/rpc/detail/Role.cpp index 499787cece..f832e43119 100644 --- a/src/xrpld/rpc/detail/Role.cpp +++ b/src/xrpld/rpc/detail/Role.cpp @@ -224,7 +224,7 @@ extractIpAddrFromField(std::string_view field) // If there's a port appended to the IP address, strip that by // terminating at the colon. - if (std::size_t colon = ret.find(':'); colon != std::string_view::npos) + if (std::size_t const colon = ret.find(':'); colon != std::string_view::npos) ret = ret.substr(0, colon); return ret; @@ -256,7 +256,7 @@ forwardedFor(http_request_type const& request) // We found a "for=". Scan for the end of the IP address. std::size_t const pos = [&found, &it]() { - std::size_t pos = + std::size_t const pos = std::string_view(found, it->value().end() - found).find_first_of(",;"); if (pos != std::string_view::npos) return pos; diff --git a/src/xrpld/rpc/detail/ServerHandler.cpp b/src/xrpld/rpc/detail/ServerHandler.cpp index ca026104cf..e5cc7a83bf 100644 --- a/src/xrpld/rpc/detail/ServerHandler.cpp +++ b/src/xrpld/rpc/detail/ServerHandler.cpp @@ -78,12 +78,12 @@ authorized(Port const& port, std::map const& h) return false; std::string strUserPass64 = it->second.substr(6); boost::trim(strUserPass64); - std::string strUserPass = base64_decode(strUserPass64); - std::string::size_type nColon = strUserPass.find(':'); + std::string const strUserPass = base64_decode(strUserPass64); + std::string::size_type const nColon = strUserPass.find(':'); if (nColon == std::string::npos) return false; - std::string strUser = strUserPass.substr(0, nColon); - std::string strPassword = strUserPass.substr(nColon + 1); + std::string const strUser = strUserPass.substr(0, nColon); + std::string const strPassword = strUserPass.substr(nColon + 1); return strUser == port.user && strPassword == port.password; } @@ -158,7 +158,7 @@ ServerHandler::onAccept(Session& session, boost::asio::ip::tcp::endpoint endpoin auto const& port = session.port(); auto const c = [this, &port]() { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); return ++count_[port]; }(); @@ -282,7 +282,7 @@ ServerHandler::onRequest(Session& session) return; } - std::shared_ptr detachedSession = session.detach(); + std::shared_ptr const detachedSession = session.detach(); auto const postResult = m_jobQueue.postCoro( jtCLIENT_RPC, "RPC-Client", [this, detachedSession](std::shared_ptr coro) { processSession(detachedSession, coro); @@ -343,14 +343,14 @@ ServerHandler::onWSMessage( void ServerHandler::onClose(Session& session, boost::system::error_code const&) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); --count_[session.port()]; } void ServerHandler::onStopped(Server&) { - std::lock_guard lock(mutex_); + std::lock_guard const lock(mutex_); stopped_ = true; condition_.notify_one(); } @@ -732,7 +732,7 @@ ServerHandler::processRequest( continue; } - std::string strMethod = method.asString(); + std::string const strMethod = method.asString(); if (strMethod.empty()) { usage.charge(Resource::feeMalformedRPC); diff --git a/src/xrpld/rpc/detail/TransactionSign.cpp b/src/xrpld/rpc/detail/TransactionSign.cpp index 1fb6fc291f..23c70b9def 100644 --- a/src/xrpld/rpc/detail/TransactionSign.cpp +++ b/src/xrpld/rpc/detail/TransactionSign.cpp @@ -251,7 +251,7 @@ checkPayment( return RPC::make_error(rpcINVALID_PARAMS, "Cannot build XRP to XRP paths."); { - LegacyPathFind lpf(isUnlimited(role), app); + LegacyPathFind const lpf(isUnlimited(role), app); if (!lpf.isOk()) return rpcError(rpcTOO_BUSY); @@ -274,7 +274,7 @@ checkPayment( // 4 is the maximum paths pf.computePathRanks(4); STPath fullLiquidityPath; - STPathSet paths; + STPathSet const paths; result = pf.getBestPaths(4, fullLiquidityPath, paths, sendMax.issue().account); } } @@ -631,7 +631,7 @@ transactionPreProcessImpl( // If multisign then return multiSignature, else set TxnSignature field. if (signingArgs.isMultiSigning()) { - Serializer s = buildMultiSigningData(*stTx, signingArgs.getSigner()); + Serializer const s = buildMultiSigningData(*stTx, signingArgs.getSigner()); auto multisig = xrpl::sign(pk, sk, s.slice()); @@ -673,7 +673,7 @@ transactionConstructImpl( { Serializer s; tpTrans->getSTransaction()->add(s); - Blob transBlob = s.getData(); + Blob const transBlob = s.getData(); SerialIter sit{makeSlice(transBlob)}; // Check the signature if that's called for. @@ -954,15 +954,15 @@ transactionSign( // Add and amend fields based on the transaction type. SigningForParams signForParams; - transactionPreProcessResult preprocResult = + transactionPreProcessResult const preprocResult = transactionPreProcessImpl(jvRequest, role, signForParams, validatedLedgerAge, app); if (!preprocResult.second) return preprocResult.first; - std::shared_ptr ledger = app.getOpenLedger().current(); + std::shared_ptr const ledger = app.getOpenLedger().current(); // Make sure the STTx makes a legitimate Transaction. - std::pair txn = + std::pair const txn = transactionConstructImpl(preprocResult.second, ledger->rules(), app); if (!txn.second) @@ -990,7 +990,7 @@ transactionSubmit( // Add and amend fields based on the transaction type. SigningForParams signForParams; - transactionPreProcessResult preprocResult = + transactionPreProcessResult const preprocResult = transactionPreProcessImpl(jvRequest, role, signForParams, validatedLedgerAge, app); if (!preprocResult.second) @@ -1150,7 +1150,7 @@ transactionSignFor( // Add and amend fields based on the transaction type. SigningForParams signForParams(*signerAccountID); - transactionPreProcessResult preprocResult = + transactionPreProcessResult const preprocResult = transactionPreProcessImpl(jvRequest, role, signForParams, validatedLedgerAge, app); if (!preprocResult.second) @@ -1160,7 +1160,8 @@ transactionSignFor( signForParams.validMultiSign(), "xrpl::RPC::transactionSignFor : valid multi-signature"); { - std::shared_ptr account_state = ledger->read(keylet::account(*signerAccountID)); + std::shared_ptr const account_state = + ledger->read(keylet::account(*signerAccountID)); // Make sure the account and secret belong together. auto const err = acctMatchesPubKey(account_state, *signerAccountID, signForParams.getPublicKey()); @@ -1198,7 +1199,7 @@ transactionSignFor( } // Make sure the STTx makes a legitimate Transaction. - std::pair txn = + std::pair const txn = transactionConstructImpl(sttx, ledger->rules(), app); if (!txn.second) @@ -1245,7 +1246,7 @@ transactionSubmitMultiSigned( if (RPC::contains_error(txJsonResult)) return std::move(txJsonResult); - std::shared_ptr sle = ledger->read(keylet::account(srcAddressID)); + std::shared_ptr const sle = ledger->read(keylet::account(srcAddressID)); if (!sle) { @@ -1291,7 +1292,7 @@ transactionSubmitMultiSigned( } catch (std::exception& ex) { - std::string reason(ex.what()); + std::string const reason(ex.what()); return RPC::make_error( rpcINTERNAL, "Exception while serializing transaction: " + reason); } diff --git a/src/xrpld/rpc/handlers/AccountLines.cpp b/src/xrpld/rpc/handlers/AccountLines.cpp index f7fc9bdd2d..24ebfaa446 100644 --- a/src/xrpld/rpc/handlers/AccountLines.cpp +++ b/src/xrpld/rpc/handlers/AccountLines.cpp @@ -105,7 +105,7 @@ doAccountLines(RPC::JsonContext& context) // this flag allows the requester to ask incoming trustlines in default // state be omitted - bool ignoreDefault = + bool const ignoreDefault = params.isMember(jss::ignore_default) && params[jss::ignore_default].asBool(); Json::Value& jsonLines(result[jss::lines] = Json::arrayValue); diff --git a/src/xrpld/rpc/handlers/AccountObjects.cpp b/src/xrpld/rpc/handlers/AccountObjects.cpp index cd67391da8..12132122c1 100644 --- a/src/xrpld/rpc/handlers/AccountObjects.cpp +++ b/src/xrpld/rpc/handlers/AccountObjects.cpp @@ -131,7 +131,7 @@ doAccountNFTs(RPC::JsonContext& context) obj[sfIssuer.jsonName] = to_string(nft::getIssuer(nftokenID)); obj[sfNFTokenTaxon.jsonName] = nft::toUInt32(nft::getTaxon(nftokenID)); obj[jss::nft_serial] = nft::getSerial(nftokenID); - if (std::uint16_t xferFee = {nft::getTransferFee(nftokenID)}) + if (std::uint16_t const xferFee = {nft::getTransferFee(nftokenID)}) obj[sfTransferFee.jsonName] = xferFee; } diff --git a/src/xrpld/rpc/handlers/AccountOffers.cpp b/src/xrpld/rpc/handlers/AccountOffers.cpp index 517c0728e9..38cc7c1dc5 100644 --- a/src/xrpld/rpc/handlers/AccountOffers.cpp +++ b/src/xrpld/rpc/handlers/AccountOffers.cpp @@ -17,7 +17,7 @@ namespace xrpl { void appendOfferJson(std::shared_ptr const& offer, Json::Value& offers) { - STAmount dirRate = amountFromQuality(getQuality(offer->getFieldH256(sfBookDirectory))); + STAmount const dirRate = amountFromQuality(getQuality(offer->getFieldH256(sfBookDirectory))); Json::Value& obj(offers.append(Json::objectValue)); offer->getFieldAmount(sfTakerPays).setJson(obj[jss::taker_pays]); offer->getFieldAmount(sfTakerGets).setJson(obj[jss::taker_gets]); diff --git a/src/xrpld/rpc/handlers/AccountTx.cpp b/src/xrpld/rpc/handlers/AccountTx.cpp index e120c98523..f46a71308c 100644 --- a/src/xrpld/rpc/handlers/AccountTx.cpp +++ b/src/xrpld/rpc/handlers/AccountTx.cpp @@ -41,18 +41,18 @@ parseLedgerArgs(RPC::Context& context, Json::Value const& params) if ((params.isMember(jss::ledger_index_min) || params.isMember(jss::ledger_index_max)) && (params.isMember(jss::ledger_hash) || params.isMember(jss::ledger_index))) { - RPC::Status status{rpcINVALID_PARAMS, "invalidParams"}; + RPC::Status const status{rpcINVALID_PARAMS, "invalidParams"}; status.inject(response); return response; } } if (params.isMember(jss::ledger_index_min) || params.isMember(jss::ledger_index_max)) { - uint32_t min = + uint32_t const min = params.isMember(jss::ledger_index_min) && params[jss::ledger_index_min].asInt() >= 0 ? params[jss::ledger_index_min].asUInt() : 0; - uint32_t max = + uint32_t const max = params.isMember(jss::ledger_index_max) && params[jss::ledger_index_max].asInt() >= 0 ? params[jss::ledger_index_max].asUInt() : UINT32_MAX; @@ -64,7 +64,7 @@ parseLedgerArgs(RPC::Context& context, Json::Value const& params) auto& hashValue = params[jss::ledger_hash]; if (!hashValue.isString()) { - RPC::Status status{rpcINVALID_PARAMS, "ledgerHashNotString"}; + RPC::Status const status{rpcINVALID_PARAMS, "ledgerHashNotString"}; status.inject(response); return response; } @@ -72,7 +72,7 @@ parseLedgerArgs(RPC::Context& context, Json::Value const& params) LedgerHash hash; if (!hash.parseHex(hashValue.asString())) { - RPC::Status status{rpcINVALID_PARAMS, "ledgerHashMalformed"}; + RPC::Status const status{rpcINVALID_PARAMS, "ledgerHashMalformed"}; status.inject(response); return response; } @@ -87,7 +87,7 @@ parseLedgerArgs(RPC::Context& context, Json::Value const& params) } else { - std::string ledgerStr = params[jss::ledger_index].asString(); + std::string const ledgerStr = params[jss::ledger_index].asString(); if (ledgerStr == "current" || ledgerStr.empty()) { @@ -103,7 +103,7 @@ parseLedgerArgs(RPC::Context& context, Json::Value const& params) } else { - RPC::Status status{rpcINVALID_PARAMS, "ledger_index string malformed"}; + RPC::Status const status{rpcINVALID_PARAMS, "ledger_index string malformed"}; status.inject(response); return response; } @@ -118,7 +118,7 @@ getLedgerRange(RPC::Context& context, std::optional const& ledg { std::uint32_t uValidatedMin = 0; std::uint32_t uValidatedMax = 0; - bool bValidated = context.ledgerMaster.getValidatedRange(uValidatedMin, uValidatedMax); + bool const bValidated = context.ledgerMaster.getValidatedRange(uValidatedMin, uValidatedMax); if (!bValidated) { @@ -173,7 +173,7 @@ getLedgerRange(RPC::Context& context, std::optional const& ledg return status; } - bool validated = context.ledgerMaster.isValidated(*ledgerView); + bool const validated = context.ledgerMaster.isValidated(*ledgerView); if (!validated || ledgerView->header().seq > uValidatedMax || ledgerView->header().seq < uValidatedMin) @@ -210,7 +210,7 @@ doAccountTxHelp(RPC::Context& context, AccountTxArgs const& args) result.marker = args.marker; - RelationalDatabase::AccountTxPageOptions options = { + RelationalDatabase::AccountTxPageOptions const options = { args.account, result.ledgerRange, result.marker, args.limit, isUnlimited(context.role)}; auto& db = context.app.getRelationalDatabase(); @@ -419,7 +419,7 @@ doAccountTxJson(RPC::JsonContext& context) !token[jss::ledger].isConvertibleTo(Json::ValueType::uintValue) || !token[jss::seq].isConvertibleTo(Json::ValueType::uintValue)) { - RPC::Status status{ + RPC::Status const status{ rpcINVALID_PARAMS, "invalid marker. Provide ledger index via ledger field, and " "transaction sequence number via seq field"}; diff --git a/src/xrpld/rpc/handlers/CanDelete.cpp b/src/xrpld/rpc/handlers/CanDelete.cpp index 052ebdf745..7d881e7d2e 100644 --- a/src/xrpld/rpc/handlers/CanDelete.cpp +++ b/src/xrpld/rpc/handlers/CanDelete.cpp @@ -22,7 +22,7 @@ doCanDelete(RPC::JsonContext& context) if (context.params.isMember(jss::can_delete)) { - Json::Value canDelete = context.params.get(jss::can_delete, 0); + Json::Value const canDelete = context.params.get(jss::can_delete, 0); std::uint32_t canDeleteSeq = 0; if (canDelete.isUInt()) diff --git a/src/xrpld/rpc/handlers/GatewayBalances.cpp b/src/xrpld/rpc/handlers/GatewayBalances.cpp index 8d03a3961d..20679e5f42 100644 --- a/src/xrpld/rpc/handlers/GatewayBalances.cpp +++ b/src/xrpld/rpc/handlers/GatewayBalances.cpp @@ -164,7 +164,7 @@ doGatewayBalances(RPC::JsonContext& context) if (!rs) return; - int balSign = rs->getBalance().signum(); + int const balSign = rs->getBalance().signum(); if (balSign == 0) return; diff --git a/src/xrpld/rpc/handlers/GetAggregatePrice.cpp b/src/xrpld/rpc/handlers/GetAggregatePrice.cpp index 4979c21f42..281f2d63a7 100644 --- a/src/xrpld/rpc/handlers/GetAggregatePrice.cpp +++ b/src/xrpld/rpc/handlers/GetAggregatePrice.cpp @@ -62,8 +62,8 @@ iteratePriceData( if (++history > maxHistory) return; - uint256 prevTx = chain->getFieldH256(sfPreviousTxnID); - std::uint32_t prevSeq = chain->getFieldU32(sfPreviousTxnLgrSeq); + uint256 const prevTx = chain->getFieldH256(sfPreviousTxnID); + std::uint32_t const prevSeq = chain->getFieldU32(sfPreviousTxnLgrSeq); auto const ledger = context.ledgerMaster.getLedgerBySeq(prevSeq); if (!ledger) @@ -320,7 +320,7 @@ doGetAggregatePrice(RPC::JsonContext& context) auto const middle = size_ / 2; if ((size_ % 2) == 0) { - static STAmount two{noIssue(), 2, 0}; + static STAmount const two{noIssue(), 2, 0}; auto it = itAdvance(prices.right.begin(), middle - 1); auto const& a1 = it->first; auto const& a2 = (++it)->first; diff --git a/src/xrpld/rpc/handlers/GetCounts.cpp b/src/xrpld/rpc/handlers/GetCounts.cpp index 09a952e114..648d29a5fd 100644 --- a/src/xrpld/rpc/handlers/GetCounts.cpp +++ b/src/xrpld/rpc/handlers/GetCounts.cpp @@ -71,7 +71,7 @@ getCountsJson(Application& app, int minObjectCount) ret[jss::dbKBTransaction] = dbKB; { - std::size_t c = app.getOPs().getLocalTxCount(); + std::size_t const c = app.getOPs().getLocalTxCount(); if (c > 0) ret[jss::local_txs] = static_cast(c); } diff --git a/src/xrpld/rpc/handlers/GetCounts.h b/src/xrpld/rpc/handlers/GetCounts.h index 60c7a3b693..286ad38af3 100644 --- a/src/xrpld/rpc/handlers/GetCounts.h +++ b/src/xrpld/rpc/handlers/GetCounts.h @@ -7,4 +7,4 @@ namespace xrpl { Json::Value getCountsJson(Application& app, int minObjectCount); -} +} // namespace xrpl diff --git a/src/xrpld/rpc/handlers/LedgerAccept.cpp b/src/xrpld/rpc/handlers/LedgerAccept.cpp index c7a828863a..91e88b707f 100644 --- a/src/xrpld/rpc/handlers/LedgerAccept.cpp +++ b/src/xrpld/rpc/handlers/LedgerAccept.cpp @@ -22,7 +22,7 @@ doLedgerAccept(RPC::JsonContext& context) } else { - std::unique_lock lock{context.app.getMasterMutex()}; + std::unique_lock const lock{context.app.getMasterMutex()}; context.netOps.acceptLedger(); jvResult[jss::ledger_current_index] = context.ledgerMaster.getCurrentLedgerIndex(); } diff --git a/src/xrpld/rpc/handlers/LedgerData.cpp b/src/xrpld/rpc/handlers/LedgerData.cpp index 733d1c99c6..059c844e6e 100644 --- a/src/xrpld/rpc/handlers/LedgerData.cpp +++ b/src/xrpld/rpc/handlers/LedgerData.cpp @@ -116,9 +116,9 @@ doLedgerData(RPC::JsonContext& context) std::pair doLedgerDataGrpc(RPC::GRPCContext& context) { - org::xrpl::rpc::v1::GetLedgerDataRequest& request = context.params; + org::xrpl::rpc::v1::GetLedgerDataRequest const& request = context.params; org::xrpl::rpc::v1::GetLedgerDataResponse response; - grpc::Status status = grpc::Status::OK; + grpc::Status const status = grpc::Status::OK; std::shared_ptr ledger; if (auto status = RPC::ledgerFromRequest(ledger, context)) @@ -142,7 +142,7 @@ doLedgerDataGrpc(RPC::GRPCContext& con } else if (!request.marker().empty()) { - grpc::Status errorStatus{grpc::StatusCode::INVALID_ARGUMENT, "marker malformed"}; + grpc::Status const errorStatus{grpc::StatusCode::INVALID_ARGUMENT, "marker malformed"}; return {response, errorStatus}; } diff --git a/src/xrpld/rpc/handlers/LedgerDiff.cpp b/src/xrpld/rpc/handlers/LedgerDiff.cpp index 2990315880..56a4d97b94 100644 --- a/src/xrpld/rpc/handlers/LedgerDiff.cpp +++ b/src/xrpld/rpc/handlers/LedgerDiff.cpp @@ -5,50 +5,50 @@ namespace xrpl { std::pair doLedgerDiffGrpc(RPC::GRPCContext& context) { - org::xrpl::rpc::v1::GetLedgerDiffRequest& request = context.params; + org::xrpl::rpc::v1::GetLedgerDiffRequest const& request = context.params; org::xrpl::rpc::v1::GetLedgerDiffResponse response; - grpc::Status status = grpc::Status::OK; + grpc::Status const status = grpc::Status::OK; std::shared_ptr baseLedgerRv; std::shared_ptr desiredLedgerRv; if (RPC::ledgerFromSpecifier(baseLedgerRv, request.base_ledger(), context)) { - grpc::Status errorStatus{grpc::StatusCode::NOT_FOUND, "base ledger not found"}; + grpc::Status const errorStatus{grpc::StatusCode::NOT_FOUND, "base ledger not found"}; return {response, errorStatus}; } if (RPC::ledgerFromSpecifier(desiredLedgerRv, request.desired_ledger(), context)) { - grpc::Status errorStatus{grpc::StatusCode::NOT_FOUND, "desired ledger not found"}; + grpc::Status const errorStatus{grpc::StatusCode::NOT_FOUND, "desired ledger not found"}; return {response, errorStatus}; } - std::shared_ptr baseLedger = + std::shared_ptr const baseLedger = std::dynamic_pointer_cast(baseLedgerRv); if (!baseLedger) { - grpc::Status errorStatus{grpc::StatusCode::NOT_FOUND, "base ledger not validated"}; + grpc::Status const errorStatus{grpc::StatusCode::NOT_FOUND, "base ledger not validated"}; return {response, errorStatus}; } - std::shared_ptr desiredLedger = + std::shared_ptr const desiredLedger = std::dynamic_pointer_cast(desiredLedgerRv); if (!desiredLedger) { - grpc::Status errorStatus{grpc::StatusCode::NOT_FOUND, "base ledger not validated"}; + grpc::Status const errorStatus{grpc::StatusCode::NOT_FOUND, "base ledger not validated"}; return {response, errorStatus}; } SHAMap::Delta differences; - int maxDifferences = std::numeric_limits::max(); + int const maxDifferences = std::numeric_limits::max(); - bool res = + bool const res = baseLedger->stateMap().compare(desiredLedger->stateMap(), differences, maxDifferences); if (!res) { - grpc::Status errorStatus{ + grpc::Status const errorStatus{ grpc::StatusCode::RESOURCE_EXHAUSTED, "too many differences between specified ledgers"}; return {response, errorStatus}; } diff --git a/src/xrpld/rpc/handlers/LedgerEntry.cpp b/src/xrpld/rpc/handlers/LedgerEntry.cpp index c7a47a0517..d27574944d 100644 --- a/src/xrpld/rpc/handlers/LedgerEntry.cpp +++ b/src/xrpld/rpc/handlers/LedgerEntry.cpp @@ -370,7 +370,7 @@ parseDirectoryNode( "malformedRequest", "Must have exactly one of `owner` and `dir_root` fields."); } - std::uint64_t uSubIndex = params.get(jss::sub_index, 0).asUInt(); + std::uint64_t const uSubIndex = params.get(jss::sub_index, 0).asUInt(); if (params.isMember(jss::dir_root)) { @@ -956,9 +956,9 @@ doLedgerEntry(RPC::JsonContext& context) std::pair doLedgerEntryGrpc(RPC::GRPCContext& context) { - org::xrpl::rpc::v1::GetLedgerEntryRequest& request = context.params; + org::xrpl::rpc::v1::GetLedgerEntryRequest const& request = context.params; org::xrpl::rpc::v1::GetLedgerEntryResponse response; - grpc::Status status = grpc::Status::OK; + grpc::Status const status = grpc::Status::OK; std::shared_ptr ledger; if (auto status = RPC::ledgerFromRequest(ledger, context)) @@ -978,14 +978,14 @@ doLedgerEntryGrpc(RPC::GRPCContext& c auto const key = uint256::fromVoidChecked(request.key()); if (!key) { - grpc::Status errorStatus{grpc::StatusCode::INVALID_ARGUMENT, "index malformed"}; + grpc::Status const errorStatus{grpc::StatusCode::INVALID_ARGUMENT, "index malformed"}; return {response, errorStatus}; } auto const sleNode = ledger->read(keylet::unchecked(*key)); if (!sleNode) { - grpc::Status errorStatus{grpc::StatusCode::NOT_FOUND, "object not found"}; + grpc::Status const errorStatus{grpc::StatusCode::NOT_FOUND, "object not found"}; return {response, errorStatus}; } diff --git a/src/xrpld/rpc/handlers/LedgerEntryHelpers.h b/src/xrpld/rpc/handlers/LedgerEntryHelpers.h index 9182c9cfd7..17207d81e8 100644 --- a/src/xrpld/rpc/handlers/LedgerEntryHelpers.h +++ b/src/xrpld/rpc/handlers/LedgerEntryHelpers.h @@ -16,7 +16,7 @@ namespace xrpl { namespace LedgerEntryHelpers { -Unexpected +inline Unexpected missingFieldError(Json::StaticString const field, std::optional err = std::nullopt) { Json::Value json = Json::objectValue; @@ -26,7 +26,7 @@ missingFieldError(Json::StaticString const field, std::optional err return Unexpected(json); } -Unexpected +inline Unexpected invalidFieldError(std::string const& err, Json::StaticString const field, std::string const& type) { Json::Value json = Json::objectValue; @@ -36,7 +36,7 @@ invalidFieldError(std::string const& err, Json::StaticString const field, std::s return Unexpected(json); } -Unexpected +inline Unexpected malformedError(std::string const& err, std::string const& message) { Json::Value json = Json::objectValue; @@ -46,7 +46,7 @@ malformedError(std::string const& err, std::string const& message) return Unexpected(json); } -Expected +inline Expected hasRequired( Json::Value const& params, std::initializer_list fields, @@ -86,7 +86,7 @@ required( } template <> -std::optional +inline std::optional parse(Json::Value const& param) { if (!param.isString()) @@ -101,7 +101,7 @@ parse(Json::Value const& param) return account; } -Expected +inline Expected requiredAccountID( Json::Value const& params, Json::StaticString const fieldName, @@ -110,7 +110,7 @@ requiredAccountID( return required(params, fieldName, err, "AccountID"); } -std::optional +inline std::optional parseHexBlob(Json::Value const& param, std::size_t maxLength) { if (!param.isString()) @@ -123,7 +123,7 @@ parseHexBlob(Json::Value const& param, std::size_t maxLength) return blob; } -Expected +inline Expected requiredHexBlob( Json::Value const& params, Json::StaticString const fieldName, @@ -142,7 +142,7 @@ requiredHexBlob( } template <> -std::optional +inline std::optional parse(Json::Value const& param) { if (param.isUInt() || (param.isInt() && param.asInt() >= 0)) @@ -158,7 +158,7 @@ parse(Json::Value const& param) return std::nullopt; } -Expected +inline Expected requiredUInt32( Json::Value const& params, Json::StaticString const fieldName, @@ -168,7 +168,7 @@ requiredUInt32( } template <> -std::optional +inline std::optional parse(Json::Value const& param) { uint256 uNodeIndex; @@ -180,7 +180,7 @@ parse(Json::Value const& param) return uNodeIndex; } -Expected +inline Expected requiredUInt256( Json::Value const& params, Json::StaticString const fieldName, @@ -190,7 +190,7 @@ requiredUInt256( } template <> -std::optional +inline std::optional parse(Json::Value const& param) { uint192 field; @@ -202,7 +202,7 @@ parse(Json::Value const& param) return field; } -Expected +inline Expected requiredUInt192( Json::Value const& params, Json::StaticString const fieldName, @@ -212,7 +212,7 @@ requiredUInt192( } template <> -std::optional +inline std::optional parse(Json::Value const& param) { try @@ -225,13 +225,13 @@ parse(Json::Value const& param) } } -Expected +inline Expected requiredIssue(Json::Value const& params, Json::StaticString const fieldName, std::string const& err) { return required(params, fieldName, err, "Issue"); } -Expected +inline Expected parseBridgeFields(Json::Value const& params) { if (auto const value = hasRequired( diff --git a/src/xrpld/rpc/handlers/LedgerHandler.cpp b/src/xrpld/rpc/handlers/LedgerHandler.cpp index cd70cb064a..0707ad1ffe 100644 --- a/src/xrpld/rpc/handlers/LedgerHandler.cpp +++ b/src/xrpld/rpc/handlers/LedgerHandler.cpp @@ -21,7 +21,7 @@ Status LedgerHandler::check() { auto const& params = context_.params; - bool needsLedger = params.isMember(jss::ledger) || params.isMember(jss::ledger_hash) || + bool const needsLedger = params.isMember(jss::ledger) || params.isMember(jss::ledger_hash) || params.isMember(jss::ledger_index); if (!needsLedger) return Status::OK; @@ -113,9 +113,9 @@ std::pair doLedgerGrpc(RPC::GRPCContext& context) { auto begin = std::chrono::system_clock::now(); - org::xrpl::rpc::v1::GetLedgerRequest& request = context.params; + org::xrpl::rpc::v1::GetLedgerRequest const& request = context.params; org::xrpl::rpc::v1::GetLedgerResponse response; - grpc::Status status = grpc::Status::OK; + grpc::Status const status = grpc::Status::OK; std::shared_ptr ledger; if (auto status = RPC::ledgerFromRequest(ledger, context)) @@ -147,11 +147,11 @@ doLedgerGrpc(RPC::GRPCContext& context) if (request.expand()) { auto txn = response.mutable_transactions_list()->add_transactions(); - Serializer sTxn = i.first->getSerializer(); + Serializer const sTxn = i.first->getSerializer(); txn->set_transaction_blob(sTxn.data(), sTxn.getLength()); if (i.second) { - Serializer sMeta = i.second->getSerializer(); + Serializer const sMeta = i.second->getSerializer(); txn->set_metadata_blob(sMeta.data(), sMeta.getLength()); } } @@ -173,30 +173,32 @@ doLedgerGrpc(RPC::GRPCContext& context) if (request.get_objects()) { - std::shared_ptr parent = + std::shared_ptr const parent = context.app.getLedgerMaster().getLedgerBySeq(ledger->seq() - 1); - std::shared_ptr base = std::dynamic_pointer_cast(parent); + std::shared_ptr const base = std::dynamic_pointer_cast(parent); if (!base) { - grpc::Status errorStatus{grpc::StatusCode::NOT_FOUND, "parent ledger not validated"}; + grpc::Status const errorStatus{ + grpc::StatusCode::NOT_FOUND, "parent ledger not validated"}; return {response, errorStatus}; } - std::shared_ptr desired = std::dynamic_pointer_cast(ledger); + std::shared_ptr const desired = + std::dynamic_pointer_cast(ledger); if (!desired) { - grpc::Status errorStatus{grpc::StatusCode::NOT_FOUND, "ledger not validated"}; + grpc::Status const errorStatus{grpc::StatusCode::NOT_FOUND, "ledger not validated"}; return {response, errorStatus}; } SHAMap::Delta differences; - int maxDifferences = std::numeric_limits::max(); + int const maxDifferences = std::numeric_limits::max(); - bool res = base->stateMap().compare(desired->stateMap(), differences, maxDifferences); + bool const res = base->stateMap().compare(desired->stateMap(), differences, maxDifferences); if (!res) { - grpc::Status errorStatus{ + grpc::Status const errorStatus{ grpc::StatusCode::RESOURCE_EXHAUSTED, "too many differences between specified ledgers"}; return {response, errorStatus}; diff --git a/src/xrpld/rpc/handlers/LedgerHandler.h b/src/xrpld/rpc/handlers/LedgerHandler.h index 418958e9f1..f024241546 100644 --- a/src/xrpld/rpc/handlers/LedgerHandler.h +++ b/src/xrpld/rpc/handlers/LedgerHandler.h @@ -14,7 +14,7 @@ namespace Json { class Object; -} +} // namespace Json namespace xrpl { namespace RPC { diff --git a/src/xrpld/rpc/handlers/LogLevel.cpp b/src/xrpld/rpc/handlers/LogLevel.cpp index a932dfb198..e1e637435c 100644 --- a/src/xrpld/rpc/handlers/LogLevel.cpp +++ b/src/xrpld/rpc/handlers/LogLevel.cpp @@ -22,7 +22,7 @@ doLogLevel(RPC::JsonContext& context) Json::Value lev(Json::objectValue); lev[jss::base] = Logs::toString(Logs::fromSeverity(context.app.getLogs().threshold())); - std::vector> logTable( + std::vector> const logTable( context.app.getLogs().partition_severities()); for (auto const& [k, v] : logTable) lev[k] = v; @@ -49,7 +49,7 @@ doLogLevel(RPC::JsonContext& context) if (context.params.isMember(jss::partition)) { // set partition threshold - std::string partition(context.params[jss::partition].asString()); + std::string const partition(context.params[jss::partition].asString()); if (boost::iequals(partition, "base")) { diff --git a/src/xrpld/rpc/handlers/NoRippleCheck.cpp b/src/xrpld/rpc/handlers/NoRippleCheck.cpp index c3e36280a6..d00a3e279b 100644 --- a/src/xrpld/rpc/handlers/NoRippleCheck.cpp +++ b/src/xrpld/rpc/handlers/NoRippleCheck.cpp @@ -88,7 +88,7 @@ doNoRippleCheck(RPC::JsonContext& context) if (!ledger) return result; - Json::Value dummy; + Json::Value dummy; // NOLINT(misc-const-correctness) Json::Value& jvTransactions = transactions ? (result[jss::transactions] = Json::arrayValue) : dummy; @@ -107,7 +107,7 @@ doNoRippleCheck(RPC::JsonContext& context) Json::Value& problems = (result["problems"] = Json::arrayValue); - bool bDefaultRipple = (sle->getFieldU32(sfFlags) & lsfDefaultRipple) != 0u; + bool const bDefaultRipple = (sle->getFieldU32(sfFlags) & lsfDefaultRipple) != 0u; if ((static_cast(bDefaultRipple) & static_cast(!roleGateway)) != 0) { @@ -151,9 +151,10 @@ doNoRippleCheck(RPC::JsonContext& context) } if (needFix) { - AccountID peer = + AccountID const peer = ownedItem->getFieldAmount(bLow ? sfHighLimit : sfLowLimit).getIssuer(); - STAmount peerLimit = ownedItem->getFieldAmount(bLow ? sfHighLimit : sfLowLimit); + STAmount const peerLimit = + ownedItem->getFieldAmount(bLow ? sfHighLimit : sfLowLimit); problem += to_string(peerLimit.getCurrency()); problem += " line to "; problem += to_string(peerLimit.getIssuer()); diff --git a/src/xrpld/rpc/handlers/OwnerInfo.cpp b/src/xrpld/rpc/handlers/OwnerInfo.cpp index 202d0e9b5b..659a149e20 100644 --- a/src/xrpld/rpc/handlers/OwnerInfo.cpp +++ b/src/xrpld/rpc/handlers/OwnerInfo.cpp @@ -20,7 +20,7 @@ doOwnerInfo(RPC::JsonContext& context) return RPC::missing_field_error(jss::account); } - std::string strIdent = context.params.isMember(jss::account) + std::string const strIdent = context.params.isMember(jss::account) ? context.params[jss::account].asString() : context.params[jss::ident].asString(); Json::Value ret; diff --git a/src/xrpld/rpc/handlers/PathFind.cpp b/src/xrpld/rpc/handlers/PathFind.cpp index 1b180167ea..ced3625b4c 100644 --- a/src/xrpld/rpc/handlers/PathFind.cpp +++ b/src/xrpld/rpc/handlers/PathFind.cpp @@ -40,7 +40,7 @@ doPathFind(RPC::JsonContext& context) if (sSubCommand == "close") { - InfoSubRequest::pointer request = context.infoSub->getRequest(); + InfoSubRequest::pointer const request = context.infoSub->getRequest(); if (!request) return rpcError(rpcNO_PF_REQUEST); @@ -51,7 +51,7 @@ doPathFind(RPC::JsonContext& context) if (sSubCommand == "status") { - InfoSubRequest::pointer request = context.infoSub->getRequest(); + InfoSubRequest::pointer const request = context.infoSub->getRequest(); if (!request) return rpcError(rpcNO_PF_REQUEST); diff --git a/src/xrpld/rpc/handlers/Peers.cpp b/src/xrpld/rpc/handlers/Peers.cpp index ddcb674b33..646aae7bc8 100644 --- a/src/xrpld/rpc/handlers/Peers.cpp +++ b/src/xrpld/rpc/handlers/Peers.cpp @@ -42,7 +42,7 @@ doPeers(RPC::JsonContext& context) auto const self = context.app.nodeIdentity().first; Json::Value& cluster = (jvResult[jss::cluster] = Json::objectValue); - std::uint32_t ref = context.app.getFeeTrack().getLoadBase(); + std::uint32_t const ref = context.app.getFeeTrack().getLoadBase(); context.app.getCluster().for_each([&cluster, now, ref, &self](ClusterNode const& node) { if (node.identity() == self) diff --git a/src/xrpld/rpc/handlers/Random.cpp b/src/xrpld/rpc/handlers/Random.cpp index 2fb8abf3c9..5ed4426940 100644 --- a/src/xrpld/rpc/handlers/Random.cpp +++ b/src/xrpld/rpc/handlers/Random.cpp @@ -10,7 +10,7 @@ namespace xrpl { namespace RPC { struct JsonContext; -} +} // namespace RPC // Result: // { diff --git a/src/xrpld/rpc/handlers/RipplePathFind.cpp b/src/xrpld/rpc/handlers/RipplePathFind.cpp index cc695908fb..ac4f22a1aa 100644 --- a/src/xrpld/rpc/handlers/RipplePathFind.cpp +++ b/src/xrpld/rpc/handlers/RipplePathFind.cpp @@ -113,7 +113,7 @@ doRipplePathFind(RPC::JsonContext& context) // captured reference could evaporate when we return from // coroCopy->resume(). This is not strictly necessary, but // will make maintenance easier. - std::shared_ptr coroCopy{context.coro}; + std::shared_ptr const coroCopy{context.coro}; if (!coroCopy->post()) { // The post() failed, so we won't get a thread to let @@ -140,7 +140,7 @@ doRipplePathFind(RPC::JsonContext& context) if (!lpLedger) return jvResult; - RPC::LegacyPathFind lpf(isUnlimited(context.role), context.app); + RPC::LegacyPathFind const lpf(isUnlimited(context.role), context.app); if (!lpf.isOk()) return rpcError(rpcTOO_BUSY); diff --git a/src/xrpld/rpc/handlers/ServerDefinitions.cpp b/src/xrpld/rpc/handlers/ServerDefinitions.cpp index 2f11e18efb..f99f427ca8 100644 --- a/src/xrpld/rpc/handlers/ServerDefinitions.cpp +++ b/src/xrpld/rpc/handlers/ServerDefinitions.cpp @@ -123,7 +123,7 @@ ServerDefinitions::ServerDefinitions() : defs_{Json::objectValue} std::map typeMap{{-1, "Done"}}; for (auto const& [rawName, typeValue] : sTypeMap) { - std::string typeName = translate(std::string(rawName).substr(4) /* remove STI_ */); + std::string const typeName = translate(std::string(rawName).substr(4) /* remove STI_ */); defs_[jss::TYPES][typeName] = typeValue; typeMap[typeValue] = typeName; } diff --git a/src/xrpld/rpc/handlers/Stop.cpp b/src/xrpld/rpc/handlers/Stop.cpp index d2f1cd7a80..b47c35e21d 100644 --- a/src/xrpld/rpc/handlers/Stop.cpp +++ b/src/xrpld/rpc/handlers/Stop.cpp @@ -7,7 +7,7 @@ namespace xrpl { namespace RPC { struct JsonContext; -} +} // namespace RPC Json::Value doStop(RPC::JsonContext& context) diff --git a/src/xrpld/rpc/handlers/Subscribe.cpp b/src/xrpld/rpc/handlers/Subscribe.cpp index fc5238b37b..af3e998a58 100644 --- a/src/xrpld/rpc/handlers/Subscribe.cpp +++ b/src/xrpld/rpc/handlers/Subscribe.cpp @@ -32,7 +32,7 @@ doSubscribe(RPC::JsonContext& context) if (context.role != Role::ADMIN) return rpcError(rpcNO_PERMISSION); - std::string strUrl = context.params[jss::url].asString(); + std::string const strUrl = context.params[jss::url].asString(); std::string strUsername = context.params.isMember(jss::url_username) ? context.params[jss::url_username].asString() : ""; @@ -106,7 +106,7 @@ doSubscribe(RPC::JsonContext& context) if (!it.isString()) return rpcError(rpcSTREAM_MALFORMED); - std::string streamName = it.asString(); + std::string const streamName = it.asString(); if (streamName == "server") { context.netOps.subServer(ispSub, jvResult, context.role == Role::ADMIN); diff --git a/src/xrpld/rpc/handlers/Tx.cpp b/src/xrpld/rpc/handlers/Tx.cpp index 211372db45..a3ed788060 100644 --- a/src/xrpld/rpc/handlers/Tx.cpp +++ b/src/xrpld/rpc/handlers/Tx.cpp @@ -125,7 +125,8 @@ doTxHelp(RPC::Context& context, TxArgs args) return {result, rpcSUCCESS}; } - std::shared_ptr ledger = context.ledgerMaster.getLedgerBySeq(txn->getLedger()); + std::shared_ptr const ledger = + context.ledgerMaster.getLedgerBySeq(txn->getLedger()); if (ledger && !ledger->open()) result.ledgerHash = ledger->header().hash; @@ -148,9 +149,9 @@ doTxHelp(RPC::Context& context, TxArgs args) // compute outgoing CTID if (meta->getAsObject().isFieldPresent(sfTransactionIndex)) { - uint32_t lgrSeq = ledger->header().seq; - uint32_t txnIdx = meta->getAsObject().getFieldU32(sfTransactionIndex); - uint32_t netID = context.app.getNetworkIDService().getNetworkID(); + uint32_t const lgrSeq = ledger->header().seq; + uint32_t const txnIdx = meta->getAsObject().getFieldU32(sfTransactionIndex); + uint32_t const netID = context.app.getNetworkIDService().getNetworkID(); if (txnIdx <= 0xFFFFU && netID < 0xFFFFU && lgrSeq < 0x0FFF'FFFFUL) result.ctid = RPC::encodeCTID(lgrSeq, txnIdx, netID); @@ -310,7 +311,7 @@ doTxJson(RPC::JsonContext& context) } } - std::pair res = doTxHelp(context, args); + std::pair const res = doTxHelp(context, args); return populateJsonResponse(res, args, context); } diff --git a/src/xrpld/rpc/handlers/TxHistory.cpp b/src/xrpld/rpc/handlers/TxHistory.cpp index 02ff6fb43c..3467b1c990 100644 --- a/src/xrpld/rpc/handlers/TxHistory.cpp +++ b/src/xrpld/rpc/handlers/TxHistory.cpp @@ -27,7 +27,7 @@ doTxHistory(RPC::JsonContext& context) if (!context.params.isMember(jss::start)) return rpcError(rpcINVALID_PARAMS); - unsigned int startIndex = context.params[jss::start].asUInt(); + unsigned int const startIndex = context.params[jss::start].asUInt(); if ((startIndex > 10000) && (!isUnlimited(context.role))) return rpcError(rpcNO_PERMISSION); diff --git a/src/xrpld/rpc/handlers/Unsubscribe.cpp b/src/xrpld/rpc/handlers/Unsubscribe.cpp index 824d57203c..d3e36cc612 100644 --- a/src/xrpld/rpc/handlers/Unsubscribe.cpp +++ b/src/xrpld/rpc/handlers/Unsubscribe.cpp @@ -28,7 +28,7 @@ doUnsubscribe(RPC::JsonContext& context) if (context.role != Role::ADMIN) return rpcError(rpcNO_PERMISSION); - std::string strUrl = context.params[jss::url].asString(); + std::string const strUrl = context.params[jss::url].asString(); ispSub = context.netOps.findRpcSub(strUrl); if (!ispSub) return jvResult; @@ -49,7 +49,7 @@ doUnsubscribe(RPC::JsonContext& context) if (!it.isString()) return rpcError(rpcSTREAM_MALFORMED); - std::string streamName = it.asString(); + std::string const streamName = it.asString(); if (streamName == "server") { context.netOps.unsubServer(ispSub->getSeq()); diff --git a/src/xrpld/shamap/NodeFamily.cpp b/src/xrpld/shamap/NodeFamily.cpp index ec5e9eb1b2..3460c68608 100644 --- a/src/xrpld/shamap/NodeFamily.cpp +++ b/src/xrpld/shamap/NodeFamily.cpp @@ -39,7 +39,7 @@ void NodeFamily::reset() { { - std::lock_guard lock(maxSeqMutex_); + std::lock_guard const lock(maxSeqMutex_); maxSeq_ = 0; } From a9afd2c11655ff3b46ac363fa52f96a21689e9f6 Mon Sep 17 00:00:00 2001 From: Mayukha Vadari Date: Tue, 31 Mar 2026 15:56:30 -0400 Subject: [PATCH 41/53] fix: Fix previous ledger size typo in RCLConsensus (#6696) --- src/xrpld/app/consensus/RCLConsensus.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/xrpld/app/consensus/RCLConsensus.cpp b/src/xrpld/app/consensus/RCLConsensus.cpp index 838529795b..b7b0919aad 100644 --- a/src/xrpld/app/consensus/RCLConsensus.cpp +++ b/src/xrpld/app/consensus/RCLConsensus.cpp @@ -137,7 +137,7 @@ RCLConsensus::Adaptor::share(RCLCxPeerPos const& peerPos) prop.set_closetime(proposal.closeTime().time_since_epoch().count()); prop.set_currenttxhash(proposal.position().begin(), proposal.position().size()); - prop.set_previousledger(proposal.prevLedger().begin(), proposal.position().size()); + prop.set_previousledger(proposal.prevLedger().begin(), proposal.prevLedger().size()); auto const pk = peerPos.publicKey().slice(); prop.set_nodepubkey(pk.data(), pk.size()); From b6aa4a8fde15b8be27e9ac6485175b2dea125060 Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Wed, 1 Apr 2026 11:33:02 +0100 Subject: [PATCH 42/53] chore: Use nudb recipe from the upstream (#6701) --- BUILD.md | 2 +- conan.lock | 17 ++++++++--------- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/BUILD.md b/BUILD.md index 4f709a032b..757f76a716 100644 --- a/BUILD.md +++ b/BUILD.md @@ -141,7 +141,7 @@ Alternatively, you can pull our recipes from the repository and export them loca ```bash # Define which recipes to export. -recipes=('abseil' 'ed25519' 'grpc' 'm4' 'mpt-crypto' 'nudb' 'openssl' 'secp256k1' 'snappy' 'soci' 'wasm-xrplf' 'wasmi') +recipes=('abseil' 'ed25519' 'grpc' 'm4' 'mpt-crypto' 'openssl' 'secp256k1' 'snappy' 'soci' 'wasm-xrplf' 'wasmi') # Selectively check out the recipes from our CCI fork. cd external diff --git a/conan.lock b/conan.lock index 575be2e071..f1d6ed3fa5 100644 --- a/conan.lock +++ b/conan.lock @@ -3,22 +3,22 @@ "requires": [ "zlib/1.3.1#cac0f6daea041b0ccf42934163defb20%1774439233.809", "xxhash/0.8.3#681d36a0a6111fc56e5e45ea182c19cc%1765850149.987", - "sqlite3/3.51.0#66aa11eabd0e34954c5c1c061ad44abe%1763899256.358", + "sqlite3/3.51.0#66aa11eabd0e34954c5c1c061ad44abe%1774467355.988", "soci/4.0.3#fe32b9ad5eb47e79ab9e45a68f363945%1774450067.231", "snappy/1.1.10#968fef506ff261592ec30c574d4a7809%1765850147.878", "secp256k1/0.7.1#481881709eb0bdd0185a12b912bbe8ad%1770910500.329", "rocksdb/10.5.1#4a197eca381a3e5ae8adf8cffa5aacd0%1765850186.86", "re2/20251105#8579cfd0bda4daf0683f9e3898f964b4%1774398111.888", - "protobuf/6.33.5#d96d52ba5baaaa532f47bda866ad87a5%1773224203.27", + "protobuf/6.33.5#d96d52ba5baaaa532f47bda866ad87a5%1774467363.12", "openssl/3.6.1#e6399de266349245a4542fc5f6c71552%1774458290.139", - "nudb/2.0.9#0432758a24204da08fee953ec9ea03cb%1769436073.32", + "nudb/2.0.9#11149c73f8f2baff9a0198fe25971fc7%1774883011.384", "lz4/1.10.0#59fc63cac7f10fbe8e05c7e62c2f3504%1765850143.914", "libiconv/1.17#1e65319e945f2d31941a9d28cc13c058%1765842973.492", "libbacktrace/cci.20210118#a7691bfccd8caaf66309df196790a5a1%1765842973.03", "libarchive/3.8.1#ffee18995c706e02bf96e7a2f7042e0d%1765850144.736", "jemalloc/5.3.0#e951da9cf599e956cebc117880d2d9f8%1729241615.244", "gtest/1.17.0#5224b3b3ff3b4ce1133cbdd27d53ee7d%1768312129.152", - "grpc/1.78.1#b1a9e74b145cc471bed4dc64dc6eb2c1%1772623605.068", + "grpc/1.78.1#b1a9e74b145cc471bed4dc64dc6eb2c1%1774467387.342", "ed25519/2015.03#ae761bdc52730a843f0809bdf6c1b1f6%1765850143.772", "date/3.0.4#862e11e80030356b53c2c38599ceb32b%1765850143.772", "c-ares/1.34.6#545240bb1c40e2cacd4362d6b8967650%1774439234.681", @@ -29,7 +29,7 @@ "build_requires": [ "zlib/1.3.1#cac0f6daea041b0ccf42934163defb20%1774439233.809", "strawberryperl/5.32.1.1#8d114504d172cfea8ea1662d09b6333e%1774447376.964", - "protobuf/6.33.5#d96d52ba5baaaa532f47bda866ad87a5%1773224203.27", + "protobuf/6.33.5#d96d52ba5baaaa532f47bda866ad87a5%1774467363.12", "nasm/2.16.01#31e26f2ee3c4346ecd347911bd126904%1765850144.707", "msys2/cci.latest#d22fe7b2808f5fd34d0a7923ace9c54f%1770657326.649", "m4/1.4.19#5d7a4994e5875d76faf7acf3ed056036%1774365463.87", @@ -41,16 +41,15 @@ ], "python_requires": [], "overrides": { - "boost/1.90.0#d5e8defe7355494953be18524a7f135b": [ - null, - "boost/1.90.0" - ], "protobuf/[>=5.27.0 <7]": [ "protobuf/6.33.5" ], "lz4/1.9.4": [ "lz4/1.10.0" ], + "boost/[>=1.83.0 <1.91.0]": [ + "boost/1.90.0" + ], "sqlite3/[>=3.44 <4]": [ "sqlite3/3.51.0" ], From bee1056faa114357efc62520c2d24a25c89f24d0 Mon Sep 17 00:00:00 2001 From: Vito Tumas <5780819+Tapanito@users.noreply.github.com> Date: Wed, 1 Apr 2026 15:35:13 +0200 Subject: [PATCH 43/53] fix: Enforce aggregate MaximumAmount in multi-send MPT (#6644) Co-authored-by: xrplf-ai-reviewer[bot] <266832837+xrplf-ai-reviewer[bot]@users.noreply.github.com> --- src/libxrpl/ledger/helpers/TokenHelpers.cpp | 72 ++++++++---- src/test/app/MPToken_test.cpp | 119 ++++++++++++++++++++ 2 files changed, 170 insertions(+), 21 deletions(-) diff --git a/src/libxrpl/ledger/helpers/TokenHelpers.cpp b/src/libxrpl/ledger/helpers/TokenHelpers.cpp index ce4ba4002a..8d2b0d5fff 100644 --- a/src/libxrpl/ledger/helpers/TokenHelpers.cpp +++ b/src/libxrpl/ledger/helpers/TokenHelpers.cpp @@ -1155,57 +1155,87 @@ rippleSendMultiMPT( beast::Journal j, WaiveTransferFee waiveFee) { - // Safe to get MPT since rippleSendMultiMPT is only called by - // accountSendMultiMPT auto const& issuer = mptIssue.getIssuer(); auto const sle = view.read(keylet::mptIssuance(mptIssue.getMptID())); if (!sle) return tecOBJECT_NOT_FOUND; - // These may diverge + // For the issuer-as-sender case, track the running total to validate + // against MaximumAmount. The read-only SLE (view.read) is not updated + // by rippleCreditMPT, so a per-iteration SLE read would be stale. + // Use uint64_t, not STAmount, to keep MaximumAmount comparisons in exact + // integer arithmetic. STAmount implicitly converts to Number, whose + // small-scale mantissa (~16 digits) can lose precision for values near + // maxMPTokenAmount (19 digits). + std::uint64_t totalSendAmount{0}; + std::uint64_t const maximumAmount = sle->at(~sfMaximumAmount).value_or(maxMPTokenAmount); + std::uint64_t const outstandingAmount = sle->getFieldU64(sfOutstandingAmount); + + // actual accumulates the total cost to the sender (includes transfer + // fees for third-party transit sends). takeFromSender accumulates only + // the transit portion that is debited to the issuer in bulk after the + // loop. They diverge when there are transfer fees. STAmount takeFromSender{mptIssue}; actual = takeFromSender; - for (auto const& r : receivers) + for (auto const& [receiverID, amt] : receivers) { - auto const& receiverID = r.first; - STAmount const amount{mptIssue, r.second}; + STAmount const amount{mptIssue, amt}; if (amount < beast::zero) - { return tecINTERNAL; // LCOV_EXCL_LINE - } - /* If we aren't sending anything or if the sender is the same as the - * receiver then we don't need to do anything. - */ - if (!amount || (senderID == receiverID)) + if (!amount || senderID == receiverID) continue; if (senderID == issuer || receiverID == issuer) { - // if sender is issuer, check that the new OutstandingAmount will - // not exceed MaximumAmount if (senderID == issuer) { XRPL_ASSERT_PARTS( takeFromSender == beast::zero, "xrpl::rippleSendMultiMPT", "sender == issuer, takeFromSender == zero"); - auto const sendAmount = amount.mpt().value(); - auto const maximumAmount = sle->at(~sfMaximumAmount).value_or(maxMPTokenAmount); - if (sendAmount > maximumAmount || - sle->getFieldU64(sfOutstandingAmount) > maximumAmount - sendAmount) - return tecPATH_DRY; + + std::uint64_t const sendAmount = amount.mpt().value(); + + if (view.rules().enabled(fixSecurity3_1_3)) + { + // Post-fixSecurity3_1_3: aggregate MaximumAmount + // check. WARNING: the order of conditions is + // critical — each guards the subtraction in the + // next against unsigned underflow. Do not reorder. + bool const exceedsMaximumAmount = + // This send alone exceeds the max cap + sendAmount > maximumAmount || + // The aggregate of all sends exceeds the max cap + totalSendAmount > maximumAmount - sendAmount || + // Outstanding + aggregate exceeds the max cap + outstandingAmount > maximumAmount - sendAmount - totalSendAmount; + + if (exceedsMaximumAmount) + return tecPATH_DRY; + totalSendAmount += sendAmount; + } + else + { + // Pre-fixSecurity3_1_3: per-iteration MaximumAmount + // check. Reads sfOutstandingAmount from a stale + // view.read() snapshot — incorrect for multi-destination + // sends but retained for ledger replay compatibility. + if (sendAmount > maximumAmount || + outstandingAmount > maximumAmount - sendAmount) + return tecPATH_DRY; + } } // Direct send: redeeming MPTs and/or sending own MPTs. if (auto const ter = rippleCreditMPT(view, senderID, receiverID, amount, j)) return ter; actual += amount; - // Do not add amount to takeFromSender, because rippleCreditMPT took - // it + // Do not add amount to takeFromSender, because rippleCreditMPT + // took it. continue; } diff --git a/src/test/app/MPToken_test.cpp b/src/test/app/MPToken_test.cpp index 6e94ffd9bc..81fcec4b7a 100644 --- a/src/test/app/MPToken_test.cpp +++ b/src/test/app/MPToken_test.cpp @@ -6,6 +6,7 @@ #include #include +#include #include #include #include @@ -3272,6 +3273,123 @@ class MPToken_test : public beast::unit_test::suite mptAlice.claw(alice, bob, 1, tecNO_PERMISSION); } + void + testMultiSendMaximumAmount(FeatureBitset features) + { + // Verify that rippleSendMultiMPT correctly enforces MaximumAmount + // when the issuer sends to multiple receivers. Pre-fixSecurity3_1_3, + // a stale view.read() snapshot caused per-iteration checks to miss + // aggregate overflows. Post-fix, a running total is used instead. + testcase("Multi-send MaximumAmount enforcement"); + + using namespace test::jtx; + + Account const issuer("issuer"); + Account const alice("alice"); + Account const bob("bob"); + + std::uint64_t constexpr maxAmt = 150; + Env env{*this, features}; + + MPTTester mptt(env, issuer, {.holders = {alice, bob}}); + mptt.create({.maxAmt = maxAmt, .ownerCount = 1, .flags = tfMPTCanTransfer}); + mptt.authorize({.account = alice}); + mptt.authorize({.account = bob}); + + Asset const asset{MPTIssue{mptt.issuanceID()}}; + + // Each test case creates a fresh ApplyView and calls + // accountSendMulti from the issuer to the given receivers. + auto const runTest = [&](MultiplePaymentDestinations const& receivers, + TER expectedTer, + std::optional expectedOutstanding, + std::string const& label) { + ApplyViewImpl av(&*env.current(), tapNONE); + auto const ter = + accountSendMulti(av, issuer.id(), asset, receivers, env.app().getJournal("View")); + BEAST_EXPECTS(ter == expectedTer, label); + + // Only verify OutstandingAmount on success — on error the + // view may contain partial state and must be discarded. + if (expectedOutstanding) + { + auto const sle = av.peek(keylet::mptIssuance(mptt.issuanceID())); + if (!BEAST_EXPECT(sle)) + return; + BEAST_EXPECTS(sle->getFieldU64(sfOutstandingAmount) == *expectedOutstanding, label); + } + }; + + using R = MultiplePaymentDestinations; + + // Post-amendment: aggregate check with running total + runTest( + R{{alice.id(), 100}, {bob.id(), 100}}, + tecPATH_DRY, + std::nullopt, + "aggregate exceeds max"); + + runTest(R{{alice.id(), 75}, {bob.id(), 75}}, tesSUCCESS, maxAmt, "aggregate at boundary"); + + runTest(R{{alice.id(), 50}, {bob.id(), 50}}, tesSUCCESS, 100, "aggregate within limit"); + + runTest( + R{{alice.id(), 150}, {bob.id(), 0}}, + tesSUCCESS, + maxAmt, + "one receiver at max, other zero"); + + runTest( + R{{alice.id(), 151}, {bob.id(), 0}}, + tecPATH_DRY, + std::nullopt, + "one receiver exceeds max, other zero"); + + // Issue 50 tokens so outstandingAmount is nonzero, then verify + // the third condition: outstandingAmount > maximumAmount - sendAmount - totalSendAmount + mptt.pay(issuer, alice, 50); + env.close(); + + // maxAmt=150, outstanding=50, so 100 more available + runTest( + R{{alice.id(), 50}, {bob.id(), 50}}, + tesSUCCESS, + maxAmt, + "nonzero outstanding, aggregate at boundary"); + + runTest( + R{{alice.id(), 50}, {bob.id(), 51}}, + tecPATH_DRY, + std::nullopt, + "nonzero outstanding, aggregate exceeds max"); + + runTest( + R{{alice.id(), 100}, {bob.id(), 0}}, + tesSUCCESS, + maxAmt, + "nonzero outstanding, single send at remaining capacity"); + + runTest( + R{{alice.id(), 101}, {bob.id(), 0}}, + tecPATH_DRY, + std::nullopt, + "nonzero outstanding, single send exceeds remaining capacity"); + + // Pre-amendment: the stale per-iteration check allows each + // individual send (100 <= 150) even though the aggregate (200) + // exceeds MaximumAmount. Preserved for ledger replay. + { + // KNOWN BUG (pre-fixSecurity3_1_3): preserved for ledger replay only + env.disableFeature(fixSecurity3_1_3); + runTest( + R{{alice.id(), 100}, {bob.id(), 100}}, + tesSUCCESS, + 250, + "pre-amendment allows over-send"); + env.enableFeature(fixSecurity3_1_3); + } + } + public: void run() override @@ -3279,6 +3397,7 @@ public: using namespace test::jtx; FeatureBitset const all{testable_amendments()}; + testMultiSendMaximumAmount(all); // MPTokenIssuanceCreate testCreateValidation(all - featureSingleAssetVault); testCreateValidation(all - featurePermissionedDomains); From ae21f53e4d7a0a2932270876f8d4d1c0e3629383 Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Wed, 1 Apr 2026 14:37:35 +0100 Subject: [PATCH 44/53] ci: Allow uploading artifacts for XRPLF org (#6702) --- .github/workflows/publish-docs.yml | 6 +++--- .github/workflows/reusable-build-test-config.yml | 2 +- .github/workflows/reusable-clang-tidy-files.yml | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/publish-docs.yml b/.github/workflows/publish-docs.yml index 7d40ff3363..637246ec40 100644 --- a/.github/workflows/publish-docs.yml +++ b/.github/workflows/publish-docs.yml @@ -36,7 +36,7 @@ env: BUILD_DIR: build # ubuntu-latest has only 2 CPUs for private repositories # https://docs.github.com/en/actions/reference/runners/github-hosted-runners#standard-github-hosted-runners-for--private-repositories - NPROC_SUBTRACT: ${{ github.event.repository.private && '1' || '2' }} + NPROC_SUBTRACT: ${{ github.event.repository.visibility == 'public' && '2' || '1' }} jobs: build: @@ -81,13 +81,13 @@ jobs: cmake --build . --target docs --parallel ${BUILD_NPROC} - name: Create documentation artifact - if: ${{ github.event.repository.visibility == 'public' && github.event_name == 'push' }} + if: ${{ (github.repository_owner == 'XRPLF' || github.event.repository.visibility == 'public') && github.event_name == 'push' }} uses: actions/upload-pages-artifact@7b1f4a764d45c48632c6b24a0339c27f5614fb0b # v4.0.0 with: path: ${{ env.BUILD_DIR }}/docs/html deploy: - if: ${{ github.event.repository.visibility == 'public' && github.event_name == 'push' }} + if: ${{ (github.repository_owner == 'XRPLF' || github.event.repository.visibility == 'public') && github.event_name == 'push' }} needs: build runs-on: ubuntu-latest permissions: diff --git a/.github/workflows/reusable-build-test-config.yml b/.github/workflows/reusable-build-test-config.yml index 27dfa2fd6a..920b5b5278 100644 --- a/.github/workflows/reusable-build-test-config.yml +++ b/.github/workflows/reusable-build-test-config.yml @@ -199,7 +199,7 @@ jobs: fi - name: Upload the binary (Linux) - if: ${{ github.event.repository.visibility == 'public' && runner.os == 'Linux' }} + if: ${{ (github.repository_owner == 'XRPLF' || github.event.repository.visibility == 'public') && runner.os == 'Linux' }} uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 with: name: xrpld-${{ inputs.config_name }} diff --git a/.github/workflows/reusable-clang-tidy-files.yml b/.github/workflows/reusable-clang-tidy-files.yml index fcbb041ed9..81264cf24e 100644 --- a/.github/workflows/reusable-clang-tidy-files.yml +++ b/.github/workflows/reusable-clang-tidy-files.yml @@ -83,7 +83,7 @@ jobs: run-clang-tidy -j ${{ steps.nproc.outputs.nproc }} -p "${BUILD_DIR}" -quiet -allow-no-checks ${TARGETS} 2>&1 | tee clang-tidy-output.txt - name: Upload clang-tidy output - if: ${{ github.event.repository.visibility == 'public' && steps.run_clang_tidy.outcome != 'success' }} + if: ${{ (github.repository_owner == 'XRPLF' || github.event.repository.visibility == 'public') && steps.run_clang_tidy.outcome != 'success' }} uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 with: name: clang-tidy-results From 29e49abd3c268e8abcebc4cfefc4a8dc7ddc47fa Mon Sep 17 00:00:00 2001 From: Alex Kremer Date: Wed, 1 Apr 2026 16:46:14 +0100 Subject: [PATCH 45/53] chore: Enable clang-tidy `coreguidelines` checks (#6698) Co-authored-by: Ayaz Salikhov --- .clang-tidy | 12 +++--- include/xrpl/basics/CountedObject.h | 2 +- include/xrpl/basics/DecayingSample.h | 4 +- include/xrpl/basics/IntrusivePointer.h | 12 ++++-- include/xrpl/basics/Number.h | 4 +- include/xrpl/basics/SlabAllocator.h | 2 +- include/xrpl/basics/TaggedCache.h | 13 +++--- include/xrpl/basics/TaggedCache.ipp | 4 +- include/xrpl/basics/base_uint.h | 4 +- include/xrpl/basics/random.h | 2 +- include/xrpl/beast/asio/io_latency_probe.h | 6 +-- .../container/detail/aged_ordered_container.h | 11 +++-- .../detail/aged_unordered_container.h | 14 +++++-- include/xrpl/beast/core/LockFreeStack.h | 4 +- include/xrpl/beast/hash/xxhasher.h | 2 +- include/xrpl/beast/unit_test/results.h | 12 +++--- include/xrpl/beast/utility/PropertyStream.h | 2 +- include/xrpl/beast/xor_shift_engine.h | 2 +- include/xrpl/core/ClosureCounter.h | 4 +- include/xrpl/core/Coro.ipp | 1 - include/xrpl/core/JobQueue.h | 6 +-- include/xrpl/core/JobTypeData.h | 14 +++---- include/xrpl/core/LoadMonitor.h | 8 ++-- include/xrpl/core/PeerReservationTable.h | 2 +- include/xrpl/core/detail/Workers.h | 8 ++-- include/xrpl/json/json_reader.h | 14 +++---- include/xrpl/json/json_writer.h | 8 ++-- include/xrpl/nodestore/Scheduler.h | 2 +- include/xrpl/nodestore/detail/BatchWriter.h | 4 +- include/xrpl/nodestore/detail/EncodedBlob.h | 5 ++- include/xrpl/nodestore/detail/codec.h | 28 ++++++------- include/xrpl/protocol/IOUAmount.h | 4 +- include/xrpl/protocol/Indexes.h | 3 +- include/xrpl/protocol/Quality.h | 4 +- include/xrpl/protocol/STAmount.h | 4 +- include/xrpl/protocol/STLedgerEntry.h | 4 +- include/xrpl/protocol/STObject.h | 9 +++-- include/xrpl/protocol/STTx.h | 3 +- include/xrpl/protocol/detail/STVar.h | 2 +- include/xrpl/protocol/detail/b58_utils.h | 4 +- include/xrpl/protocol/json_get_or_throw.h | 2 +- include/xrpl/protocol/nft.h | 8 ++-- include/xrpl/rdb/RelationalDatabase.h | 18 ++++----- include/xrpl/resource/Gossip.h | 2 +- include/xrpl/resource/detail/Entry.h | 2 +- include/xrpl/resource/detail/Import.h | 2 +- include/xrpl/server/LoadFeeTrack.h | 12 ++---- include/xrpl/server/Port.h | 4 +- include/xrpl/server/State.h | 2 +- include/xrpl/server/detail/BaseHTTPPeer.h | 4 +- include/xrpl/server/detail/Door.h | 16 ++++---- include/xrpl/server/detail/ServerImpl.h | 2 +- include/xrpl/tx/Transactor.h | 3 +- include/xrpl/tx/invariants/AMMInvariant.h | 4 +- include/xrpl/tx/paths/AMMOffer.h | 2 +- include/xrpl/tx/paths/BookTip.h | 2 +- include/xrpl/tx/paths/Offer.h | 4 +- include/xrpl/tx/paths/OfferStream.h | 4 +- include/xrpl/tx/paths/detail/AmountSpec.h | 2 +- include/xrpl/tx/paths/detail/StrandFlow.h | 4 +- .../tx/transactors/lending/LendingHelpers.h | 2 +- .../transactors/token/MPTokenIssuanceCreate.h | 2 +- .../beast/utility/beast_PropertyStream.cpp | 3 +- src/libxrpl/core/detail/JobQueue.cpp | 2 - src/libxrpl/core/detail/LoadMonitor.cpp | 6 +-- src/libxrpl/core/detail/Workers.cpp | 9 +---- src/libxrpl/json/json_writer.cpp | 5 +-- src/libxrpl/nodestore/BatchWriter.cpp | 2 +- src/libxrpl/protocol/STAmount.cpp | 2 +- src/libxrpl/tx/paths/AMMOffer.cpp | 7 +--- src/libxrpl/tx/paths/BookTip.cpp | 2 +- src/test/csf/Peer.h | 16 +++----- src/test/csf/Tx.h | 5 ++- src/test/jtx/Env_ss.h | 2 +- src/test/jtx/Oracle.h | 2 +- src/test/jtx/flags.h | 4 +- src/test/jtx/impl/Oracle.cpp | 2 +- src/test/jtx/impl/quality2.cpp | 2 + src/test/jtx/impl/xchain_bridge.cpp | 1 - src/test/jtx/quality.h | 4 +- src/test/jtx/xchain_bridge.h | 2 +- src/xrpld/app/ledger/InboundLedger.h | 12 +++--- src/xrpld/app/ledger/detail/InboundLedger.cpp | 6 --- .../app/ledger/detail/TimeoutCounter.cpp | 4 -- src/xrpld/app/ledger/detail/TimeoutCounter.h | 12 +++--- .../app/ledger/detail/TransactionAcquire.cpp | 1 - .../app/ledger/detail/TransactionAcquire.h | 2 +- src/xrpld/app/misc/TxQ.h | 16 ++++---- src/xrpld/app/misc/ValidatorList.h | 6 +-- src/xrpld/app/misc/ValidatorSite.h | 4 +- src/xrpld/app/misc/detail/TxQ.cpp | 1 - src/xrpld/app/misc/detail/ValidatorList.cpp | 2 +- src/xrpld/app/misc/detail/ValidatorSite.cpp | 3 +- src/xrpld/consensus/Consensus.h | 2 +- src/xrpld/consensus/ConsensusTypes.h | 2 +- src/xrpld/consensus/DisputedTx.h | 10 ++--- src/xrpld/consensus/LedgerTrie.h | 2 +- src/xrpld/overlay/Slot.h | 12 +++--- src/xrpld/overlay/detail/ConnectAttempt.h | 2 +- src/xrpld/overlay/detail/OverlayImpl.cpp | 1 - src/xrpld/overlay/detail/OverlayImpl.h | 5 +-- src/xrpld/overlay/detail/ProtocolMessage.h | 2 +- src/xrpld/peerfinder/PeerfinderManager.h | 14 ++++--- src/xrpld/peerfinder/detail/Bootcache.cpp | 7 +--- src/xrpld/peerfinder/detail/Bootcache.h | 2 +- src/xrpld/peerfinder/detail/Checker.h | 4 +- src/xrpld/peerfinder/detail/Counts.h | 40 +++++-------------- src/xrpld/peerfinder/detail/Fixed.h | 4 +- src/xrpld/peerfinder/detail/Livecache.h | 2 +- .../peerfinder/detail/PeerfinderConfig.cpp | 10 +---- src/xrpld/peerfinder/detail/Store.h | 2 +- src/xrpld/rpc/ServerHandler.h | 2 +- src/xrpld/rpc/Status.h | 2 +- src/xrpld/rpc/detail/LegacyPathFind.cpp | 2 +- src/xrpld/rpc/detail/LegacyPathFind.h | 2 +- src/xrpld/rpc/detail/Pathfinder.h | 6 +-- src/xrpld/rpc/handlers/LedgerEntryHelpers.h | 2 +- 117 files changed, 299 insertions(+), 343 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index 9cfc08ff5b..07274eb53a 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -78,14 +78,14 @@ Checks: "-*, bugprone-unused-return-value, bugprone-unused-local-non-trivial-variable, bugprone-virtual-near-miss, - # cppcoreguidelines-init-variables, # has issues - # cppcoreguidelines-misleading-capture-default-by-value, # has issues + cppcoreguidelines-init-variables, + cppcoreguidelines-misleading-capture-default-by-value, cppcoreguidelines-no-suspend-with-lock, - # cppcoreguidelines-pro-type-member-init, # has issues + cppcoreguidelines-pro-type-member-init, cppcoreguidelines-pro-type-static-cast-downcast, - # cppcoreguidelines-rvalue-reference-param-not-moved, # has issues - # cppcoreguidelines-use-default-member-init, # has issues - # cppcoreguidelines-virtual-class-destructor, # has issues + cppcoreguidelines-rvalue-reference-param-not-moved, + cppcoreguidelines-use-default-member-init, + cppcoreguidelines-virtual-class-destructor, hicpp-ignored-remove-result, misc-const-correctness, misc-definitions-in-headers, diff --git a/include/xrpl/basics/CountedObject.h b/include/xrpl/basics/CountedObject.h index 55a895dbb1..acf75360e1 100644 --- a/include/xrpl/basics/CountedObject.h +++ b/include/xrpl/basics/CountedObject.h @@ -34,7 +34,7 @@ public: { // Insert ourselves at the front of the lock-free linked list CountedObjects& instance = CountedObjects::getInstance(); - Counter* head; + Counter* head = nullptr; do { diff --git a/include/xrpl/basics/DecayingSample.h b/include/xrpl/basics/DecayingSample.h index a8d6a2360e..d3343535e9 100644 --- a/include/xrpl/basics/DecayingSample.h +++ b/include/xrpl/basics/DecayingSample.h @@ -93,7 +93,7 @@ class DecayWindow public: using time_point = typename Clock::time_point; - explicit DecayWindow(time_point now) : value_(0), when_(now) + explicit DecayWindow(time_point now) : when_(now) { } @@ -125,7 +125,7 @@ private: when_ = now; } - double value_; + double value_{0}; time_point when_; }; diff --git a/include/xrpl/basics/IntrusivePointer.h b/include/xrpl/basics/IntrusivePointer.h index e6261be340..f816af1c05 100644 --- a/include/xrpl/basics/IntrusivePointer.h +++ b/include/xrpl/basics/IntrusivePointer.h @@ -84,7 +84,8 @@ public: template requires std::convertible_to - SharedIntrusive(SharedIntrusive&& rhs); + SharedIntrusive( + SharedIntrusive&& rhs); // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved) SharedIntrusive& operator=(SharedIntrusive const& rhs); @@ -106,7 +107,8 @@ public: template requires std::convertible_to SharedIntrusive& - operator=(SharedIntrusive&& rhs); + operator=( + SharedIntrusive&& rhs); // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved) /** Adopt the raw pointer. The strong reference may or may not be incremented, depending on the TAdoptTag @@ -314,7 +316,8 @@ public: template requires std::convertible_to - SharedWeakUnion(SharedIntrusive&& rhs); + SharedWeakUnion( + SharedIntrusive&& rhs); // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved) SharedWeakUnion& operator=(SharedWeakUnion const& rhs); @@ -327,7 +330,8 @@ public: template requires std::convertible_to SharedWeakUnion& - operator=(SharedIntrusive&& rhs); + operator=( + SharedIntrusive&& rhs); // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved) ~SharedWeakUnion(); diff --git a/include/xrpl/basics/Number.h b/include/xrpl/basics/Number.h index e3da029c03..c39aae2dd3 100644 --- a/include/xrpl/basics/Number.h +++ b/include/xrpl/basics/Number.h @@ -73,12 +73,12 @@ struct MantissaRange enum mantissa_scale { small, large }; explicit constexpr MantissaRange(mantissa_scale scale_) - : min(getMin(scale_)), max(min * 10 - 1), log(logTen(min).value_or(-1)), scale(scale_) + : min(getMin(scale_)), log(logTen(min).value_or(-1)), scale(scale_) { } rep min; - rep max; + rep max{min * 10 - 1}; int log; mantissa_scale scale; diff --git a/include/xrpl/basics/SlabAllocator.h b/include/xrpl/basics/SlabAllocator.h index 17acbbaa87..4ed88a32f7 100644 --- a/include/xrpl/basics/SlabAllocator.h +++ b/include/xrpl/basics/SlabAllocator.h @@ -91,7 +91,7 @@ class SlabAllocator std::uint8_t* allocate() noexcept { - std::uint8_t* ret; + std::uint8_t* ret = nullptr; // NOLINT(misc-const-correctness) { std::lock_guard const l(m_); diff --git a/include/xrpl/basics/TaggedCache.h b/include/xrpl/basics/TaggedCache.h index 6cbe8680c9..1a19c653bc 100644 --- a/include/xrpl/basics/TaggedCache.h +++ b/include/xrpl/basics/TaggedCache.h @@ -182,8 +182,7 @@ private: : hook(collector->make_hook(handler)) , size(collector->make_gauge(prefix, "size")) , hit_rate(collector->make_gauge(prefix, "hit_rate")) - , hits(0) - , misses(0) + { } @@ -191,8 +190,8 @@ private: beast::insight::Gauge size; beast::insight::Gauge hit_rate; - std::size_t hits; - std::size_t misses; + std::size_t hits{0}; + std::size_t misses{0}; }; class KeyOnlyEntry @@ -294,10 +293,10 @@ private: clock_type::duration const m_target_age; // Number of items cached - int m_cache_count; + int m_cache_count{0}; cache_type m_cache; // Hold strong reference to recent objects - std::uint64_t m_hits; - std::uint64_t m_misses; + std::uint64_t m_hits{0}; + std::uint64_t m_misses{0}; }; } // namespace xrpl diff --git a/include/xrpl/basics/TaggedCache.ipp b/include/xrpl/basics/TaggedCache.ipp index 8c0fde5e7d..6879ad435d 100644 --- a/include/xrpl/basics/TaggedCache.ipp +++ b/include/xrpl/basics/TaggedCache.ipp @@ -36,9 +36,7 @@ inline TaggedCache< , m_name(name) , m_target_size(size) , m_target_age(expiration) - , m_cache_count(0) - , m_hits(0) - , m_misses(0) + { } diff --git a/include/xrpl/basics/base_uint.h b/include/xrpl/basics/base_uint.h index 4ce135c036..5fb13319ea 100644 --- a/include/xrpl/basics/base_uint.h +++ b/include/xrpl/basics/base_uint.h @@ -335,11 +335,13 @@ public: operator=(std::uint64_t uHost) { *this = beast::zero; + // NOLINTBEGIN(cppcoreguidelines-pro-type-member-init) union { unsigned u[2]; std::uint64_t ul; }; + // NOLINTEND(cppcoreguidelines-pro-type-member-init) // Put in least significant bits. ul = boost::endian::native_to_big(uHost); data_[WIDTH - 2] = u[0]; @@ -621,7 +623,7 @@ template <> inline std::size_t extract(uint256 const& key) { - std::size_t result; + std::size_t result = 0; // Use memcpy to avoid unaligned UB // (will optimize to equivalent code) std::memcpy(&result, key.data(), sizeof(std::size_t)); diff --git a/include/xrpl/basics/random.h b/include/xrpl/basics/random.h index ae3a8c6ec6..db66b303d4 100644 --- a/include/xrpl/basics/random.h +++ b/include/xrpl/basics/random.h @@ -58,7 +58,7 @@ default_prng() // The thread-specific PRNGs: thread_local beast::xor_shift_engine engine = [] { - std::uint64_t seed; + std::uint64_t seed = 0; { std::lock_guard const lk(m); std::uniform_int_distribution distribution{1}; diff --git a/include/xrpl/beast/asio/io_latency_probe.h b/include/xrpl/beast/asio/io_latency_probe.h index 0718a32af7..2dc1fcba15 100644 --- a/include/xrpl/beast/asio/io_latency_probe.h +++ b/include/xrpl/beast/asio/io_latency_probe.h @@ -23,15 +23,15 @@ private: std::recursive_mutex m_mutex; std::condition_variable_any m_cond; - std::size_t m_count; + std::size_t m_count{1}; duration const m_period; boost::asio::io_context& m_ios; boost::asio::basic_waitable_timer m_timer; - bool m_cancel; + bool m_cancel{false}; public: io_latency_probe(duration const& period, boost::asio::io_context& ios) - : m_count(1), m_period(period), m_ios(ios), m_timer(m_ios), m_cancel(false) + : m_period(period), m_ios(ios), m_timer(m_ios) { } diff --git a/include/xrpl/beast/container/detail/aged_ordered_container.h b/include/xrpl/beast/container/detail/aged_ordered_container.h index b482cd33c1..dad0d92e0b 100644 --- a/include/xrpl/beast/container/detail/aged_ordered_container.h +++ b/include/xrpl/beast/container/detail/aged_ordered_container.h @@ -262,7 +262,9 @@ private: { } - config_t(config_t&& other, Allocator const& alloc) + config_t( + config_t&& other, // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved) + Allocator const& alloc) : KeyValueCompare(std::move(other.key_compare())) , beast::detail::empty_base_optimization(alloc) , clock(other.clock) @@ -552,7 +554,10 @@ public: aged_ordered_container(aged_ordered_container&& other); - aged_ordered_container(aged_ordered_container&& other, Allocator const& alloc); + aged_ordered_container( + // NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved) + aged_ordered_container&& other, + Allocator const& alloc); aged_ordered_container(std::initializer_list init, clock_type& clock); @@ -1290,7 +1295,7 @@ aged_ordered_container::aged_ template aged_ordered_container::aged_ordered_container( - aged_ordered_container&& other, + aged_ordered_container&& other, // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved) Allocator const& alloc) : m_config(std::move(other.m_config), alloc) #if BOOST_VERSION >= 108000 diff --git a/include/xrpl/beast/container/detail/aged_unordered_container.h b/include/xrpl/beast/container/detail/aged_unordered_container.h index d912f06ce1..dfc853f019 100644 --- a/include/xrpl/beast/container/detail/aged_unordered_container.h +++ b/include/xrpl/beast/container/detail/aged_unordered_container.h @@ -318,7 +318,9 @@ private: { } - config_t(config_t&& other, Allocator const& alloc) + config_t( + config_t&& other, // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved) + Allocator const& alloc) : ValueHash(std::move(other.hash_function())) , KeyValueEqual(std::move(other.key_eq())) , beast::detail::empty_base_optimization(alloc) @@ -774,7 +776,10 @@ public: aged_unordered_container(aged_unordered_container&& other); - aged_unordered_container(aged_unordered_container&& other, Allocator const& alloc); + aged_unordered_container( + // NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved) + aged_unordered_container&& other, + Allocator const& alloc); aged_unordered_container(std::initializer_list init, clock_type& clock); @@ -1838,7 +1843,10 @@ template < class KeyEqual, class Allocator> aged_unordered_container:: - aged_unordered_container(aged_unordered_container&& other, Allocator const& alloc) + aged_unordered_container( + // NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved) + aged_unordered_container&& other, + Allocator const& alloc) : m_config(std::move(other.m_config), alloc) , m_buck(alloc) , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) diff --git a/include/xrpl/beast/core/LockFreeStack.h b/include/xrpl/beast/core/LockFreeStack.h index fe3baa0564..cf512725fe 100644 --- a/include/xrpl/beast/core/LockFreeStack.h +++ b/include/xrpl/beast/core/LockFreeStack.h @@ -187,7 +187,7 @@ public: bool push_front(Node* node) { - bool first; + bool first = false; Node* old_head = m_head.load(std::memory_order_relaxed); do { @@ -211,7 +211,7 @@ public: pop_front() { Node* node = m_head.load(); - Node* new_head; + Node* new_head = nullptr; do { if (node == &m_end) diff --git a/include/xrpl/beast/hash/xxhasher.h b/include/xrpl/beast/hash/xxhasher.h index 473907ea89..7c6ae894fc 100644 --- a/include/xrpl/beast/hash/xxhasher.h +++ b/include/xrpl/beast/hash/xxhasher.h @@ -23,7 +23,7 @@ private: // A 64-byte buffer should to be big enough for us static constexpr std::size_t INTERNAL_BUFFER_SIZE = 64; - alignas(64) std::array buffer_; + alignas(64) std::array buffer_{}; std::span readBuffer_; std::span writeBuffer_; diff --git a/include/xrpl/beast/unit_test/results.h b/include/xrpl/beast/unit_test/results.h index cbd0a71057..b8a8e2aadf 100644 --- a/include/xrpl/beast/unit_test/results.h +++ b/include/xrpl/beast/unit_test/results.h @@ -35,10 +35,10 @@ private: class tests_t : public detail::const_container> { private: - std::size_t failed_; + std::size_t failed_{0}; public: - tests_t() : failed_(0) + tests_t() { } @@ -167,12 +167,12 @@ public: class results : public detail::const_container> { private: - std::size_t m_cases; - std::size_t total_; - std::size_t failed_; + std::size_t m_cases{0}; + std::size_t total_{0}; + std::size_t failed_{0}; public: - results() : m_cases(0), total_(0), failed_(0) + results() { } diff --git a/include/xrpl/beast/utility/PropertyStream.h b/include/xrpl/beast/utility/PropertyStream.h index 3d29138a12..290730c1a2 100644 --- a/include/xrpl/beast/utility/PropertyStream.h +++ b/include/xrpl/beast/utility/PropertyStream.h @@ -311,7 +311,7 @@ private: std::string const m_name; std::recursive_mutex lock_; Item item_; - Source* parent_; + Source* parent_{nullptr}; List children_; public: diff --git a/include/xrpl/beast/xor_shift_engine.h b/include/xrpl/beast/xor_shift_engine.h index d49cb08fc0..4fbe5ec165 100644 --- a/include/xrpl/beast/xor_shift_engine.h +++ b/include/xrpl/beast/xor_shift_engine.h @@ -37,7 +37,7 @@ public: } private: - result_type s_[2]; + result_type s_[2]{}; static result_type murmurhash3(result_type x); diff --git a/include/xrpl/core/ClosureCounter.h b/include/xrpl/core/ClosureCounter.h index f0f277cc0e..b1939b2e63 100644 --- a/include/xrpl/core/ClosureCounter.h +++ b/include/xrpl/core/ClosureCounter.h @@ -92,7 +92,9 @@ private: ++counter_; } - Substitute(ClosureCounter& counter, Closure&& closure) + Substitute( + ClosureCounter& counter, + Closure&& closure) // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved) : counter_(counter), closure_(std::forward(closure)) { ++counter_; diff --git a/include/xrpl/core/Coro.ipp b/include/xrpl/core/Coro.ipp index dca9504679..38d921a658 100644 --- a/include/xrpl/core/Coro.ipp +++ b/include/xrpl/core/Coro.ipp @@ -7,7 +7,6 @@ JobQueue::Coro::Coro(Coro_create_t, JobQueue& jq, JobType type, std::string cons : jq_(jq) , type_(type) , name_(name) - , running_(false) , coro_( // Stack size of 1MB wasn't sufficient for deep calls. ASAN tests flagged the issue. Hence // increasing the size to 1.5MB. diff --git a/include/xrpl/core/JobQueue.h b/include/xrpl/core/JobQueue.h index 994e2b424c..558e55cf31 100644 --- a/include/xrpl/core/JobQueue.h +++ b/include/xrpl/core/JobQueue.h @@ -45,7 +45,7 @@ public: JobQueue& jq_; JobType type_; std::string name_; - bool running_; + bool running_{false}; std::mutex mutex_; std::mutex mutex_run_; std::condition_variable cv_; @@ -224,7 +224,7 @@ private: beast::Journal m_journal; mutable std::mutex m_mutex; - std::uint64_t m_lastJob; + std::uint64_t m_lastJob{0}; std::set m_jobSet; JobCounter jobCounter_; std::atomic_bool stopping_{false}; @@ -233,7 +233,7 @@ private: JobTypeData m_invalidJobData; // The number of jobs currently in processTask() - int m_processCount; + int m_processCount{0}; // The number of suspended coroutines int nSuspend_ = 0; diff --git a/include/xrpl/core/JobTypeData.h b/include/xrpl/core/JobTypeData.h index 32df3e88cf..c180629af7 100644 --- a/include/xrpl/core/JobTypeData.h +++ b/include/xrpl/core/JobTypeData.h @@ -19,13 +19,13 @@ public: JobTypeInfo const& info; /* The number of jobs waiting */ - int waiting; + int waiting{0}; /* The number presently running */ - int running; + int running{0}; /* And the number we deferred executing because of job limits */ - int deferred; + int deferred{0}; /* Notification callbacks */ beast::insight::Event dequeue; @@ -35,12 +35,8 @@ public: JobTypeInfo const& info_, beast::insight::Collector::ptr const& collector, Logs& logs) noexcept - : m_load(logs.journal("LoadMonitor")) - , m_collector(collector) - , info(info_) - , waiting(0) - , running(0) - , deferred(0) + : m_load(logs.journal("LoadMonitor")), m_collector(collector), info(info_) + { m_load.setTargetLatency(info.getAverageLatency(), info.getPeakLatency()); diff --git a/include/xrpl/core/LoadMonitor.h b/include/xrpl/core/LoadMonitor.h index 71fbf75d68..b8777a7056 100644 --- a/include/xrpl/core/LoadMonitor.h +++ b/include/xrpl/core/LoadMonitor.h @@ -36,10 +36,10 @@ public: { Stats(); - std::uint64_t count; + std::uint64_t count{0}; std::chrono::milliseconds latencyAvg; std::chrono::milliseconds latencyPeak; - bool isOverloaded; + bool isOverloaded{false}; }; Stats @@ -54,8 +54,8 @@ private: std::mutex mutex_; - std::uint64_t mCounts; - int mLatencyEvents; + std::uint64_t mCounts{0}; + int mLatencyEvents{0}; std::chrono::milliseconds mLatencyMSAvg; std::chrono::milliseconds mLatencyMSPeak; std::chrono::milliseconds mTargetLatencyAvg; diff --git a/include/xrpl/core/PeerReservationTable.h b/include/xrpl/core/PeerReservationTable.h index 6d861e5fbe..fc943f0807 100644 --- a/include/xrpl/core/PeerReservationTable.h +++ b/include/xrpl/core/PeerReservationTable.h @@ -92,7 +92,7 @@ public: private: beast::Journal mutable journal_; std::mutex mutable mutex_; - DatabaseCon* connection_; + DatabaseCon* connection_{}; std::unordered_set, KeyEqual> table_; }; diff --git a/include/xrpl/core/detail/Workers.h b/include/xrpl/core/detail/Workers.h index 7925d11e62..dbc93ecf81 100644 --- a/include/xrpl/core/detail/Workers.h +++ b/include/xrpl/core/detail/Workers.h @@ -183,8 +183,8 @@ private: std::thread thread_; std::mutex mutex_; std::condition_variable wakeup_; - int wakeCount_; // how many times to un-pause - bool shouldExit_; + int wakeCount_{0}; // how many times to un-pause + bool shouldExit_{false}; }; private: @@ -197,9 +197,9 @@ private: std::string m_threadNames; // The name to give each thread std::condition_variable m_cv; // signaled when all threads paused std::mutex m_mut; - bool m_allPaused; + bool m_allPaused{true}; semaphore m_semaphore; // each pending task is 1 resource - int m_numberOfThreads; // how many we want active now + int m_numberOfThreads{0}; // how many we want active now std::atomic m_activeCount; // to know when all are paused std::atomic m_pauseCount; // how many threads need to pause now std::atomic m_runningTaskCount; // how many calls to processTask() active diff --git a/include/xrpl/json/json_reader.h b/include/xrpl/json/json_reader.h index 09dac80a2f..dd1be76923 100644 --- a/include/xrpl/json/json_reader.h +++ b/include/xrpl/json/json_reader.h @@ -103,9 +103,9 @@ private: public: explicit ErrorInfo() = default; - Token token_; + Token token_{}; std::string message_; - Location extra_; + Location extra_{}; }; using Errors = std::deque; @@ -173,11 +173,11 @@ private: Nodes nodes_; Errors errors_; std::string document_; - Location begin_; - Location end_; - Location current_; - Location lastValueEnd_; - Value* lastValue_; + Location begin_{}; + Location end_{}; + Location current_{}; + Location lastValueEnd_{}; + Value* lastValue_{}; }; template diff --git a/include/xrpl/json/json_writer.h b/include/xrpl/json/json_writer.h index cc3790a7dd..e49abcd81a 100644 --- a/include/xrpl/json/json_writer.h +++ b/include/xrpl/json/json_writer.h @@ -106,8 +106,8 @@ private: ChildValues childValues_; std::string document_; std::string indentString_; - int rightMargin_; - int indentSize_; + int rightMargin_{74}; + int indentSize_{3}; bool addChildValues_{}; }; @@ -171,9 +171,9 @@ private: using ChildValues = std::vector; ChildValues childValues_; - std::ostream* document_; + std::ostream* document_{nullptr}; std::string indentString_; - int rightMargin_; + int rightMargin_{74}; std::string indentation_; bool addChildValues_{}; }; diff --git a/include/xrpl/nodestore/Scheduler.h b/include/xrpl/nodestore/Scheduler.h index 6e01533930..dc3e1e3d15 100644 --- a/include/xrpl/nodestore/Scheduler.h +++ b/include/xrpl/nodestore/Scheduler.h @@ -16,7 +16,7 @@ struct FetchReport { } - std::chrono::milliseconds elapsed; + std::chrono::milliseconds elapsed{}; FetchType const fetchType; bool wasFound = false; }; diff --git a/include/xrpl/nodestore/detail/BatchWriter.h b/include/xrpl/nodestore/detail/BatchWriter.h index 1820435133..93993d1c3e 100644 --- a/include/xrpl/nodestore/detail/BatchWriter.h +++ b/include/xrpl/nodestore/detail/BatchWriter.h @@ -71,8 +71,8 @@ private: Scheduler& m_scheduler; LockType mWriteMutex; CondvarType mWriteCondition; - int mWriteLoad; - bool mWritePending; + int mWriteLoad{0}; + bool mWritePending{false}; Batch mWriteSet; }; diff --git a/include/xrpl/nodestore/detail/EncodedBlob.h b/include/xrpl/nodestore/detail/EncodedBlob.h index 78e7153f73..b05583475e 100644 --- a/include/xrpl/nodestore/detail/EncodedBlob.h +++ b/include/xrpl/nodestore/detail/EncodedBlob.h @@ -35,7 +35,7 @@ namespace NodeStore { class EncodedBlob { /** The 32-byte key of the serialized object. */ - std::array key_; + std::array key_{}; /** A pre-allocated buffer for the serialized object. @@ -43,7 +43,8 @@ class EncodedBlob 1024 more bytes. The precise size is calculated automatically at compile time so as to avoid wasting space on padding bytes. */ - std::array payload_; + std::array + payload_{}; /** The size of the serialized data. */ std::uint32_t size_; diff --git a/include/xrpl/nodestore/detail/codec.h b/include/xrpl/nodestore/detail/codec.h index 8a337ca4c3..4e12c6b4db 100644 --- a/include/xrpl/nodestore/detail/codec.h +++ b/include/xrpl/nodestore/detail/codec.h @@ -56,7 +56,7 @@ lz4_compress(void const* in, std::size_t in_size, BufferFactory&& bf) using std::runtime_error; using namespace nudb::detail; std::pair result; - std::array::max> vi; + std::array::max> vi{}; auto const n = write_varint(vi.data(), in_size); auto const out_max = LZ4_compressBound(in_size); std::uint8_t* out = reinterpret_cast(bf(n + out_max)); @@ -88,7 +88,7 @@ nodeobject_decompress(void const* in, std::size_t in_size, BufferFactory&& bf) using namespace nudb::detail; std::uint8_t const* p = reinterpret_cast(in); - std::size_t type; + std::size_t type = 0; auto const vn = read_varint(p, in_size, type); if (vn == 0) Throw("nodeobject decompress"); @@ -117,7 +117,7 @@ nodeobject_decompress(void const* in, std::size_t in_size, BufferFactory&& bf) "nodeobject codec v1: short inner node size: " + std::string("in_size = ") + std::to_string(in_size) + " hs = " + std::to_string(hs)); istream is(p, in_size); - std::uint16_t mask; + std::uint16_t mask = 0; read(is, mask); // Mask in_size -= hs; result.second = 525; @@ -196,10 +196,10 @@ nodeobject_compress(void const* in, std::size_t in_size, BufferFactory&& bf) if (in_size == 525) { istream is(in, in_size); - std::uint32_t index; - std::uint32_t unused; - std::uint8_t kind; - std::uint32_t prefix; + std::uint32_t index = 0; + std::uint32_t unused = 0; + std::uint8_t kind = 0; + std::uint32_t prefix = 0; read(is, index); read(is, unused); read(is, kind); @@ -208,7 +208,7 @@ nodeobject_compress(void const* in, std::size_t in_size, BufferFactory&& bf) { std::size_t n = 0; std::uint16_t mask = 0; - std::array vh; + std::array vh{}; for (unsigned bit = 0x8000; bit; bit >>= 1) { void const* const h = is(32); @@ -247,7 +247,7 @@ nodeobject_compress(void const* in, std::size_t in_size, BufferFactory&& bf) } } - std::array::max> vi; + std::array::max> vi{}; constexpr std::size_t codecType = 1; auto const vn = write_varint(vi.data(), codecType); @@ -257,7 +257,7 @@ nodeobject_compress(void const* in, std::size_t in_size, BufferFactory&& bf) // case 0 was uncompressed data; we always compress now. case 1: // lz4 { - std::uint8_t* p; + std::uint8_t* p = nullptr; auto const lzr = NodeStore::lz4_compress(in, in_size, [&p, &vn, &bf](std::size_t n) { p = reinterpret_cast(bf(vn + n)); return p + vn; @@ -287,10 +287,10 @@ filter_inner(void* in, std::size_t in_size) if (in_size == 525) { istream is(in, in_size); - std::uint32_t index; - std::uint32_t unused; - std::uint8_t kind; - std::uint32_t prefix; + std::uint32_t index = 0; + std::uint32_t unused = 0; + std::uint8_t kind = 0; + std::uint32_t prefix = 0; read(is, index); read(is, unused); read(is, kind); diff --git a/include/xrpl/protocol/IOUAmount.h b/include/xrpl/protocol/IOUAmount.h index 2ee453f575..47aa35e0e8 100644 --- a/include/xrpl/protocol/IOUAmount.h +++ b/include/xrpl/protocol/IOUAmount.h @@ -26,8 +26,8 @@ class IOUAmount : private boost::totally_ordered, private boost::addi private: using mantissa_type = std::int64_t; using exponent_type = int; - mantissa_type mantissa_; - exponent_type exponent_; + mantissa_type mantissa_{}; + exponent_type exponent_{}; /** Adjusts the mantissa and exponent to the proper range. diff --git a/include/xrpl/protocol/Indexes.h b/include/xrpl/protocol/Indexes.h index 7884905d9e..574bbfbde6 100644 --- a/include/xrpl/protocol/Indexes.h +++ b/include/xrpl/protocol/Indexes.h @@ -363,11 +363,12 @@ uint256 getTicketIndex(AccountID const& account, SeqProxy ticketSeq); template +// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) struct keyletDesc { std::function function; Json::StaticString expectedLEName; - bool includeInTests; + bool includeInTests{}; }; // This list should include all of the keylet functions that take a single diff --git a/include/xrpl/protocol/Quality.h b/include/xrpl/protocol/Quality.h index 0ec797da0c..e9451d44ed 100644 --- a/include/xrpl/protocol/Quality.h +++ b/include/xrpl/protocol/Quality.h @@ -56,8 +56,8 @@ struct TAmounts return *this; } - In in; - Out out; + In in{}; + Out out{}; }; using Amounts = TAmounts; diff --git a/include/xrpl/protocol/STAmount.h b/include/xrpl/protocol/STAmount.h index 9cd7221d1e..df26f99b75 100644 --- a/include/xrpl/protocol/STAmount.h +++ b/include/xrpl/protocol/STAmount.h @@ -35,9 +35,9 @@ public: private: Asset mAsset; - mantissa_type mValue; + mantissa_type mValue{}; exponent_type mOffset; - bool mIsNegative; + bool mIsNegative{}; public: using value_type = STAmount; diff --git a/include/xrpl/protocol/STLedgerEntry.h b/include/xrpl/protocol/STLedgerEntry.h index 994a616210..a28868cd7a 100644 --- a/include/xrpl/protocol/STLedgerEntry.h +++ b/include/xrpl/protocol/STLedgerEntry.h @@ -86,7 +86,9 @@ inline STLedgerEntry::STLedgerEntry(LedgerEntryType type, uint256 const& key) { } -inline STLedgerEntry::STLedgerEntry(SerialIter&& sit, uint256 const& index) +inline STLedgerEntry::STLedgerEntry( + SerialIter&& sit, // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved) + uint256 const& index) : STLedgerEntry(sit, index) { } diff --git a/include/xrpl/protocol/STObject.h b/include/xrpl/protocol/STObject.h index 3a7d3f4b16..61a1cce05e 100644 --- a/include/xrpl/protocol/STObject.h +++ b/include/xrpl/protocol/STObject.h @@ -671,7 +671,7 @@ public: OptionalProxy& operator=(std::nullopt_t const&); OptionalProxy& - operator=(optional_type&& v); + operator=(optional_type&& v); // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved) OptionalProxy& operator=(optional_type const& v); @@ -766,7 +766,7 @@ STObject::Proxy::assign(U&& u) st_->makeFieldAbsent(*f_); return; } - T* t; + T* t = nullptr; if (style_ == soeINVALID) t = dynamic_cast(st_->getPField(*f_, true)); else @@ -851,7 +851,9 @@ STObject::OptionalProxy::operator=(std::nullopt_t const&) -> OptionalProxy& template auto -STObject::OptionalProxy::operator=(optional_type&& v) -> OptionalProxy& +STObject::OptionalProxy::operator=( + optional_type&& v) // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved) + -> OptionalProxy& { if (v) this->assign(std::move(*v)); @@ -930,6 +932,7 @@ STObject::Transform::operator()(detail::STVar const& e) const //------------------------------------------------------------------------------ +// NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved) inline STObject::STObject(SerialIter&& sit, SField const& name) : STObject(sit, name) { } diff --git a/include/xrpl/protocol/STTx.h b/include/xrpl/protocol/STTx.h index f200c19eac..b27d9e0637 100644 --- a/include/xrpl/protocol/STTx.h +++ b/include/xrpl/protocol/STTx.h @@ -179,7 +179,8 @@ sterilize(STTx const& stx); bool isPseudoTx(STObject const& tx); -inline STTx::STTx(SerialIter&& sit) : STTx(sit) +inline STTx::STTx(SerialIter&& sit) // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved) + : STTx(sit) { } diff --git a/include/xrpl/protocol/detail/STVar.h b/include/xrpl/protocol/detail/STVar.h index aaf9696571..1131437850 100644 --- a/include/xrpl/protocol/detail/STVar.h +++ b/include/xrpl/protocol/detail/STVar.h @@ -50,7 +50,7 @@ public: STVar& operator=(STVar&& rhs); - STVar(STBase&& t) + STVar(STBase&& t) // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved) { p_ = t.move(max_size, &d_); } diff --git a/include/xrpl/protocol/detail/b58_utils.h b/include/xrpl/protocol/detail/b58_utils.h index adb889ee53..5ad12d56e3 100644 --- a/include/xrpl/protocol/detail/b58_utils.h +++ b/include/xrpl/protocol/detail/b58_utils.h @@ -59,7 +59,7 @@ inplace_bigint_add(std::span a, std::uint64_t b) return TokenCodecErrc::inputTooSmall; } - std::uint64_t carry; + std::uint64_t carry = 0; std::tie(a[0], carry) = carrying_add(a[0], b); for (auto& v : a.subspan(1)) @@ -162,7 +162,7 @@ b58_10_to_b58_be(std::uint64_t input) int i = 0; while (input > 0) { - std::uint64_t rem; + std::uint64_t rem = 0; std::tie(input, rem) = div_rem(input, 58); result[resultSize - 1 - i] = rem; i += 1; diff --git a/include/xrpl/protocol/json_get_or_throw.h b/include/xrpl/protocol/json_get_or_throw.h index 336d875450..4406d9ff24 100644 --- a/include/xrpl/protocol/json_get_or_throw.h +++ b/include/xrpl/protocol/json_get_or_throw.h @@ -112,7 +112,7 @@ getOrThrow(Json::Value const& v, xrpl::SField const& field) { auto const s = inner.asString(); // parse as hex - std::uint64_t val; + std::uint64_t val = 0; auto [p, ec] = std::from_chars(s.data(), s.data() + s.size(), val, 16); diff --git a/include/xrpl/protocol/nft.h b/include/xrpl/protocol/nft.h index 4be58c381c..821d146ff7 100644 --- a/include/xrpl/protocol/nft.h +++ b/include/xrpl/protocol/nft.h @@ -39,7 +39,7 @@ constexpr std::uint16_t const flagMutable = 0x0010; inline std::uint16_t getFlags(uint256 const& id) { - std::uint16_t flags; + std::uint16_t flags = 0; memcpy(&flags, id.begin(), 2); return boost::endian::big_to_native(flags); } @@ -47,7 +47,7 @@ getFlags(uint256 const& id) inline std::uint16_t getTransferFee(uint256 const& id) { - std::uint16_t fee; + std::uint16_t fee = 0; memcpy(&fee, id.begin() + 2, 2); return boost::endian::big_to_native(fee); } @@ -55,7 +55,7 @@ getTransferFee(uint256 const& id) inline std::uint32_t getSerial(uint256 const& id) { - std::uint32_t seq; + std::uint32_t seq = 0; memcpy(&seq, id.begin() + 28, 4); return boost::endian::big_to_native(seq); } @@ -87,7 +87,7 @@ cipheredTaxon(std::uint32_t tokenSeq, Taxon taxon) inline Taxon getTaxon(uint256 const& id) { - std::uint32_t taxon; + std::uint32_t taxon = 0; memcpy(&taxon, id.begin() + 24, 4); taxon = boost::endian::big_to_native(taxon); diff --git a/include/xrpl/rdb/RelationalDatabase.h b/include/xrpl/rdb/RelationalDatabase.h index 56c20e4263..1c28ddec0a 100644 --- a/include/xrpl/rdb/RelationalDatabase.h +++ b/include/xrpl/rdb/RelationalDatabase.h @@ -51,19 +51,19 @@ public: AccountID const& account; /// Ledger sequence range to search. A value of 0 for min or max /// means unbounded in that direction (no constraint applied). - LedgerRange ledgerRange; - std::uint32_t offset; - std::uint32_t limit; - bool bUnlimited; + LedgerRange ledgerRange{}; + std::uint32_t offset = 0; + std::uint32_t limit = 0; + bool bUnlimited{}; }; struct AccountTxPageOptions { AccountID const& account; - LedgerRange ledgerRange; + LedgerRange ledgerRange{}; std::optional marker; - std::uint32_t limit; - bool bAdmin; + std::uint32_t limit = 0; + bool bAdmin = false; }; using AccountTx = std::pair, std::shared_ptr>; @@ -88,8 +88,8 @@ public: struct AccountTxResult { std::variant transactions; - LedgerRange ledgerRange; - uint32_t limit; + LedgerRange ledgerRange{}; + uint32_t limit = 0; std::optional marker; }; diff --git a/include/xrpl/resource/Gossip.h b/include/xrpl/resource/Gossip.h index e581145149..9a70309cc4 100644 --- a/include/xrpl/resource/Gossip.h +++ b/include/xrpl/resource/Gossip.h @@ -17,7 +17,7 @@ struct Gossip { explicit Item() = default; - int balance; + int balance{}; beast::IP::Endpoint address; }; diff --git a/include/xrpl/resource/detail/Entry.h b/include/xrpl/resource/detail/Entry.h index ecff8828af..2a6414778c 100644 --- a/include/xrpl/resource/detail/Entry.h +++ b/include/xrpl/resource/detail/Entry.h @@ -62,7 +62,7 @@ struct Entry : public beast::List::Node std::optional publicKey; // Back pointer to the map key (bit of a hack here) - Key const* key; + Key const* key{}; // Number of Consumer references int refcount; diff --git a/include/xrpl/resource/detail/Import.h b/include/xrpl/resource/detail/Import.h index 790fc0596a..bee90afbf0 100644 --- a/include/xrpl/resource/detail/Import.h +++ b/include/xrpl/resource/detail/Import.h @@ -13,7 +13,7 @@ struct Import { explicit Item() = default; - int balance; + int balance{}; Consumer consumer; }; diff --git a/include/xrpl/server/LoadFeeTrack.h b/include/xrpl/server/LoadFeeTrack.h index 08be3e0406..226408dbde 100644 --- a/include/xrpl/server/LoadFeeTrack.h +++ b/include/xrpl/server/LoadFeeTrack.h @@ -26,10 +26,6 @@ class LoadFeeTrack final public: explicit LoadFeeTrack(beast::Journal journal = beast::Journal(beast::Journal::getNullSink())) : j_(journal) - , localTxnLoadFee_(lftNormalFee) - , remoteTxnLoadFee_(lftNormalFee) - , clusterTxnLoadFee_(lftNormalFee) - , raiseCount_(0) { } @@ -124,10 +120,10 @@ private: beast::Journal const j_; std::mutex mutable lock_; - std::uint32_t localTxnLoadFee_; // Scale factor, lftNormalFee = normal fee - std::uint32_t remoteTxnLoadFee_; // Scale factor, lftNormalFee = normal fee - std::uint32_t clusterTxnLoadFee_; // Scale factor, lftNormalFee = normal fee - std::uint32_t raiseCount_; + std::uint32_t localTxnLoadFee_{lftNormalFee}; // Scale factor, lftNormalFee = normal fee + std::uint32_t remoteTxnLoadFee_{lftNormalFee}; // Scale factor, lftNormalFee = normal fee + std::uint32_t clusterTxnLoadFee_{lftNormalFee}; // Scale factor, lftNormalFee = normal fee + std::uint32_t raiseCount_{0}; }; //------------------------------------------------------------------------------ diff --git a/include/xrpl/server/Port.h b/include/xrpl/server/Port.h index b00f4f4041..c7acabbc85 100644 --- a/include/xrpl/server/Port.h +++ b/include/xrpl/server/Port.h @@ -54,7 +54,7 @@ struct Port int limit = 0; // Websocket disconnects if send queue exceeds this limit - std::uint16_t ws_queue_limit; + std::uint16_t ws_queue_limit{}; // Returns `true` if any websocket protocols are specified bool @@ -90,7 +90,7 @@ struct ParsedPort std::string ssl_ciphers; boost::beast::websocket::permessage_deflate pmd_options; int limit = 0; - std::uint16_t ws_queue_limit; + std::uint16_t ws_queue_limit{}; std::optional ip; std::optional port; diff --git a/include/xrpl/server/State.h b/include/xrpl/server/State.h index 48e11869f4..c3cc4f609c 100644 --- a/include/xrpl/server/State.h +++ b/include/xrpl/server/State.h @@ -12,7 +12,7 @@ struct SavedState { std::string writableDb; std::string archiveDb; - LedgerIndex lastRotated; + LedgerIndex lastRotated{}; }; /** diff --git a/include/xrpl/server/detail/BaseHTTPPeer.h b/include/xrpl/server/detail/BaseHTTPPeer.h index 8354e63c64..878f6a1ddf 100644 --- a/include/xrpl/server/detail/BaseHTTPPeer.h +++ b/include/xrpl/server/detail/BaseHTTPPeer.h @@ -48,14 +48,14 @@ protected: struct buffer { - buffer(void const* ptr, std::size_t len) : data(new char[len]), bytes(len), used(0) + buffer(void const* ptr, std::size_t len) : data(new char[len]), bytes(len) { memcpy(data.get(), ptr, len); } std::unique_ptr data; std::size_t bytes; - std::size_t used; + std::size_t used{0}; }; Port const& port_; diff --git a/include/xrpl/server/detail/Door.h b/include/xrpl/server/detail/Door.h index f977dc6002..87baad42db 100644 --- a/include/xrpl/server/detail/Door.h +++ b/include/xrpl/server/detail/Door.h @@ -88,8 +88,12 @@ private: boost::asio::io_context& ioc_; acceptor_type acceptor_; boost::asio::strand strand_; - bool ssl_; - bool plain_; + bool ssl_{ + port_.protocol.count("https") > 0 || port_.protocol.count("wss") > 0 || + port_.protocol.count("wss2") > 0 || port_.protocol.count("peer") > 0}; + bool plain_{ + port_.protocol.count("http") > 0 || port_.protocol.count("ws") > 0 || + port_.protocol.count("ws2")}; static constexpr std::chrono::milliseconds INITIAL_ACCEPT_DELAY{50}; static constexpr std::chrono::milliseconds MAX_ACCEPT_DELAY{2000}; std::chrono::milliseconds accept_delay_{INITIAL_ACCEPT_DELAY}; @@ -274,12 +278,6 @@ Door::Door( , ioc_(io_context) , acceptor_(io_context) , strand_(boost::asio::make_strand(io_context)) - , ssl_( - port_.protocol.count("https") > 0 || port_.protocol.count("wss") > 0 || - port_.protocol.count("wss2") > 0 || port_.protocol.count("peer") > 0) - , plain_( - port_.protocol.count("http") > 0 || port_.protocol.count("ws") > 0 || - port_.protocol.count("ws2")) , backoff_timer_(io_context) { reOpen(); @@ -397,7 +395,7 @@ Door::query_fd_stats() const return std::nullopt; #else FDStats s; - struct rlimit rl; + struct rlimit rl{}; if (getrlimit(RLIMIT_NOFILE, &rl) != 0 || rl.rlim_cur == RLIM_INFINITY) return std::nullopt; s.limit = static_cast(rl.rlim_cur); diff --git a/include/xrpl/server/detail/ServerImpl.h b/include/xrpl/server/detail/ServerImpl.h index 1f91413521..0b5d075d87 100644 --- a/include/xrpl/server/detail/ServerImpl.h +++ b/include/xrpl/server/detail/ServerImpl.h @@ -74,7 +74,7 @@ private: std::vector ports_; std::vector>> list_; int high_ = 0; - std::array hist_; + std::array hist_{}; io_list ios_; diff --git a/include/xrpl/tx/Transactor.h b/include/xrpl/tx/Transactor.h index e9d3159919..287f785cd7 100644 --- a/include/xrpl/tx/Transactor.h +++ b/include/xrpl/tx/Transactor.h @@ -116,12 +116,13 @@ protected: AccountID const account_; XRPAmount preFeeBalance_{}; // Balance before fees. - virtual ~Transactor() = default; Transactor(Transactor const&) = delete; Transactor& operator=(Transactor const&) = delete; public: + virtual ~Transactor() = default; + enum ConsequencesFactoryType { Normal, Blocker, Custom }; /** Process the transaction. */ ApplyResult diff --git a/include/xrpl/tx/invariants/AMMInvariant.h b/include/xrpl/tx/invariants/AMMInvariant.h index 63ebb804ae..e872c61f76 100644 --- a/include/xrpl/tx/invariants/AMMInvariant.h +++ b/include/xrpl/tx/invariants/AMMInvariant.h @@ -15,12 +15,12 @@ class ValidAMM std::optional ammAccount_; std::optional lptAMMBalanceAfter_; std::optional lptAMMBalanceBefore_; - bool ammPoolChanged_; + bool ammPoolChanged_{false}; public: enum class ZeroAllowed : bool { No = false, Yes = true }; - ValidAMM() : ammPoolChanged_{false} + ValidAMM() { } void diff --git a/include/xrpl/tx/paths/AMMOffer.h b/include/xrpl/tx/paths/AMMOffer.h index aa6132dfce..4ef1b2048b 100644 --- a/include/xrpl/tx/paths/AMMOffer.h +++ b/include/xrpl/tx/paths/AMMOffer.h @@ -37,7 +37,7 @@ private: // else the amounts quality Quality const quality_; // AMM offer can be consumed once at a given iteration - bool consumed_; + bool consumed_{false}; public: AMMOffer( diff --git a/include/xrpl/tx/paths/BookTip.h b/include/xrpl/tx/paths/BookTip.h index 98036a86eb..6a1805e83a 100644 --- a/include/xrpl/tx/paths/BookTip.h +++ b/include/xrpl/tx/paths/BookTip.h @@ -16,7 +16,7 @@ class BookTip { private: ApplyView& view_; - bool m_valid; + bool m_valid{false}; uint256 m_book; uint256 m_end; uint256 m_dir; diff --git a/include/xrpl/tx/paths/Offer.h b/include/xrpl/tx/paths/Offer.h index 4b161c5f2d..de3eed933a 100644 --- a/include/xrpl/tx/paths/Offer.h +++ b/include/xrpl/tx/paths/Offer.h @@ -32,10 +32,10 @@ class TOffer : private TOfferBase { private: SLE::pointer m_entry; - Quality m_quality; + Quality m_quality{}; AccountID m_account; - TAmounts m_amounts; + TAmounts m_amounts{}; void setFieldAmounts(); diff --git a/include/xrpl/tx/paths/OfferStream.h b/include/xrpl/tx/paths/OfferStream.h index df96a1b6da..ba553360ef 100644 --- a/include/xrpl/tx/paths/OfferStream.h +++ b/include/xrpl/tx/paths/OfferStream.h @@ -19,11 +19,11 @@ public: { private: std::uint32_t const limit_; - std::uint32_t count_; + std::uint32_t count_{0}; beast::Journal j_; public: - StepCounter(std::uint32_t limit, beast::Journal j) : limit_(limit), count_(0), j_(j) + StepCounter(std::uint32_t limit, beast::Journal j) : limit_(limit), j_(j) { } diff --git a/include/xrpl/tx/paths/detail/AmountSpec.h b/include/xrpl/tx/paths/detail/AmountSpec.h index 690e67ae22..1adee6a0a3 100644 --- a/include/xrpl/tx/paths/detail/AmountSpec.h +++ b/include/xrpl/tx/paths/detail/AmountSpec.h @@ -12,7 +12,7 @@ struct AmountSpec { explicit AmountSpec() = default; - bool native; + bool native{}; union { XRPAmount xrp; diff --git a/include/xrpl/tx/paths/detail/StrandFlow.h b/include/xrpl/tx/paths/detail/StrandFlow.h index a67542269e..fba631c695 100644 --- a/include/xrpl/tx/paths/detail/StrandFlow.h +++ b/include/xrpl/tx/paths/detail/StrandFlow.h @@ -27,7 +27,7 @@ namespace xrpl { template struct StrandResult { - bool success; ///< Strand succeeded + bool success = false; ///< Strand succeeded TInAmt in = beast::zero; ///< Currency amount in TOutAmt out = beast::zero; ///< Currency amount out std::optional sandbox; ///< Resulting Sandbox state @@ -61,7 +61,7 @@ struct StrandResult } StrandResult(Strand const& strand, boost::container::flat_set ofrsToRm_) - : success(false), ofrsToRm(std::move(ofrsToRm_)), ofrsUsed(offersUsed(strand)) + : ofrsToRm(std::move(ofrsToRm_)), ofrsUsed(offersUsed(strand)) { } }; diff --git a/include/xrpl/tx/transactors/lending/LendingHelpers.h b/include/xrpl/tx/transactors/lending/LendingHelpers.h index 4057c9c173..897ca3995b 100644 --- a/include/xrpl/tx/transactors/lending/LendingHelpers.h +++ b/include/xrpl/tx/transactors/lending/LendingHelpers.h @@ -143,7 +143,7 @@ struct LoanProperties // - A minimum scale required to represent the periodic payment accurately // All loan state values (principal, interest, fees) are rounded to this // scale. - std::int32_t loanScale; + std::int32_t loanScale{}; // The principal portion of the first payment. Number firstPaymentPrincipal; diff --git a/include/xrpl/tx/transactors/token/MPTokenIssuanceCreate.h b/include/xrpl/tx/transactors/token/MPTokenIssuanceCreate.h index 0ebde22a37..5ef12df282 100644 --- a/include/xrpl/tx/transactors/token/MPTokenIssuanceCreate.h +++ b/include/xrpl/tx/transactors/token/MPTokenIssuanceCreate.h @@ -10,7 +10,7 @@ struct MPTCreateArgs { std::optional priorBalance; AccountID const& account; - std::uint32_t sequence; + std::uint32_t sequence = 0; std::uint32_t flags = 0; std::optional maxAmount{}; std::optional assetScale{}; diff --git a/src/libxrpl/beast/utility/beast_PropertyStream.cpp b/src/libxrpl/beast/utility/beast_PropertyStream.cpp index 9cf4f23065..662d763ce0 100644 --- a/src/libxrpl/beast/utility/beast_PropertyStream.cpp +++ b/src/libxrpl/beast/utility/beast_PropertyStream.cpp @@ -151,8 +151,7 @@ PropertyStream::Set::stream() const // //------------------------------------------------------------------------------ -PropertyStream::Source::Source(std::string const& name) - : m_name(name), item_(this), parent_(nullptr) +PropertyStream::Source::Source(std::string const& name) : m_name(name), item_(this) { } diff --git a/src/libxrpl/core/detail/JobQueue.cpp b/src/libxrpl/core/detail/JobQueue.cpp index 434ab146bd..ddfc42c97e 100644 --- a/src/libxrpl/core/detail/JobQueue.cpp +++ b/src/libxrpl/core/detail/JobQueue.cpp @@ -13,9 +13,7 @@ JobQueue::JobQueue( Logs& logs, perf::PerfLog& perfLog) : m_journal(journal) - , m_lastJob(0) , m_invalidJobData(JobTypes::instance().getInvalid(), collector, logs) - , m_processCount(0) , m_workers(*this, &perfLog, "JobQueue", threadCount) , perfLog_(perfLog) , m_collector(collector) diff --git a/src/libxrpl/core/detail/LoadMonitor.cpp b/src/libxrpl/core/detail/LoadMonitor.cpp index 967947ee17..e613717ed8 100644 --- a/src/libxrpl/core/detail/LoadMonitor.cpp +++ b/src/libxrpl/core/detail/LoadMonitor.cpp @@ -15,16 +15,14 @@ TODO //------------------------------------------------------------------------------ -LoadMonitor::Stats::Stats() : count(0), latencyAvg(0), latencyPeak(0), isOverloaded(false) +LoadMonitor::Stats::Stats() : latencyAvg(0), latencyPeak(0) { } //------------------------------------------------------------------------------ LoadMonitor::LoadMonitor(beast::Journal j) - : mCounts(0) - , mLatencyEvents(0) - , mLatencyMSAvg(0) + : mLatencyMSAvg(0) , mLatencyMSPeak(0) , mTargetLatencyAvg(0) , mTargetLatencyPk(0) diff --git a/src/libxrpl/core/detail/Workers.cpp b/src/libxrpl/core/detail/Workers.cpp index a654d20280..ed9d09d1e8 100644 --- a/src/libxrpl/core/detail/Workers.cpp +++ b/src/libxrpl/core/detail/Workers.cpp @@ -12,9 +12,7 @@ Workers::Workers( : m_callback(callback) , perfLog_(perfLog) , m_threadNames(threadNames) - , m_allPaused(true) , m_semaphore(0) - , m_numberOfThreads(0) , m_activeCount(0) , m_pauseCount(0) , m_runningTaskCount(0) @@ -138,11 +136,8 @@ Workers::deleteWorkers(beast::LockFreeStack& stack) //------------------------------------------------------------------------------ Workers::Worker::Worker(Workers& workers, std::string const& threadName, int const instance) - : m_workers{workers} - , threadName_{threadName} - , instance_{instance} - , wakeCount_{0} - , shouldExit_{false} + : m_workers{workers}, threadName_{threadName}, instance_{instance} + { thread_ = std::thread{&Workers::Worker::run, this}; } diff --git a/src/libxrpl/json/json_writer.cpp b/src/libxrpl/json/json_writer.cpp index 2d0fc1c288..150a7fe2e5 100644 --- a/src/libxrpl/json/json_writer.cpp +++ b/src/libxrpl/json/json_writer.cpp @@ -252,7 +252,7 @@ FastWriter::writeValue(Value const& value) // Class StyledWriter // ////////////////////////////////////////////////////////////////// -StyledWriter::StyledWriter() : rightMargin_(74), indentSize_(3) +StyledWriter::StyledWriter() { } @@ -486,8 +486,7 @@ StyledWriter::unindent() // Class StyledStreamWriter // ////////////////////////////////////////////////////////////////// -StyledStreamWriter::StyledStreamWriter(std::string indentation) - : document_(nullptr), rightMargin_(74), indentation_(indentation) +StyledStreamWriter::StyledStreamWriter(std::string indentation) : indentation_(indentation) { } diff --git a/src/libxrpl/nodestore/BatchWriter.cpp b/src/libxrpl/nodestore/BatchWriter.cpp index 50f4486f59..75b9a8dcde 100644 --- a/src/libxrpl/nodestore/BatchWriter.cpp +++ b/src/libxrpl/nodestore/BatchWriter.cpp @@ -4,7 +4,7 @@ namespace xrpl { namespace NodeStore { BatchWriter::BatchWriter(Callback& callback, Scheduler& scheduler) - : m_callback(callback), m_scheduler(scheduler), mWriteLoad(0), mWritePending(false) + : m_callback(callback), m_scheduler(scheduler) { mWriteSet.reserve(batchWritePreallocationSize); } diff --git a/src/libxrpl/protocol/STAmount.cpp b/src/libxrpl/protocol/STAmount.cpp index 0a0da2193e..cc935cff61 100644 --- a/src/libxrpl/protocol/STAmount.cpp +++ b/src/libxrpl/protocol/STAmount.cpp @@ -181,7 +181,7 @@ STAmount::STAmount(SerialIter& sit, SField const& name) : STBase(name) } STAmount::STAmount(SField const& name, std::int64_t mantissa) - : STBase(name), mAsset(xrpIssue()), mValue(0), mOffset(0), mIsNegative(false) + : STBase(name), mAsset(xrpIssue()), mOffset(0) { set(mantissa); } diff --git a/src/libxrpl/tx/paths/AMMOffer.cpp b/src/libxrpl/tx/paths/AMMOffer.cpp index 2168d80094..79071850c2 100644 --- a/src/libxrpl/tx/paths/AMMOffer.cpp +++ b/src/libxrpl/tx/paths/AMMOffer.cpp @@ -10,11 +10,8 @@ AMMOffer::AMMOffer( TAmounts const& amounts, TAmounts const& balances, Quality const& quality) - : ammLiquidity_(ammLiquidity) - , amounts_(amounts) - , balances_(balances) - , quality_(quality) - , consumed_(false) + : ammLiquidity_(ammLiquidity), amounts_(amounts), balances_(balances), quality_(quality) + { } diff --git a/src/libxrpl/tx/paths/BookTip.cpp b/src/libxrpl/tx/paths/BookTip.cpp index 5611a081c3..f9b700b7af 100644 --- a/src/libxrpl/tx/paths/BookTip.cpp +++ b/src/libxrpl/tx/paths/BookTip.cpp @@ -5,7 +5,7 @@ namespace xrpl { BookTip::BookTip(ApplyView& view, Book const& book) - : view_(view), m_valid(false), m_book(getBookBase(book)), m_end(getQualityNext(m_book)) + : view_(view), m_book(getBookBase(book)), m_end(getQualityNext(m_book)) { } diff --git a/src/test/csf/Peer.h b/src/test/csf/Peer.h index 94b2c74a0b..fb1238990e 100644 --- a/src/test/csf/Peer.h +++ b/src/test/csf/Peer.h @@ -231,7 +231,7 @@ struct Peer // Number of proposers in the prior round std::size_t prevProposers = 0; // Duration of prior round - std::chrono::milliseconds prevRoundTime; + std::chrono::milliseconds prevRoundTime{}; // Quorum of validations needed for a ledger to be fully validated // TODO: Use the logic in ValidatorList to set this dynamically @@ -501,16 +501,10 @@ struct Peer NetClock::duration const& closeResolution, ConsensusCloseTimes const& rawCloseTimes, ConsensusMode const& mode, - Json::Value&& consensusJson) + Json::Value const& consensusJson) { onAccept( - result, - prevLedger, - closeResolution, - rawCloseTimes, - mode, - std::move(consensusJson), - validating()); + result, prevLedger, closeResolution, rawCloseTimes, mode, consensusJson, validating()); } void @@ -520,10 +514,10 @@ struct Peer NetClock::duration const& closeResolution, ConsensusCloseTimes const& rawCloseTimes, ConsensusMode const& mode, - Json::Value&& consensusJson, + Json::Value const& consensusJson, bool const validating) { - schedule(delays.ledgerAccept, [=, this]() { + schedule(delays.ledgerAccept, [mode, result, prevLedger, closeResolution, this]() { bool const proposing = mode == ConsensusMode::proposing; bool const consensusFail = result.state == ConsensusState::MovedOn; diff --git a/src/test/csf/Tx.h b/src/test/csf/Tx.h index f919b650db..81393f7bda 100644 --- a/src/test/csf/Tx.h +++ b/src/test/csf/Tx.h @@ -100,7 +100,8 @@ public: { } - TxSet(MutableTxSet&& m) : txs_{std::move(m.txs_)}, id_{calcID(txs_)} + TxSet(MutableTxSet&& m) // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved) + : txs_{m.txs_}, id_{calcID(txs_)} { } @@ -161,7 +162,7 @@ private: TxSetType txs_; //! The unique ID of this tx set - ID id_; + ID id_{}; }; //------------------------------------------------------------------------------ diff --git a/src/test/jtx/Env_ss.h b/src/test/jtx/Env_ss.h index 9db96d5907..d6f5fd1a29 100644 --- a/src/test/jtx/Env_ss.h +++ b/src/test/jtx/Env_ss.h @@ -24,7 +24,7 @@ private: operator=(SignSubmitRunner&&) = delete; SignSubmitRunner(Env& env, JTx&& jt, std::source_location loc) - : env_(env), jt_(jt), loc_(loc) + : env_(env), jt_(std::move(jt)), loc_(loc) { } diff --git a/src/test/jtx/Oracle.h b/src/test/jtx/Oracle.h index 8efd17802c..7924d278e5 100644 --- a/src/test/jtx/Oracle.h +++ b/src/test/jtx/Oracle.h @@ -99,7 +99,7 @@ private: static inline std::uint32_t fee = 0; Env& env_; AccountID owner_; - std::uint32_t documentID_; + std::uint32_t documentID_{}; private: void diff --git a/src/test/jtx/flags.h b/src/test/jtx/flags.h index 3dde1fa414..a203f1461e 100644 --- a/src/test/jtx/flags.h +++ b/src/test/jtx/flags.h @@ -12,7 +12,7 @@ namespace detail { class flags_helper { protected: - std::uint32_t mask_; + std::uint32_t mask_{0}; private: void @@ -79,7 +79,7 @@ private: protected: template - flags_helper(Args... args) : mask_(0) + flags_helper(Args... args) { set_args(args...); } diff --git a/src/test/jtx/impl/Oracle.cpp b/src/test/jtx/impl/Oracle.cpp index 0c9ddc8f0d..d48432e8e4 100644 --- a/src/test/jtx/impl/Oracle.cpp +++ b/src/test/jtx/impl/Oracle.cpp @@ -12,7 +12,7 @@ namespace test { namespace jtx { namespace oracle { -Oracle::Oracle(Env& env, CreateArg const& arg, bool submit) : env_(env), documentID_{} +Oracle::Oracle(Env& env, CreateArg const& arg, bool submit) : env_(env) { // LastUpdateTime is checked to be in range // {close-maxLastUpdateTimeDelta, close+maxLastUpdateTimeDelta}. diff --git a/src/test/jtx/impl/quality2.cpp b/src/test/jtx/impl/quality2.cpp index c202592b9d..9da366d4c2 100644 --- a/src/test/jtx/impl/quality2.cpp +++ b/src/test/jtx/impl/quality2.cpp @@ -8,12 +8,14 @@ namespace test { namespace jtx { qualityInPercent::qualityInPercent(double percent) + // NOLINTNEXTLINE(cppcoreguidelines-use-default-member-init) : qIn_(static_cast((percent / 100) * QUALITY_ONE)) { assert(percent <= 400 && percent >= 0); } qualityOutPercent::qualityOutPercent(double percent) + // NOLINTNEXTLINE(cppcoreguidelines-use-default-member-init) : qOut_(static_cast((percent / 100) * QUALITY_ONE)) { assert(percent <= 400 && percent >= 0); diff --git a/src/test/jtx/impl/xchain_bridge.cpp b/src/test/jtx/impl/xchain_bridge.cpp index 19c1b7fab5..72d932463f 100644 --- a/src/test/jtx/impl/xchain_bridge.cpp +++ b/src/test/jtx/impl/xchain_bridge.cpp @@ -413,7 +413,6 @@ XChainBridgeObjects::XChainBridgeObjects() } return r; }()) - , quorum(UT_XCHAIN_DEFAULT_QUORUM) , reward(XRP(1)) , split_reward_quorum(divide(reward, STAmount(UT_XCHAIN_DEFAULT_QUORUM), reward.issue())) , split_reward_everyone(divide(reward, STAmount(UT_XCHAIN_DEFAULT_NUM_SIGNERS), reward.issue())) diff --git a/src/test/jtx/quality.h b/src/test/jtx/quality.h index 34c960224f..2da83eeef5 100644 --- a/src/test/jtx/quality.h +++ b/src/test/jtx/quality.h @@ -25,7 +25,7 @@ public: class qualityInPercent { private: - std::uint32_t qIn_; + std::uint32_t qIn_; // NOLINT(cppcoreguidelines-use-default-member-init) public: explicit qualityInPercent(double percent); @@ -53,7 +53,7 @@ public: class qualityOutPercent { private: - std::uint32_t qOut_; + std::uint32_t qOut_; // NOLINT(cppcoreguidelines-use-default-member-init) public: explicit qualityOutPercent(double percent); diff --git a/src/test/jtx/xchain_bridge.h b/src/test/jtx/xchain_bridge.h index 698426c59c..1270d03ed6 100644 --- a/src/test/jtx/xchain_bridge.h +++ b/src/test/jtx/xchain_bridge.h @@ -170,7 +170,7 @@ struct XChainBridgeObjects std::vector const alt_signers; std::vector const payee; std::vector const payees; - std::uint32_t const quorum; + std::uint32_t const quorum{UT_XCHAIN_DEFAULT_QUORUM}; STAmount const reward; // 1 xrp STAmount const split_reward_quorum; // 250,000 drops diff --git a/src/xrpld/app/ledger/InboundLedger.h b/src/xrpld/app/ledger/InboundLedger.h index 4795ea8f9f..b17b59b27f 100644 --- a/src/xrpld/app/ledger/InboundLedger.h +++ b/src/xrpld/app/ledger/InboundLedger.h @@ -152,11 +152,11 @@ private: clock_type::time_point mLastAction; std::shared_ptr mLedger; - bool mHaveHeader; - bool mHaveState; - bool mHaveTransactions; - bool mSignaled; - bool mByHash; + bool mHaveHeader{false}; + bool mHaveState{false}; + bool mHaveTransactions{false}; + bool mSignaled{false}; + bool mByHash{true}; std::uint32_t mSeq; Reason const mReason; @@ -168,7 +168,7 @@ private: std::mutex mReceivedDataLock; std::vector, std::shared_ptr>> mReceivedData; - bool mReceiveDispatched; + bool mReceiveDispatched{false}; std::unique_ptr mPeerSet; }; diff --git a/src/xrpld/app/ledger/detail/InboundLedger.cpp b/src/xrpld/app/ledger/detail/InboundLedger.cpp index 69af55b8f3..2402b5b561 100644 --- a/src/xrpld/app/ledger/detail/InboundLedger.cpp +++ b/src/xrpld/app/ledger/detail/InboundLedger.cpp @@ -67,14 +67,8 @@ InboundLedger::InboundLedger( {jtLEDGER_DATA, "InboundLedger", 5}, app.getJournal("InboundLedger")) , m_clock(clock) - , mHaveHeader(false) - , mHaveState(false) - , mHaveTransactions(false) - , mSignaled(false) - , mByHash(true) , mSeq(seq) , mReason(reason) - , mReceiveDispatched(false) , mPeerSet(std::move(peerSet)) { JLOG(journal_.trace()) << "Acquiring ledger " << hash_; diff --git a/src/xrpld/app/ledger/detail/TimeoutCounter.cpp b/src/xrpld/app/ledger/detail/TimeoutCounter.cpp index f329665031..216771e60d 100644 --- a/src/xrpld/app/ledger/detail/TimeoutCounter.cpp +++ b/src/xrpld/app/ledger/detail/TimeoutCounter.cpp @@ -15,10 +15,6 @@ TimeoutCounter::TimeoutCounter( : app_(app) , journal_(journal) , hash_(hash) - , timeouts_(0) - , complete_(false) - , failed_(false) - , progress_(false) , timerInterval_(interval) , queueJobParameter_(std::move(jobParameter)) , timer_(app_.getIOContext()) diff --git a/src/xrpld/app/ledger/detail/TimeoutCounter.h b/src/xrpld/app/ledger/detail/TimeoutCounter.h index 5f5ccb2f43..a7e4c043be 100644 --- a/src/xrpld/app/ledger/detail/TimeoutCounter.h +++ b/src/xrpld/app/ledger/detail/TimeoutCounter.h @@ -59,6 +59,8 @@ public: virtual void cancel(); + virtual ~TimeoutCounter() = default; + protected: using ScopedLockType = std::unique_lock; @@ -76,8 +78,6 @@ protected: QueueJobParameter&& jobParameter, beast::Journal journal); - virtual ~TimeoutCounter() = default; - /** Schedule a call to queueJob() after mTimerInterval. */ void setTimer(ScopedLockType&); @@ -109,11 +109,11 @@ protected: /** The hash of the object (in practice, always a ledger) we are trying to * fetch. */ uint256 const hash_; - int timeouts_; - bool complete_; - bool failed_; + int timeouts_{0}; + bool complete_{false}; + bool failed_{false}; /** Whether forward progress has been made. */ - bool progress_; + bool progress_{false}; /** The minimum time to wait between calls to execute(). */ std::chrono::milliseconds timerInterval_; diff --git a/src/xrpld/app/ledger/detail/TransactionAcquire.cpp b/src/xrpld/app/ledger/detail/TransactionAcquire.cpp index 0dd654d80b..d2561718a3 100644 --- a/src/xrpld/app/ledger/detail/TransactionAcquire.cpp +++ b/src/xrpld/app/ledger/detail/TransactionAcquire.cpp @@ -31,7 +31,6 @@ TransactionAcquire::TransactionAcquire( TX_ACQUIRE_TIMEOUT, {jtTXN_DATA, "TxAcq", {}}, app.getJournal("TransactionAcquire")) - , mHaveRoot(false) , mPeerSet(std::move(peerSet)) { mMap = std::make_shared(SHAMapType::TRANSACTION, hash, app_.getNodeFamily()); diff --git a/src/xrpld/app/ledger/detail/TransactionAcquire.h b/src/xrpld/app/ledger/detail/TransactionAcquire.h index a39f6a2f35..f29a01fca4 100644 --- a/src/xrpld/app/ledger/detail/TransactionAcquire.h +++ b/src/xrpld/app/ledger/detail/TransactionAcquire.h @@ -31,7 +31,7 @@ public: private: std::shared_ptr mMap; - bool mHaveRoot; + bool mHaveRoot{false}; std::unique_ptr mPeerSet; void diff --git a/src/xrpld/app/misc/TxQ.h b/src/xrpld/app/misc/TxQ.h index 7c441867ea..772d51b959 100644 --- a/src/xrpld/app/misc/TxQ.h +++ b/src/xrpld/app/misc/TxQ.h @@ -146,23 +146,23 @@ public: explicit Metrics() = default; /// Number of transactions in the queue - std::size_t txCount; + std::size_t txCount{}; /// Max transactions currently allowed in queue std::optional txQMaxSize; /// Number of transactions currently in the open ledger - std::size_t txInLedger; + std::size_t txInLedger{}; /// Number of transactions expected per ledger - std::size_t txPerLedger; + std::size_t txPerLedger{}; /// Reference transaction fee level - FeeLevel64 referenceFeeLevel; + FeeLevel64 referenceFeeLevel{}; /// Minimum fee level for a transaction to be considered for /// the open ledger or the queue - FeeLevel64 minProcessingFeeLevel; + FeeLevel64 minProcessingFeeLevel{}; /// Median fee level of the last ledger - FeeLevel64 medFeeLevel; + FeeLevel64 medFeeLevel{}; /// Minimum fee level to get into the current open ledger, /// bypassing the queue - FeeLevel64 openLedgerFeeLevel; + FeeLevel64 openLedgerFeeLevel{}; }; /** @@ -511,7 +511,7 @@ private: their `retriesRemaining` forced down as part of the penalty. */ - int retriesRemaining; + int retriesRemaining{retriesAllowed}; /// Flags provided to `apply`. If the transaction is later /// attempted with different flags, it will need to be /// `preflight`ed again. diff --git a/src/xrpld/app/misc/ValidatorList.h b/src/xrpld/app/misc/ValidatorList.h index c10561b6e7..9b7670a482 100644 --- a/src/xrpld/app/misc/ValidatorList.h +++ b/src/xrpld/app/misc/ValidatorList.h @@ -157,7 +157,7 @@ class ValidatorList std::vector list; std::vector manifests; - std::size_t sequence; + std::size_t sequence{}; TimeKeeper::time_point validFrom; TimeKeeper::time_point validUntil; std::string siteUri; @@ -173,7 +173,7 @@ class ValidatorList struct PublisherListCollection { - PublisherStatus status; + PublisherStatus status = PublisherStatus::unavailable; /* The `current` VL is the one which 1. Has the largest sequence number that @@ -223,7 +223,7 @@ class ValidatorList hash_set trustedMasterKeys_; // Minimum number of lists on which a trusted validator must appear on - std::size_t listThreshold_; + std::size_t listThreshold_{1}; // The current list of trusted signing keys. For those validators using // a manifest, the signing key is the ephemeral key. For the ones using diff --git a/src/xrpld/app/misc/ValidatorSite.h b/src/xrpld/app/misc/ValidatorSite.h index 9d9031b9a2..270df6f9f0 100644 --- a/src/xrpld/app/misc/ValidatorSite.h +++ b/src/xrpld/app/misc/ValidatorSite.h @@ -85,12 +85,12 @@ private: /// when we've gotten a temp redirect std::shared_ptr activeResource; - unsigned short redirCount; + unsigned short redirCount{0}; std::chrono::minutes refreshInterval; clock_type::time_point nextRefresh; std::optional lastRefreshStatus; endpoint_type lastRequestEndpoint; - bool lastRequestSuccessful; + bool lastRequestSuccessful{false}; }; Application& app_; diff --git a/src/xrpld/app/misc/detail/TxQ.cpp b/src/xrpld/app/misc/detail/TxQ.cpp index 8f8f14d5a7..3494a4b7bd 100644 --- a/src/xrpld/app/misc/detail/TxQ.cpp +++ b/src/xrpld/app/misc/detail/TxQ.cpp @@ -257,7 +257,6 @@ TxQ::MaybeTx::MaybeTx( , account(txn_->getAccountID(sfAccount)) , lastValid(getLastLedgerSequence(*txn_)) , seqProxy(txn_->getSeqProxy()) - , retriesRemaining(retriesAllowed) , flags(flags_) , pfResult(pfResult_) { diff --git a/src/xrpld/app/misc/detail/ValidatorList.cpp b/src/xrpld/app/misc/detail/ValidatorList.cpp index 5543d0029f..bed91afc44 100644 --- a/src/xrpld/app/misc/detail/ValidatorList.cpp +++ b/src/xrpld/app/misc/detail/ValidatorList.cpp @@ -109,7 +109,7 @@ ValidatorList::ValidatorList( , j_(j) , quorum_(minimumQuorum.value_or(1)) // Genesis ledger quorum , minimumQuorum_(minimumQuorum) - , listThreshold_(1) + { } diff --git a/src/xrpld/app/misc/detail/ValidatorSite.cpp b/src/xrpld/app/misc/detail/ValidatorSite.cpp index f9b6553fc2..a4623e7acc 100644 --- a/src/xrpld/app/misc/detail/ValidatorSite.cpp +++ b/src/xrpld/app/misc/detail/ValidatorSite.cpp @@ -60,10 +60,9 @@ ValidatorSite::Site::Resource::Resource(std::string uri_) : uri{std::move(uri_)} ValidatorSite::Site::Site(std::string uri) : loadedResource{std::make_shared(std::move(uri))} , startingResource{loadedResource} - , redirCount{0} , refreshInterval{default_refresh_interval} , nextRefresh{clock_type::now()} - , lastRequestSuccessful{false} + { } diff --git a/src/xrpld/consensus/Consensus.h b/src/xrpld/consensus/Consensus.h index d5441dc1c4..142b1a01f0 100644 --- a/src/xrpld/consensus/Consensus.h +++ b/src/xrpld/consensus/Consensus.h @@ -554,7 +554,7 @@ private: ConsensusParms::AvalancheState closeTimeAvalancheState_ = ConsensusParms::init; // Time it took for the last consensus round to converge - std::chrono::milliseconds prevRoundTime_; + std::chrono::milliseconds prevRoundTime_{}; //------------------------------------------------------------------------- // Network time measurements of consensus progress diff --git a/src/xrpld/consensus/ConsensusTypes.h b/src/xrpld/consensus/ConsensusTypes.h index 2331c9dfbf..8aba48f34e 100644 --- a/src/xrpld/consensus/ConsensusTypes.h +++ b/src/xrpld/consensus/ConsensusTypes.h @@ -117,7 +117,7 @@ class ConsensusTimer { using time_point = std::chrono::steady_clock::time_point; time_point start_; - std::chrono::milliseconds dur_; + std::chrono::milliseconds dur_{}; public: std::chrono::milliseconds diff --git a/src/xrpld/consensus/DisputedTx.h b/src/xrpld/consensus/DisputedTx.h index 0657ad7ac2..e8304f4242 100644 --- a/src/xrpld/consensus/DisputedTx.h +++ b/src/xrpld/consensus/DisputedTx.h @@ -39,7 +39,7 @@ public: @param j Journal for debugging */ DisputedTx(Tx_t const& tx, bool ourVote, std::size_t numPeers, beast::Journal j) - : yays_(0), nays_(0), ourVote_(ourVote), tx_(tx), j_(j) + : ourVote_(ourVote), tx_(tx), j_(j) { votes_.reserve(numPeers); } @@ -173,8 +173,8 @@ public: getJson() const; private: - int yays_; //< Number of yes votes - int nays_; //< Number of no votes + int yays_{0}; //< Number of yes votes + int nays_{0}; //< Number of no votes bool ourVote_; //< Our vote (true is yes) Tx_t tx_; //< Transaction under dispute Map_t votes_; //< Map from NodeID to vote @@ -258,8 +258,8 @@ DisputedTx::updateVote(int percentTime, bool proposing, Consensu if (!ourVote_ && (yays_ == 0)) return false; - bool newPosition; - int weight; + bool newPosition = false; + int weight = 0; // When proposing, to prevent avalanche stalls, we increase the needed // weight slightly over time. We also need to ensure that the consensus has diff --git a/src/xrpld/consensus/LedgerTrie.h b/src/xrpld/consensus/LedgerTrie.h index 335c2cae7f..aecd105c07 100644 --- a/src/xrpld/consensus/LedgerTrie.h +++ b/src/xrpld/consensus/LedgerTrie.h @@ -72,7 +72,7 @@ public: XRPL_ASSERT(ledger_.seq() == start_, "xrpl::Span::Span : ledger is genesis"); } - Span(Ledger ledger) : start_{0}, end_{ledger.seq() + Seq{1}}, ledger_{std::move(ledger)} + Span(Ledger ledger) : end_{ledger.seq() + Seq{1}}, ledger_{std::move(ledger)} { } diff --git a/src/xrpld/overlay/Slot.h b/src/xrpld/overlay/Slot.h index 44a2e7afad..22e908ee99 100644 --- a/src/xrpld/overlay/Slot.h +++ b/src/xrpld/overlay/Slot.h @@ -98,9 +98,7 @@ private: * validator message source */ Slot(SquelchHandler const& handler, beast::Journal journal, uint16_t maxSelectedPeers) - : reachedThreshold_(0) - , lastSelected_(clock_type::now()) - , state_(SlotState::Counting) + : lastSelected_(clock_type::now()) , handler_(handler) , journal_(journal) , maxSelectedPeers_(maxSelectedPeers) @@ -220,14 +218,14 @@ private: std::unordered_set considered_; // number of peers that reached MAX_MESSAGE_THRESHOLD - std::uint16_t reachedThreshold_; + std::uint16_t reachedThreshold_{0}; // last time peers were selected, used to age the slot typename clock_type::time_point lastSelected_; - SlotState state_; // slot's state - SquelchHandler const& handler_; // squelch/unsquelch handler - beast::Journal const journal_; // logging + SlotState state_{SlotState::Counting}; // slot's state + SquelchHandler const& handler_; // squelch/unsquelch handler + beast::Journal const journal_; // logging // the maximum number of peers that should be selected as a validator // message source diff --git a/src/xrpld/overlay/detail/ConnectAttempt.h b/src/xrpld/overlay/detail/ConnectAttempt.h index a3b2fd5cce..520ebe277e 100644 --- a/src/xrpld/overlay/detail/ConnectAttempt.h +++ b/src/xrpld/overlay/detail/ConnectAttempt.h @@ -145,7 +145,7 @@ public: beast::Journal journal, OverlayImpl& overlay); - ~ConnectAttempt(); + virtual ~ConnectAttempt(); /** * @brief Stop the connection attempt diff --git a/src/xrpld/overlay/detail/OverlayImpl.cpp b/src/xrpld/overlay/detail/OverlayImpl.cpp index a1edfe4e33..2720c10140 100644 --- a/src/xrpld/overlay/detail/OverlayImpl.cpp +++ b/src/xrpld/overlay/detail/OverlayImpl.cpp @@ -126,7 +126,6 @@ OverlayImpl::OverlayImpl( collector)) , m_resolver(resolver) , next_id_(1) - , timer_count_(0) , slots_(app, *this, app.config()) , m_stats( std::bind(&OverlayImpl::collect_metrics, this), diff --git a/src/xrpld/overlay/detail/OverlayImpl.h b/src/xrpld/overlay/detail/OverlayImpl.h index 26b5a77371..167d574188 100644 --- a/src/xrpld/overlay/detail/OverlayImpl.h +++ b/src/xrpld/overlay/detail/OverlayImpl.h @@ -49,9 +49,8 @@ public: explicit Child(OverlayImpl& overlay); - virtual ~Child(); - public: + virtual ~Child(); virtual void stop() = 0; }; @@ -98,7 +97,7 @@ private: hash_map> ids_; Resolver& m_resolver; std::atomic next_id_; - int timer_count_; + int timer_count_{0}; std::atomic jqTransOverflow_{0}; std::atomic peerDisconnects_{0}; std::atomic peerDisconnectsCharges_{0}; diff --git a/src/xrpld/overlay/detail/ProtocolMessage.h b/src/xrpld/overlay/detail/ProtocolMessage.h index ac06b10292..41d42674ba 100644 --- a/src/xrpld/overlay/detail/ProtocolMessage.h +++ b/src/xrpld/overlay/detail/ProtocolMessage.h @@ -349,7 +349,7 @@ invokeProtocolMessage(Buffers const& buffers, Handler& handler, std::size_t& hin return result; } - bool success; + bool success = false; switch (header->message_type) { diff --git a/src/xrpld/peerfinder/PeerfinderManager.h b/src/xrpld/peerfinder/PeerfinderManager.h index b850a10975..57fde8a569 100644 --- a/src/xrpld/peerfinder/PeerfinderManager.h +++ b/src/xrpld/peerfinder/PeerfinderManager.h @@ -8,6 +8,8 @@ #include +#include "xrpld/peerfinder/detail/Tuning.h" + #include namespace xrpl { @@ -27,7 +29,7 @@ struct Config This includes both inbound and outbound, but does not include fixed peers. */ - std::size_t maxPeers; + std::size_t maxPeers{Tuning::defaultMaxPeers}; /** The number of automatic outbound connections to maintain. Outbound connections are only maintained if autoConnect @@ -39,25 +41,25 @@ struct Config Inbound connections are only maintained if wantIncoming is `true`. */ - std::size_t inPeers; + std::size_t inPeers{0}; /** `true` if we want our IP address kept private. */ bool peerPrivate = true; /** `true` if we want to accept incoming connections. */ - bool wantIncoming; + bool wantIncoming{true}; /** `true` if we want to establish connections automatically */ - bool autoConnect; + bool autoConnect{true}; /** The listening port number. */ - std::uint16_t listeningPort; + std::uint16_t listeningPort{0}; /** The set of features we advertise. */ std::string features; /** Limit how many incoming connections we allow per IP */ - int ipLimit; + int ipLimit{0}; //-------------------------------------------------------------------------- diff --git a/src/xrpld/peerfinder/detail/Bootcache.cpp b/src/xrpld/peerfinder/detail/Bootcache.cpp index d07ec444a4..580ebe0c53 100644 --- a/src/xrpld/peerfinder/detail/Bootcache.cpp +++ b/src/xrpld/peerfinder/detail/Bootcache.cpp @@ -10,11 +10,8 @@ namespace xrpl { namespace PeerFinder { Bootcache::Bootcache(Store& store, clock_type& clock, beast::Journal journal) - : m_store(store) - , m_clock(clock) - , m_journal(journal) - , m_whenUpdate(m_clock.now()) - , m_needsUpdate(false) + : m_store(store), m_clock(clock), m_journal(journal), m_whenUpdate(m_clock.now()) + { } diff --git a/src/xrpld/peerfinder/detail/Bootcache.h b/src/xrpld/peerfinder/detail/Bootcache.h index a4687d95f4..9ab0a878e8 100644 --- a/src/xrpld/peerfinder/detail/Bootcache.h +++ b/src/xrpld/peerfinder/detail/Bootcache.h @@ -97,7 +97,7 @@ private: clock_type::time_point m_whenUpdate; // Set to true when a database update is needed - bool m_needsUpdate; + bool m_needsUpdate{false}; public: static constexpr int staticValence = 32; diff --git a/src/xrpld/peerfinder/detail/Checker.h b/src/xrpld/peerfinder/detail/Checker.h index ccc395f053..21cc0f160e 100644 --- a/src/xrpld/peerfinder/detail/Checker.h +++ b/src/xrpld/peerfinder/detail/Checker.h @@ -44,7 +44,7 @@ private: async_op(Checker& owner, boost::asio::io_context& io_context, Handler&& handler); - ~async_op(); + virtual ~async_op(); void stop() override; @@ -108,7 +108,7 @@ template Checker::async_op::async_op( Checker& owner, boost::asio::io_context& io_context, - Handler&& handler) + Handler&& handler) // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved) : checker_(owner), socket_(io_context), handler_(std::forward(handler)) { } diff --git a/src/xrpld/peerfinder/detail/Counts.h b/src/xrpld/peerfinder/detail/Counts.h index 26e02a4cb1..8d40b44300 100644 --- a/src/xrpld/peerfinder/detail/Counts.h +++ b/src/xrpld/peerfinder/detail/Counts.h @@ -13,24 +13,6 @@ namespace PeerFinder { class Counts { public: - Counts() - : m_attempts(0) - , m_active(0) - , m_in_max(0) - , m_in_active(0) - , m_out_max(0) - , m_out_active(0) - , m_fixed(0) - , m_fixed_active(0) - , m_reserved(0) - - , m_acceptCount(0) - , m_closingCount(0) - { - } - - //-------------------------------------------------------------------------- - /** Adds the slot state and properties to the slot counts. */ void add(Slot const& s) @@ -282,38 +264,38 @@ private: private: /** Outbound connection attempts. */ - int m_attempts; + int m_attempts{0}; /** Active connections, including fixed and reserved. */ - std::size_t m_active; + std::size_t m_active{0}; /** Total number of inbound slots. */ - std::size_t m_in_max; + std::size_t m_in_max{0}; /** Number of inbound slots assigned to active peers. */ - std::size_t m_in_active; + std::size_t m_in_active{0}; /** Maximum desired outbound slots. */ - std::size_t m_out_max; + std::size_t m_out_max{0}; /** Active outbound slots. */ - std::size_t m_out_active; + std::size_t m_out_active{0}; /** Fixed connections. */ - std::size_t m_fixed; + std::size_t m_fixed{0}; /** Active fixed connections. */ - std::size_t m_fixed_active; + std::size_t m_fixed_active{0}; /** Reserved connections. */ - std::size_t m_reserved; + std::size_t m_reserved{0}; // Number of inbound connections that are // not active or gracefully closing. - int m_acceptCount; + int m_acceptCount{0}; // Number of connections that are gracefully closing. - int m_closingCount; + int m_closingCount{0}; }; } // namespace PeerFinder diff --git a/src/xrpld/peerfinder/detail/Fixed.h b/src/xrpld/peerfinder/detail/Fixed.h index 75b5ed9062..8b67347e6a 100644 --- a/src/xrpld/peerfinder/detail/Fixed.h +++ b/src/xrpld/peerfinder/detail/Fixed.h @@ -9,7 +9,7 @@ namespace PeerFinder { class Fixed { public: - explicit Fixed(clock_type& clock) : m_when(clock.now()), m_failures(0) + explicit Fixed(clock_type& clock) : m_when(clock.now()) { } @@ -40,7 +40,7 @@ public: private: clock_type::time_point m_when; - std::size_t m_failures; + std::size_t m_failures{0}; }; } // namespace PeerFinder diff --git a/src/xrpld/peerfinder/detail/Livecache.h b/src/xrpld/peerfinder/detail/Livecache.h index bedfd6c9d6..ac435e1e24 100644 --- a/src/xrpld/peerfinder/detail/Livecache.h +++ b/src/xrpld/peerfinder/detail/Livecache.h @@ -327,7 +327,7 @@ public: friend class Livecache; lists_type m_lists; - Histogram m_hist; + Histogram m_hist{}; } hops; /** Returns `true` if the cache is empty. */ diff --git a/src/xrpld/peerfinder/detail/PeerfinderConfig.cpp b/src/xrpld/peerfinder/detail/PeerfinderConfig.cpp index a94dbdfbd9..6a158fbbab 100644 --- a/src/xrpld/peerfinder/detail/PeerfinderConfig.cpp +++ b/src/xrpld/peerfinder/detail/PeerfinderConfig.cpp @@ -6,14 +6,8 @@ namespace xrpl { namespace PeerFinder { -Config::Config() - : maxPeers(Tuning::defaultMaxPeers) - , outPeers(calcOutPeers()) - , inPeers(0) - , wantIncoming(true) - , autoConnect(true) - , listeningPort(0) - , ipLimit(0) +Config::Config() : outPeers(calcOutPeers()) + { } diff --git a/src/xrpld/peerfinder/detail/Store.h b/src/xrpld/peerfinder/detail/Store.h index dab50b3ce0..390f80800a 100644 --- a/src/xrpld/peerfinder/detail/Store.h +++ b/src/xrpld/peerfinder/detail/Store.h @@ -22,7 +22,7 @@ public: explicit Entry() = default; beast::IP::Endpoint endpoint; - int valence; + int valence{}; }; virtual void save(std::vector const& v) = 0; diff --git a/src/xrpld/rpc/ServerHandler.h b/src/xrpld/rpc/ServerHandler.h index 74f59756b0..2ffdc9556b 100644 --- a/src/xrpld/rpc/ServerHandler.h +++ b/src/xrpld/rpc/ServerHandler.h @@ -147,7 +147,7 @@ public: Handoff onHandoff( Session& session, - http_request_type&& request, + http_request_type&& request, // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved) boost::asio::ip::tcp::endpoint const& remote_address) { return onHandoff(session, {}, std::forward(request), remote_address); diff --git a/src/xrpld/rpc/Status.h b/src/xrpld/rpc/Status.h index c8ec9d0472..418ad9ccae 100644 --- a/src/xrpld/rpc/Status.h +++ b/src/xrpld/rpc/Status.h @@ -29,7 +29,7 @@ public: // The enable_if allows only integers (not enums). Prevents enum narrowing. template ::value>> - Status(T code, Strings d = {}) : type_(Type::none), code_(code), messages_(std::move(d)) + Status(T code, Strings d = {}) : code_(code), messages_(std::move(d)) { } diff --git a/src/xrpld/rpc/detail/LegacyPathFind.cpp b/src/xrpld/rpc/detail/LegacyPathFind.cpp index b0fa07d676..5b5bcc540b 100644 --- a/src/xrpld/rpc/detail/LegacyPathFind.cpp +++ b/src/xrpld/rpc/detail/LegacyPathFind.cpp @@ -9,7 +9,7 @@ namespace xrpl { namespace RPC { -LegacyPathFind::LegacyPathFind(bool isAdmin, Application& app) : m_isOk(false) +LegacyPathFind::LegacyPathFind(bool isAdmin, Application& app) { if (isAdmin) { diff --git a/src/xrpld/rpc/detail/LegacyPathFind.h b/src/xrpld/rpc/detail/LegacyPathFind.h index 139075b53d..3d45bc9cfd 100644 --- a/src/xrpld/rpc/detail/LegacyPathFind.h +++ b/src/xrpld/rpc/detail/LegacyPathFind.h @@ -23,7 +23,7 @@ public: private: static std::atomic inProgress; - bool m_isOk; + bool m_isOk{false}; }; } // namespace RPC diff --git a/src/xrpld/rpc/detail/Pathfinder.h b/src/xrpld/rpc/detail/Pathfinder.h index 5eaafd3370..662d59ac9a 100644 --- a/src/xrpld/rpc/detail/Pathfinder.h +++ b/src/xrpld/rpc/detail/Pathfinder.h @@ -82,10 +82,10 @@ public: struct PathRank { - std::uint64_t quality; - std::uint64_t length; + std::uint64_t quality{}; + std::uint64_t length{}; STAmount liquidity; - int index; + int index{}; }; private: diff --git a/src/xrpld/rpc/handlers/LedgerEntryHelpers.h b/src/xrpld/rpc/handlers/LedgerEntryHelpers.h index 17207d81e8..9c5f0b2fcb 100644 --- a/src/xrpld/rpc/handlers/LedgerEntryHelpers.h +++ b/src/xrpld/rpc/handlers/LedgerEntryHelpers.h @@ -150,7 +150,7 @@ parse(Json::Value const& param) if (param.isString()) { - std::uint32_t v; + std::uint32_t v = 0; if (beast::lexicalCastChecked(v, param.asString())) return v; } From 6e2452207d59a64179800e0a1bfb581fde7111b6 Mon Sep 17 00:00:00 2001 From: Valentin Balaschenko <13349202+vlntb@users.noreply.github.com> Date: Wed, 1 Apr 2026 17:56:45 +0100 Subject: [PATCH 46/53] fix: Remove fatal assertion on Linux thread name truncation (#6690) --- src/libxrpl/beast/core/CurrentThreadName.cpp | 5 ----- src/xrpld/app/ledger/OrderBookDBImpl.cpp | 4 +++- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/src/libxrpl/beast/core/CurrentThreadName.cpp b/src/libxrpl/beast/core/CurrentThreadName.cpp index 8e54a74e4d..6f22687dcc 100644 --- a/src/libxrpl/beast/core/CurrentThreadName.cpp +++ b/src/libxrpl/beast/core/CurrentThreadName.cpp @@ -95,11 +95,6 @@ setCurrentThreadNameImpl(std::string_view name) { std::cerr << "WARNING: Thread name \"" << name << "\" (length " << name.size() << ") exceeds maximum of " << maxThreadNameLength << " characters on Linux.\n"; - - XRPL_ASSERT( - false, - "beast::detail::setCurrentThreadNameImpl : Thread name exceeds " - "maximum length for Linux"); } #endif } diff --git a/src/xrpld/app/ledger/OrderBookDBImpl.cpp b/src/xrpld/app/ledger/OrderBookDBImpl.cpp index 229110fa04..ffd8499aba 100644 --- a/src/xrpld/app/ledger/OrderBookDBImpl.cpp +++ b/src/xrpld/app/ledger/OrderBookDBImpl.cpp @@ -56,8 +56,10 @@ OrderBookDBImpl::setup(std::shared_ptr const& ledger) } else { + // Shorten job name to fit Linux 15-char thread name limit with "j:" prefix + // "OB" + seq (max 9 digits) = 11 chars, + "j:" = 13 chars (fits in 15) registry_.get().getJobQueue().addJob( - jtUPDATE_PF, "OBUpd" + std::to_string(ledger->seq()), [this, ledger]() { + jtUPDATE_PF, "OB" + std::to_string(ledger->seq() % 1000000000), [this, ledger]() { update(ledger); }); } From 02fa55df8d13be61d2d66e5c1905a0883d404d7d Mon Sep 17 00:00:00 2001 From: Vito Tumas <5780819+Tapanito@users.noreply.github.com> Date: Wed, 1 Apr 2026 21:31:45 +0200 Subject: [PATCH 47/53] fix: Check trustline limits for share-denominated vault withdrawals (#6645) --- .../tx/transactors/vault/VaultWithdraw.cpp | 53 +++++++++- src/test/app/Vault_test.cpp | 97 +++++++++++++++++++ 2 files changed, 146 insertions(+), 4 deletions(-) diff --git a/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp b/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp index e4c671b462..f6b8c98788 100644 --- a/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp @@ -43,10 +43,10 @@ VaultWithdraw::preclaim(PreclaimContext const& ctx) if (!vault) return tecNO_ENTRY; - auto const assets = ctx.tx[sfAmount]; + auto const amount = ctx.tx[sfAmount]; auto const vaultAsset = vault->at(sfAsset); auto const vaultShare = vault->at(sfShareMPTID); - if (assets.asset() != vaultAsset && assets.asset() != vaultShare) + if (amount.asset() != vaultAsset && amount.asset() != vaultShare) return tecWRONG_ASSET; auto const& vaultAccount = vault->at(sfAccount); @@ -67,8 +67,53 @@ VaultWithdraw::preclaim(PreclaimContext const& ctx) // LCOV_EXCL_STOP } - if (auto const ret = canWithdraw(ctx.view, ctx.tx)) - return ret; + if (ctx.view.rules().enabled(fixSecurity3_1_3) && amount.asset() == vaultShare) + { + // Post-fixSecurity3_1_3: if the user specified shares, convert + // to the equivalent asset amount before checking withdrawal + // limits. Pre-amendment the limit check was skipped for + // share-denominated withdrawals. + auto const sleIssuance = ctx.view.read(keylet::mptIssuance(vaultShare)); + if (!sleIssuance) + { + // LCOV_EXCL_START + JLOG(ctx.j.error()) << "VaultWithdraw: missing issuance of vault shares."; + return tefINTERNAL; + // LCOV_EXCL_STOP + } + + try + { + auto const maybeAssets = sharesToAssetsWithdraw(vault, sleIssuance, amount); + if (!maybeAssets) + return tefINTERNAL; // LCOV_EXCL_LINE + + if (auto const ret = canWithdraw( + ctx.view, + account, + dstAcct, + *maybeAssets, + ctx.tx.isFieldPresent(sfDestinationTag))) + return ret; + } + catch (std::overflow_error const&) + { + // It's easy to hit this exception from Number with large enough Scale + // so we avoid spamming the log and only use debug here. + JLOG(ctx.j.debug()) // + << "VaultWithdraw: overflow error with" + << " scale=" << (int)vault->at(sfScale) // + << ", assetsTotal=" << vault->at(sfAssetsTotal) + << ", sharesTotal=" << sleIssuance->at(sfOutstandingAmount) + << ", amount=" << amount.value(); + return tecPATH_DRY; + } + } + else + { + if (auto const ret = canWithdraw(ctx.view, ctx.tx)) + return ret; + } // If sending to Account (i.e. not a transfer), we will also create (only // if authorized) a trust line or MPToken as needed, in doApply(). diff --git a/src/test/app/Vault_test.cpp b/src/test/app/Vault_test.cpp index 50417305b4..823cf7aafd 100644 --- a/src/test/app/Vault_test.cpp +++ b/src/test/app/Vault_test.cpp @@ -5231,6 +5231,102 @@ class Vault_test : public beast::unit_test::suite } } + // Reproduction: canWithdraw IOU limit check bypassed when + // withdrawal amount is specified in shares (MPT) rather than in assets. + void + testBug6_LimitBypassWithShares() + { + using namespace test::jtx; + testcase("Bug6 - limit bypass with share-denominated withdrawal"); + + auto const allAmendments = testable_amendments() | featureSingleAssetVault; + + for (auto const& features : {allAmendments, allAmendments - fixSecurity3_1_3}) + { + bool const withFix = features[fixSecurity3_1_3]; + + Env env{*this, features}; + Account const owner{"owner"}; + Account const issuer{"issuer"}; + Account const depositor{"depositor"}; + Account const charlie{"charlie"}; + Vault const vault{env}; + + env.fund(XRP(1000), issuer, owner, depositor, charlie); + env(fset(issuer, asfAllowTrustLineClawback)); + env.close(); + + PrettyAsset const asset = issuer["IOU"]; + env.trust(asset(1000), owner); + env.trust(asset(1000), depositor); + env(pay(issuer, owner, asset(200))); + env(pay(issuer, depositor, asset(200))); + env.close(); + + // Charlie gets a LOW trustline limit of 5 + env.trust(asset(5), charlie); + env.close(); + + auto const [tx, keylet] = vault.create({.owner = owner, .asset = asset}); + env(tx); + env.close(); + + auto const depositTx = + vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); + env(depositTx); + env.close(); + + // Get the share MPT info + auto const vaultSle = env.le(keylet); + if (!BEAST_EXPECT(vaultSle)) + return; + auto const mptIssuanceID = vaultSle->at(sfShareMPTID); + MPTIssue const shares(mptIssuanceID); + PrettyAsset const share(shares); + + // CONTROL: Withdraw 10 IOU (asset-denominated) to charlie. + // Charlie's limit is 5, so this should be rejected with tecNO_LINE + // regardless of the amendment. + { + auto withdrawTx = + vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(10)}); + withdrawTx[sfDestination] = charlie.human(); + env(withdrawTx, ter{tecNO_LINE}); + env.close(); + } + auto const charlieBalanceBefore = env.balance(charlie, asset.raw().get()); + + // Withdraw the equivalent amount in shares to charlie. + // Post-fix: rejected (tecNO_LINE) because the share amount is + // converted to assets and the trustline limit is checked. + // Pre-fix: succeeds (tesSUCCESS) because the limit check was + // skipped for share-denominated withdrawals. + { + auto withdrawTx = vault.withdraw( + {.depositor = depositor, + .id = keylet.key, + .amount = STAmount(share, 10'000'000)}); + withdrawTx[sfDestination] = charlie.human(); + env(withdrawTx, ter{withFix ? TER{tecNO_LINE} : TER{tesSUCCESS}}); + env.close(); + + auto const charlieBalanceAfter = env.balance(charlie, asset.raw().get()); + if (withFix) + { + // Post-fix: charlie's balance is unchanged — the withdrawal + // was correctly rejected despite being share-denominated. + BEAST_EXPECT(charlieBalanceAfter == charlieBalanceBefore); + } + else + { + // Pre-fix: charlie received the assets, bypassing the + // trustline limit. + BEAST_EXPECT(charlieBalanceAfter > charlieBalanceBefore); + } + } + } + } + public: void run() override @@ -5251,6 +5347,7 @@ public: testVaultClawbackBurnShares(); testVaultClawbackAssets(); testAssetsMaximum(); + testBug6_LimitBypassWithShares(); } }; From 6d9ed125f347933d1bcc3b4eae576f9f26f766e0 Mon Sep 17 00:00:00 2001 From: yinyiqian1 Date: Thu, 2 Apr 2026 16:48:00 -0400 Subject: [PATCH 48/53] fix: Decouple reserve from fee in delegate payment (#6568) --- .../tx/transactors/payment/Payment.cpp | 19 +- src/test/app/Delegate_test.cpp | 227 ++++++++++++++---- 2 files changed, 189 insertions(+), 57 deletions(-) diff --git a/src/libxrpl/tx/transactors/payment/Payment.cpp b/src/libxrpl/tx/transactors/payment/Payment.cpp index 5f2a78917c..bf8a0caa4b 100644 --- a/src/libxrpl/tx/transactors/payment/Payment.cpp +++ b/src/libxrpl/tx/transactors/payment/Payment.cpp @@ -559,18 +559,23 @@ Payment::doApply() // This is the total reserve in drops. auto const reserve = view().fees().accountReserve(ownerCount); - // preFeeBalance_ is the balance on the sending account BEFORE the - // fees were charged. We want to make sure we have enough reserve - // to send. Allow final spend to use reserve for fee. - auto const mmm = std::max(reserve, ctx_.tx.getFieldAmount(sfFee).xrp()); + // In a delegated payment, the fee payer is the delegated account, + // not the source account (account_). + bool const accountIsPayer = (ctx_.tx.getFeePayer() == account_); - if (preFeeBalance_ < dstAmount.xrp() + mmm) + // preFeeBalance_ is the balance on the source account (account_) BEFORE the fees + // were charged. If source account is the fee payer, it must also cover the fee. + // The final spend may use the reserve to cover fees. + auto const minRequiredFunds = + accountIsPayer ? std::max(reserve, ctx_.tx.getFieldAmount(sfFee).xrp()) : reserve; + + if (preFeeBalance_ < dstAmount.xrp() + minRequiredFunds) { // Vote no. However the transaction might succeed, if applied in // a different order. JLOG(j_.trace()) << "Delay transaction: Insufficient funds: " << to_string(preFeeBalance_) - << " / " << to_string(dstAmount.xrp() + mmm) << " (" << to_string(reserve) - << ")"; + << " / " << to_string(dstAmount.xrp() + minRequiredFunds) << " (" + << to_string(reserve) << ")"; return tecUNFUNDED_PAYMENT; } diff --git a/src/test/app/Delegate_test.cpp b/src/test/app/Delegate_test.cpp index 3f6d5e6b47..6c5698a227 100644 --- a/src/test/app/Delegate_test.cpp +++ b/src/test/app/Delegate_test.cpp @@ -274,37 +274,42 @@ class Delegate_test : public beast::unit_test::suite testcase("test fee"); using namespace jtx; - Env env(*this); - Account const alice{"alice"}; - Account const bob{"bob"}; - Account const carol{"carol"}; - env.fund(XRP(10000), alice, carol); - env.fund(XRP(1000), bob); - env.close(); + // Common setup: fund alice, bob, carol with 1000 XRP. + auto setup = [&](Env& env) { + Account const alice{"alice"}; + Account const bob{"bob"}; + Account const carol{"carol"}; + env.fund(XRP(1000), alice, bob, carol); + env.close(); + return std::make_tuple(alice, bob, carol); + }; + // No fee deduction for terNO_DELEGATE_PERMISSION. { - auto aliceBalance = env.balance(alice); - auto bobBalance = env.balance(bob); - auto carolBalance = env.balance(carol); + Env env(*this); + auto [alice, bob, carol] = setup(env); - env(pay(alice, carol, XRP(100)), - fee(XRP(2000)), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); + auto const aliceBalance = env.balance(alice); + auto const bobBalance = env.balance(bob); + auto const carolBalance = env.balance(carol); + + env(pay(alice, carol, XRP(100)), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); env.close(); BEAST_EXPECT(env.balance(alice) == aliceBalance); BEAST_EXPECT(env.balance(bob) == bobBalance); BEAST_EXPECT(env.balance(carol) == carolBalance); } - env(delegate::set(alice, bob, {"Payment"})); - env.close(); - + // Delegate pays the fee successfully. { - // Delegate pays the fee - auto aliceBalance = env.balance(alice); - auto bobBalance = env.balance(bob); - auto carolBalance = env.balance(carol); + Env env(*this); + auto [alice, bob, carol] = setup(env); + env(delegate::set(alice, bob, {"Payment"})); + env.close(); + + auto const aliceBalance = env.balance(alice); + auto const bobBalance = env.balance(bob); + auto const carolBalance = env.balance(carol); auto const sendAmt = XRP(100); auto const feeAmt = XRP(10); @@ -315,11 +320,16 @@ class Delegate_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(carol) == carolBalance + sendAmt); } + // Bob has insufficient balance to pay the fee, will get terINSUF_FEE_B. { - // insufficient balance to pay fee - auto aliceBalance = env.balance(alice); - auto bobBalance = env.balance(bob); - auto carolBalance = env.balance(carol); + Env env(*this); + auto [alice, bob, carol] = setup(env); + env(delegate::set(alice, bob, {"Payment"})); + env.close(); + + auto const aliceBalance = env.balance(alice); + auto const bobBalance = env.balance(bob); + auto const carolBalance = env.balance(carol); env(pay(alice, carol, XRP(100)), fee(XRP(2000)), @@ -331,22 +341,143 @@ class Delegate_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(carol) == carolBalance); } + // The delegated account has enough balance to pay and delegator has enough reserve { - // fee is paid by Delegate - // on context reset (tec error) - auto aliceBalance = env.balance(alice); - auto bobBalance = env.balance(bob); - auto carolBalance = env.balance(carol); - auto const feeAmt = XRP(10); + // Common setup: fund accounts and grant Bob permission to pay on Alice's behalf. + // Alice is funded with exactly (paymentAmount + reserve + baseFee): baseFee covers + // the DelegateSet tx cost, leaving Alice with exactly (paymentAmount + reserve). + // highFee = reserve + baseFee, strictly greater than reserve, so that + // max(reserve, highFee) = highFee — making the direct payment check fail. + auto setup = [&](Env& env) { + Account const alice{"alice"}; + Account const bob{"bob"}; + Account const carol{"carol"}; - env(pay(alice, carol, XRP(20000)), - fee(feeAmt), - delegate::as(bob), - ter(tecUNFUNDED_PAYMENT)); + auto const baseFee = env.current()->fees().base; + auto const reserve = env.current()->fees().accountReserve(1); + auto const paymentAmount = XRP(1); + auto const highFee = reserve + baseFee; + BEAST_EXPECT(highFee > reserve); + + env.fund(paymentAmount + reserve + baseFee, alice); + env.fund(XRP(1000), bob); + env.fund(XRP(1000), carol); + env.close(); + + env(delegate::set(alice, bob, {"Payment"})); + env.close(); + + env.require(balance(alice, paymentAmount + reserve)); + + return std::make_tuple(alice, bob, carol, paymentAmount, highFee, reserve); + }; + + // Alice's balance (paymentAmount + reserve) is insufficient to cover both + // the payment and highFee directly. Even though fees are allowed to dip + // below reserve, when Alice pays the fee herself the required funds = + // paymentAmount + max(reserve, highFee) = paymentAmount + highFee + // (since highFee > reserve), which still exceeds her balance. + // tec: highFee is consumed from Alice's balance. + { + Env env(*this); + auto [alice, bob, carol, paymentAmount, highFee, reserve] = setup(env); + auto const aliceBalance = env.balance(alice); + auto const bobBalance = env.balance(bob); + auto const carolBalance = env.balance(carol); + + env(pay(alice, carol, paymentAmount), fee(highFee), ter(tecUNFUNDED_PAYMENT)); + + // tec consumes the fee from Alice; carol and bob are unaffected. + BEAST_EXPECT(env.balance(alice) == aliceBalance - highFee); + BEAST_EXPECT(env.balance(bob) == bobBalance); + BEAST_EXPECT(env.balance(carol) == carolBalance); + } + + // The payment succeeds because the delegated account pays the fee. + // Alice only needs (paymentAmount + reserve). + { + Env env(*this); + auto [alice, bob, carol, paymentAmount, highFee, reserve] = setup(env); + + auto const alicePrePay = env.balance(alice, XRP); + auto const bobPrePay = env.balance(bob, XRP); + auto const carolPrePay = env.balance(carol, XRP); + + env(pay(alice, carol, paymentAmount), delegate::as(bob), fee(highFee)); + env.close(); + + env.require(balance(alice, alicePrePay - paymentAmount)); + env.require(balance(bob, bobPrePay - highFee)); + env.require(balance(carol, carolPrePay + paymentAmount)); + } + } + + // Delegated account can pay the fee even if it dips below reserve. + { + Env env(*this); + Account const alice{"alice"}; + Account const bob{"bob"}; + Account const carol{"carol"}; + + auto const baseFee = env.current()->fees().base; + auto const baseReserve = env.current()->fees().accountReserve(0); + + env.fund(env.current()->fees().accountReserve(1) + baseFee + XRP(1), alice); + env.fund(baseReserve, bob); + env.fund(XRP(1000), carol); env.close(); - BEAST_EXPECT(env.balance(alice) == aliceBalance); - BEAST_EXPECT(env.balance(bob) == bobBalance - feeAmt); - BEAST_EXPECT(env.balance(carol) == carolBalance); + + env(delegate::set(alice, bob, {"Payment"})); + env.close(); + + auto const alicePreTx = env.balance(alice, XRP); + auto const bobPreTx = env.balance(bob, XRP); + + // After paying for this transaction, bob's balance will + // dip below the base reserve + env(pay(alice, carol, XRP(1)), delegate::as(bob)); + env.close(); + + // Bob's balance is now less than the base reserve. + BEAST_EXPECT(env.balance(bob, XRP) < baseReserve); + env.require(balance(bob, bobPreTx - drops(baseFee))); + + // Alice's balance only decreased by the 1.0 XRP she sent. + env.require(balance(alice, alicePreTx - XRP(1))); + } + + // The delegated account has enough balance for the fee, but delegator + // runs into tecUNFUNDED_PAYMENT. + { + Env env(*this); + Account const alice{"alice"}; + Account const bob{"bob"}; + Account const carol{"carol"}; + + auto const baseFee = env.current()->fees().base; + auto const reserve = env.current()->fees().accountReserve(1); + + // Alice is funded with (reserve + baseFee): after DelegateSet she has + // exactly 'reserve', which is insufficient to send XRP(10) while keeping + // reserve. Bob has plenty to pay the fee. + env.fund(reserve + baseFee, alice); + env.fund(XRP(1000), bob); + env.fund(XRP(1000), carol); + env.close(); + + env(delegate::set(alice, bob, {"Payment"})); + env.close(); + + auto const alicePrePay = env.balance(alice, XRP); + auto const bobPrePay = env.balance(bob, XRP); + auto const carolPrePay = env.balance(carol, XRP); + + // Bob pays the fee, but Alice has insufficient balance to send XRP(10). + env(pay(alice, carol, XRP(10)), delegate::as(bob), ter(tecUNFUNDED_PAYMENT)); + + env.require(balance(alice, alicePrePay)); + env.require(balance(bob, bobPrePay - drops(baseFee))); + env.require(balance(carol, carolPrePay)); } } @@ -1238,8 +1369,8 @@ class Delegate_test : public beast::unit_test::suite // test MPTokenIssuanceUnlock and MPTokenIssuanceLock permissions { Env env(*this); - Account alice{"alice"}; - Account bob{"bob"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(100000), alice, bob); env.close(); @@ -1285,8 +1416,8 @@ class Delegate_test : public beast::unit_test::suite // test mix of granular and transaction level permission { Env env(*this); - Account alice{"alice"}; - Account bob{"bob"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(100000), alice, bob); env.close(); @@ -1332,8 +1463,8 @@ class Delegate_test : public beast::unit_test::suite // tfFullyCanonicalSig won't block delegated transaction { Env env(*this); - Account alice{"alice"}; - Account bob{"bob"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(100000), alice, bob); env.close(); @@ -1410,11 +1541,9 @@ class Delegate_test : public beast::unit_test::suite { Env env(*this); - Account const alice{"alice"}; Account const bob{"bob"}; Account const carol{"carol"}; - env.fund(XRP(100000), alice, bob, carol); env.close(); @@ -1448,11 +1577,9 @@ class Delegate_test : public beast::unit_test::suite { Env env(*this); - Account const alice{"alice"}; Account const bob{"bob"}; Account const carol{"carol"}; - env.fund(XRP(100000), alice, bob, carol); env.close(); @@ -1567,8 +1694,8 @@ class Delegate_test : public beast::unit_test::suite Env env(*this, features); - Account alice{"alice"}; - Account bob{"bob"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(100000), alice, bob); env.close(); From 3414a1776b2a2eef379a83cc7fb8ba6544a62396 Mon Sep 17 00:00:00 2001 From: yinyiqian1 Date: Thu, 2 Apr 2026 16:48:35 -0400 Subject: [PATCH 49/53] docs: Add explanatory comment to checkFee (#6631) --- src/libxrpl/tx/Transactor.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/libxrpl/tx/Transactor.cpp b/src/libxrpl/tx/Transactor.cpp index 7d2ac06fc1..8847174122 100644 --- a/src/libxrpl/tx/Transactor.cpp +++ b/src/libxrpl/tx/Transactor.cpp @@ -363,6 +363,13 @@ Transactor::checkFee(PreclaimContext const& ctx, XRPAmount baseFee) auto const balance = (*sle)[sfBalance].xrp(); + // NOTE: Because preclaim evaluates against a static readview, it + // does not reflect fee deductions from other transactions paid by + // the same account within the current ledger. + // As a result, if an account's balance is over-committed across multiple + // transactions, this check may pass optimistically. + // The fee shortfall will be handled by the Transactor::reset mechanism, + // which caps the fee to the remaining actual balance. if (balance < feePaid) { JLOG(ctx.j.trace()) << "Insufficient balance:" << " balance=" << to_string(balance) From 6b55c4cdc801fbaa5bd7fb7c5a60d3115216a79a Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Thu, 2 Apr 2026 22:34:20 +0100 Subject: [PATCH 50/53] chore: Update XRPLF/actions (#6713) --- .github/workflows/check-pr-commits.yml | 2 +- .github/workflows/check-pr-title.yml | 2 +- .github/workflows/pre-commit.yml | 2 +- .github/workflows/publish-docs.yml | 2 +- .github/workflows/reusable-build-test-config.yml | 2 +- .github/workflows/reusable-clang-tidy-files.yml | 2 +- .github/workflows/upload-conan-deps.yml | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/check-pr-commits.yml b/.github/workflows/check-pr-commits.yml index 2697a3a40e..37e15a5648 100644 --- a/.github/workflows/check-pr-commits.yml +++ b/.github/workflows/check-pr-commits.yml @@ -10,4 +10,4 @@ permissions: jobs: check_commits: - uses: XRPLF/actions/.github/workflows/check-pr-commits.yml@481048b78b94ac3343d1292b4ef125a813879f2b + uses: XRPLF/actions/.github/workflows/check-pr-commits.yml@e2c7f400d1e85ae65dad552fd425169fbacca4a3 diff --git a/.github/workflows/check-pr-title.yml b/.github/workflows/check-pr-title.yml index fc03cdf8e1..6d7bdefa08 100644 --- a/.github/workflows/check-pr-title.yml +++ b/.github/workflows/check-pr-title.yml @@ -11,4 +11,4 @@ on: jobs: check_title: if: ${{ github.event.pull_request.draft != true }} - uses: XRPLF/actions/.github/workflows/check-pr-title.yml@e2c7f400d1e85ae65dad552fd425169fbacca4a3 + uses: XRPLF/actions/.github/workflows/check-pr-title.yml@a5d8dd35be543365e90a11358447130c8763871d diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml index 5cc99d1804..89255f0e47 100644 --- a/.github/workflows/pre-commit.yml +++ b/.github/workflows/pre-commit.yml @@ -14,7 +14,7 @@ on: jobs: # Call the workflow in the XRPLF/actions repo that runs the pre-commit hooks. run-hooks: - uses: XRPLF/actions/.github/workflows/pre-commit.yml@e7896f15cc60d0da1a272c77ee5c4026b424f9c7 + uses: XRPLF/actions/.github/workflows/pre-commit.yml@9307df762265e15c745ddcdb38a581c989f7f349 with: runs_on: ubuntu-latest container: '{ "image": "ghcr.io/xrplf/ci/tools-rippled-pre-commit:sha-41ec7c1" }' diff --git a/.github/workflows/publish-docs.yml b/.github/workflows/publish-docs.yml index 637246ec40..bed97cfafa 100644 --- a/.github/workflows/publish-docs.yml +++ b/.github/workflows/publish-docs.yml @@ -47,7 +47,7 @@ jobs: uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Prepare runner - uses: XRPLF/actions/prepare-runner@2bbc2dc1abeec7bfaa886804ab86871ac201764e + uses: XRPLF/actions/prepare-runner@90f11ee655d1687824fb8793db770477d52afbab with: enable_ccache: false diff --git a/.github/workflows/reusable-build-test-config.yml b/.github/workflows/reusable-build-test-config.yml index 920b5b5278..c79b22ac54 100644 --- a/.github/workflows/reusable-build-test-config.yml +++ b/.github/workflows/reusable-build-test-config.yml @@ -107,7 +107,7 @@ jobs: uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Prepare runner - uses: XRPLF/actions/prepare-runner@2bbc2dc1abeec7bfaa886804ab86871ac201764e + uses: XRPLF/actions/prepare-runner@90f11ee655d1687824fb8793db770477d52afbab with: enable_ccache: ${{ inputs.ccache_enabled }} diff --git a/.github/workflows/reusable-clang-tidy-files.yml b/.github/workflows/reusable-clang-tidy-files.yml index 81264cf24e..b6c66bc27a 100644 --- a/.github/workflows/reusable-clang-tidy-files.yml +++ b/.github/workflows/reusable-clang-tidy-files.yml @@ -35,7 +35,7 @@ jobs: uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Prepare runner - uses: XRPLF/actions/prepare-runner@2bbc2dc1abeec7bfaa886804ab86871ac201764e + uses: XRPLF/actions/prepare-runner@90f11ee655d1687824fb8793db770477d52afbab with: enable_ccache: false diff --git a/.github/workflows/upload-conan-deps.yml b/.github/workflows/upload-conan-deps.yml index 832e455453..f14efde05b 100644 --- a/.github/workflows/upload-conan-deps.yml +++ b/.github/workflows/upload-conan-deps.yml @@ -70,7 +70,7 @@ jobs: uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Prepare runner - uses: XRPLF/actions/prepare-runner@2bbc2dc1abeec7bfaa886804ab86871ac201764e + uses: XRPLF/actions/prepare-runner@90f11ee655d1687824fb8793db770477d52afbab with: enable_ccache: false From 81555d54569b41782293e08b1b2e583b4b01257d Mon Sep 17 00:00:00 2001 From: Mayukha Vadari Date: Thu, 2 Apr 2026 19:46:17 -0400 Subject: [PATCH 51/53] refactor: Reorganize RPC handler files (#6628) --- .github/scripts/rename/copyright.sh | 8 +- src/test/rpc/KeyGeneration_test.cpp | 2 +- src/xrpld/overlay/detail/OverlayImpl.cpp | 2 +- src/xrpld/rpc/detail/Handler.cpp | 4 +- src/xrpld/rpc/handlers/ChannelVerify.cpp | 71 ++++++++ src/xrpld/rpc/handlers/Handlers.h | 4 +- .../{ => account}/AccountChannels.cpp | 0 .../AccountCurrencies.cpp} | 0 .../handlers/{ => account}/AccountInfo.cpp | 0 .../handlers/{ => account}/AccountLines.cpp | 0 .../rpc/handlers/account/AccountNFTs.cpp | 160 ++++++++++++++++++ .../handlers/{ => account}/AccountObjects.cpp | 145 ---------------- .../handlers/{ => account}/AccountOffers.cpp | 0 .../rpc/handlers/{ => account}/AccountTx.cpp | 2 +- .../{ => account}/GatewayBalances.cpp | 0 .../handlers/{ => account}/NoRippleCheck.cpp | 0 .../rpc/handlers/{ => account}/OwnerInfo.cpp | 0 .../rpc/handlers/{ => admin}/BlackList.cpp | 0 .../rpc/handlers/{ => admin}/UnlList.cpp | 0 .../handlers/{ => admin/data}/CanDelete.cpp | 0 .../data/LedgerCleaner.cpp} | 0 .../{ => admin/data}/LedgerRequest.cpp | 0 .../{ => admin/keygen}/ValidationCreate.cpp | 0 .../{ => admin/keygen}/WalletPropose.cpp | 2 +- .../{ => admin/keygen}/WalletPropose.h | 0 .../rpc/handlers/{ => admin/log}/LogLevel.cpp | 0 .../handlers/{ => admin/log}/LogRotate.cpp | 0 .../rpc/handlers/{ => admin/peer}/Connect.cpp | 0 .../peer/PeerReservationsAdd.cpp} | 43 ----- .../admin/peer/PeerReservationsDel.cpp | 41 +++++ .../admin/peer/PeerReservationsList.cpp | 24 +++ .../rpc/handlers/{ => admin/peer}/Peers.cpp | 0 .../server_control}/LedgerAccept.cpp | 0 .../{ => admin/server_control}/Stop.cpp | 0 .../signing/ChannelAuthorize.cpp} | 58 ------- .../signing/Sign.cpp} | 0 .../handlers/{ => admin/signing}/SignFor.cpp | 0 .../{ => admin/status}/ConsensusInfo.cpp | 0 .../handlers/{ => admin/status}/FetchInfo.cpp | 0 .../handlers/{ => admin/status}/GetCounts.cpp | 0 .../handlers/{ => admin/status}/GetCounts.h | 0 .../rpc/handlers/{ => admin/status}/Print.cpp | 0 .../{ => admin/status}/ValidatorInfo.cpp | 0 .../{ => admin/status}/ValidatorListSites.cpp | 0 .../{ => admin/status}/Validators.cpp | 0 .../{LedgerHandler.cpp => ledger/Ledger.cpp} | 2 +- .../{LedgerHandler.h => ledger/Ledger.h} | 0 .../handlers/{ => ledger}/LedgerClosed.cpp | 0 .../handlers/{ => ledger}/LedgerCurrent.cpp | 0 .../rpc/handlers/{ => ledger}/LedgerData.cpp | 0 .../rpc/handlers/{ => ledger}/LedgerDiff.cpp | 0 .../rpc/handlers/{ => ledger}/LedgerEntry.cpp | 2 +- .../{ => ledger}/LedgerEntryHelpers.h | 0 .../handlers/{ => ledger}/LedgerHeader.cpp | 0 .../rpc/handlers/{ => orderbook}/AMMInfo.cpp | 0 .../rpc/handlers/orderbook/BookChanges.cpp | 21 +++ .../handlers/{ => orderbook}/BookOffers.cpp | 13 -- .../{ => orderbook}/DepositAuthorized.cpp | 0 .../{ => orderbook}/GetAggregatePrice.cpp | 0 .../rpc/handlers/orderbook/NFTBuyOffers.cpp | 24 +++ .../NFTOffersHelpers.h} | 34 +--- .../rpc/handlers/orderbook/NFTSellOffers.cpp | 24 +++ .../rpc/handlers/{ => orderbook}/PathFind.cpp | 0 .../{ => orderbook}/RipplePathFind.cpp | 0 .../{Feature1.cpp => server_info/Feature.cpp} | 0 .../{Fee1.cpp => server_info/Fee.cpp} | 0 .../Manifest.cpp} | 0 .../{ => server_info}/ServerDefinitions.cpp | 0 .../handlers/{ => server_info}/ServerInfo.cpp | 0 .../{ => server_info}/ServerState.cpp | 0 .../rpc/handlers/{ => server_info}/Version.h | 0 .../handlers/{ => subscribe}/Subscribe.cpp | 0 .../handlers/{ => subscribe}/Unsubscribe.cpp | 0 .../handlers/{ => transaction}/Simulate.cpp | 0 .../rpc/handlers/{ => transaction}/Submit.cpp | 0 .../{ => transaction}/SubmitMultiSigned.cpp | 0 .../{ => transaction}/TransactionEntry.cpp | 0 .../rpc/handlers/{ => transaction}/Tx.cpp | 0 .../handlers/{ => transaction}/TxHistory.cpp | 0 .../{ => transaction}/TxReduceRelay.cpp | 0 src/xrpld/rpc/handlers/{ => utility}/Ping.cpp | 0 .../rpc/handlers/{ => utility}/Random.cpp | 0 82 files changed, 383 insertions(+), 303 deletions(-) create mode 100644 src/xrpld/rpc/handlers/ChannelVerify.cpp rename src/xrpld/rpc/handlers/{ => account}/AccountChannels.cpp (100%) rename src/xrpld/rpc/handlers/{AccountCurrenciesHandler.cpp => account/AccountCurrencies.cpp} (100%) rename src/xrpld/rpc/handlers/{ => account}/AccountInfo.cpp (100%) rename src/xrpld/rpc/handlers/{ => account}/AccountLines.cpp (100%) create mode 100644 src/xrpld/rpc/handlers/account/AccountNFTs.cpp rename src/xrpld/rpc/handlers/{ => account}/AccountObjects.cpp (68%) rename src/xrpld/rpc/handlers/{ => account}/AccountOffers.cpp (100%) rename src/xrpld/rpc/handlers/{ => account}/AccountTx.cpp (99%) rename src/xrpld/rpc/handlers/{ => account}/GatewayBalances.cpp (100%) rename src/xrpld/rpc/handlers/{ => account}/NoRippleCheck.cpp (100%) rename src/xrpld/rpc/handlers/{ => account}/OwnerInfo.cpp (100%) rename src/xrpld/rpc/handlers/{ => admin}/BlackList.cpp (100%) rename src/xrpld/rpc/handlers/{ => admin}/UnlList.cpp (100%) rename src/xrpld/rpc/handlers/{ => admin/data}/CanDelete.cpp (100%) rename src/xrpld/rpc/handlers/{LedgerCleanerHandler.cpp => admin/data/LedgerCleaner.cpp} (100%) rename src/xrpld/rpc/handlers/{ => admin/data}/LedgerRequest.cpp (100%) rename src/xrpld/rpc/handlers/{ => admin/keygen}/ValidationCreate.cpp (100%) rename src/xrpld/rpc/handlers/{ => admin/keygen}/WalletPropose.cpp (98%) rename src/xrpld/rpc/handlers/{ => admin/keygen}/WalletPropose.h (100%) rename src/xrpld/rpc/handlers/{ => admin/log}/LogLevel.cpp (100%) rename src/xrpld/rpc/handlers/{ => admin/log}/LogRotate.cpp (100%) rename src/xrpld/rpc/handlers/{ => admin/peer}/Connect.cpp (100%) rename src/xrpld/rpc/handlers/{Reservations.cpp => admin/peer/PeerReservationsAdd.cpp} (63%) create mode 100644 src/xrpld/rpc/handlers/admin/peer/PeerReservationsDel.cpp create mode 100644 src/xrpld/rpc/handlers/admin/peer/PeerReservationsList.cpp rename src/xrpld/rpc/handlers/{ => admin/peer}/Peers.cpp (100%) rename src/xrpld/rpc/handlers/{ => admin/server_control}/LedgerAccept.cpp (100%) rename src/xrpld/rpc/handlers/{ => admin/server_control}/Stop.cpp (100%) rename src/xrpld/rpc/handlers/{PayChanClaim.cpp => admin/signing/ChannelAuthorize.cpp} (59%) rename src/xrpld/rpc/handlers/{SignHandler.cpp => admin/signing/Sign.cpp} (100%) rename src/xrpld/rpc/handlers/{ => admin/signing}/SignFor.cpp (100%) rename src/xrpld/rpc/handlers/{ => admin/status}/ConsensusInfo.cpp (100%) rename src/xrpld/rpc/handlers/{ => admin/status}/FetchInfo.cpp (100%) rename src/xrpld/rpc/handlers/{ => admin/status}/GetCounts.cpp (100%) rename src/xrpld/rpc/handlers/{ => admin/status}/GetCounts.h (100%) rename src/xrpld/rpc/handlers/{ => admin/status}/Print.cpp (100%) rename src/xrpld/rpc/handlers/{ => admin/status}/ValidatorInfo.cpp (100%) rename src/xrpld/rpc/handlers/{ => admin/status}/ValidatorListSites.cpp (100%) rename src/xrpld/rpc/handlers/{ => admin/status}/Validators.cpp (100%) rename src/xrpld/rpc/handlers/{LedgerHandler.cpp => ledger/Ledger.cpp} (99%) rename src/xrpld/rpc/handlers/{LedgerHandler.h => ledger/Ledger.h} (100%) rename src/xrpld/rpc/handlers/{ => ledger}/LedgerClosed.cpp (100%) rename src/xrpld/rpc/handlers/{ => ledger}/LedgerCurrent.cpp (100%) rename src/xrpld/rpc/handlers/{ => ledger}/LedgerData.cpp (100%) rename src/xrpld/rpc/handlers/{ => ledger}/LedgerDiff.cpp (100%) rename src/xrpld/rpc/handlers/{ => ledger}/LedgerEntry.cpp (99%) rename src/xrpld/rpc/handlers/{ => ledger}/LedgerEntryHelpers.h (100%) rename src/xrpld/rpc/handlers/{ => ledger}/LedgerHeader.cpp (100%) rename src/xrpld/rpc/handlers/{ => orderbook}/AMMInfo.cpp (100%) create mode 100644 src/xrpld/rpc/handlers/orderbook/BookChanges.cpp rename src/xrpld/rpc/handlers/{ => orderbook}/BookOffers.cpp (95%) rename src/xrpld/rpc/handlers/{ => orderbook}/DepositAuthorized.cpp (100%) rename src/xrpld/rpc/handlers/{ => orderbook}/GetAggregatePrice.cpp (100%) create mode 100644 src/xrpld/rpc/handlers/orderbook/NFTBuyOffers.cpp rename src/xrpld/rpc/handlers/{NFTOffers.cpp => orderbook/NFTOffersHelpers.h} (82%) create mode 100644 src/xrpld/rpc/handlers/orderbook/NFTSellOffers.cpp rename src/xrpld/rpc/handlers/{ => orderbook}/PathFind.cpp (100%) rename src/xrpld/rpc/handlers/{ => orderbook}/RipplePathFind.cpp (100%) rename src/xrpld/rpc/handlers/{Feature1.cpp => server_info/Feature.cpp} (100%) rename src/xrpld/rpc/handlers/{Fee1.cpp => server_info/Fee.cpp} (100%) rename src/xrpld/rpc/handlers/{DoManifest.cpp => server_info/Manifest.cpp} (100%) rename src/xrpld/rpc/handlers/{ => server_info}/ServerDefinitions.cpp (100%) rename src/xrpld/rpc/handlers/{ => server_info}/ServerInfo.cpp (100%) rename src/xrpld/rpc/handlers/{ => server_info}/ServerState.cpp (100%) rename src/xrpld/rpc/handlers/{ => server_info}/Version.h (100%) rename src/xrpld/rpc/handlers/{ => subscribe}/Subscribe.cpp (100%) rename src/xrpld/rpc/handlers/{ => subscribe}/Unsubscribe.cpp (100%) rename src/xrpld/rpc/handlers/{ => transaction}/Simulate.cpp (100%) rename src/xrpld/rpc/handlers/{ => transaction}/Submit.cpp (100%) rename src/xrpld/rpc/handlers/{ => transaction}/SubmitMultiSigned.cpp (100%) rename src/xrpld/rpc/handlers/{ => transaction}/TransactionEntry.cpp (100%) rename src/xrpld/rpc/handlers/{ => transaction}/Tx.cpp (100%) rename src/xrpld/rpc/handlers/{ => transaction}/TxHistory.cpp (100%) rename src/xrpld/rpc/handlers/{ => transaction}/TxReduceRelay.cpp (100%) rename src/xrpld/rpc/handlers/{ => utility}/Ping.cpp (100%) rename src/xrpld/rpc/handlers/{ => utility}/Random.cpp (100%) diff --git a/.github/scripts/rename/copyright.sh b/.github/scripts/rename/copyright.sh index c5a9fb2cd3..3d690321b9 100755 --- a/.github/scripts/rename/copyright.sh +++ b/.github/scripts/rename/copyright.sh @@ -76,11 +76,11 @@ fi if ! grep -q 'Dev Null' src/test/rpc/ValidatorInfo_test.cpp; then echo -e "// Copyright (c) 2020 Dev Null Productions\n\n$(cat src/test/rpc/ValidatorInfo_test.cpp)" > src/test/rpc/ValidatorInfo_test.cpp fi -if ! grep -q 'Dev Null' src/xrpld/rpc/handlers/DoManifest.cpp; then - echo -e "// Copyright (c) 2019 Dev Null Productions\n\n$(cat src/xrpld/rpc/handlers/DoManifest.cpp)" > src/xrpld/rpc/handlers/DoManifest.cpp +if ! grep -q 'Dev Null' src/xrpld/rpc/handlers/server_info/Manifest.cpp; then + echo -e "// Copyright (c) 2019 Dev Null Productions\n\n$(cat src/xrpld/rpc/handlers/server_info/Manifest.cpp)" > src/xrpld/rpc/handlers/server_info/Manifest.cpp fi -if ! grep -q 'Dev Null' src/xrpld/rpc/handlers/ValidatorInfo.cpp; then - echo -e "// Copyright (c) 2019 Dev Null Productions\n\n$(cat src/xrpld/rpc/handlers/ValidatorInfo.cpp)" > src/xrpld/rpc/handlers/ValidatorInfo.cpp +if ! grep -q 'Dev Null' src/xrpld/rpc/handlers/admin/status/ValidatorInfo.cpp; then + echo -e "// Copyright (c) 2019 Dev Null Productions\n\n$(cat src/xrpld/rpc/handlers/admin/status/ValidatorInfo.cpp)" > src/xrpld/rpc/handlers/admin/status/ValidatorInfo.cpp fi if ! grep -q 'Bougalis' include/xrpl/basics/SlabAllocator.h; then echo -e "// Copyright (c) 2022, Nikolaos D. Bougalis \n\n$(cat include/xrpl/basics/SlabAllocator.h)" > include/xrpl/basics/SlabAllocator.h # cspell: ignore Nikolaos Bougalis nikb diff --git a/src/test/rpc/KeyGeneration_test.cpp b/src/test/rpc/KeyGeneration_test.cpp index 87d2ded7ad..f11df0dffb 100644 --- a/src/test/rpc/KeyGeneration_test.cpp +++ b/src/test/rpc/KeyGeneration_test.cpp @@ -1,7 +1,7 @@ #include #include -#include +#include #include #include diff --git a/src/xrpld/overlay/detail/OverlayImpl.cpp b/src/xrpld/overlay/detail/OverlayImpl.cpp index 2720c10140..9bfd3f6818 100644 --- a/src/xrpld/overlay/detail/OverlayImpl.cpp +++ b/src/xrpld/overlay/detail/OverlayImpl.cpp @@ -7,7 +7,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/xrpld/rpc/detail/Handler.cpp b/src/xrpld/rpc/detail/Handler.cpp index 0f95e69d3f..05fc1cb0b4 100644 --- a/src/xrpld/rpc/detail/Handler.cpp +++ b/src/xrpld/rpc/detail/Handler.cpp @@ -1,6 +1,6 @@ #include #include -#include +#include #include #include @@ -75,7 +75,7 @@ Handler const handlerArray[]{ {"account_nfts", byRef(&doAccountNFTs), Role::USER, NO_CONDITION}, {"account_objects", byRef(&doAccountObjects), Role::USER, NO_CONDITION}, {"account_offers", byRef(&doAccountOffers), Role::USER, NO_CONDITION}, - {"account_tx", byRef(&doAccountTxJson), Role::USER, NO_CONDITION}, + {"account_tx", byRef(&doAccountTx), Role::USER, NO_CONDITION}, {"amm_info", byRef(&doAMMInfo), Role::USER, NO_CONDITION}, {"blacklist", byRef(&doBlackList), Role::ADMIN, NO_CONDITION}, {"book_changes", byRef(&doBookChanges), Role::USER, NO_CONDITION}, diff --git a/src/xrpld/rpc/handlers/ChannelVerify.cpp b/src/xrpld/rpc/handlers/ChannelVerify.cpp new file mode 100644 index 0000000000..91b23db4e6 --- /dev/null +++ b/src/xrpld/rpc/handlers/ChannelVerify.cpp @@ -0,0 +1,71 @@ +#include +#include + +#include +#include +#include +#include +#include + +#include + +namespace xrpl { + +// { +// public_key: +// channel_id: 256-bit channel id +// drops: 64-bit uint (as string) +// signature: signature to verify +// } +Json::Value +doChannelVerify(RPC::JsonContext& context) +{ + auto const& params(context.params); + for (auto const& p : {jss::public_key, jss::channel_id, jss::amount, jss::signature}) + { + if (!params.isMember(p)) + return RPC::missing_field_error(p); + } + + std::optional pk; + { + std::string const strPk = params[jss::public_key].asString(); + pk = parseBase58(TokenType::AccountPublic, strPk); + + if (!pk) + { + auto pkHex = strUnHex(strPk); + if (!pkHex) + return rpcError(rpcPUBLIC_MALFORMED); + auto const pkType = publicKeyType(makeSlice(*pkHex)); + if (!pkType) + return rpcError(rpcPUBLIC_MALFORMED); + pk.emplace(makeSlice(*pkHex)); + } + } + + uint256 channelId; + if (!channelId.parseHex(params[jss::channel_id].asString())) + return rpcError(rpcCHANNEL_MALFORMED); + + std::optional const optDrops = + params[jss::amount].isString() ? to_uint64(params[jss::amount].asString()) : std::nullopt; + + if (!optDrops) + return rpcError(rpcCHANNEL_AMT_MALFORMED); + + std::uint64_t const drops = *optDrops; + + auto sig = strUnHex(params[jss::signature].asString()); + if (!sig || sig->empty()) + return rpcError(rpcINVALID_PARAMS); + + Serializer msg; + serializePayChanAuthorization(msg, channelId, XRPAmount(drops)); + + Json::Value result; + result[jss::signature_verified] = verify(*pk, msg.slice(), makeSlice(*sig)); + return result; +} + +} // namespace xrpl diff --git a/src/xrpld/rpc/handlers/Handlers.h b/src/xrpld/rpc/handlers/Handlers.h index a5a96baa31..23328cf52a 100644 --- a/src/xrpld/rpc/handlers/Handlers.h +++ b/src/xrpld/rpc/handlers/Handlers.h @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace xrpl { @@ -19,7 +19,7 @@ doAccountObjects(RPC::JsonContext&); Json::Value doAccountOffers(RPC::JsonContext&); Json::Value -doAccountTxJson(RPC::JsonContext&); +doAccountTx(RPC::JsonContext&); Json::Value doAMMInfo(RPC::JsonContext&); Json::Value diff --git a/src/xrpld/rpc/handlers/AccountChannels.cpp b/src/xrpld/rpc/handlers/account/AccountChannels.cpp similarity index 100% rename from src/xrpld/rpc/handlers/AccountChannels.cpp rename to src/xrpld/rpc/handlers/account/AccountChannels.cpp diff --git a/src/xrpld/rpc/handlers/AccountCurrenciesHandler.cpp b/src/xrpld/rpc/handlers/account/AccountCurrencies.cpp similarity index 100% rename from src/xrpld/rpc/handlers/AccountCurrenciesHandler.cpp rename to src/xrpld/rpc/handlers/account/AccountCurrencies.cpp diff --git a/src/xrpld/rpc/handlers/AccountInfo.cpp b/src/xrpld/rpc/handlers/account/AccountInfo.cpp similarity index 100% rename from src/xrpld/rpc/handlers/AccountInfo.cpp rename to src/xrpld/rpc/handlers/account/AccountInfo.cpp diff --git a/src/xrpld/rpc/handlers/AccountLines.cpp b/src/xrpld/rpc/handlers/account/AccountLines.cpp similarity index 100% rename from src/xrpld/rpc/handlers/AccountLines.cpp rename to src/xrpld/rpc/handlers/account/AccountLines.cpp diff --git a/src/xrpld/rpc/handlers/account/AccountNFTs.cpp b/src/xrpld/rpc/handlers/account/AccountNFTs.cpp new file mode 100644 index 0000000000..b879968e4e --- /dev/null +++ b/src/xrpld/rpc/handlers/account/AccountNFTs.cpp @@ -0,0 +1,160 @@ +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace xrpl { + +/** General RPC command that can retrieve objects in the account root. + { + account: + ledger_hash: // optional + ledger_index: // optional + type: // optional, defaults to all account objects types + limit: // optional + marker: // optional, resume previous query + } +*/ +Json::Value +doAccountNFTs(RPC::JsonContext& context) +{ + auto const& params = context.params; + if (!params.isMember(jss::account)) + return RPC::missing_field_error(jss::account); + + if (!params[jss::account].isString()) + return RPC::invalid_field_error(jss::account); + + auto id = parseBase58(params[jss::account].asString()); + if (!id) + { + return rpcError(rpcACT_MALFORMED); + } + + std::shared_ptr ledger; + auto result = RPC::lookupLedger(ledger, context); + if (ledger == nullptr) + return result; + auto const accountID{id.value()}; + + if (!ledger->exists(keylet::account(accountID))) + return rpcError(rpcACT_NOT_FOUND); + + unsigned int limit = 0; + if (auto err = readLimitField(limit, RPC::Tuning::accountNFTokens, context)) + return *err; + + uint256 marker; + bool const markerSet = params.isMember(jss::marker); + + if (markerSet) + { + auto const& m = params[jss::marker]; + if (!m.isString()) + return RPC::expected_field_error(jss::marker, "string"); + + if (!marker.parseHex(m.asString())) + return RPC::invalid_field_error(jss::marker); + } + + auto const first = keylet::nftpage(keylet::nftpage_min(accountID), marker); + auto const last = keylet::nftpage_max(accountID); + + auto cp = ledger->read( + Keylet(ltNFTOKEN_PAGE, ledger->succ(first.key, last.key.next()).value_or(last.key))); + + std::uint32_t cnt = 0; + auto& nfts = (result[jss::account_nfts] = Json::arrayValue); + + // Continue iteration from the current page: + bool pastMarker = marker.isZero(); + bool markerFound = false; + uint256 const maskedMarker = marker & nft::pageMask; + while (cp) + { + auto arr = cp->getFieldArray(sfNFTokens); + + for (auto const& o : arr) + { + // Scrolling past the marker gets weird. We need to look at + // a couple of conditions. + // + // 1. If the low 96-bits don't match, then we compare only + // against the low 96-bits, since that's what determines + // the sort order of the pages. + // + // 2. However, within one page there can be a number of + // NFTokenIDs that all have the same low 96 bits. If we're + // in that case then we need to compare against the full + // 256 bits. + uint256 const nftokenID = o[sfNFTokenID]; + uint256 const maskedNftokenID = nftokenID & nft::pageMask; + + if (!pastMarker) + { + if (maskedNftokenID < maskedMarker) + continue; + + if (maskedNftokenID == maskedMarker && nftokenID < marker) + continue; + + if (nftokenID == marker) + { + markerFound = true; + continue; + } + } + + if (markerSet && !markerFound) + return RPC::invalid_field_error(jss::marker); + + pastMarker = true; + + { + Json::Value& obj = nfts.append(o.getJson(JsonOptions::none)); + + // Pull out the components of the nft ID. + obj[sfFlags.jsonName] = nft::getFlags(nftokenID); + obj[sfIssuer.jsonName] = to_string(nft::getIssuer(nftokenID)); + obj[sfNFTokenTaxon.jsonName] = nft::toUInt32(nft::getTaxon(nftokenID)); + obj[jss::nft_serial] = nft::getSerial(nftokenID); + if (std::uint16_t const xferFee = {nft::getTransferFee(nftokenID)}) + obj[sfTransferFee.jsonName] = xferFee; + } + + if (++cnt == limit) + { + result[jss::limit] = limit; + result[jss::marker] = to_string(o.getFieldH256(sfNFTokenID)); + return result; + } + } + + if (auto npm = (*cp)[~sfNextPageMin]) + { + cp = ledger->read(Keylet(ltNFTOKEN_PAGE, *npm)); + } + else + { + cp = nullptr; + } + } + + if (markerSet && !markerFound) + return RPC::invalid_field_error(jss::marker); + + result[jss::account] = toBase58(accountID); + context.loadType = Resource::feeMediumBurdenRPC; + return result; +} + +} // namespace xrpl diff --git a/src/xrpld/rpc/handlers/AccountObjects.cpp b/src/xrpld/rpc/handlers/account/AccountObjects.cpp similarity index 68% rename from src/xrpld/rpc/handlers/AccountObjects.cpp rename to src/xrpld/rpc/handlers/account/AccountObjects.cpp index 12132122c1..c09920f4a6 100644 --- a/src/xrpld/rpc/handlers/AccountObjects.cpp +++ b/src/xrpld/rpc/handlers/account/AccountObjects.cpp @@ -11,156 +11,11 @@ #include #include #include -#include #include namespace xrpl { -/** General RPC command that can retrieve objects in the account root. - { - account: - ledger_hash: // optional - ledger_index: // optional - type: // optional, defaults to all account objects types - limit: // optional - marker: // optional, resume previous query - } -*/ - -Json::Value -doAccountNFTs(RPC::JsonContext& context) -{ - auto const& params = context.params; - if (!params.isMember(jss::account)) - return RPC::missing_field_error(jss::account); - - if (!params[jss::account].isString()) - return RPC::invalid_field_error(jss::account); - - auto id = parseBase58(params[jss::account].asString()); - if (!id) - { - return rpcError(rpcACT_MALFORMED); - } - - std::shared_ptr ledger; - auto result = RPC::lookupLedger(ledger, context); - if (ledger == nullptr) - return result; - auto const accountID{id.value()}; - - if (!ledger->exists(keylet::account(accountID))) - return rpcError(rpcACT_NOT_FOUND); - - unsigned int limit = 0; - if (auto err = readLimitField(limit, RPC::Tuning::accountNFTokens, context)) - return *err; - - uint256 marker; - bool const markerSet = params.isMember(jss::marker); - - if (markerSet) - { - auto const& m = params[jss::marker]; - if (!m.isString()) - return RPC::expected_field_error(jss::marker, "string"); - - if (!marker.parseHex(m.asString())) - return RPC::invalid_field_error(jss::marker); - } - - auto const first = keylet::nftpage(keylet::nftpage_min(accountID), marker); - auto const last = keylet::nftpage_max(accountID); - - auto cp = ledger->read( - Keylet(ltNFTOKEN_PAGE, ledger->succ(first.key, last.key.next()).value_or(last.key))); - - std::uint32_t cnt = 0; - auto& nfts = (result[jss::account_nfts] = Json::arrayValue); - - // Continue iteration from the current page: - bool pastMarker = marker.isZero(); - bool markerFound = false; - uint256 const maskedMarker = marker & nft::pageMask; - while (cp) - { - auto arr = cp->getFieldArray(sfNFTokens); - - for (auto const& o : arr) - { - // Scrolling past the marker gets weird. We need to look at - // a couple of conditions. - // - // 1. If the low 96-bits don't match, then we compare only - // against the low 96-bits, since that's what determines - // the sort order of the pages. - // - // 2. However, within one page there can be a number of - // NFTokenIDs that all have the same low 96 bits. If we're - // in that case then we need to compare against the full - // 256 bits. - uint256 const nftokenID = o[sfNFTokenID]; - uint256 const maskedNftokenID = nftokenID & nft::pageMask; - - if (!pastMarker) - { - if (maskedNftokenID < maskedMarker) - continue; - - if (maskedNftokenID == maskedMarker && nftokenID < marker) - continue; - - if (nftokenID == marker) - { - markerFound = true; - continue; - } - } - - if (markerSet && !markerFound) - return RPC::invalid_field_error(jss::marker); - - pastMarker = true; - - { - Json::Value& obj = nfts.append(o.getJson(JsonOptions::none)); - - // Pull out the components of the nft ID. - obj[sfFlags.jsonName] = nft::getFlags(nftokenID); - obj[sfIssuer.jsonName] = to_string(nft::getIssuer(nftokenID)); - obj[sfNFTokenTaxon.jsonName] = nft::toUInt32(nft::getTaxon(nftokenID)); - obj[jss::nft_serial] = nft::getSerial(nftokenID); - if (std::uint16_t const xferFee = {nft::getTransferFee(nftokenID)}) - obj[sfTransferFee.jsonName] = xferFee; - } - - if (++cnt == limit) - { - result[jss::limit] = limit; - result[jss::marker] = to_string(o.getFieldH256(sfNFTokenID)); - return result; - } - } - - if (auto npm = (*cp)[~sfNextPageMin]) - { - cp = ledger->read(Keylet(ltNFTOKEN_PAGE, *npm)); - } - else - { - cp = nullptr; - } - } - - if (markerSet && !markerFound) - return RPC::invalid_field_error(jss::marker); - - result[jss::account] = toBase58(accountID); - context.loadType = Resource::feeMediumBurdenRPC; - return result; -} - /** Gathers all objects for an account in a ledger. @param ledger Ledger to search account objects. @param account AccountID to find objects for. diff --git a/src/xrpld/rpc/handlers/AccountOffers.cpp b/src/xrpld/rpc/handlers/account/AccountOffers.cpp similarity index 100% rename from src/xrpld/rpc/handlers/AccountOffers.cpp rename to src/xrpld/rpc/handlers/account/AccountOffers.cpp diff --git a/src/xrpld/rpc/handlers/AccountTx.cpp b/src/xrpld/rpc/handlers/account/AccountTx.cpp similarity index 99% rename from src/xrpld/rpc/handlers/AccountTx.cpp rename to src/xrpld/rpc/handlers/account/AccountTx.cpp index f46a71308c..acd5912ee0 100644 --- a/src/xrpld/rpc/handlers/AccountTx.cpp +++ b/src/xrpld/rpc/handlers/account/AccountTx.cpp @@ -364,7 +364,7 @@ populateJsonResponse( // resume previous query // } Json::Value -doAccountTxJson(RPC::JsonContext& context) +doAccountTx(RPC::JsonContext& context) { if (!context.app.config().useTxTables()) return rpcError(rpcNOT_ENABLED); diff --git a/src/xrpld/rpc/handlers/GatewayBalances.cpp b/src/xrpld/rpc/handlers/account/GatewayBalances.cpp similarity index 100% rename from src/xrpld/rpc/handlers/GatewayBalances.cpp rename to src/xrpld/rpc/handlers/account/GatewayBalances.cpp diff --git a/src/xrpld/rpc/handlers/NoRippleCheck.cpp b/src/xrpld/rpc/handlers/account/NoRippleCheck.cpp similarity index 100% rename from src/xrpld/rpc/handlers/NoRippleCheck.cpp rename to src/xrpld/rpc/handlers/account/NoRippleCheck.cpp diff --git a/src/xrpld/rpc/handlers/OwnerInfo.cpp b/src/xrpld/rpc/handlers/account/OwnerInfo.cpp similarity index 100% rename from src/xrpld/rpc/handlers/OwnerInfo.cpp rename to src/xrpld/rpc/handlers/account/OwnerInfo.cpp diff --git a/src/xrpld/rpc/handlers/BlackList.cpp b/src/xrpld/rpc/handlers/admin/BlackList.cpp similarity index 100% rename from src/xrpld/rpc/handlers/BlackList.cpp rename to src/xrpld/rpc/handlers/admin/BlackList.cpp diff --git a/src/xrpld/rpc/handlers/UnlList.cpp b/src/xrpld/rpc/handlers/admin/UnlList.cpp similarity index 100% rename from src/xrpld/rpc/handlers/UnlList.cpp rename to src/xrpld/rpc/handlers/admin/UnlList.cpp diff --git a/src/xrpld/rpc/handlers/CanDelete.cpp b/src/xrpld/rpc/handlers/admin/data/CanDelete.cpp similarity index 100% rename from src/xrpld/rpc/handlers/CanDelete.cpp rename to src/xrpld/rpc/handlers/admin/data/CanDelete.cpp diff --git a/src/xrpld/rpc/handlers/LedgerCleanerHandler.cpp b/src/xrpld/rpc/handlers/admin/data/LedgerCleaner.cpp similarity index 100% rename from src/xrpld/rpc/handlers/LedgerCleanerHandler.cpp rename to src/xrpld/rpc/handlers/admin/data/LedgerCleaner.cpp diff --git a/src/xrpld/rpc/handlers/LedgerRequest.cpp b/src/xrpld/rpc/handlers/admin/data/LedgerRequest.cpp similarity index 100% rename from src/xrpld/rpc/handlers/LedgerRequest.cpp rename to src/xrpld/rpc/handlers/admin/data/LedgerRequest.cpp diff --git a/src/xrpld/rpc/handlers/ValidationCreate.cpp b/src/xrpld/rpc/handlers/admin/keygen/ValidationCreate.cpp similarity index 100% rename from src/xrpld/rpc/handlers/ValidationCreate.cpp rename to src/xrpld/rpc/handlers/admin/keygen/ValidationCreate.cpp diff --git a/src/xrpld/rpc/handlers/WalletPropose.cpp b/src/xrpld/rpc/handlers/admin/keygen/WalletPropose.cpp similarity index 98% rename from src/xrpld/rpc/handlers/WalletPropose.cpp rename to src/xrpld/rpc/handlers/admin/keygen/WalletPropose.cpp index a5005ce701..ec06017b1b 100644 --- a/src/xrpld/rpc/handlers/WalletPropose.cpp +++ b/src/xrpld/rpc/handlers/admin/keygen/WalletPropose.cpp @@ -1,6 +1,6 @@ #include #include -#include +#include #include #include diff --git a/src/xrpld/rpc/handlers/WalletPropose.h b/src/xrpld/rpc/handlers/admin/keygen/WalletPropose.h similarity index 100% rename from src/xrpld/rpc/handlers/WalletPropose.h rename to src/xrpld/rpc/handlers/admin/keygen/WalletPropose.h diff --git a/src/xrpld/rpc/handlers/LogLevel.cpp b/src/xrpld/rpc/handlers/admin/log/LogLevel.cpp similarity index 100% rename from src/xrpld/rpc/handlers/LogLevel.cpp rename to src/xrpld/rpc/handlers/admin/log/LogLevel.cpp diff --git a/src/xrpld/rpc/handlers/LogRotate.cpp b/src/xrpld/rpc/handlers/admin/log/LogRotate.cpp similarity index 100% rename from src/xrpld/rpc/handlers/LogRotate.cpp rename to src/xrpld/rpc/handlers/admin/log/LogRotate.cpp diff --git a/src/xrpld/rpc/handlers/Connect.cpp b/src/xrpld/rpc/handlers/admin/peer/Connect.cpp similarity index 100% rename from src/xrpld/rpc/handlers/Connect.cpp rename to src/xrpld/rpc/handlers/admin/peer/Connect.cpp diff --git a/src/xrpld/rpc/handlers/Reservations.cpp b/src/xrpld/rpc/handlers/admin/peer/PeerReservationsAdd.cpp similarity index 63% rename from src/xrpld/rpc/handlers/Reservations.cpp rename to src/xrpld/rpc/handlers/admin/peer/PeerReservationsAdd.cpp index fb874247ad..dcd97bb2e4 100644 --- a/src/xrpld/rpc/handlers/Reservations.cpp +++ b/src/xrpld/rpc/handlers/admin/peer/PeerReservationsAdd.cpp @@ -9,7 +9,6 @@ #include #include -#include namespace xrpl { @@ -66,46 +65,4 @@ doPeerReservationsAdd(RPC::JsonContext& context) return result; } -Json::Value -doPeerReservationsDel(RPC::JsonContext& context) -{ - auto const& params = context.params; - - // We repeat much of the parameter parsing from `doPeerReservationsAdd`. - if (!params.isMember(jss::public_key)) - return RPC::missing_field_error(jss::public_key); - if (!params[jss::public_key].isString()) - return RPC::expected_field_error(jss::public_key, "a string"); - - std::optional optPk = - parseBase58(TokenType::NodePublic, params[jss::public_key].asString()); - if (!optPk) - return rpcError(rpcPUBLIC_MALFORMED); - PublicKey const& nodeId = *optPk; - - auto const previous = context.app.getPeerReservations().erase(nodeId); - - Json::Value result{Json::objectValue}; - if (previous) - { - result[jss::previous] = previous->toJson(); - } - return result; -} - -Json::Value -doPeerReservationsList(RPC::JsonContext& context) -{ - auto const& reservations = context.app.getPeerReservations().list(); - // Enumerate the reservations in context.app.getPeerReservations() - // as a Json::Value. - Json::Value result{Json::objectValue}; - Json::Value& jaReservations = result[jss::reservations] = Json::arrayValue; - for (auto const& reservation : reservations) - { - jaReservations.append(reservation.toJson()); - } - return result; -} - } // namespace xrpl diff --git a/src/xrpld/rpc/handlers/admin/peer/PeerReservationsDel.cpp b/src/xrpld/rpc/handlers/admin/peer/PeerReservationsDel.cpp new file mode 100644 index 0000000000..14d017779d --- /dev/null +++ b/src/xrpld/rpc/handlers/admin/peer/PeerReservationsDel.cpp @@ -0,0 +1,41 @@ +#include +#include + +#include +#include +#include +#include +#include + +#include + +namespace xrpl { + +Json::Value +doPeerReservationsDel(RPC::JsonContext& context) +{ + auto const& params = context.params; + + // We repeat much of the parameter parsing from `doPeerReservationsAdd`. + if (!params.isMember(jss::public_key)) + return RPC::missing_field_error(jss::public_key); + if (!params[jss::public_key].isString()) + return RPC::expected_field_error(jss::public_key, "a string"); + + std::optional optPk = + parseBase58(TokenType::NodePublic, params[jss::public_key].asString()); + if (!optPk) + return rpcError(rpcPUBLIC_MALFORMED); + PublicKey const& nodeId = *optPk; + + auto const previous = context.app.getPeerReservations().erase(nodeId); + + Json::Value result{Json::objectValue}; + if (previous) + { + result[jss::previous] = previous->toJson(); + } + return result; +} + +} // namespace xrpl diff --git a/src/xrpld/rpc/handlers/admin/peer/PeerReservationsList.cpp b/src/xrpld/rpc/handlers/admin/peer/PeerReservationsList.cpp new file mode 100644 index 0000000000..119af3f73c --- /dev/null +++ b/src/xrpld/rpc/handlers/admin/peer/PeerReservationsList.cpp @@ -0,0 +1,24 @@ +#include +#include + +#include +#include + +namespace xrpl { + +Json::Value +doPeerReservationsList(RPC::JsonContext& context) +{ + auto const& reservations = context.app.getPeerReservations().list(); + // Enumerate the reservations in context.app.getPeerReservations() + // as a Json::Value. + Json::Value result{Json::objectValue}; + Json::Value& jaReservations = result[jss::reservations] = Json::arrayValue; + for (auto const& reservation : reservations) + { + jaReservations.append(reservation.toJson()); + } + return result; +} + +} // namespace xrpl diff --git a/src/xrpld/rpc/handlers/Peers.cpp b/src/xrpld/rpc/handlers/admin/peer/Peers.cpp similarity index 100% rename from src/xrpld/rpc/handlers/Peers.cpp rename to src/xrpld/rpc/handlers/admin/peer/Peers.cpp diff --git a/src/xrpld/rpc/handlers/LedgerAccept.cpp b/src/xrpld/rpc/handlers/admin/server_control/LedgerAccept.cpp similarity index 100% rename from src/xrpld/rpc/handlers/LedgerAccept.cpp rename to src/xrpld/rpc/handlers/admin/server_control/LedgerAccept.cpp diff --git a/src/xrpld/rpc/handlers/Stop.cpp b/src/xrpld/rpc/handlers/admin/server_control/Stop.cpp similarity index 100% rename from src/xrpld/rpc/handlers/Stop.cpp rename to src/xrpld/rpc/handlers/admin/server_control/Stop.cpp diff --git a/src/xrpld/rpc/handlers/PayChanClaim.cpp b/src/xrpld/rpc/handlers/admin/signing/ChannelAuthorize.cpp similarity index 59% rename from src/xrpld/rpc/handlers/PayChanClaim.cpp rename to src/xrpld/rpc/handlers/admin/signing/ChannelAuthorize.cpp index b24a241147..73d185be44 100644 --- a/src/xrpld/rpc/handlers/PayChanClaim.cpp +++ b/src/xrpld/rpc/handlers/admin/signing/ChannelAuthorize.cpp @@ -3,7 +3,6 @@ #include #include -#include #include #include #include @@ -83,61 +82,4 @@ doChannelAuthorize(RPC::JsonContext& context) return result; } -// { -// public_key: -// channel_id: 256-bit channel id -// drops: 64-bit uint (as string) -// signature: signature to verify -// } -Json::Value -doChannelVerify(RPC::JsonContext& context) -{ - auto const& params(context.params); - for (auto const& p : {jss::public_key, jss::channel_id, jss::amount, jss::signature}) - { - if (!params.isMember(p)) - return RPC::missing_field_error(p); - } - - std::optional pk; - { - std::string const strPk = params[jss::public_key].asString(); - pk = parseBase58(TokenType::AccountPublic, strPk); - - if (!pk) - { - auto pkHex = strUnHex(strPk); - if (!pkHex) - return rpcError(rpcPUBLIC_MALFORMED); - auto const pkType = publicKeyType(makeSlice(*pkHex)); - if (!pkType) - return rpcError(rpcPUBLIC_MALFORMED); - pk.emplace(makeSlice(*pkHex)); - } - } - - uint256 channelId; - if (!channelId.parseHex(params[jss::channel_id].asString())) - return rpcError(rpcCHANNEL_MALFORMED); - - std::optional const optDrops = - params[jss::amount].isString() ? to_uint64(params[jss::amount].asString()) : std::nullopt; - - if (!optDrops) - return rpcError(rpcCHANNEL_AMT_MALFORMED); - - std::uint64_t const drops = *optDrops; - - auto sig = strUnHex(params[jss::signature].asString()); - if (!sig || sig->empty()) - return rpcError(rpcINVALID_PARAMS); - - Serializer msg; - serializePayChanAuthorization(msg, channelId, XRPAmount(drops)); - - Json::Value result; - result[jss::signature_verified] = verify(*pk, msg.slice(), makeSlice(*sig)); - return result; -} - } // namespace xrpl diff --git a/src/xrpld/rpc/handlers/SignHandler.cpp b/src/xrpld/rpc/handlers/admin/signing/Sign.cpp similarity index 100% rename from src/xrpld/rpc/handlers/SignHandler.cpp rename to src/xrpld/rpc/handlers/admin/signing/Sign.cpp diff --git a/src/xrpld/rpc/handlers/SignFor.cpp b/src/xrpld/rpc/handlers/admin/signing/SignFor.cpp similarity index 100% rename from src/xrpld/rpc/handlers/SignFor.cpp rename to src/xrpld/rpc/handlers/admin/signing/SignFor.cpp diff --git a/src/xrpld/rpc/handlers/ConsensusInfo.cpp b/src/xrpld/rpc/handlers/admin/status/ConsensusInfo.cpp similarity index 100% rename from src/xrpld/rpc/handlers/ConsensusInfo.cpp rename to src/xrpld/rpc/handlers/admin/status/ConsensusInfo.cpp diff --git a/src/xrpld/rpc/handlers/FetchInfo.cpp b/src/xrpld/rpc/handlers/admin/status/FetchInfo.cpp similarity index 100% rename from src/xrpld/rpc/handlers/FetchInfo.cpp rename to src/xrpld/rpc/handlers/admin/status/FetchInfo.cpp diff --git a/src/xrpld/rpc/handlers/GetCounts.cpp b/src/xrpld/rpc/handlers/admin/status/GetCounts.cpp similarity index 100% rename from src/xrpld/rpc/handlers/GetCounts.cpp rename to src/xrpld/rpc/handlers/admin/status/GetCounts.cpp diff --git a/src/xrpld/rpc/handlers/GetCounts.h b/src/xrpld/rpc/handlers/admin/status/GetCounts.h similarity index 100% rename from src/xrpld/rpc/handlers/GetCounts.h rename to src/xrpld/rpc/handlers/admin/status/GetCounts.h diff --git a/src/xrpld/rpc/handlers/Print.cpp b/src/xrpld/rpc/handlers/admin/status/Print.cpp similarity index 100% rename from src/xrpld/rpc/handlers/Print.cpp rename to src/xrpld/rpc/handlers/admin/status/Print.cpp diff --git a/src/xrpld/rpc/handlers/ValidatorInfo.cpp b/src/xrpld/rpc/handlers/admin/status/ValidatorInfo.cpp similarity index 100% rename from src/xrpld/rpc/handlers/ValidatorInfo.cpp rename to src/xrpld/rpc/handlers/admin/status/ValidatorInfo.cpp diff --git a/src/xrpld/rpc/handlers/ValidatorListSites.cpp b/src/xrpld/rpc/handlers/admin/status/ValidatorListSites.cpp similarity index 100% rename from src/xrpld/rpc/handlers/ValidatorListSites.cpp rename to src/xrpld/rpc/handlers/admin/status/ValidatorListSites.cpp diff --git a/src/xrpld/rpc/handlers/Validators.cpp b/src/xrpld/rpc/handlers/admin/status/Validators.cpp similarity index 100% rename from src/xrpld/rpc/handlers/Validators.cpp rename to src/xrpld/rpc/handlers/admin/status/Validators.cpp diff --git a/src/xrpld/rpc/handlers/LedgerHandler.cpp b/src/xrpld/rpc/handlers/ledger/Ledger.cpp similarity index 99% rename from src/xrpld/rpc/handlers/LedgerHandler.cpp rename to src/xrpld/rpc/handlers/ledger/Ledger.cpp index 0707ad1ffe..6bf627d29c 100644 --- a/src/xrpld/rpc/handlers/LedgerHandler.cpp +++ b/src/xrpld/rpc/handlers/ledger/Ledger.cpp @@ -3,7 +3,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/xrpld/rpc/handlers/LedgerHandler.h b/src/xrpld/rpc/handlers/ledger/Ledger.h similarity index 100% rename from src/xrpld/rpc/handlers/LedgerHandler.h rename to src/xrpld/rpc/handlers/ledger/Ledger.h diff --git a/src/xrpld/rpc/handlers/LedgerClosed.cpp b/src/xrpld/rpc/handlers/ledger/LedgerClosed.cpp similarity index 100% rename from src/xrpld/rpc/handlers/LedgerClosed.cpp rename to src/xrpld/rpc/handlers/ledger/LedgerClosed.cpp diff --git a/src/xrpld/rpc/handlers/LedgerCurrent.cpp b/src/xrpld/rpc/handlers/ledger/LedgerCurrent.cpp similarity index 100% rename from src/xrpld/rpc/handlers/LedgerCurrent.cpp rename to src/xrpld/rpc/handlers/ledger/LedgerCurrent.cpp diff --git a/src/xrpld/rpc/handlers/LedgerData.cpp b/src/xrpld/rpc/handlers/ledger/LedgerData.cpp similarity index 100% rename from src/xrpld/rpc/handlers/LedgerData.cpp rename to src/xrpld/rpc/handlers/ledger/LedgerData.cpp diff --git a/src/xrpld/rpc/handlers/LedgerDiff.cpp b/src/xrpld/rpc/handlers/ledger/LedgerDiff.cpp similarity index 100% rename from src/xrpld/rpc/handlers/LedgerDiff.cpp rename to src/xrpld/rpc/handlers/ledger/LedgerDiff.cpp diff --git a/src/xrpld/rpc/handlers/LedgerEntry.cpp b/src/xrpld/rpc/handlers/ledger/LedgerEntry.cpp similarity index 99% rename from src/xrpld/rpc/handlers/LedgerEntry.cpp rename to src/xrpld/rpc/handlers/ledger/LedgerEntry.cpp index d27574944d..377983718e 100644 --- a/src/xrpld/rpc/handlers/LedgerEntry.cpp +++ b/src/xrpld/rpc/handlers/ledger/LedgerEntry.cpp @@ -1,7 +1,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/xrpld/rpc/handlers/LedgerEntryHelpers.h b/src/xrpld/rpc/handlers/ledger/LedgerEntryHelpers.h similarity index 100% rename from src/xrpld/rpc/handlers/LedgerEntryHelpers.h rename to src/xrpld/rpc/handlers/ledger/LedgerEntryHelpers.h diff --git a/src/xrpld/rpc/handlers/LedgerHeader.cpp b/src/xrpld/rpc/handlers/ledger/LedgerHeader.cpp similarity index 100% rename from src/xrpld/rpc/handlers/LedgerHeader.cpp rename to src/xrpld/rpc/handlers/ledger/LedgerHeader.cpp diff --git a/src/xrpld/rpc/handlers/AMMInfo.cpp b/src/xrpld/rpc/handlers/orderbook/AMMInfo.cpp similarity index 100% rename from src/xrpld/rpc/handlers/AMMInfo.cpp rename to src/xrpld/rpc/handlers/orderbook/AMMInfo.cpp diff --git a/src/xrpld/rpc/handlers/orderbook/BookChanges.cpp b/src/xrpld/rpc/handlers/orderbook/BookChanges.cpp new file mode 100644 index 0000000000..83b26729a1 --- /dev/null +++ b/src/xrpld/rpc/handlers/orderbook/BookChanges.cpp @@ -0,0 +1,21 @@ +#include +#include +#include + +#include + +namespace xrpl { + +Json::Value +doBookChanges(RPC::JsonContext& context) +{ + std::shared_ptr ledger; + + Json::Value result = RPC::lookupLedger(ledger, context); + if (ledger == nullptr) + return result; + + return RPC::computeBookChanges(ledger); +} + +} // namespace xrpl diff --git a/src/xrpld/rpc/handlers/BookOffers.cpp b/src/xrpld/rpc/handlers/orderbook/BookOffers.cpp similarity index 95% rename from src/xrpld/rpc/handlers/BookOffers.cpp rename to src/xrpld/rpc/handlers/orderbook/BookOffers.cpp index ec53473821..33d1e938ad 100644 --- a/src/xrpld/rpc/handlers/BookOffers.cpp +++ b/src/xrpld/rpc/handlers/orderbook/BookOffers.cpp @@ -1,5 +1,4 @@ #include -#include #include #include #include @@ -205,16 +204,4 @@ doBookOffers(RPC::JsonContext& context) return jvResult; } -Json::Value -doBookChanges(RPC::JsonContext& context) -{ - std::shared_ptr ledger; - - Json::Value result = RPC::lookupLedger(ledger, context); - if (ledger == nullptr) - return result; - - return RPC::computeBookChanges(ledger); -} - } // namespace xrpl diff --git a/src/xrpld/rpc/handlers/DepositAuthorized.cpp b/src/xrpld/rpc/handlers/orderbook/DepositAuthorized.cpp similarity index 100% rename from src/xrpld/rpc/handlers/DepositAuthorized.cpp rename to src/xrpld/rpc/handlers/orderbook/DepositAuthorized.cpp diff --git a/src/xrpld/rpc/handlers/GetAggregatePrice.cpp b/src/xrpld/rpc/handlers/orderbook/GetAggregatePrice.cpp similarity index 100% rename from src/xrpld/rpc/handlers/GetAggregatePrice.cpp rename to src/xrpld/rpc/handlers/orderbook/GetAggregatePrice.cpp diff --git a/src/xrpld/rpc/handlers/orderbook/NFTBuyOffers.cpp b/src/xrpld/rpc/handlers/orderbook/NFTBuyOffers.cpp new file mode 100644 index 0000000000..3ee8935f3a --- /dev/null +++ b/src/xrpld/rpc/handlers/orderbook/NFTBuyOffers.cpp @@ -0,0 +1,24 @@ +#include +#include + +#include +#include +#include + +namespace xrpl { + +Json::Value +doNFTBuyOffers(RPC::JsonContext& context) +{ + if (!context.params.isMember(jss::nft_id)) + return RPC::missing_field_error(jss::nft_id); + + uint256 nftId; + + if (!nftId.parseHex(context.params[jss::nft_id].asString())) + return RPC::invalid_field_error(jss::nft_id); + + return enumerateNFTOffers(context, nftId, keylet::nft_buys(nftId)); +} + +} // namespace xrpl diff --git a/src/xrpld/rpc/handlers/NFTOffers.cpp b/src/xrpld/rpc/handlers/orderbook/NFTOffersHelpers.h similarity index 82% rename from src/xrpld/rpc/handlers/NFTOffers.cpp rename to src/xrpld/rpc/handlers/orderbook/NFTOffersHelpers.h index 5fe2e3bede..8f68aeaadd 100644 --- a/src/xrpld/rpc/handlers/NFTOffers.cpp +++ b/src/xrpld/rpc/handlers/orderbook/NFTOffersHelpers.h @@ -1,3 +1,5 @@ +#pragma once + #include #include #include @@ -14,7 +16,7 @@ namespace xrpl { -static void +inline void appendNftOfferJson( Application const& app, std::shared_ptr const& offer, @@ -42,7 +44,7 @@ appendNftOfferJson( // limit: integer // optional // marker: opaque // optional, resume previous query // } -static Json::Value +inline Json::Value enumerateNFTOffers(RPC::JsonContext& context, uint256 const& nftId, Keylet const& directory) { unsigned int limit = 0; @@ -127,32 +129,4 @@ enumerateNFTOffers(RPC::JsonContext& context, uint256 const& nftId, Keylet const return result; } -Json::Value -doNFTSellOffers(RPC::JsonContext& context) -{ - if (!context.params.isMember(jss::nft_id)) - return RPC::missing_field_error(jss::nft_id); - - uint256 nftId; - - if (!nftId.parseHex(context.params[jss::nft_id].asString())) - return RPC::invalid_field_error(jss::nft_id); - - return enumerateNFTOffers(context, nftId, keylet::nft_sells(nftId)); -} - -Json::Value -doNFTBuyOffers(RPC::JsonContext& context) -{ - if (!context.params.isMember(jss::nft_id)) - return RPC::missing_field_error(jss::nft_id); - - uint256 nftId; - - if (!nftId.parseHex(context.params[jss::nft_id].asString())) - return RPC::invalid_field_error(jss::nft_id); - - return enumerateNFTOffers(context, nftId, keylet::nft_buys(nftId)); -} - } // namespace xrpl diff --git a/src/xrpld/rpc/handlers/orderbook/NFTSellOffers.cpp b/src/xrpld/rpc/handlers/orderbook/NFTSellOffers.cpp new file mode 100644 index 0000000000..9dbd9ef49f --- /dev/null +++ b/src/xrpld/rpc/handlers/orderbook/NFTSellOffers.cpp @@ -0,0 +1,24 @@ +#include +#include + +#include +#include +#include + +namespace xrpl { + +Json::Value +doNFTSellOffers(RPC::JsonContext& context) +{ + if (!context.params.isMember(jss::nft_id)) + return RPC::missing_field_error(jss::nft_id); + + uint256 nftId; + + if (!nftId.parseHex(context.params[jss::nft_id].asString())) + return RPC::invalid_field_error(jss::nft_id); + + return enumerateNFTOffers(context, nftId, keylet::nft_sells(nftId)); +} + +} // namespace xrpl diff --git a/src/xrpld/rpc/handlers/PathFind.cpp b/src/xrpld/rpc/handlers/orderbook/PathFind.cpp similarity index 100% rename from src/xrpld/rpc/handlers/PathFind.cpp rename to src/xrpld/rpc/handlers/orderbook/PathFind.cpp diff --git a/src/xrpld/rpc/handlers/RipplePathFind.cpp b/src/xrpld/rpc/handlers/orderbook/RipplePathFind.cpp similarity index 100% rename from src/xrpld/rpc/handlers/RipplePathFind.cpp rename to src/xrpld/rpc/handlers/orderbook/RipplePathFind.cpp diff --git a/src/xrpld/rpc/handlers/Feature1.cpp b/src/xrpld/rpc/handlers/server_info/Feature.cpp similarity index 100% rename from src/xrpld/rpc/handlers/Feature1.cpp rename to src/xrpld/rpc/handlers/server_info/Feature.cpp diff --git a/src/xrpld/rpc/handlers/Fee1.cpp b/src/xrpld/rpc/handlers/server_info/Fee.cpp similarity index 100% rename from src/xrpld/rpc/handlers/Fee1.cpp rename to src/xrpld/rpc/handlers/server_info/Fee.cpp diff --git a/src/xrpld/rpc/handlers/DoManifest.cpp b/src/xrpld/rpc/handlers/server_info/Manifest.cpp similarity index 100% rename from src/xrpld/rpc/handlers/DoManifest.cpp rename to src/xrpld/rpc/handlers/server_info/Manifest.cpp diff --git a/src/xrpld/rpc/handlers/ServerDefinitions.cpp b/src/xrpld/rpc/handlers/server_info/ServerDefinitions.cpp similarity index 100% rename from src/xrpld/rpc/handlers/ServerDefinitions.cpp rename to src/xrpld/rpc/handlers/server_info/ServerDefinitions.cpp diff --git a/src/xrpld/rpc/handlers/ServerInfo.cpp b/src/xrpld/rpc/handlers/server_info/ServerInfo.cpp similarity index 100% rename from src/xrpld/rpc/handlers/ServerInfo.cpp rename to src/xrpld/rpc/handlers/server_info/ServerInfo.cpp diff --git a/src/xrpld/rpc/handlers/ServerState.cpp b/src/xrpld/rpc/handlers/server_info/ServerState.cpp similarity index 100% rename from src/xrpld/rpc/handlers/ServerState.cpp rename to src/xrpld/rpc/handlers/server_info/ServerState.cpp diff --git a/src/xrpld/rpc/handlers/Version.h b/src/xrpld/rpc/handlers/server_info/Version.h similarity index 100% rename from src/xrpld/rpc/handlers/Version.h rename to src/xrpld/rpc/handlers/server_info/Version.h diff --git a/src/xrpld/rpc/handlers/Subscribe.cpp b/src/xrpld/rpc/handlers/subscribe/Subscribe.cpp similarity index 100% rename from src/xrpld/rpc/handlers/Subscribe.cpp rename to src/xrpld/rpc/handlers/subscribe/Subscribe.cpp diff --git a/src/xrpld/rpc/handlers/Unsubscribe.cpp b/src/xrpld/rpc/handlers/subscribe/Unsubscribe.cpp similarity index 100% rename from src/xrpld/rpc/handlers/Unsubscribe.cpp rename to src/xrpld/rpc/handlers/subscribe/Unsubscribe.cpp diff --git a/src/xrpld/rpc/handlers/Simulate.cpp b/src/xrpld/rpc/handlers/transaction/Simulate.cpp similarity index 100% rename from src/xrpld/rpc/handlers/Simulate.cpp rename to src/xrpld/rpc/handlers/transaction/Simulate.cpp diff --git a/src/xrpld/rpc/handlers/Submit.cpp b/src/xrpld/rpc/handlers/transaction/Submit.cpp similarity index 100% rename from src/xrpld/rpc/handlers/Submit.cpp rename to src/xrpld/rpc/handlers/transaction/Submit.cpp diff --git a/src/xrpld/rpc/handlers/SubmitMultiSigned.cpp b/src/xrpld/rpc/handlers/transaction/SubmitMultiSigned.cpp similarity index 100% rename from src/xrpld/rpc/handlers/SubmitMultiSigned.cpp rename to src/xrpld/rpc/handlers/transaction/SubmitMultiSigned.cpp diff --git a/src/xrpld/rpc/handlers/TransactionEntry.cpp b/src/xrpld/rpc/handlers/transaction/TransactionEntry.cpp similarity index 100% rename from src/xrpld/rpc/handlers/TransactionEntry.cpp rename to src/xrpld/rpc/handlers/transaction/TransactionEntry.cpp diff --git a/src/xrpld/rpc/handlers/Tx.cpp b/src/xrpld/rpc/handlers/transaction/Tx.cpp similarity index 100% rename from src/xrpld/rpc/handlers/Tx.cpp rename to src/xrpld/rpc/handlers/transaction/Tx.cpp diff --git a/src/xrpld/rpc/handlers/TxHistory.cpp b/src/xrpld/rpc/handlers/transaction/TxHistory.cpp similarity index 100% rename from src/xrpld/rpc/handlers/TxHistory.cpp rename to src/xrpld/rpc/handlers/transaction/TxHistory.cpp diff --git a/src/xrpld/rpc/handlers/TxReduceRelay.cpp b/src/xrpld/rpc/handlers/transaction/TxReduceRelay.cpp similarity index 100% rename from src/xrpld/rpc/handlers/TxReduceRelay.cpp rename to src/xrpld/rpc/handlers/transaction/TxReduceRelay.cpp diff --git a/src/xrpld/rpc/handlers/Ping.cpp b/src/xrpld/rpc/handlers/utility/Ping.cpp similarity index 100% rename from src/xrpld/rpc/handlers/Ping.cpp rename to src/xrpld/rpc/handlers/utility/Ping.cpp diff --git a/src/xrpld/rpc/handlers/Random.cpp b/src/xrpld/rpc/handlers/utility/Random.cpp similarity index 100% rename from src/xrpld/rpc/handlers/Random.cpp rename to src/xrpld/rpc/handlers/utility/Random.cpp From 8e05416211f3fc3998d4745da856e40fce382d5b Mon Sep 17 00:00:00 2001 From: Mayukha Vadari Date: Fri, 3 Apr 2026 11:16:50 -0400 Subject: [PATCH 52/53] fix: Change variable signedness and correctly handle `std::optional` (#6657) --- src/libxrpl/tx/transactors/account/AccountDelete.cpp | 2 +- src/xrpld/app/misc/detail/ValidatorList.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libxrpl/tx/transactors/account/AccountDelete.cpp b/src/libxrpl/tx/transactors/account/AccountDelete.cpp index 8c2f23b754..815b314f9f 100644 --- a/src/libxrpl/tx/transactors/account/AccountDelete.cpp +++ b/src/libxrpl/tx/transactors/account/AccountDelete.cpp @@ -292,7 +292,7 @@ AccountDelete::preclaim(PreclaimContext const& ctx) if (!cdirFirst(ctx.view, ownerDirKeylet.key, sleDirNode, uDirEntry, dirEntry)) return tesSUCCESS; - std::int32_t deletableDirEntryCount{0}; + std::uint32_t deletableDirEntryCount{0}; do { // Make sure any directory node types that we find are the kind diff --git a/src/xrpld/app/misc/detail/ValidatorList.cpp b/src/xrpld/app/misc/detail/ValidatorList.cpp index bed91afc44..0b203114b3 100644 --- a/src/xrpld/app/misc/detail/ValidatorList.cpp +++ b/src/xrpld/app/misc/detail/ValidatorList.cpp @@ -1710,7 +1710,7 @@ ValidatorList::for_each_available( if (plCollection.status != PublisherStatus::available) continue; XRPL_ASSERT( - plCollection.maxSequence != 0, + plCollection.maxSequence.value_or(0) != 0, "xrpl::ValidatorList::for_each_available : nonzero maxSequence"); func( plCollection.rawManifest, From c0ee81366674cd7ca395139d3bc2ea2cc0f943b2 Mon Sep 17 00:00:00 2001 From: Vito Tumas <5780819+Tapanito@users.noreply.github.com> Date: Fri, 3 Apr 2026 19:41:45 +0200 Subject: [PATCH 53/53] fix: Add assorted Lending Protocol fixes (#6678) Co-authored-by: Shawn Xie <35279399+shawnxie999@users.noreply.github.com> --- .../tx/invariants/LoanBrokerInvariant.cpp | 28 +++-- .../tx/transactors/lending/LoanManage.cpp | 34 +++--- .../tx/transactors/lending/LoanPay.cpp | 2 +- src/test/app/Invariants_test.cpp | 104 +++++++++++++----- src/test/app/Loan_test.cpp | 14 ++- 5 files changed, 133 insertions(+), 49 deletions(-) diff --git a/src/libxrpl/tx/invariants/LoanBrokerInvariant.cpp b/src/libxrpl/tx/invariants/LoanBrokerInvariant.cpp index 2bc9e622ad..8ee0a0deb8 100644 --- a/src/libxrpl/tx/invariants/LoanBrokerInvariant.cpp +++ b/src/libxrpl/tx/invariants/LoanBrokerInvariant.cpp @@ -175,18 +175,32 @@ ValidLoanBroker::finalize( return false; } auto const& vaultAsset = vault->at(sfAsset); - if (after->at(sfCoverAvailable) < accountHolds( - view, - after->at(sfAccount), - vaultAsset, - FreezeHandling::fhIGNORE_FREEZE, - AuthHandling::ahIGNORE_AUTH, - j)) + auto const pseudoBalance = accountHolds( + view, + after->at(sfAccount), + vaultAsset, + FreezeHandling::fhIGNORE_FREEZE, + AuthHandling::ahIGNORE_AUTH, + j); + if (after->at(sfCoverAvailable) < pseudoBalance) { JLOG(j.fatal()) << "Invariant failed: Loan Broker cover available " "is less than pseudo-account asset balance"; return false; } + + if (view.rules().enabled(fixSecurity3_1_3)) + { + // Don't check the balance when LoanBroker is deleted, + // sfCoverAvailable is not zeroed + if (tx.getTxnType() != ttLOAN_BROKER_DELETE && + after->at(sfCoverAvailable) > pseudoBalance) + { + JLOG(j.fatal()) << "Invariant failed: Loan Broker cover available is greater " + "than pseudo-account asset balance"; + return false; + } + } } return true; } diff --git a/src/libxrpl/tx/transactors/lending/LoanManage.cpp b/src/libxrpl/tx/transactors/lending/LoanManage.cpp index adef5374b9..8c3e625963 100644 --- a/src/libxrpl/tx/transactors/lending/LoanManage.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanManage.cpp @@ -386,21 +386,29 @@ LoanManage::doApply() return tefBAD_LEDGER; // LCOV_EXCL_LINE auto const vaultAsset = vaultSle->at(sfAsset); - // Valid flag combinations are checked in preflight. No flags is valid - - // just a noop. - if (tx.isFlag(tfLoanDefault)) - return defaultLoan(view, loanSle, brokerSle, vaultSle, vaultAsset, j_); - if (tx.isFlag(tfLoanImpair)) - return impairLoan(view, loanSle, vaultSle, vaultAsset, j_); - if (tx.isFlag(tfLoanUnimpair)) - return unimpairLoan(view, loanSle, vaultSle, vaultAsset, j_); - // Noop, as described above. + auto const result = [&]() -> TER { + // Valid flag combinations are checked in preflight. No flags is valid - + // just a noop. + if (tx.isFlag(tfLoanDefault)) + return defaultLoan(view, loanSle, brokerSle, vaultSle, vaultAsset, j_); + if (tx.isFlag(tfLoanImpair)) + return impairLoan(view, loanSle, vaultSle, vaultAsset, j_); + if (tx.isFlag(tfLoanUnimpair)) + return unimpairLoan(view, loanSle, vaultSle, vaultAsset, j_); + // Noop, as described above. + return tesSUCCESS; + }(); - associateAsset(*loanSle, vaultAsset); - associateAsset(*brokerSle, vaultAsset); - associateAsset(*vaultSle, vaultAsset); + // Pre-amendment, associateAsset was only called on the noop (no flags) + // path. Post-amendment, we call associateAsset on all successful paths. + if (view.rules().enabled(fixSecurity3_1_3) && isTesSuccess(result)) + { + associateAsset(*loanSle, vaultAsset); + associateAsset(*brokerSle, vaultAsset); + associateAsset(*vaultSle, vaultAsset); + } - return tesSUCCESS; + return result; } //------------------------------------------------------------------------------ diff --git a/src/libxrpl/tx/transactors/lending/LoanPay.cpp b/src/libxrpl/tx/transactors/lending/LoanPay.cpp index f748a670fd..d400fb3630 100644 --- a/src/libxrpl/tx/transactors/lending/LoanPay.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanPay.cpp @@ -155,7 +155,7 @@ LoanPay::preclaim(PreclaimContext const& ctx) if (tx.isFlag(tfLoanOverpayment) && !loanSle->isFlag(lsfLoanOverpayment)) { JLOG(ctx.j.warn()) << "Requested overpayment on a loan that doesn't allow it"; - return temINVALID_FLAG; + return ctx.view.rules().enabled(fixSecurity3_1_3) ? TER{tecNO_PERMISSION} : temINVALID_FLAG; } auto const principalOutstanding = loanSle->at(sfPrincipalOutstanding); diff --git a/src/test/app/Invariants_test.cpp b/src/test/app/Invariants_test.cpp index ef0624b481..72ed7ba57b 100644 --- a/src/test/app/Invariants_test.cpp +++ b/src/test/app/Invariants_test.cpp @@ -2046,36 +2046,36 @@ class Invariants_test : public beast::unit_test::suite { // Initialize with a placeholder value because there's no default // ctor + auto const setupAsset = + [&](Account const& alice, Account const& issuer, Env& env) -> PrettyAsset { + switch (assetType) + { + case Asset::IOU: { + PrettyAsset const iouAsset = issuer["IOU"]; + env(trust(alice, iouAsset(1000))); + env(pay(issuer, alice, iouAsset(1000))); + env.close(); + return iouAsset; + } + case Asset::MPT: { + MPTTester mptt{env, issuer, mptInitNoFund}; + mptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); + PrettyAsset const mptAsset = mptt.issuanceID(); + mptt.authorize({.account = alice}); + env(pay(issuer, alice, mptAsset(1000))); + env.close(); + return mptAsset; + } + case Asset::XRP: + default: + return PrettyAsset{xrpIssue(), 1'000'000}; + } + }; + Keylet loanBrokerKeylet = keylet::amendments(); Preclose const createLoanBroker = [&, this](Account const& alice, Account const& issuer, Env& env) { - PrettyAsset const asset = [&]() { - switch (assetType) - { - case Asset::IOU: { - PrettyAsset const iouAsset = issuer["IOU"]; - env(trust(alice, iouAsset(1000))); - env(pay(issuer, alice, iouAsset(1000))); - env.close(); - return iouAsset; - } - - case Asset::MPT: { - MPTTester mptt{env, issuer, mptInitNoFund}; - mptt.create( - {.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); - PrettyAsset const mptAsset = mptt.issuanceID(); - mptt.authorize({.account = alice}); - env(pay(issuer, alice, mptAsset(1000))); - env.close(); - return mptAsset; - } - - case Asset::XRP: - default: - return PrettyAsset{xrpIssue(), 1'000'000}; - } - }(); + auto const asset = setupAsset(alice, issuer, env); loanBrokerKeylet = this->createLoanBroker(alice, env, asset); return BEAST_EXPECT(env.le(loanBrokerKeylet)); }; @@ -2249,6 +2249,56 @@ class Invariants_test : public beast::unit_test::suite STTx{ttLOAN_BROKER_SET, [](STObject& tx) {}}, {tecINVARIANT_FAILED, tefINVARIANT_FAILED}, createLoanBroker); + + // Test: cover available less than pseudo-account asset balance + { + Keylet brokerKeylet = keylet::amendments(); + Preclose const createBrokerWithCover = + [&, this](Account const& alice, Account const& issuer, Env& env) { + auto const asset = setupAsset(alice, issuer, env); + brokerKeylet = this->createLoanBroker(alice, env, asset); + if (!BEAST_EXPECT(env.le(brokerKeylet))) + return false; + env(loanBroker::coverDeposit(alice, brokerKeylet.key, asset(10))); + env.close(); + return BEAST_EXPECT(env.le(brokerKeylet)); + }; + + doInvariantCheck( + {{"Loan Broker cover available is less than pseudo-account asset balance"}}, + [&](Account const&, Account const&, ApplyContext& ac) { + auto sle = ac.view().peek(brokerKeylet); + if (!BEAST_EXPECT(sle)) + return false; + // Pseudo-account holds 10 units, set cover to 5 + sle->at(sfCoverAvailable) = Number(5); + ac.view().update(sle); + return true; + }, + XRPAmount{}, + STTx{ttLOAN_BROKER_SET, [](STObject& tx) {}}, + {tecINVARIANT_FAILED, tefINVARIANT_FAILED}, + createBrokerWithCover); + } + + // Test: cover available greater than pseudo-account asset balance + // (requires fixSecurity3_1_3) + doInvariantCheck( + {{"Loan Broker cover available is greater than pseudo-account asset balance"}}, + [&](Account const&, Account const&, ApplyContext& ac) { + auto sle = ac.view().peek(loanBrokerKeylet); + if (!BEAST_EXPECT(sle)) + return false; + // Pseudo-account has no cover deposited; set cover + // higher than any incidental balance + sle->at(sfCoverAvailable) = Number(1'000'000); + ac.view().update(sle); + return true; + }, + XRPAmount{}, + STTx{ttLOAN_BROKER_SET, [](STObject& tx) {}}, + {tecINVARIANT_FAILED, tefINVARIANT_FAILED}, + createLoanBroker); } } diff --git a/src/test/app/Loan_test.cpp b/src/test/app/Loan_test.cpp index a63d31f030..05123c11c0 100644 --- a/src/test/app/Loan_test.cpp +++ b/src/test/app/Loan_test.cpp @@ -2071,7 +2071,19 @@ protected: STAmount{broker.asset, state.periodicPayment * Number{15, -1}}, tfLoanOverpayment), fee(XRPAmount{baseFee * (Number{15, -1} / loanPaymentsPerFeeIncrement + 1)}), - ter(temINVALID_FLAG)); + ter(tecNO_PERMISSION)); + + { + env.disableFeature(fixSecurity3_1_3); + env(pay(borrower, + loanKeylet.key, + STAmount{broker.asset, state.periodicPayment * Number{15, -1}}, + tfLoanOverpayment), + fee(XRPAmount{ + baseFee * (Number{15, -1} / loanPaymentsPerFeeIncrement + 1)}), + ter(temINVALID_FLAG)); + env.enableFeature(fixSecurity3_1_3); + } } // Try to send a payment marked as multiple mutually exclusive // payment types. Do not include `txFlags`, so we don't duplicate