From 57e4cbbcd977c7fecb9df1b52a72b5a1d8ff4cf8 Mon Sep 17 00:00:00 2001 From: Alex Kremer Date: Wed, 18 Mar 2026 16:41:49 +0000 Subject: [PATCH] refactor: Add simple clang-tidy readability checks (#6556) This change enables the following clang-tidy checks: - 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-else-after-return, - readability-make-member-function-const, - readability-redundant-casting, - readability-redundant-inline-specifier, - readability-redundant-member-init, - readability-redundant-string-init, - readability-reference-to-constructed-temporary, - readability-static-definition --- .clang-tidy | 32 +- include/xrpl/protocol/Permissions.h | 2 +- include/xrpl/protocol/STObject.h | 2 +- include/xrpl/server/InfoSub.h | 2 +- include/xrpl/tx/invariants/InvariantCheck.h | 20 +- include/xrpl/tx/invariants/MPTInvariant.h | 2 +- include/xrpl/tx/invariants/NFTInvariant.h | 4 +- src/libxrpl/basics/BasicConfig.cpp | 6 +- src/libxrpl/basics/Log.cpp | 4 + src/libxrpl/basics/MallocTrim.cpp | 2 +- src/libxrpl/basics/Number.cpp | 12 +- src/libxrpl/basics/ResolverAsio.cpp | 2 +- src/libxrpl/basics/base64.cpp | 4 +- src/libxrpl/basics/make_SSLContext.cpp | 2 + src/libxrpl/beast/core/SemanticVersion.cpp | 42 ++- src/libxrpl/beast/net/IPEndpoint.cpp | 8 +- src/libxrpl/beast/utility/beast_Journal.cpp | 4 + .../beast/utility/beast_PropertyStream.cpp | 16 + src/libxrpl/core/detail/Workers.cpp | 8 +- src/libxrpl/crypto/RFC1751.cpp | 8 + src/libxrpl/json/Writer.cpp | 8 +- src/libxrpl/json/json_reader.cpp | 32 +- src/libxrpl/json/json_value.cpp | 23 +- src/libxrpl/json/json_valueiterator.cpp | 2 +- src/libxrpl/json/json_writer.cpp | 20 ++ src/libxrpl/ledger/ApplyStateTable.cpp | 6 +- src/libxrpl/ledger/BookListeners.cpp | 2 + src/libxrpl/ledger/CachedView.cpp | 6 + src/libxrpl/ledger/CredentialHelpers.cpp | 10 +- src/libxrpl/ledger/OpenView.cpp | 6 +- src/libxrpl/ledger/PaymentSandbox.cpp | 20 +- src/libxrpl/ledger/RawStateTable.cpp | 14 +- src/libxrpl/ledger/View.cpp | 176 +++++++---- .../nodestore/backend/MemoryFactory.cpp | 4 + src/libxrpl/nodestore/backend/NuDBFactory.cpp | 4 + .../nodestore/backend/RocksDBFactory.cpp | 10 + src/libxrpl/protocol/Feature.cpp | 12 +- src/libxrpl/protocol/Indexes.cpp | 2 +- src/libxrpl/protocol/Issue.cpp | 6 + src/libxrpl/protocol/NFTokenID.cpp | 2 +- src/libxrpl/protocol/Permissions.cpp | 6 +- src/libxrpl/protocol/PublicKey.cpp | 4 +- src/libxrpl/protocol/Rules.cpp | 4 +- src/libxrpl/protocol/STAccount.cpp | 2 +- src/libxrpl/protocol/STAmount.cpp | 40 ++- src/libxrpl/protocol/STLedgerEntry.cpp | 4 + src/libxrpl/protocol/STNumber.cpp | 4 + src/libxrpl/protocol/STObject.cpp | 12 +- src/libxrpl/protocol/STParsedJSON.cpp | 4 + src/libxrpl/protocol/STTx.cpp | 10 +- src/libxrpl/protocol/STVar.cpp | 8 + src/libxrpl/protocol/STVector256.cpp | 2 + src/libxrpl/protocol/Serializer.cpp | 8 +- src/libxrpl/protocol/tokens.cpp | 2 +- src/libxrpl/rdb/SociDB.cpp | 12 + src/libxrpl/server/InfoSub.cpp | 10 +- src/libxrpl/server/LoadFeeTrack.cpp | 10 +- src/libxrpl/server/Port.cpp | 4 +- src/libxrpl/shamap/SHAMap.cpp | 8 + src/libxrpl/shamap/SHAMapDelta.cpp | 24 +- src/libxrpl/shamap/SHAMapInnerNode.cpp | 10 +- src/libxrpl/shamap/SHAMapLeafNode.cpp | 8 + src/libxrpl/shamap/SHAMapNodeID.cpp | 4 + src/libxrpl/shamap/SHAMapSync.cpp | 8 +- src/libxrpl/tx/Transactor.cpp | 8 + src/libxrpl/tx/apply.cpp | 8 + src/libxrpl/tx/applySteps.cpp | 2 + src/libxrpl/tx/invariants/AMMInvariant.cpp | 4 + src/libxrpl/tx/invariants/FreezeInvariant.cpp | 4 + src/libxrpl/tx/invariants/InvariantCheck.cpp | 26 +- src/libxrpl/tx/invariants/MPTInvariant.cpp | 17 +- src/libxrpl/tx/invariants/NFTInvariant.cpp | 4 +- .../invariants/PermissionedDEXInvariant.cpp | 4 + .../PermissionedDomainInvariant.cpp | 5 +- src/libxrpl/tx/invariants/VaultInvariant.cpp | 4 +- src/libxrpl/tx/paths/Flow.cpp | 4 + src/libxrpl/tx/paths/OfferStream.cpp | 2 + .../tx/transactors/account/DeleteAccount.cpp | 2 + .../tx/transactors/account/SetAccount.cpp | 22 +- .../tx/transactors/account/SetSignerList.cpp | 2 +- .../tx/transactors/bridge/XChainBridge.cpp | 38 +++ .../tx/transactors/check/CashCheck.cpp | 2 + .../tx/transactors/delegate/DelegateSet.cpp | 2 + src/libxrpl/tx/transactors/dex/AMMBid.cpp | 35 ++- .../tx/transactors/dex/AMMClawback.cpp | 6 + src/libxrpl/tx/transactors/dex/AMMCreate.cpp | 19 +- src/libxrpl/tx/transactors/dex/AMMDeposit.cpp | 44 ++- src/libxrpl/tx/transactors/dex/AMMHelpers.cpp | 68 ++--- src/libxrpl/tx/transactors/dex/AMMUtils.cpp | 32 +- src/libxrpl/tx/transactors/dex/AMMVote.cpp | 24 +- .../tx/transactors/dex/AMMWithdraw.cpp | 28 +- .../tx/transactors/dex/CreateOffer.cpp | 14 + .../tx/transactors/escrow/EscrowCancel.cpp | 2 + .../tx/transactors/escrow/EscrowCreate.cpp | 2 + .../tx/transactors/escrow/EscrowFinish.cpp | 10 + .../tx/transactors/lending/LendingHelpers.cpp | 78 +++-- .../lending/LoanBrokerCoverClawback.cpp | 6 +- .../tx/transactors/lending/LoanPay.cpp | 14 + .../tx/transactors/lending/LoanSet.cpp | 36 ++- .../tx/transactors/nft/NFTokenAcceptOffer.cpp | 2 + .../tx/transactors/nft/NFTokenMint.cpp | 21 +- .../tx/transactors/nft/NFTokenModify.cpp | 2 +- .../tx/transactors/nft/NFTokenUtils.cpp | 30 ++ .../tx/transactors/oracle/DeleteOracle.cpp | 9 +- .../tx/transactors/oracle/SetOracle.cpp | 10 + .../tx/transactors/payment/Payment.cpp | 30 +- .../payment_channel/PayChanClaim.cpp | 2 + .../payment_channel/PayChanFund.cpp | 2 + src/libxrpl/tx/transactors/system/Batch.cpp | 4 + src/libxrpl/tx/transactors/system/Change.cpp | 4 + src/libxrpl/tx/transactors/token/Clawback.cpp | 6 +- .../token/MPTokenIssuanceCreate.cpp | 2 +- .../transactors/token/MPTokenIssuanceSet.cpp | 26 +- src/libxrpl/tx/transactors/token/SetTrust.cpp | 21 +- .../tx/transactors/vault/VaultClawback.cpp | 4 +- .../tx/transactors/vault/VaultCreate.cpp | 12 +- .../tx/transactors/vault/VaultDeposit.cpp | 6 +- .../tx/transactors/vault/VaultWithdraw.cpp | 2 + src/test/app/AMMCalc_test.cpp | 14 +- src/test/app/AMMClawback_test.cpp | 280 ++++++++++++++++++ src/test/app/AMMExtended_test.cpp | 6 + src/test/app/AMM_test.cpp | 154 +++++++++- src/test/app/AccountSet_test.cpp | 4 + src/test/app/AmendmentTable_test.cpp | 16 +- src/test/app/Check_test.cpp | 46 +-- src/test/app/DNS_test.cpp | 4 +- src/test/app/DepositAuth_test.cpp | 2 + src/test/app/Discrepancy_test.cpp | 10 + src/test/app/EscrowToken_test.cpp | 4 + src/test/app/Flow_test.cpp | 8 + src/test/app/HashRouter_test.cpp | 2 +- src/test/app/Invariants_test.cpp | 53 ++-- src/test/app/LPTokenTransfer_test.cpp | 4 + src/test/app/LedgerLoad_test.cpp | 12 +- src/test/app/LedgerReplay_test.cpp | 10 +- src/test/app/LoanBroker_test.cpp | 28 +- src/test/app/Loan_test.cpp | 120 +++++--- src/test/app/MPToken_test.cpp | 6 + src/test/app/NFTokenBurn_test.cpp | 18 +- src/test/app/NFTokenDir_test.cpp | 4 + src/test/app/NFToken_test.cpp | 18 ++ src/test/app/Offer_test.cpp | 20 +- src/test/app/OversizeMeta_test.cpp | 2 + src/test/app/Path_test.cpp | 2 +- src/test/app/PayChan_test.cpp | 4 + src/test/app/PayStrand_test.cpp | 16 + src/test/app/PermissionedDomains_test.cpp | 10 +- src/test/app/RCLValidations_test.cpp | 4 + src/test/app/ReducedOffer_test.cpp | 2 + src/test/app/SHAMapStore_test.cpp | 4 +- src/test/app/SetTrust_test.cpp | 6 + src/test/app/TheoreticalQuality_test.cpp | 7 +- src/test/app/Ticket_test.cpp | 4 + src/test/app/TrustAndBalance_test.cpp | 4 + src/test/app/TxQ_test.cpp | 4 + src/test/app/ValidatorList_test.cpp | 67 ++++- src/test/app/ValidatorSite_test.cpp | 4 + src/test/app/Vault_test.cpp | 33 ++- src/test/app/XChain_test.cpp | 33 ++- src/test/basics/Buffer_test.cpp | 6 +- src/test/basics/IntrusiveShared_test.cpp | 4 +- src/test/basics/Number_test.cpp | 16 + src/test/basics/PerfLog_test.cpp | 11 +- src/test/basics/XRPAmount_test.cpp | 6 + src/test/beast/LexicalCast_test.cpp | 2 +- src/test/conditions/PreimageSha256_test.cpp | 2 +- src/test/consensus/Consensus_test.cpp | 40 +-- src/test/consensus/LedgerTiming_test.cpp | 6 + src/test/consensus/LedgerTrie_test.cpp | 6 +- src/test/consensus/NegativeUNL_test.cpp | 24 +- src/test/consensus/Validations_test.cpp | 4 + src/test/core/ClosureCounter_test.cpp | 2 +- src/test/core/Config_test.cpp | 26 +- src/test/csf/BasicNetwork_test.cpp | 4 + src/test/csf/impl/ledgers.cpp | 6 + src/test/jtx/Env_test.cpp | 4 +- src/test/jtx/impl/AMM.cpp | 58 +++- src/test/jtx/impl/AMMTest.cpp | 6 + src/test/jtx/impl/Env.cpp | 48 +-- src/test/jtx/impl/JSONRPCClient.cpp | 2 + src/test/jtx/impl/Oracle.cpp | 64 +++- src/test/jtx/impl/WSClient.cpp | 4 + src/test/jtx/impl/amount.cpp | 4 + src/test/jtx/impl/balance.cpp | 2 +- src/test/jtx/impl/directory.cpp | 4 + src/test/jtx/impl/fee.cpp | 4 + src/test/jtx/impl/flags.cpp | 12 + src/test/jtx/impl/mpt.cpp | 52 +++- src/test/jtx/impl/multisign.cpp | 8 + src/test/jtx/impl/sig.cpp | 4 + src/test/jtx/impl/vault.cpp | 2 +- src/test/jtx/impl/xchain_bridge.cpp | 4 + src/test/jtx/vault.h | 2 +- src/test/ledger/BookDirs_test.cpp | 2 + src/test/ledger/Directory_test.cpp | 10 + src/test/nodestore/Timing_test.cpp | 14 +- src/test/nodestore/import_test.cpp | 2 + src/test/overlay/compression_test.cpp | 2 +- src/test/overlay/reduce_relay_test.cpp | 31 +- src/test/overlay/short_read_test.cpp | 78 ++++- src/test/overlay/tx_reduce_relay_test.cpp | 11 +- src/test/peerfinder/Livecache_test.cpp | 2 +- src/test/peerfinder/PeerFinder_test.cpp | 2 +- src/test/protocol/STAccount_test.cpp | 4 +- src/test/protocol/STObject_test.cpp | 6 +- src/test/protocol/STParsedJSON_test.cpp | 4 +- src/test/protocol/SecretKey_test.cpp | 4 +- src/test/protocol/Seed_test.cpp | 8 +- src/test/resource/Logic_test.cpp | 20 ++ src/test/rpc/AMMInfo_test.cpp | 18 +- src/test/rpc/AccountObjects_test.cpp | 4 + src/test/rpc/AccountOffers_test.cpp | 2 +- src/test/rpc/AccountTx_test.cpp | 43 ++- src/test/rpc/DeliveredAmount_test.cpp | 22 ++ src/test/rpc/DepositAuthorized_test.cpp | 2 + src/test/rpc/Feature_test.cpp | 4 + src/test/rpc/KeyGeneration_test.cpp | 4 + src/test/rpc/LedgerData_test.cpp | 4 +- src/test/rpc/LedgerEntry_test.cpp | 22 +- src/test/rpc/LedgerRPC_test.cpp | 6 + src/test/rpc/NoRippleCheck_test.cpp | 2 + src/test/rpc/NoRipple_test.cpp | 4 + src/test/rpc/RPCOverload_test.cpp | 2 + src/test/rpc/ServerInfo_test.cpp | 2 +- src/test/rpc/Simulate_test.cpp | 2 +- src/test/rpc/Transaction_test.cpp | 8 + src/test/rpc/ValidatorRPC_test.cpp | 2 +- src/test/rpc/Version_test.cpp | 2 + src/test/server/ServerStatus_test.cpp | 5 +- src/test/server/Server_test.cpp | 4 + src/test/shamap/SHAMapSync_test.cpp | 2 +- src/test/shamap/SHAMap_test.cpp | 16 + src/test/unit_test/multi_runner.cpp | 6 +- src/tests/libxrpl/basics/Slice.cpp | 8 + src/xrpld/app/consensus/RCLConsensus.cpp | 14 +- src/xrpld/app/consensus/RCLCxPeerPos.cpp | 2 +- src/xrpld/app/consensus/RCLValidations.cpp | 4 + src/xrpld/app/ledger/AcceptedLedger.cpp | 2 + src/xrpld/app/ledger/Ledger.cpp | 22 +- src/xrpld/app/ledger/LedgerHistory.cpp | 4 + src/xrpld/app/ledger/OrderBookDBImpl.cpp | 30 ++ src/xrpld/app/ledger/detail/BuildLedger.cpp | 2 + src/xrpld/app/ledger/detail/InboundLedger.cpp | 40 ++- .../app/ledger/detail/InboundLedgers.cpp | 10 + .../app/ledger/detail/InboundTransactions.cpp | 12 +- src/xrpld/app/ledger/detail/LedgerCleaner.cpp | 2 + .../app/ledger/detail/LedgerDeltaAcquire.cpp | 16 +- src/xrpld/app/ledger/detail/LedgerMaster.cpp | 28 +- .../app/ledger/detail/LedgerReplayTask.cpp | 6 + .../app/ledger/detail/LedgerReplayer.cpp | 2 + src/xrpld/app/ledger/detail/LedgerToJson.cpp | 22 +- src/xrpld/app/ledger/detail/LocalTxs.cpp | 2 + .../app/ledger/detail/TransactionAcquire.cpp | 12 +- src/xrpld/app/main/Application.cpp | 14 +- src/xrpld/app/main/GRPCServer.cpp | 6 +- src/xrpld/app/main/LoadManager.cpp | 2 +- src/xrpld/app/main/Main.cpp | 114 +++---- src/xrpld/app/main/NodeIdentity.cpp | 4 +- src/xrpld/app/misc/FeeVoteImpl.cpp | 8 + src/xrpld/app/misc/NegativeUNLVote.cpp | 36 +-- src/xrpld/app/misc/NegativeUNLVote.h | 2 +- src/xrpld/app/misc/NetworkOPs.cpp | 86 +++++- src/xrpld/app/misc/SHAMapStoreImp.cpp | 16 +- src/xrpld/app/misc/detail/AccountTxPaging.cpp | 4 + src/xrpld/app/misc/detail/AmendmentTable.cpp | 38 +-- src/xrpld/app/misc/detail/TxQ.cpp | 36 ++- src/xrpld/app/misc/detail/ValidatorList.cpp | 164 +++++----- src/xrpld/app/misc/detail/ValidatorSite.cpp | 7 +- src/xrpld/app/misc/detail/WorkSSL.cpp | 10 +- .../app/misc/detail/setup_HashRouter.cpp | 4 + src/xrpld/app/paths/PathRequest.cpp | 14 +- src/xrpld/app/paths/PathRequests.cpp | 2 + src/xrpld/app/paths/Pathfinder.cpp | 20 +- src/xrpld/app/paths/RippleLineCache.cpp | 2 +- src/xrpld/app/paths/detail/AMMLiquidity.cpp | 33 ++- src/xrpld/app/paths/detail/BookStep.cpp | 91 +++--- src/xrpld/app/paths/detail/DirectStep.cpp | 34 +-- src/xrpld/app/paths/detail/PaySteps.cpp | 20 +- src/xrpld/app/rdb/backend/detail/Node.cpp | 46 ++- src/xrpld/core/detail/Config.cpp | 134 ++++++++- src/xrpld/overlay/detail/ConnectAttempt.cpp | 134 +++++++-- src/xrpld/overlay/detail/Handshake.cpp | 4 + src/xrpld/overlay/detail/Message.cpp | 10 +- src/xrpld/overlay/detail/OverlayImpl.cpp | 98 ++++-- src/xrpld/overlay/detail/OverlayImpl.h | 4 +- src/xrpld/overlay/detail/PeerImp.cpp | 255 ++++++++++++---- src/xrpld/overlay/detail/TrafficCount.cpp | 24 ++ src/xrpld/peerfinder/PeerfinderManager.h | 2 +- src/xrpld/peerfinder/detail/Bootcache.cpp | 8 +- .../peerfinder/detail/PeerfinderConfig.cpp | 11 +- .../peerfinder/detail/PeerfinderManager.cpp | 3 +- src/xrpld/perflog/detail/PerfLogImp.cpp | 10 +- src/xrpld/rpc/detail/Handler.cpp | 8 + src/xrpld/rpc/detail/RPCCall.cpp | 67 +++-- src/xrpld/rpc/detail/RPCHandler.cpp | 8 +- src/xrpld/rpc/detail/RPCHelpers.cpp | 18 +- src/xrpld/rpc/detail/RPCLedgerHelpers.cpp | 26 +- src/xrpld/rpc/detail/RPCSub.cpp | 15 +- src/xrpld/rpc/detail/Role.cpp | 6 +- src/xrpld/rpc/detail/ServerHandler.cpp | 50 +++- src/xrpld/rpc/detail/TransactionSign.cpp | 34 ++- src/xrpld/rpc/handlers/AMMInfo.cpp | 12 + src/xrpld/rpc/handlers/AccountInfo.cpp | 8 + src/xrpld/rpc/handlers/AccountLines.cpp | 4 + src/xrpld/rpc/handlers/AccountObjects.cpp | 10 +- src/xrpld/rpc/handlers/AccountTx.cpp | 20 +- src/xrpld/rpc/handlers/BlackList.cpp | 6 +- src/xrpld/rpc/handlers/BookOffers.cpp | 22 +- src/xrpld/rpc/handlers/Connect.cpp | 4 + src/xrpld/rpc/handlers/DepositAuthorized.cpp | 8 +- src/xrpld/rpc/handlers/Feature1.cpp | 4 + src/xrpld/rpc/handlers/GatewayBalances.cpp | 2 +- src/xrpld/rpc/handlers/LedgerData.cpp | 4 +- src/xrpld/rpc/handlers/LedgerEntry.cpp | 8 +- src/xrpld/rpc/handlers/LedgerHandler.cpp | 6 + src/xrpld/rpc/handlers/LogLevel.cpp | 4 + src/xrpld/rpc/handlers/NoRippleCheck.cpp | 4 + src/xrpld/rpc/handlers/PayChanClaim.cpp | 6 +- src/xrpld/rpc/handlers/Peers.cpp | 6 + src/xrpld/rpc/handlers/Ping.cpp | 2 +- src/xrpld/rpc/handlers/ServerDefinitions.cpp | 10 +- src/xrpld/rpc/handlers/Submit.cpp | 4 +- src/xrpld/rpc/handlers/Subscribe.cpp | 6 +- src/xrpld/rpc/handlers/TransactionEntry.cpp | 4 + src/xrpld/rpc/handlers/Tx.cpp | 8 +- src/xrpld/rpc/handlers/Unsubscribe.cpp | 12 +- src/xrpld/rpc/handlers/VaultInfo.cpp | 3 +- src/xrpld/rpc/handlers/WalletPropose.cpp | 8 + 328 files changed, 4415 insertions(+), 1176 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index 642bcb8a96..d8a7cb1b6f 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -98,12 +98,26 @@ 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-duplicate-include, + readability-else-after-return, readability-enum-initial-value, + readability-make-member-function-const, readability-misleading-indentation, readability-non-const-parameter, + readability-redundant-casting, readability-redundant-declaration, - readability-reference-to-constructed-temporary + readability-redundant-inline-specifier, + readability-redundant-member-init, + readability-redundant-string-init, + readability-reference-to-constructed-temporary, + readability-static-definition-in-anonymous-namespace, + readability-use-std-min-max " # --- # checks that have some issues that need to be resolved: @@ -113,27 +127,13 @@ Checks: "-*, # misc-include-cleaner, # misc-redundant-expression, # -# readability-avoid-nested-conditional-operator, -# readability-avoid-return-with-void-value, -# readability-braces-around-statements, -# readability-container-contains, -# readability-container-size-empty, # readability-convert-member-functions-to-static, -# readability-const-return-type, -# readability-else-after-return, # readability-implicit-bool-conversion, # readability-inconsistent-declaration-parameter-name, # readability-identifier-naming, -# readability-make-member-function-const, # readability-math-missing-parentheses, -# readability-redundant-inline-specifier, -# readability-redundant-member-init, -# readability-redundant-casting, -# readability-redundant-string-init, # readability-simplify-boolean-expr, -# readability-static-definition-in-anonymous-namespace, # readability-suspicious-call-argument, -# readability-use-std-min-max, # readability-static-accessed-through-instance, # # modernize-concat-nested-namespaces, @@ -157,7 +157,7 @@ Checks: "-*, # --- # CheckOptions: - # readability-braces-around-statements.ShortStatementLines: 2 + readability-braces-around-statements.ShortStatementLines: 2 # readability-identifier-naming.MacroDefinitionCase: UPPER_CASE # readability-identifier-naming.ClassCase: CamelCase # readability-identifier-naming.StructCase: CamelCase diff --git a/include/xrpl/protocol/Permissions.h b/include/xrpl/protocol/Permissions.h index e8800a41d2..65861addc7 100644 --- a/include/xrpl/protocol/Permissions.h +++ b/include/xrpl/protocol/Permissions.h @@ -65,7 +65,7 @@ public: std::optional getGranularTxType(GranularPermissionType const& gpType) const; - std::optional> const + std::optional> getTxFeature(TxType txType) const; bool diff --git a/include/xrpl/protocol/STObject.h b/include/xrpl/protocol/STObject.h index 0eb76a80c1..ecfae0086b 100644 --- a/include/xrpl/protocol/STObject.h +++ b/include/xrpl/protocol/STObject.h @@ -401,7 +401,7 @@ public: getStyle(SField const& field) const; bool - hasMatchingEntry(STBase const&); + hasMatchingEntry(STBase const&) const; bool operator==(STObject const& o) const; diff --git a/include/xrpl/server/InfoSub.h b/include/xrpl/server/InfoSub.h index 97cdf1aa35..d45f4d7740 100644 --- a/include/xrpl/server/InfoSub.h +++ b/include/xrpl/server/InfoSub.h @@ -173,7 +173,7 @@ public: send(Json::Value const& jvObj, bool broadcast) = 0; std::uint64_t - getSeq(); + getSeq() const; void onSendEmpty(); diff --git a/include/xrpl/tx/invariants/InvariantCheck.h b/include/xrpl/tx/invariants/InvariantCheck.h index 64eff33ff7..e0ad65f14c 100644 --- a/include/xrpl/tx/invariants/InvariantCheck.h +++ b/include/xrpl/tx/invariants/InvariantCheck.h @@ -132,7 +132,7 @@ public: visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); bool - finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); + finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; }; /** @@ -152,7 +152,7 @@ public: visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); bool - finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); + finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; }; /** @@ -198,7 +198,7 @@ public: visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); bool - finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); + finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; }; /** @@ -215,7 +215,7 @@ public: visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); bool - finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); + finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; }; /** @@ -233,7 +233,7 @@ public: visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); bool - finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); + finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; }; /** @@ -252,7 +252,7 @@ public: visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); bool - finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); + finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; }; /** @@ -271,7 +271,7 @@ public: visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); bool - finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); + finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; }; /** @@ -287,7 +287,7 @@ public: visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); bool - finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); + finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; }; /** @@ -307,7 +307,7 @@ public: visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); bool - finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); + finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; }; /** @@ -328,7 +328,7 @@ public: visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); bool - finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); + finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; }; /** diff --git a/include/xrpl/tx/invariants/MPTInvariant.h b/include/xrpl/tx/invariants/MPTInvariant.h index b6533c263d..68f866d362 100644 --- a/include/xrpl/tx/invariants/MPTInvariant.h +++ b/include/xrpl/tx/invariants/MPTInvariant.h @@ -25,7 +25,7 @@ public: visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); bool - finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); + finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; }; } // namespace xrpl diff --git a/include/xrpl/tx/invariants/NFTInvariant.h b/include/xrpl/tx/invariants/NFTInvariant.h index 8a88ca1c63..5bb5f90437 100644 --- a/include/xrpl/tx/invariants/NFTInvariant.h +++ b/include/xrpl/tx/invariants/NFTInvariant.h @@ -36,7 +36,7 @@ public: visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); bool - finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); + finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; }; /** @@ -64,7 +64,7 @@ public: visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); bool - finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); + finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; }; } // namespace xrpl diff --git a/src/libxrpl/basics/BasicConfig.cpp b/src/libxrpl/basics/BasicConfig.cpp index 63d3a56c40..edc8bea7d9 100644 --- a/src/libxrpl/basics/BasicConfig.cpp +++ b/src/libxrpl/basics/BasicConfig.cpp @@ -55,7 +55,7 @@ Section::append(std::vector const& lines) val = ""; break; } - else if (val.at(comment - 1) == '\\') + if (val.at(comment - 1) == '\\') { // we have an escaped comment char. Erase the escape char // and keep looking @@ -83,9 +83,13 @@ Section::append(std::vector const& lines) boost::smatch match; if (boost::regex_match(line, match, re1)) + { set(match[1], match[2]); + } else + { values_.push_back(line); + } lines_.push_back(std::move(line)); } diff --git a/src/libxrpl/basics/Log.cpp b/src/libxrpl/basics/Log.cpp index 3e36b7d458..9cebd1f04a 100644 --- a/src/libxrpl/basics/Log.cpp +++ b/src/libxrpl/basics/Log.cpp @@ -417,9 +417,13 @@ public: swap(holder_, sink); if (holder_) + { sink_ = *holder_; + } else + { sink_ = beast::Journal::getNullSink(); + } return sink; } diff --git a/src/libxrpl/basics/MallocTrim.cpp b/src/libxrpl/basics/MallocTrim.cpp index 1b0932b39d..ed20ac6c94 100644 --- a/src/libxrpl/basics/MallocTrim.cpp +++ b/src/libxrpl/basics/MallocTrim.cpp @@ -51,7 +51,7 @@ parseStatmRSSkB(std::string const& statm) // /proc/self/statm format: size resident shared text lib data dt // We want the second field (resident) which is in pages std::istringstream iss(statm); - long size, resident; + long size = 0, resident = 0; if (!(iss >> size >> resident)) return -1; diff --git a/src/libxrpl/basics/Number.cpp b/src/libxrpl/basics/Number.cpp index 11d2368b03..b520261ffe 100644 --- a/src/libxrpl/basics/Number.cpp +++ b/src/libxrpl/basics/Number.cpp @@ -94,7 +94,7 @@ public: // This enables the client to round towards nearest, and on // tie, round towards even. int - round() noexcept; + round() const noexcept; // Modify the result to the correctly rounded value template @@ -114,7 +114,7 @@ public: // Modify the result to the correctly rounded value void - doRound(rep& drops, std::string location); + doRound(rep& drops, std::string location) const; private: void @@ -171,7 +171,7 @@ Number::Guard::pop() noexcept // 0 if Guard is exactly half // 1 if Guard is greater than half int -Number::Guard::round() noexcept +Number::Guard::round() const noexcept { auto mode = Number::getround(); @@ -282,7 +282,7 @@ Number::Guard::doRoundDown( // Modify the result to the correctly rounded value void -Number::Guard::doRound(rep& drops, std::string location) +Number::Guard::doRound(rep& drops, std::string location) const { auto r = round(); if (r == 1 || (r == 0 && (drops & 1) == 1)) @@ -911,9 +911,13 @@ to_string(Number const& amount) // Assemble the output: if (pre_from == pre_to) + { ret.append(1, '0'); + } else + { ret.append(pre_from, pre_to); + } if (post_to != post_from) { diff --git a/src/libxrpl/basics/ResolverAsio.cpp b/src/libxrpl/basics/ResolverAsio.cpp index 225cbe2926..b746092645 100644 --- a/src/libxrpl/basics/ResolverAsio.cpp +++ b/src/libxrpl/basics/ResolverAsio.cpp @@ -374,7 +374,7 @@ public: JLOG(m_journal.debug()) << "Queued new job with " << names.size() << " tasks. " << m_work.size() << " jobs outstanding."; - if (m_work.size() > 0) + if (!m_work.empty()) { boost::asio::post( m_io_context, diff --git a/src/libxrpl/basics/base64.cpp b/src/libxrpl/basics/base64.cpp index 90bbc71359..31888ec99c 100644 --- a/src/libxrpl/basics/base64.cpp +++ b/src/libxrpl/basics/base64.cpp @@ -77,13 +77,13 @@ get_inverse() } /// Returns max chars needed to encode a base64 string -inline std::size_t constexpr encoded_size(std::size_t n) +std::size_t constexpr encoded_size(std::size_t n) { return 4 * ((n + 2) / 3); } /// Returns max bytes needed to decode a base64 string -inline std::size_t constexpr decoded_size(std::size_t n) +std::size_t constexpr decoded_size(std::size_t n) { return ((n / 4) * 3) + 2; } diff --git a/src/libxrpl/basics/make_SSLContext.cpp b/src/libxrpl/basics/make_SSLContext.cpp index 7fd6c5b97a..74aab709d8 100644 --- a/src/libxrpl/basics/make_SSLContext.cpp +++ b/src/libxrpl/basics/make_SSLContext.cpp @@ -272,9 +272,11 @@ initAuthenticated( if (!cert_set) { if (SSL_CTX_use_certificate(ssl, x) != 1) + { LogicError( "Problem retrieving SSL certificate from chain " "file."); + } cert_set = true; } diff --git a/src/libxrpl/beast/core/SemanticVersion.cpp b/src/libxrpl/beast/core/SemanticVersion.cpp index e8899e6854..34bb5e3df0 100644 --- a/src/libxrpl/beast/core/SemanticVersion.cpp +++ b/src/libxrpl/beast/core/SemanticVersion.cpp @@ -234,27 +234,43 @@ int compare(SemanticVersion const& lhs, SemanticVersion const& rhs) { if (lhs.majorVersion > rhs.majorVersion) + { return 1; - else if (lhs.majorVersion < rhs.majorVersion) + } + if (lhs.majorVersion < rhs.majorVersion) + { return -1; + } if (lhs.minorVersion > rhs.minorVersion) + { return 1; - else if (lhs.minorVersion < rhs.minorVersion) + } + if (lhs.minorVersion < rhs.minorVersion) + { return -1; + } if (lhs.patchVersion > rhs.patchVersion) + { return 1; - else if (lhs.patchVersion < rhs.patchVersion) + } + if (lhs.patchVersion < rhs.patchVersion) + { return -1; + } if (lhs.isPreRelease() || rhs.isPreRelease()) { // Pre-releases have a lower precedence if (lhs.isRelease() && rhs.isPreRelease()) + { return 1; - else if (lhs.isPreRelease() && rhs.isRelease()) + } + if (lhs.isPreRelease() && rhs.isRelease()) + { return -1; + } // Compare pre-release identifiers for (int i = 0; @@ -263,18 +279,26 @@ compare(SemanticVersion const& lhs, SemanticVersion const& rhs) { // A larger list of identifiers has a higher precedence if (i >= rhs.preReleaseIdentifiers.size()) + { return 1; - else if (i >= lhs.preReleaseIdentifiers.size()) + } + if (i >= lhs.preReleaseIdentifiers.size()) + { return -1; + } std::string const& left(lhs.preReleaseIdentifiers[i]); std::string const& right(rhs.preReleaseIdentifiers[i]); // Numeric identifiers have lower precedence if (!isNumeric(left) && isNumeric(right)) + { return 1; - else if (isNumeric(left) && !isNumeric(right)) + } + if (isNumeric(left) && !isNumeric(right)) + { return -1; + } if (isNumeric(left)) { @@ -284,9 +308,13 @@ compare(SemanticVersion const& lhs, SemanticVersion const& rhs) int const iRight(lexicalCastThrow(right)); if (iLeft > iRight) + { return 1; - else if (iLeft < iRight) + } + if (iLeft < iRight) + { return -1; + } } else { diff --git a/src/libxrpl/beast/net/IPEndpoint.cpp b/src/libxrpl/beast/net/IPEndpoint.cpp index 992da0041b..f8352f4318 100644 --- a/src/libxrpl/beast/net/IPEndpoint.cpp +++ b/src/libxrpl/beast/net/IPEndpoint.cpp @@ -95,10 +95,14 @@ operator>>(std::istream& is, Endpoint& endpoint) char i{0}; char readTo{0}; is.get(i); - if (i == '[') // we are an IPv6 endpoint + if (i == '[') + { // we are an IPv6 endpoint readTo = ']'; + } else + { addrStr += i; + } while (is && is.rdbuf()->in_avail() > 0 && is.get(i)) { @@ -166,7 +170,9 @@ operator>>(std::istream& is, Endpoint& endpoint) endpoint = Endpoint(addr, port); } else + { endpoint = Endpoint(addr); + } return is; } diff --git a/src/libxrpl/beast/utility/beast_Journal.cpp b/src/libxrpl/beast/utility/beast_Journal.cpp index f9ee0cdb73..7164fcfb06 100644 --- a/src/libxrpl/beast/utility/beast_Journal.cpp +++ b/src/libxrpl/beast/utility/beast_Journal.cpp @@ -124,9 +124,13 @@ Journal::ScopedStream::~ScopedStream() if (!s.empty()) { if (s == "\n") + { m_sink.write(m_level, ""); + } else + { m_sink.write(m_level, s); + } } } diff --git a/src/libxrpl/beast/utility/beast_PropertyStream.cpp b/src/libxrpl/beast/utility/beast_PropertyStream.cpp index f1edb4c4ef..454b9d1323 100644 --- a/src/libxrpl/beast/utility/beast_PropertyStream.cpp +++ b/src/libxrpl/beast/utility/beast_PropertyStream.cpp @@ -237,9 +237,13 @@ PropertyStream::Source::write(PropertyStream& stream, std::string const& path) return; if (result.second) + { result.first->write(stream); + } else + { result.first->write_one(stream); + } } std::pair @@ -301,9 +305,13 @@ PropertyStream::Source::peel_name(std::string* path) std::string s(first, pos); if (pos != last) + { *path = std::string(pos + 1, last); + } else + { *path = std::string(); + } return s; } @@ -371,9 +379,13 @@ void PropertyStream::add(std::string const& key, bool value) { if (value) + { add(key, "true"); + } else + { add(key, "false"); + } } void @@ -464,9 +476,13 @@ void PropertyStream::add(bool value) { if (value) + { add("true"); + } else + { add("false"); + } } void diff --git a/src/libxrpl/core/detail/Workers.cpp b/src/libxrpl/core/detail/Workers.cpp index a5e331bd44..c037169a29 100644 --- a/src/libxrpl/core/detail/Workers.cpp +++ b/src/libxrpl/core/detail/Workers.cpp @@ -205,11 +205,9 @@ Workers::Worker::run() // We got paused break; } - else - { - // Undo our decrement - ++m_workers.m_pauseCount; - } + + // Undo our decrement + ++m_workers.m_pauseCount; } // We couldn't pause so we must have gotten diff --git a/src/libxrpl/crypto/RFC1751.cpp b/src/libxrpl/crypto/RFC1751.cpp index a21bc71c31..f7c1e675cb 100644 --- a/src/libxrpl/crypto/RFC1751.cpp +++ b/src/libxrpl/crypto/RFC1751.cpp @@ -285,13 +285,21 @@ RFC1751::standard(std::string& strWord) for (auto& letter : strWord) { if (islower(static_cast(letter))) + { letter = toupper(static_cast(letter)); + } else if (letter == '1') + { letter = 'L'; + } else if (letter == '0') + { letter = 'O'; + } else if (letter == '5') + { letter = 'S'; + } } } diff --git a/src/libxrpl/json/Writer.cpp b/src/libxrpl/json/Writer.cpp index ee3d6f97a8..6ff5a130dd 100644 --- a/src/libxrpl/json/Writer.cpp +++ b/src/libxrpl/json/Writer.cpp @@ -25,7 +25,7 @@ std::map jsonSpecialCharacterEscape = { {'\r', "\\r"}, {'\t', "\\t"}}; -static size_t const jsonEscapeLength = 2; +size_t const jsonEscapeLength = 2; // All other JSON punctuation. char const closeBrace = '}'; @@ -36,7 +36,7 @@ char const openBrace = '{'; char const openBracket = '['; char const quote = '"'; -static auto const integralFloatsBecomeInts = false; +auto const integralFloatsBecomeInts = false; size_t lengthWithoutTrailingZeros(std::string const& s) @@ -137,9 +137,13 @@ public: check(false, "Not an " + ((type == array ? "array: " : "object: ") + message)); } if (stack_.top().isFirst) + { stack_.top().isFirst = false; + } else + { output_({&comma, 1}); + } } void diff --git a/src/libxrpl/json/json_reader.cpp b/src/libxrpl/json/json_reader.cpp index 1195816516..4c2a27400f 100644 --- a/src/libxrpl/json/json_reader.cpp +++ b/src/libxrpl/json/json_reader.cpp @@ -278,9 +278,13 @@ Reader::skipSpaces() Char c = *current_; if (c == ' ' || c == '\t' || c == '\r' || c == '\n') + { ++current_; + } else + { break; + } } } @@ -293,8 +297,10 @@ Reader::match(Location pattern, int patternLength) int index = patternLength; while (index--) + { if (current_[index] != pattern[index]) return false; + } current_ += patternLength; return true; @@ -384,9 +390,13 @@ Reader::readString() c = getNextChar(); if (c == '\\') + { getNextChar(); + } else if (c == '"') + { break; + } } return c == '"'; @@ -578,9 +588,13 @@ Reader::decodeNumber(Token& token) // If it's representable as a signed integer, construct it as one. if (value <= Value::maxInt) + { currentValue() = static_cast(value); + } else + { currentValue() = static_cast(value); + } } return true; @@ -646,8 +660,10 @@ Reader::decodeString(Token& token, std::string& decoded) Char c = *current++; if (c == '"') + { break; - else if (c == '\\') + } + if (c == '\\') { if (current == end) return addError("Empty escape sequence in string", token, current); @@ -721,19 +737,23 @@ Reader::decodeUnicodeCodePoint(Token& token, Location& current, Location end, un { // surrogate pairs if (end - current < 6) + { return addError( "additional six characters expected to parse unicode surrogate " "pair.", token, current); + } unsigned int surrogatePair = 0; if (*current != '\\' || *(current + 1) != 'u') + { return addError( "expecting another \\u token to begin the second half of a unicode surrogate pair", token, current); + } current += 2; // skip two characters checked above @@ -754,8 +774,10 @@ Reader::decodeUnicodeEscapeSequence( unsigned int& unicode) { if (end - current < 4) + { return addError( "Bad unicode escape sequence in string: four digits expected.", token, current); + } unicode = 0; @@ -765,17 +787,25 @@ Reader::decodeUnicodeEscapeSequence( unicode *= 16; if (c >= '0' && c <= '9') + { unicode += c - '0'; + } else if (c >= 'a' && c <= 'f') + { unicode += c - 'a' + 10; + } else if (c >= 'A' && c <= 'F') + { unicode += c - 'A' + 10; + } else + { return addError( "Bad unicode escape sequence in string: hexadecimal digit " "expected.", token, current); + } } return true; diff --git a/src/libxrpl/json/json_value.cpp b/src/libxrpl/json/json_value.cpp index 88542f530d..94b077d224 100644 --- a/src/libxrpl/json/json_value.cpp +++ b/src/libxrpl/json/json_value.cpp @@ -98,8 +98,11 @@ Value::CZString::CZString(CZString const& other) other.index_ != noDuplication && other.cstr_ != 0 ? valueAllocator()->makeMemberName(other.cstr_) : other.cstr_) - , index_( - other.cstr_ ? (other.index_ == noDuplication ? noDuplication : duplicate) : other.index_) + , index_([&]() -> int { + if (!other.cstr_) + return other.index_; + return other.index_ == noDuplication ? noDuplication : duplicate; + }()) { } @@ -254,7 +257,9 @@ Value::Value(Value const& other) : type_(other.type_) allocated_ = true; } else + { value_.string_ = 0; + } break; @@ -351,7 +356,9 @@ integerCmp(Int i, UInt ui) return -1; // Now we can safely compare. - return (i < ui) ? -1 : (i == ui) ? 0 : 1; + if (i < ui) + return -1; + return (i == ui) ? 0 : 1; } bool @@ -360,9 +367,13 @@ operator<(Value const& x, Value const& y) if (auto signum = x.type_ - y.type_) { if (x.type_ == intValue && y.type_ == uintValue) + { signum = integerCmp(x.value_.int_, y.value_.uint_); + } else if (x.type_ == uintValue && y.type_ == intValue) + { signum = -integerCmp(y.value_.int_, x.value_.uint_); + } return signum < 0; } @@ -696,7 +707,7 @@ Value::asBool() const case arrayValue: case objectValue: - return value_.map_->size() != 0; + return !value_.map_->empty(); // LCOV_EXCL_START default: @@ -743,10 +754,10 @@ Value::isConvertibleTo(ValueType other) const (other == nullValue && (!value_.string_ || value_.string_[0] == 0)); case arrayValue: - return other == arrayValue || (other == nullValue && value_.map_->size() == 0); + return other == arrayValue || (other == nullValue && value_.map_->empty()); case objectValue: - return other == objectValue || (other == nullValue && value_.map_->size() == 0); + return other == objectValue || (other == nullValue && value_.map_->empty()); // LCOV_EXCL_START default: diff --git a/src/libxrpl/json/json_valueiterator.cpp b/src/libxrpl/json/json_valueiterator.cpp index e40e674ee7..e49ad50f9a 100644 --- a/src/libxrpl/json/json_valueiterator.cpp +++ b/src/libxrpl/json/json_valueiterator.cpp @@ -13,7 +13,7 @@ namespace Json { // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// -ValueIteratorBase::ValueIteratorBase() : current_(), isNull_(true) +ValueIteratorBase::ValueIteratorBase() : isNull_(true) { } diff --git a/src/libxrpl/json/json_writer.cpp b/src/libxrpl/json/json_writer.cpp index 8ba2576552..66507f0111 100644 --- a/src/libxrpl/json/json_writer.cpp +++ b/src/libxrpl/json/json_writer.cpp @@ -304,7 +304,9 @@ StyledWriter::writeValue(Value const& value) Value::Members members(value.getMemberNames()); if (members.empty()) + { pushValue("{}"); + } else { writeWithIndent("{"); @@ -339,7 +341,9 @@ StyledWriter::writeArrayValue(Value const& value) unsigned size = value.size(); if (size == 0) + { pushValue("[]"); + } else { bool isArrayMultiLine = isMultilineArray(value); @@ -356,7 +360,9 @@ StyledWriter::writeArrayValue(Value const& value) Value const& childValue = value[index]; if (hasChildValue) + { writeWithIndent(childValues_[index]); + } else { writeIndent(); @@ -429,9 +435,13 @@ void StyledWriter::pushValue(std::string const& value) { if (addChildValues_) + { childValues_.push_back(value); + } else + { document_ += value; + } } void @@ -529,7 +539,9 @@ StyledStreamWriter::writeValue(Value const& value) Value::Members members(value.getMemberNames()); if (members.empty()) + { pushValue("{}"); + } else { writeWithIndent("{"); @@ -564,7 +576,9 @@ StyledStreamWriter::writeArrayValue(Value const& value) unsigned size = value.size(); if (size == 0) + { pushValue("[]"); + } else { bool isArrayMultiLine = isMultilineArray(value); @@ -581,7 +595,9 @@ StyledStreamWriter::writeArrayValue(Value const& value) Value const& childValue = value[index]; if (hasChildValue) + { writeWithIndent(childValues_[index]); + } else { writeIndent(); @@ -654,9 +670,13 @@ void StyledStreamWriter::pushValue(std::string const& value) { if (addChildValues_) + { childValues_.push_back(value); + } else + { *document_ << value; + } } void diff --git a/src/libxrpl/ledger/ApplyStateTable.cpp b/src/libxrpl/ledger/ApplyStateTable.cpp index 8c1f8d64d2..a0074c0b53 100644 --- a/src/libxrpl/ledger/ApplyStateTable.cpp +++ b/src/libxrpl/ledger/ApplyStateTable.cpp @@ -169,9 +169,11 @@ ApplyStateTable::apply( "xrpl::detail::ApplyStateTable::apply : valid nodes for " "modification"); - if (curNode->isThreadedType(to.rules())) // thread transaction to node - // item modified + if (curNode->isThreadedType(to.rules())) + { // thread transaction to node + // item modified threadItem(meta, curNode); + } STObject prevs(sfPreviousFields); for (auto const& obj : *origNode) diff --git a/src/libxrpl/ledger/BookListeners.cpp b/src/libxrpl/ledger/BookListeners.cpp index 9ba25b783a..22b78e46bb 100644 --- a/src/libxrpl/ledger/BookListeners.cpp +++ b/src/libxrpl/ledger/BookListeners.cpp @@ -38,7 +38,9 @@ BookListeners::publish(MultiApiJson const& jvObj, hash_set& haveP ++it; } else + { it = mListeners.erase(it); + } } } diff --git a/src/libxrpl/ledger/CachedView.cpp b/src/libxrpl/ledger/CachedView.cpp index 12704d227e..5c15ccdac4 100644 --- a/src/libxrpl/ledger/CachedView.cpp +++ b/src/libxrpl/ledger/CachedView.cpp @@ -40,11 +40,17 @@ CachedViewImpl::read(Keylet const& k) const // If the sle is null, then a failure must have occurred in base_.read() XRPL_ASSERT(sle || baseRead, "xrpl::CachedView::read : null SLE result from base"); if (cacheHit && baseRead) + { hitsexpired.increment(); + } else if (cacheHit) + { hits.increment(); + } else + { misses.increment(); + } if (!cacheHit) { diff --git a/src/libxrpl/ledger/CredentialHelpers.cpp b/src/libxrpl/ledger/CredentialHelpers.cpp index 1f32f5f1fa..0782eda67d 100644 --- a/src/libxrpl/ledger/CredentialHelpers.cpp +++ b/src/libxrpl/ledger/CredentialHelpers.cpp @@ -186,10 +186,12 @@ validDomain(ReadView const& view, uint256 domainID, AccountID const& subject) foundExpired = true; continue; } - else if (sleCredential->getFlags() & lsfAccepted) + if (sleCredential->getFlags() & lsfAccepted) + { return tesSUCCESS; - else - continue; + } + + continue; } } @@ -337,9 +339,11 @@ verifyDepositPreauth( if (src != dst) { if (!view.exists(keylet::depositPreauth(dst, src))) + { return !credentialsPresent ? tecNO_PERMISSION : credentials::authorizedDepositPreauth( view, tx.getFieldV256(sfCredentialIDs), dst); + } } } diff --git a/src/libxrpl/ledger/OpenView.cpp b/src/libxrpl/ledger/OpenView.cpp index 5b94be5da8..b5e358053c 100644 --- a/src/libxrpl/ledger/OpenView.cpp +++ b/src/libxrpl/ledger/OpenView.cpp @@ -185,7 +185,7 @@ OpenView::txsEnd() const -> std::unique_ptr bool OpenView::txExists(key_type const& key) const { - return txs_.find(key) != txs_.end(); + return txs_.contains(key); } auto @@ -198,9 +198,13 @@ OpenView::txRead(key_type const& key) const -> tx_type auto stx = std::make_shared(SerialIter{item.txn->slice()}); decltype(tx_type::second) sto; if (item.meta) + { sto = std::make_shared(SerialIter{item.meta->slice()}, sfMetadata); + } else + { sto = nullptr; + } return {std::move(stx), std::move(sto)}; } diff --git a/src/libxrpl/ledger/PaymentSandbox.cpp b/src/libxrpl/ledger/PaymentSandbox.cpp index e211917466..1f84da1dcb 100644 --- a/src/libxrpl/ledger/PaymentSandbox.cpp +++ b/src/libxrpl/ledger/PaymentSandbox.cpp @@ -11,9 +11,11 @@ auto DeferredCredits::makeKey(AccountID const& a1, AccountID const& a2, Currency const& c) -> Key { if (a1 < a2) + { return std::make_tuple(a1, a2, c); - else - return std::make_tuple(a2, a1, c); + } + + return std::make_tuple(a2, a1, c); } void @@ -53,9 +55,13 @@ DeferredCredits::credit( // only record the balance the first time, do not record it here auto& v = i->second; if (sender < receiver) + { v.highAcctCredits += amount; + } else + { v.lowAcctCredits += amount; + } } } @@ -101,11 +107,9 @@ DeferredCredits::adjustments( result.emplace(v.highAcctCredits, v.lowAcctCredits, v.lowAcctOrigBalance); return result; } - else - { - result.emplace(v.lowAcctCredits, v.highAcctCredits, -v.lowAcctOrigBalance); - return result; - } + + result.emplace(v.lowAcctCredits, v.highAcctCredits, -v.lowAcctOrigBalance); + return result; } void @@ -179,11 +183,13 @@ PaymentSandbox::balanceHook( adjustedAmt.setIssuer(amount.getIssuer()); if (isXRP(issuer) && adjustedAmt < beast::zero) + { // A calculated negative XRP balance is not an error case. Consider a // payment snippet that credits a large XRP amount and then debits the // same amount. The credit can't be used but we subtract the debit and // calculate a negative value. It's not an error case. adjustedAmt.clear(); + } return adjustedAmt; } diff --git a/src/libxrpl/ledger/RawStateTable.cpp b/src/libxrpl/ledger/RawStateTable.cpp index fcd8126c87..b411a25b00 100644 --- a/src/libxrpl/ledger/RawStateTable.cpp +++ b/src/libxrpl/ledger/RawStateTable.cpp @@ -94,9 +94,13 @@ public: dereference() const override { if (!sle1_) + { return sle0_; - else if (!sle0_) + } + if (!sle0_) + { return sle1_; + } if (sle1_->key() <= sle0_->key()) return sle1_; return sle0_; @@ -108,9 +112,13 @@ private: { ++iter0_; if (iter0_ == end0_) + { sle0_ = nullptr; + } else + { sle0_ = *iter0_; + } } void @@ -118,9 +126,13 @@ private: { ++iter1_; if (iter1_ == end1_) + { sle1_ = nullptr; + } else + { sle1_ = iter1_->second.sle; + } } void diff --git a/src/libxrpl/ledger/View.cpp b/src/libxrpl/ledger/View.cpp index 67aa4f5978..e76f0bfddc 100644 --- a/src/libxrpl/ledger/View.cpp +++ b/src/libxrpl/ledger/View.cpp @@ -51,9 +51,13 @@ internalDirNext( } 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"); @@ -83,9 +87,13 @@ internalDirFirst( 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; @@ -180,9 +188,13 @@ 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()); } @@ -381,7 +393,7 @@ getLineIfUsable( { return nullptr; // LCOV_EXCL_LINE } - else if (sleIssuer->isFieldPresent(sfAMMID)) + if (sleIssuer->isFieldPresent(sfAMMID)) { auto const sleAmm = view.read(keylet::amm((*sleIssuer)[sfAMMID])); @@ -457,9 +469,11 @@ accountHolds( 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 = @@ -514,9 +528,13 @@ accountHolds( 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)}; @@ -751,8 +769,10 @@ forEachItemAfter( 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; @@ -791,9 +811,13 @@ 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()); } @@ -1168,9 +1192,13 @@ canAddHolding(ReadView const& view, Issue const& issue) auto const issuer = view.read(keylet::account(issue.getIssuer())); if (!issuer) + { return terNO_ACCOUNT; - else if (!issuer->isFlag(lsfDefaultRipple)) + } + if (!issuer->isFlag(lsfDefaultRipple)) + { return terNO_RIPPLE; + } return tesSUCCESS; } @@ -1526,11 +1554,15 @@ authorizeMPToken( // 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); @@ -2319,15 +2351,13 @@ accountSendMultiIOU( { return TER{tecFAILED_PROCESSING}; } - else - { - auto const sndBal = sender->getFieldAmount(sfBalance); - view.creditHook(senderID, xrpAccount(), takeFromSender, sndBal); - // Decrement XRP balance. - sender->setFieldAmount(sfBalance, sndBal - takeFromSender); - view.update(sender); - } + 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()) @@ -2375,7 +2405,9 @@ rippleCreditMPT( view.update(sle); } else + { return tecNO_AUTH; + } } if (uReceiverID == issuer) @@ -2388,7 +2420,9 @@ rippleCreditMPT( view.update(sleIssuance); } else + { return tecINTERNAL; // LCOV_EXCL_LINE + } } else { @@ -2399,7 +2433,9 @@ rippleCreditMPT( view.update(sle); } else + { return tecNO_AUTH; + } } return tesSUCCESS; @@ -2599,9 +2635,13 @@ accountSend( 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()); } @@ -2620,9 +2660,13 @@ accountSendMulti( 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()); } @@ -2725,12 +2769,14 @@ issueIOU( // 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); @@ -2898,9 +2944,11 @@ requireAuth(ReadView const& view, Issue const& issue, AccountID const& account, issuerAccount && (*issuerAccount)[sfFlags] & lsfRequireAuth) { if (trustLine) + { return ((*trustLine)[sfFlags] & ((account > issue.account) ? lsfLowAuth : lsfHighAuth)) ? tesSUCCESS : TER{tecNO_AUTH}; + } return TER{tecNO_LINE}; } @@ -2948,9 +2996,13 @@ requireAuth( 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)) @@ -2974,11 +3026,15 @@ requireAuth( sleIssuance->getFieldU32(sfFlags) & lsfMPTRequireAuth, "xrpl::requireAuth : issuance requires authorization"); // ter = tefINTERNAL | tecOBJECT_NOT_FOUND | tecNO_AUTH | tecEXPIRED - if (auto const ter = credentials::validDomain(view, *maybeDomainID, account); - isTesSuccess(ter)) + auto const ter = credentials::validDomain(view, *maybeDomainID, account); + if (isTesSuccess(ter)) + { return ter; // Note: sleToken might be null - else if (!sleToken) + } + 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. } @@ -3045,14 +3101,14 @@ enforceMPTokenAuthorization( // Either way, return tecNO_AUTH and there is nothing else to do return expired ? tecEXPIRED : tecNO_AUTH; } - else if (!authorizedByDomain && maybeDomainID.has_value()) + 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; } - else if (!authorizedByDomain) + if (!authorizedByDomain) { // We found an MPToken, but sfDomainID is not set, so this is a classic // MPToken which requires authorization by the token issuer. @@ -3064,7 +3120,7 @@ enforceMPTokenAuthorization( return tecNO_AUTH; } - else if (authorizedByDomain && sleToken != nullptr) + if (authorizedByDomain && sleToken != nullptr) { // Found an MPToken, authorized by the domain. Ignore authorization flag // lsfMPTAuthorized because it is meaningless. Return tesSUCCESS @@ -3073,7 +3129,7 @@ enforceMPTokenAuthorization( "xrpl::enforceMPTokenAuthorization : found MPToken for domain"); return tesSUCCESS; } - else if (authorizedByDomain) + if (authorizedByDomain) { // Could not find MPToken but there should be one because we are // authorized by domain. Proceed to create it, then return tesSUCCESS @@ -3314,9 +3370,11 @@ assetsToSharesDeposit( 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(); @@ -3339,8 +3397,10 @@ sharesToAssetsDeposit( 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; @@ -3455,9 +3515,13 @@ rippleLockEscrowMPT( } // LCOV_EXCL_STOP if (sle->isFieldPresent(sfLockedAmount)) + { (*sle)[sfLockedAmount] += pay; + } else + { sle->setFieldU64(sfLockedAmount, pay); + } view.update(sle); } @@ -3478,9 +3542,13 @@ rippleLockEscrowMPT( } // LCOV_EXCL_STOP if (sleIssuance->isFieldPresent(sfLockedAmount)) + { (*sleIssuance)[sfLockedAmount] += pay; + } else + { sleIssuance->setFieldU64(sfLockedAmount, pay); + } view.update(sleIssuance); } @@ -3497,8 +3565,10 @@ rippleUnlockEscrowMPT( 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(); @@ -3533,9 +3603,13 @@ rippleUnlockEscrowMPT( auto const newLocked = locked - redeem; if (newLocked == 0) + { sleIssuance->makeFieldAbsent(sfLockedAmount); + } else + { sleIssuance->setFieldU64(sfLockedAmount, newLocked); + } view.update(sleIssuance); } @@ -3588,42 +3662,44 @@ rippleUnlockEscrowMPT( "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 { - // 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); + 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 diff --git a/src/libxrpl/nodestore/backend/MemoryFactory.cpp b/src/libxrpl/nodestore/backend/MemoryFactory.cpp index b11d90610a..0366fe3573 100644 --- a/src/libxrpl/nodestore/backend/MemoryFactory.cpp +++ b/src/libxrpl/nodestore/backend/MemoryFactory.cpp @@ -142,9 +142,13 @@ public: std::shared_ptr nObj; Status status = fetch(h, &nObj); if (status != ok) + { results.push_back({}); + } else + { results.push_back(nObj); + } } return {results, ok}; diff --git a/src/libxrpl/nodestore/backend/NuDBFactory.cpp b/src/libxrpl/nodestore/backend/NuDBFactory.cpp index 229bf8b67b..2d8cffa85a 100644 --- a/src/libxrpl/nodestore/backend/NuDBFactory.cpp +++ b/src/libxrpl/nodestore/backend/NuDBFactory.cpp @@ -216,9 +216,13 @@ public: std::shared_ptr nObj; Status status = fetch(h, &nObj); if (status != ok) + { results.push_back({}); + } else + { results.push_back(nObj); + } } return {results, ok}; diff --git a/src/libxrpl/nodestore/backend/RocksDBFactory.cpp b/src/libxrpl/nodestore/backend/RocksDBFactory.cpp index 01bc74f5ed..67c329bb4a 100644 --- a/src/libxrpl/nodestore/backend/RocksDBFactory.cpp +++ b/src/libxrpl/nodestore/backend/RocksDBFactory.cpp @@ -166,8 +166,10 @@ public: auto const s = rocksdb::GetBlockBasedTableOptionsFromString( config_options, table_options, get(keyValues, "bbt_options"), &table_options); if (!s.ok()) + { Throw( std::string("Unable to set RocksDB bbt_options: ") + s.ToString()); + } } m_options.table_factory.reset(NewBlockBasedTableFactory(table_options)); @@ -177,8 +179,10 @@ public: auto const s = rocksdb::GetOptionsFromString(m_options, get(keyValues, "options"), &m_options); if (!s.ok()) + { Throw( std::string("Unable to set RocksDB options: ") + s.ToString()); + } } std::string s1, s2; @@ -210,8 +214,10 @@ public: m_options.create_if_missing = createIfMissing; rocksdb::Status status = rocksdb::DB::Open(m_options, m_name, &db); if (!status.ok() || !db) + { Throw( std::string("Unable to open/create RocksDB: ") + status.ToString()); + } m_db.reset(db); } @@ -304,9 +310,13 @@ public: std::shared_ptr nObj; Status status = fetch(h, &nObj); if (status != ok) + { results.push_back({}); + } else + { results.push_back(nObj); + } } return {results, ok}; diff --git a/src/libxrpl/protocol/Feature.cpp b/src/libxrpl/protocol/Feature.cpp index 4d904a5e43..f91e164c92 100644 --- a/src/libxrpl/protocol/Feature.cpp +++ b/src/libxrpl/protocol/Feature.cpp @@ -250,18 +250,22 @@ FeatureCollections::registerFeature(std::string const& name, Supported support, supported.emplace(name, vote); if (vote == VoteBehavior::DefaultYes) + { ++upVotes; + } else + { ++downVotes; + } } check(upVotes + downVotes == supported.size(), "Feature counting logic broke"); check(supported.size() <= features.size(), "More supported features than defined features"); check(features.size() == all.size(), "The 'all' features list is populated incorrectly"); return f; } - else - // Each feature should only be registered once - LogicError("Duplicate feature registration"); + + // Each feature should only be registered once + LogicError("Duplicate feature registration"); } /** Tell FeatureCollections when registration is complete. */ @@ -302,7 +306,7 @@ FeatureCollections::featureToName(uint256 const& f) const return feature ? feature->name : to_string(f); } -static FeatureCollections featureCollections; +FeatureCollections featureCollections; } // namespace diff --git a/src/libxrpl/protocol/Indexes.cpp b/src/libxrpl/protocol/Indexes.cpp index 45ab20f057..aabe8395ae 100644 --- a/src/libxrpl/protocol/Indexes.cpp +++ b/src/libxrpl/protocol/Indexes.cpp @@ -137,7 +137,7 @@ getQuality(uint256 const& uBase) uint256 getTicketIndex(AccountID const& account, std::uint32_t ticketSeq) { - return indexHash(LedgerNameSpace::TICKET, account, std::uint32_t(ticketSeq)); + return indexHash(LedgerNameSpace::TICKET, account, ticketSeq); } uint256 diff --git a/src/libxrpl/protocol/Issue.cpp b/src/libxrpl/protocol/Issue.cpp index 1a56007729..c73c6c8513 100644 --- a/src/libxrpl/protocol/Issue.cpp +++ b/src/libxrpl/protocol/Issue.cpp @@ -25,11 +25,17 @@ Issue::getText() const ret += "/"; if (isXRP(account)) + { ret += "0"; + } else if (account == noAccount()) + { ret += "1"; + } else + { ret += to_string(account); + } } return ret; diff --git a/src/libxrpl/protocol/NFTokenID.cpp b/src/libxrpl/protocol/NFTokenID.cpp index 66f05a81fc..d867cdb8c9 100644 --- a/src/libxrpl/protocol/NFTokenID.cpp +++ b/src/libxrpl/protocol/NFTokenID.cpp @@ -154,7 +154,7 @@ insertNFTokenID( { std::vector result = getNFTokenIDFromDeletedOffer(transactionMeta); - if (result.size() > 0) + if (!result.empty()) response[jss::nftoken_id] = to_string(result.front()); } else if (type == ttNFTOKEN_CANCEL_OFFER) diff --git a/src/libxrpl/protocol/Permissions.cpp b/src/libxrpl/protocol/Permissions.cpp index cce7ab5058..4137c73624 100644 --- a/src/libxrpl/protocol/Permissions.cpp +++ b/src/libxrpl/protocol/Permissions.cpp @@ -68,10 +68,12 @@ Permission::Permission() }; for ([[maybe_unused]] auto const& permission : granularPermissionMap_) + { XRPL_ASSERT( permission.second > UINT16_MAX, "xrpl::Permission::granularPermissionMap_ : granular permission " "value must not exceed the maximum uint16_t value."); + } } Permission const& @@ -126,7 +128,7 @@ Permission::getGranularTxType(GranularPermissionType const& gpType) const return std::nullopt; } -std::optional> const +std::optional> Permission::getTxFeature(TxType txType) const { auto const txFeaturesIt = txFeatureMap_.find(txType); @@ -145,8 +147,10 @@ Permission::isDelegable(std::uint32_t const& permissionValue, Rules const& rules auto const granularPermission = getGranularName(static_cast(permissionValue)); if (granularPermission) + { // granular permissions are always allowed to be delegated return true; + } auto const txType = permissionToTxType(permissionValue); auto const it = delegableTx_.find(txType); diff --git a/src/libxrpl/protocol/PublicKey.cpp b/src/libxrpl/protocol/PublicKey.cpp index 3251cb84ac..2c63ddac64 100644 --- a/src/libxrpl/protocol/PublicKey.cpp +++ b/src/libxrpl/protocol/PublicKey.cpp @@ -171,9 +171,11 @@ ed25519Canonical(Slice const& sig) PublicKey::PublicKey(Slice const& slice) { if (slice.size() < size_) + { LogicError( "PublicKey::PublicKey - Input slice cannot be an undersized " "buffer"); + } if (!publicKeyType(slice)) LogicError("PublicKey::PublicKey invalid type"); @@ -270,7 +272,7 @@ verify(PublicKey const& publicKey, Slice const& m, Slice const& sig) noexcept { return verifyDigest(publicKey, sha512Half(m), sig); } - else if (*type == KeyType::ed25519) + if (*type == KeyType::ed25519) { if (!ed25519Canonical(sig)) return false; diff --git a/src/libxrpl/protocol/Rules.cpp b/src/libxrpl/protocol/Rules.cpp index 5a97a33185..4ef052d2cc 100644 --- a/src/libxrpl/protocol/Rules.cpp +++ b/src/libxrpl/protocol/Rules.cpp @@ -77,9 +77,9 @@ public: bool enabled(uint256 const& feature) const { - if (presets_.count(feature) > 0) + if (presets_.contains(feature)) return true; - return set_.count(feature) > 0; + return set_.contains(feature); } bool diff --git a/src/libxrpl/protocol/STAccount.cpp b/src/libxrpl/protocol/STAccount.cpp index 9570191273..ffd0b5d3c8 100644 --- a/src/libxrpl/protocol/STAccount.cpp +++ b/src/libxrpl/protocol/STAccount.cpp @@ -16,7 +16,7 @@ namespace xrpl { -STAccount::STAccount() : STBase(), value_(beast::zero), default_(true) +STAccount::STAccount() : value_(beast::zero), default_(true) { } diff --git a/src/libxrpl/protocol/STAmount.cpp b/src/libxrpl/protocol/STAmount.cpp index 5990e1d7d4..92ce129825 100644 --- a/src/libxrpl/protocol/STAmount.cpp +++ b/src/libxrpl/protocol/STAmount.cpp @@ -223,9 +223,13 @@ STAmount::STAmount(XRPAmount const& amount) : mAsset(xrpIssue()), mOffset(0), mIsNegative(amount < beast::zero) { if (mIsNegative) + { mValue = unsafe_cast(-amount.drops()); + } else + { mValue = unsafe_cast(amount.drops()); + } canonicalize(); } @@ -305,9 +309,13 @@ STAmount::operator=(IOUAmount const& iou) mOffset = iou.exponent(); mIsNegative = iou < beast::zero; if (mIsNegative) + { mValue = static_cast(-iou.mantissa()); + } else + { mValue = static_cast(iou.mantissa()); + } return *this; } @@ -722,9 +730,13 @@ STAmount::getText() const // Assemble the output: if (pre_from == pre_to) + { ret.append(1, '0'); + } else + { ret.append(pre_from, pre_to); + } if (post_to != post_from) { @@ -751,9 +763,13 @@ STAmount::add(Serializer& s) const XRPL_ASSERT(mOffset == 0, "xrpl::STAmount::add : zero offset"); if (!mIsNegative) + { s.add64(mValue | cPositive); + } else + { s.add64(mValue); + } } else if (mAsset.holds()) { @@ -767,11 +783,17 @@ STAmount::add(Serializer& s) const else { if (*this == beast::zero) + { s.add64(cIssuedCurrency); - else if (mIsNegative) // 512 = not native + } + else if (mIsNegative) + { // 512 = not native s.add64(mValue | (static_cast(mOffset + 512 + 97) << (64 - 10))); - else // 256 = positive + } + else + { // 256 = positive s.add64(mValue | (static_cast(mOffset + 512 + 256 + 97) << (64 - 10))); + } s.addBitString(mAsset.get().currency); s.addBitString(mAsset.get().account); } @@ -839,11 +861,17 @@ STAmount::canonicalize() mValue = mIsNegative ? -value : value; }; if (native()) + { set(XRPAmount{num}); + } else if (mAsset.holds()) + { set(MPTAmount{num}); + } else + { Throw("Unknown integral asset type"); + } mOffset = 0; } else @@ -859,9 +887,13 @@ STAmount::canonicalize() // N.B. do not move the overflow check to after the // multiplication if (native() && mValue > cMaxNativeN) + { Throw("Native currency amount out of range"); + } else if (!native() && mValue > maxMPTokenAmount) + { Throw("MPT amount out of range"); + } mValue *= 10; --mOffset; @@ -869,9 +901,13 @@ STAmount::canonicalize() } if (native() && mValue > cMaxNativeN) + { Throw("Native currency amount out of range"); + } else if (!native() && mValue > maxMPTokenAmount) + { Throw("MPT amount out of range"); + } return; } diff --git a/src/libxrpl/protocol/STLedgerEntry.cpp b/src/libxrpl/protocol/STLedgerEntry.cpp index 09993583be..aa97b6b3a2 100644 --- a/src/libxrpl/protocol/STLedgerEntry.cpp +++ b/src/libxrpl/protocol/STLedgerEntry.cpp @@ -33,9 +33,11 @@ STLedgerEntry::STLedgerEntry(Keylet const& k) : STObject(sfLedgerEntry), key_(k. auto const format = LedgerFormats::getInstance().findByType(type_); if (format == nullptr) + { Throw( "Attempt to create a SLE of unknown type " + std::to_string(safe_cast(k.type))); + } set(format->getSOTemplate()); @@ -118,8 +120,10 @@ STLedgerEntry::getJson(JsonOptions options) const ret[jss::index] = to_string(key_); if (getType() == ltMPTOKEN_ISSUANCE) + { ret[jss::mpt_issuance_id] = to_string(makeMptID(getFieldU32(sfSequence), getAccountID(sfIssuer))); + } return ret; } diff --git a/src/libxrpl/protocol/STNumber.cpp b/src/libxrpl/protocol/STNumber.cpp index 6d382bee9c..aab4bdc0f5 100644 --- a/src/libxrpl/protocol/STNumber.cpp +++ b/src/libxrpl/protocol/STNumber.cpp @@ -198,9 +198,13 @@ partsFromString(std::string const& number) { // we have an exponent if (match[6].matched && (match[6] == "-")) + { exponent -= boost::lexical_cast(std::string(match[7])); + } else + { exponent += boost::lexical_cast(std::string(match[7])); + } } return {mantissa, exponent, negative}; diff --git a/src/libxrpl/protocol/STObject.cpp b/src/libxrpl/protocol/STObject.cpp index 05d4d12503..fe9e95cc82 100644 --- a/src/libxrpl/protocol/STObject.cpp +++ b/src/libxrpl/protocol/STObject.cpp @@ -140,9 +140,13 @@ STObject::set(SOTemplate const& type) for (auto const& elem : type) { if (elem.style() != soeREQUIRED) + { v_.emplace_back(detail::nonPresentObject, elem.sField()); + } else + { v_.emplace_back(detail::defaultObject, elem.sField()); + } } } @@ -268,7 +272,7 @@ STObject::set(SerialIter& sit, int depth) } bool -STObject::hasMatchingEntry(STBase const& t) +STObject::hasMatchingEntry(STBase const& t) const { STBase const* o = peekAtPField(t.getFName()); @@ -290,16 +294,22 @@ STObject::getFullText() const ret += " = {"; } else + { ret = "{"; + } for (auto const& elem : v_) { if (elem->getSType() != STI_NOTPRESENT) { if (!first) + { ret += ", "; + } else + { first = false; + } ret += elem->getFullText(); } diff --git a/src/libxrpl/protocol/STParsedJSON.cpp b/src/libxrpl/protocol/STParsedJSON.cpp index b246daf48e..0bf0c827af 100644 --- a/src/libxrpl/protocol/STParsedJSON.cpp +++ b/src/libxrpl/protocol/STParsedJSON.cpp @@ -267,8 +267,10 @@ parseUint16( } } if (!ret) + { return parseUnsigned( field, json_name, fieldName, name, value, error); + } } catch (std::exception const&) { @@ -320,8 +322,10 @@ parseUint32( } } if (!ret) + { return parseUnsigned( field, json_name, fieldName, name, value, error); + } } catch (std::exception const&) { diff --git a/src/libxrpl/protocol/STTx.cpp b/src/libxrpl/protocol/STTx.cpp index bb4b9b3067..00a2acd788 100644 --- a/src/libxrpl/protocol/STTx.cpp +++ b/src/libxrpl/protocol/STTx.cpp @@ -199,8 +199,10 @@ STTx::getSeqProxy() const std::optional const ticketSeq{operator[](~sfTicketSequence)}; if (!ticketSeq) + { // No TicketSequence specified. Return the Sequence, whatever it is. return SeqProxy::sequence(seq); + } return SeqProxy{SeqProxy::ticket, *ticketSeq}; } @@ -337,8 +339,8 @@ STTx::getJson(JsonOptions options, bool binary) const ret[jss::hash] = to_string(getTransactionID()); return ret; } - else - return Json::Value{dataBin}; + + return Json::Value{dataBin}; } Json::Value ret = STObject::getJson(JsonOptions::none); @@ -500,9 +502,11 @@ multiSignHelper( errorWhat = e.what(); } if (!validSig) + { return Unexpected( std::string("Invalid signature on account ") + toBase58(accountID) + errorWhat.value_or("") + "."); + } } // All signatures verified. return {}; @@ -576,7 +580,7 @@ STTx::getBatchTransactionIDs() const // The list of inner ids is built once, then reused on subsequent calls. // After the list is built, it must always have the same size as the array // `sfRawTransactions`. The assert below verifies that. - if (batchTxnIds_.size() == 0) + if (batchTxnIds_.empty()) { for (STObject const& rb : getFieldArray(sfRawTransactions)) batchTxnIds_.push_back(rb.getHash(HashPrefix::transactionID)); diff --git a/src/libxrpl/protocol/STVar.cpp b/src/libxrpl/protocol/STVar.cpp index 6218bb6db6..255514d70c 100644 --- a/src/libxrpl/protocol/STVar.cpp +++ b/src/libxrpl/protocol/STVar.cpp @@ -61,9 +61,13 @@ STVar::operator=(STVar const& rhs) { destroy(); if (rhs.p_) + { p_ = rhs.p_->copy(max_size, &d_); + } else + { p_ = nullptr; + } } return *this; @@ -116,9 +120,13 @@ void STVar::destroy() { if (on_heap()) + { delete p_; + } else + { p_->~STBase(); + } p_ = nullptr; } diff --git a/src/libxrpl/protocol/STVector256.cpp b/src/libxrpl/protocol/STVector256.cpp index 886fed5d2d..6357e2f2cb 100644 --- a/src/libxrpl/protocol/STVector256.cpp +++ b/src/libxrpl/protocol/STVector256.cpp @@ -19,8 +19,10 @@ STVector256::STVector256(SerialIter& sit, SField const& name) : STBase(name) auto const slice = sit.getSlice(sit.getVLDataLength()); if (slice.size() % uint256::size() != 0) + { Throw( "Bad serialization for STVector256: " + std::to_string(slice.size())); + } auto const cnt = slice.size() / uint256::size(); diff --git a/src/libxrpl/protocol/Serializer.cpp b/src/libxrpl/protocol/Serializer.cpp index 4415f96484..08d221f75b 100644 --- a/src/libxrpl/protocol/Serializer.cpp +++ b/src/libxrpl/protocol/Serializer.cpp @@ -112,8 +112,10 @@ Serializer::addFieldID(int type, int name) if (type < 16) { - if (name < 16) // common type, common name + if (name < 16) + { // common type, common name mData.push_back(static_cast((type << 4) | name)); + } else { // common type, uncommon name @@ -187,7 +189,7 @@ int Serializer::addVL(Slice const& slice) { int ret = addEncoded(slice.size()); - if (slice.size()) + if (!slice.empty()) addRaw(slice.data(), slice.size()); return ret; } @@ -230,7 +232,9 @@ Serializer::addEncoded(int length) numBytes = 3; } else + { Throw("lenlen"); + } return addRaw(&bytes[0], numBytes); } diff --git a/src/libxrpl/protocol/tokens.cpp b/src/libxrpl/protocol/tokens.cpp index 868c45e46c..b46591725f 100644 --- a/src/libxrpl/protocol/tokens.cpp +++ b/src/libxrpl/protocol/tokens.cpp @@ -615,7 +615,7 @@ encodeBase58Token( { return Unexpected(TokenCodecErrc::inputTooLarge); } - if (input.size() == 0) + if (input.empty()) { return Unexpected(TokenCodecErrc::inputTooSmall); } diff --git a/src/libxrpl/rdb/SociDB.cpp b/src/libxrpl/rdb/SociDB.cpp index 3ba0d4c980..baadeef00a 100644 --- a/src/libxrpl/rdb/SociDB.cpp +++ b/src/libxrpl/rdb/SociDB.cpp @@ -81,9 +81,13 @@ void open(soci::session& s, std::string const& beName, std::string const& connectionString) { if (beName == "sqlite") + { s.open(soci::sqlite3, connectionString); + } else + { Throw("Unsupported soci backend: " + beName); + } } static sqlite_api::sqlite3* @@ -143,18 +147,26 @@ void convert(std::vector const& from, soci::blob& to) { if (!from.empty()) + { to.write(0, reinterpret_cast(&from[0]), from.size()); + } else + { to.trim(0); + } } void convert(std::string const& from, soci::blob& to) { if (!from.empty()) + { to.write(0, from.data(), from.size()); + } else + { to.trim(0); + } } namespace { diff --git a/src/libxrpl/server/InfoSub.cpp b/src/libxrpl/server/InfoSub.cpp index 0ec432883d..5857e4d6ae 100644 --- a/src/libxrpl/server/InfoSub.cpp +++ b/src/libxrpl/server/InfoSub.cpp @@ -52,7 +52,7 @@ InfoSub::getConsumer() } std::uint64_t -InfoSub::getSeq() +InfoSub::getSeq() const { return mSeq; } @@ -68,9 +68,13 @@ InfoSub::insertSubAccountInfo(AccountID const& account, bool rt) std::lock_guard sl(mLock); if (rt) + { realTimeSubscriptions_.insert(account); + } else + { normalSubscriptions_.insert(account); + } } void @@ -79,9 +83,13 @@ InfoSub::deleteSubAccountInfo(AccountID const& account, bool rt) std::lock_guard sl(mLock); if (rt) + { realTimeSubscriptions_.erase(account); + } else + { normalSubscriptions_.erase(account); + } } bool diff --git a/src/libxrpl/server/LoadFeeTrack.cpp b/src/libxrpl/server/LoadFeeTrack.cpp index e3867f36f5..e206b50863 100644 --- a/src/libxrpl/server/LoadFeeTrack.cpp +++ b/src/libxrpl/server/LoadFeeTrack.cpp @@ -4,6 +4,7 @@ #include #include +#include #include namespace xrpl { @@ -19,14 +20,12 @@ LoadFeeTrack::raiseLocalFee() std::uint32_t const origFee = localTxnLoadFee_; // make sure this fee takes effect - if (localTxnLoadFee_ < remoteTxnLoadFee_) - localTxnLoadFee_ = remoteTxnLoadFee_; + localTxnLoadFee_ = std::max(localTxnLoadFee_, remoteTxnLoadFee_); // Increase slowly localTxnLoadFee_ += (localTxnLoadFee_ / lftFeeIncFraction); - if (localTxnLoadFee_ > lftFeeMax) - localTxnLoadFee_ = lftFeeMax; + localTxnLoadFee_ = std::min(localTxnLoadFee_, lftFeeMax); if (origFee == localTxnLoadFee_) return false; @@ -45,8 +44,7 @@ LoadFeeTrack::lowerLocalFee() // Reduce slowly localTxnLoadFee_ -= (localTxnLoadFee_ / lftFeeDecFraction); - if (localTxnLoadFee_ < lftNormalFee) - localTxnLoadFee_ = lftNormalFee; + localTxnLoadFee_ = std::max(localTxnLoadFee_, lftNormalFee); if (origFee == localTxnLoadFee_) return false; diff --git a/src/libxrpl/server/Port.cpp b/src/libxrpl/server/Port.cpp index 0cef9bed90..2d0b4ec257 100644 --- a/src/libxrpl/server/Port.cpp +++ b/src/libxrpl/server/Port.cpp @@ -44,7 +44,7 @@ operator<<(std::ostream& os, Port const& p) { os << "'" << p.name << "' (ip=" << p.ip << ":" << p.port << ", "; - if (p.admin_nets_v4.size() || p.admin_nets_v6.size()) + if (!p.admin_nets_v4.empty() || !p.admin_nets_v6.empty()) { os << "admin nets:"; for (auto const& net : p.admin_nets_v4) @@ -59,7 +59,7 @@ operator<<(std::ostream& os, Port const& p) } } - if (p.secure_gateway_nets_v4.size() || p.secure_gateway_nets_v6.size()) + if (!p.secure_gateway_nets_v4.empty() || !p.secure_gateway_nets_v6.empty()) { os << "secure_gateway nets:"; for (auto const& net : p.secure_gateway_nets_v4) diff --git a/src/libxrpl/shamap/SHAMap.cpp b/src/libxrpl/shamap/SHAMap.cpp index d5fa67fdac..a6aacfabc9 100644 --- a/src/libxrpl/shamap/SHAMap.cpp +++ b/src/libxrpl/shamap/SHAMap.cpp @@ -418,9 +418,13 @@ SHAMap::belowHelper( } auto inner = intr_ptr::static_pointer_cast(node); if (stack.empty()) + { stack.push({inner, SHAMapNodeID{}}); + } else + { stack.push({inner, stack.top().second.getChildNodeID(branch)}); + } for (int i = init; cmp(i);) { if (!inner->isEmptyBranch(i)) @@ -438,7 +442,9 @@ SHAMap::belowHelper( i = init; // descend and reset loop } else + { incr(i); // scan next branch + } } return nullptr; } @@ -1114,7 +1120,9 @@ SHAMap::dump(bool hash) const } } else + { ++leafCount; + } } while (!stack.empty()); JLOG(journal_.info()) << leafCount << " resident leaves"; diff --git a/src/libxrpl/shamap/SHAMapDelta.cpp b/src/libxrpl/shamap/SHAMapDelta.cpp index 7ef78d51c3..98a31fea55 100644 --- a/src/libxrpl/shamap/SHAMapDelta.cpp +++ b/src/libxrpl/shamap/SHAMapDelta.cpp @@ -42,8 +42,10 @@ SHAMap::walkBranch( // This is an inner node, add all non-empty branches auto inner = safe_downcast(node); for (int i = 0; i < 16; ++i) + { if (!inner->isEmptyBranch(i)) nodeStack.push({descendThrow(inner, i)}); + } } else { @@ -54,9 +56,13 @@ SHAMap::walkBranch( { // unmatched if (isFirstMap) + { differences.insert(std::make_pair(item->key(), DeltaRef(item, nullptr))); + } else + { differences.insert(std::make_pair(item->key(), DeltaRef(nullptr, item))); + } if (--maxCount <= 0) return false; @@ -65,9 +71,13 @@ SHAMap::walkBranch( { // non-matching items with same tag if (isFirstMap) + { differences.insert(std::make_pair(item->key(), DeltaRef(item, otherMapItem))); + } else + { differences.insert(std::make_pair(item->key(), DeltaRef(otherMapItem, item))); + } if (--maxCount <= 0) return false; @@ -85,12 +95,16 @@ SHAMap::walkBranch( if (!emptyBranch) { // otherMapItem was unmatched, must add - if (isFirstMap) // this is first map, so other item is from second + if (isFirstMap) + { // this is first map, so other item is from second differences.insert( std::make_pair(otherMapItem->key(), DeltaRef(nullptr, otherMapItem))); + } else + { differences.insert( std::make_pair(otherMapItem->key(), DeltaRef(otherMapItem, nullptr))); + } if (--maxCount <= 0) return false; @@ -179,6 +193,7 @@ SHAMap::compare(SHAMap const& otherMap, Delta& differences, int maxCount) const auto ours = safe_downcast(ourNode); auto other = safe_downcast(otherNode); for (int i = 0; i < 16; ++i) + { if (ours->getChildHash(i) != other->getChildHash(i)) { if (other->isEmptyBranch(i)) @@ -195,9 +210,12 @@ SHAMap::compare(SHAMap const& otherMap, Delta& differences, int maxCount) const if (!otherMap.walkBranch(iNode, nullptr, false, differences, maxCount)) return false; } - else // The two trees have different non-empty branches + else + { // The two trees have different non-empty branches nodeStack.push({descendThrow(ours, i), otherMap.descendThrow(other, i)}); + } } + } } else { @@ -306,9 +324,11 @@ SHAMap::walkMapParallel(std::vector& missingNodes, int maxMis if (nextNode) { if (nextNode->isInner()) + { nodeStack.push( intr_ptr::static_pointer_cast( nextNode)); + } } else { diff --git a/src/libxrpl/shamap/SHAMapInnerNode.cpp b/src/libxrpl/shamap/SHAMapInnerNode.cpp index 695e35c75d..599d343745 100644 --- a/src/libxrpl/shamap/SHAMapInnerNode.cpp +++ b/src/libxrpl/shamap/SHAMapInnerNode.cpp @@ -125,9 +125,13 @@ SHAMapInnerNode::makeFullInner(Slice data, SHAMapHash const& hash, bool hashVali ret->resizeChildArrays(ret->getBranchCount()); if (hashValid) + { ret->hash_ = hash; + } else + { ret->updateHash(); + } return ret; } @@ -253,9 +257,11 @@ SHAMapInnerNode::setChild(int m, intr_ptr::SharedPtr child) auto const dstIsBranch = [&] { if (child) + { return isBranch_ | (1u << m); - else - return isBranch_ & ~(1u << m); + } + + return isBranch_ & ~(1u << m); }(); auto const dstToAllocate = popcnt16(dstIsBranch); diff --git a/src/libxrpl/shamap/SHAMapLeafNode.cpp b/src/libxrpl/shamap/SHAMapLeafNode.cpp index 49dd99e935..3776de3a35 100644 --- a/src/libxrpl/shamap/SHAMapLeafNode.cpp +++ b/src/libxrpl/shamap/SHAMapLeafNode.cpp @@ -51,13 +51,21 @@ SHAMapLeafNode::getString(SHAMapNodeID const& id) const auto const type = getType(); if (type == SHAMapNodeType::tnTRANSACTION_NM) + { ret += ",txn\n"; + } else if (type == SHAMapNodeType::tnTRANSACTION_MD) + { ret += ",txn+md\n"; + } else if (type == SHAMapNodeType::tnACCOUNT_STATE) + { ret += ",as\n"; + } else + { ret += ",leaf\n"; + } ret += " Tag="; ret += to_string(item_->key()); diff --git a/src/libxrpl/shamap/SHAMapNodeID.cpp b/src/libxrpl/shamap/SHAMapNodeID.cpp index f7cc80e250..6536e628ef 100644 --- a/src/libxrpl/shamap/SHAMapNodeID.cpp +++ b/src/libxrpl/shamap/SHAMapNodeID.cpp @@ -107,9 +107,13 @@ selectBranch(SHAMapNodeID const& id, uint256 const& hash) auto branch = static_cast(*(hash.begin() + (depth / 2))); if (depth & 1) + { branch &= 0xf; + } else + { branch >>= 4; + } XRPL_ASSERT(branch < SHAMap::branchFactor, "xrpl::selectBranch : maximum result"); return branch; diff --git a/src/libxrpl/shamap/SHAMapSync.cpp b/src/libxrpl/shamap/SHAMapSync.cpp index 948d972c18..c6e4c3dcb0 100644 --- a/src/libxrpl/shamap/SHAMapSync.cpp +++ b/src/libxrpl/shamap/SHAMapSync.cpp @@ -46,7 +46,9 @@ SHAMap::visitNodes(std::function const& function) const return; if (child->isLeaf()) + { ++pos; + } else { // If there are no more children, don't push this node @@ -164,7 +166,7 @@ SHAMap::gmn_ProcessNodes(MissingNodes& mn, MissingNodes::StackEntry& se) auto const& childHash = node->getChildHash(branch); - if (mn.missingHashes_.count(childHash) != 0) + if (mn.missingHashes_.contains(childHash)) { // we already know this child node is missing fullBelow = false; @@ -358,8 +360,10 @@ SHAMap::getMissingNodes(int max, SHAMapSyncFilter* filter) { // Recheck nodes we could not finish before for (auto const& [innerNode, nodeId] : mn.resumes_) + { if (!innerNode->isFullBelow(mn.generation_)) mn.stack_.push(std::make_tuple(innerNode, nodeId, rand_int(255), 0, true)); + } mn.resumes_.clear(); } @@ -644,7 +648,7 @@ SHAMap::deepCompare(SHAMap& other) const JLOG(journal_.info()) << "unable to fetch node"; return false; } - else if (otherNode->getHash() != node->getHash()) + if (otherNode->getHash() != node->getHash()) { JLOG(journal_.warn()) << "node hash mismatch"; return false; diff --git a/src/libxrpl/tx/Transactor.cpp b/src/libxrpl/tx/Transactor.cpp index ec8e6aae2f..ff42441e2f 100644 --- a/src/libxrpl/tx/Transactor.cpp +++ b/src/libxrpl/tx/Transactor.cpp @@ -191,9 +191,11 @@ NotTEC Transactor::preflight2(PreflightContext const& ctx) { if (auto const ret = detail::preflightCheckSimulateKeys(ctx.flags, ctx.tx, ctx.j)) + { // Skips following checks if the transaction is being simulated, // regardless of success or failure return *ret; + } // It should be impossible for the InnerBatchTxn flag to be set without // featureBatch being enabled @@ -547,9 +549,13 @@ Transactor::ticketDelete( if (auto ticketCount = (*sleAccount)[~sfTicketCount]) { if (*ticketCount == 1) + { sleAccount->makeFieldAbsent(sfTicketCount); + } else + { ticketCount = *ticketCount - 1; + } } else { @@ -623,10 +629,12 @@ Transactor::checkSign( auto const sle = view.read(keylet::account(idAccount)); if (view.rules().enabled(featureLendingProtocol) && isPseudoAccount(sle)) + { // Pseudo-accounts can't sign transactions. This check is gated on // the Lending Protocol amendment because that's the project it was // added under, and it doesn't justify another amendment return tefBAD_AUTH; + } } auto const pkSigner = sigObject.getFieldVL(sfSigningPubKey); diff --git a/src/libxrpl/tx/apply.cpp b/src/libxrpl/tx/apply.cpp index caf42e9326..8fd898366e 100644 --- a/src/libxrpl/tx/apply.cpp +++ b/src/libxrpl/tx/apply.cpp @@ -50,8 +50,10 @@ checkValidity(HashRouter& router, STTx const& tx, Rules const& rules) } if (any(flags & SF_SIGBAD)) + { // Signature is known bad return {Validity::SigBad, "Transaction has bad signature."}; + } if (!any(flags & SF_SIGGOOD)) { @@ -66,14 +68,18 @@ checkValidity(HashRouter& router, STTx const& tx, Rules const& rules) // Signature is now known good if (any(flags & SF_LOCALBAD)) + { // ...but the local checks // are known bad. return {Validity::SigGoodOnly, "Local checks failed."}; + } if (any(flags & SF_LOCALGOOD)) + { // ...and the local checks // are known good. return {Validity::Valid, ""}; + } // Do the local checks std::string reason; @@ -189,7 +195,9 @@ applyBatchTransactions( break; } else if (mode & tfOnlyOne) + { break; + } } return applied != 0; diff --git a/src/libxrpl/tx/applySteps.cpp b/src/libxrpl/tx/applySteps.cpp index 0c8c538a11..6c6b3f8c98 100644 --- a/src/libxrpl/tx/applySteps.cpp +++ b/src/libxrpl/tx/applySteps.cpp @@ -344,6 +344,7 @@ preclaim(PreflightResult const& preflightResult, ServiceRegistry& registry, Open { auto secondFlight = [&]() { if (preflightResult.parentBatchId) + { return preflight( registry, view.rules(), @@ -351,6 +352,7 @@ preclaim(PreflightResult const& preflightResult, ServiceRegistry& registry, Open preflightResult.tx, preflightResult.flags, preflightResult.j); + } return preflight( registry, diff --git a/src/libxrpl/tx/invariants/AMMInvariant.cpp b/src/libxrpl/tx/invariants/AMMInvariant.cpp index 4d3c63cf4e..b64be6192b 100644 --- a/src/libxrpl/tx/invariants/AMMInvariant.cpp +++ b/src/libxrpl/tx/invariants/AMMInvariant.cpp @@ -55,8 +55,10 @@ validBalances( bool const positive = amount > beast::zero && amount2 > beast::zero && lptAMMBalance > beast::zero; if (zeroAllowed == ValidAMM::ZeroAllowed::Yes) + { return positive || (amount == beast::zero && amount2 == beast::zero && lptAMMBalance == beast::zero); + } return positive; } @@ -236,7 +238,9 @@ ValidAMM::finalizeDeposit( // LCOV_EXCL_STOP } else if (!generalInvariant(tx, view, ZeroAllowed::No, j) && enforce) + { return false; + } return true; } diff --git a/src/libxrpl/tx/invariants/FreezeInvariant.cpp b/src/libxrpl/tx/invariants/FreezeInvariant.cpp index 858c4cdcb8..f38d260782 100644 --- a/src/libxrpl/tx/invariants/FreezeInvariant.cpp +++ b/src/libxrpl/tx/invariants/FreezeInvariant.cpp @@ -157,9 +157,13 @@ TransfersNotFrozen::recordBalance(Issue const& issue, BalanceChange change) "balance sign."); auto& changes = balanceChanges_[issue]; if (change.balanceChangeSign < 0) + { changes.senders.emplace_back(std::move(change)); + } else + { changes.receivers.emplace_back(std::move(change)); + } } void diff --git a/src/libxrpl/tx/invariants/InvariantCheck.cpp b/src/libxrpl/tx/invariants/InvariantCheck.cpp index babeba9281..00580b2548 100644 --- a/src/libxrpl/tx/invariants/InvariantCheck.cpp +++ b/src/libxrpl/tx/invariants/InvariantCheck.cpp @@ -147,7 +147,7 @@ XRPNotCreated::finalize( TER const, XRPAmount const fee, ReadView const&, - beast::Journal const& j) + beast::Journal const& j) const { // The net change should never be positive, as this would mean that the // transaction created XRP out of thin air. That's not possible. @@ -207,7 +207,7 @@ XRPBalanceChecks::finalize( TER const, XRPAmount const, ReadView const&, - beast::Journal const& j) + beast::Journal const& j) const { if (bad_) { @@ -251,7 +251,7 @@ NoBadOffers::finalize( TER const, XRPAmount const, ReadView const&, - beast::Journal const& j) + beast::Journal const& j) const { if (bad_) { @@ -344,7 +344,7 @@ NoZeroEscrow::finalize( TER const, XRPAmount const, ReadView const& rv, - beast::Journal const& j) + beast::Journal const& j) const { if (bad_) { @@ -373,7 +373,7 @@ AccountRootsNotDeleted::finalize( TER const result, XRPAmount const, ReadView const&, - beast::Journal const& j) + beast::Journal const& j) const { // AMM account root can be deleted as the result of AMM withdraw/delete // transaction when the total AMM LP Tokens balance goes to 0. @@ -385,8 +385,10 @@ AccountRootsNotDeleted::finalize( return true; if (accountsDeleted_ == 0) + { JLOG(j.fatal()) << "Invariant failed: account deletion " "succeeded without deleting an account"; + } else JLOG(j.fatal()) << "Invariant failed: account deletion " "succeeded but deleted multiple accounts!"; @@ -565,7 +567,7 @@ LedgerEntryTypesMatch::finalize( TER const, XRPAmount const, ReadView const&, - beast::Journal const& j) + beast::Journal const& j) const { if ((!typeMismatch_) && (!invalidTypeAdded_)) return true; @@ -607,7 +609,7 @@ NoXRPTrustLines::finalize( TER const, XRPAmount const, ReadView const&, - beast::Journal const& j) + beast::Journal const& j) const { if (!xrpTrustLine_) return true; @@ -643,7 +645,7 @@ NoDeepFreezeTrustLinesWithoutFreeze::finalize( TER const, XRPAmount const, ReadView const&, - beast::Journal const& j) + beast::Journal const& j) const { if (!deepFreezeWithoutFreeze_) return true; @@ -676,7 +678,7 @@ ValidNewAccountRoot::finalize( TER const result, XRPAmount const, ReadView const& view, - beast::Journal const& j) + beast::Journal const& j) const { if (accountsCreated_ == 0) return true; @@ -751,7 +753,7 @@ ValidClawback::finalize( TER const result, XRPAmount const, ReadView const& view, - beast::Journal const& j) + beast::Journal const& j) const { if (tx.getTxnType() != ttCLAWBACK) return true; @@ -814,8 +816,10 @@ ValidPseudoAccounts::visitEntry( std::shared_ptr const& after) { if (isDelete) + { // Deletion is ignored return; + } if (after && after->getType() == ltACCOUNT_ROOT) { @@ -903,8 +907,10 @@ NoModifiedUnmodifiableFields::visitEntry( std::shared_ptr const& after) { if (isDelete || !before) + { // Creation and deletion are ignored return; + } changedEntries_.emplace(before, after); } diff --git a/src/libxrpl/tx/invariants/MPTInvariant.cpp b/src/libxrpl/tx/invariants/MPTInvariant.cpp index 56e0b54e7e..a3a5bf897d 100644 --- a/src/libxrpl/tx/invariants/MPTInvariant.cpp +++ b/src/libxrpl/tx/invariants/MPTInvariant.cpp @@ -19,15 +19,21 @@ ValidMPTIssuance::visitEntry( if (after && after->getType() == ltMPTOKEN_ISSUANCE) { if (isDelete) + { mptIssuancesDeleted_++; + } else if (!before) + { mptIssuancesCreated_++; + } } if (after && after->getType() == ltMPTOKEN) { if (isDelete) + { mptokensDeleted_++; + } else if (!before) { mptokensCreated_++; @@ -44,7 +50,7 @@ ValidMPTIssuance::finalize( TER const result, XRPAmount const _fee, ReadView const& view, - beast::Journal const& j) + beast::Journal const& j) const { if (isTesSuccess(result)) { @@ -122,26 +128,25 @@ ValidMPTIssuance::finalize( "succeeded but created MPT issuances"; return false; } - else if (mptIssuancesDeleted_ > 0) + if (mptIssuancesDeleted_ > 0) { JLOG(j.fatal()) << "Invariant failed: MPT authorize " "succeeded but deleted issuances"; return false; } - else if (lendingProtocolEnabled && mptokensCreated_ + mptokensDeleted_ > 1) + if (lendingProtocolEnabled && mptokensCreated_ + mptokensDeleted_ > 1) { JLOG(j.fatal()) << "Invariant failed: MPT authorize succeeded " "but created/deleted bad number mptokens"; return false; } - else if (submittedByIssuer && (mptokensCreated_ > 0 || mptokensDeleted_ > 0)) + if (submittedByIssuer && (mptokensCreated_ > 0 || mptokensDeleted_ > 0)) { JLOG(j.fatal()) << "Invariant failed: MPT authorize submitted by issuer " "succeeded but created/deleted mptokens"; return false; } - else if ( - !submittedByIssuer && hasPrivilege(tx, mustAuthorizeMPT) && + if (!submittedByIssuer && hasPrivilege(tx, mustAuthorizeMPT) && (mptokensCreated_ + mptokensDeleted_ != 1)) { // if the holder submitted this tx, then a mptoken must be diff --git a/src/libxrpl/tx/invariants/NFTInvariant.cpp b/src/libxrpl/tx/invariants/NFTInvariant.cpp index 7077625b60..cf00dc9290 100644 --- a/src/libxrpl/tx/invariants/NFTInvariant.cpp +++ b/src/libxrpl/tx/invariants/NFTInvariant.cpp @@ -120,7 +120,7 @@ ValidNFTokenPage::finalize( TER const result, XRPAmount const, ReadView const& view, - beast::Journal const& j) + beast::Journal const& j) const { if (badLink_) { @@ -196,7 +196,7 @@ NFTokenCountTracking::finalize( TER const result, XRPAmount const, ReadView const& view, - beast::Journal const& j) + beast::Journal const& j) const { if (!hasPrivilege(tx, changeNFTCounts)) { diff --git a/src/libxrpl/tx/invariants/PermissionedDEXInvariant.cpp b/src/libxrpl/tx/invariants/PermissionedDEXInvariant.cpp index e12312ad0f..e932a6ba09 100644 --- a/src/libxrpl/tx/invariants/PermissionedDEXInvariant.cpp +++ b/src/libxrpl/tx/invariants/PermissionedDEXInvariant.cpp @@ -24,9 +24,13 @@ ValidPermissionedDEX::visitEntry( if (after && after->getType() == ltOFFER) { if (after->isFieldPresent(sfDomainID)) + { domains_.insert(after->getFieldH256(sfDomainID)); + } else + { regularOffers_ = true; + } // if a hybrid offer is missing domain or additional book, there's // something wrong diff --git a/src/libxrpl/tx/invariants/PermissionedDomainInvariant.cpp b/src/libxrpl/tx/invariants/PermissionedDomainInvariant.cpp index 541be69623..d4cbe81f9b 100644 --- a/src/libxrpl/tx/invariants/PermissionedDomainInvariant.cpp +++ b/src/libxrpl/tx/invariants/PermissionedDomainInvariant.cpp @@ -90,9 +90,10 @@ ValidPermissionedDomain::finalize( { // No permissioned domains should be affected if the transaction failed if (!isTesSuccess(result)) - // If nothing changed, all is good. If there were changes, that's - // bad. + { + // If nothing changed, all is good. If there were changes, that's bad. return sleStatus_.empty(); + } if (sleStatus_.size() > 1) { diff --git a/src/libxrpl/tx/invariants/VaultInvariant.cpp b/src/libxrpl/tx/invariants/VaultInvariant.cpp index c3db3a563a..e955e00b50 100644 --- a/src/libxrpl/tx/invariants/VaultInvariant.cpp +++ b/src/libxrpl/tx/invariants/VaultInvariant.cpp @@ -157,7 +157,7 @@ ValidVault::finalize( return true; // Not a vault operation } - else if (!(hasPrivilege(tx, mustModifyVault) || hasPrivilege(tx, mayModifyVault))) + if (!(hasPrivilege(tx, mustModifyVault) || hasPrivilege(tx, mayModifyVault))) { JLOG(j.fatal()) << // "Invariant failed: vault updated by a wrong transaction type"; @@ -239,7 +239,7 @@ ValidVault::finalize( return result; } - else if (txnType == ttVAULT_DELETE) + if (txnType == ttVAULT_DELETE) { JLOG(j.fatal()) << "Invariant failed: vault deletion succeeded without " "deleting a vault"; diff --git a/src/libxrpl/tx/paths/Flow.cpp b/src/libxrpl/tx/paths/Flow.cpp index c27eb54cbe..fc33585179 100644 --- a/src/libxrpl/tx/paths/Flow.cpp +++ b/src/libxrpl/tx/paths/Flow.cpp @@ -16,9 +16,13 @@ finishFlow(PaymentSandbox& sb, Issue const& srcIssue, Issue const& dstIssue, Flo { path::RippleCalc::Output result; if (isTesSuccess(f.ter)) + { f.sandbox->apply(sb); + } else + { result.removableOffers = std::move(f.removableOffers); + } result.setResult(f.ter); result.actualAmountIn = toSTAmount(f.in, srcIssue); diff --git a/src/libxrpl/tx/paths/OfferStream.cpp b/src/libxrpl/tx/paths/OfferStream.cpp index 596ae36b96..b406c27298 100644 --- a/src/libxrpl/tx/paths/OfferStream.cpp +++ b/src/libxrpl/tx/paths/OfferStream.cpp @@ -95,8 +95,10 @@ accountFundsHelper( beast::Journal j) { if (issue.account == id) + { // self funded return amtDefault; + } return toAmount( accountHolds(view, id, issue.currency, issue.account, freezeHandling, j)); diff --git a/src/libxrpl/tx/transactors/account/DeleteAccount.cpp b/src/libxrpl/tx/transactors/account/DeleteAccount.cpp index 639e83c7e6..a70cc24549 100644 --- a/src/libxrpl/tx/transactors/account/DeleteAccount.cpp +++ b/src/libxrpl/tx/transactors/account/DeleteAccount.cpp @@ -30,8 +30,10 @@ NotTEC DeleteAccount::preflight(PreflightContext const& ctx) { if (ctx.tx[sfAccount] == ctx.tx[sfDestination]) + { // An account cannot be deleted and give itself the resulting XRP. return temDST_IS_SRC; + } if (auto const err = credentials::checkFields(ctx.tx, ctx.j); !isTesSuccess(err)) return err; diff --git a/src/libxrpl/tx/transactors/account/SetAccount.cpp b/src/libxrpl/tx/transactors/account/SetAccount.cpp index 032b4727ad..9bb92c2ea5 100644 --- a/src/libxrpl/tx/transactors/account/SetAccount.cpp +++ b/src/libxrpl/tx/transactors/account/SetAccount.cpp @@ -126,7 +126,7 @@ SetAccount::preflight(PreflightContext const& ctx) if (auto const mk = tx[~sfMessageKey]) { - if (mk->size() && !publicKeyType({mk->data(), mk->size()})) + if (!mk->empty() && !publicKeyType({mk->data(), mk->size()})) { JLOG(j.trace()) << "Invalid message key specified."; return telBAD_PUBLIC_KEY; @@ -565,32 +565,52 @@ SetAccount::doApply() sle->makeFieldAbsent(sfNFTokenMinter); if (uSetFlag == asfDisallowIncomingNFTokenOffer) + { uFlagsOut |= lsfDisallowIncomingNFTokenOffer; + } else if (uClearFlag == asfDisallowIncomingNFTokenOffer) + { uFlagsOut &= ~lsfDisallowIncomingNFTokenOffer; + } if (uSetFlag == asfDisallowIncomingCheck) + { uFlagsOut |= lsfDisallowIncomingCheck; + } else if (uClearFlag == asfDisallowIncomingCheck) + { uFlagsOut &= ~lsfDisallowIncomingCheck; + } if (uSetFlag == asfDisallowIncomingPayChan) + { uFlagsOut |= lsfDisallowIncomingPayChan; + } else if (uClearFlag == asfDisallowIncomingPayChan) + { uFlagsOut &= ~lsfDisallowIncomingPayChan; + } if (uSetFlag == asfDisallowIncomingTrustline) + { uFlagsOut |= lsfDisallowIncomingTrustline; + } else if (uClearFlag == asfDisallowIncomingTrustline) + { uFlagsOut &= ~lsfDisallowIncomingTrustline; + } // Set or clear flags for disallowing escrow if (ctx_.view().rules().enabled(featureTokenEscrow)) { if (uSetFlag == asfAllowTrustLineLocking) + { uFlagsOut |= lsfAllowTrustLineLocking; + } else if (uClearFlag == asfAllowTrustLineLocking) + { uFlagsOut &= ~lsfAllowTrustLineLocking; + } } // Set flag for clawback diff --git a/src/libxrpl/tx/transactors/account/SetSignerList.cpp b/src/libxrpl/tx/transactors/account/SetSignerList.cpp index 2a807febd3..54fe91aaa6 100644 --- a/src/libxrpl/tx/transactors/account/SetSignerList.cpp +++ b/src/libxrpl/tx/transactors/account/SetSignerList.cpp @@ -124,7 +124,7 @@ SetSignerList::preCompute() signers_ = std::get<2>(result); do_ = std::get<3>(result); - return Transactor::preCompute(); + Transactor::preCompute(); } // The return type is signed so it is compatible with the 3rd argument diff --git a/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp b/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp index b0c1d657dd..2e274f138d 100644 --- a/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp +++ b/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp @@ -1027,8 +1027,10 @@ applyCreateAccountAttestations( XChainCreateAccountAttestations curAtts = [&] { if (sleClaimID) + { return XChainCreateAccountAttestations{ sleClaimID->getFieldArray(sfXChainCreateAccountAttestations)}; + } return XChainCreateAccountAttestations{}; }(); @@ -1203,8 +1205,10 @@ attestationDoApply(ApplyContext& ctx) { auto const att = toClaim(ctx.tx); if (!att) + { // Should already be checked in preflight return tecINTERNAL; // LCOV_EXCL_LINE + } STXChainBridge const bridgeSpec = ctx.tx[sfXChainBridge]; @@ -1233,11 +1237,17 @@ attestationDoApply(ApplyContext& ctx) STXChainBridge::ChainType dstChain = STXChainBridge::ChainType::locking; { if (thisDoor == bridgeSpec.lockingChainDoor()) + { dstChain = STXChainBridge::ChainType::locking; + } else if (thisDoor == bridgeSpec.issuingChainDoor()) + { dstChain = STXChainBridge::ChainType::issuing; + } else + { return Unexpected(tecINTERNAL); + } } STXChainBridge::ChainType const srcChain = STXChainBridge::otherChain(dstChain); @@ -1598,11 +1608,17 @@ XChainClaim::preclaim(PreclaimContext const& ctx) bool isLockingChain = false; { if (thisDoor == bridgeSpec.lockingChainDoor()) + { isLockingChain = true; + } else if (thisDoor == bridgeSpec.issuingChainDoor()) + { isLockingChain = false; + } else + { return tecINTERNAL; // LCOV_EXCL_LINE + } } { @@ -1631,9 +1647,13 @@ XChainClaim::preclaim(PreclaimContext const& ctx) auto const otherChainAmount = [&]() -> STAmount { STAmount r(thisChainAmount); if (isLockingChain) + { r.setIssue(bridgeSpec.issuingChainIssue()); + } else + { r.setIssue(bridgeSpec.lockingChainIssue()); + } return r; }(); @@ -1696,11 +1716,17 @@ XChainClaim::doApply() STXChainBridge::ChainType dstChain = STXChainBridge::ChainType::locking; { if (thisDoor == bridgeSpec.lockingChainDoor()) + { dstChain = STXChainBridge::ChainType::locking; + } else if (thisDoor == bridgeSpec.issuingChainDoor()) + { dstChain = STXChainBridge::ChainType::issuing; + } else + { return Unexpected(tecINTERNAL); + } } STXChainBridge::ChainType const srcChain = STXChainBridge::otherChain(dstChain); @@ -1823,11 +1849,17 @@ XChainCommit::preclaim(PreclaimContext const& ctx) bool isLockingChain = false; { if (thisDoor == bridgeSpec.lockingChainDoor()) + { isLockingChain = true; + } else if (thisDoor == bridgeSpec.issuingChainDoor()) + { isLockingChain = false; + } else + { return tecINTERNAL; // LCOV_EXCL_LINE + } } if (isLockingChain) @@ -2095,11 +2127,17 @@ XChainCreateAccountCommit::preclaim(PreclaimContext const& ctx) STXChainBridge::ChainType srcChain = STXChainBridge::ChainType::locking; { if (thisDoor == bridgeSpec.lockingChainDoor()) + { srcChain = STXChainBridge::ChainType::locking; + } else if (thisDoor == bridgeSpec.issuingChainDoor()) + { srcChain = STXChainBridge::ChainType::issuing; + } else + { return tecINTERNAL; // LCOV_EXCL_LINE + } } STXChainBridge::ChainType const dstChain = STXChainBridge::otherChain(srcChain); diff --git a/src/libxrpl/tx/transactors/check/CashCheck.cpp b/src/libxrpl/tx/transactors/check/CashCheck.cpp index 35368836a3..cba945cc82 100644 --- a/src/libxrpl/tx/transactors/check/CashCheck.cpp +++ b/src/libxrpl/tx/transactors/check/CashCheck.cpp @@ -265,8 +265,10 @@ CashCheck::doApply() } if (optDeliverMin) + { // Set the DeliveredAmount metadata. ctx_.deliver(xrpDeliver); + } // The source account has enough XRP so make the ledger change. if (TER const ter{transferXRP(psb, srcId, account_, xrpDeliver, viewJ)}; diff --git a/src/libxrpl/tx/transactors/delegate/DelegateSet.cpp b/src/libxrpl/tx/transactors/delegate/DelegateSet.cpp index 58f68b628a..2a9aafc6be 100644 --- a/src/libxrpl/tx/transactors/delegate/DelegateSet.cpp +++ b/src/libxrpl/tx/transactors/delegate/DelegateSet.cpp @@ -66,8 +66,10 @@ DelegateSet::doApply() { auto const& permissions = ctx_.tx.getFieldArray(sfPermissions); if (permissions.empty()) + { // if permissions array is empty, delete the ledger object. return deleteDelegate(view(), sle, account_, j_); + } sle->setFieldArray(sfPermissions, permissions); ctx_.view().update(sle); diff --git a/src/libxrpl/tx/transactors/dex/AMMBid.cpp b/src/libxrpl/tx/transactors/dex/AMMBid.cpp index cc255edcf2..a1ace702dc 100644 --- a/src/libxrpl/tx/transactors/dex/AMMBid.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMBid.cpp @@ -46,13 +46,13 @@ AMMBid::preflight(PreflightContext const& ctx) if (ctx.tx.isFieldPresent(sfAuthAccounts)) { - if (auto const authAccounts = ctx.tx.getFieldArray(sfAuthAccounts); - authAccounts.size() > AUCTION_SLOT_MAX_AUTH_ACCOUNTS) + auto const authAccounts = ctx.tx.getFieldArray(sfAuthAccounts); + if (authAccounts.size() > AUCTION_SLOT_MAX_AUTH_ACCOUNTS) { JLOG(ctx.j.debug()) << "AMM Bid: Invalid number of AuthAccounts."; return temMALFORMED; } - else if (ctx.rules.enabled(fixAMMv1_3)) + if (ctx.rules.enabled(fixAMMv1_3)) { AccountID account = ctx.tx[sfAccount]; std::set unique; @@ -193,14 +193,22 @@ applyBid(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::Jour auctionSlot.setAccountID(sfAccount, account_); auctionSlot.setFieldU32(sfExpiration, current + TOTAL_TIME_SLOT_SECS); if (fee != 0) + { auctionSlot.setFieldU16(sfDiscountedFee, fee); + } else if (auctionSlot.isFieldPresent(sfDiscountedFee)) + { auctionSlot.makeFieldAbsent(sfDiscountedFee); + } auctionSlot.setFieldAmount(sfPrice, toSTAmount(lpTokens.issue(), minPrice)); if (ctx_.tx.isFieldPresent(sfAuthAccounts)) + { auctionSlot.setFieldArray(sfAuthAccounts, ctx_.tx.getFieldArray(sfAuthAccounts)); + } else + { auctionSlot.makeFieldAbsent(sfAuthAccounts); + } // Burn the remaining bid amount auto const saBurn = adjustLPTokens(lptAMMBalance, toSTAmount(lptAMMBalance.issue(), burn), IsDeposit::No); @@ -245,7 +253,7 @@ applyBid(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::Jour { return std::max(computedPrice, Number(*bidMin)); } - else if (bidMax) + if (bidMax) { if (computedPrice <= *bidMax) return computedPrice; @@ -253,23 +261,30 @@ applyBid(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::Jour << "AMM Bid: not in range " << computedPrice << " " << *bidMax; return std::nullopt; } - else - return computedPrice; + + return computedPrice; }(); if (!payPrice) + { return Unexpected(tecAMM_FAILED); - else if (payPrice > lpTokens) + } + if (payPrice > lpTokens) + { return Unexpected(tecAMM_INVALID_TOKENS); + } return *payPrice; }; // No one owns the slot or expired slot. if (auto const acct = auctionSlot[~sfAccount]; !acct || !validOwner(*acct)) { - if (auto const payPrice = getPayPrice(minSlotPrice); !payPrice) + auto const payPrice = getPayPrice(minSlotPrice); + if (!payPrice) + { return {payPrice.error(), false}; - else - res = updateSlot(discountedFee, *payPrice, *payPrice); + } + + res = updateSlot(discountedFee, *payPrice, *payPrice); } else { diff --git a/src/libxrpl/tx/transactors/dex/AMMClawback.cpp b/src/libxrpl/tx/transactors/dex/AMMClawback.cpp index 20645238c5..a5fda15033 100644 --- a/src/libxrpl/tx/transactors/dex/AMMClawback.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMClawback.cpp @@ -156,6 +156,7 @@ AMMClawback::applyGuts(Sandbox& sb) return tecAMM_BALANCE; if (!clawAmount) + { // Because we are doing a two-asset withdrawal, // tfee is actually not used, so pass tfee as 0. std::tie(result, newLPTokenBalance, amountWithdraw, amount2Withdraw) = @@ -174,7 +175,9 @@ AMMClawback::applyGuts(Sandbox& sb) WithdrawAll::Yes, preFeeBalance_, ctx_.journal); + } else + { std::tie(result, newLPTokenBalance, amountWithdraw, amount2Withdraw) = equalWithdrawMatchingOneAmount( sb, @@ -186,6 +189,7 @@ AMMClawback::applyGuts(Sandbox& sb) lptAMMBalance, holdLPtokens, *clawAmount); + } if (!isTesSuccess(result)) return result; // LCOV_EXCL_LINE @@ -235,6 +239,7 @@ AMMClawback::equalWithdrawMatchingOneAmount( auto const lpTokensWithdraw = toSTAmount(lptAMMBalance.issue(), lptAMMBalance * frac); if (lpTokensWithdraw > holdLPtokens) + { // if lptoken balance less than what the issuer intended to clawback, // clawback all the tokens. Because we are doing a two-asset withdrawal, // tfee is actually not used, so pass tfee as 0. @@ -253,6 +258,7 @@ AMMClawback::equalWithdrawMatchingOneAmount( WithdrawAll::Yes, preFeeBalance_, ctx_.journal); + } auto const& rules = sb.rules(); if (rules.enabled(fixAMMClawbackRounding)) diff --git a/src/libxrpl/tx/transactors/dex/AMMCreate.cpp b/src/libxrpl/tx/transactors/dex/AMMCreate.cpp index 38eea436dd..86128ed1cd 100644 --- a/src/libxrpl/tx/transactors/dex/AMMCreate.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMCreate.cpp @@ -163,9 +163,10 @@ AMMCreate::preclaim(PreclaimContext const& ctx) auto clawbackDisabled = [&](Issue const& issue) -> TER { if (isXRP(issue)) return tesSUCCESS; - if (auto const sle = ctx.view.read(keylet::account(issue.account)); !sle) + auto const sle = ctx.view.read(keylet::account(issue.account)); + if (!sle) return tecINTERNAL; // LCOV_EXCL_LINE - else if (sle->getFlags() & lsfAllowTrustLineClawback) + if (sle->getFlags() & lsfAllowTrustLineClawback) return tecNO_PERMISSION; return tesSUCCESS; }; @@ -244,15 +245,15 @@ applyCreate(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::J // Set AMM flag on AMM trustline if (!isXRP(amount)) { - if (SLE::pointer sleRippleState = sb.peek(keylet::line(accountId, amount.issue())); - !sleRippleState) - return tecINTERNAL; // LCOV_EXCL_LINE - else + SLE::pointer sleRippleState = sb.peek(keylet::line(accountId, amount.issue())); + if (!sleRippleState) { - auto const flags = sleRippleState->getFlags(); - sleRippleState->setFieldU32(sfFlags, flags | lsfAMMNode); - sb.update(sleRippleState); + return tecINTERNAL; // LCOV_EXCL_LINE } + + auto const flags = sleRippleState->getFlags(); + sleRippleState->setFieldU32(sfFlags, flags | lsfAMMNode); + sb.update(sleRippleState); } return tesSUCCESS; }; diff --git a/src/libxrpl/tx/transactors/dex/AMMDeposit.cpp b/src/libxrpl/tx/transactors/dex/AMMDeposit.cpp index c83b1f2245..9b78b9e2bf 100644 --- a/src/libxrpl/tx/transactors/dex/AMMDeposit.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMDeposit.cpp @@ -356,6 +356,7 @@ AMMDeposit::applyGuts(Sandbox& sb) &lptAMMBalance = lptAMMBalance]() -> std::pair { if (subTxType & tfTwoAsset) + { return equalDepositLimit( sb, ammAccountID, @@ -366,16 +367,24 @@ AMMDeposit::applyGuts(Sandbox& sb) *amount2, lpTokensDeposit, tfee); + } if (subTxType & tfOneAssetLPToken) + { return singleDepositTokens( sb, ammAccountID, amountBalance, *amount, lptAMMBalance, *lpTokensDeposit, tfee); + } if (subTxType & tfLimitLPToken) + { return singleDepositEPrice( sb, ammAccountID, amountBalance, *amount, lptAMMBalance, *ePrice, tfee); + } if (subTxType & tfSingleAsset) + { return singleDeposit( sb, ammAccountID, amountBalance, lptAMMBalance, *amount, lpTokensDeposit, tfee); + } if (subTxType & tfLPToken) + { return equalDepositTokens( sb, ammAccountID, @@ -386,9 +395,12 @@ AMMDeposit::applyGuts(Sandbox& sb) amount, amount2, tfee); + } if (subTxType & tfTwoAssetIfEmpty) + { return equalDepositInEmptyState( sb, ammAccountID, *amount, *amount2, lptAMMBalance.issue(), tfee); + } // should not happen. // LCOV_EXCL_START JLOG(j_.error()) << "AMM Deposit: invalid options."; @@ -462,7 +474,9 @@ AMMDeposit::deposit( depositAmount.issue(), FreezeHandling::fhIGNORE_FREEZE, ctx_.journal) >= depositAmount) + { return tesSUCCESS; + } return tecUNFUNDED_AMM; }; @@ -646,14 +660,17 @@ AMMDeposit::equalDepositLimit( if (tokensAdj == beast::zero) { if (!view.rules().enabled(fixAMMv1_3)) + { return {tecAMM_FAILED, STAmount{}}; // LCOV_EXCL_LINE - else - return {tecAMM_INVALID_TOKENS, STAmount{}}; + } + + return {tecAMM_INVALID_TOKENS, STAmount{}}; } // factor in the adjusted tokens frac = adjustFracByTokens(view.rules(), lptAMMBalance, tokensAdj, frac); auto const amount2Deposit = getRoundedAsset(view.rules(), amount2Balance, frac, IsDeposit::Yes); if (amount2Deposit <= amount2) + { return deposit( view, ammAccount, @@ -666,19 +683,23 @@ AMMDeposit::equalDepositLimit( std::nullopt, lpTokensDepositMin, tfee); + } frac = Number{amount2} / amount2Balance; tokensAdj = getRoundedLPTokens(view.rules(), lptAMMBalance, frac, IsDeposit::Yes); if (tokensAdj == beast::zero) { if (!view.rules().enabled(fixAMMv1_3)) + { return {tecAMM_FAILED, STAmount{}}; // LCOV_EXCL_LINE - else - return {tecAMM_INVALID_TOKENS, STAmount{}}; // LCOV_EXCL_LINE + } + + return {tecAMM_INVALID_TOKENS, STAmount{}}; // LCOV_EXCL_LINE } // factor in the adjusted tokens frac = adjustFracByTokens(view.rules(), lptAMMBalance, tokensAdj, frac); auto const amountDeposit = getRoundedAsset(view.rules(), amountBalance, frac, IsDeposit::Yes); if (amountDeposit <= amount) + { return deposit( view, ammAccount, @@ -691,6 +712,7 @@ AMMDeposit::equalDepositLimit( std::nullopt, lpTokensDepositMin, tfee); + } return {tecAMM_FAILED, STAmount{}}; } @@ -717,9 +739,11 @@ AMMDeposit::singleDeposit( if (tokens == beast::zero) { if (!view.rules().enabled(fixAMMv1_3)) + { return {tecAMM_FAILED, STAmount{}}; // LCOV_EXCL_LINE - else - return {tecAMM_INVALID_TOKENS, STAmount{}}; + } + + return {tecAMM_INVALID_TOKENS, STAmount{}}; } // factor in the adjusted tokens auto const [tokensAdj, amountDepositAdj] = @@ -820,9 +844,11 @@ AMMDeposit::singleDepositEPrice( if (tokens <= beast::zero) { if (!view.rules().enabled(fixAMMv1_3)) + { return {tecAMM_FAILED, STAmount{}}; // LCOV_EXCL_LINE - else - return {tecAMM_INVALID_TOKENS, STAmount{}}; + } + + return {tecAMM_INVALID_TOKENS, STAmount{}}; } // factor in the adjusted tokens auto const [tokensAdj, amountDepositAdj] = @@ -831,6 +857,7 @@ AMMDeposit::singleDepositEPrice( return {tecAMM_INVALID_TOKENS, STAmount{}}; // LCOV_EXCL_LINE auto const ep = Number{amountDepositAdj} / tokensAdj; if (ep <= ePrice) + { return deposit( view, ammAccount, @@ -843,6 +870,7 @@ AMMDeposit::singleDepositEPrice( std::nullopt, std::nullopt, tfee); + } } // LPTokens is asset out => E = b / t diff --git a/src/libxrpl/tx/transactors/dex/AMMHelpers.cpp b/src/libxrpl/tx/transactors/dex/AMMHelpers.cpp index 75aa51c9d4..20ffab52ca 100644 --- a/src/libxrpl/tx/transactors/dex/AMMHelpers.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMHelpers.cpp @@ -34,12 +34,10 @@ lpTokensOut( auto const t = lptAMMBalance * (r - c) / (1 + c); return toSTAmount(lptAMMBalance.issue(), t); } - else - { - // minimize tokens out - auto const frac = (r - c) / (1 + c); - return multiply(lptAMMBalance, frac, Number::downward); - } + + // minimize tokens out + auto const frac = (r - c) / (1 + c); + return multiply(lptAMMBalance, frac, Number::downward); } /* Equation 4 solves equation 3 for b: @@ -72,12 +70,10 @@ ammAssetIn( { return toSTAmount(asset1Balance.issue(), asset1Balance * solveQuadraticEq(a, b, c)); } - else - { - // maximize deposit - auto const frac = solveQuadraticEq(a, b, c); - return multiply(asset1Balance, frac, Number::upward); - } + + // maximize deposit + auto const frac = solveQuadraticEq(a, b, c); + return multiply(asset1Balance, frac, Number::upward); } /* Equation 7: @@ -99,12 +95,10 @@ lpTokensIn( auto const t = lptAMMBalance * (c - root2(c * c - 4 * fr)) / 2; return toSTAmount(lptAMMBalance.issue(), t); } - else - { - // maximize tokens in - auto const frac = (c - root2(c * c - 4 * fr)) / 2; - return multiply(lptAMMBalance, frac, Number::upward); - } + + // maximize tokens in + auto const frac = (c - root2(c * c - 4 * fr)) / 2; + return multiply(lptAMMBalance, frac, Number::upward); } /* Equation 8 solves equation 7 for b: @@ -131,12 +125,10 @@ ammAssetOut( auto const b = assetBalance * (t1 * t1 - t1 * (2 - f)) / (t1 * f - 1); return toSTAmount(assetBalance.issue(), b); } - else - { - // minimize withdraw - auto const frac = (t1 * t1 - t1 * (2 - f)) / (t1 * f - 1); - return multiply(assetBalance, frac, Number::downward); - } + + // minimize withdraw + auto const frac = (t1 * t1 - t1 * (2 - f)) / (t1 * f - 1); + return multiply(assetBalance, frac, Number::downward); } Number @@ -194,29 +186,37 @@ adjustAmountsByLPTokens( auto const amountActual = toSTAmount(amount.issue(), fr * amount); auto const amount2Actual = toSTAmount(amount2->issue(), fr * *amount2); if (!ammRoundingEnabled) + { return std::make_tuple( amountActual < amount ? amountActual : amount, amount2Actual < amount2 ? amount2Actual : amount2, lpTokensActual); - else - return std::make_tuple(amountActual, amount2Actual, lpTokensActual); + } + + return std::make_tuple(amountActual, amount2Actual, lpTokensActual); } // Single trade auto const amountActual = [&]() { if (isDeposit == IsDeposit::Yes) + { return ammAssetIn(amountBalance, lptAMMBalance, lpTokensActual, tfee); - else if (!ammRoundingEnabled) + } + if (!ammRoundingEnabled) + { return ammAssetOut(amountBalance, lptAMMBalance, lpTokens, tfee); - else - return ammAssetOut(amountBalance, lptAMMBalance, lpTokensActual, tfee); + } + + return ammAssetOut(amountBalance, lptAMMBalance, lpTokensActual, tfee); }(); if (!ammRoundingEnabled) + { return amountActual < amount ? std::make_tuple(amountActual, std::nullopt, lpTokensActual) : std::make_tuple(amount, std::nullopt, lpTokensActual); - else - return std::make_tuple(amountActual, std::nullopt, lpTokensActual); + } + + return std::make_tuple(amountActual, std::nullopt, lpTokensActual); } XRPL_ASSERT( @@ -241,9 +241,11 @@ solveQuadraticEqSmallest(Number const& a, Number const& b, Number const& c) // use numerically stable citardauq formula for quadratic equation solution // https://people.csail.mit.edu/bkph/articles/Quadratics.pdf if (b > 0) + { return (2 * c) / (-b - root2(d)); - else - return (2 * c) / (-b + root2(d)); + } + + return (2 * c) / (-b + root2(d)); } STAmount diff --git a/src/libxrpl/tx/transactors/dex/AMMUtils.cpp b/src/libxrpl/tx/transactors/dex/AMMUtils.cpp index ed008ca75b..91891ce86f 100644 --- a/src/libxrpl/tx/transactors/dex/AMMUtils.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMUtils.cpp @@ -52,9 +52,13 @@ ammHolds( Issue checkIssue, char const* label) -> std::optional> { if (checkIssue == issue1) + { return std::make_optional(std::make_pair(issue1, issue2)); - else if (checkIssue == issue2) + } + if (checkIssue == issue2) + { return std::make_optional(std::make_pair(issue2, issue1)); + } // Unreachable unless AMM corrupted. // LCOV_EXCL_START JLOG(j.debug()) << "ammHolds: Invalid " << label << " " << checkIssue; @@ -65,7 +69,7 @@ ammHolds( { return singleIssue(*optIssue1, "optIssue1"); } - else if (optIssue2) + if (optIssue2) { // Cannot have Amount2 without Amount. return singleIssue(*optIssue2, "optIssue2"); // LCOV_EXCL_LINE @@ -165,8 +169,10 @@ getTradingFee(ReadView const& view, SLE const& ammSle, AccountID const& account) if (auctionSlot.isFieldPresent(sfAuthAccounts)) { for (auto const& acct : auctionSlot.getFieldArray(sfAuthAccounts)) + { if (acct[~sfAccount] == account) return auctionSlot[sfDiscountedFee]; + } } } } @@ -323,13 +329,21 @@ initializeFeeAuctionVote( auctionSlot.setFieldAmount(sfPrice, STAmount{lptIssue, 0}); // Set the fee if (tfee != 0) + { ammSle->setFieldU16(sfTradingFee, tfee); + } else if (ammSle->isFieldPresent(sfTradingFee)) + { ammSle->makeFieldAbsent(sfTradingFee); // LCOV_EXCL_LINE + } if (auto const dfee = tfee / AUCTION_SLOT_DISCOUNTED_FEE_FRACTION) + { auctionSlot.setFieldU16(sfDiscountedFee, dfee); + } else if (auctionSlot.isFieldPresent(sfDiscountedFee)) + { auctionSlot.makeFieldAbsent(sfDiscountedFee); // LCOV_EXCL_LINE + } } Expected @@ -390,13 +404,19 @@ isOnlyLiquidityProvider(ReadView const& view, Issue const& ammIssue, AccountID c return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE } else if (++nIOUTrustLines > 2) + { return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + } } // Another Liquidity Provider LPToken trustline else if (isLPTokenTrustline) + { return false; + } else if (++nIOUTrustLines > 2) + { return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + } } auto const uNodeNext = ownerDir->getFieldU64(sfIndexNext); if (uNodeNext == 0) @@ -417,9 +437,13 @@ verifyAndAdjustLPTokenBalance( std::shared_ptr& ammSle, AccountID const& account) { - if (auto const res = isOnlyLiquidityProvider(sb, lpTokens.issue(), account); !res) + auto const res = isOnlyLiquidityProvider(sb, lpTokens.issue(), account); + if (!res.has_value()) + { return Unexpected(res.error()); - else if (res.value()) + } + + if (res.value()) { if (withinRelativeDistance( lpTokens, ammSle->getFieldAmount(sfLPTokenBalance), Number{1, -3})) diff --git a/src/libxrpl/tx/transactors/dex/AMMVote.cpp b/src/libxrpl/tx/transactors/dex/AMMVote.cpp index d784b67f88..2096eca0f0 100644 --- a/src/libxrpl/tx/transactors/dex/AMMVote.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMVote.cpp @@ -35,15 +35,17 @@ AMMVote::preflight(PreflightContext const& ctx) TER AMMVote::preclaim(PreclaimContext const& ctx) { - if (auto const ammSle = ctx.view.read(keylet::amm(ctx.tx[sfAsset], ctx.tx[sfAsset2])); !ammSle) + auto const ammSle = ctx.view.read(keylet::amm(ctx.tx[sfAsset], ctx.tx[sfAsset2])); + if (!ammSle) { JLOG(ctx.j.debug()) << "AMM Vote: Invalid asset pair."; return terNO_AMM; } - else if (ammSle->getFieldAmount(sfLPTokenBalance) == beast::zero) + if (ammSle->getFieldAmount(sfLPTokenBalance) == beast::zero) + { return tecAMM_EMPTY; - else if ( - auto const lpTokensNew = ammLPHolds(ctx.view, *ammSle, ctx.tx[sfAccount], ctx.j); + } + if (auto const lpTokensNew = ammLPHolds(ctx.view, *ammSle, ctx.tx[sfAccount], ctx.j); lpTokensNew == beast::zero) { JLOG(ctx.j.debug()) << "AMM Vote: account is not LP."; @@ -134,16 +136,22 @@ applyVote(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::Jou num += feeNew * lpTokensNew; den += lpTokensNew; if (minPos) + { *(updatedVoteSlots.begin() + *minPos) = std::move(newEntry); + } else + { updatedVoteSlots.push_back(std::move(newEntry)); + } }; // Add new entry if the number of the vote entries // is less than Max. if (updatedVoteSlots.size() < VOTE_MAX_SLOTS) + { update(); - // Add the entry if the account has more tokens than - // the least token holder or same tokens and higher fee. + // Add the entry if the account has more tokens than + // the least token holder or same tokens and higher fee. + } else if (lpTokensNew > *minTokens || (lpTokensNew == *minTokens && feeNew > minFee)) { auto const entry = updatedVoteSlots.begin() + minPos; @@ -174,9 +182,13 @@ applyVote(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::Jou { auto& auctionSlot = ammSle->peekFieldObject(sfAuctionSlot); if (auto const discountedFee = fee / AUCTION_SLOT_DISCOUNTED_FEE_FRACTION) + { auctionSlot.setFieldU16(sfDiscountedFee, discountedFee); + } else if (auctionSlot.isFieldPresent(sfDiscountedFee)) + { auctionSlot.makeFieldAbsent(sfDiscountedFee); + } } } else diff --git a/src/libxrpl/tx/transactors/dex/AMMWithdraw.cpp b/src/libxrpl/tx/transactors/dex/AMMWithdraw.cpp index 8b0b75b317..f43367ac21 100644 --- a/src/libxrpl/tx/transactors/dex/AMMWithdraw.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMWithdraw.cpp @@ -305,6 +305,7 @@ AMMWithdraw::applyGuts(Sandbox& sb) &lptAMMBalance = lptAMMBalance]() -> std::pair { if (subTxType & tfTwoAsset) + { return equalWithdrawLimit( sb, *ammSle, @@ -315,7 +316,9 @@ AMMWithdraw::applyGuts(Sandbox& sb) *amount, *amount2, tfee); + } if (subTxType & tfOneAssetLPToken || subTxType & tfOneAssetWithdrawAll) + { return singleWithdrawTokens( sb, *ammSle, @@ -325,12 +328,17 @@ AMMWithdraw::applyGuts(Sandbox& sb) *amount, *lpTokensWithdraw, tfee); + } if (subTxType & tfLimitLPToken) + { return singleWithdrawEPrice( sb, *ammSle, ammAccountID, amountBalance, lptAMMBalance, *amount, *ePrice, tfee); + } if (subTxType & tfSingleAsset) + { return singleWithdraw( sb, *ammSle, ammAccountID, amountBalance, lptAMMBalance, *amount, tfee); + } if (subTxType & tfLPToken || subTxType & tfWithdrawAll) { return equalWithdrawTokens( @@ -449,6 +457,7 @@ AMMWithdraw::withdraw( auto const [amountWithdrawActual, amount2WithdrawActual, lpTokensWithdrawActual] = [&]() -> std::tuple, STAmount> { if (withdrawAll == WithdrawAll::No) + { return adjustAmountsByLPTokens( amountBalance, amountWithdraw, @@ -457,6 +466,7 @@ AMMWithdraw::withdraw( lpTokensWithdraw, tfee, IsDeposit::No); + } return std::make_tuple(amountWithdraw, amount2Withdraw, lpTokensWithdraw); }(); @@ -649,8 +659,8 @@ AMMWithdraw::deleteAMMAccountIfEmpty( ter = deleteAMMAccount(sb, issue1, issue2, journal); if (!isTesSuccess(ter) && ter != tecINCOMPLETE) return {ter, false}; // LCOV_EXCL_LINE - else - updateBalance = (ter == tecINCOMPLETE); + + updateBalance = (ter == tecINCOMPLETE); } if (updateBalance) @@ -821,7 +831,9 @@ AMMWithdraw::equalWithdrawLimit( // LCOV_EXCL_STOP } else if (amountWithdraw > amount) + { return {tecAMM_FAILED, STAmount{}}; // LCOV_EXCL_LINE + } return withdraw( view, ammSle, @@ -857,9 +869,11 @@ AMMWithdraw::singleWithdraw( if (tokens == beast::zero) { if (!view.rules().enabled(fixAMMv1_3)) + { return {tecAMM_FAILED, STAmount{}}; // LCOV_EXCL_LINE - else - return {tecAMM_INVALID_TOKENS, STAmount{}}; + } + + return {tecAMM_INVALID_TOKENS, STAmount{}}; } // factor in the adjusted tokens auto const [tokensAdj, amountWithdrawAdj] = @@ -973,9 +987,11 @@ AMMWithdraw::singleWithdrawEPrice( if (tokensAdj <= beast::zero) { if (!view.rules().enabled(fixAMMv1_3)) + { return {tecAMM_FAILED, STAmount{}}; - else - return {tecAMM_INVALID_TOKENS, STAmount{}}; + } + + return {tecAMM_INVALID_TOKENS, STAmount{}}; } auto amtNoRoundCb = [&] { return tokensAdj / ePrice; }; auto amtProdCb = [&] { return tokensAdj / ePrice; }; diff --git a/src/libxrpl/tx/transactors/dex/CreateOffer.cpp b/src/libxrpl/tx/transactors/dex/CreateOffer.cpp index a620584c4e..58241803a9 100644 --- a/src/libxrpl/tx/transactors/dex/CreateOffer.cpp +++ b/src/libxrpl/tx/transactors/dex/CreateOffer.cpp @@ -337,14 +337,18 @@ CreateOffer::flowCross( // specified. Since we don't know how much they might offer, // we allow delivery of the largest possible amount. if (deliver.native()) + { deliver = STAmount{STAmount::cMaxNative}; + } else + { // We can't use the maximum possible currency here because // there might be a gateway transfer rate to account for. // Since the transfer rate cannot exceed 200%, we use 1/2 // maxValue for our limit. deliver = STAmount{ takerAmount.out.issue(), STAmount::cMaxValue / 2, STAmount::cMaxOffset}; + } } // Call the payment engine's flow() to do the actual work. @@ -402,17 +406,21 @@ CreateOffer::flowCross( // gateway's transfer rate. STAmount nonGatewayAmountIn = result.actualAmountIn; if (gatewayXferRate.value != QUALITY_ONE) + { nonGatewayAmountIn = divideRound( result.actualAmountIn, gatewayXferRate, takerAmount.in.issue(), true); + } afterCross.in -= nonGatewayAmountIn; // It's possible that the divRound will cause our subtract // to go slightly negative. So limit afterCross.in to zero. if (afterCross.in < beast::zero) + { // We should verify that the difference *is* small, but // what is a good threshold to check? afterCross.in.clear(); + } afterCross.out = divRoundStrict(afterCross.in, rate, takerAmount.out.issue(), false); @@ -713,10 +721,12 @@ CreateOffer::applyGuts(Sandbox& sb, Sandbox& sbCancel) { JLOG(j_.trace()) << "Immediate or cancel: offer canceled"; if (!crossed) + { // Any ImmediateOrCancel offer that transfers absolutely no funds // returns tecKILLED rather than tesSUCCESS. Motivation for the // change is here: https://github.com/ripple/rippled/issues/4115 return {tecKILLED, false}; + } return {tesSUCCESS, true}; } @@ -855,9 +865,13 @@ CreateOffer::doApply() auto const result = applyGuts(sb, sbCancel); if (result.second) + { sb.apply(ctx_.rawView()); + } else + { sbCancel.apply(ctx_.rawView()); + } return result.first; } diff --git a/src/libxrpl/tx/transactors/escrow/EscrowCancel.cpp b/src/libxrpl/tx/transactors/escrow/EscrowCancel.cpp index 153366f167..61e27a7c38 100644 --- a/src/libxrpl/tx/transactors/escrow/EscrowCancel.cpp +++ b/src/libxrpl/tx/transactors/escrow/EscrowCancel.cpp @@ -150,7 +150,9 @@ EscrowCancel::doApply() // Transfer amount back to the owner if (isXRP(amount)) + { (*sle)[sfBalance] = (*sle)[sfBalance] + amount; + } else { if (!ctx_.view().rules().enabled(featureTokenEscrow)) diff --git a/src/libxrpl/tx/transactors/escrow/EscrowCreate.cpp b/src/libxrpl/tx/transactors/escrow/EscrowCreate.cpp index bf3a6c7600..adeee09390 100644 --- a/src/libxrpl/tx/transactors/escrow/EscrowCreate.cpp +++ b/src/libxrpl/tx/transactors/escrow/EscrowCreate.cpp @@ -476,7 +476,9 @@ EscrowCreate::doApply() // Deduct owner's balance if (isXRP(amount)) + { (*sle)[sfBalance] = (*sle)[sfBalance] - amount; + } else { if (auto const ret = std::visit( diff --git a/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp b/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp index d3167b95b9..680a20a077 100644 --- a/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp +++ b/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp @@ -81,9 +81,13 @@ EscrowFinish::preflightSigValidated(PreflightContext const& ctx) if (!any(flags & (SF_CF_INVALID | SF_CF_VALID))) { if (checkCondition(*fb, *cb)) + { router.setFlags(id, SF_CF_VALID); + } else + { router.setFlags(id, SF_CF_INVALID); + } } } @@ -246,9 +250,13 @@ EscrowFinish::doApply() return tecINTERNAL; if (checkCondition(*fb, *cb)) + { flags = SF_CF_VALID; + } else + { flags = SF_CF_INVALID; + } ctx_.registry.getHashRouter().setFlags(id, flags); // LCOV_EXCL_STOP @@ -315,7 +323,9 @@ EscrowFinish::doApply() STAmount const amount = slep->getFieldAmount(sfAmount); // Transfer amount to destination if (isXRP(amount)) + { (*sled)[sfBalance] = (*sled)[sfBalance] + amount; + } else { if (!ctx_.view().rules().enabled(featureTokenEscrow)) diff --git a/src/libxrpl/tx/transactors/lending/LendingHelpers.cpp b/src/libxrpl/tx/transactors/lending/LendingHelpers.cpp index d7162bbb0e..ad4cd8440d 100644 --- a/src/libxrpl/tx/transactors/lending/LendingHelpers.cpp +++ b/src/libxrpl/tx/transactors/lending/LendingHelpers.cpp @@ -856,9 +856,11 @@ computeFullPayment( << ", untrackedInterest: " << full.untrackedInterest; if (amount < full.totalDue) + { // If the payment is less than the full payment amount, it's not // sufficient to be a full payment. return Unexpected(tecINSUFFICIENT_PAYMENT); + } return full; } @@ -1635,24 +1637,26 @@ loanMakePayment( LoanState const roundedLoanState = constructLoanState( totalValueOutstandingProxy, principalOutstandingProxy, managementFeeOutstandingProxy); - if (auto const fullPaymentComponents = detail::computeFullPayment( - asset, - view, - principalOutstandingProxy, - managementFeeOutstandingProxy, - periodicPayment, - paymentRemainingProxy, - prevPaymentDateProxy, - startDate, - paymentInterval, - closeInterestRate, - loanScale, - roundedLoanState.interestDue, - periodicRate, - closePaymentFee, - amount, - managementFeeRate, - j)) + auto const fullPaymentComponents = detail::computeFullPayment( + asset, + view, + principalOutstandingProxy, + managementFeeOutstandingProxy, + periodicPayment, + paymentRemainingProxy, + prevPaymentDateProxy, + startDate, + paymentInterval, + closeInterestRate, + loanScale, + roundedLoanState.interestDue, + periodicRate, + closePaymentFee, + amount, + managementFeeRate, + j); + + if (fullPaymentComponents.has_value()) { return doPayment( *fullPaymentComponents, @@ -1664,11 +1668,14 @@ loanMakePayment( nextDueDateProxy, paymentInterval); } - else if (fullPaymentComponents.error()) + + if (fullPaymentComponents.error()) + { // error() will be the TER returned if a payment is not made. It // will only evaluate to true if it's unsuccessful. Otherwise, // tesSUCCESS means nothing was done, so continue. return Unexpected(fullPaymentComponents.error()); + } // LCOV_EXCL_START UNREACHABLE("xrpl::loanMakePayment : invalid full payment result"); @@ -1704,18 +1711,20 @@ loanMakePayment( TenthBips32 const lateInterestRate{loan->at(sfLateInterestRate)}; Number const latePaymentFee = loan->at(sfLatePaymentFee); - if (auto const latePaymentComponents = detail::computeLatePayment( - asset, - view, - principalOutstandingProxy, - nextDueDateProxy, - periodic, - lateInterestRate, - loanScale, - latePaymentFee, - amount, - managementFeeRate, - j)) + auto const latePaymentComponents = detail::computeLatePayment( + asset, + view, + principalOutstandingProxy, + nextDueDateProxy, + periodic, + lateInterestRate, + loanScale, + latePaymentFee, + amount, + managementFeeRate, + j); + + if (latePaymentComponents.has_value()) { return doPayment( *latePaymentComponents, @@ -1727,7 +1736,8 @@ loanMakePayment( nextDueDateProxy, paymentInterval); } - else if (latePaymentComponents.error()) + + if (latePaymentComponents.error()) { // error() will be the TER returned if a payment is not made. It // will only evaluate to true if it's unsuccessful. @@ -1858,13 +1868,17 @@ loanMakePayment( paymentRemainingProxy, managementFeeRate, j)) + { totalParts += *overResult; + } else if (overResult.error()) + { // error() will be the TER returned if a payment is not // made. It will only evaluate to true if it's unsuccessful. // Otherwise, tesSUCCESS means nothing was done, so // continue. return Unexpected(overResult.error()); + } } } diff --git a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp index 8513ae5999..4c55a7d33a 100644 --- a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp @@ -118,14 +118,14 @@ determineAsset( { return amount.asset(); } - else if (holder == brokerPseudoAccountID) + if (holder == brokerPseudoAccountID) { // We want the asset to match the vault asset, so use the account as the // issuer return Issue{amount.getCurrency(), account}; } - else - return Unexpected(tecWRONG_ASSET); + + return Unexpected(tecWRONG_ASSET); } Expected diff --git a/src/libxrpl/tx/transactors/lending/LoanPay.cpp b/src/libxrpl/tx/transactors/lending/LoanPay.cpp index d894c56631..3543b7607f 100644 --- a/src/libxrpl/tx/transactors/lending/LoanPay.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanPay.cpp @@ -56,9 +56,11 @@ LoanPay::calculateBaseFee(ReadView const& view, STTx const& tx) auto const normalCost = Transactor::calculateBaseFee(view, tx); if (tx.isFlag(tfLoanFullPayment) || tx.isFlag(tfLoanLatePayment)) + { // The loan will be making one set of calculations for one full or late // payment return normalCost; + } // The fee is based on the potential number of payments, unless the loan is // being fully paid off. @@ -67,8 +69,10 @@ LoanPay::calculateBaseFee(ReadView const& view, STTx const& tx) auto const loanSle = view.read(keylet::loan(loanID)); if (!loanSle) + { // Let preclaim worry about the error for this return normalCost; + } if (loanSle->at(sfPaymentRemaining) <= loanPaymentsPerFeeIncrement) { @@ -78,24 +82,32 @@ LoanPay::calculateBaseFee(ReadView const& view, STTx const& tx) } if (hasExpired(view, loanSle->at(sfNextPaymentDueDate))) + { // If the payment is late, and the late payment flag is not set, it'll // fail return normalCost; + } auto const brokerSle = view.read(keylet::loanbroker(loanSle->at(sfLoanBrokerID))); if (!brokerSle) + { // Let preclaim worry about the error for this return normalCost; + } auto const vaultSle = view.read(keylet::vault(brokerSle->at(sfVaultID))); if (!vaultSle) + { // Let preclaim worry about the error for this return normalCost; + } auto const asset = vaultSle->at(sfAsset); if (asset != amount.asset()) + { // Let preclaim worry about the error for this return normalCost; + } auto const scale = loanSle->at(sfLoanScale); @@ -517,9 +529,11 @@ LoanPay::doApply() if (auto const ter = addEmptyHolding( view, brokerPayee, brokerPayeeSle->at(sfBalance).value().xrp(), asset, j_); ter && ter != tecDUPLICATE) + { // ignore tecDUPLICATE. That means the holding already exists, // and is fine here return ter; + } } if (auto const ter = requireAuth(view, asset, brokerPayee, AuthType::StrongAuth)) return ter; diff --git a/src/libxrpl/tx/transactors/lending/LoanSet.cpp b/src/libxrpl/tx/transactors/lending/LoanSet.cpp index 848af47957..7212f079ce 100644 --- a/src/libxrpl/tx/transactors/lending/LoanSet.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanSet.cpp @@ -62,9 +62,10 @@ LoanSet::preflight(PreflightContext const& ctx) return temINVALID; } // Principal Requested is required - if (auto const p = tx[sfPrincipalRequested]; p <= 0) + auto const p = tx[sfPrincipalRequested]; + if (p <= 0) return temINVALID; - else if (!validNumericRange(tx[~sfLoanOriginationFee], p)) + if (!validNumericRange(tx[~sfLoanOriginationFee], p)) return temINVALID; if (!validNumericRange(tx[~sfInterestRate], maxInterestRate)) return temINVALID; @@ -80,17 +81,16 @@ LoanSet::preflight(PreflightContext const& ctx) if (auto const paymentTotal = tx[~sfPaymentTotal]; paymentTotal && *paymentTotal <= 0) return temINVALID; - if (auto const paymentInterval = tx[~sfPaymentInterval]; - !validNumericMinimum(paymentInterval, LoanSet::minPaymentInterval)) - return temINVALID; - // Grace period is between min default value and payment interval - else if ( - auto const gracePeriod = tx[~sfGracePeriod]; // - !validNumericRange( + auto const paymentInterval = tx[~sfPaymentInterval]; + if (!validNumericMinimum(paymentInterval, LoanSet::minPaymentInterval)) + return temINVALID; // Grace period is between min default value and payment interval + if (auto const gracePeriod = tx[~sfGracePeriod]; !validNumericRange( gracePeriod, paymentInterval.value_or(LoanSet::defaultPaymentInterval), defaultGracePeriod)) + { return temINVALID; + } // Copied from preflight2 if (counterPartySig) @@ -150,12 +150,12 @@ LoanSet::calculateBaseFee(ReadView const& view, STTx const& tx) // for the transaction. Note that unlike the base class, the single signer // is counted if present. It will only be absent in a batch inner // transaction. - std::size_t const signerCount = [&counterSig]() { - // Compute defensively. Assure that "tx" cannot be accessed and cause - // confusion or miscalculations. - return counterSig.isFieldPresent(sfSigners) - ? counterSig.getFieldArray(sfSigners).size() - : (counterSig.isFieldPresent(sfTxnSignature) ? 1 : 0); + std::size_t const signerCount = [&counterSig]() -> int { + // Compute defensively. + // Assure that "tx" cannot be accessed and cause confusion or miscalculations. + if (counterSig.isFieldPresent(sfSigners)) + return counterSig.getFieldArray(sfSigners).size(); + return counterSig.isFieldPresent(sfTxnSignature) ? 1 : 0; }(); return normalCost + (signerCount * baseFee); @@ -266,8 +266,10 @@ LoanSet::preclaim(PreclaimContext const& ctx) auto const vault = ctx.view.read(keylet::vault(brokerSle->at(sfVaultID))); if (!vault) + { // Should be impossible return tefBAD_LEDGER; // LCOV_EXCL_LINE + } if (vault->at(sfAssetsMaximum) != 0 && vault->at(sfAssetsTotal) >= vault->at(sfAssetsMaximum)) { @@ -492,9 +494,11 @@ LoanSet::doApply() if (auto const ter = addEmptyHolding( view, borrower, borrowerSle->at(sfBalance).value().xrp(), vaultAsset, j_); ter && ter != tecDUPLICATE) + { // ignore tecDUPLICATE. That means the holding already exists, and // is fine here return ter; + } if (auto const ter = requireAuth(view, vaultAsset, borrower, AuthType::StrongAuth)) return ter; @@ -513,9 +517,11 @@ LoanSet::doApply() if (auto const ter = addEmptyHolding( view, brokerOwner, brokerOwnerSle->at(sfBalance).value().xrp(), vaultAsset, j_); ter && ter != tecDUPLICATE) + { // ignore tecDUPLICATE. That means the holding already exists, // and is fine here return ter; + } } if (auto const ter = requireAuth(view, vaultAsset, brokerOwner, AuthType::StrongAuth)) diff --git a/src/libxrpl/tx/transactors/nft/NFTokenAcceptOffer.cpp b/src/libxrpl/tx/transactors/nft/NFTokenAcceptOffer.cpp index 15ea1eb074..3022188ccf 100644 --- a/src/libxrpl/tx/transactors/nft/NFTokenAcceptOffer.cpp +++ b/src/libxrpl/tx/transactors/nft/NFTokenAcceptOffer.cpp @@ -271,8 +271,10 @@ NFTokenAcceptOffer::preclaim(PreclaimContext const& ctx) // this nftoken auto const& offer = bo ? bo : so; if (!offer) + { // Purely defensive, should be caught in preflight. return tecINTERNAL; // LCOV_EXCL_LINE + } auto const& tokenID = offer->at(sfNFTokenID); auto const& amount = offer->at(sfAmount); diff --git a/src/libxrpl/tx/transactors/nft/NFTokenMint.cpp b/src/libxrpl/tx/transactors/nft/NFTokenMint.cpp index 538d28718f..7bebbd0070 100644 --- a/src/libxrpl/tx/transactors/nft/NFTokenMint.cpp +++ b/src/libxrpl/tx/transactors/nft/NFTokenMint.cpp @@ -47,11 +47,16 @@ NFTokenMint::getFlagsMask(PreflightContext const& ctx) // The fixRemoveNFTokenAutoTrustLine amendment disables minting with the // tfTrustLine flag as a way to prevent the attack. But until the // amendment passes we still need to keep the old behavior available. - std::uint32_t const nfTokenMintMask = ctx.rules.enabled(fixRemoveNFTokenAutoTrustLine) - // if featureDynamicNFT enabled then new flag allowing mutable URI available - ? ctx.rules.enabled(featureDynamicNFT) ? tfNFTokenMintMask : tfNFTokenMintMaskWithoutMutable - : ctx.rules.enabled(featureDynamicNFT) ? tfNFTokenMintOldMaskWithMutable - : tfNFTokenMintOldMask; + std::uint32_t const nfTokenMintMask = [&]() -> std::uint32_t { + if (ctx.rules.enabled(fixRemoveNFTokenAutoTrustLine)) + { + // if featureDynamicNFT enabled then new flag allowing mutable URI available + return ctx.rules.enabled(featureDynamicNFT) ? tfNFTokenMintMask + : tfNFTokenMintMaskWithoutMutable; + } + return ctx.rules.enabled(featureDynamicNFT) ? tfNFTokenMintOldMaskWithMutable + : tfNFTokenMintOldMask; + }(); return nfTokenMintMask; } @@ -76,7 +81,7 @@ NFTokenMint::preflight(PreflightContext const& ctx) if (auto uri = ctx.tx[~sfURI]) { - if (uri->length() == 0 || uri->length() > maxTokenURILength) + if (uri->empty() || uri->length() > maxTokenURILength) return temMALFORMED; } @@ -202,8 +207,10 @@ NFTokenMint::doApply() auto const tokenSeq = [this, &issuer]() -> Expected { auto const root = view().peek(keylet::account(issuer)); if (root == nullptr) + { // Should not happen. Checked in preclaim. return Unexpected(tecNO_ISSUER); + } // If the issuer hasn't minted an NFToken before we must add a // FirstNFTokenSequence field to the issuer's AccountRoot. The @@ -259,8 +266,10 @@ NFTokenMint::doApply() InnerObjectFormats::getInstance().findSOTemplateBySField(sfNFToken); if (nfTokenTemplate == nullptr) + { // Should never happen. return tecINTERNAL; // LCOV_EXCL_LINE + } auto const nftokenID = createNFTokenID( extractNFTokenFlagsFromTxFlags(ctx_.tx.getFlags()), diff --git a/src/libxrpl/tx/transactors/nft/NFTokenModify.cpp b/src/libxrpl/tx/transactors/nft/NFTokenModify.cpp index af852530e4..1b2c9c2ab0 100644 --- a/src/libxrpl/tx/transactors/nft/NFTokenModify.cpp +++ b/src/libxrpl/tx/transactors/nft/NFTokenModify.cpp @@ -13,7 +13,7 @@ NFTokenModify::preflight(PreflightContext const& ctx) if (auto uri = ctx.tx[~sfURI]) { - if (uri->length() == 0 || uri->length() > maxTokenURILength) + if (uri->empty() || uri->length() > maxTokenURILength) return temMALFORMED; } diff --git a/src/libxrpl/tx/transactors/nft/NFTokenUtils.cpp b/src/libxrpl/tx/transactors/nft/NFTokenUtils.cpp index 177092787c..40b7171015 100644 --- a/src/libxrpl/tx/transactors/nft/NFTokenUtils.cpp +++ b/src/libxrpl/tx/transactors/nft/NFTokenUtils.cpp @@ -101,9 +101,11 @@ getPageForToken( // equivalent NFTokens then check the front of the page for a // place to make the split. if (splitIter == narr.end()) + { splitIter = std::find_if(narr.begin(), narr.end(), [&cmp](STObject const& obj) { return (obj.getFieldH256(sfNFTokenID) & nft::pageMask) == cmp; }); + } // There should be no circumstance when splitIter == end(), but if it // were to happen we should bail out because something is confused. @@ -218,9 +220,13 @@ changeTokenURI( return tecINTERNAL; // LCOV_EXCL_LINE if (uri) + { nftIter->setFieldVL(sfURI, *uri); + } else if (nftIter->isFieldPresent(sfURI)) + { nftIter->makeFieldAbsent(sfURI); + } view.update(page); return tesSUCCESS; @@ -368,9 +374,11 @@ removeToken( page2 = view.peek(Keylet(ltNFTOKEN_PAGE, *id)); if (!page2) + { Throw( "page " + to_string(page1->key()) + " has a broken " + field.getName() + " field pointing to " + to_string(*id)); + } } return page2; @@ -396,11 +404,13 @@ removeToken( cnt--; if (cnt != 0) + { adjustOwnerCount( view, view.peek(keylet::account(owner)), cnt, beast::Journal{beast::Journal::getNullSink()}); + } return tesSUCCESS; } @@ -448,9 +458,13 @@ removeToken( // The page is empty and not the last page, so we can just unlink it // and then remove it. if (next) + { prev->setFieldH256(sfNextPageMin, next->key()); + } else + { prev->makeFieldAbsent(sfNextPageMin); + } view.update(prev); } @@ -459,9 +473,13 @@ removeToken( { // Make our next page point to our previous page: if (prev) + { next->setFieldH256(sfPreviousPageMin, prev->key()); + } else + { next->makeFieldAbsent(sfPreviousPageMin); + } view.update(next); } @@ -526,8 +544,10 @@ findTokenAndPage(ApplyView& view, AccountID const& owner, uint256 const& nftoken for (auto const& t : page->getFieldArray(sfNFTokens)) { if (t[sfNFTokenID] == nftokenID) + { // This std::optional constructor is explicit, so it is spelled out. return std::optional(std::in_place, t, std::move(page)); + } } return std::nullopt; } @@ -564,10 +584,14 @@ removeTokenOffersWithLimit(ApplyView& view, Keylet const& directory, std::size_t if (auto const offer = view.peek(keylet::nftoffer(offerIndexes[i]))) { if (deleteTokenOffer(view, offer)) + { ++deletedOffersCount; + } else + { Throw( "Offer " + to_string(offerIndexes[i]) + " cannot be deleted!"); + } } if (maxDeletableOffers == deletedOffersCount) @@ -696,8 +720,10 @@ repairNFTokenDirectoryLinks(ApplyView& view, AccountID const& owner) } if (nextPage->key() == last.key) + { // We need special handling for the last page. break; + } page = nextPage; } @@ -727,9 +753,11 @@ repairNFTokenDirectoryLinks(ApplyView& view, AccountID const& owner) // Also fix up the NextPageMin link in the new Previous. auto const newPrev = view.peek(Keylet(ltNFTOKEN_PAGE, *prevLink)); if (!newPrev) + { Throw( "NFTokenPage directory for " + to_string(owner) + " cannot be repaired. Unexpected link problem."); + } newPrev->at(sfNextPageMin) = nextPage->key(); view.update(newPrev); } @@ -760,8 +788,10 @@ tokenOfferCreatePreflight( std::uint32_t txFlags) { if (amount.negative()) + { // An offer for a negative amount makes no sense. return temBAD_AMOUNT; + } if (!isXRP(amount)) { diff --git a/src/libxrpl/tx/transactors/oracle/DeleteOracle.cpp b/src/libxrpl/tx/transactors/oracle/DeleteOracle.cpp index 5452096b6d..78bba900da 100644 --- a/src/libxrpl/tx/transactors/oracle/DeleteOracle.cpp +++ b/src/libxrpl/tx/transactors/oracle/DeleteOracle.cpp @@ -18,14 +18,15 @@ DeleteOracle::preclaim(PreclaimContext const& ctx) if (!ctx.view.exists(keylet::account(ctx.tx.getAccountID(sfAccount)))) return terNO_ACCOUNT; // LCOV_EXCL_LINE - if (auto const sle = ctx.view.read( - keylet::oracle(ctx.tx.getAccountID(sfAccount), ctx.tx[sfOracleDocumentID])); - !sle) + auto const sle = + ctx.view.read(keylet::oracle(ctx.tx.getAccountID(sfAccount), ctx.tx[sfOracleDocumentID])); + if (!sle) { JLOG(ctx.j.debug()) << "Oracle Delete: Oracle does not exist."; return tecNO_ENTRY; } - else if (ctx.tx.getAccountID(sfAccount) != sle->getAccountID(sfOwner)) + + if (ctx.tx.getAccountID(sfAccount) != sle->getAccountID(sfOwner)) { // this can't happen because of the above check // LCOV_EXCL_START diff --git a/src/libxrpl/tx/transactors/oracle/SetOracle.cpp b/src/libxrpl/tx/transactors/oracle/SetOracle.cpp index be827c25d5..62ca6c5ea0 100644 --- a/src/libxrpl/tx/transactors/oracle/SetOracle.cpp +++ b/src/libxrpl/tx/transactors/oracle/SetOracle.cpp @@ -77,11 +77,17 @@ SetOracle::preclaim(PreclaimContext const& ctx) if (entry[~sfScale] > maxPriceScale) return temMALFORMED; if (entry.isFieldPresent(sfAssetPrice)) + { pairs.emplace(key); + } else if (sle) + { pairsDel.emplace(key); + } else + { return temMALFORMED; + } } // Lambda is used to check if the value of a field, passed @@ -111,9 +117,13 @@ SetOracle::preclaim(PreclaimContext const& ctx) if (!pairs.contains(key)) { if (pairsDel.contains(key)) + { pairsDel.erase(key); + } else + { pairs.emplace(key); + } } } if (!pairsDel.empty()) diff --git a/src/libxrpl/tx/transactors/payment/Payment.cpp b/src/libxrpl/tx/transactors/payment/Payment.cpp index 8663a70b9e..8bf86b7b38 100644 --- a/src/libxrpl/tx/transactors/payment/Payment.cpp +++ b/src/libxrpl/tx/transactors/payment/Payment.cpp @@ -33,15 +33,19 @@ getMaxSourceAmount( std::optional const& sendMax) { if (sendMax) + { return *sendMax; - else if (dstAmount.native() || dstAmount.holds()) + } + if (dstAmount.native() || dstAmount.holds()) + { return dstAmount; - else - return STAmount( - Issue{dstAmount.get().currency, account}, - dstAmount.mantissa(), - dstAmount.exponent(), - dstAmount < beast::zero); + } + + return STAmount( + Issue{dstAmount.get().currency, account}, + dstAmount.mantissa(), + dstAmount.exponent(), + dstAmount < beast::zero); } bool @@ -282,7 +286,7 @@ Payment::preclaim(PreclaimContext const& ctx) // transaction would succeed. return tecNO_DST; } - else if (ctx.view.open() && partialPaymentAllowed) + if (ctx.view.open() && partialPaymentAllowed) { // You cannot fund an account with a partial payment. // Make retry work smaller, by rejecting this. @@ -293,7 +297,7 @@ Payment::preclaim(PreclaimContext const& ctx) // transaction would succeed. return telNO_DST_PARTIAL; } - else if (dstAmount < STAmount(ctx.view.fees().reserve)) + if (dstAmount < STAmount(ctx.view.fees().reserve)) { // accountReserve is the minimum amount that an account can have. // Reserve is not scaled by load. @@ -438,9 +442,13 @@ Payment::doApply() if (isTesSuccess(rc.result()) && rc.actualAmountOut != dstAmount) { if (deliverMin && rc.actualAmountOut < *deliverMin) + { rc.setResult(tecPATH_PARTIAL); + } else + { ctx_.deliver(rc.actualAmountOut); + } } auto terResult = rc.result(); @@ -453,7 +461,7 @@ Payment::doApply() terResult = tecPATH_DRY; return terResult; } - else if (mptDirect) + if (mptDirect) { JLOG(j_.trace()) << " dstAmount=" << dstAmount.getFullText(); auto const& mptIssue = dstAmount.get(); @@ -524,7 +532,9 @@ Payment::doApply() ctx_.deliver(amountDeliver); } else if (res == tecINSUFFICIENT_FUNDS || res == tecPATH_DRY) + { res = tecPATH_PARTIAL; + } return res; } diff --git a/src/libxrpl/tx/transactors/payment_channel/PayChanClaim.cpp b/src/libxrpl/tx/transactors/payment_channel/PayChanClaim.cpp index d41e6f043c..e70c1f11ac 100644 --- a/src/libxrpl/tx/transactors/payment_channel/PayChanClaim.cpp +++ b/src/libxrpl/tx/transactors/payment_channel/PayChanClaim.cpp @@ -135,8 +135,10 @@ PayChanClaim::doApply() return tecUNFUNDED_PAYMENT; if (reqBalance <= chanBalance) + { // nothing requested return tecUNFUNDED_PAYMENT; + } auto const sled = ctx_.view().peek(keylet::account(dst)); if (!sled) diff --git a/src/libxrpl/tx/transactors/payment_channel/PayChanFund.cpp b/src/libxrpl/tx/transactors/payment_channel/PayChanFund.cpp index eb6fe1d2a9..f01b8a7c40 100644 --- a/src/libxrpl/tx/transactors/payment_channel/PayChanFund.cpp +++ b/src/libxrpl/tx/transactors/payment_channel/PayChanFund.cpp @@ -42,8 +42,10 @@ PayChanFund::doApply() } if (src != txAccount) + { // only the owner can add funds or extend return tecNO_PERMISSION; + } if (auto extend = ctx_.tx[~sfExpiration]) { diff --git a/src/libxrpl/tx/transactors/system/Batch.cpp b/src/libxrpl/tx/transactors/system/Batch.cpp index d27c42f88f..b2a111a182 100644 --- a/src/libxrpl/tx/transactors/system/Batch.cpp +++ b/src/libxrpl/tx/transactors/system/Batch.cpp @@ -105,9 +105,13 @@ Batch::calculateBaseFee(ReadView const& view, STTx const& tx) for (STObject const& signer : signers) { if (signer.isFieldPresent(sfTxnSignature)) + { signerCount += 1; + } else if (signer.isFieldPresent(sfSigners)) + { signerCount += signer.getFieldArray(sfSigners).size(); + } } } diff --git a/src/libxrpl/tx/transactors/system/Change.cpp b/src/libxrpl/tx/transactors/system/Change.cpp index d1e2d148d6..5b0a431004 100644 --- a/src/libxrpl/tx/transactors/system/Change.cpp +++ b/src/libxrpl/tx/transactors/system/Change.cpp @@ -222,9 +222,13 @@ Change::applyAmendment() } if (newMajorities.empty()) + { amendmentObject->makeFieldAbsent(sfMajorities); + } else + { amendmentObject->setFieldArray(sfMajorities, newMajorities); + } view().update(amendmentObject); diff --git a/src/libxrpl/tx/transactors/token/Clawback.cpp b/src/libxrpl/tx/transactors/token/Clawback.cpp index c64459faa9..a3ac810e90 100644 --- a/src/libxrpl/tx/transactors/token/Clawback.cpp +++ b/src/libxrpl/tx/transactors/token/Clawback.cpp @@ -168,9 +168,13 @@ Clawback::preclaim(PreclaimContext const& ctx) // Note the order of checks - when SAV is active, this check here will make // the one which follows `sleHolder->isFieldPresent(sfAMMID)` redundant. if (ctx.view.rules().enabled(featureSingleAssetVault) && isPseudoAccount(sleHolder)) + { return tecPSEUDO_ACCOUNT; - else if (sleHolder->isFieldPresent(sfAMMID)) + } + if (sleHolder->isFieldPresent(sfAMMID)) + { return tecAMM_ACCOUNT; + } return std::visit( [&](T const&) { diff --git a/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp b/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp index f9b9f9c01e..9f9362da4e 100644 --- a/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp +++ b/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp @@ -58,7 +58,7 @@ MPTokenIssuanceCreate::preflight(PreflightContext const& ctx) if (auto const metadata = ctx.tx[~sfMPTokenMetadata]) { - if (metadata->length() == 0 || metadata->length() > maxMPTokenMetadataLength) + if (metadata->empty() || metadata->length() > maxMPTokenMetadataLength) return temMALFORMED; } diff --git a/src/libxrpl/tx/transactors/token/MPTokenIssuanceSet.cpp b/src/libxrpl/tx/transactors/token/MPTokenIssuanceSet.cpp index 5676ebd6af..dc5827419b 100644 --- a/src/libxrpl/tx/transactors/token/MPTokenIssuanceSet.cpp +++ b/src/libxrpl/tx/transactors/token/MPTokenIssuanceSet.cpp @@ -158,9 +158,13 @@ MPTokenIssuanceSet::preclaim(PreclaimContext const& ctx) // For readability two separate `if` rather than `||` of two conditions if (!ctx.view.rules().enabled(featureSingleAssetVault) && !ctx.view.rules().enabled(featureDynamicMPT)) + { return tecNO_PERMISSION; - else if (ctx.tx.isFlag(tfMPTLock) || ctx.tx.isFlag(tfMPTUnlock)) + } + if (ctx.tx.isFlag(tfMPTLock) || ctx.tx.isFlag(tfMPTUnlock)) + { return tecNO_PERMISSION; + } } // ensure it is issued by the tx submitter @@ -240,9 +244,13 @@ MPTokenIssuanceSet::doApply() std::shared_ptr sle; if (holderID) + { sle = view().peek(keylet::mptoken(mptIssuanceID, *holderID)); + } else + { sle = view().peek(keylet::mptIssuance(mptIssuanceID)); + } if (!sle) return tecINTERNAL; // LCOV_EXCL_LINE @@ -251,18 +259,26 @@ MPTokenIssuanceSet::doApply() std::uint32_t flagsOut = flagsIn; if (txFlags & tfMPTLock) + { flagsOut |= lsfMPTLocked; + } else if (txFlags & tfMPTUnlock) + { flagsOut &= ~lsfMPTLocked; + } if (auto const mutableFlags = ctx_.tx[~sfMutableFlags].value_or(0)) { for (auto const& f : mptMutabilityFlags) { if (mutableFlags & f.setFlag) + { flagsOut |= f.canMutateFlag; + } else if (mutableFlags & f.clearFlag) + { flagsOut &= ~f.canMutateFlag; + } } if (mutableFlags & tmfMPTClearCanTransfer) @@ -283,17 +299,25 @@ MPTokenIssuanceSet::doApply() // - If the field is present, it must be non-zero. // Therefore, when TransferFee is 0, the field should be removed. if (transferFee == 0) + { sle->makeFieldAbsent(sfTransferFee); + } else + { sle->setFieldU16(sfTransferFee, *transferFee); + } } if (auto const metadata = ctx_.tx[~sfMPTokenMetadata]) { if (metadata->empty()) + { sle->makeFieldAbsent(sfMPTokenMetadata); + } else + { sle->setFieldVL(sfMPTokenMetadata, *metadata); + } } if (domainID) diff --git a/src/libxrpl/tx/transactors/token/SetTrust.cpp b/src/libxrpl/tx/transactors/token/SetTrust.cpp index 76e586d2d3..7140d5ef2a 100644 --- a/src/libxrpl/tx/transactors/token/SetTrust.cpp +++ b/src/libxrpl/tx/transactors/token/SetTrust.cpp @@ -214,7 +214,9 @@ SetTrust::preclaim(PreclaimContext const& ctx) // pass } else + { return tecNO_PERMISSION; + } } // In general, trust lines to pseudo accounts are not permitted, unless @@ -233,14 +235,20 @@ SetTrust::preclaim(PreclaimContext const& ctx) } else if (auto const ammSle = ctx.view.read({ltAMM, sleDst->getFieldH256(sfAMMID)})) { - if (auto const lpTokens = ammSle->getFieldAmount(sfLPTokenBalance); - lpTokens == beast::zero) + auto const lpTokens = ammSle->getFieldAmount(sfLPTokenBalance); + if (lpTokens == beast::zero) + { return tecAMM_EMPTY; - else if (lpTokens.getCurrency() != saLimitAmount.getCurrency()) + } + if (lpTokens.getCurrency() != saLimitAmount.getCurrency()) + { return tecNO_PERMISSION; + } } else + { return tecINTERNAL; // LCOV_EXCL_LINE + } } else if (sleDst->isFieldPresent(sfVaultID) || sleDst->isFieldPresent(sfLoanBrokerID)) { @@ -249,7 +257,9 @@ SetTrust::preclaim(PreclaimContext const& ctx) // else pass } else + { return tecPSEUDO_ACCOUNT; + } } // Checking all freeze/deep freeze flag invariants. @@ -473,11 +483,14 @@ SetTrust::doApply() if (bSetNoRipple && !bClearNoRipple) { if ((bHigh ? saHighBalance : saLowBalance) >= beast::zero) + { uFlagsOut |= (bHigh ? lsfHighNoRipple : lsfLowNoRipple); - + } else + { // Cannot set noRipple on a negative balance. return tecNO_PERMISSION; + } } else if (bClearNoRipple && !bSetNoRipple) { diff --git a/src/libxrpl/tx/transactors/vault/VaultClawback.cpp b/src/libxrpl/tx/transactors/vault/VaultClawback.cpp index bfce93b1dd..ed47dfb63d 100644 --- a/src/libxrpl/tx/transactors/vault/VaultClawback.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultClawback.cpp @@ -27,8 +27,10 @@ VaultClawback::preflight(PreflightContext const& ctx) { // Note, zero amount is valid, it means "all". It is also the default. if (*amount < beast::zero) + { return temBAD_AMOUNT; - else if (isXRP(amount->asset())) + } + if (isXRP(amount->asset())) { JLOG(ctx.j.debug()) << "VaultClawback: cannot clawback XRP."; return temMALFORMED; diff --git a/src/libxrpl/tx/transactors/vault/VaultCreate.cpp b/src/libxrpl/tx/transactors/vault/VaultCreate.cpp index 4e9faeb56c..a5b039f06b 100644 --- a/src/libxrpl/tx/transactors/vault/VaultCreate.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultCreate.cpp @@ -50,9 +50,13 @@ VaultCreate::preflight(PreflightContext const& ctx) if (auto const domain = ctx.tx[~sfDomainID]) { if (*domain == beast::zero) + { return temMALFORMED; - else if ((ctx.tx.getFlags() & tfVaultPrivate) == 0) + } + if ((ctx.tx.getFlags() & tfVaultPrivate) == 0) + { return temMALFORMED; // DomainID only allowed on private vaults + } } if (auto const assetMax = ctx.tx[~sfAssetsMaximum]) @@ -63,7 +67,7 @@ VaultCreate::preflight(PreflightContext const& ctx) if (auto const metadata = ctx.tx[~sfMPTokenMetadata]) { - if (metadata->length() == 0 || metadata->length() > maxMPTokenMetadataLength) + if (metadata->empty() || metadata->length() > maxMPTokenMetadataLength) return temMALFORMED; } @@ -197,9 +201,13 @@ VaultCreate::doApply() vault->at(sfData) = *value; // Required field, default to vaultStrategyFirstComeFirstServe if (auto value = tx[~sfWithdrawalPolicy]) + { vault->at(sfWithdrawalPolicy) = *value; + } else + { vault->at(sfWithdrawalPolicy) = vaultStrategyFirstComeFirstServe; + } if (scale) vault->at(sfScale) = scale; view().insert(vault); diff --git a/src/libxrpl/tx/transactors/vault/VaultDeposit.cpp b/src/libxrpl/tx/transactors/vault/VaultDeposit.cpp index fe3d8d313a..66f4fb09b8 100644 --- a/src/libxrpl/tx/transactors/vault/VaultDeposit.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultDeposit.cpp @@ -101,7 +101,9 @@ VaultDeposit::preclaim(PreclaimContext const& ctx) return err; } else + { return tecNO_AUTH; + } } // Source MPToken must exist (if asset is an MPT) @@ -196,8 +198,10 @@ VaultDeposit::doApply() auto const maybeAssets = sharesToAssetsDeposit(vault, sleIssuance, sharesCreated); if (!maybeAssets) + { return tecINTERNAL; // LCOV_EXCL_LINE - else if (*maybeAssets > amount) + } + if (*maybeAssets > amount) { // LCOV_EXCL_START JLOG(j_.error()) << "VaultDeposit: would take more than offered."; diff --git a/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp b/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp index 725c54a3fd..a473ac7c36 100644 --- a/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp @@ -144,7 +144,9 @@ VaultWithdraw::doApply() assetsWithdrawn = *maybeAssets; } else + { return tefINTERNAL; // LCOV_EXCL_LINE + } } catch (std::overflow_error const&) { diff --git a/src/test/app/AMMCalc_test.cpp b/src/test/app/AMMCalc_test.cpp index 690329d2f3..c1068b08ba 100644 --- a/src/test/app/AMMCalc_test.cpp +++ b/src/test/app/AMMCalc_test.cpp @@ -43,10 +43,14 @@ class AMMCalc_test : public beast::unit_test::suite if (delimited) *delimited = (match[3] != ""); if (match[1] == "XRP") + { return XRP(std::stoll(match[2])); - // drops - else if (match[1] == "XRPA") + // drops + } + if (match[1] == "XRPA") + { return XRPAmount{std::stoll(match[2])}; + } return amountFromString(gw[match[1]].asset(), match[2]); } return std::nullopt; @@ -120,7 +124,9 @@ class AMMCalc_test : public beast::unit_test::suite break; } else + { return std::nullopt; + } } return rates; } @@ -398,13 +404,17 @@ class AMMCalc_test : public beast::unit_test::suite env.current()->rules(), beast::Journal(beast::Journal::getNullSink())); ammOffer) + { std::cout << "amm offer: " << toString(ammOffer->in) << " " << toString(ammOffer->out) << "\nnew pool: " << toString(pool->first.in + ammOffer->in) << " " << toString(pool->first.out - ammOffer->out) << std::endl; + } else + { std::cout << "can't change the pool's SP quality" << std::endl; + } return true; } } diff --git a/src/test/app/AMMClawback_test.cpp b/src/test/app/AMMClawback_test.cpp index 3034c628f4..9033fe2bdd 100644 --- a/src/test/app/AMMClawback_test.cpp +++ b/src/test/app/AMMClawback_test.cpp @@ -531,11 +531,15 @@ class AMMClawback_test : public beast::unit_test::suite env.close(); if (!features[fixAMMv1_3]) + { BEAST_EXPECT( amm.expectBalances(USD(4000), EUR(5000), IOUAmount{4472135954999580, -12})); + } else + { BEAST_EXPECT( amm.expectBalances(USD(4000), EUR(5000), IOUAmount{4472135954999579, -12})); + } // gw clawback 1000 USD from the AMM pool env(amm::ammClawback(gw, alice, USD, EUR, USD(1000)), ter(tesSUCCESS)); @@ -554,17 +558,25 @@ class AMMClawback_test : public beast::unit_test::suite // 1000 USD and 1250 EUR was withdrawn from the AMM pool, so the // current balance is 3000 USD and 3750 EUR. if (!features[fixAMMv1_3]) + { BEAST_EXPECT( amm.expectBalances(USD(3000), EUR(3750), IOUAmount{3354101966249685, -12})); + } else + { BEAST_EXPECT( amm.expectBalances(USD(3000), EUR(3750), IOUAmount{3354101966249684, -12})); + } // Alice has 3/4 of its initial lptokens Left. if (!features[fixAMMv1_3]) + { BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{3354101966249685, -12})); + } else + { BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{3354101966249684, -12})); + } // gw clawback another 500 USD from the AMM pool. env(amm::ammClawback(gw, alice, USD, EUR, USD(500)), ter(tesSUCCESS)); @@ -575,19 +587,27 @@ class AMMClawback_test : public beast::unit_test::suite env.require(balance(alice, USD(2000))); if (!features[fixAMMv1_3]) + { BEAST_EXPECT(amm.expectBalances( STAmount{USD, UINT64_C(2500000000000001), -12}, STAmount{EUR, UINT64_C(3125000000000001), -12}, IOUAmount{2795084971874738, -12})); + } else + { BEAST_EXPECT( amm.expectBalances(USD(2500), EUR(3125), IOUAmount{2795084971874737, -12})); + } if (!features[fixAMMv1_3]) + { BEAST_EXPECT( env.balance(alice, EUR) == STAmount(EUR, UINT64_C(2874999999999999), -12)); + } else + { BEAST_EXPECT(env.balance(alice, EUR) == EUR(2875)); + } // gw clawback small amount, 1 USD. env(amm::ammClawback(gw, alice, USD, EUR, USD(1)), ter(tesSUCCESS)); @@ -597,27 +617,39 @@ class AMMClawback_test : public beast::unit_test::suite env.require(balance(alice, USD(2000))); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) + { BEAST_EXPECT(amm.expectBalances( STAmount{USD, UINT64_C(2499000000000002), -12}, STAmount{EUR, UINT64_C(3123750000000002), -12}, IOUAmount{2793966937885989, -12})); + } else if (!features[fixAMMClawbackRounding]) + { BEAST_EXPECT( amm.expectBalances(USD(2499), EUR(3123.75), IOUAmount{2793966937885987, -12})); + } else if (features[fixAMMClawbackRounding] && features[fixAMMv1_3]) + { BEAST_EXPECT(amm.expectBalances( STAmount{USD, UINT64_C(2499000000000001), -12}, STAmount{EUR, UINT64_C(3123750000000001), -12}, IOUAmount{2793966937885988, -12})); + } if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) + { BEAST_EXPECT( env.balance(alice, EUR) == STAmount(EUR, UINT64_C(2876'249999999998), -12)); + } else if (!features[fixAMMClawbackRounding]) + { BEAST_EXPECT(env.balance(alice, EUR) == EUR(2876.25)); + } else if (features[fixAMMClawbackRounding] && features[fixAMMv1_3]) + { BEAST_EXPECT( env.balance(alice, EUR) == STAmount(EUR, UINT64_C(2876'249999999999), -12)); + } // gw clawback 4000 USD, exceeding the current balance. We // will clawback all. @@ -685,27 +717,39 @@ class AMMClawback_test : public beast::unit_test::suite // gw2 creates AMM pool of XRP/EUR, alice and bob deposit XRP/EUR. AMM amm2(env, gw2, XRP(3000), EUR(1000), ter(tesSUCCESS)); if (!features[fixAMMv1_3]) + { BEAST_EXPECT( amm2.expectBalances(EUR(1000), XRP(3000), IOUAmount{1732050807568878, -9})); + } else + { BEAST_EXPECT( amm2.expectBalances(EUR(1000), XRP(3000), IOUAmount{1732050807568877, -9})); + } amm2.deposit(alice, EUR(1000), XRP(3000)); if (!features[fixAMMv1_3]) + { BEAST_EXPECT( amm2.expectBalances(EUR(2000), XRP(6000), IOUAmount{3464101615137756, -9})); + } else + { BEAST_EXPECT( amm2.expectBalances(EUR(2000), XRP(6000), IOUAmount{3464101615137754, -9})); + } amm2.deposit(bob, EUR(1000), XRP(3000)); if (!features[fixAMMv1_3]) + { BEAST_EXPECT( amm2.expectBalances(EUR(3000), XRP(9000), IOUAmount{5196152422706634, -9})); + } else + { BEAST_EXPECT( amm2.expectBalances(EUR(3000), XRP(9000), IOUAmount{5196152422706631, -9})); + } env.close(); auto aliceXrpBalance = env.balance(alice, XRP); @@ -725,28 +769,44 @@ class AMMClawback_test : public beast::unit_test::suite // Alice gets 1000 XRP back. if (features[fixAMMClawbackRounding] && features[fixAMMv1_3]) + { BEAST_EXPECT( expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(1000) - XRPAmount(1))); + } else + { BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(1000))); + } aliceXrpBalance = env.balance(alice, XRP); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) + { BEAST_EXPECT( amm.expectBalances(USD(2500), XRP(5000), IOUAmount{3535533905932738, -9})); + } else if (!features[fixAMMClawbackRounding]) + { BEAST_EXPECT( amm.expectBalances(USD(2500), XRP(5000), IOUAmount{3535533905932737, -9})); + } else if (features[fixAMMClawbackRounding] && features[fixAMMv1_3]) + { BEAST_EXPECT(amm.expectBalances( USD(2500), XRPAmount(5000000001), IOUAmount{3'535'533'905932738, -9})); + } if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) + { BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{7071067811865480, -10})); + } else if (!features[fixAMMClawbackRounding]) + { BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{7071067811865474, -10})); + } else if (features[fixAMMClawbackRounding] && features[fixAMMv1_3]) + { BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{707106781186548, -9})); + } BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{1414213562373095, -9})); @@ -762,32 +822,50 @@ class AMMClawback_test : public beast::unit_test::suite bobXrpBalance = env.balance(bob, XRP); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) + { BEAST_EXPECT(amm.expectBalances( STAmount{USD, UINT64_C(2490000000000001), -12}, XRP(4980), IOUAmount{3521391770309008, -9})); + } else if (!features[fixAMMClawbackRounding]) + { BEAST_EXPECT( amm.expectBalances(USD(2'490), XRP(4980), IOUAmount{3521391770309006, -9})); + } else if (features[fixAMMClawbackRounding] && features[fixAMMv1_3]) + { BEAST_EXPECT(amm.expectBalances( STAmount{USD, UINT64_C(2490000000000001), -12}, XRPAmount(4980000001), IOUAmount{3521391'770309008, -9})); + } if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) + { BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{7071067811865480, -10})); + } else if (!features[fixAMMClawbackRounding]) + { BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{7071067811865474, -10})); + } else if (features[fixAMMClawbackRounding] && features[fixAMMv1_3]) + { BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{707106781186548, -9})); + } if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) + { BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{1400071426749365, -9})); + } else if (!features[fixAMMClawbackRounding]) + { BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{1400071426749364, -9})); + } else if (features[fixAMMClawbackRounding] && features[fixAMMv1_3]) + { BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{1400071426749365, -9})); + } // gw2 clawback 200 EUR from amm2. env(amm::ammClawback(gw2, alice, EUR, XRP, EUR(200)), ter(tesSUCCESS)); @@ -797,32 +875,52 @@ class AMMClawback_test : public beast::unit_test::suite env.require(balance(bob, EUR(3000))); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) + { BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(600))); + } else if (!features[fixAMMClawbackRounding]) + { BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(600))); + } else if (features[fixAMMClawbackRounding] && features[fixAMMv1_3]) + { BEAST_EXPECT( expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(600) - XRPAmount{1})); + } aliceXrpBalance = env.balance(alice, XRP); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) + { BEAST_EXPECT( amm2.expectBalances(EUR(2800), XRP(8400), IOUAmount{4849742261192859, -9})); + } else if (!features[fixAMMClawbackRounding]) + { BEAST_EXPECT( amm2.expectBalances(EUR(2800), XRP(8400), IOUAmount{4849742261192856, -9})); + } else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) + { BEAST_EXPECT(amm2.expectBalances( EUR(2800), XRPAmount(8400000001), IOUAmount{4849742261192856, -9})); + } if (!features[fixAMMv1_3]) + { BEAST_EXPECT(amm2.expectLPTokens(alice, IOUAmount{1385640646055103, -9})); + } else + { BEAST_EXPECT(amm2.expectLPTokens(alice, IOUAmount{1385640646055102, -9})); + } if (!features[fixAMMv1_3]) + { BEAST_EXPECT(amm2.expectLPTokens(bob, IOUAmount{1732050807568878, -9})); + } else + { BEAST_EXPECT(amm2.expectLPTokens(bob, IOUAmount{1732050807568877, -9})); + } // gw claw back 1000 USD from alice in amm, which exceeds alice's // balance. This will clawback all the remaining LP tokens of alice @@ -835,35 +933,53 @@ class AMMClawback_test : public beast::unit_test::suite // Alice gets 1000 XRP back. if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) + { BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(1000))); + } else if (!features[fixAMMClawbackRounding]) + { BEAST_EXPECT( expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(1000) - XRPAmount{1})); + } else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) + { BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(1000))); + } aliceXrpBalance = env.balance(alice, XRP); BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount(0))); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) + { BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{1400071426749365, -9})); + } else if (!features[fixAMMClawbackRounding]) + { BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{1400071426749364, -9})); + } else if (features[fixAMMClawbackRounding] && features[fixAMMv1_3]) + { BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{1400071426749365, -9})); + } if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) + { BEAST_EXPECT(amm.expectBalances( STAmount{USD, UINT64_C(1990000000000001), -12}, XRP(3980), IOUAmount{2814284989122460, -9})); + } else if (!features[fixAMMClawbackRounding]) + { BEAST_EXPECT(amm.expectBalances( USD(1'990), XRPAmount{3'980'000'001}, IOUAmount{2814284989122459, -9})); + } else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) + { BEAST_EXPECT(amm.expectBalances( STAmount{USD, UINT64_C(1990000000000001), -12}, XRPAmount{3'980'000'001}, IOUAmount{2814284989122460, -9})); + } // gw clawback 1000 USD from bob in amm, which also exceeds bob's // balance in amm. All bob's lptoken in amm will be consumed, which @@ -903,14 +1019,20 @@ class AMMClawback_test : public beast::unit_test::suite BEAST_EXPECT(amm2.expectLPTokens(alice, IOUAmount(0))); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) + { BEAST_EXPECT( amm2.expectBalances(EUR(2000), XRP(6000), IOUAmount{3464101615137756, -9})); + } else if (!features[fixAMMClawbackRounding]) + { BEAST_EXPECT( amm2.expectBalances(EUR(2000), XRP(6000), IOUAmount{3464101615137754, -9})); + } else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) + { BEAST_EXPECT(amm2.expectBalances( EUR(2000), XRPAmount(6000000001), IOUAmount{3464101615137754, -9})); + } // gw2 claw back 2000 EUR from bob in amm2, which exceeds bob's // balance. All bob's lptokens will be consumed, which corresponds @@ -933,14 +1055,20 @@ class AMMClawback_test : public beast::unit_test::suite BEAST_EXPECT(amm2.expectLPTokens(bob, IOUAmount(0))); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) + { BEAST_EXPECT( amm2.expectBalances(EUR(1000), XRP(3000), IOUAmount{1732050807568878, -9})); + } else if (!features[fixAMMClawbackRounding]) + { BEAST_EXPECT( amm2.expectBalances(EUR(1000), XRP(3000), IOUAmount{1732050807568877, -9})); + } else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) + { BEAST_EXPECT(amm2.expectBalances( EUR(1000), XRPAmount(3000000001), IOUAmount{1732050807568877, -9})); + } } } @@ -999,38 +1127,62 @@ class AMMClawback_test : public beast::unit_test::suite env.close(); if (!features[fixAMMv1_3]) + { BEAST_EXPECT( amm.expectBalances(USD(4000), EUR(5000), IOUAmount{4472135954999580, -12})); + } else + { BEAST_EXPECT( amm.expectBalances(USD(4000), EUR(5000), IOUAmount{4472135954999579, -12})); + } amm.deposit(bob, USD(2000), EUR(2500)); if (!features[fixAMMv1_3]) + { BEAST_EXPECT( amm.expectBalances(USD(6000), EUR(7500), IOUAmount{6708203932499370, -12})); + } else + { BEAST_EXPECT( amm.expectBalances(USD(6000), EUR(7500), IOUAmount{6708203932499368, -12})); + } amm.deposit(carol, USD(1000), EUR(1250)); if (!features[fixAMMv1_3]) + { BEAST_EXPECT( amm.expectBalances(USD(7000), EUR(8750), IOUAmount{7826237921249265, -12})); + } else + { BEAST_EXPECT( amm.expectBalances(USD(7000), EUR(8750), IOUAmount{7826237921249262, -12})); + } if (!features[fixAMMv1_3]) + { BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{4472135954999580, -12})); + } else + { BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{4472135954999579, -12})); + } if (!features[fixAMMv1_3]) + { BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{2236067977499790, -12})); + } else + { BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{2236067977499789, -12})); + } if (!features[fixAMMv1_3]) + { BEAST_EXPECT(amm.expectLPTokens(carol, IOUAmount{1118033988749895, -12})); + } else + { BEAST_EXPECT(amm.expectLPTokens(carol, IOUAmount{1118033988749894, -12})); + } env.require(balance(alice, USD(2000))); env.require(balance(alice, EUR(1000))); @@ -1044,25 +1196,37 @@ class AMMClawback_test : public beast::unit_test::suite env.close(); if (!features[fixAMMv1_3]) + { BEAST_EXPECT(amm.expectBalances( STAmount{USD, UINT64_C(4999999999999999), -12}, STAmount{EUR, UINT64_C(6249999999999999), -12}, IOUAmount{5590169943749475, -12})); + } else + { BEAST_EXPECT(amm.expectBalances( STAmount{USD, UINT64_C(5000000000000001), -12}, STAmount{EUR, UINT64_C(6250000000000001), -12}, IOUAmount{5590169943749473, -12})); + } if (!features[fixAMMv1_3]) + { BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{4472135954999580, -12})); + } else + { BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{4472135954999579, -12})); + } BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount(0))); if (!features[fixAMMv1_3]) + { BEAST_EXPECT(amm.expectLPTokens(carol, IOUAmount{1118033988749895, -12})); + } else + { BEAST_EXPECT(amm.expectLPTokens(carol, IOUAmount{1118033988749894, -12})); + } // Bob will get 2500 EUR back. env.require(balance(alice, USD(2000))); @@ -1070,11 +1234,15 @@ class AMMClawback_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(bob, USD) == STAmount(USD, UINT64_C(3000000000000000), -12)); if (!features[fixAMMv1_3]) + { BEAST_EXPECT( env.balance(bob, EUR) == STAmount(EUR, UINT64_C(5000000000000001), -12)); + } else + { BEAST_EXPECT( env.balance(bob, EUR) == STAmount(EUR, UINT64_C(4999999999999999), -12)); + } env.require(balance(carol, USD(3000))); env.require(balance(carol, EUR(2750))); @@ -1082,20 +1250,28 @@ class AMMClawback_test : public beast::unit_test::suite env(amm::ammClawback(gw2, carol, EUR, USD, std::nullopt), ter(tesSUCCESS)); env.close(); if (!features[fixAMMv1_3]) + { BEAST_EXPECT(amm.expectBalances( STAmount{USD, UINT64_C(3999999999999999), -12}, STAmount{EUR, UINT64_C(4999999999999999), -12}, IOUAmount{4472135954999580, -12})); + } else + { BEAST_EXPECT(amm.expectBalances( STAmount{USD, UINT64_C(4000000000000001), -12}, STAmount{EUR, UINT64_C(5000000000000002), -12}, IOUAmount{4472135954999579, -12})); + } if (!features[fixAMMv1_3]) + { BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{4472135954999580, -12})); + } else + { BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{4472135954999579, -12})); + } BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount(0))); BEAST_EXPECT(amm.expectLPTokens(carol, IOUAmount(0))); @@ -1134,25 +1310,37 @@ class AMMClawback_test : public beast::unit_test::suite // gw creates AMM pool of XRP/USD, alice and bob deposit XRP/USD. AMM amm(env, gw, XRP(2000), USD(10000), ter(tesSUCCESS)); if (!features[fixAMMv1_3]) + { BEAST_EXPECT( amm.expectBalances(USD(10000), XRP(2000), IOUAmount{4472135954999580, -9})); + } else + { BEAST_EXPECT( amm.expectBalances(USD(10000), XRP(2000), IOUAmount{4472135954999579, -9})); + } amm.deposit(alice, USD(1000), XRP(200)); if (!features[fixAMMv1_3]) + { BEAST_EXPECT( amm.expectBalances(USD(11000), XRP(2200), IOUAmount{4919349550499538, -9})); + } else + { BEAST_EXPECT( amm.expectBalances(USD(11000), XRP(2200), IOUAmount{4919349550499536, -9})); + } amm.deposit(bob, USD(2000), XRP(400)); if (!features[fixAMMv1_3]) + { BEAST_EXPECT( amm.expectBalances(USD(13000), XRP(2600), IOUAmount{5813776741499453, -9})); + } else + { BEAST_EXPECT( amm.expectBalances(USD(13000), XRP(2600), IOUAmount{5813776741499451, -9})); + } env.close(); auto aliceXrpBalance = env.balance(alice, XRP); @@ -1162,27 +1350,39 @@ class AMMClawback_test : public beast::unit_test::suite env(amm::ammClawback(gw, alice, USD, XRP, std::nullopt), ter(tesSUCCESS)); env.close(); if (!features[fixAMMv1_3]) + { BEAST_EXPECT( amm.expectBalances(USD(12000), XRP(2400), IOUAmount{5366563145999495, -9})); + } else + { BEAST_EXPECT(amm.expectBalances( USD(12000), XRPAmount(2400000001), IOUAmount{5366563145999494, -9})); + } if (!features[fixAMMv1_3]) + { BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(200))); + } else + { BEAST_EXPECT( expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(200) - XRPAmount{1})); + } BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount(0))); // gw clawback all bob's USD in amm. (2000 USD / 400 XRP) env(amm::ammClawback(gw, bob, USD, XRP, std::nullopt), ter(tesSUCCESS)); env.close(); if (!features[fixAMMv1_3]) + { BEAST_EXPECT( amm.expectBalances(USD(10000), XRP(2000), IOUAmount{4472135954999580, -9})); + } else + { BEAST_EXPECT(amm.expectBalances( USD(10000), XRPAmount(2000000001), IOUAmount{4472135954999579, -9})); + } BEAST_EXPECT(expectLedgerEntryRoot(env, bob, bobXrpBalance + XRP(400))); BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount(0))); BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount(0))); @@ -1237,9 +1437,13 @@ class AMMClawback_test : public beast::unit_test::suite amm.deposit(bob, USD(4000), EUR(1000)); BEAST_EXPECT(amm.expectBalances(USD(12000), EUR(3000), IOUAmount(6000))); if (!features[fixAMMv1_3]) + { amm.deposit(carol, USD(2000), EUR(500)); + } else + { amm.deposit(carol, USD(2000.25), EUR(500)); + } BEAST_EXPECT(amm.expectBalances(USD(14000), EUR(3500), IOUAmount(7000))); // gw clawback 1000 USD from carol. env(amm::ammClawback(gw, carol, USD, EUR, USD(1000)), ter(tesSUCCESS)); @@ -1254,10 +1458,14 @@ class AMMClawback_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(bob, USD) == USD(5000)); BEAST_EXPECT(env.balance(bob, EUR) == EUR(8000)); if (!features[fixAMMv1_3]) + { BEAST_EXPECT(env.balance(carol, USD) == USD(6000)); + } else + { BEAST_EXPECT( env.balance(carol, USD) == STAmount(USD, UINT64_C(5999'999999999999), -12)); + } // 250 EUR goes back to carol. BEAST_EXPECT(env.balance(carol, EUR) == EUR(7750)); @@ -1279,10 +1487,14 @@ class AMMClawback_test : public beast::unit_test::suite // 250 EUR did not go back to bob because tfClawTwoAssets is set. BEAST_EXPECT(env.balance(bob, EUR) == EUR(8000)); if (!features[fixAMMv1_3]) + { BEAST_EXPECT(env.balance(carol, USD) == USD(6000)); + } else + { BEAST_EXPECT( env.balance(carol, USD) == STAmount(USD, UINT64_C(5999'999999999999), -12)); + } BEAST_EXPECT(env.balance(carol, EUR) == EUR(7750)); // gw clawback all USD from alice and set tfClawTwoAssets. @@ -1300,10 +1512,14 @@ class AMMClawback_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(bob, USD) == USD(5000)); BEAST_EXPECT(env.balance(bob, EUR) == EUR(8000)); if (!features[fixAMMv1_3]) + { BEAST_EXPECT(env.balance(carol, USD) == USD(6000)); + } else + { BEAST_EXPECT( env.balance(carol, USD) == STAmount(USD, UINT64_C(5999'999999999999), -12)); + } BEAST_EXPECT(env.balance(carol, EUR) == EUR(7750)); } @@ -1460,17 +1676,25 @@ class AMMClawback_test : public beast::unit_test::suite env(amm::ammClawback(gw, gw2, USD, EUR, USD(1000)), ter(tesSUCCESS)); env.close(); if (!features[fixAMMv1_3] || !features[fixAMMClawbackRounding]) + { BEAST_EXPECT( amm.expectBalances(USD(5000), EUR(10000), IOUAmount{7071067811865475, -12})); + } else + { BEAST_EXPECT( amm.expectBalances(USD(5000), EUR(10000), IOUAmount{7071067811865474, -12})); + } BEAST_EXPECT(amm.expectLPTokens(gw, IOUAmount{1414213562373095, -12})); if (!features[fixAMMv1_3] || !features[fixAMMClawbackRounding]) + { BEAST_EXPECT(amm.expectLPTokens(gw2, IOUAmount{1414213562373095, -12})); + } else + { BEAST_EXPECT(amm.expectLPTokens(gw2, IOUAmount{1414213562373094, -12})); + } BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{4242640687119285, -12})); BEAST_EXPECT(env.balance(alice, USD) == USD(2000)); @@ -1482,30 +1706,46 @@ class AMMClawback_test : public beast::unit_test::suite env(amm::ammClawback(gw2, gw, EUR, USD, EUR(1000)), ter(tesSUCCESS)); env.close(); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) + { BEAST_EXPECT(amm.expectBalances( USD(4500), STAmount(EUR, UINT64_C(9000000000000001), -12), IOUAmount{6363961030678928, -12})); + } else if (!features[fixAMMClawbackRounding]) + { BEAST_EXPECT( amm.expectBalances(USD(4500), EUR(9000), IOUAmount{6363961030678928, -12})); + } else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) + { BEAST_EXPECT(amm.expectBalances( USD(4500), STAmount(EUR, UINT64_C(9000000000000001), -12), IOUAmount{6363961030678927, -12})); + } if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) + { BEAST_EXPECT(amm.expectLPTokens(gw, IOUAmount{7071067811865480, -13})); + } else if (!features[fixAMMClawbackRounding]) + { BEAST_EXPECT(amm.expectLPTokens(gw, IOUAmount{7071067811865475, -13})); + } else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) + { BEAST_EXPECT(amm.expectLPTokens(gw, IOUAmount{7071067811865480, -13})); + } if (!features[fixAMMv1_3] || !features[fixAMMClawbackRounding]) + { BEAST_EXPECT(amm.expectLPTokens(gw2, IOUAmount{1414213562373095, -12})); + } else + { BEAST_EXPECT(amm.expectLPTokens(gw2, IOUAmount{1414213562373094, -12})); + } BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{4242640687119285, -12})); @@ -1518,30 +1758,46 @@ class AMMClawback_test : public beast::unit_test::suite env(amm::ammClawback(gw2, alice, EUR, USD, EUR(4000)), ter(tesSUCCESS)); env.close(); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) + { BEAST_EXPECT(amm.expectBalances( USD(2500), STAmount(EUR, UINT64_C(5000000000000001), -12), IOUAmount{3535533905932738, -12})); + } else if (!features[fixAMMClawbackRounding]) + { BEAST_EXPECT( amm.expectBalances(USD(2500), EUR(5000), IOUAmount{3535533905932738, -12})); + } else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) + { BEAST_EXPECT(amm.expectBalances( USD(2500), STAmount(EUR, UINT64_C(5000000000000001), -12), IOUAmount{3535533905932737, -12})); + } if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) + { BEAST_EXPECT(amm.expectLPTokens(gw, IOUAmount{7071067811865480, -13})); + } else if (!features[fixAMMClawbackRounding]) + { BEAST_EXPECT(amm.expectLPTokens(gw, IOUAmount{7071067811865475, -13})); + } else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) + { BEAST_EXPECT(amm.expectLPTokens(gw, IOUAmount{7071067811865480, -13})); + } if (!features[fixAMMv1_3] || !features[fixAMMClawbackRounding]) + { BEAST_EXPECT(amm.expectLPTokens(gw2, IOUAmount{1414213562373095, -12})); + } else + { BEAST_EXPECT(amm.expectLPTokens(gw2, IOUAmount{1414213562373094, -12})); + } BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{1414213562373095, -12})); BEAST_EXPECT(env.balance(alice, USD) == USD(4000)); @@ -1791,9 +2047,13 @@ class AMMClawback_test : public beast::unit_test::suite amm.deposit(bob, USD(4000), EUR(1000)); BEAST_EXPECT(amm.expectBalances(USD(12000), EUR(3000), IOUAmount(6000))); if (!features[fixAMMv1_3]) + { amm.deposit(carol, USD(2000), EUR(500)); + } else + { amm.deposit(carol, USD(2000.25), EUR(500)); + } BEAST_EXPECT(amm.expectBalances(USD(14000), EUR(3500), IOUAmount(7000))); // global freeze @@ -1813,10 +2073,14 @@ class AMMClawback_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(bob, USD) == USD(5000)); BEAST_EXPECT(env.balance(bob, EUR) == EUR(8000)); if (!features[fixAMMv1_3]) + { BEAST_EXPECT(env.balance(carol, USD) == USD(6000)); + } else + { BEAST_EXPECT( env.balance(carol, USD) == STAmount(USD, UINT64_C(5999'999999999999), -12)); + } // 250 EUR goes back to carol. BEAST_EXPECT(env.balance(carol, EUR) == EUR(7750)); @@ -1838,10 +2102,14 @@ class AMMClawback_test : public beast::unit_test::suite // 250 EUR did not go back to bob because tfClawTwoAssets is set. BEAST_EXPECT(env.balance(bob, EUR) == EUR(8000)); if (!features[fixAMMv1_3]) + { BEAST_EXPECT(env.balance(carol, USD) == USD(6000)); + } else + { BEAST_EXPECT( env.balance(carol, USD) == STAmount(USD, UINT64_C(5999'999999999999), -12)); + } BEAST_EXPECT(env.balance(carol, EUR) == EUR(7750)); // gw clawback all USD from alice and set tfClawTwoAssets. @@ -1859,10 +2127,14 @@ class AMMClawback_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(bob, USD) == USD(5000)); BEAST_EXPECT(env.balance(bob, EUR) == EUR(8000)); if (!features[fixAMMv1_3]) + { BEAST_EXPECT(env.balance(carol, USD) == USD(6000)); + } else + { BEAST_EXPECT( env.balance(carol, USD) == STAmount(USD, UINT64_C(5999'999999999999), -12)); + } BEAST_EXPECT(env.balance(carol, EUR) == EUR(7750)); } } @@ -1911,16 +2183,24 @@ class AMMClawback_test : public beast::unit_test::suite env.close(); if (!features[fixAMMv1_3]) + { BEAST_EXPECT(amm.expectBalances( STAmount(USD, UINT64_C(5656854249492380), -13), XRP(70.710678), IOUAmount(200000))); + } else + { BEAST_EXPECT(amm.expectBalances( STAmount(USD, UINT64_C(565'685424949238), -12), XRP(70.710679), IOUAmount(200000))); + } BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount(0))); if (!features[fixAMMv1_3]) + { BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(29.289322))); + } else + { BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(29.289321))); + } } void diff --git a/src/test/app/AMMExtended_test.cpp b/src/test/app/AMMExtended_test.cpp index 14be260822..93ad92af3d 100644 --- a/src/test/app/AMMExtended_test.cpp +++ b/src/test/app/AMMExtended_test.cpp @@ -1971,8 +1971,10 @@ private: return false; Sandbox sb(&view, tapNONE); for (auto const& o : flowResult.removableOffers) + { if (auto ok = sb.peek(keylet::offer(o))) offerDelete(sb, ok, flowJournal); + } sb.apply(view); return true; }); @@ -2633,9 +2635,13 @@ private: // offer, removes 999 more as unfunded, then hits the step limit. env(offer(alice, USD(1'000), XRP(1'000))); if (!features[fixAMMv1_1]) + { env.require(balance(alice, STAmount{USD, UINT64_C(2'050126257867561), -15})); + } else + { env.require(balance(alice, STAmount{USD, UINT64_C(2'050125257867587), -15})); + } env.require(owners(alice, 2)); env.require(balance(bob, USD(0))); env.require(owners(bob, 1'001)); diff --git a/src/test/app/AMM_test.cpp b/src/test/app/AMM_test.cpp index 44ec1f039e..152a97fece 100644 --- a/src/test/app/AMM_test.cpp +++ b/src/test/app/AMM_test.cpp @@ -739,16 +739,20 @@ private: [&](AMM& ammAlice, Env& env) { env(fset(gw, asfGlobalFreeze)); if (!features[featureAMMClawback]) + { // If the issuer set global freeze, the holder still can // deposit the other non-frozen token when AMMClawback is // not enabled. ammAlice.deposit(carol, XRP(100)); + } else + { // If the issuer set global freeze, the holder cannot // deposit the other non-frozen token when AMMClawback is // enabled. ammAlice.deposit( carol, XRP(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); + } ammAlice.deposit( carol, USD(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); ammAlice.deposit(carol, 1'000'000, std::nullopt, std::nullopt, ter(tecFROZEN)); @@ -766,14 +770,18 @@ private: env(trust(gw, carol["USD"](0), tfSetFreeze)); env.close(); if (!features[featureAMMClawback]) + { // Can deposit non-frozen token if AMMClawback is not // enabled ammAlice.deposit(carol, XRP(100)); + } else + { // Cannot deposit non-frozen token if the other token is // frozen when AMMClawback is enabled ammAlice.deposit( carol, XRP(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); + } ammAlice.deposit(carol, 1'000'000, std::nullopt, std::nullopt, ter(tecFROZEN)); ammAlice.deposit( @@ -837,14 +845,18 @@ private: env.close(); if (features[featureAMMClawback]) + { // if featureAMMClawback is enabled, bob can not deposit XRP // because he's not authorized to hold the paired token // gw["USD"]. amm.deposit( bob, XRP(10), std::nullopt, std::nullopt, std::nullopt, ter(tecNO_AUTH)); + } else + { amm.deposit( bob, XRP(10), std::nullopt, std::nullopt, std::nullopt, ter(tesSUCCESS)); + } } // Insufficient XRP balance @@ -1687,8 +1699,10 @@ private: ammAlice.withdraw( alice, IOUAmount{9'999'999'9999, -4}, std::nullopt, std::nullopt, err); if (env.enabled(fixAMMv1_3)) + { BEAST_EXPECT(ammAlice.expectBalances( XRPAmount(1), STAmount{USD, 1, -7}, IOUAmount{1, -4})); + } }, std::nullopt, 0, @@ -1707,8 +1721,10 @@ private: ammAlice.withdraw( alice, IOUAmount{9'999'999'999999999, -9}, std::nullopt, std::nullopt, err); if (env.enabled(fixAMMv1_3)) + { BEAST_EXPECT(ammAlice.expectBalances( XRPAmount(1), STAmount{USD, 1, -11}, IOUAmount{1, -8})); + } }, std::nullopt, 0, @@ -1932,11 +1948,15 @@ private: [&](AMM& ammAlice, Env& env) { ammAlice.withdraw(alice, XRP(1'000)); if (!env.enabled(fixAMMv1_3)) + { BEAST_EXPECT(ammAlice.expectBalances( XRP(9'000), USD(10'000), IOUAmount{9'486'832'98050514, -8})); + } else + { BEAST_EXPECT(ammAlice.expectBalances( XRPAmount{9'000'000'001}, USD(10'000), IOUAmount{9'486'832'98050514, -8})); + } }, std::nullopt, 0, @@ -2000,11 +2020,15 @@ private: lpTokens = ammAlice.deposit(carol, XRPAmount(1)); ammAlice.withdraw(carol, lpTokens, XRPAmount(0)); if (!env.enabled(fixAMMv1_3)) + { BEAST_EXPECT( ammAlice.expectBalances(XRP(10'000), USD(10'000), ammAlice.tokens())); + } else + { BEAST_EXPECT(ammAlice.expectBalances( XRPAmount(10'000'000'001), USD(10'000), ammAlice.tokens())); + } BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{0})); }, std::nullopt, @@ -2057,20 +2081,26 @@ private: ammAlice.withdraw(carol, USD(100), std::nullopt, IOUAmount{520, 0}); BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{153'846'15384616, -8})); if (!env.enabled(fixAMMv1_1) && !env.enabled(fixAMMv1_3)) + { BEAST_EXPECT(ammAlice.expectBalances( XRPAmount(11'000'000'000), STAmount{USD, UINT64_C(9'372'781065088757), -12}, IOUAmount{10'153'846'15384616, -8})); + } else if (env.enabled(fixAMMv1_1) && !env.enabled(fixAMMv1_3)) + { BEAST_EXPECT(ammAlice.expectBalances( XRPAmount(11'000'000'000), STAmount{USD, UINT64_C(9'372'781065088769), -12}, IOUAmount{10'153'846'15384616, -8})); + } else if (env.enabled(fixAMMv1_3)) + { BEAST_EXPECT(ammAlice.expectBalances( XRPAmount(11'000'000'000), STAmount{USD, UINT64_C(9'372'78106508877), -11}, IOUAmount{10'153'846'15384616, -8})); + } ammAlice.withdrawAll(carol); BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{0})); }, @@ -2083,20 +2113,26 @@ private: ammAlice.withdraw(carol, USD(0), std::nullopt, IOUAmount{520, 0}); BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{153'846'15384616, -8})); if (!env.enabled(fixAMMv1_1) && !env.enabled(fixAMMv1_3)) + { BEAST_EXPECT(ammAlice.expectBalances( XRP(11'000), STAmount{USD, UINT64_C(9'372'781065088757), -12}, IOUAmount{10'153'846'15384616, -8})); + } else if (env.enabled(fixAMMv1_1) && !env.enabled(fixAMMv1_3)) + { BEAST_EXPECT(ammAlice.expectBalances( XRP(11'000), STAmount{USD, UINT64_C(9'372'781065088769), -12}, IOUAmount{10'153'846'15384616, -8})); + } else if (env.enabled(fixAMMv1_3)) + { BEAST_EXPECT(ammAlice.expectBalances( XRP(11'000), STAmount{USD, UINT64_C(9'372'78106508877), -11}, IOUAmount{10'153'846'15384616, -8})); + } }, std::nullopt, 0, @@ -2142,11 +2178,15 @@ private: // Single XRP pool ammAlice.withdraw(alice, std::nullopt, XRPAmount{1}); if (!env.enabled(fixAMMv1_3)) + { BEAST_EXPECT(ammAlice.expectBalances( XRPAmount{9'999'999'999}, USD(10'000), IOUAmount{9'999'999'9995, -4})); + } else + { BEAST_EXPECT(ammAlice.expectBalances( XRP(10'000), USD(10'000), IOUAmount{9'999'999'9995, -4})); + } }, std::nullopt, 0, @@ -2670,11 +2710,15 @@ private: fund(env, gw, {bob}, {USD(10'000)}, Fund::Acct); ammAlice.deposit(bob, 1'000'000); if (!features[fixAMMv1_3]) + { BEAST_EXPECT(ammAlice.expectBalances( XRP(12'000), USD(12'000), IOUAmount{12'000'000, 0})); + } else + { BEAST_EXPECT(ammAlice.expectBalances( XRPAmount{12'000'000'001}, USD(12'000), IOUAmount{12'000'000, 0})); + } // Initial state. Pay bidMin. env(ammAlice.bid({.account = carol, .bidMin = 110})).close(); @@ -2701,11 +2745,15 @@ private: BEAST_EXPECT(ammAlice.expectAuctionSlot(0, std::nullopt, IOUAmount{110})); // ~321.09 tokens burnt on bidding fees. if (!features[fixAMMv1_3]) + { BEAST_EXPECT(ammAlice.expectBalances( XRP(12'000), USD(12'000), IOUAmount{11'999'678'91, -2})); + } else + { BEAST_EXPECT(ammAlice.expectBalances( XRPAmount{12'000'000'001}, USD(12'000), IOUAmount{11'999'678'91, -2})); + } }, std::nullopt, 0, @@ -2735,10 +2783,14 @@ private: ammTokens -= slotPrice; BEAST_EXPECT(ammAlice.expectAuctionSlot(100, 0, slotPrice)); if (!features[fixAMMv1_3]) + { BEAST_EXPECT(ammAlice.expectBalances(XRP(13'000), USD(13'000), ammTokens)); + } else + { BEAST_EXPECT( ammAlice.expectBalances(XRPAmount{13'000'000'003}, USD(13'000), ammTokens)); + } // Discounted trade for (int i = 0; i < 10; ++i) { @@ -2774,15 +2826,19 @@ private: env.balance(ed, USD) == STAmount(USD, UINT64_C(18'999'0057261184), -10)); // USD pool is slightly higher because of the fees. if (!features[fixAMMv1_3]) + { BEAST_EXPECT(ammAlice.expectBalances( XRP(13'000), STAmount(USD, UINT64_C(13'002'98282151422), -11), ammTokens)); + } else + { BEAST_EXPECT(ammAlice.expectBalances( XRPAmount{13'000'000'003}, STAmount(USD, UINT64_C(13'002'98282151422), -11), ammTokens)); + } } ammTokens = ammAlice.getLPTokensBalance(); // Trade with the fee @@ -2818,51 +2874,67 @@ private: else { if (!features[fixAMMv1_3]) + { BEAST_EXPECT( env.balance(dan, USD) == STAmount(USD, UINT64_C(19'490'05672274399), -11)); + } else + { BEAST_EXPECT( env.balance(dan, USD) == STAmount(USD, UINT64_C(19'490'05672274398), -11)); + } // USD pool gains more in dan's fees. if (!features[fixAMMv1_3]) + { BEAST_EXPECT(ammAlice.expectBalances( XRP(13'000), STAmount{USD, UINT64_C(13'012'92609877023), -11}, ammTokens)); + } else + { BEAST_EXPECT(ammAlice.expectBalances( XRPAmount{13'000'000'003}, STAmount{USD, UINT64_C(13'012'92609877024), -11}, ammTokens)); + } // Discounted fee payment ammAlice.deposit(carol, USD(100)); ammTokens = ammAlice.getLPTokensBalance(); if (!features[fixAMMv1_3]) + { BEAST_EXPECT(ammAlice.expectBalances( XRP(13'000), STAmount{USD, UINT64_C(13'112'92609877023), -11}, ammTokens)); + } else + { BEAST_EXPECT(ammAlice.expectBalances( XRPAmount{13'000'000'003}, STAmount{USD, UINT64_C(13'112'92609877024), -11}, ammTokens)); + } env(pay(carol, bob, USD(100)), path(~USD), sendmax(XRP(110))); env.close(); // carol pays 100000 drops in fees // 99900668XRP swapped in for 100USD if (!features[fixAMMv1_3]) + { BEAST_EXPECT(ammAlice.expectBalances( XRPAmount{13'100'000'668}, STAmount{USD, UINT64_C(13'012'92609877023), -11}, ammTokens)); + } else + { BEAST_EXPECT(ammAlice.expectBalances( XRPAmount{13'100'000'671}, STAmount{USD, UINT64_C(13'012'92609877024), -11}, ammTokens)); + } } // Payment with the trading fee env(pay(alice, carol, XRP(100)), path(~XRP), sendmax(USD(110))); @@ -2896,13 +2968,17 @@ private: // clock is parent's based env.close(); if (!features[fixAMMv1_1]) + { BEAST_EXPECT( env.balance(carol, USD) == STAmount(USD, UINT64_C(29'399'00572620545), -11)); + } else if (!features[fixAMMv1_3]) + { BEAST_EXPECT( env.balance(carol, USD) == STAmount(USD, UINT64_C(29'399'00572620544), -11)); + } ammTokens = ammAlice.getLPTokensBalance(); for (int i = 0; i < 10; ++i) { @@ -4397,17 +4473,21 @@ private: prep( [&](Env& env) { if (!features[fixAMMv1_1]) + { env(offer( LP1, XRPAmount{18'095'133}, STAmount{TST, UINT64_C(1'68737984885388), -14}), txflags(tfPassive)); + } else + { env(offer( LP1, XRPAmount{18'095'132}, STAmount{TST, UINT64_C(1'68737976189735), -14}), txflags(tfPassive)); + } }, [&](Env& env) { BEAST_EXPECT( @@ -4528,11 +4608,15 @@ private: // carol withdraws ~1,443.44USD auto const balanceAfterWithdraw = [&]() { if (!features[fixAMMv1_1] && !features[fixAMMv1_3]) + { return STAmount(USD, UINT64_C(30'443'43891402715), -11); - else if (features[fixAMMv1_1] && !features[fixAMMv1_3]) + } + if (features[fixAMMv1_1] && !features[fixAMMv1_3]) + { return STAmount(USD, UINT64_C(30'443'43891402714), -11); - else - return STAmount(USD, UINT64_C(30'443'43891402713), -11); + } + + return STAmount(USD, UINT64_C(30'443'43891402713), -11); }(); BEAST_EXPECT(env.balance(carol, USD) == balanceAfterWithdraw); // Set to original pool size @@ -4543,25 +4627,37 @@ private: BEAST_EXPECT(ammAlice.expectTradingFee(0)); auto const tokensNoFee = ammAlice.withdraw(carol, deposit); if (!features[fixAMMv1_1] && !features[fixAMMv1_3]) + { BEAST_EXPECT( env.balance(carol, USD) == STAmount(USD, UINT64_C(30'443'43891402717), -11)); + } else if (features[fixAMMv1_1] && !features[fixAMMv1_3]) + { BEAST_EXPECT( env.balance(carol, USD) == STAmount(USD, UINT64_C(30'443'43891402716), -11)); + } else + { BEAST_EXPECT( env.balance(carol, USD) == STAmount(USD, UINT64_C(30'443'43891402713), -11)); + } // carol pays ~4008 LPTokens in fees or ~0.5% of the no-fee // LPTokens if (!features[fixAMMv1_1] && !features[fixAMMv1_3]) + { BEAST_EXPECT(tokensNoFee == IOUAmount(746'579'80779913, -8)); + } else if (features[fixAMMv1_1] && !features[fixAMMv1_3]) + { BEAST_EXPECT(tokensNoFee == IOUAmount(746'579'80779912, -8)); + } else + { BEAST_EXPECT(tokensNoFee == IOUAmount(746'579'80779911, -8)); + } BEAST_EXPECT(tokensFee == IOUAmount(750'588'23529411, -8)); }, std::nullopt, @@ -4808,49 +4904,73 @@ private: // other have a tiny loss. The last account to withdraw // gets everything in the pool. if (!features[fixAMMv1_1] && !features[fixAMMv1_3]) + { BEAST_EXPECT(ammAlice.expectBalances( XRP(10'000), STAmount{USD, UINT64_C(10'000'0000000013), -10}, IOUAmount{10'000'000})); + } else if (features[fixAMMv1_3]) + { BEAST_EXPECT(ammAlice.expectBalances( XRP(10'000), STAmount{USD, UINT64_C(10'000'0000000003), -10}, IOUAmount{10'000'000})); + } else + { BEAST_EXPECT( ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000})); + } BEAST_EXPECT(expectHolding(env, ben, USD(1'500'000))); BEAST_EXPECT(expectHolding(env, simon, USD(1'500'000))); BEAST_EXPECT(expectHolding(env, chris, USD(1'500'000))); BEAST_EXPECT(expectHolding(env, dan, USD(1'500'000))); if (!features[fixAMMv1_1] && !features[fixAMMv1_3]) + { BEAST_EXPECT(expectHolding( env, carol, STAmount{USD, UINT64_C(30'000'00000000001), -11})); + } else if (features[fixAMMv1_1] && !features[fixAMMv1_3]) + { BEAST_EXPECT(expectHolding(env, carol, USD(30'000))); + } else + { BEAST_EXPECT(expectHolding(env, carol, USD(30'000))); + } BEAST_EXPECT(expectHolding(env, ed, USD(1'500'000))); BEAST_EXPECT(expectHolding(env, paul, USD(1'500'000))); if (!features[fixAMMv1_1] && !features[fixAMMv1_3]) + { BEAST_EXPECT(expectHolding( env, natalie, STAmount{USD, UINT64_C(1'500'000'000000002), -9})); + } else if (features[fixAMMv1_1] && !features[fixAMMv1_3]) + { BEAST_EXPECT(expectHolding( env, natalie, STAmount{USD, UINT64_C(1'500'000'000000005), -9})); + } else + { BEAST_EXPECT(expectHolding(env, natalie, USD(1'500'000))); + } ammAlice.withdrawAll(alice); BEAST_EXPECT(!ammAlice.ammExists()); if (!features[fixAMMv1_1]) + { BEAST_EXPECT( expectHolding(env, alice, STAmount{USD, UINT64_C(30'000'0000000013), -10})); + } else if (features[fixAMMv1_3]) + { BEAST_EXPECT( expectHolding(env, alice, STAmount{USD, UINT64_C(30'000'0000000003), -10})); + } else + { BEAST_EXPECT(expectHolding(env, alice, USD(30'000))); + } // alice XRP balance is 30,000 initial - 50 AMMCreate fee - // 10drops fee BEAST_EXPECT( @@ -5252,6 +5372,7 @@ private: if (rates.first == 1.5) { if (!features[fixAMMv1_1]) + { BEAST_EXPECT(expectOffers( env, ed, @@ -5259,7 +5380,9 @@ private: {{Amounts{ STAmount{ETH, UINT64_C(378'6327949540823), -13}, STAmount{USD, UINT64_C(283'9745962155617), -13}}}})); + } else + { BEAST_EXPECT(expectOffers( env, ed, @@ -5267,10 +5390,12 @@ private: {{Amounts{ STAmount{ETH, UINT64_C(378'6327949540813), -13}, STAmount{USD, UINT64_C(283'974596215561), -12}}}})); + } } else { if (!features[fixAMMv1_1]) + { BEAST_EXPECT(expectOffers( env, ed, @@ -5278,7 +5403,9 @@ private: {{Amounts{ STAmount{ETH, UINT64_C(325'299461620749), -12}, STAmount{USD, UINT64_C(243'9745962155617), -13}}}})); + } else + { BEAST_EXPECT(expectOffers( env, ed, @@ -5286,6 +5413,7 @@ private: {{Amounts{ STAmount{ETH, UINT64_C(325'299461620748), -12}, STAmount{USD, UINT64_C(243'974596215561), -12}}}})); + } } } else if (i == 2) @@ -5701,18 +5829,26 @@ private: if (status == SucceedShouldSucceedResize) { if (!features[fixAMMv1_1]) + { BEAST_EXPECT(Quality{*amounts} < quality); + } else + { BEAST_EXPECT(Quality{*amounts} >= quality); + } } else if (status == Succeed) { if (!features[fixAMMv1_1]) + { BEAST_EXPECT( Quality{*amounts} >= quality || withinRelativeDistance(Quality{*amounts}, quality, Number{1, -7})); + } else + { BEAST_EXPECT(Quality{*amounts} >= quality); + } } else if (status == FailShouldSucceed) { @@ -5741,7 +5877,7 @@ private: takerPays, swapAssetIn(Amounts{poolIn, poolOut}, takerPays, tfee)}; } - else if (isXRP(poolOut)) + if (isXRP(poolOut)) { auto const takerGets = STAmount{xrpIssue(), 1}; return Amounts{ @@ -5871,7 +6007,7 @@ private: STAmount const goodUsdBIT; STAmount const goodUsdBITr; IOUAmount const lpTokenBalance; - std::optional const lpTokenBalanceAlt = {}; + std::optional const lpTokenBalanceAlt = std::nullopt; double const offer1BtcGH = 0.1; double const offer2BtcGH = 0.1; double const offer2UsdGH = 1; @@ -6640,9 +6776,13 @@ private: amm.withdraw(WithdrawArg{.asset1Out = STAmount{XPM, 1, -5}}); auto const [amount_, amount2_, lptAMM_] = amm.balances(XRP, XPM); if (!env.enabled(fixAMMv1_3)) + { BEAST_EXPECT((amount2 - amount2_) > withdraw); + } else + { BEAST_EXPECT((amount2 - amount2_) <= withdraw); + } }, 0); } @@ -6657,9 +6797,13 @@ private: auto const res = root2(amount * amount2); if (shouldFail) + { BEAST_EXPECT(res < lptBalance); + } else + { BEAST_EXPECT(res >= lptBalance); + } } void diff --git a/src/test/app/AccountSet_test.cpp b/src/test/app/AccountSet_test.cpp index 87c6474be2..73e807a8aa 100644 --- a/src/test/app/AccountSet_test.cpp +++ b/src/test/app/AccountSet_test.cpp @@ -307,9 +307,13 @@ public: // If the field is not present expect the default value if (!(*env.le(alice))[~sfTransferRate]) + { BEAST_EXPECT(r.get == 1.0); + } else + { BEAST_EXPECT(*(*env.le(alice))[~sfTransferRate] == r.get * QUALITY_ONE); + } } }; diff --git a/src/test/app/AmendmentTable_test.cpp b/src/test/app/AmendmentTable_test.cpp index 3b14c8b622..d8431e5696 100644 --- a/src/test/app/AmendmentTable_test.cpp +++ b/src/test/app/AmendmentTable_test.cpp @@ -390,7 +390,7 @@ public: { uint256 const supportedID = amendmentId(a); bool const enabled = table->isEnabled(supportedID); - bool const found = allEnabled.find(supportedID) != allEnabled.end(); + bool const found = allEnabled.contains(supportedID); BEAST_EXPECTS( enabled == found, a + (enabled ? " enabled " : " disabled ") + (found ? " found" : " not found")); @@ -404,7 +404,7 @@ public: std::vector const desired = table->getDesired(); for (uint256 const& a : desired) - BEAST_EXPECT(vetoed.count(a) == 0); + BEAST_EXPECT(not vetoed.contains(a)); // Unveto an amendment that is already not vetoed. Shouldn't // hurt anything, but the values returned by getDesired() @@ -526,22 +526,22 @@ public: { case 0: // amendment goes from majority to enabled - if (enabled.find(hash) != enabled.end()) + if (enabled.contains(hash)) Throw("enabling already enabled"); - if (majority.find(hash) == majority.end()) + if (!majority.contains(hash)) Throw("enabling without majority"); enabled.insert(hash); majority.erase(hash); break; case tfGotMajority: - if (majority.find(hash) != majority.end()) + if (majority.contains(hash)) Throw("got majority while having majority"); majority[hash] = roundTime; break; case tfLostMajority: - if (majority.find(hash) == majority.end()) + if (!majority.contains(hash)) Throw("lost majority without majority"); majority.erase(hash); break; @@ -719,7 +719,7 @@ public: BEAST_EXPECT(ourVotes.size() == yes_.size()); BEAST_EXPECT(enabled.empty()); for (auto const& i : yes_) - BEAST_EXPECT(majority.find(amendmentId(i)) == majority.end()); + BEAST_EXPECT(not majority.contains(amendmentId(i))); // Now, everyone votes for this feature for (auto const& i : yes_) @@ -766,7 +766,7 @@ public: BEAST_EXPECT(enabled.size() == yes_.size()); BEAST_EXPECT(ourVotes.empty()); for (auto const& i : yes_) - BEAST_EXPECT(majority.find(amendmentId(i)) == majority.end()); + BEAST_EXPECT(not majority.contains(amendmentId(i))); } // Detect majority at 80%, enable later diff --git a/src/test/app/Check_test.cpp b/src/test/app/Check_test.cpp index 00e8dd4d53..f8bb0ddcf2 100644 --- a/src/test/app/Check_test.cpp +++ b/src/test/app/Check_test.cpp @@ -528,8 +528,8 @@ class Check_test : public beast::unit_test::suite env.close(); env.require(balance(alice, startBalance - XRP(10) - drops(baseFeeDrops))); env.require(balance(bob, startBalance + XRP(10) - drops(baseFeeDrops))); - BEAST_EXPECT(checksOnAccount(env, alice).size() == 0); - BEAST_EXPECT(checksOnAccount(env, bob).size() == 0); + BEAST_EXPECT(checksOnAccount(env, alice).empty()); + BEAST_EXPECT(checksOnAccount(env, bob).empty()); BEAST_EXPECT(ownerCount(env, alice) == 0); BEAST_EXPECT(ownerCount(env, bob) == 0); @@ -562,8 +562,8 @@ class Check_test : public beast::unit_test::suite verifyDeliveredAmount(env, drops(checkAmount.mantissa())); env.require(balance(alice, reserve)); env.require(balance(bob, startBalance + checkAmount - drops(baseFeeDrops * 3))); - BEAST_EXPECT(checksOnAccount(env, alice).size() == 0); - BEAST_EXPECT(checksOnAccount(env, bob).size() == 0); + BEAST_EXPECT(checksOnAccount(env, alice).empty()); + BEAST_EXPECT(checksOnAccount(env, bob).empty()); BEAST_EXPECT(ownerCount(env, alice) == 0); BEAST_EXPECT(ownerCount(env, bob) == 0); @@ -592,8 +592,8 @@ class Check_test : public beast::unit_test::suite verifyDeliveredAmount(env, drops(checkAmount.mantissa() - 1)); env.require(balance(alice, reserve)); env.require(balance(bob, startBalance + checkAmount - drops(baseFeeDrops * 2 + 1))); - BEAST_EXPECT(checksOnAccount(env, alice).size() == 0); - BEAST_EXPECT(checksOnAccount(env, bob).size() == 0); + BEAST_EXPECT(checksOnAccount(env, alice).empty()); + BEAST_EXPECT(checksOnAccount(env, bob).empty()); BEAST_EXPECT(ownerCount(env, alice) == 0); BEAST_EXPECT(ownerCount(env, bob) == 0); @@ -663,8 +663,8 @@ class Check_test : public beast::unit_test::suite env.close(); env.require(balance(alice, USD(0))); env.require(balance(bob, USD(10))); - BEAST_EXPECT(checksOnAccount(env, alice).size() == 0); - BEAST_EXPECT(checksOnAccount(env, bob).size() == 0); + BEAST_EXPECT(checksOnAccount(env, alice).empty()); + BEAST_EXPECT(checksOnAccount(env, bob).empty()); BEAST_EXPECT(ownerCount(env, alice) == 1); BEAST_EXPECT(ownerCount(env, bob) == 1); @@ -688,8 +688,8 @@ class Check_test : public beast::unit_test::suite env.close(); env.require(balance(alice, USD(2))); env.require(balance(bob, USD(8))); - BEAST_EXPECT(checksOnAccount(env, alice).size() == 0); - BEAST_EXPECT(checksOnAccount(env, bob).size() == 0); + BEAST_EXPECT(checksOnAccount(env, alice).empty()); + BEAST_EXPECT(checksOnAccount(env, bob).empty()); BEAST_EXPECT(ownerCount(env, alice) == 1); BEAST_EXPECT(ownerCount(env, bob) == 1); @@ -755,8 +755,8 @@ class Check_test : public beast::unit_test::suite env.close(); env.require(balance(alice, USD(0))); env.require(balance(bob, USD(10))); - BEAST_EXPECT(checksOnAccount(env, alice).size() == 0); - BEAST_EXPECT(checksOnAccount(env, bob).size() == 0); + BEAST_EXPECT(checksOnAccount(env, alice).empty()); + BEAST_EXPECT(checksOnAccount(env, bob).empty()); BEAST_EXPECT(ownerCount(env, alice) == 1); BEAST_EXPECT(ownerCount(env, bob) == 1); } @@ -838,8 +838,8 @@ class Check_test : public beast::unit_test::suite verifyDeliveredAmount(env, USD(2)); env.require(balance(alice, USD(0))); env.require(balance(bob, USD(8))); - BEAST_EXPECT(checksOnAccount(env, alice).size() == 0); - BEAST_EXPECT(checksOnAccount(env, bob).size() == 0); + BEAST_EXPECT(checksOnAccount(env, alice).empty()); + BEAST_EXPECT(checksOnAccount(env, bob).empty()); BEAST_EXPECT(ownerCount(env, alice) == 1); BEAST_EXPECT(ownerCount(env, bob) == 1); } @@ -890,8 +890,8 @@ class Check_test : public beast::unit_test::suite env.require(balance(alice, USD(8) - bobGot)); env.require(balance(bob, bobGot)); - BEAST_EXPECT(checksOnAccount(env, alice).size() == 0); - BEAST_EXPECT(checksOnAccount(env, bob).size() == 0); + BEAST_EXPECT(checksOnAccount(env, alice).empty()); + BEAST_EXPECT(checksOnAccount(env, bob).empty()); BEAST_EXPECT(ownerCount(env, alice) == 1); BEAST_EXPECT(ownerCount(env, bob) == 1); } @@ -945,8 +945,8 @@ class Check_test : public beast::unit_test::suite env.close(); env.require(balance(alice, USD(5))); env.require(balance(bob, USD(3))); - BEAST_EXPECT(checksOnAccount(env, alice).size() == 0); - BEAST_EXPECT(checksOnAccount(env, bob).size() == 0); + BEAST_EXPECT(checksOnAccount(env, alice).empty()); + BEAST_EXPECT(checksOnAccount(env, bob).empty()); BEAST_EXPECT(ownerCount(env, alice) == 1); BEAST_EXPECT(ownerCount(env, bob) == 2); } @@ -1018,8 +1018,8 @@ class Check_test : public beast::unit_test::suite env.close(); env.require(balance(alice, USD(1000 - 125 - 60))); env.require(balance(bob, USD(0 + 100 + 50))); - BEAST_EXPECT(checksOnAccount(env, alice).size() == 0); - BEAST_EXPECT(checksOnAccount(env, bob).size() == 0); + BEAST_EXPECT(checksOnAccount(env, alice).empty()); + BEAST_EXPECT(checksOnAccount(env, bob).empty()); } void @@ -1655,7 +1655,7 @@ class Check_test : public beast::unit_test::suite env(check::cancel(bob, chkIdNotExp3)); env.close(); - BEAST_EXPECT(checksOnAccount(env, alice).size() == 0); + BEAST_EXPECT(checksOnAccount(env, alice).empty()); BEAST_EXPECT(ownerCount(env, alice) == 1); } } @@ -1815,7 +1815,7 @@ class Check_test : public beast::unit_test::suite env.require(owners(alice, 6)); env.require(tickets(alice, env.seq(alice) - aliceTicketSeq)); - BEAST_EXPECT(checksOnAccount(env, alice).size() == 0); + BEAST_EXPECT(checksOnAccount(env, alice).empty()); BEAST_EXPECT(env.seq(alice) == aliceSeq); env.require(balance(alice, USD(700))); @@ -1852,7 +1852,7 @@ class Check_test : public beast::unit_test::suite } // Operators to make using the class more convenient. - operator Account const() const + operator Account() const { return acct; } diff --git a/src/test/app/DNS_test.cpp b/src/test/app/DNS_test.cpp index 0c2946f8ed..9b75e66b85 100644 --- a/src/test/app/DNS_test.cpp +++ b/src/test/app/DNS_test.cpp @@ -15,7 +15,7 @@ class DNS_test : public beast::unit_test::suite using endpoint_type = boost::asio::ip::tcp::endpoint; using error_code = boost::system::error_code; std::weak_ptr work_; - endpoint_type lastEndpoint_{}; + endpoint_type lastEndpoint_; parsedURL pUrl_; std::string port_; jtx::Env env_; @@ -76,7 +76,7 @@ public: parse() { std::string url = arg(); - if (url == "") + if (url.empty()) url = "https://vl.ripple.com"; BEAST_EXPECT(parseUrl(pUrl_, url)); port_ = pUrl_.port ? std::to_string(*pUrl_.port) : "443"; diff --git a/src/test/app/DepositAuth_test.cpp b/src/test/app/DepositAuth_test.cpp index 547d9d8b62..ad401499bc 100644 --- a/src/test/app/DepositAuth_test.cpp +++ b/src/test/app/DepositAuth_test.cpp @@ -1283,8 +1283,10 @@ struct DepositPreauth_test : public beast::unit_test::suite auto issuer = c[jss::Issuer].asString(); if (BEAST_EXPECT(pubKey2Acc.contains(issuer))) + { readCreds.emplace_back( pubKey2Acc.at(issuer), c["CredentialType"].asString()); + } } BEAST_EXPECT(std::ranges::is_sorted(readCreds)); diff --git a/src/test/app/Discrepancy_test.cpp b/src/test/app/Discrepancy_test.cpp index 08a8a01753..3f808b37d8 100644 --- a/src/test/app/Discrepancy_test.cpp +++ b/src/test/app/Discrepancy_test.cpp @@ -93,11 +93,17 @@ class Discrepancy_test : public beast::unit_test::suite { Json::Value node; if (an.isMember(sfCreatedNode.fieldName)) + { node = an[sfCreatedNode.fieldName]; + } else if (an.isMember(sfModifiedNode.fieldName)) + { node = an[sfModifiedNode.fieldName]; + } else if (an.isMember(sfDeletedNode.fieldName)) + { node = an[sfDeletedNode.fieldName]; + } if (node && node[sfLedgerEntryType.fieldName] == jss::AccountRoot) { @@ -108,11 +114,15 @@ class Discrepancy_test : public beast::unit_test::suite ? node[sfFinalFields.fieldName] : node[sfNewFields.fieldName]; if (prevFields) + { sumPrev += beast::lexicalCastThrow( prevFields[sfBalance.fieldName].asString()); + } if (finalFields) + { sumFinal += beast::lexicalCastThrow( finalFields[sfBalance.fieldName].asString()); + } } } // the difference in balances (final and prev) should be the diff --git a/src/test/app/EscrowToken_test.cpp b/src/test/app/EscrowToken_test.cpp index 5cbeb0b94a..280356c494 100644 --- a/src/test/app/EscrowToken_test.cpp +++ b/src/test/app/EscrowToken_test.cpp @@ -1258,9 +1258,13 @@ struct EscrowToken_test : public beast::unit_test::suite env.close(); if (t.hasTrustline) + { env.trust(USD(100'000), t.src, t.dst); + } else + { env.trust(USD(100'000), t.src); + } env.close(); env(pay(t.gw, t.src, USD(10'000))); diff --git a/src/test/app/Flow_test.cpp b/src/test/app/Flow_test.cpp index c56cef39f8..692d9d2b50 100644 --- a/src/test/app/Flow_test.cpp +++ b/src/test/app/Flow_test.cpp @@ -196,6 +196,7 @@ struct Flow_test : public beast::unit_test::suite // Dan -> Bob -> Alice -> Carol; vary bobDanQIn and bobAliceQOut for (auto bobDanQIn : {80, 100, 120}) + { for (auto bobAliceQOut : {80, 100, 120}) { Env env(*this, features); @@ -213,12 +214,17 @@ struct Flow_test : public beast::unit_test::suite txflags(tfNoRippleDirect)); env.require(balance(bob, USDA(90))); if (bobAliceQOut > bobDanQIn) + { env.require( balance(bob, USDD(10.0 * double(bobAliceQOut) / double(bobDanQIn)))); + } else + { env.require(balance(bob, USDD(10))); + } env.require(balance(carol, USDA(10))); } + } // bob -> alice -> carol; vary carolAliceQIn for (auto carolAliceQIn : {80, 100, 120}) @@ -472,8 +478,10 @@ struct Flow_test : public beast::unit_test::suite return false; Sandbox sb(&view, tapNONE); for (auto const& o : flowResult.removableOffers) + { if (auto ok = sb.peek(keylet::offer(o))) offerDelete(sb, ok, flowJournal); + } sb.apply(view); return true; }); diff --git a/src/test/app/HashRouter_test.cpp b/src/test/app/HashRouter_test.cpp index 43ef4a4e06..58bace3ef2 100644 --- a/src/test/app/HashRouter_test.cpp +++ b/src/test/app/HashRouter_test.cpp @@ -231,7 +231,7 @@ class HashRouter_test : public beast::unit_test::suite ++stopwatch; // Confirm that peers list is empty. peers = router.shouldRelay(key1); - BEAST_EXPECT(peers && peers->size() == 0); + BEAST_EXPECT(peers && peers->empty()); } void diff --git a/src/test/app/Invariants_test.cpp b/src/test/app/Invariants_test.cpp index 3101fda316..e17ef1fd55 100644 --- a/src/test/app/Invariants_test.cpp +++ b/src/test/app/Invariants_test.cpp @@ -71,7 +71,7 @@ class Invariants_test : public beast::unit_test::suite Preclose const& preclose = {}, TxAccount setTxAccount = TxAccount::None) { - return doInvariantCheck( + doInvariantCheck( test::jtx::Env(*this, defaultAmendments()), expect_logs, precheck, @@ -105,7 +105,7 @@ class Invariants_test : public beast::unit_test::suite if (setTxAccount != TxAccount::None) tx.setAccountID(sfAccount, setTxAccount == TxAccount::A1 ? A1.id() : A2.id()); - return doInvariantCheck(std::move(env), A1, A2, expect_logs, precheck, fee, tx, ters); + doInvariantCheck(std::move(env), A1, A2, expect_logs, precheck, fee, tx, ters); } void @@ -395,22 +395,21 @@ class Invariants_test : public beast::unit_test::suite for (auto const& trustKeylet : {keylet::line(ammAcctID, A1["USD"]), keylet::line(A1, ammIssue)}) { - if (auto const line = ac.view().peek(trustKeylet); !line) + auto const line = ac.view().peek(trustKeylet); + if (!line) { return false; } - else - { - STAmount const lowLimit = line->at(sfLowLimit); - STAmount const highLimit = line->at(sfHighLimit); - BEAST_EXPECT( - trustDelete( - ac.view(), - line, - lowLimit.getIssuer(), - highLimit.getIssuer(), - ac.journal) == tesSUCCESS); - } + + STAmount const lowLimit = line->at(sfLowLimit); + STAmount const highLimit = line->at(sfHighLimit); + BEAST_EXPECT( + trustDelete( + ac.view(), + line, + lowLimit.getIssuer(), + highLimit.getIssuer(), + ac.journal) == tesSUCCESS); } auto const ammSle = ac.view().peek(keylet::amm(ammKey)); @@ -2262,14 +2261,16 @@ class Invariants_test : public beast::unit_test::suite }; struct Adjustments { - std::optional assetsTotal = {}; - std::optional assetsAvailable = {}; - std::optional lossUnrealized = {}; - std::optional assetsMaximum = {}; - std::optional sharesTotal = {}; - std::optional vaultAssets = {}; - std::optional accountAssets = {}; - std::optional accountShares = {}; + // NOLINTBEGIN(readability-redundant-member-init) + std::optional assetsTotal = std::nullopt; + std::optional assetsAvailable = std::nullopt; + std::optional lossUnrealized = std::nullopt; + std::optional assetsMaximum = std::nullopt; + std::optional sharesTotal = std::nullopt; + std::optional vaultAssets = std::nullopt; + std::optional accountAssets = std::nullopt; + std::optional accountShares = std::nullopt; + // NOLINTEND(readability-redundant-member-init) }; auto constexpr adjust = [&](ApplyView& ac, xrpl::Keylet keylet, Adjustments args) { auto sleVault = ac.peek(keylet); @@ -2291,8 +2292,10 @@ class Invariants_test : public beast::unit_test::suite if (args.assetsTotal) (*sleVault)[sfAssetsTotal] = *(*sleVault)[sfAssetsTotal] + *args.assetsTotal; if (args.assetsAvailable) + { (*sleVault)[sfAssetsAvailable] = *(*sleVault)[sfAssetsAvailable] + *args.assetsAvailable; + } ac.update(sleVault); if (args.sharesTotal) @@ -2325,7 +2328,9 @@ class Invariants_test : public beast::unit_test::suite ac.update(sleMPToken); } else + { return false; // Not supporting testing with IOU + } } if (args.accountAssets) @@ -2349,7 +2354,9 @@ class Invariants_test : public beast::unit_test::suite ac.update(sleMPToken); } else + { return false; // Not supporting testing with IOU + } } if (args.accountShares) diff --git a/src/test/app/LPTokenTransfer_test.cpp b/src/test/app/LPTokenTransfer_test.cpp index 15a8837c4f..265ff7d2ef 100644 --- a/src/test/app/LPTokenTransfer_test.cpp +++ b/src/test/app/LPTokenTransfer_test.cpp @@ -299,9 +299,13 @@ class LPTokenTransfer_test : public jtx::AMMTest // with fixFrozenLPTokenTransfer enabled, bob fails to cash the check if (features[fixFrozenLPTokenTransfer]) + { env(check::cash(bob, carolChkId, STAmount{lpIssue, 10}), ter(tecPATH_PARTIAL)); + } else + { env(check::cash(bob, carolChkId, STAmount{lpIssue, 10})); + } env.close(); diff --git a/src/test/app/LedgerLoad_test.cpp b/src/test/app/LedgerLoad_test.cpp index 4c0cb00f3f..46c372923e 100644 --- a/src/test/app/LedgerLoad_test.cpp +++ b/src/test/app/LedgerLoad_test.cpp @@ -36,17 +36,19 @@ class LedgerLoad_test : public beast::unit_test::suite struct SetupData { std::string const dbPath; - std::string ledgerFile{}; - Json::Value ledger{}; - Json::Value hashes{}; - uint256 trapTxHash{}; + // NOLINTBEGIN(readability-redundant-member-init) + std::string ledgerFile = {}; + Json::Value ledger = {}; + Json::Value hashes = {}; + uint256 trapTxHash = {}; + // NOLINTEND(readability-redundant-member-init) }; SetupData setupLedger(beast::temp_dir const& td) { using namespace test::jtx; - SetupData retval = {td.path()}; + SetupData retval = {.dbPath = td.path()}; retval.ledgerFile = td.file("ledgerdata.json"); diff --git a/src/test/app/LedgerReplay_test.cpp b/src/test/app/LedgerReplay_test.cpp index 4428e82ea9..54c12b465a 100644 --- a/src/test/app/LedgerReplay_test.cpp +++ b/src/test/app/LedgerReplay_test.cpp @@ -355,9 +355,13 @@ struct TestPeerSet : public PeerSet { int dropRate = 0; if (behavior == PeerSetBehavior::Drop50) + { dropRate = 50; + } else if (behavior == PeerSetBehavior::DropAll) + { dropRate = 100; + } if ((rand() % 100 + 1) <= dropRate) return; @@ -497,7 +501,7 @@ struct LedgerServer auto updateIdx = [&]() { assert(fundedAccounts > senders.size()); fromIdx = (fromIdx + r) % fundedAccounts; - while (senders.count(fromIdx) != 0) + while (senders.contains(fromIdx)) fromIdx = (fromIdx + 1) % fundedAccounts; senders.insert(fromIdx); toIdx = (toIdx + r * 2) % fundedAccounts; @@ -968,7 +972,7 @@ struct LedgerReplayer_test : public beast::unit_test::suite { testcase("TaskParameter"); - auto makeSkipList = [](int count) -> std::vector const { + auto makeSkipList = [](int count) -> std::vector { std::vector sList; for (int i = 0; i < count; ++i) sList.emplace_back(i); @@ -1095,7 +1099,9 @@ struct LedgerReplayer_test : public beast::unit_test::suite l = net.server.ledgerMaster.getLedgerByHash(l->header().parentHash); } else + { break; + } } net.client.replayer.replay(InboundLedger::Reason::GENERIC, finalHash, totalReplay); diff --git a/src/test/app/LoanBroker_test.cpp b/src/test/app/LoanBroker_test.cpp index 380035167c..361f70209f 100644 --- a/src/test/app/LoanBroker_test.cpp +++ b/src/test/app/LoanBroker_test.cpp @@ -91,12 +91,24 @@ class LoanBroker_test : public beast::unit_test::suite { { auto const& asset = vault.asset.raw(); - testcase << "Lifecycle: " - << (asset.native() ? "XRP " - : asset.holds() ? "IOU " - : asset.holds() ? "MPT " - : "Unknown ") - << label; + std::string_view assetLabel; + if (asset.native()) + { + assetLabel = "XRP "; + } + else if (asset.holds()) + { + assetLabel = "IOU "; + } + else if (asset.holds()) + { + assetLabel = "MPT "; + } + else + { + assetLabel = "Unknown "; + } + testcase << "Lifecycle: " << assetLabel << label; } using namespace jtx; @@ -877,8 +889,10 @@ class LoanBroker_test : public beast::unit_test::suite env(coverDeposit(alice, brokerKeylet.key, vaultInfo.asset(10)), ter(tecFROZEN)); } else + { // Fund the cover deposit env(coverDeposit(alice, brokerKeylet.key, vaultInfo.asset(10))); + } env.close(); if (brokerTest == CoverWithdraw) @@ -999,7 +1013,9 @@ class LoanBroker_test : public beast::unit_test::suite env(del(alice, brokerKeylet.key), ter(tesSUCCESS)); } else + { env(del(alice, brokerKeylet.key)); + } if (brokerTest == Set) { diff --git a/src/test/app/Loan_test.cpp b/src/test/app/Loan_test.cpp index f1cd76d88b..171e2eddb5 100644 --- a/src/test/app/Loan_test.cpp +++ b/src/test/app/Loan_test.cpp @@ -81,7 +81,7 @@ protected: int coverDeposit = 1000; TenthBips16 managementFeeRate{100}; TenthBips32 coverRateLiquidation = percentageToTenthBips(25); - std::string data{}; + std::string data = {}; // NOLINT(readability-redundant-member-init) std::uint32_t flags = 0; Number @@ -150,20 +150,22 @@ protected: // only signs. bool counterpartyExplicit = true; Number principalRequest; - std::optional setFee{}; - std::optional originationFee{}; - std::optional serviceFee{}; - std::optional lateFee{}; - std::optional closeFee{}; - std::optional overFee{}; - std::optional interest{}; - std::optional lateInterest{}; - std::optional closeInterest{}; - std::optional overpaymentInterest{}; - std::optional payTotal{}; - std::optional payInterval{}; - std::optional gracePd{}; - std::optional flags{}; + // NOLINTBEGIN(readability-redundant-member-init) + std::optional setFee = std::nullopt; + std::optional originationFee = std::nullopt; + std::optional serviceFee = std::nullopt; + std::optional lateFee = std::nullopt; + std::optional closeFee = std::nullopt; + std::optional overFee = std::nullopt; + std::optional interest = std::nullopt; + std::optional lateInterest = std::nullopt; + std::optional closeInterest = std::nullopt; + std::optional overpaymentInterest = std::nullopt; + std::optional payTotal = std::nullopt; + std::optional payInterval = std::nullopt; + std::optional gracePd = std::nullopt; + std::optional flags = std::nullopt; + // NOLINTEND(readability-redundant-member-init) template jtx::JTx @@ -232,7 +234,7 @@ protected: struct LoanState { std::uint32_t previousPaymentDate = 0; - NetClock::time_point startDate = {}; + NetClock::time_point startDate; std::uint32_t nextPaymentDate = 0; std::uint32_t paymentRemaining = 0; std::int32_t const loanScale = 0; @@ -698,10 +700,12 @@ protected: env.close(); if (asset.native() || lender != issuer) + { env( pay((asset.native() ? env.master : issuer), lender, asset(brokerParams.vaultDeposit + brokerParams.coverDeposit))); + } // Fund the borrower later once we know the total loan // size @@ -773,10 +777,12 @@ protected: auto const shortage = totalNeeded - borrowerBalance.number(); if (shortage > beast::zero && (broker.asset.native() || issuer != borrower)) + { env( pay((broker.asset.native() ? env.master : issuer), borrower, STAmount{broker.asset, shortage})); + } } void @@ -826,6 +832,7 @@ protected: roundPeriodicPayment(broker.asset, state.periodicPayment, state.loanScale)}; if (!showStepBalances) + { log << currencyLabel << " Payment components: " << "Payments remaining, " << "rawInterest, rawPrincipal, " @@ -833,6 +840,7 @@ protected: << "trackedValueDelta, trackedPrincipalDelta, " "trackedInterestDelta, trackedMgmtFeeDelta, special" << std::endl; + } // Include the service fee STAmount const totalDue = @@ -947,18 +955,21 @@ protected: (state.loanScale - (deltas.total() - state.periodicPayment).exponent()) > 14); if (!showStepBalances) + { log << currencyLabel << " Payment components: " << state.paymentRemaining << ", " << deltas.interest << ", " << deltas.principal << ", " << deltas.managementFee << ", " << paymentComponents.trackedValueDelta << ", " << paymentComponents.trackedPrincipalDelta << ", " << paymentComponents.trackedInterestPart() << ", " - << paymentComponents.trackedManagementFeeDelta << ", " - << (paymentComponents.specialCase == detail::PaymentSpecialCase::final ? "final" - : paymentComponents.specialCase == detail::PaymentSpecialCase::extra - ? "extra" - : "none") - << std::endl; + << paymentComponents.trackedManagementFeeDelta << ", " << [&]() -> char const* { + if (paymentComponents.specialCase == detail::PaymentSpecialCase::final) + return "final"; + if (paymentComponents.specialCase == detail::PaymentSpecialCase::extra) + return "extra"; + return "none"; + }() << std::endl; + } auto const totalDueAmount = STAmount{broker.asset, paymentComponents.trackedValueDelta + serviceFee}; @@ -1016,8 +1027,10 @@ protected: { auto const loanSle = env.le(loanKeylet); if (!BEAST_EXPECT(loanSle)) + { // No reason for this not to exist return; + } auto const current = constructRoundedLoanState(loanSle); auto const errors = nextTrueState - current; log << currencyLabel << " Loan balances: " @@ -1091,8 +1104,10 @@ protected: { auto const loanSle = env.le(loanKeylet); if (!BEAST_EXPECT(loanSle)) + { // No reason for this not to exist return; + } log << currencyLabel << " Total amounts paid: " << "\n\tTotal value: " << totalPaid.trackedValueDelta << " (initial: " << truncate(initialState.totalValue) @@ -1179,8 +1194,10 @@ protected: auto const [keylet, loanSequence] = [&]() { auto const brokerSle = env.le(keylet::loanbroker(broker.brokerID)); if (!BEAST_EXPECT(brokerSle)) + { // will be invalid return std::make_pair(keylet::loan(broker.brokerID), std::uint32_t(0)); + } // Broker has no loans BEAST_EXPECT(brokerSle->at(sfOwnerCount) == 0); @@ -1454,11 +1471,13 @@ protected: std::string getCurrencyLabel(Asset const& asset) { - return ( - asset.native() ? "XRP" - : asset.holds() ? "IOU" - : asset.holds() ? "MPT" - : "Unknown"); + if (asset.native()) + return "XRP"; + if (asset.holds()) + return "IOU"; + if (asset.holds()) + return "MPT"; + return "Unknown"; } /** Wrapper to run a series of lifecycle tests for a given asset and loan @@ -1788,8 +1807,10 @@ protected: auto const vaultPseudo = [&]() { auto const vaultSle = env.le(keylet::vault(brokerSle->at(sfVaultID))); if (!BEAST_EXPECT(vaultSle)) + { // This will be wrong, but the test has failed anyway. return lender; + } auto const vaultPseudo = Account("Vault pseudo-account", vaultSle->at(sfAccount)); return vaultPseudo; }(); @@ -1807,7 +1828,7 @@ protected: // XRP can't be frozen return std::make_tuple(empty, empty, empty, tesSUCCESS); } - else if (broker.asset.holds()) + if (broker.asset.holds()) { auto freeze = [&](Account const& holder) { env(trust(issuer, holder[iouCurrency](0), tfSetFreeze)); @@ -1821,16 +1842,14 @@ protected: }; return std::make_tuple(freeze, deepfreeze, unfreeze, tecFROZEN); } - else - { - auto freeze = [&](Account const& holder) { - mptt.set({.account = issuer, .holder = holder, .flags = tfMPTLock}); - }; - auto unfreeze = [&](Account const& holder) { - mptt.set({.account = issuer, .holder = holder, .flags = tfMPTUnlock}); - }; - return std::make_tuple(freeze, empty, unfreeze, tecLOCKED); - } + + auto freeze = [&](Account const& holder) { + mptt.set({.account = issuer, .holder = holder, .flags = tfMPTLock}); + }; + auto unfreeze = [&](Account const& holder) { + mptt.set({.account = issuer, .holder = holder, .flags = tfMPTUnlock}); + }; + return std::make_tuple(freeze, empty, unfreeze, tecLOCKED); }(); // Try freezing the accounts that can't be frozen @@ -2511,12 +2530,13 @@ protected: << ", " << paymentComponents.trackedPrincipalDelta << ", " << paymentComponents.trackedInterestPart() << ", " << paymentComponents.trackedManagementFeeDelta << ", " - << (paymentComponents.specialCase == detail::PaymentSpecialCase::final - ? "final" - : paymentComponents.specialCase == - detail::PaymentSpecialCase::extra - ? "extra" - : "none"); + << [&]() -> char const* { + if (paymentComponents.specialCase == detail::PaymentSpecialCase::final) + return "final"; + if (paymentComponents.specialCase == detail::PaymentSpecialCase::extra) + return "extra"; + return "none"; + }(); auto const totalDueAmount = STAmount{ broker.asset, paymentComponents.trackedValueDelta + serviceFee.number()}; @@ -2568,8 +2588,10 @@ protected: auto const borrowerBalanceBeforePayment = env.balance(borrower, broker.asset); if (canImpairLoan(env, broker, state)) + { // Making a payment will unimpair the loan env(manage(lender, loanKeylet.key, tfLoanImpair)); + } env.close(); @@ -4247,10 +4269,8 @@ protected: { return Account{"pseudo", brokerSle->at(sfAccount)}; } - else - { - return std::nullopt; - } + + return std::nullopt; }(); if (!pseudoBroker) return; @@ -6247,9 +6267,13 @@ protected: Vault vault(env); if (borrower == broker) + { env.fund(XRP(10'000), broker, issuer, depositor); + } else + { env.fund(XRP(10'000), broker, borrower, issuer, depositor); + } env.close(); auto const xrpFee = XRP(100); diff --git a/src/test/app/MPToken_test.cpp b/src/test/app/MPToken_test.cpp index 5a46331aa9..5a90a3a71e 100644 --- a/src/test/app/MPToken_test.cpp +++ b/src/test/app/MPToken_test.cpp @@ -1840,11 +1840,17 @@ class MPToken_test : public beast::unit_test::suite if (withAmount) jv[field.fieldName] = USD(10).value().getJson(JsonOptions::none); if (field == sfAsset) + { jv[jss::Asset] = to_json(mpt.get()); + } else if (field == sfAsset2) + { jv[jss::Asset2] = to_json(mpt.get()); + } else + { jv[field.fieldName] = mpt.getJson(JsonOptions::none); + } }; // All transactions with sfAmount, which don't support MPT. // Transactions with amount fields, which can't be MPT. diff --git a/src/test/app/NFTokenBurn_test.cpp b/src/test/app/NFTokenBurn_test.cpp index 8cd67bd72b..25f5a0f880 100644 --- a/src/test/app/NFTokenBurn_test.cpp +++ b/src/test/app/NFTokenBurn_test.cpp @@ -96,14 +96,18 @@ class NFTokenBurn_test : public beast::unit_test::suite else { if (tokenCount > 0) + { std::cout << "first: " << state[i][sfNFTokens.jsonName][0u].toStyledString() << std::endl; + } if (tokenCount > 1) + { std::cout << "last: " << state[i][sfNFTokens.jsonName][tokenCount - 1].toStyledString() << std::endl; + } } } } @@ -256,7 +260,7 @@ class NFTokenBurn_test : public beast::unit_test::suite std::uniform_int_distribution acctDist(0, 2); std::uniform_int_distribution mintDist(0, 1); - while (stats[0]->nfts.size() > 0 || stats[1]->nfts.size() > 0 || stats[2]->nfts.size() > 0) + while (!stats[0]->nfts.empty() || !stats[1]->nfts.empty() || !stats[2]->nfts.empty()) { // Pick an account to burn an nft. If there are no nfts left // pick again. @@ -273,14 +277,20 @@ 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 = owner.acct == becky.acct ? *(stats[acctDist(engine)]) - : mintDist(engine) ? alice - : minter; + AcctStat& burner = [&]() -> AcctStat& { + if (owner.acct == becky.acct) + return *(stats[acctDist(engine)]); + return mintDist(engine) ? alice : minter; + }(); if (owner.acct == burner.acct) + { env(token::burn(burner, nft)); + } else + { env(token::burn(burner, nft), token::owner(owner)); + } env.close(); // Every time we burn an nft, the number of nfts they hold should diff --git a/src/test/app/NFTokenDir_test.cpp b/src/test/app/NFTokenDir_test.cpp index 551b987204..73698f1f89 100644 --- a/src/test/app/NFTokenDir_test.cpp +++ b/src/test/app/NFTokenDir_test.cpp @@ -57,14 +57,18 @@ class NFTokenDir_test : public beast::unit_test::suite else { if (tokenCount > 0) + { std::cout << "first: " << state[i][sfNFTokens.jsonName][0u].toStyledString() << std::endl; + } if (tokenCount > 1) + { std::cout << "last: " << state[i][sfNFTokens.jsonName][tokenCount - 1].toStyledString() << std::endl; + } } } } diff --git a/src/test/app/NFToken_test.cpp b/src/test/app/NFToken_test.cpp index 95dfc60c41..d9010d5d6e 100644 --- a/src/test/app/NFToken_test.cpp +++ b/src/test/app/NFToken_test.cpp @@ -171,7 +171,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite int line) { auto oneCheck = [line, this](char const* type, std::uint32_t found, std::uint32_t exp) { if (found == exp) + { pass(); + } else { std::stringstream ss; @@ -269,7 +271,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite auto oneCheck = [this](char const* type, std::uint32_t found, std::uint32_t exp, int line) { if (found == exp) + { pass(); + } else { std::stringstream ss; @@ -2171,9 +2175,13 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite for (auto NumberSwitchOver : {true}) { if (NumberSwitchOver) + { env.enableFeature(fixUniversalNumber); + } else + { env.disableFeature(fixUniversalNumber); + } // An nft with a transfer fee of 1 basis point. uint256 const nftID = token::getNextID(env, alice, 0u, tfTransferable, 1); @@ -2347,7 +2355,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite auto check = [this](std::uint32_t taxon, uint256 const& nftID) { nft::Taxon const gotTaxon = nft::getTaxon(nftID); if (nft::toTaxon(taxon) == gotTaxon) + { pass(); + } else { std::stringstream ss; @@ -4791,7 +4801,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env(pay(secondarySeller, gw, env.balance(secondarySeller, gwXPB))); auto brokerDiff = gwXAU(5000) - env.balance(broker, gwXAU); if (brokerDiff > gwXAU(0)) + { env(pay(gw, broker, brokerDiff)); + } else if (brokerDiff < gwXAU(0)) { brokerDiff.negate(); @@ -6976,7 +6988,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite auto checkURI = [&accountNFTs, this](Account const& acct, char const* uri, int line) { auto const nfts = accountNFTs(acct); if (nfts.size() == 1) + { pass(); + } else { std::ostringstream text; @@ -6988,7 +7002,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite if (uri == nullptr) { if (!nfts[0u].isMember(sfURI.jsonName)) + { pass(); + } else { std::ostringstream text; @@ -6999,7 +7015,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite } if (nfts[0u][sfURI.jsonName] == strHex(std::string(uri))) + { pass(); + } else { std::ostringstream text; diff --git a/src/test/app/Offer_test.cpp b/src/test/app/Offer_test.cpp index bfda01f672..62edc844c7 100644 --- a/src/test/app/Offer_test.cpp +++ b/src/test/app/Offer_test.cpp @@ -1208,7 +1208,7 @@ public: { auto acctOffers = offersOnAccount(env, account_to_test); - BEAST_EXPECT(acctOffers.size() == 0); + BEAST_EXPECT(acctOffers.empty()); for (auto const& offerPtr : acctOffers) { auto const& offer = *offerPtr; @@ -1926,9 +1926,13 @@ public: { Env env{*this, features}; if (NumberSwitchOver) + { env.enableFeature(fixUniversalNumber); + } else + { env.disableFeature(fixUniversalNumber); + } auto const gw = Account{"gateway"}; auto const alice = Account{"alice"}; @@ -2281,7 +2285,7 @@ public: auto acctOffers = offersOnAccount(env, acct); BEAST_EXPECT(acctOffers.size() == t.offers); - if (acctOffers.size() && t.offers) + if (!acctOffers.empty() && t.offers) { auto const& acctOffer = *(acctOffers.front()); @@ -2592,7 +2596,7 @@ public: // In pre-flow code alice's offer is left empty in the ledger. auto const aliceOffers = offersOnAccount(env, alice); - if (aliceOffers.size() != 0) + if (!aliceOffers.empty()) { BEAST_EXPECT(aliceOffers.size() == 1); auto const& aliceOffer = *(aliceOffers.front()); @@ -2772,7 +2776,7 @@ public: if (t.offers) { auto const acctOffers = offersOnAccount(env, acct); - if (acctOffers.size() > 0) + if (!acctOffers.empty()) { BEAST_EXPECT(acctOffers.size() == 1); auto const& acctOffer = *(acctOffers.front()); @@ -2984,7 +2988,7 @@ public: env.require(balance(eve, XRP(18000))); auto const evesOffers = offersOnAccount(env, eve); BEAST_EXPECT(evesOffers.size() == 1); - if (evesOffers.size() != 0) + if (!evesOffers.empty()) { auto const& evesOffer = *(evesOffers.front()); BEAST_EXPECT(evesOffer[sfLedgerEntryType] == ltOFFER); @@ -3160,7 +3164,7 @@ public: // In pre-flow code ova's offer is left empty in the ledger. auto const ovasOffers = offersOnAccount(env, ova); - if (ovasOffers.size() != 0) + if (!ovasOffers.empty()) { BEAST_EXPECT(ovasOffers.size() == 1); auto const& ovasOffer = *(ovasOffers.front()); @@ -4593,8 +4597,10 @@ public: std::map> offers; forEachItem(*env.current(), alice, [&](std::shared_ptr const& sle) { if (sle->getType() == ltOFFER) + { offers.emplace( (*sle)[sfSequence], std::make_pair((*sle)[sfTakerPays], (*sle)[sfTakerGets])); + } }); // first offer @@ -4749,7 +4755,7 @@ public: // Verify that the third offer alice created was consumed. { auto offers = sortedOffersOnAccount(env, alice); - BEAST_EXPECT(offers.size() == 0); + BEAST_EXPECT(offers.empty()); } env.require(balance(alice, USD(0))); env.require(owners(alice, 1)); diff --git a/src/test/app/OversizeMeta_test.cpp b/src/test/app/OversizeMeta_test.cpp index d5e2948f5b..3831e45a78 100644 --- a/src/test/app/OversizeMeta_test.cpp +++ b/src/test/app/OversizeMeta_test.cpp @@ -123,7 +123,9 @@ public: len -= l2 + 1; } else + { len = l2; + } } return lo; } diff --git a/src/test/app/Path_test.cpp b/src/test/app/Path_test.cpp index 283abb330e..9315370809 100644 --- a/src/test/app/Path_test.cpp +++ b/src/test/app/Path_test.cpp @@ -1518,7 +1518,7 @@ public: } else { - BEAST_EXPECT(st.size() == 0); + BEAST_EXPECT(st.empty()); BEAST_EXPECT(equal(sa, XRP(0))); } }; diff --git a/src/test/app/PayChan_test.cpp b/src/test/app/PayChan_test.cpp index ba79eb037d..5322349797 100644 --- a/src/test/app/PayChan_test.cpp +++ b/src/test/app/PayChan_test.cpp @@ -1015,9 +1015,11 @@ struct PayChan_test : public beast::unit_test::suite BEAST_EXPECT(r[jss::result][jss::validated]); BEAST_EXPECT(chan1Str != chan2Str); for (auto const& c : {chan1Str, chan2Str}) + { BEAST_EXPECT( r[jss::result][jss::channels][0u][jss::channel_id] == c || r[jss::result][jss::channels][1u][jss::channel_id] == c); + } } } @@ -1249,9 +1251,11 @@ struct PayChan_test : public beast::unit_test::suite BEAST_EXPECT(r[jss::result][jss::validated]); BEAST_EXPECT(chan1Str != chan2Str); for (auto const& c : {chan1Str, chan2Str}) + { BEAST_EXPECT( r[jss::result][jss::channels][0u][jss::channel_id] == c || r[jss::result][jss::channels][1u][jss::channel_id] == c); + } } auto sliceToHex = [](Slice const& slice) { diff --git a/src/test/app/PayStrand_test.cpp b/src/test/app/PayStrand_test.cpp index 16e7a857ff..70444637bf 100644 --- a/src/test/app/PayStrand_test.cpp +++ b/src/test/app/PayStrand_test.cpp @@ -183,8 +183,10 @@ class ElementComboIter hasAny(std::initializer_list sb) const { for (auto const s : sb) + { if (has(s)) return true; + } return false; } @@ -194,8 +196,10 @@ class ElementComboIter size_t result = 0; for (auto const s : sb) + { if (has(s)) result++; + } return result; } @@ -275,13 +279,17 @@ public: return currencyF(); }(); if (!has(SB::boundary)) + { col.emplace_back(acc, cur, iss); + } else + { col.emplace_back( STPathElement::Type::typeBoundary, acc.value_or(AccountID{}), cur.value_or(Currency{}), iss.value_or(AccountID{})); + } } }; @@ -368,11 +376,17 @@ struct ExistingElementPool for (size_t id = 0; id < numCur; ++id) { if (id < 10) + { snprintf(buf, bufSize, "CC%zu", id); + } else if (id < 100) + { snprintf(buf, bufSize, "C%zu", id); + } else + { snprintf(buf, bufSize, "%zu", id); + } currencies.emplace_back(to_currency(buf)); currencyNames.emplace_back(buf); } @@ -407,8 +421,10 @@ struct ExistingElementPool std::vector ious; ious.reserve(numAct * numCur); for (auto const& a : accounts) + { for (auto const& cn : currencyNames) ious.emplace_back(a[cn]); + } // create offers from every currency to every other currency for (auto takerPays = ious.begin(), ie = ious.end(); takerPays != ie; ++takerPays) diff --git a/src/test/app/PermissionedDomains_test.cpp b/src/test/app/PermissionedDomains_test.cpp index d2a14ce82a..c4bbd80e74 100644 --- a/src/test/app/PermissionedDomains_test.cpp +++ b/src/test/app/PermissionedDomains_test.cpp @@ -199,9 +199,13 @@ class PermissionedDomains_test : public beast::unit_test::suite uint256 d; if (domain) + { d = *domain; + } else + { d = pdomain::getNewDomain(env.meta()); + } env.close(); auto objects = pdomain::getObjects(account, env); auto const fromObject = pdomain::credentialsFromJson(objects[d], human2Acc); @@ -228,9 +232,13 @@ class PermissionedDomains_test : public beast::unit_test::suite uint256 d; if (domain) + { d = *domain; + } else + { d = pdomain::getNewDomain(env.meta()); + } env.close(); auto objects = pdomain::getObjects(account, env); auto const fromObject = pdomain::credentialsFromJson(objects[d], human2Acc); @@ -479,7 +487,7 @@ class PermissionedDomains_test : public beast::unit_test::suite pdomain::Credentials credentials{{alice, "first credential"}}; env(pdomain::setTx(alice, credentials), ter(tecINSUFFICIENT_RESERVE)); BEAST_EXPECT(env.ownerCount(alice) == 0); - BEAST_EXPECT(pdomain::getObjects(alice, env).size() == 0); + BEAST_EXPECT(pdomain::getObjects(alice, env).empty()); env.close(); auto const baseFee = env.current()->fees().base.drops(); diff --git a/src/test/app/RCLValidations_test.cpp b/src/test/app/RCLValidations_test.cpp index 140ba9f1d7..a7941ea64f 100644 --- a/src/test/app/RCLValidations_test.cpp +++ b/src/test/app/RCLValidations_test.cpp @@ -112,9 +112,13 @@ class RCLValidations_test : public beast::unit_test::suite for (Seq s = a.seq(); s > 0; s--) { if (s >= a.minSeq()) + { BEAST_EXPECT(a[s] == history[s - 1]->header().hash); + } else + { BEAST_EXPECT(a[s] == ID{0}); + } } } diff --git a/src/test/app/ReducedOffer_test.cpp b/src/test/app/ReducedOffer_test.cpp index 737d73e462..d0cf1b5324 100644 --- a/src/test/app/ReducedOffer_test.cpp +++ b/src/test/app/ReducedOffer_test.cpp @@ -92,9 +92,11 @@ public: // alice's offer should be fully crossed and so gone from // the ledger. if (!BEAST_EXPECT(!offerInLedger(env, alice, aliceOfferSeq))) + { // If the in-ledger offer was not consumed then further // results are meaningless. return 1; + } // bob's offer should be in the ledger, but reduced in size. unsigned int badRate = 1; diff --git a/src/test/app/SHAMapStore_test.cpp b/src/test/app/SHAMapStore_test.cpp index 97a9a38e77..d7d3e281f4 100644 --- a/src/test/app/SHAMapStore_test.cpp +++ b/src/test/app/SHAMapStore_test.cpp @@ -190,7 +190,7 @@ public: ledgers.emplace(std::make_pair(i, env.rpc("ledger", std::to_string(i)))); BEAST_EXPECT( goodLedger(env, ledgers[i], std::to_string(i), true) && - getHash(ledgers[i]).length()); + !getHash(ledgers[i]).empty()); } ledgerCheck(env, deleteInterval + 1, 2); @@ -229,7 +229,7 @@ public: store.getLastRotated() == lastRotated || i == lastRotated + deleteInterval - 2); BEAST_EXPECT( goodLedger(env, ledgers[i], std::to_string(i), true) && - getHash(ledgers[i]).length()); + !getHash(ledgers[i]).empty()); } store.rendezvous(); diff --git a/src/test/app/SetTrust_test.cpp b/src/test/app/SetTrust_test.cpp index 06aebcd915..fdc73eed79 100644 --- a/src/test/app/SetTrust_test.cpp +++ b/src/test/app/SetTrust_test.cpp @@ -151,9 +151,13 @@ public: testFreeTrustlines(FeatureBitset features, bool thirdLineCreatesLE, bool createOnHighAcct) { if (thirdLineCreatesLE) + { testcase("Allow two free trustlines"); + } else + { testcase("Dynamic reserve for trustline"); + } using namespace jtx; Env env(*this, features); @@ -284,8 +288,10 @@ public: badFlag *= 2) { if (badFlag & tfTrustSetMask) + { env(trust(alice, gw["USD"](100), static_cast(badFlag)), ter(temINVALID_FLAG)); + } } // trust amount can't be XRP diff --git a/src/test/app/TheoreticalQuality_test.cpp b/src/test/app/TheoreticalQuality_test.cpp index e272f2aedb..b4f6f3697d 100644 --- a/src/test/app/TheoreticalQuality_test.cpp +++ b/src/test/app/TheoreticalQuality_test.cpp @@ -57,10 +57,15 @@ struct RippleCalcTestParams auto const currency = to_currency(pe[jss::currency].asString()); std::optional issuer; if (!isXRP(currency)) + { // NOLINTNEXTLINE(bugprone-unchecked-optional-access) issuer = *parseBase58(pe[jss::issuer].asString()); + } else + { + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) assert(isXRP(*parseBase58(pe[jss::issuer].asString()))); + } p.emplace_back(std::nullopt, currency, issuer); } else @@ -148,7 +153,7 @@ public: jtx::Env& env, jtx::Account const& acc, jtx::Account const& peer, - Currency const& currency) + Currency const& currency) const { using namespace jtx; IOU const iou{acc, currency}; diff --git a/src/test/app/Ticket_test.cpp b/src/test/app/Ticket_test.cpp index 760cce88be..35fc7ea979 100644 --- a/src/test/app/Ticket_test.cpp +++ b/src/test/app/Ticket_test.cpp @@ -286,11 +286,15 @@ class Ticket_test : public beast::unit_test::suite BEAST_EXPECT(prevTicketCount > 0); if (prevTicketCount == 1) + { BEAST_EXPECT(!finalFields.isMember(sfTicketCount.jsonName)); + } else + { BEAST_EXPECT( finalFields.isMember(sfTicketCount.jsonName) && finalFields[sfTicketCount.jsonName].asUInt() == prevTicketCount - 1); + } } } else if (node.isMember(sfDeletedNode.jsonName)) diff --git a/src/test/app/TrustAndBalance_test.cpp b/src/test/app/TrustAndBalance_test.cpp index 413ef6dd78..3a2aa8e7c9 100644 --- a/src/test/app/TrustAndBalance_test.cpp +++ b/src/test/app/TrustAndBalance_test.cpp @@ -343,12 +343,16 @@ class TrustAndBalance_test : public beast::unit_test::suite // alice pays amazon via multiple paths if (with_rate) + { env(pay(alice, amazon, gw["USD"](150)), sendmax(alice["USD"](200)), test::jtx::path(bob), test::jtx::path(carol)); + } else + { env(pay(alice, amazon, gw["USD"](150)), test::jtx::path(bob), test::jtx::path(carol)); + } if (with_rate) { diff --git a/src/test/app/TxQ_test.cpp b/src/test/app/TxQ_test.cpp index d183330aaf..59db7e0d5d 100644 --- a/src/test/app/TxQ_test.cpp +++ b/src/test/app/TxQ_test.cpp @@ -2757,14 +2757,18 @@ public: for (int i = 0; i < 5; ++i) { if (i == 2) + { envs( noop(alice), fee(baseFee * 100), seq(none), json(jss::LastLedgerSequence, lastLedgerSeq), ter(terQUEUED))(submitParams); + } else + { envs(noop(alice), fee(baseFee * 100), seq(none), ter(terQUEUED))(submitParams); + } } checkMetrics(*this, env, 5, std::nullopt, 7, 6); { diff --git a/src/test/app/ValidatorList_test.cpp b/src/test/app/ValidatorList_test.cpp index 679fad800f..32e899ad95 100644 --- a/src/test/app/ValidatorList_test.cpp +++ b/src/test/app/ValidatorList_test.cpp @@ -1045,9 +1045,13 @@ private: auto const valKey = randomNode(); cfgKeys.push_back(toBase58(TokenType::NodePublic, valKey)); if (cfgKeys.size() <= maxKeys - 5) + { activeValidatorsOuter.emplace(calcNodeID(valKey)); + } else + { unseenValidators.emplace(calcNodeID(valKey)); + } } BEAST_EXPECT(trustedKeysOuter->load({}, cfgKeys, cfgPublishersOuter)); @@ -1075,7 +1079,9 @@ private: BEAST_EXPECT(trustedKeysOuter->trusted(*valKey)); } else + { fail(); + } } changes = trustedKeysOuter->updateTrusted( @@ -1266,9 +1272,13 @@ private: cfgKeys.push_back(toBase58(TokenType::NodePublic, valKey)); expectedTrusted.emplace(calcNodeID(valKey)); if (cfgKeys.size() < std::ceil(n * 0.8f)) + { activeValidators.emplace(calcNodeID(valKey)); + } else if (cfgKeys.size() < std::ceil(n * 0.8f)) + { toBeSeen = calcNodeID(valKey); + } } BEAST_EXPECT(trustedKeys->load({}, cfgKeys, cfgPublishersOuter)); @@ -1462,9 +1472,13 @@ private: env.app().getHashRouter()); BEAST_EXPECT(changes.removed.empty()); if (cfgKeys.size() > 2) + { BEAST_EXPECT(changes.added == asNodeIDs({valKey})); + } else + { BEAST_EXPECT(changes.added == asNodeIDs({localKey, valKey})); + } BEAST_EXPECT(trustedKeys->quorum() == std::ceil(cfgKeys.size() * 0.8f)); @@ -1617,14 +1631,28 @@ private: auto const sequence = 1; using namespace std::chrono_literals; // Want to drop 1 sooner - NetClock::time_point const validUntil = env.timeKeeper().now() + - (i == 2 ? 120s - : i == 1 ? 60s - : 3600s); + std::chrono::seconds duration; + if (i == 2) + { + duration = 120s; + } + else if (i == 1) + { + duration = 60s; + } + else + { + duration = 3600s; + } + NetClock::time_point const validUntil = env.timeKeeper().now() + duration; if (i == 1) + { validUntil1 = validUntil; + } else if (i == 2) + { validUntil2 = validUntil; + } std::vector localKeys{locals[i].first, locals[i].second}; auto const blob = makeList(localKeys, sequence, validUntil.time_since_epoch().count()); @@ -1665,7 +1693,9 @@ private: added.insert(calcNodeID(val.masterPublic)); } else + { BEAST_EXPECT(!trustedKeys->trusted(val.masterPublic)); + } } BEAST_EXPECT(changes.added == added); BEAST_EXPECT(changes.removed.empty()); @@ -1689,7 +1719,9 @@ private: { auto const& val = valKeys[i]; if (i >= 2 && i < maxKeys - 4) + { BEAST_EXPECT(trustedKeys->trusted(val.masterPublic)); + } else { BEAST_EXPECT(!trustedKeys->trusted(val.masterPublic)); @@ -1717,9 +1749,13 @@ private: { auto const& val = valKeys[i]; if (i < maxKeys - 4) + { BEAST_EXPECT(trustedKeys->listed(val.masterPublic)); + } else + { BEAST_EXPECT(!trustedKeys->listed(val.masterPublic)); + } BEAST_EXPECT(!trustedKeys->trusted(val.masterPublic)); if (i >= 2 && i < maxKeys - 4) @@ -2020,7 +2056,7 @@ private: { for (auto& n : nUnl_temp) { - if (nUnl.find(n) == nUnl.end()) + if (!nUnl.contains(n)) return false; } validators->updateTrusted( @@ -2338,7 +2374,7 @@ private: 1, 8, maxSequence, version, manifest, blobInfos, messages), 0, 0); - BEAST_EXPECT(messages.size() == 0); + BEAST_EXPECT(messages.empty()); // Don't repeat the work if messages is populated, even though the // peerSequence provided indicates it should. Note that this @@ -2392,7 +2428,7 @@ private: 2, maxSequence * 2, maxSequence, version, manifest, blobInfos, messages), 0, 0); - BEAST_EXPECT(messages.size() == 0); + BEAST_EXPECT(messages.empty()); // Don't repeat the work if messages is populated, even though the // peerSequence provided indicates it should. Note that this @@ -2491,7 +2527,7 @@ private: PublicKey pubKey; std::pair signingKeys; std::string manifest; - NetClock::time_point expiry = {}; + NetClock::time_point expiry = {}; // NOLINT(readability-redundant-member-init) }; // Create ValidatorList with a set of countTotal publishers, of which @@ -2528,7 +2564,12 @@ private: pubSigningKeys.second, i < countRevoked ? revoked : 1)); publishers.push_back( - Publisher{i < countRevoked, publisherPublic, pubSigningKeys, manifest}); + Publisher{ + .revoked = i < countRevoked, + .pubKey = publisherPublic, + .signingKeys = pubSigningKeys, + .manifest = manifest, + }); } std::vector const emptyCfgKeys; @@ -2670,7 +2711,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); - BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == 0); + BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().empty()); hash_set removed; for (auto const& val : valKeys) @@ -2938,7 +2979,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); - BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == 0); + BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().empty()); hash_set removed; for (auto const& val : valKeys) @@ -3376,7 +3417,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); - BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == 0); + BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().empty()); hash_set removed; for (auto const& val : valKeys) @@ -3558,7 +3599,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); - BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == 0); + BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().empty()); hash_set removed; for (auto const& val : valKeys) diff --git a/src/test/app/ValidatorSite_test.cpp b/src/test/app/ValidatorSite_test.cpp index eaae4c278e..c47c93c426 100644 --- a/src/test/app/ValidatorSite_test.cpp +++ b/src/test/app/ValidatorSite_test.cpp @@ -225,8 +225,10 @@ private: Json::Value myStatus; for (auto const& vs : jv[jss::validator_sites]) + { if (vs[jss::uri].asString().find(u.uri) != std::string::npos) myStatus = vs; + } BEAST_EXPECTS( myStatus[jss::last_refresh_message].asString().empty() != u.cfg.failFetch, to_string(myStatus) + "\n" + sink.messages().str()); @@ -307,8 +309,10 @@ private: auto const jv = sites->getJson(); Json::Value myStatus; for (auto const& vs : jv[jss::validator_sites]) + { if (vs[jss::uri].asString().find(u.uri) != std::string::npos) myStatus = vs; + } BEAST_EXPECTS( myStatus[jss::last_refresh_message].asString().empty() != u.shouldFail, to_string(myStatus)); diff --git a/src/test/app/Vault_test.cpp b/src/test/app/Vault_test.cpp index 5a5292b06c..e62f7fee50 100644 --- a/src/test/app/Vault_test.cpp +++ b/src/test/app/Vault_test.cpp @@ -66,15 +66,23 @@ class Vault_test : public beast::unit_test::suite auto const vault = env.le(keylet); BEAST_EXPECT(vault != nullptr); if (!asset.integral()) + { BEAST_EXPECT(vault->at(sfScale) == 6); + } else + { BEAST_EXPECT(vault->at(sfScale) == 0); + } auto const shares = env.le(keylet::mptIssuance(vault->at(sfShareMPTID))); BEAST_EXPECT(shares != nullptr); if (!asset.integral()) + { BEAST_EXPECT(shares->at(sfAssetScale) == 6); + } else + { BEAST_EXPECT(shares->at(sfAssetScale) == 0); + } return {MPTIssue(vault->at(sfShareMPTID)), Account("vault", vault->at(sfAccount))}; }(); auto const shares = share.raw().get(); @@ -1330,11 +1338,17 @@ class Vault_test : public beast::unit_test::suite BEAST_EXPECT(asset1 <= toFund1 && asset2 <= toFund2); if (!asset1.native() && !asset2.native()) + { fund(env, gw, {alice, carol}, {toFund1, toFund2}, Fund::All); + } else if (asset1.native()) + { fund(env, gw, {alice, carol}, toFund1, {toFund2}, Fund::All); + } else if (asset2.native()) + { fund(env, gw, {alice, carol}, toFund2, {toFund1}, Fund::All); + } AMM ammAlice(env, alice, asset1, asset2, CreateArg{.log = false, .tfee = 0}); @@ -2276,7 +2290,9 @@ class Vault_test : public beast::unit_test::suite env(fset(issuer, asfDefaultRipple)); } else + { env.trust(asset(1000), charlie); + } env.close(); env(rate(issuer, args.transferRate)); env.close(); @@ -4605,18 +4621,23 @@ class Vault_test : public beast::unit_test::suite { testcase("VaultClawback (share) - " + prefix + " owner asset clawback fails"); auto [vault, vaultKeylet] = setupVault(asset, owner, depositor); + // when asset is XRP or owner is not issuer clawback fail + // when owner is issuer precision loss occurs as vault is + // empty + auto const expectedTer = [&]() { + if (asset.native()) + return ter(temMALFORMED); + if (asset.raw().getIssuer() != owner.id()) + return ter(tecNO_PERMISSION); + return ter(tecPRECISION_LOSS); + }(); env(vault.clawback({ .issuer = owner, .id = vaultKeylet.key, .holder = depositor, .amount = asset(100).value(), }), - // when asset is XRP or owner is not issuer clawback fail - // when owner is issuer precision loss occurs as vault is - // empty - asset.native() ? ter(temMALFORMED) - : asset.raw().getIssuer() != owner.id() ? ter(tecNO_PERMISSION) - : ter(tecPRECISION_LOSS)); + expectedTer); env.close(); } diff --git a/src/test/app/XChain_test.cpp b/src/test/app/XChain_test.cpp index 2265d9f33b..b90ff49a84 100644 --- a/src/test/app/XChain_test.cpp +++ b/src/test/app/XChain_test.cpp @@ -2142,14 +2142,22 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj TER const expectedTER = i < quorum ? tesSUCCESS : TER{tecXCHAIN_NO_CLAIM_ID}; if (i + 1 == quorum) + { scEnv.tx(att, ter(expectedTER)).close(); + } else + { scEnv.tx(att, ter(expectedTER)).close(); + } if (i + 1 < quorum) + { BEAST_EXPECT(dstStartBalance == scEnv.env_.balance(dst)); + } else + { BEAST_EXPECT(dstStartBalance + amt == scEnv.env_.balance(dst)); + } } BEAST_EXPECT(dstStartBalance + amt == scEnv.env_.balance(dst)); } @@ -2336,9 +2344,13 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj scEnv.tx(att, ter(expectedTER)).close(); if (i + 1 < xrp_b.quorum) + { BEAST_EXPECT(!scEnv.env_.le(ua)); + } else + { BEAST_EXPECT(scEnv.env_.le(ua)); + } } BEAST_EXPECT(scEnv.env_.le(ua)); } @@ -3917,8 +3929,10 @@ private: verify() const { for (auto const& [acct, state] : accounts) + { if (!state.verify(env, acct)) return false; + } return true; } @@ -4297,9 +4311,14 @@ private: break; case st_attesting: - sm_state = attest(time, rnd) - ? (xfer.with_claim == WithClaim::yes ? st_attested : st_completed) - : st_attesting; + if (attest(time, rnd)) + { + sm_state = xfer.with_claim == WithClaim::yes ? st_attested : st_completed; + } + else + { + sm_state = st_attesting; + } break; case st_attested: @@ -4366,9 +4385,13 @@ public: }; auto& [t, sm] = *it; if (t <= time && std::visit(vis, sm) == st_completed) + { it = sm_.erase(it); + } else + { ++it; + } } // send attestations @@ -4408,8 +4431,10 @@ public: std::vector result; result.reserve(num_acct); for (int i = 0; i < num_acct; ++i) + { result.emplace_back( "a"s + std::to_string(i), (i % 2) ? KeyType::ed25519 : KeyType::secp256k1); + } result.emplace_back("doorXRPLocking"); doorXRPLocking = result.back(); result.emplace_back("doorUSDLocking"); @@ -4458,8 +4483,10 @@ public: std::vector result; result.reserve(num_ua); for (int i = 0; i < num_ua; ++i) + { result.emplace_back( "ua"s + std::to_string(i), (i % 2) ? KeyType::ed25519 : KeyType::secp256k1); + } return result; }(); diff --git a/src/test/basics/Buffer_test.cpp b/src/test/basics/Buffer_test.cpp index 675228c42f..f5f626133f 100644 --- a/src/test/basics/Buffer_test.cpp +++ b/src/test/basics/Buffer_test.cpp @@ -12,7 +12,7 @@ struct Buffer_test : beast::unit_test::suite bool sane(Buffer const& b) const { - if (b.size() == 0) + if (b.empty()) return b.data() == nullptr; return b.data() != nullptr; @@ -241,13 +241,13 @@ struct Buffer_test : beast::unit_test::suite // Try to clear: x.clear(); BEAST_EXPECT(sane(x)); - BEAST_EXPECT(x.size() == 0); + BEAST_EXPECT(x.empty()); BEAST_EXPECT(x.data() == nullptr); // Try to clear again: x.clear(); BEAST_EXPECT(sane(x)); - BEAST_EXPECT(x.size() == 0); + BEAST_EXPECT(x.empty()); BEAST_EXPECT(x.data() == nullptr); }; diff --git a/src/test/basics/IntrusiveShared_test.cpp b/src/test/basics/IntrusiveShared_test.cpp index 817cbb8c1d..5a460a6044 100644 --- a/src/test/basics/IntrusiveShared_test.cpp +++ b/src/test/basics/IntrusiveShared_test.cpp @@ -144,7 +144,7 @@ public: } void - partialDestructor() + partialDestructor() const { using enum TrackedState; @@ -245,7 +245,7 @@ public: while (!weak.empty()) { weak.resize(weak.size() - 1); - if (weak.size()) + if (!weak.empty()) BEAST_EXPECT(TIBase::getState(id) == partiallyDeleted); } BEAST_EXPECT(TIBase::getState(id) == deleted); diff --git a/src/test/basics/Number_test.cpp b/src/test/basics/Number_test.cpp index eaf184ffe4..fb434a0182 100644 --- a/src/test/basics/Number_test.cpp +++ b/src/test/basics/Number_test.cpp @@ -199,9 +199,13 @@ public: } }; if (scale == MantissaRange::small) + { test(cSmall); + } else + { test(cLarge); + } { bool caught = false; try @@ -291,9 +295,13 @@ public: } }; if (scale == MantissaRange::small) + { test(cSmall); + } else + { test(cLarge); + } } void @@ -314,9 +322,13 @@ public: }; auto tests = [&](auto const& cSmall, auto const& cLarge) { if (scale == MantissaRange::small) + { test(cSmall); + } else + { test(cLarge); + } }; auto const maxMantissa = Number::maxMantissa(); @@ -622,9 +634,13 @@ public: auto const maxMantissa = Number::maxMantissa(); auto tests = [&](auto const& cSmall, auto const& cLarge) { if (scale == MantissaRange::small) + { test(cSmall); + } else + { test(cLarge); + } }; saveNumberRoundMode save{Number::setround(Number::to_nearest)}; { diff --git a/src/test/basics/PerfLog_test.cpp b/src/test/basics/PerfLog_test.cpp index 6e73b5f696..ce0109c53d 100644 --- a/src/test/basics/PerfLog_test.cpp +++ b/src/test/basics/PerfLog_test.cpp @@ -87,7 +87,10 @@ class PerfLog_test : public beast::unit_test::suite { perf::PerfLog::Setup const setup{ withFile == WithFile::no ? "" : logFile(), logInterval()}; - return perf::make_PerfLog(setup, app_, j_, [this]() { return signalStop(); }); + return perf::make_PerfLog(setup, app_, j_, [this]() { + signalStop(); + return; + }); } // Block until the log file has grown in size, indicating that the @@ -451,8 +454,10 @@ public: Json::Value parsedLastLine; Json::Reader().parse(lastLine, parsedLastLine); if (!BEAST_EXPECT(!RPC::contains_error(parsedLastLine))) + { // Avoid cascade of failures return; + } // Validate the contents of the last line of the log. validateFinalCounters(parsedLastLine[jss::counters]); @@ -770,8 +775,10 @@ public: Json::Value parsedLastLine; Json::Reader().parse(lastLine, parsedLastLine); if (!BEAST_EXPECT(!RPC::contains_error(parsedLastLine))) + { // Avoid cascade of failures return; + } // Validate the contents of the last line of the log. validateFinalCounters(parsedLastLine[jss::counters]); @@ -908,8 +915,10 @@ public: Json::Value parsedLastLine; Json::Reader().parse(lastLine, parsedLastLine); if (!BEAST_EXPECT(!RPC::contains_error(parsedLastLine))) + { // Avoid cascade of failures return; + } // Validate the contents of the last line of the log. verifyCounters(parsedLastLine[jss::counters], 2, 2, 24, 36); diff --git a/src/test/basics/XRPAmount_test.cpp b/src/test/basics/XRPAmount_test.cpp index 8b8d657123..58b15b5d2d 100644 --- a/src/test/basics/XRPAmount_test.cpp +++ b/src/test/basics/XRPAmount_test.cpp @@ -16,11 +16,17 @@ public: XRPAmount const x(i); if (i < 0) + { BEAST_EXPECT(x.signum() < 0); + } else if (i > 0) + { BEAST_EXPECT(x.signum() > 0); + } else + { BEAST_EXPECT(x.signum() == 0); + } } } diff --git a/src/test/beast/LexicalCast_test.cpp b/src/test/beast/LexicalCast_test.cpp index 0c84e075c6..5cfc73a6f6 100644 --- a/src/test/beast/LexicalCast_test.cpp +++ b/src/test/beast/LexicalCast_test.cpp @@ -220,7 +220,7 @@ public: testcase("entire range"); std::int32_t i = std::numeric_limits::min(); - std::string const empty(""); + std::string const empty; while (i <= std::numeric_limits::max()) { diff --git a/src/test/conditions/PreimageSha256_test.cpp b/src/test/conditions/PreimageSha256_test.cpp index 5c9ec5e552..973f714ba4 100644 --- a/src/test/conditions/PreimageSha256_test.cpp +++ b/src/test/conditions/PreimageSha256_test.cpp @@ -17,7 +17,7 @@ namespace cryptoconditions { class PreimageSha256_test : public beast::unit_test::suite { - inline Buffer + Buffer hexblob(std::string const& s) { auto blob = strUnHex(s); diff --git a/src/test/consensus/Consensus_test.cpp b/src/test/consensus/Consensus_test.cpp index 0d023f270d..a096b82365 100644 --- a/src/test/consensus/Consensus_test.cpp +++ b/src/test/consensus/Consensus_test.cpp @@ -157,7 +157,7 @@ public: BEAST_EXPECT(peer->prevLedgerID() == lcl.id()); BEAST_EXPECT(lcl.seq() == Ledger::Seq{1}); BEAST_EXPECT(lcl.txs().size() == 1); - BEAST_EXPECT(lcl.txs().find(Tx{1}) != lcl.txs().end()); + BEAST_EXPECT(lcl.txs().contains(Tx{1})); BEAST_EXPECT(peer->prevProposers == 0); } @@ -193,7 +193,7 @@ public: BEAST_EXPECT(peer->prevProposers == peers.size() - 1); // All transactions were accepted for (std::uint32_t i = 0; i < peers.size(); ++i) - BEAST_EXPECT(lcl.txs().find(Tx{i}) != lcl.txs().end()); + BEAST_EXPECT(lcl.txs().contains(Tx{i})); } } } @@ -244,12 +244,12 @@ public: BEAST_EXPECT(peer->prevProposers == network.size() - 1); BEAST_EXPECT(peer->prevRoundTime == network[0]->prevRoundTime); - BEAST_EXPECT(lcl.txs().find(Tx{0}) == lcl.txs().end()); + BEAST_EXPECT(not lcl.txs().contains(Tx{0})); for (std::uint32_t i = 2; i < network.size(); ++i) - BEAST_EXPECT(lcl.txs().find(Tx{i}) != lcl.txs().end()); + BEAST_EXPECT(lcl.txs().contains(Tx{i})); // Tx 0 didn't make it - BEAST_EXPECT(peer->openTxs.find(Tx{0}) != peer->openTxs.end()); + BEAST_EXPECT(peer->openTxs.contains(Tx{0})); } } } @@ -297,21 +297,25 @@ public: // Closed ledger has all but transaction 0,1 auto const& lcl = peer->lastClosedLedger; BEAST_EXPECT(lcl.seq() == Ledger::Seq{1}); - BEAST_EXPECT(lcl.txs().find(Tx{0}) == lcl.txs().end()); - BEAST_EXPECT(lcl.txs().find(Tx{1}) == lcl.txs().end()); + BEAST_EXPECT(not lcl.txs().contains(Tx{0})); + BEAST_EXPECT(not lcl.txs().contains(Tx{1})); for (std::uint32_t i = slow.size(); i < network.size(); ++i) - BEAST_EXPECT(lcl.txs().find(Tx{i}) != lcl.txs().end()); + BEAST_EXPECT(lcl.txs().contains(Tx{i})); // Tx 0-1 didn't make it - BEAST_EXPECT(peer->openTxs.find(Tx{0}) != peer->openTxs.end()); - BEAST_EXPECT(peer->openTxs.find(Tx{1}) != peer->openTxs.end()); + BEAST_EXPECT(peer->openTxs.contains(Tx{0})); + BEAST_EXPECT(peer->openTxs.contains(Tx{1})); } Peer const* slowPeer = slow[0]; if (isParticipant) + { BEAST_EXPECT(slowPeer->prevProposers == network.size() - 1); + } else + { BEAST_EXPECT(slowPeer->prevProposers == fast.size()); + } for (Peer* peer : fast) { @@ -726,7 +730,9 @@ public: // Since the overlapped nodes have a UNL that is the union of the // two cliques, the maximum sized UNL list is the number of peers if (overlap > 0.4 * numPeers) + { BEAST_EXPECT(sim.synchronized()); + } else { // Even if we do fork, there shouldn't be more than 3 ledgers @@ -1100,7 +1106,7 @@ public: BEAST_EXPECT(!proposingFalse.stalled(p, true, peersUnchanged, j, clog)); BEAST_EXPECT(!followingTrue.stalled(p, false, peersUnchanged, j, clog)); BEAST_EXPECT(!followingFalse.stalled(p, false, peersUnchanged, j, clog)); - BEAST_EXPECT(clog->str() == ""); + BEAST_EXPECT(clog->str().empty()); // I'm in the majority, my vote should not change BEAST_EXPECT(!proposingTrue.updateVote(5, true, p)); @@ -1118,7 +1124,7 @@ public: BEAST_EXPECT(!proposingFalse.stalled(p, true, peersUnchanged, j, clog)); BEAST_EXPECT(!followingTrue.stalled(p, false, peersUnchanged, j, clog)); BEAST_EXPECT(!followingFalse.stalled(p, false, peersUnchanged, j, clog)); - BEAST_EXPECT(clog->str() == ""); + BEAST_EXPECT(clog->str().empty()); // Right now, the vote is 51%. The requirement is about to jump to // 65% @@ -1212,7 +1218,7 @@ public: BEAST_EXPECT(!proposingFalse.stalled(p, true, peersUnchanged, j, clog)); BEAST_EXPECT(!followingTrue.stalled(p, false, peersUnchanged, j, clog)); BEAST_EXPECT(!followingFalse.stalled(p, false, peersUnchanged, j, clog)); - BEAST_EXPECT(clog->str() == ""); + BEAST_EXPECT(clog->str().empty()); // Threshold jumps to 95% BEAST_EXPECT(proposingTrue.updateVote(220, true, p)); @@ -1253,7 +1259,7 @@ public: BEAST_EXPECT(!proposingFalse.stalled(p, true, peersUnchanged, j, clog)); BEAST_EXPECT(!followingTrue.stalled(p, false, peersUnchanged, j, clog)); BEAST_EXPECT(!followingFalse.stalled(p, false, peersUnchanged, j, clog)); - BEAST_EXPECT(clog->str() == ""); + BEAST_EXPECT(clog->str().empty()); } auto expectStalled = [this, &clog]( @@ -1301,7 +1307,7 @@ public: // true vote has changed recently, so not stalled BEAST_EXPECT(!proposingTrue.stalled(p, true, 0, j, clog)); - BEAST_EXPECT(clog->str() == ""); + BEAST_EXPECT(clog->str().empty()); // remaining votes have been unchanged in so long that we only // need to hit the second round at 95% to be stalled, regardless // of peers @@ -1314,7 +1320,7 @@ public: // true vote has changed recently, so not stalled BEAST_EXPECT(!proposingTrue.stalled(p, true, peersUnchanged, j, clog)); - BEAST_EXPECTS(clog->str() == "", clog->str()); + BEAST_EXPECTS(clog->str().empty(), clog->str()); // remaining votes have been unchanged in so long that we only // need to hit the second round at 95% to be stalled, regardless // of peers @@ -1340,7 +1346,7 @@ public: // true vote changed 2 rounds ago, and peers are changing, so // not stalled BEAST_EXPECT(!proposingTrue.stalled(p, true, 0, j, clog)); - BEAST_EXPECTS(clog->str() == "", clog->str()); + BEAST_EXPECTS(clog->str().empty(), clog->str()); // still stalled BEAST_EXPECT(proposingFalse.stalled(p, true, 0, j, clog)); expectStalled(98, false, 11 + i, 0, 2, __LINE__); diff --git a/src/test/consensus/LedgerTiming_test.cpp b/src/test/consensus/LedgerTiming_test.cpp index 62902d6a28..945f6b4ff0 100644 --- a/src/test/consensus/LedgerTiming_test.cpp +++ b/src/test/consensus/LedgerTiming_test.cpp @@ -29,11 +29,17 @@ class LedgerTiming_test : public beast::unit_test::suite nextCloseResolution = getNextLedgerTimeResolution(closeResolution, previousAgree, ++round); if (nextCloseResolution < closeResolution) + { ++res.decrease; + } else if (nextCloseResolution > closeResolution) + { ++res.increase; + } else + { ++res.equal; + } std::swap(nextCloseResolution, closeResolution); } while (round < rounds); return res; diff --git a/src/test/consensus/LedgerTrie_test.cpp b/src/test/consensus/LedgerTrie_test.cpp index 175a8d7616..7fd8c71b64 100644 --- a/src/test/consensus/LedgerTrie_test.cpp +++ b/src/test/consensus/LedgerTrie_test.cpp @@ -669,7 +669,7 @@ class LedgerTrie_test : public beast::unit_test::suite for (std::uint32_t i = 0; i < iterations; ++i) { // pick a random ledger history - std::string curr = ""; + std::string curr; char depth = depthDist(gen); char offset = 0; for (char d = 0; d < depth; ++d) @@ -681,9 +681,13 @@ class LedgerTrie_test : public beast::unit_test::suite // 50-50 to add remove if (flip(gen) == 0) + { t.insert(h[curr]); + } else + { t.remove(h[curr]); + } if (!BEAST_EXPECT(t.checkInvariants())) return; } diff --git a/src/test/consensus/NegativeUNL_test.cpp b/src/test/consensus/NegativeUNL_test.cpp index b71fb77796..23f7610300 100644 --- a/src/test/consensus/NegativeUNL_test.cpp +++ b/src/test/consensus/NegativeUNL_test.cpp @@ -835,9 +835,13 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite for (auto const& [n, score] : *scoreTable) { if (n == myId) + { BEAST_EXPECT(score == 256); + } else + { BEAST_EXPECT(score == 0); + } } } @@ -1306,11 +1310,17 @@ class NegativeUNLVoteScoreTable_test : public beast::unit_test::suite [&](std::shared_ptr const& l, std::size_t idx) -> bool { std::size_t k = 0; if (idx < 2) + { k = 0; + } else if (idx < 4) + { k = 1; + } else + { k = 2; + } bool add_50 = scorePattern[sp][k] == 50 && l->seq() % 2 == 0; bool add_100 = scorePattern[sp][k] == 100; @@ -1333,9 +1343,11 @@ class NegativeUNLVoteScoreTable_test : public beast::unit_test::suite if (scorePattern[sp][k] == 50) return score == 256 / 2; if (scorePattern[sp][k] == 100) + { return score == 256; - else - return false; + } + + return false; }; for (; i < 2; ++i) { @@ -1753,9 +1765,11 @@ applyAndTestResult(jtx::Env& env, OpenView& view, STTx const& tx, bool pass) { auto const res = apply(env.app(), view, tx, ApplyFlags::tapNONE, env.journal); if (pass) + { return isTesSuccess(res.ter); - else - return res.ter == tefFAILURE || res.ter == temDISABLED; + } + + return res.ter == tefFAILURE || res.ter == temDISABLED; } bool @@ -1791,7 +1805,7 @@ VerifyPubKeyAndSeq( return false; nUnlLedgerSeq.erase(it); } - return nUnlLedgerSeq.size() == 0; + return nUnlLedgerSeq.empty(); } std::size_t diff --git a/src/test/consensus/Validations_test.cpp b/src/test/consensus/Validations_test.cpp index e3c9901398..cf4498bd52 100644 --- a/src/test/consensus/Validations_test.cpp +++ b/src/test/consensus/Validations_test.cpp @@ -942,9 +942,13 @@ class Validations_test : public beast::unit_test::suite BEAST_EXPECT( vals.getNodesAfter(this->genesisLedger, genesisLedger.id()) == trustedVals.size()); if (trustedVals.empty()) + { BEAST_EXPECT(vals.getPreferred(this->genesisLedger) == std::nullopt); + } else + { BEAST_EXPECT(vals.getPreferred(this->genesisLedger)->second == testID); + } BEAST_EXPECT(vals.getTrustedForLedger(testID, testSeq) == trustedVals); BEAST_EXPECT(vals.numTrustedForLedger(testID) == trustedVals.size()); }; diff --git a/src/test/core/ClosureCounter_test.cpp b/src/test/core/ClosureCounter_test.cpp index fc56d7f6c9..fe3f0a219f 100644 --- a/src/test/core/ClosureCounter_test.cpp +++ b/src/test/core/ClosureCounter_test.cpp @@ -221,7 +221,7 @@ class ClosureCounter_test : public beast::unit_test::suite BEAST_EXPECT(result.copies == 0); BEAST_EXPECT(result.moves == 1); BEAST_EXPECT(result.str == "rvalue abcdefghijklmnopqrstuvwxyz!"); - BEAST_EXPECT(strRValue.str.size() == 0); // NOLINT(bugprone-use-after-move) + BEAST_EXPECT(strRValue.str.empty()); // NOLINT(bugprone-use-after-move) } } diff --git a/src/test/core/Config_test.cpp b/src/test/core/Config_test.cpp index c71406cc07..e9f7354482 100644 --- a/src/test/core/Config_test.cpp +++ b/src/test/core/Config_test.cpp @@ -284,7 +284,7 @@ port_wss_admin expectException([&c] { c.legacy("server"); }); // not a single line // set a legacy value - BEAST_EXPECT(c.legacy("not_in_file") == ""); + BEAST_EXPECT(c.legacy("not_in_file").empty()); c.legacy("not_in_file", "new_value"); BEAST_EXPECT(c.legacy("not_in_file") == "new_value"); } @@ -434,7 +434,7 @@ port_wss_admin // load will not. Config c; c.loadFromString(""); - BEAST_EXPECT(c.legacy("database_path") == ""); + BEAST_EXPECT(c.legacy("database_path").empty()); } } { @@ -533,7 +533,7 @@ main error = e.what(); } - BEAST_EXPECT(error == ""); + BEAST_EXPECT(error.empty()); BEAST_EXPECT(c.NETWORK_ID == 0); try @@ -546,7 +546,7 @@ main error = e.what(); } - BEAST_EXPECT(error == ""); + BEAST_EXPECT(error.empty()); BEAST_EXPECT(c.NETWORK_ID == 0); try @@ -561,7 +561,7 @@ main error = e.what(); } - BEAST_EXPECT(error == ""); + BEAST_EXPECT(error.empty()); BEAST_EXPECT(c.NETWORK_ID == 255); try @@ -576,7 +576,7 @@ main error = e.what(); } - BEAST_EXPECT(error == ""); + BEAST_EXPECT(error.empty()); BEAST_EXPECT(c.NETWORK_ID == 10000); } @@ -1337,7 +1337,7 @@ r.ripple.com:51235 auto val_3 = get(s, "a_string"); BEAST_EXPECT(val_3 == "mystring"); auto val_4 = get(s, "not_a_key"); - BEAST_EXPECT(val_4 == ""); + BEAST_EXPECT(val_4.empty()); auto val_5 = get(s, "not_a_key", "default"); BEAST_EXPECT(val_5 == "default"); @@ -1429,7 +1429,7 @@ r.ripple.com:51235 {"months", 2592000, 1, false}, {"years", 31536000, 1, false}}; - std::string space = ""; + std::string space; for (auto& [unit, sec, val, shouldPass] : units) { Config c; @@ -1437,22 +1437,30 @@ r.ripple.com:51235 [amendment_majority_time] )xrpldConfig"); toLoad += std::to_string(val) + space + unit; - space = space == "" ? " " : ""; + space = space.empty() ? " " : ""; try { c.loadFromString(toLoad); if (shouldPass) + { BEAST_EXPECT(c.AMENDMENT_MAJORITY_TIME.count() == val * sec); + } else + { fail(); + } } catch (std::runtime_error&) { if (!shouldPass) + { pass(); + } else + { fail(); + } } } } diff --git a/src/test/csf/BasicNetwork_test.cpp b/src/test/csf/BasicNetwork_test.cpp index eaef805f33..eee16c2ce1 100644 --- a/src/test/csf/BasicNetwork_test.cpp +++ b/src/test/csf/BasicNetwork_test.cpp @@ -33,8 +33,10 @@ public: if (id == 0) { for (auto const link : net.links(this)) + { net.send( this, link.target, [&, to = link.target] { to->receive(net, this, 1); }); + } } else { @@ -51,9 +53,11 @@ public: if (m < 5) { for (auto const link : net.links(this)) + { net.send(this, link.target, [&, mm = m, to = link.target] { to->receive(net, this, mm); }); + } } } }; diff --git a/src/test/csf/impl/ledgers.cpp b/src/test/csf/impl/ledgers.cpp index 12d461a214..33e9b123c5 100644 --- a/src/test/csf/impl/ledgers.cpp +++ b/src/test/csf/impl/ledgers.cpp @@ -58,7 +58,9 @@ mismatch(Ledger const& a, Ledger const& b) count -= step + Seq{1}; } else + { count = step; + } } return start; } @@ -88,9 +90,13 @@ LedgerOracle::accept( next.closeTimeResolution = closeTimeResolution; next.closeTimeAgree = consensusCloseTime != NetClock::time_point{}; if (next.closeTimeAgree) + { next.closeTime = effCloseTime(consensusCloseTime, closeTimeResolution, parent.closeTime()); + } else + { next.closeTime = parent.closeTime() + 1s; + } next.parentCloseTime = parent.closeTime(); next.parentID = parent.id(); diff --git a/src/test/jtx/Env_test.cpp b/src/test/jtx/Env_test.cpp index bd1867adb3..bd40ac9a81 100644 --- a/src/test/jtx/Env_test.cpp +++ b/src/test/jtx/Env_test.cpp @@ -707,8 +707,10 @@ public: auto const neverSupportedFeat = [&]() -> std::optional { auto const n = supported.size(); for (size_t i = 0; i < n; ++i) + { if (!supported[i]) return bitsetIndexToFeature(i); + } return std::nullopt; }(); @@ -721,7 +723,7 @@ public: } auto hasFeature = [](Env& env, uint256 const& f) { - return (env.app().config().features.find(f) != env.app().config().features.end()); + return (env.app().config().features.contains(f)); }; { diff --git a/src/test/jtx/impl/AMM.cpp b/src/test/jtx/impl/AMM.cpp index e1f6137a10..6b2042efda 100644 --- a/src/test/jtx/impl/AMM.cpp +++ b/src/test/jtx/impl/AMM.cpp @@ -53,8 +53,6 @@ AMM::AMM( , log_(log) , doClose_(close) , lastPurchasePrice_(0) - , bidMin_() - , bidMax_() , msig_(ms) , fee_(fee) , ammAccount_(create(tfee, flags, seq, ter)) @@ -123,9 +121,13 @@ AMM::create( if (flags) jv[jss::Flags] = *flags; if (fee_ != 0) + { jv[sfFee] = std::to_string(fee_); + } else + { jv[jss::Fee] = std::to_string(env_.current()->fees().increment.drops()); + } submit(jv, seq, ter); if (!ter || env_.ter() == tesSUCCESS) @@ -218,6 +220,7 @@ IOUAmount AMM::getLPTokensBalance(std::optional const& account) const { if (account) + { return accountHolds( *env_.current(), *account, @@ -225,6 +228,7 @@ AMM::getLPTokensBalance(std::optional const& account) const FreezeHandling::fhZERO_IF_FROZEN, env_.journal) .iou(); + } if (auto const amm = env_.current()->read(keylet::amm(asset1_.issue(), asset2_.issue()))) return amm->getFieldAmount(sfLPTokenBalance).iou(); return IOUAmount{0}; @@ -442,15 +446,25 @@ AMM::deposit( if (!(jvFlags & tfDepositSubTx)) { if (tokens && !asset1In) + { jvFlags |= tfLPToken; + } else if (tokens && asset1In) + { jvFlags |= tfOneAssetLPToken; + } else if (asset1In && asset2In) + { jvFlags |= tfTwoAsset; + } else if (maxEP && asset1In) + { jvFlags |= tfLimitLPToken; + } else if (asset1In) + { jvFlags |= tfSingleAsset; + } } jv[jss::Flags] = jvFlags; return deposit(account, jv, assets, seq, ter); @@ -562,15 +576,25 @@ AMM::withdraw( if (!(jvFlags & tfWithdrawSubTx)) { if (tokens && !asset1Out) + { jvFlags |= tfLPToken; + } else if (asset1Out && asset2Out) + { jvFlags |= tfTwoAsset; + } else if (tokens && asset1Out) + { jvFlags |= tfOneAssetLPToken; + } else if (asset1Out && maxEP) + { jvFlags |= tfLimitLPToken; + } else if (asset1Out) + { jvFlags |= tfSingleAsset; + } } jv[jss::Flags] = jvFlags; return withdraw(account, jv, seq, assets, ter); @@ -615,7 +639,7 @@ AMM::vote( void AMM::vote(VoteArg const& arg) { - return vote(arg.account, arg.tfee, arg.flags, arg.seq, arg.assets, arg.err); + vote(arg.account, arg.tfee, arg.flags, arg.seq, arg.assets, arg.err); } Json::Value @@ -641,11 +665,15 @@ AMM::bid(BidArg const& arg) setTokens(jv, arg.assets); auto getBid = [&](auto const& bid) { if (std::holds_alternative(bid)) + { return STAmount{lptIssue_, std::get(bid)}; - else if (std::holds_alternative(bid)) + } + if (std::holds_alternative(bid)) + { return toSTAmount(std::get(bid), lptIssue_); - else - return std::get(bid); + } + + return std::get(bid); }; if (arg.bidMin) { @@ -659,7 +687,7 @@ AMM::bid(BidArg const& arg) saTokens.setJson(jv[jss::BidMax]); bidMax_ = saTokens.iou(); } - if (arg.authAccounts.size() > 0) + if (!arg.authAccounts.empty()) { Json::Value accounts(Json::arrayValue); for (auto const& account : arg.authAccounts) @@ -691,22 +719,38 @@ AMM::submit( if (msig_) { if (seq && ter) + { env_(jv, *msig_, *seq, *ter); + } else if (seq) + { env_(jv, *msig_, *seq); + } else if (ter) + { env_(jv, *msig_, *ter); + } else + { env_(jv, *msig_); + } } else if (seq && ter) + { env_(jv, *seq, *ter); + } else if (seq) + { env_(jv, *seq); + } else if (ter) + { env_(jv, *ter); + } else + { env_(jv); + } if (doClose_) env_.close(); } diff --git a/src/test/jtx/impl/AMMTest.cpp b/src/test/jtx/impl/AMMTest.cpp index eb39408fbd..ab8c1578a3 100644 --- a/src/test/jtx/impl/AMMTest.cpp +++ b/src/test/jtx/impl/AMMTest.cpp @@ -129,11 +129,17 @@ AMMTestBase::testAMM(std::function const& cb, TestAM BEAST_EXPECT(asset1 <= toFund1 && asset2 <= toFund2); if (!asset1.native() && !asset2.native()) + { fund(env, gw, {alice, carol}, {toFund1, toFund2}, Fund::All); + } else if (asset1.native()) + { fund(env, gw, {alice, carol}, toFund1, {toFund2}, Fund::All); + } else if (asset2.native()) + { fund(env, gw, {alice, carol}, toFund2, {toFund1}, Fund::All); + } AMM ammAlice( env, alice, asset1, asset2, CreateArg{.log = false, .tfee = arg.tfee, .err = arg.ter}); diff --git a/src/test/jtx/impl/Env.cpp b/src/test/jtx/impl/Env.cpp index 35531634f4..3217f67cbe 100644 --- a/src/test/jtx/impl/Env.cpp +++ b/src/test/jtx/impl/Env.cpp @@ -107,7 +107,9 @@ Env::close(NetClock::time_point closeTime, std::optionalgetFieldU64(sfOutstandingAmount), 0, true}; return {amount, lookup(issuer).name()}; } - else - { - // Holder balance - auto const sle = le(keylet::mptoken(id, account)); - if (!sle) - return {STAmount(mptIssue, 0), account.name()}; - STAmount const amount{mptIssue, sle->getFieldU64(sfMPTAmount)}; - return {amount, lookup(issuer).name()}; - } + // Holder balance + auto const sle = le(keylet::mptoken(id, account)); + if (!sle) + return {STAmount(mptIssue, 0), account.name()}; + + STAmount const amount{mptIssue, sle->getFieldU64(sfMPTAmount)}; + return {amount, lookup(issuer).name()}; } PrettyAmount @@ -336,10 +342,14 @@ Env::parseResult(Json::Value const& jr) parsed.rpcCode.emplace(rpcSUCCESS); } else + { error(parsed, result); + } } else + { error(parsed, jr); + } return parsed; } @@ -362,16 +372,14 @@ Env::submit(JTx const& jt, std::source_location const& loc) return jr; } - else - { - // Parsing failed or the JTx is - // otherwise missing the stx field. - parsedResult.ter = ter_ = temMALFORMED; - return Json::Value(); - } + // Parsing failed or the JTx is + // otherwise missing the stx field. + parsedResult.ter = ter_ = temMALFORMED; + + return Json::Value(); }(); - return postconditions(jt, parsedResult, jr, loc); + postconditions(jt, parsedResult, jr, loc); } void @@ -409,7 +417,7 @@ Env::sign_and_submit(JTx const& jt, Json::Value params, std::source_location con test.expect(parsedResult.ter, "ter uninitialized!"); ter_ = parsedResult.ter.value_or(telENV_RPC_FAILED); - return postconditions(jt, parsedResult, jr, loc); + postconditions(jt, parsedResult, jr, loc); } void @@ -532,9 +540,13 @@ Env::autofill_sig(JTx& jt) } auto const ar = le(account); if (ar && ar->isFieldPresent(sfRegularKey)) + { jtx::sign(jv, lookup(ar->getAccountID(sfRegularKey))); + } else + { jtx::sign(jv, account); + } } void diff --git a/src/test/jtx/impl/JSONRPCClient.cpp b/src/test/jtx/impl/JSONRPCClient.cpp index b635050984..6b60744aad 100644 --- a/src/test/jtx/impl/JSONRPCClient.cpp +++ b/src/test/jtx/impl/JSONRPCClient.cpp @@ -35,8 +35,10 @@ class JSONRPCClient : public AbstractClient continue; using namespace boost::asio::ip; if (pp.ip && pp.ip->is_unspecified()) + { *pp.ip = pp.ip->is_v6() ? address{address_v6::loopback()} : address{address_v4::loopback()}; + } if (!pp.port) Throw("Use fixConfigPorts with auto ports"); diff --git a/src/test/jtx/impl/Oracle.cpp b/src/test/jtx/impl/Oracle.cpp index 9c75b21973..8bc456cd4e 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), owner_{}, documentID_{} +Oracle::Oracle(Env& env, CreateArg const& arg, bool submit) : env_(env), documentID_{} { // LastUpdateTime is checked to be in range // {close-maxLastUpdateTimeDelta, close+maxLastUpdateTimeDelta}. @@ -38,11 +38,17 @@ Oracle::remove(RemoveArg const& arg) jv[jss::Account] = to_string(arg.owner.value_or(owner_)); toJson(jv[jss::OracleDocumentID], arg.documentID.value_or(documentID_)); if (Oracle::fee != 0) + { jv[jss::Fee] = std::to_string(Oracle::fee); + } else if (arg.fee != 0) + { jv[jss::Fee] = std::to_string(arg.fee); + } else + { jv[jss::Fee] = std::to_string(env_.current()->fees().increment.drops()); + } if (arg.flags != 0) jv[jss::Flags] = arg.flags; submit(jv, arg.msig, arg.seq, arg.err); @@ -58,22 +64,38 @@ Oracle::submit( if (msig) { if (seq && err) + { env_(jv, *msig, *seq, *err); + } else if (seq) + { env_(jv, *msig, *seq); + } else if (err) + { env_(jv, *msig, *err); + } else + { env_(jv, *msig); + } } else if (seq && err) + { env_(jv, *seq, *err); + } else if (seq) + { env_(jv, *seq); + } else if (err) + { env_(jv, *err); + } else + { env_(jv); + } env_.close(); } @@ -90,7 +112,7 @@ Oracle::expectPrice(DataSeries const& series) const if (auto const sle = env_.le(keylet::oracle(owner_, documentID_))) { auto const& leSeries = sle->getFieldArray(sfPriceDataSeries); - if (leSeries.size() == 0 || leSeries.size() != series.size()) + if (leSeries.empty() || leSeries.size() != series.size()) return false; for (auto const& data : series) { @@ -157,9 +179,13 @@ Oracle::aggregatePrice( if (jr.isObject()) { if (jr.isMember(jss::result) && jr[jss::result].isMember(jss::status)) + { return jr[jss::result]; - else if (jr.isMember(jss::error)) + } + if (jr.isMember(jss::error)) + { return jr; + } } return Json::nullValue; } @@ -177,9 +203,13 @@ Oracle::set(UpdateArg const& arg) jv[jss::OracleDocumentID] = documentID_; } else if (arg.documentID) + { toJson(jv[jss::OracleDocumentID], *arg.documentID); + } else + { jv[jss::OracleDocumentID] = documentID_; + } jv[jss::TransactionType] = jss::OracleSet; jv[jss::Account] = to_string(owner_); if (arg.assetClass) @@ -191,24 +221,36 @@ Oracle::set(UpdateArg const& arg) if (arg.flags != 0) jv[jss::Flags] = arg.flags; if (Oracle::fee != 0) + { jv[jss::Fee] = std::to_string(Oracle::fee); + } else if (arg.fee != 0) + { jv[jss::Fee] = std::to_string(arg.fee); + } else + { jv[jss::Fee] = std::to_string(env_.current()->fees().increment.drops()); + } // lastUpdateTime if provided is offset from testStartTime if (arg.lastUpdateTime) { if (std::holds_alternative(*arg.lastUpdateTime)) + { jv[jss::LastUpdateTime] = to_string(testStartTime.count() + std::get(*arg.lastUpdateTime)); + } else + { toJson(jv[jss::LastUpdateTime], *arg.lastUpdateTime); + } } else + { jv[jss::LastUpdateTime] = to_string( duration_cast(env_.current()->header().closeTime.time_since_epoch()).count() + epoch_offset.count()); + } Json::Value dataSeries(Json::arrayValue); auto assetToStr = [](std::string const& s) { // assume standard currency @@ -225,8 +267,10 @@ Oracle::set(UpdateArg const& arg) price[jss::BaseAsset] = assetToStr(std::get<0>(data)); price[jss::QuoteAsset] = assetToStr(std::get<1>(data)); if (std::get<2>(data)) + { price[jss::AssetPrice] = *std::get<2>(data); // NOLINT(bugprone-unchecked-optional-access) + } if (std::get<3>(data)) price[jss::Scale] = *std::get<3>(data); // NOLINT(bugprone-unchecked-optional-access) priceData[jss::PriceData] = price; @@ -265,9 +309,13 @@ Oracle::ledgerEntry( if (account) { if (std::holds_alternative(*account)) + { jvParams[jss::oracle][jss::account] = to_string(std::get(*account)); + } else + { jvParams[jss::oracle][jss::account] = std::get(*account); + } } if (documentID) toJson(jvParams[jss::oracle][jss::oracle_document_id], *documentID); @@ -275,9 +323,13 @@ Oracle::ledgerEntry( { std::uint32_t i = 0; if (boost::conversion::try_lexical_convert(*index, i)) + { jvParams[jss::oracle][jss::ledger_index] = i; + } else + { jvParams[jss::oracle][jss::ledger_index] = *index; + } } // Convert "%None%" to None auto str = to_string(jvParams); @@ -308,12 +360,18 @@ toJsonHex(Json::Value& jv, AnyValue const& v) if constexpr (std::is_same_v) { if (arg.starts_with("##")) + { jv = arg.substr(2); + } else + { jv = strHex(arg); + } } else + { jv = arg; + } }, v); } diff --git a/src/test/jtx/impl/WSClient.cpp b/src/test/jtx/impl/WSClient.cpp index a51357c9b5..ebe4721d60 100644 --- a/src/test/jtx/impl/WSClient.cpp +++ b/src/test/jtx/impl/WSClient.cpp @@ -49,8 +49,10 @@ class WSClientImpl : public WSClient continue; using namespace boost::asio::ip; if (pp.ip && pp.ip->is_unspecified()) + { *pp.ip = pp.ip->is_v6() ? address{address_v6::loopback()} : address{address_v4::loopback()}; + } if (!pp.port) Throw("Use fixConfigPorts with auto ports"); @@ -178,7 +180,9 @@ public: jp[jss::id] = 5; } else + { jp[jss::command] = cmd; + } auto const s = to_string(jp); ws_.write_some(true, buffer(s)); } diff --git a/src/test/jtx/impl/amount.cpp b/src/test/jtx/impl/amount.cpp index 4952334fe8..25fcb5c8f0 100644 --- a/src/test/jtx/impl/amount.cpp +++ b/src/test/jtx/impl/amount.cpp @@ -62,9 +62,13 @@ operator<<(std::ostream& os, PrettyAmount const& amount) if (n < c) { if (amount.value().negative()) + { os << "-" << n << " drops"; + } else + { os << n << " drops"; + } return os; } auto const d = double(n) / dropsPerXRP.drops(); diff --git a/src/test/jtx/impl/balance.cpp b/src/test/jtx/impl/balance.cpp index a136b19bdb..1c3cc0b3c3 100644 --- a/src/test/jtx/impl/balance.cpp +++ b/src/test/jtx/impl/balance.cpp @@ -66,7 +66,7 @@ doBalance( void balance::operator()(Env& env) const { - return std::visit( + std::visit( [&](auto const& issue) { doBalance(env, account_.id(), none_, value_, issue); }, value_.asset().value()); } diff --git a/src/test/jtx/impl/directory.cpp b/src/test/jtx/impl/directory.cpp index 7231389d1e..bf63bc523b 100644 --- a/src/test/jtx/impl/directory.cpp +++ b/src/test/jtx/impl/directory.cpp @@ -72,7 +72,9 @@ bumpLastPage( // Adjust root previous and previous node's next sleRoot->setFieldU64(sfIndexPrevious, newLastPage); if (prevIndex.value_or(0) == 0) + { sleRoot->setFieldU64(sfIndexNext, newLastPage); + } else { auto slePrev = sb.peek(keylet::page(directory, *prevIndex)); @@ -88,6 +90,7 @@ bumpLastPage( // Fixup page numbers in the objects referred by indexes if (adjust) + { for (auto const key : indexes) { if (!adjust(sb, key, newLastPage)) @@ -96,6 +99,7 @@ bumpLastPage( return false; } } + } sb.apply(view); return true; diff --git a/src/test/jtx/impl/fee.cpp b/src/test/jtx/impl/fee.cpp index 2b1ac6c398..fc05afcb46 100644 --- a/src/test/jtx/impl/fee.cpp +++ b/src/test/jtx/impl/fee.cpp @@ -14,9 +14,13 @@ fee::operator()(Env& env, JTx& jt) const jt.fill_fee = false; assert(!increment_ || !amount_); if (increment_) + { jt[sfFee] = STAmount(env.current()->fees().increment).getJson(); + } else if (amount_) + { jt[sfFee] = amount_->getJson(JsonOptions::none); + } } } // namespace jtx diff --git a/src/test/jtx/impl/flags.cpp b/src/test/jtx/impl/flags.cpp index 11e7831f55..aee01a107e 100644 --- a/src/test/jtx/impl/flags.cpp +++ b/src/test/jtx/impl/flags.cpp @@ -24,11 +24,17 @@ flags::operator()(Env& env) const { auto const sle = env.le(account_); if (!sle) + { env.test.fail(); + } else if (sle->isFieldPresent(sfFlags)) + { env.test.expect((sle->getFieldU32(sfFlags) & mask_) == mask_); + } else + { env.test.expect(mask_ == 0); + } } void @@ -36,11 +42,17 @@ nflags::operator()(Env& env) const { auto const sle = env.le(account_); if (!sle) + { env.test.fail(); + } else if (sle->isFieldPresent(sfFlags)) + { env.test.expect((sle->getFieldU32(sfFlags) & mask_) == 0); + } else + { env.test.pass(); + } } } // namespace jtx diff --git a/src/test/jtx/impl/mpt.cpp b/src/test/jtx/impl/mpt.cpp index c1cde76896..b6b08734c7 100644 --- a/src/test/jtx/impl/mpt.cpp +++ b/src/test/jtx/impl/mpt.cpp @@ -77,12 +77,14 @@ static MPTCreate makeMPTCreate(MPTInitDef const& arg) { if (arg.pay) + { return { .maxAmt = arg.maxAmt, .transferFee = arg.transferFee, .pay = {{arg.holders, *arg.pay}}, .flags = arg.flags, .authHolder = arg.authHolder}; + } return { .maxAmt = arg.maxAmt, .transferFee = arg.transferFee, @@ -174,16 +176,24 @@ MPTTester::create(MPTCreate const& arg) if (arg.authorize) { if (arg.authorize->empty()) + { authAndPay(holders_, [](auto const& it) { return it.second; }); + } else + { authAndPay(*arg.authorize, [](auto const& it) { return it; }); + } } else if (arg.pay) { if (arg.pay->first.empty()) + { authAndPay(holders_, [](auto const& it) { return it.second; }); + } else + { authAndPay(arg.pay->first, [](auto const& it) { return it; }); + } } } } @@ -253,10 +263,14 @@ MPTTester::authorize(MPTAuthorize const& arg) auto const flags = getFlags(arg.holder); // issuer un-authorizes the holder if (arg.flags.value_or(0) == tfMPTUnauthorize) + { env_.require(mptflags(*this, flags, arg.holder)); - // issuer authorizes the holder + // issuer authorizes the holder + } else + { env_.require(mptflags(*this, flags | lsfMPTAuthorized, arg.holder)); + } } // Holder authorizes else if (arg.flags.value_or(0) != tfMPTUnauthorize) @@ -315,9 +329,13 @@ MPTTester::setJV(MPTSet const& arg) std::visit( [&jv](T const& holder) { if constexpr (std::is_same_v) + { jv[sfHolder] = holder.human(); + } else if constexpr (std::is_same_v) + { jv[sfHolder] = toBase58(holder); + } }, *arg.holder); } @@ -360,42 +378,70 @@ MPTTester::set(MPTSet const& arg) if (arg.flags) { if (*arg.flags & tfMPTLock) + { flags |= lsfMPTLocked; + } else if (*arg.flags & tfMPTUnlock) + { flags &= ~lsfMPTLocked; + } } if (arg.mutableFlags) { if (*arg.mutableFlags & tmfMPTSetCanLock) + { flags |= lsfMPTCanLock; + } else if (*arg.mutableFlags & tmfMPTClearCanLock) + { flags &= ~lsfMPTCanLock; + } if (*arg.mutableFlags & tmfMPTSetRequireAuth) + { flags |= lsfMPTRequireAuth; + } else if (*arg.mutableFlags & tmfMPTClearRequireAuth) + { flags &= ~lsfMPTRequireAuth; + } if (*arg.mutableFlags & tmfMPTSetCanEscrow) + { flags |= lsfMPTCanEscrow; + } else if (*arg.mutableFlags & tmfMPTClearCanEscrow) + { flags &= ~lsfMPTCanEscrow; + } if (*arg.mutableFlags & tmfMPTSetCanClawback) + { flags |= lsfMPTCanClawback; + } else if (*arg.mutableFlags & tmfMPTClearCanClawback) + { flags &= ~lsfMPTCanClawback; + } if (*arg.mutableFlags & tmfMPTSetCanTrade) + { flags |= lsfMPTCanTrade; + } else if (*arg.mutableFlags & tmfMPTClearCanTrade) + { flags &= ~lsfMPTCanTrade; + } if (*arg.mutableFlags & tmfMPTSetCanTransfer) + { flags |= lsfMPTCanTransfer; + } else if (*arg.mutableFlags & tmfMPTClearCanTransfer) + { flags &= ~lsfMPTCanTransfer; + } } } env_.require(mptflags(*this, flags, holder)); @@ -498,12 +544,16 @@ MPTTester::pay( auto const outstandingAmt = getBalance(issuer_); if (credentials) + { env_( jtx::pay(src, dest, mpt(amount)), ter(err.value_or(tesSUCCESS)), credentials::ids(*credentials)); + } else + { env_(jtx::pay(src, dest, mpt(amount)), ter(err.value_or(tesSUCCESS))); + } if (!isTesSuccess(env_.ter())) amount = 0; diff --git a/src/test/jtx/impl/multisign.cpp b/src/test/jtx/impl/multisign.cpp index 54bde3ebb9..ae39382824 100644 --- a/src/test/jtx/impl/multisign.cpp +++ b/src/test/jtx/impl/multisign.cpp @@ -53,9 +53,13 @@ msig::operator()(Env& env, JTx& jt) const // The signing pub key is only required at the top level. if (!subField) + { sigObject[sfSigningPubKey] = ""; + } else if (sigObject.isNull()) + { sigObject = Json::Value(Json::objectValue); + } std::optional st; try { @@ -80,9 +84,13 @@ msig::operator()(Env& env, JTx& jt) const } }; if (!subField) + { jt.mainSigners.emplace_back(callback); + } else + { jt.postSigners.emplace_back(callback); + } } } // namespace jtx diff --git a/src/test/jtx/impl/sig.cpp b/src/test/jtx/impl/sig.cpp index 3ea7f669a7..850c5af781 100644 --- a/src/test/jtx/impl/sig.cpp +++ b/src/test/jtx/impl/sig.cpp @@ -23,9 +23,13 @@ sig::operator()(Env&, JTx& jt) const jtx::sign(jtx.jv, account, sigObject); }; if (!subField_) + { jt.mainSigners.emplace_back(callback); + } else + { jt.postSigners.emplace_back(callback); + } } } diff --git a/src/test/jtx/impl/vault.cpp b/src/test/jtx/impl/vault.cpp index 90250aece0..49c0dddaec 100644 --- a/src/test/jtx/impl/vault.cpp +++ b/src/test/jtx/impl/vault.cpp @@ -12,7 +12,7 @@ namespace test { namespace jtx { std::tuple -Vault::create(CreateArgs const& args) +Vault::create(CreateArgs const& args) const { auto keylet = keylet::vault(args.owner.id(), env.seq(args.owner)); Json::Value jv; diff --git a/src/test/jtx/impl/xchain_bridge.cpp b/src/test/jtx/impl/xchain_bridge.cpp index dfd7f0ba96..c2617f5073 100644 --- a/src/test/jtx/impl/xchain_bridge.cpp +++ b/src/test/jtx/impl/xchain_bridge.cpp @@ -286,6 +286,7 @@ claim_attestations( JValueVec vec; vec.reserve(numAtts); for (auto i = fromIdx; i < fromIdx + numAtts; ++i) + { vec.emplace_back(claim_attestation( submittingAccount, jvBridge, @@ -296,6 +297,7 @@ claim_attestations( claimID, dst, signers[i])); + } return vec; } @@ -319,6 +321,7 @@ create_account_attestations( JValueVec vec; vec.reserve(numAtts); for (auto i = fromIdx; i < fromIdx + numAtts; ++i) + { vec.emplace_back(create_account_attestation( submittingAccount, jvBridge, @@ -330,6 +333,7 @@ create_account_attestations( createCount, dst, signers[i])); + } return vec; } diff --git a/src/test/jtx/vault.h b/src/test/jtx/vault.h index 65a5706354..43f975323a 100644 --- a/src/test/jtx/vault.h +++ b/src/test/jtx/vault.h @@ -30,7 +30,7 @@ struct Vault /** Return a VaultCreate transaction and the Vault's expected keylet. */ std::tuple - create(CreateArgs const& args); + create(CreateArgs const& args) const; struct SetArgs { diff --git a/src/test/ledger/BookDirs_test.cpp b/src/test/ledger/BookDirs_test.cpp index 50f1bb46ba..d7841fe502 100644 --- a/src/test/ledger/BookDirs_test.cpp +++ b/src/test/ledger/BookDirs_test.cpp @@ -56,8 +56,10 @@ struct BookDirs_test : public beast::unit_test::suite { auto AUD = gw["AUD"]; for (auto i = 1, j = 3; i <= 3; ++i, --j) + { for (auto k = 0; k < 80; ++k) env(offer("alice", AUD(i), XRP(j))); + } auto d = BookDirs(*env.current(), Book(AUD.issue(), xrpIssue(), std::nullopt)); BEAST_EXPECT(std::distance(d.begin(), d.end()) == 240); diff --git a/src/test/ledger/Directory_test.cpp b/src/test/ledger/Directory_test.cpp index 8e7ba38c53..ec76b67e9c 100644 --- a/src/test/ledger/Directory_test.cpp +++ b/src/test/ledger/Directory_test.cpp @@ -46,14 +46,22 @@ struct Directory_test : public beast::unit_test::suite p->setFieldV256(sfIndexes, STVector256{}); if (i + 1 == n) + { p->setFieldU64(sfIndexNext, 0); + } else + { p->setFieldU64(sfIndexNext, i + 1); + } if (i == 0) + { p->setFieldU64(sfIndexPrevious, n - 1); + } else + { p->setFieldU64(sfIndexPrevious, i - 1); + } sb.insert(p); } @@ -254,8 +262,10 @@ struct Directory_test : public beast::unit_test::suite // Fill up three pages of offers for (int i = 0; i < 3; ++i) + { for (int j = 0; j < dirNodeMaxEntries; ++j) env(offer(alice, XRP(1), USD(1))); + } env.close(); // remove all the offers. Remove the middle page last diff --git a/src/test/nodestore/Timing_test.cpp b/src/test/nodestore/Timing_test.cpp index e334283052..d5c89dbcc9 100644 --- a/src/test/nodestore/Timing_test.cpp +++ b/src/test/nodestore/Timing_test.cpp @@ -13,6 +13,7 @@ #include +#include #include #include #include @@ -621,8 +622,9 @@ public: using std::setw; int w = 8; for (auto const& test : tests) - if (w < test.first.size()) - w = test.first.size(); + { + w = std::max::size_type>(w, test.first.size()); + } log << threads << " Thread" << (threads > 1 ? "s" : "") << ", " << default_items << " Objects" << std::endl; { @@ -649,8 +651,10 @@ public: std::stringstream ss; ss << std::left << setw(10) << get(config, "type", std::string()) << std::right; for (auto const& test : tests) + { ss << " " << setw(w) << to_string(do_test(test.second, config, params, journal)); + } ss << " " << to_string(config); log << ss.str() << std::endl; } @@ -690,10 +694,16 @@ public: std::vector config_strings; boost::split(config_strings, args, boost::algorithm::is_any_of(";")); for (auto iter = config_strings.begin(); iter != config_strings.end();) + { if (iter->empty()) + { iter = config_strings.erase(iter); + } else + { ++iter; + } + } do_tests(1, tests, config_strings); do_tests(4, tests, config_strings); diff --git a/src/test/nodestore/import_test.cpp b/src/test/nodestore/import_test.cpp index 2177646eaa..e5f281486b 100644 --- a/src/test/nodestore/import_test.cpp +++ b/src/test/nodestore/import_test.cpp @@ -367,8 +367,10 @@ public: for (it->SeekToFirst(); it->Valid(); it->Next()) { if (it->key().size() != 32) + { Throw( "Unexpected key size " + std::to_string(it->key().size())); + } void const* const key = it->key().data(); void const* const data = it->value().data(); auto const size = it->value().size(); diff --git a/src/test/overlay/compression_test.cpp b/src/test/overlay/compression_test.cpp index 3c787a4c72..f784a91350 100644 --- a/src/test/overlay/compression_test.cpp +++ b/src/test/overlay/compression_test.cpp @@ -176,7 +176,7 @@ public: return std::string{reinterpret_cast(blob->data()), blob->size()}; }; - std::string usdTxBlob = ""; + std::string usdTxBlob; auto wsc = makeWSClient(env.app().config()); { Json::Value requestUSD; diff --git a/src/test/overlay/reduce_relay_test.cpp b/src/test/overlay/reduce_relay_test.cpp index 7e105e9f85..8e50415aa9 100644 --- a/src/test/overlay/reduce_relay_test.cpp +++ b/src/test/overlay/reduce_relay_test.cpp @@ -14,6 +14,7 @@ #include +#include #include #include #include @@ -404,7 +405,7 @@ public: } std::uint16_t - id() + id() const { return id_; } @@ -482,9 +483,13 @@ public: auto validator = squelch.validatorpubkey(); PublicKey key(Slice(validator.data(), validator.size())); if (squelch.squelch()) + { squelch_.addSquelch(key, std::chrono::seconds{squelch.squelchduration()}); + } else + { squelch_.removeSquelch(key); + } } private: @@ -601,8 +606,7 @@ public: for (auto& [id, _] : peers_) { (void)_; - if (id > maxId) - maxId = id; + maxId = std::max(id, maxId); } deletePeer(maxId, false); @@ -626,7 +630,7 @@ public: isSelected(PublicKey const& validator, Peer::id_t peer) { auto selected = slots_.getSelected(validator); - return selected.find(peer) != selected.end(); + return selected.contains(peer); } id_t @@ -752,9 +756,13 @@ public: validators_.begin(), validators_.end(), [&](auto& v) { return v.id() == validatorId; }); assert(it != validators_.end()); if (enable) + { it->linkUp(peer); + } else + { it->linkDown(peer); + } } void @@ -940,9 +948,11 @@ protected: for (auto s : selected) str << s << " "; if (log) + { std::cout << (double)reduce_relay::epoch(now).count() / 1000. << " random, squelched, validator: " << validator.id() << " peers: " << str.str() << std::endl; + } auto countingState = network_.overlay().isCountingState(validator); BEAST_EXPECT( countingState == false && @@ -968,7 +978,9 @@ protected: network_.overlay().isSelected(validator, link.peerId()); } else + { events[event].isSelected_ = network_.isSelected(link.peerId()); + } }; auto r = rand_int(0, 1000); if (r == (int)EventType::LinkDown || r == (int)EventType::PeerDisconnected) @@ -1025,7 +1037,7 @@ protected: d > milliseconds(reduce_relay::IDLED).count() && network_.overlay().inState( *event.key_, reduce_relay::PeerState::Squelched) > 0 && - peers.find(event.peer_) != peers.end(); + peers.contains(event.peer_); } network_.overlay().deleteIdlePeers([&](PublicKey const& v, PeerWPtr const& ptr) { event.handled_ = true; @@ -1060,9 +1072,11 @@ protected: // All Peer Disconnect events must be handled BEAST_EXPECT(disconnected.cnt_ == disconnected.handledCnt_); if (log) + { std::cout << "link down count: " << down.cnt_ << "/" << down.handledCnt_ << " peer disconnect count: " << disconnected.cnt_ << "/" << disconnected.handledCnt_; + } } bool @@ -1455,8 +1469,7 @@ vp_base_squelch_max_selected_peers=2 void squelch(PublicKey const&, Peer::id_t, std::uint32_t duration) const override { - if (duration > maxDuration_) - maxDuration_ = duration; + maxDuration_ = std::max(duration, maxDuration_); } void unsquelch(PublicKey const&, Peer::id_t) const override @@ -1519,18 +1532,22 @@ vp_base_squelch_max_selected_peers=2 handler.maxDuration_ <= MAX_UNSQUELCH_EXPIRE_PEERS.count()); using namespace beast::unit_test::detail; if (handler.maxDuration_ <= MAX_UNSQUELCH_EXPIRE_DEFAULT.count()) + { log << make_reason("warning: squelch duration is low", __FILE__, __LINE__) << std::endl << std::flush; + } // more than 400 is still less than MAX_UNSQUELCH_EXPIRE_PEERS run(400); BEAST_EXPECT( handler.maxDuration_ >= MIN_UNSQUELCH_EXPIRE.count() && handler.maxDuration_ <= MAX_UNSQUELCH_EXPIRE_PEERS.count()); if (handler.maxDuration_ <= MAX_UNSQUELCH_EXPIRE_DEFAULT.count()) + { log << make_reason("warning: squelch duration is low", __FILE__, __LINE__) << std::endl << std::flush; + } }); } diff --git a/src/test/overlay/short_read_test.cpp b/src/test/overlay/short_read_test.cpp index bff0bd82cb..d96f67c8a1 100644 --- a/src/test/overlay/short_read_test.cpp +++ b/src/test/overlay/short_read_test.cpp @@ -180,7 +180,10 @@ private: close() override { if (!strand_.running_in_this_thread()) - return post(strand_, std::bind(&Acceptor::close, shared_from_this())); + { + post(strand_, std::bind(&Acceptor::close, shared_from_this())); + return; + } acceptor_.close(); } @@ -210,7 +213,10 @@ private: on_accept(error_code ec) { if (ec) - return fail("accept", ec); + { + fail("accept", ec); + return; + } auto const p = std::make_shared(server_, std::move(socket_)); server_.add(p); p->run(); @@ -248,7 +254,10 @@ private: close() override { if (!strand_.running_in_this_thread()) - return post(strand_, std::bind(&Connection::close, shared_from_this())); + { + post(strand_, std::bind(&Connection::close, shared_from_this())); + return; + } if (socket_.is_open()) { socket_.close(); @@ -289,7 +298,10 @@ private: if (ec == boost::asio::error::operation_aborted) return; if (ec) - return fail("timer", ec); + { + fail("timer", ec); + return; + } test_.log << "[server] timeout" << std::endl; socket_.close(); } @@ -298,7 +310,10 @@ private: on_handshake(error_code ec) { if (ec) - return fail("handshake", ec); + { + fail("handshake", ec); + return; + } #if 1 boost::asio::async_read_until( stream_, @@ -322,13 +337,17 @@ private: if (ec == boost::asio::error::eof) { server_.test_.log << "[server] read: EOF" << std::endl; - return stream_.async_shutdown(bind_executor( + stream_.async_shutdown(bind_executor( strand_, std::bind( &Connection::on_shutdown, shared_from_this(), std::placeholders::_1))); + return; } if (ec) - return fail("read", ec); + { + fail("read", ec); + return; + } buf_.commit(bytes_transferred); buf_.consume(bytes_transferred); @@ -350,7 +369,10 @@ private: { buf_.consume(bytes_transferred); if (ec) - return fail("write", ec); + { + fail("write", ec); + return; + } stream_.async_shutdown(bind_executor( strand_, std::bind( @@ -361,7 +383,10 @@ private: on_shutdown(error_code ec) { if (ec) - return fail("shutdown", ec); + { + fail("shutdown", ec); + return; + } socket_.close(); timer_.cancel(); } @@ -422,7 +447,10 @@ private: close() override { if (!strand_.running_in_this_thread()) - return post(strand_, std::bind(&Connection::close, shared_from_this())); + { + post(strand_, std::bind(&Connection::close, shared_from_this())); + return; + } if (socket_.is_open()) { socket_.close(); @@ -463,7 +491,10 @@ private: if (ec == boost::asio::error::operation_aborted) return; if (ec) - return fail("timer", ec); + { + fail("timer", ec); + return; + } test_.log << "[client] timeout"; socket_.close(); } @@ -472,7 +503,10 @@ private: on_connect(error_code ec) { if (ec) - return fail("connect", ec); + { + fail("connect", ec); + return; + } stream_.async_handshake( stream_type::client, bind_executor( @@ -485,7 +519,10 @@ private: on_handshake(error_code ec) { if (ec) - return fail("handshake", ec); + { + fail("handshake", ec); + return; + } write(buf_, "HELLO\n"); #if 1 @@ -512,7 +549,10 @@ private: { buf_.consume(bytes_transferred); if (ec) - return fail("write", ec); + { + fail("write", ec); + return; + } #if 1 boost::asio::async_read_until( stream_, @@ -537,7 +577,10 @@ private: on_read(error_code ec, std::size_t bytes_transferred) { if (ec) - return fail("read", ec); + { + fail("read", ec); + return; + } buf_.commit(bytes_transferred); stream_.async_shutdown(bind_executor( strand_, @@ -549,7 +592,10 @@ private: on_shutdown(error_code ec) { if (ec) - return fail("shutdown", ec); + { + fail("shutdown", ec); + return; + } socket_.close(); timer_.cancel(); } diff --git a/src/test/overlay/tx_reduce_relay_test.cpp b/src/test/overlay/tx_reduce_relay_test.cpp index e3facb2f76..11b5c95a4e 100644 --- a/src/test/overlay/tx_reduce_relay_test.cpp +++ b/src/test/overlay/tx_reduce_relay_test.cpp @@ -53,16 +53,24 @@ private: BEAST_EXPECT(c.TX_REDUCE_RELAY_MIN_PEERS == min); BEAST_EXPECT(c.TX_RELAY_PERCENTAGE == pct); if (success) + { pass(); + } else + { fail(); + } } catch (...) { if (success) + { fail(); + } else + { pass(); + } } }; @@ -146,8 +154,7 @@ private: auto& overlay = dynamic_cast(env.app().overlay()); boost::beast::http::request request; (nDisabled == 0) - ? (void)request.insert( - "X-Protocol-Ctl", makeFeaturesRequestHeader(false, false, true, false)) + ? request.insert("X-Protocol-Ctl", makeFeaturesRequestHeader(false, false, true, false)) : (void)nDisabled--; auto stream_ptr = std::make_unique( socket_type(std::forward(env.app().getIOContext())), diff --git a/src/test/peerfinder/Livecache_test.cpp b/src/test/peerfinder/Livecache_test.cpp index a69a300686..b2d0eeeaf1 100644 --- a/src/test/peerfinder/Livecache_test.cpp +++ b/src/test/peerfinder/Livecache_test.cpp @@ -30,7 +30,7 @@ public: // Add the address as an endpoint template - inline void + void add(beast::IP::Endpoint ep, C& c, std::uint32_t hops = 0) { Endpoint cep{ep, hops}; diff --git a/src/test/peerfinder/PeerFinder_test.cpp b/src/test/peerfinder/PeerFinder_test.cpp index 038ed438f0..c39564c54c 100644 --- a/src/test/peerfinder/PeerFinder_test.cpp +++ b/src/test/peerfinder/PeerFinder_test.cpp @@ -391,7 +391,7 @@ public: testcase(test); - std::string toLoad = ""; + std::string toLoad; int max = 0; if (maxPeers) { diff --git a/src/test/protocol/STAccount_test.cpp b/src/test/protocol/STAccount_test.cpp index cab5df9631..3b12605a92 100644 --- a/src/test/protocol/STAccount_test.cpp +++ b/src/test/protocol/STAccount_test.cpp @@ -12,7 +12,7 @@ struct STAccount_test : public beast::unit_test::suite // Test default constructor. STAccount const defaultAcct; BEAST_EXPECT(defaultAcct.getSType() == STI_ACCOUNT); - BEAST_EXPECT(defaultAcct.getText() == ""); + BEAST_EXPECT(defaultAcct.getText().empty()); BEAST_EXPECT(defaultAcct.isDefault() == true); BEAST_EXPECT(defaultAcct.value() == AccountID{}); { @@ -38,7 +38,7 @@ struct STAccount_test : public beast::unit_test::suite // Test constructor from SField. STAccount const sfAcct{sfAccount}; BEAST_EXPECT(sfAcct.getSType() == STI_ACCOUNT); - BEAST_EXPECT(sfAcct.getText() == ""); + BEAST_EXPECT(sfAcct.getText().empty()); BEAST_EXPECT(sfAcct.isDefault()); BEAST_EXPECT(sfAcct.value() == AccountID{}); BEAST_EXPECT(sfAcct.isEquivalent(defaultAcct)); diff --git a/src/test/protocol/STObject_test.cpp b/src/test/protocol/STObject_test.cpp index b809ffccad..0faa1946a9 100644 --- a/src/test/protocol/STObject_test.cpp +++ b/src/test/protocol/STObject_test.cpp @@ -420,9 +420,9 @@ public: STObject st(sot, sfGeneric); auto const& cst(st); - BEAST_EXPECT(cst[sf1].size() == 0); + BEAST_EXPECT(cst[sf1].empty()); BEAST_EXPECT(!cst[~sf2]); - BEAST_EXPECT(cst[sf3].size() == 0); + BEAST_EXPECT(cst[sf3].empty()); std::vector v; v.emplace_back(1); st[sf1] = v; @@ -437,7 +437,7 @@ public: BEAST_EXPECT(cst[sf3].size() == 1); BEAST_EXPECT(cst[sf3][0] == uint256{1}); st[sf3] = std::vector{}; - BEAST_EXPECT(cst[sf3].size() == 0); + BEAST_EXPECT(cst[sf3].empty()); } } // namespace xrpl diff --git a/src/test/protocol/STParsedJSON_test.cpp b/src/test/protocol/STParsedJSON_test.cpp index 97da346015..18e695d25d 100644 --- a/src/test/protocol/STParsedJSON_test.cpp +++ b/src/test/protocol/STParsedJSON_test.cpp @@ -894,7 +894,7 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(obj.object->isFieldPresent(sfPublicKey)); auto const& blob = obj.object->getFieldVL(sfPublicKey); // NOLINT(bugprone-unchecked-optional-access) - BEAST_EXPECT(blob.size() == 0); + BEAST_EXPECT(blob.empty()); } // Test lowercase hex string for blob @@ -975,7 +975,7 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(obj.object->isFieldPresent(sfHashes)); auto const& vec = obj.object->getFieldV256(sfHashes); // NOLINT(bugprone-unchecked-optional-access) - BEAST_EXPECT(vec.size() == 0); + BEAST_EXPECT(vec.empty()); } // Test array with invalid hex string (should fail) diff --git a/src/test/protocol/SecretKey_test.cpp b/src/test/protocol/SecretKey_test.cpp index 43065d4e40..e42bec3363 100644 --- a/src/test/protocol/SecretKey_test.cpp +++ b/src/test/protocol/SecretKey_test.cpp @@ -112,7 +112,7 @@ public: auto sig = signDigest(pk, sk, digest); - BEAST_EXPECT(sig.size() != 0); + BEAST_EXPECT(!sig.empty()); BEAST_EXPECT(verifyDigest(pk, digest, sig, true)); // Wrong digest: @@ -150,7 +150,7 @@ public: auto sig = sign(pk, sk, makeSlice(data)); - BEAST_EXPECT(sig.size() != 0); + BEAST_EXPECT(!sig.empty()); BEAST_EXPECT(verify(pk, makeSlice(data), sig)); // Construct wrong data: diff --git a/src/test/protocol/Seed_test.cpp b/src/test/protocol/Seed_test.cpp index d516ec3e59..d7ad1f4afa 100644 --- a/src/test/protocol/Seed_test.cpp +++ b/src/test/protocol/Seed_test.cpp @@ -120,7 +120,7 @@ public: to_string(calcNodeID(publicKey)) == "7E59C17D50F5959C7B158FEC95C8F815BF653DC8"); auto sig = sign(publicKey, secretKey, makeSlice(message1)); - BEAST_EXPECT(sig.size() != 0); + BEAST_EXPECT(!sig.empty()); BEAST_EXPECT(verify(publicKey, makeSlice(message1), sig)); // Correct public key but wrong message @@ -162,7 +162,7 @@ public: to_string(calcNodeID(publicKey)) == "AA066C988C712815CC37AF71472B7CBBBD4E2A0A"); auto sig = sign(publicKey, secretKey, makeSlice(message1)); - BEAST_EXPECT(sig.size() != 0); + BEAST_EXPECT(!sig.empty()); BEAST_EXPECT(verify(publicKey, makeSlice(message1), sig)); // Correct public key but wrong message @@ -202,7 +202,7 @@ public: "p9JfM6HHi64m6mvB6v5k7G2b1cXzGmYiCNJf6GHPKvFTWdeRVjh"); auto sig = sign(pk, sk, makeSlice(message1)); - BEAST_EXPECT(sig.size() != 0); + BEAST_EXPECT(!sig.empty()); BEAST_EXPECT(verify(pk, makeSlice(message1), sig)); // Correct public key but wrong message @@ -241,7 +241,7 @@ public: "pwDQjwEhbUBmPuEjFpEG75bFhv2obkCB7NxQsfFxM7xGHBMVPu9"); auto sig = sign(pk, sk, makeSlice(message1)); - BEAST_EXPECT(sig.size() != 0); + BEAST_EXPECT(!sig.empty()); BEAST_EXPECT(verify(pk, makeSlice(message1), sig)); // Correct public key but wrong message diff --git a/src/test/resource/Logic_test.cpp b/src/test/resource/Logic_test.cpp index de57c715bc..c555b92860 100644 --- a/src/test/resource/Logic_test.cpp +++ b/src/test/resource/Logic_test.cpp @@ -66,9 +66,13 @@ public: testDrop(beast::Journal j, bool limited) { if (limited) + { testcase("Limited warn/drop"); + } else + { testcase("Unlimited warn/drop"); + } TestLogic logic(j); @@ -90,18 +94,26 @@ public: if (n == 0) { if (limited) + { fail("Loop count exceeded without warning"); + } else + { pass(); + } return; } if (c.charge(fee) == warn) { if (limited) + { pass(); + } else + { fail("Should loop forever with no warning"); + } break; } ++logic.clock(); @@ -113,9 +125,13 @@ public: if (n == 0) { if (limited) + { fail("Loop count exceeded without dropping"); + } else + { pass(); + } return; } @@ -136,9 +152,13 @@ public: if (c.disposition() != drop) { if (limited) + { fail("Dropped consumer not put on blacklist"); + } else + { pass(); + } return; } } diff --git a/src/test/rpc/AMMInfo_test.cpp b/src/test/rpc/AMMInfo_test.cpp index d3be04ff96..3f20e0378d 100644 --- a/src/test/rpc/AMMInfo_test.cpp +++ b/src/test/rpc/AMMInfo_test.cpp @@ -23,11 +23,15 @@ public: enum TestAccount { None, Alice, Bogie }; auto accountId = [&](AMM const& ammAlice, TestAccount v) -> std::optional { if (v == Alice) + { return ammAlice.ammAccount(); - else if (v == Bogie) + } + if (v == Bogie) + { return bogie; - else - return std::nullopt; + } + + return std::nullopt; }; // Invalid tokens pair @@ -185,9 +189,13 @@ public: Account a(std::to_string(i)); votes.insert({a.human(), 50 * (i + 1)}); if (!features[fixAMMv1_3]) + { fund(env, gw, {a}, {USD(10000)}, Fund::Acct); + } else + { fund(env, gw, {a}, {USD(10001)}, Fund::Acct); + } ammAlice.deposit(a, 10000000); ammAlice.vote(a, 50 * (i + 1)); } @@ -197,6 +205,7 @@ public: env.fund(XRP(1000), bob, ed, bill); env(ammAlice.bid({.bidMin = 100, .authAccounts = {carol, bob, ed, bill}})); if (!features[fixAMMv1_3]) + { BEAST_EXPECT(ammAlice.expectAmmRpcInfo( XRP(80000), USD(80000), @@ -204,7 +213,9 @@ public: std::nullopt, std::nullopt, ammAlice.ammAccount())); + } else + { BEAST_EXPECT(ammAlice.expectAmmRpcInfo( XRPAmount(80000000005), STAmount{USD, UINT64_C(80'000'00000000005), -11}, @@ -212,6 +223,7 @@ public: std::nullopt, std::nullopt, ammAlice.ammAccount())); + } for (auto i = 0; i < 2; ++i) { std::unordered_set authAccounts = { diff --git a/src/test/rpc/AccountObjects_test.cpp b/src/test/rpc/AccountObjects_test.cpp index 090f2a43b9..435bbd37d5 100644 --- a/src/test/rpc/AccountObjects_test.cpp +++ b/src/test/rpc/AccountObjects_test.cpp @@ -305,9 +305,13 @@ public: BEAST_EXPECT(aobjs.size() == 1); auto& aobj = aobjs[0U]; if (i < 3) + { BEAST_EXPECT(resp[jss::result][jss::limit] == 1); + } else + { BEAST_EXPECT(!resp[jss::result].isMember(jss::limit)); + } aobj.removeMember("PreviousTxnID"); aobj.removeMember("PreviousTxnLgrSeq"); diff --git a/src/test/rpc/AccountOffers_test.cpp b/src/test/rpc/AccountOffers_test.cpp index 55e60f8caa..6b93e0570f 100644 --- a/src/test/rpc/AccountOffers_test.cpp +++ b/src/test/rpc/AccountOffers_test.cpp @@ -13,7 +13,7 @@ public: checkMarker(Json::Value const& val) { return val.isMember(jss::marker) && val[jss::marker].isString() && - val[jss::marker].asString().size() > 0; + !val[jss::marker].asString().empty(); } void diff --git a/src/test/rpc/AccountTx_test.cpp b/src/test/rpc/AccountTx_test.cpp index 5015b960f9..a11f957628 100644 --- a/src/test/rpc/AccountTx_test.cpp +++ b/src/test/rpc/AccountTx_test.cpp @@ -62,19 +62,24 @@ class AccountTx_test : public beast::unit_test::suite for (Json::Value const& metaNode : txNode[jss::meta][sfAffectedNodes.jsonName]) { if (metaNode.isMember(sfCreatedNode.jsonName)) + { createdNodes.insert( metaNode[sfCreatedNode.jsonName][sfLedgerEntryType.jsonName].asString()); - + } else if (metaNode.isMember(sfDeletedNode.jsonName)) + { deletedNodes.insert( metaNode[sfDeletedNode.jsonName][sfLedgerEntryType.jsonName].asString()); - + } else if (metaNode.isMember(sfModifiedNode.jsonName)) + { modifiedNodes.insert( metaNode[sfModifiedNode.jsonName][sfLedgerEntryType.jsonName].asString()); - + } else + { fail("Unexpected or unlabeled node type in metadata.", __FILE__, __LINE__); + } } BEAST_EXPECT(createdNodes == sane.created); @@ -138,7 +143,9 @@ class AccountTx_test : public beast::unit_test::suite (payment[jss::close_time_iso] == "2000-01-01T00:00:10Z"); } else + { return false; + } default: return false; @@ -177,18 +184,26 @@ class AccountTx_test : public beast::unit_test::suite p[jss::ledger_index_min] = 0; p[jss::ledger_index_max] = 100; if (apiVersion < 2u) + { BEAST_EXPECT(hasTxs(env.rpc(apiVersion, "json", "account_tx", to_string(p)))); + } else + { BEAST_EXPECT( isErr(env.rpc("json", "account_tx", to_string(p)), rpcLGR_IDX_MALFORMED)); + } p[jss::ledger_index_min] = 1; p[jss::ledger_index_max] = 2; if (apiVersion < 2u) + { BEAST_EXPECT(noTxs(env.rpc("json", "account_tx", to_string(p)))); + } else + { BEAST_EXPECT( isErr(env.rpc("json", "account_tx", to_string(p)), rpcLGR_IDX_MALFORMED)); + } p[jss::ledger_index_min] = 2; p[jss::ledger_index_max] = 1; @@ -204,10 +219,14 @@ class AccountTx_test : public beast::unit_test::suite p[jss::ledger_index_min] = 1; if (apiVersion < 2u) + { BEAST_EXPECT(hasTxs(env.rpc(apiVersion, "json", "account_tx", to_string(p)))); + } else + { BEAST_EXPECT( isErr(env.rpc("json", "account_tx", to_string(p)), rpcLGR_IDX_MALFORMED)); + } p[jss::ledger_index_min] = env.current()->header().seq; BEAST_EXPECT(isErr( @@ -223,10 +242,14 @@ class AccountTx_test : public beast::unit_test::suite p[jss::ledger_index_max] = env.current()->header().seq; if (apiVersion < 2u) + { BEAST_EXPECT(hasTxs(env.rpc(apiVersion, "json", "account_tx", to_string(p)))); + } else + { BEAST_EXPECT( isErr(env.rpc("json", "account_tx", to_string(p)), rpcLGR_IDX_MALFORMED)); + } p[jss::ledger_index_max] = 3; BEAST_EXPECT(hasTxs(env.rpc(apiVersion, "json", "account_tx", to_string(p)))); @@ -278,9 +301,13 @@ class AccountTx_test : public beast::unit_test::suite p[jss::ledger_index] = -1; if (apiVersion < 2u) + { BEAST_EXPECT(hasTxs(env.rpc(apiVersion, "json", "account_tx", to_string(p)))); + } else + { BEAST_EXPECT(isErr(env.rpc("json", "account_tx", to_string(p)), rpcINVALID_PARAMS)); + } } // Ledger index max only @@ -288,10 +315,14 @@ class AccountTx_test : public beast::unit_test::suite Json::Value p{jParams}; p[jss::ledger_index_max] = env.current()->header().seq; if (apiVersion < 2u) + { BEAST_EXPECT(hasTxs(env.rpc(apiVersion, "json", "account_tx", to_string(p)))); + } else + { BEAST_EXPECT( isErr(env.rpc("json", "account_tx", to_string(p)), rpcLGR_IDX_MALFORMED)); + } } // test account non-string { @@ -320,7 +351,9 @@ class AccountTx_test : public beast::unit_test::suite BEAST_EXPECT(result[jss::result][jss::status] == "success"); } else + { BEAST_EXPECT(isErr(env.rpc("json", "account_tx", to_string(p)), rpcINVALID_PARAMS)); + } p[jss::binary] = true; Json::Value result{env.rpc("json", "account_tx", to_string(p))}; @@ -328,9 +361,13 @@ class AccountTx_test : public beast::unit_test::suite p[jss::forward] = "true"; if (apiVersion < 2u) + { BEAST_EXPECT(result[jss::result][jss::status] == "success"); + } else + { BEAST_EXPECT(isErr(env.rpc("json", "account_tx", to_string(p)), rpcINVALID_PARAMS)); + } p[jss::forward] = false; result = env.rpc("json", "account_tx", to_string(p)); diff --git a/src/test/rpc/DeliveredAmount_test.cpp b/src/test/rpc/DeliveredAmount_test.cpp index c156a566b0..00f8c54ee5 100644 --- a/src/test/rpc/DeliveredAmount_test.cpp +++ b/src/test/rpc/DeliveredAmount_test.cpp @@ -36,9 +36,13 @@ class CheckDeliveredAmount if (!afterSwitchTime_) { if (partial) + { ++numExpectedAvailable_; + } else + { ++numExpectedSetUnavailable_; + } return; } // normal case: after switch time & successful transaction @@ -91,16 +95,26 @@ public: if (isSet) { if (metaData[jss::delivered_amount] != "unavailable") + { isSetAvailable = true; + } else + { isSetUnavailable = true; + } } if (isSetAvailable) + { --numExpectedAvailable_; + } else if (isSetUnavailable) + { --numExpectedSetUnavailable_; + } else if (!isSet) + { --numExpectedNotSet_; + } if (isSet) { @@ -178,9 +192,13 @@ class DeliveredAmount_test : public beast::unit_test::suite env.fund(XRP(10000), alice, bob, carol, gw); env.trust(USD(1000), alice, bob, carol); if (afterSwitchTime) + { env.close(NetClock::time_point{446000000s}); + } else + { env.close(); + } CheckDeliveredAmount checkDeliveredAmount{afterSwitchTime}; { @@ -265,9 +283,13 @@ class DeliveredAmount_test : public beast::unit_test::suite env.fund(XRP(10000), alice, bob, carol, gw); env.trust(USD(1000), alice, bob, carol); if (afterSwitchTime) + { env.close(NetClock::time_point{446000000s}); + } else + { env.close(); + } CheckDeliveredAmount checkDeliveredAmount{afterSwitchTime}; // normal payments diff --git a/src/test/rpc/DepositAuthorized_test.cpp b/src/test/rpc/DepositAuthorized_test.cpp index 9d6de94ccc..87951e397c 100644 --- a/src/test/rpc/DepositAuthorized_test.cpp +++ b/src/test/rpc/DepositAuthorized_test.cpp @@ -246,9 +246,11 @@ public: if (result.isMember(jss::deposit_authorized)) BEAST_EXPECT(result[jss::deposit_authorized] == authorized); if (authorized) + { BEAST_EXPECT( result.isMember(jss::deposit_authorized) && (result[jss::deposit_authorized] == true)); + } BEAST_EXPECT(result.isMember(jss::error) == !error.empty()); if (!error.empty()) diff --git a/src/test/rpc/Feature_test.cpp b/src/test/rpc/Feature_test.cpp index 43c8d788ac..0050429c99 100644 --- a/src/test/rpc/Feature_test.cpp +++ b/src/test/rpc/Feature_test.cpp @@ -347,9 +347,12 @@ class Feature_test : public beast::unit_test::suite (*it).isMember(jss::enabled) && (*it)[jss::enabled].asBool() == expectEnabled, (*it)[jss::name].asString() + " enabled"); if (expectEnabled) + { BEAST_EXPECTS( !(*it).isMember(jss::vetoed), (*it)[jss::name].asString() + " vetoed"); + } else + { BEAST_EXPECTS( (*it).isMember(jss::vetoed) && (*it)[jss::vetoed].isBool() == !expectObsolete && (!(*it)[jss::vetoed].isBool() || @@ -357,6 +360,7 @@ class Feature_test : public beast::unit_test::suite ((*it)[jss::vetoed].isBool() || (*it)[jss::vetoed].asString() == "Obsolete"), (*it)[jss::name].asString() + " vetoed"); + } BEAST_EXPECTS( (*it).isMember(jss::supported) && (*it)[jss::supported].asBool() == expectSupported, (*it)[jss::name].asString() + " supported"); diff --git a/src/test/rpc/KeyGeneration_test.cpp b/src/test/rpc/KeyGeneration_test.cpp index dc46a66c07..e4af2608b7 100644 --- a/src/test/rpc/KeyGeneration_test.cpp +++ b/src/test/rpc/KeyGeneration_test.cpp @@ -164,9 +164,13 @@ public: auto const wallet = testSecretWallet(params, strings); if (value == strings.passphrase) + { BEAST_EXPECT(wallet[jss::warning] == strings.passphrase_warning); + } else + { BEAST_EXPECT(!wallet.isMember(jss::warning)); + } } void diff --git a/src/test/rpc/LedgerData_test.cpp b/src/test/rpc/LedgerData_test.cpp index 1cce3d1383..472f5b2aa2 100644 --- a/src/test/rpc/LedgerData_test.cpp +++ b/src/test/rpc/LedgerData_test.cpp @@ -13,7 +13,7 @@ public: checkMarker(Json::Value const& val) { return val.isMember(jss::marker) && val[jss::marker].isString() && - val[jss::marker].asString().size() > 0; + !val[jss::marker].asString().empty(); } void @@ -198,8 +198,10 @@ public: jvParams[jss::ledger_index] = "closed"; auto jrr = env.rpc("json", "ledger_data", to_string(jvParams))[jss::result]; if (BEAST_EXPECT(jrr.isMember(jss::ledger))) + { BEAST_EXPECT( jrr[jss::ledger][jss::ledger_hash] == to_string(env.closed()->header().hash)); + } } { // Closed ledger with binary form diff --git a/src/test/rpc/LedgerEntry_test.cpp b/src/test/rpc/LedgerEntry_test.cpp index ffc4329109..eec114b71c 100644 --- a/src/test/rpc/LedgerEntry_test.cpp +++ b/src/test/rpc/LedgerEntry_test.cpp @@ -60,10 +60,8 @@ getFieldType(Json::StaticString fieldName) { return it->second; } - else - { - Throw("`mappings` is missing field " + std::string(fieldName.c_str())); - } + + Throw("`mappings` is missing field " + std::string(fieldName.c_str())); } std::string @@ -110,10 +108,12 @@ class LedgerEntry_test : public beast::unit_test::suite if (BEAST_EXPECT(jv.isMember(jss::status))) BEAST_EXPECTS(jv[jss::status] == "error", std::to_string(location.line())); if (BEAST_EXPECT(jv.isMember(jss::error))) + { BEAST_EXPECTS( jv[jss::error] == err, "Expected error " + err + ", received " + jv[jss::error].asString() + ", at line " + std::to_string(location.line()) + ", " + jv.toStyledString()); + } if (msg.empty()) { BEAST_EXPECTS( @@ -122,11 +122,13 @@ class LedgerEntry_test : public beast::unit_test::suite "\", at line " + std::to_string(location.line()) + ", " + jv.toStyledString()); } else if (BEAST_EXPECT(jv.isMember(jss::error_message))) + { BEAST_EXPECTS( jv[jss::error_message] == msg, "Expected error message \"" + msg + "\", received \"" + jv[jss::error_message].asString() + "\", at line " + std::to_string(location.line()) + ", " + jv.toStyledString()); + } } std::vector @@ -175,7 +177,7 @@ class LedgerEntry_test : public beast::unit_test::suite values.reserve(allBadValues.size() - indexSet.size()); for (std::size_t i = 0; i < allBadValues.size(); ++i) { - if (indexSet.find(i) == indexSet.end()) + if (!indexSet.contains(i)) { values.push_back(allBadValues[i]); } @@ -286,10 +288,14 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value const jrr = env.rpc( apiVersion, "json", "ledger_entry", to_string(correctRequest))[jss::result]; if (apiVersion < 2u) + { checkErrorValue(jrr, "unknownOption", "", location); + } else + { checkErrorValue( jrr, "invalidParams", "No ledger_entry params provided.", location); + } } auto tryField = [&](Json::Value fieldValue) -> void { correctRequest[fieldName] = fieldValue; @@ -491,9 +497,13 @@ class LedgerEntry_test : public beast::unit_test::suite env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; if (apiVersion < 2u) + { checkErrorValue(jrr, "unknownOption", ""); + } else + { checkErrorValue(jrr, "invalidParams", "No ledger_entry params provided."); + } } }); } @@ -2640,7 +2650,9 @@ class LedgerEntry_XChain_test : public beast::unit_test::suite, BEAST_EXPECT(jv[jss::error_message] == Json::nullValue || jv[jss::error_message] == ""); } else if (BEAST_EXPECT(jv.isMember(jss::error_message))) + { BEAST_EXPECT(jv[jss::error_message] == msg); + } } void diff --git a/src/test/rpc/LedgerRPC_test.cpp b/src/test/rpc/LedgerRPC_test.cpp index d45f50c657..2f4a63a090 100644 --- a/src/test/rpc/LedgerRPC_test.cpp +++ b/src/test/rpc/LedgerRPC_test.cpp @@ -30,10 +30,12 @@ class LedgerRPC_test : public beast::unit_test::suite BEAST_EXPECT(jv[jss::error_message] == Json::nullValue || jv[jss::error_message] == ""); } else if (BEAST_EXPECT(jv.isMember(jss::error_message))) + { BEAST_EXPECTS( jv[jss::error_message] == msg, "Expected error message \"" + msg + "\", received \"" + jv[jss::error_message].asString() + "\""); + } } // Corrupt a valid address by replacing the 10th character with '!'. @@ -634,15 +636,19 @@ class LedgerRPC_test : public beast::unit_test::suite BEAST_EXPECT(jrr[jss::ledger][jss::accountState].isArray()); for (auto i = 0; i < jrr[jss::ledger][jss::accountState].size(); i++) + { if (jrr[jss::ledger][jss::accountState][i]["LedgerEntryType"] == jss::LedgerHashes) { index = jrr[jss::ledger][jss::accountState][i]["index"].asString(); hashesLedgerEntryIndex = i; } + } for (auto const& object : jrr[jss::ledger][jss::accountState]) + { if (object["LedgerEntryType"] == jss::LedgerHashes) index = object["index"].asString(); + } // jss::type is a deprecated field BEAST_EXPECT( diff --git a/src/test/rpc/NoRippleCheck_test.cpp b/src/test/rpc/NoRippleCheck_test.cpp index c436c1d7b1..54a2931ba5 100644 --- a/src/test/rpc/NoRippleCheck_test.cpp +++ b/src/test/rpc/NoRippleCheck_test.cpp @@ -235,8 +235,10 @@ public: { testBadInput(); for (auto user : {true, false}) + { for (auto problem : {true, false}) testBasic(user, problem); + } } }; diff --git a/src/test/rpc/NoRipple_test.cpp b/src/test/rpc/NoRipple_test.cpp index 27f13aa3e2..fcf412bbd4 100644 --- a/src/test/rpc/NoRipple_test.cpp +++ b/src/test/rpc/NoRipple_test.cpp @@ -234,9 +234,13 @@ public: auto lines = env.rpc("json", "noripple_check", to_string(params)); if (apiVersion < 2u) + { BEAST_EXPECT(lines[jss::result][jss::status] == "success"); + } else + { BEAST_EXPECT(lines[jss::result][jss::error] == "invalidParams"); + } } } } diff --git a/src/test/rpc/RPCOverload_test.cpp b/src/test/rpc/RPCOverload_test.cpp index c8f02cd0a3..e5558af82c 100644 --- a/src/test/rpc/RPCOverload_test.cpp +++ b/src/test/rpc/RPCOverload_test.cpp @@ -45,7 +45,9 @@ public: jv = jv[jss::result]; // When booted, we just get a null json response if (jv.isNull()) + { booted = true; + } else if (!(jv.isMember(jss::status) && (jv[jss::status] == "success"))) { // Don't use BEAST_EXPECT above b/c it will be called a diff --git a/src/test/rpc/ServerInfo_test.cpp b/src/test/rpc/ServerInfo_test.cpp index 9fdfe5e13b..5bb2c31757 100644 --- a/src/test/rpc/ServerInfo_test.cpp +++ b/src/test/rpc/ServerInfo_test.cpp @@ -85,7 +85,7 @@ admin = 127.0.0.1 (git[jss::hash].isString() && git[jss::hash].asString().size() == 40)); BEAST_EXPECT( !git.isMember(jss::branch) || - (git[jss::branch].isString() && git[jss::branch].asString().size() != 0)); + (git[jss::branch].isString() && !git[jss::branch].asString().empty())); } } diff --git a/src/test/rpc/Simulate_test.cpp b/src/test/rpc/Simulate_test.cpp index 6712c3f229..74f9b03111 100644 --- a/src/test/rpc/Simulate_test.cpp +++ b/src/test/rpc/Simulate_test.cpp @@ -59,7 +59,7 @@ class Simulate_test : public beast::unit_test::suite int const expectedSequence, XRPAmount const& expectedFee) { - return checkBasicReturnValidity( + checkBasicReturnValidity( result, tx, expectedSequence, expectedFee.jsonClipped().asString()); } diff --git a/src/test/rpc/Transaction_test.cpp b/src/test/rpc/Transaction_test.cpp index fa76f62cdf..2709900bf1 100644 --- a/src/test/rpc/Transaction_test.cpp +++ b/src/test/rpc/Transaction_test.cpp @@ -92,9 +92,13 @@ class Transaction_test : public beast::unit_test::suite result[jss::result][jss::error] == NOT_FOUND); if (deltaEndSeq) + { BEAST_EXPECT(!result[jss::result][jss::searched_all].asBool()); + } else + { BEAST_EXPECT(result[jss::result][jss::searched_all].asBool()); + } } // Find transactions outside of provided range. @@ -329,9 +333,13 @@ class Transaction_test : public beast::unit_test::suite result[jss::result][jss::error] == NOT_FOUND); if (deltaEndSeq) + { BEAST_EXPECT(!result[jss::result][jss::searched_all].asBool()); + } else + { BEAST_EXPECT(!result[jss::result][jss::searched_all].asBool()); + } } // Find transactions outside of provided range. diff --git a/src/test/rpc/ValidatorRPC_test.cpp b/src/test/rpc/ValidatorRPC_test.cpp index 829e2699a7..43ba188f6a 100644 --- a/src/test/rpc/ValidatorRPC_test.cpp +++ b/src/test/rpc/ValidatorRPC_test.cpp @@ -134,7 +134,7 @@ public: parseBase58(TokenType::NodePublic, jrrnUnl[x].asString()); BEAST_EXPECT(parsedKey); if (parsedKey) - BEAST_EXPECT(disabledKeys.find(*parsedKey) != disabledKeys.end()); + BEAST_EXPECT(disabledKeys.contains(*parsedKey)); } disabledKeys.clear(); diff --git a/src/test/rpc/Version_test.cpp b/src/test/rpc/Version_test.cpp index c86bb8a660..7fa6720f83 100644 --- a/src/test/rpc/Version_test.cpp +++ b/src/test/rpc/Version_test.cpp @@ -42,10 +42,12 @@ class Version_test : public beast::unit_test::suite auto badVersion = [](Json::Value const& re) -> bool { if (re.isMember("error_what")) + { if (re["error_what"].isString()) { return re["error_what"].asString().find(jss::invalid_API_version.c_str()) == 0; } + } return false; }; diff --git a/src/test/server/ServerStatus_test.cpp b/src/test/server/ServerStatus_test.cpp index 49ee3d2079..178b85b3e4 100644 --- a/src/test/server/ServerStatus_test.cpp +++ b/src/test/server/ServerStatus_test.cpp @@ -616,9 +616,8 @@ class ServerStatus_test : public beast::unit_test::suite, public beast::test::en boost::system::error_code ec; doRequest(yield, makeWSUpgrade(ip, port), ip, port, true, resp, ec); BEAST_EXPECT(resp.result() == boost::beast::http::status::switching_protocols); - BEAST_EXPECT(resp.find("Upgrade") != resp.end() && resp["Upgrade"] == "websocket"); - BEAST_EXPECT( - resp.find("Connection") != resp.end() && boost::iequals(resp["Connection"], "upgrade")); + BEAST_EXPECT(resp.contains("Upgrade") && resp["Upgrade"] == "websocket"); + BEAST_EXPECT(resp.contains("Connection") && boost::iequals(resp["Connection"], "upgrade")); } void diff --git a/src/test/server/Server_test.cpp b/src/test/server/Server_test.cpp index bc12d98659..bce8bced60 100644 --- a/src/test/server/Server_test.cpp +++ b/src/test/server/Server_test.cpp @@ -121,9 +121,13 @@ public: { session.write(std::string("Hello, world!\n")); if (beast::rfc2616::is_keep_alive(session.request())) + { session.complete(); + } else + { session.close(true); + } } void diff --git a/src/test/shamap/SHAMapSync_test.cpp b/src/test/shamap/SHAMapSync_test.cpp index 81305c4dab..a8f3a478b2 100644 --- a/src/test/shamap/SHAMapSync_test.cpp +++ b/src/test/shamap/SHAMapSync_test.cpp @@ -107,7 +107,7 @@ public: BEAST_EXPECT(source.getNodeFat(SHAMapNodeID(), a, rand_bool(eng_), rand_int(eng_, 2))); - unexpected(a.size() < 1, "NodeSize"); + unexpected(a.empty(), "NodeSize"); BEAST_EXPECT(destination.addRootNode(source.getHash(), makeSlice(a[0].second), nullptr) .isGood()); diff --git a/src/test/shamap/SHAMap_test.cpp b/src/test/shamap/SHAMap_test.cpp index 1eb050178c..b16f7b157f 100644 --- a/src/test/shamap/SHAMap_test.cpp +++ b/src/test/shamap/SHAMap_test.cpp @@ -110,9 +110,13 @@ public: run(bool backed, beast::Journal const& journal) { if (backed) + { testcase("add/traverse backed"); + } else + { testcase("add/traverse unbacked"); + } tests::TestNodeFamily f(journal); @@ -163,9 +167,13 @@ public: unexpected(i != e, "bad traverse"); if (backed) + { testcase("snapshot backed"); + } else + { testcase("snapshot unbacked"); + } SHAMapHash mapHash = sMap.getHash(); std::shared_ptr map2 = sMap.snapShot(false); @@ -191,9 +199,13 @@ public: sMap.dump(); if (backed) + { testcase("build/tear backed"); + } else + { testcase("build/tear unbacked"); + } { constexpr std::array keys{ uint256( @@ -269,9 +281,13 @@ public: } if (backed) + { testcase("iterate backed"); + } else + { testcase("iterate unbacked"); + } { constexpr std::array keys{ diff --git a/src/test/unit_test/multi_runner.cpp b/src/test/unit_test/multi_runner.cpp index 3838f128f0..239564bd7c 100644 --- a/src/test/unit_test/multi_runner.cpp +++ b/src/test/unit_test/multi_runner.cpp @@ -108,7 +108,7 @@ results::print(S& s) { using namespace beast::unit_test; - if (top.size() > 0) + if (!top.empty()) { s << "Longest suite times:\n"; for (auto const& [name, dur] : top) @@ -234,9 +234,13 @@ multi_runner_base::multi_runner_base() region_ = boost::interprocess::mapped_region{shared_mem_, boost::interprocess::read_write}; if (IsParent) + { inner_ = new (region_.get_address()) inner{}; + } else + { inner_ = reinterpret_cast(region_.get_address()); + } } catch (...) { diff --git a/src/tests/libxrpl/basics/Slice.cpp b/src/tests/libxrpl/basics/Slice.cpp index 0e5e0877d0..72f2d081c7 100644 --- a/src/tests/libxrpl/basics/Slice.cpp +++ b/src/tests/libxrpl/basics/Slice.cpp @@ -28,18 +28,26 @@ TEST(Slice, equality_and_inequality) EXPECT_NE(s1.data(), nullptr); if (i == 0) + { EXPECT_EQ(s1, s0); + } else + { EXPECT_NE(s1, s0); + } for (std::size_t j = 0; j != sizeof(data); ++j) { Slice const s2{data, j}; if (i == j) + { EXPECT_EQ(s1, s2); + } else + { EXPECT_NE(s1, s2); + } } } diff --git a/src/xrpld/app/consensus/RCLConsensus.cpp b/src/xrpld/app/consensus/RCLConsensus.cpp index 16cf7f4c9d..5a3d53dae0 100644 --- a/src/xrpld/app/consensus/RCLConsensus.cpp +++ b/src/xrpld/app/consensus/RCLConsensus.cpp @@ -498,7 +498,7 @@ RCLConsensus::Adaptor::doAccept( std::move(accepted), [curr = built.seq(), j = app_.journal("CensorshipDetector"), &failed]( uint256 const& id, LedgerIndex seq) { - if (failed.count(id)) + if (failed.contains(id)) return true; auto const wait = curr - seq; @@ -585,9 +585,13 @@ RCLConsensus::Adaptor::doAccept( auto const lastVal = ledgerMaster_.getValidatedLedger(); std::optional rules; if (lastVal) + { rules = makeRulesGivenLedger(*lastVal, app_.config().features); + } else + { rules.emplace(app_.config().features); + } app_.openLedger().accept( app_, *rules, @@ -664,9 +668,13 @@ RCLConsensus::Adaptor::notify( protocol::TMStatusChange s; if (!haveCorrectLCL) + { s.set_newevent(protocol::neLOST_SYNC); + } else + { s.set_newevent(ne); + } s.set_ledgerseq(ledger.seq()); s.set_networktime(app_.timeKeeper().now().time_since_epoch().count()); @@ -726,9 +734,13 @@ RCLConsensus::Adaptor::buildLCL( // And stash the ledger in the ledger master if (ledgerMaster_.storeLedger(built)) + { JLOG(j_.debug()) << "Consensus built ledger we already had"; + } else if (app_.getInboundLedgers().find(built->header().hash)) + { JLOG(j_.debug()) << "Consensus built ledger we were acquiring"; + } else JLOG(j_.debug()) << "Consensus built new ledger"; return RCLCxLedger{std::move(built)}; diff --git a/src/xrpld/app/consensus/RCLCxPeerPos.cpp b/src/xrpld/app/consensus/RCLCxPeerPos.cpp index 4128d65c49..cdb8350468 100644 --- a/src/xrpld/app/consensus/RCLCxPeerPos.cpp +++ b/src/xrpld/app/consensus/RCLCxPeerPos.cpp @@ -19,7 +19,7 @@ RCLCxPeerPos::RCLCxPeerPos( signature.size() != 0 && signature.size() <= signature_.capacity(), "xrpl::RCLCxPeerPos::RCLCxPeerPos : valid signature size"); - if (signature.size() != 0 && signature.size() <= signature_.capacity()) + if (!signature.empty() && signature.size() <= signature_.capacity()) signature_.assign(signature.begin(), signature.end()); } diff --git a/src/xrpld/app/consensus/RCLValidations.cpp b/src/xrpld/app/consensus/RCLValidations.cpp index 60e02f53b4..a968acb1a7 100644 --- a/src/xrpld/app/consensus/RCLValidations.cpp +++ b/src/xrpld/app/consensus/RCLValidations.cpp @@ -205,14 +205,18 @@ handleNewValidation( }(); if (outcome == ValStatus::conflicting) + { ls << "Byzantine Behavior Detector: " << (val->isTrusted() ? "trusted " : "untrusted ") << id << ": Conflicting validation for " << seq << "!\n[" << val->getSerializer().slice() << "]"; + } if (outcome == ValStatus::multiple) + { ls << "Byzantine Behavior Detector: " << (val->isTrusted() ? "trusted " : "untrusted ") << id << ": Multiple validations for " << seq << "/" << hash << "!\n[" << val->getSerializer().slice() << "]"; + } } } diff --git a/src/xrpld/app/ledger/AcceptedLedger.cpp b/src/xrpld/app/ledger/AcceptedLedger.cpp index 339c5f57c7..1da70702bf 100644 --- a/src/xrpld/app/ledger/AcceptedLedger.cpp +++ b/src/xrpld/app/ledger/AcceptedLedger.cpp @@ -10,8 +10,10 @@ AcceptedLedger::AcceptedLedger(std::shared_ptr const& ledger) : auto insertAll = [&](auto const& txns) { for (auto const& item : txns) + { transactions_.emplace_back( std::make_unique(ledger, item.first, item.second)); + } }; transactions_.reserve(256); diff --git a/src/xrpld/app/ledger/Ledger.cpp b/src/xrpld/app/ledger/Ledger.cpp index 3a81b5f3a3..7be1b5e762 100644 --- a/src/xrpld/app/ledger/Ledger.cpp +++ b/src/xrpld/app/ledger/Ledger.cpp @@ -597,9 +597,13 @@ Ledger::setup() if (src) { if (src->native()) + { dest = src->xrp(); + } else + { ret = false; + } } }; assign(fees_.base, baseFeeXRP); @@ -608,11 +612,15 @@ Ledger::setup() newFees = baseFeeXRP || reserveBaseXRP || reserveIncrementXRP; } if (oldFees && newFees) + { // Should be all of one or the other, but not both ret = false; + } if (!rules_.enabled(featureXRPFees) && newFees) + { // Can't populate the new fees before the amendment is enabled ret = false; + } } } catch (SHAMapMissingNode const&) @@ -770,9 +778,11 @@ Ledger::walkLedger(beast::Journal j, bool parallel) const else { if (parallel) + { return stateMap_.walkMapParallel(missingNodes1, 32); - else - stateMap_.walkMap(missingNodes1, 32); + } + + stateMap_.walkMap(missingNodes1, 32); } if (!missingNodes1.empty()) @@ -864,9 +874,13 @@ Ledger::updateSkipList() sle->setFieldV256(sfHashes, STVector256(hashes)); sle->setFieldU32(sfLastLedgerSequence, prevIndex); if (created) + { rawInsert(sle); + } else + { rawReplace(sle); + } } // update record of past 256 ledger @@ -891,9 +905,13 @@ Ledger::updateSkipList() sle->setFieldV256(sfHashes, STVector256(hashes)); sle->setFieldU32(sfLastLedgerSequence, prevIndex); if (created) + { rawInsert(sle); + } else + { rawReplace(sle); + } } bool diff --git a/src/xrpld/app/ledger/LedgerHistory.cpp b/src/xrpld/app/ledger/LedgerHistory.cpp index f2e2afb3e6..5ff5555fff 100644 --- a/src/xrpld/app/ledger/LedgerHistory.cpp +++ b/src/xrpld/app/ledger/LedgerHistory.cpp @@ -337,9 +337,11 @@ LedgerHistory::handleMismatch( if (builtConsensusHash && validatedConsensusHash) { if (builtConsensusHash != validatedConsensusHash) + { JLOG(j_.error()) << "MISMATCH on consensus transaction set " << " built: " << to_string(*builtConsensusHash) << " validated: " << to_string(*validatedConsensusHash); + } else JLOG(j_.error()) << "MISMATCH with same consensus transaction set: " << to_string(*builtConsensusHash); @@ -350,7 +352,9 @@ LedgerHistory::handleMismatch( auto const validTx = leaves(validLedger->txMap()); if (builtTx == validTx) + { JLOG(j_.error()) << "MISMATCH with same " << builtTx.size() << " transactions"; + } else JLOG(j_.error()) << "MISMATCH with " << builtTx.size() << " built and " << validTx.size() << " valid transactions."; diff --git a/src/xrpld/app/ledger/OrderBookDBImpl.cpp b/src/xrpld/app/ledger/OrderBookDBImpl.cpp index b82fa3896b..2691935911 100644 --- a/src/xrpld/app/ledger/OrderBookDBImpl.cpp +++ b/src/xrpld/app/ledger/OrderBookDBImpl.cpp @@ -52,12 +52,16 @@ OrderBookDBImpl::setup(std::shared_ptr const& ledger) if (pathSearchMax_ != 0) { if (standalone_) + { update(ledger); + } else + { registry_.getJobQueue().addJob( jtUPDATE_PF, "OrderBookUpd" + std::to_string(ledger->seq()), [this, ledger]() { update(ledger); }); + } } } @@ -111,14 +115,22 @@ OrderBookDBImpl::update(std::shared_ptr const& ledger) book.domain = (*sle)[~sfDomainID]; if (book.domain) + { domainBooks[{book.in, *book.domain}].insert(book.out); + } else + { allBooks[book.in].insert(book.out); + } if (book.domain && isXRP(book.out)) + { xrpDomainBooks.insert({book.in, *book.domain}); + } else if (isXRP(book.out)) + { xrpBooks.insert(book.in); + } ++cnt; } @@ -167,14 +179,22 @@ OrderBookDBImpl::addOrderBook(Book const& book) std::lock_guard sl(mLock); if (book.domain) + { domainBooks_[{book.in, *book.domain}].insert(book.out); + } else + { allBooks_[book.in].insert(book.out); + } if (book.domain && toXRP) + { xrpDomainBooks_.insert({book.in, *book.domain}); + } else if (toXRP) + { xrpBooks_.insert(book.in); + } } // return list of all orderbooks that want this issuerID and currencyID @@ -198,9 +218,13 @@ OrderBookDBImpl::getBooksByTakerPays(Issue const& issue, std::optional }; if (!domain) + { getBooks(allBooks_, issue); + } else + { getBooks(domainBooks_, std::make_pair(issue, *domain)); + } } return ret; @@ -306,11 +330,17 @@ OrderBookDBImpl::processTxn( // We need a field that contains the TakerGets and TakerPays // parameters. if (node.getFName() == sfModifiedNode) + { process(sfPreviousFields); + } else if (node.getFName() == sfCreatedNode) + { process(sfNewFields); + } else if (node.getFName() == sfDeletedNode) + { process(sfFinalFields); + } } } catch (std::exception const& ex) diff --git a/src/xrpld/app/ledger/detail/BuildLedger.cpp b/src/xrpld/app/ledger/detail/BuildLedger.cpp index c4f8f9e60a..5ad72c7a69 100644 --- a/src/xrpld/app/ledger/detail/BuildLedger.cpp +++ b/src/xrpld/app/ledger/detail/BuildLedger.cpp @@ -181,10 +181,12 @@ buildLedger( auto const applied = applyTransactions(app, built, txns, failedTxns, accum, j); if (!txns.empty() || !failedTxns.empty()) + { JLOG(j.debug()) << "Applied " << applied << " transactions; " << failedTxns.size() << " failed and " << txns.size() << " will be retried. " << "Total transactions in ledger (including Inner Batch): " << accum.txCount(); + } else JLOG(j.debug()) << "Applied " << applied << " transactions. " << "Total transactions in ledger (including Inner Batch): " diff --git a/src/xrpld/app/ledger/detail/InboundLedger.cpp b/src/xrpld/app/ledger/detail/InboundLedger.cpp index b8158e507f..9f7312ea34 100644 --- a/src/xrpld/app/ledger/detail/InboundLedger.cpp +++ b/src/xrpld/app/ledger/detail/InboundLedger.cpp @@ -145,9 +145,13 @@ InboundLedger::checkLocal() if (!isDone()) { if (mLedger) + { tryDB(mLedger->stateMap().family().db()); + } else + { tryDB(app_.getNodeFamily().db()); + } if (failed_ || complete_) { done(); @@ -184,7 +188,9 @@ neededHashes(uint256 const& root, SHAMap& map, int max, SHAMapSyncFilter* filter if (!root.isZero()) { if (map.getHash().isZero()) + { ret.push_back(root); + } else { auto mn = map.getMissingNodes(max, filter); @@ -435,7 +441,9 @@ InboundLedger::done() self->app_.getLedgerMaster().tryAdvance(); } else + { self->app_.getInboundLedgers().logFailure(self->hash_, self->mSeq); + } }); } @@ -461,9 +469,13 @@ InboundLedger::trigger(std::shared_ptr const& peer, TriggerReason reason) ss << " from " << peer; if (complete_ || failed_) + { ss << " complete=" << complete_ << " failed=" << failed_; + } else + { ss << " header=" << mHaveHeader << " tx=" << mHaveTransactions << " as=" << mHaveState; + } stream << ss.str(); } @@ -562,7 +574,9 @@ InboundLedger::trigger(std::shared_ptr const& peer, TriggerReason reason) tmGL.set_querydepth(2); } else + { tmGL.set_querydepth(1); + } // Get the state data first because it's the most likely to be useful // if we wind up abandoning this fetch. @@ -602,7 +616,9 @@ InboundLedger::trigger(std::shared_ptr const& peer, TriggerReason reason) if (nodes.empty()) { if (!mLedger->stateMap().isValid()) + { failed_ = true; + } else { mHaveState = true; @@ -628,10 +644,8 @@ InboundLedger::trigger(std::shared_ptr const& peer, TriggerReason reason) mPeerSet->sendRequest(tmGL, peer); return; } - else - { - JLOG(journal_.trace()) << "All AS nodes filtered"; - } + + JLOG(journal_.trace()) << "All AS nodes filtered"; } } } @@ -667,7 +681,9 @@ InboundLedger::trigger(std::shared_ptr const& peer, TriggerReason reason) if (nodes.empty()) { if (!mLedger->txMap().isValid()) + { failed_ = true; + } else { mHaveTransactions = true; @@ -692,10 +708,8 @@ InboundLedger::trigger(std::shared_ptr const& peer, TriggerReason reason) mPeerSet->sendRequest(tmGL, peer); return; } - else - { - JLOG(journal_.trace()) << "All TX nodes filtered"; - } + + JLOG(journal_.trace()) << "All TX nodes filtered"; } } } @@ -823,11 +837,13 @@ InboundLedger::receiveNode(protocol::TMLedgerData& packet, SHAMapAddNode& san) auto [map, rootHash, filter] = [&]() -> std::tuple> { if (packet.type() == protocol::liTX_NODE) + { return { mLedger->txMap(), SHAMapHash{mLedger->header().txHash}, std::make_unique( mLedger->txMap().family().db(), app_.getLedgerMaster())}; + } return { mLedger->stateMap(), SHAMapHash{mLedger->header().accountHash}, @@ -872,9 +888,13 @@ InboundLedger::receiveNode(protocol::TMLedgerData& packet, SHAMapAddNode& san) if (!map.isSynching()) { if (packet.type() == protocol::liTX_NODE) + { mHaveTransactions = true; + } else + { mHaveState = true; + } if (mHaveTransactions && mHaveState) { @@ -1129,9 +1149,13 @@ struct PeerDataCounts while (i != counts.end()) { if (i->second < thresh) + { i = counts.erase(i); + } else + { ++i; + } } } diff --git a/src/xrpld/app/ledger/detail/InboundLedgers.cpp b/src/xrpld/app/ledger/detail/InboundLedgers.cpp index a5fdd889ec..be7577a2c3 100644 --- a/src/xrpld/app/ledger/detail/InboundLedgers.cpp +++ b/src/xrpld/app/ledger/detail/InboundLedgers.cpp @@ -174,8 +174,10 @@ public: // Stash the data for later processing and see if we need to // dispatch if (ledger->gotData(std::weak_ptr(peer), packet)) + { app_.getJobQueue().addJob( jtLEDGER_DATA, "ProcessLData", [ledger]() { ledger->runData(); }); + } return true; } @@ -290,9 +292,13 @@ public: for (auto const& it : mRecentFailures) { if (it.second > 1) + { ret[std::to_string(it.second)][jss::failed] = true; + } else + { ret[to_string(it.first)][jss::failed] = true; + } } } @@ -301,9 +307,13 @@ public: // getJson is expensive, so call without the lock std::uint32_t seq = it.second->getSeq(); if (seq > 1) + { ret[std::to_string(seq)] = it.second->getJson(0); + } else + { ret[to_string(it.first)] = it.second->getJson(0); + } } return ret; diff --git a/src/xrpld/app/ledger/detail/InboundTransactions.cpp b/src/xrpld/app/ledger/detail/InboundTransactions.cpp index b10adad438..f27f2c33f0 100644 --- a/src/xrpld/app/ledger/detail/InboundTransactions.cpp +++ b/src/xrpld/app/ledger/detail/InboundTransactions.cpp @@ -9,6 +9,7 @@ #include #include +#include #include #include @@ -167,13 +168,16 @@ public: auto& inboundSet = m_map[hash]; - if (inboundSet.mSeq < m_seq) - inboundSet.mSeq = m_seq; + inboundSet.mSeq = std::max(inboundSet.mSeq, m_seq); if (inboundSet.mSet) + { isNew = false; + } else + { inboundSet.mSet = set; + } inboundSet.mAcquire.reset(); } @@ -202,9 +206,13 @@ public: while (it != m_map.end()) { if (it->second.mSeq < minSeq || it->second.mSeq > maxSeq) + { it = m_map.erase(it); + } else + { ++it; + } } } } diff --git a/src/xrpld/app/ledger/detail/LedgerCleaner.cpp b/src/xrpld/app/ledger/detail/LedgerCleaner.cpp index 4266185591..3052f787dc 100644 --- a/src/xrpld/app/ledger/detail/LedgerCleaner.cpp +++ b/src/xrpld/app/ledger/detail/LedgerCleaner.cpp @@ -93,7 +93,9 @@ public: std::lock_guard lock(mutex_); if (maxRange_ == 0) + { map["status"] = "idle"; + } else { map["status"] = "running"; diff --git a/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp b/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp index e22351fc77..cb2e2e57ea 100644 --- a/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp +++ b/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp @@ -145,7 +145,7 @@ LedgerDeltaAcquire::addDataCallback(InboundLedger::Reason reason, OnDeltaDataCB& { ScopedLockType sl(mtx_); dataReadyCallbacks_.emplace_back(std::move(cb)); - if (reasons_.count(reason) == 0) + if (!reasons_.contains(reason)) { reasons_.emplace(reason); if (fullLedger_) @@ -185,14 +185,12 @@ LedgerDeltaAcquire::tryBuild(std::shared_ptr const& parent) onLedgerBuilt(sl); return fullLedger_; } - else - { - failed_ = true; - complete_ = false; - JLOG(journal_.error()) << "tryBuild failed " << hash_ << " with parent " - << parent->header().hash; - Throw("Cannot replay ledger"); - } + + failed_ = true; + complete_ = false; + JLOG(journal_.error()) << "tryBuild failed " << hash_ << " with parent " + << parent->header().hash; + Throw("Cannot replay ledger"); } void diff --git a/src/xrpld/app/ledger/detail/LedgerMaster.cpp b/src/xrpld/app/ledger/detail/LedgerMaster.cpp index 178e14f5c1..42d7f2ec6e 100644 --- a/src/xrpld/app/ledger/detail/LedgerMaster.cpp +++ b/src/xrpld/app/ledger/detail/LedgerMaster.cpp @@ -283,7 +283,9 @@ LedgerMaster::setValidLedger(std::shared_ptr const& l) app_.getOPs().setAmendmentWarned(); } else + { app_.getOPs().clearAmendmentWarned(); + } } } } @@ -350,10 +352,12 @@ LedgerMaster::canBeCurrent(std::shared_ptr const& ledger) LedgerIndex maxSeq = validLedger->header().seq + 10; if (closeTime > validLedger->header().parentCloseTime) + { maxSeq += std::chrono::duration_cast( closeTime - validLedger->header().parentCloseTime) .count() / 2; + } if (ledger->header().seq > maxSeq) { @@ -520,9 +524,13 @@ LedgerMaster::getFullValidatedRange(std::uint32_t& minVal, std::uint32_t& maxVal } if (maybeMin == std::nullopt) + { minVal = maxVal; + } else + { minVal = 1 + *maybeMin; + } return true; } @@ -544,9 +552,9 @@ LedgerMaster::getValidatedRange(std::uint32_t& minVal, std::uint32_t& maxVal) // Ensure we shrink the tips as much as possible. If we have 7-9 and // 8,9 are invalid, we don't want to see the 8 and shrink to just 9 // because then we'll have nothing when we could have 7. - while (pendingSaves.count(maxVal) > 0) + while (pendingSaves.contains(maxVal)) --maxVal; - while (pendingSaves.count(minVal) > 0) + while (pendingSaves.contains(minVal)) ++minVal; // Best effort for remaining exclusions @@ -555,9 +563,13 @@ LedgerMaster::getValidatedRange(std::uint32_t& minVal, std::uint32_t& maxVal) if ((v.first >= minVal) && (v.first <= maxVal)) { if (v.first > ((minVal + maxVal) / 2)) + { maxVal = v.first - 1; + } else + { minVal = v.first + 1; + } } } @@ -577,9 +589,13 @@ LedgerMaster::getEarliestFetch() std::uint32_t e = getClosedLedger()->header().seq; if (e > fetch_depth_) + { e -= fetch_depth_; + } else + { e = 0; + } return e; } @@ -1094,6 +1110,7 @@ LedgerMaster::consensusBuilt( // Of the ledgers with sufficient validations, // find the one with the highest sequence for (auto& v : count) + { if (v.second.valCount_ > neededValidations) { // If we still don't know the sequence, get it @@ -1109,6 +1126,7 @@ LedgerMaster::consensusBuilt( maxLedger = v.first; } } + } if (maxSeq > mValidLedgerSeq) { @@ -1221,8 +1239,10 @@ LedgerMaster::findNewLedgersToPublish(std::unique_lock& sl { // Can we try to acquire the ledger we need? if (!ledger && (++acqCount < ledger_fetch_size_)) + { ledger = app_.getInboundLedgers().acquire( *hash, seq, InboundLedger::Reason::GENERIC); + } } // Did we acquire the next ledger we need to publish? @@ -1850,7 +1870,9 @@ LedgerMaster::doAdvance(std::unique_lock& sl) JLOG(m_journal.trace()) << "advanceThread should acquire"; } else + { missing = std::nullopt; + } } if (missing) { @@ -2133,9 +2155,11 @@ LedgerMaster::txnIdFromIndex(uint32_t ledgerSeq, uint32_t txnIndex) return {}; for (auto it = lgr->txs.begin(); it != lgr->txs.end(); ++it) + { if (it->first && it->second && it->second->isFieldPresent(sfTransactionIndex) && it->second->getFieldU32(sfTransactionIndex) == txnIndex) return it->first->getTransactionID(); + } return {}; } diff --git a/src/xrpld/app/ledger/detail/LedgerReplayTask.cpp b/src/xrpld/app/ledger/detail/LedgerReplayTask.cpp index 8f225335c7..b878c840dd 100644 --- a/src/xrpld/app/ledger/detail/LedgerReplayTask.cpp +++ b/src/xrpld/app/ledger/detail/LedgerReplayTask.cpp @@ -183,7 +183,9 @@ LedgerReplayTask::tryAdvance(ScopedLockType& sl) parent_ = l; } else + { return; + } } complete_ = true; @@ -248,9 +250,13 @@ LedgerReplayTask::addDelta(std::shared_ptr const& delta) if (auto sptr = wptr.lock(); sptr) { if (!good) + { sptr->cancel(); + } else + { sptr->deltaReady(hash); + } } }); diff --git a/src/xrpld/app/ledger/detail/LedgerReplayer.cpp b/src/xrpld/app/ledger/detail/LedgerReplayer.cpp index 5aacf5b5a6..553ff91174 100644 --- a/src/xrpld/app/ledger/detail/LedgerReplayer.cpp +++ b/src/xrpld/app/ledger/detail/LedgerReplayer.cpp @@ -217,7 +217,9 @@ LedgerReplayer::sweep() it = subTasks.erase(it); } else + { ++it; + } } }; removeCannotLocked(skipLists_); diff --git a/src/xrpld/app/ledger/detail/LedgerToJson.cpp b/src/xrpld/app/ledger/detail/LedgerToJson.cpp index 038a5ae742..c0211059a1 100644 --- a/src/xrpld/app/ledger/detail/LedgerToJson.cpp +++ b/src/xrpld/app/ledger/detail/LedgerToJson.cpp @@ -74,7 +74,9 @@ void fillJsonBinary(Json::Value& json, bool closed, LedgerHeader const& info) { if (!closed) + { json[jss::closed] = false; + } else { json[jss::closed] = true; @@ -120,11 +122,13 @@ fillJsonTx( // If applicable, insert delivered amount if (txnType == ttPAYMENT || txnType == ttCHECK_CASH) + { RPC::insertDeliveredAmount( txJson[jss::meta], fill.ledger, txn, {txn->getTransactionID(), fill.ledger.seq(), *stMeta}); + } // If applicable, insert mpt issuance id RPC::insertMPTokenIssuanceID( @@ -154,11 +158,13 @@ fillJsonTx( // If applicable, insert delivered amount if (txnType == ttPAYMENT || txnType == ttCHECK_CASH) + { RPC::insertDeliveredAmount( txJson[jss::metaData], fill.ledger, txn, {txn->getTransactionID(), fill.ledger.seq(), *stMeta}); + } // If applicable, insert mpt issuance id RPC::insertMPTokenIssuanceID( @@ -233,9 +239,13 @@ fillJsonState(Json::Value& json, LedgerFill const& fill) obj[jss::tx_blob] = serializeHex(*sle); } else if (expanded) + { array.append(sle->getJson(JsonOptions::none)); + } else + { array.append(to_string(sle->key())); + } } } @@ -266,9 +276,13 @@ fillJsonQueue(Json::Value& json, LedgerFill const& fill) auto&& temp = fillJsonTx(fill, bBinary, bExpanded, tx.txn, nullptr); if (fill.context->apiVersion > 1) + { copyFrom(txJson, temp); + } else + { copyFrom(txJson[jss::tx], temp); + } } } @@ -279,14 +293,18 @@ fillJson(Json::Value& json, LedgerFill const& fill) // Is there a way to report this back? auto bFull = isFull(fill); if (isBinary(fill)) + { fillJsonBinary(json, !fill.ledger.open(), fill.ledger.header()); + } else + { fillJson( json, !fill.ledger.open(), fill.ledger.header(), bFull, (fill.context ? fill.context->apiVersion : RPC::apiMaximumSupportedVersion)); + } if (bFull || fill.options & LedgerFill::dumpTxrp) fillJsonTx(json, fill); @@ -318,8 +336,10 @@ getJson(LedgerFill const& fill) void copyFrom(Json::Value& to, Json::Value const& from) { - if (!to) // Short circuit this very common case. + if (!to) + { // Short circuit this very common case. to = from; + } else { // TODO: figure out if there is a way to remove this clause diff --git a/src/xrpld/app/ledger/detail/LocalTxs.cpp b/src/xrpld/app/ledger/detail/LocalTxs.cpp index 48bd80fbf2..8eb821a6c9 100644 --- a/src/xrpld/app/ledger/detail/LocalTxs.cpp +++ b/src/xrpld/app/ledger/detail/LocalTxs.cpp @@ -142,10 +142,12 @@ public: return acctSeq > seqProx; // Remove tefPAST_SEQ if (seqProx.isTicket() && acctSeq.value() <= seqProx.value()) + { // Keep ticket from the future. Note, however, that the // transaction will not be held indefinitely since LocalTxs // will only hold a transaction for a maximum of 5 ledgers. return false; + } // Ticket should have been created by now. Remove if ticket // does not exist. diff --git a/src/xrpld/app/ledger/detail/TransactionAcquire.cpp b/src/xrpld/app/ledger/detail/TransactionAcquire.cpp index 8cc26b1da6..18c5066064 100644 --- a/src/xrpld/app/ledger/detail/TransactionAcquire.cpp +++ b/src/xrpld/app/ledger/detail/TransactionAcquire.cpp @@ -6,6 +6,7 @@ #include +#include #include namespace xrpl { @@ -129,9 +130,13 @@ TransactionAcquire::trigger(std::shared_ptr const& peer) if (nodes.empty()) { if (mMap->isValid()) + { complete_ = true; + } else + { failed_ = true; + } done(); return; @@ -183,13 +188,17 @@ TransactionAcquire::takeNodes( if (d.first.isRoot()) { if (mHaveRoot) + { JLOG(journal_.debug()) << "Got root TXS node, already have it"; + } else if (!mMap->addRootNode(SHAMapHash{hash_}, d.second, nullptr).isGood()) { JLOG(journal_.warn()) << "TX acquire got bad root node"; } else + { mHaveRoot = true; + } } else if (!mMap->addKnownNode(d.first, d.second, &sf).isGood()) { @@ -234,8 +243,7 @@ TransactionAcquire::stillNeed() { ScopedLockType sl(mtx_); - if (timeouts_ > NORM_TIMEOUTS) - timeouts_ = NORM_TIMEOUTS; + 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 53eada2dec..048ef0d9b4 100644 --- a/src/xrpld/app/main/Application.cpp +++ b/src/xrpld/app/main/Application.cpp @@ -92,7 +92,7 @@ private: beast::Journal journal, std::chrono::milliseconds interval, boost::asio::io_context& ios) - : m_event(ev), m_journal(journal), m_probe(interval, ios), lastSample_{} + : m_event(ev), m_journal(journal), m_probe(interval, ios) { } @@ -278,11 +278,17 @@ public: // for the job queue if the server is configured as // "large" or "huge" if there are enough cores. if (config->NODE_SIZE >= 4 && count >= 16) + { count = 6 + std::min(count, 8); + } else if (config->NODE_SIZE >= 3 && count >= 8) + { count = 4 + std::min(count, 6); + } else + { count = 2 + std::min(count, 4); + } return count; }(config_), @@ -600,7 +606,7 @@ public: } void - gotTXSet(std::shared_ptr const& set, bool fromAcquire) + gotTXSet(std::shared_ptr const& set, bool fromAcquire) const { if (set) m_networkOPs->mapComplete(set, fromAcquire); @@ -823,7 +829,7 @@ public: } bool - initNodeStore() + initNodeStore() const { if (config_->doImport) { @@ -1573,7 +1579,9 @@ ApplicationImp::signalStop(std::string msg) if (!isTimeToStop.test_and_set(std::memory_order_acquire)) { if (msg.empty()) + { JLOG(m_journal.warn()) << "Server stopping"; + } else JLOG(m_journal.warn()) << "Server stopping: " << msg; diff --git a/src/xrpld/app/main/GRPCServer.cpp b/src/xrpld/app/main/GRPCServer.cpp index 7f4fb57fb7..a9810ae22b 100644 --- a/src/xrpld/app/main/GRPCServer.cpp +++ b/src/xrpld/app/main/GRPCServer.cpp @@ -205,9 +205,11 @@ Role GRPCServerImpl::CallData::getRole(bool isUnlimited) { if (isUnlimited) + { return Role::IDENTIFIED; - else - return Role::USER; + } + + return Role::USER; } template diff --git a/src/xrpld/app/main/LoadManager.cpp b/src/xrpld/app/main/LoadManager.cpp index 5d2bd9a81e..f0fc4085ac 100644 --- a/src/xrpld/app/main/LoadManager.cpp +++ b/src/xrpld/app/main/LoadManager.cpp @@ -13,7 +13,7 @@ namespace xrpl { LoadManager::LoadManager(Application& app, beast::Journal journal) - : app_(app), journal_(journal), lastHeartbeat_(), armed_(false) + : app_(app), journal_(journal), armed_(false) { } diff --git a/src/xrpld/app/main/Main.cpp b/src/xrpld/app/main/Main.cpp index 7c440d728c..03f8076ed1 100644 --- a/src/xrpld/app/main/Main.cpp +++ b/src/xrpld/app/main/Main.cpp @@ -69,9 +69,13 @@ adjustDescriptorLimit(int needed, beast::Journal j) { // If the limit is infinite, then we are good. if (rl.rlim_cur == RLIM_INFINITY) + { available = needed; + } else + { available = rl.rlim_cur; + } if (available < needed) { @@ -195,8 +199,10 @@ public: operator()(beast::unit_test::suite_info const& s) { for (auto& sel : selectors_) + { if (sel(s)) return true; + } return false; } @@ -277,8 +283,10 @@ runUnitTests( } for (std::size_t i = 0; i < num_jobs; ++i) + { children.emplace_back( boost::process::v1::exe = exe_name, boost::process::v1::args = args); + } int bad_child_exits = 0; int terminated_child_exits = 0; @@ -305,17 +313,15 @@ runUnitTests( return EXIT_FAILURE; return EXIT_SUCCESS; } - else - { - // child - multi_runner_child runner{num_jobs, quiet, log}; - runner.arg(argument); - auto const anyFailed = runner.run_multi(multi_selector(pattern)); - if (anyFailed) - return EXIT_FAILURE; - return EXIT_SUCCESS; - } + // child + multi_runner_child runner{num_jobs, quiet, log}; + runner.arg(argument); + auto const anyFailed = runner.run_multi(multi_selector(pattern)); + + if (anyFailed) + return EXIT_FAILURE; + return EXIT_SUCCESS; } #endif // ENABLE_TESTS @@ -468,13 +474,13 @@ run(int argc, char** argv) return 1; } - if (vm.count("help")) + if (vm.contains("help")) { printHelp(desc); return 0; } - if (vm.count("version")) + if (vm.contains("version")) { std::cout << "rippled version " << BuildInfo::getVersionString() << std::endl; std::cout << "Git commit hash: " << xrpl::git::getCommitHash() << std::endl; @@ -493,57 +499,53 @@ run(int argc, char** argv) // Run the unit tests if requested. // The unit tests will exit the application with an appropriate return code. // - if (vm.count("unittest")) + if (vm.contains("unittest")) { std::string argument; - if (vm.count("unittest-arg")) + if (vm.contains("unittest-arg")) argument = vm["unittest-arg"].as(); std::size_t numJobs = 1; bool unittestChild = false; - if (vm.count("unittest-jobs")) + if (vm.contains("unittest-jobs")) numJobs = std::max(numJobs, vm["unittest-jobs"].as()); - unittestChild = bool(vm.count("unittest-child")); + unittestChild = vm.contains("unittest-child"); return runUnitTests( vm["unittest"].as(), argument, - bool(vm.count("quiet")), - bool(vm.count("unittest-log")), + vm.contains("quiet"), + vm.contains("unittest-log"), unittestChild, - bool(vm.count("unittest-ipv6")), + vm.contains("unittest-ipv6"), numJobs, argc, argv); } // LCOV_EXCL_START - else + + if (vm.contains("unittest-jobs")) { - if (vm.count("unittest-jobs")) - { - // unittest jobs only makes sense with `unittest` - std::cerr << "rippled: '--unittest-jobs' specified without " - "'--unittest'.\n"; - std::cerr << "To run the unit tests the '--unittest' option must " - "be present.\n"; - return 1; - } + // unittest jobs only makes sense with `unittest` + std::cerr << "rippled: '--unittest-jobs' specified without " + "'--unittest'.\n"; + std::cerr << "To run the unit tests the '--unittest' option must " + "be present.\n"; + return 1; } + #endif // ENABLE_TESTS auto config = std::make_unique(); - auto configFile = vm.count("conf") ? vm["conf"].as() : std::string(); + auto configFile = vm.contains("conf") ? vm["conf"].as() : std::string(); // config file, quiet flag. config->setup( - configFile, - bool(vm.count("quiet")), - bool(vm.count("silent")), - bool(vm.count("standalone"))); + configFile, vm.contains("quiet"), vm.contains("silent"), vm.contains("standalone")); - if (vm.count("vacuum")) + if (vm.contains("vacuum")) { if (config->standalone()) { @@ -609,21 +611,21 @@ run(int argc, char** argv) } } - if (vm.count("start")) + if (vm.contains("start")) { config->START_UP = StartUpType::FRESH; } - if (vm.count("import")) + if (vm.contains("import")) config->doImport = true; - if (vm.count("ledger")) + if (vm.contains("ledger")) { config->START_LEDGER = vm["ledger"].as(); - if (vm.count("replay")) + if (vm.contains("replay")) { config->START_UP = StartUpType::REPLAY; - if (vm.count("trap_tx_hash")) + if (vm.contains("trap_tx_hash")) { uint256 tmp = {}; auto hash = vm["trap_tx_hash"].as(); @@ -641,25 +643,27 @@ run(int argc, char** argv) } } else + { config->START_UP = StartUpType::LOAD; + } } - else if (vm.count("ledgerfile")) + else if (vm.contains("ledgerfile")) { config->START_LEDGER = vm["ledgerfile"].as(); config->START_UP = StartUpType::LOAD_FILE; } - else if (vm.count("load") || config->FAST_LOAD) + else if (vm.contains("load") || config->FAST_LOAD) { config->START_UP = StartUpType::LOAD; } - if (vm.count("trap_tx_hash") && vm.count("replay") == 0) + if (vm.contains("trap_tx_hash") && !vm.contains("replay")) { std::cerr << "Cannot use trap option without replay option" << std::endl; return -1; } - if (vm.count("net") && !config->FAST_LOAD) + if (vm.contains("net") && !config->FAST_LOAD) { if ((config->START_UP == StartUpType::LOAD) || (config->START_UP == StartUpType::REPLAY)) { @@ -670,14 +674,14 @@ run(int argc, char** argv) config->START_UP = StartUpType::NETWORK; } - if (vm.count("valid")) + if (vm.contains("valid")) { config->START_VALID = true; } // Override the RPC destination IP address. This must // happen after the config file is loaded. - if (vm.count("rpc_ip")) + if (vm.contains("rpc_ip")) { auto endpoint = beast::IP::Endpoint::from_string_checked(vm["rpc_ip"].as()); if (!endpoint) @@ -689,7 +693,7 @@ run(int argc, char** argv) if (endpoint->port() == 0) { std::cerr << "No port specified in rpc_ip.\n"; - if (vm.count("rpc_port")) + if (vm.contains("rpc_port")) { std::cerr << "WARNING: using deprecated rpc_port param.\n"; try @@ -705,13 +709,15 @@ run(int argc, char** argv) } } else + { return -1; + } } config->rpc_ip = std::move(*endpoint); } - if (vm.count("quorum")) + if (vm.contains("quorum")) { try { @@ -732,15 +738,19 @@ run(int argc, char** argv) using namespace beast::severities; Severity thresh = kInfo; - if (vm.count("quiet")) + if (vm.contains("quiet")) + { thresh = kFatal; - else if (vm.count("verbose")) + } + else if (vm.contains("verbose")) + { thresh = kTrace; + } auto logs = std::make_unique(thresh); // No arguments. Run server. - if (!vm.count("parameters")) + if (!vm.contains("parameters")) { // TODO: this comment can be removed in a future release - // say 1.7 or higher @@ -760,7 +770,7 @@ run(int argc, char** argv) if (!adjustDescriptorLimit(1024, logs->journal("Application"))) return -1; - if (vm.count("debug")) + if (vm.contains("debug")) setDebugLogSink(logs->makeSink("Debug", beast::severities::kTrace)); auto app = diff --git a/src/xrpld/app/main/NodeIdentity.cpp b/src/xrpld/app/main/NodeIdentity.cpp index 3019caeb31..bc2c943b10 100644 --- a/src/xrpld/app/main/NodeIdentity.cpp +++ b/src/xrpld/app/main/NodeIdentity.cpp @@ -12,7 +12,7 @@ getNodeIdentity(Application& app, boost::program_options::variables_map const& c { std::optional seed; - if (cmdline.count("nodeid")) + if (cmdline.contains("nodeid")) { seed = parseGenericSeed(cmdline["nodeid"].as(), false); @@ -37,7 +37,7 @@ getNodeIdentity(Application& app, boost::program_options::variables_map const& c auto db = app.getWalletDB().checkoutDb(); - if (cmdline.count("newnodeid") != 0) + if (cmdline.contains("newnodeid")) clearNodeIdentity(*db); return getNodeIdentity(*db); diff --git a/src/xrpld/app/misc/FeeVoteImpl.cpp b/src/xrpld/app/misc/FeeVoteImpl.cpp index 5cb203115a..764a9564ad 100644 --- a/src/xrpld/app/misc/FeeVoteImpl.cpp +++ b/src/xrpld/app/misc/FeeVoteImpl.cpp @@ -177,9 +177,13 @@ FeeVoteImpl::doVoting( { auto const vote = field->xrp(); if (isLegalAmountSigned(vote)) + { value.addVote(vote); + } else + { value.noVote(); + } } else { @@ -207,12 +211,16 @@ FeeVoteImpl::doVoting( auto const vote = *field; if (vote <= std::numeric_limits::max() && isLegalAmountSigned(XRPAmount{unsafe_cast(vote)})) + { value.addVote(XRPAmount{unsafe_cast(vote)}); + } else + { // Invalid amounts will be treated as if they're // not provided. Don't throw because this value is // provided by an external entity. value.noVote(); + } } else { diff --git a/src/xrpld/app/misc/NegativeUNLVote.cpp b/src/xrpld/app/misc/NegativeUNLVote.cpp index 6673785b61..8f0ba5255a 100644 --- a/src/xrpld/app/misc/NegativeUNLVote.cpp +++ b/src/xrpld/app/misc/NegativeUNLVote.cpp @@ -52,7 +52,7 @@ NegativeUNLVote::doVoting( { auto nid = calcNodeID(k); negUnlNodeIDs.emplace(nid); - if (!nidToKeyMap.count(nid)) + if (!nidToKeyMap.contains(nid)) { nidToKeyMap.emplace(nid, k); } @@ -175,7 +175,7 @@ NegativeUNLVote::buildScoreTable( for (auto const& v : validations.getTrustedForLedger(ledgerAncestors[numAncestors - 1 - i], seq - 2 - i)) { - if (scoreTable.count(v->getNodeID())) + if (scoreTable.contains(v->getNodeID())) ++scoreTable[v->getNodeID()]; } } @@ -195,24 +195,20 @@ NegativeUNLVote::buildScoreTable( << " The reliability measurement could be wrong."; return {}; } - else if ( - myValidationCount > negativeUNLMinLocalValsToVote && + if (myValidationCount > negativeUNLMinLocalValsToVote && myValidationCount <= FLAG_LEDGER_INTERVAL) { return scoreTable; } - else - { - // cannot happen because validations.getTrustedForLedger does not - // return multiple validations of the same ledger from a validator. - JLOG(j_.error()) << "N-UNL: ledger " << seq << ". Local node issued " << myValidationCount - << " validations in last " << FLAG_LEDGER_INTERVAL - << " ledgers. Too many!"; - return {}; - } + + // cannot happen because validations.getTrustedForLedger does not + // return multiple validations of the same ledger from a validator. + JLOG(j_.error()) << "N-UNL: ledger " << seq << ". Local node issued " << myValidationCount + << " validations in last " << FLAG_LEDGER_INTERVAL << " ledgers. Too many!"; + return {}; } -NegativeUNLVote::Candidates const +NegativeUNLVote::Candidates NegativeUNLVote::findAllCandidates( hash_set const& unl, hash_set const& negUnl, @@ -225,7 +221,7 @@ NegativeUNLVote::findAllCandidates( std::size_t negativeListed = 0; for (auto const& n : unl) { - if (negUnl.count(n)) + if (negUnl.contains(n)) ++negativeListed; } bool const result = negativeListed < maxNegativeListed; @@ -246,8 +242,8 @@ NegativeUNLVote::findAllCandidates( // (2) has less than negativeUNLLowWaterMark validations, // (3) is not in negUnl, and // (4) is not a new validator. - if (canAdd && score < negativeUNLLowWaterMark && !negUnl.count(nodeId) && - !newValidators_.count(nodeId)) + if (canAdd && score < negativeUNLLowWaterMark && !negUnl.contains(nodeId) && + !newValidators_.contains(nodeId)) { JLOG(j_.trace()) << "N-UNL: toDisable candidate " << nodeId; candidates.toDisableCandidates.push_back(nodeId); @@ -256,7 +252,7 @@ NegativeUNLVote::findAllCandidates( // Find toReEnable Candidates: check if // (1) has more than negativeUNLHighWaterMark validations, // (2) is in negUnl - if (score > negativeUNLHighWaterMark && negUnl.count(nodeId)) + if (score > negativeUNLHighWaterMark && negUnl.contains(nodeId)) { JLOG(j_.trace()) << "N-UNL: toReEnable candidate " << nodeId; candidates.toReEnableCandidates.push_back(nodeId); @@ -277,7 +273,7 @@ NegativeUNLVote::findAllCandidates( { for (auto const& n : negUnl) { - if (!unl.count(n)) + if (!unl.contains(n)) { candidates.toReEnableCandidates.push_back(n); } @@ -292,7 +288,7 @@ NegativeUNLVote::newValidators(LedgerIndex seq, hash_set const& nowTrust std::lock_guard lock(mutex_); for (auto const& n : nowTrusted) { - if (newValidators_.find(n) == newValidators_.end()) + if (!newValidators_.contains(n)) { JLOG(j_.trace()) << "N-UNL: add a new validator " << n << " at ledger seq=" << seq; newValidators_[n] = seq; diff --git a/src/xrpld/app/misc/NegativeUNLVote.h b/src/xrpld/app/misc/NegativeUNLVote.h index 95646af034..601ac7d060 100644 --- a/src/xrpld/app/misc/NegativeUNLVote.h +++ b/src/xrpld/app/misc/NegativeUNLVote.h @@ -172,7 +172,7 @@ private: * @param scoreTable the score table * @return the candidates to disable and the candidates to re-enable */ - Candidates const + Candidates findAllCandidates( hash_set const& unl, hash_set const& negUnl, diff --git a/src/xrpld/app/misc/NetworkOPs.cpp b/src/xrpld/app/misc/NetworkOPs.cpp index 18abab674d..d709981c46 100644 --- a/src/xrpld/app/misc/NetworkOPs.cpp +++ b/src/xrpld/app/misc/NetworkOPs.cpp @@ -752,7 +752,7 @@ private: DispatchState mDispatchState = DispatchState::none; std::vector mTransactions; - StateAccounting accounting_{}; + StateAccounting accounting_; std::set pendingValidations_; std::mutex validationsMutex_; @@ -1012,9 +1012,13 @@ NetworkOPsImp::processHeartbeatTimer() auto origMode = mMode.load(); CLOG(clog.ss()) << "mode: " << strOperatingMode(origMode, true); if (mMode == OperatingMode::SYNCING) + { setMode(OperatingMode::SYNCING); + } else if (mMode == OperatingMode::CONNECTED) + { setMode(OperatingMode::CONNECTED); + } auto newMode = mMode.load(); if (origMode != newMode) { @@ -1224,9 +1228,13 @@ NetworkOPsImp::processTransaction( return; if (bLocal) + { doTransactionSync(transaction, bUnlimited, failType); + } else + { doTransactionAsync(transaction, bUnlimited, failType); + } } void @@ -1287,7 +1295,7 @@ NetworkOPsImp::doTransactionSyncBatch( { apply(lock); - if (mTransactions.size()) + if (!mTransactions.empty()) { // More transactions need to be applied, but by another job. if (m_job_queue.addJob(jtBATCH, "TxBatchSync", [this]() { transactionBatch(); })) @@ -1342,7 +1350,9 @@ NetworkOPsImp::processTransactionSet(CanonicalTXSet const& set) } if (mTransactions.empty()) + { mTransactions.swap(transactions); + } else { mTransactions.reserve(mTransactions.size() + transactions.size()); @@ -1371,7 +1381,7 @@ NetworkOPsImp::transactionBatch() if (mDispatchState == DispatchState::running) return; - while (mTransactions.size()) + while (!mTransactions.empty()) { apply(lock); } @@ -1606,7 +1616,9 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) if (!submit_held.empty()) { if (mTransactions.empty()) + { mTransactions.swap(submit_held); + } else { mTransactions.reserve(mTransactions.size() + submit_held.size()); @@ -1804,7 +1816,9 @@ NetworkOPsImp::checkLastClosedLedger(Overlay::PeerSequence const& peerList, uint switchLedgers = false; } else + { networkClosed = closedLedger; + } if (!switchLedgers) return false; @@ -1812,8 +1826,10 @@ NetworkOPsImp::checkLastClosedLedger(Overlay::PeerSequence const& peerList, uint auto consensus = m_ledgerMaster.getLedgerByHash(closedLedger); if (!consensus) + { consensus = registry_.getInboundLedgers().acquire( closedLedger, 0, InboundLedger::Reason::CONSENSUS); + } if (consensus && (!m_ledgerMaster.canBeCurrent(consensus) || @@ -1865,9 +1881,13 @@ NetworkOPsImp::switchLastClosedLedger(std::shared_ptr const& newLC auto const lastVal = registry_.getLedgerMaster().getValidatedLedger(); std::optional rules; if (lastVal) + { rules = makeRulesGivenLedger(*lastVal, registry_.app().config().features); + } else + { rules.emplace(registry_.app().config().features); + } registry_.openLedger().accept( registry_.app(), *rules, @@ -2187,7 +2207,9 @@ NetworkOPsImp::pubServer() jvObj[jss::load_factor_fee_reference] = f.em->referenceFeeLevel.jsonClipped(); } else + { jvObj[jss::load_factor] = f.loadFactorServer; + } mLastFeeSummary = f; @@ -2411,9 +2433,13 @@ NetworkOPsImp::recvValidation(std::shared_ptr const& val, std::str try { if (pendingValidations_.contains(val->getLedgerHash())) + { bypassAccept = BypassAccept::yes; + } else + { pendingValidations_.insert(val->getLedgerHash()); + } scope_unlock unlock(lock); handleNewValidation(registry_.app(), val, source, bypassAccept, m_journal); } @@ -2555,10 +2581,14 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) if (!human) { if (when) + { info[jss::validator_list_expires] = safe_cast(when->time_since_epoch().count()); + } else + { info[jss::validator_list_expires] = 0; + } } else { @@ -2578,9 +2608,13 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) x[jss::expiration] = to_string(*when); if (*when > registry_.timeKeeper().now()) + { x[jss::status] = "active"; + } else + { x[jss::status] = "expired"; + } } } else @@ -2713,22 +2747,30 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) } if (escalationMetrics.openLedgerFeeLevel != escalationMetrics.referenceFeeLevel && (admin || loadFactorFeeEscalation != loadFactor)) + { info[jss::load_factor_fee_escalation] = escalationMetrics.openLedgerFeeLevel.decimalFromReference( escalationMetrics.referenceFeeLevel); + } if (escalationMetrics.minProcessingFeeLevel != escalationMetrics.referenceFeeLevel) + { info[jss::load_factor_fee_queue] = escalationMetrics.minProcessingFeeLevel.decimalFromReference( escalationMetrics.referenceFeeLevel); + } } bool valid = false; auto lpClosed = m_ledgerMaster.getValidatedLedger(); if (lpClosed) + { valid = true; + } else + { lpClosed = m_ledgerMaster.getClosedLedger(); + } if (lpClosed) { @@ -2775,15 +2817,23 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) } if (valid) + { info[jss::validated_ledger] = l; + } else + { info[jss::closed_ledger] = l; + } auto lpPublished = m_ledgerMaster.getPublishedLedger(); if (!lpPublished) + { info[jss::published_ledger] = "none"; + } else if (lpPublished->header().seq != lpClosed->header().seq) + { info[jss::published_ledger] = lpPublished->header().seq; + } } accounting_.json(info); @@ -2953,7 +3003,9 @@ NetworkOPsImp::pubLedger(std::shared_ptr const& lpAccepted) ++it; } else + { it = mStreamMaps[sLedger].erase(it); + } } } @@ -2971,7 +3023,9 @@ NetworkOPsImp::pubLedger(std::shared_ptr const& lpAccepted) ++it; } else + { it = mStreamMaps[sBookChanges].erase(it); + } } } @@ -3166,7 +3220,9 @@ NetworkOPsImp::pubValidatedTransaction( ++it; } else + { it = mStreamMaps[sTransactions].erase(it); + } } it = mStreamMaps[sRTTransactions].begin(); @@ -3183,7 +3239,9 @@ NetworkOPsImp::pubValidatedTransaction( ++it; } else + { it = mStreamMaps[sRTTransactions].erase(it); + } } } @@ -3228,7 +3286,9 @@ NetworkOPsImp::pubAccountTransaction( ++iProposed; } else + { it = simiIt->second.erase(it); + } } } @@ -3246,7 +3306,9 @@ NetworkOPsImp::pubAccountTransaction( ++iAccepted; } else + { it = simiIt->second.erase(it); + } } } @@ -3360,7 +3422,9 @@ NetworkOPsImp::pubProposedAccountTransaction( ++iProposed; } else + { it = simiIt->second.erase(it); + } } } } @@ -3375,9 +3439,11 @@ NetworkOPsImp::pubProposedAccountTransaction( MultiApiJson jvObj = transJson(tx, result, false, ledger, std::nullopt); for (InfoSub::ref isrListener : notify) + { jvObj.visit( isrListener->getApiVersion(), // [&](Json::Value const& jv) { isrListener->send(jv, true); }); + } XRPL_ASSERT( jvObj.isMember(jss::account_history_tx_stream) == MultiApiJson::none, @@ -3729,10 +3795,8 @@ NetworkOPsImp::addAccountHistoryJob(SubAccountHistoryInfoWeak subInfo) << " done, found last tx."; return; } - else - { - sendMultiApiJson(jvTx, false); - } + + sendMultiApiJson(jvTx, false); } if (marker) @@ -3892,7 +3956,9 @@ bool NetworkOPsImp::subBook(InfoSub::ref isrListener, Book const& book) { if (auto listeners = registry_.getOrderBookDB().makeBookListeners(book)) + { listeners->addSubscriber(isrListener); + } else { // LCOV_EXCL_START @@ -4150,7 +4216,7 @@ NetworkOPsImp::tryRemoveRpcSub(std::string const& strUrl) // this entry before removing for (SubMapType const& map : mStreamMaps) { - if (map.find(pInfo->getSeq()) != map.end()) + if (map.contains(pInfo->getSeq())) return false; } mRpcSubMap.erase(strUrl); @@ -4213,9 +4279,13 @@ NetworkOPsImp::getBookPage( auto const ledgerIndex = view.succ(uTipIndex, uBookEnd); if (ledgerIndex) + { sleOfferDir = view.read(keylet::page(*ledgerIndex)); + } else + { sleOfferDir.reset(); + } if (!sleOfferDir) { diff --git a/src/xrpld/app/misc/SHAMapStoreImp.cpp b/src/xrpld/app/misc/SHAMapStoreImp.cpp index 60dcd90388..13746369f5 100644 --- a/src/xrpld/app/misc/SHAMapStoreImp.cpp +++ b/src/xrpld/app/misc/SHAMapStoreImp.cpp @@ -143,7 +143,7 @@ SHAMapStoreImp::makeNodeStore(int readThreads) SavedState state = state_db_.getState(); auto writableBackend = makeBackendRotating(state.writableDb); auto archiveBackend = makeBackendRotating(state.archiveDb); - if (!state.writableDb.size()) + if (state.writableDb.empty()) { state.writableDb = writableBackend->getName(); state.archiveDb = archiveBackend->getName(); @@ -248,7 +248,9 @@ SHAMapStoreImp::run() validatedLedger = std::move(newLedger_); } else + { continue; + } } LedgerIndex const validatedSeq = validatedLedger->header().seq; @@ -385,15 +387,21 @@ SHAMapStoreImp::dbPaths() ++it) { if (!state.writableDb.compare(it->path().string())) + { writableDbExists = true; + } else if (!state.archiveDb.compare(it->path().string())) + { archiveDbExists = true; + } else if (!dbPrefix_.compare(it->path().stem().string())) + { pathsToDelete.push_back(it->path()); + } } - if ((!writableDbExists && state.writableDb.size()) || - (!archiveDbExists && state.archiveDb.size()) || (writableDbExists != archiveDbExists) || + if ((!writableDbExists && !state.writableDb.empty()) || + (!archiveDbExists && !state.archiveDb.empty()) || (writableDbExists != archiveDbExists) || state.writableDb.empty() != state.archiveDb.empty()) { boost::filesystem::path stateDbPathName = app_.config().legacy("database_path"); @@ -428,7 +436,7 @@ SHAMapStoreImp::makeBackendRotating(std::string path) Section section{app_.config().section(ConfigSection::nodeDatabase())}; boost::filesystem::path newPath; - if (path.size()) + if (!path.empty()) { newPath = path; } diff --git a/src/xrpld/app/misc/detail/AccountTxPaging.cpp b/src/xrpld/app/misc/detail/AccountTxPaging.cpp index 63457f00ac..4e79b53ed0 100644 --- a/src/xrpld/app/misc/detail/AccountTxPaging.cpp +++ b/src/xrpld/app/misc/detail/AccountTxPaging.cpp @@ -27,13 +27,17 @@ convertBlobsToTxResult( // if properly formed meta is available we can use it to generate ctid if (metaset->getAsObject().isFieldPresent(sfTransactionIndex)) + { tr->setStatus( Transaction::sqlTransactionStatus(status), ledger_index, metaset->getAsObject().getFieldU32(sfTransactionIndex), app.getNetworkIDService().getNetworkID()); + } else + { tr->setStatus(Transaction::sqlTransactionStatus(status), ledger_index); + } to.emplace_back(std::move(tr), metaset); }; diff --git a/src/xrpld/app/misc/detail/AmendmentTable.cpp b/src/xrpld/app/misc/detail/AmendmentTable.cpp index 5bdd604828..2b7005f4cc 100644 --- a/src/xrpld/app/misc/detail/AmendmentTable.cpp +++ b/src/xrpld/app/misc/detail/AmendmentTable.cpp @@ -40,8 +40,10 @@ parseSection(Section const& section) uint256 id; if (!id.parseHex(match[1])) + { Throw( "Invalid amendment ID '" + match[1] + "' in [" + section.name() + "]"); + } names.push_back(std::make_pair(id, match[2])); } @@ -525,11 +527,10 @@ AmendmentTableImpl::AmendmentTableImpl( " in favor of data in db/wallet.db."; break; } - else - { // Otherwise transfer config data into the table - detect_conflict.insert(a.first); - persistVote(a.first, a.second, AmendmentVote::up); - } + + // Otherwise transfer config data into the table + detect_conflict.insert(a.first); + persistVote(a.first, a.second, AmendmentVote::up); } // Parse vetoed amendments from config @@ -541,18 +542,17 @@ AmendmentTableImpl::AmendmentTableImpl( " in favor of data in db/wallet.db."; break; } + + // Otherwise transfer config data into the table + if (!detect_conflict.contains(a.first)) + { + persistVote(a.first, a.second, AmendmentVote::down); + } else - { // Otherwise transfer config data into the table - if (detect_conflict.count(a.first) == 0) - { - persistVote(a.first, a.second, AmendmentVote::down); - } - else - { - JLOG(j_.warn()) << "[veto_amendments] section in config has amendment " << '(' - << a.first << ", " << a.second - << ") both [veto_amendments] and [amendments]."; - } + { + JLOG(j_.warn()) << "[veto_amendments] section in config has amendment " << '(' + << a.first << ", " << a.second + << ") both [veto_amendments] and [amendments]."; } } @@ -745,7 +745,7 @@ AmendmentTableImpl::doValidation(std::set const& enabled) const for (auto const& e : amendmentMap_) { if (e.second.supported && e.second.vote == AmendmentVote::up && - (enabled.count(e.first) == 0)) + (!enabled.contains(e.first))) { amendments.push_back(e.first); JLOG(j_.info()) << "Voting for amendment " << e.second.name; @@ -927,9 +927,13 @@ AmendmentTableImpl::injectJson( if (!fs.enabled && isAdmin) { if (fs.vote == AmendmentVote::obsolete) + { v[jss::vetoed] = "Obsolete"; + } else + { v[jss::vetoed] = fs.vote == AmendmentVote::down; + } } v[jss::enabled] = fs.enabled; diff --git a/src/xrpld/app/misc/detail/TxQ.cpp b/src/xrpld/app/misc/detail/TxQ.cpp index 0dd0fc1063..2b90cb8161 100644 --- a/src/xrpld/app/misc/detail/TxQ.cpp +++ b/src/xrpld/app/misc/detail/TxQ.cpp @@ -386,23 +386,29 @@ TxQ::canBeHeld( // transaction fills the _first_ sequence hole for the account. auto const txSeqProx = tx.getSeqProxy(); if (txSeqProx.isTicket()) + { // Tickets always follow sequence-based transactions, so a ticket // cannot unblock a sequence-based transaction. return telCAN_NOT_QUEUE_FULL; + } // This is the next queuable sequence-based SeqProxy for the account. SeqProxy const nextQueuable = nextQueuableSeqImpl(sleAccount, lock); if (txSeqProx != nextQueuable) + { // The provided transaction does not fill the next open sequence gap. return telCAN_NOT_QUEUE_FULL; + } // Make sure they are not just topping off the account's queued // sequence-based transactions. if (auto const nextTxIter = txQAcct.transactions.upper_bound(nextQueuable); nextTxIter != txQAcct.transactions.end() && nextTxIter->first.isSeq()) + { // There is a next transaction and it is sequence based. They are // filling a real gap. Allow it. return tesSUCCESS; + } return telCAN_NOT_QUEUE_FULL; } @@ -718,9 +724,11 @@ TxQ::apply( if (txSeqProx.isTicket() && !view.exists(keylet::ticket(account, txSeqProx))) { if (txSeqProx.value() < acctSeqProx.value()) + { // The ticket number is low enough that it should already be // in the ledger if it were ever going to exist. return {tefNO_TICKET, false}; + } // We don't queue transactions that use Tickets unless // we can find the Ticket in the ledger. @@ -762,9 +770,11 @@ TxQ::apply( TxQAccount::TxMap::iterator const firstIter = acctTxs.lower_bound(acctSeqProx); if (firstIter == acctTxs.end()) + { // Even though there may be transactions in the queue, there are // none that we should pay attention to. return {}; + } return {TxIter{firstIter, acctTxs.end()}}; }(); @@ -949,9 +959,13 @@ TxQ::apply( if (txSeqProx.isSeq()) { if (txSeqProx < acctSeqProx) + { return {tefPAST_SEQ, false}; - else if (txSeqProx > acctSeqProx) + } + if (txSeqProx > acctSeqProx) + { return {terPRE_SEQ, false}; + } } } else if (!replacedTxIter) @@ -1301,9 +1315,13 @@ TxQ::processClosedLedger(Application& app, ReadView const& view, bool timeLeap) for (auto txQAccountIter = byAccount_.begin(); txQAccountIter != byAccount_.end();) { if (txQAccountIter->second.empty()) + { txQAccountIter = byAccount_.erase(txQAccountIter); + } else + { ++txQAccountIter; + } } } @@ -1393,9 +1411,13 @@ TxQ::accept(Application& app, OpenView& view) candidateIter->retriesRemaining <= 0) { if (candidateIter->retriesRemaining <= 0) + { account.retryPenalty = true; + } else + { account.dropPenalty = true; + } JLOG(j_.debug()) << "Queued transaction " << candidateIter->txID << " failed with " << transToken(txnResult) << ". Remove from queue."; candidateIter = eraseAndAdvance(candidateIter); @@ -1406,9 +1428,13 @@ TxQ::accept(Application& app, OpenView& view) << transToken(txnResult) << ". Leave in queue." << " Applied: " << didApply << ". Flags: " << candidateIter->flags; if (account.retryPenalty && candidateIter->retriesRemaining > 2) + { candidateIter->retriesRemaining = 1; + } else + { --candidateIter->retriesRemaining; + } candidateIter->lastResult = txnResult; if (account.dropPenalty && account.transactions.size() > 1 && isFull<95>()) { @@ -1447,7 +1473,9 @@ TxQ::accept(Application& app, OpenView& view) } } else + { ++candidateIter; + } } } else @@ -1462,9 +1490,13 @@ TxQ::accept(Application& app, OpenView& view) // reordered. LedgerHash const& parentHash = view.header().parentHash; if (parentHash == parentHash_) + { JLOG(j_.warn()) << "Parent ledger hash unchanged from " << parentHash; + } else + { parentHash_ = parentHash; + } [[maybe_unused]] auto const startingSize = byFee_.size(); // byFee_ doesn't "own" the candidate objects inside it, so it's @@ -1532,12 +1564,14 @@ TxQ::nextQueuableSeqImpl( TxQAccount::TxMap::const_iterator txIter = acctTxs.lower_bound(acctSeqProx); if (txIter == acctTxs.end() || !txIter->first.isSeq() || txIter->first != acctSeqProx) + { // Either... // o There are no queued sequence-based transactions equal to or // following acctSeqProx or // o acctSeqProx is not currently in the queue. // So acctSeqProx is as good as it gets. return acctSeqProx; + } // There are sequence-based transactions queued that follow acctSeqProx. // Locate the first opening to put a transaction into. diff --git a/src/xrpld/app/misc/detail/ValidatorList.cpp b/src/xrpld/app/misc/detail/ValidatorList.cpp index 73db2f8bdb..386b96387e 100644 --- a/src/xrpld/app/misc/detail/ValidatorList.cpp +++ b/src/xrpld/app/misc/detail/ValidatorList.cpp @@ -158,7 +158,7 @@ ValidatorList::load( status = PublisherStatus::revoked; } - if (publisherLists_.count(id)) + if (publisherLists_.contains(id)) { JLOG(j_.warn()) << "Duplicate validator list publisher key: " << key; continue; @@ -508,34 +508,29 @@ splitMessageParts( 1); return messages.back().numVLs; } - else + + std::optional smallMsg; + smallMsg.emplace(); + smallMsg->set_version(largeMsg.version()); + smallMsg->set_manifest(largeMsg.manifest()); + + for (std::size_t i = begin; i < end; ++i) { - std::optional smallMsg; - smallMsg.emplace(); - smallMsg->set_version(largeMsg.version()); - smallMsg->set_manifest(largeMsg.manifest()); - - for (std::size_t i = begin; i < end; ++i) - { - *smallMsg->add_blobs() = largeMsg.blobs(i); - } - - if (Message::totalSize(*smallMsg) > maxSize) - { - // free up the message space - smallMsg.reset(); - return splitMessage(messages, largeMsg, maxSize, begin, end); - } - else - { - messages.emplace_back( - std::make_shared(*smallMsg, protocol::mtVALIDATOR_LIST_COLLECTION), - sha512Half(*smallMsg), - smallMsg->blobs_size()); - return messages.back().numVLs; - } + *smallMsg->add_blobs() = largeMsg.blobs(i); } - return 0; + + if (Message::totalSize(*smallMsg) > maxSize) + { + // free up the message space + smallMsg.reset(); + return splitMessage(messages, largeMsg, maxSize, begin, end); + } + + messages.emplace_back( + std::make_shared(*smallMsg, protocol::mtVALIDATOR_LIST_COLLECTION), + sha512Half(*smallMsg), + smallMsg->blobs_size()); + return messages.back().numVLs; } // Build a v1 protocol message using only the current VL @@ -608,14 +603,12 @@ buildValidatorListMessage( // split into smaller messages return splitMessage(messages, msg, maxSize); } - else - { - messages.emplace_back( - std::make_shared(msg, protocol::mtVALIDATOR_LIST_COLLECTION), - sha512Half(msg), - msg.blobs_size()); - return messages.back().numVLs; - } + + messages.emplace_back( + std::make_shared(msg, protocol::mtVALIDATOR_LIST_COLLECTION), + sha512Half(msg), + msg.blobs_size()); + return messages.back().numVLs; } [[nodiscard]] @@ -648,15 +641,17 @@ ValidatorList::buildValidatorListMessages( numVLs = buildValidatorListMessage( messages, peerSequence, rawVersion, rawManifest, blobInfos, maxSize); if (messages.empty()) + { // No message was generated. Create an empty placeholder so we // dont' repeat the work later. messages.emplace_back(); + } } // Don't send it next time. return {maxSequence, numVLs}; } - else if (messageVersion == 1 && peerSequence < currentSeq) + if (messageVersion == 1 && peerSequence < currentSeq) { // Version 1 if (messages.empty()) @@ -668,9 +663,11 @@ ValidatorList::buildValidatorListMessages( currentBlob, maxSize); if (messages.empty()) + { // No message was generated. Create an empty placeholder so we // dont' repeat the work later. messages.emplace_back(); + } } // Don't send it next time. @@ -693,10 +690,15 @@ ValidatorList::sendValidatorList( HashRouter& hashRouter, beast::Journal j) { - std::size_t const messageVersion = - peer.supportsFeature(ProtocolFeature::ValidatorList2Propagation) ? 2 - : peer.supportsFeature(ProtocolFeature::ValidatorListPropagation) ? 1 - : 0; + std::size_t messageVersion = 0; + if (peer.supportsFeature(ProtocolFeature::ValidatorList2Propagation)) + { + messageVersion = 2; + } + else if (peer.supportsFeature(ProtocolFeature::ValidatorListPropagation)) + { + messageVersion = 1; + } if (!messageVersion) return; auto const [newPeerSequence, numVLs] = buildValidatorListMessages( @@ -728,11 +730,13 @@ ValidatorList::sendValidatorList( if (sent) { if (messageVersion > 1) + { JLOG(j.debug()) << "Sent " << messages.size() << " validator list collection(s) containing " << numVLs << " validator list(s) for " << strHex(publisherKey) << " with sequence range " << peerSequence << ", " << newPeerSequence << " to " << peer.fingerprint(); + } else { XRPL_ASSERT( @@ -835,7 +839,7 @@ ValidatorList::broadcastBlobs( // the peer, and foreach provides a const& for (auto& peer : overlay.getActivePeers()) { - if (toSkip->count(peer->id()) == 0) + if (!toSkip->contains(peer->id())) { auto const peerSequence = peer->publisherListSequence(publisherKey).value_or(0); if (peerSequence < maxSequence) @@ -955,13 +959,15 @@ ValidatorList::applyLists( result = std::move(stats); } else + { result.mergeDispositions(stats); + } ///////// } // Clean up the collection, because some of the processing may have made it // inconsistent - if (result.publisherKey && publisherLists_.count(*result.publisherKey)) + if (result.publisherKey && publisherLists_.contains(*result.publisherKey)) { auto& pubCollection = publisherLists_[*result.publisherKey]; auto& remaining = pubCollection.remaining; @@ -1017,9 +1023,13 @@ ValidatorList::updatePublisherList( { // Decrement list count for removed keys if (keyListings_[*iOld] <= 1) + { keyListings_.erase(*iOld); + } else + { --keyListings_[*iOld]; + } ++iOld; } else @@ -1038,7 +1048,7 @@ ValidatorList::updatePublisherList( { auto m = deserializeManifest(base64_decode(valManifest)); - if (!m || !keyListings_.count(m->masterKey)) + if (!m || !keyListings_.contains(m->masterKey)) { JLOG(j_.warn()) << "List for " << strHex(pubKey) << " contained untrusted validator manifest"; @@ -1099,7 +1109,7 @@ ValidatorList::applyList( PublicKey pubKey = *pubKeyOpt; if (result > ListDisposition::pending) { - if (publisherLists_.count(pubKey)) + if (publisherLists_.contains(pubKey)) { auto const& pubCollection = publisherLists_[pubKey]; if (pubCollection.maxSequence && @@ -1122,15 +1132,17 @@ ValidatorList::applyList( (result == ListDisposition::accepted || result == ListDisposition::expired); if (accepted) + { pubCollection.status = result == ListDisposition::accepted ? PublisherStatus::available : PublisherStatus::expired; + } pubCollection.rawManifest = globalManifest; if (!pubCollection.maxSequence || sequence > *pubCollection.maxSequence) pubCollection.maxSequence = sequence; Json::Value const& newList = list[jss::validators]; std::vector oldList; - if (accepted && pubCollection.remaining.count(sequence) != 0) + if (accepted && pubCollection.remaining.contains(sequence)) { // We've seen this list before and stored it in "remaining". The // normal expected process is that the processed list would have @@ -1282,7 +1294,7 @@ ValidatorList::verify( std::string const& blob, std::string const& signature) { - if (!publisherLists_.count(manifest.masterKey)) + if (!publisherLists_.contains(manifest.masterKey)) return {ListDisposition::untrusted, {}}; PublicKey masterPubKey = manifest.masterKey; @@ -1324,14 +1336,23 @@ ValidatorList::verify( auto const now = timeKeeper_.now(); auto const& listCollection = publisherLists_[masterPubKey]; if (validUntil <= validFrom) + { return {ListDisposition::invalid, masterPubKey}; - else if (sequence < listCollection.current.sequence) + } + if (sequence < listCollection.current.sequence) + { return {ListDisposition::stale, masterPubKey}; - else if (sequence == listCollection.current.sequence) + } + if (sequence == listCollection.current.sequence) + { return {ListDisposition::same_sequence, masterPubKey}; - else if (validUntil <= now) + } + if (validUntil <= now) + { return {ListDisposition::expired, masterPubKey}; - else if (validFrom > now) + } + if (validFrom > now) + { // Not yet valid. Return pending if one of the following is true // * There's no maxSequence, indicating this is the first blob seen // for this publisher @@ -1343,10 +1364,11 @@ ValidatorList::verify( // prevents the risk of missing valid data. Else return // known_sequence return !listCollection.maxSequence || sequence > *listCollection.maxSequence || - (listCollection.remaining.count(sequence) == 0 && + (!listCollection.remaining.contains(sequence) && validFrom < listCollection.remaining.at(*listCollection.maxSequence).validFrom) ? std::make_pair(ListDisposition::pending, masterPubKey) : std::make_pair(ListDisposition::known_sequence, masterPubKey); + } } else { @@ -1362,14 +1384,14 @@ ValidatorList::listed(PublicKey const& identity) const std::shared_lock read_lock{mutex_}; auto const pubKey = validatorManifests_.getMasterKey(identity); - return keyListings_.find(pubKey) != keyListings_.end(); + return keyListings_.contains(pubKey); } bool ValidatorList::trusted(ValidatorList::shared_lock const&, PublicKey const& identity) const { auto const pubKey = validatorManifests_.getMasterKey(identity); - return trustedMasterKeys_.find(pubKey) != trustedMasterKeys_.end(); + return trustedMasterKeys_.contains(pubKey); } bool @@ -1385,7 +1407,7 @@ ValidatorList::getListedKey(PublicKey const& identity) const std::shared_lock read_lock{mutex_}; auto const pubKey = validatorManifests_.getMasterKey(identity); - if (keyListings_.find(pubKey) != keyListings_.end()) + if (keyListings_.contains(pubKey)) return pubKey; return std::nullopt; } @@ -1394,7 +1416,7 @@ std::optional ValidatorList::getTrustedKey(ValidatorList::shared_lock const&, PublicKey const& identity) const { auto const pubKey = validatorManifests_.getMasterKey(identity); - if (trustedMasterKeys_.find(pubKey) != trustedMasterKeys_.end()) + if (trustedMasterKeys_.contains(pubKey)) return pubKey; return std::nullopt; } @@ -1411,7 +1433,7 @@ bool ValidatorList::trustedPublisher(PublicKey const& identity) const { std::shared_lock read_lock{mutex_}; - return identity.size() && publisherLists_.count(identity) && + return identity.size() && publisherLists_.contains(identity) && publisherLists_.at(identity).status < PublisherStatus::revoked; } @@ -1444,9 +1466,13 @@ ValidatorList::removePublisherList( continue; if (iVal->second <= 1) + { keyListings_.erase(iVal); + } else + { --iVal->second; + } } iList->second.current.list.clear(); @@ -1458,7 +1484,7 @@ ValidatorList::removePublisherList( std::size_t ValidatorList::count(ValidatorList::shared_lock const&) const { - return publisherLists_.size() + (localPublisherList.list.size() > 0); + return publisherLists_.size() + (!localPublisherList.list.empty()); } std::size_t @@ -1489,9 +1515,13 @@ ValidatorList::expires(ValidatorList::shared_lock const&) const { (void)sequence; if (check.validFrom <= chainedExpiration) + { chainedExpiration = check.validUntil; + } else + { break; + } } // Earliest @@ -1501,7 +1531,7 @@ ValidatorList::expires(ValidatorList::shared_lock const&) const } } - if (localPublisherList.list.size() > 0) + if (!localPublisherList.list.empty()) { PublisherList collection = localPublisherList; // Unfetched @@ -1550,9 +1580,13 @@ ValidatorList::getJson() const x[jss::expiration] = to_string(*when); if (*when > timeKeeper_.now()) + { x[jss::status] = "active"; + } else + { x[jss::status] = "expired"; + } } } else @@ -1951,7 +1985,7 @@ ValidatorList::updateTrusted( { for (auto const& k : trustedMasterKeys_) { - if (negativeUNL_.count(k)) + if (negativeUNL_.contains(k)) --effectiveUnlSize; } hash_set negUnlNodeIDs; @@ -1961,7 +1995,7 @@ ValidatorList::updateTrusted( } for (auto const& nid : seenValidators) { - if (negUnlNodeIDs.count(nid)) + if (negUnlNodeIDs.contains(nid)) --seenSize; } } @@ -1977,7 +2011,7 @@ ValidatorList::updateTrusted( << " exceeds the number of trusted validators (" << unlSize << ")"; } - if ((publisherLists_.size() || localPublisherList.list.size()) && unlSize == 0) + if ((!publisherLists_.empty() || !localPublisherList.list.empty()) && unlSize == 0) { // No validators. Lock down. ops.setUNLBlocked(); @@ -2031,12 +2065,10 @@ ValidatorList::negativeUNLFilter(std::vector>&& va if (auto const masterKey = getTrustedKey(read_lock, v->getSignerPublic()); masterKey) { - return negativeUNL_.count(*masterKey); - } - else - { - return false; + return negativeUNL_.contains(*masterKey); } + + return false; }), ret.end()); } diff --git a/src/xrpld/app/misc/detail/ValidatorSite.cpp b/src/xrpld/app/misc/detail/ValidatorSite.cpp index 0a207c344c..8db29c0bb0 100644 --- a/src/xrpld/app/misc/detail/ValidatorSite.cpp +++ b/src/xrpld/app/misc/detail/ValidatorSite.cpp @@ -52,7 +52,9 @@ ValidatorSite::Site::Resource::Resource(std::string uri_) : uri{std::move(uri_)} pUrl.port = 443; } else + { throw std::runtime_error("Unsupported scheme: '" + pUrl.scheme + "'"); + } } ValidatorSite::Site::Site(std::string uri) @@ -61,7 +63,6 @@ ValidatorSite::Site::Site(std::string uri) , redirCount{0} , refreshInterval{default_refresh_interval} , nextRefresh{clock_type::now()} - , lastRequestEndpoint{} , lastRequestSuccessful{false} { } @@ -301,7 +302,9 @@ ValidatorSite::onRequestTimeout(std::size_t siteIdx, error_code const& ec) // first, which will leave activeResource empty. auto const& site = sites_[siteIdx]; if (site.activeResource) + { JLOG(j_.warn()) << "Request for " << site.activeResource->uri << " took too long"; + } else JLOG(j_.error()) << "Request took too long, but a response has " "already been processed"; @@ -459,7 +462,7 @@ ValidatorSite::processRedirect( { using namespace boost::beast::http; std::shared_ptr newLocation; - if (res.find(field::location) == res.end() || res[field::location].empty()) + if (!res.contains(field::location) || res[field::location].empty()) { JLOG(j_.warn()) << "Request for validator list at " << sites_[siteIdx].activeResource->uri << " returned a redirect with no Location."; diff --git a/src/xrpld/app/misc/detail/WorkSSL.cpp b/src/xrpld/app/misc/detail/WorkSSL.cpp index 47902e900a..3ae0db1a96 100644 --- a/src/xrpld/app/misc/detail/WorkSSL.cpp +++ b/src/xrpld/app/misc/detail/WorkSSL.cpp @@ -32,7 +32,10 @@ WorkSSL::onConnect(error_code const& ec) { auto err = ec ? ec : context_.postConnectVerify(stream_, host_); if (err) - return fail(err); + { + fail(err); + return; + } stream_.async_handshake( boost::asio::ssl::stream_base::client, @@ -44,7 +47,10 @@ void WorkSSL::onHandshake(error_code const& ec) { if (ec) - return fail(ec); + { + fail(ec); + return; + } onStart(); } diff --git a/src/xrpld/app/misc/detail/setup_HashRouter.cpp b/src/xrpld/app/misc/detail/setup_HashRouter.cpp index a0e63dd67e..0cc61f0730 100644 --- a/src/xrpld/app/misc/detail/setup_HashRouter.cpp +++ b/src/xrpld/app/misc/detail/setup_HashRouter.cpp @@ -18,17 +18,21 @@ setup_HashRouter(Config const& config) if (set(tmp, "hold_time", section)) { if (tmp < 12) + { Throw( "HashRouter hold time must be at least 12 seconds (the " "approximate validation time for three ledgers)."); + } setup.holdTime = seconds(tmp); } if (set(tmp, "relay_time", section)) { if (tmp < 8) + { Throw( "HashRouter relay time must be at least 8 seconds (the " "approximate validation time for two ledgers)."); + } setup.relayTime = seconds(tmp); } if (setup.relayTime > setup.holdTime) diff --git a/src/xrpld/app/paths/PathRequest.cpp b/src/xrpld/app/paths/PathRequest.cpp index b3758a690b..f82a207552 100644 --- a/src/xrpld/app/paths/PathRequest.cpp +++ b/src/xrpld/app/paths/PathRequest.cpp @@ -406,10 +406,8 @@ PathRequest::parseJson(Json::Value const& jvParams) jvStatus = rpcError(rpcDOMAIN_MALFORMED); return PFR_PJ_INVALID; } - else - { - domain = num; - } + + domain = num; } return PFR_PJ_NOCHANGE; @@ -461,9 +459,13 @@ PathRequest::getPathFinder( domain, app_); if (pathfinder->findPaths(level, continueCallback)) + { pathfinder->computePathRanks(max_paths_, continueCallback); + } else + { pathfinder.reset(); // It's a bad request - clear it. + } return currency_map[currency] = std::move(pathfinder); } @@ -652,9 +654,13 @@ PathRequest::doUpdate( { // first pass if (loaded || fast) + { iLevel = app_.config().PATH_SEARCH_FAST; + } else + { iLevel = app_.config().PATH_SEARCH; + } } else if ((iLevel == app_.config().PATH_SEARCH_FAST) && !fast) { diff --git a/src/xrpld/app/paths/PathRequests.cpp b/src/xrpld/app/paths/PathRequests.cpp index 35a6c7aa48..61db1e58ef 100644 --- a/src/xrpld/app/paths/PathRequests.cpp +++ b/src/xrpld/app/paths/PathRequests.cpp @@ -95,7 +95,9 @@ PathRequests::updateAll(std::shared_ptr const& inLedger) return (bool)getSubscriber(request); }; if (!request->needsUpdate(newRequests, cache->getLedger()->seq())) + { remove = false; + } else { if (auto ipSub = getSubscriber(request)) diff --git a/src/xrpld/app/paths/Pathfinder.cpp b/src/xrpld/app/paths/Pathfinder.cpp index 38d4488663..c777fcb2f7 100644 --- a/src/xrpld/app/paths/Pathfinder.cpp +++ b/src/xrpld/app/paths/Pathfinder.cpp @@ -95,7 +95,7 @@ struct PathCost }; using PathCostList = std::vector; -static PathTable mPathTable; +PathTable mPathTable; std::string pathTypeToString(Pathfinder::PathType const& type) @@ -574,17 +574,29 @@ Pathfinder::getBestPaths( bool useExtraPath = false; if (pathsIterator == mPathRanks.end()) + { useExtraPath = true; + } else if (extraPathsIterator == extraPathRanks.end()) + { usePath = true; + } else if (extraPathsIterator->quality < pathsIterator->quality) + { useExtraPath = true; + } else if (extraPathsIterator->quality > pathsIterator->quality) + { usePath = true; + } else if (extraPathsIterator->liquidity > pathsIterator->liquidity) + { useExtraPath = true; + } else if (extraPathsIterator->liquidity < pathsIterator->liquidity) + { usePath = true; + } else { // Risk is high they have identical liquidity @@ -1020,9 +1032,13 @@ Pathfinder::addLink( int count = candidates.size(); // allow more paths from source if ((count > 10) && (uEndAccount != mSrcAccount)) + { count = 10; + } else if (count > 50) + { count = 50; + } auto it = candidates.begin(); while (count-- != 0) @@ -1090,7 +1106,9 @@ Pathfinder::addLink( addUniquePath(mCompletePaths, newPath); } else + { incompletePaths.push_back(newPath); + } } else if (!currentPath.hasSeen( book.out.account, book.out.currency, book.out.account)) diff --git a/src/xrpld/app/paths/RippleLineCache.cpp b/src/xrpld/app/paths/RippleLineCache.cpp index 9916facdc2..ac3e28e579 100644 --- a/src/xrpld/app/paths/RippleLineCache.cpp +++ b/src/xrpld/app/paths/RippleLineCache.cpp @@ -76,7 +76,7 @@ RippleLineCache::getRippleLines(AccountID const& accountID, LineDirection direct { XRPL_ASSERT(it->second == nullptr, "xrpl::RippleLineCache::getRippleLines : null lines"); auto lines = PathFindTrustLine::getItems(accountID, *ledger_, direction); - if (lines.size()) + if (!lines.empty()) { it->second = std::make_shared>(std::move(lines)); totalLineCount_ += it->second->size(); diff --git a/src/xrpld/app/paths/detail/AMMLiquidity.cpp b/src/xrpld/app/paths/detail/AMMLiquidity.cpp index 3ffc86d1ba..72ee8eb261 100644 --- a/src/xrpld/app/paths/detail/AMMLiquidity.cpp +++ b/src/xrpld/app/paths/detail/AMMLiquidity.cpp @@ -80,11 +80,17 @@ constexpr T maxAmount() { if constexpr (std::is_same_v) + { return XRPAmount(STAmount::cMaxNative); + } else if constexpr (std::is_same_v) + { return IOUAmount(STAmount::cMaxValue / 2, STAmount::cMaxOffset); + } else if constexpr (std::is_same_v) + { return STAmount(STAmount::cMaxValue / 2, STAmount::cMaxOffset); + } } template @@ -108,14 +114,12 @@ AMMLiquidity::maxOffer(TAmounts const& balances, Rules con balances, Quality{balances}); } - else - { - auto const out = maxOut(balances.out, issueOut()); - if (out <= TOut{0} || out >= balances.out) - return std::nullopt; - return AMMOffer( - *this, {swapAssetOut(balances, out, tradingFee_), out}, balances, Quality{balances}); - } + + auto const out = maxOut(balances.out, issueOut()); + if (out <= TOut{0} || out >= balances.out) + return std::nullopt; + return AMMOffer( + *this, {swapAssetOut(balances, out, tradingFee_), out}, balances, Quality{balances}); } template @@ -166,7 +170,7 @@ AMMLiquidity::getOffer(ReadView const& view, std::optional c return std::nullopt; return AMMOffer(*this, amounts, balances, Quality{amounts}); } - else if (!clobQuality) + if (!clobQuality) { // If there is no CLOB to compare against, return the largest // amount, which doesn't overflow. The size is going to be @@ -175,13 +179,12 @@ AMMLiquidity::getOffer(ReadView const& view, std::optional c // nullopt if the pool is small. return maxOffer(balances, view.rules()); } - else if ( - auto const amounts = + if (auto const amounts = changeSpotPriceQuality(balances, *clobQuality, tradingFee_, view.rules(), j_)) { return AMMOffer(*this, *amounts, balances, Quality{*amounts}); } - else if (view.rules().enabled(fixAMMv1_2)) + if (view.rules().enabled(fixAMMv1_2)) { if (auto const maxAMMOffer = maxOffer(balances, view.rules()); maxAMMOffer && Quality{maxAMMOffer->amount()} > *clobQuality) @@ -192,9 +195,11 @@ AMMLiquidity::getOffer(ReadView const& view, std::optional c { JLOG(j_.error()) << "AMMLiquidity::getOffer overflow " << e.what(); if (!view.rules().enabled(fixAMMOverflowOffer)) + { return maxOffer(balances, view.rules()); - else - return std::nullopt; + } + + return std::nullopt; } catch (std::exception const& e) { diff --git a/src/xrpld/app/paths/detail/BookStep.cpp b/src/xrpld/app/paths/detail/BookStep.cpp index 37ca16c72d..ae0c371e3e 100644 --- a/src/xrpld/app/paths/detail/BookStep.cpp +++ b/src/xrpld/app/paths/detail/BookStep.cpp @@ -74,6 +74,7 @@ private: { if (auto const ammSle = ctx.view.read(keylet::amm(in, out)); ammSle && ammSle->getFieldAmount(sfLPTokenBalance) != beast::zero) + { ammLiquidity_.emplace( ctx.view, (*ammSle)[sfAccount], @@ -82,6 +83,7 @@ private: out, ctx.ammContext, ctx.j); + } } public: @@ -491,11 +493,14 @@ public: // when calculating the upper bound quality and the quality function // because single path AMM's offer quality is not constant. if (!rules.enabled(fixAMMv1_1)) + { return ofrQ; - else if ( - offerType == OfferType::CLOB || + } + if (offerType == OfferType::CLOB || (this->ammLiquidity_ && this->ammLiquidity_->multiPath())) + { return ofrQ; + } auto rate = [&](AccountID const& id) { if (isXRP(id) || id == this->strandDst_) @@ -674,9 +679,13 @@ BookStep::forEachOffer( // Note that offer.quality() returns a (non-optional) Quality. So // ofrQ is always safe to use below this point in the lambda. if (!ofrQ) + { ofrQ = offer.quality(); + } else if (*ofrQ != offer.quality()) + { return false; + } if (static_cast(this)->limitSelfCrossQuality( strandSrc_, strandDst_, offer, ofrQ, offers, offerAttempted)) @@ -704,8 +713,10 @@ BookStep::forEachOffer( if (auto const key = offer.key()) offers.permRmOffer(*key); if (!offerAttempted) + { // Change quality only if no previous offers were tried. ofrQ = std::nullopt; + } // Returning true causes offers.step() to delete the offer. return true; } @@ -881,24 +892,34 @@ auto BookStep::tipOfferQuality(ReadView const& view) const -> std::optional> { - if (auto const res = tip(view); !res) + auto const res = tip(view); + if (!res) + { return std::nullopt; - else if (auto const q = std::get_if(&(*res))) + } + if (auto const q = std::get_if(&(*res))) + { return std::make_pair(*q, OfferType::CLOB); - else - return std::make_pair(std::get>(*res).quality(), OfferType::AMM); + } + + return std::make_pair(std::get>(*res).quality(), OfferType::AMM); } template std::optional BookStep::tipOfferQualityF(ReadView const& view) const { - if (auto const res = tip(view); !res) + auto const res = tip(view); + if (!res) + { return std::nullopt; - else if (auto const q = std::get_if(&(*res))) + } + if (auto const q = std::get_if(&(*res))) + { return QualityFunction{*q, QualityFunction::CLOBLikeTag{}}; - else - return std::get>(*res).getQualityFunc(); + } + + return std::get>(*res).getQualityFunc(); } template @@ -954,33 +975,31 @@ BookStep::revImp( // we need to consume the offer return true; } - else - { - auto ofrAdjAmt = ofrAmt; - auto stpAdjAmt = stpAmt; - auto ownerGivesAdj = ownerGives; - limitStepOut( - offer, - ofrAdjAmt, - stpAdjAmt, - ownerGivesAdj, - transferRateIn, - transferRateOut, - remainingOut); - remainingOut = beast::zero; - savedIns.insert(stpAdjAmt.in); - savedOuts.insert(remainingOut); - result.in = sum(savedIns); - result.out = out; - this->consumeOffer(sb, offer, ofrAdjAmt, stpAdjAmt, ownerGivesAdj); - // Explicitly check whether the offer is funded. Given that we have - // (stpAmt.out > remainingOut), it's natural to assume the offer - // will still be funded after consuming remainingOut but that is - // not always the case. If the mantissas of two IOU amounts differ - // by less than ten, then subtracting them leaves a zero. - return offer.fully_consumed(); - } + auto ofrAdjAmt = ofrAmt; + auto stpAdjAmt = stpAmt; + auto ownerGivesAdj = ownerGives; + limitStepOut( + offer, + ofrAdjAmt, + stpAdjAmt, + ownerGivesAdj, + transferRateIn, + transferRateOut, + remainingOut); + remainingOut = beast::zero; + savedIns.insert(stpAdjAmt.in); + savedOuts.insert(remainingOut); + result.in = sum(savedIns); + result.out = out; + this->consumeOffer(sb, offer, ofrAdjAmt, stpAdjAmt, ownerGivesAdj); + + // Explicitly check whether the offer is funded. Given that we have + // (stpAmt.out > remainingOut), it's natural to assume the offer + // will still be funded after consuming remainingOut but that is + // not always the case. If the mantissas of two IOU amounts differ + // by less than ten, then subtracting them leaves a zero. + return offer.fully_consumed(); }; { diff --git a/src/xrpld/app/paths/detail/DirectStep.cpp b/src/xrpld/app/paths/detail/DirectStep.cpp index dab16f010d..a07e5824d6 100644 --- a/src/xrpld/app/paths/detail/DirectStep.cpp +++ b/src/xrpld/app/paths/detail/DirectStep.cpp @@ -335,18 +335,20 @@ DirectIPaymentStep::quality(ReadView const& sb, QualityDirection qDir) const { // compute dst quality in if (this->dst_ < this->src_) + { return sfLowQualityIn; - else - return sfHighQualityIn; + } + + return sfHighQualityIn; } - else + + // compute src quality out + if (this->src_ < this->dst_) { - // compute src quality out - if (this->src_ < this->dst_) - return sfLowQualityOut; - else - return sfHighQualityOut; + return sfLowQualityOut; } + + return sfHighQualityOut; }(); if (!sle->isFieldPresent(field)) @@ -756,15 +758,13 @@ DirectStepI::qualities( { return qualitiesSrcRedeems(sb); } - else - { - auto const prevStepDebtDirection = [&] { - if (prevStep_) - return prevStep_->debtDirection(sb, strandDir); - return DebtDirection::issues; - }(); - return qualitiesSrcIssues(sb, prevStepDebtDirection); - } + + auto const prevStepDebtDirection = [&] { + if (prevStep_) + return prevStep_->debtDirection(sb, strandDir); + return DebtDirection::issues; + }(); + return qualitiesSrcIssues(sb, prevStepDebtDirection); } template diff --git a/src/xrpld/app/paths/detail/PaySteps.cpp b/src/xrpld/app/paths/detail/PaySteps.cpp index e438d4442a..9087647aeb 100644 --- a/src/xrpld/app/paths/detail/PaySteps.cpp +++ b/src/xrpld/app/paths/detail/PaySteps.cpp @@ -264,9 +264,13 @@ toStrand( auto const next = &normPath[i + 1]; if (cur->isAccount()) + { curIssue.account = cur->getAccountID(); + } else if (cur->hasIssuer()) + { curIssue.account = cur->getIssuerID(); + } if (cur->hasCurrency()) { @@ -314,14 +318,12 @@ toStrand( { if (i != normPath.size() - 2) return {temBAD_PATH, Strand{}}; - else - { - // Last step. insert xrp endpoint step - auto msr = make_XRPEndpointStep(ctx(), next->getAccountID()); - if (!isTesSuccess(msr.first)) - return {msr.first, Strand{}}; - result.push_back(std::move(msr.second)); - } + + // Last step. insert xrp endpoint step + auto msr = make_XRPEndpointStep(ctx(), next->getAccountID()); + if (!isTesSuccess(msr.first)) + return {msr.first, Strand{}}; + result.push_back(std::move(msr.second)); } else { @@ -347,7 +349,9 @@ toStrand( auto s = toStep(ctx(/*isLast*/ i == normPath.size() - 2), cur, next, curIssue); if (isTesSuccess(s.first)) + { result.emplace_back(std::move(s.second)); + } else { JLOG(j.debug()) << "toStep failed: " << s.first; diff --git a/src/xrpld/app/rdb/backend/detail/Node.cpp b/src/xrpld/app/rdb/backend/detail/Node.cpp index eccc946e9f..09b4ebc241 100644 --- a/src/xrpld/app/rdb/backend/detail/Node.cpp +++ b/src/xrpld/app/rdb/backend/detail/Node.cpp @@ -97,8 +97,8 @@ makeLedgerDBs( return {std::move(lgr), std::move(tx), true}; } - else - return {std::move(lgr), {}, true}; + + return {std::move(lgr), {}, true}; } std::optional @@ -282,7 +282,9 @@ saveValidatedLedger( for (auto const& account : accts) { if (!first) + { sql += ", ('"; + } else { sql += "('"; @@ -600,9 +602,13 @@ getTxHistory(soci::session& session, Application& app, LedgerIndex startIndex, i while (st.fetch()) { if (soci::i_ok == rti) + { convert(sociRawTxnBlob, rawTxn); + } else + { rawTxn.clear(); + } if (auto trans = Transaction::transactionFromSQL(ledgerSeq, status, rawTxn, app)) { @@ -665,8 +671,8 @@ transactionsSQL( numberOfResults = options.limit; } - std::string maxClause = ""; - std::string minClause = ""; + std::string maxClause; + std::string minClause; if (options.maxLedger) { @@ -683,13 +689,16 @@ transactionsSQL( std::string sql; if (count) + { sql = boost::str( boost::format( "SELECT %s FROM AccountTransactions " "WHERE Account = '%s' %s %s LIMIT %u, %u;") % selection % toBase58(options.account) % maxClause % minClause % options.offset % numberOfResults); + } else + { sql = boost::str( boost::format( "SELECT %s FROM " @@ -702,6 +711,7 @@ transactionsSQL( selection % toBase58(options.account) % maxClause % minClause % (descending ? "DESC" : "ASC") % (descending ? "DESC" : "ASC") % (descending ? "DESC" : "ASC") % options.offset % numberOfResults); + } JLOG(j.trace()) << "txSQL query: " << sql; return sql; } @@ -746,7 +756,7 @@ getAccountTxs( false, false, j); - if (sql == "") + if (sql.empty()) return {ret, 0}; int total = 0; @@ -769,14 +779,22 @@ getAccountTxs( while (st.fetch()) { if (soci::i_ok == rti) + { convert(sociTxnBlob, rawTxn); + } else + { rawTxn.clear(); + } if (soci::i_ok == tmi) + { convert(sociTxnMetaBlob, txnMeta); + } else + { txnMeta.clear(); + } auto txn = Transaction::transactionFromSQL(ledgerSeq, status, rawTxn, app); @@ -862,7 +880,7 @@ getAccountTxsB( true /*binary*/, false, j); - if (sql == "") + if (sql.empty()) return {ret, 0}; int total = 0; @@ -957,9 +975,13 @@ accountTxPage( if (options.limit == 0 || options.limit == UINT32_MAX || (options.limit > page_length && !options.bAdmin)) + { numberOfResults = page_length; + } else + { numberOfResults = options.limit; + } // As an account can have many thousands of transactions, there is a limit // placed on the amount of transactions returned. If the limit is reached @@ -1062,7 +1084,9 @@ accountTxPage( lookingForMarker = false; } else + { continue; + } } else if (numberOfResults == 0) { @@ -1072,17 +1096,25 @@ accountTxPage( } if (dataPresent == soci::i_ok) + { convert(txnData, rawData); + } else + { rawData.clear(); + } if (metaPresent == soci::i_ok) + { convert(txnMeta, rawMeta); + } else + { rawMeta.clear(); + } // Work around a bug that could leave the metadata missing - if (rawMeta.size() == 0) + if (rawMeta.empty()) onUnsavedLedger(ledgerSeq.value_or(0)); // `rawData` and `rawMeta` will be used after they are moved. diff --git a/src/xrpld/core/detail/Config.cpp b/src/xrpld/core/detail/Config.cpp index cee1ce5ed1..52186ca9da 100644 --- a/src/xrpld/core/detail/Config.cpp +++ b/src/xrpld/core/detail/Config.cpp @@ -154,7 +154,7 @@ parseIniFile(std::string const& strInput, bool const bTrim) boost::algorithm::split(vLines, strData, boost::algorithm::is_any_of("\n")); // Set the default Section name. - std::string strSection = SECTION_DEFAULT_NAME; + std::string strSection = SECTION_DEFAULT_NAME; // NOLINT(readability-redundant-string-init) // Initialize the default Section. secResult[strSection] = IniFileSections::mapped_type(); @@ -364,9 +364,13 @@ Config::setup(std::string const& strConf, bool bQuiet, bool bSilent, bool bStand // load() may have set a new value for the dataDir std::string const dbPath(legacy("database_path")); if (!dbPath.empty()) + { dataDir = boost::filesystem::path(dbPath); + } else if (RUN_STANDALONE) + { dataDir.clear(); + } } if (!dataDir.empty()) @@ -493,13 +497,21 @@ Config::loadFromString(std::string const& fileContents) if (getSingleSection(secConfig, SECTION_NETWORK_ID, strTemp, j_)) { if (strTemp == "main") + { NETWORK_ID = 0; + } else if (strTemp == "testnet") + { NETWORK_ID = 1; + } else if (strTemp == "devnet") + { NETWORK_ID = 2; + } else + { NETWORK_ID = beast::lexicalCastThrow(strTemp); + } } if (getSingleSection(secConfig, SECTION_PEER_PRIVATE, strTemp, j_)) @@ -516,8 +528,10 @@ Config::loadFromString(std::string const& fileContents) { peers_in_max = beast::lexicalCastThrow(strTemp); if (*peers_in_max > 1000) + { Throw("Invalid value specified in [" SECTION_PEERS_IN_MAX "] section; the value must be less or equal than 1000"); + } } std::optional peers_out_max{}; @@ -525,15 +539,19 @@ Config::loadFromString(std::string const& fileContents) { peers_out_max = beast::lexicalCastThrow(strTemp); if (*peers_out_max < 10 || *peers_out_max > 1000) + { Throw("Invalid value specified in [" SECTION_PEERS_OUT_MAX "] section; the value must be in range 10-1000"); + } } // if one section is configured then the other must be configured too if ((peers_in_max && !peers_out_max) || (peers_out_max && !peers_in_max)) + { Throw("Both sections [" SECTION_PEERS_IN_MAX "]" "and [" SECTION_PEERS_OUT_MAX "] must be configured"); + } if (peers_in_max && peers_out_max) { @@ -545,17 +563,29 @@ Config::loadFromString(std::string const& fileContents) if (getSingleSection(secConfig, SECTION_NODE_SIZE, strTemp, j_)) { if (boost::iequals(strTemp, "tiny")) + { NODE_SIZE = 0; + } else if (boost::iequals(strTemp, "small")) + { NODE_SIZE = 1; + } else if (boost::iequals(strTemp, "medium")) + { NODE_SIZE = 2; + } else if (boost::iequals(strTemp, "large")) + { NODE_SIZE = 3; + } else if (boost::iequals(strTemp, "huge")) + { NODE_SIZE = 4; + } else + { NODE_SIZE = std::min(4, beast::lexicalCastThrow(strTemp)); + } } if (getSingleSection(secConfig, SECTION_SIGNING_SUPPORT, strTemp, j_)) @@ -573,32 +603,50 @@ Config::loadFromString(std::string const& fileContents) if (getSingleSection(secConfig, SECTION_RELAY_VALIDATIONS, strTemp, j_)) { if (boost::iequals(strTemp, "all")) + { RELAY_UNTRUSTED_VALIDATIONS = 1; + } else if (boost::iequals(strTemp, "trusted")) + { RELAY_UNTRUSTED_VALIDATIONS = 0; + } else if (boost::iequals(strTemp, "drop_untrusted")) + { RELAY_UNTRUSTED_VALIDATIONS = -1; + } else + { Throw("Invalid value specified in [" SECTION_RELAY_VALIDATIONS "] section"); + } } if (getSingleSection(secConfig, SECTION_RELAY_PROPOSALS, strTemp, j_)) { if (boost::iequals(strTemp, "all")) + { RELAY_UNTRUSTED_PROPOSALS = 1; + } else if (boost::iequals(strTemp, "trusted")) + { RELAY_UNTRUSTED_PROPOSALS = 0; + } else if (boost::iequals(strTemp, "drop_untrusted")) + { RELAY_UNTRUSTED_PROPOSALS = -1; + } else + { Throw("Invalid value specified in [" SECTION_RELAY_PROPOSALS "] section"); + } } if (exists(SECTION_VALIDATION_SEED) && exists(SECTION_VALIDATOR_TOKEN)) + { Throw("Cannot have both [" SECTION_VALIDATION_SEED "] and [" SECTION_VALIDATOR_TOKEN "] config sections"); + } if (getSingleSection(secConfig, SECTION_NETWORK_QUORUM, strTemp, j_)) NETWORK_QUORUM = beast::lexicalCastThrow(strTemp); @@ -613,24 +661,35 @@ Config::loadFromString(std::string const& fileContents) if (getSingleSection(secConfig, SECTION_LEDGER_HISTORY, strTemp, j_)) { if (boost::iequals(strTemp, "full")) + { LEDGER_HISTORY = std::numeric_limits::max(); + } else if (boost::iequals(strTemp, "none")) + { LEDGER_HISTORY = 0; + } else + { LEDGER_HISTORY = beast::lexicalCastThrow(strTemp); + } } if (getSingleSection(secConfig, SECTION_FETCH_DEPTH, strTemp, j_)) { if (boost::iequals(strTemp, "none")) + { FETCH_DEPTH = 0; + } else if (boost::iequals(strTemp, "full")) + { FETCH_DEPTH = std::numeric_limits::max(); + } else + { FETCH_DEPTH = beast::lexicalCastThrow(strTemp); + } - if (FETCH_DEPTH < 10) - FETCH_DEPTH = 10; + FETCH_DEPTH = std::max(FETCH_DEPTH, 10); } // By default, validators don't have pathfinding enabled, unless it is @@ -655,8 +714,10 @@ Config::loadFromString(std::string const& fileContents) SWEEP_INTERVAL = beast::lexicalCastThrow(strTemp); if (SWEEP_INTERVAL < 10 || SWEEP_INTERVAL > 600) + { Throw("Invalid " SECTION_SWEEP_INTERVAL ": must be between 10 and 600 inclusive"); + } } if (getSingleSection(secConfig, SECTION_WORKERS, strTemp, j_)) @@ -664,8 +725,10 @@ Config::loadFromString(std::string const& fileContents) WORKERS = beast::lexicalCastThrow(strTemp); if (WORKERS < 1 || WORKERS > 1024) + { Throw("Invalid " SECTION_WORKERS ": must be between 1 and 1024 inclusive."); + } } if (getSingleSection(secConfig, SECTION_IO_WORKERS, strTemp, j_)) @@ -673,8 +736,10 @@ Config::loadFromString(std::string const& fileContents) IO_WORKERS = beast::lexicalCastThrow(strTemp); if (IO_WORKERS < 1 || IO_WORKERS > 1024) + { Throw("Invalid " SECTION_IO_WORKERS ": must be between 1 and 1024 inclusive."); + } } if (getSingleSection(secConfig, SECTION_PREFETCH_WORKERS, strTemp, j_)) @@ -682,8 +747,10 @@ Config::loadFromString(std::string const& fileContents) PREFETCH_WORKERS = beast::lexicalCastThrow(strTemp); if (PREFETCH_WORKERS < 1 || PREFETCH_WORKERS > 1024) + { Throw("Invalid " SECTION_PREFETCH_WORKERS ": must be between 1 and 1024 inclusive."); + } } if (getSingleSection(secConfig, SECTION_COMPRESSION, strTemp, j_)) @@ -703,18 +770,26 @@ Config::loadFromString(std::string const& fileContents) // VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = // // sec.value_or("vp_base_squelch_enable", true); // if (sec.exists("vp_base_squelch_enable") && sec.exists("vp_enable")) + { Throw("Invalid " SECTION_REDUCE_RELAY " cannot specify both vp_base_squelch_enable and vp_enable " "options. " "vp_enable was deprecated and replaced by " "vp_base_squelch_enable"); + } if (sec.exists("vp_base_squelch_enable")) + { VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = sec.value_or("vp_base_squelch_enable", false); + } else if (sec.exists("vp_enable")) + { VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = sec.value_or("vp_enable", false); + } else + { VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = false; + } ///////////////// !!END OF TEMPORARY CODE BLOCK!! ///////////////////// ///////////////////// !!TEMPORARY CODE BLOCK!! /////////////////////// @@ -724,9 +799,11 @@ Config::loadFromString(std::string const& fileContents) VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS = sec.value_or("vp_base_squelch_max_selected_peers", 5); if (VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS < 3) + { Throw("Invalid " SECTION_REDUCE_RELAY " vp_base_squelch_max_selected_peers must be " "greater than or equal to 3"); + } ///////////////// !!END OF TEMPORARY CODE BLOCK!! ///////////////////// TX_REDUCE_RELAY_ENABLE = sec.value_or("tx_enable", false); @@ -734,10 +811,12 @@ Config::loadFromString(std::string const& fileContents) TX_REDUCE_RELAY_MIN_PEERS = sec.value_or("tx_min_peers", 20); TX_RELAY_PERCENTAGE = sec.value_or("tx_relay_percentage", 25); if (TX_RELAY_PERCENTAGE < 10 || TX_RELAY_PERCENTAGE > 100 || TX_REDUCE_RELAY_MIN_PEERS < 10) + { Throw("Invalid " SECTION_REDUCE_RELAY ", tx_min_peers must be greater than or equal to 10" ", tx_relay_percentage must be greater than or equal to 10 " "and less than or equal to 100"); + } } if (getSingleSection(secConfig, SECTION_MAX_TRANSACTIONS, strTemp, j_)) @@ -776,9 +855,11 @@ Config::loadFromString(std::string const& fileContents) } if (MAX_UNKNOWN_TIME < seconds{300} || MAX_UNKNOWN_TIME > seconds{1800}) + { Throw( "Invalid value 'max_unknown_time' in " SECTION_OVERLAY ": the time must be between 300 and 1800 seconds, inclusive."); + } try { @@ -804,24 +885,36 @@ Config::loadFromString(std::string const& fileContents) boost::regex const re("^\\s*(\\d+)\\s*(minutes|hours|days|weeks)\\s*(\\s+.*)?$"); boost::smatch match; if (!boost::regex_match(strTemp, match, re)) + { Throw("Invalid " SECTION_AMENDMENT_MAJORITY_TIME ", must be: [0-9]+ [minutes|hours|days|weeks]"); + } std::uint32_t duration = beast::lexicalCastThrow(match[1].str()); if (boost::iequals(match[2], "minutes")) + { AMENDMENT_MAJORITY_TIME = minutes(duration); + } else if (boost::iequals(match[2], "hours")) + { AMENDMENT_MAJORITY_TIME = hours(duration); + } else if (boost::iequals(match[2], "days")) + { AMENDMENT_MAJORITY_TIME = days(duration); + } else if (boost::iequals(match[2], "weeks")) + { AMENDMENT_MAJORITY_TIME = weeks(duration); + } if (AMENDMENT_MAJORITY_TIME < minutes(15)) + { Throw("Invalid " SECTION_AMENDMENT_MAJORITY_TIME ", the minimum amount of time an amendment must hold a " "majority is 15 minutes"); + } } if (getSingleSection(secConfig, SECTION_BETA_RPC_API, strTemp, j_)) @@ -845,25 +938,30 @@ Config::loadFromString(std::string const& fileContents) validatorsFile = strTemp; if (validatorsFile.empty()) + { Throw("Invalid path specified in [" SECTION_VALIDATORS_FILE "]"); + } if (!validatorsFile.is_absolute() && !CONFIG_DIR.empty()) validatorsFile = CONFIG_DIR / validatorsFile; if (!boost::filesystem::exists(validatorsFile)) + { Throw( "The file specified in [" SECTION_VALIDATORS_FILE "] " "does not exist: " + validatorsFile.string()); - + } else if ( !boost::filesystem::is_regular_file(validatorsFile) && !boost::filesystem::is_symlink(validatorsFile)) + { Throw( "Invalid file specified in [" SECTION_VALIDATORS_FILE "]: " + validatorsFile.string()); + } } else if (!CONFIG_DIR.empty()) { @@ -872,11 +970,15 @@ Config::loadFromString(std::string const& fileContents) if (!validatorsFile.empty()) { if (!boost::filesystem::exists(validatorsFile)) + { validatorsFile.clear(); + } else if ( !boost::filesystem::is_regular_file(validatorsFile) && !boost::filesystem::is_symlink(validatorsFile)) + { validatorsFile.clear(); + } } } @@ -921,6 +1023,7 @@ Config::loadFromString(std::string const& fileContents) section(SECTION_VALIDATOR_LIST_THRESHOLD).append(*valListThreshold); if (!entries && !valKeyEntries && !valListKeys) + { Throw( "The file specified in [" SECTION_VALIDATORS_FILE "] " @@ -932,19 +1035,24 @@ Config::loadFromString(std::string const& fileContents) "]" " section: " + validatorsFile.string()); + } } VALIDATOR_LIST_THRESHOLD = [&]() -> std::optional { auto const& listThreshold = section(SECTION_VALIDATOR_LIST_THRESHOLD); if (listThreshold.lines().empty()) + { return std::nullopt; - else if (listThreshold.values().size() == 1) + } + if (listThreshold.values().size() == 1) { auto strTemp = listThreshold.values()[0]; auto const listThreshold = beast::lexicalCastThrow(strTemp); if (listThreshold == 0) + { return std::nullopt; // NOTE: Explicitly ask for computed - else if (listThreshold > section(SECTION_VALIDATOR_LIST_KEYS).values().size()) + } + if (listThreshold > section(SECTION_VALIDATOR_LIST_KEYS).values().size()) { Throw( "Value in config section " @@ -953,12 +1061,10 @@ Config::loadFromString(std::string const& fileContents) } return listThreshold; } - else - { - Throw( - "Config section " - "[" SECTION_VALIDATOR_LIST_THRESHOLD "] should contain single value only"); - } + + Throw( + "Config section " + "[" SECTION_VALIDATOR_LIST_THRESHOLD "] should contain single value only"); }(); // Consolidate [validator_keys] and [validators] @@ -977,9 +1083,13 @@ Config::loadFromString(std::string const& fileContents) for (auto const& s : part.values()) { if (auto const f = getRegisteredFeature(s)) + { features.insert(*f); + } else + { Throw("Unknown feature: " + s + " in config file."); + } } } diff --git a/src/xrpld/overlay/detail/ConnectAttempt.cpp b/src/xrpld/overlay/detail/ConnectAttempt.cpp index 54765c68db..78aee006f1 100644 --- a/src/xrpld/overlay/detail/ConnectAttempt.cpp +++ b/src/xrpld/overlay/detail/ConnectAttempt.cpp @@ -51,7 +51,10 @@ void ConnectAttempt::stop() { if (!strand_.running_in_this_thread()) - return boost::asio::post(strand_, std::bind(&ConnectAttempt::stop, shared_from_this())); + { + boost::asio::post(strand_, std::bind(&ConnectAttempt::stop, shared_from_this())); + return; + } if (!socket_.is_open()) return; @@ -65,7 +68,10 @@ void ConnectAttempt::run() { if (!strand_.running_in_this_thread()) - return boost::asio::post(strand_, std::bind(&ConnectAttempt::run, shared_from_this())); + { + boost::asio::post(strand_, std::bind(&ConnectAttempt::run, shared_from_this())); + return; + } JLOG(journal_.debug()) << "run: connecting to " << remote_endpoint_; @@ -115,9 +121,10 @@ ConnectAttempt::tryAsyncShutdown() if (currentStep_ != ConnectionStep::TcpConnect && currentStep_ != ConnectionStep::TlsHandshake) { setTimer(ConnectionStep::ShutdownStarted); - return stream_.async_shutdown(bind_executor( + stream_.async_shutdown(bind_executor( strand_, std::bind(&ConnectAttempt::onShutdown, shared_from_this(), std::placeholders::_1))); + return; } close(); @@ -197,7 +204,8 @@ ConnectAttempt::setTimer(ConnectionStep step) catch (std::exception const& ex) { JLOG(journal_.error()) << "setTimer (global): " << ex.what(); - return close(); + close(); + return; } } @@ -240,7 +248,8 @@ ConnectAttempt::setTimer(ConnectionStep step) catch (std::exception const& ex) { JLOG(journal_.error()) << "setTimer (step " << stepToString(step) << "): " << ex.what(); - return close(); + close(); + return; } } @@ -272,7 +281,8 @@ ConnectAttempt::onTimer(error_code ec) // This should never happen JLOG(journal_.error()) << "onTimer: " << ec.message(); - return close(); + close(); + return; } // Determine which timer expired by checking their expiry times @@ -304,9 +314,13 @@ ConnectAttempt::onConnect(error_code ec) if (ec) { if (ec == boost::asio::error::operation_aborted) - return tryAsyncShutdown(); + { + tryAsyncShutdown(); + return; + } - return fail("onConnect", ec); + fail("onConnect", ec); + return; } if (!socket_.is_open()) @@ -315,10 +329,16 @@ ConnectAttempt::onConnect(error_code ec) // check if connection has really been established socket_.local_endpoint(ec); if (ec) - return fail("onConnect", ec); + { + fail("onConnect", ec); + return; + } if (shutdown_) - return tryAsyncShutdown(); + { + tryAsyncShutdown(); + return; + } ioPending_ = true; @@ -340,25 +360,38 @@ ConnectAttempt::onHandshake(error_code ec) if (ec) { if (ec == boost::asio::error::operation_aborted) - return tryAsyncShutdown(); + { + tryAsyncShutdown(); + return; + } - return fail("onHandshake", ec); + fail("onHandshake", ec); + return; } auto const local_endpoint = socket_.local_endpoint(ec); if (ec) - return fail("onHandshake", ec); + { + fail("onHandshake", ec); + return; + } setTimer(ConnectionStep::HttpWrite); // check if we connected to ourselves if (!overlay_.peerFinder().onConnected( slot_, beast::IPAddressConversion::from_asio(local_endpoint))) - return fail("Self connection"); + { + fail("Self connection"); + return; + } auto const sharedValue = makeSharedValue(*stream_ptr_, journal_); if (!sharedValue) - return shutdown(); // makeSharedValue logs + { + shutdown(); + return; // makeSharedValue logs + } req_ = makeRequest( !overlay_.peerFinder().config().peerPrivate, @@ -376,7 +409,10 @@ ConnectAttempt::onHandshake(error_code ec) app_); if (shutdown_) - return tryAsyncShutdown(); + { + tryAsyncShutdown(); + return; + } ioPending_ = true; @@ -396,13 +432,20 @@ ConnectAttempt::onWrite(error_code ec) if (ec) { if (ec == boost::asio::error::operation_aborted) - return tryAsyncShutdown(); + { + tryAsyncShutdown(); + return; + } - return fail("onWrite", ec); + fail("onWrite", ec); + return; } if (shutdown_) - return tryAsyncShutdown(); + { + tryAsyncShutdown(); + return; + } ioPending_ = true; @@ -429,17 +472,25 @@ ConnectAttempt::onRead(error_code ec) if (ec == boost::asio::error::eof) { JLOG(journal_.debug()) << "EOF"; - return shutdown(); + shutdown(); + return; } if (ec == boost::asio::error::operation_aborted) - return tryAsyncShutdown(); + { + tryAsyncShutdown(); + return; + } - return fail("onRead", ec); + fail("onRead", ec); + return; } if (shutdown_) - return tryAsyncShutdown(); + { + tryAsyncShutdown(); + return; + } processResponse(); } @@ -457,7 +508,8 @@ ConnectAttempt::processResponse() { JLOG(journal_.warn()) << "Unable to upgrade to peer protocol: " << response_.result() << " (" << response_.reason() << ")"; - return shutdown(); + shutdown(); + return; } // Parse response body to determine if this is a redirect or other @@ -465,8 +517,10 @@ ConnectAttempt::processResponse() std::string responseBody; responseBody.reserve(boost::asio::buffer_size(response_.body().data())); for (auto const buffer : response_.body().data()) + { responseBody.append( static_cast(buffer.data()), boost::asio::buffer_size(buffer)); + } Json::Value json; Json::Reader reader; @@ -481,12 +535,16 @@ ConnectAttempt::processResponse() << " failed to upgrade to peer protocol: " << response_.result() << " (" << response_.reason() << ")"; - return shutdown(); + shutdown(); + return; } Json::Value const& peerIps = json["peer-ips"]; if (!peerIps.isArray()) - return fail("processResponse: invalid peer-ips format"); + { + fail("processResponse: invalid peer-ips format"); + return; + } // Extract and validate peer endpoints std::vector redirectEndpoints; @@ -506,7 +564,8 @@ ConnectAttempt::processResponse() // Notify PeerFinder about the redirect redirectEndpoints may be empty overlay_.peerFinder().onRedirects(remote_endpoint_, redirectEndpoints); - return fail("processResponse: failed to connect to peer: redirected"); + fail("processResponse: failed to connect to peer: redirected"); + return; } // Just because our peer selected a particular protocol version doesn't @@ -520,12 +579,18 @@ ConnectAttempt::processResponse() negotiatedProtocol = pvs[0]; if (!negotiatedProtocol) - return fail("processResponse: Unable to negotiate protocol version"); + { + fail("processResponse: Unable to negotiate protocol version"); + return; + } } auto const sharedValue = makeSharedValue(*stream_ptr_, journal_); if (!sharedValue) - return shutdown(); // makeSharedValue logs + { + shutdown(); + return; // makeSharedValue logs + } try { @@ -553,14 +618,18 @@ ConnectAttempt::processResponse() { std::stringstream ss; ss << "Outbound Connect Attempt " << remote_endpoint_ << " " << to_string(result); - return fail(ss.str()); + fail(ss.str()); + return; } if (!socket_.is_open()) return; if (shutdown_) - return tryAsyncShutdown(); + { + tryAsyncShutdown(); + return; + } auto const peer = std::make_shared( app_, @@ -578,7 +647,8 @@ ConnectAttempt::processResponse() } catch (std::exception const& e) { - return fail(std::string("Handshake failure (") + e.what() + ")"); + fail(std::string("Handshake failure (") + e.what() + ")"); + return; } } diff --git a/src/xrpld/overlay/detail/Handshake.cpp b/src/xrpld/overlay/detail/Handshake.cpp index 715afc90e8..e9ad25bcc4 100644 --- a/src/xrpld/overlay/detail/Handshake.cpp +++ b/src/xrpld/overlay/detail/Handshake.cpp @@ -300,9 +300,11 @@ verifyHandshake( throw std::runtime_error("Invalid Local-IP"); if (beast::IP::is_public(remote) && remote != local_ip) + { throw std::runtime_error( "Incorrect Local-IP: " + remote.to_string() + " instead of " + local_ip.to_string()); + } } if (auto const iter = headers.find("Remote-IP"); iter != headers.end()) @@ -318,9 +320,11 @@ verifyHandshake( // We know our public IP and peer reports our connection came // from some other IP. if (remote_ip != public_ip) + { throw std::runtime_error( "Incorrect Remote-IP: " + public_ip.to_string() + " instead of " + remote_ip.to_string()); + } } } diff --git a/src/xrpld/overlay/detail/Message.cpp b/src/xrpld/overlay/detail/Message.cpp index 672ce995ca..754545f04a 100644 --- a/src/xrpld/overlay/detail/Message.cpp +++ b/src/xrpld/overlay/detail/Message.cpp @@ -106,7 +106,9 @@ Message::compress() setHeader(bufferCompressed_.data(), compressedSize, type, Algorithm::LZ4, messageBytes); } else + { bufferCompressed_.resize(0); + } } } @@ -188,10 +190,12 @@ Message::getBuffer(Compressed tryCompressed) std::call_once(once_flag_, &Message::compress, this); - if (bufferCompressed_.size() > 0) + if (!bufferCompressed_.empty()) + { return bufferCompressed_; - else - return buffer_; + } + + return buffer_; } int diff --git a/src/xrpld/overlay/detail/OverlayImpl.cpp b/src/xrpld/overlay/detail/OverlayImpl.cpp index d9680d7748..d9077686ec 100644 --- a/src/xrpld/overlay/detail/OverlayImpl.cpp +++ b/src/xrpld/overlay/detail/OverlayImpl.cpp @@ -24,6 +24,8 @@ #include #include +#include + namespace xrpl { namespace CrawlOptions { @@ -479,9 +481,13 @@ OverlayImpl::start() for (auto const& addr : addresses) { if (addr.port() == 0) + { ips.push_back(to_string(addr.at_port(DEFAULT_PEER_PORT))); + } else + { ips.push_back(to_string(addr)); + } } std::string const base("config: "); @@ -501,9 +507,13 @@ OverlayImpl::start() for (auto& addr : addresses) { if (addr.port() == 0) + { ips.emplace_back(addr.address(), DEFAULT_PEER_PORT); + } else + { ips.emplace_back(addr); + } } if (!ips.empty()) @@ -634,8 +644,10 @@ OverlayImpl::onManifests( } if (!relay.list().empty()) + { for_each([m2 = std::make_shared(relay, protocol::mtMANIFESTS)]( std::shared_ptr const& p) { p->send(m2); }); + } } void @@ -667,7 +679,7 @@ OverlayImpl::limit() } Json::Value -OverlayImpl::getOverlayInfo() +OverlayImpl::getOverlayInfo() const { using namespace std::chrono; Json::Value jv; @@ -695,8 +707,10 @@ OverlayImpl::getOverlayInfo() { auto version{sp->getVersion()}; if (!version.empty()) + { // Could move here if Json::value supported moving from strings pv[jss::version] = std::string{version}; + } } std::uint32_t minSeq = 0, maxSeq = 0; @@ -868,20 +882,18 @@ OverlayImpl::processValidatorList(http_request_type const& req, Handoff& handoff // 404 not found return fail(boost::beast::http::status::not_found); } - else if (!*vl) + if (!*vl) { return fail(boost::beast::http::status::bad_request); } - else - { - msg.result(boost::beast::http::status::ok); - msg.body() = *vl; + msg.result(boost::beast::http::status::ok); - msg.prepare_payload(); - handoff.response = std::make_shared(msg); - return true; - } + msg.body() = *vl; + + msg.prepare_payload(); + handoff.response = std::make_shared(msg); + return true; } bool @@ -909,19 +921,20 @@ OverlayImpl::processHealth(http_request_type const& req, Handoff& handoff) enum class HealthState { healthy, warning, critical }; auto health = HealthState::healthy; - auto set_health = [&health](HealthState state) { - if (health < state) - health = state; - }; + auto set_health = [&health](HealthState state) { health = std::max(health, state); }; msg.body()[jss::info] = Json::objectValue; if (last_validated_ledger_age >= 7 || last_validated_ledger_age < 0) { msg.body()[jss::info][jss::validated_ledger] = last_validated_ledger_age; if (last_validated_ledger_age < 20) + { set_health(HealthState::warning); + } else + { set_health(HealthState::critical); + } } if (amendment_blocked) @@ -934,9 +947,13 @@ OverlayImpl::processHealth(http_request_type const& req, Handoff& handoff) { msg.body()[jss::info][jss::peers] = number_peers; if (number_peers != 0) + { set_health(HealthState::warning); + } else + { set_health(HealthState::critical); + } } if (!(server_state == "full" || server_state == "validating" || server_state == "proposing")) @@ -947,16 +964,22 @@ OverlayImpl::processHealth(http_request_type const& req, Handoff& handoff) set_health(HealthState::warning); } else + { set_health(HealthState::critical); + } } if (load_factor > 100) { msg.body()[jss::info][jss::load_factor] = load_factor; if (load_factor < 1000) + { set_health(HealthState::warning); + } else + { set_health(HealthState::critical); + } } switch (health) @@ -1021,10 +1044,14 @@ OverlayImpl::getActivePeers( if (!reduceRelayEnabled) ++disabled; - if (toSkip.count(id) == 0) + if (!toSkip.contains(id)) + { ret.emplace_back(std::move(p)); + } else if (reduceRelayEnabled) + { ++enabledInSkip; + } } } @@ -1080,7 +1107,7 @@ OverlayImpl::relay(protocol::TMProposeSet& m, uint256 const& uid, PublicKey cons { auto const sm = std::make_shared(m, protocol::mtPROPOSE_LEDGER, validator); for_each([&](std::shared_ptr const& p) { - if (toSkip->find(p->id()) == toSkip->end()) + if (!toSkip->contains(p->id())) p->send(sm); }); return *toSkip; @@ -1102,7 +1129,7 @@ OverlayImpl::relay(protocol::TMValidation& m, uint256 const& uid, PublicKey cons { auto const sm = std::make_shared(m, protocol::mtVALIDATION, validator); for_each([&](std::shared_ptr const& p) { - if (toSkip->find(p->id()) == toSkip->end()) + if (!toSkip->contains(p->id())) p->send(sm); }); return *toSkip; @@ -1297,7 +1324,7 @@ OverlayImpl::sendEndpoints() } void -OverlayImpl::sendTxQueue() +OverlayImpl::sendTxQueue() const { for_each([](auto const& p) { if (p->txReduceRelayEnabled()) @@ -1347,17 +1374,23 @@ OverlayImpl::updateSlotAndSquelch( return; if (!strand_.running_in_this_thread()) - return post( + { + post( strand_, // Must capture copies of reference parameters (i.e. key, validator) [this, key = key, validator = validator, peers = std::move(peers), type]() mutable { updateSlotAndSquelch(key, validator, std::move(peers), type); }); + return; + } + for (auto id : peers) + { slots_.updateSlotAndSquelch(key, validator, id, type, [&]() { reportInboundTraffic(TrafficCount::squelch_ignored, 0); }); + } } void @@ -1371,12 +1404,17 @@ OverlayImpl::updateSlotAndSquelch( return; if (!strand_.running_in_this_thread()) - return post( - strand_, - // Must capture copies of reference parameters (i.e. key, validator) - [this, key = key, validator = validator, peer, type]() { - updateSlotAndSquelch(key, validator, peer, type); - }); + { + { + post( + strand_, + // Must capture copies of reference parameters (i.e. key, validator) + [this, key = key, validator = validator, peer, type]() { + updateSlotAndSquelch(key, validator, peer, type); + }); + } + return; + } slots_.updateSlotAndSquelch(key, validator, peer, type, [&]() { reportInboundTraffic(TrafficCount::squelch_ignored, 0); @@ -1387,7 +1425,10 @@ void OverlayImpl::deletePeer(Peer::id_t id) { if (!strand_.running_in_this_thread()) - return post(strand_, std::bind(&OverlayImpl::deletePeer, this, id)); + { + post(strand_, std::bind(&OverlayImpl::deletePeer, this, id)); + return; + } slots_.deletePeer(id, true); } @@ -1396,7 +1437,10 @@ void OverlayImpl::deleteIdlePeers() { if (!strand_.running_in_this_thread()) - return post(strand_, std::bind(&OverlayImpl::deleteIdlePeers, this)); + { + post(strand_, std::bind(&OverlayImpl::deleteIdlePeers, this)); + return; + } slots_.deleteIdlePeers(); } diff --git a/src/xrpld/overlay/detail/OverlayImpl.h b/src/xrpld/overlay/detail/OverlayImpl.h index 9e891e6e8a..b77b4e69aa 100644 --- a/src/xrpld/overlay/detail/OverlayImpl.h +++ b/src/xrpld/overlay/detail/OverlayImpl.h @@ -474,7 +474,7 @@ private: Controlled through the config section [crawl] overlay=[0|1] */ Json::Value - getOverlayInfo(); + getOverlayInfo() const; /** Returns information about the local server. Reported through the /crawl API @@ -522,7 +522,7 @@ private: /** Send once a second transactions' hashes aggregated by peers. */ void - sendTxQueue(); + sendTxQueue() const; /** Check if peers stopped relaying messages * and if slots stopped receiving messages from the validator */ diff --git a/src/xrpld/overlay/detail/PeerImp.cpp b/src/xrpld/overlay/detail/PeerImp.cpp index 18e784cdeb..7ed8c45453 100644 --- a/src/xrpld/overlay/detail/PeerImp.cpp +++ b/src/xrpld/overlay/detail/PeerImp.cpp @@ -134,7 +134,10 @@ void PeerImp::run() { if (!strand_.running_in_this_thread()) - return post(strand_, std::bind(&PeerImp::run, shared_from_this())); + { + post(strand_, std::bind(&PeerImp::run, shared_from_this())); + return; + } auto parseLedgerHash = [](std::string_view value) -> std::optional { if (uint256 ret; ret.parseHex(value)) @@ -177,9 +180,13 @@ PeerImp::run() } if (inbound_) + { doAccept(); + } else + { doProtocolStart(); + } // Anything else that needs to be done with the connection should be // done in doProtocolStart @@ -189,7 +196,10 @@ void PeerImp::stop() { if (!strand_.running_in_this_thread()) - return post(strand_, std::bind(&PeerImp::stop, shared_from_this())); + { + post(strand_, std::bind(&PeerImp::stop, shared_from_this())); + return; + } if (!socket_.is_open()) return; @@ -209,14 +219,20 @@ void PeerImp::send(std::shared_ptr const& m) { if (!strand_.running_in_this_thread()) - return post(strand_, std::bind(&PeerImp::send, shared_from_this(), m)); + { + post(strand_, std::bind(&PeerImp::send, shared_from_this(), m)); + return; + } if (!socket_.is_open()) return; // we are in progress of closing the connection if (shutdown_) - return tryAsyncShutdown(); + { + tryAsyncShutdown(); + return; + } auto validator = m->getValidatorKey(); if (validator && !squelch_.expireSquelch(*validator)) @@ -273,7 +289,10 @@ void PeerImp::sendTxQueue() { if (!strand_.running_in_this_thread()) - return post(strand_, std::bind(&PeerImp::sendTxQueue, shared_from_this())); + { + post(strand_, std::bind(&PeerImp::sendTxQueue, shared_from_this())); + return; + } if (!txQueue_.empty()) { @@ -291,7 +310,10 @@ void PeerImp::addTxQueue(uint256 const& hash) { if (!strand_.running_in_this_thread()) - return post(strand_, std::bind(&PeerImp::addTxQueue, shared_from_this(), hash)); + { + post(strand_, std::bind(&PeerImp::addTxQueue, shared_from_this(), hash)); + return; + } if (txQueue_.size() == reduce_relay::MAX_TX_QUEUE_SIZE) { @@ -307,7 +329,10 @@ void PeerImp::removeTxQueue(uint256 const& hash) { if (!strand_.running_in_this_thread()) - return post(strand_, std::bind(&PeerImp::removeTxQueue, shared_from_this(), hash)); + { + post(strand_, std::bind(&PeerImp::removeTxQueue, shared_from_this(), hash)); + return; + } auto removed = txQueue_.erase(hash); JLOG(p_journal_.trace()) << "removeTxQueue " << removed; @@ -366,8 +391,10 @@ PeerImp::json() ret[jss::cluster] = true; if (auto const n = name(); !n.empty()) + { // Could move here if Json::Value supported moving from a string ret[jss::name] = n; + } } if (auto const d = domain(); !d.empty()) @@ -545,10 +572,13 @@ void PeerImp::fail(std::string const& reason) { if (!strand_.running_in_this_thread()) - return post( + { + post( strand_, std::bind( (void (Peer::*)(std::string const&))&PeerImp::fail, shared_from_this(), reason)); + return; + } if (!socket_.is_open()) return; @@ -658,7 +688,8 @@ PeerImp::setTimer(std::chrono::seconds interval) catch (std::exception const& ex) { JLOG(journal_.error()) << "setTimer: " << ex.what(); - return shutdown(); + shutdown(); + return; } timer_.async_wait(bind_executor( @@ -691,7 +722,8 @@ PeerImp::onTimer(error_code const& ec) // This should never happen JLOG(journal_.error()) << "onTimer: " << ec.message(); - return close(); + close(); + return; } // the timer expired before the shutdown completed @@ -699,11 +731,15 @@ PeerImp::onTimer(error_code const& ec) if (shutdown_) { JLOG(journal_.debug()) << "onTimer: shutdown timer expired"; - return close(); + close(); + return; } if (large_sendq_++ >= Tuning::sendqIntervals) - return fail("Large send queue"); + { + fail("Large send queue"); + return; + } if (auto const t = tracking_.load(); !inbound_ && t != Tracking::converged) { @@ -718,13 +754,17 @@ PeerImp::onTimer(error_code const& ec) (t == Tracking::unknown && (duration > app_.config().MAX_UNKNOWN_TIME))) { overlay_.peerFinder().on_failure(slot_); - return fail("Not useful"); + fail("Not useful"); + return; } } // Already waiting for PONG if (lastPingSeq_) - return fail("Ping Timeout"); + { + fail("Ping Timeout"); + return; + } lastPingTime_ = clock_type::now(); lastPingSeq_ = rand_int(); @@ -761,14 +801,20 @@ PeerImp::doAccept() // a shutdown was initiated before the handshake, there is nothing to do if (shutdown_) - return tryAsyncShutdown(); + { + tryAsyncShutdown(); + return; + } auto const sharedValue = makeSharedValue(*stream_ptr_, journal_); // This shouldn't fail since we already computed // the shared value successfully in OverlayImpl if (!sharedValue) - return fail("makeSharedValue: Unexpected failure"); + { + fail("makeSharedValue: Unexpected failure"); + return; + } JLOG(journal_.debug()) << "Protocol: " << to_string(protocol_); @@ -811,12 +857,22 @@ PeerImp::doAccept() if (!socket_.is_open()) return; if (ec == boost::asio::error::operation_aborted) - return tryAsyncShutdown(); + { + tryAsyncShutdown(); + return; + } if (ec) - return fail("onWriteResponse", ec); + { + fail("onWriteResponse", ec); + return; + } if (write_buffer->size() == bytes_transferred) - return doProtocolStart(); - return fail("Failed to write header"); + { + doProtocolStart(); + return; + } + fail("Failed to write header"); + return; })); } @@ -842,7 +898,10 @@ PeerImp::doProtocolStart() { // a shutdown was initiated before the handshare, there is nothing to do if (shutdown_) - return tryAsyncShutdown(); + { + tryAsyncShutdown(); + return; + } onReadMessage(error_code(), 0); @@ -895,17 +954,25 @@ PeerImp::onReadMessage(error_code ec, std::size_t bytes_transferred) if (ec == boost::asio::error::eof) { JLOG(journal_.debug()) << "EOF"; - return shutdown(); + shutdown(); + return; } if (ec == boost::asio::error::operation_aborted) - return tryAsyncShutdown(); + { + tryAsyncShutdown(); + return; + } - return fail("onReadMessage", ec); + fail("onReadMessage", ec); + return; } // we started shutdown, no reason to process further data if (shutdown_) - return tryAsyncShutdown(); + { + tryAsyncShutdown(); + return; + } if (auto stream = journal_.trace()) { @@ -936,7 +1003,10 @@ PeerImp::onReadMessage(error_code ec, std::size_t bytes_transferred) // the error_code is produced by invokeProtocolMessage // it could be due to a bad message if (ec) - return fail("onReadMessage", ec); + { + fail("onReadMessage", ec); + return; + } if (bytes_consumed == 0) break; @@ -946,7 +1016,10 @@ PeerImp::onReadMessage(error_code ec, std::size_t bytes_transferred) // check if a shutdown was initiated while processing messages if (shutdown_) - return tryAsyncShutdown(); + { + tryAsyncShutdown(); + return; + } readPending_ = true; @@ -978,9 +1051,13 @@ PeerImp::onWriteMessage(error_code ec, std::size_t bytes_transferred) if (ec) { if (ec == boost::asio::error::operation_aborted) - return tryAsyncShutdown(); + { + tryAsyncShutdown(); + return; + } - return fail("onWriteMessage", ec); + fail("onWriteMessage", ec); + return; } if (auto stream = journal_.trace()) @@ -995,7 +1072,10 @@ PeerImp::onWriteMessage(error_code ec, std::size_t bytes_transferred) send_queue_.pop(); if (shutdown_) - return tryAsyncShutdown(); + { + tryAsyncShutdown(); + return; + } if (!send_queue_.empty()) { @@ -1003,7 +1083,7 @@ PeerImp::onWriteMessage(error_code ec, std::size_t bytes_transferred) XRPL_ASSERT(!shutdownStarted_, "xrpl::PeerImp::onWriteMessage : shutdown started"); // Timeout on writes only - return boost::asio::async_write( + boost::asio::async_write( stream_, boost::asio::buffer(send_queue_.front()->getBuffer(compressionEnabled_)), bind_executor( @@ -1013,6 +1093,7 @@ PeerImp::onWriteMessage(error_code ec, std::size_t bytes_transferred) shared_from_this(), std::placeholders::_1, std::placeholders::_2))); + return; } } @@ -1122,9 +1203,13 @@ PeerImp::onMessage(std::shared_ptr const& m) std::lock_guard sl(recentLock_); if (latency_) + { latency_ = (*latency_ * 7 + rtt) / 8; + } else + { latency_ = rtt; + } } return; @@ -1330,7 +1415,9 @@ PeerImp::handleTransaction( // Erase only if the server has seen this tx. If the server has not // seen this tx then the tx could not has been queued for this peer. else if (eraseTxQueue && txReduceRelayEnabled()) + { removeTxQueue(txID); + } overlay_.reportInboundTraffic( TrafficCount::category::transaction_duplicate, Message::messageSize(*m)); @@ -1402,7 +1489,10 @@ PeerImp::onMessage(std::shared_ptr const& m) // Verify ledger info type if (itype < protocol::liBASE || itype > protocol::liTS_CANDIDATE) - return badData("Invalid ledger info type"); + { + badData("Invalid ledger info type"); + return; + } auto const ltype = [&m]() -> std::optional<::protocol::TMLedgerType> { if (m->has_ltype()) @@ -1413,21 +1503,31 @@ PeerImp::onMessage(std::shared_ptr const& m) if (itype == protocol::liTS_CANDIDATE) { if (!m->has_ledgerhash()) - return badData("Invalid TX candidate set, missing TX set hash"); + { + badData("Invalid TX candidate set, missing TX set hash"); + return; + } } else if ( !m->has_ledgerhash() && !m->has_ledgerseq() && !(ltype && *ltype == protocol::ltCLOSED)) { - return badData("Invalid request"); + badData("Invalid request"); + return; } // Verify ledger type if (ltype && (*ltype < protocol::ltACCEPTED || *ltype > protocol::ltCLOSED)) - return badData("Invalid ledger type"); + { + badData("Invalid ledger type"); + return; + } // Verify ledger hash if (m->has_ledgerhash() && !stringIsUint256Sized(m->ledgerhash())) - return badData("Invalid ledger hash"); + { + badData("Invalid ledger hash"); + return; + } // Verify ledger sequence if (m->has_ledgerseq()) @@ -1439,7 +1539,8 @@ PeerImp::onMessage(std::shared_ptr const& m) if (app_.getLedgerMaster().getValidatedLedgerAge() <= 10s && ledgerSeq > app_.getLedgerMaster().getValidLedgerIndex() + 10) { - return badData("Invalid ledger sequence " + std::to_string(ledgerSeq)); + badData("Invalid ledger sequence " + std::to_string(ledgerSeq)); + return; } } @@ -1447,25 +1548,35 @@ PeerImp::onMessage(std::shared_ptr const& m) if (itype != protocol::liBASE) { if (m->nodeids_size() <= 0) - return badData("Invalid ledger node IDs"); + { + badData("Invalid ledger node IDs"); + return; + } for (auto const& nodeId : m->nodeids()) { if (deserializeSHAMapNodeID(nodeId) == std::nullopt) - return badData("Invalid SHAMap node ID"); + { + badData("Invalid SHAMap node ID"); + return; + } } } // Verify query type if (m->has_querytype() && m->querytype() != protocol::qtINDIRECT) - return badData("Invalid query type"); + { + badData("Invalid query type"); + return; + } // Verify query depth if (m->has_querydepth()) { if (m->querydepth() > Tuning::maxQueryDepth || itype == protocol::liBASE) { - return badData("Invalid query depth"); + badData("Invalid query depth"); + return; } } @@ -1496,9 +1607,13 @@ PeerImp::onMessage(std::shared_ptr const& m) if (reply.has_error()) { if (reply.error() == protocol::TMReplyError::reBAD_REQUEST) + { peer->charge(Resource::feeMalformedRequest, "proof_path_request"); + } else + { peer->charge(Resource::feeRequestNoReply, "proof_path_request"); + } } else { @@ -1542,9 +1657,13 @@ PeerImp::onMessage(std::shared_ptr const& m) if (reply.has_error()) { if (reply.error() == protocol::TMReplyError::reBAD_REQUEST) + { peer->charge(Resource::feeMalformedRequest, "replay_delta_request"); + } else + { peer->charge(Resource::feeRequestNoReply, "replay_delta_request"); + } } else { @@ -1579,7 +1698,10 @@ PeerImp::onMessage(std::shared_ptr const& m) // Verify ledger hash if (!stringIsUint256Sized(m->ledgerhash())) - return badData("Invalid ledger hash"); + { + badData("Invalid ledger hash"); + return; + } // Verify ledger sequence { @@ -1588,7 +1710,8 @@ PeerImp::onMessage(std::shared_ptr const& m) { if (ledgerSeq != 0) { - return badData("Invalid ledger sequence " + std::to_string(ledgerSeq)); + badData("Invalid ledger sequence " + std::to_string(ledgerSeq)); + return; } } else @@ -1598,26 +1721,32 @@ PeerImp::onMessage(std::shared_ptr const& m) if (app_.getLedgerMaster().getValidatedLedgerAge() <= 10s && ledgerSeq > app_.getLedgerMaster().getValidLedgerIndex() + 10) { - return badData("Invalid ledger sequence " + std::to_string(ledgerSeq)); + badData("Invalid ledger sequence " + std::to_string(ledgerSeq)); + return; } } } // Verify ledger info type if (m->type() < protocol::liBASE || m->type() > protocol::liTS_CANDIDATE) - return badData("Invalid ledger info type"); + { + badData("Invalid ledger info type"); + return; + } // Verify reply error if (m->has_error() && (m->error() < protocol::reNO_LEDGER || m->error() > protocol::reBAD_REQUEST)) { - return badData("Invalid reply error"); + badData("Invalid reply error"); + return; } // Verify ledger nodes. if (m->nodes_size() <= 0 || m->nodes_size() > Tuning::hardMaxReplyNodes) { - return badData("Invalid Ledger/TXset nodes " + std::to_string(m->nodes_size())); + badData("Invalid Ledger/TXset nodes " + std::to_string(m->nodes_size())); + return; } // If there is a request cookie, attempt to relay the message @@ -1770,7 +1899,9 @@ PeerImp::onMessage(std::shared_ptr const& m) { std::lock_guard sl(recentLock_); if (!last_status_.has_newstatus() || m->has_newstatus()) + { last_status_ = *m; + } else { // preserve old status @@ -2227,7 +2358,7 @@ PeerImp::onMessage(std::shared_ptr const& m fee_.update(Resource::feeUselessData, "unsupported peer"); return; } - else if (m->version() < 2) + if (m->version() < 2) { JLOG(p_journal_.debug()) << "ValidatorListCollection: received invalid validator list " @@ -2312,8 +2443,10 @@ PeerImp::onMessage(std::shared_ptr const& m) // peer receives within IDLED seconds since the message has been // relayed. if (relayed && (stopwatch().now() - *relayed) < reduce_relay::IDLED) + { overlay_.updateSlotAndSquelch( key, val->getSignerPublic(), id_, protocol::mtVALIDATION); + } // increase duplicate validations received overlay_.reportInboundTraffic( @@ -2483,7 +2616,9 @@ PeerImp::onMessage(std::shared_ptr const& m) JLOG(p_journal_.debug()) << "GetObj: Late fetch pack for " << pLSeq; } else + { progress = true; + } } } @@ -2584,11 +2719,13 @@ PeerImp::onMessage(std::shared_ptr const& m) overlay_.addTxMetrics(m->transactions_size()); for (std::uint32_t i = 0; i < m->transactions_size(); ++i) + { handleTransaction( std::shared_ptr( m->mutable_transactions(i), [](protocol::TMTransaction*) {}), false, true); + } } void @@ -2596,7 +2733,10 @@ PeerImp::onMessage(std::shared_ptr const& m) { using on_message_fn = void (PeerImp::*)(std::shared_ptr const&); if (!strand_.running_in_this_thread()) - return post(strand_, std::bind((on_message_fn)&PeerImp::onMessage, shared_from_this(), m)); + { + post(strand_, std::bind((on_message_fn)&PeerImp::onMessage, shared_from_this(), m)); + return; + } if (!m->has_validatorpubkey()) { @@ -2621,9 +2761,13 @@ PeerImp::onMessage(std::shared_ptr const& m) std::uint32_t duration = m->has_squelchduration() ? m->squelchduration() : 0; if (!m->squelch()) + { squelch_.removeSquelch(key); + } else if (!squelch_.addSquelch(key, std::chrono::seconds{duration})) + { fee_.update(Resource::feeInvalidData, "squelch duration"); + } JLOG(p_journal_.debug()) << "onMessage: TMSquelch " << slice << " " << id() << " " << duration; } @@ -2882,9 +3026,13 @@ PeerImp::checkPropose( bool relay = false; if (isTrusted) + { relay = app_.getOPs().processTrustedProposal(peerPos); + } else + { relay = app_.config().RELAY_UNTRUSTED_PROPOSALS == 1 || cluster(); + } if (relay) { @@ -2895,11 +3043,13 @@ PeerImp::checkPropose( auto haveMessage = app_.overlay().relay(*packet, peerPos.suppressionID(), peerPos.publicKey()); if (!haveMessage.empty()) + { overlay_.updateSlotAndSquelch( peerPos.suppressionID(), peerPos.publicKey(), std::move(haveMessage), protocol::mtPROPOSE_LEDGER); + } } } @@ -3235,7 +3385,8 @@ PeerImp::processLedgerRequest(std::shared_ptr const& m) // Add requested node data to reply if (m->nodeids_size() > 0) { - auto const queryDepth{m->has_querydepth() ? m->querydepth() : (isHighLatency() ? 2 : 1)}; + std::uint32_t const defaultDepth = isHighLatency() ? 2 : 1; + auto const queryDepth{m->has_querydepth() ? m->querydepth() : defaultDepth}; std::vector> data; @@ -3347,9 +3498,13 @@ PeerImp::getScore(bool haveItem) const } if (latency) + { score -= latency->count() * spLatency; + } else + { score -= spNoLatency; + } return score; } diff --git a/src/xrpld/overlay/detail/TrafficCount.cpp b/src/xrpld/overlay/detail/TrafficCount.cpp index f782d7cf0a..2ce32b4468 100644 --- a/src/xrpld/overlay/detail/TrafficCount.cpp +++ b/src/xrpld/overlay/detail/TrafficCount.cpp @@ -36,16 +36,22 @@ TrafficCount::categorize( if (auto msg = dynamic_cast(&message)) { if (msg->type() == protocol::liTS_CANDIDATE) + { return (inbound && !msg->has_requestcookie()) ? TrafficCount::category::ld_tsc_get : TrafficCount::category::ld_tsc_share; + } if (msg->type() == protocol::liTX_NODE) + { return (inbound && !msg->has_requestcookie()) ? TrafficCount::category::ld_txn_get : TrafficCount::category::ld_txn_share; + } if (msg->type() == protocol::liAS_NODE) + { return (inbound && !msg->has_requestcookie()) ? TrafficCount::category::ld_asn_get : TrafficCount::category::ld_asn_share; + } return (inbound && !msg->has_requestcookie()) ? TrafficCount::category::ld_get : TrafficCount::category::ld_share; @@ -54,16 +60,22 @@ TrafficCount::categorize( if (auto msg = dynamic_cast(&message)) { if (msg->itype() == protocol::liTS_CANDIDATE) + { return (inbound || msg->has_requestcookie()) ? TrafficCount::category::gl_tsc_share : TrafficCount::category::gl_tsc_get; + } if (msg->itype() == protocol::liTX_NODE) + { return (inbound || msg->has_requestcookie()) ? TrafficCount::category::gl_txn_share : TrafficCount::category::gl_txn_get; + } if (msg->itype() == protocol::liAS_NODE) + { return (inbound || msg->has_requestcookie()) ? TrafficCount::category::gl_asn_share : TrafficCount::category::gl_asn_get; + } return (inbound || msg->has_requestcookie()) ? TrafficCount::category::gl_share : TrafficCount::category::gl_get; @@ -72,28 +84,40 @@ TrafficCount::categorize( if (auto msg = dynamic_cast(&message)) { if (msg->type() == protocol::TMGetObjectByHash::otLEDGER) + { return (msg->query() == inbound) ? TrafficCount::category::share_hash_ledger : TrafficCount::category::get_hash_ledger; + } if (msg->type() == protocol::TMGetObjectByHash::otTRANSACTION) + { return (msg->query() == inbound) ? TrafficCount::category::share_hash_tx : TrafficCount::category::get_hash_tx; + } if (msg->type() == protocol::TMGetObjectByHash::otTRANSACTION_NODE) + { return (msg->query() == inbound) ? TrafficCount::category::share_hash_txnode : TrafficCount::category::get_hash_txnode; + } if (msg->type() == protocol::TMGetObjectByHash::otSTATE_NODE) + { return (msg->query() == inbound) ? TrafficCount::category::share_hash_asnode : TrafficCount::category::get_hash_asnode; + } if (msg->type() == protocol::TMGetObjectByHash::otCAS_OBJECT) + { return (msg->query() == inbound) ? TrafficCount::category::share_cas_object : TrafficCount::category::get_cas_object; + } if (msg->type() == protocol::TMGetObjectByHash::otFETCH_PACK) + { return (msg->query() == inbound) ? TrafficCount::category::share_fetch_pack : TrafficCount::category::get_fetch_pack; + } if (msg->type() == protocol::TMGetObjectByHash::otTRANSACTIONS) return TrafficCount::category::get_transactions; diff --git a/src/xrpld/peerfinder/PeerfinderManager.h b/src/xrpld/peerfinder/PeerfinderManager.h index ab53068fca..b850a10975 100644 --- a/src/xrpld/peerfinder/PeerfinderManager.h +++ b/src/xrpld/peerfinder/PeerfinderManager.h @@ -74,7 +74,7 @@ struct Config /** Write the configuration into a property stream */ void - onWrite(beast::PropertyStream::Map& map); + onWrite(beast::PropertyStream::Map& map) const; /** Make PeerFinder::Config from configuration parameters * @param config server's configuration diff --git a/src/xrpld/peerfinder/detail/Bootcache.cpp b/src/xrpld/peerfinder/detail/Bootcache.cpp index af9a1ad57b..d07ec444a4 100644 --- a/src/xrpld/peerfinder/detail/Bootcache.cpp +++ b/src/xrpld/peerfinder/detail/Bootcache.cpp @@ -4,6 +4,8 @@ #include +#include + namespace xrpl { namespace PeerFinder { @@ -131,8 +133,7 @@ Bootcache::on_success(beast::IP::Endpoint const& endpoint) else { Entry entry(result.first->right); - if (entry.valence() < 0) - entry.valence() = 0; + entry.valence() = std::max(entry.valence(), 0); ++entry.valence(); m_map.erase(result.first); result = m_map.insert(value_type(endpoint, entry)); @@ -156,8 +157,7 @@ Bootcache::on_failure(beast::IP::Endpoint const& endpoint) else { Entry entry(result.first->right); - if (entry.valence() > 0) - entry.valence() = 0; + entry.valence() = std::min(entry.valence(), 0); --entry.valence(); m_map.erase(result.first); result = m_map.insert(value_type(endpoint, entry)); diff --git a/src/xrpld/peerfinder/detail/PeerfinderConfig.cpp b/src/xrpld/peerfinder/detail/PeerfinderConfig.cpp index 58246cd198..cc74018fc0 100644 --- a/src/xrpld/peerfinder/detail/PeerfinderConfig.cpp +++ b/src/xrpld/peerfinder/detail/PeerfinderConfig.cpp @@ -1,6 +1,8 @@ #include #include +#include + namespace xrpl { namespace PeerFinder { @@ -51,7 +53,7 @@ Config::applyTuning() } void -Config::onWrite(beast::PropertyStream::Map& map) +Config::onWrite(beast::PropertyStream::Map& map) const { map["max_peers"] = maxPeers; map["out_peers"] = outPeers; @@ -81,8 +83,7 @@ Config::makeConfig( if (cfg.PEERS_MAX != 0) config.maxPeers = cfg.PEERS_MAX; - if (config.maxPeers < Tuning::minOutCount) - config.maxPeers = Tuning::minOutCount; + config.maxPeers = std::max(config.maxPeers, Tuning::minOutCount); config.outPeers = config.calcOutPeers(); // Calculate the number of outbound peers we want. If we dont want @@ -93,9 +94,13 @@ Config::makeConfig( // Calculate the largest number of inbound connections we could // take. if (config.maxPeers >= config.outPeers) + { config.inPeers = config.maxPeers - config.outPeers; + } else + { config.inPeers = 0; + } } else { diff --git a/src/xrpld/peerfinder/detail/PeerfinderManager.cpp b/src/xrpld/peerfinder/detail/PeerfinderManager.cpp index d04e09441c..70f082c0d5 100644 --- a/src/xrpld/peerfinder/detail/PeerfinderManager.cpp +++ b/src/xrpld/peerfinder/detail/PeerfinderManager.cpp @@ -33,8 +33,7 @@ public: beast::Journal journal, BasicConfig const& config, beast::insight::Collector::ptr const& collector) - : Manager() - , io_context_(io_context) + : io_context_(io_context) , work_(std::in_place, boost::asio::make_work_guard(io_context_)) , m_clock(clock) , m_journal(journal) diff --git a/src/xrpld/perflog/detail/PerfLogImp.cpp b/src/xrpld/perflog/detail/PerfLogImp.cpp index eb271ac91a..fc9ef70830 100644 --- a/src/xrpld/perflog/detail/PerfLogImp.cpp +++ b/src/xrpld/perflog/detail/PerfLogImp.cpp @@ -257,8 +257,10 @@ void PerfLogImp::report() { if (!logFile_) + { // If logFile_ is not writable do no further work. return; + } auto const present = system_clock::now(); if (present < lastLog_ + setup_.logInterval) @@ -345,9 +347,13 @@ PerfLogImp::rpcEnd(std::string const& method, std::uint64_t const requestId, boo } std::lock_guard lock(counter->second.mutex); if (finish) + { ++counter->second.value.finished; + } else + { ++counter->second.value.errored; + } counter->second.value.duration += std::chrono::duration_cast(steady_clock::now() - startTime); } @@ -437,7 +443,7 @@ PerfLogImp::rotate() void PerfLogImp::start() { - if (setup_.perfLog.size()) + if (!setup_.perfLog.empty()) thread_ = std::thread(&PerfLogImp::run, this); } @@ -463,7 +469,7 @@ setup_PerfLog(Section const& section, boost::filesystem::path const& configDir) PerfLog::Setup setup; std::string perfLog; set(perfLog, "perf_log", section); - if (perfLog.size()) + if (!perfLog.empty()) { setup.perfLog = boost::filesystem::path(perfLog); if (setup.perfLog.is_relative()) diff --git a/src/xrpld/rpc/detail/Handler.cpp b/src/xrpld/rpc/detail/Handler.cpp index ec970b107e..04cf0420b7 100644 --- a/src/xrpld/rpc/detail/Handler.cpp +++ b/src/xrpld/rpc/detail/Handler.cpp @@ -42,9 +42,13 @@ handle(JsonContext& context, Object& object) auto status = handler.check(); if (status) + { status.inject(object); + } else + { handler.writeResult(object); + } return status; } @@ -172,9 +176,11 @@ private: { if (overlappingApiVersion( table_.equal_range(entry.name_), entry.minApiVer_, entry.maxApiVer_)) + { LogicError( std::string("Handler for ") + entry.name_ + " overlaps with an existing handler"); + } table_.insert({entry.name_, entry}); } @@ -232,9 +238,11 @@ private: table_.equal_range(HandlerImpl::name), HandlerImpl::minApiVer, HandlerImpl::maxApiVer)) + { LogicError( std::string("Handler for ") + HandlerImpl::name + " overlaps with an existing handler"); + } table_.insert({HandlerImpl::name, handlerFrom()}); } diff --git a/src/xrpld/rpc/detail/RPCCall.cpp b/src/xrpld/rpc/detail/RPCCall.cpp index 43ca166f9f..cd36208294 100644 --- a/src/xrpld/rpc/detail/RPCCall.cpp +++ b/src/xrpld/rpc/detail/RPCCall.cpp @@ -116,7 +116,7 @@ private: jvResult[jss::currency] = strCurrency; - if (strIssuer.length()) + if (!strIssuer.empty()) { // Could confirm issuer is a valid Ripple address. jvResult[jss::issuer] = strIssuer; @@ -124,11 +124,9 @@ private: return jvResult; } - else - { - return RPC::make_param_error( - std::string("Invalid currency/issuer '") + strCurrencyIssuer + "'"); - } + + return RPC::make_param_error( + std::string("Invalid currency/issuer '") + strCurrencyIssuer + "'"); } static bool @@ -212,6 +210,7 @@ private: // account_tx accountID [ledger_min [ledger_max [limit [offset]]]] [binary] // [count] [descending] Json::Value + // NOLINTNEXTLINE(readability-make-member-function-const) parseAccountTransactions(Json::Value const& jvParams) { Json::Value jvRequest(Json::objectValue); @@ -298,19 +297,15 @@ private: { return jvTakerPays; } - else - { - jvRequest[jss::taker_pays] = jvTakerPays; - } + + jvRequest[jss::taker_pays] = jvTakerPays; if (isRpcError(jvTakerGets)) { return jvTakerGets; } - else - { - jvRequest[jss::taker_gets] = jvTakerGets; - } + + jvRequest[jss::taker_gets] = jvTakerGets; if (jvParams.size() >= 3) { @@ -366,9 +361,13 @@ private: std::string input = jvParams[0u].asString(); if (input.find_first_not_of("0123456789") == std::string::npos) + { jvRequest["can_delete"] = jvParams[0u].asUInt(); + } else + { jvRequest["can_delete"] = input; + } return jvRequest; } @@ -447,11 +446,17 @@ private: // determines whether an amendment is vetoed - so "reject" means // that jss::vetoed is true. if (boost::iequals(action, "reject")) + { jvRequest[jss::vetoed] = Json::Value(true); + } else if (boost::iequals(action, "accept")) + { jvRequest[jss::vetoed] = Json::Value(false); + } else + { return rpcError(rpcINVALID_PARAMS); + } } return jvRequest; @@ -967,8 +972,7 @@ private: return jvRequest; } - else if ( - (jvParams.size() >= 2 || bOffline) && reader.parse(jvParams[1u].asString(), txJSON)) + if ((jvParams.size() >= 2 || bOffline) && reader.parse(jvParams[1u].asString(), txJSON)) { // Signing or submitting tx_json. Json::Value jvRequest{Json::objectValue}; @@ -1055,9 +1059,13 @@ private: } if (jvParams[0u].asString().length() == 16) + { jvRequest[jss::ctid] = jvParams[0u].asString(); + } else + { jvRequest[jss::transaction] = jvParams[0u].asString(); + } return jvRequest; } @@ -1123,9 +1131,13 @@ private: if (param[0] != 'r') { if (param.size() == 64) + { jvRequest[jss::ledger_hash] = param; + } else + { jvRequest[jss::ledger_index] = param; + } if (size <= index) return RPC::make_param_error("Invalid hotwallet"); @@ -1355,10 +1367,12 @@ struct RPCCallImp // Receive reply if (strData.empty()) + { Throw( "no response from server. Please " "ensure that the rippled server is running in another " "process."); + } // Parse reply JLOG(j.debug()) << "RPC reply: " << strData << std::endl; @@ -1435,9 +1449,13 @@ rpcCmdToJson( }; if (jvRequest.isObject()) + { insert_api_version(jvRequest); + } else if (jvRequest.isArray()) + { std::for_each(jvRequest.begin(), jvRequest.end(), insert_api_version); + } JLOG(j.trace()) << "RPC Request: " << jvRequest << std::endl; return jvRequest; @@ -1500,7 +1518,9 @@ rpcClient( jvRequest["admin_password"] = setup.client.admin_password; if (jvRequest.isObject()) + { jvParams.append(jvRequest); + } else if (jvRequest.isArray()) { for (Json::UInt i = 0; i < jvRequest.size(); ++i) @@ -1516,9 +1536,12 @@ rpcClient( setup.client.user, setup.client.password, "", - jvRequest.isMember(jss::method) // Allow parser to rewrite method. - ? jvRequest[jss::method].asString() - : jvRequest.isArray() ? "batch" : args[0], + // Allow parser to rewrite method. + [&]() -> std::string { + if (jvRequest.isMember(jss::method)) + return jvRequest[jss::method].asString(); + return jvRequest.isArray() ? "batch" : args[0]; + }(), jvParams, // Parsed, execute. setup.client.secure != 0, // Use SSL config.quiet(), @@ -1557,11 +1580,17 @@ rpcClient( { jvOutput[jss::status] = "error"; if (jvOutput.isMember(jss::error_code)) + { nRet = std::stoi(jvOutput[jss::error_code].asString()); + } else if (jvOutput[jss::error].isMember(jss::error_code)) + { nRet = std::stoi(jvOutput[jss::error][jss::error_code].asString()); + } else + { nRet = rpcBAD_SYNTAX; + } } // YYY We could have a command line flag for single line output for diff --git a/src/xrpld/rpc/detail/RPCHandler.cpp b/src/xrpld/rpc/detail/RPCHandler.cpp index 2066c8a5e9..840ebd5946 100644 --- a/src/xrpld/rpc/detail/RPCHandler.cpp +++ b/src/xrpld/rpc/detail/RPCHandler.cpp @@ -215,11 +215,9 @@ doCommand(RPC::JsonContext& context, Json::Value& result) return ret; } - else - { - auto ret = callMethod(context, method, handler->name_, result); - return ret; - } + + auto ret = callMethod(context, method, handler->name_, result); + return ret; } return rpcUNKNOWN_COMMAND; diff --git a/src/xrpld/rpc/detail/RPCHelpers.cpp b/src/xrpld/rpc/detail/RPCHelpers.cpp index 385bc7f4af..832ff778e1 100644 --- a/src/xrpld/rpc/detail/RPCHelpers.cpp +++ b/src/xrpld/rpc/detail/RPCHelpers.cpp @@ -24,9 +24,13 @@ getStartHint(std::shared_ptr const& sle, AccountID const& accountID) if (sle->getType() == ltRIPPLE_STATE) { if (sle->getFieldAmount(sfLowLimit).getIssuer() == accountID) + { return sle->getFieldU64(sfLowNode); - else if (sle->getFieldAmount(sfHighLimit).getIssuer() == accountID) + } + if (sle->getFieldAmount(sfHighLimit).getIssuer() == accountID) + { return sle->getFieldU64(sfHighNode); + } } if (!sle->isFieldPresent(sfOwnerNode)) @@ -46,7 +50,7 @@ isRelatedToAccount( return (sle->getFieldAmount(sfLowLimit).getIssuer() == accountID) || (sle->getFieldAmount(sfHighLimit).getIssuer() == accountID); } - else if (sle->isFieldPresent(sfAccount)) + if (sle->isFieldPresent(sfAccount)) { // If there's an sfAccount present, also test the sfDestination, if // present. This will match objects such as Escrows (ltESCROW), Payment @@ -57,12 +61,12 @@ isRelatedToAccount( return sle->getAccountID(sfAccount) == accountID || (sle->isFieldPresent(sfDestination) && sle->getAccountID(sfDestination) == accountID); } - else if (sle->getType() == ltSIGNER_LIST) + if (sle->getType() == ltSIGNER_LIST) { Keylet const accountSignerList = keylet::signers(accountID); return sle->key() == accountSignerList.key; } - else if (sle->getType() == ltNFTOKEN_OFFER) + if (sle->getType() == ltNFTOKEN_OFFER) { // Do not check the sfDestination field. NFToken Offers are NOT added to // the Destination account's directory. @@ -234,9 +238,13 @@ keypairForSignature(Json::Value const& params, Json::Value& error, unsigned int if (!keyType) { if (apiVersion > 1u) + { error = RPC::make_error(rpcBAD_KEY_TYPE); + } else + { error = RPC::invalid_field_error(jss::key_type); + } return {}; } @@ -279,7 +287,9 @@ keypairForSignature(Json::Value const& params, Json::Value& error, unsigned int if (!seed) { if (has_key_type) + { seed = getSeedFromRPC(params, error); + } else { if (!params[jss::secret].isString()) diff --git a/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp b/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp index acf9ecd23a..54ff515894 100644 --- a/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp +++ b/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp @@ -78,10 +78,12 @@ ledgerFromRequest(T& ledger, JsonContext const& context) // while `ledger` is still supported, it is deprecated // and therefore shouldn't be mentioned in the error message if (hasLedger) + { return { rpcINVALID_PARAMS, "Exactly one of 'ledger', 'ledger_hash', or " "'ledger_index' can be specified."}; + } return { rpcINVALID_PARAMS, "Exactly one of 'ledger_hash' or " @@ -97,9 +99,11 @@ ledgerFromRequest(T& ledger, JsonContext const& context) return {rpcINVALID_PARAMS, expected_field_message(jss::ledger, "string or number")}; } if (legacyLedger.isString() && legacyLedger.asString().size() == 64) + { return ledgerFromHash(ledger, legacyLedger, context, jss::ledger); - else - return ledgerFromIndex(ledger, legacyLedger, context, jss::ledger); + } + + return ledgerFromIndex(ledger, legacyLedger, context, jss::ledger); } if (hasHash) @@ -182,17 +186,15 @@ ledgerFromSpecifier( { return getLedger(ledger, LedgerShortcut::Validated, context); } - else + + if (shortcut == org::xrpl::rpc::v1::LedgerSpecifier::SHORTCUT_CURRENT || + shortcut == org::xrpl::rpc::v1::LedgerSpecifier::SHORTCUT_UNSPECIFIED) { - if (shortcut == org::xrpl::rpc::v1::LedgerSpecifier::SHORTCUT_CURRENT || - shortcut == org::xrpl::rpc::v1::LedgerSpecifier::SHORTCUT_UNSPECIFIED) - { - return getLedger(ledger, LedgerShortcut::Current, context); - } - else if (shortcut == org::xrpl::rpc::v1::LedgerSpecifier::SHORTCUT_CLOSED) - { - return getLedger(ledger, LedgerShortcut::Closed, context); - } + return getLedger(ledger, LedgerShortcut::Current, context); + } + if (shortcut == org::xrpl::rpc::v1::LedgerSpecifier::SHORTCUT_CLOSED) + { + return getLedger(ledger, LedgerShortcut::Closed, context); } } } diff --git a/src/xrpld/rpc/detail/RPCSub.cpp b/src/xrpld/rpc/detail/RPCSub.cpp index 49a78d0755..233981001a 100644 --- a/src/xrpld/rpc/detail/RPCSub.cpp +++ b/src/xrpld/rpc/detail/RPCSub.cpp @@ -34,16 +34,29 @@ public: parsedURL pUrl; if (!parseUrl(pUrl, strUrl)) + { Throw("Failed to parse url."); + } else if (pUrl.scheme == "https") + { mSSL = true; + } else if (pUrl.scheme != "http") + { Throw("Only http and https is supported."); + } mSeq = 1; mIp = pUrl.domain; - mPort = (!pUrl.port) ? (mSSL ? 443 : 80) : *pUrl.port; + if (!pUrl.port) + { + mPort = mSSL ? 443 : 80; + } + else + { + mPort = *pUrl.port; + } mPath = pUrl.path; JLOG(j_.info()) << "RPCCall::fromNetwork sub: ip=" << mIp << " port=" << mPort diff --git a/src/xrpld/rpc/detail/Role.cpp b/src/xrpld/rpc/detail/Role.cpp index e040a55c69..499787cece 100644 --- a/src/xrpld/rpc/detail/Role.cpp +++ b/src/xrpld/rpc/detail/Role.cpp @@ -83,7 +83,7 @@ requestRole( if (ipAllowed(remoteIp.address(), port.secure_gateway_nets_v4, port.secure_gateway_nets_v6)) { - if (user.size()) + if (!user.empty()) return Role::IDENTIFIED; return Role::PROXY; } @@ -137,9 +137,11 @@ extractIpAddrFromField(std::string_view field) { std::size_t const firstNonSpace = ret.find_first_not_of(' '); if (firstNonSpace == std::string_view::npos) + { // We know there's at least one leading space. So if we got // npos, then it must be all spaces. Return empty string_view. return {}; + } ret = ret.substr(firstNonSpace); } @@ -151,9 +153,11 @@ extractIpAddrFromField(std::string_view field) { std::size_t const lastNonSpace = ret.find_last_not_of(" \r\n"); if (lastNonSpace == std::string_view::npos) + { // We know there's at least one leading space. So if we // got npos, then it must be all spaces. return {}; + } ret = ret.substr(0, lastNonSpace + 1); } diff --git a/src/xrpld/rpc/detail/ServerHandler.cpp b/src/xrpld/rpc/detail/ServerHandler.cpp index 39f0be6722..f5187d6285 100644 --- a/src/xrpld/rpc/detail/ServerHandler.cpp +++ b/src/xrpld/rpc/detail/ServerHandler.cpp @@ -363,9 +363,13 @@ void logDuration(Json::Value const& request, T const& duration, beast::Journal& journal) { using namespace std::chrono_literals; - auto const level = (duration >= 10s) ? journal.error() - : (duration >= 1s) ? journal.warn() - : journal.debug(); + auto const level = [&]() { + if (duration >= 10s) + return journal.error(); + if (duration >= 1s) + return journal.warn(); + return journal.debug(); + }(); JLOG(level) << "RPC request processing duration = " << std::chrono::duration_cast(duration).count() @@ -535,9 +539,13 @@ ServerHandler::processSession( }()); if (beast::rfc2616::is_keep_alive(session->request())) + { session->complete(); + } else + { session->close(true); + } } static Json::Value @@ -643,8 +651,10 @@ ServerHandler::processRequest( auto role = Role::FORBID; auto required = Role::FORBID; if (jsonRPC.isMember(jss::method) && jsonRPC[jss::method].isString()) + { required = RPC::roleRequired( apiVersion, app_.config().BETA_RPC_API, jsonRPC[jss::method].asString()); + } if (jsonRPC.isMember(jss::params) && jsonRPC[jss::params].isArray() && jsonRPC[jss::params].size() > 0 && jsonRPC[jss::params][Json::UInt(0)].isObjectOrNull()) @@ -749,8 +759,9 @@ ServerHandler::processRequest( { params = jsonRPC[jss::params]; if (!params) + { params = Json::Value(Json::objectValue); - + } else if (!params.isArray() || params.size() != 1) { usage.charge(Resource::feeMalformedRPC); @@ -909,9 +920,13 @@ ServerHandler::processRequest( if (params.isMember(jss::id)) r[jss::id] = params[jss::id]; if (batch) + { reply.append(std::move(r)); + } else + { reply = std::move(r); + } if (reply.isMember(jss::result) && reply[jss::result].isMember(jss::result)) { @@ -957,9 +972,13 @@ ServerHandler::processRequest( { static int const maxSize = 10000; if (response.size() <= maxSize) + { stream << "Reply: " << response; + } else + { stream << "Reply: " << response.substr(0, maxSize); + } } HTTPReply(httpStatus, response, output, rpcJ); @@ -1009,10 +1028,14 @@ ServerHandler::Setup::makeContexts() if (p.secure()) { if (p.ssl_key.empty() && p.ssl_cert.empty() && p.ssl_chain.empty()) + { p.context = make_SSLContext(p.ssl_ciphers); + } else + { p.context = make_SSLContextAuthed(p.ssl_key, p.ssl_cert, p.ssl_chain, p.ssl_ciphers); + } } else { @@ -1113,9 +1136,13 @@ 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()) + { it = result.erase(it); + } else + { ++it; + } } } else @@ -1143,15 +1170,22 @@ setup_Client(ServerHandler::Setup& setup) { decltype(setup.ports)::const_iterator iter; for (iter = setup.ports.cbegin(); iter != setup.ports.cend(); ++iter) + { if (iter->protocol.count("http") > 0 || iter->protocol.count("https") > 0) break; + } if (iter == setup.ports.cend()) return; setup.client.secure = iter->protocol.count("https") > 0; - setup.client.ip = beast::IP::is_unspecified(iter->ip) ? - // VFALCO HACK! to make localhost work - (iter->ip.is_v6() ? "::1" : "127.0.0.1") - : iter->ip.to_string(); + if (beast::IP::is_unspecified(iter->ip)) + { + // VFALCO HACK! to make localhost work + setup.client.ip = iter->ip.is_v6() ? "::1" : "127.0.0.1"; + } + else + { + setup.client.ip = iter->ip.to_string(); + } setup.client.port = iter->port; setup.client.user = iter->user; setup.client.password = iter->password; diff --git a/src/xrpld/rpc/detail/TransactionSign.cpp b/src/xrpld/rpc/detail/TransactionSign.cpp index 8afe3612fe..80c608dbbf 100644 --- a/src/xrpld/rpc/detail/TransactionSign.cpp +++ b/src/xrpld/rpc/detail/TransactionSign.cpp @@ -72,7 +72,7 @@ public: bool validMultiSign() const { - return isMultiSigning() && multiSignPublicKey_ && multiSignature_.size(); + return isMultiSigning() && multiSignPublicKey_ && !multiSignature_.empty(); } // Don't call this method unless isMultiSigning() returns true. @@ -179,11 +179,15 @@ checkPayment( if (tx_json.isMember(jss::Amount)) { if (tx_json[jss::DeliverMax] != tx_json[jss::Amount]) + { return RPC::make_error( rpcINVALID_PARAMS, "Cannot specify differing 'Amount' and 'DeliverMax'"); + } } else + { tx_json[jss::Amount] = tx_json[jss::DeliverMax]; + } tx_json.removeMember(jss::DeliverMax); } @@ -204,12 +208,16 @@ checkPayment( return RPC::invalid_field_error("tx_json.Destination"); if (params.isMember(jss::build_path) && ((doPath == false) || amount.holds())) + { return RPC::make_error( rpcINVALID_PARAMS, "Field 'build_path' not allowed in this context."); + } if (tx_json.isMember(jss::Paths) && params.isMember(jss::build_path)) + { return RPC::make_error( rpcINVALID_PARAMS, "Cannot specify both 'tx_json.Paths' and 'build_path'"); + } std::optional domain; if (tx_json.isMember(sfDomainID.jsonName)) @@ -220,10 +228,8 @@ checkPayment( { return RPC::make_error(rpcDOMAIN_MALFORMED, "Unable to parse 'DomainID'."); } - else - { - domain = num; - } + + domain = num; } if (!tx_json.isMember(jss::Paths) && params.isMember(jss::build_path)) @@ -338,9 +344,13 @@ checkTxJsonFields( if (verify && !config.standalone() && (validatedLedgerAge > Tuning::maxValidatedLedgerAge)) { if (apiVersion == 1) + { ret.first = rpcError(rpcNO_CURRENT); + } else + { ret.first = rpcError(rpcNOT_SYNCED); + } return ret; } @@ -525,8 +535,10 @@ transactionPreProcessImpl( if (verify) { if (!sle) + { // XXX Ignore transactions for accounts not created. return rpcError(rpcSRC_ACT_NOT_FOUND); + } JLOG(j.trace()) << "verify: " << toBase58(calcAccountID(pk)) << " : " << toBase58(srcAddressID); @@ -592,8 +604,10 @@ transactionPreProcessImpl( { // If the target object doesn't exist, make one. if (!parsed.object->isFieldPresent(*signatureTarget)) + { parsed.object->setFieldObject( *signatureTarget, STObject{*signatureTemplate, *signatureTarget}); + } sigObject = &parsed.object->peekFieldObject(*signatureTarget); } sigObject->setFieldVL( @@ -666,8 +680,10 @@ transactionConstructImpl( // Check the signature if that's called for. auto sttxNew = std::make_shared(sit); if (!app.checkSigs()) + { forceValidity( app.getHashRouter(), sttxNew->getTransactionID(), Validity::SigGoodOnly); + } if (checkValidity(app.getHashRouter(), *sttxNew, rules).first != Validity::Valid) { ret.first = RPC::make_error(rpcINTERNAL, "Invalid signature."); @@ -714,7 +730,9 @@ transactionFormatResultImpl(Transaction::pointer tpTrans, unsigned apiVersion) jvResult[jss::hash] = to_string(tpTrans->getID()); } else + { jvResult[jss::tx_json] = tpTrans->getJson(JsonOptions::none); + } RPC::insertDeliverMax( jvResult[jss::tx_json], tpTrans->getSTransaction()->getTxnType(), apiVersion); @@ -880,9 +898,11 @@ checkFee( { mult = request[jss::fee_mult_max].asInt(); if (mult < 0) + { return RPC::make_error( rpcINVALID_PARAMS, RPC::expected_field_message(jss::fee_mult_max, "a positive integer")); + } } else { @@ -896,9 +916,11 @@ checkFee( { div = request[jss::fee_div_max].asInt(); if (div <= 0) + { return RPC::make_error( rpcINVALID_PARAMS, RPC::expected_field_message(jss::fee_div_max, "a positive integer")); + } } else { @@ -1024,8 +1046,10 @@ checkMultiSignFields(Json::Value const& jvRequest) // Account. if (!jvRequest.isMember(jss::signature_target) && !tx_json[sfSigningPubKey.getJsonName()].asString().empty()) + { return RPC::make_error( rpcINVALID_PARAMS, "When multi-signing 'tx_json.SigningPubKey' must be empty."); + } return Json::Value(); } diff --git a/src/xrpld/rpc/handlers/AMMInfo.cpp b/src/xrpld/rpc/handlers/AMMInfo.cpp index e174a49f87..42e44f004d 100644 --- a/src/xrpld/rpc/handlers/AMMInfo.cpp +++ b/src/xrpld/rpc/handlers/AMMInfo.cpp @@ -75,17 +75,25 @@ doAMMInfo(RPC::JsonContext& context) if (params.isMember(jss::asset)) { if (auto const i = getIssue(params[jss::asset], context.j)) + { issue1 = *i; + } else + { return Unexpected(i.error()); + } } if (params.isMember(jss::asset2)) { if (auto const i = getIssue(params[jss::asset2], context.j)) + { issue2 = *i; + } else + { return Unexpected(i.error()); + } } if (params.isMember(jss::amm_account)) @@ -204,11 +212,15 @@ doAMMInfo(RPC::JsonContext& context) } if (!isXRP(asset1Balance)) + { ammResult[jss::asset_frozen] = isFrozen(*ledger, ammAccountID, issue1.currency, issue1.account); + } if (!isXRP(asset2Balance)) + { ammResult[jss::asset2_frozen] = isFrozen(*ledger, ammAccountID, issue2.currency, issue2.account); + } result[jss::amm] = std::move(ammResult); if (!result.isMember(jss::ledger_index) && !result.isMember(jss::ledger_hash)) diff --git a/src/xrpld/rpc/handlers/AccountInfo.cpp b/src/xrpld/rpc/handlers/AccountInfo.cpp index e88da097f7..f144c934ec 100644 --- a/src/xrpld/rpc/handlers/AccountInfo.cpp +++ b/src/xrpld/rpc/handlers/AccountInfo.cpp @@ -84,7 +84,9 @@ doAccountInfo(RPC::JsonContext& context) strIdent = params[jss::ident].asString(); } else + { return RPC::missing_field_error(jss::account); + } std::shared_ptr ledger; auto result = RPC::lookupLedger(ledger, context); @@ -150,12 +152,16 @@ doAccountInfo(RPC::JsonContext& context) acctFlags[lsf.first.data()] = sleAccepted->isFlag(lsf.second); if (ledger->rules().enabled(featureClawback)) + { acctFlags[allowTrustLineClawbackFlag.first.data()] = sleAccepted->isFlag(allowTrustLineClawbackFlag.second); + } if (ledger->rules().enabled(featureTokenEscrow)) + { acctFlags[allowTrustLineLockingFlag.first.data()] = sleAccepted->isFlag(allowTrustLineLockingFlag.second); + } result[jss::account_flags] = std::move(acctFlags); @@ -300,7 +306,9 @@ doAccountInfo(RPC::JsonContext& context) jvQueueData[jss::max_spend_drops_total] = to_string(totalSpend); } else + { jvQueueData[jss::txn_count] = 0u; + } result[jss::queue_data] = std::move(jvQueueData); } diff --git a/src/xrpld/rpc/handlers/AccountLines.cpp b/src/xrpld/rpc/handlers/AccountLines.cpp index d065180c64..952141fb8d 100644 --- a/src/xrpld/rpc/handlers/AccountLines.cpp +++ b/src/xrpld/rpc/handlers/AccountLines.cpp @@ -191,9 +191,13 @@ doAccountLines(RPC::JsonContext& context) if (visitData.ignoreDefault) { if (sleCur->getFieldAmount(sfLowLimit).getIssuer() == visitData.accountID) + { ignore = !(sleCur->getFieldU32(sfFlags) & lsfLowReserve); + } else + { ignore = !(sleCur->getFieldU32(sfFlags) & lsfHighReserve); + } } if (!ignore && count <= limit) diff --git a/src/xrpld/rpc/handlers/AccountObjects.cpp b/src/xrpld/rpc/handlers/AccountObjects.cpp index f5f48d8050..cd67391da8 100644 --- a/src/xrpld/rpc/handlers/AccountObjects.cpp +++ b/src/xrpld/rpc/handlers/AccountObjects.cpp @@ -144,9 +144,13 @@ doAccountNFTs(RPC::JsonContext& context) } if (auto npm = (*cp)[~sfNextPageMin]) + { cp = ledger->read(Keylet(ltNFTOKEN_PAGE, *npm)); + } else + { cp = nullptr; + } } if (markerSet && !markerFound) @@ -229,9 +233,13 @@ getAccountObjects( jvObjects.append(cp->getJson(JsonOptions::none)); auto const npm = (*cp)[~sfNextPageMin]; if (npm) + { cp = ledger.read(Keylet(ltNFTOKEN_PAGE, *npm)); + } else + { cp = nullptr; + } if (--mlimit == 0) { @@ -429,7 +437,7 @@ doAccountObjects(RPC::JsonContext& context) rpcStatus.inject(result); return result; } - else if (type != ltANY) + if (type != ltANY) { typeFilter = std::vector({type}); } diff --git a/src/xrpld/rpc/handlers/AccountTx.cpp b/src/xrpld/rpc/handlers/AccountTx.cpp index 6c227b16b9..d7bffe5d95 100644 --- a/src/xrpld/rpc/handlers/AccountTx.cpp +++ b/src/xrpld/rpc/handlers/AccountTx.cpp @@ -59,7 +59,7 @@ parseLedgerArgs(RPC::Context& context, Json::Value const& params) return LedgerRange{min, max}; } - else if (params.isMember(jss::ledger_hash)) + if (params.isMember(jss::ledger_hash)) { auto& hashValue = params[jss::ledger_hash]; if (!hashValue.isString()) @@ -78,21 +78,29 @@ parseLedgerArgs(RPC::Context& context, Json::Value const& params) } return hash; } - else if (params.isMember(jss::ledger_index)) + if (params.isMember(jss::ledger_index)) { LedgerSpecifier ledger; if (params[jss::ledger_index].isNumeric()) + { ledger = params[jss::ledger_index].asUInt(); + } else { std::string ledgerStr = params[jss::ledger_index].asString(); if (ledgerStr == "current" || ledgerStr.empty()) + { ledger = LedgerShortcut::Current; + } else if (ledgerStr == "closed") + { ledger = LedgerShortcut::Closed; + } else if (ledgerStr == "validated") + { ledger = LedgerShortcut::Validated; + } else { RPC::Status status{rpcINVALID_PARAMS, "ledger_index string malformed"}; @@ -298,7 +306,9 @@ populateJsonResponse( jvObj[jss::close_time_iso] = to_string_iso(*closeTime); } else + { jvObj[json_tx] = txn->getJson(JsonOptions::include_date); + } auto const& sttx = txn->getSTransaction(); RPC::insertDeliverMax(jvObj[json_tx], sttx->getTxnType(), context.apiVersion); @@ -404,10 +414,8 @@ doAccountTxJson(RPC::JsonContext& context) { return *jv; } - else - { - args.ledger = std::get>(parseRes); - } + + args.ledger = std::get>(parseRes); if (params.isMember(jss::marker)) { diff --git a/src/xrpld/rpc/handlers/BlackList.cpp b/src/xrpld/rpc/handlers/BlackList.cpp index 102041b8d0..86abe53686 100644 --- a/src/xrpld/rpc/handlers/BlackList.cpp +++ b/src/xrpld/rpc/handlers/BlackList.cpp @@ -11,9 +11,11 @@ doBlackList(RPC::JsonContext& context) { auto& rm = context.app.getResourceManager(); if (context.params.isMember(jss::threshold)) + { return rm.getJson(context.params[jss::threshold].asInt()); - else - return rm.getJson(); + } + + return rm.getJson(); } } // namespace xrpl diff --git a/src/xrpld/rpc/handlers/BookOffers.cpp b/src/xrpld/rpc/handlers/BookOffers.cpp index 593f3e1fa2..ec53473821 100644 --- a/src/xrpld/rpc/handlers/BookOffers.cpp +++ b/src/xrpld/rpc/handlers/BookOffers.cpp @@ -83,12 +83,16 @@ doBookOffers(RPC::JsonContext& context) return RPC::expected_field_error("taker_pays.issuer", "string"); if (!to_issuer(pay_issuer, taker_pays[jss::issuer].asString())) + { return RPC::make_error( rpcSRC_ISR_MALFORMED, "Invalid field 'taker_pays.issuer', bad issuer."); + } if (pay_issuer == noAccount()) + { return RPC::make_error( rpcSRC_ISR_MALFORMED, "Invalid field 'taker_pays.issuer', bad issuer account one."); + } } else { @@ -96,14 +100,18 @@ doBookOffers(RPC::JsonContext& context) } if (isXRP(pay_currency) && !isXRP(pay_issuer)) + { return RPC::make_error( rpcSRC_ISR_MALFORMED, "Unneeded field 'taker_pays.issuer' for " "XRP currency specification."); + } if (!isXRP(pay_currency) && isXRP(pay_issuer)) + { return RPC::make_error( rpcSRC_ISR_MALFORMED, "Invalid field 'taker_pays.issuer', expected non-XRP issuer."); + } AccountID get_issuer; @@ -113,12 +121,16 @@ doBookOffers(RPC::JsonContext& context) return RPC::expected_field_error("taker_gets.issuer", "string"); if (!to_issuer(get_issuer, taker_gets[jss::issuer].asString())) + { return RPC::make_error( rpcDST_ISR_MALFORMED, "Invalid field 'taker_gets.issuer', bad issuer."); + } if (get_issuer == noAccount()) + { return RPC::make_error( rpcDST_ISR_MALFORMED, "Invalid field 'taker_gets.issuer', bad issuer account one."); + } } else { @@ -126,14 +138,18 @@ doBookOffers(RPC::JsonContext& context) } if (isXRP(get_currency) && !isXRP(get_issuer)) + { return RPC::make_error( rpcDST_ISR_MALFORMED, "Unneeded field 'taker_gets.issuer' for " "XRP currency specification."); + } if (!isXRP(get_currency) && isXRP(get_issuer)) + { return RPC::make_error( rpcDST_ISR_MALFORMED, "Invalid field 'taker_gets.issuer', expected non-XRP issuer."); + } std::optional takerID; if (context.params.isMember(jss::taker)) @@ -155,10 +171,8 @@ doBookOffers(RPC::JsonContext& context) { return RPC::make_error(rpcDOMAIN_MALFORMED, "Unable to parse domain."); } - else - { - domain = num; - } + + domain = num; } if (pay_currency == get_currency && pay_issuer == get_issuer) diff --git a/src/xrpld/rpc/handlers/Connect.cpp b/src/xrpld/rpc/handlers/Connect.cpp index 415adbd2fd..292cd50cbb 100644 --- a/src/xrpld/rpc/handlers/Connect.cpp +++ b/src/xrpld/rpc/handlers/Connect.cpp @@ -36,9 +36,13 @@ doConnect(RPC::JsonContext& context) int iPort = 0; if (context.params.isMember(jss::port)) + { iPort = context.params[jss::port].asInt(); + } else + { iPort = DEFAULT_PEER_PORT; + } auto const ip_str = context.params[jss::ip].asString(); auto ip = beast::IP::Endpoint::from_string(ip_str); diff --git a/src/xrpld/rpc/handlers/DepositAuthorized.cpp b/src/xrpld/rpc/handlers/DepositAuthorized.cpp index 7bad908c51..7ab7e30c8a 100644 --- a/src/xrpld/rpc/handlers/DepositAuthorized.cpp +++ b/src/xrpld/rpc/handlers/DepositAuthorized.cpp @@ -27,8 +27,10 @@ doDepositAuthorized(RPC::JsonContext& context) if (!params.isMember(jss::source_account)) return RPC::missing_field_error(jss::source_account); if (!params[jss::source_account].isString()) + { return RPC::make_error( rpcINVALID_PARAMS, RPC::expected_field_message(jss::source_account, "a string")); + } auto srcID = parseBase58(params[jss::source_account].asString()); if (!srcID) @@ -39,8 +41,10 @@ doDepositAuthorized(RPC::JsonContext& context) if (!params.isMember(jss::destination_account)) return RPC::missing_field_error(jss::destination_account); if (!params[jss::destination_account].isString()) + { return RPC::make_error( rpcINVALID_PARAMS, RPC::expected_field_message(jss::destination_account, "a string")); + } auto dstID = parseBase58(params[jss::destination_account].asString()); if (!dstID) @@ -84,7 +88,7 @@ doDepositAuthorized(RPC::JsonContext& context) RPC::expected_field_message( jss::credentials, "is non-empty array of CredentialID(hash256)")); } - else if (creds.size() > maxCredentialsArraySize) + if (creds.size() > maxCredentialsArraySize) { return RPC::make_error( rpcINVALID_PARAMS, RPC::expected_field_message(jss::credentials, "array too long")); @@ -151,8 +155,10 @@ doDepositAuthorized(RPC::JsonContext& context) // not set, then the deposit should be fine. bool depositAuthorized = true; if (reqAuth) + { depositAuthorized = ledger->exists(keylet::depositPreauth(dstAcct, srcAcct)) || (credentialsPresent && ledger->exists(keylet::depositPreauth(dstAcct, sorted))); + } result[jss::source_account] = params[jss::source_account].asString(); result[jss::destination_account] = params[jss::destination_account].asString(); diff --git a/src/xrpld/rpc/handlers/Feature1.cpp b/src/xrpld/rpc/handlers/Feature1.cpp index bd1e501506..24ff0d62b8 100644 --- a/src/xrpld/rpc/handlers/Feature1.cpp +++ b/src/xrpld/rpc/handlers/Feature1.cpp @@ -61,9 +61,13 @@ doFeature(RPC::JsonContext& context) return rpcError(rpcNO_PERMISSION); if (context.params[jss::vetoed].asBool()) + { table.veto(feature); + } else + { table.unVeto(feature); + } } Json::Value jvReply = table.getJson(feature, isAdmin); diff --git a/src/xrpld/rpc/handlers/GatewayBalances.cpp b/src/xrpld/rpc/handlers/GatewayBalances.cpp index a2176ab388..60e031c812 100644 --- a/src/xrpld/rpc/handlers/GatewayBalances.cpp +++ b/src/xrpld/rpc/handlers/GatewayBalances.cpp @@ -173,7 +173,7 @@ doGatewayBalances(RPC::JsonContext& context) // A positive balance means the cold wallet has an asset // (unusual) - if (hotWallets.count(peer) > 0) + if (hotWallets.contains(peer)) { // This is a specified hot wallet hotBalances[peer].push_back(-rs->getBalance()); diff --git a/src/xrpld/rpc/handlers/LedgerData.cpp b/src/xrpld/rpc/handlers/LedgerData.cpp index 308f4b4436..733d1c99c6 100644 --- a/src/xrpld/rpc/handlers/LedgerData.cpp +++ b/src/xrpld/rpc/handlers/LedgerData.cpp @@ -140,14 +140,14 @@ doLedgerDataGrpc(RPC::GRPCContext& con { startKey = *key; } - else if (request.marker().size() != 0) + else if (!request.marker().empty()) { grpc::Status errorStatus{grpc::StatusCode::INVALID_ARGUMENT, "marker malformed"}; return {response, errorStatus}; } auto e = ledger->sles.end(); - if (request.end_marker().size() != 0) + if (!request.end_marker().empty()) { auto const key = uint256::fromVoidChecked(request.end_marker()); diff --git a/src/xrpld/rpc/handlers/LedgerEntry.cpp b/src/xrpld/rpc/handlers/LedgerEntry.cpp index e4e8f52fd7..8e3b7f214d 100644 --- a/src/xrpld/rpc/handlers/LedgerEntry.cpp +++ b/src/xrpld/rpc/handlers/LedgerEntry.cpp @@ -70,9 +70,11 @@ parseIndex(Json::Value const& params, Json::StaticString const fieldName, unsign if (index == jss::nunl) return keylet::negativeUNL().key; if (index == jss::hashes) + { // Note this only finds the "short" skip list. Use "hashes":index to // get the long list. return keylet::skip().key; + } } return parseObjectID(params, fieldName, "hex string"); } @@ -532,8 +534,10 @@ parseMPTokenIssuance( { auto const mptIssuanceID = LedgerEntryHelpers::parse(params); if (!mptIssuanceID) + { return LedgerEntryHelpers::invalidFieldError( "malformedMPTokenIssuance", fieldName, "Hash192"); + } return keylet::mptIssuance(*mptIssuanceID).key; } @@ -901,8 +905,8 @@ doLedgerEntry(RPC::JsonContext& context) // this exception return an invalidParam error. return RPC::make_error(rpcINVALID_PARAMS); } - else - throw; + + throw; } // Return the computed index regardless of whether the node exists. diff --git a/src/xrpld/rpc/handlers/LedgerHandler.cpp b/src/xrpld/rpc/handlers/LedgerHandler.cpp index 6d188f8520..43c9780bb0 100644 --- a/src/xrpld/rpc/handlers/LedgerHandler.cpp +++ b/src/xrpld/rpc/handlers/LedgerHandler.cpp @@ -215,11 +215,17 @@ doLedgerGrpc(RPC::GRPCContext& context) obj->set_data(inDesired->data(), inDesired->size()); } if (inBase && inDesired) + { obj->set_mod_type(org::xrpl::rpc::v1::RawLedgerObject::MODIFIED); + } else if (inBase && !inDesired) + { obj->set_mod_type(org::xrpl::rpc::v1::RawLedgerObject::DELETED); + } else + { obj->set_mod_type(org::xrpl::rpc::v1::RawLedgerObject::CREATED); + } auto const blob = inDesired ? inDesired->slice() : inBase->slice(); auto const objectType = static_cast(blob[1] << 8 | blob[2]); diff --git a/src/xrpld/rpc/handlers/LogLevel.cpp b/src/xrpld/rpc/handlers/LogLevel.cpp index 2596cd6c70..2bc1beb7d4 100644 --- a/src/xrpld/rpc/handlers/LogLevel.cpp +++ b/src/xrpld/rpc/handlers/LogLevel.cpp @@ -52,9 +52,13 @@ doLogLevel(RPC::JsonContext& context) std::string partition(context.params[jss::partition].asString()); if (boost::iequals(partition, "base")) + { context.app.logs().threshold(severity); + } else + { context.app.logs().get(partition).threshold(severity); + } return Json::objectValue; } diff --git a/src/xrpld/rpc/handlers/NoRippleCheck.cpp b/src/xrpld/rpc/handlers/NoRippleCheck.cpp index 9985591303..f21a67a31d 100644 --- a/src/xrpld/rpc/handlers/NoRippleCheck.cpp +++ b/src/xrpld/rpc/handlers/NoRippleCheck.cpp @@ -55,9 +55,13 @@ doNoRippleCheck(RPC::JsonContext& context) { std::string const role = params["role"].asString(); if (role == "gateway") + { roleGateway = true; + } else if (role != "user") + { return RPC::invalid_field_error("role"); + } } unsigned int limit = 0; diff --git a/src/xrpld/rpc/handlers/PayChanClaim.cpp b/src/xrpld/rpc/handlers/PayChanClaim.cpp index 44312ee336..b24a241147 100644 --- a/src/xrpld/rpc/handlers/PayChanClaim.cpp +++ b/src/xrpld/rpc/handlers/PayChanClaim.cpp @@ -29,8 +29,10 @@ doChannelAuthorize(RPC::JsonContext& context) auto const& params(context.params); for (auto const& p : {jss::channel_id, jss::amount}) + { if (!params.isMember(p)) return RPC::missing_field_error(p); + } // Compatibility if a key type isn't specified. If it is, the // keypairForSignature code will validate parameters and return @@ -92,8 +94,10 @@ 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; { @@ -125,7 +129,7 @@ doChannelVerify(RPC::JsonContext& context) std::uint64_t const drops = *optDrops; auto sig = strUnHex(params[jss::signature].asString()); - if (!sig || !sig->size()) + if (!sig || sig->empty()) return rpcError(rpcINVALID_PARAMS); Serializer msg; diff --git a/src/xrpld/rpc/handlers/Peers.cpp b/src/xrpld/rpc/handlers/Peers.cpp index 1be136a5f8..b21efc01fb 100644 --- a/src/xrpld/rpc/handlers/Peers.cpp +++ b/src/xrpld/rpc/handlers/Peers.cpp @@ -27,9 +27,13 @@ doPeers(RPC::JsonContext& context) auto const s = p[jss::track].asString(); if (s == "diverged") + { p["sanity"] = "insane"; + } else if (s == "unknown") + { p["sanity"] = "unknown"; + } } } } @@ -53,8 +57,10 @@ doPeers(RPC::JsonContext& context) json[jss::fee] = static_cast(node.getLoadFee()) / ref; if (node.getReportTime() != NetClock::time_point{}) + { json[jss::age] = (node.getReportTime() >= now) ? 0 : (now - node.getReportTime()).count(); + } }); return jvResult; diff --git a/src/xrpld/rpc/handlers/Ping.cpp b/src/xrpld/rpc/handlers/Ping.cpp index cc3c558cd9..4e9b18c4c9 100644 --- a/src/xrpld/rpc/handlers/Ping.cpp +++ b/src/xrpld/rpc/handlers/Ping.cpp @@ -22,7 +22,7 @@ doPing(RPC::JsonContext& context) case Role::IDENTIFIED: ret[jss::role] = "identified"; ret[jss::username] = std::string{context.headers.user}; - if (context.headers.forwardedFor.size()) + if (!context.headers.forwardedFor.empty()) ret[jss::ip] = std::string{context.headers.forwardedFor}; break; case Role::PROXY: diff --git a/src/xrpld/rpc/handlers/ServerDefinitions.cpp b/src/xrpld/rpc/handlers/ServerDefinitions.cpp index e153065ea9..24abd69a02 100644 --- a/src/xrpld/rpc/handlers/ServerDefinitions.cpp +++ b/src/xrpld/rpc/handlers/ServerDefinitions.cpp @@ -63,9 +63,11 @@ ServerDefinitions::translate(std::string const& inp) { if (contains("512") || contains("384") || contains("256") || contains("192") || contains("160") || contains("128")) + { return replace("UINT", "Hash"); - else - return replace("UINT", "UInt"); + } + + return replace("UINT", "UInt"); } static std::unordered_map const replacements{ @@ -102,7 +104,9 @@ ServerDefinitions::translate(std::string const& inp) out += token; } else + { out += token; + } if (pos == inpToProcess.size()) break; inpToProcess = inpToProcess.substr(pos + 1); @@ -217,7 +221,7 @@ ServerDefinitions::ServerDefinitions() : defs_{Json::objectValue} for (auto const& [code, field] : xrpl::SField::getKnownCodeToField()) { - if (field->fieldName == "") + if (field->fieldName.empty()) continue; Json::Value innerObj = Json::objectValue; diff --git a/src/xrpld/rpc/handlers/Submit.cpp b/src/xrpld/rpc/handlers/Submit.cpp index b8cca3670a..cac7259a00 100644 --- a/src/xrpld/rpc/handlers/Submit.cpp +++ b/src/xrpld/rpc/handlers/Submit.cpp @@ -55,7 +55,7 @@ doSubmit(RPC::JsonContext& context) auto ret = strUnHex(context.params[jss::tx_blob].asString()); - if (!ret || !ret->size()) + if (!ret || ret->empty()) return rpcError(rpcINVALID_PARAMS); SerialIter sitTrans(makeSlice(*ret)); @@ -76,8 +76,10 @@ doSubmit(RPC::JsonContext& context) { if (!context.app.checkSigs()) + { forceValidity( context.app.getHashRouter(), stTx->getTransactionID(), Validity::SigGoodOnly); + } auto [validity, reason] = checkValidity( context.app.getHashRouter(), *stTx, context.ledgerMaster.getCurrentLedger()->rules()); if (validity != Validity::Valid) diff --git a/src/xrpld/rpc/handlers/Subscribe.cpp b/src/xrpld/rpc/handlers/Subscribe.cpp index 8fbf5a917e..6e8d9dbaa3 100644 --- a/src/xrpld/rpc/handlers/Subscribe.cpp +++ b/src/xrpld/rpc/handlers/Subscribe.cpp @@ -281,10 +281,8 @@ doSubscribe(RPC::JsonContext& context) { return rpcError(rpcDOMAIN_MALFORMED); } - else - { - book.domain = domain; - } + + book.domain = domain; } if (!isConsistent(book)) diff --git a/src/xrpld/rpc/handlers/TransactionEntry.cpp b/src/xrpld/rpc/handlers/TransactionEntry.cpp index 8cd1120aad..36f53130fa 100644 --- a/src/xrpld/rpc/handlers/TransactionEntry.cpp +++ b/src/xrpld/rpc/handlers/TransactionEntry.cpp @@ -59,8 +59,10 @@ doTransactionEntry(RPC::JsonContext& context) jvResult[jss::hash] = to_string(sttx->getTransactionID()); if (!lpLedger->open()) + { jvResult[jss::ledger_hash] = to_string(context.ledgerMaster.getHashBySeq(lpLedger->seq())); + } bool const validated = context.ledgerMaster.isValidated(*lpLedger); @@ -73,7 +75,9 @@ doTransactionEntry(RPC::JsonContext& context) } } else + { jvResult[jss::tx_json] = sttx->getJson(JsonOptions::none); + } RPC::insertDeliverMax(jvResult[jss::tx_json], sttx->getTxnType(), context.apiVersion); diff --git a/src/xrpld/rpc/handlers/Tx.cpp b/src/xrpld/rpc/handlers/Tx.cpp index a34c1f1a2e..482b7e3bf1 100644 --- a/src/xrpld/rpc/handlers/Tx.cpp +++ b/src/xrpld/rpc/handlers/Tx.cpp @@ -153,7 +153,7 @@ doTxHelp(RPC::Context& context, TxArgs args) uint32_t netID = context.app.getNetworkIDService().getNetworkID(); if (txnIdx <= 0xFFFFU && netID < 0xFFFFU && lgrSeq < 0x0FFF'FFFFUL) - result.ctid = RPC::encodeCTID(lgrSeq, (uint32_t)txnIdx, (uint32_t)netID); + result.ctid = RPC::encodeCTID(lgrSeq, txnIdx, netID); } } @@ -192,7 +192,9 @@ populateJsonResponse( constexpr auto optionsJson = JsonOptions::include_date | JsonOptions::disable_API_prior_V2; if (args.binary) + { response[jss::tx_blob] = result.txn->getJson(optionsJson, true); + } else { response[jss::tx_json] = result.txn->getJson(optionsJson); @@ -258,8 +260,10 @@ doTxJson(RPC::JsonContext& context) TxArgs args; if (context.params.isMember(jss::transaction) && context.params.isMember(jss::ctid)) + { // specifying both is ambiguous return rpcError(rpcINVALID_PARAMS); + } if (context.params.isMember(jss::transaction)) { @@ -286,7 +290,9 @@ doTxJson(RPC::JsonContext& context) args.ctid = {lgr_seq, txn_idx}; } else + { return rpcError(rpcINVALID_PARAMS); + } args.binary = context.params.isMember(jss::binary) && context.params[jss::binary].asBool(); diff --git a/src/xrpld/rpc/handlers/Unsubscribe.cpp b/src/xrpld/rpc/handlers/Unsubscribe.cpp index 15da0d1d6a..824d57203c 100644 --- a/src/xrpld/rpc/handlers/Unsubscribe.cpp +++ b/src/xrpld/rpc/handlers/Unsubscribe.cpp @@ -165,8 +165,7 @@ doUnsubscribe(RPC::JsonContext& context) return rpcError(rpcSRC_CUR_MALFORMED); } // Parse optional issuer. - else if ( - ((taker_pays.isMember(jss::issuer)) && + if (((taker_pays.isMember(jss::issuer)) && (!taker_pays[jss::issuer].isString() || !to_issuer(book.in.account, taker_pays[jss::issuer].asString()))) // Don't allow illegal issuers. @@ -186,8 +185,7 @@ doUnsubscribe(RPC::JsonContext& context) return rpcError(rpcDST_AMT_MALFORMED); } // Parse optional issuer. - else if ( - ((taker_gets.isMember(jss::issuer)) && + if (((taker_gets.isMember(jss::issuer)) && (!taker_gets[jss::issuer].isString() || !to_issuer(book.out.account, taker_gets[jss::issuer].asString()))) // Don't allow illegal issuers. @@ -211,10 +209,8 @@ doUnsubscribe(RPC::JsonContext& context) { return rpcError(rpcDOMAIN_MALFORMED); } - else - { - book.domain = domain; - } + + book.domain = domain; } context.netOps.unsubBook(ispSub->getSeq(), book); diff --git a/src/xrpld/rpc/handlers/VaultInfo.cpp b/src/xrpld/rpc/handlers/VaultInfo.cpp index b17a16cc4a..4a704e0b0b 100644 --- a/src/xrpld/rpc/handlers/VaultInfo.cpp +++ b/src/xrpld/rpc/handlers/VaultInfo.cpp @@ -35,8 +35,7 @@ parseVault(Json::Value const& params, Json::Value& jvResult) RPC::inject_error(rpcACT_MALFORMED, jvResult); return std::nullopt; } - else if ( - !(params[jss::seq].isInt() || params[jss::seq].isUInt()) || + if (!(params[jss::seq].isInt() || params[jss::seq].isUInt()) || params[jss::seq].asDouble() <= 0.0 || params[jss::seq].asDouble() > double(Json::Value::maxUInt)) { diff --git a/src/xrpld/rpc/handlers/WalletPropose.cpp b/src/xrpld/rpc/handlers/WalletPropose.cpp index 273d829670..a5005ce701 100644 --- a/src/xrpld/rpc/handlers/WalletPropose.cpp +++ b/src/xrpld/rpc/handlers/WalletPropose.cpp @@ -76,9 +76,13 @@ walletPropose(Json::Value const& params) // to detect such keys to avoid user confusion. { if (params.isMember(jss::passphrase)) + { seed = RPC::parseRippleLibSeed(params[jss::passphrase]); + } else if (params.isMember(jss::seed)) + { seed = RPC::parseRippleLibSeed(params[jss::seed]); + } if (seed) { @@ -142,15 +146,19 @@ walletPropose(Json::Value const& params) // 80 bits of entropy isn't bad, but it's better to // err on the side of caution and be conservative. if (estimate_entropy(passphrase) < 80.0) + { obj[jss::warning] = "This wallet was generated using a user-supplied " "passphrase that has low entropy and is vulnerable " "to brute-force attacks."; + } else + { obj[jss::warning] = "This wallet was generated using a user-supplied " "passphrase. It may be vulnerable to brute-force " "attacks."; + } } }