From eabca8439fd78866a653839b1962a705a448949b Mon Sep 17 00:00:00 2001 From: Bronek Kozicki Date: Mon, 16 Dec 2024 22:48:33 +0000 Subject: [PATCH 1/5] Antithesis instrumentation improvements (#5213) * Rename ASSERT to XRPL_ASSERT * Upgrade to Anthithesis SDK 0.4.4, and use new 0.4.4 features * automatic cast to bool, like assert * Add instrumentation workflow to verify build with instrumentation enabled --- .github/workflows/instrumentation.yml | 103 +++ .github/workflows/macos.yml | 2 +- .github/workflows/nix.yml | 2 +- .github/workflows/windows.yml | 2 +- CONTRIBUTING.md | 6 +- external/antithesis-sdk/CMakeLists.txt | 2 +- external/antithesis-sdk/README.md | 2 +- .../antithesis_instrumentation.h | 2 +- external/antithesis-sdk/antithesis_sdk.h | 768 +++++++++--------- include/xrpl/basics/Buffer.h | 2 +- include/xrpl/basics/MathUtilities.h | 2 +- include/xrpl/basics/SlabAllocator.h | 8 +- include/xrpl/basics/Slice.h | 2 +- include/xrpl/basics/base_uint.h | 4 +- .../xrpl/basics/partitioned_unordered_map.h | 4 +- include/xrpl/basics/random.h | 2 +- include/xrpl/basics/scope.h | 2 +- include/xrpl/basics/spinlock.h | 2 +- include/xrpl/beast/asio/io_latency_probe.h | 8 +- include/xrpl/beast/clock/manual_clock.h | 4 +- .../detail/aged_unordered_container.h | 4 +- include/xrpl/beast/core/LexicalCast.h | 9 +- include/xrpl/beast/utility/Journal.h | 2 +- include/xrpl/beast/utility/instrumentation.h | 44 +- include/xrpl/beast/utility/rngfill.h | 2 +- include/xrpl/protocol/AmountConversions.h | 10 +- include/xrpl/protocol/Feature.h | 6 +- include/xrpl/protocol/FeeUnits.h | 6 +- include/xrpl/protocol/Indexes.h | 3 +- include/xrpl/protocol/MultiApiJson.h | 4 +- include/xrpl/protocol/Quality.h | 2 +- include/xrpl/protocol/STAmount.h | 2 +- include/xrpl/protocol/STBitString.h | 5 +- include/xrpl/protocol/STInteger.h | 5 +- include/xrpl/protocol/STObject.h | 19 +- include/xrpl/protocol/STPathSet.h | 4 +- include/xrpl/protocol/STValidation.h | 4 +- include/xrpl/protocol/Serializer.h | 7 +- include/xrpl/protocol/TxMeta.h | 2 +- include/xrpl/protocol/detail/b58_utils.h | 6 +- include/xrpl/resource/detail/Logic.h | 2 +- include/xrpl/server/detail/BaseWSPeer.h | 2 +- src/libxrpl/basics/Number.cpp | 13 +- src/libxrpl/basics/ResolverAsio.cpp | 19 +- .../beast/clock/basic_seconds_clock.cpp | 2 +- src/libxrpl/beast/core/SemanticVersion.cpp | 4 +- src/libxrpl/beast/insight/StatsDCollector.cpp | 2 +- .../utility/src/beast_PropertyStream.cpp | 4 +- src/libxrpl/crypto/RFC1751.cpp | 16 +- src/libxrpl/json/Object.cpp | 2 +- src/libxrpl/json/json_reader.cpp | 2 +- src/libxrpl/json/json_value.cpp | 16 +- src/libxrpl/json/json_writer.cpp | 12 +- src/libxrpl/protocol/AMMCore.cpp | 2 +- src/libxrpl/protocol/AccountID.cpp | 2 +- src/libxrpl/protocol/ErrorCodes.cpp | 2 +- src/libxrpl/protocol/Feature.cpp | 8 +- src/libxrpl/protocol/Indexes.cpp | 15 +- src/libxrpl/protocol/Keylet.cpp | 2 +- src/libxrpl/protocol/Quality.cpp | 20 +- src/libxrpl/protocol/Rate2.cpp | 18 +- src/libxrpl/protocol/Rules.cpp | 6 +- src/libxrpl/protocol/STAccount.cpp | 5 +- src/libxrpl/protocol/STAmount.cpp | 29 +- src/libxrpl/protocol/STBase.cpp | 9 +- src/libxrpl/protocol/STBlob.cpp | 4 +- src/libxrpl/protocol/STInteger.cpp | 4 +- src/libxrpl/protocol/STLedgerEntry.cpp | 2 +- src/libxrpl/protocol/STNumber.cpp | 7 +- src/libxrpl/protocol/STObject.cpp | 2 +- src/libxrpl/protocol/STPathSet.cpp | 5 +- src/libxrpl/protocol/STTx.cpp | 5 +- src/libxrpl/protocol/STValidation.cpp | 2 +- src/libxrpl/protocol/STVar.cpp | 2 +- src/libxrpl/protocol/STVector256.cpp | 5 +- src/libxrpl/protocol/Serializer.cpp | 6 +- src/libxrpl/protocol/TxMeta.cpp | 22 +- src/libxrpl/protocol/tokens.cpp | 6 +- src/libxrpl/resource/Consumer.cpp | 18 +- src/xrpld/app/consensus/RCLConsensus.cpp | 15 +- src/xrpld/app/consensus/RCLCxPeerPos.cpp | 2 +- src/xrpld/app/consensus/RCLCxTx.h | 7 +- src/xrpld/app/consensus/RCLValidations.cpp | 11 +- src/xrpld/app/ledger/AcceptedLedgerTx.cpp | 4 +- src/xrpld/app/ledger/ConsensusTransSetSF.cpp | 4 +- src/xrpld/app/ledger/Ledger.cpp | 23 +- src/xrpld/app/ledger/LedgerHistory.cpp | 27 +- src/xrpld/app/ledger/OpenLedger.h | 2 +- src/xrpld/app/ledger/OrderBookDB.cpp | 2 +- src/xrpld/app/ledger/TransactionStateSF.cpp | 2 +- src/xrpld/app/ledger/detail/BuildLedger.cpp | 7 +- src/xrpld/app/ledger/detail/InboundLedger.cpp | 16 +- .../app/ledger/detail/InboundLedgers.cpp | 12 +- src/xrpld/app/ledger/detail/LedgerCleaner.cpp | 4 +- .../app/ledger/detail/LedgerDeltaAcquire.cpp | 6 +- src/xrpld/app/ledger/detail/LedgerMaster.cpp | 32 +- .../app/ledger/detail/LedgerReplayTask.cpp | 8 +- .../app/ledger/detail/LedgerReplayer.cpp | 2 +- .../app/ledger/detail/SkipListAcquire.cpp | 4 +- .../app/ledger/detail/TimeoutCounter.cpp | 2 +- src/xrpld/app/main/Application.cpp | 34 +- src/xrpld/app/main/GRPCServer.cpp | 2 +- src/xrpld/app/main/LoadManager.cpp | 2 +- src/xrpld/app/misc/FeeVoteImpl.cpp | 2 +- src/xrpld/app/misc/HashRouter.cpp | 2 +- src/xrpld/app/misc/NegativeUNLVote.cpp | 10 +- src/xrpld/app/misc/NetworkOPs.cpp | 31 +- src/xrpld/app/misc/SHAMapStoreImp.cpp | 4 +- src/xrpld/app/misc/detail/AMMHelpers.cpp | 2 +- src/xrpld/app/misc/detail/AMMUtils.cpp | 2 +- src/xrpld/app/misc/detail/AmendmentTable.cpp | 2 +- src/xrpld/app/misc/detail/Manifest.cpp | 2 +- src/xrpld/app/misc/detail/Transaction.cpp | 2 +- src/xrpld/app/misc/detail/TxQ.cpp | 52 +- src/xrpld/app/misc/detail/ValidatorList.cpp | 52 +- src/xrpld/app/misc/detail/ValidatorSite.cpp | 6 +- src/xrpld/app/misc/detail/WorkBase.h | 4 +- src/xrpld/app/misc/detail/WorkFile.h | 2 +- src/xrpld/app/paths/Credit.cpp | 8 +- src/xrpld/app/paths/Flow.cpp | 2 +- src/xrpld/app/paths/PathRequest.cpp | 3 +- src/xrpld/app/paths/Pathfinder.cpp | 10 +- src/xrpld/app/paths/RippleLineCache.cpp | 6 +- src/xrpld/app/paths/detail/AMMLiquidity.cpp | 2 +- src/xrpld/app/paths/detail/AmountSpec.h | 14 +- src/xrpld/app/paths/detail/BookStep.cpp | 11 +- src/xrpld/app/paths/detail/DirectStep.cpp | 8 +- src/xrpld/app/paths/detail/FlowDebugInfo.h | 2 +- src/xrpld/app/paths/detail/PaySteps.cpp | 4 +- src/xrpld/app/paths/detail/StepChecks.h | 2 +- src/xrpld/app/paths/detail/StrandFlow.h | 6 +- .../app/paths/detail/XRPEndpointStep.cpp | 5 +- src/xrpld/app/rdb/backend/detail/Node.cpp | 2 +- src/xrpld/app/rdb/detail/Vacuum.cpp | 7 +- src/xrpld/app/tx/detail/AMMBid.cpp | 4 +- src/xrpld/app/tx/detail/AMMDeposit.cpp | 2 +- src/xrpld/app/tx/detail/AMMVote.cpp | 2 +- src/xrpld/app/tx/detail/AMMWithdraw.cpp | 2 +- src/xrpld/app/tx/detail/ApplyContext.cpp | 2 +- src/xrpld/app/tx/detail/Change.cpp | 2 +- src/xrpld/app/tx/detail/CreateOffer.cpp | 20 +- src/xrpld/app/tx/detail/DeleteAccount.cpp | 17 +- src/xrpld/app/tx/detail/InvariantCheck.cpp | 2 +- src/xrpld/app/tx/detail/NFTokenMint.cpp | 2 +- src/xrpld/app/tx/detail/NFTokenUtils.cpp | 13 +- src/xrpld/app/tx/detail/OfferStream.cpp | 2 +- src/xrpld/app/tx/detail/PayChan.cpp | 4 +- src/xrpld/app/tx/detail/Payment.cpp | 2 +- src/xrpld/app/tx/detail/SetSignerList.cpp | 10 +- src/xrpld/app/tx/detail/Taker.cpp | 48 +- src/xrpld/app/tx/detail/Transactor.cpp | 21 +- src/xrpld/app/tx/detail/XChainBridge.cpp | 4 +- src/xrpld/app/tx/detail/applySteps.cpp | 2 +- src/xrpld/consensus/Consensus.h | 28 +- src/xrpld/consensus/ConsensusTypes.h | 2 +- src/xrpld/consensus/LedgerTiming.h | 4 +- src/xrpld/consensus/LedgerTrie.h | 21 +- src/xrpld/consensus/Validations.h | 5 +- src/xrpld/core/Coro.ipp | 4 +- src/xrpld/core/DatabaseCon.h | 2 +- src/xrpld/core/JobTypes.h | 6 +- src/xrpld/core/detail/Config.cpp | 12 +- src/xrpld/core/detail/DatabaseCon.cpp | 2 +- src/xrpld/core/detail/JobQueue.cpp | 45 +- src/xrpld/core/detail/LoadEvent.cpp | 2 +- src/xrpld/core/detail/Workers.cpp | 2 +- src/xrpld/ledger/detail/ApplyStateTable.cpp | 18 +- src/xrpld/ledger/detail/BookDirs.cpp | 11 +- src/xrpld/ledger/detail/Dir.cpp | 12 +- src/xrpld/ledger/detail/PaymentSandbox.cpp | 10 +- src/xrpld/ledger/detail/RawStateTable.cpp | 6 +- src/xrpld/ledger/detail/ReadViewFwdRange.ipp | 2 +- src/xrpld/ledger/detail/View.cpp | 70 +- src/xrpld/net/detail/InfoSub.cpp | 2 +- src/xrpld/net/detail/RPCCall.cpp | 2 +- src/xrpld/nodestore/Database.h | 2 +- src/xrpld/nodestore/backend/MemoryFactory.cpp | 14 +- .../nodestore/backend/RocksDBFactory.cpp | 12 +- src/xrpld/nodestore/detail/BatchWriter.cpp | 2 +- src/xrpld/nodestore/detail/Database.cpp | 14 +- src/xrpld/nodestore/detail/DatabaseNodeImp.h | 4 +- src/xrpld/nodestore/detail/DecodedBlob.cpp | 2 +- src/xrpld/nodestore/detail/EncodedBlob.h | 6 +- src/xrpld/nodestore/detail/ManagerImp.cpp | 2 +- src/xrpld/overlay/Slot.h | 2 +- src/xrpld/overlay/detail/ConnectAttempt.cpp | 2 +- src/xrpld/overlay/detail/Message.cpp | 7 +- src/xrpld/overlay/detail/OverlayImpl.cpp | 19 +- src/xrpld/overlay/detail/OverlayImpl.h | 2 +- src/xrpld/overlay/detail/PeerImp.cpp | 27 +- src/xrpld/overlay/detail/ProtocolMessage.h | 2 +- src/xrpld/overlay/detail/TrafficCount.h | 2 +- src/xrpld/overlay/detail/ZeroCopyStream.h | 2 +- src/xrpld/peerfinder/detail/Bootcache.cpp | 4 +- src/xrpld/peerfinder/detail/Counts.h | 6 +- src/xrpld/peerfinder/detail/Handouts.h | 2 +- src/xrpld/peerfinder/detail/Livecache.h | 6 +- src/xrpld/peerfinder/detail/Logic.h | 22 +- src/xrpld/peerfinder/detail/SlotImp.cpp | 12 +- src/xrpld/rpc/Status.h | 5 +- src/xrpld/rpc/detail/Handler.cpp | 6 +- src/xrpld/rpc/detail/RPCHelpers.cpp | 19 +- src/xrpld/rpc/detail/RPCHelpers.h | 2 +- src/xrpld/rpc/detail/Role.cpp | 2 +- src/xrpld/rpc/detail/Status.cpp | 2 +- src/xrpld/rpc/detail/TransactionSign.cpp | 2 +- src/xrpld/rpc/handlers/AMMInfo.cpp | 8 +- src/xrpld/rpc/handlers/AccountInfo.cpp | 4 +- src/xrpld/rpc/handlers/AccountTx.cpp | 5 +- src/xrpld/rpc/handlers/LedgerClosed.cpp | 3 +- src/xrpld/rpc/handlers/LedgerDiff.cpp | 2 +- src/xrpld/rpc/handlers/LedgerHandler.cpp | 7 +- src/xrpld/rpc/handlers/PayChanClaim.cpp | 2 +- src/xrpld/rpc/handlers/Tx.cpp | 3 +- src/xrpld/shamap/SHAMap.h | 8 +- src/xrpld/shamap/SHAMapItem.h | 2 +- src/xrpld/shamap/detail/SHAMap.cpp | 87 +- src/xrpld/shamap/detail/SHAMapDelta.cpp | 6 +- src/xrpld/shamap/detail/SHAMapInnerNode.cpp | 57 +- src/xrpld/shamap/detail/SHAMapLeafNode.cpp | 11 +- src/xrpld/shamap/detail/SHAMapNodeID.cpp | 12 +- src/xrpld/shamap/detail/SHAMapSync.cpp | 21 +- src/xrpld/shamap/detail/TaggedPointer.ipp | 14 +- 223 files changed, 1439 insertions(+), 1331 deletions(-) create mode 100644 .github/workflows/instrumentation.yml diff --git a/.github/workflows/instrumentation.yml b/.github/workflows/instrumentation.yml new file mode 100644 index 00000000000..6a1aef64350 --- /dev/null +++ b/.github/workflows/instrumentation.yml @@ -0,0 +1,103 @@ +name: instrumentation +on: + pull_request: + push: + # If the branches list is ever changed, be sure to change it on all + # build/test jobs (nix, macos, windows, instrumentation) + branches: + # Always build the package branches + - develop + - release + - master + # Branches that opt-in to running + - 'ci/**' +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + + # NOTE we are not using dependencies built inside nix because nix is lagging + # with compiler versions. Instrumentation requires clang version 16 or later + + instrumentation-build: + env: + CLANG_RELEASE: 16 + strategy: + fail-fast: false + runs-on: [self-hosted, heavy] + container: debian:bookworm + steps: + - name: install prerequisites + env: + DEBIAN_FRONTEND: noninteractive + run: | + apt-get update + apt-get install --yes --no-install-recommends \ + clang-${CLANG_RELEASE} clang++-${CLANG_RELEASE} \ + python3-pip python-is-python3 make cmake git wget + apt-get clean + update-alternatives --install \ + /usr/bin/clang clang /usr/bin/clang-${CLANG_RELEASE} 100 \ + --slave /usr/bin/clang++ clang++ /usr/bin/clang++-${CLANG_RELEASE} + update-alternatives --auto clang + pip install --no-cache --break-system-packages "conan<2" + + - name: checkout + uses: actions/checkout@v4 + + - name: prepare environment + run: | + mkdir ${GITHUB_WORKSPACE}/.build + echo "SOURCE_DIR=$GITHUB_WORKSPACE" >> $GITHUB_ENV + echo "BUILD_DIR=$GITHUB_WORKSPACE/.build" >> $GITHUB_ENV + echo "CC=/usr/bin/clang" >> $GITHUB_ENV + echo "CXX=/usr/bin/clang++" >> $GITHUB_ENV + + - name: configure Conan + run: | + conan profile new --detect default + conan profile update settings.compiler=clang default + conan profile update settings.compiler.version=${CLANG_RELEASE} default + conan profile update settings.compiler.libcxx=libstdc++11 default + conan profile update settings.compiler.cppstd=20 default + conan profile update options.rocksdb=False default + conan profile update \ + 'conf.tools.build:compiler_executables={"c": "/usr/bin/clang", "cpp": "/usr/bin/clang++"}' default + conan profile update 'env.CXXFLAGS="-DBOOST_ASIO_DISABLE_CONCEPTS"' default + conan profile update 'conf.tools.build:cxxflags+=["-DBOOST_ASIO_DISABLE_CONCEPTS"]' default + conan export external/snappy snappy/1.1.10@ + conan export external/soci soci/4.0.3@ + + - name: build dependencies + run: | + cd ${BUILD_DIR} + conan install ${SOURCE_DIR} \ + --output-folder ${BUILD_DIR} \ + --install-folder ${BUILD_DIR} \ + --build missing \ + --settings build_type=Debug + + - name: build with instrumentation + run: | + cd ${BUILD_DIR} + cmake -S ${SOURCE_DIR} -B ${BUILD_DIR} \ + -Dvoidstar=ON \ + -Dtests=ON \ + -Dxrpld=ON \ + -DCMAKE_BUILD_TYPE=Debug \ + -DSECP256K1_BUILD_BENCHMARK=OFF \ + -DSECP256K1_BUILD_TESTS=OFF \ + -DSECP256K1_BUILD_EXHAUSTIVE_TESTS=OFF \ + -DCMAKE_TOOLCHAIN_FILE=${BUILD_DIR}/build/generators/conan_toolchain.cmake + cmake --build . --parallel $(nproc) + + - name: verify instrumentation enabled + run: | + cd ${BUILD_DIR} + ./rippled --version | grep libvoidstar + + - name: run unit tests + run: | + cd ${BUILD_DIR} + ./rippled -u --unittest-jobs $(( $(nproc)/4 )) diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml index ab4be74fbf4..c66e0e05f7a 100644 --- a/.github/workflows/macos.yml +++ b/.github/workflows/macos.yml @@ -3,7 +3,7 @@ on: pull_request: push: # If the branches list is ever changed, be sure to change it on all - # build/test jobs (nix, macos, windows) + # build/test jobs (nix, macos, windows, instrumentation) branches: # Always build the package branches - develop diff --git a/.github/workflows/nix.yml b/.github/workflows/nix.yml index 6b8261c5d69..9f2cbac951f 100644 --- a/.github/workflows/nix.yml +++ b/.github/workflows/nix.yml @@ -3,7 +3,7 @@ on: pull_request: push: # If the branches list is ever changed, be sure to change it on all - # build/test jobs (nix, macos, windows) + # build/test jobs (nix, macos, windows, instrumentation) branches: # Always build the package branches - develop diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 13b48a04cdd..ed29b800ee5 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -4,7 +4,7 @@ on: pull_request: push: # If the branches list is ever changed, be sure to change it on all - # build/test jobs (nix, macos, windows) + # build/test jobs (nix, macos, windows, instrumentation) branches: # Always build the package branches - develop diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0609cd7f2e5..3bfce52c09b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -349,7 +349,7 @@ We are using [Antithesis](https://antithesis.com/) for continuous fuzzing, and keep a copy of [Antithesis C++ SDK](https://github.com/antithesishq/antithesis-sdk-cpp/) in `external/antithesis-sdk`. One of the aims of fuzzing is to identify bugs by finding external conditions which cause contracts violations inside `rippled`. -The contracts are expressed as `ASSERT` or `UNREACHABLE` (defined in +The contracts are expressed as `XRPL_ASSERT` or `UNREACHABLE` (defined in `include/xrpl/beast/utility/instrumentation.h`), which are effectively (outside of Antithesis) wrappers for `assert(...)` with added name. The purpose of name is to provide contracts with stable identity which does not rely on line numbers. @@ -372,7 +372,7 @@ For this reason: * `constexpr` functions * unit tests i.e. files under `src/test` * unit tests-related modules (files under `beast/test` and `beast/unit_test`) -* Outside of the listed locations, do not use `assert`; use `ASSERT` instead, +* Outside of the listed locations, do not use `assert`; use `XRPL_ASSERT` instead, giving it unique name, with the short description of the contract. * Outside of the listed locations, do not use `assert(false)`; use `UNREACHABLE` instead, giving it unique name, with the description of the @@ -391,7 +391,7 @@ For this reason: situation which caused the line to have been reached. * Example good name for an `UNREACHABLE` macro `"Json::operator==(Value, Value) : invalid type"`; example - good name for an `ASSERT` macro `"Json::Value::asCString : valid type"`. + good name for an `XRPL_ASSERT` macro `"Json::Value::asCString : valid type"`. * Example **bad** name `"RFC1751::insert(char* s, int x, int start, int length) : length is greater than or equal zero"` (missing namespace, unnecessary full function signature, description too verbose). diff --git a/external/antithesis-sdk/CMakeLists.txt b/external/antithesis-sdk/CMakeLists.txt index b7fa22de107..d2c1f536afd 100644 --- a/external/antithesis-sdk/CMakeLists.txt +++ b/external/antithesis-sdk/CMakeLists.txt @@ -1,7 +1,7 @@ cmake_minimum_required(VERSION 3.25) # Note, version set explicitly by rippled project -project(antithesis-sdk-cpp VERSION 0.4.2 LANGUAGES CXX) +project(antithesis-sdk-cpp VERSION 0.4.4 LANGUAGES CXX) add_library(antithesis-sdk-cpp INTERFACE antithesis_sdk.h) diff --git a/external/antithesis-sdk/README.md b/external/antithesis-sdk/README.md index ce512d7c6fd..eb0237868de 100644 --- a/external/antithesis-sdk/README.md +++ b/external/antithesis-sdk/README.md @@ -5,4 +5,4 @@ This library provides methods for C++ programs to configure the [Antithesis](htt * Randomness functions for requesting both structured and unstructured randomness from the Antithesis platform. * Lifecycle functions that inform the Antithesis environment that particular test phases or milestones have been reached. -For general usage guidance see the [Antithesis C++ SDK Documentation](https://antithesis.com/docs/using_antithesis/sdk/cpp/overview.html) +For general usage guidance see the [Antithesis C++ SDK Documentation](https://antithesis.com/docs/using_antithesis/sdk/cpp/overview/) diff --git a/external/antithesis-sdk/antithesis_instrumentation.h b/external/antithesis-sdk/antithesis_instrumentation.h index a2e88dbef5d..a88895d72a0 100644 --- a/external/antithesis-sdk/antithesis_instrumentation.h +++ b/external/antithesis-sdk/antithesis_instrumentation.h @@ -7,7 +7,7 @@ This header file can be used in both C and C++ programs. (The rest of the SDK wo You should include it in a single .cpp or .c file. -The instructions (such as required compiler flags) and usage guidance are found at https://antithesis.com/docs/using_antithesis/sdk/cpp/overview.html. +The instructions (such as required compiler flags) and usage guidance are found at https://antithesis.com/docs/using_antithesis/sdk/cpp/overview/. */ #include diff --git a/external/antithesis-sdk/antithesis_sdk.h b/external/antithesis-sdk/antithesis_sdk.h index f6ed8e52d33..14eb292c2d5 100644 --- a/external/antithesis-sdk/antithesis_sdk.h +++ b/external/antithesis-sdk/antithesis_sdk.h @@ -2,10 +2,38 @@ // This header file contains the Antithesis C++ SDK, which enables C++ applications to integrate with the [Antithesis platform]. // -// Documentation for the SDK is found at https://antithesis.com/docs/using_antithesis/sdk/cpp/overview.html. +// Documentation for the SDK is found at https://antithesis.com/docs/using_antithesis/sdk/cpp/overview/. + +#ifndef NO_ANTITHESIS_SDK + +#if __cplusplus < 202000L + #error "The Antithesis C++ API requires C++20 or higher" + #define NO_ANTITHESIS_SDK +#endif + +#if !defined(__clang__) + #error "The Antithesis C++ API requires a clang compiler" + #define NO_ANTITHESIS_SDK +#endif + +#if __clang_major__ < 16 + #error "The Antithesis C++ API requires clang version 16 or higher" + #define NO_ANTITHESIS_SDK +#endif + +#else + +#if __cplusplus < 201700L + #error "The Antithesis C++ API (with NO_ANTITHESIS_SDK) requires C++17 or higher" +#endif + +#endif + +/***************************************************************************** + * COMMON + *****************************************************************************/ #include -#include #include #include #include @@ -14,32 +42,16 @@ #include namespace antithesis { - inline const char* SDK_VERSION = "0.4.0"; + inline const char* SDK_VERSION = "0.4.4"; inline const char* PROTOCOL_VERSION = "1.1.0"; - struct LocalRandom { - std::random_device device; - std::mt19937_64 gen; - std::uniform_int_distribution distribution; - - LocalRandom() : device(), gen(device()), distribution() {} - - uint64_t random() { -#ifdef ANTITHESIS_RANDOM_OVERRIDE - return ANTITHESIS_RANDOM_OVERRIDE(); -#else - return distribution(gen); -#endif - } - }; - struct JSON; struct JSONArray; typedef std::variant JSONValue; struct JSONArray : std::vector { using std::vector::vector; - template::value, bool>::type = true> + template::value, bool>::type = true> JSONArray(std::vector vals) : std::vector(vals.begin(), vals.end()) {} }; @@ -53,57 +65,153 @@ namespace antithesis { } } }; - - // Declarations that we expose - uint64_t get_random(); } -#if defined(NO_ANTITHESIS_SDK) || __cplusplus < 202000L || (defined(__clang__) && __clang_major__ < 16) -#if __cplusplus < 202000L - #error "The Antithesis C++ API requires C++20 or higher" -#endif -#if defined(__clang__) && __clang_major__ < 16 - #error "The Antithesis C++ API requires clang version 16 or higher" +/***************************************************************************** + * INTERNAL HELPERS: LOCAL RANDOM + * Used in both the NO_ANTITHESIS_SDK version and when running locally + *****************************************************************************/ + +#include + +namespace antithesis::internal::random { + struct LocalRandom { + std::random_device device; + std::mt19937_64 gen; + std::uniform_int_distribution distribution; + + LocalRandom() : device(), gen(device()), distribution() {} + + uint64_t random() { +#ifdef ANTITHESIS_RANDOM_OVERRIDE + return ANTITHESIS_RANDOM_OVERRIDE(); +#else + return distribution(gen); #endif + } + }; +} -#define ALWAYS(cond, message, ...) -#define ALWAYS_OR_UNREACHABLE(cond, message, ...) -#define SOMETIMES(cond, message, ...) -#define REACHABLE(message, ...) -#define UNREACHABLE(message, ...) -#define ALWAYS_GREATER_THAN(val, threshold, message, ...) -#define ALWAYS_GREATER_THAN_OR_EQUAL_TO(val, threshold, message, ...) -#define SOMETIMES_GREATER_THAN(val, threshold, message, ...) -#define SOMETIMES_GREATER_THAN_OR_EQUAL_TO(val, threshold, message, ...) -#define ALWAYS_LESS_THAN(val, threshold, message, ...) -#define ALWAYS_LESS_THAN_OR_EQUAL_TO(val, threshold, message, ...) -#define SOMETIMES_LESS_THAN(val, threshold, message, ...) -#define SOMETIMES_LESS_THAN_OR_EQUAL_TO(val, threshold, message, ...) -#define ALWAYS_SOME(pairs, message, ...) -#define SOMETIMES_ALL(pairs, message, ...) +/***************************************************************************** + * INTERNAL HELPERS: JSON + *****************************************************************************/ -namespace antithesis { - inline uint64_t get_random() { - static LocalRandom random_gen; - return random_gen.random(); +#ifndef NO_ANTITHESIS_SDK + +#include +#include + +namespace antithesis::internal::json { + template + inline constexpr bool always_false_v = false; + + static std::ostream& operator<<(std::ostream& out, const JSON& details); + + static void escaped(std::ostream& out, const char c) { + const char HEX[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; + switch (c) { + case '\t': out << "\\t"; break; + case '\b': out << "\\b"; break; + case '\n': out << "\\n"; break; + case '\f': out << "\\f"; break; + case '\r': out << "\\r"; break; + case '\"': out << "\\\""; break; + case '\\': out << "\\\\"; break; + default: + if ('\u0000' <= c && c <= '\u001F') { + out << "\\u00" << HEX[(c >> 4) & 0x0F] << HEX[c & 0x0F]; + } else { + out << c; + } + } } - inline void setup_complete(const JSON& details) { + static std::ostream& operator<<(std::ostream& out, const JSONValue& json) { + std::visit([&](auto&& arg) { + using T = std::decay_t; + if constexpr (std::is_same_v) { + out << '"'; + for (auto c : arg) { + escaped(out, c); + } + out << '"'; + } else if constexpr (std::is_same_v) { + out << (arg ? "true" : "false"); + } else if constexpr (std::is_same_v) { + out << '"'; + escaped(out, arg); + out << '"'; + } else if constexpr (std::is_same_v) { + out << arg; + } else if constexpr (std::is_same_v) { + out << arg; + } else if constexpr (std::is_same_v) { + out << arg; + } else if constexpr (std::is_same_v) { + out << arg; + } else if constexpr (std::is_same_v) { + out << '"'; + for (auto str = arg; *str != '\0'; str++) { + escaped(out, *str); + } + out << '"'; + } else if constexpr (std::is_same_v) { + out << "null"; + } else if constexpr (std::is_same_v) { + out << arg; + } else if constexpr (std::is_same_v) { + out << '['; + bool first = true; + for (auto &item : arg) { + if (!first) { + out << ','; + } + first = false; + out << item; + } + out << ']'; + } else { + static_assert(always_false_v, "non-exhaustive JSONValue visitor!"); + } + }, json); + + return out; } - inline void send_event(const char* name, const JSON& details) { + static std::ostream& operator<<(std::ostream& out, const JSON& details) { + out << '{'; + + bool first = true; + for (auto [key, value] : details) { + if (!first) { + out << ','; + } + out << '"'; + for (auto c : key) { + escaped(out, c); + } + out << '"' << ':' << value; + first = false; + } + + out << '}'; + return out; } } -#else +#endif + +/***************************************************************************** + * INTERNAL HELPERS: HANDLERS + * Implementations for running locally and running in Antithesis + *****************************************************************************/ + +#ifndef NO_ANTITHESIS_SDK #include -#include -#include #include #include -#include #include #include #include @@ -112,13 +220,14 @@ namespace antithesis { #include #include -namespace antithesis { + +namespace antithesis::internal::handlers { constexpr const char* const ERROR_LOG_LINE_PREFIX = "[* antithesis-sdk-cpp *]"; constexpr const char* LIB_PATH = "/usr/lib/libvoidstar.so"; constexpr const char* LOCAL_OUTPUT_ENVIRONMENT_VARIABLE = "ANTITHESIS_SDK_LOCAL_OUTPUT"; - - static std::ostream& operator<<(std::ostream& out, const JSON& details); + using namespace antithesis::internal::json; + struct LibHandler { virtual ~LibHandler() = default; virtual void output(const char* message) const = 0; @@ -214,7 +323,7 @@ namespace antithesis { } private: FILE* file; - LocalRandom random_gen; + antithesis::internal::random::LocalRandom random_gen; LocalHandler(FILE* file): file(file), random_gen() { } @@ -259,76 +368,48 @@ namespace antithesis { } } - struct AssertionState { - uint8_t false_not_seen : 1; - uint8_t true_not_seen : 1; - uint8_t rest : 6; - - AssertionState() : false_not_seen(true), true_not_seen(true), rest(0) {} - }; + inline LibHandler& get_lib_handler() { + static LibHandler* lib_handler = nullptr; + if (lib_handler == nullptr) { + lib_handler = init().release(); // Leak on exit, rather than exit-time-destructor - template - inline constexpr bool always_false_v = false; + JSON language_block{ + {"name", "C++"}, + {"version", __VERSION__} + }; - static std::ostream& operator<<(std::ostream& out, const JSONValue& json) { - std::visit([&](auto&& arg) - { - using T = std::decay_t; - if constexpr (std::is_same_v) { - out << std::quoted(arg); - } else if constexpr (std::is_same_v) { - out << (arg ? "true" : "false"); - } else if constexpr (std::is_same_v) { - char tmp[2] = {arg, '\0'}; - out << std::quoted(tmp); - } else if constexpr (std::is_same_v) { - out << arg; - } else if constexpr (std::is_same_v) { - out << arg; - } else if constexpr (std::is_same_v) { - out << arg; - } else if constexpr (std::is_same_v) { - out << arg; - } else if constexpr (std::is_same_v) { - out << std::quoted(arg); - } else if constexpr (std::is_same_v) { - out << "null"; - } else if constexpr (std::is_same_v) { - out << arg; - } else if constexpr (std::is_same_v) { - out << '['; - bool first = true; - for (auto &item : arg) { - if (!first) { - out << ','; - } - first = false; - out << item; + JSON version_message{ + {"antithesis_sdk", JSON{ + {"language", language_block}, + {"sdk_version", SDK_VERSION}, + {"protocol_version", PROTOCOL_VERSION} } - out << ']'; - } else { - static_assert(always_false_v, "non-exhaustive JSONValue visitor!"); - } - }, json); + }}; + lib_handler->output(version_message); + } - return out; + return *lib_handler; } +} - static std::ostream& operator<<(std::ostream& out, const JSON& details) { - out << '{'; +#endif - bool first = true; - for (auto [key, value] : details) { - if (!first) { - out << ','; - } - out << std::quoted(key) << ':' << value; - first = false; - } +/***************************************************************************** + * INTERNAL HELPERS: Various classes related to assertions + *****************************************************************************/ - out << '}'; - return out; - } +#ifndef NO_ANTITHESIS_SDK + +namespace antithesis::internal::assertions { + using namespace antithesis::internal::handlers; + + struct AssertionState { + uint8_t false_not_seen : 1; + uint8_t true_not_seen : 1; + uint8_t rest : 6; + + AssertionState() : false_not_seen(true), true_not_seen(true), rest(0) {} + }; enum AssertionType { ALWAYS_ASSERTION, @@ -395,29 +476,6 @@ namespace antithesis { return message; } - inline LibHandler& get_lib_handler() { - static LibHandler* lib_handler = nullptr; - if (lib_handler == nullptr) { - lib_handler = init().release(); // Leak on exit, rather than exit-time-destructor - - JSON language_block{ - {"name", "C++"}, - {"version", __VERSION__} - }; - - JSON version_message{ - {"antithesis_sdk", JSON{ - {"language", language_block}, - {"sdk_version", SDK_VERSION}, - {"protocol_version", PROTOCOL_VERSION} - } - }}; - lib_handler->output(version_message); - } - - return *lib_handler; - } - inline void assert_impl(bool cond, const char* message, const JSON& details, const LocationInfo& location_info, bool hit, bool must_hit, const char* assert_type, const char* display_type, const char* id) { JSON assertion{ @@ -433,7 +491,7 @@ namespace antithesis { {"details", details}, }} }; - get_lib_handler().output(assertion); + antithesis::internal::handlers::get_lib_handler().output(assertion); } inline void assert_raw(bool cond, const char* message, const JSON& details, @@ -475,12 +533,13 @@ namespace antithesis { } } - [[clang::always_inline]] inline void check_assertion(bool cond, const JSON& details) { + [[clang::always_inline]] inline void check_assertion(auto&& cond, const JSON& details) + requires requires { static_cast(std::forward(cond)); } { #if defined(NO_ANTITHESIS_SDK) #error "Antithesis SDK has been disabled" #endif if (__builtin_expect(state.false_not_seen || state.true_not_seen, false)) { - check_assertion_internal(cond, details); + check_assertion_internal(static_cast(std::forward(cond)), details); } } @@ -508,25 +567,6 @@ namespace antithesis { } }; - inline uint64_t get_random() { - return get_lib_handler().random(); - } - - inline void setup_complete(const JSON& details) { - JSON json{ - { "antithesis_setup", JSON{ - {"status", "complete"}, - {"details", details} - }} - }; - get_lib_handler().output(json); - } - - inline void send_event(const char* name, const JSON& details) { - JSON json = { { name, details } }; - get_lib_handler().output(json); - } - enum GuidepostType { GUIDEPOST_MAXIMIZE, GUIDEPOST_MINIMIZE, @@ -725,7 +765,8 @@ namespace antithesis { }; } -namespace { +namespace antithesis::internal { +namespace { // Anonymous namespace which is translation-unit-specific; certain symbols aren't exposed in the symbol table as a result template struct fixed_string { std::array contents; @@ -763,50 +804,55 @@ namespace { } #pragma clang diagnostic pop - template + template struct CatalogEntry { - [[clang::always_inline]] static inline antithesis::Assertion create() { - antithesis::LocationInfo location{ "", function_name.c_str(), file_name.c_str(), line, column }; - return antithesis::Assertion(message.c_str(), type, std::move(location)); + [[clang::always_inline]] static inline antithesis::internal::assertions::Assertion create() { + antithesis::internal::assertions::LocationInfo location{ "", function_name.c_str(), file_name.c_str(), line, column }; + return antithesis::internal::assertions::Assertion(message.c_str(), type, std::move(location)); } - static inline antithesis::Assertion assertion = create(); + static inline antithesis::internal::assertions::Assertion assertion = create(); }; - template + template struct BooleanGuidanceCatalogEntry { - [[clang::always_inline]] static inline antithesis::BooleanGuidepost create() { - antithesis::LocationInfo location{ "", function_name.c_str(), file_name.c_str(), line, column }; + [[clang::always_inline]] static inline antithesis::internal::assertions::BooleanGuidepost create() { + antithesis::internal::assertions::LocationInfo location{ "", function_name.c_str(), file_name.c_str(), line, column }; switch (type) { - case antithesis::GUIDEPOST_ALL: - case antithesis::GUIDEPOST_NONE: - return antithesis::BooleanGuidepost(message.c_str(), std::move(location), type); + case antithesis::internal::assertions::GUIDEPOST_ALL: + case antithesis::internal::assertions::GUIDEPOST_NONE: + return antithesis::internal::assertions::BooleanGuidepost(message.c_str(), std::move(location), type); default: throw std::runtime_error("Can't create boolean guidepost with non-boolean type"); } } - static inline antithesis::BooleanGuidepost guidepost = create(); + static inline antithesis::internal::assertions::BooleanGuidepost guidepost = create(); }; - template + template struct NumericGuidanceCatalogEntry { - [[clang::always_inline]] static inline antithesis::NumericGuidepost create() { - antithesis::LocationInfo location{ "", function_name.c_str(), file_name.c_str(), line, column }; + [[clang::always_inline]] static inline antithesis::internal::assertions::NumericGuidepost create() { + antithesis::internal::assertions::LocationInfo location{ "", function_name.c_str(), file_name.c_str(), line, column }; switch (type) { - case antithesis::GUIDEPOST_MAXIMIZE: - case antithesis::GUIDEPOST_MINIMIZE: - return antithesis::NumericGuidepost(message.c_str(), std::move(location), type); + case antithesis::internal::assertions::GUIDEPOST_MAXIMIZE: + case antithesis::internal::assertions::GUIDEPOST_MINIMIZE: + return antithesis::internal::assertions::NumericGuidepost(message.c_str(), std::move(location), type); default: throw std::runtime_error("Can't create numeric guidepost with non-numeric type"); } } - static inline antithesis::NumericGuidepost guidepost = create(); + static inline antithesis::internal::assertions::NumericGuidepost guidepost = create(); }; } +} -#define FIXED_STRING_FROM_C_STR(s) (fixed_string::from_c_str(s)) +#endif + +/***************************************************************************** + * PUBLIC SDK: ASSERTIONS + *****************************************************************************/ #define _NL_1(foo) { #foo, foo } #define _NL_2(foo, ...) { #foo, foo }, _NL_1(__VA_ARGS__) @@ -826,37 +872,90 @@ namespace { #define NAMED_LIST(...) { _GET_NL(__VA_ARGS__)(__VA_ARGS__) } +#ifdef NO_ANTITHESIS_SDK + +#ifndef ANTITHESIS_SDK_ALWAYS_POLYFILL + #define ANTITHESIS_SDK_ALWAYS_POLYFILL(...) +#endif + +#ifndef ANTITHESIS_SDK_SOMETIMES_POLYFILL + #define ANTITHESIS_SDK_SOMETIMES_POLYFILL(...) +#endif + +#ifndef ANTITHESIS_SDK_ALWAYS_OR_UNREACHABLE_POLYFILL + #define ANTITHESIS_SDK_ALWAYS_OR_UNREACHABLE_POLYFILL(...) \ + ANTITHESIS_SDK_ALWAYS_POLYFILL(__VA_ARGS__) +#endif + +#define ALWAYS(cond, message, ...) \ + ANTITHESIS_SDK_ALWAYS_POLYFILL(cond, message, __VA_ARGS__) +#define ALWAYS_OR_UNREACHABLE(cond, message, ...) \ + ANTITHESIS_SDK_ALWAYS_OR_UNREACHABLE_POLYFILL(cond, message, __VA_ARGS__) +#define SOMETIMES(cond, message, ...) \ + ANTITHESIS_SDK_SOMETIMES_POLYFILL(cond, message, __VA_ARGS__) +#define REACHABLE(message, ...) \ + ANTITHESIS_SDK_SOMETIMES_POLYFILL(true, message, __VA_ARGS__) +#define UNREACHABLE(message, ...) \ + ANTITHESIS_SDK_ALWAYS_POLYFILL(false, message, __VA_ARGS__) +#define ALWAYS_GREATER_THAN(val, threshold, message, ...) \ + ANTITHESIS_SDK_ALWAYS_POLYFILL((val > threshold), message, __VA_ARGS__) +#define ALWAYS_GREATER_THAN_OR_EQUAL_TO(val, threshold, message, ...) \ + ANTITHESIS_SDK_ALWAYS_POLYFILL((val >= threshold), message, __VA_ARGS__) +#define SOMETIMES_GREATER_THAN(val, threshold, message, ...) \ + ANTITHESIS_SDK_SOMETIMES_POLYFILL((val > threshold), message, __VA_ARGS__) +#define SOMETIMES_GREATER_THAN_OR_EQUAL_TO(val, threshold, message, ...) \ + ANTITHESIS_SDK_SOMETIMES_POLYFILL((val >= threshold), message, __VA_ARGS__) +#define ALWAYS_LESS_THAN(val, threshold, message, ...) \ + ANTITHESIS_SDK_ALWAYS_POLYFILL((val < threshold), message, __VA_ARGS__) +#define ALWAYS_LESS_THAN_OR_EQUAL_TO(val, threshold, message, ...) \ + ANTITHESIS_SDK_ALWAYS_POLYFILL((val <= threshold), message, __VA_ARGS__) +#define SOMETIMES_LESS_THAN(val, threshold, message, ...) \ + ANTITHESIS_SDK_SOMETIMES_POLYFILL((val < threshold), message, __VA_ARGS__) +#define SOMETIMES_LESS_THAN_OR_EQUAL_TO(val, threshold, message, ...) \ + ANTITHESIS_SDK_SOMETIMES_POLYFILL((val <= threshold), message, __VA_ARGS__) +#define ALWAYS_SOME(pairs, message, ...) \ + ANTITHESIS_SDK_ALWAYS_POLYFILL(([&](){ \ + std::initializer_list> ps = pairs; \ + for (auto const& pair : ps) \ + if (pair.second) return true; \ + return false; }()), message, __VA_ARGS__) +#define SOMETIMES_ALL(pairs, message, ...) \ + ANTITHESIS_SDK_SOMETIMES_POLYFILL(([&](){ \ + std::initializer_list> ps = pairs; \ + for (auto const& pair : ps) \ + if (!pair.second) return false; \ + return true; }()), message, __VA_ARGS__) + +#else + +#include + +#define FIXED_STRING_FROM_C_STR(s) (antithesis::internal::fixed_string::from_c_str(s)) + #define ANTITHESIS_ASSERT_RAW(type, cond, message, ...) ( \ - CatalogEntry< \ + antithesis::internal::CatalogEntry< \ type, \ - fixed_string(message), \ + antithesis::internal::fixed_string(message), \ FIXED_STRING_FROM_C_STR(std::source_location::current().file_name()), \ FIXED_STRING_FROM_C_STR(std::source_location::current().function_name()), \ std::source_location::current().line(), \ std::source_location::current().column() \ >::assertion.check_assertion(cond, (antithesis::JSON(__VA_ARGS__)) ) ) -#define ALWAYS(cond, message, ...) ANTITHESIS_ASSERT_RAW(antithesis::ALWAYS_ASSERTION, cond, message, __VA_ARGS__) -#define ALWAYS_OR_UNREACHABLE(cond, message, ...) ANTITHESIS_ASSERT_RAW(antithesis::ALWAYS_OR_UNREACHABLE_ASSERTION, cond, message, __VA_ARGS__) -#define SOMETIMES(cond, message, ...) ANTITHESIS_ASSERT_RAW(antithesis::SOMETIMES_ASSERTION, cond, message, __VA_ARGS__) -#define REACHABLE(message, ...) ANTITHESIS_ASSERT_RAW(antithesis::REACHABLE_ASSERTION, true, message, __VA_ARGS__) -#define UNREACHABLE(message, ...) ANTITHESIS_ASSERT_RAW(antithesis::UNREACHABLE_ASSERTION, false, message, __VA_ARGS__) +#define ALWAYS(cond, message, ...) ANTITHESIS_ASSERT_RAW(antithesis::internal::assertions::ALWAYS_ASSERTION, cond, message, __VA_ARGS__) +#define ALWAYS_OR_UNREACHABLE(cond, message, ...) ANTITHESIS_ASSERT_RAW(antithesis::internal::assertions::ALWAYS_OR_UNREACHABLE_ASSERTION, cond, message, __VA_ARGS__) +#define SOMETIMES(cond, message, ...) ANTITHESIS_ASSERT_RAW(antithesis::internal::assertions::SOMETIMES_ASSERTION, cond, message, __VA_ARGS__) +#define REACHABLE(message, ...) ANTITHESIS_ASSERT_RAW(antithesis::internal::assertions::REACHABLE_ASSERTION, true, message, __VA_ARGS__) +#define UNREACHABLE(message, ...) ANTITHESIS_ASSERT_RAW(antithesis::internal::assertions::UNREACHABLE_ASSERTION, false, message, __VA_ARGS__) -#define ALWAYS_GREATER_THAN(left, right, message, ...) \ +#define ANTITHESIS_NUMERIC_ASSERT_RAW(name, assertion_type, guidepost_type, left, cmp, right, message, ...) \ do { \ - static_assert(std::is_same_v, "Values compared in ALWAYS_GREATER_THAN must be of same type"); \ - CatalogEntry< \ - antithesis::ALWAYS_ASSERTION, \ - fixed_string(message), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().file_name()), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().function_name()), \ - std::source_location::current().line(), \ - std::source_location::current().column() \ - >::assertion.check_assertion(left > right, (antithesis::JSON(__VA_ARGS__, {{ "left", left }, { "right", right }})) ); \ - NumericGuidanceCatalogEntry< \ + static_assert(std::is_same_v, "Values compared in " #name " must be of same type"); \ + ANTITHESIS_ASSERT_RAW(assertion_type, left cmp right, message, __VA_ARGS__ __VA_OPT__(,) {{ "left", left }, { "right", right }} ); \ + antithesis::internal::NumericGuidanceCatalogEntry< \ decltype(left), \ - antithesis::GUIDEPOST_MINIMIZE, \ - fixed_string(message), \ + guidepost_type, \ + antithesis::internal::fixed_string(message), \ FIXED_STRING_FROM_C_STR(std::source_location::current().file_name()), \ FIXED_STRING_FROM_C_STR(std::source_location::current().function_name()), \ std::source_location::current().line(), \ @@ -864,182 +963,39 @@ do { \ >::guidepost.send_guidance({ left, right }); \ } while (0) +#define ALWAYS_GREATER_THAN(left, right, message, ...) \ +ANTITHESIS_NUMERIC_ASSERT_RAW(ALWAYS_GREATER_THAN, antithesis::internal::assertions::ALWAYS_ASSERTION, antithesis::internal::assertions::GUIDEPOST_MINIMIZE, left, >, right, message, __VA_ARGS__) #define ALWAYS_GREATER_THAN_OR_EQUAL_TO(left, right, message, ...) \ -do { \ - static_assert(std::is_same_v, "Values compared in ALWAYS_GREATER_THAN_OR_EQUAL_TO must be of same type"); \ - CatalogEntry< \ - antithesis::ALWAYS_ASSERTION, \ - fixed_string(message), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().file_name()), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().function_name()), \ - std::source_location::current().line(), \ - std::source_location::current().column() \ - >::assertion.check_assertion(left >= right, (antithesis::JSON(__VA_ARGS__, {{ "left", left }, { "right", right }})) ); \ - NumericGuidanceCatalogEntry< \ - decltype(left), \ - antithesis::GUIDEPOST_MINIMIZE, \ - fixed_string(message), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().file_name()), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().function_name()), \ - std::source_location::current().line(), \ - std::source_location::current().column() \ - >::guidepost.send_guidance({ left, right }); \ -} while (0) - +ANTITHESIS_NUMERIC_ASSERT_RAW(ALWAYS_GREATER_THAN_OR_EQUAL_TO, antithesis::internal::assertions::ALWAYS_ASSERTION, antithesis::internal::assertions::GUIDEPOST_MINIMIZE, left, >=, right, message, __VA_ARGS__) #define SOMETIMES_GREATER_THAN(left, right, message, ...) \ -do { \ - static_assert(std::is_same_v, "Values compared in SOMETIMES_GREATER_THAN must be of same type"); \ - CatalogEntry< \ - antithesis::SOMETIMES_ASSERTION, \ - fixed_string(message), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().file_name()), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().function_name()), \ - std::source_location::current().line(), \ - std::source_location::current().column() \ - >::assertion.check_assertion(left > right, (antithesis::JSON(__VA_ARGS__, {{ "left", left }, { "right", right }})) ); \ - NumericGuidanceCatalogEntry< \ - decltype(left), \ - antithesis::GUIDEPOST_MAXIMIZE, \ - fixed_string(message), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().file_name()), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().function_name()), \ - std::source_location::current().line(), \ - std::source_location::current().column() \ - >::guidepost.send_guidance({ left, right }); \ -} while (0) - +ANTITHESIS_NUMERIC_ASSERT_RAW(SOMETIMES_GREATER_THAN, antithesis::internal::assertions::SOMETIMES_ASSERTION, antithesis::internal::assertions::GUIDEPOST_MAXIMIZE, left, >, right, message, __VA_ARGS__) #define SOMETIMES_GREATER_THAN_OR_EQUAL_TO(left, right, message, ...) \ -do { \ - static_assert(std::is_same_v, "Values compared in SOMETIMES_GREATER_THAN_OR_EQUAL_TO must be of same type"); \ - CatalogEntry< \ - antithesis::SOMETIMES_ASSERTION, \ - fixed_string(message), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().file_name()), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().function_name()), \ - std::source_location::current().line(), \ - std::source_location::current().column() \ - >::assertion.check_assertion(left >= right, (antithesis::JSON(__VA_ARGS__, {{ "left", left }, { "right", right }})) ); \ - NumericGuidanceCatalogEntry< \ - decltype(left), \ - antithesis::GUIDEPOST_MAXIMIZE, \ - fixed_string(message), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().file_name()), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().function_name()), \ - std::source_location::current().line(), \ - std::source_location::current().column() \ - >::guidepost.send_guidance({ left, right }); \ -} while (0) - +ANTITHESIS_NUMERIC_ASSERT_RAW(SOMETIMES_GREATER_THAN_OR_EQUAL_TO, antithesis::internal::assertions::SOMETIMES_ASSERTION, antithesis::internal::assertions::GUIDEPOST_MAXIMIZE, left, >=, right, message, __VA_ARGS__) #define ALWAYS_LESS_THAN(left, right, message, ...) \ -do { \ - static_assert(std::is_same_v, "Values compared in ALWAYS_LESS_THAN must be of same type"); \ - CatalogEntry< \ - antithesis::ALWAYS_ASSERTION, \ - fixed_string(message), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().file_name()), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().function_name()), \ - std::source_location::current().line(), \ - std::source_location::current().column() \ - >::assertion.check_assertion(left < right, (antithesis::JSON(__VA_ARGS__, {{ "left", left }, { "right", right }})) ); \ - NumericGuidanceCatalogEntry< \ - decltype(left), \ - antithesis::GUIDEPOST_MAXIMIZE, \ - fixed_string(message), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().file_name()), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().function_name()), \ - std::source_location::current().line(), \ - std::source_location::current().column() \ - >::guidepost.send_guidance({ left, right }); \ -} while (0) - +ANTITHESIS_NUMERIC_ASSERT_RAW(ALWAYS_LESS_THAN, antithesis::internal::assertions::ALWAYS_ASSERTION, antithesis::internal::assertions::GUIDEPOST_MAXIMIZE, left, <, right, message, __VA_ARGS__) #define ALWAYS_LESS_THAN_OR_EQUAL_TO(left, right, message, ...) \ -do { \ - static_assert(std::is_same_v, "Values compared in ALWAYS_LESS_THAN_OR_EQUAL_TO must be of same type"); \ - CatalogEntry< \ - antithesis::ALWAYS_ASSERTION, \ - fixed_string(message), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().file_name()), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().function_name()), \ - std::source_location::current().line(), \ - std::source_location::current().column() \ - >::assertion.check_assertion(left <= right, (antithesis::JSON(__VA_ARGS__, {{ "left", left }, { "right", right }})) ); \ - NumericGuidanceCatalogEntry< \ - decltype(left), \ - antithesis::GUIDEPOST_MAXIMIZE, \ - fixed_string(message), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().file_name()), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().function_name()), \ - std::source_location::current().line(), \ - std::source_location::current().column() \ - >::guidepost.send_guidance({ left, right }); \ -} while (0) - +ANTITHESIS_NUMERIC_ASSERT_RAW(ALWAYS_LESS_THAN_OR_EQUAL_TO, antithesis::internal::assertions::ALWAYS_ASSERTION, antithesis::internal::assertions::GUIDEPOST_MAXIMIZE, left, <=, right, message, __VA_ARGS__) #define SOMETIMES_LESS_THAN(left, right, message, ...) \ -do { \ - static_assert(std::is_same_v, "Values compared in SOMETIMES_LESS_THAN must be of same type"); \ - CatalogEntry< \ - antithesis::SOMETIMES_ASSERTION, \ - fixed_string(message), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().file_name()), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().function_name()), \ - std::source_location::current().line(), \ - std::source_location::current().column() \ - >::assertion.check_assertion(left < right, (antithesis::JSON(__VA_ARGS__, {{ "left", left }, { "right", right }})) ); \ - NumericGuidanceCatalogEntry< \ - decltype(left), \ - antithesis::GUIDEPOST_MINIMIZE, \ - fixed_string(message), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().file_name()), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().function_name()), \ - std::source_location::current().line(), \ - std::source_location::current().column() \ - >::guidepost.send_guidance({ left, right }); \ -} while (0) - +ANTITHESIS_NUMERIC_ASSERT_RAW(SOMETIMES_LESS_THAN, antithesis::internal::assertions::SOMETIMES_ASSERTION, antithesis::internal::assertions::GUIDEPOST_MINIMIZE, left, <, right, message, __VA_ARGS__) #define SOMETIMES_LESS_THAN_OR_EQUAL_TO(left, right, message, ...) \ -do { \ - static_assert(std::is_same_v, "Values compared in SOMETIMES_LESS_THAN_OR_EQUAL_TO must be of same type"); \ - CatalogEntry< \ - antithesis::SOMETIMES_ASSERTION, \ - fixed_string(message), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().file_name()), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().function_name()), \ - std::source_location::current().line(), \ - std::source_location::current().column() \ - >::assertion.check_assertion(left <= right, (antithesis::JSON(__VA_ARGS__, {{ "left", left }, { "right", right }})) ); \ - NumericGuidanceCatalogEntry< \ - decltype(left), \ - antithesis::GUIDEPOST_MINIMIZE, \ - fixed_string(message), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().file_name()), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().function_name()), \ - std::source_location::current().line(), \ - std::source_location::current().column() \ - >::guidepost.send_guidance({ left, right }); \ -} while (0) +ANTITHESIS_NUMERIC_ASSERT_RAW(SOMETIMES_LESS_THAN_OR_EQUAL_TO, antithesis::internal::assertions::SOMETIMES_ASSERTION, antithesis::internal::assertions::GUIDEPOST_MINIMIZE, left, <=, right, message, __VA_ARGS__) #define ALWAYS_SOME(pairs, message, ...) \ do { \ bool disjunction = false; \ - for (std::pair pair : pairs) { \ + std::vector> vec_pairs = pairs; \ + for (std::pair pair : vec_pairs) { \ if (pair.second) { \ disjunction = true; \ break; \ } \ } \ - CatalogEntry< \ - antithesis::ALWAYS_ASSERTION, \ - fixed_string(message), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().file_name()), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().function_name()), \ - std::source_location::current().line(), \ - std::source_location::current().column() \ - >::assertion.check_assertion(disjunction, (antithesis::JSON(__VA_ARGS__, pairs)) ); \ - antithesis::json json_pairs = antithesis::json(pairs); \ - BooleanGuidanceCatalogEntry< \ + ANTITHESIS_ASSERT_RAW(antithesis::internal::assertions::ALWAYS_ASSERTION, disjunction, message, __VA_ARGS__ __VA_OPT__(,) pairs); \ + antithesis::JSON json_pairs = antithesis::JSON(pairs); \ + antithesis::internal::BooleanGuidanceCatalogEntry< \ decltype(json_pairs), \ - antithesis::GUIDEPOST_NONE, \ - fixed_string(message), \ + antithesis::internal::assertions::GUIDEPOST_NONE, \ + antithesis::internal::fixed_string(message), \ FIXED_STRING_FROM_C_STR(std::source_location::current().file_name()), \ FIXED_STRING_FROM_C_STR(std::source_location::current().function_name()), \ std::source_location::current().line(), \ @@ -1050,25 +1006,19 @@ do { \ #define SOMETIMES_ALL(pairs, message, ...) \ do { \ bool conjunction = true; \ - for (std::pair pair : pairs) { \ + std::vector> vec_pairs = pairs; \ + for (std::pair pair : vec_pairs) { \ if (!pair.second) { \ conjunction = false; \ break; \ } \ } \ - CatalogEntry< \ - antithesis::SOMETIMES_ASSERTION, \ - fixed_string(message), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().file_name()), \ - FIXED_STRING_FROM_C_STR(std::source_location::current().function_name()), \ - std::source_location::current().line(), \ - std::source_location::current().column() \ - >::assertion.check_assertion(conjunction, (antithesis::JSON(__VA_ARGS__, pairs)) ); \ - antithesis::json json_pairs = antithesis::json(pairs); \ - BooleanGuidanceCatalogEntry< \ + ANTITHESIS_ASSERT_RAW(antithesis::internal::assertions::SOMETIMES_ASSERTION, conjunction, message, __VA_ARGS__ __VA_OPT__(,) pairs); \ + antithesis::JSON json_pairs = antithesis::JSON(pairs); \ + antithesis::internal::BooleanGuidanceCatalogEntry< \ decltype(json_pairs), \ - antithesis::GUIDEPOST_ALL, \ - fixed_string(message), \ + antithesis::internal::assertions::GUIDEPOST_ALL, \ + antithesis::internal::fixed_string(message), \ FIXED_STRING_FROM_C_STR(std::source_location::current().file_name()), \ FIXED_STRING_FROM_C_STR(std::source_location::current().function_name()), \ std::source_location::current().line(), \ @@ -1078,6 +1028,68 @@ do { \ #endif +/***************************************************************************** + * PUBLIC SDK: LIFECYCLE + *****************************************************************************/ + +#ifdef NO_ANTITHESIS_SDK + +namespace antithesis { + inline void setup_complete(const JSON& details) { + } + + inline void send_event(const char* name, const JSON& details) { + } +} + +#else + +namespace antithesis { + inline void setup_complete(const JSON& details) { + JSON json{ + { "antithesis_setup", JSON{ + {"status", "complete"}, + {"details", details} + }} + }; + antithesis::internal::handlers::get_lib_handler().output(json); + } + + inline void send_event(const char* name, const JSON& details) { + JSON json = { { name, details } }; + antithesis::internal::handlers::get_lib_handler().output(json); + } +} +#endif + +/***************************************************************************** + * PUBLIC SDK: RANDOM + *****************************************************************************/ + +namespace antithesis { + // Declarations that we expose + uint64_t get_random(); +} + +#ifdef NO_ANTITHESIS_SDK + +namespace antithesis { + inline uint64_t get_random() { + static antithesis::internal::random::LocalRandom random_gen; + return random_gen.random(); + } +} + +#else + +namespace antithesis { + inline uint64_t get_random() { + return antithesis::internal::handlers::get_lib_handler().random(); + } +} + +#endif + namespace antithesis { template Iter random_choice(Iter begin, Iter end) { diff --git a/include/xrpl/basics/Buffer.h b/include/xrpl/basics/Buffer.h index 733db0bdb72..eb7a4571981 100644 --- a/include/xrpl/basics/Buffer.h +++ b/include/xrpl/basics/Buffer.h @@ -112,7 +112,7 @@ class Buffer operator=(Slice s) { // Ensure the slice isn't a subset of the buffer. - ASSERT( + XRPL_ASSERT( s.size() == 0 || size_ == 0 || s.data() < p_.get() || s.data() >= p_.get() + size_, "ripple::Buffer::operator=(Slice) : input not a subset"); diff --git a/include/xrpl/basics/MathUtilities.h b/include/xrpl/basics/MathUtilities.h index 45b8fc485cc..516c07f377f 100644 --- a/include/xrpl/basics/MathUtilities.h +++ b/include/xrpl/basics/MathUtilities.h @@ -43,7 +43,7 @@ namespace ripple { constexpr std::size_t calculatePercent(std::size_t count, std::size_t total) { - assert(total != 0); // NOTE No ASSERT here, because constexpr + assert(total != 0); // NOTE No XRPL_ASSERT here, because constexpr return ((std::min(count, total) * 100) + total - 1) / total; } diff --git a/include/xrpl/basics/SlabAllocator.h b/include/xrpl/basics/SlabAllocator.h index 147231299e7..5e3a2b5138e 100644 --- a/include/xrpl/basics/SlabAllocator.h +++ b/include/xrpl/basics/SlabAllocator.h @@ -143,7 +143,7 @@ class SlabAllocator void deallocate(std::uint8_t* ptr) noexcept { - ASSERT( + XRPL_ASSERT( own(ptr), "ripple::SlabAllocator::SlabBlock::deallocate : own input"); @@ -188,7 +188,7 @@ class SlabAllocator boost::alignment::align_up(sizeof(Type) + extra, itemAlignment_)) , slabSize_(alloc) { - ASSERT( + XRPL_ASSERT( (itemAlignment_ & (itemAlignment_ - 1)) == 0, "ripple::SlabAllocator::SlabAllocator : valid alignment"); } @@ -300,8 +300,8 @@ class SlabAllocator bool deallocate(std::uint8_t* ptr) noexcept { - ASSERT( - ptr != nullptr, + XRPL_ASSERT( + ptr, "ripple::SlabAllocator::SlabAllocator::deallocate : non-null " "input"); diff --git a/include/xrpl/basics/Slice.h b/include/xrpl/basics/Slice.h index c10ca0b0e96..9e9991f0dd2 100644 --- a/include/xrpl/basics/Slice.h +++ b/include/xrpl/basics/Slice.h @@ -103,7 +103,7 @@ class Slice std::uint8_t operator[](std::size_t i) const noexcept { - ASSERT( + XRPL_ASSERT( i < size_, "ripple::Slice::operator[](std::size_t) const : valid input"); return data_[i]; diff --git a/include/xrpl/basics/base_uint.h b/include/xrpl/basics/base_uint.h index 66237dcf3d1..05d83b3bb0a 100644 --- a/include/xrpl/basics/base_uint.h +++ b/include/xrpl/basics/base_uint.h @@ -291,7 +291,7 @@ class base_uint std::is_trivially_copyable::value>> explicit base_uint(Container const& c) { - ASSERT( + XRPL_ASSERT( c.size() * sizeof(typename Container::value_type) == size(), "ripple::base_uint::base_uint(Container auto) : input size match"); std::memcpy(data_.data(), c.data(), size()); @@ -304,7 +304,7 @@ class base_uint base_uint&> operator=(Container const& c) { - ASSERT( + XRPL_ASSERT( c.size() * sizeof(typename Container::value_type) == size(), "ripple::base_uint::operator=(Container auto) : input size match"); std::memcpy(data_.data(), c.data(), size()); diff --git a/include/xrpl/basics/partitioned_unordered_map.h b/include/xrpl/basics/partitioned_unordered_map.h index 3c33749d6d4..4619ca1f4ce 100644 --- a/include/xrpl/basics/partitioned_unordered_map.h +++ b/include/xrpl/basics/partitioned_unordered_map.h @@ -258,8 +258,8 @@ class partitioned_unordered_map ? *partitions : std::thread::hardware_concurrency(); map_.resize(partitions_); - ASSERT( - partitions_ != 0, + XRPL_ASSERT( + partitions_, "ripple::partitioned_unordered_map::partitioned_unordered_map : " "nonzero partitions"); } diff --git a/include/xrpl/basics/random.h b/include/xrpl/basics/random.h index 41369d2a454..ca65b581d2e 100644 --- a/include/xrpl/basics/random.h +++ b/include/xrpl/basics/random.h @@ -114,7 +114,7 @@ std::enable_if_t< Integral> rand_int(Engine& engine, Integral min, Integral max) { - ASSERT(max > min, "ripple::rand_int : max over min inputs"); + XRPL_ASSERT(max > min, "ripple::rand_int : max over min inputs"); // This should have no state and constructing it should // be very cheap. If that turns out not to be the case diff --git a/include/xrpl/basics/scope.h b/include/xrpl/basics/scope.h index a38184041c6..954edcc2a16 100644 --- a/include/xrpl/basics/scope.h +++ b/include/xrpl/basics/scope.h @@ -235,7 +235,7 @@ class scope_unlock explicit scope_unlock(std::unique_lock& lock) noexcept(true) : plock(&lock) { - ASSERT( + XRPL_ASSERT( plock->owns_lock(), "ripple::scope_unlock::scope_unlock : mutex must be locked"); plock->unlock(); diff --git a/include/xrpl/basics/spinlock.h b/include/xrpl/basics/spinlock.h index 92514478c4f..14a063e27a6 100644 --- a/include/xrpl/basics/spinlock.h +++ b/include/xrpl/basics/spinlock.h @@ -117,7 +117,7 @@ class packed_spinlock packed_spinlock(std::atomic& lock, int index) : bits_(lock), mask_(static_cast(1) << index) { - ASSERT( + XRPL_ASSERT( index >= 0 && (mask_ != 0), "ripple::packed_spinlock::packed_spinlock : valid index and mask"); } diff --git a/include/xrpl/beast/asio/io_latency_probe.h b/include/xrpl/beast/asio/io_latency_probe.h index fb4f5f9f6a2..ca3efcdb3f1 100644 --- a/include/xrpl/beast/asio/io_latency_probe.h +++ b/include/xrpl/beast/asio/io_latency_probe.h @@ -174,8 +174,8 @@ class io_latency_probe , m_repeat(repeat) , m_probe(probe) { - ASSERT( - m_probe != nullptr, + XRPL_ASSERT( + m_probe, "beast::io_latency_probe::sample_op::sample_op : non-null " "probe input"); m_probe->addref(); @@ -187,8 +187,8 @@ class io_latency_probe , m_repeat(from.m_repeat) , m_probe(from.m_probe) { - ASSERT( - m_probe != nullptr, + XRPL_ASSERT( + m_probe, "beast::io_latency_probe::sample_op::sample_op(sample_op&&) : " "non-null probe input"); from.m_probe = nullptr; diff --git a/include/xrpl/beast/clock/manual_clock.h b/include/xrpl/beast/clock/manual_clock.h index 505cbe27208..32ff76bb073 100644 --- a/include/xrpl/beast/clock/manual_clock.h +++ b/include/xrpl/beast/clock/manual_clock.h @@ -61,7 +61,7 @@ class manual_clock : public abstract_clock void set(time_point const& when) { - ASSERT( + XRPL_ASSERT( !Clock::is_steady || when >= now_, "beast::manual_clock::set(time_point) : forward input"); now_ = when; @@ -80,7 +80,7 @@ class manual_clock : public abstract_clock void advance(std::chrono::duration const& elapsed) { - ASSERT( + XRPL_ASSERT( !Clock::is_steady || (now_ + elapsed) >= now_, "beast::manual_clock::advance(duration) : forward input"); now_ += elapsed; diff --git a/include/xrpl/beast/container/detail/aged_unordered_container.h b/include/xrpl/beast/container/detail/aged_unordered_container.h index 30c8489693e..abafc6b2c4c 100644 --- a/include/xrpl/beast/container/detail/aged_unordered_container.h +++ b/include/xrpl/beast/container/detail/aged_unordered_container.h @@ -1330,7 +1330,7 @@ class aged_unordered_container size_type bucket(Key const& k) const { - ASSERT( + XRPL_ASSERT( bucket_count() != 0, "beast::detail::aged_unordered_container::bucket : nonzero bucket " "count"); @@ -1474,7 +1474,7 @@ class aged_unordered_container { if (would_exceed(additional)) m_buck.resize(size() + additional, m_cont); - ASSERT( + XRPL_ASSERT( load_factor() <= max_load_factor(), "beast::detail::aged_unordered_container::maybe_rehash : maximum " "load factor"); diff --git a/include/xrpl/beast/core/LexicalCast.h b/include/xrpl/beast/core/LexicalCast.h index 0a7f2379daf..b01fd8ae140 100644 --- a/include/xrpl/beast/core/LexicalCast.h +++ b/include/xrpl/beast/core/LexicalCast.h @@ -160,9 +160,8 @@ struct LexicalCast bool operator()(Out& out, char const* in) const { - ASSERT( - in != nullptr, - "beast::detail::LexicalCast(char const*) : non-null input"); + XRPL_ASSERT( + in, "beast::detail::LexicalCast(char const*) : non-null input"); return LexicalCast()(out, in); } }; @@ -177,9 +176,7 @@ struct LexicalCast bool operator()(Out& out, char* in) const { - ASSERT( - in != nullptr, - "beast::detail::LexicalCast(char*) : non-null input"); + XRPL_ASSERT(in, "beast::detail::LexicalCast(char*) : non-null input"); return LexicalCast()(out, in); } }; diff --git a/include/xrpl/beast/utility/Journal.h b/include/xrpl/beast/utility/Journal.h index aaa53a3515d..908738a2be2 100644 --- a/include/xrpl/beast/utility/Journal.h +++ b/include/xrpl/beast/utility/Journal.h @@ -205,7 +205,7 @@ class Journal */ Stream(Sink& sink, Severity level) : m_sink(sink), m_level(level) { - ASSERT( + XRPL_ASSERT( m_level < severities::kDisabled, "beast::Journal::Stream::Stream : maximum level"); } diff --git a/include/xrpl/beast/utility/instrumentation.h b/include/xrpl/beast/utility/instrumentation.h index f3f8987242e..72c48959a04 100644 --- a/include/xrpl/beast/utility/instrumentation.h +++ b/include/xrpl/beast/utility/instrumentation.h @@ -28,37 +28,43 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #endif #include #else -#define ALWAYS(cond, name, ...) assert((name) && (cond)) -#define ALWAYS_OR_UNREACHABLE(cond, name, ...) assert((name) && (cond)) -#define SOMETIMES(cond, name, ...) -#define REACHABLE(name, ...) -#define UNREACHABLE(name, ...) assert((name) && false) +// Macros below are copied from antithesis_sdk.h and slightly simplified +// The duplication is because Visual Studio 2019 cannot compile that header +// even with the option -Zc:__cplusplus added. +#define ALWAYS(cond, message, ...) assert((message) && (cond)) +#define ALWAYS_OR_UNREACHABLE(cond, message, ...) assert((message) && (cond)) +#define SOMETIMES(cond, message, ...) +#define REACHABLE(message, ...) +#define UNREACHABLE(message, ...) assert((message) && false) #endif -#define ASSERT ALWAYS_OR_UNREACHABLE +#define XRPL_ASSERT ALWAYS_OR_UNREACHABLE // How to use the instrumentation macros: // -// ALWAYS if cond must be true and the line must be reached during fuzzing -// ASSERT if cond must be true but the line might not be reached during fuzzing -// REACHABLE if the line must be reached during fuzzing -// SOMETIMES a hint for the fuzzer to try to make the cond true -// UNREACHABLE if the line must not be reached (in fuzzing or in normal use) +// * XRPL_ASSERT if cond must be true but the line might not be reached during +// fuzzing. Same like `assert` in normal use. +// * ALWAYS if cond must be true _and_ the line must be reached during fuzzing. +// Same like `assert` in normal use. +// * REACHABLE if the line must be reached during fuzzing +// * SOMETIMES a hint for the fuzzer to try to make the cond true +// * UNREACHABLE if the line must not be reached (in fuzzing or in normal use). +// Same like `assert(false)` in normal use. // -// NOTE: ASSERT has similar semantics as C assert macro, with minor differences: -// * ASSERT must have an unique name (naming convention in CONTRIBUTING.md) -// * the condition (which comes first) must be *implicitly* convertible to bool -// * during fuzzing, the program will continue execution past a failed ASSERT +// NOTE: XRPL_ASSERT has similar semantics as C `assert` macro, with only minor +// differences: +// * XRPL_ASSERT must have an unique name (naming convention in CONTRIBUTING.md) +// * during fuzzing, the program will continue execution past failed XRPL_ASSERT // -// We continue to use regular C assert inside unit tests and inside constexpr +// We continue to use regular C `assert` inside unit tests and inside constexpr // functions. // // NOTE: UNREACHABLE does *not* have the same semantics as std::unreachable. // The program will continue execution past an UNREACHABLE in a Release build -// and during fuzzing (similar to ASSERT). +// and during fuzzing (similar to failed XRPL_ASSERT). // Also, the naming convention in UNREACHABLE is subtly different from other -// instrumentation macros - its name describes the condition which was *not* -// meant to happen, while name in other macros describe the condition that is +// instrumentation macros - its name describes the condition which was _not_ +// meant to happen, while name in other macros describes the condition that is // meant to happen (e.g. as in "assert that this happens"). #endif diff --git a/include/xrpl/beast/utility/rngfill.h b/include/xrpl/beast/utility/rngfill.h index 3be6aa307b3..93f11559cf8 100644 --- a/include/xrpl/beast/utility/rngfill.h +++ b/include/xrpl/beast/utility/rngfill.h @@ -42,7 +42,7 @@ rngfill(void* buffer, std::size_t bytes, Generator& g) bytes -= sizeof(v); } - ASSERT( + XRPL_ASSERT( bytes < sizeof(result_type), "beast::rngfill(void*) : maximum bytes"); #ifdef __GNUC__ diff --git a/include/xrpl/protocol/AmountConversions.h b/include/xrpl/protocol/AmountConversions.h index 24270a7b9ee..a65f7fcad8b 100644 --- a/include/xrpl/protocol/AmountConversions.h +++ b/include/xrpl/protocol/AmountConversions.h @@ -53,7 +53,7 @@ toSTAmount(XRPAmount const& xrp) inline STAmount toSTAmount(XRPAmount const& xrp, Issue const& iss) { - ASSERT( + XRPL_ASSERT( isXRP(iss.account) && isXRP(iss.currency), "ripple::toSTAmount : is XRP"); return toSTAmount(xrp); @@ -74,14 +74,14 @@ template <> inline IOUAmount toAmount(STAmount const& amt) { - ASSERT( + XRPL_ASSERT( amt.mantissa() < std::numeric_limits::max(), "ripple::toAmount : maximum mantissa"); bool const isNeg = amt.negative(); std::int64_t const sMant = isNeg ? -std::int64_t(amt.mantissa()) : amt.mantissa(); - ASSERT(!isXRP(amt), "ripple::toAmount : is not XRP"); + XRPL_ASSERT(!isXRP(amt), "ripple::toAmount : is not XRP"); return IOUAmount(sMant, amt.exponent()); } @@ -89,14 +89,14 @@ template <> inline XRPAmount toAmount(STAmount const& amt) { - ASSERT( + XRPL_ASSERT( amt.mantissa() < std::numeric_limits::max(), "ripple::toAmount : maximum mantissa"); bool const isNeg = amt.negative(); std::int64_t const sMant = isNeg ? -std::int64_t(amt.mantissa()) : amt.mantissa(); - ASSERT(isXRP(amt), "ripple::toAmount : is XRP"); + XRPL_ASSERT(isXRP(amt), "ripple::toAmount : is XRP"); return XRPAmount(sMant); } diff --git a/include/xrpl/protocol/Feature.h b/include/xrpl/protocol/Feature.h index 219230e69a1..18a9b9498aa 100644 --- a/include/xrpl/protocol/Feature.h +++ b/include/xrpl/protocol/Feature.h @@ -151,7 +151,7 @@ class FeatureBitset : private std::bitset explicit FeatureBitset(base const& b) : base(b) { - ASSERT( + XRPL_ASSERT( b.count() == count(), "ripple::FeatureBitset::FeatureBitset(base) : count match"); } @@ -160,7 +160,7 @@ class FeatureBitset : private std::bitset explicit FeatureBitset(uint256 const& f, Fs&&... fs) { initFromFeatures(f, std::forward(fs)...); - ASSERT( + XRPL_ASSERT( count() == (sizeof...(fs) + 1), "ripple::FeatureBitset::FeatureBitset(uint256) : count and " "sizeof... do match"); @@ -171,7 +171,7 @@ class FeatureBitset : private std::bitset { for (auto const& f : fs) set(featureToBitsetIndex(f)); - ASSERT( + XRPL_ASSERT( fs.size() == count(), "ripple::FeatureBitset::FeatureBitset(Container auto) : count and " "size do match"); diff --git a/include/xrpl/protocol/FeeUnits.h b/include/xrpl/protocol/FeeUnits.h index 0ef07b34ee1..640635c3fcb 100644 --- a/include/xrpl/protocol/FeeUnits.h +++ b/include/xrpl/protocol/FeeUnits.h @@ -426,12 +426,12 @@ mulDivU(Source1 value, Dest mul, Source2 div) { // split the asserts so if one hits, the user can tell which // without a debugger. - ASSERT( + XRPL_ASSERT( value.value() >= 0, "ripple::feeunit::mulDivU : minimum value input"); - ASSERT( + XRPL_ASSERT( mul.value() >= 0, "ripple::feeunit::mulDivU : minimum mul input"); - ASSERT( + XRPL_ASSERT( div.value() >= 0, "ripple::feeunit::mulDivU : minimum div input"); return std::nullopt; } diff --git a/include/xrpl/protocol/Indexes.h b/include/xrpl/protocol/Indexes.h index 6b5024a1f03..fe0be5d0cb0 100644 --- a/include/xrpl/protocol/Indexes.h +++ b/include/xrpl/protocol/Indexes.h @@ -220,7 +220,8 @@ page(uint256 const& root, std::uint64_t index = 0) noexcept; inline Keylet page(Keylet const& root, std::uint64_t index = 0) noexcept { - ASSERT(root.type == ltDIR_NODE, "ripple::keylet::page : valid root type"); + XRPL_ASSERT( + root.type == ltDIR_NODE, "ripple::keylet::page : valid root type"); return page(root.key, index); } /** @} */ diff --git a/include/xrpl/protocol/MultiApiJson.h b/include/xrpl/protocol/MultiApiJson.h index e1f65199617..03bab9b32ea 100644 --- a/include/xrpl/protocol/MultiApiJson.h +++ b/include/xrpl/protocol/MultiApiJson.h @@ -159,7 +159,7 @@ struct MultiApiJson -> std:: invoke_result_t { - ASSERT( + XRPL_ASSERT( valid(version) && index(version) >= 0 && index(version) < size, "ripple::detail::MultiApiJson::operator() : valid " "version"); @@ -179,7 +179,7 @@ struct MultiApiJson operator()(Json& json, Version version, Fn fn) const -> std::invoke_result_t { - ASSERT( + XRPL_ASSERT( valid(version) && index(version) >= 0 && index(version) < size, "ripple::detail::MultiApiJson::operator() : valid version"); return std::invoke(fn, json.val[index(version)]); diff --git a/include/xrpl/protocol/Quality.h b/include/xrpl/protocol/Quality.h index cc4feaa6118..6783fbf6dac 100644 --- a/include/xrpl/protocol/Quality.h +++ b/include/xrpl/protocol/Quality.h @@ -298,7 +298,7 @@ class Quality friend double relativeDistance(Quality const& q1, Quality const& q2) { - ASSERT( + XRPL_ASSERT( q1.m_value > 0 && q2.m_value > 0, "ripple::Quality::relativeDistance : minimum inputs"); diff --git a/include/xrpl/protocol/STAmount.h b/include/xrpl/protocol/STAmount.h index eb7ba6fbfba..a20f06ea307 100644 --- a/include/xrpl/protocol/STAmount.h +++ b/include/xrpl/protocol/STAmount.h @@ -355,7 +355,7 @@ STAmount::STAmount( , mIsNegative(negative) { // mValue is uint64, but needs to fit in the range of int64 - ASSERT( + XRPL_ASSERT( mValue <= std::numeric_limits::max(), "ripple::STAmount::STAmount(SField, A, std::uint64_t, int, bool) : " "maximum mantissa input"); diff --git a/include/xrpl/protocol/STBitString.h b/include/xrpl/protocol/STBitString.h index a80c3c2c253..bf4ce84a3f3 100644 --- a/include/xrpl/protocol/STBitString.h +++ b/include/xrpl/protocol/STBitString.h @@ -170,8 +170,9 @@ template void STBitString::add(Serializer& s) const { - ASSERT(getFName().isBinary(), "ripple::STBitString::add : field is binary"); - ASSERT( + XRPL_ASSERT( + getFName().isBinary(), "ripple::STBitString::add : field is binary"); + XRPL_ASSERT( getFName().fieldType == getSType(), "ripple::STBitString::add : field type match"); s.addBitString(value_); diff --git a/include/xrpl/protocol/STInteger.h b/include/xrpl/protocol/STInteger.h index 8dc6b7ff1a3..68e25be1c9f 100644 --- a/include/xrpl/protocol/STInteger.h +++ b/include/xrpl/protocol/STInteger.h @@ -110,8 +110,9 @@ template inline void STInteger::add(Serializer& s) const { - ASSERT(getFName().isBinary(), "ripple::STInteger::add : field is binary"); - ASSERT( + XRPL_ASSERT( + getFName().isBinary(), "ripple::STInteger::add : field is binary"); + XRPL_ASSERT( getFName().fieldType == getSType(), "ripple::STInteger::add : field type match"); s.addInteger(value_); diff --git a/include/xrpl/protocol/STObject.h b/include/xrpl/protocol/STObject.h index 63f421636e9..4c8db2e01e4 100644 --- a/include/xrpl/protocol/STObject.h +++ b/include/xrpl/protocol/STObject.h @@ -737,8 +737,7 @@ STObject::Proxy::assign(U&& u) t = dynamic_cast(st_->getPField(*f_, true)); else t = dynamic_cast(st_->makeFieldPresent(*f_)); - ASSERT( - t != nullptr, "ripple::STObject::Proxy::assign : type cast succeeded"); + XRPL_ASSERT(t, "ripple::STObject::Proxy::assign : type cast succeeded"); *t = std::forward(u); } @@ -1034,17 +1033,17 @@ STObject::at(TypedField const& f) const if (auto const u = dynamic_cast(b)) return u->value(); - ASSERT( - mType != nullptr, + XRPL_ASSERT( + mType, "ripple::STObject::at(TypedField auto) : field template non-null"); - ASSERT( + XRPL_ASSERT( b->getSType() == STI_NOTPRESENT, "ripple::STObject::at(TypedField auto) : type not present"); if (mType->style(f) == soeOPTIONAL) Throw("Missing optional field: " + f.getName()); - ASSERT( + XRPL_ASSERT( mType->style(f) == soeDEFAULT, "ripple::STObject::at(TypedField auto) : template style is default"); @@ -1064,16 +1063,16 @@ STObject::at(OptionaledField const& of) const auto const u = dynamic_cast(b); if (!u) { - ASSERT( - mType != nullptr, + XRPL_ASSERT( + mType, "ripple::STObject::at(OptionaledField auto) : field template " "non-null"); - ASSERT( + XRPL_ASSERT( b->getSType() == STI_NOTPRESENT, "ripple::STObject::at(OptionaledField auto) : type not present"); if (mType->style(*of.f) == soeOPTIONAL) return std::nullopt; - ASSERT( + XRPL_ASSERT( mType->style(*of.f) == soeDEFAULT, "ripple::STObject::at(OptionaledField auto) : template style is " "default"); diff --git a/include/xrpl/protocol/STPathSet.h b/include/xrpl/protocol/STPathSet.h index 754bb279238..953a209c150 100644 --- a/include/xrpl/protocol/STPathSet.h +++ b/include/xrpl/protocol/STPathSet.h @@ -257,7 +257,7 @@ inline STPathElement::STPathElement( is_offer_ = false; mAccountID = *account; mType |= typeAccount; - ASSERT( + XRPL_ASSERT( mAccountID != noAccount(), "ripple::STPathElement::STPathElement : account is set"); } @@ -272,7 +272,7 @@ inline STPathElement::STPathElement( { mIssuerID = *issuer; mType |= typeIssuer; - ASSERT( + XRPL_ASSERT( mIssuerID != noAccount(), "ripple::STPathElement::STPathElement : issuer is set"); } diff --git a/include/xrpl/protocol/STValidation.h b/include/xrpl/protocol/STValidation.h index adb8085a43e..32c60026fcd 100644 --- a/include/xrpl/protocol/STValidation.h +++ b/include/xrpl/protocol/STValidation.h @@ -176,7 +176,7 @@ STValidation::STValidation( Throw("Invalid signature in validation"); } - ASSERT( + XRPL_ASSERT( nodeID_.isNonZero(), "ripple::STValidation::STValidation(SerialIter) : nonzero node"); } @@ -201,7 +201,7 @@ STValidation::STValidation( , nodeID_(nodeID) , seenTime_(signTime) { - ASSERT( + XRPL_ASSERT( nodeID_.isNonZero(), "ripple::STValidation::STValidation(PublicKey, SecretKey) : nonzero " "node"); diff --git a/include/xrpl/protocol/Serializer.h b/include/xrpl/protocol/Serializer.h index e5e3907101d..80829c80003 100644 --- a/include/xrpl/protocol/Serializer.h +++ b/include/xrpl/protocol/Serializer.h @@ -55,8 +55,8 @@ class Serializer if (size) { - ASSERT( - data != nullptr, + XRPL_ASSERT( + data, "ripple::Serializer::Serializer(void const*) : non-null input"); std::memcpy(mData.data(), data, size); } @@ -333,7 +333,8 @@ Serializer::addVL(Iter begin, Iter end, int len) len -= begin->size(); #endif } - ASSERT(len == 0, "ripple::Serializer::addVL : length matches distance"); + XRPL_ASSERT( + len == 0, "ripple::Serializer::addVL : length matches distance"); return ret; } diff --git a/include/xrpl/protocol/TxMeta.h b/include/xrpl/protocol/TxMeta.h index 868efd854ff..44ec8ae93fd 100644 --- a/include/xrpl/protocol/TxMeta.h +++ b/include/xrpl/protocol/TxMeta.h @@ -116,7 +116,7 @@ class TxMeta STAmount getDeliveredAmount() const { - ASSERT( + XRPL_ASSERT( hasDeliveredAmount(), "ripple::TxMeta::getDeliveredAmount : non-null delivered amount"); return *mDelivered; diff --git a/include/xrpl/protocol/detail/b58_utils.h b/include/xrpl/protocol/detail/b58_utils.h index 76e470f54e7..8fc85f390b0 100644 --- a/include/xrpl/protocol/detail/b58_utils.h +++ b/include/xrpl/protocol/detail/b58_utils.h @@ -148,11 +148,11 @@ inplace_bigint_div_rem(std::span numerator, std::uint64_t divisor) unsigned __int128 const denom128 = denom; unsigned __int128 const d = num / denom128; unsigned __int128 const r = num - (denom128 * d); - ASSERT( + XRPL_ASSERT( d >> 64 == 0, "ripple::b58_fast::detail::inplace_bigint_div_rem::div_rem_64 : " "valid division result"); - ASSERT( + XRPL_ASSERT( r >> 64 == 0, "ripple::b58_fast::detail::inplace_bigint_div_rem::div_rem_64 : " "valid remainder"); @@ -179,7 +179,7 @@ b58_10_to_b58_be(std::uint64_t input) { [[maybe_unused]] static constexpr std::uint64_t B_58_10 = 430804206899405824; // 58^10; - ASSERT( + XRPL_ASSERT( input < B_58_10, "ripple::b58_fast::detail::b58_10_to_b58_be : valid input"); constexpr std::size_t resultSize = 10; diff --git a/include/xrpl/resource/detail/Logic.h b/include/xrpl/resource/detail/Logic.h index 6b7830c07cd..b6c776d1aff 100644 --- a/include/xrpl/resource/detail/Logic.h +++ b/include/xrpl/resource/detail/Logic.h @@ -401,7 +401,7 @@ class Logic { std::lock_guard _(lock_); Entry& entry(iter->second); - ASSERT( + XRPL_ASSERT( entry.refcount == 0, "ripple::Resource::Logic::erase : entry not used"); inactive_.erase(inactive_.iterator_to(entry)); diff --git a/include/xrpl/server/detail/BaseWSPeer.h b/include/xrpl/server/detail/BaseWSPeer.h index 8f3022bdf32..027b0cbf7ca 100644 --- a/include/xrpl/server/detail/BaseWSPeer.h +++ b/include/xrpl/server/detail/BaseWSPeer.h @@ -512,7 +512,7 @@ template void BaseWSPeer::fail(error_code ec, String const& what) { - ASSERT( + XRPL_ASSERT( strand_.running_in_this_thread(), "ripple::BaseWSPeer::fail : strand in this thread"); diff --git a/src/libxrpl/basics/Number.cpp b/src/libxrpl/basics/Number.cpp index 15db729e18d..3bc58970ef7 100644 --- a/src/libxrpl/basics/Number.cpp +++ b/src/libxrpl/basics/Number.cpp @@ -235,7 +235,7 @@ Number::operator+=(Number const& y) *this = Number{}; return *this; } - ASSERT( + XRPL_ASSERT( isnormal() && y.isnormal(), "ripple::Number::operator+=(Number) : is normal"); auto xm = mantissa(); @@ -376,7 +376,7 @@ Number::operator*=(Number const& y) *this = y; return *this; } - ASSERT( + XRPL_ASSERT( isnormal() && y.isnormal(), "ripple::Number::operator*=(Number) : is normal"); auto xm = mantissa(); @@ -432,7 +432,7 @@ Number::operator*=(Number const& y) std::to_string(xe)); mantissa_ = xm * zn; exponent_ = xe; - ASSERT( + XRPL_ASSERT( isnormal() || *this == Number{}, "ripple::Number::operator*=(Number) : result is normal"); return *this; @@ -532,7 +532,8 @@ to_string(Number const& amount) negative = true; } - ASSERT(exponent + 43 > 0, "ripple::to_string(Number) : minimum exponent"); + XRPL_ASSERT( + exponent + 43 > 0, "ripple::to_string(Number) : minimum exponent"); ptrdiff_t const pad_prefix = 27; ptrdiff_t const pad_suffix = 23; @@ -558,7 +559,7 @@ to_string(Number const& amount) if (std::distance(pre_from, pre_to) > pad_prefix) pre_from += pad_prefix; - ASSERT( + XRPL_ASSERT( post_to >= post_from, "ripple::to_string(Number) : first distance check"); @@ -569,7 +570,7 @@ to_string(Number const& amount) if (std::distance(post_from, post_to) > pad_suffix) post_to -= pad_suffix; - ASSERT( + XRPL_ASSERT( post_to >= post_from, "ripple::to_string(Number) : second distance check"); diff --git a/src/libxrpl/basics/ResolverAsio.cpp b/src/libxrpl/basics/ResolverAsio.cpp index efaaf80b5af..8951d809dec 100644 --- a/src/libxrpl/basics/ResolverAsio.cpp +++ b/src/libxrpl/basics/ResolverAsio.cpp @@ -48,7 +48,7 @@ class AsyncObject ~AsyncObject() { // Destroying the object with I/O pending? Not a clean exit! - ASSERT( + XRPL_ASSERT( m_pending.load() == 0, "ripple::AsyncObject::~AsyncObject : nothing pending"); } @@ -155,10 +155,10 @@ class ResolverAsioImpl : public ResolverAsio, ~ResolverAsioImpl() override { - ASSERT( + XRPL_ASSERT( m_work.empty(), "ripple::ResolverAsioImpl::~ResolverAsioImpl : no pending work"); - ASSERT( + XRPL_ASSERT( m_stopped, "ripple::ResolverAsioImpl::~ResolverAsioImpl : stopped"); } @@ -181,8 +181,9 @@ class ResolverAsioImpl : public ResolverAsio, void start() override { - ASSERT(m_stopped == true, "ripple::ResolverAsioImpl::start : stopped"); - ASSERT( + XRPL_ASSERT( + m_stopped == true, "ripple::ResolverAsioImpl::start : stopped"); + XRPL_ASSERT( m_stop_called == false, "ripple::ResolverAsioImpl::start : not stopping"); @@ -224,10 +225,10 @@ class ResolverAsioImpl : public ResolverAsio, resolve(std::vector const& names, HandlerType const& handler) override { - ASSERT( + XRPL_ASSERT( m_stop_called == false, "ripple::ResolverAsioImpl::resolve : not stopping"); - ASSERT( + XRPL_ASSERT( !names.empty(), "ripple::ResolverAsioImpl::resolve : names non-empty"); @@ -246,7 +247,7 @@ class ResolverAsioImpl : public ResolverAsio, void do_stop(CompletionCounter) { - ASSERT( + XRPL_ASSERT( m_stop_called == true, "ripple::ResolverAsioImpl::do_stop : stopping"); @@ -394,7 +395,7 @@ class ResolverAsioImpl : public ResolverAsio, HandlerType const& handler, CompletionCounter) { - ASSERT( + XRPL_ASSERT( !names.empty(), "ripple::ResolverAsioImpl::do_resolve : names non-empty"); diff --git a/src/libxrpl/beast/clock/basic_seconds_clock.cpp b/src/libxrpl/beast/clock/basic_seconds_clock.cpp index fa9a8725df5..1407b67de9a 100644 --- a/src/libxrpl/beast/clock/basic_seconds_clock.cpp +++ b/src/libxrpl/beast/clock/basic_seconds_clock.cpp @@ -57,7 +57,7 @@ static_assert(std::atomic::is_always_lock_free); seconds_clock_thread::~seconds_clock_thread() { - ASSERT( + XRPL_ASSERT( thread_.joinable(), "beast::seconds_clock_thread::~seconds_clock_thread : thread joinable"); { diff --git a/src/libxrpl/beast/core/SemanticVersion.cpp b/src/libxrpl/beast/core/SemanticVersion.cpp index e4a5aee486a..dfe699848d5 100644 --- a/src/libxrpl/beast/core/SemanticVersion.cpp +++ b/src/libxrpl/beast/core/SemanticVersion.cpp @@ -304,7 +304,7 @@ compare(SemanticVersion const& lhs, SemanticVersion const& rhs) if (isNumeric(left)) { - ASSERT( + XRPL_ASSERT( isNumeric(right), "beast::compare : both inputs numeric"); int const iLeft(lexicalCastThrow(left)); @@ -317,7 +317,7 @@ compare(SemanticVersion const& lhs, SemanticVersion const& rhs) } else { - ASSERT( + XRPL_ASSERT( !isNumeric(right), "beast::compare : both inputs non-numeric"); diff --git a/src/libxrpl/beast/insight/StatsDCollector.cpp b/src/libxrpl/beast/insight/StatsDCollector.cpp index 58322fc95ed..a9febbb3070 100644 --- a/src/libxrpl/beast/insight/StatsDCollector.cpp +++ b/src/libxrpl/beast/insight/StatsDCollector.cpp @@ -400,7 +400,7 @@ class StatsDCollectorImp for (auto const& s : *keepAlive) { std::size_t const length(s.size()); - ASSERT( + XRPL_ASSERT( !s.empty(), "beast::insight::detail::StatsDCollectorImp::send_buffers : " "non-empty payload"); diff --git a/src/libxrpl/beast/utility/src/beast_PropertyStream.cpp b/src/libxrpl/beast/utility/src/beast_PropertyStream.cpp index 46c17ea4644..3d68ea30cff 100644 --- a/src/libxrpl/beast/utility/src/beast_PropertyStream.cpp +++ b/src/libxrpl/beast/utility/src/beast_PropertyStream.cpp @@ -199,7 +199,7 @@ PropertyStream::Source::add(Source& source) std::lock_guard lk1(lock_, std::adopt_lock); std::lock_guard lk2(source.lock_, std::adopt_lock); - ASSERT( + XRPL_ASSERT( source.parent_ == nullptr, "beast::PropertyStream::Source::add : null source parent"); children_.push_back(source.item_); @@ -213,7 +213,7 @@ PropertyStream::Source::remove(Source& child) std::lock_guard lk1(lock_, std::adopt_lock); std::lock_guard lk2(child.lock_, std::adopt_lock); - ASSERT( + XRPL_ASSERT( child.parent_ == this, "beast::PropertyStream::Source::remove : child parent match"); children_.erase(children_.iterator_to(child.item_)); diff --git a/src/libxrpl/crypto/RFC1751.cpp b/src/libxrpl/crypto/RFC1751.cpp index 35363c862b5..952e246f5f8 100644 --- a/src/libxrpl/crypto/RFC1751.cpp +++ b/src/libxrpl/crypto/RFC1751.cpp @@ -270,10 +270,10 @@ RFC1751::extract(char const* s, int start, int length) unsigned char cr; unsigned long x; - ASSERT(length <= 11, "ripple::RFC1751::extract : maximum length"); - ASSERT(start >= 0, "ripple::RFC1751::extract : minimum start"); - ASSERT(length >= 0, "ripple::RFC1751::extract : minimum length"); - ASSERT( + XRPL_ASSERT(length <= 11, "ripple::RFC1751::extract : maximum length"); + XRPL_ASSERT(start >= 0, "ripple::RFC1751::extract : minimum start"); + XRPL_ASSERT(length >= 0, "ripple::RFC1751::extract : minimum length"); + XRPL_ASSERT( start + length <= 66, "ripple::RFC1751::extract : maximum start + length"); @@ -322,10 +322,10 @@ RFC1751::insert(char* s, int x, int start, int length) unsigned long y; int shift; - ASSERT(length <= 11, "ripple::RFC1751::insert : maximum length"); - ASSERT(start >= 0, "ripple::RFC1751::insert : minimum start"); - ASSERT(length >= 0, "ripple::RFC1751::insert : minimum length"); - ASSERT( + XRPL_ASSERT(length <= 11, "ripple::RFC1751::insert : maximum length"); + XRPL_ASSERT(start >= 0, "ripple::RFC1751::insert : minimum start"); + XRPL_ASSERT(length >= 0, "ripple::RFC1751::insert : minimum length"); + XRPL_ASSERT( start + length <= 66, "ripple::RFC1751::insert : maximum start + length"); diff --git a/src/libxrpl/json/Object.cpp b/src/libxrpl/json/Object.cpp index d38132b1f21..f1f30af9a21 100644 --- a/src/libxrpl/json/Object.cpp +++ b/src/libxrpl/json/Object.cpp @@ -214,7 +214,7 @@ template void doCopyFrom(Object& to, Json::Value const& from) { - ASSERT(from.isObjectOrNull(), "Json::doCopyFrom : valid input type"); + XRPL_ASSERT(from.isObjectOrNull(), "Json::doCopyFrom : valid input type"); auto members = from.getMemberNames(); for (auto& m : members) to[m] = from[m]; diff --git a/src/libxrpl/json/json_reader.cpp b/src/libxrpl/json/json_reader.cpp index 3e445ab5cc8..5f027e5189d 100644 --- a/src/libxrpl/json/json_reader.cpp +++ b/src/libxrpl/json/json_reader.cpp @@ -953,7 +953,7 @@ operator>>(std::istream& sin, Value& root) Json::Reader reader; bool ok = reader.parse(sin, root); - // ASSERT(ok, "Json::operator>>() : parse succeeded"); + // XRPL_ASSERT(ok, "Json::operator>>() : parse succeeded"); if (!ok) ripple::Throw(reader.getFormatedErrorMessages()); diff --git a/src/libxrpl/json/json_value.cpp b/src/libxrpl/json/json_value.cpp index a2034f471c4..90926afc6c4 100644 --- a/src/libxrpl/json/json_value.cpp +++ b/src/libxrpl/json/json_value.cpp @@ -461,7 +461,7 @@ operator==(const Value& x, const Value& y) const char* Value::asCString() const { - ASSERT(type_ == stringValue, "Json::Value::asCString : valid type"); + XRPL_ASSERT(type_ == stringValue, "Json::Value::asCString : valid type"); return value_.string_; } @@ -752,7 +752,7 @@ Value::operator bool() const void Value::clear() { - ASSERT( + XRPL_ASSERT( type_ == nullValue || type_ == arrayValue || type_ == objectValue, "Json::Value::clear : valid type"); @@ -771,7 +771,7 @@ Value::clear() Value& Value::operator[](UInt index) { - ASSERT( + XRPL_ASSERT( type_ == nullValue || type_ == arrayValue, "Json::Value::operator[](UInt) : valid type"); @@ -792,7 +792,7 @@ Value::operator[](UInt index) const Value& Value::operator[](UInt index) const { - ASSERT( + XRPL_ASSERT( type_ == nullValue || type_ == arrayValue, "Json::Value::operator[](UInt) const : valid type"); @@ -817,7 +817,7 @@ Value::operator[](const char* key) Value& Value::resolveReference(const char* key, bool isStatic) { - ASSERT( + XRPL_ASSERT( type_ == nullValue || type_ == objectValue, "Json::Value::resolveReference : valid type"); @@ -853,7 +853,7 @@ Value::isValidIndex(UInt index) const const Value& Value::operator[](const char* key) const { - ASSERT( + XRPL_ASSERT( type_ == nullValue || type_ == objectValue, "Json::Value::operator[](const char*) const : valid type"); @@ -915,7 +915,7 @@ Value::get(std::string const& key, const Value& defaultValue) const Value Value::removeMember(const char* key) { - ASSERT( + XRPL_ASSERT( type_ == nullValue || type_ == objectValue, "Json::Value::removeMember : valid type"); @@ -958,7 +958,7 @@ Value::isMember(std::string const& key) const Value::Members Value::getMemberNames() const { - ASSERT( + XRPL_ASSERT( type_ == nullValue || type_ == objectValue, "Json::Value::getMemberNames : valid type"); diff --git a/src/libxrpl/json/json_writer.cpp b/src/libxrpl/json/json_writer.cpp index 3ae0dacfc2b..de0ed5848af 100644 --- a/src/libxrpl/json/json_writer.cpp +++ b/src/libxrpl/json/json_writer.cpp @@ -70,7 +70,7 @@ valueToString(Int value) if (isNegative) *--current = '-'; - ASSERT(current >= buffer, "Json::valueToString(Int) : buffer check"); + XRPL_ASSERT(current >= buffer, "Json::valueToString(Int) : buffer check"); return current; } @@ -80,7 +80,7 @@ valueToString(UInt value) char buffer[32]; char* current = buffer + sizeof(buffer); uintToString(value, current); - ASSERT(current >= buffer, "Json::valueToString(UInt) : buffer check"); + XRPL_ASSERT(current >= buffer, "Json::valueToString(UInt) : buffer check"); return current; } @@ -391,7 +391,7 @@ StyledWriter::writeArrayValue(const Value& value) } else // output on a single line { - ASSERT( + XRPL_ASSERT( childValues_.size() == size, "Json::StyledWriter::writeArrayValue : child size match"); document_ += "[ "; @@ -485,7 +485,7 @@ StyledWriter::indent() void StyledWriter::unindent() { - ASSERT( + XRPL_ASSERT( int(indentString_.size()) >= indentSize_, "Json::StyledWriter::unindent : maximum indent size"); indentString_.resize(indentString_.size() - indentSize_); @@ -617,7 +617,7 @@ StyledStreamWriter::writeArrayValue(const Value& value) } else // output on a single line { - ASSERT( + XRPL_ASSERT( childValues_.size() == size, "Json::StyledStreamWriter::writeArrayValue : child size match"); *document_ << "[ "; @@ -712,7 +712,7 @@ StyledStreamWriter::indent() void StyledStreamWriter::unindent() { - ASSERT( + XRPL_ASSERT( indentString_.size() >= indentation_.size(), "Json::StyledStreamWriter::unindent : maximum indent size"); indentString_.resize(indentString_.size() - indentation_.size()); diff --git a/src/libxrpl/protocol/AMMCore.cpp b/src/libxrpl/protocol/AMMCore.cpp index 6661ab69a74..3bebfc4659a 100644 --- a/src/libxrpl/protocol/AMMCore.cpp +++ b/src/libxrpl/protocol/AMMCore.cpp @@ -109,7 +109,7 @@ ammAuctionTimeSlot(std::uint64_t current, STObject const& auctionSlot) // It should be impossible for expiration to be < TOTAL_TIME_SLOT_SECS, // but check just to be safe auto const expiration = auctionSlot[sfExpiration]; - ASSERT( + XRPL_ASSERT( expiration >= TOTAL_TIME_SLOT_SECS, "ripple::ammAuctionTimeSlot : minimum expiration"); if (expiration >= TOTAL_TIME_SLOT_SECS) diff --git a/src/libxrpl/protocol/AccountID.cpp b/src/libxrpl/protocol/AccountID.cpp index 8fe9ce115c4..f271882158b 100644 --- a/src/libxrpl/protocol/AccountID.cpp +++ b/src/libxrpl/protocol/AccountID.cpp @@ -77,7 +77,7 @@ class AccountIdCache auto ret = encodeBase58Token(TokenType::AccountID, id.data(), id.size()); - ASSERT( + XRPL_ASSERT( ret.size() <= 38, "ripple::detail::AccountIdCache : maximum result size"); diff --git a/src/libxrpl/protocol/ErrorCodes.cpp b/src/libxrpl/protocol/ErrorCodes.cpp index c9988eb589b..3482a65ee74 100644 --- a/src/libxrpl/protocol/ErrorCodes.cpp +++ b/src/libxrpl/protocol/ErrorCodes.cpp @@ -211,7 +211,7 @@ error_code_http_status(error_code_i code) std::string rpcErrorString(Json::Value const& jv) { - ASSERT( + XRPL_ASSERT( RPC::contains_error(jv), "ripple::RPC::rpcErrorString : input contains an error"); return jv[jss::error].asString() + jv[jss::error_message].asString(); diff --git a/src/libxrpl/protocol/Feature.cpp b/src/libxrpl/protocol/Feature.cpp index 47c495f9d62..05164489ec7 100644 --- a/src/libxrpl/protocol/Feature.cpp +++ b/src/libxrpl/protocol/Feature.cpp @@ -221,7 +221,7 @@ FeatureCollections::FeatureCollections() std::optional FeatureCollections::getRegisteredFeature(std::string const& name) const { - ASSERT( + XRPL_ASSERT( readOnly.load(), "ripple::FeatureCollections::getRegisteredFeature : startup completed"); Feature const* feature = getByName(name); @@ -305,7 +305,7 @@ FeatureCollections::registrationIsDone() size_t FeatureCollections::featureToBitsetIndex(uint256 const& f) const { - ASSERT( + XRPL_ASSERT( readOnly.load(), "ripple::FeatureCollections::featureToBitsetIndex : startup completed"); @@ -319,7 +319,7 @@ FeatureCollections::featureToBitsetIndex(uint256 const& f) const uint256 const& FeatureCollections::bitsetIndexToFeature(size_t i) const { - ASSERT( + XRPL_ASSERT( readOnly.load(), "ripple::FeatureCollections::bitsetIndexToFeature : startup completed"); Feature const& feature = getByIndex(i); @@ -329,7 +329,7 @@ FeatureCollections::bitsetIndexToFeature(size_t i) const std::string FeatureCollections::featureToName(uint256 const& f) const { - ASSERT( + XRPL_ASSERT( readOnly.load(), "ripple::FeatureCollections::featureToName : startup completed"); Feature const* feature = getByFeature(f); diff --git a/src/libxrpl/protocol/Indexes.cpp b/src/libxrpl/protocol/Indexes.cpp index 1519673ad4a..730610707f7 100644 --- a/src/libxrpl/protocol/Indexes.cpp +++ b/src/libxrpl/protocol/Indexes.cpp @@ -95,7 +95,8 @@ indexHash(LedgerNameSpace space, Args const&... args) uint256 getBookBase(Book const& book) { - ASSERT(isConsistent(book), "ripple::getBookBase : input is consistent"); + XRPL_ASSERT( + isConsistent(book), "ripple::getBookBase : input is consistent"); auto const index = indexHash( LedgerNameSpace::BOOK_DIR, @@ -135,7 +136,7 @@ getTicketIndex(AccountID const& account, std::uint32_t ticketSeq) uint256 getTicketIndex(AccountID const& account, SeqProxy ticketSeq) { - ASSERT(ticketSeq.isTicket(), "ripple::getTicketIndex : valid input"); + XRPL_ASSERT(ticketSeq.isTicket(), "ripple::getTicketIndex : valid input"); return getTicketIndex(account, ticketSeq.value()); } @@ -222,7 +223,8 @@ line( // There is code in SetTrust that calls us with id0 == id1, to allow users // to locate and delete such "weird" trustlines. If we remove that code, we // could enable this assert: - // ASSERT(id0 != id1, "ripple::keylet::line : accounts must be different"); + // XRPL_ASSERT(id0 != id1, "ripple::keylet::line : accounts must be + // different"); // A trust line is shared between two accounts; while we typically think // of this as an "issuer" and a "holder" the relationship is actually fully @@ -251,7 +253,8 @@ offer(AccountID const& id, std::uint32_t seq) noexcept Keylet quality(Keylet const& k, std::uint64_t q) noexcept { - ASSERT(k.type == ltDIR_NODE, "ripple::keylet::quality : valid input type"); + XRPL_ASSERT( + k.type == ltDIR_NODE, "ripple::keylet::quality : valid input type"); // Indexes are stored in big endian format: they print as hex as stored. // Most significant bytes are first and the least significant bytes @@ -269,7 +272,7 @@ quality(Keylet const& k, std::uint64_t q) noexcept Keylet next_t::operator()(Keylet const& k) const { - ASSERT( + XRPL_ASSERT( k.type == ltDIR_NODE, "ripple::keylet::next_t::operator() : valid input type"); return {ltDIR_NODE, getQualityNext(k.key)}; @@ -389,7 +392,7 @@ nftpage_max(AccountID const& owner) Keylet nftpage(Keylet const& k, uint256 const& token) { - ASSERT( + XRPL_ASSERT( k.type == ltNFTOKEN_PAGE, "ripple::keylet::nftpage : valid input type"); return {ltNFTOKEN_PAGE, (k.key & ~nft::pageMask) + (token & nft::pageMask)}; } diff --git a/src/libxrpl/protocol/Keylet.cpp b/src/libxrpl/protocol/Keylet.cpp index ab6b8ad0cf7..846c3bc07b3 100644 --- a/src/libxrpl/protocol/Keylet.cpp +++ b/src/libxrpl/protocol/Keylet.cpp @@ -25,7 +25,7 @@ namespace ripple { bool Keylet::check(STLedgerEntry const& sle) const { - ASSERT( + XRPL_ASSERT( sle.getType() != ltANY || sle.getType() != ltCHILD, "ripple::Keylet::check : valid input type"); diff --git a/src/libxrpl/protocol/Quality.cpp b/src/libxrpl/protocol/Quality.cpp index 005e824760e..ba669d9bd1f 100644 --- a/src/libxrpl/protocol/Quality.cpp +++ b/src/libxrpl/protocol/Quality.cpp @@ -35,7 +35,7 @@ Quality::Quality(Amounts const& amount) Quality& Quality::operator++() { - ASSERT(m_value > 0, "ripple::Quality::operator++() : minimum value"); + XRPL_ASSERT(m_value > 0, "ripple::Quality::operator++() : minimum value"); --m_value; return *this; } @@ -51,7 +51,7 @@ Quality::operator++(int) Quality& Quality::operator--() { - ASSERT( + XRPL_ASSERT( m_value < std::numeric_limits::max(), "ripple::Quality::operator--() : maximum value"); ++m_value; @@ -83,11 +83,12 @@ ceil_in_impl( // Clamp out if (result.out > amount.out) result.out = amount.out; - ASSERT( + XRPL_ASSERT( result.in == limit, "ripple::ceil_in_impl : result matches limit"); return result; } - ASSERT(amount.in <= limit, "ripple::ceil_in_impl : result inside limit"); + XRPL_ASSERT( + amount.in <= limit, "ripple::ceil_in_impl : result inside limit"); return amount; } @@ -123,12 +124,13 @@ ceil_out_impl( // Clamp in if (result.in > amount.in) result.in = amount.in; - ASSERT( + XRPL_ASSERT( result.out == limit, "ripple::ceil_out_impl : result matches limit"); return result; } - ASSERT(amount.out <= limit, "ripple::ceil_out_impl : result inside limit"); + XRPL_ASSERT( + amount.out <= limit, "ripple::ceil_out_impl : result inside limit"); return amount; } @@ -151,12 +153,12 @@ Quality composed_quality(Quality const& lhs, Quality const& rhs) { STAmount const lhs_rate(lhs.rate()); - ASSERT( + XRPL_ASSERT( lhs_rate != beast::zero, "ripple::composed_quality : nonzero left input"); STAmount const rhs_rate(rhs.rate()); - ASSERT( + XRPL_ASSERT( rhs_rate != beast::zero, "ripple::composed_quality : nonzero right input"); @@ -165,7 +167,7 @@ composed_quality(Quality const& lhs, Quality const& rhs) std::uint64_t const stored_exponent(rate.exponent() + 100); std::uint64_t const stored_mantissa(rate.mantissa()); - ASSERT( + XRPL_ASSERT( (stored_exponent > 0) && (stored_exponent <= 255), "ripple::composed_quality : valid exponent"); diff --git a/src/libxrpl/protocol/Rate2.cpp b/src/libxrpl/protocol/Rate2.cpp index 3e7d467e184..64ac6c46315 100644 --- a/src/libxrpl/protocol/Rate2.cpp +++ b/src/libxrpl/protocol/Rate2.cpp @@ -46,7 +46,7 @@ transferFeeAsRate(std::uint16_t fee) STAmount multiply(STAmount const& amount, Rate const& rate) { - ASSERT(rate.value != 0, "ripple::nft::multiply : nonzero rate input"); + XRPL_ASSERT(rate.value, "ripple::nft::multiply : nonzero rate input"); if (rate == parityRate) return amount; @@ -57,7 +57,7 @@ multiply(STAmount const& amount, Rate const& rate) STAmount multiplyRound(STAmount const& amount, Rate const& rate, bool roundUp) { - ASSERT(rate.value != 0, "ripple::nft::multiplyRound : nonzero rate input"); + XRPL_ASSERT(rate.value, "ripple::nft::multiplyRound : nonzero rate input"); if (rate == parityRate) return amount; @@ -72,9 +72,8 @@ multiplyRound( Asset const& asset, bool roundUp) { - ASSERT( - rate.value != 0, - "ripple::nft::multiplyRound(Issue) : nonzero rate input"); + XRPL_ASSERT( + rate.value, "ripple::nft::multiplyRound(Issue) : nonzero rate input"); if (rate == parityRate) { @@ -87,7 +86,7 @@ multiplyRound( STAmount divide(STAmount const& amount, Rate const& rate) { - ASSERT(rate.value != 0, "ripple::nft::divide : nonzero rate input"); + XRPL_ASSERT(rate.value, "ripple::nft::divide : nonzero rate input"); if (rate == parityRate) return amount; @@ -98,7 +97,7 @@ divide(STAmount const& amount, Rate const& rate) STAmount divideRound(STAmount const& amount, Rate const& rate, bool roundUp) { - ASSERT(rate.value != 0, "ripple::nft::divideRound : nonzero rate input"); + XRPL_ASSERT(rate.value, "ripple::nft::divideRound : nonzero rate input"); if (rate == parityRate) return amount; @@ -113,9 +112,8 @@ divideRound( Asset const& asset, bool roundUp) { - ASSERT( - rate.value != 0, - "ripple::nft::divideRound(Issue) : nonzero rate input"); + XRPL_ASSERT( + rate.value, "ripple::nft::divideRound(Issue) : nonzero rate input"); if (rate == parityRate) return amount; diff --git a/src/libxrpl/protocol/Rules.cpp b/src/libxrpl/protocol/Rules.cpp index 3edc1448d00..7043acff96d 100644 --- a/src/libxrpl/protocol/Rules.cpp +++ b/src/libxrpl/protocol/Rules.cpp @@ -91,7 +91,7 @@ class Rules::Impl return true; if (!digest_ || !other.digest_) return false; - ASSERT( + XRPL_ASSERT( presets_ == other.presets_, "ripple::Rules::Impl::operator==(Impl) const : input presets do " "match"); @@ -121,7 +121,7 @@ Rules::presets() const bool Rules::enabled(uint256 const& feature) const { - ASSERT(impl_ != nullptr, "ripple::Rules::enabled : initialized"); + XRPL_ASSERT(impl_, "ripple::Rules::enabled : initialized"); // The functionality of the "NonFungibleTokensV1_1" amendment is // precisely the functionality of the following three amendments @@ -140,7 +140,7 @@ Rules::enabled(uint256 const& feature) const bool Rules::operator==(Rules const& other) const { - ASSERT( + XRPL_ASSERT( impl_ && other.impl_, "ripple::Rules::operator==(Rules) const : both initialized"); if (impl_.get() == other.impl_.get()) diff --git a/src/libxrpl/protocol/STAccount.cpp b/src/libxrpl/protocol/STAccount.cpp index d3d93f75601..c033e4cb580 100644 --- a/src/libxrpl/protocol/STAccount.cpp +++ b/src/libxrpl/protocol/STAccount.cpp @@ -80,8 +80,9 @@ STAccount::getSType() const void STAccount::add(Serializer& s) const { - ASSERT(getFName().isBinary(), "ripple::STAccount::add : field is binary"); - ASSERT( + XRPL_ASSERT( + getFName().isBinary(), "ripple::STAccount::add : field is binary"); + XRPL_ASSERT( getFName().fieldType == STI_ACCOUNT, "ripple::STAccount::add : valid field type"); diff --git a/src/libxrpl/protocol/STAmount.cpp b/src/libxrpl/protocol/STAmount.cpp index c33b2b40aa3..37830830ade 100644 --- a/src/libxrpl/protocol/STAmount.cpp +++ b/src/libxrpl/protocol/STAmount.cpp @@ -68,11 +68,12 @@ getInt64Value(STAmount const& amount, bool valid, const char* error) { if (!valid) Throw(error); - ASSERT(amount.exponent() == 0, "ripple::getInt64Value : exponent is zero"); + XRPL_ASSERT( + amount.exponent() == 0, "ripple::getInt64Value : exponent is zero"); auto ret = static_cast(amount.mantissa()); - ASSERT( + XRPL_ASSERT( static_cast(ret) == amount.mantissa(), "ripple::getInt64Value : mantissa must roundtrip"); @@ -201,7 +202,7 @@ STAmount::STAmount(SField const& name, std::uint64_t mantissa, bool negative) , mOffset(0) , mIsNegative(negative) { - ASSERT( + XRPL_ASSERT( mValue <= std::numeric_limits::max(), "ripple::STAmount::STAmount(SField, std::uint64_t, bool) : maximum " "mantissa input"); @@ -214,7 +215,7 @@ STAmount::STAmount(SField const& name, STAmount const& from) , mOffset(from.mOffset) , mIsNegative(from.mIsNegative) { - ASSERT( + XRPL_ASSERT( mValue <= std::numeric_limits::max(), "ripple::STAmount::STAmount(SField, STAmount) : maximum input"); canonicalize(); @@ -228,7 +229,7 @@ STAmount::STAmount(std::uint64_t mantissa, bool negative) , mOffset(0) , mIsNegative(mantissa != 0 && negative) { - ASSERT( + XRPL_ASSERT( mValue <= std::numeric_limits::max(), "ripple::STAmount::STAmount(std::uint64_t, bool) : maximum mantissa " "input"); @@ -315,7 +316,7 @@ STAmount::mpt() const STAmount& STAmount::operator=(IOUAmount const& iou) { - ASSERT( + XRPL_ASSERT( native() == false, "ripple::STAmount::operator=(IOUAmount) : is not XRP"); mOffset = iou.exponent(); @@ -456,7 +457,7 @@ getRate(STAmount const& offerOut, STAmount const& offerIn) STAmount r = divide(offerIn, offerOut, noIssue()); if (r == beast::zero) // offer is too good return 0; - ASSERT( + XRPL_ASSERT( (r.exponent() >= -100) && (r.exponent() <= 155), "ripple::getRate : exponent inside range"); std::uint64_t ret = r.exponent() + 100; @@ -539,7 +540,7 @@ STAmount::getText() const return ret; } - ASSERT(mOffset + 43 > 0, "ripple::STAmount::getText : minimum offset"); + XRPL_ASSERT(mOffset + 43 > 0, "ripple::STAmount::getText : minimum offset"); size_t const pad_prefix = 27; size_t const pad_suffix = 23; @@ -563,7 +564,7 @@ STAmount::getText() const if (std::distance(pre_from, pre_to) > pad_prefix) pre_from += pad_prefix; - ASSERT( + XRPL_ASSERT( post_to >= post_from, "ripple::STAmount::getText : first distance check"); @@ -574,7 +575,7 @@ STAmount::getText() const if (std::distance(post_from, post_to) > pad_suffix) post_to -= pad_suffix; - ASSERT( + XRPL_ASSERT( post_to >= post_from, "ripple::STAmount::getText : second distance check"); @@ -612,7 +613,7 @@ STAmount::add(Serializer& s) const { if (native()) { - ASSERT(mOffset == 0, "ripple::STAmount::add : zero offset"); + XRPL_ASSERT(mOffset == 0, "ripple::STAmount::add : zero offset"); if (!mIsNegative) s.add64(mValue | cPositive); @@ -789,13 +790,13 @@ STAmount::canonicalize() if (mOffset > cMaxOffset) Throw("value overflow"); - ASSERT( + XRPL_ASSERT( (mValue == 0) || ((mValue >= cMinValue) && (mValue <= cMaxValue)), "ripple::STAmount::canonicalize : value inside range"); - ASSERT( + XRPL_ASSERT( (mValue == 0) || ((mOffset >= cMinOffset) && (mOffset <= cMaxOffset)), "ripple::STAmount::canonicalize : offset inside range"); - ASSERT( + XRPL_ASSERT( (mValue != 0) || (mOffset != -100), "ripple::STAmount::canonicalize : value or offset set"); } diff --git a/src/libxrpl/protocol/STBase.cpp b/src/libxrpl/protocol/STBase.cpp index d93068bb053..6986957b61e 100644 --- a/src/libxrpl/protocol/STBase.cpp +++ b/src/libxrpl/protocol/STBase.cpp @@ -29,7 +29,7 @@ STBase::STBase() : fName(&sfGeneric) STBase::STBase(SField const& n) : fName(&n) { - ASSERT(fName != nullptr, "ripple::STBase::STBase : field is set"); + XRPL_ASSERT(fName, "ripple::STBase::STBase : field is set"); } STBase& @@ -111,7 +111,7 @@ STBase::add(Serializer& s) const bool STBase::isEquivalent(const STBase& t) const { - ASSERT( + XRPL_ASSERT( getSType() == STI_NOTPRESENT, "ripple::STBase::isEquivalent : type not present"); return t.getSType() == STI_NOTPRESENT; @@ -127,7 +127,7 @@ void STBase::setFName(SField const& n) { fName = &n; - ASSERT(fName != nullptr, "ripple::STBase::setFName : field is set"); + XRPL_ASSERT(fName, "ripple::STBase::setFName : field is set"); } SField const& @@ -139,7 +139,8 @@ STBase::getFName() const void STBase::addFieldID(Serializer& s) const { - ASSERT(fName->isBinary(), "ripple::STBase::addFieldID : field is binary"); + XRPL_ASSERT( + fName->isBinary(), "ripple::STBase::addFieldID : field is binary"); s.addFieldID(fName->fieldType, fName->fieldValue); } diff --git a/src/libxrpl/protocol/STBlob.cpp b/src/libxrpl/protocol/STBlob.cpp index 755588138a2..34e759b4c37 100644 --- a/src/libxrpl/protocol/STBlob.cpp +++ b/src/libxrpl/protocol/STBlob.cpp @@ -54,8 +54,8 @@ STBlob::getText() const void STBlob::add(Serializer& s) const { - ASSERT(getFName().isBinary(), "ripple::STBlob::add : field is binary"); - ASSERT( + XRPL_ASSERT(getFName().isBinary(), "ripple::STBlob::add : field is binary"); + XRPL_ASSERT( (getFName().fieldType == STI_VL) || (getFName().fieldType == STI_ACCOUNT), "ripple::STBlob::add : valid field type"); diff --git a/src/libxrpl/protocol/STInteger.cpp b/src/libxrpl/protocol/STInteger.cpp index 5e8fc47d9da..9525a47c462 100644 --- a/src/libxrpl/protocol/STInteger.cpp +++ b/src/libxrpl/protocol/STInteger.cpp @@ -199,14 +199,14 @@ Json::Value STUInt64::getJson(JsonOptions) const { auto convertToString = [](uint64_t const value, int const base) { - ASSERT( + XRPL_ASSERT( base == 10 || base == 16, "ripple::STUInt64::getJson : base 10 or 16"); std::string str( base == 10 ? 20 : 16, 0); // Allocate space depending on base auto ret = std::to_chars(str.data(), str.data() + str.size(), value, base); - ASSERT( + XRPL_ASSERT( ret.ec == std::errc(), "ripple::STUInt64::getJson : to_chars succeeded"); str.resize(std::distance(str.data(), ret.ptr)); diff --git a/src/libxrpl/protocol/STLedgerEntry.cpp b/src/libxrpl/protocol/STLedgerEntry.cpp index b7579a04ca8..0350dd883b8 100644 --- a/src/libxrpl/protocol/STLedgerEntry.cpp +++ b/src/libxrpl/protocol/STLedgerEntry.cpp @@ -161,7 +161,7 @@ STLedgerEntry::thread( if (oldPrevTxID == txID) { // this transaction is already threaded - ASSERT( + XRPL_ASSERT( getFieldU32(sfPreviousTxnLgrSeq) == ledgerSeq, "ripple::STLedgerEntry::thread : ledger sequence match"); return false; diff --git a/src/libxrpl/protocol/STNumber.cpp b/src/libxrpl/protocol/STNumber.cpp index 74bda0046cf..74961bfbcab 100644 --- a/src/libxrpl/protocol/STNumber.cpp +++ b/src/libxrpl/protocol/STNumber.cpp @@ -53,8 +53,9 @@ STNumber::getText() const void STNumber::add(Serializer& s) const { - ASSERT(getFName().isBinary(), "ripple::STNumber::add : field is binary"); - ASSERT( + XRPL_ASSERT( + getFName().isBinary(), "ripple::STNumber::add : field is binary"); + XRPL_ASSERT( getFName().fieldType == getSType(), "ripple::STNumber::add : field type match"); s.add64(value_.mantissa()); @@ -88,7 +89,7 @@ STNumber::move(std::size_t n, void* buf) bool STNumber::isEquivalent(STBase const& t) const { - ASSERT( + XRPL_ASSERT( t.getSType() == this->getSType(), "ripple::STNumber::isEquivalent : field type match"); STNumber const& v = dynamic_cast(t); diff --git a/src/libxrpl/protocol/STObject.cpp b/src/libxrpl/protocol/STObject.cpp index 520dc53b0de..821f8f05c96 100644 --- a/src/libxrpl/protocol/STObject.cpp +++ b/src/libxrpl/protocol/STObject.cpp @@ -862,7 +862,7 @@ STObject::add(Serializer& s, WhichFields whichFields) const // the type associated by rule with this field name // must be OBJECT, or the object cannot be deserialized SerializedTypeID const sType{field->getSType()}; - ASSERT( + XRPL_ASSERT( (sType != STI_OBJECT) || (field->getFName().fieldType == STI_OBJECT), "ripple::STObject::add : valid field type"); diff --git a/src/libxrpl/protocol/STPathSet.cpp b/src/libxrpl/protocol/STPathSet.cpp index 3409299d7cb..57bcaca6b2c 100644 --- a/src/libxrpl/protocol/STPathSet.cpp +++ b/src/libxrpl/protocol/STPathSet.cpp @@ -209,8 +209,9 @@ STPathSet::getSType() const void STPathSet::add(Serializer& s) const { - ASSERT(getFName().isBinary(), "ripple::STPathSet::add : field is binary"); - ASSERT( + XRPL_ASSERT( + getFName().isBinary(), "ripple::STPathSet::add : field is binary"); + XRPL_ASSERT( getFName().fieldType == STI_PATHSET, "ripple::STPathSet::add : valid field type"); bool first = true; diff --git a/src/libxrpl/protocol/STTx.cpp b/src/libxrpl/protocol/STTx.cpp index b530271080d..7c862578ba3 100644 --- a/src/libxrpl/protocol/STTx.cpp +++ b/src/libxrpl/protocol/STTx.cpp @@ -137,7 +137,7 @@ STTx::getMentionedAccounts() const { if (auto sacc = dynamic_cast(&it)) { - ASSERT( + XRPL_ASSERT( !sacc->isDefault(), "ripple::STTx::getMentionedAccounts : account is set"); if (!sacc->isDefault()) @@ -300,8 +300,7 @@ STTx::getMetaSQL( std::string rTxn = sqlBlobLiteral(rawTxn.peekData()); auto format = TxFormats::getInstance().findByType(tx_type_); - ASSERT( - format != nullptr, "ripple::STTx::getMetaSQL : non-null type format"); + XRPL_ASSERT(format, "ripple::STTx::getMetaSQL : non-null type format"); return str( boost::format(bfTrans) % to_string(getTransactionID()) % diff --git a/src/libxrpl/protocol/STValidation.cpp b/src/libxrpl/protocol/STValidation.cpp index 5820fc9f9b0..16f0c288796 100644 --- a/src/libxrpl/protocol/STValidation.cpp +++ b/src/libxrpl/protocol/STValidation.cpp @@ -107,7 +107,7 @@ STValidation::isValid() const noexcept { if (!valid_) { - ASSERT( + XRPL_ASSERT( publicKeyType(getSignerPublic()) == KeyType::secp256k1, "ripple::STValidation::isValid : valid key type"); diff --git a/src/libxrpl/protocol/STVar.cpp b/src/libxrpl/protocol/STVar.cpp index 4c9217328f6..c5d3102bfa7 100644 --- a/src/libxrpl/protocol/STVar.cpp +++ b/src/libxrpl/protocol/STVar.cpp @@ -121,7 +121,7 @@ STVar::STVar(SerialIter& sit, SField const& name, int depth) STVar::STVar(SerializedTypeID id, SField const& name) { - ASSERT( + XRPL_ASSERT( (id == STI_NOTPRESENT) || (id == name.fieldType), "ripple::detail::STVar::STVar(SerializedTypeID) : valid type input"); constructST(id, 0, name); diff --git a/src/libxrpl/protocol/STVector256.cpp b/src/libxrpl/protocol/STVector256.cpp index e9ea1e862de..6f70a3849c1 100644 --- a/src/libxrpl/protocol/STVector256.cpp +++ b/src/libxrpl/protocol/STVector256.cpp @@ -68,8 +68,9 @@ STVector256::isDefault() const void STVector256::add(Serializer& s) const { - ASSERT(getFName().isBinary(), "ripple::STVector256::add : field is binary"); - ASSERT( + XRPL_ASSERT( + getFName().isBinary(), "ripple::STVector256::add : field is binary"); + XRPL_ASSERT( getFName().fieldType == STI_VECTOR256, "ripple::STVector256::add : valid field type"); s.addVL(mValue.begin(), mValue.end(), mValue.size() * (256 / 8)); diff --git a/src/libxrpl/protocol/Serializer.cpp b/src/libxrpl/protocol/Serializer.cpp index 51fb94054e3..f46104f6382 100644 --- a/src/libxrpl/protocol/Serializer.cpp +++ b/src/libxrpl/protocol/Serializer.cpp @@ -107,7 +107,7 @@ int Serializer::addFieldID(int type, int name) { int ret = mData.size(); - ASSERT( + XRPL_ASSERT( (type > 0) && (type < 256) && (name > 0) && (name < 256), "ripple::Serializer::addFieldID : inputs inside range"); @@ -178,7 +178,7 @@ Serializer::addVL(Blob const& vector) { int ret = addEncoded(vector.size()); addRaw(vector); - ASSERT( + XRPL_ASSERT( mData.size() == (ret + vector.size() + encodeLengthLength(vector.size())), "ripple::Serializer::addVL : size matches expected"); @@ -485,7 +485,7 @@ SerialIter::getVLDataLength() } else { - ASSERT( + XRPL_ASSERT( lenLen == 3, "ripple::SerialIter::getVLDataLength : lenLen is 3"); int b2 = get8(); int b3 = get8(); diff --git a/src/libxrpl/protocol/TxMeta.cpp b/src/libxrpl/protocol/TxMeta.cpp index ea3e43240ba..dad67c13349 100644 --- a/src/libxrpl/protocol/TxMeta.cpp +++ b/src/libxrpl/protocol/TxMeta.cpp @@ -55,8 +55,8 @@ TxMeta::TxMeta(uint256 const& txid, std::uint32_t ledger, STObject const& obj) auto affectedNodes = dynamic_cast(obj.peekAtPField(sfAffectedNodes)); - ASSERT( - affectedNodes != nullptr, + XRPL_ASSERT( + affectedNodes, "ripple::TxMeta::TxMeta(STObject) : type cast succeeded"); if (affectedNodes) mNodes = *affectedNodes; @@ -108,7 +108,7 @@ TxMeta::setAffectedNode( mNodes.push_back(STObject(type)); STObject& obj = mNodes.back(); - ASSERT( + XRPL_ASSERT( obj.getFName() == type, "ripple::TxMeta::setAffectedNode : field type match"); obj.setFieldH256(sfLedgerIndex, node); @@ -131,8 +131,8 @@ TxMeta::getAffectedAccounts() const if (index != -1) { auto inner = dynamic_cast(&it.peekAtIndex(index)); - ASSERT( - inner != nullptr, + XRPL_ASSERT( + inner, "ripple::getAffectedAccounts : STObject type cast succeeded"); if (inner) { @@ -140,7 +140,7 @@ TxMeta::getAffectedAccounts() const { if (auto sa = dynamic_cast(&field)) { - ASSERT( + XRPL_ASSERT( !sa->isDefault(), "ripple::getAffectedAccounts : account is set"); if (!sa->isDefault()) @@ -153,8 +153,8 @@ TxMeta::getAffectedAccounts() const (field.getFName() == sfTakerGets)) { auto lim = dynamic_cast(&field); - ASSERT( - lim != nullptr, + XRPL_ASSERT( + lim, "ripple::getAffectedAccounts : STAmount type cast " "succeeded"); @@ -186,7 +186,7 @@ TxMeta::getAffectedNode(SLE::ref node, SField const& type) mNodes.push_back(STObject(type)); STObject& obj = mNodes.back(); - ASSERT( + XRPL_ASSERT( obj.getFName() == type, "ripple::TxMeta::getAffectedNode(SLE::ref) : field type match"); obj.setFieldH256(sfLedgerIndex, index); @@ -212,7 +212,7 @@ STObject TxMeta::getAsObject() const { STObject metaData(sfTransactionMetaData); - ASSERT(mResult != 255, "ripple::TxMeta::getAsObject : result is set"); + XRPL_ASSERT(mResult != 255, "ripple::TxMeta::getAsObject : result is set"); metaData.setFieldU8(sfTransactionResult, mResult); metaData.setFieldU32(sfTransactionIndex, mIndex); metaData.emplace_back(mNodes); @@ -226,7 +226,7 @@ TxMeta::addRaw(Serializer& s, TER result, std::uint32_t index) { mResult = TERtoInt(result); mIndex = index; - ASSERT( + XRPL_ASSERT( (mResult == 0) || ((mResult > 100) && (mResult <= 255)), "ripple::TxMeta::addRaw : valid TER input"); diff --git a/src/libxrpl/protocol/tokens.cpp b/src/libxrpl/protocol/tokens.cpp index de3812637cf..49ec926a775 100644 --- a/src/libxrpl/protocol/tokens.cpp +++ b/src/libxrpl/protocol/tokens.cpp @@ -248,7 +248,7 @@ encodeBase58( iter[-1] = carry % 58; carry /= 58; } - ASSERT( + XRPL_ASSERT( carry == 0, "ripple::b58_ref::detail::encodeBase58 : zero carry"); pbegin++; } @@ -299,7 +299,7 @@ decodeBase58(std::string const& s) *iter = carry % 256; carry /= 256; } - ASSERT( + XRPL_ASSERT( carry == 0, "ripple::b58_ref::detail::decodeBase58 : zero carry"); ++psz; --remain; @@ -537,7 +537,7 @@ b58_to_b256_be(std::string_view input, std::span out) ripple::b58_fast::detail::div_rem(input.size(), 10); auto const num_partial_coeffs = partial_coeff_len ? 1 : 0; auto const num_b_58_10_coeffs = num_full_coeffs + num_partial_coeffs; - ASSERT( + XRPL_ASSERT( num_b_58_10_coeffs <= b_58_10_coeff.size(), "ripple::b58_fast::detail::b58_to_b256_be : maximum coeff"); for (auto c : input.substr(0, partial_coeff_len)) diff --git a/src/libxrpl/resource/Consumer.cpp b/src/libxrpl/resource/Consumer.cpp index adabd770964..618b4f5e614 100644 --- a/src/libxrpl/resource/Consumer.cpp +++ b/src/libxrpl/resource/Consumer.cpp @@ -109,18 +109,15 @@ Consumer::charge(Charge const& what) bool Consumer::warn() { - ASSERT( - m_entry != nullptr, - "ripple::Resource::Consumer::warn : non-null entry"); + XRPL_ASSERT(m_entry, "ripple::Resource::Consumer::warn : non-null entry"); return m_logic->warn(*m_entry); } bool Consumer::disconnect(beast::Journal const& j) { - ASSERT( - m_entry != nullptr, - "ripple::Resource::Consumer::disconnect : non-null entry"); + XRPL_ASSERT( + m_entry, "ripple::Resource::Consumer::disconnect : non-null entry"); bool const d = m_logic->disconnect(*m_entry); if (d) { @@ -132,18 +129,15 @@ Consumer::disconnect(beast::Journal const& j) int Consumer::balance() { - ASSERT( - m_entry != nullptr, - "ripple::Resource::Consumer::balance : non-null entry"); + XRPL_ASSERT( + m_entry, "ripple::Resource::Consumer::balance : non-null entry"); return m_logic->balance(*m_entry); } Entry& Consumer::entry() { - ASSERT( - m_entry != nullptr, - "ripple::Resource::Consumer::entry : non-null entry"); + XRPL_ASSERT(m_entry, "ripple::Resource::Consumer::entry : non-null entry"); return *m_entry; } diff --git a/src/xrpld/app/consensus/RCLConsensus.cpp b/src/xrpld/app/consensus/RCLConsensus.cpp index 0be77c7de79..a746b30357d 100644 --- a/src/xrpld/app/consensus/RCLConsensus.cpp +++ b/src/xrpld/app/consensus/RCLConsensus.cpp @@ -93,9 +93,8 @@ RCLConsensus::Adaptor::Adaptor( std::numeric_limits::max() - 1)) , nUnlVote_(validatorKeys_.nodeID, j_) { - ASSERT( - valCookie_ != 0, - "ripple::RCLConsensus::Adaptor::Adaptor : nonzero cookie"); + XRPL_ASSERT( + valCookie_, "ripple::RCLConsensus::Adaptor::Adaptor : nonzero cookie"); JLOG(j_.info()) << "Consensus engine started (cookie: " + std::to_string(valCookie_) + ")"; @@ -149,10 +148,10 @@ RCLConsensus::Adaptor::acquireLedger(LedgerHash const& hash) return std::nullopt; } - ASSERT( + XRPL_ASSERT( !built->open() && built->isImmutable(), "ripple::RCLConsensus::Adaptor::acquireLedger : valid ledger state"); - ASSERT( + XRPL_ASSERT( built->info().hash == hash, "ripple::RCLConsensus::Adaptor::acquireLedger : ledger hash match"); @@ -680,10 +679,10 @@ RCLConsensus::Adaptor::doAccept( ledgerMaster_.switchLCL(built.ledger_); // Do these need to exist? - ASSERT( + XRPL_ASSERT( ledgerMaster_.getClosedLedger()->info().hash == built.id(), "ripple::RCLConsensus::Adaptor::doAccept : ledger hash match"); - ASSERT( + XRPL_ASSERT( app_.openLedger().current()->info().parentHash == built.id(), "ripple::RCLConsensus::Adaptor::doAccept : parent hash match"); } @@ -781,7 +780,7 @@ RCLConsensus::Adaptor::buildLCL( std::shared_ptr built = [&]() { if (auto const replayData = ledgerMaster_.releaseReplay()) { - ASSERT( + XRPL_ASSERT( replayData->parent()->info().hash == previousLedger.id(), "ripple::RCLConsensus::Adaptor::buildLCL : parent hash match"); return buildLedger(*replayData, tapNONE, app_, j_); diff --git a/src/xrpld/app/consensus/RCLCxPeerPos.cpp b/src/xrpld/app/consensus/RCLCxPeerPos.cpp index 14a60a84182..37f61a8c2d5 100644 --- a/src/xrpld/app/consensus/RCLCxPeerPos.cpp +++ b/src/xrpld/app/consensus/RCLCxPeerPos.cpp @@ -38,7 +38,7 @@ RCLCxPeerPos::RCLCxPeerPos( { // The maximum allowed size of a signature is 72 bytes; we verify // this elsewhere, but we want to be extra careful here: - ASSERT( + XRPL_ASSERT( signature.size() != 0 && signature.size() <= signature_.capacity(), "ripple::RCLCxPeerPos::RCLCxPeerPos : valid signature size"); diff --git a/src/xrpld/app/consensus/RCLCxTx.h b/src/xrpld/app/consensus/RCLCxTx.h index 0181eb03c21..bbf3797887c 100644 --- a/src/xrpld/app/consensus/RCLCxTx.h +++ b/src/xrpld/app/consensus/RCLCxTx.h @@ -111,9 +111,8 @@ class RCLTxSet */ RCLTxSet(std::shared_ptr m) : map_{std::move(m)} { - ASSERT( - map_ != nullptr, - "ripple::RCLTxSet::MutableTxSet::RCLTxSet : non-null input"); + XRPL_ASSERT( + map_, "ripple::RCLTxSet::MutableTxSet::RCLTxSet : non-null input"); } /** Constructor from a previously created MutableTxSet @@ -179,7 +178,7 @@ class RCLTxSet std::map ret; for (auto const& [k, v] : delta) { - ASSERT( + XRPL_ASSERT( (v.first && !v.second) || (v.second && !v.first), "ripple::RCLTxSet::compare : either side is set"); diff --git a/src/xrpld/app/consensus/RCLValidations.cpp b/src/xrpld/app/consensus/RCLValidations.cpp index e620cd3de90..c4d9389e896 100644 --- a/src/xrpld/app/consensus/RCLValidations.cpp +++ b/src/xrpld/app/consensus/RCLValidations.cpp @@ -50,7 +50,7 @@ RCLValidatedLedger::RCLValidatedLedger( auto const hashIndex = ledger->read(keylet::skip()); if (hashIndex) { - ASSERT( + XRPL_ASSERT( hashIndex->getFieldU32(sfLastLedgerSequence) == (seq() - 1), "ripple::RCLValidatedLedger::RCLValidatedLedger(Ledger) : valid " "last ledger sequence"); @@ -154,10 +154,10 @@ RCLValidationsAdaptor::acquire(LedgerHash const& hash) return std::nullopt; } - ASSERT( + XRPL_ASSERT( !ledger->open() && ledger->isImmutable(), "ripple::RCLValidationsAdaptor::acquire : valid ledger state"); - ASSERT( + XRPL_ASSERT( ledger->info().hash == hash, "ripple::RCLValidationsAdaptor::acquire : ledger hash match"); @@ -198,9 +198,8 @@ handleNewValidation( { if (bypassAccept == BypassAccept::yes) { - ASSERT( - j.has_value(), - "ripple::handleNewValidation : journal is available"); + XRPL_ASSERT( + j, "ripple::handleNewValidation : journal is available"); if (j.has_value()) { JLOG(j->trace()) << "Bypassing checkAccept for validation " diff --git a/src/xrpld/app/ledger/AcceptedLedgerTx.cpp b/src/xrpld/app/ledger/AcceptedLedgerTx.cpp index 620ab031762..6bdb602fd83 100644 --- a/src/xrpld/app/ledger/AcceptedLedgerTx.cpp +++ b/src/xrpld/app/ledger/AcceptedLedgerTx.cpp @@ -33,7 +33,7 @@ AcceptedLedgerTx::AcceptedLedgerTx( , mMeta(txn->getTransactionID(), ledger->seq(), *met) , mAffected(mMeta.getAffectedAccounts()) { - ASSERT( + XRPL_ASSERT( !ledger->open(), "ripple::AcceptedLedgerTx::AcceptedLedgerTx : valid ledger state"); @@ -78,7 +78,7 @@ AcceptedLedgerTx::AcceptedLedgerTx( std::string AcceptedLedgerTx::getEscMeta() const { - ASSERT( + XRPL_ASSERT( !mRawMeta.empty(), "ripple::AcceptedLedgerTx::getEscMeta : metadata is set"); return sqlBlobLiteral(mRawMeta); diff --git a/src/xrpld/app/ledger/ConsensusTransSetSF.cpp b/src/xrpld/app/ledger/ConsensusTransSetSF.cpp index 334b6d46dbd..77a0370f7d9 100644 --- a/src/xrpld/app/ledger/ConsensusTransSetSF.cpp +++ b/src/xrpld/app/ledger/ConsensusTransSetSF.cpp @@ -60,7 +60,7 @@ ConsensusTransSetSF::gotNode( Serializer s(nodeData.data() + 4, nodeData.size() - 4); SerialIter sit(s.slice()); auto stx = std::make_shared(std::ref(sit)); - ASSERT( + XRPL_ASSERT( stx->getTransactionID() == nodeHash.as_uint256(), "ripple::ConsensusTransSetSF::gotNode : transaction hash " "match"); @@ -95,7 +95,7 @@ ConsensusTransSetSF::getNode(SHAMapHash const& nodeHash) const Serializer s; s.add32(HashPrefix::transactionID); txn->getSTransaction()->add(s); - ASSERT( + XRPL_ASSERT( sha512Half(s.slice()) == nodeHash.as_uint256(), "ripple::ConsensusTransSetSF::getNode : transaction hash match"); nodeData = s.peekData(); diff --git a/src/xrpld/app/ledger/Ledger.cpp b/src/xrpld/app/ledger/Ledger.cpp index 5fdc4811051..90e77c1e3d0 100644 --- a/src/xrpld/app/ledger/Ledger.cpp +++ b/src/xrpld/app/ledger/Ledger.cpp @@ -369,7 +369,7 @@ Ledger::setAccepted( bool correctCloseTime) { // Used when we witnessed the consensus. - ASSERT(!open(), "ripple::Ledger::setAccepted : valid ledger state"); + XRPL_ASSERT(!open(), "ripple::Ledger::setAccepted : valid ledger state"); info_.closeTime = closeTime; info_.closeTimeResolution = closeResolution; @@ -562,9 +562,8 @@ Ledger::rawTxInsert( std::shared_ptr const& txn, std::shared_ptr const& metaData) { - ASSERT( - metaData != nullptr, - "ripple::Ledger::rawTxInsert : non-null metadata input"); + XRPL_ASSERT( + metaData, "ripple::Ledger::rawTxInsert : non-null metadata input"); // low-level - just add to table Serializer s(txn->getDataLength() + metaData->getDataLength() + 16); @@ -581,8 +580,8 @@ Ledger::rawTxInsertWithHash( std::shared_ptr const& txn, std::shared_ptr const& metaData) { - ASSERT( - metaData != nullptr, + XRPL_ASSERT( + metaData, "ripple::Ledger::rawTxInsertWithHash : non-null metadata input"); // low-level - just add to table @@ -679,7 +678,7 @@ Ledger::setup() void Ledger::defaultFees(Config const& config) { - ASSERT( + XRPL_ASSERT( fees_.base == 0 && fees_.reserve == 0 && fees_.increment == 0, "ripple::Ledger::defaultFees : zero fees"); if (fees_.base == 0) @@ -911,7 +910,7 @@ Ledger::updateSkipList() created = false; } - ASSERT( + XRPL_ASSERT( hashes.size() <= 256, "ripple::Ledger::updateSkipList : first maximum hashes size"); hashes.push_back(info_.parentHash); @@ -938,7 +937,7 @@ Ledger::updateSkipList() hashes = static_cast(sle->getFieldV256(sfHashes)); created = false; } - ASSERT( + XRPL_ASSERT( hashes.size() <= 256, "ripple::Ledger::updateSkipList : second maximum hashes size"); if (hashes.size() == 256) @@ -1020,7 +1019,7 @@ pendSaveValidated( } } - ASSERT( + XRPL_ASSERT( ledger->isImmutable(), "ripple::pendSaveValidated : immutable ledger"); if (!app.pendingSaves().shouldWork(ledger->info().seq, isSynchronous)) @@ -1098,7 +1097,7 @@ finishLoadByIndexOrHash( if (!ledger) return; - ASSERT( + XRPL_ASSERT( ledger->info().seq < XRP_LEDGER_EARLIEST_FEES || ledger->read(keylet::fees()), "ripple::finishLoadByIndexOrHash : valid ledger fees"); @@ -1140,7 +1139,7 @@ loadByHash(uint256 const& ledgerHash, Application& app, bool acquire) { std::shared_ptr ledger = loadLedgerHelper(*info, app, acquire); finishLoadByIndexOrHash(ledger, app.config(), app.journal("Ledger")); - ASSERT( + XRPL_ASSERT( !ledger || ledger->info().hash == ledgerHash, "ripple::loadByHash : ledger hash match if loaded"); return ledger; diff --git a/src/xrpld/app/ledger/LedgerHistory.cpp b/src/xrpld/app/ledger/LedgerHistory.cpp index b12a0da0fa3..ed0b11723b0 100644 --- a/src/xrpld/app/ledger/LedgerHistory.cpp +++ b/src/xrpld/app/ledger/LedgerHistory.cpp @@ -58,7 +58,7 @@ LedgerHistory::insert( if (!ledger->isImmutable()) LogicError("mutable Ledger in insert"); - ASSERT( + XRPL_ASSERT( ledger->stateMap().getHash().isNonZero(), "ripple::LedgerHistory::insert : nonzero hash"); @@ -101,7 +101,7 @@ LedgerHistory::getLedgerBySeq(LedgerIndex index) if (!ret) return ret; - ASSERT( + XRPL_ASSERT( ret->info().seq == index, "ripple::LedgerHistory::getLedgerBySeq : result sequence match"); @@ -109,7 +109,7 @@ LedgerHistory::getLedgerBySeq(LedgerIndex index) // Add this ledger to the local tracking by index std::unique_lock sl(m_ledgers_by_hash.peekMutex()); - ASSERT( + XRPL_ASSERT( ret->isImmutable(), "ripple::LedgerHistory::getLedgerBySeq : immutable result ledger"); m_ledgers_by_hash.canonicalize_replace_client(ret->info().hash, ret); @@ -125,11 +125,11 @@ LedgerHistory::getLedgerByHash(LedgerHash const& hash) if (ret) { - ASSERT( + XRPL_ASSERT( ret->isImmutable(), "ripple::LedgerHistory::getLedgerByHash : immutable fetched " "ledger"); - ASSERT( + XRPL_ASSERT( ret->info().hash == hash, "ripple::LedgerHistory::getLedgerByHash : fetched ledger hash " "match"); @@ -141,14 +141,14 @@ LedgerHistory::getLedgerByHash(LedgerHash const& hash) if (!ret) return ret; - ASSERT( + XRPL_ASSERT( ret->isImmutable(), "ripple::LedgerHistory::getLedgerByHash : immutable loaded ledger"); - ASSERT( + XRPL_ASSERT( ret->info().hash == hash, "ripple::LedgerHistory::getLedgerByHash : loaded ledger hash match"); m_ledgers_by_hash.canonicalize_replace_client(ret->info().hash, ret); - ASSERT( + XRPL_ASSERT( ret->info().hash == hash, "ripple::LedgerHistory::getLedgerByHash : result hash match"); @@ -194,7 +194,7 @@ log_metadata_difference( auto validMetaData = getMeta(validLedger, tx); auto builtMetaData = getMeta(builtLedger, tx); - ASSERT( + XRPL_ASSERT( validMetaData || builtMetaData, "ripple::log_metadata_difference : some metadata present"); @@ -340,7 +340,7 @@ LedgerHistory::handleMismatch( std::optional const& validatedConsensusHash, Json::Value const& consensus) { - ASSERT( + XRPL_ASSERT( built != valid, "ripple::LedgerHistory::handleMismatch : unequal hashes"); ++mismatch_counter_; @@ -357,7 +357,7 @@ LedgerHistory::handleMismatch( return; } - ASSERT( + XRPL_ASSERT( builtLedger->info().seq == validLedger->info().seq, "ripple::LedgerHistory::handleMismatch : sequence match"); @@ -452,7 +452,8 @@ LedgerHistory::builtLedger( { LedgerIndex index = ledger->info().seq; LedgerHash hash = ledger->info().hash; - ASSERT(!hash.isZero(), "ripple::LedgerHistory::builtLedger : nonzero hash"); + XRPL_ASSERT( + !hash.isZero(), "ripple::LedgerHistory::builtLedger : nonzero hash"); std::unique_lock sl(m_consensus_validated.peekMutex()); @@ -492,7 +493,7 @@ LedgerHistory::validatedLedger( { LedgerIndex index = ledger->info().seq; LedgerHash hash = ledger->info().hash; - ASSERT( + XRPL_ASSERT( !hash.isZero(), "ripple::LedgerHistory::validatedLedger : nonzero hash"); diff --git a/src/xrpld/app/ledger/OpenLedger.h b/src/xrpld/app/ledger/OpenLedger.h index 2ec355fd82f..95d4a7cb234 100644 --- a/src/xrpld/app/ledger/OpenLedger.h +++ b/src/xrpld/app/ledger/OpenLedger.h @@ -263,7 +263,7 @@ OpenLedger::apply( // If there are any transactions left, we must have // tried them in at least one final pass - ASSERT( + XRPL_ASSERT( retries.empty() || !retry, "ripple::OpenLedger::apply : valid retries"); } diff --git a/src/xrpld/app/ledger/OrderBookDB.cpp b/src/xrpld/app/ledger/OrderBookDB.cpp index 926728cbf4f..f9f95e76691 100644 --- a/src/xrpld/app/ledger/OrderBookDB.cpp +++ b/src/xrpld/app/ledger/OrderBookDB.cpp @@ -225,7 +225,7 @@ OrderBookDB::makeBookListeners(Book const& book) ret = std::make_shared(); mListeners[book] = ret; - ASSERT( + XRPL_ASSERT( getBookListeners(book) == ret, "ripple::OrderBookDB::makeBookListeners : result roundtrip lookup"); } diff --git a/src/xrpld/app/ledger/TransactionStateSF.cpp b/src/xrpld/app/ledger/TransactionStateSF.cpp index fef622945c1..30a4d2f8173 100644 --- a/src/xrpld/app/ledger/TransactionStateSF.cpp +++ b/src/xrpld/app/ledger/TransactionStateSF.cpp @@ -30,7 +30,7 @@ TransactionStateSF::gotNode( SHAMapNodeType type) const { - ASSERT( + XRPL_ASSERT( type != SHAMapNodeType::tnTRANSACTION_NM, "ripple::TransactionStateSF::gotNode : valid input"); db_.store( diff --git a/src/xrpld/app/ledger/detail/BuildLedger.cpp b/src/xrpld/app/ledger/detail/BuildLedger.cpp index 812f9dbbc05..6e0fe75efe0 100644 --- a/src/xrpld/app/ledger/detail/BuildLedger.cpp +++ b/src/xrpld/app/ledger/detail/BuildLedger.cpp @@ -57,7 +57,8 @@ buildLedgerImpl( { OpenView accum(&*built); - ASSERT(!accum.open(), "ripple::buildLedgerImpl : valid ledger state"); + XRPL_ASSERT( + !accum.open(), "ripple::buildLedgerImpl : valid ledger state"); applyTxs(accum, built); accum.apply(*built); } @@ -75,7 +76,7 @@ buildLedgerImpl( built->unshare(); // Accept ledger - ASSERT( + XRPL_ASSERT( built->info().seq < XRP_LEDGER_EARLIEST_FEES || built->read(keylet::fees()), "ripple::buildLedgerImpl : valid ledger fees"); @@ -170,7 +171,7 @@ applyTransactions( // If there are any transactions left, we must have // tried them in at least one final pass - ASSERT( + XRPL_ASSERT( txns.empty() || !certainRetry, "ripple::applyTransactions : retry transactions"); return count; diff --git a/src/xrpld/app/ledger/detail/InboundLedger.cpp b/src/xrpld/app/ledger/detail/InboundLedger.cpp index add0726719a..4f25e917c19 100644 --- a/src/xrpld/app/ledger/detail/InboundLedger.cpp +++ b/src/xrpld/app/ledger/detail/InboundLedger.cpp @@ -120,7 +120,7 @@ InboundLedger::init(ScopedLockType& collectionLock) JLOG(journal_.debug()) << "Acquiring ledger we already have in " << " local store. " << hash_; - ASSERT( + XRPL_ASSERT( mLedger->info().seq < XRP_LEDGER_EARLIEST_FEES || mLedger->read(keylet::fees()), "ripple::InboundLedger::init : valid ledger fees"); @@ -352,7 +352,7 @@ InboundLedger::tryDB(NodeStore::Database& srcDB) { JLOG(journal_.debug()) << "Had everything locally"; complete_ = true; - ASSERT( + XRPL_ASSERT( mLedger->info().seq < XRP_LEDGER_EARLIEST_FEES || mLedger->read(keylet::fees()), "ripple::InboundLedger::tryDB : valid ledger fees"); @@ -449,13 +449,13 @@ InboundLedger::done() std::to_string(timeouts_) + " ")) << mStats.get(); - ASSERT( + XRPL_ASSERT( complete_ || failed_, "ripple::InboundLedger::done : complete or failed"); if (complete_ && !failed_ && mLedger) { - ASSERT( + XRPL_ASSERT( mLedger->info().seq < XRP_LEDGER_EARLIEST_FEES || mLedger->read(keylet::fees()), "ripple::InboundLedger::done : valid ledger fees"); @@ -618,8 +618,8 @@ InboundLedger::trigger(std::shared_ptr const& peer, TriggerReason reason) // if we wind up abandoning this fetch. if (mHaveHeader && !mHaveState && !failed_) { - ASSERT( - mLedger != nullptr, + XRPL_ASSERT( + mLedger, "ripple::InboundLedger::trigger : non-null ledger to read state " "from"); @@ -693,8 +693,8 @@ InboundLedger::trigger(std::shared_ptr const& peer, TriggerReason reason) if (mHaveHeader && !mHaveTransactions && !failed_) { - ASSERT( - mLedger != nullptr, + XRPL_ASSERT( + mLedger, "ripple::InboundLedger::trigger : non-null ledger to read " "transactions from"); diff --git a/src/xrpld/app/ledger/detail/InboundLedgers.cpp b/src/xrpld/app/ledger/detail/InboundLedgers.cpp index 3b492de5531..99a26ce8f9f 100644 --- a/src/xrpld/app/ledger/detail/InboundLedgers.cpp +++ b/src/xrpld/app/ledger/detail/InboundLedgers.cpp @@ -73,7 +73,7 @@ class InboundLedgersImp : public InboundLedgers InboundLedger::Reason reason) override { auto doAcquire = [&, seq, reason]() -> std::shared_ptr { - ASSERT( + XRPL_ASSERT( hash.isNonZero(), "ripple::InboundLedgersImp::acquire::doAcquire : nonzero hash"); @@ -164,7 +164,7 @@ class InboundLedgersImp : public InboundLedgers std::shared_ptr find(uint256 const& hash) override { - ASSERT( + XRPL_ASSERT( hash.isNonZero(), "ripple::InboundLedgersImp::find : nonzero input"); @@ -328,8 +328,8 @@ class InboundLedgersImp : public InboundLedgers acqs.reserve(mLedgers.size()); for (auto const& it : mLedgers) { - ASSERT( - it.second != nullptr, + XRPL_ASSERT( + it.second, "ripple::InboundLedgersImp::getInfo : non-null ledger"); acqs.push_back(it); } @@ -365,8 +365,8 @@ class InboundLedgersImp : public InboundLedgers acquires.reserve(mLedgers.size()); for (auto const& it : mLedgers) { - ASSERT( - it.second != nullptr, + XRPL_ASSERT( + it.second, "ripple::InboundLedgersImp::gotFetchPack : non-null " "ledger"); acquires.push_back(it.second); diff --git a/src/xrpld/app/ledger/detail/LedgerCleaner.cpp b/src/xrpld/app/ledger/detail/LedgerCleaner.cpp index 7c9d0f9fd53..27322e302cc 100644 --- a/src/xrpld/app/ledger/detail/LedgerCleaner.cpp +++ b/src/xrpld/app/ledger/detail/LedgerCleaner.cpp @@ -231,7 +231,7 @@ class LedgerCleanerImp : public LedgerCleaner }); if (shouldExit_) break; - ASSERT( + XRPL_ASSERT( state_ == State::cleaning, "ripple::LedgerCleanerImp::run : is cleaning"); } @@ -355,7 +355,7 @@ class LedgerCleanerImp : public LedgerCleaner LedgerHash refHash = getLedgerHash(referenceLedger, refIndex); bool const nonzero(refHash.isNonZero()); - ASSERT( + XRPL_ASSERT( nonzero, "ripple::LedgerCleanerImp::getHash : nonzero hash"); if (nonzero) diff --git a/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp b/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp index 6c19f6da4ea..d312a09008a 100644 --- a/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp +++ b/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp @@ -199,10 +199,10 @@ LedgerDeltaAcquire::tryBuild(std::shared_ptr const& parent) if (failed_ || !complete_ || !replayTemp_) return {}; - ASSERT( + XRPL_ASSERT( parent->seq() + 1 == replayTemp_->seq(), "ripple::LedgerDeltaAcquire::tryBuild : parent sequence match"); - ASSERT( + XRPL_ASSERT( parent->info().hash == replayTemp_->info().parentHash, "ripple::LedgerDeltaAcquire::tryBuild : parent hash match"); // build ledger @@ -266,7 +266,7 @@ LedgerDeltaAcquire::onLedgerBuilt( void LedgerDeltaAcquire::notify(ScopedLockType& sl) { - ASSERT(isDone(), "ripple::LedgerDeltaAcquire::notify : is done"); + XRPL_ASSERT(isDone(), "ripple::LedgerDeltaAcquire::notify : is done"); std::vector toCall; std::swap(toCall, dataReadyCallbacks_); auto const good = !failed_; diff --git a/src/xrpld/app/ledger/detail/LedgerMaster.cpp b/src/xrpld/app/ledger/detail/LedgerMaster.cpp index f5d55f6af23..a302c4fb276 100644 --- a/src/xrpld/app/ledger/detail/LedgerMaster.cpp +++ b/src/xrpld/app/ledger/detail/LedgerMaster.cpp @@ -276,7 +276,7 @@ LedgerMaster::setValidLedger(std::shared_ptr const& l) mValidLedger.set(l); mValidLedgerSign = signTime.time_since_epoch().count(); - ASSERT( + XRPL_ASSERT( mValidLedgerSeq || !app_.getMaxDisallowedLedger() || l->info().seq + max_ledger_difference_ > app_.getMaxDisallowedLedger(), @@ -345,9 +345,7 @@ LedgerMaster::addHeldTransaction( bool LedgerMaster::canBeCurrent(std::shared_ptr const& ledger) { - ASSERT( - ledger != nullptr, - "ripple::LedgerMaster::canBeCurrent : non-null input"); + XRPL_ASSERT(ledger, "ripple::LedgerMaster::canBeCurrent : non-null input"); // Never jump to a candidate ledger that precedes our // last validated ledger @@ -415,9 +413,7 @@ LedgerMaster::canBeCurrent(std::shared_ptr const& ledger) void LedgerMaster::switchLCL(std::shared_ptr const& lastClosed) { - ASSERT( - lastClosed != nullptr, - "ripple::LedgerMaster::switchLCL : non-null input"); + XRPL_ASSERT(lastClosed, "ripple::LedgerMaster::switchLCL : non-null input"); if (!lastClosed->isImmutable()) LogicError("mutable ledger in switchLCL"); @@ -534,7 +530,7 @@ LedgerMaster::isValidated(ReadView const& ledger) // This ledger's hash is not the hash of the validated ledger if (hash) { - ASSERT( + XRPL_ASSERT( hash->isNonZero(), "ripple::LedgerMaster::isValidated : nonzero hash"); uint256 valHash = @@ -826,7 +822,7 @@ LedgerMaster::setFullLedger( // A new ledger has been accepted as part of the trusted chain JLOG(m_journal.debug()) << "Ledger " << ledger->info().seq << " accepted :" << ledger->info().hash; - ASSERT( + XRPL_ASSERT( ledger->stateMap().getHash().isNonZero(), "ripple::LedgerMaster::setFullLedger : nonzero ledger state hash"); @@ -1381,7 +1377,7 @@ LedgerMaster::tryAdvance() app_.getJobQueue().addJob(jtADVANCE, "advanceLedger", [this]() { std::unique_lock sl(m_mutex); - ASSERT( + XRPL_ASSERT( !mValidLedger.empty() && mAdvanceThread, "ripple::LedgerMaster::tryAdvance : has valid ledger"); @@ -1684,9 +1680,7 @@ LedgerMaster::walkHashBySeq( // be located easily and should contain the hash. LedgerIndex refIndex = getCandidateLedger(index); auto const refHash = hashOfSeq(*referenceLedger, refIndex, m_journal); - ASSERT( - refHash.has_value(), - "ripple::LedgerMaster::walkHashBySeq : found ledger"); + XRPL_ASSERT(refHash, "ripple::LedgerMaster::walkHashBySeq : found ledger"); if (refHash) { // Try the hash and sequence of a better reference ledger just found @@ -1711,8 +1705,8 @@ LedgerMaster::walkHashBySeq( *refHash, refIndex, reason)) { ledgerHash = hashOfSeq(*l, index, m_journal); - ASSERT( - ledgerHash.has_value(), + XRPL_ASSERT( + ledgerHash, "ripple::LedgerMaster::walkHashBySeq : has complete " "ledger"); } @@ -1826,7 +1820,7 @@ LedgerMaster::fetchForHistory( scope_unlock sul{sl}; if (auto hash = getLedgerHashForHistory(missing, reason)) { - ASSERT( + XRPL_ASSERT( hash->isNonZero(), "ripple::LedgerMaster::fetchForHistory : found ledger"); auto ledger = getLedgerByHash(*hash); @@ -1855,7 +1849,7 @@ LedgerMaster::fetchForHistory( if (ledger) { auto seq = ledger->info().seq; - ASSERT( + XRPL_ASSERT( seq == missing, "ripple::LedgerMaster::fetchForHistory : sequence match"); JLOG(m_journal.trace()) << "fetchForHistory acquired " << seq; @@ -1898,7 +1892,7 @@ LedgerMaster::fetchForHistory( std::uint32_t seq = missing - i; if (auto h = getLedgerHashForHistory(seq, reason)) { - ASSERT( + XRPL_ASSERT( h->isNonZero(), "ripple::LedgerMaster::fetchForHistory : " "prefetched ledger"); @@ -2087,7 +2081,7 @@ populateFetchPack( std::uint32_t seq, bool withLeaves = true) { - ASSERT(cnt != 0, "ripple::populateFetchPack : nonzero count input"); + XRPL_ASSERT(cnt, "ripple::populateFetchPack : nonzero count input"); Serializer s(1024); diff --git a/src/xrpld/app/ledger/detail/LedgerReplayTask.cpp b/src/xrpld/app/ledger/detail/LedgerReplayTask.cpp index e03137a8b09..164fbf8cc5a 100644 --- a/src/xrpld/app/ledger/detail/LedgerReplayTask.cpp +++ b/src/xrpld/app/ledger/detail/LedgerReplayTask.cpp @@ -32,7 +32,7 @@ LedgerReplayTask::TaskParameter::TaskParameter( std::uint32_t totalNumLedgers) : reason_(r), finishHash_(finishLedgerHash), totalLedgers_(totalNumLedgers) { - ASSERT( + XRPL_ASSERT( finishLedgerHash.isNonZero() && totalNumLedgers > 0, "ripple::LedgerReplayTask::TaskParameter::TaskParameter : valid " "inputs"); @@ -51,7 +51,7 @@ LedgerReplayTask::TaskParameter::update( skipList_ = sList; skipList_.emplace_back(finishHash_); startHash_ = skipList_[skipList_.size() - totalLedgers_]; - ASSERT( + XRPL_ASSERT( startHash_.isNonZero(), "ripple::LedgerReplayTask::TaskParameter::update : nonzero start hash"); startSeq_ = finishSeq_ - totalLedgers_ + 1; @@ -205,7 +205,7 @@ LedgerReplayTask::tryAdvance(ScopedLockType& sl) for (; deltaToBuild_ < deltas_.size(); ++deltaToBuild_) { auto& delta = deltas_[deltaToBuild_]; - ASSERT( + XRPL_ASSERT( parent_->seq() + 1 == delta->ledgerSeq_, "ripple::LedgerReplayTask::tryAdvance : consecutive sequence"); if (auto l = delta->tryBuild(parent_); l) @@ -296,7 +296,7 @@ LedgerReplayTask::addDelta(std::shared_ptr const& delta) JLOG(journal_.trace()) << "addDelta task " << hash_ << " deltaIndex=" << deltaToBuild_ << " totalDeltas=" << deltas_.size(); - ASSERT( + XRPL_ASSERT( deltas_.empty() || deltas_.back()->ledgerSeq_ + 1 == delta->ledgerSeq_, "ripple::LedgerReplayTask::addDelta : no deltas or consecutive " diff --git a/src/xrpld/app/ledger/detail/LedgerReplayer.cpp b/src/xrpld/app/ledger/detail/LedgerReplayer.cpp index 7557d9ed344..3ef3201567a 100644 --- a/src/xrpld/app/ledger/detail/LedgerReplayer.cpp +++ b/src/xrpld/app/ledger/detail/LedgerReplayer.cpp @@ -47,7 +47,7 @@ LedgerReplayer::replay( uint256 const& finishLedgerHash, std::uint32_t totalNumLedgers) { - ASSERT( + XRPL_ASSERT( finishLedgerHash.isNonZero() && totalNumLedgers > 0 && totalNumLedgers <= LedgerReplayParameters::MAX_TASK_SIZE, "ripple::LedgerReplayer::replay : valid inputs"); diff --git a/src/xrpld/app/ledger/detail/SkipListAcquire.cpp b/src/xrpld/app/ledger/detail/SkipListAcquire.cpp index 3b3952a5557..912c29a9f67 100644 --- a/src/xrpld/app/ledger/detail/SkipListAcquire.cpp +++ b/src/xrpld/app/ledger/detail/SkipListAcquire.cpp @@ -139,7 +139,7 @@ SkipListAcquire::processData( std::uint32_t ledgerSeq, boost::intrusive_ptr const& item) { - ASSERT( + XRPL_ASSERT( ledgerSeq != 0 && item, "ripple::SkipListAcquire::processData : valid inputs"); ScopedLockType sl(mtx_); @@ -226,7 +226,7 @@ SkipListAcquire::onSkipListAcquired( void SkipListAcquire::notify(ScopedLockType& sl) { - ASSERT(isDone(), "ripple::SkipListAcquire::notify : is done"); + XRPL_ASSERT(isDone(), "ripple::SkipListAcquire::notify : is done"); std::vector toCall; std::swap(toCall, dataReadyCallbacks_); auto const good = !failed_; diff --git a/src/xrpld/app/ledger/detail/TimeoutCounter.cpp b/src/xrpld/app/ledger/detail/TimeoutCounter.cpp index 1d8efca37f9..35d8f1fffb1 100644 --- a/src/xrpld/app/ledger/detail/TimeoutCounter.cpp +++ b/src/xrpld/app/ledger/detail/TimeoutCounter.cpp @@ -43,7 +43,7 @@ TimeoutCounter::TimeoutCounter( , queueJobParameter_(std::move(jobParameter)) , timer_(app_.getIOService()) { - ASSERT( + XRPL_ASSERT( (timerInterval_ > 10ms) && (timerInterval_ < 30s), "ripple::TimeoutCounter::TimeoutCounter : interval input inside range"); } diff --git a/src/xrpld/app/main/Application.cpp b/src/xrpld/app/main/Application.cpp index c10862d8217..f950e7b6c97 100644 --- a/src/xrpld/app/main/Application.cpp +++ b/src/xrpld/app/main/Application.cpp @@ -586,8 +586,8 @@ class ApplicationImp : public Application, public BasicApp virtual ServerHandler& getServerHandler() override { - ASSERT( - serverHandler_ != nullptr, + XRPL_ASSERT( + serverHandler_, "ripple::ApplicationImp::getServerHandler : non-null server " "handle"); return *serverHandler_; @@ -795,17 +795,16 @@ class ApplicationImp : public Application, public BasicApp Overlay& overlay() override { - ASSERT( - overlay_ != nullptr, - "ripple::ApplicationImp::overlay : non-null overlay"); + XRPL_ASSERT( + overlay_, "ripple::ApplicationImp::overlay : non-null overlay"); return *overlay_; } TxQ& getTxQ() override { - ASSERT( - txQ_.get() != nullptr, + XRPL_ASSERT( + txQ_, "ripple::ApplicationImp::getTxQ : non-null transaction queue"); return *txQ_; } @@ -813,8 +812,8 @@ class ApplicationImp : public Application, public BasicApp RelationalDatabase& getRelationalDatabase() override { - ASSERT( - mRelationalDatabase.get() != nullptr, + XRPL_ASSERT( + mRelationalDatabase, "ripple::ApplicationImp::getRelationalDatabase : non-null " "relational database"); return *mRelationalDatabase; @@ -823,8 +822,8 @@ class ApplicationImp : public Application, public BasicApp DatabaseCon& getWalletDB() override { - ASSERT( - mWalletDB.get() != nullptr, + XRPL_ASSERT( + mWalletDB, "ripple::ApplicationImp::getWalletDB : non-null wallet database"); return *mWalletDB; } @@ -840,7 +839,7 @@ class ApplicationImp : public Application, public BasicApp bool initRelationalDatabase() { - ASSERT( + XRPL_ASSERT( mWalletDB.get() == nullptr, "ripple::ApplicationImp::initRelationalDatabase : null wallet " "database"); @@ -1245,9 +1244,8 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) for (auto const& [a, vote] : amendments) { auto const f = ripple::getRegisteredFeature(a); - ASSERT( - f.has_value(), - "ripple::ApplicationImp::setup : registered feature"); + XRPL_ASSERT( + f, "ripple::ApplicationImp::setup : registered feature"); if (f) supported.emplace_back(a, *f, vote); } @@ -1710,7 +1708,7 @@ ApplicationImp::startGenesisLedger() auto const next = std::make_shared(*genesis, timeKeeper().closeTime()); next->updateSkipList(); - ASSERT( + XRPL_ASSERT( next->info().seq < XRP_LEDGER_EARLIEST_FEES || next->read(keylet::fees()), "ripple::ApplicationImp::startGenesisLedger : valid ledger fees"); @@ -1732,7 +1730,7 @@ ApplicationImp::getLastFullLedger() if (!ledger) return ledger; - ASSERT( + XRPL_ASSERT( ledger->info().seq < XRP_LEDGER_EARLIEST_FEES || ledger->read(keylet::fees()), "ripple::ApplicationImp::getLastFullLedger : valid ledger fees"); @@ -1887,7 +1885,7 @@ ApplicationImp::loadLedgerFromFile(std::string const& name) loadLedger->stateMap().flushDirty(hotACCOUNT_NODE); - ASSERT( + XRPL_ASSERT( loadLedger->info().seq < XRP_LEDGER_EARLIEST_FEES || loadLedger->read(keylet::fees()), "ripple::ApplicationImp::loadLedgerFromFile : valid ledger fees"); diff --git a/src/xrpld/app/main/GRPCServer.cpp b/src/xrpld/app/main/GRPCServer.cpp index c4a1b2458c9..a7280a7688c 100644 --- a/src/xrpld/app/main/GRPCServer.cpp +++ b/src/xrpld/app/main/GRPCServer.cpp @@ -606,7 +606,7 @@ GRPCServer::stop() GRPCServer::~GRPCServer() { - ASSERT(!running_, "ripple::GRPCServer::~GRPCServer : is not running"); + XRPL_ASSERT(!running_, "ripple::GRPCServer::~GRPCServer : is not running"); } } // namespace ripple diff --git a/src/xrpld/app/main/LoadManager.cpp b/src/xrpld/app/main/LoadManager.cpp index 181007305ef..01b96a3d26c 100644 --- a/src/xrpld/app/main/LoadManager.cpp +++ b/src/xrpld/app/main/LoadManager.cpp @@ -73,7 +73,7 @@ void LoadManager::start() { JLOG(journal_.debug()) << "Starting"; - ASSERT( + XRPL_ASSERT( !thread_.joinable(), "ripple::LoadManager::start : thread not joinable"); diff --git a/src/xrpld/app/misc/FeeVoteImpl.cpp b/src/xrpld/app/misc/FeeVoteImpl.cpp index 7943bbe97a7..95160f398a1 100644 --- a/src/xrpld/app/misc/FeeVoteImpl.cpp +++ b/src/xrpld/app/misc/FeeVoteImpl.cpp @@ -200,7 +200,7 @@ FeeVoteImpl::doVoting( std::shared_ptr const& initialPosition) { // LCL must be flag ledger - ASSERT( + XRPL_ASSERT( lastClosedLedger && isFlagLedger(lastClosedLedger->seq()), "ripple::FeeVoteImpl::doVoting : has a flag ledger"); diff --git a/src/xrpld/app/misc/HashRouter.cpp b/src/xrpld/app/misc/HashRouter.cpp index 44133dddf9b..58e811d4b8f 100644 --- a/src/xrpld/app/misc/HashRouter.cpp +++ b/src/xrpld/app/misc/HashRouter.cpp @@ -101,7 +101,7 @@ HashRouter::getFlags(uint256 const& key) bool HashRouter::setFlags(uint256 const& key, int flags) { - ASSERT(flags != 0, "ripple::HashRouter::setFlags : valid input"); + XRPL_ASSERT(flags, "ripple::HashRouter::setFlags : valid input"); std::lock_guard lock(mutex_); diff --git a/src/xrpld/app/misc/NegativeUNLVote.cpp b/src/xrpld/app/misc/NegativeUNLVote.cpp index b8f485c3dc0..471c9374728 100644 --- a/src/xrpld/app/misc/NegativeUNLVote.cpp +++ b/src/xrpld/app/misc/NegativeUNLVote.cpp @@ -89,8 +89,8 @@ NegativeUNLVote::doVoting( { auto n = choose(prevLedger->info().hash, candidates.toDisableCandidates); - ASSERT( - nidToKeyMap.count(n) != 0, + XRPL_ASSERT( + nidToKeyMap.contains(n), "ripple::NegativeUNLVote::doVoting : found node to disable"); addTx(seq, nidToKeyMap.at(n), ToDisable, initialSet); } @@ -99,8 +99,8 @@ NegativeUNLVote::doVoting( { auto n = choose( prevLedger->info().hash, candidates.toReEnableCandidates); - ASSERT( - nidToKeyMap.count(n) != 0, + XRPL_ASSERT( + nidToKeyMap.contains(n), "ripple::NegativeUNLVote::doVoting : found node to enable"); addTx(seq, nidToKeyMap.at(n), ToReEnable, initialSet); } @@ -144,7 +144,7 @@ NegativeUNLVote::choose( uint256 const& randomPadData, std::vector const& candidates) { - ASSERT( + XRPL_ASSERT( !candidates.empty(), "ripple::NegativeUNLVote::choose : non-empty input"); static_assert(NodeID::bytes <= uint256::bytes); diff --git a/src/xrpld/app/misc/NetworkOPs.cpp b/src/xrpld/app/misc/NetworkOPs.cpp index e7432b4de0c..8e483811145 100644 --- a/src/xrpld/app/misc/NetworkOPs.cpp +++ b/src/xrpld/app/misc/NetworkOPs.cpp @@ -105,7 +105,7 @@ class NetworkOPsImp final : public NetworkOPs FailHard f) : transaction(t), admin(a), local(l), failType(f) { - ASSERT( + XRPL_ASSERT( local || failType == FailHard::no, "ripple::NetworkOPsImp::TransactionStatus::TransactionStatus : " "valid inputs"); @@ -1213,7 +1213,7 @@ NetworkOPsImp::processTransaction( *transaction->getSTransaction(), view->rules(), app_.config()); - ASSERT( + XRPL_ASSERT( validity == Validity::Valid, "ripple::NetworkOPsImp::processTransaction : valid validity"); @@ -1321,10 +1321,10 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) std::vector submit_held; std::vector transactions; mTransactions.swap(transactions); - ASSERT( + XRPL_ASSERT( !transactions.empty(), "ripple::NetworkOPsImp::apply : non-empty transactions"); - ASSERT( + XRPL_ASSERT( mDispatchState != DispatchState::running, "ripple::NetworkOPsImp::apply : is not running"); @@ -1543,8 +1543,8 @@ NetworkOPsImp::getOwnerInfo( for (auto const& uDirEntry : sleNode->getFieldV256(sfIndexes)) { auto sleCur = lpLedger->read(keylet::child(uDirEntry)); - ASSERT( - sleCur != nullptr, + XRPL_ASSERT( + sleCur, "ripple::NetworkOPsImp::getOwnerInfo : non-null child SLE"); switch (sleCur->getType()) @@ -1584,8 +1584,8 @@ NetworkOPsImp::getOwnerInfo( if (uNodeDir) { sleNode = lpLedger->read(keylet::page(root, uNodeDir)); - ASSERT( - sleNode != nullptr, + XRPL_ASSERT( + sleNode, "ripple::NetworkOPsImp::getOwnerInfo : read next page"); } } while (uNodeDir); @@ -1817,7 +1817,7 @@ NetworkOPsImp::switchLastClosedLedger( bool NetworkOPsImp::beginConsensus(uint256 const& networkClosed) { - ASSERT( + XRPL_ASSERT( networkClosed.isNonZero(), "ripple::NetworkOPsImp::beginConsensus : nonzero input"); @@ -1840,11 +1840,11 @@ NetworkOPsImp::beginConsensus(uint256 const& networkClosed) return false; } - ASSERT( + XRPL_ASSERT( prevLedger->info().hash == closingInfo.parentHash, "ripple::NetworkOPsImp::beginConsensus : prevLedger hash matches " "parent"); - ASSERT( + XRPL_ASSERT( closingInfo.parentHash == m_ledgerMaster.getClosedLedger()->info().hash, "ripple::NetworkOPsImp::beginConsensus : closedLedger parent matches " "hash"); @@ -2820,7 +2820,7 @@ NetworkOPsImp::pubLedger(std::shared_ptr const& lpAccepted) lpAccepted->info().hash, alpAccepted); } - ASSERT( + XRPL_ASSERT( alpAccepted->getLedger().get() == lpAccepted.get(), "ripple::NetworkOPsImp::pubLedger : accepted input"); @@ -3225,7 +3225,7 @@ NetworkOPsImp::pubAccountTransaction( if (last) jvObj.set(jss::account_history_boundary, true); - ASSERT( + XRPL_ASSERT( jvObj.isMember(jss::account_history_tx_stream) == MultiApiJson::none, "ripple::NetworkOPsImp::pubAccountTransaction : " @@ -3302,7 +3302,7 @@ NetworkOPsImp::pubProposedAccountTransaction( isrListener->getApiVersion(), // [&](Json::Value const& jv) { isrListener->send(jv, true); }); - ASSERT( + XRPL_ASSERT( jvObj.isMember(jss::account_history_tx_stream) == MultiApiJson::none, "ripple::NetworkOPs::pubProposedAccountTransaction : " @@ -3854,7 +3854,8 @@ NetworkOPsImp::acceptLedger( { // This code-path is exclusively used when the server is in standalone // mode via `ledger_accept` - ASSERT(m_standalone, "ripple::NetworkOPsImp::acceptLedger : is standalone"); + XRPL_ASSERT( + m_standalone, "ripple::NetworkOPsImp::acceptLedger : is standalone"); if (!m_standalone) Throw( diff --git a/src/xrpld/app/misc/SHAMapStoreImp.cpp b/src/xrpld/app/misc/SHAMapStoreImp.cpp index 2913ebb857f..3a530e0e410 100644 --- a/src/xrpld/app/misc/SHAMapStoreImp.cpp +++ b/src/xrpld/app/misc/SHAMapStoreImp.cpp @@ -513,8 +513,8 @@ SHAMapStoreImp::clearSql( std::function()> const& getMinSeq, std::function const& deleteBeforeSeq) { - ASSERT( - deleteInterval_ != 0, + XRPL_ASSERT( + deleteInterval_, "ripple::SHAMapStoreImp::clearSql : nonzero delete interval"); LedgerIndex min = std::numeric_limits::max(); diff --git a/src/xrpld/app/misc/detail/AMMHelpers.cpp b/src/xrpld/app/misc/detail/AMMHelpers.cpp index 4e23a607502..8724c413a68 100644 --- a/src/xrpld/app/misc/detail/AMMHelpers.cpp +++ b/src/xrpld/app/misc/detail/AMMHelpers.cpp @@ -209,7 +209,7 @@ adjustAmountsByLPTokens( return std::make_tuple(amountActual, std::nullopt, lpTokensActual); } - ASSERT( + XRPL_ASSERT( lpTokensActual == lpTokens, "ripple::adjustAmountsByLPTokens : LP tokens match actual"); diff --git a/src/xrpld/app/misc/detail/AMMUtils.cpp b/src/xrpld/app/misc/detail/AMMUtils.cpp index c91f0c56642..172b2ee1101 100644 --- a/src/xrpld/app/misc/detail/AMMUtils.cpp +++ b/src/xrpld/app/misc/detail/AMMUtils.cpp @@ -145,7 +145,7 @@ std::uint16_t getTradingFee(ReadView const& view, SLE const& ammSle, AccountID const& account) { using namespace std::chrono; - ASSERT( + XRPL_ASSERT( !view.rules().enabled(fixInnerObjTemplate) || ammSle.isFieldPresent(sfAuctionSlot), "ripple::getTradingFee : auction present"); diff --git a/src/xrpld/app/misc/detail/AmendmentTable.cpp b/src/xrpld/app/misc/detail/AmendmentTable.cpp index a35eb72efeb..270b5daced2 100644 --- a/src/xrpld/app/misc/detail/AmendmentTable.cpp +++ b/src/xrpld/app/misc/detail/AmendmentTable.cpp @@ -656,7 +656,7 @@ AmendmentTableImpl::persistVote( std::string const& name, AmendmentVote vote) const { - ASSERT( + XRPL_ASSERT( vote != AmendmentVote::obsolete, "ripple::AmendmentTableImpl::persistVote : valid vote input"); auto db = db_.checkoutDb(); diff --git a/src/xrpld/app/misc/detail/Manifest.cpp b/src/xrpld/app/misc/detail/Manifest.cpp index bf3b58cc9d9..04c8523aece 100644 --- a/src/xrpld/app/misc/detail/Manifest.cpp +++ b/src/xrpld/app/misc/detail/Manifest.cpp @@ -390,7 +390,7 @@ ManifestCache::applyManifest(Manifest m) auto prewriteCheck = [this, &m](auto const& iter, bool checkSignature, auto const& lock) -> std::optional { - ASSERT( + XRPL_ASSERT( lock.owns_lock(), "ripple::ManifestCache::applyManifest::prewriteCheck : locked"); (void)lock; // not used. parameter is present to ensure the mutex is diff --git a/src/xrpld/app/misc/detail/Transaction.cpp b/src/xrpld/app/misc/detail/Transaction.cpp index 27cb785eb78..30af6b773d0 100644 --- a/src/xrpld/app/misc/detail/Transaction.cpp +++ b/src/xrpld/app/misc/detail/Transaction.cpp @@ -82,7 +82,7 @@ Transaction::sqlTransactionStatus(boost::optional const& status) return INCLUDED; } - ASSERT( + XRPL_ASSERT( c == txnSqlUnknown, "ripple::Transaction::sqlTransactionStatus : unknown transaction " "status"); diff --git a/src/xrpld/app/misc/detail/TxQ.cpp b/src/xrpld/app/misc/detail/TxQ.cpp index 9f886fd2977..4c78bc4bc99 100644 --- a/src/xrpld/app/misc/detail/TxQ.cpp +++ b/src/xrpld/app/misc/detail/TxQ.cpp @@ -52,7 +52,7 @@ getFeeLevelPaid(ReadView const& view, STTx const& tx) return std::pair{baseFee + mod, feePaid + mod}; }(); - ASSERT(baseFee.signum() > 0, "ripple::getFeeLevelPaid : positive fee"); + XRPL_ASSERT(baseFee.signum() > 0, "ripple::getFeeLevelPaid : positive fee"); if (effectiveFeePaid.signum() <= 0 || baseFee.signum() <= 0) { return FeeLevel64(0); @@ -95,7 +95,7 @@ TxQ::FeeMetrics::update( feeLevels.push_back(getFeeLevelPaid(view, *tx.first)); }); std::sort(feeLevels.begin(), feeLevels.end()); - ASSERT( + XRPL_ASSERT( size == feeLevels.size(), "ripple::TxQ::FeeMetrics::update : fee levels size"); @@ -249,7 +249,7 @@ TxQ::FeeMetrics::escalatedSeriesFeeLevel( auto const target = snapshot.txnsExpected; auto const multiplier = snapshot.escalationMultiplier; - ASSERT( + XRPL_ASSERT( current > target, "ripple::TxQ::FeeMetrics::escalatedSeriesFeeLevel : current over " "target"); @@ -297,9 +297,8 @@ std::pair TxQ::MaybeTx::apply(Application& app, OpenView& view, beast::Journal j) { // If the rules or flags change, preflight again - ASSERT( - pfresult.has_value(), - "ripple::TxQ::MaybeTx::apply : preflight result is set"); + XRPL_ASSERT( + pfresult, "ripple::TxQ::MaybeTx::apply : preflight result is set"); STAmountSO stAmountSO{view.rules().enabled(fixSTAmountCanonicalize)}; NumberSO stNumberSO{view.rules().enabled(fixUniversalNumber)}; @@ -344,8 +343,9 @@ TxQ::TxQAccount::add(MaybeTx&& txn) auto const seqProx = txn.seqProxy; auto result = transactions.emplace(seqProx, std::move(txn)); - ASSERT(result.second, "ripple::TxQ::TxQAccount::add : emplace succeeded"); - ASSERT( + XRPL_ASSERT( + result.second, "ripple::TxQ::TxQAccount::add : emplace succeeded"); + XRPL_ASSERT( &result.first->second != &txn, "ripple::TxQ::TxQAccount::add : transaction moved"); @@ -456,7 +456,7 @@ TxQ::erase(TxQ::FeeMultiSet::const_iterator_type candidateIter) // intrusive list remove it from the TxQAccount // so the memory can be freed. [[maybe_unused]] auto const found = txQAccount.remove(seqProx); - ASSERT(found, "ripple::TxQ::erase : account removed"); + XRPL_ASSERT(found, "ripple::TxQ::erase : account removed"); return newCandidateIter; } @@ -468,18 +468,18 @@ TxQ::eraseAndAdvance(TxQ::FeeMultiSet::const_iterator_type candidateIter) auto& txQAccount = byAccount_.at(candidateIter->account); auto const accountIter = txQAccount.transactions.find(candidateIter->seqProxy); - ASSERT( + XRPL_ASSERT( accountIter != txQAccount.transactions.end(), "ripple::TxQ::eraseAndAdvance : account found"); // Note that sequence-based transactions must be applied in sequence order // from smallest to largest. But ticket-based transactions can be // applied in any order. - ASSERT( + XRPL_ASSERT( candidateIter->seqProxy.isTicket() || accountIter == txQAccount.transactions.begin(), "ripple::TxQ::eraseAndAdvance : ticket or sequence"); - ASSERT( + XRPL_ASSERT( byFee_.iterator_to(accountIter->second) == candidateIter, "ripple::TxQ::eraseAndAdvance : found in byFee"); auto const accountNextIter = std::next(accountIter); @@ -528,7 +528,7 @@ TxQ::tryClearAccountQueueUpThruTx( beast::Journal j) { SeqProxy const tSeqProx{tx.getSeqProxy()}; - ASSERT( + XRPL_ASSERT( beginTxIter != accountIter->second.transactions.end(), "ripple::TxQ::tryClearAccountQueueUpThruTx : non-empty accounts input"); @@ -1013,7 +1013,8 @@ TxQ::apply( // o The current first thing in the queue has a Ticket and // * The tx has a Ticket that precedes it or // * txSeqProx == acctSeqProx. - ASSERT(prevIter != txIter->end, "ripple::TxQ::apply : not end"); + XRPL_ASSERT( + prevIter != txIter->end, "ripple::TxQ::apply : not end"); if (prevIter == txIter->end || txSeqProx < prevIter->first) { // The first Sequence number in the queue must be the @@ -1134,7 +1135,7 @@ TxQ::apply( // inserted in the middle from fouling up later transactions. auto const potentialTotalSpend = totalFee + std::min(balance - std::min(balance, reserve), potentialSpend); - ASSERT( + XRPL_ASSERT( potentialTotalSpend > XRPAmount{0} || (potentialTotalSpend == XRPAmount{0} && multiTxn->applyView.fees().base == 0), @@ -1168,7 +1169,7 @@ TxQ::apply( return {pcresult.ter, false}; // Too low of a fee should get caught by preclaim - ASSERT(feeLevelPaid >= baseLevel, "ripple::TxQ::apply : minimum fee"); + XRPL_ASSERT(feeLevelPaid >= baseLevel, "ripple::TxQ::apply : minimum fee"); JLOG(j_.trace()) << "Transaction " << transactionID << " from account " << account << " has fee level of " << feeLevelPaid @@ -1293,7 +1294,7 @@ TxQ::apply( // The queue is full, and this transaction is more // valuable, so kick out the cheapest transaction. auto dropRIter = endAccount.transactions.rbegin(); - ASSERT( + XRPL_ASSERT( dropRIter->second.account == lastRIter->account, "ripple::TxQ::apply : cheapest transaction found"); JLOG(j_.info()) @@ -1324,7 +1325,7 @@ TxQ::apply( [[maybe_unused]] bool created = false; std::tie(accountIter, created) = byAccount_.emplace(account, TxQAccount(tx)); - ASSERT(created, "ripple::TxQ::apply : account created"); + XRPL_ASSERT(created, "ripple::TxQ::apply : account created"); } // Modify the flags for use when coming out of the queue. // These changes _may_ cause an extra `preflight`, but as long as @@ -1537,7 +1538,7 @@ TxQ::accept(Application& app, OpenView& view) // making things worse, drop the _last_ transaction for // this account. auto dropRIter = account.transactions.rbegin(); - ASSERT( + XRPL_ASSERT( dropRIter->second.account == candidateIter->account, "ripple::TxQ::accept : account check"); @@ -1570,7 +1571,8 @@ TxQ::accept(Application& app, OpenView& view) LedgerHash const& parentHash = view.info().parentHash; #if !NDEBUG auto const startingSize = byFee_.size(); - ASSERT(parentHash != parentHash_, "ripple::TxQ::accept : new parent hash"); + XRPL_ASSERT( + parentHash != parentHash_, "ripple::TxQ::accept : new parent hash"); parentHash_ = parentHash; #endif // byFee_ doesn't "own" the candidate objects inside it, so it's @@ -1592,7 +1594,7 @@ TxQ::accept(Application& app, OpenView& view) byFee_.insert(candidate); } } - ASSERT( + XRPL_ASSERT( byFee_.size() == startingSize, "ripple::TxQ::accept : byFee size match"); @@ -1753,16 +1755,16 @@ TxQ::removeFromByFee( // If the transaction we're holding replaces a transaction in the // queue, remove the transaction that is being replaced. auto deleteIter = byFee_.iterator_to((*replacedTxIter)->second); - ASSERT( + XRPL_ASSERT( deleteIter != byFee_.end(), "ripple::TxQ::removeFromByFee : found in byFee"); - ASSERT( + XRPL_ASSERT( &(*replacedTxIter)->second == &*deleteIter, "ripple::TxQ::removeFromByFee : matching transaction"); - ASSERT( + XRPL_ASSERT( deleteIter->seqProxy == tx->getSeqProxy(), "ripple::TxQ::removeFromByFee : matching sequence"); - ASSERT( + XRPL_ASSERT( deleteIter->account == (*tx)[sfAccount], "ripple::TxQ::removeFromByFee : matching account"); diff --git a/src/xrpld/app/misc/detail/ValidatorList.cpp b/src/xrpld/app/misc/detail/ValidatorList.cpp index 052cecb80b1..ba77a3213c7 100644 --- a/src/xrpld/app/misc/detail/ValidatorList.cpp +++ b/src/xrpld/app/misc/detail/ValidatorList.cpp @@ -276,7 +276,7 @@ ValidatorList::buildFileData( { Json::Value value(Json::objectValue); - ASSERT( + XRPL_ASSERT( pubCollection.rawVersion == 2 || pubCollection.remaining.empty(), "ripple::ValidatorList::buildFileData : valid publisher list input"); auto const effectiveVersion = @@ -378,7 +378,7 @@ ValidatorList::parseBlobs(std::uint32_t version, Json::Value const& body) ValidatorBlobInfo& info = result.emplace_back(); info.blob = body[jss::blob].asString(); info.signature = body[jss::signature].asString(); - ASSERT( + XRPL_ASSERT( result.size() == 1, "ripple::ValidatorList::parseBlobs : single element result"); return result; @@ -415,7 +415,7 @@ ValidatorList::parseBlobs(std::uint32_t version, Json::Value const& body) info.manifest = blobInfo[jss::manifest].asString(); } } - ASSERT( + XRPL_ASSERT( result.size() == blobs.size(), "ripple::ValidatorList::parseBlobs(version, Jason::Value) : " "result size matches"); @@ -449,7 +449,7 @@ ValidatorList::parseBlobs(protocol::TMValidatorListCollection const& body) info.manifest = blob.manifest(); } } - ASSERT( + XRPL_ASSERT( result.size() == body.blobs_size(), "ripple::ValidatorList::parseBlobs(TMValidatorList) : result size " "match"); @@ -474,7 +474,7 @@ splitMessage( { if (begin == 0 && end == 0) end = largeMsg.blobs_size(); - ASSERT(begin < end, "ripple::splitMessage : valid inputs"); + XRPL_ASSERT(begin < end, "ripple::splitMessage : valid inputs"); if (end <= begin) return 0; @@ -508,7 +508,7 @@ splitMessageParts( if (blob.has_manifest()) smallMsg.set_manifest(blob.manifest()); - ASSERT( + XRPL_ASSERT( Message::totalSize(smallMsg) <= maximiumMessageSize, "ripple::splitMessageParts : maximum message size"); @@ -558,7 +558,7 @@ buildValidatorListMessage( ValidatorBlobInfo const& currentBlob, std::size_t maxSize) { - ASSERT( + XRPL_ASSERT( messages.empty(), "ripple::buildValidatorListMessage(ValidatorBlobInfo) : empty messages " "input"); @@ -572,7 +572,7 @@ buildValidatorListMessage( // Override the version msg.set_version(version); - ASSERT( + XRPL_ASSERT( Message::totalSize(msg) <= maximiumMessageSize, "ripple::buildValidatorListMessage(ValidatorBlobInfo) : maximum " "message size"); @@ -594,7 +594,7 @@ buildValidatorListMessage( std::map const& blobInfos, std::size_t maxSize) { - ASSERT( + XRPL_ASSERT( messages.empty(), "ripple::buildValidatorListMessage(std::map) : empty messages input"); @@ -613,7 +613,7 @@ buildValidatorListMessage( if (blobInfo.manifest) blob.set_manifest(*blobInfo.manifest); } - ASSERT( + XRPL_ASSERT( msg.blobs_size() > 0, "ripple::buildValidatorListMessage(std::map) : minimum message blobs"); @@ -645,7 +645,7 @@ ValidatorList::buildValidatorListMessages( std::vector& messages, std::size_t maxSize /*= maximiumMessageSize*/) { - ASSERT( + XRPL_ASSERT( !blobInfos.empty(), "ripple::ValidatorList::buildValidatorListMessages : empty messages " "input"); @@ -731,7 +731,7 @@ ValidatorList::sendValidatorList( messages); if (newPeerSequence) { - ASSERT( + XRPL_ASSERT( !messages.empty(), "ripple::ValidatorList::sendValidatorList : non-empty messages " "input"); @@ -750,7 +750,7 @@ ValidatorList::sendValidatorList( } // The only way sent wil be false is if the messages was too big, and // thus there will only be one entry without a message - ASSERT( + XRPL_ASSERT( sent || messages.size() == 1, "ripple::ValidatorList::sendValidatorList : sent or one message"); if (sent) @@ -766,7 +766,7 @@ ValidatorList::sendValidatorList( << "]"; else { - ASSERT( + XRPL_ASSERT( numVLs == 1, "ripple::ValidatorList::sendValidatorList : one validator " "list"); @@ -864,7 +864,7 @@ ValidatorList::broadcastBlobs( // be built to hold info for all of the valid VLs. std::map blobInfos; - ASSERT( + XRPL_ASSERT( lists.current.sequence == maxSequence || lists.remaining.count(maxSequence) == 1, "ripple::ValidatorList::broadcastBlobs : valid sequence"); @@ -1011,7 +1011,7 @@ ValidatorList::applyLists( for (auto iter = remaining.begin(); iter != remaining.end();) { auto next = std::next(iter); - ASSERT( + XRPL_ASSERT( next == remaining.end() || next->first > iter->first, "ripple::ValidatorList::applyLists : next is valid"); if (iter->first <= current.sequence || @@ -1185,7 +1185,7 @@ ValidatorList::applyList( // Remove the entry in "remaining" pubCollection.remaining.erase(sequence); // Done - ASSERT( + XRPL_ASSERT( publisher.sequence == sequence, "ripple::ValidatorList::applyList : publisher sequence match"); } @@ -1481,7 +1481,7 @@ ValidatorList::removePublisherList( PublicKey const& publisherKey, PublisherStatus reason) { - ASSERT( + XRPL_ASSERT( reason != PublisherStatus::available && reason != PublisherStatus::unavailable, "ripple::ValidatorList::removePublisherList : valid reason input"); @@ -1669,7 +1669,7 @@ ValidatorList::getJson() const Json::Value& r = remaining.append(Json::objectValue); appendList(future, r); // Race conditions can happen, so make this check "fuzzy" - ASSERT( + XRPL_ASSERT( future.validFrom > timeKeeper_.now() + 600s, "ripple::ValidatorList::getJson : minimum valid from"); } @@ -1736,7 +1736,7 @@ ValidatorList::for_each_available( { if (plCollection.status != PublisherStatus::available) continue; - ASSERT( + XRPL_ASSERT( plCollection.maxSequence != 0, "ripple::ValidatorList::for_each_available : nonzero maxSequence"); func( @@ -1872,12 +1872,12 @@ ValidatorList::updateTrusted( next->second.validFrom <= closeTime; ++iter, ++next) { - ASSERT( + XRPL_ASSERT( std::next(iter) == next, "ripple::ValidatorList::updateTrusted : sequential " "remaining"); } - ASSERT( + XRPL_ASSERT( iter != remaining.end(), "ripple::ValidatorList::updateTrusted : non-end of " "remaining"); @@ -1886,7 +1886,7 @@ ValidatorList::updateTrusted( auto sequence = iter->first; auto& candidate = iter->second; auto& current = collection.current; - ASSERT( + XRPL_ASSERT( candidate.validFrom <= closeTime, "ripple::ValidatorList::updateTrusted : maximum time"); @@ -1894,7 +1894,7 @@ ValidatorList::updateTrusted( current = std::move(candidate); if (collection.status != PublisherStatus::available) collection.status = PublisherStatus::available; - ASSERT( + XRPL_ASSERT( current.sequence == sequence, "ripple::ValidatorList::updateTrusted : sequence match"); // If the list is expired, remove the validators so they don't @@ -1973,8 +1973,8 @@ ValidatorList::updateTrusted( { std::optional const signingKey = validatorManifests_.getSigningKey(k); - ASSERT( - signingKey.has_value(), + XRPL_ASSERT( + signingKey, "ripple::ValidatorList::updateTrusted : found signing key"); trustedSigningKeys_.insert(*signingKey); } diff --git a/src/xrpld/app/misc/detail/ValidatorSite.cpp b/src/xrpld/app/misc/detail/ValidatorSite.cpp index fd775fc9251..1994f498614 100644 --- a/src/xrpld/app/misc/detail/ValidatorSite.cpp +++ b/src/xrpld/app/misc/detail/ValidatorSite.cpp @@ -411,7 +411,7 @@ ValidatorSite::parseJsonResponse( } auto const manifest = body[jss::manifest].asString(); - ASSERT( + XRPL_ASSERT( version == body[jss::version].asUInt(), "ripple::ValidatorSite::parseJsonResponse : version match"); auto const& uri = sites_[siteIdx].activeResource->uri; @@ -588,8 +588,8 @@ ValidatorSite::onSiteFetch( case status::temporary_redirect: { auto newLocation = processRedirect(res, siteIdx, lock_sites); - ASSERT( - newLocation != nullptr, + XRPL_ASSERT( + newLocation, "ripple::ValidatorSite::onSiteFetch : non-null " "validator"); // for perm redirects, also update our starting URI diff --git a/src/xrpld/app/misc/detail/WorkBase.h b/src/xrpld/app/misc/detail/WorkBase.h index 8fece4703f5..cd909265115 100644 --- a/src/xrpld/app/misc/detail/WorkBase.h +++ b/src/xrpld/app/misc/detail/WorkBase.h @@ -282,9 +282,7 @@ WorkBase::onResponse(error_code const& ec) return fail(ec); close(); - ASSERT( - cb_ != nullptr, - "ripple::detail::WorkBase::onResponse : callback is set"); + XRPL_ASSERT(cb_, "ripple::detail::WorkBase::onResponse : callback is set"); cb_(ec, lastEndpoint_, std::move(res_)); cb_ = nullptr; } diff --git a/src/xrpld/app/misc/detail/WorkFile.h b/src/xrpld/app/misc/detail/WorkFile.h index 1f08cacac68..9b8d86f5e16 100644 --- a/src/xrpld/app/misc/detail/WorkFile.h +++ b/src/xrpld/app/misc/detail/WorkFile.h @@ -88,7 +88,7 @@ WorkFile::run() error_code ec; auto const fileContents = getFileContents(ec, path_, megabytes(1)); - ASSERT(cb_ != nullptr, "ripple::detail::WorkFile::run : callback is set"); + XRPL_ASSERT(cb_, "ripple::detail::WorkFile::run : callback is set"); cb_(ec, fileContents); cb_ = nullptr; } diff --git a/src/xrpld/app/paths/Credit.cpp b/src/xrpld/app/paths/Credit.cpp index dbf0db45c4b..e027949e761 100644 --- a/src/xrpld/app/paths/Credit.cpp +++ b/src/xrpld/app/paths/Credit.cpp @@ -42,10 +42,10 @@ creditLimit( result.setIssuer(account); } - ASSERT( + XRPL_ASSERT( result.getIssuer() == account, "ripple::creditLimit : result issuer match"); - ASSERT( + XRPL_ASSERT( result.getCurrency() == currency, "ripple::creditLimit : result currency match"); return result; @@ -80,10 +80,10 @@ creditBalance( result.setIssuer(account); } - ASSERT( + XRPL_ASSERT( result.getIssuer() == account, "ripple::creditBalance : result issuer match"); - ASSERT( + XRPL_ASSERT( result.getCurrency() == currency, "ripple::creditBalance : result currency match"); return result; diff --git a/src/xrpld/app/paths/Flow.cpp b/src/xrpld/app/paths/Flow.cpp index 6b8f46e558d..3df8f6f9992 100644 --- a/src/xrpld/app/paths/Flow.cpp +++ b/src/xrpld/app/paths/Flow.cpp @@ -193,7 +193,7 @@ flow( flowDebugInfo)); } - ASSERT(!srcIsXRP && !dstIsXRP, "ripple::flow : neither is XRP"); + XRPL_ASSERT(!srcIsXRP && !dstIsXRP, "ripple::flow : neither is XRP"); return finishFlow( sb, srcIssue, diff --git a/src/xrpld/app/paths/PathRequest.cpp b/src/xrpld/app/paths/PathRequest.cpp index 28ade441c2d..643923320a2 100644 --- a/src/xrpld/app/paths/PathRequest.cpp +++ b/src/xrpld/app/paths/PathRequest.cpp @@ -158,7 +158,8 @@ PathRequest::updateComplete() { std::lock_guard sl(mIndexLock); - ASSERT(mInProgress, "ripple::PathRequest::updateComplete : in progress"); + XRPL_ASSERT( + mInProgress, "ripple::PathRequest::updateComplete : in progress"); mInProgress = false; if (fCompletion) diff --git a/src/xrpld/app/paths/Pathfinder.cpp b/src/xrpld/app/paths/Pathfinder.cpp index 3f506809887..5864357aec4 100644 --- a/src/xrpld/app/paths/Pathfinder.cpp +++ b/src/xrpld/app/paths/Pathfinder.cpp @@ -189,7 +189,7 @@ Pathfinder::Pathfinder( , app_(app) , j_(app.journal("Pathfinder")) { - ASSERT( + XRPL_ASSERT( !uSrcIssuer || isXRP(uSrcCurrency) == isXRP(uSrcIssuer.value()), "ripple::Pathfinder::Pathfinder : valid inputs"); } @@ -579,7 +579,7 @@ Pathfinder::getBestPaths( if (mCompletePaths.empty() && extraPaths.empty()) return mCompletePaths; - ASSERT( + XRPL_ASSERT( fullLiquidityPath.empty(), "ripple::Pathfinder::getBestPaths : first empty path result"); const bool issuerIsSender = @@ -685,7 +685,7 @@ Pathfinder::getBestPaths( if (remaining > beast::zero) { - ASSERT( + XRPL_ASSERT( fullLiquidityPath.empty(), "ripple::Pathfinder::getBestPaths : second empty path result"); JLOG(j_.info()) << "Paths could not send " << remaining << " of " @@ -836,7 +836,7 @@ Pathfinder::addPathsForType( { case nt_SOURCE: // Source must always be at the start, so pathsOut has to be empty. - ASSERT( + XRPL_ASSERT( pathsOut.empty(), "ripple::Pathfinder::addPathsForType : empty paths"); pathsOut.push_back(STPath()); @@ -1290,7 +1290,7 @@ void fillPaths(Pathfinder::PaymentType type, PathCostList const& costs) { auto& list = mPathTable[type]; - ASSERT(list.empty(), "ripple::fillPaths : empty paths"); + XRPL_ASSERT(list.empty(), "ripple::fillPaths : empty paths"); for (auto& cost : costs) list.push_back({cost.cost, makePath(cost.path)}); } diff --git a/src/xrpld/app/paths/RippleLineCache.cpp b/src/xrpld/app/paths/RippleLineCache.cpp index 053546ce0be..38b630eeb7e 100644 --- a/src/xrpld/app/paths/RippleLineCache.cpp +++ b/src/xrpld/app/paths/RippleLineCache.cpp @@ -79,7 +79,7 @@ RippleLineCache::getRippleLines( // to be replaced by the full set. The full set will be built // below, and will be returned, if needed, on subsequent calls // for either value of outgoing. - ASSERT( + XRPL_ASSERT( size <= totalLineCount_, "ripple::RippleLineCache::getRippleLines : maximum lines"); totalLineCount_ -= size; @@ -101,7 +101,7 @@ RippleLineCache::getRippleLines( if (inserted) { - ASSERT( + XRPL_ASSERT( it->second == nullptr, "ripple::RippleLineCache::getRippleLines : null lines"); auto lines = @@ -114,7 +114,7 @@ RippleLineCache::getRippleLines( } } - ASSERT( + XRPL_ASSERT( !it->second || (it->second->size() > 0), "ripple::RippleLineCache::getRippleLines : null or nonempty lines"); auto const size = it->second ? it->second->size() : 0; diff --git a/src/xrpld/app/paths/detail/AMMLiquidity.cpp b/src/xrpld/app/paths/detail/AMMLiquidity.cpp index 88600e2cc66..813554ba7ff 100644 --- a/src/xrpld/app/paths/detail/AMMLiquidity.cpp +++ b/src/xrpld/app/paths/detail/AMMLiquidity.cpp @@ -77,7 +77,7 @@ AMMLiquidity::generateFibSeqOffer( 196418, 317811, 514229, 832040, 1346269}; // clang-format on - ASSERT( + XRPL_ASSERT( !ammContext_.maxItersReached(), "ripple::AMMLiquidity::generateFibSeqOffer : maximum iterations"); diff --git a/src/xrpld/app/paths/detail/AmountSpec.h b/src/xrpld/app/paths/detail/AmountSpec.h index 5d8264ed4b8..d57e9140f80 100644 --- a/src/xrpld/app/paths/detail/AmountSpec.h +++ b/src/xrpld/app/paths/detail/AmountSpec.h @@ -125,7 +125,8 @@ template <> inline IOUAmount& get(EitherAmount& amt) { - ASSERT(!amt.native, "ripple::get(EitherAmount&) : is not XRP"); + XRPL_ASSERT( + !amt.native, "ripple::get(EitherAmount&) : is not XRP"); return amt.iou; } @@ -133,7 +134,7 @@ template <> inline XRPAmount& get(EitherAmount& amt) { - ASSERT(amt.native, "ripple::get(EitherAmount&) : is XRP"); + XRPL_ASSERT(amt.native, "ripple::get(EitherAmount&) : is XRP"); return amt.xrp; } @@ -149,7 +150,7 @@ template <> inline IOUAmount const& get(EitherAmount const& amt) { - ASSERT( + XRPL_ASSERT( !amt.native, "ripple::get(EitherAmount const&) : is not XRP"); return amt.iou; @@ -159,14 +160,15 @@ template <> inline XRPAmount const& get(EitherAmount const& amt) { - ASSERT(amt.native, "ripple::get(EitherAmount const&) : is XRP"); + XRPL_ASSERT( + amt.native, "ripple::get(EitherAmount const&) : is XRP"); return amt.xrp; } inline AmountSpec toAmountSpec(STAmount const& amt) { - ASSERT( + XRPL_ASSERT( amt.mantissa() < std::numeric_limits::max(), "ripple::toAmountSpec(STAmount const&) : maximum mantissa"); bool const isNeg = amt.negative(); @@ -203,7 +205,7 @@ toAmountSpec(EitherAmount const& ea, std::optional const& c) AmountSpec r; r.native = (!c || isXRP(*c)); r.currency = c; - ASSERT( + XRPL_ASSERT( ea.native == r.native, "ripple::toAmountSpec(EitherAmount const&&, std::optional) : " "matching native"); diff --git a/src/xrpld/app/paths/detail/BookStep.cpp b/src/xrpld/app/paths/detail/BookStep.cpp index 0085d28bb39..1d35f80b183 100644 --- a/src/xrpld/app/paths/detail/BookStep.cpp +++ b/src/xrpld/app/paths/detail/BookStep.cpp @@ -380,8 +380,8 @@ class BookOfferCrossingStep getQuality(std::optional const& limitQuality) { // It's really a programming error if the quality is missing. - ASSERT( - limitQuality.has_value(), + XRPL_ASSERT( + limitQuality, "ripple::BookOfferCrossingStep::getQuality : nonzero quality"); if (!limitQuality) Throw(tefINTERNAL, "Offer requires quality."); @@ -1133,7 +1133,7 @@ BookStep::fwdImp( boost::container::flat_set& ofrsToRm, TIn const& in) { - ASSERT(cache_.has_value(), "ripple::BookStep::fwdImp : cache is set"); + XRPL_ASSERT(cache_, "ripple::BookStep::fwdImp : cache is set"); TAmounts result(beast::zero, beast::zero); @@ -1152,9 +1152,8 @@ BookStep::fwdImp( TOut const& ownerGives, std::uint32_t transferRateIn, std::uint32_t transferRateOut) mutable -> bool { - ASSERT( - cache_.has_value(), - "ripple::BookStep::fwdImp::eachOffer : cache is set"); + XRPL_ASSERT( + cache_, "ripple::BookStep::fwdImp::eachOffer : cache is set"); if (remainingIn <= beast::zero) return false; diff --git a/src/xrpld/app/paths/detail/DirectStep.cpp b/src/xrpld/app/paths/detail/DirectStep.cpp index 3165ecf675e..95e64b337bc 100644 --- a/src/xrpld/app/paths/detail/DirectStep.cpp +++ b/src/xrpld/app/paths/detail/DirectStep.cpp @@ -514,7 +514,7 @@ DirectStepI::revImp( auto const [srcQOut, dstQIn] = qualities(sb, srcDebtDir, StrandDirection::reverse); - ASSERT( + XRPL_ASSERT( static_cast(this)->verifyDstQualityIn(dstQIn), "ripple::DirectStepI : valid destination quality"); @@ -635,7 +635,7 @@ DirectStepI::fwdImp( boost::container::flat_set& /*ofrsToRm*/, IOUAmount const& in) { - ASSERT(cache_.has_value(), "ripple::DirectStepI::fwdImp : cache is set"); + XRPL_ASSERT(cache_, "ripple::DirectStepI::fwdImp : cache is set"); auto const [maxSrcToDst, srcDebtDir] = static_cast(this)->maxFlow(sb, cache_->srcToDst); @@ -722,7 +722,7 @@ DirectStepI::validFwd( auto const savCache = *cache_; - ASSERT(!in.native, "ripple::DirectStepI::validFwd : input is not XRP"); + XRPL_ASSERT(!in.native, "ripple::DirectStepI::validFwd : input is not XRP"); auto const [maxSrcToDst, srcDebtDir] = static_cast(this)->maxFlow(sb, cache_->srcToDst); @@ -786,7 +786,7 @@ DirectStepI::qualitiesSrcIssues( { // Charge a transfer rate when issuing and previous step redeems - ASSERT( + XRPL_ASSERT( static_cast(this)->verifyPrevStepDebtDirection( prevStepDebtDirection), "ripple::DirectStepI::qualitiesSrcIssues : will prevStepDebtDirection " diff --git a/src/xrpld/app/paths/detail/FlowDebugInfo.h b/src/xrpld/app/paths/detail/FlowDebugInfo.h index 1151c42856b..4c3ea5faf1b 100644 --- a/src/xrpld/app/paths/detail/FlowDebugInfo.h +++ b/src/xrpld/app/paths/detail/FlowDebugInfo.h @@ -89,7 +89,7 @@ struct FlowDebugInfo void pushLiquiditySrc(EitherAmount const& eIn, EitherAmount const& eOut) { - ASSERT( + XRPL_ASSERT( !liquiditySrcIn.empty(), "ripple::path::detail::FlowDebugInfo::pushLiquiditySrc : " "non-empty liquidity source"); diff --git a/src/xrpld/app/paths/detail/PaySteps.cpp b/src/xrpld/app/paths/detail/PaySteps.cpp index 24891a2d4bc..b73b1ac8acc 100644 --- a/src/xrpld/app/paths/detail/PaySteps.cpp +++ b/src/xrpld/app/paths/detail/PaySteps.cpp @@ -105,7 +105,7 @@ toStep( return {temBAD_PATH, std::unique_ptr{}}; } - ASSERT( + XRPL_ASSERT( (e2->getNodeType() & STPathElement::typeCurrency) || (e2->getNodeType() & STPathElement::typeIssuer), "ripple::toStep : currency or issuer"); @@ -122,7 +122,7 @@ toStep( return {temBAD_PATH, std::unique_ptr{}}; } - ASSERT(e2->isOffer(), "ripple::toStep : is offer"); + XRPL_ASSERT(e2->isOffer(), "ripple::toStep : is offer"); if (isXRP(outCurrency)) return make_BookStepIX(ctx, curIssue); diff --git a/src/xrpld/app/paths/detail/StepChecks.h b/src/xrpld/app/paths/detail/StepChecks.h index 3c1c883ebf6..2c2fee91cf9 100644 --- a/src/xrpld/app/paths/detail/StepChecks.h +++ b/src/xrpld/app/paths/detail/StepChecks.h @@ -35,7 +35,7 @@ checkFreeze( AccountID const& dst, Currency const& currency) { - ASSERT(src != dst, "ripple::checkFreeze : unequal input accounts"); + XRPL_ASSERT(src != dst, "ripple::checkFreeze : unequal input accounts"); // check freeze if (auto sle = view.read(keylet::account(dst))) diff --git a/src/xrpld/app/paths/detail/StrandFlow.h b/src/xrpld/app/paths/detail/StrandFlow.h index 070c7901eed..0e168b73cce 100644 --- a/src/xrpld/app/paths/detail/StrandFlow.h +++ b/src/xrpld/app/paths/detail/StrandFlow.h @@ -707,7 +707,7 @@ flow( flowDebugInfo->pushLiquiditySrc( EitherAmount(f.in), EitherAmount(f.out)); - ASSERT( + XRPL_ASSERT( f.out <= remainingOut && f.sandbox && (!remainingIn || f.in <= *remainingIn), "ripple::flow : remaining constraints"); @@ -733,7 +733,7 @@ flow( if (baseView.rules().enabled(featureFlowSortStrands)) { - ASSERT(!best, "ripple::flow : best is unset"); + XRPL_ASSERT(!best, "ripple::flow : best is unset"); if (!f.inactive) activeStrands.push(strand); best.emplace(f.in, f.out, std::move(*f.sandbox), *strand, q); @@ -884,7 +884,7 @@ flow( // Handles both cases 1. and 2. // fixFillOrKill amendment: // Handles 2. 1. is handled above and falls through for tfSell. - ASSERT(remainingIn.has_value(), "ripple::flow : nonzero remainingIn"); + XRPL_ASSERT(remainingIn, "ripple::flow : nonzero remainingIn"); if (remainingIn && *remainingIn != beast::zero) return { tecPATH_PARTIAL, diff --git a/src/xrpld/app/paths/detail/XRPEndpointStep.cpp b/src/xrpld/app/paths/detail/XRPEndpointStep.cpp index 27b4b0d7efd..ab211a7c856 100644 --- a/src/xrpld/app/paths/detail/XRPEndpointStep.cpp +++ b/src/xrpld/app/paths/detail/XRPEndpointStep.cpp @@ -281,8 +281,7 @@ XRPEndpointStep::fwdImp( boost::container::flat_set& ofrsToRm, XRPAmount const& in) { - ASSERT( - cache_.has_value(), "ripple::XRPEndpointStep::fwdImp : cache is set"); + XRPL_ASSERT(cache_, "ripple::XRPEndpointStep::fwdImp : cache is set"); auto const balance = static_cast(this)->xrpLiquid(sb); auto const result = isLast_ ? in : std::min(balance, in); @@ -310,7 +309,7 @@ XRPEndpointStep::validFwd( return {false, EitherAmount(XRPAmount(beast::zero))}; } - ASSERT(in.native, "ripple::XRPEndpointStep::validFwd : input is XRP"); + XRPL_ASSERT(in.native, "ripple::XRPEndpointStep::validFwd : input is XRP"); auto const& xrpIn = in.xrp; auto const balance = static_cast(this)->xrpLiquid(sb); diff --git a/src/xrpld/app/rdb/backend/detail/Node.cpp b/src/xrpld/app/rdb/backend/detail/Node.cpp index cd7bab3782a..493e277bfcd 100644 --- a/src/xrpld/app/rdb/backend/detail/Node.cpp +++ b/src/xrpld/app/rdb/backend/detail/Node.cpp @@ -215,7 +215,7 @@ saveValidatedLedger( "ripple::detail::saveValidatedLedger : mismatched account hash"); } - ASSERT( + XRPL_ASSERT( ledger->info().txHash == ledger->txMap().getHash().as_uint256(), "ripple::detail::saveValidatedLedger : transaction hash match"); diff --git a/src/xrpld/app/rdb/detail/Vacuum.cpp b/src/xrpld/app/rdb/detail/Vacuum.cpp index 10bd95177ed..3c61fb5790a 100644 --- a/src/xrpld/app/rdb/detail/Vacuum.cpp +++ b/src/xrpld/app/rdb/detail/Vacuum.cpp @@ -28,7 +28,7 @@ doVacuumDB(DatabaseCon::Setup const& setup, beast::Journal j) boost::filesystem::path dbPath = setup.dataDir / TxDBName; uintmax_t const dbSize = file_size(dbPath); - ASSERT( + XRPL_ASSERT( dbSize != static_cast(-1), "ripple:doVacuumDB : file_size succeeded"); @@ -56,9 +56,8 @@ doVacuumDB(DatabaseCon::Setup const& setup, beast::Journal j) std::cout << "VACUUM beginning. page_size: " << pageSize << std::endl; session << "VACUUM;"; - ASSERT( - setup.globalPragma != nullptr, - "ripple:doVacuumDB : non-null global pragma"); + XRPL_ASSERT( + setup.globalPragma, "ripple:doVacuumDB : non-null global pragma"); for (auto const& p : *setup.globalPragma) session << p; session << "PRAGMA page_size;", soci::into(pageSize); diff --git a/src/xrpld/app/tx/detail/AMMBid.cpp b/src/xrpld/app/tx/detail/AMMBid.cpp index 29ac826a5de..8b93ed02c36 100644 --- a/src/xrpld/app/tx/detail/AMMBid.cpp +++ b/src/xrpld/app/tx/detail/AMMBid.cpp @@ -181,7 +181,7 @@ applyBid( } else { - ASSERT( + XRPL_ASSERT( ammSle->isFieldPresent(sfAuctionSlot), "ripple::applyBid : has auction slot"); if (!ammSle->isFieldPresent(sfAuctionSlot)) @@ -306,7 +306,7 @@ applyBid( { // Price the slot was purchased at. STAmount const pricePurchased = auctionSlot[sfPrice]; - ASSERT(timeSlot.has_value(), "ripple::applyBid : timeSlot is set"); + XRPL_ASSERT(timeSlot, "ripple::applyBid : timeSlot is set"); auto const fractionUsed = (Number(*timeSlot) + 1) / AUCTION_SLOT_TIME_INTERVALS; auto const fractionRemaining = Number(1) - fractionUsed; diff --git a/src/xrpld/app/tx/detail/AMMDeposit.cpp b/src/xrpld/app/tx/detail/AMMDeposit.cpp index 21d48d42c9a..9766a9ad2fe 100644 --- a/src/xrpld/app/tx/detail/AMMDeposit.cpp +++ b/src/xrpld/app/tx/detail/AMMDeposit.cpp @@ -466,7 +466,7 @@ AMMDeposit::applyGuts(Sandbox& sb) if (result == tesSUCCESS) { - ASSERT( + XRPL_ASSERT( newLPTokenBalance > beast::zero, "ripple::AMMDeposit::applyGuts : valid new LP token balance"); ammSle->setFieldAmount(sfLPTokenBalance, newLPTokenBalance); diff --git a/src/xrpld/app/tx/detail/AMMVote.cpp b/src/xrpld/app/tx/detail/AMMVote.cpp index 1269bf4c383..7e1dc4861d4 100644 --- a/src/xrpld/app/tx/detail/AMMVote.cpp +++ b/src/xrpld/app/tx/detail/AMMVote.cpp @@ -200,7 +200,7 @@ applyVote( } } - ASSERT( + XRPL_ASSERT( !ctx_.view().rules().enabled(fixInnerObjTemplate) || ammSle->isFieldPresent(sfAuctionSlot), "ripple::applyVote : has auction slot"); diff --git a/src/xrpld/app/tx/detail/AMMWithdraw.cpp b/src/xrpld/app/tx/detail/AMMWithdraw.cpp index d1cfebe0639..eec9f096bfa 100644 --- a/src/xrpld/app/tx/detail/AMMWithdraw.cpp +++ b/src/xrpld/app/tx/detail/AMMWithdraw.cpp @@ -877,7 +877,7 @@ AMMWithdraw::equalWithdrawLimit( frac = Number{amount2} / amount2Balance; auto const amountWithdraw = amountBalance * frac; - ASSERT( + XRPL_ASSERT( amountWithdraw <= amount, "ripple::AMMWithdraw::equalWithdrawLimit : maximum amountWithdraw"); return withdraw( diff --git a/src/xrpld/app/tx/detail/ApplyContext.cpp b/src/xrpld/app/tx/detail/ApplyContext.cpp index 925da7aaf48..620c286bd73 100644 --- a/src/xrpld/app/tx/detail/ApplyContext.cpp +++ b/src/xrpld/app/tx/detail/ApplyContext.cpp @@ -146,7 +146,7 @@ ApplyContext::checkInvariantsHelper( TER ApplyContext::checkInvariants(TER const result, XRPAmount const fee) { - ASSERT( + XRPL_ASSERT( isTesSuccess(result) || isTecClaim(result), "ripple::ApplyContext::checkInvariants : is tesSUCCESS or tecCLAIM"); diff --git a/src/xrpld/app/tx/detail/Change.cpp b/src/xrpld/app/tx/detail/Change.cpp index d2772d6966e..45834742c8e 100644 --- a/src/xrpld/app/tx/detail/Change.cpp +++ b/src/xrpld/app/tx/detail/Change.cpp @@ -157,7 +157,7 @@ Change::doApply() void Change::preCompute() { - ASSERT( + XRPL_ASSERT( account_ == beast::zero, "ripple::Change::preCompute : zero account"); } diff --git a/src/xrpld/app/tx/detail/CreateOffer.cpp b/src/xrpld/app/tx/detail/CreateOffer.cpp index 578600621f2..52ca602b956 100644 --- a/src/xrpld/app/tx/detail/CreateOffer.cpp +++ b/src/xrpld/app/tx/detail/CreateOffer.cpp @@ -210,7 +210,7 @@ CreateOffer::checkAcceptAsset( Issue const& issue) { // Only valid for custom currencies - ASSERT( + XRPL_ASSERT( !isXRP(issue.currency), "ripple::CreateOffer::checkAcceptAsset : input is not XRP"); @@ -285,7 +285,7 @@ CreateOffer::select_path( OfferStream const& leg2) { // If we don't have any viable path, why are we here?! - ASSERT( + XRPL_ASSERT( have_direct || have_bridge, "ripple::CreateOffer::select_path : valid inputs"); @@ -331,7 +331,7 @@ CreateOffer::bridged_cross( { auto const& takerAmount = taker.original_offer(); - ASSERT( + XRPL_ASSERT( !isXRP(takerAmount.in) && !isXRP(takerAmount.out), "ripple::CreateOffer::bridged_cross : neither is XRP"); @@ -503,7 +503,7 @@ CreateOffer::bridged_cross( // Postcondition: If we aren't done, then we *must* have consumed at // least one offer fully. - ASSERT( + XRPL_ASSERT( direct_consumed || leg1_consumed || leg2_consumed, "ripple::CreateOffer::bridged_cross : consumed an offer"); @@ -595,7 +595,7 @@ CreateOffer::direct_cross( // Postcondition: If we aren't done, then we *must* have consumed the // offer on the books fully! - ASSERT( + XRPL_ASSERT( direct_consumed, "ripple::CreateOffer::direct_cross : consumed an offer"); @@ -859,7 +859,7 @@ CreateOffer::flowCross( // remaining output. This too preserves the offer // Quality. afterCross.out -= result.actualAmountOut; - ASSERT( + XRPL_ASSERT( afterCross.out >= beast::zero, "ripple::CreateOffer::flowCross : minimum offer"); if (afterCross.out < beast::zero) @@ -1058,7 +1058,7 @@ CreateOffer::applyGuts(Sandbox& sb, Sandbox& sbCancel) // We expect the implementation of cross to succeed // or give a tec. - ASSERT( + XRPL_ASSERT( result == tesSUCCESS || isTecClaim(result), "ripple::CreateOffer::applyGuts : result is tesSUCCESS or " "tecCLAIM"); @@ -1079,10 +1079,10 @@ CreateOffer::applyGuts(Sandbox& sb, Sandbox& sbCancel) return {result, true}; } - ASSERT( + XRPL_ASSERT( saTakerGets.issue() == place_offer.in.issue(), "ripple::CreateOffer::applyGuts : taker gets issue match"); - ASSERT( + XRPL_ASSERT( saTakerPays.issue() == place_offer.out.issue(), "ripple::CreateOffer::applyGuts : taker pays issue match"); @@ -1112,7 +1112,7 @@ CreateOffer::applyGuts(Sandbox& sb, Sandbox& sbCancel) saTakerGets = place_offer.in; } - ASSERT( + XRPL_ASSERT( saTakerPays > zero && saTakerGets > zero, "ripple::CreateOffer::applyGuts : taker pays and gets positive"); diff --git a/src/xrpld/app/tx/detail/DeleteAccount.cpp b/src/xrpld/app/tx/detail/DeleteAccount.cpp index 9dbab905d13..18ddf01a8d7 100644 --- a/src/xrpld/app/tx/detail/DeleteAccount.cpp +++ b/src/xrpld/app/tx/detail/DeleteAccount.cpp @@ -243,9 +243,8 @@ DeleteAccount::preclaim(PreclaimContext const& ctx) } auto sleAccount = ctx.view.read(keylet::account(account)); - ASSERT( - sleAccount != nullptr, - "ripple::DeleteAccount::preclaim : non-null account"); + XRPL_ASSERT( + sleAccount, "ripple::DeleteAccount::preclaim : non-null account"); if (!sleAccount) return terNO_ACCOUNT; @@ -348,15 +347,13 @@ TER DeleteAccount::doApply() { auto src = view().peek(keylet::account(account_)); - ASSERT( - src != nullptr, - "ripple::DeleteAccount::doApply : non-null source account"); + XRPL_ASSERT( + src, "ripple::DeleteAccount::doApply : non-null source account"); auto const dstID = ctx_.tx[sfDestination]; auto dst = view().peek(keylet::account(dstID)); - ASSERT( - dst != nullptr, - "ripple::DeleteAccount::doApply : non-null destination account"); + XRPL_ASSERT( + dst, "ripple::DeleteAccount::doApply : non-null destination account"); if (!src || !dst) return tefBAD_LEDGER; @@ -400,7 +397,7 @@ DeleteAccount::doApply() (*src)[sfBalance] = (*src)[sfBalance] - mSourceBalance; ctx_.deliver(mSourceBalance); - ASSERT( + XRPL_ASSERT( (*src)[sfBalance] == XRPAmount(0), "ripple::DeleteAccount::doApply : source balance is zero"); diff --git a/src/xrpld/app/tx/detail/InvariantCheck.cpp b/src/xrpld/app/tx/detail/InvariantCheck.cpp index 7698402ffc2..def7914a49b 100644 --- a/src/xrpld/app/tx/detail/InvariantCheck.cpp +++ b/src/xrpld/app/tx/detail/InvariantCheck.cpp @@ -400,7 +400,7 @@ AccountRootsDeletedClean::finalize( JLOG(j.fatal()) << "Invariant failed: account deletion left behind a " << typeName << " object"; - ASSERT( + XRPL_ASSERT( enforce, "ripple::AccountRootsDeletedClean::finalize::objectExists : " "account deletion left no objects behind"); diff --git a/src/xrpld/app/tx/detail/NFTokenMint.cpp b/src/xrpld/app/tx/detail/NFTokenMint.cpp index b903563dff7..5699a29c039 100644 --- a/src/xrpld/app/tx/detail/NFTokenMint.cpp +++ b/src/xrpld/app/tx/detail/NFTokenMint.cpp @@ -160,7 +160,7 @@ NFTokenMint::createNFTokenID( std::memcpy(ptr, &tokenSeq, sizeof(tokenSeq)); ptr += sizeof(tokenSeq); - ASSERT( + XRPL_ASSERT( std::distance(buf.data(), ptr) == buf.size(), "ripple::NFTokenMint::createNFTokenID : data size matches the buffer"); diff --git a/src/xrpld/app/tx/detail/NFTokenUtils.cpp b/src/xrpld/app/tx/detail/NFTokenUtils.cpp index 38378b7ff9e..07edfe1b79a 100644 --- a/src/xrpld/app/tx/detail/NFTokenUtils.cpp +++ b/src/xrpld/app/tx/detail/NFTokenUtils.cpp @@ -191,7 +191,7 @@ getPageForToken( : carr[0].getFieldH256(sfNFTokenID); auto np = std::make_shared(keylet::nftpage(base, tokenIDForNewPage)); - ASSERT( + XRPL_ASSERT( np->key() > base.key, "ripple::nft::getPageForToken : valid NFT page index"); np->setFieldArray(sfNFTokens, narr); @@ -245,7 +245,7 @@ compareTokens(uint256 const& a, uint256 const& b) TER insertToken(ApplyView& view, AccountID owner, STObject&& nft) { - ASSERT( + XRPL_ASSERT( nft.isFieldPresent(sfNFTokenID), "ripple::nft::insertToken : has NFT token"); @@ -787,8 +787,8 @@ repairNFTokenDirectoryLinks(ApplyView& view, AccountID const& owner) return didRepair; } - ASSERT( - nextPage != nullptr, + XRPL_ASSERT( + nextPage, "ripple::nft::repairNFTokenDirectoryLinks : next page is available"); if (nextPage->isFieldPresent(sfNextPageMin)) { @@ -897,9 +897,8 @@ tokenOfferCreatePreclaim( if (nftIssuer != acctID && !(nftFlags & nft::flagTransferable)) { auto const root = view.read(keylet::account(nftIssuer)); - ASSERT( - root != nullptr, - "ripple::nft::tokenOfferCreatePreclaim : non-null account"); + XRPL_ASSERT( + root, "ripple::nft::tokenOfferCreatePreclaim : non-null account"); if (auto minter = (*root)[~sfNFTokenMinter]; minter != acctID) return tefNFTOKEN_IS_NOT_TRANSFERABLE; diff --git a/src/xrpld/app/tx/detail/OfferStream.cpp b/src/xrpld/app/tx/detail/OfferStream.cpp index 2fb9ad6a143..ea18306234b 100644 --- a/src/xrpld/app/tx/detail/OfferStream.cpp +++ b/src/xrpld/app/tx/detail/OfferStream.cpp @@ -51,7 +51,7 @@ TOfferStreamBase::TOfferStreamBase( , tip_(view, book_) , counter_(counter) { - ASSERT( + XRPL_ASSERT( validBook_, "ripple::TOfferStreamBase::TOfferStreamBase : valid book"); } diff --git a/src/xrpld/app/tx/detail/PayChan.cpp b/src/xrpld/app/tx/detail/PayChan.cpp index 388a5f0c028..aa248075d56 100644 --- a/src/xrpld/app/tx/detail/PayChan.cpp +++ b/src/xrpld/app/tx/detail/PayChan.cpp @@ -150,7 +150,7 @@ closeChannel( if (!sle) return tefINTERNAL; - ASSERT( + XRPL_ASSERT( (*slep)[sfAmount] >= (*slep)[sfBalance], "ripple::closeChannel : minimum channel amount"); (*sle)[sfBalance] = @@ -548,7 +548,7 @@ PayChanClaim::doApply() (*slep)[sfBalance] = ctx_.tx[sfBalance]; XRPAmount const reqDelta = reqBalance - chanBalance; - ASSERT( + XRPL_ASSERT( reqDelta >= beast::zero, "ripple::PayChanClaim::doApply : minimum balance delta"); (*sled)[sfBalance] = (*sled)[sfBalance] + reqDelta; diff --git a/src/xrpld/app/tx/detail/Payment.cpp b/src/xrpld/app/tx/detail/Payment.cpp index d6f7c60fabc..1ed3bacbbd8 100644 --- a/src/xrpld/app/tx/detail/Payment.cpp +++ b/src/xrpld/app/tx/detail/Payment.cpp @@ -525,7 +525,7 @@ Payment::doApply() return res; } - ASSERT(dstAmount.native(), "ripple::Payment::doApply : amount is XRP"); + XRPL_ASSERT(dstAmount.native(), "ripple::Payment::doApply : amount is XRP"); // Direct XRP payment. diff --git a/src/xrpld/app/tx/detail/SetSignerList.cpp b/src/xrpld/app/tx/detail/SetSignerList.cpp index 9c4fcd0e6c1..a74b0f7351c 100644 --- a/src/xrpld/app/tx/detail/SetSignerList.cpp +++ b/src/xrpld/app/tx/detail/SetSignerList.cpp @@ -137,10 +137,10 @@ SetSignerList::preCompute() { // Get the quorum and operation info. auto result = determineOperation(ctx_.tx, view().flags(), j_); - ASSERT( + XRPL_ASSERT( std::get<0>(result) == tesSUCCESS, "ripple::SetSignerList::preCompute : result is tesSUCCESS"); - ASSERT( + XRPL_ASSERT( std::get<3>(result) != unknown, "ripple::SetSignerList::preCompute : result is known operation"); @@ -175,10 +175,10 @@ signerCountBasedOwnerCountDelta(std::size_t entryCount, Rules const& rules) // The static_cast should always be safe since entryCount should always // be in the range from 1 to 8 (or 32 if ExpandedSignerList is enabled). // We've got a lot of room to grow. - ASSERT( + XRPL_ASSERT( entryCount >= STTx::minMultiSigners, "ripple::signerCountBasedOwnerCountDelta : minimum signers"); - ASSERT( + XRPL_ASSERT( entryCount <= STTx::maxMultiSigners(&rules), "ripple::signerCountBasedOwnerCountDelta : maximum signers"); return 2 + static_cast(entryCount); @@ -268,7 +268,7 @@ SetSignerList::validateQuorumAndSignerEntries( } // Make sure there are no duplicate signers. - ASSERT( + XRPL_ASSERT( std::is_sorted(signers.begin(), signers.end()), "ripple::SetSignerList::validateQuorumAndSignerEntries : sorted " "signers"); diff --git a/src/xrpld/app/tx/detail/Taker.cpp b/src/xrpld/app/tx/detail/Taker.cpp index 6e4b7f5cd57..e98d65fd114 100644 --- a/src/xrpld/app/tx/detail/Taker.cpp +++ b/src/xrpld/app/tx/detail/Taker.cpp @@ -54,34 +54,32 @@ BasicTaker::BasicTaker( , cross_type_(cross_type) , journal_(journal) { - ASSERT( + XRPL_ASSERT( remaining_.in > beast::zero, "ripple::BasicTaker::BasicTaker : positive remaining in"); - ASSERT( + XRPL_ASSERT( remaining_.out > beast::zero, "ripple::BasicTaker::BasicTaker : positive remaining out"); - ASSERT( - m_rate_in.value != 0, - "ripple::BasicTaker::BasicTaker : nonzero rate in"); - ASSERT( - m_rate_out.value != 0, - "ripple::BasicTaker::BasicTaker : nonzero rate out"); + XRPL_ASSERT( + m_rate_in.value, "ripple::BasicTaker::BasicTaker : nonzero rate in"); + XRPL_ASSERT( + m_rate_out.value, "ripple::BasicTaker::BasicTaker : nonzero rate out"); // If we are dealing with a particular flavor, make sure that it's the // flavor we expect: - ASSERT( + XRPL_ASSERT( cross_type != CrossType::XrpToIou || (isXRP(issue_in()) && !isXRP(issue_out())), "ripple::BasicTaker::BasicTaker : valid cross to IOU"); - ASSERT( + XRPL_ASSERT( cross_type != CrossType::IouToXrp || (!isXRP(issue_in()) && isXRP(issue_out())), "ripple::BasicTaker::BasicTaker : valid cross to XRP"); // And make sure we're not crossing XRP for XRP - ASSERT( + XRPL_ASSERT( !isXRP(issue_in()) || !isXRP(issue_out()), "ripple::BasicTaker::BasicTaker : not crossing XRP for XRP"); @@ -162,7 +160,7 @@ BasicTaker::remaining_offer() const if (sell_) { - ASSERT( + XRPL_ASSERT( remaining_.in > beast::zero, "ripple::BasicTaker::remaining_offer : positive remaining in"); @@ -172,7 +170,7 @@ BasicTaker::remaining_offer() const divRound(remaining_.in, quality_.rate(), issue_out_, true)); } - ASSERT( + XRPL_ASSERT( remaining_.out > beast::zero, "ripple::BasicTaker::remaining_offer : positive remaining out"); @@ -440,7 +438,7 @@ BasicTaker::do_cross(Amounts offer, Quality quality, AccountID const& owner) remaining_.out -= result.order.out; remaining_.in -= result.order.in; - ASSERT( + XRPL_ASSERT( remaining_.in >= beast::zero, "ripple::BasicTaker::do_cross : minimum remaining in"); @@ -457,15 +455,15 @@ BasicTaker::do_cross( Quality quality2, AccountID const& owner2) { - ASSERT( + XRPL_ASSERT( !offer1.in.native(), "ripple::BasicTaker::do_cross : offer1 in is not XRP"); - ASSERT( + XRPL_ASSERT( offer1.out.native(), "ripple::BasicTaker::do_cross : offer1 out is XRP"); - ASSERT( + XRPL_ASSERT( offer2.in.native(), "ripple::BasicTaker::do_cross : offer2 in is XRP"); - ASSERT( + XRPL_ASSERT( !offer2.out.native(), "ripple::BasicTaker::do_cross : offer2 out is not XRP"); @@ -584,10 +582,10 @@ Taker::Taker( , direct_crossings_(0) , bridge_crossings_(0) { - ASSERT( + XRPL_ASSERT( issue_in() == offer.in.issue(), "ripple::Taker::Taker : issue in is a match"); - ASSERT( + XRPL_ASSERT( issue_out() == offer.out.issue(), "ripple::Taker::Taker : issue out is a match"); @@ -718,7 +716,7 @@ Taker::fill(BasicTaker::Flow const& flow, Offer& offer) if (cross_type() != CrossType::XrpToIou) { - ASSERT( + XRPL_ASSERT( !isXRP(flow.order.in), "ripple::Taker::fill : order in is not XRP"); if (result == tesSUCCESS) @@ -731,7 +729,8 @@ Taker::fill(BasicTaker::Flow const& flow, Offer& offer) } else { - ASSERT(isXRP(flow.order.in), "ripple::Taker::fill : order in is XRP"); + XRPL_ASSERT( + isXRP(flow.order.in), "ripple::Taker::fill : order in is XRP"); if (result == tesSUCCESS) result = transferXRP(account(), offer.owner(), flow.order.in); @@ -740,7 +739,7 @@ Taker::fill(BasicTaker::Flow const& flow, Offer& offer) // Now send funds from the account whose offer we're taking if (cross_type() != CrossType::IouToXrp) { - ASSERT( + XRPL_ASSERT( !isXRP(flow.order.out), "ripple::Taker::fill : order out is not XRP"); @@ -754,7 +753,8 @@ Taker::fill(BasicTaker::Flow const& flow, Offer& offer) } else { - ASSERT(isXRP(flow.order.out), "ripple::Taker::fill : order out is XRP"); + XRPL_ASSERT( + isXRP(flow.order.out), "ripple::Taker::fill : order out is XRP"); if (result == tesSUCCESS) result = transferXRP(offer.owner(), account(), flow.order.out); diff --git a/src/xrpld/app/tx/detail/Transactor.cpp b/src/xrpld/app/tx/detail/Transactor.cpp index 7e965e3cbe0..df3d32f8a58 100644 --- a/src/xrpld/app/tx/detail/Transactor.cpp +++ b/src/xrpld/app/tx/detail/Transactor.cpp @@ -368,9 +368,8 @@ Transactor::checkPriorTxAndLastLedger(PreclaimContext const& ctx) TER Transactor::consumeSeqProxy(SLE::pointer const& sleAccount) { - ASSERT( - sleAccount != nullptr, - "ripple::Transactor::consumeSeqProxy : non-null account"); + XRPL_ASSERT( + sleAccount, "ripple::Transactor::consumeSeqProxy : non-null account"); SeqProxy const seqProx = ctx_.tx.getSeqProxy(); if (seqProx.isSeq()) { @@ -442,7 +441,7 @@ Transactor::ticketDelete( void Transactor::preCompute() { - ASSERT( + XRPL_ASSERT( account_ != beast::zero, "ripple::Transactor::preCompute : nonzero account"); } @@ -458,7 +457,7 @@ Transactor::apply() // sle must exist except for transactions // that allow zero account. - ASSERT( + XRPL_ASSERT( sle != nullptr || account_ == beast::zero, "ripple::Transactor::apply : non-null SLE or zero account"); @@ -585,10 +584,10 @@ Transactor::checkMultiSign(PreclaimContext const& ctx) // We have plans to support multiple SignerLists in the future. The // presence and defaulted value of the SignerListID field will enable that. - ASSERT( + XRPL_ASSERT( sleAccountSigners->isFieldPresent(sfSignerListID), "ripple::Transactor::checkMultiSign : has signer list ID"); - ASSERT( + XRPL_ASSERT( sleAccountSigners->getFieldU32(sfSignerListID) == 0, "ripple::Transactor::checkMultiSign : signer list ID is 0"); @@ -826,7 +825,7 @@ Transactor::reset(XRPAmount fee) auto const balance = txnAcct->getFieldAmount(sfBalance).xrp(); // balance should have already been checked in checkFee / preFlight. - ASSERT( + XRPL_ASSERT( balance != beast::zero && (!view().open() || balance >= fee), "ripple::Transactor::reset : valid balance"); @@ -843,7 +842,7 @@ Transactor::reset(XRPAmount fee) // reject the transaction. txnAcct->setFieldAmount(sfBalance, balance - fee); TER const ter{consumeSeqProxy(txnAcct)}; - ASSERT( + XRPL_ASSERT( isTesSuccess(ter), "ripple::Transactor::reset : result is tesSUCCESS"); if (isTesSuccess(ter)) @@ -902,7 +901,7 @@ Transactor::operator()() // No transaction can return temUNKNOWN from apply, // and it can't be passed in from a preclaim. - ASSERT( + XRPL_ASSERT( result != temUNKNOWN, "ripple::Transactor::operator() : result is not temUNKNOWN"); @@ -960,7 +959,7 @@ Transactor::operator()() std::shared_ptr const& after) { if (isDelete) { - ASSERT( + XRPL_ASSERT( before && after, "ripple::Transactor::operator()::visit : non-null SLE " "inputs"); diff --git a/src/xrpld/app/tx/detail/XChainBridge.cpp b/src/xrpld/app/tx/detail/XChainBridge.cpp index b5cf636f160..0c6be61040c 100644 --- a/src/xrpld/app/tx/detail/XChainBridge.cpp +++ b/src/xrpld/app/tx/detail/XChainBridge.cpp @@ -440,9 +440,7 @@ transferHelper( if (amt.native()) { auto const sleSrc = psb.peek(keylet::account(src)); - ASSERT( - sleSrc != nullptr, - "ripple::transferHelper : non-null source account"); + XRPL_ASSERT(sleSrc, "ripple::transferHelper : non-null source account"); if (!sleSrc) return tecINTERNAL; diff --git a/src/xrpld/app/tx/detail/applySteps.cpp b/src/xrpld/app/tx/detail/applySteps.cpp index 24d6d6bb61f..bf492f540ba 100644 --- a/src/xrpld/app/tx/detail/applySteps.cpp +++ b/src/xrpld/app/tx/detail/applySteps.cpp @@ -235,7 +235,7 @@ TxConsequences::TxConsequences(NotTEC pfresult) , seqProx_(SeqProxy::sequence(0)) , sequencesConsumed_(0) { - ASSERT( + XRPL_ASSERT( !isTesSuccess(pfresult), "ripple::TxConsequences::TxConsequences : is not tesSUCCESS"); } diff --git a/src/xrpld/consensus/Consensus.h b/src/xrpld/consensus/Consensus.h index 7b8d03f48a7..daad520c77f 100644 --- a/src/xrpld/consensus/Consensus.h +++ b/src/xrpld/consensus/Consensus.h @@ -863,7 +863,7 @@ Consensus::gotTxSet( { // Our position is added to acquired_ as soon as we create it, // so this txSet must differ - ASSERT( + XRPL_ASSERT( id != result_->position.position(), "ripple::Consensus::gotTxSet : updated transaction set"); bool any = false; @@ -1010,7 +1010,7 @@ template void Consensus::handleWrongLedger(typename Ledger_t::ID const& lgrId) { - ASSERT( + XRPL_ASSERT( lgrId != prevLedgerID_ || previousLedger_.id() != lgrId, "ripple::Consensus::handleWrongLedger : have wrong ledger"); @@ -1263,9 +1263,7 @@ void Consensus::phaseEstablish() { // can only establish consensus if we already took a stance - ASSERT( - result_.has_value(), - "ripple::Consensus::phaseEstablish : result is set"); + XRPL_ASSERT(result_, "ripple::Consensus::phaseEstablish : result is set"); using namespace std::chrono; ConsensusParms const& parms = adaptor_.parms(); @@ -1313,7 +1311,7 @@ void Consensus::closeLedger() { // We should not be closing if we already have a position - ASSERT(!result_, "ripple::Consensus::closeLedger : result is not set"); + XRPL_ASSERT(!result_, "ripple::Consensus::closeLedger : result is not set"); phase_ = ConsensusPhase::establish; JLOG(j_.debug()) << "transitioned to ConsensusPhase::establish"; @@ -1366,9 +1364,8 @@ void Consensus::updateOurPositions() { // We must have a position if we are updating it - ASSERT( - result_.has_value(), - "ripple::Consensus::updateOurPositions : result is set"); + XRPL_ASSERT( + result_, "ripple::Consensus::updateOurPositions : result is set"); ConsensusParms const& parms = adaptor_.parms(); // Compute a cutoff time @@ -1552,8 +1549,7 @@ bool Consensus::haveConsensus() { // Must have a stance if we are checking for consensus - ASSERT( - result_.has_value(), "ripple::Consensus::haveConsensus : has result"); + XRPL_ASSERT(result_, "ripple::Consensus::haveConsensus : has result"); // CHECKME: should possibly count unacquired TX sets as disagreeing int agree = 0, disagree = 0; @@ -1628,9 +1624,7 @@ void Consensus::createDisputes(TxSet_t const& o) { // Cannot create disputes without our stance - ASSERT( - result_.has_value(), - "ripple::Consensus::createDisputes : result is set"); + XRPL_ASSERT(result_, "ripple::Consensus::createDisputes : result is set"); // Only create disputes if this is a new set if (!result_->compares.emplace(o.id()).second) @@ -1651,7 +1645,7 @@ Consensus::createDisputes(TxSet_t const& o) { ++dc; // create disputed transactions (from the ledger that has them) - ASSERT( + XRPL_ASSERT( (inThisSet && result_->txns.find(txId) && !o.find(txId)) || (!inThisSet && !result_->txns.find(txId) && o.find(txId)), "ripple::Consensus::createDisputes : has disputed transactions"); @@ -1690,9 +1684,7 @@ void Consensus::updateDisputes(NodeID_t const& node, TxSet_t const& other) { // Cannot updateDisputes without our stance - ASSERT( - result_.has_value(), - "ripple::Consensus::updateDisputes : result is set"); + XRPL_ASSERT(result_, "ripple::Consensus::updateDisputes : result is set"); // Ensure we have created disputes against this set if we haven't seen // it before diff --git a/src/xrpld/consensus/ConsensusTypes.h b/src/xrpld/consensus/ConsensusTypes.h index 15bc858848d..ba8e0a8b1ac 100644 --- a/src/xrpld/consensus/ConsensusTypes.h +++ b/src/xrpld/consensus/ConsensusTypes.h @@ -214,7 +214,7 @@ struct ConsensusResult ConsensusResult(TxSet_t&& s, Proposal_t&& p) : txns{std::move(s)}, position{std::move(p)} { - ASSERT( + XRPL_ASSERT( txns.id() == position.position(), "ripple::ConsensusResult : valid inputs"); } diff --git a/src/xrpld/consensus/LedgerTiming.h b/src/xrpld/consensus/LedgerTiming.h index 57247abe968..b3ef5ee59c2 100644 --- a/src/xrpld/consensus/LedgerTiming.h +++ b/src/xrpld/consensus/LedgerTiming.h @@ -82,7 +82,7 @@ getNextLedgerTimeResolution( bool previousAgree, Seq ledgerSeq) { - ASSERT( + XRPL_ASSERT( ledgerSeq != Seq{0}, "ripple:getNextLedgerTimeResolution : valid ledger sequence"); @@ -92,7 +92,7 @@ getNextLedgerTimeResolution( std::begin(ledgerPossibleTimeResolutions), std::end(ledgerPossibleTimeResolutions), previousResolution); - ASSERT( + XRPL_ASSERT( iter != std::end(ledgerPossibleTimeResolutions), "ripple:getNextLedgerTimeResolution : found time resolution"); diff --git a/src/xrpld/consensus/LedgerTrie.h b/src/xrpld/consensus/LedgerTrie.h index ad1797d51fe..17f9e570b0e 100644 --- a/src/xrpld/consensus/LedgerTrie.h +++ b/src/xrpld/consensus/LedgerTrie.h @@ -64,7 +64,7 @@ class SpanTip ID ancestor(Seq const& s) const { - ASSERT(s <= seq, "ripple::SpanTip::ancestor : valid input"); + XRPL_ASSERT(s <= seq, "ripple::SpanTip::ancestor : valid input"); return ledger[s]; } @@ -90,7 +90,7 @@ class Span Span() : ledger_{typename Ledger::MakeGenesis{}} { // Require default ledger to be genesis seq - ASSERT( + XRPL_ASSERT( ledger_.seq() == start_, "ripple::Span::Span : ledger is genesis"); } @@ -160,7 +160,7 @@ class Span : start_{start}, end_{end}, ledger_{l} { // Spans cannot be empty - ASSERT(start < end, "ripple::Span::Span : non-empty span input"); + XRPL_ASSERT(start < end, "ripple::Span::Span : non-empty span input"); } Seq @@ -233,7 +233,7 @@ struct Node [child](std::unique_ptr const& curr) { return curr.get() == child; }); - ASSERT(it != children.end(), "ripple::Node::erase : valid input"); + XRPL_ASSERT(it != children.end(), "ripple::Node::erase : valid input"); std::swap(*it, children.back()); children.pop_back(); } @@ -374,7 +374,7 @@ class LedgerTrie Node* curr = root.get(); // Root is always defined and is in common with all ledgers - ASSERT(curr != nullptr, "ripple::LedgerTrie::find : non-null root"); + XRPL_ASSERT(curr, "ripple::LedgerTrie::find : non-null root"); Seq pos = curr->span.diff(ledger); bool done = false; @@ -455,8 +455,7 @@ class LedgerTrie auto const [loc, diffSeq] = find(ledger); // There is always a place to insert - ASSERT( - loc != nullptr, "ripple::LedgerTrie::insert : valid input ledger"); + XRPL_ASSERT(loc, "ripple::LedgerTrie::insert : valid input ledger"); // Node from which to start incrementing branchSupport Node* incNode = loc; @@ -491,16 +490,14 @@ class LedgerTrie newNode->tipSupport = loc->tipSupport; newNode->branchSupport = loc->branchSupport; newNode->children = std::move(loc->children); - ASSERT( + XRPL_ASSERT( loc->children.empty(), "ripple::LedgerTrie::insert : moved-from children"); for (std::unique_ptr& child : newNode->children) child->parent = newNode.get(); // Loc truncates to prefix and newNode is its child - ASSERT( - prefix.has_value(), - "ripple::LedgerTrie::insert : prefix is set"); + XRPL_ASSERT(prefix, "ripple::LedgerTrie::insert : prefix is set"); loc->span = *prefix; newNode->parent = loc; loc->children.emplace_back(std::move(newNode)); @@ -553,7 +550,7 @@ class LedgerTrie loc->tipSupport -= count; auto const it = seqSupport.find(ledger.seq()); - ASSERT( + XRPL_ASSERT( it != seqSupport.end() && it->second >= count, "ripple::LedgerTrie::remove : valid input ledger"); it->second -= count; diff --git a/src/xrpld/consensus/Validations.h b/src/xrpld/consensus/Validations.h index 765298d897a..582d36cbcd9 100644 --- a/src/xrpld/consensus/Validations.h +++ b/src/xrpld/consensus/Validations.h @@ -434,7 +434,7 @@ class Validations Validation const& val, std::optional> prior) { - ASSERT( + XRPL_ASSERT( val.trusted(), "ripple::Validations::updateTrie : trusted input validation"); @@ -715,7 +715,8 @@ class Validations setSeqToKeep(Seq const& low, Seq const& high) { std::lock_guard lock{mutex_}; - ASSERT(low < high, "ripple::Validations::setSeqToKeep : valid inputs"); + XRPL_ASSERT( + low < high, "ripple::Validations::setSeqToKeep : valid inputs"); toKeep_ = {low, high}; } diff --git a/src/xrpld/core/Coro.ipp b/src/xrpld/core/Coro.ipp index a046971015e..5901e07c684 100644 --- a/src/xrpld/core/Coro.ipp +++ b/src/xrpld/core/Coro.ipp @@ -53,7 +53,7 @@ JobQueue::Coro::Coro( inline JobQueue::Coro::~Coro() { #ifndef NDEBUG - ASSERT(finished_, "ripple::JobQueue::Coro::~Coro : is finished"); + XRPL_ASSERT(finished_, "ripple::JobQueue::Coro::~Coro : is finished"); #endif } @@ -103,7 +103,7 @@ JobQueue::Coro::resume() auto saved = detail::getLocalValues().release(); detail::getLocalValues().reset(&lvs_); std::lock_guard lock(mutex_); - ASSERT( + XRPL_ASSERT( static_cast(coro_), "ripple::JobQueue::Coro::resume : is runnable"); coro_(); diff --git a/src/xrpld/core/DatabaseCon.h b/src/xrpld/core/DatabaseCon.h index bb6f36d4d56..8c6ba730320 100644 --- a/src/xrpld/core/DatabaseCon.h +++ b/src/xrpld/core/DatabaseCon.h @@ -97,7 +97,7 @@ class DatabaseCon std::vector const* commonPragma() const { - ASSERT( + XRPL_ASSERT( !useGlobalPragma || globalPragma, "ripple::DatabaseCon::Setup::commonPragma : consistent global " "pragma"); diff --git a/src/xrpld/core/JobTypes.h b/src/xrpld/core/JobTypes.h index 5963446cd43..29b096b7a3b 100644 --- a/src/xrpld/core/JobTypes.h +++ b/src/xrpld/core/JobTypes.h @@ -53,7 +53,7 @@ class JobTypes int limit, std::chrono::milliseconds avgLatency, std::chrono::milliseconds peakLatency) { - ASSERT( + XRPL_ASSERT( m_map.find(jt) == m_map.end(), "ripple::JobTypes::JobTypes::add : unique job type input"); @@ -66,7 +66,7 @@ class JobTypes jt, name, limit, avgLatency, peakLatency)) .second; - ASSERT( + XRPL_ASSERT( inserted == true, "ripple::JobTypes::JobTypes::add : input is inserted"); }; @@ -142,7 +142,7 @@ class JobTypes get(JobType jt) const { Map::const_iterator const iter(m_map.find(jt)); - ASSERT(iter != m_map.end(), "ripple::JobTypes::get : valid input"); + XRPL_ASSERT(iter != m_map.end(), "ripple::JobTypes::get : valid input"); if (iter != m_map.end()) return iter->second; diff --git a/src/xrpld/core/detail/Config.cpp b/src/xrpld/core/detail/Config.cpp index b37a931bca0..957ccc767f8 100644 --- a/src/xrpld/core/detail/Config.cpp +++ b/src/xrpld/core/detail/Config.cpp @@ -266,7 +266,8 @@ Config::Config() void Config::setupControl(bool bQuiet, bool bSilent, bool bStandalone) { - ASSERT(NODE_SIZE == 0, "ripple::Config::setupControl : node size not set"); + XRPL_ASSERT( + NODE_SIZE == 0, "ripple::Config::setupControl : node size not set"); QUIET = bQuiet || bSilent; SILENT = bSilent; @@ -287,7 +288,7 @@ Config::setupControl(bool bQuiet, bool bSilent, bool bStandalone) return (limit == 0) || (ramSize_ < limit); }); - ASSERT( + XRPL_ASSERT( ns != threshold.second.end(), "ripple::Config::setupControl : valid node size"); @@ -300,7 +301,8 @@ Config::setupControl(bool bQuiet, bool bSilent, bool bStandalone) NODE_SIZE = std::min(hc / 2, NODE_SIZE); } - ASSERT(NODE_SIZE <= 4, "ripple::Config::setupControl : node size is set"); + XRPL_ASSERT( + NODE_SIZE <= 4, "ripple::Config::setupControl : node size is set"); } void @@ -1006,10 +1008,10 @@ int Config::getValueFor(SizedItem item, std::optional node) const { auto const index = static_cast>(item); - ASSERT( + XRPL_ASSERT( index < sizedItems.size(), "ripple::Config::getValueFor : valid index input"); - ASSERT( + XRPL_ASSERT( !node || *node <= 4, "ripple::Config::getValueFor : unset or valid node"); return sizedItems.at(index).second.at(node.value_or(NODE_SIZE)); diff --git a/src/xrpld/core/detail/DatabaseCon.cpp b/src/xrpld/core/detail/DatabaseCon.cpp index d93a66cfb83..6d49c647a6f 100644 --- a/src/xrpld/core/detail/DatabaseCon.cpp +++ b/src/xrpld/core/detail/DatabaseCon.cpp @@ -231,7 +231,7 @@ setup_DatabaseCon(Config const& c, std::optional j) "nodes storing large amounts of history, because of the " "difficulty inherent in rebuilding corrupted data."; } - ASSERT( + XRPL_ASSERT( result->size() == 3, "ripple::setup_DatabaseCon::globalPragma : result size is 3"); return result; diff --git a/src/xrpld/core/detail/JobQueue.cpp b/src/xrpld/core/detail/JobQueue.cpp index 3e87dd22212..5eb1f24d43a 100644 --- a/src/xrpld/core/detail/JobQueue.cpp +++ b/src/xrpld/core/detail/JobQueue.cpp @@ -55,7 +55,7 @@ JobQueue::JobQueue( std::piecewise_construct, std::forward_as_tuple(jt.type()), std::forward_as_tuple(jt, m_collector, logs))); - ASSERT( + XRPL_ASSERT( result.second == true, "ripple::JobQueue::JobQueue : jobs added"); (void)result.second; @@ -82,12 +82,12 @@ JobQueue::addRefCountedJob( std::string const& name, JobFunction const& func) { - ASSERT( + XRPL_ASSERT( type != jtINVALID, "ripple::JobQueue::addRefCountedJob : valid input job type"); auto iter(m_jobData.find(type)); - ASSERT( + XRPL_ASSERT( iter != m_jobData.end(), "ripple::JobQueue::addRefCountedJob : job type found in jobs"); if (iter == m_jobData.end()) @@ -99,7 +99,7 @@ JobQueue::addRefCountedJob( // FIXME: Workaround incorrect client shutdown ordering // do not add jobs to a queue with no threads - ASSERT( + XRPL_ASSERT( (type >= jtCLIENT && type <= jtCLIENT_WEBSOCKET) || m_workers.getNumberOfThreads() > 0, "ripple::JobQueue::addRefCountedJob : threads available or job " @@ -112,10 +112,10 @@ JobQueue::addRefCountedJob( auto const& job = *result.first; JobType const type(job.getType()); - ASSERT( + XRPL_ASSERT( type != jtINVALID, "ripple::JobQueue::addRefCountedJob : has valid job type"); - ASSERT( + XRPL_ASSERT( m_jobSet.find(job) != m_jobSet.end(), "ripple::JobQueue::addRefCountedJob : job found"); perfLog_.jobQueue(type); @@ -177,7 +177,7 @@ std::unique_ptr JobQueue::makeLoadEvent(JobType t, std::string const& name) { JobDataMap::iterator iter(m_jobData.find(t)); - ASSERT( + XRPL_ASSERT( iter != m_jobData.end(), "ripple::JobQueue::makeLoadEvent : valid job type input"); @@ -194,7 +194,7 @@ JobQueue::addLoadEvents(JobType t, int count, std::chrono::milliseconds elapsed) LogicError("JobQueue::addLoadEvents() called after JobQueue stopped"); JobDataMap::iterator iter(m_jobData.find(t)); - ASSERT( + XRPL_ASSERT( iter != m_jobData.end(), "ripple::JobQueue::addLoadEvents : valid job type input"); iter->second.load().addSamples(count, elapsed); @@ -222,7 +222,7 @@ JobQueue::getJson(int c) for (auto& x : m_jobData) { - ASSERT( + XRPL_ASSERT( x.first != jtINVALID, "ripple::JobQueue::getJson : valid job type"); if (x.first == jtGENERIC) @@ -278,7 +278,7 @@ JobTypeData& JobQueue::getJobTypeData(JobType type) { JobDataMap::iterator c(m_jobData.find(type)); - ASSERT( + XRPL_ASSERT( c != m_jobData.end(), "ripple::JobQueue::getJobTypeData : valid job type input"); @@ -305,11 +305,13 @@ JobQueue::stop() std::unique_lock lock(m_mutex); cv_.wait( lock, [this] { return m_processCount == 0 && m_jobSet.empty(); }); - ASSERT( + XRPL_ASSERT( m_processCount == 0, "ripple::JobQueue::stop : all processes completed"); - ASSERT(m_jobSet.empty(), "ripple::JobQueue::stop : all jobs completed"); - ASSERT(nSuspend_ == 0, "ripple::JobQueue::stop : no coros suspended"); + XRPL_ASSERT( + m_jobSet.empty(), "ripple::JobQueue::stop : all jobs completed"); + XRPL_ASSERT( + nSuspend_ == 0, "ripple::JobQueue::stop : no coros suspended"); stopped_ = true; } } @@ -323,24 +325,25 @@ JobQueue::isStopped() const void JobQueue::getNextJob(Job& job) { - ASSERT(!m_jobSet.empty(), "ripple::JobQueue::getNextJob : non-empty jobs"); + XRPL_ASSERT( + !m_jobSet.empty(), "ripple::JobQueue::getNextJob : non-empty jobs"); std::set::const_iterator iter; for (iter = m_jobSet.begin(); iter != m_jobSet.end(); ++iter) { JobType const type = iter->getType(); - ASSERT( + XRPL_ASSERT( type != jtINVALID, "ripple::JobQueue::getNextJob : valid job type"); JobTypeData& data(getJobTypeData(type)); - ASSERT( + XRPL_ASSERT( data.running <= getJobLimit(type), "ripple::JobQueue::getNextJob : maximum jobs running"); // Run this job if we're running below the limit. if (data.running < getJobLimit(data.type())) { - ASSERT( + XRPL_ASSERT( data.waiting > 0, "ripple::JobQueue::getNextJob : positive data waiting"); --data.waiting; @@ -349,7 +352,7 @@ JobQueue::getNextJob(Job& job) } } - ASSERT( + XRPL_ASSERT( iter != m_jobSet.end(), "ripple::JobQueue::getNextJob : found next job"); job = *iter; @@ -359,7 +362,7 @@ JobQueue::getNextJob(Job& job) void JobQueue::finishJob(JobType type) { - ASSERT( + XRPL_ASSERT( type != jtINVALID, "ripple::JobQueue::finishJob : valid input job type"); @@ -368,7 +371,7 @@ JobQueue::finishJob(JobType type) // Queue a deferred task if possible if (data.deferred > 0) { - ASSERT( + XRPL_ASSERT( data.running + data.waiting >= getJobLimit(type), "ripple::JobQueue::finishJob : job limit"); @@ -436,7 +439,7 @@ int JobQueue::getJobLimit(JobType type) { JobTypeInfo const& j(JobTypes::instance().get(type)); - ASSERT( + XRPL_ASSERT( j.type() != jtINVALID, "ripple::JobQueue::getJobLimit : valid job type"); diff --git a/src/xrpld/core/detail/LoadEvent.cpp b/src/xrpld/core/detail/LoadEvent.cpp index b9c1de79a33..2602c0691fc 100644 --- a/src/xrpld/core/detail/LoadEvent.cpp +++ b/src/xrpld/core/detail/LoadEvent.cpp @@ -83,7 +83,7 @@ LoadEvent::start() void LoadEvent::stop() { - ASSERT(running_, "ripple::LoadEvent::stop : is running"); + XRPL_ASSERT(running_, "ripple::LoadEvent::stop : is running"); auto const now = std::chrono::steady_clock::now(); diff --git a/src/xrpld/core/detail/Workers.cpp b/src/xrpld/core/detail/Workers.cpp index 32e6ace4402..7286f378e85 100644 --- a/src/xrpld/core/detail/Workers.cpp +++ b/src/xrpld/core/detail/Workers.cpp @@ -119,7 +119,7 @@ Workers::stop() m_cv.wait(lk, [this] { return m_allPaused; }); lk.unlock(); - ASSERT( + XRPL_ASSERT( numberOfCurrentlyRunningTasks() == 0, "ripple::Workers::stop : zero running tasks"); } diff --git a/src/xrpld/ledger/detail/ApplyStateTable.cpp b/src/xrpld/ledger/detail/ApplyStateTable.cpp index 2649ac2e207..25ac5d00560 100644 --- a/src/xrpld/ledger/detail/ApplyStateTable.cpp +++ b/src/xrpld/ledger/detail/ApplyStateTable.cpp @@ -155,7 +155,7 @@ ApplyStateTable::apply( meta.setAffectedNode(item.first, *type, nodeType); if (type == &sfDeletedNode) { - ASSERT( + XRPL_ASSERT( origNode && curNode, "ripple::detail::ApplyStateTable::apply : valid nodes for " "deletion"); @@ -190,7 +190,7 @@ ApplyStateTable::apply( } else if (type == &sfModifiedNode) { - ASSERT( + XRPL_ASSERT( curNode && origNode, "ripple::detail::ApplyStateTable::apply : valid nodes for " "modification"); @@ -228,7 +228,7 @@ ApplyStateTable::apply( } else if (type == &sfCreatedNode) // if created, thread to owner(s) { - ASSERT( + XRPL_ASSERT( curNode && !origNode, "ripple::detail::ApplyStateTable::apply : valid nodes for " "creation"); @@ -547,7 +547,7 @@ ApplyStateTable::threadItem(TxMeta& meta, std::shared_ptr const& sle) if (node.getFieldIndex(sfPreviousTxnID) == -1) { - ASSERT( + XRPL_ASSERT( node.getFieldIndex(sfPreviousTxnLgrSeq) == -1, "ripple::ApplyStateTable::threadItem : previous ledger is not " "set"); @@ -555,11 +555,11 @@ ApplyStateTable::threadItem(TxMeta& meta, std::shared_ptr const& sle) node.setFieldU32(sfPreviousTxnLgrSeq, prevLgrID); } - ASSERT( + XRPL_ASSERT( node.getFieldH256(sfPreviousTxnID) == prevTxID, "ripple::ApplyStateTable::threadItem : previous transaction is a " "match"); - ASSERT( + XRPL_ASSERT( node.getFieldU32(sfPreviousTxnLgrSeq) == prevLgrID, "ripple::ApplyStateTable::threadItem : previous ledger is a match"); } @@ -576,8 +576,8 @@ ApplyStateTable::getForMod( auto miter = mods.find(key); if (miter != mods.end()) { - ASSERT( - miter->second != nullptr, + XRPL_ASSERT( + miter->second, "ripple::ApplyStateTable::getForMod : non-null result"); return miter->second; } @@ -634,7 +634,7 @@ ApplyStateTable::threadTx( return; } // threadItem only applied to AccountRoot - ASSERT( + XRPL_ASSERT( sle->isThreadedType(base.rules()), "ripple::ApplyStateTable::threadTx : SLE is threaded"); threadItem(meta, sle); diff --git a/src/xrpld/ledger/detail/BookDirs.cpp b/src/xrpld/ledger/detail/BookDirs.cpp index 4561aa2df18..f584db89e84 100644 --- a/src/xrpld/ledger/detail/BookDirs.cpp +++ b/src/xrpld/ledger/detail/BookDirs.cpp @@ -30,7 +30,8 @@ BookDirs::BookDirs(ReadView const& view, Book const& book) , next_quality_(getQualityNext(root_)) , key_(view_->succ(root_, next_quality_).value_or(beast::zero)) { - ASSERT(root_ != beast::zero, "ripple::BookDirs::BookDirs : nonzero root"); + XRPL_ASSERT( + root_ != beast::zero, "ripple::BookDirs::BookDirs : nonzero root"); if (key_ != beast::zero) { if (!cdirFirst(*view_, key_, sle_, entry_, index_)) @@ -70,7 +71,7 @@ BookDirs::const_iterator::operator==( if (view_ == nullptr || other.view_ == nullptr) return false; - ASSERT( + XRPL_ASSERT( view_ == other.view_ && root_ == other.root_, "ripple::BookDirs::const_iterator::operator== : views and roots are " "matching"); @@ -81,7 +82,7 @@ BookDirs::const_iterator::operator==( BookDirs::const_iterator::reference BookDirs::const_iterator::operator*() const { - ASSERT( + XRPL_ASSERT( index_ != beast::zero, "ripple::BookDirs::const_iterator::operator* : nonzero index"); if (!cache_) @@ -94,7 +95,7 @@ BookDirs::const_iterator::operator++() { using beast::zero; - ASSERT( + XRPL_ASSERT( index_ != zero, "ripple::BookDirs::const_iterator::operator++ : nonzero index"); if (!cdirNext(*view_, cur_key_, sle_, entry_, index_)) @@ -122,7 +123,7 @@ BookDirs::const_iterator::operator++() BookDirs::const_iterator BookDirs::const_iterator::operator++(int) { - ASSERT( + XRPL_ASSERT( index_ != beast::zero, "ripple::BookDirs::const_iterator::operator++(int) : nonzero index"); const_iterator tmp(*this); diff --git a/src/xrpld/ledger/detail/Dir.cpp b/src/xrpld/ledger/detail/Dir.cpp index 24c88a52f09..01d44872762 100644 --- a/src/xrpld/ledger/detail/Dir.cpp +++ b/src/xrpld/ledger/detail/Dir.cpp @@ -60,7 +60,7 @@ const_iterator::operator==(const_iterator const& other) const if (view_ == nullptr || other.view_ == nullptr) return false; - ASSERT( + XRPL_ASSERT( view_ == other.view_ && root_.key == other.root_.key, "ripple::const_iterator::operator== : views and roots are matching"); return page_.key == other.page_.key && index_ == other.index_; @@ -69,7 +69,7 @@ const_iterator::operator==(const_iterator const& other) const const_iterator::reference const_iterator::operator*() const { - ASSERT( + XRPL_ASSERT( index_ != beast::zero, "ripple::const_iterator::operator* : nonzero index"); if (!cache_) @@ -80,7 +80,7 @@ const_iterator::operator*() const const_iterator& const_iterator::operator++() { - ASSERT( + XRPL_ASSERT( index_ != beast::zero, "ripple::const_iterator::operator++ : nonzero index"); if (++it_ != std::end(*indexes_)) @@ -96,7 +96,7 @@ const_iterator::operator++() const_iterator const_iterator::operator++(int) { - ASSERT( + XRPL_ASSERT( index_ != beast::zero, "ripple::const_iterator::operator++(int) : nonzero index"); const_iterator tmp(*this); @@ -117,9 +117,7 @@ const_iterator::next_page() { page_ = keylet::page(root_, next); sle_ = view_->read(page_); - ASSERT( - sle_ != nullptr, - "ripple::const_iterator::next_page : non-null SLE"); + XRPL_ASSERT(sle_, "ripple::const_iterator::next_page : non-null SLE"); indexes_ = &sle_->getFieldV256(sfIndexes); if (indexes_->empty()) { diff --git a/src/xrpld/ledger/detail/PaymentSandbox.cpp b/src/xrpld/ledger/detail/PaymentSandbox.cpp index 3400427448d..745d8a90c7a 100644 --- a/src/xrpld/ledger/detail/PaymentSandbox.cpp +++ b/src/xrpld/ledger/detail/PaymentSandbox.cpp @@ -48,10 +48,10 @@ DeferredCredits::credit( STAmount const& amount, STAmount const& preCreditSenderBalance) { - ASSERT( + XRPL_ASSERT( sender != receiver, "ripple::detail::DeferredCredits::credit : sender is not receiver"); - ASSERT( + XRPL_ASSERT( !amount.negative(), "ripple::detail::DeferredCredits::credit : positive amount"); @@ -256,14 +256,14 @@ PaymentSandbox::adjustOwnerCountHook( void PaymentSandbox::apply(RawView& to) { - ASSERT(!ps_, "ripple::PaymentSandbox::apply : non-null sandbox"); + XRPL_ASSERT(!ps_, "ripple::PaymentSandbox::apply : non-null sandbox"); items_.apply(to); } void PaymentSandbox::apply(PaymentSandbox& to) { - ASSERT(ps_ == &to, "ripple::PaymentSandbox::apply : matching sandbox"); + XRPL_ASSERT(ps_ == &to, "ripple::PaymentSandbox::apply : matching sandbox"); items_.apply(to); tab_.apply(to.tab_); } @@ -347,7 +347,7 @@ PaymentSandbox::balanceChanges(ReadView const& view) const { // modify auto const at = after->getType(); - ASSERT( + XRPL_ASSERT( at == before->getType(), "ripple::PaymentSandbox::balanceChanges : after and before " "types matching"); diff --git a/src/xrpld/ledger/detail/RawStateTable.cpp b/src/xrpld/ledger/detail/RawStateTable.cpp index f8c575fc520..b93fc4a2aa6 100644 --- a/src/xrpld/ledger/detail/RawStateTable.cpp +++ b/src/xrpld/ledger/detail/RawStateTable.cpp @@ -63,7 +63,7 @@ class RawStateTable::sles_iter_impl : public ReadView::sles_type::iter_base { if (auto const p = dynamic_cast(&impl)) { - ASSERT( + XRPL_ASSERT( end1_ == p->end1_ && end0_ == p->end0_, "ripple::detail::RawStateTable::equal : matching end " "iterators"); @@ -76,7 +76,7 @@ class RawStateTable::sles_iter_impl : public ReadView::sles_type::iter_base void increment() override { - ASSERT( + XRPL_ASSERT( sle1_ || sle0_, "ripple::detail::RawStateTable::increment : either SLE is " "non-null"); @@ -185,7 +185,7 @@ RawStateTable::apply(RawView& to) const bool RawStateTable::exists(ReadView const& base, Keylet const& k) const { - ASSERT( + XRPL_ASSERT( k.key.isNonZero(), "ripple::detail::RawStateTable::exists : nonzero key"); auto const iter = items_.find(k.key); diff --git a/src/xrpld/ledger/detail/ReadViewFwdRange.ipp b/src/xrpld/ledger/detail/ReadViewFwdRange.ipp index 844705a3f80..86c1eedfddc 100644 --- a/src/xrpld/ledger/detail/ReadViewFwdRange.ipp +++ b/src/xrpld/ledger/detail/ReadViewFwdRange.ipp @@ -80,7 +80,7 @@ template bool ReadViewFwdRange::iterator::operator==(iterator const& other) const { - ASSERT( + XRPL_ASSERT( view_ == other.view_, "ripple::detail::ReadViewFwdRange::iterator::operator==(iterator) " "const : input view match"); diff --git a/src/xrpld/ledger/detail/View.cpp b/src/xrpld/ledger/detail/View.cpp index 23dbd81d5ad..ebf307f1535 100644 --- a/src/xrpld/ledger/detail/View.cpp +++ b/src/xrpld/ledger/detail/View.cpp @@ -48,7 +48,7 @@ internalDirNext( uint256& entry) { auto const& svIndexes = page->getFieldV256(sfIndexes); - ASSERT( + XRPL_ASSERT( index <= svIndexes.size(), "ripple::detail::internalDirNext : index inside range"); @@ -67,8 +67,7 @@ internalDirNext( else page = view.peek(keylet::page(root, next)); - ASSERT( - page != nullptr, "ripple::detail::internalDirNext : non-null root"); + XRPL_ASSERT(page, "ripple::detail::internalDirNext : non-null root"); if (!page) return false; @@ -421,7 +420,7 @@ confineOwnerCount( << "Account " << *id << " owner count set below 0!"; } adjusted = 0; - ASSERT(!id, "ripple::confineOwnerCount : id is not set"); + XRPL_ASSERT(!id, "ripple::confineOwnerCount : id is not set"); } } return adjusted; @@ -470,7 +469,8 @@ forEachItem( Keylet const& root, std::function const&)> const& f) { - ASSERT(root.type == ltDIR_NODE, "ripple::forEachItem : valid root type"); + XRPL_ASSERT( + root.type == ltDIR_NODE, "ripple::forEachItem : valid root type"); if (root.type != ltDIR_NODE) return; @@ -500,7 +500,7 @@ forEachItemAfter( unsigned int limit, std::function const&)> const& f) { - ASSERT( + XRPL_ASSERT( root.type == ltDIR_NODE, "ripple::forEachItemAfter : valid root type"); if (root.type != ltDIR_NODE) @@ -776,7 +776,7 @@ hashOfSeq(ReadView const& ledger, LedgerIndex seq, beast::Journal journal) auto const hashIndex = ledger.read(keylet::skip()); if (hashIndex) { - ASSERT( + XRPL_ASSERT( hashIndex->getFieldU32(sfLastLedgerSequence) == (ledger.seq() - 1), "ripple::hashOfSeq : matching ledger sequence"); @@ -807,8 +807,9 @@ hashOfSeq(ReadView const& ledger, LedgerIndex seq, beast::Journal journal) if (hashIndex) { auto const lastSeq = hashIndex->getFieldU32(sfLastLedgerSequence); - ASSERT(lastSeq >= seq, "ripple::hashOfSeq : minimum last ledger"); - ASSERT((lastSeq & 0xff) == 0, "ripple::hashOfSeq : valid last ledger"); + XRPL_ASSERT(lastSeq >= seq, "ripple::hashOfSeq : minimum last ledger"); + XRPL_ASSERT( + (lastSeq & 0xff) == 0, "ripple::hashOfSeq : valid last ledger"); auto const diff = (lastSeq - seq) >> 8; STVector256 vec = hashIndex->getFieldV256(sfHashes); if (vec.size() > diff) @@ -834,7 +835,7 @@ adjustOwnerCount( { if (!sle) return; - ASSERT(amount != 0, "ripple::adjustOwnerCount : nonzero amount input"); + XRPL_ASSERT(amount, "ripple::adjustOwnerCount : nonzero amount input"); std::uint32_t const current{sle->getFieldU32(sfOwnerCount)}; AccountID const id = (*sle)[sfAccount]; std::uint32_t const adjusted = confineOwnerCount(current, amount, id, j); @@ -899,11 +900,11 @@ trustCreate( const bool bSetDst = saLimit.getIssuer() == uDstAccountID; const bool bSetHigh = bSrcHigh ^ bSetDst; - ASSERT(sleAccount != nullptr, "ripple::trustCreate : non-null SLE"); + XRPL_ASSERT(sleAccount, "ripple::trustCreate : non-null SLE"); if (!sleAccount) return tefINTERNAL; - ASSERT( + XRPL_ASSERT( sleAccount->getAccountID(sfAccount) == (bSetHigh ? uHighAccountID : uLowAccountID), "ripple::trustCreate : matching account ID"); @@ -1058,23 +1059,23 @@ rippleCreditIOU( Currency const& currency = saAmount.getCurrency(); // Make sure issuer is involved. - ASSERT( + XRPL_ASSERT( !bCheckIssuer || uSenderID == issuer || uReceiverID == issuer, "ripple::rippleCreditIOU : matching issuer or don't care"); (void)issuer; // Disallow sending to self. - ASSERT( + XRPL_ASSERT( uSenderID != uReceiverID, "ripple::rippleCreditIOU : sender is not receiver"); bool const bSenderHigh = uSenderID > uReceiverID; auto const index = keylet::line(uSenderID, uReceiverID, currency); - ASSERT( + XRPL_ASSERT( !isXRP(uSenderID) && uSenderID != noAccount(), "ripple::rippleCreditIOU : sender is not XRP"); - ASSERT( + XRPL_ASSERT( !isXRP(uReceiverID) && uReceiverID != noAccount(), "ripple::rippleCreditIOU : receiver is not XRP"); @@ -1210,10 +1211,10 @@ rippleSendIOU( { auto const issuer = saAmount.getIssuer(); - ASSERT( + XRPL_ASSERT( !isXRP(uSenderID) && !isXRP(uReceiverID), "ripple::rippleSendIOU : neither sender nor receiver is XRP"); - ASSERT( + XRPL_ASSERT( uSenderID != uReceiverID, "ripple::rippleSendIOU : sender is not receiver"); @@ -1268,7 +1269,7 @@ accountSendIOU( } else { - ASSERT( + XRPL_ASSERT( saAmount >= beast::zero && !saAmount.holds(), "ripple::accountSendIOU : minimum amount and not MPT"); } @@ -1440,7 +1441,7 @@ rippleSendMPT( beast::Journal j, WaiveTransferFee waiveFee) { - ASSERT( + XRPL_ASSERT( uSenderID != uReceiverID, "ripple::rippleSendMPT : sender is not receiver"); @@ -1505,7 +1506,7 @@ accountSendMPT( beast::Journal j, WaiveTransferFee waiveFee) { - ASSERT( + XRPL_ASSERT( saAmount >= beast::zero && saAmount.holds(), "ripple::accountSendMPT : minimum amount and MPT"); @@ -1603,15 +1604,16 @@ issueIOU( Issue const& issue, beast::Journal j) { - ASSERT( + XRPL_ASSERT( !isXRP(account) && !isXRP(issue.account), "ripple::issueIOU : neither account nor issuer is XRP"); // Consistency check - ASSERT(issue == amount.issue(), "ripple::issueIOU : matching issue"); + XRPL_ASSERT(issue == amount.issue(), "ripple::issueIOU : matching issue"); // Can't send to self! - ASSERT(issue.account != account, "ripple::issueIOU : not issuer account"); + XRPL_ASSERT( + issue.account != account, "ripple::issueIOU : not issuer account"); JLOG(j.trace()) << "issueIOU: " << to_string(account) << ": " << amount.getFullText(); @@ -1701,15 +1703,16 @@ redeemIOU( Issue const& issue, beast::Journal j) { - ASSERT( + XRPL_ASSERT( !isXRP(account) && !isXRP(issue.account), "ripple::redeemIOU : neither account nor issuer is XRP"); // Consistency check - ASSERT(issue == amount.issue(), "ripple::redeemIOU : matching issue"); + XRPL_ASSERT(issue == amount.issue(), "ripple::redeemIOU : matching issue"); // Can't send to self! - ASSERT(issue.account != account, "ripple::redeemIOU : not issuer account"); + XRPL_ASSERT( + issue.account != account, "ripple::redeemIOU : not issuer account"); JLOG(j.trace()) << "redeemIOU: " << to_string(account) << ": " << amount.getFullText(); @@ -1773,10 +1776,11 @@ transferXRP( STAmount const& amount, beast::Journal j) { - ASSERT(from != beast::zero, "ripple::transferXRP : nonzero from account"); - ASSERT(to != beast::zero, "ripple::transferXRP : nonzero to account"); - ASSERT(from != to, "ripple::transferXRP : sender is not receiver"); - ASSERT(amount.native(), "ripple::transferXRP : amount is XRP"); + XRPL_ASSERT( + from != beast::zero, "ripple::transferXRP : nonzero from account"); + XRPL_ASSERT(to != beast::zero, "ripple::transferXRP : nonzero to account"); + XRPL_ASSERT(from != to, "ripple::transferXRP : sender is not receiver"); + XRPL_ASSERT(amount.native(), "ripple::transferXRP : amount is XRP"); SLE::pointer const sender = view.peek(keylet::account(from)); SLE::pointer const receiver = view.peek(keylet::account(to)); @@ -1939,7 +1943,7 @@ cleanupOnAccountDelete( // // 3. So we verify that uDirEntry is indeed 'it'+1. Then we jam it // back to 'it' to "un-invalidate" the iterator. - ASSERT( + XRPL_ASSERT( uDirEntry >= 1, "ripple::cleanupOnAccountDelete : minimum dir entries"); if (uDirEntry == 0) @@ -2025,7 +2029,7 @@ rippleCredit( } else { - ASSERT( + XRPL_ASSERT( !bCheckIssuer, "ripple::rippleCredit : not checking issuer"); return rippleCreditMPT( diff --git a/src/xrpld/net/detail/InfoSub.cpp b/src/xrpld/net/detail/InfoSub.cpp index 4d18bf0b8fa..e22a3704802 100644 --- a/src/xrpld/net/detail/InfoSub.cpp +++ b/src/xrpld/net/detail/InfoSub.cpp @@ -145,7 +145,7 @@ InfoSub::setApiVersion(unsigned int apiVersion) unsigned int InfoSub::getApiVersion() const noexcept { - ASSERT( + XRPL_ASSERT( apiVersion_ > 0, "ripple::InfoSub::getApiVersion : valid API version"); return apiVersion_; } diff --git a/src/xrpld/net/detail/RPCCall.cpp b/src/xrpld/net/detail/RPCCall.cpp index bbcd4fd52c1..e6e6540b14f 100644 --- a/src/xrpld/net/detail/RPCCall.cpp +++ b/src/xrpld/net/detail/RPCCall.cpp @@ -977,7 +977,7 @@ class RPCParser parseTransactionEntry(Json::Value const& jvParams) { // Parameter count should have already been verified. - ASSERT( + XRPL_ASSERT( jvParams.size() == 2, "ripple::RPCParser::parseTransactionEntry : valid parameter count"); diff --git a/src/xrpld/nodestore/Database.h b/src/xrpld/nodestore/Database.h index 04bd718104d..c22ede82481 100644 --- a/src/xrpld/nodestore/Database.h +++ b/src/xrpld/nodestore/Database.h @@ -246,7 +246,7 @@ class Database void storeStats(std::uint64_t count, std::uint64_t sz) { - ASSERT( + XRPL_ASSERT( count <= sz, "ripple::NodeStore::Database::storeStats : valid inputs"); storeCount_ += count; diff --git a/src/xrpld/nodestore/backend/MemoryFactory.cpp b/src/xrpld/nodestore/backend/MemoryFactory.cpp index 1b7bf79c81e..aac305cea07 100644 --- a/src/xrpld/nodestore/backend/MemoryFactory.cpp +++ b/src/xrpld/nodestore/backend/MemoryFactory.cpp @@ -131,9 +131,8 @@ class MemoryBackend : public Backend Status fetch(void const* key, std::shared_ptr* pObject) override { - ASSERT( - db_ != nullptr, - "ripple::NodeStore::MemoryBackend::fetch : non-null database"); + XRPL_ASSERT( + db_, "ripple::NodeStore::MemoryBackend::fetch : non-null database"); uint256 const hash(uint256::fromVoid(key)); std::lock_guard _(db_->mutex); @@ -169,9 +168,8 @@ class MemoryBackend : public Backend void store(std::shared_ptr const& object) override { - ASSERT( - db_ != nullptr, - "ripple::NodeStore::MemoryBackend::store : non-null database"); + XRPL_ASSERT( + db_, "ripple::NodeStore::MemoryBackend::store : non-null database"); std::lock_guard _(db_->mutex); db_->table.emplace(object->getHash(), object); } @@ -191,8 +189,8 @@ class MemoryBackend : public Backend void for_each(std::function)> f) override { - ASSERT( - db_ != nullptr, + XRPL_ASSERT( + db_, "ripple::NodeStore::MemoryBackend::for_each : non-null database"); for (auto const& e : db_->table) f(e.second); diff --git a/src/xrpld/nodestore/backend/RocksDBFactory.cpp b/src/xrpld/nodestore/backend/RocksDBFactory.cpp index a4bb4ae5fb6..2034128949f 100644 --- a/src/xrpld/nodestore/backend/RocksDBFactory.cpp +++ b/src/xrpld/nodestore/backend/RocksDBFactory.cpp @@ -275,8 +275,8 @@ class RocksDBBackend : public Backend, public BatchWriter::Callback Status fetch(void const* key, std::shared_ptr* pObject) override { - ASSERT( - m_db != nullptr, + XRPL_ASSERT( + m_db, "ripple::NodeStore::RocksDBBackend::fetch : non-null database"); pObject->reset(); @@ -353,8 +353,8 @@ class RocksDBBackend : public Backend, public BatchWriter::Callback void storeBatch(Batch const& batch) override { - ASSERT( - m_db != nullptr, + XRPL_ASSERT( + m_db, "ripple::NodeStore::RocksDBBackend::storeBatch : non-null " "database"); rocksdb::WriteBatch wb; @@ -388,8 +388,8 @@ class RocksDBBackend : public Backend, public BatchWriter::Callback void for_each(std::function)> f) override { - ASSERT( - m_db != nullptr, + XRPL_ASSERT( + m_db, "ripple::NodeStore::RocksDBBackend::for_each : non-null database"); rocksdb::ReadOptions const options; diff --git a/src/xrpld/nodestore/detail/BatchWriter.cpp b/src/xrpld/nodestore/detail/BatchWriter.cpp index ec360f89f31..9fd90f82e74 100644 --- a/src/xrpld/nodestore/detail/BatchWriter.cpp +++ b/src/xrpld/nodestore/detail/BatchWriter.cpp @@ -83,7 +83,7 @@ BatchWriter::writeBatch() std::lock_guard sl(mWriteMutex); mWriteSet.swap(set); - ASSERT( + XRPL_ASSERT( mWriteSet.empty(), "ripple::NodeStore::BatchWriter::writeBatch : writes not set"); mWriteLoad = set.size(); diff --git a/src/xrpld/nodestore/detail/Database.cpp b/src/xrpld/nodestore/detail/Database.cpp index f9875d5062f..7564ca60b52 100644 --- a/src/xrpld/nodestore/detail/Database.cpp +++ b/src/xrpld/nodestore/detail/Database.cpp @@ -40,8 +40,8 @@ Database::Database( , requestBundle_(get(config, "rq_bundle", 4)) , readThreads_(std::max(1, readThreads)) { - ASSERT( - readThreads != 0, + XRPL_ASSERT( + readThreads, "ripple::NodeStore::Database::Database : nonzero threads input"); if (earliestLedgerSeq_ < 1) @@ -89,7 +89,7 @@ Database::Database( for (auto it = read.begin(); it != read.end(); ++it) { - ASSERT( + XRPL_ASSERT( !it->second.empty(), "ripple::NodeStore::Database::Database : non-empty " "data"); @@ -166,7 +166,7 @@ Database::stop() while (readThreads_.load() != 0) { - ASSERT( + XRPL_ASSERT( steady_clock::now() - start < 30s, "ripple::NodeStore::Database::stop : maximum stop duration"); std::this_thread::yield(); @@ -219,8 +219,8 @@ Database::importInternal(Backend& dstBackend, Database& srcDB) }; srcDB.for_each([&](std::shared_ptr nodeObject) { - ASSERT( - nodeObject != nullptr, + XRPL_ASSERT( + nodeObject, "ripple::NodeStore::Database::importInternal : non-null node"); if (!nodeObject) // This should never happen return; @@ -265,7 +265,7 @@ Database::fetchNodeObject( void Database::getCountsJson(Json::Value& obj) { - ASSERT( + XRPL_ASSERT( obj.isObject(), "ripple::NodeStore::Database::getCountsJson : valid input type"); diff --git a/src/xrpld/nodestore/detail/DatabaseNodeImp.h b/src/xrpld/nodestore/detail/DatabaseNodeImp.h index 2ed3443da92..d90f02ce877 100644 --- a/src/xrpld/nodestore/detail/DatabaseNodeImp.h +++ b/src/xrpld/nodestore/detail/DatabaseNodeImp.h @@ -76,8 +76,8 @@ class DatabaseNodeImp : public Database j); } - ASSERT( - backend_ != nullptr, + XRPL_ASSERT( + backend_, "ripple::NodeStore::DatabaseNodeImp::DatabaseNodeImp : non-null " "backend"); } diff --git a/src/xrpld/nodestore/detail/DecodedBlob.cpp b/src/xrpld/nodestore/detail/DecodedBlob.cpp index 49e1ff5e3bb..fbf9f532a0a 100644 --- a/src/xrpld/nodestore/detail/DecodedBlob.cpp +++ b/src/xrpld/nodestore/detail/DecodedBlob.cpp @@ -72,7 +72,7 @@ DecodedBlob::DecodedBlob(void const* key, void const* value, int valueBytes) std::shared_ptr DecodedBlob::createObject() { - ASSERT( + XRPL_ASSERT( m_success, "ripple::NodeStore::DecodedBlob::createObject : valid object type"); diff --git a/src/xrpld/nodestore/detail/EncodedBlob.h b/src/xrpld/nodestore/detail/EncodedBlob.h index d99908cf4f6..01b167159e7 100644 --- a/src/xrpld/nodestore/detail/EncodedBlob.h +++ b/src/xrpld/nodestore/detail/EncodedBlob.h @@ -80,8 +80,8 @@ class EncodedBlob public: explicit EncodedBlob(std::shared_ptr const& obj) : size_([&obj]() { - ASSERT( - obj != nullptr, + XRPL_ASSERT( + obj, "ripple::NodeStore::EncodedBlob::EncodedBlob : non-null input"); if (!obj) @@ -102,7 +102,7 @@ class EncodedBlob ~EncodedBlob() { - ASSERT( + XRPL_ASSERT( ((ptr_ == payload_.data()) && (size_ <= payload_.size())) || ((ptr_ != payload_.data()) && (size_ > payload_.size())), "ripple::NodeStore::EncodedBlob::~EncodedBlob : valid payload " diff --git a/src/xrpld/nodestore/detail/ManagerImp.cpp b/src/xrpld/nodestore/detail/ManagerImp.cpp index 38f193a7d8a..24371dd58c3 100644 --- a/src/xrpld/nodestore/detail/ManagerImp.cpp +++ b/src/xrpld/nodestore/detail/ManagerImp.cpp @@ -91,7 +91,7 @@ ManagerImp::erase(Factory& factory) std::find_if(list_.begin(), list_.end(), [&factory](Factory* other) { return other == &factory; }); - ASSERT( + XRPL_ASSERT( iter != list_.end(), "ripple::NodeStore::ManagerImp::erase : valid input"); list_.erase(iter); diff --git a/src/xrpld/overlay/Slot.h b/src/xrpld/overlay/Slot.h index fca6c621fa0..92ec09de124 100644 --- a/src/xrpld/overlay/Slot.h +++ b/src/xrpld/overlay/Slot.h @@ -362,7 +362,7 @@ Slot::update( << consideredPoolSize << " selected " << *s << " " << *std::next(s, 1) << " " << *std::next(s, 2); - ASSERT( + XRPL_ASSERT( peers_.size() >= MAX_SELECTED_PEERS, "ripple::reduce_relay::Slot::update : minimum peers"); diff --git a/src/xrpld/overlay/detail/ConnectAttempt.cpp b/src/xrpld/overlay/detail/ConnectAttempt.cpp index d65366560d5..4bb76369c4c 100644 --- a/src/xrpld/overlay/detail/ConnectAttempt.cpp +++ b/src/xrpld/overlay/detail/ConnectAttempt.cpp @@ -90,7 +90,7 @@ ConnectAttempt::run() void ConnectAttempt::close() { - ASSERT( + XRPL_ASSERT( strand_.running_in_this_thread(), "ripple::ConnectAttempt::close : strand in this thread"); if (socket_.is_open()) diff --git a/src/xrpld/overlay/detail/Message.cpp b/src/xrpld/overlay/detail/Message.cpp index 6e44f3e957c..cdcf433f610 100644 --- a/src/xrpld/overlay/detail/Message.cpp +++ b/src/xrpld/overlay/detail/Message.cpp @@ -34,9 +34,8 @@ Message::Message( auto const messageBytes = messageSize(message); - ASSERT( - messageBytes != 0, - "ripple::Message::Message : non-empty message input"); + XRPL_ASSERT( + messageBytes, "ripple::Message::Message : non-empty message input"); buffer_.resize(headerBytes + messageBytes); @@ -45,7 +44,7 @@ Message::Message( if (messageBytes != 0) message.SerializeToArray(buffer_.data() + headerBytes, messageBytes); - ASSERT( + XRPL_ASSERT( getBufferSize() == totalSize(message), "ripple::Message::Message : message size matches the buffer"); } diff --git a/src/xrpld/overlay/detail/OverlayImpl.cpp b/src/xrpld/overlay/detail/OverlayImpl.cpp index d5bd6e2ce68..e27b752ae10 100644 --- a/src/xrpld/overlay/detail/OverlayImpl.cpp +++ b/src/xrpld/overlay/detail/OverlayImpl.cpp @@ -294,7 +294,7 @@ OverlayImpl::onHandoff( std::lock_guard lock(mutex_); { auto const result = m_peers.emplace(peer->slot(), peer); - ASSERT( + XRPL_ASSERT( result.second, "ripple::OverlayImpl::onHandoff : peer is inserted"); (void)result.second; @@ -389,7 +389,7 @@ OverlayImpl::makeErrorResponse( void OverlayImpl::connect(beast::IP::Endpoint const& remote_endpoint) { - ASSERT(work_.has_value(), "ripple::OverlayImpl::connect : work is set"); + XRPL_ASSERT(work_, "ripple::OverlayImpl::connect : work is set"); auto usage = resourceManager().newOutboundEndpoint(remote_endpoint); if (usage.disconnect(journal_)) @@ -431,7 +431,7 @@ OverlayImpl::add_active(std::shared_ptr const& peer) { auto const result = m_peers.emplace(peer->slot(), peer); - ASSERT( + XRPL_ASSERT( result.second, "ripple::OverlayImpl::add_active : peer is inserted"); (void)result.second; @@ -442,7 +442,7 @@ OverlayImpl::add_active(std::shared_ptr const& peer) std::piecewise_construct, std::make_tuple(peer->id()), std::make_tuple(peer)); - ASSERT( + XRPL_ASSERT( result.second, "ripple::OverlayImpl::add_active : peer ID is inserted"); (void)result.second; @@ -467,7 +467,8 @@ OverlayImpl::remove(std::shared_ptr const& slot) { std::lock_guard lock(mutex_); auto const iter = m_peers.find(slot); - ASSERT(iter != m_peers.end(), "ripple::OverlayImpl::remove : valid input"); + XRPL_ASSERT( + iter != m_peers.end(), "ripple::OverlayImpl::remove : valid input"); m_peers.erase(iter); } @@ -604,7 +605,7 @@ OverlayImpl::activate(std::shared_ptr const& peer) std::piecewise_construct, std::make_tuple(peer->id()), std::make_tuple(peer))); - ASSERT( + XRPL_ASSERT( result.second, "ripple::OverlayImpl::activate : peer ID is inserted"); (void)result.second; @@ -617,7 +618,7 @@ OverlayImpl::activate(std::shared_ptr const& peer) << ")"; // We just accepted this peer so we have non-zero active peers - ASSERT(size() != 0, "ripple::OverlayImpl::activate : nonzero peers"); + XRPL_ASSERT(size(), "ripple::OverlayImpl::activate : nonzero peers"); } void @@ -656,8 +657,8 @@ OverlayImpl::onManifests( // the loaded Manifest out of the optional so we need to // reload it here. mo = deserializeManifest(serialized); - ASSERT( - mo.has_value(), + XRPL_ASSERT( + mo, "ripple::OverlayImpl::onManifests : manifest " "deserialization succeeded"); diff --git a/src/xrpld/overlay/detail/OverlayImpl.h b/src/xrpld/overlay/detail/OverlayImpl.h index 63e002ddf79..f1458702fe6 100644 --- a/src/xrpld/overlay/detail/OverlayImpl.h +++ b/src/xrpld/overlay/detail/OverlayImpl.h @@ -600,7 +600,7 @@ class OverlayImpl : public Overlay, public reduce_relay::SquelchHandler { auto counts = m_traffic.getCounts(); std::lock_guard lock(m_statsMutex); - ASSERT( + XRPL_ASSERT( counts.size() == m_stats.trafficGauges.size(), "ripple::OverlayImpl::collect_metrics : counts size do match"); diff --git a/src/xrpld/overlay/detail/PeerImp.cpp b/src/xrpld/overlay/detail/PeerImp.cpp index 5dd64c27ea5..b04e1a6b024 100644 --- a/src/xrpld/overlay/detail/PeerImp.cpp +++ b/src/xrpld/overlay/detail/PeerImp.cpp @@ -565,7 +565,7 @@ PeerImp::hasRange(std::uint32_t uMin, std::uint32_t uMax) void PeerImp::close() { - ASSERT( + XRPL_ASSERT( strand_.running_in_this_thread(), "ripple::PeerImp::close : strand in this thread"); if (socket_.is_open()) @@ -608,7 +608,7 @@ PeerImp::fail(std::string const& reason) void PeerImp::fail(std::string const& name, error_code ec) { - ASSERT( + XRPL_ASSERT( strand_.running_in_this_thread(), "ripple::PeerImp::fail : strand in this thread"); if (socket_.is_open()) @@ -623,12 +623,12 @@ PeerImp::fail(std::string const& name, error_code ec) void PeerImp::gracefulClose() { - ASSERT( + XRPL_ASSERT( strand_.running_in_this_thread(), "ripple::PeerImp::gracefulClose : strand in this thread"); - ASSERT( + XRPL_ASSERT( socket_.is_open(), "ripple::PeerImp::gracefulClose : socket is open"); - ASSERT( + XRPL_ASSERT( !gracefulClose_, "ripple::PeerImp::gracefulClose : socket is not closing"); gracefulClose_ = true; @@ -756,7 +756,7 @@ PeerImp::onShutdown(error_code ec) void PeerImp::doAccept() { - ASSERT( + XRPL_ASSERT( read_buffer_.size() == 0, "ripple::PeerImp::doAccept : empty read buffer"); @@ -959,7 +959,7 @@ PeerImp::onWriteMessage(error_code ec, std::size_t bytes_transferred) metrics_.sent.add_message(bytes_transferred); - ASSERT( + XRPL_ASSERT( !send_queue_.empty(), "ripple::PeerImp::onWriteMessage : non-empty send buffer"); send_queue_.pop(); @@ -2015,8 +2015,8 @@ PeerImp::onValidatorListMessage( case ListDisposition::pending: { std::lock_guard sl(recentLock_); - ASSERT( - applyResult.publisherKey.has_value(), + XRPL_ASSERT( + applyResult.publisherKey, "ripple::PeerImp::onValidatorListMessage : publisher key is " "set"); auto const& pubKey = *applyResult.publisherKey; @@ -2024,7 +2024,7 @@ PeerImp::onValidatorListMessage( if (auto const iter = publisherListSequences_.find(pubKey); iter != publisherListSequences_.end()) { - ASSERT( + XRPL_ASSERT( iter->second < applyResult.sequence, "ripple::PeerImp::onValidatorListMessage : lower sequence"); } @@ -2037,11 +2037,11 @@ PeerImp::onValidatorListMessage( #ifndef NDEBUG { std::lock_guard sl(recentLock_); - ASSERT( + XRPL_ASSERT( applyResult.sequence && applyResult.publisherKey, "ripple::PeerImp::onValidatorListMessage : nonzero sequence " "and set publisher key"); - ASSERT( + XRPL_ASSERT( publisherListSequences_[*applyResult.publisherKey] <= applyResult.sequence, "ripple::PeerImp::onValidatorListMessage : maximum sequence"); @@ -2833,8 +2833,7 @@ PeerImp::checkPropose( JLOG(p_journal_.trace()) << "Checking " << (isTrusted ? "trusted" : "UNTRUSTED") << " proposal"; - ASSERT( - packet != nullptr, "ripple::PeerImp::checkPropose : non-null packet"); + XRPL_ASSERT(packet, "ripple::PeerImp::checkPropose : non-null packet"); if (!cluster() && !peerPos.checkSign()) { diff --git a/src/xrpld/overlay/detail/ProtocolMessage.h b/src/xrpld/overlay/detail/ProtocolMessage.h index b1e871437f3..54f99eb73d0 100644 --- a/src/xrpld/overlay/detail/ProtocolMessage.h +++ b/src/xrpld/overlay/detail/ProtocolMessage.h @@ -175,7 +175,7 @@ parseMessageHeader( MessageHeader hdr; auto iter = buffersBegin(bufs); - ASSERT( + XRPL_ASSERT( iter != buffersEnd(bufs), "ripple::detail::parseMessageHeader : non-empty buffer"); diff --git a/src/xrpld/overlay/detail/TrafficCount.h b/src/xrpld/overlay/detail/TrafficCount.h index 754e2872b18..9b4fabdc344 100644 --- a/src/xrpld/overlay/detail/TrafficCount.h +++ b/src/xrpld/overlay/detail/TrafficCount.h @@ -172,7 +172,7 @@ class TrafficCount void addCount(category cat, bool inbound, int bytes) { - ASSERT( + XRPL_ASSERT( cat <= category::unknown, "ripple::TrafficCount::addCount : valid category input"); diff --git a/src/xrpld/overlay/detail/ZeroCopyStream.h b/src/xrpld/overlay/detail/ZeroCopyStream.h index 44d8100952e..ac210bf6b9e 100644 --- a/src/xrpld/overlay/detail/ZeroCopyStream.h +++ b/src/xrpld/overlay/detail/ZeroCopyStream.h @@ -206,7 +206,7 @@ template void ZeroCopyOutputStream::BackUp(int count) { - ASSERT( + XRPL_ASSERT( count <= commit_, "ripple::ZeroCopyOutputStream::BackUp : valid input"); auto const n = commit_ - count; streambuf_.commit(n); diff --git a/src/xrpld/peerfinder/detail/Bootcache.cpp b/src/xrpld/peerfinder/detail/Bootcache.cpp index 88fa4c6221a..1af5f0e1c97 100644 --- a/src/xrpld/peerfinder/detail/Bootcache.cpp +++ b/src/xrpld/peerfinder/detail/Bootcache.cpp @@ -159,7 +159,7 @@ Bootcache::on_success(beast::IP::Endpoint const& endpoint) ++entry.valence(); m_map.erase(result.first); result = m_map.insert(value_type(endpoint, entry)); - ASSERT( + XRPL_ASSERT( result.second, "ripple:PeerFinder::Bootcache::on_success : endpoint inserted"); } @@ -187,7 +187,7 @@ Bootcache::on_failure(beast::IP::Endpoint const& endpoint) --entry.valence(); m_map.erase(result.first); result = m_map.insert(value_type(endpoint, entry)); - ASSERT( + XRPL_ASSERT( result.second, "ripple:PeerFinder::Bootcache::on_failure : endpoint inserted"); } diff --git a/src/xrpld/peerfinder/detail/Counts.h b/src/xrpld/peerfinder/detail/Counts.h index d18aa858567..0078ae28411 100644 --- a/src/xrpld/peerfinder/detail/Counts.h +++ b/src/xrpld/peerfinder/detail/Counts.h @@ -71,7 +71,7 @@ class Counts can_activate(Slot const& s) const { // Must be handshaked and in the right state - ASSERT( + XRPL_ASSERT( s.state() == Slot::connected || s.state() == Slot::accept, "ripple::PeerFinder::Counts::can_activate : valid input state"); @@ -264,7 +264,7 @@ class Counts switch (s.state()) { case Slot::accept: - ASSERT( + XRPL_ASSERT( s.inbound(), "ripple::PeerFinder::Counts::adjust : input is inbound"); m_acceptCount += n; @@ -272,7 +272,7 @@ class Counts case Slot::connect: case Slot::connected: - ASSERT( + XRPL_ASSERT( !s.inbound(), "ripple::PeerFinder::Counts::adjust : input is not " "inbound"); diff --git a/src/xrpld/peerfinder/detail/Handouts.h b/src/xrpld/peerfinder/detail/Handouts.h index aa397d79c6e..36e9c712e38 100644 --- a/src/xrpld/peerfinder/detail/Handouts.h +++ b/src/xrpld/peerfinder/detail/Handouts.h @@ -43,7 +43,7 @@ template std::size_t handout_one(Target& t, HopContainer& h) { - ASSERT( + XRPL_ASSERT( !t.full(), "ripple::PeerFinder::detail::handout_one : target is not full"); for (auto it = h.begin(); it != h.end(); ++it) diff --git a/src/xrpld/peerfinder/detail/Livecache.h b/src/xrpld/peerfinder/detail/Livecache.h index bf1aca2eb9d..03d99592107 100644 --- a/src/xrpld/peerfinder/detail/Livecache.h +++ b/src/xrpld/peerfinder/detail/Livecache.h @@ -432,7 +432,7 @@ Livecache::insert(Endpoint const& ep) // but we will use it to make connections and hand it out // when redirecting. // - ASSERT( + XRPL_ASSERT( ep.hops <= (Tuning::maxHops + 1), "ripple::PeerFinder::Livecache::insert : maximum input hops"); auto result = m_cache.emplace(ep.address, ep); @@ -532,7 +532,7 @@ template void Livecache::hops_t::insert(Element& e) { - ASSERT( + XRPL_ASSERT( e.endpoint.hops <= Tuning::maxHops + 1, "ripple::PeerFinder::Livecache::hops_t::insert : maximum input hops"); // This has security implications without a shuffle @@ -544,7 +544,7 @@ template void Livecache::hops_t::reinsert(Element& e, std::uint32_t numHops) { - ASSERT( + XRPL_ASSERT( numHops <= Tuning::maxHops + 1, "ripple::PeerFinder::Livecache::hops_t::reinsert : maximum hops input"); diff --git a/src/xrpld/peerfinder/detail/Logic.h b/src/xrpld/peerfinder/detail/Logic.h index 41bb6789a86..01f38ad7fd4 100644 --- a/src/xrpld/peerfinder/detail/Logic.h +++ b/src/xrpld/peerfinder/detail/Logic.h @@ -304,7 +304,7 @@ class Logic // Add slot to table auto const result(slots_.emplace(slot->remote_endpoint(), slot)); // Remote address must not already exist - ASSERT( + XRPL_ASSERT( result.second, "ripple::PeerFinder::Logic::new_inbound_slot : remote endpoint " "inserted"); @@ -342,7 +342,7 @@ class Logic // Add slot to table auto const result = slots_.emplace(slot->remote_endpoint(), slot); // Remote address must not already exist - ASSERT( + XRPL_ASSERT( result.second, "ripple::PeerFinder::Logic::new_outbound_slot : remote endpoint " "inserted"); @@ -368,7 +368,7 @@ class Logic std::lock_guard _(lock_); // The object must exist in our table - ASSERT( + XRPL_ASSERT( slots_.find(slot->remote_endpoint()) != slots_.end(), "ripple::PeerFinder::Logic::onConnected : valid slot input"); // Assign the local endpoint now that it's known @@ -379,7 +379,7 @@ class Logic auto const iter(slots_.find(local_endpoint)); if (iter != slots_.end()) { - ASSERT( + XRPL_ASSERT( iter->second->local_endpoint() == slot->remote_endpoint(), "ripple::PeerFinder::Logic::onConnected : local and remote " "endpoints do match"); @@ -407,11 +407,11 @@ class Logic std::lock_guard _(lock_); // The object must exist in our table - ASSERT( + XRPL_ASSERT( slots_.find(slot->remote_endpoint()) != slots_.end(), "ripple::PeerFinder::Logic::activate : valid slot input"); // Must be accepted or connected - ASSERT( + XRPL_ASSERT( slot->state() == Slot::accept || slot->state() == Slot::connected, "ripple::PeerFinder::Logic::activate : valid slot state"); @@ -439,7 +439,7 @@ class Logic { [[maybe_unused]] bool const inserted = keys_.insert(key).second; // Public key must not already exist - ASSERT( + XRPL_ASSERT( inserted, "ripple::PeerFinder::Logic::activate : public key inserted"); } @@ -803,12 +803,12 @@ class Logic std::lock_guard _(lock_); // The object must exist in our table - ASSERT( + XRPL_ASSERT( slots_.find(slot->remote_endpoint()) != slots_.end(), "ripple::PeerFinder::Logic::on_endpoints : valid slot input"); // Must be handshaked! - ASSERT( + XRPL_ASSERT( slot->state() == Slot::active, "ripple::PeerFinder::Logic::on_endpoints : valid slot state"); @@ -822,8 +822,8 @@ class Logic for (auto const& ep : list) { - ASSERT( - ep.hops != 0, + XRPL_ASSERT( + ep.hops, "ripple::PeerFinder::Logic::on_endpoints : nonzero hops"); slot->recent.insert(ep.address, ep.hops); diff --git a/src/xrpld/peerfinder/detail/SlotImp.cpp b/src/xrpld/peerfinder/detail/SlotImp.cpp index 4cc3e577d66..c1950aac508 100644 --- a/src/xrpld/peerfinder/detail/SlotImp.cpp +++ b/src/xrpld/peerfinder/detail/SlotImp.cpp @@ -64,29 +64,29 @@ void SlotImp::state(State state_) { // Must go through activate() to set active state - ASSERT( + XRPL_ASSERT( state_ != active, "ripple::PeerFinder::SlotImp::state : input state is not active"); // The state must be different - ASSERT( + XRPL_ASSERT( state_ != m_state, "ripple::PeerFinder::SlotImp::state : input state is different from " "current"); // You can't transition into the initial states - ASSERT( + XRPL_ASSERT( state_ != accept && state_ != connect, "ripple::PeerFinder::SlotImp::state : input state is not an initial"); // Can only become connected from outbound connect state - ASSERT( + XRPL_ASSERT( state_ != connected || (!m_inbound && m_state == connect), "ripple::PeerFinder::SlotImp::state : input state is not connected an " "invalid state"); // Can't gracefully close on an outbound connection attempt - ASSERT( + XRPL_ASSERT( state_ != closing || m_state != connect, "ripple::PeerFinder::SlotImp::state : input state is not closing an " "invalid state"); @@ -98,7 +98,7 @@ void SlotImp::activate(clock_type::time_point const& now) { // Can only become active from the accept or connected state - ASSERT( + XRPL_ASSERT( m_state == accept || m_state == connected, "ripple::PeerFinder::SlotImp::activate : valid state"); diff --git a/src/xrpld/rpc/Status.h b/src/xrpld/rpc/Status.h index 34ca69e9576..8edbb13ed36 100644 --- a/src/xrpld/rpc/Status.h +++ b/src/xrpld/rpc/Status.h @@ -95,7 +95,8 @@ struct Status : public std::exception TER toTER() const { - ASSERT(type_ == Type::TER, "ripple::RPC::Status::toTER : type is TER"); + XRPL_ASSERT( + type_ == Type::TER, "ripple::RPC::Status::toTER : type is TER"); return TER::fromInt(code_); } @@ -104,7 +105,7 @@ struct Status : public std::exception error_code_i toErrorCode() const { - ASSERT( + XRPL_ASSERT( type_ == Type::error_code_i, "ripple::RPC::Status::toTER : type is error code"); return error_code_i(code_); diff --git a/src/xrpld/rpc/detail/Handler.cpp b/src/xrpld/rpc/detail/Handler.cpp index f303f657172..4847f5e0d6b 100644 --- a/src/xrpld/rpc/detail/Handler.cpp +++ b/src/xrpld/rpc/detail/Handler.cpp @@ -50,7 +50,7 @@ template Status handle(JsonContext& context, Object& object) { - ASSERT( + XRPL_ASSERT( context.apiVersion >= HandlerImpl::minApiVer && context.apiVersion <= HandlerImpl::maxApiVer, "ripple::RPC::handle : valid API version"); @@ -205,10 +205,10 @@ class HandlerTable unsigned minVer, unsigned maxVer) { - ASSERT( + XRPL_ASSERT( minVer <= maxVer, "ripple::RPC::HandlerTable : valid API version range"); - ASSERT( + XRPL_ASSERT( maxVer <= RPC::apiMaximumValidVersion, "ripple::RPC::HandlerTable : valid max API version"); diff --git a/src/xrpld/rpc/detail/RPCHelpers.cpp b/src/xrpld/rpc/detail/RPCHelpers.cpp index 60eff492dc9..4c0a8ee3689 100644 --- a/src/xrpld/rpc/detail/RPCHelpers.cpp +++ b/src/xrpld/rpc/detail/RPCHelpers.cpp @@ -544,7 +544,7 @@ getLedger(T& ledger, LedgerShortcut shortcut, Context& context) return {rpcNOT_SYNCED, "notSynced"}; } - ASSERT( + XRPL_ASSERT( !ledger->open(), "ripple::RPC::getLedger : validated is not open"); } else @@ -552,12 +552,13 @@ getLedger(T& ledger, LedgerShortcut shortcut, Context& context) if (shortcut == LedgerShortcut::CURRENT) { ledger = context.ledgerMaster.getCurrentLedger(); - ASSERT(ledger->open(), "ripple::RPC::getLedger : current is open"); + XRPL_ASSERT( + ledger->open(), "ripple::RPC::getLedger : current is open"); } else if (shortcut == LedgerShortcut::CLOSED) { ledger = context.ledgerMaster.getClosedLedger(); - ASSERT( + XRPL_ASSERT( !ledger->open(), "ripple::RPC::getLedger : closed is not open"); } else @@ -967,7 +968,7 @@ chooseLedgerEntryType(Json::Value const& params) { result.first = RPC::Status{ rpcINVALID_PARAMS, "Invalid field 'type', not string."}; - ASSERT( + XRPL_ASSERT( result.first.type() == RPC::Status::Type::error_code_i, "ripple::RPC::chooseLedgerEntryType : first valid result type"); return result; @@ -982,7 +983,7 @@ chooseLedgerEntryType(Json::Value const& params) { result.first = RPC::Status{rpcINVALID_PARAMS, "Invalid field 'type'."}; - ASSERT( + XRPL_ASSERT( result.first.type() == RPC::Status::Type::error_code_i, "ripple::RPC::chooseLedgerEntryType : second valid result " "type"); @@ -1091,8 +1092,8 @@ getLedgerByContext(RPC::JsonContext& context) // ledger auto const refIndex = getCandidateLedger(ledgerIndex); auto refHash = hashOfSeq(*ledger, refIndex, j); - ASSERT( - refHash.has_value(), + XRPL_ASSERT( + refHash, "ripple::RPC::getLedgerByContext : nonzero ledger hash"); ledger = ledgerMaster.getLedgerByHash(*refHash); @@ -1127,8 +1128,8 @@ getLedgerByContext(RPC::JsonContext& context) neededHash = hashOfSeq(*ledger, ledgerIndex, j); } - ASSERT( - neededHash.has_value(), + XRPL_ASSERT( + neededHash, "ripple::RPC::getLedgerByContext : nonzero needed hash"); ledgerHash = neededHash ? *neededHash : beast::zero; // kludge } diff --git a/src/xrpld/rpc/detail/RPCHelpers.h b/src/xrpld/rpc/detail/RPCHelpers.h index 80ab9d6a5ec..74171af28e3 100644 --- a/src/xrpld/rpc/detail/RPCHelpers.h +++ b/src/xrpld/rpc/detail/RPCHelpers.h @@ -213,7 +213,7 @@ template void setVersion(Object& parent, unsigned int apiVersion, bool betaEnabled) { - ASSERT( + XRPL_ASSERT( apiVersion != apiInvalidVersion, "ripple::RPC::setVersion : input is valid"); auto&& object = addObject(parent, jss::version); diff --git a/src/xrpld/rpc/detail/Role.cpp b/src/xrpld/rpc/detail/Role.cpp index 739c8f58012..b374f035884 100644 --- a/src/xrpld/rpc/detail/Role.cpp +++ b/src/xrpld/rpc/detail/Role.cpp @@ -28,7 +28,7 @@ namespace ripple { bool passwordUnrequiredOrSentCorrect(Port const& port, Json::Value const& params) { - ASSERT( + XRPL_ASSERT( !(port.admin_nets_v4.empty() && port.admin_nets_v6.empty()), "ripple::passwordUnrequiredOrSentCorrect : non-empty admin nets"); bool const passwordRequired = diff --git a/src/xrpld/rpc/detail/Status.cpp b/src/xrpld/rpc/detail/Status.cpp index 1773d3bc949..7b23c2cc13a 100644 --- a/src/xrpld/rpc/detail/Status.cpp +++ b/src/xrpld/rpc/detail/Status.cpp @@ -37,7 +37,7 @@ Status::codeString() const std::string s1, s2; [[maybe_unused]] auto const success = transResultInfo(toTER(), s1, s2); - ASSERT(success, "ripple::RPC::codeString : valid TER result"); + XRPL_ASSERT(success, "ripple::RPC::codeString : valid TER result"); return s1 + ": " + s2; } diff --git a/src/xrpld/rpc/detail/TransactionSign.cpp b/src/xrpld/rpc/detail/TransactionSign.cpp index 3623b26d356..f7c04e356c3 100644 --- a/src/xrpld/rpc/detail/TransactionSign.cpp +++ b/src/xrpld/rpc/detail/TransactionSign.cpp @@ -1031,7 +1031,7 @@ transactionSignFor( if (!preprocResult.second) return preprocResult.first; - ASSERT( + XRPL_ASSERT( signForParams.validMultiSign(), "ripple::RPC::transactionSignFor : valid multi-signature"); diff --git a/src/xrpld/rpc/handlers/AMMInfo.cpp b/src/xrpld/rpc/handlers/AMMInfo.cpp index e6a1d713a4a..ba02b6869b0 100644 --- a/src/xrpld/rpc/handlers/AMMInfo.cpp +++ b/src/xrpld/rpc/handlers/AMMInfo.cpp @@ -147,7 +147,7 @@ doAMMInfo(RPC::JsonContext& context) if (context.apiVersion >= 3 && invalid(params)) return Unexpected(rpcINVALID_PARAMS); - ASSERT( + XRPL_ASSERT( (issue1.has_value() == issue2.has_value()) && (issue1.has_value() != ammID.has_value()), "ripple::doAMMInfo : issue1 and issue2 do match"); @@ -155,9 +155,7 @@ doAMMInfo(RPC::JsonContext& context) auto const ammKeylet = [&]() { if (issue1 && issue2) return keylet::amm(*issue1, *issue2); - ASSERT( - ammID.has_value(), - "ripple::doAMMInfo::ammKeylet : ammID is set"); + XRPL_ASSERT(ammID, "ripple::doAMMInfo::ammKeylet : ammID is set"); return keylet::amm(*ammID); }(); auto const amm = ledger->read(ammKeylet); @@ -216,7 +214,7 @@ doAMMInfo(RPC::JsonContext& context) } if (voteSlots.size() > 0) ammResult[jss::vote_slots] = std::move(voteSlots); - ASSERT( + XRPL_ASSERT( !ledger->rules().enabled(fixInnerObjTemplate) || amm->isFieldPresent(sfAuctionSlot), "ripple::doAMMInfo : auction slot is set"); diff --git a/src/xrpld/rpc/handlers/AccountInfo.cpp b/src/xrpld/rpc/handlers/AccountInfo.cpp index 4f62eb5880a..90e3a8d46e0 100644 --- a/src/xrpld/rpc/handlers/AccountInfo.cpp +++ b/src/xrpld/rpc/handlers/AccountInfo.cpp @@ -214,7 +214,7 @@ doAccountInfo(RPC::JsonContext& context) if (tx.seqProxy.isSeq()) { - ASSERT( + XRPL_ASSERT( prevSeqProxy < tx.seqProxy, "rpple::doAccountInfo : first sorted proxy"); prevSeqProxy = tx.seqProxy; @@ -226,7 +226,7 @@ doAccountInfo(RPC::JsonContext& context) } else { - ASSERT( + XRPL_ASSERT( prevSeqProxy < tx.seqProxy, "rpple::doAccountInfo : second sorted proxy"); prevSeqProxy = tx.seqProxy; diff --git a/src/xrpld/rpc/handlers/AccountTx.cpp b/src/xrpld/rpc/handlers/AccountTx.cpp index 5b391ebe3b6..ae50401b630 100644 --- a/src/xrpld/rpc/handlers/AccountTx.cpp +++ b/src/xrpld/rpc/handlers/AccountTx.cpp @@ -307,7 +307,7 @@ populateJsonResponse( if (auto txnsData = std::get_if(&result.transactions)) { - ASSERT( + XRPL_ASSERT( !args.binary, "ripple::populateJsonResponse : binary is not set"); @@ -364,7 +364,8 @@ populateJsonResponse( } else { - ASSERT(args.binary, "ripple::populateJsonResponse : binary is set"); + XRPL_ASSERT( + args.binary, "ripple::populateJsonResponse : binary is set"); for (auto const& binaryData : std::get(result.transactions)) diff --git a/src/xrpld/rpc/handlers/LedgerClosed.cpp b/src/xrpld/rpc/handlers/LedgerClosed.cpp index 759f4aecd33..b5644d9910e 100644 --- a/src/xrpld/rpc/handlers/LedgerClosed.cpp +++ b/src/xrpld/rpc/handlers/LedgerClosed.cpp @@ -29,8 +29,7 @@ Json::Value doLedgerClosed(RPC::JsonContext& context) { auto ledger = context.ledgerMaster.getClosedLedger(); - ASSERT( - ledger != nullptr, "ripple::doLedgerClosed : non-null closed ledger"); + XRPL_ASSERT(ledger, "ripple::doLedgerClosed : non-null closed ledger"); Json::Value jvResult; jvResult[jss::ledger_index] = ledger->info().seq; diff --git a/src/xrpld/rpc/handlers/LedgerDiff.cpp b/src/xrpld/rpc/handlers/LedgerDiff.cpp index e562197f4af..d713f43bfdf 100644 --- a/src/xrpld/rpc/handlers/LedgerDiff.cpp +++ b/src/xrpld/rpc/handlers/LedgerDiff.cpp @@ -73,7 +73,7 @@ doLedgerDiffGrpc( } else { - ASSERT( + XRPL_ASSERT( inDesired->size() > 0, "ripple::doLedgerDiffGrpc : non-empty desired"); diff->set_key(k.data(), k.size()); diff --git a/src/xrpld/rpc/handlers/LedgerHandler.cpp b/src/xrpld/rpc/handlers/LedgerHandler.cpp index 54f9a8b8459..b1a8a4b2252 100644 --- a/src/xrpld/rpc/handlers/LedgerHandler.cpp +++ b/src/xrpld/rpc/handlers/LedgerHandler.cpp @@ -135,9 +135,8 @@ doLedgerGrpc(RPC::GRPCContext& context) { for (auto& i : ledger->txs) { - ASSERT( - i.first != nullptr, - "ripple::doLedgerGrpc : non-null transaction"); + XRPL_ASSERT( + i.first, "ripple::doLedgerGrpc : non-null transaction"); if (request.expand()) { auto txn = response.mutable_transactions_list() @@ -213,7 +212,7 @@ doLedgerGrpc(RPC::GRPCContext& context) obj->set_key(k.data(), k.size()); if (inDesired) { - ASSERT( + XRPL_ASSERT( inDesired->size() > 0, "ripple::doLedgerGrpc : non-empty desired"); obj->set_data(inDesired->data(), inDesired->size()); diff --git a/src/xrpld/rpc/handlers/PayChanClaim.cpp b/src/xrpld/rpc/handlers/PayChanClaim.cpp index e55191877ef..f9c40ee776d 100644 --- a/src/xrpld/rpc/handlers/PayChanClaim.cpp +++ b/src/xrpld/rpc/handlers/PayChanClaim.cpp @@ -58,7 +58,7 @@ doChannelAuthorize(RPC::JsonContext& context) std::optional> const keyPair = RPC::keypairForSignature(params, result, context.apiVersion); - ASSERT( + XRPL_ASSERT( keyPair || RPC::contains_error(result), "ripple::doChannelAuthorize : valid keyPair or an error"); if (!keyPair || RPC::contains_error(result)) diff --git a/src/xrpld/rpc/handlers/Tx.cpp b/src/xrpld/rpc/handlers/Tx.cpp index af08575bbd8..b603e3945a2 100644 --- a/src/xrpld/rpc/handlers/Tx.cpp +++ b/src/xrpld/rpc/handlers/Tx.cpp @@ -251,7 +251,8 @@ populateJsonResponse( // populate binary metadata if (auto blob = std::get_if(&result.meta)) { - ASSERT(args.binary, "ripple::populateJsonResponse : binary is set"); + XRPL_ASSERT( + args.binary, "ripple::populateJsonResponse : binary is set"); auto json_meta = (context.apiVersion > 1 ? jss::meta_blob : jss::meta); response[json_meta] = strHex(makeSlice(*blob)); diff --git a/src/xrpld/shamap/SHAMap.h b/src/xrpld/shamap/SHAMap.h index cc9a8d9e6ae..c10f4eb1cb7 100644 --- a/src/xrpld/shamap/SHAMap.h +++ b/src/xrpld/shamap/SHAMap.h @@ -599,7 +599,7 @@ SHAMap::setLedgerSeq(std::uint32_t lseq) inline void SHAMap::setImmutable() { - ASSERT( + XRPL_ASSERT( state_ != SHAMapState::Invalid, "ripple::SHAMap::setImmutable : state is valid"); state_ = SHAMapState::Immutable; @@ -682,8 +682,8 @@ class SHAMap::const_iterator inline SHAMap::const_iterator::const_iterator(SHAMap const* map) : map_(map) { - ASSERT( - map_ != nullptr, + XRPL_ASSERT( + map_, "ripple::SHAMap::const_iterator::const_iterator : non-null input"); if (auto temp = map_->peekFirstItem(stack_)) @@ -736,7 +736,7 @@ SHAMap::const_iterator::operator++(int) inline bool operator==(SHAMap::const_iterator const& x, SHAMap::const_iterator const& y) { - ASSERT( + XRPL_ASSERT( x.map_ == y.map_, "ripple::operator==(SHAMap::const_iterator, SHAMap::const_iterator) : " "inputs map do match"); diff --git a/src/xrpld/shamap/SHAMapItem.h b/src/xrpld/shamap/SHAMapItem.h index e49762a50b2..2aba5d5d8eb 100644 --- a/src/xrpld/shamap/SHAMapItem.h +++ b/src/xrpld/shamap/SHAMapItem.h @@ -159,7 +159,7 @@ intrusive_ptr_release(SHAMapItem const* x) inline boost::intrusive_ptr make_shamapitem(uint256 const& tag, Slice data) { - ASSERT( + XRPL_ASSERT( data.size() <= megabytes(16), "ripple::make_shamapitem : maximum input size"); diff --git a/src/xrpld/shamap/detail/SHAMap.cpp b/src/xrpld/shamap/detail/SHAMap.cpp index 11cf079320f..09a546be147 100644 --- a/src/xrpld/shamap/detail/SHAMap.cpp +++ b/src/xrpld/shamap/detail/SHAMap.cpp @@ -101,10 +101,10 @@ SHAMap::dirtyUp( // stack is a path of inner nodes up to, but not including, child // child can be an inner node or a leaf - ASSERT( + XRPL_ASSERT( (state_ != SHAMapState::Synching) && (state_ != SHAMapState::Immutable), "ripple::SHAMap::dirtyUp : valid state"); - ASSERT( + XRPL_ASSERT( child && (child->cowid() == cowid_), "ripple::SHAMap::dirtyUp : valid child input"); @@ -114,10 +114,10 @@ SHAMap::dirtyUp( std::dynamic_pointer_cast(stack.top().first); SHAMapNodeID nodeID = stack.top().second; stack.pop(); - ASSERT(node != nullptr, "ripple::SHAMap::dirtyUp : non-null node"); + XRPL_ASSERT(node, "ripple::SHAMap::dirtyUp : non-null node"); int branch = selectBranch(nodeID, target); - ASSERT(branch >= 0, "ripple::SHAMap::dirtyUp : valid branch"); + XRPL_ASSERT(branch >= 0, "ripple::SHAMap::dirtyUp : valid branch"); node = unshareNode(std::move(node), nodeID); node->setChild(branch, std::move(child)); @@ -129,7 +129,7 @@ SHAMap::dirtyUp( SHAMapLeafNode* SHAMap::walkTowardsKey(uint256 const& id, SharedPtrNodeStack* stack) const { - ASSERT( + XRPL_ASSERT( stack == nullptr || stack->empty(), "ripple::SHAMap::walkTowardsKey : empty stack input"); auto inNode = root_; @@ -166,7 +166,7 @@ SHAMap::findKey(uint256 const& id) const std::shared_ptr SHAMap::fetchNodeFromDB(SHAMapHash const& hash) const { - ASSERT(backed_, "ripple::SHAMap::fetchNodeFromDB : is backed"); + XRPL_ASSERT(backed_, "ripple::SHAMap::fetchNodeFromDB : is backed"); auto obj = f_.db().fetchNodeObject(hash.as_uint256(), ledgerSeq_); return finishFetch(hash, obj); } @@ -176,7 +176,7 @@ SHAMap::finishFetch( SHAMapHash const& hash, std::shared_ptr const& object) const { - ASSERT(backed_, "ripple::SHAMap::finishFetch : is backed"); + XRPL_ASSERT(backed_, "ripple::SHAMap::finishFetch : is backed"); try { @@ -364,11 +364,12 @@ SHAMap::descend( int branch, SHAMapSyncFilter* filter) const { - ASSERT(parent->isInner(), "ripple::SHAMap::descend : valid parent input"); - ASSERT( + XRPL_ASSERT( + parent->isInner(), "ripple::SHAMap::descend : valid parent input"); + XRPL_ASSERT( (branch >= 0) && (branch < branchFactor), "ripple::SHAMap::descend : valid branch input"); - ASSERT( + XRPL_ASSERT( !parent->isEmptyBranch(branch), "ripple::SHAMap::descend : parent branch is non-empty"); @@ -438,13 +439,13 @@ std::shared_ptr SHAMap::unshareNode(std::shared_ptr node, SHAMapNodeID const& nodeID) { // make sure the node is suitable for the intended operation (copy on write) - ASSERT( + XRPL_ASSERT( node->cowid() <= cowid_, "ripple::SHAMap::unshareNode : node valid for cowid"); if (node->cowid() != cowid_) { // have a CoW - ASSERT( + XRPL_ASSERT( state_ != SHAMapState::Immutable, "ripple::SHAMap::unshareNode : not immutable"); node = std::static_pointer_cast(node->clone(cowid_)); @@ -479,7 +480,7 @@ SHAMap::belowHelper( if (!inner->isEmptyBranch(i)) { node = descendThrow(inner, i); - ASSERT( + XRPL_ASSERT( !stack.empty(), "ripple::SHAMap::belowHelper : non-empty stack"); if (node->isLeaf()) @@ -555,7 +556,7 @@ SHAMap::onlyBelow(SHAMapTreeNode* node) const // An inner node must have at least one leaf // below it, unless it's the root_ auto const leaf = static_cast(node); - ASSERT( + XRPL_ASSERT( leaf->peekItem() || (leaf == root_.get()), "ripple::SHAMap::onlyBelow : valid inner node"); return leaf->peekItem(); @@ -564,7 +565,8 @@ SHAMap::onlyBelow(SHAMapTreeNode* node) const SHAMapLeafNode const* SHAMap::peekFirstItem(SharedPtrNodeStack& stack) const { - ASSERT(stack.empty(), "ripple::SHAMap::peekFirstItem : empty stack input"); + XRPL_ASSERT( + stack.empty(), "ripple::SHAMap::peekFirstItem : empty stack input"); SHAMapLeafNode* node = firstBelow(root_, stack); if (!node) { @@ -578,16 +580,16 @@ SHAMap::peekFirstItem(SharedPtrNodeStack& stack) const SHAMapLeafNode const* SHAMap::peekNextItem(uint256 const& id, SharedPtrNodeStack& stack) const { - ASSERT( + XRPL_ASSERT( !stack.empty(), "ripple::SHAMap::peekNextItem : non-empty stack input"); - ASSERT( + XRPL_ASSERT( stack.top().first->isLeaf(), "ripple::SHAMap::peekNextItem : stack starts with leaf"); stack.pop(); while (!stack.empty()) { auto [node, nodeID] = stack.top(); - ASSERT( + XRPL_ASSERT( !node->isLeaf(), "ripple::SHAMap::peekNextItem : another node is not leaf"); auto inner = std::static_pointer_cast(node); @@ -599,7 +601,7 @@ SHAMap::peekNextItem(uint256 const& id, SharedPtrNodeStack& stack) const auto leaf = firstBelow(node, stack, i); if (!leaf) Throw(type_, id); - ASSERT( + XRPL_ASSERT( leaf->isLeaf(), "ripple::SHAMap::peekNextItem : leaf is valid"); return leaf; @@ -719,7 +721,7 @@ bool SHAMap::delItem(uint256 const& id) { // delete the item with this ID - ASSERT( + XRPL_ASSERT( state_ != SHAMapState::Immutable, "ripple::SHAMap::delItem : not immutable"); @@ -800,10 +802,10 @@ SHAMap::addGiveItem( SHAMapNodeType type, boost::intrusive_ptr item) { - ASSERT( + XRPL_ASSERT( state_ != SHAMapState::Immutable, "ripple::SHAMap::addGiveItem : not immutable"); - ASSERT( + XRPL_ASSERT( type != SHAMapNodeType::tnINNER, "ripple::SHAMap::addGiveItem : valid type input"); @@ -831,7 +833,7 @@ SHAMap::addGiveItem( // easy case, we end on an inner node auto inner = std::static_pointer_cast(node); int branch = selectBranch(nodeID, tag); - ASSERT( + XRPL_ASSERT( inner->isEmptyBranch(branch), "ripple::SHAMap::addGiveItem : inner branch is empty"); inner->setChild(branch, makeTypedLeaf(type, std::move(item), cowid_)); @@ -842,7 +844,7 @@ SHAMap::addGiveItem( // items auto leaf = std::static_pointer_cast(node); auto otherItem = leaf->peekItem(); - ASSERT( + XRPL_ASSERT( otherItem && (tag != otherItem->key()), "ripple::SHAMap::addGiveItem : non-null item"); @@ -862,7 +864,8 @@ SHAMap::addGiveItem( } // we can add the two leaf nodes here - ASSERT(node->isInner(), "ripple::SHAMap::addGiveItem : node is inner"); + XRPL_ASSERT( + node->isInner(), "ripple::SHAMap::addGiveItem : node is inner"); auto inner = static_cast(node.get()); inner->setChild(b1, makeTypedLeaf(type, std::move(item), cowid_)); @@ -901,7 +904,7 @@ SHAMap::updateGiveItem( // can't change the tag but can change the hash uint256 tag = item->key(); - ASSERT( + XRPL_ASSERT( state_ != SHAMapState::Immutable, "ripple::SHAMap::updateGiveItem : not immutable"); @@ -962,7 +965,7 @@ SHAMap::fetchRoot(SHAMapHash const& hash, SHAMapSyncFilter* filter) if (newRoot) { root_ = newRoot; - ASSERT( + XRPL_ASSERT( root_->getHash() == hash, "ripple::SHAMap::fetchRoot : root hash do match"); return true; @@ -986,8 +989,9 @@ SHAMap::fetchRoot(SHAMapHash const& hash, SHAMapSyncFilter* filter) std::shared_ptr SHAMap::writeNode(NodeObjectType t, std::shared_ptr node) const { - ASSERT(node->cowid() == 0, "ripple::SHAMap::writeNode : valid input node"); - ASSERT(backed_, "ripple::SHAMap::writeNode : is backed"); + XRPL_ASSERT( + node->cowid() == 0, "ripple::SHAMap::writeNode : valid input node"); + XRPL_ASSERT(backed_, "ripple::SHAMap::writeNode : is backed"); canonicalize(node->getHash(), node); @@ -1007,8 +1011,8 @@ SHAMap::preFlushNode(std::shared_ptr node) const { // A shared node should never need to be flushed // because that would imply someone modified it - ASSERT( - node->cowid() != 0, "ripple::SHAMap::preFlushNode : valid input node"); + XRPL_ASSERT( + node->cowid(), "ripple::SHAMap::preFlushNode : valid input node"); if (node->cowid() != cowid_) { @@ -1036,7 +1040,8 @@ SHAMap::flushDirty(NodeObjectType t) int SHAMap::walkSubTree(bool doWrite, NodeObjectType t) { - ASSERT(!doWrite || backed_, "ripple::SHAMap::walkSubTree : valid input"); + XRPL_ASSERT( + !doWrite || backed_, "ripple::SHAMap::walkSubTree : valid input"); int flushed = 0; @@ -1111,7 +1116,7 @@ SHAMap::walkSubTree(bool doWrite, NodeObjectType t) // flush this leaf ++flushed; - ASSERT( + XRPL_ASSERT( node->cowid() == cowid_, "ripple::SHAMap::walkSubTree : node cowid do " "match"); @@ -1147,7 +1152,7 @@ SHAMap::walkSubTree(bool doWrite, NodeObjectType t) stack.pop(); // Hook this inner node to its parent - ASSERT( + XRPL_ASSERT( parent->cowid() == cowid_, "ripple::SHAMap::walkSubTree : parent cowid do match"); parent->shareChild(pos, node); @@ -1193,7 +1198,7 @@ SHAMap::dump(bool hash) const auto child = inner->getChildPointer(i); if (child) { - ASSERT( + XRPL_ASSERT( child->getHash() == inner->getChildHash(i), "ripple::SHAMap::dump : child hash do match"); stack.push({child, nodeID.getChildNodeID(i)}); @@ -1212,7 +1217,7 @@ std::shared_ptr SHAMap::cacheLookup(SHAMapHash const& hash) const { auto ret = f_.getTreeNodeCache()->fetch(hash.as_uint256()); - ASSERT( + XRPL_ASSERT( !ret || !ret->cowid(), "ripple::SHAMap::cacheLookup : not found or zero cowid"); return ret; @@ -1223,10 +1228,10 @@ SHAMap::canonicalize( SHAMapHash const& hash, std::shared_ptr& node) const { - ASSERT(backed_, "ripple::SHAMap::canonicalize : is backed"); - ASSERT( + XRPL_ASSERT(backed_, "ripple::SHAMap::canonicalize : is backed"); + XRPL_ASSERT( node->cowid() == 0, "ripple::SHAMap::canonicalize : valid node input"); - ASSERT( + XRPL_ASSERT( node->getHash() == hash, "ripple::SHAMap::canonicalize : node hash do match"); @@ -1238,8 +1243,8 @@ SHAMap::invariants() const { (void)getHash(); // update node hashes auto node = root_.get(); - ASSERT(node != nullptr, "ripple::SHAMap::invariants : non-null root node"); - ASSERT( + XRPL_ASSERT(node, "ripple::SHAMap::invariants : non-null root node"); + XRPL_ASSERT( !node->isLeaf(), "ripple::SHAMap::invariants : root node is not leaf"); SharedPtrNodeStack stack; for (auto leaf = peekFirstItem(stack); leaf != nullptr; diff --git a/src/xrpld/shamap/detail/SHAMapDelta.cpp b/src/xrpld/shamap/detail/SHAMapDelta.cpp index b2f62685829..baabd4ef139 100644 --- a/src/xrpld/shamap/detail/SHAMapDelta.cpp +++ b/src/xrpld/shamap/detail/SHAMapDelta.cpp @@ -128,7 +128,7 @@ SHAMap::compare(SHAMap const& otherMap, Delta& differences, int maxCount) const // many differences throws on corrupt tables or missing nodes CAUTION: // otherMap is not locked and must be immutable - ASSERT( + XRPL_ASSERT( isValid() && otherMap.isValid(), "ripple::SHAMap::compare : valid state and valid input"); @@ -325,8 +325,8 @@ SHAMap::walkMapParallel( { std::shared_ptr node = std::move(nodeStack.top()); - ASSERT( - node != nullptr, + XRPL_ASSERT( + node, "ripple::SHAMap::walkMapParallel : non-null node"); nodeStack.pop(); diff --git a/src/xrpld/shamap/detail/SHAMapInnerNode.cpp b/src/xrpld/shamap/detail/SHAMapInnerNode.cpp index 2f8448d7edc..b2fba1f9314 100644 --- a/src/xrpld/shamap/detail/SHAMapInnerNode.cpp +++ b/src/xrpld/shamap/detail/SHAMapInnerNode.cpp @@ -225,7 +225,7 @@ SHAMapInnerNode::updateHashDeep() void SHAMapInnerNode::serializeForWire(Serializer& s) const { - ASSERT( + XRPL_ASSERT( !isEmpty(), "ripple::SHAMapInnerNode::serializeForWire : is non-empty"); // If the node is sparse, then only send non-empty branches: @@ -250,7 +250,7 @@ SHAMapInnerNode::serializeForWire(Serializer& s) const void SHAMapInnerNode::serializeWithPrefix(Serializer& s) const { - ASSERT( + XRPL_ASSERT( !isEmpty(), "ripple::SHAMapInnerNode::serializeWithPrefix : is non-empty"); @@ -277,11 +277,11 @@ SHAMapInnerNode::getString(const SHAMapNodeID& id) const void SHAMapInnerNode::setChild(int m, std::shared_ptr child) { - ASSERT( + XRPL_ASSERT( (m >= 0) && (m < branchFactor), "ripple::SHAMapInnerNode::setChild : valid branch input"); - ASSERT(cowid_ != 0, "ripple::SHAMapInnerNode::setChild : nonzero cowid"); - ASSERT( + XRPL_ASSERT(cowid_, "ripple::SHAMapInnerNode::setChild : nonzero cowid"); + XRPL_ASSERT( child.get() != this, "ripple::SHAMapInnerNode::setChild : valid child input"); @@ -310,7 +310,7 @@ SHAMapInnerNode::setChild(int m, std::shared_ptr child) hash_.zero(); - ASSERT( + XRPL_ASSERT( getBranchCount() <= hashesAndChildren_.capacity(), "ripple::SHAMapInnerNode::setChild : maximum branch count"); } @@ -319,18 +319,17 @@ SHAMapInnerNode::setChild(int m, std::shared_ptr child) void SHAMapInnerNode::shareChild(int m, std::shared_ptr const& child) { - ASSERT( + XRPL_ASSERT( (m >= 0) && (m < branchFactor), "ripple::SHAMapInnerNode::shareChild : valid branch input"); - ASSERT(cowid_ != 0, "ripple::SHAMapInnerNode::shareChild : nonzero cowid"); - ASSERT( - child != nullptr, - "ripple::SHAMapInnerNode::shareChild : non-null child input"); - ASSERT( + XRPL_ASSERT(cowid_, "ripple::SHAMapInnerNode::shareChild : nonzero cowid"); + XRPL_ASSERT( + child, "ripple::SHAMapInnerNode::shareChild : non-null child input"); + XRPL_ASSERT( child.get() != this, "ripple::SHAMapInnerNode::shareChild : valid child input"); - ASSERT( + XRPL_ASSERT( !isEmptyBranch(m), "ripple::SHAMapInnerNode::shareChild : non-empty branch input"); hashesAndChildren_.getChildren()[*getChildIndex(m)] = child; @@ -339,10 +338,10 @@ SHAMapInnerNode::shareChild(int m, std::shared_ptr const& child) SHAMapTreeNode* SHAMapInnerNode::getChildPointer(int branch) { - ASSERT( + XRPL_ASSERT( branch >= 0 && branch < branchFactor, "ripple::SHAMapInnerNode::getChildPointer : valid branch input"); - ASSERT( + XRPL_ASSERT( !isEmptyBranch(branch), "ripple::SHAMapInnerNode::getChildPointer : non-empty branch input"); @@ -356,10 +355,10 @@ SHAMapInnerNode::getChildPointer(int branch) std::shared_ptr SHAMapInnerNode::getChild(int branch) { - ASSERT( + XRPL_ASSERT( branch >= 0 && branch < branchFactor, "ripple::SHAMapInnerNode::getChild : valid branch input"); - ASSERT( + XRPL_ASSERT( !isEmptyBranch(branch), "ripple::SHAMapInnerNode::getChild : non-empty branch input"); @@ -373,7 +372,7 @@ SHAMapInnerNode::getChild(int branch) SHAMapHash const& SHAMapInnerNode::getChildHash(int m) const { - ASSERT( + XRPL_ASSERT( (m >= 0) && (m < branchFactor), "ripple::SHAMapInnerNode::getChildHash : valid branch input"); if (auto const i = getChildIndex(m)) @@ -387,18 +386,18 @@ SHAMapInnerNode::canonicalizeChild( int branch, std::shared_ptr node) { - ASSERT( + XRPL_ASSERT( branch >= 0 && branch < branchFactor, "ripple::SHAMapInnerNode::canonicalizeChild : valid branch input"); - ASSERT( + XRPL_ASSERT( node != nullptr, "ripple::SHAMapInnerNode::canonicalizeChild : valid node input"); - ASSERT( + XRPL_ASSERT( !isEmptyBranch(branch), "ripple::SHAMapInnerNode::canonicalizeChild : non-empty branch input"); auto const childIndex = *getChildIndex(branch); auto [_, hashes, children] = hashesAndChildren_.getHashesAndChildren(); - ASSERT( + XRPL_ASSERT( node->getHash() == hashes[childIndex], "ripple::SHAMapInnerNode::canonicalizeChild : node and branch inputs " "hash do match"); @@ -431,7 +430,7 @@ SHAMapInnerNode::invariants(bool is_root) const auto const branchCount = getBranchCount(); for (int i = 0; i < branchCount; ++i) { - ASSERT( + XRPL_ASSERT( hashes[i].isNonZero(), "ripple::SHAMapInnerNode::invariants : nonzero hash in branch"); if (children[i] != nullptr) @@ -445,8 +444,8 @@ SHAMapInnerNode::invariants(bool is_root) const { if (hashes[i].isNonZero()) { - ASSERT( - (isBranch_ & (1 << i)) != 0, + XRPL_ASSERT( + (isBranch_ & (1 << i)), "ripple::SHAMapInnerNode::invariants : valid branch when " "nonzero hash"); if (children[i] != nullptr) @@ -455,7 +454,7 @@ SHAMapInnerNode::invariants(bool is_root) const } else { - ASSERT( + XRPL_ASSERT( (isBranch_ & (1 << i)) == 0, "ripple::SHAMapInnerNode::invariants : valid branch when " "zero hash"); @@ -465,13 +464,13 @@ SHAMapInnerNode::invariants(bool is_root) const if (!is_root) { - ASSERT( + XRPL_ASSERT( hash_.isNonZero(), "ripple::SHAMapInnerNode::invariants : nonzero hash"); - ASSERT( + XRPL_ASSERT( count >= 1, "ripple::SHAMapInnerNode::invariants : minimum count"); } - ASSERT( + XRPL_ASSERT( (count == 0) ? hash_.isZero() : hash_.isNonZero(), "ripple::SHAMapInnerNode::invariants : hash and count do match"); } diff --git a/src/xrpld/shamap/detail/SHAMapLeafNode.cpp b/src/xrpld/shamap/detail/SHAMapLeafNode.cpp index f6f13cfdaab..72ec177fb39 100644 --- a/src/xrpld/shamap/detail/SHAMapLeafNode.cpp +++ b/src/xrpld/shamap/detail/SHAMapLeafNode.cpp @@ -28,7 +28,7 @@ SHAMapLeafNode::SHAMapLeafNode( std::uint32_t cowid) : SHAMapTreeNode(cowid), item_(std::move(item)) { - ASSERT( + XRPL_ASSERT( item_->size() >= 12, "ripple::SHAMapLeafNode::SHAMapLeafNode(boost::intrusive_ptr<" "SHAMapItem const>, std::uint32_t) : minimum input size"); @@ -40,7 +40,7 @@ SHAMapLeafNode::SHAMapLeafNode( SHAMapHash const& hash) : SHAMapTreeNode(cowid, hash), item_(std::move(item)) { - ASSERT( + XRPL_ASSERT( item_->size() >= 12, "ripple::SHAMapLeafNode::SHAMapLeafNode(boost::intrusive_ptr<" "SHAMapItem const>, std::uint32_t, SHAMapHash const&) : minimum input " @@ -56,7 +56,7 @@ SHAMapLeafNode::peekItem() const bool SHAMapLeafNode::setItem(boost::intrusive_ptr item) { - ASSERT(cowid_ != 0, "ripple::SHAMapLeafNode::setItem : nonzero cowid"); + XRPL_ASSERT(cowid_, "ripple::SHAMapLeafNode::setItem : nonzero cowid"); item_ = std::move(item); auto const oldHash = hash_; @@ -94,10 +94,9 @@ SHAMapLeafNode::getString(const SHAMapNodeID& id) const void SHAMapLeafNode::invariants(bool) const { - ASSERT( + XRPL_ASSERT( hash_.isNonZero(), "ripple::SHAMapLeafNode::invariants : nonzero hash"); - ASSERT( - item_ != nullptr, "ripple::SHAMapLeafNode::invariants : non-null item"); + XRPL_ASSERT(item_, "ripple::SHAMapLeafNode::invariants : non-null item"); } } // namespace ripple diff --git a/src/xrpld/shamap/detail/SHAMapNodeID.cpp b/src/xrpld/shamap/detail/SHAMapNodeID.cpp index 82cf9436366..7f093dbe46e 100644 --- a/src/xrpld/shamap/detail/SHAMapNodeID.cpp +++ b/src/xrpld/shamap/detail/SHAMapNodeID.cpp @@ -57,10 +57,10 @@ depthMask(unsigned int depth) SHAMapNodeID::SHAMapNodeID(unsigned int depth, uint256 const& hash) : id_(hash), depth_(depth) { - ASSERT( + XRPL_ASSERT( depth <= SHAMap::leafDepth, "ripple::SHAMapNodeID::SHAMapNodeID : maximum depth input"); - ASSERT( + XRPL_ASSERT( id_ == (id_ & depthMask(depth)), "ripple::SHAMapNodeID::SHAMapNodeID : hash and depth inputs do match"); } @@ -77,7 +77,7 @@ SHAMapNodeID::getRawString() const SHAMapNodeID SHAMapNodeID::getChildNodeID(unsigned int m) const { - ASSERT( + XRPL_ASSERT( m < SHAMap::branchFactor, "ripple::SHAMapNodeID::getChildNodeID : valid branch input"); @@ -89,7 +89,7 @@ SHAMapNodeID::getChildNodeID(unsigned int m) const // We throw (but never assert) if the node is at level 64, since // entries at that depth are leaf nodes and have no children and even // constructing a child node from them would break the above invariant. - ASSERT( + XRPL_ASSERT( depth_ <= SHAMap::leafDepth, "ripple::SHAMapNodeID::getChildNodeID : maximum leaf depth"); @@ -136,7 +136,7 @@ selectBranch(SHAMapNodeID const& id, uint256 const& hash) else branch >>= 4; - ASSERT( + XRPL_ASSERT( branch < SHAMap::branchFactor, "ripple::selectBranch : maximum result"); return branch; } @@ -144,7 +144,7 @@ selectBranch(SHAMapNodeID const& id, uint256 const& hash) SHAMapNodeID SHAMapNodeID::createID(int depth, uint256 const& key) { - ASSERT( + XRPL_ASSERT( (depth >= 0) && (depth < 65), "ripple::SHAMapNodeID::createID : valid branch input"); return SHAMapNodeID(depth, key & depthMask(depth)); diff --git a/src/xrpld/shamap/detail/SHAMapSync.cpp b/src/xrpld/shamap/detail/SHAMapSync.cpp index 4425662415e..4f938257511 100644 --- a/src/xrpld/shamap/detail/SHAMapSync.cpp +++ b/src/xrpld/shamap/detail/SHAMapSync.cpp @@ -314,10 +314,10 @@ SHAMap::gmn_ProcessDeferredReads(MissingNodes& mn) std::vector> SHAMap::getMissingNodes(int max, SHAMapSyncFilter* filter) { - ASSERT( + XRPL_ASSERT( root_->getHash().isNonZero(), "ripple::SHAMap::getMissingNodes : nonzero root hash"); - ASSERT(max > 0, "ripple::SHAMap::getMissingNodes : valid max input"); + XRPL_ASSERT(max > 0, "ripple::SHAMap::getMissingNodes : valid max input"); MissingNodes mn( max, @@ -376,8 +376,8 @@ SHAMap::getMissingNodes(int max, SHAMapSyncFilter* filter) // This is a node we are continuing to process fullBelow = fullBelow && was; // was and still is } - ASSERT( - node != nullptr, + XRPL_ASSERT( + node, "ripple::SHAMap::getMissingNodes : first non-null node"); } } @@ -409,8 +409,8 @@ SHAMap::getMissingNodes(int max, SHAMapSyncFilter* filter) // Resume at the top of the stack pos = mn.stack_.top(); mn.stack_.pop(); - ASSERT( - node != nullptr, + XRPL_ASSERT( + node, "ripple::SHAMap::getMissingNodes : second non-null node"); } } @@ -538,13 +538,13 @@ SHAMap::addRootNode( if (root_->getHash().isNonZero()) { JLOG(journal_.trace()) << "got root node, already have one"; - ASSERT( + XRPL_ASSERT( root_->getHash() == hash, "ripple::SHAMap::addRootNode : valid hash input"); return SHAMapAddNode::duplicate(); } - ASSERT(cowid_ >= 1, "ripple::SHAMap::addRootNode : valid cowid"); + XRPL_ASSERT(cowid_ >= 1, "ripple::SHAMap::addRootNode : valid cowid"); auto node = SHAMapTreeNode::makeFromWire(rootNode); if (!node || node->getHash() != hash) return SHAMapAddNode::invalid(); @@ -578,7 +578,8 @@ SHAMap::addKnownNode( Slice const& rawNode, SHAMapSyncFilter* filter) { - ASSERT(!node.isRoot(), "ripple::SHAMap::addKnownNode : valid node input"); + XRPL_ASSERT( + !node.isRoot(), "ripple::SHAMap::addKnownNode : valid node input"); if (!isSynching()) { @@ -595,7 +596,7 @@ SHAMap::addKnownNode( (iNodeID.getDepth() < node.getDepth())) { int branch = selectBranch(iNodeID, node.getNodeID()); - ASSERT(branch >= 0, "ripple::SHAMap::addKnownNode : valid branch"); + XRPL_ASSERT(branch >= 0, "ripple::SHAMap::addKnownNode : valid branch"); auto inner = static_cast(iNode); if (inner->isEmptyBranch(branch)) { diff --git a/src/xrpld/shamap/detail/TaggedPointer.ipp b/src/xrpld/shamap/detail/TaggedPointer.ipp index 3833ce58a11..0e67947a8ed 100644 --- a/src/xrpld/shamap/detail/TaggedPointer.ipp +++ b/src/xrpld/shamap/detail/TaggedPointer.ipp @@ -79,7 +79,7 @@ constexpr auto chunksPerBlock = [[nodiscard]] inline std::uint8_t numAllocatedChildren(std::uint8_t n) { - ASSERT( + XRPL_ASSERT( n <= SHAMapInnerNode::branchFactor, "ripple::numAllocatedChildren : valid input"); return *std::lower_bound(boundaries.begin(), boundaries.end(), n); @@ -88,7 +88,7 @@ numAllocatedChildren(std::uint8_t n) [[nodiscard]] inline std::size_t boundariesIndex(std::uint8_t numChildren) { - ASSERT( + XRPL_ASSERT( numChildren <= SHAMapInnerNode::branchFactor, "ripple::boundariesIndex : valid input"); return std::distance( @@ -160,7 +160,7 @@ allocateArrays(std::uint8_t numChildren) inline void deallocateArrays(std::uint8_t boundaryIndex, void* p) { - ASSERT( + XRPL_ASSERT( isFromArrayFuns[boundaryIndex](p), "ripple::deallocateArrays : valid inputs"); freeArrayFuns[boundaryIndex](p); @@ -276,11 +276,11 @@ TaggedPointer::getChildIndex(std::uint16_t isBranch, int i) const inline TaggedPointer::TaggedPointer(RawAllocateTag, std::uint8_t numChildren) { auto [tag, p] = allocateArrays(numChildren); - ASSERT( + XRPL_ASSERT( tag < boundaries.size(), "ripple::TaggedPointer::TaggedPointer(RawAllocateTag, std::uint8_t) : " "maximum tag"); - ASSERT( + XRPL_ASSERT( (reinterpret_cast(p) & ptrMask) == reinterpret_cast(p), "ripple::TaggedPointer::TaggedPointer(RawAllocateTag, std::uint8_t) : " @@ -294,7 +294,7 @@ inline TaggedPointer::TaggedPointer( std::uint16_t dstBranches, std::uint8_t toAllocate) { - ASSERT( + XRPL_ASSERT( toAllocate >= popcnt16(dstBranches), "ripple::TaggedPointer::TaggedPointer(TaggedPointer&& ...) : minimum " "toAllocate input"); @@ -442,7 +442,7 @@ inline TaggedPointer::TaggedPointer( } } // If sparse, may need to run additional constructors - ASSERT( + XRPL_ASSERT( !dstIsDense || dstIndex == dstNumAllocated, "ripple::TaggedPointer::TaggedPointer(TaggedPointer&& ...) : " "non-sparse or valid sparse"); From 5cd72f2431e7e9da968ba930c75b9b52c619dad1 Mon Sep 17 00:00:00 2001 From: Gregory Tsipenyuk Date: Mon, 16 Dec 2024 17:52:48 -0500 Subject: [PATCH 2/5] Add MPTIssue to STIssue (#5200) Replace Issue in STIssue with Asset. STIssue with MPTIssue is only used in MPT tests. Will be used in Vault and in transactions with STIssue fields once MPT is integrated into DEX. --- include/xrpl/protocol/Asset.h | 33 ++++- include/xrpl/protocol/Indexes.h | 2 +- include/xrpl/protocol/Issue.h | 5 +- include/xrpl/protocol/MPTIssue.h | 10 +- include/xrpl/protocol/SOTemplate.h | 13 +- include/xrpl/protocol/STAmount.h | 5 - include/xrpl/protocol/STIssue.h | 102 ++++++++++----- include/xrpl/protocol/STXChainBridge.h | 4 +- src/libxrpl/protocol/Indexes.cpp | 6 +- src/libxrpl/protocol/STIssue.cpp | 88 +++++++++---- src/libxrpl/protocol/STTx.cpp | 6 +- src/test/app/MPToken_test.cpp | 109 +++++++++++----- src/test/protocol/STIssue_test.cpp | 164 ++++++++++++++++++++++++ src/xrpld/app/ledger/OrderBookDB.cpp | 4 +- src/xrpld/app/misc/detail/AMMUtils.cpp | 8 +- src/xrpld/app/tx/detail/AMMBid.cpp | 3 +- src/xrpld/app/tx/detail/AMMClawback.cpp | 14 +- src/xrpld/app/tx/detail/AMMDelete.cpp | 4 +- src/xrpld/app/tx/detail/AMMDeposit.cpp | 8 +- src/xrpld/app/tx/detail/AMMVote.cpp | 3 +- src/xrpld/app/tx/detail/AMMWithdraw.cpp | 11 +- src/xrpld/rpc/handlers/AMMInfo.cpp | 4 +- 22 files changed, 463 insertions(+), 143 deletions(-) create mode 100644 src/test/protocol/STIssue_test.cpp diff --git a/include/xrpl/protocol/Asset.h b/include/xrpl/protocol/Asset.h index 2cccc28bd41..0d12cd40580 100644 --- a/include/xrpl/protocol/Asset.h +++ b/include/xrpl/protocol/Asset.h @@ -26,10 +26,17 @@ namespace ripple { +class Asset; + template concept ValidIssueType = std::is_same_v || std::is_same_v; +template +concept AssetType = + std::is_convertible_v || std::is_convertible_v || + std::is_convertible_v || std::is_convertible_v; + /* Asset is an abstraction of three different issue types: XRP, IOU, MPT. * For historical reasons, two issue types XRP and IOU are wrapped in Issue * type. Many functions and classes there were first written for Issue @@ -37,8 +44,10 @@ concept ValidIssueType = */ class Asset { -private: +public: using value_type = std::variant; + +private: value_type issue_; public: @@ -92,8 +101,8 @@ class Asset friend constexpr bool operator==(Asset const& lhs, Asset const& rhs); - friend constexpr bool - operator!=(Asset const& lhs, Asset const& rhs); + friend constexpr std::weak_ordering + operator<=>(Asset const& lhs, Asset const& rhs); friend constexpr bool operator==(Currency const& lhs, Asset const& rhs); @@ -151,10 +160,22 @@ operator==(Asset const& lhs, Asset const& rhs) rhs.issue_); } -constexpr bool -operator!=(Asset const& lhs, Asset const& rhs) +constexpr std::weak_ordering +operator<=>(Asset const& lhs, Asset const& rhs) { - return !(lhs == rhs); + return std::visit( + []( + TLhs const& lhs_, TRhs const& rhs_) { + if constexpr (std::is_same_v) + return std::weak_ordering(lhs_ <=> rhs_); + else if constexpr ( + std::is_same_v && std::is_same_v) + return std::weak_ordering::greater; + else + return std::weak_ordering::less; + }, + lhs.issue_, + rhs.issue_); } constexpr bool diff --git a/include/xrpl/protocol/Indexes.h b/include/xrpl/protocol/Indexes.h index fe0be5d0cb0..3ce6ef8e836 100644 --- a/include/xrpl/protocol/Indexes.h +++ b/include/xrpl/protocol/Indexes.h @@ -274,7 +274,7 @@ nft_sells(uint256 const& id) noexcept; /** AMM entry */ Keylet -amm(Issue const& issue1, Issue const& issue2) noexcept; +amm(Asset const& issue1, Asset const& issue2) noexcept; Keylet amm(uint256 const& amm) noexcept; diff --git a/include/xrpl/protocol/Issue.h b/include/xrpl/protocol/Issue.h index 60182698ee6..83ef337c357 100644 --- a/include/xrpl/protocol/Issue.h +++ b/include/xrpl/protocol/Issue.h @@ -58,6 +58,9 @@ class Issue bool native() const; + + friend constexpr std::weak_ordering + operator<=>(Issue const& lhs, Issue const& rhs); }; bool @@ -95,7 +98,7 @@ operator==(Issue const& lhs, Issue const& rhs) /** Strict weak ordering. */ /** @{ */ -[[nodiscard]] inline constexpr std::weak_ordering +[[nodiscard]] constexpr std::weak_ordering operator<=>(Issue const& lhs, Issue const& rhs) { if (auto const c{lhs.currency <=> rhs.currency}; c != 0) diff --git a/include/xrpl/protocol/MPTIssue.h b/include/xrpl/protocol/MPTIssue.h index 06f55686caf..028051ab1ae 100644 --- a/include/xrpl/protocol/MPTIssue.h +++ b/include/xrpl/protocol/MPTIssue.h @@ -54,8 +54,8 @@ class MPTIssue friend constexpr bool operator==(MPTIssue const& lhs, MPTIssue const& rhs); - friend constexpr bool - operator!=(MPTIssue const& lhs, MPTIssue const& rhs); + friend constexpr std::weak_ordering + operator<=>(MPTIssue const& lhs, MPTIssue const& rhs); bool native() const @@ -70,10 +70,10 @@ operator==(MPTIssue const& lhs, MPTIssue const& rhs) return lhs.mptID_ == rhs.mptID_; } -constexpr bool -operator!=(MPTIssue const& lhs, MPTIssue const& rhs) +constexpr std::weak_ordering +operator<=>(MPTIssue const& lhs, MPTIssue const& rhs) { - return !(lhs == rhs); + return lhs.mptID_ <=> rhs.mptID_; } /** MPT is a non-native token. diff --git a/include/xrpl/protocol/SOTemplate.h b/include/xrpl/protocol/SOTemplate.h index 95cd35fead2..b86fb63b858 100644 --- a/include/xrpl/protocol/SOTemplate.h +++ b/include/xrpl/protocol/SOTemplate.h @@ -40,7 +40,7 @@ enum SOEStyle { }; /** Amount fields that can support MPT */ -enum SOETxMPTAmount { soeMPTNone, soeMPTSupported, soeMPTNotSupported }; +enum SOETxMPTIssue { soeMPTNone, soeMPTSupported, soeMPTNotSupported }; //------------------------------------------------------------------------------ @@ -50,7 +50,7 @@ class SOElement // Use std::reference_wrapper so SOElement can be stored in a std::vector. std::reference_wrapper sField_; SOEStyle style_; - SOETxMPTAmount supportMpt_ = soeMPTNone; + SOETxMPTIssue supportMpt_ = soeMPTNone; private: void @@ -72,10 +72,13 @@ class SOElement { init(fieldName); } + + template + requires(std::is_same_v || std::is_same_v) SOElement( - TypedField const& fieldName, + TypedField const& fieldName, SOEStyle style, - SOETxMPTAmount supportMpt = soeMPTNotSupported) + SOETxMPTIssue supportMpt = soeMPTNotSupported) : sField_(fieldName), style_(style), supportMpt_(supportMpt) { init(fieldName); @@ -93,7 +96,7 @@ class SOElement return style_; } - SOETxMPTAmount + SOETxMPTIssue supportMPT() const { return supportMpt_; diff --git a/include/xrpl/protocol/STAmount.h b/include/xrpl/protocol/STAmount.h index a20f06ea307..23e4c5e5b59 100644 --- a/include/xrpl/protocol/STAmount.h +++ b/include/xrpl/protocol/STAmount.h @@ -36,11 +36,6 @@ namespace ripple { -template -concept AssetType = - std::is_same_v || std::is_convertible_v || - std::is_convertible_v || std::is_convertible_v; - // Internal form: // 1: If amount is zero, then value is zero and offset is -100 // 2: Otherwise: diff --git a/include/xrpl/protocol/STIssue.h b/include/xrpl/protocol/STIssue.h index a0dfbd4faec..08812c15aec 100644 --- a/include/xrpl/protocol/STIssue.h +++ b/include/xrpl/protocol/STIssue.h @@ -21,7 +21,7 @@ #define RIPPLE_PROTOCOL_STISSUE_H_INCLUDED #include -#include +#include #include #include #include @@ -31,31 +31,40 @@ namespace ripple { class STIssue final : public STBase, CountedObject { private: - Issue issue_{xrpIssue()}; + Asset asset_{xrpIssue()}; public: - using value_type = Issue; + using value_type = Asset; STIssue() = default; explicit STIssue(SerialIter& sit, SField const& name); - explicit STIssue(SField const& name, Issue const& issue); + template + explicit STIssue(SField const& name, A const& issue); explicit STIssue(SField const& name); - Issue const& - issue() const; + template + TIss const& + get() const; - Issue const& + template + bool + holds() const; + + value_type const& value() const noexcept; void - setIssue(Issue const& issue); + setIssue(Asset const& issue); SerializedTypeID getSType() const override; + std::string + getText() const override; + Json::Value getJson(JsonOptions) const override; void @@ -67,6 +76,18 @@ class STIssue final : public STBase, CountedObject bool isDefault() const override; + friend constexpr bool + operator==(STIssue const& lhs, STIssue const& rhs); + + friend constexpr std::weak_ordering + operator<=>(STIssue const& lhs, STIssue const& rhs); + + friend constexpr bool + operator==(STIssue const& lhs, Asset const& rhs); + + friend constexpr std::weak_ordering + operator<=>(STIssue const& lhs, Asset const& rhs); + private: STBase* copy(std::size_t n, void* buf) const override; @@ -76,59 +97,72 @@ class STIssue final : public STBase, CountedObject friend class detail::STVar; }; +template +STIssue::STIssue(SField const& name, A const& asset) + : STBase{name}, asset_{asset} +{ + if (holds() && !isConsistent(asset_.get())) + Throw( + "Invalid asset: currency and account native mismatch"); +} + STIssue issueFromJson(SField const& name, Json::Value const& v); -inline Issue const& -STIssue::issue() const +template +bool +STIssue::holds() const +{ + return asset_.holds(); +} + +template +TIss const& +STIssue::get() const { - return issue_; + if (!holds(asset_)) + Throw("Asset doesn't hold the requested issue"); + return std::get(asset_); } -inline Issue const& +inline STIssue::value_type const& STIssue::value() const noexcept { - return issue_; + return asset_; } inline void -STIssue::setIssue(Issue const& issue) +STIssue::setIssue(Asset const& asset) { - if (isXRP(issue_.currency) != isXRP(issue_.account)) + if (holds() && !isConsistent(asset_.get())) Throw( - "invalid issue: currency and account native mismatch"); + "Invalid asset: currency and account native mismatch"); - issue_ = issue; + asset_ = asset; } -inline bool +constexpr bool operator==(STIssue const& lhs, STIssue const& rhs) { - return lhs.issue() == rhs.issue(); -} - -inline bool -operator!=(STIssue const& lhs, STIssue const& rhs) -{ - return !operator==(lhs, rhs); + return lhs.asset_ == rhs.asset_; } -inline bool -operator<(STIssue const& lhs, STIssue const& rhs) +constexpr std::weak_ordering +operator<=>(STIssue const& lhs, STIssue const& rhs) { - return lhs.issue() < rhs.issue(); + return lhs.asset_ <=> rhs.asset_; } -inline bool -operator==(STIssue const& lhs, Issue const& rhs) +constexpr bool +operator==(STIssue const& lhs, Asset const& rhs) { - return lhs.issue() == rhs; + return lhs.asset_ == rhs; } -inline bool -operator<(STIssue const& lhs, Issue const& rhs) +constexpr std::weak_ordering +operator<=>(STIssue const& lhs, Asset const& rhs) { - return lhs.issue() < rhs; + return lhs.asset_ <=> rhs; } } // namespace ripple diff --git a/include/xrpl/protocol/STXChainBridge.h b/include/xrpl/protocol/STXChainBridge.h index 38db1912c70..813bcc44437 100644 --- a/include/xrpl/protocol/STXChainBridge.h +++ b/include/xrpl/protocol/STXChainBridge.h @@ -170,7 +170,7 @@ STXChainBridge::lockingChainDoor() const inline Issue const& STXChainBridge::lockingChainIssue() const { - return lockingChainIssue_.value(); + return lockingChainIssue_.value().get(); }; inline AccountID const& @@ -182,7 +182,7 @@ STXChainBridge::issuingChainDoor() const inline Issue const& STXChainBridge::issuingChainIssue() const { - return issuingChainIssue_.value(); + return issuingChainIssue_.value().get(); }; inline STXChainBridge::value_type const& diff --git a/src/libxrpl/protocol/Indexes.cpp b/src/libxrpl/protocol/Indexes.cpp index 730610707f7..c7f4441c7bc 100644 --- a/src/libxrpl/protocol/Indexes.cpp +++ b/src/libxrpl/protocol/Indexes.cpp @@ -18,6 +18,7 @@ //============================================================================== #include +#include #include #include #include @@ -417,9 +418,10 @@ nft_sells(uint256 const& id) noexcept } Keylet -amm(Issue const& issue1, Issue const& issue2) noexcept +amm(Asset const& issue1, Asset const& issue2) noexcept { - auto const& [minI, maxI] = std::minmax(issue1, issue2); + auto const& [minI, maxI] = + std::minmax(issue1.get(), issue2.get()); return amm(indexHash( LedgerNameSpace::AMM, minI.account, diff --git a/src/libxrpl/protocol/STIssue.cpp b/src/libxrpl/protocol/STIssue.cpp index 00fe86b3287..5a2008cb178 100644 --- a/src/libxrpl/protocol/STIssue.cpp +++ b/src/libxrpl/protocol/STIssue.cpp @@ -40,23 +40,46 @@ STIssue::STIssue(SField const& name) : STBase{name} STIssue::STIssue(SerialIter& sit, SField const& name) : STBase{name} { - issue_.currency = sit.get160(); - if (!isXRP(issue_.currency)) - issue_.account = sit.get160(); - else - issue_.account = xrpAccount(); - - if (isXRP(issue_.currency) != isXRP(issue_.account)) - Throw( - "invalid issue: currency and account native mismatch"); -} + auto const currencyOrAccount = sit.get160(); -STIssue::STIssue(SField const& name, Issue const& issue) - : STBase{name}, issue_{issue} -{ - if (isXRP(issue_.currency) != isXRP(issue_.account)) - Throw( - "invalid issue: currency and account native mismatch"); + if (isXRP(static_cast(currencyOrAccount))) + { + asset_ = xrpIssue(); + } + // Check if MPT + else + { + // MPT is serialized as: + // - 160 bits MPT issuer account + // - 160 bits black hole account + // - 32 bits sequence + AccountID account = static_cast(sit.get160()); + // MPT + if (noAccount() == account) + { + MPTID mptID; + std::uint32_t sequence = sit.get32(); + static_assert( + MPTID::size() == sizeof(sequence) + sizeof(currencyOrAccount)); + memcpy(mptID.data(), &sequence, sizeof(sequence)); + memcpy( + mptID.data() + sizeof(sequence), + currencyOrAccount.data(), + sizeof(currencyOrAccount)); + MPTIssue issue{mptID}; + asset_ = issue; + } + else + { + Issue issue; + issue.currency = currencyOrAccount; + issue.account = account; + if (!isConsistent(issue)) + Throw( + "invalid issue: currency and account native mismatch"); + asset_ = issue; + } + } } SerializedTypeID @@ -65,18 +88,39 @@ STIssue::getSType() const return STI_ISSUE; } +std::string +STIssue::getText() const +{ + return asset_.getText(); +} + Json::Value STIssue::getJson(JsonOptions) const { - return to_json(issue_); + Json::Value jv; + asset_.setJson(jv); + return jv; } void STIssue::add(Serializer& s) const { - s.addBitString(issue_.currency); - if (!isXRP(issue_.currency)) - s.addBitString(issue_.account); + if (holds()) + { + auto const& issue = asset_.get(); + s.addBitString(issue.currency); + if (!isXRP(issue.currency)) + s.addBitString(issue.account); + } + else + { + auto const& issue = asset_.get(); + s.addBitString(issue.getIssuer()); + s.addBitString(noAccount()); + std::uint32_t sequence; + memcpy(&sequence, issue.getMptID().data(), sizeof(sequence)); + s.add32(sequence); + } } bool @@ -89,7 +133,7 @@ STIssue::isEquivalent(const STBase& t) const bool STIssue::isDefault() const { - return issue_ == xrpIssue(); + return holds() && asset_.get() == xrpIssue(); } STBase* @@ -107,7 +151,7 @@ STIssue::move(std::size_t n, void* buf) STIssue issueFromJson(SField const& name, Json::Value const& v) { - return STIssue{name, issueFromJson(v)}; + return STIssue{name, assetFromJson(v)}; } } // namespace ripple diff --git a/src/libxrpl/protocol/STTx.cpp b/src/libxrpl/protocol/STTx.cpp index 7c862578ba3..bd1c461c8c7 100644 --- a/src/libxrpl/protocol/STTx.cpp +++ b/src/libxrpl/protocol/STTx.cpp @@ -559,8 +559,10 @@ invalidMPTAmountInTx(STObject const& tx) if (tx.isFieldPresent(e.sField()) && e.supportMPT() != soeMPTNone) { if (auto const& field = tx.peekAtField(e.sField()); - field.getSType() == STI_AMOUNT && - static_cast(field).holds()) + (field.getSType() == STI_AMOUNT && + static_cast(field).holds()) || + (field.getSType() == STI_ISSUE && + static_cast(field).holds())) { if (e.supportMPT() != soeMPTSupported) return true; diff --git a/src/test/app/MPToken_test.cpp b/src/test/app/MPToken_test.cpp index 796a3f14c88..9fd4927d5eb 100644 --- a/src/test/app/MPToken_test.cpp +++ b/src/test/app/MPToken_test.cpp @@ -1470,19 +1470,19 @@ class MPToken_test : public beast::unit_test::suite void testMPTInvalidInTx(FeatureBitset features) { - testcase("MPT Amount Invalid in Transaction"); + testcase("MPT Issue Invalid in Transaction"); using namespace test::jtx; - // Validate that every transaction with an amount field, + // Validate that every transaction with an amount/issue field, // which doesn't support MPT, fails. - // keyed by transaction + amount field + // keyed by transaction + amount/issue field std::set txWithAmounts; for (auto const& format : TxFormats::getInstance()) { for (auto const& e : format.getSOTemplate()) { - // Transaction has amount fields. + // Transaction has amount/issue fields. // Exclude pseudo-transaction SetFee. Don't consider // the Fee field since it's included in every transaction. if (e.supportMPT() == soeMPTNotSupported && @@ -1508,9 +1508,9 @@ class MPToken_test : public beast::unit_test::suite env.fund(XRP(1'000), alice); env.fund(XRP(1'000), carol); auto test = [&](Json::Value const& jv, - std::string const& amtField) { + std::string const& mptField) { txWithAmounts.erase( - jv[jss::TransactionType].asString() + amtField); + jv[jss::TransactionType].asString() + mptField); // tx is signed auto jtx = env.jt(jv); @@ -1530,8 +1530,27 @@ class MPToken_test : public beast::unit_test::suite jrr = env.rpc("json", "sign", to_string(jv1)); BEAST_EXPECT(jrr[jss::result][jss::error] == "invalidParams"); }; - // All transactions with sfAmount, which don't support MPT - // and transactions with amount fields, which can't be MPT + auto toSFieldRef = [](SField const& field) { + return std::ref(field); + }; + auto setMPTFields = [&](SField const& field, + Json::Value& jv, + bool withAmount = true) { + jv[jss::Asset] = to_json(xrpIssue()); + jv[jss::Asset2] = to_json(USD.issue()); + 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. + // Transactions with issue fields, which can't be MPT. // AMMCreate auto ammCreate = [&](SField const& field) { @@ -1554,58 +1573,84 @@ class MPToken_test : public beast::unit_test::suite Json::Value jv; jv[jss::TransactionType] = jss::AMMDeposit; jv[jss::Account] = alice.human(); - jv[jss::Asset] = to_json(xrpIssue()); - jv[jss::Asset2] = to_json(USD.issue()); - jv[field.fieldName] = mpt.getJson(JsonOptions::none); jv[jss::Flags] = tfSingleAsset; + setMPTFields(field, jv); test(jv, field.fieldName); }; for (SField const& field : - {std::ref(sfAmount), - std::ref(sfAmount2), - std::ref(sfEPrice), - std::ref(sfLPTokenOut)}) + {toSFieldRef(sfAmount), + toSFieldRef(sfAmount2), + toSFieldRef(sfEPrice), + toSFieldRef(sfLPTokenOut), + toSFieldRef(sfAsset), + toSFieldRef(sfAsset2)}) ammDeposit(field); // AMMWithdraw auto ammWithdraw = [&](SField const& field) { Json::Value jv; jv[jss::TransactionType] = jss::AMMWithdraw; jv[jss::Account] = alice.human(); - jv[jss::Asset] = to_json(xrpIssue()); - jv[jss::Asset2] = to_json(USD.issue()); jv[jss::Flags] = tfSingleAsset; - jv[field.fieldName] = mpt.getJson(JsonOptions::none); + setMPTFields(field, jv); test(jv, field.fieldName); }; ammWithdraw(sfAmount); for (SField const& field : - {std::ref(sfAmount2), - std::ref(sfEPrice), - std::ref(sfLPTokenIn)}) + {toSFieldRef(sfAmount2), + toSFieldRef(sfEPrice), + toSFieldRef(sfLPTokenIn), + toSFieldRef(sfAsset), + toSFieldRef(sfAsset2)}) ammWithdraw(field); // AMMBid auto ammBid = [&](SField const& field) { Json::Value jv; jv[jss::TransactionType] = jss::AMMBid; jv[jss::Account] = alice.human(); - jv[jss::Asset] = to_json(xrpIssue()); - jv[jss::Asset2] = to_json(USD.issue()); - jv[field.fieldName] = mpt.getJson(JsonOptions::none); + setMPTFields(field, jv); test(jv, field.fieldName); }; - ammBid(sfBidMin); - ammBid(sfBidMax); + for (SField const& field : + {toSFieldRef(sfBidMin), + toSFieldRef(sfBidMax), + toSFieldRef(sfAsset), + toSFieldRef(sfAsset2)}) + ammBid(field); // AMMClawback - { + auto ammClawback = [&](SField const& field) { Json::Value jv; jv[jss::TransactionType] = jss::AMMClawback; jv[jss::Account] = alice.human(); jv[jss::Holder] = carol.human(); - jv[jss::Asset] = to_json(xrpIssue()); - jv[jss::Asset2] = to_json(USD.issue()); - jv[jss::Amount] = mpt.getJson(JsonOptions::none); - test(jv, jss::Amount.c_str()); - } + setMPTFields(field, jv); + test(jv, field.fieldName); + }; + for (SField const& field : + {toSFieldRef(sfAmount), + toSFieldRef(sfAsset), + toSFieldRef(sfAsset2)}) + ammClawback(field); + // AMMDelete + auto ammDelete = [&](SField const& field) { + Json::Value jv; + jv[jss::TransactionType] = jss::AMMDelete; + jv[jss::Account] = alice.human(); + setMPTFields(field, jv, false); + test(jv, field.fieldName); + }; + ammDelete(sfAsset); + ammDelete(sfAsset2); + // AMMVote + auto ammVote = [&](SField const& field) { + Json::Value jv; + jv[jss::TransactionType] = jss::AMMVote; + jv[jss::Account] = alice.human(); + jv[jss::TradingFee] = 100; + setMPTFields(field, jv, false); + test(jv, field.fieldName); + }; + ammVote(sfAsset); + ammVote(sfAsset2); // CheckCash auto checkCash = [&](SField const& field) { Json::Value jv; diff --git a/src/test/protocol/STIssue_test.cpp b/src/test/protocol/STIssue_test.cpp new file mode 100644 index 00000000000..4c9eeb0ba1b --- /dev/null +++ b/src/test/protocol/STIssue_test.cpp @@ -0,0 +1,164 @@ +//------------------------------------------------------------------------------ +/* + This file is part of rippled: https://github.com/ripple/rippled + Copyright (c) 2024 Ripple Labs Inc. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted, provided that the above + copyright notice and this permission notice appear in all copies. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +*/ +//============================================================================== + +#include +#include +#include + +namespace ripple { +namespace test { + +class STIssue_test : public beast::unit_test::suite +{ +public: + void + testConstructor() + { + testcase("Constructor"); + using namespace jtx; + Account const alice{"alice"}; + auto const USD = alice["USD"]; + Issue issue; + + try + { + issue = xrpIssue(); + issue.account = alice; + STIssue stissue(sfAsset, Asset{issue}); + fail("Inconsistent XRP Issue doesn't fail"); + } + catch (...) + { + pass(); + } + + try + { + issue = USD; + issue.account = xrpAccount(); + STIssue stissue(sfAsset, Asset{issue}); + fail("Inconsistent IOU Issue doesn't fail"); + } + catch (...) + { + pass(); + } + + try + { + // Currency is USD but account is XRP + auto const data = + "00000000000000000000000055534400000000000000000000000000000000" + "000000000000000000"; + base_uint<320> uint; + (void)uint.parseHex(data); + SerialIter iter(Slice(uint.data(), uint.size())); + STIssue stissue(iter, sfAsset); + fail("Inconsistent IOU Issue doesn't fail on serializer"); + } + catch (...) + { + pass(); + } + + try + { + STIssue stissue(sfAsset, Asset{xrpIssue()}); + } + catch (...) + { + fail("XRP issue failed"); + } + + try + { + STIssue stissue(sfAsset, Asset{USD}); + } + catch (...) + { + fail("USD issue failed"); + } + + try + { + auto const data = + "0000000000000000000000005553440000000000ae123a8556f3cf91154711" + "376afb0f894f832b3d"; + base_uint<320> uint; + (void)uint.parseHex(data); + SerialIter iter(Slice(uint.data(), uint.size())); + STIssue stissue(iter, sfAsset); + BEAST_EXPECT(stissue.value() == USD); + } + catch (...) + { + fail("USD Issue fails on serializer"); + } + + try + { + auto const data = "0000000000000000000000000000000000000000"; + base_uint<160> uint; + (void)uint.parseHex(data); + SerialIter iter(Slice(uint.data(), uint.size())); + STIssue stissue(iter, sfAsset); + BEAST_EXPECT(stissue.value() == xrpCurrency()); + } + catch (...) + { + fail("XRP Issue fails on serializer"); + } + } + + void + testCompare() + { + testcase("Compare"); + using namespace jtx; + Account const alice{"alice"}; + auto const USD = alice["USD"]; + Asset const asset1{xrpIssue()}; + Asset const asset2{USD}; + Asset const asset3{MPTID{2}}; + + BEAST_EXPECT(STIssue(sfAsset, asset1) != asset2); + BEAST_EXPECT(STIssue(sfAsset, asset1) != asset3); + BEAST_EXPECT(STIssue(sfAsset, asset1) == asset1); + BEAST_EXPECT(STIssue(sfAsset, asset1).getText() == "XRP"); + BEAST_EXPECT( + STIssue(sfAsset, asset2).getText() == + "USD/rG1QQv2nh2gr7RCZ1P8YYcBUKCCN633jCn"); + BEAST_EXPECT( + STIssue(sfAsset, asset3).getText() == + "000000000000000000000000000000000000000000000002"); + } + + void + run() override + { + // compliments other unit tests to ensure complete coverage + testConstructor(); + testCompare(); + } +}; + +BEAST_DEFINE_TESTSUITE(STIssue, ripple_data, ripple); + +} // namespace test +} // namespace ripple \ No newline at end of file diff --git a/src/xrpld/app/ledger/OrderBookDB.cpp b/src/xrpld/app/ledger/OrderBookDB.cpp index f9f95e76691..265e0b62905 100644 --- a/src/xrpld/app/ledger/OrderBookDB.cpp +++ b/src/xrpld/app/ledger/OrderBookDB.cpp @@ -129,8 +129,8 @@ OrderBookDB::update(std::shared_ptr const& ledger) } else if (sle->getType() == ltAMM) { - auto const issue1 = (*sle)[sfAsset]; - auto const issue2 = (*sle)[sfAsset2]; + auto const issue1 = (*sle)[sfAsset].get(); + auto const issue2 = (*sle)[sfAsset2].get(); auto addBook = [&](Issue const& in, Issue const& out) { allBooks[in].insert(out); diff --git a/src/xrpld/app/misc/detail/AMMUtils.cpp b/src/xrpld/app/misc/detail/AMMUtils.cpp index 172b2ee1101..f5f6ae6612c 100644 --- a/src/xrpld/app/misc/detail/AMMUtils.cpp +++ b/src/xrpld/app/misc/detail/AMMUtils.cpp @@ -51,8 +51,8 @@ ammHolds( beast::Journal const j) { auto const issues = [&]() -> std::optional> { - auto const issue1 = ammSle[sfAsset]; - auto const issue2 = ammSle[sfAsset2]; + auto const issue1 = ammSle[sfAsset].get(); + auto const issue2 = ammSle[sfAsset2].get(); if (optIssue1 && optIssue2) { if (invalidAMMAssetPair( @@ -134,8 +134,8 @@ ammLPHolds( { return ammLPHolds( view, - ammSle[sfAsset].currency, - ammSle[sfAsset2].currency, + ammSle[sfAsset].get().currency, + ammSle[sfAsset2].get().currency, ammSle[sfAccount], lpAccount, j); diff --git a/src/xrpld/app/tx/detail/AMMBid.cpp b/src/xrpld/app/tx/detail/AMMBid.cpp index 8b93ed02c36..e8a14c14922 100644 --- a/src/xrpld/app/tx/detail/AMMBid.cpp +++ b/src/xrpld/app/tx/detail/AMMBid.cpp @@ -46,7 +46,8 @@ AMMBid::preflight(PreflightContext const& ctx) return temINVALID_FLAG; } - if (auto const res = invalidAMMAssetPair(ctx.tx[sfAsset], ctx.tx[sfAsset2])) + if (auto const res = invalidAMMAssetPair( + ctx.tx[sfAsset].get(), ctx.tx[sfAsset2].get())) { JLOG(ctx.j.debug()) << "AMM Bid: Invalid asset pair."; return res; diff --git a/src/xrpld/app/tx/detail/AMMClawback.cpp b/src/xrpld/app/tx/detail/AMMClawback.cpp index cd1e3008e97..162224ff913 100644 --- a/src/xrpld/app/tx/detail/AMMClawback.cpp +++ b/src/xrpld/app/tx/detail/AMMClawback.cpp @@ -57,8 +57,8 @@ AMMClawback::preflight(PreflightContext const& ctx) } std::optional const clawAmount = ctx.tx[~sfAmount]; - auto const asset = ctx.tx[sfAsset]; - auto const asset2 = ctx.tx[sfAsset2]; + auto const asset = ctx.tx[sfAsset].get(); + auto const asset2 = ctx.tx[sfAsset2].get(); if (isXRP(asset)) return temMALFORMED; @@ -78,7 +78,7 @@ AMMClawback::preflight(PreflightContext const& ctx) return temMALFORMED; } - if (clawAmount && clawAmount->issue() != asset) + if (clawAmount && clawAmount->get() != asset) { JLOG(ctx.j.trace()) << "AMMClawback: Amount's issuer/currency subfield " "does not match Asset field"; @@ -94,8 +94,8 @@ AMMClawback::preflight(PreflightContext const& ctx) TER AMMClawback::preclaim(PreclaimContext const& ctx) { - auto const asset = ctx.tx[sfAsset]; - auto const asset2 = ctx.tx[sfAsset2]; + auto const asset = ctx.tx[sfAsset].get(); + auto const asset2 = ctx.tx[sfAsset2].get(); auto const sleIssuer = ctx.view.read(keylet::account(ctx.tx[sfAccount])); if (!sleIssuer) return terNO_ACCOUNT; // LCOV_EXCL_LINE @@ -139,8 +139,8 @@ AMMClawback::applyGuts(Sandbox& sb) std::optional const clawAmount = ctx_.tx[~sfAmount]; AccountID const issuer = ctx_.tx[sfAccount]; AccountID const holder = ctx_.tx[sfHolder]; - Issue const asset = ctx_.tx[sfAsset]; - Issue const asset2 = ctx_.tx[sfAsset2]; + Issue const asset = ctx_.tx[sfAsset].get(); + Issue const asset2 = ctx_.tx[sfAsset2].get(); auto ammSle = sb.peek(keylet::amm(asset, asset2)); if (!ammSle) diff --git a/src/xrpld/app/tx/detail/AMMDelete.cpp b/src/xrpld/app/tx/detail/AMMDelete.cpp index 89ce34052d2..430ac17e87b 100644 --- a/src/xrpld/app/tx/detail/AMMDelete.cpp +++ b/src/xrpld/app/tx/detail/AMMDelete.cpp @@ -72,8 +72,8 @@ AMMDelete::doApply() // as we go on processing transactions. Sandbox sb(&ctx_.view()); - auto const ter = - deleteAMMAccount(sb, ctx_.tx[sfAsset], ctx_.tx[sfAsset2], j_); + auto const ter = deleteAMMAccount( + sb, ctx_.tx[sfAsset].get(), ctx_.tx[sfAsset2].get(), j_); if (ter == tesSUCCESS || ter == tecINCOMPLETE) sb.apply(ctx_.rawView()); diff --git a/src/xrpld/app/tx/detail/AMMDeposit.cpp b/src/xrpld/app/tx/detail/AMMDeposit.cpp index 9766a9ad2fe..675f560098c 100644 --- a/src/xrpld/app/tx/detail/AMMDeposit.cpp +++ b/src/xrpld/app/tx/detail/AMMDeposit.cpp @@ -100,8 +100,8 @@ AMMDeposit::preflight(PreflightContext const& ctx) return temMALFORMED; } - auto const asset = ctx.tx[sfAsset]; - auto const asset2 = ctx.tx[sfAsset2]; + auto const asset = ctx.tx[sfAsset].get(); + auto const asset2 = ctx.tx[sfAsset2].get(); if (auto const res = invalidAMMAssetPair(asset, asset2)) { JLOG(ctx.j.debug()) << "AMM Deposit: invalid asset pair."; @@ -268,10 +268,10 @@ AMMDeposit::preclaim(PreclaimContext const& ctx) return tesSUCCESS; }; - if (auto const ter = checkAsset(ctx.tx[sfAsset])) + if (auto const ter = checkAsset(ctx.tx[sfAsset].get())) return ter; - if (auto const ter = checkAsset(ctx.tx[sfAsset2])) + if (auto const ter = checkAsset(ctx.tx[sfAsset2].get())) return ter; } diff --git a/src/xrpld/app/tx/detail/AMMVote.cpp b/src/xrpld/app/tx/detail/AMMVote.cpp index 7e1dc4861d4..1b8b91e518a 100644 --- a/src/xrpld/app/tx/detail/AMMVote.cpp +++ b/src/xrpld/app/tx/detail/AMMVote.cpp @@ -38,7 +38,8 @@ AMMVote::preflight(PreflightContext const& ctx) if (auto const ret = preflight1(ctx); !isTesSuccess(ret)) return ret; - if (auto const res = invalidAMMAssetPair(ctx.tx[sfAsset], ctx.tx[sfAsset2])) + if (auto const res = invalidAMMAssetPair( + ctx.tx[sfAsset].get(), ctx.tx[sfAsset2].get())) { JLOG(ctx.j.debug()) << "AMM Vote: invalid asset pair."; return res; diff --git a/src/xrpld/app/tx/detail/AMMWithdraw.cpp b/src/xrpld/app/tx/detail/AMMWithdraw.cpp index eec9f096bfa..23e8529cfc9 100644 --- a/src/xrpld/app/tx/detail/AMMWithdraw.cpp +++ b/src/xrpld/app/tx/detail/AMMWithdraw.cpp @@ -100,8 +100,8 @@ AMMWithdraw::preflight(PreflightContext const& ctx) return temMALFORMED; } - auto const asset = ctx.tx[sfAsset]; - auto const asset2 = ctx.tx[sfAsset2]; + auto const asset = ctx.tx[sfAsset].get(); + auto const asset2 = ctx.tx[sfAsset2].get(); if (auto const res = invalidAMMAssetPair(asset, asset2)) { JLOG(ctx.j.debug()) << "AMM Withdraw: Invalid asset pair."; @@ -418,7 +418,12 @@ AMMWithdraw::applyGuts(Sandbox& sb) return {result, false}; auto const res = deleteAMMAccountIfEmpty( - sb, ammSle, newLPTokenBalance, ctx_.tx[sfAsset], ctx_.tx[sfAsset2], j_); + sb, + ammSle, + newLPTokenBalance, + ctx_.tx[sfAsset].get(), + ctx_.tx[sfAsset2].get(), + j_); // LCOV_EXCL_START if (!res.second) return {res.first, false}; diff --git a/src/xrpld/rpc/handlers/AMMInfo.cpp b/src/xrpld/rpc/handlers/AMMInfo.cpp index ba02b6869b0..1990cdafd3e 100644 --- a/src/xrpld/rpc/handlers/AMMInfo.cpp +++ b/src/xrpld/rpc/handlers/AMMInfo.cpp @@ -163,8 +163,8 @@ doAMMInfo(RPC::JsonContext& context) return Unexpected(rpcACT_NOT_FOUND); if (!issue1 && !issue2) { - issue1 = (*amm)[sfAsset]; - issue2 = (*amm)[sfAsset2]; + issue1 = (*amm)[sfAsset].get(); + issue2 = (*amm)[sfAsset2].get(); } return ValuesFromContextParams{ From bcbfb049922a5d8eb4b06f99c87a3172e4cdf9d6 Mon Sep 17 00:00:00 2001 From: Mayukha Vadari Date: Mon, 16 Dec 2024 15:00:14 -0800 Subject: [PATCH 3/5] fix: allow overlapping types in `Expected` (#5218) For example, Expected, will now build even though there is animplicit conversion from unsigned int to Json::Value. --- include/xrpl/basics/Expected.h | 6 ++++-- src/test/basics/Expected_test.cpp | 23 +++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/include/xrpl/basics/Expected.h b/include/xrpl/basics/Expected.h index 10f188af11c..ced41b13caa 100644 --- a/include/xrpl/basics/Expected.h +++ b/include/xrpl/basics/Expected.h @@ -137,13 +137,15 @@ class [[nodiscard]] Expected public: template requires std::convertible_to - constexpr Expected(U&& r) : Base(T(std::forward(r))) + constexpr Expected(U&& r) + : Base(boost::outcome_v2::in_place_type_t{}, std::forward(r)) { } template requires std::convertible_to && (!std::is_reference_v) - constexpr Expected(Unexpected e) : Base(E(std::move(e.value()))) + constexpr Expected(Unexpected e) + : Base(boost::outcome_v2::in_place_type_t{}, std::move(e.value())) { } diff --git a/src/test/basics/Expected_test.cpp b/src/test/basics/Expected_test.cpp index d60809aee1f..2f8b92eb916 100644 --- a/src/test/basics/Expected_test.cpp +++ b/src/test/basics/Expected_test.cpp @@ -84,6 +84,29 @@ struct Expected_test : beast::unit_test::suite } BEAST_EXPECT(throwOccurred); } + // Test non-error overlapping type construction. + { + auto expected = []() -> Expected { + return 1; + }(); + BEAST_EXPECT(expected); + BEAST_EXPECT(expected.has_value()); + BEAST_EXPECT(expected.value() == 1); + BEAST_EXPECT(*expected == 1); + + bool throwOccurred = false; + try + { + // There's no error, so should throw. + [[maybe_unused]] std::uint16_t const t = expected.error(); + } + catch (std::runtime_error const& e) + { + BEAST_EXPECT(e.what() == std::string("bad expected access")); + throwOccurred = true; + } + BEAST_EXPECT(throwOccurred); + } // Test error construction from rvalue. { auto const expected = []() -> Expected { From 7506852a997d478ba5dc30b011f1dc27e3180ed0 Mon Sep 17 00:00:00 2001 From: Michael Legleux Date: Mon, 16 Dec 2024 15:01:45 -0800 Subject: [PATCH 4/5] fix: Add header for set_difference (#5197) Fix `error C2039: 'set_difference': is not a member of 'std'` --- src/test/csf/Tx.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/test/csf/Tx.h b/src/test/csf/Tx.h index b21481dcbf9..f87f382167d 100644 --- a/src/test/csf/Tx.h +++ b/src/test/csf/Tx.h @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include From 49e0d54c76be6323f7932386973e38b490e18eda Mon Sep 17 00:00:00 2001 From: Ed Hennis Date: Mon, 16 Dec 2024 18:14:02 -0500 Subject: [PATCH 5/5] Set version to 2.4.0-b1 --- src/libxrpl/protocol/BuildInfo.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libxrpl/protocol/BuildInfo.cpp b/src/libxrpl/protocol/BuildInfo.cpp index 995df262885..9b9d56fa663 100644 --- a/src/libxrpl/protocol/BuildInfo.cpp +++ b/src/libxrpl/protocol/BuildInfo.cpp @@ -33,7 +33,7 @@ namespace BuildInfo { // and follow the format described at http://semver.org/ //------------------------------------------------------------------------------ // clang-format off -char const* const versionString = "2.3.0" +char const* const versionString = "2.4.0-b1" // clang-format on #if defined(DEBUG) || defined(SANITIZER)