From 577d7457f1e8e9389eb24d49e34ed7cb3b00d28f Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Mon, 8 Jun 2026 18:10:05 +0100 Subject: [PATCH 1/9] ci: Use XRPLF/actions build-multiarch-image workflow (#7428) --- .github/workflows/build-nix-images.yml | 7 +- .github/workflows/build-packaging-images.yml | 7 +- .../workflows/reusable-build-docker-image.yml | 89 ------------------- .../reusable-build-merge-docker-images.yml | 89 ------------------- nix/docker/check-tools.sh | 1 + nix/packages.nix | 1 + 6 files changed, 6 insertions(+), 188 deletions(-) delete mode 100644 .github/workflows/reusable-build-docker-image.yml delete mode 100644 .github/workflows/reusable-build-merge-docker-images.yml diff --git a/.github/workflows/build-nix-images.yml b/.github/workflows/build-nix-images.yml index 4e38ca7c57..24f069902d 100644 --- a/.github/workflows/build-nix-images.yml +++ b/.github/workflows/build-nix-images.yml @@ -6,16 +6,12 @@ on: - develop paths: - ".github/workflows/build-nix-images.yml" - - ".github/workflows/reusable-build-docker-image.yml" - - ".github/workflows/reusable-build-merge-docker-images.yml" - "flake.nix" - "flake.lock" - "nix/**" pull_request: paths: - ".github/workflows/build-nix-images.yml" - - ".github/workflows/reusable-build-docker-image.yml" - - ".github/workflows/reusable-build-merge-docker-images.yml" - "flake.nix" - "flake.lock" - "nix/**" @@ -50,8 +46,9 @@ jobs: base_image: debian:bookworm - name: rhel base_image: registry.access.redhat.com/ubi9/ubi:latest - uses: ./.github/workflows/reusable-build-merge-docker-images.yml + uses: XRPLF/actions/.github/workflows/build-multiarch-image.yml@c1b480188519e0cad040e6aa70db1cbc5a797e07 with: image_name: ghcr.io/xrplf/xrpld/nix-${{ matrix.distro.name }} dockerfile: nix/docker/Dockerfile base_image: ${{ matrix.distro.base_image }} + push: ${{ github.repository == 'XRPLF/rippled' && github.event_name == 'push' }} diff --git a/.github/workflows/build-packaging-images.yml b/.github/workflows/build-packaging-images.yml index c445dbf726..d6dabb0f95 100644 --- a/.github/workflows/build-packaging-images.yml +++ b/.github/workflows/build-packaging-images.yml @@ -6,15 +6,11 @@ on: - develop paths: - ".github/workflows/build-packaging-images.yml" - - ".github/workflows/reusable-build-docker-image.yml" - - ".github/workflows/reusable-build-merge-docker-images.yml" - "package/Dockerfile" - "package/install-packaging-tools.sh" pull_request: paths: - ".github/workflows/build-packaging-images.yml" - - ".github/workflows/reusable-build-docker-image.yml" - - ".github/workflows/reusable-build-merge-docker-images.yml" - "package/Dockerfile" - "package/install-packaging-tools.sh" workflow_dispatch: @@ -42,8 +38,9 @@ jobs: base_image: debian:bookworm - name: rhel base_image: registry.access.redhat.com/ubi9/ubi:latest - uses: ./.github/workflows/reusable-build-merge-docker-images.yml + uses: XRPLF/actions/.github/workflows/build-multiarch-image.yml@c1b480188519e0cad040e6aa70db1cbc5a797e07 with: image_name: ghcr.io/xrplf/xrpld/packaging-${{ matrix.distro.name }} dockerfile: package/Dockerfile base_image: ${{ matrix.distro.base_image }} + push: ${{ github.repository == 'XRPLF/rippled' && github.event_name == 'push' }} diff --git a/.github/workflows/reusable-build-docker-image.yml b/.github/workflows/reusable-build-docker-image.yml deleted file mode 100644 index 253563c6a5..0000000000 --- a/.github/workflows/reusable-build-docker-image.yml +++ /dev/null @@ -1,89 +0,0 @@ -# Build a single-platform Docker image. On push, the image is pushed to -# GHCR with arch-suffixed tags (e.g. `:latest-amd64`, `:sha-abc-amd64`) -# so the calling workflow can stitch per-arch builds into a multi-arch -# manifest without needing to pass digests around. -name: Reusable build Docker image (single platform) - -on: - workflow_call: - inputs: - image_name: - description: "Full image name without tag (e.g. 'ghcr.io/xrplf/xrpld/nix-ubuntu')" - required: true - type: string - dockerfile: - description: "Path to the Dockerfile, relative to the repository root" - required: true - type: string - base_image: - description: "Value passed to the Dockerfile as the BASE_IMAGE build arg" - required: true - type: string - platform: - description: "Docker platform string, e.g. linux/amd64" - required: true - type: string - runner: - description: "GitHub Actions runner label to build on" - required: true - type: string - push: - description: "Whether to push the image to GHCR" - required: true - type: boolean - -defaults: - run: - shell: bash - -jobs: - build: - name: Build ${{ inputs.platform }} - runs-on: ${{ inputs.runner }} - permissions: - contents: read - packages: write - - steps: - - name: Checkout repository - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - - - name: Determine arch - id: vars - env: - PLATFORM: ${{ inputs.platform }} - run: | - echo "arch=${PLATFORM##*/}" >>$GITHUB_OUTPUT - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0 - - - name: Login to GitHub Container Registry - if: inputs.push - uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0 - with: - registry: ghcr.io - username: ${{ github.repository_owner }} - password: ${{ secrets.GITHUB_TOKEN }} - - - name: Docker metadata - id: meta - uses: docker/metadata-action@80c7e94dd9b9319bd5eb7a0e0fe9291e23a2a2e9 # v6.1.0 - with: - images: ${{ inputs.image_name }} - tags: | - type=sha,prefix=sha-,format=short - type=raw,value=latest - flavor: | - suffix=-${{ steps.vars.outputs.arch }},onlatest=true - - - name: Build and push - uses: docker/build-push-action@f9f3042f7e2789586610d6e8b85c8f03e5195baf # v7.2.0 - with: - context: . - file: ${{ inputs.dockerfile }} - platforms: ${{ inputs.platform }} - push: ${{ inputs.push }} - tags: ${{ steps.meta.outputs.tags }} - labels: ${{ steps.meta.outputs.labels }} - build-args: BASE_IMAGE=${{ inputs.base_image }} diff --git a/.github/workflows/reusable-build-merge-docker-images.yml b/.github/workflows/reusable-build-merge-docker-images.yml deleted file mode 100644 index 98deb6ea3f..0000000000 --- a/.github/workflows/reusable-build-merge-docker-images.yml +++ /dev/null @@ -1,89 +0,0 @@ -name: Reusable build and merge Docker image (multi-arch) - -on: - workflow_call: - inputs: - image_name: - description: "Full image name without tag (e.g. 'ghcr.io/xrplf/xrpld/nix-ubuntu')" - required: true - type: string - dockerfile: - description: "Path to the Dockerfile, relative to the repository root" - required: true - type: string - base_image: - description: "Value passed to the Dockerfile as the BASE_IMAGE build arg" - required: true - type: string - -defaults: - run: - shell: bash - -jobs: - build: - name: Build ${{ inputs.image_name }} - permissions: - contents: read - packages: write - - strategy: - fail-fast: false - matrix: - target: - - platform: linux/amd64 - runner: ubuntu-latest - - platform: linux/arm64 - runner: ubuntu-24.04-arm - - uses: ./.github/workflows/reusable-build-docker-image.yml - with: - image_name: ${{ inputs.image_name }} - dockerfile: ${{ inputs.dockerfile }} - base_image: ${{ inputs.base_image }} - platform: ${{ matrix.target.platform }} - runner: ${{ matrix.target.runner }} - push: ${{ github.repository == 'XRPLF/rippled' && github.event_name == 'push' }} - - merge: - name: Merge ${{ inputs.image_name }} - needs: build - runs-on: ubuntu-latest - permissions: - contents: read - packages: write - - steps: - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0 - - - name: Docker metadata - id: meta - uses: docker/metadata-action@80c7e94dd9b9319bd5eb7a0e0fe9291e23a2a2e9 # v6.1.0 - with: - images: ${{ inputs.image_name }} - tags: | - type=sha,prefix=sha-,format=short - type=raw,value=latest - - - name: Login to GitHub Container Registry - uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0 - with: - registry: ghcr.io - username: ${{ github.repository_owner }} - password: ${{ secrets.GITHUB_TOKEN }} - - - name: Create multi-arch manifests - if: ${{ github.repository == 'XRPLF/rippled' && github.event_name == 'push' }} - run: | - for tag in $(jq -cr '.tags[]' <<<"$DOCKER_METADATA_OUTPUT_JSON"); do - docker buildx imagetools create -t "$tag" "${tag}-amd64" "${tag}-arm64" - done - - - name: Inspect image - if: ${{ github.repository == 'XRPLF/rippled' && github.event_name == 'push' }} - env: - IMAGE_NAME: ${{ inputs.image_name }} - IMAGE_VERSION: ${{ steps.meta.outputs.version }} - run: | - docker buildx imagetools inspect "${IMAGE_NAME}:${IMAGE_VERSION}" diff --git a/nix/docker/check-tools.sh b/nix/docker/check-tools.sh index faa6520678..67bcdff8a9 100755 --- a/nix/docker/check-tools.sh +++ b/nix/docker/check-tools.sh @@ -15,6 +15,7 @@ gcc --version gcov --version gcovr --version git --version +git-cliff --version gpg --version less --version make --version diff --git a/nix/packages.nix b/nix/packages.nix index 6a83446d88..d40472634b 100644 --- a/nix/packages.nix +++ b/nix/packages.nix @@ -15,6 +15,7 @@ in doxygen gcovr git + git-cliff gnumake gnupg # needed for signing commits & codecov/codecov-action llvmPackages_22.clang-tools From ee9fbc4e08cd52afed4bf3abd3e2c46169331896 Mon Sep 17 00:00:00 2001 From: Bart Date: Tue, 9 Jun 2026 06:04:09 -0400 Subject: [PATCH 2/9] refactor: Use const function arguments where possible (#7423) Co-authored-by: Bart <11445373+bthomee@users.noreply.github.com> --- include/xrpl/net/HTTPClient.h | 6 ++--- include/xrpl/shamap/SHAMap.h | 24 +++++++++++-------- src/libxrpl/net/HTTPClient.cpp | 8 +++---- src/libxrpl/shamap/SHAMap.cpp | 10 ++++---- src/libxrpl/shamap/SHAMapSync.cpp | 6 ++--- src/xrpld/app/ledger/InboundLedger.h | 8 +++---- src/xrpld/app/ledger/detail/InboundLedger.cpp | 10 ++++---- src/xrpld/app/main/Application.cpp | 4 ++-- src/xrpld/app/main/Application.h | 2 +- src/xrpld/consensus/Validations.h | 2 +- src/xrpld/overlay/Overlay.h | 8 +++---- src/xrpld/overlay/detail/OverlayImpl.cpp | 10 ++++---- src/xrpld/overlay/detail/OverlayImpl.h | 10 ++++---- 13 files changed, 56 insertions(+), 52 deletions(-) diff --git a/include/xrpl/net/HTTPClient.h b/include/xrpl/net/HTTPClient.h index f059b19047..456f769922 100644 --- a/include/xrpl/net/HTTPClient.h +++ b/include/xrpl/net/HTTPClient.h @@ -53,7 +53,7 @@ public: boost::system::error_code const& ecResult, int iStatus, std::string const& strData)> complete, - beast::Journal& j); + beast::Journal const& j); static void get(bool bSSL, @@ -67,7 +67,7 @@ public: boost::system::error_code const& ecResult, int iStatus, std::string const& strData)> complete, - beast::Journal& j); + beast::Journal const& j); static void request( @@ -82,7 +82,7 @@ public: boost::system::error_code const& ecResult, int iStatus, std::string const& strData)> complete, - beast::Journal& j); + beast::Journal const& j); }; } // namespace xrpl diff --git a/include/xrpl/shamap/SHAMap.h b/include/xrpl/shamap/SHAMap.h index 32e87b64c6..3d08318cf6 100644 --- a/include/xrpl/shamap/SHAMap.h +++ b/include/xrpl/shamap/SHAMap.h @@ -161,7 +161,7 @@ public: setLedgerSeq(std::uint32_t lseq); bool - fetchRoot(SHAMapHash const& hash, SHAMapSyncFilter* filter); + fetchRoot(SHAMapHash const& hash, SHAMapSyncFilter const* filter); // normal hash access functions @@ -248,7 +248,7 @@ public: @param return The nodes known to be missing */ std::vector> - getMissingNodes(int maxNodes, SHAMapSyncFilter* filter); + getMissingNodes(int maxNodes, SHAMapSyncFilter const* filter); bool getNodeFat( @@ -281,9 +281,9 @@ public: serializeRoot(Serializer& s) const; SHAMapAddNode - addRootNode(SHAMapHash const& hash, Slice const& rootNode, SHAMapSyncFilter* filter); + addRootNode(SHAMapHash const& hash, Slice const& rootNode, SHAMapSyncFilter const* filter); SHAMapAddNode - addKnownNode(SHAMapNodeID const& nodeID, Slice const& rawNode, SHAMapSyncFilter* filter); + addKnownNode(SHAMapNodeID const& nodeID, Slice const& rawNode, SHAMapSyncFilter const* filter); // status functions void @@ -343,11 +343,11 @@ private: SHAMapTreeNodePtr fetchNodeNT(SHAMapHash const& hash) const; SHAMapTreeNodePtr - fetchNodeNT(SHAMapHash const& hash, SHAMapSyncFilter* filter) const; + fetchNodeNT(SHAMapHash const& hash, SHAMapSyncFilter const* filter) const; SHAMapTreeNodePtr fetchNode(SHAMapHash const& hash) const; SHAMapTreeNodePtr - checkFilter(SHAMapHash const& hash, SHAMapSyncFilter* filter) const; + checkFilter(SHAMapHash const& hash, SHAMapSyncFilter const* filter) const; /** Update hashes up to the root */ void @@ -411,7 +411,7 @@ private: descendAsync( SHAMapInnerNode* parent, int branch, - SHAMapSyncFilter* filter, + SHAMapSyncFilter const* filter, bool& pending, descendCallback&&) const; @@ -420,7 +420,7 @@ private: SHAMapInnerNode* parent, SHAMapNodeID const& parentID, int branch, - SHAMapSyncFilter* filter) const; + SHAMapSyncFilter const* filter) const; // Non-storing // Does not hook the returned node to its parent @@ -461,7 +461,7 @@ private: // basic parameters int max; - SHAMapSyncFilter* filter; + SHAMapSyncFilter const* filter; int const maxDefer; std::uint32_t generation; @@ -500,7 +500,11 @@ private: // reads std::map resumes; - MissingNodes(int max, SHAMapSyncFilter* filter, int maxDefer, std::uint32_t generation) + MissingNodes( + int max, + SHAMapSyncFilter const* filter, + int maxDefer, + std::uint32_t generation) : max(max), filter(filter), maxDefer(maxDefer), generation(generation), deferred(0) { missingNodes.reserve(max); diff --git a/src/libxrpl/net/HTTPClient.cpp b/src/libxrpl/net/HTTPClient.cpp index 78ee5eb577..4b9cc9d6e6 100644 --- a/src/libxrpl/net/HTTPClient.cpp +++ b/src/libxrpl/net/HTTPClient.cpp @@ -64,7 +64,7 @@ public: boost::asio::io_context& ioContext, unsigned short const port, std::size_t maxResponseSize, - beast::Journal& j) + beast::Journal const& j) : socket_( ioContext, gHttpClientSslContext->context()) // NOLINT(bugprone-unchecked-optional-access) @@ -552,7 +552,7 @@ HTTPClient::get( std::function< bool(boost::system::error_code const& ecResult, int iStatus, std::string const& strData)> complete, - beast::Journal& j) + beast::Journal const& j) { auto client = std::make_shared(ioContext, port, responseMax, j); client->get(bSSL, deqSites, strPath, timeout, complete); @@ -570,7 +570,7 @@ HTTPClient::get( std::function< bool(boost::system::error_code const& ecResult, int iStatus, std::string const& strData)> complete, - beast::Journal& j) + beast::Journal const& j) { std::deque const deqSites(1, strSite); @@ -590,7 +590,7 @@ HTTPClient::request( std::function< bool(boost::system::error_code const& ecResult, int iStatus, std::string const& strData)> complete, - beast::Journal& j) + beast::Journal const& j) { std::deque const deqSites(1, strSite); diff --git a/src/libxrpl/shamap/SHAMap.cpp b/src/libxrpl/shamap/SHAMap.cpp index 4aad255d81..8a521f6a47 100644 --- a/src/libxrpl/shamap/SHAMap.cpp +++ b/src/libxrpl/shamap/SHAMap.cpp @@ -206,7 +206,7 @@ SHAMap::finishFetch(SHAMapHash const& hash, std::shared_ptr const& o // See if a sync filter has a node SHAMapTreeNodePtr -SHAMap::checkFilter(SHAMapHash const& hash, SHAMapSyncFilter* filter) const +SHAMap::checkFilter(SHAMapHash const& hash, SHAMapSyncFilter const* filter) const { if (auto nodeData = filter->getNode(hash)) { @@ -232,7 +232,7 @@ SHAMap::checkFilter(SHAMapHash const& hash, SHAMapSyncFilter* filter) const // Get a node without throwing // Used on maps where missing nodes are expected SHAMapTreeNodePtr -SHAMap::fetchNodeNT(SHAMapHash const& hash, SHAMapSyncFilter* filter) const +SHAMap::fetchNodeNT(SHAMapHash const& hash, SHAMapSyncFilter const* filter) const { auto node = cacheLookup(hash); if (node) @@ -345,7 +345,7 @@ SHAMap::descend( SHAMapInnerNode* parent, SHAMapNodeID const& parentID, int branch, - SHAMapSyncFilter* filter) const + SHAMapSyncFilter const* filter) const { XRPL_ASSERT(parent->isInner(), "xrpl::SHAMap::descend : valid parent input"); XRPL_ASSERT( @@ -374,7 +374,7 @@ SHAMapTreeNode* SHAMap::descendAsync( SHAMapInnerNode* parent, int branch, - SHAMapSyncFilter* filter, + SHAMapSyncFilter const* filter, bool& pending, descendCallback&& callback) const { @@ -885,7 +885,7 @@ SHAMap::updateGiveItem(SHAMapNodeType type, boost::intrusive_ptrgetHash()) return true; diff --git a/src/libxrpl/shamap/SHAMapSync.cpp b/src/libxrpl/shamap/SHAMapSync.cpp index 0601bfefda..1f38049abe 100644 --- a/src/libxrpl/shamap/SHAMapSync.cpp +++ b/src/libxrpl/shamap/SHAMapSync.cpp @@ -305,7 +305,7 @@ SHAMap::gmnProcessDeferredReads(MissingNodes& mn) nodes that are not permanently stored locally */ std::vector> -SHAMap::getMissingNodes(int max, SHAMapSyncFilter* filter) +SHAMap::getMissingNodes(int max, SHAMapSyncFilter const* filter) { XRPL_ASSERT(root_->getHash().isNonZero(), "xrpl::SHAMap::getMissingNodes : nonzero root hash"); XRPL_ASSERT(max > 0, "xrpl::SHAMap::getMissingNodes : valid max input"); @@ -507,7 +507,7 @@ SHAMap::serializeRoot(Serializer& s) const } SHAMapAddNode -SHAMap::addRootNode(SHAMapHash const& hash, Slice const& rootNode, SHAMapSyncFilter* filter) +SHAMap::addRootNode(SHAMapHash const& hash, Slice const& rootNode, SHAMapSyncFilter const* filter) { // we already have a root_ node if (root_->getHash().isNonZero()) @@ -542,7 +542,7 @@ SHAMap::addRootNode(SHAMapHash const& hash, Slice const& rootNode, SHAMapSyncFil } SHAMapAddNode -SHAMap::addKnownNode(SHAMapNodeID const& node, Slice const& rawNode, SHAMapSyncFilter* filter) +SHAMap::addKnownNode(SHAMapNodeID const& node, Slice const& rawNode, SHAMapSyncFilter const* filter) { XRPL_ASSERT(!node.isRoot(), "xrpl::SHAMap::addKnownNode : valid node input"); diff --git a/src/xrpld/app/ledger/InboundLedger.h b/src/xrpld/app/ledger/InboundLedger.h index d155c5902c..b82e2f69cd 100644 --- a/src/xrpld/app/ledger/InboundLedger.h +++ b/src/xrpld/app/ledger/InboundLedger.h @@ -128,13 +128,13 @@ private: pmDowncast() override; int - processData(std::shared_ptr peer, protocol::TMLedgerData& data); + processData(std::shared_ptr peer, protocol::TMLedgerData const& data); bool takeHeader(std::string const& data); void - receiveNode(protocol::TMLedgerData& packet, SHAMapAddNode&); + receiveNode(protocol::TMLedgerData const& packet, SHAMapAddNode&); bool takeTxRootNode(Slice const& data, SHAMapAddNode&); @@ -143,10 +143,10 @@ private: takeAsRootNode(Slice const& data, SHAMapAddNode&); std::vector - neededTxHashes(int max, SHAMapSyncFilter* filter) const; + neededTxHashes(int max, SHAMapSyncFilter const* filter) const; std::vector - neededStateHashes(int max, SHAMapSyncFilter* filter) const; + neededStateHashes(int max, SHAMapSyncFilter const* filter) const; clock_type& clock_; clock_type::time_point lastAction_; diff --git a/src/xrpld/app/ledger/detail/InboundLedger.cpp b/src/xrpld/app/ledger/detail/InboundLedger.cpp index 9ba7bdf22e..5a9f24cc2e 100644 --- a/src/xrpld/app/ledger/detail/InboundLedger.cpp +++ b/src/xrpld/app/ledger/detail/InboundLedger.cpp @@ -188,7 +188,7 @@ InboundLedger::~InboundLedger() } static std::vector -neededHashes(uint256 const& root, SHAMap& map, int max, SHAMapSyncFilter* filter) +neededHashes(uint256 const& root, SHAMap& map, int max, SHAMapSyncFilter const* filter) { std::vector ret; @@ -211,13 +211,13 @@ neededHashes(uint256 const& root, SHAMap& map, int max, SHAMapSyncFilter* filter } std::vector -InboundLedger::neededTxHashes(int max, SHAMapSyncFilter* filter) const +InboundLedger::neededTxHashes(int max, SHAMapSyncFilter const* filter) const { return neededHashes(ledger_->header().txHash, ledger_->txMap(), max, filter); } std::vector -InboundLedger::neededStateHashes(int max, SHAMapSyncFilter* filter) const +InboundLedger::neededStateHashes(int max, SHAMapSyncFilter const* filter) const { return neededHashes(ledger_->header().accountHash, ledger_->stateMap(), max, filter); } @@ -820,7 +820,7 @@ InboundLedger::takeHeader(std::string const& data) Call with a lock */ void -InboundLedger::receiveNode(protocol::TMLedgerData& packet, SHAMapAddNode& san) +InboundLedger::receiveNode(protocol::TMLedgerData const& packet, SHAMapAddNode& san) { if (!haveHeader_) { @@ -1026,7 +1026,7 @@ InboundLedger::gotData( // TODO Change peer to Consumer // int -InboundLedger::processData(std::shared_ptr peer, protocol::TMLedgerData& packet) +InboundLedger::processData(std::shared_ptr peer, protocol::TMLedgerData const& packet) { if (packet.type() == protocol::liBASE) { diff --git a/src/xrpld/app/main/Application.cpp b/src/xrpld/app/main/Application.cpp index 508dfc8590..af5d51289d 100644 --- a/src/xrpld/app/main/Application.cpp +++ b/src/xrpld/app/main/Application.cpp @@ -492,7 +492,7 @@ public: void run() override; void - signalStop(std::string msg) override; + signalStop(std::string const& msg) override; bool checkSigs() const override; void @@ -1602,7 +1602,7 @@ ApplicationImp::run() } void -ApplicationImp::signalStop(std::string msg) +ApplicationImp::signalStop(std::string const& msg) { if (!isTimeToStop.test_and_set(std::memory_order_acquire)) { diff --git a/src/xrpld/app/main/Application.h b/src/xrpld/app/main/Application.h index 200fed7cf9..08e41e2c4c 100644 --- a/src/xrpld/app/main/Application.h +++ b/src/xrpld/app/main/Application.h @@ -111,7 +111,7 @@ public: virtual void run() = 0; virtual void - signalStop(std::string msg) = 0; + signalStop(std::string const& msg) = 0; [[nodiscard]] virtual bool checkSigs() const = 0; virtual void diff --git a/src/xrpld/consensus/Validations.h b/src/xrpld/consensus/Validations.h index 7be578060e..2f5762ce83 100644 --- a/src/xrpld/consensus/Validations.h +++ b/src/xrpld/consensus/Validations.h @@ -693,7 +693,7 @@ public: validationSET_EXPIRES ago and were not asked to keep. */ void - expire(beast::Journal& j) + expire(beast::Journal const& j) { auto const start = std::chrono::steady_clock::now(); { diff --git a/src/xrpld/overlay/Overlay.h b/src/xrpld/overlay/Overlay.h index ef97ea7f24..87c6ff132a 100644 --- a/src/xrpld/overlay/Overlay.h +++ b/src/xrpld/overlay/Overlay.h @@ -117,11 +117,11 @@ public: /** Broadcast a proposal. */ virtual void - broadcast(protocol::TMProposeSet& m) = 0; + broadcast(protocol::TMProposeSet const& m) = 0; /** Broadcast a validation. */ virtual void - broadcast(protocol::TMValidation& m) = 0; + broadcast(protocol::TMValidation const& m) = 0; /** Relay a proposal. * @param m the serialized proposal @@ -130,7 +130,7 @@ public: * @return the set of peers which have already sent us this proposal */ virtual std::set - relay(protocol::TMProposeSet& m, uint256 const& uid, PublicKey const& validator) = 0; + relay(protocol::TMProposeSet const& m, uint256 const& uid, PublicKey const& validator) = 0; /** Relay a validation. * @param m the serialized validation @@ -139,7 +139,7 @@ public: * @return the set of peers which have already sent us this validation */ virtual std::set - relay(protocol::TMValidation& m, uint256 const& uid, PublicKey const& validator) = 0; + relay(protocol::TMValidation const& m, uint256 const& uid, PublicKey const& validator) = 0; /** Relay a transaction. If the tx reduce-relay feature is enabled then * randomly select peers to relay to and queue transaction's hash diff --git a/src/xrpld/overlay/detail/OverlayImpl.cpp b/src/xrpld/overlay/detail/OverlayImpl.cpp index b31f54058a..b71cef6719 100644 --- a/src/xrpld/overlay/detail/OverlayImpl.cpp +++ b/src/xrpld/overlay/detail/OverlayImpl.cpp @@ -407,7 +407,7 @@ OverlayImpl::makeErrorResponse( std::shared_ptr const& slot, http_request_type const& request, address_type remoteAddress, - std::string text) + std::string const& text) { boost::beast::http::response msg; msg.version(request.version()); @@ -1157,14 +1157,14 @@ OverlayImpl::findPeerByPublicKey(PublicKey const& pubKey) } void -OverlayImpl::broadcast(protocol::TMProposeSet& m) +OverlayImpl::broadcast(protocol::TMProposeSet const& m) { auto const sm = std::make_shared(m, protocol::mtPROPOSE_LEDGER); forEach([&](std::shared_ptr const& p) { p->send(sm); }); } std::set -OverlayImpl::relay(protocol::TMProposeSet& m, uint256 const& uid, PublicKey const& validator) +OverlayImpl::relay(protocol::TMProposeSet const& m, uint256 const& uid, PublicKey const& validator) { if (auto const toSkip = app_.getHashRouter().shouldRelay(uid)) { @@ -1179,14 +1179,14 @@ OverlayImpl::relay(protocol::TMProposeSet& m, uint256 const& uid, PublicKey cons } void -OverlayImpl::broadcast(protocol::TMValidation& m) +OverlayImpl::broadcast(protocol::TMValidation const& m) { auto const sm = std::make_shared(m, protocol::mtVALIDATION); forEach([sm](std::shared_ptr const& p) { p->send(sm); }); } std::set -OverlayImpl::relay(protocol::TMValidation& m, uint256 const& uid, PublicKey const& validator) +OverlayImpl::relay(protocol::TMValidation const& m, uint256 const& uid, PublicKey const& validator) { if (auto const toSkip = app_.getHashRouter().shouldRelay(uid)) { diff --git a/src/xrpld/overlay/detail/OverlayImpl.h b/src/xrpld/overlay/detail/OverlayImpl.h index 6fcc2df854..545d9eb75c 100644 --- a/src/xrpld/overlay/detail/OverlayImpl.h +++ b/src/xrpld/overlay/detail/OverlayImpl.h @@ -202,16 +202,16 @@ public: findPeerByPublicKey(PublicKey const& pubKey) override; void - broadcast(protocol::TMProposeSet& m) override; + broadcast(protocol::TMProposeSet const& m) override; void - broadcast(protocol::TMValidation& m) override; + broadcast(protocol::TMValidation const& m) override; std::set - relay(protocol::TMProposeSet& m, uint256 const& uid, PublicKey const& validator) override; + relay(protocol::TMProposeSet const& m, uint256 const& uid, PublicKey const& validator) override; std::set - relay(protocol::TMValidation& m, uint256 const& uid, PublicKey const& validator) override; + relay(protocol::TMValidation const& m, uint256 const& uid, PublicKey const& validator) override; void relay( @@ -433,7 +433,7 @@ private: std::shared_ptr const& slot, http_request_type const& request, address_type remoteAddress, - std::string msg); + std::string const& msg); /** Handles crawl requests. Crawl returns information about the node and its peers so crawlers can map the network. From c9769d1add290e4fb53add23d1e9859237134b73 Mon Sep 17 00:00:00 2001 From: Bart Date: Tue, 9 Jun 2026 09:56:32 -0400 Subject: [PATCH 3/9] refactor: Use `std::move` and `std::string_view` where possible (#7424) Co-authored-by: Bart <11445373+bthomee@users.noreply.github.com> --- include/xrpl/basics/StringUtilities.h | 9 ++---- include/xrpl/basics/base64.h | 3 +- include/xrpl/basics/join.h | 3 +- include/xrpl/beast/insight/Counter.h | 3 +- include/xrpl/beast/insight/Event.h | 3 +- include/xrpl/beast/insight/Gauge.h | 3 +- include/xrpl/beast/insight/Hook.h | 3 +- include/xrpl/beast/insight/Meter.h | 3 +- include/xrpl/beast/unit_test/match.h | 6 ++-- include/xrpl/crypto/RFC1751.h | 3 +- include/xrpl/ledger/CanonicalTXSet.h | 2 +- include/xrpl/protocol/STVector256.h | 10 +++--- include/xrpl/server/Session.h | 5 +-- include/xrpl/shamap/SHAMapNodeID.h | 3 +- src/libxrpl/beast/insight/StatsDCollector.cpp | 32 +++++++++---------- src/libxrpl/crypto/RFC1751.cpp | 3 +- src/libxrpl/ledger/CanonicalTXSet.cpp | 10 ++---- src/test/jtx/credentials.h | 2 +- src/test/server/Server_test.cpp | 4 ++- src/xrpld/app/consensus/RCLCxLedger.h | 2 +- src/xrpld/app/consensus/RCLValidations.h | 2 +- src/xrpld/app/ledger/AcceptedLedger.cpp | 19 ++++------- src/xrpld/app/ledger/AcceptedLedger.h | 2 +- src/xrpld/app/ledger/OpenLedger.h | 3 +- src/xrpld/app/ledger/detail/OpenLedger.cpp | 3 +- src/xrpld/app/ledger/detail/SkipListAcquire.h | 4 +-- src/xrpld/app/misc/detail/ValidatorList.cpp | 2 +- src/xrpld/overlay/detail/Cluster.cpp | 3 +- src/xrpld/peerfinder/PeerfinderManager.h | 2 +- src/xrpld/peerfinder/detail/Logic.h | 4 +-- .../peerfinder/detail/PeerfinderManager.cpp | 4 +-- src/xrpld/rpc/detail/AssetCache.cpp | 4 +-- src/xrpld/rpc/detail/AssetCache.h | 2 +- src/xrpld/rpc/detail/PathRequest.cpp | 4 +-- src/xrpld/rpc/detail/PathRequest.h | 2 +- 35 files changed, 86 insertions(+), 86 deletions(-) diff --git a/include/xrpl/basics/StringUtilities.h b/include/xrpl/basics/StringUtilities.h index 28421626aa..1d3434b7ed 100644 --- a/include/xrpl/basics/StringUtilities.h +++ b/include/xrpl/basics/StringUtilities.h @@ -11,6 +11,7 @@ #include #include #include +#include #include namespace xrpl { @@ -95,13 +96,7 @@ strUnHex(std::size_t strSize, Iterator begin, Iterator end) } inline std::optional -strUnHex(std::string const& strSrc) -{ - return strUnHex(strSrc.size(), strSrc.cbegin(), strSrc.cend()); -} - -inline std::optional -strViewUnHex(std::string_view strSrc) +strUnHex(std::string_view strSrc) { return strUnHex(strSrc.size(), strSrc.cbegin(), strSrc.cend()); } diff --git a/include/xrpl/basics/base64.h b/include/xrpl/basics/base64.h index ed30e40a36..660958ce14 100644 --- a/include/xrpl/basics/base64.h +++ b/include/xrpl/basics/base64.h @@ -36,6 +36,7 @@ #include #include +#include namespace xrpl { @@ -43,7 +44,7 @@ std::string base64Encode(std::uint8_t const* data, std::size_t len); inline std::string -base64Encode(std::string const& s) +base64Encode(std::string_view s) { return base64Encode(reinterpret_cast(s.data()), s.size()); } diff --git a/include/xrpl/basics/join.h b/include/xrpl/basics/join.h index 0fb00aaf82..c214212473 100644 --- a/include/xrpl/basics/join.h +++ b/include/xrpl/basics/join.h @@ -1,12 +1,13 @@ #pragma once #include +#include namespace xrpl { template Stream& -join(Stream& s, Iter iter, Iter end, std::string const& delimiter) +join(Stream& s, Iter iter, Iter end, std::string_view delimiter) { if (iter == end) return s; diff --git a/include/xrpl/beast/insight/Counter.h b/include/xrpl/beast/insight/Counter.h index 71ace4bb4e..482808b2c7 100644 --- a/include/xrpl/beast/insight/Counter.h +++ b/include/xrpl/beast/insight/Counter.h @@ -3,6 +3,7 @@ #include #include +#include namespace beast::insight { @@ -29,7 +30,7 @@ public: factory function in the Collector interface. @see Collector. */ - explicit Counter(std::shared_ptr const& impl) : impl_(impl) + explicit Counter(std::shared_ptr impl) : impl_(std::move(impl)) { } diff --git a/include/xrpl/beast/insight/Event.h b/include/xrpl/beast/insight/Event.h index 5e424a0f9b..afccf9baba 100644 --- a/include/xrpl/beast/insight/Event.h +++ b/include/xrpl/beast/insight/Event.h @@ -4,6 +4,7 @@ #include #include +#include namespace beast::insight { @@ -31,7 +32,7 @@ public: factory function in the Collector interface. @see Collector. */ - explicit Event(std::shared_ptr const& impl) : impl_(impl) + explicit Event(std::shared_ptr impl) : impl_(std::move(impl)) { } diff --git a/include/xrpl/beast/insight/Gauge.h b/include/xrpl/beast/insight/Gauge.h index dd2c4bc6b6..b24c4366c3 100644 --- a/include/xrpl/beast/insight/Gauge.h +++ b/include/xrpl/beast/insight/Gauge.h @@ -3,6 +3,7 @@ #include #include +#include namespace beast::insight { @@ -31,7 +32,7 @@ public: factory function in the Collector interface. @see Collector. */ - explicit Gauge(std::shared_ptr const& impl) : impl_(impl) + explicit Gauge(std::shared_ptr impl) : impl_(std::move(impl)) { } diff --git a/include/xrpl/beast/insight/Hook.h b/include/xrpl/beast/insight/Hook.h index 1cb6cae5d9..8dbe5a4be0 100644 --- a/include/xrpl/beast/insight/Hook.h +++ b/include/xrpl/beast/insight/Hook.h @@ -3,6 +3,7 @@ #include #include +#include namespace beast::insight { @@ -20,7 +21,7 @@ public: factory function in the Collector interface. @see Collector. */ - explicit Hook(std::shared_ptr const& impl) : impl_(impl) + explicit Hook(std::shared_ptr impl) : impl_(std::move(impl)) { } diff --git a/include/xrpl/beast/insight/Meter.h b/include/xrpl/beast/insight/Meter.h index 03aa17c313..25ffabd928 100644 --- a/include/xrpl/beast/insight/Meter.h +++ b/include/xrpl/beast/insight/Meter.h @@ -3,6 +3,7 @@ #include #include +#include namespace beast::insight { @@ -28,7 +29,7 @@ public: factory function in the Collector interface. @see Collector. */ - explicit Meter(std::shared_ptr const& impl) : impl_(impl) + explicit Meter(std::shared_ptr impl) : impl_(std::move(impl)) { } diff --git a/include/xrpl/beast/unit_test/match.h b/include/xrpl/beast/unit_test/match.h index 222c4ea656..da466ab228 100644 --- a/include/xrpl/beast/unit_test/match.h +++ b/include/xrpl/beast/unit_test/match.h @@ -41,7 +41,7 @@ private: public: template - explicit Selector(ModeT mode, std::string const& pattern = ""); + explicit Selector(ModeT mode, std::string pattern = ""); template bool @@ -51,9 +51,9 @@ public: //------------------------------------------------------------------------------ template -Selector::Selector(ModeT mode, std::string const& pattern) : mode_(mode), pat_(pattern) +Selector::Selector(ModeT mode, std::string pattern) : mode_(mode), pat_(std::move(pattern)) { - if (mode_ == ModeT::Automatch && pattern.empty()) + if (mode_ == ModeT::Automatch && pat_.empty()) mode_ = ModeT::All; } diff --git a/include/xrpl/crypto/RFC1751.h b/include/xrpl/crypto/RFC1751.h index c99c691ba0..19b636b9dc 100644 --- a/include/xrpl/crypto/RFC1751.h +++ b/include/xrpl/crypto/RFC1751.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include namespace xrpl { @@ -34,7 +35,7 @@ private: static void standard(std::string& strWord); static int - wsrch(std::string const& strWord, int iMin, int iMax); + wsrch(std::string_view strWord, int iMin, int iMax); static int etob(std::string& strData, std::vector vsHuman); diff --git a/include/xrpl/ledger/CanonicalTXSet.h b/include/xrpl/ledger/CanonicalTXSet.h index 8653816eee..4dffadd52f 100644 --- a/include/xrpl/ledger/CanonicalTXSet.h +++ b/include/xrpl/ledger/CanonicalTXSet.h @@ -93,7 +93,7 @@ public: } void - insert(std::shared_ptr const& txn); + insert(std::shared_ptr txn); // Pops the next transaction on account that follows seqProx in the // sort order. Normally called when a transaction is successfully diff --git a/include/xrpl/protocol/STVector256.h b/include/xrpl/protocol/STVector256.h index ab3a2f99e3..5c454b6be0 100644 --- a/include/xrpl/protocol/STVector256.h +++ b/include/xrpl/protocol/STVector256.h @@ -17,8 +17,8 @@ public: STVector256() = default; explicit STVector256(SField const& n); - explicit STVector256(std::vector const& vector); - STVector256(SField const& n, std::vector const& vector); + explicit STVector256(std::vector vector); + STVector256(SField const& n, std::vector vector); STVector256(SerialIter& sit, SField const& name); [[nodiscard]] SerializedTypeID @@ -103,12 +103,12 @@ inline STVector256::STVector256(SField const& n) : STBase(n) { } -inline STVector256::STVector256(std::vector const& vector) : value_(vector) +inline STVector256::STVector256(std::vector vector) : value_(std::move(vector)) { } -inline STVector256::STVector256(SField const& n, std::vector const& vector) - : STBase(n), value_(vector) +inline STVector256::STVector256(SField const& n, std::vector vector) + : STBase(n), value_(std::move(vector)) { } diff --git a/include/xrpl/server/Session.h b/include/xrpl/server/Session.h index 2cb991e130..151e57e7f2 100644 --- a/include/xrpl/server/Session.h +++ b/include/xrpl/server/Session.h @@ -10,6 +10,7 @@ #include #include #include +#include #include namespace xrpl { @@ -53,10 +54,10 @@ public: /** Send a copy of data asynchronously. */ /** @{ */ void - write(std::string const& s) + write(std::string_view s) { if (!s.empty()) - write(&s[0], std::distance(s.begin(), s.end())); + write(s.data(), s.size()); } template diff --git a/include/xrpl/shamap/SHAMapNodeID.h b/include/xrpl/shamap/SHAMapNodeID.h index dbc087b356..248c9cb80b 100644 --- a/include/xrpl/shamap/SHAMapNodeID.h +++ b/include/xrpl/shamap/SHAMapNodeID.h @@ -5,6 +5,7 @@ #include #include +#include #include namespace xrpl { @@ -127,7 +128,7 @@ operator<<(std::ostream& out, SHAMapNodeID const& node) deserializeSHAMapNodeID(void const* data, std::size_t size); [[nodiscard]] inline std::optional -deserializeSHAMapNodeID(std::string const& s) +deserializeSHAMapNodeID(std::string_view s) { return deserializeSHAMapNodeID(s.data(), s.size()); } diff --git a/src/libxrpl/beast/insight/StatsDCollector.cpp b/src/libxrpl/beast/insight/StatsDCollector.cpp index 88f52c26de..0d0e013274 100644 --- a/src/libxrpl/beast/insight/StatsDCollector.cpp +++ b/src/libxrpl/beast/insight/StatsDCollector.cpp @@ -66,7 +66,7 @@ public: class StatsDHookImpl : public HookImpl, public StatsDMetricBase { public: - StatsDHookImpl(HandlerType handler, std::shared_ptr const& impl); + StatsDHookImpl(HandlerType handler, std::shared_ptr impl); ~StatsDHookImpl() override; @@ -86,7 +86,7 @@ private: class StatsDCounterImpl : public CounterImpl, public StatsDMetricBase { public: - StatsDCounterImpl(std::string name, std::shared_ptr const& impl); + StatsDCounterImpl(std::string name, std::shared_ptr impl); ~StatsDCounterImpl() override; @@ -115,7 +115,7 @@ private: class StatsDEventImpl : public EventImpl { public: - StatsDEventImpl(std::string name, std::shared_ptr const& impl); + StatsDEventImpl(std::string name, std::shared_ptr impl); ~StatsDEventImpl() override = default; @@ -140,7 +140,7 @@ private: class StatsDGaugeImpl : public GaugeImpl, public StatsDMetricBase { public: - StatsDGaugeImpl(std::string name, std::shared_ptr const& impl); + StatsDGaugeImpl(std::string name, std::shared_ptr impl); ~StatsDGaugeImpl() override; @@ -174,7 +174,7 @@ private: class StatsDMeterImpl : public MeterImpl, public StatsDMetricBase { public: - explicit StatsDMeterImpl(std::string name, std::shared_ptr const& impl); + explicit StatsDMeterImpl(std::string name, std::shared_ptr impl); ~StatsDMeterImpl() override; @@ -478,8 +478,8 @@ public: //------------------------------------------------------------------------------ -StatsDHookImpl::StatsDHookImpl(HandlerType handler, std::shared_ptr const& impl) - : impl_(impl), handler_(std::move(handler)) +StatsDHookImpl::StatsDHookImpl(HandlerType handler, std::shared_ptr impl) + : impl_(std::move(impl)), handler_(std::move(handler)) { impl_->add(*this); } @@ -497,10 +497,8 @@ StatsDHookImpl::doProcess() //------------------------------------------------------------------------------ -StatsDCounterImpl::StatsDCounterImpl( - std::string name, - std::shared_ptr const& impl) - : impl_(impl), name_(std::move(name)) +StatsDCounterImpl::StatsDCounterImpl(std::string name, std::shared_ptr impl) + : impl_(std::move(impl)), name_(std::move(name)) { impl_->add(*this); } @@ -550,8 +548,8 @@ StatsDCounterImpl::doProcess() //------------------------------------------------------------------------------ -StatsDEventImpl::StatsDEventImpl(std::string name, std::shared_ptr const& impl) - : impl_(impl), name_(std::move(name)) +StatsDEventImpl::StatsDEventImpl(std::string name, std::shared_ptr impl) + : impl_(std::move(impl)), name_(std::move(name)) { } @@ -577,8 +575,8 @@ StatsDEventImpl::doNotify(EventImpl::value_type const& value) //------------------------------------------------------------------------------ -StatsDGaugeImpl::StatsDGaugeImpl(std::string name, std::shared_ptr const& impl) - : impl_(impl), name_(std::move(name)) +StatsDGaugeImpl::StatsDGaugeImpl(std::string name, std::shared_ptr impl) + : impl_(std::move(impl)), name_(std::move(name)) { impl_->add(*this); } @@ -664,8 +662,8 @@ StatsDGaugeImpl::doProcess() //------------------------------------------------------------------------------ -StatsDMeterImpl::StatsDMeterImpl(std::string name, std::shared_ptr const& impl) - : impl_(impl), name_(std::move(name)) +StatsDMeterImpl::StatsDMeterImpl(std::string name, std::shared_ptr impl) + : impl_(std::move(impl)), name_(std::move(name)) { impl_->add(*this); } diff --git a/src/libxrpl/crypto/RFC1751.cpp b/src/libxrpl/crypto/RFC1751.cpp index 30f2c3a5b8..16482945d2 100644 --- a/src/libxrpl/crypto/RFC1751.cpp +++ b/src/libxrpl/crypto/RFC1751.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include namespace xrpl { @@ -306,7 +307,7 @@ RFC1751::standard(std::string& strWord) // Binary search of dictionary. int -RFC1751::wsrch(std::string const& strWord, int iMin, int iMax) +RFC1751::wsrch(std::string_view strWord, int iMin, int iMax) { int iResult = -1; diff --git a/src/libxrpl/ledger/CanonicalTXSet.cpp b/src/libxrpl/ledger/CanonicalTXSet.cpp index a06576342a..df4e88e346 100644 --- a/src/libxrpl/ledger/CanonicalTXSet.cpp +++ b/src/libxrpl/ledger/CanonicalTXSet.cpp @@ -40,14 +40,10 @@ CanonicalTXSet::accountKey(AccountID const& account) } void -CanonicalTXSet::insert(std::shared_ptr const& txn) +CanonicalTXSet::insert(std::shared_ptr txn) { - map_.insert( - std::make_pair( - Key(accountKey(txn->getAccountID(sfAccount)), - txn->getSeqProxy(), - txn->getTransactionID()), - txn)); + Key key(accountKey(txn->getAccountID(sfAccount)), txn->getSeqProxy(), txn->getTransactionID()); + map_.emplace(key, std::move(txn)); } std::shared_ptr diff --git a/src/test/jtx/credentials.h b/src/test/jtx/credentials.h index c2719bf897..4bdd716918 100644 --- a/src/test/jtx/credentials.h +++ b/src/test/jtx/credentials.h @@ -40,7 +40,7 @@ private: std::vector const credentials_; public: - explicit Ids(std::vector const& creds) : credentials_(creds) + explicit Ids(std::vector creds) : credentials_(std::move(creds)) { } diff --git a/src/test/server/Server_test.cpp b/src/test/server/Server_test.cpp index 263fb9451f..1b0107167c 100644 --- a/src/test/server/Server_test.cpp +++ b/src/test/server/Server_test.cpp @@ -33,6 +33,7 @@ #include #include #include +#include #include #include #include @@ -133,7 +134,8 @@ public: static void onRequest(Session& session) { - session.write(std::string("Hello, world!\n")); + using namespace std::string_view_literals; + session.write("Hello, world!\n"sv); if (beast::rfc2616::isKeepAlive(session.request())) { session.complete(); diff --git a/src/xrpld/app/consensus/RCLCxLedger.h b/src/xrpld/app/consensus/RCLCxLedger.h index 3d6ed4912b..9f7984aaa6 100644 --- a/src/xrpld/app/consensus/RCLCxLedger.h +++ b/src/xrpld/app/consensus/RCLCxLedger.h @@ -32,7 +32,7 @@ public: @param l The ledger to wrap. */ - RCLCxLedger(std::shared_ptr const& l) : ledger{l} + RCLCxLedger(std::shared_ptr l) : ledger{std::move(l)} { } diff --git a/src/xrpld/app/consensus/RCLValidations.h b/src/xrpld/app/consensus/RCLValidations.h index 16f6e15d4d..37a6f6c743 100644 --- a/src/xrpld/app/consensus/RCLValidations.h +++ b/src/xrpld/app/consensus/RCLValidations.h @@ -32,7 +32,7 @@ public: @param v The validation to wrap. */ - RCLValidation(std::shared_ptr const& v) : val_{v} + RCLValidation(std::shared_ptr v) : val_{std::move(v)} { } diff --git a/src/xrpld/app/ledger/AcceptedLedger.cpp b/src/xrpld/app/ledger/AcceptedLedger.cpp index ea594308bd..6da869198b 100644 --- a/src/xrpld/app/ledger/AcceptedLedger.cpp +++ b/src/xrpld/app/ledger/AcceptedLedger.cpp @@ -5,23 +5,18 @@ #include #include +#include namespace xrpl { -AcceptedLedger::AcceptedLedger(std::shared_ptr const& ledger) : ledger_(ledger) +AcceptedLedger::AcceptedLedger(std::shared_ptr ledger) : ledger_(std::move(ledger)) { transactions_.reserve(256); - - auto insertAll = [&](auto const& txns) { - for (auto const& item : txns) - { - transactions_.emplace_back( - std::make_unique(ledger, item.first, item.second)); - } - }; - - transactions_.reserve(256); - insertAll(ledger->txs); + for (auto const& item : ledger_->txs) + { + transactions_.emplace_back( + std::make_unique(ledger_, item.first, item.second)); + } std::ranges::sort(transactions_, [](auto const& a, auto const& b) { return a->getTxnSeq() < b->getTxnSeq(); diff --git a/src/xrpld/app/ledger/AcceptedLedger.h b/src/xrpld/app/ledger/AcceptedLedger.h index 621bea9e0d..b05af1f18a 100644 --- a/src/xrpld/app/ledger/AcceptedLedger.h +++ b/src/xrpld/app/ledger/AcceptedLedger.h @@ -25,7 +25,7 @@ namespace xrpl { class AcceptedLedger : public CountedObject { public: - AcceptedLedger(std::shared_ptr const& ledger); + AcceptedLedger(std::shared_ptr ledger); [[nodiscard]] std::shared_ptr const& getLedger() const diff --git a/src/xrpld/app/ledger/OpenLedger.h b/src/xrpld/app/ledger/OpenLedger.h index 02e073bc9a..554002d6af 100644 --- a/src/xrpld/app/ledger/OpenLedger.h +++ b/src/xrpld/app/ledger/OpenLedger.h @@ -12,6 +12,7 @@ #include #include +#include namespace xrpl { @@ -149,7 +150,7 @@ public: bool retriesFirst, OrderedTxs& retries, ApplyFlags flags, - std::string const& suffix = "", + std::string_view suffix = "", modify_type const& f = {}); private: diff --git a/src/xrpld/app/ledger/detail/OpenLedger.cpp b/src/xrpld/app/ledger/detail/OpenLedger.cpp index 3bee4b9d13..60599c80d3 100644 --- a/src/xrpld/app/ledger/detail/OpenLedger.cpp +++ b/src/xrpld/app/ledger/detail/OpenLedger.cpp @@ -32,6 +32,7 @@ #include #include #include +#include #include #include @@ -82,7 +83,7 @@ OpenLedger::accept( bool retriesFirst, OrderedTxs& retries, ApplyFlags flags, - std::string const& suffix, + std::string_view suffix, modify_type const& f) { JLOG(j_.trace()) << "accept ledger " << ledger->seq() << " " << suffix; diff --git a/src/xrpld/app/ledger/detail/SkipListAcquire.h b/src/xrpld/app/ledger/detail/SkipListAcquire.h index da62578d41..6600b495c9 100644 --- a/src/xrpld/app/ledger/detail/SkipListAcquire.h +++ b/src/xrpld/app/ledger/detail/SkipListAcquire.h @@ -35,8 +35,8 @@ public: std::uint32_t const ledgerSeq; std::vector const skipList; - SkipListData(std::uint32_t const ledgerSeq, std::vector const& skipList) - : ledgerSeq(ledgerSeq), skipList(skipList) + SkipListData(std::uint32_t const ledgerSeq, std::vector skipList) + : ledgerSeq(ledgerSeq), skipList(std::move(skipList)) { } }; diff --git a/src/xrpld/app/misc/detail/ValidatorList.cpp b/src/xrpld/app/misc/detail/ValidatorList.cpp index 0981c32050..a9e7156158 100644 --- a/src/xrpld/app/misc/detail/ValidatorList.cpp +++ b/src/xrpld/app/misc/detail/ValidatorList.cpp @@ -1777,7 +1777,7 @@ ValidatorList::getAvailable( { std::shared_lock const readLock{mutex_}; - auto const keyBlob = strViewUnHex(pubKey); + auto const keyBlob = strUnHex(pubKey); if (!keyBlob || !publicKeyType(makeSlice(*keyBlob))) { diff --git a/src/xrpld/overlay/detail/Cluster.cpp b/src/xrpld/overlay/detail/Cluster.cpp index dcb40a54f5..7855c9647d 100644 --- a/src/xrpld/overlay/detail/Cluster.cpp +++ b/src/xrpld/overlay/detail/Cluster.cpp @@ -19,6 +19,7 @@ #include #include #include +#include namespace xrpl { @@ -67,7 +68,7 @@ Cluster::update( iter = nodes_.erase(iter); } - nodes_.emplace_hint(iter, identity, name, loadFee, reportTime); + nodes_.emplace_hint(iter, identity, std::move(name), loadFee, reportTime); return true; } diff --git a/src/xrpld/peerfinder/PeerfinderManager.h b/src/xrpld/peerfinder/PeerfinderManager.h index f88b1b637c..ec4beb2db4 100644 --- a/src/xrpld/peerfinder/PeerfinderManager.h +++ b/src/xrpld/peerfinder/PeerfinderManager.h @@ -201,7 +201,7 @@ public: file, along with the set of corresponding IP addresses. */ virtual void - addFixedPeer(std::string const& name, std::vector const& addresses) = 0; + addFixedPeer(std::string_view name, std::vector const& addresses) = 0; /** Add a set of strings as fallback IP::Endpoint sources. @param name A label used for diagnostics. diff --git a/src/xrpld/peerfinder/detail/Logic.h b/src/xrpld/peerfinder/detail/Logic.h index 3ebe0cf2f4..815858cf00 100644 --- a/src/xrpld/peerfinder/detail/Logic.h +++ b/src/xrpld/peerfinder/detail/Logic.h @@ -148,13 +148,13 @@ public: } void - addFixedPeer(std::string const& name, beast::IP::Endpoint const& ep) + addFixedPeer(std::string_view name, beast::IP::Endpoint const& ep) { addFixedPeer(name, std::vector{ep}); } void - addFixedPeer(std::string const& name, std::vector const& addresses) + addFixedPeer(std::string_view name, std::vector const& addresses) { std::scoped_lock const _(lock); diff --git a/src/xrpld/peerfinder/detail/PeerfinderManager.cpp b/src/xrpld/peerfinder/detail/PeerfinderManager.cpp index 873c18aad9..f51f3630eb 100644 --- a/src/xrpld/peerfinder/detail/PeerfinderManager.cpp +++ b/src/xrpld/peerfinder/detail/PeerfinderManager.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include #include @@ -99,8 +100,7 @@ public: } void - addFixedPeer(std::string const& name, std::vector const& addresses) - override + addFixedPeer(std::string_view name, std::vector const& addresses) override { logic_.addFixedPeer(name, addresses); } diff --git a/src/xrpld/rpc/detail/AssetCache.cpp b/src/xrpld/rpc/detail/AssetCache.cpp index 0976290d4c..23cc31252d 100644 --- a/src/xrpld/rpc/detail/AssetCache.cpp +++ b/src/xrpld/rpc/detail/AssetCache.cpp @@ -22,8 +22,8 @@ namespace xrpl { -AssetCache::AssetCache(std::shared_ptr const& ledger, beast::Journal j) - : ledger_(ledger), journal_(j) +AssetCache::AssetCache(std::shared_ptr ledger, beast::Journal j) + : ledger_(std::move(ledger)), journal_(j) { JLOG(journal_.debug()) << "created for ledger " << ledger_->header().seq; } diff --git a/src/xrpld/rpc/detail/AssetCache.h b/src/xrpld/rpc/detail/AssetCache.h index dd53620cdf..e53bc3ff94 100644 --- a/src/xrpld/rpc/detail/AssetCache.h +++ b/src/xrpld/rpc/detail/AssetCache.h @@ -17,7 +17,7 @@ namespace xrpl { class AssetCache final : public CountedObject { public: - explicit AssetCache(std::shared_ptr const& l, beast::Journal j); + explicit AssetCache(std::shared_ptr l, beast::Journal j); ~AssetCache(); [[nodiscard]] std::shared_ptr const& diff --git a/src/xrpld/rpc/detail/PathRequest.cpp b/src/xrpld/rpc/detail/PathRequest.cpp index 06507319f7..3c09917dad 100644 --- a/src/xrpld/rpc/detail/PathRequest.cpp +++ b/src/xrpld/rpc/detail/PathRequest.cpp @@ -72,7 +72,7 @@ PathRequest::PathRequest( PathRequest::PathRequest( Application& app, - std::function const& completion, + std::function completion, Resource::Consumer& consumer, int id, PathRequestManager& owner, @@ -80,7 +80,7 @@ PathRequest::PathRequest( : app_(app) , journal_(journal) , owner_(owner) - , fCompletion_(completion) + , fCompletion_(std::move(completion)) , consumer_(consumer) , jvStatus_(json::ValueType::Object) , lastIndex_(0) diff --git a/src/xrpld/rpc/detail/PathRequest.h b/src/xrpld/rpc/detail/PathRequest.h index de8c10de0e..372223e99f 100644 --- a/src/xrpld/rpc/detail/PathRequest.h +++ b/src/xrpld/rpc/detail/PathRequest.h @@ -51,7 +51,7 @@ public: // Completion function is called after path update is complete PathRequest( Application& app, - std::function const& completion, + std::function completion, Resource::Consumer& consumer, int id, PathRequestManager&, From c552eb333f5625aaee67698af2e6771ba729d23c Mon Sep 17 00:00:00 2001 From: Bart Date: Tue, 9 Jun 2026 10:58:21 -0400 Subject: [PATCH 4/9] refactor: Change config section and key string literals into constants (#7095) Co-authored-by: Bart <11445373+bthomee@users.noreply.github.com> --- .../scripts/levelization/results/ordering.txt | 22 ++ cmake/XrplCore.cmake | 14 +- include/xrpl/{basics => config}/BasicConfig.h | 0 include/xrpl/config/Constants.h | 180 ++++++++++ include/xrpl/core/PerfLog.h | 2 +- include/xrpl/nodestore/Database.h | 5 +- include/xrpl/nodestore/Factory.h | 5 +- .../xrpl/nodestore/detail/DatabaseNodeImp.h | 10 +- include/xrpl/server/Port.h | 4 +- .../{basics => config}/BasicConfig.cpp | 2 +- src/libxrpl/nodestore/Database.cpp | 7 +- src/libxrpl/nodestore/DatabaseRotatingImp.cpp | 2 +- src/libxrpl/nodestore/ManagerImp.cpp | 5 +- .../nodestore/backend/MemoryFactory.cpp | 5 +- src/libxrpl/nodestore/backend/NuDBFactory.cpp | 9 +- src/libxrpl/nodestore/backend/NullFactory.cpp | 2 +- .../nodestore/backend/RocksDBFactory.cpp | 49 +-- src/libxrpl/rdb/SociDB.cpp | 9 +- src/libxrpl/server/Port.cpp | 48 +-- src/libxrpl/server/State.cpp | 2 +- src/test/app/AmendmentTable_test.cpp | 8 +- src/test/app/Batch_test.cpp | 20 +- src/test/app/FeeVote_test.cpp | 2 +- src/test/app/GRPCServerTLS_test.cpp | 141 ++++---- src/test/app/HashRouter_test.cpp | 37 +- src/test/app/Manifest_test.cpp | 3 +- src/test/app/MultiSign_test.cpp | 6 +- src/test/app/Regression_test.cpp | 13 +- src/test/app/SHAMapStore_test.cpp | 23 +- src/test/app/TxQ_test.cpp | 152 ++++---- src/test/app/ValidatorKeys_test.cpp | 16 +- src/test/app/ValidatorList_test.cpp | 53 +-- src/test/core/Config_test.cpp | 182 +++++----- src/test/core/SociDB_test.cpp | 7 +- src/test/jtx/Env_test.cpp | 3 +- src/test/jtx/envconfig.h | 5 - src/test/jtx/impl/JSONRPCClient.cpp | 7 +- src/test/jtx/impl/WSClient.cpp | 7 +- src/test/jtx/impl/envconfig.cpp | 119 +++---- src/test/nodestore/Backend_test.cpp | 7 +- src/test/nodestore/Database_test.cpp | 106 +++--- src/test/nodestore/NuDBFactory_test.cpp | 9 +- src/test/nodestore/Timing_test.cpp | 8 +- src/test/overlay/cluster_test.cpp | 2 +- src/test/rpc/AmendmentBlocked_test.cpp | 5 +- src/test/rpc/Feature_test.cpp | 5 +- src/test/rpc/JSONRPC_test.cpp | 7 +- src/test/rpc/LedgerRPC_test.cpp | 7 +- src/test/rpc/ManifestRPC_test.cpp | 4 +- src/test/rpc/RPCOverload_test.cpp | 5 +- src/test/rpc/ServerInfo_test.cpp | 8 +- src/test/rpc/Simulate_test.cpp | 3 +- src/test/rpc/Subscribe_test.cpp | 7 +- src/test/rpc/ValidatorInfo_test.cpp | 4 +- src/test/rpc/ValidatorRPC_test.cpp | 20 +- src/test/server/ServerStatus_test.cpp | 128 +++---- src/test/server/Server_test.cpp | 68 ++-- src/test/shamap/common.h | 6 +- src/tests/libxrpl/helpers/TestFamily.h | 6 +- src/xrpld/app/main/Application.cpp | 41 +-- src/xrpld/app/main/CollectorManager.cpp | 9 +- src/xrpld/app/main/CollectorManager.h | 2 +- src/xrpld/app/main/GRPCServer.cpp | 22 +- src/xrpld/app/main/Main.cpp | 6 +- src/xrpld/app/main/NodeIdentity.cpp | 11 +- src/xrpld/app/misc/NetworkOPs.cpp | 13 +- src/xrpld/app/misc/SHAMapStoreImp.cpp | 57 +-- src/xrpld/app/misc/ValidatorList.h | 4 +- src/xrpld/app/misc/detail/AmendmentTable.cpp | 2 +- src/xrpld/app/misc/detail/TxQ.cpp | 29 +- src/xrpld/app/misc/detail/ValidatorKeys.cpp | 23 +- .../app/misc/detail/setup_HashRouter.cpp | 9 +- src/xrpld/app/rdb/backend/detail/Node.cpp | 3 +- src/xrpld/app/rdb/detail/PeerFinder.cpp | 2 +- src/xrpld/core/Config.h | 2 +- src/xrpld/core/ConfigSections.h | 80 ----- src/xrpld/core/detail/Config.cpp | 329 ++++++++++-------- src/xrpld/overlay/Cluster.h | 2 +- src/xrpld/overlay/detail/Cluster.cpp | 2 +- src/xrpld/overlay/detail/OverlayImpl.cpp | 25 +- .../peerfinder/detail/PeerfinderManager.cpp | 2 +- src/xrpld/perflog/detail/PerfLogImp.cpp | 5 +- src/xrpld/rpc/detail/ServerHandler.cpp | 10 +- 83 files changed, 1262 insertions(+), 1029 deletions(-) rename include/xrpl/{basics => config}/BasicConfig.h (100%) create mode 100644 include/xrpl/config/Constants.h rename src/libxrpl/{basics => config}/BasicConfig.cpp (99%) delete mode 100644 src/xrpld/core/ConfigSections.h diff --git a/.github/scripts/levelization/results/ordering.txt b/.github/scripts/levelization/results/ordering.txt index c2000d1768..12176ec0d4 100644 --- a/.github/scripts/levelization/results/ordering.txt +++ b/.github/scripts/levelization/results/ordering.txt @@ -1,6 +1,8 @@ libxrpl.basics > xrpl.basics libxrpl.conditions > xrpl.basics libxrpl.conditions > xrpl.conditions +libxrpl.config > xrpl.basics +libxrpl.config > xrpl.config libxrpl.core > xrpl.basics libxrpl.core > xrpl.core libxrpl.core > xrpl.json @@ -17,6 +19,7 @@ libxrpl.ledger > xrpl.shamap libxrpl.net > xrpl.basics libxrpl.net > xrpl.net libxrpl.nodestore > xrpl.basics +libxrpl.nodestore > xrpl.config libxrpl.nodestore > xrpl.json libxrpl.nodestore > xrpl.nodestore libxrpl.nodestore > xrpl.protocol @@ -24,6 +27,7 @@ libxrpl.protocol > xrpl.basics libxrpl.protocol > xrpl.json libxrpl.protocol > xrpl.protocol libxrpl.rdb > xrpl.basics +libxrpl.rdb > xrpl.config libxrpl.rdb > xrpl.core libxrpl.rdb > xrpl.rdb libxrpl.resource > xrpl.basics @@ -31,6 +35,7 @@ libxrpl.resource > xrpl.json libxrpl.resource > xrpl.protocol libxrpl.resource > xrpl.resource libxrpl.server > xrpl.basics +libxrpl.server > xrpl.config libxrpl.server > xrpl.core libxrpl.server > xrpl.json libxrpl.server > xrpl.protocol @@ -52,6 +57,7 @@ libxrpl.tx > xrpl.tx test.app > test.jtx test.app > test.unit_test test.app > xrpl.basics +test.app > xrpl.config test.app > xrpl.core test.app > xrpld.app test.app > xrpld.consensus @@ -90,6 +96,7 @@ test.consensus > xrpl.tx test.core > test.jtx test.core > test.unit_test test.core > xrpl.basics +test.core > xrpl.config test.core > xrpl.core test.core > xrpld.core test.core > xrpl.json @@ -104,6 +111,7 @@ test.csf > xrpl.protocol test.json > test.jtx test.json > xrpl.json test.jtx > xrpl.basics +test.jtx > xrpl.config test.jtx > xrpl.core test.jtx > xrpld.app test.jtx > xrpld.core @@ -126,6 +134,7 @@ test.ledger > xrpl.protocol test.nodestore > test.jtx test.nodestore > test.unit_test test.nodestore > xrpl.basics +test.nodestore > xrpl.config test.nodestore > xrpld.core test.nodestore > xrpl.nodestore test.nodestore > xrpl.protocol @@ -133,6 +142,7 @@ test.nodestore > xrpl.rdb test.overlay > test.jtx test.overlay > test.unit_test test.overlay > xrpl.basics +test.overlay > xrpl.config test.overlay > xrpld.app test.overlay > xrpld.core test.overlay > xrpld.overlay @@ -159,6 +169,7 @@ test.resource > xrpl.basics test.resource > xrpl.resource test.rpc > test.jtx test.rpc > xrpl.basics +test.rpc > xrpl.config test.rpc > xrpl.core test.rpc > xrpld.app test.rpc > xrpld.core @@ -173,6 +184,7 @@ test.rpc > xrpl.tx test.server > test.jtx test.server > test.unit_test test.server > xrpl.basics +test.server > xrpl.config test.server > xrpld.app test.server > xrpld.core test.server > xrpl.json @@ -180,6 +192,7 @@ test.server > xrpl.protocol test.server > xrpl.server test.shamap > test.unit_test test.shamap > xrpl.basics +test.shamap > xrpl.config test.shamap > xrpl.nodestore test.shamap > xrpl.protocol test.shamap > xrpl.shamap @@ -188,6 +201,7 @@ test.toplevel > xrpl.json test.unit_test > xrpl.basics test.unit_test > xrpl.protocol tests.libxrpl > xrpl.basics +tests.libxrpl > xrpl.config tests.libxrpl > xrpl.core tests.libxrpl > xrpl.json tests.libxrpl > xrpl.ledger @@ -200,6 +214,7 @@ tests.libxrpl > xrpl.shamap tests.libxrpl > xrpl.tx xrpl.conditions > xrpl.basics xrpl.conditions > xrpl.protocol +xrpl.config > xrpl.basics xrpl.core > xrpl.basics xrpl.core > xrpl.json xrpl.core > xrpl.protocol @@ -210,6 +225,7 @@ xrpl.ledger > xrpl.server xrpl.ledger > xrpl.shamap xrpl.net > xrpl.basics xrpl.nodestore > xrpl.basics +xrpl.nodestore > xrpl.config xrpl.nodestore > xrpl.protocol xrpl.protocol > xrpl.basics xrpl.protocol > xrpl.json @@ -237,6 +253,7 @@ xrpl.tx > xrpl.ledger xrpl.tx > xrpl.protocol xrpld.app > test.unit_test xrpld.app > xrpl.basics +xrpld.app > xrpl.config xrpld.app > xrpl.core xrpld.app > xrpld.consensus xrpld.app > xrpld.core @@ -255,11 +272,13 @@ xrpld.consensus > xrpl.json xrpld.consensus > xrpl.ledger xrpld.consensus > xrpl.protocol xrpld.core > xrpl.basics +xrpld.core > xrpl.config xrpld.core > xrpl.core xrpld.core > xrpl.net xrpld.core > xrpl.protocol xrpld.core > xrpl.rdb xrpld.overlay > xrpl.basics +xrpld.overlay > xrpl.config xrpld.overlay > xrpl.core xrpld.overlay > xrpld.consensus xrpld.overlay > xrpld.core @@ -272,15 +291,18 @@ xrpld.overlay > xrpl.server xrpld.overlay > xrpl.shamap xrpld.overlay > xrpl.tx xrpld.peerfinder > xrpl.basics +xrpld.peerfinder > xrpl.config xrpld.peerfinder > xrpld.core xrpld.peerfinder > xrpl.protocol xrpld.peerfinder > xrpl.rdb xrpld.perflog > xrpl.basics +xrpld.perflog > xrpl.config xrpld.perflog > xrpl.core xrpld.perflog > xrpld.rpc xrpld.perflog > xrpl.json xrpld.perflog > xrpl.protocol xrpld.rpc > xrpl.basics +xrpld.rpc > xrpl.config xrpld.rpc > xrpl.core xrpld.rpc > xrpld.core xrpld.rpc > xrpl.json diff --git a/cmake/XrplCore.cmake b/cmake/XrplCore.cmake index 9b1dc74049..52d7714a99 100644 --- a/cmake/XrplCore.cmake +++ b/cmake/XrplCore.cmake @@ -94,6 +94,9 @@ add_module(xrpl basics) target_link_libraries(xrpl.libxrpl.basics PUBLIC xrpl.libxrpl.beast) # Level 03 +add_module(xrpl config) +target_link_libraries(xrpl.libxrpl.config PUBLIC xrpl.libxrpl.basics) + add_module(xrpl json) target_link_libraries(xrpl.libxrpl.json PUBLIC xrpl.libxrpl.basics) @@ -120,6 +123,7 @@ target_link_libraries( xrpl.libxrpl.core PUBLIC xrpl.libxrpl.basics + xrpl.libxrpl.config xrpl.libxrpl.json xrpl.libxrpl.protocol xrpl.libxrpl.protocol_autogen @@ -143,7 +147,11 @@ target_link_libraries( add_module(xrpl nodestore) target_link_libraries( xrpl.libxrpl.nodestore - PUBLIC xrpl.libxrpl.basics xrpl.libxrpl.json xrpl.libxrpl.protocol + PUBLIC + xrpl.libxrpl.basics + xrpl.libxrpl.config + xrpl.libxrpl.json + xrpl.libxrpl.protocol ) add_module(xrpl shamap) @@ -159,13 +167,14 @@ target_link_libraries( add_module(xrpl rdb) target_link_libraries( xrpl.libxrpl.rdb - PUBLIC xrpl.libxrpl.basics xrpl.libxrpl.core + PUBLIC xrpl.libxrpl.basics xrpl.libxrpl.config xrpl.libxrpl.core ) add_module(xrpl server) target_link_libraries( xrpl.libxrpl.server PUBLIC + xrpl.libxrpl.config xrpl.libxrpl.protocol xrpl.libxrpl.core xrpl.libxrpl.rdb @@ -210,6 +219,7 @@ target_link_modules( basics beast conditions + config core crypto git diff --git a/include/xrpl/basics/BasicConfig.h b/include/xrpl/config/BasicConfig.h similarity index 100% rename from include/xrpl/basics/BasicConfig.h rename to include/xrpl/config/BasicConfig.h diff --git a/include/xrpl/config/Constants.h b/include/xrpl/config/Constants.h new file mode 100644 index 0000000000..5514e0e77b --- /dev/null +++ b/include/xrpl/config/Constants.h @@ -0,0 +1,180 @@ +#pragma once + +namespace xrpl { + +struct Sections +{ + static constexpr auto kAmendments = "amendments"; + static constexpr auto kAmendmentMajorityTime = "amendment_majority_time"; + static constexpr auto kBetaRpcApi = "beta_rpc_api"; + static constexpr auto kClusterNodes = "cluster_nodes"; + static constexpr auto kCompression = "compression"; + static constexpr auto kCrawl = "crawl"; + static constexpr auto kDatabasePath = "database_path"; + static constexpr auto kDebugLogfile = "debug_logfile"; + static constexpr auto kElbSupport = "elb_support"; + static constexpr auto kFeatures = "features"; + static constexpr auto kFeeDefault = "fee_default"; + static constexpr auto kFetchDepth = "fetch_depth"; + static constexpr auto kHashrouter = "hashrouter"; + static constexpr auto kImportNodeDatabase = "import_db"; + static constexpr auto kInsight = "insight"; + static constexpr auto kIoWorkers = "io_workers"; + static constexpr auto kIps = "ips"; + static constexpr auto kIpsFixed = "ips_fixed"; + static constexpr auto kLedgerHistory = "ledger_history"; + static constexpr auto kLedgerReplay = "ledger_replay"; + static constexpr auto kLedgerTxTables = "ledger_tx_tables"; + static constexpr auto kMaxTransactions = "max_transactions"; + static constexpr auto kNetworkId = "network_id"; + static constexpr auto kNetworkQuorum = "network_quorum"; + static constexpr auto kNodeDatabase = "node_db"; + static constexpr auto kNodeSeed = "node_seed"; + static constexpr auto kNodeSize = "node_size"; + static constexpr auto kOverlay = "overlay"; + static constexpr auto kPathSearch = "path_search"; + static constexpr auto kPathSearchFast = "path_search_fast"; + static constexpr auto kPathSearchMax = "path_search_max"; + static constexpr auto kPathSearchOld = "path_search_old"; + static constexpr auto kPeerPrivate = "peer_private"; + static constexpr auto kPeersInMax = "peers_in_max"; + static constexpr auto kPeersMax = "peers_max"; + static constexpr auto kPeersOutMax = "peers_out_max"; + static constexpr auto kPerf = "perf"; + static constexpr auto kPortGrpc = "port_grpc"; + static constexpr auto kPortPeer = "port_peer"; + static constexpr auto kPortRpc = "port_rpc"; + static constexpr auto kPortWs = "port_ws"; + static constexpr auto kPortWssAdmin = "port_wss_admin"; + static constexpr auto kPrefetchWorkers = "prefetch_workers"; + static constexpr auto kReduceRelay = "reduce_relay"; + static constexpr auto kRelationalDb = "relational_db"; + static constexpr auto kRelayProposals = "relay_proposals"; + static constexpr auto kRelayValidations = "relay_validations"; + static constexpr auto kRpcStartup = "rpc_startup"; + static constexpr auto kServer = "server"; + static constexpr auto kServerDomain = "server_domain"; + static constexpr auto kSigningSupport = "signing_support"; + static constexpr auto kSntp = "sntp_servers"; + static constexpr auto kSqdb = "sqdb"; + static constexpr auto kSqlite = "sqlite"; + static constexpr auto kSslVerify = "ssl_verify"; + static constexpr auto kSslVerifyDir = "ssl_verify_dir"; + static constexpr auto kSslVerifyFile = "ssl_verify_file"; + static constexpr auto kSweepInterval = "sweep_interval"; + static constexpr auto kTransactionQueue = "transaction_queue"; + static constexpr auto kValidationSeed = "validation_seed"; + static constexpr auto kValidatorKeys = "validator_keys"; + static constexpr auto kValidatorKeyRevocation = "validator_key_revocation"; + static constexpr auto kValidatorListKeys = "validator_list_keys"; + static constexpr auto kValidatorListSites = "validator_list_sites"; + static constexpr auto kValidatorListThreshold = "validator_list_threshold"; + static constexpr auto kValidatorToken = "validator_token"; + static constexpr auto kValidators = "validators"; + static constexpr auto kValidatorsFile = "validators_file"; + static constexpr auto kVetoAmendments = "veto_amendments"; + static constexpr auto kVl = "vl"; + static constexpr auto kVoting = "voting"; + static constexpr auto kWorkers = "workers"; +}; + +struct Keys +{ + static constexpr auto kAccountReserve = "account_reserve"; + static constexpr auto kAddress = "address"; + static constexpr auto kAdmin = "admin"; + static constexpr auto kAdminPassword = "admin_password"; + static constexpr auto kAdminUser = "admin_user"; + static constexpr auto kAdvisoryDelete = "advisory_delete"; + static constexpr auto kAgeThresholdSeconds = "age_threshold_seconds"; + static constexpr auto kBackOff = "backOff"; + static constexpr auto kBackOffMilliseconds = "back_off_milliseconds"; + static constexpr auto kBackend = "backend"; + static constexpr auto kBbtOptions = "bbt_options"; + static constexpr auto kBgThreads = "bg_threads"; + static constexpr auto kBlockSize = "block_size"; + static constexpr auto kCacheAge = "cache_age"; + static constexpr auto kCacheMb = "cache_mb"; + static constexpr auto kCacheSize = "cache_size"; + static constexpr auto kClientMaxWindowBits = "client_max_window_bits"; + static constexpr auto kClientNoContextTakeover = "client_no_context_takeover"; + static constexpr auto kCompressLevel = "compress_level"; + static constexpr auto kCounts = "counts"; + static constexpr auto kDeleteBatch = "delete_batch"; + static constexpr auto kEarliestSeq = "earliest_seq"; + static constexpr auto kFastLoad = "fast_load"; + static constexpr auto kFileSizeMb = "file_size_mb"; + static constexpr auto kFileSizeMult = "file_size_mult"; + static constexpr auto kFilterBits = "filter_bits"; + static constexpr auto kFilterFull = "filter_full"; + static constexpr auto kHardSet = "hard_set"; + static constexpr auto kHighThreads = "high_threads"; + static constexpr auto kHoldTime = "hold_time"; + static constexpr auto kIp = "ip"; + static constexpr auto kJournalMode = "journal_mode"; + static constexpr auto kJournalSizeLimit = "journal_size_limit"; + static constexpr auto kLedgersInQueue = "ledgers_in_queue"; + static constexpr auto kLimit = "limit"; + static constexpr auto kLogInterval = "log_interval"; + static constexpr auto kMaxDivergedTime = "max_diverged_time"; + static constexpr auto kMaxLedgerCountsToStore = "max_ledger_counts_to_store"; + static constexpr auto kMaxUnknownTime = "max_unknown_time"; + static constexpr auto kMaximumTxnInLedger = "maximum_txn_in_ledger"; + static constexpr auto kMaximumTxnPerAccount = "maximum_txn_per_account"; + static constexpr auto kMemoryLevel = "memory_level"; + static constexpr auto kMinLedgersToComputeSizeLimit = "min_ledgers_to_compute_size_limit"; + static constexpr auto kMinimumEscalationMultiplier = "minimum_escalation_multiplier"; + static constexpr auto kMinimumLastLedgerBuffer = "minimum_last_ledger_buffer"; + static constexpr auto kMinimumQueueSize = "minimum_queue_size"; + static constexpr auto kMinimumTxnInLedger = "minimum_txn_in_ledger"; + static constexpr auto kMinimumTxnInLedgerStandalone = "minimum_txn_in_ledger_standalone"; + static constexpr auto kNormalConsensusIncreasePercent = "normal_consensus_increase_percent"; + static constexpr auto kNudbBlockSize = "nudb_block_size"; + static constexpr auto kOnlineDelete = "online_delete"; + static constexpr auto kOpenFiles = "open_files"; + static constexpr auto kOptions = "options"; + static constexpr auto kOverlay = "overlay"; + static constexpr auto kOwnerReserve = "owner_reserve"; + static constexpr auto kPageSize = "page_size"; + static constexpr auto kPassword = "password"; + static constexpr auto kPath = "path"; + static constexpr auto kPermessageDeflate = "permessage_deflate"; + static constexpr auto kPort = "port"; + static constexpr auto kPrefix = "prefix"; + static constexpr auto kProtocol = "protocol"; + static constexpr auto kRecoveryWaitSeconds = "recovery_wait_seconds"; + static constexpr auto kReferenceFee = "reference_fee"; + static constexpr auto kRelayTime = "relay_time"; + static constexpr auto kRetrySequencePercent = "retry_sequence_percent"; + static constexpr auto kRqBundle = "rq_bundle"; + static constexpr auto kSafetyLevel = "safety_level"; + static constexpr auto kSecureGateway = "secure_gateway"; + static constexpr auto kSendQueueLimit = "send_queue_limit"; + static constexpr auto kServer = "server"; + static constexpr auto kServerMaxWindowBits = "server_max_window_bits"; + static constexpr auto kServerNoContextTakeover = "server_no_context_takeover"; + static constexpr auto kSlowConsensusDecreasePercent = "slow_consensus_decrease_percent"; + static constexpr auto kSslCert = "ssl_cert"; + static constexpr auto kSslCertChain = "ssl_cert_chain"; + static constexpr auto kSslChain = "ssl_chain"; + static constexpr auto kSslCiphers = "ssl_ciphers"; + static constexpr auto kSslClientCa = "ssl_client_ca"; + static constexpr auto kSslKey = "ssl_key"; + static constexpr auto kSynchronous = "synchronous"; + static constexpr auto kTargetTxnInLedger = "target_txn_in_ledger"; + static constexpr auto kTempStore = "temp_store"; + static constexpr auto kTxEnable = "tx_enable"; + static constexpr auto kTxMetrics = "tx_metrics"; + static constexpr auto kTxMinPeers = "tx_min_peers"; + static constexpr auto kTxRelayPercentage = "tx_relay_percentage"; + static constexpr auto kType = "type"; + static constexpr auto kUniversalCompaction = "universal_compaction"; + static constexpr auto kUnl = "unl"; + static constexpr auto kUseTxTables = "use_tx_tables"; + static constexpr auto kUser = "user"; + static constexpr auto kVpBaseSquelchEnable = "vp_base_squelch_enable"; + static constexpr auto kVpBaseSquelchMaxSelectedPeers = "vp_base_squelch_max_selected_peers"; + static constexpr auto kVpEnable = "vp_enable"; +}; + +} // namespace xrpl diff --git a/include/xrpl/core/PerfLog.h b/include/xrpl/core/PerfLog.h index 38318c745d..ca0d9333a4 100644 --- a/include/xrpl/core/PerfLog.h +++ b/include/xrpl/core/PerfLog.h @@ -1,6 +1,5 @@ #pragma once -#include #include #include @@ -18,6 +17,7 @@ class Journal; namespace xrpl { class Application; +class Section; namespace perf { /** diff --git a/include/xrpl/nodestore/Database.h b/include/xrpl/nodestore/Database.h index 438a3cc7fc..68c5dcefb6 100644 --- a/include/xrpl/nodestore/Database.h +++ b/include/xrpl/nodestore/Database.h @@ -1,6 +1,5 @@ #pragma once -#include #include #include #include @@ -10,6 +9,10 @@ #include +namespace xrpl { +class Section; +} // namespace xrpl + namespace xrpl::NodeStore { /** Persistency layer for NodeObject diff --git a/include/xrpl/nodestore/Factory.h b/include/xrpl/nodestore/Factory.h index c40be62d21..3e6ba76a08 100644 --- a/include/xrpl/nodestore/Factory.h +++ b/include/xrpl/nodestore/Factory.h @@ -1,12 +1,15 @@ #pragma once -#include #include #include #include #include +namespace xrpl { +class Section; +} // namespace xrpl + namespace xrpl::NodeStore { /** Base class for backend factories. */ diff --git a/include/xrpl/nodestore/detail/DatabaseNodeImp.h b/include/xrpl/nodestore/detail/DatabaseNodeImp.h index 951c60c8c7..38b8763f31 100644 --- a/include/xrpl/nodestore/detail/DatabaseNodeImp.h +++ b/include/xrpl/nodestore/detail/DatabaseNodeImp.h @@ -2,6 +2,8 @@ #include #include +#include +#include #include namespace xrpl::NodeStore { @@ -24,16 +26,16 @@ public: { std::optional cacheSize, cacheAge; - if (config.exists("cache_size")) + if (config.exists(Keys::kCacheSize)) { - cacheSize = get(config, "cache_size"); + cacheSize = get(config, Keys::kCacheSize); if (cacheSize.value() < 0) Throw("Specified negative value for cache_size"); } - if (config.exists("cache_age")) + if (config.exists(Keys::kCacheAge)) { - cacheAge = get(config, "cache_age"); + cacheAge = get(config, Keys::kCacheAge); if (cacheAge.value() < 0) Throw("Specified negative value for cache_age"); } diff --git a/include/xrpl/server/Port.h b/include/xrpl/server/Port.h index ac9b855cf0..fd773c78fc 100644 --- a/include/xrpl/server/Port.h +++ b/include/xrpl/server/Port.h @@ -1,6 +1,5 @@ #pragma once -#include #include #include @@ -14,6 +13,7 @@ #include #include #include +#include namespace boost::asio::ssl { class context; // NOLINT(readability-identifier-naming) -- external library name @@ -21,6 +21,8 @@ class context; // NOLINT(readability-identifier-naming) -- external library nam namespace xrpl { +class Section; + /** Configuration information for a Server listening port. */ struct Port { diff --git a/src/libxrpl/basics/BasicConfig.cpp b/src/libxrpl/config/BasicConfig.cpp similarity index 99% rename from src/libxrpl/basics/BasicConfig.cpp rename to src/libxrpl/config/BasicConfig.cpp index 9fe79bdf4e..6b94473392 100644 --- a/src/libxrpl/basics/BasicConfig.cpp +++ b/src/libxrpl/config/BasicConfig.cpp @@ -1,4 +1,4 @@ -#include +#include #include diff --git a/src/libxrpl/nodestore/Database.cpp b/src/libxrpl/nodestore/Database.cpp index b584aca268..ac51dbfb2c 100644 --- a/src/libxrpl/nodestore/Database.cpp +++ b/src/libxrpl/nodestore/Database.cpp @@ -1,12 +1,13 @@ #include -#include #include #include #include #include #include #include +#include +#include #include #include #include @@ -38,8 +39,8 @@ Database::Database( beast::Journal journal) : j_(journal) , scheduler_(scheduler) - , earliestLedgerSeq_(get(config, "earliest_seq", kXrpLedgerEarliestSeq)) - , requestBundle_(get(config, "rq_bundle", 4)) + , earliestLedgerSeq_(get(config, Keys::kEarliestSeq, kXrpLedgerEarliestSeq)) + , requestBundle_(get(config, Keys::kRqBundle, 4)) , readThreads_(std::max(1, readThreads)) { XRPL_ASSERT(readThreads, "xrpl::NodeStore::Database::Database : nonzero threads input"); diff --git a/src/libxrpl/nodestore/DatabaseRotatingImp.cpp b/src/libxrpl/nodestore/DatabaseRotatingImp.cpp index 1de6a83b4c..7f4dca3ed1 100644 --- a/src/libxrpl/nodestore/DatabaseRotatingImp.cpp +++ b/src/libxrpl/nodestore/DatabaseRotatingImp.cpp @@ -1,11 +1,11 @@ #include -#include #include #include #include #include #include +#include #include #include #include diff --git a/src/libxrpl/nodestore/ManagerImp.cpp b/src/libxrpl/nodestore/ManagerImp.cpp index 5cefbfd357..5f366079f1 100644 --- a/src/libxrpl/nodestore/ManagerImp.cpp +++ b/src/libxrpl/nodestore/ManagerImp.cpp @@ -1,9 +1,10 @@ #include -#include #include #include #include +#include +#include #include #include #include @@ -66,7 +67,7 @@ ManagerImp::makeBackend( Scheduler& scheduler, beast::Journal journal) { - std::string const type{get(parameters, "type")}; + std::string const type{get(parameters, Keys::kType)}; if (type.empty()) missingBackend(); diff --git a/src/libxrpl/nodestore/backend/MemoryFactory.cpp b/src/libxrpl/nodestore/backend/MemoryFactory.cpp index 5bdf8e65b5..70578c8613 100644 --- a/src/libxrpl/nodestore/backend/MemoryFactory.cpp +++ b/src/libxrpl/nodestore/backend/MemoryFactory.cpp @@ -1,8 +1,9 @@ -#include #include #include #include #include +#include +#include #include #include #include @@ -90,7 +91,7 @@ private: public: MemoryBackend(size_t keyBytes, Section const& keyValues, beast::Journal journal) - : name_(get(keyValues, "path")), journal_(journal) + : name_(get(keyValues, Keys::kPath)), journal_(journal) { boost::ignore_unused(journal_); // Keep unused journal_ just in case. if (name_.empty()) diff --git a/src/libxrpl/nodestore/backend/NuDBFactory.cpp b/src/libxrpl/nodestore/backend/NuDBFactory.cpp index abf09e871d..749d4020b5 100644 --- a/src/libxrpl/nodestore/backend/NuDBFactory.cpp +++ b/src/libxrpl/nodestore/backend/NuDBFactory.cpp @@ -1,10 +1,11 @@ -#include #include #include #include #include #include #include +#include +#include #include #include #include @@ -72,7 +73,7 @@ public: : j(journal) , keyBytes(keyBytes) , burstSize(burstSize) - , name(get(keyValues, "path")) + , name(get(keyValues, Keys::kPath)) , blockSize(parseBlockSize(name, keyValues, journal)) , deletePath(false) , scheduler(scheduler) @@ -91,7 +92,7 @@ public: : j(journal) , keyBytes(keyBytes) , burstSize(burstSize) - , name(get(keyValues, "path")) + , name(get(keyValues, Keys::kPath)) , blockSize(parseBlockSize(name, keyValues, journal)) , db(context) , deletePath(false) @@ -359,7 +360,7 @@ private: std::size_t const blockSize = defaultSize; std::string blockSizeStr; - if (!getIfExists(keyValues, "nudb_block_size", blockSizeStr)) + if (!getIfExists(keyValues, Keys::kNudbBlockSize, blockSizeStr)) { return blockSize; // Early return with default } diff --git a/src/libxrpl/nodestore/backend/NullFactory.cpp b/src/libxrpl/nodestore/backend/NullFactory.cpp index 36b8139984..e36b13a2e1 100644 --- a/src/libxrpl/nodestore/backend/NullFactory.cpp +++ b/src/libxrpl/nodestore/backend/NullFactory.cpp @@ -1,6 +1,6 @@ -#include #include #include +#include #include #include #include diff --git a/src/libxrpl/nodestore/backend/RocksDBFactory.cpp b/src/libxrpl/nodestore/backend/RocksDBFactory.cpp index d2c193888c..252ff32ccf 100644 --- a/src/libxrpl/nodestore/backend/RocksDBFactory.cpp +++ b/src/libxrpl/nodestore/backend/RocksDBFactory.cpp @@ -1,8 +1,9 @@ -#include #include #include #include #include +#include +#include #include #include #include @@ -111,17 +112,18 @@ public: RocksDBEnv* env) : deletePath_(false), journal(journal), keyBytes(keyBytes), batch(*this, scheduler) { - if (!getIfExists(keyValues, "path", name)) + if (!getIfExists(keyValues, Keys::kPath, name)) Throw("Missing path in RocksDBFactory backend"); rocksdb::BlockBasedTableOptions tableOptions; options.env = env; - bool const hardSet = keyValues.exists("hard_set") && get(keyValues, "hard_set"); + bool const hardSet = + keyValues.exists(Keys::kHardSet) && get(keyValues, Keys::kHardSet); - if (keyValues.exists("cache_mb")) + if (keyValues.exists(Keys::kCacheMb)) { - auto size = get(keyValues, "cache_mb"); + auto size = get(keyValues, Keys::kCacheMb); if (!hardSet && size == 256) size = 1024; @@ -129,14 +131,14 @@ public: tableOptions.block_cache = rocksdb::NewLRUCache(megabytes(size)); } - if (auto const v = get(keyValues, "filter_bits")) + if (auto const v = get(keyValues, Keys::kFilterBits)) { - bool const filterBlocks = - !keyValues.exists("filter_full") || (get(keyValues, "filter_full") == 0); + bool const filterBlocks = !keyValues.exists(Keys::kFilterFull) || + (get(keyValues, Keys::kFilterFull) == 0); tableOptions.filter_policy.reset(rocksdb::NewBloomFilterPolicy(v, filterBlocks)); } - if (getIfExists(keyValues, "open_files", options.max_open_files)) + if (getIfExists(keyValues, Keys::kOpenFiles, options.max_open_files)) { if (!hardSet && options.max_open_files == 2000) options.max_open_files = 8000; @@ -144,9 +146,9 @@ public: fdMinRequired = options.max_open_files + 128; } - if (keyValues.exists("file_size_mb")) + if (keyValues.exists(Keys::kFileSizeMb)) { - auto fileSizeMb = get(keyValues, "file_size_mb"); + auto fileSizeMb = get(keyValues, Keys::kFileSizeMb); if (!hardSet && fileSizeMb == 8) fileSizeMb = 256; @@ -156,16 +158,17 @@ public: options.write_buffer_size = 2 * options.target_file_size_base; } - getIfExists(keyValues, "file_size_mult", options.target_file_size_multiplier); + getIfExists(keyValues, Keys::kFileSizeMult, options.target_file_size_multiplier); - if (keyValues.exists("bg_threads")) + if (keyValues.exists(Keys::kBgThreads)) { - options.env->SetBackgroundThreads(get(keyValues, "bg_threads"), rocksdb::Env::LOW); + options.env->SetBackgroundThreads( + get(keyValues, Keys::kBgThreads), rocksdb::Env::LOW); } - if (keyValues.exists("high_threads")) + if (keyValues.exists(Keys::kHighThreads)) { - auto const highThreads = get(keyValues, "high_threads"); + auto const highThreads = get(keyValues, Keys::kHighThreads); options.env->SetBackgroundThreads(highThreads, rocksdb::Env::HIGH); // If we have high-priority threads, presumably we want to @@ -176,10 +179,10 @@ public: options.compression = rocksdb::kSnappyCompression; - getIfExists(keyValues, "block_size", tableOptions.block_size); + getIfExists(keyValues, Keys::kBlockSize, tableOptions.block_size); - if (keyValues.exists("universal_compaction") && - (get(keyValues, "universal_compaction") != 0)) + if (keyValues.exists(Keys::kUniversalCompaction) && + (get(keyValues, Keys::kUniversalCompaction) != 0)) { options.compaction_style = rocksdb::kCompactionStyleUniversal; options.min_write_buffer_number_to_merge = 2; @@ -187,11 +190,11 @@ public: options.write_buffer_size = 6 * options.target_file_size_base; } - if (keyValues.exists("bbt_options")) + if (keyValues.exists(Keys::kBbtOptions)) { rocksdb::ConfigOptions const configOptions; auto const s = rocksdb::GetBlockBasedTableOptionsFromString( - configOptions, tableOptions, get(keyValues, "bbt_options"), &tableOptions); + configOptions, tableOptions, get(keyValues, Keys::kBbtOptions), &tableOptions); if (!s.ok()) { Throw( @@ -201,10 +204,10 @@ public: options.table_factory.reset(NewBlockBasedTableFactory(tableOptions)); - if (keyValues.exists("options")) + if (keyValues.exists(Keys::kOptions)) { auto const s = - rocksdb::GetOptionsFromString(options, get(keyValues, "options"), &options); + rocksdb::GetOptionsFromString(options, get(keyValues, Keys::kOptions), &options); if (!s.ok()) { Throw( diff --git a/src/libxrpl/rdb/SociDB.cpp b/src/libxrpl/rdb/SociDB.cpp index 541933b3b0..06e58d373f 100644 --- a/src/libxrpl/rdb/SociDB.cpp +++ b/src/libxrpl/rdb/SociDB.cpp @@ -1,5 +1,6 @@ -#include #include +#include +#include #include #include #include @@ -53,13 +54,13 @@ getSociSqliteInit(std::string const& name, std::string const& dir, std::string c std::string getSociInit(BasicConfig const& config, std::string const& dbName) { - auto const& section = config.section("sqdb"); - auto const backendName = get(section, "backend", "sqlite"); + auto const& section = config.section(Sections::kSqdb); + auto const backendName = get(section, Keys::kBackend, "sqlite"); if (backendName != "sqlite") Throw("Unsupported soci backend: " + backendName); - auto const path = config.legacy("database_path"); + auto const path = config.legacy(Sections::kDatabasePath); auto const ext = dbName == "validators" || dbName == "peerfinder" ? ".sqlite" : ".db"; return detail::getSociSqliteInit(dbName, path, ext); } diff --git a/src/libxrpl/server/Port.cpp b/src/libxrpl/server/Port.cpp index b3fd7a1526..c1a79019af 100644 --- a/src/libxrpl/server/Port.cpp +++ b/src/libxrpl/server/Port.cpp @@ -1,11 +1,12 @@ #include -#include #include #include #include #include #include +#include +#include #include #include @@ -195,7 +196,7 @@ parsePort(ParsedPort& port, Section const& section, std::ostream& log) { port.name = section.name(); { - auto const optResult = section.get("ip"); + auto const optResult = section.get(Keys::kIp); if (optResult) { try @@ -212,7 +213,7 @@ parsePort(ParsedPort& port, Section const& section, std::ostream& log) } { - auto const optResult = section.get("port"); + auto const optResult = section.get(Keys::kPort); if (optResult) { try @@ -233,7 +234,7 @@ parsePort(ParsedPort& port, Section const& section, std::ostream& log) } { - auto const optResult = section.get("protocol"); + auto const optResult = section.get(Keys::kProtocol); if (optResult) { for (auto const& s : beast::rfc2616::splitCommas(optResult->begin(), optResult->end())) @@ -242,7 +243,7 @@ parsePort(ParsedPort& port, Section const& section, std::ostream& log) } { - auto const lim = get(section, "limit", "unlimited"); + auto const lim = get(section, Keys::kLimit, "unlimited"); if (!boost::iequals(lim, "unlimited")) { @@ -260,7 +261,7 @@ parsePort(ParsedPort& port, Section const& section, std::ostream& log) } { - auto const optResult = section.get("send_queue_limit"); + auto const optResult = section.get(Keys::kSendQueueLimit); if (optResult) { try @@ -285,27 +286,28 @@ parsePort(ParsedPort& port, Section const& section, std::ostream& log) } } - populate(section, "admin", log, port.adminNetsV4, port.adminNetsV6); - populate(section, "secure_gateway", log, port.secureGatewayNetsV4, port.secureGatewayNetsV6); + populate(section, Keys::kAdmin, log, port.adminNetsV4, port.adminNetsV6); + populate( + section, Keys::kSecureGateway, log, port.secureGatewayNetsV4, port.secureGatewayNetsV6); - set(port.user, "user", section); - set(port.password, "password", section); - set(port.adminUser, "admin_user", section); - set(port.adminPassword, "admin_password", section); - set(port.sslKey, "ssl_key", section); - set(port.sslCert, "ssl_cert", section); - set(port.sslChain, "ssl_chain", section); - set(port.sslCiphers, "ssl_ciphers", section); + set(port.user, Keys::kUser, section); + set(port.password, Keys::kPassword, section); + set(port.adminUser, Keys::kAdminUser, section); + set(port.adminPassword, Keys::kAdminPassword, section); + set(port.sslKey, Keys::kSslKey, section); + set(port.sslCert, Keys::kSslCert, section); + set(port.sslChain, Keys::kSslChain, section); + set(port.sslCiphers, Keys::kSslCiphers, section); - port.pmdOptions.server_enable = section.valueOr("permessage_deflate", true); - port.pmdOptions.client_max_window_bits = section.valueOr("client_max_window_bits", 15); - port.pmdOptions.server_max_window_bits = section.valueOr("server_max_window_bits", 15); + port.pmdOptions.server_enable = section.valueOr(Keys::kPermessageDeflate, true); + port.pmdOptions.client_max_window_bits = section.valueOr(Keys::kClientMaxWindowBits, 15); + port.pmdOptions.server_max_window_bits = section.valueOr(Keys::kServerMaxWindowBits, 15); port.pmdOptions.client_no_context_takeover = - section.valueOr("client_no_context_takeover", false); + section.valueOr(Keys::kClientNoContextTakeover, false); port.pmdOptions.server_no_context_takeover = - section.valueOr("server_no_context_takeover", false); - port.pmdOptions.compLevel = section.valueOr("compress_level", 8); - port.pmdOptions.memLevel = section.valueOr("memory_level", 4); + section.valueOr(Keys::kServerNoContextTakeover, false); + port.pmdOptions.compLevel = section.valueOr(Keys::kCompressLevel, 8); + port.pmdOptions.memLevel = section.valueOr(Keys::kMemoryLevel, 4); } } // namespace xrpl diff --git a/src/libxrpl/server/State.cpp b/src/libxrpl/server/State.cpp index b9cb7c6ff2..d9793f53d0 100644 --- a/src/libxrpl/server/State.cpp +++ b/src/libxrpl/server/State.cpp @@ -1,7 +1,7 @@ #include -#include #include +#include #include #include diff --git a/src/test/app/AmendmentTable_test.cpp b/src/test/app/AmendmentTable_test.cpp index 219aaabdda..7c2087bd4a 100644 --- a/src/test/app/AmendmentTable_test.cpp +++ b/src/test/app/AmendmentTable_test.cpp @@ -4,14 +4,14 @@ #include #include -#include -#include #include #include #include #include #include +#include +#include #include #include #include @@ -83,8 +83,8 @@ private: makeConfig() { auto cfg = test::jtx::envconfig(); - cfg->section(SECTION_AMENDMENTS) = makeSection(SECTION_AMENDMENTS, enabled_); - cfg->section(SECTION_VETO_AMENDMENTS) = makeSection(SECTION_VETO_AMENDMENTS, vetoed_); + cfg->section(Sections::kAmendments) = makeSection(Sections::kAmendments, enabled_); + cfg->section(Sections::kVetoAmendments) = makeSection(Sections::kVetoAmendments, vetoed_); return cfg; } diff --git a/src/test/app/Batch_test.cpp b/src/test/app/Batch_test.cpp index 791bb5a4d6..47f9a84fb9 100644 --- a/src/test/app/Batch_test.cpp +++ b/src/test/app/Batch_test.cpp @@ -33,6 +33,8 @@ #include #include #include +#include +#include #include #include #include @@ -168,13 +170,13 @@ class Batch_test : public beast::unit_test::Suite std::map extraVoting = {}) { auto p = test::jtx::envconfig(); - auto& section = p->section("transaction_queue"); - section.set("ledgers_in_queue", "2"); - section.set("minimum_queue_size", "2"); - section.set("min_ledgers_to_compute_size_limit", "3"); - section.set("max_ledger_counts_to_store", "100"); - section.set("retry_sequence_percent", "25"); - section.set("normal_consensus_increase_percent", "0"); + auto& section = p->section(Sections::kTransactionQueue); + section.set(Keys::kLedgersInQueue, "2"); + section.set(Keys::kMinimumQueueSize, "2"); + section.set(Keys::kMinLedgersToComputeSizeLimit, "3"); + section.set(Keys::kMaxLedgerCountsToStore, "100"); + section.set(Keys::kRetrySequencePercent, "25"); + section.set(Keys::kNormalConsensusIncreasePercent, "0"); for (auto const& [k, v] : extraTxQ) section.set(k, v); @@ -4361,7 +4363,7 @@ class Batch_test : public beast::unit_test::Suite { test::jtx::Env env{ *this, - makeSmallQueueConfig({{"minimum_txn_in_ledger_standalone", "2"}}), + makeSmallQueueConfig({{Keys::kMinimumTxnInLedgerStandalone, "2"}}), features, nullptr, beast::Severity::Error}; @@ -4417,7 +4419,7 @@ class Batch_test : public beast::unit_test::Suite { test::jtx::Env env{ *this, - makeSmallQueueConfig({{"minimum_txn_in_ledger_standalone", "2"}}), + makeSmallQueueConfig({{Keys::kMinimumTxnInLedgerStandalone, "2"}}), features, nullptr, beast::Severity::Error}; diff --git a/src/test/app/FeeVote_test.cpp b/src/test/app/FeeVote_test.cpp index 22e8322bb5..bf42e762c6 100644 --- a/src/test/app/FeeVote_test.cpp +++ b/src/test/app/FeeVote_test.cpp @@ -4,9 +4,9 @@ #include #include -#include #include #include +#include #include #include #include diff --git a/src/test/app/GRPCServerTLS_test.cpp b/src/test/app/GRPCServerTLS_test.cpp index c7156fb3a2..ae0d839a6e 100644 --- a/src/test/app/GRPCServerTLS_test.cpp +++ b/src/test/app/GRPCServerTLS_test.cpp @@ -1,9 +1,8 @@ #include #include -#include - #include +#include #include #include @@ -368,7 +367,8 @@ public: Env env(*this, std::move(cfg)); // Verify the server actually started by checking the port - auto const grpcPort = env.app().config()[SECTION_PORT_GRPC].get("port"); + auto const grpcPort = + env.app().config()[Sections::kPortGrpc].get(Keys::kPort); BEAST_EXPECT(grpcPort.has_value()); // NOLINTBEGIN(bugprone-unchecked-optional-access) grpcPort.has_value() checked above BEAST_EXPECT(*grpcPort > 0); @@ -394,7 +394,8 @@ public: Env env(*this, std::move(cfg)); // Verify the server actually started by checking the port - auto const grpcPort = env.app().config()[SECTION_PORT_GRPC].get("port"); + auto const grpcPort = + env.app().config()[Sections::kPortGrpc].get(Keys::kPort); BEAST_EXPECT(grpcPort.has_value()); // NOLINTBEGIN(bugprone-unchecked-optional-access) grpcPort.has_value() checked above BEAST_EXPECT(*grpcPort > 0); @@ -431,7 +432,8 @@ public: Env env(*this, std::move(cfg)); // Verify the server actually started by checking the port - auto const grpcPort = env.app().config()[SECTION_PORT_GRPC].get("port"); + auto const grpcPort = + env.app().config()[Sections::kPortGrpc].get(Keys::kPort); BEAST_EXPECT(grpcPort.has_value()); // NOLINTBEGIN(bugprone-unchecked-optional-access) grpcPort.has_value() checked above BEAST_EXPECT(*grpcPort > 0); @@ -465,9 +467,9 @@ public: // Create config with only cert (missing key) auto cfg = envconfig(); - (*cfg)[SECTION_PORT_GRPC].set("ip", "127.0.0.1"); - (*cfg)[SECTION_PORT_GRPC].set("port", "0"); - (*cfg)[SECTION_PORT_GRPC].set("ssl_cert", getServerCertPath().string()); + (*cfg)[Sections::kPortGrpc].set(Keys::kIp, "127.0.0.1"); + (*cfg)[Sections::kPortGrpc].set(Keys::kPort, "0"); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslCert, getServerCertPath().string()); // Intentionally omit ssl_key try @@ -491,9 +493,9 @@ public: // Create config with only key (missing cert) auto cfg = envconfig(); - (*cfg)[SECTION_PORT_GRPC].set("ip", "127.0.0.1"); - (*cfg)[SECTION_PORT_GRPC].set("port", "0"); - (*cfg)[SECTION_PORT_GRPC].set("ssl_key", getServerKeyPath().string()); + (*cfg)[Sections::kPortGrpc].set(Keys::kIp, "127.0.0.1"); + (*cfg)[Sections::kPortGrpc].set(Keys::kPort, "0"); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslKey, getServerKeyPath().string()); // Intentionally omit ssl_cert try @@ -518,9 +520,9 @@ public: // Test 1: ssl_client_ca specified without any TLS config { auto cfg = envconfig(); - (*cfg)[SECTION_PORT_GRPC].set("ip", "127.0.0.1"); - (*cfg)[SECTION_PORT_GRPC].set("port", "0"); - (*cfg)[SECTION_PORT_GRPC].set("ssl_client_ca", getCACertPath().string()); + (*cfg)[Sections::kPortGrpc].set(Keys::kIp, "127.0.0.1"); + (*cfg)[Sections::kPortGrpc].set(Keys::kPort, "0"); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslClientCa, getCACertPath().string()); // Intentionally omit both ssl_cert and ssl_key try @@ -539,10 +541,10 @@ public: // Test 2: ssl_client_ca with only ssl_cert (missing ssl_key) { auto cfg = envconfig(); - (*cfg)[SECTION_PORT_GRPC].set("ip", "127.0.0.1"); - (*cfg)[SECTION_PORT_GRPC].set("port", "0"); - (*cfg)[SECTION_PORT_GRPC].set("ssl_cert", getServerCertPath().string()); - (*cfg)[SECTION_PORT_GRPC].set("ssl_client_ca", getCACertPath().string()); + (*cfg)[Sections::kPortGrpc].set(Keys::kIp, "127.0.0.1"); + (*cfg)[Sections::kPortGrpc].set(Keys::kPort, "0"); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslCert, getServerCertPath().string()); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslClientCa, getCACertPath().string()); // Intentionally omit ssl_key try @@ -563,10 +565,10 @@ public: // Test 3: ssl_client_ca with only ssl_key (missing ssl_cert) { auto cfg = envconfig(); - (*cfg)[SECTION_PORT_GRPC].set("ip", "127.0.0.1"); - (*cfg)[SECTION_PORT_GRPC].set("port", "0"); - (*cfg)[SECTION_PORT_GRPC].set("ssl_key", getServerKeyPath().string()); - (*cfg)[SECTION_PORT_GRPC].set("ssl_client_ca", getCACertPath().string()); + (*cfg)[Sections::kPortGrpc].set(Keys::kIp, "127.0.0.1"); + (*cfg)[Sections::kPortGrpc].set(Keys::kPort, "0"); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslKey, getServerKeyPath().string()); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslClientCa, getCACertPath().string()); // Intentionally omit ssl_cert try @@ -595,9 +597,9 @@ public: // Test 1: ssl_cert_chain specified without any TLS config { auto cfg = envconfig(); - (*cfg)[SECTION_PORT_GRPC].set("ip", "127.0.0.1"); - (*cfg)[SECTION_PORT_GRPC].set("port", "0"); - (*cfg)[SECTION_PORT_GRPC].set("ssl_cert_chain", getCACertPath().string()); + (*cfg)[Sections::kPortGrpc].set(Keys::kIp, "127.0.0.1"); + (*cfg)[Sections::kPortGrpc].set(Keys::kPort, "0"); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslCertChain, getCACertPath().string()); // Intentionally omit both ssl_cert and ssl_key try @@ -616,10 +618,10 @@ public: // Test 2: ssl_cert_chain with only ssl_cert (missing ssl_key) { auto cfg = envconfig(); - (*cfg)[SECTION_PORT_GRPC].set("ip", "127.0.0.1"); - (*cfg)[SECTION_PORT_GRPC].set("port", "0"); - (*cfg)[SECTION_PORT_GRPC].set("ssl_cert", getServerCertPath().string()); - (*cfg)[SECTION_PORT_GRPC].set("ssl_cert_chain", getCACertPath().string()); + (*cfg)[Sections::kPortGrpc].set(Keys::kIp, "127.0.0.1"); + (*cfg)[Sections::kPortGrpc].set(Keys::kPort, "0"); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslCert, getServerCertPath().string()); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslCertChain, getCACertPath().string()); // Intentionally omit ssl_key try @@ -655,7 +657,8 @@ public: Env env(*this, std::move(cfg)); // Verify the server actually started by checking the port - auto const grpcPort = env.app().config()[SECTION_PORT_GRPC].get("port"); + auto const grpcPort = + env.app().config()[Sections::kPortGrpc].get(Keys::kPort); BEAST_EXPECT(grpcPort.has_value()); // NOLINTBEGIN(bugprone-unchecked-optional-access) grpcPort.has_value() checked above BEAST_EXPECT(*grpcPort > 0); @@ -684,15 +687,16 @@ public: using namespace jtx; auto cfg = envconfig(); - (*cfg)[SECTION_PORT_GRPC].set("ip", "127.0.0.1"); - (*cfg)[SECTION_PORT_GRPC].set("port", "0"); - (*cfg)[SECTION_PORT_GRPC].set("ssl_cert", "/nonexistent/path/to/cert.pem"); - (*cfg)[SECTION_PORT_GRPC].set("ssl_key", getServerKeyPath().string()); + (*cfg)[Sections::kPortGrpc].set(Keys::kIp, "127.0.0.1"); + (*cfg)[Sections::kPortGrpc].set(Keys::kPort, "0"); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslCert, "/nonexistent/path/to/cert.pem"); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslKey, getServerKeyPath().string()); Env env(*this, std::move(cfg)); // Server should fail to start - verify port is 0 - auto const grpcPort = env.app().config()[SECTION_PORT_GRPC].get("port"); + auto const grpcPort = + env.app().config()[Sections::kPortGrpc].get(Keys::kPort); BEAST_EXPECT(grpcPort.has_value()); BEAST_EXPECT(*grpcPort == 0); // NOLINT(bugprone-unchecked-optional-access) } @@ -705,15 +709,16 @@ public: using namespace jtx; auto cfg = envconfig(); - (*cfg)[SECTION_PORT_GRPC].set("ip", "127.0.0.1"); - (*cfg)[SECTION_PORT_GRPC].set("port", "0"); - (*cfg)[SECTION_PORT_GRPC].set("ssl_cert", getServerCertPath().string()); - (*cfg)[SECTION_PORT_GRPC].set("ssl_key", "/nonexistent/path/to/key.pem"); + (*cfg)[Sections::kPortGrpc].set(Keys::kIp, "127.0.0.1"); + (*cfg)[Sections::kPortGrpc].set(Keys::kPort, "0"); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslCert, getServerCertPath().string()); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslKey, "/nonexistent/path/to/key.pem"); Env env(*this, std::move(cfg)); // Server should fail to start - verify port is 0 - auto const grpcPort = env.app().config()[SECTION_PORT_GRPC].get("port"); + auto const grpcPort = + env.app().config()[Sections::kPortGrpc].get(Keys::kPort); BEAST_EXPECT(grpcPort.has_value()); BEAST_EXPECT(*grpcPort == 0); // NOLINT(bugprone-unchecked-optional-access) } @@ -726,16 +731,17 @@ public: using namespace jtx; auto cfg = envconfig(); - (*cfg)[SECTION_PORT_GRPC].set("ip", "127.0.0.1"); - (*cfg)[SECTION_PORT_GRPC].set("port", "0"); - (*cfg)[SECTION_PORT_GRPC].set("ssl_cert", getServerCertPath().string()); - (*cfg)[SECTION_PORT_GRPC].set("ssl_key", getServerKeyPath().string()); - (*cfg)[SECTION_PORT_GRPC].set("ssl_cert_chain", "/nonexistent/path/to/chain.pem"); + (*cfg)[Sections::kPortGrpc].set(Keys::kIp, "127.0.0.1"); + (*cfg)[Sections::kPortGrpc].set(Keys::kPort, "0"); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslCert, getServerCertPath().string()); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslKey, getServerKeyPath().string()); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslCertChain, "/nonexistent/path/to/chain.pem"); Env env(*this, std::move(cfg)); // Server should fail to start - verify port is 0 - auto const grpcPort = env.app().config()[SECTION_PORT_GRPC].get("port"); + auto const grpcPort = + env.app().config()[Sections::kPortGrpc].get(Keys::kPort); BEAST_EXPECT(grpcPort.has_value()); BEAST_EXPECT(*grpcPort == 0); // NOLINT(bugprone-unchecked-optional-access) } @@ -748,16 +754,17 @@ public: using namespace jtx; auto cfg = envconfig(); - (*cfg)[SECTION_PORT_GRPC].set("ip", "127.0.0.1"); - (*cfg)[SECTION_PORT_GRPC].set("port", "0"); - (*cfg)[SECTION_PORT_GRPC].set("ssl_cert", getServerCertPath().string()); - (*cfg)[SECTION_PORT_GRPC].set("ssl_key", getServerKeyPath().string()); - (*cfg)[SECTION_PORT_GRPC].set("ssl_client_ca", "/nonexistent/path/to/ca.pem"); + (*cfg)[Sections::kPortGrpc].set(Keys::kIp, "127.0.0.1"); + (*cfg)[Sections::kPortGrpc].set(Keys::kPort, "0"); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslCert, getServerCertPath().string()); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslKey, getServerKeyPath().string()); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslClientCa, "/nonexistent/path/to/ca.pem"); Env env(*this, std::move(cfg)); // Server should fail to start - verify port is 0 - auto const grpcPort = env.app().config()[SECTION_PORT_GRPC].get("port"); + auto const grpcPort = + env.app().config()[Sections::kPortGrpc].get(Keys::kPort); BEAST_EXPECT(grpcPort.has_value()); BEAST_EXPECT(*grpcPort == 0); // NOLINT(bugprone-unchecked-optional-access) } @@ -775,16 +782,17 @@ public: emptyFile.close(); auto cfg = envconfig(); - (*cfg)[SECTION_PORT_GRPC].set("ip", "127.0.0.1"); - (*cfg)[SECTION_PORT_GRPC].set("port", "0"); - (*cfg)[SECTION_PORT_GRPC].set("ssl_cert", getServerCertPath().string()); - (*cfg)[SECTION_PORT_GRPC].set("ssl_key", getServerKeyPath().string()); - (*cfg)[SECTION_PORT_GRPC].set("ssl_client_ca", emptyCAPath.string()); + (*cfg)[Sections::kPortGrpc].set(Keys::kIp, "127.0.0.1"); + (*cfg)[Sections::kPortGrpc].set(Keys::kPort, "0"); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslCert, getServerCertPath().string()); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslKey, getServerKeyPath().string()); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslClientCa, emptyCAPath.string()); Env env(*this, std::move(cfg)); // Server should fail to start due to empty CA file - auto const grpcPort = env.app().config()[SECTION_PORT_GRPC].get("port"); + auto const grpcPort = + env.app().config()[Sections::kPortGrpc].get(Keys::kPort); BEAST_EXPECT(grpcPort.has_value()); BEAST_EXPECT(*grpcPort == 0); // NOLINT(bugprone-unchecked-optional-access) } @@ -798,18 +806,19 @@ public: // Test with all TLS features enabled: cert, key, cert_chain, and client_ca auto cfg = envconfig(); - (*cfg)[SECTION_PORT_GRPC].set("ip", getEnvLocalhostAddr()); - (*cfg)[SECTION_PORT_GRPC].set("port", "0"); - (*cfg)[SECTION_PORT_GRPC].set("ssl_cert", getServerCertPath().string()); - (*cfg)[SECTION_PORT_GRPC].set("ssl_key", getServerKeyPath().string()); - (*cfg)[SECTION_PORT_GRPC].set( - "ssl_cert_chain", getCACertPath().string()); // Using CA as intermediate - (*cfg)[SECTION_PORT_GRPC].set("ssl_client_ca", getCACertPath().string()); + (*cfg)[Sections::kPortGrpc].set(Keys::kIp, getEnvLocalhostAddr()); + (*cfg)[Sections::kPortGrpc].set(Keys::kPort, "0"); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslCert, getServerCertPath().string()); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslKey, getServerKeyPath().string()); + (*cfg)[Sections::kPortGrpc].set( + Keys::kSslCertChain, getCACertPath().string()); // Using CA as intermediate + (*cfg)[Sections::kPortGrpc].set(Keys::kSslClientCa, getCACertPath().string()); Env env(*this, std::move(cfg)); // Verify the server started successfully - auto const grpcPort = env.app().config()[SECTION_PORT_GRPC].get("port"); + auto const grpcPort = + env.app().config()[Sections::kPortGrpc].get(Keys::kPort); BEAST_EXPECT(grpcPort.has_value()); // NOLINTBEGIN(bugprone-unchecked-optional-access) grpcPort.has_value() checked above BEAST_EXPECT(*grpcPort > 0); diff --git a/src/test/app/HashRouter_test.cpp b/src/test/app/HashRouter_test.cpp index 8f9cae351e..0266da2bc0 100644 --- a/src/test/app/HashRouter_test.cpp +++ b/src/test/app/HashRouter_test.cpp @@ -3,6 +3,7 @@ #include #include +#include #include #include @@ -274,9 +275,9 @@ class HashRouter_test : public beast::unit_test::Suite { Config cfg; // non-default - auto& h = cfg.section("hashrouter"); - h.set("hold_time", "600"); - h.set("relay_time", "15"); + auto& h = cfg.section(Sections::kHashrouter); + h.set(Keys::kHoldTime, "600"); + h.set(Keys::kRelayTime, "15"); auto const setup = setupHashRouter(cfg); BEAST_EXPECT(setup.holdTime == 600s); BEAST_EXPECT(setup.relayTime == 15s); @@ -284,9 +285,9 @@ class HashRouter_test : public beast::unit_test::Suite { Config cfg; // equal - auto& h = cfg.section("hashrouter"); - h.set("hold_time", "400"); - h.set("relay_time", "400"); + auto& h = cfg.section(Sections::kHashrouter); + h.set(Keys::kHoldTime, "400"); + h.set(Keys::kRelayTime, "400"); auto const setup = setupHashRouter(cfg); BEAST_EXPECT(setup.holdTime == 400s); BEAST_EXPECT(setup.relayTime == 400s); @@ -294,9 +295,9 @@ class HashRouter_test : public beast::unit_test::Suite { Config cfg; // wrong order - auto& h = cfg.section("hashrouter"); - h.set("hold_time", "60"); - h.set("relay_time", "120"); + auto& h = cfg.section(Sections::kHashrouter); + h.set(Keys::kHoldTime, "60"); + h.set(Keys::kRelayTime, "120"); try { setupHashRouter(cfg); @@ -313,9 +314,9 @@ class HashRouter_test : public beast::unit_test::Suite { Config cfg; // too small hold - auto& h = cfg.section("hashrouter"); - h.set("hold_time", "10"); - h.set("relay_time", "120"); + auto& h = cfg.section(Sections::kHashrouter); + h.set(Keys::kHoldTime, "10"); + h.set(Keys::kRelayTime, "120"); try { setupHashRouter(cfg); @@ -333,9 +334,9 @@ class HashRouter_test : public beast::unit_test::Suite { Config cfg; // too small relay - auto& h = cfg.section("hashrouter"); - h.set("hold_time", "500"); - h.set("relay_time", "6"); + auto& h = cfg.section(Sections::kHashrouter); + h.set(Keys::kHoldTime, "500"); + h.set(Keys::kRelayTime, "6"); try { setupHashRouter(cfg); @@ -352,9 +353,9 @@ class HashRouter_test : public beast::unit_test::Suite { Config cfg; // garbage - auto& h = cfg.section("hashrouter"); - h.set("hold_time", "alice"); - h.set("relay_time", "bob"); + auto& h = cfg.section(Sections::kHashrouter); + h.set(Keys::kHoldTime, "alice"); + h.set(Keys::kRelayTime, "bob"); auto const setup = setupHashRouter(cfg); // The set function ignores values that don't convert, so the // defaults are left unchanged diff --git a/src/test/app/Manifest_test.cpp b/src/test/app/Manifest_test.cpp index d559ecd7b5..0cf1155cf5 100644 --- a/src/test/app/Manifest_test.cpp +++ b/src/test/app/Manifest_test.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -246,7 +247,7 @@ public: auto& app = env.app(); auto unl = std::make_unique( - m, m, env.timeKeeper(), app.config().legacy("database_path"), env.journal); + m, m, env.timeKeeper(), app.config().legacy(Sections::kDatabasePath), env.journal); { // save should not store untrusted master keys to db diff --git a/src/test/app/MultiSign_test.cpp b/src/test/app/MultiSign_test.cpp index f21611df0e..5092cafef9 100644 --- a/src/test/app/MultiSign_test.cpp +++ b/src/test/app/MultiSign_test.cpp @@ -24,11 +24,11 @@ #include #include -#include #include #include #include +#include #include #include #include @@ -496,7 +496,7 @@ public: Env env( *this, envconfig([](std::unique_ptr cfg) { - cfg->loadFromString("[" SECTION_SIGNING_SUPPORT "]\ntrue"); + cfg->loadFromString(std::string("[") + Sections::kSigningSupport + "]\ntrue"); return cfg; }), features); @@ -1308,7 +1308,7 @@ public: Env env( *this, envconfig([](std::unique_ptr cfg) { - cfg->loadFromString("[" SECTION_SIGNING_SUPPORT "]\ntrue"); + cfg->loadFromString(std::string("[") + Sections::kSigningSupport + "]\ntrue"); return cfg; }), features); diff --git a/src/test/app/Regression_test.cpp b/src/test/app/Regression_test.cpp index 1c83e97e61..6ebde20176 100644 --- a/src/test/app/Regression_test.cpp +++ b/src/test/app/Regression_test.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -193,7 +194,7 @@ struct Regression_test : public beast::unit_test::Suite testcase("Autofilled fee should use the escalated fee"); using namespace jtx; Env env(*this, envconfig([](std::unique_ptr cfg) { - cfg->section("transaction_queue").set("minimum_txn_in_ledger_standalone", "3"); + cfg->section(Sections::kTransactionQueue).set(Keys::kMinimumTxnInLedgerStandalone, "3"); cfg->fees.referenceFee = 10; return cfg; })); @@ -233,11 +234,11 @@ struct Regression_test : public beast::unit_test::Suite using namespace std::chrono_literals; Env env(*this, envconfig([](std::unique_ptr cfg) { - auto& s = cfg->section("transaction_queue"); - s.set("minimum_txn_in_ledger_standalone", "4294967295"); - s.set("minimum_txn_in_ledger", "4294967295"); - s.set("target_txn_in_ledger", "4294967295"); - s.set("normal_consensus_increase_percent", "4294967295"); + auto& s = cfg->section(Sections::kTransactionQueue); + s.set(Keys::kMinimumTxnInLedgerStandalone, "4294967295"); + s.set(Keys::kMinimumTxnInLedger, "4294967295"); + s.set(Keys::kTargetTxnInLedger, "4294967295"); + s.set(Keys::kNormalConsensusIncreasePercent, "4294967295"); return cfg; })); diff --git a/src/test/app/SHAMapStore_test.cpp b/src/test/app/SHAMapStore_test.cpp index 6e279eadb2..7a149b2f64 100644 --- a/src/test/app/SHAMapStore_test.cpp +++ b/src/test/app/SHAMapStore_test.cpp @@ -7,11 +7,12 @@ #include #include #include -#include #include #include #include +#include +#include #include #include #include @@ -42,8 +43,8 @@ class SHAMapStore_test : public beast::unit_test::Suite onlineDelete(std::unique_ptr cfg) { cfg->ledgerHistory = kDeleteInterval; - auto& section = cfg->section(ConfigSection::nodeDatabase()); - section.set("online_delete", std::to_string(kDeleteInterval)); + auto& section = cfg->section(Sections::kNodeDatabase); + section.set(Keys::kOnlineDelete, std::to_string(kDeleteInterval)); return cfg; } @@ -51,7 +52,7 @@ class SHAMapStore_test : public beast::unit_test::Suite advisoryDelete(std::unique_ptr cfg) { cfg = onlineDelete(std::move(cfg)); - cfg->section(ConfigSection::nodeDatabase()).set("advisory_delete", "1"); + cfg->section(Sections::kNodeDatabase).set(Keys::kAdvisoryDelete, "1"); return cfg; } @@ -490,13 +491,13 @@ public: std::unique_ptr makeBackendRotating(jtx::Env& env, NodeStoreScheduler& scheduler, std::string path) { - Section section{env.app().config().section(ConfigSection::nodeDatabase())}; + Section section{env.app().config().section(Sections::kNodeDatabase)}; boost::filesystem::path newPath; if (!BEAST_EXPECT(path.size())) return {}; newPath = path; - section.set("path", newPath.string()); + section.set(Keys::kPath, newPath.string()); auto backend{NodeStore::Manager::instance().makeBackend( section, @@ -520,21 +521,21 @@ public: ///////////////////////////////////////////////////////////// // Create NodeStore with two backends to allow online deletion of data. // Normally, SHAMapStoreImp handles all these details. - auto nscfg = env.app().config().section(ConfigSection::nodeDatabase()); + auto nscfg = env.app().config().section(Sections::kNodeDatabase); // Provide default values. - if (!nscfg.exists("cache_size")) + if (!nscfg.exists(Keys::kCacheSize)) { nscfg.set( - "cache_size", + Keys::kCacheSize, std::to_string( env.app().config().getValueFor(SizedItem::TreeCacheSize, std::nullopt))); } - if (!nscfg.exists("cache_age")) + if (!nscfg.exists(Keys::kCacheAge)) { nscfg.set( - "cache_age", + Keys::kCacheAge, std::to_string( env.app().config().getValueFor(SizedItem::TreeCacheAge, std::nullopt))); } diff --git a/src/test/app/TxQ_test.cpp b/src/test/app/TxQ_test.cpp index dc28388de4..0ae6b4d80a 100644 --- a/src/test/app/TxQ_test.cpp +++ b/src/test/app/TxQ_test.cpp @@ -29,6 +29,7 @@ #include #include +#include #include #include #include @@ -167,7 +168,7 @@ public: using namespace std::chrono; testcase("queue sequence"); - Env env(*this, makeConfig({{"minimum_txn_in_ledger_standalone", "3"}})); + Env env(*this, makeConfig({{Keys::kMinimumTxnInLedgerStandalone, "3"}})); auto alice = Account("alice"); auto bob = Account("bob"); @@ -380,7 +381,7 @@ public: using namespace jtx; testcase("queue ticket"); - Env env(*this, makeConfig({{"minimum_txn_in_ledger_standalone", "3"}})); + Env env(*this, makeConfig({{Keys::kMinimumTxnInLedgerStandalone, "3"}})); auto alice = Account("alice"); @@ -618,7 +619,7 @@ public: using namespace jtx; testcase("queue tec"); - Env env(*this, makeConfig({{"minimum_txn_in_ledger_standalone", "2"}})); + Env env(*this, makeConfig({{Keys::kMinimumTxnInLedgerStandalone, "2"}})); auto alice = Account("alice"); auto gw = Account("gw"); @@ -655,7 +656,7 @@ public: using namespace std::chrono; testcase("local tx retry"); - Env env(*this, makeConfig({{"minimum_txn_in_ledger_standalone", "2"}})); + Env env(*this, makeConfig({{Keys::kMinimumTxnInLedgerStandalone, "2"}})); auto alice = Account("alice"); auto bob = Account("bob"); @@ -708,7 +709,7 @@ public: using namespace std::chrono; testcase("last ledger sequence"); - Env env(*this, makeConfig({{"minimum_txn_in_ledger_standalone", "2"}})); + Env env(*this, makeConfig({{Keys::kMinimumTxnInLedgerStandalone, "2"}})); auto alice = Account("alice"); auto bob = Account("bob"); @@ -830,7 +831,7 @@ public: using namespace std::chrono; testcase("zero transaction fee"); - Env env(*this, makeConfig({{"minimum_txn_in_ledger_standalone", "2"}})); + Env env(*this, makeConfig({{Keys::kMinimumTxnInLedgerStandalone, "2"}})); auto alice = Account("alice"); auto bob = Account("bob"); @@ -957,7 +958,7 @@ public: using namespace jtx; testcase("queued tx fails"); - Env env(*this, makeConfig({{"minimum_txn_in_ledger_standalone", "2"}})); + Env env(*this, makeConfig({{Keys::kMinimumTxnInLedgerStandalone, "2"}})); auto alice = Account("alice"); auto bob = Account("bob"); @@ -1009,8 +1010,8 @@ public: Env env( *this, makeConfig( - {{"minimum_txn_in_ledger_standalone", "3"}}, - {{"account_reserve", "200"}, {"owner_reserve", "50"}})); + {{Keys::kMinimumTxnInLedgerStandalone, "3"}}, + {{Keys::kAccountReserve, "200"}, {Keys::kOwnerReserve, "50"}})); auto alice = Account("alice"); auto bob = Account("bob"); @@ -1258,7 +1259,7 @@ public: using namespace std::chrono; testcase("tie breaking"); - auto cfg = makeConfig({{"minimum_txn_in_ledger_standalone", "4"}}); + auto cfg = makeConfig({{Keys::kMinimumTxnInLedgerStandalone, "4"}}); cfg->fees.referenceFee = 10; Env env(*this, std::move(cfg)); @@ -1471,7 +1472,7 @@ public: using namespace jtx; testcase("acct tx id"); - Env env(*this, makeConfig({{"minimum_txn_in_ledger_standalone", "1"}})); + Env env(*this, makeConfig({{Keys::kMinimumTxnInLedgerStandalone, "1"}})); auto alice = Account("alice"); @@ -1511,10 +1512,10 @@ public: Env env( *this, makeConfig( - {{"minimum_txn_in_ledger_standalone", "2"}, - {"minimum_txn_in_ledger", "5"}, - {"target_txn_in_ledger", "4"}, - {"maximum_txn_in_ledger", "5"}})); + {{Keys::kMinimumTxnInLedgerStandalone, "2"}, + {Keys::kMinimumTxnInLedger, "5"}, + {Keys::kTargetTxnInLedger, "4"}, + {Keys::kMaximumTxnInLedger, "5"}})); auto const baseFee = env.current()->fees().base.drops(); auto alice = Account("alice"); @@ -1555,10 +1556,10 @@ public: Env const env( *this, makeConfig( - {{"minimum_txn_in_ledger", "200"}, - {"minimum_txn_in_ledger_standalone", "200"}, - {"target_txn_in_ledger", "4"}, - {"maximum_txn_in_ledger", "5"}})); + {{Keys::kMinimumTxnInLedger, "200"}, + {Keys::kMinimumTxnInLedgerStandalone, "200"}, + {Keys::kTargetTxnInLedger, "4"}, + {Keys::kMaximumTxnInLedger, "5"}})); // should throw fail(); } @@ -1576,10 +1577,10 @@ public: Env const env( *this, makeConfig( - {{"minimum_txn_in_ledger", "200"}, - {"minimum_txn_in_ledger_standalone", "2"}, - {"target_txn_in_ledger", "4"}, - {"maximum_txn_in_ledger", "5"}})); + {{Keys::kMinimumTxnInLedger, "200"}, + {Keys::kMinimumTxnInLedgerStandalone, "2"}, + {Keys::kTargetTxnInLedger, "4"}, + {Keys::kMaximumTxnInLedger, "5"}})); // should throw fail(); } @@ -1597,10 +1598,10 @@ public: Env const env( *this, makeConfig( - {{"minimum_txn_in_ledger", "2"}, - {"minimum_txn_in_ledger_standalone", "200"}, - {"target_txn_in_ledger", "4"}, - {"maximum_txn_in_ledger", "5"}})); + {{Keys::kMinimumTxnInLedger, "2"}, + {Keys::kMinimumTxnInLedgerStandalone, "200"}, + {Keys::kTargetTxnInLedger, "4"}, + {Keys::kMaximumTxnInLedger, "5"}})); // should throw fail(); } @@ -1624,8 +1625,8 @@ public: Env env( *this, makeConfig( - {{"minimum_txn_in_ledger_standalone", "3"}}, - {{"account_reserve", "200"}, {"owner_reserve", "50"}})); + {{Keys::kMinimumTxnInLedgerStandalone, "3"}}, + {{Keys::kAccountReserve, "200"}, {Keys::kOwnerReserve, "50"}})); auto alice = Account("alice"); auto bob = Account("bob"); @@ -1716,7 +1717,7 @@ public: auto queued = Ter(terQUEUED); - Env env(*this, makeConfig({{"minimum_txn_in_ledger_standalone", "3"}})); + Env env(*this, makeConfig({{Keys::kMinimumTxnInLedgerStandalone, "3"}})); auto const baseFee = env.current()->fees().base.drops(); checkMetrics(*this, env, 0, std::nullopt, 0, 3); @@ -1845,7 +1846,7 @@ public: auto queued = Ter(terQUEUED); - Env env(*this, makeConfig({{"minimum_txn_in_ledger_standalone", "3"}})); + Env env(*this, makeConfig({{Keys::kMinimumTxnInLedgerStandalone, "3"}})); auto const baseFee = env.current()->fees().base.drops(); checkMetrics(*this, env, 0, std::nullopt, 0, 3); @@ -1996,8 +1997,8 @@ public: Env env( *this, makeConfig( - {{"minimum_txn_in_ledger_standalone", "3"}}, - {{"account_reserve", "200"}, {"owner_reserve", "50"}})); + {{Keys::kMinimumTxnInLedgerStandalone, "3"}}, + {{Keys::kAccountReserve, "200"}, {Keys::kOwnerReserve, "50"}})); auto alice = Account("alice"); auto charlie = Account("charlie"); @@ -2399,7 +2400,7 @@ public: auto queued = Ter(terQUEUED); - Env env(*this, makeConfig({{"minimum_txn_in_ledger_standalone", "3"}})); + Env env(*this, makeConfig({{Keys::kMinimumTxnInLedgerStandalone, "3"}})); auto const baseFee = env.current()->fees().base.drops(); checkMetrics(*this, env, 0, std::nullopt, 0, 3); @@ -2568,9 +2569,9 @@ public: Env env( *this, makeConfig( - {{"minimum_txn_in_ledger_standalone", "1"}, - {"ledgers_in_queue", "10"}, - {"maximum_txn_per_account", "20"}})); + {{Keys::kMinimumTxnInLedgerStandalone, "1"}, + {Keys::kLedgersInQueue, "10"}, + {Keys::kMaximumTxnPerAccount, "20"}})); auto const baseFee = env.current()->fees().base.drops(); @@ -2650,9 +2651,9 @@ public: testcase("full queue gap handling"); auto cfg = makeConfig( - {{"minimum_txn_in_ledger_standalone", "1"}, - {"ledgers_in_queue", "10"}, - {"maximum_txn_per_account", "11"}}); + {{Keys::kMinimumTxnInLedgerStandalone, "1"}, + {Keys::kLedgersInQueue, "10"}, + {Keys::kMaximumTxnPerAccount, "11"}}); cfg->fees.referenceFee = 10; Env env(*this, std::move(cfg)); @@ -2777,7 +2778,7 @@ public: { testcase("Autofilled sequence should account for TxQ"); using namespace jtx; - Env env(*this, makeConfig({{"minimum_txn_in_ledger_standalone", "6"}})); + Env env(*this, makeConfig({{Keys::kMinimumTxnInLedgerStandalone, "6"}})); auto const baseFee = env.current()->fees().base.drops(); EnvSs envs(env); auto const& txQ = env.app().getTxQ(); @@ -2911,7 +2912,7 @@ public: using namespace jtx; testcase("account info"); - Env env(*this, makeConfig({{"minimum_txn_in_ledger_standalone", "3"}})); + Env env(*this, makeConfig({{Keys::kMinimumTxnInLedgerStandalone, "3"}})); auto const baseFee = env.current()->fees().base.drops(); EnvSs envs(env); @@ -3181,7 +3182,7 @@ public: using namespace jtx; testcase("server info"); - Env env(*this, makeConfig({{"minimum_txn_in_ledger_standalone", "3"}})); + Env env(*this, makeConfig({{Keys::kMinimumTxnInLedgerStandalone, "3"}})); auto const baseFee = env.current()->fees().base.drops(); EnvSs envs(env); @@ -3407,7 +3408,7 @@ public: using namespace jtx; testcase("server subscribe"); - Env env(*this, makeConfig({{"minimum_txn_in_ledger_standalone", "3"}})); + Env env(*this, makeConfig({{Keys::kMinimumTxnInLedgerStandalone, "3"}})); auto const baseFee = env.current()->fees().base.drops(); json::Value stream; @@ -3546,7 +3547,7 @@ public: using namespace jtx; testcase("clear queued acct txs"); - Env env(*this, makeConfig({{"minimum_txn_in_ledger_standalone", "3"}})); + Env env(*this, makeConfig({{Keys::kMinimumTxnInLedgerStandalone, "3"}})); auto const baseFee = env.current()->fees().base.drops(); auto alice = Account("alice"); auto bob = Account("bob"); @@ -3756,11 +3757,11 @@ public: Env env( *this, makeConfig( - {{"minimum_txn_in_ledger_standalone", "3"}, - {"normal_consensus_increase_percent", "25"}, - {"slow_consensus_decrease_percent", "50"}, - {"target_txn_in_ledger", "10"}, - {"maximum_txn_per_account", "200"}})); + {{Keys::kMinimumTxnInLedgerStandalone, "3"}, + {Keys::kNormalConsensusIncreasePercent, "25"}, + {Keys::kSlowConsensusDecreasePercent, "50"}, + {Keys::kTargetTxnInLedger, "10"}, + {Keys::kMaximumTxnPerAccount, "200"}})); auto alice = Account("alice"); checkMetrics(*this, env, 0, std::nullopt, 0, 3); @@ -3842,11 +3843,11 @@ public: Env env( *this, makeConfig( - {{"minimum_txn_in_ledger_standalone", "3"}, - {"normal_consensus_increase_percent", "150"}, - {"slow_consensus_decrease_percent", "150"}, - {"target_txn_in_ledger", "10"}, - {"maximum_txn_per_account", "200"}})); + {{Keys::kMinimumTxnInLedgerStandalone, "3"}, + {Keys::kNormalConsensusIncreasePercent, "150"}, + {Keys::kSlowConsensusDecreasePercent, "150"}, + {Keys::kTargetTxnInLedger, "10"}, + {Keys::kMaximumTxnPerAccount, "200"}})); auto alice = Account("alice"); checkMetrics(*this, env, 0, std::nullopt, 0, 3); @@ -3899,7 +3900,7 @@ public: testcase("Sequence in queue and open ledger"); using namespace jtx; - Env env(*this, makeConfig({{"minimum_txn_in_ledger_standalone", "3"}})); + Env env(*this, makeConfig({{Keys::kMinimumTxnInLedgerStandalone, "3"}})); auto const alice = Account("alice"); @@ -3962,7 +3963,7 @@ public: testcase("Ticket in queue and open ledger"); using namespace jtx; - Env env(*this, makeConfig({{"minimum_txn_in_ledger_standalone", "3"}})); + Env env(*this, makeConfig({{Keys::kMinimumTxnInLedgerStandalone, "3"}})); auto alice = Account("alice"); @@ -4063,15 +4064,16 @@ public: static constexpr int kLedgersInQueue = 30; auto cfg = makeConfig( - {{"minimum_txn_in_ledger_standalone", "1"}, - {"ledgers_in_queue", std::to_string(kLedgersInQueue)}, - {"maximum_txn_per_account", "10"}}, - {{"account_reserve", "1000"}, {"owner_reserve", "50"}}); + {{Keys::kMinimumTxnInLedgerStandalone, "1"}, + {Keys::kLedgersInQueue, std::to_string(kLedgersInQueue)}, + {Keys::kMaximumTxnPerAccount, "10"}}, + {{Keys::kAccountReserve, "1000"}, {Keys::kOwnerReserve, "50"}}); - auto& votingSection = cfg->section("voting"); - votingSection.set("account_reserve", std::to_string(cfg->fees.referenceFee.drops() * 100)); + auto& votingSection = cfg->section(Sections::kVoting); + votingSection.set( + Keys::kAccountReserve, std::to_string(cfg->fees.referenceFee.drops() * 100)); - votingSection.set("reference_fee", std::to_string(cfg->fees.referenceFee.drops())); + votingSection.set(Keys::kReferenceFee, std::to_string(cfg->fees.referenceFee.drops())); Env env(*this, std::move(cfg)); @@ -4228,10 +4230,10 @@ public: Account const fiona("fiona"); auto cfg = makeConfig( - {{"minimum_txn_in_ledger_standalone", "5"}, - {"ledgers_in_queue", "5"}, - {"maximum_txn_per_account", "30"}, - {"minimum_queue_size", "50"}}); + {{Keys::kMinimumTxnInLedgerStandalone, "5"}, + {Keys::kLedgersInQueue, "5"}, + {Keys::kMaximumTxnPerAccount, "30"}, + {Keys::kMinimumQueueSize, "50"}}); Env env(*this, std::move(cfg)); auto const baseFee = env.current()->fees().base.drops(); @@ -4437,10 +4439,10 @@ public: auto usd = gw["USD"]; auto cfg = makeConfig( - {{"minimum_txn_in_ledger_standalone", "5"}, - {"ledgers_in_queue", "5"}, - {"maximum_txn_per_account", "30"}, - {"minimum_queue_size", "50"}}); + {{Keys::kMinimumTxnInLedgerStandalone, "5"}, + {Keys::kLedgersInQueue, "5"}, + {Keys::kMaximumTxnPerAccount, "30"}, + {Keys::kMinimumQueueSize, "50"}}); Env env(*this, std::move(cfg)); @@ -4537,8 +4539,10 @@ public: Env env( *this, makeConfig( - {{"minimum_txn_in_ledger_standalone", "3"}}, - {{"reference_fee", "0"}, {"account_reserve", "0"}, {"owner_reserve", "0"}})); + {{Keys::kMinimumTxnInLedgerStandalone, "3"}}, + {{Keys::kReferenceFee, "0"}, + {Keys::kAccountReserve, "0"}, + {Keys::kOwnerReserve, "0"}})); checkMetrics(*this, env, 0, std::nullopt, 0, 3); diff --git a/src/test/app/ValidatorKeys_test.cpp b/src/test/app/ValidatorKeys_test.cpp index 83267bf0a7..ca0e76c0b3 100644 --- a/src/test/app/ValidatorKeys_test.cpp +++ b/src/test/app/ValidatorKeys_test.cpp @@ -4,11 +4,11 @@ #include #include -#include #include #include #include +#include #include #include #include @@ -100,7 +100,7 @@ public: { // validation seed section -> empty manifest and valid seeds Config c; - c.section(SECTION_VALIDATION_SEED).append(seed_); + c.section(Sections::kValidationSeed).append(seed_); ValidatorKeys k{c, journal}; if (BEAST_EXPECT(k.keys); k.keys.has_value()) @@ -116,7 +116,7 @@ public: { // validation seed bad seed -> invalid Config c; - c.section(SECTION_VALIDATION_SEED).append("badseed"); + c.section(Sections::kValidationSeed).append("badseed"); ValidatorKeys const k{c, journal}; BEAST_EXPECT(k.configInvalid()); @@ -127,7 +127,7 @@ public: { // validator token Config c; - c.section(SECTION_VALIDATOR_TOKEN).append(tokenBlob_); + c.section(Sections::kValidatorToken).append(tokenBlob_); ValidatorKeys k{c, journal}; if (BEAST_EXPECT(k.keys); k.keys.has_value()) @@ -142,7 +142,7 @@ public: { // invalid validator token Config c; - c.section(SECTION_VALIDATOR_TOKEN).append("badtoken"); + c.section(Sections::kValidatorToken).append("badtoken"); ValidatorKeys const k{c, journal}; BEAST_EXPECT(k.configInvalid()); BEAST_EXPECT(!k.keys); @@ -152,8 +152,8 @@ public: { // Cannot specify both Config c; - c.section(SECTION_VALIDATION_SEED).append(seed_); - c.section(SECTION_VALIDATOR_TOKEN).append(tokenBlob_); + c.section(Sections::kValidationSeed).append(seed_); + c.section(Sections::kValidatorToken).append(tokenBlob_); ValidatorKeys const k{c, journal}; BEAST_EXPECT(k.configInvalid()); @@ -164,7 +164,7 @@ public: { // Token manifest and private key must match Config c; - c.section(SECTION_VALIDATOR_TOKEN).append(invalidTokenBlob_); + c.section(Sections::kValidatorToken).append(invalidTokenBlob_); ValidatorKeys const k{c, journal}; BEAST_EXPECT(k.configInvalid()); diff --git a/src/test/app/ValidatorList_test.cpp b/src/test/app/ValidatorList_test.cpp index 80483446a2..d71554f714 100644 --- a/src/test/app/ValidatorList_test.cpp +++ b/src/test/app/ValidatorList_test.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -198,7 +199,7 @@ private: manifests, manifests, env.timeKeeper(), - app.config().legacy("database_path"), + app.config().legacy(Sections::kDatabasePath), env.journal); BEAST_EXPECT(trustedKeys->quorum() == 1); } @@ -208,7 +209,7 @@ private: manifests, manifests, env.timeKeeper(), - app.config().legacy("database_path"), + app.config().legacy(Sections::kDatabasePath), env.journal, minQuorum); BEAST_EXPECT(trustedKeys->quorum() == minQuorum); @@ -266,7 +267,7 @@ private: manifests, manifests, env.timeKeeper(), - app.config().legacy("database_path"), + app.config().legacy(Sections::kDatabasePath), env.journal); // Correct (empty) configuration @@ -292,7 +293,7 @@ private: manifests, manifests, env.timeKeeper(), - app.config().legacy("database_path"), + app.config().legacy(Sections::kDatabasePath), env.journal); BEAST_EXPECT(trustedKeys->load({}, cfgKeys, emptyCfgPublishers)); @@ -327,7 +328,7 @@ private: manifests, manifests, env.timeKeeper(), - app.config().legacy("database_path"), + app.config().legacy(Sections::kDatabasePath), env.journal); auto const localSigningPublic = @@ -347,7 +348,7 @@ private: manifests, manifests, env.timeKeeper(), - app.config().legacy("database_path"), + app.config().legacy(Sections::kDatabasePath), env.journal); auto const localSigningPublic = randomNode(); @@ -365,7 +366,7 @@ private: manifests, manifests, env.timeKeeper(), - app.config().legacy("database_path"), + app.config().legacy(Sections::kDatabasePath), env.journal); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) @@ -385,7 +386,7 @@ private: manifests, manifests, env.timeKeeper(), - app.config().legacy("database_path"), + app.config().legacy(Sections::kDatabasePath), env.journal); // load should reject invalid validator list signing keys @@ -421,7 +422,7 @@ private: manifests, manifests, env.timeKeeper(), - app.config().legacy("database_path"), + app.config().legacy(Sections::kDatabasePath), env.journal); std::vector const keys( @@ -446,7 +447,7 @@ private: valManifests, pubManifests, env.timeKeeper(), - app.config().legacy("database_path"), + app.config().legacy(Sections::kDatabasePath), env.journal); auto const pubRevokedSecret = randomSecretKey(); @@ -485,7 +486,7 @@ private: valManifests, pubManifests, env.timeKeeper(), - app.config().legacy("database_path"), + app.config().legacy(Sections::kDatabasePath), env.journal); auto const pubRevokedSecret = randomSecretKey(); @@ -571,7 +572,7 @@ private: manifests, manifests, env.app().getTimeKeeper(), - app.config().legacy("database_path"), + app.config().legacy(Sections::kDatabasePath), env.journal); auto expectTrusted = [this, &trustedKeys](std::vector const& list) { @@ -986,7 +987,7 @@ private: manifests, manifests, env.app().getTimeKeeper(), - app.config().legacy("database_path"), + app.config().legacy(Sections::kDatabasePath), env.journal); auto const publisherSecret = randomSecretKey(); @@ -1117,7 +1118,7 @@ private: manifestsOuter, manifestsOuter, env.timeKeeper(), - app.config().legacy("database_path"), + app.config().legacy(Sections::kDatabasePath), env.journal); std::vector const cfgPublishersOuter; @@ -1283,7 +1284,7 @@ private: manifestsOuter, manifestsOuter, env.timeKeeper(), - app.config().legacy("database_path"), + app.config().legacy(Sections::kDatabasePath), env.journal); auto const publisherSecret = randomSecretKey(); auto const publisherPublic = derivePublicKey(KeyType::Ed25519, publisherSecret); @@ -1310,7 +1311,7 @@ private: manifestsOuter, manifestsOuter, env.timeKeeper(), - app.config().legacy("database_path"), + app.config().legacy(Sections::kDatabasePath), env.journal); auto const masterPrivate = randomSecretKey(); auto const masterPublic = derivePublicKey(KeyType::Ed25519, masterPrivate); @@ -1344,7 +1345,7 @@ private: manifests, manifests, env.timeKeeper(), - app.config().legacy("database_path"), + app.config().legacy(Sections::kDatabasePath), env.journal, minQuorum); @@ -1400,7 +1401,7 @@ private: manifestsOuter, manifestsOuter, env.app().getTimeKeeper(), - app.config().legacy("database_path"), + app.config().legacy(Sections::kDatabasePath), env.journal); std::vector const emptyCfgKeys; @@ -1499,7 +1500,7 @@ private: manifestsOuter, manifestsOuter, env.timeKeeper(), - app.config().legacy("database_path"), + app.config().legacy(Sections::kDatabasePath), env.journal); std::vector const cfgPublishers; @@ -1535,7 +1536,7 @@ private: manifestsOuter, manifestsOuter, env.timeKeeper(), - app.config().legacy("database_path"), + app.config().legacy(Sections::kDatabasePath), env.journal); auto const localKey = randomNode(); @@ -1582,7 +1583,7 @@ private: manifests, manifests, env.timeKeeper(), - app.config().legacy("database_path"), + app.config().legacy(Sections::kDatabasePath), env.journal); hash_set activeValidators; @@ -1670,7 +1671,7 @@ private: manifests, manifests, env.timeKeeper(), - app.config().legacy("database_path"), + app.config().legacy(Sections::kDatabasePath), env.journal); hash_set activeValidators; @@ -1877,7 +1878,7 @@ private: manifests, manifests, env.timeKeeper(), - app.config().legacy("database_path"), + app.config().legacy(Sections::kDatabasePath), env.journal); // Empty list has no expiration @@ -1899,7 +1900,7 @@ private: manifests, manifests, env.app().getTimeKeeper(), - app.config().legacy("database_path"), + app.config().legacy(Sections::kDatabasePath), env.journal); std::vector validators = {randomValidator()}; @@ -2040,7 +2041,7 @@ private: manifests, manifests, env.timeKeeper(), - env.app().config().legacy("database_path"), + env.app().config().legacy(Sections::kDatabasePath), env.journal, minimumQuorum); @@ -2636,7 +2637,7 @@ private: valManifests, pubManifests, env.timeKeeper(), - app.config().legacy("database_path"), + app.config().legacy(Sections::kDatabasePath), env.journal); std::vector cfgPublishers; diff --git a/src/test/core/Config_test.cpp b/src/test/core/Config_test.cpp index 92f59fe644..fdac1e450d 100644 --- a/src/test/core/Config_test.cpp +++ b/src/test/core/Config_test.cpp @@ -2,11 +2,11 @@ #include #include -#include -#include #include #include +#include +#include #include // IWYU pragma: keep #include @@ -295,9 +295,9 @@ port_wss_admin c.loadFromString(toLoad); - BEAST_EXPECT(c.legacy("ssl_verify") == "0"); + BEAST_EXPECT(c.legacy(Sections::kSslVerify) == "0"); expectException( - [&c] { [[maybe_unused]] auto _ = c.legacy("server"); }); // not a single line + [&c] { [[maybe_unused]] auto _ = c.legacy(Sections::kServer); }); // not a single line // set a legacy value BEAST_EXPECT(c.legacy("not_in_file").empty()); @@ -329,9 +329,9 @@ port_wss_admin // Load the config file from the current directory and verify it. Config c; c.setup("", true, false, true); - BEAST_EXPECT(c.section(SECTION_DEBUG_LOGFILE).values().size() == 1); + BEAST_EXPECT(c.section(Sections::kDebugLogfile).values().size() == 1); BEAST_EXPECT( - c.section(SECTION_DEBUG_LOGFILE).values()[0] == + c.section(Sections::kDebugLogfile).values()[0] == "/Users/dummy/xrpld/config/log/debug.log"); } @@ -368,9 +368,9 @@ port_wss_admin // Load the config file from the config directory and verify it. Config c; c.setup("", true, false, true); - BEAST_EXPECT(c.section(SECTION_DEBUG_LOGFILE).values().size() == 1); + BEAST_EXPECT(c.section(Sections::kDebugLogfile).values().size() == 1); BEAST_EXPECT( - c.section(SECTION_DEBUG_LOGFILE).values()[0] == + c.section(Sections::kDebugLogfile).values()[0] == "/Users/dummy/xrpld/config/log/debug.log"); // Restore the environment variables. @@ -404,9 +404,9 @@ port_wss_admin // Load the config file from the config directory and verify it. Config c; c.setup("", true, false, true); - BEAST_EXPECT(c.section(SECTION_DEBUG_LOGFILE).values().size() == 1); + BEAST_EXPECT(c.section(Sections::kDebugLogfile).values().size() == 1); BEAST_EXPECT( - c.section(SECTION_DEBUG_LOGFILE).values()[0] == + c.section(Sections::kDebugLogfile).values()[0] == "/Users/dummy/xrpld/config/log/debug.log"); // Restore the environment variables. @@ -436,13 +436,13 @@ port_wss_admin // Dummy test - do we get back what we put in Config c; c.loadFromString(boost::str(cc % dataDirAbs.string())); - BEAST_EXPECT(c.legacy("database_path") == dataDirAbs.string()); + BEAST_EXPECT(c.legacy(Sections::kDatabasePath) == dataDirAbs.string()); } { // Rel paths should convert to abs paths Config c; c.loadFromString(boost::str(cc % dataDirRel.string())); - BEAST_EXPECT(c.legacy("database_path") == dataDirAbs.string()); + BEAST_EXPECT(c.legacy(Sections::kDatabasePath) == dataDirAbs.string()); } { // No db section. @@ -450,7 +450,7 @@ port_wss_admin // load will not. Config c; c.loadFromString(""); - BEAST_EXPECT(c.legacy("database_path").empty()); + BEAST_EXPECT(c.legacy(Sections::kDatabasePath).empty()); } } { @@ -464,7 +464,7 @@ port_wss_admin auto const& c(g.config()); BEAST_EXPECT(g.dataDirExists()); BEAST_EXPECT(g.configFileExists()); - BEAST_EXPECT(c.legacy("database_path") == dataDirAbs.string()); + BEAST_EXPECT(c.legacy(Sections::kDatabasePath) == dataDirAbs.string()); } { // read from file relative path @@ -474,7 +474,7 @@ port_wss_admin std::string const nativeDbPath = absolute(path(dbPath)).string(); BEAST_EXPECT(g.dataDirExists()); BEAST_EXPECT(g.configFileExists()); - BEAST_EXPECT(c.legacy("database_path") == nativeDbPath); + BEAST_EXPECT(c.legacy(Sections::kDatabasePath) == nativeDbPath); } { // read from file no path @@ -484,7 +484,7 @@ port_wss_admin absolute(g.subdir() / path(Config::kDatabaseDirName)).string(); BEAST_EXPECT(g.dataDirExists()); BEAST_EXPECT(g.configFileExists()); - BEAST_EXPECT(c.legacy("database_path") == nativeDbPath); + BEAST_EXPECT(c.legacy(Sections::kDatabasePath) == nativeDbPath); } } @@ -653,8 +653,8 @@ nHUhG1PgAG8H8myUENypM35JgfqXAKNQvRVVAFDRzJrny5eZN8d5 nHBu9PTL9dn2GuZtdW4U2WzBwffyX9qsQCd9CNU4Z5YG3PQfViM8 )xrpldConfig"); c.loadFromString(toLoad); - BEAST_EXPECT(c.legacy("validators_file").empty()); - BEAST_EXPECT(c.section(SECTION_VALIDATORS).values().size() == 5); + BEAST_EXPECT(c.legacy(Sections::kValidatorsFile).empty()); + BEAST_EXPECT(c.section(Sections::kValidators).values().size() == 5); BEAST_EXPECT(c.validatorListThreshold == std::nullopt); } { @@ -672,19 +672,19 @@ trust-these-validators.gov 1 )xrpldConfig"); c.loadFromString(toLoad); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 2); + BEAST_EXPECT(c.section(Sections::kValidatorListSites).values().size() == 2); BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_SITES).values()[0] == "xrpl-validators.com"); + c.section(Sections::kValidatorListSites).values()[0] == "xrpl-validators.com"); BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_SITES).values()[1] == + c.section(Sections::kValidatorListSites).values()[1] == "trust-these-validators.gov"); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 1); + BEAST_EXPECT(c.section(Sections::kValidatorListKeys).values().size() == 1); BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_KEYS).values()[0] == + c.section(Sections::kValidatorListKeys).values()[0] == "021A99A537FDEBC34E4FCA03B39BEADD04299BB19E85097EC92B15A3518801" "E566"); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == 1); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values()[0] == "1"); + BEAST_EXPECT(c.section(Sections::kValidatorListThreshold).values().size() == 1); + BEAST_EXPECT(c.section(Sections::kValidatorListThreshold).values()[0] == "1"); BEAST_EXPECT(c.validatorListThreshold == std::size_t(1)); } { @@ -702,19 +702,19 @@ trust-these-validators.gov 0 )xrpldConfig"); c.loadFromString(toLoad); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 2); + BEAST_EXPECT(c.section(Sections::kValidatorListSites).values().size() == 2); BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_SITES).values()[0] == "xrpl-validators.com"); + c.section(Sections::kValidatorListSites).values()[0] == "xrpl-validators.com"); BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_SITES).values()[1] == + c.section(Sections::kValidatorListSites).values()[1] == "trust-these-validators.gov"); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 1); + BEAST_EXPECT(c.section(Sections::kValidatorListKeys).values().size() == 1); BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_KEYS).values()[0] == + c.section(Sections::kValidatorListKeys).values()[0] == "021A99A537FDEBC34E4FCA03B39BEADD04299BB19E85097EC92B15A3518801" "E566"); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == 1); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values()[0] == "0"); + BEAST_EXPECT(c.section(Sections::kValidatorListThreshold).values().size() == 1); + BEAST_EXPECT(c.section(Sections::kValidatorListThreshold).values()[0] == "0"); BEAST_EXPECT(c.validatorListThreshold == std::nullopt); } { @@ -831,11 +831,11 @@ trust-these-validators.gov Config c; boost::format cc("[validators_file]\n%1%\n"); c.loadFromString(boost::str(cc % vtg.validatorsFile())); - BEAST_EXPECT(c.legacy("validators_file") == vtg.validatorsFile()); - BEAST_EXPECT(c.section(SECTION_VALIDATORS).values().size() == 8); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 2); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 2); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == 1); + BEAST_EXPECT(c.legacy(Sections::kValidatorsFile) == vtg.validatorsFile()); + BEAST_EXPECT(c.section(Sections::kValidators).values().size() == 8); + BEAST_EXPECT(c.section(Sections::kValidatorListSites).values().size() == 2); + BEAST_EXPECT(c.section(Sections::kValidatorListKeys).values().size() == 2); + BEAST_EXPECT(c.section(Sections::kValidatorListThreshold).values().size() == 1); BEAST_EXPECT(c.validatorListThreshold == 2); } { @@ -848,11 +848,11 @@ trust-these-validators.gov BEAST_EXPECT(vtg.validatorsFileExists()); BEAST_EXPECT(rcg.configFileExists()); auto const& c(rcg.config()); - BEAST_EXPECT(c.legacy("validators_file") == valFileName); - BEAST_EXPECT(c.section(SECTION_VALIDATORS).values().size() == 8); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 2); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 2); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == 1); + BEAST_EXPECT(c.legacy(Sections::kValidatorsFile) == valFileName); + BEAST_EXPECT(c.section(Sections::kValidators).values().size() == 8); + BEAST_EXPECT(c.section(Sections::kValidatorListSites).values().size() == 2); + BEAST_EXPECT(c.section(Sections::kValidatorListKeys).values().size() == 2); + BEAST_EXPECT(c.section(Sections::kValidatorListThreshold).values().size() == 1); BEAST_EXPECT(c.validatorListThreshold == 2); } { @@ -865,11 +865,11 @@ trust-these-validators.gov BEAST_EXPECT(vtg.validatorsFileExists()); BEAST_EXPECT(rcg.configFileExists()); auto const& c(rcg.config()); - BEAST_EXPECT(c.legacy("validators_file") == valFilePath); - BEAST_EXPECT(c.section(SECTION_VALIDATORS).values().size() == 8); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 2); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 2); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == 1); + BEAST_EXPECT(c.legacy(Sections::kValidatorsFile) == valFilePath); + BEAST_EXPECT(c.section(Sections::kValidators).values().size() == 8); + BEAST_EXPECT(c.section(Sections::kValidatorListSites).values().size() == 2); + BEAST_EXPECT(c.section(Sections::kValidatorListKeys).values().size() == 2); + BEAST_EXPECT(c.section(Sections::kValidatorListThreshold).values().size() == 1); BEAST_EXPECT(c.validatorListThreshold == 2); } { @@ -880,11 +880,11 @@ trust-these-validators.gov BEAST_EXPECT(vtg.validatorsFileExists()); BEAST_EXPECT(rcg.configFileExists()); auto const& c(rcg.config()); - BEAST_EXPECT(c.legacy("validators_file").empty()); - BEAST_EXPECT(c.section(SECTION_VALIDATORS).values().size() == 8); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 2); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 2); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == 1); + BEAST_EXPECT(c.legacy(Sections::kValidatorsFile).empty()); + BEAST_EXPECT(c.section(Sections::kValidators).values().size() == 8); + BEAST_EXPECT(c.section(Sections::kValidatorListSites).values().size() == 2); + BEAST_EXPECT(c.section(Sections::kValidatorListKeys).values().size() == 2); + BEAST_EXPECT(c.section(Sections::kValidatorListThreshold).values().size() == 1); BEAST_EXPECT(c.validatorListThreshold == 2); } { @@ -899,11 +899,11 @@ trust-these-validators.gov *this, vtg.subdir(), "", Config::kConfigFileName, vtg.validatorsFile(), false); BEAST_EXPECT(rcg.configFileExists()); auto const& c(rcg.config()); - BEAST_EXPECT(c.legacy("validators_file") == vtg.validatorsFile()); - BEAST_EXPECT(c.section(SECTION_VALIDATORS).values().size() == 8); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 2); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 2); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == 1); + BEAST_EXPECT(c.legacy(Sections::kValidatorsFile) == vtg.validatorsFile()); + BEAST_EXPECT(c.section(Sections::kValidators).values().size() == 8); + BEAST_EXPECT(c.section(Sections::kValidatorListSites).values().size() == 2); + BEAST_EXPECT(c.section(Sections::kValidatorListKeys).values().size() == 2); + BEAST_EXPECT(c.section(Sections::kValidatorListThreshold).values().size() == 1); BEAST_EXPECT(c.validatorListThreshold == 2); } @@ -935,11 +935,11 @@ trust-these-validators.gov BEAST_EXPECT(vtg.validatorsFileExists()); Config c; c.loadFromString(boost::str(cc % vtg.validatorsFile())); - BEAST_EXPECT(c.legacy("validators_file") == vtg.validatorsFile()); - BEAST_EXPECT(c.section(SECTION_VALIDATORS).values().size() == 15); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 4); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 3); - BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == 1); + BEAST_EXPECT(c.legacy(Sections::kValidatorsFile) == vtg.validatorsFile()); + BEAST_EXPECT(c.section(Sections::kValidators).values().size() == 15); + BEAST_EXPECT(c.section(Sections::kValidatorListSites).values().size() == 4); + BEAST_EXPECT(c.section(Sections::kValidatorListKeys).values().size() == 3); + BEAST_EXPECT(c.section(Sections::kValidatorListThreshold).values().size() == 1); BEAST_EXPECT(c.validatorListThreshold == 2); } { @@ -1018,7 +1018,7 @@ trust-these-validators.gov BEAST_EXPECT(!config.silent()); BEAST_EXPECT(!config.standalone()); BEAST_EXPECT(config.ledgerHistory == 256); - BEAST_EXPECT(!config.legacy("database_path").empty()); + BEAST_EXPECT(!config.legacy(Sections::kDatabasePath).empty()); } { Config config; @@ -1031,7 +1031,7 @@ trust-these-validators.gov BEAST_EXPECT(!config.silent()); BEAST_EXPECT(!config.standalone()); BEAST_EXPECT(config.ledgerHistory == 256); - BEAST_EXPECT(!config.legacy("database_path").empty()); + BEAST_EXPECT(!config.legacy(Sections::kDatabasePath).empty()); } { Config config; @@ -1044,7 +1044,7 @@ trust-these-validators.gov BEAST_EXPECT(config.silent()); BEAST_EXPECT(!config.standalone()); BEAST_EXPECT(config.ledgerHistory == 256); - BEAST_EXPECT(!config.legacy("database_path").empty()); + BEAST_EXPECT(!config.legacy(Sections::kDatabasePath).empty()); } { Config config; @@ -1057,7 +1057,7 @@ trust-these-validators.gov BEAST_EXPECT(config.silent()); BEAST_EXPECT(!config.standalone()); BEAST_EXPECT(config.ledgerHistory == 256); - BEAST_EXPECT(!config.legacy("database_path").empty()); + BEAST_EXPECT(!config.legacy(Sections::kDatabasePath).empty()); } { Config config; @@ -1070,7 +1070,7 @@ trust-these-validators.gov BEAST_EXPECT(!config.silent()); BEAST_EXPECT(config.standalone()); BEAST_EXPECT(config.ledgerHistory == 0); - BEAST_EXPECT(config.legacy("database_path").empty() == !explicitPath); + BEAST_EXPECT(config.legacy(Sections::kDatabasePath).empty() == !explicitPath); } { Config config; @@ -1083,7 +1083,7 @@ trust-these-validators.gov BEAST_EXPECT(!config.silent()); BEAST_EXPECT(config.standalone()); BEAST_EXPECT(config.ledgerHistory == 0); - BEAST_EXPECT(config.legacy("database_path").empty() == !explicitPath); + BEAST_EXPECT(config.legacy(Sections::kDatabasePath).empty() == !explicitPath); } { Config config; @@ -1096,7 +1096,7 @@ trust-these-validators.gov BEAST_EXPECT(config.silent()); BEAST_EXPECT(config.standalone()); BEAST_EXPECT(config.ledgerHistory == 0); - BEAST_EXPECT(config.legacy("database_path").empty() == !explicitPath); + BEAST_EXPECT(config.legacy(Sections::kDatabasePath).empty() == !explicitPath); } { Config config; @@ -1109,7 +1109,7 @@ trust-these-validators.gov BEAST_EXPECT(config.silent()); BEAST_EXPECT(config.standalone()); BEAST_EXPECT(config.ledgerHistory == 0); - BEAST_EXPECT(config.legacy("database_path").empty() == !explicitPath); + BEAST_EXPECT(config.legacy(Sections::kDatabasePath).empty() == !explicitPath); } } @@ -1118,16 +1118,16 @@ trust-these-validators.gov { detail::FileCfgGuard const cfg(*this, "testPort", "", Config::kConfigFileName, ""); auto const& conf = cfg.config(); - if (!BEAST_EXPECT(conf.exists("port_rpc"))) + if (!BEAST_EXPECT(conf.exists(Sections::kPortRpc))) return; - if (!BEAST_EXPECT(conf.exists("port_wss_admin"))) + if (!BEAST_EXPECT(conf.exists(Sections::kPortWssAdmin))) return; ParsedPort rpc; - if (!unexcept([&]() { parsePort(rpc, conf["port_rpc"], log); })) + if (!unexcept([&]() { parsePort(rpc, conf[Sections::kPortRpc], log); })) return; BEAST_EXPECT(rpc.adminNetsV4.size() + rpc.adminNetsV6.size() == 2); ParsedPort wss; - if (!unexcept([&]() { parsePort(wss, conf["port_wss_admin"], log); })) + if (!unexcept([&]() { parsePort(wss, conf[Sections::kPortWssAdmin], log); })) return; BEAST_EXPECT(wss.adminNetsV4.size() + wss.adminNetsV6.size() == 1); } @@ -1182,14 +1182,15 @@ r.ripple.com 51235 )"); cfg.loadFromString(toLoad); BEAST_EXPECT( - cfg.exists("port_rpc") && cfg.section("port_rpc").lines().empty() && - cfg.section("port_rpc").values().empty()); + cfg.exists(Sections::kPortRpc) && cfg.section(Sections::kPortRpc).lines().empty() && + cfg.section(Sections::kPortRpc).values().empty()); BEAST_EXPECT( - cfg.exists(SECTION_IPS) && cfg.section(SECTION_IPS).lines().size() == 1 && - cfg.section(SECTION_IPS).values().size() == 1); + cfg.exists(Sections::kIps) && cfg.section(Sections::kIps).lines().size() == 1 && + cfg.section(Sections::kIps).values().size() == 1); BEAST_EXPECT( - cfg.exists(SECTION_IPS_FIXED) && cfg.section(SECTION_IPS_FIXED).lines().size() == 2 && - cfg.section(SECTION_IPS_FIXED).values().size() == 2); + cfg.exists(Sections::kIpsFixed) && + cfg.section(Sections::kIpsFixed).lines().size() == 2 && + cfg.section(Sections::kIpsFixed).values().size() == 2); } void @@ -1237,14 +1238,15 @@ r.ripple.com:51235 )"); cfg.loadFromString(toLoad); BEAST_EXPECT( - cfg.exists("port_rpc") && cfg.section("port_rpc").lines().empty() && - cfg.section("port_rpc").values().empty()); + cfg.exists(Sections::kPortRpc) && cfg.section(Sections::kPortRpc).lines().empty() && + cfg.section(Sections::kPortRpc).values().empty()); BEAST_EXPECT( - cfg.exists(SECTION_IPS) && cfg.section(SECTION_IPS).lines().size() == 1 && - cfg.section(SECTION_IPS).values().size() == 1); + cfg.exists(Sections::kIps) && cfg.section(Sections::kIps).lines().size() == 1 && + cfg.section(Sections::kIps).values().size() == 1); BEAST_EXPECT( - cfg.exists(SECTION_IPS_FIXED) && cfg.section(SECTION_IPS_FIXED).lines().size() == 15 && - cfg.section(SECTION_IPS_FIXED).values().size() == 15); + cfg.exists(Sections::kIpsFixed) && + cfg.section(Sections::kIpsFixed).lines().size() == 15 && + cfg.section(Sections::kIpsFixed).values().size() == 15); BEAST_EXPECT(cfg.ips[0] == "r.ripple.com 51235"); BEAST_EXPECT(cfg.ipsFixed[0] == "s1.ripple.com 51235"); @@ -1335,18 +1337,18 @@ r.ripple.com:51235 Section s; s.append("online_delete = 3000"); std::uint32_t od = 0; - BEAST_EXPECT(set(od, "online_delete", s)); + BEAST_EXPECT(set(od, Keys::kOnlineDelete, s)); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - BEAST_EXPECTS(od == 3000, *(s.get("online_delete"))); + BEAST_EXPECTS(od == 3000, *(s.get(Keys::kOnlineDelete))); } { Section s; s.append("online_delete = 2000 #my comment on this"); std::uint32_t od = 0; - BEAST_EXPECT(set(od, "online_delete", s)); + BEAST_EXPECT(set(od, Keys::kOnlineDelete, s)); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - BEAST_EXPECTS(od == 2000, *(s.get("online_delete"))); + BEAST_EXPECTS(od == 2000, *(s.get(Keys::kOnlineDelete))); } } diff --git a/src/test/core/SociDB_test.cpp b/src/test/core/SociDB_test.cpp index f4c6fb04f1..57ff19fec5 100644 --- a/src/test/core/SociDB_test.cpp +++ b/src/test/core/SociDB_test.cpp @@ -1,8 +1,9 @@ #include -#include #include #include +#include +#include #include #include @@ -32,10 +33,10 @@ private: static void setupSQLiteConfig(BasicConfig& config, boost::filesystem::path const& dbPath) { - config.overwrite("sqdb", "backend", "sqlite"); + config.overwrite(Sections::kSqdb, Keys::kBackend, "sqlite"); auto value = dbPath.string(); if (!value.empty()) - config.legacy("database_path", value); + config.legacy(Sections::kDatabasePath, value); } static void diff --git a/src/test/jtx/Env_test.cpp b/src/test/jtx/Env_test.cpp index 0c9e5ffe24..d82cb86b36 100644 --- a/src/test/jtx/Env_test.cpp +++ b/src/test/jtx/Env_test.cpp @@ -35,6 +35,7 @@ #include #include #include +#include #include #include #include @@ -863,7 +864,7 @@ public: jtx::Env const env{ *this, jtx::envconfig([](std::unique_ptr cfg) { - (*cfg).deprecatedClearSection("port_rpc"); + (*cfg).deprecatedClearSection(Sections::kPortRpc); return cfg; }), nullptr, diff --git a/src/test/jtx/envconfig.h b/src/test/jtx/envconfig.h index 9a4e1dc20a..4c56ec8217 100644 --- a/src/test/jtx/envconfig.h +++ b/src/test/jtx/envconfig.h @@ -4,11 +4,6 @@ namespace xrpl::test { -// frequently used macros defined here for convenience. -#define PORT_WS "port_ws" -#define PORT_RPC "port_rpc" -#define PORT_PEER "port_peer" - extern std::atomic gEnvUseIPv4; inline char const* diff --git a/src/test/jtx/impl/JSONRPCClient.cpp b/src/test/jtx/impl/JSONRPCClient.cpp index cf81bfab0c..495fc5a657 100644 --- a/src/test/jtx/impl/JSONRPCClient.cpp +++ b/src/test/jtx/impl/JSONRPCClient.cpp @@ -4,8 +4,9 @@ #include -#include #include +#include +#include #include #include #include @@ -40,8 +41,8 @@ class JSONRPCClient : public AbstractClient { auto& log = std::cerr; ParsedPort common; - parsePort(common, cfg["server"], log); - for (auto const& name : cfg.section("server").values()) + parsePort(common, cfg[Sections::kServer], log); + for (auto const& name : cfg.section(Sections::kServer).values()) { if (!cfg.exists(name)) continue; diff --git a/src/test/jtx/impl/WSClient.cpp b/src/test/jtx/impl/WSClient.cpp index 6d069523d2..c00a88f270 100644 --- a/src/test/jtx/impl/WSClient.cpp +++ b/src/test/jtx/impl/WSClient.cpp @@ -2,8 +2,9 @@ #include -#include #include +#include +#include #include #include #include @@ -62,9 +63,9 @@ class WSClientImpl : public WSClient { auto& log = std::cerr; ParsedPort common; - parsePort(common, cfg["server"], log); + parsePort(common, cfg[Sections::kServer], log); auto const ps = v2 ? "ws2" : "ws"; - for (auto const& name : cfg.section("server").values()) + for (auto const& name : cfg.section(Sections::kServer).values()) { if (!cfg.exists(name)) continue; diff --git a/src/test/jtx/impl/envconfig.cpp b/src/test/jtx/impl/envconfig.cpp index 56197e1078..bc65738b44 100644 --- a/src/test/jtx/impl/envconfig.cpp +++ b/src/test/jtx/impl/envconfig.cpp @@ -3,7 +3,8 @@ #include #include -#include + +#include #include #include @@ -27,33 +28,33 @@ setupConfigForUnitTests(Config& cfg) // The Beta API (currently v2) is always available to tests cfg.betaRpcApi = true; - cfg.overwrite(ConfigSection::nodeDatabase(), "type", "memory"); - cfg.overwrite(ConfigSection::nodeDatabase(), "path", "main"); - cfg.deprecatedClearSection(ConfigSection::importNodeDatabase()); - cfg.legacy("database_path", ""); + cfg.overwrite(Sections::kNodeDatabase, Keys::kType, "memory"); + cfg.overwrite(Sections::kNodeDatabase, Keys::kPath, "main"); + cfg.deprecatedClearSection(Sections::kImportNodeDatabase); + cfg.legacy(Sections::kDatabasePath, ""); cfg.setupControl(true, true, true); - cfg["server"].append(PORT_PEER); - cfg[PORT_PEER].set("ip", getEnvLocalhostAddr()); + cfg[Sections::kServer].append(Sections::kPortPeer); + cfg[Sections::kPortPeer].set(Keys::kIp, getEnvLocalhostAddr()); // Using port 0 asks the operating system to allocate an unused port, which // can be obtained after a "bind" call. // Works for all system (Linux, Windows, Unix, Mac). // Check https://man7.org/linux/man-pages/man7/ip.7.html // "ip_local_port_range" section for more info - cfg[PORT_PEER].set("port", "0"); - cfg[PORT_PEER].set("protocol", "peer"); + cfg[Sections::kPortPeer].set(Keys::kPort, "0"); + cfg[Sections::kPortPeer].set(Keys::kProtocol, "peer"); - cfg["server"].append(PORT_RPC); - cfg[PORT_RPC].set("ip", getEnvLocalhostAddr()); - cfg[PORT_RPC].set("admin", getEnvLocalhostAddr()); - cfg[PORT_RPC].set("port", "0"); - cfg[PORT_RPC].set("protocol", "http,ws2"); + cfg[Sections::kServer].append(Sections::kPortRpc); + cfg[Sections::kPortRpc].set(Keys::kIp, getEnvLocalhostAddr()); + cfg[Sections::kPortRpc].set(Keys::kAdmin, getEnvLocalhostAddr()); + cfg[Sections::kPortRpc].set(Keys::kPort, "0"); + cfg[Sections::kPortRpc].set(Keys::kProtocol, "http,ws2"); - cfg["server"].append(PORT_WS); - cfg[PORT_WS].set("ip", getEnvLocalhostAddr()); - cfg[PORT_WS].set("admin", getEnvLocalhostAddr()); - cfg[PORT_WS].set("port", "0"); - cfg[PORT_WS].set("protocol", "ws"); + cfg[Sections::kServer].append(Sections::kPortWs); + cfg[Sections::kPortWs].set(Keys::kIp, getEnvLocalhostAddr()); + cfg[Sections::kPortWs].set(Keys::kAdmin, getEnvLocalhostAddr()); + cfg[Sections::kPortWs].set(Keys::kPort, "0"); + cfg[Sections::kPortWs].set(Keys::kProtocol, "ws"); cfg.sslVerify = false; } @@ -62,35 +63,35 @@ namespace jtx { std::unique_ptr noAdmin(std::unique_ptr cfg) { - (*cfg)[PORT_RPC].set("admin", ""); - (*cfg)[PORT_WS].set("admin", ""); + (*cfg)[Sections::kPortRpc].set(Keys::kAdmin, ""); + (*cfg)[Sections::kPortWs].set(Keys::kAdmin, ""); return cfg; } std::unique_ptr secureGateway(std::unique_ptr cfg) { - (*cfg)[PORT_RPC].set("admin", ""); - (*cfg)[PORT_WS].set("admin", ""); - (*cfg)[PORT_RPC].set("secure_gateway", getEnvLocalhostAddr()); + (*cfg)[Sections::kPortRpc].set(Keys::kAdmin, ""); + (*cfg)[Sections::kPortWs].set(Keys::kAdmin, ""); + (*cfg)[Sections::kPortRpc].set(Keys::kSecureGateway, getEnvLocalhostAddr()); return cfg; } std::unique_ptr adminLocalnet(std::unique_ptr cfg) { - (*cfg)[PORT_RPC].set("admin", "127.0.0.0/8"); - (*cfg)[PORT_WS].set("admin", "127.0.0.0/8"); + (*cfg)[Sections::kPortRpc].set(Keys::kAdmin, "127.0.0.0/8"); + (*cfg)[Sections::kPortWs].set(Keys::kAdmin, "127.0.0.0/8"); return cfg; } std::unique_ptr secureGatewayLocalnet(std::unique_ptr cfg) { - (*cfg)[PORT_RPC].set("admin", ""); - (*cfg)[PORT_WS].set("admin", ""); - (*cfg)[PORT_RPC].set("secure_gateway", "127.0.0.0/8"); - (*cfg)[PORT_WS].set("secure_gateway", "127.0.0.0/8"); + (*cfg)[Sections::kPortRpc].set(Keys::kAdmin, ""); + (*cfg)[Sections::kPortWs].set(Keys::kAdmin, ""); + (*cfg)[Sections::kPortRpc].set(Keys::kSecureGateway, "127.0.0.0/8"); + (*cfg)[Sections::kPortWs].set(Keys::kSecureGateway, "127.0.0.0/8"); return cfg; } std::unique_ptr @@ -106,7 +107,7 @@ std::unique_ptr validator(std::unique_ptr cfg, std::string const& seed) { // If the config has valid validation keys then we run as a validator. - cfg->section(SECTION_VALIDATION_SEED) + cfg->section(Sections::kValidationSeed) .append(std::vector{seed.empty() ? kDefaultSeed : seed}); return cfg; } @@ -114,20 +115,20 @@ validator(std::unique_ptr cfg, std::string const& seed) std::unique_ptr addGrpcConfig(std::unique_ptr cfg) { - (*cfg)[SECTION_PORT_GRPC].set("ip", getEnvLocalhostAddr()); - (*cfg)[SECTION_PORT_GRPC].set("port", "0"); + (*cfg)[Sections::kPortGrpc].set(Keys::kIp, getEnvLocalhostAddr()); + (*cfg)[Sections::kPortGrpc].set(Keys::kPort, "0"); return cfg; } std::unique_ptr addGrpcConfigWithSecureGateway(std::unique_ptr cfg, std::string const& secureGateway) { - (*cfg)[SECTION_PORT_GRPC].set("ip", getEnvLocalhostAddr()); + (*cfg)[Sections::kPortGrpc].set(Keys::kIp, getEnvLocalhostAddr()); // Check https://man7.org/linux/man-pages/man7/ip.7.html // "ip_local_port_range" section for using 0 ports - (*cfg)[SECTION_PORT_GRPC].set("port", "0"); - (*cfg)[SECTION_PORT_GRPC].set("secure_gateway", secureGateway); + (*cfg)[Sections::kPortGrpc].set(Keys::kPort, "0"); + (*cfg)[Sections::kPortGrpc].set(Keys::kSecureGateway, secureGateway); return cfg; } @@ -137,10 +138,10 @@ addGrpcConfigWithTLS( std::string const& certPath, std::string const& keyPath) { - (*cfg)[SECTION_PORT_GRPC].set("ip", getEnvLocalhostAddr()); - (*cfg)[SECTION_PORT_GRPC].set("port", "0"); - (*cfg)[SECTION_PORT_GRPC].set("ssl_cert", certPath); - (*cfg)[SECTION_PORT_GRPC].set("ssl_key", keyPath); + (*cfg)[Sections::kPortGrpc].set(Keys::kIp, getEnvLocalhostAddr()); + (*cfg)[Sections::kPortGrpc].set(Keys::kPort, "0"); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslCert, certPath); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslKey, keyPath); return cfg; } @@ -151,11 +152,11 @@ addGrpcConfigWithTLSAndClientCA( std::string const& keyPath, std::string const& clientCAPath) { - (*cfg)[SECTION_PORT_GRPC].set("ip", getEnvLocalhostAddr()); - (*cfg)[SECTION_PORT_GRPC].set("port", "0"); - (*cfg)[SECTION_PORT_GRPC].set("ssl_cert", certPath); - (*cfg)[SECTION_PORT_GRPC].set("ssl_key", keyPath); - (*cfg)[SECTION_PORT_GRPC].set("ssl_client_ca", clientCAPath); + (*cfg)[Sections::kPortGrpc].set(Keys::kIp, getEnvLocalhostAddr()); + (*cfg)[Sections::kPortGrpc].set(Keys::kPort, "0"); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslCert, certPath); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslKey, keyPath); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslClientCa, clientCAPath); return cfg; } @@ -166,11 +167,11 @@ addGrpcConfigWithTLSAndCertChain( std::string const& keyPath, std::string const& certChainPath) { - (*cfg)[SECTION_PORT_GRPC].set("ip", getEnvLocalhostAddr()); - (*cfg)[SECTION_PORT_GRPC].set("port", "0"); - (*cfg)[SECTION_PORT_GRPC].set("ssl_cert", certPath); - (*cfg)[SECTION_PORT_GRPC].set("ssl_key", keyPath); - (*cfg)[SECTION_PORT_GRPC].set("ssl_cert_chain", certChainPath); + (*cfg)[Sections::kPortGrpc].set(Keys::kIp, getEnvLocalhostAddr()); + (*cfg)[Sections::kPortGrpc].set(Keys::kPort, "0"); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslCert, certPath); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslKey, keyPath); + (*cfg)[Sections::kPortGrpc].set(Keys::kSslCertChain, certChainPath); return cfg; } @@ -180,13 +181,13 @@ makeConfig( std::map extraVoting) { auto p = test::jtx::envconfig(); - auto& section = p->section("transaction_queue"); - section.set("ledgers_in_queue", "2"); - section.set("minimum_queue_size", "2"); - section.set("min_ledgers_to_compute_size_limit", "3"); - section.set("max_ledger_counts_to_store", "100"); - section.set("retry_sequence_percent", "25"); - section.set("normal_consensus_increase_percent", "0"); + auto& section = p->section(Sections::kTransactionQueue); + section.set(Keys::kLedgersInQueue, "2"); + section.set(Keys::kMinimumQueueSize, "2"); + section.set(Keys::kMinLedgersToComputeSizeLimit, "3"); + section.set(Keys::kMaxLedgerCountsToStore, "100"); + section.set(Keys::kRetrySequencePercent, "25"); + section.set(Keys::kNormalConsensusIncreasePercent, "0"); for (auto const& [k, v] : extraTxQ) section.set(k, v); @@ -195,14 +196,14 @@ makeConfig( // a FeeVote if (!extraVoting.empty()) { - auto& votingSection = p->section("voting"); + auto& votingSection = p->section(Sections::kVoting); for (auto const& [k, v] : extraVoting) { votingSection.set(k, v); } // In order for the vote to occur, we must run as a validator - p->section("validation_seed").legacy("shUwVw52ofnCUX5m7kPTKzJdr4HEH"); + p->section(Sections::kValidationSeed).legacy("shUwVw52ofnCUX5m7kPTKzJdr4HEH"); } return p; } diff --git a/src/test/nodestore/Backend_test.cpp b/src/test/nodestore/Backend_test.cpp index 32b7d46868..65601b0cf5 100644 --- a/src/test/nodestore/Backend_test.cpp +++ b/src/test/nodestore/Backend_test.cpp @@ -1,12 +1,13 @@ #include #include -#include #include #include #include #include #include +#include +#include #include #include #include @@ -33,8 +34,8 @@ public: Section params; beast::TempDir const tempDir; - params.set("type", type); - params.set("path", tempDir.path()); + params.set(Keys::kType, type); + params.set(Keys::kPath, tempDir.path()); beast::xor_shift_engine rng(seedValue); diff --git a/src/test/nodestore/Database_test.cpp b/src/test/nodestore/Database_test.cpp index 50bdfefd4c..bb8ec7d4fd 100644 --- a/src/test/nodestore/Database_test.cpp +++ b/src/test/nodestore/Database_test.cpp @@ -11,6 +11,8 @@ #include #include #include +#include +#include #include #include #include @@ -71,8 +73,8 @@ public: Env env = [&]() { auto p = test::jtx::envconfig(); { - auto& section = p->section("sqlite"); - section.set("safety_level", "high"); + auto& section = p->section(Sections::kSqlite); + section.set(Keys::kSafetyLevel, "high"); } p->ledgerHistory = 100'000'000; @@ -100,8 +102,8 @@ public: Env env = [&]() { auto p = test::jtx::envconfig(); { - auto& section = p->section("sqlite"); - section.set("safety_level", "low"); + auto& section = p->section(Sections::kSqlite); + section.set(Keys::kSafetyLevel, "low"); } p->ledgerHistory = 100'000'000; @@ -129,10 +131,10 @@ public: Env env = [&]() { auto p = test::jtx::envconfig(); { - auto& section = p->section("sqlite"); - section.set("journal_mode", "off"); - section.set("synchronous", "extra"); - section.set("temp_store", "default"); + auto& section = p->section(Sections::kSqlite); + section.set(Keys::kJournalMode, "off"); + section.set(Keys::kSynchronous, "extra"); + section.set(Keys::kTempStore, "default"); } return Env( @@ -161,10 +163,10 @@ public: Env env = [&]() { auto p = test::jtx::envconfig(); { - auto& section = p->section("sqlite"); - section.set("journal_mode", "off"); - section.set("synchronous", "extra"); - section.set("temp_store", "default"); + auto& section = p->section(Sections::kSqlite); + section.set(Keys::kJournalMode, "off"); + section.set(Keys::kSynchronous, "extra"); + section.set(Keys::kTempStore, "default"); } p->ledgerHistory = 50'000'000; @@ -197,11 +199,11 @@ public: auto p = test::jtx::envconfig(); { - auto& section = p->section("sqlite"); - section.set("safety_level", "low"); - section.set("journal_mode", "off"); - section.set("synchronous", "extra"); - section.set("temp_store", "default"); + auto& section = p->section(Sections::kSqlite); + section.set(Keys::kSafetyLevel, "low"); + section.set(Keys::kJournalMode, "off"); + section.set(Keys::kSynchronous, "extra"); + section.set(Keys::kTempStore, "default"); } try @@ -228,9 +230,9 @@ public: auto p = test::jtx::envconfig(); { - auto& section = p->section("sqlite"); - section.set("safety_level", "high"); - section.set("journal_mode", "off"); + auto& section = p->section(Sections::kSqlite); + section.set(Keys::kSafetyLevel, "high"); + section.set(Keys::kJournalMode, "off"); } try @@ -257,9 +259,9 @@ public: auto p = test::jtx::envconfig(); { - auto& section = p->section("sqlite"); - section.set("safety_level", "low"); - section.set("synchronous", "extra"); + auto& section = p->section(Sections::kSqlite); + section.set(Keys::kSafetyLevel, "low"); + section.set(Keys::kSynchronous, "extra"); } try @@ -286,9 +288,9 @@ public: auto p = test::jtx::envconfig(); { - auto& section = p->section("sqlite"); - section.set("safety_level", "high"); - section.set("temp_store", "default"); + auto& section = p->section(Sections::kSqlite); + section.set(Keys::kSafetyLevel, "high"); + section.set(Keys::kTempStore, "default"); } try @@ -315,8 +317,8 @@ public: auto p = test::jtx::envconfig(); { - auto& section = p->section("sqlite"); - section.set("safety_level", "slow"); + auto& section = p->section(Sections::kSqlite); + section.set(Keys::kSafetyLevel, "slow"); } try @@ -343,8 +345,8 @@ public: auto p = test::jtx::envconfig(); { - auto& section = p->section("sqlite"); - section.set("journal_mode", "fast"); + auto& section = p->section(Sections::kSqlite); + section.set(Keys::kJournalMode, "fast"); } try @@ -371,8 +373,8 @@ public: auto p = test::jtx::envconfig(); { - auto& section = p->section("sqlite"); - section.set("synchronous", "instant"); + auto& section = p->section(Sections::kSqlite); + section.set(Keys::kSynchronous, "instant"); } try @@ -399,8 +401,8 @@ public: auto p = test::jtx::envconfig(); { - auto& section = p->section("sqlite"); - section.set("temp_store", "network"); + auto& section = p->section(Sections::kSqlite); + section.set(Keys::kTempStore, "network"); } try @@ -434,9 +436,9 @@ public: Env env = [&]() { auto p = test::jtx::envconfig(); { - auto& section = p->section("sqlite"); - section.set("page_size", "512"); - section.set("journal_size_limit", "2582080"); + auto& section = p->section(Sections::kSqlite); + section.set(Keys::kPageSize, "512"); + section.set(Keys::kJournalSizeLimit, "2582080"); } return Env(*this, std::move(p)); }(); @@ -455,8 +457,8 @@ public: bool found = false; auto p = test::jtx::envconfig(); { - auto& section = p->section("sqlite"); - section.set("page_size", "256"); + auto& section = p->section(Sections::kSqlite); + section.set(Keys::kPageSize, "256"); } try { @@ -478,8 +480,8 @@ public: bool found = false; auto p = test::jtx::envconfig(); { - auto& section = p->section("sqlite"); - section.set("page_size", "131072"); + auto& section = p->section(Sections::kSqlite); + section.set(Keys::kPageSize, "131072"); } try { @@ -501,8 +503,8 @@ public: bool found = false; auto p = test::jtx::envconfig(); { - auto& section = p->section("sqlite"); - section.set("page_size", "513"); + auto& section = p->section(Sections::kSqlite); + section.set(Keys::kPageSize, "513"); } try { @@ -532,8 +534,8 @@ public: beast::TempDir const nodeDb; Section srcParams; - srcParams.set("type", srcBackendType); - srcParams.set("path", nodeDb.path()); + srcParams.set(Keys::kType, srcBackendType); + srcParams.set(Keys::kPath, nodeDb.path()); // Create a batch auto batch = createPredictableBatch(kNumObjectsToTest, seedValue); @@ -555,8 +557,8 @@ public: // Set up the destination database beast::TempDir const destDb; Section destParams; - destParams.set("type", destBackendType); - destParams.set("path", destDb.path()); + destParams.set(Keys::kType, destBackendType); + destParams.set(Keys::kPath, destDb.path()); std::unique_ptr dest = Manager::instance().makeDatabase(megabytes(4), scheduler, 2, destParams, journal_); @@ -593,8 +595,8 @@ public: beast::TempDir const nodeDb; Section nodeParams; - nodeParams.set("type", type); - nodeParams.set("path", nodeDb.path()); + nodeParams.set(Keys::kType, type); + nodeParams.set(Keys::kPath, nodeDb.path()); beast::xor_shift_engine rng(seedValue); @@ -653,7 +655,7 @@ public: // Set an invalid earliest ledger sequence try { - nodeParams.set("earliest_seq", "0"); + nodeParams.set(Keys::kEarliestSeq, "0"); std::unique_ptr const db = Manager::instance().makeDatabase( megabytes(4), scheduler, 2, nodeParams, journal_); } @@ -664,7 +666,7 @@ public: { // Set a valid earliest ledger sequence - nodeParams.set("earliest_seq", "1"); + nodeParams.set(Keys::kEarliestSeq, "1"); std::unique_ptr db = Manager::instance().makeDatabase( megabytes(4), scheduler, 2, nodeParams, journal_); @@ -676,7 +678,7 @@ public: try { // Set to default earliest ledger sequence - nodeParams.set("earliest_seq", std::to_string(kXrpLedgerEarliestSeq)); + nodeParams.set(Keys::kEarliestSeq, std::to_string(kXrpLedgerEarliestSeq)); std::unique_ptr const db2 = Manager::instance().makeDatabase( megabytes(4), scheduler, 2, nodeParams, journal_); } diff --git a/src/test/nodestore/NuDBFactory_test.cpp b/src/test/nodestore/NuDBFactory_test.cpp index fae13b9cc8..3ca3fa6838 100644 --- a/src/test/nodestore/NuDBFactory_test.cpp +++ b/src/test/nodestore/NuDBFactory_test.cpp @@ -1,12 +1,13 @@ #include #include -#include #include #include #include #include #include +#include +#include #include #include #include @@ -29,10 +30,10 @@ private: createSection(std::string const& path, std::string const& blockSize = "") { Section params; - params.set("type", "nudb"); - params.set("path", path); + params.set(Keys::kType, "nudb"); + params.set(Keys::kPath, path); if (!blockSize.empty()) - params.set("nudb_block_size", blockSize); + params.set(Keys::kNudbBlockSize, blockSize); return params; } diff --git a/src/test/nodestore/Timing_test.cpp b/src/test/nodestore/Timing_test.cpp index 67feace198..f5e6bf8aa4 100644 --- a/src/test/nodestore/Timing_test.cpp +++ b/src/test/nodestore/Timing_test.cpp @@ -1,7 +1,6 @@ #include #include -#include #include #include #include @@ -12,6 +11,8 @@ #include #include #include +#include +#include #include #include #include @@ -661,9 +662,10 @@ public: { beast::TempDir const tempDir; Section config = parse(configString); - config.set("path", tempDir.path()); + config.set(Keys::kPath, tempDir.path()); std::stringstream ss; - ss << std::left << setw(10) << get(config, "type", std::string()) << std::right; + ss << std::left << setw(10) << get(config, Keys::kType, std::string()) + << std::right; for (auto const& test : tests) { ss << " " << setw(w) << toString(doTest(test.second, config, params, journal)); diff --git a/src/test/overlay/cluster_test.cpp b/src/test/overlay/cluster_test.cpp index 0c164dfded..6c2114b7de 100644 --- a/src/test/overlay/cluster_test.cpp +++ b/src/test/overlay/cluster_test.cpp @@ -3,9 +3,9 @@ #include -#include #include #include +#include #include #include #include diff --git a/src/test/rpc/AmendmentBlocked_test.cpp b/src/test/rpc/AmendmentBlocked_test.cpp index ae4fb99542..850d6db35b 100644 --- a/src/test/rpc/AmendmentBlocked_test.cpp +++ b/src/test/rpc/AmendmentBlocked_test.cpp @@ -9,10 +9,10 @@ #include #include -#include #include #include +#include #include #include #include @@ -20,6 +20,7 @@ #include #include +#include namespace xrpl { @@ -30,7 +31,7 @@ class AmendmentBlocked_test : public beast::unit_test::Suite { using namespace test::jtx; Env env{*this, envconfig([](std::unique_ptr cfg) { - cfg->loadFromString("[" SECTION_SIGNING_SUPPORT "]\ntrue"); + cfg->loadFromString(std::string("[") + Sections::kSigningSupport + "]\ntrue"); return cfg; })}; auto const gw = Account{"gateway"}; diff --git a/src/test/rpc/Feature_test.cpp b/src/test/rpc/Feature_test.cpp index d899b6dfd9..8cda5965cb 100644 --- a/src/test/rpc/Feature_test.cpp +++ b/src/test/rpc/Feature_test.cpp @@ -6,6 +6,7 @@ #include #include +#include #include #include #include @@ -276,8 +277,8 @@ class Feature_test : public beast::unit_test::Suite using namespace test::jtx; Env env{*this, envconfig([](std::unique_ptr cfg) { - (*cfg)["port_rpc"].set("admin", ""); - (*cfg)["port_ws"].set("admin", ""); + (*cfg)[Sections::kPortRpc].set(Keys::kAdmin, ""); + (*cfg)[Sections::kPortWs].set(Keys::kAdmin, ""); return cfg; })}; diff --git a/src/test/rpc/JSONRPC_test.cpp b/src/test/rpc/JSONRPC_test.cpp index 1f24d229f2..7f6b123533 100644 --- a/src/test/rpc/JSONRPC_test.cpp +++ b/src/test/rpc/JSONRPC_test.cpp @@ -12,12 +12,12 @@ #include #include -#include #include #include #include #include +#include #include #include #include @@ -2375,8 +2375,9 @@ public: testcase("autofill escalated fees"); using namespace test::jtx; Env env{*this, envconfig([](std::unique_ptr cfg) { - cfg->loadFromString("[" SECTION_SIGNING_SUPPORT "]\ntrue"); - cfg->section("transaction_queue").set("minimum_txn_in_ledger_standalone", "3"); + cfg->loadFromString(std::string("[") + Sections::kSigningSupport + "]\ntrue"); + cfg->section(Sections::kTransactionQueue) + .set(Keys::kMinimumTxnInLedgerStandalone, "3"); return cfg; })}; LoadFeeTrack const& feeTrackOuter = env.app().getFeeTrack(); diff --git a/src/test/rpc/LedgerRPC_test.cpp b/src/test/rpc/LedgerRPC_test.cpp index f35dddffb1..af56a9e9ba 100644 --- a/src/test/rpc/LedgerRPC_test.cpp +++ b/src/test/rpc/LedgerRPC_test.cpp @@ -15,6 +15,7 @@ #include #include +#include #include #include #include @@ -431,9 +432,9 @@ class LedgerRPC_test : public beast::unit_test::Suite testcase("Ledger with Queued Transactions"); using namespace test::jtx; auto cfg = envconfig([](std::unique_ptr cfg) { - auto& section = cfg->section("transaction_queue"); - section.set("minimum_txn_in_ledger_standalone", "3"); - section.set("normal_consensus_increase_percent", "0"); + auto& section = cfg->section(Sections::kTransactionQueue); + section.set(Keys::kMinimumTxnInLedgerStandalone, "3"); + section.set(Keys::kNormalConsensusIncreasePercent, "0"); return cfg; }); diff --git a/src/test/rpc/ManifestRPC_test.cpp b/src/test/rpc/ManifestRPC_test.cpp index c29f3d4e39..7e89cd029e 100644 --- a/src/test/rpc/ManifestRPC_test.cpp +++ b/src/test/rpc/ManifestRPC_test.cpp @@ -4,9 +4,9 @@ #include #include -#include #include +#include #include #include @@ -48,7 +48,7 @@ public: using namespace jtx; std::string const key = "n949f75evCHwgyP4fPVgaHqNHxUVN15PsJEZ3B3HnXPcPjcZAoy7"; Env env{*this, envconfig([&key](std::unique_ptr cfg) { - cfg->section(SECTION_VALIDATORS).append(key); + cfg->section(Sections::kValidators).append(key); return cfg; })}; { diff --git a/src/test/rpc/RPCOverload_test.cpp b/src/test/rpc/RPCOverload_test.cpp index b1030ebea5..33bc84eab0 100644 --- a/src/test/rpc/RPCOverload_test.cpp +++ b/src/test/rpc/RPCOverload_test.cpp @@ -8,14 +8,15 @@ #include #include -#include #include +#include #include #include #include #include +#include #include namespace xrpl::test { @@ -29,7 +30,7 @@ public: testcase << "Overload " << (useWS ? "WS" : "HTTP") << " RPC client"; using namespace jtx; Env env{*this, envconfig([](std::unique_ptr cfg) { - cfg->loadFromString("[" SECTION_SIGNING_SUPPORT "]\ntrue"); + cfg->loadFromString(std::string("[") + Sections::kSigningSupport + "]\ntrue"); return noAdmin(std::move(cfg)); })}; diff --git a/src/test/rpc/ServerInfo_test.cpp b/src/test/rpc/ServerInfo_test.cpp index 1d52f3b83e..52a1e6cdb0 100644 --- a/src/test/rpc/ServerInfo_test.cpp +++ b/src/test/rpc/ServerInfo_test.cpp @@ -3,9 +3,9 @@ #include #include -#include #include +#include #include #include @@ -108,9 +108,9 @@ admin = 127.0.0.1 Env env(*this, makeValidatorConfig()); auto const& config = env.app().config(); - auto const rpcPort = config["port_rpc"].get("port"); - auto const grpcPort = config[SECTION_PORT_GRPC].get("port"); - auto const wsPort = config["port_ws"].get("port"); + auto const rpcPort = config[Sections::kPortRpc].get(Keys::kPort); + auto const grpcPort = config[Sections::kPortGrpc].get(Keys::kPort); + auto const wsPort = config[Sections::kPortWs].get(Keys::kPort); BEAST_EXPECT(grpcPort); BEAST_EXPECT(rpcPort); BEAST_EXPECT(wsPort); diff --git a/src/test/rpc/Simulate_test.cpp b/src/test/rpc/Simulate_test.cpp index 9206bf42ac..5ea79c3996 100644 --- a/src/test/rpc/Simulate_test.cpp +++ b/src/test/rpc/Simulate_test.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -429,7 +430,7 @@ class Simulate_test : public beast::unit_test::Suite using namespace jtx; Env env(*this, envconfig([](std::unique_ptr cfg) { - cfg->section("transaction_queue").set("minimum_txn_in_ledger_standalone", "3"); + cfg->section(Sections::kTransactionQueue).set(Keys::kMinimumTxnInLedgerStandalone, "3"); return cfg; })); diff --git a/src/test/rpc/Subscribe_test.cpp b/src/test/rpc/Subscribe_test.cpp index 090a599e7c..5c519f3869 100644 --- a/src/test/rpc/Subscribe_test.cpp +++ b/src/test/rpc/Subscribe_test.cpp @@ -18,12 +18,12 @@ #include #include -#include #include #include #include #include +#include #include #include #include @@ -431,9 +431,10 @@ public: Env env{*this, singleThreadIo(envconfig(validator, "")), features}; auto& cfg = env.app().config(); - if (!BEAST_EXPECT(cfg.section(SECTION_VALIDATION_SEED).empty())) + if (!BEAST_EXPECT(cfg.section(Sections::kValidationSeed).empty())) return; - auto const parsedseed = parseBase58(cfg.section(SECTION_VALIDATION_SEED).values()[0]); + auto const parsedseed = + parseBase58(cfg.section(Sections::kValidationSeed).values()[0]); if (BEAST_EXPECT(parsedseed); not parsedseed.has_value()) return; diff --git a/src/test/rpc/ValidatorInfo_test.cpp b/src/test/rpc/ValidatorInfo_test.cpp index 8acdca8a1f..ece0aa1224 100644 --- a/src/test/rpc/ValidatorInfo_test.cpp +++ b/src/test/rpc/ValidatorInfo_test.cpp @@ -4,9 +4,9 @@ #include #include -#include #include +#include #include #include @@ -68,7 +68,7 @@ public: "5AqDedFv5TJa2w0i21eq3MYywLVJZnFOr7C0kw2AiTzSCjIzditQ8="; Env env{*this, envconfig([&tokenBlob](std::unique_ptr cfg) { - cfg->section(SECTION_VALIDATOR_TOKEN).append(tokenBlob); + cfg->section(Sections::kValidatorToken).append(tokenBlob); return cfg; })}; { diff --git a/src/test/rpc/ValidatorRPC_test.cpp b/src/test/rpc/ValidatorRPC_test.cpp index 1c6fb94fac..360cf13c75 100644 --- a/src/test/rpc/ValidatorRPC_test.cpp +++ b/src/test/rpc/ValidatorRPC_test.cpp @@ -5,12 +5,12 @@ #include #include #include -#include #include #include #include #include +#include #include #include #include @@ -90,7 +90,7 @@ public: *this, envconfig([&keys](std::unique_ptr cfg) { for (auto const& key : keys) - cfg->section(SECTION_VALIDATORS).append(key); + cfg->section(Sections::kValidators).append(key); return cfg; }), }; @@ -200,8 +200,8 @@ public: Env env{ *this, envconfig([&](std::unique_ptr cfg) { - cfg->section(SECTION_VALIDATOR_LIST_SITES).append(siteURI); - cfg->section(SECTION_VALIDATOR_LIST_KEYS) + cfg->section(Sections::kValidatorListSites).append(siteURI); + cfg->section(Sections::kValidatorListKeys) .append(strHex(server->publisherPublic())); return cfg; }), @@ -260,8 +260,8 @@ public: Env env{ *this, envconfig([&](std::unique_ptr cfg) { - cfg->section(SECTION_VALIDATOR_LIST_SITES).append(siteURI); - cfg->section(SECTION_VALIDATOR_LIST_KEYS) + cfg->section(Sections::kValidatorListSites).append(siteURI); + cfg->section(Sections::kValidatorListKeys) .append(strHex(server->publisherPublic())); return cfg; }), @@ -323,8 +323,8 @@ public: Env env{ *this, envconfig([&](std::unique_ptr cfg) { - cfg->section(SECTION_VALIDATOR_LIST_SITES).append(siteURI); - cfg->section(SECTION_VALIDATOR_LIST_KEYS) + cfg->section(Sections::kValidatorListSites).append(siteURI); + cfg->section(Sections::kValidatorListKeys) .append(strHex(server->publisherPublic())); return cfg; }), @@ -416,8 +416,8 @@ public: Env env{ *this, envconfig([&](std::unique_ptr cfg) { - cfg->section(SECTION_VALIDATOR_LIST_SITES).append(siteURI); - cfg->section(SECTION_VALIDATOR_LIST_KEYS) + cfg->section(Sections::kValidatorListSites).append(siteURI); + cfg->section(Sections::kValidatorListKeys) .append(strHex(server->publisherPublic())); return cfg; }), diff --git a/src/test/server/ServerStatus_test.cpp b/src/test/server/ServerStatus_test.cpp index 6569a2d2a4..5ba71962b3 100644 --- a/src/test/server/ServerStatus_test.cpp +++ b/src/test/server/ServerStatus_test.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -55,22 +56,23 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En static auto makeConfig(std::string const& proto, bool admin = true, bool credentials = false) { - auto const sectionName = boost::starts_with(proto, "h") ? "port_rpc" : "port_ws"; + auto const sectionName = + boost::starts_with(proto, "h") ? Sections::kPortRpc : Sections::kPortWs; auto p = jtx::envconfig(); - p->overwrite(sectionName, "protocol", proto); + p->overwrite(sectionName, Keys::kProtocol, proto); if (!admin) - p->overwrite(sectionName, "admin", ""); + p->overwrite(sectionName, Keys::kAdmin, ""); if (credentials) { - (*p)[sectionName].set("admin_password", "p"); - (*p)[sectionName].set("admin_user", "u"); + (*p)[sectionName].set(Keys::kAdminPassword, "p"); + (*p)[sectionName].set(Keys::kAdminUser, "u"); } p->overwrite( - boost::starts_with(proto, "h") ? "port_ws" : "port_rpc", - "protocol", + boost::starts_with(proto, "h") ? Sections::kPortWs : Sections::kPortRpc, + Keys::kProtocol, boost::starts_with(proto, "h") ? "ws" : "http"); if (proto == "https") @@ -78,11 +80,11 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En // this port is here to allow the env to create its internal client, // which requires an http endpoint to talk to. In the connection // failure test, this endpoint should never be used - (*p)["server"].append("port_alt"); - (*p)["port_alt"].set("ip", getEnvLocalhostAddr()); - (*p)["port_alt"].set("port", "7099"); - (*p)["port_alt"].set("protocol", "http"); - (*p)["port_alt"].set("admin", getEnvLocalhostAddr()); + (*p)[Sections::kServer].append("port_alt"); + (*p)["port_alt"].set(Keys::kIp, getEnvLocalhostAddr()); + (*p)["port_alt"].set(Keys::kPort, "7099"); + (*p)["port_alt"].set(Keys::kProtocol, "http"); + (*p)["port_alt"].set(Keys::kAdmin, getEnvLocalhostAddr()); } return p; @@ -212,8 +214,8 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En boost::beast::http::response& resp, boost::system::error_code& ec) { - auto const port = env.app().config()["port_ws"].get("port"); - auto ip = env.app().config()["port_ws"].get("ip"); + auto const port = env.app().config()[Sections::kPortWs].get(Keys::kPort); + auto ip = env.app().config()[Sections::kPortWs].get(Keys::kIp); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) doRequest(yield, makeWSUpgrade(*ip, *port), *ip, *port, secure, resp, ec); return; @@ -229,8 +231,8 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En std::string const& body = "", MyFields const& fields = {}) { - auto const port = env.app().config()["port_rpc"].get("port"); - auto const ip = env.app().config()["port_rpc"].get("ip"); + auto const port = env.app().config()[Sections::kPortRpc].get(Keys::kPort); + auto const ip = env.app().config()[Sections::kPortRpc].get(Keys::kIp); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) doRequest(yield, makeHTTPRequest(*ip, *port, body, fields), *ip, *port, secure, resp, ec); return; @@ -298,12 +300,13 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En if (admin && credentials) { - auto const user = - env.app().config()[protoWs ? "port_ws" : "port_rpc"].get("admin_user"); + auto const user = env.app() + .config()[protoWs ? Sections::kPortWs : Sections::kPortRpc] + .get(Keys::kAdminUser); - auto const password = - env.app().config()[protoWs ? "port_ws" : "port_rpc"].get( - "admin_password"); + auto const password = env.app() + .config()[protoWs ? Sections::kPortWs : Sections::kPortRpc] + .get(Keys::kAdminPassword); // 1 - FAILS with wrong pass // NOLINTNEXTLINE(bugprone-unchecked-optional-access) @@ -368,7 +371,7 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En testcase("WS client to http server fails"); using namespace jtx; Env env{*this, envconfig([](std::unique_ptr cfg) { - cfg->section("port_ws").set("protocol", "http,https"); + cfg->section(Sections::kPortWs).set(Keys::kProtocol, "http,https"); return cfg; })}; @@ -399,8 +402,8 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En testcase("Status request"); using namespace jtx; Env env{*this, envconfig([](std::unique_ptr cfg) { - cfg->section("port_rpc").set("protocol", "ws2,wss2"); - cfg->section("port_ws").set("protocol", "http"); + cfg->section(Sections::kPortRpc).set(Keys::kProtocol, "ws2,wss2"); + cfg->section(Sections::kPortWs).set(Keys::kProtocol, "http"); return cfg; })}; @@ -433,12 +436,12 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En using namespace boost::asio; using namespace boost::beast::http; Env env{*this, envconfig([](std::unique_ptr cfg) { - cfg->section("port_ws").set("protocol", "ws2"); + cfg->section(Sections::kPortWs).set(Keys::kProtocol, "ws2"); return cfg; })}; - auto const port = env.app().config()["port_ws"].get("port"); - auto const ip = env.app().config()["port_ws"].get("ip"); + auto const port = env.app().config()[Sections::kPortWs].get(Keys::kPort); + auto const ip = env.app().config()[Sections::kPortWs].get(Keys::kIp); boost::system::error_code ec; response resp; @@ -505,11 +508,11 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En using namespace test::jtx; Env env{*this, envconfig([secure](std::unique_ptr cfg) { - (*cfg)["port_rpc"].set("user", "me"); - (*cfg)["port_rpc"].set("password", "secret"); - (*cfg)["port_rpc"].set("protocol", secure ? "https" : "http"); + (*cfg)[Sections::kPortRpc].set(Keys::kUser, "me"); + (*cfg)[Sections::kPortRpc].set(Keys::kPassword, "secret"); + (*cfg)[Sections::kPortRpc].set(Keys::kProtocol, secure ? "https" : "http"); if (secure) - (*cfg)["port_ws"].set("protocol", "http,ws"); + (*cfg)[Sections::kPortWs].set(Keys::kProtocol, "http,ws"); return cfg; })}; @@ -533,11 +536,11 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En doHTTPRequest(env, yield, secure, resp, ec, to_string(jr), auth); BEAST_EXPECT(resp.result() == boost::beast::http::status::forbidden); - // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - auto const user = env.app().config().section("port_rpc").get("user").value(); - auto const pass = - // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - env.app().config().section("port_rpc").get("password").value(); + auto const section = env.app().config().section(Sections::kPortRpc); + // NOLINTBEGIN(bugprone-unchecked-optional-access) + auto const user = section.get(Keys::kUser).value(); + auto const pass = section.get(Keys::kPassword).value(); + // NOLINTEND(bugprone-unchecked-optional-access) // try with the correct user/pass, but not encoded auth.set("Authorization", "Basic " + user + ":" + pass); @@ -560,15 +563,15 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En using namespace boost::asio; using namespace boost::beast::http; Env env{*this, envconfig([&](std::unique_ptr cfg) { - (*cfg)["port_rpc"].set("limit", std::to_string(limit)); + (*cfg)[Sections::kPortRpc].set(Keys::kLimit, std::to_string(limit)); return cfg; })}; - // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - auto const port = env.app().config()["port_rpc"].get("port").value(); - - // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - auto const ip = env.app().config()["port_rpc"].get("ip").value(); + auto const section = env.app().config().section(Sections::kPortRpc); + // NOLINTBEGIN(bugprone-unchecked-optional-access) + auto const port = section.get(Keys::kPort).value(); + auto const ip = section.get(Keys::kIp).value(); + // NOLINTEND(bugprone-unchecked-optional-access) boost::system::error_code ec; io_context& ios = getIoContext(); @@ -620,14 +623,15 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En using namespace test::jtx; Env env{*this, envconfig([](std::unique_ptr cfg) { - (*cfg)["port_ws"].set("protocol", "wss"); + (*cfg)[Sections::kPortWs].set(Keys::kProtocol, "wss"); return cfg; })}; - // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - auto const port = env.app().config()["port_ws"].get("port").value(); - // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - auto const ip = env.app().config()["port_ws"].get("ip").value(); + auto const section = env.app().config().section(Sections::kPortWs); + // NOLINTBEGIN(bugprone-unchecked-optional-access) + auto const port = section.get(Keys::kPort).value(); + auto const ip = section.get(Keys::kIp).value(); + // NOLINTEND(bugprone-unchecked-optional-access) boost::beast::http::response resp; boost::system::error_code ec; doRequest(yield, makeWSUpgrade(ip, port), ip, port, true, resp, ec); @@ -644,10 +648,11 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En using namespace test::jtx; Env env{*this}; - // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - auto const port = env.app().config()["port_ws"].get("port").value(); - // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - auto const ip = env.app().config()["port_ws"].get("ip").value(); + auto const section = env.app().config().section(Sections::kPortWs); + // NOLINTBEGIN(bugprone-unchecked-optional-access) + auto const port = section.get(Keys::kPort).value(); + auto const ip = section.get(Keys::kIp).value(); + // NOLINTEND(bugprone-unchecked-optional-access) boost::beast::http::response resp; boost::system::error_code ec; // body content is required here to avoid being @@ -667,10 +672,11 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En using namespace boost::beast::http; Env env{*this}; - // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - auto const port = env.app().config()["port_ws"].get("port").value(); - // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - auto const ip = env.app().config()["port_ws"].get("ip").value(); + auto const section = env.app().config().section(Sections::kPortWs); + // NOLINTBEGIN(bugprone-unchecked-optional-access) + auto const port = section.get(Keys::kPort).value(); + auto const ip = section.get(Keys::kIp).value(); + // NOLINTEND(bugprone-unchecked-optional-access) boost::system::error_code ec; io_context& ios = getIoContext(); @@ -746,7 +752,7 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En *this, validator( envconfig([](std::unique_ptr cfg) { - cfg->section("port_rpc").set("protocol", "http"); + cfg->section(Sections::kPortRpc).set(Keys::kProtocol, "http"); return cfg; }), "")}; @@ -774,8 +780,8 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En BEAST_EXPECT(env.app().getOPs().getConsensusInfo()["validating"] == true); BEAST_EXPECT(!si[jss::state].isMember(jss::warnings)); - auto const portWs = env.app().config()["port_ws"].get("port"); - auto const ipWs = env.app().config()["port_ws"].get("ip"); + auto const portWs = env.app().config()[Sections::kPortWs].get(Keys::kPort); + auto const ipWs = env.app().config()[Sections::kPortWs].get(Keys::kIp); boost::system::error_code ec; response resp; @@ -874,7 +880,7 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En *this, validator( envconfig([](std::unique_ptr cfg) { - cfg->section("port_rpc").set("protocol", "http"); + cfg->section(Sections::kPortRpc).set(Keys::kProtocol, "http"); return cfg; }), "")}; @@ -902,8 +908,8 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En BEAST_EXPECT(env.app().getOPs().getConsensusInfo()["validating"] == true); BEAST_EXPECT(!si[jss::state].isMember(jss::warnings)); - auto const portWs = env.app().config()["port_ws"].get("port"); - auto const ipWs = env.app().config()["port_ws"].get("ip"); + auto const portWs = env.app().config()[Sections::kPortWs].get(Keys::kPort); + auto const ipWs = env.app().config()[Sections::kPortWs].get(Keys::kIp); boost::system::error_code ec; response resp; diff --git a/src/test/server/Server_test.cpp b/src/test/server/Server_test.cpp index 1b0107167c..455a365b7c 100644 --- a/src/test/server/Server_test.cpp +++ b/src/test/server/Server_test.cpp @@ -4,11 +4,11 @@ #include #include -#include #include #include #include +#include #include #include #include @@ -396,7 +396,7 @@ public: Env const env{ *this, envconfig([](std::unique_ptr cfg) { - (*cfg).deprecatedClearSection("port_rpc"); + (*cfg).deprecatedClearSection(Sections::kPortRpc); return cfg; }), std::make_unique(&messages)}; @@ -407,8 +407,8 @@ public: Env const env{ *this, envconfig([](std::unique_ptr cfg) { - (*cfg).deprecatedClearSection("port_rpc"); - (*cfg)["port_rpc"].set("ip", getEnvLocalhostAddr()); + (*cfg).deprecatedClearSection(Sections::kPortRpc); + (*cfg)[Sections::kPortRpc].set(Keys::kIp, getEnvLocalhostAddr()); return cfg; }), std::make_unique(&messages)}; @@ -419,9 +419,9 @@ public: Env const env{ *this, envconfig([](std::unique_ptr cfg) { - (*cfg).deprecatedClearSection("port_rpc"); - (*cfg)["port_rpc"].set("ip", getEnvLocalhostAddr()); - (*cfg)["port_rpc"].set("port", "0"); + (*cfg).deprecatedClearSection(Sections::kPortRpc); + (*cfg)[Sections::kPortRpc].set(Keys::kIp, getEnvLocalhostAddr()); + (*cfg)[Sections::kPortRpc].set(Keys::kPort, "0"); return cfg; }), std::make_unique(&messages)}; @@ -433,7 +433,7 @@ public: Env const env{ *this, envconfig([](std::unique_ptr cfg) { - (*cfg)["server"].set("port", "0"); + (*cfg)[Sections::kServer].set(Keys::kPort, "0"); return cfg; }), std::make_unique(&messages)}; @@ -445,10 +445,10 @@ public: Env const env{ *this, envconfig([](std::unique_ptr cfg) { - (*cfg).deprecatedClearSection("port_rpc"); - (*cfg)["port_rpc"].set("ip", getEnvLocalhostAddr()); - (*cfg)["port_rpc"].set("port", "8081"); - (*cfg)["port_rpc"].set("protocol", ""); + (*cfg).deprecatedClearSection(Sections::kPortRpc); + (*cfg)[Sections::kPortRpc].set(Keys::kIp, getEnvLocalhostAddr()); + (*cfg)[Sections::kPortRpc].set(Keys::kPort, "8081"); + (*cfg)[Sections::kPortRpc].set(Keys::kProtocol, ""); return cfg; }), std::make_unique(&messages)}; @@ -462,22 +462,22 @@ public: *this, envconfig([](std::unique_ptr cfg) { cfg = std::make_unique(); - cfg->overwrite(ConfigSection::nodeDatabase(), "type", "memory"); - cfg->overwrite(ConfigSection::nodeDatabase(), "path", "main"); - cfg->deprecatedClearSection(ConfigSection::importNodeDatabase()); - cfg->legacy("database_path", ""); + cfg->overwrite(Sections::kNodeDatabase, Keys::kType, "memory"); + cfg->overwrite(Sections::kNodeDatabase, Keys::kPath, "main"); + cfg->deprecatedClearSection(Sections::kImportNodeDatabase); + cfg->legacy(Sections::kDatabasePath, ""); cfg->setupControl(true, true, true); - (*cfg)["port_peer"].set("ip", getEnvLocalhostAddr()); - (*cfg)["port_peer"].set("port", "8080"); - (*cfg)["port_peer"].set("protocol", "peer"); - (*cfg)["port_rpc"].set("ip", getEnvLocalhostAddr()); - (*cfg)["port_rpc"].set("port", "8081"); - (*cfg)["port_rpc"].set("protocol", "http,ws2"); - (*cfg)["port_rpc"].set("admin", getEnvLocalhostAddr()); - (*cfg)["port_ws"].set("ip", getEnvLocalhostAddr()); - (*cfg)["port_ws"].set("port", "8082"); - (*cfg)["port_ws"].set("protocol", "ws"); - (*cfg)["port_ws"].set("admin", getEnvLocalhostAddr()); + (*cfg)[Sections::kPortPeer].set(Keys::kIp, getEnvLocalhostAddr()); + (*cfg)[Sections::kPortPeer].set(Keys::kPort, "8080"); + (*cfg)[Sections::kPortPeer].set(Keys::kProtocol, "peer"); + (*cfg)[Sections::kPortRpc].set(Keys::kIp, getEnvLocalhostAddr()); + (*cfg)[Sections::kPortRpc].set(Keys::kPort, "8081"); + (*cfg)[Sections::kPortRpc].set(Keys::kProtocol, "http,ws2"); + (*cfg)[Sections::kPortRpc].set(Keys::kAdmin, getEnvLocalhostAddr()); + (*cfg)[Sections::kPortWs].set(Keys::kIp, getEnvLocalhostAddr()); + (*cfg)[Sections::kPortWs].set(Keys::kPort, "8082"); + (*cfg)[Sections::kPortWs].set(Keys::kProtocol, "ws"); + (*cfg)[Sections::kPortWs].set(Keys::kAdmin, getEnvLocalhostAddr()); return cfg; }), std::make_unique(&messages)}; @@ -491,14 +491,14 @@ public: *this, envconfig([](std::unique_ptr cfg) { cfg = std::make_unique(); - cfg->overwrite(ConfigSection::nodeDatabase(), "type", "memory"); - cfg->overwrite(ConfigSection::nodeDatabase(), "path", "main"); - cfg->deprecatedClearSection(ConfigSection::importNodeDatabase()); - cfg->legacy("database_path", ""); + cfg->overwrite(Sections::kNodeDatabase, Keys::kType, "memory"); + cfg->overwrite(Sections::kNodeDatabase, Keys::kPath, "main"); + cfg->deprecatedClearSection(Sections::kImportNodeDatabase); + cfg->legacy(Sections::kDatabasePath, ""); cfg->setupControl(true, true, true); - (*cfg)["server"].append("port_peer"); - (*cfg)["server"].append("port_rpc"); - (*cfg)["server"].append("port_ws"); + (*cfg)[Sections::kServer].append(Sections::kPortPeer); + (*cfg)[Sections::kServer].append(Sections::kPortRpc); + (*cfg)[Sections::kServer].append(Sections::kPortWs); return cfg; }), std::make_unique(&messages)}; diff --git a/src/test/shamap/common.h b/src/test/shamap/common.h index 49f1c07741..0475acdf6d 100644 --- a/src/test/shamap/common.h +++ b/src/test/shamap/common.h @@ -1,6 +1,8 @@ #pragma once #include +#include +#include #include #include #include @@ -33,8 +35,8 @@ public: , j_(j) { Section testSection; - testSection.set("type", "memory"); - testSection.set("path", "SHAMap_test"); + testSection.set(Keys::kType, "memory"); + testSection.set(Keys::kPath, "SHAMap_test"); db_ = NodeStore::Manager::instance().makeDatabase( megabytes(4), scheduler_, 1, testSection, j); } diff --git a/src/tests/libxrpl/helpers/TestFamily.h b/src/tests/libxrpl/helpers/TestFamily.h index dea7a6d4b4..50f514480a 100644 --- a/src/tests/libxrpl/helpers/TestFamily.h +++ b/src/tests/libxrpl/helpers/TestFamily.h @@ -1,6 +1,8 @@ #pragma once #include +#include +#include #include #include #include @@ -37,8 +39,8 @@ public: , j_(j) { Section config; - config.set("type", "memory"); - config.set("path", "TestFamily"); + config.set(Keys::kType, "memory"); + config.set(Keys::kPath, "TestFamily"); db_ = NodeStore::Manager::instance().makeDatabase(megabytes(4), scheduler_, 1, config, j); } diff --git a/src/xrpld/app/main/Application.cpp b/src/xrpld/app/main/Application.cpp index af5d51289d..67b5e30eb7 100644 --- a/src/xrpld/app/main/Application.cpp +++ b/src/xrpld/app/main/Application.cpp @@ -27,7 +27,6 @@ #include #include #include -#include #include #include #include @@ -40,7 +39,6 @@ #include #include -#include #include #include #include @@ -56,6 +54,8 @@ #include #include #include +#include +#include #include #include #include @@ -316,13 +316,14 @@ public: // PerfLog must be started before any other threads are launched. , perfLog_( perf::makePerfLog( - perf::setupPerfLog(config_->section("perf"), config_->configDir), + perf::setupPerfLog(config_->section(Sections::kPerf), config_->configDir), *this, logs_->journal("PerfLog"), [this] { signalStop("PerfLog"); })) , txMaster_(*this) - , collectorManager_( - makeCollectorManager(config_->section(SECTION_INSIGHT), logs_->journal("Collector"))) + , collectorManager_(makeCollectorManager( + config_->section(Sections::kInsight), + logs_->journal("Collector"))) , jobQueue_( std::make_unique( [](std::unique_ptr const& config) { @@ -864,7 +865,7 @@ public: megabytes(config_->getValueFor(SizedItem::BurstSize, std::nullopt)), dummyScheduler, 0, - config_->section(ConfigSection::importNodeDatabase()), + config_->section(Sections::kImportNodeDatabase), j); JLOG(j.warn()) << "Starting node import from '" << source->getName() << "' to '" @@ -1224,9 +1225,9 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) } return supported; }(); - Section const& downVoted = config_->section(SECTION_VETO_AMENDMENTS); + Section const& downVoted = config_->section(Sections::kVetoAmendments); - Section const& upVoted = config_->section(SECTION_AMENDMENTS); + Section const& upVoted = config_->section(Sections::kAmendments); amendmentTable_ = makeAmendmentTable( *this, @@ -1295,7 +1296,7 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) nodeIdentity_ = getNodeIdentity(*this, cmdline); - if (!cluster_->load(config().section(SECTION_CLUSTER_NODES))) + if (!cluster_->load(config().section(Sections::kClusterNodes))) { JLOG(journal_.fatal()) << "Invalid entry in cluster configuration."; return false; @@ -1309,7 +1310,7 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) getWalletDB(), "ValidatorManifests", validatorKeys_.manifest, - config().section(SECTION_VALIDATOR_KEY_REVOCATION).values())) + config().section(Sections::kValidatorKeyRevocation).values())) { JLOG(journal_.fatal()) << "Invalid configured validator manifest."; return false; @@ -1320,7 +1321,7 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) // It is possible to have a valid ValidatorKeys object without // setting the signingKey or masterKey. This occurs if the // configuration file does not have either - // SECTION_VALIDATOR_TOKEN or SECTION_VALIDATION_SEED section. + // Sections::kValidatorToken or Sections::kValidationSeed section. // masterKey for the configuration-file specified validator keys std::optional localSigningKey; @@ -1330,8 +1331,8 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) // Setup trusted validators if (!validators_->load( localSigningKey, - config().section(SECTION_VALIDATORS).values(), - config().section(SECTION_VALIDATOR_LIST_KEYS).values(), + config().section(Sections::kValidators).values(), + config().section(Sections::kValidatorListKeys).values(), config().validatorListThreshold)) { JLOG(journal_.fatal()) << "Invalid entry in validator configuration."; @@ -1339,9 +1340,9 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) } } - if (!validatorSites_->load(config().section(SECTION_VALIDATOR_LIST_SITES).values())) + if (!validatorSites_->load(config().section(Sections::kValidatorListSites).values())) { - JLOG(journal_.fatal()) << "Invalid entry in [" << SECTION_VALIDATOR_LIST_SITES << "]"; + JLOG(journal_.fatal()) << "Invalid entry in [" << Sections::kValidatorListSites << "]"; return false; } @@ -1439,7 +1440,7 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) // // Execute start up rpc commands. // - for (auto const& cmd : config_->section(SECTION_RPC_STARTUP).lines()) + for (auto const& cmd : config_->section(Sections::kRpcStartup).lines()) { json::Reader jrReader; json::Value jvCommand; @@ -1447,7 +1448,7 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) if (!jrReader.parse(cmd, jvCommand)) { JLOG(journal_.fatal()) - << "Couldn't parse entry in [" << SECTION_RPC_STARTUP << "]: '" << cmd; + << "Couldn't parse entry in [" << Sections::kRpcStartup << "]: '" << cmd; } if (!config_->quiet()) @@ -1503,7 +1504,7 @@ ApplicationImp::start(bool withTimers) overlay_->start(); if (grpcServer_->start()) - fixConfigPorts(*config_, {{SECTION_PORT_GRPC, grpcServer_->getEndpoint()}}); + fixConfigPorts(*config_, {{Sections::kPortGrpc, grpcServer_->getEndpoint()}}); ledgerCleaner_->start(); perfLog_->start(); @@ -2170,12 +2171,12 @@ fixConfigPorts(Config& config, Endpoints const& endpoints) continue; auto& section = config[name]; - auto const optPort = section.get("port"); + auto const optPort = section.get(Keys::kPort); if (optPort) { std::uint16_t const port = beast::lexicalCast(*optPort); if (port == 0u) - section.set("port", std::to_string(ep.port())); + section.set(Keys::kPort, std::to_string(ep.port())); } } } diff --git a/src/xrpld/app/main/CollectorManager.cpp b/src/xrpld/app/main/CollectorManager.cpp index 6cdbca8d8a..9e1278607f 100644 --- a/src/xrpld/app/main/CollectorManager.cpp +++ b/src/xrpld/app/main/CollectorManager.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -8,6 +7,8 @@ #include #include #include +#include +#include #include #include @@ -25,13 +26,13 @@ public: CollectorManagerImp(Section const& params, beast::Journal journal) : journal_(journal) { - std::string const& server = get(params, "server"); + std::string const& server = get(params, Keys::kServer); if (server == "statsd") { beast::IP::Endpoint const address( - beast::IP::Endpoint::fromString(get(params, "address"))); - std::string const& prefix(get(params, "prefix")); + beast::IP::Endpoint::fromString(get(params, Keys::kAddress))); + std::string const& prefix(get(params, Keys::kPrefix)); collector_ = beast::insight::StatsDCollector::make(address, prefix, journal); } diff --git a/src/xrpld/app/main/CollectorManager.h b/src/xrpld/app/main/CollectorManager.h index e736ae57db..d07da15353 100644 --- a/src/xrpld/app/main/CollectorManager.h +++ b/src/xrpld/app/main/CollectorManager.h @@ -1,7 +1,7 @@ #pragma once -#include #include +#include namespace xrpl { diff --git a/src/xrpld/app/main/GRPCServer.cpp b/src/xrpld/app/main/GRPCServer.cpp index 7a622f632f..1af1343fc5 100644 --- a/src/xrpld/app/main/GRPCServer.cpp +++ b/src/xrpld/app/main/GRPCServer.cpp @@ -1,13 +1,11 @@ #include #include -#include #include #include #include #include -#include #include #include #include @@ -15,6 +13,8 @@ #include #include #include +#include +#include #include #include #include @@ -335,15 +335,15 @@ GRPCServerImpl::GRPCServerImpl(Application& app) : app_(app), journal_(app_.getJournal("gRPC Server")) { // if present, get endpoint from config - if (app_.config().exists(SECTION_PORT_GRPC)) + if (app_.config().exists(Sections::kPortGrpc)) { - Section const& section = app_.config().section(SECTION_PORT_GRPC); + Section const& section = app_.config().section(Sections::kPortGrpc); - auto const optIp = section.get("ip"); + auto const optIp = section.get(Keys::kIp); if (!optIp) return; - auto const optPort = section.get("port"); + auto const optPort = section.get(Keys::kPort); if (!optPort) return; try @@ -361,7 +361,7 @@ GRPCServerImpl::GRPCServerImpl(Application& app) Throw("Error setting grpc server address"); } - auto const optSecureGateway = section.get("secure_gateway"); + auto const optSecureGateway = section.get(Keys::kSecureGateway); if (optSecureGateway) { try @@ -391,10 +391,10 @@ GRPCServerImpl::GRPCServerImpl(Application& app) } // Read TLS certificate configuration (optional) - sslCertPath_ = section.get("ssl_cert"); - sslKeyPath_ = section.get("ssl_key"); - sslCertChainPath_ = section.get("ssl_cert_chain"); - sslClientCAPath_ = section.get("ssl_client_ca"); + sslCertPath_ = section.get(Keys::kSslCert); + sslKeyPath_ = section.get(Keys::kSslKey); + sslCertChainPath_ = section.get(Keys::kSslCertChain); + sslClientCAPath_ = section.get(Keys::kSslClientCa); // If cert or key is specified, both must be specified if (sslCertPath_.has_value() || sslKeyPath_.has_value()) diff --git a/src/xrpld/app/main/Main.cpp b/src/xrpld/app/main/Main.cpp index f470a2d80f..d0b40efce8 100644 --- a/src/xrpld/app/main/Main.cpp +++ b/src/xrpld/app/main/Main.cpp @@ -1,6 +1,5 @@ #include #include -#include #include #include #include @@ -12,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -362,10 +362,10 @@ run(int argc, char** argv) std::string importText; { importText += "Import an existing node database (specified in the ["; - importText += ConfigSection::importNodeDatabase(); + importText += Sections::kImportNodeDatabase; importText += "] configuration file section) into the current "; importText += "node database (specified in the ["; - importText += ConfigSection::nodeDatabase(); + importText += Sections::kNodeDatabase; importText += "] configuration file section)."; } diff --git a/src/xrpld/app/main/NodeIdentity.cpp b/src/xrpld/app/main/NodeIdentity.cpp index 656e2b91a2..8198c43af7 100644 --- a/src/xrpld/app/main/NodeIdentity.cpp +++ b/src/xrpld/app/main/NodeIdentity.cpp @@ -2,9 +2,9 @@ #include #include -#include #include +#include #include #include #include @@ -31,12 +31,15 @@ getNodeIdentity(Application& app, boost::program_options::variables_map const& c if (!seed) Throw("Invalid 'nodeid' in command line"); } - else if (app.config().exists(SECTION_NODE_SEED)) + else if (app.config().exists(Sections::kNodeSeed)) { - seed = parseBase58(app.config().section(SECTION_NODE_SEED).lines().front()); + seed = parseBase58(app.config().section(Sections::kNodeSeed).lines().front()); if (!seed) - Throw("Invalid [" SECTION_NODE_SEED "] in configuration file"); + { + Throw( + std::string("Invalid [") + Sections::kNodeSeed + "] in configuration file"); + } } if (seed) diff --git a/src/xrpld/app/misc/NetworkOPs.cpp b/src/xrpld/app/misc/NetworkOPs.cpp index 54cf85ba35..917cf6aeb2 100644 --- a/src/xrpld/app/misc/NetworkOPs.cpp +++ b/src/xrpld/app/misc/NetworkOPs.cpp @@ -24,7 +24,6 @@ #include #include #include -#include #include #include #include @@ -54,6 +53,7 @@ #include #include #include +#include #include #include #include @@ -313,7 +313,7 @@ public: , consensus_( registry_.get().getApp(), makeFeeVote( - setupFeeVote(registry_.get().getApp().config().section("voting")), + setupFeeVote(registry_.get().getApp().config().section(Sections::kVoting)), registry_.get().getJournal("FeeVote")), ledgerMaster, *localTX_, @@ -2973,11 +2973,12 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) } } - if (registry_.get().getApp().config().exists(SECTION_PORT_GRPC)) + if (registry_.get().getApp().config().exists(Sections::kPortGrpc)) { - auto const& grpcSection = registry_.get().getApp().config().section(SECTION_PORT_GRPC); - auto const optPort = grpcSection.get("port"); - if (optPort && grpcSection.get("ip")) + auto const& grpcSection = + registry_.get().getApp().config().section(Sections::kPortGrpc); + auto const optPort = grpcSection.get(Keys::kPort); + if (optPort && grpcSection.get(Keys::kIp)) { auto& jv = ports.append(json::Value(json::ValueType::Object)); jv[jss::port] = *optPort; diff --git a/src/xrpld/app/misc/SHAMapStoreImp.cpp b/src/xrpld/app/misc/SHAMapStoreImp.cpp index 3f4bd6280f..7259c233e4 100644 --- a/src/xrpld/app/misc/SHAMapStoreImp.cpp +++ b/src/xrpld/app/misc/SHAMapStoreImp.cpp @@ -4,15 +4,15 @@ #include #include #include -#include -#include #include #include #include #include #include #include +#include +#include #include #include #include @@ -101,44 +101,45 @@ SHAMapStoreImp::SHAMapStoreImp( { Config& config{app.config()}; - Section& section{config.section(ConfigSection::nodeDatabase())}; + Section& section{config.section(Sections::kNodeDatabase)}; if (section.empty()) { Throw( - "Missing [" + ConfigSection::nodeDatabase() + "] entry in configuration file"); + std::string("Missing [") + Sections::kNodeDatabase + "] entry in configuration file"); } // RocksDB only. Use sensible defaults if no values specified. - if (boost::iequals(get(section, "type"), "RocksDB")) + if (boost::iequals(get(section, Keys::kType), "RocksDB")) { - if (!section.exists("cache_mb")) + if (!section.exists(Keys::kCacheMb)) { - section.set("cache_mb", std::to_string(config.getValueFor(SizedItem::HashNodeDbCache))); + section.set( + Keys::kCacheMb, std::to_string(config.getValueFor(SizedItem::HashNodeDbCache))); } - if (!section.exists("filter_bits") && (config.nodeSize >= 2)) - section.set("filter_bits", "10"); + if (!section.exists(Keys::kFilterBits) && (config.nodeSize >= 2)) + section.set(Keys::kFilterBits, "10"); } - getIfExists(section, "online_delete", deleteInterval_); + getIfExists(section, Keys::kOnlineDelete, deleteInterval_); if (deleteInterval_ != 0u) { // Configuration that affects the behavior of online delete - getIfExists(section, "delete_batch", deleteBatch_); + getIfExists(section, Keys::kDeleteBatch, deleteBatch_); std::uint32_t temp = 0; - if (getIfExists(section, "back_off_milliseconds", temp) || + if (getIfExists(section, Keys::kBackOffMilliseconds, temp) || // Included for backward compatibility with an undocumented setting - getIfExists(section, "backOff", temp)) + getIfExists(section, Keys::kBackOff, temp)) { backOff_ = std::chrono::milliseconds{temp}; } - if (getIfExists(section, "age_threshold_seconds", temp)) + if (getIfExists(section, Keys::kAgeThresholdSeconds, temp)) ageThreshold_ = std::chrono::seconds{temp}; - if (getIfExists(section, "recovery_wait_seconds", temp)) + if (getIfExists(section, Keys::kRecoveryWaitSeconds, temp)) recoveryWaitTime_ = std::chrono::seconds{temp}; - getIfExists(section, "advisory_delete", advisoryDelete_); + getIfExists(section, Keys::kAdvisoryDelete, advisoryDelete_); auto const minInterval = config.standalone() ? kMinimumDeletionIntervalSa : kMinimumDeletionInterval; @@ -164,20 +165,20 @@ SHAMapStoreImp::SHAMapStoreImp( std::unique_ptr SHAMapStoreImp::makeNodeStore(int readThreads) { - auto nscfg = app_.config().section(ConfigSection::nodeDatabase()); + auto nscfg = app_.config().section(Sections::kNodeDatabase); // Provide default values. - if (!nscfg.exists("cache_size")) + if (!nscfg.exists(Keys::kCacheSize)) { nscfg.set( - "cache_size", + Keys::kCacheSize, std::to_string(app_.config().getValueFor(SizedItem::TreeCacheSize, std::nullopt))); } - if (!nscfg.exists("cache_age")) + if (!nscfg.exists(Keys::kCacheAge)) { nscfg.set( - "cache_age", + Keys::kCacheAge, std::to_string(app_.config().getValueFor(SizedItem::TreeCacheAge, std::nullopt))); } @@ -385,8 +386,8 @@ SHAMapStoreImp::run() void SHAMapStoreImp::dbPaths() { - Section const section{app_.config().section(ConfigSection::nodeDatabase())}; - boost::filesystem::path dbPath = get(section, "path"); + Section const section{app_.config().section(Sections::kNodeDatabase)}; + boost::filesystem::path dbPath = get(section, Keys::kPath); if (boost::filesystem::exists(dbPath)) { @@ -451,7 +452,7 @@ SHAMapStoreImp::dbPaths() (!archiveDbExists && !state.archiveDb.empty()) || (writableDbExists != archiveDbExists) || state.writableDb.empty() != state.archiveDb.empty()) { - boost::filesystem::path stateDbPathName = app_.config().legacy("database_path"); + boost::filesystem::path stateDbPathName = app_.config().legacy(Sections::kDatabasePath); stateDbPathName /= dbName_; stateDbPathName += "*"; @@ -463,7 +464,7 @@ SHAMapStoreImp::dbPaths() << "The existing data is in a corrupted state.\n" << "To resume operation, remove the files matching " << stateDbPathName.string() << " and contents of the directory " - << get(section, "path") << '\n' + << get(section, Keys::kPath) << '\n' << "Optionally, you can move those files to another\n" << "location if you wish to analyze or back up the data.\n" << "However, there is no guarantee that the data in its\n" @@ -480,7 +481,7 @@ SHAMapStoreImp::dbPaths() std::unique_ptr SHAMapStoreImp::makeBackendRotating(std::string path) { - Section section{app_.config().section(ConfigSection::nodeDatabase())}; + Section section{app_.config().section(Sections::kNodeDatabase)}; boost::filesystem::path newPath; if (!path.empty()) @@ -489,12 +490,12 @@ SHAMapStoreImp::makeBackendRotating(std::string path) } else { - boost::filesystem::path p = get(section, "path"); + boost::filesystem::path p = get(section, Keys::kPath); p /= dbPrefix_; p += ".%%%%"; newPath = boost::filesystem::unique_path(p); } - section.set("path", newPath.string()); + section.set(Keys::kPath, newPath.string()); auto backend{NodeStore::Manager::instance().makeBackend( section, diff --git a/src/xrpld/app/misc/ValidatorList.h b/src/xrpld/app/misc/ValidatorList.h index dcd7a24499..3f1823f930 100644 --- a/src/xrpld/app/misc/ValidatorList.h +++ b/src/xrpld/app/misc/ValidatorList.h @@ -233,8 +233,8 @@ class ValidatorList std::optional localPubKey_; // The below variable contains the Publisher list specified in the local - // config file under the title of SECTION_VALIDATORS or [validators]. - // This list is not associated with the masterKey of any publisher. + // config file under the title of [validators]. This list is not associated + // with the masterKey of any publisher. // Apropos PublisherListCollection fields, localPublisherList does not // have any "remaining" manifests. It is assumed to be perennially diff --git a/src/xrpld/app/misc/detail/AmendmentTable.cpp b/src/xrpld/app/misc/detail/AmendmentTable.cpp index 65771f6aa3..4f331b0781 100644 --- a/src/xrpld/app/misc/detail/AmendmentTable.cpp +++ b/src/xrpld/app/misc/detail/AmendmentTable.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -8,6 +7,7 @@ #include #include #include +#include #include #include #include diff --git a/src/xrpld/app/misc/detail/TxQ.cpp b/src/xrpld/app/misc/detail/TxQ.cpp index c12632875d..f98580ede4 100644 --- a/src/xrpld/app/misc/detail/TxQ.cpp +++ b/src/xrpld/app/misc/detail/TxQ.cpp @@ -3,12 +3,13 @@ #include #include -#include #include #include #include #include #include +#include +#include #include #include #include @@ -1872,16 +1873,16 @@ TxQ::Setup setupTxQ(Config const& config) { TxQ::Setup setup; - auto const& section = config.section("transaction_queue"); - set(setup.ledgersInQueue, "ledgers_in_queue", section); - set(setup.queueSizeMin, "minimum_queue_size", section); - set(setup.retrySequencePercent, "retry_sequence_percent", section); - set(setup.minimumEscalationMultiplier, "minimum_escalation_multiplier", section); - set(setup.minimumTxnInLedger, "minimum_txn_in_ledger", section); - set(setup.minimumTxnInLedgerSA, "minimum_txn_in_ledger_standalone", section); - set(setup.targetTxnInLedger, "target_txn_in_ledger", section); + auto const& section = config.section(Sections::kTransactionQueue); + set(setup.ledgersInQueue, Keys::kLedgersInQueue, section); + set(setup.queueSizeMin, Keys::kMinimumQueueSize, section); + set(setup.retrySequencePercent, Keys::kRetrySequencePercent, section); + set(setup.minimumEscalationMultiplier, Keys::kMinimumEscalationMultiplier, section); + set(setup.minimumTxnInLedger, Keys::kMinimumTxnInLedger, section); + set(setup.minimumTxnInLedgerSA, Keys::kMinimumTxnInLedgerStandalone, section); + set(setup.targetTxnInLedger, Keys::kTargetTxnInLedger, section); std::uint32_t max = 0; - if (set(max, "maximum_txn_in_ledger", section)) + if (set(max, Keys::kMaximumTxnInLedger, section)) { if (max < setup.minimumTxnInLedger) { @@ -1909,7 +1910,7 @@ setupTxQ(Config const& config) moot. (There are other ways to do that, including minimum_txn_in_ledger_.) */ - set(setup.normalConsensusIncreasePercent, "normal_consensus_increase_percent", section); + set(setup.normalConsensusIncreasePercent, Keys::kNormalConsensusIncreasePercent, section); setup.normalConsensusIncreasePercent = std::clamp(setup.normalConsensusIncreasePercent, 0u, 1000u); @@ -1917,11 +1918,11 @@ setupTxQ(Config const& config) are nonsensical (uint overflows happen, so the limit grows instead of shrinking). 0 is not recommended. */ - set(setup.slowConsensusDecreasePercent, "slow_consensus_decrease_percent", section); + set(setup.slowConsensusDecreasePercent, Keys::kSlowConsensusDecreasePercent, section); setup.slowConsensusDecreasePercent = std::clamp(setup.slowConsensusDecreasePercent, 0u, 100u); - set(setup.maximumTxnPerAccount, "maximum_txn_per_account", section); - set(setup.minimumLastLedgerBuffer, "minimum_last_ledger_buffer", section); + set(setup.maximumTxnPerAccount, Keys::kMaximumTxnPerAccount, section); + set(setup.minimumLastLedgerBuffer, Keys::kMinimumLastLedgerBuffer, section); setup.standAlone = config.standalone(); return setup; diff --git a/src/xrpld/app/misc/detail/ValidatorKeys.cpp b/src/xrpld/app/misc/detail/ValidatorKeys.cpp index 0380e2e294..e439eca936 100644 --- a/src/xrpld/app/misc/detail/ValidatorKeys.cpp +++ b/src/xrpld/app/misc/detail/ValidatorKeys.cpp @@ -1,11 +1,11 @@ #include #include -#include #include #include #include +#include #include #include #include @@ -17,18 +17,18 @@ namespace xrpl { ValidatorKeys::ValidatorKeys(Config const& config, beast::Journal j) { - if (config.exists(SECTION_VALIDATOR_TOKEN) && config.exists(SECTION_VALIDATION_SEED)) + if (config.exists(Sections::kValidatorToken) && config.exists(Sections::kValidationSeed)) { configInvalid_ = true; - JLOG(j.fatal()) << "Cannot specify both [" SECTION_VALIDATION_SEED - "] and [" SECTION_VALIDATOR_TOKEN "]"; + JLOG(j.fatal()) << "Cannot specify both [" << Sections::kValidationSeed << "] and [" + << Sections::kValidatorToken << "]"; return; } - if (config.exists(SECTION_VALIDATOR_TOKEN)) + if (config.exists(Sections::kValidatorToken)) { // token is non-const so it can be moved from - if (auto token = loadValidatorToken(config.section(SECTION_VALIDATOR_TOKEN).lines())) + if (auto token = loadValidatorToken(config.section(Sections::kValidatorToken).lines())) { auto const pk = derivePublicKey(KeyType::Secp256k1, token->validationSecret); auto const m = deserializeManifest(base64Decode(token->manifest)); @@ -36,7 +36,8 @@ ValidatorKeys::ValidatorKeys(Config const& config, beast::Journal j) if (!m || pk != m->signingKey) { configInvalid_ = true; - JLOG(j.fatal()) << "Invalid token specified in [" SECTION_VALIDATOR_TOKEN "]"; + JLOG(j.fatal()) << "Invalid token specified in [" << Sections::kValidatorToken + << "]"; } else { @@ -49,17 +50,17 @@ ValidatorKeys::ValidatorKeys(Config const& config, beast::Journal j) else { configInvalid_ = true; - JLOG(j.fatal()) << "Invalid token specified in [" SECTION_VALIDATOR_TOKEN "]"; + JLOG(j.fatal()) << "Invalid token specified in [" << Sections::kValidatorToken << "]"; } } - else if (config.exists(SECTION_VALIDATION_SEED)) + else if (config.exists(Sections::kValidationSeed)) { auto const seed = - parseBase58(config.section(SECTION_VALIDATION_SEED).lines().front()); + parseBase58(config.section(Sections::kValidationSeed).lines().front()); if (!seed) { configInvalid_ = true; - JLOG(j.fatal()) << "Invalid seed specified in [" SECTION_VALIDATION_SEED "]"; + JLOG(j.fatal()) << "Invalid seed specified in [" << Sections::kValidationSeed << "]"; } else { diff --git a/src/xrpld/app/misc/detail/setup_HashRouter.cpp b/src/xrpld/app/misc/detail/setup_HashRouter.cpp index 9727f5d733..97aa501698 100644 --- a/src/xrpld/app/misc/detail/setup_HashRouter.cpp +++ b/src/xrpld/app/misc/detail/setup_HashRouter.cpp @@ -2,8 +2,9 @@ #include -#include #include +#include +#include #include #include @@ -18,11 +19,11 @@ setupHashRouter(Config const& config) using namespace std::chrono; HashRouter::Setup setup; - auto const& section = config.section("hashrouter"); + auto const& section = config.section(Sections::kHashrouter); std::int32_t tmp{}; - if (set(tmp, "hold_time", section)) + if (set(tmp, Keys::kHoldTime, section)) { if (tmp < 12) { @@ -32,7 +33,7 @@ setupHashRouter(Config const& config) } setup.holdTime = seconds(tmp); } - if (set(tmp, "relay_time", section)) + if (set(tmp, Keys::kRelayTime, section)) { if (tmp < 8) { diff --git a/src/xrpld/app/rdb/backend/detail/Node.cpp b/src/xrpld/app/rdb/backend/detail/Node.cpp index 1fd3136420..9b7db6f0f5 100644 --- a/src/xrpld/app/rdb/backend/detail/Node.cpp +++ b/src/xrpld/app/rdb/backend/detail/Node.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include // IWYU pragma: keep @@ -1291,7 +1292,7 @@ bool dbHasSpace(soci::session& session, Config const& config, beast::Journal j) { boost::filesystem::space_info const space = - boost::filesystem::space(config.legacy("database_path")); + boost::filesystem::space(config.legacy(Sections::kDatabasePath)); if (space.available < megabytes(512)) { diff --git a/src/xrpld/app/rdb/detail/PeerFinder.cpp b/src/xrpld/app/rdb/detail/PeerFinder.cpp index 2481b63d2b..9452c3af99 100644 --- a/src/xrpld/app/rdb/detail/PeerFinder.cpp +++ b/src/xrpld/app/rdb/detail/PeerFinder.cpp @@ -2,11 +2,11 @@ #include -#include #include #include #include #include +#include #include #include // IWYU pragma: keep diff --git a/src/xrpld/core/Config.h b/src/xrpld/core/Config.h index a18b68a508..45b36808b2 100644 --- a/src/xrpld/core/Config.h +++ b/src/xrpld/core/Config.h @@ -1,9 +1,9 @@ #pragma once -#include #include #include #include +#include #include #include #include // VFALCO Breaks levelization diff --git a/src/xrpld/core/ConfigSections.h b/src/xrpld/core/ConfigSections.h deleted file mode 100644 index 7f22dd59c1..0000000000 --- a/src/xrpld/core/ConfigSections.h +++ /dev/null @@ -1,80 +0,0 @@ -#pragma once - -#include - -namespace xrpl { - -// VFALCO DEPRECATED in favor of the BasicConfig interface -struct ConfigSection -{ - explicit ConfigSection() = default; - - static std::string - nodeDatabase() - { - return "node_db"; - } - static std::string - importNodeDatabase() - { - return "import_db"; - } -}; - -// VFALCO TODO Rename and replace these macros with variables. -#define SECTION_AMENDMENTS "amendments" -#define SECTION_AMENDMENT_MAJORITY_TIME "amendment_majority_time" -#define SECTION_BETA_RPC_API "beta_rpc_api" -#define SECTION_CLUSTER_NODES "cluster_nodes" -#define SECTION_COMPRESSION "compression" -#define SECTION_DEBUG_LOGFILE "debug_logfile" -#define SECTION_ELB_SUPPORT "elb_support" -#define SECTION_FEE_DEFAULT "fee_default" -#define SECTION_FETCH_DEPTH "fetch_depth" -#define SECTION_INSIGHT "insight" -#define SECTION_IO_WORKERS "io_workers" -#define SECTION_IPS "ips" -#define SECTION_IPS_FIXED "ips_fixed" -#define SECTION_LEDGER_HISTORY "ledger_history" -#define SECTION_LEDGER_REPLAY "ledger_replay" -#define SECTION_MAX_TRANSACTIONS "max_transactions" -#define SECTION_NETWORK_ID "network_id" -#define SECTION_NETWORK_QUORUM "network_quorum" -#define SECTION_NODE_SEED "node_seed" -#define SECTION_NODE_SIZE "node_size" -#define SECTION_OVERLAY "overlay" -#define SECTION_PATH_SEARCH_OLD "path_search_old" -#define SECTION_PATH_SEARCH "path_search" -#define SECTION_PATH_SEARCH_FAST "path_search_fast" -#define SECTION_PATH_SEARCH_MAX "path_search_max" -#define SECTION_PEER_PRIVATE "peer_private" -#define SECTION_PEERS_MAX "peers_max" -#define SECTION_PEERS_IN_MAX "peers_in_max" -#define SECTION_PEERS_OUT_MAX "peers_out_max" -#define SECTION_PORT_GRPC "port_grpc" -#define SECTION_PREFETCH_WORKERS "prefetch_workers" -#define SECTION_REDUCE_RELAY "reduce_relay" -#define SECTION_RELATIONAL_DB "relational_db" -#define SECTION_RELAY_PROPOSALS "relay_proposals" -#define SECTION_RELAY_VALIDATIONS "relay_validations" -#define SECTION_RPC_STARTUP "rpc_startup" -#define SECTION_SIGNING_SUPPORT "signing_support" -#define SECTION_SNTP "sntp_servers" -#define SECTION_SSL_VERIFY "ssl_verify" -#define SECTION_SSL_VERIFY_FILE "ssl_verify_file" -#define SECTION_SSL_VERIFY_DIR "ssl_verify_dir" -#define SECTION_SERVER_DOMAIN "server_domain" -#define SECTION_SWEEP_INTERVAL "sweep_interval" -#define SECTION_VALIDATORS_FILE "validators_file" -#define SECTION_VALIDATION_SEED "validation_seed" -#define SECTION_VALIDATOR_KEYS "validator_keys" -#define SECTION_VALIDATOR_KEY_REVOCATION "validator_key_revocation" -#define SECTION_VALIDATOR_LIST_KEYS "validator_list_keys" -#define SECTION_VALIDATOR_LIST_SITES "validator_list_sites" -#define SECTION_VALIDATOR_LIST_THRESHOLD "validator_list_threshold" -#define SECTION_VALIDATORS "validators" -#define SECTION_VALIDATOR_TOKEN "validator_token" -#define SECTION_VETO_AMENDMENTS "veto_amendments" -#define SECTION_WORKERS "workers" - -} // namespace xrpl diff --git a/src/xrpld/core/detail/Config.cpp b/src/xrpld/core/detail/Config.cpp index 6eedc43edd..1b2449823e 100644 --- a/src/xrpld/core/detail/Config.cpp +++ b/src/xrpld/core/detail/Config.cpp @@ -1,8 +1,5 @@ #include -#include - -#include #include #include #include @@ -11,6 +8,8 @@ #include #include #include +#include +#include #include #include #include @@ -385,7 +384,7 @@ Config::setup(std::string const& strConf, bool bQuiet, bool bSilent, bool bStand load(); { // load() may have set a new value for the dataDir - std::string const dbPath(legacy("database_path")); + std::string const dbPath(legacy(Sections::kDatabasePath)); if (!dbPath.empty()) { dataDir = boost::filesystem::path(dbPath); @@ -404,7 +403,7 @@ Config::setup(std::string const& strConf, bool bQuiet, bool bSilent, bool bStand if (ec) Throw(boost::str(boost::format("Can not create %s") % dataDir)); - legacy("database_path", boost::filesystem::absolute(dataDir).string()); + legacy(Sections::kDatabasePath, boost::filesystem::absolute(dataDir).string()); } HTTPClient::initializeSSLContext(this->sslVerifyDir, this->sslVerifyFile, this->sslVerify, j_); @@ -412,11 +411,11 @@ Config::setup(std::string const& strConf, bool bQuiet, bool bSilent, bool bStand if (runStandalone_) ledgerHistory = 0; - Section const ledgerTxTablesSection = section("ledger_tx_tables"); - getIfExists(ledgerTxTablesSection, "use_tx_tables", useTxTables_); + Section const ledgerTxTablesSection = section(Sections::kLedgerTxTables); + getIfExists(ledgerTxTablesSection, Keys::kUseTxTables, useTxTables_); - Section const& nodeDbSection{section(ConfigSection::nodeDatabase())}; - getIfExists(nodeDbSection, "fast_load", fastLoad); + Section const& nodeDbSection{section(Sections::kNodeDatabase)}; + getIfExists(nodeDbSection, Keys::kFastLoad, fastLoad); } // 0 ports are allowed for unit tests, but still not allowed to be present in @@ -424,16 +423,16 @@ Config::setup(std::string const& strConf, bool bQuiet, bool bSilent, bool bStand static void checkZeroPorts(Config const& config) { - if (!config.exists("server")) + if (!config.exists(Sections::kServer)) return; - for (auto const& name : config.section("server").values()) + for (auto const& name : config.section(Sections::kServer).values()) { if (!config.exists(name)) return; auto const& section = config[name]; - auto const optResult = section.get("port"); + auto const optResult = section.get(Keys::kPort); if (optResult) { auto const port = beast::lexicalCast(*optResult); @@ -477,10 +476,10 @@ Config::loadFromString(std::string const& fileContents) build(secConfig); - if (auto s = getIniFileSection(secConfig, SECTION_IPS)) + if (auto s = getIniFileSection(secConfig, Sections::kIps)) ips = *s; - if (auto s = getIniFileSection(secConfig, SECTION_IPS_FIXED)) + if (auto s = getIniFileSection(secConfig, Sections::kIpsFixed)) ipsFixed = *s; // if the user has specified ip:port then replace : with a space. @@ -507,16 +506,16 @@ Config::loadFromString(std::string const& fileContents) { std::string dbPath; - if (getSingleSection(secConfig, "database_path", dbPath, j_)) + if (getSingleSection(secConfig, Sections::kDatabasePath, dbPath, j_)) { boost::filesystem::path const p(dbPath); - legacy("database_path", boost::filesystem::absolute(p).string()); + legacy(Sections::kDatabasePath, boost::filesystem::absolute(p).string()); } } std::string strTemp; - if (getSingleSection(secConfig, SECTION_NETWORK_ID, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kNetworkId, strTemp, j_)) { if (strTemp == "main") { @@ -536,43 +535,45 @@ Config::loadFromString(std::string const& fileContents) } } - if (getSingleSection(secConfig, SECTION_PEER_PRIVATE, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kPeerPrivate, strTemp, j_)) peerPrivate = beast::lexicalCastThrow(strTemp); - if (getSingleSection(secConfig, SECTION_PEERS_MAX, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kPeersMax, strTemp, j_)) { peersMax = beast::lexicalCastThrow(strTemp); } else { std::optional peersInMaxOpt{}; - if (getSingleSection(secConfig, SECTION_PEERS_IN_MAX, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kPeersInMax, strTemp, j_)) { peersInMaxOpt = beast::lexicalCastThrow(strTemp); if (*peersInMaxOpt > 1000) { - Throw("Invalid value specified in [" SECTION_PEERS_IN_MAX - "] section; the value must be less or equal than 1000"); + Throw( + std::string("Invalid value specified in [") + Sections::kPeersInMax + + "] section; the value must be less or equal than 1000"); } } std::optional peersOutMaxOpt{}; - if (getSingleSection(secConfig, SECTION_PEERS_OUT_MAX, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kPeersOutMax, strTemp, j_)) { peersOutMaxOpt = beast::lexicalCastThrow(strTemp); if (*peersOutMaxOpt < 10 || *peersOutMaxOpt > 1000) { - Throw("Invalid value specified in [" SECTION_PEERS_OUT_MAX - "] section; the value must be in range 10-1000"); + Throw( + std::string("Invalid value specified in [") + Sections::kPeersOutMax + + "] section; the value must be in range 10-1000"); } } // if one section is configured then the other must be configured too if ((peersInMaxOpt && !peersOutMaxOpt) || (peersOutMaxOpt && !peersInMaxOpt)) { - Throw("Both sections [" SECTION_PEERS_IN_MAX - "]" - "and [" SECTION_PEERS_OUT_MAX "] must be configured"); + Throw( + std::string("Both sections [") + Sections::kPeersInMax + "]" + " and [" + + Sections::kPeersOutMax + "] must be configured"); } if (peersInMaxOpt && peersOutMaxOpt) @@ -582,7 +583,7 @@ Config::loadFromString(std::string const& fileContents) } } - if (getSingleSection(secConfig, SECTION_NODE_SIZE, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kNodeSize, strTemp, j_)) { if (boost::iequals(strTemp, "tiny")) { @@ -610,19 +611,19 @@ Config::loadFromString(std::string const& fileContents) } } - if (getSingleSection(secConfig, SECTION_SIGNING_SUPPORT, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kSigningSupport, strTemp, j_)) signingEnabled_ = beast::lexicalCastThrow(strTemp); - if (getSingleSection(secConfig, SECTION_ELB_SUPPORT, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kElbSupport, strTemp, j_)) elbSupport = beast::lexicalCastThrow(strTemp); - getSingleSection(secConfig, SECTION_SSL_VERIFY_FILE, sslVerifyFile, j_); - getSingleSection(secConfig, SECTION_SSL_VERIFY_DIR, sslVerifyDir, j_); + getSingleSection(secConfig, Sections::kSslVerifyFile, sslVerifyFile, j_); + getSingleSection(secConfig, Sections::kSslVerifyDir, sslVerifyDir, j_); - if (getSingleSection(secConfig, SECTION_SSL_VERIFY, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kSslVerify, strTemp, j_)) sslVerify = beast::lexicalCastThrow(strTemp); - if (getSingleSection(secConfig, SECTION_RELAY_VALIDATIONS, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kRelayValidations, strTemp, j_)) { if (boost::iequals(strTemp, "all")) { @@ -638,12 +639,13 @@ Config::loadFromString(std::string const& fileContents) } else { - Throw("Invalid value specified in [" SECTION_RELAY_VALIDATIONS - "] section"); + Throw( + std::string("Invalid value specified in [") + Sections::kRelayValidations + + "] section"); } } - if (getSingleSection(secConfig, SECTION_RELAY_PROPOSALS, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kRelayProposals, strTemp, j_)) { if (boost::iequals(strTemp, "all")) { @@ -659,28 +661,30 @@ Config::loadFromString(std::string const& fileContents) } else { - Throw("Invalid value specified in [" SECTION_RELAY_PROPOSALS - "] section"); + Throw( + std::string("Invalid value specified in [") + Sections::kRelayProposals + + "] section"); } } - if (exists(SECTION_VALIDATION_SEED) && exists(SECTION_VALIDATOR_TOKEN)) + if (exists(Sections::kValidationSeed) && exists(Sections::kValidatorToken)) { - Throw("Cannot have both [" SECTION_VALIDATION_SEED - "] and [" SECTION_VALIDATOR_TOKEN "] config sections"); + Throw( + std::string("Cannot have both [") + Sections::kValidationSeed + "] and [" + + Sections::kValidatorToken + "] config sections"); } - if (getSingleSection(secConfig, SECTION_NETWORK_QUORUM, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kNetworkQuorum, strTemp, j_)) networkQuorum = beast::lexicalCastThrow(strTemp); - fees = setupFeeVote(section("voting")); + fees = setupFeeVote(section(Sections::kVoting)); /* [fee_default] is documented in the example config files as useful for * things like offline transaction signing. Until that's completely * deprecated, allow it to override the [voting] section. */ - if (getSingleSection(secConfig, SECTION_FEE_DEFAULT, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kFeeDefault, strTemp, j_)) fees.referenceFee = beast::lexicalCastThrow(strTemp); - if (getSingleSection(secConfig, SECTION_LEDGER_HISTORY, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kLedgerHistory, strTemp, j_)) { if (boost::iequals(strTemp, "full")) { @@ -696,7 +700,7 @@ Config::loadFromString(std::string const& fileContents) } } - if (getSingleSection(secConfig, SECTION_FETCH_DEPTH, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kFetchDepth, strTemp, j_)) { if (boost::iequals(strTemp, "none")) { @@ -716,74 +720,78 @@ Config::loadFromString(std::string const& fileContents) // By default, validators don't have pathfinding enabled, unless it is // explicitly requested by the server's admin. - if (exists(SECTION_VALIDATION_SEED) || exists(SECTION_VALIDATOR_TOKEN)) + if (exists(Sections::kValidationSeed) || exists(Sections::kValidatorToken)) pathSearchMax = 0; - if (getSingleSection(secConfig, SECTION_PATH_SEARCH_OLD, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kPathSearchOld, strTemp, j_)) pathSearchOld = beast::lexicalCastThrow(strTemp); - if (getSingleSection(secConfig, SECTION_PATH_SEARCH, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kPathSearch, strTemp, j_)) pathSearch = beast::lexicalCastThrow(strTemp); - if (getSingleSection(secConfig, SECTION_PATH_SEARCH_FAST, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kPathSearchFast, strTemp, j_)) pathSearchFast = beast::lexicalCastThrow(strTemp); - if (getSingleSection(secConfig, SECTION_PATH_SEARCH_MAX, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kPathSearchMax, strTemp, j_)) pathSearchMax = beast::lexicalCastThrow(strTemp); - if (getSingleSection(secConfig, SECTION_DEBUG_LOGFILE, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kDebugLogfile, strTemp, j_)) debugLogfile_ = strTemp; - if (getSingleSection(secConfig, SECTION_SWEEP_INTERVAL, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kSweepInterval, strTemp, j_)) { sweepInterval = beast::lexicalCastThrow(strTemp); if (sweepInterval < 10 || sweepInterval > 600) { - Throw("Invalid " SECTION_SWEEP_INTERVAL - ": must be between 10 and 600 inclusive"); + Throw( + std::string("Invalid ") + Sections::kSweepInterval + + ": must be between 10 and 600 inclusive"); } } - if (getSingleSection(secConfig, SECTION_WORKERS, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kWorkers, strTemp, j_)) { workers = beast::lexicalCastThrow(strTemp); if (workers < 1 || workers > 1024) { - Throw("Invalid " SECTION_WORKERS - ": must be between 1 and 1024 inclusive."); + Throw( + std::string("Invalid ") + Sections::kWorkers + + ": must be between 1 and 1024 inclusive."); } } - if (getSingleSection(secConfig, SECTION_IO_WORKERS, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kIoWorkers, strTemp, j_)) { ioWorkers = beast::lexicalCastThrow(strTemp); if (ioWorkers < 1 || ioWorkers > 1024) { - Throw("Invalid " SECTION_IO_WORKERS - ": must be between 1 and 1024 inclusive."); + Throw( + std::string("Invalid ") + Sections::kIoWorkers + + ": must be between 1 and 1024 inclusive."); } } - if (getSingleSection(secConfig, SECTION_PREFETCH_WORKERS, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kPrefetchWorkers, strTemp, j_)) { prefetchWorkers = beast::lexicalCastThrow(strTemp); if (prefetchWorkers < 1 || prefetchWorkers > 1024) { - Throw("Invalid " SECTION_PREFETCH_WORKERS - ": must be between 1 and 1024 inclusive."); + Throw( + std::string("Invalid ") + Sections::kPrefetchWorkers + + ": must be between 1 and 1024 inclusive."); } } - if (getSingleSection(secConfig, SECTION_COMPRESSION, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kCompression, strTemp, j_)) compression = beast::lexicalCastThrow(strTemp); - if (getSingleSection(secConfig, SECTION_LEDGER_REPLAY, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kLedgerReplay, strTemp, j_)) ledgerReplay = beast::lexicalCastThrow(strTemp); - if (exists(SECTION_REDUCE_RELAY)) + if (exists(Sections::kReduceRelay)) { - auto sec = section(SECTION_REDUCE_RELAY); + auto sec = section(Sections::kReduceRelay); ///////////////////// !!TEMPORARY CODE BLOCK!! //////////////////////// // vp_enable config option is deprecated by vp_base_squelch_enable // @@ -791,22 +799,23 @@ Config::loadFromString(std::string const& fileContents) // is the default algorithm, it must be replaced with: // // VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = // // sec.value_or("vp_base_squelch_enable", true); // - if (sec.exists("vp_base_squelch_enable") && sec.exists("vp_enable")) + if (sec.exists(Keys::kVpBaseSquelchEnable) && sec.exists(Keys::kVpEnable)) { - Throw("Invalid " SECTION_REDUCE_RELAY - " cannot specify both vp_base_squelch_enable and vp_enable " - "options. " - "vp_enable was deprecated and replaced by " - "vp_base_squelch_enable"); + Throw( + std::string("Invalid ") + Sections::kReduceRelay + + " cannot specify both vp_base_squelch_enable and vp_enable " + "options. " + "vp_enable was deprecated and replaced by " + "vp_base_squelch_enable"); } - if (sec.exists("vp_base_squelch_enable")) + if (sec.exists(Keys::kVpBaseSquelchEnable)) { - vpReduceRelayBaseSquelchEnable = sec.valueOr("vp_base_squelch_enable", false); + vpReduceRelayBaseSquelchEnable = sec.valueOr(Keys::kVpBaseSquelchEnable, false); } - else if (sec.exists("vp_enable")) + else if (sec.exists(Keys::kVpEnable)) { - vpReduceRelayBaseSquelchEnable = sec.valueOr("vp_enable", false); + vpReduceRelayBaseSquelchEnable = sec.valueOr(Keys::kVpEnable, false); } else { @@ -818,97 +827,103 @@ Config::loadFromString(std::string const& fileContents) // Temporary squelching config for the peers selected as a source of // // validator messages. The config must be removed once squelching is // // made the default routing algorithm. // - vpReduceRelaySquelchMaxSelectedPeers = sec.valueOr("vp_base_squelch_max_selected_peers", 5); + vpReduceRelaySquelchMaxSelectedPeers = sec.valueOr(Keys::kVpBaseSquelchMaxSelectedPeers, 5); if (vpReduceRelaySquelchMaxSelectedPeers < 3) { - Throw("Invalid " SECTION_REDUCE_RELAY - " vp_base_squelch_max_selected_peers must be " - "greater than or equal to 3"); + Throw( + std::string("Invalid ") + Sections::kReduceRelay + + " vp_base_squelch_max_selected_peers must be " + "greater than or equal to 3"); } ///////////////// !!END OF TEMPORARY CODE BLOCK!! ///////////////////// - txReduceRelayEnable = sec.valueOr("tx_enable", false); - txReduceRelayMetrics = sec.valueOr("tx_metrics", false); - txReduceRelayMinPeers = sec.valueOr("tx_min_peers", 20); - txRelayPercentage = sec.valueOr("tx_relay_percentage", 25); + txReduceRelayEnable = sec.valueOr(Keys::kTxEnable, false); + txReduceRelayMetrics = sec.valueOr(Keys::kTxMetrics, false); + txReduceRelayMinPeers = sec.valueOr(Keys::kTxMinPeers, 20); + txRelayPercentage = sec.valueOr(Keys::kTxRelayPercentage, 25); if (txRelayPercentage < 10 || txRelayPercentage > 100 || txReduceRelayMinPeers < 10) { - Throw("Invalid " SECTION_REDUCE_RELAY - ", tx_min_peers must be greater than or equal to 10" - ", tx_relay_percentage must be greater than or equal to 10 " - "and less than or equal to 100"); + Throw( + std::string("Invalid ") + Sections::kReduceRelay + + ", tx_min_peers must be greater than or equal to 10" + ", tx_relay_percentage must be greater than or equal to 10 " + "and less than or equal to 100"); } } - if (getSingleSection(secConfig, SECTION_MAX_TRANSACTIONS, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kMaxTransactions, strTemp, j_)) { maxTransactions = std::clamp(beast::lexicalCastThrow(strTemp), kMinJobQueueTx, kMaxJobQueueTx); } - if (getSingleSection(secConfig, SECTION_SERVER_DOMAIN, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kServerDomain, strTemp, j_)) { if (!isProperlyFormedTomlDomain(strTemp)) { Throw( - "Invalid " SECTION_SERVER_DOMAIN + std::string("Invalid ") + Sections::kServerDomain + ": the domain name does not appear to meet the requirements."); } serverDomain = strTemp; } - if (exists(SECTION_OVERLAY)) + if (exists(Sections::kOverlay)) { - auto const sec = section(SECTION_OVERLAY); + auto const sec = section(Sections::kOverlay); using namespace std::chrono; try { - if (auto val = sec.get("max_unknown_time")) + if (auto val = sec.get(Keys::kMaxUnknownTime)) maxUnknownTime = seconds{beast::lexicalCastThrow(*val)}; } catch (...) { - Throw("Invalid value 'max_unknown_time' in " SECTION_OVERLAY - ": must be of the form '' representing seconds."); + Throw( + std::string("Invalid value 'max_unknown_time' in ") + Sections::kOverlay + + ": must be of the form '' representing seconds."); } if (maxUnknownTime < seconds{300} || maxUnknownTime > seconds{1800}) { Throw( - "Invalid value 'max_unknown_time' in " SECTION_OVERLAY + std::string("Invalid value 'max_unknown_time' in ") + Sections::kOverlay + ": the time must be between 300 and 1800 seconds, inclusive."); } try { - if (auto val = sec.get("max_diverged_time")) + if (auto val = sec.get(Keys::kMaxDivergedTime)) maxDivergedTime = seconds{beast::lexicalCastThrow(*val)}; } catch (...) { - Throw("Invalid value 'max_diverged_time' in " SECTION_OVERLAY - ": must be of the form '' representing seconds."); + Throw( + std::string("Invalid value 'max_diverged_time' in ") + Sections::kOverlay + + ": must be of the form '' representing seconds."); } if (maxDivergedTime < seconds{60} || maxDivergedTime > seconds{900}) { - Throw("Invalid value 'max_diverged_time' in " SECTION_OVERLAY - ": the time must be between 60 and 900 seconds, inclusive."); + Throw( + std::string("Invalid value 'max_diverged_time' in ") + Sections::kOverlay + + ": the time must be between 60 and 900 seconds, inclusive."); } } - if (getSingleSection(secConfig, SECTION_AMENDMENT_MAJORITY_TIME, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kAmendmentMajorityTime, strTemp, j_)) { using namespace std::chrono; boost::regex const re("^\\s*(\\d+)\\s*(minutes|hours|days|weeks)\\s*(\\s+.*)?$"); boost::smatch match; if (!boost::regex_match(strTemp, match, re)) { - Throw("Invalid " SECTION_AMENDMENT_MAJORITY_TIME - ", must be: [0-9]+ [minutes|hours|days|weeks]"); + Throw( + std::string("Invalid ") + Sections::kAmendmentMajorityTime + + ", must be: [0-9]+ [minutes|hours|days|weeks]"); } std::uint32_t const duration = beast::lexicalCastThrow(match[1].str()); @@ -932,13 +947,14 @@ Config::loadFromString(std::string const& fileContents) if (amendmentMajorityTime < minutes(15)) { - Throw("Invalid " SECTION_AMENDMENT_MAJORITY_TIME - ", the minimum amount of time an amendment must hold a " - "majority is 15 minutes"); + Throw( + std::string("Invalid ") + Sections::kAmendmentMajorityTime + + ", the minimum amount of time an amendment must hold a " + "majority is 15 minutes"); } } - if (getSingleSection(secConfig, SECTION_BETA_RPC_API, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kBetaRpcApi, strTemp, j_)) betaRpcApi = beast::lexicalCastThrow(strTemp); // Do not load trusted validator configuration for standalone mode @@ -954,14 +970,14 @@ Config::loadFromString(std::string const& fileContents) // if we can't find it. boost::filesystem::path validatorsFile; - if (getSingleSection(secConfig, SECTION_VALIDATORS_FILE, strTemp, j_)) + if (getSingleSection(secConfig, Sections::kValidatorsFile, strTemp, j_)) { validatorsFile = strTemp; if (validatorsFile.empty()) { - Throw("Invalid path specified in [" SECTION_VALIDATORS_FILE - "]"); + Throw( + std::string("Invalid path specified in [") + Sections::kValidatorsFile + "]"); } if (!validatorsFile.is_absolute() && !configDir.empty()) @@ -970,7 +986,7 @@ Config::loadFromString(std::string const& fileContents) if (!boost::filesystem::exists(validatorsFile)) { Throw( - "The file specified in [" SECTION_VALIDATORS_FILE + std::string("The file specified in [") + Sections::kValidatorsFile + "] " "does not exist: " + validatorsFile.string()); @@ -980,8 +996,8 @@ Config::loadFromString(std::string const& fileContents) !boost::filesystem::is_symlink(validatorsFile)) { Throw( - "Invalid file specified in [" SECTION_VALIDATORS_FILE "]: " + - validatorsFile.string()); + std::string("Invalid file specified in [") + Sections::kValidatorsFile + + "]: " + validatorsFile.string()); } } else if (!configDir.empty()) @@ -1018,41 +1034,44 @@ Config::loadFromString(std::string const& fileContents) auto iniFile = parseIniFile(data, true); - auto entries = getIniFileSection(iniFile, SECTION_VALIDATORS); + auto entries = getIniFileSection(iniFile, Sections::kValidators); if (entries != nullptr) - section(SECTION_VALIDATORS).append(*entries); + section(Sections::kValidators).append(*entries); - auto valKeyEntries = getIniFileSection(iniFile, SECTION_VALIDATOR_KEYS); + auto valKeyEntries = getIniFileSection(iniFile, Sections::kValidatorKeys); if (valKeyEntries != nullptr) - section(SECTION_VALIDATOR_KEYS).append(*valKeyEntries); + section(Sections::kValidatorKeys).append(*valKeyEntries); - auto valSiteEntries = getIniFileSection(iniFile, SECTION_VALIDATOR_LIST_SITES); + auto valSiteEntries = getIniFileSection(iniFile, Sections::kValidatorListSites); if (valSiteEntries != nullptr) - section(SECTION_VALIDATOR_LIST_SITES).append(*valSiteEntries); + section(Sections::kValidatorListSites).append(*valSiteEntries); - auto valListKeys = getIniFileSection(iniFile, SECTION_VALIDATOR_LIST_KEYS); + auto valListKeys = getIniFileSection(iniFile, Sections::kValidatorListKeys); if (valListKeys != nullptr) - section(SECTION_VALIDATOR_LIST_KEYS).append(*valListKeys); + section(Sections::kValidatorListKeys).append(*valListKeys); - auto valListThreshold = getIniFileSection(iniFile, SECTION_VALIDATOR_LIST_THRESHOLD); + auto valListThreshold = getIniFileSection(iniFile, Sections::kValidatorListThreshold); if (valListThreshold != nullptr) - section(SECTION_VALIDATOR_LIST_THRESHOLD).append(*valListThreshold); + section(Sections::kValidatorListThreshold).append(*valListThreshold); if ((entries == nullptr) && (valKeyEntries == nullptr) && (valListKeys == nullptr)) { Throw( - "The file specified in [" SECTION_VALIDATORS_FILE + std::string("The file specified in [") + Sections::kValidatorsFile + "] " - "does not contain a [" SECTION_VALIDATORS + "does not contain a [" + + Sections::kValidators + "], " - "[" SECTION_VALIDATOR_KEYS + "[" + + Sections::kValidatorKeys + "] or " - "[" SECTION_VALIDATOR_LIST_KEYS + "[" + + Sections::kValidatorListKeys + "]" " section: " + validatorsFile.string()); @@ -1060,7 +1079,7 @@ Config::loadFromString(std::string const& fileContents) } validatorListThreshold = [&]() -> std::optional { - auto const& listThreshold = section(SECTION_VALIDATOR_LIST_THRESHOLD); + auto const& listThreshold = section(Sections::kValidatorListThreshold); if (listThreshold.lines().empty()) { return std::nullopt; @@ -1073,34 +1092,38 @@ Config::loadFromString(std::string const& fileContents) { return std::nullopt; // NOTE: Explicitly ask for computed } - if (listThreshold > section(SECTION_VALIDATOR_LIST_KEYS).values().size()) + if (listThreshold > section(Sections::kValidatorListKeys).values().size()) { Throw( - "Value in config section " - "[" SECTION_VALIDATOR_LIST_THRESHOLD + std::string( + "Value in config section " + "[") + + Sections::kValidatorListThreshold + "] exceeds the number of configured list keys"); } return listThreshold; } Throw( - "Config section " - "[" SECTION_VALIDATOR_LIST_THRESHOLD "] should contain single value only"); + std::string( + "Config section " + "[") + + Sections::kValidatorListThreshold + "] should contain single value only"); }(); // Consolidate [validator_keys] and [validators] - section(SECTION_VALIDATORS).append(section(SECTION_VALIDATOR_KEYS).lines()); + section(Sections::kValidators).append(section(Sections::kValidatorKeys).lines()); - if (!section(SECTION_VALIDATOR_LIST_SITES).lines().empty() && - section(SECTION_VALIDATOR_LIST_KEYS).lines().empty()) + if (!section(Sections::kValidatorListSites).lines().empty() && + section(Sections::kValidatorListKeys).lines().empty()) { Throw( - "[" + std::string(SECTION_VALIDATOR_LIST_KEYS) + "] config section is missing"); + "[" + std::string(Sections::kValidatorListKeys) + "] config section is missing"); } } { - auto const part = section("features"); + auto const part = section(Sections::kFeatures); for (auto const& s : part.values()) { if (auto const f = getRegisteredFeature(s)) @@ -1182,15 +1205,15 @@ setupFeeVote(Section const& section) FeeSetup setup; { std::uint64_t temp = 0; - if (set(temp, "reference_fee", section) && + if (set(temp, Keys::kReferenceFee, section) && temp <= std::numeric_limits::max()) setup.referenceFee = temp; } { std::uint32_t temp = 0; - if (set(temp, "account_reserve", section)) + if (set(temp, Keys::kAccountReserve, section)) setup.accountReserve = temp; - if (set(temp, "owner_reserve", section)) + if (set(temp, Keys::kOwnerReserve, section)) setup.ownerReserve = temp; } return setup; @@ -1203,7 +1226,7 @@ setupDatabaseCon(Config const& c, std::optional j) setup.startUp = c.startUp; setup.standAlone = c.standalone(); - setup.dataDir = c.legacy("database_path"); + setup.dataDir = c.legacy(Sections::kDatabasePath); if (!setup.standAlone && setup.dataDir.empty()) { Throw("database_path must be set."); @@ -1211,7 +1234,7 @@ setupDatabaseCon(Config const& c, std::optional j) if (!setup.globalPragma) { - auto const& sqlite = c.section("sqlite"); + auto const& sqlite = c.section(Sections::kSqlite); auto result = std::make_unique>(); result->reserve(3); @@ -1328,11 +1351,11 @@ setupDatabaseCon(Config const& c, std::optional j) // TX Pragma int64_t pageSize = 4096; int64_t journalSizeLimit = 1582080; - if (c.exists("sqlite")) + if (c.exists(Sections::kSqlite)) { - auto& s = c.section("sqlite"); - set(journalSizeLimit, "journal_size_limit", s); - set(pageSize, "page_size", s); + auto& s = c.section(Sections::kSqlite); + set(journalSizeLimit, Keys::kJournalSizeLimit, s); + set(pageSize, Keys::kPageSize, s); if (pageSize < 512 || pageSize > 65536) Throw("Invalid page_size. Must be between 512 and 65536."); diff --git a/src/xrpld/overlay/Cluster.h b/src/xrpld/overlay/Cluster.h index 982f11aaae..a8c2083fbc 100644 --- a/src/xrpld/overlay/Cluster.h +++ b/src/xrpld/overlay/Cluster.h @@ -2,9 +2,9 @@ #include -#include #include #include +#include #include #include diff --git a/src/xrpld/overlay/detail/Cluster.cpp b/src/xrpld/overlay/detail/Cluster.cpp index 7855c9647d..15c8fa9c66 100644 --- a/src/xrpld/overlay/detail/Cluster.cpp +++ b/src/xrpld/overlay/detail/Cluster.cpp @@ -2,11 +2,11 @@ #include -#include #include #include #include #include +#include #include #include diff --git a/src/xrpld/overlay/detail/OverlayImpl.cpp b/src/xrpld/overlay/detail/OverlayImpl.cpp index b71cef6719..89c7dfe5eb 100644 --- a/src/xrpld/overlay/detail/OverlayImpl.cpp +++ b/src/xrpld/overlay/detail/OverlayImpl.cpp @@ -16,7 +16,6 @@ #include #include -#include #include #include #include @@ -36,6 +35,8 @@ #include #include #include +#include +#include #include #include #include @@ -96,7 +97,7 @@ static constexpr auto kDisabled = 0; static constexpr auto kOverlay = (1 << 0); static constexpr auto kServerInfo = (1 << 1); static constexpr auto kServerCounts = (1 << 2); -static constexpr auto kUNL = (1 << 3); +static constexpr auto kUnl = (1 << 3); } // namespace CrawlOptions //------------------------------------------------------------------------------ @@ -885,7 +886,7 @@ OverlayImpl::processCrawl(http_request_type const& req, Handoff& handoff) { msg.body()["counts"] = getServerCounts(); } - if ((setup_.crawlOptions & CrawlOptions::kUNL) != 0u) + if ((setup_.crawlOptions & CrawlOptions::kUnl) != 0u) { msg.body()["unl"] = getUnlInfo(); } @@ -1516,7 +1517,7 @@ setupOverlay(BasicConfig const& config, beast::Journal j) Overlay::Setup setup; { - auto const& section = config.section("overlay"); + auto const& section = config.section(Sections::kOverlay); setup.context = makeSslContext(""); set(setup.ipLimit, "ip_limit", section); @@ -1543,7 +1544,7 @@ setupOverlay(BasicConfig const& config, beast::Journal j) } { - auto const& section = config.section("crawl"); + auto const& section = config.section(Sections::kCrawl); auto const& values = section.values(); if (values.size() > 1) @@ -1569,33 +1570,33 @@ setupOverlay(BasicConfig const& config, beast::Journal j) if (crawlEnabled) { - if (get(section, "overlay", true)) + if (get(section, Keys::kOverlay, true)) { setup.crawlOptions |= CrawlOptions::kOverlay; } - if (get(section, "server", true)) + if (get(section, Keys::kServer, true)) { setup.crawlOptions |= CrawlOptions::kServerInfo; } - if (get(section, "counts", false)) + if (get(section, Keys::kCounts, false)) { setup.crawlOptions |= CrawlOptions::kServerCounts; } - if (get(section, "unl", true)) + if (get(section, Keys::kUnl, true)) { - setup.crawlOptions |= CrawlOptions::kUNL; + setup.crawlOptions |= CrawlOptions::kUnl; } } } { - auto const& section = config.section("vl"); + auto const& section = config.section(Sections::kVl); set(setup.vlEnabled, "enabled", section); } try { - auto id = config.legacy("network_id"); + auto id = config.legacy(Sections::kNetworkId); if (!id.empty()) { diff --git a/src/xrpld/peerfinder/detail/PeerfinderManager.cpp b/src/xrpld/peerfinder/detail/PeerfinderManager.cpp index f51f3630eb..9dbedfe4f1 100644 --- a/src/xrpld/peerfinder/detail/PeerfinderManager.cpp +++ b/src/xrpld/peerfinder/detail/PeerfinderManager.cpp @@ -7,13 +7,13 @@ #include #include -#include #include #include #include #include #include #include +#include #include #include diff --git a/src/xrpld/perflog/detail/PerfLogImp.cpp b/src/xrpld/perflog/detail/PerfLogImp.cpp index 60b6efc0a9..5ace4d8c8b 100644 --- a/src/xrpld/perflog/detail/PerfLogImp.cpp +++ b/src/xrpld/perflog/detail/PerfLogImp.cpp @@ -1,11 +1,12 @@ #include -#include #include #include #include #include #include +#include +#include #include #include #include @@ -489,7 +490,7 @@ setupPerfLog(Section const& section, boost::filesystem::path const& configDir) } std::uint64_t logInterval = 0; - if (getIfExists(section, "log_interval", logInterval)) + if (getIfExists(section, Keys::kLogInterval, logInterval)) setup.logInterval = std::chrono::seconds(logInterval); return setup; } diff --git a/src/xrpld/rpc/detail/ServerHandler.cpp b/src/xrpld/rpc/detail/ServerHandler.cpp index c73e474e18..5177c85738 100644 --- a/src/xrpld/rpc/detail/ServerHandler.cpp +++ b/src/xrpld/rpc/detail/ServerHandler.cpp @@ -1,7 +1,6 @@ #include #include -#include #include #include #include @@ -16,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -1128,16 +1128,16 @@ parsePorts(Config const& config, std::ostream& log) { std::vector result; - if (!config.exists("server")) + if (!config.exists(Sections::kServer)) { log << "Required section [server] is missing"; Throw(); } ParsedPort common; - parsePort(common, config["server"], log); + parsePort(common, config[Sections::kServer], log); - auto const& names = config.section("server").values(); + auto const& names = config.section(Sections::kServer).values(); result.reserve(names.size()); for (auto const& name : names) { @@ -1149,7 +1149,7 @@ parsePorts(Config const& config, std::ostream& log) // grpc ports are parsed by GRPCServer class. Do not validate // grpc port information in this file. - if (name == SECTION_PORT_GRPC) + if (name == Sections::kPortGrpc) continue; ParsedPort parsed = common; From 0fb1aca461c775b2f5e0334dcff9ded3571634d7 Mon Sep 17 00:00:00 2001 From: Vito Tumas <5780819+Tapanito@users.noreply.github.com> Date: Tue, 9 Jun 2026 19:02:06 +0200 Subject: [PATCH 5/9] refactor: Introduce XRPL_ASSERT_IF for amendment-gated assertions (#7378) Co-authored-by: xrplf-ai-reviewer[bot] <266832837+xrplf-ai-reviewer[bot]@users.noreply.github.com> --- include/xrpl/beast/utility/instrumentation.h | 12 +++ src/libxrpl/ledger/helpers/LendingHelpers.cpp | 84 +++++++++---------- src/libxrpl/ledger/helpers/MPTokenHelpers.cpp | 8 +- 3 files changed, 57 insertions(+), 47 deletions(-) diff --git a/include/xrpl/beast/utility/instrumentation.h b/include/xrpl/beast/utility/instrumentation.h index 39b80bc438..c20c42156a 100644 --- a/include/xrpl/beast/utility/instrumentation.h +++ b/include/xrpl/beast/utility/instrumentation.h @@ -11,6 +11,8 @@ // 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. +// NOTE: cond must not contain bare commas outside () or []. Commas inside {} +// are not protected by the preprocessor and would be parsed as extra arguments. #define ALWAYS(cond, message, ...) assert((message) && (cond)) #define ALWAYS_OR_UNREACHABLE(cond, message) assert((message) && (cond)) #define SOMETIMES(cond, message, ...) @@ -22,6 +24,8 @@ #define XRPL_ASSERT_PARTS(cond, function, description, ...) \ XRPL_ASSERT(cond, function " : " description) +#define XRPL_ASSERT_IF(guard, cond, message) XRPL_ASSERT(!(guard) || (cond), message) + // How to use the instrumentation macros: // // * XRPL_ASSERT if cond must be true but the line might not be reached during @@ -29,6 +33,14 @@ // * XRPL_ASSERT_PARTS is for convenience, and works like XRPL_ASSERT, but // splits the message param into "function" and "description", then joins // them with " : " before passing to XRPL_ASSERT. +// * XRPL_ASSERT_IF(guard, cond, message) asserts the implication +// `guard => cond`: it can only fail when guard is true (e.g. an amendment +// is enabled) and cond is false. Unlike `if (guard) XRPL_ASSERT(...)`, the +// assertion site is always evaluated, so the fuzzer registers it +// unconditionally; cond itself is short-circuited and only evaluated when +// guard is true. NOTE: do not rely on side effects in guard — in release +// builds the assertion body is stripped, and the compiler may optimize away +// a side-effect-free guard entirely. // * 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 diff --git a/src/libxrpl/ledger/helpers/LendingHelpers.cpp b/src/libxrpl/ledger/helpers/LendingHelpers.cpp index 15ebf33e46..0a195f9cbe 100644 --- a/src/libxrpl/ledger/helpers/LendingHelpers.cpp +++ b/src/libxrpl/ledger/helpers/LendingHelpers.cpp @@ -798,44 +798,44 @@ doOverpayment( // (P * factor) / factor round-trip can leave the new principal one // scale-unit high, so these equalities do not hold on the pre-amendment // code path and must be gated to match the fix they verify. - if (rules.enabled(fixCleanup3_2_0)) - { - // The valueChange returned by tryOverpayment satisfies - // valueChange = (newInterestDue - oldInterestDue) + untrackedInterest. - // Using the loan-state identity v = p + i + m and the adjacent - // `principal change agrees` assertion (dp = oldP - newP), this - // rearranges into three independently-computable terms: - // - // 1. TVO change beyond what principal repayment alone explains: - // newTVO - (oldTVO - dp) - // 2. Management fee released by re-amortization (positive when - // mfee decreased; zero when managementFeeRate == 0): - // oldMfee - newMfee - // 3. The overpayment's penalty interest part (= untrackedInterest - // for the overpayment path; see computeOverpaymentComponents): - // trackedInterestPart() - [[maybe_unused]] Number const tvoChange = newRoundedLoanState.valueOutstanding - - (totalValueOutstandingProxy - overpaymentComponents.trackedPrincipalDelta); - [[maybe_unused]] Number const managementFeeReleased = - managementFeeOutstandingProxy - newRoundedLoanState.managementFeeDue; - [[maybe_unused]] Number const interestPart = overpaymentComponents.trackedInterestPart(); + // + // The valueChange returned by tryOverpayment satisfies + // valueChange = (newInterestDue - oldInterestDue) + untrackedInterest. + // Using the loan-state identity v = p + i + m and the adjacent + // `principal change agrees` assertion (dp = oldP - newP), this + // rearranges into three independently-computable terms: + // + // 1. TVO change beyond what principal repayment alone explains: + // newTVO - (oldTVO - dp) + // 2. Management fee released by re-amortization (positive when + // mfee decreased; zero when managementFeeRate == 0): + // oldMfee - newMfee + // 3. The overpayment's penalty interest part (= untrackedInterest + // for the overpayment path; see computeOverpaymentComponents): + // trackedInterestPart() + bool const fix320Enabled = rules.enabled(fixCleanup3_2_0); + XRPL_ASSERT_IF( + fix320Enabled, + overpaymentComponents.trackedPrincipalDelta == + principalOutstandingProxy - newRoundedLoanState.principalOutstanding, + "xrpl::detail::doOverpayment : principal change agrees"); - XRPL_ASSERT_PARTS( - overpaymentComponents.trackedPrincipalDelta == - principalOutstandingProxy - newRoundedLoanState.principalOutstanding, - "xrpl::detail::doOverpayment", - "principal change agrees"); + XRPL_ASSERT_IF( + fix320Enabled, + [&] { + Number const tvoChange = newRoundedLoanState.valueOutstanding - + (totalValueOutstandingProxy - overpaymentComponents.trackedPrincipalDelta); + Number const managementFeeReleased = + managementFeeOutstandingProxy - newRoundedLoanState.managementFeeDue; + Number const interestPart = overpaymentComponents.trackedInterestPart(); + return loanPaymentParts.valueChange == tvoChange + managementFeeReleased + interestPart; + }(), + "xrpl::detail::doOverpayment : interest paid agrees"); - XRPL_ASSERT_PARTS( - loanPaymentParts.valueChange == tvoChange + managementFeeReleased + interestPart, - "xrpl::detail::doOverpayment", - "interest paid agrees"); - - XRPL_ASSERT_PARTS( - overpaymentComponents.trackedPrincipalDelta == loanPaymentParts.principalPaid, - "xrpl::detail::doOverpayment", - "principal payment matches"); - } + XRPL_ASSERT_IF( + fix320Enabled, + overpaymentComponents.trackedPrincipalDelta == loanPaymentParts.principalPaid, + "xrpl::detail::doOverpayment : principal payment matches"); // All validations passed, so update the proxy objects (which will // modify the actual Loan ledger object) @@ -1326,13 +1326,11 @@ computeOverpaymentComponents( TenthBips32 const overpaymentFeeRate, TenthBips16 const managementFeeRate) { - if (rules.enabled(fixCleanup3_2_0)) - { - XRPL_ASSERT( - overpayment > 0 && isRounded(asset, overpayment, loanScale), - "xrpl::detail::computeOverpaymentComponents : valid overpayment " - "amount"); - } + XRPL_ASSERT_IF( + rules.enabled(fixCleanup3_2_0), + overpayment > 0 && isRounded(asset, overpayment, loanScale), + "xrpl::detail::computeOverpaymentComponents : valid overpayment " + "amount"); // First, deduct the fixed overpayment fee from the total amount. // This reduces the effective payment that will be applied to the loan. diff --git a/src/libxrpl/ledger/helpers/MPTokenHelpers.cpp b/src/libxrpl/ledger/helpers/MPTokenHelpers.cpp index 387116d820..8b3385471d 100644 --- a/src/libxrpl/ledger/helpers/MPTokenHelpers.cpp +++ b/src/libxrpl/ledger/helpers/MPTokenHelpers.cpp @@ -736,10 +736,10 @@ unlockEscrowMPT( STAmount const& grossAmount, beast::Journal j) { - if (!view.rules().enabled(fixTokenEscrowV1)) - { - XRPL_ASSERT(netAmount == grossAmount, "xrpl::unlockEscrowMPT : netAmount == grossAmount"); - } + XRPL_ASSERT_IF( + !view.rules().enabled(fixTokenEscrowV1), + netAmount == grossAmount, + "xrpl::unlockEscrowMPT : netAmount == grossAmount"); auto const& issuer = netAmount.getIssuer(); auto const& mptIssue = netAmount.get(); From fccb109e4829a3608f3b35f97586ccd41452061a Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Tue, 9 Jun 2026 18:36:17 +0100 Subject: [PATCH 6/9] feat: Use C++ 23 standard (#7431) --- .clang-tidy | 2 +- .../workflows/reusable-build-test-config.yml | 2 +- BUILD.md | 14 +- CMakeLists.txt | 2 +- conan/lockfile/linux.profile | 2 +- conan/lockfile/macos.profile | 2 +- conan/lockfile/windows.profile | 2 +- conan/profiles/default | 2 +- include/xrpl/basics/Expected.h | 248 ------------------ include/xrpl/basics/base_uint.h | 8 +- include/xrpl/beast/hash/xxhasher.h | 3 + include/xrpl/ledger/helpers/AMMHelpers.h | 9 +- .../xrpl/ledger/helpers/AccountRootHelpers.h | 4 +- include/xrpl/ledger/helpers/LendingHelpers.h | 5 +- include/xrpl/protocol/STTx.h | 16 +- include/xrpl/protocol/XChainAttestations.h | 2 +- include/xrpl/protocol/detail/STVar.h | 2 +- include/xrpl/protocol/tokens.h | 4 +- include/xrpl/tx/SignerEntries.h | 4 +- .../transactors/token/MPTokenIssuanceCreate.h | 5 +- .../xrpl/tx/transactors/vault/VaultClawback.h | 4 +- src/libxrpl/ledger/helpers/AMMHelpers.cpp | 32 +-- .../ledger/helpers/AccountRootHelpers.cpp | 6 +- .../ledger/helpers/CredentialHelpers.cpp | 6 +- src/libxrpl/ledger/helpers/LendingHelpers.cpp | 48 ++-- src/libxrpl/protocol/STTx.cpp | 46 ++-- src/libxrpl/protocol/tokens.cpp | 34 +-- src/libxrpl/tx/SignerEntries.cpp | 8 +- .../tx/transactors/bridge/XChainBridge.cpp | 50 ++-- src/libxrpl/tx/transactors/dex/AMMBid.cpp | 8 +- .../lending/LoanBrokerCoverClawback.cpp | 18 +- .../tx/transactors/lending/LoanPay.cpp | 4 +- .../tx/transactors/nft/NFTokenMint.cpp | 10 +- .../token/MPTokenIssuanceCreate.cpp | 14 +- .../tx/transactors/vault/VaultClawback.cpp | 22 +- src/test/app/Delegate_test.cpp | 4 +- src/test/app/GRPCServerTLS_test.cpp | 26 +- src/test/app/Invariants_test.cpp | 5 +- src/test/app/MultiSign_test.cpp | 4 +- src/test/app/NFTokenBurn_test.cpp | 8 +- src/test/app/NetworkOPs_test.cpp | 2 +- src/test/app/ValidatorSite_test.cpp | 12 +- src/test/basics/Expected_test.cpp | 221 ---------------- src/test/consensus/Consensus_test.cpp | 9 +- src/test/jtx/CheckMessageLogs.h | 2 +- src/test/jtx/directory.h | 4 +- src/test/jtx/impl/directory.cpp | 20 +- src/test/nodestore/NuDBFactory_test.cpp | 18 +- src/test/overlay/reduce_relay_test.cpp | 2 +- src/test/server/ServerStatus_test.cpp | 14 +- src/test/server/Server_test.cpp | 16 +- src/xrpld/overlay/detail/PeerImp.cpp | 2 +- src/xrpld/rpc/detail/RPCLedgerHelpers.cpp | 29 +- src/xrpld/rpc/detail/RPCLedgerHelpers.h | 5 +- src/xrpld/rpc/detail/TransactionSign.cpp | 10 +- src/xrpld/rpc/handlers/ledger/Ledger.cpp | 6 +- src/xrpld/rpc/handlers/ledger/LedgerEntry.cpp | 156 +++++------ .../rpc/handlers/ledger/LedgerEntryHelpers.h | 37 +-- src/xrpld/rpc/handlers/orderbook/AMMInfo.cpp | 28 +- .../server_info/ServerDefinitions.cpp | 2 +- .../rpc/handlers/transaction/Simulate.cpp | 10 +- src/xrpld/rpc/handlers/transaction/Submit.cpp | 6 +- 62 files changed, 412 insertions(+), 894 deletions(-) delete mode 100644 include/xrpl/basics/Expected.h delete mode 100644 src/test/basics/Expected_test.cpp diff --git a/.clang-tidy b/.clang-tidy index 2d72eae701..e09d326916 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -153,7 +153,7 @@ Checks: "-*, readability-use-std-min-max " # --- -# readability-inconsistent-declaration-parameter-name, # in this codebase this check will break a lot of arg names +# readability-inconsistent-declaration-parameter-name, # In this codebase this check will break a lot of arg names # readability-static-accessed-through-instance, # this check is probably unnecessary. It makes the code less readable # --- diff --git a/.github/workflows/reusable-build-test-config.yml b/.github/workflows/reusable-build-test-config.yml index d53cf97a39..8cb5f8c46a 100644 --- a/.github/workflows/reusable-build-test-config.yml +++ b/.github/workflows/reusable-build-test-config.yml @@ -82,7 +82,7 @@ jobs: name: ${{ inputs.config_name }} runs-on: ${{ fromJSON(inputs.runs_on) }} container: ${{ inputs.image != '' && inputs.image || null }} - timeout-minutes: ${{ inputs.sanitizers != '' && 360 || 60 }} + timeout-minutes: ${{ inputs.sanitizers != '' && 360 || 90 }} env: # Use a namespace to keep the objects separate for each configuration. CCACHE_NAMESPACE: ${{ inputs.config_name }} diff --git a/BUILD.md b/BUILD.md index 1d3fc8f774..662ba0d33d 100644 --- a/BUILD.md +++ b/BUILD.md @@ -45,14 +45,14 @@ found here](./docs/build/environment.md). It is possible to build with Conan 1.60+, but the instructions are significantly different, which is why we are not recommending it. -`xrpld` is written in the C++20 dialect and includes the `` header. -The [minimum compiler versions][2] required are: +`xrpld` is written in the C++23 dialect and includes the `` header. +The [tested compiler versions][2] are: | Compiler | Version | | ----------- | --------- | -| GCC | 12 | -| Clang | 16 | -| Apple Clang | 16 | +| GCC | 15 | +| Clang | 22 | +| Apple Clang | 17 | | MSVC | 19.44[^3] | ### Linux @@ -232,11 +232,11 @@ name and then creating a new `default` profile for a different compiler. #### Select language The default profile created by Conan will typically select different C++ dialect -than C++20 used by this project. You should set `20` in the profile line +than C++23 used by this project. You should set `23` in the profile line starting with `compiler.cppstd=`. For example: ```bash -sed -i.bak -e 's|^compiler\.cppstd=.*$|compiler.cppstd=20|' $(conan config home)/profiles/default +sed -i.bak -e 's|^compiler\.cppstd=.*$|compiler.cppstd=23|' $(conan config home)/profiles/default ``` #### Select standard library in Linux diff --git a/CMakeLists.txt b/CMakeLists.txt index d315a5dcec..3dbe60a220 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -15,7 +15,7 @@ list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") project(xrpl) set(CMAKE_CXX_EXTENSIONS OFF) -set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD 23) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) diff --git a/conan/lockfile/linux.profile b/conan/lockfile/linux.profile index 25ad5988c5..ea9f66de69 100644 --- a/conan/lockfile/linux.profile +++ b/conan/lockfile/linux.profile @@ -2,7 +2,7 @@ arch=x86_64 build_type=Release compiler=gcc -compiler.cppstd=20 +compiler.cppstd=23 compiler.libcxx=libstdc++11 compiler.version=13 os=Linux diff --git a/conan/lockfile/macos.profile b/conan/lockfile/macos.profile index 332a0c143d..f223627c26 100644 --- a/conan/lockfile/macos.profile +++ b/conan/lockfile/macos.profile @@ -2,7 +2,7 @@ arch=armv8 build_type=Release compiler=apple-clang -compiler.cppstd=20 +compiler.cppstd=23 compiler.libcxx=libc++ compiler.version=17.0 os=Macos diff --git a/conan/lockfile/windows.profile b/conan/lockfile/windows.profile index 4bb266a62e..b3a8fed4f3 100644 --- a/conan/lockfile/windows.profile +++ b/conan/lockfile/windows.profile @@ -2,7 +2,7 @@ arch=x86_64 build_type=Release compiler=msvc -compiler.cppstd=20 +compiler.cppstd=23 compiler.runtime=dynamic compiler.runtime_type=Release compiler.version=194 diff --git a/conan/profiles/default b/conan/profiles/default index cde59f7f3b..e0a88ebca1 100644 --- a/conan/profiles/default +++ b/conan/profiles/default @@ -12,7 +12,7 @@ arch={{ arch }} build_type=Debug compiler={{compiler}} compiler.version={{ compiler_version }} -compiler.cppstd=20 +compiler.cppstd=23 {% if os == "Windows" %} compiler.runtime=static {% else %} diff --git a/include/xrpl/basics/Expected.h b/include/xrpl/basics/Expected.h deleted file mode 100644 index 3796151777..0000000000 --- a/include/xrpl/basics/Expected.h +++ /dev/null @@ -1,248 +0,0 @@ -#pragma once - -#include - -#include - -#include - -namespace xrpl { - -/** Expected is an approximation of std::expected (hoped for in C++23) - - See: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p0323r10.html - - The implementation is entirely based on boost::outcome_v2::result. -*/ - -// Exception thrown by an invalid access to Expected. -struct BadExpectedAccess : public std::runtime_error -{ - BadExpectedAccess() : runtime_error("bad expected access") - { - } -}; - -namespace detail { - -// Custom policy for Expected. Always throw on an invalid access. -struct ThrowPolicy : public boost::outcome_v2::policy::base -{ - template - static constexpr void - // NOLINTNEXTLINE(readability-identifier-naming) - wide_value_check(Impl&& self) - { - if (!base::_has_value(std::forward(self))) - Throw(); - } - - template - static constexpr void - // NOLINTNEXTLINE(readability-identifier-naming) - wide_error_check(Impl&& self) - { - if (!base::_has_error(std::forward(self))) - Throw(); - } - - template - static constexpr void - // NOLINTNEXTLINE(readability-identifier-naming) - wide_exception_check(Impl&& self) - { - if (!base::_has_exception(std::forward(self))) - Throw(); - } -}; - -} // namespace detail - -// Definition of Unexpected, which is used to construct the unexpected -// return type of an Expected. -template -class Unexpected -{ -public: - static_assert(!std::is_same_v, "E must not be void"); - - Unexpected() = delete; - - constexpr explicit Unexpected(E const& e) : val_(e) - { - } - - constexpr explicit Unexpected(E&& e) : val_(std::move(e)) - { - } - - [[nodiscard]] constexpr E const& - value() const& - { - return val_; - } - - constexpr E& - value() & - { - return val_; - } - - constexpr E&& - value() && - { - return std::move(val_); - } - - [[nodiscard]] constexpr E const&& - value() const&& - { - return std::move(val_); - } - -private: - E val_; -}; - -// Unexpected deduction guide that converts array to const*. -template -Unexpected(E (&)[N]) -> Unexpected; - -// Definition of Expected. All of the machinery comes from boost::result. -template -class [[nodiscard]] Expected : private boost::outcome_v2::result -{ - using Base = boost::outcome_v2::result; - -public: - template - requires std::convertible_to - 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(boost::outcome_v2::in_place_type_t{}, std::move(e.value())) - { - } - - [[nodiscard]] constexpr bool - // NOLINTNEXTLINE(readability-identifier-naming) - has_value() const - { - return Base::has_value(); - } - - [[nodiscard]] constexpr T const& - value() const - { - return Base::value(); - } - - constexpr T& - value() - { - return Base::value(); - } - - [[nodiscard]] constexpr E const& - error() const& - { - return Base::error(); - } - - [[nodiscard]] constexpr E& - error() & - { - return Base::error(); - } - - [[nodiscard]] constexpr E&& - error() && - { - return std::move(Base::error()); - } - - constexpr explicit - operator bool() const - { - return has_value(); - } - - // Add operator* and operator-> so the Expected API looks a bit more like - // what std::expected is likely to look like. See: - // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p0323r10.html - [[nodiscard]] constexpr T& - operator*() - { - return this->value(); - } - - [[nodiscard]] constexpr T const& - operator*() const - { - return this->value(); - } - - [[nodiscard]] constexpr T* - operator->() - { - return &this->value(); - } - - [[nodiscard]] constexpr T const* - operator->() const - { - return &this->value(); - } -}; - -// Specialization of Expected. Allows returning either success -// (without a value) or the reason for the failure. -template -class [[nodiscard]] -Expected : private boost::outcome_v2::result -{ - using Base = boost::outcome_v2::result; - -public: - // The default constructor makes a successful Expected. - // This aligns with std::expected behavior proposed in P0323R10. - constexpr Expected() : Base(boost::outcome_v2::success()) - { - } - - template - requires std::convertible_to && (!std::is_reference_v) - constexpr Expected(Unexpected e) : Base(E(std::move(e.value()))) - { - } - - [[nodiscard]] constexpr E const& - error() const& - { - return Base::error(); - } - - [[nodiscard]] constexpr E& - error() & - { - return Base::error(); - } - - [[nodiscard]] constexpr E&& - error() && - { - return std::move(Base::error()); - } - - constexpr explicit - operator bool() const - { - return Base::has_value(); - } -}; - -} // namespace xrpl diff --git a/include/xrpl/basics/base_uint.h b/include/xrpl/basics/base_uint.h index 93a9ced15e..93520ff699 100644 --- a/include/xrpl/basics/base_uint.h +++ b/include/xrpl/basics/base_uint.h @@ -5,7 +5,6 @@ #pragma once -#include #include #include #include @@ -20,6 +19,7 @@ #include #include #include +#include #include namespace xrpl { @@ -177,7 +177,7 @@ private: BadChar, }; - constexpr Expected + constexpr std::expected parseFromStringView(std::string_view sv) noexcept { // Local lambda that converts a single hex char to four bits and @@ -216,7 +216,7 @@ private: } if (sv.size() != size() * 2) - return Unexpected(ParseResult::BadLength); + return std::unexpected(ParseResult::BadLength); std::size_t i = 0u; auto in = sv.begin(); @@ -227,7 +227,7 @@ private: { if (auto const result = hexCharToUInt(*in++, shift, accum); result != ParseResult::Okay) - return Unexpected(result); + return std::unexpected(result); } ret[i++] = accum; } diff --git a/include/xrpl/beast/hash/xxhasher.h b/include/xrpl/beast/hash/xxhasher.h index 95a67dede0..978bbc6917 100644 --- a/include/xrpl/beast/hash/xxhasher.h +++ b/include/xrpl/beast/hash/xxhasher.h @@ -7,8 +7,11 @@ #include #include #include +#include +#include #include #include +#include namespace beast { diff --git a/include/xrpl/ledger/helpers/AMMHelpers.h b/include/xrpl/ledger/helpers/AMMHelpers.h index 61d6e9d2fb..d21e50e7cb 100644 --- a/include/xrpl/ledger/helpers/AMMHelpers.h +++ b/include/xrpl/ledger/helpers/AMMHelpers.h @@ -1,6 +1,5 @@ #pragma once -#include #include #include #include @@ -18,6 +17,8 @@ #include #include +#include + namespace xrpl { namespace detail { @@ -741,7 +742,7 @@ ammPoolHolds( * provided then they are used as the AMM token pair issues. * Otherwise the missing issues are fetched from ammSle. */ -Expected, TER> +std::expected, TER> ammHolds( ReadView const& view, SLE const& ammSle, @@ -801,14 +802,14 @@ initializeFeeAuctionVote( * otherwise. Return tecINTERNAL if encountered an unexpected condition, * for instance Liquidity Provider has more than one LPToken trustline. */ -Expected +std::expected isOnlyLiquidityProvider(ReadView const& view, Issue const& ammIssue, AccountID const& lpAccount); /** Due to rounding, the LPTokenBalance of the last LP might * not match the LP's trustline balance. If it's within the tolerance, * update LPTokenBalance to match the LP's trustline balance. */ -Expected +std::expected verifyAndAdjustLPTokenBalance( Sandbox& sb, STAmount const& lpTokens, diff --git a/include/xrpl/ledger/helpers/AccountRootHelpers.h b/include/xrpl/ledger/helpers/AccountRootHelpers.h index c02cad98d8..cf6082d533 100644 --- a/include/xrpl/ledger/helpers/AccountRootHelpers.h +++ b/include/xrpl/ledger/helpers/AccountRootHelpers.h @@ -1,6 +1,5 @@ #pragma once -#include #include #include #include @@ -9,6 +8,7 @@ #include #include +#include #include #include @@ -91,7 +91,7 @@ isPseudoAccount( * before using a field. The amendment check is **not** performed in * createPseudoAccount. */ -[[nodiscard]] Expected +[[nodiscard]] std::expected createPseudoAccount(ApplyView& view, uint256 const& pseudoOwnerKey, SField const& ownerField); /** Checks the destination and tag. diff --git a/include/xrpl/ledger/helpers/LendingHelpers.h b/include/xrpl/ledger/helpers/LendingHelpers.h index 32f94ee277..8de945233b 100644 --- a/include/xrpl/ledger/helpers/LendingHelpers.h +++ b/include/xrpl/ledger/helpers/LendingHelpers.h @@ -4,6 +4,7 @@ #include #include +#include #include namespace xrpl { @@ -397,7 +398,7 @@ struct LoanStateDeltas nonNegative(); }; -Expected, TER> +std::expected, TER> tryOverpayment( Rules const& rules, Asset const& asset, @@ -523,7 +524,7 @@ isRounded(Asset const& asset, Number const& value, std::int32_t scale); // potential extra work at the end. enum class LoanPaymentType { Regular = 0, Late, Full, Overpayment }; -Expected +std::expected loanMakePayment( Asset const& asset, ApplyView& view, diff --git a/include/xrpl/protocol/STTx.h b/include/xrpl/protocol/STTx.h index 4deedfafb7..659fede31d 100644 --- a/include/xrpl/protocol/STTx.h +++ b/include/xrpl/protocol/STTx.h @@ -1,6 +1,5 @@ #pragma once -#include #include #include #include @@ -11,6 +10,7 @@ #include +#include #include namespace xrpl { @@ -108,10 +108,10 @@ public: @param rules The current ledger rules. @return `true` if valid signature. If invalid, the error message string. */ - Expected + std::expected checkSign(Rules const& rules) const; - Expected + std::expected checkBatchSign(Rules const& rules) const; // SQL Functions with metadata. @@ -138,19 +138,19 @@ private: Will be *this more often than not. @return `true` if valid signature. If invalid, the error message string. */ - Expected + std::expected checkSign(Rules const& rules, STObject const& sigObject) const; - Expected + std::expected checkSingleSign(STObject const& sigObject) const; - Expected + std::expected checkMultiSign(Rules const& rules, STObject const& sigObject) const; - Expected + std::expected checkBatchSingleSign(STObject const& batchSigner) const; - Expected + std::expected checkBatchMultiSign(STObject const& batchSigner, Rules const& rules) const; STBase* diff --git a/include/xrpl/protocol/XChainAttestations.h b/include/xrpl/protocol/XChainAttestations.h index 993f478b5e..457af727a2 100644 --- a/include/xrpl/protocol/XChainAttestations.h +++ b/include/xrpl/protocol/XChainAttestations.h @@ -1,7 +1,6 @@ #pragma once #include -#include #include #include #include @@ -15,6 +14,7 @@ #include #include +#include #include #include diff --git a/include/xrpl/protocol/detail/STVar.h b/include/xrpl/protocol/detail/STVar.h index 98a0b8dcd2..71077d4b33 100644 --- a/include/xrpl/protocol/detail/STVar.h +++ b/include/xrpl/protocol/detail/STVar.h @@ -37,7 +37,7 @@ private: // The largest "small object" we can accommodate static constexpr std::size_t kMaxSize = 72; - std::aligned_storage::type d_ = {}; + alignas(std::max_align_t) std::byte d_[kMaxSize] = {}; STBase* p_ = nullptr; public: diff --git a/include/xrpl/protocol/tokens.h b/include/xrpl/protocol/tokens.h index 125cfe8583..67cb25c7fb 100644 --- a/include/xrpl/protocol/tokens.h +++ b/include/xrpl/protocol/tokens.h @@ -1,10 +1,10 @@ #pragma once -#include #include #include #include +#include #include #include #include @@ -13,7 +13,7 @@ namespace xrpl { template -using B58Result = Expected; +using B58Result = std::expected; enum class TokenType : std::uint8_t { None = 1, // unused diff --git a/include/xrpl/tx/SignerEntries.h b/include/xrpl/tx/SignerEntries.h index 91fc4bd030..af0c9b9d28 100644 --- a/include/xrpl/tx/SignerEntries.h +++ b/include/xrpl/tx/SignerEntries.h @@ -1,11 +1,11 @@ #pragma once -#include // #include // beast::Journal #include // temMALFORMED #include // AccountID #include // NotTEC +#include #include #include @@ -60,7 +60,7 @@ public: // obj Contains a SignerEntries field that is an STArray. // journal For reporting error conditions. // annotation Source of SignerEntries, like "ledger" or "transaction". - static Expected, NotTEC> + static std::expected, NotTEC> deserialize(STObject const& obj, beast::Journal journal, std::string_view annotation); }; diff --git a/include/xrpl/tx/transactors/token/MPTokenIssuanceCreate.h b/include/xrpl/tx/transactors/token/MPTokenIssuanceCreate.h index a706c71e18..d946587e32 100644 --- a/include/xrpl/tx/transactors/token/MPTokenIssuanceCreate.h +++ b/include/xrpl/tx/transactors/token/MPTokenIssuanceCreate.h @@ -1,9 +1,10 @@ #pragma once -#include #include #include +#include + namespace xrpl { // NOLINTBEGIN(readability-redundant-member-init) @@ -61,7 +62,7 @@ public: ReadView const& view, beast::Journal const& j) override; - static Expected + static std::expected create(ApplyView& view, beast::Journal journal, MPTCreateArgs const& args); }; diff --git a/include/xrpl/tx/transactors/vault/VaultClawback.h b/include/xrpl/tx/transactors/vault/VaultClawback.h index b8032809ee..2ff97abca2 100644 --- a/include/xrpl/tx/transactors/vault/VaultClawback.h +++ b/include/xrpl/tx/transactors/vault/VaultClawback.h @@ -2,6 +2,8 @@ #include +#include + namespace xrpl { class VaultClawback : public Transactor @@ -34,7 +36,7 @@ public: beast::Journal const& j) override; private: - Expected, TER> + std::expected, TER> assetsToClawback( SLE::ref vault, SLE::const_ref sleShareIssuance, diff --git a/src/libxrpl/ledger/helpers/AMMHelpers.cpp b/src/libxrpl/ledger/helpers/AMMHelpers.cpp index fe6d022490..a59b8e4436 100644 --- a/src/libxrpl/ledger/helpers/AMMHelpers.cpp +++ b/src/libxrpl/ledger/helpers/AMMHelpers.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -34,6 +33,7 @@ #include #include #include +#include #include #include #include @@ -433,7 +433,7 @@ ammPoolHolds( return std::make_pair(assetInBalance, assetOutBalance); } -Expected, TER> +std::expected, TER> ammHolds( ReadView const& view, SLE const& ammSle, @@ -489,7 +489,7 @@ ammHolds( return std::make_optional(std::make_pair(asset1, asset2)); }(); if (!assets) - return Unexpected(tecAMM_INVALID_TOKENS); + return std::unexpected(tecAMM_INVALID_TOKENS); auto const [amount1, amount2] = ammPoolHolds( view, ammSle.getAccountID(sfAccount), @@ -821,7 +821,7 @@ initializeFeeAuctionVote( auctionSlot.makeFieldAbsent(sfAuthAccounts); } -Expected +std::expected isOnlyLiquidityProvider(ReadView const& view, Issue const& ammIssue, AccountID const& lpAccount) { // Liquidity Provider (LP) must have one LPToken trustline @@ -852,18 +852,18 @@ isOnlyLiquidityProvider(ReadView const& view, Issue const& ammIssue, AccountID c { auto const ownerDir = view.read(currentIndex); if (!ownerDir) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE for (auto const& key : ownerDir->getFieldV256(sfIndexes)) { auto const sle = view.read(keylet::child(key)); if (!sle) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE auto const entryType = sle->getFieldU16(sfLedgerEntryType); // Only one AMM object if (entryType == ltAMM) { if (hasAMM) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE hasAMM = true; continue; } @@ -873,7 +873,7 @@ isOnlyLiquidityProvider(ReadView const& view, Issue const& ammIssue, AccountID c continue; } if (entryType != ltRIPPLE_STATE) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE auto const lowLimit = sle->getFieldAmount(sfLowLimit); auto const highLimit = sle->getFieldAmount(sfHighLimit); auto const isLPTrustline = @@ -889,12 +889,12 @@ isOnlyLiquidityProvider(ReadView const& view, Issue const& ammIssue, AccountID c { // LP has exactly one LPToken trustline if (++nLPTokenTrustLines > 1) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE } // AMM account has at most two IOU trustlines else if (++nIOUTrustLines > 2) { - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE } } // Another Liquidity Provider LPToken trustline @@ -905,7 +905,7 @@ isOnlyLiquidityProvider(ReadView const& view, Issue const& ammIssue, AccountID c // AMM account has at most two IOU trustlines else if (++nIOUTrustLines > 2) { - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE } } auto const uNodeNext = ownerDir->getFieldU64(sfIndexNext); @@ -913,15 +913,15 @@ isOnlyLiquidityProvider(ReadView const& view, Issue const& ammIssue, AccountID c { if (nLPTokenTrustLines != 1 || (nIOUTrustLines == 0 && nMPT == 0) || (nIOUTrustLines > 2 || nMPT > 2) || (nIOUTrustLines + nMPT) > 2) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE return true; } currentIndex = keylet::page(root, uNodeNext); } - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE } -Expected +std::expected verifyAndAdjustLPTokenBalance( Sandbox& sb, STAmount const& lpTokens, @@ -931,7 +931,7 @@ verifyAndAdjustLPTokenBalance( auto const res = isOnlyLiquidityProvider(sb, lpTokens.get(), account); if (!res.has_value()) { - return Unexpected(res.error()); + return std::unexpected(res.error()); } if (res.value()) @@ -944,7 +944,7 @@ verifyAndAdjustLPTokenBalance( } else { - return Unexpected(tecAMM_INVALID_TOKENS); + return std::unexpected(tecAMM_INVALID_TOKENS); } } return true; diff --git a/src/libxrpl/ledger/helpers/AccountRootHelpers.cpp b/src/libxrpl/ledger/helpers/AccountRootHelpers.cpp index 1634de93c9..1c4acc7bc4 100644 --- a/src/libxrpl/ledger/helpers/AccountRootHelpers.cpp +++ b/src/libxrpl/ledger/helpers/AccountRootHelpers.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -22,6 +21,7 @@ #include #include +#include #include #include #include @@ -202,7 +202,7 @@ isPseudoAccount(SLE::const_pointer sleAcct, std::set const& pseud }) > 0; } -Expected +std::expected createPseudoAccount(ApplyView& view, uint256 const& pseudoOwnerKey, SField const& ownerField) { [[maybe_unused]] @@ -216,7 +216,7 @@ createPseudoAccount(ApplyView& view, uint256 const& pseudoOwnerKey, SField const auto const accountId = pseudoAccountAddress(view, pseudoOwnerKey); if (accountId == beast::kZero) - return Unexpected(tecDUPLICATE); + return std::unexpected(tecDUPLICATE); // Create pseudo-account. auto account = std::make_shared(keylet::account(accountId)); diff --git a/src/libxrpl/ledger/helpers/CredentialHelpers.cpp b/src/libxrpl/ledger/helpers/CredentialHelpers.cpp index 28b50b51d6..ca5876f88a 100644 --- a/src/libxrpl/ledger/helpers/CredentialHelpers.cpp +++ b/src/libxrpl/ledger/helpers/CredentialHelpers.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -24,6 +23,7 @@ #include #include +#include #include #include #include @@ -43,7 +43,7 @@ checkExpired(SLE const& sleCredential, NetClock::time_point const& closed) } [[nodiscard]] -static Expected +static std::expected removeExpired(ApplyView& view, STVector256 const& arr, beast::Journal const j) { auto const closeTime = view.header().parentCloseTime; @@ -61,7 +61,7 @@ removeExpired(ApplyView& view, STVector256 const& arr, beast::Journal const j) // delete expired credentials even if the transaction failed auto const err = deleteSLE(view, sleCred, j); if (view.rules().enabled(fixCleanup3_1_3) && !isTesSuccess(err)) - return Unexpected(err); + return std::unexpected(err); foundExpired = true; } } diff --git a/src/libxrpl/ledger/helpers/LendingHelpers.cpp b/src/libxrpl/ledger/helpers/LendingHelpers.cpp index 0a195f9cbe..676b473132 100644 --- a/src/libxrpl/ledger/helpers/LendingHelpers.cpp +++ b/src/libxrpl/ledger/helpers/LendingHelpers.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -25,6 +24,7 @@ #include #include #include +#include #include #include @@ -514,7 +514,7 @@ doPayment( * The function preserves accumulated rounding errors across the re-amortization * to ensure the loan state remains consistent with its payment history. */ -Expected, TER> +std::expected, TER> tryOverpayment( Rules const& rules, Asset const& asset, @@ -643,7 +643,7 @@ tryOverpayment( JLOG(j.warn()) << "Principal overpayment would cause the loan to be in " "an invalid state. Ignore the overpayment"; - return Unexpected(tesSUCCESS); + return std::unexpected(tesSUCCESS); } // Validate that all computed properties are reasonable. These checks should @@ -660,7 +660,7 @@ tryOverpayment( << ", PeriodicPayment : " << newLoanProperties.periodicPayment << ", ManagementFeeOwedToBroker: " << newLoanProperties.loanState.managementFeeDue; - return Unexpected(tesSUCCESS); + return std::unexpected(tesSUCCESS); // LCOV_EXCL_STOP } @@ -685,7 +685,7 @@ tryOverpayment( { JLOG(j.warn()) << "Principal overpayment would increase the value of " "the loan. Ignore the overpayment"; - return Unexpected(tesSUCCESS); + return std::unexpected(tesSUCCESS); } return std::make_pair( @@ -718,7 +718,7 @@ tryOverpayment( * gracefully without corrupting the ledger data. */ template -Expected +std::expected doOverpayment( Rules const& rules, Asset const& asset, @@ -760,7 +760,7 @@ doOverpayment( managementFeeRate, j); if (!ret) - return Unexpected(ret.error()); + return std::unexpected(ret.error()); auto const& [loanPaymentParts, newLoanProperties] = *ret; auto const newRoundedLoanState = newLoanProperties.loanState; @@ -774,7 +774,7 @@ doOverpayment( JLOG(j.warn()) << "Overpayment not allowed: principal " << "outstanding did not decrease. Before: " << *principalOutstandingProxy << ". After: " << newRoundedLoanState.principalOutstanding; - return Unexpected(tesSUCCESS); + return std::unexpected(tesSUCCESS); // LCOV_EXCL_STOP } @@ -860,7 +860,7 @@ doOverpayment( * * Implements equation (15) from XLS-66 spec, Section A-2 Equation Glossary */ -Expected +std::expected computeLatePayment( Asset const& asset, ApplyView const& view, @@ -877,7 +877,7 @@ computeLatePayment( // Check if the due date has passed. If not, reject the payment as // being too soon if (!hasExpired(view, nextDueDate)) - return Unexpected(tecTOO_SOON); + return std::unexpected(tecTOO_SOON); // Calculate the penalty interest based on how long the payment is overdue. auto const latePaymentInterest = loanLatePaymentInterest( @@ -929,7 +929,7 @@ computeLatePayment( { JLOG(j.warn()) << "Late loan payment amount is insufficient. Due: " << late.totalDue << ", paid: " << amount; - return Unexpected(tecINSUFFICIENT_PAYMENT); + return std::unexpected(tecINSUFFICIENT_PAYMENT); } return late; @@ -954,7 +954,7 @@ computeLatePayment( * * Implements equation (26) from XLS-66 spec, Section A-2 Equation Glossary */ -Expected +std::expected computeFullPayment( Asset const& asset, ApplyView& view, @@ -979,7 +979,7 @@ computeFullPayment( { // If this is the last payment, it has to be a regular payment JLOG(j.warn()) << "Last payment cannot be a full payment."; - return Unexpected(tecKILLED); + return std::unexpected(tecKILLED); } // Calculate the theoretical principal based on the payment schedule. @@ -1059,7 +1059,7 @@ computeFullPayment( { // If the payment is less than the full payment amount, it's not // sufficient to be a full payment. - return Unexpected(tecINSUFFICIENT_PAYMENT); + return std::unexpected(tecINSUFFICIENT_PAYMENT); } return full; @@ -1780,7 +1780,7 @@ computeLoanProperties( * It is an implementation of the make_payment function from the XLS-66 * spec. Section 3.2.4.4 */ -Expected +std::expected loanMakePayment( Asset const& asset, ApplyView& view, @@ -1800,7 +1800,7 @@ loanMakePayment( // Loan complete this is already checked in LoanPay::preclaim() // LCOV_EXCL_START JLOG(j.warn()) << "Loan is already paid off."; - return Unexpected(tecKILLED); + return std::unexpected(tecKILLED); // LCOV_EXCL_STOP } @@ -1812,7 +1812,7 @@ loanMakePayment( if (*nextDueDateProxy == 0) { JLOG(j.warn()) << "Loan next payment due date is not set."; - return Unexpected(tecINTERNAL); + return std::unexpected(tecINTERNAL); } std::int32_t const loanScale = loan->at(sfLoanScale); @@ -1850,7 +1850,7 @@ loanMakePayment( << startDate << ", prev payment due date is " << prevPaymentDateProxy << ", next payment due date is " << nextDueDateProxy << ", ledger time is " << view.parentCloseTime().time_since_epoch().count(); - return Unexpected(tecEXPIRED); + return std::unexpected(tecEXPIRED); } // ------------------------------------------------------------- @@ -1900,13 +1900,13 @@ loanMakePayment( // error() will be the TER returned if a payment is not made. It // will only evaluate to true if it's unsuccessful. Otherwise, // tesSUCCESS means nothing was done, so continue. - return Unexpected(fullPaymentComponents.error()); + return std::unexpected(fullPaymentComponents.error()); } // LCOV_EXCL_START UNREACHABLE("xrpl::loanMakePayment : invalid full payment result"); JLOG(j.error()) << "Full payment computation failed unexpectedly."; - return Unexpected(tecINTERNAL); + return std::unexpected(tecINTERNAL); // LCOV_EXCL_STOP } @@ -1968,13 +1968,13 @@ loanMakePayment( { // error() will be the TER returned if a payment is not made. It // will only evaluate to true if it's unsuccessful. - return Unexpected(latePaymentComponents.error()); + return std::unexpected(latePaymentComponents.error()); } // LCOV_EXCL_START UNREACHABLE("xrpl::loanMakePayment : invalid late payment result"); JLOG(j.error()) << "Late payment computation failed unexpectedly."; - return Unexpected(tecINTERNAL); + return std::unexpected(tecINTERNAL); // LCOV_EXCL_STOP } @@ -2041,7 +2041,7 @@ loanMakePayment( { JLOG(j.warn()) << "Regular loan payment amount is insufficient. Due: " << periodic.totalDue << ", paid: " << amount; - return Unexpected(tecINSUFFICIENT_PAYMENT); + return std::unexpected(tecINSUFFICIENT_PAYMENT); } XRPL_ASSERT_PARTS( @@ -2127,7 +2127,7 @@ loanMakePayment( // made. It will only evaluate to true if it's unsuccessful. // Otherwise, tesSUCCESS means nothing was done, so // continue. - return Unexpected(overResult.error()); + return std::unexpected(overResult.error()); } } } diff --git a/src/libxrpl/protocol/STTx.cpp b/src/libxrpl/protocol/STTx.cpp index 2777981fd7..55f0ea1289 100644 --- a/src/libxrpl/protocol/STTx.cpp +++ b/src/libxrpl/protocol/STTx.cpp @@ -1,7 +1,6 @@ #include #include -#include #include #include #include @@ -40,6 +39,7 @@ #include #include #include +#include #include #include #include @@ -248,7 +248,7 @@ STTx::sign( tid_ = getHash(HashPrefix::TransactionId); } -Expected +std::expected STTx::checkSign(Rules const& rules, STObject const& sigObject) const { try @@ -263,11 +263,11 @@ STTx::checkSign(Rules const& rules, STObject const& sigObject) const } catch (...) { - return Unexpected("Internal signature check failure."); + return std::unexpected("Internal signature check failure."); } } -Expected +std::expected STTx::checkSign(Rules const& rules) const { if (auto const ret = checkSign(rules, *this); !ret) @@ -277,12 +277,12 @@ STTx::checkSign(Rules const& rules) const { auto const counterSig = getFieldObject(sfCounterpartySignature); if (auto const ret = checkSign(rules, counterSig); !ret) - return Unexpected("Counterparty: " + ret.error()); + return std::unexpected("Counterparty: " + ret.error()); } return {}; } -Expected +std::expected STTx::checkBatchSign(Rules const& rules) const { try @@ -291,7 +291,7 @@ STTx::checkBatchSign(Rules const& rules) const if (getTxnType() != ttBATCH) { JLOG(debugLog().fatal()) << "not a batch transaction"; - return Unexpected("Not a batch transaction."); + return std::unexpected("Not a batch transaction."); } STArray const& signers{getFieldArray(sfBatchSigners)}; for (auto const& signer : signers) @@ -309,7 +309,7 @@ STTx::checkBatchSign(Rules const& rules) const { JLOG(debugLog().error()) << "Batch signature check failed: " << e.what(); } - return Unexpected("Internal batch signature check failure."); + return std::unexpected("Internal batch signature check failure."); } json::Value @@ -389,14 +389,14 @@ STTx::getMetaSQL( safeCast(status) % rTxn % escapedMetaData); } -static Expected +static std::expected singleSignHelper(STObject const& sigObject, Slice const& data) { // We don't allow both a non-empty sfSigningPubKey and an sfSigners. // That would allow the transaction to be signed two ways. So if both // fields are present the signature is invalid. if (sigObject.isFieldPresent(sfSigners)) - return Unexpected("Cannot both single- and multi-sign."); + return std::unexpected("Cannot both single- and multi-sign."); bool validSig = false; try @@ -414,19 +414,19 @@ singleSignHelper(STObject const& sigObject, Slice const& data) } if (!validSig) - return Unexpected("Invalid signature."); + return std::unexpected("Invalid signature."); return {}; } -Expected +std::expected STTx::checkSingleSign(STObject const& sigObject) const { auto const data = getSigningData(*this); return singleSignHelper(sigObject, makeSlice(data)); } -Expected +std::expected STTx::checkBatchSingleSign(STObject const& batchSigner) const { Serializer msg; @@ -434,7 +434,7 @@ STTx::checkBatchSingleSign(STObject const& batchSigner) const return singleSignHelper(batchSigner, msg.slice()); } -Expected +std::expected multiSignHelper( STObject const& sigObject, std::optional txnAccountID, @@ -444,18 +444,18 @@ multiSignHelper( // Make sure the MultiSigners are present. Otherwise they are not // attempting multi-signing and we just have a bad SigningPubKey. if (!sigObject.isFieldPresent(sfSigners)) - return Unexpected("Empty SigningPubKey."); + return std::unexpected("Empty SigningPubKey."); // We don't allow both an sfSigners and an sfTxnSignature. Both fields // being present would indicate that the transaction is signed both ways. if (sigObject.isFieldPresent(sfTxnSignature)) - return Unexpected("Cannot both single- and multi-sign."); + return std::unexpected("Cannot both single- and multi-sign."); STArray const& signers{sigObject.getFieldArray(sfSigners)}; // There are well known bounds that the number of signers must be within. if (signers.size() < STTx::kMinMultiSigners || signers.size() > STTx::kMaxMultiSigners) - return Unexpected("Invalid Signers array size."); + return std::unexpected("Invalid Signers array size."); // Signers must be in sorted order by AccountID. AccountID lastAccountID(beast::kZero); @@ -468,15 +468,15 @@ multiSignHelper( // If they can, txnAccountID will be unseated, which is not equal to any // value. if (txnAccountID == accountID) - return Unexpected("Invalid multisigner."); + return std::unexpected("Invalid multisigner."); // No duplicate signers allowed. if (lastAccountID == accountID) - return Unexpected("Duplicate Signers not allowed."); + return std::unexpected("Duplicate Signers not allowed."); // Accounts must be in order by account ID. No duplicates allowed. if (lastAccountID > accountID) - return Unexpected("Unsorted Signers array."); + return std::unexpected("Unsorted Signers array."); // The next signature must be greater than this one. lastAccountID = accountID; @@ -502,7 +502,7 @@ multiSignHelper( } if (!validSig) { - return Unexpected( + return std::unexpected( std::string("Invalid signature on account ") + toBase58(accountID) + errorWhat.value_or("") + "."); } @@ -511,7 +511,7 @@ multiSignHelper( return {}; } -Expected +std::expected STTx::checkBatchMultiSign(STObject const& batchSigner, Rules const& rules) const { // We can ease the computational load inside the loop a bit by @@ -530,7 +530,7 @@ STTx::checkBatchMultiSign(STObject const& batchSigner, Rules const& rules) const rules); } -Expected +std::expected STTx::checkMultiSign(Rules const& rules, STObject const& sigObject) const { // Used inside the loop in multiSignHelper to enforce that diff --git a/src/libxrpl/protocol/tokens.cpp b/src/libxrpl/protocol/tokens.cpp index a43cbd9c85..fcd822a747 100644 --- a/src/libxrpl/protocol/tokens.cpp +++ b/src/libxrpl/protocol/tokens.cpp @@ -9,7 +9,6 @@ #include -#include #include #include #include @@ -23,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -353,7 +353,7 @@ b256ToB58Be(std::span input, std::span out) // (33 bytes for nodepublic + 1 byte token + 4 bytes checksum) if (input.size() > 38) { - return Unexpected(TokenCodecErrc::InputTooLarge); + return std::unexpected(TokenCodecErrc::InputTooLarge); }; auto countLeadingZeros = [](std::span const& col) -> std::size_t { @@ -441,7 +441,7 @@ b256ToB58Be(std::span input, std::span out) static constexpr std::uint64_t kB5810 = 430804206899405824; // 58^10; if (base5810Coeff[i] >= kB5810) { - return Unexpected(TokenCodecErrc::InputTooLarge); + return std::unexpected(TokenCodecErrc::InputTooLarge); } std::array const b58Be = xrpl::b58_fast::detail::b5810ToB58Be(base5810Coeff[i]); @@ -453,7 +453,7 @@ b256ToB58Be(std::span input, std::span out) skipZeros = false; if (out.size() < ((i + 1) * 10) - toSkip) { - return Unexpected(TokenCodecErrc::OutputTooSmall); + return std::unexpected(TokenCodecErrc::OutputTooSmall); } } for (auto b58Coeff : b58BeS.subspan(toSkip)) @@ -476,11 +476,11 @@ b58ToB256Be(std::string_view input, std::span out) // log(2^(38*8),58) ~= 51.9 if (input.size() > 52) { - return Unexpected(TokenCodecErrc::InputTooLarge); + return std::unexpected(TokenCodecErrc::InputTooLarge); }; if (out.size() < 8) { - return Unexpected(TokenCodecErrc::OutputTooSmall); + return std::unexpected(TokenCodecErrc::OutputTooSmall); } auto countLeadingZeros = [&](auto const& col) -> std::size_t { @@ -513,7 +513,7 @@ b58ToB256Be(std::string_view input, std::span out) auto curVal = ::xrpl::kAlphabetReverse[c]; if (curVal < 0) { - return Unexpected(TokenCodecErrc::InvalidEncodingChar); + return std::unexpected(TokenCodecErrc::InvalidEncodingChar); } b5810Coeff[0] *= 58; b5810Coeff[0] += curVal; @@ -526,7 +526,7 @@ b58ToB256Be(std::string_view input, std::span out) auto curVal = ::xrpl::kAlphabetReverse[c]; if (curVal < 0) { - return Unexpected(TokenCodecErrc::InvalidEncodingChar); + return std::unexpected(TokenCodecErrc::InvalidEncodingChar); } b5810Coeff[numPartialCoeffs + j] *= 58; b5810Coeff[numPartialCoeffs + j] += curVal; @@ -548,7 +548,7 @@ b58ToB256Be(std::string_view input, std::span out) std::span(&result[0], curResultSize + 1), kB5810); if (code != TokenCodecErrc::Success) { - return Unexpected(code); + return std::unexpected(code); } } { @@ -556,7 +556,7 @@ b58ToB256Be(std::string_view input, std::span out) std::span(&result[0], curResultSize + 1), c); if (code != TokenCodecErrc::Success) { - return Unexpected(code); + return std::unexpected(code); } } if (result[curResultSize] != 0) @@ -589,7 +589,7 @@ b58ToB256Be(std::string_view input, std::span out) } if ((curOutI + (8 * (curResultSize - 1))) > out.size()) { - return Unexpected(TokenCodecErrc::OutputTooSmall); + return std::unexpected(TokenCodecErrc::OutputTooSmall); } for (int i = curResultSize - 2; i >= 0; --i) @@ -614,11 +614,11 @@ encodeBase58Token( std::array buf{}; if (input.size() > kTmpBufSize - 5) { - return Unexpected(TokenCodecErrc::InputTooLarge); + return std::unexpected(TokenCodecErrc::InputTooLarge); } if (input.empty()) { - return Unexpected(TokenCodecErrc::InputTooSmall); + return std::unexpected(TokenCodecErrc::InputTooSmall); } // buf[0] = static_cast(tokenType); @@ -648,23 +648,23 @@ decodeBase58Token(TokenType type, std::string_view s, std::span ou // Reject zero length tokens if (ret.size() < 6) - return Unexpected(TokenCodecErrc::InputTooSmall); + return std::unexpected(TokenCodecErrc::InputTooSmall); // The type must match. if (type != static_cast(static_cast(ret[0]))) - return Unexpected(TokenCodecErrc::MismatchedTokenType); + return std::unexpected(TokenCodecErrc::MismatchedTokenType); // And the checksum must as well. std::array guard{}; checksum(guard.data(), ret.data(), ret.size() - guard.size()); if (!std::equal(guard.rbegin(), guard.rend(), ret.rbegin())) { - return Unexpected(TokenCodecErrc::MismatchedChecksum); + return std::unexpected(TokenCodecErrc::MismatchedChecksum); } std::size_t const outSize = ret.size() - 1 - guard.size(); if (outBuf.size() < outSize) - return Unexpected(TokenCodecErrc::OutputTooSmall); + return std::unexpected(TokenCodecErrc::OutputTooSmall); // Skip the leading type byte and the trailing checksum. std::copy(ret.begin() + 1, ret.begin() + outSize + 1, outBuf.begin()); return outBuf.subspan(0, outSize); diff --git a/src/libxrpl/tx/SignerEntries.cpp b/src/libxrpl/tx/SignerEntries.cpp index 7251b8260f..943b66292e 100644 --- a/src/libxrpl/tx/SignerEntries.cpp +++ b/src/libxrpl/tx/SignerEntries.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -12,19 +11,20 @@ #include #include +#include #include #include #include namespace xrpl { -Expected, NotTEC> +std::expected, NotTEC> SignerEntries::deserialize(STObject const& obj, beast::Journal journal, std::string_view annotation) { if (!obj.isFieldPresent(sfSignerEntries)) { JLOG(journal.trace()) << "Malformed " << annotation << ": Need signer entry array."; - return Unexpected(temMALFORMED); + return std::unexpected(temMALFORMED); } std::vector accountVec; @@ -37,7 +37,7 @@ SignerEntries::deserialize(STObject const& obj, beast::Journal journal, std::str if (sEntry.getFName() != sfSignerEntry) { JLOG(journal.trace()) << "Malformed " << annotation << ": Expected SignerEntry."; - return Unexpected(temMALFORMED); + return std::unexpected(temMALFORMED); } // Extract SignerEntry fields. diff --git a/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp b/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp index 7c9c9d95dc..273beaea0f 100644 --- a/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp +++ b/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -40,6 +39,7 @@ #include #include +#include #include #include #include @@ -186,7 +186,7 @@ checkAttestationPublicKey( enum class CheckDst { Check, Ignore }; template -Expected, TER> +std::expected, TER> claimHelper( XChainAttestationsBase& attestations, ReadView const& view, @@ -233,7 +233,7 @@ claimHelper( if (weight >= quorum) return rewardAccounts; - return Unexpected(tecXCHAIN_CLAIM_NO_QUORUM); + return std::unexpected(tecXCHAIN_CLAIM_NO_QUORUM); } /** @@ -337,7 +337,7 @@ onNewAttestations( // Check if there is a quorum of attestations for the given amount and // chain. If so return the reward accounts, if not return the tec code (most // likely tecXCHAIN_CLAIM_NO_QUORUM) -Expected, TER> +std::expected, TER> onClaim( XChainClaimAttestations& attestations, ReadView const& view, @@ -847,14 +847,14 @@ applyClaimAttestations( AccountID cidOwner; }; - auto const scopeResult = [&]() -> Expected { + auto const scopeResult = [&]() -> std::expected { // This lambda is ugly - admittedly. The purpose of this lambda is to // limit the scope of sles so they don't overlap with // `finalizeClaimHelper`. Since `finalizeClaimHelper` can create child // views, it's important that the sle's lifetime doesn't overlap. auto const sleClaimID = psb.peek(claimIDKeylet); if (!sleClaimID) - return Unexpected(tecXCHAIN_NO_CLAIM_ID); + return std::unexpected(tecXCHAIN_NO_CLAIM_ID); // Add claims that are part of the signer's list to the "claims" vector std::vector atts; @@ -868,13 +868,13 @@ applyClaimAttestations( if (atts.empty()) { - return Unexpected(tecXCHAIN_PROOF_UNKNOWN_KEY); + return std::unexpected(tecXCHAIN_PROOF_UNKNOWN_KEY); } AccountID const otherChainSource = (*sleClaimID)[sfOtherChainSource]; if (attBegin->sendingAccount != otherChainSource) { - return Unexpected(tecXCHAIN_SENDING_ACCOUNT_MISMATCH); + return std::unexpected(tecXCHAIN_SENDING_ACCOUNT_MISMATCH); } { @@ -885,7 +885,7 @@ applyClaimAttestations( if (attDstChain != dstChain) { - return Unexpected(tecXCHAIN_WRONG_CHAIN); + return std::unexpected(tecXCHAIN_WRONG_CHAIN); } } @@ -964,10 +964,10 @@ applyCreateAccountAttestations( PaymentSandbox psb(&view); - auto const claimCountResult = [&]() -> Expected { + auto const claimCountResult = [&]() -> std::expected { auto const sleBridge = psb.peek(bridgeK); if (!sleBridge) - return Unexpected(tecINTERNAL); + return std::unexpected(tecINTERNAL); return (*sleBridge)[sfXChainAccountClaimCount]; }(); @@ -1009,7 +1009,7 @@ applyCreateAccountAttestations( XChainCreateAccountAttestations curAtts; }; - auto const scopeResult = [&]() -> Expected { + auto const scopeResult = [&]() -> std::expected { // This lambda is ugly - admittedly. The purpose of this lambda is to // limit the scope of sles so they don't overlap with // `finalizeClaimHelper`. Since `finalizeClaimHelper` can create child @@ -1025,14 +1025,14 @@ applyCreateAccountAttestations( auto const sleDoor = psb.peek(doorK); if (!sleDoor) - return Unexpected(tecINTERNAL); + return std::unexpected(tecINTERNAL); // Check reserve auto const balance = (*sleDoor)[sfBalance]; auto const reserve = psb.fees().accountReserve((*sleDoor)[sfOwnerCount] + 1); if (balance < reserve) - return Unexpected(tecINSUFFICIENT_RESERVE); + return std::unexpected(tecINSUFFICIENT_RESERVE); } std::vector atts; @@ -1045,7 +1045,7 @@ applyCreateAccountAttestations( } if (atts.empty()) { - return Unexpected(tecXCHAIN_PROOF_UNKNOWN_KEY); + return std::unexpected(tecXCHAIN_PROOF_UNKNOWN_KEY); } XChainCreateAccountAttestations curAtts = [&] { @@ -1071,7 +1071,7 @@ applyCreateAccountAttestations( // Modify the object before it's potentially deleted, so the meta // data will include the new attestations if (!sleClaimID) - return Unexpected(tecINTERNAL); + return std::unexpected(tecINTERNAL); sleClaimID->setFieldArray(sfXChainCreateAccountAttestations, curAtts.toSTArray()); psb.update(sleClaimID); } @@ -1244,7 +1244,7 @@ attestationDoApply(ApplyContext& ctx) Keylet bridgeK; }; - auto const scopeResult = [&]() -> Expected { + auto const scopeResult = [&]() -> std::expected { // This lambda is ugly - admittedly. The purpose of this lambda is to // limit the scope of sles so they don't overlap with // `finalizeClaimHelper`. Since `finalizeClaimHelper` can create child @@ -1252,7 +1252,7 @@ attestationDoApply(ApplyContext& ctx) auto sleBridge = readBridge(ctx.view(), bridgeSpec); if (!sleBridge) { - return Unexpected(tecNO_ENTRY); + return std::unexpected(tecNO_ENTRY); } Keylet const bridgeK{ltBRIDGE, sleBridge->key()}; AccountID const thisDoor = (*sleBridge)[sfAccount]; @@ -1269,7 +1269,7 @@ attestationDoApply(ApplyContext& ctx) } else { - return Unexpected(tecINTERNAL); + return std::unexpected(tecINTERNAL); } } STXChainBridge::ChainType const srcChain = STXChainBridge::otherChain(dstChain); @@ -1279,7 +1279,7 @@ attestationDoApply(ApplyContext& ctx) getSignersListAndQuorum(ctx.view(), *sleBridge, ctx.journal); if (!isTesSuccess(slTer)) - return Unexpected(slTer); + return std::unexpected(slTer); return ScopeResult{srcChain, std::move(signersList), quorum, thisDoor, bridgeK}; }(); @@ -1721,7 +1721,7 @@ XChainClaim::doApply() STAmount signatureReward; }; - auto const scopeResult = [&]() -> Expected { + auto const scopeResult = [&]() -> std::expected { // This lambda is ugly - admittedly. The purpose of this lambda is to // limit the scope of sles so they don't overlap with // `finalizeClaimHelper`. Since `finalizeClaimHelper` can create child @@ -1732,7 +1732,7 @@ XChainClaim::doApply() auto const sleClaimID = psb.peek(claimIDKeylet); if (!(sleBridge && sleClaimID && sleAcct)) - return Unexpected(tecINTERNAL); + return std::unexpected(tecINTERNAL); AccountID const thisDoor = (*sleBridge)[sfAccount]; @@ -1748,7 +1748,7 @@ XChainClaim::doApply() } else { - return Unexpected(tecINTERNAL); + return std::unexpected(tecINTERNAL); } } STXChainBridge::ChainType const srcChain = STXChainBridge::otherChain(dstChain); @@ -1763,7 +1763,7 @@ XChainClaim::doApply() getSignersListAndQuorum(ctx_.view(), *sleBridge, ctx_.journal); if (!isTesSuccess(slTer)) - return Unexpected(slTer); + return std::unexpected(slTer); XChainClaimAttestations curAtts{sleClaimID->getFieldArray(sfXChainClaimAttestations)}; @@ -1776,7 +1776,7 @@ XChainClaim::doApply() signersList, ctx_.journal); if (!claimR.has_value()) - return Unexpected(claimR.error()); + return std::unexpected(claimR.error()); return ScopeResult{ .rewardAccounts = claimR.value(), diff --git a/src/libxrpl/tx/transactors/dex/AMMBid.cpp b/src/libxrpl/tx/transactors/dex/AMMBid.cpp index a98f439d0a..83432fa0d0 100644 --- a/src/libxrpl/tx/transactors/dex/AMMBid.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMBid.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -27,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -266,7 +266,7 @@ applyBid(ApplyContext& ctx, Sandbox& sb, AccountID const& account, beast::Journa auto const bidMin = ctx.tx[~sfBidMin]; auto const bidMax = ctx.tx[~sfBidMax]; - auto getPayPrice = [&](Number const& computedPrice) -> Expected { + auto getPayPrice = [&](Number const& computedPrice) -> std::expected { auto const payPrice = [&]() -> std::optional { // Both min/max bid price are defined if (bidMin && bidMax) @@ -295,11 +295,11 @@ applyBid(ApplyContext& ctx, Sandbox& sb, AccountID const& account, beast::Journa }(); if (!payPrice) { - return Unexpected(tecAMM_FAILED); + return std::unexpected(tecAMM_FAILED); } if (payPrice > lpTokens) { - return Unexpected(tecAMM_INVALID_TOKENS); + return std::unexpected(tecAMM_INVALID_TOKENS); } return *payPrice; }; diff --git a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp index 0e1a4b3a3d..041bf73abf 100644 --- a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -28,6 +27,7 @@ #include #include +#include #include #include @@ -83,7 +83,7 @@ LoanBrokerCoverClawback::preflight(PreflightContext const& ctx) return tesSUCCESS; } -Expected +std::expected determineBrokerID(ReadView const& view, STTx const& tx) { // If the broker ID was provided in the transaction, that's all we @@ -96,7 +96,7 @@ determineBrokerID(ReadView const& view, STTx const& tx) // because that should have been rejected in preflight(). auto const dstAmount = tx[~sfAmount]; if (!dstAmount || !dstAmount->holds()) - return Unexpected{tecINTERNAL}; // LCOV_EXCL_LINE + return std::unexpected{tecINTERNAL}; // LCOV_EXCL_LINE // Every trust line is bidirectional. Both sides are simultaneously // issuer and holder. For this transaction, the Account is acting as @@ -112,7 +112,7 @@ determineBrokerID(ReadView const& view, STTx const& tx) // If the account was not found, the transaction can't go further. if (!sle) - return Unexpected{tecNO_ENTRY}; + return std::unexpected{tecNO_ENTRY}; // If the account was found, and has a LoanBrokerID (and therefore // is a pseudo-account), that's the @@ -122,11 +122,11 @@ determineBrokerID(ReadView const& view, STTx const& tx) // If the account does not have a LoanBrokerID, the transaction // can't go further, even if it's a different type of Pseudo-account. - return Unexpected{tecOBJECT_NOT_FOUND}; + return std::unexpected{tecOBJECT_NOT_FOUND}; // Or tecWRONG_ASSET? } -Expected +std::expected determineAsset( ReadView const& view, AccountID const& account, @@ -153,10 +153,10 @@ determineAsset( return Issue{amount.get().currency, account}; } - return Unexpected(tecWRONG_ASSET); + return std::unexpected(tecWRONG_ASSET); } -Expected +std::expected determineClawAmount( SLE const& sleBroker, Asset const& vaultAsset, @@ -182,7 +182,7 @@ determineClawAmount( return sleBroker[sfCoverAvailable] - minRequiredCover; }(); if (maxClawAmount <= beast::kZero) - return Unexpected(tecINSUFFICIENT_FUNDS); + return std::unexpected(tecINSUFFICIENT_FUNDS); // Use the vaultAsset here, because it will be the right type in all // circumstances. The amount may be an IOU indicating the pseudo-account's diff --git a/src/libxrpl/tx/transactors/lending/LoanPay.cpp b/src/libxrpl/tx/transactors/lending/LoanPay.cpp index a0a1479bdb..5c0b46de42 100644 --- a/src/libxrpl/tx/transactors/lending/LoanPay.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanPay.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -29,6 +28,7 @@ #include #include #include +#include #include namespace xrpl { @@ -380,7 +380,7 @@ LoanPay::doApply() return LoanPaymentType::Regular; }(); - Expected const paymentParts = + std::expected const paymentParts = loanMakePayment(asset, view, loanSle, brokerSle, amount, paymentType, j_); if (!paymentParts) diff --git a/src/libxrpl/tx/transactors/nft/NFTokenMint.cpp b/src/libxrpl/tx/transactors/nft/NFTokenMint.cpp index bd7413d50b..d8e5a7b235 100644 --- a/src/libxrpl/tx/transactors/nft/NFTokenMint.cpp +++ b/src/libxrpl/tx/transactors/nft/NFTokenMint.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -26,6 +25,7 @@ #include #include #include +#include #include // IWYU pragma: keep #include @@ -223,12 +223,12 @@ NFTokenMint::doApply() { auto const issuer = ctx_.tx[~sfIssuer].value_or(accountID_); - auto const tokenSeq = [this, &issuer]() -> Expected { + auto const tokenSeq = [this, &issuer]() -> std::expected { auto const root = view().peek(keylet::account(issuer)); if (root == nullptr) { // Should not happen. Checked in preclaim. - return Unexpected(tecNO_ISSUER); + return std::unexpected(tecNO_ISSUER); } // If the issuer hasn't minted an NFToken before we must add a @@ -259,7 +259,7 @@ NFTokenMint::doApply() (*root)[sfMintedNFTokens] = mintedNftCnt + 1u; if ((*root)[sfMintedNFTokens] == 0u) - return Unexpected(tecMAX_SEQUENCE_REACHED); + return std::unexpected(tecMAX_SEQUENCE_REACHED); // Get the unique sequence number of this token by // sfFirstNFTokenSequence + sfMintedNFTokens @@ -268,7 +268,7 @@ NFTokenMint::doApply() // Check for more overflow cases if (tokenSeq + 1u == 0u || tokenSeq < offset) - return Unexpected(tecMAX_SEQUENCE_REACHED); + return std::unexpected(tecMAX_SEQUENCE_REACHED); ctx_.view().update(root); return tokenSeq; diff --git a/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp b/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp index 94a5ca848d..90e33d3a70 100644 --- a/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp +++ b/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -22,6 +21,7 @@ #include #include +#include #include namespace xrpl { @@ -100,16 +100,16 @@ MPTokenIssuanceCreate::preflight(PreflightContext const& ctx) return tesSUCCESS; } -Expected +std::expected MPTokenIssuanceCreate::create(ApplyView& view, beast::Journal journal, MPTCreateArgs const& args) { auto const acct = view.peek(keylet::account(args.account)); if (!acct) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE if (args.priorBalance && *(args.priorBalance) < view.fees().accountReserve((*acct)[sfOwnerCount] + 1)) - return Unexpected(tecINSUFFICIENT_RESERVE); + return std::unexpected(tecINSUFFICIENT_RESERVE); auto const mptId = makeMptID(args.sequence, args.account); auto const mptIssuanceKeylet = keylet::mptIssuance(mptId); @@ -120,7 +120,7 @@ MPTokenIssuanceCreate::create(ApplyView& view, beast::Journal journal, MPTCreate keylet::ownerDir(args.account), mptIssuanceKeylet, describeOwnerDir(args.account)); if (!ownerNode) - return Unexpected(tecDIR_FULL); // LCOV_EXCL_LINE + return std::unexpected(tecDIR_FULL); // LCOV_EXCL_LINE auto mptIssuance = std::make_shared(mptIssuanceKeylet); (*mptIssuance)[sfFlags] = args.flags & ~tfUniversal; @@ -156,10 +156,10 @@ MPTokenIssuanceCreate::create(ApplyView& view, beast::Journal journal, MPTCreate // would dangle the pointer and is a programmer error. auto const sleHolding = view.read(keylet::unchecked(*args.referenceHolding)); if (!sleHolding) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE auto const type = sleHolding->getType(); if (type != ltMPTOKEN && type != ltRIPPLE_STATE) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE (*mptIssuance)[sfReferenceHolding] = *args.referenceHolding; } diff --git a/src/libxrpl/tx/transactors/vault/VaultClawback.cpp b/src/libxrpl/tx/transactors/vault/VaultClawback.cpp index eb12905467..a8587feaeb 100644 --- a/src/libxrpl/tx/transactors/vault/VaultClawback.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultClawback.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -26,6 +25,7 @@ #include #include +#include #include #include #include @@ -218,7 +218,7 @@ VaultClawback::preclaim(PreclaimContext const& ctx) return tecWRONG_ASSET; } -Expected, TER> +std::expected, TER> VaultClawback::assetsToClawback( SLE::ref vault, SLE::const_ref sleShareIssuance, @@ -230,7 +230,7 @@ VaultClawback::assetsToClawback( // preclaim should have blocked this , now it's an internal error // LCOV_EXCL_START JLOG(j_.error()) << "VaultClawback: asset mismatch in clawback."; - return Unexpected(tecINTERNAL); + return std::unexpected(tecINTERNAL); // LCOV_EXCL_STOP } @@ -248,7 +248,7 @@ VaultClawback::assetsToClawback( view(), holder, share, FreezeHandling::IgnoreFreeze, AuthHandling::IgnoreAuth, j_); auto const maybeAssets = sharesToAssetsWithdraw(vault, sleShareIssuance, sharesDestroyed); if (!maybeAssets) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE return std::make_pair(*maybeAssets, sharesDestroyed); } @@ -265,7 +265,7 @@ VaultClawback::assetsToClawback( auto const maybeAssets = sharesToAssetsWithdraw(vault, sleShareIssuance, sharesDestroyed); if (!maybeAssets) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE assetsRecovered = *maybeAssets; } @@ -274,13 +274,13 @@ VaultClawback::assetsToClawback( auto const maybeShares = assetsToSharesWithdraw(vault, sleShareIssuance, clawbackAmount); if (!maybeShares) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE sharesDestroyed = *maybeShares; auto const maybeAssets = sharesToAssetsWithdraw(vault, sleShareIssuance, sharesDestroyed); if (!maybeAssets) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE assetsRecovered = *maybeAssets; } // Clamp to maximum. @@ -294,20 +294,20 @@ VaultClawback::assetsToClawback( auto const maybeShares = assetsToSharesWithdraw( vault, sleShareIssuance, assetsRecovered, TruncateShares::Yes); if (!maybeShares) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE sharesDestroyed = *maybeShares; } auto const maybeAssets = sharesToAssetsWithdraw(vault, sleShareIssuance, sharesDestroyed); if (!maybeAssets) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE assetsRecovered = *maybeAssets; if (assetsRecovered > *assetsAvailable) { // LCOV_EXCL_START JLOG(j_.error()) << "VaultClawback: invalid rounding of shares."; - return Unexpected(tecINTERNAL); + return std::unexpected(tecINTERNAL); // LCOV_EXCL_STOP } } @@ -322,7 +322,7 @@ VaultClawback::assetsToClawback( << ", assetsTotal=" << vault->at(sfAssetsTotal).value() << ", sharesTotal=" << sleShareIssuance->at(sfOutstandingAmount) << ", amount=" << clawbackAmount.value(); - return Unexpected(tecPATH_DRY); + return std::unexpected(tecPATH_DRY); } return std::make_pair(assetsRecovered, sharesDestroyed); diff --git a/src/test/app/Delegate_test.cpp b/src/test/app/Delegate_test.cpp index 588aeee634..70b091290c 100644 --- a/src/test/app/Delegate_test.cpp +++ b/src/test/app/Delegate_test.cpp @@ -2018,8 +2018,8 @@ class Delegate_test : public beast::unit_test::Suite auto jrr = env.rpc("json", "sign_for", to_string(jv))[jss::result]; BEAST_EXPECT(jrr[jss::status] == "error"); BEAST_EXPECT( - jrr[jss::error_message].asString().find( - "A Signer may not be the transaction's Account") != std::string::npos); + jrr[jss::error_message].asString().contains( + "A Signer may not be the transaction's Account")); } } diff --git a/src/test/app/GRPCServerTLS_test.cpp b/src/test/app/GRPCServerTLS_test.cpp index ae0d839a6e..a48986d004 100644 --- a/src/test/app/GRPCServerTLS_test.cpp +++ b/src/test/app/GRPCServerTLS_test.cpp @@ -479,8 +479,7 @@ public: } catch (std::runtime_error const& e) { - BEAST_EXPECT( - std::string(e.what()).find("Incomplete TLS configuration") != std::string::npos); + BEAST_EXPECT(std::string(e.what()).contains("Incomplete TLS configuration")); } } @@ -505,8 +504,7 @@ public: } catch (std::runtime_error const& e) { - BEAST_EXPECT( - std::string(e.what()).find("Incomplete TLS configuration") != std::string::npos); + BEAST_EXPECT(std::string(e.what()).contains("Incomplete TLS configuration")); } } @@ -533,8 +531,8 @@ public: catch (std::runtime_error const& e) { BEAST_EXPECT( - std::string(e.what()).find( - "ssl_client_ca requires both ssl_cert and ssl_key") != std::string::npos); + std::string(e.what()).contains( + "ssl_client_ca requires both ssl_cert and ssl_key")); } } @@ -556,9 +554,7 @@ public: { // This should fail with "Incomplete TLS configuration" first // because ssl_cert is specified without ssl_key - BEAST_EXPECT( - std::string(e.what()).find("Incomplete TLS configuration") != - std::string::npos); + BEAST_EXPECT(std::string(e.what()).contains("Incomplete TLS configuration")); } } @@ -580,9 +576,7 @@ public: { // This should fail with "Incomplete TLS configuration" first // because ssl_key is specified without ssl_cert - BEAST_EXPECT( - std::string(e.what()).find("Incomplete TLS configuration") != - std::string::npos); + BEAST_EXPECT(std::string(e.what()).contains("Incomplete TLS configuration")); } } } @@ -610,8 +604,8 @@ public: catch (std::runtime_error const& e) { BEAST_EXPECT( - std::string(e.what()).find( - "ssl_cert_chain requires both ssl_cert and ssl_key") != std::string::npos); + std::string(e.what()).contains( + "ssl_cert_chain requires both ssl_cert and ssl_key")); } } @@ -633,9 +627,7 @@ public: { // This should fail with "Incomplete TLS configuration" first // because ssl_cert is specified without ssl_key - BEAST_EXPECT( - std::string(e.what()).find("Incomplete TLS configuration") != - std::string::npos); + BEAST_EXPECT(std::string(e.what()).contains("Incomplete TLS configuration")); } } } diff --git a/src/test/app/Invariants_test.cpp b/src/test/app/Invariants_test.cpp index 3654036869..6d53d25661 100644 --- a/src/test/app/Invariants_test.cpp +++ b/src/test/app/Invariants_test.cpp @@ -216,7 +216,7 @@ class Invariants_test : public beast::unit_test::Suite // std::cerr << messages << '\n'; for (auto const& m : expectLogs) { - BEAST_EXPECTS(messages.find(m) != std::string::npos, m); + BEAST_EXPECTS(messages.contains(m), m); } } } @@ -2187,8 +2187,7 @@ class Invariants_test : public beast::unit_test::Suite BEAST_EXPECT(!invariant.finalize( makeOfferCreateTx(), tesSUCCESS, XRPAmount{}, view, missingRootJlog)); BEAST_EXPECT( - missingRootSink.messages().str().find("book directory root missing") != - std::string::npos); + missingRootSink.messages().str().contains("book directory root missing")); } { // delete diff --git a/src/test/app/MultiSign_test.cpp b/src/test/app/MultiSign_test.cpp index 5092cafef9..f161226210 100644 --- a/src/test/app/MultiSign_test.cpp +++ b/src/test/app/MultiSign_test.cpp @@ -1121,8 +1121,8 @@ public: // Signature should fail. auto const info = submitSTTx(local); BEAST_EXPECT( - info[jss::result][jss::error_exception].asString().find( - "Invalid signature on account r") != std::string::npos); + info[jss::result][jss::error_exception].asString().contains( + "Invalid signature on account r")); } { // Multisign with an empty signers array should fail. diff --git a/src/test/app/NFTokenBurn_test.cpp b/src/test/app/NFTokenBurn_test.cpp index 482d275d51..46b02d03cf 100644 --- a/src/test/app/NFTokenBurn_test.cpp +++ b/src/test/app/NFTokenBurn_test.cpp @@ -794,9 +794,8 @@ class NFTokenBurn_test : public beast::unit_test::Suite BEAST_EXPECT(sink.messages().str().starts_with("Invariant failed:")); // uncomment to log the invariant failure message // log << " --> " << sink.messages().str() << std::endl; - BEAST_EXPECT( - sink.messages().str().find( - "Last NFT page deleted with non-empty directory") != std::string::npos); + BEAST_EXPECT(sink.messages().str().contains( + "Last NFT page deleted with non-empty directory")); } } { @@ -831,8 +830,7 @@ class NFTokenBurn_test : public beast::unit_test::Suite BEAST_EXPECT(sink.messages().str().starts_with("Invariant failed:")); // uncomment to log the invariant failure message // log << " --> " << sink.messages().str() << std::endl; - BEAST_EXPECT( - sink.messages().str().find("Lost NextMinPage link") != std::string::npos); + BEAST_EXPECT(sink.messages().str().contains("Lost NextMinPage link")); } } } diff --git a/src/test/app/NetworkOPs_test.cpp b/src/test/app/NetworkOPs_test.cpp index d0a692b894..c5c8d33706 100644 --- a/src/test/app/NetworkOPs_test.cpp +++ b/src/test/app/NetworkOPs_test.cpp @@ -54,7 +54,7 @@ public: env.close(); } - BEAST_EXPECT(logs.find("No transaction to process!") != std::string::npos); + BEAST_EXPECT(logs.contains("No transaction to process!")); } }; diff --git a/src/test/app/ValidatorSite_test.cpp b/src/test/app/ValidatorSite_test.cpp index e3e3ec27df..8400f2d794 100644 --- a/src/test/app/ValidatorSite_test.cpp +++ b/src/test/app/ValidatorSite_test.cpp @@ -239,7 +239,7 @@ private: json::Value myStatus; for (auto const& vs : jv[jss::validator_sites]) { - if (vs[jss::uri].asString().find(u.uri) != std::string::npos) + if (vs[jss::uri].asString().contains(u.uri)) myStatus = vs; } BEAST_EXPECTS( @@ -248,9 +248,7 @@ private: if (!u.cfg.msg.empty()) { - BEAST_EXPECTS( - sink.messages().str().find(u.cfg.msg) != std::string::npos, - sink.messages().str()); + BEAST_EXPECTS(sink.messages().str().contains(u.cfg.msg), sink.messages().str()); } if (u.cfg.expectedRefreshMin != 0) @@ -324,7 +322,7 @@ private: json::Value myStatus; for (auto const& vs : jv[jss::validator_sites]) { - if (vs[jss::uri].asString().find(u.uri) != std::string::npos) + if (vs[jss::uri].asString().contains(u.uri)) myStatus = vs; } BEAST_EXPECTS( @@ -332,9 +330,7 @@ private: to_string(myStatus)); if (u.shouldFail) { - BEAST_EXPECTS( - sink.messages().str().find(u.expectMsg) != std::string::npos, - sink.messages().str()); + BEAST_EXPECTS(sink.messages().str().contains(u.expectMsg), sink.messages().str()); } } } diff --git a/src/test/basics/Expected_test.cpp b/src/test/basics/Expected_test.cpp deleted file mode 100644 index c8e570835b..0000000000 --- a/src/test/basics/Expected_test.cpp +++ /dev/null @@ -1,221 +0,0 @@ -#include -#include -#include - -#include -#include - -#include -#include -#include -#include - -#if BOOST_VERSION >= 107500 -#endif // BOOST_VERSION -#include - -namespace xrpl::test { - -struct Expected_test : beast::unit_test::Suite -{ - void - run() override - { - // Test non-error const construction. - { - auto const expected = []() -> Expected { return "Valid value"; }(); - BEAST_EXPECT(expected); - BEAST_EXPECT(expected.has_value()); - BEAST_EXPECT(expected.value() == "Valid value"); - BEAST_EXPECT(*expected == "Valid value"); - BEAST_EXPECT(expected->at(0) == 'V'); - - bool throwOccurred = false; - try - { - // There's no error, so should throw. - [[maybe_unused]] TER 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 non-error non-const construction. - { - auto expected = []() -> Expected { return "Valid value"; }(); - BEAST_EXPECT(expected); - BEAST_EXPECT(expected.has_value()); - BEAST_EXPECT(expected.value() == "Valid value"); - BEAST_EXPECT(*expected == "Valid value"); - BEAST_EXPECT(expected->at(0) == 'V'); - std::string const mv = std::move(*expected); - BEAST_EXPECT(mv == "Valid value"); - - bool throwOccurred = false; - try - { - // There's no error, so should throw. - [[maybe_unused]] TER 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 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 { - return Unexpected(telLOCAL_ERROR); - }(); - BEAST_EXPECT(!expected); - BEAST_EXPECT(!expected.has_value()); - BEAST_EXPECT(expected.error() == telLOCAL_ERROR); - - bool throwOccurred = false; - try - { - // There's no result, so should throw. - [[maybe_unused]] std::string const s = *expected; - } - catch (std::runtime_error const& e) - { - BEAST_EXPECT(e.what() == std::string("bad expected access")); - throwOccurred = true; - } - BEAST_EXPECT(throwOccurred); - } - // Test error construction from lvalue. - { - auto const err(telLOCAL_ERROR); - auto expected = [&err]() -> Expected { return Unexpected(err); }(); - BEAST_EXPECT(!expected); - BEAST_EXPECT(!expected.has_value()); - BEAST_EXPECT(expected.error() == telLOCAL_ERROR); - - bool throwOccurred = false; - try - { - // There's no result, so should throw. - [[maybe_unused]] std::size_t const s = expected->size(); - } - catch (std::runtime_error const& e) - { - BEAST_EXPECT(e.what() == std::string("bad expected access")); - throwOccurred = true; - } - BEAST_EXPECT(throwOccurred); - } - // Test error construction from const char*. - { - auto const expected = []() -> Expected { - return Unexpected("Not what is expected!"); - }(); - BEAST_EXPECT(!expected); - BEAST_EXPECT(!expected.has_value()); - BEAST_EXPECT(expected.error() == std::string("Not what is expected!")); - } - // Test error construction of string from const char*. - { - auto expected = []() -> Expected { - return Unexpected("Not what is expected!"); - }(); - BEAST_EXPECT(!expected); - BEAST_EXPECT(!expected.has_value()); - BEAST_EXPECT(expected.error() == "Not what is expected!"); - std::string const s(std::move(expected.error())); - BEAST_EXPECT(s == "Not what is expected!"); - } - // Test non-error const construction of Expected. - { - auto const expected = []() -> Expected { return {}; }(); - BEAST_EXPECT(expected); - bool throwOccurred = false; - try - { - // There's no error, so should throw. - [[maybe_unused]] std::size_t const s = expected.error().size(); - } - catch (std::runtime_error const& e) - { - BEAST_EXPECT(e.what() == std::string("bad expected access")); - throwOccurred = true; - } - BEAST_EXPECT(throwOccurred); - } - // Test non-error non-const construction of Expected. - { - auto expected = []() -> Expected { return {}; }(); - BEAST_EXPECT(expected); - bool throwOccurred = false; - try - { - // There's no error, so should throw. - [[maybe_unused]] std::size_t const s = expected.error().size(); - } - catch (std::runtime_error const& e) - { - BEAST_EXPECT(e.what() == std::string("bad expected access")); - throwOccurred = true; - } - BEAST_EXPECT(throwOccurred); - } - // Test error const construction of Expected. - { - auto const expected = []() -> Expected { - return Unexpected("Not what is expected!"); - }(); - BEAST_EXPECT(!expected); - BEAST_EXPECT(expected.error() == "Not what is expected!"); - } - // Test error non-const construction of Expected. - { - auto expected = []() -> Expected { - return Unexpected("Not what is expected!"); - }(); - BEAST_EXPECT(!expected); - BEAST_EXPECT(expected.error() == "Not what is expected!"); - std::string const s(std::move(expected.error())); - BEAST_EXPECT(s == "Not what is expected!"); - } - // Test a case that previously unintentionally returned an array. -#if BOOST_VERSION >= 107500 - { - auto expected = []() -> Expected { - return boost::json::object{{"oops", "me array now"}}; - }(); - BEAST_EXPECT(expected); - BEAST_EXPECT(!expected.value().is_array()); - } -#endif // BOOST_VERSION - } -}; - -BEAST_DEFINE_TESTSUITE(Expected, basics, xrpl); - -} // namespace xrpl::test diff --git a/src/test/consensus/Consensus_test.cpp b/src/test/consensus/Consensus_test.cpp index 6cc8d4fde1..629a97f0ea 100644 --- a/src/test/consensus/Consensus_test.cpp +++ b/src/test/consensus/Consensus_test.cpp @@ -1296,14 +1296,11 @@ public: auto const s = clog->str(); expect(s.find("stalled"), s, __FILE__, line); expect(s.starts_with("Transaction "s + std::to_string(txid)), s, __FILE__, line); - expect(s.find("voting "s + (ourVote ? "YES" : "NO")) != s.npos, s, __FILE__, line); + expect(s.contains("voting "s + (ourVote ? "YES" : "NO")), s, __FILE__, line); expect( - s.find("for "s + std::to_string(ourTime) + " rounds."s) != s.npos, - s, - __FILE__, - line); + s.contains("for "s + std::to_string(ourTime) + " rounds."s), s, __FILE__, line); expect( - s.find("votes in "s + std::to_string(peerTime) + " rounds.") != s.npos, + s.contains("votes in "s + std::to_string(peerTime) + " rounds."), s, __FILE__, line); diff --git a/src/test/jtx/CheckMessageLogs.h b/src/test/jtx/CheckMessageLogs.h index 2cc8c661eb..4bbdec6f06 100644 --- a/src/test/jtx/CheckMessageLogs.h +++ b/src/test/jtx/CheckMessageLogs.h @@ -24,7 +24,7 @@ class CheckMessageLogs : public Logs void write(beast::Severity level, std::string const& text) override { - if (text.find(owner_.msg_) != std::string::npos) + if (text.contains(owner_.msg_)) *owner_.pFound_ = true; } diff --git a/src/test/jtx/directory.h b/src/test/jtx/directory.h index 9a87266802..c63640ae1f 100644 --- a/src/test/jtx/directory.h +++ b/src/test/jtx/directory.h @@ -2,11 +2,11 @@ #include -#include #include #include #include +#include #include /** Directory operations. */ @@ -34,7 +34,7 @@ bumpLastPage( Env& env, std::uint64_t newLastPage, Keylet directory, - std::function adjust) -> Expected; + std::function adjust) -> std::expected; /// Implementation of adjust for the most common ledger entry, i.e. one where /// page index is stored in sfOwnerNode (and only there). Pass this function diff --git a/src/test/jtx/impl/directory.cpp b/src/test/jtx/impl/directory.cpp index 7a92c2bf25..9fb06e25df 100644 --- a/src/test/jtx/impl/directory.cpp +++ b/src/test/jtx/impl/directory.cpp @@ -2,7 +2,6 @@ #include -#include #include #include #include @@ -15,6 +14,7 @@ #include #include +#include #include #include @@ -26,9 +26,9 @@ bumpLastPage( Env& env, std::uint64_t newLastPage, Keylet directory, - std::function adjust) -> Expected + std::function adjust) -> std::expected { - Expected res{}; + std::expected res{}; env.app().getOpenLedger().modify([&](OpenView& view, beast::Journal j) -> bool { Sandbox sb(&view, TapNone); @@ -36,7 +36,7 @@ bumpLastPage( auto sleRoot = sb.peek(directory); if (!sleRoot) { - res = Unexpected(Error::DirectoryRootNotFound); + res = std::unexpected(Error::DirectoryRootNotFound); return false; } @@ -44,26 +44,26 @@ bumpLastPage( auto const lastIndex = sleRoot->getFieldU64(sfIndexPrevious); if (lastIndex == 0) { - res = Unexpected(Error::DirectoryTooSmall); + res = std::unexpected(Error::DirectoryTooSmall); return false; } if (sb.exists(keylet::page(directory, newLastPage))) { - res = Unexpected(Error::DirectoryPageDuplicate); + res = std::unexpected(Error::DirectoryPageDuplicate); return false; } if (lastIndex >= newLastPage) { - res = Unexpected(Error::InvalidLastPage); + res = std::unexpected(Error::InvalidLastPage); return false; } auto slePage = sb.peek(keylet::page(directory, lastIndex)); if (!slePage) { - res = Unexpected(Error::DirectoryPageNotFound); + res = std::unexpected(Error::DirectoryPageNotFound); return false; } @@ -94,7 +94,7 @@ bumpLastPage( auto slePrev = sb.peek(keylet::page(directory, *prevIndex)); if (!slePrev) { - res = Unexpected(Error::DirectoryPageNotFound); + res = std::unexpected(Error::DirectoryPageNotFound); return false; } slePrev->setFieldU64(sfIndexNext, newLastPage); @@ -109,7 +109,7 @@ bumpLastPage( { if (!adjust(sb, key, newLastPage)) { - res = Unexpected(Error::AdjustmentError); + res = std::unexpected(Error::AdjustmentError); return false; } } diff --git a/src/test/nodestore/NuDBFactory_test.cpp b/src/test/nodestore/NuDBFactory_test.cpp index 3ca3fa6838..d0675b3893 100644 --- a/src/test/nodestore/NuDBFactory_test.cpp +++ b/src/test/nodestore/NuDBFactory_test.cpp @@ -88,7 +88,7 @@ private: auto backend = Manager::instance().makeBackend(params, megabytes(4), scheduler, journal); std::string const logOutput = sink.messages().str(); - BEAST_EXPECT(logOutput.find(expectedMessage) != std::string::npos); + BEAST_EXPECT(logOutput.contains(expectedMessage)); } // Helper function to test power of two validation @@ -105,7 +105,7 @@ private: auto backend = Manager::instance().makeBackend(params, megabytes(4), scheduler, journal); std::string const logOutput = sink.messages().str(); - bool const hasWarning = logOutput.find("Invalid nudb_block_size") != std::string::npos; + bool const hasWarning = logOutput.contains("Invalid nudb_block_size"); BEAST_EXPECT(hasWarning == !shouldWork); } @@ -221,10 +221,8 @@ public: catch (std::exception const& e) { std::string const logOutput{e.what()}; - BEAST_EXPECT(logOutput.find("Invalid nudb_block_size: 5000") != std::string::npos); - BEAST_EXPECT( - logOutput.find("Must be power of 2 between 4096 and 32768") != - std::string::npos); + BEAST_EXPECT(logOutput.contains("Invalid nudb_block_size: 5000")); + BEAST_EXPECT(logOutput.contains("Must be power of 2 between 4096 and 32768")); } } @@ -247,8 +245,7 @@ public: catch (std::exception const& e) { std::string const logOutput{e.what()}; - BEAST_EXPECT( - logOutput.find("Invalid nudb_block_size value: invalid") != std::string::npos); + BEAST_EXPECT(logOutput.contains("Invalid nudb_block_size value: invalid")); } } } @@ -291,7 +288,7 @@ public: catch (std::exception const& e) { std::string const logOutput{e.what()}; - BEAST_EXPECT(logOutput.find("Invalid nudb_block_size") != std::string::npos); + BEAST_EXPECT(logOutput.contains("Invalid nudb_block_size")); } } } @@ -355,8 +352,7 @@ public: // Should log success message for valid values std::string const logOutput = sink.messages().str(); - bool const hasSuccessMessage = - logOutput.find("Using custom NuDB block size") != std::string::npos; + bool const hasSuccessMessage = logOutput.contains("Using custom NuDB block size"); BEAST_EXPECT(hasSuccessMessage); } diff --git a/src/test/overlay/reduce_relay_test.cpp b/src/test/overlay/reduce_relay_test.cpp index 54d8f555a2..1c9bf1f9c1 100644 --- a/src/test/overlay/reduce_relay_test.cpp +++ b/src/test/overlay/reduce_relay_test.cpp @@ -806,7 +806,7 @@ public: { auto size = max - min; std::vector s(size); - std::iota(s.begin(), s.end(), min); + std::iota(s.begin(), s.end(), min); // NOLINT(modernize-use-ranges) std::random_device d; std::mt19937 g(d()); std::shuffle(s.begin(), s.end(), g); diff --git a/src/test/server/ServerStatus_test.cpp b/src/test/server/ServerStatus_test.cpp index 5ba71962b3..4a9c12c96b 100644 --- a/src/test/server/ServerStatus_test.cpp +++ b/src/test/server/ServerStatus_test.cpp @@ -801,7 +801,7 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En if (!BEAST_EXPECTS(!ec, ec.message())) return; BEAST_EXPECT(resp.result() == boost::beast::http::status::ok); - BEAST_EXPECT(resp.body().find("connectivity is working.") != std::string::npos); + BEAST_EXPECT(resp.body().contains("connectivity is working.")); // mark the Network as having an Amendment Warning, but won't fail env.app().getOPs().setAmendmentWarned(); @@ -846,7 +846,7 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En if (!BEAST_EXPECTS(!ec, ec.message())) return; BEAST_EXPECT(resp.result() == boost::beast::http::status::ok); - BEAST_EXPECT(resp.body().find("connectivity is working.") != std::string::npos); + BEAST_EXPECT(resp.body().contains("connectivity is working.")); // with ELB_SUPPORT, status still does not indicate a problem env.app().config().elbSupport = true; @@ -866,7 +866,7 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En if (!BEAST_EXPECTS(!ec, ec.message())) return; BEAST_EXPECT(resp.result() == boost::beast::http::status::ok); - BEAST_EXPECT(resp.body().find("connectivity is working.") != std::string::npos); + BEAST_EXPECT(resp.body().contains("connectivity is working.")); } void @@ -929,7 +929,7 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En if (!BEAST_EXPECTS(!ec, ec.message())) return; BEAST_EXPECT(resp.result() == boost::beast::http::status::ok); - BEAST_EXPECT(resp.body().find("connectivity is working.") != std::string::npos); + BEAST_EXPECT(resp.body().contains("connectivity is working.")); // mark the Network as Amendment Blocked, but still won't fail until // ELB is enabled (next step) @@ -977,7 +977,7 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En if (!BEAST_EXPECTS(!ec, ec.message())) return; BEAST_EXPECT(resp.result() == boost::beast::http::status::ok); - BEAST_EXPECT(resp.body().find("connectivity is working.") != std::string::npos); + BEAST_EXPECT(resp.body().contains("connectivity is working.")); env.app().config().elbSupport = true; @@ -996,8 +996,8 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En if (!BEAST_EXPECTS(!ec, ec.message())) return; BEAST_EXPECT(resp.result() == boost::beast::http::status::internal_server_error); - BEAST_EXPECT(resp.body().find("cannot accept clients:") != std::string::npos); - BEAST_EXPECT(resp.body().find("Server version too old") != std::string::npos); + BEAST_EXPECT(resp.body().contains("cannot accept clients:")); + BEAST_EXPECT(resp.body().contains("Server version too old")); } void diff --git a/src/test/server/Server_test.cpp b/src/test/server/Server_test.cpp index 455a365b7c..54091ef767 100644 --- a/src/test/server/Server_test.cpp +++ b/src/test/server/Server_test.cpp @@ -401,7 +401,7 @@ public: }), std::make_unique(&messages)}; }); - BEAST_EXPECT(messages.find("Missing 'ip' in [port_rpc]") != std::string::npos); + BEAST_EXPECT(messages.contains("Missing 'ip' in [port_rpc]")); except([&] { Env const env{ @@ -413,7 +413,7 @@ public: }), std::make_unique(&messages)}; }); - BEAST_EXPECT(messages.find("Missing 'port' in [port_rpc]") != std::string::npos); + BEAST_EXPECT(messages.contains("Missing 'port' in [port_rpc]")); except([&] { Env const env{ @@ -426,8 +426,7 @@ public: }), std::make_unique(&messages)}; }); - BEAST_EXPECT( - messages.find("Invalid value '0' for key 'port' in [port_rpc]") == std::string::npos); + BEAST_EXPECT(!messages.contains("Invalid value '0' for key 'port' in [port_rpc]")); except([&] { Env const env{ @@ -438,8 +437,7 @@ public: }), std::make_unique(&messages)}; }); - BEAST_EXPECT( - messages.find("Invalid value '0' for key 'port' in [server]") != std::string::npos); + BEAST_EXPECT(messages.contains("Invalid value '0' for key 'port' in [server]")); except([&] { Env const env{ @@ -453,7 +451,7 @@ public: }), std::make_unique(&messages)}; }); - BEAST_EXPECT(messages.find("Missing 'protocol' in [port_rpc]") != std::string::npos); + BEAST_EXPECT(messages.contains("Missing 'protocol' in [port_rpc]")); except([&] // this creates a standard test config without the server // section @@ -482,7 +480,7 @@ public: }), std::make_unique(&messages)}; }); - BEAST_EXPECT(messages.find("Required section [server] is missing") != std::string::npos); + BEAST_EXPECT(messages.contains("Required section [server] is missing")); except([&] // this creates a standard test config without some of the // port sections @@ -503,7 +501,7 @@ public: }), std::make_unique(&messages)}; }); - BEAST_EXPECT(messages.find("Missing section: [port_peer]") != std::string::npos); + BEAST_EXPECT(messages.contains("Missing section: [port_peer]")); } void diff --git a/src/xrpld/overlay/detail/PeerImp.cpp b/src/xrpld/overlay/detail/PeerImp.cpp index 325f8ba038..323dc14673 100644 --- a/src/xrpld/overlay/detail/PeerImp.cpp +++ b/src/xrpld/overlay/detail/PeerImp.cpp @@ -783,7 +783,7 @@ PeerImp::onShutdown(error_code ec) // - broken_pipe: the peer is gone bool const shouldLog = (ec != boost::asio::error::eof && ec != boost::asio::error::operation_aborted && - ec.message().find("application data after close notify") == std::string::npos); + !ec.message().contains("application data after close notify")); if (shouldLog) { diff --git a/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp b/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp index 4d0d10a66b..38827dc93c 100644 --- a/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp +++ b/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp @@ -8,7 +8,6 @@ #include #include -#include #include #include #include @@ -24,6 +23,7 @@ #include #include +#include #include namespace xrpl::RPC { @@ -381,7 +381,7 @@ lookupLedger(std::shared_ptr& ledger, JsonContext const& context return result; } -Expected, json::Value> +std::expected, json::Value> getOrAcquireLedger(RPC::JsonContext const& context) { auto const hasHash = context.params.isMember(jss::ledger_hash); @@ -393,7 +393,7 @@ getOrAcquireLedger(RPC::JsonContext const& context) if ((static_cast(hasHash) + static_cast(hasIndex)) != 1) { - return Unexpected( + return std::unexpected( RPC::makeParamError( "Exactly one of 'ledger_hash' or " "'ledger_index' can be specified.")); @@ -403,29 +403,29 @@ getOrAcquireLedger(RPC::JsonContext const& context) { auto const& jsonHash = context.params.get(jss::ledger_hash, json::ValueType::Null); if (!jsonHash.isString() || !ledgerHash.parseHex(jsonHash.asString())) - return Unexpected(RPC::expectedFieldError(jss::ledger_hash, "hex string")); + return std::unexpected(RPC::expectedFieldError(jss::ledger_hash, "hex string")); } else { auto const& jsonIndex = context.params.get(jss::ledger_index, json::ValueType::Null); if (!jsonIndex.isInt() && !jsonIndex.isUInt()) - return Unexpected(RPC::expectedFieldError(jss::ledger_index, "number")); + return std::unexpected(RPC::expectedFieldError(jss::ledger_index, "number")); // We need a validated ledger to get the hash from the sequence if (ledgerMaster.getValidatedLedgerAge() > RPC::Tuning::kMaxValidatedLedgerAge) { if (context.apiVersion == 1) - return Unexpected(rpcError(RpcNoCurrent)); - return Unexpected(rpcError(RpcNotSynced)); + return std::unexpected(rpcError(RpcNoCurrent)); + return std::unexpected(rpcError(RpcNotSynced)); } ledgerIndex = jsonIndex.asInt(); auto ledger = ledgerMaster.getValidatedLedger(); if (ledgerIndex >= ledger->header().seq) - return Unexpected(RPC::makeParamError("Ledger index too large")); + return std::unexpected(RPC::makeParamError("Ledger index too large")); if (ledgerIndex <= 0) - return Unexpected(RPC::makeParamError("Ledger index too small")); + return std::unexpected(RPC::makeParamError("Ledger index too small")); auto const j = context.app.getJournal("RPCHandler"); // Try to get the hash of the desired ledger from the validated @@ -452,7 +452,7 @@ getOrAcquireLedger(RPC::JsonContext const& context) json::Value jvResult = RPC::makeError( RpcLgrNotFound, "acquiring ledger containing requested index"); jvResult[jss::acquiring] = getJson(LedgerFill(*il, &context)); - return Unexpected(jvResult); + return std::unexpected(jvResult); } if (auto il = context.app.getInboundLedgers().find(*refHash)) @@ -461,11 +461,11 @@ getOrAcquireLedger(RPC::JsonContext const& context) json::Value jvResult = RPC::makeError( RpcLgrNotFound, "acquiring ledger containing requested index"); jvResult[jss::acquiring] = il->getJson(0); - return Unexpected(jvResult); + return std::unexpected(jvResult); } // Likely the app is shutting down - return Unexpected(json::Value()); + return std::unexpected(json::Value()); } neededHash = hashOfSeq(*ledger, ledgerIndex, j); @@ -487,9 +487,10 @@ getOrAcquireLedger(RPC::JsonContext const& context) return ledger; if (auto il = context.app.getInboundLedgers().find(ledgerHash)) - return Unexpected(il->getJson(0)); + return std::unexpected(il->getJson(0)); - return Unexpected(RPC::makeError(RpcNotReady, "findCreate failed to return an inbound ledger")); + return std::unexpected( + RPC::makeError(RpcNotReady, "findCreate failed to return an inbound ledger")); } } // namespace xrpl::RPC diff --git a/src/xrpld/rpc/detail/RPCLedgerHelpers.h b/src/xrpld/rpc/detail/RPCLedgerHelpers.h index faec4ae069..9ec2a6673c 100644 --- a/src/xrpld/rpc/detail/RPCLedgerHelpers.h +++ b/src/xrpld/rpc/detail/RPCLedgerHelpers.h @@ -10,6 +10,7 @@ #include #include +#include #include namespace xrpl { @@ -163,11 +164,11 @@ ledgerFromSpecifier( * * @param context The RPC JsonContext containing request parameters and * environment. - * @return Expected, json::Value> + * @return std::expected, json::Value> * On success, contains a shared pointer to the requested Ledger. * On failure, contains a json::Value describing the error. */ -Expected, json::Value> +std::expected, json::Value> getOrAcquireLedger(RPC::JsonContext const& context); } // namespace RPC diff --git a/src/xrpld/rpc/detail/TransactionSign.cpp b/src/xrpld/rpc/detail/TransactionSign.cpp index 86d895fa1b..8c3a5ea245 100644 --- a/src/xrpld/rpc/detail/TransactionSign.cpp +++ b/src/xrpld/rpc/detail/TransactionSign.cpp @@ -14,7 +14,6 @@ #include #include -#include #include #include #include @@ -57,6 +56,7 @@ #include #include #include +#include #include #include #include @@ -407,23 +407,23 @@ checkTxJsonFields( return ret; } -static Expected +static std::expected checkNetworkID(json::Value const& txJson, uint32_t appNetworkId) { if (appNetworkId > 1024) { if (!txJson.isMember(jss::NetworkID)) { - return Unexpected( + return std::unexpected( RPC::makeError(RpcInvalidParams, RPC::missingFieldMessage("tx_json.NetworkID"))); } if (!txJson[jss::NetworkID].isIntegral() || txJson[jss::NetworkID].asUInt() != appNetworkId) { - return Unexpected( + return std::unexpected( RPC::makeError(RpcInvalidParams, RPC::invalidFieldMessage("tx_json.NetworkID"))); } } - return Expected(); + return std::expected(); } //------------------------------------------------------------------------------ diff --git a/src/xrpld/rpc/handlers/ledger/Ledger.cpp b/src/xrpld/rpc/handlers/ledger/Ledger.cpp index 1b096002bd..5938c8c9c5 100644 --- a/src/xrpld/rpc/handlers/ledger/Ledger.cpp +++ b/src/xrpld/rpc/handlers/ledger/Ledger.cpp @@ -8,7 +8,6 @@ #include #include -#include #include #include #include @@ -28,6 +27,7 @@ #include #include +#include #include #include #include @@ -44,14 +44,14 @@ LedgerHandler::check() { auto const& params = context_.params; - auto getBool = [&](json::StaticString const& field) -> Expected { + auto getBool = [&](json::StaticString const& field) -> std::expected { if (!params.isMember(field)) { return false; } if (!params[field].isBool()) { - return Unexpected(RpcInvalidParams); + return std::unexpected(RpcInvalidParams); } return params[field].asBool(); diff --git a/src/xrpld/rpc/handlers/ledger/LedgerEntry.cpp b/src/xrpld/rpc/handlers/ledger/LedgerEntry.cpp index 9a9119d2ba..236712f0c2 100644 --- a/src/xrpld/rpc/handlers/ledger/LedgerEntry.cpp +++ b/src/xrpld/rpc/handlers/ledger/LedgerEntry.cpp @@ -3,7 +3,6 @@ #include #include -#include #include #include #include @@ -27,6 +26,7 @@ #include #include +#include #include #include #include @@ -34,12 +34,12 @@ namespace xrpl { -using FunctionType = std::function( +using FunctionType = std::function( json::Value const&, json::StaticString const, unsigned const apiVersion)>; -static Expected +static std::expected parseFixed( Keylet const& keylet, json::Value const& params, @@ -55,12 +55,12 @@ fixed(Keylet const& keylet) return [keylet]( json::Value const& params, json::StaticString const fieldName, - unsigned const apiVersion) -> Expected { + unsigned const apiVersion) -> std::expected { return parseFixed(keylet, params, fieldName, apiVersion); }; } -static Expected +static std::expected parseObjectID( json::Value const& params, json::StaticString const fieldName, @@ -73,7 +73,7 @@ parseObjectID( return LedgerEntryHelpers::invalidFieldError("malformedRequest", fieldName, expectedType); } -static Expected +static std::expected parseIndex(json::Value const& params, json::StaticString const fieldName, unsigned const apiVersion) { if (apiVersion > 2u && params.isString()) @@ -95,7 +95,7 @@ parseIndex(json::Value const& params, json::StaticString const fieldName, unsign return parseObjectID(params, fieldName, "hex string"); } -static Expected +static std::expected parseAccountRoot( json::Value const& params, json::StaticString const fieldName, @@ -111,7 +111,7 @@ parseAccountRoot( auto const parseAmendments = fixed(keylet::amendments()); -static Expected +static std::expected parseAMM( json::Value const& params, json::StaticString const fieldName, @@ -125,21 +125,21 @@ parseAMM( if (auto const value = LedgerEntryHelpers::hasRequired(params, {jss::asset, jss::asset2}); !value) { - return Unexpected(value.error()); + return std::unexpected(value.error()); } auto const asset = LedgerEntryHelpers::requiredAsset(params, jss::asset, "malformedRequest"); if (!asset) - return Unexpected(asset.error()); + return std::unexpected(asset.error()); auto const asset2 = LedgerEntryHelpers::requiredAsset(params, jss::asset2, "malformedRequest"); if (!asset2) - return Unexpected(asset2.error()); + return std::unexpected(asset2.error()); return keylet::amm(*asset, *asset2).key; } -static Expected +static std::expected parseBridge( json::Value const& params, json::StaticString const fieldName, @@ -147,7 +147,7 @@ parseBridge( { if (!params.isMember(jss::bridge)) { - return Unexpected(LedgerEntryHelpers::missingFieldError(jss::bridge)); + return std::unexpected(LedgerEntryHelpers::missingFieldError(jss::bridge)); } if (params[jss::bridge].isString()) @@ -157,12 +157,12 @@ parseBridge( auto const bridge = LedgerEntryHelpers::parseBridgeFields(params[jss::bridge]); if (!bridge) - return Unexpected(bridge.error()); + return std::unexpected(bridge.error()); auto const account = LedgerEntryHelpers::requiredAccountID( params, jss::bridge_account, "malformedBridgeAccount"); if (!account) - return Unexpected(account.error()); + return std::unexpected(account.error()); STXChainBridge::ChainType const chainType = STXChainBridge::srcChain(account.value() == bridge->lockingChainDoor()); @@ -172,7 +172,7 @@ parseBridge( return keylet::bridge(*bridge, chainType).key; } -static Expected +static std::expected parseCheck( json::Value const& params, json::StaticString const fieldName, @@ -181,7 +181,7 @@ parseCheck( return parseObjectID(params, fieldName, "hex string"); } -static Expected +static std::expected parseCredential( json::Value const& cred, json::StaticString const fieldName, @@ -195,22 +195,22 @@ parseCredential( auto const subject = LedgerEntryHelpers::requiredAccountID(cred, jss::subject, "malformedRequest"); if (!subject) - return Unexpected(subject.error()); + return std::unexpected(subject.error()); auto const issuer = LedgerEntryHelpers::requiredAccountID(cred, jss::issuer, "malformedRequest"); if (!issuer) - return Unexpected(issuer.error()); + return std::unexpected(issuer.error()); auto const credType = LedgerEntryHelpers::requiredHexBlob( cred, jss::credential_type, kMaxCredentialTypeLength, "malformedRequest"); if (!credType) - return Unexpected(credType.error()); + return std::unexpected(credType.error()); return keylet::credential(*subject, *issuer, Slice(credType->data(), credType->size())).key; } -static Expected +static std::expected parseDelegate( json::Value const& params, json::StaticString const fieldName, @@ -224,17 +224,17 @@ parseDelegate( auto const account = LedgerEntryHelpers::requiredAccountID(params, jss::account, "malformedAddress"); if (!account) - return Unexpected(account.error()); + return std::unexpected(account.error()); auto const authorize = LedgerEntryHelpers::requiredAccountID(params, jss::authorize, "malformedAddress"); if (!authorize) - return Unexpected(authorize.error()); + return std::unexpected(authorize.error()); return keylet::delegate(*account, *authorize).key; } -static Expected +static std::expected parseAuthorizeCredentials(json::Value const& jv) { if (!jv.isArray()) @@ -246,7 +246,7 @@ parseAuthorizeCredentials(json::Value const& jv) std::uint32_t const n = jv.size(); if (n > kMaxCredentialsArraySize) { - return Unexpected( + return std::unexpected( LedgerEntryHelpers::malformedError( "malformedAuthorizedCredentials", "Invalid field '" + std::string(jss::authorized_credentials) + @@ -255,7 +255,7 @@ parseAuthorizeCredentials(json::Value const& jv) if (n == 0) { - return Unexpected( + return std::unexpected( LedgerEntryHelpers::malformedError( "malformedAuthorizedCredentials", "Invalid field '" + std::string(jss::authorized_credentials) + "', array empty.")); @@ -274,18 +274,18 @@ parseAuthorizeCredentials(json::Value const& jv) jo, {jss::issuer, jss::credential_type}, "malformedAuthorizedCredentials"); !value) { - return Unexpected(value.error()); + return std::unexpected(value.error()); } auto const issuer = LedgerEntryHelpers::requiredAccountID( jo, jss::issuer, "malformedAuthorizedCredentials"); if (!issuer) - return Unexpected(issuer.error()); + return std::unexpected(issuer.error()); auto const credentialType = LedgerEntryHelpers::requiredHexBlob( jo, jss::credential_type, kMaxCredentialTypeLength, "malformedAuthorizedCredentials"); if (!credentialType) - return Unexpected(credentialType.error()); + return std::unexpected(credentialType.error()); auto credential = STObject::makeInnerObject(sfCredential); credential.setAccountID(sfIssuer, *issuer); @@ -296,7 +296,7 @@ parseAuthorizeCredentials(json::Value const& jv) return arr; } -static Expected +static std::expected parseDepositPreauth( json::Value const& dp, json::StaticString const fieldName, @@ -318,7 +318,7 @@ parseDepositPreauth( auto const owner = LedgerEntryHelpers::requiredAccountID(dp, jss::owner, "malformedOwner"); if (!owner) { - return Unexpected(owner.error()); + return std::unexpected(owner.error()); } if (dp.isMember(jss::authorized)) @@ -334,7 +334,7 @@ parseDepositPreauth( auto const& ac(dp[jss::authorized_credentials]); auto const arr = parseAuthorizeCredentials(ac); if (!arr.has_value()) - return Unexpected(arr.error()); + return std::unexpected(arr.error()); auto const& sorted = credentials::makeSorted(arr.value()); if (sorted.empty()) @@ -347,7 +347,7 @@ parseDepositPreauth( return keylet::depositPreauth(*owner, sorted).key; } -static Expected +static std::expected parseDID( json::Value const& params, json::StaticString const fieldName, @@ -362,7 +362,7 @@ parseDID( return keylet::did(*account).key; } -static Expected +static std::expected parseDirectoryNode( json::Value const& params, json::StaticString const fieldName, @@ -413,7 +413,7 @@ parseDirectoryNode( return LedgerEntryHelpers::malformedError("malformedRequest", ""); } -static Expected +static std::expected parseEscrow( json::Value const& params, json::StaticString const fieldName, @@ -426,17 +426,17 @@ parseEscrow( auto const id = LedgerEntryHelpers::requiredAccountID(params, jss::owner, "malformedOwner"); if (!id) - return Unexpected(id.error()); + return std::unexpected(id.error()); auto const seq = LedgerEntryHelpers::requiredUInt32(params, jss::seq, "malformedSeq"); if (!seq) - return Unexpected(seq.error()); + return std::unexpected(seq.error()); return keylet::escrow(*id, *seq).key; } auto const parseFeeSettings = fixed(keylet::fees()); -static Expected +static std::expected parseFixed( Keylet const& keylet, json::Value const& params, @@ -455,7 +455,7 @@ parseFixed( return keylet.key; } -static Expected +static std::expected parseLedgerHashes( json::Value const& params, json::StaticString const fieldName, @@ -475,7 +475,7 @@ parseLedgerHashes( return parseFixed(keylet::skip(), params, fieldName, apiVersion); } -static Expected +static std::expected parseLoanBroker( json::Value const& params, json::StaticString const fieldName, @@ -488,15 +488,15 @@ parseLoanBroker( auto const id = LedgerEntryHelpers::requiredAccountID(params, jss::owner, "malformedOwner"); if (!id) - return Unexpected(id.error()); + return std::unexpected(id.error()); auto const seq = LedgerEntryHelpers::requiredUInt32(params, jss::seq, "malformedSeq"); if (!seq) - return Unexpected(seq.error()); + return std::unexpected(seq.error()); return keylet::loanbroker(*id, *seq).key; } -static Expected +static std::expected parseLoan( json::Value const& params, json::StaticString const fieldName, @@ -510,15 +510,15 @@ parseLoan( auto const id = LedgerEntryHelpers::requiredUInt256(params, jss::loan_broker_id, "malformedBroker"); if (!id) - return Unexpected(id.error()); + return std::unexpected(id.error()); auto const seq = LedgerEntryHelpers::requiredUInt32(params, jss::loan_seq, "malformedSeq"); if (!seq) - return Unexpected(seq.error()); + return std::unexpected(seq.error()); return keylet::loan(*id, *seq).key; } -static Expected +static std::expected parseMPToken( json::Value const& params, json::StaticString const fieldName, @@ -532,17 +532,17 @@ parseMPToken( auto const mptIssuanceID = LedgerEntryHelpers::requiredUInt192(params, jss::mpt_issuance_id, "malformedMPTIssuanceID"); if (!mptIssuanceID) - return Unexpected(mptIssuanceID.error()); + return std::unexpected(mptIssuanceID.error()); auto const account = LedgerEntryHelpers::requiredAccountID(params, jss::account, "malformedAccount"); if (!account) - return Unexpected(account.error()); + return std::unexpected(account.error()); return keylet::mptoken(*mptIssuanceID, *account).key; } -static Expected +static std::expected parseMPTokenIssuance( json::Value const& params, json::StaticString const fieldName, @@ -558,7 +558,7 @@ parseMPTokenIssuance( return keylet::mptIssuance(*mptIssuanceID).key; } -static Expected +static std::expected parseNFTokenOffer( json::Value const& params, json::StaticString const fieldName, @@ -567,7 +567,7 @@ parseNFTokenOffer( return parseObjectID(params, fieldName, "hex string"); } -static Expected +static std::expected parseNFTokenPage( json::Value const& params, json::StaticString const fieldName, @@ -578,7 +578,7 @@ parseNFTokenPage( auto const parseNegativeUNL = fixed(keylet::negativeUNL()); -static Expected +static std::expected parseOffer( json::Value const& params, json::StaticString const fieldName, @@ -591,16 +591,16 @@ parseOffer( auto const id = LedgerEntryHelpers::requiredAccountID(params, jss::account, "malformedAddress"); if (!id) - return Unexpected(id.error()); + return std::unexpected(id.error()); auto const seq = LedgerEntryHelpers::requiredUInt32(params, jss::seq, "malformedRequest"); if (!seq) - return Unexpected(seq.error()); + return std::unexpected(seq.error()); return keylet::offer(*id, *seq).key; } -static Expected +static std::expected parseOracle( json::Value const& params, json::StaticString const fieldName, @@ -613,17 +613,17 @@ parseOracle( auto const id = LedgerEntryHelpers::requiredAccountID(params, jss::account, "malformedAccount"); if (!id) - return Unexpected(id.error()); + return std::unexpected(id.error()); auto const seq = LedgerEntryHelpers::requiredUInt32(params, jss::oracle_document_id, "malformedDocumentID"); if (!seq) - return Unexpected(seq.error()); + return std::unexpected(seq.error()); return keylet::oracle(*id, *seq).key; } -static Expected +static std::expected parsePayChannel( json::Value const& params, json::StaticString const fieldName, @@ -632,7 +632,7 @@ parsePayChannel( return parseObjectID(params, fieldName, "hex string"); } -static Expected +static std::expected parsePermissionedDomain( json::Value const& pd, json::StaticString const fieldName, @@ -652,16 +652,16 @@ parsePermissionedDomain( auto const account = LedgerEntryHelpers::requiredAccountID(pd, jss::account, "malformedAddress"); if (!account) - return Unexpected(account.error()); + return std::unexpected(account.error()); auto const seq = LedgerEntryHelpers::requiredUInt32(pd, jss::seq, "malformedRequest"); if (!seq) - return Unexpected(seq.error()); + return std::unexpected(seq.error()); return keylet::permissionedDomain(*account, pd[jss::seq].asUInt()).key; } -static Expected +static std::expected parseRippleState( json::Value const& jvRippleState, json::StaticString const fieldName, @@ -678,7 +678,7 @@ parseRippleState( LedgerEntryHelpers::hasRequired(jvRippleState, {jss::currency, jss::accounts}); !value) { - return Unexpected(value.error()); + return std::unexpected(value.error()); } if (!jvRippleState[jss::accounts].isArray() || jvRippleState[jss::accounts].size() != 2) @@ -710,7 +710,7 @@ parseRippleState( return keylet::line(*id1, *id2, uCurrency).key; } -static Expected +static std::expected parseSignerList( json::Value const& params, json::StaticString const fieldName, @@ -719,7 +719,7 @@ parseSignerList( return parseObjectID(params, fieldName, "hex string"); } -static Expected +static std::expected parseTicket( json::Value const& params, json::StaticString const fieldName, @@ -732,17 +732,17 @@ parseTicket( auto const id = LedgerEntryHelpers::requiredAccountID(params, jss::account, "malformedAddress"); if (!id) - return Unexpected(id.error()); + return std::unexpected(id.error()); auto const seq = LedgerEntryHelpers::requiredUInt32(params, jss::ticket_seq, "malformedRequest"); if (!seq) - return Unexpected(seq.error()); + return std::unexpected(seq.error()); return getTicketIndex(*id, *seq); } -static Expected +static std::expected parseVault( json::Value const& params, json::StaticString const fieldName, @@ -755,16 +755,16 @@ parseVault( auto const id = LedgerEntryHelpers::requiredAccountID(params, jss::owner, "malformedOwner"); if (!id) - return Unexpected(id.error()); + return std::unexpected(id.error()); auto const seq = LedgerEntryHelpers::requiredUInt32(params, jss::seq, "malformedRequest"); if (!seq) - return Unexpected(seq.error()); + return std::unexpected(seq.error()); return keylet::vault(*id, *seq).key; } -static Expected +static std::expected parseXChainOwnedClaimID( json::Value const& claimId, json::StaticString const fieldName, @@ -777,20 +777,20 @@ parseXChainOwnedClaimID( auto const bridgeSpec = LedgerEntryHelpers::parseBridgeFields(claimId); if (!bridgeSpec) - return Unexpected(bridgeSpec.error()); + return std::unexpected(bridgeSpec.error()); auto const seq = LedgerEntryHelpers::requiredUInt32( claimId, jss::xchain_owned_claim_id, "malformedXChainOwnedClaimID"); if (!seq) { - return Unexpected(seq.error()); + return std::unexpected(seq.error()); } - Keylet keylet = keylet::xChainClaimID(*bridgeSpec, *seq); + Keylet const keylet = keylet::xChainClaimID(*bridgeSpec, *seq); return keylet.key; } -static Expected +static std::expected parseXChainOwnedCreateAccountClaimID( json::Value const& claimId, json::StaticString const fieldName, @@ -803,7 +803,7 @@ parseXChainOwnedCreateAccountClaimID( auto const bridgeSpec = LedgerEntryHelpers::parseBridgeFields(claimId); if (!bridgeSpec) - return Unexpected(bridgeSpec.error()); + return std::unexpected(bridgeSpec.error()); auto const seq = LedgerEntryHelpers::requiredUInt32( claimId, @@ -811,10 +811,10 @@ parseXChainOwnedCreateAccountClaimID( "malformedXChainOwnedCreateAccountClaimID"); if (!seq) { - return Unexpected(seq.error()); + return std::unexpected(seq.error()); } - Keylet keylet = keylet::xChainCreateAccountClaimID(*bridgeSpec, *seq); + Keylet const keylet = keylet::xChainCreateAccountClaimID(*bridgeSpec, *seq); return keylet.key; } diff --git a/src/xrpld/rpc/handlers/ledger/LedgerEntryHelpers.h b/src/xrpld/rpc/handlers/ledger/LedgerEntryHelpers.h index e8e295ca2c..463547a90d 100644 --- a/src/xrpld/rpc/handlers/ledger/LedgerEntryHelpers.h +++ b/src/xrpld/rpc/handlers/ledger/LedgerEntryHelpers.h @@ -10,41 +10,42 @@ #include #include +#include #include namespace xrpl::LedgerEntryHelpers { -inline Unexpected +inline std::unexpected missingFieldError(json::StaticString const field, std::optional err = std::nullopt) { json::Value json = json::ValueType::Object; json[jss::error] = err.value_or("malformedRequest"); json[jss::error_code] = RpcInvalidParams; json[jss::error_message] = RPC::missingFieldMessage(std::string(field.cStr())); - return Unexpected(json); + return std::unexpected(json); } -inline Unexpected +inline std::unexpected invalidFieldError(std::string const& err, json::StaticString const field, std::string const& type) { json::Value json = json::ValueType::Object; json[jss::error] = err; json[jss::error_code] = RpcInvalidParams; json[jss::error_message] = RPC::expectedFieldMessage(field, type); - return Unexpected(json); + return std::unexpected(json); } -inline Unexpected +inline std::unexpected malformedError(std::string const& err, std::string const& message) { json::Value json = json::ValueType::Object; json[jss::error] = err; json[jss::error_code] = RpcInvalidParams; json[jss::error_message] = message; - return Unexpected(json); + return std::unexpected(json); } -inline Expected +inline std::expected hasRequired( json::Value const& params, std::initializer_list fields, @@ -65,7 +66,7 @@ std::optional parse(json::Value const& param); template -Expected +std::expected required( json::Value const& params, json::StaticString const fieldName, @@ -99,7 +100,7 @@ parse(json::Value const& param) return account; } -inline Expected +inline std::expected requiredAccountID( json::Value const& params, json::StaticString const fieldName, @@ -121,7 +122,7 @@ parseHexBlob(json::Value const& param, std::size_t maxLength) return blob; } -inline Expected +inline std::expected requiredHexBlob( json::Value const& params, json::StaticString const fieldName, @@ -156,7 +157,7 @@ parse(json::Value const& param) return std::nullopt; } -inline Expected +inline std::expected requiredUInt32( json::Value const& params, json::StaticString const fieldName, @@ -178,7 +179,7 @@ parse(json::Value const& param) return uNodeIndex; } -inline Expected +inline std::expected requiredUInt256( json::Value const& params, json::StaticString const fieldName, @@ -200,7 +201,7 @@ parse(json::Value const& param) return field; } -inline Expected +inline std::expected requiredUInt192( json::Value const& params, json::StaticString const fieldName, @@ -223,13 +224,13 @@ parse(json::Value const& param) } } -inline Expected +inline std::expected requiredAsset(json::Value const& params, json::StaticString const fieldName, std::string const& err) { return required(params, fieldName, err, "Asset"); } -inline Expected +inline std::expected parseBridgeFields(json::Value const& params) { if (auto const value = hasRequired( @@ -240,21 +241,21 @@ parseBridgeFields(json::Value const& params) jss::IssuingChainIssue}); !value) { - return Unexpected(value.error()); + return std::unexpected(value.error()); } auto const lockingChainDoor = requiredAccountID(params, jss::LockingChainDoor, "malformedLockingChainDoor"); if (!lockingChainDoor) { - return Unexpected(lockingChainDoor.error()); + return std::unexpected(lockingChainDoor.error()); } auto const issuingChainDoor = requiredAccountID(params, jss::IssuingChainDoor, "malformedIssuingChainDoor"); if (!issuingChainDoor) { - return Unexpected(issuingChainDoor.error()); + return std::unexpected(issuingChainDoor.error()); } Issue lockingChainIssue; diff --git a/src/xrpld/rpc/handlers/orderbook/AMMInfo.cpp b/src/xrpld/rpc/handlers/orderbook/AMMInfo.cpp index b9f4a42880..2c2f96b0e8 100644 --- a/src/xrpld/rpc/handlers/orderbook/AMMInfo.cpp +++ b/src/xrpld/rpc/handlers/orderbook/AMMInfo.cpp @@ -2,7 +2,6 @@ #include #include -#include #include #include #include @@ -18,7 +17,7 @@ #include #include #include -#include +#include // IWYU pragma: keep #include #include #include @@ -27,6 +26,7 @@ #include #include +#include #include #include #include @@ -35,7 +35,7 @@ namespace xrpl { -Expected +std::expected getAsset(json::Value const& v, beast::Journal j) { try @@ -46,7 +46,7 @@ getAsset(json::Value const& v, beast::Journal j) { JLOG(j.debug()) << "getAsset " << ex.what(); } - return Unexpected(RpcIssueMalformed); + return std::unexpected(RpcIssueMalformed); } std::string @@ -79,7 +79,7 @@ doAMMInfo(RPC::JsonContext& context) SLE::const_pointer amm; }; - auto getValuesFromContextParams = [&]() -> Expected { + auto getValuesFromContextParams = [&]() -> std::expected { std::optional accountID; std::optional asset1; std::optional asset2; @@ -92,7 +92,7 @@ doAMMInfo(RPC::JsonContext& context) // NOTE, identical check for apVersion >= 3 below if (context.apiVersion < 3 && kInvalid(params)) - return Unexpected(RpcInvalidParams); + return std::unexpected(RpcInvalidParams); if (params.isMember(jss::asset)) { @@ -102,7 +102,7 @@ doAMMInfo(RPC::JsonContext& context) } else { - return Unexpected(i.error()); + return std::unexpected(i.error()); } } @@ -114,7 +114,7 @@ doAMMInfo(RPC::JsonContext& context) } else { - return Unexpected(i.error()); + return std::unexpected(i.error()); } } @@ -122,25 +122,25 @@ doAMMInfo(RPC::JsonContext& context) { auto const id = parseBase58((params[jss::amm_account].asString())); if (!id) - return Unexpected(RpcActMalformed); + return std::unexpected(RpcActMalformed); auto const sle = ledger->read(keylet::account(*id)); if (!sle) - return Unexpected(RpcActMalformed); + return std::unexpected(RpcActMalformed); ammID = sle->getFieldH256(sfAMMID); if (ammID->isZero()) - return Unexpected(RpcActNotFound); + return std::unexpected(RpcActNotFound); } if (params.isMember(jss::account)) { accountID = parseBase58(params[jss::account].asString()); if (!accountID || !ledger->read(keylet::account(*accountID))) - return Unexpected(RpcActMalformed); + return std::unexpected(RpcActMalformed); } // NOTE, identical check for apVersion < 3 above if (context.apiVersion >= 3 && kInvalid(params)) - return Unexpected(RpcInvalidParams); + return std::unexpected(RpcInvalidParams); XRPL_ASSERT( (asset1.has_value() == asset2.has_value()) && (asset1.has_value() != ammID.has_value()), @@ -154,7 +154,7 @@ doAMMInfo(RPC::JsonContext& context) }(); auto const amm = ledger->read(ammKeylet); if (!amm) - return Unexpected(RpcActNotFound); + return std::unexpected(RpcActNotFound); if (!asset1 && !asset2) { asset1 = (*amm)[sfAsset]; diff --git a/src/xrpld/rpc/handlers/server_info/ServerDefinitions.cpp b/src/xrpld/rpc/handlers/server_info/ServerDefinitions.cpp index aa23a7af26..1e9e0ddc14 100644 --- a/src/xrpld/rpc/handlers/server_info/ServerDefinitions.cpp +++ b/src/xrpld/rpc/handlers/server_info/ServerDefinitions.cpp @@ -65,7 +65,7 @@ ServerDefinitions::translate(std::string const& inp) }; // TODO: use string::contains with C++23 - auto contains = [&](std::string_view s) -> bool { return inp.find(s) != std::string::npos; }; + auto contains = [&](std::string_view s) -> bool { return inp.contains(s); }; if (contains("UINT")) { diff --git a/src/xrpld/rpc/handlers/transaction/Simulate.cpp b/src/xrpld/rpc/handlers/transaction/Simulate.cpp index 676f0318a2..7ee28c4886 100644 --- a/src/xrpld/rpc/handlers/transaction/Simulate.cpp +++ b/src/xrpld/rpc/handlers/transaction/Simulate.cpp @@ -7,7 +7,6 @@ #include #include -#include #include #include #include @@ -33,6 +32,7 @@ #include #include +#include #include #include #include @@ -42,7 +42,7 @@ namespace xrpl { -static Expected +static std::expected getAutofillSequence(json::Value const& txJson, RPC::JsonContext& context) { // autofill Sequence @@ -52,13 +52,13 @@ getAutofillSequence(json::Value const& txJson, RPC::JsonContext& context) { // sanity check, should fail earlier // LCOV_EXCL_START - return Unexpected(RPC::invalidFieldError("tx.Account")); + return std::unexpected(RPC::invalidFieldError("tx.Account")); // LCOV_EXCL_STOP } auto const srcAddressID = parseBase58(accountStr.asString()); if (!srcAddressID.has_value()) { - return Unexpected( + return std::unexpected( RPC::makeError(RpcSrcActMalformed, RPC::invalidFieldMessage("tx.Account"))); } SLE::const_pointer const sle = @@ -69,7 +69,7 @@ getAutofillSequence(json::Value const& txJson, RPC::JsonContext& context) << "Failed to find source account " << "in current ledger: " << toBase58(*srcAddressID); - return Unexpected(rpcError(RpcSrcActNotFound)); + return std::unexpected(rpcError(RpcSrcActNotFound)); } return hasTicketSeq ? 0 : context.app.getTxQ().nextQueuableSeq(sle).value(); diff --git a/src/xrpld/rpc/handlers/transaction/Submit.cpp b/src/xrpld/rpc/handlers/transaction/Submit.cpp index f0c4cb2391..79f3680684 100644 --- a/src/xrpld/rpc/handlers/transaction/Submit.cpp +++ b/src/xrpld/rpc/handlers/transaction/Submit.cpp @@ -4,7 +4,6 @@ #include #include -#include #include #include #include @@ -21,17 +20,18 @@ #include #include +#include #include #include namespace xrpl { -static Expected +static std::expected getFailHard(RPC::JsonContext const& context) { if (context.params.isMember(jss::fail_hard) && !context.params[jss::fail_hard].isBool()) { - return Unexpected(RPC::expectedFieldError(jss::fail_hard, "boolean")); + return std::unexpected(RPC::expectedFieldError(jss::fail_hard, "boolean")); } return NetworkOPs::doFailHard( context.params.isMember(jss::fail_hard) && context.params[jss::fail_hard].asBool()); From 2cbc3c139e0469c98e49d4fe9453de2d15f6f4e4 Mon Sep 17 00:00:00 2001 From: Ed Hennis Date: Tue, 9 Jun 2026 13:46:56 -0400 Subject: [PATCH 7/9] fix: Fix Number comparison operator (#7406) --- include/xrpl/basics/Number.h | 35 ++++++----- src/test/basics/Number_test.cpp | 104 ++++++++++++++++++++++++++++++-- 2 files changed, 121 insertions(+), 18 deletions(-) diff --git a/include/xrpl/basics/Number.h b/include/xrpl/basics/Number.h index 93bef82a8c..cee0c45355 100644 --- a/include/xrpl/basics/Number.h +++ b/include/xrpl/basics/Number.h @@ -408,33 +408,40 @@ public: } friend constexpr bool - operator<(Number const& x, Number const& y) noexcept + operator<(Number const& l, Number const& r) noexcept { + bool const lneg = l.negative_; + bool const rneg = r.negative_; + // If the two amounts have different signs (zero is treated as positive) // then the comparison is true iff the left is negative. - bool const lneg = x.negative_; - bool const rneg = y.negative_; - if (lneg != rneg) return lneg; - // Both have same sign and the left is zero: the right must be - // greater than 0. - if (x.mantissa_ == 0) - return y.mantissa_ > 0; + // Both have same sign and the left is zero: both must be non-negative. + // If the right is greater than 0, then it is larger, so the comparison is true. + if (l.mantissa_ == 0) + return r.mantissa_ > 0; - // Both have same sign, the right is zero and the left is non-zero. - if (y.mantissa_ == 0) + // Both have same sign, the right is zero and the left is non-zero, so the left must be + // positive, and thus is larger, so the comparison is false. + if (r.mantissa_ == 0) return false; // Both have the same sign, compare by exponents: - if (x.exponent_ > y.exponent_) + if (l.exponent_ > r.exponent_) return lneg; - if (x.exponent_ < y.exponent_) + if (l.exponent_ < r.exponent_) return !lneg; - // If equal exponents, compare mantissas - return x.mantissa_ < y.mantissa_; + // If equal signs and exponents, compare mantissas. + if (lneg) + { + // If negative, the operator is reversed. + return l.mantissa_ > r.mantissa_; + } + + return l.mantissa_ < r.mantissa_; } /** Return the sign of the amount */ diff --git a/src/test/basics/Number_test.cpp b/src/test/basics/Number_test.cpp index 81019970ad..f4bd1c9d66 100644 --- a/src/test/basics/Number_test.cpp +++ b/src/test/basics/Number_test.cpp @@ -10,6 +10,7 @@ #include #include +#include #include #include #include @@ -20,6 +21,8 @@ #include #include #include +#include +#include namespace xrpl { @@ -1386,10 +1389,103 @@ public: testRelationals() { testcase << "test_relationals " << to_string(Number::getMantissaScale()); - BEAST_EXPECT(!(Number{100} < Number{10})); - BEAST_EXPECT(Number{100} > Number{10}); - BEAST_EXPECT(Number{100} >= Number{10}); - BEAST_EXPECT(!(Number{100} <= Number{10})); + + { + auto test = [this](auto const& nums) { + BEAST_EXPECT(std::ranges::is_sorted(nums)); + + for (auto iter1 = nums.begin(); iter1 != nums.end(); ++iter1) + { + auto iter2 = iter1; + for (++iter2; iter2 != nums.end(); ++iter2) + { + Number const& smaller = *iter1; + Number const& larger = *iter2; + std::stringstream ss; + ss << smaller << " < " << larger; + auto const str = ss.str(); + + // The ==/!= operators use a completely different code path than <, etc. + // This helps detect a breakage in one but not the other. It also helps + // verify that the values are being ordered correctly. + BEAST_EXPECTS(smaller != larger, str + " (!=)"); + BEAST_EXPECTS(!(smaller == larger), str + " (==)"); + + // true results using operator< and derived operators + BEAST_EXPECTS(smaller < larger, str + " (<)"); + BEAST_EXPECTS(larger > smaller, str + " (>)"); + BEAST_EXPECTS(larger >= smaller, str + " (>=)"); + BEAST_EXPECTS(smaller <= larger, str + " (<=)"); + + // false results using operator< and derived operators + BEAST_EXPECTS(!(larger < smaller), str + " (! <)"); + BEAST_EXPECTS(!(smaller > larger), str + " (! >)"); + BEAST_EXPECTS(!(smaller >= larger), str + " (! >=)"); + BEAST_EXPECTS(!(larger <= smaller), str + " (! <=)"); + } + } + }; + + auto const intNums = [this]() { + // Inequality test cases are built from a list of sorted integers + auto const values = + std::to_array({-100, -50, -20, -10, -1, 0, 1, 10, 20, 50, 100}); + // Check this list is sorted before converting it to Numbers. + // That way if any of the other tests fail, we know it's because of code and not the + // source data. + BEAST_EXPECT(std::ranges::is_sorted(values)); + + std::vector result; + result.reserve(values.size()); + for (auto const v : values) + result.emplace_back(v); + return result; + }(); + + auto const otherNums = std::to_array({ + Number{-5, 100}, + Number{-1, 100}, + Number{-7, -10}, + Number{-2, -10}, + Number{0}, + Number{2, -10}, + Number{7, -10}, + Number{1, 100}, + Number{5, 100}, + }); + + test(intNums); + test(otherNums); + } + + { + // Equality test cases are . Number will be compared against itself + using Case = std::pair; + auto const c = std::to_array({ + {700, __LINE__}, + {50, __LINE__}, + {1, __LINE__}, + {0, __LINE__}, + {-1, __LINE__}, + {-30, __LINE__}, + {-600, __LINE__}, + }); + for (auto const& [n, line] : c) + { + auto const str = to_string(n); + + // NOLINTBEGIN(misc-redundant-expression) Explicitly testing operators with + // equivalent values + expect(n == n, str + " ==", __FILE__, line); + expect(!(n != n), str + " !=", __FILE__, line); + + expect(!(n < n), str + " < ", __FILE__, line); + expect(!(n > n), str + " >", __FILE__, line); + expect(n >= n, str + " >=", __FILE__, line); + expect(n <= n, str + " <=", __FILE__, line); + // NOLINTEND(misc-redundant-expression) + } + } } void From f3fc85fd2b3e696750b9c5a6d37c5af85916cb0d Mon Sep 17 00:00:00 2001 From: Pratik Mankawde <3397372+pratikmankawde@users.noreply.github.com> Date: Tue, 9 Jun 2026 19:24:38 +0100 Subject: [PATCH 8/9] test(telemetry): drop sampling_ratio tests, fix tracePeer default expectation sampling_ratio is no longer parsed (head sampling fixed at 1.0), so remove the parse/clamp assertions and the sampling_ratio_clamped test. Update the default-tracePeer expectations to TRUE to match the enabled-by-default change. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../libxrpl/telemetry/TelemetryConfig.cpp | 19 ++----------------- 1 file changed, 2 insertions(+), 17 deletions(-) diff --git a/src/tests/libxrpl/telemetry/TelemetryConfig.cpp b/src/tests/libxrpl/telemetry/TelemetryConfig.cpp index dc84bd937f..137b30a62f 100644 --- a/src/tests/libxrpl/telemetry/TelemetryConfig.cpp +++ b/src/tests/libxrpl/telemetry/TelemetryConfig.cpp @@ -25,7 +25,7 @@ TEST(TelemetryConfig, setup_defaults) EXPECT_TRUE(s.traceTransactions); EXPECT_TRUE(s.traceConsensus); EXPECT_TRUE(s.traceRpc); - EXPECT_FALSE(s.tracePeer); + EXPECT_TRUE(s.tracePeer); EXPECT_TRUE(s.traceLedger); } @@ -42,7 +42,7 @@ TEST(TelemetryConfig, parse_empty_section) EXPECT_TRUE(setup.traceRpc); EXPECT_TRUE(setup.traceTransactions); EXPECT_TRUE(setup.traceConsensus); - EXPECT_FALSE(setup.tracePeer); + EXPECT_TRUE(setup.tracePeer); EXPECT_TRUE(setup.traceLedger); } @@ -56,7 +56,6 @@ TEST(TelemetryConfig, parse_full_section) section.set("endpoint", "http://collector:4318/v1/traces"); section.set("use_tls", "1"); section.set("tls_ca_cert", "/etc/ssl/ca.pem"); - section.set("sampling_ratio", "0.5"); section.set("batch_size", "256"); section.set("batch_delay_ms", "3000"); section.set("max_queue_size", "4096"); @@ -74,7 +73,6 @@ TEST(TelemetryConfig, parse_full_section) EXPECT_EQ(setup.exporterEndpoint, "http://collector:4318/v1/traces"); EXPECT_TRUE(setup.useTls); EXPECT_EQ(setup.tlsCertPath, "/etc/ssl/ca.pem"); - EXPECT_DOUBLE_EQ(setup.samplingRatio, 0.5); EXPECT_EQ(setup.batchSize, 256u); EXPECT_EQ(setup.batchDelay, std::chrono::milliseconds{3000}); EXPECT_EQ(setup.maxQueueSize, 4096u); @@ -105,16 +103,3 @@ TEST(TelemetryConfig, null_telemetry_factory) tel->start(); tel->stop(); } - -TEST(TelemetryConfig, sampling_ratio_clamped) -{ - Section section; - section.set("sampling_ratio", "2.5"); - auto setup = telemetry::setupTelemetry(section, "nHUtest123", "2.0.0", 0); - EXPECT_DOUBLE_EQ(setup.samplingRatio, 1.0); - - Section section2; - section2.set("sampling_ratio", "-0.5"); - auto setup2 = telemetry::setupTelemetry(section2, "nHUtest123", "2.0.0", 0); - EXPECT_DOUBLE_EQ(setup2.samplingRatio, 0.0); -} From 8617eaeb26f07e7c671b8f86fb639179a5998f71 Mon Sep 17 00:00:00 2001 From: Ayaz Salikhov Date: Wed, 10 Jun 2026 01:00:19 +0100 Subject: [PATCH 9/9] ci: Launch upload-conan-deps on profile change (#7442) --- .github/workflows/upload-conan-deps.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/upload-conan-deps.yml b/.github/workflows/upload-conan-deps.yml index 1a52ceee63..7ca9d13007 100644 --- a/.github/workflows/upload-conan-deps.yml +++ b/.github/workflows/upload-conan-deps.yml @@ -30,6 +30,7 @@ on: - ".github/scripts/strategy-matrix/**" - conanfile.py - conan.lock + - conan/profiles/** env: CONAN_REMOTE_NAME: xrplf